From c59619d1fc6bdc4c11c66d75a5ab0ac2869bc4f0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 04:17:22 +0000 Subject: [PATCH] [K3c] Schnitt und Ansicht im Kern: Abfragen sectionPlan/elevationPlan liefern den Plan-Puffer v2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Neu: core/src/plan/section.rs (toSection.ts, generateSectionPlan, sectionOpenings.ts) und core/src/plan/elevation.rs (toElevation.ts) rechnen auf dem Projekt-Dokument: Besitzer-Zuordnung, Schicht-Bänder, Stil, Decken-Terminierung, Dominanz, Treppen, Monolith, Abzugskörper, Körper, Gelände, Schnitt-Tiefe, geschnittene Fenster/Türen; Ansicht mit Eck-Verlängerung, Verdeckung, Schatten und Painter-Reihenfolge. Der Prismen-Schnitt läuft über render3d::section::cut_section (Kern hängt an render3d ohne Features); die frühere JSON-Reise der Zahlen wird bitgleich nachgebildet. Aus TS kommen nur die truck-Körper (Float64Array). Die TS-Fassade (plan/sectionCore.ts) liefert lazy Pläne wie generatePlan; Viewport, CLI und MCP laufen darüber. CLI section/elevation kann --format json (render2d-Szene). Gleichheit (vorübergehender Test sectionPort.parity.test.ts): Primitive (Object.is), Ausmass, Szene und SVG gegen die TS-Fassung — Beispiel, 60 Zufallsprojekte, Kacheln 6x6; CLI-SVG byte-gleich. Ausnahme: durchgesickerte render3d-Schraffur nicht zuordenbarer Bänder wird zur vorgesehenen Rückfall-Schraffur (s. TODO). Die alte TS-Fassung bleibt bis nach den Leistungs-Schritten für den Vergleich stehen. Nicht in der Tauri-App angesehen. --- TODO.md | 13 + src-tauri/core/Cargo.lock | 8 + src-tauri/core/Cargo.toml | 2 + src-tauri/core/src/plan/elevation.rs | 757 ++++++++++++ src-tauri/core/src/plan/mod.rs | 2 + src-tauri/core/src/plan/section.rs | 1683 ++++++++++++++++++++++++++ src-tauri/core/src/queries.rs | 2 + src/cli/main.ts | 4 + src/core/document.ts | 6 +- src/core/index.ts | 13 +- src/plan/sectionBench.test.ts | 66 + src/plan/sectionCore.ts | 164 +++ src/plan/sectionParity.testing.ts | 173 +++ src/plan/sectionPort.parity.test.ts | 197 +++ src/views/viewportContent.tsx | 44 +- 15 files changed, 3094 insertions(+), 40 deletions(-) create mode 100644 src-tauri/core/src/plan/elevation.rs create mode 100644 src-tauri/core/src/plan/section.rs create mode 100644 src/plan/sectionBench.test.ts create mode 100644 src/plan/sectionCore.ts create mode 100644 src/plan/sectionParity.testing.ts create mode 100644 src/plan/sectionPort.parity.test.ts diff --git a/TODO.md b/TODO.md index 57348e8d..b614d84a 100644 --- a/TODO.md +++ b/TODO.md @@ -112,6 +112,19 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern ✅ Netz-Ebenenschnitt (Körper/Gelände) + Ringe→Flächen (`mesh_section.rs`; behebt nebenbei: rückwärts geschlossene Ringe gingen verloren). ✅ Dach-Schnittspur (Cyrus–Beck, lineare Oberkante, Verschmelzen) in `plan_section.rs`. ✅ Abzugskörper-Geometrie (`voids.rs`: Polygon minus Schneider mit Schlüsselloch-Stegen, Strecke ausserhalb, Schnitt-Rechtecke); behebt: bei mehreren getrennten Aussparungen wurde nichts abgezogen. + ◐ (29.10.) Schnitt und Ansicht als Kern-Abfragen `sectionPlan`/`elevationPlan` (`core/src/plan/{section,elevation}.rs`) auf dem + Dokument, Ausgabe Plan-Puffer v2 mit Pick-Ids (lazy gelesen wie `generatePlan`): Besitzer-Zuordnung, Schicht-Bänder, Stil, + Decken-Terminierung, Dominanz, Treppen, Monolith, Abzugskörper, Gelände, Schnitt-Tiefe, geschnittene Fenster/Türen + (`sectionOpenings`), Ansicht mit Eck-Verlängerung, Verdeckung, Schatten, Painter. Der Prismen-Schnitt läuft über + `render3d::section::cut_section` (Kern hängt an render3d ohne Features); Zahlen, die früher über JSON in render3d + reisten, werden bitgleich nachgebildet (kürzeste Darstellung, serde_json ohne `float_roundtrip`). Aus TS kommen nur + noch die truck-Körper (flach, `Float64Array`). Gleichheit: Primitive (Object.is, auch −0), Ausmass, render2d-Szene und + SVG gegen die TS-Fassung — Beispiel (40 Linien), 60 Zufallsprojekte (Dächer aller Formen, Treppentypen, Öffnungen, + Abzugskörper, Gelände, Overrides, Terminierung, Tiefe) × 3 Optionssätze, gekacheltes Projekt 6×6; CLI-SVG byte-gleich. + Ausnahme (Fehler der alten Fassung): eine render3d-interne Schraffur (Muster als Zahl) sickerte bei nicht zuordenbaren + Decken-/Treppen-Bändern als Plan-Schraffur durch (GPU: Diagonale, SVG: keine) — jetzt die vorgesehene + Rückfall-Schraffur. Ursache bleibt offen: `slabSegmentOwners` zählt Decken, das Schnitt-Modell emittiert je + Deckenschicht und Treppentritt eine Platte (Index-Versatz; mehrschichtige Decken im Schnitt falsch geschichtet). Rest in TS (28.10.): Stil-Auflösung (Bauteil, Schraffur, Farbe, Linienstil, Pick-IDs, Painter-Reihenfolge) in `generatePlan*.ts`, `toSection.ts` (Besitzer-Zuordnung, Schichtbänder), `toElevation.ts` (Orchestrierung), `sectionOpenings.ts`, `planUnderlay.ts`, `drawing2d.ts`. Das ist kein Rechenanteil mehr, sondern liest das Modell; es zieht mit [K4] um. diff --git a/src-tauri/core/Cargo.lock b/src-tauri/core/Cargo.lock index 6ee3e324..12a715a5 100644 --- a/src-tauri/core/Cargo.lock +++ b/src-tauri/core/Cargo.lock @@ -31,6 +31,7 @@ dependencies = [ "console_error_panic_hook", "i_overlay", "kernel2d", + "render3d", "serde", "serde_json", "ts-rs", @@ -156,6 +157,13 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "render3d" +version = "0.1.0" +dependencies = [ + "serde", +] + [[package]] name = "rustversion" version = "1.0.23" diff --git a/src-tauri/core/Cargo.toml b/src-tauri/core/Cargo.toml index 030de901..71f1c260 100644 --- a/src-tauri/core/Cargo.toml +++ b/src-tauri/core/Cargo.toml @@ -22,6 +22,8 @@ i_overlay = { version = "9.1", default-features = false } serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order", "float_roundtrip"] } kernel2d = { path = "../kernel2d" } +# Analytischer Schnitt-Extraktor (`section::cut_section`, GPU-frei, nur serde) für Schnitt/Ansicht im Kern ([K3c]). +render3d = { path = "../render3d", default-features = false } wasm-bindgen = { version = "0.2", optional = true } console_error_panic_hook = { version = "0.1", optional = true } # TS-Typen aus dem Rust-Modell ([K4] S4): `src/model/types.generated.ts`, s. `model/ts_export.rs`. diff --git a/src-tauri/core/src/plan/elevation.rs b/src-tauri/core/src/plan/elevation.rs new file mode 100644 index 00000000..455e9c68 --- /dev/null +++ b/src-tauri/core/src/plan/elevation.rs @@ -0,0 +1,757 @@ +//! Ansicht auf dem Dokument ([K3c]): Rust-Gegenstück zu `src/plan/toElevation.ts` (Orchestrierung, +//! Stil, Painter-Reihenfolge). Die Geometrie (Flächen, Eck-Verlängerung, Öffnungen, Verdeckung, +//! Schatten, XOR-Umriss) rechnet `plan_elevation.rs`; hier werden sie aus dem Dokument gespeist, +//! gestylt, mit Pick-Ids versehen und fern → nah sortiert. Zahlsemantik wie in TS. + +use super::prim::Primitive; +use super::section::{line, polygon, v2, Acc, LevelSpec, Visibility}; +use super::style::no_hatch; +use crate::js_fmt::js_number; +use crate::jsmath::{hypot, hypot2}; +use crate::jsnum::{max, min, round}; +use crate::model::*; +use crate::model3d::{self, RSlab, RWall}; +use crate::plan::overrides::js_trim; +use std::collections::HashMap; + +const EDGE_INK: &str = "#2b3039"; +const EDGE_MM: f64 = 0.13; +const FRAME_MM: f64 = 0.18; +const GLASS_FILL_MONO: &str = "#c4c8cd"; +const GLASS_FILL_COLOR: &str = "#9fc2d9"; +const SHADOW_FILL: &str = "#8f959e"; +const OPENING_SHADOW_FILL: &str = "#a7adb5"; +const GROUND_INK: &str = "#1f242c"; +const GROUND_MM: f64 = 0.5; +const FRAME_FILL_COLOR: &str = "#d9d9d4"; +const SILL_FILL_COLOR: &str = "#cccccb"; +const DOOR_LEAF_FILL_COLOR: &str = "#ede6d9"; +const SYMBOL_INK: &str = "#7d858f"; +const ROOF_RGB_FALLBACK: [f64; 3] = [0.72, 0.45, 0.36]; +const EPS: f64 = 1e-6; + +type Pt = [f64; 2]; + +/// `hexToRgb` der Ansicht (mit JS-`trim`). +fn hex_to_rgb(hex: &str, fallback: [f64; 3]) -> [f64; 3] { + let t = js_trim(hex); + let h = t.strip_prefix('#').unwrap_or(t); + if h.len() != 6 || !h.bytes().all(|b| b.is_ascii_hexdigit()) { + return fallback; + } + let p = |i: usize| u32::from_str_radix(&h[i..i + 2], 16).unwrap_or(0) as f64 / 255.0; + [p(0), p(2), p(4)] +} + +/// `rgbToHex`. +fn rgb_to_hex(c: [f64; 3]) -> String { + let b = |v: f64| -> String { + let x = max(0.0, min(255.0, round(v * 255.0))); + if x.is_nan() { + return "NaN".into(); + } + format!("{:02x}", x as u32) + }; + format!("#{}{}{}", b(c[0]), b(c[1]), b(c[2])) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Role { + Wall, + Slab, + Roof, +} + +struct Face { + pts: Vec, + depth: f64, + depth_min: f64, + depth_max: f64, + role: Role, + id: String, + fill: [f64; 3], + normal: [f64; 3], +} + +/// `elevationFrame` flach: `[P, N, U]`. +fn frame_of(plane: &super::section::Plane) -> [f64; 9] { + let [nx, ny, nz] = plane.normal; + let l = hypot(&[nx, ny, nz]); + let n_len = if l == 0.0 || l.is_nan() { 1.0 } else { l }; + let ux = nz / n_len; + let uz = -nx / n_len; + let l = hypot2(ux, uz); + let u_len = if l == 0.0 || l.is_nan() { 1.0 } else { l }; + let p = plane.point; + [p[0], p[1], p[2], nx / n_len, ny / n_len, nz / n_len, ux / u_len, 0.0, uz / u_len] +} + +struct RoofIn { + id: String, + fill: [f64; 3], + planes: Vec>, + gables: Vec>, +} + +/// `projectFaces`. +fn project_faces(frame: &[f64; 9], walls: &[RWall], slabs: &[RSlab], roofs: &[RoofIn]) -> Vec { + let mut w = vec![walls.len() as f64]; + for x in walls { + w.extend([x.start[0], x.start[1], x.end[0], x.end[1], x.thickness, x.height, x.base_elevation]); + } + let mut sl = vec![slabs.len() as f64]; + for x in slabs { + sl.extend([x.z_bottom, x.z_top, x.outline.len() as f64]); + for q in &x.outline { + sl.extend(q); + } + } + let mut r = vec![roofs.len() as f64]; + for roof in roofs { + r.extend([roof.planes.len() as f64, roof.gables.len() as f64]); + for poly in roof.planes.iter().chain(&roof.gables) { + r.push(poly.len() as f64); + for q in poly { + r.extend(q); + } + } + } + let f = crate::plan_elevation::faces(frame, &w, &sl, &r); + let mut out = Vec::new(); + let n = f.first().copied().unwrap_or(0.0) as usize; + let mut i = 1; + for _ in 0..n { + let role = match f[i] as i64 { + 0 => Role::Wall, + 1 => Role::Slab, + _ => Role::Roof, + }; + let src = f[i + 1] as usize; + let count = f[i + 8] as usize; + let pts = (0..count).map(|j| [f[i + 9 + 2 * j], f[i + 10 + 2 * j]]).collect(); + let (id, fill) = match role { + Role::Wall => (walls[src].wall_id.clone(), walls[src].color), + Role::Slab => (slabs[src].ceiling_id.clone(), slabs[src].color), + Role::Roof => (roofs[src].id.clone(), roofs[src].fill), + }; + out.push(Face { pts, depth: f[i + 2], depth_min: f[i + 3], depth_max: f[i + 4], role, id, fill, normal: [f[i + 5], f[i + 6], f[i + 7]] }); + i += 9 + 2 * count; + } + out +} + +/// `collectRoofFaces`. +fn collect_roof_faces(p: &Project, frame: &[f64; 9]) -> Result, String> { + let mut roofs = Vec::new(); + for roof in p.roofs.as_deref().unwrap_or(&[]) { + let g = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof)); + let layers = p.roof_layers(roof); + let outer = layers.first(); + let fill = match roof.color.as_deref().filter(|c| !c.is_empty()) { + Some(c) => hex_to_rgb(c, ROOF_RGB_FALLBACK), + None => match outer.filter(|l| !l.component_id.is_empty()) { + Some(l) => hex_to_rgb(&p.component(&l.component_id).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {}", l.component_id))?.color, ROOF_RGB_FALLBACK), + None => ROOF_RGB_FALLBACK, + }, + }; + roofs.push(RoofIn { id: roof.id.clone(), fill, planes: g.planes.clone(), gables: g.gables.clone() }); + } + Ok(project_faces(frame, &[], &[], &roofs)) +} + +/// `extendWallCornersForElevation`. +fn extend_wall_corners(p: &Project, rwalls: &mut [RWall], u: (f64, f64)) { + let mut floors: HashMap<&str, usize> = HashMap::new(); + let mut b = vec![p.walls.len() as f64]; + for w in &p.walls { + let n = floors.len(); + let k = *floors.entry(w.floor_id.as_str()).or_insert(n); + let thickness = p.wall_type(w).map_or(0.2, |t| t.layers.iter().fold(0.0, |s, l| s + l.thickness)); + b.extend([k as f64, w.start.x, w.start.y, w.end.x, w.end.y, thickness / 2.0]); + } + let ext = crate::plan_elevation::wall_extensions(&b); + if ext.is_empty() { + return; + } + let mut by_wall: HashMap<&str, Vec> = HashMap::new(); + let ids: Vec = rwalls.iter().map(|r| r.wall_id.clone()).collect(); + for (i, id) in ids.iter().enumerate() { + by_wall.entry(id.as_str()).or_default().push(i); + } + let close = |a: [f64; 2], v: Vec2| (a[0] - v.x).abs() < 1e-6 && (a[1] - v.y).abs() < 1e-6; + for (k, w) in p.walls.iter().enumerate() { + let e_start = ext[1 + 2 * k]; + let e_end = ext[2 + 2 * k]; + if e_start <= EPS && e_end <= EPS { + continue; + } + let Some(pieces) = by_wall.get(w.id.as_str()) else { continue }; + let (dx, dz) = (w.end.x - w.start.x, w.end.y - w.start.y); + let len = hypot2(dx, dz); + if len < 1e-9 { + continue; + } + let (ux, uz) = (dx / len, dz / len); + if (ux * u.0 + uz * u.1).abs() < 0.35 { + continue; + } + if e_start > EPS { + if let Some(&i) = pieces.iter().find(|&&i| close(rwalls[i].start, w.start)) { + let s = rwalls[i].start; + rwalls[i].start = [s[0] - ux * e_start, s[1] - uz * e_start]; + } + } + if e_end > EPS { + if let Some(&i) = pieces.iter().find(|&&i| close(rwalls[i].end, w.end)) { + let e = rwalls[i].end; + rwalls[i].end = [e[0] + ux * e_end, e[1] + uz * e_end]; + } + } + } +} + +struct ProjOpening { + pts: [Pt; 4], + depth: f64, + glass: Vec<[Pt; 4]>, + door_leaf: Vec<[Pt; 4]>, + divisions: Vec<(Pt, Pt)>, + sash_rects: Vec<[Pt; 4]>, + sill: Vec<[Pt; 4]>, + symbol: Vec<(Pt, Pt)>, + id: String, +} + +fn sash_kind(k: OpeningKind) -> f64 { + match k { + OpeningKind::Dreh => 1.0, + OpeningKind::Kipp => 2.0, + OpeningKind::Drehkipp => 3.0, + OpeningKind::Schiebe => 4.0, + _ => 0.0, + } +} + +/// `collectOpenings`. +fn collect_openings(p: &Project, frame: &[f64; 9]) -> Vec { + let mut b = vec![0.0]; + let mut ids: Vec<&str> = Vec::new(); + for wall in &p.walls { + let thickness = p.wall_type(wall).map_or(0.2, |t| t.layers.iter().fold(0.0, |s, l| s + l.thickness)); + for op in p.openings_of_wall(&wall.id) { + let axis = hypot2(wall.end.x - wall.start.x, wall.end.y - wall.start.y); + let from = max(0.0, min(op.position, axis)); + let to = max(from, min(op.position + op.width, axis)); + if to - from < 1e-4 { + continue; + } + let (zb, zt) = p.wall_vertical_extent(wall); + let ob = zb + max(0.0, op.sill_height); + let ot = min(zt, ob + op.height); + let door = op.kind == ElementKind::Door; + let dt = if door { p.door_type(op) } else { None }; + let wt = if door { None } else { p.window_type(op) }; + b.extend([ + wall.start.x, + wall.start.y, + wall.end.x, + wall.end.y, + thickness, + from, + to, + ob, + ot, + if door { 1.0 } else { 0.0 }, + if dt.is_some_and(|d| d.leaf_style == DoorTypeLeafStyle::Glas) { 1.0 } else { 0.0 }, + dt.and_then(|d| d.glazing_ratio).unwrap_or(f64::NAN), + wt.and_then(|t| t.frame_width).unwrap_or(0.06), + wt.and_then(|t| t.transom_height).unwrap_or(0.0), + wt.and_then(|t| t.mullion_rows).unwrap_or(f64::NAN), + wt.and_then(|t| t.mullion_cols).unwrap_or(f64::NAN), + if matches!(wt.and_then(|t| t.sill_board), Some(WindowTypeSillBoard::Keine | WindowTypeSillBoard::Innen)) { 0.0 } else { 1.0 }, + wt.map_or(0.0, |t| sash_kind(t.kind)), + ]); + // Flügel: (pfosten, postWidth, autoWidth, width, opening, hingeLeft). + let mut sashes: Vec<[f64; 6]> = Vec::new(); + if !door { + match wt { + Some(t) => match t.sashes.as_deref().filter(|s| !s.is_empty()) { + Some(list) => { + for s in list { + sashes.push([ + if s.kind == SashDefKind::Pfosten { 1.0 } else { 0.0 }, + s.post_width.unwrap_or(f64::NAN), + if s.auto_width == Some(false) { 0.0 } else { 1.0 }, + s.width.unwrap_or(f64::NAN), + s.opening.map_or(-1.0, sash_kind), + if s.hinge_side.unwrap_or(SashDefHingeSide::Left) == SashDefHingeSide::Left { 1.0 } else { 0.0 }, + ]); + } + } + None => { + let wc = if t.wing_count == 0.0 || t.wing_count.is_nan() { 1.0 } else { t.wing_count }; + let n = max(1.0, round(wc)) as usize; + for i in 0..n { + sashes.push([0.0, f64::NAN, 1.0, f64::NAN, sash_kind(t.kind), if i % 2 == 0 { 1.0 } else { 0.0 }]); + } + } + }, + None => sashes.push([0.0, f64::NAN, 1.0, f64::NAN, -1.0, 1.0]), + } + } + b.push(sashes.len() as f64); + for s in &sashes { + b.extend(s); + } + ids.push(&op.id); + b[0] += 1.0; + } + } + let f = crate::plan_elevation::openings(frame, &b); + let mut out = Vec::new(); + if f.is_empty() { + return out; + } + let mut i = 1; + let quads = |i: &mut usize| -> Vec<[Pt; 4]> { + let n = f[*i] as usize; + *i += 1; + let mut list = Vec::with_capacity(n); + for _ in 0..n { + list.push([[f[*i], f[*i + 1]], [f[*i + 2], f[*i + 3]], [f[*i + 4], f[*i + 5]], [f[*i + 6], f[*i + 7]]]); + *i += 8; + } + list + }; + let lines = |i: &mut usize| -> Vec<(Pt, Pt)> { + let n = f[*i] as usize; + *i += 1; + let mut list = Vec::with_capacity(n); + for _ in 0..n { + list.push(([f[*i], f[*i + 1]], [f[*i + 2], f[*i + 3]])); + *i += 4; + } + list + }; + for k in 0..f[0] as usize { + let vis = f[i]; + i += 1; + if vis == 0.0 { + continue; + } + let depth = f[i]; + let pts = [[f[i + 2], f[i + 3]], [f[i + 4], f[i + 5]], [f[i + 6], f[i + 7]], [f[i + 8], f[i + 9]]]; + i += 10; + let glass = quads(&mut i); + let door_leaf = quads(&mut i); + let divisions = lines(&mut i); + let sash_rects = quads(&mut i); + let sill = quads(&mut i); + let symbol = lines(&mut i); + out.push(ProjOpening { pts, depth, glass, door_leaf, divisions, sash_rects, sill, symbol, id: ids[k].to_string() }); + } + out +} + +fn encode_shadow_faces(faces: &[&Face]) -> Vec { + let mut b = vec![faces.len() as f64]; + for f in faces { + b.extend([f.depth, f.depth_min, f.pts.len() as f64]); + for q in &f.pts { + b.extend(q); + } + } + b +} + +/// Eintrag des Painter-Stroms. +struct Item { + depth: f64, + seq: usize, + rank: Option, + prim: Primitive, +} + +enum Pending { + Line { a: Pt, b: Pt, depth: f64 }, + Item { depth: f64, rank: Option, prim: Primitive }, +} + +fn outline_line(a: Pt, b: Pt) -> Primitive { + line(v2(a[0], a[1]), v2(b[0], b[1]), "elevation-outline", EDGE_MM, EDGE_INK) +} + +/// Schlüssel einer Kante wie `edgeKey` (gerundet auf 0,1 mm, Endpunkte sortiert als Text). +fn edge_key(a: Pt, b: Pt) -> String { + let r = |v: f64| js_number(round(v * 1e4)); + let ka = format!("{},{}", r(a[0]), r(a[1])); + let kb = format!("{},{}", r(b[0]), r(b[1])); + if ka < kb { + format!("{ka}|{kb}") + } else { + format!("{kb}|{ka}") + } +} + +/// Schlüssel einer `Map` (SameValueZero). +fn num_key(x: f64) -> u64 { + if x == 0.0 { + 0 + } else if x.is_nan() { + u64::MAX + } else { + x.to_bits() + } +} + +fn poly_prim(pts: Vec, fill: &str, stroke: &str, w: f64, opening: Option<&str>) -> Primitive { + let mut pr = polygon(pts, fill, stroke, w, no_hatch()); + if let (Primitive::Polygon { opening_id, .. }, Some(id)) = (&mut pr, opening) { + *opening_id = Some(id.into()); + } + pr +} + +/// `generateElevationPlan`: Primitive und Ausmass; `None` ohne Ansichtslinie. +pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono: bool, vis: &Visibility) -> Result, [f64; 4])>, String> { + let Some(plane) = level.plane() else { return Ok(None) }; + let frame = frame_of(&plane); + let mut walls = model3d::emit_walls(p, false)?; + let mut slabs = model3d::emit_slabs(p); + slabs.extend(model3d::emit_stairs(p, false)); + extend_wall_corners(p, &mut walls, (frame[6], frame[8])); + let mut faces = project_faces(&frame, &walls, &slabs, &[]); + faces.extend(collect_roof_faces(p, &frame)?); + + // Kategorie einer Fläche (erstes Element mit der id, wie `find`). + let mut wall_cat: HashMap<&str, &str> = HashMap::new(); + for w in &p.walls { + wall_cat.entry(w.id.as_str()).or_insert(w.category_code.as_str()); + } + let mut ceil_cat: HashMap<&str, &str> = HashMap::new(); + for c in p.ceilings.as_deref().unwrap_or(&[]) { + ceil_cat.entry(c.id.as_str()).or_insert(c.category_code.as_str()); + } + let mut roof_cat: HashMap<&str, &str> = HashMap::new(); + for r in p.roofs.as_deref().unwrap_or(&[]) { + roof_cat.entry(r.id.as_str()).or_insert(r.category_code.as_str()); + } + let category = |f: &Face| -> Option<&str> { + if f.id.is_empty() { + return None; + } + match f.role { + Role::Wall => wall_cat.get(f.id.as_str()).copied(), + Role::Slab => ceil_cat.get(f.id.as_str()).copied(), + Role::Roof => roof_cat.get(f.id.as_str()).copied(), + } + }; + if vis.has_vis && vis.has_display { + faces.retain(|f| category(f).is_none_or(|c| vis.visible(c) && vis.render(c))); + } + let greyed = |f: &Face| vis.has_display && category(f).is_some_and(|c| vis.greyed(c)); + + let openings = collect_openings(p, &frame); + let mut occ = vec![(faces.len() + openings.len()) as f64]; + for f in &faces { + occ.extend([f.depth_max, f.pts.len() as f64]); + for q in &f.pts { + occ.extend(q); + } + } + for op in &openings { + occ.extend([op.depth, 4.0]); + for q in &op.pts { + occ.extend(q); + } + } + let occluded = { + let mut b = vec![openings.len() as f64]; + for op in &openings { + let q = &op.pts; + b.extend([(q[0][0] + q[1][0] + q[2][0] + q[3][0]) / 4.0, (q[0][1] + q[1][1] + q[2][1] + q[3][1]) / 4.0, op.depth]); + } + crate::plan_elevation::occluded_points(&occ, &b) + }; + + let mut acc = Acc::new(); + // Jede Fläche trägt ihre Bauteilfarbe (Wand/Decke aus dem 3D-Modell, Dach aus der Eindeckung). + let fill_for = |fill: [f64; 3]| -> String { if mono { "#ffffff".into() } else { rgb_to_hex(fill) } }; + let mut items: Vec = Vec::new(); + let mut seq = 0usize; + let mut pending: Vec = Vec::new(); + + let mut roof_edges: HashMap> = HashMap::new(); + for (fi, f) in faces.iter().enumerate() { + if f.role != Role::Roof || f.id.is_empty() { + continue; + } + for i in 0..f.pts.len() { + roof_edges.entry(edge_key(f.pts[i], f.pts[(i + 1) % f.pts.len()])).or_default().push(fi); + } + } + let coplanar_seam = |fi: usize, a: Pt, b: Pt| -> bool { + let f = &faces[fi]; + if f.role != Role::Roof || f.id.is_empty() { + return false; + } + roof_edges.get(&edge_key(a, b)).is_some_and(|list| { + list.iter().any(|&oi| { + let o = &faces[oi]; + oi != fi && o.id == f.id && f.normal[0] * o.normal[0] + f.normal[1] * o.normal[1] + f.normal[2] * o.normal[2] > 1.0 - 1e-9 + }) + }) + }; + let mut group_order: Vec = Vec::new(); + let mut groups: HashMap, f64)> = HashMap::new(); + for (fi, f) in faces.iter().enumerate() { + let pts: Vec = f + .pts + .iter() + .map(|q| { + acc.add(q[0], q[1]); + v2(q[0], q[1]) + }) + .collect(); + let is_roof = f.role == Role::Roof; + let frontal = !is_roof && f.depth_max - f.depth_min < 1e-4; + if frontal { + let gk = num_key(round(f.depth * 1e4)); + groups + .entry(gk) + .or_insert_with(|| { + group_order.push(gk); + (Vec::new(), f.depth) + }) + .0 + .push(fi); + } else { + for i in 0..f.pts.len() { + let a = f.pts[i]; + let b = f.pts[(i + 1) % f.pts.len()]; + if coplanar_seam(fi, a, b) { + continue; + } + pending.push(Pending::Line { a, b, depth: f.depth_min - EPS * 5.0 }); + } + } + let mut prim = polygon(pts, &fill_for(f.fill), "none", 0.0, no_hatch()); + if let Primitive::Polygon { greyed: g, wall_id, ceiling_id, roof_id, .. } = &mut prim { + *g = Some(greyed(f)); + if !f.id.is_empty() { + match f.role { + Role::Wall => *wall_id = Some(f.id.clone()), + Role::Slab => *ceiling_id = Some(f.id.clone()), + Role::Roof => *roof_id = Some(f.id.clone()), + } + } + } + let rank = match f.role { + Role::Slab => 0.0, + Role::Wall => 1.0, + Role::Roof => 2.0, + }; + pending.push(Pending::Item { depth: f.depth, rank: Some(rank), prim }); + } + for gk in &group_order { + let (list, depth) = &groups[gk]; + let mut b = vec![list.len() as f64]; + for &fi in list { + b.push(faces[fi].pts.len() as f64); + for q in &faces[fi].pts { + b.extend(q); + } + } + let e = crate::plan_elevation::xor_outline(&b); + for k in 0..e.first().copied().unwrap_or(0.0) as usize { + let i = 1 + 4 * k; + pending.push(Pending::Line { a: [e[i], e[i + 1]], b: [e[i + 2], e[i + 3]], depth: depth - EPS * 5.0 }); + } + } + // Linien gebündelt gegen die Verdecker clippen (`flushPending`). + { + let mut q = vec![0.0]; + for pd in &pending { + if let Pending::Line { a, b, depth } = pd { + q.extend([a[0], a[1], b[0], b[1], *depth]); + q[0] += 1.0; + } + } + let r = crate::plan_elevation::clip_segments(&occ, &q); + let mut i = 1; + for pd in pending { + match pd { + Pending::Item { depth, rank, prim } => { + items.push(Item { depth, seq, rank, prim }); + seq += 1; + } + Pending::Line { a, b, depth } => { + let c = if r.is_empty() { + 1 + } else { + i += 1; + r[i - 1] as usize + }; + for _ in 0..c { + let (sa, sb) = if r.is_empty() { + (a, b) + } else { + let s = ([r[i], r[i + 1]], [r[i + 2], r[i + 3]]); + i += 4; + s + }; + acc.add(sa[0], sa[1]); + acc.add(sb[0], sb[1]); + items.push(Item { depth, seq, rank: None, prim: outline_line(sa, sb) }); + seq += 1; + } + } + } + } + } + + if shadows { + let wall_faces: Vec<&Face> = faces.iter().filter(|f| f.role == Role::Wall).collect(); + let mut casters: Vec<&Face> = faces.iter().filter(|f| f.role == Role::Slab).collect(); + casters.extend(faces.iter().filter(|f| f.role == Role::Roof)); + let f = crate::plan_elevation::shadows(&encode_shadow_faces(&wall_faces), &encode_shadow_faces(&casters)); + let mut i = 1; + for _ in 0..f.first().copied().unwrap_or(0.0) as usize { + let depth = f[i]; + let count = f[i + 1] as usize; + i += 2; + let pts: Vec = (0..count) + .map(|j| { + let (x, y) = (f[i + 2 * j], f[i + 2 * j + 1]); + acc.add(x, y); + v2(x, y) + }) + .collect(); + i += 2 * count; + items.push(Item { depth: depth - EPS * 10.0, seq, rank: None, prim: polygon(pts, SHADOW_FILL, "none", 0.0, no_hatch()) }); + seq += 1; + } + } + + for (k, op) in openings.iter().enumerate() { + if occluded.get(1 + k) == Some(&1.0) { + continue; + } + let mut to_vec = |q: &[Pt]| -> Vec { + q.iter() + .map(|p| { + acc.add(p[0], p[1]); + v2(p[0], p[1]) + }) + .collect() + }; + let d = op.depth - EPS * 100.0; + let id = Some(op.id.as_str()); + let mut push = |prim: Primitive| { + items.push(Item { depth: d, seq, rank: None, prim }); + seq += 1; + }; + push(poly_prim(to_vec(&op.pts), if mono { "#ffffff" } else { FRAME_FILL_COLOR }, EDGE_INK, FRAME_MM, id)); + for r in &op.sill { + push(poly_prim(to_vec(r), if mono { "#ffffff" } else { SILL_FILL_COLOR }, EDGE_INK, EDGE_MM, id)); + } + for r in &op.sash_rects { + push(poly_prim(to_vec(r), "none", EDGE_INK, EDGE_MM, id)); + } + for r in &op.glass { + push(poly_prim(to_vec(r), if mono { GLASS_FILL_MONO } else { GLASS_FILL_COLOR }, EDGE_INK, EDGE_MM, id)); + } + for r in &op.door_leaf { + push(poly_prim(to_vec(r), if mono { "#ffffff" } else { DOOR_LEAF_FILL_COLOR }, EDGE_INK, EDGE_MM, id)); + } + if shadows { + let q = &op.pts; + let lerp = |a: Pt, b: Pt, t: f64| -> Pt { [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t] }; + let quad_at = |fa: f64, fz: f64| lerp(lerp(q[0], q[1], fa), lerp(q[3], q[2], fa), fz); + let w_u = hypot2(q[1][0] - q[0][0], q[1][1] - q[0][1]); + let h_v = hypot2(q[3][0] - q[0][0], q[3][1] - q[0][1]); + let f_u = min(0.3, 0.08 / max(w_u, 1e-6)); + let f_v = min(0.3, 0.08 / max(h_v, 1e-6)); + for (fa0, fa1, fz0, fz1) in [(0.0, 1.0, 1.0 - f_v, 1.0), (0.0, f_u, 0.0, 1.0 - f_v)] { + let r = [quad_at(fa0, fz0), quad_at(fa1, fz0), quad_at(fa1, fz1), quad_at(fa0, fz1)]; + push(polygon(to_vec(&r), OPENING_SHADOW_FILL, "none", 0.0, no_hatch())); + } + } + for (a, b) in &op.divisions { + push(line(v2(a[0], a[1]), v2(b[0], b[1]), "elevation-division", EDGE_MM, EDGE_INK)); + } + for (a, b) in &op.symbol { + let mut l = line(v2(a[0], a[1]), v2(b[0], b[1]), "elevation-opening-symbol", 0.1, SYMBOL_INK); + if let Primitive::Line { dash, .. } = &mut l { + *dash = Some(Some(vec![2.2, 1.8])); + } + push(l); + } + } + + // Painter: fern zuerst; Gleichstand nach Rang (Decke < Wand < Dach < Rest), dann Reihenfolge. + let nz = |d: f64| if d.is_nan() { 0.0 } else { d }; + items.sort_by(|a, b| { + let d = nz(b.depth - a.depth); + if d != 0.0 { + return super::section::cmp_num(d); + } + let r = nz(a.rank.unwrap_or(3.0) - b.rank.unwrap_or(3.0)); + if r != 0.0 { + return super::section::cmp_num(r); + } + a.seq.cmp(&b.seq) + }); + let mut prims: Vec = items.into_iter().map(|it| it.prim).collect(); + if acc.min_x.is_finite() && acc.min_y.is_finite() { + prims.push(line(v2(acc.min_x, acc.min_y), v2(acc.max_x, acc.min_y), "elevation-ground", GROUND_MM, GROUND_INK)); + } + Ok(Some((prims, acc.bounds()))) +} + +/// Abfrage `elevationPlan`: `args` = `[mono, shadows]`, `text` = `{"level": {...}, "hasVis", "invisible", +/// "hasDisplay", "norender", "grey"}`. Puffer mit einer Gruppe und Ausmass; ohne Ansichtslinie ohne Gruppen. +pub fn elevation_plan_buf(p: &Project, args: &[f64], text: &str) -> Result, String> { + let v: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("Ansicht-Argumente: {e}"))?; + let level = LevelSpec::from_json(v.get("level").unwrap_or(&serde_json::Value::Null)); + let vis = Visibility::from_json(&v); + let mono = args.first().is_some_and(|&x| x != 0.0); + let shadows = args.get(1).is_some_and(|&x| x != 0.0); + let mut w = crate::plan_buf::Writer::new(true); + if let Some((prims, bounds)) = elevation_primitives(p, &level, shadows, mono, &vis)? { + w.group(&prims); + w.bounds = Some(bounds); + } + Ok(w.finish()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample() -> Project { + serde_json::from_str(include_str!("../../tests/fixtures/sample_project.json")).unwrap() + } + + #[test] + fn farben_wie_ts() { + assert_eq!(rgb_to_hex([1.0, 0.0, 0.5]), "#ff0080"); + assert_eq!(rgb_to_hex([f64::NAN, 2.0, -1.0]), "#NaNff00"); + assert_eq!(hex_to_rgb(" #ff0000 ", [0.0; 3]), [1.0, 0.0, 0.0]); + assert_eq!(hex_to_rgb("#abc", [0.5; 3]), [0.5; 3]); + } + + #[test] + fn beispiel_ansicht() { + let p = sample(); + let l = p.drawing_levels.iter().find(|l| l.id == "ansicht-sued").unwrap(); + let level = LevelSpec::from_json(&serde_json::to_value(l).unwrap()); + let (prims, b) = elevation_primitives(&p, &level, true, false, &Visibility::default()).unwrap().unwrap(); + let json = serde_json::to_string(&prims).unwrap(); + assert!(json.contains("\"wallId\":\"W1\"") && json.contains("\"openingId\":\"O1\"") && json.contains("elevation-ground"), "{json}"); + assert!(json.contains("#8f959e"), "Schlagschatten fehlt"); + assert!(b[2] > b[0]); + // Painter: die Bodenlinie zuletzt + assert!(matches!(prims.last(), Some(Primitive::Line { cls, .. }) if cls == "elevation-ground")); + } +} diff --git a/src-tauri/core/src/plan/mod.rs b/src-tauri/core/src/plan/mod.rs index bedb2154..d23c6a57 100644 --- a/src-tauri/core/src/plan/mod.rs +++ b/src-tauri/core/src/plan/mod.rs @@ -8,3 +8,5 @@ pub mod domains; pub mod walls; pub mod stairs; pub mod context; +pub mod section; +pub mod elevation; diff --git a/src-tauri/core/src/plan/section.rs b/src-tauri/core/src/plan/section.rs new file mode 100644 index 00000000..80dd2cbb --- /dev/null +++ b/src-tauri/core/src/plan/section.rs @@ -0,0 +1,1683 @@ +//! Schnitt auf dem Dokument ([K3c]): Rust-Gegenstück zu `src/plan/toSection.ts` (Besitzer-Zuordnung, +//! Schicht-Bänder, Stil-Auflösung, Decken-Terminierung, Dominanz, Treppen, Monolith-Vereinigung, +//! Abzugskörper, Körper, Gelände, Schnitt-Tiefe), `generateSectionPlan` (Primitive mit Pick-Ids) und +//! `sectionOpenings.ts` (geschnittene Fenster/Türen). Der analytische Prismen-Schnitt läuft über +//! `render3d::section::cut_section` (dieselbe Rechnung wie früher im render3d-WASM). Rechenreihenfolge +//! und Zahlsemantik wie in TS (`jsnum`, `jsmath`), damit die Ausgabe bitgleich bleibt. +//! +//! Einheiten: Meter; Ausgabe in (u, v) = (entlang der Ebene, absolute Höhe). + +use super::prim::{HatchRender, Primitive}; +use super::style::*; +use crate::jsmath::hypot2; +use crate::jsnum::{atan2, max, min, round}; +use crate::model::*; +use crate::model3d::{self, RRoofLayer, RSlab, RWall}; +use std::collections::{HashMap, HashSet}; + +/// Tinte der Schnitt-Poché-Umrisslinie (dunkles Grau). +const SECTION_INK: &str = "#1f242c"; +const SECTION_VISIBLE_INK: &str = "#2b3039"; +const SECTION_HIDDEN_INK: &str = "#8a929c"; +const SECTION_CUT_OUTLINE_MM: f64 = 0.35; +const SECTION_VISIBLE_MM: f64 = 0.18; +const SECTION_GROUND_MM: f64 = 0.5; +const SECTION_HIDDEN_MM: f64 = 0.13; +const SECTION_HIDDEN_DASH: [f64; 2] = [0.12, 0.08]; +const OWNER_EPS: f64 = 1e-4; +/// Achswinkel geschnittener Wände/Decken für wandrelative Muster (s. `toSection.ts`). +const SECTION_WALL_AXIS_ANGLE_DEG: f64 = 90.0; +const SECTION_SLAB_AXIS_ANGLE_DEG: f64 = 90.0; +/// Seitenrand (m) der Geländelinie um den Inhalt des Schnitts. +const TERRAIN_MARGIN: f64 = 6.0; +/// Neutrale Füllung geschnittener freier Körper. +const BODY_FILL: &str = "#d9dde2"; + +/// Rückfall-Schraffur der Cut-Flächen ohne auflösbares Bauteil. +fn section_hatch() -> HatchRender { + HatchRender { pattern: HatchPattern::Diagonal, scale: 1.0, angle: 45.0, color: HATCH_INK.into(), line_weight: 0.13, ..no_hatch_base() } +} + +fn no_hatch_base() -> HatchRender { + HatchRender { dash: None, ..no_hatch() } +} + +// ── Ebene ───────────────────────────────────────────────────────────────────── + +/// Schnitt-/Ansichtsebene einer Zeichnungsebene (`sectionPlaneFromLevel`): Punkt (x, 0, y) und +/// horizontale Normale (Blickrichtung). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Plane { + pub point: [f64; 3], + pub normal: [f64; 3], +} + +impl Plane { + /// u-Achse in Grundriss-Koordinaten (`sectionUAxisModel`): Blickrichtungs-RECHTS. + pub fn u_model(&self) -> (f64, f64) { + (self.normal[2], -self.normal[0]) + } + pub fn base(&self) -> (f64, f64) { + (self.point[0], self.point[2]) + } +} + +/// Die Felder einer Schnitt-/Ansichtsebene, die die Projektion bestimmen (aus dem Aufruf). +#[derive(Clone, Debug, Default)] +pub struct LevelSpec { + pub kind: String, + pub line: Option<[Vec2; 2]>, + pub direction_sign: Option, + pub depth: Option, + pub shadows: bool, +} + +impl LevelSpec { + pub fn from_json(v: &serde_json::Value) -> LevelSpec { + let num = |k: &str| v.get(k).and_then(|x| x.as_f64()); + let pt = |q: &serde_json::Value| -> Option { Some(Vec2 { x: q.get("x")?.as_f64()?, y: q.get("y")?.as_f64()? }) }; + let line = v.get("linePoints").and_then(|l| l.as_array()).and_then(|a| Some([pt(a.first()?)?, pt(a.get(1)?)?])); + LevelSpec { + kind: v.get("kind").and_then(|k| k.as_str()).unwrap_or_default().to_string(), + line, + direction_sign: num("directionSign"), + depth: num("depth"), + shadows: v.get("shadows").and_then(|b| b.as_bool()).unwrap_or(false), + } + } + + pub fn plane(&self) -> Option { + let [p0, p1] = self.line?; + let dx = p1.x - p0.x; + let dy = p1.y - p0.y; + let len = hypot2(dx, dy); + if len < 1e-9 { + return None; + } + let ux = dx / len; + let uy = dy / len; + let sign = self.direction_sign.unwrap_or(1.0); + Some(Plane { point: [p0.x, 0.0, p0.y], normal: [-uy * sign, 0.0, ux * sign] }) + } +} + +/// Sichtbarkeit der Kategorien (UI-Zustand des Aufrufers): `vis` = Codes, die in `visibleCodes` +/// fehlen (nur mit `has_vis`), `norender`/`grey` aus dem Darstellungsmodus (nur mit `has_display`). +#[derive(Clone, Debug, Default)] +pub struct Visibility { + pub has_vis: bool, + pub invisible: HashSet, + pub has_display: bool, + pub norender: HashSet, + pub grey: HashSet, +} + +impl Visibility { + pub fn from_json(v: &serde_json::Value) -> Visibility { + let set = |k: &str| -> HashSet { v.get(k).and_then(|a| a.as_array()).map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect()).unwrap_or_default() }; + Visibility { + has_vis: v.get("hasVis").and_then(|b| b.as_bool()).unwrap_or(false), + invisible: set("invisible"), + has_display: v.get("hasDisplay").and_then(|b| b.as_bool()).unwrap_or(false), + norender: set("norender"), + grey: set("grey"), + } + } + /// `visibleCodes.has(code)` (ohne `visibleCodes`: wahr). + pub fn visible(&self, code: &str) -> bool { + !self.has_vis || !self.invisible.contains(code) + } + /// `categoryDisplay(code).render` (Rückfall SHOW_ALL). + pub fn render(&self, code: &str) -> bool { + !self.norender.contains(code) + } + pub fn greyed(&self, code: &str) -> bool { + self.grey.contains(code) + } +} + +// ── Cut-Bänder ──────────────────────────────────────────────────────────────── + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Kind { + Wall, + Slab, + Roof, + Body, +} + +/// Ein geschnittenes Band (`SectionCutPolygon`). +#[derive(Clone, Debug)] +pub struct Cut { + pub kind: Kind, + pub index: usize, + pub pts: Vec<[f64; 2]>, + pub nse: Option>, + pub fill: Option, + pub hatch: Option, + pub join_priority: Option, + pub component_id: Option, + pub source_id: Option, + pub category: Option, + pub stair_id: Option, +} + +impl Cut { + fn new(kind: Kind, index: usize, pts: Vec<[f64; 2]>) -> Cut { + Cut { kind, index, pts, nse: None, fill: None, hatch: None, join_priority: None, component_id: None, source_id: None, category: None, stair_id: None } + } +} + +/// Eine projizierte Kante (`SectionEdge`). +#[derive(Clone, Copy, Debug)] +pub struct Edge { + pub kind: Kind, + pub index: usize, + pub a: [f64; 2], + pub b: [f64; 2], +} + +/// Geländelinie. +#[derive(Clone, Debug)] +pub struct Profile { + pub category: Option, + pub pts: Vec<[f64; 2]>, +} + +/// Ergebnis eines Schnitts (`SectionOutput`). +#[derive(Clone, Debug, Default)] +pub struct Output { + pub cuts: Vec, + pub visible: Vec, + pub hidden: Vec, + pub profiles: Vec, +} + +/// Ein truck-Körper (aus TS, asynchron gebaut): Index in `extrudedSolids` + Netz. +pub struct BodyMesh { + pub index: usize, + pub positions: Vec, + pub indices: Vec, +} + +/// Liest `[n, (index, nPos, pos…, nIdx, idx…) × n]`; Unsinn → `None`. +pub fn read_bodies(buf: &[f64]) -> Option> { + if buf.is_empty() { + return Some(Vec::new()); + } + let mut r = crate::flat_read::Reader::new(buf); + let n = r.count()?; + let mut out = Vec::with_capacity(n); + for _ in 0..n { + let index = r.count()?; + let np = r.count()?; + let positions = (0..np).map(|_| r.num()).collect::>>()?; + let ni = r.count()?; + let indices = (0..ni).map(|_| r.num()).collect::>>()?; + out.push(BodyMesh { index, positions, indices }); + } + Some(out) +} + +/// f32 aus render3d wie über JSON gereist: kürzeste Dezimaldarstellung, als f64 gelesen. +fn js_f32(x: f32) -> f64 { + if !x.is_finite() { + return 0.0; // JSON `null` → 0 in der Arithmetik + } + // serde_json schrieb f32 mit der kürzesten Darstellung (Gleichstand → gerade Ziffer), JS las sie. + serde_json::to_string(&x).ok().and_then(|t| t.parse::().ok()).unwrap_or(0.0) +} + +fn kind_of(k: render3d::ComponentKind) -> Kind { + match k { + render3d::ComponentKind::Wall => Kind::Wall, + render3d::ComponentKind::Slab => Kind::Slab, + render3d::ComponentKind::Roof => Kind::Roof, + } +} + +/// Zehnerpotenzen wie `POW10` in serde_json (Literale `1e0` … `1e308`). +fn pow10(k: usize) -> f64 { + use std::sync::OnceLock; + static T: OnceLock> = OnceLock::new(); + T.get_or_init(|| (0..=308).map(|i| format!("1e{i}").parse::().unwrap_or(f64::INFINITY)).collect())[k] +} + +/// Zahl, wie sie früher über JSON in den render3d-Schnitt reiste: JS schreibt die kürzeste +/// Dezimaldarstellung, serde_json (dort ohne `float_roundtrip`) liest sie als Ganzzahl-Mantisse +/// mal Zehnerpotenz und rundet dann auf f32. Bitgleich zur alten Eingabe (auch wo die Lesung +/// um eine Stelle daneben liegt). +fn json_f32(x: f64) -> f32 { + if x == 0.0 || !x.is_finite() { + return 0.0; + } + if x.fract() == 0.0 && x.abs() < 1e21 { + return x as f32; // JS schreibt eine Ganzzahl, serde liest u64/i64 + } + // Ziffern und Exponent der kürzesten Darstellung (wie JS: Gleichstand → gerade Ziffer). + let s = serde_json::to_string(&x.abs()).unwrap_or_default(); + let (mant, exp) = s.split_once(['e', 'E']).unwrap_or((&s, "0")); + let (int_part, frac_part) = mant.split_once('.').unwrap_or((mant, "")); + let digits = format!("{int_part}{frac_part}"); + let mut exponent: i32 = exp.parse::().unwrap_or(0) - frac_part.len() as i32; + let sig: u64 = digits.parse().unwrap_or(0); + let mut f = sig as f64; + loop { + let k = exponent.unsigned_abs() as usize; + if k <= 308 { + if exponent >= 0 { + f *= pow10(k); + } else { + f /= pow10(k); + } + break; + } + if f == 0.0 || exponent >= 0 { + break; + } + f /= 1e308; + exponent += 308; + } + (if x < 0.0 { -f } else { f }) as f32 +} + +fn f32s2(v: [f64; 2]) -> [f32; 2] { + [json_f32(v[0]), json_f32(v[1])] +} + +fn f32s3(v: [f64; 3]) -> [f32; 3] { + [json_f32(v[0]), json_f32(v[1]), json_f32(v[2])] +} + +fn wall_input(w: &RWall) -> render3d::WallInput { + render3d::WallInput { + start: f32s2(w.start), + end: f32s2(w.end), + thickness: json_f32(w.thickness), + height: json_f32(w.height), + base_elevation: json_f32(w.base_elevation), + top_drop: w.top_drop.map_or([0.0, 0.0], f32s2), + color: f32s3(w.color), + openings: Vec::new(), + layers: Some(Vec::new()), + holes: w + .holes + .as_deref() + .unwrap_or(&[]) + .iter() + .map(|h| render3d::types::Hole { from: json_f32(h.from), to: json_f32(h.to), z_bottom: json_f32(h.z_bottom), z_top: json_f32(h.z_top) }) + .collect(), + material_index: None, + hatch: None, + cut: None, + } +} + +fn slab_input(s: &RSlab) -> render3d::SlabInput { + render3d::SlabInput { + outline: s.outline.iter().map(|q| f32s2(*q)).collect(), + z_bottom: json_f32(s.z_bottom), + z_top: json_f32(s.z_top), + color: f32s3(s.color), + hatch: None, + cut: None, + monolith: s.monolith.clone(), + } +} + +fn roof_input(r: &RRoofLayer) -> render3d::types::RoofLayerInput { + render3d::types::RoofLayerInput { polygon: r.polygon.iter().map(|q| f32s3(*q)).collect(), normal: f32s3(r.normal), thickness: json_f32(r.thickness), color: f32s3(r.color), hatch: None, cut: None } +} + +// ── Besitzer (Emissions-Reihenfolge des Schnitt-Modells) ───────────────────── + +fn opening_extent(p: &Project, w: &Wall, o: &Opening) -> (f64, f64) { + let (zb, zt) = p.wall_vertical_extent(w); + let sill = max(0.0, o.sill_height); + let ob = zb + sill; + (ob, min(zt, ob + o.height)) +} + +fn opening_interval(w: &Wall, o: &Opening) -> Option<(f64, f64)> { + let axis = hypot2(w.end.x - w.start.x, w.end.y - w.start.y); + let from = max(0.0, min(o.position, axis)); + let to = max(from, min(o.position + o.width, axis)); + if to - from < 1e-4 { + return None; + } + Some((from, to)) +} + +/// Je emittiertem Wand-Teilquader die Quellwand (`wallSegmentOwners`). +pub fn wall_segment_owners(p: &Project) -> Vec<&Wall> { + let mut owners = Vec::new(); + for wall in &p.walls { + let (z_bottom, z_top) = p.wall_vertical_extent(wall); + let axis_len = hypot2(wall.end.x - wall.start.x, wall.end.y - wall.start.y); + if axis_len < 1e-9 || z_top - z_bottom <= OWNER_EPS { + continue; + } + let mut push = |from: f64, to: f64, zb: f64, zt: f64| { + if to - from <= OWNER_EPS || zt - zb <= OWNER_EPS { + return; + } + owners.push(wall); + }; + let mut cutouts: Vec<(f64, f64, f64, f64)> = Vec::new(); + for op in p.openings_of_wall(&wall.id) { + let Some((from, to)) = opening_interval(wall, op) else { continue }; + let (ob, ot) = opening_extent(p, wall, op); + cutouts.push((from, to, ob, ot)); + } + // `Array.sort` mit `a.from - b.from` (stabil). + cutouts.sort_by(|a, b| cmp_num(a.0 - b.0)); + if cutouts.is_empty() { + push(0.0, axis_len, z_bottom, z_top); + continue; + } + let mut cursor = 0.0; + for &(from, to, ob, ot) in &cutouts { + let seg_from = max(cursor, from); + if from > cursor { + push(cursor, from, z_bottom, z_top); + } + if to > seg_from { + if ob > z_bottom + OWNER_EPS { + push(seg_from, to, z_bottom, ob); + } + if ot < z_top - OWNER_EPS { + push(seg_from, to, ot, z_top); + } + } + cursor = max(cursor, to); + } + if cursor < axis_len { + push(cursor, axis_len, z_bottom, z_top); + } + } + owners +} + +/// Ordnung eines JS-Vergleichs `(a, b) => d` (NaN/0 = gleich). +pub fn cmp_num(d: f64) -> std::cmp::Ordering { + if d < 0.0 { + std::cmp::Ordering::Less + } else if d > 0.0 { + std::cmp::Ordering::Greater + } else { + std::cmp::Ordering::Equal + } +} + +/// Je emittierter Deckenplatte die Quelldecke (`slabSegmentOwners`). +pub fn slab_segment_owners(p: &Project) -> Vec<&Ceiling> { + let mut owners = Vec::new(); + for c in p.ceilings.as_deref().unwrap_or(&[]) { + if c.outline.len() < 3 { + continue; + } + let (zb, zt) = p.ceiling_vertical_extent(c); + if zt - zb <= OWNER_EPS { + continue; + } + owners.push(c); + } + owners +} + +// ── Stil-Auflösung ──────────────────────────────────────────────────────────── + +fn sum_thickness(layers: &[Layer]) -> f64 { + layers.iter().fold(0.0, |s, l| s + l.thickness) +} + +fn ceiling_layers<'a>(p: &'a Project, c: &Ceiling) -> Option<&'a [Layer]> { + model3d::ceiling_type_ref(p, c).map(|t| t.2) +} + +/// `resolveWallSectionStyle`. +fn wall_section_style(p: &Project, wall: &Wall) -> Option<(String, HatchRender)> { + let wt = p.wall_type(wall)?; + let mut best: Option<&Component> = None; + for layer in &wt.layers { + let comp = p.component(&layer.component_id)?; + if best.is_none_or(|b| comp.join_priority > b.join_priority) { + best = Some(comp); + } + } + let best = best?; + let category = p.layer_category(&wall.category_code); + let angle = atan2(wall.end.y - wall.start.y, wall.end.x - wall.start.x) * 180.0 / std::f64::consts::PI; + let hatch_id = resolve_hatch_id(wall.hatch_id.as_deref(), wall.hatch_source, category, Some(&best.hatch_id)).unwrap_or(&best.hatch_id); + let hatch = resolve_hatch(p, hatch_id, Some(angle), resolve_foreground(best, wall.foreground.as_deref(), category, wall.foreground_source), None)?; + Some((poche_fill(hatch.pattern).to_string(), hatch)) +} + +/// `resolveCeilingSectionStyle`. +fn ceiling_section_style(p: &Project, c: &Ceiling) -> Option<(String, HatchRender)> { + let layers = ceiling_layers(p, c)?; + let first = layers.first()?; + let comp = p.component(&first.component_id)?; + let category = p.layer_category(&c.category_code); + let hatch_id = resolve_hatch_id(c.hatch_id.as_deref(), c.hatch_source, category, Some(&comp.hatch_id)).unwrap_or(&comp.hatch_id); + let hatch = resolve_hatch(p, hatch_id, None, resolve_foreground(comp, c.foreground.as_deref(), category, c.foreground_source), None)?; + Some((poche_fill(hatch.pattern).to_string(), hatch)) +} + +fn wall_representative_priority(p: &Project, wall: &Wall) -> Option { + let wt = p.wall_type(wall)?; + let mut best: Option = None; + for layer in &wt.layers { + let jp = p.component(&layer.component_id)?.join_priority; + if best.is_none_or(|b| jp > b) { + best = Some(jp); + } + } + best +} + +fn wall_representative_component_id(p: &Project, wall: &Wall) -> Option { + let wt = p.wall_type(wall)?; + let mut best: Option<&str> = None; + let mut best_prio = f64::NEG_INFINITY; + for layer in &wt.layers { + let jp = p.component(&layer.component_id)?.join_priority; + if best.is_none() || jp > best_prio { + best = Some(&layer.component_id); + best_prio = jp; + } + } + best.map(String::from) +} + +fn ceiling_representative_component_id(p: &Project, c: &Ceiling) -> Option { + ceiling_layers(p, c)?.first().map(|l| l.component_id.clone()) +} + +fn ceiling_representative_priority(p: &Project, c: &Ceiling) -> Option { + let first = ceiling_layers(p, c)?.first()?; + Some(p.component(&first.component_id)?.join_priority) +} + +/// Bounding-Box `[uMin, uMax, vMin, vMax]` über `Math.min(...)`/`Math.max(...)`. +fn bbox(pts: &[[f64; 2]]) -> [f64; 4] { + let mut b = [f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY]; + for q in pts { + b[0] = min(b[0], q[0]); + b[1] = max(b[1], q[0]); + b[2] = min(b[2], q[1]); + b[3] = max(b[3], q[1]); + } + b +} + +fn rect_of_band(c: &Cut) -> Option<[f64; 4]> { + (c.pts.len() >= 3).then(|| bbox(&c.pts)) +} + +fn missing(what: &str, id: &str) -> String { + format!("{what}: {id}") +} + +/// Bauteil-Stil einer Schicht (Füllung, Schraffur) mit dem Override des Elements (`split*Layers`). +#[allow(clippy::too_many_arguments)] +fn layer_style( + p: &Project, + comp: &Component, + hatch_id: Option<&str>, + hatch_source: Option, + fg: Option<&str>, + fg_source: Option, + bg: Option<&str>, + bg_source: Option, + category: Option<&LayerCategory>, + angle: f64, +) -> Result<(String, HatchRender), String> { + let hid = resolve_hatch_id(hatch_id, hatch_source, category, Some(&comp.hatch_id)).unwrap_or(&comp.hatch_id); + let hatch = resolve_hatch(p, hid, Some(angle), resolve_foreground(comp, fg, category, fg_source), None).ok_or_else(|| missing("Unbekannte Schraffur", hid))?; + let bg = resolve_background(comp, bg, category, bg_source); + let fill = bg.map(String::from).unwrap_or_else(|| poche_fill(hatch.pattern).to_string()); + Ok((fill, hatch)) +} + +/// `splitSlabLayers`: liegende Teil-Rechtecke je Schicht (oben → unten). +fn split_slab_layers(cp: &Cut, p: &Project, layers: &[Layer], owner: &Ceiling) -> Result, String> { + let total = sum_thickness(layers); + let [u_min, u_max, v_min, v_max] = bbox(&cp.pts); + let v_span = v_max - v_min; + if total <= 1e-9 || v_span <= 1e-9 { + return Ok(vec![cp.clone()]); + } + let scale = v_span / total; + let category = p.layer_category(&owner.category_code); + let mut out = Vec::with_capacity(layers.len()); + let mut acc = 0.0; + for layer in layers { + let comp = p.component(&layer.component_id).ok_or_else(|| missing("Unbekanntes Bauteil-Material", &layer.component_id))?; + let (fill, hatch) = layer_style(p, comp, owner.hatch_id.as_deref(), owner.hatch_source, owner.foreground.as_deref(), owner.foreground_source, owner.background.as_deref(), owner.background_source, category, SECTION_SLAB_AXIS_ANGLE_DEG)?; + let v_top = v_max - acc * scale; + acc += layer.thickness; + let v_bottom = v_max - acc * scale; + let mut c = Cut::new(cp.kind, cp.index, vec![[u_min, v_top], [u_max, v_top], [u_max, v_bottom], [u_min, v_bottom]]); + c.fill = Some(fill); + c.hatch = Some(hatch); + c.join_priority = Some(comp.join_priority); + c.component_id = Some(comp.id.clone()); + c.source_id = cp.source_id.clone(); + c.category = cp.category.clone(); + out.push(c); + } + Ok(out) +} + +/// `wallLayersReversedInU`. +fn wall_layers_reversed_in_u(w: &Wall, u: (f64, f64)) -> bool { + let (ax, ay) = (w.end.x - w.start.x, w.end.y - w.start.y); + if hypot2(ax, ay) < 1e-9 { + return false; + } + let l = hypot2(ax, ay); + let l = if l == 0.0 || l.is_nan() { 1.0 } else { l }; + let (nx, ny) = (ax / l, ay / l); + let (bx, by) = (-ny, nx); + bx * u.0 + by * u.1 < 0.0 +} + +/// `splitWallLayers`: stehende Teil-Rechtecke je Schicht quer zur Dicke (u). +fn split_wall_layers(cp: &Cut, p: &Project, layers: &[Layer], owner: &Wall, u_world: (f64, f64)) -> Result, String> { + let total = sum_thickness(layers); + let [u_min, u_max, v_min, v_max] = bbox(&cp.pts); + let u_span = u_max - u_min; + if total <= 1e-9 || u_span <= 1e-9 { + return Ok(vec![cp.clone()]); + } + let scale = u_span / total; + let ordered: Vec<&Layer> = if wall_layers_reversed_in_u(owner, u_world) { layers.iter().rev().collect() } else { layers.iter().collect() }; + let category = p.layer_category(&owner.category_code); + let mut out = Vec::with_capacity(layers.len()); + let mut acc = 0.0; + for layer in ordered { + let comp = p.component(&layer.component_id).ok_or_else(|| missing("Unbekanntes Bauteil-Material", &layer.component_id))?; + let (fill, hatch) = layer_style(p, comp, owner.hatch_id.as_deref(), owner.hatch_source, owner.foreground.as_deref(), owner.foreground_source, owner.background.as_deref(), owner.background_source, category, SECTION_WALL_AXIS_ANGLE_DEG)?; + let u_left = u_min + acc * scale; + acc += layer.thickness; + let u_right = u_min + acc * scale; + let mut c = Cut::new(cp.kind, cp.index, vec![[u_left, v_max], [u_right, v_max], [u_right, v_min], [u_left, v_min]]); + c.fill = Some(fill); + c.hatch = Some(hatch); + c.join_priority = Some(comp.join_priority); + c.component_id = Some(comp.id.clone()); + c.source_id = cp.source_id.clone(); + c.category = cp.category.clone(); + out.push(c); + } + Ok(out) +} + +/// `attachCutStyles`: Stil, Herkunft, Schicht-Bänder, Terminierung, Dominanz. +fn attach_cut_styles(cuts: Vec, p: &Project, plane: &Plane, walls: &[&Wall], slabs: &[&Ceiling]) -> Result, String> { + if cuts.is_empty() { + return Ok(cuts); + } + let u_world = plane.u_model(); + let roofs = p.roofs.as_deref().unwrap_or(&[]); + let mut bands: Vec = Vec::with_capacity(cuts.len()); + for mut cp in cuts { + match cp.kind { + Kind::Roof => { + let owner = roofs.get(cp.index); + cp.source_id = owner.map(|o| o.id.clone()); + cp.category = owner.map(|o| o.category_code.clone()); + bands.push(cp); + } + Kind::Wall => { + let owner = walls.get(cp.index).copied(); + cp.source_id = owner.map(|o| o.id.clone()); + cp.category = owner.map(|o| o.category_code.clone()); + if let Some(o) = owner { + let wt = p.wall_type(o).ok_or_else(|| missing("Unbekannter Wandtyp", &o.wall_type_id))?; + if wt.layers.len() > 1 { + bands.extend(split_wall_layers(&cp, p, &wt.layers, o, u_world)?); + continue; + } + } + if let Some((fill, hatch)) = owner.and_then(|o| wall_section_style(p, o)) { + cp.fill = Some(fill); + cp.hatch = Some(hatch); + } + cp.join_priority = owner.and_then(|o| wall_representative_priority(p, o)); + cp.component_id = owner.and_then(|o| wall_representative_component_id(p, o)); + bands.push(cp); + } + _ => { + let owner = slabs.get(cp.index).copied(); + cp.source_id = owner.map(|o| o.id.clone()); + cp.category = owner.map(|o| o.category_code.clone()); + if let Some(o) = owner { + let layers = ceiling_layers(p, o).ok_or_else(|| missing("Unbekannter Deckentyp", o.ceiling_type_id.as_deref().unwrap_or(&o.wall_type_id)))?; + if layers.len() > 1 { + bands.extend(split_slab_layers(&cp, p, layers, o)?); + continue; + } + if let Some((fill, hatch)) = ceiling_section_style(p, o) { + cp.fill = Some(fill); + cp.hatch = Some(hatch); + } + cp.join_priority = ceiling_representative_priority(p, o); + cp.component_id = ceiling_representative_component_id(p, o); + } + bands.push(cp); + } + } + } + let terminated = apply_wall_termination(bands, walls); + Ok(subtract_dominant_bands(terminated)) +} + +/// `applyWallTermination`: Wände mit `sliceTermination` "below"/"above" enden an der Decke. +fn apply_wall_termination(bands: Vec, walls: &[&Wall]) -> Vec { + const EPS_T: f64 = 1e-9; + const TOUCH: f64 = 0.05; + let slab_bands: Vec<([f64; 4], f64)> = bands.iter().filter(|b| b.kind == Kind::Slab).filter_map(|b| b.join_priority.map(|jp| (bbox(&b.pts), jp))).collect(); + if slab_bands.is_empty() { + return bands; + } + let mut out = Vec::with_capacity(bands.len()); + for b in bands { + if b.kind != Kind::Wall { + out.push(b); + continue; + } + let term = walls.get(b.index).and_then(|w| w.slice_termination); + let (Some(term @ (SliceTermination::Below | SliceTermination::Above)), Some(jp)) = (term, b.join_priority) else { + out.push(b); + continue; + }; + let wb = bbox(&b.pts); + let cutters: Vec<&([f64; 4], f64)> = slab_bands.iter().filter(|(sb, sjp)| *sjp > jp && sb[1] > wb[0] - TOUCH && sb[0] < wb[1] + TOUCH).collect(); + if cutters.is_empty() { + out.push(b); + continue; + } + if term == SliceTermination::Below { + let mut clip_top = f64::INFINITY; + for c in &cutters { + clip_top = min(clip_top, c.0[2]); + } + let top = min(clip_top, wb[3]); + if top > wb[2] + EPS_T { + out.push(Cut { pts: vec![[wb[0], top], [wb[1], top], [wb[1], wb[2]], [wb[0], wb[2]]], ..b }); + } + continue; + } + let mut clip_bottom = f64::NEG_INFINITY; + for c in &cutters { + clip_bottom = max(clip_bottom, c.0[3]); + } + let bottom = max(clip_bottom, wb[2]); + if bottom < wb[3] - EPS_T { + out.push(Cut { pts: vec![[wb[0], wb[3]], [wb[1], wb[3]], [wb[1], bottom], [wb[0], bottom]], ..b }); + } + } + out +} + +/// `subtractDominantBands` (Rechnung: `plan_section::dominant_bands`). +fn subtract_dominant_bands(bands: Vec) -> Vec { + let mut ids: HashMap<&str, usize> = HashMap::new(); + let mut b: Vec = Vec::with_capacity(1 + 7 * bands.len()); + b.push(bands.len() as f64); + for band in &bands { + let r = rect_of_band(band); + let mut comp = -1.0; + if let Some(id) = band.component_id.as_deref() { + let n = ids.len(); + let k = *ids.entry(id).or_insert(n); + comp = k as f64; + } + let r4 = r.unwrap_or([0.0; 4]); + b.extend([if r.is_some() { 1.0 } else { 0.0 }, r4[0], r4[1], r4[2], r4[3], band.join_priority.unwrap_or(f64::NAN), comp]); + } + let f = crate::plan_section::dominant_bands(&b); + let mut out = Vec::new(); + let Some(&n) = f.first() else { return out }; + let mut i = 1; + for _ in 0..n as usize { + let src = &bands[f[i] as usize]; + if f[i + 1] == 0.0 { + out.push(src.clone()); + } else { + let mut c = Cut::new(src.kind, src.index, vec![[f[i + 2], f[i + 5]], [f[i + 3], f[i + 5]], [f[i + 3], f[i + 4]], [f[i + 2], f[i + 4]]]); + c.fill = src.fill.clone(); + c.hatch = src.hatch.clone(); + c.join_priority = src.join_priority; + c.component_id = src.component_id.clone(); + c.source_id = src.source_id.clone(); + out.push(c); + } + i += 6; + } + out +} + +// ── Dächer ──────────────────────────────────────────────────────────────────── + +/// `appendRoofSections`: Schnittspur der Dachflächen, je Schicht ein Band. +fn append_roof_sections(cuts: &mut Vec, p: &Project, plane: &Plane) { + let roofs = p.roofs.as_deref().unwrap_or(&[]); + if roofs.is_empty() { + return; + } + let (bx, by) = plane.base(); + let (ux, uy) = plane.u_model(); + for (index, roof) in roofs.iter().enumerate() { + let eaves = p.roof_base_elevation(roof); + let geo = crate::roof::roof_geometry(&roof.params(), eaves); + let layers = p.roof_layers(roof); + let total = layers.iter().fold(0.0, |s, l| s + max(0.0, l.thickness)); + if total <= 1e-9 { + continue; + } + let mut pl: Vec = vec![geo.planes.len() as f64]; + for plane in &geo.planes { + pl.push(plane.len() as f64); + for q in plane { + pl.extend([q[0], q[1], q[2]]); + } + } + let sg = crate::plan_section::roof_segments(bx, by, ux, uy, &pl); + let n = sg.first().copied().unwrap_or(0.0) as usize; + for k in 0..n { + let o = 1 + 5 * k; + let (t_lo, t_hi, z0, z1, cos_t) = (sg[o], sg[o + 1], sg[o + 2], sg[o + 3], sg[o + 4]); + let mut prefix = 0.0; + for layer in &layers { + let t = max(0.0, layer.thickness); + if t <= 1e-9 { + continue; + } + let vt = t / max(cos_t, 1e-6); + let top0 = z0 - prefix; + let top1 = z1 - prefix; + prefix += vt; + let mut c = Cut::new(Kind::Roof, index, vec![[t_lo, top0], [t_hi, top1], [t_hi, top1 - vt], [t_lo, top0 - vt]]); + if !layer.component_id.is_empty() { + if let Some(h) = p.component(&layer.component_id).and_then(|comp| resolve_hatch(p, &comp.hatch_id, None, None, None)) { + c.fill = Some(poche_fill(h.pattern).to_string()); + c.hatch = Some(h); + } + } + cuts.push(c); + } + } + } +} + +// ── Monolith, Abzugskörper, Körper, Gelände, Tiefe ─────────────────────────── + +/// `unionRectOutlines` (Rechnung: `plan_section::union_outlines`). +fn union_rect_outlines(rects: &[[f64; 4]]) -> Vec> { + let mut b = vec![rects.len() as f64]; + for r in rects { + b.extend(r); + } + let f = crate::plan_section::union_outlines(&b); + let mut rings = Vec::new(); + let mut i = 1; + for _ in 0..f.first().copied().unwrap_or(0.0) as usize { + let count = f[i] as usize; + i += 1; + rings.push((0..count).map(|j| [f[i + 2 * j], f[i + 2 * j + 1]]).collect()); + i += 2 * count; + } + rings +} + +/// `mergeMonolithCuts`. +fn merge_monolith_cuts(cuts: Vec, slabs: &[RSlab]) -> Vec { + let mut order: Vec = Vec::new(); + let mut groups: HashMap> = HashMap::new(); + let mut out = Vec::new(); + for cp in cuts { + let g = if cp.kind == Kind::Slab { slabs.get(cp.index).and_then(|s| s.monolith.clone()).filter(|g| !g.is_empty()) } else { None }; + match g { + None => out.push(cp), + Some(g) => { + if !groups.contains_key(&g) { + order.push(g.clone()); + } + groups.entry(g).or_default().push(cp); + } + } + } + for g in order { + let list = groups.remove(&g).unwrap_or_default(); + if list.len() == 1 { + out.extend(list); + continue; + } + let rects: Vec<[f64; 4]> = list.iter().filter_map(rect_of_band).collect(); + if rects.len() != list.len() { + out.extend(list); + continue; + } + for ring in union_rect_outlines(&rects) { + out.push(Cut { pts: ring, ..list[0].clone() }); + } + } + out +} + +fn is_void_solid(s: &ExtrudedSolid) -> bool { + s.operation.as_deref() == Some("subtract") && s.brep.is_none() && s.taper.unwrap_or(0.0) < 1e-6 && s.points.len() >= 3 && s.height > 0.0 +} + +fn encode_rings(rings: &[&[[f64; 2]]]) -> Vec { + let mut b = vec![rings.len() as f64]; + for r in rings { + b.push(r.len() as f64); + for q in *r { + b.extend(q); + } + } + b +} + +/// `subtractVoidsInSection`. +fn subtract_voids_in_section(cuts: Vec, p: &Project, base: (f64, f64), u: (f64, f64)) -> Vec { + let mut rects: Vec> = Vec::new(); + let mut any = false; + for s in p.extruded_solids.as_deref().unwrap_or(&[]) { + if !is_void_solid(s) { + continue; + } + any = true; + let z0 = p.floor(&s.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0)) + s.base_offset.unwrap_or(0.0); + let z1 = z0 + s.height; + let mut pts = vec![s.points.len() as f64]; + for q in &s.points { + pts.extend([q.x, q.y]); + } + let f = crate::voids::section_rects_flat(&pts, &[base.0, base.1, u.0, u.1]); + for k in 0..f.first().copied().unwrap_or(0.0) as usize { + let (u0, u1) = (f[1 + 2 * k], f[2 + 2 * k]); + rects.push(vec![[u0, z0], [u1, z0], [u1, z1], [u0, z1]]); + } + } + if !any || rects.is_empty() { + return cuts; + } + let refs: Vec<&[[f64; 2]]> = rects.iter().map(|r| r.as_slice()).collect(); + let cutters = encode_rings(&refs); + let mut out = Vec::with_capacity(cuts.len()); + for cp in cuts { + if cp.pts.len() < 3 { + out.push(cp); + continue; + } + let ring = &encode_rings(&[cp.pts.as_slice()])[1..]; + let nse = cp.nse.as_deref().unwrap_or(&[]); + let mut ns = vec![nse.len() as f64]; + ns.extend(nse); + let f = crate::voids::subtract_rings_flat(ring, &cutters, &ns); + if f.is_empty() || f[0] < 0.0 { + out.push(cp); + continue; + } + let mut i = 1; + for _ in 0..f[0] as usize { + let n = f[i] as usize; + i += 1; + let pts: Vec<[f64; 2]> = (0..n).map(|j| [f[i + 2 * j], f[i + 2 * j + 1]]).collect(); + i += 2 * n; + let m = f[i] as usize; + i += 1; + let nse: Vec = f[i..i + m].to_vec(); + i += m; + out.push(Cut { pts, nse: (!nse.is_empty()).then_some(nse), ..cp.clone() }); + } + } + out +} + +/// Liest `[n, (k, u, v …) × n]` ab `i`. +fn read_rings(f: &[f64], i: &mut usize) -> Vec> { + let mut out = Vec::new(); + let n = f[*i] as usize; + *i += 1; + for _ in 0..n { + let k = f[*i] as usize; + *i += 1; + out.push((0..k).map(|j| [f[*i + 2 * j], f[*i + 2 * j + 1]]).collect()); + *i += 2 * k; + } + out +} + +/// `cutMeshWithPlane` (senkrecht): (Ringe, Linienzüge). +fn cut_mesh(positions: &[f64], indices: &[f64], base: (f64, f64), u: (f64, f64)) -> (Vec>, Vec>) { + let f = crate::mesh_section::cut(positions, indices, &[0.0, base.0, base.1, u.0, u.1]); + if f.is_empty() { + return (Vec::new(), Vec::new()); + } + let mut i = 0; + let rings = read_rings(&f, &mut i); + let lines = read_rings(&f, &mut i); + (rings, lines) +} + +/// `ringsToPolygons`. +fn rings_to_polygons(rings: &[Vec<[f64; 2]>]) -> Vec>> { + let refs: Vec<&[[f64; 2]]> = rings.iter().map(|r| r.as_slice()).collect(); + let f = crate::mesh_section::rings_to_polygons(&encode_rings(&refs)); + if f.is_empty() { + return Vec::new(); + } + let mut out = Vec::new(); + let mut i = 1; + for _ in 0..f[0] as usize { + let nr = f[i] as usize; + i += 1; + let mut set = Vec::with_capacity(nr); + for _ in 0..nr { + let count = f[i] as usize; + i += 1; + set.push((0..count).map(|j| [f[i + 2 * j], f[i + 2 * j + 1]]).collect()); + i += 2 * count; + } + out.push(set); + } + out +} + +/// `keyhole` (Rechnung: `voids::keyhole_flat`). +fn keyhole(poly: &[Vec<[f64; 2]>]) -> (Vec<[f64; 2]>, Vec) { + let refs: Vec<&[[f64; 2]]> = poly.iter().map(|r| r.as_slice()).collect(); + let f = crate::voids::keyhole_flat(&encode_rings(&refs)); + let n = f.first().copied().unwrap_or(0.0) as usize; + let pts = (0..n).map(|i| [f[1 + 2 * i], f[2 + 2 * i]]).collect(); + let nb = f.get(1 + 2 * n).copied().unwrap_or(0.0) as usize; + let bridges = (0..nb).map(|i| f[2 + 2 * n + i]).collect(); + (pts, bridges) +} + +/// `appendBodySections` + `attachBodyOwners`: geschnittene freie Körper. +fn append_body_sections(cuts: &mut Vec, p: &Project, bodies: &[BodyMesh], base: (f64, f64), u: (f64, f64)) { + let solids = p.extruded_solids.as_deref().unwrap_or(&[]); + for b in bodies { + let (rings, _) = cut_mesh(&b.positions, &b.indices, base, u); + for poly in rings_to_polygons(&rings) { + let (pts, nse) = if poly.len() > 1 { + let (pts, bridges) = keyhole(&poly); + let n = pts.len() as f64; + (pts, Some(bridges.into_iter().filter(|&i| i < n).collect())) + } else { + (poly[0].clone(), None) + }; + let mut c = Cut::new(Kind::Body, b.index, pts); + c.fill = Some(BODY_FILL.into()); + c.nse = nse; + c.source_id = solids.get(b.index).map(|s| s.id.clone()); + cuts.push(c); + } + } +} + +/// `clipLineToU`. +fn clip_line_to_u(pts: &[[f64; 2]], lo: f64, hi: f64) -> Vec> { + let mut out = Vec::new(); + let mut cur: Vec<[f64; 2]> = Vec::new(); + fn flush(cur: &mut Vec<[f64; 2]>, out: &mut Vec>) { + if cur.len() >= 2 { + out.push(std::mem::take(cur)); + } + cur.clear(); + } + for i in 0..pts.len().saturating_sub(1) { + let a = pts[i]; + let b = pts[i + 1]; + let (u0, u1) = (a[0], b[0]); + if (u0 < lo && u1 < lo) || (u0 > hi && u1 > hi) { + flush(&mut cur, &mut out); + continue; + } + let at = |u: f64| -> [f64; 2] { + let t = if u1 == u0 { 0.0 } else { (u - u0) / (u1 - u0) }; + [u, a[1] + (b[1] - a[1]) * t] + }; + let pa = if u0 < lo { at(lo) } else if u0 > hi { at(hi) } else { a }; + let pb = if u1 < lo { at(lo) } else if u1 > hi { at(hi) } else { b }; + if cur.is_empty() { + cur.push(pa); + } + cur.push(pb); + if u1 < lo || u1 > hi { + flush(&mut cur, &mut out); + } + } + flush(&mut cur, &mut out); + out +} + +/// `appendTerrainProfiles`. +fn append_terrain_profiles(out: &mut Output, p: &Project, base: (f64, f64), u: (f64, f64)) { + let terrains: Vec<&TerrainMesh> = p.context.as_deref().unwrap_or(&[]).iter().filter_map(|c| if let ContextObject::TerrainMesh(t) = c { Some(t) } else { None }).collect(); + if terrains.is_empty() { + return; + } + let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); + for cp in &out.cuts { + for q in &cp.pts { + lo = min(lo, q[0]); + hi = max(hi, q[0]); + } + } + for e in out.visible.iter().chain(out.hidden.iter()) { + lo = min(min(lo, e.a[0]), e.b[0]); + hi = max(max(hi, e.a[0]), e.b[0]); + } + let range = lo.is_finite().then_some((lo, hi)); + for t in terrains { + if t.positions.len() < 9 { + continue; + } + let (_, lines) = cut_mesh(&t.positions, &t.indices, base, u); + for line in lines { + let parts = match range { + Some((lo, hi)) => clip_line_to_u(&line, lo - TERRAIN_MARGIN, hi + TERRAIN_MARGIN), + None => vec![line], + }; + for pts in parts { + out.profiles.push(Profile { category: t.category_code.clone(), pts }); + } + } + } +} + +fn centroid(pts: &[Vec2]) -> Option<(f64, f64)> { + if pts.is_empty() { + return None; + } + let (mut x, mut y) = (0.0, 0.0); + for q in pts { + x += q.x; + y += q.y; + } + let n = pts.len() as f64; + Some((x / n, y / n)) +} + +/// `filterByDepth`: Ansichtskanten weiter als `depth` hinter der Ebene ausblenden. +fn filter_by_depth(out: &mut Output, p: &Project, plane: &Plane, depth: f64, walls: &[&Wall], slabs: &[&Ceiling]) { + if !(depth > 0.0) { + return; + } + let (nx, ny) = (plane.normal[0], plane.normal[2]); + let l = hypot2(nx, ny); + let l = if l == 0.0 || l.is_nan() { 1.0 } else { l }; + let blick = (nx / l, ny / l); + let origin = plane.base(); + let roofs = p.roofs.as_deref().unwrap_or(&[]); + let owner_point = |e: &Edge| -> Option<(f64, f64)> { + match e.kind { + Kind::Wall => walls.get(e.index).map(|w| ((w.start.x + w.end.x) / 2.0, (w.start.y + w.end.y) / 2.0)), + Kind::Slab => slabs.get(e.index).and_then(|c| centroid(&c.outline)), + _ => roofs.get(e.index).and_then(|r| centroid(&r.outline)), + } + }; + let keep = |e: &Edge| -> bool { + match owner_point(e) { + None => true, + Some(q) => (q.0 - origin.0) * blick.0 + (q.1 - origin.1) * blick.1 <= depth + 1e-6, + } + }; + out.visible.retain(keep); + out.hidden.retain(keep); +} + +// ── Schnitt ─────────────────────────────────────────────────────────────────── + +/// `computeSection` (ohne den asynchronen Teil: die Körper-Netze kommen fertig aus TS). +pub fn compute_section(p: &Project, level: &LevelSpec, bodies: &[BodyMesh]) -> Result, String> { + let Some(plane) = level.plane() else { return Ok(None) }; + let walls_r = model3d::emit_walls(p, false)?; + let mut slabs_r = model3d::emit_slabs(p); + slabs_r.extend(model3d::emit_stairs(p, true)); + let roofs_r = model3d::emit_roof_cut_layers(p)?; + let wi: Vec = walls_r.iter().map(wall_input).collect(); + let si: Vec = slabs_r.iter().map(slab_input).collect(); + let ri: Vec = roofs_r.iter().map(roof_input).collect(); + // Die Ebene ging als Zahl-Argument (wasm-bindgen, `Math.fround`) hinein, nicht über JSON. + let fr = |v: [f64; 3]| [v[0] as f32, v[1] as f32, v[2] as f32]; + let rp = render3d::SectionPlane::new(fr(plane.point), fr(plane.normal)); + let raw = render3d::cut_section(&rp, &wi, &si, &ri); + + let mut cut_owners: HashSet<(Kind, usize)> = HashSet::new(); + let mut cuts: Vec = Vec::with_capacity(raw.cut_polygons.len()); + for cp in &raw.cut_polygons { + let kind = kind_of(cp.component.kind); + cut_owners.insert((kind, cp.component.index)); + cuts.push(Cut::new(kind, cp.component.index, cp.pts.iter().map(|q| [js_f32(q[0]), js_f32(q[1])]).collect())); + } + let edge = |e: &render3d::SectionEdge| Edge { kind: kind_of(e.component.kind), index: e.component.index, a: [js_f32(e.a[0]), js_f32(e.a[1])], b: [js_f32(e.b[0]), js_f32(e.b[1])] }; + let not_cut = |e: &&render3d::SectionEdge| !cut_owners.contains(&(kind_of(e.component.kind), e.component.index)); + let visible: Vec = raw.visible_edges.iter().filter(not_cut).map(edge).collect(); + let hidden: Vec = raw.hidden_edges.iter().filter(not_cut).map(edge).collect(); + + append_roof_sections(&mut cuts, p, &plane); + let walls = wall_segment_owners(p); + let slabs = slab_segment_owners(p); + let mut cuts = attach_cut_styles(cuts, p, &plane, &walls, &slabs)?; + // Treppen-Prismen: Herkunft + Kategorie (bei doppelten ids gewinnt die letzte, wie `new Map`). + let mut stairs_by_id: HashMap<&str, &Stair> = HashMap::new(); + for st in p.stairs.as_deref().unwrap_or(&[]) { + stairs_by_id.insert(st.id.as_str(), st); + } + for cp in cuts.iter_mut() { + if cp.kind != Kind::Slab { + continue; + } + let id = slabs_r.get(cp.index).map_or("", |s| s.ceiling_id.as_str()); + if let Some(st) = stairs_by_id.get(id) { + cp.stair_id = Some(st.id.clone()); + cp.category = Some(st.category_code.clone()); + } + } + let cuts = merge_monolith_cuts(cuts, &slabs_r); + let base = plane.base(); + let u = plane.u_model(); + let mut cuts = subtract_voids_in_section(cuts, p, base, u); + append_body_sections(&mut cuts, p, bodies, base, u); + let mut out = Output { cuts, visible, hidden, profiles: Vec::new() }; + append_terrain_profiles(&mut out, p, base, u); + if let Some(d) = level.depth { + filter_by_depth(&mut out, p, &plane, d, &walls, &slabs); + } + Ok(Some(out)) +} + +// ── Primitive ───────────────────────────────────────────────────────────────── + +pub(crate) fn polygon(pts: Vec, fill: &str, stroke: &str, w: f64, hatch: HatchRender) -> Primitive { + Primitive::Polygon { + pts, + fill: fill.into(), + stroke: stroke.into(), + stroke_width_mm: w, + hatch, + greyed: None, + opacity: None, + no_stroke_edges: None, + wall_id: None, + drawing_id: None, + ceiling_id: None, + opening_id: None, + stair_id: None, + room_id: None, + extruded_solid_id: None, + context_object_id: None, + column_id: None, + roof_id: None, + section_line_id: None, + } +} + +pub(crate) fn line(a: Vec2, b: Vec2, cls: &str, w: f64, color: &str) -> Primitive { + Primitive::Line { a, b, cls: cls.into(), weight_mm: w, dash: None, zigzag: None, motif: None, color: Some(color.into()), drawing_id: None, opening_id: None, stair_id: None, greyed: None, opacity: None } +} + +pub(crate) fn v2(x: f64, y: f64) -> Vec2 { + Vec2 { x, y } +} + +/// Ausmass wie `acc` in TS (`<`/`>`-Vergleiche, NaN bleibt draussen). +#[derive(Clone, Copy)] +pub(crate) struct Acc { + pub min_x: f64, + pub min_y: f64, + pub max_x: f64, + pub max_y: f64, +} + +impl Acc { + pub fn new() -> Acc { + Acc { min_x: f64::INFINITY, min_y: f64::INFINITY, max_x: f64::NEG_INFINITY, max_y: f64::NEG_INFINITY } + } + pub fn add(&mut self, x: f64, y: f64) { + if x < self.min_x { + self.min_x = x; + } + if y < self.min_y { + self.min_y = y; + } + if x > self.max_x { + self.max_x = x; + } + if y > self.max_y { + self.max_y = y; + } + } + pub fn bounds(&self) -> [f64; 4] { + if !self.min_x.is_finite() { + [0.0, 0.0, 1.0, 1.0] + } else { + [self.min_x, self.min_y, self.max_x, self.max_y] + } + } +} + +/// `generateSectionPlan`: Primitive (u → x, Höhe → y) und Ausmass. +pub fn section_primitives(out: &Output, mono: bool, hidden_lines: bool, vis: &Visibility) -> (Vec, [f64; 4]) { + let mut prims = Vec::new(); + let mut acc = Acc::new(); + let shown = |code: &str| vis.visible(code) && vis.render(code); + for cp in &out.cuts { + if cp.pts.len() < 3 { + continue; + } + if let Some(code) = cp.category.as_deref() { + if !shown(code) { + continue; + } + } + let pts: Vec = cp + .pts + .iter() + .map(|q| { + acc.add(q[0], q[1]); + v2(q[0], q[1]) + }) + .collect(); + let fill = cp.fill.as_deref().unwrap_or(HATCH_PAPER); + let hatch = cp.hatch.clone().unwrap_or_else(section_hatch); + let solid = hatch.pattern == HatchPattern::Solid; + let (fill, hatch) = if mono { + let mono_fill = if solid { HATCH_INK } else { HATCH_PAPER }; + let mono_hatch = if !solid && hatch.pattern != HatchPattern::None { HatchRender { color: SECTION_INK.into(), ..hatch } } else { hatch }; + (mono_fill.to_string(), mono_hatch) + } else { + (fill.to_string(), hatch) + }; + let src = cp.source_id.clone(); + let mut pr = polygon(pts, &fill, SECTION_INK, SECTION_CUT_OUTLINE_MM, hatch); + if let Primitive::Polygon { wall_id, ceiling_id, roof_id, stair_id, extruded_solid_id, no_stroke_edges, greyed, .. } = &mut pr { + *wall_id = if cp.kind == Kind::Wall { src.clone() } else { None }; + *ceiling_id = if cp.kind == Kind::Slab && cp.stair_id.is_none() { src.clone() } else { None }; + *roof_id = if cp.kind == Kind::Roof { src.clone() } else { None }; + *stair_id = cp.stair_id.clone(); + *extruded_solid_id = if cp.kind == Kind::Body { src } else { None }; + *no_stroke_edges = cp.nse.clone(); + *greyed = Some(cp.category.as_deref().is_some_and(|c| vis.greyed(c))); + } + prims.push(pr); + } + for pr in &out.profiles { + if let Some(code) = pr.category.as_deref() { + if !shown(code) { + continue; + } + } + for w in pr.pts.windows(2) { + acc.add(w[0][0], w[0][1]); + acc.add(w[1][0], w[1][1]); + prims.push(line(v2(w[0][0], w[0][1]), v2(w[1][0], w[1][1]), "section-terrain", SECTION_GROUND_MM, SECTION_INK)); + } + } + if hidden_lines { + for e in &out.hidden { + acc.add(e.a[0], e.a[1]); + acc.add(e.b[0], e.b[1]); + let mut l = line(v2(e.a[0], e.a[1]), v2(e.b[0], e.b[1]), "section-hidden", SECTION_HIDDEN_MM, SECTION_HIDDEN_INK); + if let Primitive::Line { dash, .. } = &mut l { + *dash = Some(Some(SECTION_HIDDEN_DASH.to_vec())); + } + prims.push(l); + } + } + for e in &out.visible { + acc.add(e.a[0], e.a[1]); + acc.add(e.b[0], e.b[1]); + prims.push(line(v2(e.a[0], e.a[1]), v2(e.b[0], e.b[1]), "section-visible", SECTION_VISIBLE_MM, SECTION_VISIBLE_INK)); + } + if acc.min_x.is_finite() && acc.max_x > acc.min_x { + prims.push(line(v2(acc.min_x, acc.min_y), v2(acc.max_x, acc.min_y), "section-ground", SECTION_GROUND_MM, SECTION_INK)); + } + (prims, acc.bounds()) +} + +// ── Geschnittene Fenster/Türen (`sectionOpenings.ts`) ──────────────────────── + +const OPENING_INK: &str = "#1f242c"; +const FRAME_MM: f64 = 0.25; +const GLASS_MM: f64 = 0.13; +const DEFAULT_FRAME_DEPTH: f64 = 0.07; +const DEFAULT_FRAME_WIDTH: f64 = 0.06; +const DOOR_LEAF_THICKNESS: f64 = 0.04; +const MIN_CROSS: f64 = 0.15; + +fn rect(u0: f64, u1: f64, v0: f64, v1: f64) -> Vec { + vec![v2(min(u0, u1), v0), v2(max(u0, u1), v0), v2(max(u0, u1), v1), v2(min(u0, u1), v1)] +} + +fn opening_poly(pts: Vec, profile: bool, id: &str) -> Primitive { + let mut pr = if profile { polygon(pts, "#ffffff", OPENING_INK, FRAME_MM, no_hatch_base()) } else { polygon(pts, "none", "none", 0.0, no_hatch_base()) }; + if let Primitive::Polygon { opening_id, .. } = &mut pr { + *opening_id = Some(id.into()); + } + pr +} + +struct CrossSection { + n0: f64, + un: f64, + z_bottom: f64, + z_top: f64, + face_min: f64, + face_max: f64, +} + +impl CrossSection { + fn u_at(&self, s: f64) -> f64 { + (s - self.n0) / self.un + } +} + +fn axis_frame(w: &Wall) -> ((f64, f64), (f64, f64)) { + let (dx, dy) = (w.end.x - w.start.x, w.end.y - w.start.y); + let l = hypot2(dx, dy); + let l = if l == 0.0 || l.is_nan() { 1.0 } else { l }; + let u = (dx / l, dy / l); + (u, (-u.1, u.0)) +} + +fn cross_section(p: &Project, wall: &Wall, o: &Opening, p0: (f64, f64), u: (f64, f64)) -> Result, String> { + let Some((from, to)) = opening_interval(wall, o) else { return Ok(None) }; + let (a, n) = axis_frame(wall); + let un = u.0 * n.0 + u.1 * n.1; + if un.abs() < MIN_CROSS { + return Ok(None); + } + let rel = (p0.0 - wall.start.x, p0.1 - wall.start.y); + let n0 = rel.0 * n.0 + rel.1 * n.1; + let a0 = rel.0 * a.0 + rel.1 * a.1; + let ua = u.0 * a.0 + u.1 * a.1; + let wt = p.wall_type(wall).ok_or_else(|| missing("Unbekannter Wandtyp", &wall.wall_type_id))?; + let total = sum_thickness(&wt.layers); + let ref_off = crate::joins::reference_offset(model3d::wall_reference(wall), total); + let along = a0 + ((ref_off - n0) / un) * ua; + if along < from + 1e-4 || along > to - 1e-4 { + return Ok(None); + } + let (z_bottom, z_top) = opening_extent(p, wall, o); + if z_top - z_bottom < 1e-3 { + return Ok(None); + } + Ok(Some(CrossSection { n0, un, z_bottom, z_top, face_min: ref_off - total / 2.0, face_max: ref_off + total / 2.0 })) +} + +/// Sash-Liste eines Fenstertyps (`sashesOfWindowType`) für das Fenster-Symbol. +pub(crate) fn sashes_of_window_type(wt: &WindowType) -> Vec { + if let Some(s) = wt.sashes.as_deref().filter(|s| !s.is_empty()) { + return s + .iter() + .map(|s| crate::opening_geom::Sash { + post: s.kind == SashDefKind::Pfosten, + auto_width: s.auto_width != Some(false), + width: s.width.unwrap_or(f64::NAN), + post_width: s.post_width.unwrap_or(f64::NAN), + operable: s.opening.is_some_and(|o| o != OpeningKind::Fest), + }) + .collect(); + } + let wc = if wt.wing_count == 0.0 || wt.wing_count.is_nan() { 1.0 } else { wt.wing_count }; + let n = max(1.0, round(wc)) as usize; + let operable = wt.kind != OpeningKind::Fest; + (0..n).map(|_| crate::opening_geom::Sash { post: false, auto_width: true, width: f64::NAN, post_width: f64::NAN, operable }).collect() +} + +fn window_cut(p: &Project, wall: &Wall, o: &Opening, c: &CrossSection) -> Result, String> { + let wt = p.window_type(o); + let fw = max(0.02, wt.and_then(|t| t.frame_width).unwrap_or(DEFAULT_FRAME_WIDTH)); + let (_, n) = axis_frame(wall); + let off_of = |q: crate::opening_geom::V| (q.x - wall.start.x) * n.0 + (q.y - wall.start.y) * n.1; + let mut f_min = (c.face_min + c.face_max) / 2.0 - DEFAULT_FRAME_DEPTH / 2.0; + let mut f_max = f_min + DEFAULT_FRAME_DEPTH; + let mut glass: Vec = vec![(f_min + f_max) / 2.0]; + // `windowSymbol(project, wall, o, 1, spec, "mittel")`. + let total = sum_thickness(&p.wall_type(wall).ok_or_else(|| missing("Unbekannter Wandtyp", &wall.wall_type_id))?.layers); + let ref_off = crate::joins::reference_offset(model3d::wall_reference(wall), total); + let spec = wt.map(|t| crate::opening_geom::WindowSpec { + sashes: sashes_of_window_type(t), + frame_width: t.frame_width.unwrap_or(DEFAULT_FRAME_WIDTH), + frame_depth: t.frame_depth.unwrap_or(f64::NAN), + inset_from_face: t.inset_from_face.unwrap_or(f64::NAN), + inset_inner: t.inset_face == Some(WindowTypeInsetFace::Innen), + }); + let finite = [wall.start.x, wall.start.y, wall.end.x, wall.end.y, total, ref_off, o.position, o.width].iter().all(|x| x.is_finite()); + let sym = if finite { + let wr = crate::opening_geom::WallRef { start: crate::opening_geom::v(wall.start.x, wall.start.y), end: crate::opening_geom::v(wall.end.x, wall.end.y), total, ref_off }; + crate::opening_geom::window_symbol(&wr, o.position, o.width, 1.0, spec.as_ref(), o.wing_count.unwrap_or(f64::NAN), crate::opening_geom::Detail::Mittel) + } else { + None + }; + if let (Some(sym), true) = (sym, spec.is_some()) { + let mut lo = f64::INFINITY; + let mut hi = f64::NEG_INFINITY; + for q in &sym.frame { + let s = off_of(*q); + lo = min(lo, s); + hi = max(hi, s); + } + f_min = lo; + f_max = hi; + if !sym.glass_lines.is_empty() { + let mut seen: Vec = Vec::new(); + for (q, _) in &sym.glass_lines { + let x = round(off_of(*q) * 1e6) / 1e6; + // `new Set` (SameValueZero: 0 = -0, NaN = NaN). + if !seen.iter().any(|&s| s == x || (s.is_nan() && x.is_nan())) { + seen.push(x); + } + } + glass = seen; + } + } + let u0 = c.u_at(f_min); + let u1 = c.u_at(f_max); + let h = c.z_top - c.z_bottom; + let fwv = min(fw, h / 3.0); + let mut out = vec![opening_poly(rect(c.u_at(c.face_min), c.u_at(c.face_max), c.z_bottom, c.z_top), false, &o.id)]; + out.push(opening_poly(rect(u0, u1, c.z_bottom, c.z_bottom + fwv), true, &o.id)); + out.push(opening_poly(rect(u0, u1, c.z_top - fwv, c.z_top), true, &o.id)); + for s in glass { + let u = c.u_at(s); + let mut l = line(v2(u, c.z_bottom + fwv), v2(u, c.z_top - fwv), "section-window-glass", GLASS_MM, OPENING_INK); + if let Primitive::Line { opening_id, .. } = &mut l { + *opening_id = Some(o.id.clone()); + } + out.push(l); + } + Ok(out) +} + +fn door_cut(o: &Opening, c: &CrossSection) -> Vec { + let mut out = vec![opening_poly(rect(c.u_at(c.face_min), c.u_at(c.face_max), c.z_bottom, c.z_top), false, &o.id)]; + if o.door_type == Some(OpeningDoorType::Wandoeffnung) { + return out; + } + let mid = (c.face_min + c.face_max) / 2.0; + let fw = min(DEFAULT_FRAME_WIDTH, (c.z_top - c.z_bottom) / 4.0); + out.push(opening_poly(rect(c.u_at(mid - DEFAULT_FRAME_DEPTH / 2.0), c.u_at(mid + DEFAULT_FRAME_DEPTH / 2.0), c.z_top - fw, c.z_top), true, &o.id)); + out.push(opening_poly(rect(c.u_at(mid - DOOR_LEAF_THICKNESS / 2.0), c.u_at(mid + DOOR_LEAF_THICKNESS / 2.0), c.z_bottom + 0.01, c.z_top - fw), true, &o.id)); + out +} + +/// `sectionOpeningPrimitives`. +pub fn section_opening_primitives(p: &Project, level: &LevelSpec, vis: &Visibility) -> Result, String> { + let Some(plane) = level.plane() else { return Ok(Vec::new()) }; + if level.kind != "section" { + return Ok(Vec::new()); + } + let u_raw = plane.u_model(); + let l = hypot2(u_raw.0, u_raw.1); + let l = if l == 0.0 || l.is_nan() { 1.0 } else { l }; + let u = (u_raw.0 / l, u_raw.1 / l); + let p0 = plane.base(); + let mut walls_by_id: HashMap<&str, &Wall> = HashMap::new(); + for w in &p.walls { + walls_by_id.insert(w.id.as_str(), w); + } + let mut out = Vec::new(); + for o in p.openings.as_deref().unwrap_or(&[]) { + if !vis.visible(&o.category_code) || !vis.render(&o.category_code) { + continue; + } + let Some(wall) = walls_by_id.get(o.host_wall_id.as_str()).copied() else { continue }; + if !vis.visible(&wall.category_code) { + continue; + } + let Some(c) = cross_section(p, wall, o, p0, u)? else { continue }; + let prims = if o.kind == ElementKind::Window { window_cut(p, wall, o, &c)? } else { door_cut(o, &c) }; + let greyed = vis.greyed(&o.category_code); + for pr in prims { + out.push(if greyed { pr.with_greyed(true) } else { pr }); + } + } + Ok(out) +} + +// ── Abfrage ─────────────────────────────────────────────────────────────────── + +/// Abfrage `sectionPlan`: `args` = `[mono, openings, bodies…]` (Körper s. [`read_bodies`]), +/// `text` = `{"level": {...}, "hiddenLines", "hasVis", "invisible", "hasDisplay", "norender", "grey"}`. +/// Puffer: Gruppe 0 Schnitt, Gruppe 1 geschnittene Öffnungen; Ausmass ohne die Öffnungen. +/// Ohne gültige Schnittlinie: leerer Puffer ohne Gruppen. +pub fn section_plan_buf(p: &Project, args: &[f64], text: &str) -> Result, String> { + let v: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("Schnitt-Argumente: {e}"))?; + let level = LevelSpec::from_json(v.get("level").unwrap_or(&serde_json::Value::Null)); + let vis = Visibility::from_json(&v); + let mono = args.first().is_some_and(|&x| x != 0.0); + let openings = args.get(1).is_some_and(|&x| x != 0.0); + let bodies = read_bodies(args.get(2..).unwrap_or(&[])).ok_or("Schnitt: Körper-Netze unlesbar")?; + let mut w = crate::plan_buf::Writer::new(true); + let Some(out) = compute_section(p, &level, &bodies)? else { return Ok(w.finish()) }; + let hidden = v.get("hiddenLines").and_then(|b| b.as_bool()).unwrap_or(false); + let (prims, bounds) = section_primitives(&out, mono, hidden, &vis); + w.group(&prims); + let ops = if openings { section_opening_primitives(p, &level, &vis)? } else { Vec::new() }; + w.group(&ops); + w.bounds = Some(bounds); + Ok(w.finish()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample() -> Project { + serde_json::from_str(include_str!("../../tests/fixtures/sample_project.json")).unwrap() + } + + fn level(p: &Project, id: &str) -> LevelSpec { + let l = p.drawing_levels.iter().find(|l| l.id == id).unwrap(); + LevelSpec::from_json(&serde_json::to_value(l).unwrap()) + } + + #[test] + fn ebene_wie_section_plane_from_level() { + let l = LevelSpec { kind: "section".into(), line: Some([Vec2 { x: -1.0, y: 2.0 }, Vec2 { x: 6.0, y: 2.0 }]), ..Default::default() }; + let pl = l.plane().unwrap(); + assert_eq!(pl.point, [-1.0, 0.0, 2.0]); + assert_eq!(pl.normal, [-0.0, 0.0, 1.0]); + assert_eq!(pl.u_model(), (1.0, 0.0)); + let l0 = LevelSpec { line: Some([Vec2 { x: 1.0, y: 1.0 }, Vec2 { x: 1.0, y: 1.0 }]), ..Default::default() }; + assert!(l0.plane().is_none()); + } + + #[test] + fn json_zahlen_wie_frueher() { + // JS schreibt die kürzeste Darstellung, serde_json (ohne float_roundtrip) liest Mantisse/10^k. + assert_eq!(json_f32(2.6), 2.6f32); + assert_eq!(json_f32(-0.0), 0.0f32); + assert_eq!(json_f32(3.0), 3.0f32); + assert_eq!(json_f32(1e-9), 1e-9f32); + // Gleichstand der kürzesten Darstellung → gerade Ziffer (wie serde_json beim Schreiben). + assert_eq!(js_f32(5.00390625f32), 5.0039062f64); + } + + #[test] + fn beispiel_schnitt_mit_pick_ids() { + let p = sample(); + let l = level(&p, "schnitt-a"); + let out = compute_section(&p, &l, &[]).unwrap().unwrap(); + let (prims, b) = section_primitives(&out, false, false, &Visibility::default()); + let json = serde_json::to_string(&prims).unwrap(); + assert!(json.contains("\"wallId\":\"W2\"") && json.contains("\"roofId\":\"RF1\""), "{json}"); + assert!(json.contains("section-ground")); + assert!(b[2] > b[0] && b[3] > b[1]); + // Kategorie ausgeblendet → keine Dach-Schnittflächen mehr. (Von der Dominanz beschnittene + // Wand-/Deckenbänder verlieren ihre Kategorie und bleiben sichtbar — wie in der TS-Fassung.) + let vis = Visibility { has_vis: true, invisible: ["31".to_string()].into_iter().collect(), ..Default::default() }; + let (hidden, _) = section_primitives(&out, false, false, &vis); + assert!(!serde_json::to_string(&hidden).unwrap().contains("\"roofId\"")); + } + + #[test] + fn puffer_hat_zwei_gruppen() { + let p = sample(); + let text = serde_json::json!({ "level": serde_json::to_value(p.drawing_levels.iter().find(|l| l.id == "schnitt-a").unwrap()).unwrap() }).to_string(); + let buf = section_plan_buf(&p, &[0.0, 1.0, 0.0], &text).unwrap(); + let (prims, groups, bounds) = crate::plan_buf::decode(&buf).unwrap(); + assert_eq!(groups.len(), 2); + assert!(bounds.is_some() && !prims.is_empty()); + // Ohne Schnittlinie: leerer Puffer ohne Gruppen. + let none = section_plan_buf(&p, &[0.0, 0.0], r#"{"level":{"kind":"section"}}"#).unwrap(); + assert!(crate::plan_buf::decode(&none).unwrap().1.is_empty()); + } +} + +#[cfg(test)] +mod bench { + use super::*; + use std::time::Instant; + + /// Messung je Stufe (nativ): `SECTION_BENCH_FILE=projekt.obp cargo test --release --lib section::bench -- --ignored --nocapture`. + #[test] + #[ignore] + fn stufen() { + let Ok(path) = std::env::var("SECTION_BENCH_FILE") else { return }; + let p: Project = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + for l in p.drawing_levels.iter().filter(|l| l.line_points.is_some()) { + let level = LevelSpec::from_json(&serde_json::to_value(l).unwrap()); + let t = Instant::now(); + let walls = model3d::emit_walls(&p, false).unwrap(); + let t_walls = t.elapsed(); + let t = Instant::now(); + let mut slabs = model3d::emit_slabs(&p); + slabs.extend(model3d::emit_stairs(&p, true)); + let roofs = model3d::emit_roof_cut_layers(&p).unwrap(); + let t_rest = t.elapsed(); + let t = Instant::now(); + let wi: Vec = walls.iter().map(wall_input).collect(); + let si: Vec = slabs.iter().map(slab_input).collect(); + let ri: Vec = roofs.iter().map(roof_input).collect(); + let t_conv = t.elapsed(); + let pl = level.plane().unwrap(); + let fr = |v: [f64; 3]| [v[0] as f32, v[1] as f32, v[2] as f32]; + let t = Instant::now(); + let raw = render3d::cut_section(&render3d::SectionPlane::new(fr(pl.point), fr(pl.normal)), &wi, &si, &ri); + let t_cut = t.elapsed(); + let t = Instant::now(); + let buf = if l.kind == DrawingLevelKind::Section { + section_plan_buf(&p, &[0.0, 1.0, 0.0], &serde_json::json!({ "level": serde_json::to_value(l).unwrap() }).to_string()).unwrap() + } else { + crate::plan::elevation::elevation_plan_buf(&p, &[0.0, 0.0], &serde_json::json!({ "level": serde_json::to_value(l).unwrap() }).to_string()).unwrap() + }; + let t_all = t.elapsed(); + println!( + "{} {:?}: Wände {:?} Platten/Dach {:?} Umwandlung {:?} cut_section {:?} ({} Cut, {} Kanten) | gesamt {:?} ({} Bytes)", + l.id, l.kind, t_walls, t_rest, t_conv, t_cut, raw.cut_polygons.len(), raw.visible_edges.len() + raw.hidden_edges.len(), t_all, buf.len() + ); + } + } +} diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs index 50ee88af..5de71260 100644 --- a/src-tauri/core/src/queries.rs +++ b/src-tauri/core/src/queries.rs @@ -49,6 +49,8 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result Result, String> { match (name, args.len()) { ("planDomains", 1) => crate::plan::domains::plan_domains_buf(p, &crate::plan::domains::PlanArgs::parse(args[0], text)?), + ("sectionPlan", _) => crate::plan::section::section_plan_buf(p, args, text), + ("elevationPlan", _) => crate::plan::elevation::elevation_plan_buf(p, args, text), _ => Err(format!("Unbekannte Abfrage: {name}")), } } diff --git a/src/cli/main.ts b/src/cli/main.ts index 94aa8ef7..a370e015 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -596,6 +596,10 @@ async function execute(project: Project, file: string, command: string, rest: st plan = generateElevationPlan(project, lvl); if (!plan) fail("keine gültige Ansichtslinie"); } + if (args.flags.get("format") === "json") { + out(args, JSON.stringify(planToRenderScene(plan, scale)), `${lvl.name}.scene.json`); + return 0; + } out(args, planToSvgString(plan, { scaleDenominator: scale }), `${lvl.name}.svg`); return 0; } diff --git a/src/core/document.ts b/src/core/document.ts index 9f7fb616..f38743a9 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -36,6 +36,8 @@ export type QueryName = | "pickGeometry" | "model3dParts" | "planDomains" + | "sectionPlan" + | "elevationPlan" | "modelJson"; export class ProjectDocument { @@ -99,9 +101,9 @@ export class ProjectDocument { * Abfrage mit binärer Antwort (`queries.rs::run_bin`, z. B. `planDomains` als Plan-Puffer v2, * s. `plan/planBuf.ts`). Fehler kommen als Fehlerpuffer (`decodePlanBuf` wirft die Meldung). */ - queryBin(name: QueryName, args: number[] = [], text = ""): Uint8Array { + queryBin(name: QueryName, args: number[] | Float64Array = [], text = ""): Uint8Array { if (!this.handle) throw new Error(`Kern-Abfrage „${name}": Dokument nicht offen`); - return core().doc_query_bin(this.handle, name, Float64Array.from(args), text); + return core().doc_query_bin(this.handle, name, args instanceof Float64Array ? args : Float64Array.from(args), text); } /** Datei-Text des Projekts (Formatversion vorn, Einrückung 2). */ diff --git a/src/core/index.ts b/src/core/index.ts index 8ae08a37..27709da0 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -172,7 +172,6 @@ export { type PlanImage, type UnderlayGroup, generatePlan, - generateSectionPlan, generateVisibleLevelsPlan, materializeGreyed, materializeUnderlay, @@ -294,12 +293,12 @@ export { } from "../plan/planView/underlayAccess"; export { - sectionOpeningPrimitives, -} from "../plan/sectionOpenings"; - -export { + type ElevationOptions, + type SectionOutput, + computeSection, generateElevationPlan, -} from "../plan/toElevation"; + generateSectionPlan, +} from "../plan/sectionCore"; export { planSceneBin, @@ -307,8 +306,6 @@ export { } from "../plan/toRenderScene"; export { - type SectionOutput, - computeSection, sameSectionInputs, sameSectionLine, sectionPlaneFromLevel, diff --git a/src/plan/sectionBench.test.ts b/src/plan/sectionBench.test.ts new file mode 100644 index 00000000..9817457e --- /dev/null +++ b/src/plan/sectionBench.test.ts @@ -0,0 +1,66 @@ +// VORÜBERGEHEND ([K3c]): Messung alt (TS) gegen neu (Kern) für Schnitt und Ansicht (nur mit BENCH=1). +import { it } from "vitest"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { setWasmBytesProvider } from "../engine/wasmSource"; +import { computeSection as oldCompute } from "./toSection"; +import { generateSectionPlan as oldGen } from "./generatePlan"; +import { sectionOpeningPrimitives } from "./sectionOpenings"; +import { generateElevationPlan as oldElev } from "./toElevation"; +import { computeSection as newCompute, generateSectionPlan as newGen, generateElevationPlan as newElev } from "./sectionCore"; +import { planToRenderScene } from "./toRenderScene"; +import { sampleProject } from "../model/sampleProject"; +import { flattenCategories } from "../model/types"; +import type { DrawingLevel, Project } from "../model/types"; +import { bigSectionProject } from "./sectionParity.testing"; + +async function time(f: () => Promise | unknown, runs: number): Promise<[number, number]> { + await f(); + const t: number[] = []; + for (let i = 0; i < runs; i++) { + const t0 = performance.now(); + await f(); + t.push(performance.now() - t0); + } + t.sort((a, b) => a - b); + return [t[0], t[Math.floor(t.length / 2)]]; +} + +const fmt = ([a, b]: [number, number]) => `${a.toFixed(1)}/${b.toFixed(1)}`; + +it.skipIf(!process.env.BENCH)("Messung Schnitt/Ansicht alt gegen neu", async () => { + setWasmBytesProvider(async (name) => readFileSync(join(process.cwd(), "src", "engine", name === "trucksolid" ? "pkgTruck/trucksolid_bg.wasm" : "pkg3d/render3d_bg.wasm"))); + const only = process.env.BENCH_ONLY; + const all: Array<[string, Project]> = [["Beispiel", sampleProject], ["big6", bigSectionProject(6)], ["big8", bigSectionProject(8)], ["big16", bigSectionProject(16)]]; + const cases = all.filter(([n]) => !only || only.split(",").includes(n)); + const rows: string[] = ["Projekt | Ebene | alt Plan | neu Plan | alt +Szene | neu +Szene (ms min/median)"]; + for (const [name, p] of cases) { + const codes = new Set(flattenCategories(p.layers).map((c) => c.code)); + const levels = p.drawingLevels.filter((l) => (l.kind === "section" || l.kind === "elevation") && l.linePoints) as DrawingLevel[]; + const runs = name === "big16" ? 1 : name === "Beispiel" ? 20 : 5; + for (const l of levels) { + if (l.kind === "section") { + const oldP = async () => { + const o = (await oldCompute(p, l))!; + const pl = oldGen(o, false, { hiddenLines: l.hiddenLines, visibleCodes: codes }); + return { ...pl, primitives: [...pl.primitives, ...sectionOpeningPrimitives(p, l, codes)] }; + }; + const newP = async () => newGen((await newCompute(p, l))!, false, { hiddenLines: l.hiddenLines, visibleCodes: codes, openings: true }); + const a = await time(oldP, runs); + const b = await time(newP, runs); + const c = await time(async () => planToRenderScene(await oldP(), 100), runs); + const d = await time(async () => planToRenderScene(await newP(), 100), runs); + rows.push(`${name} | ${l.id} Schnitt | ${fmt(a)} | ${fmt(b)} | ${fmt(c)} | ${fmt(d)}`); + process.stderr.write(rows[rows.length - 1] + "\n"); + } else { + const a = await time(() => oldElev(p, l), runs); + const b = await time(() => newElev(p, l), runs); + const c = await time(() => planToRenderScene(oldElev(p, l)!, 100), runs); + const d = await time(() => planToRenderScene(newElev(p, l)!, 100), runs); + rows.push(`${name} | ${l.id} Ansicht | ${fmt(a)} | ${fmt(b)} | ${fmt(c)} | ${fmt(d)}`); + process.stderr.write(rows[rows.length - 1] + "\n"); + } + } + } + console.log(rows.join("\n")); +}, 3_600_000); diff --git a/src/plan/sectionCore.ts b/src/plan/sectionCore.ts new file mode 100644 index 00000000..335c541a --- /dev/null +++ b/src/plan/sectionCore.ts @@ -0,0 +1,164 @@ +// Schnitt und Ansicht aus dem Kern ([K3c]): die Abfragen `sectionPlan`/`elevationPlan` +// (`src-tauri/core/src/plan/{section,elevation}.rs`) liefern den Plan-Puffer v2 samt Pick-Ids; +// TS reicht nur die Ebene, die Sichtbarkeit (UI-Zustand) und — für den Schnitt — die +// asynchron gebauten truck-Körper hinein. + +import type { DrawingLevel, Project } from "../model/types"; +import { flattenCategories, getFloor } from "../model/types"; +import { documentFor } from "../core/document"; +import { buildSolidMesh } from "../engine/truckSolid"; +import { extrudedSolidSpec } from "./extrudedSolidSpec"; +import { decodePlanBuf } from "./planBuf"; +import { lazyPlan } from "./planLazy"; +import type { CategoryDisplayResolver, Plan } from "./generatePlan"; + +/** Vorbereitete Eingabe eines Schnitts: Projekt, Ebene und die truck-Körper (flach). */ +export interface SectionOutput { + project: Project; + level: DrawingLevel; + /** `[mono, openings, n, (index, nPos, pos…, nIdx, idx…) × n]`: Platz für die zwei Schalter, dann die + * geschnittenen freien Körper. */ + bodies: Float64Array; +} + +/** Ob die Ebene eine gültige Schnittlinie trägt (wie `sectionPlaneFromLevel`). */ +function hasLine(level: DrawingLevel): boolean { + const line = level.linePoints; + if (!line) return false; + return Math.hypot(line[1].x - line[0].x, line[1].y - line[0].y) >= 1e-9; +} + +/** Ob ein Körper als Abzugskörper wirkt (s. `voids.ts`). */ +function isVoid(s: NonNullable[number]): boolean { + return s.operation === "subtract" && !s.brep && (s.taper ?? 0) < 1e-6 && s.points.length >= 3 && s.height > 0; +} + +/** + * Bereitet den Schnitt der Ebene vor: baut die Netze der freien Körper (truck, asynchron, mit + * Cache). `null`, wenn die Ebene keine gültige Schnittlinie trägt. + */ +export async function computeSection(project: Project, level: DrawingLevel): Promise { + if (!hasLine(level)) return null; + const bodies: number[] = [0, 0, 0]; + const solids = project.extrudedSolids ?? []; + for (let index = 0; index < solids.length; index++) { + const solid = solids[index]; + if (solid.operation === "subtract" || isVoid(solid)) continue; + let baseZ = 0; + try { + baseZ = solid.levelId ? (getFloor(project, solid.levelId).baseElevation ?? 0) : 0; + } catch { + baseZ = 0; + } + const spec = extrudedSolidSpec(solid, baseZ); + if (!spec) continue; + let mesh: { positions: ArrayLike; indices: ArrayLike }; + try { + mesh = await buildSolidMesh(spec, 0.01); + } catch { + continue; // Körper nicht baubar → im Schnitt weglassen, wie im 3D + } + bodies.push(index, mesh.positions.length); + for (let i = 0; i < mesh.positions.length; i++) bodies.push(mesh.positions[i]); + bodies.push(mesh.indices.length); + for (let i = 0; i < mesh.indices.length; i++) bodies.push(mesh.indices[i]); + bodies[2]++; + } + return { project, level, bodies: Float64Array.from(bodies) }; +} + +/** Kategorie-Codes, die Schnitt/Ansicht prüfen. */ +function candidateCodes(project: Project): Set { + const codes = new Set(); + for (const c of flattenCategories(project.layers)) codes.add(c.code); + for (const list of [project.walls, project.ceilings, project.roofs, project.stairs, project.openings]) { + for (const e of list ?? []) codes.add(e.categoryCode); + } + for (const c of project.context ?? []) if (c.type === "terrainMesh" && c.categoryCode !== undefined) codes.add(c.categoryCode); + return codes; +} + +/** Sichtbarkeit (UI-Zustand) als Code-Listen für den Kern. */ +function visibilityArgs(project: Project, visibleCodes?: Set, categoryDisplay?: CategoryDisplayResolver) { + const invisible: string[] = []; + const norender: string[] = []; + const grey: string[] = []; + for (const c of candidateCodes(project)) { + if (visibleCodes && !visibleCodes.has(c)) invisible.push(c); + if (categoryDisplay) { + const d = categoryDisplay(c); + if (!d.render) norender.push(c); + if (d.greyed) grey.push(c); + } + } + return { hasVis: !!visibleCodes, invisible, hasDisplay: !!categoryDisplay, norender, grey }; +} + +/** Ebene ohne fremde Felder für den Kern. */ +function levelArg(level: DrawingLevel) { + return { + kind: level.kind, + linePoints: level.linePoints, + directionSign: level.directionSign, + depth: level.depth, + shadows: level.shadows, + }; +} + +/** + * Plan eines Schnitts (Cut-Flächen mit Stil und Pick-Ids, Gelände, sichtbare/verdeckte Kanten, + * Bodenlinie). `openings`: geschnittene Fenster/Türen anhängen (nicht im Ausmass). + */ +export function generateSectionPlan( + output: SectionOutput, + mono = false, + opts: { hiddenLines?: boolean; visibleCodes?: Set; categoryDisplay?: CategoryDisplayResolver; openings?: boolean } = {}, +): Plan { + const { project, level } = output; + const text = JSON.stringify({ + level: levelArg(level), + hiddenLines: !!opts.hiddenLines, + ...visibilityArgs(project, opts.visibleCodes, opts.categoryDisplay), + }); + const args = output.bodies.slice(); + args[0] = mono ? 1 : 0; + args[1] = opts.openings ? 1 : 0; + const buf = decodePlanBuf(documentFor(project).queryBin("sectionPlan", args, text)); + if (buf.groups.length === 0) return { primitives: [], bounds: { minX: 0, minY: 0, maxX: 1, maxY: 1 } }; + const b = buf.bounds ?? [0, 0, 1, 1]; + return lazyPlan( + { bounds: { minX: b[0], minY: b[1], maxX: b[2], maxY: b[3] } }, + buf.groups.map(([from, to]) => ({ buf, from, to })), + ); +} + +/** Optionen des Ansichts-Generators. */ +export interface ElevationOptions { + /** Schlagschatten zeichnen (Default aus `level.shadows`). */ + shadows?: boolean; + /** Schwarz-Weiss-Modus (neutralisierte Füllungen). */ + mono?: boolean; + /** + * Ebenen-Panel-Sichtbarkeit: mit beiden Angaben werden Flächen ausgeblendeter Kategorien vor der + * Verdeckung entfernt (sie verdecken dann auch nichts); ohne bleibt jede Fläche sichtbar. + */ + visibleCodes?: Set; + categoryDisplay?: CategoryDisplayResolver; +} + +/** + * Ansichts-Plan einer Ebene (gefüllte Fassadenansicht, Painter fern → nah, Öffnungen, Schatten, + * Bodenlinie). `null` ohne Ansichtslinie. + */ +export function generateElevationPlan(project: Project, level: DrawingLevel, opts: ElevationOptions = {}): Plan | null { + if (!hasLine(level)) return null; + const shadows = opts.shadows ?? level.shadows ?? false; + const text = JSON.stringify({ level: levelArg(level), ...visibilityArgs(project, opts.visibleCodes, opts.categoryDisplay) }); + const buf = decodePlanBuf(documentFor(project).queryBin("elevationPlan", [opts.mono ? 1 : 0, shadows ? 1 : 0], text)); + if (buf.groups.length === 0) return null; + const b = buf.bounds ?? [0, 0, 1, 1]; + return lazyPlan( + { bounds: { minX: b[0], minY: b[1], maxX: b[2], maxY: b[3] } }, + buf.groups.map(([from, to]) => ({ buf, from, to })), + ); +} diff --git a/src/plan/sectionParity.testing.ts b/src/plan/sectionParity.testing.ts new file mode 100644 index 00000000..83dfc351 --- /dev/null +++ b/src/plan/sectionParity.testing.ts @@ -0,0 +1,173 @@ +// VORÜBERGEHEND ([K3c]): Zufallsprojekte und Schnitt-/Ansichtsebenen für den Gleichheitstest +// alt (TS) gegen neu (Kern). Wird mit dem Test gelöscht. + +import type { DrawingLevel, ExtrudedSolid, Project, TerrainMesh, Wall } from "../model/types"; +import { sampleProject } from "../model/sampleProject"; +import { bigSampleProject } from "./bigSampleProject.testing"; + +export function rng(seed: number): () => number { + let x = (seed * 2654435761) >>> 0; + return () => (x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296; +} + +const pick = (r: () => number, a: readonly T[]): T => a[Math.floor(r() * a.length)]; +const clone = (v: T): T => JSON.parse(JSON.stringify(v)) as T; +const round = (v: number) => Math.round(v * 1e4) / 1e4; + +const HATCHES = ["none", "insulation", "diagonal", "crosshatch", "solid-concrete", "sia-concrete", "sia-brick", "sia-insulation", "missing-hatch"]; +const COLORS = ["#ff0000", "#00aa33", " #123456 ", "#abc", "#000000"]; + +function terrain(r: () => number): TerrainMesh { + const n = 12; + const positions: number[] = []; + const tilt = (r() - 0.5) * 0.3; + for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) positions.push(i * 2 - 8, j * 2 - 8, tilt * (i - 5) + (r() - 0.5) * 0.4 - 0.2); + const indices: number[] = []; + for (let j = 0; j + 1 < n; j++) + for (let i = 0; i + 1 < n; i++) { + const a = j * n + i; + indices.push(a, a + 1, a + n, a + 1, a + n + 1, a + n); + } + return { id: "terrain" + Math.floor(r() * 100), type: "terrainMesh", name: "Gelände", positions, indices, categoryCode: r() < 0.5 ? "99" : undefined } as TerrainMesh; +} + +/** Zufallsprojekt auf Basis des Beispielhauses (Wände, Öffnungen, Dächer, Treppen, Abzugskörper, Overrides …). */ +export function randomSectionProject(seed: number): Project { + const r = rng(seed); + const p = clone(sampleProject) as Project; + const jit = (v: number, a: number) => round(v + (r() - 0.5) * a); + // Wände: verschieben, Typen, Overrides, Terminierung, zusätzliche Wände + const extra: Wall[] = []; + for (let k = 0; k < Math.floor(r() * 4); k++) { + const x0 = jit(2.5, 6), y0 = jit(2, 5); + const ang = r() < 0.6 ? (r() < 0.5 ? 0 : Math.PI / 2) : r() * Math.PI; + const len = 1 + r() * 4; + extra.push({ + id: `WX${k}`, type: "wall", floorId: r() < 0.7 ? "eg" : "og", categoryCode: r() < 0.8 ? "20" : "22", + start: { x: x0, y: y0 }, end: { x: round(x0 + Math.cos(ang) * len), y: round(y0 + Math.sin(ang) * len) }, + wallTypeId: pick(r, ["aw", "iw", "iw", "aw", "nope"]), height: round(2 + r()), + } as Wall); + } + p.walls = [...p.walls, ...extra].map((w) => { + const o: Wall = { ...w }; + if (r() < 0.2) o.start = { x: jit(o.start.x, 0.4), y: jit(o.start.y, 0.4) }; + if (r() < 0.2) o.end = { x: jit(o.end.x, 0.4), y: jit(o.end.y, 0.4) }; + if (r() < 0.15) o.wallTypeId = pick(r, ["aw", "iw"]); + if (r() < 0.2) { + o.hatchSource = pick(r, ["layer", "object"] as const); + if (r() < 0.6) o.hatchId = pick(r, HATCHES); + } + if (r() < 0.15) { o.foreground = pick(r, COLORS); o.foregroundSource = pick(r, ["layer", "object"] as const); } + if (r() < 0.15) { o.background = pick(r, COLORS); o.backgroundSource = pick(r, ["layer", "object"] as const); } + if (r() < 0.3) o.sliceTermination = pick(r, ["below", "above", "both"] as const); + if (r() < 0.1) o.height = round(1 + r() * 3); + return o; + }); + // Öffnungen + const ops = [...(p.openings ?? [])]; + for (let k = 0; k < Math.floor(r() * 5); k++) { + const host = pick(r, p.walls); + const door = r() < 0.4; + ops.push({ + id: `OX${k}`, type: "opening", hostWallId: host.id, categoryCode: r() < 0.9 ? "21" : "22", + kind: door ? "door" : "window", + typeId: door ? pick(r, ["door-standard", "door-entry", "nope", undefined]) : pick(r, ["window-standard", "window-double", "nope", undefined]), + position: round(r() * 3), width: round(0.5 + r() * 1.5), height: round(0.8 + r() * 1.6), sillHeight: door ? 0 : round(r() * 1.2), + ...(door && r() < 0.2 ? { doorType: "wandoeffnung" } : {}), + ...(r() < 0.2 ? { wingCount: 1 + Math.floor(r() * 3) } : {}), + } as never); + } + p.openings = ops.map((o) => (r() < 0.2 ? { ...o, position: jit(o.position, 1), width: Math.max(0.2, jit(o.width, 0.6)) } : o)); + // Decken + p.ceilings = (p.ceilings ?? []).map((c) => ({ + ...c, + ...(r() < 0.3 ? { thickness: round(0.1 + r() * 0.3) } : {}), + ...(r() < 0.2 ? { ceilingTypeId: undefined, wallTypeId: pick(r, ["aw", "iw", "nope"]) } : {}), + ...(r() < 0.2 ? { hatchSource: pick(r, ["layer", "object"] as const), hatchId: pick(r, HATCHES) } : {}), + })); + if (r() < 0.4) { + p.ceilings!.push({ ...p.ceilings![0], id: "CX", floorId: "og", outline: [{ x: -1, y: -1 }, { x: 3, y: -1 }, { x: 3, y: 2 }, { x: -1, y: 2 }] }); + } + // Dächer + p.roofs = (p.roofs ?? []).map((rf) => ({ + ...rf, + shape: pick(r, ["sattel", "walm", "pult", "flach", "mansarde", "zelt", "sattel"] as const), + pitchDeg: round(10 + r() * 40), + overhang: round(r() * 0.8), + ridgeAxis: pick(r, ["x", "y"] as const), + ...(r() < 0.5 ? { roofTypeId: "roof-warm" } : {}), + ...(r() < 0.2 ? { color: pick(r, COLORS) } : {}), + ...(r() < 0.3 ? { thickness: round(r() * 0.4) } : {}), + })); + if (r() < 0.3) p.roofs!.push({ ...p.roofs![0], id: "RX", outline: [{ x: 5, y: 0 }, { x: 8, y: 0 }, { x: 8, y: 3 }, { x: 5, y: 3 }], shape: "pult", roofTypeId: undefined }); + // Treppen + p.stairs = (p.stairs ?? []).map((st) => ({ + ...st, + typeId: pick(r, ["stair-standard", "stair-massiv", "stair-wange-holz", "stair-aufgesattelt", undefined]), + shape: pick(r, ["straight", "straight", "L", "spiral"] as const), + ...(r() < 0.3 ? { start: { x: jit(st.start.x, 2), y: jit(st.start.y, 2) } } : {}), + })); + // Abzugskörper und freie Körper + const solids: ExtrudedSolid[] = []; + for (let k = 0; k < Math.floor(r() * 4); k++) { + const cx = jit(2.5, 6), cy = jit(2, 5), w = 0.3 + r() * 1.5, d = 0.3 + r() * 1.5; + solids.push({ + id: `X${k}`, type: "extrudedSolid", levelId: r() < 0.7 ? "eg" : "og", + points: [{ x: cx, y: cy }, { x: round(cx + w), y: cy }, { x: round(cx + w), y: round(cy + d) }, { x: cx, y: round(cy + d) }], + height: round(0.3 + r() * 2.5), baseOffset: round(r() * 1.5), + ...(r() < 0.7 ? { operation: "subtract" } : {}), + } as ExtrudedSolid); + } + p.extrudedSolids = solids; + if (r() < 0.3) p.context = [terrain(r)]; + return p; +} + +/** Schnitt-/Ansichtsebenen quer durch das Projekt (verschiedene Lagen, Richtungen, Tiefen). */ +export function sectionLevels(p: Project, seed: number, count: number): DrawingLevel[] { + const r = rng(seed * 7 + 1); + let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; + for (const w of p.walls) for (const q of [w.start, w.end]) { + minX = Math.min(minX, q.x); maxX = Math.max(maxX, q.x); minY = Math.min(minY, q.y); maxY = Math.max(maxY, q.y); + } + if (!isFinite(minX)) { minX = 0; minY = 0; maxX = 5; maxY = 4; } + const out: DrawingLevel[] = []; + for (let k = 0; k < count; k++) { + const kind = k % 2 === 0 ? "section" : "elevation"; + const mode = Math.floor(r() * 3); + let a, b; + if (mode === 0) { + const y = round(minY - 1 + r() * (maxY - minY + 2)); + a = { x: minX - 1, y }; b = { x: maxX + 1, y }; + } else if (mode === 1) { + const x = round(minX - 1 + r() * (maxX - minX + 2)); + a = { x, y: minY - 1 }; b = { x, y: maxY + 1 }; + } else { + a = { x: round(minX - 1 + r() * 2), y: round(minY - 1 + r() * (maxY - minY)) }; + b = { x: round(maxX + 1 - r() * 2), y: round(minY + r() * (maxY - minY + 1)) }; + } + if (r() < 0.5) [a, b] = [b, a]; + out.push({ + id: `lvl${k}`, name: `L${k}`, kind, visible: true, locked: false, + linePoints: [a, b], + directionSign: r() < 0.5 ? 1 : -1, + ...(r() < 0.25 ? { depth: round(r() * 6) } : {}), + ...(r() < 0.4 ? { shadows: true } : {}), + ...(r() < 0.3 ? { hiddenLines: true } : {}), + } as DrawingLevel); + } + return out; +} + +/** Grosses Projekt mit Schnitt-/Ansichtslinien quer über alle Kacheln. */ +export function bigSectionProject(n: number): Project { + const p = bigSampleProject(n); + const span = n * 8; + const levels: DrawingLevel[] = [ + { id: "bs1", name: "S1", kind: "section", visible: true, locked: false, linePoints: [{ x: -2, y: 2 }, { x: span, y: 2 }], directionSign: 1 } as DrawingLevel, + { id: "bs2", name: "S2", kind: "section", visible: true, locked: false, linePoints: [{ x: 3.5, y: -2 }, { x: 3.5, y: span }], directionSign: -1, hiddenLines: true } as DrawingLevel, + { id: "be1", name: "E1", kind: "elevation", visible: true, locked: false, linePoints: [{ x: -2, y: -3 }, { x: span, y: -3 }], directionSign: 1, shadows: true } as DrawingLevel, + { id: "be2", name: "E2", kind: "elevation", visible: true, locked: false, linePoints: [{ x: -3, y: span }, { x: -3, y: -2 }], directionSign: 1 } as DrawingLevel, + ]; + return { ...p, drawingLevels: [...p.drawingLevels, ...levels] }; +} diff --git a/src/plan/sectionPort.parity.test.ts b/src/plan/sectionPort.parity.test.ts new file mode 100644 index 00000000..111671e6 --- /dev/null +++ b/src/plan/sectionPort.parity.test.ts @@ -0,0 +1,197 @@ +// VORÜBERGEHEND ([K3c]): Gleichheit alte TS-Fassung gegen den Kern (Schnitt/Ansicht). Wird mit +// der TS-Fassung gelöscht. +import { beforeAll, describe, expect, it } from "vitest"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { setWasmBytesProvider } from "../engine/wasmSource"; +import { computeSection as oldCompute } from "./toSection"; +import { generateSectionPlan as oldGen } from "./generatePlan"; +import { sectionOpeningPrimitives } from "./sectionOpenings"; +import { computeSection as newCompute, generateSectionPlan as newGen, generateElevationPlan as newElev } from "./sectionCore"; +import { generateElevationPlan as oldElev, type ElevationOptions } from "./toElevation"; +import { sampleProject } from "../model/sampleProject"; +import { flattenCategories } from "../model/types"; +import type { DrawingLevel, Project } from "../model/types"; +import type { CategoryDisplayResolver, Plan, Primitive } from "./generatePlan"; +import { planToRenderScene } from "./toRenderScene"; +import { planToSvgString } from "../export/planToSvgString"; +import { bigSectionProject, randomSectionProject, rng, sectionLevels } from "./sectionParity.testing"; + +beforeAll(() => { + setWasmBytesProvider(async (name) => + readFileSync(join(process.cwd(), "src", "engine", name === "trucksolid" ? "pkgTruck/trucksolid_bg.wasm" : "pkg3d/render3d_bg.wasm")), + ); +}); + +/** Erster Unterschied (Pfad) zweier Werte; Zahlen per Object.is, fehlend = undefined. */ +function diff(a: unknown, b: unknown, path = ""): string | null { + if (typeof a === "number" && typeof b === "number") return Object.is(a, b) ? null : `${path}: ${a} != ${b}`; + if (a === b) return null; + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) return `${path}: Länge ${a.length} != ${b.length}`; + for (let i = 0; i < a.length; i++) { + const d = diff(a[i], b[i], `${path}[${i}]`); + if (d) return d; + } + return null; + } + if (a && b && typeof a === "object" && typeof b === "object") { + const ra = a as Record; + const rb = b as Record; + for (const k of new Set([...Object.keys(ra), ...Object.keys(rb)])) { + const d = diff(ra[k], rb[k], `${path}.${k}`); + if (d) return d; + } + return null; + } + return `${path}: ${JSON.stringify(a)} != ${JSON.stringify(b)}`; +} + +const FALLBACK_HATCH = { pattern: "diagonal", scale: 1, angle: 45, color: "#0f0f0f", lineWeight: 0.13, dash: null }; + +/** Alte Ausgabe: render3d-interne Schraffur (Muster als Zahl), die als Plan-Schraffur durchsickerte, wird + * zur vorgesehenen Rückfall-Schraffur (Fehler der alten Fassung, s. TODO [K3c]). */ +function fixOld(p: Primitive, mono: boolean): Primitive { + if (p.kind !== "polygon" || typeof (p.hatch as { pattern: unknown }).pattern !== "number") return p; + stats.foreignHatch++; + return { ...p, hatch: mono ? { ...FALLBACK_HATCH, color: "#1f242c" } : FALLBACK_HATCH, fill: mono ? "#f0f0f0" : p.fill } as Primitive; +} + +interface Opts { mono: boolean; hiddenLines?: boolean; visibleCodes?: Set; categoryDisplay?: CategoryDisplayResolver; openings: boolean } + +function optionSets(project: Project, seed: number): Opts[] { + const r = rng(seed * 13 + 5); + const codes = [...flattenCategories(project.layers).map((c) => c.code), "22", "99"]; + const vis = new Set(codes.filter(() => r() < 0.75)); + const grey = new Set(codes.filter(() => r() < 0.3)); + const hide = new Set(codes.filter(() => r() < 0.15)); + const disp: CategoryDisplayResolver = (c) => ({ render: !hide.has(c), greyed: grey.has(c), locked: false }); + return [ + { mono: false, openings: false, visibleCodes: new Set(codes) }, + { mono: true, openings: true, hiddenLines: true, visibleCodes: vis, categoryDisplay: disp }, + { mono: false, openings: true, categoryDisplay: disp }, + ]; +} + +async function oldPlan(project: Project, level: DrawingLevel, o: Opts): Promise<{ prims: Primitive[]; raw: Primitive[]; bounds: Plan["bounds"] } | null> { + const out = await oldCompute(project, level); + if (!out) return null; + const plan = oldGen(out, o.mono, { hiddenLines: o.hiddenLines, visibleCodes: o.visibleCodes, categoryDisplay: o.categoryDisplay }); + const ops = o.openings ? sectionOpeningPrimitives(project, level, o.visibleCodes, o.categoryDisplay) : []; + return { prims: [...plan.primitives.map((p) => fixOld(p, o.mono)), ...ops], raw: [...plan.primitives, ...ops], bounds: plan.bounds }; +} + +async function newPlan(project: Project, level: DrawingLevel, o: Opts): Promise<{ prims: Primitive[]; bounds: Plan["bounds"]; plan: Plan } | null> { + const out = await newCompute(project, level); + if (!out) return null; + const plan = newGen(out, o.mono, o); + return { prims: plan.primitives, bounds: plan.bounds, plan }; +} + +/** Szene (render2d) und SVG wie die Verbraucher: alt als gewöhnlicher Plan, neu aus dem Puffer. */ +function outputsDiffer(a: { prims: Primitive[]; raw: Primitive[]; bounds: Plan["bounds"] }, b: Plan): string | null { + const sa = JSON.stringify(planToRenderScene({ primitives: a.prims, bounds: a.bounds }, 100)); + const sb = JSON.stringify(planToRenderScene(b, 100)); + if (sa !== sb) return "Szene verschieden"; + const va = planToSvgString({ primitives: a.raw, bounds: a.bounds }, { scaleDenominator: 100 }); + const vb = planToSvgString(b, { scaleDenominator: 100 }); + return va === vb ? null : "SVG verschieden"; +} + +async function settle(f: () => Promise): Promise<{ ok: T } | { err: string }> { + try { + return { ok: await f() }; + } catch (e) { + return { err: String(e) }; + } +} + +/** Vergleicht alt/neu für eine Ebene; liefert Fehlertext oder null. */ +async function compareSection(project: Project, level: DrawingLevel, o: Opts): Promise { + const a = await settle(() => oldPlan(project, level, o)); + const b = await settle(() => newPlan(project, level, o)); + if ("err" in a || "err" in b) { + if ("err" in a && "err" in b) { + stats.errors++; + return null; + } + return `Fehler nur auf einer Seite: alt ${"err" in a ? a.err : "ok"}, neu ${"err" in b ? b.err : "ok"}`; + } + stats.prims += a.ok?.prims.length ?? 0; + if (!a.ok || !b.ok) return a.ok === b.ok ? null : "null nur auf einer Seite"; + return diff({ prims: a.ok.prims, bounds: a.ok.bounds }, { prims: b.ok.prims, bounds: b.ok.bounds }) ?? (FULL ? outputsDiffer(a.ok, b.ok.plan) : null); +} + +/** Szene und SVG mitvergleichen (langsamer). */ +const FULL = process.env.PARITY_FULL !== "0"; + +let stats = { levels: 0, prims: 0, errors: 0, foreignHatch: 0, elevations: 0, elevPrims: 0, elevErrors: 0 }; + +function elevOptions(project: Project, seed: number): ElevationOptions[] { + const [, b, c] = optionSets(project, seed); + return [{}, { mono: true, visibleCodes: b.visibleCodes, categoryDisplay: b.categoryDisplay }, { shadows: true, categoryDisplay: c.categoryDisplay }, { shadows: false, visibleCodes: b.visibleCodes }]; +} + +function compareElevation(project: Project, level: DrawingLevel, o: ElevationOptions): string | null { + const run = (f: typeof oldElev) => { + try { + const pl = f(project, level, o); + return { ok: pl ? { prims: pl.primitives, bounds: pl.bounds, plan: pl } : null }; + } catch (e) { + return { err: String(e) }; + } + }; + const a = run(oldElev); + const b = run(newElev); + if ("err" in a || "err" in b) { + if ("err" in a && "err" in b) { + stats.elevErrors++; + return null; + } + return `Fehler nur auf einer Seite: alt ${"err" in a ? a.err : "ok"}, neu ${"err" in b ? b.err : "ok"}`; + } + stats.elevPrims += a.ok?.prims.length ?? 0; + if (!a.ok || !b.ok) return a.ok === b.ok ? null : "null nur auf einer Seite"; + return diff({ prims: a.ok.prims, bounds: a.ok.bounds }, { prims: b.ok.prims, bounds: b.ok.bounds }) ?? + (FULL ? outputsDiffer({ prims: a.ok.prims, raw: a.ok.prims, bounds: a.ok.bounds }, b.ok.plan) : null); +} + +async function check(project: Project, levels: DrawingLevel[], label: string, seed = 1) { + const sets = optionSets(project, seed); + for (const level of levels.filter((l) => l.kind === "section")) { + for (const [k, o] of sets.entries()) { + const d = await compareSection(project, level, o); + expect(d, `${label} ${level.id} Optionen ${k}`).toBeNull(); + stats.levels++; + } + } + for (const level of levels.filter((l) => l.kind === "elevation")) { + for (const [k, o] of elevOptions(project, seed).entries()) { + const d = compareElevation(project, level, o); + expect(d, `${label} ${level.id} Ansicht-Optionen ${k}`).toBeNull(); + stats.elevations++; + } + } +} + +describe("Schnitt und Ansicht: Kern gleich alter TS-Fassung", () => { + it("Beispielprojekt, viele Schnittlinien", async () => { + const own = sampleProject.drawingLevels; + await check(sampleProject, [...own, ...sectionLevels(sampleProject, 1, 40)], "Beispiel"); + }, 600_000); + + it("Zufallsprojekte", async () => { + const n = Number(process.env.PARITY_N ?? 60); + for (let seed = 1; seed <= n; seed++) { + const p = randomSectionProject(seed); + await check(p, sectionLevels(p, seed, 12), `Saat ${seed}`, seed); + } + console.log("Gleichheit:", stats); + }, 3_600_000); + + it("Grosses Projekt (6×6)", async () => { + const p = bigSectionProject(6); + await check(p, p.drawingLevels, "big6"); + console.log("Gleichheit (gesamt):", stats); + }, 600_000); +}); diff --git a/src/views/viewportContent.tsx b/src/views/viewportContent.tsx index 55c2bf97..5da1acbb 100644 --- a/src/views/viewportContent.tsx +++ b/src/views/viewportContent.tsx @@ -23,13 +23,12 @@ import { categoryNameForPick } from "../core"; import type { PickKind } from "../core"; import { generatePlan, generateSectionPlan, generateVisibleLevelsPlan } from "../core"; import { planWithExtra } from "../core"; -import type { CategoryDisplayResolver, Plan, Primitive } from "../core"; +import type { CategoryDisplayResolver, Primitive } from "../core"; import type { RichTextDoc } from "../text/richText"; import { computeSection, sameSectionInputs, sameSectionLine } from "../core"; import type { SectionOutput } from "../core"; import { generateElevationPlan } from "../core"; import { crossKindOverlayAllowed, planUnderlayPrimitives } from "../core"; -import { sectionOpeningPrimitives } from "../core"; import { levelMarkerPrimitives, levelMarksEnabled } from "../core"; import { setSheetOwnerOutlines, setSheetSnapSegments, snapSegmentsFromPrimitives } from "../tools/sheetSnapGeometry"; import { pushNativeScene, pushNativeWalls } from "./plan/nativeSync"; @@ -923,24 +922,12 @@ function LevelPlanView({ } /** - * Geschnittene Fenster/Türen in den Schnitt-Plan einsetzen: nach den Cut- - * Polygonen (liegen in deren Aussparung), vor den Ansichtskanten — die Reihen- - * folge spielt kaum eine Rolle, da sie sich nicht überdecken. - */ -function withSectionOpenings(plan: Plan, openings: Primitive[]): Plan { - if (openings.length === 0) return plan; - return { ...plan, primitives: [...plan.primitives, ...openings] }; -} - -/** - * Schnitt-/Ansichts-Ebene: der render3d-Schnitt-Extraktor (WASM, plan/toSection) - * durchschneidet das Modell entlang der Schnittlinie der Ebene und übersetzt das - * Ergebnis (Cut-Polygone + sichtbare/verdeckte Kanten) über generateSectionPlan - * in Plan-Primitive, die dieselbe PlanView wie ein Grundriss zeichnet. + * Schnitt-/Ansichts-Ebene: der Kern rechnet Schnitt bzw. Ansicht entlang der Schnittlinie der + * Ebene (`generateSectionPlan`/`generateElevationPlan`, Plan-Puffer v2 mit Pick-Ids, samt den + * geschnittenen Fenstern/Türen), die dieselbe PlanView wie ein Grundriss zeichnet. * - * Die Berechnung ist asynchron (WASM lazy geladen); bis das Ergebnis da ist, - * bzw. wenn die Ebene keine Schnittlinie trägt oder das WASM-Modul den Export - * (noch) nicht kennt, wird ein Hinweis eingeblendet. + * Der Schnitt ist asynchron (die freien Körper baut truck); bis das Ergebnis da ist bzw. wenn + * die Ebene keine Schnittlinie trägt, wird ein Hinweis eingeblendet. */ function SectionPlanView({ project, @@ -1052,9 +1039,8 @@ function SectionPlanView({ selectedDrawingIds?: string[]; gripHandlers: GripHandlers; }) { - // Die Ansicht (kind "elevation") läuft NICHT über den WASM-Schnitt, sondern - // über den rein TS-seitigen Flächen-Generator (Painter, toElevation.ts) — - // synchron, kein Lazy-Load. Nur der echte Schnitt braucht die WASM-Pipeline. + // Die Ansicht (kind "elevation") ist synchron (Kern, Painter); nur der Schnitt wartet auf die + // truck-Körper. const isElevation = level.kind === "elevation"; const [output, setOutput] = useState(null); const [status, setStatus] = useState<"loading" | "ready" | "empty" | "error">( @@ -1122,14 +1108,12 @@ function SectionPlanView({ const sectionPlan = useMemo( () => !isElevation && output - ? withSectionOpenings( - generateSectionPlan(output, mono, { - hiddenLines: level.hiddenLines, - visibleCodes, - categoryDisplay, - }), - sectionOpeningPrimitives(inputs.project, inputs.level, visibleCodes, categoryDisplay), - ) + ? generateSectionPlan(output, mono, { + hiddenLines: level.hiddenLines, + visibleCodes, + categoryDisplay, + openings: true, + }) : null, [isElevation, output, mono, level.hiddenLines, visibleCodes, categoryDisplay, inputs], );