//! Zeichenbefehle im Kern ([K4] S3, vorher die Objekt-Literale in `commands/cmds/*.ts` und die //! Werkzeug-Commits in `tools/tools.ts`): aus den Klickpunkten und Optionen eines Befehls entstehen hier //! die neuen Elemente (Vorgaben aus Typen/Stilen, abgeleitete Felder, ids) samt der Live-Vorschau je //! Mausschritt. Die Zustandsautomaten (Klicks, Tasten, Optionen) bleiben in der TS-Hülle. //! //! Drei Einstiege: //! - [`ops`] — Ops des Commits (`cmdOps`/`doc_cmd_commit`, Anfrage `{cmd, …, ctx, stamp}`), //! - [`preview`] — Vorschau-Formen je Mausschritt (`doc_create_preview`: Optionen als JSON, die Punkte //! flach), dazu `ok` (würde ein Commit hier etwas erzeugen?) und einige Zahlen für HUD/Zustand, //! - [`query`] — Treffer zwischen den Schritten (Host-Wand, Profil, Tangenten-Objekt …). //! //! Dazu die Gruppen-Zuordnung beim Zeichnen in einer betretenen Gruppe ([`group_ops`], vorher //! `activeGroupOps` in `state/groupActions.ts`). //! //! Zahlen wie in JS (`jsnum`, `jsmath`, `js_fmt`), Rechenreihenfolge wie die frühere TS-Fassung; //! Elemente mit der Schlüsselreihenfolge der früheren Objekt-Literale. use crate::cmd_transform::{IdGen, Shapes}; use crate::json_util::{arr, field, js_num, num_of, pt, truthy, xy}; use crate::jsmath::hypot2; use crate::jsnum; use crate::model::{LayerCategory, Project}; use crate::ops::{id_of, Op}; use kernel2d::{self as k, Vec2 as P}; use serde_json::{json, Map, Value}; pub(crate) type V = (f64, f64); /// Mindestlänge/-grösse der meisten Befehle (Modell-Meter). pub(crate) const EPS: f64 = 1e-6; /// Vorgabe-Höhe, wenn das Geschoss keine hat. const DEF_HEIGHT: f64 = 2.6; // ── Anfrage lesen ──────────────────────────────────────────────────────────── pub(crate) fn s_of<'a>(v: &'a Value, k: &str) -> &'a str { v.get(k).and_then(Value::as_str).unwrap_or("") } /// Zahl der Anfrage (fehlend = NaN, `null` = 0 wie `num_of`). pub(crate) fn n_of(v: &Value, k: &str) -> f64 { num_of(v.get(k)) } /// Optionale Zahl (`null`/fehlend = keine). pub(crate) fn opt_n(v: &Value, k: &str) -> Option { match v.get(k) { None | Some(Value::Null) => None, x => Some(num_of(x)), } } pub(crate) fn b_of(v: &Value, k: &str) -> bool { truthy(v.get(k)) } /// Punkt der Anfrage: Paar `[x, y]` oder Objekt `{x, y}` (Zustands-Punkte der Hülle unverändert). pub(crate) fn pair(x: &Value) -> V { if x.is_object() { return xy(x); } let n = |i: usize| x.get(i).map_or(f64::NAN, |c| num_of(Some(c))); (n(0), n(1)) } /// Punkt `[x, y]` der Anfrage. pub(crate) fn p_of(v: &Value, k: &str) -> V { v.get(k).map_or((f64::NAN, f64::NAN), pair) } /// Optionaler Punkt (`null`/fehlend = keiner). pub(crate) fn opt_p(v: &Value, k: &str) -> Option { match v.get(k) { None | Some(Value::Null) => None, Some(x) => Some(pair(x)), } } /// Punktliste `[[x, y], …]` der Anfrage. pub(crate) fn pts_of(v: &Value, k: &str) -> Vec { arr(v.get(k)).iter().map(pair).collect() } /// Flache Punkte `[x0, y0, …]` (Vorschau). pub(crate) fn flat_pts(f: &[f64]) -> Vec { f.chunks_exact(2).map(|c| (c[0], c[1])).collect() } /// Kontext der Hülle: aktive Ebene/Geschoss, Kategorie, Wandtyp. pub struct Ctx<'a> { pub level: &'a str, /// `level.floorHeight`, falls > 0 (sonst Vorgabe). pub floor_height: Option, pub cat: &'a str, pub wall_type: &'a str, /// Schrifthöhe neuer Texte (Modell-Meter, `textHeight` im Kontext): im Grundriss die Vorgabe /// [`DEFAULT_TEXT_HEIGHT`], auf einem Layout-Blatt (Papier 1:1) die Papierhöhe. pub text_height: f64, /// Faktor der fixen Symbolgrössen (Kote, Detailverweis, Punktmarke): 1 im Modell, auf einem /// Layout-Blatt (`sheet: true` im Kontext) `plan::drawings::SHEET_SYMBOL_FACTOR`. pub symbol: f64, } /// Schrifthöhe neuer Texte im Grundriss (Modell-Meter, 2.5 mm bei 1:100). pub const DEFAULT_TEXT_HEIGHT: f64 = 0.25; fn text_height_of(c: &Value) -> f64 { opt_n(c, "textHeight").filter(|h| *h > 0.0 && h.is_finite()).unwrap_or(DEFAULT_TEXT_HEIGHT) } fn symbol_of(c: &Value) -> f64 { if c.get("sheet").and_then(Value::as_bool) == Some(true) { crate::plan::drawings::SHEET_SYMBOL_FACTOR } else { 1.0 } } pub(crate) fn ctx_of(v: &Value) -> Ctx<'_> { let c = v.get("ctx").unwrap_or(&Value::Null); let fh = opt_n(c, "floorHeight").filter(|h| *h > 0.0); Ctx { level: s_of(c, "level"), floor_height: fh, cat: s_of(c, "cat"), wall_type: s_of(c, "wallType"), text_height: text_height_of(c), symbol: symbol_of(c) } } // ── Werte bauen ────────────────────────────────────────────────────────────── pub(crate) fn pv(p: V) -> Value { pt(p.0, p.1) } pub(crate) fn pvs(pts: &[V]) -> Value { Value::Array(pts.iter().map(|p| pv(*p)).collect()) } pub(crate) fn s(x: &str) -> Value { Value::String(x.into()) } /// Objekt in der gegebenen Schlüsselreihenfolge. pub(crate) fn obj(fields: Vec<(&str, Value)>) -> Value { let mut m = Map::with_capacity(fields.len()); for (k, v) in fields { m.insert(k.into(), v); } Value::Object(m) } pub(crate) fn add_op(collection: &str, items: Vec) -> Vec { if items.is_empty() { return Vec::new(); } vec![Op::Add { collection: collection.into(), items, at: None }] } /// `removeItems(p, collection, ids)`: nur vorhandene ids, je einmal. pub(crate) fn remove_op(root: &Map, collection: &str, ids: &[&str]) -> Vec { let mut drop: Vec = Vec::new(); for e in arr(root.get(collection)) { if let Some(id) = id_of(e) { if ids.contains(&id) && !drop.iter().any(|d| d == id) { drop.push(id.into()); } } } if drop.is_empty() { Vec::new() } else { vec![Op::Remove { collection: collection.into(), ids: drop }] } } // ── Geometrie-Helfer (wie die früheren TS-Einzeiler) ───────────────────────── pub(crate) fn seg_len(a: V, b: V) -> f64 { hypot2(b.0 - a.0, b.1 - a.1) } /// `normalize` aus `model/geometry.ts` (`len || 1`). pub(crate) fn normalize(a: V) -> V { let l = hypot2(a.0, a.1); let l = if l == 0.0 || l.is_nan() { 1.0 } else { l }; (a.0 / l, a.1 / l) } /// Die vier Ecken eines Wandbands (`wallCorners`). fn wall_corners(start: V, end: V, thickness: f64) -> [V; 4] { let h = thickness / 2.0; let u = normalize((end.0 - start.0, end.1 - start.1)); let n = (-u.1, u.0); let off = |p: V, s: f64| (p.0 + n.0 * s, p.1 + n.1 * s); [off(start, h), off(end, h), off(end, -h), off(start, -h)] } /// Achsparalleles Rechteck aus zwei Gegenecken (CCW ab min). pub(crate) fn rect_corners(a: V, b: V) -> [V; 4] { let (x0, x1) = (jsnum::min(a.0, b.0), jsnum::max(a.0, b.0)); let (y0, y1) = (jsnum::min(a.1, b.1), jsnum::max(a.1, b.1)); [(x0, y0), (x1, y0), (x1, y1), (x0, y1)] } /// `n` Punkte auf einem Kreis (`t = (i / n)·2π`, wie die Vorschau-Kreise der Befehle). pub(crate) fn circle_pts(c: V, r: f64, n: usize) -> Vec { (0..n) .map(|i| { let t = (i as f64 / n as f64) * std::f64::consts::PI * 2.0; (c.0 + r * jsnum::cos(t), c.1 + r * jsnum::sin(t)) }) .collect() } pub(crate) fn to_p(p: V) -> P { P::new(p.0, p.1) } /// Gerade Kanten eines Rings/Zugs (`polylineEdges`). pub(crate) fn polyline_edges(pts: &[V], closed: bool) -> Vec<(V, V)> { let mut out: Vec<(V, V)> = pts.windows(2).map(|w| (w[0], w[1])).collect(); if closed && pts.len() > 2 { out.push((pts[pts.len() - 1], pts[0])); } out } pub(crate) fn point_segment_distance(p: V, a: V, b: V) -> f64 { k::point_segment_distance(to_p(p), to_p(a), to_p(b)) } // ── Projekt lesen ──────────────────────────────────────────────────────────── // Lesen über die typisierte Sicht (`&Project`, [124]): Muster für die weiteren Befehle. Neue Elemente // entstehen weiter als JSON (Schlüsselreihenfolge der früheren Objekt-Literale). /// Erste Kategorie `code` im Ebenen-Baum (Tiefensuche über `children`, wie `flat.find`). fn find_category<'a>(list: &'a [LayerCategory], code: &str) -> Option<&'a LayerCategory> { for c in list { if c.code == code { return Some(c); } if let Some(f) = c.children.as_deref().and_then(|ch| find_category(ch, code)) { return Some(f); } } None } /// Gibt es die Kategorie `code` irgendwo im Ebenen-Baum (`layers`, rekursiv über `children`)? pub(crate) fn has_category(p: &Project, code: &str) -> bool { find_category(&p.layers, code).is_some() } /// Kategorie `code`, falls vorhanden, sonst die aktive. pub(crate) fn category_or(p: &Project, code: &str, ctx: &Ctx) -> Value { s(if has_category(p, code) { code } else { ctx.cat }) } /// Farbe der Kategorie `code` (erste im Baum), sonst `def` (auch bei leerer Farbe: fehlt sie in der /// Datei, liest die typisierte Sicht ""). pub(crate) fn category_color(p: &Project, code: &str, def: &str) -> Value { match find_category(&p.layers, code) { Some(c) if !c.color.is_empty() => s(&c.color), _ => s(def), } } pub(crate) fn wall_types(root: &Map) -> &[Value] { arr(root.get("wallTypes")) } /// Aktiver Wandtyp (Fallback: erster des Projekts). fn active_wall_type<'a>(root: &'a Map, ctx: &Ctx) -> Option<&'a Value> { let list = wall_types(root); list.iter().find(|t| id_of(t) == Some(ctx.wall_type)).or(list.first()) } /// id des aktiven Wandtyps (Fallback: erster Typ, sonst die id aus dem Kontext). pub(crate) fn active_wall_type_id(p: &Project, ctx: &Ctx) -> Value { let t = p.wall_types.iter().find(|t| t.id == ctx.wall_type).or(p.wall_types.first()); s(t.map_or(ctx.wall_type, |t| t.id.as_str())) } /// Gesamtdicke eines Wand-/Deckentyps (`wallTypeThickness`: Summe der Schichten). pub(crate) fn type_thickness(t: &Value) -> f64 { arr(field(t, "layers")).iter().fold(0.0, |sum, l| sum + num_of(field(l, "thickness"))) } fn layers_len(t: &Value) -> usize { arr(field(t, "layers")).len() } pub(crate) fn find<'a>(root: &'a Map, collection: &str, id: &str) -> Option<&'a Value> { arr(root.get(collection)).iter().find(|e| id_of(e) == Some(id)) } pub(crate) fn level_of(e: &Value) -> Option<&str> { field(e, "levelId").and_then(Value::as_str) } pub(crate) fn floor_of(e: &Value) -> Option<&str> { field(e, "floorId").and_then(Value::as_str) } // ═════════════════════════════════════════════════════════════════════════════ // Bauteile: Wand, Decke, Raum, Treppe, Öffnung, Dach, Stütze, Extrusion // ═════════════════════════════════════════════════════════════════════════════ /// Kleinste sinnvolle Wanddicke (Dicke-Feld des Wand-Befehls). const MIN_THICKNESS: f64 = 0.01; /// Wirksame Banddicke der Wand-Vorschau: gelockte Dicke (nur einschichtig) oder Wandtyp-Dicke. fn wall_thickness(root: &Map, ctx: &Ctx, thick: Option) -> f64 { let wt = active_wall_type(root, ctx); if let (Some(t), Some(w)) = (thick, wt) { if t >= MIN_THICKNESS && layers_len(w) == 1 { return t; } } wt.map_or(0.2, type_thickness) } /// Einschichtiger Wandtyp mit Dicke `thickness` (gleiches Bauteil wie `base`): vorhanden oder neu. fn wall_type_for_thickness(root: &Map, base: &Value, thickness: f64, ids: &mut IdGen) -> (Vec, Value) { let layer0 = &arr(field(base, "layers"))[0]; let component = field(layer0, "componentId"); let near = |a: f64, b: f64| (a - b).abs() < 1e-4; let same_component = |c: Option<&Value>| match (c, component) { (None, None) => true, (Some(a), Some(b)) => a == b && !a.is_object() && !a.is_array(), _ => false, }; for t in wall_types(root) { let ls = arr(field(t, "layers")); if ls.len() == 1 && same_component(field(&ls[0], "componentId")) && near(num_of(field(&ls[0], "thickness")), thickness) { return (Vec::new(), field(t, "id").cloned().unwrap_or(Value::Null)); } } let name = match field(base, "name") { Some(n) => crate::js_fmt::js_string(n), None => "undefined".into(), }; let id = ids.next("WT"); let mut layer = Vec::new(); if let Some(c) = component { layer.push(("componentId", c.clone())); } layer.push(("thickness", js_num(thickness))); let nt = obj(vec![ ("id", s(&id)), ("name", s(&format!("{name} {} cm", crate::js_fmt::to_fixed(thickness * 100.0, 0)))), ("layers", Value::Array(vec![obj(layer)])), ]); (add_op("wallTypes", vec![nt]), s(&id)) } /// Wand-Befehl: je Achssegment eine Wand des aktiven Typs (Null-Strecken übersprungen); eine gelockte /// Dicke (einschichtig) wählt/erzeugt den passenden Wandtyp. fn wall_ops(root: &Map, p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let pts = pts_of(v, "pts"); let height = ctx.floor_height.unwrap_or(DEF_HEIGHT); let mut type_ops = Vec::new(); let mut type_id = active_wall_type_id(p, ctx); if let (Some(base), Some(t)) = (active_wall_type(root, ctx), opt_n(v, "thick")) { if layers_len(base) == 1 && t >= MIN_THICKNESS && (t - type_thickness(base)).abs() > 1e-4 { let (o, id) = wall_type_for_thickness(root, base, t, ids); type_ops = o; type_id = id; } } // Bogen-Modus ([T2]): `segs` je Segment wie bei der Polylinie (gerade, tangential, Durchgangspunkt). let bulges = crate::cmd_draw::poly_bulges(&pts, arr(v.get("segs"))); let mut walls = Vec::new(); for (i, w) in pts.windows(2).enumerate() { let (a, b) = (w[0], w[1]); if seg_len(a, b) < EPS { continue; } let mut f = vec![ ("id", s(&ids.next("W"))), ("type", s("wall")), ("floorId", s(ctx.level)), ("categoryCode", s(ctx.cat)), ("start", pv(a)), ("end", pv(b)), ]; if let Some(bl) = bulges.get(i).copied().filter(|b| b.abs() > EPS && b.is_finite()) { f.push(("bulge", js_num(bl))); } f.push(("wallTypeId", type_id.clone())); f.push(("height", js_num(height))); walls.push(obj(f)); } if walls.is_empty() { return Vec::new(); } type_ops.extend(add_op("walls", walls)); type_ops } /// Wand-Vorschau: je Segment das Band (Dicke wie beim Commit) und die Achse. fn wall_preview(root: &Map, v: &Value, ctx: &Ctx, pts: &[V], out: &mut Shapes) { let t = wall_thickness(root, ctx, opt_n(v, "thick")); let bulges = crate::cmd_draw::preview_bulges(v, pts); for (i, w) in pts.windows(2).enumerate() { let (a, b) = (w[0], w[1]); if seg_len(a, b) < EPS { continue; } // Bogenwand ([T2]): Band als Kreisringsektor, Achse als Bogen. if let Some((band, axis)) = crate::wall_arc::band_preview(a, b, bulges.get(i).copied(), t) { out.poly(&band); out.poly_open(&axis); continue; } out.poly(&wall_corners(a, b, t)); out.line(a, b); } } /// `normalizeOutline`: doppelte Folgepunkte und den schliessenden Duplikat-Punkt weg, CCW erzwingen. fn normalize_outline(pts: &[V]) -> Option> { let eq = |a: V, b: V| (a.0 - b.0).abs() <= k::EPS && (a.1 - b.1).abs() <= k::EPS; let mut clean: Vec = Vec::new(); for p in pts { if clean.last().is_none_or(|l| !eq(*l, *p)) { clean.push(*p); } } if clean.len() > 1 && eq(clean[0], clean[clean.len() - 1]) { clean.pop(); } if clean.len() < 3 { return None; } let ps: Vec

