diff --git a/TODO.md b/TODO.md index 6564b9d6..3351a5b0 100644 --- a/TODO.md +++ b/TODO.md @@ -719,13 +719,44 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern (Minimum, im Rauschen; die Kosten liegen beim Klonen der JSON-Elemente im Kern statt beim JSON-Lesen). Abweichung (gewollt): Griff-Vorschau „Element verschieben“ zeigt bei Formen ohne Primitive die einfachen Ersatz-Formen wie die Transformations-Vorschau. Nicht in der Tauri-App geprüft. - **Offen (S3, Befehle):** Zeichenbefehle (Wand, Decke, Raum, Treppe, Öffnung, Dach, Stütze, Extrusion, alle + **Offen (S3, Befehle):** ~~Zeichenbefehle (Wand, Decke, Raum, Treppe, Öffnung, Dach, Stütze, Extrusion, alle 2D-Formen, Bemassung, autodim, sectionline, solid/solidbool/voidbox/terrain, ceilingOpening) und die Werkzeug-Commits in `tools/tools.ts` bauen ihre Elemente noch in TS (meist ein Objekt-Literal aus den - Klickpunkten); Einfügen (`pasteElementClipboard`), Gruppen-Zuordnung (`activeGroupOps`); Split/Segment + Klickpunkten)~~ (erledigt 29.10., s. unten); Einfügen (`pasteElementClipboard`), ~~Gruppen-Zuordnung + (`activeGroupOps`)~~; Split/Segment löschen (`editors/splitJoin.ts`, App) — dort ersetzt `cutSegment` per `replace` mit NEUER id (hängt an statt zu ersetzen; beim Port prüfen); Fang-Kandidaten aus dem Modell (`tools/snapping.ts`: `baseSegments`, Kreise, Raum-Anker; Nahmodus ab 2000 Zeichnungen) → `snap.rs`. + **Zeichenbefehle im Kern (29.10.):** alle Erzeuge-Befehle bauen ihre Elemente im Kern (`cmd_create.rs`: + Wand, Decke, Raum, Treppe, Öffnung/Fenster/Tür, Dach, Stütze, Extrusion; `cmd_draw.rs`: Linie, xline, ray, + Polylinie, Rechteck, Kreis, Bogen, Ellipse, Polygon, Spline, Bézier, Revisionswolke, Wipeout, Multilinie, + Texte, Hinweis, Kote, Detailverweis, Massstab, Punkt, Block, Bemassung, autodim; `cmd_solid.rs`: solid, + solidbool, voidbox, terrain, Deckenöffnung, Dachhof, Schnittlinie/Ansichtslinie): Vorgaben aus Typen/Stilen, + abgeleitete Felder, ids und Gruppen-Zuordnung (`group` im Request, ersetzt `activeGroupOps`). TS hält nur + die Zustandsautomaten (`commands/createCore.ts`: `createMutation`, `createPreview` mit zwischengespeichertem + Request → `doc_create_preview_again` ohne JSON je Mausschritt, `createQuery` für Wand-/Profil-/Körper-Wahl). + Vorschauen mit Rechnung (Wand, Treppe, Öffnung, Raum innen, Stütze, Kreis/Bogen/Ellipse/Polygon, Multilinie, + Bemassung, autodim, Körper, Schnittlinie) aus dem Kern; reine Echo-Vorschauen (Gummiband, Linie, Punktlisten) + und HUD-Texte/Feld-Helfer bleiben TS. `tools/tools.ts`: alte Wand/Decke/Linie/Polylinie/Rechteck-Werkzeuge + entfernt. Gelöscht (TS): `geometry/ceiling.ts`, `opening.ts`, `autoDimensions.ts`, `revisionCloud.ts`, + Fassaden `arcThroughPoints`/`arcFromStartEnd*`/`bulgeThroughPoint`, `polylineEdges`/`pointSegmentDistance`/ + `signedArea`/`isCCW`/`offsetSegment`/`tangentCircleCenters`/`filletCorner`, `stairGeometry`/`stairCut`/ + `defaultStepCount`, `ellipsePts`, `roofHoleWorks`/`addRoofHole`, `roomFromPointInside(Faces)`, + `activeGroupOps`; `extrudedSolidSpec` und `generateTerrainFromContours` sind Fassaden über den Kern. + Gleichheit alt (TS) ↔ Kern mit zeitweiligen Zufallstests (Ops gleich bis auf ids, Vorschauen bitgleich mit + −0 ≡ 0, danach gelöscht): Wand 1000 Folgen/39677 Vorschauen/2136 Commits, Decke 1941, Raum 937, Treppe 11287, + Öffnung 1531/Fenster 738/Tür 1502, Dach 9224, Stütze 15833, Extrusion 438; Linie 9643, xline 5430, ray 5387, + Polylinie 67647 Vorschauen/3699 Commits, Rechteck 15293, Kreis 16408, Bogen 9751, Ellipse 10530, Polygon + 10846, Spline 3561, Bézier 829, Wolke 3519, Wipeout 1280, Multilinie 6449, Text 7258, Textbox 5055, Textpfad + 1096, Hinweis 2019, Kote 435, Detail 7329, Massstab 12068, Punkt 7247, Block 3570, Bemassung 2466 (68378 + Vorschauen), autodim 1066; solid 9348, solidbool 302, voidbox 1764, terrain 7805 (+2000 Höhenlinien-Sätze, + 38617 Dreiecke), Deckenöffnung 1558, Dachhof 288, Schnittlinie 11162, Ansichtslinie 5538, extrudedSolidSpec + 20000; Gruppen-Ops = altes `activeGroupOps`. Messung Wand-Vorschau je Mausschritt (vitest/WASM `--no-opt`, + 3000 Wände, Minimum aus 7): nur Vorschau 1/4/12 Punkte 0,5/1,3/3,8 → 2,9/3,8/3,2 µs; ganzer Mausschritt + (Fang + Vorschau) 70,6/70,0/75,5 → 75,0/75,3/73,1 µs (Rauschen ±10 µs, Fang dominiert). Abweichungen + (gewollt): ids `präfix-stamp-k` (Schnittlinien-Geschoss `section-stamp-1` statt `section-`); + nicht-endliche Zahlen/−0 wie im Dokument gespeichert. `bulgePolylinePoints` bleibt (DXF-Import-Test). + Nicht in der Tauri-App geprüft. **Leistung nach der Zusammenführung (29.10.)** — erledigt damit die Offen-Punkte der Griffe/Objekt-Info: (a) **id-Suche indiziert:** der Positions-Index des Dokuments (`PosCache`) wird ab der ersten Suche gebaut (Listen ≥ 32), überlebt `add` am Ende und ist über `Lookup` (`Document::lookup`) auch für die Wurzel-Abfragen da — Griffe diff --git a/src-tauri/core/src/cmd_create.rs b/src-tauri/core/src/cmd_create.rs new file mode 100644 index 00000000..0514ec8f --- /dev/null +++ b/src-tauri/core/src/cmd_create.rs @@ -0,0 +1,1112 @@ +//! Zeichenbefehle im Kern ([K4] S3, vorher die Objekt-Literale in `commands/cmds/*.ts` und die +//! Werkzeug-Commits in `tools/tools.ts`): aus den Klickpunkten und Optionen eines Befehls entstehen hier +//! die neuen Elemente (Vorgaben aus Typen/Stilen, abgeleitete Felder, ids) samt der Live-Vorschau je +//! Mausschritt. Die Zustandsautomaten (Klicks, Tasten, Optionen) bleiben in der TS-Hülle. +//! +//! Drei Einstiege: +//! - [`ops`] — Ops des Commits (`cmdOps`/`doc_cmd_commit`, Anfrage `{cmd, …, ctx, stamp}`), +//! - [`preview`] — Vorschau-Formen je Mausschritt (`doc_create_preview`: Optionen als JSON, die Punkte +//! flach), dazu `ok` (würde ein Commit hier etwas erzeugen?) und einige Zahlen für HUD/Zustand, +//! - [`query`] — Treffer zwischen den Schritten (Host-Wand, Profil, Tangenten-Objekt …). +//! +//! Dazu die Gruppen-Zuordnung beim Zeichnen in einer betretenen Gruppe ([`group_ops`], vorher +//! `activeGroupOps` in `state/groupActions.ts`). +//! +//! Zahlen wie in JS (`jsnum`, `jsmath`, `js_fmt`), Rechenreihenfolge wie die frühere TS-Fassung; +//! Elemente mit der Schlüsselreihenfolge der früheren Objekt-Literale. + +use crate::cmd_transform::{IdGen, Shapes}; +use crate::grips::{arr, field, js_num, num_of, pt, truthy, xy}; +use crate::jsmath::hypot2; +use crate::jsnum; +use crate::ops::{id_of, Op}; +use kernel2d::{self as k, Vec2 as P}; +use serde_json::{json, Map, Value}; + +pub(crate) type V = (f64, f64); + +/// Mindestlänge/-grösse der meisten Befehle (Modell-Meter). +pub(crate) const EPS: f64 = 1e-6; +/// Vorgabe-Höhe, wenn das Geschoss keine hat. +const DEF_HEIGHT: f64 = 2.6; + +// ── Anfrage lesen ──────────────────────────────────────────────────────────── + +pub(crate) fn s_of<'a>(v: &'a Value, k: &str) -> &'a str { + v.get(k).and_then(Value::as_str).unwrap_or("") +} + +/// Zahl der Anfrage (fehlend = NaN, `null` = 0 wie `num_of`). +pub(crate) fn n_of(v: &Value, k: &str) -> f64 { + num_of(v.get(k)) +} + +/// Optionale Zahl (`null`/fehlend = keine). +pub(crate) fn opt_n(v: &Value, k: &str) -> Option { + match v.get(k) { + None | Some(Value::Null) => None, + x => Some(num_of(x)), + } +} + +pub(crate) fn b_of(v: &Value, k: &str) -> bool { + truthy(v.get(k)) +} + +/// Punkt der Anfrage: Paar `[x, y]` oder Objekt `{x, y}` (Zustands-Punkte der Hülle unverändert). +pub(crate) fn pair(x: &Value) -> V { + if x.is_object() { + return xy(x); + } + let n = |i: usize| x.get(i).map_or(f64::NAN, |c| num_of(Some(c))); + (n(0), n(1)) +} + +/// Punkt `[x, y]` der Anfrage. +pub(crate) fn p_of(v: &Value, k: &str) -> V { + v.get(k).map_or((f64::NAN, f64::NAN), pair) +} + +/// Optionaler Punkt (`null`/fehlend = keiner). +pub(crate) fn opt_p(v: &Value, k: &str) -> Option { + match v.get(k) { + None | Some(Value::Null) => None, + Some(x) => Some(pair(x)), + } +} + +/// Punktliste `[[x, y], …]` der Anfrage. +pub(crate) fn pts_of(v: &Value, k: &str) -> Vec { + arr(v.get(k)).iter().map(pair).collect() +} + +/// Flache Punkte `[x0, y0, …]` (Vorschau). +pub(crate) fn flat_pts(f: &[f64]) -> Vec { + f.chunks_exact(2).map(|c| (c[0], c[1])).collect() +} + +/// Kontext der Hülle: aktive Ebene/Geschoss, Kategorie, Wandtyp. +pub struct Ctx<'a> { + pub level: &'a str, + /// `level.floorHeight`, falls > 0 (sonst Vorgabe). + pub floor_height: Option, + pub cat: &'a str, + pub wall_type: &'a str, +} + +pub(crate) fn ctx_of(v: &Value) -> Ctx<'_> { + let c = v.get("ctx").unwrap_or(&Value::Null); + let fh = opt_n(c, "floorHeight").filter(|h| *h > 0.0); + Ctx { level: s_of(c, "level"), floor_height: fh, cat: s_of(c, "cat"), wall_type: s_of(c, "wallType") } +} + +// ── Werte bauen ────────────────────────────────────────────────────────────── + +pub(crate) fn pv(p: V) -> Value { + pt(p.0, p.1) +} + +pub(crate) fn pvs(pts: &[V]) -> Value { + Value::Array(pts.iter().map(|p| pv(*p)).collect()) +} + +pub(crate) fn s(x: &str) -> Value { + Value::String(x.into()) +} + +/// Objekt in der gegebenen Schlüsselreihenfolge. +pub(crate) fn obj(fields: Vec<(&str, Value)>) -> Value { + let mut m = Map::with_capacity(fields.len()); + for (k, v) in fields { + m.insert(k.into(), v); + } + Value::Object(m) +} + +pub(crate) fn add_op(collection: &str, items: Vec) -> Vec { + if items.is_empty() { + return Vec::new(); + } + vec![Op::Add { collection: collection.into(), items, at: None }] +} + +/// `removeItems(p, collection, ids)`: nur vorhandene ids, je einmal. +pub(crate) fn remove_op(root: &Map, collection: &str, ids: &[&str]) -> Vec { + let mut drop: Vec = Vec::new(); + for e in arr(root.get(collection)) { + if let Some(id) = id_of(e) { + if ids.contains(&id) && !drop.iter().any(|d| d == id) { + drop.push(id.into()); + } + } + } + if drop.is_empty() { + Vec::new() + } else { + vec![Op::Remove { collection: collection.into(), ids: drop }] + } +} + +// ── Geometrie-Helfer (wie die früheren TS-Einzeiler) ───────────────────────── + +pub(crate) fn seg_len(a: V, b: V) -> f64 { + hypot2(b.0 - a.0, b.1 - a.1) +} + +/// `normalize` aus `model/geometry.ts` (`len || 1`). +pub(crate) fn normalize(a: V) -> V { + let l = hypot2(a.0, a.1); + let l = if l == 0.0 || l.is_nan() { 1.0 } else { l }; + (a.0 / l, a.1 / l) +} + +/// Die vier Ecken eines Wandbands (`wallCorners`). +fn wall_corners(start: V, end: V, thickness: f64) -> [V; 4] { + let h = thickness / 2.0; + let u = normalize((end.0 - start.0, end.1 - start.1)); + let n = (-u.1, u.0); + let off = |p: V, s: f64| (p.0 + n.0 * s, p.1 + n.1 * s); + [off(start, h), off(end, h), off(end, -h), off(start, -h)] +} + +/// Achsparalleles Rechteck aus zwei Gegenecken (CCW ab min). +pub(crate) fn rect_corners(a: V, b: V) -> [V; 4] { + let (x0, x1) = (jsnum::min(a.0, b.0), jsnum::max(a.0, b.0)); + let (y0, y1) = (jsnum::min(a.1, b.1), jsnum::max(a.1, b.1)); + [(x0, y0), (x1, y0), (x1, y1), (x0, y1)] +} + +/// `n` Punkte auf einem Kreis (`t = (i / n)·2π`, wie die Vorschau-Kreise der Befehle). +pub(crate) fn circle_pts(c: V, r: f64, n: usize) -> Vec { + (0..n) + .map(|i| { + let t = (i as f64 / n as f64) * std::f64::consts::PI * 2.0; + (c.0 + r * jsnum::cos(t), c.1 + r * jsnum::sin(t)) + }) + .collect() +} + +pub(crate) fn to_p(p: V) -> P { + P::new(p.0, p.1) +} + +/// Gerade Kanten eines Rings/Zugs (`polylineEdges`). +pub(crate) fn polyline_edges(pts: &[V], closed: bool) -> Vec<(V, V)> { + let mut out: Vec<(V, V)> = pts.windows(2).map(|w| (w[0], w[1])).collect(); + if closed && pts.len() > 2 { + out.push((pts[pts.len() - 1], pts[0])); + } + out +} + +pub(crate) fn point_segment_distance(p: V, a: V, b: V) -> f64 { + k::point_segment_distance(to_p(p), to_p(a), to_p(b)) +} + +// ── Projekt lesen ──────────────────────────────────────────────────────────── + +/// Gibt es die Kategorie `code` irgendwo im Ebenen-Baum (`layers`, rekursiv über `children`)? +pub(crate) fn has_category(root: &Map, code: &str) -> bool { + fn walk(list: &[Value], code: &str) -> bool { + list.iter().any(|c| field(c, "code").and_then(Value::as_str) == Some(code) || walk(arr(field(c, "children")), code)) + } + walk(arr(root.get("layers")), code) +} + +/// Kategorie `code`, falls vorhanden, sonst die aktive. +pub(crate) fn category_or(root: &Map, code: &str, ctx: &Ctx) -> Value { + s(if has_category(root, code) { code } else { ctx.cat }) +} + +/// Farbe der Kategorie `code` (erste im Baum, Tiefensuche wie `flat.find`), sonst `def`. +fn category_color(root: &Map, code: &str, def: &str) -> Value { + fn walk<'a>(list: &'a [Value], code: &str) -> Option<&'a Value> { + for c in list { + if field(c, "code").and_then(Value::as_str) == Some(code) { + return Some(c); + } + if let Some(f) = walk(arr(field(c, "children")), code) { + return Some(f); + } + } + None + } + match walk(arr(root.get("layers")), code).and_then(|c| field(c, "color")) { + None | Some(Value::Null) => s(def), + Some(c) => c.clone(), + } +} + +pub(crate) fn wall_types(root: &Map) -> &[Value] { + arr(root.get("wallTypes")) +} + +/// Aktiver Wandtyp (Fallback: erster des Projekts). +fn active_wall_type<'a>(root: &'a Map, ctx: &Ctx) -> Option<&'a Value> { + let list = wall_types(root); + list.iter().find(|t| id_of(t) == Some(ctx.wall_type)).or(list.first()) +} + +/// id des aktiven Wandtyps (Fallback: die id aus dem Kontext). +fn active_wall_type_id(root: &Map, ctx: &Ctx) -> Value { + match active_wall_type(root, ctx) { + Some(t) => field(t, "id").cloned().unwrap_or(Value::Null), + None => s(ctx.wall_type), + } +} + +/// Gesamtdicke eines Wand-/Deckentyps (`wallTypeThickness`: Summe der Schichten). +pub(crate) fn type_thickness(t: &Value) -> f64 { + arr(field(t, "layers")).iter().fold(0.0, |sum, l| sum + num_of(field(l, "thickness"))) +} + +fn layers_len(t: &Value) -> usize { + arr(field(t, "layers")).len() +} + +pub(crate) fn find<'a>(root: &'a Map, collection: &str, id: &str) -> Option<&'a Value> { + arr(root.get(collection)).iter().find(|e| id_of(e) == Some(id)) +} + +pub(crate) fn level_of(e: &Value) -> Option<&str> { + field(e, "levelId").and_then(Value::as_str) +} + +pub(crate) fn floor_of(e: &Value) -> Option<&str> { + field(e, "floorId").and_then(Value::as_str) +} + +// ═════════════════════════════════════════════════════════════════════════════ +// Bauteile: Wand, Decke, Raum, Treppe, Öffnung, Dach, Stütze, Extrusion +// ═════════════════════════════════════════════════════════════════════════════ + +/// Kleinste sinnvolle Wanddicke (Dicke-Feld des Wand-Befehls). +const MIN_THICKNESS: f64 = 0.01; + +/// Wirksame Banddicke der Wand-Vorschau: gelockte Dicke (nur einschichtig) oder Wandtyp-Dicke. +fn wall_thickness(root: &Map, ctx: &Ctx, thick: Option) -> f64 { + let wt = active_wall_type(root, ctx); + if let (Some(t), Some(w)) = (thick, wt) { + if t >= MIN_THICKNESS && layers_len(w) == 1 { + return t; + } + } + wt.map_or(0.2, type_thickness) +} + +/// Einschichtiger Wandtyp mit Dicke `thickness` (gleiches Bauteil wie `base`): vorhanden oder neu. +fn wall_type_for_thickness(root: &Map, base: &Value, thickness: f64, ids: &mut IdGen) -> (Vec, Value) { + let layer0 = &arr(field(base, "layers"))[0]; + let component = field(layer0, "componentId"); + let near = |a: f64, b: f64| (a - b).abs() < 1e-4; + let same_component = |c: Option<&Value>| match (c, component) { + (None, None) => true, + (Some(a), Some(b)) => a == b && !a.is_object() && !a.is_array(), + _ => false, + }; + for t in wall_types(root) { + let ls = arr(field(t, "layers")); + if ls.len() == 1 && same_component(field(&ls[0], "componentId")) && near(num_of(field(&ls[0], "thickness")), thickness) { + return (Vec::new(), field(t, "id").cloned().unwrap_or(Value::Null)); + } + } + let name = match field(base, "name") { + Some(n) => crate::js_fmt::js_string(n), + None => "undefined".into(), + }; + let id = ids.next("WT"); + let mut layer = Vec::new(); + if let Some(c) = component { + layer.push(("componentId", c.clone())); + } + layer.push(("thickness", js_num(thickness))); + let nt = obj(vec![ + ("id", s(&id)), + ("name", s(&format!("{name} {} cm", crate::js_fmt::to_fixed(thickness * 100.0, 0)))), + ("layers", Value::Array(vec![obj(layer)])), + ]); + (add_op("wallTypes", vec![nt]), s(&id)) +} + +/// Wand-Befehl: je Achssegment eine Wand des aktiven Typs (Null-Strecken übersprungen); eine gelockte +/// Dicke (einschichtig) wählt/erzeugt den passenden Wandtyp. +fn wall_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let pts = pts_of(v, "pts"); + let height = ctx.floor_height.unwrap_or(DEF_HEIGHT); + let mut type_ops = Vec::new(); + let mut type_id = active_wall_type_id(root, ctx); + if let (Some(base), Some(t)) = (active_wall_type(root, ctx), opt_n(v, "thick")) { + if layers_len(base) == 1 && t >= MIN_THICKNESS && (t - type_thickness(base)).abs() > 1e-4 { + let (o, id) = wall_type_for_thickness(root, base, t, ids); + type_ops = o; + type_id = id; + } + } + let mut walls = Vec::new(); + for w in pts.windows(2) { + let (a, b) = (w[0], w[1]); + if seg_len(a, b) < EPS { + continue; + } + walls.push(obj(vec![ + ("id", s(&ids.next("W"))), + ("type", s("wall")), + ("floorId", s(ctx.level)), + ("categoryCode", s(ctx.cat)), + ("start", pv(a)), + ("end", pv(b)), + ("wallTypeId", type_id.clone()), + ("height", js_num(height)), + ])); + } + if walls.is_empty() { + return Vec::new(); + } + type_ops.extend(add_op("walls", walls)); + type_ops +} + +/// Wand-Vorschau: je Segment das Band (Dicke wie beim Commit) und die Achse. +fn wall_preview(root: &Map, v: &Value, ctx: &Ctx, pts: &[V], out: &mut Shapes) { + let t = wall_thickness(root, ctx, opt_n(v, "thick")); + for w in pts.windows(2) { + let (a, b) = (w[0], w[1]); + if seg_len(a, b) < EPS { + continue; + } + out.poly(&wall_corners(a, b, t)); + out.line(a, b); + } +} + +/// `normalizeOutline`: doppelte Folgepunkte und den schliessenden Duplikat-Punkt weg, CCW erzwingen. +fn normalize_outline(pts: &[V]) -> Option> { + let eq = |a: V, b: V| (a.0 - b.0).abs() <= k::EPS && (a.1 - b.1).abs() <= k::EPS; + let mut clean: Vec = Vec::new(); + for p in pts { + if clean.last().is_none_or(|l| !eq(*l, *p)) { + clean.push(*p); + } + } + if clean.len() > 1 && eq(clean[0], clean[clean.len() - 1]) { + clean.pop(); + } + if clean.len() < 3 { + return None; + } + let ps: Vec

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

= pts.iter().map(|p| to_p(*p)).collect(); + k::signed_area(&ps).abs() +} + +/// Decke aus einem geschlossenen Umriss (entartet → nichts). +fn ceiling_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let Some(outline) = normalize_outline(&pts_of(v, "pts")) else { return Vec::new() }; + if abs_area(&outline) < 1e-4 { + return Vec::new(); + } + add_op( + "ceilings", + vec![obj(vec![ + ("id", s(&ids.next("C"))), + ("type", s("ceiling")), + ("floorId", s(ctx.level)), + ("categoryCode", category_or(root, "30", ctx)), + ("outline", pvs(&outline)), + ("wallTypeId", active_wall_type_id(root, ctx)), + ])], + ) +} + +/// Wände des Geschosses als `[n, (ax, ay, bx, by, dicke)…]` für die Raumerkennung. +fn floor_walls_flat(root: &Map, level: &str) -> Vec { + let types = wall_types(root); + let mut out = vec![0.0]; + let mut n = 0; + for w in arr(root.get("walls")) { + if floor_of(w) != Some(level) { + continue; + } + let tid = field(w, "wallTypeId").and_then(Value::as_str); + let wt = types.iter().find(|t| id_of(t) == tid); + let (a, b) = (xy(field(w, "start").unwrap_or(&Value::Null)), xy(field(w, "end").unwrap_or(&Value::Null))); + out.extend([a.0, a.1, b.0, b.1, wt.map_or(0.2, type_thickness)]); + n += 1; + } + out[0] = n as f64; + out +} + +/// Lichter Umriss der Zelle um `at` (Raum „innen“), `None` = keine geschlossene Zelle. +fn room_inside(root: &Map, level: &str, at: V) -> Option> { + let f = crate::room_boundary::from_point(at.0, at.1, &floor_walls_flat(root, level), 0.05, true); + if f.is_empty() { + return None; + } + let n = f[0] as usize; + Some((0..n).map(|i| (f[1 + 2 * i], f[2 + 2 * i])).collect()) +} + +/// Raum aus Umriss (Modus „manuell“: `pts`; „innen“: `at` → Zelle). +fn room_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let boundary = match opt_p(v, "at") { + Some(at) => match room_inside(root, ctx.level, at) { + Some(b) if b.len() >= 3 => b, + _ => return Vec::new(), + }, + None => pts_of(v, "pts"), + }; + let ring: Vec<[f64; 2]> = boundary.iter().map(|p| [p.0, p.1]).collect(); + let e = crate::room_area::evaluate(&ring, 0.0); + if boundary.len() < 3 || e.gross < 1e-4 { + return Vec::new(); + } + let code = if has_category(root, "60") { "60" } else { ctx.cat }; + let name = format!("Raum {}", arr(root.get("rooms")).len() + 1); + let doc = json!({ "version": 1, "paragraphs": [{ "runs": [{ "text": name, "marks": {} }], "align": "center" }] }); + add_op( + "rooms", + vec![obj(vec![ + ("id", s(&ids.next("RM"))), + ("type", s("room")), + ("floorId", s(ctx.level)), + ("categoryCode", s(code)), + ("siaCategory", s("HNF")), + ("name", s(&name)), + ("boundary", pvs(&boundary)), + ("color", category_color(root, code, "#5a7a9a")), + ("stampAnchor", pt(e.centroid[0], e.centroid[1])), + ("stampDoc", doc), + ])], + ) +} + +// ── Treppe ─────────────────────────────────────────────────────────────────── + +const MIN_STEPS: f64 = 2.0; + +/// Stufenzahl aus Soll-Auftritt und Lauflänge (`stepsFromTread`; mindestens 0.24 m Auftritt). +pub fn steps_from_tread(auftritt: f64, run_length: f64) -> f64 { + let a = jsnum::max(0.05, auftritt); + let raw = jsnum::round(run_length / a); + let max_by_run = if run_length > 0.0 { jsnum::max(MIN_STEPS, (run_length / 0.24).floor() + 1.0) } else { raw }; + jsnum::max(MIN_STEPS, jsnum::min(raw, max_by_run)) +} + +/// Aufgelöste Treppe des Befehls (`buildStair`): Felder in der Reihenfolge des früheren Literals. +struct StairBuilt { + fields: Vec<(&'static str, Value)>, + params: [f64; 16], + rise: f64, + steps: f64, +} + +fn build_stair(root: &Map, v: &Value, ctx: &Ctx, id: Value) -> StairBuilt { + let shape = s_of(v, "shape"); + let start = p_of(v, "start"); + let cursor = p_of(v, "cursor"); + let width = n_of(v, "width"); + let referenz = s_of(v, "referenz"); + let rise = opt_n(v, "rise").unwrap_or(ctx.floor_height.unwrap_or(DEF_HEIGHT)); + let d = (cursor.0 - start.0, cursor.1 - start.1); + let dist = jsnum::max(0.1, hypot2(d.0, d.1)); + let dir = if dist > EPS { + let l = hypot2(d.0, d.1); + let l = if l == 0.0 || l.is_nan() { 1e-9 } else { l }; + (d.0 / l, d.1 / l) + } else { + (1.0, 0.0) + }; + let run_length = if shape == "spiral" { jsnum::max(0.5, dist) } else { dist }; + let steps = if s_of(v, "treadMode") == "with" { + steps_from_tread(n_of(v, "auftritt"), run_length) + } else { + opt_n(v, "steps").unwrap_or_else(|| crate::stair::default_step_count(rise, run_length) as f64) + }; + let up = b_of(v, "up"); + let mut f: Vec<(&'static str, Value)> = vec![ + ("id", id), + ("type", s("stair")), + ("floorId", s(ctx.level)), + ("categoryCode", category_or(root, "40", ctx)), + ("shape", s(shape)), + ("start", pv(start)), + ("dir", pv(dir)), + ("runLength", js_num(run_length)), + ("width", js_num(width)), + ("referenz", s(referenz)), + ("totalRise", js_num(rise)), + ("stepCount", js_num(steps)), + ("up", Value::Bool(up)), + ]; + let nan = f64::NAN; + let form = match shape { + "L" => 1.0, + "spiral" => 2.0, + _ => 0.0, + }; + let refz = match referenz { + "links" => 1.0, + "rechts" => 2.0, + _ => 0.0, + }; + let mut params = [form, start.0, start.1, dir.0, dir.1, run_length, nan, nan, nan, nan, nan, nan, width, steps, if up { 1.0 } else { 0.0 }, refz]; + if shape == "L" { + f.push(("run2Length", js_num(run_length))); + f.push(("turn", js_num(1.0))); + params[6] = run_length; + params[7] = 1.0; + } else if shape == "spiral" { + f.push(("center", pv(start))); + f.push(("radius", js_num(dist))); + f.push(("sweep", js_num(270.0))); + // Startpunkt am äusseren Rand: die Lauflinie beginnt hier (Schlüssel bleibt an seiner Stelle). + f[5].1 = pv(cursor); + params[1] = cursor.0; + params[2] = cursor.1; + params[8] = start.0; + params[9] = start.1; + params[10] = dist; + params[11] = 270.0; + } + StairBuilt { fields: f, params, rise, steps } +} + +fn stair_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let b = build_stair(root, v, ctx, s(&ids.next("ST"))); + add_op("stairs", vec![obj(b.fields)]) +} + +/// Treppen-Vorschau: Tritte, Podest, Lauflinie; `info = [Stufenzahl]`. +fn stair_preview(root: &Map, v: &Value, ctx: &Ctx, out: &mut Shapes, info: &mut Vec) { + let b = build_stair(root, v, ctx, Value::Null); + info.push(b.steps); + let f = crate::stair::geometry(&b.params, b.rise); + if f.len() < 4 { + return; + } + let at = |i: usize| (f[i], f[i + 1]); + let pts_at = |i: usize, n: usize| -> Vec { (0..n).map(|k| at(i + 2 * k)).collect() }; + let n_treads = f[3] as usize; + let mut i = 4; + for _ in 0..n_treads { + out.poly(&pts_at(i + 3, 4)); + i += 11; + } + let nl = f[i]; + i += 1; + if nl >= 0.0 { + let n = nl as usize; + out.poly(&pts_at(i, n)); + i += 2 * n; + } + let n_run = f[i] as usize; + i += 1; + if n_run >= 2 { + out.poly_open(&pts_at(i, n_run)); + } +} + +// ── Öffnung ────────────────────────────────────────────────────────────────── + +/// Pick-Toleranz der Host-Wand. +const WALL_PICK_DIST: f64 = 0.6; + +/// Auf die Wandachse projizierter Fusspunkt: (Abstand vom Wandanfang, Fusspunkt, Distanz). +fn project_onto_wall(start: V, end: V, p: V) -> (f64, V, f64) { + let ax = (end.0 - start.0, end.1 - start.1); + let d = ax.0 * ax.0 + ax.1 * ax.1; + let len2 = if d == 0.0 || d.is_nan() { 1e-9 } else { d }; + let raw = ((p.0 - start.0) * ax.0 + (p.1 - start.1) * ax.1) / len2; + let t = jsnum::max(0.0, jsnum::min(1.0, raw)); + let foot = (start.0 + ax.0 * t, start.1 + ax.1 * t); + let dist = hypot2(p.0 - foot.0, p.1 - foot.1); + (t * len2.sqrt(), foot, dist) +} + +/// Nächste Wand des Geschosses zum Klickpunkt (innerhalb der Toleranz). +fn pick_wall<'a>(root: &'a Map, level: &str, p: V) -> Option<(&'a Value, V, V)> { + let mut best: Option<(&Value, V, V, f64)> = None; + for w in arr(root.get("walls")) { + if floor_of(w) != Some(level) { + continue; + } + let (a, b) = (xy(field(w, "start").unwrap_or(&Value::Null)), xy(field(w, "end").unwrap_or(&Value::Null))); + let (_, _, dist) = project_onto_wall(a, b, p); + if dist <= WALL_PICK_DIST && best.is_none_or(|x| dist < x.3) { + best = Some((w, a, b, dist)); + } + } + best.map(|(w, a, b, _)| (w, a, b)) +} + +/// Öffnung in eine Wand (`start`/`end` der Host-Wand beim Picken, `pos` = Abstand vom Wandanfang). +fn opening_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let (st, en) = (p_of(v, "start"), p_of(v, "end")); + let len = hypot2(en.0 - st.0, en.1 - st.1); + let width = jsnum::max(0.1, jsnum::min(n_of(v, "width"), len)); + let position = jsnum::max(0.0, jsnum::min(n_of(v, "pos"), jsnum::max(0.0, len - width))); + let door = s_of(v, "kind") == "door"; + let lib = arr(root.get(if door { "doorTypes" } else { "windowTypes" })); + let type_id = lib.first().and_then(|t| field(t, "id")).filter(|id| truthy(Some(id))); + let mut f = vec![ + ("id", s(&ids.next("O"))), + ("type", s("opening")), + ("hostWallId", s(s_of(v, "wall"))), + ("categoryCode", category_or(root, "21", ctx)), + ("kind", s(s_of(v, "kind"))), + ("position", js_num(position)), + ("width", js_num(width)), + ("height", js_num(n_of(v, "height"))), + ("sillHeight", js_num(if door { 0.0 } else { n_of(v, "sill") })), + ]; + if let Some(t) = type_id { + f.push(("typeId", t.clone())); + } + if door { + f.push(("hinge", s(s_of(v, "hinge")))); + f.push(("swing", s(s_of(v, "side")))); + f.push(("openingDir", s(s_of(v, "dir")))); + f.push(("swingAngle", js_num(n_of(v, "swingAngle")))); + } + add_op("openings", vec![obj(f)]) +} + +/// Öffnungs-Vorschau (Lücken-Balken + Symbol). `pos` fehlt → aus dem Cursor projiziert. +/// `info = [pos, von, ax, ay, bx, by, mx, my]` (Position für den Zustand, HUD/Stützpunkte). +fn opening_preview(v: &Value, cursor: Option, out: &mut Shapes, info: &mut Vec) { + let (st, en) = (p_of(v, "start"), p_of(v, "end")); + let pos = match (opt_n(v, "pos"), cursor) { + (Some(p), _) => p, + (None, Some(c)) => project_onto_wall(st, en, c).0, + (None, None) => 0.0, + }; + let ax = (en.0 - st.0, en.1 - st.1); + let l = hypot2(ax.0, ax.1); + let len = if l == 0.0 || l.is_nan() { 1e-9 } else { l }; + let u = (ax.0 / len, ax.1 / len); + let n = (-u.1, u.0); + let width = n_of(v, "width"); + let from = jsnum::max(0.0, jsnum::min(pos, len)); + let to = jsnum::max(from, jsnum::min(from + width, len)); + let a = (st.0 + u.0 * from, st.1 + u.1 * from); + let b = (st.0 + u.0 * to, st.1 + u.1 * to); + let half = 0.15; + let off = |p: V, s: f64| (p.0 + n.0 * s, p.1 + n.1 * s); + out.poly(&[off(a, half), off(b, half), off(b, -half), off(a, -half)]); + if s_of(v, "kind") == "door" { + let swing = if s_of(v, "side") == "left" { 1.0 } else { -1.0 }; + let dir = if s_of(v, "dir") == "in" { 1.0 } else { -1.0 }; + let hinge = if s_of(v, "hinge") == "start" { a } else { b }; + out.line(hinge, off(hinge, swing * dir * width)); + } else { + out.line(a, b); + } + let m = (to - from) / 2.0; + info.extend([pos, from, a.0, a.1, b.0, b.1, a.0 + u.0 * m, a.1 + u.1 * m]); +} + +// ── Dach, Stütze ───────────────────────────────────────────────────────────── + +fn roof_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let (a, b) = (p_of(v, "a"), p_of(v, "b")); + let (w, d) = ((b.0 - a.0).abs(), (b.1 - a.1).abs()); + if w < 0.1 || d < 0.1 { + return Vec::new(); + } + let shape = s_of(v, "shape"); + add_op( + "roofs", + vec![obj(vec![ + ("id", s(&ids.next("RF"))), + ("type", s("roof")), + ("floorId", s(ctx.level)), + ("categoryCode", category_or(root, "31", ctx)), + ("outline", pvs(&rect_corners(a, b))), + ("shape", s(shape)), + ("pitchDeg", js_num(if shape == "flach" { 0.0 } else { 30.0 })), + ("overhang", js_num(0.4)), + ("ridgeAxis", s(if w >= d { "x" } else { "y" })), + ("thickness", js_num(0.2)), + ])], + ) +} + +/// Stützen-Profil: rund (Durchmesser `size`) oder quadratisch (Kante `size`). +fn column_profile(v: &Value) -> Value { + let size = n_of(v, "size"); + if s_of(v, "kind") == "round" { + obj(vec![("kind", s("round")), ("radius", js_num(size / 2.0))]) + } else { + obj(vec![("kind", s("rect")), ("width", js_num(size)), ("depth", js_num(size))]) + } +} + +fn column_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + add_op( + "columns", + vec![obj(vec![ + ("id", s(&ids.next("column"))), + ("type", s("column")), + ("floorId", s(ctx.level)), + ("categoryCode", s("50")), + ("position", pv(p_of(v, "at"))), + ("profile", column_profile(v)), + ("rotation", js_num(0.0)), + ("height", js_num(ctx.floor_height.unwrap_or(DEF_HEIGHT))), + ])], + ) +} + +/// Grundriss einer Stütze ohne Drehung (`columnFootprint`: rund 32 Punkte, sonst 4 Ecken). +fn column_footprint(at: V, v: &Value) -> Vec { + let size = n_of(v, "size"); + if s_of(v, "kind") == "round" { + return circle_pts(at, size / 2.0, 32); + } + let (hw, hd) = (size / 2.0, size / 2.0); + let (cos, sin) = (jsnum::cos(0.0), jsnum::sin(0.0)); + [(-hw, -hd), (hw, -hd), (hw, hd), (-hw, hd)].iter().map(|p| (at.0 + p.0 * cos - p.1 * sin, at.1 + p.0 * sin + p.1 * cos)).collect() +} + +// ── Extrusion ──────────────────────────────────────────────────────────────── + +/// Profil-Pick-Toleranz. +const PROFILE_HIT_TOL: f64 = 0.25; + +/// Extrudierbares Profil einer Zeichnung: geschlossene Polylinie (≥ 3 Punkte), Rechteck, Kreis. +/// Punkte als JSON-Werte (Polylinie: die gespeicherten), dazu `circle` beim Kreis. +fn profile_of(d: &Value) -> Option<(Vec, Option)> { + let g = field(d, "geom")?; + match field(g, "shape").and_then(Value::as_str)? { + "polyline" => { + let pts = arr(field(g, "pts")); + (truthy(field(g, "closed")) && pts.len() >= 3).then(|| (pts.to_vec(), None)) + } + "rect" => { + let (mn, mx) = (field(g, "min")?, field(g, "max")?); + let (a, b) = (xy(mn), xy(mx)); + Some((vec![mn.clone(), pt(b.0, a.1), mx.clone(), pt(a.0, b.1)], None)) + } + "circle" => { + let c = field(g, "center")?; + let r = field(g, "r").cloned().unwrap_or(Value::Null); + let pts = circle_pts(xy(c), num_of(Some(&r)), 48).into_iter().map(pv).collect(); + Some((pts, Some(obj(vec![("center", c.clone()), ("r", r)])))) + } + _ => None, + } +} + +fn profile_json(d: &Value) -> Value { + match profile_of(d) { + Some((pts, circle)) => json!({ "id": id_of(d), "pts": pts, "circle": circle }), + None => Value::Null, + } +} + +/// Nächstes Profil (Kantenabstand < Toleranz) der Ebene am Punkt. +fn pick_profile<'a>(root: &'a Map, level: &str, at: V) -> Option<&'a Value> { + let mut best = None; + let mut best_d = PROFILE_HIT_TOL; + for d in arr(root.get("drawings2d")) { + if level_of(d) != Some(level) { + continue; + } + let Some((pts, _)) = profile_of(d) else { continue }; + let pts: Vec = pts.iter().map(xy).collect(); + for (a, b) in polyline_edges(&pts, true) { + let dd = point_segment_distance(at, a, b); + if dd < best_d { + best_d = dd; + best = Some(d); + } + } + } + best +} + +/// Extrusion eines Profils (die Quelle verschwindet, der Körper kommt dazu). +fn extrude_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let src = s_of(v, "source"); + let Some((pts, circle)) = find(root, "drawings2d", src).and_then(profile_of) else { return Vec::new() }; + let taper = n_of(v, "taper"); + let mut f = vec![ + ("id", s(&ids.next("extrude"))), + ("type", s("extrudedSolid")), + ("levelId", s(ctx.level)), + ("points", Value::Array(pts)), + ("height", js_num(n_of(v, "height"))), + ]; + if let Some(c) = circle { + f.push(("circle", c)); + } + if taper > 0.0 { + f.push(("taper", js_num(taper))); + } + let mut ops = remove_op(root, "drawings2d", &[src]); + ops.extend(add_op("extrudedSolids", vec![obj(f)])); + ops +} + +// ═════════════════════════════════════════════════════════════════════════════ +// Einstiege +// ═════════════════════════════════════════════════════════════════════════════ + +/// Ops eines Zeichenbefehls (`None` = kein Zeichenbefehl). +pub fn ops(root: &Map, v: &Value) -> Option> { + let ctx = ctx_of(v); + let mut ids = IdGen::new(s_of(v, "stamp")); + let ids = &mut ids; + Some(match s_of(v, "cmd") { + "wall" => wall_ops(root, v, &ctx, ids), + "ceiling" => ceiling_ops(root, v, &ctx, ids), + "room" => room_ops(root, v, &ctx, ids), + "stair" => stair_ops(root, v, &ctx, ids), + "opening" => opening_ops(root, v, &ctx, ids), + "roof" => roof_ops(root, v, &ctx, ids), + "column" => column_ops(v, &ctx, ids), + "extrude" => extrude_ops(root, v, &ctx, ids), + _ => return crate::cmd_draw::ops(root, v, &ctx, ids).or_else(|| crate::cmd_solid::ops(root, v, &ctx, ids)), + }) +} + +/// Ergebnis einer Vorschau: Formen, ob ein Commit hier etwas erzeugte, Zusatzzahlen (je Befehl). +#[derive(Default)] +pub struct Preview { + pub shapes: Shapes, + pub ok: bool, + pub info: Vec, +} + +impl Preview { + /// Flach: `[ok, nInfo, info…, Formen…]` (Formen wie `doc_cmd_preview`). + pub fn flat(self) -> Vec { + let mut out = Vec::with_capacity(2 + self.info.len() + self.shapes.buf.len()); + out.push(if self.ok { 1.0 } else { 0.0 }); + out.push(self.info.len() as f64); + out.extend(self.info); + out.extend(self.shapes.buf); + out + } +} + +/// Vorschau eines Zeichenbefehls: `v` = Optionen (`cmd`, …, `ctx`), `pts` = die Punkte flach (je Befehl +/// die gesetzten Punkte und zuletzt der Cursor). +pub fn preview(root: &Map, v: &Value, pts: &[f64]) -> Preview { + preview_req(root, &Req::new(v.clone()), pts) +} + +/// Gelesene Vorschau-Anfrage: die Optionen und, für den Mausschritt ohne Hash-Suchen, Befehl und Kontext. +pub struct Req { + pub v: Value, + cmd: String, + level: String, + floor_height: Option, + cat: String, + wall_type: String, +} + +impl Req { + pub fn new(v: Value) -> Req { + let c = ctx_of(&v); + let (level, floor_height, cat, wall_type) = (c.level.to_string(), c.floor_height, c.cat.to_string(), c.wall_type.to_string()); + Req { cmd: s_of(&v, "cmd").to_string(), v, level, floor_height, cat, wall_type } + } +} + +/// Wie [`preview`] mit gelesener Anfrage (Mausschritt: dieselbe Anfrage, neue Punkte). +pub fn preview_req(root: &Map, req: &Req, pts: &[f64]) -> Preview { + let v = &req.v; + let ctx = Ctx { level: &req.level, floor_height: req.floor_height, cat: &req.cat, wall_type: &req.wall_type }; + let pts = flat_pts(pts); + let mut p = Preview { ok: true, ..Default::default() }; + let out = &mut p.shapes; + match req.cmd.as_str() { + "wall" => wall_preview(root, v, &ctx, &pts, out), + "stair" => stair_preview(root, v, &ctx, out, &mut p.info), + "opening" => opening_preview(v, pts.first().copied(), out, &mut p.info), + "roomInside" => p.ok = pts.first().and_then(|at| room_inside(root, ctx.level, *at)).is_some_and(|b| b.len() >= 3), + "column" => { + if let Some(at) = pts.first() { + out.poly(&column_footprint(*at, v)); + } + } + "rect4" => { + // Aufgezogenes Rechteck (Dach, Deckenaussparung, Textrahmen …): erste Ecke + Cursor. + if pts.len() >= 2 { + out.poly(&rect_corners(pts[0], pts[1])); + } + } + _ => { + if !crate::cmd_draw::preview(root, v, &ctx, &pts, &mut p) && !crate::cmd_solid::preview(root, v, &pts, &mut p) { + p.ok = false; + } + } + } + p +} + +/// Treffer-Abfragen der Zeichenbefehle (`None` = keine Abfrage dieses Moduls). +pub fn query(root: &Map, v: &Value) -> Option> { + let at = p_of(v, "pt"); + let level = s_of(v, "level"); + Some(Ok(match s_of(v, "q") { + "pickWall" => match pick_wall(root, level, at) { + Some((w, a, b)) => json!({ "hit": { "id": id_of(w), "start": [js_num(a.0), js_num(a.1)], "end": [js_num(b.0), js_num(b.1)], "t": js_num(project_onto_wall(a, b, at).0) } }), + None => json!({ "hit": null }), + }, + "pickProfile" => json!({ "hit": pick_profile(root, level, at).map_or(Value::Null, profile_json) }), + "profile" => json!({ "hit": find(root, "drawings2d", s_of(v, "id")).map_or(Value::Null, profile_json) }), + _ => return crate::cmd_draw::query(root, v).or_else(|| crate::cmd_solid::query(root, v)).map(Ok), + })) +} + +// ── Gruppen-Zuordnung ──────────────────────────────────────────────────────── + +/// Mitglieds-Listen einer Gruppe und ihre Element-Listen (Reihenfolge wie `KEYS` in der Hülle). +const MEMBER_KEYS: [(&str, &str); 8] = [ + ("wallIds", "walls"), + ("drawingIds", "drawings2d"), + ("ceilingIds", "ceilings"), + ("roomIds", "rooms"), + ("stairIds", "stairs"), + ("columnIds", "columns"), + ("roofIds", "roofs"), + ("openingIds", "openings"), +]; + +/// Zeichnet man in einer betretenen Gruppe (`group` = innerste aktive Gruppe), werden die neu +/// eingefügten Elemente (`add`-Ops) ihr Mitglied: eine `replace`-Op der Gruppe mit den ergänzten Listen +/// (Vereinigung, erste Vorkommen in Reihenfolge). Leer ohne neue Elemente oder ohne die Gruppe. +pub fn group_ops(root: &Map, ops: &[Op], group: &str) -> Vec { + let Some(g) = find(root, "groups", group) else { return Vec::new() }; + let mut added: Vec<(&str, Vec)> = Vec::new(); + for (key, coll) in MEMBER_KEYS { + let existing = arr(root.get(coll)); + let mut ids: Vec = Vec::new(); + for op in ops { + if let Op::Add { collection, items, .. } = op { + if collection != coll { + continue; + } + for e in items { + if let Some(id) = id_of(e) { + if !existing.iter().any(|x| id_of(x) == Some(id)) { + ids.push(id.into()); + } + } + } + } + } + if !ids.is_empty() { + added.push((key, ids)); + } + } + if added.is_empty() { + return Vec::new(); + } + let mut m = g.as_object().cloned().unwrap_or_default(); + for (key, _) in MEMBER_KEYS { + let mut list: Vec = Vec::new(); + let mut push = |x: &Value| { + if !list.contains(x) { + list.push(x.clone()); + } + }; + arr(m.get(key)).iter().for_each(&mut push); + if let Some((_, ids)) = added.iter().find(|(k, _)| *k == key) { + ids.iter().for_each(|id| push(&Value::String(id.clone()))); + } + m.insert(key.into(), Value::Array(list)); + } + vec![Op::Replace { collection: "groups".into(), entity: Value::Object(m) }] +} + +#[cfg(test)] +mod tests { + use super::*; + + fn root(v: Value) -> Map { + v.as_object().unwrap().clone() + } + fn items(ops: &[Op], i: usize) -> Value { + ops[i].to_json()["items"].clone() + } + const CTX: &str = r#"{"level":"F1","floorHeight":3,"cat":"20","wallType":"WT1"}"#; + fn req(extra: Value) -> Value { + let mut v = extra; + v["ctx"] = serde_json::from_str(CTX).unwrap(); + v["stamp"] = json!("s"); + v + } + + #[test] + fn waende_je_segment_mit_typ_und_hoehe() { + let r = root(json!({"wallTypes": [{"id": "WT1", "name": "Beton", "layers": [{"componentId": "c", "thickness": 0.2}]}]})); + let o = ops(&r, &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0], [4, 0], [4, 3]], "thick": null}))).unwrap(); + let w = items(&o, 0); + assert_eq!(w.as_array().unwrap().len(), 2); + assert_eq!(w[0], json!({"id": "W-s-1", "type": "wall", "floorId": "F1", "categoryCode": "20", "start": {"x": 0, "y": 0}, "end": {"x": 4, "y": 0}, "wallTypeId": "WT1", "height": 3})); + // Gelockte Dicke → neuer einschichtiger Typ vor den Wänden. + let o = ops(&r, &req(json!({"cmd": "wall", "pts": [[0, 0], [4, 0]], "thick": 0.3}))).unwrap(); + assert_eq!(items(&o, 0)[0], json!({"id": "WT-s-1", "name": "Beton 30 cm", "layers": [{"componentId": "c", "thickness": 0.3}]})); + assert_eq!(items(&o, 1)[0]["wallTypeId"], "WT-s-1"); + } + + #[test] + fn treppe_stufen_aus_auftritt() { + assert_eq!(steps_from_tread(0.29, 3.0), 10.0); + assert_eq!(steps_from_tread(0.29, 3.1), 11.0); + assert_eq!(steps_from_tread(0.29, 0.01), MIN_STEPS); + assert_eq!(steps_from_tread(0.29, -1.0), MIN_STEPS); + assert_eq!(steps_from_tread(0.25, 2.5), 10.0); + // Auftritt nie unter 0.24 m. + let s = steps_from_tread(0.01, 10.0); + assert!(10.0 / (s - 1.0) >= 0.24 - 1e-9); + assert_eq!(steps_from_tread(0.29, 10.0 * 0.29), 10.0); + } + + #[test] + fn raum_innen_und_gruppe() { + let wt = json!([{"id": "WT1", "layers": [{"thickness": 0.2}]}]); + let wall = |id: &str, a: (f64, f64), b: (f64, f64)| json!({"id": id, "floorId": "F1", "wallTypeId": "WT1", "start": {"x": a.0, "y": a.1}, "end": {"x": b.0, "y": b.1}}); + let r = root(json!({"wallTypes": wt, "rooms": [], "layers": [{"code": "60", "color": "#abc"}], "walls": [ + wall("a", (0.0, 0.0), (5.0, 0.0)), wall("b", (5.0, 0.0), (5.0, 4.0)), wall("c", (5.0, 4.0), (0.0, 4.0)), wall("d", (0.0, 4.0), (0.0, 0.0))], + "groups": [{"id": "g", "name": "G", "wallIds": ["a"], "drawingIds": []}]})); + let o = ops(&r, &req(json!({"cmd": "room", "at": [2, 2]}))).unwrap(); + let room = &items(&o, 0)[0]; + assert_eq!(room["name"], "Raum 1"); + assert_eq!(room["color"], "#abc"); + assert_eq!(room["boundary"].as_array().unwrap().len(), 4); + let g = group_ops(&r, &o, "g"); + let e = g[0].to_json()["entity"].clone(); + assert_eq!(e["roomIds"], json!(["RM-s-1"])); + assert_eq!(e["wallIds"], json!(["a"])); + assert!(group_ops(&r, &o, "x").is_empty()); + assert!(group_ops(&r, &[], "g").is_empty()); + } + + #[test] + fn oeffnung_pick_und_vorschau() { + let r = root(json!({"walls": [{"id": "w", "floorId": "F1", "start": {"x": 0, "y": 0}, "end": {"x": 6, "y": 0}}], "windowTypes": [{"id": "FT"}]})); + let q = query(&r, &json!({"q": "pickWall", "level": "F1", "pt": [2, 0.3]})).unwrap().unwrap(); + assert_eq!(q["hit"]["id"], "w"); + assert_eq!(q["hit"]["t"], 2); + let o = ops(&r, &req(json!({"cmd": "opening", "wall": "w", "start": [0, 0], "end": [6, 0], "kind": "window", "pos": 5.5, "width": 1.2, "height": 1.2, "sill": 0.9}))).unwrap(); + let op = &items(&o, 0)[0]; + assert_eq!(op["position"], 4.8); + assert_eq!(op["typeId"], "FT"); + let p = preview(&r, &json!({"cmd": "opening", "start": [0, 0], "end": [6, 0], "kind": "window", "width": 1.2, "pos": null}), &[2.0, 1.0]); + assert_eq!(p.info[0], 2.0); + assert_eq!(p.shapes.count, 2); + } +} + diff --git a/src-tauri/core/src/cmd_draw.rs b/src-tauri/core/src/cmd_draw.rs new file mode 100644 index 00000000..f8804cba --- /dev/null +++ b/src-tauri/core/src/cmd_draw.rs @@ -0,0 +1,1278 @@ +//! 2D-Zeichenbefehle und Bemassung im Kern ([K4] S3, vorher `commands/cmds/{line,xline,ray,polyline,rect, +//! circle,arc,ellipse,polygon,spline,bezier,revcloud,wipeout,multiline,text,textbox,textpath,leader,kote, +//! detailref,scalebar,pointmarker,block,dimension,autodim}.ts`): die Geometrie der neuen Zeichnung aus den +//! Klickpunkten (Bögen, Kreise, Vielecke, Rundungen, Revisionswolke …), die Vorschau-Formen je Mausschritt +//! und die Treffer der Befehle (Tangenten-Objekt, Massketten). Einstieg über `cmd_create`. + +use crate::cmd_create::{ + add_op, b_of, circle_pts, find, level_of, n_of, normalize, obj, opt_n, opt_p, p_of, pair, point_segment_distance, polyline_edges, + pts_of, pv, pvs, s, s_of, seg_len, to_p, type_thickness, wall_types, Ctx, Preview, V, EPS, +}; +use crate::cmd_transform::{IdGen, Shapes}; +use crate::grips::{arr, field, js_num, num_of, num_or, with, xy}; +use crate::jsmath::hypot2; +use crate::jsnum; +use crate::ops::{id_of, Op}; +use kernel2d::{self as k, TangentTarget, Vec2 as P}; +use serde_json::{json, Map, Value}; +use std::f64::consts::PI; + +const TAU: f64 = PI * 2.0; + +fn of(p: P) -> V { + (p.x, p.y) +} + +fn dist(a: V, b: V) -> f64 { + hypot2(b.0 - a.0, b.1 - a.1) +} + +fn mid(a: V, b: V) -> V { + ((a.0 + b.0) / 2.0, (a.1 + b.1) / 2.0) +} + +fn angle(c: V, p: V) -> f64 { + jsnum::atan2(p.1 - c.1, p.0 - c.0) +} + +/// Neue 2D-Zeichnung `{id, type, levelId, categoryCode, geom}` (Farbe/Strich erbt die Ebene). +fn drawing(id: String, ctx: &Ctx, geom: Value) -> Value { + obj(vec![("id", s(&id)), ("type", s("drawing2d")), ("levelId", s(ctx.level)), ("categoryCode", s(ctx.cat)), ("geom", geom)]) +} + +/// id der Anfrage (Text-Befehle vergeben sie selbst, um das Element gleich zu fokussieren) oder neu. +fn id_or_new(v: &Value, ids: &mut IdGen) -> String { + match v.get("id").and_then(Value::as_str) { + Some(id) => id.into(), + None => ids.next("dr2d"), + } +} + +fn add_drawing(v: &Value, ctx: &Ctx, ids: &mut IdGen, geom: Value) -> Vec { + add_op("drawings2d", vec![drawing(id_or_new(v, ids), ctx, geom)]) +} + +/// Punkt der Anfrage als JSON-Wert, wie übergeben (Objekte `{x, y}` unverändert, Paare als Punkt). +fn pt_val(v: &Value, k: &str) -> Value { + match v.get(k) { + Some(x) if x.is_object() => x.clone(), + _ => pv(p_of(v, k)), + } +} + +fn pts_val(v: &Value, k: &str) -> Value { + Value::Array(arr(v.get(k)).iter().map(|x| if x.is_object() { x.clone() } else { pv(pair(x)) }).collect()) +} + +// ── Bögen (Bulge, Kreis durch Punkte …) ────────────────────────────────────── + +struct Arc { + c: V, + r: f64, + a0: f64, + a1: f64, +} + +/// Bogen aus `[cx, cy, r, a0, a1]` (leer = keiner), wie die Bindungen in `crate::bulge` (prüfen auf +/// endliche Eingaben, genau wie die frühere TS-Fassade). +fn arc_of(f: Vec) -> Option { + (f.len() >= 5).then(|| Arc { c: (f[0], f[1]), r: f[2], a0: f[3], a1: f[4] }) +} + +fn arc_through(a: V, t: V, b: V) -> Option { + arc_of(crate::bulge::arc_through_points(a.0, a.1, t.0, t.1, b.0, b.1)) +} + +fn bulge_through(a: V, t: V, b: V) -> f64 { + crate::bulge::through_point(a.0, a.1, t.0, t.1, b.0, b.1) +} + +fn bulge_points(pts: &[V], bulge: &[f64], closed: bool) -> Vec { + // Ohne echten Bogen die Eingabepunkte selbst (wie `bulgePolylinePoints`). + if !bulge.iter().any(|b| b.abs() > 1e-9) { + return pts.to_vec(); + } + let f: Vec = pts.iter().flat_map(|p| [p.0, p.1]).collect(); + crate::bulge::polyline_points(&f, bulge, closed).chunks_exact(2).map(|q| (q[0], q[1])).collect() +} + +// ═════════════════════════════════════════════════════════════════════════════ +// Polylinie (mit Bögen) +// ═════════════════════════════════════════════════════════════════════════════ + +/// Bulge eines Bogens, der in `a` tangential an `dir` anschliesst und in `b` endet (`tangentBulge`). +fn tangent_bulge(a: V, b: V, dir: Option) -> f64 { + let Some(dir) = dir else { return 0.0 }; + let (cx, cy) = (b.0 - a.0, b.1 - a.1); + let len = hypot2(cx, cy); + let dl = hypot2(dir.0, dir.1); + if len < EPS || dl < EPS { + return 0.0; + } + let (ux, uy) = (cx / len, cy / len); + let (dx, dy) = (dir.0 / dl, dir.1 / dl); + let theta = jsnum::atan2(ux * dy - uy * dx, ux * dx + uy * dy); + jsnum::tan(theta / 2.0) +} + +/// Richtung, in der das zuletzt gelegte Segment endet (`lastDirection`). +fn last_direction(points: &[V], bulges: &[f64]) -> Option { + let n = points.len(); + if n < 2 { + return None; + } + let (a, b) = (points[n - 2], points[n - 1]); + let bulge = bulges.get(n - 2).copied().unwrap_or(0.0); + let chord = (b.0 - a.0, b.1 - a.1); + if bulge.abs() < EPS { + return Some(chord); + } + let ang = -2.0 * jsnum::atan(bulge); + let (c, si) = (jsnum::cos(ang), jsnum::sin(ang)); + Some((chord.0 * c - chord.1 * si, chord.0 * si + chord.1 * c)) +} + +/// Art eines Segments: gerade (`0`), tangential (`1`) oder Bogen durch einen Punkt (`{x, y}`/`[x, y]`). +fn seg_bulge(seg: &Value, prev: V, pt: V, points: &[V], bulges: &[f64]) -> f64 { + if seg.is_object() || seg.is_array() { + return bulge_through(prev, pair(seg), pt); + } + if num_of(Some(seg)) == 1.0 { + return tangent_bulge(prev, pt, last_direction(points, bulges)); + } + 0.0 +} + +/// Bulges der gesetzten Segmente der Reihe nach (jeder Bogen kennt die Richtung seines Vorgängers). +fn poly_bulges(points: &[V], segs: &[Value]) -> Vec { + let mut bulges: Vec = Vec::new(); + for i in 1..points.len() { + let seg = segs.get(i - 1).unwrap_or(&Value::Null); + let b = seg_bulge(seg, points[i - 1], points[i], &points[..i], &bulges); + bulges.push(b); + } + bulges +} + +/// Polylinie: `pts`, `segs` (je Segment), `closed`, `closing` (Art des Schluss-Segments). +fn polyline_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let pts = pts_of(v, "pts"); + let closed = b_of(v, "closed"); + let mut bl = poly_bulges(&pts, arr(v.get("segs"))); + if let Some(c) = v.get("closing").filter(|c| !c.is_null()) { + // Schluss-Segment zum Start; schloss ein Klick nahe dem Start, endet der Bogen dort (`closingEnd`). + let (Some(first), Some(last)) = (pts.first(), pts.last()) else { return Vec::new() }; + let end = opt_p(v, "closingEnd").unwrap_or(*first); + let b = seg_bulge(c, *last, end, &pts, &bl); + bl.push(b); + } + let n = pts.len(); + let has_arc = bl.iter().any(|b| b.abs() > EPS); + let mut g = vec![("shape", s("polyline")), ("pts", pts_val(v, "pts")), ("closed", Value::Bool(closed))]; + if has_arc { + let keep = if closed { n } else { n.saturating_sub(1) }; + g.push(("bulge", Value::Array(bl.iter().take(keep).map(|b| js_num(*b)).collect()))); + } + add_drawing(v, ctx, ids, obj(g)) +} + +/// Polylinien-Vorschau: gesetzte Punkte + Cursor (letzter Punkt in `pts`, falls `cursor`), Bogen-Modus. +fn polyline_preview(v: &Value, pts: &[V], out: &mut Shapes) { + let has_cursor = b_of(v, "cursor"); + let points = if has_cursor && !pts.is_empty() { &pts[..pts.len() - 1] } else { pts }; + let bulges = poly_bulges(points, arr(v.get("segs"))); + let mut all_b = bulges.clone(); + if has_cursor { + let cursor = pts[pts.len() - 1]; + let pb = match points.last() { + Some(last) if b_of(v, "arc") => match opt_p(v, "through") { + Some(t) => bulge_through(*last, t, cursor), + None if b_of(v, "tangent") => tangent_bulge(*last, cursor, last_direction(points, &bulges)), + None => 0.0, + }, + _ => 0.0, + }; + all_b.push(pb); + } + let shown = bulge_points(pts, &all_b, false); + if b_of(v, "closed") && pts.len() >= 3 { + out.poly(&shown); + } else { + out.poly_open(&shown); + } +} + +// ═════════════════════════════════════════════════════════════════════════════ +// Rechteck (2-Punkt, 3-Punkt gedreht, Zentrum; Eck-Radius) +// ═════════════════════════════════════════════════════════════════════════════ + +fn rect_geom(a: V, b: V) -> (V, V) { + ((jsnum::min(a.0, b.0), jsnum::min(a.1, b.1)), (jsnum::max(a.0, b.0), jsnum::max(a.1, b.1))) +} + +fn center_geom(c: V, corner: V) -> (V, V) { + let (hx, hy) = ((corner.0 - c.0).abs(), (corner.1 - c.1).abs()); + ((c.0 - hx, c.1 - hy), (c.0 + hx, c.1 + hy)) +} + +fn corners_of(mn: V, mx: V) -> [V; 4] { + [mn, (mx.0, mn.1), mx, (mn.0, mx.1)] +} + +/// Vier Ecken des gedrehten Rechtecks aus Basiskante a→b und Höhenpunkt p (`rotatedCorners`). +fn rotated_corners(a: V, b: V, p: V) -> [V; 4] { + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let len = hypot2(dx, dy); + if len < EPS { + return [a, b, b, a]; + } + let (nx, ny) = (-dy / len, dx / len); + let h = (p.0 - a.0) * nx + (p.1 - a.1) * ny; + [a, b, (b.0 + nx * h, b.1 + ny * h), (a.0 + nx * h, a.1 + ny * h)] +} + +fn rise_from(a: V, b: V, p: V) -> f64 { + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let len = hypot2(dx, dy); + if len < EPS { + return 0.0; + } + (p.0 - a.0) * (-dy / len) + (p.1 - a.1) * (dx / len) +} + +/// Ecken mit Radius `r` runden (`roundedRectPts`): Tangentenpunkte + Bulge je Ecke, `None` = scharf. +fn rounded_rect(corners: &[V], r: f64) -> Option<(Vec, Vec)> { + if r < EPS { + return None; + } + let n = corners.len(); + let mut max_r = f64::INFINITY; + for i in 0..n { + max_r = jsnum::min(max_r, seg_len(corners[i], corners[(i + 1) % n]) / 2.0); + } + let rr = jsnum::min(r, max_r - EPS); + if rr < EPS { + return None; + } + let mut pts = Vec::new(); + let mut bulge = Vec::new(); + for i in 0..n { + let (prev, cur, next) = (corners[(i + n - 1) % n], corners[i], corners[(i + 1) % n]); + let f = k::fillet_corner(to_p(cur), to_p(prev), to_p(next), rr)?; + let (dx, dy) = (cur.0 - f.center.x, cur.1 - f.center.y); + let dl = hypot2(dx, dy); + let dl = if dl == 0.0 || dl.is_nan() { 1.0 } else { dl }; + let m = (f.center.x + (dx / dl) * rr, f.center.y + (dy / dl) * rr); + let (ta, tb) = (of(f.tangent_a), of(f.tangent_b)); + pts.push(ta); + pts.push(tb); + bulge.push(bulge_through(ta, m, tb)); + bulge.push(0.0); + } + Some((pts, bulge)) +} + +fn rounded_geom(corners: &[V], r: f64) -> Option { + let (pts, bulge) = rounded_rect(corners, r)?; + Some(obj(vec![ + ("shape", s("polyline")), + ("pts", pvs(&pts)), + ("closed", Value::Bool(true)), + ("bulge", Value::Array(bulge.iter().map(|b| js_num(*b)).collect())), + ])) +} + +/// Rechteck: `method` (corner/three/center), `a`, `b`, `c` (3-Punkt), `radius`. +fn rect_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let (a, b) = (p_of(v, "a"), p_of(v, "b")); + let r = n_of(v, "radius"); + let geom = match s_of(v, "method") { + "three" => { + let c = rotated_corners(a, b, p_of(v, "c")); + if r >= EPS { + rounded_geom(&c, r) + } else if seg_len(c[0], c[1]) < EPS || seg_len(c[1], c[2]) < EPS { + None + } else { + // Basis-Ecken sind die Klickpunkte selbst. + let pts = vec![pt_val(v, "a"), pt_val(v, "b"), pv(c[2]), pv(c[3])]; + Some(obj(vec![("shape", s("polyline")), ("pts", Value::Array(pts)), ("closed", Value::Bool(true))])) + } + } + m => { + let (mn, mx) = if m == "center" { center_geom(a, b) } else { rect_geom(a, b) }; + if r >= EPS { + rounded_geom(&corners_of(mn, mx), r) + } else if mx.0 - mn.0 < EPS || mx.1 - mn.1 < EPS { + None + } else { + Some(obj(vec![("shape", s("rect")), ("min", pv(mn)), ("max", pv(mx))])) + } + } + }; + geom.map_or_else(Vec::new, |g| add_drawing(v, ctx, ids, g)) +} + +/// Rechteck-Vorschau (`pts` = a, [b], Cursor): Ecken (gerundet tesselliert); `info = [v0x, v0y, höhe]`. +fn rect_preview(v: &Value, pts: &[V], out: &mut Shapes, info: &mut Vec) { + let r = n_of(v, "radius"); + let corners = match (s_of(v, "method"), pts) { + ("three", [a, b, c]) => { + info.extend([a.0, a.1, rise_from(*a, *b, *c).abs()]); + rotated_corners(*a, *b, *c) + } + ("center", [a, c]) => { + let (mn, mx) = center_geom(*a, *c); + info.extend([mn.0, mn.1, 0.0]); + corners_of(mn, mx) + } + (_, [a, c]) => { + let (mn, mx) = rect_geom(*a, *c); + info.extend([mn.0, mn.1, 0.0]); + corners_of(mn, mx) + } + _ => return, + }; + match rounded_rect(&corners, r) { + Some((p, b)) => out.poly(&bulge_points(&p, &b, true)), + None => out.poly(&corners), + } +} + +// ═════════════════════════════════════════════════════════════════════════════ +// Kreis (Mittelpunkt, 2-Punkt, 3-Punkt, Tangente-Tangente-Radius) +// ═════════════════════════════════════════════════════════════════════════════ + +/// Pick-Toleranz des Tangenten-Objekts. +const TTR_HIT_TOL: f64 = 0.3; + +fn in_arc_span(a0: f64, a1: f64, ang: f64) -> bool { + let norm = |x: f64| ((x % TAU) + TAU) % TAU; + let sw = norm(a1 - a0); + let sweep = if sw == 0.0 || sw.is_nan() { TAU } else { sw }; + norm(ang - a0) <= sweep + 1e-6 +} + +/// Gerade Kanten einer Form für die Tangenten-Wahl (Bogen-Segmente ausgenommen). +fn straight_edges(g: &Value) -> Vec<(V, V)> { + let p = |k: &str| xy(field(g, k).unwrap_or(&Value::Null)); + match field(g, "shape").and_then(Value::as_str) { + Some("line") => vec![(p("a"), p("b"))], + Some("rect") => { + let (mn, mx) = (p("min"), p("max")); + polyline_edges(&corners_of(mn, mx), true) + } + Some("polyline") => { + let pts: Vec = arr(field(g, "pts")).iter().map(xy).collect(); + let bulge = arr(field(g, "bulge")); + polyline_edges(&pts, crate::grips::truthy(field(g, "closed"))) + .into_iter() + .enumerate() + .filter(|(i, _)| num_or(bulge.get(*i), 0.0).abs() <= EPS) + .map(|(_, e)| e) + .collect() + } + _ => Vec::new(), + } +} + +fn target_json(t: &TangentTarget) -> Value { + match t { + TangentTarget::Line { a, b } => json!({ "kind": "line", "a": pv(of(*a)), "b": pv(of(*b)) }), + TangentTarget::Circle { center, r } => json!({ "kind": "circle", "center": pv(of(*center)), "r": js_num(*r) }), + } +} + +fn target_of(v: &Value) -> Option { + let p = |k: &str| to_p(xy(field(v, k).unwrap_or(&Value::Null))); + match field(v, "kind").and_then(Value::as_str)? { + "line" => Some(TangentTarget::Line { a: p("a"), b: p("b") }), + "circle" => Some(TangentTarget::Circle { center: p("center"), r: num_of(field(v, "r")) }), + _ => None, + } +} + +/// Nächstes tangentenfähiges Element (Gerade oder Kreis/Bogen) zum Klickpunkt. +fn pick_tangent<'a>(root: &'a Map, level: &str, at: V) -> Option<(TangentTarget, &'a Value)> { + let mut best: Option<(TangentTarget, &Value)> = None; + let mut best_d = TTR_HIT_TOL; + for d in arr(root.get("drawings2d")) { + if level_of(d) != Some(level) { + continue; + } + let Some(g) = field(d, "geom") else { continue }; + let shape = field(g, "shape").and_then(Value::as_str); + if shape == Some("circle") || shape == Some("arc") { + let c = xy(field(g, "center").unwrap_or(&Value::Null)); + let r = num_of(field(g, "r")); + let dd = (dist(at, c) - r).abs(); + let span = shape == Some("circle") || in_arc_span(num_of(field(g, "a0")), num_of(field(g, "a1")), angle(c, at)); + if dd < best_d && span { + best_d = dd; + best = Some((TangentTarget::Circle { center: to_p(c), r }, d)); + } + } else { + for (a, b) in straight_edges(g) { + let dd = point_segment_distance(at, a, b); + if dd < best_d { + best_d = dd; + best = Some((TangentTarget::Line { a: to_p(a), b: to_p(b) }, d)); + } + } + } + } + best +} + +fn nearest_candidate(cands: &[P], n1: V, n2: V) -> Option { + let mut best = None; + let mut best_d = f64::INFINITY; + for c in cands { + let c = of(*c); + let dd = dist(c, n1) + dist(c, n2); + if dd < best_d { + best_d = dd; + best = Some(c); + } + } + best +} + +/// Kreis der Anfrage (`method`, `pts`, `r`; TTR: `t1`, `t2`, `near1`, `near2`): Mitte + Radius. +fn circle_of(v: &Value, pts: &[V]) -> Option<(V, f64)> { + let typed = opt_n(v, "r"); + match s_of(v, "method") { + "center" => { + let c = *pts.first()?; + Some((c, typed.unwrap_or_else(|| pts.get(1).map_or(0.0, |p| dist(c, *p))))) + } + "twoPoint" => match pts { + [a, b] => Some((mid(*a, *b), dist(*a, *b) / 2.0)), + _ => None, + }, + "threePoint" => match pts { + [a, b, c] => arc_through(*a, *b, *c).map(|a| (a.c, a.r)), + _ => None, + }, + "ttr" => { + let (n1, n2) = (p_of(v, "near1"), p_of(v, "near2")); + let r = typed.unwrap_or_else(|| pts.first().map_or(0.0, |p| dist(n1, *p))); + let (t1, t2) = (target_of(v.get("t1")?)?, target_of(v.get("t2")?)?); + if !(r > EPS) { + return None; + } + nearest_candidate(&k::tangent_circle_centers(t1, t2, r), n1, n2).map(|c| (c, r)) + } + _ => None, + } +} + +fn circle_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let pts = pts_of(v, "pts"); + match circle_of(v, &pts) { + Some((c, r)) if !(r < EPS) => add_drawing(v, ctx, ids, obj(vec![("shape", s("circle")), ("center", pv(c)), ("r", js_num(r))])), + _ => Vec::new(), + } +} + +/// Kreis-Vorschau: `ok` = Kreis bestimmt; `info = [cx, cy, r]`; Formen nur ab r ≥ EPS (48-Eck). +fn circle_preview(v: &Value, pts: &[V], p: &mut Preview) { + match circle_of(v, pts) { + Some((c, r)) => { + p.info.extend([c.0, c.1, r]); + if !(r < EPS) { + p.shapes.poly(&circle_pts(c, r, 48)); + } + } + None => { + p.ok = false; + // TTR ohne Kandidat: der Radius für den Zustand. + let r = match (s_of(v, "method"), pts.first()) { + ("ttr", Some(q)) => dist(p_of(v, "near1"), *q), + _ => f64::NAN, + }; + p.info.extend([f64::NAN, f64::NAN, r]); + } + } +} + +// ═════════════════════════════════════════════════════════════════════════════ +// Bogen (Mittelpunkt, 3-Punkt, Start-Ende-Radius, Start-Ende-Richtung) +// ═════════════════════════════════════════════════════════════════════════════ + +fn sweep_of(a0: f64, a1: f64) -> f64 { + let s = ((a1 - a0) % TAU + TAU) % TAU; + if s < EPS { + TAU + } else { + s + } +} + +fn arc_pts(c: V, r: f64, a0: f64, a1: f64) -> Vec { + let sweep = sweep_of(a0, a1); + let n = jsnum::max(2.0, (sweep / (PI / 32.0)).ceil()); + if !(n <= 100_000.0) { + return Vec::new(); + } + let n = n as usize; + (0..=n) + .map(|i| { + let t = a0 + (sweep * i as f64) / n as f64; + (c.0 + r * jsnum::cos(t), c.1 + r * jsnum::sin(t)) + }) + .collect() +} + +/// Bogen der Anfrage (`method`, `pts`; „ser“ mit getipptem `r`). +fn arc_req(v: &Value, pts: &[V]) -> Option { + match (s_of(v, "method"), pts) { + ("center", [c, st, en]) => Some(Arc { c: *c, r: dist(*c, *st), a0: angle(*c, *st), a1: angle(*c, *en) }), + ("three", [a, t, b]) => arc_through(*a, *t, *b), + ("ser", [a, b, p]) => { + let r = opt_n(v, "r").unwrap_or_else(|| dist(mid(*a, *b), *p)); + arc_of(crate::bulge::arc_from_start_end_radius(a.0, a.1, b.0, b.1, r, p.0, p.1)) + } + ("sed", [a, b, d]) => arc_of(crate::bulge::arc_from_start_end_direction(a.0, a.1, b.0, b.1, d.0, d.1)), + _ => None, + } +} + +fn arc_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + match arc_req(v, &pts_of(v, "pts")) { + Some(a) if !(a.r < EPS) => add_drawing( + v, + ctx, + ids, + obj(vec![("shape", s("arc")), ("center", pv(a.c)), ("r", js_num(a.r)), ("a0", js_num(a.a0)), ("a1", js_num(a.a1))]), + ), + _ => Vec::new(), + } +} + +/// Bogen-Vorschau: `ok` = Bogen bestimmt; `info = [cx, cy, r, Spanne°]`. `full` (Mittelpunkt-Methode +/// vor dem Startpunkt): voller Kreis um `pts[0]` durch den Cursor. +fn arc_preview(v: &Value, pts: &[V], p: &mut Preview) { + if b_of(v, "full") { + if let [c, q] = pts { + let r = dist(*c, *q); + p.info.extend([c.0, c.1, r, 0.0]); + p.shapes.poly(&circle_pts(*c, r, 48)); + } + return; + } + match arc_req(v, pts) { + Some(a) => { + p.info.extend([a.c.0, a.c.1, a.r, (sweep_of(a.a0, a.a1) * 180.0) / PI]); + if !(a.r < EPS) { + p.shapes.poly_open(&arc_pts(a.c, a.r, a.a0, a.a1)); + } + } + None => p.ok = false, + } +} + +// ═════════════════════════════════════════════════════════════════════════════ +// Ellipse, Vieleck, Spline, Bezier, Revisionswolke +// ═════════════════════════════════════════════════════════════════════════════ + +fn perp_dist(a: V, b: V, p: V) -> f64 { + let len = dist(a, b); + if len < EPS { + return 0.0; + } + let (dx, dy) = ((b.0 - a.0) / len, (b.1 - a.1) / len); + (p.0 - a.0) * -dy + (p.1 - a.1) * dx +} + +/// Ellipse der Anfrage: box (`[p0, p1]`) oder axis (`[Mitte, Hauptachse, Nebenachsen-Punkt]`). +fn ellipse_of(v: &Value, pts: &[V]) -> Option<(V, f64, f64, f64)> { + match (s_of(v, "method"), pts) { + ("box", [a, b]) => Some((mid(*a, *b), (b.0 - a.0).abs() / 2.0, (b.1 - a.1).abs() / 2.0, 0.0)), + ("axis", [c, m]) => Some((*c, dist(*c, *m), 0.0, angle(*c, *m))), + ("axis", [c, m, p]) => Some((*c, dist(*c, *m), perp_dist(*c, *m, *p).abs(), angle(*c, *m))), + _ => None, + } +} + +fn ellipse_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + match ellipse_of(v, &pts_of(v, "pts")) { + Some((c, rx, ry, rot)) if !(rx < EPS || ry < EPS) => add_drawing( + v, + ctx, + ids, + obj(vec![("shape", s("ellipse")), ("center", pv(c)), ("rx", js_num(rx)), ("ry", js_num(ry)), ("rotation", js_num(rot))]), + ), + _ => Vec::new(), + } +} + +/// `info = [cx, cy, rx, ry]`; Formen ab rx, ry ≥ EPS (64 Punkte). +fn ellipse_preview(v: &Value, pts: &[V], p: &mut Preview) { + let Some((c, rx, ry, rot)) = ellipse_of(v, pts) else { + p.ok = false; + return; + }; + p.info.extend([c.0, c.1, rx, ry]); + if !(rx < EPS || ry < EPS) { + let f = crate::curves::ellipse(c.0, c.1, rx, ry, rot, 64.0); + p.shapes.poly(&f.chunks_exact(2).map(|q| (q[0], q[1])).collect::>()); + } +} + +fn polygon_pts(c: V, r: f64, sides: f64, circumscribed: bool, dir: Option) -> Vec { + let rv = if circumscribed { r / jsnum::cos(PI / sides) } else { r }; + let t0 = match dir { + Some(d) if dist(c, d) > EPS => jsnum::atan2(d.1 - c.1, d.0 - c.0), + _ => 0.0, + }; + let n = if sides.is_finite() && sides > 0.0 { sides as usize } else { 0 }; + (0..n.min(10_000)) + .map(|i| { + let t = t0 + (i as f64 / sides) * PI * 2.0; + (c.0 + rv * jsnum::cos(t), c.1 + rv * jsnum::sin(t)) + }) + .collect() +} + +fn polygon_from_edge(a: V, b: V, sides: f64) -> Vec { + let edge = dist(a, b); + let ext = (2.0 * PI) / sides; + let mut pts = vec![a, b]; + let mut cur = b; + let mut dir = jsnum::atan2(b.1 - a.1, b.0 - a.0); + let mut i = 2.0; + while i < sides && pts.len() < 10_000 { + dir += ext; + let next = (cur.0 + edge * jsnum::cos(dir), cur.1 + edge * jsnum::sin(dir)); + pts.push(next); + cur = next; + i += 1.0; + } + pts +} + +/// Vieleck: `method` center (`center`, `r`, `dir`) oder edge (`a`, `b`), `sides`, `mode`. +fn polygon_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let sides = n_of(v, "sides"); + let pts = if s_of(v, "method") == "edge" { + let (a, b) = (p_of(v, "a"), p_of(v, "b")); + if dist(a, b) < EPS { + return Vec::new(); + } + let mut p = polygon_from_edge(a, b, sides); + // Die Kanten-Endpunkte sind die Klickpunkte selbst. + let mut out = vec![pt_val(v, "a"), pt_val(v, "b")]; + out.extend(p.drain(2..).map(pv)); + Value::Array(out) + } else { + let (c, dir) = (p_of(v, "center"), opt_p(v, "dir")); + // Radius getippt oder Abstand zum Klickpunkt (`dir`). + let r = opt_n(v, "r").unwrap_or_else(|| dir.map_or(f64::NAN, |d| dist(c, d))); + if r < EPS { + return Vec::new(); + } + pvs(&polygon_pts(c, r, sides, s_of(v, "mode") == "circumscribed", dir)) + }; + add_drawing(v, ctx, ids, obj(vec![("shape", s("polyline")), ("pts", pts), ("closed", Value::Bool(true))])) +} + +/// Vieleck-Vorschau: center `pts = [Mitte, Cursor?]` (`info = [r]`), edge `pts = [a, Cursor]`. +fn polygon_preview(v: &Value, pts: &[V], p: &mut Preview) { + let sides = n_of(v, "sides"); + if s_of(v, "method") == "edge" { + if let [a, b] = pts { + p.shapes.poly(&polygon_from_edge(*a, *b, sides)); + } + return; + } + let Some(c) = pts.first() else { return }; + let dir = pts.get(1).copied(); + let r = dir.map_or(0.0, |d| dist(*c, d)); + p.info.push(r); + if !(r < EPS) { + p.shapes.poly(&polygon_pts(*c, r, sides, s_of(v, "mode") == "circumscribed", dir)); + } +} + +fn spline_curve(pts: &[V], closed: bool, control: bool) -> Vec { + if pts.len() < 3 { + return pts.to_vec(); + } + let f: Vec = pts.iter().flat_map(|p| [p.0, p.1]).collect(); + let out = if control { crate::curves::uniform_bspline(&f, closed, 16.0) } else { crate::curves::catmull_rom(&f, closed, 16.0) }; + out.chunks_exact(2).map(|q| (q[0], q[1])).collect() +} + +/// Spline-Vorschau (`pts` = Punkte + Cursor): geschlossen ab 3 Punkten. +fn spline_preview(v: &Value, pts: &[V], out: &mut Shapes) { + let closed = b_of(v, "closed") && pts.len() >= 3; + let c = spline_curve(pts, closed, s_of(v, "mode") == "control"); + if closed { + out.poly(&c); + } else { + out.poly_open(&c); + } +} + +/// Bezier-Vorschau: Kette ab 4 Punkten (24 Schritte je Kurve). +fn bezier_preview(pts: &[V], out: &mut Shapes) { + if pts.len() >= 4 { + let f: Vec = pts.iter().flat_map(|p| [p.0, p.1]).collect(); + let c = crate::curves::bezier_chain(&f, 24.0); + out.poly_open(&c.chunks_exact(2).map(|q| (q[0], q[1])).collect::>()); + } +} + +/// `bulge` einer Beule der Revisionswolke (`tan(Δ/4)`, Δ ≈ 100°). +const REVCLOUD_BULGE: f64 = 0.42; +/// Höchstzahl Beulen je Segment. +const MAX_BUMPS_PER_SEGMENT: f64 = 2000.0; + +/// Revisionswolke: jedes Segment in gleich lange Beulen (Ziel-Bogenlänge `target`) zerlegen. +pub fn revision_cloud(points: &[V], closed: bool, target: f64) -> Option<(Vec, Vec)> { + if points.len() < 2 || !target.is_finite() || target <= 0.0 { + return None; + } + let seg_count = if closed { points.len() } else { points.len() - 1 }; + let mut out = vec![points[0]]; + let mut bulge = Vec::new(); + for sgi in 0..seg_count { + let (a, b) = (points[sgi], points[(sgi + 1) % points.len()]); + let len = dist(a, b); + if !len.is_finite() || len < 1e-9 { + continue; + } + let n = jsnum::min(MAX_BUMPS_PER_SEGMENT, jsnum::max(1.0, jsnum::round(len / jsnum::max(target, 1e-9)))); + let n = n as usize; + for i in 1..=n { + let t = i as f64 / n as f64; + out.push((a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t)); + bulge.push(REVCLOUD_BULGE); + } + } + if closed { + out.pop(); + } + if out.len() < 2 { + return None; + } + Some((out, bulge)) +} + +// ═════════════════════════════════════════════════════════════════════════════ +// Mehrfachlinie, Symbole, Block +// ═════════════════════════════════════════════════════════════════════════════ + +fn side_sign(a: V, b: V, p: V) -> f64 { + let m = mid(a, b); + let u = normalize((b.0 - a.0, b.1 - a.1)); + let n = (-u.1, u.0); + if (p.0 - m.0) * n.0 + (p.1 - m.1) * n.1 >= 0.0 { + 1.0 + } else { + -1.0 + } +} + +fn multiline_pairs(a: V, b: V, spacing: f64, sign: f64, count: f64) -> Vec<(V, V)> { + let mut out = vec![(a, b)]; + let mut kk = 1.0; + while kk < count && out.len() < 1000 { + let (pa, pb) = k::offset_segment(to_p(a), to_p(b), sign * spacing * kk); + out.push((of(pa), of(pb))); + kk += 1.0; + } + out +} + +/// Mehrfachlinie: `a`, `b`, `spacing`, `count`, `sign` (oder `side` = Punkt, dessen Seite zählt). +fn multiline_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let (a, b) = (p_of(v, "a"), p_of(v, "b")); + if seg_len(a, b) < EPS { + return Vec::new(); + } + let sign = match opt_p(v, "side") { + Some(p) => side_sign(a, b, p), + None => n_of(v, "sign"), + }; + let pairs = multiline_pairs(a, b, n_of(v, "spacing"), sign, n_of(v, "count")); + let items = pairs + .into_iter() + .enumerate() + .map(|(i, (pa, pb))| { + let (ga, gb) = if i == 0 { (pt_val(v, "a"), pt_val(v, "b")) } else { (pv(pa), pv(pb)) }; + drawing(ids.next("dr2d"), ctx, obj(vec![("shape", s("line")), ("a", ga), ("b", gb)])) + }) + .collect(); + add_op("drawings2d", items) +} + +/// `pts = [a, b, Cursor?]`: Original + Kopien auf der Seite `sign` (fehlt sie: Seite des Cursors); +/// `info = [Seite des Cursors]`. +fn multiline_preview(v: &Value, pts: &[V], p: &mut Preview) { + let (a, b) = match pts { + [a, b, ..] => (*a, *b), + _ => return, + }; + let side = pts.get(2).map(|c| side_sign(a, b, *c)); + let sign = opt_n(v, "sign").or(side).unwrap_or(f64::NAN); + p.info.push(side.unwrap_or(f64::NAN)); + for (pa, pb) in multiline_pairs(a, b, n_of(v, "spacing"), sign, n_of(v, "count")) { + p.shapes.line(pa, pb); + } +} + +const TEXT_HEIGHT: f64 = 0.25; +const TEXTBOX_MIN: f64 = 0.2; + +fn text_geom(at: Value, extra: Vec<(&str, Value)>) -> Value { + let mut f = vec![("shape", s("text")), ("at", at), ("text", s("")), ("height", js_num(TEXT_HEIGHT)), ("angle", js_num(0.0))]; + f.extend(extra); + obj(f) +} + +/// Textrahmen aus zwei Ecken: Anker oben links (eine Zeile tief), Breite, Mindesthöhe. +fn textbox_frame(a: V, b: V) -> (V, f64, f64) { + let (mn, mx) = rect_geom(a, b); + let width = jsnum::max(TEXTBOX_MIN, mx.0 - mn.0); + let height = jsnum::max(TEXTBOX_MIN, mx.1 - mn.1); + ((mn.0, mx.1 - TEXT_HEIGHT), width, height) +} + +fn kote_tri(at: V, kind: &str) -> [V; 3] { + let up = if kind == "okFertig" || kind == "okRoh" { 1.0 } else { -1.0 }; + let (size, half) = (0.15, 0.15 * 0.6); + [at, (at.0 - half, at.1 + up * size), (at.0 + half, at.1 + up * size)] +} + +fn block_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let (at, p) = (p_of(v, "at"), p_of(v, "pt")); + let d = hypot2(p.0 - at.0, p.1 - at.1); + let (rot, scale) = if d < EPS { (0.0, 1.0) } else { (jsnum::atan2(p.1 - at.1, p.0 - at.0), d) }; + let def = v.get("def").cloned().unwrap_or(Value::Null); + add_drawing( + v, + ctx, + ids, + obj(vec![("shape", s("block")), ("blockDefId", def), ("at", pt_val(v, "at")), ("rotation", js_num(rot)), ("scale", js_num(scale))]), + ) +} + +// ═════════════════════════════════════════════════════════════════════════════ +// Bemassung +// ═════════════════════════════════════════════════════════════════════════════ + +fn signed_offset(a: V, b: V, p: V) -> f64 { + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let len = hypot2(dx, dy); + if len < EPS { + return 0.0; + } + let (nx, ny) = (-dy / len, dx / len); + (p.0 - a.0) * nx + (p.1 - a.1) * ny +} + +fn project_on_line(p0: V, p1: V, p: V) -> V { + let (dx, dy) = (p1.0 - p0.0, p1.1 - p0.1); + let len2 = dx * dx + dy * dy; + if len2 < EPS { + return p; + } + let t = ((p.0 - p0.0) * dx + (p.1 - p0.1) * dy) / len2; + (p0.0 + dx * t, p0.1 + dy * t) +} + +fn offset_points(a: V, b: V, offset: f64) -> (V, V) { + 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 (nx, ny) = ((-dy / len) * offset, (dx / len) * offset); + ((a.0 + nx, a.1 + ny), (b.0 + nx, b.1 + ny)) +} + +/// Neuen Punkt in die Kette einsortieren (auf die Masslinie p0→p1 projiziert, nach Parameter). +fn insert_into_chain(pts: &[Value], raw: V) -> Vec { + if pts.len() < 2 { + let mut out = pts.to_vec(); + out.push(pv(raw)); + return out; + } + let (p0, p1) = (xy(&pts[0]), xy(&pts[1])); + let (dx, dy) = (p1.0 - p0.0, p1.1 - p0.1); + let l2 = dx * dx + dy * dy; + let len2 = if l2 == 0.0 || l2.is_nan() { 1.0 } else { l2 }; + let t_of = |p: V| ((p.0 - p0.0) * dx + (p.1 - p0.1) * dy) / len2; + let placed = project_on_line(p0, p1, raw); + let nt = t_of(placed); + let idx = pts.iter().position(|p| nt < t_of(xy(p))).unwrap_or(pts.len()); + let mut out = pts.to_vec(); + out.insert(idx, pv(placed)); + out +} + +/// Bemassung: `pts`, `offset` (oder `side` = Punkt), `editId` (bestehende Kette ändern). +fn dimension_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let raw = arr(v.get("pts")); + let pts: Vec = raw.iter().map(pair).collect(); + let offset = match opt_p(v, "side") { + Some(p) if pts.len() >= 2 => signed_offset(pts[0], pts[1], p), + Some(_) => f64::NAN, + None => n_of(v, "offset"), + }; + let cleaned: Vec = raw + .iter() + .enumerate() + .filter(|(i, _)| *i == 0 || dist(pts[*i - 1], pts[*i]) >= EPS) + .map(|(_, p)| if p.is_object() { p.clone() } else { pv(pair(p)) }) + .collect(); + if cleaned.len() < 2 { + return Vec::new(); + } + let geom = obj(vec![("shape", s("dimension")), ("pts", Value::Array(cleaned)), ("offset", js_num(offset))]); + match v.get("editId").and_then(Value::as_str) { + Some(id) => match find(root, "drawings2d", id) { + Some(d) => vec![Op::Replace { collection: "drawings2d".into(), entity: with(d, "geom", geom) }], + None => Vec::new(), + }, + None => add_drawing(v, ctx, ids, geom), + } +} + +/// Bemassungs-Vorschau. `phase` next: `pts` = Kette + roher Cursor → Kette bis zum (auf die Masslinie +/// projizierten) Cursor, `info = [cx, cy]`; offset: `pts` = Kette + Cursor (oder ohne → Abstand 0), +/// Hilfs- und Masslinien, `info = [Abstand, Summe]`. +fn dimension_preview(v: &Value, pts: &[V], p: &mut Preview) { + if pts.is_empty() { + return; + } + let has_cursor = b_of(v, "cursor"); + let chain = if has_cursor { &pts[..pts.len() - 1] } else { pts }; + if s_of(v, "phase") == "next" { + let raw = pts[pts.len() - 1]; + let c = if chain.len() >= 2 { project_on_line(chain[0], chain[1], raw) } else { raw }; + p.info.extend([c.0, c.1]); + let mut shown = chain.to_vec(); + shown.push(c); + p.shapes.poly_open(&shown); + return; + } + if chain.len() < 2 { + return; + } + let off = if has_cursor { signed_offset(chain[0], chain[1], pts[pts.len() - 1]) } else { 0.0 }; + let mut total = 0.0; + for (i, w) in chain.windows(2).enumerate() { + let (a, b) = (w[0], w[1]); + if off.abs() > EPS { + let (oa, ob) = offset_points(a, b, off); + p.shapes.line(a, oa); + p.shapes.line(b, ob); + p.shapes.line(oa, ob); + } else { + p.shapes.line(a, b); + } + total = if i == 0 { dist(a, b) } else { total + dist(a, b) }; + } + p.info.extend([off, total]); +} + +// ── Aussenbemassung ────────────────────────────────────────────────────────── + +/// Aussenbemassung des Geschosses `level` (Ketten aus `auto_dimensions`), ids `prefix-Geschoss-Seite-Kette`. +fn auto_dims(root: &Map, ctx: &Ctx, prefix: &str, scale: f64) -> Vec { + use crate::auto_dimensions::{auto_exterior_dimensions, OpeningIn, WallIn}; + let types = wall_types(root); + let walls: Vec<&Value> = arr(root.get("walls")).iter().filter(|w| crate::cmd_create::floor_of(w) == Some(ctx.level)).collect(); + if walls.is_empty() { + return Vec::new(); + } + let p = |w: &Value, k: &str| xy(field(w, k).unwrap_or(&Value::Null)); + let win: Vec = walls + .iter() + .map(|w| { + let tid = field(w, "wallTypeId").and_then(Value::as_str); + let th = types.iter().find(|t| id_of(t) == tid).map_or(0.3, type_thickness); + let (a, b) = (p(w, "start"), p(w, "end")); + WallIn { start: [a.0, a.1], end: [b.0, b.1], thickness: th } + }) + .collect(); + let mut oin = Vec::new(); + for o in arr(root.get("openings")) { + let host = field(o, "hostWallId").and_then(Value::as_str); + let Some(i) = walls.iter().position(|w| id_of(w) == host) else { continue }; + let (a, b) = (p(walls[i], "start"), p(walls[i], "end")); + let axis = dist(a, b); + let (pos, width) = (num_of(field(o, "position")), num_of(field(o, "width"))); + let from = jsnum::max(0.0, jsnum::min(pos, axis)); + let to = jsnum::max(from, jsnum::min(pos + width, axis)); + if to - from < 1e-4 { + continue; + } + let u = normalize((b.0 - a.0, b.1 - a.1)); + let at = |d: f64| [a.0 + u.0 * d, a.1 + u.1 * d]; + oin.push(OpeningIn { wall: i, jamb_start: at(from), jamb_end: at(to) }); + } + const SIDES: [&str; 4] = ["south", "east", "north", "west"]; + const CHAINS: [&str; 3] = ["openings", "steps", "total"]; + auto_exterior_dimensions(&win, &oin, scale) + .into_iter() + .map(|c| { + let id = format!("{prefix}-{}-{}-{}", ctx.level, SIDES[c.side as usize], CHAINS[c.chain as usize]); + let pts = Value::Array(c.pts.iter().map(|q| crate::grips::pt(q[0], q[1])).collect()); + drawing(id, ctx, obj(vec![("shape", s("dimension")), ("pts", pts), ("offset", js_num(c.offset))])) + }) + .collect() +} + +fn autodim_ops(root: &Map, ctx: &Ctx) -> Vec { + let dims = auto_dims(root, ctx, "autodim", 100.0); + if dims.is_empty() { + return Vec::new(); + } + let own = format!("autodim-{}-", ctx.level); + let old: Vec<&str> = arr(root.get("drawings2d")).iter().filter_map(id_of).filter(|id| id.starts_with(&own)).collect(); + let mut ops = crate::cmd_create::remove_op(root, "drawings2d", &old); + ops.extend(add_op("drawings2d", dims)); + ops +} + +// ═════════════════════════════════════════════════════════════════════════════ +// Einstiege (über `cmd_create`) +// ═════════════════════════════════════════════════════════════════════════════ + +/// Ops eines 2D-Zeichenbefehls (`None` = keiner dieses Moduls). +pub fn ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Option> { + let geom2 = |shape: &str| obj(vec![("shape", s(shape)), ("a", pt_val(v, "a")), ("b", pt_val(v, "b"))]); + Some(match s_of(v, "cmd") { + "line" | "xline" | "ray" => add_drawing(v, ctx, ids, geom2(s_of(v, "cmd"))), + "polyline" => polyline_ops(v, ctx, ids), + "rect" => rect_ops(v, ctx, ids), + "circle" => circle_ops(v, ctx, ids), + "arc" => arc_ops(v, ctx, ids), + "ellipse" => ellipse_ops(v, ctx, ids), + "polygon" => polygon_ops(v, ctx, ids), + "spline" => add_drawing( + v, + ctx, + ids, + obj(vec![("shape", s("spline")), ("pts", pts_val(v, "pts")), ("closed", Value::Bool(b_of(v, "closed"))), ("mode", s(s_of(v, "mode")))]), + ), + "bezier" => { + if arr(v.get("pts")).len() < 4 { + return Some(Vec::new()); + } + add_drawing(v, ctx, ids, obj(vec![("shape", s("bezier")), ("pts", pts_val(v, "pts"))])) + } + "revcloud" => { + let closed = b_of(v, "closed"); + match revision_cloud(&pts_of(v, "pts"), closed, n_of(v, "arcSize")) { + Some((p, b)) => add_drawing( + v, + ctx, + ids, + obj(vec![ + ("shape", s("polyline")), + ("pts", pvs(&p)), + ("closed", Value::Bool(closed)), + ("bulge", Value::Array(b.iter().map(|x| js_num(*x)).collect())), + ]), + ), + None => Vec::new(), + } + } + "wipeout" => { + let g = obj(vec![("shape", s("polyline")), ("pts", pts_val(v, "pts")), ("closed", Value::Bool(true))]); + let mut d = drawing(id_or_new(v, ids), ctx, g); + if let Some(m) = d.as_object_mut() { + m.insert("background".into(), s("#ffffff")); + m.insert("color".into(), s("#ffffff")); + } + add_op("drawings2d", vec![d]) + } + "multiline" => multiline_ops(v, ctx, ids), + "text" => add_drawing(v, ctx, ids, text_geom(pt_val(v, "at"), vec![])), + "textbox" => { + let (at, width, _) = textbox_frame(p_of(v, "a"), p_of(v, "b")); + add_drawing(v, ctx, ids, text_geom(pv(at), vec![("width", js_num(width))])) + } + "textpath" => { + let pts = pts_val(v, "pts"); + let at = pts.get(0).cloned().unwrap_or(Value::Null); + add_drawing(v, ctx, ids, text_geom(at, vec![("pathPts", pts)])) + } + "leader" => { + let mut extra = vec![("leaderTarget", pt_val(v, "target"))]; + let bends = pts_val(v, "bends"); + if bends.as_array().is_some_and(|b| !b.is_empty()) { + extra.push(("leaderBendPoints", bends)); + } + add_drawing(v, ctx, ids, text_geom(pt_val(v, "at"), extra)) + } + "kote" => add_drawing( + v, + ctx, + ids, + obj(vec![("shape", s("kote")), ("at", pt_val(v, "at")), ("value", js_num(n_of(v, "value"))), ("kind", s(s_of(v, "kind"))), ("rotation", js_num(0.0))]), + ), + "detailref" => add_drawing(v, ctx, ids, obj(vec![("shape", s("detailref")), ("at", pt_val(v, "at")), ("label", s("A"))])), + "scalebar" => add_drawing( + v, + ctx, + ids, + obj(vec![("shape", s("scalebar")), ("at", pt_val(v, "at")), ("segmentLength", js_num(n_of(v, "length"))), ("segments", js_num(n_of(v, "segments")))]), + ), + "pointmarker" => add_drawing(v, ctx, ids, obj(vec![("shape", s("pointmarker")), ("at", pt_val(v, "at"))])), + "block" => block_ops(v, ctx, ids), + "dimension" => dimension_ops(root, v, ctx, ids), + "autodim" => autodim_ops(root, ctx), + _ => return None, + }) +} + +/// Vorschau eines 2D-Zeichenbefehls (`false` = keiner dieses Moduls). +pub fn preview(root: &Map, v: &Value, ctx: &Ctx, pts: &[V], p: &mut Preview) -> bool { + match s_of(v, "cmd") { + "xline" | "ray" => { + if let [a, c] = pts { + let l = seg_len(*a, *c); + if l >= EPS { + let (ux, uy) = ((c.0 - a.0) / seg_len(*a, *c), (c.1 - a.1) / seg_len(*a, *c)); + let end = (c.0 + ux * 30.0, c.1 + uy * 30.0); + let start = if s_of(v, "cmd") == "xline" { (a.0 - ux * 30.0, a.1 - uy * 30.0) } else { *a }; + p.shapes.line(start, end); + } + } + } + "polyline" => polyline_preview(v, pts, &mut p.shapes), + "rect" => rect_preview(v, pts, &mut p.shapes, &mut p.info), + "circle" => circle_preview(v, pts, p), + "arc" => arc_preview(v, pts, p), + "ellipse" => ellipse_preview(v, pts, p), + "polygon" => polygon_preview(v, pts, p), + "spline" => spline_preview(v, pts, &mut p.shapes), + "bezier" => bezier_preview(pts, &mut p.shapes), + "revcloud" => { + let shown = revision_cloud(pts, false, n_of(v, "arcSize")).map_or_else(Vec::new, |(q, b)| bulge_points(&q, &b, false)); + p.shapes.poly_open(&shown); + } + "multiline" => multiline_preview(v, pts, p), + "textbox" => { + if let [a, b] = pts { + let (mn, mx) = rect_geom(*a, *b); + let (_, w, h) = textbox_frame(*a, *b); + p.info.extend([w, h]); + p.shapes.poly(&corners_of(mn, mx)); + } + } + "kote" => { + if let Some(at) = pts.first() { + p.shapes.poly(&kote_tri(*at, s_of(v, "kind"))); + } + } + "detailref" => { + if let Some(at) = pts.first() { + p.shapes.poly(&circle_pts(*at, 0.3, 32)); + } + } + "pointmarker" => { + if let Some(at) = pts.first() { + p.shapes.poly(&circle_pts(*at, 0.08, 32)); + p.shapes.line((at.0 - 0.12, at.1), (at.0 + 0.12, at.1)); + p.shapes.line((at.0, at.1 - 0.12), (at.0, at.1 + 0.12)); + } + } + "scalebar" => { + if let Some(at) = pts.first() { + let (len, n) = (n_of(v, "length"), n_of(v, "segments")); + let h = len * 0.06; + let mut i = 0.0; + while i < n && i < 1000.0 { + let x0 = at.0 + i * len; + let x1 = x0 + len; + p.shapes.poly(&[(x0, at.1), (x1, at.1), (x1, at.1 + h), (x0, at.1 + h)]); + i += 1.0; + } + } + } + "dimension" => dimension_preview(v, pts, p), + "autodim" => p.ok = !auto_dims(root, ctx, "autodim", 100.0).is_empty(), + _ => return false, + } + true +} + +/// Treffer-Abfragen der 2D-Befehle (`None` = keine dieses Moduls). +pub fn query(root: &Map, v: &Value) -> Option { + let at = p_of(v, "pt"); + Some(match s_of(v, "q") { + "pickTangent" => match pick_tangent(root, s_of(v, "level"), at) { + Some((t, d)) => json!({ "hit": { "target": target_json(&t), "id": id_of(d) } }), + None => json!({ "hit": null }), + }, + "dimChain" => { + let d = find(root, "drawings2d", s_of(v, "id")).filter(|d| { + field(d, "geom").and_then(|g| field(g, "shape")).and_then(Value::as_str) == Some("dimension") + }); + match d { + Some(d) => { + let g = field(d, "geom").unwrap_or(&Value::Null); + json!({ "hit": { "id": id_of(d), "pts": field(g, "pts").cloned().unwrap_or(Value::Null), "offset": field(g, "offset").cloned().unwrap_or(Value::Null) } }) + } + None => json!({ "hit": null }), + } + } + "dimInsert" => json!({ "pts": insert_into_chain(arr(v.get("pts")), at) }), + _ => return None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ctx() -> Ctx<'static> { + Ctx { level: "L", floor_height: None, cat: "20", wall_type: "" } + } + + #[test] + fn revisionswolke_beulen() { + assert!(revision_cloud(&[(0.0, 0.0)], false, 0.3).is_none()); + let (p, b) = revision_cloud(&[(0.0, 0.0), (2.0, 0.0)], false, 0.5).unwrap(); + assert_eq!(p.len(), 5); + assert!(b.iter().all(|x| *x == REVCLOUD_BULGE)); + let (p, _) = revision_cloud(&[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)], true, 1.0).unwrap(); + assert_eq!(p.len(), 3); + } + + #[test] + fn polylinie_tangential_und_schluss() { + let v = json!({"cmd": "polyline", "pts": [[0, 0], [2, 0], [2, 2]], "segs": [0, 1], "closed": true, "closing": 0}); + let o = ops(&Map::new(), &v, &ctx(), &mut IdGen::new("s")).unwrap(); + let g = &o[0].to_json()["items"][0]["geom"]; + assert_eq!(g["bulge"].as_array().unwrap().len(), 3); + assert!(g["bulge"][1].as_f64().unwrap().abs() > 0.1); + assert_eq!(g["bulge"][2], 0); + } + + #[test] + fn rechteck_gerundet_und_kreis_durch_drei_punkte() { + let v = json!({"cmd": "rect", "method": "corner", "a": [0, 0], "b": [2, 1], "radius": 0.1}); + let o = ops(&Map::new(), &v, &ctx(), &mut IdGen::new("s")).unwrap(); + assert_eq!(o[0].to_json()["items"][0]["geom"]["pts"].as_array().unwrap().len(), 8); + let v = json!({"cmd": "circle", "method": "threePoint", "pts": [[1, 0], [0, 1], [-1, 0]]}); + let o = ops(&Map::new(), &v, &ctx(), &mut IdGen::new("s")).unwrap(); + assert_eq!(o[0].to_json()["items"][0]["geom"]["r"], 1); + } + + #[test] + fn bemassung_einsortieren_und_kette_aendern() { + let pts = vec![pv((0.0, 0.0)), pv((4.0, 0.0))]; + let out = insert_into_chain(&pts, (2.0, 1.0)); + assert_eq!(out[1], json!({"x": 2, "y": 0})); + let root = json!({"drawings2d": [{"id": "d", "levelId": "L", "geom": {"shape": "dimension", "pts": [], "offset": 0}}]}); + let v = json!({"cmd": "dimension", "pts": [[0, 0], [4, 0]], "side": [1, 1], "editId": "d"}); + let o = ops(root.as_object().unwrap(), &v, &ctx(), &mut IdGen::new("s")).unwrap(); + assert_eq!(o[0].to_json()["entity"]["geom"]["offset"], 1); + } +} diff --git a/src-tauri/core/src/cmd_solid.rs b/src-tauri/core/src/cmd_solid.rs new file mode 100644 index 00000000..5b082074 --- /dev/null +++ b/src-tauri/core/src/cmd_solid.rs @@ -0,0 +1,600 @@ +//! Körper, Gelände und Sonderbefehle im Kern ([K4] S3, vorher `commands/cmds/{solid,solidbool,voidbox, +//! terrain,ceilingOpening,roofHole,sectionline}.ts`): Grundkörper (B-Rep-Beschreibung für truck), +//! Boolesche Körper, Aussparungs-Quader, Gelände-TIN aus Höhenlinien, Decken-Aussparung, Dach-Hof und +//! Schnitt-/Ansichtslinie — Ops, Vorschau und Treffer. Dazu die B-Rep-Beschreibung eines Körpers +//! (`extrudedSolidSpec`, auch für 3D, Schnitt und STEP) und das Gelände aus Höhenlinien +//! (`generateTerrainFromContours`, auch für das Lage-Panel). Einstieg über `cmd_create`. + +use crate::cmd_create::{add_op, circle_pts, find, n_of, obj, opt_p, p_of, pts_of, pv, pvs, rect_corners, s, s_of, Ctx, Preview, V}; +use crate::cmd_transform::{IdGen, Shapes}; +use crate::grips::{arr, field, js_num, num_of, num_or, truthy, with, xy}; +use crate::jsmath::hypot2; +use crate::jsnum; +use crate::ops::{id_of, Op}; +use serde_json::{json, Map, Value}; + +fn fixed2(x: f64) -> String { + crate::js_fmt::to_fixed(x, 2) +} + +fn level_of(e: &Value) -> Option<&str> { + field(e, "levelId").and_then(Value::as_str) +} + +// ═════════════════════════════════════════════════════════════════════════════ +// B-Rep-Beschreibung eines Körpers (`extrudedSolidSpec`) +// ═════════════════════════════════════════════════════════════════════════════ + +/// B-Rep-Beschreibung (`SolidSpec`) eines Körpers mit UK auf Geschoss-Höhe `floor_z` (+ `baseOffset`); +/// `None`, wenn truck dafür keine Beschreibung hat (Pyramide, entartet). +pub fn extruded_solid_spec(solid: &Value, floor_z: f64) -> Option { + let base_z = floor_z + num_or(field(solid, "baseOffset"), 0.0); + let points = arr(field(solid, "points")); + if let Some(brep) = field(solid, "brep").filter(|b| truthy(Some(b))) { + let (dx, dy) = match points.first() { + Some(p0) => { + let (o, p) = (xy(field(brep, "origin").unwrap_or(&Value::Null)), xy(p0)); + (p.0 - o.0, p.1 - o.1) + } + None => (0.0, 0.0), + }; + let spec = field(brep, "spec").cloned().unwrap_or(Value::Null); + return Some(obj(vec![("kind", s("translate")), ("v", json!([js_num(dx), js_num(dy), js_num(base_z)])), ("solid", spec)])); + } + let height = num_of(field(solid, "height")); + if points.len() < 3 || height <= 0.0 { + return None; + } + let taper = jsnum::min(1.0, jsnum::max(0.0, num_or(field(solid, "taper"), 0.0))); + let circle = field(solid, "circle").filter(|c| truthy(Some(c))); + if let Some(c) = circle { + if taper < 1e-6 || taper >= 1.0 - 1e-6 { + let ctr = xy(field(c, "center").unwrap_or(&Value::Null)); + let kind = if taper < 1e-6 { "cylinder" } else { "cone" }; + return Some(obj(vec![ + ("kind", s(kind)), + ("cx", js_num(ctr.0)), + ("cy", js_num(ctr.1)), + ("z0", js_num(base_z)), + ("r", js_num(num_of(field(c, "r")))), + ("height", js_num(height)), + ])); + } + } + let pts: Vec = points.iter().map(xy).collect(); + let flat = |ps: &[V]| Value::Array(ps.iter().flat_map(|p| [js_num(p.0), js_num(p.1)]).collect()); + if taper < 1e-6 { + let mut f = vec![("kind", s("extrude")), ("points", flat(&pts)), ("height", js_num(height)), ("z0", js_num(base_z))]; + let cr = num_or(field(solid, "cornerRadius"), 0.0); + if cr > 0.0 { + f.push(("cornerRadius", field(solid, "cornerRadius").cloned().unwrap_or(Value::Null))); + } + let ch = num_or(field(solid, "chamfer"), 0.0); + if ch > 0.0 { + f.push(("chamfer", field(solid, "chamfer").cloned().unwrap_or(Value::Null))); + } + return Some(obj(f)); + } + if taper < 1.0 - 1e-6 { + let n = pts.len() as f64; + let cx = pts.iter().fold(0.0, |a, p| a + p.0) / n; + let cy = pts.iter().fold(0.0, |a, p| a + p.1) / n; + let top: Vec = pts.iter().map(|p| (cx + (p.0 - cx) * (1.0 - taper), cy + (p.1 - cy) * (1.0 - taper))).collect(); + return Some(obj(vec![ + ("kind", s("loft")), + ( + "sections", + Value::Array(vec![ + obj(vec![("z", js_num(base_z)), ("points", flat(&pts))]), + obj(vec![("z", js_num(base_z + height)), ("points", flat(&top))]), + ]), + ), + ])); + } + None +} + +// ═════════════════════════════════════════════════════════════════════════════ +// Grundkörper, Boolesche Körper, Aussparung +// ═════════════════════════════════════════════════════════════════════════════ + +/// Grundkörper aus den Eingaben (`solidFromInputs`): Grundriss-Punkte, Höhe, B-Rep-Beschreibung, Label. +pub fn solid_from_inputs(shape: &str, p0: V, p1: Option, nums: &[f64]) -> Option<(Vec, f64, Value, String)> { + let num = |i: usize| nums.get(i).copied().unwrap_or(f64::NAN); + let ok = |x: f64| x > 1e-6; + match shape { + "sphere" => { + let r = num(0); + ok(r).then(|| { + (circle_pts(p0, r, 48), 2.0 * r, json!({ "kind": "sphere", "center": [js_num(p0.0), js_num(p0.1), js_num(r)], "r": js_num(r) }), format!("Kugel r={}", fixed2(r))) + }) + } + "cylinder" | "cone" => { + let (r, h) = (num(0), num(1)); + (ok(r) && ok(h)).then(|| { + let label = format!("{} r={} h={}", if shape == "cone" { "Kegel" } else { "Zylinder" }, fixed2(r), fixed2(h)); + let spec = obj(vec![("kind", s(shape)), ("cx", js_num(p0.0)), ("cy", js_num(p0.1)), ("z0", js_num(0.0)), ("r", js_num(r)), ("height", js_num(h))]); + (circle_pts(p0, r, 48), h, spec, label) + }) + } + "frustum" => { + let (r, rt, h) = (num(0), num(1), num(2)); + (ok(r) && ok(rt) && ok(h)).then(|| { + let profile: Vec = [0.0, 0.0, r, 0.0, rt, h, 0.0, h].iter().map(|x| js_num(*x)).collect(); + let spec = obj(vec![("kind", s("revolve")), ("cx", js_num(p0.0)), ("cy", js_num(p0.1)), ("profile", Value::Array(profile))]); + (circle_pts(p0, jsnum::max(r, rt), 48), h, spec, format!("Kegelstumpf r={}/{} h={}", fixed2(r), fixed2(rt), fixed2(h))) + }) + } + "torus" => { + let (major, minor) = (num(0), num(1)); + (ok(minor) && major > minor).then(|| { + let spec = json!({ "kind": "torus", "center": [js_num(p0.0), js_num(p0.1), js_num(minor)], "major": js_num(major), "minor": js_num(minor) }); + (circle_pts(p0, major + minor, 48), 2.0 * minor, spec, format!("Torus R={} r={}", fixed2(major), fixed2(minor))) + }) + } + "cuboid" => { + let h = num(0); + let p1 = p1?; + if !ok(h) { + return None; + } + let pts = rect_corners(p0, p1); + let (w, d) = ((p1.0 - p0.0).abs(), (p1.1 - p0.1).abs()); + if w < 1e-6 || d < 1e-6 { + return None; + } + let spec = json!({ "kind": "cuboid", "min": [js_num(pts[0].0), js_num(pts[0].1), 0], "max": [js_num(pts[2].0), js_num(pts[2].1), js_num(h)] }); + Some((pts.to_vec(), h, spec, format!("Quader {}×{}×{}", fixed2(w), fixed2(d), fixed2(h)))) + } + _ => None, + } +} + +fn solid_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let nums: Vec = arr(v.get("nums")).iter().map(|x| num_of(Some(x))).collect(); + let Some((pts, height, spec, label)) = solid_from_inputs(s_of(v, "shape"), p_of(v, "p0"), opt_p(v, "p1"), &nums) else { + return Vec::new(); + }; + let solid = obj(vec![ + ("id", s(&ids.next("body"))), + ("type", s("extrudedSolid")), + ("levelId", s(ctx.level)), + ("points", pvs(&pts)), + ("height", js_num(height)), + ("brep", obj(vec![("spec", spec), ("origin", pv(pts[0])), ("label", s(&label))])), + ]); + add_op("extrudedSolids", vec![solid]) +} + +/// Grundkörper-Vorschau: `pts = [p0, p1?, Cursor?]` (`p1`/`cursor` Flags), `step`, `nums`. +fn solid_preview(v: &Value, pts: &[V], out: &mut Shapes) { + let Some(p0) = pts.first().copied() else { return }; + let mut rest = pts[1..].iter().copied(); + let p1 = if truthy(v.get("p1")) { rest.next() } else { None }; + let cur = if truthy(v.get("cursor")) { rest.next().unwrap_or(p0) } else { p0 }; + let nums: Vec = arr(v.get("nums")).iter().map(|x| num_of(Some(x))).collect(); + let num = |i: usize, d: f64| nums.get(i).copied().unwrap_or(d); + let dist = hypot2(cur.0 - p0.0, cur.1 - p0.1); + let step = s_of(v, "step"); + let shape = s_of(v, "shape"); + if shape == "cuboid" { + out.poly(&rect_corners(p0, p1.unwrap_or(cur))); + return; + } + let r = if step == "radius" || step == "major" { dist } else { num(0, dist) }; + if shape == "frustum" && step != "radius" { + out.poly(&circle_pts(p0, jsnum::max(if step == "topRadius" { dist } else { num(1, dist) }, 0.01), 48)); + } + out.poly(&circle_pts(p0, jsnum::max(r, 0.01), 48)); + if shape == "torus" && step == "minor" { + out.poly(&circle_pts(p0, num(0, 0.0) + dist, 48)); + } +} + +/// Punkt im Polygon (Strahl-Test, `|| 1e-12` gegen waagrechte Kanten). +fn point_in_polygon(p: V, poly: &[V]) -> bool { + let mut inside = false; + let n = poly.len(); + let mut j = n.wrapping_sub(1); + for i in 0..n { + let (a, b) = (poly[i], poly[j]); + let dy = b.1 - a.1; + let dy = if dy == 0.0 || dy.is_nan() { 1e-12 } else { dy }; + if (a.1 > p.1) != (b.1 > p.1) && p.0 < ((b.0 - a.0) * (p.1 - a.1)) / dy + a.0 { + inside = !inside; + } + j = i; + } + inside +} + +struct BBox { + x0: f64, + y0: f64, + x1: f64, + y1: f64, +} + +fn bbox(pts: &[V]) -> 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); + } + BBox { x0, y0, x1, y1 } +} + +fn solid_pts(s: &Value) -> Vec { + arr(field(s, "points")).iter().map(xy).collect() +} + +/// Kleinster Körper der Ebene, dessen Grundriss den Punkt enthält. +fn pick_solid<'a>(root: &'a Map, level: &str, at: V) -> Option<&'a Value> { + let mut best = None; + let mut best_area = f64::INFINITY; + for sd in arr(root.get("extrudedSolids")) { + let pts = solid_pts(sd); + if level_of(sd) != Some(level) || !point_in_polygon(at, &pts) { + continue; + } + let b = bbox(&pts); + let area = (b.x1 - b.x0) * (b.y1 - b.y0); + if area < best_area { + best = Some(sd); + best_area = area; + } + } + best +} + +/// Boolesche Verknüpfung zweier Körper (`combineSolids`): Grundriss als Hüllrechteck (Vereinigung, +/// Durchschnitt) bzw. der des ersten (Differenz), B-Rep `boolean` aus beiden Beschreibungen. +pub fn combine_solids(a: &Value, b: &Value, op: &str, id: String) -> Option { + let sa = extruded_solid_spec(a, 0.0)?; + let sb = extruded_solid_spec(b, 0.0)?; + let (pa, pb) = (solid_pts(a), solid_pts(b)); + let (ba, bb) = (bbox(&pa), bbox(&pb)); + let (ha, hb) = (num_of(field(a, "height")), num_of(field(b, "height"))); + let rect = |x0: f64, y0: f64, x1: f64, y1: f64| vec![pv((x0, y0)), pv((x1, y0)), pv((x1, y1)), pv((x0, y1))]; + let (points, height, label) = match op { + "union" => (rect(jsnum::min(ba.x0, bb.x0), jsnum::min(ba.y0, bb.y0), jsnum::max(ba.x1, bb.x1), jsnum::max(ba.y1, bb.y1)), jsnum::max(ha, hb), "Vereinigung"), + "difference" => (arr(field(a, "points")).to_vec(), ha, "Differenz"), + _ => { + let (x0, y0) = (jsnum::max(ba.x0, bb.x0), jsnum::max(ba.y0, bb.y0)); + let (x1, y1) = (jsnum::min(ba.x1, bb.x1), jsnum::min(ba.y1, bb.y1)); + if x1 - x0 < 1e-6 || y1 - y0 < 1e-6 { + return None; + } + (rect(x0, y0, x1, y1), jsnum::min(ha, hb), "Durchschnitt") + } + }; + let origin = points.first().cloned().unwrap_or(Value::Null); + Some(obj(vec![ + ("id", s(&id)), + ("type", s("extrudedSolid")), + ("levelId", field(a, "levelId").cloned().unwrap_or(Value::Null)), + ("points", Value::Array(points)), + ("height", js_num(height)), + ( + "brep", + obj(vec![ + ("spec", obj(vec![("kind", s("boolean")), ("op", s(op)), ("a", sa), ("b", sb)])), + ("origin", origin), + ("label", s(label)), + ]), + ), + ])) +} + +fn solidbool_ops(root: &Map, v: &Value, ids: &mut IdGen) -> Vec { + let (Some(a), Some(b)) = (find(root, "extrudedSolids", s_of(v, "a")), find(root, "extrudedSolids", s_of(v, "b"))) else { + return Vec::new(); + }; + let Some(merged) = combine_solids(a, b, s_of(v, "op"), ids.next("body")) else { return Vec::new() }; + let ids_ab: Vec<&str> = [id_of(a), id_of(b)].into_iter().flatten().collect(); + let mut ops = crate::cmd_create::remove_op(root, "extrudedSolids", &ids_ab); + ops.extend(add_op("extrudedSolids", vec![merged])); + ops +} + +/// Aussparungs-Quader (`voidFromInputs`): Grundriss-Rechteck, Höhe, Versatz über der UK. +fn voidbox_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let (a, b) = (p_of(v, "a"), p_of(v, "b")); + let (height, offset) = (n_of(v, "height"), n_of(v, "offset")); + if (b.0 - a.0).abs() < 1e-6 || (b.1 - a.1).abs() < 1e-6 || !(height > 1e-6) { + return Vec::new(); + } + let mut f = vec![ + ("id", s(&ids.next("void"))), + ("type", s("extrudedSolid")), + ("levelId", s(ctx.level)), + ("points", pvs(&rect_corners(a, b))), + ("height", js_num(height)), + ("operation", s("subtract")), + ]; + if offset.abs() > 1e-9 { + f.push(("baseOffset", js_num(offset))); + } + add_op("extrudedSolids", vec![obj(f)]) +} + +// ═════════════════════════════════════════════════════════════════════════════ +// Gelände aus Höhenlinien +// ═════════════════════════════════════════════════════════════════════════════ + +/// Gelände-TIN aus Höhenlinien (`generateTerrainFromContours`): alle endlichen Stützpunkte, Delaunay +/// über (x, y), Höhe der Kontur je Punkt; Null-Flächen-Dreiecke verworfen. +pub fn terrain_from_contours(contours: &[Value], id: &str) -> Value { + let (mut xs, mut ys, mut zs) = (Vec::new(), Vec::new(), Vec::new()); + for c in contours { + let z = num_of(field(c, "z")); + let z = if z.is_finite() { z } else { 0.0 }; + for p in arr(field(c, "pts")) { + let (x, y) = xy(p); + if !x.is_finite() || !y.is_finite() { + continue; + } + xs.push(x); + ys.push(y); + zs.push(z); + } + } + if xs.len() < 3 { + return json!({ "id": id, "type": "terrainMesh", "name": "Gelände", "categoryCode": "02", "positions": [], "indices": [] }); + } + let coords: Vec = xs.iter().zip(&ys).flat_map(|(x, y)| [*x, *y]).collect(); + let tri = crate::delaunay::triangulate(&coords); + let positions: Vec = (0..xs.len()).flat_map(|i| [js_num(xs[i]), js_num(ys[i]), js_num(zs[i])]).collect(); + let mut indices = Vec::new(); + for t in tri.chunks_exact(3) { + let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize); + let area2 = ((xs[b] - xs[a]) * (ys[c] - ys[a]) - (xs[c] - xs[a]) * (ys[b] - ys[a])).abs(); + if area2 <= 1e-9 { + continue; + } + indices.extend([Value::from(t[0]), Value::from(t[1]), Value::from(t[2])]); + } + obj(vec![ + ("id", s(id)), + ("type", s("terrainMesh")), + ("name", s("Gelände")), + ("layer", s("Terrain")), + ("categoryCode", s("02")), + ("positions", Value::Array(positions)), + ("indices", Value::Array(indices)), + ]) +} + +fn terrain_ops(root: &Map, ids: &mut IdGen) -> Vec { + let Some(set) = arr(root.get("context")).iter().find(|o| field(o, "type").and_then(Value::as_str) == Some("contourSet")) else { + return Vec::new(); + }; + let t = terrain_from_contours(arr(field(set, "contours")), &ids.next("terrain")); + if arr(field(&t, "indices")).is_empty() { + return Vec::new(); + } + add_op("context", vec![t]) +} + +// ═════════════════════════════════════════════════════════════════════════════ +// Decken-Aussparung, Dach-Hof, Schnitt-/Ansichtslinie +// ═════════════════════════════════════════════════════════════════════════════ + +fn ring_of(o: &Value) -> Vec { + arr(field(o, "outline")).iter().map(xy).collect() +} + +/// Rechteckige Aussparung in die Decke des Geschosses, die alle vier Ecken enthält. +fn ceiling_opening_ops(root: &Map, v: &Value, ctx: &Ctx) -> Vec { + let (a, b) = (p_of(v, "a"), p_of(v, "b")); + if (b.0 - a.0).abs() < 0.05 || (b.1 - a.1).abs() < 0.05 { + return Vec::new(); + } + let corners = rect_corners(a, b); + let host = arr(root.get("ceilings")).iter().find(|c| { + let ring = ring_of(c); + crate::cmd_create::floor_of(c) == Some(ctx.level) && ring.len() >= 3 && corners.iter().all(|p| point_in_polygon(*p, &ring)) + }); + let Some(host) = host else { return Vec::new() }; + let mut openings = arr(field(host, "openings")).to_vec(); + openings.push(pvs(&corners)); + vec![Op::Replace { collection: "ceilings".into(), entity: with(host, "openings", Value::Array(openings)) }] +} + +/// Hof-Ring des Dach-Hof-Befehls: ≥ 3 Punkte wie gezeichnet, 2 Punkte als Rechteck. +fn hole_ring(points: &[V]) -> Option> { + match points { + [a, b] => { + if (a.0 - b.0).abs() < 0.05 || (a.1 - b.1).abs() < 0.05 { + None + } else { + Some(rect_corners(*a, *b).to_vec()) + } + } + p if p.len() >= 3 => Some(p.to_vec()), + _ => None, + } +} + +/// Lässt das Dach-Skelett den Hof zu (eigene Traufe je Hof)? +fn roof_hole_works(roof: &Value, ring: &[V]) -> bool { + if ring.len() < 3 { + return false; + } + let mut holes = arr(field(roof, "holes")).to_vec(); + holes.push(pvs(ring)); + let n = holes.len(); + let probe = with(roof, "holes", Value::Array(holes)); + match serde_json::from_value::(probe) { + Ok(r) => crate::roof::roof_geometry(&r.params(), 0.0).eaves_holes.len() == n, + Err(_) => false, + } +} + +/// Hof in das Dach des Geschosses, das den Ring enthält und ihn zulässt. +fn roof_hole_ops(root: &Map, v: &Value, ctx: &Ctx) -> Vec { + let Some(ring) = hole_ring(&pts_of(v, "pts")) else { return Vec::new() }; + let host = arr(root.get("roofs")).iter().find(|r| { + let outline = ring_of(r); + crate::cmd_create::floor_of(r) == Some(ctx.level) + && outline.len() >= 3 + && ring.iter().all(|p| point_in_polygon(*p, &outline)) + && roof_hole_works(r, &ring) + }); + let Some(host) = host else { return Vec::new() }; + let mut holes = arr(field(host, "holes")).to_vec(); + holes.push(pvs(&ring)); + vec![Op::Replace { collection: "roofs".into(), entity: with(host, "holes", Value::Array(holes)) }] +} + +/// Buchstaben der nächsten Linie (A … Z, AA …) aus der Zahl vorhandener Ebenen dieser Art. +fn level_letters(count: usize) -> String { + let mut n = count as i64; + let mut letters = String::new(); + loop { + letters.insert(0, (b'A' + (n % 26) as u8) as char); + n = n / 26 - 1; + if n < 0 { + break; + } + } + letters +} + +/// Schnitt-/Ansichtslinie: eine verwaiste Ebene dieser Art bekommt die Linie, sonst eine neue Ebene +/// (`name` = Vorlage der Hülle mit `\u{1}` für die Buchstaben). +fn sectionline_ops(root: &Map, v: &Value, ids: &mut IdGen) -> Vec { + let (a, b) = (p_of(v, "a"), p_of(v, "b")); + if hypot2(b.0 - a.0, b.1 - a.1) < 0.1 { + return Vec::new(); + } + let kind = s_of(v, "kind"); + let line = Value::Array(vec![pv(a), pv(b)]); + let levels = arr(root.get("drawingLevels")); + let of_kind: Vec<&Value> = levels.iter().filter(|z| field(z, "kind").and_then(Value::as_str) == Some(kind)).collect(); + let orphans: Vec<&&Value> = of_kind.iter().filter(|z| !truthy(field(z, "linePoints"))).collect(); + if orphans.len() == 1 { + let z = *orphans[0]; + let sign = match field(z, "directionSign") { + None | Some(Value::Null) => js_num(1.0), + Some(x) => x.clone(), + }; + return vec![Op::Replace { collection: "drawingLevels".into(), entity: crate::grips::with_all(z, vec![("linePoints", line), ("directionSign", sign)]) }]; + } + let name = s_of(v, "name").replace('\u{1}', &level_letters(of_kind.len())); + add_op( + "drawingLevels", + vec![obj(vec![ + ("id", s(&ids.next(kind))), + ("name", s(&name)), + ("kind", s(kind)), + ("visible", Value::Bool(true)), + ("locked", Value::Bool(false)), + ("linePoints", line), + ("directionSign", js_num(1.0)), + ])], + ) +} + +/// Richtungspfeil der Schnittlinie (Mitte → Blickrichtung, zwei Flügel). +fn direction_arrow(a: V, b: V, sign: f64, out: &mut Shapes) { + let d = (b.0 - a.0, b.1 - a.1); + let len = hypot2(d.0, d.1); + if len < 1e-6 { + return; + } + let u = crate::cmd_create::normalize(d); + let (nx, ny) = (-u.1 * sign, u.0 * sign); + let m = ((a.0 + b.0) / 2.0, (a.1 + b.1) / 2.0); + let arrow = jsnum::min(1.0, len / 4.0); + let tip = (m.0 + nx * arrow, m.1 + ny * arrow); + let wing = arrow * 0.35; + let back = (tip.0 - nx * wing * 2.0, tip.1 - ny * wing * 2.0); + out.line(m, tip); + out.line(tip, (back.0 + u.0 * wing, back.1 + u.1 * wing)); + out.line(tip, (back.0 - u.0 * wing, back.1 - u.1 * wing)); +} + +// ═════════════════════════════════════════════════════════════════════════════ +// Einstiege (über `cmd_create`) +// ═════════════════════════════════════════════════════════════════════════════ + +pub fn ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Option> { + Some(match s_of(v, "cmd") { + "solid" => solid_ops(v, ctx, ids), + "solidbool" => solidbool_ops(root, v, ids), + "voidbox" => voidbox_ops(v, ctx, ids), + "terrain" => terrain_ops(root, ids), + "ceilingOpening" => ceiling_opening_ops(root, v, ctx), + "roofHole" => roof_hole_ops(root, v, ctx), + "sectionline" => sectionline_ops(root, v, ids), + _ => return None, + }) +} + +pub fn preview(root: &Map, v: &Value, pts: &[V], p: &mut Preview) -> bool { + match s_of(v, "cmd") { + "solid" => solid_preview(v, pts, &mut p.shapes), + "solidOutline" => match find(root, "extrudedSolids", s_of(v, "id")) { + Some(sd) => p.shapes.poly(&solid_pts(sd)), + None => p.ok = false, + }, + "voidbox" => { + if let [a, b] = pts { + let c = rect_corners(*a, *b); + p.shapes.poly(&c); + p.shapes.line(c[0], c[2]); + p.shapes.line(c[1], c[3]); + } + } + "sectionline" => { + if let [a, c] = pts { + p.shapes.line(*a, *c); + direction_arrow(*a, *c, 1.0, &mut p.shapes); + } + } + _ => return false, + } + true +} + +pub fn query(root: &Map, v: &Value) -> Option { + Some(match s_of(v, "q") { + "pickSolid" => json!({ "hit": pick_solid(root, s_of(v, "level"), p_of(v, "pt")).and_then(id_of) }), + _ => return None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn buchstaben_der_ebenen() { + assert_eq!(level_letters(0), "A"); + assert_eq!(level_letters(25), "Z"); + assert_eq!(level_letters(26), "AA"); + assert_eq!(level_letters(27), "AB"); + } + + #[test] + fn grundkoerper_und_spezifikation() { + assert!(solid_from_inputs("torus", (0.0, 0.0), None, &[0.3, 0.5]).is_none()); + let (_, h, spec, label) = solid_from_inputs("frustum", (1.0, 2.0), None, &[2.0, 1.0, 3.0]).unwrap(); + assert_eq!(h, 3.0); + assert_eq!(spec["kind"], "revolve"); + assert_eq!(label, "Kegelstumpf r=2.00/1.00 h=3.00"); + let solid = json!({"points": [{"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 1, "y": 1}], "height": 2, "taper": 0.5}); + assert_eq!(extruded_solid_spec(&solid, 1.0).unwrap()["kind"], "loft"); + } + + #[test] + fn gelaende_aus_hoehenlinien() { + let c = json!([{"z": 1, "pts": [{"x": 0, "y": 0}, {"x": 4, "y": 0}]}, {"z": 2, "pts": [{"x": 0, "y": 3}, {"x": 4, "y": 3}]}]); + let t = terrain_from_contours(c.as_array().unwrap(), "t"); + assert_eq!(t["indices"].as_array().unwrap().len(), 6); + assert_eq!(t["positions"][2], 1); + } +} diff --git a/src-tauri/core/src/commands.rs b/src-tauri/core/src/commands.rs index a617e85a..964c3f0d 100644 --- a/src-tauri/core/src/commands.rs +++ b/src-tauri/core/src/commands.rs @@ -15,12 +15,24 @@ fn parse(v: &Value, what: &str) -> Result, text: &str) -> Result, String> { let v: Value = serde_json::from_str(text).map_err(|e| format!("cmdOps: {e}"))?; + // Zeichnen in einer betretenen Gruppe: neue Elemente werden ihr Mitglied (`cmd_create::group_ops`). + if let Some(group) = v.get("group").and_then(Value::as_str) { + let mut inner = v.clone(); + inner.as_object_mut().map(|m| m.remove("group")); + let mut out = ops(root, &inner.to_string())?; + let extra = crate::cmd_create::group_ops(root, &out, group); + out.extend(extra); + return Ok(out); + } let cmd = v.get("cmd").and_then(Value::as_str).unwrap_or(""); let ids = |k: &str| -> Vec { v.get(k).and_then(|x| serde_json::from_value(x.clone()).ok()).unwrap_or_default() }; let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_string(); if let Some(ops) = crate::cmd_edit::ops(root, &v) { return Ok(ops); } + if let Some(ops) = crate::cmd_create::ops(root, &v) { + return Ok(ops); + } Ok(match cmd { "transform" => crate::cmd_transform::transform_ops(root, &parse(&v, cmd)?), "align" => crate::cmd_transform::align_ops(root, &ids("ids"), &s("mode")), diff --git a/src-tauri/core/src/jsnum.rs b/src-tauri/core/src/jsnum.rs index 46bd826a..d04fea72 100644 --- a/src-tauri/core/src/jsnum.rs +++ b/src-tauri/core/src/jsnum.rs @@ -3,7 +3,7 @@ //! - `Math.min/max` liefern bei NaN NaN (Rust `f64::min/max` ignorieren NaN). //! - `Math.round` rundet halbe Werte Richtung +∞ (Rust `round` weg von 0). //! - `x | 0` ist ToInt32 (Rest modulo 2³², Rust `as i32` sättigt). -//! - `Math.pow` (`x ** 3`) und Trigonometrie: im Web-Build (wasm32 + Feature "web") ruft der Kern `Math.cos/sin/tan/atan2/acos` +//! - `Math.pow` (`x ** 3`) und Trigonometrie: im Web-Build (wasm32 + Feature "web") ruft der Kern `Math.cos/sin/tan/atan/atan2/acos` //! der laufenden JS-Engine. Nur so sind die Werte bitgleich zur bisherigen TS-Fassung — V8 //! (glibc-abgeleitete sin/cos), JavaScriptCore (System-libm von macOS) und Rusts libm (musl) //! unterscheiden sich in einzelnen Fällen in der letzten Stelle. Nativ (`cargo test`, Tauri) @@ -27,6 +27,12 @@ mod trig { fn js_pow(x: f64, y: f64) -> f64; #[wasm_bindgen(js_namespace = Math, js_name = tan)] fn js_tan(x: f64) -> f64; + #[wasm_bindgen(js_namespace = Math, js_name = atan)] + fn js_atan(x: f64) -> f64; + } + #[inline] + pub fn atan(x: f64) -> f64 { + js_atan(x) } #[inline] pub fn tan(x: f64) -> f64 { @@ -81,9 +87,13 @@ mod trig { pub fn tan(x: f64) -> f64 { x.tan() } + #[inline] + pub fn atan(x: f64) -> f64 { + x.atan() + } } -pub use trig::{acos, atan2, cos, pow, sin, tan}; +pub use trig::{acos, atan, atan2, cos, pow, sin, tan}; /// Endliche Zahl oder 0 (NaN/±∞ → 0; Summen der Kennzahlen/Flächen). #[inline] diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index f4e0a899..f97702e1 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -91,6 +91,9 @@ pub mod project_refs; pub mod commands; pub mod cmd_transform; pub mod cmd_edit; +pub mod cmd_create; +pub mod cmd_draw; +pub mod cmd_solid; pub mod polyline_vertex; #[cfg(feature = "web")] diff --git a/src-tauri/core/src/web/auto_dimensions.rs b/src-tauri/core/src/web/auto_dimensions.rs deleted file mode 100644 index 10376205..00000000 --- a/src-tauri/core/src/web/auto_dimensions.rs +++ /dev/null @@ -1,41 +0,0 @@ -//! Bindungen der automatischen Aussenbemassung (`crate::auto_dimensions`). - -use crate::auto_dimensions::{self, OpeningIn, WallIn}; -use crate::flat_read::Reader; -use wasm_bindgen::prelude::wasm_bindgen; - -fn read_walls(buf: &[f64]) -> Option> { - let mut r = Reader::new(buf); - let n = r.count()?; - let mut out = Vec::with_capacity(n.min(1 << 16)); - for _ in 0..n { - out.push(WallIn { start: [r.num()?, r.num()?], end: [r.num()?, r.num()?], thickness: r.num()? }); - } - Some(out) -} - -fn read_openings(buf: &[f64]) -> Option> { - let mut r = Reader::new(buf); - let n = r.count()?; - let mut out = Vec::with_capacity(n.min(1 << 16)); - for _ in 0..n { - let wall = r.count()?; - out.push(OpeningIn { wall, jamb_start: [r.num()?, r.num()?], jamb_end: [r.num()?, r.num()?] }); - } - Some(out) -} - -/// Wände `[n, (x0, y0, x1, y1, dicke)…]`, Öffnungen `[n, (wandIndex, ax, ay, bx, by)…]` -/// → `[n, (seite, kette, abstand, nPkt, x, y, …)…]` (Seite 0..3 = Süd/Ost/Nord/West, -/// Kette 0..2 = Öffnungen/Vor-Rücksprünge/Gesamt). -#[wasm_bindgen] -pub fn autodim_chains(walls: &[f64], openings: &[f64], scale_denominator: f64) -> Vec { - let (Some(w), Some(o)) = (read_walls(walls), read_openings(openings)) else { return vec![0.0] }; - let chains = auto_dimensions::auto_exterior_dimensions(&w, &o, scale_denominator); - let mut out = vec![chains.len() as f64]; - for c in chains { - out.extend([c.side as f64, c.chain as f64, c.offset, c.pts.len() as f64]); - out.extend(c.pts.into_iter().flatten()); - } - out -} diff --git a/src-tauri/core/src/web/bulge.rs b/src-tauri/core/src/web/bulge.rs index fe652392..3cc7a5f0 100644 --- a/src-tauri/core/src/web/bulge.rs +++ b/src-tauri/core/src/web/bulge.rs @@ -32,24 +32,3 @@ pub fn bulge_from_sagitta_point(ax: f64, ay: f64, bx: f64, by: f64, px: f64, py: pub fn bulge_point_at(ax: f64, ay: f64, bx: f64, by: f64, bulge: f64, t: f64) -> Vec { b::point_at(ax, ay, bx, by, bulge, t) } - -#[wasm_bindgen] -pub fn bulge_through_point(ax: f64, ay: f64, tx: f64, ty: f64, bx: f64, by: f64) -> f64 { - b::through_point(ax, ay, tx, ty, bx, by) -} - -/// `[cx, cy, r, a0, a1]` (CCW) oder leer. -#[wasm_bindgen] -pub fn arc_through_points(ax: f64, ay: f64, tx: f64, ty: f64, bx: f64, by: f64) -> Vec { - b::arc_through_points(ax, ay, tx, ty, bx, by) -} - -#[wasm_bindgen] -pub fn arc_from_start_end_radius(ax: f64, ay: f64, bx: f64, by: f64, r: f64, nx: f64, ny: f64) -> Vec { - b::arc_from_start_end_radius(ax, ay, bx, by, r, nx, ny) -} - -#[wasm_bindgen] -pub fn arc_from_start_end_direction(ax: f64, ay: f64, bx: f64, by: f64, dx: f64, dy: f64) -> Vec { - b::arc_from_start_end_direction(ax, ay, bx, by, dx, dy) -} diff --git a/src-tauri/core/src/web/cmd_create.rs b/src-tauri/core/src/web/cmd_create.rs new file mode 100644 index 00000000..0c6a1998 --- /dev/null +++ b/src-tauri/core/src/web/cmd_create.rs @@ -0,0 +1,72 @@ +//! Bindungen der Zeichenbefehle (`crate::cmd_create`): Vorschau je Mausschritt (Optionen als JSON, die +//! Punkte flach) und Treffer-Abfragen zwischen den Schritten. Der Commit läuft über `doc_cmd_commit`. +//! +//! Je Mausschritt ändern sich meist nur die Punkte: die zuletzt gelesenen Optionen bleiben hier liegen, +//! `doc_create_preview_again` rechnet mit ihnen (kein JSON hin und kein Parsen je Mausschritt — die +//! Wand-Vorschau ist sonst langsamer als die frühere TS-Fassung). + +use super::document::with_doc; +use crate::cmd_create::Req; +use serde_json::Value; +use std::cell::RefCell; +use wasm_bindgen::prelude::wasm_bindgen; + +thread_local! { + static LAST_REQ: RefCell> = const { RefCell::new(None) }; +} + +fn run(h: u32, req: &Req, pts: &[f64]) -> Vec { + if pts.len() % 2 != 0 { + return Vec::new(); + } + with_doc(h, |d| crate::cmd_create::preview_req(d.root(), req, pts).flat()).unwrap_or_default() +} + +/// Vorschau eines Zeichenbefehls auf dem Dokument `h`: `[ok, nInfo, info…, Formen…]` (Formen wie +/// `doc_cmd_preview`); leer bei Fehler. Merkt sich die Optionen für [`doc_create_preview_again`]. +#[wasm_bindgen] +pub fn doc_create_preview(h: u32, req_json: &str, pts: &[f64]) -> Vec { + let req = serde_json::from_str::(req_json).ok().filter(Value::is_object).map(Req::new); + let out = req.as_ref().map_or_else(Vec::new, |r| run(h, r, pts)); + LAST_REQ.with(|l| *l.borrow_mut() = req); + out +} + +/// Wie [`doc_create_preview`] mit den zuletzt übergebenen Optionen (nur neue Punkte). +#[wasm_bindgen] +pub fn doc_create_preview_again(h: u32, pts: &[f64]) -> Vec { + LAST_REQ.with(|l| l.borrow().as_ref().map_or_else(Vec::new, |r| run(h, r, pts))) +} + +/// Treffer-Abfrage eines Zeichenbefehls (`crate::cmd_create::query`), Antwort-JSON (Zahlen mit +/// Nicht-endlich-Marken); Fehler als Text mit `\u{1}` vorn. +#[wasm_bindgen] +pub fn doc_create_query(h: u32, req_json: &str) -> String { + let v: Value = match serde_json::from_str(req_json) { + Ok(v) => v, + Err(e) => return format!("\u{1}Zeichen-Abfrage: {e}"), + }; + match with_doc(h, |d| crate::cmd_create::query(d.root(), &v)) { + Some(Some(Ok(v))) => v.to_string(), + Some(Some(Err(e))) => format!("\u{1}{e}"), + Some(None) => "\u{1}Unbekannte Zeichen-Abfrage".to_string(), + None => "\u{1}Dokument nicht offen".to_string(), + } +} + +/// B-Rep-Beschreibung eines Körpers (`crate::cmd_solid::extruded_solid_spec`) als JSON (Zahlen mit +/// Nicht-endlich-Marken); leer = keine Beschreibung oder kein Körper. +#[wasm_bindgen] +pub fn extruded_solid_spec_json(solid_json: &str, floor_z: f64) -> String { + serde_json::from_str::(solid_json) + .ok() + .and_then(|s| crate::cmd_solid::extruded_solid_spec(&s, floor_z)) + .map_or_else(String::new, |v| v.to_string()) +} + +/// Gelände-TIN aus Höhenlinien (`crate::cmd_solid::terrain_from_contours`) als JSON; `id` des Netzes. +#[wasm_bindgen] +pub fn terrain_from_contours_json(contours_json: &str, id: &str) -> String { + let c: Value = serde_json::from_str(contours_json).unwrap_or(Value::Null); + crate::cmd_solid::terrain_from_contours(c.as_array().map(Vec::as_slice).unwrap_or(&[]), id).to_string() +} diff --git a/src-tauri/core/src/web/curves.rs b/src-tauri/core/src/web/curves.rs index 150802fb..4b4c1121 100644 --- a/src-tauri/core/src/web/curves.rs +++ b/src-tauri/core/src/web/curves.rs @@ -2,12 +2,6 @@ use wasm_bindgen::prelude::wasm_bindgen; -/// Punkte einer (gedrehten) Ellipse, `n` gleichverteilte Parameterschritte. -#[wasm_bindgen] -pub fn curves_ellipse_flat(cx: f64, cy: f64, rx: f64, ry: f64, rotation: f64, n: f64) -> Vec { - crate::curves::ellipse(cx, cy, rx, ry, rotation, n) -} - /// Kubische Bezier-Kette (Anker·Griff·Griff·Anker …); unter 4 Punkten unverändert. #[wasm_bindgen] pub fn curves_bezier_chain_flat(pts: &[f64], segs_per_curve: f64) -> Vec { diff --git a/src-tauri/core/src/web/kernel2d.rs b/src-tauri/core/src/web/kernel2d.rs index a1b0aa54..f1146cb1 100644 --- a/src-tauri/core/src/web/kernel2d.rs +++ b/src-tauri/core/src/web/kernel2d.rs @@ -8,7 +8,7 @@ //! Kaputte Eingaben (ungerade Längen, falsche Zählungen, ungültige Indizes) ergeben ein //! leeres Ergebnis statt eines Panics. -use kernel2d::{self as k, TangentTarget, Vec2}; +use kernel2d::{self as k, Vec2}; use wasm_bindgen::prelude::wasm_bindgen; // --- Lesen ------------------------------------------------------------------- @@ -61,16 +61,6 @@ fn pt_lists(buf: &[f64]) -> Option>> { (0..n).map(|_| r.count().and_then(|m| r.pts(m))).collect() } -fn tangent_target(buf: &[f64]) -> Option { - match *buf { - [kind, ax, ay, bx, by] if kind == 0.0 => { - Some(TangentTarget::Line { a: Vec2::new(ax, ay), b: Vec2::new(bx, by) }) - } - [kind, cx, cy, r, _] if kind == 1.0 => Some(TangentTarget::Circle { center: Vec2::new(cx, cy), r }), - _ => None, - } -} - // --- Schreiben --------------------------------------------------------------- fn push_pts(out: &mut Vec, pts: &[Vec2]) { @@ -107,40 +97,13 @@ const EMPTY_LIST: [f64; 1] = [0.0]; // --- Punkt/Strecke, Fläche, Kreise --------------------------------------------- -#[wasm_bindgen] -pub fn k2_point_segment_distance(px: f64, py: f64, ax: f64, ay: f64, bx: f64, by: f64) -> f64 { - k::point_segment_distance(Vec2::new(px, py), Vec2::new(ax, ay), Vec2::new(bx, by)) -} - -#[wasm_bindgen] -pub fn k2_signed_area(p: &[f64]) -> f64 { - pts(p).map_or(0.0, |p| k::signed_area(&p)) -} - -#[wasm_bindgen] -pub fn k2_is_ccw(p: &[f64]) -> bool { - pts(p).is_some_and(|p| k::is_ccw(&p)) -} - #[wasm_bindgen] pub fn k2_circle_circle_intersect(c1x: f64, c1y: f64, r1: f64, c2x: f64, c2y: f64, r2: f64) -> Vec { enc_pts(&k::circle_circle_intersect(Vec2::new(c1x, c1y), r1, Vec2::new(c2x, c2y), r2)) } -#[wasm_bindgen] -pub fn k2_tangent_circle_centers(t1: &[f64], t2: &[f64], r: f64) -> Vec { - let (Some(t1), Some(t2)) = (tangent_target(t1), tangent_target(t2)) else { return Vec::new() }; - enc_pts(&k::tangent_circle_centers(t1, t2, r)) -} - // --- Offset ------------------------------------------------------------------ -#[wasm_bindgen] -pub fn k2_offset_segment(ax: f64, ay: f64, bx: f64, by: f64, d: f64) -> Vec { - let (a, b) = k::offset_segment(Vec2::new(ax, ay), Vec2::new(bx, by), d); - vec![a.x, a.y, b.x, b.y] -} - // --- Trim / Extend ----------------------------------------------------------- @@ -151,25 +114,6 @@ pub fn k2_offset_segment(ax: f64, ay: f64, bx: f64, by: f64, d: f64) -> Vec // --- Ecken ------------------------------------------------------------------- -/// `[cx, cy, radius, tAx, tAy, tBx, tBy, startAngle, endAngle]` oder leer. -#[wasm_bindgen] -pub fn k2_fillet_corner(cx: f64, cy: f64, p1x: f64, p1y: f64, p2x: f64, p2y: f64, r: f64) -> Vec { - match k::fillet_corner(Vec2::new(cx, cy), Vec2::new(p1x, p1y), Vec2::new(p2x, p2y), r) { - Some(f) => vec![ - f.center.x, - f.center.y, - f.radius, - f.tangent_a.x, - f.tangent_a.y, - f.tangent_b.x, - f.tangent_b.y, - f.start_angle, - f.end_angle, - ], - None => Vec::new(), - } -} - // --- Split / Join / Segment löschen / Bruch ---------------------------------------- diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index bda856ea..8335e1dd 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -8,7 +8,6 @@ mod polygon; mod roof; mod sun; mod site_rules; -mod auto_dimensions; mod kennzahlen; mod bulge; mod stair; @@ -40,6 +39,7 @@ mod text_layout; mod grips; mod project_refs; mod commands; +mod cmd_create; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/room_boundary.rs b/src-tauri/core/src/web/room_boundary.rs index 202e170a..d79bd286 100644 --- a/src-tauri/core/src/web/room_boundary.rs +++ b/src-tauri/core/src/web/room_boundary.rs @@ -8,15 +8,3 @@ use wasm_bindgen::prelude::wasm_bindgen; pub fn rooms_detect(walls: &[f64], gap_tol: f64, min_area: f64, offset_to_inner: bool) -> Vec { rb::detect(walls, gap_tol, min_area, offset_to_inner) } - -/// Umriss der Zelle um den Punkt `[nPkt, x, y, …]`, leer = keine. -#[wasm_bindgen] -pub fn room_from_point(px: f64, py: f64, walls: &[f64], gap_tol: f64, offset_to_inner: bool) -> Vec { - rb::from_point(px, py, walls, gap_tol, offset_to_inner) -} - -/// Wie `room_from_point`, aber auf fertigen Wand-Innenflächen (ohne Offset). -#[wasm_bindgen] -pub fn room_from_point_faces(px: f64, py: f64, faces: &[f64], gap_tol: f64) -> Vec { - rb::from_point_faces(px, py, faces, gap_tol) -} diff --git a/src-tauri/core/src/web/stair.rs b/src-tauri/core/src/web/stair.rs index 0fa6e15b..d11f9825 100644 --- a/src-tauri/core/src/web/stair.rs +++ b/src-tauri/core/src/web/stair.rs @@ -3,26 +3,8 @@ use crate::stair as s; use wasm_bindgen::prelude::wasm_bindgen; -/// Parameter (16 Zahlen) + Gesamt-Steighöhe → flache Treppengeometrie; Unsinn → leer. -#[wasm_bindgen] -pub fn stair_geometry_flat(params: &[f64], total_rise: f64) -> Vec { - s::geometry(params, total_rise) -} - /// Plan-Aussenlinie: `[0, n, x, y …]` (Polygon) oder `[1, …]` (Wendel). #[wasm_bindgen] pub fn stair_outline_flat(params: &[f64]) -> Vec { s::outline(params) } - -/// Schnittaufteilung aus flacher Geometrie und Schnitthöhe über der Treppen-UK. -#[wasm_bindgen] -pub fn stair_cut_flat(geometry: &[f64], cut_rise: f64) -> Vec { - s::cut(geometry, cut_rise) -} - -/// Vorgabe-Stufenzahl aus Steighöhe und Lauflänge. -#[wasm_bindgen] -pub fn stair_default_step_count(total_rise: f64, run_length: f64) -> u32 { - s::default_step_count(total_rise, run_length) -} diff --git a/src/App.tsx b/src/App.tsx index 4ebb74f7..8ebfdecd 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -156,8 +156,8 @@ import { useGripEditing } from "./state/useGripEditing"; import { usePanelHostBase } from "./state/usePanelHostBase"; import { useDockDragState } from "./state/useDockDragState"; import { useMouseSelectionHandlers } from "./state/useMouseSelectionHandlers"; -import { activeGroupOps, containingGroupId, EMPTY_MEMBERSHIP } from "./state/groupActions"; -import { addItems, fieldOps, opsMutation, patchItem, patchItems, removeItems, replaceItem, replaceWithMany, setFieldIfChanged } from "./core"; +import { containingGroupId, EMPTY_MEMBERSHIP } from "./state/groupActions"; +import { addItems, cmdMutation, fieldOps, opsMutation, patchItem, patchItems, removeItems, replaceItem, replaceWithMany, setFieldIfChanged } from "./core"; import type { GroupMembership, MemberKind } from "./state/groupActions"; import { isLocked, lockMembersOps } from "./state/objectLock"; import { useProjectFileActions } from "./state/useProjectFileActions"; @@ -938,16 +938,13 @@ export default function App() { // Zeichnet man WÄHREND man eine Gruppe betreten hat (Isolation), wird // das neue Element automatisch Mitglied dieser Gruppe (Nutzer-Wunsch: // „wenn man etwas neu zeichnet ... zeichnet man in der Gruppe"). [K4] S3: - // Befehle tragen ihre Ops mit (`opsMutation`); die Gruppen-Zuordnung kommt - // als weitere Ops dazu (`activeGroupOps`). + // Befehle tragen ihre Kern-Anfrage mit (`cmdMutation`); die Gruppen-Zuordnung + // rechnet der Kern im selben Commit (`group`, `cmd_create::group_ops`). commit: (mutate) => { const groupPath = cmdLatest.current.groupPath; - cmdLatest.current.setProject( - opsMutation((p) => { - const ops = mutate.toOps(p); - return [...ops, ...activeGroupOps(p, ops, groupPath)]; - }), - ); + const group = groupPath[groupPath.length - 1]; + // Befehle ohne Kern-Anfrage (Georeferenz, Ausrichten) legen keine Elemente an. + cmdLatest.current.setProject(group && mutate.coreReq ? cmdMutation({ ...mutate.coreReq, group }) : mutate); }, isFloor: () => cmdLatest.current.activeLevel.kind === "floor", // Frisch über `text`/`textbox` erzeugtes Element sofort inline editieren diff --git a/src/commands/cmds/arc.ts b/src/commands/cmds/arc.ts index 3be38e40..c4d1604a 100644 --- a/src/commands/cmds/arc.ts +++ b/src/commands/cmds/arc.ts @@ -12,17 +12,17 @@ // 1) „Startpunkt:" → Punkt // 2) „Durchgangspunkt:" → Punkt (nur Vorschau-Linie, noch kein Bogen) // 3) „Endpunkt:" → Punkt → commit (Kreis durch alle drei Punkte, -// s. `geometry/bulge.ts` `arcThroughPoints`) +// s. `kernel2d::arc_through_points`, Kern `cmd_draw.rs`) // • Start-Ende-Radius: Start + Ende + Radius (getippt ODER als Punkt — Abstand // von der Sehnen-Mitte, wie bei `fillet.ts`s Radius-Schritt). Der Bogen // wölbt sich zur Seite, auf der der Cursor/Radius-Punkt steht (immer der -// kleinere der beiden möglichen Bögen, s. `arcFromStartEndRadius`). +// kleinere der beiden möglichen Bögen, s. `kernel2d::arc_from_start_end_radius`). // 1) „Startpunkt:" → Punkt // 2) „Endpunkt:" → Punkt // 3) „Radius:" → Punkt ODER Zahl → commit // • Start-Ende-Richtung: Start + Ende + Tangentenrichtung bei Start (klassische // dritte AutoCAD-ARC-Methode). Eindeutig bestimmt (kein Seiten-Wahl nötig), -// s. `arcFromStartEndDirection`. +// s. `kernel2d::arc_from_start_end_direction`. // 1) „Startpunkt:" → Punkt // 2) „Endpunkt:" → Punkt // 3) „Richtung:" → Punkt (Tangentenrichtung bei Start) → commit @@ -31,9 +31,6 @@ // Rendering in PlanView). In generatePlan/PlanView als glatter SVG-Bogen // (`drawingArc`) gerendert. -import type { Drawing2D } from "../../model/types"; -import { uniqueId } from "../../tools/types"; -import { arcFromStartEndDirection, arcFromStartEndRadius, arcThroughPoints } from "../../core"; import type { Command, CommandContext, @@ -41,13 +38,11 @@ import type { CommandResult, CommandState, CmdOption, - DraftShape, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview, type CreatePreview } from "../createCore"; const EPS = 1e-6; @@ -83,8 +78,8 @@ interface ArcCenterPhase3 extends CommandState { phase: "end"; method: "center"; center: Vec2; - r: number; - a0: number; + /** Startpunkt (setzt Radius und Startwinkel). */ + start: Vec2; cursor: Vec2 | null; } interface ArcThreePhase1 extends CommandState { @@ -153,48 +148,24 @@ type ArcState = | ArcThreePhase3; const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); -const angle = (c: Vec2, p: Vec2): number => Math.atan2(p.y - c.y, p.x - c.x); const mid = (a: Vec2, b: Vec2): Vec2 => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }); -/** CCW-Spanne von a0 nach a1, normiert auf (0, 2π]. */ -function sweepOf(a0: number, a1: number): number { - const TAU = Math.PI * 2; - const s = ((a1 - a0) % TAU + TAU) % TAU; - return s < EPS ? TAU : s; -} - -/** Punkte eines Bogens (CCW a0→a1) für die Vorschau. */ -function arcPts(center: Vec2, r: number, a0: number, a1: number): Vec2[] { - const sweep = sweepOf(a0, a1); - const N = Math.max(2, Math.ceil(sweep / (Math.PI / 32))); - const pts: Vec2[] = []; - for (let i = 0; i <= N; i++) { - const t = a0 + (sweep * i) / N; - pts.push({ x: center.x + r * Math.cos(t), y: center.y + r * Math.sin(t) }); - } - return pts; -} - -/** Punkte einer vollen Kreis-Approximation (Radius-Vorschau im „start"-Schritt). */ -function circlePts(center: Vec2, r: number): Vec2[] { - const N = 48; - const pts: Vec2[] = []; - for (let i = 0; i < N; i++) { - const t = (i / N) * Math.PI * 2; - pts.push({ x: center.x + r * Math.cos(t), y: center.y + r * Math.sin(t) }); - } - return pts; -} +/** + * Bogen im Kern (`cmd_draw.rs`) je Methode aus den Punkten: Mittelpunkt (Mitte, Start, Ende), 3-Punkt, + * Start-Ende-Radius (Radius = Abstand des dritten Punkts von der Sehnenmitte oder getippt), + * Start-Ende-Richtung; `ok` = bestimmt, `info = [cx, cy, r, Spanne°]`. `full`: voller Kreis um den + * Mittelpunkt durch den Cursor (Radius-Vorschau im „start"-Schritt). + */ +const arcAt = (ctx: CommandContext, req: Record, pts: Vec2[]): CreatePreview => + createPreview(ctx, { cmd: "arc", ...req }, pts); /** Vorschau (offener Bogen) + HUD (Radius als L, Spanne als W — L/W-Kästchen). */ -function arcDraft(center: Vec2, r: number, a0: number, a1: number, at: Vec2 | null): ToolDraft { +function arcDraft(pv: CreatePreview, at: Vec2 | null): ToolDraft { + const [cx, cy, r, deg] = pv.info; + const center = { x: cx, y: cy }; if (r < EPS) return { preview: [], vertices: [center] }; - const preview: DraftShape[] = [{ kind: "poly", pts: arcPts(center, r, a0, a1), closed: false }]; - const draft: ToolDraft = { preview, vertices: [center] }; - if (at) { - const deg = (sweepOf(a0, a1) * 180) / Math.PI; - draft.hud = { at, length: r, angleDeg: deg }; - } + const draft: ToolDraft = { preview: pv.shapes, vertices: [center] }; + if (at) draft.hud = { at, length: r, angleDeg: deg }; return draft; } @@ -203,17 +174,8 @@ function lineDraft(a: Vec2, b: Vec2): ToolDraft { return { preview: [{ kind: "line", a, b }], vertices: [a] }; } -function appendArc(center: Vec2, r: number, a0: number, a1: number, ctx: CommandContext): CoreOp[] { - if (r < EPS) return []; - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "arc", center, r, a0, a1 }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern): Bogen aus der Anfrage (entartet r < EPS → nichts). */ +const appendArc = (ctx: CommandContext, req: Record) => createMutation(ctx, { cmd: "arc", ...req }); const idle = (method: ArcMethod): [CommandState, CommandResult] => [ (method === "center" ? { phase: "center", method } : { phase: "p1", method }) as ArcState, @@ -265,12 +227,9 @@ export const arcCommand: Command = { // zuletzt bekannten Cursor (wie beim Tab-Feld-Controller sonst auch). if (input.kind === "number" && s.method === "ser" && s.phase === "radius") { const near = s.cursor ?? { x: s.b.x, y: s.b.y }; - const arc = arcFromStartEndRadius(s.a, s.b, input.value, near); - if (!arc) return [s, { draft: null }]; - return [ - idle("ser")[0], - { draft: null, done: true, commit: opsMutation(() => appendArc(arc.center, arc.r, arc.a0, arc.a1, ctx)) }, - ]; + const req = { method: "ser", pts: [s.a, s.b, near], r: input.value }; + if (!arcAt(ctx, req, [s.a, s.b, near]).ok) return [s, { draft: null }]; + return [idle("ser")[0], { draft: null, done: true, commit: appendArc(ctx, req) }]; } if (input.kind !== "point") return [s, { draft: null }]; const pt = input.point; @@ -281,18 +240,15 @@ export const arcCommand: Command = { return [ns, { draft: { preview: [], vertices: [pt] } }]; } if (s.phase === "start") { - const r = dist(s.center, pt); - if (r < EPS) return [s, { draft: null }]; - const a0 = angle(s.center, pt); - const ns: ArcCenterPhase3 = { phase: "end", method: "center", center: s.center, r, a0, cursor: pt, lastPoint: pt }; - return [ns, { draft: arcDraft(s.center, r, a0, a0, pt) }]; + const pv = arcAt(ctx, { method: "center" }, [s.center, pt, pt]); + if (pv.info[2] < EPS) return [s, { draft: null }]; + const ns: ArcCenterPhase3 = { phase: "end", method: "center", center: s.center, start: pt, cursor: pt, lastPoint: pt }; + return [ns, { draft: arcDraft(pv, pt) }]; } // Endpunkt: Endwinkel setzen, Bogen committen. - const a1 = angle(s.center, pt); - const { center, r, a0 } = s; return [ idle("center")[0], - { draft: null, done: true, commit: opsMutation(() => appendArc(center, r, a0, a1, ctx)) }, + { draft: null, done: true, commit: appendArc(ctx, { method: "center", pts: [s.center, s.start, pt] }) }, ]; } @@ -308,12 +264,9 @@ export const arcCommand: Command = { return [ns, { draft: lineDraft(s.a, pt) }]; } // phase "p3": Endpunkt → Kreis durch alle drei Punkte, committen. - const arc = arcThroughPoints(s.a, s.through, pt); - if (!arc) return [s, { draft: lineDraft(s.a, pt) }]; // kollinear — Punkt ignorieren, weiter warten - return [ - idle("three")[0], - { draft: null, done: true, commit: opsMutation(() => appendArc(arc.center, arc.r, arc.a0, arc.a1, ctx)) }, - ]; + const req = { method: "three", pts: [s.a, s.through, pt] }; + if (!arcAt(ctx, req, [s.a, s.through, pt]).ok) return [s, { draft: lineDraft(s.a, pt) }]; // kollinear — Punkt ignorieren, weiter warten + return [idle("three")[0], { draft: null, done: true, commit: appendArc(ctx, req) }]; } // Methode „ser" (Start-Ende-Radius). @@ -328,12 +281,9 @@ export const arcCommand: Command = { return [ns, { draft: lineDraft(s.a, pt) }]; } // phase "radius": Radius-Punkt → committen (Seite = dieser Punkt). - const arc = arcFromStartEndRadius(s.a, s.b, dist(mid(s.a, s.b), pt), pt); - if (!arc) return [s, { draft: lineDraft(s.a, s.b) }]; // Radius zu klein — weiter warten - return [ - idle("ser")[0], - { draft: null, done: true, commit: opsMutation(() => appendArc(arc.center, arc.r, arc.a0, arc.a1, ctx)) }, - ]; + const req = { method: "ser", pts: [s.a, s.b, pt] }; + if (!arcAt(ctx, req, [s.a, s.b, pt]).ok) return [s, { draft: lineDraft(s.a, s.b) }]; // Radius zu klein — weiter warten + return [idle("ser")[0], { draft: null, done: true, commit: appendArc(ctx, req) }]; } // Methode „sed" (Start-Ende-Richtung). @@ -347,35 +297,31 @@ export const arcCommand: Command = { return [ns, { draft: lineDraft(s.a, pt) }]; } // phase "direction": Richtungspunkt → committen. - const sedArc = arcFromStartEndDirection(s.a, s.b, pt); - if (!sedArc) return [s, { draft: lineDraft(s.a, s.b) }]; // entartete Richtung — weiter warten - return [ - idle("sed")[0], - { draft: null, done: true, commit: opsMutation(() => appendArc(sedArc.center, sedArc.r, sedArc.a0, sedArc.a1, ctx)) }, - ]; + const req = { method: "sed", pts: [s.a, s.b, pt] }; + if (!arcAt(ctx, req, [s.a, s.b, pt]).ok) return [s, { draft: lineDraft(s.a, s.b) }]; // entartete Richtung — weiter warten + return [idle("sed")[0], { draft: null, done: true, commit: appendArc(ctx, req) }]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as ArcState; if (s.method === "center") { if (s.phase === "start") { - const r = dist(s.center, point); + const pv = arcAt(ctx, { full: true }, [s.center, point]); const ns: ArcCenterPhase2 = { ...s, cursor: point }; return [ ns, { draft: { - preview: [{ kind: "poly", pts: circlePts(s.center, r), closed: true }], + preview: pv.shapes, vertices: [s.center], - hud: { at: point, text: `R: ${r.toFixed(3)}m` }, + hud: { at: point, text: `R: ${pv.info[2].toFixed(3)}m` }, }, }, ]; } if (s.phase === "end") { - const a1 = angle(s.center, point); const ns: ArcCenterPhase3 = { ...s, cursor: point }; - return [ns, { draft: arcDraft(s.center, s.r, s.a0, a1, point) }]; + return [ns, { draft: arcDraft(arcAt(ctx, { method: "center" }, [s.center, s.start, point]), point) }]; } return [s, { draft: null }]; } @@ -387,18 +333,18 @@ export const arcCommand: Command = { } if (s.phase === "p3") { const ns: ArcThreePhase3 = { ...s, cursor: point }; - const arc = arcThroughPoints(s.a, s.through, point); - return [ns, { draft: arc ? arcDraft(arc.center, arc.r, arc.a0, arc.a1, point) : lineDraft(s.a, point) }]; + const pv = arcAt(ctx, { method: "three" }, [s.a, s.through, point]); + return [ns, { draft: pv.ok ? arcDraft(pv, point) : lineDraft(s.a, point) }]; } if (s.phase === "radius") { const ns: ArcSerPhase3 = { ...s, cursor: point }; - const arc = arcFromStartEndRadius(s.a, s.b, dist(mid(s.a, s.b), point), point); - return [ns, { draft: arc ? arcDraft(arc.center, arc.r, arc.a0, arc.a1, point) : lineDraft(s.a, s.b) }]; + const pv = arcAt(ctx, { method: "ser" }, [s.a, s.b, point]); + return [ns, { draft: pv.ok ? arcDraft(pv, point) : lineDraft(s.a, s.b) }]; } if (s.phase === "direction") { const ns: ArcSedPhase3 = { ...s, cursor: point }; - const arc = arcFromStartEndDirection(s.a, s.b, point); - return [ns, { draft: arc ? arcDraft(arc.center, arc.r, arc.a0, arc.a1, point) : lineDraft(s.a, s.b) }]; + const pv = arcAt(ctx, { method: "sed" }, [s.a, s.b, point]); + return [ns, { draft: pv.ok ? arcDraft(pv, point) : lineDraft(s.a, s.b) }]; } return [s, { draft: null }]; }, diff --git a/src/commands/cmds/autodim.ts b/src/commands/cmds/autodim.ts index 3e19d5f8..f68066d7 100644 --- a/src/commands/cmds/autodim.ts +++ b/src/commands/cmds/autodim.ts @@ -1,12 +1,11 @@ // Aussenbemassung ([81]) — Sofort-Befehl ohne Punkt-Eingabe: erzeugt für das aktive Geschoss // die Massketten (Öffnungen, Vor-/Rücksprünge, Gesamtmass) je Gebäudeseite -// (`geometry/autoDimensions.ts`). Ein erneuter Aufruf ersetzt die zuvor automatisch erzeugten +// (Kern: `auto_dimensions.rs`, Elemente `cmd_draw.rs`). Ein erneuter Aufruf ersetzt die zuvor automatisch erzeugten // Ketten DIESES Geschosses (feste IDs), von Hand gezeichnete Bemassungen bleiben. -import { addItems, autoExteriorDimensions, opsMutation, removeItems } from "../../core"; +import { createMutation, createPreview } from "../createCore"; import type { Command, CommandContext, CommandResult, CommandState } from "../types"; -const PREFIX = "autodim"; const done = (): [CommandState, CommandResult] => [ { phase: "idle", lastPoint: null }, @@ -23,19 +22,9 @@ export const autodimCommand: Command = { autoRun: (ctx: CommandContext): CommandResult => { if (ctx.level.kind !== "floor") return { draft: null, done: true }; - const floorId = ctx.level.id; - const dims = autoExteriorDimensions(ctx.project, floorId, ctx.defaultCategoryCode, 100, PREFIX); - if (dims.length === 0) return { draft: null, done: true }; - const own = `${PREFIX}-${floorId}-`; - return { - draft: null, - done: true, - // Frühere Ketten dieses Geschosses raus, neue hinten dran. - commit: opsMutation((p) => [ - ...removeItems(p, "drawings2d", (d) => d.id.startsWith(own)), - ...addItems("drawings2d", dims.map((d) => d.drawing)), - ]), - }; + // Ketten im Kern (`cmd_draw.rs`, `auto_dimensions.rs`); ohne Ketten (keine Wände) kein Commit. + if (!createPreview(ctx, { cmd: "autodim" }, []).ok) return { draft: null, done: true }; + return { draft: null, done: true, commit: createMutation(ctx, { cmd: "autodim" }) }; }, onInput: (): [CommandState, CommandResult] => done(), diff --git a/src/commands/cmds/bezier.ts b/src/commands/cmds/bezier.ts index cceb3a8a..fc35be20 100644 --- a/src/commands/cmds/bezier.ts +++ b/src/commands/cmds/bezier.ts @@ -7,9 +7,6 @@ // Nach ≥1 fertigem Segment kann „Fertig" (Enter) den Zug abschliessen; jeder // weitere Anker startet automatisch ein neues Segment (Schritte 2–4). -import type { Drawing2D } from "../../model/types"; -import { uniqueId } from "../../tools/types"; -import { sampleBezierChain } from "../../core"; import type { Command, CommandContext, @@ -20,8 +17,7 @@ import type { ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview } from "../createCore"; interface BezierStart extends CommandState { phase: "start"; @@ -52,24 +48,15 @@ type BezierState = BezierStart | BezierC1 | BezierC2 | BezierEnd; const FINISH: CmdOption = { id: "finish", labelKey: "cmd.bezier.finish" }; /** Vorschau: abgeschlossene Kurve (tessellierte Segmente) + Gummiband-Linien des laufenden Segments. */ -function bezierDraft(pts: Vec2[], rubber: Vec2[]): ToolDraft { - const preview: DraftShape[] = []; - if (pts.length >= 4) preview.push({ kind: "poly", pts: sampleBezierChain(pts), closed: false }); +function bezierDraft(ctx: CommandContext, pts: Vec2[], rubber: Vec2[]): ToolDraft { + // Bezier-Kette ab 4 Punkten im Kern (`cmd_draw.rs`, 24 Schritte je Kurve), Gummiband dazu. + const preview: DraftShape[] = pts.length >= 4 ? createPreview(ctx, { cmd: "bezier" }, pts).shapes : []; for (let i = 0; i < rubber.length - 1; i++) preview.push({ kind: "line", a: rubber[i], b: rubber[i + 1] }); return { preview, vertices: pts.length > 0 ? [pts[0]] : [] }; } -function appendBezier(pts: Vec2[], ctx: CommandContext): CoreOp[] { - if (pts.length < 4) return []; - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "bezier", pts }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern): Bezier-Kette (mindestens 4 Punkte). */ +const appendBezier = (pts: Vec2[], ctx: CommandContext) => createMutation(ctx, { cmd: "bezier", pts }); const idle = (): [CommandState, CommandResult] => [ { phase: "start", lastPoint: null } as BezierStart, @@ -77,7 +64,7 @@ const idle = (): [CommandState, CommandResult] => [ ]; const finish = (pts: Vec2[], ctx: CommandContext): [CommandState, CommandResult] => [ { phase: "start", lastPoint: null } as BezierStart, - { draft: null, done: true, commit: opsMutation(() => appendBezier(pts, ctx)) }, + { draft: null, done: true, commit: appendBezier(pts, ctx) }, ]; export const bezierCommand: Command = { @@ -109,11 +96,11 @@ export const bezierCommand: Command = { if (s.phase === "start") { const ns: BezierC1 = { phase: "c1", pts: [pt], anchor: pt, cursor: pt, lastPoint: pt }; - return [ns, { draft: bezierDraft(ns.pts, [pt]) }]; + return [ns, { draft: bezierDraft(ctx, ns.pts, [pt]) }]; } if (s.phase === "c1") { const ns: BezierC2 = { phase: "c2", pts: s.pts, anchor: s.anchor, c1: pt, cursor: pt, lastPoint: pt }; - return [ns, { draft: bezierDraft(ns.pts, [s.anchor, pt]) }]; + return [ns, { draft: bezierDraft(ctx, ns.pts, [s.anchor, pt]) }]; } if (s.phase === "c2") { const ns: BezierEnd = { @@ -125,28 +112,28 @@ export const bezierCommand: Command = { cursor: pt, lastPoint: pt, }; - return [ns, { draft: bezierDraft(ns.pts, [s.anchor, s.c1, pt]) }]; + return [ns, { draft: bezierDraft(ctx, ns.pts, [s.anchor, s.c1, pt]) }]; } // phase "end": Segment abschliessen, direkt das nächste Segment beginnen. const pts = [...s.pts, s.c1, s.c2, pt]; const ns: BezierC1 = { phase: "c1", pts, anchor: pt, cursor: pt, lastPoint: pt }; - return [ns, { draft: bezierDraft(pts, [pt]) }]; + return [ns, { draft: bezierDraft(ctx, pts, [pt]) }]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as BezierState; if (s.phase === "start") return [s, { draft: null }]; if (s.phase === "c1") { const ns: BezierC1 = { ...s, cursor: point }; - return [ns, { draft: bezierDraft(s.pts, [s.anchor, point]) }]; + return [ns, { draft: bezierDraft(ctx, s.pts, [s.anchor, point]) }]; } if (s.phase === "c2") { const ns: BezierC2 = { ...s, cursor: point }; - return [ns, { draft: bezierDraft(s.pts, [s.anchor, s.c1, point]) }]; + return [ns, { draft: bezierDraft(ctx, s.pts, [s.anchor, s.c1, point]) }]; } const ns: BezierEnd = { ...s, cursor: point }; // Endschritt: die tatsächliche Bezier-Kurve bis zum Cursor live anzeigen. - return [ns, { draft: bezierDraft([...s.pts, s.c1, s.c2, point], []) }]; + return [ns, { draft: bezierDraft(ctx, [...s.pts, s.c1, s.c2, point], []) }]; }, onConfirm: (state, ctx): [CommandState, CommandResult] => { diff --git a/src/commands/cmds/block.ts b/src/commands/cmds/block.ts index 6619e424..27dbe7f7 100644 --- a/src/commands/cmds/block.ts +++ b/src/commands/cmds/block.ts @@ -14,8 +14,7 @@ // wie bei `circle.ts`s Radius-Punkt). Kein separater dritter Klick-Schritt // nötig — Nutzer-Wunsch „Skalierung beim Einfügen" bei minimaler UX-Änderung. -import type { Drawing2D } from "../../model/types"; -import { segmentHud, uniqueId } from "../../tools/types"; +import { segmentHud } from "../../tools/types"; import type { CmdOption, Command, @@ -24,8 +23,7 @@ import type { CommandState, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation } from "../createCore"; const EPS = 1e-6; @@ -52,28 +50,12 @@ function readDefs(ctx: CommandContext): { ids: string[]; names: string[] } { return { ids: defs.map((d) => d.id), names: defs.map((d) => d.name) }; } -function appendInstance(blockDefId: string, - at: Vec2, - rotation: number, - scale: number, - ctx: CommandContext, -): CoreOp[] { - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "block", blockDefId, at, rotation, scale }, - }; - return addItems("drawings2d", [d]); -} - -/** Drehwinkel + Skalierungsfaktor aus DEMSELBEN Punkt: Klick auf `at` = (0, 1). */ -function rotationAndScaleFrom(at: Vec2, pt: Vec2): { rotation: number; scale: number } { - const d = Math.hypot(pt.x - at.x, pt.y - at.y); - if (d < EPS) return { rotation: 0, scale: 1 }; - return { rotation: Math.atan2(pt.y - at.y, pt.x - at.x), scale: d }; -} +/** + * Commit (Kern, `cmd_draw.rs`): Block-Instanz am Einfügepunkt; der zweite Punkt gibt Drehung (Richtung) + * und Massstab (Abstand) — derselbe Punkt: unskaliert, ungedreht. + */ +const appendInstance = (blockDefId: string, at: Vec2, pt: Vec2, ctx: CommandContext) => + createMutation(ctx, { cmd: "block", def: blockDefId, at, pt }); const idle = (): [CommandState, CommandResult] => [ { phase: "point", lastPoint: null, defIds: [], defNames: [] } as BlockPoint, @@ -113,11 +95,7 @@ export const blockCommand: Command = { const blockDefId = s.defIds[lastDefIndex % s.defIds.length]; const { at } = s; const pt = input.point; - const { rotation, scale } = rotationAndScaleFrom(at, pt); - return [ - idle()[0], - { draft: null, done: true, commit: opsMutation(() => appendInstance(blockDefId, at, rotation, scale, ctx)) }, - ]; + return [idle()[0], { draft: null, done: true, commit: appendInstance(blockDefId, at, pt, ctx) }]; }, onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { diff --git a/src/commands/cmds/ceiling.ts b/src/commands/cmds/ceiling.ts index d9ea59c4..3d387e21 100644 --- a/src/commands/cmds/ceiling.ts +++ b/src/commands/cmds/ceiling.ts @@ -15,9 +15,6 @@ // • floorId ← ctx.level.id (aktives Geschoss) // • categoryCode← "30" (Ebene „Decken"; Fallback ctx.defaultCategoryCode) -import type { Ceiling } from "../../model/types"; -import { normalizeOutline, ceilingArea } from "../../core"; -import { uniqueId } from "../../tools/types"; import type { Command, CommandContext, @@ -29,14 +26,11 @@ import type { ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, xy } from "../createCore"; const EPS = 1e-6; const DEG = Math.PI / 180; const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schließt den Umriss -/** Default-Ebene (Kategorie) für Decken. */ -const CEILING_CATEGORY = "30"; const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); const segAngleDeg = (a: Vec2, b: Vec2): number => @@ -61,29 +55,6 @@ function nextFromFields( return { x: last.x + Math.cos(ang) * length, y: last.y + Math.sin(ang) * length }; } -/** Aktiver Aufbau-Typ-ID; Fallback auf den ersten Projekt-Wandtyp. */ -function activeTypeId(ctx: CommandContext): string { - const wt = - ctx.project.wallTypes.find((t) => t.id === ctx.activeWallTypeId) ?? - ctx.project.wallTypes[0]; - return wt ? wt.id : ctx.activeWallTypeId; -} - -/** Existiert die Decken-Kategorie („30")? Sonst Fallback auf die aktive Kategorie. */ -function ceilingCategory(ctx: CommandContext): string { - const flat: { code: string }[] = []; - const walk = (list: { code: string; children?: unknown[] }[]) => { - for (const c of list) { - flat.push({ code: c.code }); - if (c.children) walk(c.children as { code: string; children?: unknown[] }[]); - } - }; - walk(ctx.project.layers as { code: string; children?: unknown[] }[]); - return flat.some((c) => c.code === CEILING_CATEGORY) - ? CEILING_CATEGORY - : ctx.defaultCategoryCode; -} - interface CeilIdle extends CommandState { phase: "start"; } @@ -115,20 +86,11 @@ function ceilingDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { return draft; } -/** Hängt eine Decke ans Projekt (immutabel). Entartete Umrisse werden verworfen. */ -function appendCeiling(pts: Vec2[], ctx: CommandContext): CoreOp[] { - const outline = normalizeOutline(pts); - if (!outline || ceilingArea(outline) < 1e-4) return []; - const ceiling: Ceiling = { - id: uniqueId("C"), - type: "ceiling", - floorId: ctx.level.id, - categoryCode: ceilingCategory(ctx), - outline, - wallTypeId: activeTypeId(ctx), - }; - return addItems("ceilings", [ceiling]); -} +/** + * Commit: Decke aus dem Umriss (normalisiert, CCW; entartet → nichts), Typ = aktiver Aufbau, Ebene + * „30“ falls vorhanden — im Kern (`cmd_create.rs`). + */ +const appendCeiling = (pts: Vec2[], ctx: CommandContext) => createMutation(ctx, { cmd: "ceiling", pts: pts.map(xy) }); const idle = (): [CommandState, CommandResult] => [ { phase: "start", lastPoint: null } as CeilIdle, @@ -175,7 +137,7 @@ export const ceilingCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null } as CeilIdle, - { draft: null, done: true, commit: opsMutation(() => appendCeiling(pts, ctx)) }, + { draft: null, done: true, commit: appendCeiling(pts, ctx) }, ]; } return [s, { draft: ceilingDraft(s.points, s.cursor) }]; @@ -197,7 +159,7 @@ export const ceilingCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null } as CeilIdle, - { draft: null, done: true, commit: opsMutation(() => appendCeiling(pts, ctx)) }, + { draft: null, done: true, commit: appendCeiling(pts, ctx) }, ]; } // Null-Strecke (Klick auf denselben Punkt) ignorieren. @@ -224,7 +186,7 @@ export const ceilingCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null } as CeilIdle, - { draft: null, done: true, commit: opsMutation(() => appendCeiling(pts, ctx)) }, + { draft: null, done: true, commit: appendCeiling(pts, ctx) }, ]; } return idle(); diff --git a/src/commands/cmds/ceilingOpening.ts b/src/commands/cmds/ceilingOpening.ts index 4f62a51d..9803279b 100644 --- a/src/commands/cmds/ceilingOpening.ts +++ b/src/commands/cmds/ceilingOpening.ts @@ -8,33 +8,18 @@ // 1) „Erste Ecke der Aussparung:" → Punkt // 2) „Gegenecke:" → Live-Rechteck-Vorschau; Klick committet. -import { opsMutation, patchItem, pointInOutline } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview } from "../createCore"; import type { Command, CommandContext, CommandResult, CommandState, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; /** Vier Eckpunkte eines Rechtecks aus zwei Gegenecken (CCW). */ -function rectCorners(a: Vec2, b: Vec2): Vec2[] { - const x0 = Math.min(a.x, b.x); - const x1 = Math.max(a.x, b.x); - const y0 = Math.min(a.y, b.y); - const y1 = Math.max(a.y, b.y); - return [ - { x: x0, y: y0 }, - { x: x1, y: y0 }, - { x: x1, y: y1 }, - { x: x0, y: y1 }, - ]; -} - interface HoleIdle extends CommandState { phase: "start"; } @@ -46,9 +31,9 @@ interface HoleRect extends CommandState { type HoleState = HoleIdle | HoleRect; /** Vorschau: aufgezogenes Rechteck + Masse im HUD. */ -function holeDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { - const pts = cursor ? rectCorners(a, cursor) : [a]; - const preview: DraftShape[] = [{ kind: "poly", pts, closed: !!cursor }]; +function holeDraft(ctx: CommandContext, a: Vec2, cursor: Vec2 | null): ToolDraft { + // Aufgezogenes Rechteck im Kern (`cmd_create.rs`). + const preview: DraftShape[] = cursor ? createPreview(ctx, { cmd: "rect4" }, [a, cursor]).shapes : [{ kind: "poly", pts: [a], closed: false }]; const draft: ToolDraft = { preview, vertices: [a] }; if (cursor) { draft.hud = { @@ -64,20 +49,11 @@ function holeDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { * Rechteck vollständig enthält (alle 4 Ecken im Umriss). Entartete Rechtecke * und Rechtecke ausserhalb jeder Decke werden verworfen (Projekt unverändert). */ -function ceilingOpeningOps(p: Project, a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] { - const w = Math.abs(b.x - a.x); - const d = Math.abs(b.y - a.y); - if (w < 0.05 || d < 0.05) return []; - const corners = rectCorners(a, b); - const host = (p.ceilings ?? []).find( - (c) => - c.floorId === ctx.level.id && - c.outline.length >= 3 && - corners.every((pt) => pointInOutline(pt, c.outline)), - ); - if (!host) return []; - return patchItem(p, "ceilings", host.id, (c) => ({ ...c, openings: [...(c.openings ?? []), corners] })); -} +/** + * Commit (Kern, `cmd_solid.rs`): rechteckige Aussparung (≥ 5 cm je Seite) in die Decke des Geschosses, + * die alle vier Ecken enthält; keine solche Decke → nichts. + */ +const ceilingOpening = (a: Vec2, b: Vec2, ctx: CommandContext) => createMutation(ctx, { cmd: "ceilingOpening", a, b }); const idle = (): [CommandState, CommandResult] => [ { phase: "start", lastPoint: null } as HoleIdle, @@ -97,7 +73,7 @@ export const ceilingOpeningCommand: Command = { onInput: (state, input, ctx): [CommandState, CommandResult] => { const s = state as HoleState; if (input.kind !== "point") { - return [s, { draft: s.phase === "corner" ? holeDraft(s.a, s.cursor) : null }]; + return [s, { draft: s.phase === "corner" ? holeDraft(ctx, s.a, s.cursor) : null }]; } if (s.phase !== "corner") { const ns: HoleRect = { @@ -106,22 +82,22 @@ export const ceilingOpeningCommand: Command = { cursor: input.point, lastPoint: input.point, }; - return [ns, { draft: holeDraft(input.point, input.point) }]; + return [ns, { draft: holeDraft(ctx, input.point, input.point) }]; } // Zweite Ecke → committen. const a = s.a; const b = input.point; return [ { phase: "start", lastPoint: null } as HoleIdle, - { draft: null, done: true, commit: opsMutation((p) => ceilingOpeningOps(p, a, b, ctx)) }, + { draft: null, done: true, commit: ceilingOpening(a, b, ctx) }, ]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as HoleState; if (s.phase !== "corner") return [s, { draft: null }]; const ns: HoleRect = { ...s, cursor: point }; - return [ns, { draft: holeDraft(s.a, point) }]; + return [ns, { draft: holeDraft(ctx, s.a, point) }]; }, onConfirm: (): [CommandState, CommandResult] => idle(), diff --git a/src/commands/cmds/circle.ts b/src/commands/cmds/circle.ts index 7e49a7bb..5122055e 100644 --- a/src/commands/cmds/circle.ts +++ b/src/commands/cmds/circle.ts @@ -23,7 +23,7 @@ // dasselbe Element wie Schritt 1 wird ignoriert) // 3) „Radius:" → Punkt (Abstand zum ERSTEN Klickpunkt aus Schritt 1) // ODER getippte Zahl → commit. Die eigentliche Geometrie steckt in -// `geometry/kernel2d.ts::tangentCircleCenters` (Apollonius- +// `kernel2d::tangent_circle_centers` (Kern, `cmd_draw.rs`) (Apollonius- // Spezialfall mit bekanntem Radius): pro Tangentialobjekt wird der // geometrische Ort aller passenden Mittelpunkte gebildet (Gerade: // zwei Parallelen im Abstand r; Kreis: äussere/innere Berührung), @@ -35,10 +35,6 @@ // Maus-Punkt (Abstand) als auch eine getippte nackte Zahl. Der Kreis wird in // generatePlan als geschlossene Polygon-Approximation gerendert. -import type { Drawing2D, Drawing2DGeom } from "../../model/types"; -import { uniqueId } from "../../tools/types"; -import { arcThroughPoints } from "../../core"; -import { pointSegmentDistance, polylineEdges, tangentCircleCenters, type TangentTarget } from "../../core"; import type { CmdOption, Command, @@ -46,14 +42,14 @@ import type { CommandField, CommandResult, CommandState, - DraftShape, - Project, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview, createQuery, xy, type CreatePreview } from "../createCore"; + +/** Tangenten-Objekt (Gerade oder Kreis), wie der Kern es beim Picken liefert. */ +type TangentTarget = Record; const EPS = 1e-6; @@ -141,11 +137,8 @@ type CircleState = | CircleTtrRadius; const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); -const mid = (a: Vec2, b: Vec2): Vec2 => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }); -// ── TTR: Hit-Testing auf bestehende Linien/Kreise ─────────────────────────── - -const TTR_HIT_TOL = 0.3; // Modell-Meter: Pick-Toleranz für die Tangentenobjekt-Wahl +// ── TTR: Hit-Testing auf bestehende Linien/Kreise (Kern) ───────────────────── interface TangentPick { target: TangentTarget; @@ -153,75 +146,14 @@ interface TangentPick { drawingId: string; } -/** Winkel `ang` (rad) liegt innerhalb des Bogenspanns [a0, a1) (CCW, mit Wraparound). */ -function inArcSpan(a0: number, a1: number, ang: number): boolean { - const TAU = Math.PI * 2; - const norm = (x: number) => ((x % TAU) + TAU) % TAU; - const sweep = norm(a1 - a0) || TAU; - return norm(ang - a0) <= sweep + 1e-6; -} - -/** Gerade Kanten einer Form (line/polyline ohne Bogen-Segmente/rect) für den TTR-Hit-Test. */ -function straightEdgesOf(g: Drawing2DGeom): [Vec2, Vec2][] { - if (g.shape === "line") return [[g.a, g.b]]; - if (g.shape === "rect") { - const pts = [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }]; - return polylineEdges(pts, true); - } - if (g.shape === "polyline") { - const edges = polylineEdges(g.pts, g.closed); - // Bogen-Segmente (bulge) sind hier keine Geraden — von der Tangenten-Wahl - // ausgenommen (dieselbe Vereinfachung wie bei fillet.ts::geomToCurve). - return edges.filter((_, i) => Math.abs(g.bulge?.[i] ?? 0) <= EPS); - } - return []; -} - -/** Nächstes tangentenfähiges Element (Gerade ODER Kreis/Bogen) zum Klickpunkt, oder null. */ -function pickTangentTarget(project: Project, levelId: string, pt: Vec2): TangentPick | null { - let best: TangentPick | null = null; - let bestD = TTR_HIT_TOL; - for (const d of project.drawings2d) { - if (d.levelId !== levelId) continue; - const g = d.geom; - if (g.shape === "circle") { - const dd = Math.abs(dist(pt, g.center) - g.r); - if (dd < bestD) { - bestD = dd; - best = { target: { kind: "circle", center: g.center, r: g.r }, near: pt, drawingId: d.id }; - } - } else if (g.shape === "arc") { - const dd = Math.abs(dist(pt, g.center) - g.r); - const ang = Math.atan2(pt.y - g.center.y, pt.x - g.center.x); - if (dd < bestD && inArcSpan(g.a0, g.a1, ang)) { - bestD = dd; - best = { target: { kind: "circle", center: g.center, r: g.r }, near: pt, drawingId: d.id }; - } - } else { - for (const [a, b] of straightEdgesOf(g)) { - const dd = pointSegmentDistance(pt, a, b); - if (dd < bestD) { - bestD = dd; - best = { target: { kind: "line", a, b }, near: pt, drawingId: d.id }; - } - } - } - } - return best; -} - -/** Von mehreren Mittelpunkt-Kandidaten den zu (near1, near2) nächstgelegenen wählen. */ -function nearestCandidate(cands: Vec2[], near1: Vec2, near2: Vec2): Vec2 | null { - let best: Vec2 | null = null; - let bestD = Infinity; - for (const c of cands) { - const dd = dist(c, near1) + dist(c, near2); - if (dd < bestD) { - bestD = dd; - best = c; - } - } - return best; +/** Nächstes tangentenfähiges Element (Gerade ODER Kreis/Bogen) zum Klickpunkt (Toleranz 0.3 m), oder null. */ +function pickTangentTarget(ctx: CommandContext, pt: Vec2): TangentPick | null { + const r = createQuery<{ hit: { target: TangentTarget; id: string } | null }>(ctx.project, { + q: "pickTangent", + level: ctx.level.id, + pt: xy(pt), + }); + return r.hit ? { target: r.hit.target, near: pt, drawingId: r.hit.id } : null; } /** Tab-Feld des Radius-Schritts (nur Methode „center"): der Radius selbst. */ @@ -242,22 +174,19 @@ function circlePointFromFields(center: Vec2, locks: Record, curs return { x: center.x + r, y: center.y }; } -/** Punkte einer Kreis-Approximation (für die Vorschau). */ -function circlePts(center: Vec2, r: number): Vec2[] { - const N = 48; - const pts: Vec2[] = []; - for (let i = 0; i < N; i++) { - const t = (i / N) * Math.PI * 2; - pts.push({ x: center.x + r * Math.cos(t), y: center.y + r * Math.sin(t) }); - } - return pts; -} +/** + * Kreis im Kern (`cmd_draw.rs`): Mittelpunkt + Radius je Methode (2-Punkt: Durchmesser, 3-Punkt: + * Umkreis, TTR: tangential an zwei Objekte, nächster Kandidat zu den Klickpunkten); `ok` = bestimmt. + */ +const circleAt = (ctx: CommandContext, req: Record, pts: Vec2[]): CreatePreview => + createPreview(ctx, { cmd: "circle", ...req }, pts); -/** Vorschau (Kreis) + HUD (Radius). */ -function circleDraft(center: Vec2, r: number, at: Vec2 | null): ToolDraft { +/** Vorschau (Kreis, 48-Eck) + HUD (Radius). */ +function circleDraft(pv: CreatePreview, at: Vec2 | null): ToolDraft { + const [cx, cy, r] = pv.info; + const center = { x: cx, y: cy }; if (r < EPS) return { preview: [], vertices: [center] }; - const preview: DraftShape[] = [{ kind: "poly", pts: circlePts(center, r), closed: true }]; - const draft: ToolDraft = { preview, vertices: [center] }; + const draft: ToolDraft = { preview: pv.shapes, vertices: [center] }; if (at) draft.hud = { at, text: `R: ${r.toFixed(3)}m` }; return draft; } @@ -267,17 +196,8 @@ function lineDraft(a: Vec2, b: Vec2): ToolDraft { return { preview: [{ kind: "line", a, b }], vertices: [a] }; } -function appendCircle(center: Vec2, r: number, ctx: CommandContext): CoreOp[] { - if (r < EPS) return []; - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "circle", center, r }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern): Kreis aus der Anfrage (entartet r < EPS → nichts). */ +const appendCircle = (ctx: CommandContext, req: Record) => createMutation(ctx, { cmd: "circle", ...req }); const idle = (method: CircleMethod): [CommandState, CommandResult] => [ (method === "center" @@ -331,27 +251,25 @@ export const circleCommand: Command = { if (s.phase !== "radius") { if (input.kind !== "point") return [s, { draft: null }]; const ns: CircleCenterP2 = { phase: "radius", method: "center", center: input.point, cursor: input.point, lastPoint: input.point }; - return [ns, { draft: circleDraft(input.point, 0, null) }]; + return [ns, { draft: { preview: [], vertices: [input.point] } }]; } - let r: number; - if (input.kind === "number") r = input.value; - else r = dist(s.center, input.point); - const center = s.center; - return [idle("center")[0], { draft: null, done: true, commit: opsMutation(() => appendCircle(center, r, ctx)) }]; + const req = + input.kind === "number" + ? { method: "center", pts: [s.center], r: input.value } + : { method: "center", pts: [s.center, input.point] }; + return [idle("center")[0], { draft: null, done: true, commit: appendCircle(ctx, req) }]; } if (s.method === "ttr") { if (s.phase === "radius") { - let r: number; - if (input.kind === "number") r = input.value; - else r = dist(s.near1, input.point); - const center = r > EPS ? nearestCandidate(tangentCircleCenters(s.t1, s.t2, r), s.near1, s.near2) : null; + const req = { method: "ttr", t1: s.t1, t2: s.t2, near1: s.near1, near2: s.near2 }; + const full = input.kind === "number" ? { ...req, r: input.value } : { ...req, pts: [input.point] }; // Kein Kandidat (z. B. Radius geometrisch unpassend) — ignorieren, weiter warten. - if (!center) return [s, { draft: null }]; - return [idle("ttr")[0], { draft: null, done: true, commit: opsMutation(() => appendCircle(center, r, ctx)) }]; + if (!circleAt(ctx, full, input.kind === "number" ? [] : [input.point]).ok) return [s, { draft: null }]; + return [idle("ttr")[0], { draft: null, done: true, commit: appendCircle(ctx, full) }]; } if (input.kind !== "point") return [s, { draft: null }]; - const pick = pickTangentTarget(ctx.project, ctx.level.id, input.point); + const pick = pickTangentTarget(ctx, input.point); if (!pick) return [s, { draft: null }]; // kein Treffer auf Linie/Kreis — ignorieren, weiter warten if (s.phase === "t1") { const ns: CircleTtrT2 = { @@ -387,9 +305,7 @@ export const circleCommand: Command = { const ns: CircleTwoP2 = { phase: "p2", method: "twoPoint", a: pt, cursor: pt, lastPoint: pt }; return [ns, { draft: { preview: [], vertices: [pt] } }]; } - const center = mid(s.a, pt); - const r = dist(s.a, pt) / 2; - return [idle("twoPoint")[0], { draft: null, done: true, commit: opsMutation(() => appendCircle(center, r, ctx)) }]; + return [idle("twoPoint")[0], { draft: null, done: true, commit: appendCircle(ctx, { method: "twoPoint", pts: [s.a, pt] }) }]; } // threePoint @@ -403,26 +319,22 @@ export const circleCommand: Command = { return [ns, { draft: lineDraft(s.a, pt) }]; } // phase p3: dritter Punkt → Umkreis, committen. - const circ = arcThroughPoints(s.a, s.b, pt); // a0/a1 hier irrelevant, nur center+r zählen - if (!circ) return [s, { draft: lineDraft(s.a, pt) }]; // kollinear — ignorieren, weiter warten - return [ - idle("threePoint")[0], - { draft: null, done: true, commit: opsMutation(() => appendCircle(circ.center, circ.r, ctx)) }, - ]; + const req = { method: "threePoint", pts: [s.a, s.b, pt] }; + if (!circleAt(ctx, req, [s.a, s.b, pt]).ok) return [s, { draft: lineDraft(s.a, pt) }]; // kollinear — ignorieren, weiter warten + return [idle("threePoint")[0], { draft: null, done: true, commit: appendCircle(ctx, req) }]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as CircleState; if (s.method === "center") { if (s.phase !== "radius") return [s, { draft: null }]; - const r = dist(s.center, point); const ns: CircleCenterP2 = { ...s, cursor: point }; - return [ns, { draft: circleDraft(s.center, r, point) }]; + return [ns, { draft: circleDraft(circleAt(ctx, { method: "center" }, [s.center, point]), point) }]; } if (s.method === "twoPoint") { if (s.phase !== "p2") return [s, { draft: null }]; const ns: CircleTwoP2 = { ...s, cursor: point }; - return [ns, { draft: circleDraft(mid(s.a, point), dist(s.a, point) / 2, point) }]; + return [ns, { draft: circleDraft(circleAt(ctx, { method: "twoPoint" }, [s.a, point]), point) }]; } // threePoint if (s.phase === "p2") { @@ -431,15 +343,14 @@ export const circleCommand: Command = { } if (s.phase === "p3") { const ns: CircleThreeP3 = { ...s, cursor: point }; - const circ = arcThroughPoints(s.a, s.b, point); - return [ns, { draft: circ ? circleDraft(circ.center, circ.r, point) : lineDraft(s.a, point) }]; + const pv = circleAt(ctx, { method: "threePoint" }, [s.a, s.b, point]); + return [ns, { draft: pv.ok ? circleDraft(pv, point) : lineDraft(s.a, point) }]; } if (s.method === "ttr" && s.phase === "radius") { - const r = dist(s.near1, point); const ns: CircleTtrRadius = { ...s, cursor: point }; - if (r < EPS) return [ns, { draft: null }]; - const center = nearestCandidate(tangentCircleCenters(s.t1, s.t2, r), s.near1, s.near2); - return [ns, { draft: center ? circleDraft(center, r, point) : lineDraft(s.near1, s.near2) }]; + const pv = circleAt(ctx, { method: "ttr", t1: s.t1, t2: s.t2, near1: s.near1, near2: s.near2 }, [point]); + if (pv.info[2] < EPS) return [ns, { draft: null }]; + return [ns, { draft: pv.ok ? circleDraft(pv, point) : lineDraft(s.near1, s.near2) }]; } return [s, { draft: null }]; }, diff --git a/src/commands/cmds/column.ts b/src/commands/cmds/column.ts index a84fa172..46a887f4 100644 --- a/src/commands/cmds/column.ts +++ b/src/commands/cmds/column.ts @@ -13,9 +13,6 @@ // // Bezeichner englisch, sichtbarer Text via t() (CONVENTIONS.md). -import type { Column, ColumnProfile } from "../../model/types"; -import { uniqueId } from "../../tools/types"; -import { columnFootprint } from "../../core"; import type { Command, CommandContext, @@ -24,15 +21,10 @@ import type { CmdOption, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview, xy } from "../createCore"; -/** Default-Ebene (Kategorie) für Stützen: „50" Tragwerk (Fallback: aktive). */ -const COLUMN_CATEGORY = "50"; /** Default-Kantenlänge eines Rechteckprofils (Meter). */ const DEF_SIZE = 0.3; -/** Fallback-Höhe, falls das Geschoss keine floorHeight trägt (Meter). */ -const DEF_HEIGHT = 2.6; // ── Persistente Defaults (modulweit, leben über Befehls-Instanzen hinweg) ──── const columnDefaults: { kind: "rect" | "round"; size: number } = { @@ -40,34 +32,15 @@ const columnDefaults: { kind: "rect" | "round"; size: number } = { size: DEF_SIZE, }; -/** Baut das aktuelle Default-Profil aus `columnDefaults`. */ -function currentProfile(): ColumnProfile { - if (columnDefaults.kind === "round") { - return { kind: "round", radius: columnDefaults.size / 2 }; - } - return { kind: "rect", width: columnDefaults.size, depth: columnDefaults.size }; -} +/** Profil-Optionen der Anfrage (Kern baut daraus das Profil: rund Ø `size`, sonst quadratisch). */ +const profileReq = () => ({ kind: columnDefaults.kind, size: columnDefaults.size }); -/** Fügt die Stütze immutabel an `project.columns` an. */ -function appendColumn(position: Vec2, - ctx: CommandContext, -): CoreOp[] { - const height = - ctx.level.floorHeight != null && ctx.level.floorHeight > 0 - ? ctx.level.floorHeight - : DEF_HEIGHT; - const column: Column = { - id: uniqueId("column"), - type: "column", - floorId: ctx.level.id, - categoryCode: COLUMN_CATEGORY, - position, - profile: currentProfile(), - rotation: 0, - height, - }; - return addItems("columns", [column]); -} +/** + * Commit (Kern, `cmd_create.rs`): Stütze am Punkt, Ebene „50“, Höhe = Geschosshöhe (sonst 2.6 m), + * Profil aus den Vorgaben. + */ +const appendColumn = (position: Vec2, ctx: CommandContext) => + createMutation(ctx, { cmd: "column", at: xy(position), ...profileReq() }); interface ColState extends CommandState { phase: "place" | "done"; @@ -78,25 +51,15 @@ const finish = (): [CommandState, CommandResult] => [ { draft: null, done: true }, ]; -/** Footprint-Vorschau des aktuellen Default-Profils am Cursor. */ -function previewAt(pt: Vec2): CommandResult { - const ghost: Column = { - id: "_preview", - type: "column", - floorId: "", - categoryCode: COLUMN_CATEGORY, - position: pt, - profile: currentProfile(), - rotation: 0, - height: 0, - }; +/** Footprint-Vorschau des aktuellen Default-Profils am Cursor (Kern). */ +function previewAt(pt: Vec2, ctx: CommandContext): CommandResult { const size = columnDefaults.kind === "round" ? `Ø${(columnDefaults.size * 100).toFixed(0)}` : `${(columnDefaults.size * 100).toFixed(0)}×${(columnDefaults.size * 100).toFixed(0)}`; return { draft: { - preview: [{ kind: "poly", pts: columnFootprint(ghost), closed: true }], + preview: createPreview(ctx, { cmd: "column", ...profileReq() }, [pt]).shapes, vertices: [], hud: { at: pt, text: size }, }, @@ -134,16 +97,16 @@ export const columnCommand: Command = { if (input.kind === "point") { return [ { phase: "done", lastPoint: null } as ColState, - { draft: null, done: true, commit: opsMutation(() => appendColumn(input.point, ctx)) }, + { draft: null, done: true, commit: appendColumn(input.point, ctx) }, ]; } return [s, { draft: null }]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as ColState; if (s.phase !== "place") return [s, { draft: null }]; - return [s, previewAt(point)]; + return [s, previewAt(point, ctx)]; }, onConfirm: (): [CommandState, CommandResult] => finish(), diff --git a/src/commands/cmds/defblock.ts b/src/commands/cmds/defblock.ts index 77dd22a6..4610a596 100644 --- a/src/commands/cmds/defblock.ts +++ b/src/commands/cmds/defblock.ts @@ -10,9 +10,7 @@ // verschachtelten Blöcke, v1 — s. `BlockDef`-Kopfkommentar in model/types.ts). // Leere/rein-block-Auswahl → No-Op (kein Commit). -import { opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; -import { documentFor } from "../../core/document"; +import { cmdMutation } from "../../core/document"; import { uniqueStamp } from "../../tools/types"; import type { Command, @@ -20,7 +18,6 @@ import type { CommandResult, CommandSelection, CommandState, - Project, Vec2, } from "../types"; @@ -30,8 +27,8 @@ function selectedDrawingIds(sel: CommandSelection): string[] { } /** Definition anhängen, Quellen raus, Instanz hinten dran — rechnet der Kern (`cmd_transform::defblock_ops`). */ -function defineOps(p: Project, ids: string[], at: Vec2, ctx: CommandContext): CoreOp[] { - return documentFor(p).cmdOps({ +function defineMutation(ids: string[], at: Vec2, ctx: CommandContext) { + return cmdMutation({ cmd: "defblock", ids, at: [at.x, at.y], @@ -63,7 +60,7 @@ export const defblockCommand: Command = { const ids = selectedDrawingIds(ctx.selection); if (ids.length === 0) return idle(); const at = input.point; - return [idle()[0], { draft: null, done: true, commit: opsMutation((p) => defineOps(p, ids, at, ctx)) }]; + return [idle()[0], { draft: null, done: true, commit: defineMutation(ids, at, ctx) }]; }, onMove: (state): [CommandState, CommandResult] => [state, { draft: null }], diff --git a/src/commands/cmds/detailref.ts b/src/commands/cmds/detailref.ts index d3284dbe..42d78448 100644 --- a/src/commands/cmds/detailref.ts +++ b/src/commands/cmds/detailref.ts @@ -6,22 +6,16 @@ // Position, Feinheiten hinterher) — kein Tipp-Schritt beim Platzieren // nötig, das Symbol landet sofort selektiert-editierbar im Plan. -import type { Drawing2D } from "../../model/types"; -import { uniqueId } from "../../tools/types"; import type { Command, CommandContext, CommandResult, CommandState, - DraftShape, ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview } from "../createCore"; -const PREVIEW_RADIUS = 0.3; // Modell-Meter, deckt sich mit DETAILREF_RADIUS_M (plan/drawings.rs) -const DEFAULT_LABEL = "A"; interface DetailRefIdle extends CommandState { phase: "point"; @@ -29,27 +23,13 @@ interface DetailRefIdle extends CommandState { type DetailRefState = DetailRefIdle; /** Kreis-Vorschau (Vollkreis-Approximation, wie andere Symbol-Vorschauen). */ -function pointDraft(at: Vec2): ToolDraft { - const N = 32; - const pts: Vec2[] = []; - for (let i = 0; i < N; i++) { - const t = (i / N) * Math.PI * 2; - pts.push({ x: at.x + PREVIEW_RADIUS * Math.cos(t), y: at.y + PREVIEW_RADIUS * Math.sin(t) }); - } - const preview: DraftShape[] = [{ kind: "poly", pts, closed: true }]; - return { preview, vertices: [at] }; +/** Vorschau (Kern, `cmd_draw.rs`): Verweisblase (Kreis r = 0.3 m) am Cursor. */ +function pointDraft(ctx: CommandContext, at: Vec2): ToolDraft { + return { preview: createPreview(ctx, { cmd: "detailref" }, [at]).shapes, vertices: [at] }; } -function appendDetailRef(at: Vec2, ctx: CommandContext): CoreOp[] { - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "detailref", at, label: DEFAULT_LABEL }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern): Verweis „A“ am Punkt (Label/Blatt danach im Attribut-Panel). */ +const appendDetailRef = (at: Vec2, ctx: CommandContext) => createMutation(ctx, { cmd: "detailref", at }); const idle = (): [CommandState, CommandResult] => [ { phase: "point", lastPoint: null } as DetailRefIdle, @@ -69,11 +49,11 @@ export const detailrefCommand: Command = { if (input.kind !== "point") return [s, { draft: null }]; return [ { phase: "point", lastPoint: null } as DetailRefIdle, - { draft: null, done: true, commit: opsMutation(() => appendDetailRef(input.point, ctx)) }, + { draft: null, done: true, commit: appendDetailRef(input.point, ctx) }, ]; }, - onMove: (state, point): [CommandState, CommandResult] => [state, { draft: pointDraft(point) }], + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => [state, { draft: pointDraft(ctx, point) }], onConfirm: (): [CommandState, CommandResult] => idle(), onCancel: (): [CommandState, CommandResult] => idle(), }; diff --git a/src/commands/cmds/dimension.ts b/src/commands/cmds/dimension.ts index e53c34d3..5115946a 100644 --- a/src/commands/cmds/dimension.ts +++ b/src/commands/cmds/dimension.ts @@ -22,8 +22,7 @@ // Die Masszahl wird beim Rendern aus dist(a,b) abgeleitet (nicht gespeichert) // — bleibt beim späteren Griff-Ziehen automatisch korrekt. -import type { Drawing2D } from "../../model/types"; -import { segmentHud, uniqueId } from "../../tools/types"; +import { segmentHud } from "../../tools/types"; import type { Command, CommandContext, @@ -31,13 +30,10 @@ import type { CommandResult, CommandState, CmdOption, - DraftShape, - Project, ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation, patchItem } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview, createQuery, xy } from "../createCore"; const EPS = 1e-6; const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); @@ -51,44 +47,19 @@ function signedOffset(a: Vec2, b: Vec2, pt: Vec2): number { return (pt.x - a.x) * nx + (pt.y - a.y) * ny; } -/** Projiziert `pt` auf die Gerade durch `p0` in Richtung `p1` (Kette bleibt gerade ab Punkt 3). */ -function projectOnLine(p0: Vec2, p1: Vec2, pt: Vec2): Vec2 { - const dx = p1.x - p0.x, dy = p1.y - p0.y; - const len2 = dx * dx + dy * dy; - if (len2 < EPS) return pt; - const t = ((pt.x - p0.x) * dx + (pt.y - p0.y) * dy) / len2; - return { x: p0.x + dx * t, y: p0.y + dy * t }; -} - /** - * Sortiert `raw` (auf die Kettengerade projiziert) an die richtige Stelle in - * `pts` ein — VOR dem ersten (verlängert rückwärts), NACH dem letzten - * (verlängert vorwärts) oder ZWISCHEN zwei bestehenden Punkten (fügt ein). - * `pts` muss bereits kollinear sein (≥ 2 Punkte); die Skalarposition entlang - * der durch `pts[0]`/`pts[1]` festgelegten Geraden entscheidet die Reihenfolge. + * Neuen Punkt in die Kette einsortieren (Kern, `cmd_draw.rs`): auf die Masslinie pts[0]→pts[1] + * projiziert und nach Parameter einsortiert; unter 2 Punkten einfach angehängt. */ -function insertIntoChain(pts: Vec2[], raw: Vec2): Vec2[] { - if (pts.length < 2) return [...pts, raw]; - const p0 = pts[0], p1 = pts[1]; - const dx = p1.x - p0.x, dy = p1.y - p0.y; - const len2 = dx * dx + dy * dy || 1; - const tOf = (p: Vec2): number => ((p.x - p0.x) * dx + (p.y - p0.y) * dy) / len2; - const placed = projectOnLine(p0, p1, raw); - const newT = tOf(placed); - let idx = pts.findIndex((p) => newT < tOf(p)); - if (idx === -1) idx = pts.length; - const out = [...pts]; - out.splice(idx, 0, placed); - return out; +function insertIntoChain(ctx: CommandContext, pts: Vec2[], raw: Vec2): Vec2[] { + return createQuery<{ pts: Vec2[] }>(ctx.project, { q: "dimInsert", pts, pt: xy(raw) }).pts; } -/** Bestehende, selektierte Masskette (Rhino: erst selektieren, dann Befehl) oder null. */ +/** Vorgewählte Bemassungskette (Kern), deren Punkte erweitert werden. */ function selectedChain(ctx: CommandContext): { id: string; pts: Vec2[]; offset: number } | null { const id = ctx.selection.drawingId; if (!id) return null; - const d = ctx.project.drawings2d.find((x) => x.id === id); - if (!d || d.geom.shape !== "dimension") return null; - return { id: d.id, pts: d.geom.pts, offset: d.geom.offset }; + return createQuery<{ hit: { id: string; pts: Vec2[]; offset: number } | null }>(ctx.project, { q: "dimChain", id }).hit; } /** Endpunkte der um `offset` parallel verschobenen Masslinie (Strecke a-b). */ @@ -131,43 +102,23 @@ function chainDraft(pts: Vec2[], cursor: Vec2 | null): ToolDraft { } /** Vorschau: alle Masslinien-Segmente bei gegebenem Offset (grob — Massstriche/Text rendert generatePlan). */ -function offsetDraft(pts: Vec2[], offset: number, at: Vec2 | null): ToolDraft { - const preview: DraftShape[] = []; - for (let i = 0; i < pts.length - 1; i++) { - const a = pts[i], b = pts[i + 1]; - if (Math.abs(offset) > EPS) { - const off = offsetPoints(a, b, offset); - preview.push({ kind: "line", a, b: off.a }); - preview.push({ kind: "line", a: b, b: off.b }); - preview.push({ kind: "line", a: off.a, b: off.b }); - } else { - preview.push({ kind: "line", a, b }); - } - } - const draft: ToolDraft = { preview, vertices: pts }; +/** + * Vorschau der Lage (Kern): Hilfs- und Masslinien im Abstand des Cursors (ohne Cursor: Abstand 0) + HUD + * (Gesamtlänge · Abstand). + */ +function offsetDraft(ctx: CommandContext, pts: Vec2[], at: Vec2 | null): ToolDraft { + const pv = createPreview(ctx, { cmd: "dimension", phase: "offset", cursor: !!at }, at ? [...pts, at] : pts); + const draft: ToolDraft = { preview: pv.shapes, vertices: pts }; if (at) { - const total = pts.reduce((sum, p, i) => (i === 0 ? 0 : sum + dist(pts[i - 1], p)), 0); + const [offset, total] = pv.info; draft.hud = { at, text: `Σ${total.toFixed(3)}m · Δ${offset.toFixed(3)}m` }; } return draft; } -/** Committet eine Kette: neu anhängen (editId null) ODER dasselbe Element ersetzen. */ -function commitChain(p: Project, pts: Vec2[], offset: number, editId: string | null, ctx: CommandContext): CoreOp[] { - const cleaned = pts.filter((pt, i) => i === 0 || dist(pts[i - 1], pt) >= EPS); - if (cleaned.length < 2) return []; // zu wenig gültige Punkte → nichts committen/ändern - if (editId) { - return patchItem(p, "drawings2d", editId, (d): Drawing2D => ({ ...d, geom: { shape: "dimension", pts: cleaned, offset } })); - } - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "dimension", pts: cleaned, offset }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern): Kette (Nullstrecken entfernt) mit Abstand bzw. Seite eines Punkts; `editId` ändert eine bestehende. */ +const commitChain = (ctx: CommandContext, pts: Vec2[], offset: number | null, side: Vec2 | null, editId: string | null) => + createMutation(ctx, { cmd: "dimension", pts, offset, side, editId }); const idle = (): [CommandState, CommandResult] => [ { phase: "start", lastPoint: null }, @@ -201,7 +152,7 @@ export const dimensionCommand: Command = { } if (input.id === "finish" && s.pts.length >= 2) { const ns: DimOffset = { phase: "offset", pts: s.pts, cursor: s.cursor, editId: s.editId, lastPoint: s.lastPoint }; - return [ns, { draft: offsetDraft(s.pts, 0, null) }]; + return [ns, { draft: offsetDraft(ctx, s.pts, null) }]; } return [s, { draft: chainDraft(s.pts, s.cursor) }]; } @@ -213,43 +164,42 @@ export const dimensionCommand: Command = { // Erster Klick: bei selektierter Kette wird er EINSORTIERT (Ergänzen); // sonst startet er eine neue Kette. const existing = selectedChain(ctx); - const pts = existing ? insertIntoChain(existing.pts, pt) : [pt]; + const pts = existing ? insertIntoChain(ctx, existing.pts, pt) : [pt]; const editId = existing ? existing.id : null; const ns: DimNext = { phase: "next", pts, cursor: pt, editId, lastPoint: pt }; return [ns, { draft: chainDraft(pts, pt) }]; } // Ab dem dritten Punkt (bzw. jedem weiteren Klick im Ergänzen-Modus): // auf die durch Punkt 1/2 festgelegte Gerade projizieren/einsortieren. - const pts = s.pts.length >= 2 ? insertIntoChain(s.pts, pt) : [...s.pts, pt]; + const pts = s.pts.length >= 2 ? insertIntoChain(ctx, s.pts, pt) : [...s.pts, pt]; const ns: DimNext = { phase: "next", pts, cursor: pt, editId: s.editId, lastPoint: pt }; return [ns, { draft: chainDraft(pts, pt) }]; } // Offset-Schritt: Zahl = direkter Abstand, Punkt = Abstand zum Cursor. - let offset: number; - if (input.kind === "number") offset = input.value; - else if (input.kind === "point") offset = signedOffset(s.pts[0], s.pts[1], input.point); - else return [s, { draft: offsetDraft(s.pts, 0, null) }]; - const pts = s.pts; - const editId = s.editId; - return [ - { phase: "start", lastPoint: null }, - { draft: null, done: true, commit: opsMutation((p) => commitChain(p, pts, offset, editId, ctx)) }, - ]; + if (input.kind !== "number" && input.kind !== "point") return [s, { draft: offsetDraft(ctx, s.pts, null) }]; + const commit = + input.kind === "number" + ? commitChain(ctx, s.pts, input.value, null, s.editId) + : commitChain(ctx, s.pts, null, input.point, s.editId); + return [{ phase: "start", lastPoint: null }, { draft: null, done: true, commit }]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as DimState; if (s.phase === "next") { - const cursor = s.pts.length >= 2 ? projectOnLine(s.pts[0], s.pts[1], point) : point; + // Ab zwei Punkten folgt der Cursor der Masslinie (Projektion im Kern). + let cursor = point; + if (s.pts.length >= 2) { + const [cx, cy] = createPreview(ctx, { cmd: "dimension", phase: "next", cursor: true }, [...s.pts, point]).info; + cursor = { x: cx, y: cy }; + } const ns: DimNext = { ...s, cursor }; return [ns, { draft: chainDraft(s.pts, cursor) }]; } if (s.phase === "offset") { - // Offset relativ zum ERSTEN Segment (repräsentativ für die ganze Kette). - const off = signedOffset(s.pts[0], s.pts[1], point); const ns: DimOffset = { ...s, cursor: point }; - return [ns, { draft: offsetDraft(s.pts, off, point) }]; + return [ns, { draft: offsetDraft(ctx, s.pts, point) }]; } return [s, { draft: null }]; }, @@ -257,11 +207,11 @@ export const dimensionCommand: Command = { // Enter/Space/Rechtsklick: im "next"-Schritt (≥2 Punkte) wie Doppelklick → // Punktreihe abschliessen; im "offset"-Schritt bricht es ab (kein sinnvoller // Default-Abstand ohne Zeigegeste). - onConfirm: (state): [CommandState, CommandResult] => { + onConfirm: (state, ctx): [CommandState, CommandResult] => { const s = state as DimState; if (s.phase === "next" && s.pts.length >= 2) { const ns: DimOffset = { phase: "offset", pts: s.pts, cursor: s.cursor, editId: s.editId, lastPoint: s.lastPoint }; - return [ns, { draft: offsetDraft(s.pts, 0, null) }]; + return [ns, { draft: offsetDraft(ctx, s.pts, null) }]; } return idle(); }, diff --git a/src/commands/cmds/ellipse.ts b/src/commands/cmds/ellipse.ts index dea01b82..3bea6a37 100644 --- a/src/commands/cmds/ellipse.ts +++ b/src/commands/cmds/ellipse.ts @@ -19,9 +19,7 @@ // dafür keine Felder (separate, grössere Erweiterung, analog wie circle/arc // getrennte Shapes sind statt einer gemeinsamen mit optionaler Spanne). -import type { Drawing2D } from "../../model/types"; -import { segmentHud, uniqueId } from "../../tools/types"; -import { ellipsePts } from "../../core"; +import { segmentHud } from "../../tools/types"; import type { CmdOption, Command, @@ -29,13 +27,11 @@ import type { CommandField, CommandResult, CommandState, - DraftShape, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview, type CreatePreview } from "../createCore"; const EPS = 1e-6; @@ -100,29 +96,27 @@ type EllipseState = | EllipseAxisMajor | EllipseAxisMinor; -/** Zentrum + Halbachsen aus zwei gegenüberliegenden Bounding-Box-Ecken. */ -function ellipseFromCorners(p0: Vec2, p1: Vec2): { center: Vec2; rx: number; ry: number } { - return { - center: { x: (p0.x + p1.x) / 2, y: (p0.y + p1.y) / 2 }, - rx: Math.abs(p1.x - p0.x) / 2, - ry: Math.abs(p1.y - p0.y) / 2, - }; -} +/** + * Ellipse im Kern (`cmd_draw.rs`): box (`[p0, p1]` → Mitte, Halbachsen achsparallel) oder axis + * (`[Mitte, Hauptachse, Nebenachsen-Punkt]`); `info = [cx, cy, rx, ry]`. + */ +const ellipseAt = (ctx: CommandContext, method: EllipseMethod, pts: Vec2[]): CreatePreview => + createPreview(ctx, { cmd: "ellipse", method }, pts); // ── Vorschau ───────────────────────────────────────────────────────────────── -function ellipseDraft(center: Vec2, rx: number, ry: number, rotation: number, at: Vec2 | null): ToolDraft { +function ellipseDraft(pv: CreatePreview, at: Vec2 | null): ToolDraft { + const [cx, cy, rx, ry] = pv.info; + const center = { x: cx, y: cy }; if (rx < EPS || ry < EPS) return { preview: [], vertices: [center] }; - const preview: DraftShape[] = [{ kind: "poly", pts: ellipsePts(center, rx, ry, rotation), closed: true }]; - const draft: ToolDraft = { preview, vertices: [center] }; + const draft: ToolDraft = { preview: pv.shapes, vertices: [center] }; if (at) draft.hud = { at, text: `${(rx * 2).toFixed(3)}×${(ry * 2).toFixed(3)}m` }; return draft; } -function boxDraft(p0: Vec2, cursor: Vec2 | null): ToolDraft { +function boxDraft(ctx: CommandContext, p0: Vec2, cursor: Vec2 | null): ToolDraft { if (!cursor) return { preview: [], vertices: [p0] }; - const { center, rx, ry } = ellipseFromCorners(p0, cursor); - return ellipseDraft(center, rx, ry, 0, cursor); + return ellipseDraft(ellipseAt(ctx, "box", [p0, cursor]), cursor); } function axisMajorDraft(center: Vec2, cursor: Vec2 | null): ToolDraft { @@ -130,31 +124,16 @@ function axisMajorDraft(center: Vec2, cursor: Vec2 | null): ToolDraft { return { preview: [{ kind: "line", a: center, b: cursor }], vertices: [center], hud: segmentHud(center, cursor) }; } -function axisMinorDraft(center: Vec2, major: Vec2, cursor: Vec2 | null): ToolDraft { - const rx = dist(center, major); - if (!cursor) return ellipseDraft(center, rx, 0, angleOf(center, major), null); - const ry = Math.abs(perpDist(center, major, cursor)); - return ellipseDraft(center, rx, ry, angleOf(center, major), cursor); +function axisMinorDraft(ctx: CommandContext, center: Vec2, major: Vec2, cursor: Vec2 | null): ToolDraft { + if (!cursor) return ellipseDraft(ellipseAt(ctx, "axis", [center, major]), null); + return ellipseDraft(ellipseAt(ctx, "axis", [center, major, cursor]), cursor); } // ── Commit ─────────────────────────────────────────────────────────────────── -function appendEllipse(center: Vec2, - rx: number, - ry: number, - rotation: number, - ctx: CommandContext, -): CoreOp[] { - if (rx < EPS || ry < EPS) return []; - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "ellipse", center, rx, ry, rotation }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern): Ellipse aus den Punkten (entartet → nichts). */ +const appendEllipse = (ctx: CommandContext, method: EllipseMethod, pts: Vec2[]) => + createMutation(ctx, { cmd: "ellipse", method, pts }); const idle = (method: EllipseMethod): [CommandState, CommandResult] => [ (method === "box" ? { phase: "corner1", method } : { phase: "center", method }) as EllipseState, @@ -197,10 +176,9 @@ export const ellipseCommand: Command = { if (s.method === "box") { if (s.phase !== "corner2") { const ns: EllipseBoxP2 = { phase: "corner2", method: "box", p0: pt, cursor: pt, lastPoint: pt }; - return [ns, { draft: boxDraft(pt, pt) }]; + return [ns, { draft: boxDraft(ctx, pt, pt) }]; } - const { center, rx, ry } = ellipseFromCorners(s.p0, pt); - return [idle("box")[0], { draft: null, done: true, commit: opsMutation(() => appendEllipse(center, rx, ry, 0, ctx)) }]; + return [idle("box")[0], { draft: null, done: true, commit: appendEllipse(ctx, "box", [s.p0, pt]) }]; } // axis @@ -211,25 +189,18 @@ export const ellipseCommand: Command = { if (s.phase === "major") { if (dist(s.center, pt) < EPS) return [s, { draft: null }]; const ns: EllipseAxisMinor = { phase: "minor", method: "axis", center: s.center, major: pt, cursor: pt, lastPoint: pt }; - return [ns, { draft: axisMinorDraft(s.center, pt, null) }]; + return [ns, { draft: axisMinorDraft(ctx, s.center, pt, null) }]; } // phase "minor" → committen. - const { center, major } = s; - const rx = dist(center, major); - const ry = Math.abs(perpDist(center, major, pt)); - const rotation = angleOf(center, major); - return [ - idle("axis")[0], - { draft: null, done: true, commit: opsMutation(() => appendEllipse(center, rx, ry, rotation, ctx)) }, - ]; + return [idle("axis")[0], { draft: null, done: true, commit: appendEllipse(ctx, "axis", [s.center, s.major, pt]) }]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as EllipseState; if (s.method === "box") { if (s.phase !== "corner2") return [s, { draft: null }]; const ns: EllipseBoxP2 = { ...s, cursor: point }; - return [ns, { draft: boxDraft(s.p0, point) }]; + return [ns, { draft: boxDraft(ctx, s.p0, point) }]; } if (s.phase === "major") { const ns: EllipseAxisMajor = { ...s, cursor: point }; @@ -237,7 +208,7 @@ export const ellipseCommand: Command = { } if (s.phase === "minor") { const ns: EllipseAxisMinor = { ...s, cursor: point }; - return [ns, { draft: axisMinorDraft(s.center, s.major, point) }]; + return [ns, { draft: axisMinorDraft(ctx, s.center, s.major, point) }]; } return [s, { draft: null }]; }, diff --git a/src/commands/cmds/extrude.ts b/src/commands/cmds/extrude.ts index f2645452..9d21af23 100644 --- a/src/commands/cmds/extrude.ts +++ b/src/commands/cmds/extrude.ts @@ -13,9 +13,6 @@ // (emitExtrudedSolids); dieser Befehl legt nur die Rohdaten (Punkte + Höhe + // Verjüngung) im Projekt ab. -import type { Drawing2D, ExtrudedSolid } from "../../model/types"; -import { uniqueId } from "../../tools/types"; -import { polylineEdges, pointSegmentDistance } from "../../core"; import type { Command, CommandContext, @@ -25,108 +22,40 @@ import type { Project, Vec2, } from "../types"; -import { addItems, opsMutation, removeItems } from "../../core"; -import type { CoreOp } from "../../core"; - -const HIT_TOL = 0.25; // Modell-Meter: Pick-Toleranz für die Profil-Wahl +import { createMutation, createQuery, xy } from "../createCore"; /** Persistente Extrusionshöhe über Aufrufe hinweg (Default: Geschosshöhe). */ let lastHeight = 2.6; /** Persistente Verjüngung über Aufrufe hinweg (Default: Prisma, kein Kegel/Pyramide). */ let lastTaper = 0; -// ── Profil-Abstraktion: geschlossene polyline/rect/circle → Punktliste ───── +// ── Profil (Kern, `cmd_create.rs`): geschlossene polyline/rect/circle → Punktliste ─ -/** Kreis-Tessellierung für Footprint/Auswahl/bbox (48-Eck, wie circle.ts). */ -function circlePts(center: Vec2, r: number): Vec2[] { - const N = 48; - const pts: Vec2[] = []; - for (let i = 0; i < N; i++) { - const t = (i / N) * Math.PI * 2; - pts.push({ x: center.x + r * Math.cos(t), y: center.y + r * Math.sin(t) }); - } - return pts; -} - -/** Ein extrudierfähiges Profil: Tessellierung + optional die echte Kreis-Geometrie. */ +/** Profil eines extrudierbaren 2D-Elements (Kreis: 48-Eck + Mittelpunkt/Radius). */ interface Profile { pts: Vec2[]; circle?: { center: Vec2; r: number }; } -/** Wandelt ein extrudierfähiges (geschlossenes) Drawing2D in ein Profil. */ -function geomToProfile(d: Drawing2D): Profile | null { - const g = d.geom; - if (g.shape === "polyline" && g.closed && g.pts.length >= 3) return { pts: g.pts }; - if (g.shape === "rect") { - return { pts: [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }] }; - } - if (g.shape === "circle") { - return { pts: circlePts(g.center, g.r), circle: { center: g.center, r: g.r } }; - } - return null; +type ProfileHit = { id: string } & Profile; + +function profileQuery(project: Project, req: { q: string } & Record): ProfileHit | null { + return createQuery<{ hit: (ProfileHit & { circle: Profile["circle"] | null }) | null }>(project, req).hit ?? null; } -/** Genau ein passendes Drawing2D vorselektiert? Dann liefere sein Profil. */ -function singleSelectedProfile( - project: Project, - sel: CommandSelection, -): ({ d: Drawing2D } & Profile) | null { +/** Genau EIN geeignetes Profil vorgewählt (sonst null). */ +function singleSelectedProfile(project: Project, sel: CommandSelection): ProfileHit | null { if (!sel.drawingId || sel.wallIds.length > 0) return null; - const d = project.drawings2d.find((x) => x.id === sel.drawingId); - if (!d) return null; - const profile = geomToProfile(d); - return profile ? { d, ...profile } : null; + return profileQuery(project, { q: "profile", id: sel.drawingId }); } -/** Nächstes extrudierfähige Drawing2D zum Klickpunkt (innerhalb Toleranz). */ -function pickProfileAt( - project: Project, - levelId: string, - pt: Vec2, -): ({ d: Drawing2D } & Profile) | null { - let best: ({ d: Drawing2D } & Profile) | null = null; - let bestD = HIT_TOL; - for (const d of project.drawings2d) { - if (d.levelId !== levelId) continue; - const profile = geomToProfile(d); - if (!profile) continue; - for (const [a, b] of polylineEdges(profile.pts, true)) { - const dd = pointSegmentDistance(pt, a, b); - if (dd < bestD) { - bestD = dd; - best = { d, ...profile }; - } - } - } - return best; -} +/** Nächstes Profil der Ebene am Klickpunkt (Kanten-Abstand < 0.25 m). */ +const pickProfileAt = (project: Project, levelId: string, pt: Vec2): ProfileHit | null => + profileQuery(project, { q: "pickProfile", level: levelId, pt: xy(pt) }); -/** - * Hängt den neuen Körper an UND entfernt das Quell-Profil (`sourceId`) aus - * `drawings2d` — die Polylinie/das Rechteck WIRD zur Extrusion, sie bleibt - * nicht als unabhängiges Duplikat liegen (sonst zwei Objekte am selben Ort, - * eines davon im Grundriss unsichtbar verwaist). - */ -function appendExtrudedSolid( - p: Project, - profile: Profile, - height: number, - taper: number, - sourceId: string, - ctx: CommandContext, -): CoreOp[] { - const solid: ExtrudedSolid = { - id: uniqueId("extrude"), - type: "extrudedSolid", - levelId: ctx.level.id, - points: profile.pts, - height, - circle: profile.circle, - ...(taper > 0 ? { taper } : {}), - }; - return [...removeItems(p, "drawings2d", [sourceId]), ...addItems("extrudedSolids", [solid])]; -} +/** Commit (Kern): Quelle entfernen, Körper (Punkte + Höhe + Verjüngung) anlegen. */ +const appendExtrudedSolid = (height: number, taper: number, sourceId: string, ctx: CommandContext) => + createMutation(ctx, { cmd: "extrude", source: sourceId, height, taper }); // ── Zustand ─────────────────────────────────────────────────────────────────── @@ -168,14 +97,13 @@ const enterTaperPhase = ( ]; const commitTaper = ( - profile: Profile, height: number, taper: number, sourceId: string, ctx: CommandContext, ): [CommandState, CommandResult] => [ { phase: "done", lastPoint: null } as ExDone, - { draft: null, done: true, commit: opsMutation((p) => appendExtrudedSolid(p, profile, height, taper, sourceId, ctx)) }, + { draft: null, done: true, commit: appendExtrudedSolid(height, taper, sourceId, ctx) }, ]; export const extrudeCommand: Command = { @@ -207,16 +135,16 @@ export const extrudeCommand: Command = { const h = Math.abs(input.value); if (h < 1e-6) return [s, { draft: null }]; lastHeight = h; - return enterTaperPhase(pre, h, pre.d.id); + return enterTaperPhase(pre, h, pre.id); } // Punkt im vorselektierten Fall: Höhen-Schritt betreten (HUD zeigt Default). - const ns: ExHeight = { phase: "height", profile: pre, sourceId: pre.d.id, cursor: null, lastPoint: null }; + const ns: ExHeight = { phase: "height", profile: pre, sourceId: pre.id, cursor: null, lastPoint: null }; return [ns, { draft: null }]; } if (input.kind === "point") { const hit = pickProfileAt(ctx.project, ctx.level.id, input.point); if (!hit) return [s, { draft: null }]; - const ns: ExHeight = { phase: "height", profile: hit, sourceId: hit.d.id, cursor: null, lastPoint: null }; + const ns: ExHeight = { phase: "height", profile: hit, sourceId: hit.id, cursor: null, lastPoint: null }; return [ns, { draft: null }]; } return [s, { draft: null }]; @@ -237,7 +165,7 @@ export const extrudeCommand: Command = { if (input.kind === "number") { const t = Math.min(1, Math.max(0, input.value)); lastTaper = t; - return commitTaper(ts.profile, ts.height, t, ts.sourceId, ctx); + return commitTaper(ts.height, t, ts.sourceId, ctx); } return [ts, { draft: null }]; }, @@ -278,7 +206,7 @@ export const extrudeCommand: Command = { onConfirm: (state, ctx): [CommandState, CommandResult] => { const s = state as ExState; if (s.phase === "height") return enterTaperPhase(s.profile, lastHeight, s.sourceId); - if (s.phase === "taper") return commitTaper(s.profile, s.height, lastTaper, s.sourceId, ctx); + if (s.phase === "taper") return commitTaper(s.height, lastTaper, s.sourceId, ctx); return finish(); }, onCancel: (): [CommandState, CommandResult] => finish(), diff --git a/src/commands/cmds/kote.ts b/src/commands/cmds/kote.ts index 8b65e665..99f3574f 100644 --- a/src/commands/cmds/kote.ts +++ b/src/commands/cmds/kote.ts @@ -5,21 +5,17 @@ // commit. „Art" (Option, zyklisch: OK fertig/UK fertig/OK roh/UK roh) // wechselt VOR dem Tippen die Dreieck-Variante (Default OK fertig). -import type { Drawing2D } from "../../model/types"; -import { uniqueId } from "../../tools/types"; import type { Command, CommandContext, CommandResult, CommandState, CmdOption, - DraftShape, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview } from "../createCore"; type KoteKind = "okFertig" | "ukFertig" | "okRoh" | "ukRoh"; const KIND_ORDER: KoteKind[] = ["okFertig", "ukFertig", "okRoh", "ukRoh"]; @@ -31,19 +27,6 @@ const KIND_LABEL: Record = { ukRoh: "cmd.kote.kind.ukRoh", }; -const TRI_SIZE = 0.15; // Modell-Meter, Vorschau-Grösse (Rendering: KOTE_… in plan/drawings.rs) -const HALF_W = TRI_SIZE * 0.6; - -/** Dreieck-Punkte für die Vorschau: `at` = Spitze; OK zeigt nach unten, UK nach oben. */ -function triPts(at: Vec2, kind: KoteKind): Vec2[] { - const up = kind === "okFertig" || kind === "okRoh" ? 1 : -1; // Basis liegt in +up-Richtung von `at` - return [ - at, - { x: at.x - HALF_W, y: at.y + up * TRI_SIZE }, - { x: at.x + HALF_W, y: at.y + up * TRI_SIZE }, - ]; -} - interface KotePoint extends CommandState { phase: "point"; } @@ -58,21 +41,14 @@ function kindOption(kind: KoteKind): CmdOption { return { id: "kind", labelKey: KIND_LABEL[kind], value: kind }; } -function valueDraft(at: Vec2, kind: KoteKind): ToolDraft { - const preview: DraftShape[] = [{ kind: "poly", pts: triPts(at, kind), closed: true }]; - return { preview, vertices: [at] }; +/** Vorschau (Kern, `cmd_draw.rs`): Kote-Dreieck (Spitze am Punkt, Basis oben für OK, unten für UK). */ +function valueDraft(ctx: CommandContext, at: Vec2, kind: KoteKind): ToolDraft { + return { preview: createPreview(ctx, { cmd: "kote", kind }, [at]).shapes, vertices: [at] }; } -function appendKote(at: Vec2, value: number, kind: KoteKind, ctx: CommandContext): CoreOp[] { - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "kote", at, value, kind, rotation: 0 }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern): Höhenkote am Punkt mit getipptem Wert. */ +const appendKote = (at: Vec2, value: number, kind: KoteKind, ctx: CommandContext) => + createMutation(ctx, { cmd: "kote", at, value, kind }); const idle = (): [CommandState, CommandResult] => [ { phase: "point", lastPoint: null }, @@ -92,17 +68,17 @@ export const koteCommand: Command = { if (s.phase === "point") { if (input.kind !== "point") return [s, { draft: null }]; const ns: KoteValue = { phase: "value", at: input.point, kind: "okFertig", lastPoint: input.point }; - return [ns, { draft: valueDraft(input.point, "okFertig") }]; + return [ns, { draft: valueDraft(ctx, input.point, "okFertig") }]; } if (input.kind === "option" && input.id === "kind") { const ns: KoteValue = { ...s, kind: nextKind(s.kind) }; - return [ns, { draft: valueDraft(s.at, ns.kind) }]; + return [ns, { draft: valueDraft(ctx, s.at, ns.kind) }]; } - if (input.kind !== "number") return [s, { draft: valueDraft(s.at, s.kind) }]; + if (input.kind !== "number") return [s, { draft: valueDraft(ctx, s.at, s.kind) }]; const { at, kind } = s; return [ { phase: "point", lastPoint: null }, - { draft: null, done: true, commit: opsMutation(() => appendKote(at, input.value, kind, ctx)) }, + { draft: null, done: true, commit: appendKote(at, input.value, kind, ctx) }, ]; }, diff --git a/src/commands/cmds/leader.ts b/src/commands/cmds/leader.ts index 4c5f9a2a..37ffa493 100644 --- a/src/commands/cmds/leader.ts +++ b/src/commands/cmds/leader.ts @@ -13,7 +13,6 @@ // Inline-Editor-Infrastruktur wie beim `text`-Befehl (kein neuer Shape, // s. `Drawing2DGeom["text"].leaderTarget`/`.leaderBendPoints`). -import type { Drawing2D } from "../../model/types"; import { uniqueId } from "../../tools/types"; import type { CmdOption, @@ -26,10 +25,8 @@ import type { Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation } from "../createCore"; -const DEFAULT_TEXT_HEIGHT_M = 0.25; const MAX_BENDS = 4; /** Persistente Knick-Anzahl über Aufrufe hinweg (wie `lastCount` bei Array). */ @@ -54,29 +51,9 @@ interface LeaderAnchor extends CommandState { } type LeaderState = LeaderTarget | LeaderBend | LeaderAnchor; -function appendLeaderText(id: string, - at: Vec2, - target: Vec2, - bends: Vec2[], - ctx: CommandContext, -): CoreOp[] { - const d: Drawing2D = { - id, - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { - shape: "text", - at, - text: "", - height: DEFAULT_TEXT_HEIGHT_M, - angle: 0, - leaderTarget: target, - ...(bends.length > 0 ? { leaderBendPoints: bends } : {}), - }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern, `cmd_draw.rs`): leerer Text am Anker mit Hinweislinie zum Ziel (Knickpunkte, falls gesetzt). */ +const appendLeaderText = (id: string, at: Vec2, target: Vec2, bends: Vec2[], ctx: CommandContext) => + createMutation(ctx, { cmd: "leader", id, at, target, bends }); const idle = (): [CommandState, CommandResult] => [ { phase: "target", lastPoint: null } as LeaderTarget, @@ -142,7 +119,7 @@ export const leaderCommand: Command = { { draft: null, done: true, - commit: opsMutation(() => appendLeaderText(id, pt, target, bends, ctx)), + commit: appendLeaderText(id, pt, target, bends, ctx), focusDrawingId: id, }, ]; diff --git a/src/commands/cmds/line.ts b/src/commands/cmds/line.ts index 71d602e1..bd19f412 100644 --- a/src/commands/cmds/line.ts +++ b/src/commands/cmds/line.ts @@ -24,8 +24,7 @@ // getippte Koordinaten — das ist die Kern-Vereinheitlichung gegenüber dem alten // Tool. Live-Vorschau + HUD (Länge/Winkel) wie die bestehenden Tools. -import type { Drawing2D } from "../../model/types"; -import { segmentHud, uniqueId } from "../../tools/types"; +import { segmentHud } from "../../tools/types"; import type { Command, CommandContext, @@ -36,8 +35,7 @@ import type { ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation } from "../createCore"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -82,17 +80,8 @@ function lineDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { return draft; } -/** Hängt eine 2D-Linie ans Projekt (immutabel). Farbe/Strich erbt die Kategorie. */ -function appendLine(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] { - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "line", a, b }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern, `cmd_draw.rs`): 2D-Linie a→b; Farbe/Strich erbt die Kategorie. */ +const appendLine = (a: Vec2, b: Vec2, ctx: CommandContext) => createMutation(ctx, { cmd: "line", a, b }); export const lineCommand: Command = { name: "line", @@ -119,7 +108,7 @@ export const lineCommand: Command = { } const a = s.a; const next: LineDrawing = { phase: "end", a: pt, cursor: pt, lastPoint: pt }; - return [next, { draft: lineDraft(pt, pt), commit: opsMutation(() => appendLine(a, pt, ctx)) }]; + return [next, { draft: lineDraft(pt, pt), commit: appendLine(a, pt, ctx) }]; }, onMove: (state, point): [CommandState, CommandResult] => { diff --git a/src/commands/cmds/multiline.ts b/src/commands/cmds/multiline.ts index 9de29102..19954468 100644 --- a/src/commands/cmds/multiline.ts +++ b/src/commands/cmds/multiline.ts @@ -1,7 +1,7 @@ // Multiline — zeichnet in EINER Geste eine gerade Basislinie PLUS N−1 dazu // parallel versetzte Kopien (gleicher Abstand, gleiche Seite), z. B. für // Doppellinien/Leitungstrassen/Abstandslinien. Baut auf derselben Offset- -// Geometrie wie der bestehende `offset`-Befehl auf (`offsetSegment`), erzeugt +// Geometrie wie der bestehende `offset`-Befehl auf (`kernel2d::offset_segment`, Kern `cmd_draw.rs`), erzeugt // aber alle Kopien auf einmal statt einzeln nacheinander offsetten zu müssen. // Schritte: // 1) „Startpunkt:" → Punkt @@ -15,10 +15,7 @@ // Anwendungsfall ab (Grenzlinie+Abstand, Leitungspaar, Randlinien), ohne die // Komplexität einer mehrsegmentigen Variante. -import type { Drawing2D } from "../../model/types"; -import { segmentHud, uniqueId } from "../../tools/types"; -import { leftNormal, normalize, sub } from "../../model/geometry"; -import { offsetSegment } from "../../core"; +import { segmentHud } from "../../tools/types"; import type { CmdOption, Command, @@ -30,8 +27,7 @@ import type { ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview } from "../createCore"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -60,35 +56,18 @@ function endFromFields(a: Vec2, locks: Record, cursor: Vec2 | nu } /** Vorzeichen (+links / −rechts) für einen Klickpunkt relativ zur Basislinie a→b. */ -function sideSign(a: Vec2, b: Vec2, pt: Vec2): number { - const mid: Vec2 = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; - const u = normalize(sub(b, a)); - const n = leftNormal(u); - const rel = sub(pt, mid); - return rel.x * n.x + rel.y * n.y >= 0 ? 1 : -1; +/** + * Vorschau im Kern (`cmd_draw.rs`): Original a→b + (count−1) parallele Kopien im Abstand `spacing` auf + * der Seite `sign` (fehlt sie, die Seite des Cursors). `side` = Seite des Cursors (+1 links, −1 rechts). + */ +function multilineAt(ctx: CommandContext, a: Vec2, b: Vec2, cursor: Vec2 | null, sign: number | null) { + const pv = createPreview(ctx, { cmd: "multiline", spacing: lastSpacing, count: lastCount, sign }, cursor ? [a, b, cursor] : [a, b]); + return { shapes: pv.shapes, side: pv.info[0] }; } -/** Die `count` parallelen Linien (Index 0 = Basislinie) als Punktpaare. */ -function multilinePairs(a: Vec2, b: Vec2, spacing: number, sign: number, count: number): [Vec2, Vec2][] { - const out: [Vec2, Vec2][] = [[a, b]]; - for (let k = 1; k < count; k++) { - out.push(offsetSegment(a, b, sign * spacing * k)); - } - return out; -} - -function appendMultiline(a: Vec2, b: Vec2, spacing: number, sign: number, count: number, ctx: CommandContext): CoreOp[] { - if (segLen(a, b) < EPS) return []; - const pairs = multilinePairs(a, b, spacing, sign, count); - const copies: Drawing2D[] = pairs.map(([pa, pb]) => ({ - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "line", a: pa, b: pb }, - })); - return addItems("drawings2d", copies); -} +/** Commit (Kern): Original + parallele Kopien als einzelne Linien (Null-Strecke → nichts). */ +const appendMultiline = (a: Vec2, b: Vec2, spacing: number, sign: number, count: number, ctx: CommandContext) => + createMutation(ctx, { cmd: "multiline", a, b, spacing, sign, count }); const COUNT_OPTION: CmdOption = { id: "count", labelKey: "cmd.multiline.count" }; @@ -115,10 +94,8 @@ const idle = (): [CommandState, CommandResult] => [ ]; /** Vorschau aller `lastCount` Linien bei gegebenem Abstand+Seite. */ -function spacingDraft(a: Vec2, b: Vec2, spacing: number, sign: number, at: Vec2 | null): ToolDraft { - const pairs = multilinePairs(a, b, spacing, sign, lastCount); - const preview: DraftShape[] = pairs.map(([pa, pb]) => ({ kind: "line", a: pa, b: pb })); - const draft: ToolDraft = { preview, vertices: [a, b] }; +function spacingDraft(ctx: CommandContext, a: Vec2, b: Vec2, spacing: number, sign: number | null, at: Vec2 | null): ToolDraft { + const draft: ToolDraft = { preview: multilineAt(ctx, a, b, at, sign).shapes, vertices: [a, b] }; if (at) draft.hud = { at, text: `${spacing.toFixed(2)} m × ${lastCount}` }; return draft; } @@ -150,15 +127,14 @@ export const multilineCommand: Command = { if (input.kind !== "point") return [s, { draft: spacingDraftForEnd(s) }]; if (segLen(s.a, input.point) < EPS) return idle(); const next: MlSpacing = { phase: "spacing", a: s.a, b: input.point, cursor: input.point, lastPoint: input.point }; - return [next, { draft: spacingDraft(next.a, next.b, lastSpacing, lastSign, input.point) }]; + return [next, { draft: spacingDraft(ctx, next.a, next.b, lastSpacing, lastSign, input.point) }]; } // phase === "spacing" if (input.kind === "option") { if (input.id === "count") { lastCount = lastCount >= MAX_COUNT ? MIN_COUNT : lastCount + 1; - const sign = s.cursor ? sideSign(s.a, s.b, s.cursor) : lastSign; - return [s, { draft: spacingDraft(s.a, s.b, lastSpacing, sign, s.cursor) }]; + return [s, { draft: spacingDraft(ctx, s.a, s.b, lastSpacing, s.cursor ? null : lastSign, s.cursor) }]; } return [s, { draft: null }]; } @@ -170,21 +146,21 @@ export const multilineCommand: Command = { const { a, b } = s; return [ idle()[0], - { draft: null, done: true, commit: opsMutation(() => appendMultiline(a, b, lastSpacing, lastSign, lastCount, ctx)) }, + { draft: null, done: true, commit: appendMultiline(a, b, lastSpacing, lastSign, lastCount, ctx) }, ]; } if (input.kind === "point") { - lastSign = sideSign(s.a, s.b, input.point); + lastSign = multilineAt(ctx, s.a, s.b, input.point, null).side; const { a, b } = s; return [ idle()[0], - { draft: null, done: true, commit: opsMutation(() => appendMultiline(a, b, lastSpacing, lastSign, lastCount, ctx)) }, + { draft: null, done: true, commit: appendMultiline(a, b, lastSpacing, lastSign, lastCount, ctx) }, ]; } return [s, { draft: null }]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as MlState; if (s.phase === "end") { const next: MlEnd = { ...s, cursor: point }; @@ -194,9 +170,8 @@ export const multilineCommand: Command = { return [next, { draft }]; } if (s.phase === "spacing") { - const sign = sideSign(s.a, s.b, point); const next: MlSpacing = { ...s, cursor: point }; - return [next, { draft: spacingDraft(s.a, s.b, lastSpacing, sign, point) }]; + return [next, { draft: spacingDraft(ctx, s.a, s.b, lastSpacing, null, point) }]; } return [s, { draft: null }]; }, diff --git a/src/commands/cmds/opening.ts b/src/commands/cmds/opening.ts index 6e9992c0..7faa6407 100644 --- a/src/commands/cmds/opening.ts +++ b/src/commands/cmds/opening.ts @@ -12,8 +12,6 @@ // // Bezeichner englisch, sichtbarer Text via t() (CONVENTIONS.md). -import type { Opening } from "../../model/types"; -import { uniqueId } from "../../tools/types"; import type { Command, CommandContext, @@ -21,69 +19,25 @@ import type { CommandResult, CommandState, CmdOption, - DraftShape, ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview, createQuery, xy } from "../createCore"; -/** Default-Ebene (Kategorie) für Öffnungen: „21" Türen/Fenster (Fallback: aktive). */ -const OPENING_CATEGORY = "21"; -/** Toleranz (Modell-Meter) für das Picken einer Host-Wand per Klick. */ -const WALL_PICK_DIST = 0.6; /** Default-Maße (Meter). */ const DEF_WINDOW = { width: 1.2, height: 1.2, sill: 0.9 }; const DEF_DOOR = { width: 0.9, height: 2.1, sill: 0 }; -const sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y }); -const dot = (a: Vec2, b: Vec2): number => a.x * b.x + a.y * b.y; -const add = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x + b.x, y: a.y + b.y }); -const scale = (a: Vec2, s: number): Vec2 => ({ x: a.x * s, y: a.y * s }); - -/** Existiert die Öffnungs-Kategorie („21")? Sonst Fallback auf die aktive. */ -function openingCategory(ctx: CommandContext): string { - const flat: { code: string }[] = []; - const walk = (list: { code: string; children?: unknown[] }[]) => { - for (const c of list) { - flat.push({ code: c.code }); - if (c.children) walk(c.children as { code: string; children?: unknown[] }[]); - } - }; - walk(ctx.project.layers as { code: string; children?: unknown[] }[]); - return flat.some((c) => c.code === OPENING_CATEGORY) - ? OPENING_CATEGORY - : ctx.defaultCategoryCode; -} - -/** Auf die Wandachse projizierter Fußpunkt + Parameter t (0..len) + Distanz. */ -function projectOntoWall( - wall: { start: Vec2; end: Vec2 }, - p: Vec2, -): { t: number; foot: Vec2; dist: number } { - const ax = sub(wall.end, wall.start); - const len2 = dot(ax, ax) || 1e-9; - const raw = dot(sub(p, wall.start), ax) / len2; // 0..1 - const t = Math.max(0, Math.min(1, raw)); - const foot = add(wall.start, scale(ax, t)); - const dist = Math.hypot(p.x - foot.x, p.y - foot.y); - return { t: t * Math.sqrt(len2), foot, dist }; -} - -/** Nächste Wand auf dem aktiven Geschoss zum Klickpunkt (innerhalb Toleranz). */ -function pickWall( - ctx: CommandContext, - p: Vec2, -): { id: string; start: Vec2; end: Vec2 } | null { - let best: { id: string; start: Vec2; end: Vec2; d: number } | null = null; - for (const w of ctx.project.walls) { - if (w.floorId !== ctx.level.id) continue; - const { dist } = projectOntoWall(w, p); - if (dist <= WALL_PICK_DIST && (!best || dist < best.d)) { - best = { id: w.id, start: w.start, end: w.end, d: dist }; - } - } - return best ? { id: best.id, start: best.start, end: best.end } : null; +/** Nächste Wand des Geschosses zum Klickpunkt (Kern): id, Achse und Abstand des Fusspunkts vom Anfang. */ +function pickWall(ctx: CommandContext, p: Vec2): { id: string; start: Vec2; end: Vec2; t: number } | null { + const r = createQuery<{ hit: { id: string; start: [number, number]; end: [number, number]; t: number } | null }>(ctx.project, { + q: "pickWall", + level: ctx.level.id, + pt: xy(p), + }); + if (!r.hit) return null; + const { id, start, end, t } = r.hit; + return { id, start: { x: start[0], y: start[1] }, end: { x: end[0], y: end[1] }, t }; } /** Tab-Felder im Positionsschritt: Breite/Höhe/Brüstung (+ Winkel bei Tür). */ @@ -144,73 +98,44 @@ function initState(kind: "window" | "door" = "window"): OpIdle { }; } -/** Vorschau: Lücken-Balken entlang der Wand + Positionsmarke. */ -function posDraft(s: OpPos): ToolDraft { - const ax = sub(s.end, s.start); - const len = Math.hypot(ax.x, ax.y) || 1e-9; - const u = { x: ax.x / len, y: ax.y / len }; - const n = { x: -u.y, y: u.x }; - const from = Math.max(0, Math.min(s.posAlong, len)); - const to = Math.max(from, Math.min(from + s.width, len)); - const a = add(s.start, scale(u, from)); - const b = add(s.start, scale(u, to)); - const half = 0.15; // Vorschau-Balken quer zur Wand - const quad: Vec2[] = [ - add(a, scale(n, half)), - add(b, scale(n, half)), - add(b, scale(n, -half)), - add(a, scale(n, -half)), - ]; - const preview: DraftShape[] = [{ kind: "poly", pts: quad, closed: true }]; - // Symbol-Andeutung: Fenster = Mittellinie, Tür = Blatt-Linie in Schwenkrichtung. - if (s.kind === "window") { - preview.push({ kind: "line", a, b }); - } else { - const swingSign = s.side === "left" ? 1 : -1; - const dirSign = s.dir === "in" ? 1 : -1; - const hinge = s.hinge === "start" ? a : b; - const leafEnd = add(hinge, scale(n, swingSign * dirSign * s.width)); - preview.push({ kind: "line", a: hinge, b: leafEnd }); - } - const draft: ToolDraft = { preview, vertices: [a, b] }; - const mid = add(a, scale(u, (to - from) / 2)); +/** Anfrage an den Kern (`cmd_create.rs`); `pos` = null → Position aus dem Cursor projiziert. */ +const openingReq = (s: OpPos, pos: number | null) => ({ + cmd: "opening", + wall: s.wallId, + start: xy(s.start), + end: xy(s.end), + kind: s.kind, + hinge: s.hinge, + side: s.side, + dir: s.dir, + width: s.width, + height: s.height, + sill: s.sill, + swingAngle: s.swingAngle, + pos, +}); + +/** + * Vorschau (Kern): Lücken-Balken entlang der Wand + Symbol (Fenster = Mittellinie, Tür = Blatt in + * Schwenkrichtung); `pos` = null projiziert `at` auf die Achse. Liefert dazu die Position. + */ +function posDraftAt(s: OpPos, ctx: CommandContext, pos: number | null, at: Vec2 | null): { draft: ToolDraft; pos: number } { + const pv = createPreview(ctx, openingReq(s, pos), at ? [at] : []); + const [p, from, ax, ay, bx, by, mx, my] = pv.info; + const draft: ToolDraft = { preview: pv.shapes, vertices: [{ x: ax, y: ay }, { x: bx, y: by }] }; draft.hud = { - at: s.cursor ?? mid, + at: s.cursor ?? { x: mx, y: my }, text: `${from.toFixed(2)} m · ${s.kind === "door" ? "Tür" : "Fenster"} ${( s.width * 100 ).toFixed(0)}×${(s.height * 100).toFixed(0)}`, }; - return draft; + return { draft, pos: p }; } -/** Hängt eine Öffnung ans Projekt (immutabel). */ -function appendOpening(s: OpPos, ctx: CommandContext): CoreOp[] { - const len = Math.hypot(s.end.x - s.start.x, s.end.y - s.start.y); - const width = Math.max(0.1, Math.min(s.width, len)); - const position = Math.max(0, Math.min(s.posAlong, Math.max(0, len - width))); - // Standard-Bauteiltyp zuweisen (erster Tür-/Fenstertyp der Bibliothek), damit - // frisch platzierte Öffnungen SOFORT die volle Rahmen-/Laibungs-Darstellung - // (2D + 3D) bekommen — ohne Typ blieben sie ein blosses Loch mit flacher - // Scheibe. Fehlt eine Bibliothek, bleibt es beim Inline-Verhalten (kein Typ). - const typeId = - s.kind === "door" ? ctx.project.doorTypes?.[0]?.id : ctx.project.windowTypes?.[0]?.id; - const opening: Opening = { - id: uniqueId("O"), - type: "opening", - hostWallId: s.wallId, - categoryCode: openingCategory(ctx), - kind: s.kind, - position, - width, - height: s.height, - sillHeight: s.kind === "door" ? 0 : s.sill, - ...(typeId ? { typeId } : {}), - ...(s.kind === "door" - ? { hinge: s.hinge, swing: s.side, openingDir: s.dir, swingAngle: s.swingAngle } - : {}), - }; - return addItems("openings", [opening]); -} +const posDraft = (s: OpPos, ctx: CommandContext): ToolDraft => posDraftAt(s, ctx, s.posAlong, null).draft; + +/** Commit (Kern): Öffnung in die Host-Wand, Breite/Position auf die Wand geklemmt, Standard-Typ der Bibliothek. */ +const appendOpening = (s: OpPos, ctx: CommandContext) => createMutation(ctx, openingReq(s, s.posAlong)); const idle = (from?: OpState): [CommandState, CommandResult] => [ initState(from?.kind ?? "window"), @@ -261,27 +186,26 @@ export const openingCommand: Command = { } else if (input.id === "dir") { next.dir = s.dir === "in" ? "out" : "in"; } - return [next, { draft: next.phase === "pos" ? posDraft(next as OpPos) : null }]; + return [next, { draft: next.phase === "pos" ? posDraft(next as OpPos, ctx) : null }]; } if (input.kind === "number") { // Im Positionsschritt: getippte Zahl = Abstand vom Wandanfang (Meter). if (s.phase === "pos") { const ns: OpPos = { ...s, posAlong: input.value }; - return [ns, { draft: posDraft(ns) }]; + return [ns, { draft: posDraft(ns, ctx) }]; } return [s, { draft: null }]; } if (input.kind !== "point") { - return [s, { draft: s.phase === "pos" ? posDraft(s as OpPos) : null }]; + return [s, { draft: s.phase === "pos" ? posDraft(s as OpPos, ctx) : null }]; } const pt = input.point; if (s.phase === "wall") { const w = pickWall(ctx, pt); if (!w) return [s, { draft: null }]; // kein Treffer: Schritt wiederholen - const proj = projectOntoWall(w, pt); const ns: OpPos = { phase: "pos", lastPoint: pt, @@ -289,7 +213,7 @@ export const openingCommand: Command = { start: w.start, end: w.end, cursor: pt, - posAlong: proj.t, + posAlong: w.t, kind: s.kind, hinge: s.hinge, side: s.side, @@ -299,24 +223,23 @@ export const openingCommand: Command = { sill: s.sill, swingAngle: s.swingAngle, }; - return [ns, { draft: posDraft(ns) }]; + return [ns, { draft: posDraft(ns, ctx) }]; } // Positionsschritt: Klick projiziert auf die Achse → committen. - const proj = projectOntoWall(s, pt); - const ns: OpPos = { ...s, posAlong: proj.t, cursor: pt }; + const ns: OpPos = { ...s, posAlong: posDraftAt(s, ctx, null, pt).pos, cursor: pt }; return [ idle(s)[0], - { draft: null, done: true, commit: opsMutation(() => appendOpening(ns, ctx)) }, + { draft: null, done: true, commit: appendOpening(ns, ctx) }, ]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as OpState; if (s.phase !== "pos") return [s, { draft: null }]; - const proj = projectOntoWall(s, point); - const ns: OpPos = { ...s, posAlong: proj.t, cursor: point }; - return [ns, { draft: posDraft(ns) }]; + const at = posDraftAt({ ...s, cursor: point }, ctx, null, point); + const ns: OpPos = { ...s, posAlong: at.pos, cursor: point }; + return [ns, { draft: at.draft }]; }, onConfirm: (state, ctx): [CommandState, CommandResult] => { @@ -325,7 +248,7 @@ export const openingCommand: Command = { const ns = s; return [ idle(s)[0], - { draft: null, done: true, commit: opsMutation(() => appendOpening(ns, ctx)) }, + { draft: null, done: true, commit: appendOpening(ns, ctx) }, ]; } return idle(s); diff --git a/src/commands/cmds/pointmarker.ts b/src/commands/cmds/pointmarker.ts index 612b5227..84bcea80 100644 --- a/src/commands/cmds/pointmarker.ts +++ b/src/commands/cmds/pointmarker.ts @@ -3,53 +3,29 @@ // Kreuz-in-Kreis-Symbol an genau dieser Stelle, keine weiteren Felder // (analog `detailref.ts`, aber ohne Label/Blattverknüpfung). -import type { Drawing2D } from "../../model/types"; -import { uniqueId } from "../../tools/types"; import type { Command, CommandContext, CommandResult, CommandState, - DraftShape, ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview } from "../createCore"; -const PREVIEW_RADIUS = 0.08; // Modell-Meter, deckt sich mit POINTMARKER_RADIUS_M (plan/drawings.rs) -const PREVIEW_CROSS = 0.12; interface PointMarkerIdle extends CommandState { phase: "point"; } type PointMarkerState = PointMarkerIdle; -function pointDraft(at: Vec2): ToolDraft { - const N = 32; - const pts: Vec2[] = []; - for (let i = 0; i < N; i++) { - const t = (i / N) * Math.PI * 2; - pts.push({ x: at.x + PREVIEW_RADIUS * Math.cos(t), y: at.y + PREVIEW_RADIUS * Math.sin(t) }); - } - const preview: DraftShape[] = [ - { kind: "poly", pts, closed: true }, - { kind: "line", a: { x: at.x - PREVIEW_CROSS, y: at.y }, b: { x: at.x + PREVIEW_CROSS, y: at.y } }, - { kind: "line", a: { x: at.x, y: at.y - PREVIEW_CROSS }, b: { x: at.x, y: at.y + PREVIEW_CROSS } }, - ]; - return { preview, vertices: [at] }; +/** Vorschau (Kern, `cmd_draw.rs`): Kreis (r = 0.08 m) mit Kreuz am Cursor. */ +function pointDraft(ctx: CommandContext, at: Vec2): ToolDraft { + return { preview: createPreview(ctx, { cmd: "pointmarker" }, [at]).shapes, vertices: [at] }; } -function appendPointMarker(at: Vec2, ctx: CommandContext): CoreOp[] { - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "pointmarker", at }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern): Punktmarker am Punkt. */ +const appendPointMarker = (at: Vec2, ctx: CommandContext) => createMutation(ctx, { cmd: "pointmarker", at }); const idle = (): [CommandState, CommandResult] => [ { phase: "point", lastPoint: null } as PointMarkerIdle, @@ -69,11 +45,11 @@ export const pointmarkerCommand: Command = { if (input.kind !== "point") return [s, { draft: null }]; return [ { phase: "point", lastPoint: null } as PointMarkerIdle, - { draft: null, done: true, commit: opsMutation(() => appendPointMarker(input.point, ctx)) }, + { draft: null, done: true, commit: appendPointMarker(input.point, ctx) }, ]; }, - onMove: (state, point): [CommandState, CommandResult] => [state, { draft: pointDraft(point) }], + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => [state, { draft: pointDraft(ctx, point) }], onConfirm: (): [CommandState, CommandResult] => idle(), onCancel: (): [CommandState, CommandResult] => idle(), }; diff --git a/src/commands/cmds/polygon.ts b/src/commands/cmds/polygon.ts index 0bc17917..c055c236 100644 --- a/src/commands/cmds/polygon.ts +++ b/src/commands/cmds/polygon.ts @@ -25,8 +25,7 @@ // 2) „Zweiter Kantenpunkt:" → Punkt → commit. // Ecken-Zahl/Modus/Konstruktion per Option. -import type { Drawing2D } from "../../model/types"; -import { segmentHud, uniqueId } from "../../tools/types"; +import { segmentHud } from "../../tools/types"; import type { CmdOption, Command, @@ -34,13 +33,11 @@ import type { CommandField, CommandResult, CommandState, - DraftShape, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview } from "../createCore"; const EPS = 1e-6; const MIN_SIDES = 3; @@ -95,83 +92,34 @@ const MODE_OPTION: CmdOption = { id: "mode", labelKey: "cmd.polygon.mode" }; * eingegebene Radius das Apothema (Zentrum→Kantenmitte) — der tatsächliche * Eckpunkt-Radius ist grösser, `apothem / cos(π/n)`. */ -function vertexRadius(r: number, sides: number, mode: PolygonMode): number { - return mode === "circumscribed" ? r / Math.cos(Math.PI / sides) : r; -} - -/** Eckpunkte des regelmässigen Vielecks (erste Ecke Richtung `dir`), `r` = eingegebener Radius (Modus-abhängig). */ -function polygonPts(center: Vec2, r: number, sides: number, mode: PolygonMode, dir: Vec2 | null): Vec2[] { - const rv = vertexRadius(r, sides, mode); - const t0 = dir && dist(center, dir) > EPS ? Math.atan2(dir.y - center.y, dir.x - center.x) : 0; - const pts: Vec2[] = []; - for (let i = 0; i < sides; i++) { - const t = t0 + (i / sides) * Math.PI * 2; - pts.push({ x: center.x + rv * Math.cos(t), y: center.y + rv * Math.sin(t) }); - } - return pts; -} +/** Optionen des Vielecks für den Kern (`cmd_draw.rs`). */ +const polyReq = (method: PolygonMethod) => ({ cmd: "polygon", method, sides: lastSides, mode: lastMode }); /** - * Eckpunkte des regelmässigen Vielecks aus einer EINZELNEN Kante `a→b`: die - * Kantenlänge/Richtung legt die Grösse/Drehung eindeutig fest. Läuft von `b` - * aus nach LINKS abbiegend weiter (Aussenwinkel 2π/n je Ecke) — ein - * konvexes, CCW aufgebautes Vieleck auf der linken Seite von a→b. + * Vorschau (Kern): Vieleck um `center` durch den Cursor (Radius = Abstand, erste Ecke in Cursor-Richtung; + * umschrieben: Eckradius r / cos(π/n)) + HUD (Radius × Ecken). */ -function polygonFromEdge(a: Vec2, b: Vec2, sides: number): Vec2[] { - const edgeLen = dist(a, b); - const ext = (2 * Math.PI) / sides; - const pts: Vec2[] = [a, b]; - let cur = b; - let dir = Math.atan2(b.y - a.y, b.x - a.x); - for (let i = 2; i < sides; i++) { - dir += ext; - const next: Vec2 = { x: cur.x + edgeLen * Math.cos(dir), y: cur.y + edgeLen * Math.sin(dir) }; - pts.push(next); - cur = next; - } - return pts; -} - -function polygonDraft(center: Vec2, r: number, dir: Vec2 | null, at: Vec2 | null): ToolDraft { +function polygonDraft(ctx: CommandContext, center: Vec2, cursor: Vec2 | null): ToolDraft { + const pv = createPreview(ctx, polyReq("center"), cursor ? [center, cursor] : [center]); + const r = pv.info[0]; if (r < EPS) return { preview: [], vertices: [center] }; - const preview: DraftShape[] = [ - { kind: "poly", pts: polygonPts(center, r, lastSides, lastMode, dir), closed: true }, - ]; - const draft: ToolDraft = { preview, vertices: [center] }; - if (at) draft.hud = { at, text: `R: ${r.toFixed(3)}m × ${lastSides}` }; + const draft: ToolDraft = { preview: pv.shapes, vertices: [center] }; + if (cursor) draft.hud = { at: cursor, text: `R: ${r.toFixed(3)}m × ${lastSides}` }; return draft; } -/** Vorschau der Kanten-Konstruktion — zeigt das VOLLE Vieleck, sobald die Kante eine Länge hat. */ -function edgeDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { +/** Vorschau (Kern) des Vielecks über der Kante a→Cursor (gegen den Uhrzeigersinn). */ +function edgeDraft(ctx: CommandContext, a: Vec2, cursor: Vec2 | null): ToolDraft { if (!cursor || dist(a, cursor) < EPS) return { preview: [{ kind: "line", a, b: a }], vertices: [a] }; - const pts = polygonFromEdge(a, cursor, lastSides); - return { preview: [{ kind: "poly", pts, closed: true }], vertices: [a], hud: segmentHud(a, cursor) }; + return { preview: createPreview(ctx, polyReq("edge"), [a, cursor]).shapes, vertices: [a], hud: segmentHud(a, cursor) }; } -function appendPolygon(center: Vec2, r: number, dir: Vec2 | null, ctx: CommandContext): CoreOp[] { - if (r < EPS) return []; - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "polyline", pts: polygonPts(center, r, lastSides, lastMode, dir), closed: true }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern): Vieleck um `center`; Radius getippt oder Abstand zu `dir` (entartet → nichts). */ +const appendPolygon = (center: Vec2, r: number | null, dir: Vec2 | null, ctx: CommandContext) => + createMutation(ctx, { ...polyReq("center"), center, r, dir }); -function appendPolygonFromEdge(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] { - if (dist(a, b) < EPS) return []; - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "polyline", pts: polygonFromEdge(a, b, lastSides), closed: true }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern): Vieleck über der Kante a→b. */ +const appendPolygonFromEdge = (a: Vec2, b: Vec2, ctx: CommandContext) => createMutation(ctx, { ...polyReq("edge"), a, b }); const idle = (): [CommandState, CommandResult] => [ { phase: "p1", method: lastMethod, lastPoint: null } as PolyP1, @@ -218,16 +166,14 @@ export const polygonCommand: Command = { if (input.id === "sides") { lastSides = lastSides >= MAX_SIDES ? MIN_SIDES : lastSides + 1; if (s.phase === "radius") { - const r = s.cursor ? dist(s.center, s.cursor) : 0; - return [s, { draft: polygonDraft(s.center, r, s.cursor, s.cursor) }]; + return [s, { draft: polygonDraft(ctx, s.center, s.cursor) }]; } - if (s.phase === "edge2") return [s, { draft: edgeDraft(s.a, s.cursor) }]; + if (s.phase === "edge2") return [s, { draft: edgeDraft(ctx, s.a, s.cursor) }]; return [s, { draft: null }]; } if (input.id === "mode" && s.phase === "radius") { lastMode = nextMode(lastMode); - const r = s.cursor ? dist(s.center, s.cursor) : 0; - return [s, { draft: polygonDraft(s.center, r, s.cursor, s.cursor) }]; + return [s, { draft: polygonDraft(ctx, s.center, s.cursor) }]; } return [s, { draft: null }]; } @@ -236,51 +182,49 @@ export const polygonCommand: Command = { if (input.kind !== "point") return [s, { draft: null }]; if (s.method === "edge") { const ns: PolyEdge2 = { phase: "edge2", method: "edge", a: input.point, cursor: input.point, lastPoint: input.point }; - return [ns, { draft: edgeDraft(input.point, input.point) }]; + return [ns, { draft: edgeDraft(ctx, input.point, input.point) }]; } const ns: PolyRadius = { phase: "radius", method: "center", center: input.point, cursor: input.point, lastPoint: input.point }; - return [ns, { draft: polygonDraft(input.point, 0, null, null) }]; + return [ns, { draft: polygonDraft(ctx, input.point, null) }]; } if (s.phase === "edge2") { if (input.kind !== "point" || dist(s.a, input.point) < EPS) { - return [s, { draft: edgeDraft(s.a, s.cursor) }]; + return [s, { draft: edgeDraft(ctx, s.a, s.cursor) }]; } const a = s.a; const b = input.point; - return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendPolygonFromEdge(a, b, ctx)) }]; + return [idle()[0], { draft: null, done: true, commit: appendPolygonFromEdge(a, b, ctx) }]; } // phase "radius" - let r: number; + let r: number | null; let dir: Vec2 | null; if (input.kind === "number") { r = input.value; dir = s.cursor; } else if (input.kind === "point") { - r = dist(s.center, input.point); + r = null; dir = input.point; } else { - const rr = s.cursor ? dist(s.center, s.cursor) : 0; - return [s, { draft: polygonDraft(s.center, rr, s.cursor, s.cursor) }]; + return [s, { draft: polygonDraft(ctx, s.center, s.cursor) }]; } const center = s.center; return [ idle()[0], - { draft: null, done: true, commit: opsMutation(() => appendPolygon(center, r, dir, ctx)) }, + { draft: null, done: true, commit: appendPolygon(center, r, dir, ctx) }, ]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as PolyState; if (s.phase === "radius") { - const r = dist(s.center, point); const ns: PolyRadius = { ...s, cursor: point }; - return [ns, { draft: polygonDraft(s.center, r, point, point) }]; + return [ns, { draft: polygonDraft(ctx, s.center, point) }]; } if (s.phase === "edge2") { const ns: PolyEdge2 = { ...s, cursor: point }; - return [ns, { draft: edgeDraft(s.a, point) }]; + return [ns, { draft: edgeDraft(ctx, s.a, point) }]; } return [s, { draft: null }]; }, diff --git a/src/commands/cmds/polyline.arcMode.test.ts b/src/commands/cmds/polyline.arcMode.test.ts index 5d3f00fc..29c0522e 100644 --- a/src/commands/cmds/polyline.arcMode.test.ts +++ b/src/commands/cmds/polyline.arcMode.test.ts @@ -12,6 +12,7 @@ import { bulgeArc } from "../../geometry/bulge"; import type { CommandContext, CommandState, Project, Vec2 } from "../types"; const ctx = { + project: sampleProject, level: sampleProject.drawingLevels[0], defaultCategoryCode: sampleProject.layers[0].code, } as CommandContext; diff --git a/src/commands/cmds/polyline.ts b/src/commands/cmds/polyline.ts index ea41cec4..0bfb351f 100644 --- a/src/commands/cmds/polyline.ts +++ b/src/commands/cmds/polyline.ts @@ -18,9 +18,7 @@ // sich dann zwangsläufig aus dem Vorgänger. Das erste Segment hat keine // Tangenten-Referenz und bleibt gerade. -import type { Drawing2D } from "../../model/types"; -import { bulgePolylinePoints, bulgeThroughPoint } from "../../core"; -import { segmentHud, uniqueId } from "../../tools/types"; +import { segmentHud } from "../../tools/types"; import type { Command, CommandContext, @@ -28,12 +26,10 @@ import type { CommandResult, CommandState, CmdOption, - DraftShape, ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview } from "../createCore"; const EPS = 1e-6; const DEG = Math.PI / 180; @@ -58,43 +54,11 @@ function polyNextFromFields(last: Vec2, locks: Record, cursor: V } /** - * Bulge eines Bogens, der in `a` TANGENTIAL an die Richtung `dir` anschliesst - * und in `b` endet. Nach dem Sehnen-Tangenten-Satz ist der Winkel θ VON DER - * SEHNE ZUR TANGENTE die halbe Zentriwinkel-Spanne (θ = Δ/2), und - * `bulge = tan(Δ/4)` — also `tan(θ/2)`. Die Richtung der Winkelmessung ist - * wesentlich: von der Sehne zur Tangente, passend zur Vorzeichenkonvention - * von `bulge` (positiv = Ausbauchung LINKS von a→b). Andersherum gemessen - * läge die Tangente am falschen Bogenende. Ohne Richtung (erstes Segment) - * oder bei entarteter Sehne bleibt es gerade (0). + * Art eines Segments (Index = Segment `points[i] → points[i+1]`): gerade (`0`), Bogen tangential an den + * Vorgänger (`1`) oder Drei-Punkt-Bogen durch einen Durchgangspunkt. Die Bulges (`tan(Δ/4)`, tangential + * aus der Endrichtung des Vorgängers) rechnet der Kern (`cmd_draw.rs`) der Reihe nach. */ -function tangentBulge(a: Vec2, b: Vec2, dir: Vec2 | null): number { - if (!dir) return 0; - const cx = b.x - a.x, cy = b.y - a.y; - const len = Math.hypot(cx, cy); - const dl = Math.hypot(dir.x, dir.y); - if (len < EPS || dl < EPS) return 0; - const ux = cx / len, uy = cy / len; - const dx = dir.x / dl, dy = dir.y / dl; - const theta = Math.atan2(ux * dy - uy * dx, ux * dx + uy * dy); - return Math.tan(theta / 2); -} - -/** Richtung, in der das zuletzt gelegte Segment endet (Tangente für den nächsten Bogen). */ -function lastDirection(points: Vec2[], bulges: number[]): Vec2 | null { - const n = points.length; - if (n < 2) return null; - const a = points[n - 2]; - const b = points[n - 1]; - const bulge = bulges[n - 2] ?? 0; - const chord = { x: b.x - a.x, y: b.y - a.y }; - if (Math.abs(bulge) < EPS) return chord; - // Austritts-Tangente eines Bogens: die Sehne um den halben Zentriwinkel - // gedreht (Δ/2 = 2·atan(bulge)) — am ENDE mit umgekehrtem Vorzeichen wie am - // Anfang (der Bogen ist symmetrisch zur Sehne). - const ang = -2 * Math.atan(bulge); - const c = Math.cos(ang), si = Math.sin(ang); - return { x: chord.x * c - chord.y * si, y: chord.x * si + chord.y * c }; -} +type Seg = 0 | 1 | Vec2; interface PolyIdle extends CommandState { phase: "start"; @@ -108,8 +72,8 @@ interface PolyIdle extends CommandState { interface PolyDrawing extends CommandState { phase: "next"; points: Vec2[]; - /** Bulge je Segment (Index = Segment `points[i] → points[i+1]`), 0 = gerade. */ - bulges: number[]; + /** Art je Segment (s. {@link Seg}). */ + segs: Seg[]; cursor: Vec2 | null; /** Soll der committete Zug als Ring (geschlossen) gelten? Default: offen. */ closed: boolean; @@ -124,21 +88,12 @@ interface PolyDrawing extends CommandState { type PolyState = PolyIdle | PolyDrawing; /** - * Bulge des SCHLUSS-Segments (letzter Punkt → Start), wenn ein Ring ohne - * weiteren Klick geschlossen wird (Option „close" bzw. Ring-Toggle + Enter). - * Ein bereits gesetzter Drei-Punkt-Durchgangspunkt gilt dann für DIESES - * Segment; sonst tangential an den Vorgänger, wie bei jedem anderen Bogen. - * Ohne diesen Eintrag liest der Plan (`plan/drawings.rs`) dort einen fehlenden Bulge (Index - * ausserhalb des Arrays) und zeichnet die Schlusskante immer gerade. + * Art des SCHLUSS-Segments (letzter Punkt → Start), wenn ein Ring ohne weiteren Klick geschlossen wird + * (Option „close" bzw. Ring-Toggle + Enter): ein bereits gesetzter Drei-Punkt-Durchgangspunkt gilt dann + * für DIESES Segment; sonst im Bogen-Modus tangential an den Vorgänger. Ohne diesen Eintrag läse der + * Plan dort einen fehlenden Bulge und zeichnete die Schlusskante immer gerade. */ -function closingBulge(s: PolyDrawing): number { - if (!s.arc) return 0; - const prev = s.points[s.points.length - 1]; - const start = s.points[0]; - return s.pendingThrough - ? bulgeThroughPoint(prev, s.pendingThrough, start) - : tangentBulge(prev, start, lastDirection(s.points, s.bulges)); -} +const closingSeg = (s: PolyDrawing): Seg => (!s.arc ? 0 : (s.pendingThrough ?? 1)); /** Sofort-schließen-Aktion (nur ≥3 Punkte): committet als Ring und beendet. */ const CLOSE: CmdOption = { id: "close", labelKey: "cmd.polyline.close" }; @@ -169,8 +124,9 @@ const tangentOption = (on: boolean): CmdOption => ({ * exakte `bulge` (s. `appendPolyline`). */ function polyDraft( + ctx: CommandContext, points: Vec2[], - bulges: number[], + segs: Seg[], cursor: Vec2 | null, closed = false, arcMode = false, @@ -178,48 +134,26 @@ function polyDraft( pendingThrough: Vec2 | null = null, ): ToolDraft { const all = cursor ? [...points, cursor] : points; + const req = { cmd: "polyline", segs, closed, arc: arcMode, tangent, through: pendingThrough, cursor: !!cursor }; + const draft: ToolDraft = { preview: createPreview(ctx, req, all).shapes, vertices: points }; const last = points[points.length - 1]; - // Vorschau-Bulge des Gummiband-Segments: Drei-Punkt (sobald der - // Durchgangspunkt gesetzt ist), sonst tangential — oder gerade. - const previewBulge = - !cursor || !last || !arcMode - ? 0 - : pendingThrough - ? bulgeThroughPoint(last, pendingThrough, cursor) - : tangent - ? tangentBulge(last, cursor, lastDirection(points, bulges)) - : 0; - const allBulges = cursor ? [...bulges, previewBulge] : bulges; - // Bogen-Segmente für die Vorschau ausrollen. - const pts = bulgePolylinePoints(all, allBulges, false); - // Ring nur ab 3 Punkten zeigen; darunter bleibt die Vorschau offen. - const showClosed = closed && all.length >= 3; - const preview: DraftShape[] = [{ kind: "poly", pts, closed: showClosed }]; - const draft: ToolDraft = { preview, vertices: points }; if (cursor && last && segLen(last, cursor) >= EPS) draft.hud = segmentHud(last, cursor); return draft; } -/** Hängt eine 2D-Polylinie ans Projekt (immutabel). Farbe/Strich erbt die Kategorie. */ -function appendPolyline(pts: Vec2[], - bulges: number[], +/** + * Commit (Kern): 2D-Polylinie aus Punkten und Segment-Arten; `closing` = Art des Schluss-Segments + * (geschlossen), `closingEnd` = sein Endpunkt, falls ein Klick nahe dem Start schloss. Farbe/Strich erbt + * die Kategorie. + */ +const appendPolyline = ( + pts: Vec2[], + segs: Seg[], + closing: Seg | null, closed: boolean, ctx: CommandContext, -): CoreOp[] { - // `bulge` nur mitschreiben, wenn wirklich ein Bogen dabei ist — ein reiner - // Geradenzug bleibt damit bitgleich zu vorher (additives Feld). - const hasArc = bulges.some((b) => Math.abs(b) > EPS); - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: hasArc - ? { shape: "polyline", pts, closed, bulge: bulges.slice(0, closed ? pts.length : pts.length - 1) } - : { shape: "polyline", pts, closed }, - }; - return addItems("drawings2d", [d]); -} + closingEnd: Vec2 | null = null, +) => createMutation(ctx, { cmd: "polyline", pts, segs, closing, closingEnd, closed }); /** Ruhezustand; behält den zuletzt gewählten Schließ-Modus bei. */ const idle = (closed = false, arc = false, tangent = false): [CommandState, CommandResult] => [ @@ -273,7 +207,7 @@ export const polylineCommand: Command = { { draft: s.phase === "next" - ? polyDraft(s.points, s.bulges, s.cursor, ns.closed, ns.arc, ns.tangent, null) + ? polyDraft(ctx, s.points, s.segs, s.cursor, ns.closed, ns.arc, ns.tangent, null) : null, }, ]; @@ -283,10 +217,10 @@ export const polylineCommand: Command = { // Wartet ein Durchgangspunkt, nimmt „Zurück" zuerst diesen zurück. if (s.pendingThrough) { const ns: PolyDrawing = { ...s, pendingThrough: null }; - return [ns, { draft: polyDraft(s.points, s.bulges, s.cursor, s.closed, s.arc, s.tangent, null) }]; + return [ns, { draft: polyDraft(ctx, s.points, s.segs, s.cursor, s.closed, s.arc, s.tangent, null) }]; } const pts = s.points.slice(0, -1); - const bulges = s.bulges.slice(0, Math.max(0, pts.length - 1)); + const segs = s.segs.slice(0, Math.max(0, pts.length - 1)); if (pts.length === 0) return [ { phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle, @@ -295,7 +229,7 @@ export const polylineCommand: Command = { const ns: PolyDrawing = { phase: "next", points: pts, - bulges, + segs, cursor: s.cursor, lastPoint: pts[pts.length - 1], closed: s.closed, @@ -303,20 +237,21 @@ export const polylineCommand: Command = { tangent: s.tangent, pendingThrough: null, }; - return [ns, { draft: polyDraft(pts, bulges, s.cursor, s.closed, s.arc, s.tangent, null) }]; + return [ns, { draft: polyDraft(ctx, pts, segs, s.cursor, s.closed, s.arc, s.tangent, null) }]; } // Sofort schließen: committet als Ring (unabhängig vom Toggle-Zustand). if (input.id === "close" && s.points.length >= 3) { const pts = s.points; - const bl = [...s.bulges, closingBulge(s)]; + const segs = s.segs; + const closing = closingSeg(s); return [ { phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle, - { draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, bl, true, ctx)) }, + { draft: null, done: true, commit: appendPolyline(pts, segs, closing, true, ctx) }, ]; } return [ s, - { draft: polyDraft(s.points, s.bulges, s.cursor, s.closed, s.arc, s.tangent, s.pendingThrough) }, + { draft: polyDraft(ctx, s.points, s.segs, s.cursor, s.closed, s.arc, s.tangent, s.pendingThrough) }, ]; } @@ -326,7 +261,7 @@ export const polylineCommand: Command = { { draft: s.phase === "next" - ? polyDraft(s.points, s.bulges, s.cursor, s.closed, s.arc, s.tangent, s.pendingThrough) + ? polyDraft(ctx, s.points, s.segs, s.cursor, s.closed, s.arc, s.tangent, s.pendingThrough) : null, }, ]; @@ -336,7 +271,7 @@ export const polylineCommand: Command = { const ns: PolyDrawing = { phase: "next", points: [pt], - bulges: [], + segs: [], cursor: pt, lastPoint: pt, closed: s.closed, @@ -344,22 +279,17 @@ export const polylineCommand: Command = { tangent: s.tangent, pendingThrough: null, }; - return [ns, { draft: polyDraft([pt], [], pt, s.closed, s.arc, s.tangent, null) }]; + return [ns, { draft: polyDraft(ctx, [pt], [], pt, s.closed, s.arc, s.tangent, null) }]; } // Drei-Punkt-Bogen: der ERSTE Klick setzt nur den Durchgangspunkt; das // Segment entsteht erst mit dem zweiten Klick (Endpunkt). if (s.arc && !s.tangent && !s.pendingThrough) { const ns: PolyDrawing = { ...s, pendingThrough: pt, cursor: pt }; - return [ns, { draft: polyDraft(s.points, s.bulges, pt, s.closed, s.arc, s.tangent, pt) }]; + return [ns, { draft: polyDraft(ctx, s.points, s.segs, pt, s.closed, s.arc, s.tangent, pt) }]; } // Bulge des neuen Segments: Drei-Punkt (über den gesetzten Durchgangspunkt) // oder tangential an den Vorgänger. - const prev = s.points[s.points.length - 1]; - const newBulge = !s.arc - ? 0 - : s.pendingThrough - ? bulgeThroughPoint(prev, s.pendingThrough, pt) - : tangentBulge(prev, pt, lastDirection(s.points, s.bulges)); + const newSeg: Seg = !s.arc ? 0 : (s.pendingThrough ?? 1); // Klick nahe Startpunkt → schließen (committet als Ring). `newBulge` ist // bereits die korrekte Krümmung des Schluss-Segments (prev→pt, genau wie // die Vorschau in `polyDraft` sie zeigt) — MUSS mit angehängt werden, @@ -367,18 +297,18 @@ export const polylineCommand: Command = { // schliesst immer gerade, obwohl die Vorschau eben noch den Bogen zeigte. if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) { const pts = s.points; - const bl = [...s.bulges, newBulge]; + const segs = s.segs; return [ { phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle, - { draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, bl, true, ctx)) }, + { draft: null, done: true, commit: appendPolyline(pts, segs, newSeg, true, ctx, pt) }, ]; } const points = [...s.points, pt]; - const bulges = [...s.bulges, newBulge]; + const segs = [...s.segs, newSeg]; const ns: PolyDrawing = { phase: "next", points, - bulges, + segs, cursor: pt, lastPoint: pt, closed: s.closed, @@ -386,16 +316,16 @@ export const polylineCommand: Command = { tangent: s.tangent, pendingThrough: null, }; - return [ns, { draft: polyDraft(points, bulges, pt, s.closed, s.arc, s.tangent, null) }]; + return [ns, { draft: polyDraft(ctx, points, segs, pt, s.closed, s.arc, s.tangent, null) }]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as PolyState; if (s.phase !== "next") return [s, { draft: null }]; const ns: PolyDrawing = { ...s, cursor: point }; return [ ns, - { draft: polyDraft(s.points, s.bulges, point, s.closed, s.arc, s.tangent, s.pendingThrough) }, + { draft: polyDraft(ctx, s.points, s.segs, point, s.closed, s.arc, s.tangent, s.pendingThrough) }, ]; }, @@ -407,10 +337,10 @@ export const polylineCommand: Command = { if (s.phase === "next" && s.points.length >= 2) { const pts = s.points; const close = s.closed && pts.length >= 3; - const bl = close ? [...s.bulges, closingBulge(s)] : s.bulges; + const closing = close ? closingSeg(s) : null; return [ { phase: "start", lastPoint: null, closed: s.closed, arc: s.arc, tangent: s.tangent } as PolyIdle, - { draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, bl, close, ctx)) }, + { draft: null, done: true, commit: appendPolyline(pts, s.segs, closing, close, ctx) }, ]; } return idle(s.closed, s.arc, s.tangent); diff --git a/src/commands/cmds/ray.ts b/src/commands/cmds/ray.ts index dc4e66ed..6fd57dd3 100644 --- a/src/commands/cmds/ray.ts +++ b/src/commands/cmds/ray.ts @@ -5,8 +5,7 @@ // 1) „Anker:" → Punkt // 2) „Richtungspunkt:" → Punkt (Tab-Felder Länge/Winkel wie bei Line) → commit -import type { Drawing2D } from "../../model/types"; -import { segmentHud, uniqueId } from "../../tools/types"; +import { segmentHud } from "../../tools/types"; import type { Command, CommandContext, @@ -17,12 +16,10 @@ import type { ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview } from "../createCore"; const EPS = 1e-6; const DEG = Math.PI / 180; -const RAY_PREVIEW_EXT_M = 30; // nur für die Live-Vorschau — echte Länge kommt aus generatePlan const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); const segAngleDeg = (a: Vec2, b: Vec2): number => (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI; @@ -51,33 +48,16 @@ interface RayDrawing extends CommandState { type RayState = RayIdle | RayDrawing; /** Vorschau: kurzes Segment PLUS Verlängerung NUR über den Cursor hinaus (Anker bleibt fest). */ -function rayDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { - const preview: DraftShape[] = []; - if (cursor && segLen(a, cursor) >= EPS) { - const len = segLen(a, cursor); - const ux = (cursor.x - a.x) / len; - const uy = (cursor.y - a.y) / len; - preview.push({ - kind: "line", - a, - b: { x: cursor.x + ux * RAY_PREVIEW_EXT_M, y: cursor.y + uy * RAY_PREVIEW_EXT_M }, - }); - } +function rayDraft(ctx: CommandContext, a: Vec2, cursor: Vec2 | null): ToolDraft { + // Vorschau (Kern): einseitig um 30 m verlängert — die echte Länge kommt aus der Plan-Ableitung. + const preview: DraftShape[] = cursor ? createPreview(ctx, { cmd: "ray" }, [a, cursor]).shapes : []; const draft: ToolDraft = { preview, vertices: [a] }; if (cursor && segLen(a, cursor) >= EPS) draft.hud = segmentHud(a, cursor); return draft; } -function appendRay(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] { - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "ray", a, b }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern, `cmd_draw.rs`): Strahl durch a, b. */ +const appendRay = (a: Vec2, b: Vec2, ctx: CommandContext) => createMutation(ctx, { cmd: "ray", a, b }); export const rayCommand: Command = { name: "ray", @@ -89,11 +69,11 @@ export const rayCommand: Command = { onInput: (state, input, ctx): [CommandState, CommandResult] => { const s = state as RayState; - if (input.kind !== "point") return [s, { draft: s.phase === "end" ? rayDraft(s.a, s.cursor) : null }]; + if (input.kind !== "point") return [s, { draft: s.phase === "end" ? rayDraft(ctx, s.a, s.cursor) : null }]; const pt = input.point; if (s.phase !== "end") { const next: RayDrawing = { phase: "end", a: pt, cursor: pt, lastPoint: pt }; - return [next, { draft: rayDraft(pt, pt) }]; + return [next, { draft: rayDraft(ctx, pt, pt) }]; } if (segLen(s.a, pt) < EPS) { return [{ phase: "start", lastPoint: null }, { draft: null, done: true }]; @@ -101,15 +81,15 @@ export const rayCommand: Command = { const a = s.a; return [ { phase: "start", lastPoint: null }, - { draft: null, done: true, commit: opsMutation(() => appendRay(a, pt, ctx)) }, + { draft: null, done: true, commit: appendRay(a, pt, ctx) }, ]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as RayState; if (s.phase !== "end") return [s, { draft: null }]; const next: RayDrawing = { ...s, cursor: point }; - return [next, { draft: rayDraft(s.a, point) }]; + return [next, { draft: rayDraft(ctx, s.a, point) }]; }, onConfirm: (): [CommandState, CommandResult] => [ diff --git a/src/commands/cmds/rect.ts b/src/commands/cmds/rect.ts index 8eec65bd..c5c3edb4 100644 --- a/src/commands/cmds/rect.ts +++ b/src/commands/cmds/rect.ts @@ -29,10 +29,7 @@ // s. `model/types.ts`). Radius wird auf die halbe kürzere Kantenlänge // geklammert (sonst würden sich benachbarte Fillets überlappen). -import type { Drawing2D } from "../../model/types"; -import { deltaHud, segmentHud, uniqueId } from "../../tools/types"; -import { filletCorner } from "../../core"; -import { bulgePolylinePoints, bulgeThroughPoint } from "../../core"; +import { deltaHud, segmentHud } from "../../tools/types"; import type { Command, CommandContext, @@ -40,13 +37,11 @@ import type { CommandResult, CommandState, CmdOption, - DraftShape, ToolDraft, Vec2, } from "../types"; import type { TranslationKey } from "../../i18n"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview } from "../createCore"; const EPS = 1e-6; @@ -119,25 +114,6 @@ function baseFromFields(a: Vec2, locks: Record, cursor: Vec2 | n return { x: a.x + Math.cos(ang) * length, y: a.y + Math.sin(ang) * length }; } -/** - * Vier Ecken des gedrehten Rechtecks aus Basiskante (a→b) und einem dritten - * Punkt `p`: die Höhe ist der vorzeichenbehaftete senkrechte Abstand von `p` zur - * Basislinie; das Rechteck wird zu dieser Seite hin aufgespannt. - */ -function rotatedCorners(a: Vec2, b: Vec2, p: Vec2): Vec2[] { - const dx = b.x - a.x; - const dy = b.y - a.y; - const len = Math.hypot(dx, dy); - if (len < EPS) return [a, b, b, a]; - // Einheits-Normale (links der Basisrichtung). - const nx = -dy / len; - const ny = dx / len; - const h = (p.x - a.x) * nx + (p.y - a.y) * ny; // signierte Höhe - const c3 = { x: b.x + nx * h, y: b.y + ny * h }; - const c4 = { x: a.x + nx * h, y: a.y + ny * h }; - return [a, b, c3, c4]; -} - /** Senkrechter (signierter) Abstand eines Punktes zur Basislinie a→b. */ function riseFrom(a: Vec2, b: Vec2, p: Vec2): number { const dx = b.x - a.x; @@ -163,16 +139,6 @@ function riseToPoint(a: Vec2, b: Vec2, height: number, cursor: Vec2 | null): Vec // ── Zentrum: Ecke aus Mittelpunkt ──────────────────────────────────────────── -/** Achsparallele Ecken aus Zentrum + einer Ecke. */ -function centerGeom(center: Vec2, corner: Vec2): { min: Vec2; max: Vec2 } { - const hx = Math.abs(corner.x - center.x); - const hy = Math.abs(corner.y - center.y); - return { - min: { x: center.x - hx, y: center.y - hy }, - max: { x: center.x + hx, y: center.y + hy }, - }; -} - /** Ecke aus Zentrum + gelockten Halbmaßen (width/height als volle Kantenmaße). */ function centerCornerFromFields( center: Vec2, @@ -210,87 +176,36 @@ interface RectRise extends CommandState { } type RectState = RectIdle | RectCorner2 | RectRise; -function rectGeom(a: Vec2, b: Vec2): { min: Vec2; max: Vec2 } { - return { - 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) }, - }; -} - -// ── Eck-Radius ─────────────────────────────────────────────────────────────── - -/** - * Rundet die 4 Ecken eines Rechtecks (beliebige Umlaufreihenfolge/Ausrichtung - * — arbeitet rein über die tatsächliche Punkt-Geometrie, keine Achsparallel- - * Annahme) mit Radius `r`, geklammert auf die halbe kürzeste Kantenlänge - * (sonst würden sich benachbarte Fillets überlappen). `null` bei `r<=0` oder - * wenn selbst der geklammerte Radius nicht mehr passt (entartetes Rechteck). - */ -function roundedRectPts(corners: Vec2[], r: number): { pts: Vec2[]; bulge: number[] } | null { - if (r < EPS) return null; - const n = corners.length; - let maxR = Infinity; - for (let i = 0; i < n; i++) { - maxR = Math.min(maxR, segLen(corners[i], corners[(i + 1) % n]) / 2); - } - const rr = Math.min(r, maxR - EPS); - if (rr < EPS) return null; - - const pts: Vec2[] = []; - const bulge: number[] = []; - for (let i = 0; i < n; i++) { - const prev = corners[(i - 1 + n) % n]; - const cur = corners[i]; - const next = corners[(i + 1) % n]; - const f = filletCorner(cur, prev, next, rr); - if (!f) return null; // (nahezu) kollineare Ecke — sollte bei einem Rechteck nicht vorkommen - // Bogen-Mittelpunkt: auf dem Fillet-Kreis, in Richtung der ursprünglichen - // (jetzt weggerundeten) Ecke vom Bogen-Zentrum aus gesehen. - const dx = cur.x - f.center.x; - const dy = cur.y - f.center.y; - const dl = Math.hypot(dx, dy) || 1; - const mid: Vec2 = { x: f.center.x + (dx / dl) * rr, y: f.center.y + (dy / dl) * rr }; - pts.push(f.tangentA, f.tangentB); - bulge.push(bulgeThroughPoint(f.tangentA, mid, f.tangentB), 0); - } - return { pts, bulge }; -} - -/** Tessellierte Punkte einer gerundeten geschlossenen Kontur — für die Live-Vorschau. */ -function tessellateRounded(pts: Vec2[], bulge: number[]): Vec2[] { - return bulgePolylinePoints(pts, bulge, true); -} - // ── Vorschau ───────────────────────────────────────────────────────────────── -function corners4Draft(pts: Vec2[], hud: ToolDraft["hud"] | null): ToolDraft { - const rounded = roundedRectPts(pts, lastRadius); - const previewPts = rounded ? tessellateRounded(rounded.pts, rounded.bulge) : pts; - const preview: DraftShape[] = [{ kind: "poly", pts: previewPts, closed: true }]; - const draft: ToolDraft = { preview, vertices: [pts[0]] }; +/** + * Vorschau eines Rechtecks im Kern (`cmd_draw.rs`): Ecken (bei Eck-Radius > 0 gerundet tesselliert); + * der erste Stützpunkt ist die erste Ecke der Kontur. + */ +function cornersDraft(ctx: CommandContext, method: RectMethod, pts: Vec2[], hud: ToolDraft["hud"] | null): { draft: ToolDraft; height: number } { + const pv = createPreview(ctx, { cmd: "rect", method, radius: lastRadius }, pts); + const draft: ToolDraft = { preview: pv.shapes, vertices: [{ x: pv.info[0], y: pv.info[1] }] }; if (hud) draft.hud = hud; - return draft; + return { draft, height: pv.info[2] }; } /** Vorschau des 2-Punkt-Rechtecks (achsparallel) — HUD zeigt die Diagonale a→cursor. */ -function cornerDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { +function cornerDraft(ctx: CommandContext, a: Vec2, cursor: Vec2 | null): ToolDraft { if (!cursor) return { preview: [], vertices: [a] }; - const g = rectGeom(a, cursor); - const pts: Vec2[] = [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }]; - return corners4Draft(pts, segLen(a, cursor) >= EPS ? deltaHud(a, cursor) : null); + return cornersDraft(ctx, "corner", [a, cursor], segLen(a, cursor) >= EPS ? deltaHud(a, cursor) : null).draft; } /** Vorschau des Zentrum-Rechtecks (achsparallel) — HUD zeigt die Diagonale center→cursor. */ -function centerDraft(center: Vec2, cursor: Vec2 | null): ToolDraft { +function centerDraft(ctx: CommandContext, center: Vec2, cursor: Vec2 | null): ToolDraft { if (!cursor) return { preview: [], vertices: [center] }; - const g = centerGeom(center, cursor); - const pts: Vec2[] = [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }]; - return corners4Draft( - pts, + return cornersDraft( + ctx, + "center", + [center, cursor], segLen(center, cursor) >= EPS ? { at: cursor, dx: 2 * (cursor.x - center.x), dy: 2 * (cursor.y - center.y) } : null, - ); + ).draft; } /** Vorschau der Basiskante (3-Punkt, erster Teil). */ @@ -300,69 +215,23 @@ function baseDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { } /** Vorschau des gedrehten Rechtecks (3-Punkt, zweiter Teil) — HUD: Basisbreite + Höhe am Cursor. */ -function riseDraft(a: Vec2, b: Vec2, cursor: Vec2 | null): ToolDraft { +function riseDraft(ctx: CommandContext, a: Vec2, b: Vec2, cursor: Vec2 | null): ToolDraft { if (!cursor) return { preview: [{ kind: "line", a, b }], vertices: [a] }; - const pts = rotatedCorners(a, b, cursor); + const r = cornersDraft(ctx, "three", [a, b, cursor], null); const w = segLen(a, b); - const h = Math.abs(riseFrom(a, b, cursor)); - return corners4Draft(pts, { at: cursor, text: `B: ${w.toFixed(3)}m H: ${h.toFixed(3)}m` }); + r.draft.hud = { at: cursor, text: `B: ${w.toFixed(3)}m H: ${r.height.toFixed(3)}m` }; + return r.draft; } // ── Commit ─────────────────────────────────────────────────────────────────── -/** Achsparalleles Rechteck als `shape:"rect"` (geschlossen behandelt). */ -function appendRect(min: Vec2, max: Vec2, ctx: CommandContext): CoreOp[] { - if (max.x - min.x < EPS || max.y - min.y < EPS) return []; // Null-Rechteck - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "rect", min, max }, - }; - return addItems("drawings2d", [d]); -} - /** - * Gedrehtes Rechteck als geschlossene Polylinie (`shape:"polyline", closed:true`) - * — `shape:"rect"` kann nur achsparallel, deshalb hier ein Ring aus vier Ecken. - * Downstream (Füllung/Offset) behandelt einen geschlossenen Polygonzug als Ring. + * Commit (Kern, `cmd_draw.rs`): 2-Punkt/Zentrum achsparallel als `shape:"rect"`, 3-Punkt als + * geschlossene Polylinie; mit Eck-Radius > 0 (geklammert auf die halbe kürzeste Kante) als geschlossene + * Polylinie mit Bögen. Entartete Rechtecke ergeben nichts. */ -function appendRotated(pts: Vec2[], ctx: CommandContext): CoreOp[] { - // Fläche prüfen: entartete Rechtecke verwerfen. - const w = segLen(pts[0], pts[1]); - const h = segLen(pts[1], pts[2]); - if (w < EPS || h < EPS) return []; - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "polyline", pts, closed: true }, - }; - return addItems("drawings2d", [d]); -} - -/** - * Gerundetes Rechteck (Eck-Radius > 0) als geschlossene `polyline` MIT - * `bulge` — ersetzt `appendRect`/`appendRotated`, wenn `lastRadius` > 0 ist, - * unabhängig von der Konstruktionsmethode (`corners` sind die 4 scharfen - * Ecken, egal ob achsparallel oder gedreht). No-Op, wenn der Radius nicht - * passt (`roundedRectPts` liefert dann `null`, z. B. bei einem entarteten - * Rechteck). - */ -function appendRectRounded(corners: Vec2[], ctx: CommandContext): CoreOp[] { - const rr = roundedRectPts(corners, lastRadius); - if (!rr) return []; - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "polyline", pts: rr.pts, closed: true, bulge: rr.bulge }, - }; - return addItems("drawings2d", [d]); -} +const appendRect = (ctx: CommandContext, method: RectMethod, a: Vec2, b: Vec2, c: Vec2 | null = null) => + createMutation(ctx, { cmd: "rect", method, a, b, c, radius: lastRadius }); const idle = (method: RectMethod): [CommandState, CommandResult] => [ { phase: "corner1", lastPoint: null, method } as RectIdle, @@ -404,13 +273,13 @@ export const rectCommand: Command = { // Konstruktion NICHT verworfen, nur die Vorschau aktualisiert (der // Radius wirkt erst beim Commit, betrifft also keine Punkt-Historie). lastRadius = nextRadius(); - return [s, { draft: draftFor(s) }]; + return [s, { draft: draftFor(ctx, s) }]; } return [s, { draft: null }]; } if (input.kind !== "point") { - return [s, { draft: draftFor(s) }]; + return [s, { draft: draftFor(ctx, s) }]; } const pt = input.point; @@ -420,7 +289,7 @@ export const rectCommand: Command = { return [ns, { draft: baseDraft(pt, pt) }]; } const ns: RectCorner2 = { phase: "corner2", method: s.method, a: pt, cursor: pt, lastPoint: pt }; - return [ns, { draft: draftFor(ns) }]; + return [ns, { draft: draftFor(ctx, ns) }]; } if (s.phase === "corner2") { @@ -428,7 +297,7 @@ export const rectCommand: Command = { // Basiskante gesetzt → dritter Punkt bestimmt Höhe. if (segLen(s.a, pt) < EPS) return [s, { draft: baseDraft(s.a, s.cursor) }]; const ns: RectRise = { phase: "rise", method: "three", a: s.a, b: pt, cursor: pt, lastPoint: pt }; - return [ns, { draft: riseDraft(s.a, pt, pt) }]; + return [ns, { draft: riseDraft(ctx, s.a, pt, pt) }]; } const a = s.a; const method = s.method; @@ -437,14 +306,7 @@ export const rectCommand: Command = { { draft: null, done: true, - commit: opsMutation(() => { - const g = method === "center" ? centerGeom(a, pt) : rectGeom(a, pt); - if (lastRadius >= EPS) { - const corners = [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }]; - return appendRectRounded(corners, ctx); - } - return appendRect(g.min, g.max, ctx); - }), + commit: appendRect(ctx, method, a, pt), }, ]; } @@ -457,19 +319,16 @@ export const rectCommand: Command = { { draft: null, done: true, - commit: opsMutation(() => { - const corners = rotatedCorners(a, b, pt); - return lastRadius >= EPS ? appendRectRounded(corners, ctx) : appendRotated(corners, ctx); - }), + commit: appendRect(ctx, "three", a, b, pt), }, ]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as RectState; if (s.phase === "corner1") return [s, { draft: null }]; const ns = { ...s, cursor: point } as RectState; - return [ns, { draft: draftFor(ns) }]; + return [ns, { draft: draftFor(ctx, ns) }]; }, onConfirm: (state): [CommandState, CommandResult] => idle((state as RectState).method), @@ -514,12 +373,12 @@ export const rectCommand: Command = { }; /** Vorschau passend zum Zustand. */ -function draftFor(s: RectState): ToolDraft { +function draftFor(ctx: CommandContext, s: RectState): ToolDraft { if (s.phase === "corner2") { if (s.method === "three") return baseDraft(s.a, s.cursor); - if (s.method === "center") return centerDraft(s.a, s.cursor); - return cornerDraft(s.a, s.cursor); + if (s.method === "center") return centerDraft(ctx, s.a, s.cursor); + return cornerDraft(ctx, s.a, s.cursor); } - if (s.phase === "rise") return riseDraft(s.a, s.b, s.cursor); + if (s.phase === "rise") return riseDraft(ctx, s.a, s.b, s.cursor); return { preview: [], vertices: [] }; } diff --git a/src/commands/cmds/revcloud.ts b/src/commands/cmds/revcloud.ts index bc65d3d1..8c621986 100644 --- a/src/commands/cmds/revcloud.ts +++ b/src/commands/cmds/revcloud.ts @@ -1,6 +1,6 @@ // Revisionswolke (Nutzer-Wunsch: „Keine Revisionswolken/Markup-Werkzeuge"). // Schritte (wie `polyline.ts`, aber ohne dessen Bogen-/Tangenten-Unteroptionen -// — JEDES Segment wird automatisch zu Beulen, s. `geometry/revisionCloud.ts`): +// — JEDES Segment wird automatisch zu Beulen, s. `cmd_draw.rs::revision_cloud`): // 1) „Startpunkt:" → Punkt // 2) „Nächster Punkt ( Schliessen ):" → Punkt … Enter beendet OFFEN (≥2 // Punkte); Klick nahe dem Startpunkt ODER die Option „Schliessen" @@ -8,22 +8,17 @@ // Beulengrösse (Ziel-Bogenlänge) per Option, zyklisch, persistiert über // Aufrufe hinweg (wie `lastSides` bei `polygon.ts`). -import type { Drawing2D } from "../../model/types"; -import { bulgePolylinePoints } from "../../core"; -import { revisionCloudPts } from "../../core"; -import { segmentHud, uniqueId } from "../../tools/types"; +import { segmentHud } from "../../tools/types"; import type { CmdOption, Command, CommandContext, CommandResult, CommandState, - DraftShape, ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview } from "../createCore"; const EPS = 1e-6; const CLOSE_HIT = 0.15; // Modell-Meter: Klick nahe Startpunkt schliesst den Zug @@ -49,32 +44,18 @@ interface RevcloudDrawing extends CommandState { type RevcloudState = RevcloudIdle | RevcloudDrawing; /** Vorschau: die tatsächliche Beulen-Kontur (tesselliert), inkl. Gummiband zum Cursor. */ -function revcloudDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { +function revcloudDraft(ctx: CommandContext, points: Vec2[], cursor: Vec2 | null): ToolDraft { + // Beulen-Kontur im Kern (`cmd_draw.rs`): je Segment gleich lange Bögen der Ziel-Bogenlänge, tesselliert. const all = cursor ? [...points, cursor] : points; - const expanded = revisionCloudPts(all, false, lastArcSize); - const pts: Vec2[] = []; - if (expanded) { - pts.push(...bulgePolylinePoints(expanded.pts, expanded.bulge, false)); - } - const preview: DraftShape[] = [{ kind: "poly", pts, closed: false }]; - const draft: ToolDraft = { preview, vertices: points }; + const draft: ToolDraft = { preview: createPreview(ctx, { cmd: "revcloud", arcSize: lastArcSize }, all).shapes, vertices: points }; const last = points[points.length - 1]; if (cursor && last && segLen(last, cursor) >= EPS) draft.hud = segmentHud(last, cursor); return draft; } -function appendRevcloud(points: Vec2[], closed: boolean, ctx: CommandContext): CoreOp[] { - const expanded = revisionCloudPts(points, closed, lastArcSize); - if (!expanded) return []; - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "polyline", pts: expanded.pts, closed, bulge: expanded.bulge }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern): Revisionswolke als Polylinie mit Bögen (weniger als 2 Punkte → nichts). */ +const appendRevcloud = (points: Vec2[], closed: boolean, ctx: CommandContext) => + createMutation(ctx, { cmd: "revcloud", pts: points, closed, arcSize: lastArcSize }); const idle = (): [CommandState, CommandResult] => [ { phase: "start", lastPoint: null } as RevcloudIdle, @@ -101,41 +82,41 @@ export const revcloudCommand: Command = { lastArcSize = nextArcSize(); return [ s, - { draft: s.phase === "next" ? revcloudDraft(s.points, s.cursor) : null }, + { draft: s.phase === "next" ? revcloudDraft(ctx, s.points, s.cursor) : null }, ]; } if (input.id === "close" && s.phase === "next" && s.points.length >= 3) { const pts = s.points; - return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendRevcloud(pts, true, ctx)) }]; + return [idle()[0], { draft: null, done: true, commit: appendRevcloud(pts, true, ctx) }]; } return [s, { draft: null }]; } if (input.kind !== "point") { - return [s, { draft: s.phase === "next" ? revcloudDraft(s.points, s.cursor) : null }]; + return [s, { draft: s.phase === "next" ? revcloudDraft(ctx, s.points, s.cursor) : null }]; } const pt = input.point; if (s.phase !== "next") { const ns: RevcloudDrawing = { phase: "next", points: [pt], cursor: pt, lastPoint: pt }; - return [ns, { draft: revcloudDraft([pt], pt) }]; + return [ns, { draft: revcloudDraft(ctx, [pt], pt) }]; } // Klick nahe Startpunkt (≥3 Punkte) → schliessen (committet als Ring). if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) { const pts = s.points; - return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendRevcloud(pts, true, ctx)) }]; + return [idle()[0], { draft: null, done: true, commit: appendRevcloud(pts, true, ctx) }]; } const points = [...s.points, pt]; const ns: RevcloudDrawing = { phase: "next", points, cursor: pt, lastPoint: pt }; - return [ns, { draft: revcloudDraft(points, pt) }]; + return [ns, { draft: revcloudDraft(ctx, points, pt) }]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as RevcloudState; if (s.phase !== "next") return [s, { draft: null }]; const ns: RevcloudDrawing = { ...s, cursor: point }; - return [ns, { draft: revcloudDraft(s.points, point) }]; + return [ns, { draft: revcloudDraft(ctx, s.points, point) }]; }, // Enter/Space/Rechtsklick: Zug als OFFENE Wolke beenden (≥2 Punkte). @@ -143,7 +124,7 @@ export const revcloudCommand: Command = { const s = state as RevcloudState; if (s.phase === "next" && s.points.length >= 2) { const pts = s.points; - return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendRevcloud(pts, false, ctx)) }]; + return [idle()[0], { draft: null, done: true, commit: appendRevcloud(pts, false, ctx) }]; } return idle(); }, diff --git a/src/commands/cmds/roof.ts b/src/commands/cmds/roof.ts index beda8d4a..4cf91d92 100644 --- a/src/commands/cmds/roof.ts +++ b/src/commands/cmds/roof.ts @@ -11,23 +11,17 @@ // • floorId ← ctx.level.id (aktives Geschoss) // • categoryCode← "35" (Ebene „Dächer"; Fallback ctx.defaultCategoryCode) -import type { Roof, RoofShape } from "../../model/types"; -import { uniqueId } from "../../tools/types"; +import type { RoofShape } from "../../model/types"; import type { Command, CommandContext, CommandResult, CommandState, CmdOption, - DraftShape, ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; - -/** Default-Ebene (Kategorie) für Dächer („31 Dächer"). */ -const ROOF_CATEGORY = "31"; +import { createMutation, createPreview, xy } from "../createCore"; /** Wählbare Dachformen (Inline-Optionen der Befehlszeile). */ const SHAPE_OPTIONS: CmdOption[] = [ @@ -40,33 +34,6 @@ const SHAPE_OPTIONS: CmdOption[] = [ ]; const SHAPE_IDS = new Set(SHAPE_OPTIONS.map((o) => o.id)); -/** Existiert die Dach-Kategorie („35")? Sonst Fallback auf die aktive Kategorie. */ -function roofCategory(ctx: CommandContext): string { - const flat: string[] = []; - const walk = (list: { code: string; children?: unknown[] }[]) => { - for (const c of list) { - flat.push(c.code); - if (c.children) walk(c.children as { code: string; children?: unknown[] }[]); - } - }; - walk(ctx.project.layers as { code: string; children?: unknown[] }[]); - return flat.includes(ROOF_CATEGORY) ? ROOF_CATEGORY : ctx.defaultCategoryCode; -} - -/** Vier Eckpunkte eines Rechtecks aus zwei Gegenecken (CCW). */ -function rectCorners(a: Vec2, b: Vec2): Vec2[] { - const x0 = Math.min(a.x, b.x); - const x1 = Math.max(a.x, b.x); - const y0 = Math.min(a.y, b.y); - const y1 = Math.max(a.y, b.y); - return [ - { x: x0, y: y0 }, - { x: x1, y: y0 }, - { x: x1, y: y1 }, - { x: x0, y: y1 }, - ]; -} - interface RoofIdle extends CommandState { phase: "start"; shape: RoofShape; @@ -74,46 +41,27 @@ interface RoofIdle extends CommandState { interface RoofRect extends CommandState { phase: "corner"; a: Vec2; - cursor: Vec2 | null; + cursor: Vec2; shape: RoofShape; } type RoofState = RoofIdle | RoofRect; -/** Vorschau: aufgezogenes Rechteck + Masse im HUD. */ -function roofDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { - const pts = cursor ? rectCorners(a, cursor) : [a]; - const preview: DraftShape[] = [{ kind: "poly", pts, closed: !!cursor }]; - const draft: ToolDraft = { preview, vertices: [a] }; - if (cursor) { - draft.hud = { - at: cursor, - text: `${Math.abs(cursor.x - a.x).toFixed(2)} × ${Math.abs(cursor.y - a.y).toFixed(2)} m`, - }; - } +/** Vorschau: aufgezogenes Rechteck (Kern) + Masse im HUD. */ +function roofDraft(ctx: CommandContext, a: Vec2, cursor: Vec2): ToolDraft { + const draft: ToolDraft = { preview: createPreview(ctx, { cmd: "rect4" }, [a, cursor]).shapes, vertices: [a] }; + draft.hud = { + at: cursor, + text: `${Math.abs(cursor.x - a.x).toFixed(2)} × ${Math.abs(cursor.y - a.y).toFixed(2)} m`, + }; return draft; } -/** Hängt ein Dach ans Projekt (immutabel). Entartete Rechtecke werden verworfen. */ -function appendRoof(a: Vec2, b: Vec2, shape: RoofShape, ctx: CommandContext): CoreOp[] { - const w = Math.abs(b.x - a.x); - const d = Math.abs(b.y - a.y); - if (w < 0.1 || d < 0.1) return []; - const roof: Roof = { - id: uniqueId("RF"), - type: "roof", - floorId: ctx.level.id, - categoryCode: roofCategory(ctx), - outline: rectCorners(a, b), - shape, - // Flach/Pult brauchen keine „Firsthöhe"; Sattel/Walm/Mansarde/Zelt ~30°. - pitchDeg: shape === "flach" ? 0 : 30, - overhang: 0.4, - // First entlang der längeren Seite (Standard). - ridgeAxis: w >= d ? "x" : "y", - thickness: 0.2, - }; - return addItems("roofs", [roof]); -} +/** + * Commit (Kern, `cmd_create.rs`): Dach über dem Rechteck (entartet < 0.1 m → nichts), Ebene „31“, + * Neigung 30° (flach 0°), Vorsprung 0.4 m, First entlang der längeren Seite, Dicke 0.2 m. + */ +const appendRoof = (a: Vec2, b: Vec2, shape: RoofShape, ctx: CommandContext) => + createMutation(ctx, { cmd: "roof", a: xy(a), b: xy(b), shape }); const idle = (shape: RoofShape = "sattel"): [CommandState, CommandResult] => [ { phase: "start", shape, lastPoint: null } as RoofIdle, @@ -135,11 +83,11 @@ export const roofCommand: Command = { // Dachform-Option: aktualisiert die Form, Phase/Rechteck bleiben. if (input.kind === "option" && SHAPE_IDS.has(input.id)) { const ns = { ...s, shape: input.id as RoofShape } as RoofState; - const draft = ns.phase === "corner" ? roofDraft(ns.a, ns.cursor) : null; + const draft = ns.phase === "corner" ? roofDraft(ctx, ns.a, ns.cursor) : null; return [ns, { draft }]; } if (input.kind !== "point") { - return [s, { draft: s.phase === "corner" ? roofDraft(s.a, s.cursor) : null }]; + return [s, { draft: s.phase === "corner" ? roofDraft(ctx, s.a, s.cursor) : null }]; } if (s.phase !== "corner") { const ns: RoofRect = { @@ -149,7 +97,7 @@ export const roofCommand: Command = { shape: s.shape, lastPoint: input.point, }; - return [ns, { draft: roofDraft(input.point, input.point) }]; + return [ns, { draft: roofDraft(ctx, input.point, input.point) }]; } // Zweite Ecke → committen. const a = s.a; @@ -157,15 +105,15 @@ export const roofCommand: Command = { const shape = s.shape; return [ { phase: "start", shape, lastPoint: null } as RoofIdle, - { draft: null, done: true, commit: opsMutation(() => appendRoof(a, b, shape, ctx)) }, + { draft: null, done: true, commit: appendRoof(a, b, shape, ctx) }, ]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as RoofState; if (s.phase !== "corner") return [s, { draft: null }]; const ns: RoofRect = { ...s, cursor: point }; - return [ns, { draft: roofDraft(s.a, point) }]; + return [ns, { draft: roofDraft(ctx, s.a, point) }]; }, onConfirm: (): [CommandState, CommandResult] => idle(), diff --git a/src/commands/cmds/roofHole.ts b/src/commands/cmds/roofHole.ts index 050b873d..ea161930 100644 --- a/src/commands/cmds/roofHole.ts +++ b/src/commands/cmds/roofHole.ts @@ -1,6 +1,6 @@ // Dachhof — Innenhof/Lichthof im Dach als Engine-Befehl: eine Kontur wird per Klicks gezeichnet und // dem ERSTEN Dach des aktiven Geschosses hinzugefügt, in dem sie wirkt (ganz im Umriss, ohne -// Überschneidung, nicht bei Pultdach — das entscheidet der Rust-Kern, s. `roofHoleWorks`). +// Überschneidung, nicht bei Pultdach — das entscheidet der Rust-Kern, s. `cmd_solid.rs`). // // Warum Zeichnen statt „aus gewählter Kontur": die Auswahl kennt immer nur ein Objekt, mit dem // Dach gewählt wäre keine zweite Kontur wählbar; gezeichnet gibt es Fang auf Wände und Umriss, @@ -11,9 +11,8 @@ // 2) „Nächster Punkt ( Schliessen Zurück ):" → Punkt … Schliessen per Klick auf den Startpunkt, // Option „Schliessen" oder Enter (≥ 3 Punkte; bei genau 2 Punkten: Rechteck aus den Ecken). -import { addRoofHole, opsMutation, patchItem, pointInOutline, roofHoleWorks } from "../../core"; -import type { CoreOp } from "../../core"; -import type { Command, CommandContext, CommandResult, CommandState, CmdOption, DraftShape, Project, ToolDraft, Vec2 } from "../types"; +import type { Command, CommandContext, CommandResult, CommandState, CmdOption, DraftShape, ToolDraft, Vec2 } from "../types"; +import { createMutation } from "../createCore"; const EPS = 1e-6; const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schliesst die Kontur @@ -21,19 +20,6 @@ const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schliesst die Kon const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); /** Vier Ecken eines Rechtecks aus zwei Gegenecken. */ -function rectCorners(a: Vec2, b: Vec2): Vec2[] { - const x0 = Math.min(a.x, b.x); - const x1 = Math.max(a.x, b.x); - const y0 = Math.min(a.y, b.y); - const y1 = Math.max(a.y, b.y); - return [ - { x: x0, y: y0 }, - { x: x1, y: y0 }, - { x: x1, y: y1 }, - { x: x0, y: y1 }, - ]; -} - interface HoleIdle extends CommandState { phase: "start"; } @@ -58,33 +44,17 @@ function holeDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { } /** Aus den Klickpunkten die Hof-Kontur: ≥ 3 Punkte = Polygon, genau 2 = Rechteck. */ -function ringOf(points: Vec2[]): Vec2[] | null { - if (points.length >= 3) return points; - if (points.length === 2) { - const [a, b] = points; - if (Math.abs(a.x - b.x) < 0.05 || Math.abs(a.y - b.y) < 0.05) return null; - return rectCorners(a, b); - } - return null; -} - /** - * Hängt den Hof an das erste Dach des aktiven Geschosses, in dem er wirkt. Ohne passendes Dach - * (Hof ausserhalb, schneidet den Umriss, Pultdach) bleibt das Projekt unverändert. + * Commit (Kern, `cmd_solid.rs`): Hof-Ring (≥ 3 Punkte wie gezeichnet, 2 Punkte als Rechteck) in das Dach + * des Geschosses, das ihn ganz enthält und dessen Skelett ihn zulässt; sonst nichts. */ -function roofHoleOps(p: Project, points: Vec2[], ctx: CommandContext): CoreOp[] { - const ring = ringOf(points); - if (!ring) return []; - const host = (p.roofs ?? []).find((r) => r.floorId === ctx.level.id && r.outline.length >= 3 && ring.every((pt) => pointInOutline(pt, r.outline)) && roofHoleWorks(r, ring)); - if (!host) return []; - return patchItem(p, "roofs", host.id, (r) => ({ ...r, ...addRoofHole(r, ring) })); -} +const roofHoleOps = (points: Vec2[], ctx: CommandContext) => createMutation(ctx, { cmd: "roofHole", pts: points }); const idle = (): [CommandState, CommandResult] => [{ phase: "start", lastPoint: null } as HoleIdle, { draft: null, done: true }]; const finish = (points: Vec2[], ctx: CommandContext): [CommandState, CommandResult] => [ { phase: "start", lastPoint: null } as HoleIdle, - { draft: null, done: true, commit: opsMutation((p) => roofHoleOps(p, points, ctx)) }, + { draft: null, done: true, commit: roofHoleOps(points, ctx) }, ]; export const roofHoleCommand: Command = { diff --git a/src/commands/cmds/room.ts b/src/commands/cmds/room.ts index a76ec33b..de52f2d3 100644 --- a/src/commands/cmds/room.ts +++ b/src/commands/cmds/room.ts @@ -3,7 +3,7 @@ // // 1) „innen" (Default) — EIN Klick IN einen von Wänden umschlossenen Bereich. // Der Umriss wird über den reinen Rechenkern (geometry/roomBoundary, -// `roomFromPointInside`) aus den Wänden des aktiven Geschosses automatisch +// `room_from_point_inside`, Kern `cmd_create.rs`) aus den Wänden des aktiven Geschosses automatisch // als lichte Innenkontur erkannt. Findet der Klick keine geschlossene Zelle, // passiert nichts (der Nutzer kann in den Manuell-Modus wechseln). // @@ -17,12 +17,6 @@ // // Bezeichner englisch, sichtbarer Text via t() (CONVENTIONS.md). Einheit: METER. -import type { Room } from "../../model/types"; -import { wallTypeThickness } from "../../model/types"; -import { roomFromPointInside, type WallSegment } from "../../core"; -import { polygonArea, centroid } from "../../core"; -import { docFromText } from "../../text/richText"; -import { uniqueId } from "../../tools/types"; import type { Command, CommandContext, @@ -34,112 +28,21 @@ import type { ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview, xy } from "../createCore"; const EPS = 1e-6; const DEG = Math.PI / 180; const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schließt den Umriss -/** Default-Ebene (Kategorie) für Räume: „60" Räume (Fallback: aktive). */ -const ROOM_CATEGORY = "60"; -/** Default-Raumfarbe (falls Kategorie nicht auflösbar). */ -const ROOM_COLOR = "#5a7a9a"; - const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); const segAngleDeg = (a: Vec2, b: Vec2): number => (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI; -/** Existiert die Raum-Kategorie („45")? Sonst Fallback auf die aktive Kategorie. */ -function roomCategory(ctx: CommandContext): string { - const flat: { code: string }[] = []; - const walk = (list: { code: string; children?: unknown[] }[]) => { - for (const c of list) { - flat.push({ code: c.code }); - if (c.children) walk(c.children as { code: string; children?: unknown[] }[]); - } - }; - walk(ctx.project.layers as { code: string; children?: unknown[] }[]); - return flat.some((c) => c.code === ROOM_CATEGORY) - ? ROOM_CATEGORY - : ctx.defaultCategoryCode; -} - -/** Farbe der Raum-Kategorie (Ebene) — sonst Default. */ -function roomColor(ctx: CommandContext, code: string): string { - const flat: { code: string; color?: string; children?: unknown[] }[] = []; - const walk = (list: { code: string; color?: string; children?: unknown[] }[]) => { - for (const c of list) { - flat.push(c); - if (c.children) - walk( - c.children as { - code: string; - color?: string; - children?: unknown[]; - }[], - ); - } - }; - walk( - ctx.project.layers as { - code: string; - color?: string; - children?: unknown[]; - }[], - ); - return flat.find((c) => c.code === code)?.color ?? ROOM_COLOR; -} - /** - * Wände des aktiven Geschosses in die vom Rechenkern erwartete Form bringen: - * Mittellinie (start→end) + Gesamtdicke des Wandtyps. Grafik-2D-Geometrie und - * andere Geschosse bleiben außen vor. + * Commit eines Raums (Kern, `cmd_create.rs`): Umriss `pts` (manuell) bzw. die lichte Zelle um `at` + * (innen, aus den Wänden des Geschosses); SIA HNF, Name „Raum N“, Ebene „60“ samt Farbe, Stempel-Anker + * im Schwerpunkt und zentrierter Stempel-Text. Entartete Umrisse ergeben nichts. */ -function wallsOfFloor(ctx: CommandContext): WallSegment[] { - const { project, level } = ctx; - const out: WallSegment[] = []; - for (const w of project.walls) { - if (w.floorId !== level.id) continue; - const wt = project.wallTypes.find((t) => t.id === w.wallTypeId); - const thickness = wt ? wallTypeThickness(wt) : 0.2; - out.push({ a: w.start, b: w.end, thickness }); - } - return out; -} - -/** Baut einen Raum aus einem fertigen Umriss (immutabel; keine abgeleiteten Felder). */ -function buildRoom(ctx: CommandContext, boundary: Vec2[]): Room { - const code = roomCategory(ctx); - const name = defaultRoomName(ctx); - return { - id: uniqueId("RM"), - type: "room", - floorId: ctx.level.id, - categoryCode: code, - siaCategory: "HNF", - name, - boundary, - color: roomColor(ctx, code), - // Stempel-Anker EINMALIG auf den Zentroid setzen (danach frei verschiebbar, - // bleibt beim Ändern der Kontur an seiner Stelle). - stampAnchor: centroid(boundary), - // Frei editierbarer Stempel-Text: ein zentrierter Absatz mit dem Raumnamen. - stampDoc: { ...docFromText(name), paragraphs: docFromText(name).paragraphs.map((p) => ({ ...p, align: "center" as const })) }, - }; -} - -/** Fortlaufender Default-Name „Raum N" (N = Anzahl vorhandener Räume + 1). */ -function defaultRoomName(ctx: CommandContext): string { - const n = (ctx.project.rooms ?? []).length + 1; - return `Raum ${n}`; -} - -/** Hängt einen Raum ans Projekt (immutabel); entartete Umrisse werden verworfen. */ -function appendRoom(boundary: Vec2[], ctx: CommandContext): CoreOp[] { - if (boundary.length < 3 || polygonArea(boundary) < 1e-4) return []; - const room = buildRoom(ctx, boundary); - return addItems("rooms", [room]); -} +const appendRoom = (boundary: Vec2[], ctx: CommandContext) => createMutation(ctx, { cmd: "room", pts: boundary.map(xy) }); // ── Zustand ────────────────────────────────────────────────────────────────── @@ -254,7 +157,7 @@ export const roomCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null, mode: s.mode } as RoomIdle, - { draft: null, done: true, commit: opsMutation(() => appendRoom(pts, ctx)) }, + { draft: null, done: true, commit: appendRoom(pts, ctx) }, ]; } return [s, { draft: s.phase === "draw" ? manualDraft(s.points, s.cursor) : null }]; @@ -271,11 +174,10 @@ export const roomCommand: Command = { // ── Modus „innen": ein Klick → Umriss automatisch erkennen + committen ── if (s.mode === "inside" && s.phase !== "draw") { - const boundary = roomFromPointInside(pt, wallsOfFloor(ctx)); - if (boundary && boundary.length >= 3) { + if (createPreview(ctx, { cmd: "roomInside" }, [pt]).ok) { return [ { phase: "start", lastPoint: null, mode: "inside" } as RoomIdle, - { draft: null, done: true, commit: opsMutation(() => appendRoom(boundary, ctx)) }, + { draft: null, done: true, commit: createMutation(ctx, { cmd: "room", at: xy(pt) }) }, ]; } // Kein umschlossener Bereich getroffen → im Werkzeug bleiben (kein Commit). @@ -298,7 +200,7 @@ export const roomCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null, mode: s.mode } as RoomIdle, - { draft: null, done: true, commit: opsMutation(() => appendRoom(pts, ctx)) }, + { draft: null, done: true, commit: appendRoom(pts, ctx) }, ]; } const last = s.points[s.points.length - 1]; @@ -329,7 +231,7 @@ export const roomCommand: Command = { const pts = s.points; return [ { phase: "start", lastPoint: null, mode: s.mode } as RoomIdle, - { draft: null, done: true, commit: opsMutation(() => appendRoom(pts, ctx)) }, + { draft: null, done: true, commit: appendRoom(pts, ctx) }, ]; } return idle(s.mode); diff --git a/src/commands/cmds/scalebar.ts b/src/commands/cmds/scalebar.ts index 569de532..6ee761ea 100644 --- a/src/commands/cmds/scalebar.ts +++ b/src/commands/cmds/scalebar.ts @@ -4,20 +4,16 @@ // `lastSides` bei `polygon.ts`). // Segmentlänge + Anzahl per Option (zyklisch, tippbar als „l"/„n"). -import type { Drawing2D } from "../../model/types"; -import { uniqueId } from "../../tools/types"; import type { CmdOption, Command, CommandContext, CommandResult, CommandState, - DraftShape, ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview } from "../createCore"; const LENGTH_PRESETS = [0.5, 1, 2, 5, 10, 20, 50]; let lastLength = 1; @@ -36,40 +32,18 @@ interface ScalebarIdle extends CommandState { type ScalebarState = ScalebarIdle; /** Vorschau: abwechselnd gefüllte/leere Rechtecke, wie das Rendering (grob, ohne Beschriftung). */ -function pointDraft(at: Vec2): ToolDraft { - const h = lastLength * 0.06; // rein optische Balkenhöhe für die Vorschau - const preview: DraftShape[] = []; - for (let i = 0; i < lastSegments; i++) { - const x0 = at.x + i * lastLength; - const x1 = x0 + lastLength; - preview.push({ - kind: "poly", - pts: [ - { x: x0, y: at.y }, - { x: x1, y: at.y }, - { x: x1, y: at.y + h }, - { x: x0, y: at.y + h }, - ], - closed: true, - }); - } +/** Vorschau (Kern, `cmd_draw.rs`): Segment-Balken am Cursor + HUD (Länge × Anzahl). */ +function pointDraft(ctx: CommandContext, at: Vec2): ToolDraft { return { - preview, + preview: createPreview(ctx, { cmd: "scalebar", length: lastLength, segments: lastSegments }, [at]).shapes, vertices: [at], hud: { at, text: `${lastLength}m × ${lastSegments} = ${(lastLength * lastSegments).toFixed(1)}m` }, }; } -function appendScalebar(at: Vec2, ctx: CommandContext): CoreOp[] { - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "scalebar", at, segmentLength: lastLength, segments: lastSegments }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern): Massstabsbalken mit Segmentlänge und -anzahl. */ +const appendScalebar = (at: Vec2, ctx: CommandContext) => + createMutation(ctx, { cmd: "scalebar", at, length: lastLength, segments: lastSegments }); const idle = (): [CommandState, CommandResult] => [ { phase: "point", lastPoint: null } as ScalebarIdle, @@ -97,10 +71,10 @@ export const scalebarCommand: Command = { return [s, { draft: null }]; } if (input.kind !== "point") return [s, { draft: null }]; - return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendScalebar(input.point, ctx)) }]; + return [idle()[0], { draft: null, done: true, commit: appendScalebar(input.point, ctx) }]; }, - onMove: (state, point): [CommandState, CommandResult] => [state, { draft: pointDraft(point) }], + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => [state, { draft: pointDraft(ctx, point) }], onConfirm: (): [CommandState, CommandResult] => idle(), onCancel: (): [CommandState, CommandResult] => idle(), }; diff --git a/src/commands/cmds/sectionline.test.ts b/src/commands/cmds/sectionline.test.ts index bb974ae1..8a0b325b 100644 --- a/src/commands/cmds/sectionline.test.ts +++ b/src/commands/cmds/sectionline.test.ts @@ -1,13 +1,26 @@ -// Schnittlinien-Befehl: der reine Datenpfad (commitLine/nextLevelName) — setzt -// die Grundriss-Schnittlinie auf die richtige Ziel-Ebene bzw. legt eine neue an. +// Schnittlinien-Befehl: der Datenpfad über den Befehl (Kern, `cmd_solid.rs`) — setzt die +// Grundriss-Schnittlinie auf die richtige Ziel-Ebene bzw. legt eine neue an. import { describe, it, expect } from "vitest"; -import { _test } from "./sectionline"; +import { sectionLineCommand } from "./sectionline"; import type { DrawingLevel, Project, Vec2 } from "../../model/types"; +import type { CommandContext } from "../types"; import { applyOps } from "../../core/ops"; -const { lineOps, nextLevelName } = _test; -const commitLine = (p: Project, a: Vec2, b: Vec2, kind: "section" | "elevation") => applyOps(p, lineOps(p, a, b, kind)); +/** Linie a→b mit dem Befehl setzen (Art per Option), Ops auf `p` anwenden. */ +function commitLine(p: Project, a: Vec2, b: Vec2, kind: "section" | "elevation"): Project { + const ctx = { project: p, level: { id: "eg", kind: "floor" }, defaultCategoryCode: "20", activeWallTypeId: "", selection: { wallIds: [], drawingId: null } } as unknown as CommandContext; + let s = sectionLineCommand.init(); + [s] = sectionLineCommand.onInput(s, { kind: "option", id: kind }, ctx); + [s] = sectionLineCommand.onInput(s, { kind: "point", point: a }, ctx); + const [, res] = sectionLineCommand.onInput(s, { kind: "point", point: b }, ctx); + const ops = res.commit!.toOps(p); + return ops.length ? applyOps(p, ops) : p; +} + +/** Name der Ebene, die eine neue Linie dieser Art anlegt. */ +const nextLevelName = (p: Project, kind: "section" | "elevation"): string => + commitLine(p, a, b, kind).drawingLevels.at(-1)!.name; function projectWith(levels: DrawingLevel[]): Project { return { @@ -90,12 +103,12 @@ describe("sectionline — commitLine", () => { }); }); -describe("sectionline — nextLevelName", () => { +describe("sectionline — Name der neuen Ebene", () => { it("zählt Buchstaben je Art hoch (A, B, C …)", () => { const p0 = projectWith([]); expect(nextLevelName(p0, "section")).toContain("A"); const p1 = projectWith([ - { id: "s1", name: "Schnitt A", kind: "section", visible: true, locked: false }, + { id: "s1", name: "Schnitt A", kind: "section", visible: true, locked: false, linePoints: [{ x: 0, y: 0 }, { x: 1, y: 0 }] }, ]); expect(nextLevelName(p1, "section")).toContain("B"); }); diff --git a/src/commands/cmds/sectionline.ts b/src/commands/cmds/sectionline.ts index 847d07d6..a1a3ac5b 100644 --- a/src/commands/cmds/sectionline.ts +++ b/src/commands/cmds/sectionline.ts @@ -16,17 +16,13 @@ // „elevation"). Bezeichner englisch, sichtbarer Text via t(). import { t } from "../../i18n"; -import type { DrawingLevel, DrawingLevelKind } from "../../model/types"; -import { leftNormal, normalize, sub } from "../../model/geometry"; -import { addItems, opsMutation, patchItem } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview } from "../createCore"; import type { Command, + CommandContext, CommandResult, CommandState, CmdOption, - DraftShape, - Project, ToolDraft, Vec2, } from "../types"; @@ -42,42 +38,12 @@ const KIND_OPTIONS: CmdOption[] = [ const KIND_IDS = new Set(KIND_OPTIONS.map((o) => o.id)); /** - * Richtungspfeil-Vorschau: kurze Linie vom Mittelpunkt der Schnittlinie entlang - * der Blicknormalen (leftNormal der Linie, per directionSign gedreht) plus zwei - * Flügel-Segmente — zeigt, wohin der Schnitt „blickt". + * Vorschau: Schnittlinie + Richtungspfeil (Kern, `cmd_solid.rs`: vom Mittelpunkt entlang der + * Blicknormalen, zwei Flügel) + Länge im HUD. */ -function directionArrow(a: Vec2, b: Vec2, sign: 1 | -1): DraftShape[] { - const dir = sub(b, a); - const len = Math.hypot(dir.x, dir.y); - if (len < 1e-6) return []; - const u = normalize(dir); - const n = leftNormal(u); // (-uy, ux) - const nx = n.x * sign; - const ny = n.y * sign; - const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; - // Pfeillänge ~ min(1 m, Viertel der Linienlänge), damit die Vorschau lesbar bleibt. - const arrowLen = Math.min(1, len / 4); - const tip = { x: mid.x + nx * arrowLen, y: mid.y + ny * arrowLen }; - const wing = arrowLen * 0.35; - // Flügel: vom Spitzenpunkt zurück, je halb entlang −u und +u geneigt. - const back = { x: tip.x - nx * wing * 2, y: tip.y - ny * wing * 2 }; - const w1 = { x: back.x + u.x * wing, y: back.y + u.y * wing }; - const w2 = { x: back.x - u.x * wing, y: back.y - u.y * wing }; - return [ - { kind: "line", a: mid, b: tip }, - { kind: "line", a: tip, b: w1 }, - { kind: "line", a: tip, b: w2 }, - ]; -} - -/** Vorschau: Schnittlinie + Richtungspfeil + Länge im HUD. */ -function lineDraft(a: Vec2, cursor: Vec2 | null, sign: 1 | -1): ToolDraft { +function lineDraft(ctx: CommandContext, a: Vec2, cursor: Vec2 | null): ToolDraft { if (!cursor) return { preview: [{ kind: "poly", pts: [a] }], vertices: [a] }; - const preview: DraftShape[] = [ - { kind: "line", a, b: cursor }, - ...directionArrow(a, cursor, sign), - ]; - const draft: ToolDraft = { preview, vertices: [a] }; + const draft: ToolDraft = { preview: createPreview(ctx, { cmd: "sectionline" }, [a, cursor]).shapes, vertices: [a] }; draft.hud = { at: cursor, text: `${Math.hypot(cursor.x - a.x, cursor.y - a.y).toFixed(2)} m`, @@ -85,42 +51,13 @@ function lineDraft(a: Vec2, cursor: Vec2 | null, sign: 1 | -1): ToolDraft { return draft; } -/** Nächster freier Ebenen-Name der Art (A, B, C … über die Anzahl bestehender). */ -function nextLevelName(p: Project, kind: LineKind): string { - const count = p.drawingLevels.filter((z) => z.kind === kind).length; - // Buchstaben-Suffix (A, B, …, Z, dann AA…) — klassische Schnitt-Benennung. - let n = count; - let letters = ""; - do { - letters = String.fromCharCode(65 + (n % 26)) + letters; - n = Math.floor(n / 26) - 1; - } while (n >= 0); - const key = kind === "section" ? "cmd.sectionline.newSection" : "cmd.sectionline.newElevation"; - return t(key, { letter: letters }); -} - /** - * Setzt die Schnittlinie [a, b] auf die Ziel-Ebene (immutabel). Existiert GENAU - * EINE Ebene der Art ohne Linie, wird sie belegt; sonst wird eine neue angelegt. - * Entartete (zu kurze) Linien werden verworfen. + * Commit (Kern): Linie [a, b] auf die EINE Ebene der Art ohne Linie, sonst eine neue Ebene (Name aus der + * Vorlage, Buchstaben A, B, … nach Anzahl der Ebenen dieser Art); zu kurze Linien (< 0.1 m) → nichts. */ -function lineOps(p: Project, a: Vec2, b: Vec2, kind: LineKind): CoreOp[] { - if (Math.hypot(b.x - a.x, b.y - a.y) < 0.1) return []; - const line: [Vec2, Vec2] = [a, b]; - const orphans = p.drawingLevels.filter((z) => z.kind === kind && !z.linePoints); - if (orphans.length === 1) { - return patchItem(p, "drawingLevels", orphans[0].id, (z) => ({ ...z, linePoints: line, directionSign: z.directionSign ?? 1 })); - } - const level: DrawingLevel = { - id: `${kind}-${Date.now()}`, - name: nextLevelName(p, kind), - kind: kind as DrawingLevelKind, - visible: true, - locked: false, - linePoints: line, - directionSign: 1, - }; - return addItems("drawingLevels", [level]); +function lineMutation(ctx: CommandContext, a: Vec2, b: Vec2, kind: LineKind) { + const key = kind === "section" ? "cmd.sectionline.newSection" : "cmd.sectionline.newElevation"; + return createMutation(ctx, { cmd: "sectionline", a, b, kind, name: t(key, { letter: "\u0001" }) }); } interface LineIdle extends CommandState { @@ -135,8 +72,6 @@ interface LineEnd extends CommandState { } type LineState = LineIdle | LineEnd; -const DIRECTION_SIGN: 1 = 1; - function makeCommand(name: string, startKind: LineKind): Command { const idle = (kind: LineKind): [CommandState, CommandResult] => [ { phase: "start", kind, lastPoint: null } as LineIdle, @@ -155,18 +90,18 @@ function makeCommand(name: string, startKind: LineKind): Command { options: () => KIND_OPTIONS, init: (): LineIdle => ({ phase: "start", kind: startKind, lastPoint: null }), - onInput: (state, input): [CommandState, CommandResult] => { + onInput: (state, input, ctx): [CommandState, CommandResult] => { const s = state as LineState; if (input.kind === "option" && KIND_IDS.has(input.id)) { const ns = { ...s, kind: input.id as LineKind } as LineState; const draft = - ns.phase === "end" ? lineDraft(ns.a, ns.cursor, DIRECTION_SIGN) : null; + ns.phase === "end" ? lineDraft(ctx, ns.a, ns.cursor) : null; return [ns, { draft }]; } if (input.kind !== "point") { return [ s, - { draft: s.phase === "end" ? lineDraft(s.a, s.cursor, DIRECTION_SIGN) : null }, + { draft: s.phase === "end" ? lineDraft(ctx, s.a, s.cursor) : null }, ]; } if (s.phase !== "end") { @@ -177,22 +112,22 @@ function makeCommand(name: string, startKind: LineKind): Command { kind: s.kind, lastPoint: input.point, }; - return [ns, { draft: lineDraft(input.point, input.point, DIRECTION_SIGN) }]; + return [ns, { draft: lineDraft(ctx, input.point, input.point) }]; } const a = s.a; const b = input.point; const kind = s.kind; return [ { phase: "start", kind, lastPoint: null } as LineIdle, - { draft: null, done: true, commit: opsMutation((p) => lineOps(p, a, b, kind)) }, + { draft: null, done: true, commit: lineMutation(ctx, a, b, kind) }, ]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as LineState; if (s.phase !== "end") return [s, { draft: null }]; const ns: LineEnd = { ...s, cursor: point }; - return [ns, { draft: lineDraft(s.a, point, DIRECTION_SIGN) }]; + return [ns, { draft: lineDraft(ctx, s.a, point) }]; }, onConfirm: (state): [CommandState, CommandResult] => idle((state as LineState).kind), @@ -206,4 +141,3 @@ export const sectionLineCommand: Command = makeCommand("sectionline", "section") export const viewLineCommand: Command = makeCommand("viewline", "elevation"); // Für Tests: die reinen Datenpfad-Helfer. -export const _test = { lineOps, nextLevelName, directionArrow }; diff --git a/src/commands/cmds/solid.test.ts b/src/commands/cmds/solid.test.ts index 7e2ae767..de37d05e 100644 --- a/src/commands/cmds/solid.test.ts +++ b/src/commands/cmds/solid.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { sampleProject } from "../../model/sampleProject"; import type { CommandContext } from "../types"; -import { solidCommand, solidFromInputs } from "./solid"; +import { solidCommand } from "./solid"; const ctx = { project: sampleProject, level: { id: "eg" } } as unknown as CommandContext; @@ -47,14 +47,15 @@ describe("solid-Befehl", () => { { kind: "number", value: 3 }, ])!; expect(q.extrudedSolids![0].brep!.spec).toMatchObject({ kind: "cuboid", min: [0, 0, 0], max: [4, 2, 3] }); - expect(solidFromInputs("torus", { x: 0, y: 0 }, null, [0.3, 0.5])).toBeNull(); - expect(solidFromInputs("torus", { x: 0, y: 0 }, null, [2, 0.5])?.height).toBeCloseTo(1, 9); + // Torus: Hauptradius ≤ Rohrradius ergibt keinen Körper. + expect(run("torus", [{ kind: "point", point: { x: 0, y: 0 } }, { kind: "number", value: 0.3 }, { kind: "number", value: 0.5 }])!.extrudedSolids).toHaveLength(0); + expect(run("torus", [{ kind: "point", point: { x: 0, y: 0 } }, { kind: "number", value: 2 }, { kind: "number", value: 0.5 }])!.extrudedSolids![0].height).toBeCloseTo(1, 9); }); it("Kegelstumpf: Revolve-Profil aus Radius, Oberradius, Hoehe", () => { - const b = solidFromInputs("frustum", { x: 1, y: 2 }, null, [2, 1, 3]); - expect(b?.height).toBe(3); - expect(b?.spec).toMatchObject({ kind: "revolve", cx: 1, cy: 2, profile: [0, 0, 2, 0, 1, 3, 0, 3] }); - expect(solidFromInputs("frustum", { x: 0, y: 0 }, null, [2, 0, 3])).toBeNull(); + const p = run("frustum", [{ kind: "point", point: { x: 1, y: 2 } }, { kind: "number", value: 2 }, { kind: "number", value: 1 }, { kind: "number", value: 3 }])!; + const b = p.extrudedSolids![0]; + expect(b.height).toBe(3); + expect(b.brep!.spec).toMatchObject({ kind: "revolve", cx: 1, cy: 2, profile: [0, 0, 2, 0, 1, 3, 0, 3] }); }); }); diff --git a/src/commands/cmds/solid.ts b/src/commands/cmds/solid.ts index 711ed578..4f324c65 100644 --- a/src/commands/cmds/solid.ts +++ b/src/commands/cmds/solid.ts @@ -12,18 +12,16 @@ // Quader Ecke → Gegenecke → Höhe // Der Körper steht auf der Geschoss-UK (Z = 0 lokal). -import type { ExtrudedSolid } from "../../model/types"; -import { addItems, opsMutation } from "../../core"; -import { uniqueId } from "../../tools/types"; import type { Command, + CommandContext, CommandResult, CommandState, CmdOption, - DraftShape, ToolDraft, Vec2, } from "../types"; +import { createMutation, createPreview } from "../createCore"; export type SolidShape = "sphere" | "cylinder" | "cone" | "frustum" | "torus" | "cuboid"; @@ -75,104 +73,22 @@ interface SolidState extends CommandState { /** Persistente Defaults über Aufrufe hinweg (Enter übernimmt sie). */ let lastShape: SolidShape = "sphere"; -const circlePts = (c: Vec2, r: number): Vec2[] => - Array.from({ length: 48 }, (_, i) => { - const t = (i / 48) * Math.PI * 2; - return { x: c.x + r * Math.cos(t), y: c.y + r * Math.sin(t) }; - }); - -const rectPts = (a: Vec2, b: Vec2): Vec2[] => { - const [x0, x1] = [Math.min(a.x, b.x), Math.max(a.x, b.x)]; - const [y0, y1] = [Math.min(a.y, b.y), Math.max(a.y, b.y)]; - return [{ x: x0, y: y0 }, { x: x1, y: y0 }, { x: x1, y: y1 }, { x: x0, y: y1 }]; -}; - -/** Grundriss-Fläche, Körperhöhe und B-Rep-Spezifikation (lokales Z ab 0) einer Form. */ -export function solidFromInputs( - shape: SolidShape, - p0: Vec2, - p1: Vec2 | null, - nums: number[], -): { points: Vec2[]; height: number; spec: Record; label: string } | null { - const fmt = (v: number) => v.toFixed(2); - switch (shape) { - case "sphere": { - const r = nums[0]; - if (!(r > 1e-6)) return null; - return { - points: circlePts(p0, r), - height: 2 * r, - spec: { kind: "sphere", center: [p0.x, p0.y, r], r }, - label: `Kugel r=${fmt(r)}`, - }; - } - case "cylinder": - case "cone": { - const [r, h] = nums; - if (!(r > 1e-6) || !(h > 1e-6)) return null; - return { - points: circlePts(p0, r), - height: h, - spec: { kind: shape, cx: p0.x, cy: p0.y, z0: 0, r, height: h }, - label: `${shape === "cone" ? "Kegel" : "Zylinder"} r=${fmt(r)} h=${fmt(h)}`, - }; - } - case "frustum": { - const [r, rt, h] = nums; - if (!(r > 1e-6) || !(rt > 1e-6) || !(h > 1e-6)) return null; - return { - points: circlePts(p0, Math.max(r, rt)), - height: h, - spec: { kind: "revolve", cx: p0.x, cy: p0.y, profile: [0, 0, r, 0, rt, h, 0, h] }, - label: `Kegelstumpf r=${fmt(r)}/${fmt(rt)} h=${fmt(h)}`, - }; - } - case "torus": { - const [major, minor] = nums; - if (!(minor > 1e-6) || !(major > minor)) return null; - return { - points: circlePts(p0, major + minor), - height: 2 * minor, - spec: { kind: "torus", center: [p0.x, p0.y, minor], major, minor }, - label: `Torus R=${fmt(major)} r=${fmt(minor)}`, - }; - } - case "cuboid": { - const h = nums[0]; - if (!p1 || !(h > 1e-6)) return null; - const pts = rectPts(p0, p1); - const [w, d] = [Math.abs(p1.x - p0.x), Math.abs(p1.y - p0.y)]; - if (w < 1e-6 || d < 1e-6) return null; - return { - points: pts, - height: h, - spec: { kind: "cuboid", min: [pts[0].x, pts[0].y, 0], max: [pts[2].x, pts[2].y, h] }, - label: `Quader ${fmt(w)}×${fmt(d)}×${fmt(h)}`, - }; - } - } -} - -function draftOf(s: SolidState): ToolDraft | null { +/** + * Vorschau (Kern, `cmd_draw.rs`/`cmd_solid.rs`): Grundriss des Körpers je Schritt (Kreise bzw. Rechteck) + * + HUD (aktuelles Mass). + */ +function draftOf(ctx: CommandContext, s: SolidState): ToolDraft | null { if (!s.p0) return null; const step = STEPS[s.shape][s.stepIdx]; - const preview: DraftShape[] = []; - let hud: string | undefined; const cur = s.cursor ?? s.p0; + const pts = [s.p0, ...(s.p1 ? [s.p1] : []), ...(s.cursor ? [s.cursor] : [])]; + const preview = createPreview(ctx, { cmd: "solid", shape: s.shape, step, nums: s.nums, p1: !!s.p1, cursor: !!s.cursor }, pts).shapes; const dist = Math.hypot(cur.x - s.p0.x, cur.y - s.p0.y); + let hud: string; if (s.shape === "cuboid") { const b = s.p1 ?? cur; - preview.push({ kind: "poly", pts: rectPts(s.p0, b), closed: true }); hud = s.p1 ? `h = ${(s.nums[0] ?? 0).toFixed(2)} m` : `${Math.abs(b.x - s.p0.x).toFixed(2)} × ${Math.abs(b.y - s.p0.y).toFixed(2)} m`; } else { - const r = step === "radius" || step === "major" ? dist : (s.nums[0] ?? dist); - if (s.shape === "frustum" && step !== "radius") { - preview.push({ kind: "poly", pts: circlePts(s.p0, Math.max(step === "topRadius" ? dist : (s.nums[1] ?? dist), 0.01)), closed: true }); - } - preview.push({ kind: "poly", pts: circlePts(s.p0, Math.max(r, 0.01)), closed: true }); - if (s.shape === "torus" && step === "minor") { - preview.push({ kind: "poly", pts: circlePts(s.p0, (s.nums[0] ?? 0) + dist), closed: true }); - } hud = `${step === "height" ? "h" : step === "topRadius" ? "r2" : "r"} = ${dist.toFixed(2)} m`; } return { preview, vertices: [s.p0], hud: { at: cur, text: hud } }; @@ -207,16 +123,16 @@ export const solidCommand: Command = { lastShape = input.id as SolidShape; // Form-Wechsel setzt die Schritte zurück (der Mittelpunkt bleibt, falls schon gesetzt). const ns: SolidState = { ...reset(lastShape), p0: s.p0, stepIdx: s.p0 ? 1 : 0, cursor: s.cursor }; - return [ns, { draft: draftOf(ns) }]; + return [ns, { draft: draftOf(ctx, ns) }]; } const steps = STEPS[s.shape]; const step = steps[s.stepIdx]; // 1) Mittelpunkt / erste Ecke if (step === "center") { - if (input.kind !== "point") return [s, { draft: draftOf(s) }]; + if (input.kind !== "point") return [s, { draft: draftOf(ctx, s) }]; const ns: SolidState = { ...s, p0: input.point, stepIdx: 1, cursor: input.point, lastPoint: input.point }; - return [ns, { draft: draftOf(ns) }]; + return [ns, { draft: draftOf(ctx, ns) }]; } // Wert des aktuellen Schritts: getippte Zahl oder Klick-Abstand zum Mittelpunkt. @@ -228,45 +144,29 @@ export const solidCommand: Command = { // Quader: Gegenecke als Punkt if (step === "corner2") { - if (input.kind !== "point") return [s, { draft: draftOf(s) }]; + if (input.kind !== "point") return [s, { draft: draftOf(ctx, s) }]; const ns: SolidState = { ...s, p1: input.point, stepIdx: s.stepIdx + 1, cursor: input.point }; - return [ns, { draft: draftOf(ns) }]; + return [ns, { draft: draftOf(ctx, ns) }]; } - if (value === null || !(value > 1e-6)) return [s, { draft: draftOf(s) }]; + if (value === null || !(value > 1e-6)) return [s, { draft: draftOf(ctx, s) }]; const nums = [...s.nums, value]; if (s.stepIdx + 1 < steps.length) { const ns: SolidState = { ...s, nums, stepIdx: s.stepIdx + 1 }; - return [ns, { draft: draftOf(ns) }]; + return [ns, { draft: draftOf(ctx, ns) }]; } // Letzter Schritt → committen. - const built = solidFromInputs(s.shape, s.p0!, s.p1, nums); - const levelId = ctx.level.id; + // Körper im Kern (`cmd_solid.rs`): Grundriss, Höhe, B-Rep-Beschreibung (truck) und Label. return [ reset(s.shape), - { - draft: null, - done: true, - commit: opsMutation(() => { - if (!built) return []; - const solid: ExtrudedSolid = { - id: uniqueId("body"), - type: "extrudedSolid", - levelId, - points: built.points, - height: built.height, - brep: { spec: built.spec, origin: built.points[0], label: built.label }, - }; - return addItems("extrudedSolids", [solid]); - }), - }, + { draft: null, done: true, commit: createMutation(ctx, { cmd: "solid", shape: s.shape, p0: s.p0, p1: s.p1, nums }) }, ]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as SolidState; const ns: SolidState = { ...s, cursor: point }; - return [ns, { draft: draftOf(ns) }]; + return [ns, { draft: draftOf(ctx, ns) }]; }, onConfirm: (state): [CommandState, CommandResult] => [reset((state as SolidState).shape), { draft: null, done: true }], diff --git a/src/commands/cmds/solidbool.test.ts b/src/commands/cmds/solidbool.test.ts index b20c2e6f..c1441f4c 100644 --- a/src/commands/cmds/solidbool.test.ts +++ b/src/commands/cmds/solidbool.test.ts @@ -1,7 +1,15 @@ import { describe, expect, it } from "vitest"; import { sampleProject } from "../../model/sampleProject"; import type { ExtrudedSolid } from "../../model/types"; -import { combineSolids } from "./solidbool"; +import { documentFor } from "../../core/document"; + +/** Boolesche Verknüpfung zweier Körper über den Befehl im Kern (`cmd_solid.rs`); null = kein Körper. */ +function combineSolids(project: typeof sampleProject, a: ExtrudedSolid, b: ExtrudedSolid, op: string): ExtrudedSolid | null { + const p = { ...project, extrudedSolids: [a, b] }; + const ops = documentFor(p).cmdOps({ cmd: "solidbool", a: a.id, b: b.id, op, stamp: "t", ctx: { level: "eg" } }); + const add = ops.find((o) => o.kind === "add"); + return add && add.kind === "add" ? (add.items[0] as unknown as ExtrudedSolid) : null; +} const box = (id: string, x0: number, y0: number, x1: number, y1: number, h: number): ExtrudedSolid => ({ id, diff --git a/src/commands/cmds/solidbool.ts b/src/commands/cmds/solidbool.ts index 5e249292..97959597 100644 --- a/src/commands/cmds/solidbool.ts +++ b/src/commands/cmds/solidbool.ts @@ -7,11 +7,8 @@ // fertig. Die Operation wählt man als Inline-Option (Default Vereinigung); bei Differenz wird // der ZWEITE vom ERSTEN abgezogen. Beide Quellkörper werden durch das Ergebnis ersetzt. -import type { ExtrudedSolid, Vec2 } from "../../model/types"; -import { getFloor } from "../../model/types"; -import { uniqueId } from "../../tools/types"; -import { addItems, extrudedSolidSpec, opsMutation, removeItems } from "../../core"; -import type { Command, CommandResult, CommandState, CmdOption, Project, ToolDraft } from "../types"; +import type { Command, CommandContext, CommandResult, CommandState, CmdOption, ToolDraft } from "../types"; +import { createMutation, createPreview, createQuery, xy } from "../createCore"; export type SolidBoolOp = "union" | "difference" | "intersection"; @@ -30,110 +27,18 @@ interface BoolState extends CommandState { firstId: string | null; } -function pointInPolygon(p: Vec2, poly: Vec2[]): boolean { - let inside = false; - for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { - const a = poly[i]; - const b = poly[j]; - if (a.y > p.y !== b.y > p.y && p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y || 1e-12) + a.x) { - inside = !inside; - } - } - return inside; -} - -function bbox(pts: Vec2[]): { x0: number; y0: number; x1: number; y1: number } { - return { - x0: Math.min(...pts.map((p) => p.x)), - y0: Math.min(...pts.map((p) => p.y)), - x1: Math.max(...pts.map((p) => p.x)), - y1: Math.max(...pts.map((p) => p.y)), - }; -} - -const rect = (b: { x0: number; y0: number; x1: number; y1: number }): Vec2[] => [ - { x: b.x0, y: b.y0 }, - { x: b.x1, y: b.y0 }, - { x: b.x1, y: b.y1 }, - { x: b.x0, y: b.y1 }, -]; - -/** Körper auf der aktiven Ebene, dessen Grundfläche den Punkt enthält (der kleinste gewinnt). */ -function pickSolid(project: Project, levelId: string, pt: Vec2): ExtrudedSolid | null { - let best: ExtrudedSolid | null = null; - let bestArea = Infinity; - for (const s of project.extrudedSolids ?? []) { - if (s.levelId !== levelId || !pointInPolygon(pt, s.points)) continue; - const b = bbox(s.points); - const area = (b.x1 - b.x0) * (b.y1 - b.y0); - if (area < bestArea) { - best = s; - bestArea = area; - } - } - return best; -} - -/** Ergebnis-Körper aus zwei Operanden (reiner Kern, getestet). `null`, wenn ein Operand keine B-Rep-Beschreibung hat. */ -export function combineSolids( - project: Project, - a: ExtrudedSolid, - b: ExtrudedSolid, - op: SolidBoolOp, -): ExtrudedSolid | null { - let baseZ = 0; - try { - baseZ = getFloor(project, a.levelId).baseElevation ?? 0; - } catch { - baseZ = 0; - } - // Operanden mit UK 0 beschreiben (lokales Z ab Geschoss-UK), Verschiebung ist eingebacken. - const sa = extrudedSolidSpec(a, 0); - const sb = extrudedSolidSpec(b, 0); - void baseZ; - if (!sa || !sb) return null; - const ba = bbox(a.points); - const bb = bbox(b.points); - let points: Vec2[]; - let height: number; - let label: string; - if (op === "union") { - points = rect({ x0: Math.min(ba.x0, bb.x0), y0: Math.min(ba.y0, bb.y0), x1: Math.max(ba.x1, bb.x1), y1: Math.max(ba.y1, bb.y1) }); - height = Math.max(a.height, b.height); - label = "Vereinigung"; - } else if (op === "difference") { - points = a.points.map((p) => ({ ...p })); - height = a.height; - label = "Differenz"; - } else { - const x0 = Math.max(ba.x0, bb.x0); - const y0 = Math.max(ba.y0, bb.y0); - const x1 = Math.min(ba.x1, bb.x1); - const y1 = Math.min(ba.y1, bb.y1); - if (x1 - x0 < 1e-6 || y1 - y0 < 1e-6) return null; - points = rect({ x0, y0, x1, y1 }); - height = Math.min(a.height, b.height); - label = "Durchschnitt"; - } - return { - id: uniqueId("body"), - type: "extrudedSolid", - levelId: a.levelId, - points, - height, - brep: { - spec: { kind: "boolean", op, a: sa, b: sb } as unknown as Record, - origin: points[0], - label, - }, - }; +/** Kleinster Körper der Ebene, dessen Grundriss den Punkt enthält (Kern), oder null. */ +function pickSolid(ctx: CommandContext, pt: { x: number; y: number }): string | null { + return createQuery<{ hit: string | null }>(ctx.project, { q: "pickSolid", level: ctx.level.id, pt: xy(pt) }).hit; } const reset = (op: SolidBoolOp): BoolState => ({ phase: "first", op, firstId: null, lastPoint: null }); -function highlight(project: Project, id: string | null): ToolDraft | null { - const s = id ? (project.extrudedSolids ?? []).find((x) => x.id === id) : null; - return s ? { preview: [{ kind: "poly", pts: s.points, closed: true }], vertices: [] } : null; +/** Hervorhebung des ersten gewählten Körpers (Grundriss aus dem Kern). */ +function highlight(ctx: CommandContext, id: string | null): ToolDraft | null { + if (!id) return null; + const pv = createPreview(ctx, { cmd: "solidOutline", id }, []); + return pv.ok ? { preview: pv.shapes, vertices: [] } : null; } export const solidBoolCommand: Command = { @@ -150,16 +55,16 @@ export const solidBoolCommand: Command = { if (input.kind === "option" && OP_IDS.has(input.id)) { lastOp = input.id as SolidBoolOp; const ns: BoolState = { ...s, op: lastOp }; - return [ns, { draft: highlight(ctx.project, s.firstId) }]; + return [ns, { draft: highlight(ctx, s.firstId) }]; } - if (input.kind !== "point") return [s, { draft: highlight(ctx.project, s.firstId) }]; - const hit = pickSolid(ctx.project, ctx.level.id, input.point); - if (!hit) return [s, { draft: highlight(ctx.project, s.firstId) }]; + if (input.kind !== "point") return [s, { draft: highlight(ctx, s.firstId) }]; + const hit = pickSolid(ctx, input.point); + if (!hit) return [s, { draft: highlight(ctx, s.firstId) }]; if (s.phase === "first") { - const ns: BoolState = { ...s, phase: "second", firstId: hit.id, lastPoint: input.point }; - return [ns, { draft: highlight(ctx.project, hit.id) }]; + const ns: BoolState = { ...s, phase: "second", firstId: hit, lastPoint: input.point }; + return [ns, { draft: highlight(ctx, hit) }]; } - if (hit.id === s.firstId) return [s, { draft: highlight(ctx.project, s.firstId) }]; + if (hit === s.firstId) return [s, { draft: highlight(ctx, s.firstId) }]; const firstId = s.firstId!; const op = s.op; return [ @@ -167,15 +72,8 @@ export const solidBoolCommand: Command = { { draft: null, done: true, - commit: opsMutation((p) => { - const a = (p.extrudedSolids ?? []).find((x) => x.id === firstId); - const b = (p.extrudedSolids ?? []).find((x) => x.id === hit.id); - if (!a || !b) return []; - const merged = combineSolids(p, a, b, op); - if (!merged) return []; - // Beide Körper raus, das Ergebnis hinten dran. - return [...removeItems(p, "extrudedSolids", [a.id, b.id]), ...addItems("extrudedSolids", [merged])]; - }), + // Verknüpfung im Kern (`cmd_solid.rs`): Grundriss, Höhe, B-Rep `boolean` beider Körper. + commit: createMutation(ctx, { cmd: "solidbool", a: firstId, b: hit, op }), }, ]; }, diff --git a/src/commands/cmds/spline.ts b/src/commands/cmds/spline.ts index 3b957061..91276aff 100644 --- a/src/commands/cmds/spline.ts +++ b/src/commands/cmds/spline.ts @@ -15,21 +15,17 @@ // Kein Gewicht pro Kontrollpunkt (NURBS) — bewusst auf den unbewichteten // Fall beschränkt, s. PENDENZEN.md. -import type { Drawing2D } from "../../model/types"; -import { segmentHud, uniqueId } from "../../tools/types"; -import { sampleCatmullRom, sampleUniformBSpline } from "../../core"; +import { segmentHud } from "../../tools/types"; import type { Command, CommandContext, CommandResult, CommandState, CmdOption, - DraftShape, ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview } from "../createCore"; const EPS = 1e-6; const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schließt den Zug @@ -65,32 +61,19 @@ const curveModeOption = (mode: CurveMode): CmdOption => ({ }); /** Kurvenpunkte je nach Modus (fit = interpolierend, control = B-Spline-Kontrollnetz). */ -function sampleCurve(pts: Vec2[], closed: boolean, mode: CurveMode): Vec2[] { - return mode === "control" ? sampleUniformBSpline(pts, closed) : sampleCatmullRom(pts, closed); -} - -/** Vorschau (geglätteter Zug + Gummiband zum Cursor) + HUD. */ -function splineDraft(points: Vec2[], cursor: Vec2 | null, closed: boolean, mode: CurveMode): ToolDraft { +function splineDraft(ctx: CommandContext, points: Vec2[], cursor: Vec2 | null, closed: boolean, mode: CurveMode): ToolDraft { + // Kurve im Kern (`cmd_draw.rs`): Catmull-Rom durch die Punkte bzw. B-Spline über dem Kontrollnetz, + // geschlossen ab 3 Punkten. const pts = cursor ? [...points, cursor] : points; - const showClosed = closed && pts.length >= 3; - const curve = sampleCurve(pts, showClosed, mode); - const preview: DraftShape[] = [{ kind: "poly", pts: curve, closed: showClosed }]; - const draft: ToolDraft = { preview, vertices: points }; + const draft: ToolDraft = { preview: createPreview(ctx, { cmd: "spline", closed, mode }, pts).shapes, vertices: points }; const last = points[points.length - 1]; if (cursor && last && segLen(last, cursor) >= EPS) draft.hud = segmentHud(last, cursor); return draft; } -function appendSpline(pts: Vec2[], closed: boolean, mode: CurveMode, ctx: CommandContext): CoreOp[] { - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "spline", pts, closed, mode }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern): Spline-Zeichnung aus den Punkten. */ +const appendSpline = (pts: Vec2[], closed: boolean, mode: CurveMode, ctx: CommandContext) => + createMutation(ctx, { cmd: "spline", pts, closed, mode }); const idle = (closed = false, curveMode: CurveMode = "fit"): [CommandState, CommandResult] => [ { phase: "start", lastPoint: null, closed, curveMode } as SplineIdle, @@ -116,11 +99,11 @@ export const splineCommand: Command = { if (input.kind === "option") { if (input.id === "mode") { const ns = { ...s, closed: !s.closed } as SplineState; - return [ns, { draft: s.phase === "next" ? splineDraft(s.points, s.cursor, ns.closed, s.curveMode) : null }]; + return [ns, { draft: s.phase === "next" ? splineDraft(ctx, s.points, s.cursor, ns.closed, s.curveMode) : null }]; } if (input.id === "curveMode") { const ns = { ...s, curveMode: s.curveMode === "control" ? "fit" : "control" } as SplineState; - return [ns, { draft: s.phase === "next" ? splineDraft(s.points, s.cursor, s.closed, ns.curveMode) : null }]; + return [ns, { draft: s.phase === "next" ? splineDraft(ctx, s.points, s.cursor, s.closed, ns.curveMode) : null }]; } if (s.phase !== "next") return [s, { draft: null }]; if (input.id === "undo") { @@ -138,20 +121,20 @@ export const splineCommand: Command = { closed: s.closed, curveMode: s.curveMode, }; - return [ns, { draft: splineDraft(pts, s.cursor, s.closed, s.curveMode) }]; + return [ns, { draft: splineDraft(ctx, pts, s.cursor, s.closed, s.curveMode) }]; } if (input.id === "close" && s.points.length >= 3) { const pts = s.points; return [ { phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle, - { draft: null, done: true, commit: opsMutation(() => appendSpline(pts, true, s.curveMode, ctx)) }, + { draft: null, done: true, commit: appendSpline(pts, true, s.curveMode, ctx) }, ]; } - return [s, { draft: splineDraft(s.points, s.cursor, s.closed, s.curveMode) }]; + return [s, { draft: splineDraft(ctx, s.points, s.cursor, s.closed, s.curveMode) }]; } if (input.kind !== "point") { - return [s, { draft: s.phase === "next" ? splineDraft(s.points, s.cursor, s.closed, s.curveMode) : null }]; + return [s, { draft: s.phase === "next" ? splineDraft(ctx, s.points, s.cursor, s.closed, s.curveMode) : null }]; } const pt = input.point; if (s.phase !== "next") { @@ -163,13 +146,13 @@ export const splineCommand: Command = { closed: s.closed, curveMode: s.curveMode, }; - return [ns, { draft: splineDraft([pt], pt, s.closed, s.curveMode) }]; + return [ns, { draft: splineDraft(ctx, [pt], pt, s.closed, s.curveMode) }]; } if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) { const pts = s.points; return [ { phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle, - { draft: null, done: true, commit: opsMutation(() => appendSpline(pts, true, s.curveMode, ctx)) }, + { draft: null, done: true, commit: appendSpline(pts, true, s.curveMode, ctx) }, ]; } const points = [...s.points, pt]; @@ -181,14 +164,14 @@ export const splineCommand: Command = { closed: s.closed, curveMode: s.curveMode, }; - return [ns, { draft: splineDraft(points, pt, s.closed, s.curveMode) }]; + return [ns, { draft: splineDraft(ctx, points, pt, s.closed, s.curveMode) }]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as SplineState; if (s.phase !== "next") return [s, { draft: null }]; const ns: SplineDrawing = { ...s, cursor: point }; - return [ns, { draft: splineDraft(s.points, point, s.closed, s.curveMode) }]; + return [ns, { draft: splineDraft(ctx, s.points, point, s.closed, s.curveMode) }]; }, onConfirm: (state, ctx): [CommandState, CommandResult] => { @@ -198,7 +181,7 @@ export const splineCommand: Command = { const close = s.closed && pts.length >= 3; return [ { phase: "start", lastPoint: null, closed: s.closed, curveMode: s.curveMode } as SplineIdle, - { draft: null, done: true, commit: opsMutation(() => appendSpline(pts, close, s.curveMode, ctx)) }, + { draft: null, done: true, commit: appendSpline(pts, close, s.curveMode, ctx) }, ]; } return idle(s.closed, s.curveMode); diff --git a/src/commands/cmds/stair.tread.test.ts b/src/commands/cmds/stair.tread.test.ts deleted file mode 100644 index ec09600d..00000000 --- a/src/commands/cmds/stair.tread.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Unit-Tests für `stepsFromTread` — Stufenzahl-Ableitung aus Soll-Auftritt + Lauflänge. - * - * Entspricht dem `target_a`-Modus im Rhino-Plugin (_make_treppe_preview_handler, - * Variable `target_a` = Soll-Auftritt). - */ - -import { describe, it, expect } from "vitest"; -import { stepsFromTread } from "./stair"; -import { MIN_STEPS, IDEAL_TREAD } from "../../geometry/stair"; - -describe("stepsFromTread — Grundfälle", () => { - it("ergibt das ideale Soll-Trittmass bei exakter Teilbarkeit", () => { - // 10 × 0.29 m = 2.9 m → 10 Stufen - const steps = stepsFromTread(IDEAL_TREAD, 10 * IDEAL_TREAD); - expect(steps).toBe(10); - }); - - it("rundet auf die nächste ganze Stufenzahl", () => { - // 3.0 / 0.29 ≈ 10.34 → 10 - expect(stepsFromTread(0.29, 3.0)).toBe(10); - // 3.1 / 0.29 ≈ 10.69 → 11 - expect(stepsFromTread(0.29, 3.1)).toBe(11); - }); - - it("bleibt mindestens bei MIN_STEPS", () => { - // Sehr kurze Lauflänge → immer MIN_STEPS (2) - expect(stepsFromTread(0.29, 0.01)).toBe(MIN_STEPS); - }); - - it("klemmt nach oben: Stufenzahl durch 0.24-m-Auftritts-Grenze begrenzt", () => { - // 10 m Lauflänge, Auftritt 0.01 m → raw = 1000, aber durch Clamp auf - // floor(10/0.24)+1 = 42 begrenzt. Der resultierende Auftritt (≈ 0.238 m) - // ist der Grenzwert der floor-Formel aus defaultStepCount — kein echter Bug, - // sondern die bewusste Clamp-Schwelle (≥ min ~ 0.24 m, off-by-one durch +1). - const steps = stepsFromTread(0.01, 10.0); - // Die Stufenzahl muss deutlich kleiner als 1000 sein (Clamp wirkt). - expect(steps).toBeLessThan(100); - expect(steps).toBeGreaterThanOrEqual(MIN_STEPS); - // Auftrittstiefe muss im vernünftigen Bereich liegen (nahe 0.24 m). - const treadDepth = 10.0 / steps; - expect(treadDepth).toBeGreaterThanOrEqual(0.23 - 1e-6); - expect(treadDepth).toBeLessThanOrEqual(0.30); - }); - - it("typische Nutzung: Lauflänge 3 m, Auftritt 0.29 m → ca. 10 Stufen", () => { - const steps = stepsFromTread(0.29, 3.0); - expect(steps).toBeGreaterThanOrEqual(MIN_STEPS); - // Auftrittstiefe nahe am Soll - const tread = 3.0 / steps; - expect(tread).toBeGreaterThan(0.20); - expect(tread).toBeLessThan(0.40); - }); - - it("nullartige Auftritt-Eingabe wird intern auf 0.05 m geklippt", () => { - // Sollte nicht abstürzen, Ergebnis durch 0.24-m-Clamp begrenzt. - const steps = stepsFromTread(0, 3.0); - expect(steps).toBeGreaterThanOrEqual(MIN_STEPS); - }); - - it("negative Lauflänge → MIN_STEPS", () => { - expect(stepsFromTread(0.29, -1)).toBe(MIN_STEPS); - }); - - it("Auftritt 0.25 m, Lauflänge 2.5 m → 10 Stufen (exakt)", () => { - expect(stepsFromTread(0.25, 2.5)).toBe(10); - }); -}); - -describe("stepsFromTread — Grenzwerte / Konsistenz", () => { - it("liefert immer ganze Zahlen", () => { - for (const run of [1.0, 2.5, 3.14, 5.0, 10.0]) { - const steps = stepsFromTread(0.29, run); - expect(Number.isInteger(steps)).toBe(true); - } - }); - - it("resultierender Auftritt liegt stets im erlaubten Bereich (>= 0.24 m)", () => { - for (const run of [1.0, 2.0, 3.0, 5.0]) { - const steps = stepsFromTread(IDEAL_TREAD, run); - const tread = run / steps; - expect(tread).toBeGreaterThanOrEqual(0.24 - 1e-6); - } - }); -}); diff --git a/src/commands/cmds/stair.ts b/src/commands/cmds/stair.ts index 8c55f336..a203f864 100644 --- a/src/commands/cmds/stair.ts +++ b/src/commands/cmds/stair.ts @@ -19,9 +19,8 @@ // // Bezeichner englisch, sichtbarer Text via t() (CONVENTIONS.md). -import type { Stair, StairShape, Vec2 as MVec2 } from "../../model/types"; -import { stairGeometry, defaultStepCount, IDEAL_TREAD, MIN_STEPS } from "../../core"; -import { uniqueId } from "../../tools/types"; +import type { StairShape } from "../../model/types"; +import { IDEAL_TREAD, MIN_STEPS } from "../../core"; import type { Command, CommandContext, @@ -29,18 +28,13 @@ import type { CommandResult, CommandState, CmdOption, - DraftShape, ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview, xy } from "../createCore"; -/** Default-Ebene (Kategorie) für Treppen: „40" Treppen (Fallback: aktive). */ -const STAIR_CATEGORY = "40"; /** Default-Laufbreite (Meter). */ const DEF_WIDTH = 1.0; -const EPS = 1e-6; // ── Trittmass-Modus ────────────────────────────────────────────────────────── /** Trittmass-Modus: „with" = Soll-Auftritt vorgegeben, Stufen abgeleitet; @@ -73,44 +67,6 @@ const stairDefaults: { // ── Vektor-Helfer ───────────────────────────────────────────────────────────── const sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y }); const lenOf = (a: Vec2): number => Math.hypot(a.x, a.y); -const normv = (a: Vec2): Vec2 => { - const l = lenOf(a) || 1e-9; - return { x: a.x / l, y: a.y / l }; -}; - -/** Existiert die Treppen-Kategorie („40")? Sonst Fallback auf die aktive. */ -function stairCategory(ctx: CommandContext): string { - const flat: { code: string }[] = []; - const walk = (list: { code: string; children?: unknown[] }[]) => { - for (const c of list) { - flat.push({ code: c.code }); - if (c.children) walk(c.children as { code: string; children?: unknown[] }[]); - } - }; - walk(ctx.project.layers as { code: string; children?: unknown[] }[]); - return flat.some((c) => c.code === STAIR_CATEGORY) - ? STAIR_CATEGORY - : ctx.defaultCategoryCode; -} - -/** Geschosshöhe als Default-Steighöhe (Fallback 2.6 m). */ -function floorRise(ctx: CommandContext): number { - return ctx.level.floorHeight && ctx.level.floorHeight > 0 ? ctx.level.floorHeight : 2.6; -} - -// ── Trittmass-Ableitung ─────────────────────────────────────────────────────── -/** - * Leitet die Stufenzahl aus Auftritt (Soll-Trittmass) + Lauflänge ab. - * Klemmt auf [MIN_STEPS, maxByRun] (mind. 0.24 m Auftrittstiefe). - * Entspricht dem `target_a`-Modus im Rhino-Plugin (_make_treppe_preview_handler). - */ -export function stepsFromTread(auftritt: number, runLength: number): number { - const a = Math.max(0.05, auftritt); - const raw = Math.round(runLength / a); - // Auftrittstiefe aus Stufenzahl darf nicht unter 0.24 m sinken. - const maxByRun = runLength > 0 ? Math.max(MIN_STEPS, Math.floor(runLength / 0.24) + 1) : raw; - return Math.max(MIN_STEPS, Math.min(raw, maxByRun)); -} // ── Felder (Tab-Zyklus) ─────────────────────────────────────────────────────── /** Tab-Feld: Breite (immer, ab idle). */ @@ -173,78 +129,38 @@ function initState(override?: Partial): StairIdle { } /** - * Baut aus dem Laufzustand ein konkretes `Stair`-Objekt (aufgelöste Felder). Die - * Richtung/Länge folgen aus start→cursor; bei L bricht der zweite Lauf um 90° - * (links) ab, bei Wendel wird der Cursorabstand zum Radius. - * - * Im Trittmass-Modus „mit" wird die Stufenzahl aus dem Soll-Auftritt + der - * aktuellen Lauflänge abgeleitet (stepsFromTread), kein freies steps-Feld. + * Anfrage an den Kern (`cmd_create.rs`): aus dem Laufzustand entsteht dort die Treppe — Richtung/Länge + * aus start→cursor, bei L ein symmetrischer zweiter Lauf, bei Wendel der Cursorabstand als Radius; + * Stufenzahl im Trittmass-Modus „mit“ aus Soll-Auftritt + Lauflänge, sonst gesetzt oder Vorgabe; + * Steighöhe = Geschosshöhe, falls nicht gesetzt; Ebene „40“. */ -function buildStair(s: StairRun, ctx: CommandContext): Stair { - const rise = s.rise ?? floorRise(ctx); - const d = sub(s.cursor, s.start); - const dist = Math.max(0.1, lenOf(d)); - const dir = dist > EPS ? normv(d) : ({ x: 1, y: 0 } as MVec2); - const runLength = s.shape === "spiral" ? Math.max(0.5, dist) : dist; +const stairReq = (s: StairRun) => ({ + cmd: "stair", + shape: s.shape, + up: s.up, + width: s.width, + referenz: s.referenz, + treadMode: s.treadMode, + auftritt: s.auftritt, + steps: s.steps, + rise: s.rise, + start: xy(s.start), + cursor: xy(s.cursor), +}); - // Stufenzahl je Trittmass-Modus: - // „mit Trittmass" → aus Auftritt + Lauflänge ableiten (Soll-Schrittmass). - // „ohne Trittmass" → manuell oder defaultStepCount (heutiges Verhalten). - const steps = - s.treadMode === "with" - ? stepsFromTread(s.auftritt, runLength) - : (s.steps ?? defaultStepCount(rise, runLength)); - - const base: Stair = { - id: uniqueId("ST"), - type: "stair", - floorId: ctx.level.id, - categoryCode: stairCategory(ctx), - shape: s.shape, - start: s.start, - dir, - runLength, - width: s.width, - referenz: s.referenz, - totalRise: rise, - stepCount: steps, - up: s.up, - }; - if (s.shape === "L") { - base.run2Length = runLength; // symmetrischer zweiter Lauf - base.turn = 1; - } else if (s.shape === "spiral") { - base.center = s.start; - base.radius = dist; - base.sweep = 270; - // Startpunkt am äußeren Rand: Lauflinie beginnt hier. - base.start = s.cursor; - base.dir = dir; - } - return base; -} - -/** Vorschau: Tritt-Linien + Lauflinie + HUD (Länge · Stufenanzahl). */ +/** Vorschau: Tritt-Linien + Podest + Lauflinie (Kern) + HUD (Länge · Stufenanzahl). */ function runDraft(s: StairRun, ctx: CommandContext): ToolDraft { - const stair = buildStair(s, ctx); - const rise = stair.totalRise ?? floorRise(ctx); - const geo = stairGeometry(stair, rise); - const preview: DraftShape[] = []; - for (const tr of geo.treads) preview.push({ kind: "poly", pts: tr.pts, closed: true }); - if (geo.landing) preview.push({ kind: "poly", pts: geo.landing, closed: true }); - if (geo.runLine.length >= 2) preview.push({ kind: "poly", pts: geo.runLine, closed: false }); - const draft: ToolDraft = { preview, vertices: [s.start] }; + const pv = createPreview(ctx, stairReq(s), []); + const draft: ToolDraft = { preview: pv.shapes, vertices: [s.start] }; draft.hud = { at: s.cursor, - text: `${lenOf(sub(s.cursor, s.start)).toFixed(2)} m · ${stair.stepCount} STG`, + text: `${lenOf(sub(s.cursor, s.start)).toFixed(2)} m · ${pv.info[0]} STG`, }; return draft; } -/** Hängt eine Treppe ans Projekt (immutabel) und aktualisiert die Defaults. */ -function appendStair(s: StairRun, ctx: CommandContext): CoreOp[] { - const stair = buildStair(s, ctx); - // Zuletzt genutzte Einstellungen für die nächste Treppe merken. +/** Commit der Treppe (Kern) und die Einstellungen für die nächste Treppe merken. */ +function appendStair(s: StairRun, ctx: CommandContext) { stairDefaults.shape = s.shape; stairDefaults.up = s.up; stairDefaults.width = s.width; @@ -253,7 +169,7 @@ function appendStair(s: StairRun, ctx: CommandContext): CoreOp[] { stairDefaults.auftritt = s.auftritt; stairDefaults.steps = s.steps; stairDefaults.rise = s.rise; - return addItems("stairs", [stair]); + return createMutation(ctx, stairReq(s)); } const idle = (from?: StairCmdState): [CommandState, CommandResult] => [ @@ -348,7 +264,7 @@ export const stairCommand: Command = { const ns: StairRun = { ...s, cursor: pt }; return [ idle(s)[0], - { draft: null, done: true, commit: opsMutation(() => appendStair(ns, ctx)) }, + { draft: null, done: true, commit: appendStair(ns, ctx) }, ]; }, @@ -365,7 +281,7 @@ export const stairCommand: Command = { const ns = s; return [ idle(s)[0], - { draft: null, done: true, commit: opsMutation(() => appendStair(ns, ctx)) }, + { draft: null, done: true, commit: appendStair(ns, ctx) }, ]; } return idle(s); diff --git a/src/commands/cmds/terrain.ts b/src/commands/cmds/terrain.ts index 9cb6809c..d6deac39 100644 --- a/src/commands/cmds/terrain.ts +++ b/src/commands/cmds/terrain.ts @@ -11,33 +11,14 @@ // // Bezeichner englisch, sichtbarer Text via t() (Namespace `cmd.terrain.*`). -import { generateTerrainFromContours } from "../../model/terrain"; -import type { ContextObject } from "../../model/types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; -import type { - Command, - CommandResult, - CommandState, - Project, -} from "../types"; +import { createMutation } from "../createCore"; +import type { Command, CommandContext, CommandResult, CommandState } from "../types"; -/** Ops: hängt ein aus dem ersten ContourSet abgeleitetes TIN an `context` an. */ -function terrainOps(p: Project): CoreOp[] { - const context: ContextObject[] = p.context ?? []; - const set = context.find((o) => o.type === "contourSet"); - if (!set || set.type !== "contourSet") return []; - const terrain = generateTerrainFromContours(set.contours); - if (terrain.indices.length === 0) return []; // kein sinnvolles TIN - return addItems("context", [terrain]); -} - -/** Ergebnis, das den Befehl sofort beendet und das TIN committet. */ -const COMMIT_DONE: CommandResult = { - draft: null, - done: true, - commit: opsMutation(terrainOps), -}; +/** + * Ergebnis, das den Befehl sofort beendet und das TIN committet (Kern, `cmd_solid.rs`: erstes + * ContourSet aus `context` → Delaunay-TIN; ohne sinnvolles TIN nichts). + */ +const commitDone = (ctx: CommandContext): CommandResult => ({ draft: null, done: true, commit: createMutation(ctx, { cmd: "terrain" }) }); const IDLE: CommandState = { phase: "idle", lastPoint: null }; @@ -51,10 +32,10 @@ export const terrainCommand: Command = { init: () => ({ ...IDLE }), // Jeglicher Input beendet den Befehl mit dem Commit (es gibt keine Schritte). - onInput: (): [CommandState, CommandResult] => [{ ...IDLE }, COMMIT_DONE], + onInput: (_s, _i, ctx): [CommandState, CommandResult] => [{ ...IDLE }, commitDone(ctx)], onMove: (state): [CommandState, CommandResult] => [state, { draft: null }], // Enter/Space/Rechtsklick: Gelände erzeugen + beenden. - onConfirm: (): [CommandState, CommandResult] => [{ ...IDLE }, COMMIT_DONE], + onConfirm: (_s, ctx): [CommandState, CommandResult] => [{ ...IDLE }, commitDone(ctx)], onCancel: (): [CommandState, CommandResult] => [ { ...IDLE }, { draft: null, done: true }, diff --git a/src/commands/cmds/text.ts b/src/commands/cmds/text.ts index ec306206..055696fd 100644 --- a/src/commands/cmds/text.ts +++ b/src/commands/cmds/text.ts @@ -8,30 +8,18 @@ // Wortumbruch-Textfeld). Bleibt der Editor leer, verwirft `commitTextEdit` // (App.tsx) das Element wieder. -import type { Drawing2D } from "../../model/types"; import { uniqueId } from "../../tools/types"; import type { Command, CommandContext, CommandResult, CommandState, Vec2 } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation } from "../createCore"; -/** Default-Schrifthöhe eines frei platzierten Texts in Modell-Metern. */ -const DEFAULT_TEXT_HEIGHT_M = 0.25; interface TextIdle extends CommandState { phase: "point"; } type TextState = TextIdle; -function appendEmptyText(id: string, at: Vec2, ctx: CommandContext): CoreOp[] { - const d: Drawing2D = { - id, - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "text", at, text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0 }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern, `cmd_draw.rs`): leere Textzeile am Anker (Höhe 0.25 m), mit vorab vergebener id. */ +const appendEmptyText = (id: string, at: Vec2, ctx: CommandContext) => createMutation(ctx, { cmd: "text", id, at }); const idle = (): [CommandState, CommandResult] => [ { phase: "point", lastPoint: null } as TextIdle, @@ -56,7 +44,7 @@ export const textCommand: Command = { { draft: null, done: true, - commit: opsMutation(() => appendEmptyText(id, at, ctx)), + commit: appendEmptyText(id, at, ctx), focusDrawingId: id, }, ]; diff --git a/src/commands/cmds/textbox.ts b/src/commands/cmds/textbox.ts index c823c142..609ab8ad 100644 --- a/src/commands/cmds/textbox.ts +++ b/src/commands/cmds/textbox.ts @@ -19,7 +19,6 @@ // Wortumbruch) — die Höhe bleibt reine Editor-Startgrösse (PlanView-lokal, // s. focusMinHeightM), die Textmenge bestimmt die tatsächliche Höhe. -import type { Drawing2D } from "../../model/types"; import { uniqueId } from "../../tools/types"; import type { Command, @@ -29,13 +28,8 @@ import type { DraftShape, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview } from "../createCore"; -/** Default-Schrifthöhe einer Textspalte in Modell-Metern (= Baseline-Versatz vom Rahmen-Top). */ -const DEFAULT_TEXT_HEIGHT_M = 0.25; -/** Kleinste sinnvolle Rahmen-Breite/-Höhe (Meter). */ -const MIN_SIZE_M = 0.2; interface TbFirst extends CommandState { phase: "first"; @@ -48,53 +42,23 @@ interface TbSecond extends CommandState { type TbState = TbFirst | TbSecond; /** Normalisiertes Rechteck aus zwei diagonalen Punkten (beliebige Zugrichtung). */ -function rectOf(a: Vec2, b: Vec2): { minX: number; maxX: number; minY: number; maxY: number } { +/** + * Textrahmen im Kern (`cmd_draw.rs`): Rechteck aus zwei Ecken, Breite/Höhe mindestens 0.2 m + * (`info = [Breite, Höhe]`), Anker oben links eine Zeilenhöhe tief. + */ +function frameDraft(ctx: CommandContext, a: Vec2, cursor: Vec2): { preview: DraftShape[]; vertices: Vec2[]; hud: { at: Vec2; text: string } } { + const pv = createPreview(ctx, { cmd: "textbox" }, [a, cursor]); + const [w, h] = pv.info; return { - minX: Math.min(a.x, b.x), - maxX: Math.max(a.x, b.x), - minY: Math.min(a.y, b.y), - maxY: Math.max(a.y, b.y), - }; -} - -/** Breite/Höhe (geklemmt auf MIN_SIZE_M) + die Textanker-Position (oben-links, als Baseline). */ -function frameOf(a: Vec2, b: Vec2): { at: Vec2; width: number; heightM: number } { - const r = rectOf(a, b); - const width = Math.max(MIN_SIZE_M, r.maxX - r.minX); - const heightM = Math.max(MIN_SIZE_M, r.maxY - r.minY); - // `at` ist die Baseline-links der ERSTEN Zeile (s. plan/drawings.rs/primitives.tsx); - // die Rahmen-Oberkante liegt eine Zeilenhöhe darüber → at.y = Rahmen-Top − Zeilenhöhe. - return { at: { x: r.minX, y: r.maxY - DEFAULT_TEXT_HEIGHT_M }, width, heightM }; -} - -/** Vorschau: Rahmen-Rechteck zwischen den beiden Ecken. */ -function frameDraft(a: Vec2, cursor: Vec2): { preview: DraftShape[]; vertices: Vec2[]; hud: { at: Vec2; text: string } } { - const r = rectOf(a, cursor); - const pts: Vec2[] = [ - { x: r.minX, y: r.minY }, - { x: r.maxX, y: r.minY }, - { x: r.maxX, y: r.maxY }, - { x: r.minX, y: r.maxY }, - ]; - const w = Math.max(MIN_SIZE_M, r.maxX - r.minX); - const h = Math.max(MIN_SIZE_M, r.maxY - r.minY); - return { - preview: [{ kind: "poly", pts, closed: true }], + preview: pv.shapes, vertices: [a, cursor], hud: { at: cursor, text: `${w.toFixed(2)} × ${h.toFixed(2)} m` }, }; } -function appendEmptyTextbox(id: string, at: Vec2, width: number, ctx: CommandContext): CoreOp[] { - const d: Drawing2D = { - id, - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "text", at, text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0, width }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern): leere Textspalte (Breite des Rahmens), mit vorab vergebener id. */ +const appendEmptyTextbox = (id: string, a: Vec2, b: Vec2, ctx: CommandContext) => + createMutation(ctx, { cmd: "textbox", id, a, b }); const idle = (): [CommandState, CommandResult] => [ { phase: "first", lastPoint: null } as TbFirst, @@ -117,25 +81,25 @@ export const textboxCommand: Command = { return [ns, { draft: { preview: [], vertices: [input.point] } }]; } // phase === "second" - const { at, width, heightM } = frameOf(s.a, input.point); + const heightM = createPreview(ctx, { cmd: "textbox" }, [s.a, input.point]).info[1]; const id = uniqueId("dr2d"); return [ { phase: "first", lastPoint: null } as TbFirst, { draft: null, done: true, - commit: opsMutation(() => appendEmptyTextbox(id, at, width, ctx)), + commit: appendEmptyTextbox(id, s.a, input.point, ctx), focusDrawingId: id, focusMinHeightM: heightM, }, ]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as TbState; if (s.phase !== "second") return [s, { draft: null }]; const ns: TbSecond = { ...s, cursor: point }; - return [ns, { draft: frameDraft(s.a, point) }]; + return [ns, { draft: frameDraft(ctx, s.a, point) }]; }, onConfirm: (): [CommandState, CommandResult] => idle(), diff --git a/src/commands/cmds/textpath.ts b/src/commands/cmds/textpath.ts index 00b8bd9c..1ad6ddaa 100644 --- a/src/commands/cmds/textpath.ts +++ b/src/commands/cmds/textpath.ts @@ -6,7 +6,6 @@ // 1) „Pfadpunkt:" → Punkt // 2) „Nächster Pfadpunkt ( Fertig ):" → Punkt … Enter beendet (≥2 Punkte nötig) -import type { Drawing2D } from "../../model/types"; import { segmentHud, uniqueId } from "../../tools/types"; import type { Command, @@ -18,12 +17,10 @@ import type { ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation } from "../createCore"; const EPS = 1e-6; const DEG = Math.PI / 180; -const DEFAULT_TEXT_HEIGHT_M = 0.25; const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); const segAngleDeg = (a: Vec2, b: Vec2): number => (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI; @@ -60,16 +57,8 @@ function pathDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { return draft; } -function appendEmptyTextPath(id: string, pts: Vec2[], ctx: CommandContext): CoreOp[] { - const d: Drawing2D = { - id, - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "text", at: pts[0], text: "", height: DEFAULT_TEXT_HEIGHT_M, angle: 0, pathPts: pts }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern, `cmd_draw.rs`): leerer Text entlang des Pfads (Anker = erster Pfadpunkt), vorab vergebene id. */ +const appendEmptyTextPath = (id: string, pts: Vec2[], ctx: CommandContext) => createMutation(ctx, { cmd: "textpath", id, pts }); const idle = (): [CommandState, CommandResult] => [ { phase: "start", lastPoint: null } as TpIdle, @@ -78,7 +67,7 @@ const idle = (): [CommandState, CommandResult] => [ function commitPath(pts: Vec2[], ctx: CommandContext): CommandResult { const id = uniqueId("dr2d"); - return { draft: null, done: true, commit: opsMutation(() => appendEmptyTextPath(id, pts, ctx)), focusDrawingId: id }; + return { draft: null, done: true, commit: appendEmptyTextPath(id, pts, ctx), focusDrawingId: id }; } export const textpathCommand: Command = { diff --git a/src/commands/cmds/voidbox.test.ts b/src/commands/cmds/voidbox.test.ts index 41517a7d..97ea4549 100644 --- a/src/commands/cmds/voidbox.test.ts +++ b/src/commands/cmds/voidbox.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { sampleProject } from "../../model/sampleProject"; import type { CommandContext } from "../types"; -import { voidBoxCommand, voidFromInputs } from "./voidbox"; +import { voidBoxCommand } from "./voidbox"; const ctx = { project: sampleProject, level: { id: "eg" } } as unknown as CommandContext; @@ -20,7 +20,15 @@ describe("Durchbruch", () => { expect(v.points).toHaveLength(4); }); it("entartete Eingaben ergeben nichts", () => { - expect(voidFromInputs("eg", { x: 0, y: 0 }, { x: 0, y: 1 }, 1, 0)).toBeNull(); - expect(voidFromInputs("eg", { x: 0, y: 0 }, { x: 1, y: 1 }, 0, 0)).toBeNull(); + const ops = (a: { x: number; y: number }, b: { x: number; y: number }, h: number) => { + let st = voidBoxCommand.init(); + [st] = voidBoxCommand.onInput(st, { kind: "point", point: a }, ctx); + [st] = voidBoxCommand.onInput(st, { kind: "point", point: b }, ctx); + [st] = voidBoxCommand.onInput(st, { kind: "number", value: h }, ctx); + const [, res] = voidBoxCommand.onInput(st, { kind: "number", value: 0 }, ctx); + return res.commit!.toOps(sampleProject); + }; + expect(ops({ x: 0, y: 0 }, { x: 0, y: 1 }, 1)).toEqual([]); + expect(ops({ x: 0, y: 0 }, { x: 1, y: 1 }, 1)).toHaveLength(1); }); }); diff --git a/src/commands/cmds/voidbox.ts b/src/commands/cmds/voidbox.ts index ea9bfe90..1201c07f 100644 --- a/src/commands/cmds/voidbox.ts +++ b/src/commands/cmds/voidbox.ts @@ -5,10 +5,8 @@ // Schritte: Ecke → Gegenecke → Höhe → Abstand über Geschoss-UK (Zahl tippen; Enter = 0). // Beliebige Profile: Polylinie extrudieren und im Objekt-Panel „Abzugskörper" setzen. -import type { ExtrudedSolid } from "../../model/types"; -import { addItems, opsMutation } from "../../core"; -import { uniqueId } from "../../tools/types"; -import type { Command, CommandResult, CommandState, ToolDraft, Vec2 } from "../types"; +import type { Command, CommandContext, CommandResult, CommandState, ToolDraft, Vec2 } from "../types"; +import { createMutation, createPreview } from "../createCore"; type Step = "corner" | "corner2" | "height" | "offset"; @@ -24,36 +22,12 @@ interface VoidState extends CommandState { let lastHeight = 0.3; let lastOffset = 1.0; -const rectPts = (a: Vec2, b: Vec2): Vec2[] => { - const [x0, x1] = [Math.min(a.x, b.x), Math.max(a.x, b.x)]; - const [y0, y1] = [Math.min(a.y, b.y), Math.max(a.y, b.y)]; - return [{ x: x0, y: y0 }, { x: x1, y: y0 }, { x: x1, y: y1 }, { x: x0, y: y1 }]; -}; - -/** Abzugskörper aus den Eingaben (reiner Kern, getestet). */ -export function voidFromInputs(levelId: string, a: Vec2, b: Vec2, height: number, offset: number): ExtrudedSolid | null { - if (Math.abs(b.x - a.x) < 1e-6 || Math.abs(b.y - a.y) < 1e-6 || !(height > 1e-6)) return null; - return { - id: uniqueId("void"), - type: "extrudedSolid", - levelId, - points: rectPts(a, b), - height, - operation: "subtract", - ...(Math.abs(offset) > 1e-9 ? { baseOffset: offset } : {}), - }; -} - -function draftOf(s: VoidState): ToolDraft | null { +/** Vorschau (Kern): Rechteck mit Diagonalen + HUD (Masse bzw. Höhe/Versatz). */ +function draftOf(ctx: CommandContext, s: VoidState): ToolDraft | null { if (!s.p0) return null; const b = s.p1 ?? s.cursor ?? s.p0; - const pts = rectPts(s.p0, b); return { - preview: [ - { kind: "poly", pts, closed: true }, - { kind: "line", a: pts[0], b: pts[2] }, - { kind: "line", a: pts[1], b: pts[3] }, - ], + preview: createPreview(ctx, { cmd: "voidbox" }, [s.p0, b]).shapes, vertices: [s.p0], hud: { at: b, @@ -76,17 +50,11 @@ const PROMPT: Record = { offset: "cmd.void.offset", }; -function finish(s: VoidState, offset: number, levelId: string): [CommandState, CommandResult] { +/** Commit (Kern, `cmd_solid.rs`): Aussparungs-Quader (subtrahierender Körper) mit Versatz über der UK. */ +function finish(s: VoidState, offset: number, ctx: CommandContext): [CommandState, CommandResult] { lastOffset = offset; - const solid = s.p0 && s.p1 && s.height ? voidFromInputs(levelId, s.p0, s.p1, s.height, offset) : null; - return [ - reset(), - { - draft: null, - done: true, - commit: opsMutation(() => (solid ? addItems("extrudedSolids", [solid]) : [])), - }, - ]; + // Unvollständige Eingaben (ohne Ecken/Höhe) ergeben im Kern nichts. + return [reset(), { draft: null, done: true, commit: createMutation(ctx, { cmd: "voidbox", a: s.p0, b: s.p1, height: s.height, offset }) }]; } export const voidBoxCommand: Command = { @@ -102,25 +70,25 @@ export const voidBoxCommand: Command = { const s = state as VoidState; if (s.step === "corner" && input.kind === "point") { const ns: VoidState = { ...s, step: "corner2", p0: input.point, cursor: input.point, lastPoint: input.point }; - return [ns, { draft: draftOf(ns) }]; + return [ns, { draft: draftOf(ctx, ns) }]; } if (s.step === "corner2" && input.kind === "point") { const ns: VoidState = { ...s, step: "height", p1: input.point }; - return [ns, { draft: draftOf(ns) }]; + return [ns, { draft: draftOf(ctx, ns) }]; } if (s.step === "height" && input.kind === "number" && input.value > 0) { lastHeight = input.value; const ns: VoidState = { ...s, step: "offset", height: input.value }; - return [ns, { draft: draftOf(ns) }]; + return [ns, { draft: draftOf(ctx, ns) }]; } - if (s.step === "offset" && input.kind === "number") return finish(s, input.value, ctx.level.id); - return [s, { draft: draftOf(s) }]; + if (s.step === "offset" && input.kind === "number") return finish(s, input.value, ctx); + return [s, { draft: draftOf(ctx, s) }]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as VoidState; const ns: VoidState = { ...s, cursor: point }; - return [ns, { draft: draftOf(ns) }]; + return [ns, { draft: draftOf(ctx, ns) }]; }, // Enter übernimmt die letzten Werte (Höhe bzw. Abstand). @@ -128,9 +96,9 @@ export const voidBoxCommand: Command = { const s = state as VoidState; if (s.step === "height") { const ns: VoidState = { ...s, step: "offset", height: lastHeight }; - return [ns, { draft: draftOf(ns) }]; + return [ns, { draft: draftOf(ctx, ns) }]; } - if (s.step === "offset") return finish(s, lastOffset, ctx.level.id); + if (s.step === "offset") return finish(s, lastOffset, ctx); return [reset(), { draft: null, done: true }]; }, onCancel: (): [CommandState, CommandResult] => [reset(), { draft: null, done: true }], diff --git a/src/commands/cmds/wall.ts b/src/commands/cmds/wall.ts index 6ee35578..0f73184f 100644 --- a/src/commands/cmds/wall.ts +++ b/src/commands/cmds/wall.ts @@ -15,10 +15,7 @@ // • floorId ← ctx.level.id (aktives Geschoss) // • categoryCode← ctx.defaultCategoryCode (aktive Kategorie, i. d. R. „20") -import type { Wall, WallType } from "../../model/types"; -import { wallTypeThickness } from "../../model/types"; -import { wallCorners } from "../../model/geometry"; -import { segmentHud, uniqueId } from "../../tools/types"; +import { segmentHud } from "../../tools/types"; import type { Command, CommandContext, @@ -27,17 +24,13 @@ import type { CommandState, CmdOption, DraftShape, - Project, ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview, xy } from "../createCore"; const EPS = 1e-6; const DEG = Math.PI / 180; -const DEFAULT_HEIGHT = 2.6; // Fallback-Wandhöhe (Meter), wenn das Geschoss keine hat -const DEFAULT_THICKNESS = 0.2; // Fallback-Banddicke für die Vorschau (Meter) const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); const segAngleDeg = (a: Vec2, b: Vec2): number => (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI; @@ -61,74 +54,14 @@ function wallNextFromFields(last: Vec2, locks: Record, cursor: V return { x: last.x + Math.cos(ang) * length, y: last.y + Math.sin(ang) * length }; } -/** - * Dicke des aktiven Wandtyps (für die Band-Vorschau). Liest `ctx.activeWallTypeId`; - * fehlt der Typ, Fallback auf den ersten Projekt-Wandtyp bzw. DEFAULT_THICKNESS. - */ -function activeWallThickness(ctx: CommandContext): number { +/** Einschichtig? Nur dann ist das Dicke-Feld sinnvoll (überschreibt die Schicht). */ +function isSingleLayer(ctx: CommandContext): boolean { const wt = ctx.project.wallTypes.find((t) => t.id === ctx.activeWallTypeId) ?? ctx.project.wallTypes[0]; - return wt ? wallTypeThickness(wt) : DEFAULT_THICKNESS; -} - -/** Aktives Wandtyp-Objekt (Fallback: erster Projekt-Wandtyp). */ -function activeWallType(ctx: CommandContext): WallType | undefined { - return ( - ctx.project.wallTypes.find((t) => t.id === ctx.activeWallTypeId) ?? - ctx.project.wallTypes[0] - ); -} - -/** Aktiver Wandtyp-ID; Fallback auf den ersten Projekt-Wandtyp. */ -function activeWallTypeId(ctx: CommandContext): string { - const wt = activeWallType(ctx); - return wt ? wt.id : ctx.activeWallTypeId; -} - -/** Einschichtig? Nur dann ist das Dicke-Feld sinnvoll (überschreibt die Schicht). */ -function isSingleLayer(ctx: CommandContext): boolean { - const wt = activeWallType(ctx); return !!wt && wt.layers.length === 1; } -/** - * Liefert die effektive Vorschau-/Commit-Dicke: eine gelockte `thick`-Eingabe - * (nur bei einschichtigen Typen) überschreibt die Wandtyp-Dicke. - */ -function effectiveThickness(ctx: CommandContext, override: number | null): number { - if (override != null && override >= MIN_THICKNESS && isSingleLayer(ctx)) return override; - return activeWallThickness(ctx); -} - -/** - * Findet einen einschichtigen Wandtyp mit gegebener Dicke (gleiches Bauteil wie - * `base`) oder erzeugt ihn. Gibt das (evtl. erweiterte) Projekt + die Typ-ID - * zurück — so bleibt die Plan-/3D-Darstellung unverändert (sie liest die Dicke - * aus den Schichten des Wandtyps). - */ -function wallTypeForThickness( - p: Project, - base: WallType, - thickness: number, -): { ops: CoreOp[]; wallTypeId: string } { - const componentId = base.layers[0].componentId; - const near = (a: number, b: number) => Math.abs(a - b) < 1e-4; - const existing = p.wallTypes.find( - (t) => - t.layers.length === 1 && - t.layers[0].componentId === componentId && - near(t.layers[0].thickness, thickness), - ); - if (existing) return { ops: [], wallTypeId: existing.id }; - const nt: WallType = { - id: uniqueId("WT"), - name: `${base.name} ${(thickness * 100).toFixed(0)} cm`, - layers: [{ componentId, thickness }], - }; - return { ops: addItems("wallTypes", [nt]), wallTypeId: nt.id }; -} - interface WallIdle extends CommandState { phase: "start"; /** Sticky Dicke-Übersteuerung (nur einschichtig); null = Wandtyp-Dicke. */ @@ -150,75 +83,40 @@ type WallCmdState = WallIdle | WallDrawing; const UNDO: CmdOption = { id: "undo", labelKey: "cmd.polyline.undo" }; /** - * Vorschau: Achs-Polylinie + Band-Vorschau je Segment (Dicke = aktiver Wandtyp) + - * HUD (Länge·Winkel des lebenden Segments). Die FERTIGE Wand rendert über die + * Bänder der schon gesetzten Segmente: sie ändern sich je Mausschritt nicht und werden nur neu gerechnet, + * wenn sich Punkte, Dicke, Projekt oder Wandtyp ändern — je Mausschritt rechnet der Kern nur das lebende + * Segment (gleich schnell bei langen Wandzügen). + */ +let fixedCache: { points: Vec2[]; thick: number | null; project: unknown; wallType: string; shapes: DraftShape[] } | null = null; + +function fixedShapes(ctx: CommandContext, points: Vec2[], thick: number | null): DraftShape[] { + const c = fixedCache; + if (c && c.points === points && c.thick === thick && c.project === ctx.project && c.wallType === ctx.activeWallTypeId) return c.shapes; + const shapes = points.length >= 2 ? createPreview(ctx, { cmd: "wall", thick }, points).shapes : []; + fixedCache = { points, thick, project: ctx.project, wallType: ctx.activeWallTypeId, shapes }; + return shapes; +} + +/** + * Vorschau: Band (Dicke = aktiver Wandtyp bzw. gelockte Dicke) + Achse je Segment, gerechnet im Kern + * (`cmd_create.rs`), dazu HUD (Länge·Winkel des lebenden Segments). Die FERTIGE Wand rendert über die * bestehende Wand-Darstellung — hier ist nur der Rubber-Band-Entwurf. */ -function wallDraft(points: Vec2[], cursor: Vec2 | null, thickness: number): ToolDraft { - const all = cursor ? [...points, cursor] : points; - const preview: DraftShape[] = []; - for (let i = 0; i < all.length - 1; i++) { - const a = all[i]; - const b = all[i + 1]; - if (segLen(a, b) < EPS) continue; - preview.push({ kind: "poly", pts: wallCorners(a, b, thickness), closed: true }); - preview.push({ kind: "line", a, b }); // Achse - } - const draft: ToolDraft = { preview, vertices: points }; +function wallDraft(ctx: CommandContext, points: Vec2[], cursor: Vec2 | null, thick: number | null): ToolDraft { + const fixed = fixedShapes(ctx, points, thick); + const live = cursor && points.length ? createPreview(ctx, { cmd: "wall", thick }, [points[points.length - 1], cursor]).shapes : []; + const draft: ToolDraft = { preview: live.length ? [...fixed, ...live] : fixed, vertices: points }; const last = points[points.length - 1]; if (cursor && last && segLen(last, cursor) >= EPS) draft.hud = segmentHud(last, cursor); return draft; } /** - * Hängt je Achssegment ein `Wall` des aktiven Typs ans Projekt (immutabel). Höhe - * aus dem aktiven Geschoss (floorHeight), Geschoss + Kategorie + Wandtyp aus dem - * Context. Null-Strecken werden übersprungen. Gehrung an Ecken entsteht später - * automatisch aus der Verschneidung im Kern (`joins.rs`). + * Commit: je Achssegment eine Wand des aktiven Typs (Höhe aus dem Geschoss); eine gelockte Dicke + * (einschichtig) wählt/erzeugt den passenden Wandtyp — beides im Kern (`cmd_create.rs`). */ -function appendWalls( - p: Project, - pts: Vec2[], - ctx: CommandContext, - thickOverride: number | null, -): CoreOp[] { - const height = - ctx.level.floorHeight && ctx.level.floorHeight > 0 ? ctx.level.floorHeight : DEFAULT_HEIGHT; - // Dicke-Übersteuerung (nur einschichtig): passenden Wandtyp finden/erzeugen, - // damit Plan/3D — die die Dicke aus dem Wandtyp lesen — korrekt darstellen. - let typeOps: CoreOp[] = []; - let wallTypeId = activeWallTypeId(ctx); - const base = activeWallType(ctx); - if ( - base && - base.layers.length === 1 && - thickOverride != null && - thickOverride >= MIN_THICKNESS && - Math.abs(thickOverride - wallTypeThickness(base)) > 1e-4 - ) { - const r = wallTypeForThickness(p, base, thickOverride); - typeOps = r.ops; - wallTypeId = r.wallTypeId; - } - const newWalls: Wall[] = []; - for (let i = 0; i < pts.length - 1; i++) { - const a = pts[i]; - const b = pts[i + 1]; - if (segLen(a, b) < EPS) continue; - newWalls.push({ - id: uniqueId("W"), - type: "wall", - floorId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - start: a, - end: b, - wallTypeId, - height, - }); - } - if (newWalls.length === 0) return []; - return [...typeOps, ...addItems("walls", newWalls)]; -} +const appendWalls = (pts: Vec2[], ctx: CommandContext, thick: number | null) => + createMutation(ctx, { cmd: "wall", pts: pts.map(xy), thick }); const idle = ( thickOverride: number | null = null, @@ -244,7 +142,6 @@ export const wallCommand: Command = { onInput: (state, input, ctx): [CommandState, CommandResult] => { const s = state as WallCmdState; - const thickness = effectiveThickness(ctx, s.thickOverride); const to = s.thickOverride; const single = isSingleLayer(ctx); @@ -262,35 +159,35 @@ export const wallCommand: Command = { thickOverride: to, single, }; - return [ns, { draft: wallDraft(pts, s.cursor, thickness) }]; + return [ns, { draft: wallDraft(ctx, pts, s.cursor, to) }]; } - return [{ ...s, single } as WallCmdState, { draft: wallDraft(s.points, s.cursor, thickness) }]; + return [{ ...s, single } as WallCmdState, { draft: wallDraft(ctx, s.points, s.cursor, to) }]; } if (input.kind !== "point") { - return [{ ...s, single } as WallCmdState, { draft: s.phase === "next" ? wallDraft(s.points, s.cursor, thickness) : null }]; + return [{ ...s, single } as WallCmdState, { draft: s.phase === "next" ? wallDraft(ctx, s.points, s.cursor, to) : null }]; } const pt = input.point; if (s.phase !== "next") { const ns: WallDrawing = { phase: "next", points: [pt], cursor: pt, lastPoint: pt, thickOverride: to, single }; - return [ns, { draft: wallDraft([pt], pt, thickness) }]; + return [ns, { draft: wallDraft(ctx, [pt], pt, to) }]; } // Chaining: jede weitere Wand beginnt am letzten Endpunkt. Null-Strecke // (Klick auf denselben Punkt) ignorieren — nicht abbrechen. const last = s.points[s.points.length - 1]; if (segLen(last, pt) < EPS) { - return [{ ...s, single } as WallCmdState, { draft: wallDraft(s.points, s.cursor, thickness) }]; + return [{ ...s, single } as WallCmdState, { draft: wallDraft(ctx, s.points, s.cursor, to) }]; } const points = [...s.points, pt]; const ns: WallDrawing = { phase: "next", points, cursor: pt, lastPoint: pt, thickOverride: to, single }; - return [ns, { draft: wallDraft(points, pt, thickness) }]; + return [ns, { draft: wallDraft(ctx, points, pt, to) }]; }, onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as WallCmdState; if (s.phase !== "next") return [s, { draft: null }]; const ns: WallDrawing = { ...s, cursor: point, single: isSingleLayer(ctx) }; - return [ns, { draft: wallDraft(s.points, point, effectiveThickness(ctx, s.thickOverride)) }]; + return [ns, { draft: wallDraft(ctx, s.points, point, s.thickOverride) }]; }, // Enter/Space/Rechtsklick: offenen Zug beenden (≥2 Punkte) und committen. @@ -301,7 +198,7 @@ export const wallCommand: Command = { const to = s.thickOverride; return [ { phase: "start", lastPoint: null, thickOverride: to, single: s.single } as WallIdle, - { draft: null, done: true, commit: opsMutation((p) => appendWalls(p, pts, ctx, to)) }, + { draft: null, done: true, commit: appendWalls(pts, ctx, to) }, ]; } return idle(s.thickOverride, s.single); diff --git a/src/commands/cmds/wipeout.ts b/src/commands/cmds/wipeout.ts index 2450767c..901e7158 100644 --- a/src/commands/cmds/wipeout.ts +++ b/src/commands/cmds/wipeout.ts @@ -21,8 +21,7 @@ // Attribute-Panel wie bei jeder anderen Fläche nachträglich änderbar (kein // Sonderfall, nur ein sinnvoller Default). -import type { Drawing2D } from "../../model/types"; -import { segmentHud, uniqueId } from "../../tools/types"; +import { segmentHud } from "../../tools/types"; import type { Command, CommandContext, @@ -32,12 +31,10 @@ import type { ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation } from "../createCore"; const EPS = 1e-6; const CLOSE_HIT = 0.15; // Modell-Meter: Klick nahe Startpunkt schliesst den Zug -const MASK_COLOR = "#ffffff"; // Deckt wie Papier ab — Fläche UND Rand (unsichtbare Kontur) const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); @@ -60,18 +57,8 @@ function wipeoutDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { return draft; } -function appendWipeout(points: Vec2[], ctx: CommandContext): CoreOp[] { - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "polyline", pts: points, closed: true }, - background: MASK_COLOR, - color: MASK_COLOR, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern): geschlossene Polylinie, Fläche und Rand weiss (deckt wie Papier ab). */ +const appendWipeout = (points: Vec2[], ctx: CommandContext) => createMutation(ctx, { cmd: "wipeout", pts: points }); const idle = (): [CommandState, CommandResult] => [ { phase: "start", lastPoint: null } as WipeoutIdle, @@ -101,7 +88,7 @@ export const wipeoutCommand: Command = { // Klick nahe Startpunkt (≥3 Punkte) → schliessen (committet). if (s.points.length >= 3 && segLen(s.points[0], pt) < CLOSE_HIT) { const pts = s.points; - return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendWipeout(pts, ctx)) }]; + return [idle()[0], { draft: null, done: true, commit: appendWipeout(pts, ctx) }]; } const points = [...s.points, pt]; const ns: WipeoutDrawing = { phase: "next", points, cursor: pt, lastPoint: pt }; @@ -121,7 +108,7 @@ export const wipeoutCommand: Command = { const s = state as WipeoutState; if (s.phase === "next" && s.points.length >= 3) { const pts = s.points; - return [idle()[0], { draft: null, done: true, commit: opsMutation(() => appendWipeout(pts, ctx)) }]; + return [idle()[0], { draft: null, done: true, commit: appendWipeout(pts, ctx) }]; } return idle(); }, diff --git a/src/commands/cmds/xline.ts b/src/commands/cmds/xline.ts index cb5d1d13..e0c0c922 100644 --- a/src/commands/cmds/xline.ts +++ b/src/commands/cmds/xline.ts @@ -5,8 +5,7 @@ // 1) „Startpunkt:" → Punkt // 2) „Richtungspunkt:" → Punkt (Tab-Felder Länge/Winkel wie bei Line) → commit -import type { Drawing2D } from "../../model/types"; -import { segmentHud, uniqueId } from "../../tools/types"; +import { segmentHud } from "../../tools/types"; import type { Command, CommandContext, @@ -17,12 +16,10 @@ import type { ToolDraft, Vec2, } from "../types"; -import { addItems, opsMutation } from "../../core"; -import type { CoreOp } from "../../core"; +import { createMutation, createPreview } from "../createCore"; const EPS = 1e-6; const DEG = Math.PI / 180; -const XLINE_PREVIEW_EXT_M = 30; // nur für die Live-Vorschau — echte Länge kommt aus generatePlan const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); const segAngleDeg = (a: Vec2, b: Vec2): number => (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI; @@ -51,32 +48,16 @@ interface XlineDrawing extends CommandState { type XlineState = XlineIdle | XlineDrawing; /** Vorschau: kurzes Segment PLUS Verlängerung in beide Richtungen (deutet „unendlich" an). */ -function xlineDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { - const preview: DraftShape[] = []; - if (cursor && segLen(a, cursor) >= EPS) { - const ux = (cursor.x - a.x) / segLen(a, cursor); - const uy = (cursor.y - a.y) / segLen(a, cursor); - preview.push({ - kind: "line", - a: { x: a.x - ux * XLINE_PREVIEW_EXT_M, y: a.y - uy * XLINE_PREVIEW_EXT_M }, - b: { x: cursor.x + ux * XLINE_PREVIEW_EXT_M, y: cursor.y + uy * XLINE_PREVIEW_EXT_M }, - }); - } +function xlineDraft(ctx: CommandContext, a: Vec2, cursor: Vec2 | null): ToolDraft { + // Vorschau (Kern): beidseitig um 30 m verlängert — die echte Länge kommt aus der Plan-Ableitung. + const preview: DraftShape[] = cursor ? createPreview(ctx, { cmd: "xline" }, [a, cursor]).shapes : []; const draft: ToolDraft = { preview, vertices: [a] }; if (cursor && segLen(a, cursor) >= EPS) draft.hud = segmentHud(a, cursor); return draft; } -function appendXline(a: Vec2, b: Vec2, ctx: CommandContext): CoreOp[] { - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "xline", a, b }, - }; - return addItems("drawings2d", [d]); -} +/** Commit (Kern, `cmd_draw.rs`): Konstruktionslinie durch a, b. */ +const appendXline = (a: Vec2, b: Vec2, ctx: CommandContext) => createMutation(ctx, { cmd: "xline", a, b }); export const xlineCommand: Command = { name: "xline", @@ -88,11 +69,11 @@ export const xlineCommand: Command = { onInput: (state, input, ctx): [CommandState, CommandResult] => { const s = state as XlineState; - if (input.kind !== "point") return [s, { draft: s.phase === "end" ? xlineDraft(s.a, s.cursor) : null }]; + if (input.kind !== "point") return [s, { draft: s.phase === "end" ? xlineDraft(ctx, s.a, s.cursor) : null }]; const pt = input.point; if (s.phase !== "end") { const next: XlineDrawing = { phase: "end", a: pt, cursor: pt, lastPoint: pt }; - return [next, { draft: xlineDraft(pt, pt) }]; + return [next, { draft: xlineDraft(ctx, pt, pt) }]; } if (segLen(s.a, pt) < EPS) { return [{ phase: "start", lastPoint: null }, { draft: null, done: true }]; @@ -100,15 +81,15 @@ export const xlineCommand: Command = { const a = s.a; return [ { phase: "start", lastPoint: null }, - { draft: null, done: true, commit: opsMutation(() => appendXline(a, pt, ctx)) }, + { draft: null, done: true, commit: appendXline(a, pt, ctx) }, ]; }, - onMove: (state, point): [CommandState, CommandResult] => { + onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => { const s = state as XlineState; if (s.phase !== "end") return [s, { draft: null }]; const next: XlineDrawing = { ...s, cursor: point }; - return [next, { draft: xlineDraft(s.a, point) }]; + return [next, { draft: xlineDraft(ctx, s.a, point) }]; }, onConfirm: (): [CommandState, CommandResult] => [ diff --git a/src/commands/createCore.ts b/src/commands/createCore.ts new file mode 100644 index 00000000..354e5304 --- /dev/null +++ b/src/commands/createCore.ts @@ -0,0 +1,81 @@ +// Brücke der Zeichenbefehle zum Kern ([K4] S3, `src-tauri/core/src/cmd_create.rs`): die Befehle halten +// nur noch ihre Zustandsautomaten (Klicks, Tasten, Optionen) und die gesetzten Punkte; die neuen +// Elemente (Vorgaben aus Typen/Stilen, abgeleitete Felder, ids), die Vorschau je Mausschritt und die +// Treffer zwischen den Schritten rechnet der Kern. + +import type { Project, Vec2 } from "../model/types"; +import type { CommandContext, DraftShape } from "./types"; +import type { ProjectMutation } from "../core"; +import { cmdMutation, documentFor } from "../core/document"; +import { toMarkedJson } from "../core/ops"; +import { uniqueStamp } from "../tools/types"; +import { decodeShapes } from "../tools/coreCmd"; + +/** Vorschau eines Zeichenbefehls: Formen, ob ein Commit hier etwas erzeugte, Zusatzzahlen je Befehl. */ +export interface CreatePreview { + shapes: DraftShape[]; + ok: boolean; + info: number[]; +} + +/** Kontext der Anfrage: aktive Ebene/Geschoss, Kategorie, Wandtyp. */ +function ctxReq(ctx: CommandContext): object { + return { + level: ctx.level.id, + floorHeight: ctx.level.floorHeight ?? null, + cat: ctx.defaultCategoryCode, + wallType: ctx.activeWallTypeId, + }; +} + +/** Commit eines Zeichenbefehls: `req` = `{cmd, …}`; der Kern baut die Elemente (ids aus dem Stempel). */ +export function createMutation(ctx: CommandContext, req: { cmd: string } & Record): ProjectMutation { + return cmdMutation({ ...req, ctx: ctxReq(ctx), stamp: uniqueStamp() }); +} + +/** Punkt als Paar (Anfragen an den Kern). */ +export const xy = (p: Vec2): [number, number] => [p.x, p.y]; + +// Je Mausschritt ändern sich meist nur die Punkte: sind Optionen und Kontext (flach verglichen, Objekte und +// Listen per Referenz) dieselben wie beim letzten Aufruf, rechnet der Kern mit den gemerkten Optionen +// (kein JSON je Mausschritt). Punkte dürfen als Paar `[x, y]` oder als `{x, y}` reisen. +let lastReq: Record | null = null; +let lastCtx: { level: string; floorHeight: unknown; cat: string; wallType: string } | null = null; + +function sameReq(req: Record, ctx: CommandContext): boolean { + const c = lastCtx; + if (!lastReq || !c) return false; + if (c.level !== ctx.level.id || !Object.is(c.floorHeight, ctx.level.floorHeight) || c.cat !== ctx.defaultCategoryCode || c.wallType !== ctx.activeWallTypeId) return false; + const ka = Object.keys(req); + if (ka.length !== Object.keys(lastReq).length) return false; + for (const k of ka) { + const v = req[k]; + // Objekte/Listen per Referenz: die Zustände der Befehle sind unveränderlich (neue Liste je Klick). + if (!Object.is(v, lastReq[k])) return false; + } + return true; +} + +/** Vorschau eines Zeichenbefehls: `req` = Optionen, `pts` = die Punkte (je Befehl, zuletzt der Cursor). */ +export function createPreview(ctx: CommandContext, req: { cmd: string } & Record, pts: readonly Vec2[]): CreatePreview { + const flat = new Float64Array(pts.length * 2); + for (let i = 0; i < pts.length; i++) { + flat[2 * i] = pts[i].x; + flat[2 * i + 1] = pts[i].y; + } + let json: string | null = null; + if (!sameReq(req, ctx)) { + json = toMarkedJson({ ...req, ctx: ctxReq(ctx) }); + lastReq = req; + lastCtx = { level: ctx.level.id, floorHeight: ctx.level.floorHeight, cat: ctx.defaultCategoryCode, wallType: ctx.activeWallTypeId }; + } + const f = documentFor(ctx.project).createPreview(json, flat); + if (f.length < 2) return { shapes: [], ok: false, info: [] }; + const n = f[1]; + return { ok: f[0] === 1, info: Array.from(f.subarray(2, 2 + n)), shapes: decodeShapes(f.subarray(2 + n)) }; +} + +/** Treffer-Abfrage eines Zeichenbefehls (`cmd_create::query`) auf dem Dokument von `project`. */ +export function createQuery(project: Project, req: { q: string } & Record): T { + return documentFor(project).createQuery(req); +} diff --git a/src/core/document.ts b/src/core/document.ts index 97eb37e3..49591ac1 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -316,6 +316,24 @@ export class ProjectDocument { return fromMarkedJson(out); } + /** + * Vorschau eines Zeichenbefehls (`doc_create_preview`, `cmd_create.rs`): `reqJson` = Optionen (mit + * Nicht-endlich-Marken; `null` = dieselben wie beim letzten Aufruf), `pts` flach; Antwort + * `[ok, nInfo, info…, Formen…]`. + */ + createPreview(reqJson: string | null, pts: Float64Array): Float64Array { + if (!this.handle) return new Float64Array(0); + return reqJson === null ? core().doc_create_preview_again(this.handle, pts) : core().doc_create_preview(this.handle, reqJson, pts); + } + + /** Treffer-Abfrage eines Zeichenbefehls (`doc_create_query`), JSON-Antwort. */ + createQuery(req: object): T { + if (!this.handle) throw new Error("Kern-Abfrage „createQuery“: Dokument nicht offen"); + const out = core().doc_create_query(this.handle, toMarkedJson(req)); + if (out.startsWith("\u0001")) throw new Error(out.slice(1)); + return fromMarkedJson(out); + } + /** Vorschau-Formen eines Befehls (`doc_cmd_preview`): flach je Form `[art, n, x0, y0, …]`. */ cmdPreview(req: object): Float64Array { return this.handle ? core().doc_cmd_preview(this.handle, toMarkedJson(req)) : new Float64Array(0); diff --git a/src/core/index.ts b/src/core/index.ts index 464d1377..c9a91001 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -3,31 +3,20 @@ // Erzeugt mit scripts/core-facade.py — neue Einträge von Hand ergänzen. export { - arcFromStartEndDirection, - arcFromStartEndRadius, - arcThroughPoints, bulgeArc, bulgeArcPoints, bulgePolylinePoints, bulgeFromSagittaPoint, bulgePointAt, - bulgeThroughPoint, hasRealBulge, pointOnCircle, } from "../geometry/bulge"; -export { - ceilingArea, - normalizeOutline, - pointInOutline, -} from "../geometry/ceiling"; - export { columnFootprint, } from "../geometry/column"; export { - ellipsePts, sampleBezierChain, sampleCatmullRom, sampleUniformBSpline, @@ -52,18 +41,11 @@ export { } from "../geometry/snapSegments"; export { - type Fillet, - type TangentTarget, - filletCorner, - offsetSegment, - pointSegmentDistance, - polylineEdges, removeSegment, removeSegmentWithBulge, splitAtIntersections, splitClosedByChord, splitPolylineAtParam, - tangentCircleCenters, vecEqual, } from "../geometry/kernel2d"; @@ -78,11 +60,7 @@ export { segmentsToDash, } from "../geometry/lineSegments"; -export { -} from "../geometry/opening"; -export { autoExteriorDimensions } from "../geometry/autoDimensions"; export * as polygonBool from "../geometry/polygonBool"; -export type { AutoDimension } from "../geometry/autoDimensions"; export { nearestPolylineTarget, @@ -95,19 +73,13 @@ export { vertexTypeOf, } from "../geometry/polylineVertexType"; -export { - revisionCloudPts, -} from "../geometry/revisionCloud"; - export { roofBaseElevation, roofGeometry, } from "../geometry/roof"; export { - addRoofHole, removeRoofHole, - roofHoleWorks, setRoofEdge, } from "../geometry/roofEdges"; export type { EdgeSpec, RoofEdge } from "../geometry/roofEdges"; @@ -124,14 +96,11 @@ export { export { type WallSegment, - roomFromPointInside, } from "../geometry/roomBoundary"; export { IDEAL_TREAD, MIN_STEPS, - defaultStepCount, - stairGeometry, stairOutline, } from "../geometry/stair"; diff --git a/src/engine/truckBrep.wasm.test.ts b/src/engine/truckBrep.wasm.test.ts index 001100dc..ec4f5408 100644 --- a/src/engine/truckBrep.wasm.test.ts +++ b/src/engine/truckBrep.wasm.test.ts @@ -3,7 +3,15 @@ import { describe, expect, it, beforeAll } from "vitest"; import { readFileSync } from "node:fs"; import { sampleProject } from "../model/sampleProject"; -import { combineSolids } from "../commands/cmds/solidbool"; +import { documentFor } from "../core/document"; + +/** Boolesche Verknüpfung zweier Körper über den Befehl im Kern (`cmd_solid.rs`); null = kein Körper. */ +function combineSolids(project: typeof sampleProject, a: ExtrudedSolid, b: ExtrudedSolid, op: string): ExtrudedSolid | null { + const p = { ...project, extrudedSolids: [a, b] }; + const ops = documentFor(p).cmdOps({ cmd: "solidbool", a: a.id, b: b.id, op, stamp: "t", ctx: { level: "eg" } }); + const add = ops.find((o) => o.kind === "add"); + return add && add.kind === "add" ? (add.items[0] as unknown as ExtrudedSolid) : null; +} import { extrudedSolidSpec } from "../plan/extrudedSolidSpec"; import type { ExtrudedSolid } from "../model/types"; diff --git a/src/geometry/autoDimensions.test.ts b/src/geometry/autoDimensions.test.ts deleted file mode 100644 index c2cdedef..00000000 --- a/src/geometry/autoDimensions.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { autoExteriorDimensions } from "./autoDimensions"; -import type { Opening, Project, Wall } from "../model/types"; - -// L-förmiger Grundriss aus 0.3-m-Wänden (Achsen): (0,0)→(10,0)→(10,6)→(4,6)→(4,9)→(0,9)→(0,0). -const axis: [number, number][] = [[0, 0], [10, 0], [10, 6], [4, 6], [4, 9], [0, 9]]; -function project(openings: Opening[] = []): Project { - const walls: Wall[] = axis.map(([x, y], i) => { - const [x2, y2] = axis[(i + 1) % axis.length]; - return { id: `W${i}`, type: "wall", floorId: "eg", categoryCode: "20", start: { x, y }, end: { x: x2, y: y2 }, wallTypeId: "aw" } as Wall; - }); - return { - id: "t", name: "T", lineStyles: [], hatches: [], components: [{ id: "c", name: "C", color: "#ccc", hatchId: "none", joinPriority: 1 }], - wallTypes: [{ id: "aw", name: "AW", layers: [{ componentId: "c", thickness: 0.3 }] }], - drawingLevels: [{ id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1, baseElevation: 0 }], - layers: [], walls, openings, ceilings: [], stairs: [], rooms: [], drawings2d: [], context: [], - } as unknown as Project; -} -const lengths = (pts: { x: number; y: number }[]) => pts.slice(1).map((p, i) => Math.hypot(p.x - pts[i].x, p.y - pts[i].y)); -const sum = (a: number[]) => a.reduce((s, v) => s + v, 0); - -describe("automatische Aussenbemassung", () => { - it("vier Seiten, Gesamtmass = Aussenmass", () => { - const dims = autoExteriorDimensions(project(), "eg", "80"); - const totals = dims.filter((d) => d.chain === "total"); - expect(totals).toHaveLength(4); - const byside = Object.fromEntries(totals.map((d) => [d.side, sum(lengths(d.drawing.geom.shape === "dimension" ? d.drawing.geom.pts : []))])); - expect(byside.south).toBeCloseTo(10.3, 6); - expect(byside.north).toBeCloseTo(10.3, 6); - expect(byside.west).toBeCloseTo(9.3, 6); - expect(byside.east).toBeCloseTo(9.3, 6); - }); - it("Vor-/Rücksprung-Kette nur, wo die Seite gestuft ist (L: Nord und Ost)", () => { - const dims = autoExteriorDimensions(project(), "eg", "80"); - const steps = dims.filter((d) => d.chain === "steps"); - expect(steps.map((d) => d.side).sort()).toEqual(["east", "north"]); - const north = steps.find((d) => d.side === "north")!; - const g = north.drawing.geom; - expect(g.shape === "dimension" && lengths(g.pts).map((v) => +v.toFixed(3)).sort((a, b) => a - b)).toEqual([4.3, 6]); - }); - it("Öffnungskette mit Leibungen, Abstand nach aussen positiv", () => { - const o = { id: "F1", type: "opening", categoryCode: "21", kind: "window", hostWallId: "W0", position: 2, width: 1.5, height: 1.4, sillHeight: 0.9 } as Opening; - const dims = autoExteriorDimensions(project([o]), "eg", "80"); - const south = dims.find((d) => d.side === "south" && d.chain === "openings")!; - const g = south.drawing.geom; - expect(g.shape).toBe("dimension"); - if (g.shape !== "dimension") return; - expect(lengths(g.pts).length).toBe(3); - expect(sum(lengths(g.pts))).toBeCloseTo(10.3, 6); - expect(g.offset).toBeGreaterThan(0); - // Masslinie liegt ausserhalb (südlich) des Gebäudes. - const nx = -(g.pts[1].y - g.pts[0].y), ny = g.pts[1].x - g.pts[0].x; - const len = Math.hypot(nx, ny); - expect(g.pts[0].y + (ny / len) * g.offset).toBeLessThan(-0.15); - expect(south.drawing.levelId).toBe("eg"); - expect(south.drawing.categoryCode).toBe("80"); - }); - it("ohne Wände nichts", () => { - expect(autoExteriorDimensions({ ...project(), walls: [] }, "eg", "80")).toEqual([]); - }); -}); - -describe("Planbegrenzung mit Bemassung", () => { - it("umfasst die versetzte Masslinie samt Masszahl", async () => { - const { generatePlan } = await import("../plan/generatePlan"); - const p = project(); - const dims = autoExteriorDimensions(p, "eg", "80"); - const withDims = { ...p, layers: [{ code: "80", name: "Mass", color: "#000", lw: 0.18, visible: true, locked: false }], drawings2d: dims.map((d) => d.drawing) } as Project; - const b = generatePlan(withDims, "eg", new Set(["80"])).bounds; - // Gesamtmass Süd liegt 2.4 m ausserhalb von y = -0.15. - expect(b.minY).toBeLessThan(-0.15 - 2.4); - expect(b.maxX).toBeGreaterThan(10.15 + 2.4); - }); -}); diff --git a/src/geometry/autoDimensions.ts b/src/geometry/autoDimensions.ts deleted file mode 100644 index d3cbdef3..00000000 --- a/src/geometry/autoDimensions.ts +++ /dev/null @@ -1,89 +0,0 @@ -// Automatische Aussenbemassung ([81]): je Gebäudeseite (Süd, Ost, Nord, West) bis zu drei -// Massketten ausserhalb des Grundrisses, von innen nach aussen: -// 1. Öffnungen — Gebäudeecken der Seite plus Leibungen der Fenster/Türen in Wänden dieser Seite, -// 2. Vor-/Rücksprünge — die Ecken der nach dieser Seite schauenden Aussenkanten (nur bei Stufung), -// 3. Gesamtmass. -// Grundlage ist die vereinigte Grundfläche der Wände des Geschosses (an verbundenen Enden um die -// halbe Dicke verlängert, damit Aussenecken voll sind). Nur achsparallele Kanten werden bemasst; -// schiefe Wände fehlen in den Ketten. Ergebnis sind gewöhnliche Bemassungen (Drawing2D), danach -// frei bearbeitbar. - -import type { Drawing2D, Project, Wall } from "../model/types"; -import { getWallType, wallTypeThickness } from "../model/types"; -import { openingJambs } from "./opening"; -import { core } from "../engine/coreWasm"; -import { FlatReader, FlatWriter } from "./coreFlat"; - -export type DimSide = "south" | "east" | "north" | "west"; -export type DimChain = "openings" | "steps" | "total"; - -export interface AutoDimension { - side: DimSide; - chain: DimChain; - drawing: Drawing2D; -} - -/** Reihenfolge wie im Rust-Kern (`auto_dimensions.rs`: SIDES, CHAIN_*). */ -const SIDES: DimSide[] = ["south", "east", "north", "west"]; -const CHAINS: DimChain[] = ["openings", "steps", "total"]; - -function thicknessOf(project: Project, w: Wall): number { - try { - return wallTypeThickness(getWallType(project, w)); - } catch { - return 0.3; // verwaister Wandtyp - } -} - -/** - * Erzeugt die Aussenbemassung eines Geschosses. `scaleDenominator` bestimmt den Abstand der - * Ketten (Papier-mm → Modell-Meter), `categoryCode` die Ebene der neuen Bemassungen. Die Ketten - * rechnet der Rust-Kern aus Wandachsen/-dicken und Öffnungs-Leibungen. - */ -export function autoExteriorDimensions( - project: Project, - floorId: string, - categoryCode: string, - scaleDenominator = 100, - idPrefix = "autodim", -): AutoDimension[] { - const walls = project.walls.filter((w) => w.floorId === floorId); - if (walls.length === 0) return []; - const ww = new FlatWriter().num(walls.length); - for (const w of walls) ww.num(w.start.x, w.start.y, w.end.x, w.end.y, thicknessOf(project, w)); - const index = new Map(); - walls.forEach((w, i) => index.has(w.id) || index.set(w.id, i)); - const ow = new FlatWriter(); - const count = ow.slot(); - let nOpenings = 0; - for (const o of project.openings ?? []) { - const i = index.get(o.hostWallId); - if (i === undefined) continue; - const j = openingJambs(walls[i], o); - if (!j) continue; - ow.num(i, j.jambStart.x, j.jambStart.y, j.jambEnd.x, j.jambEnd.y); - nOpenings++; - } - ow.set(count, nOpenings); - - const rd = new FlatReader(core().autodim_chains(ww.done(), ow.done(), scaleDenominator)); - const out: AutoDimension[] = []; - for (let n = rd.count(); n > 0; n--) { - const side = SIDES[rd.num()]; - const chain = CHAINS[rd.num()]; - const offset = rd.num(); - const pts = rd.ring(); - out.push({ - side, - chain, - drawing: { - id: `${idPrefix}-${floorId}-${side}-${chain}`, - type: "drawing2d", - levelId: floorId, - categoryCode, - geom: { shape: "dimension", pts, offset }, - } as Drawing2D, - }); - } - return out; -} diff --git a/src/geometry/bulge.test.ts b/src/geometry/bulge.test.ts index 692c2056..fbe6320e 100644 --- a/src/geometry/bulge.test.ts +++ b/src/geometry/bulge.test.ts @@ -5,14 +5,10 @@ import { describe, it, expect } from "vitest"; import { - arcFromStartEndDirection, - arcFromStartEndRadius, - arcThroughPoints, bulgeArc, bulgeArcPoints, bulgePolylinePoints, bulgeFromSagittaPoint, - bulgeThroughPoint, } from "./bulge"; import type { Vec2 } from "../model/types"; @@ -83,194 +79,6 @@ describe("bulgeFromSagittaPoint — Umkehrung für die Griff-Interaktion", () => }); }); -describe("bulgeThroughPoint — Drei-Punkt-Bogen (unabhängig vom Vorgänger-Segment)", () => { - it("Halbkreis über der Sehne: Durchgangspunkt im Scheitel", () => { - const b = bulgeThroughPoint({ x: 0, y: 0 }, { x: 2, y: 2 }, { x: 4, y: 0 }); - // Halbkreis → |bulge| = 1 (Δ = 180°, tan(45°) = 1); Wölbung nach +Y - // liegt LINKS von a→b, also positiv. - expect(b).toBeCloseTo(1, 9); - }); - - it("Durchgangspunkt auf der anderen Seite kehrt das Vorzeichen um", () => { - const b = bulgeThroughPoint({ x: 0, y: 0 }, { x: 2, y: -2 }, { x: 4, y: 0 }); - expect(b).toBeCloseTo(-1, 9); - }); - - it("der erzeugte Bogen läuft tatsächlich durch den Durchgangspunkt", () => { - const a = { x: 0, y: 0 }; - const through = { x: 3, y: 1 }; - const bb = { x: 5, y: -2 }; - const bulge = bulgeThroughPoint(a, through, bb); - const arc = bulgeArc(a, bb, bulge)!; - // Der Durchgangspunkt liegt auf dem Kreis … - expect(Math.hypot(through.x - arc.center.x, through.y - arc.center.y)).toBeCloseTo(arc.r, 9); - // … und innerhalb der tatsächlich durchlaufenen Spanne. - const TAU = Math.PI * 2; - const norm = (x: number) => ((x % TAU) + TAU) % TAU; - const rel = arc.sweep >= 0 - ? norm(Math.atan2(through.y - arc.center.y, through.x - arc.center.x) - arc.a0) - : norm(arc.a0 - Math.atan2(through.y - arc.center.y, through.x - arc.center.x)); - expect(rel).toBeLessThanOrEqual(Math.abs(arc.sweep) + 1e-9); - }); - - it("kollineare Punkte → gerade (kein Kreis)", () => { - expect(bulgeThroughPoint({ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 5, y: 0 })).toBe(0); - }); - - it("die Grösse hängt NUR von den drei Punkten ab (unabhängig vom Startpunkt der Kette)", () => { - // Dieselbe relative Geometrie an anderer Stelle ⇒ identischer Bulge. - const b1 = bulgeThroughPoint({ x: 0, y: 0 }, { x: 2, y: 1 }, { x: 4, y: 0 }); - const b2 = bulgeThroughPoint({ x: 100, y: 50 }, { x: 102, y: 51 }, { x: 104, y: 50 }); - expect(b2).toBeCloseTo(b1, 12); - }); -}); - -describe("arcThroughPoints — Drei-Punkt-Bogen als {center,r,a0,a1} (commands/cmds/arc.ts)", () => { - it("Viertelkreis (0°→90° via 45°) liefert Mittelpunkt/Radius/Winkel exakt", () => { - const a = { x: 1, y: 0 }; - const through = { x: Math.SQRT1_2, y: Math.SQRT1_2 }; // 45° - const b = { x: 0, y: 1 }; - const arc = arcThroughPoints(a, through, b)!; - expect(arc).not.toBeNull(); - expect(arc.center.x).toBeCloseTo(0, 9); - expect(arc.center.y).toBeCloseTo(0, 9); - expect(arc.r).toBeCloseTo(1, 9); - expect(arc.a0).toBeCloseTo(0, 9); - expect(arc.a1).toBeCloseTo(Math.PI / 2, 9); - }); - - it("a0/a1 laufen IMMER CCW und decken den Durchgangspunkt ab, unabhängig von der Klickreihenfolge (a,through,b) vs (b,through,a)", () => { - const a = { x: 1, y: 0 }; - const through = { x: Math.SQRT1_2, y: Math.SQRT1_2 }; - const b = { x: 0, y: 1 }; - const forward = arcThroughPoints(a, through, b)!; - const backward = arcThroughPoints(b, through, a)!; - expect(backward.center.x).toBeCloseTo(forward.center.x, 9); - expect(backward.center.y).toBeCloseTo(forward.center.y, 9); - expect(backward.r).toBeCloseTo(forward.r, 9); - expect(backward.a0).toBeCloseTo(forward.a0, 9); - expect(backward.a1).toBeCloseTo(forward.a1, 9); - }); - - it("Start/End/Durchgangspunkt liegen alle auf dem Kreis, Durchgangspunkt innerhalb [a0,a1]", () => { - const a = { x: 0, y: 0 }; - const through = { x: 3, y: 1 }; - const b = { x: 5, y: -2 }; - const arc = arcThroughPoints(a, through, b)!; - const onCircle = (p: { x: number; y: number }) => - Math.hypot(p.x - arc.center.x, p.y - arc.center.y); - expect(onCircle(a)).toBeCloseTo(arc.r, 9); - expect(onCircle(b)).toBeCloseTo(arc.r, 9); - expect(onCircle(through)).toBeCloseTo(arc.r, 9); - const TAU = Math.PI * 2; - const norm = (x: number) => ((x % TAU) + TAU) % TAU; - const sweep = norm(arc.a1 - arc.a0); - const toThrough = norm(Math.atan2(through.y - arc.center.y, through.x - arc.center.x) - arc.a0); - expect(toThrough).toBeLessThanOrEqual(sweep + 1e-9); - }); - - it("kollineare Punkte → null (kein Kreis)", () => { - expect(arcThroughPoints({ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 5, y: 0 })).toBeNull(); - }); -}); - -describe("arcFromStartEndRadius — Start/Ende/Radius (commands/cmds/arc.ts, dritte Methode)", () => { - const onCircle = (arc: { center: Vec2; r: number }, p: Vec2) => - Math.hypot(p.x - arc.center.x, p.y - arc.center.y); - const TAU = Math.PI * 2; - const norm = (x: number) => ((x % TAU) + TAU) % TAU; - - it("Halbkreis exakt bei r = halbe Sehnenlänge (Grenzfall)", () => { - const a = { x: 0, y: 0 }; - const b = { x: 4, y: 0 }; - const arc = arcFromStartEndRadius(a, b, 2, { x: 2, y: 5 })!; - expect(arc).not.toBeNull(); - expect(arc.r).toBeCloseTo(2, 9); - expect(onCircle(arc, a)).toBeCloseTo(2, 9); - expect(onCircle(arc, b)).toBeCloseTo(2, 9); - expect(norm(arc.a1 - arc.a0)).toBeCloseTo(Math.PI, 6); // exakt 180° - }); - - it("wölbt sich zur cursor-nahen Seite (near oberhalb → Bogenscheitel oberhalb der Sehne)", () => { - const a = { x: 0, y: 0 }; - const b = { x: 4, y: 0 }; - const arc = arcFromStartEndRadius(a, b, 3, { x: 2, y: 5 })!; - const mid = arc.a0 + norm(arc.a1 - arc.a0) / 2; - const apex = { x: arc.center.x + arc.r * Math.cos(mid), y: arc.center.y + arc.r * Math.sin(mid) }; - expect(apex.y).toBeGreaterThan(0); - }); - - it("wölbt sich zur ANDEREN Seite, wenn `near` unterhalb der Sehne liegt", () => { - const a = { x: 0, y: 0 }; - const b = { x: 4, y: 0 }; - const arc = arcFromStartEndRadius(a, b, 3, { x: 2, y: -5 })!; - const mid = arc.a0 + norm(arc.a1 - arc.a0) / 2; - const apex = { x: arc.center.x + arc.r * Math.cos(mid), y: arc.center.y + arc.r * Math.sin(mid) }; - expect(apex.y).toBeLessThan(0); - }); - - it("liefert immer den KLEINEREN Bogen (Sehnenwinkel ≤ 180°)", () => { - const a = { x: 0, y: 0 }; - const b = { x: 4, y: 0 }; - const arc = arcFromStartEndRadius(a, b, 10, { x: 2, y: 1 })!; - expect(norm(arc.a1 - arc.a0)).toBeLessThanOrEqual(Math.PI + 1e-9); - }); - - it("liefert null, wenn der Radius kleiner als die halbe Sehnenlänge ist", () => { - expect(arcFromStartEndRadius({ x: 0, y: 0 }, { x: 4, y: 0 }, 1, { x: 2, y: 1 })).toBeNull(); - }); - - it("liefert null bei entarteter Sehne (a≈b)", () => { - expect(arcFromStartEndRadius({ x: 1, y: 1 }, { x: 1, y: 1 }, 2, { x: 2, y: 2 })).toBeNull(); - }); -}); - -describe("arcFromStartEndDirection — Start/Ende/Tangentenrichtung (commands/cmds/arc.ts, vierte Methode)", () => { - const onCircle = (arc: { center: Vec2; r: number }, p: Vec2) => - Math.hypot(p.x - arc.center.x, p.y - arc.center.y); - - it("Viertelkreis: Tangente bei (1,0) nach +y führt zum Bogen bis (0,1)", () => { - const a = { x: 1, y: 0 }; - const b = { x: 0, y: 1 }; - const dir = { x: 1, y: 1 }; // von a aus Richtung +y (tangential zum Einheitskreis bei a) - const arc = arcFromStartEndDirection(a, b, dir)!; - expect(arc).not.toBeNull(); - expect(arc.center.x).toBeCloseTo(0, 6); - expect(arc.center.y).toBeCloseTo(0, 6); - expect(arc.r).toBeCloseTo(1, 6); - expect(onCircle(arc, a)).toBeCloseTo(1, 9); - expect(onCircle(arc, b)).toBeCloseTo(1, 9); - }); - - it("Bogen-Tangente bei a zeigt tatsächlich in Richtung `dir`, nicht rückwärts", () => { - const a = { x: 1, y: 0 }; - const b = { x: 0, y: 1 }; - const dir = { x: 1, y: 1 }; - const arc = arcFromStartEndDirection(a, b, dir)!; - // CCW-Tangente bei a0 (Ableitung von (cos,sin) nach wachsendem Winkel). - const tangentCCW = { x: -Math.sin(arc.a0), y: Math.cos(arc.a0) }; - const wantedDir = { x: dir.x - a.x, y: dir.y - a.y }; - const dot = tangentCCW.x * wantedDir.x + tangentCCW.y * wantedDir.y; - expect(dot).toBeGreaterThan(0); - }); - - it("entgegengesetzte Tangentenrichtung liefert den KOMPLEMENTÄREN Bogen (gleicher Kreis, andere Seite)", () => { - const a = { x: 1, y: 0 }; - const b = { x: 0, y: 1 }; - const forward = arcFromStartEndDirection(a, b, { x: 1, y: 1 })!; - const backward = arcFromStartEndDirection(a, b, { x: 1, y: -1 })!; - expect(backward.center.x).toBeCloseTo(forward.center.x, 6); - expect(backward.center.y).toBeCloseTo(forward.center.y, 6); - expect(backward.r).toBeCloseTo(forward.r, 6); - // Unterschiedlicher Schwenk (a0/a1 vertauscht bzw. andere Bogenseite). - expect(backward.a0).not.toBeCloseTo(forward.a0, 3); - }); - - it("liefert null bei entarteter Tangentenrichtung (dir≈a)", () => { - expect(arcFromStartEndDirection({ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 0, y: 0 })).toBeNull(); - }); -}); - describe("bulgePolylinePoints (ganze Polylinie auf einmal)", () => { const sq: Vec2[] = [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 2 }, { x: 0, y: 2 }]; @@ -298,7 +106,6 @@ describe("bulgePolylinePoints (ganze Polylinie auf einmal)", () => { expect(bulgePolylinePoints([], undefined, true)).toEqual([]); expect(bulgePolylinePoints([{ x: NaN, y: 0 }, { x: 1, y: 0 }], [1], false)).toEqual([]); expect(bulgeArc({ x: NaN, y: 0 }, { x: 1, y: 0 }, 1)).toBeNull(); - expect(bulgeThroughPoint({ x: 0, y: 0 }, { x: NaN, y: 1 }, { x: 2, y: 0 })).toBe(0); expect(bulgeArcPoints({ x: 0, y: 0 }, { x: 1, y: 0 }, NaN)).toHaveLength(2); }); }); diff --git a/src/geometry/bulge.ts b/src/geometry/bulge.ts index 83c04be6..22aefd68 100644 --- a/src/geometry/bulge.ts +++ b/src/geometry/bulge.ts @@ -89,51 +89,7 @@ export function bulgePointAt(a: Vec2, b: Vec2, bulge: number, t: number): Vec2 { return { x: r[0], y: r[1] }; } -/** - * Bulge eines Kreisbogens, der von `a` über `through` nach `b` läuft — der klassische - * Drei-Punkt-Bogen, nur von diesen drei Punkten abhängig (nicht vom vorherigen Segment). - * Liegen die Punkte (nahezu) auf einer Geraden, gibt es keinen Kreis — dann 0. - */ -export function bulgeThroughPoint(a: Vec2, through: Vec2, b: Vec2): number { - return core().bulge_through_point(a.x, a.y, through.x, through.y, b.x, b.y); -} - /** Punkt auf einem Kreis (center, r) beim Winkel `a` (Radiant). */ export function pointOnCircle(center: Vec2, r: number, a: number): Vec2 { return { x: center.x + r * Math.cos(a), y: center.y + r * Math.sin(a) }; } - -type ArcParams = { center: Vec2; r: number; a0: number; a1: number }; - -function toArcParams(r: Float64Array): ArcParams | null { - if (r.length < 5) return null; - return { center: { x: r[0], y: r[1] }, r: r[2], a0: r[3], a1: r[4] }; -} - -/** - * Kreisbogen-Parameter durch drei Punkte `a`→`through`→`b`, direkt als `{center,r,a0,a1}` - * für Werkzeuge, die einen eigenständigen `{shape:"arc"}` erzeugen (`commands/cmds/arc.ts`). - * `a0`/`a1` sind IMMER so geordnet, dass der Bogen CCW von a0 nach a1 läuft. `null` bei - * (nahezu) kollinearen Punkten. - */ -export function arcThroughPoints(a: Vec2, through: Vec2, b: Vec2): ArcParams | null { - return toArcParams(core().arc_through_points(a.x, a.y, through.x, through.y, b.x, b.y)); -} - -/** - * Kreisbogen durch zwei Endpunkte `a`→`b` mit vorgegebenem Radius `r` (Methode „Start-Ende- - * Radius"). `near` (typischerweise der Cursor) wählt die Seite der Sehne; es entsteht immer der - * KLEINERE der beiden möglichen Bögen (Sehnenwinkel ≤ 180°). `null`, wenn `r` kleiner als die - * halbe Sehnenlänge ist oder die Sehne entartet. - */ -export function arcFromStartEndRadius(a: Vec2, b: Vec2, r: number, near: Vec2): ArcParams | null { - return toArcParams(core().arc_from_start_end_radius(a.x, a.y, b.x, b.y, r, near.x, near.y)); -} - -/** - * Kreisbogen durch `a`→`b`, bei `a` tangential zur Richtung `dir` (ein Punkt AUF dem - * Tangentenstrahl). `null` bei entarteter Tangente oder wenn sie entlang der Sehne a-b zeigt. - */ -export function arcFromStartEndDirection(a: Vec2, b: Vec2, dir: Vec2): ArcParams | null { - return toArcParams(core().arc_from_start_end_direction(a.x, a.y, b.x, b.y, dir.x, dir.y)); -} diff --git a/src/geometry/ceiling.ts b/src/geometry/ceiling.ts deleted file mode 100644 index ca674075..00000000 --- a/src/geometry/ceiling.ts +++ /dev/null @@ -1,56 +0,0 @@ -// Geometrie-Helfer für Decken (Slabs) — reine Funktionen über `Vec2`, kein -// externer Kernel. Eine Decke ist ein GESCHLOSSENER Umriss (Polygon) plus eine -// Dicke; diese Helfer normalisieren den Umriss, berechnen Fläche/Umriss-Prüfung -// und liefern eine extrude-fertige Form. Baut auf kernel2d/model/geometry auf. -// -// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). - -import type { Vec2 } from "../model/types"; -import { signedArea, isCCW, vecEqual } from "./kernel2d"; - -/** Kleinste sinnvolle Deckenfläche (m²) — darunter gilt der Umriss als entartet. */ -export const MIN_CEILING_AREA = 1e-4; - -/** - * Normalisiert einen Deckenumriss: - * • entfernt aufeinanderfolgende (nahezu) gleiche Punkte, - * • entfernt einen schließenden Duplikat-Endpunkt (pts[last] == pts[0]), - * • erzwingt CCW-Wicklung (positive Fläche) — konsistent für Plan-Füllung und - * 3D-Extrusion. - * Liefert `null`, wenn nach der Bereinigung < 3 Punkte übrig bleiben (kein - * gültiges Polygon). - */ -export function normalizeOutline(pts: Vec2[]): Vec2[] | null { - const clean: Vec2[] = []; - for (const p of pts) { - if (clean.length === 0 || !vecEqual(clean[clean.length - 1], p)) clean.push(p); - } - // Schließenden Duplikat-Endpunkt verwerfen. - if (clean.length > 1 && vecEqual(clean[0], clean[clean.length - 1])) clean.pop(); - if (clean.length < 3) return null; - // CCW erzwingen. - return isCCW(clean) ? clean : clean.slice().reverse(); -} - -/** Fläche eines Deckenumrisses in m² (immer positiv). */ -export function ceilingArea(pts: Vec2[]): number { - return Math.abs(signedArea(pts)); -} - -/** - * Punkt-in-Polygon-Test (Ray-Casting) für einen geschlossenen Umriss — dient dem - * Body-Select einer Decke im Grundriss/3D. Randpunkte gelten als innen genug. - */ -export function pointInOutline(p: Vec2, outline: Vec2[]): boolean { - let inside = false; - const n = outline.length; - for (let i = 0, j = n - 1; i < n; j = i++) { - const a = outline[i]; - const b = outline[j]; - const intersect = - a.y > p.y !== b.y > p.y && - p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y || 1e-12) + a.x; - if (intersect) inside = !inside; - } - return inside; -} diff --git a/src/geometry/curves.test.ts b/src/geometry/curves.test.ts index 6006bc8a..f6f67605 100644 --- a/src/geometry/curves.test.ts +++ b/src/geometry/curves.test.ts @@ -1,30 +1,5 @@ import { describe, it, expect } from "vitest"; -import { ellipsePts, sampleBezierChain, sampleCatmullRom, sampleUniformBSpline } from "./curves"; - -describe("ellipsePts", () => { - it("liegt auf der Ellipse (rotation 0): Ost/Nord-Punkte bei rx/ry", () => { - const pts = ellipsePts({ x: 0, y: 0 }, 4, 2, 0, 4); - // t=0 → Ost (rx,0); t=π/2 → Nord (0,ry) - expect(pts[0].x).toBeCloseTo(4, 6); - expect(pts[0].y).toBeCloseTo(0, 6); - expect(pts[1].x).toBeCloseTo(0, 6); - expect(pts[1].y).toBeCloseTo(2, 6); - }); - - it("Drehung um 90° vertauscht die Achsen", () => { - const pts = ellipsePts({ x: 0, y: 0 }, 4, 2, Math.PI / 2, 4); - // Der ehemalige Ost-Punkt (rx,0) liegt jetzt bei (0, rx). - expect(pts[0].x).toBeCloseTo(0, 6); - expect(pts[0].y).toBeCloseTo(4, 6); - }); - - it("Mittelpunkt-Verschiebung wird respektiert", () => { - const pts = ellipsePts({ x: 10, y: 5 }, 3, 3, 0, 8); - for (const p of pts) { - expect(Math.hypot(p.x - 10, p.y - 5)).toBeCloseTo(3, 6); - } - }); -}); +import { sampleBezierChain, sampleCatmullRom, sampleUniformBSpline } from "./curves"; describe("sampleBezierChain", () => { it("weniger als 4 Punkte: Rohpunkte unverändert (Gummiband-Vorschau)", () => { diff --git a/src/geometry/curves.ts b/src/geometry/curves.ts index 7f4d4577..7a16253a 100644 --- a/src/geometry/curves.ts +++ b/src/geometry/curves.ts @@ -22,17 +22,6 @@ function toFlat(pts: Vec2[]): Float64Array { return f; } -/** Punkte einer (ggf. gedrehten) Ellipse, N gleichverteilte Parameterschritte. */ -export function ellipsePts( - center: Vec2, - rx: number, - ry: number, - rotation: number, - n = 64, -): Vec2[] { - return toPoints(core().curves_ellipse_flat(center.x, center.y, rx, ry, rotation, n)); -} - /** * Tessellierte Punkte einer kubischen Bezier-Kette. `pts` folgt dem Muster * Anker·Griff·Griff·Anker·… (`pts.length` ≡ 1 mod 3). Mit weniger als 4 diff --git a/src/geometry/kernel2d.ts b/src/geometry/kernel2d.ts index 72aa17dd..4a7289c7 100644 --- a/src/geometry/kernel2d.ts +++ b/src/geometry/kernel2d.ts @@ -26,14 +26,6 @@ export function vecEqual(a: Vec2, b: Vec2, eps = EPS): boolean { return Math.abs(a.x - b.x) <= eps && Math.abs(a.y - b.y) <= eps; } -/** Kanten einer Polylinie als [from,to]-Paare (Schlusskante bei `closed`). */ -export function polylineEdges(pts: Vec2[], closed: boolean): [Vec2, Vec2][] { - const out: [Vec2, Vec2][] = []; - for (let i = 0; i < pts.length - 1; i++) out.push([pts[i], pts[i + 1]]); - if (closed && pts.length > 2) out.push([pts[pts.length - 1], pts[0]]); - return out; -} - // ── Kodierung ──────────────────────────────────────────────────────────────── function encPts(pts: Vec2[]): Float64Array { @@ -86,21 +78,6 @@ function decPtsBulge(buf: Float64Array): { pts: Vec2[]; bulge: number[] } { // ── Punkt/Strecke, Fläche ─────────────────────────────────────────────────── -/** Abstand von p zur Strecke a→b. */ -export function pointSegmentDistance(p: Vec2, a: Vec2, b: Vec2): number { - return core().k2_point_segment_distance(p.x, p.y, a.x, a.y, b.x, b.y); -} - -/** Vorzeichenbehaftete Polygonfläche (Shoelace); >0 = CCW, <0 = CW. */ -export function signedArea(pts: Vec2[]): number { - return core().k2_signed_area(encPts(pts)); -} - -/** Ob ein Polygonzug gegen den Uhrzeigersinn (CCW) gewickelt ist. */ -export function isCCW(pts: Vec2[]): boolean { - return core().k2_is_ccw(encPts(pts)); -} - /** Schnittpunkte zweier Kreise (0/1/2 Punkte). */ export function circleCircleIntersect(c1: Vec2, r1: number, c2: Vec2, r2: number): Vec2[] { return decPts(core().k2_circle_circle_intersect(c1.x, c1.y, r1, c2.x, c2.y, r2)); @@ -108,63 +85,10 @@ export function circleCircleIntersect(c1: Vec2, r1: number, c2: Vec2, r2: number // ── Offset ─────────────────────────────────────────────────────────────────── -/** Offset einer einzelnen Strecke um `d` (links positiv). */ -export function offsetSegment(a: Vec2, b: Vec2, d: number): [Vec2, Vec2] { - const r = core().k2_offset_segment(a.x, a.y, b.x, b.y, d); - return [{ x: r[0], y: r[1] }, { x: r[2], y: r[3] }]; -} - // ── Tangente-Tangente-Radius ──────────────────────────────────────────────── -/** Ein Tangentialobjekt für `tangentCircleCenters`: Gerade (durch a/b, unendlich gedacht) oder Kreis. */ -export type TangentTarget = { kind: "line"; a: Vec2; b: Vec2 } | { kind: "circle"; center: Vec2; r: number }; - -function encTarget(t: TangentTarget): Float64Array { - return t.kind === "line" - ? Float64Array.of(0, t.a.x, t.a.y, t.b.x, t.b.y) - : Float64Array.of(1, t.center.x, t.center.y, t.r, 0); -} - -/** - * Alle Mittelpunkt-Kandidaten eines Kreises mit Radius `r`, der `t1` UND `t2` berührt - * (TTR). Unsortiert/undedupliziert; der Aufrufer wählt über einen Referenzpunkt. - */ -export function tangentCircleCenters(t1: TangentTarget, t2: TangentTarget, r: number): Vec2[] { - return decPts(core().k2_tangent_circle_centers(encTarget(t1), encTarget(t2), r)); -} - // ── Fillet / Fase ──────────────────────────────────────────────────────────── -/** Ergebnis einer Eck-Verrundung. */ -export interface Fillet { - center: Vec2; - radius: number; - /** Tangentenpunkt auf dem ersten Schenkel (corner→p1). */ - tangentA: Vec2; - /** Tangentenpunkt auf dem zweiten Schenkel (corner→p2). */ - tangentB: Vec2; - /** Bogen-Endwinkel in Radiant (für ein Arc-Primitiv). */ - startAngle: number; - endAngle: number; -} - -/** - * Verrundet die Ecke bei `corner` (Schenkel corner→p1, corner→p2) mit Radius `r`; null bei - * (nahezu) kollinearen oder zu kurzen Schenkeln. - */ -export function filletCorner(corner: Vec2, p1: Vec2, p2: Vec2, r: number): Fillet | null { - const f = core().k2_fillet_corner(corner.x, corner.y, p1.x, p1.y, p2.x, p2.y, r); - if (f.length !== 9) return null; - return { - center: { x: f[0], y: f[1] }, - radius: f[2], - tangentA: { x: f[3], y: f[4] }, - tangentB: { x: f[5], y: f[6] }, - startAngle: f[7], - endAngle: f[8], - }; -} - // ── Split / Segment löschen ───────────────────────────────────────────────── /** diff --git a/src/geometry/kernel2d.ttr.test.ts b/src/geometry/kernel2d.ttr.test.ts deleted file mode 100644 index c1ebe749..00000000 --- a/src/geometry/kernel2d.ttr.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -// Tests für `tangentCircleCenters` (Tangente-Tangente-Radius-Konstruktion), -// getrennt von `kernel2d.parity.test.ts` (dort werden nur die bereits vor -// dieser Session bestehenden Funktionen gegen die DXF-Referenzimplementierung -// geprüft). - -import { describe, it, expect } from "vitest"; -import { tangentCircleCenters, type TangentTarget } from "./kernel2d"; -import type { Vec2 } from "../model/types"; - -const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); - -/** Prüft, dass `center` mit Radius `r` tangential (Abstand == r) an `t` liegt. */ -function isTangent(center: Vec2, r: number, t: TangentTarget): boolean { - if (t.kind === "line") { - const dx = t.b.x - t.a.x, dy = t.b.y - t.a.y; - const len = Math.hypot(dx, dy); - const cross = ((center.x - t.a.x) * dy - (center.y - t.a.y) * dx) / len; - return Math.abs(Math.abs(cross) - r) < 1e-6; - } - const d = dist(center, t.center); - // Äussere ODER innere Berührung. - return Math.abs(d - (t.r + r)) < 1e-6 || Math.abs(d - Math.abs(t.r - r)) < 1e-6; -} - -describe("tangentCircleCenters — zwei Geraden", () => { - it("zwei senkrechte Geraden, Radius 2 → vier Kandidaten (je ein Quadrant)", () => { - const l1: TangentTarget = { kind: "line", a: { x: -10, y: 0 }, b: { x: 10, y: 0 } }; // X-Achse - const l2: TangentTarget = { kind: "line", a: { x: 0, y: -10 }, b: { x: 0, y: 10 } }; // Y-Achse - const cands = tangentCircleCenters(l1, l2, 2); - expect(cands.length).toBe(4); - // Ein Kandidat pro Quadrant, jeweils bei (±2, ±2). - const quadrants = [ - { x: 2, y: 2 }, - { x: 2, y: -2 }, - { x: -2, y: 2 }, - { x: -2, y: -2 }, - ]; - for (const q of quadrants) { - expect(cands.some((c) => dist(c, q) < 1e-9)).toBe(true); - } - for (const c of cands) { - expect(isTangent(c, 2, l1)).toBe(true); - expect(isTangent(c, 2, l2)).toBe(true); - } - }); - - it("parallele Geraden, Abstand ≠ 2*r → geometrisch unlösbar (ein Kreis tangential an beide Parallelen MUSS Durchmesser = Abstand haben), keine Kandidaten", () => { - const l1: TangentTarget = { kind: "line", a: { x: 0, y: 0 }, b: { x: 10, y: 0 } }; - const l2: TangentTarget = { kind: "line", a: { x: 0, y: 4 }, b: { x: 10, y: 4 } }; - // Abstand 4, Zielradius 3 (Durchmesser 6 ≠ 4) → keine Lösung. - expect(tangentCircleCenters(l1, l2, 3)).toEqual([]); - }); - - it("parallele Geraden, Abstand GENAU 2*r → degenerierter Fall (unendlich viele Lösungen entlang der Linie): bekannte Einschränkung, liefert KEINE Kandidaten statt unendlich vieler", () => { - const l1: TangentTarget = { kind: "line", a: { x: 0, y: 0 }, b: { x: 10, y: 0 } }; - const l2: TangentTarget = { kind: "line", a: { x: 0, y: 4 }, b: { x: 10, y: 4 } }; - // Abstand 4 = 2*r bei r=2 → jede x-Position auf y=2 wäre tangential an beide; - // `tangentCircleCenters` schneidet nur Geraden-PAARE (lineIntersect scheitert - // an zusammenfallenden/parallelen Geraden) und liefert hier bewusst nichts, - // statt eine beliebige der unendlich vielen Lösungen zu erraten. - expect(tangentCircleCenters(l1, l2, 2)).toEqual([]); - }); -}); - -describe("tangentCircleCenters — Gerade + Kreis", () => { - it("X-Achse + Kreis (Mittelpunkt (0,6), r=3), Zielradius 2 → Kandidaten in der Lücke, tangential an beide", () => { - // Lücke zwischen Achse und Kreis-Unterkante (y=3) ist 3 — bei Zielradius 2 - // (Durchmesser 4 > Lücke 3) passt ein Kreis, der beide von aussen berührt. - const line: TangentTarget = { kind: "line", a: { x: -10, y: 0 }, b: { x: 10, y: 0 } }; - const circle: TangentTarget = { kind: "circle", center: { x: 0, y: 6 }, r: 3 }; - const cands = tangentCircleCenters(line, circle, 2); - expect(cands.length).toBeGreaterThan(0); - for (const c of cands) { - expect(isTangent(c, 2, line)).toBe(true); - expect(isTangent(c, 2, circle)).toBe(true); - } - // Erwartet (rechnerisch): (±3, 2) — tangential an y=0 (Abstand 2) und an - // den Kreis (Abstand zu (0,6) = sqrt(9+16) = 5 = 3+2). - expect(cands.some((c) => Math.abs(c.x - 3) < 1e-9 && Math.abs(c.y - 2) < 1e-9)).toBe(true); - expect(cands.some((c) => Math.abs(c.x + 3) < 1e-9 && Math.abs(c.y - 2) < 1e-9)).toBe(true); - }); -}); - -describe("tangentCircleCenters — zwei Kreise", () => { - it("zwei getrennte Kreise, Zielradius verbindet beide von aussen (äussere Berührung)", () => { - // Loci-Radien 2+8=10 je Seite, Mittelpunkt-Abstand 16 ≤ 10+10 → lösbar, - // symmetrische Schnittpunkte bei (0, ±6) (10² = 8² + 6²). - const c1: TangentTarget = { kind: "circle", center: { x: -8, y: 0 }, r: 2 }; - const c2: TangentTarget = { kind: "circle", center: { x: 8, y: 0 }, r: 2 }; - const cands = tangentCircleCenters(c1, c2, 8); - expect(cands.length).toBeGreaterThan(0); - for (const c of cands) { - expect(isTangent(c, 8, c1)).toBe(true); - expect(isTangent(c, 8, c2)).toBe(true); - } - // Symmetrische Konfiguration: je ein Kandidat oberhalb/unterhalb der X-Achse bei x≈0. - expect(cands.some((c) => Math.abs(c.x) < 1e-6 && Math.abs(c.y - 6) < 1e-9)).toBe(true); - expect(cands.some((c) => Math.abs(c.x) < 1e-6 && Math.abs(c.y + 6) < 1e-9)).toBe(true); - }); - - it("ein kleiner Kreis INNERHALB eines grossen → innere Berührung liefert Kandidaten", () => { - const outer: TangentTarget = { kind: "circle", center: { x: 0, y: 0 }, r: 10 }; - const inner: TangentTarget = { kind: "circle", center: { x: 3, y: 0 }, r: 2 }; - // Zielkreis mit r=4, tangential von innen an `outer` und von aussen an `inner`. - const cands = tangentCircleCenters(outer, inner, 4); - expect(cands.length).toBeGreaterThan(0); - for (const c of cands) { - expect(isTangent(c, 4, outer)).toBe(true); - expect(isTangent(c, 4, inner)).toBe(true); - } - }); - - it("konzentrische Kreise gleichen Radius (innere Loci kollabieren) → keine Endlosschleife, endliches Ergebnis", () => { - const c1: TangentTarget = { kind: "circle", center: { x: 0, y: 0 }, r: 5 }; - const c2: TangentTarget = { kind: "circle", center: { x: 0, y: 0 }, r: 5 }; - const cands = tangentCircleCenters(c1, c2, 2); - // Konzentrisch → circleCircleIntersect liefert für die äussere Loci-Kombination - // nichts (gleicher Mittelpunkt, `d < EPS`); Funktion muss dennoch sauber terminieren. - expect(Array.isArray(cands)).toBe(true); - }); -}); diff --git a/src/geometry/opening.ts b/src/geometry/opening.ts deleted file mode 100644 index bb87b6f8..00000000 --- a/src/geometry/opening.ts +++ /dev/null @@ -1,48 +0,0 @@ -// Geometrie-Helfer für Öffnungen (Fenster/Türen) — reine Funktionen, die eine -// `Opening` relativ zu ihrer Wirts-Wand in konkrete Welt-Geometrie auflösen: -// • die Öffnungs-Lücke entlang der Wandachse (from/to in Metern), die Pfosten. -// (Die vertikale Lage rechnet der Kern: `model3d.rs`/`plan/section.rs`, UK/OK der Wand: `model/helpers.rs::heights`.) -// -// Da JEDE Größe aus der aktuellen Wandachse (`wall.start`/`wall.end`) abgeleitet -// wird, folgt eine Öffnung ihrer Wand automatisch, sobald die Wand bewegt wird — -// es gibt keine eingebackenen Weltkoordinaten. -// -// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). - -import type { Opening, Vec2, Wall } from "../model/types"; -import { along } from "../model/geometry"; - -/** Achslänge einer Wand (Meter). */ -export function wallAxisLength(wall: Wall): number { - return Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y); -} - -/** - * Öffnungs-Intervall entlang der Wandachse (from..to in Metern), auf die - * Achslänge geklemmt. Liefert null, wenn das Intervall entartet (Breite ≤ 0 oder - * vollständig außerhalb der Achse). - */ -export function openingInterval( - wall: Wall, - o: Opening, -): { from: number; to: number } | null { - const axis = wallAxisLength(wall); - const from = Math.max(0, Math.min(o.position, axis)); - const to = Math.max(from, Math.min(o.position + o.width, axis)); - if (to - from < 1e-4) return null; - return { from, to }; -} - -/** Die beiden Pfosten-Punkte (auf der Achse) einer Öffnung im Grundriss. */ -export function openingJambs( - wall: Wall, - o: Opening, -): { jambStart: Vec2; jambEnd: Vec2 } | null { - const iv = openingInterval(wall, o); - if (!iv) return null; - return { - jambStart: along(wall.start, wall.end, iv.from), - jambEnd: along(wall.start, wall.end, iv.to), - }; -} - diff --git a/src/geometry/revisionCloud.test.ts b/src/geometry/revisionCloud.test.ts deleted file mode 100644 index f5d70d10..00000000 --- a/src/geometry/revisionCloud.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -/** - * `revisionCloudPts` — wandelt eine geklickte Punktfolge in eine - * Beulen-Kontur (Revisionswolke) um. - */ -import { describe, it, expect } from "vitest"; -import { revisionCloudPts, REVCLOUD_BULGE } from "./revisionCloud"; -import { bulgeArcPoints } from "./bulge"; -import type { Vec2 } from "../model/types"; - -describe("revisionCloudPts", () => { - it("liefert null bei < 2 Punkten", () => { - expect(revisionCloudPts([{ x: 0, y: 0 }], false, 0.3)).toBeNull(); - }); - - it("ein einzelnes offenes Segment wird in ~len/targetArcLen Beulen zerlegt", () => { - const pts: Vec2[] = [{ x: 0, y: 0 }, { x: 3, y: 0 }]; - const res = revisionCloudPts(pts, false, 0.5)!; - expect(res).not.toBeNull(); - // 3m Länge / 0.5m Ziel-Bogenlänge ≈ 6 Beulen. - expect(res.bulge.length).toBe(6); - expect(res.bulge.every((b) => b === REVCLOUD_BULGE)).toBe(true); - // Erster und letzter Punkt der expandierten Kontur = Start/Ende der Eingabe. - expect(res.pts[0]).toEqual({ x: 0, y: 0 }); - expect(res.pts[res.pts.length - 1]).toEqual({ x: 3, y: 0 }); - }); - - it("mehrere Segmente werden nahtlos aneinandergehängt (keine doppelten Zwischenpunkte)", () => { - const pts: Vec2[] = [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 2 }]; - const res = revisionCloudPts(pts, false, 1)!; - // Der mittlere Eingabepunkt (2,0) muss GENAU EINMAL in der expandierten - // Kontur vorkommen (nicht doppelt vom Ende des ersten UND Anfang des - // zweiten Segments). - const occurrences = res.pts.filter((p) => p.x === 2 && p.y === 0).length; - expect(occurrences).toBe(1); - }); - - it("geschlossene Kontur: kein doppelter Schlusspunkt", () => { - const pts: Vec2[] = [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }]; - const res = revisionCloudPts(pts, true, 1)!; - // Der letzte Punkt der expandierten Kontur darf NICHT (0,0) sein (das - // wäre der Startpunkt erneut) — der Ring schliesst sich implizit über - // die geschlossene Interpretation, nicht über einen doppelten Punkt. - const last = res.pts[res.pts.length - 1]; - expect(last).not.toEqual({ x: 0, y: 0 }); - // Bulge-Array hat genau so viele Einträge wie Punkte (Schluss-Segment - // pts[last]→pts[0] eingerechnet, wie bei jeder geschlossenen Polylinie). - expect(res.bulge.length).toBe(res.pts.length); - }); - - it("jede Beule liegt exakt auf einem Kreisbogen mit dem erwarteten bulge (Rückwärtsprobe)", () => { - const pts: Vec2[] = [{ x: 0, y: 0 }, { x: 2, y: 0 }]; - const res = revisionCloudPts(pts, false, 1)!; - // Genau 2 Beulen bei 2m/1m Ziel-Länge. - expect(res.pts.length).toBe(3); // Start + 2 Zwischenpunkte - for (let i = 0; i < res.pts.length - 1; i++) { - const arcPts = bulgeArcPoints(res.pts[i], res.pts[i + 1], res.bulge[i]); - // Ein echter Bogen (bulge≠0) tesselliert zu MEHR als 2 Punkten. - expect(arcPts.length).toBeGreaterThan(2); - } - }); - - it("sehr kurzes Segment (kürzer als die Ziel-Bogenlänge) ergibt genau EINE Beule", () => { - const pts: Vec2[] = [{ x: 0, y: 0 }, { x: 0.1, y: 0 }]; - const res = revisionCloudPts(pts, false, 1)!; - expect(res.bulge.length).toBe(1); - }); -}); diff --git a/src/geometry/revisionCloud.ts b/src/geometry/revisionCloud.ts deleted file mode 100644 index 78d8a89e..00000000 --- a/src/geometry/revisionCloud.ts +++ /dev/null @@ -1,86 +0,0 @@ -// Revisionswolke (Nutzer-Wunsch: „Keine Revisionswolken/Markup-Werkzeuge") — -// wandelt eine geklickte (Polylinien-artige) Punktfolge in eine „ausgebeulte" -// Kontur um: jedes gerade Segment zwischen zwei aufeinanderfolgenden Punkten -// wird in mehrere gleich lange Teilstücke zerlegt, die JEWEILS als -// Kreisbogen („Beule") statt als Gerade gezeichnet werden — die klassische -// CAD-Revisionswolke. -// -// Bewusst KEIN neuer Shape-Typ: das Ergebnis ist eine ganz normale -// `Drawing2DGeom["polyline"]` mit `bulge` (DXF-Konvention, s. `bulge.ts`) — -// erbt dadurch Rendering/Snapping/Griffe/Export/Transformieren komplett vom -// bereits vorhandenen Polylinien-Pfad, exakt wie bei `polygon.ts`/den -// gerundeten Ecken von `rect.ts`. -// -// Alle Beulen bulgen in die GLEICHE Richtung relativ zur jeweiligen -// Segment-Zeichenrichtung (positives `bulge` = links von a→b, s. bulge.ts) — -// bei einem GEGEN den Uhrzeigersinn geklickten geschlossenen Zug zeigen sie -// dadurch nach AUSSEN (die übliche Optik). Die Umlaufrichtung wird bewusst -// NICHT automatisch erkannt/korrigiert (eigener, grösserer Scope) — zeichnet -// der Nutzer im Uhrzeigersinn, zeigen die Beulen nach innen; einfach in der -// anderen Richtung klicken behebt das. - -import type { Vec2 } from "../model/types"; - -const EPS = 1e-9; -/** Höchstzahl Beulen je Segment (praktische Wolken haben < 100). */ -const MAX_BUMPS_PER_SEGMENT = 2000; - -/** - * `bulge`-Wert EINER Beule — `tan(Δ/4)` für einen Öffnungswinkel Δ ≈ 100° - * (Δ = 4·atan(0.42)): sichtbar, aber nicht übertrieben rund — der übliche - * REVCLOUD-Look. - */ -export const REVCLOUD_BULGE = 0.42; - -const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); -const lerp = (a: Vec2, b: Vec2, t: number): Vec2 => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }); - -/** - * Zerlegt EIN gerades Segment a→b in `n` gleich lange Beulen (Ziel-Bogenlänge - * `targetArcLen`, mindestens 1 Beule). Liefert die neuen Zwischenpunkte OHNE - * den Startpunkt `a` (der gehört dem Aufrufer/vorherigen Segment) UND die - * `n` Bulge-Werte für die `n` neuen Teilsegmente. - */ -function expandSegment(a: Vec2, b: Vec2, targetArcLen: number): { pts: Vec2[]; bulge: number[] } { - const len = dist(a, b); - if (!Number.isFinite(len) || len < EPS) return { pts: [], bulge: [] }; - // Obergrenze gegen Unsinn-Eingaben (winzige Bogenlänge, riesige Strecke): sonst Speicher-Explosion. - const n = Math.min(MAX_BUMPS_PER_SEGMENT, Math.max(1, Math.round(len / Math.max(targetArcLen, EPS)))); - const pts: Vec2[] = []; - const bulge: number[] = []; - for (let i = 1; i <= n; i++) { - pts.push(lerp(a, b, i / n)); - bulge.push(REVCLOUD_BULGE); - } - return { pts, bulge }; -} - -/** - * Wandelt eine geklickte Punktfolge (offen ODER geschlossen) in die volle - * Revisionswolken-Kontur um: alle geraden Segmente (inkl. Schluss-Segment bei - * `closed`) werden zu Beulen-Ketten der Ziel-Bogenlänge `targetArcLen` - * expandiert. Liefert `null` bei < 2 Punkten (nichts zu zeichnen). - */ -export function revisionCloudPts( - points: Vec2[], - closed: boolean, - targetArcLen: number, -): { pts: Vec2[]; bulge: number[] } | null { - if (points.length < 2 || !Number.isFinite(targetArcLen) || targetArcLen <= 0) return null; - const segCount = closed ? points.length : points.length - 1; - const outPts: Vec2[] = [points[0]]; - const outBulge: number[] = []; - for (let s = 0; s < segCount; s++) { - const a = points[s]; - const b = points[(s + 1) % points.length]; - const { pts, bulge } = expandSegment(a, b, targetArcLen); - outPts.push(...pts); - outBulge.push(...bulge); - } - // Geschlossen: das letzte expandierte Segment endet exakt am Startpunkt - // (points[0]) — der doppelte Schlusspunkt fällt weg (der Ring schliesst - // sich implizit über `closed:true`, wie bei jeder anderen Polylinie). - if (closed) outPts.pop(); - if (outPts.length < 2) return null; - return { pts: outPts, bulge: outBulge }; -} diff --git a/src/geometry/roofEdges.test.ts b/src/geometry/roofEdges.test.ts index 8d989b61..69d9a788 100644 --- a/src/geometry/roofEdges.test.ts +++ b/src/geometry/roofEdges.test.ts @@ -2,7 +2,7 @@ // 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, roofHoleWorks, setRoofEdge } from "./roofEdges"; +import { removeRoofHole, setRoofEdge } from "./roofEdges"; const rect = (x: number, y: number, w: number, h: number): Vec2[] => [ { x, y }, @@ -45,14 +45,6 @@ describe("setRoofEdge", () => { }); describe("Höfe", () => { - it("Hof hinzufügen: Ring bleibt, ungültige (ausserhalb, Pult) wirken nicht", () => { - const r = roof(); - expect(roofHoleWorks(r, court)).toBe(true); - expect(roofHoleWorks(r, rect(10, 2, 4, 4))).toBe(false); - expect(roofHoleWorks(roof({ shape: "pult" }), court)).toBe(false); - const p = addRoofHole(r, court); - expect(p.holes).toEqual([court]); - }); it("Hof entfernen nimmt seine Kantenneigungen mit; Indizes der übrigen Höfe rücken nach", () => { const h2 = rect(1, 1, 1, 1); diff --git a/src/geometry/roofEdges.ts b/src/geometry/roofEdges.ts index 1af860e6..5141d15e 100644 --- a/src/geometry/roofEdges.ts +++ b/src/geometry/roofEdges.ts @@ -1,13 +1,12 @@ // 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`). +// Änderungen als Teilobjekt (`Partial`, für `updateRoof`/`patchItem` — ein Undo-Schritt). Höfe +// legt der Befehl im Kern an (`cmd_solid.rs`, samt Prüfung am Skelett); die Geometrie rechnet `roof.rs`. // // Kantennummerierung wie `Roof.edgePitchDeg`: erst die Kanten von `outline` (Kante i = Punkt i → // i+1), dann die der `holes` Ring für Ring. Eintrag `null` = Giebel, Zahl ≥ 0 = Neigung, negativ // (oder fehlend) = Standard. import type { Roof, Vec2 } from "../model/types"; -import { roofGeometry } from "./roof"; /** Vorgabe einer Kante. */ export type EdgeSpec = { kind: "default" } | { kind: "gable" } | { kind: "pitch"; deg: number }; @@ -50,19 +49,6 @@ export function setRoofEdge(roof: Roof, index: number, spec: EdgeSpec): Pick { - return { holes: [...(roof.holes ?? []), ring.map((p) => ({ x: p.x, y: p.y }))] }; -} - /** Teilobjekt für `updateRoof`: Hof `k` entfernen samt seinen Kantenneigungen. */ export function removeRoofHole(roof: Roof, k: number): Pick { const holes = roof.holes ?? []; diff --git a/src/geometry/roomBoundary.test.ts b/src/geometry/roomBoundary.test.ts index 0bcd58d8..df598933 100644 --- a/src/geometry/roomBoundary.test.ts +++ b/src/geometry/roomBoundary.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest"; import type { Vec2 } from "../model/types"; -import { detectRooms, roomFromPointInside, roomFromPointInsideFaces, type WallSegment } from "./roomBoundary"; +import { detectRooms, type WallSegment } from "./roomBoundary"; const P = (x: number, y: number): Vec2 => ({ x, y }); const area = (pts: Vec2[]): number => { @@ -58,24 +58,3 @@ describe("detectRooms", () => { expect(detectRooms(box(5, 4), { gapTol: Number.NaN })).toEqual([]); }); }); - -describe("roomFromPointInside", () => { - const walls = [...box(6, 4), { a: P(3, 0), b: P(3, 4), thickness: 0.2 }]; - - it("liefert die kleinste umgebende Zelle", () => { - const r = roomFromPointInside(P(1.5, 2), walls); - expect(r).not.toBeNull(); - expect(area(r!)).toBeCloseTo(2.8 * 3.8, 9); - }); - - it("ausserhalb: null", () => { - expect(roomFromPointInside(P(10, 10), walls)).toBeNull(); - expect(roomFromPointInside(P(Number.NaN, 1), walls)).toBeNull(); - }); - - it("auf Wandflächen: ohne Offset", () => { - const faces = box(4, 3).map(({ a, b }) => ({ a, b })); - expect(area(roomFromPointInsideFaces(P(2, 1), faces)!)).toBeCloseTo(12, 9); - expect(roomFromPointInsideFaces(P(9, 9), faces)).toBeNull(); - }); -}); diff --git a/src/geometry/roomBoundary.ts b/src/geometry/roomBoundary.ts index ef8009fc..8304d653 100644 --- a/src/geometry/roomBoundary.ts +++ b/src/geometry/roomBoundary.ts @@ -1,8 +1,8 @@ // Raum-Erkennung — geschlossene Raum-Umrisse aus Wandsegmenten ableiten. // // Fassade über den Rust-Kern (`src-tauri/core/src/room_boundary.rs`, Bindungen `web/room_boundary.rs`; -// die Rechnung steht in `kernel2d`: `detect_rooms`, `room_from_point_inside`, -// `room_from_point_inside_faces`). Wände gehen flach hinüber, Umrisse kommen flach zurück. +// die Rechnung steht in `kernel2d`: `detect_rooms`). Wände gehen flach hinüber, Umrisse kommen flach +// zurück. Der Klick-in-Raum des Raum-Befehls rechnet direkt im Kern (`cmd_create.rs`). // // Verfahren (Rust): planare Anordnung der Wand-MITTELLINIEN (Schnitte an Kreuzungen, Lücken ≤ `gapTol` // per Endpunkt-Snapping geschlossen), minimale Maschen über „next edge counter-clockwise" @@ -13,8 +13,6 @@ // als geschlossen modelliert werden. // // detectRooms(walls) alle Räume (lichte Innenkonturen, CCW) -// roomFromPointInside(point, walls) Klick-in-Raum: kleinste Masche um den Punkt, oder null -// roomFromPointInsideFaces(point, faces) dasselbe auf fertigen Wand-Innenflächen (ohne Offset) // // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). Einheit: METER. @@ -43,12 +41,6 @@ export interface DetectRoomsOptions { offsetToInner?: boolean; } -/** Eine Wand-Innenfläche (Face) als gerichtete/ungerichtete Strecke. */ -export interface WallFace { - a: Vec2; - b: Vec2; -} - /** `[n, (ax, ay, bx, by, dicke)…]`. */ function encodeWalls(walls: WallSegment[]): Float64Array { const out = new Float64Array(1 + 5 * walls.length); @@ -57,19 +49,6 @@ function encodeWalls(walls: WallSegment[]): Float64Array { return out; } -/** `[n, (ax, ay, bx, by)…]`. */ -function encodeFaces(faces: WallFace[]): Float64Array { - const out = new Float64Array(1 + 4 * faces.length); - out[0] = faces.length; - faces.forEach((f, i) => out.set([f.a.x, f.a.y, f.b.x, f.b.y], 1 + 4 * i)); - return out; -} - -/** `[nPkt, x, y, …]` → Umriss, leer → null. */ -function decodeRing(buf: Float64Array): Vec2[] | null { - return buf.length ? new FlatReader(buf).ring() : null; -} - /** * Erkennt geschlossene Räume aus einer Menge von Wandsegmenten (Mittellinien * mit Dicke). Liefert die lichten Innen-Umrisse (Vec2[] je Raum), CCW orientiert. @@ -87,27 +66,3 @@ export function detectRooms(walls: WallSegment[], options: DetectRoomsOptions = for (let n = r.count(); n > 0; n--) rooms.push(r.ring()); return rooms; } - -/** - * Klick-in-Raum-Fallback: findet die Masche, die den Saatpunkt einschliesst, und - * gibt ihren lichten Innen-Umriss zurück (oder null, wenn der Punkt in keiner - * geschlossenen Zelle liegt). Wählt die Masche mit kleinster Fläche, die den Punkt - * enthält (die unmittelbar umgebende Zelle statt einer grösseren umschliessenden). - */ -export function roomFromPointInside( - point: Vec2, - walls: WallSegment[], - options: DetectRoomsOptions = {}, -): Vec2[] | null { - return decodeRing( - core().room_from_point(point.x, point.y, encodeWalls(walls), options.gapTol ?? 0.05, options.offsetToInner ?? true), - ); -} - -/** - * Variante des Klick-Tracers auf bereits berechneten Wand-INNENFLÄCHEN: die Strecken - * bilden schon die lichten Wandseiten, kein Innen-Offset. - */ -export function roomFromPointInsideFaces(point: Vec2, wallFaces: WallFace[], gapTol = 0.05): Vec2[] | null { - return decodeRing(core().room_from_point_faces(point.x, point.y, encodeFaces(wallFaces), gapTol)); -} diff --git a/src/geometry/stair.test.ts b/src/geometry/stair.test.ts deleted file mode 100644 index 483af9aa..00000000 --- a/src/geometry/stair.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -/** - * `geometry/stair.ts` — Fassade über den Rust-Kern: Form-Prüfungen für gerade/L/Wendel, - * Referenz, Schnitt, Rahmen und Unsinn-Eingaben (Rust-Tests decken die Mathematik je Fall ab). - */ -import { describe, it, expect } from "vitest"; -import { defaultStepCount, stairCut, stairGeometry, stairOutline } from "./stair"; -import type { Stair } from "../model/types"; - -const base: Stair = { - id: "s", type: "stair", floorId: "eg", categoryCode: "40", shape: "straight", - start: { x: 0, y: 0 }, dir: { x: 1, y: 0 }, runLength: 3, width: 1.2, stepCount: 16, -}; - -describe("stairGeometry", () => { - it("gerade: 16 Tritte, Setzstufe, Lauflinie, Pfeil nach oben", () => { - const g = stairGeometry(base, 2.8); - expect(g.treads).toHaveLength(16); - expect(g.riserHeight).toBeCloseTo(0.175, 12); - expect(g.landing).toBeNull(); - expect(g.treads[15].topRise).toBeCloseTo(2.8, 12); - expect(g.arrow.head[1]).toEqual(g.runLine[1]); - expect(stairGeometry({ ...base, up: false }, 2.8).arrow.head[1]).toEqual(g.runLine[0]); - }); - - it("L: Podest + zweiter Lauf, turn dreht die Richtung", () => { - const l: Stair = { ...base, shape: "L", run2Length: 2 }; - const g = stairGeometry(l, 2.8); - expect(g.treads).toHaveLength(15); - expect(g.landing).toHaveLength(4); - expect(g.runLine[2].y).toBeGreaterThan(1); - expect(stairGeometry({ ...l, turn: -1 }, 2.8).runLine[2].y).toBeLessThan(-1); - }); - - it("Wendel: Keile, Auge mit 12 Punkten, Lauflinie als Bogen", () => { - const sp: Stair = { ...base, shape: "spiral", center: { x: 0, y: 0 }, start: { x: 1, y: 0 }, radius: 1, stepCount: 12 }; - const g = stairGeometry(sp, 2.4); - expect(g.treads).toHaveLength(12); - expect(g.landing).toHaveLength(12); - expect(g.runLine).toHaveLength(13); - }); - - it("Referenz links versetzt die Achse eine halbe Breite auf die Mitte", () => { - const g = stairGeometry({ ...base, referenz: "links" }, 2.8); - expect(g.treads[0].pts[0].y).toBeCloseTo(0, 12); - expect(g.treads[0].pts[3].y).toBeCloseTo(-1.2, 12); - expect(stairOutline({ ...base, referenz: "rechts" }, 0).polygon![0].y).toBeCloseTo(1.2, 12); - }); - - it("Unsinn (NaN, 0 Stufen) liefert leere bzw. Mindest-Geometrie ohne Fehler", () => { - expect(stairGeometry({ ...base, width: NaN }, 2.8).treads).toEqual([]); - 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 }); - }); -}); - -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); - expect(c.belowIndices).toEqual([0, 1, 2, 3, 4]); - expect(c.aboveIndices).toHaveLength(11); - expect(c.breakLine).toHaveLength(2); - expect(stairCut(g, 99).breakLine).toBeNull(); - expect(stairCut(stairGeometry(base, NaN), 1)).toEqual({ belowIndices: [], aboveIndices: [], breakLine: null }); - }); - - 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); - expect(defaultStepCount(0.1, 0)).toBe(2); - }); -}); diff --git a/src/geometry/stair.ts b/src/geometry/stair.ts index af50a9f1..6be71bf7 100644 --- a/src/geometry/stair.ts +++ b/src/geometry/stair.ts @@ -1,18 +1,7 @@ -// Geometrie-Helfer für Treppen (Stairs) — Fassade über den Rust-Kern -// (`src-tauri/kernel2d/src/lib.rs`: `stair_geometry`, `stair_outline`, `stair_cut`, `stair_bbox`; -// Bindungen `src-tauri/core/src/web/stair.rs`, Kodierung `src-tauri/core/src/stair.rs`). -// Aus einer `Stair` (gerade/L/Wendel) werden abgeleitet: -// • die Tritt-Rechtecke im Grundriss (jeweils mit ihrer Z-Höhe der Setzstufe), -// • das Zwischenpodest-Polygon (L / Wendel-Auge), -// • die Lauflinie (Polyline) + der Auf-/Abpfeil, -// • die Schnittposition (welche Tritte unter/über der Grundriss-Schnitthöhe -// liegen → im Plan durchgezogen vs. gestrichelt) samt SIA-Bruchlinie, -// • die Plan-Aussenlinie (`stairOutline`). -// -// Die 3D-Darstellung baut aus denselben Tritt-Rechtecken + Setzstufen-Höhen die -// Stufenboxen (siehe `plan/toWalls3d/stairs.ts`). So bleiben Plan und 3D konsistent -// aus EINER Quelle abgeleitet. Referenz (links/mitte/rechts): die gespeicherte Achse wird im -// Kern auf die visuelle Treppen-MITTE versetzt, Lauflinie samt Pfeil liegen stets auf der Mitte. +// Geometrie-Helfer für Treppen (Stairs) — Fassade über den Rust-Kern (`src-tauri/kernel2d/src/lib.rs`: +// `stair_outline`; Bindung `src-tauri/core/src/web/stair.rs`, Kodierung `src-tauri/core/src/stair.rs`): +// die Plan-Aussenlinie (`stairOutline`, Fang). Tritte, Podest, Lauflinie und Schnitt rechnet der Kern +// direkt (Plan, 3D, Zeichenbefehl `cmd_create.rs`). // // Bezeichner englisch, Kommentare deutsch. @@ -22,48 +11,17 @@ import { core } from "../engine/coreWasm"; export const IDEAL_TREAD = 0.29; export const MIN_STEPS = 2; -/** - * Sinnvolle Default-Stufenzahl aus Steighöhe + verfügbarer Lauflänge: möglichst - * nahe an der idealen Steigungshöhe, gedeckelt durch die Lauflänge (min. - * Auftritt ~0.24 m). Immer ≥ MIN_STEPS. - */ -export function defaultStepCount(totalRise: number, runLength: number): number { - return core().stair_default_step_count(totalRise, runLength); -} - -/** Ein Tritt im Grundriss (Rechteck-Polygon) samt Setzstufen-Z (Oberkante). */ -export interface TreadRect { - /** Vier Eckpunkte (CCW), Grundriss-Meter. */ - pts: Vec2[]; - /** Index der Stufe (0 = unterste). */ - index: number; - /** Oberkante dieses Tritts relativ zur Treppen-UK (Meter). */ - topRise: number; - /** Unterkante-Höhe (Setzstufe darunter) relativ zur UK (Meter). */ - baseRise: number; -} - -/** Vollständige, abgeleitete Treppengeometrie (Plan + 3D + Schnitt). */ -export interface StairGeometry { - /** Alle Tritt-Rechtecke (untere → obere Stufe). */ - treads: TreadRect[]; - /** Zwischenpodest-Polygon (L/Wendel) oder null (gerade). */ - landing: Vec2[] | null; - /** Setzstufen-Höhe (Meter). */ - riserHeight: number; - /** Auftrittstiefe (Meter) des geraden Laufs. */ - treadDepth: number; - /** Lauflinie als Polyline (Meter) — Mitte des Laufs, Start → Austritt. */ - runLine: Vec2[]; - /** Auf-/Abpfeil-Geometrie (Schaft + zwei Spitzenflügel). */ - arrow: { shaft: [Vec2, Vec2]; head: [Vec2, Vec2, Vec2] }; - /** Gesamt-Steighöhe (Meter). */ - totalRise: number; -} - const FORM = { straight: 0, L: 1, spiral: 2 } as const; const REFERENZ = { mitte: 0, links: 1, rechts: 2 } as const; +const pt = (f: Float64Array, i: number): Vec2 => ({ x: f[i], y: f[i + 1] }); + +function ptsAt(f: Float64Array, i: number, n: number): Vec2[] { + const out: Vec2[] = new Array(n); + for (let k = 0; k < n; k++) out[k] = pt(f, i + 2 * k); + return out; +} + /** Treppen-Parameter als 16 Zahlen (Aufbau: `src-tauri/core/src/stair.rs`); fehlend = NaN. */ export function encodeStair(s: Stair): Float64Array { const n = (v: number | undefined) => (v === undefined ? Number.NaN : v); @@ -84,119 +42,6 @@ export function encodeStair(s: Stair): Float64Array { ); } -const pt = (f: Float64Array, i: number): Vec2 => ({ x: f[i], y: f[i + 1] }); - -function ptsAt(f: Float64Array, i: number, n: number): Vec2[] { - const out: Vec2[] = new Array(n); - for (let k = 0; k < n; k++) out[k] = pt(f, i + 2 * k); - return out; -} - -/** Flache Treppengeometrie (Aufbau: `stair.rs`) → Objekt; leer (Unsinn-Eingabe) → leere Geometrie. */ -function decodeGeometry(f: Float64Array): StairGeometry { - if (f.length < 4) { - const z = { x: 0, y: 0 }; - return { - treads: [], landing: null, riserHeight: 0, treadDepth: 0, runLine: [], - arrow: { shaft: [z, z], head: [z, z, z] }, totalRise: 0, - }; - } - const nTreads = f[3]; - let i = 4; - const treads: TreadRect[] = []; - for (let t = 0; t < nTreads; t++, i += 11) { - treads.push({ index: f[i], topRise: f[i + 1], baseRise: f[i + 2], pts: ptsAt(f, i + 3, 4) }); - } - const nl = f[i++]; - let landing: Vec2[] | null = null; - if (nl >= 0) { - landing = ptsAt(f, i, nl); - i += 2 * nl; - } - const nRun = f[i++]; - const runLine = ptsAt(f, i, nRun); - i += 2 * nRun; - const a = ptsAt(f, i, 5); - return { - treads, - landing, - riserHeight: f[0], - treadDepth: f[1], - runLine, - arrow: { shaft: [a[0], a[1]], head: [a[2], a[3], a[4]] }, - totalRise: f[2], - }; -} - -/** Geometrie → flacher Puffer (gleicher Aufbau wie die Ausgabe von `stair_geometry_flat`). */ -function encodeGeometry(g: StairGeometry): Float64Array { - const out: number[] = [g.riserHeight, g.treadDepth, g.totalRise, g.treads.length]; - const push = (p: Vec2) => out.push(p.x, p.y); - for (const t of g.treads) { - out.push(t.index, t.topRise, t.baseRise); - t.pts.forEach(push); - } - if (g.landing) { - out.push(g.landing.length); - g.landing.forEach(push); - } else out.push(-1); - out.push(g.runLine.length); - g.runLine.forEach(push); - push(g.arrow.shaft[0]); - push(g.arrow.shaft[1]); - g.arrow.head.forEach(push); - return Float64Array.from(out); -} - -/** - * Leitet die vollständige Geometrie einer Treppe ab. `totalRise` MUSS vom - * 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)); -} - -/** - * Schnitt-Aufteilung im Grundriss: DOSSIER schneidet die Treppe auf `cutRise` - * (Schnitthöhe über OKFF). Tritte mit Oberkante ≤ cutRise werden durchgezogen - * gezeichnet (unterhalb der Schnittebene), darüberliegende gestrichelt (oberhalb, - * verdeckt). Der ERSTE Tritt oberhalb markiert die SIA-Bruchlinie (diagonaler - * Doppelstrich über die Laufbreite). - */ -export interface StairCut { - /** Indizes der Tritte UNTER der Schnittebene (durchgezogen). */ - belowIndices: number[]; - /** Indizes der Tritte ÜBER der Schnittebene (gestrichelt/verdeckt). */ - aboveIndices: number[]; - /** Bruchlinie (SIA): zwei parallele Diagonalstriche über die Laufbreite. */ - breakLine: [Vec2, Vec2][] | null; -} - -/** - * Bestimmt die Schnittaufteilung. `cutRise` = Schnitthöhe über der Treppen-UK. - * Findet den ersten Tritt, dessen Oberkante die Schnittebene überschreitet, und - * legt dort die Bruchlinie quer über den Lauf. - */ -export function stairCut(geo: StairGeometry, cutRise: number): StairCut { - const f = core().stair_cut_flat(encodeGeometry(geo), cutRise); - if (f.length < 3) return { belowIndices: [], aboveIndices: [], breakLine: null }; - let i = 0; - const nBelow = f[i++]; - const belowIndices = Array.from(f.subarray(i, i + nBelow)); - i += nBelow; - const nAbove = f[i++]; - const aboveIndices = Array.from(f.subarray(i, i + nAbove)); - i += nAbove; - const nBreak = f[i++]; - let breakLine: [Vec2, Vec2][] | null = null; - if (nBreak > 0) { - breakLine = []; - for (let k = 0; k < nBreak; k++, i += 4) breakLine.push([pt(f, i), pt(f, i + 2)]); - } - return { belowIndices, aboveIndices, breakLine }; -} - /** * Spiral-Outline: Innenbogen + Aussenbogen + zwei radiale Schliesslinien. * Die Bögen werden als Kreisbogen-Parameter geliefert (cx/cy/r/a0/a1), die @@ -221,7 +66,7 @@ export function stairOutline( stair: Stair, totalRise: number, ): { polygon: Vec2[] | null; spiral: SpiralOutlineSegments | null } { - void totalRise; // Signatur-Konsistenz mit stairGeometry; derzeit ungenutzt + void totalRise; // Signatur-Konsistenz; derzeit ungenutzt const f = core().stair_outline_flat(encodeStair(stair)); if (f.length === 0) return { polygon: null, spiral: null }; if (f[0] === 0) return { polygon: ptsAt(f, 2, f[1]), spiral: null }; diff --git a/src/geometry/stairOutline.test.ts b/src/geometry/stairOutline.test.ts index fc239c68..58f57a63 100644 --- a/src/geometry/stairOutline.test.ts +++ b/src/geometry/stairOutline.test.ts @@ -11,7 +11,7 @@ */ import { describe, it, expect } from "vitest"; -import { stairOutline, stairGeometry } from "./stair"; +import { stairOutline } from "./stair"; import type { Stair, Vec2 } from "../model/types"; /** Einfache Distanz-Funktion. */ @@ -187,25 +187,3 @@ describe("stairOutline — Referenz links/mitte/rechts (Item 4)", () => { } }); }); - -describe("stairGeometry — Lauflinie bleibt visuell zentriert (Item 4)", () => { - const totalRise = 3.0; - const links = stairGeometry({ ...geradeStair, referenz: "links" }, totalRise); - const mitte = stairGeometry({ ...geradeStair, referenz: "mitte" }, totalRise); - - it("Lauflinie liegt auf der Treppen-Mitte, nicht auf der Referenzkante (y=0)", () => { - // Bei referenz=links liegt die Mitte bei y = −width/2 = −0.6. - for (const p of links.runLine) { - expect(p.y).toBeCloseTo(-geradeStair.width / 2, 5); - } - // Bei mitte liegt die Lauflinie auf y=0 (Achse = Mitte). - for (const p of mitte.runLine) { - expect(p.y).toBeCloseTo(0, 5); - } - }); - - it("Tritte sind bei referenz=links um −width/2 versetzt", () => { - const dy = links.treads[0].pts[0].y - mitte.treads[0].pts[0].y; - expect(dy).toBeCloseTo(-geradeStair.width / 2, 5); - }); -}); diff --git a/src/model/terrain.ts b/src/model/terrain.ts index 60ddd585..3df861ac 100644 --- a/src/model/terrain.ts +++ b/src/model/terrain.ts @@ -9,6 +9,7 @@ // Gelände ist NICHT semantisch — es ist Kontext-Geometrie (Project.context). import { core } from "../engine/coreWasm"; +import { toMarkedJson } from "../core/ops"; import type { Contour, TerrainMesh } from "./types"; import { TERRAIN_CATEGORY } from "./contextCategories"; @@ -18,92 +19,14 @@ let terrainSeq = 0; export const TERRAIN_LAYER = "Terrain"; /** - * Erzeugt ein TIN aus Konturen. - * - * Algorithmus: - * 1. Sampling: jeder Stützpunkt jeder Kontur wird ein 3D-Vertex (x, y, z) mit - * z = Kontur-Höhe. Es wird KEIN zusätzliches Resampling betrieben — die - * Kontur-Vertices selbst sind die Breaklines. - * 2. Delaunay: 2D-Triangulation über die (x,y)-Projektion aller Vertices - * (Rust-Kern, `delaunay.rs`). Die Z-Höhe je Vertex bleibt erhalten → echtes Gelände-TIN. - * 3. Degenerate-Filter: Dreiecke mit (nahezu) null Fläche in der (x,y)-Ebene - * bzw. mit nicht-endlichen Koordinaten werden verworfen. - * - * Robustheit: - * • offene UND geschlossene Konturen werden gleich behandelt (nur die Punkte - * zählen; closed/offen beeinflusst die TIN-Fläche nicht). - * • leere/zu kleine Eingabe (< 3 Punkte) → leeres Mesh (kein Crash). - * • NaN/Infinity-Punkte werden vor der Triangulation aussortiert. + * Erzeugt ein TIN aus Konturen (Rust-Kern, `cmd_solid.rs::terrain_from_contours`): alle endlichen + * Stützpunkte der Konturen als Vertices (Z = Kontur-Höhe, nicht endlich → 0), 2D-Delaunay über die + * (x, y)-Projektion (`delaunay.rs`), Dreiecke mit (nahezu) null Fläche verworfen. Offene und + * geschlossene Konturen gleich; unter 3 Punkten ein leeres Mesh. */ export function generateTerrainFromContours(contours: Contour[]): TerrainMesh { const id = `terrain-${Date.now()}-${terrainSeq++}`; - const name = "Gelände"; - - // 1. Sampling: alle Kontur-Stützpunkte als (x,y,z)-Vertices sammeln, ungültige - // (nicht-endliche) Punkte überspringen. - const xs: number[] = []; - const ys: number[] = []; - const zs: number[] = []; - for (const c of contours) { - const z = Number.isFinite(c.z) ? c.z : 0; - for (const p of c.pts) { - if (!Number.isFinite(p.x) || !Number.isFinite(p.y)) continue; - xs.push(p.x); - ys.push(p.y); - zs.push(z); - } - } - - // Zu wenige Punkte für ein Dreieck → triviales leeres Mesh. - if (xs.length < 3) { - return { id, type: "terrainMesh", name, categoryCode: TERRAIN_CATEGORY.code, positions: [], indices: [] }; - } - - // 2. Delaunay über die (x,y)-Projektion. der Kern erwartet ein flaches - // [x0,y0, x1,y1, …]-Koordinatenarray. - const coords2d = new Float64Array(xs.length * 2); - for (let i = 0; i < xs.length; i++) { - coords2d[i * 2] = xs[i]; - coords2d[i * 2 + 1] = ys[i]; - } - // Der Kern (`delaunay.rs`, Port von delaunator) liefert bei kollinearen Punkten eine leere - // Triangulation — das ist korrekt. - const triangles = core().delaunay_flat(coords2d); - - // 3. positions (x,y,z) aufbauen; Z aus zs je Vertex. - const positions: number[] = new Array(xs.length * 3); - for (let i = 0; i < xs.length; i++) { - positions[i * 3] = xs[i]; - positions[i * 3 + 1] = ys[i]; - positions[i * 3 + 2] = zs[i]; - } - - // Degenerierte Dreiecke (Null-Fläche in (x,y)) herausfiltern, damit das TIN - // keine entarteten Faces enthält. - const indices: number[] = []; - const EPS_AREA = 1e-9; - for (let t = 0; t < triangles.length; t += 3) { - const a = triangles[t]; - const b = triangles[t + 1]; - const c = triangles[t + 2]; - const ax = xs[a], ay = ys[a]; - const bx = xs[b], by = ys[b]; - const cx = xs[c], cy = ys[c]; - // doppelte Dreiecksfläche (Kreuzprodukt) in der (x,y)-Ebene. - const area2 = Math.abs((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)); - if (area2 <= EPS_AREA) continue; - indices.push(a, b, c); - } - - return { - id, - type: "terrainMesh", - name, - layer: TERRAIN_LAYER, - categoryCode: TERRAIN_CATEGORY.code, - positions, - indices, - }; + return JSON.parse(core().terrain_from_contours_json(toMarkedJson(contours), id)) as TerrainMesh; } /** diff --git a/src/plan/extrudedSolidSpec.ts b/src/plan/extrudedSolidSpec.ts index 32993296..2caa980a 100644 --- a/src/plan/extrudedSolidSpec.ts +++ b/src/plan/extrudedSolidSpec.ts @@ -1,9 +1,11 @@ // Übersetzt einen `ExtrudedSolid` des Projekts in eine B-Rep-Spezifikation (`SolidSpec`, // truck/trucksolid). Gemeinsame Quelle für den 3D-Viewer (Eckenradius, Grundkörper) und den -// STEP-Export — reiner Kern, kein WASM. +// STEP-Export; die Beschreibung rechnet der Rust-Kern. import type { ExtrudedSolid } from "../model/types"; import type { SolidSpec } from "../engine/truckSolid"; +import { core } from "../engine/coreWasm"; +import { fromMarkedJson, toMarkedJson } from "../core/ops"; /** * Ob der Körper über den B-Rep-Pfad (`buildSolidMesh`) gebaut werden muss: Grundkörper @@ -17,61 +19,11 @@ export function needsBrepPath(solid: ExtrudedSolid): boolean { } /** - * B-Rep-Spezifikation des Körpers, UK auf `baseZ`. `null`, wenn truck dafür (noch) keine - * Beschreibung hat (Pyramide: Spitze als B-Rep entartet). + * B-Rep-Spezifikation des Körpers, UK auf `baseZ` (Rust-Kern, `cmd_solid.rs::extruded_solid_spec`: + * Grundkörper verschoben, Zylinder/Kegel bei Kreis-Profil, Extrusion mit Eckenradius/Fase, Loft bei + * Verjüngung). `null`, wenn truck dafür (noch) keine Beschreibung hat (Pyramide: Spitze als B-Rep entartet). */ export function extrudedSolidSpec(solid: ExtrudedSolid, floorZ: number): SolidSpec | null { - const baseZ = floorZ + (solid.baseOffset ?? 0); - if (solid.brep) { - const p0 = solid.points[0]; - const dx = p0 ? p0.x - solid.brep.origin.x : 0; - const dy = p0 ? p0.y - solid.brep.origin.y : 0; - return { kind: "translate", v: [dx, dy, baseZ], solid: solid.brep.spec as unknown as SolidSpec }; - } - if (solid.points.length < 3 || solid.height <= 0) return null; - const taper = Math.min(1, Math.max(0, solid.taper ?? 0)); - if (solid.circle && taper < 1e-6) { - return { - kind: "cylinder", - cx: solid.circle.center.x, - cy: solid.circle.center.y, - z0: baseZ, - r: solid.circle.r, - height: solid.height, - }; - } - if (solid.circle && taper >= 1 - 1e-6) { - return { - kind: "cone", - cx: solid.circle.center.x, - cy: solid.circle.center.y, - z0: baseZ, - r: solid.circle.r, - height: solid.height, - }; - } - const flat = solid.points.flatMap((p) => [p.x, p.y]); - if (taper < 1e-6) { - return { - kind: "extrude", - points: flat, - height: solid.height, - z0: baseZ, - ...((solid.cornerRadius ?? 0) > 0 ? { cornerRadius: solid.cornerRadius } : {}), - ...((solid.chamfer ?? 0) > 0 ? { chamfer: solid.chamfer } : {}), - }; - } - if (taper < 1 - 1e-6) { - const cx = solid.points.reduce((s, p) => s + p.x, 0) / solid.points.length; - const cy = solid.points.reduce((s, p) => s + p.y, 0) / solid.points.length; - const top = solid.points.flatMap((p) => [cx + (p.x - cx) * (1 - taper), cy + (p.y - cy) * (1 - taper)]); - return { - kind: "loft", - sections: [ - { z: baseZ, points: flat }, - { z: baseZ + solid.height, points: top }, - ], - }; - } - return null; + const out = core().extruded_solid_spec_json(toMarkedJson(solid), floorZ); + return out ? fromMarkedJson(out) : null; } diff --git a/src/state/groupActions.test.ts b/src/state/groupActions.test.ts index c221d07b..c73f76c9 100644 --- a/src/state/groupActions.test.ts +++ b/src/state/groupActions.test.ts @@ -7,7 +7,6 @@ import { describe, it, expect } from "vitest"; import { - activeGroupOps, applyGroupDimming, applyGroupDimmingToPlan, containingGroupId, @@ -22,7 +21,7 @@ import { materializeUnderlay, type Plan } from "../plan/generatePlan"; import type { Drawing2D, Group, Project } from "../model/types"; import { applyOps } from "../core/ops"; import type { CoreOp } from "../core/ops"; -import { addItems, replaceItem } from "../core/opsBuild"; +import { documentFor } from "../core/document"; const EMPTY_MEM = { wallIds: [] as string[], @@ -214,45 +213,48 @@ describe("applyGroupDimmingToPlan", () => { }); }); -describe("activeGroupOps ([K4] S3: neue Elemente in die aktive Gruppe, als Ops)", () => { +describe("Zeichnen in der aktiven Gruppe ([K4] S3: Gruppen-Zuordnung im Kern, `cmd_create::group_ops`)", () => { const g1: Group = { id: "g1", wallIds: ["w1"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] }; const line = (id: string) => ({ id, type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } } }) as Project["drawings2d"][number]; - /** Wendet `ops` plus die Gruppen-Ops an (wie `EngineHost.commit` in App.tsx). */ - const commit = (before: Project, ops: CoreOp[], path: string[]) => applyOps(before, [...ops, ...activeGroupOps(before, ops, path)]); + const ctx = { level: "eg", cat: "20" }; + /** Befehl im Kern rechnen (mit `group` wie `EngineHost.commit` in App.tsx) und anwenden. */ + const ops = (before: Project, req: object, group?: string): CoreOp[] => + documentFor(before).cmdOps({ ...req, ctx, stamp: "t", ...(group ? { group } : {}) }); + const commit = (before: Project, req: object, group?: string) => applyOps(before, ops(before, req, group)); + const lineReq = { cmd: "line", a: [0, 0], b: [2, 0] }; it("neu gezeichnetes Element wird Mitglied der aktiven (innersten) Gruppe", () => { - const result = commit(project([g1]), addItems("drawings2d", [line("d1")]), ["g1"]); + const result = commit(project([g1]), lineReq, "g1"); const g = result.groups!.find((x) => x.id === "g1")!; - expect(g.drawingIds).toEqual(["d1"]); + expect(g.drawingIds).toEqual(["dr2d-t-1"]); expect(g.wallIds).toEqual(["w1"]); // bestehende Mitgliedschaft bleibt }); - it("ohne aktive Gruppe (groupPath leer) keine zusätzlichen Ops", () => { - expect(activeGroupOps(project([g1]), addItems("drawings2d", [line("d1")]), [])).toEqual([]); + it("ohne aktive Gruppe keine zusätzlichen Ops", () => { + expect(ops(project([g1]), lineReq)).toHaveLength(1); }); it("ohne neue Elemente (nur Ersetzen) keine zusätzlichen Ops", () => { const p: Project = { ...project([g1]), drawings2d: [line("d0")] }; - expect(activeGroupOps(p, [replaceItem("drawings2d", { ...line("d0"), color: "#f00" })], ["g1"])).toEqual([]); - expect(activeGroupOps(p, [], ["g1"])).toEqual([]); + const move = { cmd: "transform", sel: { drawingIds: ["d0"] }, op: "move", pts: [[0, 0], [1, 0]], mode: "move", count: 1 }; + expect(ops(p, move, "g1").map((o) => o.kind)).toEqual(["replace"]); }); it("unbekannte aktive Gruppe: keine zusätzlichen Ops", () => { - expect(activeGroupOps(project([g1]), addItems("drawings2d", [line("d1")]), ["gx"])).toEqual([]); + expect(ops(project([g1]), lineReq, "gx")).toHaveLength(1); }); - it("mehrere neue Elemente auf einmal (z. B. Feld/Array) werden alle Mitglied", () => { - const result = commit(project([g1]), addItems("drawings2d", [line("d1"), line("d2"), line("d3")]), ["g1"]); - const g = result.groups!.find((x) => x.id === "g1")!; - expect(g.drawingIds.sort()).toEqual(["d1", "d2", "d3"]); + it("mehrere neue Elemente auf einmal (Mehrfachlinie) werden alle Mitglied", () => { + const result = commit(project([g1]), { cmd: "multiline", a: [0, 0], b: [4, 0], spacing: 0.3, sign: 1, count: 3 }, "g1"); + expect(result.groups!.find((x) => x.id === "g1")!.drawingIds).toEqual(["dr2d-t-1", "dr2d-t-2", "dr2d-t-3"]); }); it("verschachtelt: neues Element landet in der INNERSTEN (aktiven) Gruppe, nicht der äusseren", () => { const inner: Group = { id: "g1", wallIds: [], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: [] }; const outer: Group = { id: "g2", wallIds: [], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: ["g1"] }; - const result = commit(project([inner, outer]), addItems("drawings2d", [line("d1")]), ["g2", "g1"]); - expect(result.groups!.find((x) => x.id === "g1")!.drawingIds).toEqual(["d1"]); + const result = commit(project([inner, outer]), lineReq, "g1"); + expect(result.groups!.find((x) => x.id === "g1")!.drawingIds).toEqual(["dr2d-t-1"]); expect(result.groups!.find((x) => x.id === "g2")!.drawingIds).toEqual([]); }); }); diff --git a/src/state/groupActions.ts b/src/state/groupActions.ts index cc19ed08..f6d13b4b 100644 --- a/src/state/groupActions.ts +++ b/src/state/groupActions.ts @@ -9,11 +9,9 @@ import type { Drawing2D, Group, Project } from "../model/types"; import type { Plan, UnderlayGroup } from "../core"; import { uniqueId } from "../tools/types"; import type { Primitive } from "../core"; -import { applyOps } from "../core"; import type { CoreOp } from "../core"; -import { addItems, itemsOf, patchItem, removeItems } from "../core"; -import type { EntityCollection } from "../core"; -import { EMPTY_MEMBERSHIP, transitiveMembership } from "../core"; +import { addItems, removeItems } from "../core"; +import { transitiveMembership } from "../core"; import type { GroupMembership, MemberKind } from "../core"; export type { GroupMembership, MemberKind } from "../core"; @@ -113,58 +111,6 @@ export function applyGroupDimmingToPlan(plan: Plan, project: Project, groupPath: return { ...plan, primitives, underlay }; } -/** Liste je Mitgliedsart. */ -const COLLECTION_OF: Record = { - wallIds: "walls", - drawingIds: "drawings2d", - ceilingIds: "ceilings", - roomIds: "rooms", - stairIds: "stairs", - columnIds: "columns", - roofIds: "roofs", - openingIds: "openings", -}; - -/** - * Zeichnet man WÄHREND man eine Gruppe betreten hat (Isolation) ein neues Element, wird es - * automatisch Mitglied dieser (innersten) Gruppe — man zeichnet ja SICHTLICH „in" ihr - * (Nutzer-Wunsch, Vectorworks-Verhalten). Für eine Änderung als Ops ([K4] S3): die zusätzlichen - * Ops, die die neu eingefügten Elemente (`add`-Ops) der aktiven Gruppe zuschlagen. Leer ohne - * aktive Gruppe oder ohne neue Elemente. - */ -export function activeGroupOps(before: Project, ops: readonly CoreOp[], groupPath: string[]): CoreOp[] { - if (groupPath.length === 0) return []; - const addedIds = new Set(); - const touched = new Set(); - for (const op of ops) { - if (op.kind !== "add") continue; - touched.add(op.collection); - for (const e of op.items) addedIds.add(e.id); - } - if (addedIds.size === 0) return []; - const after = applyOps(before, ops); - const activeId = groupPath[groupPath.length - 1]; - const g = (after.groups ?? []).find((x) => x.id === activeId); - if (!g) return []; - const added = { ...EMPTY_MEMBERSHIP }; - for (const k of KEYS) { - const coll = COLLECTION_OF[k]; - if (!touched.has(coll)) continue; - // Reihenfolge wie in der Liste (wie `newIds`); vorher vorhandene ids sind nie neu. - const existed = new Set(); - for (const e of itemsOf(before, coll)) { - const id = (e as { id: string }).id; - if (addedIds.has(id)) existed.add(id); - } - added[k] = itemsOf(after, coll) - .map((e) => (e as { id: string }).id) - .filter((id) => addedIds.has(id) && !existed.has(id)); - } - if (KEYS.every((k) => added[k].length === 0)) return []; - const merged: Group = { ...g, ...mergeMembership(g, added) }; - return patchItem(after, "groups", activeId, () => merged); -} - /** * Erzeugt eine neue Gruppe aus einer Mengen-Auswahl (+ optional bereits * gewählte Gruppen, die dabei als Untergruppen verschachtelt werden — „zwei diff --git a/src/state/roofEdges.store.test.ts b/src/state/roofEdges.store.test.ts index 5ca50df2..d173cdea 100644 --- a/src/state/roofEdges.store.test.ts +++ b/src/state/roofEdges.store.test.ts @@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it } from "vitest"; import { getState, setState } from "./appStore"; import type { Project, Roof } from "../model/types"; -import { addRoofHole, removeRoofHole, roofGeometry, setRoofEdge } from "../core"; +import { removeRoofHole, roofGeometry, setRoofEdge } from "../core"; import { parseProjectFile, serializeProject } from "../io/projectFormat"; import { sampleProject } from "../model/sampleProject"; @@ -81,7 +81,7 @@ describe("Kantenneigung über Ops", () => { describe("Innenhöfe über Ops", () => { it("Hof hinzufügen und entfernen: je ein Undo-Schritt, Dach spart den Hof aus", () => { - getState().updateRoof("RF1", addRoofHole(current(), court)); + getState().updateRoof("RF1", { holes: [...(current().holes ?? []), court] }); expect(current().holes).toEqual([court]); expect(roofGeometry(current(), 0).eavesHoles).toHaveLength(1); expect(getState().undoDepth).toBe(1); diff --git a/src/tools/tools.ts b/src/tools/tools.ts index fcc2a1be..4c9107a6 100644 --- a/src/tools/tools.ts +++ b/src/tools/tools.ts @@ -1,24 +1,9 @@ -// Konkrete Werkzeuge (Phase 1: select / wall / line) + Registry. -// docs/design/drawing-tools.md §3, §4, §10. +// Werkzeug-Registry (docs/design/drawing-tools.md §3, §4, §10). Alle Zeichenwerkzeuge sind an +// Befehle gekoppelt (TOOL_COMMAND in App.tsx); die Elemente baut der Kern ([K4] S3, +// `src-tauri/core/src/cmd_create.rs`). Hier stehen nur noch Platzhalter (Label, Hinweis) und +// das Auswahl-Werkzeug. -import type { Ceiling, Drawing2D, Project, Vec2, Wall } from "../model/types"; -import { wallTypeThickness } from "../model/types"; -import { wallCorners } from "../model/geometry"; -import { addItems, ceilingArea, normalizeOutline, opsMutation } from "../core"; -import type { CoreOp } from "../core"; -import type { DraftShape, Tool, ToolContext, ToolDraft, ToolId } from "./types"; -import { uniqueId } from "./types"; - -const EPS = 1e-6; -const segLen = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y); -const segAngleDeg = (a: Vec2, b: Vec2): number => - (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI; - -/** Dicke des aktiven Wandtyps (Meter); Fallback, falls unbekannt. */ -function activeWallThickness(ctx: ToolContext): number { - const wt = ctx.project.wallTypes.find((t) => t.id === ctx.activeWallTypeId); - return wt ? wallTypeThickness(wt) : 0.2; -} +import type { Tool, ToolId } from "./types"; // ── Select ────────────────────────────────────────────────────────────────── // Reines Platzhalter-Werkzeug: die Auswahl-/Marquee-Logik bleibt in PlanView; @@ -34,200 +19,32 @@ const selectTool: Tool = { onCancel: (s) => [s, { draft: null, done: true }], }; -// ── Wall ───────────────────────────────────────────────────────────────────── -// Zeichnet eine Achs-Polylinie; jedes Segment wird ein eigenständiges Wall. -// Die Gehrung an Ecken entsteht automatisch aus der Verschneidung im Kern (`joins.rs`). - -interface WallDrawing { - phase: "drawing"; - points: Vec2[]; - cursor: Vec2 | null; -} -type WallState = { phase: "idle" } | WallDrawing; - -/** Baut die Band-Vorschau für eine Achs-Polylinie + lebendes Segment. */ -function wallDraft(points: Vec2[], cursor: Vec2 | null, ctx: ToolContext): ToolDraft { - const thickness = activeWallThickness(ctx); - const preview: DraftShape[] = []; - const all = cursor ? [...points, cursor] : points; - for (let i = 0; i < all.length - 1; i++) { - const a = all[i]; - const b = all[i + 1]; - if (segLen(a, b) < EPS) continue; - preview.push({ kind: "poly", pts: wallCorners(a, b, thickness), closed: true }); - preview.push({ kind: "line", a, b }); // Achse - } - const draft: ToolDraft = { preview, vertices: points }; - // HUD am lebenden Segment: Länge + Winkel. - if (cursor && points.length > 0) { - const a = points[points.length - 1]; - if (segLen(a, cursor) >= EPS) { - draft.hud = { - at: cursor, - text: `${segLen(a, cursor).toFixed(2)} m · ${Math.abs( - ((segAngleDeg(a, cursor) + 360) % 360), - ).toFixed(0)}°`, - }; - } - } - return draft; -} - -/** Ops: hängt je Achssegment ein Wall des aktiven Typs an. */ -function appendWalls(pts: Vec2[], ctx: ToolContext): CoreOp[] { - const height = - ctx.level.floorHeight && ctx.level.floorHeight > 0 ? ctx.level.floorHeight : 2.6; - const newWalls: Wall[] = []; - for (let i = 0; i < pts.length - 1; i++) { - const a = pts[i]; - const b = pts[i + 1]; - if (segLen(a, b) < EPS) continue; - newWalls.push({ - id: uniqueId("W"), - type: "wall", - floorId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - start: a, - end: b, - wallTypeId: ctx.activeWallTypeId, - height, - }); - } - return addItems("walls", newWalls); -} - +// ── Wall / Ceiling ─────────────────────────────────────────────────────────── +// An die gekoppelten Befehle `wall`/`ceiling` (TOOL_COMMAND in App.tsx) gebunden: Klick und +// getipptes „wall“ münden in denselben Befehl, die Elemente baut der Kern ([K4] S3, +// `cmd_create.rs`). Diese Tool-Objekte sind reine Platzhalter (wie window/door). const wallTool: Tool = { id: "wall", labelKey: "tool.wall", floorOnly: true, - hintKey: (s) => - (s as WallState).phase === "drawing" ? "tool.wall.nextPoint" : "tool.wall.firstPoint", + hintKey: () => "tool.wall.firstPoint", init: () => ({ phase: "idle" }), - onClick: (state, p, ctx) => { - const s = state as WallState; - const points = s.phase === "drawing" ? [...s.points, p.point] : [p.point]; - const next: WallState = { phase: "drawing", points, cursor: p.point }; - return [next, { draft: wallDraft(points, p.point, ctx) }]; - }, - onMove: (state, p, ctx) => { - const s = state as WallState; - if (s.phase !== "drawing") return [s, { draft: { preview: [], vertices: [] } }]; - const next: WallState = { ...s, cursor: p.point }; - return [next, { draft: wallDraft(s.points, p.point, ctx) }]; - }, - onCommitGesture: (state, ctx) => { - const s = state as WallState; - if (s.phase !== "drawing" || s.points.length < 2) { - return [{ phase: "idle" }, { draft: null, done: true }]; - } - const pts = s.points; - return [ - { phase: "idle" }, - { draft: null, done: true, commit: opsMutation(() => appendWalls(pts, ctx)) }, - ]; - }, - onCancel: () => [{ phase: "idle" }, { draft: null, done: true }], - onUndoPoint: (state, ctx) => { - const s = state as WallState; - if (s.phase === "drawing" && s.points.length > 1) { - const points = s.points.slice(0, -1); - const next: WallState = { phase: "drawing", points, cursor: s.cursor }; - return [next, { draft: wallDraft(points, s.cursor, ctx) }]; - } - return [{ phase: "idle" }, { draft: null, done: true }]; - }, + onClick: (s) => [s, { draft: null }], + onMove: (s) => [s, { draft: null }], + onCommitGesture: (s) => [s, { draft: null, done: true }], + onCancel: (s) => [s, { draft: null, done: true }], }; -// ── Ceiling ──────────────────────────────────────────────────────────────── -// Zeichnet einen GESCHLOSSENEN Umriss (wie eine geschlossene Polylinie) und -// committet daraus eine `Ceiling`. Der reguläre Zeichenpfad läuft über den -// gekoppelten `ceiling`-Befehl (TOOL_COMMAND); dieses Legacy-Tool ist eine -// vollständige, funktionsfähige Alternative (kein Stub). - -interface CeilDrawing { - phase: "drawing"; - points: Vec2[]; - cursor: Vec2 | null; -} -type CeilState = { phase: "idle" } | CeilDrawing; - -function ceilDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { - const all = cursor ? [...points, cursor] : points; - const preview: DraftShape[] = [{ kind: "poly", pts: all, closed: all.length >= 3 }]; - const draft: ToolDraft = { preview, vertices: points }; - if (cursor && points.length > 0) { - const a = points[points.length - 1]; - if (segLen(a, cursor) >= EPS) { - draft.hud = { - at: cursor, - text: `${segLen(a, cursor).toFixed(2)} m · ${Math.abs( - (segAngleDeg(a, cursor) + 360) % 360, - ).toFixed(0)}°`, - }; - } - } - return draft; -} - -function appendCeiling(project: Project, pts: Vec2[], ctx: ToolContext): CoreOp[] { - const outline = normalizeOutline(pts); - if (!outline || ceilingArea(outline) < 1e-4) return []; - const hasCat = project.layers.some((c) => c.code === "30"); - const c: Ceiling = { - id: uniqueId("C"), - type: "ceiling", - floorId: ctx.level.id, - categoryCode: hasCat ? "30" : ctx.defaultCategoryCode, - outline, - wallTypeId: ctx.activeWallTypeId, - }; - return addItems("ceilings", [c]); -} - const ceilingTool: Tool = { id: "ceiling", labelKey: "tool.ceiling", floorOnly: true, - hintKey: (s) => - (s as CeilState).phase === "drawing" - ? "tool.ceiling.nextPoint" - : "tool.ceiling.firstPoint", + hintKey: () => "tool.ceiling.firstPoint", init: () => ({ phase: "idle" }), - onClick: (state, p, ctx) => { - const s = state as CeilState; - if (s.phase !== "drawing") { - return [{ phase: "drawing", points: [p.point], cursor: p.point }, { draft: ceilDraft([p.point], p.point) }]; - } - // Klick auf den Startpunkt schließt den Umriss (ab 3 Punkten) und committet. - if (s.points.length >= 3 && segLen(p.point, s.points[0]) < EPS) { - const pts = s.points; - return [{ phase: "idle" }, { draft: null, done: true, commit: opsMutation((proj) => appendCeiling(proj, pts, ctx)) }]; - } - const points = [...s.points, p.point]; - return [{ phase: "drawing", points, cursor: p.point }, { draft: ceilDraft(points, p.point) }]; - }, - onMove: (state, p) => { - const s = state as CeilState; - if (s.phase !== "drawing") return [s, { draft: { preview: [], vertices: [] } }]; - return [{ ...s, cursor: p.point }, { draft: ceilDraft(s.points, p.point) }]; - }, - onCommitGesture: (state, ctx) => { - const s = state as CeilState; - if (s.phase !== "drawing" || s.points.length < 3) { - return [{ phase: "idle" }, { draft: null, done: true }]; - } - const pts = s.points; - return [{ phase: "idle" }, { draft: null, done: true, commit: opsMutation((proj) => appendCeiling(proj, pts, ctx)) }]; - }, - onCancel: () => [{ phase: "idle" }, { draft: null, done: true }], - onUndoPoint: (state) => { - const s = state as CeilState; - if (s.phase === "drawing" && s.points.length > 1) { - const points = s.points.slice(0, -1); - return [{ phase: "drawing", points, cursor: s.cursor }, { draft: ceilDraft(points, s.cursor) }]; - } - return [{ phase: "idle" }, { draft: null, done: true }]; - }, + onClick: (s) => [s, { draft: null }], + onMove: (s) => [s, { draft: null }], + onCommitGesture: (s) => [s, { draft: null, done: true }], + onCancel: (s) => [s, { draft: null, done: true }], }; // ── Window / Door (Öffnungen) ───────────────────────────────────────────────── @@ -293,123 +110,19 @@ const roomTool: Tool = { onCancel: (s) => [s, { draft: null, done: true }], }; -// ── Line ───────────────────────────────────────────────────────────────────── -// Zwei-Klick-Strecke → Drawing2D{shape:"line"}. - -interface LineDrawing { - phase: "drawing"; - a: Vec2; - cursor: Vec2 | null; -} -type LineState = { phase: "idle" } | LineDrawing; - -function lineDraft(a: Vec2, cursor: Vec2 | null): ToolDraft { - const preview: DraftShape[] = []; - if (cursor && segLen(a, cursor) >= EPS) preview.push({ kind: "line", a, b: cursor }); - const draft: ToolDraft = { preview, vertices: [a] }; - if (cursor && segLen(a, cursor) >= EPS) { - draft.hud = { - at: cursor, - text: `${segLen(a, cursor).toFixed(2)} m · ${Math.abs( - (segAngleDeg(a, cursor) + 360) % 360, - ).toFixed(0)}°`, - }; - } - return draft; -} - -function appendLine(a: Vec2, b: Vec2, ctx: ToolContext): CoreOp[] { - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "line", a, b }, - // Kein expliziter Linienstil → erbt Farbe/Strichstärke aus der aktiven Ebene - // (Kategorie). Ein Linienstil-Picker kann das später überschreiben. - }; - return addItems("drawings2d", [d]); -} - +// ── Line / Polyline / Rectangle ────────────────────────────────────────────── +// Gekoppelt an die Befehle `line`/`polyline`/`rect` (TOOL_COMMAND); reine Platzhalter. const lineTool: Tool = { id: "line", labelKey: "tool.line", - hintKey: (s) => - (s as LineState).phase === "drawing" ? "tool.line.secondPoint" : "tool.line.firstPoint", + hintKey: () => "tool.line.firstPoint", init: () => ({ phase: "idle" }), - onClick: (state, p, ctx) => { - const s = state as LineState; - if (s.phase !== "drawing") { - return [{ phase: "drawing", a: p.point, cursor: p.point }, { draft: lineDraft(p.point, p.point) }]; - } - // Zweiter Klick: Strecke abschließen (Null-Strecke verwerfen). - if (segLen(s.a, p.point) < EPS) { - return [{ phase: "idle" }, { draft: null, done: true }]; - } - const a = s.a; - const b = p.point; - return [ - { phase: "idle" }, - { draft: null, done: true, commit: opsMutation(() => appendLine(a, b, ctx)) }, - ]; - }, - onMove: (state, p) => { - const s = state as LineState; - if (s.phase !== "drawing") return [s, { draft: { preview: [], vertices: [] } }]; - return [{ ...s, cursor: p.point }, { draft: lineDraft(s.a, p.point) }]; - }, - // Linie braucht genau zwei Punkte; Doppelklick/Enter bricht den offenen - // Entwurf ab (kein gültiges zweites Ende gesetzt). - onCommitGesture: () => [{ phase: "idle" }, { draft: null, done: true }], - onCancel: () => [{ phase: "idle" }, { draft: null, done: true }], + onClick: (s) => [s, { draft: null }], + onMove: (s) => [s, { draft: null }], + onCommitGesture: (s) => [s, { draft: null, done: true }], + onCancel: (s) => [s, { draft: null, done: true }], }; -// ── Polyline ───────────────────────────────────────────────────────────────── -// Mehrteilige 2D-Polylinie → Drawing2D{shape:"polyline"}. Abschluss per Doppel-/ -// Rechtsklick/Enter (offen) ODER Klick auf den Startpunkt (geschlossen). - -interface PolyDrawing { - phase: "drawing"; - points: Vec2[]; - cursor: Vec2 | null; -} -type PolyState = { phase: "idle" } | PolyDrawing; - -function polyDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft { - const preview: DraftShape[] = []; - const all = cursor ? [...points, cursor] : points; - for (let i = 0; i < all.length - 1; i++) { - if (segLen(all[i], all[i + 1]) >= EPS) preview.push({ kind: "line", a: all[i], b: all[i + 1] }); - } - const draft: ToolDraft = { preview, vertices: points }; - if (cursor && points.length > 0) { - const a = points[points.length - 1]; - if (segLen(a, cursor) >= EPS) { - draft.hud = { - at: cursor, - text: `${segLen(a, cursor).toFixed(2)} m · ${Math.abs( - (segAngleDeg(a, cursor) + 360) % 360, - ).toFixed(0)}°`, - }; - } - } - return draft; -} - -function appendPolyline(pts: Vec2[], closed: boolean, ctx: ToolContext): CoreOp[] { - if (pts.length < 2) return []; - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "polyline", pts, closed }, - // Kein expliziter Linienstil → erbt Farbe/Strichstärke aus der aktiven Ebene - // (Kategorie). Ein Linienstil-Picker kann das später überschreiben. - }; - return addItems("drawings2d", [d]); -} - // Konstruktionslinie: Platzhalter-Werkzeug, gekoppelt an den `xline`-Befehl // (zwei Punkte legen die Richtung fest, Rendering/Snapping verlängern weit // darüber hinaus). Nicht floorOnly (freies 2D-Element). @@ -440,117 +153,23 @@ const rayTool: Tool = { const polylineTool: Tool = { id: "polyline", labelKey: "tool.polyline", - hintKey: (s) => - (s as PolyState).phase === "drawing" ? "tool.polyline.nextPoint" : "tool.polyline.firstPoint", + hintKey: () => "tool.polyline.firstPoint", init: () => ({ phase: "idle" }), - onClick: (state, p, ctx) => { - const s = state as PolyState; - if (s.phase !== "drawing") { - return [{ phase: "drawing", points: [p.point], cursor: p.point }, { draft: polyDraft([p.point], p.point) }]; - } - // Klick auf den Startpunkt schließt die Polylinie (ab 3 Punkten). - if (s.points.length >= 3 && segLen(p.point, s.points[0]) < EPS) { - const pts = s.points; - return [{ phase: "idle" }, { draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, true, ctx)) }]; - } - const points = [...s.points, p.point]; - return [{ phase: "drawing", points, cursor: p.point }, { draft: polyDraft(points, p.point) }]; - }, - onMove: (state, p) => { - const s = state as PolyState; - if (s.phase !== "drawing") return [s, { draft: { preview: [], vertices: [] } }]; - return [{ ...s, cursor: p.point }, { draft: polyDraft(s.points, p.point) }]; - }, - onCommitGesture: (state, ctx) => { - const s = state as PolyState; - if (s.phase !== "drawing" || s.points.length < 2) { - return [{ phase: "idle" }, { draft: null, done: true }]; - } - const pts = s.points; - return [{ phase: "idle" }, { draft: null, done: true, commit: opsMutation(() => appendPolyline(pts, false, ctx)) }]; - }, - onCancel: () => [{ phase: "idle" }, { draft: null, done: true }], - onUndoPoint: (state) => { - const s = state as PolyState; - if (s.phase === "drawing" && s.points.length > 1) { - const points = s.points.slice(0, -1); - return [{ phase: "drawing", points, cursor: s.cursor }, { draft: polyDraft(points, s.cursor) }]; - } - return [{ phase: "idle" }, { draft: null, done: true }]; - }, + onClick: (s) => [s, { draft: null }], + onMove: (s) => [s, { draft: null }], + onCommitGesture: (s) => [s, { draft: null, done: true }], + onCancel: (s) => [s, { draft: null, done: true }], }; -// ── Rectangle ──────────────────────────────────────────────────────────────── -// Zwei Ecken (Klick-Klick) → Drawing2D{shape:"rect"} (achsparallel, min/max sortiert). - -interface RectDrawing { - phase: "drawing"; - p0: Vec2; - cursor: Vec2 | null; -} -type RectState = { phase: "idle" } | RectDrawing; - -function rectCorners(a: Vec2, b: Vec2): Vec2[] { - const minX = Math.min(a.x, b.x), maxX = Math.max(a.x, b.x); - const minY = Math.min(a.y, b.y), maxY = Math.max(a.y, b.y); - return [ - { x: minX, y: minY }, - { x: maxX, y: minY }, - { x: maxX, y: maxY }, - { x: minX, y: maxY }, - ]; -} - -function rectDraft(p0: Vec2, cursor: Vec2 | null): ToolDraft { - const preview: DraftShape[] = []; - if (cursor) preview.push({ kind: "poly", pts: rectCorners(p0, cursor), closed: true }); - const draft: ToolDraft = { preview, vertices: [p0] }; - if (cursor) { - const w = Math.abs(cursor.x - p0.x); - const h = Math.abs(cursor.y - p0.y); - draft.hud = { at: cursor, text: `${w.toFixed(2)} × ${h.toFixed(2)} m` }; - } - return draft; -} - -function appendRect(a: Vec2, b: Vec2, ctx: ToolContext): CoreOp[] { - const min = { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y) }; - const max = { x: Math.max(a.x, b.x), y: Math.max(a.y, b.y) }; - if (Math.abs(max.x - min.x) < EPS || Math.abs(max.y - min.y) < EPS) return []; - const d: Drawing2D = { - id: uniqueId("dr2d"), - type: "drawing2d", - levelId: ctx.level.id, - categoryCode: ctx.defaultCategoryCode, - geom: { shape: "rect", min, max }, - // Kein expliziter Linienstil → erbt Farbe/Strichstärke aus der aktiven Ebene - // (Kategorie). Ein Linienstil-Picker kann das später überschreiben. - }; - return addItems("drawings2d", [d]); -} - const rectTool: Tool = { id: "rect", labelKey: "tool.rect", - hintKey: (s) => - (s as RectState).phase === "drawing" ? "tool.rect.secondCorner" : "tool.rect.firstCorner", + hintKey: () => "tool.rect.firstCorner", init: () => ({ phase: "idle" }), - onClick: (state, p, ctx) => { - const s = state as RectState; - if (s.phase !== "drawing") { - return [{ phase: "drawing", p0: p.point, cursor: p.point }, { draft: rectDraft(p.point, p.point) }]; - } - const a = s.p0; - const b = p.point; - return [{ phase: "idle" }, { draft: null, done: true, commit: opsMutation(() => appendRect(a, b, ctx)) }]; - }, - onMove: (state, p) => { - const s = state as RectState; - if (s.phase !== "drawing") return [s, { draft: { preview: [], vertices: [] } }]; - return [{ ...s, cursor: p.point }, { draft: rectDraft(s.p0, p.point) }]; - }, - onCommitGesture: () => [{ phase: "idle" }, { draft: null, done: true }], - onCancel: () => [{ phase: "idle" }, { draft: null, done: true }], + onClick: (s) => [s, { draft: null }], + onMove: (s) => [s, { draft: null }], + onCommitGesture: (s) => [s, { draft: null, done: true }], + onCancel: (s) => [s, { draft: null, done: true }], }; // Kreis: Platzhalter-Werkzeug (analog window/door), gekoppelt an den