diff --git a/TODO.md b/TODO.md index 0635863b..1983ccf2 100644 --- a/TODO.md +++ b/TODO.md @@ -29,8 +29,12 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern SIA-416-Zuordnung (`roomArea.ts::balance`) und `checkRoomProgram` bleiben vorerst TS. Offen: `bulge.ts` (Bogenformeln doppelt), Triangulierung, Straight Skeleton [B2]. · M - ◐ **[K2] Geometrie-Ableitungen.** (27.10.) Dachgeometrie in Rust (`roof.rs`, `roof_skeleton.rs`; - `roofSkeleton.ts` gelöscht, ~2× schneller, Ergebnis bitgleich). Offen: Wand-Joins/-Bänder (`toWalls3d`), - Treppen, Räume. · L + `roofSkeleton.ts` gelöscht, ~2× schneller, Ergebnis bitgleich). Offen: Treppen, Räume. · L + - ✅ (27.10.) Wand-Joins und -Bänder in Rust (`joins.rs`, `wall_bands.rs`): Gehrung/T-Stoss/Kreuzung, + Pro-Schicht-Cuts, Nah-Putz-Aussparungen, Decken-Dominanz, Öffnungs-Löcher, `topDrop` unter Dächern. + `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. - ○ **[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 new file mode 100644 index 00000000..3e092e0a --- /dev/null +++ b/src-tauri/core/src/joins.rs @@ -0,0 +1,834 @@ +//! Wand-Verschneidung (Gehrung, T-Stoss, Kreuzung): berechnet je Wand die optionalen +//! Schnittlinien an Start- und Endpunkt, materialbewusste Pro-Schicht-Cuts am T-Stoss und die +//! Nah-Putz-Aussparungen der Durchgangswand. Portiert aus `src/model/joins.ts` (dort bleiben die +//! Typen und das Sammeln aus dem `Project`). +//! +//! Behandelt: L-Ecken (zwei Wandenden im Knoten), T-Knoten (drei Enden, zwei kollinear), +//! Mittelspannen-T-Stösse (freies Ende trifft auf die Seite einer anderen Wand) und +//! „+"-Kreuzungen (zwei kollineare Enden auf der Achse einer durchlaufenden Wand). Echte +//! Stern-Knoten (≥ 4 Enden ohne Durchgang) bleiben rechtwinklig. +//! +//! Die Rechenschritte folgen der TS-Fassung Operation für Operation (gleiche Term-Reihenfolge), +//! damit das Ergebnis bitgleich bleibt. + +use kernel2d::{add, dot, left_normal, line_intersect, scale, sub, Vec2}; +use std::collections::HashMap; + +/// Referenzlinie einer Wand (`Wall.referenceLine` / `referenceOffset`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Reference { + Center, + Left, + Right, + /// Freier Versatz (Meter), übersteuert die benannte Referenzlinie. + Offset(f64), +} + +/// Querversatz der Wandachse gegenüber der Wandmitte (`wallReferenceOffset` in `model/wall.ts`). +pub fn reference_offset(r: Reference, total_thickness: f64) -> f64 { + let half = total_thickness / 2.0; + match r { + // Math.max(-half, Math.min(half, v)) — Reihenfolge wie TS. + Reference::Offset(v) => (-half).max(half.min(v)), + Reference::Left => half, + Reference::Right => -half, + Reference::Center => 0.0, + } +} + +/// Eine Schicht des Wandtyps: Dicke, Bauteil-Identität (`None` = Bauteil unbekannt) und +/// Verschneidungs-Rang (`Component.joinPriority`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct JoinLayer { + pub thickness: f64, + pub component: Option, + pub priority: f64, +} + +/// Eine Wand für die Verschneidung. `layers = None`: Wandtyp unbekannt. +#[derive(Clone, Debug, PartialEq)] +pub struct JoinWall { + pub start: Vec2, + pub end: Vec2, + pub reference: Reference, + pub layers: Option>, +} + +/// Unendliche Gerade (Stützpunkt + Richtung, nicht normiert). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Line { + pub point: Vec2, + pub dir: Vec2, +} + +/// Pro-Schicht-Cuts eines materialbewussten T-Stosses (`LayerCuts` in TS). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct LayerCuts { + pub start: Vec>, + pub end: Vec>, + pub start_side: Vec>, + pub end_side: Vec>, +} + +/// Aussparung der Nah-Putz-Zone einer Durchgangswand (`SpanCutout` in TS). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SpanCutout { + pub from: f64, + pub to: f64, + pub off_a: f64, + pub off_b: f64, +} + +/// Schnittlinien einer Wand (`WallCuts` in TS). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct WallCuts { + pub start_cut: Option, + pub end_cut: Option, + pub layer_cuts: Option, + pub span_cutouts: Vec, +} + +/// Eine benötigte Angabe fehlt: Wandtyp oder Bauteil der Wand mit diesem Index ist unbekannt +/// (TS wirft dann denselben Fehler wie früher `getWallType`/`getComponent`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum JoinError { + UnknownWallType(usize), + UnknownComponent(usize), +} + +/// Verschneidungs-Entscheidung zweier Bauteile am Stoss (`resolveJoinPriority` in TS). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum JoinResolution { + /// Gleiche Priorität und gleiche Komponente: verschmelzen, kein Cut. + Merge, + /// `b` gewinnt, `a` wird getrimmt. + TrimA, + /// `a` gewinnt, `b` wird getrimmt. + TrimB, + /// Gleiche Priorität, verschiedene Komponente: keine Rangfolge (getrimmt wie bisher). + Coexist, +} + +pub fn resolve_join_priority(prio_a: f64, prio_b: f64, same_component: bool) -> JoinResolution { + if prio_a == prio_b { + if same_component { + JoinResolution::Merge + } else { + JoinResolution::Coexist + } + } else if prio_a > prio_b { + JoinResolution::TrimB + } else { + JoinResolution::TrimA + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum End { + Start, + End, +} + +#[derive(Clone, Copy, Debug)] +struct WallEnd { + wall: usize, + end: End, +} + +type R = Result; + +fn layers_of(walls: &[JoinWall], i: usize) -> R<&[JoinLayer]> { + walls[i].layers.as_deref().ok_or(JoinError::UnknownWallType(i)) +} + +/// `wallTypeThickness`: Summe der Schichtdicken (Reihenfolge wie `reduce`). +fn thickness(walls: &[JoinWall], i: usize) -> R { + Ok(layers_of(walls, i)?.iter().fold(0.0, |s, l| s + l.thickness)) +} + +fn component(i: usize, l: &JoinLayer) -> R { + l.component.ok_or(JoinError::UnknownComponent(i)) +} + +/// `Math.hypot(x, y)` wie V8 (Skalierung mit dem Maximum, kompensierte Summe) — `f64::hypot` +/// rundet im letzten Bit teils anders, das Ergebnis soll aber bitgleich zur TS-Fassung bleiben. +pub fn js_hypot(x: f64, y: f64) -> f64 { + let (ax, ay) = (x.abs(), y.abs()); + if ax.is_infinite() || ay.is_infinite() { + return f64::INFINITY; + } + if ax.is_nan() || ay.is_nan() { + return f64::NAN; + } + let max = ax.max(ay); + if max == 0.0 { + return 0.0; + } + let mut sum = 0.0; + let mut comp = 0.0; + for v in [ax, ay] { + let n = v / max; + let summand = n * n - comp; + let pre = sum + summand; + comp = (pre - sum) - summand; + sum = pre; + } + sum.sqrt() * max +} + +/// Vektorlänge wie `len` in `model/geometry.ts`. +pub fn len(a: Vec2) -> f64 { + js_hypot(a.x, a.y) +} + +/// Normieren wie `normalize` in `model/geometry.ts` (Länge 0 → Divisor 1). +pub fn normalize(a: Vec2) -> Vec2 { + let l = len(a); + let l = if l == 0.0 { 1.0 } else { l }; + Vec2::new(a.x / l, a.y / l) +} + +/// `Math.round` (halbe Werte nach +∞). +fn js_round(x: f64) -> f64 { + if !x.is_finite() { + return x; + } + let f = x.floor(); + if x - f >= 0.5 { + f + 1.0 + } else { + f + } +} + +/// Knoten-Schlüssel wie `roundKey` in TS (Raster 1e-4; −0 = 0; alle NaN gleich). +fn round_key(p: Vec2) -> (u64, u64) { + let r = |v: f64| { + let q = js_round(v * 1e4) / 1e4; + if q.is_nan() { + f64::NAN.to_bits() + } else if q == 0.0 { + 0 + } else { + q.to_bits() + } + }; + (r(p.x), r(p.y)) +} + +fn point_of(w: &JoinWall, e: End) -> Vec2 { + match e { + End::Start => w.start, + End::End => w.end, + } +} + +/// Achsrichtung start→end, normiert. +fn dir_of(w: &JoinWall) -> Vec2 { + normalize(sub(w.end, w.start)) +} + +fn set_cut(result: &mut [WallCuts], we: WallEnd, cut: Line) { + let c = &mut result[we.wall]; + match we.end { + End::Start => c.start_cut = Some(cut), + End::End => c.end_cut = Some(cut), + } +} + +/// Berechnet für jede Wand (Index = Eingabe-Reihenfolge) die Gehrungs-/Anschluss-Schnittlinien. +/// `walls` ist die bereits gefilterte Wandmenge (z. B. ein Geschoss). +pub fn compute_joins(walls: &[JoinWall]) -> Result, JoinError> { + let mut result = vec![WallCuts::default(); walls.len()]; + + // Knotenkarte in Einfüge-Reihenfolge: gerundeter Endpunkt → dort endende Wandenden. + let mut index: HashMap<(u64, u64), usize> = HashMap::new(); + let mut junctions: Vec> = Vec::new(); + let mut push = |p: Vec2, we: WallEnd| { + let key = round_key(p); + match index.get(&key) { + Some(&k) => junctions[k].push(we), + None => { + index.insert(key, junctions.len()); + junctions.push(vec![we]); + } + } + }; + for (i, w) in walls.iter().enumerate() { + push(w.start, WallEnd { wall: i, end: End::Start }); + push(w.end, WallEnd { wall: i, end: End::End }); + } + + for ends in &junctions { + match ends.len() { + 2 => { + if let Some(cut) = miter_line(walls, ends[0].wall, ends[0].end, ends[1].wall)? { + set_cut(&mut result, ends[0], cut); + set_cut(&mut result, ends[1], cut); + } + } + 3 => apply_t_junction(walls, ends, &mut result)?, + // Freies Ende (Fall 2 unten) bzw. echter Stern-Knoten (bleibt rechtwinklig). + _ => {} + } + } + + // Fall 2: jedes noch ungeschnittene Ende gegen die Mittelspanne aller anderen Wände prüfen + // (Mittelspannen-T und „+"-Kreuzung). Bereits geschnittene Enden bleiben unangetastet. + for ends in &junctions { + for &we in ends { + let c = &result[we.wall]; + let cut = match we.end { + End::Start => c.start_cut, + End::End => c.end_cut, + }; + if cut.is_none() { + apply_mid_span_tee(walls, we, &mut result)?; + } + } + } + Ok(result) +} + +/// Gemeinsame Gehrungslinie zweier Wände A, B im Knoten (orientierungsbasierte Flächen-Paarung: +/// Aussen mit Aussen, Innen mit Innen — robust auch bei spitzen Winkeln). `None` bei kollinearen +/// Achsen. +fn miter_line(walls: &[JoinWall], ai: usize, a_end: End, bi: usize) -> R> { + let (a, b) = (&walls[ai], &walls[bi]); + let j = point_of(a, a_end); + let t_a = thickness(walls, ai)?; + let t_b = thickness(walls, bi)?; + let u_a = dir_of(a); + let u_b = dir_of(b); + let n_a = left_normal(u_a); + let n_b = left_normal(u_b); + let off_a = reference_offset(a.reference, t_a); + let off_b = reference_offset(b.reference, t_b); + + let p_la = add(j, scale(n_a, off_a + t_a / 2.0)); + let p_ra = add(j, scale(n_a, off_a - t_a / 2.0)); + let p_lb = add(j, scale(n_b, off_b + t_b / 2.0)); + let p_rb = add(j, scale(n_b, off_b - t_b / 2.0)); + + let d_a = if a_end == End::Start { u_a } else { scale(u_a, -1.0) }; + let b_at_start = len(sub(b.start, j)) <= len(sub(b.end, j)); + let d_b = if b_at_start { u_b } else { scale(u_b, -1.0) }; + + let b_outer = if dot(n_b, d_a) < 0.0 { p_lb } else { p_rb }; + let b_inner = if dot(n_b, d_a) < 0.0 { p_rb } else { p_lb }; + let a_left_is_outer = dot(n_a, d_b) < 0.0; + let b_for_left = if a_left_is_outer { b_outer } else { b_inner }; + let b_for_right = if a_left_is_outer { b_inner } else { b_outer }; + + let (Some(c1), Some(c2)) = (line_intersect(p_la, u_a, b_for_left, u_b), line_intersect(p_ra, u_a, b_for_right, u_b)) else { + return Ok(None); + }; + let dir = sub(c2, c1); + if len(dir) < 1e-9 { + return Ok(None); + } + Ok(Some(Line { point: c1, dir })) +} + +/// Fall 1 — T-Knoten: drei Enden im Knoten, zwei davon kollinear (Durchgang). Der Abzweig bekommt +/// einen Schnitt an der ihm zugewandten Fläche der Durchgangswand; ohne kollineares Paar bleibt +/// der Knoten rechtwinklig. +fn apply_t_junction(walls: &[JoinWall], ends: &[WallEnd], result: &mut [WallCuts]) -> R<()> { + let dirs: Vec = ends.iter().map(|e| dir_of(&walls[e.wall])).collect(); + let mut through: Option<(usize, usize)> = None; + 'outer: for i in 0..3 { + for k in i + 1..3 { + if 1.0 - dot(dirs[i], dirs[k]).abs() < 1e-6 { + through = Some((i, k)); + break 'outer; + } + } + } + let Some((t0, t1)) = through else { return Ok(()) }; + let branch_idx = (0..3).find(|&i| i != t0 && i != t1).unwrap_or(0); + let branch_end = ends[branch_idx]; + let through_end = ends[t0]; + let (bi, ti) = (branch_end.wall, through_end.wall); + let through_wall = &walls[ti]; + + let j = point_of(through_wall, through_end.end); + let t_t = thickness(walls, ti)?; + let u_t = dir_of(through_wall); + let n_t = left_normal(u_t); + let off_t = reference_offset(through_wall.reference, t_t); + + let d_branch = if branch_end.end == End::Start { dir_of(&walls[bi]) } else { scale(dir_of(&walls[bi]), -1.0) }; + let sign = if dot(n_t, d_branch) >= 0.0 { 1.0 } else { -1.0 }; + let face_point = add(j, scale(n_t, off_t + sign * (t_t / 2.0))); + let face_cut = Line { point: face_point, dir: u_t }; + + set_cut(result, branch_end, face_cut); + apply_layer_cuts(walls, result, branch_end, ti, face_cut, j, u_t, sign) +} + +/// Materialbewusste Pro-Schicht-Erweiterung eines T-Stoss-Cuts: Abzweig-Schichten gleichen +/// Materials wie das Rückgrat der Durchgangswand (oder prioritärer) laufen bis zur +/// Rückgrat-Nahfläche durch; angrenzende getrimmte Schichten bekommen eine seitliche Linie; die +/// Durchgangswand bekommt eine Nah-Putz-Aussparung über die Kernbreite. Setzt `layer_cuts` nur, +/// wenn mindestens eine Schicht verschmilzt. +#[allow(clippy::too_many_arguments)] +fn apply_layer_cuts( + walls: &[JoinWall], + result: &mut [WallCuts], + branch_end: WallEnd, + ti: usize, + face_cut: Line, + axis_point: Vec2, + through_dir: Vec2, + sign: f64, +) -> R<()> { + let bi = branch_end.wall; + let branch_layers = layers_of(walls, bi)?; + let through_layers = layers_of(walls, ti)?; + if branch_layers.is_empty() || through_layers.is_empty() { + return Ok(()); + } + + // Rückgrat der Durchgangswand: Schicht mit der höchsten joinPriority (erste gewinnt). + let mut backbone = (component(ti, &through_layers[0])?, through_layers[0].priority); + let mut backbone_idx = 0; + for (i, l) in through_layers.iter().enumerate() { + let c = component(ti, l)?; + if l.priority > backbone.1 { + backbone = (c, l.priority); + backbone_idx = i; + } + } + + let n = branch_layers.len(); + let mut merged = vec![false; n]; + for (i, l) in branch_layers.iter().enumerate() { + let c = component(bi, l)?; + // "merge" (gleiches Rückgrat-Material) oder "trim-b" (Abzweig-Schicht selbst prioritärer) + // → die Schicht läuft durch. + merged[i] = matches!(resolve_join_priority(l.priority, backbone.1, c == backbone.0), JoinResolution::Merge | JoinResolution::TrimB); + } + if !merged.iter().any(|&m| m) { + return Ok(()); + } + + let lc = result[bi].layer_cuts.get_or_insert_with(|| LayerCuts { + start: vec![None; n], + end: vec![None; n], + start_side: vec![None; n], + end_side: vec![None; n], + }); + if lc.start.len() != n { + return Ok(()); + } + + let t_t = through_layers.iter().fold(0.0, |s, l| s + l.thickness); + let off_t = reference_offset(walls[ti].reference, t_t); + let near = |i: usize| if sign > 0.0 { i > backbone_idx } else { i < backbone_idx }; + let mut near_plaster = 0.0; + for (i, l) in through_layers.iter().enumerate() { + if near(i) { + near_plaster += l.thickness; + } + } + let n_t = left_normal(through_dir); + let merge_point = add(axis_point, scale(n_t, off_t + sign * (t_t / 2.0 - near_plaster))); + let merge_cut = Line { point: merge_point, dir: through_dir }; + let side_line = merge_cut; + + // Materialien des Nah-Putzes (Komponenten sind hier alle bekannt, s. Rückgrat-Suche). + let near_comps: Vec> = through_layers.iter().enumerate().filter(|(i, _)| near(*i)).map(|(_, l)| l.component).collect(); + + let (face_arr, side_arr) = match branch_end.end { + End::Start => (&mut lc.start, &mut lc.start_side), + End::End => (&mut lc.end, &mut lc.end_side), + }; + for i in 0..n { + face_arr[i] = Some(if merged[i] { merge_cut } else { face_cut }); + let adj_merged = !merged[i] && ((i > 0 && merged[i - 1]) || (i + 1 < n && merged[i + 1])); + let merges_with_near = near_comps.contains(&branch_layers[i].component); + side_arr[i] = if adj_merged && !merges_with_near { Some(side_line) } else { None }; + } + + // Durchgangswand-Aussparung über die Kernbreite des Abzweigs (nur bei Nah-Putz). + if near_plaster > 1e-9 { + let total_branch = branch_layers.iter().fold(0.0, |s, l| s + l.thickness); + let ref_off_branch = reference_offset(walls[bi].reference, total_branch); + let mut b_off = ref_off_branch - total_branch / 2.0; + let mut core_lo = f64::INFINITY; + let mut core_hi = f64::NEG_INFINITY; + for (i, l) in branch_layers.iter().enumerate() { + let th = l.thickness; + if merged[i] { + if b_off < core_lo { + core_lo = b_off; + } + if b_off + th > core_hi { + core_hi = b_off + th; + } + } + b_off += th; + } + if core_hi > core_lo { + let n_branch = left_normal(dir_of(&walls[bi])); + let proj = dot(n_branch, through_dir); + let axis_at = dot(sub(axis_point, walls[ti].start), through_dir); + let e1 = axis_at + core_lo * proj; + let e2 = axis_at + core_hi * proj; + let off_a = off_t + sign * (t_t / 2.0); + let off_b = off_t + sign * (t_t / 2.0 - near_plaster); + result[ti].span_cutouts.push(SpanCutout { from: e1.min(e2), to: e1.max(e2), off_a, off_b }); + } + } + Ok(()) +} + +/// Fall 2 — Mittelspannen-T-Stoss: trifft das Ende `free` auf die innere Spanne einer anderen +/// Wand (senkrecht höchstens halbe Dicke + 1 mm entfernt), bekommt es einen Schnitt an deren +/// zugewandter Fläche; bei mehreren Treffern gewinnt die nächstliegende Wand. +fn apply_mid_span_tee(walls: &[JoinWall], free: WallEnd, result: &mut [WallCuts]) -> R<()> { + let fi = free.wall; + let free_wall = &walls[fi]; + let p = point_of(free_wall, free.end); + const END_GAP: f64 = 1e-4; + const TOL: f64 = 1e-3; + + // (Wand, perp, dist, distAlong) + let mut best: Option<(usize, f64, f64, f64)> = None; + for (wi, w) in walls.iter().enumerate() { + if wi == fi { + continue; + } + let u = dir_of(w); + let w_len = len(sub(w.end, w.start)); + if w_len < 1e-9 { + continue; + } + let rel = sub(p, w.start); + let dist_along = dot(rel, u); + if dist_along <= END_GAP || dist_along >= w_len - END_GAP { + continue; + } + let perp = dot(rel, left_normal(u)); + let tw = thickness(walls, wi)?; + let dist = perp.abs(); + if dist > tw / 2.0 + TOL { + continue; + } + if best.map_or(true, |b| dist < b.2) { + best = Some((wi, perp, dist, dist_along)); + } + } + let Some((wi, perp, _, dist_along)) = best else { return Ok(()) }; + + let w = &walls[wi]; + let tw = thickness(walls, wi)?; + let u_w = dir_of(w); + let n_w = left_normal(u_w); + let off_w = reference_offset(w.reference, tw); + let d_free = if free.end == End::Start { dir_of(free_wall) } else { scale(dir_of(free_wall), -1.0) }; + let facing = dot(n_w, d_free); + let sign = if facing.abs() > 1e-6 { + if facing >= 0.0 { + 1.0 + } else { + -1.0 + } + } else if perp >= 0.0 { + 1.0 + } else { + -1.0 + }; + let face_point = add(w.start, scale(n_w, off_w + sign * (tw / 2.0))); + let face_cut = Line { point: face_point, dir: u_w }; + + set_cut(result, free, face_cut); + let axis_point = add(w.start, scale(u_w, dist_along)); + apply_layer_cuts(walls, result, free, wi, face_cut, axis_point, u_w, sign) +} + +// ── Flache Kodierung ───────────────────────────────────────────────────────── +// +// Wände: [n, (sx, sy, ex, ey, refKind, refValue, typeOk, nLayers, (dicke, bauteil, prio)…)…] +// refKind: 0 Mitte, 1 links, 2 rechts, 3 freier Versatz (refValue); bauteil < 0 = unbekannt. +// Cuts einer Wand: [start(5), end(5), nLC, (start, end, startSide, endSide je nLC × 5), +// nSpan, (from, to, offA, offB)…]; Linie = (gesetzt 0/1, px, py, dx, dy). + +/// Liest die Wände; `None` bei kaputten/unendlichen Daten. +pub fn decode_walls(buf: &[f64]) -> Option> { + let mut r = crate::flat_read::Reader::new(buf); + let n = r.count()?; + let mut out = Vec::with_capacity(n.min(1 << 16)); + for _ in 0..n { + let (sx, sy, ex, ey) = (r.num()?, r.num()?, r.num()?, r.num()?); + let (kind, value) = (r.num()?, r.num()?); + let type_ok = r.num()? != 0.0; + let nl = r.count()?; + if ![sx, sy, ex, ey].iter().all(|v| v.is_finite()) { + return None; + } + let reference = match kind as i64 { + 1 => Reference::Left, + 2 => Reference::Right, + 3 if value.is_finite() => Reference::Offset(value), + 3 => return None, + _ => Reference::Center, + }; + let mut layers = Vec::with_capacity(nl.min(1 << 10)); + for _ in 0..nl { + let (t, c, p) = (r.num()?, r.num()?, r.num()?); + if !t.is_finite() { + return None; + } + let component = (c.is_finite() && c >= 0.0 && c < 4e9).then_some(c as u32); + // Unbekanntes Bauteil: Priorität spielt keine Rolle (Fehler, sobald gebraucht). + let priority = if component.is_some() { p } else { f64::NAN }; + layers.push(JoinLayer { thickness: t, component, priority }); + } + out.push(JoinWall { start: Vec2::new(sx, sy), end: Vec2::new(ex, ey), reference, layers: type_ok.then_some(layers) }); + } + Some(out) +} + +fn push_line(out: &mut Vec, l: &Option) { + match l { + Some(l) => out.extend([1.0, l.point.x, l.point.y, l.dir.x, l.dir.y]), + None => out.extend([0.0; 5]), + } +} + +/// Hängt die Cuts einer Wand flach an. +pub fn encode_cuts(out: &mut Vec, c: &WallCuts) { + push_line(out, &c.start_cut); + push_line(out, &c.end_cut); + match &c.layer_cuts { + Some(lc) => { + out.push(lc.start.len() as f64); + for arr in [&lc.start, &lc.end, &lc.start_side, &lc.end_side] { + for l in arr { + push_line(out, l); + } + } + } + None => out.push(0.0), + } + out.push(c.span_cutouts.len() as f64); + for s in &c.span_cutouts { + out.extend([s.from, s.to, s.off_a, s.off_b]); + } +} + +fn read_line(r: &mut crate::flat_read::Reader) -> Option> { + let (set, px, py, dx, dy) = (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?); + if set == 0.0 { + return Some(None); + } + if ![px, py, dx, dy].iter().all(|v| v.is_finite()) { + return None; + } + Some(Some(Line { point: Vec2::new(px, py), dir: Vec2::new(dx, dy) })) +} + +/// Liest die Cuts einer Wand (Gegenstück zu [`encode_cuts`]). +pub fn decode_cuts(r: &mut crate::flat_read::Reader) -> Option { + let start_cut = read_line(r)?; + let end_cut = read_line(r)?; + let n = r.count()?; + let layer_cuts = if n > 0 { + if n > 1 << 12 { + return None; + } + let mut arrs: [Vec>; 4] = Default::default(); + for a in arrs.iter_mut() { + for _ in 0..n { + a.push(read_line(r)?); + } + } + let [start, end, start_side, end_side] = arrs; + Some(LayerCuts { start, end, start_side, end_side }) + } else { + None + }; + let m = r.count()?; + let mut span_cutouts = Vec::with_capacity(m.min(1 << 10)); + for _ in 0..m { + let s = SpanCutout { from: r.num()?, to: r.num()?, off_a: r.num()?, off_b: r.num()? }; + if ![s.from, s.to, s.off_a, s.off_b].iter().all(|v| v.is_finite()) { + return None; + } + span_cutouts.push(s); + } + Some(WallCuts { start_cut, end_cut, layer_cuts, span_cutouts }) +} + +/// Ergebnis flach: `[0, (cuts je Wand)…]`; Fehler `[1, wandIndex]` (Wandtyp bzw. Bauteil +/// unbekannt — TS wirft); kaputte Eingabe: leer. +pub fn compute_joins_flat(buf: &[f64]) -> Vec { + let Some(walls) = decode_walls(buf) else { return vec![] }; + match compute_joins(&walls) { + Ok(cuts) => { + let mut out = vec![0.0]; + for c in &cuts { + encode_cuts(&mut out, c); + } + out + } + Err(JoinError::UnknownWallType(i)) | Err(JoinError::UnknownComponent(i)) => vec![1.0, i as f64], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn layer(t: f64, c: u32, p: f64) -> JoinLayer { + JoinLayer { thickness: t, component: Some(c), priority: p } + } + fn wall(s: (f64, f64), e: (f64, f64), layers: Vec) -> JoinWall { + JoinWall { start: Vec2::new(s.0, s.1), end: Vec2::new(e.0, e.1), reference: Reference::Center, layers: Some(layers) } + } + fn mono(s: (f64, f64), e: (f64, f64), t: f64) -> JoinWall { + wall(s, e, vec![layer(t, 0, 10.0)]) + } + /// Abstand eines Punkts von der Geraden. + fn dist(l: &Line, p: Vec2) -> f64 { + kernel2d::cross(l.dir, sub(p, l.point)).abs() / len(l.dir) + } + fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 + } + + #[test] + fn l_ecke_gehrung_auf_diagonale() { + let w = vec![mono((0.0, 0.0), (5.0, 0.0), 0.4), mono((5.0, 0.0), (5.0, 4.0), 0.4)]; + let c = compute_joins(&w).unwrap(); + let a = c[0].end_cut.unwrap(); + assert_eq!(c[1].start_cut, Some(a)); + // Aussen-Apex (5.2, -0.2), Innen-Apex (4.8, 0.2). + assert!(dist(&a, Vec2::new(5.2, -0.2)) < 1e-9 && dist(&a, Vec2::new(4.8, 0.2)) < 1e-9); + assert_eq!(c[0].start_cut, None); + } + + #[test] + fn spitze_ecke_paart_aussen_mit_aussen() { + let w = vec![mono((0.0, 0.0), (4.0, 0.0), 0.2), mono((4.0, 0.0), (1.0, 1.0), 0.2)]; + let c = compute_joins(&w).unwrap(); + let cut = c[0].end_cut.unwrap(); + // Gleiche Dicken: die Gehrung ist die Winkelhalbierende durch den Knoten (über Kreuz + // gepaart stünde sie senkrecht dazu). + let bis = add(Vec2::new(-1.0, 0.0), normalize(Vec2::new(-3.0, 1.0))); + assert!(kernel2d::cross(normalize(cut.dir), normalize(bis)).abs() < 1e-9, "{cut:?}"); + assert!(dist(&cut, Vec2::new(4.0, 0.0)) < 1e-9); + } + + #[test] + fn t_knoten_schneidet_nur_abzweig() { + let w = vec![mono((0.0, 0.0), (3.0, 0.0), 0.3), mono((3.0, 0.0), (6.0, 0.0), 0.3), mono((3.0, 0.0), (3.0, 4.0), 0.2)]; + let c = compute_joins(&w).unwrap(); + assert_eq!(c[0].end_cut, None); + assert_eq!(c[1].start_cut, None); + let cut = c[2].start_cut.unwrap(); + assert!(close(cut.point.y, 0.15) && close(cut.dir.y, 0.0)); + } + + #[test] + fn mittelspannen_t_und_kreuzung() { + // Durchlaufende Wand, oben ein Abzweig, unten/oben eine Kreuzung aus zwei Hälften. + let w = vec![ + mono((0.0, 0.0), (10.0, 0.0), 0.3), + mono((2.0, 0.0), (2.0, 3.0), 0.2), + mono((6.0, -3.0), (6.0, 0.0), 0.2), + mono((6.0, 0.0), (6.0, 3.0), 0.2), + ]; + let c = compute_joins(&w).unwrap(); + assert!(close(c[1].start_cut.unwrap().point.y, 0.15)); + assert!(close(c[2].end_cut.unwrap().point.y, -0.15)); + assert!(close(c[3].start_cut.unwrap().point.y, 0.15)); + assert_eq!(c[0], WallCuts::default()); + } + + #[test] + fn freies_ende_bleibt_rechtwinklig() { + let w = vec![mono((0.0, 0.0), (10.0, 0.0), 0.3), mono((2.0, 1.0), (2.0, 3.0), 0.2)]; + assert_eq!(compute_joins(&w).unwrap(), vec![WallCuts::default(); 2]); + } + + #[test] + fn materialbewusster_t_stoss() { + // Durchgang: Putz(0) 0.02 | Backstein(1, prio 50) 0.15 | Putz(0) 0.015; Abzweig gleich. + let lay = || vec![layer(0.02, 0, 10.0), layer(0.15, 1, 50.0), layer(0.015, 0, 10.0)]; + let w = vec![wall((0.0, 0.0), (10.0, 0.0), lay()), wall((4.0, 0.0), (4.0, 3.0), lay())]; + let c = compute_joins(&w).unwrap(); + let lc = c[1].layer_cuts.as_ref().unwrap(); + let total: f64 = 0.185; + // Kern läuft bis zur Rückgrat-Nahfläche (Nah-Putz 0.015 auf der +n-Seite). + assert!(close(lc.start[1].unwrap().point.y, total / 2.0 - 0.015)); + assert!(close(lc.start[0].unwrap().point.y, total / 2.0)); + // Putz-Schichten sind materialgleich mit dem Nah-Putz → keine Seitenlinie. + assert_eq!(lc.start_side, vec![None; 3]); + assert_eq!(lc.end, vec![None; 3]); + // Durchgangswand bekommt die Nah-Putz-Aussparung über die Kernbreite. + let s = c[0].span_cutouts[0]; + assert!(close(s.off_a, total / 2.0) && close(s.off_b, total / 2.0 - 0.015)); + assert!(close(s.to - s.from, 0.15), "{s:?}"); + } + + #[test] + fn hypot_wie_js() { + assert_eq!(js_hypot(3.0, 4.0), 5.0); + assert_eq!(js_hypot(0.0, -0.0), 0.0); + assert!(js_hypot(f64::NAN, 1.0).is_nan()); + assert_eq!(js_hypot(f64::INFINITY, f64::NAN), f64::INFINITY); + assert_eq!(normalize(Vec2::new(0.0, 0.0)), Vec2::new(0.0, 0.0)); + } + + #[test] + fn referenzlinie() { + assert_eq!(reference_offset(Reference::Left, 0.4), 0.2); + assert_eq!(reference_offset(Reference::Right, 0.4), -0.2); + assert_eq!(reference_offset(Reference::Offset(5.0), 0.4), 0.2); + assert_eq!(reference_offset(Reference::Offset(-0.05), 0.4), -0.05); + } + + #[test] + fn unbekannter_typ_nur_wenn_gebraucht() { + let mut w = vec![mono((0.0, 0.0), (5.0, 0.0), 0.4), mono((5.0, 0.0), (5.0, 4.0), 0.4), mono((20.0, 0.0), (25.0, 0.0), 0.4)]; + w[2].layers = None; + assert!(compute_joins(&w).is_ok()); // freistehend → nie gebraucht + w[1].layers = None; + assert_eq!(compute_joins(&w), Err(JoinError::UnknownWallType(1))); + } + + #[test] + fn unsinn_ohne_panic() { + assert!(compute_joins_flat(&[]).is_empty()); + assert!(compute_joins_flat(&[f64::NAN]).is_empty()); + assert!(compute_joins_flat(&[1.0, 0.0, 0.0]).is_empty()); + assert!(compute_joins_flat(&[1.0, f64::NAN, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0]).is_empty()); + assert_eq!(compute_joins_flat(&[0.0]), vec![0.0]); + // Nulllängen-Wände und deckungsgleiche Enden. + let w = [ + 3.0, // + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.2, 0.0, 10.0, // Nulllänge, eine Schicht + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, // Nulllänge, ohne Schichten + 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, // Wandtyp unbekannt + ]; + let out = compute_joins_flat(&w); + assert_eq!(out.first(), Some(&0.0)); + // Kaputte Cuts lesen. + let mut r = crate::flat_read::Reader::new(&[1.0, 0.0]); + assert!(decode_cuts(&mut r).is_none()); + } + + #[test] + fn cuts_hin_und_zurueck() { + let lay = || vec![layer(0.02, 0, 10.0), layer(0.15, 1, 50.0), layer(0.015, 0, 10.0)]; + let w = vec![wall((0.0, 0.0), (10.0, 0.0), lay()), wall((4.0, 0.0), (4.0, 3.0), lay()), wall((10.0, 0.0), (10.0, 5.0), lay())]; + for c in compute_joins(&w).unwrap() { + let mut buf = vec![]; + encode_cuts(&mut buf, &c); + let mut r = crate::flat_read::Reader::new(&buf); + assert_eq!(decode_cuts(&mut r), Some(c)); + } + } +} diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index d430121c..a345e5e6 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -13,6 +13,8 @@ pub mod sun; pub mod site_rules; pub mod auto_dimensions; pub mod kennzahlen; +pub mod joins; +pub mod wall_bands; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/wall_bands.rs b/src-tauri/core/src/wall_bands.rs new file mode 100644 index 00000000..f3add672 --- /dev/null +++ b/src-tauri/core/src/wall_bands.rs @@ -0,0 +1,969 @@ +//! Wand-Schichtbänder für 3D/STL/OBJ/IFC: zerlegt EINE Wand in quer zur Dicke gestapelte +//! Materialbänder und schneidet daraus achsparallele Körper — mit Gehrungs-/Anschluss-Cuts +//! (aus [`crate::joins`]), Nah-Putz-Aussparungen der Durchgangswand, Decken-Dominanz pro Schicht, +//! Öffnungs-Löchern und schräger Oberkante unter Dachflächen (`top_drop`). Portiert aus +//! `src/plan/toWalls3d/bands.ts`; dort bleiben das Sammeln aus dem `Project` (Wandtyp, Öffnungen, +//! Decken-/Dachaufbau, Höhen) und die Darstellungs-Metadaten (Farbe, Schraffur, Material). +//! +//! Zwei Pfade wie in TS: `layered` (3D-Viewer: ein Körper je Band über die volle Achse, Öffnungen +//! als Löcher) und Schnitt-Eingabe (Pfeiler/Brüstung/Sturz-Segmente ohne Löcher). + +use crate::joins::{js_hypot, reference_offset, Line, Reference, WallCuts}; +use crate::roof::roof_underside_at; +use kernel2d::{add, dot, left_normal, line_intersect, point_in_outline, scale, sub, Vec2}; + +/// Toleranz der Wand-Ableitung (`EPS` in `toWalls3d/shared.ts`). +pub const EPS: f64 = 1e-4; +/// Schrittweite (Meter) der Dach-Unterkanten-Abtastung. +const ROOF_CLIP_STEP: f64 = 0.15; + +/// Ein Schicht-Band: Dicke und Verschneidungs-Rang (`None`: keine Decken-Subtraktion). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BandIn { + pub thickness: f64, + pub priority: Option, +} + +/// Eine Öffnung der Wand: Achsen-Intervall (Meter ab Wandstart), absolute z-Ausdehnung und ob +/// die innerste Schicht an der Laibung zurückspringt (`WindowType.innerLayerRecess`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OpeningIn { + pub from: f64, + pub to: f64, + pub z_bottom: f64, + pub z_top: f64, + pub recess_inner_layer: bool, +} + +/// Eine Decke desselben Geschosses: z-Ausdehnung, Umriss, Schichten (Dicke, Rang; `None` = +/// Bauteil unbekannt). `layers = None`: Deckentyp unbekannt. +#[derive(Clone, Debug, PartialEq)] +pub struct CeilingIn { + pub z_bottom: f64, + pub z_top: f64, + pub outline: Vec, + pub layers: Option)>>, +} + +/// Ein Dach desselben Geschosses: Traufhöhe, Summe der Schichtdicken, Traufe-Umriss, Flächen. +#[derive(Clone, Debug, PartialEq)] +pub struct RoofIn { + pub eaves_z: f64, + pub total_thickness: f64, + pub eaves: Vec<[f64; 2]>, + pub planes: Vec>, +} + +/// Terminierung am Deckenanschluss (`Wall.sliceTermination`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Termination { + Both, + Below, + Above, +} + +/// Eine Wand mit allem, was die Bänder brauchen. +#[derive(Clone, Debug, PartialEq)] +pub struct WallIn { + pub start: Vec2, + pub end: Vec2, + pub z_bottom: f64, + pub z_top: f64, + pub layered: bool, + /// `true`: Bänder sind die Wandschichten (Versätze gestapelt); `false`: EIN Band über die + /// ganze Dicke, Versatz = Referenzversatz. + pub stacked: bool, + pub reference: Reference, + /// Wanddicke für die grobe Grundriss-Hülle (Decken-Vorfilter). + pub thickness_safe: f64, + pub termination: Termination, + pub bands: Vec, + pub openings: Vec, + pub cuts: WallCuts, +} + +/// Decken und Dächer eines Geschosses — einmal je Geschoss gelesen, für alle seine Wände; die +/// Grundriss-Hüllen werden dabei vorab bestimmt. +#[derive(Clone, Debug, Default)] +pub struct FloorContext { + ceilings: Vec<(CeilingIn, Bounds)>, + roofs: Vec<(RoofIn, Bounds)>, +} + +impl FloorContext { + pub fn new(ceilings: Vec, roofs: Vec) -> Self { + FloorContext { + ceilings: ceilings + .into_iter() + .map(|c| { + let b = outline_bounds(c.outline.iter().map(|p| (p.x, p.y))); + (c, b) + }) + .collect(), + roofs: roofs + .into_iter() + .map(|r| { + let b = outline_bounds(r.eaves.iter().map(|p| (p[0], p[1]))); + (r, b) + }) + .collect(), + } + } +} + +/// Ein Wandkörper: Band-Index, Achse (versetzt), z-Bereich, Absenkung der Oberkante am +/// Anfang/Ende (`None` = flach), Löcher `[from, to, zBottom, zTop]` relativ zum Körper-Start. +#[derive(Clone, Debug, PartialEq)] +pub struct Piece { + pub band: usize, + pub start: Vec2, + pub end: Vec2, + pub z_bottom: f64, + pub z_top: f64, + pub top_drop: Option<[f64; 2]>, + pub holes: Vec<[f64; 4]>, +} + +#[derive(Clone, Copy, Debug)] +struct Bounds { + min_x: f64, + max_x: f64, + min_y: f64, + max_y: f64, +} + +fn wall_bounds(w: &WallIn, half: f64) -> Bounds { + Bounds { + min_x: w.start.x.min(w.end.x) - half, + max_x: w.start.x.max(w.end.x) + half, + min_y: w.start.y.min(w.end.y) - half, + max_y: w.start.y.max(w.end.y) + half, + } +} + +fn outline_bounds(pts: impl Iterator) -> Bounds { + let mut b = Bounds { min_x: f64::INFINITY, max_x: f64::NEG_INFINITY, min_y: f64::INFINITY, max_y: f64::NEG_INFINITY }; + for (x, y) in pts { + if x < b.min_x { + b.min_x = x; + } + if x > b.max_x { + b.max_x = x; + } + if y < b.min_y { + b.min_y = y; + } + if y > b.max_y { + b.max_y = y; + } + } + b +} + +fn bounds_overlap(a: Bounds, b: Bounds) -> bool { + a.min_x <= b.max_x + EPS && a.max_x >= b.min_x - EPS && a.min_y <= b.max_y + EPS && a.max_y >= b.min_y - EPS +} + +/// Decken-„Cutter": z-Band einer Deckenschicht, ihr Rang und der Decken-Umriss. +struct Cutter<'a> { + z_bottom: f64, + z_top: f64, + priority: f64, + outline: &'a [Vec2], +} + +/// Decken, die die Wand pro Schicht einschneiden: dasselbe Geschoss (Aufrufer), vertikale +/// Überlappung, grober Grundriss-Überlapp; je Deckenschicht ein eigener Cutter (proportional auf +/// die Decken-z-Spanne verteilt, oben → unten), sonst einer über die volle Höhe mit dem höchsten +/// Rang. +fn ceiling_cutters<'a>(w: &WallIn, ctx: &'a FloorContext) -> Vec> { + let wb = wall_bounds(w, w.thickness_safe / 2.0); + let mut out = Vec::new(); + for (c, cb) in &ctx.ceilings { + if c.outline.len() < 3 { + continue; + } + if c.z_bottom >= w.z_top - EPS || c.z_top <= w.z_bottom + EPS { + continue; + } + if !bounds_overlap(wb, *cb) { + continue; + } + let total = c.layers.as_ref().map_or(0.0, |ls| ls.iter().fold(0.0, |s, l| s + l.0)); + match &c.layers { + Some(ls) if !ls.is_empty() && total > EPS => { + let span = c.z_top - c.z_bottom; + let mut prefix_top = 0.0; + for &(th, prio) in ls { + let t = (th / total) * span; + let layer_top = c.z_top - prefix_top; + let layer_bottom = layer_top - t; + prefix_top += t; + if let Some(p) = prio { + out.push(Cutter { z_bottom: layer_bottom, z_top: layer_top, priority: p, outline: &c.outline }); + } + } + } + _ => { + // Höchster Rang aller Schichten; ein unbekanntes Bauteil (oder Typ) → kein Cutter. + let Some(ls) = &c.layers else { continue }; + let mut best: Option = None; + let mut known = true; + for &(_, p) in ls { + match p { + Some(p) => { + if best.map_or(true, |b| p > b) { + best = Some(p); + } + } + None => known = false, + } + } + if let (true, Some(p)) = (known, best) { + out.push(Cutter { z_bottom: c.z_bottom, z_top: c.z_top, priority: p, outline: &c.outline }); + } + } + } + } + out +} + +/// Achsen-Teilintervalle in `[lo, hi]`, auf denen die Mittellinie eines Bands (Querversatz +/// `offset`) im Umriss liegt: Raster ~5 cm (min. 32 Schritte), Übergänge per Bisektion. +fn band_coverage(w: &WallIn, u: Vec2, n: Vec2, offset: f64, outline: &[Vec2], lo: f64, hi: f64) -> Vec<[f64; 2]> { + if hi - lo <= EPS { + return vec![]; + } + let base = add(w.start, scale(n, offset)); + let inside = |t: f64| point_in_outline(add(base, scale(u, t)), outline); + let steps = 32f64.max(((hi - lo) / 0.05).ceil()) as usize; + let dt = (hi - lo) / steps as f64; + let mut out = Vec::new(); + let mut prev_inside = inside(lo); + let mut start = if prev_inside { Some(lo) } else { None }; + let mut prev_t = lo; + for i in 1..=steps { + let t = if i == steps { hi } else { lo + i as f64 * dt }; + let now = inside(t); + if now != prev_inside { + let cross = bisect(&inside, prev_t, t); + if now { + start = Some(cross); + } else if let Some(s) = start.take() { + out.push([s, cross]); + } + } + prev_inside = now; + prev_t = t; + } + if let Some(s) = start { + out.push([s, hi]); + } + out +} + +fn bisect(inside: &impl Fn(f64) -> bool, a: f64, b: f64) -> f64 { + let a_inside = inside(a); + let (mut lo, mut hi) = (a, b); + let mut i = 0; + while i < 40 && hi - lo > EPS * 0.01 { + let mid = (lo + hi) / 2.0; + if inside(mid) == a_inside { + lo = mid; + } else { + hi = mid; + } + i += 1; + } + (lo + hi) / 2.0 +} + +/// `[lo, hi]` minus die (geklemmten, vereinigten) Intervalle `holes`. +fn subtract_spans(lo: f64, hi: f64, holes: &[[f64; 2]]) -> Vec<[f64; 2]> { + let mut clipped: Vec<[f64; 2]> = holes + .iter() + .map(|&[a, b]| [lo.max(a.min(b)), hi.min(a.max(b))]) + .filter(|&[a, b]| b > a + EPS) + .collect(); + clipped.sort_by(|p, q| p[0].partial_cmp(&q[0]).unwrap_or(std::cmp::Ordering::Equal)); + let mut parts = Vec::new(); + let mut cursor = lo; + for [a, b] in clipped { + if a > cursor + EPS { + parts.push([cursor, a]); + } + if b > cursor { + cursor = b; + } + } + if cursor < hi - EPS { + parts.push([cursor, hi]); + } + parts +} + +/// Decken-z-Cutter auf `[lo, hi]` je Terminierung: ausstanzen (beide), unter der Decke enden, +/// über der Decke beginnen. +fn terminate_or_subtract(lo: f64, hi: f64, cutters: &[[f64; 2]], term: Termination) -> Vec<[f64; 2]> { + if cutters.is_empty() { + return vec![[lo, hi]]; + } + match term { + Termination::Below => { + let clip_top = cutters.iter().fold(f64::INFINITY, |m, c| m.min(c[0])); + let top = clip_top.min(hi); + if top > lo + EPS { + vec![[lo, top]] + } else { + vec![] + } + } + Termination::Above => { + let clip_bottom = cutters.iter().fold(f64::NEG_INFINITY, |m, c| m.max(c[1])); + let bottom = clip_bottom.max(lo); + if bottom < hi - EPS { + vec![[bottom, hi]] + } else { + vec![] + } + } + Termination::Both => subtract_spans(lo, hi, cutters), + } +} + +/// Achsen-Distanz, an der die Band-Mittellinie die Schnittlinie trifft (`None`: parallel). +fn band_cut_distance(w: &WallIn, u: Vec2, n: Vec2, offset: f64, cut: &Line) -> Option { + let base = add(w.start, scale(n, offset)); + let hit = line_intersect(base, u, cut.point, cut.dir)?; + Some(dot(sub(hit, w.start), u)) +} + +/// Sammelt die Körper; `emit_piece` des layered-Pfads je Band. +struct Emitter<'a> { + w: &'a WallIn, + out: Vec, +} + +impl Emitter<'_> { + /// `pushSegment`: Achsenstück [from, to] × [zb, zt], quer um `offset` versetzt. + fn push(&mut self, band: usize, from: f64, to: f64, zb: f64, zt: f64, offset: f64, holes: Vec<[f64; 4]>, drop: [f64; 2]) { + if to - from <= EPS || zt - zb <= EPS { + return; + } + let (dx, dy) = (self.w.end.x - self.w.start.x, self.w.end.y - self.w.start.y); + let len = js_hypot(dx, dy); + if len < 1e-9 { + return; + } + let (ux, uy) = (dx / len, dy / len); + let (ox, oy) = (-uy * offset, ux * offset); + let s = self.w.start; + self.out.push(Piece { + band, + start: Vec2::new(s.x + ux * from + ox, s.y + uy * from + oy), + end: Vec2::new(s.x + ux * to + ox, s.y + uy * to + oy), + z_bottom: zb, + z_top: zt, + top_drop: (drop[0] > EPS || drop[1] > EPS).then_some(drop), + holes, + }); + } +} + +/// Oberkante des Bands unter den Dächern: Dach-Unterkante entlang der Achse abtasten, zu geraden +/// Stücken (Toleranz 2 mm) zusammenfassen, Knicke exakt als Schnitt der Nachbargeraden; je Stück +/// ein Körper mit schräger Oberkante. Ohne Dach darüber: ein Körper, unverändert. +#[allow(clippy::too_many_arguments)] +fn clip_to_roofs(w: &WallIn, ctx: &FloorContext, u: Vec2, n: Vec2, offset: f64, a: f64, bb: f64, zb: f64, zt: f64, emit: &mut dyn FnMut(f64, f64, f64, f64, f64)) { + if zt - zb <= EPS || bb - a <= EPS { + return; + } + let wb = wall_bounds(w, offset.abs() + 0.01); + let roofs: Vec<&RoofIn> = ctx.roofs.iter().filter(|(r, rb)| r.eaves_z + 50.0 >= zb && bounds_overlap(wb, *rb)).map(|(r, _)| r).collect(); + if roofs.is_empty() { + emit(a, bb, zb, zt, zt); + return; + } + let span = bb - a; + let count = 1usize.max((span / ROOF_CLIP_STEP).ceil() as usize); + let top_at = |t: f64| { + let tt = (bb - 1e-3).min((a + 1e-3).max(t)); + let p = add(add(w.start, scale(u, tt)), scale(n, offset)); + let mut clip = zt; + for r in &roofs { + if let Some(under) = roof_underside_at(&r.planes, r.total_thickness, p.x, p.y) { + if under < clip { + clip = under; + } + } + } + zb.max(clip) + }; + let mut ts = Vec::with_capacity(count + 1); + let mut tops = Vec::with_capacity(count + 1); + for i in 0..=count { + ts.push(a + (span * i as f64) / count as f64); + tops.push(top_at(ts[i])); + } + const TOL: f64 = 0.002; + let mut runs: Vec<(usize, usize)> = Vec::new(); + let mut i0 = 0; + while i0 < count { + let mut i1 = i0 + 1; + while i1 < count { + let k = i1 + 1; + let slope = (tops[k] - tops[i0]) / (ts[k] - ts[i0]); + let ok = (i0 + 1..=k).all(|m| (tops[i0] + slope * (ts[m] - ts[i0]) - tops[m]).abs() <= TOL); + if !ok { + break; + } + i1 = k; + } + runs.push((i0, i1)); + i0 = i1; + } + let line = |r: (usize, usize)| { + let m = (tops[r.1] - tops[r.0]) / (ts[r.1] - ts[r.0]); + (m, tops[r.0] - m * ts[r.0]) + }; + let mut cuts = vec![a]; + for r in 0..runs.len().saturating_sub(1) { + let l1 = line(runs[r]); + let l2 = line(runs[r + 1]); + let lo = ts[runs[r].1 - 1]; + let hi = ts[count.min(runs[r].1 + 1)]; + let mut x = ts[runs[r].1]; + if (l1.0 - l2.0).abs() > 1e-9 { + let cx = (l2.1 - l1.1) / (l1.0 - l2.0); + if cx >= lo && cx <= hi { + x = cx; + } + } + cuts.push(x); + } + cuts.push(bb); + for (k, &r) in runs.iter().enumerate() { + let (sa, sb) = (cuts[k], cuts[k + 1]); + if sb - sa <= EPS { + continue; + } + let value_at = |x: f64| { + let l = line(r); + zt.min(zb.max(l.0 * x + l.1)) + }; + let (z0, z1) = (value_at(sa), value_at(sb)); + if z0.max(z1) - zb > EPS { + emit(sa, sb, zb, z0, z1); + } + } +} + +/// Band-Versätze (Mitte je Band, entlang der linken Normalen, relativ zur Achse). +fn band_offsets(w: &WallIn) -> Vec { + if !w.stacked { + return w.bands.iter().map(|b| reference_offset(w.reference, b.thickness)).collect(); + } + let total = w.bands.iter().fold(0.0, |s, b| s + b.thickness); + let ref_off = reference_offset(w.reference, total); + let mut prefix = 0.0; + w.bands + .iter() + .map(|b| { + let o = ref_off - total / 2.0 + prefix + b.thickness / 2.0; + prefix += b.thickness; + o + }) + .collect() +} + +/// Alle Körper EINER Wand, in der Reihenfolge der früheren TS-Emission. +pub fn wall_bands(w: &WallIn, ctx: &FloorContext) -> Vec { + let mut em = Emitter { w, out: Vec::new() }; + let axis_len = js_hypot(w.end.x - w.start.x, w.end.y - w.start.y); + if axis_len < 1e-9 || w.z_top - w.z_bottom <= EPS { + return em.out; + } + let offsets = band_offsets(w); + let (z_bottom, z_top) = (w.z_bottom, w.z_top); + let mut cutouts = w.openings.clone(); + cutouts.sort_by(|a, b| a.from.partial_cmp(&b.from).unwrap_or(std::cmp::Ordering::Equal)); + + if !w.layered { + // Schnitt-Pfad: Pfeiler/Brüstung/Sturz, je Segment alle Bänder. + let seg = |em: &mut Emitter, from: f64, to: f64, zb: f64, zt: f64| { + for (i, &off) in offsets.iter().enumerate() { + em.push(i, from, to, zb, zt, off, vec![], [0.0, 0.0]); + } + }; + if cutouts.is_empty() { + seg(&mut em, 0.0, axis_len, z_bottom, z_top); + return em.out; + } + let mut cursor = 0.0f64; + for c in &cutouts { + let seg_from = cursor.max(c.from); + if c.from > cursor { + seg(&mut em, cursor, c.from, z_bottom, z_top); + } + if c.to > seg_from { + if c.z_bottom > z_bottom + EPS { + seg(&mut em, seg_from, c.to, z_bottom, c.z_bottom); + } + if c.z_top < z_top - EPS { + seg(&mut em, seg_from, c.to, c.z_top, z_top); + } + } + cursor = cursor.max(c.to); + } + if cursor < axis_len { + seg(&mut em, cursor, axis_len, z_bottom, z_top); + } + return em.out; + } + + let cuts = &w.cuts; + let u = Vec2::new((w.end.x - w.start.x) / axis_len, (w.end.y - w.start.y) / axis_len); + let n = left_normal(u); + let cutters = ceiling_cutters(w, ctx); + let n_bands = w.bands.len(); + + for (li, b) in w.bands.iter().enumerate() { + let off = offsets[li]; + // (1) Cuts an den Achsenenden (pro Schicht, falls materialbewusst). + let (s_cut, e_cut) = match &cuts.layer_cuts { + Some(lc) => (lc.start.get(li).copied().flatten(), lc.end.get(li).copied().flatten()), + None => (cuts.start_cut, cuts.end_cut), + }; + let mut from0 = 0.0; + let mut to0 = axis_len; + if let Some(c) = s_cut { + if let Some(d) = band_cut_distance(w, u, n, off, &c) { + from0 = d; + } + } + if let Some(c) = e_cut { + if let Some(d) = band_cut_distance(w, u, n, off, &c) { + to0 = d; + } + } + + // (2) Nah-Putz-Aussparungen, die dieses Band quer treffen. + let band_lo = off - b.thickness / 2.0; + let band_hi = off + b.thickness / 2.0; + let axis_holes: Vec<[f64; 2]> = cuts + .span_cutouts + .iter() + .filter(|c| band_lo < c.off_a.max(c.off_b) - EPS && band_hi > c.off_a.min(c.off_b) + EPS) + .map(|c| [c.from, c.to]) + .collect(); + let axis_pieces = subtract_spans(from0, to0, &axis_holes); + + // (3) Decken-Subtraktion je Band dort, wo der Decken-Umriss die Band-Mittellinie deckt. + let mut band_z_cuts: Vec<[f64; 4]> = Vec::new(); // from, to, zBottom, zTop + if let Some(bp) = b.priority { + for cc in &cutters { + if cc.priority <= bp { + continue; + } + for [ca, cb] in band_coverage(w, u, n, off, cc.outline, from0, to0) { + band_z_cuts.push([ca, cb, cc.z_bottom, cc.z_top]); + } + } + } + + let innermost = li == n_bands - 1; + let recess = b.thickness; + let mut emit_piece = |a: f64, bb: f64, zb: f64, zt_start: f64, zt_end: f64| { + emit_band_piece(&mut em, li, off, &cutouts, innermost, recess, a, bb, zb, zt_start, zt_end); + }; + + for [a, bb] in axis_pieces { + let local: Vec<[f64; 4]> = band_z_cuts + .iter() + .map(|c| [a.max(c[0]), bb.min(c[1]), c[2], c[3]]) + .filter(|c| c[1] > c[0] + EPS) + .collect(); + if local.is_empty() { + clip_to_roofs(w, ctx, u, n, off, a, bb, z_bottom, z_top, &mut emit_piece); + continue; + } + let mut xs = vec![a, bb]; + for c in &local { + xs.push(c[0]); + xs.push(c[1]); + } + xs.sort_by(|p, q| p.partial_cmp(q).unwrap_or(std::cmp::Ordering::Equal)); + xs.dedup(); + for i in 0..xs.len() - 1 { + let (xa, xb) = (xs[i], xs[i + 1]); + if xb - xa <= EPS { + continue; + } + let mid = (xa + xb) / 2.0; + let z_cutters: Vec<[f64; 2]> = local.iter().filter(|c| c[0] <= mid && c[1] >= mid).map(|c| [c[2], c[3]]).collect(); + for [zb, zt] in terminate_or_subtract(z_bottom, z_top, &z_cutters, w.termination) { + clip_to_roofs(w, ctx, u, n, off, xa, xb, zb, zt, &mut emit_piece); + } + } + } + } + em.out +} + +/// Ein Körper eines Bands im layered-Pfad: Öffnungs-Löcher auf den Körper-Start umrechnen (an der +/// innersten Schicht mit Laibungs-Rücksprung geweitet); schräge Oberkante mit Löchern geht in +/// render3d nicht → gestuft annähern. +#[allow(clippy::too_many_arguments)] +fn emit_band_piece(em: &mut Emitter, li: usize, off: f64, cutouts: &[OpeningIn], innermost: bool, recess: f64, a: f64, bb: f64, zb: f64, zt_start: f64, zt_end: f64) { + let zt = zt_start.max(zt_end); + let holes: Vec<[f64; 4]> = cutouts + .iter() + .filter(|h| h.z_top > zb + EPS && h.z_bottom < zt - EPS) + .map(|h| { + if innermost && h.recess_inner_layer { + [h.from - a - recess, h.to - a + recess, h.z_bottom - recess, h.z_top + recess] + } else { + [h.from - a, h.to - a, h.z_bottom, h.z_top] + } + }) + .collect(); + if !holes.is_empty() && (zt_start - zt_end).abs() > EPS { + let k = 1usize.max(((bb - a) / ROOF_CLIP_STEP).ceil() as usize); + for i in 0..k { + let sa = a + ((bb - a) * i as f64) / k as f64; + let sb = a + ((bb - a) * (i + 1) as f64) / k as f64; + let zm = zt_start + ((zt_end - zt_start) * (i as f64 + 0.5)) / k as f64; + emit_band_piece(em, li, off, cutouts, innermost, recess, sa, sb, zb, zm, zm); + } + return; + } + em.push(li, a, bb, zb, zt, off, holes, [zt - zt_start, zt - zt_end]); +} + +// ── Flache Kodierung ───────────────────────────────────────────────────────── +// +// Geschosse: [nGeschosse, (nDecken, (zBottom, zTop, nPkt, (x, y)…, typOk, nSchichten, +// (dicke, prio|NaN)…)…, nDächer, (traufZ, schichtdicke, nPkt, (x, y)…, nFlächen, +// (m, (x, y, z)…)…)…)…] +// Wände: [nWände, (geschoss, sx, sy, ex, ey, zBottom, zTop, layered, stacked, refKind, refValue, +// dickeHülle, terminierung (0 beide, 1 unten, 2 oben), nBänder, (dicke, prio|NaN)…, +// nÖffnungen, (from, to, zBottom, zTop, rücksprung)…, )…] +// geschoss: Index in die Geschosse (ausserhalb = ohne Decken/Dächer). +// Ausgabe: [nWände, (nKörper, (band, x1, y1, x2, y2, zBottom, zTop, schräg 0/1, drop0, drop1, +// nLöcher, (from, to, zBottom, zTop)…)…)…] — nWände < Eingabe, wenn der Puffer mittendrin +// kaputt ist; eine Wand mit ungültigen Werten (NaN …) hat keine Körper. + +use crate::flat_read::Reader; + +fn fin(v: &[f64]) -> bool { + v.iter().all(|x| x.is_finite()) +} + +/// Liest die Decken und Dächer eines Geschosses; einzelne ungültige fallen weg. +fn decode_context(r: &mut Reader) -> Option { + let nc = r.count()?; + let mut ceilings = Vec::with_capacity(nc.min(1 << 12)); + for _ in 0..nc { + let (czb, czt) = (r.num()?, r.num()?); + let outline = r.ring()?; + let type_ok = r.num()? != 0.0; + let nl = r.count()?; + let mut layers = Vec::with_capacity(nl.min(1 << 10)); + let mut ok = fin(&[czb, czt]) && outline.iter().all(|p| fin(p)); + for _ in 0..nl { + let (t, p) = (r.num()?, r.num()?); + ok &= t.is_finite() && !p.is_infinite(); + layers.push((t, (!p.is_nan()).then_some(p))); + } + if ok { + let outline = outline.into_iter().map(|p| Vec2::new(p[0], p[1])).collect(); + ceilings.push(CeilingIn { z_bottom: czb, z_top: czt, outline, layers: type_ok.then_some(layers) }); + } + } + let nr = r.count()?; + let mut roofs = Vec::with_capacity(nr.min(1 << 12)); + for _ in 0..nr { + let (ez, total) = (r.num()?, r.num()?); + let eaves = r.ring()?; + let np = r.count()?; + let mut planes = Vec::with_capacity(np.min(1 << 12)); + for _ in 0..np { + let m = r.count()?; + planes.push(r.points3(m)?); + } + if fin(&[ez, total]) && eaves.iter().all(|p| fin(p)) && planes.iter().flatten().all(|p| fin(p)) { + roofs.push(RoofIn { eaves_z: ez, total_thickness: total, eaves, planes }); + } + } + Some(FloorContext::new(ceilings, roofs)) +} + +/// Liest eine Wand: `None` = Puffer kaputt (Abbruch), `Some((geschoss, None))` = Werte ungültig. +fn decode_wall(r: &mut Reader) -> Option<(f64, Option)> { + let floor = r.num()?; + let (sx, sy, ex, ey, zb, zt) = (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?); + let (layered, stacked, kind, value, thick, term) = (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?); + let mut ok = fin(&[sx, sy, ex, ey, zb, zt, thick]); + let reference = match kind as i64 { + 1 => Reference::Left, + 2 => Reference::Right, + 3 => { + ok &= value.is_finite(); + Reference::Offset(value) + } + _ => Reference::Center, + }; + let termination = match term as i64 { + 1 => Termination::Below, + 2 => Termination::Above, + _ => Termination::Both, + }; + let nb = r.count()?; + let mut bands = Vec::with_capacity(nb.min(1 << 10)); + for _ in 0..nb { + let (t, p) = (r.num()?, r.num()?); + ok &= t.is_finite() && !p.is_infinite(); + bands.push(BandIn { thickness: t, priority: (!p.is_nan()).then_some(p) }); + } + let no = r.count()?; + let mut openings = Vec::with_capacity(no.min(1 << 12)); + for _ in 0..no { + let o = [r.num()?, r.num()?, r.num()?, r.num()?]; + let recess = r.num()? != 0.0; + ok &= fin(&o); + openings.push(OpeningIn { from: o[0], to: o[1], z_bottom: o[2], z_top: o[3], recess_inner_layer: recess }); + } + let cuts = crate::joins::decode_cuts(r)?; + let wall = WallIn { + start: Vec2::new(sx, sy), + end: Vec2::new(ex, ey), + z_bottom: zb, + z_top: zt, + layered: layered != 0.0, + stacked: stacked != 0.0, + reference, + thickness_safe: thick, + termination, + bands, + openings, + cuts, + }; + Some((floor, ok.then_some(wall))) +} + +fn encode_pieces(out: &mut Vec, pieces: &[Piece]) { + out.push(pieces.len() as f64); + for p in pieces { + out.extend([p.band as f64, p.start.x, p.start.y, p.end.x, p.end.y, p.z_bottom, p.z_top]); + match p.top_drop { + Some([d0, d1]) => out.extend([1.0, d0, d1]), + None => out.extend([0.0, 0.0, 0.0]), + } + out.push(p.holes.len() as f64); + for h in &p.holes { + out.extend(h); + } + } +} + +/// Wände + Geschosse flach → Körper je Wand flach (s. Kodierung oben); nie ein Panic. +pub fn wall_bands_flat(walls: &[f64], floors: &[f64]) -> Vec { + let mut fr = Reader::new(floors); + let mut contexts = Vec::new(); + if let Some(n) = fr.count() { + for _ in 0..n { + match decode_context(&mut fr) { + Some(c) => contexts.push(c), + None => break, + } + } + } + let empty = FloorContext::default(); + let mut out = vec![0.0]; + let mut r = Reader::new(walls); + let Some(n) = r.count() else { return out }; + let mut done = 0usize; + for _ in 0..n { + let Some((floor, wall)) = decode_wall(&mut r) else { break }; + let ctx = if floor >= 0.0 && floor.fract() == 0.0 { contexts.get(floor as usize).unwrap_or(&empty) } else { &empty }; + let pieces = wall.map(|w| wall_bands(&w, ctx)).unwrap_or_default(); + encode_pieces(&mut out, &pieces); + done += 1; + } + out[0] = done as f64; + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::joins::{compute_joins, JoinLayer, JoinWall, SpanCutout}; + + fn base(start: (f64, f64), end: (f64, f64), bands: Vec) -> WallIn { + WallIn { + start: Vec2::new(start.0, start.1), + end: Vec2::new(end.0, end.1), + z_bottom: 0.0, + z_top: 2.6, + layered: true, + stacked: true, + reference: Reference::Center, + thickness_safe: bands.iter().map(|b| b.thickness).sum(), + termination: Termination::Both, + bands, + openings: vec![], + cuts: WallCuts::default(), + } + } + fn band(t: f64, p: f64) -> BandIn { + BandIn { thickness: t, priority: Some(p) } + } + fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 + } + fn bands_of(w: &WallIn) -> Vec { + wall_bands(w, &FloorContext::default()) + } + /// Achsen-Länge eines Körpers. + fn plen(p: &Piece) -> f64 { + js_hypot(p.end.x - p.start.x, p.end.y - p.start.y) + } + + #[test] + fn schichten_gestapelt_und_referenzversetzt() { + let mut w = base((0.0, 0.0), (4.0, 0.0), vec![band(0.1, 10.0), band(0.2, 50.0)]); + let p = bands_of(&w); + assert_eq!(p.len(), 2); + assert!(close(p[0].start.y, -0.1) && close(p[1].start.y, 0.05)); + w.reference = Reference::Left; // Stapel um die halbe Dicke nach +n verschoben + let p = bands_of(&w); + assert!(close(p[0].start.y, 0.05) && close(p[1].start.y, 0.2)); + } + + #[test] + fn l_ecke_kuerzt_und_verlaengert_je_band() { + let jw = |s: (f64, f64), e: (f64, f64)| JoinWall { + start: Vec2::new(s.0, s.1), + end: Vec2::new(e.0, e.1), + reference: Reference::Center, + layers: Some(vec![JoinLayer { thickness: 0.1, component: Some(0), priority: 10.0 }, JoinLayer { thickness: 0.2, component: Some(1), priority: 50.0 }]), + }; + let cuts = compute_joins(&[jw((0.0, 0.0), (4.0, 0.0)), jw((4.0, 0.0), (4.0, 3.0))]).unwrap(); + let mut w = base((0.0, 0.0), (4.0, 0.0), vec![band(0.1, 10.0), band(0.2, 50.0)]); + w.cuts = cuts[0].clone(); + let p = bands_of(&w); + // Gehrung: das aussen liegende Band (−n, unten) ist länger als das innere. + assert!(close(p[0].end.x, 4.0 + 0.1) && close(p[1].end.x, 4.0 - 0.05), "{p:?}"); + assert!(close(p[0].start.x, 0.0)); + } + + #[test] + fn t_stoss_aussparung_bricht_band_auf() { + let mut w = base((0.0, 0.0), (6.0, 0.0), vec![band(0.02, 10.0), band(0.15, 50.0), band(0.015, 10.0)]); + w.cuts.span_cutouts.push(SpanCutout { from: 2.0, to: 2.15, off_a: 0.0925, off_b: 0.0775 }); + let p = bands_of(&w); + // Aussenputz und Kern durchgehend, Innenputz (Band 2) in zwei Stücken. + assert_eq!(p.iter().filter(|q| q.band == 2).count(), 2); + assert_eq!(p.iter().filter(|q| q.band == 1).count(), 1); + } + + #[test] + fn oeffnung_am_rand_und_ruecksprung() { + let mut w = base((0.0, 0.0), (3.0, 0.0), vec![band(0.15, 50.0), band(0.02, 10.0)]); + w.openings.push(OpeningIn { from: 0.0, to: 0.9, z_bottom: 0.0, z_top: 2.1, recess_inner_layer: false }); + w.openings.push(OpeningIn { from: 2.0, to: 3.0, z_bottom: 0.9, z_top: 2.1, recess_inner_layer: true }); + let p = bands_of(&w); + assert_eq!(p.len(), 2); + assert_eq!(p[0].holes.len(), 2); + assert_eq!(p[0].holes[1], [2.0, 3.0, 0.9, 2.1]); + let r = p[1].holes[1]; + assert!(close(r[0], 1.98) && close(r[1], 3.02) && close(r[2], 0.88) && close(r[3], 2.12)); + // Schnitt-Pfad: Pfeiler/Brüstung/Sturz ohne Löcher. + w.layered = false; + w.stacked = false; + w.bands = vec![BandIn { thickness: 0.17, priority: None }]; + let s = bands_of(&w); + // Sturz Tür, Pfeiler, Brüstung + Sturz Fenster (Tür bis zum Rand: kein Pfeiler davor). + assert_eq!(s.len(), 4, "{s:?}"); + assert!(s.iter().all(|q| q.holes.is_empty() && q.top_drop.is_none())); + } + + #[test] + fn decke_hoeherer_prioritaet_schneidet_nur_schwache_baender() { + let mut w = base((0.0, 0.0), (4.0, 0.0), vec![band(0.15, 50.0), band(0.02, 10.0)]); + w.z_top = 3.0; + let outline = vec![Vec2::new(-1.0, -1.0), Vec2::new(5.0, -1.0), Vec2::new(5.0, 5.0), Vec2::new(-1.0, 5.0)]; + let ctx = FloorContext::new(vec![CeilingIn { z_bottom: 2.6, z_top: 2.8, outline, layers: Some(vec![(0.2, Some(30.0))]) }], vec![]); + let p = wall_bands(&w, &ctx); + assert_eq!(p.iter().filter(|q| q.band == 0).count(), 1); // Kern (50) läuft durch + let weak: Vec<_> = p.iter().filter(|q| q.band == 1).collect(); + assert_eq!(weak.len(), 2); + assert!(close(weak[0].z_top, 2.6) && close(weak[1].z_bottom, 2.8)); + // Terminierung „below": endet an der Deckenunterkante, kein Rest darüber. + w.termination = Termination::Below; + let p = wall_bands(&w, &ctx); + assert_eq!(p.iter().filter(|q| q.band == 1).count(), 1); + } + + #[test] + fn wand_unter_pultdach_bekommt_schraege_oberkante() { + let mut w = base((0.0, 0.0), (4.0, 0.0), vec![band(0.2, 50.0)]); + w.z_top = 5.0; + // Ebene z = 2 + 0.5·x über [−1, 5]². + let plane = vec![[-1.0, -1.0, 1.5], [5.0, -1.0, 4.5], [5.0, 5.0, 4.5], [-1.0, 5.0, 1.5]]; + let roof = RoofIn { eaves_z: 1.5, total_thickness: 0.0, eaves: plane.iter().map(|p| [p[0], p[1]]).collect(), planes: vec![plane] }; + let ctx = FloorContext::new(vec![], vec![roof]); + let p = wall_bands(&w, &ctx); + assert_eq!(p.len(), 1, "{p:?}"); + let d = p[0].top_drop.unwrap(); + // Abtastung 1 mm innerhalb der Enden (wie TS) → Toleranz 1e-3. + let near = |a: f64, b: f64| (a - b).abs() < 1e-3; + assert!(near(p[0].z_top, 4.0) && near(d[0], 2.0) && d[1] == 0.0, "{p:?}"); + // Mit Öffnung: gestuft, ohne top_drop. + w.openings.push(OpeningIn { from: 1.0, to: 2.0, z_bottom: 0.0, z_top: 2.0, recess_inner_layer: false }); + let p = wall_bands(&w, &ctx); + assert!(p.len() > 10 && p.iter().all(|q| q.top_drop.is_none())); + let total: f64 = p.iter().map(plen).sum(); + assert!(close(total, 4.0)); + } + + #[test] + fn unsinn_ohne_panic() { + assert_eq!(wall_bands_flat(&[], &[]), vec![0.0]); + assert_eq!(wall_bands_flat(&[f64::NAN; 40], &[f64::NAN]), vec![0.0]); + assert_eq!(wall_bands_flat(&[0.0; 3], &[1.0, 5.0]), vec![0.0]); + // Nulllänge, umgekehrte Höhen, Öffnung ausserhalb, Bänder ohne Dicke, entartete Decke/Dach. + let mut w = base((1.0, 1.0), (1.0, 1.0), vec![band(0.2, 50.0)]); + assert!(bands_of(&w).is_empty()); + w.end = Vec2::new(2.0, 1.0); + w.z_top = -1.0; + assert!(bands_of(&w).is_empty()); + w.z_top = 2.0; + w.openings.push(OpeningIn { from: 5.0, to: -3.0, z_bottom: 9.0, z_top: -9.0, recess_inner_layer: true }); + w.bands.push(band(0.0, 1.0)); + let ctx = FloorContext::new( + vec![CeilingIn { z_bottom: 0.5, z_top: 0.5, outline: vec![Vec2::new(0.0, 0.0); 3], layers: Some(vec![]) }], + vec![RoofIn { eaves_z: 0.0, total_thickness: 0.0, eaves: vec![], planes: vec![vec![]] }], + ); + let _ = wall_bands(&w, &ctx); + + // Flach: zwei Wände (die zweite mit NaN-Koordinate → keine Körper), ein Geschoss. + let wall = |x: f64| { + let mut b = vec![0.0, x, 1.0, 2.0, 1.0, 0.0, 2.0, 1.0, 1.0, 0.0, 0.0, 0.2, 0.0, 1.0, 0.2, 50.0, 0.0]; + crate::joins::encode_cuts(&mut b, &WallCuts::default()); + b + }; + let mut buf = vec![2.0]; + buf.extend(wall(1.0)); + buf.extend(wall(f64::NAN)); + let floors = [1.0, 0.0, 0.0]; + let out = wall_bands_flat(&buf, &floors); + assert_eq!(out[0], 2.0); + assert_eq!(out[1], 1.0); // ein Körper + assert_eq!(*out.last().unwrap(), 0.0); // zweite Wand: keine Körper + // Abgeschnittener Puffer: nur die vollständige erste Wand. + assert_eq!(wall_bands_flat(&buf[..buf.len() - 1], &floors)[0], 1.0); + // Kaputte Geschosse: Wände ohne Decken/Dächer. + assert_eq!(wall_bands_flat(&buf, &[3.0, 1.0])[0], 2.0); + } +} diff --git a/src-tauri/core/src/web/joins.rs b/src-tauri/core/src/web/joins.rs new file mode 100644 index 00000000..4c68f0ae --- /dev/null +++ b/src-tauri/core/src/web/joins.rs @@ -0,0 +1,22 @@ +//! Bindungen der Wand-Verschneidung (`crate::joins`). Kodierung s. dort. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Wände flach → `[0, (Cuts je Wand)…]`; `[1, wandIndex]` = Wandtyp/Bauteil unbekannt; +/// kaputte Eingabe → leer. +#[wasm_bindgen] +pub fn compute_joins_flat(walls: &[f64]) -> Vec { + crate::joins::compute_joins_flat(walls) +} + +/// Verschneidungs-Entscheidung: 0 merge, 1 trim-a, 2 trim-b, 3 coexist. +#[wasm_bindgen] +pub fn join_priority_resolution(prio_a: f64, prio_b: f64, same_component: bool) -> u8 { + use crate::joins::JoinResolution::*; + match crate::joins::resolve_join_priority(prio_a, prio_b, same_component) { + Merge => 0, + TrimA => 1, + TrimB => 2, + Coexist => 3, + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 0581d961..405fd94d 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -10,6 +10,8 @@ mod sun; mod site_rules; mod auto_dimensions; mod kennzahlen; +mod joins; +mod wall_bands; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/wall_bands.rs b/src-tauri/core/src/web/wall_bands.rs new file mode 100644 index 00000000..8f201d85 --- /dev/null +++ b/src-tauri/core/src/web/wall_bands.rs @@ -0,0 +1,9 @@ +//! Bindungen der Wand-Schichtbänder (`crate::wall_bands`). Kodierung s. dort. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Wände + Geschosse (Decken, Dächer) flach → Körper je Wand flach; nie ein Panic. +#[wasm_bindgen] +pub fn wall_bands_flat(walls: &[f64], floors: &[f64]) -> Vec { + crate::wall_bands::wall_bands_flat(walls, floors) +} diff --git a/src/geometry/roof.ts b/src/geometry/roof.ts index 296d7c3a..22fc7a8c 100644 --- a/src/geometry/roof.ts +++ b/src/geometry/roof.ts @@ -159,6 +159,12 @@ export function roofUndersideAt( x: number, y: number, ): number | null { + const z = core().roof_underside_at(roofPlanesFlat(geo), totalLayerThickness, x, y); + return Number.isNaN(z) ? null : z; +} + +/** Dachflächen als flacher Puffer `[n, (m, (x, y, z)…)…]` (Kodierung `roof.rs`), je Geometrie gemerkt. */ +export function roofPlanesFlat(geo: RoofGeometry): Float64Array { let flat = planesFlat.get(geo); if (!flat) { const vals = [geo.planes.length]; @@ -169,6 +175,5 @@ export function roofUndersideAt( flat = Float64Array.from(vals); planesFlat.set(geo, flat); } - const z = core().roof_underside_at(flat, totalLayerThickness, x, y); - return Number.isNaN(z) ? null : z; + return flat; } diff --git a/src/model/joins.ts b/src/model/joins.ts index 921ea58b..b74fecf8 100644 --- a/src/model/joins.ts +++ b/src/model/joins.ts @@ -1,22 +1,16 @@ // Wand-Verschneidung (Gehrung): an einer Ecke, wo zwei Wände aufeinander­ // treffen, sollen sich die Schicht-Bänder nicht überlappen, sondern an einer -// gemeinsamen Gehrungslinie sauber stoßen. Dieses Modul berechnet pro Wand -// die optionalen Schnittlinien an Start- und Endpunkt. +// gemeinsamen Gehrungslinie sauber stoßen. Pro Wand entstehen die optionalen +// Schnittlinien an Start- und Endpunkt. +// +// Gerechnet wird im Rust-Kern (`src-tauri/core/src/joins.rs`); hier bleiben die +// Typen, das Sammeln der Wand-Angaben aus dem `Project` und die flache Übergabe. -import type { Component, Project, Vec2, Wall } from "./types"; -import { getComponent, getWallType, wallTypeThickness } from "./types"; -import { wallReferenceOffset } from "./wall"; -import { - add, - dot, - leftNormal, - len, - lineIntersect, - normalize, - scale, - sub, -} from "./geometry"; +import type { Component, Project, Wall } from "./types"; +import { getComponent, getWallType } from "./types"; import type { Line } from "./geometry"; +import { core } from "../engine/coreWasm"; +import { FlatReader, FlatWriter } from "../geometry/coreFlat"; /** * Pro-Schicht-Override der Nahflächen-Cuts (materialbewusster T-Stoss, siehe @@ -89,25 +83,13 @@ export interface WallCuts { */ export type JoinPriorityResolution = "merge" | "trim-a" | "trim-b" | "coexist"; +const RESOLUTIONS: JoinPriorityResolution[] = ["merge", "trim-a", "trim-b", "coexist"]; + export function resolveJoinPriority( a: Component, b: Component, ): JoinPriorityResolution { - if (a.joinPriority === b.joinPriority) { - return a.id === b.id ? "merge" : "coexist"; - } - return a.joinPriority > b.joinPriority ? "trim-b" : "trim-a"; -} - -/** Rundet eine Koordinate auf ein Gitter, um Endpunkte robust zu gruppieren. */ -const roundKey = (p: Vec2): string => { - const r = (v: number) => Math.round(v * 1e4) / 1e4; - return `${r(p.x)},${r(p.y)}`; -}; - -interface WallEnd { - wallId: string; - end: "start" | "end"; + return RESOLUTIONS[core().join_priority_resolution(a.joinPriority, b.joinPriority, a.id === b.id)] ?? "coexist"; } /** @@ -116,470 +98,99 @@ interface WallEnd { * (drei Wandenden treffen sich, zwei davon kollinear), Mittelspannen-T-Stöße * (ein freies Wandende trifft auf die Seite einer anderen Wand) UND „+"- * Kreuzungen (zwei kollineare Wandenden treffen sich exakt auf der Achse einer - * dritten, durchlaufenden Wand — z. B. wenn eine durchgehende Trennwand von - * einer weiteren durchgehenden Wand gekreuzt wird). Nur echte Stern-Knoten - * (vier oder mehr Wand-STUMMEL enden alle exakt am selben Punkt, OHNE dass - * eine von ihnen als Durchgang erkennbar ist) bleiben rechtwinklig — dafür - * fehlt eine eindeutige Rangfolge, welches Ende „durch" und welches „Abzweig" - * wäre. + * dritten, durchlaufenden Wand). Echte Stern-Knoten (vier oder mehr Wand- + * STUMMEL am selben Punkt, keiner als Durchgang erkennbar) bleiben rechtwinklig. + * An T-Stössen kommen die materialbewussten Pro-Schicht-Cuts (`layerCuts`) und + * die Nah-Putz-Aussparungen der Durchgangswand (`spanCutouts`) dazu. * * `walls` ist die bereits gefilterte Wandmenge (z. B. ein Geschoss); die - * Gehrung wird nur innerhalb dieser Menge gebildet. + * Gehrung wird nur innerhalb dieser Menge gebildet. Wirft wie früher, wenn ein + * benötigter Wandtyp oder ein Bauteil unbekannt ist. */ export function computeJoins( project: Project, walls: Wall[], ): Map { - const byId = new Map(walls.map((w) => [w.id, w])); - + const w = new FlatWriter().num(walls.length); + const compIndex = new Map(); + for (const wall of walls) { + w.num(wall.start.x, wall.start.y, wall.end.x, wall.end.y); + if (wall.referenceOffset != null) w.num(3, wall.referenceOffset); + else w.num(wall.referenceLine === "left" ? 1 : wall.referenceLine === "right" ? 2 : 0, 0); + const wt = project.wallTypes.find((t) => t.id === wall.wallTypeId); + if (!wt) { + w.num(0, 0); + continue; + } + w.num(1, wt.layers.length); + for (const l of wt.layers) { + const comp = project.components.find((c) => c.id === l.componentId); + let idx = -1; + if (comp) { + idx = compIndex.get(comp.id) ?? compIndex.size; + compIndex.set(comp.id, idx); + } + w.num(l.thickness, idx, comp ? comp.joinPriority : Number.NaN); + } + } + const out = core().compute_joins_flat(w.done()); + const r = new FlatReader(out); + const status = r.num(); + if (status === 1) { + // Wandtyp oder Bauteil unbekannt: denselben Fehler werfen wie die Modell-Helfer. + const bad = walls[r.num()]; + if (bad) for (const l of getWallType(project, bad).layers) getComponent(project, l.componentId); + throw new Error("computeJoins: unbekannter Wandtyp oder Bauteil"); + } const result = new Map(); - for (const w of walls) result.set(w.id, { startCut: null, endCut: null }); - - // Knotenkarte: gerundeter Endpunkt → Liste der dort endenden Wandenden. - const junctions = new Map(); - const push = (p: Vec2, we: WallEnd) => { - const key = roundKey(p); - const list = junctions.get(key); - if (list) list.push(we); - else junctions.set(key, [we]); - }; - for (const w of walls) { - push(w.start, { wallId: w.id, end: "start" }); - push(w.end, { wallId: w.id, end: "end" }); + if (status !== 0) { + // Kaputte Eingabe (z. B. NaN-Koordinaten): keine Verschneidung. + for (const wall of walls) result.set(wall.id, { startCut: null, endCut: null }); + return result; } - - for (const [, ends] of junctions) { - // Freies Ende → kein Schnitt hier (wird unten separat auf Mittelspannen-T - // geprüft, Fall 2). - if (ends.length === 1) continue; - - if (ends.length === 2) { - const a = byId.get(ends[0].wallId)!; - const b = byId.get(ends[1].wallId)!; - const cut = miterLine(project, a, ends[0].end, b); - if (!cut) continue; // kollinear → kein Schnitt - - setCut(result, ends[0], cut); - setCut(result, ends[1], cut); - continue; - } - - if (ends.length === 3) { - applyTJunction(project, byId, ends, result); - continue; - } - - // Echte Stern-Knoten (≥4 WANDENDEN treffen sich exakt hier, KEINS läuft - // als Durchgangswand weiter) bleiben vorerst rechtwinklig (Folge-Arbeit) — - // dafür gibt es (noch) keine eindeutige Rangfolge, welches Ende „durch" - // und welches „Abzweig" ist. Der weit häufigere Fall — eine durchlaufende - // Wand wird von zwei (oder mehr) an ihrem Knoten endenden Wänden gekreuzt, - // eine „+"/„X"-Kreuzung — greift unten in Fall 2, weil dort JEDES noch - // ungeschnittene Ende zusätzlich gegen die Mittelspanne aller anderen - // Wände geprüft wird (nicht nur echte Einzel-Enden wie bisher). - } - - // Fall 2: Mittelspannen-T-Stoß, verallgemeinert. Jedes Wandende, das nach - // Fall 1 noch UNGESCHNITTEN ist — das schliesst nicht nur echte Einzel-Enden - // ein, sondern auch die beiden kollinearen Hälften eines 2er-/3er-Knotens - // (die bewusst ungeschnitten bleiben, s. o.) —, wird zusätzlich geprüft, ob - // es auf die Mittelspanne (nicht das Ende) einer WEITEREN, an diesem Knoten - // gar nicht beteiligten Wand trifft. Das deckt genau die „+"-Kreuzung ab: - // zwei kollineare Wandhälften enden an einem Punkt, DURCH den eine dritte, - // durchlaufende Wand hindurchläuft (sonst für Fall 1 unsichtbar, weil sie - // dort keinen eigenen Endpunkt hat) — beide Hälften bekommen unabhängig - // voneinander (mit jeweils eigenem Vorzeichen/zugewandter Fläche) einen - // Schnitt gegen die durchlaufende Wand, die selbst unangetastet bleibt. - // Bereits geschnittene Enden (L-Ecke, T-Abzweig) werden NICHT erneut - // angefasst — additiv, bit-identisch zum bisherigen Verhalten überall sonst. - for (const [, ends] of junctions) { - for (const end of ends) { - const cuts = result.get(end.wallId)!; - if (end.end === "start" ? cuts.startCut : cuts.endCut) continue; - applyMidSpanTee(project, byId, walls, end, result); - } - } - + for (const wall of walls) result.set(wall.id, readWallCuts(r)); return result; } -/** Trägt eine Schnittlinie am passenden Ende einer Wand ein. */ -function setCut(result: Map, we: WallEnd, cut: Line): void { - const cuts = result.get(we.wallId)!; - if (we.end === "start") cuts.startCut = cut; - else cuts.endCut = cut; +// ── Flache Kodierung der Cuts (s. `joins.rs`), auch für `toWalls3d/bands.ts` ── + +function writeLine(w: FlatWriter, l: Line | null | undefined): void { + if (l) w.num(1, l.point.x, l.point.y, l.dir.x, l.dir.y); + else w.num(0, 0, 0, 0, 0); } -/** Achsrichtung start→end, normalisiert. */ -const dirOf = (w: Wall): Vec2 => normalize(sub(w.end, w.start)); - -/** - * Gemeinsame Gehrungslinie zweier Wände A, B, die sich im Knoten J treffen. - * Robust gegen beliebige Wicklung, ungleiche Dicken und JEDEN Öffnungswinkel - * (inkl. spitzer): Die Wandflächen werden orientierungsbasiert (vorzeichen­ - * richtig) gepaart — A's Außenfläche verschneidet B's Außenfläche zum äußeren - * Apex, A's Innenfläche B's Innenfläche zum inneren Apex. „Außen" ist jeweils - * die vom Körper der anderen Wand ABGEWANDTE Fläche. Die Gerade durch beide - * Apexe ist die Gehrung; sie trennt beide Wandbänder überlappungsfrei. - * - * Die frühere Distanz-Heuristik („nächstgelegene B-Fläche") kippt bei spitzen - * Winkeln — dort wird die falsche Fläche zur näheren, sodass Außen mit Innen - * gepaart wird und die Poché-Bänder sich kreuzweise überlappen. - */ -function miterLine( - project: Project, - a: Wall, - aEnd: "start" | "end", - b: Wall, -): Line | null { - const j = aEnd === "start" ? a.start : a.end; - - const tA = wallTypeThickness(getWallType(project, a)); - const tB = wallTypeThickness(getWallType(project, b)); - const uA = dirOf(a); - const uB = dirOf(b); - const nA = leftNormal(uA); - const nB = leftNormal(uB); - - // Referenzlinien-Versatz: liegt die Achse nicht mittig, sind die beiden - // Wandflächen um diesen Betrag entlang +n verschoben (außen −T/2+off, innen - // +T/2+off). Für „center" (Default) ist off=0 → unverändert. - const offA = wallReferenceOffset(a, tA); - const offB = wallReferenceOffset(b, tB); - - // Flächen-Stützpunkte am Knoten: linke Fläche liegt auf +n, rechte auf −n - // (inkl. Referenzversatz). - const pLA = add(j, scale(nA, offA + tA / 2)); - const pRA = add(j, scale(nA, offA - tA / 2)); - const pLB = add(j, scale(nB, offB + tB / 2)); - const pRB = add(j, scale(nB, offB - tB / 2)); - - // Auslauf-Richtungen der Achsen vom Knoten weg, in den jeweiligen Wandkörper. - const dA = aEnd === "start" ? uA : scale(uA, -1); - const bAtStart = len(sub(b.start, j)) <= len(sub(b.end, j)); - const dB = bAtStart ? uB : scale(uB, -1); - - // Orientierungsbasierte, vorzeichenrichtige Flächen-Paarung. „Außen" ist die - // vom Körper der anderen Wand ABGEWANDTE Fläche: A's +nA-Fläche (pLA) liegt - // außen, wenn nA·dB < 0; B's +nB-Fläche (pLB) außen, wenn nB·dA < 0. Gepaart - // wird Außen-mit-Außen und Innen-mit-Innen — nie über Kreuz. (nA·dB = 0 tritt - // nur bei kollinearen Achsen auf; dann sind die Flächen parallel und - // lineIntersect liefert unten ohnehin null.) - const bOuter = dot(nB, dA) < 0 ? pLB : pRB; - const bInner = dot(nB, dA) < 0 ? pRB : pLB; - const aLeftIsOuter = dot(nA, dB) < 0; - const bForLeft = aLeftIsOuter ? bOuter : bInner; - const bForRight = aLeftIsOuter ? bInner : bOuter; - - // c1 an A's linke Fläche (pLA), c2 an A's rechte (pRA) gebunden — Reihenfolge - // wie zuvor, damit rechte/stumpfe Ecken bit-identisch bleiben; nur die - // B-Partnerwahl ist jetzt orientierungs- statt distanzbasiert. - const c1 = lineIntersect(pLA, uA, bForLeft, uB); - const c2 = lineIntersect(pRA, uA, bForRight, uB); - if (!c1 || !c2) return null; - - const dir = sub(c2, c1); - if (len(dir) < 1e-9) return null; - return { point: c1, dir }; +function readLine(r: FlatReader): Line | null { + const set = r.num(); + const point = { x: r.num(), y: r.num() }; + const dir = { x: r.num(), y: r.num() }; + return set === 1 ? { point, dir } : null; } -/** - * Fall 1 — T-Knoten: drei Wandenden treffen sich im selben (gerundeten) - * Knoten. Typisch sind zwei davon kollinear (die zwei Hälften der - * Durchgangswand, die geometrisch als eine Achse durchläuft) und das dritte - * zweigt ab. Die kollinearen zwei bleiben ungeschnitten; der Abzweig bekommt - * einen Schnitt entlang der ihm zugewandten Fläche der Durchgangswand. - * Findet sich kein eindeutig kollineares Paar (z. B. echter Y-/X-Knoten), - * bleibt der Knoten unangetastet (rechtwinklig). - */ -function applyTJunction( - project: Project, - byId: Map, - ends: WallEnd[], - result: Map, -): void { - const dirs = ends.map((e) => dirOf(byId.get(e.wallId)!)); - - // Suche das (näherungsweise) kollineare Paar: |cos(Winkel der Achsen)| ≈ 1. - let throughPair: [number, number] | null = null; - for (let i = 0; i < 3 && !throughPair; i++) { - for (let k = i + 1; k < 3; k++) { - if (1 - Math.abs(dot(dirs[i], dirs[k])) < 1e-6) { - throughPair = [i, k]; - break; - } - } - } - if (!throughPair) return; // kein eindeutiger Durchgang erkennbar - - const branchIdx = [0, 1, 2].find( - (i) => i !== throughPair![0] && i !== throughPair![1], - )!; - const branchEnd = ends[branchIdx]; - const throughEnd = ends[throughPair[0]]; - const branchWall = byId.get(branchEnd.wallId)!; - const throughWall = byId.get(throughEnd.wallId)!; - - const j = throughEnd.end === "start" ? throughWall.start : throughWall.end; - const tT = wallTypeThickness(getWallType(project, throughWall)); - const uT = dirOf(throughWall); - const nT = leftNormal(uT); - const offT = wallReferenceOffset(throughWall, tT); - - // Auslaufrichtung des Abzweigs vom Knoten weg, in seinen eigenen Körper - // (gleiche Konvention wie dA/dB in miterLine). - const dBranch = - branchEnd.end === "start" - ? dirOf(branchWall) - : scale(dirOf(branchWall), -1); - - // Zugewandte Fläche: die Seite der Durchgangsachse, zu der der Abzweig - // zeigt (positive nT-Seite, wenn der Abzweig dorthin ausläuft). - const sign = dot(nT, dBranch) >= 0 ? 1 : -1; - const facePoint = add(j, scale(nT, offT + sign * (tT / 2))); - const faceCut: Line = { point: facePoint, dir: uT }; - - setCut(result, branchEnd, faceCut); - applyLayerCuts(project, result, branchEnd, branchWall, throughWall, faceCut, j, uT, sign); +/** Hängt die Cuts einer Wand flach an (fehlend = keine Cuts). */ +export function writeWallCuts(w: FlatWriter, cuts: WallCuts | undefined): void { + writeLine(w, cuts?.startCut); + writeLine(w, cuts?.endCut); + const lc = cuts?.layerCuts; + const n = lc ? lc.start.length : 0; + w.num(n); + if (lc) for (const arr of [lc.start, lc.end, lc.startSide, lc.endSide]) for (let i = 0; i < n; i++) writeLine(w, arr[i]); + const sc = cuts?.spanCutouts ?? []; + w.num(sc.length); + for (const s of sc) w.num(s.from, s.to, s.offA, s.offB); } -/** - * Materialbewusste Pro-Schicht-Erweiterung eines T-Stoss-Cuts (siehe - * {@link resolveJoinPriority}): vergleicht jede Schicht der ABZWEIG-Wand mit - * dem Rückgrat (höchste `joinPriority`) der DURCHGANGSWAND. Verschmilzt eine - * Schicht (gleiche Komponente + Priorität wie das Rückgrat, oder die - * Abzweig-Schicht ist sogar prioritärer), bekommt sie einen Cut an der - * NAHFLÄCHE DES RÜCKGRAT-KERNS der Durchgangswand: der verschmelzende Abzweig- - * Kern (z. B. Backstein) sticht nur durch den Nah-Putz der Durchgangswand und - * stoppt am Durchgangs-Kern — er läuft NICHT bis zur Achse durch und überlappt - * die Durchgangswand nicht (dort verschmelzen die beiden Kerne nahtlos). - * Getrimmte Schichten, die direkt an eine verschmelzende Nachbarschicht - * grenzen, bekommen zusätzlich eine seitliche Cut-Linie an eben dieser - * Rückgrat-Nahfläche (L-Anschluss, z. B. Putz neben durchstechendem Kern). - * - * Setzt `WallCuts.layerCuts` NUR, wenn mindestens eine Schicht verschmilzt — - * sonst bleibt das Feld `undefined` (additiv, bit-identisches Default- - * Verhalten für den ganz überwiegenden Fall ohne Materialübereinstimmung). - * - * `sign` ist die Nahseite der Durchgangswand (der Abzweig-zugewandte `nT`- - * Vorzeichen, aus {@link applyTJunction}/{@link applyMidSpanTee}); er bestimmt, - * welche Durchgangswand-Schichten als Nah-Putz vor dem Rückgrat liegen. - */ -function applyLayerCuts( - project: Project, - result: Map, - branchEnd: WallEnd, - branchWall: Wall, - throughWall: Wall, - faceCut: Line, - axisPoint: Vec2, - throughDir: Vec2, - sign: number, -): void { - const branchWt = getWallType(project, branchWall); - const throughWt = getWallType(project, throughWall); - if (branchWt.layers.length === 0 || throughWt.layers.length === 0) return; - - // Rückgrat der Durchgangswand: die Schicht mit der höchsten joinPriority - // (Index mitgeführt, um die Nah-Putz-Dicke davor zu bestimmen). - let backbone = getComponent(project, throughWt.layers[0].componentId); - let backboneIdx = 0; - for (let i = 0; i < throughWt.layers.length; i++) { - const c = getComponent(project, throughWt.layers[i].componentId); - if (c.joinPriority > backbone.joinPriority) { - backbone = c; - backboneIdx = i; - } +/** Liest die Cuts einer Wand; `layerCuts`/`spanCutouts` nur, wenn vorhanden. */ +export function readWallCuts(r: FlatReader): WallCuts { + const cuts: WallCuts = { startCut: readLine(r), endCut: readLine(r) }; + const n = r.count(); + if (n > 0) { + const arr = () => Array.from({ length: n }, () => readLine(r)); + cuts.layerCuts = { start: arr(), end: arr(), startSide: arr(), endSide: arr() }; } - - const n = branchWt.layers.length; - const merged: boolean[] = new Array(n); - for (let i = 0; i < n; i++) { - const comp = getComponent(project, branchWt.layers[i].componentId); - const res = resolveJoinPriority(comp, backbone); - // "merge": identisches Rückgrat-Material -> durchgehender Kern. - // "trim-b": die Abzweig-Schicht ist SELBST prioritärer als das Rückgrat - // der Durchgangswand -> sie gewinnt ebenfalls und läuft durch (die - // Durchgangswand könnten wir hier nicht schneiden, ausserhalb des Scopes). - merged[i] = res === "merge" || res === "trim-b"; - } - if (!merged.some(Boolean)) return; // keine Materialübereinstimmung -> Default - - const cuts = result.get(branchWall.id)!; - if (!cuts.layerCuts) { - cuts.layerCuts = { - start: new Array(n).fill(null), - end: new Array(n).fill(null), - startSide: new Array(n).fill(null), - endSide: new Array(n).fill(null), - }; - } - const lc = cuts.layerCuts; - if (lc.start.length !== n) return; // Schicht-Anzahl passt nicht zusammen (sollte nicht vorkommen) - - const faceArr = branchEnd.end === "start" ? lc.start : lc.end; - const sideArr = branchEnd.end === "start" ? lc.startSide : lc.endSide; - - // Nahflächen-Cut des verschmelzenden Kerns: von der Durchgangswand-Nahfläche - // (`offT + sign·tT/2`) um die Nah-Putz-Dicke nach innen versetzt — also genau - // die dem Abzweig zugewandte Fläche des Rückgrat-Kerns. Nah-Putz = Summe der - // Durchgangswand-Schichten, die zwischen der Nahseite (sign) und dem Rückgrat - // liegen. Die Schichten stapeln entlang +nT (Index 0 = −tT/2); auf der - // +nT-Nahseite (sign>0) sind das die Schichten HINTER dem Rückgrat - // (Index > backboneIdx), auf der −nT-Nahseite die davor (Index < backboneIdx). - const tT = wallTypeThickness(throughWt); - const offT = wallReferenceOffset(throughWall, tT); - let nearPlaster = 0; - for (let i = 0; i < throughWt.layers.length; i++) { - if (sign > 0 ? i > backboneIdx : i < backboneIdx) - nearPlaster += throughWt.layers[i].thickness; - } - const nT = leftNormal(throughDir); - const mergePoint = add( - axisPoint, - scale(nT, offT + sign * (tT / 2 - nearPlaster)), - ); - const mergeCut: Line = { point: mergePoint, dir: throughDir }; - - // Getrimmte Nachbarschichten schließen mit ihrer L-Seitenlinie an eben dieser - // Rückgrat-Nahfläche (nicht an der Wandachse) — dort endet der Kern und die - // Nachbarschicht kappt ihre Breite. - const sideLine: Line = mergeCut; - - // Materialien des durchgehenden Nah-Putzes der Durchgangswand (dieselbe - // sign-Seite wie die nearPlaster-Summe oben). Ist die getrimmte Abzweig-Schicht - // materialgleich mit einer davon, füllt der Nah-Putz den Abzweig-Putz an dieser - // Stelle durchgehend (der spanCutout schneidet nur die KERN-Breite aus, nicht - // die schmalen Putzflanken) → Putz-L OHNE Trennnaht, also KEINE L-Seitenlinie. - const nearPlasterComps = new Set(); - for (let i = 0; i < throughWt.layers.length; i++) { - if (sign > 0 ? i > backboneIdx : i < backboneIdx) - nearPlasterComps.add(throughWt.layers[i].componentId); - } - - for (let i = 0; i < n; i++) { - faceArr[i] = merged[i] ? mergeCut : faceCut; - const adjMerged = - !merged[i] && ((i > 0 && merged[i - 1]) || (i < n - 1 && merged[i + 1])); - const mergesWithNearPlaster = nearPlasterComps.has(branchWt.layers[i].componentId); - sideArr[i] = adjMerged && !mergesWithNearPlaster ? sideLine : null; - } - - // Durchgangswand-Aussparung (Phase 1c): den Nah-Putz der Durchgangswand über - // die Breite des durchstechenden Abzweig-Kerns ECHT ausschneiden. Nur nötig, - // wenn davor überhaupt Nah-Putz liegt (nearPlaster > 0) — sonst schliesst der - // Kern flächenbündig an und es gibt nichts aufzubrechen. - if (nearPlaster > 1e-9) { - // Kernbreite des Abzweigs im Quer-Offset (Offset-Konvention der Bänder: - // gestapelt entlang leftNormal ab refOff − total/2). Die verschmelzenden - // Schichten (`merged`) bilden den Kern; Lo/Hi = ihre Offset-Hülle. - const totalBranch = wallTypeThickness(branchWt); - const refOffBranch = wallReferenceOffset(branchWall, totalBranch); - let bOff = refOffBranch - totalBranch / 2; - let coreLo = Infinity; - let coreHi = -Infinity; - for (let i = 0; i < n; i++) { - const th = branchWt.layers[i].thickness; - if (merged[i]) { - if (bOff < coreLo) coreLo = bOff; - if (bOff + th > coreHi) coreHi = bOff + th; - } - bOff += th; - } - if (coreHi > coreLo) { - // Projektion der Kern-Offsethülle auf die Durchgangsachse: der Achsenpunkt - // liegt bei `axisAt` (Meter ab Durchgangs-Start), ein Abzweig-Offset `o` - // verschiebt sich entlang der Achse um `o · (nBranch · uT)`. - const nBranch = leftNormal(dirOf(branchWall)); - const proj = dot(nBranch, throughDir); - const axisAt = dot(sub(axisPoint, throughWall.start), throughDir); - const e1 = axisAt + coreLo * proj; - const e2 = axisAt + coreHi * proj; - // Quer-Offsetbereich = Nah-Putz-Zone der Durchgangswand: Nahfläche (offA) - // bis Rückgrat-Nahfläche (offB, = mergeCut-Offset). Beide in derselben - // Offset-Konvention wie die Schicht-Bänder der Durchgangswand. - const offA = offT + sign * (tT / 2); - const offB = offT + sign * (tT / 2 - nearPlaster); - const throughCuts = result.get(throughWall.id); - if (throughCuts) { - (throughCuts.spanCutouts ??= []).push({ - from: Math.min(e1, e2), - to: Math.max(e1, e2), - offA, - offB, - }); - } - } + const m = r.count(); + if (m > 0) { + cuts.spanCutouts = []; + for (let k = 0; k < m; k++) cuts.spanCutouts.push({ from: r.num(), to: r.num(), offA: r.num(), offB: r.num() }); } -} - -/** - * Fall 2 — Mittelspannen-T-Stoß: prüft, ob das freie Wandende `freeEnd` auf - * die innere Spanne einer anderen Wand trifft (projizierter Parameter im - * Inneren, nicht an deren Endpunkten) und dabei senkrecht nah genug an deren - * Achse liegt (≤ halbe Dicke + Toleranz). Bei Treffer bekommt das freie Ende - * einen Schnitt entlang der zugewandten Fläche der getroffenen Wand; bei - * mehreren Treffern gewinnt die nächstliegende Wand. - */ -function applyMidSpanTee( - project: Project, - byId: Map, - walls: Wall[], - freeEnd: WallEnd, - result: Map, -): void { - const freeWall = byId.get(freeEnd.wallId)!; - const p = freeEnd.end === "start" ? freeWall.start : freeWall.end; - - const endGap = 1e-4; // Mindestabstand zu den Wandenden für „innere Spanne" - const tol = 1e-3; // Toleranz für den senkrechten Abstand zur Wandfläche - - let best: { wall: Wall; perp: number; dist: number; distAlong: number } | null = null; - for (const w of walls) { - if (w.id === freeWall.id) continue; - const u = dirOf(w); - const wLen = len(sub(w.end, w.start)); - if (wLen < 1e-9) continue; - - const rel = sub(p, w.start); - const distAlong = dot(rel, u); - if (distAlong <= endGap || distAlong >= wLen - endGap) continue; // an Endpunkt, kein Mittelspann - - const perp = dot(rel, leftNormal(u)); - const tw = wallTypeThickness(getWallType(project, w)); - const dist = Math.abs(perp); - if (dist > tw / 2 + tol) continue; - - if (!best || dist < best.dist) best = { wall: w, perp, dist, distAlong }; - } - if (!best) return; // kein Treffer → rechtwinklig - - const w = best.wall; - const tw = wallTypeThickness(getWallType(project, w)); - const uW = dirOf(w); - const nW = leftNormal(uW); - const offW = wallReferenceOffset(w, tw); - // Zugewandte Seite: primär aus der AUSLAUFRICHTUNG des freien Endes in - // seinen eigenen Körper (wie `dBranch`/`sign` in applyTJunction) — nicht aus - // der lateralen Position `perp`. Bei einer „+"-Kreuzung (zwei kollineare - // Enden treffen exakt auf der ACHSE der durchlaufenden Wand, `perp≈0`) ist - // `perp` für beide Enden identisch und liefert für BEIDE dieselbe (falsche) - // Seite; die Auslaufrichtung unterscheidet sie dagegen korrekt (linke Hälfte - // läuft nach −u aus, rechte nach +u — je die gegenüberliegende Fläche der - // Durchgangswand). Nur wenn die Auslaufrichtung (nahezu) parallel zur - // Durchgangsachse liegt (dot≈0 — geometrisch entartet für einen T-Stoss), - // bleibt `perp` als Fallback (bisheriges Verhalten). - const dFree = - freeEnd.end === "start" ? dirOf(freeWall) : scale(dirOf(freeWall), -1); - const facing = dot(nW, dFree); - const sign = Math.abs(facing) > 1e-6 ? (facing >= 0 ? 1 : -1) : best.perp >= 0 ? 1 : -1; - const facePoint = add(w.start, scale(nW, offW + sign * (tw / 2))); - const faceCut: Line = { point: facePoint, dir: uW }; - - setCut(result, freeEnd, faceCut); - // Achsenpunkt auf der getroffenen Wand, auf Höhe der Projektion des freien - // Endes (nicht zwingend w.start) — Anker für die materialbewusste - // Pro-Schicht-Erweiterung (analog zum T-Knoten-Fall). - const axisPoint = add(w.start, scale(uW, best.distAlong)); - applyLayerCuts(project, result, freeEnd, freeWall, w, faceCut, axisPoint, uW, sign); + return cuts; } diff --git a/src/plan/toSection.ts b/src/plan/toSection.ts index 31f982ed..cbd9daa7 100644 --- a/src/plan/toSection.ts +++ b/src/plan/toSection.ts @@ -239,10 +239,10 @@ export function wallLayersReversedInU(owner: Wall, uWorld: Vec2): boolean { // `projectToWalls3d` zerlegt EINE Wand mit Öffnungen in mehrere Teilquader // (Pfeiler/Brüstung/Sturz) — die Emission ist also nicht 1:1 Wand→Element. // Um einen `index` wieder auf seine Quellwand zurückzuführen, wird hier exakt -// dieselbe Segmentierungs-/Skip-Logik wie `emitWall`/`pushSegment` -// (toWalls3d.ts) repliziert — NICHT die Geometrie, nur welches Quellelement +// dieselbe Segmentierungs-/Skip-Logik wie `emitWalls` (Schnitt-Pfad in +// `src-tauri/core/src/wall_bands.rs`) repliziert — NICHT die Geometrie, nur welches Quellelement // pro emittiertem Segment "besitzt". Bleibt diese Zählung nicht exakt parallel -// zu `emitWall`, verschieben sich die Indizes und die Hatch-Auflösung wird +// zu `emitWalls`, verschieben sich die Indizes und die Hatch-Auflösung wird // falsch (harmlos: der Aufrufer fällt dann pro Cut-Polygon auf die generische // Schnitt-Schraffur zurück, siehe `resolveWallSectionStyle`/`generatePlan.ts`). const OWNER_EPS = 1e-4; diff --git a/src/plan/toWalls3d.ts b/src/plan/toWalls3d.ts index 7be37d87..76a8f95d 100644 --- a/src/plan/toWalls3d.ts +++ b/src/plan/toWalls3d.ts @@ -63,7 +63,7 @@ import { type RVec2, type RWall, } from "./toWalls3d/shared"; -import { emitWall } from "./toWalls3d/bands"; +import { emitWalls } from "./toWalls3d/bands"; import { emitSlabs } from "./toWalls3d/ceilings"; import { emitStairMeshes, emitStairRailings, emitStairs } from "./toWalls3d/stairs"; import { emitExtrudedSolids, TRUCK_MESH_READY_EVENT } from "./toWalls3d/extrusions"; @@ -147,7 +147,7 @@ export function projectToWalls3d(project: Project, layered = true): RWall[] { // Dominanz macht toSection.ts). Anders als im 2D wird hier NICHT nach // Sichtbarkeit gefiltert — 3D zeigt alle Wände, alle nehmen an den Joins teil. const joins = layered ? computeJoinsByFloor(project) : undefined; - for (const w of project.walls) emitWall(out, project, w, layered, joins?.get(w.id)); + emitWalls(out, project, project.walls, layered, joins); return out; } @@ -364,7 +364,7 @@ export function pickGeometry( * entlang der Wandlänge, Normale (Dicke) senkrecht dazu in der XZ-Ebene, * Y = Höhe. Aus den 8 Ecken werden die 12 Kanten des Quaders emittiert. * Wände MIT Öffnungen bestehen aus mehreren Teilquadern (Pfeiler/Brüstung/ - * Sturz, s. emitWall) — alle tragen dieselbe `wallId` und werden hier ALLE + * Sturz, s. emitWalls) — alle tragen dieselbe `wallId` und werden hier ALLE * umrandet, sodass Öffnungsränder mit hervorgehoben werden. * • Decke: der Umriss oben (zTop) und unten (zBottom) je als geschlossener * Kantenzug, plus eine vertikale Kante an jeder Umriss-Ecke. diff --git a/src/plan/toWalls3d/bands.ts b/src/plan/toWalls3d/bands.ts index d3cff776..3598f434 100644 --- a/src/plan/toWalls3d/bands.ts +++ b/src/plan/toWalls3d/bands.ts @@ -3,16 +3,15 @@ // gestapelte Materialbänder auf und emittiert daraus Wandkörper — inklusive // aller materialbewussten Verschneidungen (Gehrungs-/Anschluss-Cuts an L-/ // T-Stössen, Durchgangswand-Span-Cutouts, Decken-Dominanz pro Schicht, Dach- -// Unterkanten-Kappung). Das 3D-Pendant zu `generatePlan/walls.ts::addWallPoche`. +// Unterkanten-Kappung mit schräger Oberkante). Das 3D-Pendant zu +// `generatePlan/walls.ts::addWallPoche`. +// +// Gerechnet wird im Rust-Kern (`src-tauri/core/src/wall_bands.rs`); hier bleiben +// das Sammeln aus dem `Project` (Wandtyp, Öffnungen, Decken- und Dachaufbau, +// Höhen), die flache Übergabe und die Darstellungs-Metadaten je Band (Farbe, +// Schraffur, Material, Schnitt-Stil). -import type { - Ceiling, - Layer, - Project, - SliceTermination, - Vec2, - Wall, -} from "../../model/types"; +import type { Project, Wall } from "../../model/types"; import { getCeilingType, getComponent, @@ -22,14 +21,12 @@ import { roofLayers, wallTypeThickness, } from "../../model/types"; -import { ceilingVerticalExtent, wallReferenceOffset, wallVerticalExtent } from "../../model/wall"; -import { pointInOutline } from "../../geometry/ceiling"; +import { ceilingVerticalExtent, wallVerticalExtent } from "../../model/wall"; import { openingInterval, openingVerticalExtent } from "../../geometry/opening"; -import { roofBaseElevation, roofGeometry, roofUndersideAt } from "../../geometry/roof"; -import type { RoofGeometry } from "../../geometry/roof"; -import type { WallCuts } from "../../model/joins"; -import { add, dot, leftNormal, lineIntersect, scale, sub } from "../../model/geometry"; -import type { Line } from "../../model/geometry"; +import { roofBaseElevation, roofGeometry, roofPlanesFlat } from "../../geometry/roof"; +import { writeWallCuts, type WallCuts } from "../../model/joins"; +import { FlatReader, FlatWriter } from "../../geometry/coreFlat"; +import { core } from "../../engine/coreWasm"; import { WALL_RGB, dominantLayerColor, @@ -38,7 +35,6 @@ import { resolveComponentHatch, resolveComponentMaterialLayer, resolveCutLineStyle, - EPS, type RCutMeta, type RHatch, type RHole, @@ -59,23 +55,22 @@ import { const SECTION_WALL_AXIS_ANGLE_DEG = 90; /** - * Eine quer zur Wanddicke gestapelte Materiallage als 3D-Band: eigene Dicke, - * Materialfarbe und Mitten-Versatz `offset` (Meter, entlang der Wand-Normalen, - * relativ zur Wandachse). Jede solche Lage wird pro Achsen-Teilquader zu einer - * eigenen Voll-Box (siehe {@link emitWall}/{@link pushSegment}). + * Eine quer zur Wanddicke gestapelte Materiallage als 3D-Band: eigene Dicke und + * Materialfarbe. Den Mitten-Versatz (Stapel um die Achse, Referenzlinie) rechnet + * der Kern (`wall_bands.rs`); jede Lage wird dort pro Achsen-Teilstück zu einer + * eigenen Voll-Box. */ interface WallBand { thickness: number; color: RRgb; - offset: number; /** Schnitt-Schraffur des Band-Bauteils (siehe {@link RHatch}). */ hatch?: RHatch; /** Material-Textur-Ebene des Band-Bauteils (1-basiert, siehe `wallMaterialColorMaps`). */ materialIndex?: number; /** * Verschneidungs-Rang dieser Materiallage (`Component.joinPriority`) — treibt - * die per-Schicht-Dominanz gegen Decken im layered-3D-Pfad (s. - * {@link collectCeilingCutters}/{@link emitWall}): eine Decke mit STRIKT höherer + * die per-Schicht-Dominanz gegen Decken im layered-3D-Pfad (s. `wall_bands.rs`): + * eine Decke mit STRIKT höherer * `joinPriority` schneidet nur die Bänder mit niedrigerem Rang aus ihrem * z-Intervall (der Kern höherer Priorität läuft durch). `undefined` (kein * auflösbarer WallType / synthetisches Fallback-Band) ⇒ keine Decken- @@ -111,29 +106,20 @@ function bandCutMeta(b: WallBand): RCutMeta | undefined { /** * Löst den Schichtstapel EINER Wand auf: je Materiallage ein {@link WallBand} - * mit ihrer Dicke, Component-Farbe und dem Mitten-Versatz entlang der Normalen. - * Die Versätze zentrieren den Stapel um die Wandachse UND verschieben ihn um - * {@link wallReferenceOffset} (`Wall.referenceLine`/`referenceOffset` — links/ - * Mitte/rechts/frei), damit die Achse bei „außen"/„innen" tatsächlich auf der - * gewählten Wandfläche liegt statt immer mittig — dieselbe Grösse, die der 2D- - * Plan (`generatePlan/walls.ts`) UND die Gehrungs-/Anschluss-Cuts an Ecken - * (`model/joins.ts::miterLine`) bereits verwenden. Bis 2026-08-30 rechnete - * dieser Pfad NICHT damit (Bug: Wände mit `referenceLine !== "center"` sassen - * im Standard-3D mittig, obwohl die Eckenverschneidung schon den Versatz - * annahm → Geraden und Ecken liefen auseinander). Als Gesamtdicke T dient die - * SUMME der tatsächlichen Lagen-Dicken (nicht `wallTypeThickness`, falls es - * abweicht) — so schließen die Bänder lückenlos aneinander an. Kein auflösbarer - * WallType / keine Lagen ⇒ EIN Vollkörper-Band über die volle Dicke im - * neutralen Grundton (heutiges Fallback-Verhalten), ebenfalls Referenz-versetzt. + * mit ihrer Dicke und Component-Farbe (`stacked: true`). Der Kern stapelt die + * Lagen um die Wandachse und verschiebt den Stapel um den Referenzversatz + * (`Wall.referenceLine`/`referenceOffset`), wie der 2D-Plan und die Gehrungs- + * Cuts. Gesamtdicke = SUMME der Lagen-Dicken (lückenlos). Kein auflösbarer + * WallType / keine Lagen ⇒ EIN Vollkörper-Band über die volle Dicke im neutralen + * Grundton (`stacked: false`, ebenfalls Referenz-versetzt). */ -function resolveWallBands(project: Project, wall: Wall, layered = true): WallBand[] { +function resolveWallBands(project: Project, wall: Wall, layered = true): { bands: WallBand[]; stacked: boolean } { try { const wt = getWallType(project, wall); if (wt.layers.length > 0) { // Gesamtdicke = Summe der Lagen (konsistent mit den Offsets); wenn diese // von wallTypeThickness abwiche, gewinnt die Lagen-Summe (keine Lücken). const total = wt.layers.reduce((s, l) => s + l.thickness, 0); - const refOff = wallReferenceOffset(wall, total); // Schnitt-Eingabe (layered=false): EINE Voll-Box über die ganze Dicke statt // je Lage eine Box. So bleibt die Emission 1:1 Wand→Rechteck — passend zu // `wallSegmentOwners`/`splitWallLayers` in toSection.ts, die die Schicht- @@ -141,18 +127,15 @@ function resolveWallBands(project: Project, wall: Wall, layered = true): WallBan // mit Default layered=true auf und bekommt unverändert die Schicht-Bänder.) if (!layered) { const dominant = wt.layers.reduce((best, l) => (l.thickness > best.thickness ? l : best)); - return [ - { - thickness: total, - color: dominantLayerColor(wt.layers, project, WALL_RGB), - offset: refOff, - hatch: dominantLayerHatch(wt.layers, project, SECTION_WALL_AXIS_ANGLE_DEG), - materialIndex: resolveComponentMaterialLayer(project, dominant.componentId), - }, - ]; + const band: WallBand = { + thickness: total, + color: dominantLayerColor(wt.layers, project, WALL_RGB), + hatch: dominantLayerHatch(wt.layers, project, SECTION_WALL_AXIS_ANGLE_DEG), + materialIndex: resolveComponentMaterialLayer(project, dominant.componentId), + }; + return { bands: [band], stacked: false }; } const bands: WallBand[] = []; - let prefix = 0; for (const l of wt.layers) { const comp = getComponent(project, l.componentId); const color = hexToRgb(comp.color); @@ -160,7 +143,6 @@ function resolveWallBands(project: Project, wall: Wall, layered = true): WallBan bands.push({ thickness: l.thickness, color, - offset: refOff - total / 2 + prefix + l.thickness / 2, priority: comp.joinPriority, componentId: comp.id, cutLineColor: lineStyle?.color, @@ -168,17 +150,14 @@ function resolveWallBands(project: Project, wall: Wall, layered = true): WallBan hatch: resolveComponentHatch(project, l.componentId, SECTION_WALL_AXIS_ANGLE_DEG), materialIndex: resolveComponentMaterialLayer(project, l.componentId), }); - prefix += l.thickness; } - return bands; + return { bands, stacked: true }; } // WallType ohne Schichten: EIN Vollkörper über die Typ-Gesamtdicke. - const total = wallTypeThickness(wt); - return [{ thickness: total, color: WALL_RGB, offset: wallReferenceOffset(wall, total) }]; + return { bands: [{ thickness: wallTypeThickness(wt), color: WALL_RGB }], stacked: false }; } catch { // Kein auflösbarer WallType: EIN Vollkörper mit Default-Dicke/Grundton. - const total = 0.2; - return [{ thickness: total, color: WALL_RGB, offset: wallReferenceOffset(wall, total) }]; + return { bands: [{ thickness: 0.2, color: WALL_RGB }], stacked: false }; } } @@ -199,125 +178,7 @@ function withTopAngle(h: RHatch, dx: number, dy: number): RHatch { } /** - * Hängt eine Wand-Schicht-Box an: das Achsenstück [from..to] (Meter ab - * Wand-Startpunkt) über den Höhenbereich [zBottom..zTop], quer um `normalOffset` - * Meter entlang der Wand-Normalen versetzt (Schichtmitte relativ zur Achse) und - * mit Schicht-`thickness`/`color`. Entartete Stücke (Länge ≤ 0 oder Höhe ≤ 0) - * werden übersprungen — so überleben Öffnungen dicht an den Wandenden ohne - * Nullquader. - * - * Optionale `holes`: echte rechteckige Aussparungen in DIESER Box (siehe - * {@link RHole}). Ihre `from`/`to` sind Achsen-Meter ab Wand-Start (dieselbe - * Achse wie `from`/`to` dieser Box), `zBottom`/`zTop` absolute Weltmeter — beides - * unverändert an render3d durchgereicht (der Querversatz `normalOffset` wirkt nur - * senkrecht zur Achse und lässt die Loch-Parametrisierung unberührt). Werden nur - * im 3D-Pfad (voller Achsen-Quader) gesetzt. - */ -function pushSegment( - out: RWall[], - wall: Wall, - from: number, - to: number, - zBottom: number, - zTop: number, - thickness: number, - normalOffset: number, - color: RRgb, - wallId: string, - hatch?: RHatch, - materialIndex?: number, - holes?: RHole[], - cut?: RCutMeta, - topDrop?: [number, number], -): void { - if (to - from <= EPS) return; - if (zTop - zBottom <= EPS) return; - 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; - const ux = dx / len; - const uy = dy / len; - // LINKE Grundriss-Normale (identisch zu `leftNormal(u)` = (−uy, ux) in - // generatePlan.ts/clippedBand — dieselbe Konvention, die addWallPoche für - // den Schichtstapel im 2D-Grundriss benutzt). Der Schicht-Versatz verschiebt - // Start/Ende der Box quer zur Wand, sodass render3d die Box um ihre eigene - // (versetzte) Achse zentriert aufbaut — mit dieser Normale liegt Schicht 0 - // (Aussenseite, kleinster `offset`) auf derselben Weltseite wie im Grundriss. - // Bewusst NICHT identisch zur Normale, die raycast3d/selectionHighlightLines - // für den Box-Rebuild nutzen (n = (uy, −ux), rechte Normale) — das ist - // unschädlich, weil jene Boxen symmetrisch um die (hier bereits versetzte) - // Achse jedes einzelnen Layer-Records aufgebaut werden und daher unabhängig - // von der Vorzeichen-Konvention des Versatzes sind. - const ox = -uy * normalOffset; - const oy = ux * normalOffset; - const p1: [number, number] = [wall.start.x + ux * from + ox, wall.start.y + uy * from + oy]; - const p2: [number, number] = [wall.start.x + ux * to + ox, wall.start.y + uy * to + oy]; - out.push({ - start: p1, - end: p2, - thickness, - height: zTop - zBottom, - baseElevation: zBottom, - ...(topDrop && (topDrop[0] > EPS || topDrop[1] > EPS) ? { topDrop } : {}), - color, - layers: [], - wallId, - ...(hatch ? { hatch: withTopAngle(hatch, dx, dy) } : {}), - ...(materialIndex != null ? { materialIndex } : {}), - ...(holes && holes.length > 0 ? { holes } : {}), - ...(cut ? { cut } : {}), - }); -} - -/** - * Achsenparalleles Grundriss-Rechteck (min/max je Achse), Meter, Modell-XY. - * Dient hier NUR der groben Footprint-Überlapp-Prüfung Wand↔Decke (s. - * {@link collectCeilingCutters}) — kein exakter Polygon-Test, siehe dort. - */ -interface Bounds2 { - minX: number; - maxX: number; - minY: number; - maxY: number; -} - -/** Bounding-Box der Wandachse, um `halfThickness` in beide Richtungen geweitet - * (sichere Über-Approximation des tatsächlichen Wandkörpers, unabhängig von - * dessen Orientierung). */ -function wallFootprintBounds(wall: Wall, halfThickness: number): Bounds2 { - return { - minX: Math.min(wall.start.x, wall.end.x) - halfThickness, - maxX: Math.max(wall.start.x, wall.end.x) + halfThickness, - minY: Math.min(wall.start.y, wall.end.y) - halfThickness, - maxY: Math.max(wall.start.y, wall.end.y) + halfThickness, - }; -} - -/** Bounding-Box eines geschlossenen Umrisses (Decke). */ -function outlineBounds(outline: Array<{ x: number; y: number }>): Bounds2 { - let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity; - for (const p of outline) { - if (p.x < minX) minX = p.x; - if (p.x > maxX) maxX = p.x; - if (p.y < minY) minY = p.y; - if (p.y > maxY) maxY = p.y; - } - return { minX, maxX, minY, maxY }; -} - -/** Überlappen sich zwei Bounding-Boxen (mit EPS-Toleranz an den Rändern)? */ -function boundsOverlap(a: Bounds2, b: Bounds2): boolean { - return ( - a.minX <= b.maxX + EPS && - a.maxX >= b.minX - EPS && - a.minY <= b.maxY + EPS && - a.maxY >= b.minY - EPS - ); -} - -/** - * Dicke einer Wand für die Footprint-Näherung (s. {@link wallFootprintBounds}): + * 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 @@ -331,665 +192,155 @@ export function wallThicknessSafe(project: Project, wall: Wall): number { } } -/** - * Repräsentative `joinPriority` einer Decke (höchste ihrer Schichten) — bestimmt, - * ob die Decke am Wand/Decke-Stoss "durchläuft" (gewinnt) und in die Wandschichten - * niedrigerer Priorität einschneidet (s. {@link collectCeilingCutters}). - */ -function ceilingDominantPriority(project: Project, ceiling: Ceiling): number | undefined { - try { - const ct = getCeilingType(project, ceiling); - let best: number | undefined; - for (const layer of ct.layers) { - const p = getComponent(project, layer.componentId).joinPriority; - if (best === undefined || p > best) best = p; - } - return best; - } catch { - return undefined; - } -} +/** `Wall.sliceTermination` → Kodierung im Kern (0 = beide/Standard). */ +const TERMINATION = { below: 1, above: 2 } as const; /** - * Ein Decken-„Cutter": vertikales z-Intervall + Dominanz-Rang + Grundriss-Umriss - * (s. {@link collectCeilingCutters}). Der `outline` erlaubt die PER-BAND-genaue - * Überdeckungsprüfung in {@link emitWall} (statt eines wandweiten BBox-Tests): eine - * Decke schneidet ein Schicht-Band nur dort, wo ihre Outline die Footprint- - * Mittellinie des Bandes im Grundriss überdeckt. + * Schreibt Decken und Dächer EINES Geschosses (Kodierung `wall_bands.rs`): Decken + * mit z-Ausdehnung, Umriss und Schichten samt Rang (NaN = Bauteil unbekannt, + * Typ-Flag 0 = Deckentyp unbekannt); Dächer mit Traufhöhe, Schichtdicke, Traufe + * und Flächen. Ob und wo eine Decke ein Band schneidet bzw. ein Dach die Oberkante + * kappt, entscheidet der Kern. */ -interface CeilingCutter { - zBottom: number; - zTop: number; - priority: number; - outline: Vec2[]; -} - -/** - * Sammelt die Decken, die eine Wand im layered-3D-Pfad PRO SCHICHT einschneiden — - * die 3D-Entsprechung der Schnitt-Boolean-Dominanz (`toSection.ts:: - * subtractDominantBands`): statt die GANZE Wand am Deckenanschluss zu kappen - * (früheres `trimWallTopForCeilings`), behält die Wand ihre volle Höhe und JEDES - * Schicht-Band verliert nur das z-Intervall der Decken mit STRIKT höherer - * `joinPriority` als das Band (der Kern höherer Priorität läuft durch die Decke). - * Ein Band kann dadurch vertikal in zwei Boxen zerfallen (unter Deckenunterkante - * + über Deckenoberkante, falls die Wand die Decke überragt). - * - * Kriterien je Decke (alle müssen zutreffen): - * • dasselbe Geschoss (`ceiling.floorId === wall.floorId`), - * • vertikale Überlappung mit der (vollen) Wand-Ausdehnung, - * • grober Footprint-Überlapp (Bounding-Box, s. {@link boundsOverlap}) — nur ein - * billiger Vor-Filter (keine Wand berührt, wenn die Wand-BBox die Decken-BBox - * nicht schneidet); die EXAKTE, per-Band geometrische Überdeckung entscheidet - * dann in {@link emitWall} (s. {@link bandCoverageIntervals}). - * • auflösbare Decken-`joinPriority` (`ceilingDominantPriority`). - * - * Das z-Intervall/die Priorität der Cutter ist PER DECKENSCHICHT (nicht die ganze - * Decke als EIN Block der dominanten Priorität): jede Deckenschicht wird zu einem - * eigenen Cutter mit IHREM z-Band (proportional auf [zBottom,zTop] verteilt, exakt - * wie `../ceilings.ts::emitSlabs`) und IHRER `Component.joinPriority`. Das ist - * zwingend, damit der 3D-Cut EXAKT wie der 2D-Schnitt (`toSection.ts:: - * subtractDominantBands`) verschneidet: dort trägt jede Schicht ihre eigene - * Priorität. Mit dem früheren EINEN Block (dominante Prio 100 über die volle - * Decke) verlor z. B. der Backstein (50) das GANZE Decken-z-Band [UK,OK] — - * obwohl er die schwimmenden Deckenschichten Estrich (30)/Dämmung (20) - * ÜBERRAGEN und schneiden soll; nur die Betonschicht (100) darf ihn kappen. So - * blieb im 3D (Solid UND Schnitt) über dem Backstein eine Lücke, durch die - * Estrich/Dämmung „rausliefen" (Nutzer-Bug). Per Schicht läuft der Backstein - * zwischen Beton-OK und Wandkopf durch und schneidet dort Estrich/Dämmung weg — - * identisch zum 2D-Schnitt. Der `outline` reist mit, damit {@link emitWall} PRO - * BAND prüft, ob die Decke die Footprint-Mittellinie dieses Bandes überdeckt - * (geometrischer Überlapp, kein wandweiter BBox-Test). Der Prioritätsvergleich pro - * Band passiert in {@link emitWall} (`cutter.priority > band.priority`) — eine - * Wand-Schicht mit ≥ Rang der jeweiligen Deckenschicht läuft durch deren z-Band durch. - * Ein-Schicht-/nicht auflösbare Deckentypen fallen auf EINEN Cutter über die volle - * Ausdehnung mit der dominanten Priorität zurück (Alt-Verhalten). - */ -function collectCeilingCutters( - project: Project, - wall: Wall, - zBottom: number, - zTop: number, -): CeilingCutter[] { - const halfThickness = wallThicknessSafe(project, wall) / 2; - const wallBounds = wallFootprintBounds(wall, halfThickness); - const cutters: CeilingCutter[] = []; - for (const c of project.ceilings ?? []) { - if (c.floorId !== wall.floorId) continue; - if (!c.outline || c.outline.length < 3) continue; - const cExtent = ceilingVerticalExtent(project, c); - if (cExtent.zBottom >= zTop - EPS || cExtent.zTop <= zBottom + EPS) continue; - if (!boundsOverlap(wallBounds, outlineBounds(c.outline))) continue; - - // Per-Schicht-Cutter: je Deckenschicht ein eigenes z-Band + eigene Priorität - // (proportional auf die tatsächliche Decken-z-Spanne skaliert, oben→unten wie - // emitSlabs). Nur so schneidet Beton (100) den Backstein (50), Backstein aber - // Estrich (30)/Dämmung (20) — identisch zu subtractDominantBands. - let layers: Layer[] | undefined; +function writeFloor(w: FlatWriter, project: Project, floorId: string | undefined): void { + const ceilings = (project.ceilings ?? []).filter((c) => c.floorId === floorId && c.outline && c.outline.length >= 3); + w.num(ceilings.length); + for (const c of ceilings) { + const ext = ceilingVerticalExtent(project, c); + w.num(ext.zBottom, ext.zTop).ring(c.outline); + let layers; try { layers = getCeilingType(project, c).layers; } catch { - layers = undefined; + w.num(0, 0); + continue; } - const total = layers?.reduce((s, l) => s + l.thickness, 0) ?? 0; - if (layers && layers.length > 0 && total > EPS) { - const span = cExtent.zTop - cExtent.zBottom; - let prefixTop = 0; // von OK (zTop) nach unten aufsummiert (Meter) - for (const l of layers) { - const t = (l.thickness / total) * span; - const layerTop = cExtent.zTop - prefixTop; - const layerBottom = layerTop - t; - prefixTop += t; - let prio: number | undefined; - try { - prio = getComponent(project, l.componentId).joinPriority; - } catch { - prio = undefined; - } - if (prio === undefined) continue; - cutters.push({ zBottom: layerBottom, zTop: layerTop, priority: prio, outline: c.outline }); + w.num(1, layers.length); + for (const l of layers) { + let prio = Number.NaN; + try { + prio = getComponent(project, l.componentId).joinPriority; + } catch { + // Unbekanntes Bauteil: diese Deckenschicht schneidet nicht. } - } else { - const ceilingPriority = ceilingDominantPriority(project, c); - if (ceilingPriority === undefined) continue; - cutters.push({ zBottom: cExtent.zBottom, zTop: cExtent.zTop, priority: ceilingPriority, outline: c.outline }); + w.num(l.thickness, prio); } } - return cutters; -} - -/** - * Achsen-Teilintervalle (Meter ab `wall.start` entlang `u`, geklemmt auf - * `[lo,hi]`), auf denen die MITTELLINIE eines Schicht-Bands (Querversatz - * `bandOffset` entlang `n = leftNormal(u)`) im Decken-Umriss `outline` liegt — - * die per-Band-Entsprechung des geometrischen Rechteck-Überlapps in - * `toSection.ts::subtractDominantBands`. Nur diese Teilintervalle bekommen später - * den Decken-z-Schnitt; unbedeckte Achsenabschnitte behalten die volle Höhe (so - * laufen Dämmung/Aussenputz, deren Mittellinie AUSSERHALB des Decken-Umrisses - * liegt, ununterbrochen durch — der Nutzer-Bug „Kranz durch die Dämmung"). - * - * Die Bandmittellinie wird entlang der Achse gerastert (~5-cm-Schritte, min. 32) - * und gegen {@link pointInOutline} geprüft; Innen/Aussen-Übergänge werden per - * Bisektion auf ~EPS verfeinert, sodass die Überdeckungsgrenzen scharf sind (auch - * eine Decke, die nur einen Teil der Wandlänge überdeckt, wird korrekt getrimmt). - */ -function bandCoverageIntervals( - wall: Wall, - u: Vec2, - n: Vec2, - bandOffset: number, - outline: Vec2[], - lo: number, - hi: number, -): Array<[number, number]> { - if (hi - lo <= EPS) return []; - const base = add(wall.start, scale(n, bandOffset)); - const inside = (t: number): boolean => pointInOutline(add(base, scale(u, t)), outline); - const steps = Math.max(32, Math.ceil((hi - lo) / 0.05)); - const dt = (hi - lo) / steps; - const intervals: Array<[number, number]> = []; - let prevInside = inside(lo); - let start: number | null = prevInside ? lo : null; - let prevT = lo; - for (let i = 1; i <= steps; i++) { - const t = i === steps ? hi : lo + i * dt; - const now = inside(t); - if (now !== prevInside) { - const cross = bisectBoundary(inside, prevT, t); - if (now) start = cross; - else if (start !== null) { - intervals.push([start, cross]); - start = null; - } - } - prevInside = now; - prevT = t; - } - if (start !== null) intervals.push([start, hi]); - return intervals; -} - -/** - * Bisektion des Innen/Aussen-Übergangs der Bandmittellinie zwischen `a` und `b` - * (verschiedene {@link pointInOutline}-Seiten) auf ~EPS-Genauigkeit — liefert die - * scharfe Achsen-Position der Überdeckungsgrenze. - */ -function bisectBoundary(inside: (t: number) => boolean, a: number, b: number): number { - const aInside = inside(a); - let lo = a; - let hi = b; - for (let i = 0; i < 40 && hi - lo > EPS * 0.01; i++) { - const mid = (lo + hi) / 2; - if (inside(mid) === aInside) lo = mid; - else hi = mid; - } - return (lo + hi) / 2; -} - -/** - * Zieht die Cutter-Intervalle `holes` vom Intervall `[lo,hi]` ab und liefert die - * verbleibenden Teil-Intervalle (Meter). Löcher werden auf `[lo,hi]` geklemmt, - * sortiert und vereinigt; leeres `holes` ⇒ exakt `[[lo,hi]]` (unveränderter Fall). - * Dient sowohl der Achsen-Zerlegung durch Durchgangswand-Span-Cutouts als auch - * der vertikalen Decken-Subtraktion (identische 1D-Semantik wie - * `generatePlan/walls.ts::subtractIntervals`, hier lokal gehalten). - */ -function subtractSpans(lo: number, hi: number, holes: Array<[number, number]>): Array<[number, number]> { - const clipped = holes - .map(([a, b]): [number, number] => [Math.max(lo, Math.min(a, b)), Math.min(hi, Math.max(a, b))]) - .filter(([a, b]) => b > a + EPS) - .sort((p, q) => p[0] - q[0]); - const parts: Array<[number, number]> = []; - let cursor = lo; - for (const [a, b] of clipped) { - if (a > cursor + EPS) parts.push([cursor, a]); - if (b > cursor) cursor = b; - } - if (cursor < hi - EPS) parts.push([cursor, hi]); - return parts; -} - -/** - * Wendet die Decken-z-Cutter `cutters` (dominante horizontale Cut-Bänder [zBottom, - * zTop]) auf das Wandband-Intervall `[lo,hi]` an — je nach Terminierungs-Regel der - * Wand (`Wall.sliceTermination`). Bewusst als EIGENER, klar benannter Schritt - * neben der Priorität gehalten (Terminierung = Zuschnitt, KEINE Prioritätsregel): - * - * • "both"/undefined ⇒ heutiges Verhalten: `subtractSpans` stanzt jedes Cutter- - * z-Band aus (oben+unten Reste bleiben erhalten). Bit-identisch zu vorher. - * • "below" ⇒ die Wand ENDET an der Decke: alles AB der Decken-UNTERKANTE wird - * verworfen (kein über der Decke wieder auftauchender Rest). Clip-Grenze = das - * KLEINSTE `zBottom` aller dominanten Cutter dieses Bandes. Da die dominanteste - * (tragende) Deckenschicht — z. B. Beton (Prio 100) — jedes schwächere Band - * kappt UND zugleich die unterste Deckenlage ist, terminieren so ALLE Bänder - * einheitlich an der Deckenunterkante (kein Durchstoss/Staffel, keine - * Interpenetration mit Beton/Dämmung darüber). Für den Backstein, den nur der - * Beton kappt, ist das exakt „unter dem dominanten Cut" (dessen Unterkante). - * • "above" ⇒ spiegelbildlich: alles BIS zur Decken-OBERKANTE wird verworfen. - * Clip-Grenze = das GRÖSSTE `zTop` aller dominanten Cutter dieses Bandes. - * - * Ohne Cutter (`cutters` leer) bleibt `[lo,hi]` in allen Modi unverändert — ein - * Band ausserhalb des Decken-Umrisses (Aussenputz/Dämmung) läuft also weiter voll - * durch, unabhängig von der Terminierung. - */ -function terminateOrSubtractSpans( - lo: number, - hi: number, - cutters: Array<[number, number]>, - termination: SliceTermination | undefined, -): Array<[number, number]> { - if (cutters.length === 0) return [[lo, hi]]; - if (termination === "below") { - // Deckenunterkante = kleinstes zBottom der Cutter; die Wand endet dort. - let clipTop = Infinity; - for (const [cb] of cutters) clipTop = Math.min(clipTop, cb); - const top = Math.min(clipTop, hi); - return top > lo + EPS ? [[lo, top]] : []; - } - if (termination === "above") { - // Deckenoberkante = grösstes zTop der Cutter; die Wand beginnt dort. - let clipBottom = -Infinity; - for (const [, ct] of cutters) clipBottom = Math.max(clipBottom, ct); - const bottom = Math.max(clipBottom, lo); - return bottom < hi - EPS ? [[bottom, hi]] : []; - } - return subtractSpans(lo, hi, cutters); -} - -/** - * Achsen-Distanz (Meter ab `wall.start` entlang der Wandrichtung `u`), an der die - * MITTELLINIE eines Schicht-Bands (Querversatz `bandOffset` entlang `leftNormal(u)`) - * die Gehrungs-/Anschluss-Schnittlinie `cut` trifft — die 3D-Achsenbox-Entsprechung - * des 2D-`clippedBand`. Da die Box achsparallel endet (keine gekippte Stirnfläche), - * wird die Band-Länge auf den Schnittpunkt der MITTELLINIE gekürzt/verlängert; die - * beiden 2D-Bandkanten (bei ±thickness/2) treffen die Schnittlinie an leicht - * versetzten Achsenpunkten — der Box-Wert ist ihr Mittelwert. `null` bei - * (nahezu) parallelem Schnitt (kollineare Achsen) ⇒ Aufrufer behält das Bandende. - */ -function bandCutDistance(wall: Wall, u: Vec2, n: Vec2, bandOffset: number, cut: Line): number | null { - const base = add(wall.start, scale(n, bandOffset)); - const hit = lineIntersect(base, u, cut.point, cut.dir); - if (!hit) return null; - return dot(sub(hit, wall.start), u); -} - -/** Schrittweite (Meter) der Dach-Unterkanten-Annäherung, s. {@link clipPieceToRoofs}. */ -const ROOF_CLIP_STEP = 0.15; - -/** - * Kappt ein Wand-Achsenstück [a,bb] (z-Bereich [zb,zt]) an der Dach-UNTERKANTE - * (falls ein Dach darüber liegt) und emittiert es via `emit` — in FEINE Achsen- - * Schritte (~{@link ROOF_CLIP_STEP}) zerlegt, je Schritt auf die dort gemessene - * Dach-Unterkante geklemmt. Das ist eine TREPPENSTUFEN-Annäherung an eine echte - * geneigte Giebelwand-Stirnfläche (render3d-Wandkörper (`RWall`) haben nur einen - * FLACHEN Top — echte Schrägflächen bräuchten einen neuen Mesh-Pfad); bei der - * gewählten Schrittweite optisch glatt genug UND behebt das eigentliche Problem - * (Wand durchdringt die Dachfläche → Z-Fighting, s. PENDENZEN.md „Dach-Wand- - * Verschneidung"), ohne render3d/Rust anzufassen. - * - * Ohne Dächer (oder keinem, das dieses Wandstück überdeckt) läuft das Stück - * UNVERÄNDERT als EIN Body durch (kein Overhead im Normalfall). - */ -function clipPieceToRoofs( - project: Project, - wall: Wall, - u: Vec2, - n: Vec2, - bandOffset: number, - a: number, - bb: number, - zb: number, - zt: number, - emit: (a: number, bb: number, zb: number, ztStart: number, ztEnd: number) => void, -): void { - if (zt - zb <= EPS || bb - a <= EPS) return; - const nrm = n; - const wallBounds = wallFootprintBounds(wall, Math.abs(bandOffset) + 0.01); - const roofs = (project.roofs ?? []).filter((r) => { - if (r.floorId !== wall.floorId) return false; + const roofs = (project.roofs ?? []).filter((r) => r.floorId === floorId); + w.num(roofs.length); + for (const r of roofs) { const eavesZ = roofBaseElevation(project, r); - // Grober Höhen-Ausschluss: Dach-Traufe weit unter dem Wandstück ⇒ kann nicht - // schneiden (übliche Dächer haben keine nach unten ausufernden Übermasse). - return eavesZ + 50 >= zb; // grosszügige Schranke statt exakter First-Höhe - }); - if (roofs.length === 0) { - emit(a, bb, zb, zt, zt); - return; + const geo = roofGeometry(r, eavesZ); + const total = roofLayers(project, r).reduce((s, l) => s + Math.max(0, l.thickness), 0); + w.num(eavesZ, total).ring(geo.eaves); + const planes = roofPlanesFlat(geo); + for (let i = 0; i < planes.length; i++) w.num(planes[i]); } - const roofData = roofs - .map((r) => { - const eavesZ = roofBaseElevation(project, r); - const geo = roofGeometry(r, eavesZ); - if (!boundsOverlap(wallBounds, outlineBounds(geo.eaves))) return null; - const total = roofLayers(project, r).reduce((s, l) => s + Math.max(0, l.thickness), 0); - return { geo, total }; - }) - .filter((d): d is { geo: RoofGeometry; total: number } => d !== null); - if (roofData.length === 0) { - emit(a, bb, zb, zt, zt); - return; - } - - // Oberkante entlang der Achse abtasten (Dach-Unterkante ist stückweise linear in `u`) … - const span = bb - a; - const count = Math.max(1, Math.ceil(span / ROOF_CLIP_STEP)); - const topAt = (t: number): number => { - // Randpunkte minimal nach innen: auf der Dachkante selbst liefert die Unterkante `null`. - const tt = Math.min(bb - 1e-3, Math.max(a + 1e-3, t)); - const p = add(add(wall.start, scale(u, tt)), scale(nrm, bandOffset)); - let clip = zt; - for (const { geo, total } of roofData) { - const under = roofUndersideAt(geo, total, p.x, p.y); - if (under !== null && under < clip) clip = under; - } - return Math.max(zb, clip); - }; - const ts: number[] = []; - const tops: number[] = []; - for (let i = 0; i <= count; i++) { - ts.push(a + (span * i) / count); - tops.push(topAt(ts[i])); - } - // … und zu geraden Stücken zusammenfassen (Toleranz 2 mm): jedes Stück ist ein Körper mit - // schräger Oberkante (`topDrop`), die Knicke (First, Grat) sind die Stückgrenzen. - const TOL = 0.002; - const runs: Array<{ i0: number; i1: number }> = []; - let i0 = 0; - while (i0 < count) { - let i1 = i0 + 1; - while (i1 < count) { - const k = i1 + 1; - const slope = (tops[k] - tops[i0]) / (ts[k] - ts[i0]); - let ok = true; - for (let m = i0 + 1; m <= k && ok; m++) ok = Math.abs(tops[i0] + slope * (ts[m] - ts[i0]) - tops[m]) <= TOL; - if (!ok) break; - i1 = k; - } - runs.push({ i0, i1 }); - i0 = i1; - } - // Knick exakt als Schnitt der Nachbargeraden setzen (statt auf dem Abtastpunkt). - const cuts: number[] = [a]; - const line = (r: { i0: number; i1: number }) => { - const m = (tops[r.i1] - tops[r.i0]) / (ts[r.i1] - ts[r.i0]); - return { m, c: tops[r.i0] - m * ts[r.i0] }; - }; - for (let r = 0; r + 1 < runs.length; r++) { - const l1 = line(runs[r]); - const l2 = line(runs[r + 1]); - const lo = ts[runs[r].i1 - 1]; - const hi = ts[Math.min(count, runs[r].i1 + 1)]; - let x = ts[runs[r].i1]; - if (Math.abs(l1.m - l2.m) > 1e-9) { - const cx = (l2.c - l1.c) / (l1.m - l2.m); - if (cx >= lo && cx <= hi) x = cx; - } - cuts.push(x); - } - cuts.push(bb); - const valueAt = (r: { i0: number; i1: number }, x: number): number => { - const l = line(r); - return Math.min(zt, Math.max(zb, l.m * x + l.c)); - }; - runs.forEach((r, k) => { - const sa = cuts[k]; - const sb = cuts[k + 1]; - if (sb - sa <= EPS) return; - const z0 = valueAt(r, sa); - const z1 = valueAt(r, sb); - if (Math.max(z0, z1) - zb > EPS) emit(sa, sb, zb, z0, z1); - }); } /** - * Emittiert die Wandkörper EINER Wand (mit oder ohne Öffnungen). + * Emittiert die Wandkörper der Wände `walls` in EINEM Kern-Aufruf (Decken/Dächer je + * Geschoss nur einmal übergeben). Reihenfolge der Körper wie Wand für Wand. * * ZWEI PFADE je `layered`: * • layered=true (3D-Viewer, Default): EIN Körper pro Schicht-Band über die * VOLLE Achse mit allen Öffnungen als echte `holes` (render3d stanzt sie in - * die Langseiten). Ermöglicht auch versetzt übereinanderliegende Fenster in - * EINEM Körper (keine Segment-Nähte). - * • layered=false (Schnitt-Pfad, `computeSection`): UNVERÄNDERTE Pfeiler/ - * Brüstung/Sturz-Segmentierung (EIN Voll-Band je Segment), damit die - * `ComponentRef.index`-Reihenfolge exakt zu `toSection.ts::wallSegmentOwners` - * passt (Owner-Kompatibilität; toSection.ts bleibt unangetastet). Löcher - * werden hier NICHT emittiert. + * die Langseiten), dazu die materialbewussten Verschneidungen (End-Cuts/Merge + * an L-/T-Stössen aus `joins`, Durchgangswand-Span-Cutouts, Decken-Dominanz + * pro Schicht, schräge Oberkante unter Dächern als `topDrop`). + * • layered=false (Schnitt-Pfad, `computeSection`): Pfeiler/Brüstung/Sturz- + * Segmentierung (EIN Voll-Band je Segment), passend zu + * `toSection.ts::wallSegmentOwners`. Keine Löcher, keine Cuts. */ -export function emitWall(out: RWall[], project: Project, wall: Wall, layered = true, cuts?: WallCuts): void { - const bands = resolveWallBands(project, wall, layered); - const { zBottom, zTop } = wallVerticalExtent(project, wall); - // Anders als früher (`trimWallTopForCeilings` kappte im layered-Pfad die GANZE - // Wand an der Deckenunterkante) behält die Wand jetzt IN BEIDEN PFADEN ihre - // volle Höhe; die per-Schicht-Decken-Subtraktion (unten, nur layered) schneidet - // Bänder niedrigerer Priorität im Decken-z-Band aus — die 3D-Entsprechung der - // Schnitt-Boolean-Dominanz. Der Schnitt-Pfad (layered=false) bleibt unverändert - // (volle Rohgeometrie; seine Dominanz macht toSection.ts::subtractDominantBands). - const axisLen = Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y); - if (axisLen < 1e-9 || zTop - zBottom <= EPS) return; +export function emitWalls( + out: RWall[], + project: Project, + walls: readonly Wall[], + layered = true, + joins?: Map, +): void { + const w = new FlatWriter().num(walls.length); + const floors = new FlatWriter(); + const floorIndex = new Map(); + const bandsOf: WallBand[][] = []; - // Ein Achsen-Teilquader × jede Materiallage = eine Box (Schichtstapel quer - // zur Wanddicke). Alle tragen die Wand-Id, sodass ein Klick auf irgendeine - // Schicht die GANZE Wand selektiert und das Highlight alle Bänder umrandet. - const emitSeg = (from: number, to: number, zb: number, zt: number): void => { - for (const b of bands) { - pushSegment(out, wall, from, to, zb, zt, b.thickness, b.offset, b.color, wall.id, b.hatch, b.materialIndex, undefined, bandCutMeta(b)); - } - }; - - // Aussparungen der Wand als vereinheitlichte Cutouts sammeln: - // • Öffnungen (project.openings: Fenster und Türen, mit Brüstung/Sturz). - // Jeweils [from..to] auf die Achse geklemmt + vertikale Öffnungs-Ausdehnung. - const cutouts: Array<{ - from: number; - to: number; - oBottom: number; - oTop: number; - /** Schicht-Rücksprung der innersten Schicht an DIESER Öffnung (nur Fenster - * mit `WindowType.innerLayerRecess`), s. Moduldoc unten. */ - recessInnerLayer: boolean; - }> = []; - for (const op of openingsOfWall(project, wall.id)) { - const iv = openingInterval(wall, op); - if (!iv) continue; - const v = openingVerticalExtent(project, wall, op); - const recessInnerLayer = - op.kind === "window" && getWindowType(project, op)?.innerLayerRecess === true; - cutouts.push({ from: iv.from, to: iv.to, oBottom: v.zBottom, oTop: v.zTop, recessInnerLayer }); - } - cutouts.sort((a, b) => a.from - b.from); - - // ── 3D-Viewer-Pfad (layered=true): EIN Körper je Schicht-Band über die volle - // Achse mit allen Öffnungen als echte Löcher (render3d stanzt sie), PLUS die - // materialbewussten Verschneidungen (identisch zum 2D-Grundriss/Schnitt): - // 1. End-Cuts/Merge an L-/T-Stössen: jede Schicht wird an ihrem Achsenende an - // der Gehrungs-/Anschluss-Schnittlinie individuell gekürzt/verlängert - // (`WallCuts.startCut`/`endCut`, bzw. pro Schicht `layerCuts.start/end` — - // merge: Kern läuft bis zur Rückgrat-Nahfläche durch; trim: Putz stoppt an - // der Wandoberfläche). Wie im 2D wird die Band-MITTELLINIE geschnitten. - // 2. Durchgangswand-Span-Cutouts: der Nah-Putz einer Durchgangswand wird über - // die Achsen-Breite des durchstechenden Abzweig-Kerns ausgeschnitten — ein - // Band zerfällt dabei entlang der Achse in mehrere Teilstücke. - // 3. Decken-Dominanz pro Schicht: Bänder niedrigerer `joinPriority` verlieren - // das z-Intervall überlappender Decken (vertikaler Split), der Kern läuft - // durch (s. {@link collectCeilingCutters}). - // Die Öffnungs-Löcher (`holes`, Achsen-Meter ab Wand-Start) werden je Teilstück - // auf dessen Achsen-Start umgerechnet (rebased), damit render3d sie relativ zum - // jeweiligen Box-Start korrekt stanzt. - if (layered) { - const holes: (RHole & { recessInnerLayer: boolean })[] = cutouts.map((c) => ({ - from: c.from, - to: c.to, - zBottom: c.oBottom, - zTop: c.oTop, - recessInnerLayer: c.recessInnerLayer, - })); - const startCut = cuts?.startCut ?? null; - const endCut = cuts?.endCut ?? null; - const layerCuts = cuts?.layerCuts; - const spanCutouts = cuts?.spanCutouts ?? []; - const ux = (wall.end.x - wall.start.x) / axisLen; - const uy = (wall.end.y - wall.start.y) / axisLen; - const u: Vec2 = { x: ux, y: uy }; - const n = leftNormal(u); // (-uy, ux) — dieselbe Konvention wie pushSegment/2D. - const ceilingCutters = collectCeilingCutters(project, wall, zBottom, zTop); - - for (let li = 0; li < bands.length; li++) { - const b = bands[li]; - // (1) Per-Schicht-Cuts an den Achsenden. `layerCuts` (materialbewusster - // T-Stoss) überschreibt — wo gesetzt — den einheitlichen start/endCut PRO - // Schicht; `null` an einem Index heisst „keine Kürzung an diesem Ende". - // Exakt die 2D-Wahl aus generatePlan/walls.ts::addWallPoche. - const sCut = layerCuts ? layerCuts.start[li] : startCut; - const eCut = layerCuts ? layerCuts.end[li] : endCut; - let from0 = 0; - let to0 = axisLen; - if (sCut) { - const d = bandCutDistance(wall, u, n, b.offset, sCut); - if (d !== null) from0 = d; - } - if (eCut) { - const d = bandCutDistance(wall, u, n, b.offset, eCut); - if (d !== null) to0 = d; - } - - // (2) Span-Cutouts, deren Quer-Offsetbereich dieses Band schneidet, brechen - // die Achse [from0,to0] auf (Nah-Putz-Durchstoss der Durchgangswand). - const bandLo = b.offset - b.thickness / 2; - const bandHi = b.offset + b.thickness / 2; - const axisHoles: Array<[number, number]> = []; - for (const c of spanCutouts) { - const cLo = Math.min(c.offA, c.offB); - const cHi = Math.max(c.offA, c.offB); - if (bandLo < cHi - EPS && bandHi > cLo + EPS) axisHoles.push([c.from, c.to]); - } - const axisPieces = subtractSpans(from0, to0, axisHoles); - - // (3) Decken-Subtraktion GEOMETRISCH pro Band (Replik der Schnitt-Boolean- - // Dominanz `toSection.ts::subtractDominantBands`): eine Decke mit STRIKT - // höherer Priorität schneidet dieses Band nur dort aus, wo ihr Grundriss- - // Umriss die Footprint-MITTELLINIE dieses Bandes überdeckt (nicht mehr der - // wandweite BBox-Test). Aussenschichten (Dämmung/Aussenputz), deren - // Mittellinie ausserhalb des Decken-Umrisses liegt, laufen ununterbrochen - // durch — nur der überdeckte Kern verliert das Decken-z-Intervall. Ohne - // auflösbare Band-Priorität bleibt die volle Höhe (konservativ). - const bandZCuts: Array<{ from: number; to: number; zBottom: number; zTop: number }> = []; - if (b.priority !== undefined) { - for (const cc of ceilingCutters) { - if (cc.priority <= b.priority) continue; - for (const [ca, cb] of bandCoverageIntervals(wall, u, n, b.offset, cc.outline, from0, to0)) { - bandZCuts.push({ from: ca, to: cb, zBottom: cc.zBottom, zTop: cc.zTop }); - } - } - } - - // Öffnungs-Löcher, die ein z-Teilstück vertikal berühren, auf den Box-Start - // `a` umrechnen (render3d klemmt u/z selbst auf die Box). An der INNERSTEN - // Schicht (li = letztes Band) weicht das Loch bei Fenstern mit - // `WindowType.innerLayerRecess` rundum um die eigene Schichtdicke zurück - // (Schicht-Rücksprung an der Laibung) — die anderen Schichten bleiben bündig. - const isInnermostBand = li === bands.length - 1; - const recessDepth = b.thickness; - const emitPiece = (a: number, bb: number, zb: number, ztStart: number, ztEnd: number): void => { - const zt = Math.max(ztStart, ztEnd); - const segHoles = holes - .filter((h) => h.zTop > zb + EPS && h.zBottom < zt - EPS) - .map((h) => { - const widen = isInnermostBand && h.recessInnerLayer; - return widen - ? { - from: h.from - a - recessDepth, - to: h.to - a + recessDepth, - zBottom: h.zBottom - recessDepth, - zTop: h.zTop + recessDepth, - } - : { from: h.from - a, to: h.to - a, zBottom: h.zBottom, zTop: h.zTop }; - }); - if (segHoles.length > 0 && Math.abs(ztStart - ztEnd) > EPS) { - // Schräge Oberkante und Löcher im selben Körper geht nicht (render3d): gestuft annähern. - const k = Math.max(1, Math.ceil((bb - a) / ROOF_CLIP_STEP)); - for (let i = 0; i < k; i++) { - const sa = a + ((bb - a) * i) / k; - const sb = a + ((bb - a) * (i + 1)) / k; - const zm = ztStart + ((ztEnd - ztStart) * (i + 0.5)) / k; - emitPiece(sa, sb, zb, zm, zm); - } - return; - } - const drop: [number, number] = [zt - ztStart, zt - ztEnd]; - pushSegment(out, wall, a, bb, zb, zt, b.thickness, b.offset, b.color, wall.id, b.hatch, b.materialIndex, segHoles, bandCutMeta(b), drop); - }; - - for (const [a, bb] of axisPieces) { - // Nur die Decken-z-Schnitte, die dieses Achsen-Teilstück wirklich treffen. - const local = bandZCuts - .map((c) => ({ from: Math.max(a, c.from), to: Math.min(bb, c.to), zBottom: c.zBottom, zTop: c.zTop })) - .filter((c) => c.to > c.from + EPS); - if (local.length === 0) { - // Kein Decken-Überlapp auf diesem Achsenstück ⇒ volle Höhe (Band läuft - // durch) — ausser ein Dach kappt den Top (s. {@link clipPieceToRoofs}). - clipPieceToRoofs(project, wall, u, n, b.offset, a, bb, zBottom, zTop, emitPiece); - continue; - } - // Achse [a,bb] an allen Überdeckungs-Grenzen in elementare Teilstücke - // zerlegen; je Teilstück nur die dort greifenden Decken-z-Intervalle - // subtrahieren (unbedeckte Teilstücke behalten die volle Höhe). - const bounds = new Set([a, bb]); - for (const c of local) { - bounds.add(c.from); - bounds.add(c.to); - } - const xs = [...bounds].sort((p, q) => p - q); - for (let i = 0; i < xs.length - 1; i++) { - const xa = xs[i]; - const xb = xs[i + 1]; - if (xb - xa <= EPS) continue; - const mid = (xa + xb) / 2; - const zCutters = local - .filter((c) => c.from <= mid && c.to >= mid) - .map((c): [number, number] => [c.zBottom, c.zTop]); - // Terminierung (Zuschnitt) statt reiner z-Subtraktion: bei "below"/"above" - // endet die Wand an der Decke, statt oben wieder aufzutauchen (s. - // {@link terminateOrSubtractSpans}). "both"/undefined = heutiges Verhalten. - for (const [zb, zt] of terminateOrSubtractSpans(zBottom, zTop, zCutters, wall.sliceTermination)) { - clipPieceToRoofs(project, wall, u, n, b.offset, xa, xb, zb, zt, emitPiece); - } - } + for (const wall of walls) { + const { bands, stacked } = resolveWallBands(project, wall, layered); + bandsOf.push(bands); + const { zBottom, zTop } = wallVerticalExtent(project, wall); + let floor = -1; + if (layered) { + floor = floorIndex.get(wall.floorId) ?? -1; + if (floor < 0) { + floor = floorIndex.size; + floorIndex.set(wall.floorId, floor); + writeFloor(floors, project, wall.floorId); } } - return; + w.num(floor, wall.start.x, wall.start.y, wall.end.x, wall.end.y, zBottom, zTop, layered ? 1 : 0, stacked ? 1 : 0); + if (wall.referenceOffset != null) w.num(3, wall.referenceOffset); + else w.num(wall.referenceLine === "left" ? 1 : wall.referenceLine === "right" ? 2 : 0, 0); + const term = wall.sliceTermination === "below" || wall.sliceTermination === "above" ? TERMINATION[wall.sliceTermination] : 0; + w.num(wallThicknessSafe(project, wall), term, bands.length); + for (const b of bands) w.num(b.thickness, b.priority ?? Number.NaN); + + // Öffnungen (Fenster und Türen): Achsen-Intervall + vertikale Ausdehnung. + const slot = w.slot(); + let nOpenings = 0; + for (const op of openingsOfWall(project, wall.id)) { + const iv = openingInterval(wall, op); + if (!iv) continue; + const v = openingVerticalExtent(project, wall, op); + const recess = op.kind === "window" && getWindowType(project, op)?.innerLayerRecess === true; + w.num(iv.from, iv.to, v.zBottom, v.zTop, recess ? 1 : 0); + nOpenings++; + } + w.set(slot, nOpenings); + writeWallCuts(w, layered ? joins?.get(wall.id) : undefined); } - // ── Schnitt-Pfad (layered=false): unveränderte Pfeiler/Brüstung/Sturz- - // Segmentierung (Owner-Kompatibilität mit toSection.ts::wallSegmentOwners). - // Ohne Aussparungen: ein durchgehender Quader je Schicht. - if (cutouts.length === 0) { - emitSeg(0, axisLen, zBottom, zTop); - return; - } - - // Wand entlang der Achse durchlaufen: volle Pfeiler zwischen den Aussparungen, - // Brüstung/Sturz im Öffnungsbereich. Überlappende Cutouts werden über `cursor` - // zusammengefasst. - let cursor = 0; - for (const { from, to, oBottom, oTop } of cutouts) { - const segFrom = Math.max(cursor, from); - if (from > cursor) { - // Voller Wandpfeiler bis zur Aussparung. - emitSeg(cursor, from, zBottom, zTop); + const floorBuf = new FlatWriter().num(floorIndex.size).done(); + const r = new FlatReader(core().wall_bands_flat(w.done(), concat(floorBuf, floors.done()))); + const nWalls = Math.min(r.count(), walls.length); + for (let i = 0; i < nWalls; i++) { + const wall = walls[i]; + const bands = bandsOf[i]; + const dx = wall.end.x - wall.start.x; + const dy = wall.end.y - wall.start.y; + for (let n = r.count(); n > 0; n--) { + const b = bands[r.num()]; + const start: [number, number] = [r.num(), r.num()]; + const end: [number, number] = [r.num(), r.num()]; + const zb = r.num(); + const zt = r.num(); + const sloped = r.num() === 1; + const topDrop: [number, number] = [r.num(), r.num()]; + const holes: RHole[] = []; + for (let k = r.count(); k > 0; k--) holes.push({ from: r.num(), to: r.num(), zBottom: r.num(), zTop: r.num() }); + if (!b) continue; + const cut = bandCutMeta(b); + out.push({ + start, + end, + thickness: b.thickness, + height: zt - zb, + baseElevation: zb, + ...(sloped ? { topDrop } : {}), + color: b.color, + layers: [], + wallId: wall.id, + ...(b.hatch ? { hatch: withTopAngle(b.hatch, dx, dy) } : {}), + ...(b.materialIndex != null ? { materialIndex: b.materialIndex } : {}), + ...(holes.length > 0 ? { holes } : {}), + ...(cut ? { cut } : {}), + }); } - if (to > segFrom) { - // Brüstung unter der Öffnung (bei Türen entfällt sie, da oBottom == zBottom). - if (oBottom > zBottom + EPS) { - emitSeg(segFrom, to, zBottom, oBottom); - } - // Sturz über der Öffnung (bis zum Wandkopf). - if (oTop < zTop - EPS) { - emitSeg(segFrom, to, oTop, zTop); - } - } - cursor = Math.max(cursor, to); - } - // Restlicher Wandpfeiler bis zum Achsenende. - if (cursor < axisLen) { - emitSeg(cursor, axisLen, zBottom, zTop); } } + +function concat(a: Float64Array, b: Float64Array): Float64Array { + const out = new Float64Array(a.length + b.length); + out.set(a); + out.set(b, a.length); + return out; +} diff --git a/src/plan/toWalls3d/shared.ts b/src/plan/toWalls3d/shared.ts index af2d088b..b553892b 100644 --- a/src/plan/toWalls3d/shared.ts +++ b/src/plan/toWalls3d/shared.ts @@ -262,7 +262,7 @@ export interface RWall { /** * Echte rechteckige Löcher (Fenster/Türen) in DIESEM Wandkörper (siehe * {@link RHole}). Nur im 3D-Viewer-Pfad (`projectToModel3d` mit - * `layeredWalls:true`) gesetzt: dort emittiert `emitWall` EINEN RWall pro + * `layeredWalls:true`) gesetzt: dort emittiert `emitWalls` EINEN RWall pro * Schicht-Band über die volle Achse mit ALLEN Öffnungen als `holes` — statt der * Pfeiler/Brüstung/Sturz-Segment-Boxen. So bildet EIN Körper auch versetzt * übereinanderliegende Fenster ab (das kann die Segment-Zerlegung nicht). Der