diff --git a/TODO.md b/TODO.md index a8cb98b9..45a35f0f 100644 --- a/TODO.md +++ b/TODO.md @@ -734,6 +734,20 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern Gleichheit (einmalig, Test gelöscht): 400 Zufallsprojekte × Zufallsauswahl, Ops gleich bis auf die ids (Verweise Öffnung → Wand konsistent). Offen (gab es auch vorher nicht): Versatz beim wiederholten Einfügen, Gruppen mitkopieren, Einfügen in die aktive Gruppe (`activeGroupOps`). Nicht in der Tauri-App geprüft. + ✅ (29.10.) **Split / Segment löschen im Kern** ([K4] S3): `cmd_split.rs` (`{cmd: "split", ids, stamp}`, + `{cmd: "cutSegment", id, at}`), vorher `editors/splitJoin.ts` + `App.tsx`. Split wie bisher (Schnittpunkte mit den + übrigen Zeichnungen des Geschosses, sonst Mitte; Stücke an der Stelle des Originals, Stil geerbt); Segment löschen + sucht die nächste Kante (Bögen gegen die Kurve) und entfernt sie im Kern. **Fehler behoben:** `cutSegment` gab ein + Element mit NEUER id als `replace` zurück — das traf nichts, der Kern hängte es an und das Original blieb stehen + (Alt+Klick verdoppelte die Zeichnung statt sie zu kürzen; Test zuerst rot: 2 statt 1 Element). Jetzt behält das + Element id und alle Attribute (Gruppen, Sperre, Deckkraft …), nur `geom` ist neu; Füllung/Schraffur fallen wie + vorher weg (Ergebnis offen). `splitJoin.ts` ist Fassade (`splitOps`, `cutSegmentOps`); `toPolyForm` lebt nur noch + in `booleanOps.ts`. Gelöscht: TS-Rechnung (`splitDrawing`, `cutSegment`, `nearestEdgeIndex`, `fromPolyForm` …), + Fassaden `splitAtIntersections`/`splitClosedByChord`/`splitPolylineAtParam`/`removeSegment(WithBulge)` samt + Bindungen `k2_*`. Gleichheit (einmalig, Test gelöscht): 2808 Split-Fälle über 3000 Zufallszeichnungs-Sätze (Linie, + Polylinie offen/geschlossen/ohne `closed`/mit Bögen, Rechteck, Kreis, Text; zwei Geschosse) Ops gleich bis auf die + ids; 9000 Segment-Löschen (3047 mit Löschen) gleiche Geometrie bzw. gleiche Ops, Element = Original mit neuer + Geometrie. 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_split.rs b/src-tauri/core/src/cmd_split.rs new file mode 100644 index 00000000..9aa6041f --- /dev/null +++ b/src-tauri/core/src/cmd_split.rs @@ -0,0 +1,389 @@ +//! Split und Segment löschen für 2D-Zeichnungen im Kern ([K4] S3, vorher `editors/splitJoin.ts` +//! und die Aufrufer in `App.tsx`): +//! +//! - **Split** (`{cmd: "split", ids, stamp}`): jede gewählte Zeichnung (Linie, Polylinie ohne Bögen, +//! Rechteck) wird an ihren Schnittpunkten mit den übrigen Zeichnungen desselben Geschosses geteilt +//! (geschlossen + zwei Schnitte → zwei geschlossene Hälften über die Sehne); ohne Schnitt an der +//! Mitte (offen: längste Kante; geschlossen: Kante 0 und die gegenüberliegende). Die Stücke ersetzen +//! das Original an seiner Stelle (`remove` + `add` mit Position), neue ids `d2d-stamp-k`; Stil, +//! Kategorie und Geschoss werden geerbt (Füllung/Schraffur nur an geschlossene Stücke). +//! - **Segment löschen** (`{cmd: "cutSegment", id, at}`, Alt+Klick): die dem Punkt `at` nächste Kante +//! (bei Bögen gegen die tessellierte Kurve gemessen) fällt weg; geschlossen → offene Polylinie, +//! Bögen bleiben an ihrem Punktepaar. Das Element behält id und alle Attribute (nur `geom` neu; +//! Füllung/Schraffur fallen weg, weil das Ergebnis offen ist). Bleiben weniger als zwei Punkte, +//! wird es gelöscht. (Die TS-Fassung erzeugte ein Element mit NEUER id und schickte es als +//! `replace` — das traf nichts, hängte die Kopie an und liess das Original stehen.) +//! +//! Rechnung auf der rohen Projekt-Wurzel; Geometrie aus `kernel2d` (dieselben Funktionen wie +//! vorher über die Bindungen). + +use crate::cmd_transform::IdGen; +use crate::grips::{arr, field, js_num, num_of, pt, truthy, with_opt, 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::{Map, Value}; +use std::collections::{HashMap, HashSet}; + +/// Echter Bogen ab diesem |bulge| (`hasRealBulge`). +const EPS_BULGE: f64 = 1e-9; +const DRAWINGS: &str = "drawings2d"; + +fn p_of(v: &Value) -> P { + let (x, y) = xy(v); + P::new(x, y) +} + +fn real(b: &[f64]) -> bool { + b.iter().any(|x| x.abs() > EPS_BULGE) +} + +/// Polylinien-Form einer Zeichnung (`toPolyForm` / `toPolyFormAllowBulge`). +struct Form { + pts: Vec

, + /// `closed` roh (fehlend = `None`; Rechteck `true`, Linie `false`). + closed: Option, + /// Bogen-Werte roh (nur Polylinie mit `allow_bulge`). + bulge: Option>, +} + +impl Form { + fn is_closed(&self) -> bool { + truthy(self.closed.as_ref()) + } + fn bulge_nums(&self) -> Vec { + self.bulge.as_deref().map(|b| b.iter().map(|x| num_of(Some(x))).collect()).unwrap_or_default() + } +} + +fn poly_form(g: &Value, allow_bulge: bool) -> Option

