[K3d][K4] Grundriss-Domänen aus dem Kern-Dokument: Overrides, Decken, Dächer, Räume, Wände+Öffnungen, Treppen, Stützen, Extrusionen, Kontext, Schnittlinien
Neue Abfrage `planDomains` (src-tauri/core/src/plan/{domains,walls,stairs,context,overrides}.rs)
liefert die fertigen Primitive (JSON wie TS) samt Ausmass; generatePlan ruft sie einmal je
Geschoss und setzt die Primitive an ihre Stelle der Zeichenreihenfolge. Override-Regeln,
Stil-Auflösung (By-Layer/By-Object, Schraffur, Fugen-Linienstil), Verschneidung, Raumstempel-
Daten (roomStampToDoc/ExtraLines, js_number) laufen im Kern.
Gelöscht: generatePlan/{ceilings,roofs,rooms,structures,walls,openings,stairs,context,sections}.ts,
model/joins.ts (+ Test, fehlende Fälle in joins.rs), tote Bindungen und TS-Helfer.
Gleichheit: Primitive-JSON bitgleich zur alten TS-Fassung (Beispiel + 80 Zufallsprojekte,
972 Pläne inkl. Fehlerfälle), CLI-SVG byte-gleich. Nicht in der Tauri-App angesehen.
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
42 files changed
+1908
-2645
No files matched your search
@@ -1,7 +1,7 @@
|
||||
//! Wand-Verschneidung (Gehrung, T-Stoss, Kreuzung): berechnet je Wand die optionalen
|
||||
//! Schnittlinien an Start- und Endpunkt, materialbewusste Pro-Schicht-Cuts am T-Stoss und die
|
||||
//! Nah-Putz-Aussparungen der Durchgangswand. Portiert aus `src/model/joins.ts` (dort bleiben die
|
||||
//! Typen und das Sammeln aus dem `Project`).
|
||||
//! Nah-Putz-Aussparungen der Durchgangswand. Portiert aus `src/model/joins.ts`; gesammelt wird im
|
||||
//! Kern (`model3d.rs` für 3D, `plan/walls.rs` für den Grundriss).
|
||||
//!
|
||||
//! Behandelt: L-Ecken (zwei Wandenden im Knoten), T-Knoten (drei Enden, zwei kollinear),
|
||||
//! Mittelspannen-T-Stösse (freies Ende trifft auf die Seite einer anderen Wand) und
|
||||
@@ -773,6 +773,38 @@ mod tests {
|
||||
assert!(close(s.to - s.from, 0.15), "{s:?}");
|
||||
}
|
||||
|
||||
// Aus `model/joins.test.ts` übernommen ([K3d]: der TS-Sammler ist weg).
|
||||
#[test]
|
||||
fn stern_knoten_bleibt_rechtwinklig() {
|
||||
let w = vec![mono((0.0, 5.0), (5.0, 5.0), 0.3), mono((5.0, 5.0), (10.0, 5.0), 0.3), mono((5.0, 5.0), (5.0, 0.0), 0.3), mono((5.0, 5.0), (5.0, 10.0), 0.3)];
|
||||
for c in compute_joins(&w).unwrap() {
|
||||
assert!(c.start_cut.is_none() && c.end_cut.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rangfolge_zweier_bauteile() {
|
||||
use JoinResolution::*;
|
||||
assert_eq!(resolve_join_priority(50.0, 50.0, true), Merge);
|
||||
assert_eq!(resolve_join_priority(20.0, 20.0, false), Coexist);
|
||||
assert_eq!(resolve_join_priority(10.0, 50.0, false), TrimA);
|
||||
assert_eq!(resolve_join_priority(50.0, 10.0, false), TrimB);
|
||||
assert_eq!(resolve_join_priority(100.0, 50.0, false), TrimB);
|
||||
assert_eq!(resolve_join_priority(50.0, 100.0, false), TrimA);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn l_ecke_ohne_aussparung_und_abzweig_ohne_materialgleichheit() {
|
||||
let c = compute_joins(&[mono((0.0, 0.0), (5.0, 0.0), 0.4), mono((5.0, 0.0), (5.0, 4.0), 0.4)]).unwrap();
|
||||
assert!(c.iter().all(|k| k.span_cutouts.is_empty()));
|
||||
// Durchgang Putz|Backstein|Putz, Abzweig nur Putz (kein Bauteil des Rückgrats): kein layerCuts.
|
||||
let lay = || vec![layer(0.015, 0, 10.0), layer(0.12, 1, 50.0), layer(0.015, 0, 10.0)];
|
||||
let w = vec![wall((0.0, 0.0), (5.0, 0.0), lay()), wall((5.0, 0.0), (10.0, 0.0), lay()), wall((5.0, 0.0), (5.0, 3.0), vec![layer(0.1, 0, 10.0)])];
|
||||
let c = compute_joins(&w).unwrap();
|
||||
assert!(c[2].layer_cuts.is_none());
|
||||
assert!(c[2].start_cut.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hypot_wie_js() {
|
||||
assert_eq!(js_hypot(3.0, 4.0), 5.0);
|
||||
|
||||
@@ -49,10 +49,63 @@ pub fn to_fixed(x: f64, d: usize) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// `String(x)` für Zahlen (ECMAScript `Number::toString`): kürzeste Ziffernfolge, Exponent erst ab
|
||||
/// 1e21 bzw. unter 1e-6, `-0` → `"0"`.
|
||||
pub fn js_number(x: f64) -> String {
|
||||
if x.is_nan() {
|
||||
return "NaN".into();
|
||||
}
|
||||
if x == 0.0 {
|
||||
return "0".into();
|
||||
}
|
||||
if x.is_infinite() {
|
||||
return if x > 0.0 { "Infinity".into() } else { "-Infinity".into() };
|
||||
}
|
||||
let sign = if x < 0.0 { "-" } else { "" };
|
||||
// Rusts `{:e}` liefert die kürzeste Ziffernfolge, z. B. "1.2345e3".
|
||||
let e = format!("{:e}", x.abs());
|
||||
let (mant, exp) = e.split_once('e').expect("Exponent");
|
||||
let digits: String = mant.chars().filter(|c| *c != '.').collect();
|
||||
let k = digits.len() as i64;
|
||||
let n = exp.parse::<i64>().expect("Exponent") + 1;
|
||||
let body = if k <= n && n <= 21 {
|
||||
format!("{digits}{}", "0".repeat((n - k) as usize))
|
||||
} else if 0 < n && n <= 21 {
|
||||
format!("{}.{}", &digits[..n as usize], &digits[n as usize..])
|
||||
} else if -6 < n && n <= 0 {
|
||||
format!("0.{}{digits}", "0".repeat((-n) as usize))
|
||||
} else {
|
||||
let es = if n > 0 { format!("+{}", n - 1) } else { format!("{}", n - 1) };
|
||||
if k == 1 {
|
||||
format!("{digits}e{es}")
|
||||
} else {
|
||||
format!("{}.{}e{es}", &digits[..1], &digits[1..])
|
||||
}
|
||||
};
|
||||
format!("{sign}{body}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn zahl_als_text_wie_js() {
|
||||
assert_eq!(js_number(3.0), "3");
|
||||
assert_eq!(js_number(-0.0), "0");
|
||||
assert_eq!(js_number(0.1 + 0.2), "0.30000000000000004");
|
||||
assert_eq!(js_number(1e21), "1e+21");
|
||||
assert_eq!(js_number(1.5e21), "1.5e+21");
|
||||
assert_eq!(js_number(1e20), "100000000000000000000");
|
||||
assert_eq!(js_number(1e-7), "1e-7");
|
||||
assert_eq!(js_number(1.25e-7), "1.25e-7");
|
||||
assert_eq!(js_number(0.000001), "0.000001");
|
||||
assert_eq!(js_number(-12.5), "-12.5");
|
||||
assert_eq!(js_number(123456.789), "123456.789");
|
||||
assert_eq!(js_number(f64::NAN), "NaN");
|
||||
assert_eq!(js_number(f64::NEG_INFINITY), "-Infinity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rundet_halbwerte_auf_wie_js() {
|
||||
assert_eq!(to_fixed(0.0078125, 6), "0.007813"); // JS: "0.007813"; Rust {:.6}: 0.007812
|
||||
|
||||
@@ -373,7 +373,7 @@ fn kv(v: Vec2) -> KVec {
|
||||
KVec::new(v.x, v.y)
|
||||
}
|
||||
|
||||
fn wall_reference(w: &Wall) -> Reference {
|
||||
pub(crate) fn wall_reference(w: &Wall) -> Reference {
|
||||
match (w.reference_offset, w.reference_line) {
|
||||
(Some(v), _) => Reference::Offset(v),
|
||||
(None, Some(WallReferenceLine::Left)) => Reference::Left,
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
//! Projektglobale Referenzen im Grundriss auf dem Dokument ([K3d]): Kontext-Konturen (Höhenlinien,
|
||||
//! Fussabdruck importierter Gebäude, Rahmen von Gelände-Meshes, Pick-Bänder) und Schnittführungs-
|
||||
//! Symbole der Schnitt-/Ansichtsebenen — Rust-Gegenstück zu `generatePlan/{context,sections}.ts`.
|
||||
//! Die Geometrie liegt in `plan_misc.rs`; die Meshes werden direkt aus dem Dokument gelesen.
|
||||
|
||||
use super::domains::Ctx;
|
||||
use super::overrides::{js_space, js_trim};
|
||||
use super::prim::Primitive;
|
||||
use super::style::no_hatch;
|
||||
use crate::model::*;
|
||||
|
||||
const CONTEXT_LINE_COLOR: &str = "#9aa3ad";
|
||||
const CONTEXT_LINE_MM: f64 = 0.1;
|
||||
/// Kategorie der Schnittführungs-Symbole (Referenzen).
|
||||
const SECTION_LINE_CATEGORY: &str = "90";
|
||||
const SECTION_LINE_INK: &str = "#1f242c";
|
||||
const SECTION_LINE_MM: f64 = 0.18;
|
||||
const SECTION_LINE_MARK_MM: f64 = 0.5;
|
||||
const SECTION_LINE_DASH: [f64; 4] = [6.0, 1.5, 0.4, 1.5];
|
||||
const SECTION_LABEL_H: f64 = 0.5;
|
||||
|
||||
fn v2(x: f64, y: f64) -> Vec2 {
|
||||
Vec2 { x, y }
|
||||
}
|
||||
|
||||
fn context_line(a: Vec2, b: Vec2) -> Primitive {
|
||||
Primitive::Line { a, b, cls: "context-line".into(), weight_mm: CONTEXT_LINE_MM, dash: None, zigzag: None, motif: None, color: Some(CONTEXT_LINE_COLOR.into()), drawing_id: None, opening_id: None, stair_id: None, greyed: None, opacity: None }
|
||||
}
|
||||
|
||||
fn pick_band(pts: Vec<Vec2>, context_id: Option<&str>, section_id: Option<&str>) -> Primitive {
|
||||
Primitive::Polygon {
|
||||
pts,
|
||||
fill: "none".into(),
|
||||
stroke: "none".into(),
|
||||
stroke_width_mm: 0.0,
|
||||
hatch: no_hatch(),
|
||||
greyed: None,
|
||||
opacity: None,
|
||||
no_stroke_edges: None,
|
||||
wall_id: None,
|
||||
drawing_id: None,
|
||||
ceiling_id: None,
|
||||
opening_id: None,
|
||||
stair_id: None,
|
||||
room_id: None,
|
||||
extruded_solid_id: None,
|
||||
context_object_id: context_id.map(String::from),
|
||||
column_id: None,
|
||||
roof_id: None,
|
||||
section_line_id: section_id.map(String::from),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rahmen-Ecken eines Meshes (x/y), `None` ohne Punkte.
|
||||
fn bbox_corners(positions: &[f64]) -> Option<Vec<Vec2>> {
|
||||
let b = crate::plan_misc::bbox(positions);
|
||||
(b.len() == 4).then(|| vec![v2(b[0], b[1]), v2(b[2], b[1]), v2(b[2], b[3]), v2(b[0], b[3])])
|
||||
}
|
||||
|
||||
/// Kontext-Schicht (`addContextContours`). Objekte ohne Kategorie bleiben immer sichtbar.
|
||||
pub fn plan_context(c: &Ctx, out: &mut Vec<Primitive>) {
|
||||
for obj in c.p.context.as_deref().unwrap_or(&[]) {
|
||||
let code = match obj {
|
||||
ContextObject::ImportedMesh(m) => m.category_code.as_deref(),
|
||||
ContextObject::ContourSet(s) => s.category_code.as_deref(),
|
||||
ContextObject::TerrainMesh(t) => t.category_code.as_deref(),
|
||||
ContextObject::Image(i) => i.category_code.as_deref(),
|
||||
};
|
||||
if code.is_some_and(|k| !c.shown(k)) {
|
||||
continue;
|
||||
}
|
||||
match obj {
|
||||
ContextObject::ContourSet(s) => {
|
||||
for k in &s.contours {
|
||||
let pts = &k.pts;
|
||||
if pts.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let seg_end = if k.closed { pts.len() } else { pts.len() - 1 };
|
||||
for i in 0..seg_end {
|
||||
out.push(context_line(pts[i], pts[(i + 1) % pts.len()]));
|
||||
}
|
||||
}
|
||||
}
|
||||
ContextObject::ImportedMesh(m) => {
|
||||
let f = crate::plan_misc::context_footprint(&m.positions, &m.indices);
|
||||
let n = f.first().copied().unwrap_or(0.0) as usize;
|
||||
for i in 0..n {
|
||||
out.push(context_line(v2(f[1 + 4 * i], f[2 + 4 * i]), v2(f[3 + 4 * i], f[4 + 4 * i])));
|
||||
}
|
||||
if let Some(pts) = bbox_corners(&m.positions) {
|
||||
out.push(pick_band(pts, Some(&m.id), None));
|
||||
}
|
||||
}
|
||||
ContextObject::TerrainMesh(t) => {
|
||||
if let Some(q) = bbox_corners(&t.positions) {
|
||||
for i in 0..4 {
|
||||
out.push(context_line(q[i], q[(i + 1) % 4]));
|
||||
}
|
||||
out.push(pick_band(q, Some(&t.id), None));
|
||||
}
|
||||
}
|
||||
ContextObject::Image(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Kurz-Tag eines Schnitt-Labels: letztes Wort des Namens, sonst der ganze (getrimmte) Name.
|
||||
pub fn section_label_tag(name: &str) -> String {
|
||||
let t = js_trim(name);
|
||||
let parts: Vec<&str> = t.split(js_space).filter(|s| !s.is_empty()).collect();
|
||||
if parts.len() > 1 {
|
||||
parts[parts.len() - 1].to_string()
|
||||
} else {
|
||||
t.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Schnittführungs-Symbole aller Schnitt-/Ansichtsebenen mit Linie (`addSectionLines`).
|
||||
pub fn plan_section_lines(c: &Ctx, out: &mut Vec<Primitive>) {
|
||||
if !c.shown(SECTION_LINE_CATEGORY) {
|
||||
return;
|
||||
}
|
||||
let greyed = Some(c.greyed(SECTION_LINE_CATEGORY));
|
||||
for level in &c.p.drawing_levels {
|
||||
if !matches!(level.kind, DrawingLevelKind::Section | DrawingLevelKind::Elevation) {
|
||||
continue;
|
||||
}
|
||||
let Some([p0, p1]) = level.line_points else { continue };
|
||||
let f = crate::plan_misc::section_line(p0.x, p0.y, p1.x, p1.y, level.direction_sign.unwrap_or(1.0));
|
||||
if f.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let n = f[0] as usize;
|
||||
let mut i = 1;
|
||||
for _ in 0..n {
|
||||
if f[i] == 2.0 {
|
||||
let main = f[i + 1] == 0.0;
|
||||
out.push(Primitive::Line {
|
||||
a: v2(f[i + 2], f[i + 3]),
|
||||
b: v2(f[i + 4], f[i + 5]),
|
||||
cls: "section-line".into(),
|
||||
weight_mm: if main { SECTION_LINE_MM } else { SECTION_LINE_MARK_MM },
|
||||
dash: main.then(|| Some(SECTION_LINE_DASH.to_vec())),
|
||||
zigzag: None,
|
||||
motif: None,
|
||||
color: Some(SECTION_LINE_INK.into()),
|
||||
drawing_id: None,
|
||||
opening_id: None,
|
||||
stair_id: None,
|
||||
greyed,
|
||||
opacity: None,
|
||||
});
|
||||
i += 6;
|
||||
} else if f[i] == 5.0 {
|
||||
out.push(Primitive::DrawingText {
|
||||
at: v2(f[i + 1], f[i + 2]),
|
||||
text: section_label_tag(&level.name),
|
||||
height_m: SECTION_LABEL_H,
|
||||
angle: 0.0,
|
||||
color: SECTION_LINE_INK.into(),
|
||||
marks: None,
|
||||
wrap_width: None,
|
||||
doc: None,
|
||||
drawing_id: None,
|
||||
greyed,
|
||||
opacity: None,
|
||||
});
|
||||
i += 3;
|
||||
} else {
|
||||
let pts = (0..4).map(|j| v2(f[i + 1 + 2 * j], f[i + 2 + 2 * j])).collect();
|
||||
out.push(pick_band(pts, None, Some(&level.id)));
|
||||
i += 9;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn label_tag_wie_ts() {
|
||||
assert_eq!(section_label_tag("Schnitt A"), "A");
|
||||
assert_eq!(section_label_tag(" Ansicht Süd "), "Süd");
|
||||
assert_eq!(section_label_tag("Längsschnitt"), "Längsschnitt");
|
||||
assert_eq!(section_label_tag(" "), "");
|
||||
assert_eq!(section_label_tag("a\u{A0}b"), "b");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,608 @@
|
||||
//! Plan-Domänen auf dem Dokument ([K3d]): Decken, Dächer, Räume (mit Raumstempel-Daten), Wände mit
|
||||
//! Öffnungen (`walls.rs`), Treppen (`stairs.rs`), Kontext und Schnittlinien (`context.rs`), Stützen und Extrusions-Umrisse als fertige [`Primitive`] — Rust-Gegenstück zu `generatePlan/{ceilings,roofs,
|
||||
//! rooms,structures}.ts` samt Filter, Override-Regeln und Stil-Auflösung aus `generatePlan.ts`.
|
||||
//! Die JSON-Ausgabe gleicht Feld für Feld der früheren TS-Ausgabe.
|
||||
//!
|
||||
//! Sichtbarkeit/Darstellungsmodus kommen als Code-Mengen vom Aufrufer (`show`: sichtbar und
|
||||
//! gezeichnet, `grey`: gedimmt), weil der Resolver in TS (UI-Zustand) lebt.
|
||||
|
||||
use super::overrides::{self, js_trim, Actions, Subject};
|
||||
use super::prim::{HatchRender, Primitive, StampLine};
|
||||
use super::style::*;
|
||||
use crate::js_fmt::{js_number, to_fixed};
|
||||
use crate::jsnum::{max, min, round};
|
||||
use crate::model::*;
|
||||
use crate::plan_walls::{ceiling_outline_lines, wall_footprint, WallFootprint};
|
||||
use serde::Serialize;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Footprint-Farbe der Extrusionen (wie das 3D-Orange).
|
||||
const EXTRUSION_STROKE: &str = "#d98c40";
|
||||
/// Rückfall-Füllung einer Stütze ohne auflösbares Bauteil.
|
||||
const COLUMN_FALLBACK_FILL: &str = "#3a3f47";
|
||||
/// Alpha-Suffix der (unsichtbaren) Raumfüllung.
|
||||
const ROOM_FILL_ALPHA: &str = "00";
|
||||
/// Basis-Schriftgrösse des Raumstempels (pt).
|
||||
const ROOM_STAMP_PT: f64 = 10.0;
|
||||
const NAME_PT: f64 = 12.0;
|
||||
const NUMBER_PT: f64 = 9.0;
|
||||
const LINE2_PT: f64 = 9.0;
|
||||
|
||||
/// Eingabe einer Plan-Abfrage.
|
||||
pub struct PlanArgs {
|
||||
pub floor: String,
|
||||
pub detail: Detail,
|
||||
pub show: HashSet<String>,
|
||||
pub grey: HashSet<String>,
|
||||
/// Wand-Achslinien zeichnen (Oberleiste).
|
||||
pub reference_lines: bool,
|
||||
/// Projektglobale Zutaten (Kontext, Schnittlinien) — nur der aktive Aufruf einer Überlagerung.
|
||||
pub global: bool,
|
||||
}
|
||||
|
||||
impl PlanArgs {
|
||||
/// `detail`: 0 grob, 1 mittel, 2 fein; `text`: `{"floor": id, "show": [code…], "grey": [code…],
|
||||
/// "referenceLines": bool, "global": bool}`.
|
||||
pub fn parse(detail: f64, text: &str) -> Result<PlanArgs, String> {
|
||||
let v: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("Plan-Argumente: {e}"))?;
|
||||
let set = |k: &str| -> HashSet<String> { v.get(k).and_then(|a| a.as_array()).map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect()).unwrap_or_default() };
|
||||
Ok(PlanArgs {
|
||||
floor: v.get("floor").and_then(|f| f.as_str()).unwrap_or_default().to_string(),
|
||||
detail: match detail as i64 {
|
||||
0 => Detail::Grob,
|
||||
2 => Detail::Fein,
|
||||
_ => Detail::Mittel,
|
||||
},
|
||||
show: set("show"),
|
||||
grey: set("grey"),
|
||||
reference_lines: v.get("referenceLines").and_then(|b| b.as_bool()).unwrap_or(false),
|
||||
global: v.get("global").and_then(|b| b.as_bool()).unwrap_or(false),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Gemeinsamer Zustand einer Plan-Erzeugung.
|
||||
pub struct Ctx<'a> {
|
||||
pub p: &'a Project,
|
||||
pub a: &'a PlanArgs,
|
||||
/// Code → Kategorie (bei doppeltem Code gewinnt die letzte, wie `Map.set` in TS).
|
||||
cats: HashMap<&'a str, &'a LayerCategory>,
|
||||
}
|
||||
|
||||
impl<'a> Ctx<'a> {
|
||||
pub fn new(p: &'a Project, a: &'a PlanArgs) -> Self {
|
||||
let mut cats = HashMap::new();
|
||||
for c in p.flat_categories() {
|
||||
cats.insert(c.code.as_str(), c);
|
||||
}
|
||||
Ctx { p, a, cats }
|
||||
}
|
||||
|
||||
pub fn shown(&self, code: &str) -> bool {
|
||||
self.a.show.contains(code)
|
||||
}
|
||||
|
||||
pub fn greyed(&self, code: &str) -> bool {
|
||||
self.a.grey.contains(code)
|
||||
}
|
||||
|
||||
pub fn cat(&self, code: &str) -> Option<&'a LayerCategory> {
|
||||
self.cats.get(code).copied()
|
||||
}
|
||||
|
||||
/// Effektive Override-Aktionen eines Elements (`overrideFor` in TS).
|
||||
pub fn overrides(&self, code: &str, object_name: Option<&str>) -> Actions {
|
||||
overrides::effective(self.p.override_rules.as_deref(), &Subject { layer_name: self.cat(code).map(|c| c.name.as_str()), layer_code: Some(code), object_name })
|
||||
}
|
||||
}
|
||||
|
||||
/// Ergebnis der Abfrage `planDomains`: Primitive je Domäne (TS setzt sie an ihre Stelle in der
|
||||
/// Zeichenreihenfolge) und das Ausmass der Decken, Räume und Dach-Traufen.
|
||||
#[derive(Serialize, Default)]
|
||||
pub struct DomainPrims {
|
||||
pub ceilings: Vec<Primitive>,
|
||||
/// Wände (Poché, Referenzlinie) mit ihren Öffnungs-Symbolen, je Wand nacheinander.
|
||||
pub walls: Vec<Primitive>,
|
||||
/// Treppen-Symbole (`stairs.rs`).
|
||||
pub stairs: Vec<Primitive>,
|
||||
/// Kontext-Konturen und Schnittführungs-Symbole (`context.rs`), nur mit `global`.
|
||||
pub context: Vec<Primitive>,
|
||||
pub sections: Vec<Primitive>,
|
||||
pub roofs: Vec<Primitive>,
|
||||
pub rooms: Vec<Primitive>,
|
||||
pub columns: Vec<Primitive>,
|
||||
pub solids: Vec<Primitive>,
|
||||
/// `[minX, minY, maxX, maxY]`; fehlt ohne Punkte.
|
||||
pub bounds: Option<[f64; 4]>,
|
||||
}
|
||||
|
||||
pub struct Bounds([f64; 4]);
|
||||
|
||||
impl Bounds {
|
||||
fn new() -> Self {
|
||||
Bounds([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY])
|
||||
}
|
||||
pub fn acc(&mut self, x: f64, y: f64) {
|
||||
let b = &mut self.0;
|
||||
b[0] = min(b[0], x);
|
||||
b[1] = min(b[1], y);
|
||||
b[2] = max(b[2], x);
|
||||
b[3] = max(b[3], y);
|
||||
}
|
||||
fn get(&self) -> Option<[f64; 4]> {
|
||||
self.0[0].is_finite().then_some(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Pick-Bezug eines Polygons.
|
||||
enum Pick<'a> {
|
||||
Ceiling(&'a str),
|
||||
Roof(&'a str),
|
||||
Room(&'a str),
|
||||
Column(&'a str),
|
||||
Solid(&'a str),
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn polygon(pts: Vec<Vec2>, fill: &str, stroke: &str, w: f64, hatch: HatchRender, greyed: Option<bool>, no_stroke_edges: Option<Vec<f64>>, pick: Pick) -> Primitive {
|
||||
let (mut ceiling_id, mut roof_id, mut room_id, mut column_id, mut extruded_solid_id) = (None, None, None, None, None);
|
||||
match pick {
|
||||
Pick::Ceiling(s) => ceiling_id = Some(s.to_string()),
|
||||
Pick::Roof(s) => roof_id = Some(s.to_string()),
|
||||
Pick::Room(s) => room_id = Some(s.to_string()),
|
||||
Pick::Column(s) => column_id = Some(s.to_string()),
|
||||
Pick::Solid(s) => extruded_solid_id = Some(s.to_string()),
|
||||
}
|
||||
Primitive::Polygon {
|
||||
pts,
|
||||
fill: fill.into(),
|
||||
stroke: stroke.into(),
|
||||
stroke_width_mm: w,
|
||||
hatch,
|
||||
greyed,
|
||||
opacity: None,
|
||||
no_stroke_edges,
|
||||
wall_id: None,
|
||||
drawing_id: None,
|
||||
ceiling_id,
|
||||
opening_id: None,
|
||||
stair_id: None,
|
||||
room_id,
|
||||
extruded_solid_id,
|
||||
context_object_id: None,
|
||||
column_id,
|
||||
roof_id,
|
||||
section_line_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn line(a: Vec2, b: Vec2, cls: &str, w: f64, dash: super::prim::Dash, color: &str, greyed: Option<bool>) -> Primitive {
|
||||
Primitive::Line { a, b, cls: cls.into(), weight_mm: w, dash, zigzag: None, motif: None, color: Some(color.into()), drawing_id: None, opening_id: None, stair_id: None, greyed, opacity: None }
|
||||
}
|
||||
|
||||
fn pv(p: [f64; 2]) -> Vec2 {
|
||||
Vec2 { x: p[0], y: p[1] }
|
||||
}
|
||||
|
||||
/// `getComponent` (wirft in TS).
|
||||
fn component<'a>(p: &'a Project, id: &str) -> Result<&'a Component, String> {
|
||||
p.component(id).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {id}"))
|
||||
}
|
||||
|
||||
/// `resolveHatch` mit der Fehlermeldung von TS (`getHatch`/`getLineStyle` werfen).
|
||||
pub(super) fn resolve_hatch_or_err(p: &Project, hatch_id: &str, wall_angle_deg: Option<f64>, fg: Option<&str>) -> Result<HatchRender, String> {
|
||||
let h = p.hatch(hatch_id).ok_or_else(|| format!("Unbekannte Schraffur: {hatch_id}"))?;
|
||||
if let Some(ls) = h.line_style_id.as_deref().filter(|s| !s.is_empty()) {
|
||||
p.line_style(ls).ok_or_else(|| format!("Unbekannter Linienstil: {ls}"))?;
|
||||
}
|
||||
resolve_hatch(p, hatch_id, wall_angle_deg, fg, None).ok_or_else(|| format!("Unbekannte Schraffur: {hatch_id}"))
|
||||
}
|
||||
|
||||
/// Footprints der gezeichneten Wände dieses Geschosses (`buildWallFootprints`).
|
||||
pub fn wall_footprints(c: &Ctx) -> Vec<WallFootprint> {
|
||||
c.p.walls
|
||||
.iter()
|
||||
.filter(|w| w.floor_id == c.a.floor && c.shown(&w.category_code))
|
||||
.map(|w| {
|
||||
let t = c.p.wall_thickness(w, 0.2);
|
||||
let ref_off = crate::joins::reference_offset(crate::model3d::wall_reference(w), t);
|
||||
wall_footprint([w.start.x, w.start.y], [w.end.x, w.end.y], t, ref_off)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ── Decken ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Schichten des Deckentyps (`getCeilingType`; wirft ohne Typ).
|
||||
fn ceiling_layers<'a>(p: &'a Project, c: &Ceiling) -> Result<&'a [Layer], String> {
|
||||
if let Some(id) = c.ceiling_type_id.as_deref().filter(|s| !s.is_empty()) {
|
||||
if let Some(ct) = p.ceiling_types.as_deref().unwrap_or(&[]).iter().find(|t| t.id == id) {
|
||||
return Ok(&ct.layers);
|
||||
}
|
||||
}
|
||||
p.wall_types.iter().find(|t| t.id == c.wall_type_id).map(|t| t.layers.as_slice()).ok_or_else(|| format!("Unbekannter Deckentyp: {}", c.ceiling_type_id.as_deref().unwrap_or(&c.wall_type_id)))
|
||||
}
|
||||
|
||||
/// Typname einer Decke für `object_name` (Maps in TS: letzter Eintrag je id gewinnt).
|
||||
fn ceiling_type_name<'a>(p: &'a Project, c: &Ceiling) -> Option<&'a str> {
|
||||
let ct = c.ceiling_type_id.as_deref().filter(|s| !s.is_empty()).and_then(|id| p.ceiling_types.as_deref().unwrap_or(&[]).iter().rev().find(|t| t.id == id));
|
||||
ct.map(|t| t.name.as_str()).or_else(|| p.wall_types.iter().rev().find(|t| t.id == c.wall_type_id).map(|t| t.name.as_str()))
|
||||
}
|
||||
|
||||
fn ceilings(c: &Ctx, out: &mut Vec<Primitive>, bounds: &mut Bounds) -> Result<(), String> {
|
||||
let p = c.p;
|
||||
let list: Vec<&Ceiling> = p.ceilings.as_deref().unwrap_or(&[]).iter().filter(|x| x.floor_id == c.a.floor && c.shown(&x.category_code)).collect();
|
||||
if list.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let fps = wall_footprints(c);
|
||||
for ce in list {
|
||||
for q in &ce.outline {
|
||||
bounds.acc(q.x, q.y);
|
||||
}
|
||||
let ov = c.overrides(&ce.category_code, ceiling_type_name(p, ce));
|
||||
let color = ov.color.as_deref().or(ce.color.as_deref());
|
||||
let greyed = c.greyed(&ce.category_code);
|
||||
let category = c.cat(&ce.category_code);
|
||||
let lw = resolve_stroke_weight(ce.stroke_weight, ce.stroke_weight_source, category, category.map_or(LAYER_LINE_MM, |k| k.lw));
|
||||
if ce.outline.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let pts: Vec<[f64; 2]> = ce.outline.iter().map(|v| [v.x, v.y]).collect();
|
||||
let holes: Vec<Vec<[f64; 2]>> = ce.openings.as_deref().unwrap_or(&[]).iter().map(|h| h.iter().map(|v| [v.x, v.y]).collect()).collect();
|
||||
let merged = crate::polygon_holes::merge_holes(&pts, &holes, 1e-4);
|
||||
let layers = ceiling_layers(p, ce)?;
|
||||
let comp = match layers.first() {
|
||||
Some(l) => Some(component(p, &l.component_id)?),
|
||||
None => None,
|
||||
};
|
||||
let stroke = color.unwrap_or(POCHE_STROKE);
|
||||
let view_hatch_id = resolve_hatch_id(ce.hatch_id.as_deref(), ce.hatch_source, category, comp.and_then(|k| k.view_hatch_id.as_deref()));
|
||||
let hatch = match (c.a.detail != Detail::Grob, comp, view_hatch_id.filter(|s| !s.is_empty())) {
|
||||
(true, Some(k), Some(id)) => resolve_hatch_or_err(p, id, None, resolve_foreground(k, ce.foreground.as_deref(), category, ce.foreground_source))?,
|
||||
_ => no_hatch(),
|
||||
};
|
||||
let fill = match comp {
|
||||
Some(k) => resolve_background(k, ce.background.as_deref(), category, ce.background_source).unwrap_or(poche_fill(hatch.pattern)).to_string(),
|
||||
None => "none".to_string(),
|
||||
};
|
||||
let ring: Vec<Vec2> = merged.ring.iter().map(|q| pv(*q)).collect();
|
||||
let bridges = (!merged.bridge_edges.is_empty()).then(|| merged.bridge_edges.iter().map(|&k| k as f64).collect());
|
||||
out.push(polygon(ring, &fill, "none", 0.0, hatch, Some(greyed), bridges, Pick::Ceiling(&ce.id)));
|
||||
let w = lw * c.a.detail.layer_factor();
|
||||
for [a, b] in ceiling_outline_lines(&merged.ring, &merged.bridge_edges, &fps) {
|
||||
out.push(line(pv(a), pv(b), "ceiling-outline", w, Some(Some(OVERHEAD_DASH.to_vec())), stroke, Some(greyed)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ── Dächer ──────────────────────────────────────────────────────────────────
|
||||
|
||||
fn roofs(c: &Ctx, out: &mut Vec<Primitive>, bounds: &mut Bounds) {
|
||||
let p = c.p;
|
||||
for roof in p.roofs.as_deref().unwrap_or(&[]).iter().filter(|r| r.floor_id == c.a.floor && c.shown(&r.category_code)) {
|
||||
let greyed = Some(c.greyed(&roof.category_code));
|
||||
let category = c.cat(&roof.category_code);
|
||||
let stroke = roof.color.as_deref().or(category.map(|k| k.color.as_str())).unwrap_or(POCHE_STROKE);
|
||||
let geo = crate::roof::roof_geometry(&roof.params(), 0.0);
|
||||
for q in &geo.eaves {
|
||||
bounds.acc(q[0], q[1]);
|
||||
}
|
||||
// Ansichts-Schraffur der äussersten Schicht (Eindeckung); Fehler → ohne.
|
||||
let layers = p.roof_layers(roof);
|
||||
let view_hatch = layers
|
||||
.first()
|
||||
.filter(|l| !l.component_id.is_empty())
|
||||
.and_then(|l| p.component(&l.component_id))
|
||||
.and_then(|k| k.view_hatch_id.as_deref().filter(|s| !s.is_empty()))
|
||||
.and_then(|id| resolve_hatch(p, id, None, None, None))
|
||||
.unwrap_or_else(no_hatch);
|
||||
let eaves: Vec<Vec2> = geo.eaves.iter().map(|q| pv(*q)).collect();
|
||||
if eaves.len() >= 3 {
|
||||
out.push(polygon(eaves.clone(), "none", "none", 0.0, view_hatch, greyed, None, Pick::Roof(&roof.id)));
|
||||
}
|
||||
let n = eaves.len();
|
||||
for i in 0..n {
|
||||
out.push(line(eaves[i], eaves[(i + 1) % n], "roof-eaves", ROOF_EAVES_MM, None, stroke, greyed));
|
||||
}
|
||||
for l in &geo.ridges {
|
||||
out.push(line(pv(l[0]), pv(l[1]), "roof-ridge", ROOF_RIDGE_MM, None, stroke, greyed));
|
||||
}
|
||||
for l in &geo.hips {
|
||||
out.push(line(pv(l[0]), pv(l[1]), "roof-hip", ROOF_HIP_MM, None, stroke, greyed));
|
||||
}
|
||||
for l in &geo.breaks {
|
||||
out.push(line(pv(l[0]), pv(l[1]), "roof-break", ROOF_BREAK_MM, Some(Some(ROOF_BREAK_DASH.to_vec())), stroke, greyed));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Räume ───────────────────────────────────────────────────────────────────
|
||||
|
||||
fn sia_key(s: SiaCategory) -> &'static str {
|
||||
match s {
|
||||
SiaCategory::HNF => "HNF",
|
||||
SiaCategory::NNF => "NNF",
|
||||
SiaCategory::VF => "VF",
|
||||
SiaCategory::FF => "FF",
|
||||
SiaCategory::KGF => "KGF",
|
||||
SiaCategory::AGF => "AGF",
|
||||
SiaCategory::Unknown => "undefined",
|
||||
}
|
||||
}
|
||||
|
||||
fn sia_label(s: SiaCategory) -> &'static str {
|
||||
match s {
|
||||
SiaCategory::HNF => "Hauptnutzfläche",
|
||||
SiaCategory::NNF => "Nebennutzfläche",
|
||||
SiaCategory::VF => "Verkehrsfläche",
|
||||
SiaCategory::FF => "Funktionsfläche",
|
||||
SiaCategory::KGF => "Konstruktionsfläche",
|
||||
SiaCategory::AGF => "Aussengeschossfläche",
|
||||
SiaCategory::Unknown => "undefined",
|
||||
}
|
||||
}
|
||||
|
||||
fn run(text: String, marks: Marks) -> TextRun {
|
||||
TextRun { text, marks, ..Default::default() }
|
||||
}
|
||||
|
||||
/// `docFromText`: je Zeile ein Absatz (leere Zeile = ohne Run).
|
||||
pub fn doc_from_text(text: &str) -> RichTextDoc {
|
||||
RichTextDoc {
|
||||
version: 1.0,
|
||||
paragraphs: text.split('\n').map(|l| Paragraph { runs: if l.is_empty() { vec![] } else { vec![run(l.into(), Marks::default())] }, ..Default::default() }).collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// `roomStampToDoc`: Zeile 1 = Nummer (klein) + Name (fett), Zeile 2 optional (kursiv).
|
||||
pub fn room_stamp_to_doc(s: &RoomStamp) -> RichTextDoc {
|
||||
let mut line1 = Vec::new();
|
||||
let number = js_trim(s.number.as_deref().unwrap_or(""));
|
||||
if !number.is_empty() {
|
||||
line1.push(run(format!("{number} "), Marks { size_pt: Some(NUMBER_PT), ..Default::default() }));
|
||||
}
|
||||
line1.push(run(s.name.clone(), Marks { bold: Some(true), size_pt: Some(NAME_PT), ..Default::default() }));
|
||||
let mut paragraphs = vec![Paragraph { runs: line1, align: s.name_align, ..Default::default() }];
|
||||
let line2 = js_trim(s.name_line2.as_deref().unwrap_or(""));
|
||||
if !line2.is_empty() {
|
||||
paragraphs.push(Paragraph { runs: vec![run(line2.into(), Marks { italic: Some(true), size_pt: Some(LINE2_PT), ..Default::default() })], align: s.line2_align, ..Default::default() });
|
||||
}
|
||||
RichTextDoc { version: 1.0, paragraphs, ..Default::default() }
|
||||
}
|
||||
|
||||
/// `formatStampArea`.
|
||||
pub fn format_stamp_area(area: f64, step: Option<f64>) -> String {
|
||||
match step {
|
||||
Some(st) if st > 0.0 => {
|
||||
let rounded = round(area / st) * st;
|
||||
js_number(round(rounded * 100.0) / 100.0)
|
||||
}
|
||||
_ => to_fixed(area, 2),
|
||||
}
|
||||
}
|
||||
|
||||
/// `roomStampExtraLines`.
|
||||
pub fn room_stamp_extra_lines(s: &RoomStamp, net_area: f64, sia: SiaCategory) -> Vec<StampLine> {
|
||||
let mut lines = Vec::new();
|
||||
if s.show_floor_area {
|
||||
let prefix = s.floor_area_prefix.as_deref().unwrap_or("");
|
||||
lines.push(StampLine { text: format!("{prefix}{} m²", format_stamp_area(net_area, s.rounding_step)), align: s.floor_area_align.unwrap_or(Align::Center) });
|
||||
}
|
||||
if s.show_usage {
|
||||
lines.push(StampLine { text: format!("{} · {}", sia_key(sia), sia_label(sia)), align: s.usage_align.unwrap_or(Align::Center) });
|
||||
}
|
||||
if let Some(o) = s.occupancy {
|
||||
lines.push(StampLine { text: format!("{} Pers.", js_number(o)), align: Align::Center });
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// Farbe mit Alpha-Suffix, nur bei 6-stelligem Hex (`/^#[0-9a-fA-F]{6}$/`).
|
||||
fn with_alpha(color: &str, alpha: &str) -> String {
|
||||
let b = color.as_bytes();
|
||||
if b.len() == 7 && b[0] == b'#' && b[1..].iter().all(|c| c.is_ascii_hexdigit()) {
|
||||
format!("{color}{alpha}")
|
||||
} else {
|
||||
color.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn rooms(c: &Ctx, out: &mut Vec<Primitive>, bounds: &mut Bounds) {
|
||||
for room in c.p.rooms.as_deref().unwrap_or(&[]).iter().filter(|r| r.floor_id == c.a.floor && c.shown(&r.category_code)) {
|
||||
for q in &room.boundary {
|
||||
bounds.acc(q.x, q.y);
|
||||
}
|
||||
let ov = c.overrides(&room.category_code, Some(&room.name));
|
||||
let color = ov.color.as_deref().unwrap_or(&room.color);
|
||||
let greyed = Some(c.greyed(&room.category_code));
|
||||
if room.boundary.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let pts: Vec<[f64; 2]> = room.boundary.iter().map(|v| [v.x, v.y]).collect();
|
||||
let res = crate::room_area::evaluate(&pts, 0.0);
|
||||
out.push(polygon(room.boundary.clone(), &with_alpha(color, ROOM_FILL_ALPHA), color, LAYER_LINE_MM * c.a.detail.layer_factor(), no_hatch(), greyed, None, Pick::Room(&room.id)));
|
||||
if c.a.detail == Detail::Grob {
|
||||
continue;
|
||||
}
|
||||
let at = room.stamp_anchor.unwrap_or(pv(res.centroid));
|
||||
let (doc, extra_lines) = match &room.stamp {
|
||||
Some(s) => (room_stamp_to_doc(s), room_stamp_extra_lines(s, res.net, room.sia_category)),
|
||||
None => (
|
||||
room.stamp_doc.clone().unwrap_or_else(|| doc_from_text(&room.name)),
|
||||
vec![
|
||||
StampLine { text: format!("{} m²", to_fixed(res.net, 2)), align: Align::Center },
|
||||
StampLine { text: format!("{} · {}", sia_key(room.sia_category), sia_label(room.sia_category)), align: Align::Center },
|
||||
],
|
||||
),
|
||||
};
|
||||
out.push(Primitive::Text { at, doc, extra_lines, base_pt: ROOM_STAMP_PT, color: color.into(), room_id: Some(room.id.clone()), greyed, opacity: None });
|
||||
}
|
||||
}
|
||||
|
||||
// ── Stützen ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/// `columnLabel` (für `object_name`).
|
||||
pub fn column_label(col: &Column) -> String {
|
||||
match &col.profile {
|
||||
ColumnProfile::Round { radius } => format!("Stütze Ø{}", to_fixed(radius * 200.0, 0)),
|
||||
ColumnProfile::Rect { width, depth } => format!("Stütze {}×{}", to_fixed(width * 100.0, 0), to_fixed(depth * 100.0, 0)),
|
||||
}
|
||||
}
|
||||
|
||||
fn columns(c: &Ctx, out: &mut Vec<Primitive>) {
|
||||
let p = c.p;
|
||||
for col in p.columns.as_deref().unwrap_or(&[]).iter().filter(|k| k.floor_id == c.a.floor && c.shown(&k.category_code)) {
|
||||
let greyed = Some(c.greyed(&col.category_code));
|
||||
let category = c.cat(&col.category_code);
|
||||
let ov = c.overrides(&col.category_code, Some(&column_label(col)));
|
||||
let lw = ov.lineweight.unwrap_or_else(|| resolve_stroke_weight(col.stroke_weight, col.stroke_weight_source, category, category.map_or(WALL_FALLBACK_MM, |k| k.lw)));
|
||||
let color = ov.color.as_deref().or(col.color.as_deref());
|
||||
let cat_color = category.map(|k| k.color.as_str());
|
||||
let stroke = color.or(cat_color).unwrap_or(MONO_INK);
|
||||
let mut fill = color.or(cat_color).unwrap_or(COLUMN_FALLBACK_FILL).to_string();
|
||||
let mut hatch = no_hatch();
|
||||
if let Some(k) = col.component_id.as_deref().filter(|s| !s.is_empty()).and_then(|id| p.component(id)) {
|
||||
let hatch_id = resolve_hatch_id(col.hatch_id.as_deref(), col.hatch_source, category, Some(&k.hatch_id)).unwrap_or(&k.hatch_id);
|
||||
if let Some(h) = resolve_hatch(p, hatch_id, None, resolve_foreground(k, col.foreground.as_deref(), category, col.foreground_source), None) {
|
||||
let bg = resolve_background(k, col.background.as_deref(), category, col.background_source);
|
||||
fill = bg.unwrap_or(if h.pattern == HatchPattern::Solid { HATCH_INK } else { HATCH_PAPER }).to_string();
|
||||
hatch = h;
|
||||
}
|
||||
}
|
||||
out.push(polygon(crate::model3d::column_footprint(col), &fill, stroke, lw, hatch, greyed, None, Pick::Column(&col.id)));
|
||||
}
|
||||
}
|
||||
|
||||
// ── Extrusionen ─────────────────────────────────────────────────────────────
|
||||
|
||||
fn solids(c: &Ctx, out: &mut Vec<Primitive>) {
|
||||
for s in c.p.extruded_solids.as_deref().unwrap_or(&[]).iter().filter(|s| s.level_id == c.a.floor) {
|
||||
if s.operation.as_deref() == Some("subtract") {
|
||||
out.push(polygon(s.points.clone(), "none", "none", 0.0, no_hatch(), None, None, Pick::Solid(&s.id)));
|
||||
let n = s.points.len();
|
||||
let seg = |a: Vec2, b: Vec2, dash: Option<Vec<f64>>| line(a, b, "void", SYMBOL_HAIRLINE_MM, Some(dash), EXTRUSION_STROKE, None);
|
||||
for i in 0..n {
|
||||
out.push(seg(s.points[i], s.points[(i + 1) % n], Some(vec![2.0, 1.0])));
|
||||
}
|
||||
if n == 4 {
|
||||
out.push(seg(s.points[0], s.points[2], None));
|
||||
out.push(seg(s.points[1], s.points[3], None));
|
||||
}
|
||||
} else {
|
||||
out.push(polygon(s.points.clone(), "none", EXTRUSION_STROKE, SYMBOL_HAIRLINE_MM, no_hatch(), None, None, Pick::Solid(&s.id)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Abfrage `planDomains`.
|
||||
pub fn plan_domains(p: &Project, a: &PlanArgs) -> Result<DomainPrims, String> {
|
||||
let c = Ctx::new(p, a);
|
||||
let mut out = DomainPrims::default();
|
||||
let mut bounds = Bounds::new();
|
||||
ceilings(&c, &mut out.ceilings, &mut bounds)?;
|
||||
roofs(&c, &mut out.roofs, &mut bounds);
|
||||
rooms(&c, &mut out.rooms, &mut bounds);
|
||||
super::walls::plan_walls(&c, a.reference_lines, &mut out.walls, &mut bounds)?;
|
||||
super::stairs::plan_stairs(&c, &mut out.stairs, &mut bounds);
|
||||
columns(&c, &mut out.columns);
|
||||
solids(&c, &mut out.solids);
|
||||
if a.global {
|
||||
super::context::plan_context(&c, &mut out.context);
|
||||
super::context::plan_section_lines(&c, &mut out.sections);
|
||||
}
|
||||
out.bounds = bounds.get();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample() -> Project {
|
||||
serde_json::from_str(include_str!("../../tests/fixtures/sample_project.json")).unwrap()
|
||||
}
|
||||
|
||||
fn args(floor: &str, detail: f64, codes: &[&str]) -> PlanArgs {
|
||||
let t = serde_json::json!({ "floor": floor, "show": codes, "grey": [] }).to_string();
|
||||
PlanArgs::parse(detail, &t).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn beispiel_eg_decke_raum() {
|
||||
let p = sample();
|
||||
let r = plan_domains(&p, &args("eg", 1.0, &["20", "30", "60"])).unwrap();
|
||||
let s = serde_json::to_string(&r.ceilings).unwrap();
|
||||
assert!(s.contains("\"ceilingId\":\"C1\"") && s.contains("\"kind\":\"polygon\""), "{s}");
|
||||
// Decke deckungsgleich unter den Wänden: kein freier Umriss.
|
||||
assert!(!s.contains("ceiling-outline"));
|
||||
let rooms = serde_json::to_value(&r.rooms).unwrap();
|
||||
assert_eq!(rooms[1]["kind"], "text");
|
||||
assert_eq!(rooms[1]["extraLines"][0]["text"], "17.01 m²");
|
||||
assert_eq!(rooms[1]["extraLines"][1]["text"], "HNF · Hauptnutzfläche");
|
||||
assert!(r.bounds.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsichtbare_codes_fehlen() {
|
||||
let p = sample();
|
||||
let r = plan_domains(&p, &args("eg", 1.0, &[])).unwrap();
|
||||
assert!(r.ceilings.is_empty() && r.rooms.is_empty() && r.bounds.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stempel_flaeche_und_personen() {
|
||||
assert_eq!(format_stamp_area(17.0125, None), "17.01");
|
||||
assert_eq!(format_stamp_area(17.26, Some(0.5)), "17.5");
|
||||
assert_eq!(format_stamp_area(17.26, Some(0.1)), "17.3");
|
||||
let s = RoomStamp { name: "Bad".into(), show_floor_area: false, show_usage: false, occupancy: Some(1e21), ..Default::default() };
|
||||
assert_eq!(room_stamp_extra_lines(&s, 1.0, SiaCategory::VF)[0].text, "1e+21 Pers.");
|
||||
let d = room_stamp_to_doc(&RoomStamp { number: Some(" 2 ".into()), name: "Bad".into(), name_line2: Some(" ".into()), ..Default::default() });
|
||||
assert_eq!(d.paragraphs.len(), 1);
|
||||
assert_eq!(d.paragraphs[0].runs[0].text, "2 ");
|
||||
}
|
||||
|
||||
fn stamp(name: &str) -> RoomStamp {
|
||||
RoomStamp { name: name.into(), show_floor_area: true, show_usage: true, ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stempel_dokument() {
|
||||
assert_eq!(room_stamp_to_doc(&stamp("Bad")).paragraphs.len(), 1);
|
||||
assert_eq!(room_stamp_to_doc(&RoomStamp { name_line2: Some("WC".into()), ..stamp("Bad") }).paragraphs.len(), 2);
|
||||
let d = room_stamp_to_doc(&RoomStamp { number: Some("1.01".into()), ..stamp("Bad") });
|
||||
assert_eq!(d.paragraphs[0].runs.len(), 2);
|
||||
assert_eq!(d.paragraphs[0].runs[0].text, "1.01 ");
|
||||
assert_eq!(d.paragraphs[0].runs[1].text, "Bad");
|
||||
assert_eq!(d.paragraphs[0].runs[1].marks.bold, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stempel_zeilen() {
|
||||
let l = room_stamp_extra_lines(&RoomStamp { floor_area_prefix: Some("BF ".into()), ..stamp("Bad") }, 12.345, SiaCategory::HNF);
|
||||
assert_eq!(l[0].text, "BF 12.35 m²");
|
||||
assert_eq!(l[1].text, "HNF · Hauptnutzfläche");
|
||||
let off = RoomStamp { show_floor_area: false, show_usage: false, ..stamp("Bad") };
|
||||
assert!(room_stamp_extra_lines(&off, 12.345, SiaCategory::HNF).is_empty());
|
||||
let r = room_stamp_extra_lines(&RoomStamp { show_usage: false, rounding_step: Some(0.5), ..stamp("Bad") }, 12.34, SiaCategory::HNF);
|
||||
assert_eq!(r[0].text, "12.5 m²");
|
||||
let o = room_stamp_extra_lines(&RoomStamp { occupancy: Some(4.0), ..off.clone() }, 12.345, SiaCategory::HNF);
|
||||
assert_eq!(o.len(), 1);
|
||||
assert_eq!(o[0].text, "4 Pers.");
|
||||
assert_eq!(o[0].align, Align::Center);
|
||||
assert_eq!(format_stamp_area(12.345, None), "12.35");
|
||||
assert_eq!(format_stamp_area(12.0, None), "12.00");
|
||||
assert_eq!(format_stamp_area(12.24, Some(0.5)), "12");
|
||||
assert_eq!(format_stamp_area(12.26, Some(0.5)), "12.5");
|
||||
assert_eq!(format_stamp_area(12.3, Some(0.1)), "12.3");
|
||||
assert_eq!(format_stamp_area(12.34, Some(1.0)), "12");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stuetzen_label() {
|
||||
let col = Column { profile: ColumnProfile::Round { radius: 0.125 }, ..Default::default() };
|
||||
assert_eq!(column_label(&col), "Stütze Ø25");
|
||||
}
|
||||
}
|
||||
@@ -3,3 +3,8 @@
|
||||
|
||||
pub mod prim;
|
||||
pub mod style;
|
||||
pub mod overrides;
|
||||
pub mod domains;
|
||||
pub mod walls;
|
||||
pub mod stairs;
|
||||
pub mod context;
|
||||
@@ -0,0 +1,150 @@
|
||||
//! Grafische Overrides ([K3d]): wertet `Project.overrideRules` für ein Element aus — Rust-Gegenstück
|
||||
//! zu `src/overrides/engine.ts`. Pro Aktions-Feld gewinnt die OBERSTE aktive Regel, deren Bedingung
|
||||
//! passt; spätere Regeln füllen nur noch offene Felder. Vergleiche ohne Gross-/Kleinschreibung, Werte
|
||||
//! getrimmt (wie JS `trim()`/`toLowerCase()`).
|
||||
|
||||
use crate::model::*;
|
||||
|
||||
/// Die vergleichbaren Eigenschaften eines Elements.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Subject<'a> {
|
||||
/// Name der Ebene (`LayerCategory.name`).
|
||||
pub layer_name: Option<&'a str>,
|
||||
/// Code der Ebene (`categoryCode`).
|
||||
pub layer_code: Option<&'a str>,
|
||||
/// Element-/Typ-Name (Wandtyp, Raum, Öffnungs-Label …).
|
||||
pub object_name: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// Effektive Aktionen (alle `None` = kein Override).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Actions {
|
||||
pub color: Option<String>,
|
||||
pub lineweight: Option<f64>,
|
||||
pub linetype_id: Option<String>,
|
||||
}
|
||||
|
||||
impl Actions {
|
||||
pub fn any(&self) -> bool {
|
||||
self.color.is_some() || self.lineweight.is_some() || self.linetype_id.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// Leerraum im Sinne von JS `String.prototype.trim` (WhiteSpace + LineTerminator).
|
||||
pub fn js_space(c: char) -> bool {
|
||||
matches!(c, '\u{9}' | '\u{A}' | '\u{B}' | '\u{C}' | '\u{D}' | ' ' | '\u{A0}' | '\u{1680}' | '\u{2000}'..='\u{200A}' | '\u{2028}' | '\u{2029}' | '\u{202F}' | '\u{205F}' | '\u{3000}' | '\u{FEFF}')
|
||||
}
|
||||
|
||||
/// JS `s.trim()`.
|
||||
pub fn js_trim(s: &str) -> &str {
|
||||
s.trim_matches(js_space)
|
||||
}
|
||||
|
||||
fn norm(s: &str) -> String {
|
||||
js_trim(s).to_lowercase()
|
||||
}
|
||||
|
||||
/// `matchesCondition`: `layer_name` vergleicht Name UND Code (positive Operatoren: einer passt;
|
||||
/// `not_equals`: keiner gleich), `object_name` den Element-Namen. Fehlt die Eigenschaft, trifft nur
|
||||
/// `not_equals`.
|
||||
pub fn matches_condition(c: &OverrideCondition, s: &Subject) -> bool {
|
||||
let value = norm(&c.value);
|
||||
let mut cands: Vec<String> = Vec::with_capacity(2);
|
||||
if c.r#type == OverrideConditionType::LayerName {
|
||||
cands.extend(s.layer_name.map(norm));
|
||||
cands.extend(s.layer_code.map(norm));
|
||||
} else {
|
||||
cands.extend(s.object_name.map(norm));
|
||||
}
|
||||
if cands.is_empty() {
|
||||
return c.operator == OverrideOperator::NotEquals;
|
||||
}
|
||||
match c.operator {
|
||||
OverrideOperator::NotEquals => cands.iter().all(|x| *x != value),
|
||||
OverrideOperator::Equals => cands.contains(&value),
|
||||
OverrideOperator::Contains => cands.iter().any(|x| x.contains(value.as_str())),
|
||||
OverrideOperator::StartsWith => cands.iter().any(|x| x.starts_with(value.as_str())),
|
||||
OverrideOperator::Unknown => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `effectiveOverrides`: kollabiert die Regelliste für ein Subjekt.
|
||||
pub fn effective(rules: Option<&[OverrideRule]>, s: &Subject) -> Actions {
|
||||
let mut out = Actions::default();
|
||||
let Some(rules) = rules else { return out };
|
||||
for rule in rules {
|
||||
if !rule.enabled || !matches_condition(&rule.condition, s) {
|
||||
continue;
|
||||
}
|
||||
let a = &rule.actions;
|
||||
if out.color.is_none() {
|
||||
out.color = a.color.clone();
|
||||
}
|
||||
if out.lineweight.is_none() {
|
||||
out.lineweight = a.lineweight;
|
||||
}
|
||||
if out.linetype_id.is_none() {
|
||||
out.linetype_id = a.linetype_id.clone();
|
||||
}
|
||||
if out.color.is_some() && out.lineweight.is_some() && out.linetype_id.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const WALL: Subject = Subject { layer_name: Some("Wände"), layer_code: Some("20"), object_name: Some("AW 24") };
|
||||
|
||||
fn cond(t: OverrideConditionType, op: OverrideOperator, v: &str) -> OverrideCondition {
|
||||
OverrideCondition { r#type: t, operator: op, value: v.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
fn rule(enabled: bool, c: OverrideCondition, color: Option<&str>, lw: Option<f64>, lt: Option<&str>) -> OverrideRule {
|
||||
OverrideRule {
|
||||
enabled,
|
||||
condition: c,
|
||||
actions: OverrideActions { color: color.map(Into::into), lineweight: lw, linetype_id: lt.map(Into::into), ..Default::default() },
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
use OverrideConditionType::*;
|
||||
use OverrideOperator::*;
|
||||
|
||||
#[test]
|
||||
fn operatoren_wie_ts() {
|
||||
assert!(matches_condition(&cond(LayerName, Equals, " wände "), &WALL));
|
||||
assert!(!matches_condition(&cond(LayerName, Equals, "Decken"), &WALL));
|
||||
assert!(matches_condition(&cond(LayerName, Equals, "20"), &WALL));
|
||||
assert!(matches_condition(&cond(ObjectName, Contains, "24"), &WALL));
|
||||
assert!(matches_condition(&cond(ObjectName, StartsWith, "aw"), &WALL));
|
||||
assert!(!matches_condition(&cond(ObjectName, StartsWith, "24"), &WALL));
|
||||
assert!(!matches_condition(&cond(LayerName, NotEquals, "20"), &WALL));
|
||||
assert!(!matches_condition(&cond(LayerName, NotEquals, "Wände"), &WALL));
|
||||
assert!(matches_condition(&cond(LayerName, NotEquals, "Decken"), &WALL));
|
||||
let no_obj = Subject { object_name: None, ..WALL };
|
||||
assert!(!matches_condition(&cond(ObjectName, Contains, "x"), &no_obj));
|
||||
assert!(matches_condition(&cond(ObjectName, NotEquals, "x"), &no_obj));
|
||||
// JS-trim kennt U+FEFF, aber nicht U+0085.
|
||||
assert!(matches_condition(&cond(LayerName, Equals, "\u{FEFF}20\u{FEFF}"), &WALL));
|
||||
assert!(!matches_condition(&cond(LayerName, Equals, "\u{85}20"), &WALL));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oberste_regel_gewinnt_je_feld() {
|
||||
let rules = vec![
|
||||
rule(false, cond(LayerName, Equals, "20"), Some("#000"), None, None),
|
||||
rule(true, cond(LayerName, Equals, "20"), Some("#f00"), None, None),
|
||||
rule(true, cond(ObjectName, Contains, "aw"), Some("#0f0"), Some(0.7), None),
|
||||
rule(true, cond(LayerName, Equals, "Wände"), None, Some(0.1), Some("dashed")),
|
||||
];
|
||||
let a = effective(Some(&rules), &WALL);
|
||||
assert_eq!(a, Actions { color: Some("#f00".into()), lineweight: Some(0.7), linetype_id: Some("dashed".into()) });
|
||||
assert!(!effective(None, &WALL).any());
|
||||
assert!(!effective(Some(&[]), &WALL).any());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
//! Treppen im Grundriss auf dem Dokument ([K3d]): Filter, Override-Regeln, Stil und Pick-ID um
|
||||
//! das Treppen-Symbol aus `plan_stairs.rs` — Rust-Gegenstück zu `generatePlan/stairs.ts` und der
|
||||
//! Treppen-Schleife in `generatePlan.ts`.
|
||||
|
||||
use super::domains::{Bounds, Ctx};
|
||||
use super::prim::Primitive;
|
||||
use super::style::*;
|
||||
use crate::js_fmt::js_number;
|
||||
use crate::model::*;
|
||||
|
||||
/// Linienklassen der Kern-Kodierung (`plan_stairs.rs`).
|
||||
const LINE_CLS: [&str; 5] = ["stair-outline", "stair-tread", "stair-break", "stair-run", "stair-arrow"];
|
||||
/// Strichmuster der verdeckten Tritte.
|
||||
const TREAD_DASH: [f64; 2] = [0.12, 0.08];
|
||||
|
||||
/// `stairLabel` (für `object_name`).
|
||||
pub fn stair_label(s: &Stair) -> String {
|
||||
let shape = match s.shape {
|
||||
StairShape::Straight => "Gerade",
|
||||
StairShape::L => "L-Treppe",
|
||||
_ => "Wendel",
|
||||
};
|
||||
format!("{shape} {} STG", js_number(s.step_count))
|
||||
}
|
||||
|
||||
fn v2(x: f64, y: f64) -> Vec2 {
|
||||
Vec2 { x, y }
|
||||
}
|
||||
|
||||
/// Treppen des Geschosses in Zeichenreihenfolge; Tritte und Podest ins Ausmass.
|
||||
pub fn plan_stairs(c: &Ctx, out: &mut Vec<Primitive>, bounds: &mut Bounds) {
|
||||
let p = c.p;
|
||||
let cut_height = p.floor(&c.a.floor).and_then(|f| f.cut_height).unwrap_or(1.0);
|
||||
for s in p.stairs.as_deref().unwrap_or(&[]).iter().filter(|s| s.floor_id == c.a.floor && c.shown(&s.category_code)) {
|
||||
let greyed = Some(c.greyed(&s.category_code));
|
||||
let ov = c.overrides(&s.category_code, Some(&stair_label(s)));
|
||||
let lw = ov.lineweight.unwrap_or_else(|| c.cat(&s.category_code).map_or(WALL_FALLBACK_MM, |k| k.lw));
|
||||
let stroke = ov.color.as_deref().or(s.color.as_deref()).unwrap_or(POCHE_STROKE).to_string();
|
||||
let (zb, zt) = p.stair_vertical_extent(s);
|
||||
let params = s.encode();
|
||||
if let Some(sp) = crate::stair::decode_params(¶ms).filter(|_| (zt - zb).is_finite()) {
|
||||
let geo = kernel2d::stair_geometry(&sp, zt - zb);
|
||||
for t in &geo.treads {
|
||||
for q in &t.pts {
|
||||
bounds.acc(q.x, q.y);
|
||||
}
|
||||
}
|
||||
for q in geo.landing.iter().flatten() {
|
||||
bounds.acc(q.x, q.y);
|
||||
}
|
||||
}
|
||||
let f = crate::plan_stairs::plan_stair(¶ms, zt - zb, cut_height, lw, s.arrow_style == Some(StairArrowStyle::Filled));
|
||||
if f.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let n = f[0] as usize;
|
||||
let mut i = 1;
|
||||
for _ in 0..n {
|
||||
match f[i] as i64 {
|
||||
1 => {
|
||||
let count = f[i + 3] as usize;
|
||||
let pts = (0..count).map(|j| v2(f[i + 4 + 2 * j], f[i + 5 + 2 * j])).collect();
|
||||
out.push(Primitive::Polygon {
|
||||
pts,
|
||||
fill: if f[i + 2] != 0.0 { stroke.clone() } else { "none".into() },
|
||||
stroke: stroke.clone(),
|
||||
stroke_width_mm: f[i + 1],
|
||||
hatch: no_hatch(),
|
||||
greyed,
|
||||
opacity: None,
|
||||
no_stroke_edges: None,
|
||||
wall_id: None,
|
||||
drawing_id: None,
|
||||
ceiling_id: None,
|
||||
opening_id: None,
|
||||
stair_id: Some(s.id.clone()),
|
||||
room_id: None,
|
||||
extruded_solid_id: None,
|
||||
context_object_id: None,
|
||||
column_id: None,
|
||||
roof_id: None,
|
||||
section_line_id: None,
|
||||
});
|
||||
i += 4 + 2 * count;
|
||||
}
|
||||
2 => {
|
||||
let cls = LINE_CLS.get(f[i + 1] as usize).copied().unwrap_or("");
|
||||
let dash = (cls == "stair-tread").then(|| (f[i + 3] != 0.0).then(|| TREAD_DASH.to_vec()));
|
||||
out.push(Primitive::Line {
|
||||
a: v2(f[i + 4], f[i + 5]),
|
||||
b: v2(f[i + 6], f[i + 7]),
|
||||
cls: cls.into(),
|
||||
weight_mm: f[i + 2],
|
||||
dash,
|
||||
zigzag: None,
|
||||
motif: None,
|
||||
color: Some(stroke.clone()),
|
||||
drawing_id: None,
|
||||
opening_id: None,
|
||||
stair_id: Some(s.id.clone()),
|
||||
greyed,
|
||||
opacity: None,
|
||||
});
|
||||
i += 8;
|
||||
}
|
||||
_ => {
|
||||
out.push(Primitive::Arc {
|
||||
center: v2(f[i + 2], f[i + 3]),
|
||||
from: v2(f[i + 4], f[i + 5]),
|
||||
to: v2(f[i + 6], f[i + 7]),
|
||||
r: f[i + 8],
|
||||
cls: "stair-outline".into(),
|
||||
weight_mm: f[i + 1],
|
||||
dash: None,
|
||||
opening_id: None,
|
||||
stair_id: Some(s.id.clone()),
|
||||
greyed,
|
||||
opacity: None,
|
||||
});
|
||||
i += 9;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn label_wie_ts() {
|
||||
let s = Stair { shape: StairShape::L, step_count: 16.0, ..Default::default() };
|
||||
assert_eq!(stair_label(&s), "L-Treppe 16 STG");
|
||||
assert_eq!(stair_label(&Stair { shape: StairShape::Spiral, step_count: 12.0, ..Default::default() }), "Wendel 12 STG");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
//! Wände und Öffnungen im Grundriss auf dem Dokument ([K3d]): Filter, Override-Regeln,
|
||||
//! Verschneidung, Stil (Bauteil, Schraffur, Farbe, Fugen-Linienstil) und Pick-IDs um die schon
|
||||
//! portierte Geometrie (`plan_walls.rs`, `plan_openings.rs`) — Rust-Gegenstück zu
|
||||
//! `generatePlan/{walls,openings}.ts` und der Wand-Schleife in `generatePlan.ts`.
|
||||
//!
|
||||
//! Die Geometrie-Funktionen nehmen weiter ihren flachen Puffer; er wird hier genau so aufgebaut wie
|
||||
//! früher in TS, damit das Ergebnis bitgleich bleibt.
|
||||
|
||||
use super::domains::Ctx;
|
||||
use super::prim::{HatchRender, Primitive};
|
||||
use super::style::*;
|
||||
use crate::joins::{self, WallCuts};
|
||||
use crate::js_fmt::to_fixed;
|
||||
use crate::jsnum::{atan2, round};
|
||||
use crate::model::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Linienklassen der Öffnungs-Kodierung (`plan_openings.rs`).
|
||||
const LINE_CLS: [&str; 11] = [
|
||||
"door-leaf", "door-frame", "door-lintel", "opening-frame", "window-glass", "window-mullion", "window-sash", "window-stulp", "window-sill", "window-frame", "window-shading",
|
||||
];
|
||||
|
||||
fn dash_of(code: f64) -> Option<Vec<f64>> {
|
||||
match code as i64 {
|
||||
1 => Some(vec![0.18, 0.09]),
|
||||
2 => Some(OVERHEAD_DASH.to_vec()),
|
||||
3 => Some(vec![0.04, 0.08]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `openingLabel` (für `object_name`).
|
||||
pub fn opening_label(o: &Opening) -> String {
|
||||
format!("{} {}×{}", if o.kind == ElementKind::Door { "Tür" } else { "Fenster" }, to_fixed(o.width * 100.0, 0), to_fixed(o.height * 100.0, 0))
|
||||
}
|
||||
|
||||
fn wall_type<'a>(p: &'a Project, w: &Wall) -> Result<&'a WallType, String> {
|
||||
p.wall_type(w).ok_or_else(|| format!("Unbekannter Wandtyp: {}", w.wall_type_id))
|
||||
}
|
||||
|
||||
/// Verschneidung der gezeichneten Wände (`computeJoins` in TS, gleicher Puffer). Fehler wie die
|
||||
/// Modell-Helfer in TS (unbekannter Wandtyp/Bauteil).
|
||||
fn plan_joins(p: &Project, walls: &[EffWall]) -> Result<Vec<WallCuts>, String> {
|
||||
let mut buf = vec![walls.len() as f64];
|
||||
let mut comp_index: HashMap<&str, usize> = HashMap::new();
|
||||
for e in walls {
|
||||
let w = e.w;
|
||||
buf.extend([w.start.x, w.start.y, w.end.x, w.end.y]);
|
||||
match (w.reference_offset, w.reference_line) {
|
||||
(Some(v), _) => buf.extend([3.0, v]),
|
||||
(None, Some(WallReferenceLine::Left)) => buf.extend([1.0, 0.0]),
|
||||
(None, Some(WallReferenceLine::Right)) => buf.extend([2.0, 0.0]),
|
||||
_ => buf.extend([0.0, 0.0]),
|
||||
}
|
||||
let Some(wt) = p.wall_type(w) else {
|
||||
buf.extend([0.0, 0.0]);
|
||||
continue;
|
||||
};
|
||||
buf.extend([1.0, wt.layers.len() as f64]);
|
||||
for l in &wt.layers {
|
||||
let comp = p.component(&l.component_id);
|
||||
let idx = match comp {
|
||||
Some(c) => {
|
||||
let n = comp_index.len();
|
||||
*comp_index.entry(c.id.as_str()).or_insert(n) as f64
|
||||
}
|
||||
None => -1.0,
|
||||
};
|
||||
buf.extend([l.thickness, idx, comp.map_or(f64::NAN, |c| c.join_priority)]);
|
||||
}
|
||||
}
|
||||
let out = joins::compute_joins_flat(&buf);
|
||||
if out.first() == Some(&1.0) {
|
||||
let bad = out.get(1).and_then(|i| walls.get(*i as usize));
|
||||
if let Some(e) = bad {
|
||||
for l in &wall_type(p, e.w)?.layers {
|
||||
p.component(&l.component_id).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {}", l.component_id))?;
|
||||
}
|
||||
}
|
||||
return Err("computeJoins: unbekannter Wandtyp oder Bauteil".into());
|
||||
}
|
||||
if out.first() != Some(&0.0) {
|
||||
return Ok(vec![WallCuts::default(); walls.len()]);
|
||||
}
|
||||
let mut r = crate::flat_read::Reader::new(&out[1..]);
|
||||
let mut cuts = Vec::with_capacity(walls.len());
|
||||
for _ in walls {
|
||||
cuts.push(joins::decode_cuts(&mut r).unwrap_or_default());
|
||||
}
|
||||
Ok(cuts)
|
||||
}
|
||||
|
||||
/// Wand mit angewandten Override-Regeln (Farbe → Umriss/Fugen, Strichstärke).
|
||||
struct EffWall<'a> {
|
||||
w: &'a Wall,
|
||||
color: Option<String>,
|
||||
stroke_weight: Option<f64>,
|
||||
}
|
||||
|
||||
/// `wallTypeThickness` (Summe ab 0 wie `reduce` in TS).
|
||||
fn thickness(layers: &[Layer]) -> f64 {
|
||||
layers.iter().fold(0.0, |s, l| s + l.thickness)
|
||||
}
|
||||
|
||||
fn line_buf(out: &mut Vec<f64>, l: Option<&joins::Line>) {
|
||||
match l {
|
||||
Some(l) => out.extend([1.0, l.point.x, l.point.y, l.dir.x, l.dir.y]),
|
||||
None => out.extend([0.0; 5]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Eingabe von `plan_walls::wall_poche` (wie `encodeWallPoche` in TS).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn encode_wall_poche(w: &Wall, layers: &[f64], total: f64, ref_off: f64, gaps: &[(f64, f64)], cuts: &WallCuts, grob: bool, view_only: bool) -> Vec<f64> {
|
||||
let mut b = vec![w.start.x, w.start.y, w.end.x, w.end.y, total, ref_off, if grob { 1.0 } else { 0.0 }, if view_only { 1.0 } else { 0.0 }];
|
||||
b.push(layers.len() as f64);
|
||||
b.extend_from_slice(layers);
|
||||
line_buf(&mut b, cuts.start_cut.as_ref());
|
||||
line_buf(&mut b, cuts.end_cut.as_ref());
|
||||
match &cuts.layer_cuts {
|
||||
Some(lc) => {
|
||||
b.push(1.0);
|
||||
let at = |v: &Vec<Option<joins::Line>>, i: usize| v.get(i).copied().flatten();
|
||||
for i in 0..layers.len() {
|
||||
line_buf(&mut b, at(&lc.start, i).as_ref());
|
||||
line_buf(&mut b, at(&lc.end, i).as_ref());
|
||||
line_buf(&mut b, at(&lc.start_side, i).as_ref());
|
||||
line_buf(&mut b, at(&lc.end_side, i).as_ref());
|
||||
}
|
||||
}
|
||||
None => b.push(0.0),
|
||||
}
|
||||
b.push(cuts.span_cutouts.len() as f64);
|
||||
for c in &cuts.span_cutouts {
|
||||
b.extend([c.from, c.to, c.off_a, c.off_b]);
|
||||
}
|
||||
b.push(gaps.len() as f64);
|
||||
for g in gaps {
|
||||
b.extend([g.0, g.1]);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn wall_polygon(pts: Vec<Vec2>, fill: &str, stroke: &str, w: f64, hatch: HatchRender, greyed: bool, no_stroke_edges: Option<Vec<f64>>, wall_id: Option<&str>, opening_id: Option<&str>) -> Primitive {
|
||||
Primitive::Polygon {
|
||||
pts,
|
||||
fill: fill.into(),
|
||||
stroke: stroke.into(),
|
||||
stroke_width_mm: w,
|
||||
hatch,
|
||||
greyed: Some(greyed),
|
||||
opacity: None,
|
||||
no_stroke_edges,
|
||||
wall_id: wall_id.map(String::from),
|
||||
drawing_id: None,
|
||||
ceiling_id: None,
|
||||
opening_id: opening_id.map(String::from),
|
||||
stair_id: None,
|
||||
room_id: None,
|
||||
extruded_solid_id: None,
|
||||
context_object_id: None,
|
||||
column_id: None,
|
||||
roof_id: None,
|
||||
section_line_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn mk_line(a: Vec2, b: Vec2, cls: &str, w: f64, dash: super::prim::Dash, color: Option<&str>, greyed: bool, opening_id: Option<&str>) -> Primitive {
|
||||
Primitive::Line { a, b, cls: cls.into(), weight_mm: w, dash, zigzag: None, motif: None, color: color.map(String::from), drawing_id: None, opening_id: opening_id.map(String::from), stair_id: None, greyed: Some(greyed), opacity: None }
|
||||
}
|
||||
|
||||
fn v2(x: f64, y: f64) -> Vec2 {
|
||||
Vec2 { x, y }
|
||||
}
|
||||
|
||||
/// Wand-Poché (`addWallPoche`).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn wall_poche(c: &Ctx, out: &mut Vec<Primitive>, e: &EffWall, gaps: &[(f64, f64)], cuts: &WallCuts, greyed: bool, wall_lw: f64, category: Option<&LayerCategory>, view_only: bool) -> Result<(), String> {
|
||||
let p = c.p;
|
||||
let w = e.w;
|
||||
let detail = c.a.detail;
|
||||
let wt = wall_type(p, w)?;
|
||||
let total = thickness(&wt.layers);
|
||||
let ref_off = joins::reference_offset(crate::model3d::wall_reference(w), total);
|
||||
let angle = atan2(w.end.y - w.start.y, w.end.x - w.start.x) * 180.0 / std::f64::consts::PI;
|
||||
let stroke = e.color.as_deref().unwrap_or(POCHE_STROKE);
|
||||
let outline_mm = wall_lw * detail.outline_factor();
|
||||
let layer_mm = LAYER_LINE_MM * detail.layer_factor();
|
||||
let thick: Vec<f64> = wt.layers.iter().map(|l| l.thickness).collect();
|
||||
let f = crate::plan_walls::wall_poche(&encode_wall_poche(w, &thick, total, ref_off, gaps, cuts, detail == Detail::Grob, view_only));
|
||||
if f.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut styles: HashMap<usize, (HatchRender, String)> = HashMap::new();
|
||||
let mut style_of = |li: usize| -> Result<(HatchRender, String), String> {
|
||||
if let Some(s) = styles.get(&li) {
|
||||
return Ok(s.clone());
|
||||
}
|
||||
let layer = wt.layers.get(li).ok_or("Schicht fehlt")?;
|
||||
let comp = p.component(&layer.component_id).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {}", layer.component_id))?;
|
||||
let hid = resolve_hatch_id(w.hatch_id.as_deref(), w.hatch_source, category, Some(&comp.hatch_id)).unwrap_or(&comp.hatch_id);
|
||||
let hatch = super::domains::resolve_hatch_or_err(p, hid, Some(angle), resolve_foreground(comp, w.foreground.as_deref(), category, w.foreground_source))?;
|
||||
let bg = resolve_background(comp, w.background.as_deref(), category, w.background_source);
|
||||
let fill = bg.unwrap_or(if hatch.pattern == HatchPattern::Solid { HATCH_INK } else { HATCH_PAPER }).to_string();
|
||||
styles.insert(li, (hatch.clone(), fill.clone()));
|
||||
Ok((hatch, fill))
|
||||
};
|
||||
let n = f[0] as usize;
|
||||
let mut i = 1;
|
||||
for _ in 0..n {
|
||||
if f[i] == 1.0 {
|
||||
let art = f[i + 1];
|
||||
let li = f[i + 2] as usize;
|
||||
let n_no = f[i + 3] as usize;
|
||||
let no_stroke = f[i + 4..i + 4 + n_no].to_vec();
|
||||
let q = i + 4 + n_no;
|
||||
let pts: Vec<Vec2> = (0..4).map(|j| v2(f[q + 2 * j], f[q + 2 * j + 1])).collect();
|
||||
i = q + 8;
|
||||
if art == 2.0 {
|
||||
let (hatch, fill) = style_of(li)?;
|
||||
out.push(wall_polygon(pts, &fill, "none", 0.0, hatch, greyed, Some(no_stroke), Some(&w.id), None));
|
||||
} else {
|
||||
let fill = if art == 1.0 { HATCH_INK } else { "none" };
|
||||
let sw = if art == 0.0 { layer_mm } else { outline_mm };
|
||||
out.push(wall_polygon(pts, fill, stroke, sw, no_hatch(), greyed, Some(no_stroke), Some(&w.id), None));
|
||||
}
|
||||
} else {
|
||||
let art = f[i + 1];
|
||||
let li = f[i + 2] as usize;
|
||||
let a = v2(f[i + 3], f[i + 4]);
|
||||
let b = v2(f[i + 5], f[i + 6]);
|
||||
i += 7;
|
||||
if art == 0.0 {
|
||||
out.push(mk_line(a, b, "layer-joint-l", layer_mm, None, Some(stroke), greyed, None));
|
||||
} else if art == 1.0 {
|
||||
let jls = wt.layers.get(li).and_then(|l| l.joint_line_style_id.as_deref()).filter(|s| !s.is_empty()).and_then(|id| p.line_style(id));
|
||||
let mut l = mk_line(
|
||||
a,
|
||||
b,
|
||||
"layer-joint",
|
||||
jls.map_or(layer_mm, |s| s.weight * detail.layer_factor()),
|
||||
Some(jls.and_then(|s| s.dash.clone())),
|
||||
Some(jls.map_or(stroke, |s| s.color.as_str())),
|
||||
greyed,
|
||||
None,
|
||||
);
|
||||
if let (Primitive::Line { zigzag, motif, .. }, Some(s)) = (&mut l, jls) {
|
||||
if s.kind == Some(LineStyleKind::Zigzag) {
|
||||
*zigzag = s.zigzag.clone();
|
||||
}
|
||||
if s.kind == Some(LineStyleKind::Custom) {
|
||||
*motif = s.motif.clone();
|
||||
}
|
||||
}
|
||||
out.push(l);
|
||||
} else {
|
||||
out.push(mk_line(a, b, "wall-outline", outline_mm, None, Some(stroke), greyed, None));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sashes eines Fenstertyps (`sashesOfWindowType`): fehlend → aus `wingCount` gleichmässig.
|
||||
fn sashes(wt: &WindowType) -> Vec<SashDef> {
|
||||
if let Some(s) = wt.sashes.as_ref().filter(|s| !s.is_empty()) {
|
||||
return s.clone();
|
||||
}
|
||||
let wc = if wt.wing_count == 0.0 || wt.wing_count.is_nan() { 1.0 } else { wt.wing_count };
|
||||
let n = crate::jsnum::max(1.0, round(wc)) as usize;
|
||||
let opening = if wt.kind == OpeningKind::Fest { OpeningKind::Fest } else { wt.kind };
|
||||
(0..n).map(|i| SashDef { kind: SashDefKind::Fluegel, auto_width: Some(true), opening: Some(opening), hinge_side: Some(if i % 2 == 0 { SashDefHingeSide::Left } else { SashDefHingeSide::Right }), ..Default::default() }).collect()
|
||||
}
|
||||
|
||||
fn door_type<'a>(p: &'a Project, o: &Opening) -> Option<&'a DoorType> {
|
||||
let id = o.type_id.as_deref().filter(|s| !s.is_empty())?;
|
||||
p.door_types.as_deref()?.iter().find(|t| t.id == id)
|
||||
}
|
||||
|
||||
fn window_type<'a>(p: &'a Project, o: &Opening) -> Option<&'a WindowType> {
|
||||
let id = o.type_id.as_deref().filter(|s| !s.is_empty())?;
|
||||
p.window_types.as_deref()?.iter().find(|t| t.id == id)
|
||||
}
|
||||
|
||||
/// Öffnungs-Symbol (`addOpeningSymbol`).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn opening_symbol(c: &Ctx, out: &mut Vec<Primitive>, w: &Wall, o: &Opening, color: Option<&str>, greyed: bool, detail: Detail, lw: f64) -> Result<(), String> {
|
||||
let p = c.p;
|
||||
let total = thickness(&wall_type(p, w)?.layers);
|
||||
let ref_off = joins::reference_offset(crate::model3d::wall_reference(w), total);
|
||||
let door = o.kind == ElementKind::Door;
|
||||
let wt = if door { None } else { window_type(p, o) };
|
||||
// Rahmenband nur bei Türen mit Typ (Fenster zeichnen es selbst).
|
||||
let dt = if door { door_type(p, o) } else { None };
|
||||
let sash_list = wt.map(sashes).unwrap_or_default();
|
||||
let stroke = color.unwrap_or(POCHE_STROKE);
|
||||
let frame_color = o.frame_line.as_ref().and_then(|l| l.color.as_deref()).unwrap_or(stroke);
|
||||
let frame_weight = o.frame_line.as_ref().and_then(|l| l.weight).unwrap_or(lw);
|
||||
let frame_view_weight = o.frame_view_line.as_ref().and_then(|l| l.weight).unwrap_or(frame_weight);
|
||||
let colors = [
|
||||
"",
|
||||
stroke,
|
||||
frame_color,
|
||||
o.frame_view_line.as_ref().and_then(|l| l.color.as_deref()).unwrap_or(frame_color),
|
||||
o.sash_line.as_ref().and_then(|l| l.color.as_deref()).unwrap_or(stroke),
|
||||
o.sill_line_style.as_ref().and_then(|l| l.color.as_deref()).unwrap_or(stroke),
|
||||
];
|
||||
let b01 = |b: bool| if b { 1.0 } else { 0.0 };
|
||||
let detail_code = match detail {
|
||||
Detail::Grob => 0.0,
|
||||
Detail::Mittel => 1.0,
|
||||
Detail::Fein => 2.0,
|
||||
};
|
||||
let mut b: Vec<f64> = vec![w.start.x, w.start.y, w.end.x, w.end.y, total, ref_off, o.position, o.width, b01(door), detail_code];
|
||||
// Tür
|
||||
b.push(b01(o.swing.is_some_and(|s| s != SwingSide::Left)));
|
||||
b.push(b01(o.opening_dir.is_some_and(|s| s != OpeningOpeningDir::In)));
|
||||
b.push(b01(o.hinge.is_some_and(|s| s != OpeningHinge::Start)));
|
||||
b.push(o.swing_angle.unwrap_or(f64::NAN));
|
||||
b.push(b01(o.door_type == Some(OpeningDoorType::Wandoeffnung)));
|
||||
b.push(if door { crate::jsnum::max(1.0, round(door_type(p, o).map_or(1.0, |t| t.leaf_count))) } else { 1.0 });
|
||||
b.push(match o.lintel_lines.unwrap_or(OpeningLintelLines::Beide) {
|
||||
OpeningLintelLines::Keine => 0.0,
|
||||
OpeningLintelLines::Aussen => 1.0,
|
||||
OpeningLintelLines::Innen => 2.0,
|
||||
OpeningLintelLines::Beide => 3.0,
|
||||
OpeningLintelLines::Unknown => f64::NAN,
|
||||
});
|
||||
// Rahmenband (Tür mit Typ)
|
||||
match dt {
|
||||
Some(t) => b.extend([
|
||||
1.0,
|
||||
t.frame_width.unwrap_or(0.06),
|
||||
b01(t.frame_kind == Some(DoorTypeFrameKind::Blockrahmen)),
|
||||
t.inset_from_face.unwrap_or(0.0),
|
||||
b01(t.inset_face == Some(DoorTypeInsetFace::Innen)),
|
||||
]),
|
||||
None => b.extend([0.0, 0.0, 0.0, 0.0, 0.0]),
|
||||
}
|
||||
// Fenster
|
||||
b.push(b01(wt.is_some()));
|
||||
b.push(wt.map_or(0.0, |t| t.frame_width.unwrap_or(0.06)));
|
||||
b.push(wt.and_then(|t| t.frame_depth).unwrap_or(f64::NAN));
|
||||
b.push(wt.and_then(|t| t.inset_from_face).unwrap_or(f64::NAN));
|
||||
b.push(b01(wt.and_then(|t| t.inset_face) == Some(WindowTypeInsetFace::Innen)));
|
||||
b.push(o.wing_count.unwrap_or(f64::NAN));
|
||||
b.push(if detail == Detail::Fein { 2.0 } else { 1.0 });
|
||||
let sill = wt.and_then(|t| t.sill_line.as_ref());
|
||||
b.push(sill.map_or(0.0, |s| match s.faces {
|
||||
WindowTypeSillLineFaces::Aussen => 1.0,
|
||||
WindowTypeSillLineFaces::Innen => 2.0,
|
||||
WindowTypeSillLineFaces::Beide => 3.0,
|
||||
WindowTypeSillLineFaces::Unknown => f64::NAN,
|
||||
}));
|
||||
b.push(b01(sill.is_some_and(|s| s.view == WindowTypeSillLineView::Unter)));
|
||||
let shading = wt.and_then(|t| t.shading.as_ref());
|
||||
b.push(b01(shading.is_some_and(|s| s.create)));
|
||||
b.push(shading.map_or(0.0, |s| s.r#box.width));
|
||||
b.push(shading.map_or(0.0, |s| s.r#box.height));
|
||||
// Strichstärken
|
||||
b.push(SYMBOL_HAIRLINE_MM);
|
||||
b.push(o.frame_line.as_ref().and_then(|l| l.weight).unwrap_or(SYMBOL_HAIRLINE_MM));
|
||||
b.push(frame_view_weight);
|
||||
b.push(o.sash_line.as_ref().and_then(|l| l.weight).unwrap_or(SYMBOL_HAIRLINE_MM));
|
||||
b.push(o.sill_line_style.as_ref().and_then(|l| l.weight).unwrap_or(SYMBOL_HAIRLINE_MM));
|
||||
b.push(sash_list.len() as f64);
|
||||
for s in &sash_list {
|
||||
b.extend([
|
||||
b01(s.kind == SashDefKind::Pfosten),
|
||||
if s.auto_width == Some(false) { 0.0 } else { 1.0 },
|
||||
s.width.unwrap_or(f64::NAN),
|
||||
s.post_width.unwrap_or(f64::NAN),
|
||||
b01(s.opening.is_some_and(|k| k != OpeningKind::Fest)),
|
||||
]);
|
||||
}
|
||||
let f = crate::plan_openings::plan_opening(&b);
|
||||
if f.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let id = Some(o.id.as_str());
|
||||
let slot = |k: f64| colors.get(k as usize).copied().unwrap_or("");
|
||||
let n = f[0] as usize;
|
||||
let mut i = 1;
|
||||
for _ in 0..n {
|
||||
if f[i] == 1.0 {
|
||||
let count = f[i + 4] as usize;
|
||||
let pts: Vec<Vec2> = (0..count).map(|j| v2(f[i + 5 + 2 * j], f[i + 6 + 2 * j])).collect();
|
||||
let frame = f[i + 1] == 1.0;
|
||||
out.push(wall_polygon(pts, "none", if frame { slot(f[i + 3]) } else { "none" }, f[i + 2], no_hatch(), greyed, None, None, id));
|
||||
i += 5 + 2 * count;
|
||||
} else if f[i] == 2.0 {
|
||||
let s = f[i + 3];
|
||||
let cls = LINE_CLS.get(f[i + 1] as usize).copied().unwrap_or("");
|
||||
out.push(mk_line(v2(f[i + 5], f[i + 6]), v2(f[i + 7], f[i + 8]), cls, f[i + 2], dash_of(f[i + 4]).map(Some), (s != 0.0).then(|| slot(s)), greyed, id));
|
||||
i += 9;
|
||||
} else {
|
||||
out.push(Primitive::Arc {
|
||||
center: v2(f[i + 2], f[i + 3]),
|
||||
from: v2(f[i + 4], f[i + 5]),
|
||||
to: v2(f[i + 6], f[i + 7]),
|
||||
r: f[i + 8],
|
||||
cls: "door-swing".into(),
|
||||
weight_mm: f[i + 1],
|
||||
dash: None,
|
||||
opening_id: Some(o.id.clone()),
|
||||
stair_id: None,
|
||||
greyed: Some(greyed),
|
||||
opacity: None,
|
||||
});
|
||||
i += 9;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Wände (Poché, Referenzlinie) und ihre Öffnungs-Symbole in Zeichenreihenfolge, dazu das Ausmass
|
||||
/// der Wand-Ecken (`computeBounds`).
|
||||
pub fn plan_walls(c: &Ctx, reference_lines: bool, out: &mut Vec<Primitive>, bounds: &mut super::domains::Bounds) -> Result<(), String> {
|
||||
let p = c.p;
|
||||
let type_names: HashMap<&str, &str> = p.wall_types.iter().map(|t| (t.id.as_str(), t.name.as_str())).collect();
|
||||
let walls: Vec<EffWall> = p
|
||||
.walls
|
||||
.iter()
|
||||
.filter(|w| w.floor_id == c.a.floor && c.shown(&w.category_code))
|
||||
.map(|w| {
|
||||
let ov = c.overrides(&w.category_code, type_names.get(w.wall_type_id.as_str()).copied());
|
||||
EffWall { w, color: ov.color.or_else(|| w.color.clone()), stroke_weight: ov.lineweight.or(w.stroke_weight) }
|
||||
})
|
||||
.collect();
|
||||
let cuts = plan_joins(p, &walls)?;
|
||||
let floor = p.floor(&c.a.floor);
|
||||
let cut_z = floor.and_then(|f| f.base_elevation).unwrap_or(0.0) + floor.and_then(|f| f.cut_height).unwrap_or(1.0);
|
||||
// Bei doppelten Wand-ids gewinnt in TS (Map) die letzte Verschneidung.
|
||||
let mut cut_by_id: HashMap<&str, &WallCuts> = HashMap::new();
|
||||
for (e, k) in walls.iter().zip(&cuts) {
|
||||
cut_by_id.insert(e.w.id.as_str(), k);
|
||||
}
|
||||
for e in &walls {
|
||||
let w = e.w;
|
||||
bounds_wall(p, w, bounds);
|
||||
let greyed = c.greyed(&w.category_code);
|
||||
let category = c.cat(&w.category_code);
|
||||
let lw = resolve_stroke_weight(e.stroke_weight, w.stroke_weight_source, category, category.map_or(WALL_FALLBACK_MM, |k| k.lw));
|
||||
let openings: Vec<&Opening> = p.openings_of_wall(&w.id).collect();
|
||||
let wr_total = p.wall_thickness(w, 0.2);
|
||||
let wr = crate::opening_geom::WallRef {
|
||||
start: crate::opening_geom::v(w.start.x, w.start.y),
|
||||
end: crate::opening_geom::v(w.end.x, w.end.y),
|
||||
total: wr_total,
|
||||
ref_off: joins::reference_offset(crate::model3d::wall_reference(w), wr_total),
|
||||
};
|
||||
let mut gaps: Vec<(f64, f64)> = openings.iter().filter_map(|o| crate::opening_geom::opening_interval(&wr, o.position, o.width)).collect();
|
||||
gaps.sort_by(|a, b| (a.0 - b.0).partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal));
|
||||
let empty = WallCuts::default();
|
||||
let cut = cut_by_id.get(w.id.as_str()).copied().unwrap_or(&empty);
|
||||
let (zb, zt) = p.wall_vertical_extent(w);
|
||||
let view_only = zt < cut_z || zb > cut_z;
|
||||
wall_poche(c, out, e, &gaps, cut, greyed, lw, category, view_only)?;
|
||||
if reference_lines {
|
||||
out.push(mk_line(w.start, w.end, "wall-axis", 0.13, Some(Some(vec![0.18, 0.06, 0.04, 0.06])), None, greyed, None));
|
||||
}
|
||||
for o in openings {
|
||||
if !c.shown(&o.category_code) {
|
||||
continue;
|
||||
}
|
||||
let ov = c.overrides(&o.category_code, Some(&opening_label(o)));
|
||||
let olw = ov.lineweight.unwrap_or_else(|| c.cat(&o.category_code).map_or(LAYER_LINE_MM, |k| k.lw));
|
||||
let color = ov.color.as_deref().or(o.color.as_deref());
|
||||
let detail = match o.detail_level {
|
||||
Some(DetailLevel::Grob) => Detail::Grob,
|
||||
Some(DetailLevel::Mittel) => Detail::Mittel,
|
||||
Some(DetailLevel::Fein) => Detail::Fein,
|
||||
_ => c.a.detail,
|
||||
};
|
||||
opening_symbol(c, out, w, o, color, c.greyed(&o.category_code), detail, olw)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Wand-Ecken (`wallCorners` mit Typ-Dicke) ins Ausmass.
|
||||
fn bounds_wall(p: &Project, w: &Wall, bounds: &mut super::domains::Bounds) {
|
||||
let Some(wt) = p.wall_type(w) else { return };
|
||||
let h = thickness(&wt.layers) / 2.0;
|
||||
let (dx, dy) = (w.end.x - w.start.x, w.end.y - w.start.y);
|
||||
let l = crate::jsmath::hypot2(dx, dy);
|
||||
let l = if l == 0.0 || l.is_nan() { 1.0 } else { l };
|
||||
let (ux, uy) = (dx / l, dy / l);
|
||||
let (nx, ny) = (-uy, ux);
|
||||
for (q, off) in [(w.start, h), (w.end, h), (w.end, -h), (w.start, -h)] {
|
||||
bounds.acc(q.x + nx * off, q.y + ny * off);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Öffnungs-Symbol (Tür/Fenster) im Grundriss ([K3a]): Port von `generatePlan/openings.ts`
|
||||
//! (`addOpeningSymbol`, `addOpeningFrameBand`). Geometrie aus `opening_geom.rs`. Stil löst TS aus dem
|
||||
//! (`addOpeningSymbol`, `addOpeningFrameBand`). Geometrie aus `opening_geom.rs`. Stil löst `plan/walls.rs` aus dem
|
||||
//! Modell: Strichstärken kommen als Zahlen herein, Farben als Platz (Slot) heraus (0 = keine,
|
||||
//! 1 Strichfarbe, 2 Rahmen, 3 Rahmen-Aufsicht, 4 Flügel/Sprossen, 5 Fensterbank-/Sims-Linie).
|
||||
//!
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Treppen-Symbol im Grundriss ([K3a]): Tritte, Lauflinie, Pfeil, Podest, SIA-Bruchlinie und
|
||||
//! Aussenlinie als flache Primitivliste. Port von `src/plan/generatePlan/stairs.ts`; die Geometrie
|
||||
//! kommt aus `kernel2d` (`stair_geometry`, `stair_cut`, `stair_outline`), Farbe, Pick-ID und
|
||||
//! Graustufen setzt der Aufrufer.
|
||||
//! Graustufen setzt der Aufrufer (`plan/stairs.rs`, [K3d]).
|
||||
//!
|
||||
//! Eingabe: Treppen-Parameter (16 Zahlen, s. `stair.rs`), Gesamt-Steighöhe, Schnitthöhe über der
|
||||
//! Treppen-UK, Strichstärke `lw_mm` (Papier-mm), `filled_arrow` (0/1).
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Wand-Poché und Decken-Umriss im Grundriss ([K3a]): die Geometrie von `generatePlan/walls.ts`
|
||||
//! Wand-Poché und Decken-Umriss im Grundriss ([K3a]): die Geometrie der früheren `generatePlan/walls.ts`
|
||||
//! und `ceilings.ts` (Segmente zwischen Öffnungen, Gehrungsbänder, Schichtfugen, Durchgangswand-
|
||||
//! Aussparungen, Verdeckung von Decken-Umrissen durch Wand-Footprints). Stil (Bauteil, Schraffur,
|
||||
//! Farbe, Strichstärke, Linienstil der Fuge) löst TS aus dem Modell auf und ordnet ihn über den
|
||||
//! Schichtindex zu — das Modell bleibt bis [K4] in TS.
|
||||
//! Farbe, Strichstärke, Linienstil der Fuge) löst `plan/walls.rs` auf dem Dokument auf und ordnet
|
||||
//! ihn über den Schichtindex zu ([K3d]).
|
||||
//!
|
||||
//! Rechenreihenfolge und Zahlsemantik wie in TS (`Math.hypot` über `jsmath`, `Math.min/max` über
|
||||
//! `jsnum`), damit die Ausgabe bitgleich bleibt.
|
||||
@@ -22,8 +22,8 @@
|
||||
//! ```
|
||||
//!
|
||||
//! ## Decken-Umriss
|
||||
//! Eingabe `[nRing, x, y …, nBruecken, kante…, nFootprints, (ax, ay, ux, uy, mx, my, len, half,
|
||||
//! refOff)×n]`; Ausgabe `[n, ax, ay, bx, by …]` (freie Teilstücke der Umrisskanten).
|
||||
//! [`ceiling_outline_lines`]: freie Teilstücke der Umrisskanten gegen die Wand-Footprints; Aufrufer
|
||||
//! ist die Decken-Domäne auf dem Dokument (`plan/domains.rs`, [K3d]).
|
||||
|
||||
use crate::flat_read::Reader;
|
||||
use crate::jsmath::hypot2;
|
||||
@@ -164,44 +164,50 @@ fn segment_inside(pa: V, pb: V, fp: &Footprint) -> Option<(f64, f64)> {
|
||||
|
||||
// ── Decken-Umriss ───────────────────────────────────────────────────────────
|
||||
|
||||
pub fn ceiling_outline(buf: &[f64]) -> Vec<f64> {
|
||||
(|| {
|
||||
let mut r = Reader::new(buf);
|
||||
let ring: Vec<V> = r.ring()?.into_iter().map(|p| v(p[0], p[1])).collect();
|
||||
let n_bridge = r.count()?;
|
||||
let mut bridge = Vec::with_capacity(n_bridge);
|
||||
for _ in 0..n_bridge {
|
||||
bridge.push(r.num()?);
|
||||
/// Wand-Footprint (OBB) für das Verdecken von Decken-Umrissen (`buildWallFootprints` in TS).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct WallFootprint {
|
||||
pub a: [f64; 2],
|
||||
pub u: [f64; 2],
|
||||
pub m: [f64; 2],
|
||||
pub len: f64,
|
||||
pub half: f64,
|
||||
pub ref_off: f64,
|
||||
}
|
||||
|
||||
/// Footprint einer Wand aus Achse, Dicke und Referenz-Querversatz.
|
||||
pub fn wall_footprint(start: [f64; 2], end: [f64; 2], thickness: f64, ref_off: f64) -> WallFootprint {
|
||||
let (s, e) = (v(start[0], start[1]), v(end[0], end[1]));
|
||||
let u = normalize(sub(e, s));
|
||||
let m = left_normal(u);
|
||||
WallFootprint { a: start, u: [u.x, u.y], m: [m.x, m.y], len: hypot2(e.x - s.x, e.y - s.y), half: thickness / 2.0, ref_off }
|
||||
}
|
||||
|
||||
/// Freie Teilstücke der Umrisskanten eines Decken-Rings (ohne Brückenkanten), die nicht unter einem
|
||||
/// Wand-Footprint liegen.
|
||||
pub fn ceiling_outline_lines(ring: &[[f64; 2]], bridge: &[usize], fps: &[WallFootprint]) -> Vec<[[f64; 2]; 2]> {
|
||||
let fps: Vec<Footprint> = fps
|
||||
.iter()
|
||||
.map(|f| Footprint { a: v(f.a[0], f.a[1]), u: v(f.u[0], f.u[1]), m: v(f.m[0], f.m[1]), len: f.len, half: f.half, ref_off: f.ref_off })
|
||||
.collect();
|
||||
let ring: Vec<V> = ring.iter().map(|p| v(p[0], p[1])).collect();
|
||||
let n = ring.len();
|
||||
let mut out = Vec::new();
|
||||
for i in 0..n {
|
||||
if bridge.contains(&i) {
|
||||
continue;
|
||||
}
|
||||
let n_fp = r.count()?;
|
||||
let mut fps = Vec::with_capacity(n_fp);
|
||||
for _ in 0..n_fp {
|
||||
let a = [r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?];
|
||||
fps.push(Footprint { a: v(a[0], a[1]), u: v(a[2], a[3]), m: v(a[4], a[5]), len: a[6], half: a[7], ref_off: a[8] });
|
||||
let a = ring[i];
|
||||
let b = ring[(i + 1) % n];
|
||||
let holes: Vec<(f64, f64)> = fps.iter().filter_map(|fp| segment_inside(a, b, fp)).collect();
|
||||
let d = sub(b, a);
|
||||
for (t0, t1) in subtract_intervals(0.0, 1.0, &holes) {
|
||||
let p = add(a, scale(d, t0));
|
||||
let q = add(a, scale(d, t1));
|
||||
out.push([[p.x, p.y], [q.x, q.y]]);
|
||||
}
|
||||
let n = ring.len();
|
||||
let mut lines: Vec<f64> = Vec::new();
|
||||
let mut count = 0usize;
|
||||
for i in 0..n {
|
||||
if bridge.contains(&(i as f64)) {
|
||||
continue;
|
||||
}
|
||||
let a = ring[i];
|
||||
let b = ring[(i + 1) % n];
|
||||
let holes: Vec<(f64, f64)> = fps.iter().filter_map(|fp| segment_inside(a, b, fp)).collect();
|
||||
let d = sub(b, a);
|
||||
for (t0, t1) in subtract_intervals(0.0, 1.0, &holes) {
|
||||
let p = add(a, scale(d, t0));
|
||||
let q = add(a, scale(d, t1));
|
||||
lines.extend([p.x, p.y, q.x, q.y]);
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
let mut out = vec![count as f64];
|
||||
out.extend(lines);
|
||||
Some(out)
|
||||
})()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ── Wand-Poché ──────────────────────────────────────────────────────────────
|
||||
@@ -513,15 +519,17 @@ mod tests {
|
||||
let mut b = wall(4.0, false, &[]);
|
||||
b[0] = f64::NAN;
|
||||
assert!(wall_poche(&b).is_empty());
|
||||
assert!(ceiling_outline(&[3.0, 0.0]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decken_umriss_wird_von_wand_verdeckt() {
|
||||
// Quadrat 4×4, Wand entlang der unteren Kante (Mitte y=0, Dicke 0.4)
|
||||
let mut b = vec![4.0, 0.0, 0.0, 4.0, 0.0, 4.0, 4.0, 0.0, 4.0, 0.0, 1.0];
|
||||
b.extend([0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 4.0, 0.2, 0.0]);
|
||||
let o = ceiling_outline(&b);
|
||||
assert_eq!(o[0], 3.0); // untere Kante entfällt, drei freie Kanten
|
||||
let ring = [[0.0, 0.0], [4.0, 0.0], [4.0, 4.0], [0.0, 4.0]];
|
||||
let fp = wall_footprint([0.0, 0.0], [4.0, 0.0], 0.4, 0.0);
|
||||
assert_eq!(fp, WallFootprint { a: [0.0, 0.0], u: [1.0, 0.0], m: [0.0, 1.0], len: 4.0, half: 0.2, ref_off: 0.0 });
|
||||
let o = ceiling_outline_lines(&ring, &[], &[fp]);
|
||||
assert_eq!(o.len(), 3); // untere Kante entfällt, drei freie Kanten
|
||||
// Brückenkanten werden nie gestrichen.
|
||||
assert_eq!(ceiling_outline_lines(&ring, &[1], &[fp]).len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
|
||||
("scheduleRows", _) => json(&export_schedule::schedule_rows(p)),
|
||||
("scheduleCsv", 1) => Ok(export_schedule::export_schedule_csv(p, text, args[0] != 0.0)),
|
||||
("pickGeometry", _) => json(&model3d::pick_geometry(p)?),
|
||||
("planDomains", 1) => json(&crate::plan::domains::plan_domains(p, &crate::plan::domains::PlanArgs::parse(args[0], text)?)?),
|
||||
("model3dParts", 3) => json(&model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?),
|
||||
_ => Err(format!("Unbekannte Abfrage: {name}")),
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
//! Bindungen der Wand-Verschneidung (`crate::joins`). Kodierung s. dort.
|
||||
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
/// Wände flach → `[0, (Cuts je Wand)…]`; `[1, wandIndex]` = Wandtyp/Bauteil unbekannt;
|
||||
/// kaputte Eingabe → leer.
|
||||
#[wasm_bindgen]
|
||||
pub fn compute_joins_flat(walls: &[f64]) -> Vec<f64> {
|
||||
crate::joins::compute_joins_flat(walls)
|
||||
}
|
||||
|
||||
/// Verschneidungs-Entscheidung: 0 merge, 1 trim-a, 2 trim-b, 3 coexist.
|
||||
#[wasm_bindgen]
|
||||
pub fn join_priority_resolution(prio_a: f64, prio_b: f64, same_component: bool) -> u8 {
|
||||
use crate::joins::JoinResolution::*;
|
||||
match crate::joins::resolve_join_priority(prio_a, prio_b, same_component) {
|
||||
Merge => 0,
|
||||
TrimA => 1,
|
||||
TrimB => 2,
|
||||
Coexist => 3,
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,6 @@ mod auto_dimensions;
|
||||
mod kennzahlen;
|
||||
mod bulge;
|
||||
mod stair;
|
||||
mod joins;
|
||||
mod room_area;
|
||||
mod room_boundary;
|
||||
mod polygon_holes;
|
||||
@@ -21,8 +20,6 @@ mod wall_mesh_cut;
|
||||
mod plan_buf;
|
||||
mod project_format;
|
||||
mod gpu_compile;
|
||||
mod plan_stairs;
|
||||
mod plan_walls;
|
||||
mod plan_openings;
|
||||
mod delaunay;
|
||||
mod document;
|
||||
|
||||
@@ -1,25 +1,8 @@
|
||||
//! Bindungen kleiner Plan-Bausteine (`crate::plan_misc`). Layouts s. dort.
|
||||
//! Bindung der Linienenden (`crate::plan_misc`, für 2D-Zeichnungen). Kontext-Fussabdruck und
|
||||
//! Schnittführung ruft die Plan-Erzeugung im Kern direkt (`plan/context.rs`).
|
||||
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
/// Grundriss-Fussabdruck eines Meshes (Sockelkanten); Unsinn → leer.
|
||||
#[wasm_bindgen]
|
||||
pub fn context_footprint_flat(positions: &[f64], indices: &[f64]) -> Vec<f64> {
|
||||
crate::plan_misc::context_footprint(positions, indices)
|
||||
}
|
||||
|
||||
/// `[minX, minY, maxX, maxY]` der x/y-Werte eines [x,y,z…]-Arrays; leer ohne Punkte.
|
||||
#[wasm_bindgen]
|
||||
pub fn context_bbox_flat(positions: &[f64]) -> Vec<f64> {
|
||||
crate::plan_misc::bbox(positions)
|
||||
}
|
||||
|
||||
/// Schnittführungs-Symbol einer Linie; leer bei zu kurzer Linie.
|
||||
#[wasm_bindgen]
|
||||
pub fn section_line_flat(p0x: f64, p0y: f64, p1x: f64, p1y: f64, sign: f64) -> Vec<f64> {
|
||||
crate::plan_misc::section_line(p0x, p0y, p1x, p1y, sign)
|
||||
}
|
||||
|
||||
/// Linienende (Pfeil, Punkt, Schrägstrich, Quadrat); leer ohne Wirkung.
|
||||
#[wasm_bindgen]
|
||||
pub fn end_mark_flat(x: f64, y: f64, dx: f64, dy: f64, art: f64, mm: f64, scale_denominator: f64) -> Vec<f64> {
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
//! Bindungen von Öffnungs-Symbol und Fenster-Symbol (`crate::plan_openings`). Layout s. dort.
|
||||
//! Bindung des Fenster-Symbols (`crate::plan_openings`, für Schnitt/Ansicht). Layout s. dort. Das
|
||||
//! Öffnungs-Symbol im Grundriss ruft die Plan-Erzeugung im Kern direkt (`plan/walls.rs`).
|
||||
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
/// Tür-/Fenster-Symbol einer Öffnung im Grundriss; Unsinn → leer.
|
||||
#[wasm_bindgen]
|
||||
pub fn plan_opening_flat(buf: &[f64]) -> Vec<f64> {
|
||||
crate::plan_openings::plan_opening(buf)
|
||||
}
|
||||
|
||||
/// Fenster-Symbol (Rahmen, Glas, Flügel, Stulp) einer Öffnung; Unsinn/entartet → leer.
|
||||
#[wasm_bindgen]
|
||||
pub fn window_symbol_flat(buf: &[f64]) -> Vec<f64> {
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
//! Bindung des Treppen-Symbols im Grundriss (`crate::plan_stairs`). Ausgabe-Layout s. dort.
|
||||
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
/// Treppen-Parameter (16 Zahlen), Gesamt-Steighöhe, Schnitthöhe über der UK, Strichstärke (mm),
|
||||
/// gefüllter Pfeil (0/1) → Primitivliste; Unsinn → leer.
|
||||
#[wasm_bindgen]
|
||||
pub fn plan_stair_flat(params: &[f64], total_rise: f64, cut_rise: f64, lw_mm: f64, filled_arrow: f64) -> Vec<f64> {
|
||||
crate::plan_stairs::plan_stair(params, total_rise, cut_rise, lw_mm, filled_arrow != 0.0)
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
//! Bindungen von Wand-Poché und Decken-Umriss im Grundriss (`crate::plan_walls`). Layout s. dort.
|
||||
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
/// Wand-Poché-Geometrie einer Wand; Unsinn → leer.
|
||||
#[wasm_bindgen]
|
||||
pub fn plan_wall_poche_flat(buf: &[f64]) -> Vec<f64> {
|
||||
crate::plan_walls::wall_poche(buf)
|
||||
}
|
||||
|
||||
/// Freie Teilstücke eines Decken-Umrisses gegen Wand-Footprints; Unsinn → leer.
|
||||
#[wasm_bindgen]
|
||||
pub fn plan_ceiling_outline_flat(buf: &[f64]) -> Vec<f64> {
|
||||
crate::plan_walls::ceiling_outline(buf)
|
||||
}
|
||||
Reference in new issue
Block a user