diff --git a/TODO.md b/TODO.md index 3204fb8f..6979d4a9 100644 --- a/TODO.md +++ b/TODO.md @@ -124,6 +124,14 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern 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). + ✅ Behoben (29.10.): Besitzer kommen aus dem Schnitt-Modell statt aus Zählungen — `RSlab::source` (Decke + Schicht bzw. + Treppe), Wände über `RWall::wall_id`; `wall_segment_owners`/`slab_segment_owners`/`split_slab_layers` gelöscht. Jede + Deckenschicht ist ihr eigenes Band mit ihrem Bauteil (vorher wurde jede Schicht-Platte nochmals in alle Schichten geteilt, + ein Teil fiel auf die Rückfall-Schraffur); Treppentritte tragen Treppe/Kategorie, auch für die Tiefe (Mitte des Tritts). + Dächer gehen nicht mehr zusätzlich durch render3d (ungestylte Doppel-Bänder je Schicht × Fläche unter den gestylten, + Besitzer per Index falsch); von der Dominanz beschnittene Stücke behalten Kategorie und Treppe (Ebene aus → weg). + Gewollte Ausgabe-Änderung: nur Schnitte (CLI byte-gleich für Plan/Ansicht auf 9 Projekten, 18 Schnitte geändert, + angesehen: Beispiel, mehrschichtige Decken 4/2/1 Schichten mit Aussparung, 2 Treppen, 2 Dächer); Golden `schnitt.svg` neu. Leistung (29.10., Ausgabe bitgleich, Gleichheitstest nach jedem Schritt): render3d-Verdeckung über ein u-Raster mit nach Tiefe sortierten Zellen und Abbruch bei ganz verdeckter Kante (vorher jede Kante gegen jedes Prisma); Ansicht: Verdecker, Schatten, Eck-Verlängerung über Raster (`ugrid.rs`), Linien-Clipping nah→fern mit Abbruch; Schnitt-Dominanz nur gegen @@ -133,6 +141,18 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern Der Kern merkt sich die zuletzt vorbereiteten Schnitte (Schlüssel je `computeSection`): Schwarz-Weiss/Sichtbarkeit umschalten 8×8 ~1 ms statt Neurechnen. Offen: Szene mit vielen verdeckten (gestrichelten) Kanten bleibt teuer (16×16 mit verdeckten Kanten ~2,5 s, Strichmuster-Zerlegung in `plan_scene`). + ✅ (29.10.) Strichmuster im render2d-Shader statt CPU-Zerlegung: gestrichelte Linien/Züge/Umrisse gehen je Segment als + EINE Instanz (`DashSegment`: Lauflänge, Zuglänge, Muster bis 8 Einträge) an die neue Strich-Pipeline (`DASH_LINE_WGSL`); der + Fragment-Shader setzt Striche, Lücken und runde Strich-Enden je Pixel (Semantik wie `split_dash`, CPU-Spiegel + `dash_coverage` gegen die alte Zerlegung getestet; längere Muster zerlegt weiter die CPU). Die Zerlegung lag in + `render2d::tessellate` (nicht `plan_scene`) und war das eigentliche Problem: big16-Schnitt S2 (385 000 verdeckte Kanten) + 173 Mio. Linien-Vertices/409 Mio. Indizes, `compile_scene` 9 s nativ — und schon 6×6 überschritt die WebGPU-Puffergrenze + (256 MB, „Buffer size … greater than the maximum“), der Schnitt wurde gar nicht gezeichnet. Jetzt 0,36 Mio. Vertices + + 25 MB Instanzen, `compile_scene` ~0,1–0,9 s (Container unter Last). Bilder (Headless, lavapipe, `render_png --scene`): + 13 Ausschnitte Schnitt/Plan alt vs. neu ≤ 0,09 % Pixel abweichend (Kanten-AA), Strich-Enden rund wie vorher. + SVG/PDF/DXF unberührt. Offen: Kern-Seite bleibt (big16 S2: Schnitt-Primitive 0,37 s, `planSceneBin` 0,45 s); der + Chunk-Pfad (`gpu_compile.rs`, WebGL/nativ-Chunks) zeichnet Striche weiterhin durchgezogen. Nicht in der Tauri-App/Metal und + nicht im Browser-WebGPU angesehen (nur lavapipe/Vulkan headless). TS-Fassung gelöscht (29.10.): `toSection.ts`/`toElevation.ts` sind dünne Fassaden (Ebene, Sichtbarkeit, truck-Körper → Abfrage), `sectionOpenings.ts`, `sectionExtras.ts`, `meshSection.ts`, `generateSectionPlan`/`resolve*SectionStyle` in `generatePlan.ts`, `windowSymbol` (opening.ts), `keyhole`/`voidSectionRects`/`subtractVoidsInSection` (voids.ts) und ihre @@ -142,6 +162,13 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern render3d-Verdeckung) nicht neu gebaut. Bleibt in TS: `planUnderlay.ts` (legt den TS-Grundriss unter Schnitt/Ansicht; zieht mit `generatePlan`/`drawing2d.ts` um), das Bauen der truck-Körper (asynchron, eigenes WASM). + ✅ (29.10.) Grundriss-Unterlage im Kern: `plan/underlay.rs`, Abfrage `planUnderlay` (Argumente wie `planDomains` + Ebene + + `minY`) liest den Grundriss aus den Plan-Caches (Haupt-Puffer + Zeichnungs-Stücke), bildet ab (Drehung/Verschiebung, + Schraffurwinkel, Bilder nur ohne Drehung), dimmt, entfernt die Auswahl-Ids und hängt die Schnittlinie an; TS-Fassade + `planUnderlayPrimitives(project, level, floorId, minY, …)` in `generatePlan.ts` (dort auch `crossKindOverlayAllowed`). + `planUnderlay.ts` gelöscht, seine Tests als Rust-Tests. Gleichheit gegen die TS-Fassung (Object.is, inkl. Strip der Ids): + 456 Fälle / 142 405 Primitive (9 Projekte inkl. 2D-Zeichnungen, Schnitt-/Ansichtslinien + schräg/senkrecht/beide + Blickrichtungen, Mono/Detail/Massstab). Nicht in der App angesehen (e2e grün). (Die automatischen Höhenkoten `levelMarkers.ts` rechnet seit 29.10. der Kern, Abfrage `levelMarkers`.) - ◐ **[K3d] Aufräumen:** TS-Primitive-Erzeugung löschen, SVG/PDF/DXF-Export lesen den Puffer. Hängt an [K4]: Rust braucht das typisierte Modell (Bauteil-Typen, Schraffuren, Linienstile, Kategorien) und einen Plan-Puffer v2 mit Pick-IDs + vollem `Primitive`-Umfang @@ -390,6 +417,11 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern 20k Linien 31 → 6 ms / 63 → 7 ms; Kataster 150k 533 → 59 ms / 862 → 39 ms; Plan + WASM-Renderer nach Änderung katbig 90 → 38 ms, Kataster 1,8 → 0,6 s. Erstes Öffnen 200 000 Zeichnungen (`doc_open`) 9,6 → 1,8 s, Speicher 953 → 840 MB. Nicht in der Tauri-App/im nativen Renderer angesehen. + Behoben (29.10.): je nach Code-Layout brach der WASM-Kern mit „assertion failed: psize >= size + min_overhead“ (dlmalloc) + ab, z. B. bei jedem Dach (`roof::compute_canonical`). Ursache: LTO bettete `GrowAhead::dealloc` samt std-dlmalloc + (`validate_size` liest den Chunk-Kopf vor dem Zeiger) in Funktionen ein, die den Block selbst angelegt hatten; LLVM wertete den + Lesezugriff ausserhalb der frischen Allokation als undefiniert und erzeugte eine bedingungslose Panik (im `wasm-objdump` sichtbar). + Die Allokator-Hülle ist jetzt `#[inline(never)]`. Gefunden mit einem Kern, der nach einer harmlosen Änderung reproduzierbar kippte. ✅ (29.10.) **`generatePlan` ganz im Kern** ([K3a]/[K3d]/[K4]): `core/src/plan/extras.rs` rechnet Schattenstudie und Baurecht (unterste Gruppe; Verstösse zuoberst), Abzugskörper (aus Wand-/Stützen-/Decken-Poché, über dieselben flachen Funktionen wie vorher), Schwarz-Weiss und Strichstärken nach Massstab (beim Schreiben, `plan_buf::Writer::post`, auch für die kompakte diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs index 84dbf2cb..78056656 100644 --- a/src-tauri/core/src/model/generated.rs +++ b/src-tauri/core/src/model/generated.rs @@ -1298,7 +1298,7 @@ pub struct DrawingLevel { pub hidden_lines: Option, /// Grundriss-Unterlage (nur Schnitt/Ansicht): ID eines Geschosses, dessen /// Grundriss AUSGERICHTET unter dem Schnitt/der Ansicht gezeigt wird (Schnitt- - /// linie waagrecht, Blickrichtung nach oben, s. `plan/planUnderlay.ts`). + /// linie waagrecht, Blickrichtung nach oben, s. Kern `plan/underlay.rs`). /// Fehlt ⇒ keine Unterlage. #[serde(rename = "planUnderlayId", default, skip_serializing_if = "Option::is_none")] #[ts(optional)] diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index 8cd4726d..2cb44b13 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -41,6 +41,21 @@ pub struct RSlab { pub cut: Option, #[serde(skip_serializing_if = "Option::is_none")] pub monolith: Option, + /// Herkunft der Platte (nur im Kern, nicht serialisiert): der Schnitt ordnet seine Bänder darüber + /// der Decke bzw. Deckenschicht oder der Treppe zu, statt die Platten abzuzählen. + #[serde(skip)] + pub source: SlabSource, +} + +/// Herkunft einer `RSlab`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum SlabSource { + #[default] + None, + /// Index in `Project::ceilings`; `layer` = Schicht des Deckentyps (`None` = ungeschichtet). + Ceiling { index: usize, layer: Option }, + /// Index in `Project::stairs`. + Stair { index: usize }, } /// Ein rohes Dreiecks-Mesh (`RMesh`). @@ -80,11 +95,11 @@ fn ceiling_layers<'a>(p: &'a Project, c: &Ceiling) -> Option<&'a [Layer]> { /// Deckenplatten (`emitSlabs`): eine Platte je Materiallage, oben→unten gestapelt. pub fn emit_slabs(p: &Project) -> Vec { - let mut ceilings: Vec<&Ceiling> = Vec::new(); + let mut ceilings: Vec<(usize, &Ceiling)> = Vec::new(); let mut layers_of: Vec> = Vec::new(); let mut w = FlatWriter::new(); let count = w.slot(); - for c in p.ceilings.as_deref().unwrap_or(&[]) { + for (ci, c) in p.ceilings.as_deref().unwrap_or(&[]).iter().enumerate() { if c.outline.len() < 3 { continue; } @@ -100,7 +115,7 @@ pub fn emit_slabs(p: &Project) -> Vec { for l in layers.unwrap_or(&[]) { w.num(l.thickness); } - ceilings.push(c); + ceilings.push((ci, c)); layers_of.push(layers); } if ceilings.is_empty() { @@ -109,12 +124,12 @@ pub fn emit_slabs(p: &Project) -> Vec { w.set(count, ceilings.len() as f64); let mut out = Vec::new(); for d in crate::ceilings3d::ceilings(&w.done()) { - let c = ceilings[d.ceiling]; + let (ci, c) = ceilings[d.ceiling]; let layers = layers_of[d.ceiling]; let outline: Vec = d.ring.clone(); for (layer_idx, z_bottom, z_top) in d.slabs { let Some(layers) = layers.filter(|_| layer_idx >= 0) else { - out.push(RSlab { outline: outline.clone(), z_bottom, z_top, color: SLAB_RGB, ceiling_id: c.id.clone(), hatch: None, cut: None, monolith: None }); + out.push(RSlab { outline: outline.clone(), z_bottom, z_top, color: SLAB_RGB, ceiling_id: c.id.clone(), hatch: None, cut: None, monolith: None, source: SlabSource::Ceiling { index: ci, layer: None } }); continue; }; let l = &layers[layer_idx as usize]; @@ -142,6 +157,7 @@ pub fn emit_slabs(p: &Project) -> Vec { hatch: resolve_component_hatch(p, &l.component_id, None), cut, monolith: None, + source: SlabSource::Ceiling { index: ci, layer: Some(layer_idx as usize) }, }); } } @@ -729,22 +745,22 @@ fn rail_rgb() -> Rgb { } /// Flache Eingabe der Treppen für `stairs3d` (23 Zahlen je Treppe); `wanted` wählt vor. -fn stair_input<'a>(p: &'a Project, wanted: impl Fn(&Stair, Option<&StairType>) -> bool) -> Option<(Vec<&'a Stair>, Vec)> { - let mut stairs: Vec<&Stair> = Vec::new(); +fn stair_input<'a>(p: &'a Project, wanted: impl Fn(&Stair, Option<&StairType>) -> bool) -> Option<(Vec<(usize, &'a Stair)>, Vec)> { + let mut stairs: Vec<(usize, &Stair)> = Vec::new(); let mut types: Vec> = Vec::new(); - for s in p.stairs.as_deref().unwrap_or(&[]) { + for (si, s) in p.stairs.as_deref().unwrap_or(&[]).iter().enumerate() { let st = p.stair_type(s); if !wanted(s, st) { continue; } - stairs.push(s); + stairs.push((si, s)); types.push(st); } if stairs.is_empty() { return None; } let mut buf = vec![stairs.len() as f64]; - for (s, st) in stairs.iter().zip(&types) { + for (&(_, s), st) in stairs.iter().zip(&types) { let (z_bottom, z_top) = p.stair_vertical_extent(s); buf.extend(s.encode()); buf.push(z_bottom); @@ -773,7 +789,7 @@ pub fn emit_stairs(p: &Project, for_section: bool) -> Vec { crate::stairs3d::slabs(&buf, for_section) .into_iter() .map(|s| { - let stair = stairs[s.src]; + let (si, stair) = stairs[s.src]; RSlab { outline: s.pts, z_bottom: s.z_bottom, @@ -783,6 +799,7 @@ pub fn emit_stairs(p: &Project, for_section: bool) -> Vec { hatch: None, cut: None, monolith: s.monolith.then(|| stair.id.clone()), + source: SlabSource::Stair { index: si }, } }) .collect() diff --git a/src-tauri/core/src/plan/mod.rs b/src-tauri/core/src/plan/mod.rs index d338a96a..b374a275 100644 --- a/src-tauri/core/src/plan/mod.rs +++ b/src-tauri/core/src/plan/mod.rs @@ -13,3 +13,4 @@ pub mod section; pub mod elevation; pub mod cache; pub mod extras; +pub mod underlay; diff --git a/src-tauri/core/src/plan/section.rs b/src-tauri/core/src/plan/section.rs index 5005124e..c47a819e 100644 --- a/src-tauri/core/src/plan/section.rs +++ b/src-tauri/core/src/plan/section.rs @@ -12,7 +12,7 @@ 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 crate::model3d::{self, RSlab, RWall, SlabSource}; use std::collections::{HashMap, HashSet}; /// Tinte der Schnitt-Poché-Umrisslinie (dunkles Grau). @@ -24,7 +24,6 @@ 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; @@ -344,12 +343,9 @@ fn slab_input(s: &RSlab) -> render3d::SlabInput { } } -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) ───────────────────── +// ── Besitzer (Herkunft, die das Schnitt-Modell mitführt) ───────────────────── +// Öffnungs-Lage in der Wand (für die geschnittenen Fenster/Türen). 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); @@ -367,55 +363,36 @@ fn opening_interval(w: &Wall, o: &Opening) -> Option<(f64, f64)> { Some((from, to)) } -/// Je emittiertem Wand-Teilquader die Quellwand (`wallSegmentOwners`). -pub fn wall_segment_owners(p: &Project) -> Vec<&Wall> { - let mut owners = Vec::new(); - let by_wall = p.openings_by_wall(); - 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 by_wall.get(wall.id.as_str()).map_or(&[][..], |v| v.as_slice()) { - 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); - } + +/// Je emittiertem Wand-Teilquader die Quellwand (über `RWall::wall_id`). +fn wall_owners<'a>(p: &'a Project, walls: &[RWall]) -> Vec> { + let mut by_id: HashMap<&str, &Wall> = HashMap::with_capacity(p.walls.len()); + for w in &p.walls { + by_id.entry(w.id.as_str()).or_insert(w); } - owners + walls.iter().map(|w| by_id.get(w.wall_id.as_str()).copied()).collect() +} + +/// Herkunft eines Platten-Bandes: Decke (mit Schicht des Deckentyps) oder Treppe. +#[derive(Clone, Copy, Debug)] +pub enum SlabOwner<'a> { + None, + Ceiling(&'a Ceiling, Option), + Stair(&'a Stair), +} + +/// Je emittierter Platte (Deckenschicht, Treppentritt, Podest) ihre Herkunft (`RSlab::source`). +pub fn slab_owners<'a>(p: &'a Project, slabs: &[RSlab]) -> Vec> { + let ceilings = p.ceilings.as_deref().unwrap_or(&[]); + let stairs = p.stairs.as_deref().unwrap_or(&[]); + slabs + .iter() + .map(|s| match s.source { + SlabSource::Ceiling { index, layer } => ceilings.get(index).map_or(SlabOwner::None, |c| SlabOwner::Ceiling(c, layer)), + SlabSource::Stair { index } => stairs.get(index).map_or(SlabOwner::None, SlabOwner::Stair), + SlabSource::None => SlabOwner::None, + }) + .collect() } /// Ordnung eines JS-Vergleichs `(a, b) => d` (NaN/0 = gleich). @@ -429,22 +406,6 @@ pub fn cmp_num(d: f64) -> std::cmp::Ordering { } } -/// 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 { @@ -560,34 +521,17 @@ fn layer_style( 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; +/// Stil einer geschnittenen Deckenschicht (Füllung, Schraffur, Verschneidung) mit dem Override der Decke. +/// Jede Schicht ist im Schnitt-Modell eine eigene Platte; ihr Band trägt so genau ihr Bauteil. +fn style_slab_layer(cp: &mut Cut, p: &Project, layer: &Layer, owner: &Ceiling) -> Result<(), String> { 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) + 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)?; + cp.fill = Some(fill); + cp.hatch = Some(hatch); + cp.join_priority = Some(comp.join_priority); + cp.component_id = Some(comp.id.clone()); + Ok(()) } /// `wallLayersReversedInU`. @@ -635,7 +579,7 @@ fn split_wall_layers(cp: &Cut, p: &Project, layers: &[Layer], owner: &Wall, u_wo } /// `attachCutStyles`: Stil, Herkunft, Schicht-Bänder, Terminierung, Dominanz. -fn attach_cut_styles(cuts: Vec, p: &Project, plane: &Plane, walls: &[&Wall], slabs: &[&Ceiling]) -> Result, String> { +fn attach_cut_styles(cuts: Vec, p: &Project, plane: &Plane, walls: &[Option<&Wall>], slabs: &[SlabOwner]) -> Result, String> { if cuts.is_empty() { return Ok(cuts); } @@ -651,7 +595,7 @@ fn attach_cut_styles(cuts: Vec, p: &Project, plane: &Plane, walls: &[&Wall] bands.push(cp); } Kind::Wall => { - let owner = walls.get(cp.index).copied(); + let owner = walls.get(cp.index).copied().flatten(); cp.source_id = owner.map(|o| o.id.clone()); cp.category = owner.map(|o| o.category_code.clone()); if let Some(o) = owner { @@ -670,21 +614,31 @@ fn attach_cut_styles(cuts: Vec, p: &Project, plane: &Plane, walls: &[&Wall] 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; + match slabs.get(cp.index).copied().unwrap_or(SlabOwner::None) { + SlabOwner::Ceiling(o, layer) => { + cp.source_id = Some(o.id.clone()); + cp.category = Some(o.category_code.clone()); + 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 { + // Schicht-Platte: Stil genau dieser Schicht; ohne Schicht (Dicke 0) ohne Stil. + if let Some(l) = layer.and_then(|i| layers.get(i)) { + style_slab_layer(&mut cp, p, l, o)?; + } + } else { + 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); + } } - if let Some((fill, hatch)) = ceiling_section_style(p, o) { - cp.fill = Some(fill); - cp.hatch = Some(hatch); + // Treppen-Prismen: Herkunft + Kategorie; Stil = Rückfall-Schraffur (Treppen haben kein Bauteil). + SlabOwner::Stair(st) => { + cp.stair_id = Some(st.id.clone()); + cp.category = Some(st.category_code.clone()); } - cp.join_priority = ceiling_representative_priority(p, o); - cp.component_id = ceiling_representative_component_id(p, o); + SlabOwner::None => {} } bands.push(cp); } @@ -695,7 +649,7 @@ fn attach_cut_styles(cuts: Vec, p: &Project, plane: &Plane, walls: &[&Wall] } /// `applyWallTermination`: Wände mit `sliceTermination` "below"/"above" enden an der Decke. -fn apply_wall_termination(bands: Vec, walls: &[&Wall]) -> Vec { +fn apply_wall_termination(bands: Vec, walls: &[Option<&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(); @@ -708,7 +662,7 @@ fn apply_wall_termination(bands: Vec, walls: &[&Wall]) -> Vec { out.push(b); continue; } - let term = walls.get(b.index).and_then(|w| w.slice_termination); + let term = walls.get(b.index).copied().flatten().and_then(|w| w.slice_termination); let (Some(term @ (SliceTermination::Below | SliceTermination::Above)), Some(jp)) = (term, b.join_priority) else { out.push(b); continue; @@ -773,6 +727,9 @@ fn subtract_dominant_bands(bands: Vec) -> Vec { c.join_priority = src.join_priority; c.component_id = src.component_id.clone(); c.source_id = src.source_id.clone(); + // Herkunft bleibt am Stück (Ebenen-Sichtbarkeit, Treppen-Pick). + c.category = src.category.clone(); + c.stair_id = src.stair_id.clone(); out.push(c); } i += 6; @@ -1128,7 +1085,7 @@ fn centroid(pts: &[Vec2]) -> Option<(f64, f64)> { } /// `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]) { +fn filter_by_depth(out: &mut Output, p: &Project, plane: &Plane, depth: f64, walls: &[Option<&Wall>], slabs: &[SlabOwner], slabs_r: &[RSlab]) { if !(depth > 0.0) { return; } @@ -1140,8 +1097,13 @@ fn filter_by_depth(out: &mut Output, p: &Project, plane: &Plane, depth: f64, wal 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)), + Kind::Wall => walls.get(e.index).copied().flatten().map(|w| ((w.start.x + w.end.x) / 2.0, (w.start.y + w.end.y) / 2.0)), + Kind::Slab => match slabs.get(e.index) { + Some(SlabOwner::Ceiling(c, _)) => centroid(&c.outline), + // Treppe: Mitte des Tritts bzw. Podests selbst. + Some(SlabOwner::Stair(_)) => slabs_r.get(e.index).and_then(|s| centroid(&s.outline.iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect::>())), + _ => None, + }, _ => roofs.get(e.index).and_then(|r| centroid(&r.outline)), } }; @@ -1163,14 +1125,14 @@ pub fn compute_section(p: &Project, level: &LevelSpec, bodies: &[BodyMesh]) -> R 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); + // Dächer nicht durch render3d: deren Bänder (je Schicht × Dachfläche, ohne Stil) lagen unter den + // gestylten aus `append_roof_sections` (doppelte Kontur, Rückfall-Schraffur, Besitzer per Index falsch). + let raw = render3d::cut_section(&rp, &wi, &si, &[]); // Gleiche f32 kommen oft vor (gemeinsame Ecken, Höhen): Umwandlung je Wert nur einmal. let mut conv: HashMap = HashMap::new(); @@ -1188,24 +1150,9 @@ pub fn compute_section(p: &Project, level: &LevelSpec, bodies: &[BodyMesh]) -> R let hidden: Vec = raw.hidden_edges.iter().filter(not_cut).map(&mut 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 walls = wall_owners(p, &walls_r); + let slabs = slab_owners(p, &slabs_r); + let cuts = attach_cut_styles(cuts, p, &plane, &walls, &slabs)?; let cuts = merge_monolith_cuts(cuts, &slabs_r); let base = plane.base(); let u = plane.u_model(); @@ -1214,7 +1161,7 @@ pub fn compute_section(p: &Project, level: &LevelSpec, bodies: &[BodyMesh]) -> R 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); + filter_by_depth(&mut out, p, &plane, d, &walls, &slabs, &slabs_r); } Ok(Some(out)) } @@ -1695,13 +1642,62 @@ mod tests { 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.) + // Kategorie ausgeblendet → keine Dach-Schnittflächen mehr. 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 beschnittene_baender_behalten_ihre_ebene() { + // Von der Dominanz beschnittene Wand-/Deckenstücke tragen ihre Kategorie weiter: Ebene aus → weg. + let p = sample(); + let out = compute_section(&p, &level(&p, "schnitt-a"), &[]).unwrap().unwrap(); + assert!(out.cuts.iter().filter(|c| c.kind != Kind::Body).all(|c| c.category.is_some()), "{:#?}", out.cuts); + let codes: Vec = out.cuts.iter().filter_map(|c| c.category.clone()).collect(); + let vis = Visibility { has_vis: true, invisible: codes.into_iter().collect(), ..Default::default() }; + let (prims, _) = section_primitives(&out, false, false, &vis); + assert!(prims.iter().all(|p| !matches!(p, Primitive::Polygon { .. }))); + } + + /// Mehrschichtige Decke + Treppe im Schnitt: je Deckenschicht genau ein Band mit ihrem Bauteil und + /// ihrer Dicke (nicht jedes Schicht-Prisma nochmals in alle Schichten geteilt), Treppen-Tritte ohne + /// Decken-Besitzer (früher: Besitzer per Zählung, Index-Versatz). + #[test] + fn mehrschichtige_decke_und_treppe_im_schnitt() { + let p = sample(); + let l = level(&p, "schnitt-a"); + let out = compute_section(&p, &l, &[]).unwrap().unwrap(); + let slab: Vec<&Cut> = out.cuts.iter().filter(|c| c.kind == Kind::Slab && c.stair_id.is_none()).collect(); + // Je Schicht ein Band (von stärkeren Wandschichten in Stücke geteilt): Bauteil + Höhenlage. + let mut layers: Vec<(&str, f64, f64)> = Vec::new(); + for c in &slab { + let b = bbox(&c.pts); + let comp = c.component_id.as_deref().expect("Schicht-Bauteil"); + match layers.iter().find(|l| l.0 == comp) { + Some(l) => assert!((l.1 - b[2]).abs() < 1e-5 && (l.2 - b[3]).abs() < 1e-5, "{comp}: {b:?} statt {l:?}"), + None => layers.push((comp, b[2], b[3])), + } + } + assert!(slab.iter().all(|c| c.source_id.as_deref() == Some("C1") && c.category.as_deref() == Some("30"))); + layers.sort_by(|a, b| b.2.total_cmp(&a.2)); + let names: Vec<&str> = layers.iter().map(|l| l.0).collect(); + assert_eq!(names, ["screed", "insulation", "concrete"], "{slab:#?}"); + // Schichtdicken 0.06 / 0.04 / 0.20 von oben nach unten, aneinander anschliessend. + for (l, t) in layers.iter().zip([0.06, 0.04, 0.2]) { + assert!((l.2 - l.1 - t).abs() < 1e-5, "{layers:?}"); + } + assert!((layers[0].1 - layers[1].2).abs() < 1e-5 && (layers[1].1 - layers[2].2).abs() < 1e-5, "{layers:?}"); + // Stil der Schicht (Füllung + Schraffur des Bauteils), nicht die Rückfall-Schraffur ohne Füllung. + assert!(slab.iter().all(|c| c.fill.is_some() && c.hatch.is_some() && c.join_priority.is_some()), "{slab:#?}"); + // Treppe: alle Tritt-Bänder mit Treppen-Herkunft, ohne Decken-Bauteil. + let stair: Vec<&Cut> = out.cuts.iter().filter(|c| c.kind == Kind::Slab && c.stair_id.is_some()).collect(); + assert!(!stair.is_empty()); + assert!(stair.iter().all(|c| c.stair_id.as_deref() == Some("ST1") && c.category.as_deref() == Some("40") && c.component_id.is_none()), "{stair:#?}"); + // Kein Decken-/Treppenband bleibt ohne Herkunft. + assert!(out.cuts.iter().filter(|c| c.kind == Kind::Slab).all(|c| c.source_id.is_some() || c.stair_id.is_some())); + } + #[test] fn puffer_hat_zwei_gruppen() { let p = sample(); @@ -1735,17 +1731,15 @@ mod bench { 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 raw = render3d::cut_section(&render3d::SectionPlane::new(fr(pl.point), fr(pl.normal)), &wi, &si, &[]); let t_cut = t.elapsed(); let t = Instant::now(); let buf = if l.kind == DrawingLevelKind::Section { @@ -1850,7 +1844,7 @@ mod ts_faelle { assert_eq!(rings.len(), 1); assert!(rings[0].len() >= 8); assert_eq!(union_rect_outlines(&[[0.0, 1.0, 0.0, 1.0], [2.0, 3.0, 0.0, 1.0]]).len(), 2); - let slab = |m: Option<&str>| RSlab { outline: vec![], z_bottom: 0.0, z_top: 1.0, color: [0.0; 3], ceiling_id: String::new(), hatch: None, cut: None, monolith: m.map(String::from) }; + let slab = |m: Option<&str>| RSlab { outline: vec![], z_bottom: 0.0, z_top: 1.0, color: [0.0; 3], ceiling_id: String::new(), hatch: None, cut: None, monolith: m.map(String::from), source: SlabSource::None }; let slabs = vec![slab(None), slab(Some("ST1")), slab(Some("ST1"))]; let mk = |i: usize, u0: f64| Cut::new(Kind::Slab, i, vec![[u0, 0.0], [u0 + 1.0, 0.0], [u0 + 1.0, 1.0], [u0, 1.0]]); let out = merge_monolith_cuts(vec![mk(0, 0.0), mk(1, 0.0), mk(2, 0.5)], &slabs); @@ -1870,7 +1864,7 @@ mod ts_faelle { let below = wall(Some(SliceTermination::Below)); let above = wall(Some(SliceTermination::Above)); let both = wall(None); - let run = |w: &Wall, wb: Cut, sb: Cut| apply_wall_termination(vec![wb, sb], &[w]); + let run = |w: &Wall, wb: Cut, sb: Cut| apply_wall_termination(vec![wb, sb], &[Some(w)]); let out = run(&below, band(0.0, 0.3, 0.0, 3.0, Some(10.0), "w"), slab_band(-1.0, 4.0, 2.6, 2.9, 100.0)); assert_eq!(bbox(&by(&out, "w")[0].pts), [0.0, 0.3, 0.0, 2.6]); let out = run(&above, band(0.0, 0.3, 0.0, 3.0, Some(10.0), "w"), slab_band(-1.0, 4.0, 0.0, 0.3, 100.0)); @@ -1894,16 +1888,16 @@ mod ts_faelle { Wall { id: "nah".into(), start: Vec2 { x: 0.0, y: 1.0 }, end: Vec2 { x: 4.0, y: 1.0 }, ..Default::default() }, Wall { id: "fern".into(), start: Vec2 { x: 0.0, y: 9.0 }, end: Vec2 { x: 4.0, y: 9.0 }, ..Default::default() }, ]; - let walls: Vec<&Wall> = p.walls.iter().collect(); + let walls: Vec> = p.walls.iter().map(Some).collect(); let plane = Plane { point: [0.0, 0.0, 0.0], normal: [0.0, 0.0, 1.0] }; let e = |i: usize| Edge { kind: Kind::Wall, index: i, a: [0.0, 0.0], b: [1.0, 0.0] }; let mut out = Output { visible: vec![e(0), e(1)], hidden: vec![e(1)], ..Default::default() }; - filter_by_depth(&mut out, &p, &plane, 3.0, &walls, &[]); + filter_by_depth(&mut out, &p, &plane, 3.0, &walls, &[], &[]); assert_eq!(out.visible.len(), 1); assert_eq!(out.visible[0].index, 0); assert!(out.hidden.is_empty()); let mut all = Output { visible: vec![e(0), e(1)], ..Default::default() }; - filter_by_depth(&mut all, &p, &plane, 0.0, &walls, &[]); + filter_by_depth(&mut all, &p, &plane, 0.0, &walls, &[], &[]); assert_eq!(all.visible.len(), 2, "Tiefe 0 ist kein Filter"); } diff --git a/src-tauri/core/src/plan/underlay.rs b/src-tauri/core/src/plan/underlay.rs new file mode 100644 index 00000000..98f49ce0 --- /dev/null +++ b/src-tauri/core/src/plan/underlay.rs @@ -0,0 +1,314 @@ +//! Grundriss-Unterlage in Schnitt/Ansicht (früher `src/plan/planUnderlay.ts`): ein Geschoss- +//! Grundriss wird AUSGERICHTET unter die Schnitt-/Ansichtsfläche gelegt — die klassische +//! Konstruktion „Ansicht über dem Grundriss“. Die Schnittlinie wird waagrecht gedreht, die +//! Blickrichtung zeigt im Blatt nach OBEN, und die u-Achse stimmt mit der des Schnitts überein +//! (`Plane::u_model`): ein Punkt im Grundriss liegt senkrecht unter seiner Projektion im Schnitt. +//! +//! Reine Starrkörper-Abbildung (Drehung + Verschiebung, keine Spiegelung) — Kreise bleiben Kreise, +//! Bögen behalten ihren Drehsinn. Die Unterlage ist gedimmt, ohne Auswahl-Ids (fremde Projektion: +//! ein Klick darf nie das echte Bauteil wählen) und trägt die Schnittlinie selbst (strichpunktiert). +//! Rechenreihenfolge wie in der TS-Fassung (bitgleich). + +use super::prim::Primitive; +use crate::jsmath::hypot2; +use crate::jsnum::{atan2, max, min}; +use crate::model::Vec2; + +/// Abstand (Meter) zwischen tiefster Schnitt-/Ansichtskante und Grundriss-Oberkante. +pub const GAP_M: f64 = 1.5; + +/// Abbildung Grundriss (Modell x/y) → Schnitt-Blatt (u, Höhe) (`PlanToSectionMap`). +#[derive(Clone, Copy, Debug)] +pub struct SectionMap { + /// Ursprung = Startpunkt der Schnittlinie. + pub p0: Vec2, + /// Horizontale Schnitt-u-Achse im Grundriss (Blickrichtungs-RECHTS). + pub u: Vec2, + /// Blickrichtung im Grundriss (Einheit). + pub n: Vec2, + /// Drehwinkel (Radiant, CCW). + pub theta: f64, + /// Vertikaler Versatz im Blatt. + pub dy: f64, +} + +/// Abbildung aus der Schnitt-/Ansichtslinie (`planToSectionMap`); `None` ohne (gültige) Linie. +pub fn section_map(line: [Vec2; 2], direction_sign: Option) -> Option { + let [p0, p1] = line; + let len = hypot2(p1.x - p0.x, p1.y - p0.y); + if len < 1e-9 { + return None; + } + let dx = (p1.x - p0.x) / len; + let dy = (p1.y - p0.y) / len; + let sign = direction_sign.unwrap_or(1.0); + // Wie `sectionPlaneFromLevel`: Links-Normale der Linie, per directionSign gedreht. + let n = Vec2 { x: -dy * sign, y: dx * sign }; + // Wie `sectionUAxisModel`: u = (n.y, −n.x). + let u = Vec2 { x: n.y, y: -n.x }; + Some(SectionMap { p0, u, n, theta: atan2(n.x, u.x), dy: 0.0 }) +} + +/// Bildet einen Grundriss-Punkt ins Schnitt-Blatt ab (`mapPlanPoint`). +pub fn map_point(m: &SectionMap, p: Vec2) -> Vec2 { + let rx = p.x - m.p0.x; + let ry = p.y - m.p0.y; + Vec2 { x: rx * m.u.x + ry * m.u.y, y: rx * m.n.x + ry * m.n.y + m.dy } +} + +/// Bildet ein Plan-Primitiv ab (`mapPlanPrimitive`). Achsparallele Rasterbilder lassen sich nicht +/// drehen und entfallen — ausser die Abbildung ist eine reine Verschiebung. +pub fn map_primitive(m: &SectionMap, pr: Primitive) -> Option { + let p = |q: Vec2| map_point(m, q); + Some(match pr { + Primitive::Polygon { pts, mut hatch, fill, stroke, stroke_width_mm, greyed, opacity, no_stroke_edges, wall_id, drawing_id, ceiling_id, opening_id, stair_id, room_id, extruded_solid_id, context_object_id, column_id, roof_id, section_line_id } => { + if hatch.origin.is_some() || m.theta != 0.0 { + // SVG-Musterwinkel dreht im Uhrzeigersinn (Bildschirm) = −Winkel im Modell. + hatch.angle -= (m.theta * 180.0) / std::f64::consts::PI; + hatch.origin = hatch.origin.map(p); + } + Primitive::Polygon { pts: pts.into_iter().map(p).collect(), hatch, fill, stroke, stroke_width_mm, greyed, opacity, no_stroke_edges, wall_id, drawing_id, ceiling_id, opening_id, stair_id, room_id, extruded_solid_id, context_object_id, column_id, roof_id, section_line_id } + } + // `motif` ist im Strich-lokalen Raum definiert — dreht mit der Linie mit. + Primitive::Line { a, b, cls, weight_mm, dash, zigzag, motif, color, drawing_id, opening_id, stair_id, greyed, opacity } => Primitive::Line { a: p(a), b: p(b), cls, weight_mm, dash, zigzag, motif, color, drawing_id, opening_id, stair_id, greyed, opacity }, + Primitive::Arc { center, from, to, r, cls, weight_mm, dash, opening_id, stair_id, greyed, opacity } => Primitive::Arc { center: p(center), from: p(from), to: p(to), r, cls, weight_mm, dash, opening_id, stair_id, greyed, opacity }, + Primitive::Text { at, doc, extra_lines, base_pt, color, room_id, greyed, opacity } => Primitive::Text { at: p(at), doc, extra_lines, base_pt, color, room_id, greyed, opacity }, + Primitive::DrawingText { at, text, height_m, angle, color, marks, wrap_width, doc, drawing_id, greyed, opacity } => Primitive::DrawingText { at: p(at), text, height_m, angle: angle + m.theta, color, marks, wrap_width, doc, drawing_id, greyed, opacity }, + Primitive::DrawingTextPath { path_pts, text, height_m, color, drawing_id, greyed, opacity } => Primitive::DrawingTextPath { path_pts: path_pts.into_iter().map(p).collect(), text, height_m, color, drawing_id, greyed, opacity }, + Primitive::DrawingCircle { center, r, fill, stroke, weight_mm, dash, drawing_id, greyed, opacity } => Primitive::DrawingCircle { center: p(center), r, fill, stroke, weight_mm, dash, drawing_id, greyed, opacity }, + Primitive::DrawingArc { center, r, a0, a1, stroke, weight_mm, dash, drawing_id, greyed, opacity } => Primitive::DrawingArc { center: p(center), r, a0: a0 + m.theta, a1: a1 + m.theta, stroke, weight_mm, dash, drawing_id, greyed, opacity }, + Primitive::DrawingImage { min: lo, max: hi, src, opacity, drawing_id, greyed } => { + if m.theta.abs() > 1e-9 { + return None; + } + let (a, b) = (p(lo), p(hi)); + Primitive::DrawingImage { min: Vec2 { x: min(a.x, b.x), y: min(a.y, b.y) }, max: Vec2 { x: max(a.x, b.x), y: max(a.y, b.y) }, src, opacity, drawing_id, greyed } + } + }) +} + +/// Höchster Stützpunkt eines Primitivs (`primitivePoints`, nur y), für die Höhenlage der Unterlage. +fn max_y(pr: &Primitive, acc: &mut f64) { + let mut see = |y: f64| { + if y > *acc { + *acc = y; + } + }; + match pr { + Primitive::Polygon { pts, .. } => pts.iter().for_each(|q| see(q.y)), + Primitive::Line { a, b, .. } => { + see(a.y); + see(b.y); + } + Primitive::Arc { from, to, center, .. } => { + see(from.y); + see(to.y); + see(center.y); + } + Primitive::Text { at, .. } | Primitive::DrawingText { at, .. } => see(at.y), + Primitive::DrawingTextPath { path_pts, .. } => path_pts.iter().for_each(|q| see(q.y)), + Primitive::DrawingCircle { center, r, .. } | Primitive::DrawingArc { center, r, .. } => see(center.y + r), + Primitive::DrawingImage { min, max, .. } => { + see(min.y); + see(max.y); + } + } +} + +/// Auswahl-Ids entfernen (die Geometrie stammt aus einer fremden Projektion) und dimmen. +fn as_reference(pr: Primitive) -> Primitive { + let mut pr = pr.with_greyed(true); + match &mut pr { + Primitive::Polygon { wall_id, drawing_id, ceiling_id, opening_id, stair_id, room_id, extruded_solid_id, context_object_id, column_id, roof_id, section_line_id, .. } => { + for id in [wall_id, drawing_id, ceiling_id, opening_id, stair_id, room_id, extruded_solid_id, context_object_id, column_id, roof_id, section_line_id] { + *id = None; + } + } + Primitive::Line { drawing_id, opening_id, stair_id, .. } => { + *drawing_id = None; + *opening_id = None; + *stair_id = None; + } + Primitive::Arc { opening_id, stair_id, .. } => { + *opening_id = None; + *stair_id = None; + } + Primitive::Text { room_id, .. } => *room_id = None, + Primitive::DrawingText { drawing_id, .. } + | Primitive::DrawingTextPath { drawing_id, .. } + | Primitive::DrawingImage { drawing_id, .. } + | Primitive::DrawingCircle { drawing_id, .. } + | Primitive::DrawingArc { drawing_id, .. } => *drawing_id = None, + } + pr +} + +/// Legt die Grundriss-Primitive ausgerichtet unter einen Schnitt / eine Ansicht, deren tiefste Kante +/// bei `section_min_y` liegt (`planUnderlayPrimitives`): gedimmt, ohne Auswahl-Ids, dazu die +/// Schnittlinie. Ohne gültige Linie leer. +pub fn underlay_primitives(line: Option<[Vec2; 2]>, direction_sign: Option, plan: impl IntoIterator, section_min_y: f64) -> Vec { + let Some(line) = line else { return vec![] }; + let Some(base) = section_map(line, direction_sign) else { return vec![] }; + let mut mapped = Vec::new(); + let mut top = f64::NEG_INFINITY; + for pr in plan { + let Some(q) = map_primitive(&base, pr) else { continue }; + max_y(&q, &mut top); + mapped.push(q); + } + // Die Schnittlinie (w = 0) liegt immer mit in der Unterlage. + if 0.0 > top { + top = 0.0; + } + let shift = section_min_y - GAP_M - top; + let o = Vec2 { x: 0.0, y: 0.0 }; + let shift_map = SectionMap { p0: o, u: Vec2 { x: 1.0, y: 0.0 }, n: Vec2 { x: 0.0, y: 1.0 }, theta: 0.0, dy: shift }; + let mut out: Vec = mapped.into_iter().filter_map(|q| map_primitive(&shift_map, q)).map(as_reference).collect(); + let [l0, l1] = line; + let len = hypot2(l1.x - l0.x, l1.y - l0.y); + out.push(Primitive::Line { + a: Vec2 { x: 0.0, y: shift }, + b: Vec2 { x: len, y: shift }, + cls: "section-underlay-line".into(), + weight_mm: 0.25, + dash: Some(Some(vec![3.0, 0.8, 0.4, 0.8])), + zigzag: None, + motif: None, + color: Some("#8a3b2c".into()), + drawing_id: None, + opening_id: None, + stair_id: None, + greyed: None, + opacity: None, + }); + out +} + +/// Primitive eines `planDomains`-Ergebnisses in Plan-Reihenfolge: Haupt-Puffer mit den Zeichnungs- +/// Stücken an Stelle ihrer (leeren) Gruppe 7. +pub fn plan_out_primitives(out: &super::domains::PlanOut) -> Result, String> { + use crate::plan_buf::View; + let bad = || "planUnderlay: Plan-Puffer unlesbar".to_string(); + let v = View::parse(&out.main).ok_or_else(bad)?; + let main = v.prims().ok_or_else(bad)?; + let groups = v.groups().ok_or_else(bad)?; + let at = groups.get(7).map_or(main.len(), |g| g.0); + let mut prims = Vec::with_capacity(main.len()); + let mut it = main.into_iter(); + prims.extend(it.by_ref().take(at)); + for (_, bytes) in &out.chunks { + let bytes = bytes.as_ref().ok_or_else(|| "planUnderlay: Zeichnungs-Stück fehlt".to_string())?; + prims.extend(View::parse(bytes).and_then(|c| c.prims()).ok_or_else(bad)?); + } + prims.extend(it); + Ok(prims) +} + +/// Argumente aus dem Abfrage-Text: die `planDomains`-Argumente des Geschosses plus `level` (Schnitt/ +/// Ansicht) und `minY` (tiefste Kante des Schnitts). +pub fn parse_args(text: &str) -> Result<(Option<[Vec2; 2]>, Option, f64), String> { + let v: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("planUnderlay: {e}"))?; + let level = super::section::LevelSpec::from_json(v.get("level").unwrap_or(&serde_json::Value::Null)); + let min_y = v.get("minY").and_then(|x| x.as_f64()).ok_or("planUnderlay: minY fehlt")?; + Ok((level.line, level.direction_sign, min_y)) +} + +/// Plan-Puffer (eine Gruppe) der Unterlage. +pub fn underlay_buf(prims: &[Primitive]) -> Vec { + let mut w = crate::plan_buf::Writer::new(false); + w.group(prims); + w.finish() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn v(x: f64, y: f64) -> Vec2 { + Vec2 { x, y } + } + + fn line(a: Vec2, b: Vec2) -> Primitive { + Primitive::Line { a, b, cls: "t".into(), weight_mm: 0.25, dash: None, zigzag: None, motif: None, color: None, drawing_id: Some("d".into()), opening_id: None, stair_id: None, greyed: None, opacity: None } + } + + /// Abfrage auf dem Dokument (Plan-Caches, Zeichnungs-Stücke) == ohne Cache. + #[test] + fn abfrage_mit_und_ohne_cache_gleich() { + let text = include_str!("../../tests/fixtures/sample_project.json"); + let p: crate::model::Project = serde_json::from_str(text).unwrap(); + let mut d = crate::document::Document::from_json(text).unwrap(); + let sec = p.drawing_levels.iter().find(|l| l.line_points.is_some()).unwrap(); + for floor in p.drawing_levels.iter().filter(|l| l.kind == crate::model::DrawingLevelKind::Floor) { + let show: Vec<&str> = p.layers.iter().map(|l| l.code.as_str()).collect(); + let args = serde_json::json!({ "floor": floor.id, "show": show, "scale": 100, "level": serde_json::to_value(sec).unwrap(), "minY": -0.25 }).to_string(); + let plain = crate::queries::run_bin(&p, "planUnderlay", &[1.0], &args).unwrap(); + for _ in 0..2 { + assert_eq!(crate::queries::run_bin_doc(&mut d, "planUnderlay", &[1.0], &args).unwrap(), plain); + } + let n = crate::plan_buf::View::parse(&plain).unwrap().len(); + assert!(n > 5, "{n}"); + } + } + + #[test] + fn blickrichtung_nach_oben_keine_spiegelung() { + // Linie entlang +x, Blick nach +y: reine Verschiebung. + let m = section_map([v(-1.0, 2.0), v(12.0, 2.0)], Some(1.0)).unwrap(); + assert!(m.theta.abs() < 1e-12); + let q = map_point(&m, v(0.0, 5.0)); + assert!((q.x - 1.0).abs() < 1e-12 && (q.y - 3.0).abs() < 1e-12); + // Umgekehrte Blickrichtung: 180°-Drehung. + let r = section_map([v(-1.0, 2.0), v(12.0, 2.0)], Some(-1.0)).unwrap(); + assert!((r.theta.abs() - std::f64::consts::PI).abs() < 1e-12); + assert!((map_point(&r, v(0.0, 0.0)).y - 2.0).abs() < 1e-12); + assert!(section_map([v(1.0, 1.0), v(1.0, 1.0)], None).is_none()); + } + + #[test] + fn u_wie_schnittebene() { + // Ein Punkt liegt senkrecht unter seiner Projektion im Schnitt (u wie `Plane::u_model`). + for (l, p, sign) in [([v(-1.0, 2.0), v(12.0, 2.0)], v(4.0, 7.0), 1.0), ([v(3.0, 0.0), v(3.0, 9.0)], v(6.0, 2.0), -1.0), ([v(0.0, 0.0), v(5.0, 5.0)], v(1.0, 3.0), 1.0)] { + let m = section_map(l, Some(sign)).unwrap(); + let plane = super::super::section::LevelSpec { line: Some(l), direction_sign: Some(sign), ..Default::default() }.plane().unwrap(); + let (ux, uy) = plane.u_model(); + let (bx, by) = plane.base(); + let len = hypot2(ux, uy); + let expected = ((p.x - bx) * ux + (p.y - by) * uy) / len; + assert!((map_point(&m, p).x - expected).abs() < 1e-9); + } + } + + #[test] + fn unterlage_mit_abstand_gedimmt_ohne_ids_plus_schnittlinie() { + let out = underlay_primitives(Some([v(-1.0, 2.0), v(12.0, 2.0)]), Some(1.0), vec![line(v(0.0, 0.0), v(11.0, 6.0))], -0.3); + let Primitive::Line { a, b, greyed, drawing_id, .. } = &out[0] else { panic!() }; + assert_eq!((*greyed, drawing_id.as_deref()), (Some(true), None)); + // Oberste Grundriss-Kante (y = 6 → w = 4) liegt GAP unter der Schnitt-Unterkante. + let top = a.y.max(b.y); + assert!((top - (-0.3 - GAP_M)).abs() < 1e-9); + assert!((a.x.min(b.x) - 1.0).abs() < 1e-9); + let Primitive::Line { a, b, cls, greyed, dash, .. } = out.last().unwrap() else { panic!() }; + assert_eq!(cls, "section-underlay-line"); + assert_eq!(*greyed, None); + assert_eq!(dash, &Some(Some(vec![3.0, 0.8, 0.4, 0.8]))); + assert!((b.x - a.x - 13.0).abs() < 1e-9 && (a.y - (top - 4.0)).abs() < 1e-9); + assert!(underlay_primitives(None, None, vec![line(v(0.0, 0.0), v(1.0, 1.0))], 0.0).is_empty()); + } + + #[test] + fn gedrehte_linie_dreht_schraffur_und_texte_bilder_entfallen() { + use super::super::prim::HatchRender; + let mut hatch: HatchRender = super::super::style::no_hatch(); + hatch.angle = 10.0; + let poly = Primitive::Polygon { pts: vec![v(0.0, 0.0), v(1.0, 0.0), v(1.0, 1.0)], fill: "#fff".into(), stroke: "#000".into(), stroke_width_mm: 0.2, hatch, greyed: None, opacity: None, no_stroke_edges: None, wall_id: Some("W".into()), 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 }; + let img = Primitive::DrawingImage { min: v(0.0, 0.0), max: v(1.0, 1.0), src: "x".into(), opacity: 1.0, drawing_id: None, greyed: None }; + // Linie entlang +y → Drehung um 90°. + let out = underlay_primitives(Some([v(0.0, 0.0), v(0.0, 5.0)]), None, vec![poly, img], 0.0); + assert_eq!(out.len(), 2, "Bild entfällt bei Drehung"); + let Primitive::Polygon { hatch, wall_id, greyed, .. } = &out[0] else { panic!() }; + assert_eq!((wall_id, *greyed), (&None, Some(true))); + // Blick nach −x: θ = −90°, das Muster dreht um +90°. + assert!((hatch.angle - 100.0).abs() < 1e-9, "{}", hatch.angle); + } +} diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs index 468671cb..3bdff3c4 100644 --- a/src-tauri/core/src/queries.rs +++ b/src-tauri/core/src/queries.rs @@ -153,6 +153,14 @@ pub fn run_bin(p: &Project, name: &str, args: &[f64], text: &str) -> Result { + let a = domains::PlanArgs::parse(args[0], text)?; + let (line, sign, min_y) = crate::plan::underlay::parse_args(text)?; + let bytes = domains::plan_domains_buf(p, &a)?; + let prims = crate::plan_buf::View::parse(&bytes).and_then(|v| v.prims()).ok_or("planUnderlay: Plan-Puffer unlesbar")?; + Ok(crate::plan::underlay::underlay_buf(&crate::plan::underlay::underlay_primitives(line, sign, prims, min_y))) + } ("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}")), @@ -172,6 +180,15 @@ pub fn run_bin_doc(d: &mut crate::document::Document, name: &str, args: &[f64], let (p, revs, cache) = d.project_cached().map_err(model_err)?; return crate::plan::domains::plan_domains_cached(p, revs, cache, &a, &have).map(|o| o.encode()); } + if name == "planUnderlay" && args.len() == 1 { + // Der Grundriss kommt aus den Plan-Caches (wie `generatePlan` desselben Geschosses). + let a = crate::plan::domains::PlanArgs::parse(args[0], text)?; + let (line, sign, min_y) = crate::plan::underlay::parse_args(text)?; + let (p, revs, cache) = d.project_cached().map_err(model_err)?; + let out = crate::plan::domains::plan_domains_cached(p, revs, cache, &a, &Default::default())?; + let prims = crate::plan::underlay::plan_out_primitives(&out)?; + return Ok(crate::plan::underlay::underlay_buf(&crate::plan::underlay::underlay_primitives(line, sign, prims, min_y))); + } run_bin(d.project().map_err(model_err)?, name, args, text) } diff --git a/src-tauri/core/src/wasm_alloc.rs b/src-tauri/core/src/wasm_alloc.rs index 8c8075d7..350cd2ae 100644 --- a/src-tauri/core/src/wasm_alloc.rs +++ b/src-tauri/core/src/wasm_alloc.rs @@ -24,7 +24,6 @@ mod imp { impl GrowAhead { /// Nach einem Wachstum (Seitenzahl gestiegen) den Vorrat anlegen und gleich freigeben. - #[inline] unsafe fn after(&self, before: usize) { let now = memory_size(0); if now == before { @@ -39,22 +38,31 @@ mod imp { } } + // Nie in den Aufrufer einbetten: mit LTO wurde `dealloc` (std-dlmalloc samt `validate_size`, das den + // Chunk-Kopf VOR dem Zeiger liest) in Funktionen eingebettet, die den Block selbst angelegt hatten. + // LLVM wertet den Lesezugriff ausserhalb der frischen Allokation als undefiniert und machte aus der + // Prüfung eine bedingungslose Panik („psize >= size + min_overhead", z. B. in `roof::compute_canonical` + // je nach Code-Layout). Als eigener Aufruf ist die Allokator-Hülle für LLVM undurchsichtig. unsafe impl GlobalAlloc for GrowAhead { + #[inline(never)] unsafe fn alloc(&self, l: Layout) -> *mut u8 { let before = memory_size(0); let p = System.alloc(l); self.after(before); p } + #[inline(never)] unsafe fn alloc_zeroed(&self, l: Layout) -> *mut u8 { let before = memory_size(0); let p = System.alloc_zeroed(l); self.after(before); p } + #[inline(never)] unsafe fn dealloc(&self, p: *mut u8, l: Layout) { System.dealloc(p, l) } + #[inline(never)] unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 { let before = memory_size(0); let q = System.realloc(p, l, n); diff --git a/src-tauri/render2d/src/bin/render_png.rs b/src-tauri/render2d/src/bin/render_png.rs index f607d7f4..aee3c943 100644 --- a/src-tauri/render2d/src/bin/render_png.rs +++ b/src-tauri/render2d/src/bin/render_png.rs @@ -4,10 +4,13 @@ // Session funktioniert. // // Start: cargo run --features headless --bin render_png -- [--out PFAD] [--width N] [--height N] +// [--scene szene.bin] [--crop x0,y0,x1,y1] [--scale N] +// `--scene`: Szene-Bytes wie für `set_scene_bin` (statt der Demo); Ausschnitt = Ausmass der Szene, +// `--crop` wählt daraus einen Teil (Anteile 0..1, y von oben), `--scale` den Papier-Massstab 1:N. #![cfg(feature = "headless")] use render2d::headless::HeadlessRenderer; -use render2d::{demo_scene, initial_view_box}; +use render2d::{demo_scene, initial_view_box, ViewBox}; fn main() { // Defaults passend zum Seitenverhaeltnis von `initial_view_box` (990x630 — @@ -15,6 +18,9 @@ fn main() { let mut width = 990u32; let mut height = 630u32; let mut out = String::from("target/headless-demo.png"); + let mut scene_file: Option = None; + let mut crop = [0.0f32, 0.0, 1.0, 1.0]; + let mut paper_n = 100.0f32; let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { @@ -32,12 +38,34 @@ fn main() { .unwrap_or(height); } "--out" => out = args.next().unwrap_or(out), + "--scene" => scene_file = args.next(), + "--scale" => paper_n = args.next().and_then(|v| v.parse().ok()).unwrap_or(paper_n), + "--crop" => { + let v: Vec = args.next().unwrap_or_default().split(',').filter_map(|x| x.parse().ok()).collect(); + if v.len() == 4 { + crop = [v[0], v[1], v[2], v[3]]; + } + } other => eprintln!("render_png: unbekanntes Argument ignoriert: {other}"), } } let mut renderer = HeadlessRenderer::new().expect("Headless-Renderer initialisieren"); - let image = renderer.render_to_image(&demo_scene(), width, height, initial_view_box(), 100.0); + let (scene, view_box) = match &scene_file { + None => (demo_scene(), initial_view_box()), + Some(f) => { + let bytes = std::fs::read(f).expect("Szene lesen"); + let scene = render2d::scene_bin::decode_scene(&bytes).expect("Szene dekodieren"); + // Ausmass (Modell-Meter) → Bildschirm-Raum (x·90, −y·90), dann der Ausschnitt. + let b = render2d::compile_scene(&scene).bounds; + let (x0, x1) = (b[0] * 90.0, b[2] * 90.0); + let (y0, y1) = (-b[3] * 90.0, -b[1] * 90.0); + let (w, h) = (x1 - x0, y1 - y0); + let vb = ViewBox::new(x0 + crop[0] * w, y0 + crop[1] * h, (crop[2] - crop[0]) * w, (crop[3] - crop[1]) * h); + (scene, vb) + } + }; + let image = renderer.render_to_image(&scene, width, height, view_box, paper_n); let png = image.encode_png(); if let Some(parent) = std::path::Path::new(&out).parent() { diff --git a/src-tauri/render2d/src/gpu.rs b/src-tauri/render2d/src/gpu.rs index bd223198..19a33586 100644 --- a/src-tauri/render2d/src/gpu.rs +++ b/src-tauri/render2d/src/gpu.rs @@ -18,8 +18,8 @@ use bytemuck::{Pod, Zeroable}; use wgpu::util::DeviceExt; use crate::ortho::{compute_ortho_matrix, corrected_view_box, meet_scale, mm_to_device_px, Mat4}; -use crate::shaders::{ARC_WGSL, FILL_WGSL, LINE_WGSL}; -use crate::tessellate::{compile_scene, to_screen, ArcInstanceData, BatchKind, GpuGeometry, MAX_ARC_DASH}; +use crate::shaders::{ARC_WGSL, DASH_LINE_WGSL, FILL_WGSL, LINE_WGSL}; +use crate::tessellate::{compile_scene, to_screen, ArcInstanceData, BatchKind, DashSegment, GpuGeometry, MAX_ARC_DASH, MAX_LINE_DASH}; use crate::types::{Scene, Text, TextAlign, ViewBox}; /// MSAA-Faktor: 4x Multisampling fuer glatte Linien-/Fuellkanten (wie im Browser). @@ -92,6 +92,25 @@ impl ArcInstance { } } +/// EIN gestricheltes Segment fuer die GPU (Instanz der Strich-Pipeline, 1:1 zu `DASH_LINE_WGSL`): +/// 16 f32 = 64 Byte. +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct DashInstance { + /// (a.x, a.y, b.x, b.y) Bildschirm-Raum + ab: [f32; 4], + /// (s0, run_len, total, count) Bildschirm-Einheiten + run: [f32; 4], + dash: [f32; 8], +} + +impl DashInstance { + fn from_segment(d: &DashSegment) -> Self { + const _: () = assert!(MAX_LINE_DASH == 8); + Self { ab: [d.a[0], d.a[1], d.b[0], d.b[1]], run: [d.s0, d.run_len, d.total, d.count as f32], dash: d.dash } + } +} + /// Puffer ungemappt anlegen und ueber die Queue befuellen (Groesse auf die /// Kopier-Ausrichtung von 4 Byte aufgerundet, `write_buffer` verlangt das). /// Siehe [`Renderer::upload_scene_queued`]. @@ -142,6 +161,8 @@ struct SceneBuffers { arc_vbo: Option, /// Anzahl Bogen-Instanzen (Draw: 6 Vertices je Instanz). arc_count: u32, + /// Instanz-Puffer der gestrichelten Segmente; None wenn leer. + dash_vbo: Option, geo: GpuGeometry, /// Textzeilen der Szene (Modell-Anker + Papier-mm-Groesse). Werden nicht /// tesselliert, sondern pro Frame ueber den Glyphen-Atlas gesetzt (die @@ -173,6 +194,8 @@ const DEFAULT_TEXT_FAMILY: &str = "Inter"; pub struct Renderer { fill_pipeline: wgpu::RenderPipeline, line_pipeline: wgpu::RenderPipeline, + /// Gestrichelte Linien (Muster im Fragment-Shader, `DASH_LINE_WGSL`), gleiche Globals. + dash_pipeline: wgpu::RenderPipeline, bind_group_layout: wgpu::BindGroupLayout, /// Analytische Bogen-Pipeline (exakter Kreis-Shader, `ARC_WGSL`). arc_pipeline: wgpu::RenderPipeline, @@ -339,6 +362,38 @@ impl Renderer { cache: None, }); + // ── Gestrichelte Linien: je Segment eine Instanz, Quad aus vertex_index ── + let dash_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("dash.wgsl"), + source: wgpu::ShaderSource::Wgsl(DASH_LINE_WGSL.into()), + }); + let dash_instance_layout = wgpu::VertexBufferLayout { + array_stride: 16 * 4, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &wgpu::vertex_attr_array![0 => Float32x4, 1 => Float32x4, 2 => Float32x4, 3 => Float32x4], + }; + let dash_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("dash.pipeline"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &dash_module, + entry_point: Some("vs_main"), + buffers: &[dash_instance_layout], + compilation_options: Default::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &dash_module, + entry_point: Some("fs_main"), + targets: &[Some(wgpu::ColorTargetState { format: color_format, blend, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, cull_mode: None, ..Default::default() }, + depth_stencil: None, + multisample: wgpu::MultisampleState { count: SAMPLE_COUNT, mask: !0, alpha_to_coverage_enabled: false }, + multiview_mask: None, + cache: None, + }); + // ── Analytische Bogen-Pipeline (exakter Kreis-Shader) ───────────────── let arc_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("arc.wgsl"), @@ -431,6 +486,7 @@ impl Renderer { Self { fill_pipeline, line_pipeline, + dash_pipeline, bind_group_layout, arc_pipeline, arc_uniform, @@ -520,6 +576,13 @@ impl Renderer { )) }; + let dash_instances: Vec = geo.dash_segments.iter().map(DashInstance::from_segment).collect(); + let dash_vbo = if dash_instances.is_empty() { + None + } else { + Some(make(bytemuck::cast_slice(&dash_instances), "dash.instances", wgpu::BufferUsages::VERTEX)) + }; + self.scene = Some(SceneBuffers { fill_vbo: mk_vbo(&geo.fill_pos, "fill.vbo"), fill_ibo: mk_ibo(&geo.fill_idx, "fill.ibo"), @@ -527,6 +590,7 @@ impl Renderer { line_ibo: mk_ibo(&geo.line_idx, "line.ibo"), arc_vbo, arc_count, + dash_vbo, geo, texts: scene.texts.clone(), }); @@ -704,6 +768,16 @@ impl Renderer { stroke_scale: mm_px, }); } + BatchKind::Dash => { + let b = &scene.geo.dash_batches[idx as usize]; + blocks.push(Globals { + view_proj: proj, + color: b.color, + viewport_px: [vw, vh], + stroke_px: b.stroke_mm, + stroke_scale: if b.width_screen { px_per_screen } else { mm_px }, + }); + } BatchKind::Line => { let b = &scene.geo.line_batches[idx as usize]; blocks.push(Globals { @@ -918,6 +992,19 @@ impl Renderer { let start = b.start_index; pass.draw_indexed(start..start + b.index_count, 0, 0..1); } + BatchKind::Dash => { + let Some(vbo) = &scene.dash_vbo else { + continue; + }; + if bound != Some(BatchKind::Dash) { + pass.set_pipeline(&self.dash_pipeline); + pass.set_vertex_buffer(0, vbo.slice(..)); + bound = Some(BatchKind::Dash); + } + let b = &scene.geo.dash_batches[idx as usize]; + pass.set_bind_group(0, &u.bind_group, &[block as u32 * stride]); + pass.draw(0..6, b.start..b.start + b.count); + } BatchKind::Line => { let (Some(vbo), Some(ibo)) = (&scene.line_vbo, &scene.line_ibo) else { diff --git a/src-tauri/render2d/src/lib.rs b/src-tauri/render2d/src/lib.rs index 2b720f06..734de800 100644 --- a/src-tauri/render2d/src/lib.rs +++ b/src-tauri/render2d/src/lib.rs @@ -44,8 +44,8 @@ pub mod headless; pub use demo::{demo_scene, initial_view_box}; pub use ortho::{compute_ortho_matrix, meet_scale, mm_to_device_px, Mat4}; pub use tessellate::{ - arc_screen_params, compile_scene, prepare_arc_dash, triangulate, ArcInstanceData, BatchKind, - GpuGeometry, MAX_ARC_DASH, PX_PER_M, + arc_screen_params, compile_scene, dash_coverage, prepare_arc_dash, triangulate, ArcInstanceData, BatchKind, DashBatch, DashSegment, + GpuGeometry, MAX_ARC_DASH, MAX_LINE_DASH, PX_PER_M, }; pub use types::{Arc, FillPolygon, Line, Outline, Point, Rgba, Scene, Text, TextAlign, ViewBox}; diff --git a/src-tauri/render2d/src/shaders.rs b/src-tauri/render2d/src/shaders.rs index 2b67bca5..94c4752e 100644 --- a/src-tauri/render2d/src/shaders.rs +++ b/src-tauri/render2d/src/shaders.rs @@ -262,3 +262,131 @@ fn fs_main(in : VsOut) -> @location(0) vec4 { return vec4(in.color.rgb, a); } "#; + +/// Strich-Pipeline fuer GESTRICHELTE Linien: je Segment EINE Instanz (Quad aus `vertex_index`), +/// das Strichmuster rechnet der Fragment-Shader aus der Lauflaenge (frueher zerlegte die CPU jeden +/// Zug in seine Striche, je mit runden Kappen — bei grossen Schnitten mit verdeckten Kanten +/// Hunderte Millionen Indizes). Gleiche Semantik wie damals (`tessellate::dash_coverage` ist der +/// CPU-Spiegel dieses Shaders): Phase ab Zuganfang ueber Ecken durch, Striche mit runden Enden +/// (Radius = halbe Strichbreite), hinter dem Zugende kein neuer Strich. +/// +/// Das Quad liegt um das Segment, an beiden Enden um die halbe Breite verlaengert (Kappen/Ecken). +/// Breite wie `LINE_WGSL`: `max(1, stroke_px * stroke_scale)` Geraete-px. Alles im Fragment in +/// Geraete-px: `sy` = (Lauflaenge, Querabstand), `seg` = (Segment-Anfang, -Ende, Zuglaenge, halbe +/// Breite), Muster in `d0`/`d1` (bis 8 Eintraege, gerade = Strich). +/// +/// Instanz-Layout: @location(0) ab = (a.x, a.y, b.x, b.y) Bildschirm-Raum, +/// @location(1) run = (s0, run_len, total, count) Bildschirm-Einheiten, +/// @location(2) d0, @location(3) d1 = Muster (Bildschirm-Einheiten). +pub const DASH_LINE_WGSL: &str = r#" +struct Globals { + view_proj : mat4x4, + color : vec4, + viewport_px : vec2, + stroke_px : f32, + stroke_scale : f32, +}; +@group(0) @binding(0) var globals : Globals; + +struct VsOut { + @builtin(position) pos : vec4, + @location(0) sy : vec2, + @location(1) @interpolate(flat) seg : vec4, + @location(2) @interpolate(flat) pat : vec2, + @location(3) @interpolate(flat) d0 : vec4, + @location(4) @interpolate(flat) d1 : vec4, +}; + +@vertex +fn vs_main( + @builtin(vertex_index) vidx : u32, + @location(0) ab : vec4, + @location(1) run : vec4, + @location(2) d0 : vec4, + @location(3) d1 : vec4, +) -> VsOut { + // (u, v): u = 0 Segment-Anfang, 1 Ende; v = Seite (-1/+1). + var corners = array, 6>( + vec2(0.0, -1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), + vec2(0.0, -1.0), vec2(1.0, 1.0), vec2(0.0, 1.0), + ); + let c = corners[vidx]; + let half_vp = globals.viewport_px * 0.5; + let ca = globals.view_proj * vec4(ab.xy, 0.0, 1.0); + let cb = globals.view_proj * vec4(ab.zw, 0.0, 1.0); + // Geraete-px je Bildschirm-Einheit (Ortho, gleichmaessig skaliert). + let cx = globals.view_proj * vec4(ab.xy + vec2(1.0, 0.0), 0.0, 1.0); + let pps = length((cx.xy - ca.xy) * half_vp); + + let seg_v = (cb.xy - ca.xy) * half_vp; + let seg_px = length(seg_v); + var t = vec2(1.0, 0.0); + if (seg_px > 1e-6) { + t = seg_v / seg_px; + } + let nrm = vec2(-t.y, t.x); + let hw = 0.5 * max(1.0, globals.stroke_px * globals.stroke_scale); + let ext = select(-hw, hw, c.x > 0.5); + let base = select(ca, cb, c.x > 0.5); + let off_px = t * ext + nrm * (c.y * hw); + + var out : VsOut; + out.pos = vec4(base.xy + off_px / half_vp, base.z, base.w); + let s0 = run.x * pps; + out.sy = vec2(s0 + c.x * seg_px + ext, c.y * hw); + out.seg = vec4(s0, s0 + seg_px, run.y * pps, hw); + out.pat = vec2(run.z * pps, run.w); + out.d0 = d0 * pps; + out.d1 = d1 * pps; + return out; +} + +@fragment +fn fs_main(in : VsOut) -> @location(0) vec4 { + let s = in.sy.x; + let y = in.sy.y; + let hw = in.seg.w; + let sc = clamp(s, in.seg.x, in.seg.y); + let e_out = abs(s - sc); + let total = in.pat.x; + let n = i32(in.pat.y + 0.5); + var e_in = 0.0; + if (n > 0 && total > 1e-6) { + let k = floor(sc / total); + let m = sc - k * total; + var cyc = array(in.d0.x, in.d0.y, in.d0.z, in.d0.w, in.d1.x, in.d1.y, in.d1.z, in.d1.w); + var acc = 0.0; + var on = true; + var prev_end = 0.0; + var next_start = 0.0; + for (var i = 0; i < 8; i = i + 1) { + if (i >= n) { break; } + let d = cyc[i]; + if (m >= acc && m < acc + d) { + on = (i % 2) == 0; + prev_end = acc; + next_start = acc + d; + } + acc = acc + d; + } + if (!on) { + let b = k * total; + let pe = sc - (b + prev_end); + var ne = b + next_start - sc; + if (b + next_start > in.seg.z) { ne = 1e30; } + e_in = max(min(pe, ne), 0.0); + } + } + let e = e_in + e_out; + var a = globals.color.a; + if (e > 0.0) { + // Rundes Strich-Ende (Abstand zum Strich), Kante ~1 px weich wie die Boegen. + let d = sqrt(e * e + y * y); + a = a * (1.0 - smoothstep(hw - 0.5, hw + 0.5, d)); + } + if (a <= 0.002) { + discard; + } + return vec4(globals.color.rgb, a); +} +"#; diff --git a/src-tauri/render2d/src/tessellate.rs b/src-tauri/render2d/src/tessellate.rs index 59471801..46ad78a6 100644 --- a/src-tauri/render2d/src/tessellate.rs +++ b/src-tauri/render2d/src/tessellate.rs @@ -64,6 +64,90 @@ pub struct ArcInstanceData { pub dash_total: f32, } +/// Hoechstzahl Eintraege eines Linien-Strichmusters (nach Verdoppeln ungerader Muster), die der +/// Strich-Shader (`DASH_LINE_WGSL`) rechnet; laengere Muster zerlegt die CPU wie frueher. +pub const MAX_LINE_DASH: usize = 8; + +/// EIN Segment eines gestrichelten Linienzugs fuer die Strich-Pipeline (eine Instanz, das Quad +/// spannt der Vertex-Shader auf). Statt den Zug entlang des Musters in Hunderte Teilstuecke mit +/// runden Kappen zu zerlegen (`split_dash`: bei verdeckten Kanten grosser Schnitte zig Millionen +/// Vertices, > 256 MB Puffer), traegt jedes Segment seine Lauflaenge; der Fragment-Shader setzt +/// Striche, Luecken und runde Strich-Enden je Pixel (gleiche Semantik, s. [`dash_coverage`]). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct DashSegment { + /// Segment-Anfang/-Ende in Bildschirm-Raum (`to_screen`). + pub a: Point, + pub b: Point, + /// Lauflaenge des Zugs bei `a` (Bildschirm-Einheiten, Phase laeuft ueber Ecken durch). + pub s0: f32, + /// Laenge des ganzen Zugs (Bildschirm-Einheiten): hinter dem Ende beginnt kein Strich mehr. + pub run_len: f32, + /// Zykluslaenge (Bildschirm-Einheiten). + pub total: f32, + /// Gueltige Eintraege in `dash` (gerade Indizes = Strich, ungerade = Luecke). + pub count: u32, + /// An/Aus-Laengen (Bildschirm-Einheiten). + pub dash: [f32; MAX_LINE_DASH], +} + +/// Ein Batch gestrichelter Segmente (Instanz-Bereich) mit Farbe + Strichbreite. +#[derive(Debug, Clone)] +pub struct DashBatch { + pub start: u32, + pub count: u32, + pub color: Rgba, + pub stroke_mm: f32, + pub width_screen: bool, +} + +/// Strichmuster (Papier-mm) → Zyklus in Modell-Metern wie in `split_dash`: negative Werte zu 0, +/// Nullen weg, ungerade Laenge verdoppelt. `None` = kein gueltiges Muster (durchgezogen). +fn dash_cycle_m(dash: &[f32]) -> Option> { + let pat: Vec = dash.iter().copied().map(|d| d.max(0.0) * DASH_MM_TO_M).filter(|d| *d > 0.0).collect(); + if pat.is_empty() { + return None; + } + let cycle: Vec = if pat.len() % 2 == 0 { pat } else { [pat.as_slice(), pat.as_slice()].concat() }; + let total: f32 = cycle.iter().sum(); + (total > 1e-9).then_some(cycle) +} + +/// Deckung eines Pixels durch einen gestrichelten Zug — CPU-Spiegel des Fragment-Shaders +/// (`DASH_LINE_WGSL`, gleiche Rechenschritte), fuer Tests. Alles in Geraete-px: `s` Lauflaenge +/// des Pixels (auch vor/hinter dem Segment, im Kappen-Bereich), `y` Abstand quer zur Achse, +/// `seg` = (Anfang, Ende des Segments, Laenge des Zugs, halbe Strichbreite), `total`/`cyc` das +/// Muster. Liefert den Abstand zum naechsten Strich (0 = auf einem Strich), den der Shader mit +/// der halben Breite vergleicht (runde Strich-Enden wie die frueheren Rund-Kappen). +pub fn dash_coverage(s: f32, y: f32, seg: [f32; 4], total: f32, cyc: &[f32]) -> f32 { + let sc = s.clamp(seg[0], seg[1]); + let e_out = (s - sc).abs(); + let mut e_in = 0.0f32; + if !cyc.is_empty() && total > 1e-6 { + let k = (sc / total).floor(); + let m = sc - k * total; + let mut acc = 0.0f32; + let mut on = true; + let mut prev_end = 0.0f32; + let mut next_start = 0.0f32; + for (i, &d) in cyc.iter().enumerate() { + if m >= acc && m < acc + d { + on = i % 2 == 0; + prev_end = acc; + next_start = acc + d; + } + acc += d; + } + if !on { + let base = k * total; + let pe = sc - (base + prev_end); + let ne = if base + next_start > seg[2] { f32::INFINITY } else { base + next_start - sc }; + e_in = pe.min(ne).max(0.0); + } + } + let e = e_in + e_out; + (e * e + y * y).sqrt() +} + /// Bildschirm-Raum-Parameter eines Bogens: Mittelpunkt + Radius (Bildschirm- /// Einheiten) sowie Start- und Sweep-Winkel IM BILDSCHIRM-RAUM. Der Sweep ist der /// KUERZERE Bogen (|sweep| <= pi) — exakt die Winkel-Normalisierung der frueheren @@ -223,13 +307,19 @@ fn stroke_dashed_or_solid( bounds: &mut Bounds, ) { match dash { - Some(d) if !d.is_empty() => { - for piece in split_dash(pts, d) { - if piece.len() >= 2 { - geo.stroke_polyline(&piece, false, color, stroke_mm, width_screen, bounds); + Some(d) if !d.is_empty() => match dash_cycle_m(d) { + // Strichmuster im Shader: je Segment eine Instanz mit Lauflaenge. + Some(cycle) if cycle.len() <= MAX_LINE_DASH => geo.stroke_dashed(pts, &cycle, color, stroke_mm, width_screen, bounds), + // Ungueltiges Muster: ein offener Zug (wie `split_dash` → ein Stueck); sehr lange + // Muster zerlegt weiter die CPU. + _ => { + for piece in split_dash(pts, d) { + if piece.len() >= 2 { + geo.stroke_polyline(&piece, false, color, stroke_mm, width_screen, bounds); + } } } - } + }, _ => geo.stroke_polyline(pts, closed, color, stroke_mm, width_screen, bounds), } } @@ -360,6 +450,8 @@ pub fn triangulate(pts: &[Point]) -> Vec { pub enum BatchKind { Fill, Line, + /// Gestrichelte Segmente (`GpuGeometry::dash_batches`, Strich-Pipeline). + Dash, } /// Ein zusammenhaengender Zeichen-Batch (Index-Bereich) mit einer Farbe. @@ -403,6 +495,9 @@ pub struct GpuGeometry { /// Analytisch gezeichnete Boegen (je EINE Instanz, kein Segment-Mesh mehr): /// die GPU rendert sie pro Frame exakt rund per SDF-Fragment-Shader. pub arcs: Vec, + /// Segmente gestrichelter Zuege (je EINE Instanz, Muster im Fragment-Shader). + pub dash_segments: Vec, + pub dash_batches: Vec, /// Maler-Reihenfolge ueber BEIDE Batch-Arten hinweg: (Art, Index in /// `fill_batches` bzw. `line_batches`). Der Renderer zeichnet exakt in dieser /// Reihenfolge (Pipeline-Wechsel pro Eintrag) — nur so deckt eine spaetere @@ -467,6 +562,66 @@ impl GpuGeometry { .push((BatchKind::Line, (self.line_batches.len() - 1) as u32)); } + fn add_dash_batch(&mut self, count: u32, color: Rgba, stroke_mm: f32, width_screen: bool) { + let last_idx = self.dash_batches.len().wrapping_sub(1) as u32; + if self.draw_sequence.last() == Some(&(BatchKind::Dash, last_idx)) { + if let Some(last) = self.dash_batches.last_mut() { + if last.stroke_mm == stroke_mm && last.width_screen == width_screen && same_rgba(last.color, color) { + last.count += count; + return; + } + } + } + self.dash_batches.push(DashBatch { start: self.dash_segments.len() as u32 - count, count, color, stroke_mm, width_screen }); + self.draw_sequence.push((BatchKind::Dash, (self.dash_batches.len() - 1) as u32)); + } + + /// Gestrichelter Linienzug (Modell-Meter) mit gueltigem Muster `cycle_m` (Modell-Meter, gerade + /// Laenge): je Segment eine Instanz mit Lauflaenge — Phase wie `split_dash` ueber den ganzen Zug, + /// Segmente kuerzer als 1e-12 m entfallen; ein geschlossener Umriss bleibt offen (wie frueher). + fn stroke_dashed(&mut self, pts: &[Point], cycle_m: &[f32], color: Rgba, stroke_mm: f32, width_screen: bool, bounds: &mut Bounds) { + if pts.len() < 2 { + return; + } + let mut lens: Vec = Vec::with_capacity(pts.len() - 1); + let mut run = 0.0f32; + for w in pts.windows(2) { + let l = ((w[1][0] - w[0][0]).powi(2) + (w[1][1] - w[0][1]).powi(2)).sqrt(); + lens.push(l); + if l >= 1e-12 { + run += l; + } + } + let mut dash = [0.0f32; MAX_LINE_DASH]; + for (d, c) in dash.iter_mut().zip(cycle_m) { + *d = c * PX_PER_M; + } + let total: f32 = cycle_m.iter().sum::() * PX_PER_M; + let before = self.dash_segments.len(); + let mut s0 = 0.0f32; + for (w, &l) in pts.windows(2).zip(&lens) { + if l < 1e-12 { + continue; + } + bounds.track(w[0]); + bounds.track(w[1]); + self.dash_segments.push(DashSegment { + a: to_screen(w[0]), + b: to_screen(w[1]), + s0: s0 * PX_PER_M, + run_len: run * PX_PER_M, + total, + count: cycle_m.len() as u32, + dash, + }); + s0 += l; + } + let n = (self.dash_segments.len() - before) as u32; + if n > 0 { + self.add_dash_batch(n, color, stroke_mm, width_screen); + } + } + /// Zeichnet einen zusammenhaengenden Linienzug (Modell-Meter) mit ECHTEN /// RUNDEN Kappen/Ecken (wie SVG `stroke-linecap/linejoin: round` und der /// Vektor-PDF-Pfad) statt eckigem Butt-Cap/Gehrung: @@ -902,6 +1057,114 @@ mod tests { assert_eq!(prepare_arc_dash(Some(&[])).1, 0); } + // --- Strichmuster im Shader (DashSegment, dash_coverage) ------------------- + + fn dashed_line(a: Point, b: Point, dash: Vec) -> Scene { + Scene { lines: vec![Line { a, b, color: [0.2, 0.2, 0.2, 1.0], width_mm: 0.13, dash: Some(dash), z: 0 }], ..Scene::default() } + } + + #[test] + fn gestrichelte_linie_eine_instanz_statt_zerlegung() { + let geo = compile_scene(&dashed_line([0.0, 0.0], [3.0, 0.0], vec![0.12, 0.08])); + assert!(geo.line_verts.is_empty() && geo.line_idx.is_empty(), "keine Teilstuecke mehr"); + assert_eq!(geo.dash_segments.len(), 1); + assert_eq!(geo.draw_sequence, vec![(BatchKind::Dash, 0)]); + let d = &geo.dash_segments[0]; + assert_eq!(d.a, [0.0, 0.0]); + assert_eq!(d.b, [3.0 * PX_PER_M, 0.0]); + assert_eq!((d.s0, d.run_len, d.count), (0.0, 3.0 * PX_PER_M, 2)); + assert!((d.dash[0] - 0.012 * PX_PER_M).abs() < 1e-5 && (d.dash[1] - 0.008 * PX_PER_M).abs() < 1e-5); + assert!((d.total - 0.02 * PX_PER_M).abs() < 1e-5); + assert_eq!(geo.dash_batches[0].count, 1); + assert_eq!(geo.dash_batches[0].stroke_mm, 0.13); + } + + #[test] + fn gestrichelter_zug_phase_ueber_ecken_und_offener_umriss() { + let pts = vec![[0.0, 0.0], [1.0, 0.0], [1.0, 0.0], [1.0, 2.0]]; + let scene = Scene { + polylines: vec![crate::types::Polyline { pts: pts.clone(), color: [0.0, 0.0, 0.0, 1.0], width_mm: 0.25, dash: Some(vec![1.0]), z: 0, width_screen: false }], + outlines: vec![Outline { pts: vec![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]], color: [0.0, 0.0, 0.0, 1.0], width_mm: 0.25, dash: Some(vec![1.0]), z: 1 }], + ..Scene::default() + }; + let geo = compile_scene(&scene); + // Polylinie: Nullsegment entfaellt, Phase laeuft weiter; Umriss bleibt offen (2 statt 3 Kanten). + assert_eq!(geo.dash_segments.len(), 4); + assert_eq!(geo.dash_segments[1].s0, 1.0 * PX_PER_M); + assert_eq!(geo.dash_segments[1].run_len, 3.0 * PX_PER_M); + assert_eq!(geo.dash_segments[1].count, 2, "ungerades Muster verdoppelt"); + // gleiche Farbe/Breite, aufeinanderfolgend → ein Batch + assert_eq!(geo.dash_batches.len(), 1); + assert_eq!(geo.dash_batches[0].count, 4); + } + + #[test] + fn ungueltiges_oder_langes_muster_wie_bisher() { + // nur Nullen → durchgezogen (ein offener Zug) + let geo = compile_scene(&dashed_line([0.0, 0.0], [1.0, 0.0], vec![0.0, 0.0])); + assert!(geo.dash_segments.is_empty() && !geo.line_idx.is_empty()); + // 9 Eintraege → verdoppelt 18 > MAX_LINE_DASH: CPU-Zerlegung + let geo = compile_scene(&dashed_line([0.0, 0.0], [1.0, 0.0], vec![1.0; 9])); + assert!(geo.dash_segments.is_empty() && !geo.line_idx.is_empty()); + } + + /// Der Shader-Spiegel deckt genau die Pixel, die die frueheren Teilstuecke samt runden Kappen + /// deckten: Abstand zum naechsten `split_dash`-Stueck (Geraete-px) == `dash_coverage`. + #[test] + fn deckung_wie_zerlegung_mit_rundkappen() { + let mut seed = 12345u32; + let mut rnd = || { + seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); + (seed >> 8) as f32 / (1u32 << 24) as f32 + }; + for case in 0..200 { + let len_m = 0.05 + rnd() * 3.0; + let n = 1 + (rnd() * 4.0) as usize; + let pat: Vec = (0..n).map(|_| 0.02 + rnd() * 0.6).collect(); + let pps = 0.5 + rnd() * 4.0; // Geraete-px je Bildschirm-Einheit + let hw = 0.5 + rnd() * 3.0; + let to_px = |m: f32| m * PX_PER_M * pps; + // gerade Strecke, in 1–3 kollineare Segmente geteilt + let cuts: Vec = match case % 3 { + 0 => vec![0.0, len_m], + 1 => vec![0.0, len_m * 0.37, len_m], + _ => vec![0.0, len_m * 0.2, len_m * 0.71, len_m], + }; + let pts: Vec = cuts.iter().map(|&x| [x, 0.0]).collect(); + let geo = compile_scene(&Scene { + polylines: vec![crate::types::Polyline { pts: pts.clone(), color: [0.0; 4], width_mm: 0.2, dash: Some(pat.clone()), z: 0, width_screen: false }], + ..Scene::default() + }); + let pieces = split_dash(&pts, &pat); + for _ in 0..200 { + let s = to_px(-0.1 + rnd() * (len_m + 0.2)); + let y = (rnd() * 2.0 - 1.0) * hw * 1.5; + let old = pieces + .iter() + .map(|p| { + let (p0, p1) = (to_px(p[0][0]), to_px(p[p.len() - 1][0])); + let e = (p0 - s).max(s - p1).max(0.0); + (e * e + y * y).sqrt() + }) + .fold(f32::INFINITY, f32::min); + // jedes Segment deckt seinen Bereich samt halber Breite davor/dahinter + let new = geo + .dash_segments + .iter() + .map(|d| { + let s0 = d.s0 * pps; + let s1 = s0 + (d.b[0] - d.a[0]) * pps; + let cyc: Vec = d.dash[..d.count as usize].iter().map(|v| v * pps).collect(); + dash_coverage(s, y, [s0, s1, d.run_len * pps, hw], d.total * pps, &cyc) + }) + .fold(f32::INFINITY, f32::min); + // Gleiche Entscheidung (gedeckt ja/nein) bis auf Rundung an der Kante. + let tol = 2e-3 * (1.0 + s.abs()); + assert!((old <= hw) == (new <= hw) || (old - hw).abs() < tol || (new - hw).abs() < tol, "Fall {case}: s={s} y={y} alt {old} neu {new} hw {hw}"); + } + } + } + // --- split_dash: geometrische Strichmuster-Zerlegung --------------------- #[test] @@ -958,7 +1221,7 @@ mod tests { } #[test] - fn dash_reduziert_indexanzahl_gegenueber_durchgezogenem_umriss() { + fn gestrichelter_umriss_als_shader_instanzen() { let ring = vec![[0.0, 0.0], [4.0, 0.0], [4.0, 4.0], [0.0, 4.0]]; let solid = Scene { outlines: vec![Outline { @@ -983,12 +1246,9 @@ mod tests { let geo_solid = compile_scene(&solid); let geo_dashed = compile_scene(&dashed); assert!(!geo_solid.line_idx.is_empty()); - assert!(!geo_dashed.line_idx.is_empty()); - assert_ne!( - geo_solid.line_idx.len(), - geo_dashed.line_idx.len(), - "gestrichelter Umriss sollte eine andere (geringere) Indexanzahl als der durchgezogene ergeben" - ); + // Gestrichelt: keine Strich-Dreiecke, je Kante eine Shader-Instanz (Umriss offen wie bisher). + assert!(geo_dashed.line_idx.is_empty()); + assert_eq!(geo_dashed.dash_segments.len(), 3); } #[test] @@ -1021,3 +1281,33 @@ mod tests { assert!((a.r_screen - PX_PER_M).abs() < 1e-3); } } + +#[cfg(test)] +mod bench { + use super::*; + use std::time::Instant; + + /// Messung: `SCENE_BENCH_FILE=szene.bin cargo test --release --lib tessellate::bench -- --ignored --nocapture` + /// (Szene-Bytes wie für `set_scene_bin`). + #[test] + #[ignore] + fn szene_kompilieren() { + let Ok(path) = std::env::var("SCENE_BENCH_FILE") else { return }; + let bytes = std::fs::read(path).unwrap(); + for _ in 0..3 { + let t = Instant::now(); + let scene = crate::scene_bin::decode_scene(&bytes).unwrap(); + let t_dec = t.elapsed(); + let t = Instant::now(); + let geo = compile_scene(&scene); + println!( + "decode {:?} compile {:?} lineVerts {} lineIdx {} fillIdx {}", + t_dec, + t.elapsed(), + geo.line_verts.len() / 6, + geo.line_idx.len(), + geo.fill_idx.len() + ); + } + } +} diff --git a/src/cli/__golden__/schnitt.svg b/src/cli/__golden__/schnitt.svg index 46202ad1..70d53849 100644 --- a/src/cli/__golden__/schnitt.svg +++ b/src/cli/__golden__/schnitt.svg @@ -1,39 +1,35 @@ - - - + + + - - + + - - - - - - - - - + + + + + + + + + - - - - - - - - - - - + + + + + + + diff --git a/src/cli/main.ts b/src/cli/main.ts index 798149c2..ed5b6578 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -590,7 +590,8 @@ async function execute(project: Project, file: string, command: string, rest: st if (kind === "section") { const o = await computeSection(project, lvl); if (!o) fail("keine gültige Schnittlinie"); - plan = generateSectionPlan(o, false, { visibleCodes: allCodes }); + // Wie die App: verdeckte Kanten nach der Ebene, geschnittene Fenster/Türen. + plan = generateSectionPlan(o, false, { visibleCodes: allCodes, hiddenLines: lvl.hiddenLines, openings: true }); } else { plan = generateElevationPlan(project, lvl); if (!plan) fail("keine gültige Ansichtslinie"); diff --git a/src/core/document.ts b/src/core/document.ts index 166f9b76..9aa2ffb1 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -54,6 +54,7 @@ export type QueryName = | "drawingLines" | "drawingPrims" | "levelMarkers" + | "planUnderlay" | "sectionPlan" | "elevationPlan" | "modelJson"; diff --git a/src/core/index.ts b/src/core/index.ts index 35be770d..747db81e 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -241,7 +241,7 @@ export { export { crossKindOverlayAllowed, planUnderlayPrimitives, -} from "../plan/planUnderlay"; +} from "../plan/generatePlan"; export { type Bounds, diff --git a/src/model/types.generated.ts b/src/model/types.generated.ts index c700bcab..fc493bac 100644 --- a/src/model/types.generated.ts +++ b/src/model/types.generated.ts @@ -917,7 +917,7 @@ export type DrawingLevel = { /** * Grundriss-Unterlage (nur Schnitt/Ansicht): ID eines Geschosses, dessen * Grundriss AUSGERICHTET unter dem Schnitt/der Ansicht gezeigt wird (Schnitt- - * linie waagrecht, Blickrichtung nach oben, s. `plan/planUnderlay.ts`). + * linie waagrecht, Blickrichtung nach oben, s. Kern `plan/underlay.rs`). * Fehlt ⇒ keine Unterlage. */ planUnderlayId?: string; diff --git a/src/plan/generatePlan.ts b/src/plan/generatePlan.ts index dddbeb17..6a433a8f 100644 --- a/src/plan/generatePlan.ts +++ b/src/plan/generatePlan.ts @@ -20,6 +20,8 @@ import type { ContextImage, ContextObject, Drawing2D, + DrawingLevel, + DrawingLevelKind, Project, Vec2, } from "../model/types"; @@ -446,6 +448,74 @@ const MAX_CHUNK_STORES = 16; const DETAIL_CODE: Record = { grob: 0, mittel: 1, fein: 2 }; +/** Argumente der Kern-Abfrage `planDomains` (auch `planUnderlay`). */ +function planDomainsArgs( + floorId: string, + visibleCodes: Set, + categoryDisplay: CategoryDisplayResolver, + referenceLines: boolean, + global: boolean, + scale: number, + forPrint: boolean, + compact: boolean, + mono: boolean, + sunWhen: number, +): Record { + // Sichtbar und gezeichnet bzw. gedimmt: über die sichtbaren Codes (wenige), nicht über alle + // Elemente — der Kern zeichnet ein Element genau dann, wenn sein Code in `show` steht. + const show: string[] = []; + const grey: string[] = []; + for (const c of visibleCodes) { + const d = categoryDisplay(c); + if (!d.render) continue; + show.push(c); + if (d.greyed) grey.push(c); + } + return { floor: floorId, show, grey, referenceLines, global, scale, forPrint, compact, mono, sunWhen: Number.isNaN(sunWhen) ? null : sunWhen }; +} + +/** + * Grundriss-Unterlage in Schnitt/Ansicht aus dem Kern (`plan/underlay.rs`, früher `planUnderlay.ts`): + * der Grundriss des Geschosses `floorId` (wie `generatePlan` ohne projektglobale Zutaten, aus den + * Plan-Caches) AUSGERICHTET unter die Schnitt-/Ansichtsfläche gelegt, deren tiefste Kante bei + * `sectionMinY` liegt — Schnittlinie waagrecht, Blickrichtung im Blatt nach oben, u-Achse wie im + * Schnitt. Gedimmt, ohne Auswahl-Ids (fremde Projektion), plus die Schnittlinie (strichpunktiert). + */ +export function planUnderlayPrimitives( + project: Project, + level: DrawingLevel, + floorId: string, + sectionMinY: number, + visibleCodes: Set, + categoryDisplay: CategoryDisplayResolver = SHOW_ALL, + detail: DetailLevel = "mittel", + showReferenceLines = false, + mono = false, + scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR, +): Primitive[] { + const args = planDomainsArgs(floorId, visibleCodes, categoryDisplay, showReferenceLines, false, scaleDenominator, false, false, mono, NaN); + const text = JSON.stringify({ ...args, level: { kind: level.kind, linePoints: level.linePoints, directionSign: level.directionSign }, minY: sectionMinY }); + return decodePlanBuf(documentFor(project).queryBin("planUnderlay", [DETAIL_CODE[detail] ?? 1], text)).prims; +} + +/** + * Welche Fremd-Art-Ebene darf als Unterlage in welcher aktiven Ebene erscheinen? + * Massgebend ist der Koordinatenraum: Geschoss und freie Zeichnung teilen X/Y, + * Schnitte/Ansichten messen dagegen Länge×Höhe entlang IHRER Linie. Ein Schnitt + * im Grundriss (oder ein Grundriss/eine andere Ansicht im Schnitt) lag darum + * nur zufällig irgendwo und überdeckte den eigentlichen Plan (Nutzer-Report + * 2026-10-20: Fenster der Ansicht im EG-Grundriss, Raumstempel im Schnitt). + * • freie Zeichnung: alles (Kalkierpapier zum Abzeichnen, Nutzer-Wunsch). + * • Geschoss: nur freie Zeichnungen (gleicher X/Y-Raum). + * • Schnitt/Ansicht: nichts — ein Grundriss kommt dort ausgerichtet über + * `DrawingLevel.planUnderlayId` dazu (s. {@link planUnderlayPrimitives}). + */ +export function crossKindOverlayAllowed(active: DrawingLevelKind, other: DrawingLevelKind): boolean { + if (active === "drawing") return true; + if (active === "floor") return other === "drawing"; + return false; +} + /** * Der Grundriss eines Geschosses aus dem Kern: Decken, Dächer, Räume, Wände mit Öffnungen, Treppen, * Stützen, 2D-Zeichnungen, Extrusions-Umrisse und (mit `global`) Schatten, Baurecht, Kontext-Konturen @@ -468,17 +538,7 @@ function planDomains( /** Zeitpunkt der Schattenstudie (Unix-ms, NaN = keiner). */ sunWhen: number, ): DomainPrims { - // Sichtbar und gezeichnet bzw. gedimmt: über die sichtbaren Codes (wenige), nicht über alle - // Elemente — der Kern zeichnet ein Element genau dann, wenn sein Code in `show` steht. - const show: string[] = []; - const grey: string[] = []; - for (const c of visibleCodes) { - const d = categoryDisplay(c); - if (!d.render) continue; - show.push(c); - if (d.greyed) grey.push(c); - } - const args = JSON.stringify({ floor: floorId, show, grey, referenceLines, global, scale, forPrint, compact, mono, sunWhen: Number.isNaN(sunWhen) ? null : sunWhen }); + const args = JSON.stringify(planDomainsArgs(floorId, visibleCodes, categoryDisplay, referenceLines, global, scale, forPrint, compact, mono, sunWhen)); const held = chunkStores.get(args); const query = held && held.size ? `${args.slice(0, -1)},"have":[${[...held.keys()].join(",")}]}` : args; const res = readPlanMulti(documentFor(project).queryBin("planDomains", [DETAIL_CODE[detail] ?? 1], query), held); diff --git a/src/plan/generatePlan.underlay.test.ts b/src/plan/generatePlan.underlay.test.ts index 7a422abd..4e1f4e6d 100644 --- a/src/plan/generatePlan.underlay.test.ts +++ b/src/plan/generatePlan.underlay.test.ts @@ -165,3 +165,41 @@ describe("Ebenen ein-/ausblenden (Kataster-Performance)", () => { expect(lineHash(generatePlan(recolored, "L1", vis(["60"])))).not.toBe(first); }); }); + +// Grundriss-Unterlage unter Schnitt/Ansicht (Kern `plan/underlay.rs`; Rechnung dort getestet). +import { crossKindOverlayAllowed, planUnderlayPrimitives } from "./generatePlan"; +import { sampleProject } from "../model/sampleProject"; + +describe("planUnderlayPrimitives (Kern)", () => { + it("Grundriss gedimmt, ohne Auswahl-Ids, unter dem Schnitt, plus Schnittlinie", () => { + const sec = sampleProject.drawingLevels.find((l) => l.kind === "section")!; + const eg = sampleProject.drawingLevels.find((l) => l.kind === "floor")!; + const codes = new Set(sampleProject.layers.map((l) => l.code)); + const out = planUnderlayPrimitives(sampleProject, sec, eg.id, -0.3, codes); + expect(out.length).toBeGreaterThan(10); + const last = out[out.length - 1]; + expect(last.kind === "line" && last.cls).toBe("section-underlay-line"); + const body = out.slice(0, -1); + expect(body.every((p) => (p as { greyed?: boolean }).greyed === true)).toBe(true); + expect(body.some((p) => "wallId" in p || "roomId" in p || "drawingId" in p)).toBe(false); + let top = -Infinity; + for (const p of body) if (p.kind === "polygon") for (const q of p.pts) top = Math.max(top, q.y); + expect(top).toBeLessThanOrEqual(-0.3 - 1.5 + 1e-9); + // ohne Schnittlinie: nichts + expect(planUnderlayPrimitives(sampleProject, { ...sec, linePoints: undefined }, eg.id, 0, codes)).toEqual([]); + }); +}); + +describe("crossKindOverlayAllowed", () => { + it("nur Ebenen im selben Koordinatenraum überlagern sich", () => { + expect(crossKindOverlayAllowed("floor", "drawing")).toBe(true); + expect(crossKindOverlayAllowed("floor", "section")).toBe(false); + expect(crossKindOverlayAllowed("floor", "elevation")).toBe(false); + expect(crossKindOverlayAllowed("section", "floor")).toBe(false); + expect(crossKindOverlayAllowed("elevation", "section")).toBe(false); + expect(crossKindOverlayAllowed("section", "drawing")).toBe(false); + // Freie Zeichnung bleibt Kalkierpapier für alles. + expect(crossKindOverlayAllowed("drawing", "section")).toBe(true); + expect(crossKindOverlayAllowed("drawing", "floor")).toBe(true); + }); +}); diff --git a/src/plan/planUnderlay.test.ts b/src/plan/planUnderlay.test.ts deleted file mode 100644 index a7720515..00000000 --- a/src/plan/planUnderlay.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { describe, expect, it } from "vitest"; -import type { DrawingLevel } from "../model/types"; -import type { Primitive } from "./generatePlan"; -import { - PLAN_UNDERLAY_GAP_M, - crossKindOverlayAllowed, - mapPlanPoint, - planToSectionMap, - planUnderlayPrimitives, -} from "./planUnderlay"; -import { sectionPlaneFromLevel, sectionUAxisModel } from "./toSection"; - -const level = (p0: { x: number; y: number }, p1: { x: number; y: number }, sign: 1 | -1 = 1): DrawingLevel => ({ - id: "s", - name: "S", - kind: "section", - visible: true, - locked: false, - linePoints: [p0, p1], - directionSign: sign, -}); - -const line = (a: { x: number; y: number }, b: { x: number; y: number }): Primitive => ({ - kind: "line", - a, - b, - cls: "t", - weightMm: 0.25, -}); - -describe("planToSectionMap", () => { - it("u stimmt mit der Schnitt-u-Achse überein (Punkt liegt senkrecht unter seiner Projektion)", () => { - for (const [lv, p] of [ - [level({ x: -1, y: 2 }, { x: 12, y: 2 }), { x: 4, y: 7 }], - [level({ x: 3, y: 0 }, { x: 3, y: 9 }, -1), { x: 6, y: 2 }], - [level({ x: 0, y: 0 }, { x: 5, y: 5 }), { x: 1, y: 3 }], - ] as const) { - const m = planToSectionMap(lv)!; - const plane = sectionPlaneFromLevel(lv)!; - const uAx = sectionUAxisModel(plane); - const len = Math.hypot(uAx.x, uAx.y); - const uExpected = ((p.x - plane.point[0]) * uAx.x + (p.y - plane.point[2]) * uAx.y) / len; - expect(mapPlanPoint(m, p).x).toBeCloseTo(uExpected, 9); - } - }); - - it("Blickrichtung zeigt im Blatt nach oben, keine Spiegelung", () => { - // Linie entlang +x, Blick nach +y (Norden): reine Verschiebung. - const m = planToSectionMap(level({ x: -1, y: 2 }, { x: 12, y: 2 }))!; - expect(m.theta).toBeCloseTo(0, 12); - const q = mapPlanPoint(m, { x: 0, y: 5 }); - expect(q.x).toBeCloseTo(1, 12); - expect(q.y).toBeCloseTo(3, 12); // 3 m hinter der Linie → 3 m nach oben - // Umgekehrte Blickrichtung: 180°-Drehung (Determinante +1). - const r = planToSectionMap(level({ x: -1, y: 2 }, { x: 12, y: 2 }, -1))!; - expect(Math.abs(r.theta)).toBeCloseTo(Math.PI, 12); - expect(mapPlanPoint(r, { x: 0, y: 0 }).y).toBeCloseTo(2, 12); - }); - - it("ohne Linie keine Abbildung", () => { - expect(planToSectionMap({ ...level({ x: 0, y: 0 }, { x: 1, y: 0 }), linePoints: undefined })).toBeNull(); - }); -}); - -describe("planUnderlayPrimitives", () => { - it("legt den Grundriss mit Abstand unter den Schnitt, gedimmt, plus Schnittlinie", () => { - const lv = level({ x: -1, y: 2 }, { x: 12, y: 2 }); - const out = planUnderlayPrimitives(lv, [line({ x: 0, y: 0 }, { x: 11, y: 6 })], -0.3); - const mapped = out[0] as Extract; - expect(mapped.greyed).toBe(true); - // Oberste Grundriss-Kante (y = 6 → w = 4) liegt GAP unter der Schnitt-Unterkante. - const top = Math.max(mapped.a.y, mapped.b.y); - expect(top).toBeCloseTo(-0.3 - PLAN_UNDERLAY_GAP_M, 9); - // u bleibt erhalten (x − (−1)). - expect(Math.min(mapped.a.x, mapped.b.x)).toBeCloseTo(1, 9); - const cut = out[out.length - 1] as Extract; - expect(cut.cls).toBe("section-underlay-line"); - expect(cut.b.x - cut.a.x).toBeCloseTo(13, 9); - // Schnittlinie liegt 4 m unter der obersten Grundriss-Kante (w = 0). - expect(cut.a.y).toBeCloseTo(top - 4, 9); - }); -}); - -describe("crossKindOverlayAllowed", () => { - it("nur Ebenen im selben Koordinatenraum überlagern sich", () => { - expect(crossKindOverlayAllowed("floor", "drawing")).toBe(true); - expect(crossKindOverlayAllowed("floor", "section")).toBe(false); - expect(crossKindOverlayAllowed("floor", "elevation")).toBe(false); - expect(crossKindOverlayAllowed("section", "floor")).toBe(false); - expect(crossKindOverlayAllowed("elevation", "section")).toBe(false); - expect(crossKindOverlayAllowed("section", "drawing")).toBe(false); - // Freie Zeichnung bleibt Kalkierpapier für alles. - expect(crossKindOverlayAllowed("drawing", "section")).toBe(true); - expect(crossKindOverlayAllowed("drawing", "floor")).toBe(true); - }); -}); diff --git a/src/plan/planUnderlay.ts b/src/plan/planUnderlay.ts deleted file mode 100644 index 8f40bc2d..00000000 --- a/src/plan/planUnderlay.ts +++ /dev/null @@ -1,184 +0,0 @@ -// Grundriss-Unterlage in Schnitt/Ansicht: ein Geschoss-Grundriss wird -// AUSGERICHTET unter die Schnitt-/Ansichtsfläche gelegt — wie die klassische -// Konstruktion "Ansicht über dem Grundriss". Die Schnittlinie wird dazu -// waagrecht gedreht, die Blickrichtung zeigt im Blatt nach OBEN (Betrachter -// steht unten, die gesehene Fassade liegt an der Unterkante des Grundrisses), -// und die u-Achse stimmt exakt mit der des Schnitts/der Ansicht überein -// (`sectionUAxisModel`, im Kern `Plane::u_model` bzw. der Ansichts-Rahmen): ein Punkt im Grundriss liegt also -// senkrecht unter seiner Projektion im Schnitt. -// -// Reine Starrkörper-Abbildung (Drehung + Verschiebung, keine Spiegelung) — -// Kreise bleiben Kreise, Bögen behalten ihren Drehsinn. - -import type { DrawingLevel, DrawingLevelKind, Vec2 } from "../model/types"; -import type { Primitive } from "./generatePlan"; - -/** Abstand (Meter) zwischen tiefster Schnitt-/Ansichtskante und Grundriss-Oberkante. */ -export const PLAN_UNDERLAY_GAP_M = 1.5; - -/** Abbildung Grundriss (Modell x/y) → Schnitt-Blatt (u, Höhe). */ -export interface PlanToSectionMap { - /** Ursprung = Startpunkt der Schnittlinie. */ - p0: Vec2; - /** Horizontale Schnitt-u-Achse im Grundriss (Blickrichtungs-RECHTS). */ - u: Vec2; - /** Blickrichtung im Grundriss (Einheit). */ - n: Vec2; - /** Drehwinkel (Radiant, CCW) der Abbildung. */ - theta: number; - /** Vertikaler Versatz im Blatt. */ - dy: number; -} - -/** - * Baut die Abbildung aus der Schnitt-/Ansichtslinie einer Ebene (`null` ohne - * Linie). `dy` bleibt 0 — der Aufrufer schiebt den Grundriss danach unter den - * Schnitt (s. {@link planUnderlayPrimitives}). - */ -export function planToSectionMap(level: DrawingLevel): PlanToSectionMap | null { - const line = level.linePoints; - if (!line) return null; - const [p0, p1] = line; - const len = Math.hypot(p1.x - p0.x, p1.y - p0.y); - if (len < 1e-9) return null; - const dx = (p1.x - p0.x) / len; - const dy = (p1.y - p0.y) / len; - const sign = level.directionSign ?? 1; - // Wie `sectionPlaneFromLevel`: Links-Normale der Linie, per directionSign gedreht. - const n: Vec2 = { x: -dy * sign, y: dx * sign }; - // Wie `sectionUAxisModel`: u = (n.y, −n.x) — Blickrichtungs-RECHTS. - const u: Vec2 = { x: n.y, y: -n.x }; - // Bild der x-Achse (1,0) ist (u.x, n.x) → cosθ = u.x, sinθ = n.x. - return { p0, u, n, theta: Math.atan2(n.x, u.x), dy: 0 }; -} - -/** Bildet einen Grundriss-Punkt ins Schnitt-Blatt ab. */ -export function mapPlanPoint(m: PlanToSectionMap, p: Vec2): Vec2 { - const rx = p.x - m.p0.x; - const ry = p.y - m.p0.y; - return { x: rx * m.u.x + ry * m.u.y, y: rx * m.n.x + ry * m.n.y + m.dy }; -} - -/** - * Bildet ein Plan-Primitiv ab. Achsparallele Rasterbilder lassen sich nicht - * drehen und entfallen (`null`) — ausser die Abbildung ist eine reine - * Verschiebung. - */ -export function mapPlanPrimitive(m: PlanToSectionMap, pr: Primitive): Primitive | null { - const P = (p: Vec2) => mapPlanPoint(m, p); - switch (pr.kind) { - case "polygon": { - const hatch = pr.hatch.origin || m.theta !== 0 - ? { - ...pr.hatch, - // SVG-Musterwinkel dreht im Uhrzeigersinn (Bildschirm) = −Winkel im Modell. - angle: pr.hatch.angle - (m.theta * 180) / Math.PI, - origin: pr.hatch.origin ? P(pr.hatch.origin) : undefined, - } - : pr.hatch; - return { ...pr, pts: pr.pts.map(P), hatch }; - } - case "line": - // `motif` ist im Strich-lokalen Raum definiert — dreht mit der Linie mit. - return { ...pr, a: P(pr.a), b: P(pr.b) }; - case "arc": - return { ...pr, center: P(pr.center), from: P(pr.from), to: P(pr.to) }; - case "text": - return { ...pr, at: P(pr.at) }; - case "drawingText": - return { ...pr, at: P(pr.at), angle: pr.angle + m.theta }; - case "drawingTextPath": - return { ...pr, pathPts: pr.pathPts.map(P) }; - case "drawingCircle": - return { ...pr, center: P(pr.center) }; - case "drawingArc": - return { ...pr, center: P(pr.center), a0: pr.a0 + m.theta, a1: pr.a1 + m.theta }; - case "drawingImage": { - if (Math.abs(m.theta) > 1e-9) return null; - const a = P(pr.min); - const b = P(pr.max); - return { - ...pr, - min: { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y) }, - max: { x: Math.max(a.x, b.x), y: Math.max(a.y, b.y) }, - }; - } - } -} - -/** Alle Stützpunkte eines Primitivs (für die Höhenlage der Unterlage). */ -function primitivePoints(pr: Primitive): Vec2[] { - switch (pr.kind) { - case "polygon": return pr.pts; - case "line": return [pr.a, pr.b]; - case "arc": return [pr.from, pr.to, pr.center]; - case "text": - case "drawingText": return [pr.at]; - case "drawingTextPath": return pr.pathPts; - case "drawingCircle": - case "drawingArc": - return [{ x: pr.center.x, y: pr.center.y + pr.r }]; - case "drawingImage": return [pr.min, pr.max]; - } -} - -/** - * Legt die Grundriss-Primitive `planPrims` ausgerichtet unter einen Schnitt/ - * eine Ansicht, deren tiefste Kante bei `sectionMinY` liegt. Die Unterlage ist - * gedimmt (Referenz) und trägt zusätzlich die Schnittlinie selbst (strichpunk- - * tiert), damit sichtbar ist, wo geschnitten bzw. von wo geblickt wird. - */ -export function planUnderlayPrimitives( - level: DrawingLevel, - planPrims: Primitive[], - sectionMinY: number, -): Primitive[] { - const base = planToSectionMap(level); - if (!base) return []; - const mapped: Primitive[] = []; - let maxY = -Infinity; - for (const pr of planPrims) { - const q = mapPlanPrimitive(base, pr); - if (!q) continue; - for (const p of primitivePoints(q)) if (p.y > maxY) maxY = p.y; - mapped.push(q); - } - // Schnittlinie (w = 0) liegt immer mit in der Unterlage. - if (0 > maxY) maxY = 0; - const shift = sectionMinY - PLAN_UNDERLAY_GAP_M - maxY; - const out: Primitive[] = []; - for (const q of mapped) { - const moved = mapPlanPrimitive({ p0: { x: 0, y: 0 }, u: { x: 1, y: 0 }, n: { x: 0, y: 1 }, theta: 0, dy: shift }, q); - if (moved) out.push({ ...moved, greyed: true } as Primitive); - } - const [l0, l1] = level.linePoints!; - const len = Math.hypot(l1.x - l0.x, l1.y - l0.y); - out.push({ - kind: "line", - a: { x: 0, y: shift }, - b: { x: len, y: shift }, - cls: "section-underlay-line", - weightMm: 0.25, - dash: [3, 0.8, 0.4, 0.8], - color: "#8a3b2c", - }); - return out; -} - -/** - * Welche Fremd-Art-Ebene darf als Unterlage in welcher aktiven Ebene erscheinen? - * Massgebend ist der Koordinatenraum: Geschoss und freie Zeichnung teilen X/Y, - * Schnitte/Ansichten messen dagegen Länge×Höhe entlang IHRER Linie. Ein Schnitt - * im Grundriss (oder ein Grundriss/eine andere Ansicht im Schnitt) lag darum - * nur zufällig irgendwo und überdeckte den eigentlichen Plan (Nutzer-Report - * 2026-10-20: Fenster der Ansicht im EG-Grundriss, Raumstempel im Schnitt). - * • freie Zeichnung: alles (Kalkierpapier zum Abzeichnen, Nutzer-Wunsch). - * • Geschoss: nur freie Zeichnungen (gleicher X/Y-Raum). - * • Schnitt/Ansicht: nichts — ein Grundriss kommt dort ausgerichtet über - * `DrawingLevel.planUnderlayId` dazu (s. plan/planUnderlay.ts). - */ -export function crossKindOverlayAllowed(active: DrawingLevelKind, other: DrawingLevelKind): boolean { - if (active === "drawing") return true; - if (active === "floor") return other === "drawing"; - return false; -} diff --git a/src/views/viewportContent.tsx b/src/views/viewportContent.tsx index 5da1acbb..6cdf68a4 100644 --- a/src/views/viewportContent.tsx +++ b/src/views/viewportContent.tsx @@ -1120,7 +1120,7 @@ function SectionPlanView({ const rawPlan = isElevation ? elevationPlan : sectionPlan; // Grundriss-Unterlage (Nutzer-Wunsch: "in der Ansicht auch mal einen // Grundriss zeigen können"): das in `level.planUnderlayId` gewählte Geschoss - // AUSGERICHTET unter dem Schnitt/der Ansicht (s. plan/planUnderlay.ts) — + // AUSGERICHTET unter dem Schnitt/der Ansicht (Kern `plan/underlay.rs`) — // nicht mehr jede sichtbare Ebene lose übereinander (die lag in einem // fremden Koordinatenraum und verdeckte den Schnitt). const underlayFloor = project.drawingLevels.find( @@ -1129,18 +1129,19 @@ function SectionPlanView({ const sectionMinY = rawPlan?.bounds.minY; const overlayPrimitives = useMemo(() => { if (!underlayFloor || sectionMinY === undefined) return []; - const floorPlan = generatePlan( + // Der Kern legt den Grundriss (aus seinen Plan-Caches) gedimmt und ohne Auswahl-Ids darunter. + return planUnderlayPrimitives( project, + level, underlayFloor.id, + sectionMinY, visibleCodes, categoryDisplay, detail, referenceLines, mono, - false, scaleDenominator, ); - return planUnderlayPrimitives(level, floorPlan.primitives, sectionMinY).map(stripSelectableIds); }, [underlayFloor, sectionMinY, project, level, visibleCodes, categoryDisplay, detail, referenceLines, mono, scaleDenominator]); // Eigene 2D-Elemente des Schnitts/der Ansicht (Bemassung, Höhenkoten, // Beschriftung, Ergänzungslinien …): liegen in `drawings2d` mit