From bf743a3235bc213f81c9f4ceb3e12c086480e7f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 08:43:18 +0000 Subject: [PATCH 1/3] =?UTF-8?q?[K4]=20Griffe=20im=20Kern:=20Griff-,=20Kant?= =?UTF-8?q?en-,=20Gr=C3=B6ssen-=20und=20Dicken-=C3=84nderungen=20rechnet?= =?UTF-8?q?=20grips.rs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Eckpunkt-Griffe (Wand, alle 2D-Formen), Verschieben, Kante winkeltreu, Grösse um einen Anker, Decke/Dach/Treppe/Raum, Raumstempel, Polylinien-Punkt einfügen/löschen und die Dicke einschichtiger Wände/Decken rechnet der Kern auf der Dokument-Wurzel; je Mausschritt ein Aufruf (doc_grip_commit: rechnen, prüfen, Verlauf). Griff-Listen und Kanten-Griffe über die Fassade geometry/grips.ts. Gelöscht: TS-Rechnung in projectSlice.ts, state/edgeGrips.ts, die Masszahl-Helfer in model/dimension.ts samt Bindung dim_text_frame. Gleichheit über 790 000 Zufalls-Änderungen, 19 800 Griff-Listen und 11 000 Store-Schritte (einmaliger Test, gelöscht); TODO.md nachgeführt. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- TODO.md | 25 + src-tauri/core/src/grips.rs | 1167 +++++++++++++++++ src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/queries.rs | 5 + src-tauri/core/src/web/drawings.rs | 16 - src-tauri/core/src/web/grips.rs | 81 ++ src-tauri/core/src/web/mod.rs | 2 +- src/App.tsx | 2 +- src/commands/cmds/ellipse.ts | 2 +- src/core/document.ts | 28 + src/core/extra.ts | 2 + src/core/ops.ts | 17 + src/geometry/grips.test.ts | 126 ++ src/geometry/grips.ts | 105 ++ src/geometry/polylinePoint.ts | 2 +- src/model/dimension.test.ts | 98 -- src/model/dimension.ts | 92 +- src/state/edgeGrips.test.ts | 42 - src/state/edgeGrips.ts | 58 - src/state/projectSlice.drawingGrips.test.ts | 2 +- .../projectSlice.leaderBendGrips.test.ts | 2 +- src/state/projectSlice.polylineBulge.test.ts | 2 +- src/state/projectSlice.textFrameGrips.test.ts | 2 +- src/state/projectSlice.ts | 1040 +-------------- src/state/useGripEditing.ts | 6 +- src/state/useMouseSelectionHandlers.ts | 2 +- src/text/textFrame.ts | 4 +- 27 files changed, 1639 insertions(+), 1292 deletions(-) create mode 100644 src-tauri/core/src/grips.rs delete mode 100644 src-tauri/core/src/web/drawings.rs create mode 100644 src-tauri/core/src/web/grips.rs create mode 100644 src/geometry/grips.test.ts create mode 100644 src/geometry/grips.ts delete mode 100644 src/model/dimension.test.ts delete mode 100644 src/state/edgeGrips.test.ts delete mode 100644 src/state/edgeGrips.ts diff --git a/TODO.md b/TODO.md index f89932e1..90c2717c 100644 --- a/TODO.md +++ b/TODO.md @@ -473,6 +473,31 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern (5) `model/wall.ts` (vertikale Ausdehnungen, Aufrufer in `toSection`/`voids`/Viewport — fallen mit dem Plan-Port); (6) `model/geometry.ts` (`wallBand`/`wallCorners`/`clippedBand`, Aufrufer in Werkzeugen/Fang), `model/color.ts` (Farbraum-Umrechnung der UI), `state/viewSnapshots.ts`/`visibilitySets.ts` (UI-Zustand, localStorage). + **Griffe im Kern (29.10.)** — erledigt damit (3) und aus (2) die Dicken: `grips.rs` (vorher ~800 Zeilen in `projectSlice.ts` + und `state/edgeGrips.ts`): Eckpunkt-Griff (`moveGrip`: Wand, alle 2D-Formen inkl. Bogen-Mitten-Griff der Polylinie, + Masslinien-Offset und Masszahl mit Einrasten, Textpfad/Hinweislinie/Spaltenbreite, Kreis↔Ellipse), Verschieben, Kante + winkeltreu (`movePolygonEdge`), Grösse um einen Anker (`resizeGeom`), Decke/Dach/Treppe/Raum (Griff, Verschieben, Kante, + Stempel), Polylinien-Punkt einfügen/löschen, Dicke einschichtiger Wände/Decken (id und Name eines neuen Typs gibt die + Hülle mit: `Date.now()`, `t()`). Rechnung auf der rohen Wurzel (unbekannte Felder, Schlüsselreihenfolge bleiben). Die + Store-Aktionen behalten ihre Signatur; je Mausschritt EIN Kern-Aufruf `doc_grip_commit` (rechnen, prüfen, Verlauf — + `ProjectDocument.commitGrip`), TS führt die Leseansicht mit den gelieferten Ops nach (NaN-Marken werden wieder Zahlen, + `fromMarkedJson`); die Wurzel-Abfrage `gripOps` rechnet ohne Anwenden. Griff-Listen (`drawingVertices`, `ringEdges`/ + `openEdges`/`polylineEdgeGrips`) über die Fassade `geometry/grips.ts` (Polylinie als flacher Puffer, sonst Element-JSON); + die Rahmen-Ecken einer Textspalte bleiben in TS (Schrift-Metrik, `textFrameCorners`). Gelöscht: die TS-Rechnung, + `state/edgeGrips.ts`, `dimTextFrame`/`dimTextPos`/`dimTextOffsetFromPoint`/`mmToModel`/`modelToMm` (`model/dimension.ts` hält + nur noch die Konstanten) und die Bindung `dim_text_frame`. Gleichheit (einmalig, Test gelöscht): 790 000 Zufalls-Änderungen + über 15 000 Projekte (alle Formen, entartete Geometrie, NaN/±∞ in den Eingaben, Bögen, LV95) — Ops zeichengleich zur alten + Fassung; 19 800 Griff-Listen samt Kanten-Griffen bitgleich; 11 000 Store-Schritte (Leseansicht, Undo-Tiefe, Kern == + Leseansicht). Abweichungen (gewollt): ein Griff-Index ohne Punkt (negativ, gebrochen, zu gross) ändert nichts (TS warf beim + Lesen von `undefined`, 38 000 der Zufallsfälle); gerechnet wird auf dem Dokument — ein dort als `null` gespeichertes NaN + rechnet wie `null` in JS (0) und kommt als `null` in die Leseansicht (vorher blieb dort NaN); Griff-Listen liefern −0 als 0. + Messung (vitest, 3000 Wände + 2000 Polylinien, alt/neu abwechselnd, Median, Container unter Last): Wand-Griff an Position + 10/1500/2990 39–43/198–218/324–348 µs → 40–44/192–193/318–337 µs (dominiert von der linearen id-Suche), Polylinien-Griff + 97–122 → 102–122 µs, Polylinien-Kante 108–138 → 109 µs, Wand verschieben 146–200 → 149–206 µs (gleich im Rahmen der + Streuung), Griff an einer 5000-Punkte-Polylinie 16–18 → 13–14 ms; Griff-Liste der 5000-Punkte-Polylinie 2,7 → 1,1 ms + (kleine Polylinie 2 → 4,5 µs). Nicht in der Tauri-App geprüft (vitest/Linux, e2e im Browser). Offen: `setPolylineVertexType` + (rechnet in `geometry/polylineVertexType.ts`), die lineare id-Suche je Mausschritt (im Kern beim Rechnen und beim Commit, + in TS in `applyOps`) und der Commit grosser Polylinien (~12 ms bei 5000 Punkten: Verlauf/Prüfung in `document.rs`/`ops.rs`). - ◐ **S4 Typen aus Rust**: `types.ts` wird aus den Rust-Strukturen erzeugt (ts-rs); Datei-I/O (`projectFormat`, Migration, IFC/DXF/ STEP-Ex- und -Import) im Kern. **Typen (28.10.):** Das Rust-Modell (`core/src/model/generated.rs`, `manual.rs`) ist die Quelle; ts-rs 12 (MIT, nur diff --git a/src-tauri/core/src/grips.rs b/src-tauri/core/src/grips.rs new file mode 100644 index 00000000..9a7cd790 --- /dev/null +++ b/src-tauri/core/src/grips.rs @@ -0,0 +1,1167 @@ +//! Griff-, Kanten- und Grössen-Geometrie der Bauteile ([K4] S3, vorher `state/projectSlice.ts` und +//! `state/edgeGrips.ts`): Eckpunkt-Griff ziehen (`moveGrip`), Element verschieben (`moveElementBy`), +//! Kante parallel verschieben (`moveEdge`, winkeltreu an den Nachbarkanten), Grösse um einen Anker +//! (`resizeElement`), Decken-/Dach-/Treppen-/Raum-Griffe, Raumstempel, Polylinien-Punkt einfügen/ +//! löschen und die Dicke einschichtiger Wände/Decken. Dazu die Griff-Listen (`drawingVertices`) und +//! die Kanten-Griffe (`ringEdges`/`openEdges`) für die Anzeige. +//! +//! Rechnung auf der rohen Projekt-Wurzel (`serde_json`, verlustfrei): ein geändertes Element behält +//! unbekannte Felder und die Schlüsselreihenfolge, genau wie das Objekt-Spreizen (`{...d, geom}`) in TS. +//! Ergebnis sind Ops (`replace`/`add`); keine Op, wo die TS-Fassung dasselbe Objekt zurückgab. +//! Zahlen wie in JS (`jsnum`, `jsmath`); nicht endliche Ergebnisse reisen als Marken (`"\u{1}NaN"`, +//! s. `ops.rs`), damit die Prüfung des Dokuments sie wie bisher zurückweist. +//! +//! Abweichung (gewollt): Ein Griff-Index, unter dem kein Punkt liegt (negativ, gebrochen, zu gross), ist +//! keine Änderung — TS warf dort beim Lesen von `undefined` einen Fehler. + +use crate::jsmath::hypot2; +use crate::jsnum; +use crate::ops::{id_of, Op}; +use serde_json::{Map, Value}; + +// ── JS-Zahlen in JSON ──────────────────────────────────────────────────────── + +/// Zahl als JSON-Wert wie nach `JSON.stringify` → `serde_json`: ganze Zahlen als Ganzzahl, sonst f64; +/// NaN/±∞ als Marke (`"\u{1}NaN"` …), −0 als 0. +pub fn js_num(x: f64) -> Value { + if x.is_nan() { + return Value::String("\u{1}NaN".into()); + } + if x.is_infinite() { + return Value::String(if x > 0.0 { "\u{1}Infinity" } else { "\u{1}-Infinity" }.into()); + } + if x.fract() == 0.0 { + if (0.0..18446744073709551616.0).contains(&x) { + return Value::from(x as u64); + } + if x < 0.0 && x >= -9223372036854775808.0 { + return Value::from(x as i64); + } + } + Value::from(x) +} + +/// Zahl eines JSON-Werts wie in JS-Arithmetik auf der Leseansicht: Zahl, Nicht-endlich-Marke, `null` = 0 +/// (so rechnet JS mit `null`; das Dokument speichert ein tief liegendes NaN als `null`, eine geladene +/// Datei liest es so zurück); fehlend und alles andere NaN. +pub fn num_of(v: Option<&Value>) -> f64 { + match v { + Some(Value::Number(n)) => n.as_f64().unwrap_or(f64::NAN), + Some(Value::Null) => 0.0, + Some(m) => match crate::ops::non_finite_mark(m) { + Some("Infinity") => f64::INFINITY, + Some("-Infinity") => f64::NEG_INFINITY, + _ => f64::NAN, + }, + None => f64::NAN, + } +} + +/// `a ?? b` für Zahlen (fehlend/`null` → `b`). +fn num_or(v: Option<&Value>, b: f64) -> f64 { + match v { + None | Some(Value::Null) => b, + v => num_of(v), + } +} + +/// JS-Wahrheitswert. +pub fn truthy(v: Option<&Value>) -> bool { + match v { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0 && !f.is_nan()), + Some(Value::String(s)) => !s.is_empty(), + Some(_) => true, + } +} + +fn nullish(v: Option<&Value>) -> bool { + matches!(v, None | Some(Value::Null)) +} + +/// Punkt `{x, y}` (wie ein neues Objekt-Literal in TS). +pub fn pt(x: f64, y: f64) -> Value { + let mut m = Map::new(); + m.insert("x".into(), js_num(x)); + m.insert("y".into(), js_num(y)); + Value::Object(m) +} + +/// `(x, y)` eines Punkt-Werts (fehlende Koordinaten NaN). +pub fn xy(v: &Value) -> (f64, f64) { + (num_of(v.get("x")), num_of(v.get("y"))) +} + +/// `{...v, key: val}` (vorhandener Schlüssel behält seine Stelle). Der ersetzte Wert wird nicht kopiert +/// (eine grosse Polylinie kostet sonst je Mausschritt eine Kopie mehr). +fn with(v: &Value, key: &str, val: Value) -> Value { + with_all(v, vec![(key, val)]) +} + +/// Wie [`with`] für mehrere Felder in einem Durchgang (`{...v, a, b}`). +fn with_all(v: &Value, fields: Vec<(&str, Value)>) -> Value { + with_opt(v, fields.into_iter().map(|(k, x)| (k, Some(x))).collect()) +} + +/// Wie [`with_all`]; `None` = `undefined` (das Feld fällt weg, wie in JSON). +fn with_opt(v: &Value, fields: Vec<(&str, Option)>) -> Value { + let mut fields: Vec<(&str, Option, bool)> = fields.into_iter().map(|(k, x)| (k, x, false)).collect(); + let src = v.as_object(); + let mut m = Map::with_capacity(src.map_or(0, Map::len) + fields.len()); + for (k, x) in src.into_iter().flatten() { + match fields.iter_mut().find(|(f, _, _)| *f == k) { + Some((_, new, done)) => { + *done = true; + if let Some(n) = new.take() { + m.insert(k.clone(), n); + } + } + None => { + m.insert(k.clone(), x.clone()); + } + } + } + for (k, x, done) in fields { + if let (false, Some(x)) = (done, x) { + m.insert(k.into(), x); + } + } + Value::Object(m) +} + +/// Zahl, die TS teils unverändert durchreicht (`ry: g.ry`): Wert für die Rechnung und JSON-Wert +/// (`None` = fehlend/`undefined`; ein `null` bleibt `null`). +#[derive(Clone)] +struct Pass { + f: f64, + v: Option, +} + +/// Unverändert durchgereichtes Feld. +fn pass(v: Option<&Value>) -> Pass { + Pass { f: num_of(v), v: v.cloned() } +} + +/// Neu gerechnete Zahl. +fn calc(f: f64) -> Pass { + Pass { f, v: Some(js_num(f)) } +} + +fn arr(v: Option<&Value>) -> &[Value] { + v.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]) +} + +/// Ganzzahliger Index in `0..len` (JS: `list[i]` trifft nur dann ein Element). +fn index_in(i: f64, len: usize) -> Option { + (i.fract() == 0.0 && i >= 0.0 && i < len as f64).then_some(i as usize) +} + +fn eq_index(i: usize, index: f64) -> bool { + i as f64 == index +} + +/// `pts.map((p, i) => i === index ? new : p)`. +fn replace_at(list: &[Value], index: f64, new: &Value) -> Value { + Value::Array(list.iter().enumerate().map(|(i, p)| if eq_index(i, index) { new.clone() } else { p.clone() }).collect()) +} + +fn moved(p: &Value, dx: f64, dy: f64) -> Value { + let (x, y) = xy(p); + pt(x + dx, y + dy) +} + +fn moved_all(list: &[Value], dx: f64, dy: f64) -> Value { + Value::Array(list.iter().map(|p| moved(p, dx, dy)).collect()) +} + +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)) +} + +fn replace(collection: &str, entity: Value) -> Op { + Op::Replace { collection: collection.into(), entity } +} + +fn with_geom(d: &Value, g: Value) -> Value { + with(d, "geom", g) +} + +// ── Anfrage ────────────────────────────────────────────────────────────────── + +/// Eine Änderung aus den Griff-Aktionen des Stores (JSON, Zahlen mit Nicht-endlich-Marken). +pub struct Request<'a>(&'a Value); + +impl<'a> Request<'a> { + fn n(&self, k: &str) -> f64 { + num_of(self.0.get(k)) + } + fn s(&self, k: &str) -> Option<&'a str> { + self.0.get(k).and_then(Value::as_str).filter(|s| !s.is_empty()) + } + /// Punkt als `[x, y]`. + fn p(&self, k: &str) -> (f64, f64) { + let a = arr(self.0.get(k)); + (num_of(a.first()), num_of(a.get(1))) + } +} + +/// Ergebnis: Ops und ggf. ein Hinweis-Schlüssel für die Hülle (i18n, z. B. zu wenige Punkte). +#[derive(Default)] +pub struct GripResult { + pub ops: Vec, + pub notice: Option<&'static str>, +} + +impl From> for GripResult { + fn from(ops: Vec) -> Self { + GripResult { ops, notice: None } + } +} + +/// Antwort-JSON `{"ops": […], "notice": …}` (Ops wie `CoreOp` in TS; `replace` ohne Kopie des Elements). +pub fn result_json(r: &GripResult) -> String { + let mut out = String::from("{\"ops\":["); + for (i, op) in r.ops.iter().enumerate() { + if i > 0 { + out.push(','); + } + match op { + Op::Replace { collection, entity } => { + out.push_str("{\"kind\":\"replace\",\"collection\":"); + out.push_str(&Value::from(collection.as_str()).to_string()); + out.push_str(",\"entity\":"); + out.push_str(&entity.to_string()); + out.push('}'); + } + op => out.push_str(&op.to_json().to_string()), + } + } + out.push(']'); + if let Some(n) = r.notice { + out.push_str(",\"notice\":"); + out.push_str(&Value::from(n).to_string()); + } + out.push('}'); + out +} + +/// Führt eine Griff-Änderung aus (`req.op` wählt die Art, s. `src/state/gripOps.ts`). +pub fn run(root: &Map, req: &Value) -> Result { + let r = Request(req); + let op = req.get("op").and_then(Value::as_str).unwrap_or(""); + let patch = |coll: &str, id: Option<&str>, f: &dyn Fn(&Value) -> Option| -> Vec { + id.and_then(|id| find(root, coll, id)).and_then(f).map(|e| vec![replace(coll, e)]).unwrap_or_default() + }; + Ok(match op { + "moveGrip" | "moveBy" | "moveEdge" => { + let (did, wid) = (r.s("drawingId"), r.s("wallId")); + // Jedes Element nur einmal suchen (lineare Suche, je Mausschritt). + let d = did.and_then(|i| find(root, "drawings2d", i)); + let w = wid.and_then(|i| find(root, "walls", i)); + // Objekt-Sperre: gesperrte Elemente lassen sich anwählen, aber nicht ziehen. + if d.is_some_and(|d| truthy(d.get("locked"))) || w.is_some_and(|w| truthy(w.get("locked"))) { + return Ok(GripResult::default()); + } + let f: Box Option> = match op { + "moveGrip" => { + let (index, (x, y), scale) = (r.n("index"), r.p("pt"), r.n("scale")); + Box::new(move |e, wall| if wall { Some(wall_grip(e, index, x, y)) } else { drawing_grip(e, index, x, y, scale) }) + } + "moveBy" => { + let (dx, dy) = r.p("delta"); + Box::new(move |e, wall| if wall { Some(wall_moved(e, dx, dy)) } else { drawing_moved(e, dx, dy) }) + } + _ => { + let (a, b, (dx, dy)) = (r.n("a"), r.n("b"), r.p("delta")); + Box::new(move |e, wall| if wall { Some(wall_moved(e, dx, dy)) } else { drawing_edge(e, a, b, dx, dy) }) + } + }; + // Mit Zeichnung wird nur sie geändert (die Wand zählt dann nur für die Sperre). + let (coll, e, wall) = if did.is_some() { ("drawings2d", d, false) } else { ("walls", w, true) }; + e.and_then(|e| f(e, wall)).map(|e| vec![replace(coll, e)]).unwrap_or_default().into() + } + "resize" => { + let (w, h, fx, fy) = (r.n("w"), r.n("h"), r.n("fx"), r.n("fy")); + if r.s("kind") == Some("drawing2d") { + patch("drawings2d", r.s("id"), &|d| resize_geom(d.get("geom")?, w, h, fx, fy).map(|g| with_geom(d, g))).into() + } else { + patch("walls", r.s("id"), &|wall| { + let s = xy(wall.get("start").unwrap_or(&Value::Null)); + let e = xy(wall.get("end").unwrap_or(&Value::Null)); + let (ax, ay, sx, sy) = scale_around(bbox(&[s, e]), w, h, fx, fy); + let f = |p: (f64, f64)| pt(ax + (p.0 - ax) * sx, ay + (p.1 - ay) * sy); + Some(with_all(wall, vec![("start", f(s)), ("end", f(e))])) + }) + .into() + } + } + "ceilingGrip" | "roomGrip" => { + let (coll, field) = if op == "ceilingGrip" { ("ceilings", "outline") } else { ("rooms", "boundary") }; + let (index, (x, y)) = (r.n("index"), r.p("pt")); + patch(coll, r.s("id"), &|e| Some(with(e, field, replace_at(e.get(field)?.as_array()?, index, &pt(x, y))))).into() + } + "ceilingBy" | "roofBy" => { + let coll = if op == "ceilingBy" { "ceilings" } else { "roofs" }; + let (dx, dy) = r.p("delta"); + patch(coll, r.s("id"), &|e| Some(with(e, "outline", moved_all(e.get("outline")?.as_array()?, dx, dy)))).into() + } + "ceilingEdge" | "roomEdge" => { + let (coll, field) = if op == "ceilingEdge" { ("ceilings", "outline") } else { ("rooms", "boundary") }; + let (a, b, (dx, dy)) = (r.n("a"), r.n("b"), r.p("delta")); + patch(coll, r.s("id"), &|e| Some(with(e, field, move_polygon_edge(e.get(field)?.as_array()?, a, b, dx, dy, true)?))).into() + } + "roofGrip" => { + let (index, (x, y)) = (r.n("index"), r.p("pt")); + patch("roofs", r.s("id"), &|e| roof_grip(e, index, x, y)).into() + } + "stairBy" => { + let (dx, dy) = r.p("delta"); + patch("stairs", r.s("id"), &|s| { + let mut out = with(s, "start", moved(s.get("start").unwrap_or(&Value::Null), dx, dy)); + if truthy(s.get("center")) { + out = with(&out, "center", moved(&s["center"], dx, dy)); + } + Some(out) + }) + .into() + } + "roomBy" => { + let (dx, dy) = r.p("delta"); + patch("rooms", r.s("id"), &|rm| { + let mut out = with(rm, "boundary", moved_all(rm.get("boundary")?.as_array()?, dx, dy)); + if truthy(rm.get("stampAnchor")) { + out = with(&out, "stampAnchor", moved(&rm["stampAnchor"], dx, dy)); + } + Some(out) + }) + .into() + } + "roomStamp" => { + let (dx, dy) = r.p("delta"); + patch("rooms", r.s("id"), &|rm| { + let base = match rm.get("stampAnchor") { + Some(a) if !a.is_null() => xy(a), + _ => { + let ring: Vec<[f64; 2]> = arr(rm.get("boundary")).iter().map(|p| xy(p).into()).collect(); + let c = crate::room_area::evaluate(&ring, 0.0).centroid; + (c[0], c[1]) + } + }; + Some(with(rm, "stampAnchor", pt(base.0 + dx, base.1 + dy))) + }) + .into() + } + "insertPoint" => { + let (seg, (x, y)) = (r.n("seg"), r.p("pt")); + patch("drawings2d", r.s("id"), &|d| insert_point(d, seg, x, y)).into() + } + "deletePoint" => { + let index = r.n("index"); + let Some(d) = r.s("id").and_then(|i| find(root, "drawings2d", i)) else { return Ok(GripResult::default()) }; + let g = d.get("geom").unwrap_or(&Value::Null); + if g.get("shape").and_then(Value::as_str) != Some("polyline") { + return Ok(GripResult::default()); + } + let pts = arr(g.get("pts")); + let min = if truthy(g.get("closed")) { 4 } else { 3 }; + if pts.len() < min { + return Ok(GripResult { ops: vec![], notice: Some("alert.polylineMinPoints") }); + } + let Some(k) = index_in(index, pts.len()) else { return Ok(GripResult::default()) }; + // Zwei Segmente werden eins: der Bogen des entfernten Segments fällt weg, das verbleibende behält + // seinen (die genaue Bogenform lässt sich ohne den Stützpunkt nicht erhalten). + let drop = |l: &[Value]| Value::Array(l.iter().enumerate().filter(|(i, _)| *i != k).map(|(_, v)| v.clone()).collect()); + let mut fields = vec![("pts", drop(pts))]; + if truthy(g.get("bulge")) { + fields.push(("bulge", drop(arr(g.get("bulge"))))); + } + vec![replace("drawings2d", with_geom(d, with_all(g, fields)))].into() + } + "wallThickness" => wall_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.get("newName").cloned().unwrap_or(Value::Null)).into(), + "ceilingThickness" => ceiling_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.get("newName").cloned().unwrap_or(Value::Null)).into(), + other => return Err(format!("Unbekannte Griff-Änderung: {other}")), + }) +} + +// ── Wand ───────────────────────────────────────────────────────────────────── + +fn wall_grip(w: &Value, index: f64, x: f64, y: f64) -> Value { + with(w, if index == 0.0 { "start" } else { "end" }, pt(x, y)) +} + +fn wall_moved(w: &Value, dx: f64, dy: f64) -> Value { + let s = moved(w.get("start").unwrap_or(&Value::Null), dx, dy); + let e = moved(w.get("end").unwrap_or(&Value::Null), dx, dy); + with_all(w, vec![("start", s), ("end", e)]) +} + +// ── 2D-Zeichnungen ─────────────────────────────────────────────────────────── + +fn shape(g: &Value) -> &str { + g.get("shape").and_then(Value::as_str).unwrap_or("") +} + +/// Kreis, solange rx≈ry (relative Toleranz 0.5 %) — sonst Ellipse (rotation 0). Neues Objekt (weitere +/// Felder der alten Form entfallen, wie in TS). +fn ellipse_or_circle(center: Option<&Value>, rx: Pass, ry: Pass) -> Value { + let mut m = Map::new(); + let mut put = |k: &str, v: Option| { + if let Some(v) = v { + m.insert(k.into(), v); + } + }; + if (rx.f - ry.f).abs() <= 0.005 * jsnum::max(rx.f, ry.f) { + put("shape", Some("circle".into())); + put("center", center.cloned()); + put("r", Some(js_num((rx.f + ry.f) / 2.0))); + } else { + put("shape", Some("ellipse".into())); + put("center", center.cloned()); + put("rx", rx.v); + put("ry", ry.v); + put("rotation", Some(Value::from(0u64))); + } + Value::Object(m) +} + +/// `mmToModel`: Papier-mm → Modell-Meter beim Massstab 1:N. +fn mm_to_model(mm: f64, scale: f64) -> f64 { + (mm / 1000.0) * scale +} + +fn model_to_mm(m: f64, scale: f64) -> f64 { + (m * 1000.0) / scale +} + +/// Standard-Schrifthöhe der Masszahl (Papier-mm, `DIM_DEFAULTS_MM.textHeight`). +const DIM_TEXT_HEIGHT_MM: f64 = 4.0; + +/// `dimTextFrame` der TS-Fassade: bei nicht endlichen Eingaben alles NaN. +fn dim_frame(a: (f64, f64), b: (f64, f64), offset: f64, h: f64) -> ((f64, f64), (f64, f64), (f64, f64)) { + if ![a.0, a.1, b.0, b.1, offset, h].iter().all(|v| v.is_finite()) { + let n = (f64::NAN, f64::NAN); + return (n, n, n); + } + let v = |p: (f64, f64)| crate::model::Vec2 { x: p.0, y: p.1 }; + let (base, read, up, _) = crate::plan::drawings::dim_text_frame(v(a), v(b), offset, h); + ((base.x, base.y), (read.x, read.y), (up.x, up.y)) +} + +/// `dimTextPos`: Lage der Masszahl inkl. Versatz (Modell-Meter). +fn dim_text_pos(a: (f64, f64), b: (f64, f64), offset: f64, h: f64, along: f64, perp: f64) -> (f64, f64) { + let (base, read, up) = dim_frame(a, b, offset, h); + (base.0 + read.0 * along + up.0 * perp, base.1 + read.1 * along + up.1 * perp) +} + +/// Schrifthöhe der Masszahl in Modell-Metern. +fn dim_height(g: &Value, scale: f64) -> f64 { + mm_to_model(num_or(g.get("textHeightMm"), DIM_TEXT_HEIGHT_MM), scale) +} + +/// Griff `index` einer 2D-Zeichnung auf (x, y) (`moveGrip`); `None` = keine Änderung. +fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option { + let g = d.get("geom")?; + let p = pt(x, y); + let set = |k: &str, v: Value| Some(with_geom(d, with(g, k, v))); + match shape(g) { + "line" | "xline" | "ray" => set(if index == 0.0 { "a" } else { "b" }, p), + "polyline" => { + let pts = arr(g.get("pts")); + let n = pts.len(); + if index < n as f64 { + return set("pts", replace_at(pts, index, &p)); + } + // Bulge-Griff (Index ≥ n): Segment-Mitte senkrecht zur Sehne → Bogen dieses Segments. + let seg = index - n as f64; + let k = index_in(seg, n)?; + let a = xy(&pts[k]); + let b = xy(if k == n - 1 { &pts[0] } else { &pts[k + 1] }); + let val = crate::bulge::from_sagitta_point(a.0, a.1, b.0, b.1, x, y); + let mut bulge: Vec = arr(g.get("bulge")).to_vec(); + while bulge.len() <= k { + bulge.push(Value::from(0u64)); + } + bulge[k] = js_num(val); + set("bulge", Value::Array(bulge)) + } + "bezier" | "spline" => set("pts", replace_at(arr(g.get("pts")), index, &p)), + "dimension" => { + let pts = arr(g.get("pts")); + let n = pts.len(); + if index < n as f64 { + return set("pts", replace_at(pts, index, &p)); + } + if index == n as f64 { + // Griff auf der Masslinie: nur `offset` (Normalabstand zur Punktreihe). + let (a, b) = (xy(pts.first()?), xy(pts.last()?)); + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let len = or1(hypot2(dx, dy)); + let (nx, ny) = (-dy / len, dx / len); + return set("offset", js_num((x - a.0) * nx + (y - a.1) * ny)); + } + // Masszahl-Griff: nur die Zahl des Segments, rastet nahe der Standardlage ein. + let seg = index - n as f64 - 1.0; + if seg < 0.0 || seg >= n as f64 - 1.0 { + return None; + } + let k = index_in(seg, n)?; + let h = dim_height(g, scale); + let (base, read, up) = dim_frame(xy(&pts[k]), xy(&pts[k + 1]), num_of(g.get("offset")), h); + let (vx, vy) = (x - base.0, y - base.1); + let snap = h * 0.5; + let along = vx * read.0 + vy * read.1; + let perp = vx * up.0 + vy * up.1; + let along = if along.abs() < snap { 0.0 } else { along }; + let perp = if perp.abs() < snap { 0.0 } else { perp }; + let mut next = Map::new(); + next.insert("along".into(), js_num(model_to_mm(along, scale))); + next.insert("perp".into(), js_num(model_to_mm(perp, scale))); + let old = arr(g.get("textOffsetsMm")); + let offs: Vec = (0..n - 1) + .map(|i| { + if i == k { + Value::Object(next.clone()) + } else { + match old.get(i) { + Some(v) if !v.is_null() => v.clone(), + _ => serde_json::json!({"along": 0, "perp": 0}), + } + } + }) + .collect(); + set("textOffsetsMm", Value::Array(offs)) + } + "rect" | "image" => { + let corners = rect_corners(g); + let r = (index + 2.0) % 4.0; + let opp = corners[index_in(r, 4)?]; + let min = pt(jsnum::min(x, opp.0), jsnum::min(y, opp.1)); + let max = pt(jsnum::max(x, opp.0), jsnum::max(y, opp.1)); + Some(with_geom(d, with_all(g, vec![("min", min), ("max", max)]))) + } + "text" => { + if truthy(g.get("pathPts")) { + return set("pathPts", replace_at(arr(g.get("pathPts")), index, &p)); + } + if truthy(g.get("leaderTarget")) { + let bends = arr(g.get("leaderBendPoints")); + let tip = bends.len() as f64 + 1.0; + if index == 0.0 { + return set("at", p); + } + if index == tip { + return set("leaderTarget", p); + } + if index > 0.0 && index < tip { + let v = Value::Array(bends.iter().enumerate().map(|(i, bp)| if i as f64 == index - 1.0 { p.clone() } else { bp.clone() }).collect()); + return set("leaderBendPoints", v); + } + return None; + } + let width = num_of(g.get("width")); + if truthy(g.get("width")) && width > 0.0 && index >= 0.0 && index < 4.0 { + // Nur die Spaltenbreite ändert sich (InDesign-Textrahmen); Zug auf die lokale x-Achse. + let angle = num_of(g.get("angle")); + let (cos, sin) = (jsnum::cos(angle), jsnum::sin(angle)); + let (ax, ay) = xy(g.get("at").unwrap_or(&Value::Null)); + let local_x = (x - ax) * cos + (y - ay) * sin; + const MIN_WIDTH: f64 = 0.1; + if index == 0.0 || index == 3.0 { + let w = jsnum::max(MIN_WIDTH, width - local_x); + let at = pt(ax + local_x * cos, ay + local_x * sin); + return Some(with_geom(d, with_all(g, vec![("at", at), ("width", js_num(w))]))); + } + return set("width", js_num(jsnum::max(MIN_WIDTH, local_x))); + } + set("at", p) + } + "kote" | "detailref" | "scalebar" | "pointmarker" | "block" => set("at", p), + "circle" => { + let (cx, cy) = xy(g.get("center").unwrap_or(&Value::Null)); + let r = pass(g.get("r")); + let (rx, ry) = if index == 0.0 { (calc(jsnum::max(1e-3, (x - cx).abs())), r) } else { (r, calc(jsnum::max(1e-3, (y - cy).abs()))) }; + Some(with_geom(d, ellipse_or_circle(g.get("center"), rx, ry))) + } + "arc" => { + let (cx, cy) = xy(g.get("center").unwrap_or(&Value::Null)); + if index == 2.0 { + return set("r", js_num(jsnum::max(1e-3, hypot2(x - cx, y - cy)))); + } + set(if index == 0.0 { "a0" } else { "a1" }, js_num(jsnum::atan2(y - cy, x - cx))) + } + "ellipse" => { + let rot = num_of(g.get("rotation")); + let (c, s) = (jsnum::cos(rot), jsnum::sin(rot)); + let (cx, cy) = xy(g.get("center").unwrap_or(&Value::Null)); + let (dx, dy) = (x - cx, y - cy); + let lx = dx * c + dy * s; + let ly = -dx * s + dy * c; + let rx = if index == 0.0 { calc(jsnum::max(1e-3, lx.abs())) } else { pass(g.get("rx")) }; + let ry = if index == 0.0 { pass(g.get("ry")) } else { calc(jsnum::max(1e-3, ly.abs())) }; + // Nur ungedreht (`rotation === 0`) kann eine (fast) gleichseitige Ellipse wieder zum Kreis werden. + if g.get("rotation").and_then(Value::as_f64) == Some(0.0) { + return Some(with_geom(d, ellipse_or_circle(g.get("center"), rx, ry))); + } + Some(with_geom(d, with_opt(g, vec![("rx", rx.v), ("ry", ry.v)]))) + } + _ => None, + } +} + +/// `x || 1` für eine Länge (0 und NaN → 1). +fn or1(l: f64) -> f64 { + if l == 0.0 || l.is_nan() { + 1.0 + } else { + l + } +} + +/// Ecken eines Rechtecks/Bilds in Griff-Reihenfolge: min, (max.x, min.y), max, (min.x, max.y). +fn rect_corners(g: &Value) -> [(f64, f64); 4] { + let mn = xy(g.get("min").unwrap_or(&Value::Null)); + let mx = xy(g.get("max").unwrap_or(&Value::Null)); + [mn, (mx.0, mn.1), mx, (mn.0, mx.1)] +} + +/// Ganze 2D-Zeichnung verschieben (`moveElementBy`); `None` = Form ohne Verschiebung. +fn drawing_moved(d: &Value, dx: f64, dy: f64) -> Option { + let g = d.get("geom")?; + let mv = |k: &str| moved(g.get(k).unwrap_or(&Value::Null), dx, dy); + let ng = match shape(g) { + "line" => with_all(g, vec![("a", mv("a")), ("b", mv("b"))]), + "polyline" | "bezier" | "spline" | "dimension" => with(g, "pts", moved_all(arr(g.get("pts")), dx, dy)), + "rect" | "image" => with_all(g, vec![("min", mv("min")), ("max", mv("max"))]), + "circle" | "arc" | "ellipse" => with(g, "center", mv("center")), + "kote" | "detailref" | "scalebar" | "pointmarker" | "text" => with(g, "at", mv("at")), + _ => return None, + }; + Some(with_geom(d, ng)) +} + +/// Kante (a, b) einer 2D-Zeichnung verschieben (`moveEdge`); `None` = keine Änderung. +fn drawing_edge(d: &Value, a: f64, b: f64, dx: f64, dy: f64) -> Option { + let g = d.get("geom")?; + let ng = match shape(g) { + "line" => with_all(g, vec![("a", moved(g.get("a").unwrap_or(&Value::Null), dx, dy)), ("b", moved(g.get("b").unwrap_or(&Value::Null), dx, dy))]), + "polyline" | "spline" => with(g, "pts", move_polygon_edge(arr(g.get("pts")), a, b, dx, dy, truthy(g.get("closed")))?), + "rect" | "image" => { + // Die zwei Kanten-Ecken verschieben, dann die bbox neu bilden (achsparallel). + let corners = rect_corners(g); + let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for (i, c) in corners.iter().enumerate() { + let c = if eq_index(i, a) || eq_index(i, b) { (c.0 + dx, c.1 + dy) } else { *c }; + x0 = jsnum::min(x0, c.0); + y0 = jsnum::min(y0, c.1); + x1 = jsnum::max(x1, c.0); + y1 = jsnum::max(y1, c.1); + } + with_all(g, vec![("min", pt(x0, y0)), ("max", pt(x1, y1))]) + } + _ => return None, + }; + Some(with_geom(d, ng)) +} + +/// Schnittpunkt der Geraden a + t·da mit b + s·db (`lineIntersect`); `None` bei (fast) parallelen. +fn line_intersect(a: (f64, f64), da: (f64, f64), b: (f64, f64), db: (f64, f64)) -> Option<(f64, f64)> { + let cross = |p: (f64, f64), q: (f64, f64)| p.0 * q.1 - p.1 * q.0; + let denom = cross(da, db); + if denom.abs() < 1e-9 { + return None; + } + let t = cross((b.0 - a.0, b.1 - a.1), db) / denom; + Some((a.0 + da.0 * t, a.1 + da.1 * t)) +} + +/// Neue Lage eines Eckpunkts, dessen eine Kante parallel verschoben wird: er wandert entlang seiner +/// anderen (unverschobenen) Nachbarkante (`edgeMoveVertex`); ohne Nachbarn oder bei paralleler +/// Nachbarkante einfach um das Delta. +fn edge_move_vertex(v: (f64, f64), neighbor: Option<(f64, f64)>, shifted: (f64, f64), edge_dir: (f64, f64), dx: f64, dy: f64) -> (f64, f64) { + let fallback = (v.0 + dx, v.1 + dy); + let Some(nb) = neighbor else { return fallback }; + let nd = (v.0 - nb.0, v.1 - nb.1); + if hypot2(nd.0, nd.1) < 1e-9 { + return fallback; + } + line_intersect(nb, nd, shifted, edge_dir).unwrap_or(fallback) +} + +/// Nachbar-Index von `i` in Richtung `dir` (`ringNeighbor`): `None` am offenen Ende oder wenn er auf +/// die andere Kanten-Ecke fiele. +fn ring_neighbor(i: usize, n: usize, closed: bool, dir: i64, excluding: usize) -> Option { + let j = i as i64 + dir; + let k = if j >= 0 && j < n as i64 { + Some(j as usize) + } else if closed { + Some(j.rem_euclid(n as i64) as usize) + } else { + None + }; + k.filter(|&k| k != excluding) +} + +/// Kante (a, b) eines Rings/einer Kette um das Delta verschieben, winkeltreu an den Nachbar-Ecken +/// (`movePolygonEdge`); `None`, wenn a oder b kein Punkt ist. +pub fn move_polygon_edge(pts: &[Value], a: f64, b: f64, dx: f64, dy: f64, closed: bool) -> Option { + let n = pts.len(); + let (ai, bi) = (index_in(a, n)?, index_in(b, n)?); + let (pa, pb) = (xy(&pts[ai]), xy(&pts[bi])); + let shifted = (pa.0 + dx, pa.1 + dy); + let edge_dir = (pb.0 - pa.0, pb.1 - pa.1); + let prev = ring_neighbor(ai, n, closed, -1, bi).map(|k| xy(&pts[k])); + let next = ring_neighbor(bi, n, closed, 1, ai).map(|k| xy(&pts[k])); + Some(Value::Array( + pts.iter() + .enumerate() + .map(|(i, p)| { + if i == ai { + let q = edge_move_vertex(pa, prev, shifted, edge_dir, dx, dy); + pt(q.0, q.1) + } else if i == bi { + let q = edge_move_vertex(pb, next, shifted, edge_dir, dx, dy); + pt(q.0, q.1) + } else { + p.clone() + } + }) + .collect(), + )) +} + +// ── Grösse um einen Anker ──────────────────────────────────────────────────── + +type BBox = (f64, f64, f64, f64); + +/// bbox einer Punktliste (`bbox2`; nicht endlich → Null-Box). +fn bbox(pts: &[(f64, f64)]) -> BBox { + let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for p in pts { + x0 = jsnum::min(x0, p.0); + y0 = jsnum::min(y0, p.1); + x1 = jsnum::max(x1, p.0); + y1 = jsnum::max(y1, p.1); + } + if !x0.is_finite() { + return (0.0, 0.0, 0.0, 0.0); + } + (x0, y0, x1, y1) +} + +/// Anker und Faktoren, um eine bbox auf w × h zu bringen (`scaleAround`; Null-Ausdehnung → Faktor 1). +fn scale_around(b: BBox, w: f64, h: f64, fx: f64, fy: f64) -> (f64, f64, f64, f64) { + let bw = b.2 - b.0; + let bh = b.3 - b.1; + let ax = b.0 + fx * bw; + let ay = b.1 + fy * bh; + let sx = if bw > 1e-9 { w / bw } else { 1.0 }; + let sy = if bh > 1e-9 { h / bh } else { 1.0 }; + (ax, ay, sx, sy) +} + +/// 2D-Form auf w × h um den Anker skalieren (`resizeGeom`); `None` = Form bleibt (Kote, Bemassung …). +fn resize_geom(g: &Value, w: f64, h: f64, fx: f64, fy: f64) -> Option { + let p = |k: &str| xy(g.get(k).unwrap_or(&Value::Null)); + let pts_of = |k: &str| arr(g.get(k)).iter().map(xy).collect::>(); + let scaled = |(ax, ay, sx, sy): (f64, f64, f64, f64), q: (f64, f64)| (ax + (q.0 - ax) * sx, ay + (q.1 - ay) * sy); + let ptv = |q: (f64, f64)| pt(q.0, q.1); + Some(match shape(g) { + "line" | "xline" | "ray" => { + let (a, b) = (p("a"), p("b")); + let s = scale_around(bbox(&[a, b]), w, h, fx, fy); + with_all(g, vec![("a", ptv(scaled(s, a))), ("b", ptv(scaled(s, b)))]) + } + "polyline" | "bezier" | "spline" => { + let pts = pts_of("pts"); + let s = scale_around(bbox(&pts), w, h, fx, fy); + with(g, "pts", Value::Array(pts.iter().map(|q| ptv(scaled(s, *q))).collect())) + } + "rect" | "image" => { + let (mn, mx) = (p("min"), p("max")); + let s = scale_around(bbox(&[mn, mx]), w, h, fx, fy); + let (a, b) = (scaled(s, mn), scaled(s, mx)); + with_all(g, vec![("min", pt(jsnum::min(a.0, b.0), jsnum::min(a.1, b.1))), ("max", pt(jsnum::max(a.0, b.0), jsnum::max(a.1, b.1)))]) + } + "circle" | "arc" => { + // bbox eines Kreises ist 2r × 2r; Radius = grössere Zielhälfte, Mitte nicht-uniform um den Anker. + let c = p("center"); + let r = num_of(g.get("r")); + let ax = (c.0 - r) + fx * (2.0 * r); + let ay = (c.1 - r) + fy * (2.0 * r); + let half = jsnum::max(w, h) / 2.0; + let nr = if half > 0.0 { Some(js_num(half)) } else { g.get("r").cloned() }; + let sx = if r > 1e-9 { (w / 2.0) / r } else { 1.0 }; + let sy = if r > 1e-9 { (h / 2.0) / r } else { 1.0 }; + with_opt(g, vec![("center", Some(pt(ax + (c.0 - ax) * sx, ay + (c.1 - ay) * sy))), ("r", nr)]) + } + "ellipse" => { + let c = p("center"); + let (rx, ry) = (num_of(g.get("rx")), num_of(g.get("ry"))); + let (ax, ay, sx, sy) = scale_around((c.0 - rx, c.1 - ry, c.0 + rx, c.1 + ry), w, h, fx, fy); + with_all(g, vec![("center", pt(ax + (c.0 - ax) * sx, ay + (c.1 - ay) * sy)), ("rx", js_num(jsnum::max(1e-3, rx * sx))), ("ry", js_num(jsnum::max(1e-3, ry * sy)))]) + } + "text" | "block" => { + // Nur die Einfügeposition wandert (Schrifthöhe bzw. Symbol bleiben). + let at = p("at"); + let s = scale_around((at.0, at.1, at.0, at.1), w, h, fx, fy); + with(g, "at", ptv(scaled(s, at))) + } + _ => return None, + }) +} + +// ── Dach, Polylinien-Punkte, Dicken ────────────────────────────────────────── + +/// Dach-Eckgriff: die gegenüberliegende Ecke bleibt fix, der Umriss bleibt ein achsparalleles Rechteck. +fn roof_grip(r: &Value, index: f64, x: f64, y: f64) -> Option { + let outline = r.get("outline")?.as_array()?; + let n = outline.len(); + if n < 4 { + return None; + } + let k = index_in((index + 2.0) % n as f64, n)?; + let opp = xy(&outline[k]); + let (x0, x1) = (jsnum::min(x, opp.0), jsnum::max(x, opp.0)); + let (y0, y1) = (jsnum::min(y, opp.1), jsnum::max(y, opp.1)); + Some(with(r, "outline", Value::Array(vec![pt(x0, y0), pt(x1, y0), pt(x1, y1), pt(x0, y1)]))) +} + +/// Punkt in Segment `seg` einer Polylinie einfügen. Ein Bogen wird exakt über die Kreisgeometrie in der +/// Winkel-Mitte geteilt (wie `kernel2d` Bogen-Segmente zuschneidet); eine Näherung über tessellierte +/// Punkte wäre zu ungenau. Die Bulge-Liste wird nur mitgeführt, wenn es eine gab. +fn insert_point(d: &Value, seg: f64, x: f64, y: f64) -> Option { + let g = d.get("geom")?; + if shape(g) != "polyline" { + return None; + } + let pts = arr(g.get("pts")); + let n = pts.len(); + let k = index_in(seg, n)?; + let last = k == n - 1; + if last && !truthy(g.get("closed")) { + return None; + } + let a = xy(&pts[k]); + let b = xy(if last { &pts[0] } else { &pts[k + 1] }); + let bulge = num_or(arr(g.get("bulge")).get(k), 0.0); + // `bulgeArc` der Fassade: gerade (|bulge| < 1e-9 oder NaN) ohne Bogen. + let arc = if bulge.abs() >= 1e-9 { crate::bulge::arc(a.0, a.1, b.0, b.1, bulge) } else { vec![] }; + let (insert, b1, b2) = if arc.len() >= 6 { + let (cx, cy, r, a0, a1, sweep) = (arc[0], arc[1], arc[2], arc[3], arc[4], arc[5]); + let mid = a0 + sweep / 2.0; + let sign = if sweep < 0.0 { -1.0 } else { 1.0 }; + ( + pt(cx + r * jsnum::cos(mid), cy + r * jsnum::sin(mid)), + crate::bulge::between_angles(cx, cy, r, a0, mid, sign), + crate::bulge::between_angles(cx, cy, r, mid, a1, sign), + ) + } else { + (pt(x, y), 0.0, 0.0) + }; + let mut np: Vec = pts[..=k].to_vec(); + np.push(insert); + np.extend_from_slice(&pts[k + 1..]); + let mut fields = vec![("pts", Value::Array(np))]; + if truthy(g.get("bulge")) { + let old = arr(g.get("bulge")); + let mut nb: Vec = old.iter().take(k).cloned().collect(); + nb.push(js_num(b1)); + nb.push(js_num(b2)); + nb.extend(old.iter().skip(k + 1).cloned()); + fields.push(("bulge", Value::Array(nb))); + } + Some(with_geom(d, with_all(g, fields))) +} + +/// `{...layers[0], thickness}` als einzige Schicht. +fn single_layer(layers: &[Value], thickness: f64) -> Value { + Value::Array(vec![with(&layers[0], "thickness", js_num(thickness))]) +} + +/// Neuer einschichtiger Typ `{id, name, layers}`. +fn new_type(id: &str, name: Value, layers: &[Value], thickness: f64) -> Value { + let mut m = Map::new(); + m.insert("id".into(), id.into()); + m.insert("name".into(), name); + m.insert("layers".into(), single_layer(layers, thickness)); + Value::Object(m) +} + +fn add(collection: &str, item: Value) -> Op { + Op::Add { collection: collection.into(), items: vec![item], at: None } +} + +/// Dicke einer einschichtigen Wand (`setWallThickness`): exklusiven einschichtigen Wandtyp direkt +/// ändern, sonst einen eigenen Typ `new_id`/`new_name` anlegen und der Wand zuweisen. +fn wall_thickness(root: &Map, wall_id: &str, thickness: f64, new_id: &str, new_name: Value) -> Vec { + if !thickness.is_finite() || thickness <= 0.0 { + return vec![]; + } + let Some(wall) = find(root, "walls", wall_id) else { return vec![] }; + let wt_id = wall.get("wallTypeId"); + let Some(wt) = arr(root.get("wallTypes")).iter().find(|t| t.get("id") == wt_id) else { return vec![] }; + let layers = arr(wt.get("layers")); + if layers.is_empty() { + return vec![]; + } + let wt_idv = wt.get("id"); + let used_by_others = arr(root.get("walls")).iter().any(|w| id_of(w) != Some(wall_id) && w.get("wallTypeId") == wt_idv); + if layers.len() == 1 && !used_by_others { + let tid = id_of(wt).unwrap_or(""); + return find(root, "wallTypes", tid).map(|t| vec![replace("wallTypes", with(t, "layers", single_layer(arr(t.get("layers")), thickness)))]).unwrap_or_default(); + } + vec![add("wallTypes", new_type(new_id, new_name, layers, thickness)), replace("walls", with(wall, "wallTypeId", new_id.into()))] +} + +/// Dicke einer einschichtigen Decke (`setCeilingThickness`), analog zur Wand; der geteilte +/// Alt-Wandtyp (`Ceiling.wallTypeId`) wird nie verändert. +fn ceiling_thickness(root: &Map, ceiling_id: &str, thickness: f64, new_id: &str, new_name: Value) -> Vec { + if !thickness.is_finite() || thickness <= 0.0 { + return vec![]; + } + let Some(c) = find(root, "ceilings", ceiling_id) else { return vec![] }; + let active = |c: &Value| -> Option { + let v = c.get("ceilingTypeId"); + if nullish(v) { c.get("wallTypeId").cloned() } else { v.cloned() } + }; + let active_id = active(c); + let by_id = |coll: &str, id: Option<&Value>| arr(root.get(coll)).iter().find(|t| t.get("id") == id).cloned(); + let Some(ct) = by_id("ceilingTypes", c.get("ceilingTypeId")).or_else(|| by_id("wallTypes", c.get("wallTypeId"))) else { return vec![] }; + let layers = arr(ct.get("layers")); + if layers.is_empty() { + return vec![]; + } + let used_by_others = arr(root.get("ceilings")).iter().any(|o| id_of(o) != Some(ceiling_id) && active(o) == active_id); + if layers.len() == 1 && !used_by_others && truthy(c.get("ceilingTypeId")) { + let tid = id_of(&ct).unwrap_or(""); + return find(root, "ceilingTypes", tid).map(|t| vec![replace("ceilingTypes", with(t, "layers", single_layer(arr(t.get("layers")), thickness)))]).unwrap_or_default(); + } + let mut nc = with(c, "ceilingTypeId", new_id.into()); + if let Value::Object(m) = &mut nc { + m.shift_remove("thickness"); + } + vec![add("ceilingTypes", new_type(new_id, new_name, layers, thickness)), replace("ceilings", nc)] +} + +// ── Griff-Listen für die Anzeige ───────────────────────────────────────────── + +/// Editier-Griffe einer 2D-Zeichnung in Modell-Metern (`drawingVertices`, gleiche Reihenfolge wie +/// [`drawing_grip`]): Ecken; Polylinie zusätzlich je Segment ein Bogen-Mitten-Griff; Kreis Ost/Nord; +/// Bogen Start/Ende/Mitte; Ellipse je Halbachse; Bemassung Kettenpunkte · Masslinie · je Segment die +/// Masszahl; Text Anker · Knicke · Spitze bzw. Pfadpunkte. `None` für die Textspalte (Rahmen-Ecken +/// brauchen die Schrift-Metrik der Hülle, `text/textFrame.ts`). +pub fn drawing_vertices(g: &Value, scale: f64) -> Option> { + let p = |k: &str| xy(g.get(k).unwrap_or(&Value::Null)); + let pts = |k: &str| arr(g.get(k)).iter().map(xy).collect::>(); + Some(match shape(g) { + "line" | "xline" | "ray" => vec![p("a"), p("b")], + "polyline" => { + let bulge = arr(g.get("bulge")); + polyline_vertices(pts("pts"), truthy(g.get("closed")), |i| num_or(bulge.get(i), 0.0)) + } + "rect" | "image" => rect_corners(g).to_vec(), + "circle" => { + let (c, r) = (p("center"), num_of(g.get("r"))); + vec![(c.0 + r, c.1), (c.0, c.1 + r)] + } + "arc" => { + let (c, r) = (p("center"), num_of(g.get("r"))); + let (a0, a1) = (num_of(g.get("a0")), num_of(g.get("a1"))); + let mid = (a0 + a1) / 2.0; + [a0, a1, mid].iter().map(|a| (c.0 + r * jsnum::cos(*a), c.1 + r * jsnum::sin(*a))).collect() + } + "ellipse" => { + let rot = num_of(g.get("rotation")); + let (c, s) = (jsnum::cos(rot), jsnum::sin(rot)); + let ctr = p("center"); + let (rx, ry) = (num_of(g.get("rx")), num_of(g.get("ry"))); + vec![(ctr.0 + rx * c, ctr.1 + rx * s), (ctr.0 - ry * s, ctr.1 + ry * c)] + } + "bezier" | "spline" => pts("pts"), + "dimension" => { + let mut out = pts("pts"); + let n = out.len(); + let nan = (f64::NAN, f64::NAN); + let (a, b) = (out.first().copied().unwrap_or(nan), out.last().copied().unwrap_or(nan)); + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let len = or1(hypot2(dx, dy)); + let offset = num_of(g.get("offset")); + let (nx, ny) = ((-dy / len) * offset, (dx / len) * offset); + out.push(((a.0 + b.0) / 2.0 + nx, (a.1 + b.1) / 2.0 + ny)); + let h = dim_height(g, scale); + let offs = arr(g.get("textOffsetsMm")); + for i in 0..n.saturating_sub(1) { + let (along, perp) = match offs.get(i) { + Some(o) if truthy(Some(o)) => (mm_to_model(num_of(o.get("along")), scale), mm_to_model(num_of(o.get("perp")), scale)), + _ => (0.0, 0.0), + }; + out.push(dim_text_pos(out[i], out[i + 1], offset, h, along, perp)); + } + out + } + "kote" | "detailref" | "scalebar" | "pointmarker" | "block" => vec![p("at")], + "text" => { + if truthy(g.get("pathPts")) { + pts("pathPts") + } else if truthy(g.get("leaderTarget")) { + let mut out = vec![p("at")]; + out.extend(pts("leaderBendPoints")); + out.push(p("leaderTarget")); + out + } else if truthy(g.get("width")) && num_of(g.get("width")) > 0.0 { + return None; + } else { + vec![p("at")] + } + } + _ => vec![], + }) +} + +/// Griffe einer Polylinie: die Eckpunkte, dahinter je Segment ein Bogen-Mitten-Griff (Scheitel des +/// Bogens bzw. Sehnen-Mitte); `bulge(i)` = Bogen von Segment `i` (fehlend 0). +pub fn polyline_vertices(mut out: Vec<(f64, f64)>, closed: bool, bulge: impl Fn(usize) -> f64) -> Vec<(f64, f64)> { + let n = out.len(); + let close = closed && n > 2; + let seg_count = n.saturating_sub(1) + usize::from(close); + for i in 0..seg_count { + let a = out[i]; + let b = if i == n - 1 { out[0] } else { out[i + 1] }; + let q = crate::bulge::point_at(a.0, a.1, b.0, b.1, bulge(i), 0.5); + out.push((q[0], q[1])); + } + out +} + +/// Kanten-Griffe (`ringEdges`/`openEdges`): je Kante `(a, b, Mitte, Normale)`. Ring: Normale nach +/// aussen (vom Eckpunkt-Mittel weg), auch die Schlusskante; Kette: linke Normale, ohne Schlusskante. +/// `bulge` (Polylinie): Kanten an Bogen-Segmenten fallen weg (die haben ihren Bogen-Mitten-Griff). +pub fn edge_grips(verts: &[(f64, f64)], closed: bool, bulge: Option<&[f64]>) -> Vec<(usize, usize, (f64, f64), (f64, f64))> { + let n = verts.len(); + if (closed && n < 3) || n < 2 { + return vec![]; + } + let (mut cx, mut cy) = (0.0, 0.0); + for v in verts { + cx += v.0; + cy += v.1; + } + let ctr = (cx / n as f64, cy / n as f64); + let count = if closed { n } else { n - 1 }; + let mut out = Vec::with_capacity(count); + for i in 0..count { + let j = (i + 1) % n; + if bulge.is_some_and(|b| !(b.get(i).copied().unwrap_or(0.0).abs() <= 1e-9)) { + continue; + } + let (a, b) = (verts[i], verts[j]); + let mid = ((a.0 + b.0) / 2.0, (a.1 + b.1) / 2.0); + let (lx, ly) = (-(b.1 - a.1), b.0 - a.0); + let l = or1(hypot2(lx, ly)); + let mut nrm = (lx / l, ly / l); + if closed { + let out_dir = (mid.0 - ctr.0, mid.1 - ctr.1); + if nrm.0 * out_dir.0 + nrm.1 * out_dir.1 < 0.0 { + nrm = (nrm.0 * -1.0, nrm.1 * -1.0); + } + } + out.push((i, j, mid, nrm)); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn root(v: Value) -> Map { + v.as_object().unwrap().clone() + } + + fn entity(r: &GripResult) -> &Value { + match &r.ops[0] { + Op::Replace { entity, .. } => entity, + _ => panic!("replace erwartet"), + } + } + + #[test] + fn js_zahlen() { + assert_eq!(js_num(5.0).to_string(), "5"); + assert_eq!(js_num(-0.0).to_string(), "0"); + assert_eq!(js_num(-3.0).to_string(), "-3"); + assert_eq!(js_num(0.5).to_string(), "0.5"); + assert_eq!(js_num(f64::NAN), json!("\u{1}NaN")); + assert_eq!(js_num(f64::NEG_INFINITY), json!("\u{1}-Infinity")); + assert_eq!(num_of(Some(&json!("\u{1}Infinity"))), f64::INFINITY); + assert_eq!(num_of(Some(&Value::Null)), 0.0); + assert!(num_of(None).is_nan()); + } + + #[test] + fn wand_griff_und_sperre() { + let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}, "extra": 1}]})); + let res = run(&r, &json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]})).unwrap(); + assert_eq!(entity(&res).to_string(), r#"{"id":"w","start":{"x":0,"y":0},"end":{"x":2,"y":3},"extra":1}"#); + let locked = root(json!({"walls": [{"id": "w", "locked": true, "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}}]})); + assert!(run(&locked, &json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]})).unwrap().ops.is_empty()); + // Fehlendes Element: keine Op. + assert!(run(&r, &json!({"op": "moveGrip", "wallId": "x", "index": 1, "pt": [2, 3]})).unwrap().ops.is_empty()); + } + + #[test] + fn kreis_wird_ellipse() { + let r = root(json!({"drawings2d": [{"id": "d", "geom": {"shape": "circle", "center": {"x": 0, "y": 0}, "r": 1}}]})); + let res = run(&r, &json!({"op": "moveGrip", "drawingId": "d", "index": 0, "pt": [2, 0]})).unwrap(); + assert_eq!(entity(&res)["geom"].to_string(), r#"{"shape":"ellipse","center":{"x":0,"y":0},"rx":2,"ry":1,"rotation":0}"#); + } + + #[test] + fn kante_winkeltreu() { + // Trapez: die obere Kante nach oben ziehen, die Ecken wandern entlang der Schrägen. + let pts: Vec = [(0.0, 0.0), (4.0, 0.0), (3.0, 1.0), (1.0, 1.0)].iter().map(|p| pt(p.0, p.1)).collect(); + let out = move_polygon_edge(&pts, 2.0, 3.0, 0.0, 1.0, true).unwrap(); + assert_eq!(out.to_string(), r#"[{"x":0,"y":0},{"x":4,"y":0},{"x":2,"y":2},{"x":2,"y":2}]"#); + assert!(move_polygon_edge(&pts, 4.0, 0.0, 0.0, 1.0, true).is_none()); + } + + #[test] + fn nan_als_marke() { + let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}}]})); + let res = run(&r, &json!({"op": "moveBy", "wallId": "w", "delta": ["\u{1}NaN", 0]})).unwrap(); + assert_eq!(entity(&res)["start"]["x"], json!("\u{1}NaN")); + } + + #[test] + fn punkt_loeschen_mindestzahl() { + let r = root(json!({"drawings2d": [{"id": "d", "geom": {"shape": "polyline", "closed": false, "pts": [{"x": 0, "y": 0}, {"x": 1, "y": 0}]}}]})); + let res = run(&r, &json!({"op": "deletePoint", "id": "d", "index": 0})).unwrap(); + assert_eq!(res.notice, Some("alert.polylineMinPoints")); + assert!(res.ops.is_empty()); + } + + #[test] + fn deckendicke_neuer_typ() { + let r = root(json!({ + "wallTypes": [{"id": "wt", "name": "W", "layers": [{"componentId": "c", "thickness": 0.2}]}], + "ceilings": [{"id": "c1", "wallTypeId": "wt", "thickness": 0.3}, {"id": "c2", "wallTypeId": "wt"}], + })); + let ops = run(&r, &json!({"op": "ceilingThickness", "id": "c1", "thickness": 0.25, "newId": "ct-1", "newName": "Decke"})).unwrap().ops; + assert_eq!(crate::ops::ops_to_json(&ops), r#"[{"kind":"add","collection":"ceilingTypes","items":[{"id":"ct-1","name":"Decke","layers":[{"componentId":"c","thickness":0.25}]}]},{"kind":"replace","collection":"ceilings","entity":{"id":"c1","wallTypeId":"wt","ceilingTypeId":"ct-1"}}]"#); + } + + #[test] + fn griffe_und_kanten() { + let g = json!({"shape": "polyline", "closed": true, "pts": [{"x": 0, "y": 0}, {"x": 2, "y": 0}, {"x": 2, "y": 2}], "bulge": [0, 0.5, 0]}); + let v = drawing_vertices(&g, 100.0).unwrap(); + assert_eq!(v.len(), 6); + assert_eq!(v[3], (1.0, 0.0)); + let e = edge_grips(&v[..3], true, Some(&[0.0, 0.5, 0.0])); + assert_eq!(e.iter().map(|x| (x.0, x.1)).collect::>(), vec![(0, 1), (2, 0)]); + assert_eq!(e[0].3, (0.0, -1.0)); + let text = json!({"shape": "text", "at": {"x": 0, "y": 0}, "width": 2}); + assert!(drawing_vertices(&text, 100.0).is_none()); + } +} diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 9c5fee02..4b6d1529 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -81,6 +81,7 @@ pub mod parametric_walls; pub mod geo_translate; pub mod selection_filter; pub mod reorder; +pub mod grips; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs index 473d3560..5c7d6ee4 100644 --- a/src-tauri/core/src/queries.rs +++ b/src-tauri/core/src/queries.rs @@ -98,6 +98,11 @@ pub fn run_root(root: &serde_json::Map, name: &str, t let m: crate::groups::Membership = serde_json::from_str(text).map_err(|e| format!("selectionFilterPatch: {e}"))?; json(&crate::selection_filter::filter_patch(root, &m)) } + // Griff-Änderungen ([K4] S3, `grips.rs`): `text` = JSON der Anfrage; Antwort `{ops, notice}` (ohne Commit). + "gripOps" => { + let req: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("gripOps: {e}"))?; + Ok(crate::grips::result_json(&crate::grips::run(root, &req)?)) + } _ => Err(format!("Unbekannte Wurzel-Abfrage: {name}")), } } diff --git a/src-tauri/core/src/web/drawings.rs b/src-tauri/core/src/web/drawings.rs deleted file mode 100644 index 47167376..00000000 --- a/src-tauri/core/src/web/drawings.rs +++ /dev/null @@ -1,16 +0,0 @@ -//! Bindungen der 2D-Zeichnungen im Grundriss (`crate::plan::drawings`). Die Plan-Primitive selbst -//! kommen über die Dokument-Abfragen (`planDomains`, `drawingPrims`, `drawingLines`). - -use wasm_bindgen::prelude::wasm_bindgen; - -/// Lage der Masszahl eines Mass-Segments `[baseX, baseY, readX, readY, upX, upY, angle]` -/// (`dimTextFrame`, geteilt von Plan und Masszahl-Griff); leer bei NaN/∞. -#[wasm_bindgen] -pub fn dim_text_frame(ax: f64, ay: f64, bx: f64, by: f64, offset: f64, text_height: f64) -> Vec { - if ![ax, ay, bx, by, offset, text_height].iter().all(|v| v.is_finite()) { - return Vec::new(); - } - let v = |x, y| crate::model::Vec2 { x, y }; - let (base, read, up, angle) = crate::plan::drawings::dim_text_frame(v(ax, ay), v(bx, by), offset, text_height); - vec![base.x, base.y, read.x, read.y, up.x, up.y, angle] -} diff --git a/src-tauri/core/src/web/grips.rs b/src-tauri/core/src/web/grips.rs new file mode 100644 index 00000000..f9fe1e60 --- /dev/null +++ b/src-tauri/core/src/web/grips.rs @@ -0,0 +1,81 @@ +//! Bindungen der Griff-Geometrie (`crate::grips`): Griff-Änderung im Dokument rechnen und gleich als +//! Benutzer-Änderung anwenden (ein Aufruf je Mausschritt, keine Op-Übergabe hin und zurück), Griff- +//! und Kanten-Listen für die Anzeige als flache Puffer. + +use super::document::with_doc; +use serde_json::{json, Value}; +use wasm_bindgen::prelude::wasm_bindgen; + +/// Griff-Änderung `req_json` (s. `crate::grips::run`) auf dem Dokument `h` rechnen und mit Verlauf +/// anwenden (`key` = coalesceKey, `now_ms` = Zeit für das Koaleszenz-Fenster, wie `doc_commit`). +/// Antwort: `{"ops":[…],"notice":…}` (angewendet; leer = nichts zu tun) oder `{"problems":[…]}` +/// (zurückgewiesen, Dokument unverändert); Fehler als Text mit vorangestelltem `\u{1}`. +#[wasm_bindgen] +pub fn doc_grip_commit(h: u32, req_json: &str, key: &str, now_ms: f64) -> String { + let req: Value = match serde_json::from_str(req_json) { + Ok(v) => v, + Err(e) => return format!("\u{1}Griff-Anfrage: {e}"), + }; + let key = (!key.is_empty()).then_some(key); + let now = if now_ms.is_finite() { now_ms } else { 0.0 }; + let out = with_doc(h, |d| -> Result { + let res = crate::grips::run(d.root(), &req)?; + let text = crate::grips::result_json(&res); + if res.ops.is_empty() { + return Ok(text); + } + // Nicht endliche Ergebnisse stehen als Marken in den Ops (die Prüfung weist sie zurück). + let marks = text.contains("\\u0001"); + match d.commit(res.ops, key, now, marks) { + Ok(()) => Ok(text), + Err(problems) => Ok(json!({ "problems": problems }).to_string()), + } + }); + match out { + Some(Ok(t)) => t, + Some(Err(e)) => format!("\u{1}{e}"), + None => "\u{1}Dokument nicht offen".to_string(), + } +} + +/// Editier-Griffe einer 2D-Zeichnung (JSON) beim Massstab 1:`scale`: `[n, x0, y0, …]`; `[-1]` = Textspalte +/// (Rahmen-Ecken rechnet die Hülle mit der Schrift-Metrik), `[]` bei kaputtem JSON. +#[wasm_bindgen] +pub fn grip_vertices(drawing_json: &str, scale: f64) -> Vec { + let Ok(d) = serde_json::from_str::(drawing_json) else { return vec![] }; + let g = d.get("geom").unwrap_or(&d); + match crate::grips::drawing_vertices(g, scale) { + None => vec![-1.0], + Some(v) => { + let mut out = Vec::with_capacity(1 + 2 * v.len()); + out.push(v.len() as f64); + for p in v { + out.push(p.0); + out.push(p.1); + } + out + } + } +} + +/// Editier-Griffe einer Polylinie aus flachen Puffern (grosse Kataster-Umrisse ohne JSON): `pts = [x0, y0, …]`, +/// `bulge` je Segment (fehlend/NaN = gerade) → `[x0, y0, …]` (Eckpunkte, dann je Segment die Bogen-Mitte). +#[wasm_bindgen] +pub fn grip_vertices_polyline(pts: &[f64], bulge: &[f64], closed: bool) -> Vec { + let verts: Vec<(f64, f64)> = pts.chunks_exact(2).map(|c| (c[0], c[1])).collect(); + crate::grips::polyline_vertices(verts, closed, |i| bulge.get(i).copied().unwrap_or(0.0)).into_iter().flat_map(|p| [p.0, p.1]).collect() +} + +/// Kanten-Griffe eines Rings (`closed`) bzw. einer Kette aus `pts = [x0, y0, …]`; `bulge` je Segment +/// nur bei `use_bulge` (Polylinie: Bogen-Segmente ohne Kanten-Griff). Antwort je Kante +/// `[a, b, mitteX, mitteY, normaleX, normaleY]`. +#[wasm_bindgen] +pub fn edge_grips(pts: &[f64], closed: bool, bulge: &[f64], use_bulge: bool) -> Vec { + let verts: Vec<(f64, f64)> = pts.chunks_exact(2).map(|c| (c[0], c[1])).collect(); + let edges = crate::grips::edge_grips(&verts, closed, use_bulge.then_some(bulge)); + let mut out = Vec::with_capacity(6 * edges.len()); + for (a, b, m, n) in edges { + out.extend([a as f64, b as f64, m.0, m.1, n.0, n.1]); + } + out +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 67d0dfbf..f0c56970 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -36,12 +36,12 @@ mod snap; mod plan_svg; mod plan_dxf; mod plan_print_svg; -mod drawings; mod layers; mod pens; mod layout_model; mod parametric_walls; mod reorder; +mod grips; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src/App.tsx b/src/App.tsx index 8073f3fb..4ebb74f7 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1254,7 +1254,7 @@ export default function App() { for (const id of selectedSectionLineIds) patchLevel(id, { linePoints: undefined }); } // Objekt-Sperre: gesperrte Elemente aus der Löschung ausnehmen (s. - // `moveGrip`/`moveElementBy` in projectSlice.ts für dieselbe Prüfung + // `moveGrip`/`moveElementBy` im Kern, `grips.rs`, für dieselbe Prüfung // beim Ziehen). ExtrudedSolid/Kontext-Objekte haben kein `locked`-Feld // (s. deren Typdefinitionen) — bleiben ungefiltert. const notLocked = (kind: MemberKind, ids: string[]) => diff --git a/src/commands/cmds/ellipse.ts b/src/commands/cmds/ellipse.ts index c39bebd4..dea01b82 100644 --- a/src/commands/cmds/ellipse.ts +++ b/src/commands/cmds/ellipse.ts @@ -9,7 +9,7 @@ // • Achse (gedreht): Zentrum + Hauptachse + Nebenachse — beliebig gedrehte // Ellipse. `rotation` existiert im Modell seit Langem (Rendering + // Griff-Editieren lesen es bereits, s. `plan/drawings.rs` im Kern -// Z. 448 bzw. `projectSlice.ts` `drawingVertices`), nur die Erzeugung +// Z. 448 bzw. `grips.rs` `drawing_vertices`), nur die Erzeugung // setzte es bisher immer auf 0. // 1) „Zentrum:" → Punkt // 2) „Hauptachse:" → Punkt (Richtung + rx = Abstand zum Zentrum) diff --git a/src/core/document.ts b/src/core/document.ts index 6b09ef98..754d6131 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -7,6 +7,7 @@ import type { Project } from "../model/types"; import { core } from "../engine/coreWasm"; import { applyOps, opsToJson } from "./ops"; +import { fromMarkedJson, toMarkedJson } from "./ops"; import type { CoreOp } from "./ops"; import { fieldOps } from "./opsBuild"; @@ -235,6 +236,33 @@ export class ProjectDocument { return { project }; } + /** + * Griff-Änderung ([K4] S3, `grips.rs`): der Kern rechnet `req` (s. `GripRequest`) auf seinem Stand + * von `base` und wendet das Ergebnis wie {@link commit} an — ein Aufruf je Mausschritt. Ergebnis: + * neues Projekt und die angewendeten Ops (leer = nichts zu tun, dann `project === base`), ein + * Hinweis-Schlüssel (i18n) oder die Meldungen der Prüfung (dann bleibt alles unverändert). + */ + commitGrip(base: Project, req: object, coalesceKey: string | undefined, now: number): { project: Project; ops: CoreOp[]; notice?: string } | { problems: string[] } { + this.ensure(base); + if (!this.handle) return { problems: ["Projekt-Dokument im Kern nicht offen."] }; + const out = core().doc_grip_commit(this.handle, toMarkedJson(req), coalesceKey ?? "", now); + if (out.startsWith("\u0001")) throw new Error(out.slice(1)); + const r = fromMarkedJson<{ ops: CoreOp[]; notice?: string } | { problems: string[] }>(out); + if ("problems" in r) return r; + if (r.ops.length === 0) return { project: base, ops: r.ops, notice: r.notice }; + const project = applyOps(base, r.ops); + this.mirror = project; + return { project, ops: r.ops, notice: r.notice }; + } + + /** Wie {@link commitGrip}, aber nur rechnen (ohne Anwenden): die Ops und ggf. der Hinweis. */ + gripOps(req: object): { ops: CoreOp[]; notice?: string } { + if (!this.handle) throw new Error("Kern-Abfrage „gripOps“: Dokument nicht offen"); + const out = core().doc_query_root(this.handle, "gripOps", toMarkedJson(req)); + if (out.startsWith("\u0001")) throw new Error(out.slice(1)); + return fromMarkedJson(out); + } + /** Einen Schritt zurück auf `base` (= aktuelles Projekt); `null` = nichts rückgängig zu machen. */ undo(base: Project): Project | null { return this.jump(base, "doc_undo"); diff --git a/src/core/extra.ts b/src/core/extra.ts index 60c8a878..acb9504d 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -53,3 +53,5 @@ export { addItems, fieldOps, findItem, itemsOf, opsMutation, patchItem, patchIte export type { EntityCollection, EntityOf, ProjectMutation } from "./opsBuild"; export { EMPTY_MEMBERSHIP, containingGroupId, expandToGroups, isInsideActiveGroup, transitiveMembership } from "../model/groups"; export type { GroupMembership, MemberKind } from "../model/groups"; +export { drawingVertices, gripPt, openEdges, polylineEdgeGrips, ringEdges } from "../geometry/grips"; +export type { GripRequest } from "../geometry/grips"; diff --git a/src/core/ops.ts b/src/core/ops.ts index 90b4aad3..4f107bb2 100644 --- a/src/core/ops.ts +++ b/src/core/ops.ts @@ -154,6 +154,23 @@ export function opsToJson(ops: readonly CoreOp[]): string { return JSON.stringify(ops, markNonFinite); } +/** Wert als JSON mit Nicht-endlich-Marken (wie {@link opsToJson}), z. B. Anfragen an den Kern. */ +export function toMarkedJson(v: unknown): string { + return JSON.stringify(v, markNonFinite); +} + +/** Nicht-endlich-Marken des Kerns (`"\u0001NaN"` …) zurück in Zahlen. */ +function reviveNonFinite(_key: string, v: unknown): unknown { + if (typeof v !== "string" || v.charCodeAt(0) !== 1) return v; + const t = v.slice(1); + return t === "NaN" ? NaN : t === "Infinity" ? Infinity : t === "-Infinity" ? -Infinity : v; +} + +/** JSON des Kerns lesen; Nicht-endlich-Marken werden wieder Zahlen (nur wenn welche vorkommen). */ +export function fromMarkedJson(text: string): T { + return (text.includes("\\u0001") ? JSON.parse(text, reviveNonFinite) : JSON.parse(text)) as T; +} + // ── Validierung ([7]) — im Kern (`ops.rs`) ─────────────────────────────────── function problemsOf(json: string): string[] { diff --git a/src/geometry/grips.test.ts b/src/geometry/grips.test.ts new file mode 100644 index 00000000..e5cdbd26 --- /dev/null +++ b/src/geometry/grips.test.ts @@ -0,0 +1,126 @@ +import { describe, expect, it } from "vitest"; +import { drawingVertices, openEdges, polylineEdgeGrips, ringEdges } from "./grips"; +import { documentFor } from "../core/document"; +import type { Drawing2D, Project } from "../model/types"; + +// ── Bemassung: Masszahl-Griffe (Lage und Einrasten rechnet der Kern, `grips.rs`) ── + +const dim = (pts: { x: number; y: number }[], offset: number, textOffsetsMm?: { along: number; perp: number }[]): Drawing2D => + ({ id: "m", type: "drawing2d", levelId: "f", categoryCode: "1", geom: { shape: "dimension", pts, offset, textHeightMm: 4, ...(textOffsetsMm ? { textOffsetsMm } : {}) } }) as Drawing2D; +const A = { x: 0, y: 0 }; +const B = { x: 4, y: 0 }; +/** Schrifthöhe 4 mm bei 1:50 in Modell-Metern. */ +const H = 0.2; + +describe("Bemassung: Griffe der Masszahl", () => { + it("Standardlage: mittig über der Masslinie (Offset eingerechnet), Reihenfolge Punkte · Masslinie · Zahl", () => { + const v = drawingVertices(dim([A, B], 1), 50); + expect(v).toHaveLength(4); + expect(v[2]).toEqual({ x: 2, y: 1 }); + expect(v[3].x).toBeCloseTo(2, 9); + expect(v[3].y).toBeCloseTo(1 + H * 0.6, 9); + }); + + it("Leserichtung nie kopfüber — auch bei rückwärts laufender Kette", () => { + const fwd = drawingVertices(dim([A, B], 0), 50)[3]; + const back = drawingVertices(dim([B, A], 0), 50)[3]; + expect(back.x).toBeCloseTo(fwd.x, 9); + expect(back.y).toBeCloseTo(fwd.y, 9); + }); + + it("Versatz (Papier-mm) wirkt entlang der Leserichtung und quer dazu", () => { + const base = drawingVertices(dim([A, B], 0), 50)[3]; + // 20 mm / 40 mm bei 1:50 = 1 m / 2 m. + const p = drawingVertices(dim([A, B], 0, [{ along: 20, perp: 40 }]), 50)[3]; + expect(p.x).toBeCloseTo(base.x + 1, 9); + expect(p.y).toBeCloseTo(base.y + 2, 9); + }); + + const drag = (d: Drawing2D, pt: { x: number; y: number }) => { + const p = { drawings2d: [d], walls: [] } as unknown as Project; + const res = documentFor(p).gripOps({ op: "moveGrip", drawingId: "m", wallId: null, index: d.geom.shape === "dimension" ? d.geom.pts.length + 1 : 0, pt: [pt.x, pt.y], scale: 50 }); + const e = res.ops[0] as unknown as { entity: Drawing2D }; + return (e.entity.geom as { textOffsetsMm: { along: number; perp: number }[] }).textOffsetsMm[0]; + }; + + it("nahe der Standardlage rastet BEIDES auf 0 ein", () => { + const base = drawingVertices(dim([A, B], 0), 50)[3]; + expect(drag(dim([A, B], 0), { x: base.x + H * 0.2, y: base.y - H * 0.2 })).toEqual({ along: 0, perp: 0 }); + }); + + it("die Achsen rasten UNABHÄNGIG ein (seitlich verschoben, Höhe exakt Standard)", () => { + const base = drawingVertices(dim([A, B], 0), 50)[3]; + const o = drag(dim([A, B], 0), { x: base.x + 1.5, y: base.y + H * 0.1 }); + expect(o.along).toBeCloseTo(30, 9); + expect(o.perp).toBe(0); + }); + + it("ausserhalb des Fangbereichs bleibt der gezogene Wert erhalten", () => { + const base = drawingVertices(dim([A, B], 0), 50)[3]; + const o = drag(dim([A, B], 0), { x: base.x + 0.8, y: base.y + 0.6 }); + expect(o.along).toBeCloseTo(16, 9); + expect(o.perp).toBeCloseTo(12, 9); + }); + + it("Rundreise: gezogene Position → Versatz → Griff liegt wieder am Punkt", () => { + const pt = { x: 3.1, y: 1.4 }; + const o = drag(dim([A, B], 0.5), pt); + const back = drawingVertices(dim([A, B], 0.5, [o]), 50)[3]; + expect(back.x).toBeCloseTo(pt.x, 9); + expect(back.y).toBeCloseTo(pt.y, 9); + }); +}); + +describe("Kanten-Griffe von Ringen und Ketten", () => { + it("Ring: Normalen nach aussen, auch die Schlusskante; Kette: frei, ohne Schlusskante", () => { + const tri = [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 0, y: 3 }]; + const r = ringEdges(tri, {}); + expect(r.map((e) => [e.aIndex, e.bIndex])).toEqual([[0, 1], [1, 2], [2, 0]]); + expect(r[0].normal.x).toBeCloseTo(0, 12); + expect(r[0].normal.y).toBe(-1); + expect(r[2].normal.x).toBeCloseTo(-1, 12); + const o = openEdges(tri, { wallId: "w" }); + expect(o.map((e) => [e.aIndex, e.bIndex, e.free, e.owner?.wallId])).toEqual([[0, 1, true, "w"], [1, 2, true, "w"]]); + expect(ringEdges(tri.slice(0, 2), {})).toEqual([]); + }); +}); + +const sq = [ + { x: 0, y: 0 }, + { x: 30, y: 0 }, + { x: 30, y: 30 }, + { x: 0, y: 30 }, +]; + +describe("polylineEdgeGrips", () => { + it("geschlossen, gerade: 4 Kanten auf den Seitenmitten, Normalen nach aussen", () => { + const e = polylineEdgeGrips({ shape: "polyline", pts: sq, closed: true }, { drawingId: "d" }); + expect(e.map((g) => g.mid)).toEqual([ + { x: 15, y: 0 }, + { x: 30, y: 15 }, + { x: 15, y: 30 }, + { x: 0, y: 15 }, + ]); + expect(e.map((g) => [g.aIndex, g.bIndex])).toEqual([[0, 1], [1, 2], [2, 3], [3, 0]]); + expect(e[0].normal.y).toBeCloseTo(-1); + expect(e[1].normal.x).toBeCloseTo(1); + }); + + it("geschlossen mit Bögen: nur gerade Seiten, keine Kanten über die Bogen-Mitten (nichts im Innern)", () => { + const e = polylineEdgeGrips( + { shape: "polyline", pts: sq, closed: true, bulge: [0.12, 0, -0.15, 0] }, + { drawingId: "d" }, + ); + expect(e.map((g) => g.mid)).toEqual([ + { x: 30, y: 15 }, + { x: 0, y: 15 }, + ]); + // Lauter Bögen (Strassenparzelle): keine Kanten-Griffe. + expect(polylineEdgeGrips({ shape: "polyline", pts: sq, closed: true, bulge: [0.1, 0.1, 0.1, 0.1] }, {})).toEqual([]); + }); + + it("offen: je gerades Segment ein freier Griff, ohne Schlusskante", () => { + const e = polylineEdgeGrips({ shape: "polyline", pts: sq, closed: false, bulge: [0, 0.3, 0] }, {}); + expect(e.map((g) => [g.aIndex, g.bIndex, g.free])).toEqual([[0, 1, true], [2, 3, true]]); + }); +}); diff --git a/src/geometry/grips.ts b/src/geometry/grips.ts new file mode 100644 index 00000000..871ab61c --- /dev/null +++ b/src/geometry/grips.ts @@ -0,0 +1,105 @@ +// Griff-Geometrie der Bauteile ([K4] S3): dünne Fassade über den Rust-Kern (`src-tauri/core/src/grips.rs`, +// Bindungen `web/grips.rs`). Die Griff-Änderungen selbst (Eckpunkt/Kante ziehen, verschieben, Grösse, +// Decke/Dach/Treppe/Raum, Polylinien-Punkte, Dicken) rechnet der Kern auf dem Dokument und wendet sie +// gleich an (`ProjectDocument.commitGrip`, Anfrage {@link GripRequest}); hier stehen die Griff-Listen +// für die Anzeige (`drawingVertices`, Kanten-Griffe). +// +// Bewusst TS: die Rahmen-Ecken einer Textspalte (`textFrameCorners` braucht die Schrift-Metrik der +// Hülle) — der Kern meldet dafür nur „Textspalte". + +import type { Drawing2D, Drawing2DGeom, EdgeGrip, Vec2 } from "../model/types"; +import { core } from "../engine/coreWasm"; +import { toMarkedJson } from "../core/ops"; +import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension"; +import { textFrameCorners } from "../text/textFrame"; + +/** Punkt als `[x, y]` (Anfragen an den Kern). */ +type P = [number, number]; + +/** Eine Griff-Änderung für den Kern (`grips.rs::run`); Zahlen dürfen NaN/±∞ sein (Marken). */ +export type GripRequest = + | { op: "moveGrip"; drawingId: string | null; wallId: string | null; index: number; pt: P; scale: number } + | { op: "moveBy"; drawingId: string | null; wallId: string | null; delta: P } + | { op: "moveEdge"; drawingId: string | null; wallId: string | null; a: number; b: number; delta: P } + | { op: "resize"; kind: string; id: string; w: number; h: number; fx: number; fy: number } + | { op: "ceilingGrip" | "roomGrip" | "roofGrip"; id: string; index: number; pt: P } + | { op: "ceilingBy" | "roofBy" | "stairBy" | "roomBy" | "roomStamp"; id: string; delta: P } + | { op: "ceilingEdge" | "roomEdge"; id: string; a: number; b: number; delta: P } + | { op: "insertPoint"; id: string; seg: number; pt: P } + | { op: "deletePoint"; id: string; index: number } + | { op: "wallThickness" | "ceilingThickness"; id: string; thickness: number; newId: string; newName: string }; + +/** Punkt als Anfrage-Paar. */ +export const gripPt = (p: Vec2): P => [p.x, p.y]; + +/** + * Editier-Griffe (Eckpunkte) eines 2D-Zeichenelements in Modell-Metern — dieselbe Reihenfolge, in der + * der Kern einen Griff-Index auflöst (`moveGrip`). line/polyline/rect: Eckpunkte (Polylinie zusätzlich je + * Segment ein Bogen-Mitten-Griff); Kreis Ost/Nord; Bogen Start/Ende/Mitte; Ellipse je Halbachse; + * Bemassung Kettenpunkte · Masslinie · je Segment die Masszahl (`scaleDenominator`: Papier-Massstab, die + * Masszahl-Lage hängt an der Schrifthöhe in Papier-mm); Text Anker · Knicke · Spitze, Pfadpunkte oder + * die vier Rahmen-Ecken einer Textspalte. + */ +export function drawingVertices(d: Drawing2D, scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR): Vec2[] { + const g = d.geom; + if (g.shape === "polyline") { + // Flach (Kataster-Umrisse mit tausenden Punkten): ein fehlender/null-Bogen ist gerade. + const f = core().grip_vertices_polyline(flat(g.pts), Float64Array.from(g.bulge ?? []), !!g.closed); + const out: Vec2[] = new Array(f.length >> 1); + for (let i = 0; i < out.length; i++) out[i] = { x: f[2 * i], y: f[2 * i + 1] }; + return out; + } + // NaN/±∞ als Marken (JSON hätte null daraus gemacht, das rechnet wie 0). + const f = core().grip_vertices(toMarkedJson(g), scaleDenominator); + if (f[0] === -1 && g.shape === "text") { + return textFrameCorners({ at: g.at, text: g.text, heightM: g.height, angle: g.angle, marks: g.marks, doc: g.doc, wrapWidth: g.width }); + } + const n = f[0] ?? 0; + const out: Vec2[] = new Array(n); + for (let i = 0; i < n; i++) out[i] = { x: f[1 + 2 * i], y: f[2 + 2 * i] }; + return out; +} + +type Owner = { drawingId?: string; wallId?: string }; + +function flat(verts: readonly Vec2[]): Float64Array { + const f = new Float64Array(verts.length * 2); + for (let i = 0; i < verts.length; i++) { + f[2 * i] = verts[i].x; + f[2 * i + 1] = verts[i].y; + } + return f; +} + +function edges(verts: readonly Vec2[], closed: boolean, bulge: readonly number[] | null, owner: Owner): EdgeGrip[] { + const f = core().edge_grips(flat(verts), closed, Float64Array.from(bulge ?? []), bulge !== null); + const out: EdgeGrip[] = []; + for (let i = 0; i + 5 < f.length; i += 6) { + const e: EdgeGrip = { mid: { x: f[i + 2], y: f[i + 3] }, normal: { x: f[i + 4], y: f[i + 5] }, aIndex: f[i], bIndex: f[i + 1] }; + if (!closed) e.free = true; + e.owner = owner; + out.push(e); + } + return out; +} + +/** Geschlossener Ring → Kanten-Griffe mit Aussennormale (vom Eckpunkt-Mittel weg), inkl. Schlusskante. */ +export function ringEdges(verts: readonly Vec2[], owner: Owner): EdgeGrip[] { + return edges(verts, true, null, owner); +} + +/** + * Offene Kette (Linie/offene Polylinie) → ein Griff je Segment, OHNE Schlusskante. `normal` dient nur + * der Darstellung (linke Normale der Kante); die Bewegung ist frei (`free: true`). + */ +export function openEdges(verts: readonly Vec2[], owner: Owner): EdgeGrip[] { + return edges(verts, false, null, owner); +} + +/** + * Kanten-Griffe einer Polylinie: nur über die Eckpunkte und nur an geraden Segmenten — ein Bogen hat + * seinen Bogen-Mitten-Griff (`drawingVertices`), die Sehnen-Mitte läge neben der Linie. + */ +export function polylineEdgeGrips(g: Extract, owner: Owner): EdgeGrip[] { + return edges(g.pts, !!g.closed, g.bulge ?? [], owner); +} diff --git a/src/geometry/polylinePoint.ts b/src/geometry/polylinePoint.ts index 0afb84e4..1d9481e5 100644 --- a/src/geometry/polylinePoint.ts +++ b/src/geometry/polylinePoint.ts @@ -6,7 +6,7 @@ // // Bogen-Segmente (`bulge`) werden bewusst über ihre SEHNE gemessen: für die // Frage „welches Segment ist gemeint" reicht das, und der eingefügte Punkt -// landet ohnehin exakt auf dem Bogen (s. `projectSlice.insertDrawingPoint`). +// landet ohnehin exakt auf dem Bogen (s. `insert_point` im Kern, `grips.rs`). import type { Vec2 } from "../model/types"; diff --git a/src/model/dimension.test.ts b/src/model/dimension.test.ts deleted file mode 100644 index 1bf7e55a..00000000 --- a/src/model/dimension.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { - DIM_DEFAULTS_MM, - dimTextFrame, - dimTextOffsetFromPoint, - dimTextPos, - mmToModel, - modelToMm, -} from "./dimension"; - -const A = { x: 0, y: 0 }; -const B = { x: 4, y: 0 }; -/** Schrifthöhe in MODELL-Metern bei 1:50 — die Helfer rechnen in Modellmass. */ -const H = mmToModel(DIM_DEFAULTS_MM.textHeight, 50); - -describe("dimTextFrame", () => { - it("Standardlage: mittig über der Masslinie (Offset eingerechnet)", () => { - const f = dimTextFrame(A, B, 1, H); - expect(f.base.x).toBeCloseTo(2, 9); - expect(f.base.y).toBeCloseTo(1 + H * 0.6, 9); - }); - - it("Leserichtung nie kopfüber — auch bei rückwärts laufender Kette", () => { - const forward = dimTextFrame(A, B, 0, H); - const backward = dimTextFrame(B, A, 0, H); - expect(forward.read.x).toBeCloseTo(1, 9); - // b→a zeigt nach −X; die Zahl dreht sich trotzdem in die Leserichtung. - expect(backward.read.x).toBeCloseTo(1, 9); - }); -}); - -describe("dimTextPos", () => { - it("ohne Versatz identisch zur Standardlage", () => { - const f = dimTextFrame(A, B, 0.5, H); - const p = dimTextPos(A, B, 0.5, H, undefined); - expect(p).toEqual(f.base); - }); - - it("Versatz wirkt entlang der Leserichtung und quer dazu", () => { - const p = dimTextPos(A, B, 0, H, { along: 1, perp: 2 }); - const f = dimTextFrame(A, B, 0, H); - expect(p.x).toBeCloseTo(f.base.x + 1, 9); - expect(p.y).toBeCloseTo(f.base.y + 2, 9); - }); -}); - -describe("dimTextOffsetFromPoint — Verschieben mit Einrasten", () => { - it("nahe der Standardlage rastet BEIDES auf 0 ein", () => { - const f = dimTextFrame(A, B, 0, H); - const near = { x: f.base.x + H * 0.2, y: f.base.y - H * 0.2 }; - expect(dimTextOffsetFromPoint(A, B, 0, H, near)).toEqual({ along: 0, perp: 0 }); - }); - - it("die Achsen rasten UNABHÄNGIG ein (seitlich verschoben, Höhe exakt Standard)", () => { - const f = dimTextFrame(A, B, 0, H); - const pt = { x: f.base.x + 1.5, y: f.base.y + H * 0.1 }; - const o = dimTextOffsetFromPoint(A, B, 0, H, pt); - expect(o.along).toBeCloseTo(1.5, 9); - expect(o.perp).toBe(0); - }); - - it("ausserhalb des Fangbereichs bleibt der gezogene Wert erhalten", () => { - const f = dimTextFrame(A, B, 0, H); - const pt = { x: f.base.x + 0.8, y: f.base.y + 0.6 }; - const o = dimTextOffsetFromPoint(A, B, 0, H, pt); - expect(o.along).toBeCloseTo(0.8, 9); - expect(o.perp).toBeCloseTo(0.6, 9); - }); - - it("Rundreise: gezogene Position → Versatz → Position ergibt wieder den Punkt", () => { - const pt = { x: 3.1, y: 1.4 }; - const o = dimTextOffsetFromPoint(A, B, 0.5, H, pt); - const back = dimTextPos(A, B, 0.5, H, o); - expect(back.x).toBeCloseTo(pt.x, 9); - expect(back.y).toBeCloseTo(pt.y, 9); - }); -}); - -describe("mmToModel/modelToMm — Papier-mm ↔ Modellmass", () => { - it("bei 1:50 entsprechen die Defaults exakt den früheren festen Modellwerten", () => { - expect(mmToModel(DIM_DEFAULTS_MM.gap, 50)).toBeCloseTo(0.05, 12); - expect(mmToModel(DIM_DEFAULTS_MM.overshoot, 50)).toBeCloseTo(0.05, 12); - expect(mmToModel(DIM_DEFAULTS_MM.tickLen, 50)).toBeCloseTo(0.15, 12); - expect(mmToModel(DIM_DEFAULTS_MM.textHeight, 50)).toBeCloseTo(0.2, 12); - }); - - it("derselbe Papierwert ergibt bei anderem Massstab andere Modellmasse", () => { - // 2 mm Papier: bei 1:50 = 10 cm im Modell, bei 1:100 = 20 cm. - expect(mmToModel(2, 50)).toBeCloseTo(0.1, 12); - expect(mmToModel(2, 100)).toBeCloseTo(0.2, 12); - }); - - it("Rundreise mm → Modell → mm ist verlustfrei", () => { - for (const scale of [20, 50, 100, 200]) { - expect(modelToMm(mmToModel(2.5, scale), scale)).toBeCloseTo(2.5, 12); - } - }); -}); diff --git a/src/model/dimension.ts b/src/model/dimension.ts index 8add3228..bba723b0 100644 --- a/src/model/dimension.ts +++ b/src/model/dimension.ts @@ -1,19 +1,11 @@ -// Gemeinsame Geometrie der Bemassung (SIA 400 B.5.3) — von BEIDEN Seiten -// genutzt: vom Rendering (Rust-Kern, `plan/drawings.rs`) und von den Griffen -// (`state/projectSlice.ts`). Die Lage der Masszahl (`dimTextFrame`) rechnet nur -// der Kern (Bindung `dim_text_frame`): sonst driften Masszahl-Position und -// Masszahl-Griff auseinander, sobald eine der beiden Stellen angepasst wird. +// Konstanten der Bemassung (SIA 400 B.5.3). Die Geometrie (Masszahl-Lage `dim_text_frame`, Griffe der +// Kettenpunkte, der Masslinie und der Masszahlen) rechnet der Rust-Kern — für Plan und Griffe dieselbe +// Funktion (`plan/drawings.rs`, `grips.rs`), sonst drifteten Masszahl und Masszahl-Griff auseinander. // -// EINHEITEN: die Bemassungs-Feinheiten sind PAPIER-MILLIMETER (so denkt die -// Zeichnungsnorm: „Überstand 2 mm", unabhängig vom Massstab). Umgerechnet -// wird mit dem Massstab des jeweiligen Plans (`mmToModel`) — die Funktionen -// hier unten rechnen dann in Modell-Metern, weil die Plan-Geometrie so -// vorliegt. Der Plan wird je Ziel (Bildschirm, Layout-Viewport) EIGENS -// erzeugt (s. `LayoutSheet.tsx`), der Massstab ist zur Erzeugungszeit also -// bekannt und eindeutig. - -import type { Vec2 } from "./types"; -import { core } from "../engine/coreWasm"; +// EINHEITEN: die Bemassungs-Feinheiten sind PAPIER-MILLIMETER (so denkt die Zeichnungsnorm: „Überstand +// 2 mm", unabhängig vom Massstab). Umgerechnet wird mit dem Massstab des jeweiligen Plans; der Plan wird +// je Ziel (Bildschirm, Layout-Viewport) EIGENS erzeugt (s. `LayoutSheet.tsx`), der Massstab ist zur +// Erzeugungszeit also bekannt und eindeutig. /** * Defaults in PAPIER-MILLIMETERN (übliche Zeichnungswerte; entsprechen bei @@ -31,73 +23,3 @@ export const END_MARK_DEFAULT_SIZE_MM = 3; /** Standard-Massstab, wenn ein Aufrufer keinen mitgibt (1:100, üblichster Planmassstab). */ export const DEFAULT_SCALE_DENOMINATOR = 100; - -/** Papier-Millimeter → Modell-Meter beim Massstab 1:`scaleDenominator`. */ -export function mmToModel(mm: number, scaleDenominator: number): number { - return (mm / 1000) * scaleDenominator; -} - -/** Modell-Meter → Papier-Millimeter (Umkehrung von {@link mmToModel}). */ -export function modelToMm(m: number, scaleDenominator: number): number { - return (m * 1000) / scaleDenominator; -} - -/** - * Lage der Masszahl EINES Segments in ihrer Standardstellung plus die beiden - * Achsen, in denen ein Nutzer-Versatz (`textOffsets`) gemessen wird: - * `read` = Leserichtung der Zahl, `up` = quer dazu (von der Masslinie weg). - * Die Leserichtung ist nie kopfüber (wie beim Rendern), damit „nach oben" - * für den Nutzer oben bleibt, egal wie die Kette gedreht ist. - */ -export function dimTextFrame( - a: Vec2, - b: Vec2, - offset: number, - textHeight: number, -): { base: Vec2; read: Vec2; up: Vec2; angle: number } { - const f = core().dim_text_frame(a.x, a.y, b.x, b.y, offset, textHeight); - if (f.length < 7) return { base: { x: NaN, y: NaN }, read: { x: NaN, y: NaN }, up: { x: NaN, y: NaN }, angle: NaN }; - return { base: { x: f[0], y: f[1] }, read: { x: f[2], y: f[3] }, up: { x: f[4], y: f[5] }, angle: f[6] }; -} - -/** Endgültige Position der Masszahl inkl. Nutzer-Versatz. */ -export function dimTextPos( - a: Vec2, - b: Vec2, - offset: number, - textHeight: number, - textOffset: { along: number; perp: number } | undefined, -): Vec2 { - const f = dimTextFrame(a, b, offset, textHeight); - const o = textOffset ?? { along: 0, perp: 0 }; - return { - x: f.base.x + f.read.x * o.along + f.up.x * o.perp, - y: f.base.y + f.read.y * o.along + f.up.y * o.perp, - }; -} - -/** - * Zerlegt eine gezogene Masszahl-Position in den Versatz (along/perp) und - * lässt ihn dabei EINRASTEN: nahe der Standardlage wird die jeweilige Achse - * exakt auf 0 gezogen (Nutzer-Wunsch „schiebbar, aber trotzdem einrastend"). - * Beide Achsen rasten unabhängig — man kann die Zahl also seitlich - * verschieben und trotzdem exakt auf Standardhöhe bleiben. - */ -export function dimTextOffsetFromPoint( - a: Vec2, - b: Vec2, - offset: number, - textHeight: number, - pt: Vec2, -): { along: number; perp: number } { - const f = dimTextFrame(a, b, offset, textHeight); - const vx = pt.x - f.base.x; - const vy = pt.y - f.base.y; - const snap = textHeight * 0.5; // Fangbereich ≈ halbe Schrifthöhe - const along = vx * f.read.x + vy * f.read.y; - const perp = vx * f.up.x + vy * f.up.y; - return { - along: Math.abs(along) < snap ? 0 : along, - perp: Math.abs(perp) < snap ? 0 : perp, - }; -} diff --git a/src/state/edgeGrips.test.ts b/src/state/edgeGrips.test.ts deleted file mode 100644 index 2a936d45..00000000 --- a/src/state/edgeGrips.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { polylineEdgeGrips } from "./edgeGrips"; - -const sq = [ - { x: 0, y: 0 }, - { x: 30, y: 0 }, - { x: 30, y: 30 }, - { x: 0, y: 30 }, -]; - -describe("polylineEdgeGrips", () => { - it("geschlossen, gerade: 4 Kanten auf den Seitenmitten, Normalen nach aussen", () => { - const e = polylineEdgeGrips({ shape: "polyline", pts: sq, closed: true }, { drawingId: "d" }); - expect(e.map((g) => g.mid)).toEqual([ - { x: 15, y: 0 }, - { x: 30, y: 15 }, - { x: 15, y: 30 }, - { x: 0, y: 15 }, - ]); - expect(e.map((g) => [g.aIndex, g.bIndex])).toEqual([[0, 1], [1, 2], [2, 3], [3, 0]]); - expect(e[0].normal.y).toBeCloseTo(-1); - expect(e[1].normal.x).toBeCloseTo(1); - }); - - it("geschlossen mit Bögen: nur gerade Seiten, keine Kanten über die Bogen-Mitten (nichts im Innern)", () => { - const e = polylineEdgeGrips( - { shape: "polyline", pts: sq, closed: true, bulge: [0.12, 0, -0.15, 0] }, - { drawingId: "d" }, - ); - expect(e.map((g) => g.mid)).toEqual([ - { x: 30, y: 15 }, - { x: 0, y: 15 }, - ]); - // Lauter Bögen (Strassenparzelle): keine Kanten-Griffe. - expect(polylineEdgeGrips({ shape: "polyline", pts: sq, closed: true, bulge: [0.1, 0.1, 0.1, 0.1] }, {})).toEqual([]); - }); - - it("offen: je gerades Segment ein freier Griff, ohne Schlusskante", () => { - const e = polylineEdgeGrips({ shape: "polyline", pts: sq, closed: false, bulge: [0, 0.3, 0] }, {}); - expect(e.map((g) => [g.aIndex, g.bIndex, g.free])).toEqual([[0, 1, true], [2, 3, true]]); - }); -}); diff --git a/src/state/edgeGrips.ts b/src/state/edgeGrips.ts deleted file mode 100644 index fcf03976..00000000 --- a/src/state/edgeGrips.ts +++ /dev/null @@ -1,58 +0,0 @@ -// Kanten-Griffe (je Seite ein Anfasser mit Aussennormale) eines gewählten Elements — reine -// Geometrie, ausgelagert aus `useGripEditing.ts`. - -import { leftNormal, normalize, scale, sub } from "../model/geometry"; -import type { Drawing2DGeom, EdgeGrip, Vec2 } from "../model/types"; - -type Owner = { drawingId?: string; wallId?: string }; - -/** Geschlossener Ring aus Vertices → Kanten-Griffe mit Aussennormale (vom Eckpunkt-Mittel weg). */ -export function ringEdges(verts: Vec2[], owner: Owner): EdgeGrip[] { - const n = verts.length; - if (n < 3) return []; - // Schwerpunkt (Mittel der Eckpunkte) als Innenbezug. - let cx = 0, cy = 0; - for (const v of verts) { cx += v.x; cy += v.y; } - const centroid: Vec2 = { x: cx / n, y: cy / n }; - const out: EdgeGrip[] = []; - for (let i = 0; i < n; i++) { - const a = verts[i]; - const b = verts[(i + 1) % n]; - const mid: Vec2 = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; - let nrm = normalize(leftNormal(sub(b, a))); - // Nach aussen orientieren: Normale soll von centroid → mid weisen. - const outward = sub(mid, centroid); - if (nrm.x * outward.x + nrm.y * outward.y < 0) nrm = scale(nrm, -1); - out.push({ mid, normal: nrm, aIndex: i, bIndex: (i + 1) % n, owner }); - } - return out; -} - -/** - * Offene Kette (Linie/offene Polylinie) → ein Griff je Segment, OHNE Schlusskante. `normal` dient - * nur der Darstellung (leftNormal der Kante); die Bewegung ist frei (`free: true`). - */ -export function openEdges(verts: Vec2[], owner: Owner): EdgeGrip[] { - const n = verts.length; - if (n < 2) return []; - const out: EdgeGrip[] = []; - for (let i = 0; i < n - 1; i++) { - const a = verts[i]; - const b = verts[i + 1]; - const mid: Vec2 = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; - const nrm = normalize(leftNormal(sub(b, a))); - out.push({ mid, normal: nrm, aIndex: i, bIndex: i + 1, free: true, owner }); - } - return out; -} - -/** - * Kanten-Griffe einer Polylinie: nur über die Eckpunkte (`drawingVertices` hängt dahinter je - * Segment einen Bogen-Mitten-Griff an — liefen die Kanten auch über diese, sassen Dreiecke quer im - * Innern, Fund 29.10.) und nur an geraden Segmenten: ein Bogen hat seinen Bogen-Mitten-Griff, die - * Sehnen-Mitte läge neben der Linie. - */ -export function polylineEdgeGrips(g: Extract, owner: Owner): EdgeGrip[] { - const all = g.closed ? ringEdges(g.pts, owner) : openEdges(g.pts, owner); - return all.filter((e) => Math.abs(g.bulge?.[e.aIndex] ?? 0) <= 1e-9); -} diff --git a/src/state/projectSlice.drawingGrips.test.ts b/src/state/projectSlice.drawingGrips.test.ts index e0a2c192..42db1218 100644 --- a/src/state/projectSlice.drawingGrips.test.ts +++ b/src/state/projectSlice.drawingGrips.test.ts @@ -7,7 +7,7 @@ import { describe, it, expect, beforeEach } from "vitest"; import { getState, setState } from "./appStore"; import { sampleProject } from "../model/sampleProject"; -import { drawingVertices } from "./projectSlice"; +import { drawingVertices } from "../core"; import type { Drawing2D } from "../model/types"; const circleDrawing: Drawing2D = { diff --git a/src/state/projectSlice.leaderBendGrips.test.ts b/src/state/projectSlice.leaderBendGrips.test.ts index a29f3319..6bed52b1 100644 --- a/src/state/projectSlice.leaderBendGrips.test.ts +++ b/src/state/projectSlice.leaderBendGrips.test.ts @@ -8,7 +8,7 @@ import { describe, it, expect, beforeEach } from "vitest"; import { getState, setState } from "./appStore"; import { sampleProject } from "../model/sampleProject"; -import { drawingVertices } from "./projectSlice"; +import { drawingVertices } from "../core"; import type { Drawing2D } from "../model/types"; const leaderNoBends: Drawing2D = { diff --git a/src/state/projectSlice.polylineBulge.test.ts b/src/state/projectSlice.polylineBulge.test.ts index 3c9472e7..2e212f59 100644 --- a/src/state/projectSlice.polylineBulge.test.ts +++ b/src/state/projectSlice.polylineBulge.test.ts @@ -7,7 +7,7 @@ import { describe, it, expect, beforeEach } from "vitest"; import { getState, setState } from "./appStore"; import { sampleProject } from "../model/sampleProject"; -import { drawingVertices } from "./projectSlice"; +import { drawingVertices } from "../core"; import type { Drawing2D } from "../model/types"; const openPoly: Drawing2D = { diff --git a/src/state/projectSlice.textFrameGrips.test.ts b/src/state/projectSlice.textFrameGrips.test.ts index 4fb77231..10d1fa3b 100644 --- a/src/state/projectSlice.textFrameGrips.test.ts +++ b/src/state/projectSlice.textFrameGrips.test.ts @@ -12,7 +12,7 @@ import { describe, it, expect, beforeEach } from "vitest"; import { getState, setState } from "./appStore"; import { sampleProject } from "../model/sampleProject"; -import { drawingVertices } from "./projectSlice"; +import { drawingVertices } from "../core"; import { textFrameCorners } from "../text/textFrame"; import type { Drawing2D } from "../model/types"; diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index 9b77ccff..ec413466 100644 --- a/src/state/projectSlice.ts +++ b/src/state/projectSlice.ts @@ -57,22 +57,12 @@ import { PEN_FALLBACK_COLOR, PEN_FALLBACK_WEIGHT, } from "../model/penSets"; -import { lineIntersect } from "../model/geometry"; import { reorderByIds } from "../model/reorder"; import { transformOps } from "../tools/transform"; import type { CopyMode, TransformOp, TransformSelection } from "../tools/transform"; import { uniqueId } from "../tools/types"; -import { centroid as roomCentroid } from "../core"; -import { bulgeArc, bulgeBetweenAngles, bulgeFromSagittaPoint, bulgePointAt, pointOnCircle } from "../core"; -import { - DEFAULT_SCALE_DENOMINATOR, - DIM_DEFAULTS_MM, - dimTextOffsetFromPoint, - dimTextPos, - mmToModel, - modelToMm, -} from "../model/dimension"; -import { textFrameCorners } from "../text/textFrame"; +import { gripPt, type GripRequest } from "../core"; +import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension"; import { DEFAULT_PRESETS, type TextStylePreset } from "../text/richText"; import { t } from "../i18n"; import type { StoreApi } from "./store"; @@ -520,6 +510,28 @@ export function createProjectSlice( coalesceKey?: string, ) => set((s) => commitOps(s, typeof ops === "function" ? ops(s.project) : ops, coalesceKey)); + // Griff-Änderung ([K4] S3): der Kern rechnet sie auf dem Dokument und wendet sie im selben Aufruf an + // (`grips.rs`, ein WASM-Aufruf je Mausschritt); Prüfung, Verlauf und Meldungen wie `commitOps`. + const applyGrip = (req: GripRequest, coalesceKey?: string) => { + let notice: string | undefined; + set((s) => { + const doc = storeDocument(s.project); + const res = doc.commitGrip(s.project, req, coalesceKey, Date.now()); + if ("problems" in res) { + const problems = res.problems; + console.warn("Projektänderung verworfen:", problems); + queueMicrotask(() => get().notify(`${t("project.change.rejected")} ${problems[0]}`, "error")); + return {}; + } + notice = res.notice; + if (res.ops.length === 0) return {}; + opLog.push(res.ops); + if (opLog.length > OP_LOG_LIMIT) opLog.shift(); + return { project: res.project, ...historyPatch(doc) }; + }); + if (notice) get().notify(t(notice as Parameters[0]), "warning"); + }; + return { ...history, @@ -1022,34 +1034,7 @@ export function createProjectSlice( applyChange((p) => [setField("builtinPaletteBanks", { ...p.builtinPaletteBanks, [bank]: visible })]), insertDrawingPoint: (drawingId, segIndex, pt) => - applyChange((p) => - patchItem(p, "drawings2d", drawingId, (d) => { - if (d.geom.shape !== "polyline") return d; - const g = d.geom; - const n = g.pts.length; - const last = segIndex === n - 1; - if (segIndex < 0 || segIndex >= n || (last && !g.closed)) return d; - const a = g.pts[segIndex]; - const b = last ? g.pts[0] : g.pts[segIndex + 1]; - // Bogen: exakt über die Kreisgeometrie in der Winkel-Mitte teilen — - // dieselbe Technik, mit der kernel2d Bogen-Segmente zuschneidet - // (`bulgeBetweenAngles`). Eine Näherung über tessellierte Punkte - // (`bulgePointAt`) wäre hier zu ungenau, weil sie auf Stützstellen - // rundet und der Sagitta-Rückschluss den Fehler verstärkt. - const arc = bulgeArc(a, b, g.bulge?.[segIndex] ?? 0); - const aMid = arc ? arc.a0 + arc.sweep / 2 : 0; - const insertPt = arc ? pointOnCircle(arc.center, arc.r, aMid) : pt; - const sweepSign: 1 | -1 = arc && arc.sweep < 0 ? -1 : 1; - const b1 = arc ? bulgeBetweenAngles(arc.center, arc.r, arc.a0, aMid, sweepSign) : 0; - const b2 = arc ? bulgeBetweenAngles(arc.center, arc.r, aMid, arc.a1, sweepSign) : 0; - const pts = [...g.pts.slice(0, segIndex + 1), insertPt, ...g.pts.slice(segIndex + 1)]; - // Bulge-Array nur mitführen, wenn es eines gab (additiv bleiben). - const nextBulge = g.bulge - ? [...g.bulge.slice(0, segIndex), b1, b2, ...g.bulge.slice(segIndex + 1)] - : undefined; - return { ...d, geom: { ...g, pts, ...(nextBulge ? { bulge: nextBulge } : {}) } }; - }), - ), + applyGrip({ op: "insertPoint", id: drawingId, seg: segIndex, pt: gripPt(pt) }), setPolylineVertexType: (drawingId, index, type) => applyChange((p) => @@ -1062,44 +1047,24 @@ export function createProjectSlice( }), ), - deleteDrawingPoint: (drawingId, index) => - applyChange((p) => { - const d = p.drawings2d.find((x) => x.id === drawingId); - if (!d || d.geom.shape !== "polyline") return []; - const g = d.geom; - const min = g.closed ? 4 : 3; - if (g.pts.length < min) { - get().notify(t("alert.polylineMinPoints"), "warning"); - return []; - } - if (index < 0 || index >= g.pts.length) return []; - const pts = g.pts.filter((_, i) => i !== index); - // Zwei Segmente werden zu einem: der Bulge des ENTFERNTEN Segments - // fällt weg, das verbleibende behält seinen Wert (die exakte - // Bogenform lässt sich nicht erhalten, wenn ihr Stützpunkt entfällt). - const bulge = g.bulge ? g.bulge.filter((_, i) => i !== index) : undefined; - return patchItem(p, "drawings2d", drawingId, (x) => ({ ...x, geom: { ...g, pts, ...(bulge ? { bulge } : {}) } })); - }), + deleteDrawingPoint: (drawingId, index) => applyGrip({ op: "deletePoint", id: drawingId, index }), // ── Editier-Griffe ───────────────────────────────────────────────────── // Diese Aktionen laufen AD-HOC bei jedem Maus-Move-Schritt eines Drags // (kein Draft/Commit-Muster wie bei den Zeichenwerkzeugen) — daher mit // coalesceKey, damit EIN Drag EINEN Undo-Schritt erzeugt statt vieler. - moveGripOf: (drawingId, wallId, index, pt, scaleDenominator) => - applyChange( - (p) => moveGrip(p, drawingId, wallId, index, pt, scaleDenominator), + moveGripOf: (drawingId, wallId, index, pt, scaleDenominator = DEFAULT_SCALE_DENOMINATOR) => + applyGrip( + { op: "moveGrip", drawingId, wallId, index, pt: gripPt(pt), scale: scaleDenominator }, `moveGripOf:${drawingId ?? ""}:${wallId ?? ""}:${index}`, ), moveElementByOf: (drawingId, wallId, delta) => - applyChange( - (p) => moveElementBy(p, drawingId, wallId, delta), - `moveElementByOf:${drawingId ?? ""}:${wallId ?? ""}`, - ), + applyGrip({ op: "moveBy", drawingId, wallId, delta: gripPt(delta) }, `moveElementByOf:${drawingId ?? ""}:${wallId ?? ""}`), moveEdgeOf: (drawingId, wallId, aIndex, bIndex, delta) => - applyChange( - (p) => moveEdge(p, drawingId, wallId, aIndex, bIndex, delta), + applyGrip( + { op: "moveEdge", drawingId, wallId, a: aIndex, b: bIndex, delta: gripPt(delta) }, `moveEdgeOf:${drawingId ?? ""}:${wallId ?? ""}:${aIndex}:${bIndex}`, ), @@ -1153,8 +1118,7 @@ export function createProjectSlice( applyChange((p) => fieldOps(p, "drawingLevels", reorderByIds(p.drawingLevels, ids, op))), // ── Größe (Resize um Anker) ──────────────────────────────────────────── - resizeElement: (kind, id, w, h, anchor) => - applyChange((p) => resizeElement(p, kind, id, w, h, anchor)), + resizeElement: (kind, id, w, h, anchor) => applyGrip({ op: "resize", kind, id, w, h, fx: anchor.fx, fy: anchor.fy }), // ── Transformation ───────────────────────────────────────────────────── commitTransformOn: (sel, op, points, copyMode, count) => @@ -1163,44 +1127,43 @@ export function createProjectSlice( // ── Wand-Attribute ───────────────────────────────────────────────────── updateWall: (id, patch, coalesceKey) => applyChange((p) => patchItem(p, "walls", id, patch), coalesceKey), + // Dicke einer einschichtigen Wand (Kern `grips.rs`); id und Name eines ggf. neuen Wandtyps kommen von hier. setWallThickness: (wallId, thickness) => - applyChange((p) => setWallThickness(p, wallId, thickness)), + applyGrip({ + op: "wallThickness", + id: wallId, + thickness, + newId: `wt-${Date.now()}`, + newName: t("default.wallTypeSingle", { thickness: thickness.toFixed(2) }), + }), // ── Decken-Editieren ────────────────────────────────────────────────── // (coalesceKey: siehe Kommentar bei moveGripOf — auch hier läuft die // Mutation bei jedem Maus-Move-Schritt eines Drags.) moveCeilingGrip: (ceilingId, index, pt) => - applyChange( - (p) => mapCeiling(p, ceilingId, (c) => ({ - ...c, - outline: c.outline.map((v, i) => (i === index ? pt : v)), - })), - `moveCeilingGrip:${ceilingId}:${index}`, - ), + applyGrip({ op: "ceilingGrip", id: ceilingId, index, pt: gripPt(pt) }, `moveCeilingGrip:${ceilingId}:${index}`), moveCeilingBy: (ceilingId, delta) => - applyChange( - (p) => mapCeiling(p, ceilingId, (c) => ({ - ...c, - outline: c.outline.map((v) => ({ x: v.x + delta.x, y: v.y + delta.y })), - })), - `moveCeilingBy:${ceilingId}`, - ), + applyGrip({ op: "ceilingBy", id: ceilingId, delta: gripPt(delta) }, `moveCeilingBy:${ceilingId}`), moveCeilingEdge: (ceilingId, aIndex, bIndex, delta) => - applyChange( - (p) => mapCeiling(p, ceilingId, (c) => ({ - ...c, - outline: movePolygonEdge(c.outline, aIndex, bIndex, delta, true), - })), + applyGrip( + { op: "ceilingEdge", id: ceilingId, a: aIndex, b: bIndex, delta: gripPt(delta) }, `moveCeilingEdge:${ceilingId}:${aIndex}:${bIndex}`, ), updateCeiling: (id, patch) => applyChange((p) => mapCeiling(p, id, (c) => ({ ...c, ...patch }))), + // Dicke einer einschichtigen Decke (Kern `grips.rs`), analog zur Wand. setCeilingThickness: (ceilingId, thickness) => - applyChange((p) => setCeilingThickness(p, ceilingId, thickness)), + applyGrip({ + op: "ceilingThickness", + id: ceilingId, + thickness, + newId: `ct-${Date.now()}`, + newName: t("default.ceilingTypeSingle", { thickness: thickness.toFixed(2) }), + }), // ── Öffnungs-Editieren ──────────────────────────────────────────────── updateOpening: (id, patch) => applyChange((p) => patchItem(p, "openings", id, patch)), @@ -1212,110 +1175,35 @@ export function createProjectSlice( // die GEGENÜBERLIEGENDE Ecke bleibt fix → der Umriss bleibt ein achsparalleles // Rechteck (die Dach-Geometrie rechnet ohnehin auf der Bounding-Box). moveRoofGrip: (roofId, index, pt) => - applyChange( - (p) => - patchItem(p, "roofs", roofId, (r) => { - if (r.outline.length < 4) return r; - const opp = r.outline[(index + 2) % r.outline.length]; - const x0 = Math.min(pt.x, opp.x); - const x1 = Math.max(pt.x, opp.x); - const y0 = Math.min(pt.y, opp.y); - const y1 = Math.max(pt.y, opp.y); - return { - ...r, - outline: [ - { x: x0, y: y0 }, - { x: x1, y: y0 }, - { x: x1, y: y1 }, - { x: x0, y: y1 }, - ], - }; - }), - `moveRoofGrip:${roofId}`, - ), + applyGrip({ op: "roofGrip", id: roofId, index, pt: gripPt(pt) }, `moveRoofGrip:${roofId}`), // Dach als Ganzes verschieben (Verschiebe-Griff). - moveRoofBy: (roofId, delta) => - applyChange( - (p) => - patchItem(p, "roofs", roofId, (r) => ({ - ...r, - outline: r.outline.map((v) => ({ x: v.x + delta.x, y: v.y + delta.y })), - })), - `moveRoofBy:${roofId}`, - ), + moveRoofBy: (roofId, delta) => applyGrip({ op: "roofBy", id: roofId, delta: gripPt(delta) }, `moveRoofBy:${roofId}`), // ── Treppen-Editieren ────────────────────────────────────────────────── // (coalesceKey: siehe Kommentar bei moveGripOf.) - moveStairBy: (stairId, delta) => - applyChange( - (p) => - mapStair(p, stairId, (s) => ({ - ...s, - start: { x: s.start.x + delta.x, y: s.start.y + delta.y }, - ...(s.center - ? { center: { x: s.center.x + delta.x, y: s.center.y + delta.y } } - : {}), - })), - `moveStairBy:${stairId}`, - ), + moveStairBy: (stairId, delta) => applyGrip({ op: "stairBy", id: stairId, delta: gripPt(delta) }, `moveStairBy:${stairId}`), updateStair: (id, patch) => applyChange((p) => mapStair(p, id, (s) => ({ ...s, ...patch }))), // ── Raum-Editieren ────────────────────────────────────────────────────── // (coalesceKey: siehe Kommentar bei moveGripOf.) - moveRoomBy: (roomId, delta) => - applyChange( - (p) => - mapRoom(p, roomId, (r) => ({ - ...r, - boundary: r.boundary.map((v) => ({ x: v.x + delta.x, y: v.y + delta.y })), - ...(r.stampAnchor - ? { - stampAnchor: { - x: r.stampAnchor.x + delta.x, - y: r.stampAnchor.y + delta.y, - }, - } - : {}), - })), - `moveRoomBy:${roomId}`, - ), + moveRoomBy: (roomId, delta) => applyGrip({ op: "roomBy", id: roomId, delta: gripPt(delta) }, `moveRoomBy:${roomId}`), moveRoomGrip: (roomId, index, pt) => - applyChange( - (p) => - mapRoom(p, roomId, (r) => ({ - ...r, - boundary: r.boundary.map((v, i) => (i === index ? pt : v)), - })), - `moveRoomGrip:${roomId}:${index}`, - ), + applyGrip({ op: "roomGrip", id: roomId, index, pt: gripPt(pt) }, `moveRoomGrip:${roomId}:${index}`), moveRoomEdge: (roomId, aIndex, bIndex, delta) => - applyChange( - (p) => - mapRoom(p, roomId, (r) => ({ - ...r, - boundary: movePolygonEdge(r.boundary, aIndex, bIndex, delta, true), - })), + applyGrip( + { op: "roomEdge", id: roomId, a: aIndex, b: bIndex, delta: gripPt(delta) }, `moveRoomEdge:${roomId}:${aIndex}:${bIndex}`, ), updateRoom: (id, patch) => applyChange((p) => mapRoom(p, id, (r) => ({ ...r, ...patch }))), - moveRoomStamp: (roomId, delta) => - applyChange((p) => - mapRoom(p, roomId, (r) => { - const base = r.stampAnchor ?? roomCentroid(r.boundary); - return { - ...r, - stampAnchor: { x: base.x + delta.x, y: base.y + delta.y }, - }; - }), - ), + moveRoomStamp: (roomId, delta) => applyGrip({ op: "roomStamp", id: roomId, delta: gripPt(delta) }), setRoomStampAnchor: (roomId, anchor) => applyChange((p) => mapRoom(p, roomId, (r) => ({ ...r, stampAnchor: anchor }))), @@ -1379,422 +1267,6 @@ function mapCeiling( return patchItem(project, "ceilings", ceilingId, fn); } -/** - * Setzt die Gesamtdicke einer einschichtigen Wand über ihre Wandtyp-Schicht. - * Wenn der Wandtyp einschichtig ist UND nur von dieser Wand genutzt wird, wird - * er direkt editiert. Sonst wird ein dedizierter einschichtiger Wandtyp (Klon - * der ersten Schicht des aktuellen Typs) erzeugt und der Wand zugewiesen. - */ -function setWallThickness( - project: Project, - wallId: string, - thickness: number, -): CoreOp[] { - if (!isFinite(thickness) || thickness <= 0) return []; - const wall = project.walls.find((w) => w.id === wallId); - if (!wall) return []; - const wt = project.wallTypes.find((t) => t.id === wall.wallTypeId); - if (!wt || wt.layers.length === 0) return []; - - const single = wt.layers.length === 1; - const usedByOthers = project.walls.some( - (w) => w.id !== wallId && w.wallTypeId === wt.id, - ); - - if (single && !usedByOthers) { - // Direkt die Schichtdicke des (exklusiven, einschichtigen) Wandtyps setzen. - return patchItem(project, "wallTypes", wt.id, (t) => ({ ...t, layers: [{ ...t.layers[0], thickness }] })); - } - - // Dedizierten einschichtigen Wandtyp erzeugen (erste Schicht klonen) und der - // Wand zuweisen — damit die Dicke nur diese Wand betrifft. - const id = `wt-${Date.now()}`; - const clone = { - id, - name: t("default.wallTypeSingle", { thickness: thickness.toFixed(2) }), - layers: [{ ...wt.layers[0], thickness }], - }; - return [...addItems("wallTypes", [clone]), ...patchItem(project, "walls", wallId, { wallTypeId: id })]; -} - -/** - * Setzt die Gesamtdicke einer einschichtigen Decke über ihre Deckentyp-Schicht - * — analog `setWallThickness`. Wenn der aktive Aufbau-Typ einschichtig UND ein - * DEDIZIERTER Deckentyp (`ceilingTypeId`) ist, der nur von dieser Decke genutzt - * wird, wird er direkt editiert. Sonst wird ein neuer, dedizierter - * einschichtiger Deckentyp (Klon der ersten Schicht des aktuellen Aufbaus) - * erzeugt und der Decke zugewiesen. Der geteilte LEGACY-Wandtyp - * (`Ceiling.wallTypeId`) wird dabei NIE mutiert — er gehört den Wänden. - */ -function setCeilingThickness( - project: Project, - ceilingId: string, - thickness: number, -): CoreOp[] { - if (!isFinite(thickness) || thickness <= 0) return []; - const ceiling = (project.ceilings ?? []).find((c) => c.id === ceilingId); - if (!ceiling) return []; - const activeId = ceiling.ceilingTypeId ?? ceiling.wallTypeId; - const ct = - (project.ceilingTypes ?? []).find((t) => t.id === ceiling.ceilingTypeId) ?? - project.wallTypes.find((t) => t.id === ceiling.wallTypeId); - if (!ct || ct.layers.length === 0) return []; - - const single = ct.layers.length === 1; - const usedByOthers = (project.ceilings ?? []).some( - (c) => c.id !== ceilingId && (c.ceilingTypeId ?? c.wallTypeId) === activeId, - ); - - if (single && !usedByOthers && ceiling.ceilingTypeId) { - // Direkt die Schichtdicke des (exklusiven, einschichtigen) Deckentyps setzen. - return patchItem(project, "ceilingTypes", ct.id, (t) => ({ ...t, layers: [{ ...t.layers[0], thickness }] })); - } - - // Dedizierten einschichtigen Deckentyp erzeugen (erste Schicht klonen) und - // der Decke zuweisen — damit die Dicke nur diese Decke betrifft. - const id = `ct-${Date.now()}`; - const clone = { - id, - name: t("default.ceilingTypeSingle", { thickness: thickness.toFixed(2) }), - layers: [{ ...ct.layers[0], thickness }], - }; - return [ - ...addItems("ceilingTypes", [clone]), - ...patchItem(project, "ceilings", ceilingId, (c) => ({ ...c, ceilingTypeId: id, thickness: undefined })), - ]; -} - -// ── Resize (Skalierung auf Zielmaß um einen Anker) ─────────────────────────── - -/** - * Skaliert ein Element auf Zielbreite `w` × -höhe `h` (Meter) um einen - * Ankerpunkt. `anchor.fx/fy ∈ [0,1]` liegen relativ zur aktuellen bbox - * (0,0 = oben-links, 1,1 = unten-rechts). Der Ankerpunkt bleibt fix; alle - * übrigen Punkte werden um die Skalierungsfaktoren um ihn herum gestreckt. - */ -function resizeElement( - project: Project, - kind: "wall" | "drawing2d", - id: string, - w: number, - h: number, - anchor: { fx: number; fy: number }, -): CoreOp[] { - if (kind === "drawing2d") { - return patchItem(project, "drawings2d", id, (d) => ({ ...d, geom: resizeGeom(d.geom, w, h, anchor) })); - } - return patchItem(project, "walls", id, (wall) => { - const box = bbox2([wall.start, wall.end]); - const { ax, ay, sx, sy } = scaleAround(box, w, h, anchor); - const apply = (p: Vec2): Vec2 => ({ - x: ax + (p.x - ax) * sx, - y: ay + (p.y - ay) * sy, - }); - return { ...wall, start: apply(wall.start), end: apply(wall.end) }; - }); -} - -/** bbox einer Punktliste. */ -function bbox2(pts: Vec2[]): { minX: number; minY: number; maxX: number; maxY: number } { - let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; - for (const p of pts) { - minX = Math.min(minX, p.x); minY = Math.min(minY, p.y); - maxX = Math.max(maxX, p.x); maxY = Math.max(maxY, p.y); - } - if (!isFinite(minX)) return { minX: 0, minY: 0, maxX: 0, maxY: 0 }; - return { minX, minY, maxX, maxY }; -} - -/** - * Liefert Ankerpunkt (ax,ay) und Skalierungsfaktoren (sx,sy), um eine bbox auf - * Zielbreite `w` × -höhe `h` zu bringen. Bei Null-Ausdehnung in einer Achse - * bleibt der Faktor 1 (keine Division durch 0, keine Verschiebung). - */ -function scaleAround( - box: { minX: number; minY: number; maxX: number; maxY: number }, - w: number, - h: number, - anchor: { fx: number; fy: number }, -): { ax: number; ay: number; sx: number; sy: number } { - const bw = box.maxX - box.minX; - const bh = box.maxY - box.minY; - const ax = box.minX + anchor.fx * bw; - const ay = box.minY + anchor.fy * bh; - const sx = bw > 1e-9 ? w / bw : 1; - const sy = bh > 1e-9 ? h / bh : 1; - return { ax, ay, sx, sy }; -} - -/** - * Skaliert eine 2D-Form auf Zielmaß um den Anker. - * • line/polyline/rect: jeder Punkt um den Anker skaliert (B/H aus bbox). - * • circle: Radius = halbe Zielbreite (min/Mittelwert wäre auch denkbar; Breite - * ist eindeutig), Mittelpunkt um den Anker verschoben. - * • arc: wie circle (Radius aus Zielbreite), Winkel unverändert. - * • text: nur die Einfügeposition wird um den Anker verschoben; die Schrifthöhe - * bleibt (Text skaliert über `height`, nicht über bbox — bewusst unverändert). - */ -function resizeGeom( - g: import("../model/types").Drawing2DGeom, - w: number, - h: number, - anchor: { fx: number; fy: number }, -): import("../model/types").Drawing2DGeom { - switch (g.shape) { - case "line": - case "xline": - case "ray": { - const { ax, ay, sx, sy } = scaleAround(bbox2([g.a, g.b]), w, h, anchor); - const f = (p: Vec2): Vec2 => ({ x: ax + (p.x - ax) * sx, y: ay + (p.y - ay) * sy }); - return { ...g, a: f(g.a), b: f(g.b) }; - } - case "polyline": { - const { ax, ay, sx, sy } = scaleAround(bbox2(g.pts), w, h, anchor); - const f = (p: Vec2): Vec2 => ({ x: ax + (p.x - ax) * sx, y: ay + (p.y - ay) * sy }); - return { ...g, pts: g.pts.map(f) }; - } - case "rect": { - const box = bbox2([g.min, g.max]); - const { ax, ay, sx, sy } = scaleAround(box, w, h, anchor); - const f = (p: Vec2): Vec2 => ({ x: ax + (p.x - ax) * sx, y: ay + (p.y - ay) * sy }); - const a = f(g.min); - const b = f(g.max); - return { - ...g, - min: { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y) }, - max: { x: Math.max(a.x, b.x), y: Math.max(a.y, b.y) }, - }; - } - case "circle": - case "arc": { - // bbox eines Kreises ist 2r×2r; der Anker liegt relativ dazu. - const box = { - minX: g.center.x - g.r, - minY: g.center.y - g.r, - maxX: g.center.x + g.r, - maxY: g.center.y + g.r, - }; - const ax = box.minX + anchor.fx * (2 * g.r); - const ay = box.minY + anchor.fy * (2 * g.r); - const r = Math.max(w, h) / 2 > 0 ? Math.max(w, h) / 2 : g.r; - const sx = g.r > 1e-9 ? (w / 2) / g.r : 1; - const sy = g.r > 1e-9 ? (h / 2) / g.r : 1; - // Mittelpunkt anhand der nicht-uniformen Skalierung um den Anker schieben, - // den Radius aber als skalaren Kreis (max der Zielmaße/2) setzen. - const center: Vec2 = { - x: ax + (g.center.x - ax) * sx, - y: ay + (g.center.y - ay) * sy, - }; - return { ...g, center, r }; - } - case "ellipse": { - // bbox: rotation=0 angenommen (das Werkzeug erzeugt nur achsparallele - // Ellipsen); rx/ry unabhängig skaliert, Mittelpunkt um den Anker verschoben. - const box = { - minX: g.center.x - g.rx, - minY: g.center.y - g.ry, - maxX: g.center.x + g.rx, - maxY: g.center.y + g.ry, - }; - const { ax, ay, sx, sy } = scaleAround(box, w, h, anchor); - const center: Vec2 = { - x: ax + (g.center.x - ax) * sx, - y: ay + (g.center.y - ay) * sy, - }; - return { ...g, center, rx: Math.max(1e-3, g.rx * sx), ry: Math.max(1e-3, g.ry * sy) }; - } - case "bezier": - case "spline": { - const { ax, ay, sx, sy } = scaleAround(bbox2(g.pts), w, h, anchor); - const f = (p: Vec2): Vec2 => ({ x: ax + (p.x - ax) * sx, y: ay + (p.y - ay) * sy }); - return { ...g, pts: g.pts.map(f) }; - } - case "text": { - // Text: nur die Einfügeposition um den Anker schieben (Höhe bleibt). - const box = { minX: g.at.x, minY: g.at.y, maxX: g.at.x, maxY: g.at.y }; - const { ax, ay, sx, sy } = scaleAround(box, w, h, anchor); - return { ...g, at: { x: ax + (g.at.x - ax) * sx, y: ay + (g.at.y - ay) * sy } }; - } - case "block": { - // Wie Text: nur der Einfügepunkt wandert (kein Skalierungsfaktor am - // Symbol selbst in v1). - const box = { minX: g.at.x, minY: g.at.y, maxX: g.at.x, maxY: g.at.y }; - const { ax, ay, sx, sy } = scaleAround(box, w, h, anchor); - return { ...g, at: { x: ax + (g.at.x - ax) * sx, y: ay + (g.at.y - ay) * sy } }; - } - case "image": { - const box = bbox2([g.min, g.max]); - const { ax, ay, sx, sy } = scaleAround(box, w, h, anchor); - const f = (p: Vec2): Vec2 => ({ x: ax + (p.x - ax) * sx, y: ay + (p.y - ay) * sy }); - const a = f(g.min); - const b = f(g.max); - return { - ...g, - min: { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y) }, - max: { x: Math.max(a.x, b.x), y: Math.max(a.y, b.y) }, - }; - } - default: - return g; - } -} - -/** - * Kreis, solange rx≈ry (relative Toleranz 0.5%) — sonst Ellipse (rotation 0). - * Trägt den Kreis-zu-Ellipse-Formwandel beim Griff-Ziehen (Nutzer-Wunsch: - * „Kreis wird wie bisher erstellt, kann beim Bearbeiten zur Ellipse werden"); - * symmetrisch nutzbar auch für die Rückrichtung (Ellipse → Kreis, wenn man - * die Halbachsen wieder aneinander annähert). - */ -function ellipseOrCircle( - center: Vec2, - rx: number, - ry: number, -): import("../model/types").Drawing2DGeom { - if (Math.abs(rx - ry) <= 0.005 * Math.max(rx, ry)) { - return { shape: "circle", center, r: (rx + ry) / 2 }; - } - return { shape: "ellipse", center, rx, ry, rotation: 0 }; -} - -// ── Editier-Griffe (verschoben aus App.tsx, 1:1) ───────────────────────────── - -/** - * Editier-Griffe (Eckpunkte) eines 2D-Zeichenelements in Modell-Metern. - * line/polyline/rect: Eckpunkte. circle: EIN Radius-Griff (Ost, Index 0). - * arc: Start-/End-Winkel-Griff (Index 0/1, ändern a0/a1) + ein Radius-Griff - * auf halbem Bogen (Index 2, ändert r) — siehe {@link moveGrip}. - */ -export function drawingVertices( - d: import("../model/types").Drawing2D, - /** Papier-Massstab (1:N) — nur für die Bemassungs-Griffe, deren Lage von - * der in Papier-mm angegebenen Schrifthöhe abhängt. */ - scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR, -): Vec2[] { - const g = d.geom; - if (g.shape === "line" || g.shape === "xline" || g.shape === "ray") return [g.a, g.b]; - // Polylinie: Eckpunkt-Griffe (Index 0..n-1) PLUS ein Bulge-Griff je Segment - // (Index n..; Apex des aktuellen Bogens, oder Sehnen-Mitte bei bulge=0) — - // senkrecht zur Sehne ziehen krümmt genau dieses Segment (s. moveGrip). - if (g.shape === "polyline") { - const n = g.pts.length; - const closeSeg = g.closed && n > 2; - const segCount = Math.max(0, n - 1) + (closeSeg ? 1 : 0); - const bulgeGrips: Vec2[] = []; - for (let i = 0; i < segCount; i++) { - const a = g.pts[i]; - const b = i === n - 1 ? g.pts[0] : g.pts[i + 1]; - bulgeGrips.push(bulgePointAt(a, b, g.bulge?.[i] ?? 0, 0.5)); - } - return [...g.pts, ...bulgeGrips]; - } - if (g.shape === "rect" || g.shape === "image") { - return [ - g.min, - { x: g.max.x, y: g.min.y }, - g.max, - { x: g.min.x, y: g.max.y }, - ]; - } - // Kreis: zwei Griffe (Ost/Nord, wie bei der Ellipse) — zieht man EINEN der - // beiden unabhängig, wird der Kreis zur Ellipse (s. `moveGrip`). So bleibt - // ein Kreis ein Kreis, solange man ihn nicht gezielt verzerrt (Nutzer- - // Wunsch: „Kreis erstellen wie bisher, beim Bearbeiten kann er zur Ellipse - // werden"). - if (g.shape === "circle") { - return [ - { x: g.center.x + g.r, y: g.center.y }, - { x: g.center.x, y: g.center.y + g.r }, - ]; - } - if (g.shape === "arc") { - const mid = (g.a0 + g.a1) / 2; - return [ - { x: g.center.x + g.r * Math.cos(g.a0), y: g.center.y + g.r * Math.sin(g.a0) }, - { x: g.center.x + g.r * Math.cos(g.a1), y: g.center.y + g.r * Math.sin(g.a1) }, - { x: g.center.x + g.r * Math.cos(mid), y: g.center.y + g.r * Math.sin(mid) }, - ]; - } - // Ellipse: zwei Griffe (Index 0 = rx-Achse, Index 1 = ry-Achse), gedreht um - // `rotation` (0 beim heutigen Werkzeug) — siehe `moveGrip`. - if (g.shape === "ellipse") { - const c = Math.cos(g.rotation), s = Math.sin(g.rotation); - return [ - { x: g.center.x + g.rx * c, y: g.center.y + g.rx * s }, - { x: g.center.x - g.ry * s, y: g.center.y + g.ry * c }, - ]; - } - // Bezier/Spline: alle Kontroll-/Wegpunkte als Griffe (wie polyline). - if (g.shape === "bezier" || g.shape === "spline") return [...g.pts]; - // Bemassung: Griff 0..N-1 = jeder Punkt der Kette (wie polyline); EIN - // zusätzlicher Griff (Index N) sitzt AUF der Masslinie (Mitte der Kette) — - // ihn zu ziehen ändert nur `offset`, nicht die Punkte (s. moveGrip). - if (g.shape === "dimension") { - const a = g.pts[0], b = g.pts[g.pts.length - 1]; - const dx = b.x - a.x, dy = b.y - a.y; - const len = Math.hypot(dx, dy) || 1; - const nx = (-dy / len) * g.offset, ny = (dx / len) * g.offset; - const mid: Vec2 = { x: (a.x + b.x) / 2 + nx, y: (a.y + b.y) / 2 + ny }; - // Reihenfolge: Kettenpunkte · Offset-Griff · JE SEGMENT ein Masszahl-Griff - // (verschiebt nur die Zahl, s. moveGrip) — dieselbe Ordnung erwartet - // moveGrip beim Auflösen des Index. - const heightM = mmToModel(g.textHeightMm ?? DIM_DEFAULTS_MM.textHeight, scaleDenominator); - const textGrips = g.pts.slice(0, -1).map((p0, i) => { - const off = g.textOffsetsMm?.[i]; - return dimTextPos( - p0, - g.pts[i + 1], - g.offset, - heightM, - off - ? { along: mmToModel(off.along, scaleDenominator), perp: mmToModel(off.perp, scaleDenominator) } - : undefined, - ); - }); - return [...g.pts, mid, ...textGrips]; - } - // Kote: EIN Griff an der Dreieck-Spitze (zum Verschieben; siehe moveGrip). - if (g.shape === "kote") return [g.at]; - // Detail-/Schnitt-Verweis: EIN Griff am Kreis-Zentrum (zum Verschieben). - if (g.shape === "detailref") return [g.at]; - // Massstabsbalken: EIN Griff an der linken unteren Ecke (zum Verschieben). - if (g.shape === "scalebar") return [g.at]; - // Punkt-/Knotenmarker: EIN Griff am Zentrum (zum Verschieben). - if (g.shape === "pointmarker") return [g.at]; - // Text: Griff 0 am Ankerpunkt; trägt der Text einen Leader, zusätzlich ein - // Griff je Knickpunkt (`leaderBendPoints`, falls gesetzt) und ein - // ABSCHLIESSENDER Griff an der Spitze (Pfeilspitze unabhängig verschiebbar; - // s. moveGrip) — Reihenfolge Anker→Knicke→Spitze, wie der Pfad gerendert wird. - // Text-entlang-Pfad: die Pfadpunkte SELBST sind die Griffe (wie polyline), - // ersetzt das Anker/Leader-Griffmodell komplett (schliessen sich aus). - // Textspalte (`width` gesetzt, kein Leader/Pfad): VIER Rahmen-Eckpunkte als - // Griffe (Nutzer-Wunsch: "nicht nur ein Griff unten links bei der ersten - // Glyphe") — Ziehen ändert NUR die Spaltenbreite (InDesign-Verhalten, - // Nutzer-Entscheidung), s. `moveGrip`. Dieselbe Rahmen-Berechnung wie der - // Auswahl-Rahmen im Grundriss (`text/textFrame.ts`), damit Griffe und - // sichtbarer Rahmen immer übereinstimmen. - if (g.shape === "text") { - if (g.pathPts) return [...g.pathPts]; - if (g.leaderTarget) return [g.at, ...(g.leaderBendPoints ?? []), g.leaderTarget]; - if (g.width && g.width > 0) { - return textFrameCorners({ - at: g.at, - text: g.text, - heightM: g.height, - angle: g.angle, - marks: g.marks, - doc: g.doc, - wrapWidth: g.width, - }); - } - return [g.at]; - } - // Block-Instanz: EIN Griff am Einfügepunkt (Rotation läuft über move/mirror, - // kein eigener Rotations-Griff in v1; s. moveGrip). - if (g.shape === "block") return [g.at]; - return []; -} - /** * Fügt ein Bild-Zeichenelement (eingebettete Data-URL, z. B. Foto/Logo oder * gerasterte PDF-Seite) achsparallel bei `[at .. at+size]` an — analog zu den @@ -1823,393 +1295,3 @@ export function imageDrawing2d( }, }; } - -/** - * Verschiebt den Griff `index` des selektierten Elements (2D-Element ODER Wand) - * auf `pt` (immutabel). Beim Rechteck bleibt die Achsparallelität erhalten. - */ -function moveGrip( - project: Project, - drawingId: string | null, - wallId: string | null, - index: number, - pt: Vec2, - /** Papier-Massstab (1:N) — nur für den Masszahl-Griff, s. `drawingVertices`. */ - scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR, -): CoreOp[] { - // Objekt-Sperre: gesperrte Elemente lassen sich anwählen, aber nicht - // ziehen (s. Kommentar bei `onPlanSelect` in useMouseSelectionHandlers.ts). - if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return []; - if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return []; - if (drawingId) { - return patchItem(project, "drawings2d", drawingId, (d) => { - const g = d.geom; - if (g.shape === "line" || g.shape === "xline" || g.shape === "ray") { - return { ...d, geom: index === 0 ? { ...g, a: pt } : { ...g, b: pt } }; - } - if (g.shape === "polyline") { - const n = g.pts.length; - if (index < n) { - const pts = g.pts.map((p, i) => (i === index ? pt : p)); - return { ...d, geom: { ...g, pts } }; - } - // Bulge-Griff (Index ≥ n): Segment-Mitte senkrecht zur Sehne gezogen - // → neuer Bogen-Faktor für GENAU dieses Segment (s. drawingVertices). - const segIndex = index - n; - const a = g.pts[segIndex]; - const b = segIndex === n - 1 ? g.pts[0] : g.pts[segIndex + 1]; - const bulgeVal = bulgeFromSagittaPoint(a, b, pt); - const bulge = [...(g.bulge ?? [])]; - while (bulge.length <= segIndex) bulge.push(0); - bulge[segIndex] = bulgeVal; - return { ...d, geom: { ...g, bulge } }; - } - if (g.shape === "bezier" || g.shape === "spline") { - const pts = g.pts.map((p, i) => (i === index ? pt : p)); - return { ...d, geom: { ...g, pts } }; - } - // Bemassung: Griff 0..N-1 verschiebt den jeweiligen Kettenpunkt - // (Masszahlen folgen automatisch, s. Rendering); der LETZTE Griff - // (auf der Masslinie) ändert nur `offset` — Normalabstand von `pt` - // zur (unveränderten) Punktreihe. - if (g.shape === "dimension") { - if (index < g.pts.length) { - const pts = g.pts.map((p, i) => (i === index ? pt : p)); - return { ...d, geom: { ...g, pts } }; - } - if (index === g.pts.length) { - const a = g.pts[0], b = g.pts[g.pts.length - 1]; - const dx = b.x - a.x, dy = b.y - a.y; - const len = Math.hypot(dx, dy) || 1; - const nx = -dy / len, ny = dx / len; - const offset = (pt.x - a.x) * nx + (pt.y - a.y) * ny; - return { ...d, geom: { ...g, offset } }; - } - // Masszahl-Griff: verschiebt NUR die Zahl des betroffenen Segments - // (Geometrie bleibt unangetastet) und rastet nahe der Standardlage - // ein, s. `model/dimension.ts::dimTextOffsetFromPoint`. - const seg = index - g.pts.length - 1; - if (seg < 0 || seg >= g.pts.length - 1) return d; - const height = mmToModel(g.textHeightMm ?? DIM_DEFAULTS_MM.textHeight, scaleDenominator); - const m = dimTextOffsetFromPoint(g.pts[seg], g.pts[seg + 1], g.offset, height, pt); - // Zurück in Papier-mm speichern (Einheit des Modells). - const next = { - along: modelToMm(m.along, scaleDenominator), - perp: modelToMm(m.perp, scaleDenominator), - }; - const textOffsetsMm = Array.from({ length: g.pts.length - 1 }, (_, i) => - i === seg ? next : (g.textOffsetsMm?.[i] ?? { along: 0, perp: 0 }), - ); - return { ...d, geom: { ...g, textOffsetsMm } }; - } - if (g.shape === "rect" || g.shape === "image") { - const corners = [ - g.min, - { x: g.max.x, y: g.min.y }, - g.max, - { x: g.min.x, y: g.max.y }, - ]; - const opp = corners[(index + 2) % 4]; - const min = { x: Math.min(pt.x, opp.x), y: Math.min(pt.y, opp.y) }; - const max = { x: Math.max(pt.x, opp.x), y: Math.max(pt.y, opp.y) }; - return { ...d, geom: { ...g, min, max } }; - } - // Text: Griff 0 = Ankerpunkt; bei Leader zusätzlich ein Griff je - // Knickpunkt UND ein ABSCHLIESSENDER Griff am Zielpunkt (Reihenfolge - // wie `drawingVertices`: Anker→Knicke→Spitze); trägt der Text einen - // Pfad, adressiert der Index einen Pfadpunkt; Textspalte (kein - // Leader/Pfad, `width` gesetzt) hat 4 Rahmen-Eck-Griffe (s. - // drawingVertices) — dieselbe Reihenfolge (pathPts > leaderTarget > - // Breiten-Ecken > einzelner Anker) MUSS hier gespiegelt werden, sonst - // adressiert ein Griff-Index das falsche Verhalten. - if (g.shape === "text") { - if (g.pathPts) { - const pathPts = g.pathPts.map((pp, i) => (i === index ? pt : pp)); - return { ...d, geom: { ...g, pathPts } }; - } - if (g.leaderTarget) { - const bends = g.leaderBendPoints ?? []; - const tipIndex = bends.length + 1; - if (index === 0) return { ...d, geom: { ...g, at: pt } }; - if (index === tipIndex) return { ...d, geom: { ...g, leaderTarget: pt } }; - if (index > 0 && index < tipIndex) { - const leaderBendPoints = bends.map((bp, i) => (i === index - 1 ? pt : bp)); - return { ...d, geom: { ...g, leaderBendPoints } }; - } - return d; - } - if (g.width && g.width > 0 && index >= 0 && index < 4) { - // Nur die Breite ändert sich (InDesign-Textrahmen-Verhalten, - // Nutzer-Entscheidung) — Höhe bleibt inhaltsgetrieben. Ziehen wird - // auf die LOKALE x-Achse projiziert (rotationsfest): linke Ecken - // (Index 0/3, s. textFrameCorners-Reihenfolge oben-links/oben- - // rechts/unten-rechts/unten-links) verschieben zusätzlich `at`, - // damit die RECHTE Kante fest bleibt; rechte Ecken (1/2) lassen - // `at`/die linke Kante fest. - const cos = Math.cos(g.angle); - const sin = Math.sin(g.angle); - const dx = pt.x - g.at.x; - const dy = pt.y - g.at.y; - const localX = dx * cos + dy * sin; - const MIN_WIDTH = 0.1; - const isLeft = index === 0 || index === 3; - if (isLeft) { - const width = Math.max(MIN_WIDTH, g.width - localX); - const at = { x: g.at.x + localX * cos, y: g.at.y + localX * sin }; - return { ...d, geom: { ...g, at, width } }; - } - const width = Math.max(MIN_WIDTH, localX); - return { ...d, geom: { ...g, width } }; - } - return { ...d, geom: { ...g, at: pt } }; - } - // Kote: der einzige Griff (Index 0) sitzt an der Dreieck-Spitze. - if (g.shape === "kote") return { ...d, geom: { ...g, at: pt } }; - // Detail-/Schnitt-Verweis: der einzige Griff (Index 0) sitzt am Kreis-Zentrum. - if (g.shape === "detailref") return { ...d, geom: { ...g, at: pt } }; - // Massstabsbalken: der einzige Griff (Index 0) sitzt an der linken unteren Ecke. - if (g.shape === "scalebar") return { ...d, geom: { ...g, at: pt } }; - // Punkt-/Knotenmarker: der einzige Griff (Index 0) sitzt am Zentrum. - if (g.shape === "pointmarker") return { ...d, geom: { ...g, at: pt } }; - // Block-Instanz: der einzige Griff (Index 0) sitzt am Einfügepunkt. - if (g.shape === "block") return { ...d, geom: { ...g, at: pt } }; - // Kreis: Griff 0 (Ost) bzw. 1 (Nord) — zieht man die beiden Achsen - // unabhängig auseinander, wird der Kreis zur Ellipse (rotation 0); - // bleiben rx/ry (fast) gleich, bleibt es ein Kreis (s. `ellipseOrCircle`). - if (g.shape === "circle") { - const dx = pt.x - g.center.x, dy = pt.y - g.center.y; - const rx = index === 0 ? Math.max(1e-3, Math.abs(dx)) : g.r; - const ry = index === 0 ? g.r : Math.max(1e-3, Math.abs(dy)); - return { ...d, geom: ellipseOrCircle(g.center, rx, ry) }; - } - // Bogen: Griff 0/1 (Start-/End-Winkel, s. drawingVertices) ändert a0/a1; - // Griff 2 (Bogenmitte) ändert nur den Radius (Winkel bleiben fest). - if (g.shape === "arc") { - if (index === 2) { - const r = Math.max(1e-3, Math.hypot(pt.x - g.center.x, pt.y - g.center.y)); - return { ...d, geom: { ...g, r } }; - } - const ang = Math.atan2(pt.y - g.center.y, pt.x - g.center.x); - return { ...d, geom: index === 0 ? { ...g, a0: ang } : { ...g, a1: ang } }; - } - // Ellipse: Griff 0 (rx-Achse) bzw. 1 (ry-Achse) — der gezogene Punkt wird - // ins lokale (gedrehte) Achsensystem projiziert, nur die jeweils - // betroffene Halbachse ändert sich. - if (g.shape === "ellipse") { - const c = Math.cos(g.rotation), s = Math.sin(g.rotation); - const dx = pt.x - g.center.x, dy = pt.y - g.center.y; - const lx = dx * c + dy * s; - const ly = -dx * s + dy * c; - const rx = index === 0 ? Math.max(1e-3, Math.abs(lx)) : g.rx; - const ry = index === 0 ? g.ry : Math.max(1e-3, Math.abs(ly)); - // Nur bei rotation 0 kann eine (fast) gleichseitige Ellipse wieder - // zum Kreis kollabieren — eine gedrehte Ellipse mit rx≈ry ist optisch - // bereits ein Kreis, „Drehung" wäre dann aber wieder bedeutungslos. - if (g.rotation === 0) return { ...d, geom: ellipseOrCircle(g.center, rx, ry) }; - return { ...d, geom: { ...g, rx, ry } }; - } - return d; - }); - } - if (wallId) { - return patchItem(project, "walls", wallId, (w) => ({ ...w, ...(index === 0 ? { start: pt } : { end: pt }) })); - } - return []; -} - -/** Verschiebt das selektierte Element (2D-Element ODER Wand) um `delta` (parallel). */ -function moveElementBy( - project: Project, - drawingId: string | null, - wallId: string | null, - delta: Vec2, -): CoreOp[] { - // Objekt-Sperre: s. Kommentar in `moveGrip` oben. - if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return []; - if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return []; - const mv = (p: Vec2): Vec2 => ({ x: p.x + delta.x, y: p.y + delta.y }); - if (drawingId) { - return patchItem(project, "drawings2d", drawingId, (d) => { - const g = d.geom; - switch (g.shape) { - case "line": - return { ...d, geom: { ...g, a: mv(g.a), b: mv(g.b) } }; - case "polyline": - return { ...d, geom: { ...g, pts: g.pts.map(mv) } }; - case "rect": - case "image": - return { ...d, geom: { ...g, min: mv(g.min), max: mv(g.max) } }; - case "circle": - case "arc": - case "ellipse": - return { ...d, geom: { ...g, center: mv(g.center) } }; - case "bezier": - case "spline": - case "dimension": - return { ...d, geom: { ...g, pts: g.pts.map(mv) } }; - case "kote": - return { ...d, geom: { ...g, at: mv(g.at) } }; - case "detailref": - return { ...d, geom: { ...g, at: mv(g.at) } }; - case "scalebar": - return { ...d, geom: { ...g, at: mv(g.at) } }; - case "pointmarker": - return { ...d, geom: { ...g, at: mv(g.at) } }; - case "text": - return { ...d, geom: { ...g, at: mv(g.at) } }; - default: - return d; - } - }); - } - if (wallId) { - return patchItem(project, "walls", wallId, (w) => ({ ...w, start: mv(w.start), end: mv(w.end) })); - } - return []; -} - -/** - * Neue Position eines Eckpunkts, dessen EINE Kante parallel um `delta` - * verschoben wird: der Punkt bleibt NICHT einfach delta-verschoben, sondern - * wandert entlang seiner ANDEREN (unverschobenen) Nachbarkante — deren - * Richtung bleibt exakt erhalten (nur ihre Länge ändert sich), statt sich mit - * zu drehen. Nutzer-Report: bei Vielecken mit mehr als 4/5 Ecken (nicht - * rechtwinklige Anschlüsse) kippten die Nachbarkanten bisher im Winkel, weil - * der Eckpunkt stur um `delta` versetzt wurde (korrekt nur bei rechtwinkligen - * Anschlüssen — Zufall bei Rechtecken, da rect ohnehin nur achsparallele - * Ecken kennt). Berechnet als Schnittpunkt der verschobenen Kanten-Linie mit - * der (unendlich verlängerten) Nachbarkanten-Linie durch den fixen - * Nachbarpunkt — dasselbe Prinzip wie die Wandstoß-Gehrung in `model/ - * joins.ts`. Fällt bei fehlendem Nachbarn (offenes Kettenende) oder (fast) - * paralleler Nachbarkante (kein/instabiler Schnittpunkt) auf die einfache - * Delta-Verschiebung zurück. - */ -function edgeMoveVertex( - vertexOrig: Vec2, - neighborFixed: Vec2 | null, - shiftedLinePoint: Vec2, - edgeDir: Vec2, - delta: Vec2, -): Vec2 { - const fallback: Vec2 = { x: vertexOrig.x + delta.x, y: vertexOrig.y + delta.y }; - if (!neighborFixed) return fallback; - const neighborDir: Vec2 = { - x: vertexOrig.x - neighborFixed.x, - y: vertexOrig.y - neighborFixed.y, - }; - if (Math.hypot(neighborDir.x, neighborDir.y) < 1e-9) return fallback; // entartete Nachbarkante - return lineIntersect(neighborFixed, neighborDir, shiftedLinePoint, edgeDir) ?? fallback; -} - -/** - * Nachbar-Index in einem Vertex-Ring/einer -Kette in Richtung `dir`. `null`, - * wenn `i` am offenen Ende liegt und `closed` falsch ist (kein Nachbar dort) - * ODER der Nachbar auf die andere Kanten-Ecke selbst fiele (entartetes - * 2-Punkt-„Polygon" — kein sinnvoller dritter Bezugspunkt). - */ -function ringNeighbor( - i: number, - n: number, - closed: boolean, - dir: 1 | -1, - excluding: number, -): number | null { - const j = i + dir; - const k = j >= 0 && j < n ? j : closed ? ((j % n) + n) % n : null; - return k !== null && k !== excluding ? k : null; -} - -/** - * Verschiebt die Kante (aIndex,bIndex) eines Vertex-Rings/einer -Kette um - * `delta`, winkeltreu an den beiden Nachbar-Ecken (s. `edgeMoveVertex`). - * `closed`: Ring (Raum/Decke/geschlossene Polylinie) oder offene Kette - * (offene Polylinie). - */ -function movePolygonEdge( - pts: Vec2[], - aIndex: number, - bIndex: number, - delta: Vec2, - closed: boolean, -): Vec2[] { - const n = pts.length; - const A = pts[aIndex]; - const B = pts[bIndex]; - const shiftedA: Vec2 = { x: A.x + delta.x, y: A.y + delta.y }; - const edgeDir: Vec2 = { x: B.x - A.x, y: B.y - A.y }; - const prevOfA = ringNeighbor(aIndex, n, closed, -1, bIndex); - const nextOfB = ringNeighbor(bIndex, n, closed, 1, aIndex); - return pts.map((p, i) => { - if (i === aIndex) { - return edgeMoveVertex(A, prevOfA != null ? pts[prevOfA] : null, shiftedA, edgeDir, delta); - } - if (i === bIndex) { - return edgeMoveVertex(B, nextOfB != null ? pts[nextOfB] : null, shiftedA, edgeDir, delta); - } - return p; - }); -} - -/** - * Verschiebt eine SEITE (Kante) des selektierten Elements: beide Vertices der - * Kante um `delta` (immutabel), winkeltreu an den Nachbarkanten (s. o.). Für - * 2D-Elemente: - * • rect: die zwei betroffenen Ecken (per Index) verschieben und min/max neu - * normalisieren — so wächst/schrumpft das Rechteck an genau dieser Seite - * (immer rechtwinklig, `movePolygonEdge` nicht nötig). - * • polyline: die zwei Vertices `aIndex`/`bIndex` um `delta` verschieben, - * winkeltreu über `movePolygonEdge`. - * • line: beide Endpunkte verschieben (das gesamte Segment senkrecht). - * Für die Wand: start+end gemeinsam (die ganze Wand senkrecht zur Achse). - */ -function moveEdge( - project: Project, - drawingId: string | null, - wallId: string | null, - aIndex: number, - bIndex: number, - delta: Vec2, -): CoreOp[] { - // Objekt-Sperre: s. Kommentar in `moveGrip` oben. - if (drawingId && project.drawings2d.find((d) => d.id === drawingId)?.locked) return []; - if (wallId && project.walls.find((w) => w.id === wallId)?.locked) return []; - const mv = (p: Vec2): Vec2 => ({ x: p.x + delta.x, y: p.y + delta.y }); - if (drawingId) { - return patchItem(project, "drawings2d", drawingId, (d) => { - const g = d.geom; - if (g.shape === "line") { - // Linie hat nur eine Kante [0,1] → das ganze Segment verschieben. - return { ...d, geom: { ...g, a: mv(g.a), b: mv(g.b) } }; - } - if (g.shape === "polyline" || g.shape === "spline") { - const pts = movePolygonEdge(g.pts, aIndex, bIndex, delta, !!g.closed); - return { ...d, geom: { ...g, pts } }; - } - if (g.shape === "rect" || g.shape === "image") { - // Ecken in derselben Reihenfolge wie drawingVertices, die zwei Kanten- - // Ecken verschieben, dann bbox neu bilden (achsparallel halten). - const corners = [ - g.min, - { x: g.max.x, y: g.min.y }, - g.max, - { x: g.min.x, y: g.max.y }, - ]; - const moved = corners.map((c, i) => - i === aIndex || i === bIndex ? mv(c) : c, - ); - let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; - for (const c of moved) { - minX = Math.min(minX, c.x); minY = Math.min(minY, c.y); - maxX = Math.max(maxX, c.x); maxY = Math.max(maxY, c.y); - } - return { ...d, geom: { ...g, min: { x: minX, y: minY }, max: { x: maxX, y: maxY } } }; - } - return d; - }); - } - if (wallId) { - // Wand: beide Enden gemeinsam → ganze Wand senkrecht verschieben. - return patchItem(project, "walls", wallId, (w) => ({ ...w, start: mv(w.start), end: mv(w.end) })); - } - return []; -} diff --git a/src/state/useGripEditing.ts b/src/state/useGripEditing.ts index a646b46f..c21d05c2 100644 --- a/src/state/useGripEditing.ts +++ b/src/state/useGripEditing.ts @@ -9,9 +9,9 @@ import { useRef, useState, type RefObject } from "react"; import { add, dot, leftNormal, normalize, scale, sub, wallCorners } from "../model/geometry"; import type { Ceiling, Drawing2D, EdgeGrip, Project, Room, Stair, Vec2 } from "../model/types"; import { wallTypeThickness } from "../model/types"; -import { drawingVertices } from "./projectSlice"; +import { drawingVertices } from "../core"; import { gripDrawingIdsFor } from "./gripLimits"; -import { openEdges, polylineEdgeGrips, ringEdges } from "./edgeGrips"; +import { openEdges, polylineEdgeGrips, ringEdges } from "../core"; import { areaMovePreview } from "../tools/transform"; import { mvGeom } from "../core"; import { drawingPreviewShapes } from "../tools/drawingPreview"; @@ -372,7 +372,7 @@ export function useGripEditing(opts: { // Ecken wandern mit, die Nachbar-Segmente dehnen sich nach (Parallel- // Verschieben EINER Kante einer komplexen Polylinie, §Task B). const edgeGrips: EdgeGrip[] = (() => { - // ringEdges/openEdges/polylineEdgeGrips: s. edgeGrips.ts. + // ringEdges/openEdges/polylineEdgeGrips: Kern (`geometry/grips.ts`, `grips.rs`). // Decke: geschlossener Ring aus dem Umriss (Auswahl exklusiv, wie bei grips). if (modelEditable && selectedCeiling && effectiveDrawingIds.length === 0 && selectedWallIds.length === 0) { return ringEdges(selectedCeiling.outline, {}); diff --git a/src/state/useMouseSelectionHandlers.ts b/src/state/useMouseSelectionHandlers.ts index 84e09754..280fcacc 100644 --- a/src/state/useMouseSelectionHandlers.ts +++ b/src/state/useMouseSelectionHandlers.ts @@ -256,7 +256,7 @@ export function useMouseSelectionHandlers(opts: { // Kontextmenü-„Entsperren", sobald die Selektion einmal woanders hin // wechselt — Sackgasse). Ein gesperrtes Element bleibt anwähl-/ // inspizierbar; blockiert wird die MODIFIKATION direkt an den - // Mutations-Stellen (`moveGrip`/`moveElementBy` in projectSlice.ts, + // Mutations-Stellen (`moveGrip`/`moveElementBy` im Kern, `grips.rs`, // `deleteSelection` in App.tsx) — dieselbe Semantik wie AutoCADs // Layer-„Lock" (weiterhin wählbar, nicht editierbar). // Shift+Klick: Mehrfach-Auswahl — getroffenes Element zu-/abschalten, den diff --git a/src/text/textFrame.ts b/src/text/textFrame.ts index 5cdc58e3..56122193 100644 --- a/src/text/textFrame.ts +++ b/src/text/textFrame.ts @@ -1,7 +1,7 @@ // Geschätzter Rahmen (Modell-Meter) eines gezeichneten Textes — EINE Quelle // für sowohl die visuelle Anzeige (PlanView.tsx Auswahl-Rahmen/Inline-Editor- -// Anker) als auch die Eckpunkt-Griffe (state/projectSlice.ts drawingVertices/ -// moveGrip). Reines Modul: kein React, kein DOM zwingend nötig +// Anker) als auch die Eckpunkt-Griffe der Textspalte (`geometry/grips.ts` +// drawingVertices). Reines Modul: kein React, kein DOM zwingend nötig // (`contentFontBaselineFromTop` fällt ohne Canvas sicher auf einen // Näherungswert zurück, s. dort) — darf daher auch aus dem Store-Slice // heraus aufgerufen werden. From 365500516fcb678b8dbe0d25f710d250c05b5bff Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 09:56:24 +0000 Subject: [PATCH 2/3] [K4] Objekt-Info im Kern: deriveSelection rechnet selection_info.rs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Die Objekt-Info der Auswahl (effektive Attribute, bbox, Wand/Decke/Dach/Öffnung/Treppe/Raum/ Extrusion/Stütze/Kontext/Detailverweis) ist die Wurzel-Abfrage selectionInfo; state/selectionInfo.ts hält Kontrakt und Fassade (B-Rep-Beschreibung der Extrusion aus TS). geomBBox ist gelöscht, Ausrichten/Verteilen fragt drawingBBoxes. Schneller in Griffen und Objekt-Info: Felder kleiner Objekte linear statt über den Map-Hash, Griff-Anfrage typisiert, Antworten direkt als Text, js_fmt::to_fixed mit Schnellweg. Gleichheit über 174 360 Auswahlen und 24 000 Ausricht-Fälle (einmaliger Test, gelöscht); TODO.md nachgeführt. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- TODO.md | 34 +- src-tauri/core/src/grips.rs | 353 +++++--- src-tauri/core/src/js_fmt.rs | 49 + src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/queries.rs | 13 +- src-tauri/core/src/selection_info.rs | 1242 ++++++++++++++++++++++++++ src-tauri/core/src/web/grips.rs | 2 +- src/core/document.ts | 24 +- src/editors/align.ts | 12 +- src/state/selectionInfo.test.ts | 63 ++ src/state/selectionInfo.ts | 870 ++---------------- 11 files changed, 1705 insertions(+), 958 deletions(-) create mode 100644 src-tauri/core/src/selection_info.rs create mode 100644 src/state/selectionInfo.test.ts diff --git a/TODO.md b/TODO.md index 90c2717c..c166349e 100644 --- a/TODO.md +++ b/TODO.md @@ -491,13 +491,35 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern Leseansicht). Abweichungen (gewollt): ein Griff-Index ohne Punkt (negativ, gebrochen, zu gross) ändert nichts (TS warf beim Lesen von `undefined`, 38 000 der Zufallsfälle); gerechnet wird auf dem Dokument — ein dort als `null` gespeichertes NaN rechnet wie `null` in JS (0) und kommt als `null` in die Leseansicht (vorher blieb dort NaN); Griff-Listen liefern −0 als 0. - Messung (vitest, 3000 Wände + 2000 Polylinien, alt/neu abwechselnd, Median, Container unter Last): Wand-Griff an Position - 10/1500/2990 39–43/198–218/324–348 µs → 40–44/192–193/318–337 µs (dominiert von der linearen id-Suche), Polylinien-Griff - 97–122 → 102–122 µs, Polylinien-Kante 108–138 → 109 µs, Wand verschieben 146–200 → 149–206 µs (gleich im Rahmen der - Streuung), Griff an einer 5000-Punkte-Polylinie 16–18 → 13–14 ms; Griff-Liste der 5000-Punkte-Polylinie 2,7 → 1,1 ms - (kleine Polylinie 2 → 4,5 µs). Nicht in der Tauri-App geprüft (vitest/Linux, e2e im Browser). Offen: `setPolylineVertexType` + Messung (vitest, Store, 3000 Wände + 2000 Polylinien, alt/neu abwechselnd, kleinster Wert aus drei Läufen, Container unter + Last; Stand nach dem Nachtrag unten): Wand-Griff an Position 10/1500/2990 32/150/315 µs → 28/116/262 µs (dominiert von der + linearen id-Suche), Polylinien-Griff 78 → 58 µs, Polylinien-Kante 72 → 57 µs, Wand verschieben 131 → 115 µs, Griff an einer + 5000-Punkte-Polylinie 13,7 → 9,1 ms; Griff-Liste der 5000-Punkte-Polylinie 2,7 → 1,1 ms (kleine Polylinie 2 µs, gleich). + Nicht in der Tauri-App geprüft (vitest/Linux, e2e im Browser). Offen: `setPolylineVertexType` (rechnet in `geometry/polylineVertexType.ts`), die lineare id-Suche je Mausschritt (im Kern beim Rechnen und beim Commit, - in TS in `applyOps`) und der Commit grosser Polylinien (~12 ms bei 5000 Punkten: Verlauf/Prüfung in `document.rs`/`ops.rs`). + in TS in `applyOps`) und der Commit grosser Polylinien (~9 ms bei 5000 Punkten: Verlauf/Prüfung in `document.rs`/`ops.rs`). + **Objekt-Info im Kern (29.10.)** — erledigt damit (4): `selection_info.rs` (vorher `deriveSelection` in `state/selectionInfo.ts`, + ~800 Zeilen Rechnung) liefert als Wurzel-Abfrage `selectionInfo` den Kontrakt `Selection` für das erste gewählte Element + (Vorrang wie bisher): effektive Farbe/Strichstärke/Schraffur/Vorder-/Hintergrund (Element → Linienstil → Ebene → Bauteil), + bbox, Wand (Referenzlinie, Fugen der Schichten, Typ-Liste mit `wallTypeLabel`, Geschosse, Geschoss darüber, UK/OK, Länge, + Brutto-/Öffnungs-/Nettovolumen), Decke (Typ, Fläche, Volumen, Aussparungen), Dach (Firsthöhe aus `roof.rs`, Kantenliste + `roofEdgeList`, Höfe), Öffnung (Lücke `opening_geom`, UK/OK), Treppe (`stair.rs`), Raum, Extrusion, Stütze, Kontext-Objekt + (LV95-Mitte), Detailverweis; `geomBBox` (auch für Ausrichten/Verteilen: Abfrage `drawingBBoxes`, `editors/align.ts`). Rechnung + auf der rohen Wurzel (verlustfrei, Schlüsselreihenfolge wie die früheren Objekt-Literale, keine typisierte Sicht des ganzen + Projekts); nur Dach/Treppe/Stütze werden für die schon typisierte Geometrie einzeln gelesen. Die Antwort wird direkt als Text + geschrieben; Felder kleiner Objekte linear gesucht statt über den SipHash der `IndexMap` (`grips::field`, auch in den Griffen); + die Fassade gibt die Lage des Elements aus der Leseansicht mit (spart dem Kern die lineare Suche). `state/selectionInfo.ts` + hält den Kontrakt (Typen) und die Fassade; die B-Rep-Beschreibung einer Extrusion (`spec`, truck) setzt sie aus + `extrudedSolidSpec`. `js_fmt::to_fixed` hat einen Schnellweg (nur exakte Halbwerte gehen den langen, genauen Weg; Test + gegen den genauen Weg über 1,6 Mio. Werte). Gelöscht: die TS-Rechnung, `geomBBox`. Gleichheit (einmalig, Test gelöscht): + 174 360 Auswahlen über 10 000 Zufallsprojekte (alle Bauteilarten, fehlende/null-Felder, Bindungen UK/OK, unbekannte + Typen/Bauteile, LV95, mehrere Arten gleichzeitig) zeichengleich zur alten Fassung (JSON mit NaN-Marken), 20 489 Fälle mit + derselben Fehlermeldung; Beispielprojekt alle Elemente; 24 000 Ausrichten/Verteilen-Fälle gleich. Abweichung (gewollt): ein + Element, das das Kern-Modell nicht lesen kann (Dach/Treppe/Stütze mit kaputten Pflichtfeldern), ergibt `null` mit Warnung + statt eines Werts. Messung (vitest, Store mit 3000 Wänden und 20 000 Zeichnungen, Container unter Last): Wand 36–67 → + 96–138 µs, Zeichnung (Position 10 000) 150–300 → 160–390 µs, Dach 5 → 30–60 µs (TS merkte sich die Dachgeometrie je + Objekt; im Kern ist sie für die letzten 16 Dächer gemerkt, der Rest ist die JSON-Übergabe), Griff-Schritt samt Objekt-Info + 1,6–2,6 ms → 1,5–2,4 ms; je Darstellung also ~0,05 ms mehr. Nicht in der Tauri-App geprüft. - ◐ **S4 Typen aus Rust**: `types.ts` wird aus den Rust-Strukturen erzeugt (ts-rs); Datei-I/O (`projectFormat`, Migration, IFC/DXF/ STEP-Ex- und -Import) im Kern. **Typen (28.10.):** Das Rust-Modell (`core/src/model/generated.rs`, `manual.rs`) ist die Quelle; ts-rs 12 (MIT, nur diff --git a/src-tauri/core/src/grips.rs b/src-tauri/core/src/grips.rs index 9a7cd790..687bf3c3 100644 --- a/src-tauri/core/src/grips.rs +++ b/src-tauri/core/src/grips.rs @@ -21,6 +21,18 @@ use serde_json::{Map, Value}; // ── JS-Zahlen in JSON ──────────────────────────────────────────────────────── +/// Feld `k` eines Objekts. Kleine Objekte (Punkte, Elemente) werden linear durchsucht: das ist deutlich +/// billiger als der Hash (SipHash) der `IndexMap` je Zugriff — die Griff- und Objekt-Info-Rechnung liest +/// Dutzende Felder je Aufruf. +#[inline] +pub fn field<'a>(v: &'a Value, k: &str) -> Option<&'a Value> { + match v { + Value::Object(m) if m.len() <= 32 => m.iter().find(|(kk, _)| kk.as_str() == k).map(|(_, x)| x), + Value::Object(m) => m.get(k), + _ => None, + } +} + /// Zahl als JSON-Wert wie nach `JSON.stringify` → `serde_json`: ganze Zahlen als Ganzzahl, sonst f64; /// NaN/±∞ als Marke (`"\u{1}NaN"` …), −0 als 0. pub fn js_num(x: f64) -> Value { @@ -90,7 +102,7 @@ pub fn pt(x: f64, y: f64) -> Value { /// `(x, y)` eines Punkt-Werts (fehlende Koordinaten NaN). pub fn xy(v: &Value) -> (f64, f64) { - (num_of(v.get("x")), num_of(v.get("y"))) + (num_of(field(v, "x")), num_of(field(v, "y"))) } /// `{...v, key: val}` (vorhandener Schlüssel behält seine Stelle). Der ersetzte Wert wird nicht kopiert @@ -189,20 +201,103 @@ fn with_geom(d: &Value, g: Value) -> Value { // ── Anfrage ────────────────────────────────────────────────────────────────── -/// Eine Änderung aus den Griff-Aktionen des Stores (JSON, Zahlen mit Nicht-endlich-Marken). -pub struct Request<'a>(&'a Value); +/// Zahl der Anfrage: Zahl oder Nicht-endlich-Marke, `null` = 0 (wie `num_of`), fehlend = NaN. +#[derive(Clone, Copy, Debug)] +pub struct N(pub f64); -impl<'a> Request<'a> { - fn n(&self, k: &str) -> f64 { - num_of(self.0.get(k)) +impl Default for N { + fn default() -> Self { + N(f64::NAN) } - fn s(&self, k: &str) -> Option<&'a str> { - self.0.get(k).and_then(Value::as_str).filter(|s| !s.is_empty()) +} + +impl<'de> serde::Deserialize<'de> for N { + fn deserialize>(d: D) -> Result { + struct V; + impl serde::de::Visitor<'_> for V { + type Value = N; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("Zahl") + } + fn visit_f64(self, v: f64) -> Result { + Ok(N(v)) + } + fn visit_i64(self, v: i64) -> Result { + Ok(N(v as f64)) + } + fn visit_u64(self, v: u64) -> Result { + Ok(N(v as f64)) + } + fn visit_str(self, v: &str) -> Result { + Ok(N(num_of(Some(&Value::String(v.to_owned()))))) + } + fn visit_unit(self) -> Result { + Ok(N(0.0)) + } + fn visit_bool(self, _: bool) -> Result { + Ok(N(f64::NAN)) + } + } + d.deserialize_any(V) + } +} + +/// Eine Änderung aus den Griff-Aktionen des Stores (`GripRequest` in `geometry/grips.ts`); Zahlen dürfen +/// Nicht-endlich-Marken sein. Typisiert gelesen (je Mausschritt billiger als ein JSON-Baum). +#[derive(serde::Deserialize, Default, Debug)] +#[serde(default, rename_all = "camelCase")] +pub struct Request { + pub op: String, + drawing_id: Option, + wall_id: Option, + id: Option, + kind: Option, + new_id: Option, + new_name: Value, + index: N, + a: N, + b: N, + seg: N, + scale: N, + w: N, + h: N, + fx: N, + fy: N, + thickness: N, + pt: [N; 2], + delta: [N; 2], +} + +impl Request { + fn n(&self, k: &str) -> f64 { + match k { + "index" => self.index.0, + "a" => self.a.0, + "b" => self.b.0, + "seg" => self.seg.0, + "scale" => self.scale.0, + "w" => self.w.0, + "h" => self.h.0, + "fx" => self.fx.0, + "fy" => self.fy.0, + _ => self.thickness.0, + } + } + /// Text-Feld; leer = fehlend (JS-Wahrheitswert der ids). + fn s(&self, k: &str) -> Option<&str> { + let v = match k { + "drawingId" => &self.drawing_id, + "wallId" => &self.wall_id, + "kind" => &self.kind, + "newId" => &self.new_id, + _ => &self.id, + }; + v.as_deref().filter(|s| !s.is_empty()) } /// Punkt als `[x, y]`. fn p(&self, k: &str) -> (f64, f64) { - let a = arr(self.0.get(k)); - (num_of(a.first()), num_of(a.get(1))) + let [x, y] = if k == "pt" { self.pt } else { self.delta }; + (x.0, y.0) } } @@ -221,35 +316,37 @@ impl From> for GripResult { /// Antwort-JSON `{"ops": […], "notice": …}` (Ops wie `CoreOp` in TS; `replace` ohne Kopie des Elements). pub fn result_json(r: &GripResult) -> String { - let mut out = String::from("{\"ops\":["); + // Direkt in einen Puffer (`to_writer`; `to_string` ginge über `fmt::Display` und wäre langsamer). + let mut out: Vec = b"{\"ops\":[".to_vec(); for (i, op) in r.ops.iter().enumerate() { if i > 0 { - out.push(','); + out.push(b','); } - match op { + let _ = match op { Op::Replace { collection, entity } => { - out.push_str("{\"kind\":\"replace\",\"collection\":"); - out.push_str(&Value::from(collection.as_str()).to_string()); - out.push_str(",\"entity\":"); - out.push_str(&entity.to_string()); - out.push('}'); + out.extend_from_slice(b"{\"kind\":\"replace\",\"collection\":"); + let _ = serde_json::to_writer(&mut out, collection); + out.extend_from_slice(b",\"entity\":"); + let w = serde_json::to_writer(&mut out, entity); + out.push(b'}'); + w } - op => out.push_str(&op.to_json().to_string()), - } + op => serde_json::to_writer(&mut out, &op.to_json()), + }; } - out.push(']'); + out.push(b']'); if let Some(n) = r.notice { - out.push_str(",\"notice\":"); - out.push_str(&Value::from(n).to_string()); + out.extend_from_slice(b",\"notice\":"); + let _ = serde_json::to_writer(&mut out, n); } - out.push('}'); - out + out.push(b'}'); + String::from_utf8(out).unwrap_or_default() } /// Führt eine Griff-Änderung aus (`req.op` wählt die Art, s. `src/state/gripOps.ts`). -pub fn run(root: &Map, req: &Value) -> Result { - let r = Request(req); - let op = req.get("op").and_then(Value::as_str).unwrap_or(""); +pub fn run(root: &Map, req: &Request) -> Result { + let r = req; + let op = req.op.as_str(); let patch = |coll: &str, id: Option<&str>, f: &dyn Fn(&Value) -> Option| -> Vec { id.and_then(|id| find(root, coll, id)).and_then(f).map(|e| vec![replace(coll, e)]).unwrap_or_default() }; @@ -260,7 +357,7 @@ pub fn run(root: &Map, req: &Value) -> Result let d = did.and_then(|i| find(root, "drawings2d", i)); let w = wid.and_then(|i| find(root, "walls", i)); // Objekt-Sperre: gesperrte Elemente lassen sich anwählen, aber nicht ziehen. - if d.is_some_and(|d| truthy(d.get("locked"))) || w.is_some_and(|w| truthy(w.get("locked"))) { + if d.is_some_and(|d| truthy(field(d, "locked"))) || w.is_some_and(|w| truthy(field(w, "locked"))) { return Ok(GripResult::default()); } let f: Box Option> = match op { @@ -284,11 +381,11 @@ pub fn run(root: &Map, req: &Value) -> Result "resize" => { let (w, h, fx, fy) = (r.n("w"), r.n("h"), r.n("fx"), r.n("fy")); if r.s("kind") == Some("drawing2d") { - patch("drawings2d", r.s("id"), &|d| resize_geom(d.get("geom")?, w, h, fx, fy).map(|g| with_geom(d, g))).into() + patch("drawings2d", r.s("id"), &|d| resize_geom(field(d, "geom")?, w, h, fx, fy).map(|g| with_geom(d, g))).into() } else { patch("walls", r.s("id"), &|wall| { - let s = xy(wall.get("start").unwrap_or(&Value::Null)); - let e = xy(wall.get("end").unwrap_or(&Value::Null)); + let s = xy(field(wall, "start").unwrap_or(&Value::Null)); + let e = xy(field(wall, "end").unwrap_or(&Value::Null)); let (ax, ay, sx, sy) = scale_around(bbox(&[s, e]), w, h, fx, fy); let f = |p: (f64, f64)| pt(ax + (p.0 - ax) * sx, ay + (p.1 - ay) * sy); Some(with_all(wall, vec![("start", f(s)), ("end", f(e))])) @@ -304,7 +401,7 @@ pub fn run(root: &Map, req: &Value) -> Result "ceilingBy" | "roofBy" => { let coll = if op == "ceilingBy" { "ceilings" } else { "roofs" }; let (dx, dy) = r.p("delta"); - patch(coll, r.s("id"), &|e| Some(with(e, "outline", moved_all(e.get("outline")?.as_array()?, dx, dy)))).into() + patch(coll, r.s("id"), &|e| Some(with(e, "outline", moved_all(field(e, "outline")?.as_array()?, dx, dy)))).into() } "ceilingEdge" | "roomEdge" => { let (coll, field) = if op == "ceilingEdge" { ("ceilings", "outline") } else { ("rooms", "boundary") }; @@ -318,8 +415,8 @@ pub fn run(root: &Map, req: &Value) -> Result "stairBy" => { let (dx, dy) = r.p("delta"); patch("stairs", r.s("id"), &|s| { - let mut out = with(s, "start", moved(s.get("start").unwrap_or(&Value::Null), dx, dy)); - if truthy(s.get("center")) { + let mut out = with(s, "start", moved(field(s, "start").unwrap_or(&Value::Null), dx, dy)); + if truthy(field(s, "center")) { out = with(&out, "center", moved(&s["center"], dx, dy)); } Some(out) @@ -329,8 +426,8 @@ pub fn run(root: &Map, req: &Value) -> Result "roomBy" => { let (dx, dy) = r.p("delta"); patch("rooms", r.s("id"), &|rm| { - let mut out = with(rm, "boundary", moved_all(rm.get("boundary")?.as_array()?, dx, dy)); - if truthy(rm.get("stampAnchor")) { + let mut out = with(rm, "boundary", moved_all(field(rm, "boundary")?.as_array()?, dx, dy)); + if truthy(field(rm, "stampAnchor")) { out = with(&out, "stampAnchor", moved(&rm["stampAnchor"], dx, dy)); } Some(out) @@ -340,10 +437,10 @@ pub fn run(root: &Map, req: &Value) -> Result "roomStamp" => { let (dx, dy) = r.p("delta"); patch("rooms", r.s("id"), &|rm| { - let base = match rm.get("stampAnchor") { + let base = match field(rm, "stampAnchor") { Some(a) if !a.is_null() => xy(a), _ => { - let ring: Vec<[f64; 2]> = arr(rm.get("boundary")).iter().map(|p| xy(p).into()).collect(); + let ring: Vec<[f64; 2]> = arr(field(rm, "boundary")).iter().map(|p| xy(p).into()).collect(); let c = crate::room_area::evaluate(&ring, 0.0).centroid; (c[0], c[1]) } @@ -359,12 +456,12 @@ pub fn run(root: &Map, req: &Value) -> Result "deletePoint" => { let index = r.n("index"); let Some(d) = r.s("id").and_then(|i| find(root, "drawings2d", i)) else { return Ok(GripResult::default()) }; - let g = d.get("geom").unwrap_or(&Value::Null); - if g.get("shape").and_then(Value::as_str) != Some("polyline") { + let g = field(d, "geom").unwrap_or(&Value::Null); + if field(g, "shape").and_then(Value::as_str) != Some("polyline") { return Ok(GripResult::default()); } - let pts = arr(g.get("pts")); - let min = if truthy(g.get("closed")) { 4 } else { 3 }; + let pts = arr(field(g, "pts")); + let min = if truthy(field(g, "closed")) { 4 } else { 3 }; if pts.len() < min { return Ok(GripResult { ops: vec![], notice: Some("alert.polylineMinPoints") }); } @@ -373,13 +470,13 @@ pub fn run(root: &Map, req: &Value) -> Result // seinen (die genaue Bogenform lässt sich ohne den Stützpunkt nicht erhalten). let drop = |l: &[Value]| Value::Array(l.iter().enumerate().filter(|(i, _)| *i != k).map(|(_, v)| v.clone()).collect()); let mut fields = vec![("pts", drop(pts))]; - if truthy(g.get("bulge")) { - fields.push(("bulge", drop(arr(g.get("bulge"))))); + if truthy(field(g, "bulge")) { + fields.push(("bulge", drop(arr(field(g, "bulge"))))); } vec![replace("drawings2d", with_geom(d, with_all(g, fields)))].into() } - "wallThickness" => wall_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.get("newName").cloned().unwrap_or(Value::Null)).into(), - "ceilingThickness" => ceiling_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.get("newName").cloned().unwrap_or(Value::Null)).into(), + "wallThickness" => wall_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.new_name.clone()).into(), + "ceilingThickness" => ceiling_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.new_name.clone()).into(), other => return Err(format!("Unbekannte Griff-Änderung: {other}")), }) } @@ -391,15 +488,15 @@ fn wall_grip(w: &Value, index: f64, x: f64, y: f64) -> Value { } fn wall_moved(w: &Value, dx: f64, dy: f64) -> Value { - let s = moved(w.get("start").unwrap_or(&Value::Null), dx, dy); - let e = moved(w.get("end").unwrap_or(&Value::Null), dx, dy); + let s = moved(field(w, "start").unwrap_or(&Value::Null), dx, dy); + let e = moved(field(w, "end").unwrap_or(&Value::Null), dx, dy); with_all(w, vec![("start", s), ("end", e)]) } // ── 2D-Zeichnungen ─────────────────────────────────────────────────────────── fn shape(g: &Value) -> &str { - g.get("shape").and_then(Value::as_str).unwrap_or("") + field(g, "shape").and_then(Value::as_str).unwrap_or("") } /// Kreis, solange rx≈ry (relative Toleranz 0.5 %) — sonst Ellipse (rotation 0). Neues Objekt (weitere @@ -456,18 +553,18 @@ fn dim_text_pos(a: (f64, f64), b: (f64, f64), offset: f64, h: f64, along: f64, p /// Schrifthöhe der Masszahl in Modell-Metern. fn dim_height(g: &Value, scale: f64) -> f64 { - mm_to_model(num_or(g.get("textHeightMm"), DIM_TEXT_HEIGHT_MM), scale) + mm_to_model(num_or(field(g, "textHeightMm"), DIM_TEXT_HEIGHT_MM), scale) } /// Griff `index` einer 2D-Zeichnung auf (x, y) (`moveGrip`); `None` = keine Änderung. fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option { - let g = d.get("geom")?; + let g = field(d, "geom")?; let p = pt(x, y); let set = |k: &str, v: Value| Some(with_geom(d, with(g, k, v))); match shape(g) { "line" | "xline" | "ray" => set(if index == 0.0 { "a" } else { "b" }, p), "polyline" => { - let pts = arr(g.get("pts")); + let pts = arr(field(g, "pts")); let n = pts.len(); if index < n as f64 { return set("pts", replace_at(pts, index, &p)); @@ -478,16 +575,16 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option = arr(g.get("bulge")).to_vec(); + let mut bulge: Vec = arr(field(g, "bulge")).to_vec(); while bulge.len() <= k { bulge.push(Value::from(0u64)); } bulge[k] = js_num(val); set("bulge", Value::Array(bulge)) } - "bezier" | "spline" => set("pts", replace_at(arr(g.get("pts")), index, &p)), + "bezier" | "spline" => set("pts", replace_at(arr(field(g, "pts")), index, &p)), "dimension" => { - let pts = arr(g.get("pts")); + let pts = arr(field(g, "pts")); let n = pts.len(); if index < n as f64 { return set("pts", replace_at(pts, index, &p)); @@ -507,7 +604,7 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option Option = (0..n - 1) .map(|i| { if i == k { @@ -541,11 +638,11 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option { - if truthy(g.get("pathPts")) { - return set("pathPts", replace_at(arr(g.get("pathPts")), index, &p)); + if truthy(field(g, "pathPts")) { + return set("pathPts", replace_at(arr(field(g, "pathPts")), index, &p)); } - if truthy(g.get("leaderTarget")) { - let bends = arr(g.get("leaderBendPoints")); + if truthy(field(g, "leaderTarget")) { + let bends = arr(field(g, "leaderBendPoints")); let tip = bends.len() as f64 + 1.0; if index == 0.0 { return set("at", p); @@ -559,12 +656,12 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option 0.0 && index >= 0.0 && index < 4.0 { + let width = num_of(field(g, "width")); + if truthy(field(g, "width")) && width > 0.0 && index >= 0.0 && index < 4.0 { // Nur die Spaltenbreite ändert sich (InDesign-Textrahmen); Zug auf die lokale x-Achse. - let angle = num_of(g.get("angle")); + let angle = num_of(field(g, "angle")); let (cos, sin) = (jsnum::cos(angle), jsnum::sin(angle)); - let (ax, ay) = xy(g.get("at").unwrap_or(&Value::Null)); + let (ax, ay) = xy(field(g, "at").unwrap_or(&Value::Null)); let local_x = (x - ax) * cos + (y - ay) * sin; const MIN_WIDTH: f64 = 0.1; if index == 0.0 || index == 3.0 { @@ -578,30 +675,30 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option set("at", p), "circle" => { - let (cx, cy) = xy(g.get("center").unwrap_or(&Value::Null)); - let r = pass(g.get("r")); + let (cx, cy) = xy(field(g, "center").unwrap_or(&Value::Null)); + let r = pass(field(g, "r")); let (rx, ry) = if index == 0.0 { (calc(jsnum::max(1e-3, (x - cx).abs())), r) } else { (r, calc(jsnum::max(1e-3, (y - cy).abs()))) }; - Some(with_geom(d, ellipse_or_circle(g.get("center"), rx, ry))) + Some(with_geom(d, ellipse_or_circle(field(g, "center"), rx, ry))) } "arc" => { - let (cx, cy) = xy(g.get("center").unwrap_or(&Value::Null)); + let (cx, cy) = xy(field(g, "center").unwrap_or(&Value::Null)); if index == 2.0 { return set("r", js_num(jsnum::max(1e-3, hypot2(x - cx, y - cy)))); } set(if index == 0.0 { "a0" } else { "a1" }, js_num(jsnum::atan2(y - cy, x - cx))) } "ellipse" => { - let rot = num_of(g.get("rotation")); + let rot = num_of(field(g, "rotation")); let (c, s) = (jsnum::cos(rot), jsnum::sin(rot)); - let (cx, cy) = xy(g.get("center").unwrap_or(&Value::Null)); + let (cx, cy) = xy(field(g, "center").unwrap_or(&Value::Null)); let (dx, dy) = (x - cx, y - cy); let lx = dx * c + dy * s; let ly = -dx * s + dy * c; - let rx = if index == 0.0 { calc(jsnum::max(1e-3, lx.abs())) } else { pass(g.get("rx")) }; - let ry = if index == 0.0 { pass(g.get("ry")) } else { calc(jsnum::max(1e-3, ly.abs())) }; + let rx = if index == 0.0 { calc(jsnum::max(1e-3, lx.abs())) } else { pass(field(g, "rx")) }; + let ry = if index == 0.0 { pass(field(g, "ry")) } else { calc(jsnum::max(1e-3, ly.abs())) }; // Nur ungedreht (`rotation === 0`) kann eine (fast) gleichseitige Ellipse wieder zum Kreis werden. - if g.get("rotation").and_then(Value::as_f64) == Some(0.0) { - return Some(with_geom(d, ellipse_or_circle(g.get("center"), rx, ry))); + if field(g, "rotation").and_then(Value::as_f64) == Some(0.0) { + return Some(with_geom(d, ellipse_or_circle(field(g, "center"), rx, ry))); } Some(with_geom(d, with_opt(g, vec![("rx", rx.v), ("ry", ry.v)]))) } @@ -620,18 +717,18 @@ fn or1(l: f64) -> f64 { /// Ecken eines Rechtecks/Bilds in Griff-Reihenfolge: min, (max.x, min.y), max, (min.x, max.y). fn rect_corners(g: &Value) -> [(f64, f64); 4] { - let mn = xy(g.get("min").unwrap_or(&Value::Null)); - let mx = xy(g.get("max").unwrap_or(&Value::Null)); + let mn = xy(field(g, "min").unwrap_or(&Value::Null)); + let mx = xy(field(g, "max").unwrap_or(&Value::Null)); [mn, (mx.0, mn.1), mx, (mn.0, mx.1)] } /// Ganze 2D-Zeichnung verschieben (`moveElementBy`); `None` = Form ohne Verschiebung. fn drawing_moved(d: &Value, dx: f64, dy: f64) -> Option { - let g = d.get("geom")?; + let g = field(d, "geom")?; let mv = |k: &str| moved(g.get(k).unwrap_or(&Value::Null), dx, dy); let ng = match shape(g) { "line" => with_all(g, vec![("a", mv("a")), ("b", mv("b"))]), - "polyline" | "bezier" | "spline" | "dimension" => with(g, "pts", moved_all(arr(g.get("pts")), dx, dy)), + "polyline" | "bezier" | "spline" | "dimension" => with(g, "pts", moved_all(arr(field(g, "pts")), dx, dy)), "rect" | "image" => with_all(g, vec![("min", mv("min")), ("max", mv("max"))]), "circle" | "arc" | "ellipse" => with(g, "center", mv("center")), "kote" | "detailref" | "scalebar" | "pointmarker" | "text" => with(g, "at", mv("at")), @@ -642,10 +739,10 @@ fn drawing_moved(d: &Value, dx: f64, dy: f64) -> Option { /// Kante (a, b) einer 2D-Zeichnung verschieben (`moveEdge`); `None` = keine Änderung. fn drawing_edge(d: &Value, a: f64, b: f64, dx: f64, dy: f64) -> Option { - let g = d.get("geom")?; + let g = field(d, "geom")?; let ng = match shape(g) { - "line" => with_all(g, vec![("a", moved(g.get("a").unwrap_or(&Value::Null), dx, dy)), ("b", moved(g.get("b").unwrap_or(&Value::Null), dx, dy))]), - "polyline" | "spline" => with(g, "pts", move_polygon_edge(arr(g.get("pts")), a, b, dx, dy, truthy(g.get("closed")))?), + "line" => with_all(g, vec![("a", moved(field(g, "a").unwrap_or(&Value::Null), dx, dy)), ("b", moved(field(g, "b").unwrap_or(&Value::Null), dx, dy))]), + "polyline" | "spline" => with(g, "pts", move_polygon_edge(arr(field(g, "pts")), a, b, dx, dy, truthy(field(g, "closed")))?), "rect" | "image" => { // Die zwei Kanten-Ecken verschieben, dann die bbox neu bilden (achsparallel). let corners = rect_corners(g); @@ -786,18 +883,18 @@ fn resize_geom(g: &Value, w: f64, h: f64, fx: f64, fy: f64) -> Option { "circle" | "arc" => { // bbox eines Kreises ist 2r × 2r; Radius = grössere Zielhälfte, Mitte nicht-uniform um den Anker. let c = p("center"); - let r = num_of(g.get("r")); + let r = num_of(field(g, "r")); let ax = (c.0 - r) + fx * (2.0 * r); let ay = (c.1 - r) + fy * (2.0 * r); let half = jsnum::max(w, h) / 2.0; - let nr = if half > 0.0 { Some(js_num(half)) } else { g.get("r").cloned() }; + let nr = if half > 0.0 { Some(js_num(half)) } else { field(g, "r").cloned() }; let sx = if r > 1e-9 { (w / 2.0) / r } else { 1.0 }; let sy = if r > 1e-9 { (h / 2.0) / r } else { 1.0 }; with_opt(g, vec![("center", Some(pt(ax + (c.0 - ax) * sx, ay + (c.1 - ay) * sy))), ("r", nr)]) } "ellipse" => { let c = p("center"); - let (rx, ry) = (num_of(g.get("rx")), num_of(g.get("ry"))); + let (rx, ry) = (num_of(field(g, "rx")), num_of(field(g, "ry"))); let (ax, ay, sx, sy) = scale_around((c.0 - rx, c.1 - ry, c.0 + rx, c.1 + ry), w, h, fx, fy); with_all(g, vec![("center", pt(ax + (c.0 - ax) * sx, ay + (c.1 - ay) * sy)), ("rx", js_num(jsnum::max(1e-3, rx * sx))), ("ry", js_num(jsnum::max(1e-3, ry * sy)))]) } @@ -815,7 +912,7 @@ fn resize_geom(g: &Value, w: f64, h: f64, fx: f64, fy: f64) -> Option { /// Dach-Eckgriff: die gegenüberliegende Ecke bleibt fix, der Umriss bleibt ein achsparalleles Rechteck. fn roof_grip(r: &Value, index: f64, x: f64, y: f64) -> Option { - let outline = r.get("outline")?.as_array()?; + let outline = field(r, "outline")?.as_array()?; let n = outline.len(); if n < 4 { return None; @@ -831,20 +928,20 @@ fn roof_grip(r: &Value, index: f64, x: f64, y: f64) -> Option { /// Winkel-Mitte geteilt (wie `kernel2d` Bogen-Segmente zuschneidet); eine Näherung über tessellierte /// Punkte wäre zu ungenau. Die Bulge-Liste wird nur mitgeführt, wenn es eine gab. fn insert_point(d: &Value, seg: f64, x: f64, y: f64) -> Option { - let g = d.get("geom")?; + let g = field(d, "geom")?; if shape(g) != "polyline" { return None; } - let pts = arr(g.get("pts")); + let pts = arr(field(g, "pts")); let n = pts.len(); let k = index_in(seg, n)?; let last = k == n - 1; - if last && !truthy(g.get("closed")) { + if last && !truthy(field(g, "closed")) { return None; } let a = xy(&pts[k]); let b = xy(if last { &pts[0] } else { &pts[k + 1] }); - let bulge = num_or(arr(g.get("bulge")).get(k), 0.0); + let bulge = num_or(arr(field(g, "bulge")).get(k), 0.0); // `bulgeArc` der Fassade: gerade (|bulge| < 1e-9 oder NaN) ohne Bogen. let arc = if bulge.abs() >= 1e-9 { crate::bulge::arc(a.0, a.1, b.0, b.1, bulge) } else { vec![] }; let (insert, b1, b2) = if arc.len() >= 6 { @@ -863,8 +960,8 @@ fn insert_point(d: &Value, seg: f64, x: f64, y: f64) -> Option { np.push(insert); np.extend_from_slice(&pts[k + 1..]); let mut fields = vec![("pts", Value::Array(np))]; - if truthy(g.get("bulge")) { - let old = arr(g.get("bulge")); + if truthy(field(g, "bulge")) { + let old = arr(field(g, "bulge")); let mut nb: Vec = old.iter().take(k).cloned().collect(); nb.push(js_num(b1)); nb.push(js_num(b2)); @@ -899,17 +996,17 @@ fn wall_thickness(root: &Map, wall_id: &str, thickness: f64, new_ return vec![]; } let Some(wall) = find(root, "walls", wall_id) else { return vec![] }; - let wt_id = wall.get("wallTypeId"); - let Some(wt) = arr(root.get("wallTypes")).iter().find(|t| t.get("id") == wt_id) else { return vec![] }; - let layers = arr(wt.get("layers")); + let wt_id = field(wall, "wallTypeId"); + let Some(wt) = arr(root.get("wallTypes")).iter().find(|t| field(t, "id") == wt_id) else { return vec![] }; + let layers = arr(field(wt, "layers")); if layers.is_empty() { return vec![]; } - let wt_idv = wt.get("id"); - let used_by_others = arr(root.get("walls")).iter().any(|w| id_of(w) != Some(wall_id) && w.get("wallTypeId") == wt_idv); + let wt_idv = field(wt, "id"); + let used_by_others = arr(root.get("walls")).iter().any(|w| id_of(w) != Some(wall_id) && field(w, "wallTypeId") == wt_idv); if layers.len() == 1 && !used_by_others { let tid = id_of(wt).unwrap_or(""); - return find(root, "wallTypes", tid).map(|t| vec![replace("wallTypes", with(t, "layers", single_layer(arr(t.get("layers")), thickness)))]).unwrap_or_default(); + return find(root, "wallTypes", tid).map(|t| vec![replace("wallTypes", with(t, "layers", single_layer(arr(field(t, "layers")), thickness)))]).unwrap_or_default(); } vec![add("wallTypes", new_type(new_id, new_name, layers, thickness)), replace("walls", with(wall, "wallTypeId", new_id.into()))] } @@ -922,20 +1019,20 @@ fn ceiling_thickness(root: &Map, ceiling_id: &str, thickness: f64 } let Some(c) = find(root, "ceilings", ceiling_id) else { return vec![] }; let active = |c: &Value| -> Option { - let v = c.get("ceilingTypeId"); - if nullish(v) { c.get("wallTypeId").cloned() } else { v.cloned() } + let v = field(c, "ceilingTypeId"); + if nullish(v) { field(c, "wallTypeId").cloned() } else { v.cloned() } }; let active_id = active(c); - let by_id = |coll: &str, id: Option<&Value>| arr(root.get(coll)).iter().find(|t| t.get("id") == id).cloned(); - let Some(ct) = by_id("ceilingTypes", c.get("ceilingTypeId")).or_else(|| by_id("wallTypes", c.get("wallTypeId"))) else { return vec![] }; - let layers = arr(ct.get("layers")); + let by_id = |coll: &str, id: Option<&Value>| arr(root.get(coll)).iter().find(|t| field(t, "id") == id).cloned(); + let Some(ct) = by_id("ceilingTypes", field(c, "ceilingTypeId")).or_else(|| by_id("wallTypes", field(c, "wallTypeId"))) else { return vec![] }; + let layers = arr(field(&ct, "layers")); if layers.is_empty() { return vec![]; } let used_by_others = arr(root.get("ceilings")).iter().any(|o| id_of(o) != Some(ceiling_id) && active(o) == active_id); - if layers.len() == 1 && !used_by_others && truthy(c.get("ceilingTypeId")) { + if layers.len() == 1 && !used_by_others && truthy(field(c, "ceilingTypeId")) { let tid = id_of(&ct).unwrap_or(""); - return find(root, "ceilingTypes", tid).map(|t| vec![replace("ceilingTypes", with(t, "layers", single_layer(arr(t.get("layers")), thickness)))]).unwrap_or_default(); + return find(root, "ceilingTypes", tid).map(|t| vec![replace("ceilingTypes", with(t, "layers", single_layer(arr(field(t, "layers")), thickness)))]).unwrap_or_default(); } let mut nc = with(c, "ceilingTypeId", new_id.into()); if let Value::Object(m) = &mut nc { @@ -957,25 +1054,25 @@ pub fn drawing_vertices(g: &Value, scale: f64) -> Option> { Some(match shape(g) { "line" | "xline" | "ray" => vec![p("a"), p("b")], "polyline" => { - let bulge = arr(g.get("bulge")); - polyline_vertices(pts("pts"), truthy(g.get("closed")), |i| num_or(bulge.get(i), 0.0)) + let bulge = arr(field(g, "bulge")); + polyline_vertices(pts("pts"), truthy(field(g, "closed")), |i| num_or(bulge.get(i), 0.0)) } "rect" | "image" => rect_corners(g).to_vec(), "circle" => { - let (c, r) = (p("center"), num_of(g.get("r"))); + let (c, r) = (p("center"), num_of(field(g, "r"))); vec![(c.0 + r, c.1), (c.0, c.1 + r)] } "arc" => { - let (c, r) = (p("center"), num_of(g.get("r"))); - let (a0, a1) = (num_of(g.get("a0")), num_of(g.get("a1"))); + let (c, r) = (p("center"), num_of(field(g, "r"))); + let (a0, a1) = (num_of(field(g, "a0")), num_of(field(g, "a1"))); let mid = (a0 + a1) / 2.0; [a0, a1, mid].iter().map(|a| (c.0 + r * jsnum::cos(*a), c.1 + r * jsnum::sin(*a))).collect() } "ellipse" => { - let rot = num_of(g.get("rotation")); + let rot = num_of(field(g, "rotation")); let (c, s) = (jsnum::cos(rot), jsnum::sin(rot)); let ctr = p("center"); - let (rx, ry) = (num_of(g.get("rx")), num_of(g.get("ry"))); + let (rx, ry) = (num_of(field(g, "rx")), num_of(field(g, "ry"))); vec![(ctr.0 + rx * c, ctr.1 + rx * s), (ctr.0 - ry * s, ctr.1 + ry * c)] } "bezier" | "spline" => pts("pts"), @@ -986,14 +1083,14 @@ pub fn drawing_vertices(g: &Value, scale: f64) -> Option> { let (a, b) = (out.first().copied().unwrap_or(nan), out.last().copied().unwrap_or(nan)); let (dx, dy) = (b.0 - a.0, b.1 - a.1); let len = or1(hypot2(dx, dy)); - let offset = num_of(g.get("offset")); + let offset = num_of(field(g, "offset")); let (nx, ny) = ((-dy / len) * offset, (dx / len) * offset); out.push(((a.0 + b.0) / 2.0 + nx, (a.1 + b.1) / 2.0 + ny)); let h = dim_height(g, scale); - let offs = arr(g.get("textOffsetsMm")); + let offs = arr(field(g, "textOffsetsMm")); for i in 0..n.saturating_sub(1) { let (along, perp) = match offs.get(i) { - Some(o) if truthy(Some(o)) => (mm_to_model(num_of(o.get("along")), scale), mm_to_model(num_of(o.get("perp")), scale)), + Some(o) if truthy(Some(o)) => (mm_to_model(num_of(field(o, "along")), scale), mm_to_model(num_of(field(o, "perp")), scale)), _ => (0.0, 0.0), }; out.push(dim_text_pos(out[i], out[i + 1], offset, h, along, perp)); @@ -1002,14 +1099,14 @@ pub fn drawing_vertices(g: &Value, scale: f64) -> Option> { } "kote" | "detailref" | "scalebar" | "pointmarker" | "block" => vec![p("at")], "text" => { - if truthy(g.get("pathPts")) { + if truthy(field(g, "pathPts")) { pts("pathPts") - } else if truthy(g.get("leaderTarget")) { + } else if truthy(field(g, "leaderTarget")) { let mut out = vec![p("at")]; out.extend(pts("leaderBendPoints")); out.push(p("leaderTarget")); out - } else if truthy(g.get("width")) && num_of(g.get("width")) > 0.0 { + } else if truthy(field(g, "width")) && num_of(field(g, "width")) > 0.0 { return None; } else { vec![p("at")] @@ -1080,6 +1177,10 @@ mod tests { v.as_object().unwrap().clone() } + fn rq(v: Value) -> Request { + serde_json::from_value(v).unwrap() + } + fn entity(r: &GripResult) -> &Value { match &r.ops[0] { Op::Replace { entity, .. } => entity, @@ -1103,18 +1204,18 @@ mod tests { #[test] fn wand_griff_und_sperre() { let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}, "extra": 1}]})); - let res = run(&r, &json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]})).unwrap(); + let res = run(&r, &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]}))).unwrap(); assert_eq!(entity(&res).to_string(), r#"{"id":"w","start":{"x":0,"y":0},"end":{"x":2,"y":3},"extra":1}"#); let locked = root(json!({"walls": [{"id": "w", "locked": true, "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}}]})); - assert!(run(&locked, &json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]})).unwrap().ops.is_empty()); + assert!(run(&locked, &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]}))).unwrap().ops.is_empty()); // Fehlendes Element: keine Op. - assert!(run(&r, &json!({"op": "moveGrip", "wallId": "x", "index": 1, "pt": [2, 3]})).unwrap().ops.is_empty()); + assert!(run(&r, &rq(json!({"op": "moveGrip", "wallId": "x", "index": 1, "pt": [2, 3]}))).unwrap().ops.is_empty()); } #[test] fn kreis_wird_ellipse() { let r = root(json!({"drawings2d": [{"id": "d", "geom": {"shape": "circle", "center": {"x": 0, "y": 0}, "r": 1}}]})); - let res = run(&r, &json!({"op": "moveGrip", "drawingId": "d", "index": 0, "pt": [2, 0]})).unwrap(); + let res = run(&r, &rq(json!({"op": "moveGrip", "drawingId": "d", "index": 0, "pt": [2, 0]}))).unwrap(); assert_eq!(entity(&res)["geom"].to_string(), r#"{"shape":"ellipse","center":{"x":0,"y":0},"rx":2,"ry":1,"rotation":0}"#); } @@ -1130,14 +1231,14 @@ mod tests { #[test] fn nan_als_marke() { let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}}]})); - let res = run(&r, &json!({"op": "moveBy", "wallId": "w", "delta": ["\u{1}NaN", 0]})).unwrap(); + let res = run(&r, &rq(json!({"op": "moveBy", "wallId": "w", "delta": ["\u{1}NaN", 0]}))).unwrap(); assert_eq!(entity(&res)["start"]["x"], json!("\u{1}NaN")); } #[test] fn punkt_loeschen_mindestzahl() { let r = root(json!({"drawings2d": [{"id": "d", "geom": {"shape": "polyline", "closed": false, "pts": [{"x": 0, "y": 0}, {"x": 1, "y": 0}]}}]})); - let res = run(&r, &json!({"op": "deletePoint", "id": "d", "index": 0})).unwrap(); + let res = run(&r, &rq(json!({"op": "deletePoint", "id": "d", "index": 0}))).unwrap(); assert_eq!(res.notice, Some("alert.polylineMinPoints")); assert!(res.ops.is_empty()); } @@ -1148,7 +1249,7 @@ mod tests { "wallTypes": [{"id": "wt", "name": "W", "layers": [{"componentId": "c", "thickness": 0.2}]}], "ceilings": [{"id": "c1", "wallTypeId": "wt", "thickness": 0.3}, {"id": "c2", "wallTypeId": "wt"}], })); - let ops = run(&r, &json!({"op": "ceilingThickness", "id": "c1", "thickness": 0.25, "newId": "ct-1", "newName": "Decke"})).unwrap().ops; + let ops = run(&r, &rq(json!({"op": "ceilingThickness", "id": "c1", "thickness": 0.25, "newId": "ct-1", "newName": "Decke"}))).unwrap().ops; assert_eq!(crate::ops::ops_to_json(&ops), r#"[{"kind":"add","collection":"ceilingTypes","items":[{"id":"ct-1","name":"Decke","layers":[{"componentId":"c","thickness":0.25}]}]},{"kind":"replace","collection":"ceilings","entity":{"id":"c1","wallTypeId":"wt","ceilingTypeId":"ct-1"}}]"#); } diff --git a/src-tauri/core/src/js_fmt.rs b/src-tauri/core/src/js_fmt.rs index 26ab7eff..4a5eae8d 100644 --- a/src-tauri/core/src/js_fmt.rs +++ b/src-tauri/core/src/js_fmt.rs @@ -15,6 +15,30 @@ pub fn to_fixed(x: f64, d: usize) -> String { if ax >= 1e21 { return format!("{}{}", if neg { "-" } else { "" }, ax); } + // Schnellweg: Rust rundet `{:.N}` korrekt (zum geraden Nachbarn nur bei exakten Halbwerten); ohne + // exakten Halbwert ist das Ergebnis dasselbe wie in JS, nur ohne die teure lange Formatierung. + if !exact_half(ax, d) { + let s = format!("{:.*}", d, ax); + return if neg { format!("-{s}") } else { s }; + } + to_fixed_wide(ax, d, neg) +} + +/// Ob `ax` (endlich, ≥ 0) bei `d` Nachkommastellen genau auf der Mitte zwischen zwei Ergebnissen liegt: +/// `ax · 10^d · 2` ist eine ungerade ganze Zahl, d. h. das niedrigste gesetzte Bit von `ax` ist 2^-(d+1). +fn exact_half(ax: f64, d: usize) -> bool { + if ax == 0.0 { + return false; + } + let bits = ax.to_bits(); + let exp = ((bits >> 52) & 0x7ff) as i64; + let frac = bits & ((1u64 << 52) - 1); + let (m, e) = if exp == 0 { (frac, -1074) } else { (frac | (1u64 << 52), exp - 1075) }; + e + m.trailing_zeros() as i64 + d as i64 + 1 == 0 +} + +/// Langsamer, exakter Weg (für exakte Halbwerte): Ziffern mit 25 Stellen Reserve, dann aufrunden. +fn to_fixed_wide(ax: f64, d: usize, neg: bool) -> String { // 25 Stellen mehr als nötig: ein exakter Halbwert zeigt sich als '5' gefolgt von Nullen. let wide = format!("{:.*}", d + 25, ax); let (int_part, frac) = wide.split_once('.').expect("Nachkommastellen"); @@ -119,5 +143,30 @@ mod tests { assert_eq!(to_fixed(123.456, 2), "123.46"); assert_eq!(to_fixed(2.675, 2), "2.67"); // 2.675 ist binär 2.67499999… — JS: "2.67" assert_eq!(to_fixed(1e-9, 6), "0.000000"); + assert_eq!(to_fixed(0.25, 1), "0.3"); + assert_eq!(to_fixed(-0.25, 1), "-0.3"); + assert_eq!(to_fixed(-0.0, 2), "0.00"); + } + + #[test] + fn schnellweg_gleich_dem_genauen_weg() { + let mut x: u64 = 0x2545_f491_4f6c_dd1d; + for i in 0..200_000 { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + let v = match i % 4 { + 0 => (x % 1_000_000) as f64 / 1000.0, + 1 => f64::from_bits(x) % 1e6, + 2 => (x % 4096) as f64 / 64.0, + _ => (x as f64 / u64::MAX as f64 - 0.5) * 100.0, + }; + if !v.is_finite() { + continue; + } + for d in 0..8 { + assert_eq!(to_fixed(v, d), to_fixed_wide(v.abs(), d, v < 0.0), "{v} {d}"); + } + } } } diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 4b6d1529..1241c361 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -82,6 +82,7 @@ pub mod geo_translate; pub mod selection_filter; pub mod reorder; pub mod grips; +pub mod selection_info; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs index 5c7d6ee4..d956ec1f 100644 --- a/src-tauri/core/src/queries.rs +++ b/src-tauri/core/src/queries.rs @@ -100,9 +100,20 @@ pub fn run_root(root: &serde_json::Map, name: &str, t } // Griff-Änderungen ([K4] S3, `grips.rs`): `text` = JSON der Anfrage; Antwort `{ops, notice}` (ohne Commit). "gripOps" => { - let req: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("gripOps: {e}"))?; + let req: crate::grips::Request = serde_json::from_str(text).map_err(|e| format!("gripOps: {e}"))?; Ok(crate::grips::result_json(&crate::grips::run(root, &req)?)) } + // Objekt-Info der Auswahl ([K4] S3, `selection_info.rs`): `text` = JSON der gewählten ids je Art; Antwort + // `Selection` (TS) oder null, Zahlen mit Nicht-endlich-Marken. + "selectionInfo" => { + let a: crate::selection_info::SelArgs = serde_json::from_str(text).map_err(|e| format!("selectionInfo: {e}"))?; + crate::selection_info::derive(root, &a).map(crate::selection_info::J::into_string) + } + // Bounding-Boxen von Zeichnungen (Ausrichten/Verteilen): `text` = JSON der ids. + "drawingBBoxes" => { + let ids: Vec = serde_json::from_str(text).map_err(|e| format!("drawingBBoxes: {e}"))?; + Ok(crate::selection_info::drawing_bboxes(root, &ids).into_string()) + } _ => Err(format!("Unbekannte Wurzel-Abfrage: {name}")), } } diff --git a/src-tauri/core/src/selection_info.rs b/src-tauri/core/src/selection_info.rs new file mode 100644 index 00000000..170e07ae --- /dev/null +++ b/src-tauri/core/src/selection_info.rs @@ -0,0 +1,1242 @@ +//! Objekt-Info der Auswahl ([K4] S3, vorher `deriveSelection` in `src/state/selectionInfo.ts`): die +//! anzeigefertigen, effektiv aufgelösten Attribute des ERSTEN gewählten Elements für die Paletten +//! (Attribute, Objekt-Info) — Farbe/Strichstärke/Schraffur nach derselben Kette wie der Plan, Masse, +//! Flächen, Volumen, UK/OK, die Listen der Dropdowns (Wand-/Deckentypen, Geschosse, Layouts) und je +//! Bauteilart die eigenen Felder. Ausgabe: JSON in der Form `Selection` (TS), Schlüssel in der +//! Reihenfolge der früheren Objekt-Literale, fehlende (`undefined`) Felder weggelassen. +//! +//! Rechnung auf der rohen Projekt-Wurzel (verlustfrei, keine typisierte Sicht des ganzen Projekts — +//! nach einem Mausschritt an einer grossen Liste wäre deren Neueinlesen teurer als die Abfrage). Nur das +//! gewählte Dach, die Treppe und die Stütze werden typisiert gelesen, wo die Geometrie schon typisiert im +//! Kern steht (`roof.rs`, `stair.rs`, `model3d::column_footprint`). Zahlen wie in JS: `null` rechnet wie +//! 0 (`grips::num_of`), nicht endliche Ergebnisse reisen als Marken (`grips::js_num`). +//! +//! Wo TS warf (unbekannter Wandtyp, Deckentyp oder Bauteil), kommt dieselbe Meldung als Fehler. +//! Der B-Rep-Körper einer Extrusion (`spec`) bleibt in TS (truck-Pipeline, `plan/extrudedSolidSpec.ts`). + +use crate::grips::{field, js_num, num_of, truthy, xy}; +use crate::jsmath::hypot2; +use crate::jsnum; +use crate::ops::id_of; +use serde_json::{Map, Value}; + +const WALL_FALLBACK_MM: f64 = 0.18; +const DRAW_FALLBACK_COLOR: &str = "#d0d0d0"; +const WALL_FALLBACK_COLOR: &str = "#2b3039"; +const EXTRUSION_COLOR: &str = "#d98c40"; +const COLUMN_COLOR: &str = "#3a3f47"; + +/// Gewählte ids je Art (wie die Parameter von `deriveSelection`). +#[derive(serde::Deserialize, Default)] +#[serde(default, rename_all = "camelCase")] +pub struct SelArgs { + pub wall_ids: Vec, + pub drawing_id: Option, + pub ceiling_id: Option, + pub opening_id: Option, + pub stair_id: Option, + pub room_id: Option, + pub extruded_solid_id: Option, + pub column_id: Option, + pub roof_id: Option, + pub context_object_id: Option, + /// Lage der Elemente in ihren Listen (Liste → Index), von der Leseansicht; der Kern prüft die id an + /// dieser Stelle und sucht sonst linear (die Suche über grosse Listen kostet je Element). + pub at: std::collections::HashMap, +} + +// ── Hilfen ─────────────────────────────────────────────────────────────────── + +/// JSON-Text eines Werts. Die Antwort wird direkt als Text geschrieben (kein `Value`-Baum mit je +/// Schlüssel einer Zuteilung), durchgereichte Felder werden nur gelesen, nicht kopiert. +pub struct J(Vec); + +impl J { + fn null() -> J { + J(b"null".to_vec()) + } + fn arr(items: impl IntoIterator) -> J { + let mut out = vec![b'[']; + for (i, it) in items.into_iter().enumerate() { + if i > 0 { + out.push(b','); + } + out.extend(it.0); + } + out.push(b']'); + J(out) + } + pub fn into_string(self) -> String { + String::from_utf8(self.0).unwrap_or_default() + } +} + +/// Etwas, das sich als JSON schreiben lässt (Wert, Text-Stück). +trait Emit { + fn emit(&self, out: &mut Vec); +} +impl Emit for Value { + fn emit(&self, out: &mut Vec) { + let _ = serde_json::to_writer(out, self); + } +} +impl Emit for J { + fn emit(&self, out: &mut Vec) { + out.extend_from_slice(&self.0); + } +} +impl Emit for &T { + fn emit(&self, out: &mut Vec) { + (*self).emit(out) + } +} + +/// Objekt in Schlüssel-Reihenfolge; `undefined` (None/fehlend) entfällt. +struct O(Vec); + +impl Default for O { + fn default() -> Self { + O(vec![b'{']) + } +} + +impl O { + fn key(&mut self, k: &str) { + if self.0.len() > 1 { + self.0.push(b','); + } + self.0.push(b'"'); + self.0.extend_from_slice(k.as_bytes()); + self.0.extend_from_slice(b"\":"); + } + fn v(mut self, k: &str, v: impl Emit) -> Self { + self.key(k); + v.emit(&mut self.0); + self + } + fn o(self, k: &str, v: Option) -> Self { + match v { + Some(v) => self.v(k, v), + None => self, + } + } + fn n(self, k: &str, x: f64) -> Self { + self.v(k, js_num(x)) + } + fn s(self, k: &str, s: &str) -> Self { + self.v(k, Value::from(s)) + } + /// Feld `key` von `src` unverändert durchreichen (fehlend = `undefined`). + fn raw(self, k: &str, src: &Value, key: &str) -> Self { + self.o(k, field(src, key)) + } + fn done(mut self) -> J { + self.0.push(b'}'); + J(self.0) + } +} + +fn arr(v: Option<&Value>) -> &[Value] { + v.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]) +} + +/// Erstes Element mit `id` in einer Liste der Wurzel (`hint`: vermutete Lage, wird geprüft). +fn find<'a>(root: &'a Map, list: &str, id: &str, hint: Option) -> Option<&'a Value> { + let l = arr(root.get(list)); + if let Some(e) = hint.filter(|h| h.fract() == 0.0 && *h >= 0.0).and_then(|h| l.get(h as usize)) { + if id_of(e) == Some(id) { + return Some(e); + } + } + l.iter().find(|e| id_of(e) == Some(id)) +} + +/// Erstes Element, dessen Feld `key` gleich `val` ist (`===`; fehlend gleich fehlend). +fn find_by<'a>(list: &'a [Value], key: &str, val: Option<&Value>) -> Option<&'a Value> { + list.iter().find(|e| field(e, key) == val) +} + +/// `a ?? b`: Wert, ausser fehlend/`null`. +fn nn(v: Option<&Value>) -> Option<&Value> { + v.filter(|x| !x.is_null()) +} + +fn str_of(v: Option<&Value>) -> Option<&str> { + v.and_then(Value::as_str) +} + +/// `String(v)` für die Anzeige (Name eines Geschosses). +fn js_string(v: &Value) -> Value { + match v { + Value::String(_) => v.clone(), + Value::Number(n) => Value::from(crate::js_fmt::js_number(n.as_f64().unwrap_or(f64::NAN))), + Value::Null => Value::from("null"), + Value::Bool(b) => Value::from(if *b { "true" } else { "false" }), + _ => Value::from("[object Object]"), + } +} + +/// Kategorie (Ebene) per Code: erster Treffer der Tiefensuche (`findCategory`). +fn category<'a>(root: &'a Map, code: Option<&Value>) -> Option<&'a Value> { + fn walk<'a>(list: &'a [Value], code: Option<&Value>) -> Option<&'a Value> { + for c in list { + if field(c, "code") == code { + return Some(c); + } + if let Some(hit) = walk(arr(field(c, "children")), code) { + return Some(hit); + } + } + None + } + walk(arr(root.get("layers")), code) +} + +/// `getComponent`: Bauteil per id oder Fehler (Meldung wie TS). +fn component<'a>(root: &'a Map, id: Option<&Value>) -> Result<&'a Value, String> { + find_by(arr(root.get("components")), "id", id).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {}", id.map_or("undefined".into(), |v| js_text(v)))) +} + +/// Wert in einer Template-Zeichenkette (`${v}`). +fn js_text(v: &Value) -> String { + match js_string(v) { + Value::String(s) => s, + _ => String::new(), + } +} + +/// `x.color ?? cat?.color ?? fallback`. +fn color_of(el: &Value, cat: Option<&Value>, fallback: &str) -> Value { + nn(field(el, "color")).or_else(|| cat.and_then(|c| nn(field(c, "color")))).cloned().unwrap_or_else(|| fallback.into()) +} + +/// Strichstärke `x ?? cat?.lw ?? fallback` (nur die Kategorie-Kette). +fn lw_or(over: Option<&Value>, cat: Option<&Value>, fallback: f64) -> Value { + nn(over).or_else(|| cat.and_then(|c| nn(field(c, "lw")))).cloned().unwrap_or_else(|| js_num(fallback)) +} + +fn is_layer(src: Option<&Value>) -> bool { + str_of(src) == Some("layer") +} + +/// `resolveForeground`/`resolveBackground`: Override ?? (Quelle „layer" ⇒ Kategorie-Farbe) ?? Bauteil-Feld. +fn resolve_color(comp_field: Option<&Value>, over: Option<&Value>, cat: Option<&Value>, source: Option<&Value>) -> Option { + if let Some(o) = nn(over) { + return Some(o.clone()); + } + if is_layer(source) { + if let Some(c) = cat { + return nn(field(c, "color")).cloned().or_else(|| comp_field.cloned()); + } + } + comp_field.cloned() +} + +/// `resolveHatchId`: Override ?? (Quelle „layer" ⇒ Kategorie-Schraffur) ?? Rückfall. +fn resolve_hatch(over: Option<&Value>, source: Option<&Value>, cat: Option<&Value>, fallback: Option<&Value>) -> Option { + if let Some(o) = nn(over) { + return Some(o.clone()); + } + if is_layer(source) { + return cat.and_then(|c| nn(field(c, "hatch"))).or(fallback).cloned(); + } + fallback.cloned() +} + +/// Bauteil-Feld (`comp.foreground` …) als Rückfall, unverändert (auch `null`). +fn cf<'a>(comp: Option<&'a Value>, key: &str) -> Option<&'a Value> { + comp.and_then(|c| c.get(key)) +} + +/// Achsparallele bbox mit `Math.min/max`; nicht endlich → Null-Box. +fn bbox_of(pts: impl IntoIterator) -> [f64; 4] { + let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for (x, y) in pts { + x0 = jsnum::min(x0, x); + y0 = jsnum::min(y0, y); + x1 = jsnum::max(x1, x); + y1 = jsnum::max(y1, y); + } + if !x0.is_finite() { + return [0.0; 4]; + } + [x0, y0, x1, y1] +} + +fn bbox_value(b: [f64; 4]) -> J { + O::default().n("minX", b[0]).n("minY", b[1]).n("maxX", b[2]).n("maxY", b[3]).done() +} + +fn pts_of(v: Option<&Value>) -> Vec<(f64, f64)> { + arr(v).iter().map(xy).collect() +} + +fn ring(v: Option<&Value>) -> Vec<[f64; 2]> { + arr(v).iter().map(|p| xy(p).into()).collect() +} + +/// Polygonfläche (immer positiv, `polygonArea` = Raum-Bewertung im Kern). +fn polygon_area(v: Option<&Value>) -> f64 { + crate::room_area::evaluate(&ring(v), 0.0).gross +} + +/// Deckenfläche `|signedArea|` (kernel2d). +fn ceiling_area(v: Option<&Value>) -> f64 { + let p: Vec = pts_of(v).into_iter().map(|(x, y)| kernel2d::Vec2::new(x, y)).collect(); + kernel2d::signed_area(&p).abs() +} + +/// Summe der Schichtdicken (`wallTypeThickness`, `reduce` ab 0). +fn type_thickness(t: &Value) -> f64 { + arr(field(t, "layers")).iter().fold(0.0, |s, l| s + num_of(field(l, "thickness"))) +} + +/// Geschosse (`kind === "floor"`) als `{id, name}`. +fn floors(root: &Map) -> J { + J::arr( + arr(root.get("drawingLevels")) + .iter() + .filter(|z| str_of(field(z, "kind")) == Some("floor")) + .map(|z| O::default().raw("id", z, "id").raw("name", z, "name").done()), + ) +} + +fn level<'a>(root: &'a Map, id: Option<&Value>) -> Option<&'a Value> { + find_by(arr(root.get("drawingLevels")), "id", id) +} + +/// `floor?.name ?? fallback`. +fn floor_name(floor: Option<&Value>, fallback: Option<&Value>) -> Option { + floor.and_then(|f| nn(field(f, "name"))).or(fallback).cloned() +} + +/// UK/OK-Bindung (`resolveAnchor`): absolutes Z oder `None` (Rückfall des Aufrufers). +fn anchor(root: &Map, a: Option<&Value>) -> Option { + let a = a.filter(|a| truthy(Some(a)))?; + if str_of(field(a, "mode")) == Some("custom") { + // `return anchor.z` — fehlend/null fällt beim `??` des Aufrufers zurück. + return nn(field(a, "z")).map(|z| num_of(Some(z))); + } + let f = level(root, field(a, "floorId"))?; + Some(num_or(field(f, "baseElevation"), 0.0) + num_or(field(a, "offset"), 0.0)) +} + +fn num_or(v: Option<&Value>, d: f64) -> f64 { + if nn(v).is_some() { + num_of(v) + } else { + d + } +} + +/// (UK, OK) einer Wand oder Stütze: UK aus `bottom` sonst Geschoss-Basis, OK aus `top` sonst UK + Höhe. +fn vertical_extent(root: &Map, el: &Value) -> (f64, f64) { + let floor_base = level(root, field(el, "floorId")).map_or(0.0, |f| num_or(field(f, "baseElevation"), 0.0)); + let zb = anchor(root, field(el, "bottom")).unwrap_or(floor_base); + let zt = anchor(root, field(el, "top")).unwrap_or(zb + num_of(field(el, "height"))); + (zb, zt) +} + +/// Aufbau-Typ einer Decke (`getCeilingType`): eigener Deckentyp, sonst Alt-Wandtyp, sonst Fehler. +fn ceiling_type<'a>(root: &'a Map, c: &Value) -> Result<&'a Value, String> { + if truthy(field(c, "ceilingTypeId")) { + if let Some(t) = find_by(arr(root.get("ceilingTypes")), "id", field(c, "ceilingTypeId")) { + return Ok(t); + } + } + find_by(arr(root.get("wallTypes")), "id", field(c, "wallTypeId")) + .ok_or_else(|| format!("Unbekannter Deckentyp: {}", nn(field(c, "ceilingTypeId")).or(field(c, "wallTypeId")).map_or("undefined".into(), js_text))) +} + +/// Deckendicke (`ceilingThickness`): `thickness` > 0, sonst Typ-Dicke, sonst 0.2. +fn ceiling_thickness(root: &Map, c: &Value) -> f64 { + if nn(field(c, "thickness")).is_some() && num_of(field(c, "thickness")) > 0.0 { + return num_of(field(c, "thickness")); + } + ceiling_type(root, c).map_or(0.2, type_thickness) +} + +/// `wallTypeLabel`: Kürzel + Dicke in cm (einschichtig „BET 24", mehrschichtig „GKB·BET (25.5)"), sonst der Name. +fn wall_type_label(root: &Map, t: &Value) -> Value { + let comps = arr(root.get("components")); + let total_cm: f64 = crate::js_fmt::to_fixed(type_thickness(t) * 100.0, 1).parse().unwrap_or(f64::NAN); + let cm = if total_cm % 1.0 == 0.0 { jsnum::to_int32(total_cm).to_string() } else { crate::js_fmt::js_number(total_cm) }; + let layers = arr(field(t, "layers")); + let abbrevs: Vec = layers + .iter() + .map(|l| find_by(comps, "id", field(l, "componentId")).and_then(|c| nn(field(c, "abbrev"))).map_or(String::new(), js_text)) + .collect(); + if abbrevs.iter().all(|a| !a.is_empty()) { + if layers.len() == 1 { + return Value::from(format!("{} {cm}", abbrevs[0])); + } + return Value::from(format!("{} ({cm})", abbrevs.join("·"))); + } + field(t, "name").cloned().unwrap_or(Value::Null) +} + +/// Einträge der Typ-Auswahl (`WallTypeChoice`). +fn type_choices(root: &Map, list: &str) -> J { + J::arr( + arr(root.get(list)) + .iter() + .map(|t| { + O::default() + .raw("id", t, "id") + .raw("name", t, "name") + .v("label", wall_type_label(root, t)) + .n("thickness", type_thickness(t)) + .v("layerCount", Value::from(arr(field(t, "layers")).len())) + .done() + }), + ) +} + +/// Effektive Vordergrund-/Hintergrund-/Schraffur-Vorschau eines Bauteils (äusserste Schicht bzw. das +/// zugewiesene Bauteil als Repräsentant). +fn effective(el: &Value, comp: Option<&Value>, cat: Option<&Value>) -> (Option, Option, Option) { + let fg = if comp.is_some() { resolve_color(cf(comp, "foreground"), field(el, "foreground"), cat, field(el, "foregroundSource")) } else { field(el, "foreground").cloned() }; + let bg = if comp.is_some() { resolve_color(cf(comp, "background"), field(el, "background"), cat, field(el, "backgroundSource")) } else { field(el, "background").cloned() }; + let hatch = resolve_hatch(field(el, "hatchId"), field(el, "hatchSource"), cat, cf(comp, "hatchId")); + (fg, bg, hatch) +} + +// ── Abfrage ────────────────────────────────────────────────────────────────── + +/// Objekt-Info des ersten gewählten Elements (Vorrang wie `deriveSelection`); `Value::Null` = nichts. +pub fn derive(root: &Map, a: &SelArgs) -> Result { + fn id(o: &Option) -> Option<&str> { + o.as_deref().filter(|s| !s.is_empty()) + } + if let Some(i) = id(&a.context_object_id) { + if let Some(o) = find(root, "context", i, a.at.get("context").copied()) { + return Ok(context_selection(root, o)); + } + } + if let Some(i) = id(&a.drawing_id) { + return Ok(find(root, "drawings2d", i, a.at.get("drawings2d").copied()).map_or(J::null(), |d| drawing_selection(root, d))); + } + if let Some(i) = id(&a.extruded_solid_id) { + return Ok(find(root, "extrudedSolids", i, a.at.get("extrudedSolids").copied()).map_or(J::null(), |s| solid_selection(root, s))); + } + if let Some(i) = id(&a.column_id) { + return find(root, "columns", i, a.at.get("columns").copied()).map_or(Ok(J::null()), |c| column_selection(root, c)); + } + if let Some(i) = id(&a.opening_id) { + if let Some(o) = find(root, "openings", i, a.at.get("openings").copied()) { + return opening_selection(root, o); + } + } + if let Some(i) = a.wall_ids.first().filter(|s| !s.is_empty()) { + return find(root, "walls", i, a.at.get("walls").copied()).map_or(Ok(J::null()), |w| wall_selection(root, w)); + } + if let Some(i) = id(&a.ceiling_id) { + return find(root, "ceilings", i, a.at.get("ceilings").copied()).map_or(Ok(J::null()), |c| ceiling_selection(root, c)); + } + if let Some(i) = id(&a.roof_id) { + return find(root, "roofs", i, a.at.get("roofs").copied()).map_or(Ok(J::null()), |r| roof_selection(root, r)); + } + if let Some(i) = id(&a.stair_id) { + return find(root, "stairs", i, a.at.get("stairs").copied()).map_or(Ok(J::null()), |s| stair_selection(root, s)); + } + if let Some(i) = id(&a.room_id) { + return Ok(find(root, "rooms", i, a.at.get("rooms").copied()).map_or(J::null(), |r| room_selection(root, r))); + } + Ok(J::null()) +} + +fn wall_selection(root: &Map, w: &Value) -> Result { + let cat = category(root, field(w, "categoryCode")); + let color = color_of(w, cat, WALL_FALLBACK_COLOR); + let weight = lw_or(field(w, "strokeWeight"), cat, WALL_FALLBACK_MM); + let (s, e) = (xy(field(w, "start").unwrap_or(&Value::Null)), xy(field(w, "end").unwrap_or(&Value::Null))); + let bb = [jsnum::min(s.0, e.0), jsnum::min(s.1, e.1), jsnum::max(s.0, e.0), jsnum::max(s.1, e.1)]; + let wt = find_by(arr(root.get("wallTypes")), "id", field(w, "wallTypeId")) + .ok_or_else(|| format!("Unbekannter Wandtyp: {}", field(w, "wallTypeId").map_or("undefined".into(), js_text)))?; + let thickness = type_thickness(wt); + let layers = arr(field(wt, "layers")); + let outer = component(root, layers.first().and_then(|l| field(l, "componentId")))?; + let (fg, bg, hatch) = effective(w, Some(outer), cat); + let floor = level(root, field(w, "floorId")); + let (zb, zt) = vertical_extent(root, w); + let above = next_floor_above(root, field(w, "floorId")); + let length = hypot2(e.0 - s.0, e.1 - s.1); + let height = jsnum::max(0.0, zt - zb); + let gross = length * thickness * height; + let opening_volume = arr(root.get("openings")) + .iter() + .filter(|o| field(o, "hostWallId") == field(w, "id")) + .fold(0.0, |sum, o| sum + num_of(field(o, "width")) * num_of(field(o, "height")) * thickness); + let net = jsnum::max(0.0, gross - opening_volume); + // Interne Schichttrennlinien als wählbare Referenz: Achsversatz +n = halbe Dicke − Fugenlage. + let half = thickness / 2.0; + let mut cum = 0.0; + let mut boundaries = Vec::new(); + let abbrev = |l: &Value| -> Result { + let c = component(root, field(l, "componentId"))?; + Ok(nn(field(c, "abbrev")).or_else(|| field(c, "name")).map_or("undefined".into(), js_text)) + }; + for i in 0..layers.len().saturating_sub(1) { + cum += num_of(field(&layers[i], "thickness")); + let label = format!("{}|{}", abbrev(&layers[i])?, abbrev(&layers[i + 1])?); + boundaries.push(O::default().n("offset", half - cum).s("label", &label).done()); + } + let info = O::default() + .v("referenceLine", nn(field(w, "referenceLine")).cloned().unwrap_or_else(|| "center".into())) + .raw("referenceOffset", w, "referenceOffset") + .v("layerBoundaries", J::arr(boundaries)) + .v("sliceTermination", nn(field(w, "sliceTermination")).cloned().unwrap_or_else(|| "both".into())) + .raw("wallTypeId", w, "wallTypeId") + .n("thickness", thickness) + .v("singleLayer", Value::Bool(layers.len() <= 1)) + .v("wallTypes", type_choices(root, "wallTypes")) + .raw("floorId", w, "floorId") + .o("floorName", floor_name(floor, field(w, "floorId"))) + .v("floors", floors(root)) + .o("floorAbove", above) + .raw("bottom", w, "bottom") + .raw("top", w, "top") + .n("zBottom", zb) + .n("zTop", zt) + .n("length", length) + .n("grossVolume", gross) + .n("openingVolume", opening_volume) + .n("netVolume", net) + .done(); + Ok(O::default() + .s("kind", "wall") + .raw("id", w, "id") + .raw("categoryCode", w, "categoryCode") + .raw("floorId", w, "floorId") + .v("color", color) + .raw("colorPenId", w, "colorPenId") + .v("weightMm", weight) + .raw("fillHatchId", w, "hatchId") + .raw("foreground", w, "foreground") + .raw("foregroundPenId", w, "foregroundPenId") + .raw("background", w, "background") + .raw("backgroundPenId", w, "backgroundPenId") + .raw("foregroundSource", w, "foregroundSource") + .raw("backgroundSource", w, "backgroundSource") + .o("effectiveForeground", fg) + .o("effectiveBackground", bg) + .o("effectiveHatchId", hatch) + .raw("strokeWeightOverride", w, "strokeWeight") + .raw("strokeWeightSource", w, "strokeWeightSource") + .raw("hatchSource", w, "hatchSource") + .v("bbox", bbox_value(bb)) + .v("wall", info) + .done()) +} + +/// Geschoss direkt über `floor_id` (Reihenfolge der „floor"-Ebenen), `{id, name}`. +fn next_floor_above(root: &Map, floor_id: Option<&Value>) -> Option { + let fl: Vec<&Value> = arr(root.get("drawingLevels")).iter().filter(|z| str_of(field(z, "kind")) == Some("floor")).collect(); + let idx = fl.iter().position(|z| field(z, "id") == floor_id)?; + fl.get(idx + 1).map(|a| O::default().raw("id", a, "id").raw("name", a, "name").done()) +} + +fn ceiling_selection(root: &Map, c: &Value) -> Result { + let cat = category(root, field(c, "categoryCode")); + let color = color_of(c, cat, WALL_FALLBACK_COLOR); + let weight = lw_or(field(c, "strokeWeight"), cat, WALL_FALLBACK_MM); + let bb = bbox_of(pts_of(field(c, "outline"))); + let wt = ceiling_type(root, c)?; + let thickness = ceiling_thickness(root, c); + let outer = component(root, arr(field(wt, "layers")).first().and_then(|l| field(l, "componentId")))?; + let (fg, bg, hatch) = effective(c, Some(outer), cat); + let floor = level(root, field(c, "floorId")); + let floor_top = floor.map_or(0.0, |f| num_or(field(f, "baseElevation"), 0.0) + num_or(field(f, "floorHeight"), 0.0)); + let zt = anchor(root, field(c, "top")).unwrap_or(floor_top); + let zb = anchor(root, field(c, "bottom")).unwrap_or(zt - thickness); + let area = ceiling_area(field(c, "outline")); + let openings: Vec = arr(field(c, "openings")) + .iter() + .map(|hole| { + let b = bbox_of(pts_of(Some(hole))); + O::default().n("width", b[2] - b[0]).n("depth", b[3] - b[1]).done() + }) + .collect(); + let info = O::default() + .o("typeId", nn(field(c, "ceilingTypeId")).or(field(c, "wallTypeId")).cloned()) + .n("thickness", thickness) + .v("singleLayer", Value::Bool(arr(field(wt, "layers")).len() <= 1)) + .n("area", area) + .n("volume", area * thickness) + .v("ceilingTypes", type_choices(root, "ceilingTypes")) + .raw("floorId", c, "floorId") + .o("floorName", floor_name(floor, field(c, "floorId"))) + .v("floors", floors(root)) + .raw("top", c, "top") + .raw("bottom", c, "bottom") + .n("zBottom", zb) + .n("zTop", zt) + .v("openings", J::arr(openings)) + .done(); + Ok(O::default() + .s("kind", "ceiling") + .raw("id", c, "id") + .raw("categoryCode", c, "categoryCode") + .raw("floorId", c, "floorId") + .v("color", color) + .raw("colorPenId", c, "colorPenId") + .v("weightMm", weight) + .raw("fillHatchId", c, "hatchId") + .raw("foreground", c, "foreground") + .raw("foregroundPenId", c, "foregroundPenId") + .raw("background", c, "background") + .raw("backgroundPenId", c, "backgroundPenId") + .raw("foregroundSource", c, "foregroundSource") + .raw("backgroundSource", c, "backgroundSource") + .o("effectiveForeground", fg) + .o("effectiveBackground", bg) + .o("effectiveHatchId", hatch) + .raw("strokeWeightOverride", c, "strokeWeight") + .raw("strokeWeightSource", c, "strokeWeightSource") + .raw("hatchSource", c, "hatchSource") + .v("closed", Value::Bool(true)) + .v("bbox", bbox_value(bb)) + .v("ceiling", info) + .done()) +} + +fn roof_selection(root: &Map, r: &Value) -> Result { + let cat = category(root, field(r, "categoryCode")); + let color = color_of(r, cat, WALL_FALLBACK_COLOR); + let weight = lw_or(None, cat, WALL_FALLBACK_MM); + // `roofBBox`: Vergleiche ohne Math.min (NaN wird übergangen), leer = ±∞. + let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for (x, y) in pts_of(field(r, "outline")) { + if x < x0 { + x0 = x; + } + if y < y0 { + y0 = y; + } + if x > x1 { + x1 = x; + } + if y > y1 { + y1 = y; + } + } + // `roof.baseElevation !== undefined` (auch `null` gilt als gesetzt, rechnet wie 0 und bleibt in der Ausgabe null). + let (eaves, eaves_out) = match field(r, "baseElevation") { + Some(b) => (num_of(Some(b)), b.clone()), + None => { + let z = level(root, field(r, "floorId")).map_or(0.0, |f| num_or(field(f, "baseElevation"), 0.0) + num_or(field(f, "floorHeight"), 0.0)); + (z, js_num(z)) + } + }; + let ridge_height = roof_ridge_height(r, eaves)?; + let (w, d) = ((x1 - x0).abs(), (y1 - y0).abs()); + let holes: Vec = arr(field(r, "holes")) + .iter() + .map(|h| O::default().n("area", polygon_area(Some(h)).abs()).v("points", Value::from(arr(Some(h)).len())).done()) + .collect(); + let info = O::default() + .raw("shape", r, "shape") + .raw("pitchDeg", r, "pitchDeg") + .raw("pitchUpperDeg", r, "pitchUpperDeg") + .raw("roofTypeId", r, "roofTypeId") + .raw("mansardType", r, "mansardType") + .raw("mansardKneeRatio", r, "mansardKneeRatio") + .raw("halfHipRatio", r, "halfHipRatio") + .raw("overhang", r, "overhang") + .raw("overhangGable", r, "overhangGable") + .raw("ridgeAxis", r, "ridgeAxis") + .raw("thickness", r, "thickness") + .v("baseElevation", eaves_out) + .n("ridgeHeight", ridge_height) + .n("footprintArea", w * d) + .n("width", w) + .n("depth", d) + .n("minX", x0) + .n("minY", y0) + .v("edges", roof_edges(r)) + .v("holes", J::arr(holes)) + .v("hasEdgePitch", Value::Bool(field(r, "edgePitchDeg").is_some())) + .done(); + Ok(O::default() + .s("kind", "roof") + .raw("id", r, "id") + .raw("categoryCode", r, "categoryCode") + .raw("floorId", r, "floorId") + .v("color", color) + .raw("colorPenId", r, "colorPenId") + .v("weightMm", weight) + .v("closed", Value::Bool(true)) + .v("bbox", bbox_value([x0, y0, x1, y1])) + .v("roof", info) + .done()) +} + +thread_local! { + /// Zuletzt gerechnete Firsthöhen (Dach, Traufhöhe, Firsthöhe): die Objekt-Info fragt je Darstellung + /// neu, das Skelett eines Dachs kostet aber ein Vielfaches der übrigen Abfrage (TS merkte sich die + /// Geometrie je Dach-Objekt). + static RIDGE_CACHE: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Firsthöhe über der Traufe (Dach-Geometrie des Kerns, `roof.rs`), gemerkt für die letzten Dächer. +fn roof_ridge_height(r: &Value, eaves: f64) -> Result { + let hit = RIDGE_CACHE.with(|c| c.borrow().iter().find(|(v, z, _)| z.to_bits() == eaves.to_bits() && v == r).map(|e| e.2)); + if let Some(h) = hit { + return Ok(h); + } + let typed: crate::model::Roof = serde_json::from_value(r.clone()).map_err(|e| format!("Dach passt nicht zum Kern-Modell: {e}"))?; + let h = crate::roof::roof_geometry(&typed.params(), eaves).ridge_height; + RIDGE_CACHE.with(|c| { + let mut c = c.borrow_mut(); + if c.len() >= 16 { + c.remove(0); + } + c.push((r.clone(), eaves, h)); + }); + Ok(h) +} + +/// Kantenliste eines Dachs (`roofEdgeList`): Umriss, dann Höfe; Vorgabe je Kante aus `edgePitchDeg`. +fn roof_edges(r: &Value) -> J { + let shape = str_of(field(r, "shape")); + let gabled = shape == Some("sattel") || (shape == Some("mansarde") && nn(field(r, "mansardType")).map_or(Some("giebel"), |m| m.as_str()) == Some("giebel")); + let axis_y = str_of(field(r, "ridgeAxis")) == Some("y"); + let pitches = field(r, "edgePitchDeg").and_then(Value::as_array); + let mut rings: Vec<&[Value]> = vec![arr(field(r, "outline"))]; + rings.extend(arr(field(r, "holes")).iter().map(|h| arr(Some(h)))); + let mut out = Vec::new(); + let mut index = 0usize; + for (ri, ring) in rings.iter().enumerate() { + for (edge, a) in ring.iter().enumerate() { + let b = &ring[(edge + 1) % ring.len()]; + let (pa, pb) = (xy(a), xy(b)); + let spec = match pitches.and_then(|p| p.get(index)) { + Some(Value::Null) => O::default().s("kind", "gable").done(), + Some(v) if v.as_f64().is_some_and(|d| d.is_finite() && d >= 0.0) => O::default().s("kind", "pitch").v("deg", v).done(), + _ => O::default().s("kind", "default").done(), + }; + let default_gable = gabled && { + let (dx, dy) = ((pb.0 - pa.0).abs(), (pb.1 - pa.1).abs()); + if axis_y { + dy < dx + } else { + dx < dy + } + }; + out.push( + O::default() + .v("index", Value::from(index)) + .v("ring", Value::from(ri)) + .v("edge", Value::from(edge)) + .v("a", a) + .v("b", b) + .n("length", hypot2(pb.0 - pa.0, pb.1 - pa.1)) + .v("spec", spec) + .v("defaultGable", Value::Bool(default_gable)) + .done(), + ); + index += 1; + } + } + J::arr(out) +} + +fn opening_selection(root: &Map, o: &Value) -> Result { + use crate::opening_geom::{opening_gap_quad, v, WallRef}; + let cat = category(root, field(o, "categoryCode")); + let color = color_of(o, cat, WALL_FALLBACK_COLOR); + let weight = lw_or(None, cat, WALL_FALLBACK_MM); + let wall = find_by(arr(root.get("walls")), "id", field(o, "hostWallId")); + let floor = wall.and_then(|w| level(root, field(w, "floorId"))); + let mut quad = None; + if let Some(w) = wall { + let (s, e) = (xy(field(w, "start").unwrap_or(&Value::Null)), xy(field(w, "end").unwrap_or(&Value::Null))); + let wr = |total: f64, ref_off: f64| WallRef { start: v(s.0, s.1), end: v(e.0, e.1), total, ref_off }; + let (pos, width) = (num_of(field(o, "position")), num_of(field(o, "width"))); + // Der Wandtyp wird erst gebraucht (und kann werfen), wenn die Lücke nicht entartet ist. + if crate::opening_geom::opening_interval(&wr(0.0, 0.0), pos, width).is_some() { + let wt = find_by(arr(root.get("wallTypes")), "id", field(w, "wallTypeId")) + .ok_or_else(|| format!("Unbekannter Wandtyp: {}", field(w, "wallTypeId").map_or("undefined".into(), js_text)))?; + let total = type_thickness(wt); + quad = opening_gap_quad(&wr(total, reference_offset(w, total)), pos, width); + } + } + let bb = bbox_of(quad.unwrap_or_default().into_iter().map(|p| (p.x, p.y))); + let (zb, zt) = match wall { + Some(w) => { + let (wb, wt) = vertical_extent(root, w); + let bottom = wb + jsnum::max(0.0, num_of(field(o, "sillHeight"))); + (js_num(bottom), Some(js_num(jsnum::min(wt, bottom + num_of(field(o, "height")))))) + } + None => (js_num(0.0), field(o, "height").cloned()), + }; + let info = O::default() + .raw("id", o, "id") + .raw("kind", o, "kind") + .raw("hostWallId", o, "hostWallId") + .o("hostWallName", floor.map_or_else(|| field(o, "hostWallId").cloned(), |f| Some(Value::from(field(f, "name").map_or("undefined".into(), js_text))))) + .raw("position", o, "position") + .raw("width", o, "width") + .raw("height", o, "height") + .raw("sillHeight", o, "sillHeight") + .raw("hinge", o, "hinge") + .raw("swing", o, "swing") + .raw("swingAngle", o, "swingAngle") + .raw("openingDir", o, "openingDir") + .raw("wingCount", o, "wingCount") + .raw("doorType", o, "doorType") + .raw("lintelLines", o, "lintelLines") + .raw("typeId", o, "typeId") + .raw("detailLevel", o, "detailLevel") + .v("zBottom", zb) + .o("zTop", zt) + .raw("frameLine", o, "frameLine") + .raw("frameViewLine", o, "frameViewLine") + .raw("sashLine", o, "sashLine") + .raw("sillLineStyle", o, "sillLineStyle") + .done(); + Ok(O::default() + .s("kind", "opening") + .raw("id", o, "id") + .raw("categoryCode", o, "categoryCode") + .v("color", color) + .raw("colorPenId", o, "colorPenId") + .v("weightMm", weight) + .v("bbox", bbox_value(bb)) + .v("opening", info) + .done()) +} + +/// Achsversatz der Schichtstapelung (`wallReferenceOffset`): freier Versatz (auf die Dicke geklemmt), +/// sonst die benannte Referenzlinie. +fn reference_offset(w: &Value, total: f64) -> f64 { + let half = total / 2.0; + if nn(field(w, "referenceOffset")).is_some() { + return jsnum::max(-half, jsnum::min(half, num_of(field(w, "referenceOffset")))); + } + match nn(field(w, "referenceLine")).map_or(Some("center"), Value::as_str) { + Some("left") => half, + Some("right") => -half, + _ => 0.0, + } +} + +fn stair_selection(root: &Map, s: &Value) -> Result { + let cat = category(root, field(s, "categoryCode")); + let color = color_of(s, cat, WALL_FALLBACK_COLOR); + let weight = lw_or(None, cat, WALL_FALLBACK_MM); + let floor = level(root, field(s, "floorId")); + let (base, floor_height) = floor.map_or((0.0, 0.0), |f| (num_or(field(f, "baseElevation"), 0.0), num_or(field(f, "floorHeight"), 0.0))); + let tr = field(s, "totalRise"); + let rise = if nn(tr).is_some() && num_of(tr) > 0.0 { + num_of(tr) + } else if floor_height > 0.0 { + floor_height + } else { + 2.6 + }; + let (zb, zt) = (base, base + rise); + let total_rise = zt - zb; + let typed: crate::model::Stair = serde_json::from_value(s.clone()).map_err(|e| format!("Treppe passt nicht zum Kern-Modell: {e}"))?; + // Wie die TS-Fassade: Geometrie flach, leer (Unsinn-Eingabe) = leere Geometrie, daraus die bbox. + let mut geo = crate::stair::geometry(&typed.encode(), total_rise); + if geo.len() < 4 { + geo = vec![0.0, 0.0, 0.0, 0.0, -1.0, 0.0]; + geo.extend([0.0; 10]); + } + let b = crate::stair::bbox(&geo); + let bb = if b.len() < 4 { [0.0; 4] } else { [b[0], b[1], b[2], b[3]] }; + let info = O::default() + .raw("shape", s, "shape") + .raw("width", s, "width") + .raw("stepCount", s, "stepCount") + .n("totalRise", total_rise) + .n("riserHeight", geo[0]) + .n("treadDepth", geo[1]) + .v("up", Value::Bool(field(s, "up") != Some(&Value::Bool(false)))) + .raw("arrowStyle", s, "arrowStyle") + .raw("referenz", s, "referenz") + .raw("typeId", s, "typeId") + .raw("floorId", s, "floorId") + .o("floorName", floor_name(floor, field(s, "floorId"))) + .n("zBottom", zb) + .n("zTop", zt) + .done(); + Ok(O::default() + .s("kind", "stair") + .raw("id", s, "id") + .raw("categoryCode", s, "categoryCode") + .raw("floorId", s, "floorId") + .v("color", color) + .raw("colorPenId", s, "colorPenId") + .v("weightMm", weight) + .v("bbox", bbox_value(bb)) + .v("stair", info) + .done()) +} + +fn room_selection(root: &Map, r: &Value) -> J { + let cat = category(root, field(r, "categoryCode")); + let color = color_of(r, cat, WALL_FALLBACK_COLOR); + let weight = lw_or(None, cat, WALL_FALLBACK_MM); + let ev = crate::room_area::evaluate(&ring(field(r, "boundary")), 0.0); + let floor = level(root, field(r, "floorId")); + let bb = bbox_of(pts_of(field(r, "boundary"))); + let info = O::default() + .raw("name", r, "name") + .raw("siaCategory", r, "siaCategory") + .n("area", ev.net) + .n("perimeter", ev.perimeter) + .raw("floorId", r, "floorId") + .o("floorName", floor_name(floor, field(r, "floorId"))) + .done(); + O::default() + .s("kind", "room") + .raw("id", r, "id") + .raw("categoryCode", r, "categoryCode") + .raw("floorId", r, "floorId") + .v("color", color) + .raw("colorPenId", r, "colorPenId") + .v("weightMm", weight) + .v("closed", Value::Bool(true)) + .v("bbox", bbox_value(bb)) + .v("room", info) + .done() +} + +fn solid_selection(root: &Map, s: &Value) -> J { + let floor = level(root, field(s, "levelId")); + let bb = bbox_of(pts_of(field(s, "points"))); + let brep = field(s, "brep").filter(|b| truthy(Some(b))); + let taper = num_or(field(s, "taper"), 0.0); + let subtract = str_of(field(s, "operation")) == Some("subtract"); + let info = O::default() + .raw("height", s, "height") + .n("taper", taper) + .n("cornerRadius", num_or(field(s, "cornerRadius"), 0.0)) + .n("chamfer", num_or(field(s, "chamfer"), 0.0)) + .o("brepLabel", brep.map(|b| nn(field(b, "label")).cloned().unwrap_or_else(|| "B-Rep".into()))) + .n("area", polygon_area(field(s, "points"))) + // Platzhalter: `spec` (B-Rep für truck) setzt die TS-Fassade ein. + .v("spec", Value::Null) + .v("subtract", Value::Bool(subtract)) + .v("canSubtract", Value::Bool(brep.is_none() && taper < 1e-6)) + .n("baseOffset", num_or(field(s, "baseOffset"), 0.0)) + .raw("floorId", s, "levelId") + .o("floorName", floor_name(floor, field(s, "levelId"))) + .done(); + O::default() + .s("kind", "extrudedSolid") + .raw("id", s, "id") + .s("categoryCode", "") + .raw("floorId", s, "levelId") + .s("color", EXTRUSION_COLOR) + .n("weightMm", WALL_FALLBACK_MM) + .v("fillHatchId", Value::Null) + .v("fillColor", Value::Null) + .v("closed", Value::Bool(true)) + .v("bbox", bbox_value(bb)) + .v("extrudedSolid", info) + .done() +} + +fn column_selection(root: &Map, c: &Value) -> Result { + let floor = level(root, field(c, "floorId")); + let cat = category(root, field(c, "categoryCode")); + let typed: crate::model::Column = serde_json::from_value(c.clone()).map_err(|e| format!("Stütze passt nicht zum Kern-Modell: {e}"))?; + let bb = bbox_of(crate::model3d::column_footprint(&typed).into_iter().map(|p| (p.x, p.y))); + let (zb, zt) = vertical_extent(root, c); + let rotation = num_or(field(c, "rotation"), 0.0); + let info = O::default() + .raw("profile", c, "profile") + .raw("height", c, "height") + .n("rotationDeg", (rotation * 180.0) / std::f64::consts::PI) + .raw("floorId", c, "floorId") + .o("floorName", floor_name(floor, field(c, "floorId"))) + .n("zBottom", zb) + .n("zTop", zt) + .done(); + // Ein gelöschtes Bauteil wirft hier nicht (die Vorschau fällt auf „kein Bauteil" zurück). + let comp = if truthy(field(c, "componentId")) { find_by(arr(root.get("components")), "id", field(c, "componentId")) } else { None }; + let (fg, bg, hatch) = effective(c, comp, cat); + let weight = match nn(field(c, "strokeWeight")) { + Some(w) => w.clone(), + None if is_layer(field(c, "strokeWeightSource")) => cat.and_then(|k| nn(field(k, "lw"))).cloned().unwrap_or_else(|| js_num(WALL_FALLBACK_MM)), + None => js_num(WALL_FALLBACK_MM), + }; + Ok(O::default() + .s("kind", "column") + .raw("id", c, "id") + .raw("categoryCode", c, "categoryCode") + .raw("floorId", c, "floorId") + .v("color", color_of(c, cat, COLUMN_COLOR)) + .raw("colorPenId", c, "colorPenId") + .v("weightMm", weight) + .raw("fillHatchId", c, "hatchId") + .raw("foreground", c, "foreground") + .raw("foregroundPenId", c, "foregroundPenId") + .raw("background", c, "background") + .raw("backgroundPenId", c, "backgroundPenId") + .raw("foregroundSource", c, "foregroundSource") + .raw("backgroundSource", c, "backgroundSource") + .o("effectiveForeground", fg) + .o("effectiveBackground", bg) + .o("effectiveHatchId", hatch) + .raw("strokeWeightOverride", c, "strokeWeight") + .raw("strokeWeightSource", c, "strokeWeightSource") + .raw("hatchSource", c, "hatchSource") + .v("bbox", bbox_value(bb)) + .v("column", info) + .done()) +} + +fn context_selection(root: &Map, o: &Value) -> J { + let kind = str_of(field(o, "type")); + let mut pts: Vec<(f64, f64)> = Vec::new(); + match kind { + Some("contourSet") => { + for c in arr(field(o, "contours")) { + pts.extend(pts_of(field(c, "pts"))); + } + } + Some("image") => { + pts.push(xy(field(o, "min").unwrap_or(&Value::Null))); + pts.push(xy(field(o, "max").unwrap_or(&Value::Null))); + } + _ => { + let pos = arr(field(o, "positions")); + let mut i = 0; + while i + 2 < pos.len() { + pts.push((num_of(Some(&pos[i])), num_of(Some(&pos[i + 1])))); + i += 3; + } + } + } + let bb = bbox_of(pts); + let lv95 = root.get("geoAnchor").filter(|a| truthy(Some(a))).map(|a| { + let (lv, m) = (field(a, "lv95").unwrap_or(&Value::Null), field(a, "model").unwrap_or(&Value::Null)); + let (oe, on) = (num_of(field(lv, "e")) - num_of(field(m, "x")), num_of(field(lv, "n")) - num_of(field(m, "y"))); + O::default().n("e", (bb[0] + bb[2]) / 2.0 + oe).n("n", (bb[1] + bb[3]) / 2.0 + on).done() + }); + let image = kind == Some("image"); + O::default() + .s("kind", "contextObject") + .raw("id", o, "id") + .s("categoryCode", "") + .s("color", "#888888") + .n("weightMm", WALL_FALLBACK_MM) + .v("bbox", bbox_value(bb)) + .v("contextObject", O::default().raw("objType", o, "type").o("lv95Center", lv95).done()) + .v("isImage", Value::Bool(image)) + .o("opacity", image.then(|| nn(field(o, "opacity")).cloned().unwrap_or_else(|| Value::from(1u64)))) + .o("imageFilters", if image { field(o, "filters").cloned() } else { None }) + .done() +} + +/// Ob eine 2D-Form geschlossen ist (Füllung/Schraffur sinnvoll). +fn is_closed_geom(g: &Value) -> bool { + match str_of(field(g, "shape")) { + Some("rect" | "circle" | "ellipse") => true, + Some("polyline" | "spline") => truthy(field(g, "closed")), + _ => false, + } +} + +/// Bounding-Box einer 2D-Form (`geomBBox`, auch für Ausrichten/Verteilen). +pub fn geom_bbox(g: &Value) -> [f64; 4] { + let p = |k: &str| xy(g.get(k).unwrap_or(&Value::Null)); + let mut pts: Vec<(f64, f64)> = Vec::new(); + match str_of(field(g, "shape")) { + Some("line" | "xline" | "ray") => pts.extend([p("a"), p("b")]), + Some("polyline" | "bezier" | "spline") => pts = pts_of(field(g, "pts")), + Some("rect" | "image") => pts.extend([p("min"), p("max")]), + Some("circle" | "arc") => { + let (c, r) = (p("center"), num_of(field(g, "r"))); + pts.extend([(c.0 - r, c.1 - r), (c.0 + r, c.1 + r)]); + } + Some("ellipse") => { + // Genau mit Drehung (rotation 0 beim heutigen Werkzeug). + let rot = num_of(field(g, "rotation")); + let (c, s) = (jsnum::cos(rot), jsnum::sin(rot)); + let (rx, ry) = (num_of(field(g, "rx")), num_of(field(g, "ry"))); + let (hw, hh) = (hypot2(rx * c, ry * s), hypot2(rx * s, ry * c)); + let ctr = p("center"); + pts.extend([(ctr.0 - hw, ctr.1 - hh), (ctr.0 + hw, ctr.1 + hh)]); + } + Some("dimension") => { + let chain = pts_of(field(g, "pts")); + pts.extend(chain.iter().copied()); + if chain.len() >= 2 { + let (a, b) = (chain[0], chain[chain.len() - 1]); + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let l = hypot2(dx, dy); + let len = if l == 0.0 || l.is_nan() { 1.0 } else { l }; + let off = num_of(field(g, "offset")); + let (nx, ny) = ((-dy / len) * off, (dx / len) * off); + pts.extend(chain.iter().map(|q| (q.0 + nx, q.1 + ny))); + } + } + Some("kote" | "text" | "block" | "detailref" | "pointmarker") => pts.push(p("at")), + Some("scalebar") => { + let at = p("at"); + pts.extend([at, (at.0 + num_of(field(g, "segmentLength")) * num_of(field(g, "segments")), at.1)]); + } + _ => {} + } + bbox_of(pts) +} + +fn drawing_selection(root: &Map, d: &Value) -> J { + let g = field(d, "geom").unwrap_or(&Value::Null); + let ls = if truthy(field(d, "lineStyleId")) { find_by(arr(root.get("lineStyles")), "id", field(d, "lineStyleId")) } else { None }; + let cat = category(root, field(d, "categoryCode")); + let color = nn(field(d, "color")) + .or_else(|| ls.and_then(|l| nn(field(l, "color")))) + .or_else(|| cat.and_then(|c| nn(field(c, "color")))) + .cloned() + .unwrap_or_else(|| DRAW_FALLBACK_COLOR.into()); + // Wie der Plan: Override, „layer" (Standard) erzwingt die Kategorie, sonst Linienstil → Kategorie. + let cat_lw = cat.and_then(|c| nn(field(c, "lw"))); + let weight = nn(field(d, "weightMm")) + .or_else(|| if str_of(field(d, "strokeWeightSource")) != Some("object") { cat_lw } else { None }) + .or_else(|| ls.and_then(|l| nn(field(l, "weight")))) + .or(cat_lw) + .cloned() + .unwrap_or_else(|| js_num(WALL_FALLBACK_MM)); + let closed = is_closed_geom(g); + // Ein Drawing2D hat kein Bauteil; fehlende Quelle = „Nach Ebene". + let layer = Value::from("layer"); + let src = |k: &str| nn(d.get(k)).or(Some(&layer)).cloned(); + let pick = |k: &str| if closed { d.get(k).cloned() } else { None }; + let (fg, bg, hatch) = if closed { + let fs = src("foregroundSource"); + let bs = src("backgroundSource"); + let hs = src("hatchSource"); + ( + resolve_color(None, field(d, "foreground"), cat, fs.as_ref()), + resolve_color(None, field(d, "background"), cat, bs.as_ref()), + resolve_hatch(field(d, "hatchId"), hs.as_ref(), cat, None), + ) + } else { + (None, None, Some(Value::Null)) + }; + let is_image = str_of(field(g, "shape")) == Some("image"); + let detail = (str_of(field(g, "shape")) == Some("detailref")).then(|| { + let layouts = J::arr(arr(root.get("layouts")).iter().map(|l| O::default().raw("id", l, "id").raw("name", l, "name").done())); + O::default().raw("label", g, "label").raw("sheetLayoutId", g, "sheetLayoutId").raw("sheetLabel", g, "sheetLabel").v("availableLayouts", layouts).done() + }); + O::default() + .s("kind", "drawing2d") + .raw("id", d, "id") + .raw("categoryCode", d, "categoryCode") + .raw("floorId", d, "levelId") + .v("color", color) + .raw("colorPenId", d, "colorPenId") + .v("weightMm", weight) + .v("fillHatchId", if closed { nn(field(d, "hatchId")).cloned().unwrap_or(Value::Null) } else { Value::Null }) + .v("fillColor", if closed { nn(field(d, "fillColor")).cloned().unwrap_or(Value::Null) } else { Value::Null }) + .o("foreground", pick("foreground")) + .o("foregroundPenId", pick("foregroundPenId")) + .o("background", pick("background")) + .o("backgroundPenId", pick("backgroundPenId")) + .o("foregroundSource", pick("foregroundSource")) + .o("backgroundSource", pick("backgroundSource")) + .o("effectiveForeground", fg) + .o("effectiveBackground", bg) + .o("effectiveHatchId", hatch) + .raw("strokeWeightOverride", d, "weightMm") + .raw("strokeWeightSource", d, "strokeWeightSource") + .o("hatchSource", pick("hatchSource")) + .v("closed", Value::Bool(closed)) + .v("isImage", Value::Bool(is_image)) + .o("opacity", if is_image { Some(nn(field(g, "opacity")).cloned().unwrap_or_else(|| Value::from(1u64))) } else { field(d, "opacity").cloned() }) + .v("bbox", bbox_value(geom_bbox(g))) + .o("detailRef", detail) + .done() +} + +/// Bounding-Boxen der Zeichnungen `ids` in Listen-Reihenfolge: `[[id, minX, minY, maxX, maxY], …]`. +pub fn drawing_bboxes(root: &Map, ids: &[String]) -> J { + let wanted: std::collections::HashSet<&str> = ids.iter().map(String::as_str).collect(); + J::arr( + arr(root.get("drawings2d")) + .iter() + .filter(|d| id_of(d).is_some_and(|i| wanted.contains(i))) + .map(|d| { + let b = geom_bbox(field(d, "geom").unwrap_or(&Value::Null)); + let mut out = vec![b'[']; + field(d, "id").unwrap_or(&Value::Null).emit(&mut out); + for x in b { + out.push(b','); + js_num(x).emit(&mut out); + } + out.push(b']'); + J(out) + }), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn root(v: Value) -> Map { + v.as_object().unwrap().clone() + } + + fn sel(r: &Map, a: Value) -> Result { + derive(r, &serde_json::from_value(a).unwrap()).map(|j| serde_json::from_str(&j.into_string()).unwrap()) + } + + #[test] + fn wand_mit_typ_volumen_und_fuge() { + let r = root(json!({ + "layers": [{"code": "1", "name": "W", "color": "#111111", "lw": 0.35, "children": [{"code": "2", "color": "#222222", "lw": 0.5}]}], + "components": [{"id": "a", "name": "Beton", "abbrev": "BET", "foreground": "#f00"}, {"id": "b", "name": "Daemmung"}], + "wallTypes": [{"id": "t", "name": "Aussenwand", "layers": [{"componentId": "a", "thickness": 0.2}, {"componentId": "b", "thickness": 0.1}]}], + "drawingLevels": [{"id": "eg", "name": "EG", "kind": "floor", "baseElevation": 0}, {"id": "og", "name": "OG", "kind": "floor", "baseElevation": 3}], + "walls": [{"id": "w", "floorId": "eg", "categoryCode": "2", "start": {"x": 0, "y": 0}, "end": {"x": 4, "y": 3}, "wallTypeId": "t", "height": 2.5}], + "openings": [{"id": "o", "hostWallId": "w", "width": 1, "height": 2}], + })); + let s = sel(&r, json!({"wallIds": ["w"]})).unwrap(); + assert_eq!(s["color"], json!("#222222")); + assert_eq!(s["weightMm"], json!(0.5)); + assert_eq!(s["effectiveForeground"], json!("#f00")); + assert_eq!(s["wall"]["length"], json!(5)); + assert_eq!(s["wall"]["layerBoundaries"], json!([{"offset": 0.15000000000000002 - 0.2, "label": "BET|Daemmung"}])); + assert_eq!(s["wall"]["floorAbove"], json!({"id": "og", "name": "OG"})); + assert_eq!(s["wall"]["wallTypes"][0]["label"], json!("Aussenwand")); + let gross = 5.0 * 0.30000000000000004 * 2.5; + assert_eq!(s["wall"]["netVolume"].as_f64().unwrap(), gross - 2.0 * 0.30000000000000004); + // Unbekannter Wandtyp: dieselbe Meldung wie TS. + let mut bad = r.clone(); + bad["walls"][0]["wallTypeId"] = json!("x"); + assert_eq!(sel(&bad, json!({"wallIds": ["w"]})).unwrap_err(), "Unbekannter Wandtyp: x"); + } + + #[test] + fn typ_beschriftung_wie_ts() { + let r = root(json!({"components": [{"id": "a", "abbrev": "BET"}, {"id": "b", "abbrev": "GKB"}]})); + let one = json!({"name": "N", "layers": [{"componentId": "a", "thickness": 0.24}]}); + assert_eq!(wall_type_label(&r, &one), json!("BET 24")); + let two = json!({"name": "N", "layers": [{"componentId": "b", "thickness": 0.0125}, {"componentId": "a", "thickness": 0.24}]}); + assert_eq!(wall_type_label(&r, &two), json!("GKB·BET (25.3)")); + } + + #[test] + fn zeichnung_offen_und_geschlossen() { + let r = root(json!({"layers": [{"code": "1", "color": "#123", "lw": 0.25, "hatch": "h"}], + "drawings2d": [ + {"id": "l", "categoryCode": "1", "levelId": "f", "geom": {"shape": "line", "a": {"x": 0, "y": 0}, "b": {"x": 2, "y": -1}}}, + {"id": "r", "categoryCode": "1", "levelId": "f", "geom": {"shape": "rect", "min": {"x": 0, "y": 0}, "max": {"x": 1, "y": 1}}} + ]})); + let l = sel(&r, json!({"drawingId": "l"})).unwrap(); + assert_eq!(l["effectiveHatchId"], Value::Null); + assert_eq!(l["bbox"], json!({"minX": 0, "minY": -1, "maxX": 2, "maxY": 0})); + let rr = sel(&r, json!({"drawingId": "r"})).unwrap(); + assert_eq!(rr["effectiveHatchId"], json!("h")); + assert_eq!(rr["effectiveForeground"], json!("#123")); + assert!(sel(&r, json!({"drawingId": "x"})).unwrap().is_null()); + } +} diff --git a/src-tauri/core/src/web/grips.rs b/src-tauri/core/src/web/grips.rs index f9fe1e60..00bee250 100644 --- a/src-tauri/core/src/web/grips.rs +++ b/src-tauri/core/src/web/grips.rs @@ -12,7 +12,7 @@ use wasm_bindgen::prelude::wasm_bindgen; /// (zurückgewiesen, Dokument unverändert); Fehler als Text mit vorangestelltem `\u{1}`. #[wasm_bindgen] pub fn doc_grip_commit(h: u32, req_json: &str, key: &str, now_ms: f64) -> String { - let req: Value = match serde_json::from_str(req_json) { + let req: crate::grips::Request = match serde_json::from_str(req_json) { Ok(v) => v, Err(e) => return format!("\u{1}Griff-Anfrage: {e}"), }; diff --git a/src/core/document.ts b/src/core/document.ts index 754d6131..23f5eaec 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -245,7 +245,7 @@ export class ProjectDocument { commitGrip(base: Project, req: object, coalesceKey: string | undefined, now: number): { project: Project; ops: CoreOp[]; notice?: string } | { problems: string[] } { this.ensure(base); if (!this.handle) return { problems: ["Projekt-Dokument im Kern nicht offen."] }; - const out = core().doc_grip_commit(this.handle, toMarkedJson(req), coalesceKey ?? "", now); + const out = core().doc_grip_commit(this.handle, gripJson(req), coalesceKey ?? "", now); if (out.startsWith("\u0001")) throw new Error(out.slice(1)); const r = fromMarkedJson<{ ops: CoreOp[]; notice?: string } | { problems: string[] }>(out); if ("problems" in r) return r; @@ -255,10 +255,21 @@ export class ProjectDocument { return { project, ops: r.ops, notice: r.notice }; } + /** + * Wie {@link queryRoot} für Abfragen, deren Antwort nicht endliche Zahlen als Marken trägt + * (`selectionInfo`, `drawingBBoxes`); die Marken werden wieder Zahlen. + */ + queryRootMarked(name: "selectionInfo" | "drawingBBoxes", text = ""): T { + if (!this.handle) throw new Error(`Kern-Abfrage „${name}": Dokument nicht offen`); + const out = core().doc_query_root(this.handle, name, text); + if (out.startsWith("\u0001")) throw new Error(out.slice(1)); + return fromMarkedJson(out); + } + /** Wie {@link commitGrip}, aber nur rechnen (ohne Anwenden): die Ops und ggf. der Hinweis. */ gripOps(req: object): { ops: CoreOp[]; notice?: string } { if (!this.handle) throw new Error("Kern-Abfrage „gripOps“: Dokument nicht offen"); - const out = core().doc_query_root(this.handle, "gripOps", toMarkedJson(req)); + const out = core().doc_query_root(this.handle, "gripOps", gripJson(req)); if (out.startsWith("\u0001")) throw new Error(out.slice(1)); return fromMarkedJson(out); } @@ -320,6 +331,15 @@ export class ProjectDocument { } } +/** Griff-Anfrage als JSON; Marken nur bei nicht endlichen Zahlen (der Ersetzer kostet je Wert einen Aufruf). */ +function gripJson(req: object): string { + for (const v of Object.values(req)) { + const bad = typeof v === "number" ? !Number.isFinite(v) : Array.isArray(v) && v.some((x) => typeof x === "number" && !Number.isFinite(x)); + if (bad) return toMarkedJson(req); + } + return JSON.stringify(req); +} + let shared: ProjectDocument | null = null; /** diff --git a/src/editors/align.ts b/src/editors/align.ts index 92724a76..554d7111 100644 --- a/src/editors/align.ts +++ b/src/editors/align.ts @@ -2,12 +2,12 @@ // `editors/explode.ts`), damit sie ohne UI testbar bleiben. // // Beides arbeitet auf den BOUNDING-BOXEN der Elemente (dieselbe Herleitung wie -// im Attribut-Panel, s. `geomBBox`) und verschiebt sie anschliessend als +// im Attribut-Panel: Kern `selection_info.rs::geom_bbox`, Abfrage `drawingBBoxes`) und verschiebt sie anschliessend als // Ganzes. Die Form selbst bleibt unangetastet — es wird nur verschoben, nie // skaliert oder verzerrt. import type { Drawing2D, Project, Vec2 } from "../model/types"; -import { geomBBox } from "../state/selectionInfo"; +import { documentFor } from "../core/document"; import { mvGeom, patchItems } from "../core"; import type { CoreOp } from "../core"; @@ -27,9 +27,11 @@ interface Boxed { function boxesOf(project: Project, ids: string[]): Boxed[] { const wanted = new Set(ids); - return project.drawings2d - .filter((d) => wanted.has(d.id)) - .map((d) => ({ d, ...geomBBox(d.geom) })); + const list = project.drawings2d.filter((d) => wanted.has(d.id)); + if (list.length === 0) return []; + // Je Element `[id, minX, minY, maxX, maxY]`, in Listen-Reihenfolge wie `list`. + const b = documentFor(project).queryRootMarked<[string, number, number, number, number][]>("drawingBBoxes", JSON.stringify(ids)); + return list.map((d, i) => ({ d, minX: b[i][1], minY: b[i][2], maxX: b[i][3], maxY: b[i][4] })); } /** Ops: verschiebt die genannten Elemente um je einen eigenen Vektor. */ diff --git a/src/state/selectionInfo.test.ts b/src/state/selectionInfo.test.ts new file mode 100644 index 00000000..46b11e9c --- /dev/null +++ b/src/state/selectionInfo.test.ts @@ -0,0 +1,63 @@ +// Objekt-Info der Auswahl ([K4] S3: gerechnet im Kern, `selection_info.rs`) — Wand, Decke, +// Zeichnung, Extrusion (B-Rep-Beschreibung aus TS) und die Meldung bei unbekanntem Wandtyp. +import { describe, expect, it } from "vitest"; +import { deriveSelection } from "./selectionInfo"; +import { sampleProject } from "../model/sampleProject"; +import type { Project } from "../model/types"; + +const base = (): Project => structuredClone(sampleProject); + +describe("deriveSelection (Kern)", () => { + it("Wand: Typ-Liste, Geschosse, Länge, Volumen und UK/OK", () => { + const p = base(); + const w = p.walls[0]; + const sel = deriveSelection(p, [w.id], null)!; + expect(sel.kind).toBe("wall"); + expect(sel.id).toBe(w.id); + expect(sel.wall!.wallTypes.length).toBe(p.wallTypes.length); + expect(sel.wall!.floors.every((f) => p.drawingLevels.some((z) => z.id === f.id && z.kind === "floor"))).toBe(true); + expect(sel.wall!.length).toBeCloseTo(Math.hypot(w.end.x - w.start.x, w.end.y - w.start.y), 12); + expect(sel.wall!.netVolume).toBeLessThanOrEqual(sel.wall!.grossVolume); + expect(sel.wall!.zTop).toBeGreaterThan(sel.wall!.zBottom); + expect(sel.bbox.minX).toBe(Math.min(w.start.x, w.end.x)); + }); + + it("unbekannter Wandtyp bricht mit derselben Meldung ab wie bisher", () => { + const p = base(); + p.walls[0] = { ...p.walls[0], wallTypeId: "fehlt" }; + expect(() => deriveSelection(p, [p.walls[0].id], null)).toThrow("Unbekannter Wandtyp: fehlt"); + }); + + it("Zeichnung: offene Linie ohne Füllung, Rechteck mit Ebenen-Vorgaben", () => { + const p = base(); + const lvl = p.drawingLevels[0].id; + const code = p.layers[0].code; + p.drawings2d = [ + { id: "l", type: "drawing2d", levelId: lvl, categoryCode: code, geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 3, y: -2 } } }, + { id: "r", type: "drawing2d", levelId: lvl, categoryCode: code, hatchId: "h", geom: { shape: "rect", min: { x: 1, y: 1 }, max: { x: 2, y: 4 } } }, + ]; + const l = deriveSelection(p, [], "l")!; + expect(l.closed).toBe(false); + expect(l.effectiveHatchId).toBeNull(); + expect(l.bbox).toEqual({ minX: 0, minY: -2, maxX: 3, maxY: 0 }); + const r = deriveSelection(p, [], "r")!; + expect(r.closed).toBe(true); + expect(r.fillHatchId).toBe("h"); + expect(r.effectiveHatchId).toBe("h"); + expect(deriveSelection(p, [], "nix")).toBeNull(); + }); + + it("Extrusion: Fläche im Kern, B-Rep-Beschreibung (truck) aus TS", () => { + const p = base(); + const lvl = p.drawingLevels[0].id; + p.extrudedSolids = [ + { id: "x", type: "extrudedSolid", levelId: lvl, points: [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 3 }], height: 2 }, + ]; + const sel = deriveSelection(p, [], null, null, null, null, null, "x")!; + expect(sel.extrudedSolid!.area).toBeCloseTo(3, 12); + expect(sel.extrudedSolid!.spec).toMatchObject({ kind: "extrude", height: 2 }); + expect(Object.keys(sel.extrudedSolid!)).toEqual([ + "height", "taper", "cornerRadius", "chamfer", "area", "spec", "subtract", "canSubtract", "baseOffset", "floorId", "floorName", + ]); + }); +}); diff --git a/src/state/selectionInfo.ts b/src/state/selectionInfo.ts index 11cdc85f..ae4d4a51 100644 --- a/src/state/selectionInfo.ts +++ b/src/state/selectionInfo.ts @@ -8,59 +8,30 @@ // Übersteuerung am Element → LineStyle → Kategorie-Default. So zeigt die Palette // den TATSÄCHLICH gezeichneten Wert, nicht nur das (oft leere) Override-Feld. // +// [K4] S3: gerechnet wird im Rust-Kern (`src-tauri/core/src/selection_info.rs`, Wurzel-Abfrage +// `selectionInfo` auf dem Projekt-Dokument); hier stehen der Kontrakt (Typen) und die Fassade. Der +// B-Rep-Körper einer Extrusion (`spec`) kommt aus TS (`extrudedSolidSpec`, truck-Pipeline). +// // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import { extrudedSolidSpec } from "../core"; import type { SolidSpec } from "../engine/truckSolid"; -import { - ceilingThickness, - getCeilingType, - getComponent, - getWallType, - wallTypeLabel, - wallTypeThickness, -} from "../model/types"; +import { documentFor } from "../core/document"; import type { AttributeSource, - Ceiling, - Column, ColumnProfile, ContextImage, ContextObject, - Drawing2D, - Drawing2DGeom, - ExtrudedSolid, - Opening, Project, - Roof, RoofShape, - Room, SiaCategory, SliceTermination, - Stair, StairShape, VerticalAnchor, - Wall, WallReferenceLine, } from "../model/types"; -import { findCategory } from "../model/layers"; import type { DetailLevel } from "../model/viewTypes"; -import { localToLv95 } from "../io/lv95"; -import { resolveForeground, resolveBackground, resolveHatchId, resolveStrokeWeight } from "../core"; -import { columnVerticalExtent } from "../model/wall"; -import { columnFootprint } from "../core"; -import { evaluateRoom, polygonArea } from "../core"; -import { - ceilingVerticalExtent, - nextFloorAbove, - stairVerticalExtent, - wallVerticalExtent, -} from "../model/wall"; -import { ceilingArea, outlineBBox } from "../core"; -import { roofBBox, roofBaseElevation, roofEdgeList, roofGeometry } from "../core"; import type { RoofEdge } from "../core"; -import { openingGapQuad, openingVerticalExtent } from "../core"; -import { stairGeometry, stairBBox } from "../core"; /** Eintrag für die WallType-Auswahl (Preset-Dropdown) im Object-Info-Panel. */ export interface WallTypeChoice { @@ -541,754 +512,16 @@ export interface ContextObjectInfo { lv95Center?: { e: number; n: number }; } -const WALL_FALLBACK_MM = 0.18; -const DRAW_FALLBACK_COLOR = "#d0d0d0"; -const WALL_FALLBACK_COLOR = "#2b3039"; - -/** Ob eine 2D-Form geschlossen ist (Füllung/Schraffur sinnvoll). */ -function isClosedGeom(g: Drawing2DGeom): boolean { - return ( - g.shape === "rect" || - g.shape === "circle" || - g.shape === "ellipse" || - (g.shape === "polyline" && g.closed) || - (g.shape === "spline" && g.closed) - ); -} - -/** - * Bounding-Box einer 2D-Form. Exportiert, weil auch die Editier-Werkzeuge sie - * brauchen (Ausrichten/Verteilen, `editors/align.ts`) — dieselbe Herleitung - * wie fürs Attribut-Panel, damit beide Seiten nie auseinanderlaufen. - */ -export function geomBBox(g: Drawing2DGeom): SelectionBBox { - let minX = Infinity, - minY = Infinity, - maxX = -Infinity, - maxY = -Infinity; - const acc = (x: number, y: number) => { - minX = Math.min(minX, x); - minY = Math.min(minY, y); - maxX = Math.max(maxX, x); - maxY = Math.max(maxY, y); - }; - switch (g.shape) { - case "line": - case "xline": - case "ray": - acc(g.a.x, g.a.y); - acc(g.b.x, g.b.y); - break; - case "polyline": - for (const p of g.pts) acc(p.x, p.y); - break; - case "rect": - case "image": - acc(g.min.x, g.min.y); - acc(g.max.x, g.max.y); - break; - case "circle": - case "arc": - acc(g.center.x - g.r, g.center.y - g.r); - acc(g.center.x + g.r, g.center.y + g.r); - break; - case "ellipse": { - // Präzise Bounding-Box unter Berücksichtigung der Drehung (rotation=0 - // beim heutigen Werkzeug, Feld existiert für spätere Quellen). - const c = Math.cos(g.rotation), s = Math.sin(g.rotation); - const hw = Math.hypot(g.rx * c, g.ry * s); - const hh = Math.hypot(g.rx * s, g.ry * c); - acc(g.center.x - hw, g.center.y - hh); - acc(g.center.x + hw, g.center.y + hh); - break; - } - case "bezier": - case "spline": - for (const p of g.pts) acc(p.x, p.y); - break; - case "dimension": { - for (const p of g.pts) acc(p.x, p.y); - if (g.pts.length >= 2) { - const a = g.pts[0], b = g.pts[g.pts.length - 1]; - const dx = b.x - a.x, dy = b.y - a.y; - const len = Math.hypot(dx, dy) || 1; - const nx = (-dy / len) * g.offset, ny = (dx / len) * g.offset; - for (const p of g.pts) acc(p.x + nx, p.y + ny); - } - break; - } - case "kote": - case "text": - case "block": - case "detailref": - case "pointmarker": - acc(g.at.x, g.at.y); - break; - case "scalebar": - acc(g.at.x, g.at.y); - acc(g.at.x + g.segmentLength * g.segments, g.at.y); - break; - } - if (!isFinite(minX)) return { minX: 0, minY: 0, maxX: 0, maxY: 0 }; - return { minX, minY, maxX, maxY }; -} - -/** Selektion für eine Wand ableiten (Farbe übersteuerbar, Strichstärke = Kategorie). */ -function wallSelection(project: Project, wall: Wall): Selection { - const cat = findCategory(project.layers, wall.categoryCode); - const color = wall.color ?? cat?.color ?? WALL_FALLBACK_COLOR; - // Effektive Strichstärke: expliziter Override zuerst, sonst die Kategorie - // (die Quelle "layer"/"object" macht heute keinen Unterschied, da Component - // keine eigene Strichstärke trägt — siehe resolveStrokeWeight). - const weightMm = wall.strokeWeight ?? cat?.lw ?? WALL_FALLBACK_MM; - const minX = Math.min(wall.start.x, wall.end.x); - const minY = Math.min(wall.start.y, wall.end.y); - const maxX = Math.max(wall.start.x, wall.end.x); - const maxY = Math.max(wall.start.y, wall.end.y); - // Wand-Attribute auflösen (Referenzlinie, Aufbau, Referenzgeschoss, UK/OK). - const wt = getWallType(project, wall); - const thickness = wallTypeThickness(wt); - // Effektive Vordergrund-/Hintergrund-/Schraffur-Vorschau fürs Attribut-Panel - // (Nutzer-Wunsch: immer den TATSÄCHLICHEN Wert sehen, nicht nur ein leeres - // Override-Feld) — dieselbe Resolve-Kette wie beim Rendern (resolveForeground - // & Co.), als Bauteil-Repräsentant die ÄUSSERSTE Schicht (wie `abbrevOf` - // unten). Bei mehrschichtigem Aufbau nur eine Annäherung (jede Schicht kann - // im Schnitt ihre EIGENE Bauteilfarbe zeigen) — für die Panel-Vorschau - // ausreichend, der Override selbst wirkt ohnehin einheitlich auf alle Schichten. - const outerComponent = getComponent(project, wt.layers[0]?.componentId); - const effectiveForeground = outerComponent - ? resolveForeground(outerComponent, wall.foreground, cat, wall.foregroundSource) - : wall.foreground; - const effectiveBackground = outerComponent - ? resolveBackground(outerComponent, wall.background, cat, wall.backgroundSource) - : wall.background; - const effectiveHatchId = resolveHatchId( - wall.hatchId, - wall.hatchSource, - cat, - outerComponent?.hatchId, - ); - const floor = project.drawingLevels.find((z) => z.id === wall.floorId); - const { zBottom, zTop } = wallVerticalExtent(project, wall); - const above = nextFloorAbove(project, wall); - // Volumen aus Achslänge × Gesamtdicke × Höhe, abzüglich der Öffnungen (jede - // Öffnung durchbricht die volle Wanddicke: Breite × Höhe × Dicke). - const length = Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y); - const wallHeight = Math.max(0, zTop - zBottom); - const grossVolume = length * thickness * wallHeight; - const openingVolume = (project.openings ?? []) - .filter((o) => o.hostWallId === wall.id) - .reduce((sum, o) => sum + o.width * o.height * thickness, 0); - const netVolume = Math.max(0, grossVolume - openingVolume); - // Interne Schichttrennlinien als wählbare Referenz: von aussen (Schicht 0) - // nach innen aufsummiert; der Achsversatz +n = halbe Dicke − Fugenlage. - const half = thickness / 2; - const layerBoundaries: WallInfo["layerBoundaries"] = []; - let cum = 0; - const abbrevOf = (componentId: string): string => { - const c = getComponent(project, componentId); - return c ? c.abbrev ?? c.name : "?"; - }; - for (let i = 0; i < wt.layers.length - 1; i++) { - cum += wt.layers[i].thickness; - layerBoundaries.push({ - offset: half - cum, - label: `${abbrevOf(wt.layers[i].componentId)}|${abbrevOf(wt.layers[i + 1].componentId)}`, - }); - } - const wallInfo: WallInfo = { - referenceLine: wall.referenceLine ?? "center", - referenceOffset: wall.referenceOffset, - layerBoundaries, - sliceTermination: wall.sliceTermination ?? "both", - wallTypeId: wall.wallTypeId, - thickness, - singleLayer: wt.layers.length <= 1, - wallTypes: project.wallTypes.map((t) => ({ - id: t.id, - name: t.name, - label: wallTypeLabel(t, project.components), - thickness: wallTypeThickness(t), - layerCount: t.layers.length, - })), - floorId: wall.floorId, - floorName: floor?.name ?? wall.floorId, - floors: project.drawingLevels - .filter((z) => z.kind === "floor") - .map((z) => ({ id: z.id, name: z.name })), - floorAbove: above, - bottom: wall.bottom, - top: wall.top, - zBottom, - zTop, - length, - grossVolume, - openingVolume, - netVolume, - }; - // bbox aus der Wandachse (start/end); die Schichtdicke bleibt unberücksichtigt, - // damit die Box der Achs-Geometrie folgt (genügt für die Paletten). - return { - kind: "wall", - id: wall.id, - categoryCode: wall.categoryCode, - floorId: wall.floorId, - color, - colorPenId: wall.colorPenId, - weightMm, - fillHatchId: wall.hatchId, - fillColor: undefined, - foreground: wall.foreground, - foregroundPenId: wall.foregroundPenId, - background: wall.background, - backgroundPenId: wall.backgroundPenId, - foregroundSource: wall.foregroundSource, - backgroundSource: wall.backgroundSource, - effectiveForeground, - effectiveBackground, - effectiveHatchId, - strokeWeightOverride: wall.strokeWeight, - strokeWeightSource: wall.strokeWeightSource, - hatchSource: wall.hatchSource, - closed: undefined, - bbox: { minX, minY, maxX, maxY }, - wall: wallInfo, - }; -} - -/** Selektion für eine Decke ableiten (Farbe übersteuerbar, Strichstärke = Kategorie). */ -function ceilingSelection(project: Project, ceiling: Ceiling): Selection { - const cat = findCategory(project.layers, ceiling.categoryCode); - const color = ceiling.color ?? cat?.color ?? WALL_FALLBACK_COLOR; - const weightMm = ceiling.strokeWeight ?? cat?.lw ?? WALL_FALLBACK_MM; - const box = outlineBBox(ceiling.outline); - const wt = getCeilingType(project, ceiling); - const thickness = ceilingThickness(project, ceiling); - // Effektive Vordergrund-/Hintergrund-/Schraffur-Vorschau — s. Kommentar in - // wallSelection (dieselbe Kette, äusserste Schicht als Bauteil-Repräsentant). - const outerComponent = getComponent(project, wt.layers[0]?.componentId); - const effectiveForeground = outerComponent - ? resolveForeground(outerComponent, ceiling.foreground, cat, ceiling.foregroundSource) - : ceiling.foreground; - const effectiveBackground = outerComponent - ? resolveBackground(outerComponent, ceiling.background, cat, ceiling.backgroundSource) - : ceiling.background; - const effectiveHatchId = resolveHatchId( - ceiling.hatchId, - ceiling.hatchSource, - cat, - outerComponent?.hatchId, - ); - const floor = project.drawingLevels.find((z) => z.id === ceiling.floorId); - const { zBottom, zTop } = ceilingVerticalExtent(project, ceiling); - const ceilingInfo: CeilingInfo = { - typeId: ceiling.ceilingTypeId ?? ceiling.wallTypeId, - thickness, - singleLayer: wt.layers.length <= 1, - area: ceilingArea(ceiling.outline), - volume: ceilingArea(ceiling.outline) * thickness, - ceilingTypes: (project.ceilingTypes ?? []).map((t) => ({ - id: t.id, - name: t.name, - label: wallTypeLabel(t, project.components), - thickness: wallTypeThickness(t), - layerCount: t.layers.length, - })), - floorId: ceiling.floorId, - floorName: floor?.name ?? ceiling.floorId, - floors: project.drawingLevels - .filter((z) => z.kind === "floor") - .map((z) => ({ id: z.id, name: z.name })), - top: ceiling.top, - bottom: ceiling.bottom, - zBottom, - zTop, - // Aussparungen als anzeigefertige BBox-Masse (Breite × Tiefe je Loch). - openings: (ceiling.openings ?? []).map((hole) => { - const bb = outlineBBox(hole); - return { width: bb.maxX - bb.minX, depth: bb.maxY - bb.minY }; - }), - }; - return { - kind: "ceiling", - id: ceiling.id, - categoryCode: ceiling.categoryCode, - floorId: ceiling.floorId, - color, - colorPenId: ceiling.colorPenId, - weightMm, - fillHatchId: ceiling.hatchId, - fillColor: undefined, - foreground: ceiling.foreground, - foregroundPenId: ceiling.foregroundPenId, - background: ceiling.background, - backgroundPenId: ceiling.backgroundPenId, - foregroundSource: ceiling.foregroundSource, - backgroundSource: ceiling.backgroundSource, - effectiveForeground, - effectiveBackground, - effectiveHatchId, - strokeWeightOverride: ceiling.strokeWeight, - strokeWeightSource: ceiling.strokeWeightSource, - hatchSource: ceiling.hatchSource, - closed: true, - bbox: { minX: box.minX, minY: box.minY, maxX: box.maxX, maxY: box.maxY }, - ceiling: ceilingInfo, - }; -} - -/** Selektion für ein Dach ableiten (Farbe übersteuerbar, Strichstärke = Kategorie). */ -function roofSelection(project: Project, roof: Roof): Selection { - const cat = findCategory(project.layers, roof.categoryCode); - const color = roof.color ?? cat?.color ?? WALL_FALLBACK_COLOR; - const weightMm = cat?.lw ?? WALL_FALLBACK_MM; - const bb = roofBBox(roof.outline); - const eavesZ = roofBaseElevation(project, roof); - const g = roofGeometry(roof, eavesZ); - const footprintArea = Math.abs(bb.x1 - bb.x0) * Math.abs(bb.y1 - bb.y0); - const roofInfo: RoofInfo = { - shape: roof.shape, - pitchDeg: roof.pitchDeg, - pitchUpperDeg: roof.pitchUpperDeg, - roofTypeId: roof.roofTypeId, - mansardType: roof.mansardType, - mansardKneeRatio: roof.mansardKneeRatio, - halfHipRatio: roof.halfHipRatio, - overhang: roof.overhang, - overhangGable: roof.overhangGable, - ridgeAxis: roof.ridgeAxis, - thickness: roof.thickness, - baseElevation: eavesZ, - ridgeHeight: g.ridgeHeight, - footprintArea, - width: Math.abs(bb.x1 - bb.x0), - depth: Math.abs(bb.y1 - bb.y0), - minX: bb.x0, - minY: bb.y0, - edges: roofEdgeList(roof), - holes: (roof.holes ?? []).map((h) => ({ area: Math.abs(polygonArea(h)), points: h.length })), - hasEdgePitch: roof.edgePitchDeg !== undefined, - }; - return { - kind: "roof", - id: roof.id, - categoryCode: roof.categoryCode, - floorId: roof.floorId, - color, - colorPenId: roof.colorPenId, - weightMm, - closed: true, - bbox: { minX: bb.x0, minY: bb.y0, maxX: bb.x1, maxY: bb.y1 }, - roof: roofInfo, - }; -} - -/** Selektion für eine Öffnung ableiten (Farbe übersteuerbar, Strichstärke = Kategorie). */ -function openingSelection(project: Project, o: Opening): Selection { - const cat = findCategory(project.layers, o.categoryCode); - const color = o.color ?? cat?.color ?? WALL_FALLBACK_COLOR; - const weightMm = cat?.lw ?? WALL_FALLBACK_MM; - const wall = project.walls.find((w) => w.id === o.hostWallId); - const floor = wall - ? project.drawingLevels.find((z) => z.id === wall.floorId) - : undefined; - // Bounding-Box aus dem Lücken-Quad (volle Wanddicke); Fallback: leere Box. - const quad = wall ? openingGapQuad(project, wall, o) : null; - let minX = Infinity, - minY = Infinity, - maxX = -Infinity, - maxY = -Infinity; - for (const p of quad ?? []) { - minX = Math.min(minX, p.x); - minY = Math.min(minY, p.y); - maxX = Math.max(maxX, p.x); - maxY = Math.max(maxY, p.y); - } - if (!isFinite(minX)) { - minX = minY = maxX = maxY = 0; - } - const ext = wall - ? openingVerticalExtent(project, wall, o) - : { zBottom: 0, zTop: o.height }; - const openingInfo: OpeningInfo = { - id: o.id, - kind: o.kind, - hostWallId: o.hostWallId, - hostWallName: floor ? `${floor.name}` : o.hostWallId, - position: o.position, - width: o.width, - height: o.height, - sillHeight: o.sillHeight, - hinge: o.hinge, - swing: o.swing, - swingAngle: o.swingAngle, - openingDir: o.openingDir, - wingCount: o.wingCount, - doorType: o.doorType, - lintelLines: o.lintelLines, - typeId: o.typeId, - detailLevel: o.detailLevel, - zBottom: ext.zBottom, - zTop: ext.zTop, - frameLine: o.frameLine, - frameViewLine: o.frameViewLine, - sashLine: o.sashLine, - sillLineStyle: o.sillLineStyle, - }; - return { - kind: "opening", - id: o.id, - categoryCode: o.categoryCode, - color, - colorPenId: o.colorPenId, - weightMm, - fillHatchId: undefined, - fillColor: undefined, - closed: undefined, - bbox: { minX, minY, maxX, maxY }, - opening: openingInfo, - }; -} - -/** Selektion für eine Treppe ableiten (Farbe übersteuerbar, Strichstärke = Kategorie). */ -function stairSelection(project: Project, s: Stair): Selection { - const cat = findCategory(project.layers, s.categoryCode); - const color = s.color ?? cat?.color ?? WALL_FALLBACK_COLOR; - const weightMm = cat?.lw ?? WALL_FALLBACK_MM; - const { zBottom, zTop } = stairVerticalExtent(project, s); - const totalRise = zTop - zBottom; - const geo = stairGeometry(s, totalRise); - const box = stairBBox(geo); - const floor = project.drawingLevels.find((z) => z.id === s.floorId); - const stairInfo: StairInfo = { - shape: s.shape, - width: s.width, - stepCount: s.stepCount, - totalRise, - riserHeight: geo.riserHeight, - treadDepth: geo.treadDepth, - up: s.up !== false, - arrowStyle: s.arrowStyle, - referenz: s.referenz, - typeId: s.typeId, - floorId: s.floorId, - floorName: floor?.name ?? s.floorId, - zBottom, - zTop, - }; - return { - kind: "stair", - id: s.id, - categoryCode: s.categoryCode, - floorId: s.floorId, - color, - colorPenId: s.colorPenId, - weightMm, - fillHatchId: undefined, - fillColor: undefined, - closed: undefined, - bbox: { minX: box.minX, minY: box.minY, maxX: box.maxX, maxY: box.maxY }, - stair: stairInfo, - }; -} - -/** Selektion für einen Raum ableiten (Fläche/Umfang aus dem Umriss abgeleitet). */ -function roomSelection(project: Project, r: Room): Selection { - const cat = findCategory(project.layers, r.categoryCode); - const color = r.color ?? cat?.color ?? WALL_FALLBACK_COLOR; - const weightMm = cat?.lw ?? WALL_FALLBACK_MM; - const res = evaluateRoom(r.boundary, r.siaCategory); - const floor = project.drawingLevels.find((z) => z.id === r.floorId); - let minX = Infinity, - minY = Infinity, - maxX = -Infinity, - maxY = -Infinity; - for (const p of r.boundary) { - minX = Math.min(minX, p.x); - minY = Math.min(minY, p.y); - maxX = Math.max(maxX, p.x); - maxY = Math.max(maxY, p.y); - } - if (!isFinite(minX)) minX = minY = maxX = maxY = 0; - const roomInfo: RoomInfo = { - name: r.name, - siaCategory: r.siaCategory, - area: res.netArea, - perimeter: res.perimeter, - floorId: r.floorId, - floorName: floor?.name ?? r.floorId, - }; - return { - kind: "room", - id: r.id, - categoryCode: r.categoryCode, - floorId: r.floorId, - color, - colorPenId: r.colorPenId, - weightMm, - fillHatchId: undefined, - fillColor: undefined, - closed: true, - bbox: { minX, minY, maxX, maxY }, - room: roomInfo, - }; -} - -/** Auswahl-Farbe der Extrusions-Footprints (identisch zum Grundriss-Umriss/3D-Orange). */ -const EXTRUSION_COLOR = "#d98c40"; - -/** Selektion für einen extrudierten Körper ableiten (truck-Integration). */ -function extrudedSolidSelection(project: Project, s: ExtrudedSolid): Selection { - const floor = project.drawingLevels.find((z) => z.id === s.levelId); - let minX = Infinity, - minY = Infinity, - maxX = -Infinity, - maxY = -Infinity; - for (const p of s.points) { - minX = Math.min(minX, p.x); - minY = Math.min(minY, p.y); - maxX = Math.max(maxX, p.x); - maxY = Math.max(maxY, p.y); - } - if (!isFinite(minX)) minX = minY = maxX = maxY = 0; - const info: ExtrudedSolidInfo = { - height: s.height, - taper: s.taper ?? 0, - cornerRadius: s.cornerRadius ?? 0, - chamfer: s.chamfer ?? 0, - ...(s.brep ? { brepLabel: s.brep.label ?? "B-Rep" } : {}), - area: polygonArea(s.points), - spec: s.operation === "subtract" ? null : extrudedSolidSpec(s, floor?.baseElevation ?? 0), - subtract: s.operation === "subtract", - canSubtract: !s.brep && (s.taper ?? 0) < 1e-6, - baseOffset: s.baseOffset ?? 0, - floorId: s.levelId, - floorName: floor?.name ?? s.levelId, - }; - return { - kind: "extrudedSolid", - id: s.id, - categoryCode: "", - floorId: s.levelId, - color: EXTRUSION_COLOR, - weightMm: WALL_FALLBACK_MM, - fillHatchId: null, - fillColor: null, - closed: true, - bbox: { minX, minY, maxX, maxY }, - extrudedSolid: info, - }; -} - -/** Umriss-/Auswahlfarbe der Stützen-Poché (neutrales Tragwerks-Grau). */ -const COLUMN_COLOR = "#3a3f47"; - -/** Selektion für eine Stütze (Column) ableiten. */ -function columnSelection(project: Project, col: Column): Selection { - const floor = project.drawingLevels.find((z) => z.id === col.floorId); - const category = findCategory(project.layers, col.categoryCode); - const pts = columnFootprint(col); - let minX = Infinity, - minY = Infinity, - maxX = -Infinity, - maxY = -Infinity; - for (const p of pts) { - minX = Math.min(minX, p.x); - minY = Math.min(minY, p.y); - maxX = Math.max(maxX, p.x); - maxY = Math.max(maxY, p.y); - } - if (!isFinite(minX)) minX = minY = maxX = maxY = 0; - const { zBottom, zTop } = columnVerticalExtent(project, col); - const info: ColumnInfo = { - profile: col.profile, - height: col.height, - rotationDeg: ((col.rotation ?? 0) * 180) / Math.PI, - floorId: col.floorId, - floorName: floor?.name ?? col.floorId, - zBottom, - zTop, - }; - // Effektive Vordergrund-/Hintergrund-/Schraffur-/Strichstärke-Vorschau — s. - // Kommentar in wallSelection (dieselbe Kette, das zugewiesene Bauteil als - // Repräsentant statt der äussersten Schicht, da Column nur EIN componentId - // trägt statt eines geschichteten Aufbaus). - // `getComponent` wirft bei unbekannter ID (z. B. gelöschtes Bauteil) — die - // Panel-Vorschau soll dabei nicht abstürzen (analog dem try/catch in - // structures.ts addColumnPoche), einfach auf "kein Bauteil" zurückfallen. - const comp = col.componentId - ? project.components.find((c) => c.id === col.componentId) - : undefined; - const effectiveForeground = comp - ? resolveForeground(comp, col.foreground, category, col.foregroundSource) - : col.foreground; - const effectiveBackground = comp - ? resolveBackground(comp, col.background, category, col.backgroundSource) - : col.background; - const effectiveHatchId = resolveHatchId(col.hatchId, col.hatchSource, category, comp?.hatchId); - const weightMm = resolveStrokeWeight(col.strokeWeight, col.strokeWeightSource, category, WALL_FALLBACK_MM); - return { - kind: "column", - id: col.id, - categoryCode: col.categoryCode, - floorId: col.floorId, - color: col.color ?? category?.color ?? COLUMN_COLOR, - colorPenId: col.colorPenId, - weightMm, - fillHatchId: col.hatchId, - foreground: col.foreground, - foregroundPenId: col.foregroundPenId, - background: col.background, - backgroundPenId: col.backgroundPenId, - foregroundSource: col.foregroundSource, - backgroundSource: col.backgroundSource, - effectiveForeground, - effectiveBackground, - effectiveHatchId, - strokeWeightOverride: col.strokeWeight, - strokeWeightSource: col.strokeWeightSource, - hatchSource: col.hatchSource, - bbox: { minX, minY, maxX, maxY }, - column: info, - }; -} - -/** - * Selektion für ein Kontext-Objekt (importiertes Mesh/Terrain/Konturen-Satz) - * ableiten. Bbox aus den rohen x/y-Koordinaten (Meshes: flaches [x,y,z…]- - * Array, nur x/y je Vertex; Konturen: `pts` je Kontur) — die Höhe (z) bleibt - * unberücksichtigt (2D-Bbox wie bei allen anderen Elementarten). `lv95Center` - * nur, wenn `project.geoAnchor` gesetzt ist (sonst kein Rückrechnungs-Bezug). - */ -function contextObjectSelection(project: Project, obj: ContextObject): Selection { - let minX = Infinity, - minY = Infinity, - maxX = -Infinity, - maxY = -Infinity; - const consider = (x: number, y: number) => { - minX = Math.min(minX, x); - minY = Math.min(minY, y); - maxX = Math.max(maxX, x); - maxY = Math.max(maxY, y); - }; - if (obj.type === "contourSet") { - for (const c of obj.contours) for (const p of c.pts) consider(p.x, p.y); - } else if (obj.type === "image") { - consider(obj.min.x, obj.min.y); - consider(obj.max.x, obj.max.y); - } else { - const pos = obj.positions; - for (let i = 0; i + 2 < pos.length; i += 3) consider(pos[i], pos[i + 1]); - } - if (!isFinite(minX)) minX = minY = maxX = maxY = 0; - const anchor = project.geoAnchor; - const lv95Center = anchor - ? localToLv95( - (minX + maxX) / 2, - (minY + maxY) / 2, - { e: anchor.lv95.e - anchor.model.x, n: anchor.lv95.n - anchor.model.y }, - ) - : undefined; - const isImage = obj.type === "image"; - return { - kind: "contextObject", - id: obj.id, - categoryCode: "", - color: "#888888", - weightMm: WALL_FALLBACK_MM, - bbox: { minX, minY, maxX, maxY }, - contextObject: { objType: obj.type, lv95Center }, - // Deckkraft + Bildkorrektur nur bei Luftbildern (`ContextImage`) — steuert - // die (wiederverwendete) Deckkraft-Zeile + die neue Bildkorrektur-Sektion - // im Attribute-Panel, s. `AttributesPanel.tsx`. - isImage, - opacity: isImage ? ((obj as ContextImage).opacity ?? 1) : undefined, - imageFilters: isImage ? (obj as ContextImage).filters : undefined, - }; -} - -/** Selektion für ein 2D-Zeichenelement ableiten (gleiche Auflösung wie generatePlan). */ -function drawingSelection(project: Project, d: Drawing2D): Selection { - const ls = d.lineStyleId - ? project.lineStyles.find((l) => l.id === d.lineStyleId) - : undefined; - const cat = findCategory(project.layers, d.categoryCode); - const color = d.color ?? ls?.color ?? cat?.color ?? DRAW_FALLBACK_COLOR; - // Effektive Strichstärke, dieselbe Kette wie der Plan (`plan/drawings.rs`) - // (resolveStrokeWeight): Override zuerst, Source ≠ "object" (also "layer" - // ODER fehlend, s. AttributeSource-Default) erzwingt die Kategorie (umgeht - // das LineStyle-Gewicht), sonst die LineStyle-/Kategorie-Kette. - const weightMm = - d.weightMm ?? - (d.strokeWeightSource !== "object" ? cat?.lw : undefined) ?? - ls?.weight ?? - cat?.lw ?? - WALL_FALLBACK_MM; - const closed = isClosedGeom(d.geom); - // Effektive Vordergrund-/Hintergrund-/Schraffur-Vorschau — s. Kommentar in - // wallSelection. Ein Drawing2D hat KEIN eigenes Bauteil (daher auch keine - // „Nach Bauteil"-Option im Panel, s. AttributesPanel.tsx) — als Platzhalter - // ein leeres Bauteil, dessen foreground/background/hatchId immer fehlen, - // sodass die Kette bei einem (aus Alt-Daten) expliziten `source:"object"` - // korrekt auf „kein Wert" statt einer erfundenen Bauteilfarbe fällt. Anders - // als bei Wand/Decke (Default „Nach Bauteil") gilt bei Drawing2D „Nach - // Ebene" als Default — daher hier explizit `?? "layer"` VOR dem Resolver - // (der selbst weiterhin generisch „Nach Bauteil" als Default kennt). - const noComponent = { id: "", name: "", color, hatchId: "", joinPriority: 0 }; - const effectiveForeground = closed - ? resolveForeground(noComponent, d.foreground, cat, d.foregroundSource ?? "layer") - : undefined; - const effectiveBackground = closed - ? resolveBackground(noComponent, d.background, cat, d.backgroundSource ?? "layer") - : undefined; - const effectiveHatchId = closed - ? resolveHatchId(d.hatchId, d.hatchSource ?? "layer", cat, undefined) - : null; - return { - kind: "drawing2d", - id: d.id, - categoryCode: d.categoryCode, - floorId: d.levelId, - color, - colorPenId: d.colorPenId, - weightMm, - fillHatchId: closed ? d.hatchId ?? null : null, - fillColor: closed ? d.fillColor ?? null : null, - foreground: closed ? d.foreground : undefined, - foregroundPenId: closed ? d.foregroundPenId : undefined, - background: closed ? d.background : undefined, - backgroundPenId: closed ? d.backgroundPenId : undefined, - foregroundSource: closed ? d.foregroundSource : undefined, - backgroundSource: closed ? d.backgroundSource : undefined, - effectiveForeground, - effectiveBackground, - effectiveHatchId, - strokeWeightOverride: d.weightMm, - strokeWeightSource: d.strokeWeightSource, - hatchSource: closed ? d.hatchSource : undefined, - closed, - isImage: d.geom.shape === "image", - // Deckkraft: beim BILD die eigene Bild-Deckkraft, sonst die - // Objekt-Transparenz des Elements (`Drawing2D.opacity`). - opacity: d.geom.shape === "image" ? (d.geom.opacity ?? 1) : d.opacity, - bbox: geomBBox(d.geom), - detailRef: - d.geom.shape === "detailref" - ? { - label: d.geom.label, - sheetLayoutId: d.geom.sheetLayoutId, - sheetLabel: d.geom.sheetLabel, - availableLayouts: (project.layouts ?? []).map((l) => ({ id: l.id, name: l.name })), - } - : undefined, - }; -} +/** Meldungen, mit denen die Objekt-Info wie bisher abbricht (unbekannter Typ/Bauteil). */ +const THROWN = /^Unbekannte[rs]? /; /** * Leitet den Selektions-Kontrakt für das ERSTE selektierte Element ab. * Drawing-Auswahl und Wand-Auswahl schließen sich aus; bei Drawing-Auswahl * hat diese Vorrang. Liefert `null`, wenn nichts (oder kein auffindbares - * Element) selektiert ist. + * Element) selektiert ist. Ein unbekannter Wand-/Deckentyp oder ein fehlendes + * Bauteil wirft wie bisher; ein Element, das das Kern-Modell nicht lesen kann, + * ergibt `null` (mit Warnung). */ export function deriveSelection( project: Project, @@ -1303,46 +536,49 @@ export function deriveSelection( selectedRoofId: string | null = null, selectedContextObjectId: string | null = null, ): Selection | null { - if (selectedContextObjectId) { - const o = (project.context ?? []).find((x) => x.id === selectedContextObjectId); - if (o) return contextObjectSelection(project, o); + const args = { + wallIds: selectedWallIds, + drawingId: selectedDrawingId, + ceilingId: selectedCeilingId, + openingId: selectedOpeningId, + stairId: selectedStairId, + roomId: selectedRoomId, + extrudedSolidId: selectedExtrudedSolidId, + columnId: selectedColumnId, + roofId: selectedRoofId, + contextObjectId: selectedContextObjectId, + // Lage in der Leseansicht (= Reihenfolge im Dokument): erspart dem Kern die lineare Suche. + at: {} as Record, + }; + const P = project as unknown as Record; + const hint = (list: string, id: string | null | undefined) => { + if (!id) return; + const i = (P[list] ?? []).findIndex((x) => x.id === id); + if (i >= 0) args.at[list] = i; + }; + hint("context", selectedContextObjectId); + hint("drawings2d", selectedDrawingId); + hint("extrudedSolids", selectedExtrudedSolidId); + hint("columns", selectedColumnId); + hint("openings", selectedOpeningId); + hint("walls", selectedWallIds[0]); + hint("ceilings", selectedCeilingId); + hint("roofs", selectedRoofId); + hint("stairs", selectedStairId); + hint("rooms", selectedRoomId); + let sel: Selection | null; + try { + sel = documentFor(project).queryRootMarked("selectionInfo", JSON.stringify(args)); + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + if (THROWN.test(msg)) throw new Error(msg); + console.warn("Objekt-Info:", msg); + return null; } - if (selectedDrawingId) { - const d = project.drawings2d.find((x) => x.id === selectedDrawingId); - return d ? drawingSelection(project, d) : null; + if (sel?.extrudedSolid) { + const s = (project.extrudedSolids ?? []).find((x) => x.id === sel!.id); + const floor = s && project.drawingLevels.find((z) => z.id === s.levelId); + sel.extrudedSolid.spec = s && s.operation !== "subtract" ? extrudedSolidSpec(s, floor?.baseElevation ?? 0) : null; } - if (selectedExtrudedSolidId) { - const s = (project.extrudedSolids ?? []).find((x) => x.id === selectedExtrudedSolidId); - return s ? extrudedSolidSelection(project, s) : null; - } - if (selectedColumnId) { - const c = (project.columns ?? []).find((x) => x.id === selectedColumnId); - return c ? columnSelection(project, c) : null; - } - if (selectedOpeningId) { - const o = (project.openings ?? []).find((x) => x.id === selectedOpeningId); - if (o) return openingSelection(project, o); - } - const wallId = selectedWallIds[0]; - if (wallId) { - const w = project.walls.find((x) => x.id === wallId); - return w ? wallSelection(project, w) : null; - } - if (selectedCeilingId) { - const c = (project.ceilings ?? []).find((x) => x.id === selectedCeilingId); - return c ? ceilingSelection(project, c) : null; - } - if (selectedRoofId) { - const r = (project.roofs ?? []).find((x) => x.id === selectedRoofId); - return r ? roofSelection(project, r) : null; - } - if (selectedStairId) { - const s = (project.stairs ?? []).find((x) => x.id === selectedStairId); - return s ? stairSelection(project, s) : null; - } - if (selectedRoomId) { - const r = (project.rooms ?? []).find((x) => x.id === selectedRoomId); - return r ? roomSelection(project, r) : null; - } - return null; + return sel; } From 0c15c0ede39398c2157c327b7b8f9987cb88872a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 10:26:42 +0000 Subject: [PATCH 3/3] =?UTF-8?q?[K4]=20H=C3=B6hen=20der=203D-Griffe=20im=20?= =?UTF-8?q?Kern,=20tote=20Geometrie-Helfer=20gel=C3=B6scht?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Die 3D-Griffe (Griff-Lagen, Arbeitsebene) holen UK/OK von Wänden und Decken über die Wurzel-Abfrage `verticalExtents` (selection_info.rs, Fassade in geometry/grips.ts). Gelöscht, weil ohne Aufrufer: lineIntersect, clippedBand, wallBand, stairVerticalExtent, nextFloorAbove, openingGapQuad, roofBBox, stairBBox (+ Bindung stair_bbox_flat), outlineBBox, localToLv95, roofEdgeList. Die vertikalen Ausdehnungen in TS bleiben nur für die Plan-Ableitung. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- TODO.md | 14 +++++ src-tauri/core/src/queries.rs | 5 ++ src-tauri/core/src/selection_info.rs | 48 ++++++++++++++++-- src-tauri/core/src/web/stair.rs | 6 --- src/core/document.ts | 2 +- src/core/extra.ts | 2 + src/core/index.ts | 5 -- src/geometry/ceiling.ts | 24 --------- src/geometry/grips.ts | 25 ++++++++- src/geometry/opening.ts | 24 +-------- src/geometry/roof.test.ts | 15 +++--- src/geometry/roof.ts | 15 ------ src/geometry/roofEdges.test.ts | 26 ++-------- src/geometry/roofEdges.ts | 44 +--------------- src/geometry/stair.test.ts | 11 +--- src/geometry/stair.ts | 16 +----- src/io/lv95.ts | 9 ---- src/model/geometry.ts | 76 +--------------------------- src/model/wall.ts | 49 +----------------- src/state/selectionInfo.test.ts | 28 +++++++++- src/viewport/Wasm3DViewport.tsx | 22 ++++---- 21 files changed, 149 insertions(+), 317 deletions(-) diff --git a/TODO.md b/TODO.md index c166349e..465c9306 100644 --- a/TODO.md +++ b/TODO.md @@ -520,6 +520,20 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern 96–138 µs, Zeichnung (Position 10 000) 150–300 → 160–390 µs, Dach 5 → 30–60 µs (TS merkte sich die Dachgeometrie je Objekt; im Kern ist sie für die letzten 16 Dächer gemerkt, der Rest ist die JSON-Übergabe), Griff-Schritt samt Objekt-Info 1,6–2,6 ms → 1,5–2,4 ms; je Darstellung also ~0,05 ms mehr. Nicht in der Tauri-App geprüft. + **Höhen und Wand-Bänder (29.10.)** — zu (5)/(6): die 3D-Griffe (`Wasm3DViewport`: Griff-Lagen, Arbeitsebene beim Ziehen) + holen UK/OK von Wänden und Decken über die Wurzel-Abfrage `verticalExtents` (`selection_info.rs`, dieselbe Rechnung wie die + Objekt-Info; Fassade `verticalExtents` in `geometry/grips.ts`, ganze Elemente, auch gerade gezogene Fassungen). Gleichheit + (einmalig, Test gelöscht): 480 000 Höhen über 20 000 Zufallsfälle (Bindungen UK/OK, fehlende Geschosse/Typen, NaN/±∞/null + in den Elementen) gleich `wallVerticalExtent`/`ceilingVerticalExtent` (−0 kommt als 0). Gelöscht, weil ohne Aufrufer: + `lineIntersect`/`clippedBand`/`Line`/`wallBand` (`model/geometry.ts`, `wallCorners` rechnet das Band selbst), + `stairVerticalExtent`/`nextFloorAbove` (`model/wall.ts`), `openingGapQuad`, `roofBBox`, `stairBBox` samt Bindung + `stair_bbox_flat`, `outlineBBox`, `localToLv95`, `roofEdgeList` (Kantenliste nur noch im Kern; Test über `deriveSelection`; + `setRoofEdge` zählt die Kanten direkt). Bleibt in TS: `wallVerticalExtent`/`ceilingVerticalExtent`/`columnVerticalExtent`/ + `openingVerticalExtent` nur noch für die Plan-Ableitung (`toSection`, `voids`, `sectionOpenings`, `toElevation` — fallen mit + deren Port; im Kern gibt es die Regeln doppelt: roh in `selection_info.rs`, typisiert in `model/helpers.rs`, beim Plan-Port + zusammenlegen); `wallCorners` (Plan-Treffer `planHitTest`, Werkzeug-Vorschau, Griff-Vorschau, `voids`, STEP-Export — ein + Kern-Aufruf je Wand wäre teurer als die vier Punkte) und `wallReferenceOffset` (Fang, `geometry/opening.ts`). Nicht in + der Tauri-App geprüft (3D-Griffe nur über e2e im Browser). - ◐ **S4 Typen aus Rust**: `types.ts` wird aus den Rust-Strukturen erzeugt (ts-rs); Datei-I/O (`projectFormat`, Migration, IFC/DXF/ STEP-Ex- und -Import) im Kern. **Typen (28.10.):** Das Rust-Modell (`core/src/model/generated.rs`, `manual.rs`) ist die Quelle; ts-rs 12 (MIT, nur diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs index d956ec1f..1931ea89 100644 --- a/src-tauri/core/src/queries.rs +++ b/src-tauri/core/src/queries.rs @@ -114,6 +114,11 @@ pub fn run_root(root: &serde_json::Map, name: &str, t let ids: Vec = serde_json::from_str(text).map_err(|e| format!("drawingBBoxes: {e}"))?; Ok(crate::selection_info::drawing_bboxes(root, &ids).into_string()) } + // UK/OK von Wänden und Decken (3D-Griffe): `text` = `{walls: […], ceilings: […]}` (ganze Elemente). + "verticalExtents" => { + let a: crate::selection_info::ExtentArgs = serde_json::from_str(text).map_err(|e| format!("verticalExtents: {e}"))?; + Ok(crate::selection_info::vertical_extents(root, &a).into_string()) + } _ => Err(format!("Unbekannte Wurzel-Abfrage: {name}")), } } diff --git a/src-tauri/core/src/selection_info.rs b/src-tauri/core/src/selection_info.rs index 170e07ae..b617198c 100644 --- a/src-tauri/core/src/selection_info.rs +++ b/src-tauri/core/src/selection_info.rs @@ -337,6 +337,35 @@ fn vertical_extent(root: &Map, el: &Value) -> (f64, f64) { (zb, zt) } +/// (UK, OK) einer Decke (`ceilingVerticalExtent`): OK aus `top` sonst Geschoss-Oberkante (Basis + Höhe), UK aus +/// `bottom` sonst OK − `thickness` (die Decke wächst nach unten). +fn ceiling_extent(root: &Map, c: &Value, thickness: f64) -> (f64, f64) { + let floor_top = level(root, field(c, "floorId")).map_or(0.0, |f| num_or(field(f, "baseElevation"), 0.0) + num_or(field(f, "floorHeight"), 0.0)); + let zt = anchor(root, field(c, "top")).unwrap_or(floor_top); + let zb = anchor(root, field(c, "bottom")).unwrap_or(zt - thickness); + (zb, zt) +} + +/// Anfrage `verticalExtents`: Wände und Decken als ganze Elemente (die 3D-Griffe zeigen auch gerade gezogene, +/// noch nicht übernommene Fassungen). +#[derive(serde::Deserialize, Default)] +#[serde(default)] +pub struct ExtentArgs { + pub walls: Vec, + pub ceilings: Vec, +} + +/// (UK, OK) der Wände, dann der Decken, flach: `[zb, zt, zb, zt, …]`. +pub fn vertical_extents(root: &Map, a: &ExtentArgs) -> J { + let walls = a.walls.iter().map(|w| vertical_extent(root, w)); + let ceilings = a.ceilings.iter().map(|c| ceiling_extent(root, c, ceiling_thickness(root, c))); + J::arr(walls.chain(ceilings).flat_map(|(zb, zt)| [zb, zt]).map(|x| { + let mut out = Vec::new(); + js_num(x).emit(&mut out); + J(out) + })) +} + /// Aufbau-Typ einer Decke (`getCeilingType`): eigener Deckentyp, sonst Alt-Wandtyp, sonst Fehler. fn ceiling_type<'a>(root: &'a Map, c: &Value) -> Result<&'a Value, String> { if truthy(field(c, "ceilingTypeId")) { @@ -546,9 +575,7 @@ fn ceiling_selection(root: &Map, c: &Value) -> Result let outer = component(root, arr(field(wt, "layers")).first().and_then(|l| field(l, "componentId")))?; let (fg, bg, hatch) = effective(c, Some(outer), cat); let floor = level(root, field(c, "floorId")); - let floor_top = floor.map_or(0.0, |f| num_or(field(f, "baseElevation"), 0.0) + num_or(field(f, "floorHeight"), 0.0)); - let zt = anchor(root, field(c, "top")).unwrap_or(floor_top); - let zb = anchor(root, field(c, "bottom")).unwrap_or(zt - thickness); + let (zb, zt) = ceiling_extent(root, c, thickness); let area = ceiling_area(field(c, "outline")); let openings: Vec = arr(field(c, "openings")) .iter() @@ -1215,6 +1242,21 @@ mod tests { assert_eq!(sel(&bad, json!({"wallIds": ["w"]})).unwrap_err(), "Unbekannter Wandtyp: x"); } + #[test] + fn hoehen_von_waenden_und_decken() { + let r = root(json!({ + "wallTypes": [{"id": "t", "layers": [{"componentId": "a", "thickness": 0.3}]}], + "drawingLevels": [{"id": "eg", "kind": "floor", "baseElevation": 1, "floorHeight": 3}, {"id": "og", "kind": "floor", "baseElevation": 4}], + })); + let a: ExtentArgs = serde_json::from_value(json!({ + "walls": [{"floorId": "eg", "height": 2.5}, {"floorId": "eg", "height": 2.5, "top": {"mode": "floor", "floorId": "og", "offset": -0.2}}, {"floorId": "x"}], + "ceilings": [{"floorId": "eg", "wallTypeId": "t"}, {"floorId": "eg", "thickness": 0.25, "bottom": {"mode": "custom", "z": 3}}, {"floorId": "x", "ceilingTypeId": "fehlt"}], + })) + .unwrap(); + let v: Value = serde_json::from_str(&vertical_extents(&r, &a).into_string()).unwrap(); + assert_eq!(v, json!([1, 3.5, 1, 3.8, 0, "\u{1}NaN", 3.7, 4, 3, 4, -0.2, 0])); + } + #[test] fn typ_beschriftung_wie_ts() { let r = root(json!({"components": [{"id": "a", "abbrev": "BET"}, {"id": "b", "abbrev": "GKB"}]})); diff --git a/src-tauri/core/src/web/stair.rs b/src-tauri/core/src/web/stair.rs index 62bebf44..0fa6e15b 100644 --- a/src-tauri/core/src/web/stair.rs +++ b/src-tauri/core/src/web/stair.rs @@ -21,12 +21,6 @@ pub fn stair_cut_flat(geometry: &[f64], cut_rise: f64) -> Vec { s::cut(geometry, cut_rise) } -/// `[minX, minY, maxX, maxY]` aller Tritte + Podest. -#[wasm_bindgen] -pub fn stair_bbox_flat(geometry: &[f64]) -> Vec { - s::bbox(geometry) -} - /// Vorgabe-Stufenzahl aus Steighöhe und Lauflänge. #[wasm_bindgen] pub fn stair_default_step_count(total_rise: f64, run_length: f64) -> u32 { diff --git a/src/core/document.ts b/src/core/document.ts index 23f5eaec..a013c60c 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -259,7 +259,7 @@ export class ProjectDocument { * Wie {@link queryRoot} für Abfragen, deren Antwort nicht endliche Zahlen als Marken trägt * (`selectionInfo`, `drawingBBoxes`); die Marken werden wieder Zahlen. */ - queryRootMarked(name: "selectionInfo" | "drawingBBoxes", text = ""): T { + queryRootMarked(name: "selectionInfo" | "drawingBBoxes" | "verticalExtents", text = ""): T { if (!this.handle) throw new Error(`Kern-Abfrage „${name}": Dokument nicht offen`); const out = core().doc_query_root(this.handle, name, text); if (out.startsWith("\u0001")) throw new Error(out.slice(1)); diff --git a/src/core/extra.ts b/src/core/extra.ts index acb9504d..2ec22270 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -54,4 +54,6 @@ export type { EntityCollection, EntityOf, ProjectMutation } from "./opsBuild"; export { EMPTY_MEMBERSHIP, containingGroupId, expandToGroups, isInsideActiveGroup, transitiveMembership } from "../model/groups"; export type { GroupMembership, MemberKind } from "../model/groups"; export { drawingVertices, gripPt, openEdges, polylineEdgeGrips, ringEdges } from "../geometry/grips"; +export { verticalExtents } from "../geometry/grips"; +export type { VerticalExtent } from "../geometry/grips"; export type { GripRequest } from "../geometry/grips"; diff --git a/src/core/index.ts b/src/core/index.ts index 41f40d4a..8740cfff 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -20,7 +20,6 @@ export { export { ceilingArea, normalizeOutline, - outlineBBox, pointInOutline, } from "../geometry/ceiling"; @@ -98,7 +97,6 @@ export { } from "../geometry/lineSegments"; export { - openingGapQuad, openingVerticalExtent, } from "../geometry/opening"; export { autoExteriorDimensions } from "../geometry/autoDimensions"; @@ -122,7 +120,6 @@ export { } from "../geometry/revisionCloud"; export { - roofBBox, roofBaseElevation, roofGeometry, } from "../geometry/roof"; @@ -130,7 +127,6 @@ export { export { addRoofHole, removeRoofHole, - roofEdgeList, roofHoleWorks, setRoofEdge, } from "../geometry/roofEdges"; @@ -155,7 +151,6 @@ export { IDEAL_TREAD, MIN_STEPS, defaultStepCount, - stairBBox, stairGeometry, stairOutline, } from "../geometry/stair"; diff --git a/src/geometry/ceiling.ts b/src/geometry/ceiling.ts index 1fdb29cb..bbdb4f63 100644 --- a/src/geometry/ceiling.ts +++ b/src/geometry/ceiling.ts @@ -43,30 +43,6 @@ export function ceilingArea(pts: Vec2[]): number { return Math.abs(signedArea(pts)); } -/** - * Achsparallele Bounding-Box eines Umrisses (Modell-Meter). Leerer/entarteter - * Umriss → Null-Box. - */ -export function outlineBBox(pts: Vec2[]): { - minX: number; - minY: number; - maxX: number; - maxY: number; -} { - let minX = Infinity, - minY = Infinity, - maxX = -Infinity, - maxY = -Infinity; - for (const p of pts) { - minX = Math.min(minX, p.x); - minY = Math.min(minY, p.y); - maxX = Math.max(maxX, p.x); - maxY = Math.max(maxY, p.y); - } - if (!isFinite(minX)) return { minX: 0, minY: 0, maxX: 0, maxY: 0 }; - return { minX, minY, maxX, maxY }; -} - /** Schwerpunkt (Zentroid) des Umriss-Polygons (für HUD/Beschriftung). */ export function outlineCentroid(pts: Vec2[]): Vec2 { const a = signedArea(pts); diff --git a/src/geometry/grips.ts b/src/geometry/grips.ts index 871ab61c..b7c5e8a9 100644 --- a/src/geometry/grips.ts +++ b/src/geometry/grips.ts @@ -7,7 +7,8 @@ // Bewusst TS: die Rahmen-Ecken einer Textspalte (`textFrameCorners` braucht die Schrift-Metrik der // Hülle) — der Kern meldet dafür nur „Textspalte". -import type { Drawing2D, Drawing2DGeom, EdgeGrip, Vec2 } from "../model/types"; +import type { Ceiling, Drawing2D, Drawing2DGeom, EdgeGrip, Project, Vec2, Wall } from "../model/types"; +import { documentFor } from "../core/document"; import { core } from "../engine/coreWasm"; import { toMarkedJson } from "../core/ops"; import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension"; @@ -103,3 +104,25 @@ export function openEdges(verts: readonly Vec2[], owner: Owner): EdgeGrip[] { export function polylineEdgeGrips(g: Extract, owner: Owner): EdgeGrip[] { return edges(g.pts, !!g.closed, g.bulge ?? [], owner); } + +/** Unter-/Oberkante (absolutes Z, Meter) eines Bauteils. */ +export interface VerticalExtent { + zBottom: number; + zTop: number; +} + +/** + * UK/OK von Wänden und Decken aus dem Kern (`selection_info.rs::vertical_extents`, Regeln wie + * `wallVerticalExtent`/`ceilingVerticalExtent`): Geschoss-Bindungen und Deckentypen aus `project`, die + * Elemente selbst als ganze Fassung (auch gerade gezogene, noch nicht übernommene — 3D-Griffe). + */ +export function verticalExtents( + project: Project, + walls: readonly Wall[], + ceilings: readonly Ceiling[] = [], +): { walls: VerticalExtent[]; ceilings: VerticalExtent[] } { + if (walls.length === 0 && ceilings.length === 0) return { walls: [], ceilings: [] }; + const f = documentFor(project).queryRootMarked("verticalExtents", toMarkedJson({ walls, ceilings })); + const at = (i: number): VerticalExtent => ({ zBottom: f[2 * i], zTop: f[2 * i + 1] }); + return { walls: walls.map((_, i) => at(i)), ceilings: ceilings.map((_, i) => at(walls.length + i)) }; +} diff --git a/src/geometry/opening.ts b/src/geometry/opening.ts index 91c035e5..91fafad9 100644 --- a/src/geometry/opening.ts +++ b/src/geometry/opening.ts @@ -13,7 +13,7 @@ import type { Opening, Project, SashDef, Vec2, Wall } from "../model/types"; import { core } from "../engine/coreWasm"; import { getWallType, wallTypeThickness } from "../model/types"; -import { add, along, leftNormal, normalize, scale, sub } from "../model/geometry"; +import { along, leftNormal, normalize, sub } from "../model/geometry"; import { wallReferenceOffset, wallVerticalExtent } from "../model/wall"; /** Achslänge einer Wand (Meter). */ @@ -73,28 +73,6 @@ export function openingJambs( }; } -/** - * Die Lücken-Rechteck-Ecken (über die volle Wanddicke), z. B. um im Plan die - * Öffnung als Aussparung zu markieren (Auswahl-Highlight). Reihenfolge: - * jambStart(+n/2) → jambEnd(+n/2) → jambEnd(−n/2) → jambStart(−n/2). - */ -export function openingGapQuad(project: Project, wall: Wall, o: Opening): Vec2[] | null { - const jambs = openingJambs(wall, o); - if (!jambs) return null; - const { n } = wallAxisFrame(wall); - const total = wallTypeThickness(getWallType(project, wall)); - const refOff = wallReferenceOffset(wall, total); - const outer = refOff + total / 2; - const inner = refOff - total / 2; - const { jambStart, jambEnd } = jambs; - return [ - add(jambStart, scale(n, outer)), - add(jambEnd, scale(n, outer)), - add(jambEnd, scale(n, inner)), - add(jambStart, scale(n, inner)), - ]; -} - /** Mittelpunkt einer Öffnung im Grundriss (Achse) — für HUD/Auswahl-Anker. */ export function openingCenter(wall: Wall, o: Opening): Vec2 | null { const iv = openingInterval(wall, o); diff --git a/src/geometry/roof.test.ts b/src/geometry/roof.test.ts index 4492af3d..9c85a0f6 100644 --- a/src/geometry/roof.test.ts +++ b/src/geometry/roof.test.ts @@ -1,7 +1,14 @@ import { describe, it, expect } from "vitest"; -import { roofGeometry, roofBBox, roofUndersideAt } from "./roof"; +import { roofGeometry, roofUndersideAt } from "./roof"; import type { Roof, Vec2 } from "../model/types"; +/** Bounding-Box eines Umrisses (Prüfhilfe). */ +function roofBBox(outline: Vec2[]): { x0: number; y0: number; x1: number; y1: number } { + const xs = outline.map((p) => p.x); + const ys = outline.map((p) => p.y); + return { x0: Math.min(...xs), y0: Math.min(...ys), x1: Math.max(...xs), y1: Math.max(...ys) }; +} + // Rechteck 6×4 (x:0..6, y:0..4), Neigung 45° (tan=1), Traufhöhe 10, kein Überstand. const RECT: Vec2[] = [ { x: 0, y: 0 }, @@ -35,12 +42,6 @@ function allZ(g: ReturnType): number[] { return zs; } -describe("roofBBox", () => { - it("liefert die Bounding-Box", () => { - expect(roofBBox(RECT)).toEqual({ x0: 0, y0: 0, x1: 6, y1: 4 }); - }); -}); - describe("roofGeometry — Formen (6×4, 45°, First entlang X)", () => { it("flach: eine waagrechte Fläche auf Traufhöhe, kein First", () => { const g = roofGeometry(roof({ shape: "flach" }), E); diff --git a/src/geometry/roof.ts b/src/geometry/roof.ts index 66337ac0..d0b7cb9e 100644 --- a/src/geometry/roof.ts +++ b/src/geometry/roof.ts @@ -39,21 +39,6 @@ export interface RoofGeometry { ridgeHeight: number; } -/** Bounding-Box eines Umrisses. */ -export function roofBBox(outline: Vec2[]): { x0: number; y0: number; x1: number; y1: number } { - let x0 = Infinity; - let y0 = Infinity; - let x1 = -Infinity; - let y1 = -Infinity; - for (const p of outline) { - if (p.x < x0) x0 = p.x; - if (p.y < y0) y0 = p.y; - if (p.x > x1) x1 = p.x; - if (p.y > y1) y1 = p.y; - } - return { x0, y0, x1, y1 }; -} - /** * Traufhöhe (absolutes Z) eines Dachs: `baseElevation`, sonst die OBERKANTE des * zugehörigen Geschosses (baseElevation + floorHeight) — das Dach sitzt also diff --git a/src/geometry/roofEdges.test.ts b/src/geometry/roofEdges.test.ts index 22effe62..8d989b61 100644 --- a/src/geometry/roofEdges.test.ts +++ b/src/geometry/roofEdges.test.ts @@ -1,7 +1,8 @@ -// Kanten und Höfe eines Dachs ([26]): Liste, Änderung der Kantenneigung, Hof hinzufügen/entfernen. +// Kanten und Höfe eines Dachs ([26]): Änderung der Kantenneigung, Hof hinzufügen/entfernen (die +// Kantenliste rechnet der Kern, Test in `state/selectionInfo.test.ts`). import { describe, expect, it } from "vitest"; import type { Roof, Vec2 } from "../model/types"; -import { addRoofHole, removeRoofHole, roofEdgeList, roofHoleWorks, setRoofEdge } from "./roofEdges"; +import { addRoofHole, removeRoofHole, roofHoleWorks, setRoofEdge } from "./roofEdges"; const rect = (x: number, y: number, w: number, h: number): Vec2[] => [ { x, y }, @@ -26,27 +27,6 @@ const roof = (extra: Partial = {}): Roof => ({ const court = rect(4, 2, 4, 4); -describe("roofEdgeList", () => { - it("Umrisskanten, dann Hofkanten; Standard ohne Feld", () => { - const list = roofEdgeList(roof({ holes: [court] })); - expect(list).toHaveLength(8); - expect(list.map((e) => e.ring)).toEqual([0, 0, 0, 0, 1, 1, 1, 1]); - expect(list[0]).toMatchObject({ index: 0, spec: { kind: "default" }, length: 12 }); - expect(list[5].index).toBe(5); - }); - - it("liest Giebel, Neigung und negativ = Standard; Sattel: Giebelregel zeigt sich als Vorgabe", () => { - const list = roofEdgeList(roof({ edgePitchDeg: [20, null, -1] })); - expect(list[0].spec).toEqual({ kind: "pitch", deg: 20 }); - expect(list[1].spec).toEqual({ kind: "gable" }); - expect(list[2].spec).toEqual({ kind: "default" }); - expect(list[3].spec).toEqual({ kind: "default" }); - const sattel = roofEdgeList(roof({ shape: "sattel" })); - expect(sattel.map((e) => e.defaultGable)).toEqual([false, true, false, true]); - expect(roofEdgeList(roof()).every((e) => !e.defaultGable)).toBe(true); - }); -}); - describe("setRoofEdge", () => { it("setzt Neigung/Giebel, füllt mit Standard auf, entfernt das Feld wenn alles Standard", () => { const a = setRoofEdge(roof(), 2, { kind: "pitch", deg: 25 }); diff --git a/src/geometry/roofEdges.ts b/src/geometry/roofEdges.ts index ae03763b..1af860e6 100644 --- a/src/geometry/roofEdges.ts +++ b/src/geometry/roofEdges.ts @@ -1,4 +1,4 @@ -// Kanten und Höfe eines Dachs ([26]): die Kantenliste fürs Objekt-Info (Neigung je Kante, Giebel), +// Kanten und Höfe eines Dachs ([26]): Typen der Kantenliste (gerechnet im Kern, `selection_info.rs`), // Änderungen als Teilobjekt (`Partial`, für `updateRoof`/`patchItem` — ein Undo-Schritt) und // die Prüfung, ob ein Hof wirkt. Die Geometrie selbst rechnet der Rust-Kern (`roof.rs`). // @@ -31,46 +31,6 @@ export interface RoofEdge { const MAX_PITCH = 89; -/** Die Vorgabe aus einem Eintrag von `edgePitchDeg`. */ -function specOf(v: number | null | undefined): EdgeSpec { - if (v === null) return { kind: "gable" }; - if (v === undefined || !Number.isFinite(v) || v < 0) return { kind: "default" }; - return { kind: "pitch", deg: v }; -} - -/** Giebelt der Standard dieser Dachform die Kante a→b (quer zur Firstrichtung)? */ -function defaultGableEdge(roof: Roof, a: Vec2, b: Vec2): boolean { - const gabled = roof.shape === "sattel" || (roof.shape === "mansarde" && (roof.mansardType ?? "giebel") === "giebel"); - if (!gabled) return false; - const dx = Math.abs(b.x - a.x); - const dy = Math.abs(b.y - a.y); - return roof.ridgeAxis === "y" ? dy < dx : dx < dy; -} - -/** Alle Kanten des Dachs (Umriss, dann Höfe) mit ihrer Vorgabe. */ -export function roofEdgeList(roof: Roof): RoofEdge[] { - const rings: Vec2[][] = [roof.outline, ...(roof.holes ?? [])]; - const out: RoofEdge[] = []; - let index = 0; - rings.forEach((ring, r) => { - ring.forEach((a, edge) => { - const b = ring[(edge + 1) % ring.length]; - out.push({ - index, - ring: r, - edge, - a, - b, - length: Math.hypot(b.x - a.x, b.y - a.y), - spec: specOf(roof.edgePitchDeg?.[index]), - defaultGable: defaultGableEdge(roof, a, b), - }); - index++; - }); - }); - return out; -} - /** `edgePitchDeg` ohne Standard-Einträge am Ende; alles Standard ⇒ `undefined` (Feld entfällt). */ function normalized(values: (number | null)[]): (number | null)[] | undefined { const v = values.slice(); @@ -80,7 +40,7 @@ function normalized(values: (number | null)[]): (number | null)[] | undefined { /** Teilobjekt für `updateRoof`: Kante `index` auf `spec` setzen. */ export function setRoofEdge(roof: Roof, index: number, spec: EdgeSpec): Pick { - const total = roofEdgeList(roof).length; + const total = roof.outline.length + (roof.holes ?? []).reduce((n, h) => n + h.length, 0); const values: (number | null)[] = Array.from({ length: total }, (_, i) => { const v = roof.edgePitchDeg?.[i]; return v === undefined ? -1 : v; diff --git a/src/geometry/stair.test.ts b/src/geometry/stair.test.ts index c820ea3d..483af9aa 100644 --- a/src/geometry/stair.test.ts +++ b/src/geometry/stair.test.ts @@ -3,7 +3,7 @@ * Referenz, Schnitt, Rahmen und Unsinn-Eingaben (Rust-Tests decken die Mathematik je Fall ab). */ import { describe, it, expect } from "vitest"; -import { defaultStepCount, stairBBox, stairCut, stairGeometry, stairOutline } from "./stair"; +import { defaultStepCount, stairCut, stairGeometry, stairOutline } from "./stair"; import type { Stair } from "../model/types"; const base: Stair = { @@ -51,11 +51,10 @@ describe("stairGeometry", () => { expect(stairGeometry(base, NaN).treads).toEqual([]); expect(stairGeometry({ ...base, stepCount: 0 }, 2.8).treads).toHaveLength(2); expect(stairOutline({ ...base, runLength: NaN }, 0)).toEqual({ polygon: null, spiral: null }); - expect(stairBBox(stairGeometry(base, NaN))).toEqual({ minX: 0, minY: 0, maxX: 0, maxY: 0 }); }); }); -describe("stairCut / stairBBox / defaultStepCount", () => { +describe("stairCut / defaultStepCount", () => { it("Schnitt teilt die Tritte und legt eine Doppel-Bruchlinie", () => { const g = stairGeometry(base, 2.8); const c = stairCut(g, 1.0); @@ -66,12 +65,6 @@ describe("stairCut / stairBBox / defaultStepCount", () => { expect(stairCut(stairGeometry(base, NaN), 1)).toEqual({ belowIndices: [], aboveIndices: [], breakLine: null }); }); - it("BBox über Tritte", () => { - const b = stairBBox(stairGeometry(base, 2.8)); - expect(b.maxX).toBeCloseTo(3, 12); - expect(b.minY).toBeCloseTo(-0.6, 12); - }); - it("Vorgabe-Stufenzahl: Steighöhe 0.17, gedeckelt durch die Lauflänge, mind. 2", () => { expect(defaultStepCount(2.8, 10)).toBe(16); expect(defaultStepCount(2.8, 3)).toBe(13); diff --git a/src/geometry/stair.ts b/src/geometry/stair.ts index 05f3b445..eb911d04 100644 --- a/src/geometry/stair.ts +++ b/src/geometry/stair.ts @@ -152,8 +152,8 @@ function encodeGeometry(g: StairGeometry): Float64Array { /** * Leitet die vollständige Geometrie einer Treppe ab. `totalRise` MUSS vom - * Aufrufer aufgelöst übergeben werden (Geschosshöhe-Default liegt in - * `stairVerticalExtent`), damit dieses Modul modellfrei bleibt. + * Aufrufer aufgelöst übergeben werden (Geschosshöhe-Default liegt im Kern, + * `stair_vertical_extent` in `model/helpers.rs`), damit dieses Modul modellfrei bleibt. */ export function stairGeometry(stair: Stair, totalRise: number): StairGeometry { return decodeGeometry(core().stair_geometry_flat(encodeStair(stair), totalRise)); @@ -199,18 +199,6 @@ export function stairCut(geo: StairGeometry, cutRise: number): StairCut { return { belowIndices, aboveIndices, breakLine }; } -/** Achsparallele Bounding-Box aller Tritte (+ Podest) einer Treppengeometrie. */ -export function stairBBox(geo: StairGeometry): { - minX: number; - minY: number; - maxX: number; - maxY: number; -} { - const f = core().stair_bbox_flat(encodeGeometry(geo)); - if (f.length < 4) return { minX: 0, minY: 0, maxX: 0, maxY: 0 }; - return { minX: f[0], minY: f[1], maxX: f[2], maxY: f[3] }; -} - /** * Spiral-Outline: Innenbogen + Aussenbogen + zwei radiale Schliesslinien. * Die Bögen werden als Kreisbogen-Parameter geliefert (cx/cy/r/a0/a1), die diff --git a/src/io/lv95.ts b/src/io/lv95.ts index fa1ed9ed..8980ce26 100644 --- a/src/io/lv95.ts +++ b/src/io/lv95.ts @@ -120,15 +120,6 @@ export function lv95ToLocal(pt: LV95, origin: GeoOrigin): { x: number; y: number return { x: pt.e - origin.e, y: pt.n - origin.n }; } -/** Lokale Modell-Meter → LV95 (Umkehrung von {@link lv95ToLocal}). */ -export function localToLv95( - x: number, - y: number, - origin: GeoOrigin, -): LV95 { - return { e: x + origin.e, n: y + origin.n }; -} - /** * WGS84 → lokale Modell-Meter (über LV95 und die Origin). Praktisch für * OSM-Punkte (lon/lat), die zuerst nach LV95 projiziert und dann verschoben diff --git a/src/model/geometry.ts b/src/model/geometry.ts index 19aba382..bdfa7620 100644 --- a/src/model/geometry.ts +++ b/src/model/geometry.ts @@ -22,53 +22,10 @@ export const cross = (p: Vec2, q: Vec2): number => p.x * q.y - p.y * q.x; /** Skalarprodukt zweier 2D-Vektoren. */ export const dot = (p: Vec2, q: Vec2): number => p.x * q.x + p.y * q.y; -/** Eine unendliche Gerade als Stützpunkt + Richtung. */ -export interface Line { - point: Vec2; - dir: Vec2; -} - -/** - * Schnittpunkt der Geraden (a + t·da) mit (b + s·db). - * Liefert null bei (nahezu) parallelen Richtungen. - */ -export function lineIntersect( - a: Vec2, - da: Vec2, - b: Vec2, - db: Vec2, -): Vec2 | null { - const denom = cross(da, db); - if (Math.abs(denom) < 1e-9) return null; // parallel → kein Schnitt - const t = cross(sub(b, a), db) / denom; - return add(a, scale(da, t)); -} - /** Punkt entlang einer Strecke p1→p2 im Abstand d vom Start. */ export const along = (p1: Vec2, p2: Vec2, d: number): Vec2 => add(p1, scale(normalize(sub(p2, p1)), d)); -/** - * Die vier Eckpunkte eines Bandes, das quer zur Normalen zwischen den - * Offsets offA und offB liegt (gemessen entlang der linken Normalen n). - * Reihenfolge: start+n*offA, end+n*offA, end+n*offB, start+n*offB. - */ -export function wallBand( - start: Vec2, - end: Vec2, - offA: number, - offB: number, -): [Vec2, Vec2, Vec2, Vec2] { - const u = normalize(sub(end, start)); - const n = leftNormal(u); - return [ - add(start, scale(n, offA)), - add(end, scale(n, offA)), - add(end, scale(n, offB)), - add(start, scale(n, offB)), - ]; -} - /** Die vier Eckpunkte einer Wand als Polygon (gegen den Uhrzeigersinn). */ export function wallCorners( start: Vec2, @@ -76,38 +33,7 @@ export function wallCorners( thickness: number, ): [Vec2, Vec2, Vec2, Vec2] { const h = thickness / 2; - return wallBand(start, end, h, -h); -} - -/** - * Wie {@link wallBand}, aber die Bandenden werden bei Bedarf an Geh­rungs­linien - * (startCut / endCut) abgeschnitten statt rechtwinklig gekappt. Jede der beiden - * Bandkanten (bei Offset offA bzw. offB, Richtung u) wird mit der jeweiligen - * Schnittlinie verschnitten; fehlt eine Schnittlinie, bleibt das Ende - * rechtwinklig (Punkt auf der Achssenkrechten). - * Reihenfolge bleibt konsistent zu wallBand: [A.start, A.end, B.end, B.start]. - */ -export function clippedBand( - start: Vec2, - end: Vec2, - offA: number, - offB: number, - startCut: Line | null, - endCut: Line | null, -): [Vec2, Vec2, Vec2, Vec2] { const u = normalize(sub(end, start)); const n = leftNormal(u); - - const edgeStart = (off: number): Vec2 => { - const base = add(start, scale(n, off)); - if (!startCut) return base; - return lineIntersect(base, u, startCut.point, startCut.dir) ?? base; - }; - const edgeEnd = (off: number): Vec2 => { - const base = add(end, scale(n, off)); - if (!endCut) return base; - return lineIntersect(base, u, endCut.point, endCut.dir) ?? base; - }; - - return [edgeStart(offA), edgeEnd(offA), edgeEnd(offB), edgeStart(offB)]; + return [add(start, scale(n, h)), add(end, scale(n, h)), add(end, scale(n, -h)), add(start, scale(n, -h))]; } diff --git a/src/model/wall.ts b/src/model/wall.ts index 2c37f275..28b2298b 100644 --- a/src/model/wall.ts +++ b/src/model/wall.ts @@ -5,7 +5,7 @@ // // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). -import type { Ceiling, Column, Project, Stair, VerticalAnchor, Wall } from "./types"; +import type { Ceiling, Column, Project, VerticalAnchor, Wall } from "./types"; import { ceilingThickness, getFloor } from "./types"; /** @@ -103,37 +103,6 @@ export function ceilingVerticalExtent( return { zBottom, zTop }; } -/** - * Vertikale Ausdehnung einer Treppe (absolute Z-Werte in Metern). - * • zBottom: OKFF (baseElevation) des zugehörigen Geschosses. - * • zTop: zBottom + Gesamt-Steighöhe. Fehlt `stair.totalRise`, gilt die - * Geschosshöhe (floorHeight) des Geschosses — so steigt die Treppe genau ins - * nächste Geschoss (OKFF → OKFF). - * Fehlt das Geschoss, dient 0 als sicherer Rückfall für die Unterkante. - */ -export function stairVerticalExtent( - project: Project, - stair: Stair, -): { zBottom: number; zTop: number } { - let base = 0; - let floorHeight = 0; - try { - const floor = getFloor(project, stair.floorId); - base = floor.baseElevation ?? 0; - floorHeight = floor.floorHeight ?? 0; - } catch { - base = 0; - floorHeight = 0; - } - const rise = - stair.totalRise != null && stair.totalRise > 0 - ? stair.totalRise - : floorHeight > 0 - ? floorHeight - : 2.6; - return { zBottom: base, zTop: base + rise }; -} - /** * Vertikale Ausdehnung einer Stütze (absolute Z-Werte in Metern) — dieselbe * Regel wie {@link wallVerticalExtent}: @@ -155,19 +124,3 @@ export function columnVerticalExtent( const zTop = resolveAnchor(project, column.top) ?? zBottom + column.height; return { zBottom, zTop }; } - -/** - * Das Geschoss DIREKT ÜBER dem Wand-Geschoss (in Dokumentreihenfolge der - * "floor"-Ebenen) oder `undefined`, wenn die Wand im obersten Geschoss liegt. - * Dient der „Verknüpfung zum oberen Geschoss" (OK an nächstes Geschoss binden). - */ -export function nextFloorAbove( - project: Project, - wall: Wall, -): { id: string; name: string } | undefined { - const floors = project.drawingLevels.filter((z) => z.kind === "floor"); - const idx = floors.findIndex((z) => z.id === wall.floorId); - if (idx < 0) return undefined; - const above = floors[idx + 1]; - return above ? { id: above.id, name: above.name } : undefined; -} diff --git a/src/state/selectionInfo.test.ts b/src/state/selectionInfo.test.ts index 46b11e9c..12007952 100644 --- a/src/state/selectionInfo.test.ts +++ b/src/state/selectionInfo.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest"; import { deriveSelection } from "./selectionInfo"; import { sampleProject } from "../model/sampleProject"; -import type { Project } from "../model/types"; +import type { Project, Roof } from "../model/types"; const base = (): Project => structuredClone(sampleProject); @@ -60,4 +60,30 @@ describe("deriveSelection (Kern)", () => { "height", "taper", "cornerRadius", "chamfer", "area", "spec", "subtract", "canSubtract", "baseOffset", "floorId", "floorName", ]); }); + + it("Dach: Kantenliste (Umriss, dann Hof), Vorgaben je Kante und Giebel-Standard", () => { + const p = base(); + const rect = (x: number, y: number, w: number, h: number) => [ + { x, y }, { x: x + w, y }, { x: x + w, y: y + h }, { x, y: y + h }, + ]; + const roof = (extra: Partial): Roof => ({ + id: "R", type: "roof", floorId: p.drawingLevels.find((z) => z.kind === "floor")!.id, categoryCode: "31", + outline: rect(0, 0, 12, 8), shape: "walm", pitchDeg: 35, overhang: 0, ridgeAxis: "x", thickness: 0.2, ...extra, + }); + const edges = (r: Roof) => { + // Neues Projekt-Objekt je Fall: der Kern gleicht über Referenzen ab. + return deriveSelection({ ...p, roofs: [r] }, [], null, null, null, null, null, null, null, "R")!.roof!.edges; + }; + const list = edges(roof({ holes: [rect(4, 2, 4, 4)] })); + expect(list).toHaveLength(8); + expect(list.map((e) => e.ring)).toEqual([0, 0, 0, 0, 1, 1, 1, 1]); + expect(list[0]).toMatchObject({ index: 0, spec: { kind: "default" }, length: 12 }); + expect(list[5].index).toBe(5); + const specs = edges(roof({ edgePitchDeg: [20, null, -1] })); + expect(specs.map((e) => e.spec)).toEqual([ + { kind: "pitch", deg: 20 }, { kind: "gable" }, { kind: "default" }, { kind: "default" }, + ]); + expect(edges(roof({ shape: "sattel" })).map((e) => e.defaultGable)).toEqual([false, true, false, true]); + expect(edges(roof({})).every((e) => !e.defaultGable)).toBe(true); + }); }); diff --git a/src/viewport/Wasm3DViewport.tsx b/src/viewport/Wasm3DViewport.tsx index 00b7094e..a15572d6 100644 --- a/src/viewport/Wasm3DViewport.tsx +++ b/src/viewport/Wasm3DViewport.tsx @@ -44,8 +44,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import type { Project, Wall, Drawing2D, Ceiling, Roof, Vec2 } from "../model/types"; -import { ceilingVerticalExtent, wallVerticalExtent } from "../model/wall"; -import { roofBaseElevation, roofGeometry } from "../core"; +import { roofBaseElevation, roofGeometry, verticalExtents } from "../core"; import { projectToModel3d, pickGeometry, draftWorldLines, TRUCK_MESH_READY_EVENT } from "../core"; import type { DetailLevel, RenderMode, View3d } from "../model/viewTypes"; import type { ToolDraft } from "../tools/types"; @@ -146,8 +145,9 @@ function computeGrips( drawingElevation: number, ): Grip[] { const out: Grip[] = []; - for (const w of walls) { - const { zBottom, zTop } = wallVerticalExtent(project, w); + const ext = verticalExtents(project, walls, ceilings); + walls.forEach((w, wi) => { + const { zBottom, zTop } = ext.walls[wi]; const target = { wallId: w.id }; out.push({ kind: "vertex", target, index: 0, pos: [w.start.x, zBottom, w.start.y] }); out.push({ kind: "vertex", target, index: 1, pos: [w.end.x, zBottom, w.end.y] }); @@ -155,7 +155,7 @@ function computeGrips( const midY = (w.start.y + w.end.y) / 2; out.push({ kind: "height", target, index: -1, pos: [midX, zTop, midY] }); out.push({ kind: "move", target, index: -1, pos: [midX, zBottom + 0.05, midY] }); - } + }); for (const d of drawings) { const verts = drawingGripVertices(d); const target = { drawingId: d.id }; @@ -167,12 +167,12 @@ function computeGrips( // Decken: Eckpunkt-Griffe (Umriss) + je Seite ein Kanten-Mittelpunkt-Griff // (Nutzer-Wunsch „an allen seiten auch ein punkt … wie an den eckpunkten") + // ein Verschiebe-Griff im Schwerpunkt. Griffe sitzen auf der Deckenoberkante. - for (const c of ceilings) { + ceilings.forEach((c, ci) => { const pts = c.outline; const n = pts.length; - if (n < 2) continue; + if (n < 2) return; const target = { ceilingId: c.id }; - const y = ceilingVerticalExtent(project, c).zTop + 0.02; + const y = ext.ceilings[ci].zTop + 0.02; let sx = 0; let sy = 0; pts.forEach((p, i) => { @@ -189,7 +189,7 @@ function computeGrips( sy += p.y; }); out.push({ kind: "move", target, index: -1, pos: [sx / n, y + 0.03, sy / n] }); - } + }); // Dächer: Eckpunkt-Griffe (Umriss = Traufe-Grundriss, resize) + Verschiebe-Griff // + ein FIRST-/Neigungs-Griff am höchsten Punkt (vertikal ziehen ändert die // Neigung). Eckpunkte auf Traufhöhe. @@ -927,11 +927,11 @@ export function Wasm3DViewport({ const gripPlaneY = (target: GripTarget): number | null => { if (target.wallId) { const wall = editWallsRef.current.find((w) => w.id === target.wallId); - return wall ? wallVerticalExtent(projectRef.current, wall).zBottom : null; + return wall ? verticalExtents(projectRef.current, [wall]).walls[0].zBottom : null; } if (target.ceilingId) { const c = editCeilingsRef.current.find((x) => x.id === target.ceilingId); - return c ? ceilingVerticalExtent(projectRef.current, c).zTop : null; + return c ? verticalExtents(projectRef.current, [], [c]).ceilings[0].zTop : null; } if (target.roofId) { const r = editRoofsRef.current.find((x) => x.id === target.roofId);