{ + let pts_of = |k: &str| arr(field(g, k)).iter().map(p_of).collect::>(); + match field(g, "shape").and_then(Value::as_str).unwrap_or("") { + "line" => { + let (a, b) = (field(g, "a").map_or(P::new(f64::NAN, f64::NAN), p_of), field(g, "b").map_or(P::new(f64::NAN, f64::NAN), p_of)); + Some(Form { pts: vec![a, b], closed: Some(Value::Bool(false)), bulge: None }) + } + "polyline" => { + let bulge = field(g, "bulge").and_then(Value::as_array).cloned(); + let has = bulge.as_deref().is_some_and(|b| real(&b.iter().map(|x| num_of(Some(x))).collect::>())); + if has && !allow_bulge { + return None; + } + Some(Form { pts: pts_of("pts"), closed: field(g, "closed").cloned(), bulge: if allow_bulge { bulge } else { None } }) + } + "rect" => { + let (a, b) = (field(g, "min").map_or(P::new(f64::NAN, f64::NAN), p_of), field(g, "max").map_or(P::new(f64::NAN, f64::NAN), p_of)); + Some(Form { pts: vec![a, P::new(b.x, a.y), b, P::new(a.x, b.y)], closed: Some(Value::Bool(true)), bulge: None }) + } + _ => None, + } +} + +/// Geometrie aus einer Polylinien-Form (`fromPolyForm`): zwei Punkte, offen, ohne Bogen → Linie. +fn from_form(pts: &[P], closed: Option, bulge: Option<&[f64]>) -> Value { + let has_bulge = bulge.is_some_and(real); + let mut m = Map::new(); + if pts.len() == 2 && !truthy(closed.as_ref()) && !has_bulge { + m.insert("shape".into(), "line".into()); + m.insert("a".into(), pt(pts[0].x, pts[0].y)); + m.insert("b".into(), pt(pts[1].x, pts[1].y)); + return Value::Object(m); + } + m.insert("shape".into(), "polyline".into()); + m.insert("pts".into(), Value::Array(pts.iter().map(|p| pt(p.x, p.y)).collect())); + if let Some(c) = closed { + m.insert("closed".into(), c); + } + if let (true, Some(b)) = (has_bulge, bulge) { + m.insert("bulge".into(), Value::Array(b.iter().map(|x| js_num(*x)).collect())); + } + Value::Object(m) +} + +/// Neues Element mit Stil/Kategorie/Geschoss der Quelle (`inherit`). +fn inherit(src: &Value, geom: Value, id: String) -> Value { + let closed = field(&geom, "shape").and_then(Value::as_str) == Some("polyline") && truthy(field(&geom, "closed")); + let mut m = Map::new(); + m.insert("id".into(), Value::String(id)); + m.insert("type".into(), "drawing2d".into()); + for k in ["levelId", "categoryCode"] { + if let Some(v) = field(src, k) { + m.insert(k.into(), v.clone()); + } + } + m.insert("geom".into(), geom); + let mut copy = |k: &str| { + if let Some(v) = field(src, k) { + m.insert(k.into(), v.clone()); + } + }; + copy("lineStyleId"); + copy("color"); + copy("weightMm"); + if closed { + copy("hatchId"); + copy("fillColor"); + } + Value::Object(m) +} + +/// Teilung ohne Schnitt (`fallbackSplit`). +fn fallback_split(f: &Form) -> Vec> { + let pts = &f.pts; + let n = pts.len(); + if n < 2 { + return vec![pts.clone()]; + } + if !f.is_closed() { + let (mut best, mut best_len) = (0, -1.0); + for i in 0..n - 1 { + let d = hypot2(pts[i].x - pts[i + 1].x, pts[i].y - pts[i + 1].y); + if d > best_len { + best_len = d; + best = i; + } + } + return k::split_polyline_at_param(pts, false, best, 0.5); + } + let j = 1.max(n / 2) % n; + if j == 0 { + return vec![pts.clone()]; + } + match k::split_closed_by_chord(pts, 0, 0.5, j, 0.5) { + Some((a, b)) => vec![a, b], + None => vec![pts.clone()], + } +} + +/// Stücke einer Zeichnung (`splitDrawing`); `None` = unverändert. +fn split_drawing(src: &Value, others: &[Vec

], ids: &mut IdGen) -> Option> { + let form = poly_form(field(src, "geom").unwrap_or(&Value::Null), false)?; + let mut pieces = k::split_at_intersections(&form.pts, form.is_closed(), others); + if pieces.len() < 2 { + pieces = fallback_split(&form); + } + if pieces.len() < 2 { + return None; + } + // `form.closed && pieces.length === 2` (JS: ein falscher Wert bleibt, wie er ist). + let closed = if form.is_closed() { Some(Value::Bool(pieces.len() == 2)) } else { form.closed.clone() }; + Some(pieces.iter().map(|p| inherit(src, from_form(p, closed.clone(), None), ids.next("d2d"))).collect()) +} + +/// Split der Zeichnungen `ids`: Stücke ersetzen das Original an seiner Stelle (`replaceWithMany`). +pub fn split_ops(root: &Map, ids: &[String], stamp: &str) -> Vec { + let list = arr(root.get(DRAWINGS)); + let want: HashSet<&str> = ids.iter().map(String::as_str).collect(); + let mut gen = IdGen::new(stamp); + // id → (Stücke, Position der unveränderten Quelle); spätere gleiche ids überschreiben (wie `Map.set`). + let mut repl: HashMap<&str, (Vec, Option)> = HashMap::new(); + for (i, d) in list.iter().enumerate() { + let Some(id) = id_of(d).filter(|x| want.contains(x)) else { continue }; + let level = field(d, "levelId"); + let others: Vec> = list + .iter() + .filter(|o| id_of(o) != Some(id) && field(o, "levelId") == level) + .filter_map(|o| poly_form(field(o, "geom").unwrap_or(&Value::Null), false)) + .map(|f| { + let mut pts = f.pts; + if f.closed.as_ref().is_some_and(|c| truthy(Some(c))) && pts.len() > 2 { + pts.push(pts[0]); + } + pts + }) + .collect(); + let entry = match split_drawing(d, &others, &mut gen) { + Some(pieces) => (pieces, None), + None => (vec![d.clone()], Some(i)), + }; + repl.insert(id, entry); + } + let mut dropped: Vec = Vec::new(); + let mut inserts: Vec<(usize, Vec)> = Vec::new(); + let mut len = 0; + for (i, e) in list.iter().enumerate() { + let Some((id, (items, same))) = id_of(e).and_then(|id| repl.get(id).map(|r| (id, r))) else { + len += 1; + continue; + }; + if *same == Some(i) { + len += 1; + continue; + } + dropped.push(id.to_owned()); + if !items.is_empty() { + inserts.push((len, items.clone())); + } + len += items.len(); + } + if dropped.is_empty() { + return vec![]; + } + let mut ops = vec![Op::Remove { collection: DRAWINGS.into(), ids: dropped }]; + ops.extend(inserts.into_iter().map(|(at, items)| Op::Add { collection: DRAWINGS.into(), items, at: Some(at) })); + ops +} + +/// Punkt-Argument `{x, y}` einer Anfrage (fehlend = NaN). +pub fn point_arg(v: &Value, k: &str) -> P { + v.get(k).map_or(P::new(f64::NAN, f64::NAN), p_of) +} + +/// Abstand Punkt → Strecke (`segDist` in `splitJoin.ts`). +fn seg_dist(p: P, a: P, b: P) -> f64 { + let (abx, aby) = (b.x - a.x, b.y - a.y); + let l2 = abx * abx + aby * aby; + let t = if l2 > 0.0 { ((p.x - a.x) * abx + (p.y - a.y) * aby) / l2 } else { 0.0 }; + let t = jsnum::max(0.0, jsnum::min(1.0, t)); + hypot2(p.x - (a.x + abx * t), p.y - (a.y + aby * t)) +} + +/// Index der Kante, die `p` am nächsten liegt (`nearestEdgeIndex`); Bögen gegen die Kurve gemessen. +fn nearest_edge(f: &Form, p: P) -> Option { + let n = f.pts.len(); + if n < 2 { + return None; + } + let edges = if f.is_closed() { n } else { n - 1 }; + let bulged = real(&f.bulge_nums()); + let (mut best, mut best_d) = (None, f64::INFINITY); + for i in 0..edges { + let (a, b) = (f.pts[i], f.pts[(i + 1) % n]); + let arc: Vec

= match f.bulge.as_deref().and_then(|bl| bl.get(i)).filter(|_| bulged) { + // `bulgeArcPoints`: undefined/0 → Gerade, sonst über die Bogen-Formel (null → 0). + Some(v) if v.as_f64() != Some(0.0) => { + crate::bulge::arc_points(a.x, a.y, b.x, b.y, num_of(Some(v))).chunks_exact(2).map(|c| P::new(c[0], c[1])).collect() + } + _ => vec![a, b], + }; + for w in arc.windows(2) { + let d = seg_dist(p, w[0], w[1]); + if d < best_d { + best_d = d; + best = Some(i); + } + } + } + best +} + +/// Segment löschen: Kante nächst `at` aus der Zeichnung `id` entfernen (s. Modul-Doku). +pub fn cut_segment_ops(root: &Map, id: &str, at: P) -> Vec { + let Some(d) = arr(root.get(DRAWINGS)).iter().find(|d| id_of(d) == Some(id)) else { return vec![] }; + let Some(form) = poly_form(field(d, "geom").unwrap_or(&Value::Null), true) else { return vec![] }; + let Some(edge) = nearest_edge(&form, at) else { return vec![] }; + let bulge = form.bulge_nums(); + let (pts, bulge) = if real(&bulge) { + let r = k::remove_segment_with_bulge(&form.pts, &bulge, form.is_closed(), edge); + (r.pts, Some(r.bulge)) + } else { + (k::remove_segment(&form.pts, form.is_closed(), edge).pts, None) + }; + if pts.len() < 2 { + return vec![Op::Remove { collection: DRAWINGS.into(), ids: vec![id.to_owned()] }]; + } + let geom = from_form(&pts, Some(Value::Bool(false)), bulge.as_deref()); + let entity = with_opt(d, vec![("geom", Some(geom)), ("hatchId", None), ("fillColor", None)]); + vec![Op::Replace { collection: DRAWINGS.into(), entity }] +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn root(v: Value) -> Map { + v.as_object().unwrap().clone() + } + fn poly(id: &str, pts: &[(f64, f64)], closed: bool) -> Value { + let pts: Vec = pts.iter().map(|p| json!({"x": p.0, "y": p.1})).collect(); + json!({"id": id, "type": "drawing2d", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "polyline", "pts": pts, "closed": closed}}) + } + fn json_ops(ops: &[Op]) -> Vec { + ops.iter().map(Op::to_json).collect() + } + + #[test] + fn segment_loeschen_ersetzt_an_ort_und_stelle_mit_derselben_id() { + let mut d = poly("p", &[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (2.0, 1.0)], false); + d["color"] = json!("#f00"); + d["locked"] = json!(false); + let r = root(json!({"drawings2d": [poly("x", &[(5.0, 5.0), (6.0, 5.0)], false), d]})); + let ops = json_ops(&cut_segment_ops(&r, "p", P::new(1.9, 1.0))); + assert_eq!(ops.len(), 1); + assert_eq!(ops[0]["kind"], "replace"); + let e = &ops[0]["entity"]; + assert_eq!(e["id"], "p"); + assert_eq!(e["color"], "#f00"); + assert_eq!(e["locked"], false); + assert_eq!(e["geom"], json!({"shape": "polyline", "pts": [{"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 1, "y": 1}], "closed": false})); + // Angewendet: gleich viele Elemente, das Original ist ersetzt. + let mut doc = crate::document::Document::from_json(&serde_json::to_string(&Value::Object(r)).unwrap()).unwrap(); + doc.apply(&cut_segment_ops(doc.root(), "p", P::new(1.9, 1.0))).unwrap(); + let after = arr(doc.root().get("drawings2d")); + assert_eq!(after.len(), 2); + assert_eq!(after[1]["geom"]["pts"].as_array().unwrap().len(), 3); + } + + #[test] + fn segment_loeschen_geschlossen_wird_offen_ohne_fuellung_linie_wird_geloescht() { + let mut sq = poly("q", &[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)], true); + sq["fillColor"] = json!("#0f0"); + sq["hatchId"] = json!("h1"); + let line = json!({"id": "l", "levelId": "eg", "geom": {"shape": "line", "a": {"x": 0, "y": 5}, "b": {"x": 3, "y": 5}}}); + let r = root(json!({"drawings2d": [sq, line]})); + let e = &json_ops(&cut_segment_ops(&r, "q", P::new(1.0, 0.1)))[0]["entity"]; + assert_eq!(e["id"], "q"); + assert!(e.get("fillColor").is_none() && e.get("hatchId").is_none()); + assert_eq!(e["geom"]["closed"], false); + assert_eq!(e["geom"]["pts"], json!([{"x": 2, "y": 0}, {"x": 2, "y": 2}, {"x": 0, "y": 2}, {"x": 0, "y": 0}])); + assert_eq!(json_ops(&cut_segment_ops(&r, "l", P::new(1.0, 5.0))), vec![json!({"kind": "remove", "collection": "drawings2d", "ids": ["l"]})]); + assert!(cut_segment_ops(&r, "fehlt", P::new(0.0, 0.0)).is_empty()); + } + + #[test] + fn segment_loeschen_misst_boegen_gegen_die_kurve_und_behaelt_sie() { + // Halbkreis-Bogen auf Kante 0 (bulge 1, Ausbuchtung nach -y), gerade Kante 1. + let d = json!({"id": "b", "levelId": "eg", "geom": {"shape": "polyline", "pts": [{"x": -1, "y": 0}, {"x": 1, "y": 0}, {"x": 1, "y": 3}], "closed": false, "bulge": [1, 0]}}); + let r = root(json!({"drawings2d": [d]})); + // Punkt nahe am Bogen-Scheitel (0, -1): Kante 0 (gegen die Sehne gemessen wäre Kante 1 näher). + let e = &json_ops(&cut_segment_ops(&r, "b", P::new(0.9, -0.5)))[0]["entity"]; + assert_eq!(e["geom"], json!({"shape": "line", "a": {"x": 1, "y": 0}, "b": {"x": 1, "y": 3}})); + let e = &json_ops(&cut_segment_ops(&r, "b", P::new(1.1, 2.0)))[0]["entity"]; + assert_eq!(e["geom"]["shape"], "polyline"); + assert_eq!(e["geom"]["bulge"], json!([1])); + } + + #[test] + fn split_an_schnittpunkten_ersetzt_an_der_stelle() { + let a = json!({"id": "a", "type": "drawing2d", "levelId": "eg", "categoryCode": "20", "color": "#123", "geom": {"shape": "line", "a": {"x": 0, "y": 0}, "b": {"x": 10, "y": 0}}}); + let b = json!({"id": "b", "levelId": "eg", "geom": {"shape": "line", "a": {"x": 5, "y": -1}, "b": {"x": 5, "y": 1}}}); + let other_level = json!({"id": "c", "levelId": "og", "geom": {"shape": "line", "a": {"x": 2, "y": -1}, "b": {"x": 2, "y": 1}}}); + let r = root(json!({"drawings2d": [b.clone(), a, other_level]})); + let ops = json_ops(&split_ops(&r, &["a".into()], "s")); + assert_eq!(ops[0], json!({"kind": "remove", "collection": "drawings2d", "ids": ["a"]})); + assert_eq!(ops[1]["at"], 1); + let items = ops[1]["items"].as_array().unwrap(); + assert_eq!(items.len(), 2); + assert_eq!(items[0], json!({"id": "d2d-s-1", "type": "drawing2d", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "line", "a": {"x": 0, "y": 0}, "b": {"x": 5, "y": 0}}, "color": "#123"})); + assert_eq!(items[1]["geom"]["b"], json!({"x": 10, "y": 0})); + } + + #[test] + fn split_ohne_schnitt_an_der_mitte_geschlossen_in_zwei_geschlossene() { + let mut sq = poly("q", &[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)], true); + sq["hatchId"] = json!("h"); + let r = root(json!({"drawings2d": [sq, json!({"id": "t", "geom": {"shape": "text"}})]})); + let ops = json_ops(&split_ops(&r, &["q".into(), "t".into()], "s")); + assert_eq!(ops.len(), 2); + let items = ops[1]["items"].as_array().unwrap(); + assert_eq!(items.len(), 2); + for it in items { + assert_eq!(it["geom"]["closed"], true); + assert_eq!(it["hatchId"], "h"); + } + // Nicht teilbar (Text) → keine Op. + assert!(split_ops(&r, &["t".into()], "s").is_empty()); + } +} diff --git a/src-tauri/core/src/commands.rs b/src-tauri/core/src/commands.rs index 812f292f..e89c4636 100644 --- a/src-tauri/core/src/commands.rs +++ b/src-tauri/core/src/commands.rs @@ -27,6 +27,8 @@ pub fn ops(root: &Map, text: &str) -> Result, String> { "distribute" => crate::cmd_transform::distribute_ops(root, &ids("ids"), &s("axis")), "defblock" => crate::cmd_transform::defblock_ops(root, &parse(&v, cmd)?), "paste" => crate::cmd_paste::paste_ops(v.get("clip").unwrap_or(&Value::Null), &s("levelId"), &s("stamp")), + "split" => crate::cmd_split::split_ops(root, &ids("ids"), &s("stamp")), + "cutSegment" => crate::cmd_split::cut_segment_ops(root, &s("id"), crate::cmd_split::point_arg(&v, "at")), other => return Err(format!("Unbekannter Befehl: {other}")), }) } diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 27c7e7cf..ecb9179c 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -93,6 +93,7 @@ pub mod cmd_transform; pub mod cmd_edit; pub mod polyline_vertex; pub mod cmd_paste; +pub mod cmd_split; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/web/kernel2d.rs b/src-tauri/core/src/web/kernel2d.rs index a1b0aa54..94d15d6f 100644 --- a/src-tauri/core/src/web/kernel2d.rs +++ b/src-tauri/core/src/web/kernel2d.rs @@ -2,52 +2,16 @@ //! //! Flache `f64`-Puffer statt JSON: //! - Punktliste `pts`: `[x0, y0, x1, y1, …]` -//! - Liste von Punktlisten: `[n, (n_pts, x0, y0, …)…]` //! - „kein Ergebnis" (TS `null`): leerer Puffer. //! -//! Kaputte Eingaben (ungerade Längen, falsche Zählungen, ungültige Indizes) ergeben ein -//! leeres Ergebnis statt eines Panics. +//! Kaputte Eingaben (ungerade Längen) ergeben ein leeres Ergebnis statt eines Panics. +//! (Split/Segment löschen rechnen im Kern selbst: `cmd_split.rs`.) use kernel2d::{self as k, TangentTarget, Vec2}; use wasm_bindgen::prelude::wasm_bindgen; // --- Lesen ------------------------------------------------------------------- -/// Sequentieller Leser mit Zählungs-Prüfung. -struct Reader<'a> { - buf: &'a [f64], - i: usize, -} - -impl<'a> Reader<'a> { - fn new(buf: &'a [f64]) -> Self { - Reader { buf, i: 0 } - } - fn f(&mut self) -> Option { - let v = *self.buf.get(self.i)?; - self.i += 1; - Some(v) - } - fn count(&mut self) -> Option { - count(self.f()?) - } - fn pts(&mut self, n: usize) -> Option> { - let end = self.i.checked_add(n.checked_mul(2)?)?; - let slice = self.buf.get(self.i..end)?; - self.i = end; - Some(slice.chunks_exact(2).map(|c| Vec2::new(c[0], c[1])).collect()) - } -} - -/// Nicht-negative ganze Zahl (Zählung/Index) oder None. -fn count(v: f64) -> Option { - if v.is_finite() && v >= 0.0 && v.fract() == 0.0 && v < 1e9 { - Some(v as usize) - } else { - None - } -} - fn pts(buf: &[f64]) -> Option> { if buf.len() % 2 != 0 { return None; @@ -55,12 +19,6 @@ fn pts(buf: &[f64]) -> Option> { Some(buf.chunks_exact(2).map(|c| Vec2::new(c[0], c[1])).collect()) } -fn pt_lists(buf: &[f64]) -> Option>> { - let mut r = Reader::new(buf); - let n = r.count()?; - (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 => { @@ -86,25 +44,6 @@ fn enc_pts(pts: &[Vec2]) -> Vec { out } -fn enc_pt_lists(lists: &[Vec]) -> Vec { - let mut out = vec![lists.len() as f64]; - for l in lists { - out.push(l.len() as f64); - push_pts(&mut out, l); - } - out -} - -/// `[n_pts, xy…, bulge…]` (bulge-Anzahl = Rest des Puffers). -fn enc_pts_bulge(pts: &[Vec2], bulge: &[f64]) -> Vec { - let mut out = vec![pts.len() as f64]; - push_pts(&mut out, pts); - out.extend_from_slice(bulge); - out -} - -const EMPTY_LIST: [f64; 1] = [0.0]; - // --- Punkt/Strecke, Fläche, Kreise --------------------------------------------- #[wasm_bindgen] @@ -171,54 +110,12 @@ pub fn k2_fillet_corner(cx: f64, cy: f64, p1x: f64, p1y: f64, p2x: f64, p2y: f64 } -// --- Split / Join / Segment löschen / Bruch ---------------------------------------- - -#[wasm_bindgen] -pub fn k2_split_polyline_at_param(p: &[f64], closed: bool, edge_index: f64, t: f64) -> Vec { - let (Some(p), Some(e)) = (pts(p), count(edge_index)) else { return EMPTY_LIST.to_vec() }; - enc_pt_lists(&k::split_polyline_at_param(&p, closed, e, t)) -} - -/// Zwei Ringe oder leere Liste (TS `null`). -#[wasm_bindgen] -pub fn k2_split_closed_by_chord(p: &[f64], i: f64, ti: f64, j: f64, tj: f64) -> Vec { - let (Some(p), Some(i), Some(j)) = (pts(p), count(i), count(j)) else { return EMPTY_LIST.to_vec() }; - match k::split_closed_by_chord(&p, i, ti, j, tj) { - Some((a, b)) => enc_pt_lists(&[a, b]), - None => EMPTY_LIST.to_vec(), - } -} - -#[wasm_bindgen] -pub fn k2_remove_segment(p: &[f64], closed: bool, edge_index: f64) -> Vec { - let (Some(p), Some(e)) = (pts(p), count(edge_index)) else { return Vec::new() }; - enc_pts(&k::remove_segment(&p, closed, e).pts) -} - -#[wasm_bindgen] -pub fn k2_remove_segment_with_bulge(p: &[f64], bulge: &[f64], closed: bool, edge_index: f64) -> Vec { - let (Some(p), Some(e)) = (pts(p), count(edge_index)) else { return enc_pts_bulge(&[], &[]) }; - let r = k::remove_segment_with_bulge(&p, bulge, closed, e); - enc_pts_bulge(&r.pts, &r.bulge) -} - - - -#[wasm_bindgen] -pub fn k2_split_at_intersections(target: &[f64], closed: bool, others: &[f64]) -> Vec { - let (Some(target), Some(others)) = (pts(target), pt_lists(others)) else { return EMPTY_LIST.to_vec() }; - enc_pt_lists(&k::split_at_intersections(&target, closed, &others)) -} - - #[cfg(test)] mod tests { use super::*; #[test] fn kaputte_puffer_ergeben_leere_ergebnisse() { - assert_eq!(k2_split_polyline_at_param(&[0.0, 0.0, 1.0, 0.0], false, -1.0, 0.5), vec![0.0]); - assert_eq!(k2_split_polyline_at_param(&[0.0, 0.0, 1.0, 0.0], true, 7.0, 0.5), vec![1.0, 2.0, 0.0, 0.0, 1.0, 0.0]); assert!(k2_tangent_circle_centers(&[3.0], &[0.0, 0.0, 0.0, 1.0, 0.0], 1.0).is_empty()); } } diff --git a/src/App.tsx b/src/App.tsx index 4ebb74f7..42f3e56a 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -157,7 +157,7 @@ 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 { addItems, fieldOps, opsMutation, patchItem, patchItems, removeItems, setFieldIfChanged } from "./core"; import type { GroupMembership, MemberKind } from "./state/groupActions"; import { isLocked, lockMembersOps } from "./state/objectLock"; import { useProjectFileActions } from "./state/useProjectFileActions"; @@ -188,13 +188,7 @@ import { import type { EngineHost, EngineMods } from "./commands/engine"; import type { CommandContext } from "./commands/types"; import { t, useT } from "./i18n"; -import { - cutSegment, - nearestEdgeIndex, - splitDrawing, - toPolyForm, -} from "./editors/splitJoin"; -import type { PolyForm } from "./editors/splitJoin"; +import { cutSegmentOps, splitOps } from "./editors/splitJoin"; import { countClosedAreas, differenceDrawings, @@ -1325,25 +1319,11 @@ export default function App() { // Ergebnis; neue Elemente werden ausgewählt. Wände sind ausgenommen (no-op). const runSplit = (ids: string[]) => { if (ids.length === 0) return; - const idSet = new Set(ids); - const newIds: string[] = []; + let newIds: string[] = []; applyChange((p) => { - newIds.length = 0; - const replacements = new Map(); - for (const d of p.drawings2d) { - if (!idSet.has(d.id)) continue; - const others: PolyForm[] = []; - for (const o of p.drawings2d) { - if (o.id === d.id || o.levelId !== d.levelId) continue; - const f = toPolyForm(o.geom); - if (f) others.push(f); - } - const pieces = splitDrawing(d, others); - for (const piece of pieces) newIds.push(piece.id); - replacements.set(d.id, pieces); - } - // Jedes Quell-Drawing wird an derselben Stelle durch seine Teile ersetzt. - return replaceWithMany(p, "drawings2d", replacements); + const r = splitOps(p, ids); + newIds = r.selectIds; + return r.ops; }); setSelectedDrawingIds(newIds); setSelectedWallIds([]); @@ -1541,24 +1521,14 @@ export default function App() { // Alt+Klick im Grundriss = Segment löschen (Schere): PlanView meldet das // getroffene Drawing2D + den Modellpunkt; App ermittelt daraus die nächst- - // gelegene Kante (nearestEdgeIndex) und entfernt sie. Geschlossene Form → + // gelegene Kante (Kern `cmd_split.rs`) und entfernt sie. Geschlossene Form → // offene Polylinie; bleiben <2 Punkte übrig, wird das Element gelöscht. const onSegmentCut = (drawingId: string, model: Vec2) => { - const src = project.drawings2d.find((d) => d.id === drawingId); - if (!src) return; - const edgeIndex = nearestEdgeIndex(src.geom, model); - if (edgeIndex === null) return; let removed = false; applyChange((p) => { - removed = false; - const d = p.drawings2d.find((x) => x.id === drawingId); - if (!d) return []; - const next = cutSegment(d, edgeIndex); - if (next === null) { - removed = true; - return removeItems(p, "drawings2d", [drawingId]); - } - return [replaceItem("drawings2d", next)]; + const r = cutSegmentOps(p, drawingId, model); + removed = r.removed; + return r.ops; }); if (removed) setSelectedDrawingIds([]); }; diff --git a/src/core/index.ts b/src/core/index.ts index 464d1377..2789b52d 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -58,11 +58,6 @@ export { offsetSegment, pointSegmentDistance, polylineEdges, - removeSegment, - removeSegmentWithBulge, - splitAtIntersections, - splitClosedByChord, - splitPolylineAtParam, tangentCircleCenters, vecEqual, } from "../geometry/kernel2d"; diff --git a/src/editors/booleanOps.ts b/src/editors/booleanOps.ts index 6f6a0862..1c32acb7 100644 --- a/src/editors/booleanOps.ts +++ b/src/editors/booleanOps.ts @@ -1,5 +1,5 @@ // 2D-Boolean-Operationen (Union / Subtract / Intersect) für GESCHLOSSENE -// 2D-Zeichenelemente (Drawing2D). Ergänzt Split/Join (`splitJoin.ts`). Wandelt +// 2D-Zeichenelemente (Drawing2D). Ergänzt Split/Join (Kern `cmd_split.rs`/`cmd_edit.rs`). Wandelt // Drawing2D ↔ Ring-/Polygon-Format der Polygon-Booleans des Rust-Kerns (`polygonBool`, i_overlay) und liefert // neue Drawing2D-Listen. Stil-, Kategorie- und Level-Attribute werden geerbt // (vom ersten bzw. Basis-Element). @@ -21,8 +21,34 @@ type MultiPolygon = polygonClipping.MultiPolygon; type Polygon = polygonClipping.Polygon; type Ring = polygonClipping.Ring; import type { Drawing2D, Drawing2DGeom, Vec2 } from "../model/types"; -import { toPolyForm } from "./splitJoin"; -import type { PolyForm } from "./splitJoin"; +import { hasRealBulge } from "../core"; + +/** Polylinien-Darstellung einer geschlossenen Zeichnung (Stützpunkte). */ +interface PolyForm { + pts: Vec2[]; + closed: boolean; +} + +/** + * Stützpunkte einer Zeichnung: Linie, Polylinie ohne Bögen, Rechteck; sonst `null` (Kreis, Bogen, + * Text …; Polylinien mit Bögen würden zu Sehnen entarten). + */ +function toPolyForm(geom: Drawing2DGeom): PolyForm | null { + switch (geom.shape) { + case "line": + return { pts: [geom.a, geom.b], closed: false }; + case "polyline": + if (hasRealBulge(geom.bulge)) return null; + return { pts: geom.pts.slice(), closed: geom.closed }; + case "rect": + return { + pts: [geom.min, { x: geom.max.x, y: geom.min.y }, geom.max, { x: geom.min.x, y: geom.max.y }], + closed: true, + }; + default: + return null; + } +} /** Ist die Geometrie eines Drawing2D eine GESCHLOSSENE Fläche (für Boolean)? */ export function isClosedArea(geom: Drawing2DGeom): boolean { @@ -33,7 +59,7 @@ export function isClosedArea(geom: Drawing2DGeom): boolean { /** * Wandelt ein geschlossenes Drawing2D in ein Kern-`Polygon` - * (Ring-Liste). Reuse: `toPolyForm` aus splitJoin liefert die Stützpunkte. Der + * (Ring-Liste). `toPolyForm` liefert die Stützpunkte. Der * Ring wird als `[x,y]`-Paare gebildet; der Kern schließt selbst * (erster==letzter ist nicht erforderlich, aber unschädlich). Liefert `null`, * wenn die Form nicht geschlossen ist oder zu wenige Punkte hat. diff --git a/src/editors/splitJoin.test.ts b/src/editors/splitJoin.test.ts index 15dc5e8f..24682084 100644 --- a/src/editors/splitJoin.test.ts +++ b/src/editors/splitJoin.test.ts @@ -3,7 +3,8 @@ * erhalten bleiben (nicht mehr stillschweigend zu Geraden entarten). */ import { describe, it, expect } from "vitest"; -import { cutSegment, nearestEdgeIndex } from "./splitJoin"; +import { cutSegmentOps, splitOps } from "./splitJoin"; +import { getState } from "../state/appStore"; import type { Drawing2D, Project } from "../model/types"; import { documentFor } from "../core/document"; import { applyOps } from "../core/ops"; @@ -67,7 +68,15 @@ describe("Join — bulge-Erhalt", () => { }); }); -describe("cutSegment / nearestEdgeIndex — bulge-Erhalt", () => { +/** Segment löschen über den Kern: die geänderte Zeichnung (null = gelöscht). */ +function cut(src: Drawing2D, at: { x: number; y: number }): Drawing2D | null { + const p = { ...sampleProject, drawings2d: [src] } as Project; + const next = applyOps(p, cutSegmentOps(p, src.id, at).ops).drawings2d; + expect(next.length).toBeLessThanOrEqual(1); + return next[0] ?? null; +} + +describe("Segment löschen (Kern `cmd_split.rs`) — bulge-Erhalt", () => { it("Segment-Löschen an einer GERADEN Kante lässt den Bogen der Nachbarkante unangetastet (offen)", () => { // 4 Kanten: Bogen(0->1), gerade(1->2), gerade(2->3), gerade(3->4). Löscht Kante 1 // (das längere, punktreichere Reststück rechts wird behalten, s. removeSegmentWithBulge). @@ -76,28 +85,58 @@ describe("cutSegment / nearestEdgeIndex — bulge-Erhalt", () => { [{ x: -1, y: 0 }, { x: 1, y: 0 }, { x: 2, y: 0 }, { x: 3, y: 0 }, { x: 4, y: 0 }], [1, 0, 0, 0], ); - const out = cutSegment(src, 1); + const out = cut(src, { x: 1.5, y: 0.01 }); expect(out).not.toBeNull(); if (!out || out.geom.shape !== "polyline") return; // Rechtes (längeres) Stück bleibt: [2,0] -> [3,0] -> [4,0], keine Kante mehr mit Bogen. expect(out.geom.pts).toEqual([{ x: 2, y: 0 }, { x: 3, y: 0 }, { x: 4, y: 0 }]); - // fromPolyForm lässt das bulge-Feld ganz weg, wenn kein echter Bogen mehr übrig ist. + // Das bulge-Feld fällt ganz weg, wenn kein echter Bogen mehr übrig ist. expect(out.geom.bulge).toBeUndefined(); }); it("Segment-Löschen an der BOGEN-Kante selbst entfernt genau diesen Bogen", () => { - const src = poly("a", [{ x: -1, y: 0 }, { x: 1, y: 0 }, { x: 2, y: 0 }], [1, 0]); - const out = cutSegment(src, 0); - expect(out).not.toBeNull(); - if (!out || out.geom.shape !== "polyline") return; - expect(out.geom.pts).toEqual([{ x: 1, y: 0 }, { x: 2, y: 0 }]); - expect(out.geom.bulge?.[0] ?? 0).toBeCloseTo(0, 6); - }); - - it("nearestEdgeIndex trifft die Bogen-Kante auch, wenn der Klickpunkt neben der Sehne liegt (auf dem Bogen)", () => { - // Halbkreis von (-1,0) nach (1,0), bulge=1 -> Apex bei (0,1). + // Halbkreis (-1,0)→(1,0) mit bulge 1 (Scheitel bei (0,-1)), dann gerade nach (1,2). const src = poly("a", [{ x: -1, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 2 }], [1, 0]); - const idx = nearestEdgeIndex(src.geom, { x: 0, y: 0.95 }); - expect(idx).toBe(0); // Bogen-Kante, nicht die gerade Kante 1 + // Der Klickpunkt liegt am Bogen, aber näher an der geraden Kante als an der Sehne: getroffen wird + // der Bogen (Abstand gegen die Kurve gemessen). + const out = cut(src, { x: 0.7, y: -0.65 }); + expect(out).not.toBeNull(); + if (!out) return; + expect(out.geom).toEqual({ shape: "line", a: { x: 1, y: 0 }, b: { x: 1, y: 2 } }); + }); +}); + +describe("Segment löschen ersetzt an Ort und Stelle", () => { + it("das Element behält id und Attribute, die Liste bleibt gleich lang (Store)", () => { + // Früher erzeugte cutSegment ein Element mit NEUER id als `replace` → angehängt, Original blieb. + const d: Drawing2D = { + id: "p", type: "drawing2d", levelId: "eg", categoryCode: "20", color: "#f00", opacity: 0.5, + geom: { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 1 }], closed: false }, + }; + getState().loadProject({ ...sampleProject, drawings2d: [d] } as Project); + getState().applyChange((p) => cutSegmentOps(p, "p", { x: 1.9, y: 1 }).ops); + const after = getState().project.drawings2d; + expect(after.length).toBe(1); + expect(after[0]).toEqual({ ...d, geom: { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], closed: false } }); + getState().undo(); + expect(getState().project.drawings2d).toEqual([d]); + }); +}); + +describe("Split (Kern `cmd_split.rs`)", () => { + it("teilt an den Schnittpunkten, Stücke an der Stelle des Originals, Auswahl = Stücke", () => { + const a: Drawing2D = { id: "a", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 10, y: 0 } } }; + const b: Drawing2D = { id: "b", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: 4, y: -1 }, b: { x: 4, y: 1 } } }; + const z: Drawing2D = { id: "z", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "circle", center: { x: 0, y: 0 }, r: 1 } }; + const p = { ...sampleProject, drawings2d: [a, b, z] } as Project; + const { ops, selectIds } = splitOps(p, ["a", "z"]); + const next = applyOps(p, ops).drawings2d; + expect(next.map((d) => d.geom)).toEqual([ + { shape: "line", a: { x: 0, y: 0 }, b: { x: 4, y: 0 } }, + { shape: "line", a: { x: 4, y: 0 }, b: { x: 10, y: 0 } }, + b.geom, + z.geom, + ]); + expect(new Set(selectIds)).toEqual(new Set(["z", next[0].id, next[1].id])); }); }); diff --git a/src/editors/splitJoin.ts b/src/editors/splitJoin.ts index 1b6507cf..3d5a3b98 100644 --- a/src/editors/splitJoin.ts +++ b/src/editors/splitJoin.ts @@ -1,269 +1,37 @@ -// Editier-Operationen Split / Segment-Löschen für 2D-Zeichenelemente (Join: Kern `cmd_edit.rs`) -// (Drawing2D). Wandeln Drawing2D ↔ {pts, closed}, rufen den reinen Geometrie- -// Kernel (`../geometry/kernel2d`) und liefern neue Drawing2D-Listen. Stil-, -// Kategorie- und Level-Attribute der Quelle werden geerbt. +// Split / Segment löschen für 2D-Zeichenelemente — Fassade über den Kern ([K4] S3, +// `src-tauri/core/src/cmd_split.rs`; Join: `cmd_edit.rs`). Der Kern rechnet auf dem Dokument des +// Projekts und liefert Ops; hier nur die Anfrage und die ids für die Nachauswahl. // // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). -import type { Drawing2D, Drawing2DGeom, Vec2 } from "../model/types"; -import { removeSegment, removeSegmentWithBulge, splitAtIntersections, splitClosedByChord, splitPolylineAtParam, vecEqual } from "../core"; -import { bulgeArcPoints, hasRealBulge } from "../core"; - -/** Eine Polylinien-Darstellung eines Drawing2D (für die Kernel-Funktionen). */ -export interface PolyForm { - pts: Vec2[]; - closed: boolean; - /** Bogen-Segmente (DXF-bulge, s. `geometry/bulge.ts`) — nur bei `toPolyFormAllowBulge`. */ - bulge?: number[]; -} +import type { Project, Vec2 } from "../model/types"; +import type { CoreOp } from "../core"; +import { documentFor } from "../core/document"; +import { uniqueStamp } from "../tools/types"; /** - * Wandelt die Geometrie eines Drawing2D in eine Polylinien-Form `{pts, closed}`. - * Nur line/polyline/rect werden unterstützt (circle/arc/text → `null`). + * Split der Zeichnungen `ids` an ihren Schnittpunkten mit den übrigen Zeichnungen des Geschosses + * (ohne Schnitt an der Mitte). Die Stücke ersetzen das Original an seiner Stelle. `selectIds`: die + * Stücke und die nicht teilbaren gewählten Zeichnungen (Nachauswahl). */ -export function toPolyForm(geom: Drawing2DGeom): PolyForm | null { - switch (geom.shape) { - case "line": - return { pts: [geom.a, geom.b], closed: false }; - case "polyline": - // Bogen-Segmente (bulge) hier noch nicht unterstützt — Split/Segment- - // Löschen bauen pts komplett neu auf und würden bestehende Bögen - // stillschweigend zu Geraden entarten lassen, s. offset.ts. (Join hat - // eine eigene, bulge-erhaltende Variante, s. `toPolyFormAllowBulge`.) - if (hasRealBulge(geom.bulge)) return null; - return { pts: geom.pts.slice(), closed: geom.closed }; - case "rect": - return { - pts: [ - geom.min, - { x: geom.max.x, y: geom.min.y }, - geom.max, - { x: geom.min.x, y: geom.max.y }, - ], - closed: true, - }; - default: - return null; +export function splitOps(project: Project, ids: readonly string[]): { ops: CoreOp[]; selectIds: string[] } { + const ops = documentFor(project).cmdOps({ cmd: "split", ids, stamp: uniqueStamp() }); + const removed = new Set(); + const added: string[] = []; + for (const op of ops) { + if (op.kind === "remove") for (const id of op.ids) removed.add(id); + if (op.kind === "add") for (const e of op.items) added.push((e as { id: string }).id); } + const have = new Set(project.drawings2d.map((d) => d.id)); + return { ops, selectIds: [...ids.filter((id) => have.has(id) && !removed.has(id)), ...added] }; } /** - * Wie {@link toPolyForm}, aber lässt Bogen-Segmente (bulge) durch — für Segment-Löschen - * (`cutSegment`/`nearestEdgeIndex`), das den bulge an seinem Punktepaar mitträgt. + * Segment löschen (Alt+Klick): die dem Modellpunkt `at` nächste Kante der Zeichnung `id` fällt weg + * (geschlossen → offen; Bögen bleiben). Das Element behält id und Attribute; bleiben weniger als + * zwei Punkte, wird es gelöscht (`removed`). */ -function toPolyFormAllowBulge(geom: Drawing2DGeom): PolyForm | null { - if (geom.shape === "polyline") return { pts: geom.pts.slice(), closed: geom.closed, bulge: geom.bulge }; - return toPolyForm(geom); +export function cutSegmentOps(project: Project, id: string, at: Vec2): { ops: CoreOp[]; removed: boolean } { + const ops = documentFor(project).cmdOps({ cmd: "cutSegment", id, at }); + return { ops, removed: ops.some((op) => op.kind === "remove") }; } - -/** - * Baut aus einer Polylinien-Form die passende Drawing2D-Geometrie. Zwei Punkte + - * offen → `line`; sonst `polyline` (geschlossen oder offen). Rechtecke werden - * NICHT rekonstruiert (nach dem Schneiden sind die Teile beliebige Polygone). - */ -export function fromPolyForm(form: PolyForm): Drawing2DGeom { - const pts = form.pts; - if (pts.length === 2 && !form.closed && !hasRealBulge(form.bulge)) { - return { shape: "line", a: pts[0], b: pts[1] }; - } - const geom: Drawing2DGeom = { shape: "polyline", pts, closed: form.closed }; - if (hasRealBulge(form.bulge)) geom.bulge = form.bulge; - return geom; -} - -let counter = 0; -/** Eindeutige Drawing2D-ID (zeitbasiert + Zähler, damit ein Split nicht kollidiert). */ -function newId(prefix: string): string { - counter += 1; - return `${prefix}-${Date.now()}-${counter}`; -} - -/** Übernimmt Stil-/Kategorie-/Level-Attribute der Quelle auf ein neues Drawing2D. */ -function inherit(src: Drawing2D, geom: Drawing2DGeom): Drawing2D { - const out: Drawing2D = { - id: newId("d2d"), - type: "drawing2d", - levelId: src.levelId, - categoryCode: src.categoryCode, - geom, - }; - if (src.lineStyleId !== undefined) out.lineStyleId = src.lineStyleId; - if (src.color !== undefined) out.color = src.color; - if (src.weightMm !== undefined) out.weightMm = src.weightMm; - // Füllung/Schraffur nur an geschlossene Ergebnisse weitergeben. - const closed = - geom.shape === "polyline" ? geom.closed : geom.shape === "rect"; - if (closed) { - if (src.hatchId !== undefined) out.hatchId = src.hatchId; - if (src.fillColor !== undefined) out.fillColor = src.fillColor; - } - return out; -} - -/** - * Split eines Drawing2D gegen alle ANDEREN Elemente (`others`, als PolyForm). - * • Trifft das Ziel andere Elemente, wird an den Schnittpunkten geteilt - * (geschlossen + 2 Schnitte → zwei GESCHLOSSENE Polygone via Sehne). - * • Ohne Schnitt: Fallback — an der Kanten-MITTE der „längsten" Kante teilen - * (offen → zwei Stücke; geschlossen → an einer Kantenmitte + der gegenüber- - * liegenden Kantenmitte zu zwei geschlossenen Hälften). - * Liefert ≥2 neue Drawing2D, oder `[src]` (unverändert), wenn keine Teilung - * möglich war (z. B. nicht-polyline Form). Stil/Kategorie/Level werden geerbt. - */ -export function splitDrawing( - src: Drawing2D, - others: PolyForm[], -): Drawing2D[] { - const form = toPolyForm(src.geom); - if (!form) return [src]; - - const otherPts = others.map((o) => - // Geschlossene als Ring (erster==letzter) übergeben, damit der Kernel die - // Schlusskante als Kante erkennt. - o.closed && o.pts.length > 2 ? [...o.pts, o.pts[0]] : o.pts, - ); - - let pieces = splitAtIntersections(form.pts, form.closed, otherPts); - - // Kein Schnitt-Ergebnis (eine Liste, identisch zur Quelle) → Fallback. - const noCut = pieces.length < 2; - if (noCut) { - pieces = fallbackSplit(form); - } - - if (pieces.length < 2) return [src]; - - // Jedes Stück: geschlossen bleibt geschlossen NUR, wenn das Original - // geschlossen war UND der Schnitt zwei geschlossene Hälften erzeugte - // (Sehnen-Split / Fallback-geschlossen). Bei offenem Aufschneiden sind die - // Stücke offen. - const piecesClosed = form.closed && isClosedSplit(form, pieces); - return pieces.map((pts) => - inherit(src, fromPolyForm({ pts, closed: piecesClosed })), - ); -} - -/** - * Heuristik: erzeugte der Schnitt zwei GESCHLOSSENE Hälften (Sehnen-Split)? - * Wahr, wenn das Original geschlossen war und genau zwei Stücke entstanden - * (Chord-Split) — diese sollen wieder geschlossen sein. Bei mehr Stücken - * (geschlossen an >2 Schnitten aufgetrennt) bleiben sie offen. - */ -function isClosedSplit(form: PolyForm, pieces: Vec2[][]): boolean { - return form.closed && pieces.length === 2; -} - -/** - * Fallback ohne Schnitt mit anderen Elementen: an der Mitte teilen. - * • Offen: längste Kante an t=0.5 in zwei offene Stücke. - * • Geschlossen: an den Mitten zweier „gegenüberliegender" Kanten in zwei - * geschlossene Polygone (Sehne zwischen den beiden Kantenmitten). - */ -function fallbackSplit(form: PolyForm): Vec2[][] { - const n = form.pts.length; - if (n < 2) return [form.pts]; - if (!form.closed) { - // Längste Kante suchen. - let best = 0; - let bestLen = -1; - for (let i = 0; i < n - 1; i++) { - const d = dist(form.pts[i], form.pts[i + 1]); - if (d > bestLen) { - bestLen = d; - best = i; - } - } - return splitPolylineAtParam(form.pts, false, best, 0.5); - } - // Geschlossen: Kante 0 und die „gegenüberliegende" Kante. - const i = 0; - const j = Math.max(1, Math.floor(n / 2)) % n; - if (i === j) return [form.pts]; - // Direkt den Kernel-Chord-Split nutzen. - const res = splitClosedHalf(form.pts, i, j); - return res ?? [form.pts]; -} - -/** Geschlossenes Polygon an den Mitten der Kanten i und j halbieren. */ -function splitClosedHalf(pts: Vec2[], i: number, j: number): Vec2[][] | null { - // Reuse: splitClosedByChord ist im Kernel; hier über splitAtIntersections-Form - // nachzubauen wäre umständlich — direkt importieren. - const res = chordSplit(pts, i, 0.5, j, 0.5); - return res; -} - -function chordSplit( - pts: Vec2[], - i: number, - ti: number, - j: number, - tj: number, -): Vec2[][] | null { - const r = splitClosedByChord(pts, i, ti, j, tj); - return r ? [r[0], r[1]] : null; -} - -const dist = (a: Vec2, b: Vec2): number => - Math.hypot(a.x - b.x, a.y - b.y); - -/** - * Segment-Löschen (Schere): entfernt das Segment `edgeIndex` aus einem - * Drawing2D. Geschlossene Form → offene Polylinie. Liefert das geänderte - * Drawing2D, oder `null`, wenn weniger als 2 Punkte übrig blieben (Element - * komplett löschen) bzw. die Form nicht unterstützt wird. Bogen-Segmente - * (bulge) bleiben dabei an ihrem Punktepaar erhalten (s. `removeSegmentWithBulge`). - */ -export function cutSegment(src: Drawing2D, edgeIndex: number): Drawing2D | null { - const form = toPolyFormAllowBulge(src.geom); - if (!form) return src; // nicht unterstützte Form unverändert lassen - const res = hasRealBulge(form.bulge) - ? removeSegmentWithBulge(form.pts, form.bulge!, form.closed, edgeIndex) - : removeSegment(form.pts, form.closed, edgeIndex); - if (res.pts.length < 2) return null; - return inherit(src, fromPolyForm(res)); -} - -/** - * Liefert den Index der Kante eines Drawing2D, die dem Modellpunkt `p` am - * nächsten liegt (für Alt+Klick = Segment-Löschen). `null`, wenn die Form keine - * Kanten hat (circle/arc/text) oder zu wenige Punkte. Bei Bogen-Segmenten - * (bulge) wird der Abstand gegen die tessellierte Bogenkurve gemessen (nicht - * gegen die Sehne), der Index bleibt aber der der ORIGINAL-Kante — wichtig, - * da `cutSegment` denselben Index gegen das bulge-Array auflöst. - */ -export function nearestEdgeIndex(geom: Drawing2DGeom, p: Vec2): number | null { - const form = toPolyFormAllowBulge(geom); - if (!form || form.pts.length < 2) return null; - const n = form.pts.length; - const edgeCount = form.closed ? n : n - 1; - let best: number | null = null; - let bestD = Infinity; - for (let i = 0; i < edgeCount; i++) { - const a = form.pts[i]; - const b = form.pts[(i + 1) % n]; - const arcPts = hasRealBulge(form.bulge) ? bulgeArcPoints(a, b, form.bulge?.[i]) : [a, b]; - for (let k = 0; k < arcPts.length - 1; k++) { - const d = segDist(p, arcPts[k], arcPts[k + 1]); - if (d < bestD) { - bestD = d; - best = i; - } - } - } - return best; -} - -/** Abstand Punkt → Strecke (lokal, klein gehalten). */ -function segDist(p: Vec2, a: Vec2, b: Vec2): number { - const abx = b.x - a.x; - const aby = b.y - a.y; - const l2 = abx * abx + aby * aby; - let t = l2 > 0 ? ((p.x - a.x) * abx + (p.y - a.y) * aby) / l2 : 0; - t = Math.max(0, Math.min(1, t)); - const cx = a.x + abx * t; - const cy = a.y + aby * t; - return Math.hypot(p.x - cx, p.y - cy); -} - -// `vecEqual` re-export für etwaige Aufrufer (Auswahl-Vergleich). -export { vecEqual }; diff --git a/src/geometry/kernel2d.ts b/src/geometry/kernel2d.ts index 72aa17dd..1ad99fe2 100644 --- a/src/geometry/kernel2d.ts +++ b/src/geometry/kernel2d.ts @@ -45,45 +45,12 @@ function encPts(pts: Vec2[]): Float64Array { return out; } -/** Fehlende/`null`-Einträge → 0 (Gerade), wie im Rust-Kern. */ -function encBulge(bulge: (number | undefined)[] | undefined): Float64Array { - return Float64Array.from(bulge ?? [], (b) => b ?? 0); -} - -/** Liste von Punktlisten: `[n, (n_pts, xy…)…]`. */ -function encPtLists(lists: Vec2[][]): Float64Array { - const out: number[] = [lists.length]; - for (const l of lists) { - out.push(l.length); - for (const p of l) out.push(p.x, p.y); - } - return Float64Array.from(out); -} - function decPts(buf: Float64Array, from = 0, count = (buf.length - from) / 2): Vec2[] { const out: Vec2[] = []; for (let k = 0; k < count; k++) out.push({ x: buf[from + 2 * k], y: buf[from + 2 * k + 1] }); return out; } -function decPtLists(buf: Float64Array): Vec2[][] { - const n = buf[0] ?? 0; - const out: Vec2[][] = []; - let i = 1; - for (let k = 0; k < n; k++) { - const m = buf[i++]; - out.push(decPts(buf, i, m)); - i += 2 * m; - } - return out; -} - -/** `[n_pts, xy…, bulge…]`. */ -function decPtsBulge(buf: Float64Array): { pts: Vec2[]; bulge: number[] } { - const n = buf[0] ?? 0; - return { pts: decPts(buf, 1, n), bulge: Array.from(buf.subarray(1 + 2 * n)) }; -} - // ── Punkt/Strecke, Fläche ─────────────────────────────────────────────────── /** Abstand von p zur Strecke a→b. */ @@ -164,56 +131,3 @@ export function filletCorner(corner: Vec2, p1: Vec2, p2: Vec2, r: number): Fille endAngle: f[8], }; } - -// ── Split / Segment löschen ───────────────────────────────────────────────── - -/** - * Teilt eine Polylinie an P = lerp(pts[edgeIndex], pts[edgeIndex+1], t). Offen → zwei - * offene Stücke; geschlossen → eine offene, bei P aufgeschnittene Polylinie. - */ -export function splitPolylineAtParam(pts: Vec2[], closed: boolean, edgeIndex: number, t: number): Vec2[][] { - return decPtLists(core().k2_split_polyline_at_param(encPts(pts), closed, edgeIndex, t)); -} - -/** - * Teilt ein geschlossenes Polygon an zwei Randpunkten (Kanten i/j, Parameter ti/tj) über die - * Sehne in zwei geschlossene Polygone; null bei i==j. - */ -export function splitClosedByChord( - pts: Vec2[], - i: number, - ti: number, - j: number, - tj: number, -): [Vec2[], Vec2[]] | null { - const r = decPtLists(core().k2_split_closed_by_chord(encPts(pts), i, ti, j, tj)); - return r.length === 2 ? [r[0], r[1]] : null; -} - -/** - * Entfernt das Segment `edgeIndex`. Offen: innere Kante → das punktreichere Stück bleibt, - * Randkante → End-Vertex fällt weg. Geschlossen: an der Kante zur offenen Polylinie aufgetrennt. - */ -export function removeSegment(pts: Vec2[], closed: boolean, edgeIndex: number): { pts: Vec2[]; closed: boolean } { - return { pts: decPts(core().k2_remove_segment(encPts(pts), closed, edgeIndex)), closed: false }; -} - -/** Wie {@link removeSegment}, trägt aber das bulge-Array mit (bulge bleibt an seinem Punktepaar). */ -export function removeSegmentWithBulge( - pts: Vec2[], - bulge: number[], - closed: boolean, - edgeIndex: number, -): { pts: Vec2[]; closed: boolean; bulge: number[] } { - const r = decPtsBulge(core().k2_remove_segment_with_bulge(encPts(pts), encBulge(bulge), closed, edgeIndex)); - return { pts: r.pts, closed: false, bulge: r.bulge }; -} - -/** - * Teilt das Ziel an allen Schnittpunkten mit `others`. Geschlossen + genau zwei Schnitte → - * zwei geschlossene Polygone; offen → Stücke an den Schnittpunkten. - */ -export function splitAtIntersections(targetPts: Vec2[], closed: boolean, others: Vec2[][]): Vec2[][] { - return decPtLists(core().k2_split_at_intersections(encPts(targetPts), closed, encPtLists(others))); -} -