= clean.iter().map(|p| to_p(*p)).collect(); if !k::is_ccw(&ps) { clean.reverse(); } Some(clean) } fn abs_area(pts: &[V]) -> f64 { let ps: Vec

= pts.iter().map(|p| to_p(*p)).collect(); k::signed_area(&ps).abs() } /// Decke aus einem geschlossenen Umriss (entartet → nichts). fn ceiling_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let Some(outline) = normalize_outline(&pts_of(v, "pts")) else { return Vec::new() }; if abs_area(&outline) < 1e-4 { return Vec::new(); } add_op("ceilings", vec![ceiling_item(p, ctx.level, &outline, ctx, ids)]) } /// [281] Rampe: Decke aus dem Umriss mit Neigung längs `from` → `to`; `percent` = Gefälle in % (positiv = steigt zum /// Endpunkt). Die Oberkante liegt am Anfang auf der Geschosshöhe (Boden des aktiven Geschosses), nicht an der /// Geschossoberkante wie eine Geschossdecke. Entartet (Umriss, Gefällelinie < 1 cm, Gefälle 0/NaN) → nichts. fn ramp_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let Some(outline) = normalize_outline(&pts_of(v, "pts")) else { return Vec::new() }; let (from, to) = (p_of(v, "from"), p_of(v, "to")); let len = (to.0 - from.0).hypot(to.1 - from.1); let pct = opt_n(v, "percent").unwrap_or(f64::NAN); if abs_area(&outline) < 1e-4 || !(len > 0.01) || !pct.is_finite() || pct == 0.0 || pct.abs() > 100.0 { return Vec::new(); } let mut item = ceiling_item(p, ctx.level, &outline, ctx, ids); item["top"] = json!({"mode": "floor", "floorId": ctx.level, "offset": 0}); item["slope"] = json!({"from": pv(from), "to": pv(to), "rise": js_num(pct / 100.0 * len), "ramp": true}); add_op("ceilings", vec![item]) } /// Neue Decke auf Geschoss `floor` mit dem Umriss `outline` (Aufbau wie beim Zeichnen; auch [222]). pub(crate) fn ceiling_item(p: &Project, floor: &str, outline: &[V], ctx: &Ctx, ids: &mut IdGen) -> Value { let mut fields = vec![ ("id", s(&ids.next("C"))), ("type", s("ceiling")), ("floorId", s(floor)), ("categoryCode", category_or(p, "30", ctx)), ("outline", pvs(outline)), ("wallTypeId", active_wall_type_id(p, ctx)), ]; // Eigener Deckentyp (erster des Projekts); `wallTypeId` bleibt als Pflichtfeld/Rückfall ([206]). if let Some(ct) = p.ceiling_types.as_deref().and_then(|l| l.first()) { fields.push(("ceilingTypeId", s(&ct.id))); } obj(fields) } /// Wände des Geschosses als `[n, (ax, ay, bx, by, dicke)…]` für die Raumerkennung. fn floor_walls_flat(p: &Project, level: &str) -> Vec { let mut out = vec![0.0]; let mut n = 0; for w in p.walls.iter().filter(|w| w.floor_id == level) { let wt = p.wall_types.iter().find(|t| t.id == w.wall_type_id); // Summe der Schichten wie `type_thickness` (Startwert 0, Reihenfolge der Liste). let t = wt.map_or(0.2, |t| t.layers.iter().fold(0.0, |sum, l| sum + l.thickness)); // Bogenwand ([T2]): als Sehnenzug. let pts = crate::wall_arc::axis_polyline((w.start.x, w.start.y), (w.end.x, w.end.y), w.bulge, 0.0, t); for q in pts.windows(2) { out.extend([q[0].0, q[0].1, q[1].0, q[1].1, t]); n += 1; } } out[0] = n as f64; out } /// Lichter Umriss der Zelle um `at` (Raum „innen“), `None` = keine geschlossene Zelle. fn room_inside(p: &Project, level: &str, at: V) -> Option> { let f = crate::room_boundary::from_point(at.0, at.1, &floor_walls_flat(p, level), 0.05, true); if f.is_empty() { return None; } let n = f[0] as usize; Some((0..n).map(|i| (f[1 + 2 * i], f[2 + 2 * i])).collect()) } /// Raum aus Umriss (Modus „manuell“: `pts`; „innen“: `at` → Zelle). /// Zauberstab ([77]): geschlossene Polylinie um die Masche unter `at` (mit `hatchId`, falls angegeben: Schraffur). fn wand_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let Some(r) = opt_p(v, "at").and_then(|at| crate::magic_wand::region_at(p, ctx.level, at)) else { return Vec::new() }; let mut f = vec![("shape", s("polyline")), ("pts", pvs(&r.outer)), ("closed", Value::Bool(true))]; if !r.holes.is_empty() { f.push(("holes", Value::Array(r.holes.iter().map(|h| pvs(h)).collect()))); } let g = obj(f); let mut d = crate::cmd_draw::drawing(ids.next("dr2d"), ctx, g); if let (Some(m), Some(h)) = (d.as_object_mut(), v.get("hatchId").and_then(Value::as_str).filter(|h| !h.is_empty())) { m.insert("hatchId".into(), s(h)); } add_op("drawings2d", vec![d]) } fn room_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let boundary = match opt_p(v, "at") { Some(at) => match room_inside(p, ctx.level, at) { Some(b) if b.len() >= 3 => b, _ => return Vec::new(), }, None => pts_of(v, "pts"), }; let ring: Vec<[f64; 2]> = boundary.iter().map(|p| [p.0, p.1]).collect(); let e = crate::room_area::evaluate(&ring, 0.0); if boundary.len() < 3 || e.gross < 1e-4 { return Vec::new(); } // [191] Raum an Bogenwänden: der Sehnenzug der Wandfläche wird ein echter Bogen (Kreis der Wandfläche). let (boundary, bulge) = if opt_p(v, "at").is_some() { room_arcs(p, ctx.level, &boundary) } else { (boundary, Vec::new()) }; let code = if has_category(p, "60") { "60" } else { ctx.cat }; let name = format!("Raum {}", p.rooms.as_ref().map_or(0, Vec::len) + 1); let doc = json!({ "version": 1, "paragraphs": [{ "runs": [{ "text": name, "marks": {} }], "align": "center" }] }); add_op( "rooms", vec![obj(vec![ ("id", s(&ids.next("RM"))), ("type", s("room")), ("floorId", s(ctx.level)), ("categoryCode", s(code)), ("siaCategory", s("HNF")), ("name", s(&name)), ("boundary", pvs(&boundary)), ("color", category_color(p, code, "#4a4a4a")), ("stampDoc", doc), ] .into_iter() .chain(bulge.iter().any(|b| *b != 0.0).then(|| ("boundaryBulge", Value::Array(bulge.iter().map(|b| crate::json_util::js_num(*b)).collect())))) .collect())], ) } /// [191] Bögen des lichten Raums aus den Bogenwänden des Geschosses (Ecken in gleichem Abstand vom Mittelpunkt /// einer Bogenwand, innerhalb ihrer Dicke ± 5 cm); `bulge` leer, wenn keine Bogenwand anliegt. fn room_arcs(p: &Project, level: &str, boundary: &[V]) -> (Vec, Vec) { let mut circles = Vec::new(); for w in p.walls.iter().filter(|w| w.floor_id == level) { let Some(a) = crate::wall_arc::WallArc::of_wall(w) else { continue }; let t = p.wall_types.iter().find(|t| t.id == w.wall_type_id).map_or(0.2, |t| t.layers.iter().fold(0.0, |s, l| s + l.thickness)); let c = crate::model::Vec2 { x: a.center.x, y: a.center.y }; // Raumseite der Wand: Band über die ganze Wanddicke (die Zelle liegt je nach Erkennung knapp innerhalb). circles.push((c, (a.r - t / 2.0 - 0.05).max(1e-3), a.r + t / 2.0 + 0.05)); } if circles.is_empty() { return (boundary.to_vec(), Vec::new()); } let ring: Vec = boundary.iter().map(|q| crate::model::Vec2 { x: q.0, y: q.1 }).collect(); let (pts, bulge) = crate::ring_arc::fit_arcs(&ring, &circles, 2e-3); (pts.iter().map(|q| (q.x, q.y)).collect(), bulge) } // ── Treppe ─────────────────────────────────────────────────────────────────── const MIN_STEPS: f64 = 2.0; /// Stufenzahl aus Soll-Auftritt und Lauflänge (`stepsFromTread`; mindestens 0.24 m Auftritt). pub fn steps_from_tread(auftritt: f64, run_length: f64) -> f64 { let a = jsnum::max(0.05, auftritt); let raw = jsnum::round(run_length / a); let max_by_run = if run_length > 0.0 { jsnum::max(MIN_STEPS, (run_length / 0.24).floor() + 1.0) } else { raw }; jsnum::max(MIN_STEPS, jsnum::min(raw, max_by_run)) } /// Aufgelöste Treppe des Befehls (`buildStair`): Felder in der Reihenfolge des früheren Literals. struct StairBuilt { fields: Vec<(&'static str, Value)>, params: [f64; crate::stair::PARAMS], rise: f64, steps: f64, } fn build_stair(p: &Project, v: &Value, ctx: &Ctx, id: Value) -> StairBuilt { let shape = s_of(v, "shape"); let start = p_of(v, "start"); let cursor = p_of(v, "cursor"); let width = n_of(v, "width"); let referenz = s_of(v, "referenz"); let rise = opt_n(v, "rise").unwrap_or(ctx.floor_height.unwrap_or(DEF_HEIGHT)); let d = (cursor.0 - start.0, cursor.1 - start.1); let dist = jsnum::max(0.1, hypot2(d.0, d.1)); let dir = if dist > EPS { let l = hypot2(d.0, d.1); let l = if l == 0.0 || l.is_nan() { 1e-9 } else { l }; (d.0 / l, d.1 / l) } else { (1.0, 0.0) }; // [151] Gerade mit Podest: Start → Cursor = ganze Länge (zwei gleiche Läufe, Podest = Laufbreite); // U: Start → Cursor = Lauf 1, der Gegenlauf gleich lang. let landing = jsnum::max(0.1, width); let run_length = match shape { "spiral" => jsnum::max(0.5, dist), "straightLanding" => jsnum::max(0.3, (dist - landing) / 2.0), _ => dist, }; // Weg für Stufenzahl und Trittmass: bei zwei gleichen Läufen beide. let walk = if matches!(shape, "U" | "straightLanding") { 2.0 * run_length } else { run_length }; let steps = if s_of(v, "treadMode") == "with" { steps_from_tread(n_of(v, "auftritt"), walk) + if matches!(shape, "U" | "straightLanding") { 1.0 } else { 0.0 } } else { opt_n(v, "steps").unwrap_or_else(|| crate::stair::default_step_count(rise, walk) as f64) }; let up = b_of(v, "up"); let mut f: Vec<(&'static str, Value)> = vec![ ("id", id), ("type", s("stair")), ("floorId", s(ctx.level)), ("categoryCode", category_or(p, "40", ctx)), ("shape", s(shape)), ("start", pv(start)), ("dir", pv(dir)), ("runLength", js_num(run_length)), ("width", js_num(width)), ("referenz", s(referenz)), ("totalRise", js_num(rise)), ("stepCount", js_num(steps)), ("up", Value::Bool(up)), ]; let nan = f64::NAN; let form = match shape { "L" => 1.0, "spiral" => 2.0, "U" => 3.0, "straightLanding" => 4.0, _ => 0.0, }; let refz = match referenz { "links" => 1.0, "rechts" => 2.0, _ => 0.0, }; let mut params = [form, start.0, start.1, dir.0, dir.1, run_length, nan, nan, nan, nan, nan, nan, width, steps, if up { 1.0 } else { 0.0 }, refz, nan, nan, nan, nan, nan, nan]; if shape == "L" { f.push(("run2Length", js_num(run_length))); f.push(("turn", js_num(1.0))); params[6] = run_length; params[7] = 1.0; } else if shape == "U" { const GAP: f64 = 0.1; f.push(("run2Length", js_num(run_length))); f.push(("turn", js_num(1.0))); f.push(("gap", js_num(GAP))); f.push(("landingLength", js_num(landing))); params[6] = run_length; params[7] = 1.0; params[16] = GAP; params[17] = landing; } else if shape == "straightLanding" { f.push(("run2Length", js_num(run_length))); f.push(("landingLength", js_num(landing))); params[6] = run_length; params[17] = landing; } else if shape == "spiral" { f.push(("center", pv(start))); f.push(("radius", js_num(dist))); f.push(("sweep", js_num(270.0))); // Startpunkt am äusseren Rand: die Lauflinie beginnt hier (Schlüssel bleibt an seiner Stelle). f[5].1 = pv(cursor); params[1] = cursor.0; params[2] = cursor.1; params[8] = start.0; params[9] = start.1; params[10] = dist; params[11] = 270.0; } StairBuilt { fields: f, params, rise, steps } } fn stair_ops(root: &Map, p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let b = build_stair(p, v, ctx, s(&ids.next("ST"))); // [266] Deckenloch im selben Commit (ein Undo-Schritt), wenn die Treppe die Decke des Geschosses durchstösst. let hole = crate::cmd_solid::stair_hole_ops(root, &b.params, b.rise, b_of(v, "up"), ctx); let mut ops = add_op("stairs", vec![obj(b.fields)]); ops.extend(hole); ops } /// Treppen-Vorschau: Tritte, Podest, Lauflinie; `info = [Stufenzahl]`. fn stair_preview(p: &Project, v: &Value, ctx: &Ctx, out: &mut Shapes, info: &mut Vec) { let b = build_stair(p, v, ctx, Value::Null); info.push(b.steps); let f = crate::stair::geometry(&b.params, b.rise); if f.len() < 4 { return; } let at = |i: usize| (f[i], f[i + 1]); let pts_at = |i: usize, n: usize| -> Vec { (0..n).map(|k| at(i + 2 * k)).collect() }; let n_treads = f[3] as usize; let mut i = 4; for _ in 0..n_treads { out.poly(&pts_at(i + 3, 4)); i += 11; } let nl = f[i]; i += 1; if nl >= 0.0 { let n = nl as usize; out.poly(&pts_at(i, n)); i += 2 * n; } let n_run = f[i] as usize; i += 1; if n_run >= 2 { out.poly_open(&pts_at(i, n_run)); } // zweites Podest (U mit Mittellauf) nach Lauflinie und Pfeil i += 2 * n_run + 10; if let Some(&nl2) = f.get(i).filter(|n| **n >= 3.0) { let n = nl2 as usize; if f.len() >= i + 1 + 2 * n { out.poly(&pts_at(i + 1, n)); } } } // ── Öffnung ────────────────────────────────────────────────────────────────── /// Pick-Toleranz der Host-Wand. const WALL_PICK_DIST: f64 = 0.6; /// Auf die Wandachse projizierter Fusspunkt: (Abstand vom Wandanfang, Fusspunkt, Distanz). fn project_onto_wall(start: V, end: V, p: V) -> (f64, V, f64) { let ax = (end.0 - start.0, end.1 - start.1); let d = ax.0 * ax.0 + ax.1 * ax.1; let len2 = if d == 0.0 || d.is_nan() { 1e-9 } else { d }; let raw = ((p.0 - start.0) * ax.0 + (p.1 - start.1) * ax.1) / len2; let t = jsnum::max(0.0, jsnum::min(1.0, raw)); let foot = (start.0 + ax.0 * t, start.1 + ax.1 * t); let dist = hypot2(p.0 - foot.0, p.1 - foot.1); (t * len2.sqrt(), foot, dist) } /// Bogenwand ([T2]): Bogen aus Achse und Bulge der Anfrage bzw. Wand. fn arc_of(a: V, b: V, bulge: Option) -> Option { crate::wall_arc::WallArc::of(to_p(a), to_p(b), bulge) } /// Wie [`project_onto_wall`], bei Bogenwänden auf den Bogen (Abstand = Bogenlänge ab Wandanfang). fn project_onto_any(start: V, end: V, bulge: Option, p: V) -> (f64, V, f64) { match arc_of(start, end, bulge) { Some(a) => { let (s, _) = a.local(to_p(p)); let s = jsnum::max(0.0, jsnum::min(s, a.length())); let f = a.point(s, 0.0); (s, (f.x, f.y), hypot2(p.0 - f.x, p.1 - f.y)) } None => project_onto_wall(start, end, p), } } fn bulge_of(w: &Value) -> Option { field(w, "bulge").and_then(Value::as_f64) } /// Nächste Wand des Geschosses zum Klickpunkt (innerhalb der Toleranz). fn pick_wall<'a>(root: &'a Map, level: &str, p: V) -> Option<(&'a Value, V, V)> { let mut best: Option<(&Value, V, V, f64)> = None; for w in arr(root.get("walls")) { if floor_of(w) != Some(level) { continue; } let (a, b) = (xy(field(w, "start").unwrap_or(&Value::Null)), xy(field(w, "end").unwrap_or(&Value::Null))); let (_, _, dist) = project_onto_any(a, b, bulge_of(w), p); if dist <= WALL_PICK_DIST && best.is_none_or(|x| dist < x.3) { best = Some((w, a, b, dist)); } } best.map(|(w, a, b, _)| (w, a, b)) } /// Öffnung in eine Wand (`start`/`end` der Host-Wand beim Picken, `pos` = Abstand vom Wandanfang). /// [144] Überlappt sie eine Öffnung derselben Wand, rückt sie an die nächste freie Stelle (Steg 5 cm, /// `opening_slide::place`); ist keine frei, entsteht keine. fn opening_ops(root: &Map, p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let (st, en) = (p_of(v, "start"), p_of(v, "end")); let len = match arc_of(st, en, opt_n(v, "bulge")) { Some(a) => a.length(), None => hypot2(en.0 - st.0, en.1 - st.1), }; let width = jsnum::max(0.1, jsnum::min(n_of(v, "width"), len)); let position = jsnum::max(0.0, jsnum::min(n_of(v, "pos"), jsnum::max(0.0, len - width))); let Some(placed) = crate::opening_slide::place(root, s_of(v, "wall"), len, width, None, position, &|_| false) else { return vec![] }; let position = if placed.clamped { placed.position } else { position }; let door = s_of(v, "kind") == "door"; // Erster Typ der Bibliothek (leere id = keiner, JS-Wahrheitswert). let first = if door { p.door_types.as_ref().and_then(|l| l.first()).map(|t| &t.id) } else { p.window_types.as_ref().and_then(|l| l.first()).map(|t| &t.id) }; let type_id = first.filter(|id| !id.is_empty()); let mut f = vec![ ("id", s(&ids.next("O"))), ("type", s("opening")), ("hostWallId", s(s_of(v, "wall"))), ("categoryCode", category_or(p, "21", ctx)), ("kind", s(s_of(v, "kind"))), ("position", js_num(position)), ("width", js_num(width)), ("height", js_num(n_of(v, "height"))), ("sillHeight", js_num(if door { 0.0 } else { n_of(v, "sill") })), ]; if let Some(t) = type_id { f.push(("typeId", s(t))); } if door { f.push(("hinge", s(s_of(v, "hinge")))); f.push(("swing", s(s_of(v, "side")))); f.push(("openingDir", s(s_of(v, "dir")))); f.push(("swingAngle", js_num(n_of(v, "swingAngle")))); } add_op("openings", vec![obj(f)]) } /// Lage der Lücke, wie das Setzen sie ergibt ([`opening_ops`]): Breite und Anfang in die Wand geklemmt, /// bei Überlappung an die nächste freie Stelle gerückt ([145]: die Vorschau zeigt die gesetzte Lage, nicht /// den Cursor). Ohne Platz bleibt die geklemmte Lage (das Setzen bewirkt dann nichts). `(pos, width)`. fn placed_gap(root: &Map, v: &Value, len: f64, pos: f64) -> (f64, f64) { let width = jsnum::max(0.1, jsnum::min(n_of(v, "width"), len)); let pos = jsnum::max(0.0, jsnum::min(pos, jsnum::max(0.0, len - width))); match crate::opening_slide::place(root, s_of(v, "wall"), len, width, None, pos, &|_| false) { Some(pl) if pl.clamped => (pl.position, width), _ => (pos, width), } } /// Öffnungs-Vorschau (Lücken-Balken + Symbol). `pos` fehlt → aus dem Cursor projiziert. /// `info = [pos, von, ax, ay, bx, by, mx, my]` (Position für den Zustand, HUD/Stützpunkte). fn opening_preview(root: &Map, v: &Value, cursor: Option, out: &mut Shapes, info: &mut Vec) { let (st, en) = (p_of(v, "start"), p_of(v, "end")); let wall_len = match arc_of(st, en, opt_n(v, "bulge")) { Some(a) => a.length(), None => hypot2(en.0 - st.0, en.1 - st.1), }; // Bogenwand ([T2]): Lücke und Symbol entlang des Bogens, Position = Bogenlänge. if let Some(arc) = arc_of(st, en, opt_n(v, "bulge")) { let len = arc.length(); let pos = match (opt_n(v, "pos"), cursor) { (Some(p), _) => p, (None, Some(c)) => project_onto_any(st, en, opt_n(v, "bulge"), c).0, (None, None) => 0.0, }; let (pos, width) = placed_gap(root, v, wall_len, pos); let from = jsnum::max(0.0, jsnum::min(pos, len)); let to = jsnum::max(from, jsnum::min(from + width, len)); let at = |s: f64, n: f64| { let q = arc.point(s, n); (q.x, q.y) }; let st_pts = arc.stations(from, to, arc.r + 0.15); let half = 0.15; let mut band: Vec = st_pts.iter().map(|&s| at(s, half)).collect(); band.extend(st_pts.iter().rev().map(|&s| at(s, -half))); out.poly(&band); let (a, b) = (at(from, 0.0), at(to, 0.0)); if s_of(v, "kind") == "door" { let swing = if s_of(v, "side") == "left" { 1.0 } else { -1.0 }; let dir = if s_of(v, "dir") == "in" { 1.0 } else { -1.0 }; let (hs, hinge) = if s_of(v, "hinge") == "start" { (from, a) } else { (to, b) }; let nn = arc.normal(hs); out.line(hinge, (hinge.0 + nn.x * swing * dir * width, hinge.1 + nn.y * swing * dir * width)); } else { out.poly_open(&st_pts.iter().map(|&s| at(s, 0.0)).collect::>()); } let m = at((from + to) / 2.0, 0.0); info.extend([pos, from, a.0, a.1, b.0, b.1, m.0, m.1]); return; } let pos = match (opt_n(v, "pos"), cursor) { (Some(p), _) => p, (None, Some(c)) => project_onto_wall(st, en, c).0, (None, None) => 0.0, }; let (pos, width) = placed_gap(root, v, wall_len, pos); let ax = (en.0 - st.0, en.1 - st.1); let l = hypot2(ax.0, ax.1); let len = if l == 0.0 || l.is_nan() { 1e-9 } else { l }; let u = (ax.0 / len, ax.1 / len); let n = (-u.1, u.0); let from = jsnum::max(0.0, jsnum::min(pos, len)); let to = jsnum::max(from, jsnum::min(from + width, len)); let a = (st.0 + u.0 * from, st.1 + u.1 * from); let b = (st.0 + u.0 * to, st.1 + u.1 * to); let half = 0.15; let off = |p: V, s: f64| (p.0 + n.0 * s, p.1 + n.1 * s); out.poly(&[off(a, half), off(b, half), off(b, -half), off(a, -half)]); if s_of(v, "kind") == "door" { let swing = if s_of(v, "side") == "left" { 1.0 } else { -1.0 }; let dir = if s_of(v, "dir") == "in" { 1.0 } else { -1.0 }; let hinge = if s_of(v, "hinge") == "start" { a } else { b }; out.line(hinge, off(hinge, swing * dir * width)); } else { out.line(a, b); } let m = (to - from) / 2.0; info.extend([pos, from, a.0, a.1, b.0, b.1, a.0 + u.0 * m, a.1 + u.1 * m]); } // ── Dach, Stütze ───────────────────────────────────────────────────────────── fn roof_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let (a, b) = (p_of(v, "a"), p_of(v, "b")); let (w, d) = ((b.0 - a.0).abs(), (b.1 - a.1).abs()); if w < 0.1 || d < 0.1 { return Vec::new(); } add_op("roofs", vec![roof_item(p, ctx.level, &rect_corners(a, b), s_of(v, "shape"), 0.4, ctx, ids)]) } /// Neues Dach auf Geschoss `floor` über `outline` (Vorgaben wie beim Zeichnen: 30° bzw. flach, 20 cm; auch [222]). pub(crate) fn roof_item(p: &Project, floor: &str, outline: &[V], shape: &str, overhang: f64, ctx: &Ctx, ids: &mut IdGen) -> Value { let (mut x0, mut x1, mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY); for q in outline { (x0, x1, y0, y1) = (x0.min(q.0), x1.max(q.0), y0.min(q.1), y1.max(q.1)); } obj(vec![ ("id", s(&ids.next("RF"))), ("type", s("roof")), ("floorId", s(floor)), ("categoryCode", category_or(p, "31", ctx)), ("outline", pvs(outline)), ("shape", s(shape)), ("pitchDeg", js_num(if shape == "flach" { 0.0 } else { 30.0 })), ("overhang", js_num(overhang)), ("ridgeAxis", s(if x1 - x0 >= y1 - y0 { "x" } else { "y" })), ("thickness", js_num(0.2)), ]) } /// Stützen-Profil: rund (Durchmesser `size`) oder quadratisch (Kante `size`). fn column_profile(v: &Value) -> Value { let size = n_of(v, "size"); if s_of(v, "kind") == "round" { obj(vec![("kind", s("round")), ("radius", js_num(size / 2.0))]) } else { obj(vec![("kind", s("rect")), ("width", js_num(size)), ("depth", js_num(size))]) } } fn column_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { add_op( "columns", vec![obj(vec![ ("id", s(&ids.next("column"))), ("type", s("column")), ("floorId", s(ctx.level)), ("categoryCode", s("50")), ("position", pv(p_of(v, "at"))), ("profile", column_profile(v)), ("rotation", js_num(0.0)), ("height", js_num(ctx.floor_height.unwrap_or(DEF_HEIGHT))), ])], ) } /// [280] Träger: Achse `pts[0]` → `pts[1]` auf dem aktiven Geschoss, Klasse „25“ (Stützen) bzw. „50“, Querschnitt `width` × `height` /// (Vorgabe 25 × 40 cm), Profilname nur als Text, Oberkante bündig an der Deckenunterkante (`topOffset` 0). fn beam_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let pts = pts_of(v, "pts"); let [a, b] = pts[..] else { return Vec::new() }; if seg_len(a, b) < EPS { return Vec::new(); } let num = |k: &str, d: f64| opt_n(v, k).filter(|x| *x > 0.0 && x.is_finite()).unwrap_or(d); let mut f = vec![ ("id", s(&ids.next("beam"))), ("type", s("beam")), ("floorId", s(ctx.level)), // Klasse „25“ (Stützen), sonst „50“ (Tragwerk), sonst die aktive (wie beim Erkennen von Stützen). ("categoryCode", if has_category(p, "25") { s("25") } else { category_or(p, "50", ctx) }), ("start", pv(a)), ("end", pv(b)), ("width", js_num(num("width", 0.25))), ("height", js_num(num("height", 0.4))), ]; let name = s_of(v, "profileName").trim(); if !name.is_empty() { f.push(("profileName", s(name))); } if let Some(o) = opt_n(v, "topOffset").filter(|x| x.is_finite() && x.abs() > 1e-9) { f.push(("topOffset", js_num(o))); } add_op("beams", vec![obj(f)]) } /// [149] Baum am Punkt `at`: Ebene „13" (Bäume), falls vorhanden, sonst die aktive; Abmessungen, Form, /// Bestand und Laub/Nadel aus den Werkzeug-Vorgaben (fehlende/unsinnige Werte: Vorgaben aus `tree.rs`). fn tree_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { use crate::tree::*; let num = |k: &str, d: f64| opt_n(v, k).filter(|x| *x > 0.0 && x.is_finite()).unwrap_or(d); let height = num("height", DEFAULT_HEIGHT); let crown_base = opt_n(v, "crownBase").filter(|x| *x >= 0.0 && x.is_finite()).unwrap_or(DEFAULT_CROWN_BASE).min(0.9 * height); let pick = |k: &str, allowed: &[&str]| -> Value { s(allowed.iter().copied().find(|a| *a == s_of(v, k)).unwrap_or(allowed[0])) }; let cat = if p.layer_category(TREE_CATEGORY).is_some() { TREE_CATEGORY } else { ctx.cat }; let mut f = vec![ ("id", s(&ids.next("tree"))), ("type", s("tree")), ("floorId", s(ctx.level)), ("categoryCode", s(cat)), ("position", pv(p_of(v, "at"))), ("trunkDiameter", js_num(num("trunkDiameter", DEFAULT_TRUNK_DIAMETER))), ("crownDiameter", js_num(num("crownDiameter", DEFAULT_CROWN_DIAMETER))), ("crownBase", js_num(crown_base)), ("height", js_num(height)), ("shape", pick("shape", &["round", "oval", "columnar", "conical"])), ("status", pick("status", &["existing", "new", "remove"])), ("foliage", pick("foliage", &["deciduous", "conifer"])), ]; let species = s_of(v, "species").trim(); if !species.is_empty() { f.push(("species", s(species))); } add_op("trees", vec![obj(f)]) } /// [279] Geländer über die Punkte `pts` (Polylinie, mindestens zwei verschiedene) auf dem aktiven Geschoss: Ebene „41" /// (Geländer), falls vorhanden, sonst die aktive. Art, Höhe (Vorgabe 1.00 m), Fusshöhe, Handlauf, Stababstand, Stabquerschnitt, /// Dicke und Bauteil aus den Werkzeug-Vorgaben; fehlende oder unsinnige Werte bleiben weg (Vorgaben aus `railing.rs`). /// `closed` mit mindestens drei Punkten schliesst den Zug. fn railing_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let mut pts: Vec = pts_of(v, "pts").into_iter().filter(|q| q.0.is_finite() && q.1.is_finite()).collect(); pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6); if pts.len() < 2 { return Vec::new(); } let pos = |k: &str| opt_n(v, k).filter(|x| *x > 0.0 && x.is_finite()); let kind = ["bars", "glass", "solid", "perforated"].into_iter().find(|a| *a == s_of(v, "kind")).unwrap_or("bars"); let mut f = vec![ ("id", s(&ids.next("railing"))), ("type", s("railing")), ("floorId", s(ctx.level)), ("categoryCode", category_or(p, crate::railing::CATEGORY, ctx)), ("points", pvs(&pts)), ("height", js_num(pos("height").unwrap_or(crate::railing::DEFAULT_HEIGHT))), ("kind", s(kind)), ]; if v.get("closed").and_then(Value::as_bool) == Some(true) && pts.len() >= 3 { f.push(("closed", Value::Bool(true))); } if let Some(b) = opt_n(v, "baseOffset").filter(|x| x.is_finite() && *x != 0.0) { f.push(("baseOffset", js_num(b))); } if let Some(h) = v.get("handrail").and_then(Value::as_bool) { f.push(("handrail", Value::Bool(h))); } for k in ["barSpacing", "barSize", "thickness", "handrailSize"] { if let Some(x) = pos(k) { f.push((k, js_num(x))); } } let comp = s_of(v, "componentId"); if kind == "solid" && !comp.is_empty() { f.push(("componentId", s(comp))); } add_op("railings", vec![obj(f)]) } /// [149] „Kreise in Bäume umwandeln": die gewählten Kreise (`ids`), sonst alle Kreise der Baum-Ebene auf der /// aktiven Ebene, werden Baum-Objekte (Kronendurchmesser = Kreisdurchmesser, Höhe = `sunStudy.treeHeight` /// bzw. Vorgabe, Ebene und Geschoss des Kreises); die Kreise entfallen. Ein Undo-Schritt. fn circles_to_trees_ops(root: &Map, p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { use crate::tree::*; let chosen: Vec<&str> = arr(field(v, "ids")).iter().filter_map(Value::as_str).collect(); let is_tree_cat = |code: &str| { code == TREE_CATEGORY || p.layer_category(code).is_some_and(|c| { let n = c.name.to_lowercase(); n.contains("baum") || n.contains("bäume") || n.contains("tree") }) }; let h = p.sun_study.as_ref().and_then(|s| s.tree_height).filter(|h| *h > 0.0 && h.is_finite()).unwrap_or(crate::sun::DEFAULT_TREE_HEIGHT); let (mut src, mut out) = (Vec::new(), Vec::new()); for d in &p.drawings2d { let crate::model::Drawing2DGeom::Circle { center, r } = &d.geom else { continue }; let pick = if chosen.is_empty() { d.level_id == ctx.level && is_tree_cat(&d.category_code) } else { chosen.contains(&d.id.as_str()) }; if !pick || !(*r > 0.0 && r.is_finite() && center.x.is_finite() && center.y.is_finite()) { continue; } let cat = if is_tree_cat(&d.category_code) { d.category_code.as_str() } else if p.layer_category(TREE_CATEGORY).is_some() { TREE_CATEGORY } else { d.category_code.as_str() }; src.push(d.id.as_str()); out.push(obj(vec![ ("id", s(&ids.next("tree"))), ("type", s("tree")), ("floorId", s(&d.level_id)), ("categoryCode", s(cat)), ("position", pv((center.x, center.y))), ("trunkDiameter", js_num(DEFAULT_TRUNK_DIAMETER.min(*r))), ("crownDiameter", js_num(2.0 * r)), ("crownBase", js_num(DEFAULT_CROWN_BASE.min(0.4 * h))), ("height", js_num(h)), ("shape", s("round")), ("status", s("existing")), ("foliage", s("deciduous")), ])); } if out.is_empty() { return vec![]; } let mut ops = remove_op(root, "drawings2d", &src); ops.extend(add_op("trees", out)); ops } /// Grundriss einer Stütze ohne Drehung (`columnFootprint`: rund 32 Punkte, sonst 4 Ecken). fn column_footprint(at: V, v: &Value) -> Vec { let size = n_of(v, "size"); if s_of(v, "kind") == "round" { return circle_pts(at, size / 2.0, 32); } let (hw, hd) = (size / 2.0, size / 2.0); let (cos, sin) = (jsnum::cos(0.0), jsnum::sin(0.0)); [(-hw, -hd), (hw, -hd), (hw, hd), (-hw, hd)].iter().map(|p| (at.0 + p.0 * cos - p.1 * sin, at.1 + p.0 * sin + p.1 * cos)).collect() } // ── Extrusion ──────────────────────────────────────────────────────────────── /// Profil-Pick-Toleranz. const PROFILE_HIT_TOL: f64 = 0.25; /// Extrudierbares Profil einer Zeichnung: geschlossene Polylinie (≥ 3 Punkte), Rechteck, Kreis. /// Punkte als JSON-Werte (Polylinie: die gespeicherten), dazu `circle` beim Kreis. pub(crate) fn profile_of(d: &Value) -> Option<(Vec, Option)> { let g = field(d, "geom")?; match field(g, "shape").and_then(Value::as_str)? { "polyline" => { let pts = arr(field(g, "pts")); (truthy(field(g, "closed")) && pts.len() >= 3).then(|| (pts.to_vec(), None)) } "rect" => { let (mn, mx) = (field(g, "min")?, field(g, "max")?); let (a, b) = (xy(mn), xy(mx)); Some((vec![mn.clone(), pt(b.0, a.1), mx.clone(), pt(a.0, b.1)], None)) } "circle" => { let c = field(g, "center")?; let r = field(g, "r").cloned().unwrap_or(Value::Null); let pts = circle_pts(xy(c), num_of(Some(&r)), 48).into_iter().map(pv).collect(); Some((pts, Some(obj(vec![("center", c.clone()), ("r", r)])))) } _ => None, } } fn profile_json(d: &Value) -> Value { match profile_of(d) { Some((pts, circle)) => json!({ "id": id_of(d), "pts": pts, "circle": circle }), None => Value::Null, } } /// Nächstes Profil (Kantenabstand < Toleranz) der Ebene am Punkt. fn pick_profile<'a>(root: &'a Map, level: &str, at: V) -> Option<&'a Value> { let mut best = None; let mut best_d = PROFILE_HIT_TOL; for d in arr(root.get("drawings2d")) { if level_of(d) != Some(level) { continue; } let Some((pts, _)) = profile_of(d) else { continue }; let pts: Vec = pts.iter().map(xy).collect(); for (a, b) in polyline_edges(&pts, true) { let dd = point_segment_distance(at, a, b); if dd < best_d { best_d = dd; best = Some(d); } } } best } /// Extrusion eines Profils (die Quelle verschwindet, der Körper kommt dazu). fn extrude_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let src = s_of(v, "source"); let Some((pts, circle)) = find(root, "drawings2d", src).and_then(profile_of) else { return Vec::new() }; let taper = n_of(v, "taper"); let mut f = vec![ ("id", s(&ids.next("extrude"))), ("type", s("extrudedSolid")), ("levelId", s(ctx.level)), ("points", Value::Array(pts)), ("height", js_num(n_of(v, "height"))), ]; if let Some(c) = circle { f.push(("circle", c)); } if taper > 0.0 { f.push(("taper", js_num(taper))); } let mut ops = remove_op(root, "drawings2d", &[src]); ops.extend(add_op("extrudedSolids", vec![obj(f)])); ops } // ═════════════════════════════════════════════════════════════════════════════ // Einstiege // ═════════════════════════════════════════════════════════════════════════════ /// Ops eines Zeichenbefehls (`None` = kein Zeichenbefehl). pub fn ops(root: &Map, p: &Project, v: &Value) -> Option> { let ctx = ctx_of(v); let mut ids = IdGen::new(s_of(v, "stamp")); let ids = &mut ids; Some(match s_of(v, "cmd") { "wall" => wall_ops(root, p, v, &ctx, ids), "ceiling" => ceiling_ops(p, v, &ctx, ids), "ramp" => ramp_ops(p, v, &ctx, ids), "room" => room_ops(p, v, &ctx, ids), "wand" => wand_ops(p, v, &ctx, ids), // [154] Bauteile aus Zeichnung erkennen. "recognize" => crate::drawing_recognize::ops(p, v, &ctx, ids), "stair" => stair_ops(root, p, v, &ctx, ids), "opening" => opening_ops(root, p, v, &ctx, ids), "roof" => roof_ops(p, v, &ctx, ids), "column" => column_ops(v, &ctx, ids), "beam" => beam_ops(p, v, &ctx, ids), "tree" => tree_ops(p, v, &ctx, ids), "railing" => railing_ops(p, v, &ctx, ids), "circlesToTrees" => circles_to_trees_ops(root, p, v, &ctx, ids), "extrude" => extrude_ops(root, v, &ctx, ids), // [222] Volumenstudie → Bauteile. "solidToParts" => crate::cmd_massing::ops(root, p, v, &ctx, ids), _ => return crate::cmd_draw::ops(root, p, v, &ctx, ids).or_else(|| crate::cmd_solid::ops(root, p, v, &ctx, ids)), }) } /// Ergebnis einer Vorschau: Formen, ob ein Commit hier etwas erzeugte, Zusatzzahlen (je Befehl). #[derive(Default)] pub struct Preview { pub shapes: Shapes, pub ok: bool, pub info: Vec, } impl Preview { /// Flach: `[ok, nInfo, info…, Formen…]` (Formen wie `doc_cmd_preview`). pub fn flat(self) -> Vec { let mut out = Vec::with_capacity(2 + self.info.len() + self.shapes.buf.len()); out.push(if self.ok { 1.0 } else { 0.0 }); out.push(self.info.len() as f64); out.extend(self.info); out.extend(self.shapes.buf); out } } /// Vorschau eines Zeichenbefehls: `v` = Optionen (`cmd`, …, `ctx`), `pts` = die Punkte flach (je Befehl /// die gesetzten Punkte und zuletzt der Cursor). pub fn preview(root: &Map, project: &Project, v: &Value, pts: &[f64]) -> Preview { preview_req(root, project, &Req::new(v.clone()), pts) } /// Gelesene Vorschau-Anfrage: die Optionen und, für den Mausschritt ohne Hash-Suchen, Befehl und Kontext. pub struct Req { pub v: Value, cmd: String, level: String, floor_height: Option, cat: String, wall_type: String, text_height: f64, symbol: f64, } impl Req { pub fn new(v: Value) -> Req { let c = ctx_of(&v); let (level, floor_height, cat, wall_type) = (c.level.to_string(), c.floor_height, c.cat.to_string(), c.wall_type.to_string()); let (text_height, symbol) = (c.text_height, c.symbol); Req { cmd: s_of(&v, "cmd").to_string(), v, level, floor_height, cat, wall_type, text_height, symbol } } } /// Wie [`preview`] mit gelesener Anfrage (Mausschritt: dieselbe Anfrage, neue Punkte). pub fn preview_req(root: &Map, project: &Project, req: &Req, pts: &[f64]) -> Preview { let v = &req.v; let ctx = Ctx { level: &req.level, floor_height: req.floor_height, cat: &req.cat, wall_type: &req.wall_type, text_height: req.text_height, symbol: req.symbol }; let pts = flat_pts(pts); let mut p = Preview { ok: true, ..Default::default() }; let out = &mut p.shapes; match req.cmd.as_str() { "wall" => wall_preview(root, v, &ctx, &pts, out), "stair" => stair_preview(project, v, &ctx, out, &mut p.info), "opening" => opening_preview(root, v, pts.first().copied(), out, &mut p.info), "roomInside" => p.ok = pts.first().and_then(|at| room_inside(project, ctx.level, *at)).is_some_and(|b| b.len() >= 3), // Zauberstab ([77]): die gefundene Masche unter dem Cursor. "wand" => match pts.first().and_then(|at| crate::magic_wand::region_at(project, ctx.level, *at)) { Some(r) => { out.poly(&r.outer); for h in &r.holes { out.poly(h); } } None => p.ok = false, }, "recognize" => p.ok = crate::drawing_recognize::preview(project, v, &ctx, out, &mut p.info), "column" => { if let Some(at) = pts.first() { out.poly(&column_footprint(*at, v)); } } "beam" => { // [280] Rechteck um die Achse vom ersten Punkt zum Cursor. if let [a, b] = pts[..] { let w = opt_n(v, "width").filter(|x| *x > 0.0 && x.is_finite()).unwrap_or(0.25); let beam = crate::model::Beam { start: crate::model::Vec2 { x: a.0, y: a.1 }, end: crate::model::Vec2 { x: b.0, y: b.1 }, width: w, ..Default::default() }; let fp = beam.footprint(); if fp.len() == 4 { out.poly(&fp.iter().map(|q| (q.x, q.y)).collect::>()); out.line(a, b); } } } "tree" => { // [149] Kronenkreis und Stamm am Cursor. if let Some(at) = pts.first() { let d = opt_n(v, "crownDiameter").filter(|x| *x > 0.0 && x.is_finite()).unwrap_or(crate::tree::DEFAULT_CROWN_DIAMETER); let t = opt_n(v, "trunkDiameter").filter(|x| *x > 0.0 && x.is_finite()).unwrap_or(crate::tree::DEFAULT_TRUNK_DIAMETER); out.poly(&circle_pts(*at, d / 2.0, 32)); out.poly(&circle_pts(*at, t / 2.0, 12)); } } "rect4" => { // Aufgezogenes Rechteck (Dach, Deckenaussparung, Textrahmen …): erste Ecke + Cursor. if pts.len() >= 2 { out.poly(&rect_corners(pts[0], pts[1])); } } _ => { if !crate::cmd_draw::preview(root, project, v, &ctx, &pts, &mut p) && !crate::cmd_solid::preview(root, v, &pts, &mut p) { p.ok = false; } } } p } /// Treffer-Abfragen der Zeichenbefehle (`None` = keine Abfrage dieses Moduls). pub fn query(root: &Map, p: &Project, v: &Value) -> Option> { let at = p_of(v, "pt"); let level = s_of(v, "level"); Some(Ok(match s_of(v, "q") { "pickWall" => match pick_wall(root, level, at) { Some((w, a, b)) => { let mut hit = json!({ "id": id_of(w), "start": [js_num(a.0), js_num(a.1)], "end": [js_num(b.0), js_num(b.1)], "t": js_num(project_onto_any(a, b, bulge_of(w), at).0) }); if let Some(bl) = bulge_of(w).filter(|_| arc_of(a, b, bulge_of(w)).is_some()) { hit["bulge"] = js_num(bl); } json!({ "hit": hit }) } None => json!({ "hit": null }), }, "recognize" => crate::drawing_recognize::report(p, v), "solidToParts" => crate::cmd_massing::check(p, v), "pickProfile" => json!({ "hit": pick_profile(root, level, at).map_or(Value::Null, profile_json) }), "profile" => json!({ "hit": find(root, "drawings2d", s_of(v, "id")).map_or(Value::Null, profile_json) }), _ => return crate::cmd_draw::query(root, p, v).or_else(|| crate::cmd_solid::query(root, p, v)).map(Ok), })) } // ── Gruppen-Zuordnung ──────────────────────────────────────────────────────── /// Mitglieds-Listen einer Gruppe und ihre Element-Listen (Reihenfolge wie `KEYS` in der Hülle). const MEMBER_KEYS: [(&str, &str); 11] = [ ("wallIds", "walls"), ("drawingIds", "drawings2d"), ("ceilingIds", "ceilings"), ("roomIds", "rooms"), ("stairIds", "stairs"), ("columnIds", "columns"), ("roofIds", "roofs"), ("openingIds", "openings"), // [284] Träger liegen im Auswahlkanal der Stützen; Geländer und Bäume eigene Listen. ("columnIds", "beams"), ("railingIds", "railings"), ("treeIds", "trees"), ]; /// Zeichnet man in einer betretenen Gruppe (`group` = innerste aktive Gruppe), werden die neu /// eingefügten Elemente (`add`-Ops) ihr Mitglied: eine `replace`-Op der Gruppe mit den ergänzten Listen /// (Vereinigung, erste Vorkommen in Reihenfolge). Leer ohne neue Elemente oder ohne die Gruppe. pub fn group_ops(root: &Map, ops: &[Op], group: &str) -> Vec { let Some(g) = find(root, "groups", group) else { return Vec::new() }; let mut added: Vec<(&str, Vec)> = Vec::new(); for (key, coll) in MEMBER_KEYS { let existing = arr(root.get(coll)); let mut ids: Vec = Vec::new(); for op in ops { if let Op::Add { collection, items, .. } = op { if collection != coll { continue; } for e in items { if let Some(id) = id_of(e) { if !existing.iter().any(|x| id_of(x) == Some(id)) { ids.push(id.into()); } } } } } if !ids.is_empty() { added.push((key, ids)); } } if added.is_empty() { return Vec::new(); } let mut m = g.as_object().cloned().unwrap_or_default(); for (key, _) in MEMBER_KEYS { let mut list: Vec = Vec::new(); let mut push = |x: &Value| { if !list.contains(x) { list.push(x.clone()); } }; arr(m.get(key)).iter().for_each(&mut push); for (_, ids) in added.iter().filter(|(k, _)| *k == key) { ids.iter().for_each(|id| push(&Value::String(id.clone()))); } m.insert(key.into(), Value::Array(list)); } vec![Op::Replace { collection: "groups".into(), entity: Value::Object(m) }] } #[cfg(test)] mod tests { use super::*; fn root(v: Value) -> Map { v.as_object().unwrap().clone() } fn items(ops: &[Op], i: usize) -> Value { ops[i].to_json()["items"].clone() } const CTX: &str = r#"{"level":"F1","floorHeight":3,"cat":"20","wallType":"WT1"}"#; fn req(extra: Value) -> Value { let mut v = extra; v["ctx"] = serde_json::from_str(CTX).unwrap(); v["stamp"] = json!("s"); v } /// [T2] Bogen-Modus: Drei-Punkt-Bogen (Durchgangspunkt) und tangential anschliessend; Vorschau als /// Kreisringsektor. #[test] fn bogenwand_drei_punkt_und_tangential() { let r = root(json!({"wallTypes": [{"id": "WT1", "name": "Beton", "layers": [{"componentId": "c", "thickness": 0.2}]}]})); // (0,0)→(4,0) durch (2,2): Halbkreis, Scheitel links → Modell-Bulge +1; dann tangential weiter nach (4,-4)? let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0], [8, 0]], "segs": [{"x": 2, "y": 2}, 1], "thick": null}))).unwrap(); let w = items(&o, 0); let b0 = w[0]["bulge"].as_f64().unwrap(); assert!((b0 - 1.0).abs() < 1e-9, "{b0}"); // Tangential an das Ende des Halbkreises (Richtung −y): zweiter Halbkreis mit Scheitel unten (Bulge −1). let b1 = w[1]["bulge"].as_f64().unwrap(); assert!((b1 + 1.0).abs() < 1e-9, "{b1}"); // Gerade Wand ohne `bulge`-Feld. let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0]], "segs": [0], "thick": null}))).unwrap(); assert!(items(&o, 0)[0].get("bulge").is_none()); } /// [206] Decke: eigener Deckentyp (erster aus `ceilingTypes`) statt des Wand-Aufbaus — vorher bekam eine neue /// Decke nur das LEGACY-`wallTypeId` des aktiven Wandtyps und zeigte im Schnitt die Aussenwand-Schichten. #[test] fn decke_mit_deckentyp() { let wt = json!([{"id": "WT1", "name": "Aussenwand", "layers": [{"componentId": "c", "thickness": 0.3}]}]); let ct = json!([{"id": "CT1", "name": "Stahlbetondecke", "layers": [{"componentId": "c", "thickness": 0.25}]}]); let pts = json!({"cmd": "ceiling", "pts": [[0, 0], [4, 0], [4, 3], [0, 3]]}); let r = root(json!({"wallTypes": wt, "ceilingTypes": ct})); let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(pts.clone())).unwrap(); let c = &items(&o, 0)[0]; assert_eq!(c["ceilingTypeId"], "CT1"); assert_eq!(c["wallTypeId"], "WT1"); // Ohne Deckentypen bleibt es beim Wand-Aufbau (Pflichtfeld `wallTypeId`). let r = root(json!({"wallTypes": wt})); let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(pts)).unwrap(); assert!(items(&o, 0)[0].get("ceilingTypeId").is_none()); } /// [281] Rampe: Decke mit Neigung (Gefälle in % längs Anfang → Ende), OK am Anfang auf dem Geschossboden; /// Unsinn (Gefälle 0, Linie zu kurz) legt nichts an. #[test] fn rampe_mit_gefaelle() { let ct = json!([{"id": "CT1", "name": "Stahlbetondecke", "layers": [{"componentId": "c", "thickness": 0.25}]}]); let r = root(json!({"wallTypes": [{"id": "WT1", "name": "W", "layers": [{"componentId": "c", "thickness": 0.3}]}], "ceilingTypes": ct})); let base = json!({"cmd": "ramp", "pts": [[0, 0], [10, 0], [10, 3], [0, 3]], "from": [0, 1.5], "to": [10, 1.5], "percent": -15}); let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(base.clone())).unwrap(); let c = &items(&o, 0)[0]; assert_eq!(c["slope"]["ramp"], true); assert!((c["slope"]["rise"].as_f64().unwrap() + 1.5).abs() < 1e-9, "{c}"); assert_eq!(c["top"], json!({"mode": "floor", "floorId": "F1", "offset": 0})); assert_eq!(c["ceilingTypeId"], "CT1"); for bad in [json!(0), json!(null), json!(150)] { let mut v = base.clone(); v["percent"] = bad; assert!(ops(&r, &crate::model::lenient::typed_for_test(&r), &req(v)).unwrap().is_empty()); } let mut v = base; v["to"] = json!([0, 1.505]); assert!(ops(&r, &crate::model::lenient::typed_for_test(&r), &req(v)).unwrap().is_empty()); } #[test] fn waende_je_segment_mit_typ_und_hoehe() { let r = root(json!({"wallTypes": [{"id": "WT1", "name": "Beton", "layers": [{"componentId": "c", "thickness": 0.2}]}]})); let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0], [4, 0], [4, 3]], "thick": null}))).unwrap(); let w = items(&o, 0); assert_eq!(w.as_array().unwrap().len(), 2); assert_eq!(w[0], json!({"id": "W-s-1", "type": "wall", "floorId": "F1", "categoryCode": "20", "start": {"x": 0, "y": 0}, "end": {"x": 4, "y": 0}, "wallTypeId": "WT1", "height": 3})); // Gelockte Dicke → neuer einschichtiger Typ vor den Wänden. let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0]], "thick": 0.3}))).unwrap(); assert_eq!(items(&o, 0)[0], json!({"id": "WT-s-1", "name": "Beton 30 cm", "layers": [{"componentId": "c", "thickness": 0.3}]})); assert_eq!(items(&o, 1)[0]["wallTypeId"], "WT-s-1"); } /// [149] Baum setzen (Ebene 13, Vorgaben, Unsinn verworfen) und Kreise in Bäume umwandeln. #[test] fn baum_setzen_und_kreise_umwandeln() { let r = root(json!({"layers": [{"code": "13", "name": "Bäume", "color": "#000"}], "drawings2d": [ {"id": "k1", "type": "drawing2d", "levelId": "F1", "categoryCode": "13", "geom": {"shape": "circle", "center": {"x": 3, "y": 4}, "r": 2.5}}, {"id": "k2", "type": "drawing2d", "levelId": "F1", "categoryCode": "20", "geom": {"shape": "circle", "center": {"x": 0, "y": 0}, "r": 1}}, {"id": "k3", "type": "drawing2d", "levelId": "F2", "categoryCode": "13", "geom": {"shape": "circle", "center": {"x": 0, "y": 0}, "r": 1}} ], "sunStudy": {"when": "2026-06-21T10:00:00Z", "show": true, "treeHeight": 14}})); let p = crate::model::lenient::typed_for_test(&r); let o = ops(&r, &p, &req(json!({"cmd": "tree", "at": [1, 2], "crownDiameter": 7, "height": 15, "shape": "conical", "status": "new", "foliage": "conifer", "species": " Picea abies "}))).unwrap(); let t = &items(&o, 0)[0]; assert_eq!(t["categoryCode"], "13"); assert_eq!((t["crownDiameter"].as_f64(), t["height"].as_f64(), t["trunkDiameter"].as_f64()), (Some(7.0), Some(15.0), Some(crate::tree::DEFAULT_TRUNK_DIAMETER))); assert_eq!((t["shape"].as_str(), t["status"].as_str(), t["foliage"].as_str(), t["species"].as_str()), (Some("conical"), Some("new"), Some("conifer"), Some("Picea abies"))); let _: crate::model::Tree = serde_json::from_value(t.clone()).unwrap(); // Unsinn: Vorgaben, unbekannte Form → rund. let o = ops(&r, &p, &req(json!({"cmd": "tree", "at": [0, 0], "height": -3, "shape": "weide"}))).unwrap(); let t = &items(&o, 0)[0]; assert_eq!((t["height"].as_f64(), t["shape"].as_str()), (Some(crate::tree::DEFAULT_HEIGHT), Some("round"))); // Umwandeln ohne Auswahl: nur Kreise der Baum-Ebene auf der aktiven Ebene. let o = ops(&r, &p, &req(json!({"cmd": "circlesToTrees"}))).unwrap(); assert_eq!(o[0].to_json()["ids"], json!(["k1"])); let t = &items(&o, 1)[0]; assert_eq!((t["crownDiameter"].as_f64(), t["height"].as_f64(), t["floorId"].as_str()), (Some(5.0), Some(14.0), Some("F1"))); assert_eq!(t["position"], json!({"x": 3, "y": 4})); // Mit Auswahl: genau die gewählten Kreise (auch anderer Ebene). let o = ops(&r, &p, &req(json!({"cmd": "circlesToTrees", "ids": ["k2", "k3"]}))).unwrap(); assert_eq!(o[0].to_json()["ids"], json!(["k2", "k3"])); assert_eq!(items(&o, 1)[1]["floorId"], "F2"); // Nichts zu tun: keine Ops. assert!(ops(&r, &p, &req(json!({"cmd": "circlesToTrees", "ids": ["fehlt"]}))).unwrap().is_empty()); } #[test] fn treppe_stufen_aus_auftritt() { assert_eq!(steps_from_tread(0.29, 3.0), 10.0); assert_eq!(steps_from_tread(0.29, 3.1), 11.0); assert_eq!(steps_from_tread(0.29, 0.01), MIN_STEPS); assert_eq!(steps_from_tread(0.29, -1.0), MIN_STEPS); assert_eq!(steps_from_tread(0.25, 2.5), 10.0); // Auftritt nie unter 0.24 m. let s = steps_from_tread(0.01, 10.0); assert!(10.0 / (s - 1.0) >= 0.24 - 1e-9); assert_eq!(steps_from_tread(0.29, 10.0 * 0.29), 10.0); } #[test] fn raum_innen_und_gruppe() { let wt = json!([{"id": "WT1", "layers": [{"thickness": 0.2}]}]); let wall = |id: &str, a: (f64, f64), b: (f64, f64)| json!({"id": id, "floorId": "F1", "wallTypeId": "WT1", "start": {"x": a.0, "y": a.1}, "end": {"x": b.0, "y": b.1}}); let r = root(json!({"wallTypes": wt, "rooms": [], "layers": [{"code": "60", "color": "#abc"}], "walls": [ wall("a", (0.0, 0.0), (5.0, 0.0)), wall("b", (5.0, 0.0), (5.0, 4.0)), wall("c", (5.0, 4.0), (0.0, 4.0)), wall("d", (0.0, 4.0), (0.0, 0.0))], "groups": [{"id": "g", "name": "G", "wallIds": ["a"], "drawingIds": []}]})); let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "room", "at": [2, 2]}))).unwrap(); let room = &items(&o, 0)[0]; assert_eq!(room["name"], "Raum 1"); assert_eq!(room["color"], "#abc"); assert_eq!(room["boundary"].as_array().unwrap().len(), 4); let g = group_ops(&r, &o, "g"); let e = g[0].to_json()["entity"].clone(); assert_eq!(e["roomIds"], json!(["RM-s-1"])); assert_eq!(e["wallIds"], json!(["a"])); assert!(group_ops(&r, &o, "x").is_empty()); assert!(group_ops(&r, &[], "g").is_empty()); } /// [T2] Öffnung in der Bogenwand: Picken am Bogen, Position = Bogenlänge, Begrenzung auf die Bogenlänge. #[test] fn oeffnung_in_bogenwand() { // Halbkreis (0,0)→(4,0), Scheitel oben (2,2): Bogenlänge 2π. let r = root(json!({"walls": [{"id": "w", "floorId": "F1", "start": {"x": 0, "y": 0}, "end": {"x": 4, "y": 0}, "bulge": 1}], "windowTypes": [{"id": "FT"}]})); let p = crate::document::Document::from_json(&Value::Object(r.clone()).to_string()).unwrap().project().unwrap().clone(); let q = query(&r, &p, &json!({"q": "pickWall", "level": "F1", "pt": [2, 2.2]})).unwrap().unwrap(); assert_eq!(q["hit"]["id"], "w"); assert!((q["hit"]["t"].as_f64().unwrap() - std::f64::consts::PI).abs() < 1e-9); assert_eq!(q["hit"]["bulge"], 1); let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "opening", "wall": "w", "start": [0, 0], "end": [4, 0], "bulge": 1, "kind": "window", "pos": 6.0, "width": 1.2, "height": 1.2, "sill": 0.9}))).unwrap(); let pos = items(&o, 0)[0]["position"].as_f64().unwrap(); assert!((pos - (2.0 * std::f64::consts::PI - 1.2)).abs() < 1e-9, "{pos}"); } #[test] fn oeffnung_pick_und_vorschau() { let r = root(json!({"walls": [{"id": "w", "floorId": "F1", "start": {"x": 0, "y": 0}, "end": {"x": 6, "y": 0}}], "windowTypes": [{"id": "FT"}]})); let p = crate::document::Document::from_json(&Value::Object(r.clone()).to_string()).unwrap().project().unwrap().clone(); let q = query(&r, &p, &json!({"q": "pickWall", "level": "F1", "pt": [2, 0.3]})).unwrap().unwrap(); assert_eq!(q["hit"]["id"], "w"); assert_eq!(q["hit"]["t"], 2); let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "opening", "wall": "w", "start": [0, 0], "end": [6, 0], "kind": "window", "pos": 5.5, "width": 1.2, "height": 1.2, "sill": 0.9}))).unwrap(); let op = &items(&o, 0)[0]; assert_eq!(op["position"], 4.8); assert_eq!(op["typeId"], "FT"); // [144] Neben eine bestehende Öffnung (2–3) gesetzt: rückt an die nächste freie Stelle; ohne Platz keine. let mut r2 = r.clone(); r2.insert("openings".into(), json!([{"id": "a", "hostWallId": "w", "position": 2, "width": 1}])); let place = |pos: f64, width: f64| { let o = ops(&r2, &crate::model::lenient::typed_for_test(&r2), &req(json!({"cmd": "opening", "wall": "w", "start": [0, 0], "end": [6, 0], "kind": "window", "pos": pos, "width": width, "height": 1.2, "sill": 0.9}))).unwrap(); o.first().map(|_| items(&o, 0)[0]["position"].as_f64().unwrap()) }; assert_eq!(place(2.6, 1.0), Some(3.05)); assert_eq!(place(1.5, 1.0), Some(0.95)); assert_eq!(place(4.0, 1.0), Some(4.0)); assert_eq!(place(0.0, 3.0), None); let p = preview(&r, &crate::model::lenient::typed_for_test(&r), &json!({"cmd": "opening", "start": [0, 0], "end": [6, 0], "kind": "window", "width": 1.2, "pos": null}), &[2.0, 1.0]); assert_eq!(p.info[0], 2.0); assert_eq!(p.shapes.count, 2); } /// [145] Die Vorschau zeigt die Lage, die das Setzen ergibt (an die Wand geklemmt, an die nächste freie /// Stelle gerückt), nicht den Cursor-Ort. #[test] fn oeffnung_vorschau_zeigt_gerueckte_lage() { let r = root(json!({"walls": [{"id": "w", "floorId": "F1", "start": {"x": 0, "y": 0}, "end": {"x": 6, "y": 0}}], "openings": [{"id": "a", "hostWallId": "w", "position": 2, "width": 1}], "windowTypes": [{"id": "FT"}]})); let t = crate::model::lenient::typed_for_test(&r); let pos_of = |width: f64, cursor: f64, pos: Value| { let v = json!({"cmd": "opening", "wall": "w", "start": [0, 0], "end": [6, 0], "kind": "window", "width": width, "pos": pos}); let pv = preview(&r, &t, &v, &[cursor, 0.0]); let set = ops(&r, &t, &req(json!({"cmd": "opening", "wall": "w", "start": [0, 0], "end": [6, 0], "kind": "window", "pos": pos_or(&pv), "width": width, "height": 1.2, "sill": 0.9}))).unwrap(); (pv.info[0], pv.info[1], items(&set, 0)[0]["position"].as_f64().unwrap()) }; // Cursor über der Nachbaröffnung: rückt neben sie (Steg 5 cm), Setzen an derselben Stelle. let (p, from, set) = pos_of(1.0, 2.6, Value::Null); assert_eq!((p, from), (3.05, 3.05)); assert_eq!(set, 3.05); // Cursor am Wandende: die Lücke behält ihre Breite und rückt in die Wand. let (p, from, set) = pos_of(1.2, 5.9, Value::Null); assert_eq!((p, from, set), (4.8, 4.8, 4.8)); } /// [266] Treppe durch die Decke des Geschosses: Aussparung im selben Commit (Treppenumriss), nur wenn die /// Treppe aufwärts über die volle Geschosshöhe läuft und der Umriss ganz in der Decke liegt. #[test] fn treppe_legt_deckenloch_an() { let ceil = json!({"id": "C1", "type": "ceiling", "floorId": "F1", "outline": [{"x": 0, "y": 0}, {"x": 8, "y": 0}, {"x": 8, "y": 6}, {"x": 0, "y": 6}]}); let r = root(json!({"ceilings": [ceil]})); let t = crate::model::lenient::typed_for_test(&r); let stair = |start: [f64; 2], cursor: [f64; 2], up: bool, rise: Value| { let mut v = json!({"cmd": "stair", "shape": "straight", "up": up, "width": 1.0, "referenz": "mitte", "treadMode": "without", "auftritt": 0.28, "steps": null, "start": {"x": start[0], "y": start[1]}, "cursor": {"x": cursor[0], "y": cursor[1]}}); v["rise"] = rise; ops(&r, &t, &req(v)).unwrap() }; let o = stair([1.0, 2.0], [5.0, 2.0], true, Value::Null); assert_eq!(o.len(), 2, "Treppe + Aussparung"); let j = o[1].to_json(); assert_eq!(j["entity"]["id"], "C1"); let ring = j["entity"]["openings"][0].as_array().unwrap(); assert!(ring.len() >= 4); for q in ring { let (x, y) = (q["x"].as_f64().unwrap(), q["y"].as_f64().unwrap()); assert!((0.9..=5.1).contains(&x) && (1.4..=2.6).contains(&y), "{x},{y}"); } // abwärts, Teilhöhe, ausserhalb der Decke → nur die Treppe assert_eq!(stair([1.0, 2.0], [5.0, 2.0], false, Value::Null).len(), 1); assert_eq!(stair([1.0, 2.0], [5.0, 2.0], true, json!(1.5)).len(), 1); assert_eq!(stair([7.0, 2.0], [11.0, 2.0], true, Value::Null).len(), 1); } fn pos_or(p: &Preview) -> f64 { p.info[0] } }