Files
DOSSIER/src-tauri/core/src/plan/extras.rs
T
Claude fe124a7ce0 [207] Schwarzplan/Situationsplan 1:500: Modelldarstellung "Situation", Vorlagen "Situation WBW" und "Schwarzplan"
Neue Option ModelViewOption.situation (Kern plan/situation.rs): statt der Bauteile der gefuellte
Umriss des eigenen Gebaeudes (Waende/Decken/Koerper ab Erdgeschoss + Daecher mit Ueberstand,
Klasse 83), gefuellte Grundflaeche der Kontextnetze auf ihrer Klasse (grau, Schwarzplan schwarz),
Nordpfeil und Massstabsbalken (Klasse 84); Hoehenlinien enden an den Gebaeuden, Baurecht zeigt nur
die Parzellengrenze. Standard-Ressourcen (Vorlagen + Modelldarstellungen), Ressourcen-Tab-Abschnitt,
CLI plan --snapshot, Musterhaus komplex mit fuenf Nachbargebaeuden und Ausschnitt "Situation 1:500"
an der Vorlage; Goldens (Situation, Schwarzplan; Ansicht Sued/3D durch die Nachbarn).
2026-11-12 19:07:43 +00:00

1168 lines
55 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Grundriss-Zutaten rund um die Domänen ([K3a]/[K4]): Schattenstudie und Baurecht (zuunterst; die
//! Verstösse zuoberst), Abzugskörper (aus Wand-, Stützen- und Decken-Poché), Schwarz-Weiss und
//! Strichstärken nach Massstab sowie das Ausmass des Plans — früher in TS
//! (`generatePlan/{sunShadow,siteRules}.ts`, `voids.ts::subtractVoidsInPlan`, `toMono`,
//! `lineWeightScale.ts`, `computeBounds`). Rechenreihenfolge wie dort.
use super::domains::Bounds;
use super::prim::{HatchRender, Primitive};
use super::style::*;
use crate::jsnum;
use crate::model::*;
use std::collections::HashMap;
/// [137] Pick-Ids der abgeleiteten Lage-Darstellung (im Feld `contextObjectId`, mit `@` — keine Element-Id
/// beginnt so): Schattenflächen wählen den Sonnenstand, die Baurechtslinien (unsichtbare Bänder) das Baurecht.
pub const SITE_PICK_SUN: &str = "@sunStudy";
pub const SITE_PICK_RULES: &str = "@siteRules";
/// [137] Schlagschatten der Ansicht (Ebenen-Schalter `shadows`).
pub const SITE_PICK_VIEW_SHADOWS: &str = "@viewShadows";
/// Füllfarbe der Schattenflächen.
/// [140] Schatten grau (Tusche-Darstellung), nicht blau.
pub const SUN_SHADOW_FILL: &str = "#3c3c3c";
/// [140] Schatten heller (0.28 → 0.16): Bemassung und Stempel darüber bleiben lesbar.
const SUN_SHADOW_OPACITY: f64 = 0.16;
/// Linien-Klassen und Füllfarbe des Baurechts.
pub const SITE_PARCEL_CLS: &str = "site-parcel";
pub const SITE_ALLOWED_CLS: &str = "site-allowed";
pub const SITE_VIOLATION_FILL: &str = "#d0342c";
const SITE_VIOLATION_OPACITY: f64 = 0.45;
/// Profilverstösse ([63]): gleiches Rot, schwächer gefüllt (Bauteil ragt über das Gebäudeprofil).
const SITE_PROFILE_OPACITY: f64 = 0.25;
/// [140] Baurecht in Grautönen (Parzelle dunkel, zulässiger Baukörper mittel); Verstösse bleiben rot.
const PARCEL_COLOR: &str = "#3a3a3a";
const ALLOWED_COLOR: &str = "#6e6e6e";
const PARCEL_DASH: [f64; 4] = [6.0, 1.5, 0.5, 1.5];
const ALLOWED_DASH: [f64; 2] = super::line_pattern::HIDDEN;
/// Geschoss, auf dem Boden-Schatten und Baurecht erscheinen: Basishöhe am nächsten bei 0 (das erste
/// bei Gleichstand).
pub fn ground_floor_id(p: &Project) -> Option<&str> {
let mut best: Option<(&str, f64)> = None;
for l in &p.drawing_levels {
if l.kind != DrawingLevelKind::Floor {
continue;
}
let d = l.base_elevation.unwrap_or(0.0).abs();
if best.is_none_or(|b| d < b.1) {
best = Some((&l.id, d));
}
}
best.map(|b| b.0)
}
/// Fläche ohne Strich, mit Deckkraft (Schatten, Baurechts-Verstoss).
fn flat_polygon(pts: Vec<Vec2>, fill: &str, opacity: f64) -> Primitive {
Primitive::Polygon {
pts,
fill: fill.into(),
stroke: "none".into(),
stroke_width_mm: 0.0,
hatch: Box::new(no_hatch()),
greyed: None,
opacity: Some(opacity),
no_stroke_edges: None,
wall_id: None,
drawing_id: None,
ceiling_id: None,
opening_id: None,
stair_id: None,
room_id: None,
extruded_solid_id: None,
context_object_id: None,
column_id: None,
roof_id: None,
section_line_id: None,
}
}
fn ring_pts(r: &[[f64; 2]]) -> Vec<Vec2> {
r.iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect()
}
/// Breite/Länge des Projekts aus `geoAnchor` (LV95), sonst Zürich.
fn project_lat_lon(p: &Project) -> (f64, f64) {
match &p.geo_anchor {
Some(a) => crate::geo_rebase::lv95_to_wgs84(a.lv95.e, a.lv95.n),
None => (47.3769, 8.5417),
}
}
/// Schatten zum Zeitpunkt `when_ms` (Unix-ms der Studie, `None`/NaN = ungültig) als
/// halbtransparente Flächen; nur mit sichtbarer Studie, in Geschoss-Grundrissen. [142] Auf den im
/// Grundriss sichtbaren Flächen im Freien (Terrassen, Dächer tieferer Geschosse unter dem Schnitt),
/// auf dem Gelände nur im Geschoss nächst ±0.00.
pub fn sun_shadow(p: &Project, floor: &str, when_ms: Option<f64>, out: &mut Vec<Primitive>) {
let Some(study) = &p.sun_study else { return };
if !study.show || !p.drawing_levels.iter().any(|l| l.id == floor && l.kind == DrawingLevelKind::Floor) {
return;
}
let Some(t) = when_ms.filter(|t| !t.is_nan()) else { return };
let (lat, lon) = project_lat_lon(p);
let sun = crate::sun::sun_position(lat, lon, t);
let with_ground = ground_floor_id(p) == Some(floor);
// [171] Flächen unter der Unterkante des Ansichtsbereichs (samt „darunter sichtbar bis“) zeigt der
// Grundriss nicht — auch ihren Schatten nicht.
let range = super::view_range::ViewRange::of(p, floor);
let min_top = range.bottom.map_or(f64::NEG_INFINITY, |b| b - range.depth);
for poly in crate::sun::shadow_polygons_plan_in(p, sun, cut_z(p, floor), min_top, with_ground) {
for r in crate::sun::without_holes(&poly) {
let mut q = flat_polygon(ring_pts(&r), SUN_SHADOW_FILL, SUN_SHADOW_OPACITY);
if let Primitive::Polygon { context_object_id, .. } = &mut q {
*context_object_id = Some(SITE_PICK_SUN.into());
}
out.push(q);
}
}
}
/// Baurecht im Geschoss nächst ±0.00 (ohne `show: false`): Prüfung des Modells, `None` ohne
/// gültiges Baurecht.
fn site_check(p: &Project, floor: &str) -> Option<crate::site_rules::SiteCheckOut> {
let rules = p.site_rules.as_ref()?;
if rules.show == Some(false) || ground_floor_id(p) != Some(floor) {
return None;
}
crate::site_rules::check_project(p)
}
/// Linien eines geschlossenen Rings (ein Strichmuster je Ring: Linienzug über die Ecken).
fn ring_lines(out: &mut Vec<(Primitive, u32)>, pts: &[Vec2], cls: &str, color: &str, w: f64, dash: &[f64], dash_ref: u32) {
let n = pts.len();
for i in 0..n {
let line = Primitive::Line {
a: pts[i],
b: pts[(i + 1) % n],
cls: cls.into(),
weight_mm: w,
dash: Some(Some(dash.to_vec())),
zigzag: None,
motif: None,
color: Some(color.into()),
drawing_id: None,
opening_id: None,
stair_id: None,
greyed: None,
opacity: None,
};
out.push((line, dash_ref));
}
}
/// [137] Unsichtbares Rechteck der halben Breite `half` um die Strecke a–b mit der Pick-Id des Baurechts.
fn seg_band(a: Vec2, b: Vec2, half: f64) -> Option<Primitive> {
let (dx, dy) = (b.x - a.x, b.y - a.y);
let l = dx.hypot(dy);
if !(l > 1e-9) {
return None;
}
let (nx, ny) = (-dy / l * half, dx / l * half);
let pts = vec![Vec2 { x: a.x + nx, y: a.y + ny }, Vec2 { x: b.x + nx, y: b.y + ny }, Vec2 { x: b.x - nx, y: b.y - ny }, Vec2 { x: a.x - nx, y: a.y - ny }];
let mut q = flat_polygon(pts, "none", 1.0);
if let Primitive::Polygon { context_object_id, opacity, .. } = &mut q {
*context_object_id = Some(SITE_PICK_RULES.into());
*opacity = None;
}
Some(q)
}
/// Unterste Gruppe: Schatten, dann Parzellengrenze (Strich-Punkt) und zulässige Fläche
/// (gestrichelt); mit Strichmuster-Kennung je Primitiv. Dazu die Verstösse (Gebäude-Grundfläche
/// ausserhalb der zulässigen Fläche) für die oberste Gruppe.
/// Kategorie der Vermessung; ist sie im Projekt und ausgeblendet, entfällt das Baurecht im Grundriss ([66]).
pub const SITE_CATEGORY: &str = "01";
/// `site = false`: nur der Schatten, ohne Baurecht.
pub fn site_and_shadow(p: &Project, floor: &str, when_ms: Option<f64>, scale: f64, site: bool) -> (Vec<(Primitive, u32)>, Vec<Primitive>) {
let mut shadow = Vec::new();
sun_shadow(p, floor, when_ms, &mut shadow);
let mut under: Vec<(Primitive, u32)> = shadow.into_iter().map(|q| (q, 0)).collect();
let mut violations = Vec::new();
if !site {
return (under, violations);
}
if let (Some(check), Some(rules)) = (site_check(p, floor), p.site_rules.as_ref()) {
let mut r = 1;
ring_lines(&mut under, &rules.parcel, SITE_PARCEL_CLS, PARCEL_COLOR, 0.35, &PARCEL_DASH, r);
for poly in &check.allowed {
for ring in poly {
r += 1;
ring_lines(&mut under, ring, SITE_ALLOWED_CLS, ALLOWED_COLOR, 0.25, &ALLOWED_DASH, r);
}
}
// [137] Unsichtbare Pick-Bänder (±1.5 mm Papier) über den Linien: ein Klick wählt das Baurecht.
let half = 0.0015 * if scale.is_finite() && scale > 0.0 { scale } else { 100.0 };
let rings = std::iter::once(rules.parcel.as_slice()).chain(check.allowed.iter().flatten().map(|r| r.as_slice()));
for ring in rings {
for i in 0..ring.len() {
if let Some(band) = seg_band(ring[i], ring[(i + 1) % ring.len()], half) {
under.push((band, 0));
}
}
}
for poly in &check.violations {
let rings: Vec<Vec<[f64; 2]>> = poly.iter().map(|r| r.iter().map(|q| [q.x, q.y]).collect()).collect();
for ring in crate::sun::without_holes(&rings) {
violations.push(flat_polygon(ring_pts(&ring), SITE_VIOLATION_FILL, SITE_VIOLATION_OPACITY));
}
}
for poly in &check.profile_violations {
let rings: Vec<Vec<[f64; 2]>> = poly.iter().map(|r| r.iter().map(|q| [q.x, q.y]).collect()).collect();
for ring in crate::sun::without_holes(&rings) {
violations.push(flat_polygon(ring_pts(&ring), SITE_VIOLATION_FILL, SITE_PROFILE_OPACITY));
}
}
}
(under, violations)
}
/// [207] Situationsplan: nur die Parzellengrenze des Baurechts (ohne Baubereich, Verstösse und Schatten), auf der
/// Klasse „01"; Strichstärke wie im Baurecht.
pub fn parcel_only(p: &Project) -> Vec<(Primitive, u32)> {
let mut under = Vec::new();
if let Some(rules) = p.site_rules.as_ref().filter(|r| r.parcel.len() >= 3) {
ring_lines(&mut under, &rules.parcel, SITE_PARCEL_CLS, PARCEL_COLOR, 0.35, &PARCEL_DASH, 1);
}
under
}
// ── Abzugskörper ────────────────────────────────────────────────────────────────────────────────
const EPS: f64 = 1e-7;
/// Ein Abzugskörper als Prisma (Welt-Höhen).
pub(crate) struct VoidPrism {
pub(crate) pts: Vec<Vec2>,
pub(crate) z0: f64,
pub(crate) z1: f64,
}
/// Abzugskörper des Projekts (`voidPrisms`): `operation: "subtract"`, ohne B-Rep, ohne Verjüngung,
/// gültiges Profil und Höhe.
pub(crate) fn void_prisms(p: &Project) -> Vec<VoidPrism> {
let mut out = Vec::new();
for s in p.extruded_solids.as_deref().unwrap_or(&[]) {
let is_void = s.operation.as_deref() == Some("subtract") && s.brep.is_none() && s.taper.unwrap_or(0.0) < 1e-6 && s.points.len() >= 3 && s.height > 0.0;
if !is_void {
continue;
}
let z0 = p.floor(&s.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0)) + s.base_offset.unwrap_or(0.0);
out.push(VoidPrism { pts: s.points.clone(), z0, z1: z0 + s.height });
}
out
}
/// Ringe flach wie `encodeRings` in TS: `[n, (k, x, y …) × n]`.
fn encode_rings(rings: &[&[Vec2]]) -> Vec<f64> {
let mut b = vec![rings.len() as f64];
for r in rings {
b.push(r.len() as f64);
for q in r.iter() {
b.push(q.x);
b.push(q.y);
}
}
b
}
/// Schneider-Polygon (erster Ring aussen, weitere Löcher).
type CutPoly = Vec<Vec<[f64; 2]>>;
/// [G1] Abzugskörper beliebiger Form (kein senkrechtes Prisma, s. [`void_prisms`]): Kern-Netz
/// (`solid_mesh::body_mesh`) und Höhenbereich.
pub(crate) struct VoidMesh {
pub(crate) mesh: std::rc::Rc<Option<crate::solid_bool::Mesh>>,
pub(crate) z0: f64,
pub(crate) z1: f64,
}
pub(crate) fn void_meshes(p: &Project) -> Vec<VoidMesh> {
let mut out = Vec::new();
for s in p.extruded_solids.as_deref().unwrap_or(&[]) {
let prism = s.brep.is_none() && s.taper.unwrap_or(0.0) < 1e-6 && s.points.len() >= 3 && s.height > 0.0;
if s.operation.as_deref() != Some("subtract") || prism {
continue;
}
let Some(mesh) = crate::solid_mesh::body_mesh(p, s) else { continue };
let Some((lo, hi)) = mesh.as_ref().as_ref().and_then(|m| m.bounds()) else { continue };
out.push(VoidMesh { mesh: mesh.clone(), z0: lo[2], z1: hi[2] });
}
out
}
/// Ringliste flach (`encode_rings`), solange kein Schneider Löcher hat (sonst `None`: Polygon-Weg).
fn flat_rings(polys: &[CutPoly]) -> Option<Vec<f64>> {
if polys.iter().any(|p| p.len() != 1) {
return None;
}
let mut b = vec![polys.len() as f64];
for r in polys.iter().map(|p| &p[0]) {
b.push(r.len() as f64);
for q in r {
b.extend([q[0], q[1]]);
}
}
Some(b)
}
/// [G1] Waagrechter Ebenenschnitt eines Netzes auf Höhe `z` als Polygone mit Löchern.
pub(super) fn mesh_level_polys(mesh: &Option<crate::solid_bool::Mesh>, z: f64) -> Vec<CutPoly> {
let Some(m) = mesh else { return Vec::new() };
let idx: Vec<f64> = m.indices.iter().map(|&i| i as f64).collect();
let f = crate::mesh_section::cut(&m.positions, &idx, &[1.0, z]);
let Some(&n) = f.first() else { return Vec::new() };
let mut rings = Vec::new();
let mut i = 1;
for _ in 0..n as usize {
let k = f[i] as usize;
i += 1;
rings.push((0..k).map(|j| [f[i + 2 * j], f[i + 2 * j + 1]]).collect::<Vec<_>>());
i += 2 * k;
}
super::section::rings_to_polygons(&rings)
}
/// [G1] Grundriss eines Netzes im Höhenbereich `z0..z1`: der Körper wird auf das Band beschnitten
/// (Manifold), dann die nach oben weisenden Dreiecke projiziert und vereinigt (i_overlay).
pub(super) fn mesh_footprint(mesh: &Option<crate::solid_bool::Mesh>, z0: f64, z1: f64) -> Vec<CutPoly> {
use crate::solid_bool::{Mesh, Solid};
let Some(m) = mesh else { return Vec::new() };
let Some((lo, hi)) = m.bounds() else { return Vec::new() };
let clipped;
let m = if z0 <= lo[2] + EPS && z1 >= hi[2] - EPS {
m
} else {
let (a, b) = (z0.max(lo[2] - 1.0), z1.min(hi[2] + 1.0));
if !(b > a + EPS) {
return Vec::new();
}
let r = [[lo[0] - 1.0, lo[1] - 1.0], [hi[0] + 1.0, lo[1] - 1.0], [hi[0] + 1.0, hi[1] + 1.0], [lo[0] - 1.0, hi[1] + 1.0]];
let Some(c) = Solid::new(m).ok().and_then(|s| Solid::new(&Mesh::prism(&r, a, b)).ok().and_then(|band| s.intersection(&band).ok())) else { return Vec::new() };
clipped = c.to_mesh();
&clipped
};
let p = |i: u32| {
let j = 3 * i as usize;
[m.positions[j], m.positions[j + 1]]
};
let mut tris: Vec<CutPoly> = Vec::new();
for t in m.indices.chunks_exact(3) {
let (a, b, c) = (p(t[0]), p(t[1]), p(t[2]));
let cross = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
if cross > 1e-12 {
tris.push(vec![vec![a, b, c]]);
}
}
crate::polygon_bool::union(&tris)
}
/// [G1] Echter Umriss eines Abzugskörpers im Grundriss (Ringe, Löcher eingeschlossen): Ebenenschnitt des Kern-Netzes
/// auf Schnitthöhe `cut`, liegt `cut` ausserhalb des Körpers dessen Grundriss. Ohne Netz leer (Rückfall: Profil).
pub(super) fn void_outline(p: &Project, s: &ExtrudedSolid, cut: f64) -> Vec<Vec<Vec2>> {
let Some(mesh) = crate::solid_mesh::body_mesh(p, s) else { return Vec::new() };
let Some((lo, hi)) = mesh.as_ref().as_ref().and_then(|m| m.bounds()) else { return Vec::new() };
let polys = if cut > lo[2] + EPS && cut < hi[2] - EPS { mesh_level_polys(&mesh, cut) } else { mesh_footprint(&mesh, lo[2], hi[2]) };
let mut out: Vec<Vec<Vec2>> = Vec::new();
for r in polys.into_iter().flatten() {
let ring = simplify_ring(&r);
let key = |q: &Vec2| (q.x * 1e6).round() as i64 * 1_000_003 + (q.y * 1e6).round() as i64;
let same = |o: &Vec<Vec2>| o.len() == ring.len() && o.iter().map(key).sum::<i64>() == ring.iter().map(key).sum::<i64>();
if ring.len() >= 3 && !out.iter().any(same) {
out.push(ring);
}
}
out
}
/// Ring ohne doppelte Endpunkte und ohne Punkte auf der Geraden (Teilungspunkte des Netzes).
fn simplify_ring(r: &[[f64; 2]]) -> Vec<Vec2> {
let mut pts: Vec<[f64; 2]> = Vec::new();
for q in r {
if pts.last().map_or(true, |l| (l[0] - q[0]).hypot(l[1] - q[1]) > 1e-9) {
pts.push(*q);
}
}
while pts.len() > 1 && (pts[0][0] - pts[pts.len() - 1][0]).hypot(pts[0][1] - pts[pts.len() - 1][1]) <= 1e-9 {
pts.pop();
}
let n = pts.len();
let keep: Vec<[f64; 2]> = (0..n)
.filter(|&i| {
let (a, b, c) = (pts[(i + n - 1) % n], pts[i], pts[(i + 1) % n]);
((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])).abs() > 1e-9
})
.map(|i| pts[i])
.collect();
keep.into_iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect()
}
/// [G1] Durchbruch: der Abzugskörper durchstösst eine Decke (die dieses Geschosses unten oder seine Oberkante).
pub(super) fn void_pierces_slab(p: &Project, s: &ExtrudedSolid) -> bool {
let Some(f) = p.floor(&s.level_id) else { return false };
let base = f.base_elevation.unwrap_or(0.0);
let z0 = base + s.base_offset.unwrap_or(0.0);
let z1 = z0 + s.height;
let top = base + f.floor_height.unwrap_or(0.0);
(z0 < base - EPS && z1 > base + EPS) || (f.floor_height.is_some() && z0 < top - EPS && z1 > top + EPS)
}
/// Linien-Klassen der Wand-Poché, die ein Abzugskörper auf Schnitthöhe unterbricht.
const WALL_LINE_CLS: [&str; 3] = ["wall-outline", "layer-joint", "layer-joint-l"];
/// Zieht die Abzugskörper von den Bauteil-Primitiven eines Grundrisses ab (`subtractVoidsInPlan`):
/// Wände (Poché und ihre Linien), wenn der Körper die Schnitthöhe `cut_z` durchdringt; Stützen
/// ebenso über ihren Höhenbereich; Decken, wenn der Körper die Platte durchdringt. Ohne
/// Abzugskörper unverändert. Gleiche Rechnung wie der frühere Weg über die flachen Bindungen.
pub fn subtract_voids(prims: Vec<Primitive>, p: &Project, cut_z: f64) -> Vec<Primitive> {
let voids = void_prisms(p);
let shaped = void_meshes(p);
if voids.is_empty() && shaped.is_empty() {
return prims;
}
// Maps wie in TS: bei doppelter id gewinnt der letzte Eintrag.
let ceilings: HashMap<&str, &Ceiling> = p.ceilings.as_deref().unwrap_or(&[]).iter().map(|c| (c.id.as_str(), c)).collect();
let columns: HashMap<&str, &Column> = p.columns.as_deref().unwrap_or(&[]).iter().map(|c| (c.id.as_str(), c)).collect();
let ring_of = |pts: &[Vec2]| -> Vec<[f64; 2]> { pts.iter().map(|q| [q.x, q.y]).collect() };
// [G1] Abzugskörper beliebiger Form: Grundriss des Körpers im Höhenbereich des Bauteils.
let cutters_for = |z0: f64, z1: f64| -> Vec<CutPoly> {
let mut c: Vec<CutPoly> = voids.iter().filter(|v| v.z0 < z1 - EPS && v.z1 > z0 + EPS).map(|v| vec![ring_of(&v.pts)]).collect();
for v in shaped.iter().filter(|v| v.z0 < z1 - EPS && v.z1 > z0 + EPS) {
c.extend(mesh_footprint(&v.mesh, z0, z1));
}
c
};
// Wände: Prismen wie bisher über ihr Profil, Körper beliebiger Form über ihren Ebenenschnitt auf Schnitthöhe.
let mut wall_cutters: Vec<CutPoly> = voids.iter().filter(|v| v.z0 < cut_z + 1e-4 - EPS && v.z1 > cut_z - 1e-4 + EPS).map(|v| vec![ring_of(&v.pts)]).collect();
for v in shaped.iter().filter(|v| v.z0 < cut_z && v.z1 > cut_z) {
wall_cutters.extend(mesh_level_polys(&v.mesh, cut_z));
}
let wall_flat = flat_rings(&wall_cutters);
// [159] Nichts zu tun (z. B. Kontext mit zehntausenden Höhenlinien): die Liste unverändert, ohne Umkopieren.
let nonempty = |s: &Option<String>| s.as_deref().is_some_and(|s| !s.is_empty());
let touched = |q: &Primitive| match q {
Primitive::Line { cls, .. } => WALL_LINE_CLS.contains(&cls.as_str()) && !wall_cutters.is_empty(),
Primitive::Polygon { wall_id, ceiling_id, column_id, extruded_solid_id, .. } => !nonempty(extruded_solid_id) && (nonempty(wall_id) || nonempty(ceiling_id) || nonempty(column_id)),
_ => false,
};
if !prims.iter().any(touched) {
return prims;
}
let mut out = Vec::with_capacity(prims.len());
for pr in prims {
if let Primitive::Line { a, b, cls, .. } = &pr {
if WALL_LINE_CLS.contains(&cls.as_str()) && !wall_cutters.is_empty() {
let parts: Vec<(f64, f64)> = match &wall_flat {
Some(flat) => {
let f = crate::voids::segment_outside_flat(&[a.x, a.y, b.x, b.y], flat);
let n = f.first().copied().unwrap_or(0.0) as usize;
(0..n).map(|k| (f[1 + 2 * k], f[2 + 2 * k])).collect()
}
None if [a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite()) => crate::voids::segment_outside_polys([a.x, a.y], [b.x, b.y], &wall_cutters),
None => Vec::new(),
};
if parts.len() == 1 && parts[0].0 == 0.0 && parts[0].1 == 1.0 {
out.push(pr);
} else {
let (a, b) = (*a, *b);
let at = |t: f64| Vec2 { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
for (t0, t1) in parts {
let mut q = pr.clone();
if let Primitive::Line { a: qa, b: qb, .. } = &mut q {
*qa = at(t0);
*qb = at(t1);
}
out.push(q);
}
}
continue;
}
}
let Primitive::Polygon { pts, no_stroke_edges, wall_id, ceiling_id, column_id, extruded_solid_id, .. } = &pr else {
out.push(pr);
continue;
};
// Ids zählen wie in JS nur, wenn nicht leer.
let id = |s: &Option<String>| s.as_deref().filter(|s| !s.is_empty()).map(str::to_owned);
let (wall_id, ceiling_id, column_id) = (id(wall_id), id(ceiling_id), id(column_id));
if id(extruded_solid_id).is_some() {
out.push(pr);
continue;
}
let cutters: Option<Vec<CutPoly>> = if wall_id.is_some() {
Some(wall_cutters.clone())
} else if let Some(id) = &ceiling_id {
ceilings.get(id.as_str()).map(|c| {
let (zb, zt) = p.ceiling_vertical_extent(c);
cutters_for(zb, zt)
})
} else if let Some(id) = &column_id {
columns.get(id.as_str()).map(|c| {
let (zb, zt) = p.column_vertical_extent(c);
if zb <= cut_z && zt >= cut_z {
wall_cutters.clone()
} else {
cutters_for(zb, zt)
}
})
} else {
None
};
let Some(cutters) = cutters.filter(|c| !c.is_empty()) else {
out.push(pr);
continue;
};
if pts.len() < 3 {
out.push(pr);
continue;
}
// [159] Weit neben allen Abzugskörpern (Rechtecke getrennt): unverändert wie mit leerer Schnittmenge
// (`subtract_rings` → `None`), ohne die Booleans je Polygon.
let pb = bbox_of(pts.iter().map(|q| [q.x, q.y]));
if cutters.iter().all(|c| apart(pb, bbox_of(c[0].iter().copied()))) {
out.push(pr);
continue;
}
let ns = no_stroke_edges.as_deref().unwrap_or(&[]);
let Some(cutters_flat) = flat_rings(&cutters) else {
// [G1] Schneider mit Löchern (Ring-Körper): direkt über die Polygone.
let ns: Vec<usize> = ns.iter().filter(|v| v.is_finite() && **v >= 0.0).map(|v| *v as usize).collect();
match crate::voids::subtract_polys(&ring_of(pts), &cutters, &ns) {
None => out.push(pr),
Some(pieces) => {
for pc in pieces {
let mut q = pr.clone();
if let Primitive::Polygon { pts, no_stroke_edges, .. } = &mut q {
*pts = pc.pts.iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect();
*no_stroke_edges = (!pc.no_stroke.is_empty()).then(|| pc.no_stroke.iter().map(|&i| i as f64).collect());
}
out.push(q);
}
}
}
continue;
};
let ring = encode_rings(&[pts]);
let mut nsf = vec![ns.len() as f64];
nsf.extend_from_slice(ns);
let f = crate::voids::subtract_rings_flat(&ring[1..], &cutters_flat, &nsf);
if f.is_empty() || f[0] < 0.0 {
out.push(pr);
continue;
}
let mut i = 1;
for _ in 0..f[0] as usize {
let n = f[i] as usize;
i += 1;
let rp: Vec<Vec2> = (0..n).map(|j| Vec2 { x: f[i + 2 * j], y: f[i + 2 * j + 1] }).collect();
i += 2 * n;
let m = f[i] as usize;
i += 1;
let rn: Vec<f64> = f[i..i + m].to_vec();
i += m;
let mut q = pr.clone();
if let Primitive::Polygon { pts, no_stroke_edges, .. } = &mut q {
*pts = rp;
*no_stroke_edges = (!rn.is_empty()).then_some(rn);
}
out.push(q);
}
}
out
}
/// [159] Rechteck `[x0, y0, x1, y1]` um die Punkte (NaN bleibt NaN, s. [`apart`]).
fn bbox_of(pts: impl Iterator<Item = [f64; 2]>) -> [f64; 4] {
let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
for q in pts {
if !(q[0].is_finite() && q[1].is_finite()) {
return [f64::NAN; 4];
}
b = [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[0]), b[3].max(q[1])];
}
b
}
/// [159] Zwei Rechtecke mit sicherem Abstand (1 mm, über dem Raster der Booleans) getrennt; NaN → nein.
fn apart(a: [f64; 4], b: [f64; 4]) -> bool {
const GAP: f64 = 1e-3;
a[2] + GAP < b[0] || b[2] + GAP < a[0] || a[3] + GAP < b[1] || b[3] + GAP < a[1]
}
/// Schnitthöhe des Geschosses (Welt): Basis + Schnitthöhe (Standard 1 m).
pub fn cut_z(p: &Project, floor: &str) -> f64 {
// Deckenspiegel ([100]): Schnitthöhe des Bezugsgeschosses.
let l = super::ceiling_plan::source_floor(p, floor).or_else(|| p.floor(floor));
l.and_then(|l| l.base_elevation).unwrap_or(0.0) + l.and_then(|l| l.cut_height).unwrap_or(1.0)
}
// ── Schwarz-Weiss und Strichstärken ─────────────────────────────────────────────────────────────
const REFERENCE_SCALE: f64 = 100.0;
const MIN_FACTOR: f64 = 0.4;
const MAX_FACTOR: f64 = 2.0;
/// [140] Sockel (Papier-mm), der nicht mit dem Massstab wächst/schrumpft: feine Linien (Schraffur,
/// Bemassung) ändern sich kaum, Haarlinien darunter gar nicht.
const FINE_MM: f64 = 0.09;
/// Strichstärken-Faktor für 1:`scale` ([32], nur mit `Project.scaleLineWeights`): (100/n)^0.5 (1:50 ≈ 1.41,
/// 1:200 ≈ 0.71, 1:500 ≈ 0.45), begrenzt auf 0,4–2; sonst 1. Wirkt über [`scale_weight`] je nach Stärke.
pub fn line_weight_factor(p: &Project, scale: f64) -> f64 {
if p.scale_line_weights != Some(true) || !(scale > 0.0) || !scale.is_finite() {
return 1.0;
}
let f = jsnum::pow(REFERENCE_SCALE / scale, 0.5);
jsnum::min(MAX_FACTOR, jsnum::max(MIN_FACTOR, f))
}
/// [140] Stärke `w` (Papier-mm, bezogen auf 1:100) beim Massstabsfaktor `f`: nur der Anteil über dem
/// Sockel [`FINE_MM`] skaliert (w' = 0.09 + (w − 0.09)·f). Schwere Linien folgen dem Massstab fast ganz
/// (Schnittkante 0.5 → 0.67 bei 1:50, → 0.38 bei 1:200), feine kaum (0.13 → 0.15 / 0.12) — die Rangfolge
/// bleibt in jedem Massstab erhalten (linear, steigend), und Schraffuren fallen in 1:200/1:500 nicht unter
/// die Druckgrenze. Linien bis 0.09 (Haarlinien) bleiben unverändert.
pub fn scale_weight(w: f64, f: f64) -> f64 {
if f == 1.0 || !(w > FINE_MM) || !f.is_finite() {
return w;
}
FINE_MM + (w - FINE_MM) * f
}
/// Nachbearbeitung beim Schreiben (`plan::buf::Writer::post`): Schwarz-Weiss (alle Farben auf Tinte
/// bzw. Papier; eine Vollpoché bleibt schwarz) und Strichstärken-Faktor — in dieser Reihenfolge wie
/// früher `toMono` und `scalePrimitiveWeights`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Post {
pub mono: bool,
pub lw: f64,
/// Skizzenstil ([67], `plan/sketch.rs`): Meter Modell je Papier-mm; 0 = aus.
pub sketch: f64,
}
impl Post {
/// Wirkt sie auf etwas?
pub fn active(&self) -> bool {
self.mono || self.lw != 1.0 || self.sketch > 0.0
}
fn hatch(&self, h: &mut HatchRender) {
if self.mono && h.pattern != HatchPattern::None {
if h.pattern == HatchPattern::Solid {
h.color = HATCH_INK.into();
} else if !is_neutral(&h.color) {
h.color = MONO_INK.into();
}
}
if self.lw != 1.0 {
h.line_weight = scale_weight(h.line_weight, self.lw);
}
}
/// Ein Primitiv (ohne Linien, die nimmt [`Post::line`]).
pub fn apply(&self, p: &mut Primitive) {
match p {
Primitive::Polygon { fill, stroke, stroke_width_mm, hatch, .. } => {
if self.mono {
let solid = hatch.pattern == HatchPattern::Solid;
if *fill != "none" {
if solid {
*fill = HATCH_INK.into();
} else if !is_neutral(fill) {
*fill = "#ffffff".into();
}
}
// [140] „none" bleibt (Wandschichten ohne Umriss: sonst Kontur statt Schraffur).
if *stroke != "none" && !is_neutral(stroke) {
*stroke = MONO_INK.into();
}
}
self.hatch(hatch);
if self.lw != 1.0 {
*stroke_width_mm = scale_weight(*stroke_width_mm, self.lw);
}
}
Primitive::Text { color, doc, .. } => {
if self.mono {
*color = MONO_INK.into();
// [140] Raumstempel in Tusche: farbige Auszeichnungen im Stempel-Text werden Tinte.
for r in doc.paragraphs.iter_mut().flat_map(|q| q.runs.iter_mut()) {
if r.marks.color.as_deref().is_some_and(|c| !is_neutral(c)) {
r.marks.color = Some(MONO_INK.into());
}
}
}
}
Primitive::Line { weight_mm, color, .. } => {
if self.mono && !color.as_deref().is_some_and(is_neutral) {
*color = Some(MONO_INK.into());
}
if self.lw != 1.0 {
*weight_mm = scale_weight(*weight_mm, self.lw);
}
}
Primitive::Arc { weight_mm, .. } | Primitive::DrawingCircle { weight_mm, .. } | Primitive::DrawingArc { weight_mm, .. } => {
if self.lw != 1.0 {
*weight_mm = scale_weight(*weight_mm, self.lw);
}
}
Primitive::DrawingText { .. } | Primitive::DrawingTextPath { .. } | Primitive::DrawingImage { .. } => {}
}
}
/// Farbe und Stärke einer Linie.
pub fn line<'a>(&self, color: Option<&'a str>, w: f64) -> (Option<&'a str>, f64) {
(if self.mono && !color.is_some_and(is_neutral) { Some(MONO_INK) } else { color }, scale_weight(w, self.lw))
}
}
/// [140] Unbunte Farbe (Grau/Schwarz/Weiss, `#rgb`/`#rrggbb`/`#rrggbbaa`): bleibt in Schwarz-Weiss erhalten
/// (Schatten, Gelände-Grau, Treppen-Grau); bunte Farben werden Tinte bzw. Papier.
pub fn is_neutral(c: &str) -> bool {
let h = c.trim().trim_start_matches('#');
let ch = |i: usize, n: usize| u8::from_str_radix(h.get(i..i + n)?, 16).ok().map(|v| if n == 1 { v * 17 } else { v });
let rgb = match h.len() {
3 | 4 => (ch(0, 1), ch(1, 1), ch(2, 1)),
6 | 8 => (ch(0, 2), ch(2, 2), ch(4, 2)),
_ => return false,
};
let (Some(r), Some(g), Some(b)) = rgb else { return false };
r.max(g).max(b) - r.min(g).min(b) <= 20
}
/// [32] Strichstärken nach Massstab auf Schnitt-/Ansichts-Primitive (wie im Grundriss über [`post_for`]):
/// Faktor [`line_weight_factor`] auf Linien, Umrisse und Schraffurlinien; ohne Projekt-Option nichts.
pub fn scale_line_weights(p: &Project, scale: f64, prims: &mut [Primitive]) {
let lw = line_weight_factor(p, scale);
if lw == 1.0 {
return;
}
let post = Post { mono: false, lw, sketch: 0.0 };
for q in prims.iter_mut() {
match q {
Primitive::Line { weight_mm, .. } => *weight_mm = scale_weight(*weight_mm, lw),
_ => post.apply(q),
}
}
}
/// Nachbearbeitung eines Plans: Schwarz-Weiss und Strichstärken-Faktor; `None`, wenn sie nichts tut.
/// Auf einer Blatt-Ebene (`layoutId`) gelten die Strichstärken unverändert (Papier 1:1).
pub fn post_for(p: &Project, a: &super::domains::PlanArgs) -> Option<Post> {
let level = p.floor(&a.floor);
let sheet = level.is_some_and(|l| l.layout_id.is_some());
let sketch = if sheet { 0.0 } else { sketch_k(level.and_then(|l| l.sketch), a.scale) };
Some(Post { mono: a.mono, lw: if sheet { 1.0 } else { line_weight_factor(p, a.scale) }, sketch }).filter(Post::active)
}
/// [67] Skizzenstil einer Ebene beim Massstab 1:`scale`: Meter je Papier-mm, 0 = aus.
pub fn sketch_k(on: Option<bool>, scale: f64) -> f64 {
if on == Some(true) && scale > 0.0 && scale.is_finite() {
scale / 1000.0
} else {
0.0
}
}
/// [67] Nachbearbeitung nur mit Skizzenstil (Schnitt/Ansicht; `None` = aus).
pub fn sketch_post(on: Option<bool>, scale: f64) -> Option<Post> {
Some(Post { mono: false, lw: 1.0, sketch: sketch_k(on, scale) }).filter(Post::active)
}
// ── Ausmass ─────────────────────────────────────────────────────────────────────────────────────
/// Ausmass der Zutaten, die „Einpassen" und Druck ganz zeigen sollen: Schatten und Baurechts-Linien
/// (`extra`) und die ganze Kontext-Schicht (Konturen, Netze, Luftbilder) — Rohwerte für
/// [`plan_bounds`].
/// Kontext-Objekte zählen nur, wenn ihre Kategorie gezeigt wird (`shown`, wie `plan_context`; ohne Kategorie
/// immer) — sonst bestimmt ein ausgeblendetes Gelände Zoom und Viewport-Grösse ([66]).
pub fn extra_bounds(p: &Project, extra: &[(Primitive, u32)], shown: impl Fn(&str) -> bool) -> Bounds {
let mut b = Bounds::new();
for (e, _) in extra {
match e {
Primitive::Polygon { pts, .. } => {
for q in pts {
b.acc(q.x, q.y);
}
}
Primitive::Line { a, b: e, .. } => {
b.acc(a.x, a.y);
b.acc(e.x, e.y);
}
_ => {}
}
}
for obj in p.context.as_deref().unwrap_or(&[]) {
if !shown(obj.category_code()) {
continue;
}
match obj {
ContextObject::ContourSet(cs) => {
for c in &cs.contours {
for q in &c.pts {
b.acc(q.x, q.y);
}
}
}
ContextObject::Image(im) => {
b.acc(im.min.x, im.min.y);
b.acc(im.max.x, im.max.y);
}
ContextObject::ImportedMesh(m) => mesh_bounds(&m.positions, &mut b),
ContextObject::TerrainMesh(m) => mesh_bounds(&m.positions, &mut b),
ContextObject::Excavation(e) => {
for q in e.ring().iter() {
b.acc(q.x, q.y);
}
}
}
}
b
}
fn mesh_bounds(pos: &[f64], b: &mut Bounds) {
let mut i = 0;
while i + 1 < pos.len() {
b.acc(pos[i], pos[i + 1]);
i += 3;
}
}
/// Ausmass des Plans (`computeBounds`): Ausmass der Domänen (falls vorhanden, als zwei Ecken), dann
/// die Zutaten; ohne Punkte `[0, 0, 1, 1]`.
pub fn plan_bounds(domains: &Bounds, extra: &Bounds) -> [f64; 4] {
let mut b = Bounds::new();
if let Some(d) = domains.get() {
b.acc(d[0], d[1]);
b.acc(d[2], d[3]);
}
b.merge(extra.raw());
b.get().unwrap_or([0.0, 0.0, 1.0, 1.0])
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> Project {
serde_json::from_str(include_str!("../../tests/fixtures/sample_project.json")).unwrap()
}
/// [66] Ausgeblendete Kontext-Kategorien (Höhenlinien) bestimmen das Ausmass nicht mit.
#[test]
fn ausmass_ohne_ausgeblendeten_kontext() {
let mut p = sample();
p.context = Some(vec![serde_json::from_value(serde_json::json!({
"type": "contourSet", "id": "hl", "name": "HL", "categoryCode": "14",
"contours": [{"z": 0.0, "pts": [{"x": -100.0, "y": -100.0}, {"x": 100.0, "y": 100.0}]}]
}))
.unwrap()]);
let on = extra_bounds(&p, &[], |_| true).get().unwrap();
assert_eq!(on, [-100.0, -100.0, 100.0, 100.0]);
assert!(extra_bounds(&p, &[], |k| k != "14").get().is_none());
}
/// [63] Profilverstösse erscheinen im Grundriss (schwächeres Rot); ohne Profil nichts.
#[test]
fn profilverstoesse_im_grundriss() {
let mut p = sample();
let floor = ground_floor_id(&p).unwrap().to_string();
let rules = |extra: serde_json::Value| {
let mut v = serde_json::json!({"parcel": [{"x": -1, "y": -1}, {"x": 6, "y": -1}, {"x": 6, "y": 5}, {"x": -1, "y": 5}], "defaultSetback": 0.0});
v.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
serde_json::from_value(v).unwrap()
};
p.site_rules = Some(rules(serde_json::json!({})));
let n0 = site_and_shadow(&p, &floor, None, 100.0, true).1.len();
p.site_rules = Some(rules(serde_json::json!({"profileAngle": 10.0, "profileHeight": 0.01})));
let c = crate::site_rules::check_project(&p).unwrap();
assert!(c.profile_exceeded);
let n1 = site_and_shadow(&p, &floor, None, 100.0, true).1.len();
assert!(n1 > n0, "{n0} {n1}");
// [66] Ohne Vermessung (Kategorie aus) kein Baurecht.
let (under, viol) = site_and_shadow(&p, &floor, None, 100.0, false);
assert!(under.is_empty() && viol.is_empty());
}
/// Oberste Fläche mit Pick-Id unter dem Punkt (wie `PickIndex::polygons_at`, Maske „Kontext").
fn top_pick(prims: &[(Primitive, u32)], x: f64, y: f64) -> Option<String> {
prims.iter().rev().find_map(|(q, _)| match q {
Primitive::Polygon { pts, context_object_id: Some(id), .. } => {
let flat: Vec<f64> = pts.iter().flat_map(|v| [v.x, v.y]).collect();
crate::plan::pick::point_in_polygon(x, y, &flat).then(|| id.clone())
}
_ => None,
})
}
/// [137] Schattenflächen tragen die Pick-Id des Sonnenstands, die Baurechtslinien unsichtbare Bänder mit der
/// des Baurechts (Klick darauf öffnet deren Einstellungen); ohne sichtbare Studie bzw. in einem anderen
/// Geschoss nichts.
#[test]
fn klick_auf_schatten_und_baurecht() {
let mut p = sample();
let floor = ground_floor_id(&p).unwrap().to_string();
p.sun_study = Some(SunStudy { when: "2026-12-21T09:00:00Z".into(), show: true, ..Default::default() });
let when = Some(1_797_843_600_000.0); // 2026-12-21T09:00:00Z
let (under, _) = site_and_shadow(&p, &floor, when, 100.0, true);
let shadows: Vec<&Primitive> = under.iter().map(|(q, _)| q).filter(|q| matches!(q, Primitive::Polygon { fill, .. } if fill == SUN_SHADOW_FILL)).collect();
assert!(!shadows.is_empty());
assert!(shadows.iter().all(|q| matches!(q, Primitive::Polygon { context_object_id: Some(id), .. } if id == SITE_PICK_SUN)));
// Ein Punkt in der ersten Schattenfläche (Raster über ihr Ausmass).
let Primitive::Polygon { pts, .. } = shadows[0] else { panic!() };
let flat: Vec<f64> = pts.iter().flat_map(|v| [v.x, v.y]).collect();
let (x0, x1) = pts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |a, v| (a.0.min(v.x), a.1.max(v.x)));
let (y0, y1) = pts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |a, v| (a.0.min(v.y), a.1.max(v.y)));
let inside = (0..400).map(|k| (x0 + (x1 - x0) * ((k % 20) as f64 + 0.5) / 20.0, y0 + (y1 - y0) * ((k / 20) as f64 + 0.5) / 20.0)).find(|q| crate::plan::pick::point_in_polygon(q.0, q.1, &flat)).unwrap();
assert_eq!(top_pick(&under, inside.0, inside.1).as_deref(), Some(SITE_PICK_SUN));
assert_eq!(top_pick(&under, 1e4, 1e4), None);
assert!(site_and_shadow(&p, "anderes-geschoss", when, 100.0, true).0.is_empty());
p.sun_study.as_mut().unwrap().show = false;
assert_eq!(top_pick(&site_and_shadow(&p, &floor, when, 100.0, true).0, inside.0, inside.1), None);
// Baurecht: Parzellengrenze bei x = −30, Grenzabstand 3 m → zulässige Fläche ab x = −27; Band ±0.15 m bei 1:100.
p.site_rules = Some(serde_json::from_value(serde_json::json!({"parcel": [{"x": -30, "y": -30}, {"x": 40, "y": -30}, {"x": 40, "y": 40}, {"x": -30, "y": 40}], "defaultSetback": 3.0})).unwrap());
let (under, _) = site_and_shadow(&p, &floor, when, 100.0, true);
assert_eq!(top_pick(&under, -30.1, 5.0).as_deref(), Some(SITE_PICK_RULES));
assert_eq!(top_pick(&under, -27.0, 5.0).as_deref(), Some(SITE_PICK_RULES), "zulässige Fläche");
assert_eq!(top_pick(&under, -28.5, 5.0), None);
// Massstab 1:500: Band ±0.75 m.
assert_eq!(top_pick(&site_and_shadow(&p, &floor, when, 500.0, true).0, -29.4, 5.0).as_deref(), Some(SITE_PICK_RULES));
}
#[test]
fn strichstaerken_faktor() {
let mut on = sample();
on.scale_line_weights = Some(true);
assert_eq!(line_weight_factor(&on, 100.0), 1.0);
assert!((line_weight_factor(&on, 200.0) - 0.5f64.sqrt()).abs() < 1e-12);
assert!((line_weight_factor(&on, 50.0) - 2f64.sqrt()).abs() < 1e-12);
assert_eq!(line_weight_factor(&on, 100000.0), 0.4);
assert_eq!(line_weight_factor(&on, 1.0), 2.0);
assert_eq!(line_weight_factor(&sample(), 200.0), 1.0);
assert_eq!(line_weight_factor(&on, f64::NAN), 1.0);
}
/// [32] Schnitt/Ansicht: Faktor auch auf Linien; ohne Option unverändert.
#[test]
fn strichstaerken_in_schnitt_und_ansicht() {
let mut on = sample();
on.scale_line_weights = Some(true);
let lines = || vec![Primitive::Line { a: Vec2 { x: 0.0, y: 0.0 }, b: Vec2 { x: 1.0, y: 0.0 }, cls: "x".into(), weight_mm: 0.5, dash: None, zigzag: None, motif: None, color: None, drawing_id: None, opening_id: None, stair_id: None, greyed: None, opacity: None }];
let mut a = lines();
scale_line_weights(&on, 200.0, &mut a);
let Primitive::Line { weight_mm, .. } = &a[0] else { unreachable!() };
assert!((weight_mm - (0.09 + 0.41 * 0.5f64.sqrt())).abs() < 1e-12);
let mut b = lines();
scale_line_weights(&sample(), 200.0, &mut b);
let Primitive::Line { weight_mm, .. } = &b[0] else { unreachable!() };
assert_eq!(*weight_mm, 0.5);
}
/// [140] Rangfolge der Strichstärken je Massstab: Schnittkante 0.5 (1:100) → ≈ 0.67 (1:50) / ≈ 0.38
/// (1:200); feine Linien (Schraffur 0.1, Bemassung 0.13) ändern sich kaum, nie unter 0.09; die
/// Reihenfolge schwer > mittel > fein > Schraffur bleibt in jedem Massstab.
#[test]
fn strichstaerken_rangfolge_je_massstab() {
let mut on = sample();
on.scale_line_weights = Some(true);
let at = |w: f64, s: f64| scale_weight(w, line_weight_factor(&on, s));
assert!((at(0.5, 50.0) - 0.67).abs() < 0.01);
assert!((at(0.5, 200.0) - 0.38).abs() < 0.01);
assert_eq!(at(0.5, 100.0), 0.5);
// [140] Grösste Standard-Stärke 0.25 bei 1:100 (Wand-Schnittkante): 1:50 kräftiger, 1:200 feiner.
assert_eq!(at(0.25, 100.0), 0.25);
assert!(at(0.25, 50.0) > 0.3 && at(0.25, 200.0) < 0.21 && at(0.25, 200.0) > at(0.13, 200.0));
assert!((at(0.13, 50.0) - 0.13).abs() < 0.02 && (at(0.13, 200.0) - 0.13).abs() < 0.02);
for s in [20.0, 50.0, 100.0, 200.0, 500.0, 1000.0] {
let class = [0.7, 0.5, 0.35, 0.25, 0.18, 0.13, 0.1].map(|w| at(w, s));
assert!(class.windows(2).all(|p| p[0] > p[1]), "1:{s}: {class:?}");
assert!(at(0.1, s) >= 0.09 && at(0.13, s) >= 0.09, "1:{s}: feine Linien druckbar");
}
assert_eq!(scale_weight(0.02, 0.5), 0.02, "Haarlinien bleiben");
assert_eq!(scale_weight(f64::NAN, 2.0).is_nan(), true);
}
#[test]
fn blatt_ebene_ohne_strichstaerken_faktor() {
let mut p = sample();
p.scale_line_weights = Some(true);
let mut sheet = p.drawing_levels[0].clone();
sheet.id = "blatt".into();
sheet.kind = crate::model::DrawingLevelKind::Drawing;
sheet.layout_id = Some("L1".into());
p.drawing_levels.push(sheet);
let args = |floor: &str| super::super::domains::PlanArgs::parse(1.0, &serde_json::json!({"floor": floor, "scale": 1}).to_string()).unwrap();
assert_eq!(post_for(&p, &args("blatt")), None, "Papier 1:1: Stärken unverändert");
assert!(post_for(&p, &args("eg")).is_some_and(|q| q.lw > 1.0));
}
#[test]
fn abzugskoerper_spart_wand_aus() {
let mut v: serde_json::Value = serde_json::from_str(include_str!("../../tests/fixtures/sample_project.json")).unwrap();
let walls = |v: &serde_json::Value| {
let p: Project = serde_json::from_value(v.clone()).unwrap();
let codes: Vec<String> = p.flat_categories().iter().map(|c| c.code.clone()).collect();
let a = super::super::domains::PlanArgs::parse(1.0, &serde_json::json!({"floor": "eg", "show": codes}).to_string()).unwrap();
let (prims, _, _) = crate::plan::buf::decode(&super::super::domains::plan_domains_buf(&p, &a).unwrap()).unwrap();
prims.into_iter().filter(|q| matches!(q, Primitive::Polygon { wall_id: Some(_), .. })).collect::<Vec<_>>()
};
let before = walls(&v);
v["extrudedSolids"] = serde_json::json!([{"id": "void1", "type": "extrudedSolid", "levelId": "eg", "operation": "subtract", "height": 3,
"points": [{"x": 1.95, "y": -0.5}, {"x": 2.15, "y": -0.5}, {"x": 2.15, "y": 0.5}, {"x": 1.95, "y": 0.5}]}]);
let after = walls(&v);
assert_ne!(before, after);
assert!(after.len() > before.len(), "{} → {}", before.len(), after.len());
}
/// [G1] Abzugskörper beliebiger Form im Grundriss: Zylinder (B-Rep) spart Wand-Poché und Wandlinie über
/// seinen Ebenenschnitt auf Schnitthöhe aus; ein Ring-Körper (Loch) lässt den Kern der Wand stehen; eine
/// Kugel an der Decke spart deren Grundriss im Plattenband aus.
#[test]
fn abzugskoerper_beliebiger_form_im_grundriss() {
let v2 = |x: f64, y: f64| Vec2 { x, y };
let poly = |pts: Vec<Vec2>, wall: bool| {
let mut q = flat_polygon(pts, "#000", 1.0);
if let Primitive::Polygon { wall_id, ceiling_id, .. } = &mut q {
if wall {
*wall_id = Some("w".into());
} else {
*ceiling_id = Some("d".into());
}
}
q
};
let wall = poly(vec![v2(0.0, -0.1), v2(4.0, -0.1), v2(4.0, 0.1), v2(0.0, 0.1)], true);
let outline = super::super::domains::line(v2(0.0, 0.1), v2(4.0, 0.1), "wall-outline", 0.35, None, "#000", None);
let deck = poly(vec![v2(0.0, -2.0), v2(4.0, -2.0), v2(4.0, 2.0), v2(0.0, 2.0)], false);
let project = |spec: serde_json::Value| -> Project {
serde_json::from_value(serde_json::json!({
"drawingLevels": [{"id": "eg", "name": "EG", "kind": "floor", "baseElevation": 0, "floorHeight": 3, "cutHeight": 1, "visible": true}],
"ceilings": [{"id": "d", "type": "ceiling", "floorId": "eg", "categoryCode": "30", "outline": [{"x": 0, "y": -2}, {"x": 4, "y": -2}, {"x": 4, "y": 2}, {"x": 0, "y": 2}]}],
"extrudedSolids": [{"id": "v", "type": "extrudedSolid", "levelId": "eg", "categoryCode": "20", "operation": "subtract", "height": 2,
"points": [{"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 1, "y": 1}], "brep": {"origin": {"x": 0, "y": 0}, "spec": spec}}]
}))
.unwrap()
};
let area = |prims: &[Primitive], wall: bool| -> f64 {
prims.iter().filter_map(|q| match q {
Primitive::Polygon { pts, wall_id, .. } if wall_id.is_some() == wall => {
let n = pts.len();
Some(((0..n).map(|k| pts[k].x * pts[(k + 1) % n].y - pts[(k + 1) % n].x * pts[k].y).sum::<f64>() / 2.0).abs())
}
_ => None,
}).sum()
};
let line_len = |prims: &[Primitive]| -> (usize, f64) {
let l: Vec<f64> = prims.iter().filter_map(|q| match q { Primitive::Line { a, b, .. } => Some(b.x - a.x), _ => None }).collect();
(l.len(), l.iter().sum())
};
// Zylinder r = 0.3 um (2, 0): Kreis ∩ Wandstreifen (|y| ≤ 0.1) fehlt.
let p = project(serde_json::json!({"kind": "cylinder", "cx": 2, "cy": 0, "z0": 0, "r": 0.3, "height": 2}));
let out = subtract_voids(vec![wall.clone(), outline.clone()], &p, 1.0);
let n = 2000;
let lens: f64 = (0..n).map(|k| { let y = -0.1 + 0.2 * (k as f64 + 0.5) / n as f64; 2.0 * (0.09 - y * y).sqrt() * 0.2 / n as f64 }).sum();
assert!((area(&out, true) - (0.8 - lens)).abs() < 2e-3, "{} ≠ {}", area(&out, true), 0.8 - lens);
let (k, len) = line_len(&out);
assert_eq!(k, 2, "Wandlinie unterbrochen");
assert!((len - (4.0 - 2.0 * 0.08f64.sqrt())).abs() < 5e-3, "{len}");
// Ring-Körper 1.6 × 1.6 mit Loch 0.6 × 0.6: der Wandkern im Loch bleibt.
let p = project(serde_json::json!({"kind": "extrude", "points": [1.2, -0.8, 2.8, -0.8, 2.8, 0.8, 1.2, 0.8], "holes": [[1.7, -0.3, 2.3, -0.3, 2.3, 0.3, 1.7, 0.3]], "height": 2, "z0": 0}));
let out = subtract_voids(vec![wall.clone(), outline.clone()], &p, 1.0);
assert!((area(&out, true) - 0.2 * 3.0).abs() < 1e-6, "{}", area(&out, true));
assert_eq!(out.iter().filter(|q| matches!(q, Primitive::Polygon { .. })).count(), 3);
let (k, len) = line_len(&out);
assert_eq!(k, 3);
assert!((len - 3.0).abs() < 1e-6, "{len}");
// Kugel r = 0.5 um (2, 0, 3) an der Decke (Platte am Geschoss-Oberrand): Kreis aus der Decke; die
// Wand (Schnitthöhe 1) bleibt.
let p = project(serde_json::json!({"kind": "sphere", "center": [2, 0, 3], "r": 0.5}));
let out = subtract_voids(vec![wall, outline, deck], &p, 1.0);
let pi = std::f64::consts::PI;
assert!((area(&out, false) - (16.0 - pi * 0.25)).abs() < 0.01, "{}", area(&out, false));
assert!((area(&out, true) - 0.8).abs() < 1e-9);
}
#[test]
fn erdgeschoss_naechst_null() {
let p = sample();
assert_eq!(ground_floor_id(&p), Some("eg"));
}
#[test]
fn mono_poche_bleibt_schwarz() {
let post = Post { mono: true, lw: 1.0, sketch: 0.0 };
let mut solid = HatchRender { pattern: HatchPattern::Solid, ..no_hatch() };
solid.color = "#123456".into();
let mut p = flat_polygon(vec![], "#abcdef", 1.0);
if let Primitive::Polygon { hatch, stroke, .. } = &mut p {
*hatch = Box::new(solid);
*stroke = "#ff0000".into();
}
post.apply(&mut p);
match &p {
Primitive::Polygon { fill, stroke, hatch, .. } => {
assert_eq!(fill, HATCH_INK);
assert_eq!(stroke, MONO_INK);
assert_eq!(hatch.color, HATCH_INK);
}
_ => unreachable!(),
}
assert_eq!(post.line(None, 0.25), (Some(MONO_INK), 0.25));
}
/// [140] Raumstempel in Tusche: auch farbige Auszeichnungen im Stempel-Text (Run-Farbe) werden Tinte,
/// Grautöne bleiben; „Farbig" behält die Auszeichnung.
#[test]
fn mono_raumstempel_ohne_farbige_auszeichnung() {
let run = |text: &str, color: &str| TextRun { text: text.into(), marks: Marks { color: Some(color.into()), ..Default::default() }, ..Default::default() };
let doc = RichTextDoc { version: 1.0, paragraphs: vec![Paragraph { runs: vec![run("E.01 ", "#808080"), run("Zimmer", "#d0342c")], ..Default::default() }], ..Default::default() };
let stamp = || Primitive::Text { at: Vec2 { x: 0.0, y: 0.0 }, doc: doc.clone(), extra_lines: vec![], base_pt: 10.0, color: "#2255cc".into(), room_id: Some("r".into()), greyed: None, opacity: None };
let colors = |p: &Primitive| match p {
Primitive::Text { doc, color, .. } => (color.clone(), doc.paragraphs[0].runs.iter().map(|r| r.marks.color.clone()).collect::<Vec<_>>()),
_ => unreachable!(),
};
let mut p = stamp();
Post { mono: true, lw: 1.0, sketch: 0.0 }.apply(&mut p);
assert_eq!(colors(&p), (MONO_INK.to_string(), vec![Some("#808080".into()), Some(MONO_INK.into())]));
let mut p = stamp();
Post { mono: false, lw: 0.8, sketch: 0.0 }.apply(&mut p);
assert_eq!(colors(&p), ("#2255cc".to_string(), vec![Some("#808080".into()), Some("#d0342c".into())]));
}
/// [140] Schwarz-Weiss als Tusche-Standard: Wandschichten ohne Umriss bleiben ohne Umriss (sonst verdrängt
/// die Kontur die Schraffur), Grautöne (Schatten, Gelände, Treppe) bleiben, bunte Farben werden Tinte/Papier.
#[test]
fn mono_behaelt_grau_und_ohne_umriss() {
let post = Post { mono: true, lw: 1.0, sketch: 0.0 };
let mut p = flat_polygon(vec![], "#3c3c3c", 0.0);
if let Primitive::Polygon { stroke, hatch, .. } = &mut p {
*stroke = "none".into();
*hatch = Box::new(HatchRender { pattern: HatchPattern::Diagonal, color: "#808080".into(), ..no_hatch() });
}
post.apply(&mut p);
match &p {
Primitive::Polygon { fill, stroke, hatch, .. } => {
assert_eq!(fill, "#3c3c3c");
assert_eq!(stroke, "none");
assert_eq!(hatch.color, "#808080");
}
_ => unreachable!(),
}
let mut q = flat_polygon(vec![], "#e8dcc0", 0.0);
if let Primitive::Polygon { stroke, hatch, .. } = &mut q {
*stroke = "#b06030".into();
*hatch = Box::new(HatchRender { pattern: HatchPattern::Diagonal, color: "#c04020".into(), ..no_hatch() });
}
post.apply(&mut q);
match &q {
Primitive::Polygon { fill, stroke, hatch, .. } => {
assert_eq!(fill, "#ffffff");
assert_eq!(stroke, MONO_INK);
assert_eq!(hatch.color, MONO_INK);
}
_ => unreachable!(),
}
assert_eq!(post.line(Some("#8a8a8a"), 0.13), (Some("#8a8a8a"), 0.13));
assert_eq!(post.line(Some("#a05a2c"), 0.13), (Some(MONO_INK), 0.13));
assert!(is_neutral("#fff") && is_neutral("#1a1a1aff") && !is_neutral("#ff0000") && !is_neutral("rot"));
}
}