[K4] Merge: Einfügen, Teilen/Segment löschen (Fehler: Original blieb stehen) und Fang-Kandidaten im Kern

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-29 15:16:43 +00:00
commit 51a37af64b
29 files changed
+1871 -1316

No files matched your search

+53
View File
@@ -726,6 +726,59 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
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`.
✅ (29.10.) **Einfügen im Kern** ([K4] S3): `cmd_paste.rs` (`{cmd: "paste", clip, levelId, stamp}`): Klone mit neuen
ids `prefix-stamp-k` auf dem aktiven Geschoss, an denselben Koordinaten; Öffnungen an die mitkopierte Wirtswand
umgehängt (ohne sie weggelassen); Rechnung auf rohem JSON (unbekannte Felder, Schlüsselreihenfolge bleiben). Die
Zwischenablage (Sammeln, Text-Format, Speicher) bleibt in TS; `pasteElementClipboard(project, clip, level)` ist
Fassade (neue ids für die Nachauswahl aus den `add`-Ops), die Tastatur ruft sie in `applyChange((p) => …)`.
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.
✅ (29.10.) **Fang-Kandidaten aus dem Modell im Kern** ([K4] S3/[K3d]): `snap_model.rs` sammelt je Dokument-Stand,
Geschoss und sichtbaren Ebenen (vorher `baseSegments`/`collectCircles`/`roomAnchors`/`ellipseCenters` in
`tools/snapping.ts`): Wandachsen + Schichtgrenzen, Raum-/Decken- (mit Aussparungen)/Dach-/Treppen-/Stützen-Umrisse,
2D-Zeichnungen (Konstruktionslinie/Strahl verlängert, Bezier/Spline tesselliert), Kreise/Bögen (Zeichnungen, runde
Stützen, Wendeltreppe), Raum-Anker, Ellipsen-Mittelpunkte — in zwei Teilen (Modell / Zeichnungen), Schlüssel
Epoche + Feld-Stände (`Revs`): eine Wand-Änderung sammelt die Zeichnungen nicht neu und umgekehrt; ein
unverändertes Dokument liefert dieselbe Nummer (`doc_snap_hold`). Je Mausbewegung EIN Aufruf `snap_query`
(Strecken-Fang wie bisher in `snap.rs`, jetzt über beide Teile; Nahmodus > 2000 Zeichnungen im Kern: Strecken bis
6·Toleranz über den Raster-Index, nach Abstand sortiert, Schnitt unter den 64 nächsten; dazu Raum-Anker und
Kreis-Block mit Mittelpunkt/Quadranten/Bogen-Endpunkten/Tangente). TS behält Toleranz in Pixeln, Teilpunkte/
Verweilen, Parallele, Entwurfspunkte, Blatt-Geometrie (Vorauswahl), Raster/Winkel. Neue Fassade
`geometry/modelSnap.ts`; gelöscht: TS-Sammlung, `wallLayerBoundarySegments`, `model/wall.ts`
(`wallReferenceOffset`, kein Aufrufer mehr), `geometry/snapSegments.ts` samt Bindungen `snap_segs_hold`/
`snap_segs_release`/`snap_eval`, `isIndexable`, Fassaden-Exporte `drawingsNear`/`stairOutline`. Epochen der
Dokumente sind jetzt über alle Dokumente eindeutig (auch `Document::from_json`), damit Caches ausserhalb des
Dokuments ein neu geöffnetes Dokument unter derselben Nummer erkennen.
Gleichheit (einmalig, Test gelöscht): 20 100 `computeSnap`-Abfragen alt/neu JSON-gleich (Beispielprojekt,
300 Zufallsprojekte mit allen Bauteilarten, je 6 Projekte mit 1500 bzw. 2500 Zeichnungen (Nahmodus) aus Linien,
Polylinien, Kreisen, Bögen, Rechtecken, Konstruktionslinien, Ellipsen auf zwei Geschossen, bigSample(3); zufällige
Fang-Einstellungen, Toleranzen, Massstäbe, letzter Punkt/Entwurf, Ebenen-Sichtbarkeit, Verweilen 0 ms (Teilpunkte,
Parallele)): 0 Abweichungen, alle Fang-Arten getroffen. Bleibende Tests: `geometry/modelSnap.test.ts` (Kern gegen
Suche über alle Strecken/Paare, Nummer stabil), `tools/snapping.test.ts` (Schichtgrenzen über `computeSnap`),
Rust `snap_model::tests`, Messung `tools/snapping.perf.test.ts`.
Messung (vitest/Store, `--no-opt`-WASM, Container unter Last, je Mausbewegung = Mittel über 400 Positionen,
kleinster aus 3 Läufen; Plan vorher erzeugt wie in der App; alt → neu): 3000 Wände + 20 000 Zeichnungen
(Nahmodus) 9,7 ms → 23 µs, erster Fang 188 → 25 ms, nach Wand-Änderung 7,5 → 2,6 ms, nach Zeichnungs-Änderung
52 → 11 ms; 3000 Wände + 1500 Zeichnungen 232 → 180 µs (im selben Lauf abwechselnd: 340–450 → 290–300 µs), nach
Wand-Änderung 11 → 2,5 ms; Kataster 150 000 Zeichnungen 39 → 15 µs, erster Fang 334 → 136 ms, nach
Zeichnungs-Änderung 195 → 93 ms (nativ: Strecken 36 ms + Index ~100 ms für 450 000 Strecken; ohne vorher gebaute
typisierte Sicht kommen ~470 ms dazu). Nicht in der Tauri-App geprüft. Offen: Blatt-Geometrie (Schnitt/Ansicht,
`sheetSnapGeometry.ts`) wird weiter in TS je Mausbewegung vorausgewählt.
**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
+17
View File
@@ -47,3 +47,20 @@ test("Geschoss wechseln", async ({ page }) => {
await page.getByText("Erdgeschoss", { exact: true }).first().click();
await expect(statusFloor).toContainText("Erdgeschoss");
});
test("Kopieren/Einfügen einer Wand (Kern `cmd_paste.rs`): Kopie im Baum, ein Undo-Schritt", async ({ page }) => {
await startNewProject(page);
await openSample(page);
await openTab(page, "Elemente");
// Die Kopie bekommt eine neue id `W-Stempel-k` (Zeit-Zähler-k; im Baum gekürzt „W-17…44-1-1“).
const pasted = elementRows(page).filter({ hasText: /W-\d+…\d*-\d+-\d+/ });
await expect(pasted).toHaveCount(0);
await selectW1(page);
await blurFocus(page);
await page.keyboard.press("ControlOrMeta+c");
await page.keyboard.press("ControlOrMeta+v");
await expect(pasted).toHaveCount(1);
await blurFocus(page);
await page.keyboard.press("ControlOrMeta+z");
await expect(pasted).toHaveCount(0);
});
+109
View File
@@ -0,0 +1,109 @@
//! Einfügen der Element-Zwischenablage im Kern ([K4] S3, vorher `pasteElementClipboard` in
//! `editors/elementClipboard.ts`). Die Zwischenablage selbst (tief kopierte Elemente je Bauteil-Art)
//! hält die TS-Hülle; die Anfrage trägt sie mit (`{cmd: "paste", clip, levelId, stamp}`).
//!
//! Einfügen = Klone mit neuen ids (`prefix-stamp-k`, [`IdGen`]) auf dem aktiven Geschoss, an
//! denselben Modell-Koordinaten (kein Versatz, wie das bisherige Verhalten). Verweise: eine Öffnung
//! hängt an ihrer Wirtswand (`hostWallId`) und wird auf die neue Wand umgehängt; ohne mitkopierte
//! Wirtswand fällt sie weg (keine Öffnung ohne Wirt). Gruppen-Mitgliedschaften werden nicht
//! mitkopiert (die Klone sind neue, ungruppierte Elemente).
//!
//! Rechnung auf rohem JSON (`{...e, id, floorId}`: vorhandene Schlüssel behalten ihre Stelle,
//! fehlende kommen ans Ende, unbekannte Felder bleiben).
use crate::cmd_transform::IdGen;
use crate::grips::{arr, field, with_all};
use crate::ops::{id_of, Op};
use serde_json::Value;
use std::collections::HashMap;
/// Listen der Zwischenablage: (Schlüssel in `clip`, Projekt-Liste, id-Präfix, Geschoss-Feld).
/// Reihenfolge = Reihenfolge der ids und der Ops (Wände vor Öffnungen).
const LISTS: [(&str, &str, &str, &str); 9] = [
("walls", "walls", "W", "floorId"),
("drawings", "drawings2d", "dr2d", "levelId"),
("ceilings", "ceilings", "C", "floorId"),
("roofs", "roofs", "RF", "floorId"),
("openings", "openings", "O", ""),
("stairs", "stairs", "ST", "floorId"),
("rooms", "rooms", "RM", "floorId"),
("extrudedSolids", "extrudedSolids", "extrude", "levelId"),
("columns", "columns", "column", "floorId"),
];
/// Ops des Einfügens: je Liste ein `add` (leere Listen ohne Op).
pub fn paste_ops(clip: &Value, level_id: &str, stamp: &str) -> Vec<Op> {
let mut ids = IdGen::new(stamp);
let mut wall_ids: HashMap<String, String> = HashMap::new();
let level = Value::String(level_id.to_owned());
let mut ops = Vec::new();
for (key, collection, prefix, level_field) in LISTS {
let mut items = Vec::new();
for e in arr(field(clip, key)) {
if level_field.is_empty() {
// Öffnung: nur mit mitkopierter Wirtswand, umgehängt.
let host = field(e, "hostWallId").and_then(Value::as_str).and_then(|h| wall_ids.get(h));
let Some(host) = host else { continue };
let host = Value::String(host.clone());
items.push(with_all(e, vec![("id", Value::String(ids.next(prefix))), ("hostWallId", host)]));
continue;
}
let id = ids.next(prefix);
if key == "walls" {
if let Some(old) = id_of(e) {
wall_ids.insert(old.to_owned(), id.clone());
}
}
items.push(with_all(e, vec![("id", Value::String(id)), (level_field, level.clone())]));
}
if !items.is_empty() {
ops.push(Op::Add { collection: collection.into(), items, at: None });
}
}
ops
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn klone_mit_neuen_ids_auf_dem_aktiven_geschoss_oeffnung_umgehaengt() {
let clip = json!({
"walls": [
{"id": "w1", "type": "wall", "floorId": "eg", "start": {"x": 0, "y": 0}, "end": {"x": 5, "y": 0}, "extra": 1},
{"id": "w2", "type": "wall", "start": {"x": 0, "y": 1}, "end": {"x": 5, "y": 1}}
],
"drawings": [{"id": "d1", "levelId": "eg", "geom": {"shape": "line"}}],
"openings": [
{"id": "o1", "hostWallId": "w1", "position": 1.5},
{"id": "o2", "hostWallId": "w9"}
],
"columns": [{"id": "c1", "floorId": "eg"}],
"rooms": []
});
let ops: Vec<Value> = paste_ops(&clip, "og", "s").iter().map(Op::to_json).collect();
assert_eq!(ops.len(), 4);
assert_eq!(ops[0]["collection"], "walls");
let walls = ops[0]["items"].as_array().unwrap();
assert_eq!(walls[0], json!({"id": "W-s-1", "type": "wall", "floorId": "og", "start": {"x": 0, "y": 0}, "end": {"x": 5, "y": 0}, "extra": 1}));
// Fehlendes Geschoss-Feld kommt ans Ende (wie `{...w, id, floorId}`).
assert_eq!(walls[1].as_object().unwrap().keys().collect::<Vec<_>>(), ["id", "type", "start", "end", "floorId"]);
assert_eq!(ops[1]["collection"], "drawings2d");
assert_eq!(ops[1]["items"][0]["id"], "dr2d-s-3");
assert_eq!(ops[1]["items"][0]["levelId"], "og");
// Öffnung o1 an die neue Wand, o2 (Wirtswand nicht kopiert) fällt weg.
assert_eq!(ops[2]["collection"], "openings");
assert_eq!(ops[2]["items"], json!([{"id": "O-s-4", "hostWallId": "W-s-1", "position": 1.5}]));
assert_eq!(ops[3]["collection"], "columns");
assert_eq!(ops[3]["items"][0], json!({"id": "column-s-5", "floorId": "og"}));
}
#[test]
fn leere_oder_kaputte_zwischenablage_ergibt_nichts() {
assert!(paste_ops(&json!({}), "og", "s").is_empty());
assert!(paste_ops(&json!(null), "og", "s").is_empty());
assert!(paste_ops(&json!({"walls": 3, "openings": [{"id": "o"}]}), "og", "s").is_empty());
}
}
+389
View File
@@ -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<P>,
/// `closed` roh (fehlend = `None`; Rechteck `true`, Linie `false`).
closed: Option<Value>,
/// Bogen-Werte roh (nur Polylinie mit `allow_bulge`).
bulge: Option<Vec<Value>>,
}
impl Form {
fn is_closed(&self) -> bool {
truthy(self.closed.as_ref())
}
fn bulge_nums(&self) -> Vec<f64> {
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<Form> {
let pts_of = |k: &str| arr(field(g, k)).iter().map(p_of).collect::<Vec<P>>();
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::<Vec<_>>()));
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<Value>, 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<Vec<P>> {
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<P>], ids: &mut IdGen) -> Option<Vec<Value>> {
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<String, Value>, ids: &[String], stamp: &str) -> Vec<Op> {
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<Value>, Option<usize>)> = 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<Vec<P>> = 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<String> = Vec::new();
let mut inserts: Vec<(usize, Vec<Value>)> = 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<usize> {
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<P> = 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<String, Value>, id: &str, at: P) -> Vec<Op> {
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<String, Value> {
v.as_object().unwrap().clone()
}
fn poly(id: &str, pts: &[(f64, f64)], closed: bool) -> Value {
let pts: Vec<Value> = 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<Value> {
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());
}
}
+3
View File
@@ -26,6 +26,9 @@ pub fn ops(root: &Map<String, Value>, text: &str) -> Result<Vec<Op>, String> {
"align" => crate::cmd_transform::align_ops(root, &ids("ids"), &s("mode")),
"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}")),
})
}
+10 -2
View File
@@ -56,7 +56,11 @@ impl Revs {
}
fn reset(&mut self) {
self.epoch = self.next();
// Epoche über alle Dokumente eindeutig: Caches ausserhalb eines Dokuments (Fang, `snap_model.rs`)
// erkennen so auch ein neu geöffnetes Dokument unter derselben Nummer.
static EPOCHS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
self.next();
self.epoch = EPOCHS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
self.field.clear();
self.items.clear();
}
@@ -251,7 +255,11 @@ impl<'a> Lookup<'a> {
impl Document {
pub fn from_json(text: &str) -> Result<Document, String> {
match serde_json::from_str::<Value>(text) {
Ok(Value::Object(root)) => Ok(Document { root, ..Default::default() }),
Ok(Value::Object(root)) => {
let mut d = Document { root, ..Default::default() };
d.revs.reset();
Ok(d)
}
Ok(_) => Err("Projekt ist kein JSON-Objekt".into()),
Err(e) => Err(e.to_string()),
}
+3
View File
@@ -95,6 +95,9 @@ pub mod polyline_vertex;
pub mod import_drawing;
pub mod import_context;
pub mod import_ifc;
pub mod cmd_paste;
pub mod cmd_split;
pub mod snap_model;
#[cfg(feature = "web")]
mod web;
+27 -24
View File
@@ -1,9 +1,8 @@
//! Objektfang auf Strecken ([K3d], früher die Schleifen in `src/tools/snapping.ts`): Lotfusspunkt
//! vom letzten Punkt, Endpunkte, Mittelpunkte, Schnittpunkte (unendliche Geraden) und Punkt auf
//! der Kante, dazu die nächste Strecke für die Verweil-Erkennung ("divide"). TS sammelt die
//! Strecken (Wandachsen, Schichtgrenzen, Umrisse, 2D-Zeichnung) einmal je Projekt/Geschoss und
//! legt sie hier ab; je Mausbewegung kommen nur Cursor, Toleranz und die wenigen Zusatzstrecken
//! (Entwurf, Blatt-Geometrie) dazu.
//! der Kante, dazu die nächste Strecke für die Verweil-Erkennung ("divide"). Die Strecken eines
//! Geschosses sammelt `snap_model.rs` einmal je Dokument-Stand aus dem Modell; je Mausbewegung
//! kommen nur Cursor, Toleranz und die wenigen Zusatzstrecken (Entwurf, Blatt-Geometrie) dazu.
//!
//! Bewertung wie in TS: Kandidat nur bis `tol_m` Abstand, Punktzahl `distPx − Priorität`, der
//! erste mit der kleinsten Punktzahl gewinnt. Ergebnis in zwei Blöcken (die Reihenfolge in TS ist
@@ -25,6 +24,9 @@ pub const K_ENDPOINT: f64 = 1.0;
pub const K_MIDPOINT: f64 = 2.0;
pub const K_INTERSECTION: f64 = 3.0;
pub const K_ON_EDGE: f64 = 4.0;
pub const K_CENTER: f64 = 5.0;
pub const K_QUADRANT: f64 = 6.0;
pub const K_TANGENT: f64 = 7.0;
/// Prioritäts-Bonus in Pixeln (wie `PRIORITY` in snapping.ts).
fn priority(kind: f64) -> f64 {
@@ -33,6 +35,8 @@ fn priority(kind: f64) -> f64 {
1 => 7.0,
2 => 3.0,
3 => 5.0,
5 | 6 => 3.0,
7 => 1.0,
_ => 0.0,
}
}
@@ -53,21 +57,22 @@ pub struct Cand {
pub score: f64,
}
struct Best {
/// Bester Kandidat einer Folge (`consider` in snapping.ts): der erste mit der kleinsten Punktzahl.
pub struct Best {
raw: (f64, f64),
tol_m: f64,
px_per_m: f64,
best: Option<Cand>,
pub best: Option<Cand>,
best_score: f64,
}
impl Best {
fn new(raw: (f64, f64), tol_m: f64, px_per_m: f64) -> Best {
pub fn new(raw: (f64, f64), tol_m: f64, px_per_m: f64) -> Best {
Best { raw, tol_m, px_per_m, best: None, best_score: f64::INFINITY }
}
#[inline]
fn consider(&mut self, x: f64, y: f64, kind: f64) {
pub fn consider(&mut self, x: f64, y: f64, kind: f64) {
let dx = x - self.raw.0;
let dy = y - self.raw.1;
// Schnell verwerfen (hypot ≥ max(|dx|, |dy|)); NaN fällt durch wie in TS.
@@ -151,7 +156,7 @@ impl SnapSet {
/// Strecken, die näher als `r` an `(x, y)` liegen können (aufsteigend). Alle Strecken-Fänge
/// (Endpunkt, Mitte, Lot, Kante, Verweilen) liegen auf der Strecke und höchstens `tol_m` vom
/// Cursor — die übrigen tragen nichts bei.
fn near(&self, x: f64, y: f64, r: f64) -> Vec<u32> {
pub fn near(&self, x: f64, y: f64, r: f64) -> Vec<u32> {
if x.is_finite() && y.is_finite() && r.is_finite() && r >= 0.0 {
self.ix.candidates(x, y, r * (1.0 + 1e-6) + pad(&[x, y]))
} else {
@@ -162,10 +167,10 @@ impl SnapSet {
/// Eingabe einer Fang-Abfrage.
pub struct SnapQuery<'a> {
/// Strecken in Fang-Reihenfolge: abgelegte, dann Zusatz.
pub base: &'a SnapSet,
/// Strecken in Fang-Reihenfolge: abgelegte Teile (der Reihe nach), dann Zusatz.
pub bases: &'a [&'a SnapSet],
pub extra: &'a [[f64; 4]],
/// Strecken für Schnittpunkte; `None` = dieselben wie `base` + `extra`.
/// Strecken für Schnittpunkte; `None` = dieselben wie `bases` + `extra`.
pub int_segs: Option<&'a [[f64; 4]]>,
pub raw: (f64, f64),
pub tol_m: f64,
@@ -176,23 +181,21 @@ pub struct SnapQuery<'a> {
/// Ergebnis: nächste Strecke (Verweilen), Block A (Lot, Endpunkte), Block B (Mitte, Schnitt, Kante).
pub struct SnapOut {
pub dwell: Option<usize>,
pub dwell: Option<[f64; 4]>,
pub a: Option<Cand>,
pub b: Option<Cand>,
}
pub fn snap_segments(q: &SnapQuery) -> SnapOut {
let (rx, ry) = q.raw;
let near_base = q.base.near(rx, ry, q.tol_m);
let nb = q.base.segs.len();
// Strecken in Fang-Reihenfolge (Index im Ganzen, Strecke): nahe abgelegte, dann Zusatz.
let segs = || {
near_base.iter().map(|&k| (k as usize, &q.base.segs[k as usize])).chain(q.extra.iter().enumerate().map(move |(k, s)| (nb + k, s)))
};
let near_base: Vec<&[f64; 4]> =
q.bases.iter().flat_map(|b| b.near(rx, ry, q.tol_m).into_iter().map(move |k| &b.segs[k as usize])).collect();
// Strecken in Fang-Reihenfolge: nahe abgelegte, dann Zusatz.
let segs = || near_base.iter().copied().chain(q.extra.iter()).map(|s| ((), s));
// Nächste Strecke für die Verweil-Erkennung (`nearestSegment` in snapping.ts).
let mut dwell = None;
let mut best_d = q.tol_m;
for (i, s) in segs() {
for (_, s) in segs() {
let (fx, fy) = perp_foot(rx, ry, s);
let (dx, dy) = (fx - rx, fy - ry);
if dx.abs() >= best_d || dy.abs() >= best_d {
@@ -201,7 +204,7 @@ pub fn snap_segments(q: &SnapQuery) -> SnapOut {
let d = hypot(&[dx, dy]);
if d < best_d {
best_d = d;
dwell = Some(i);
dwell = Some(*s);
}
}
let mut a = Best::new(q.raw, q.tol_m, q.px_per_m);
@@ -228,7 +231,7 @@ pub fn snap_segments(q: &SnapQuery) -> SnapOut {
if q.flags & F_INTERSECTION != 0 {
let near: Vec<&[f64; 4]> = match q.int_segs {
Some(l) => l.iter().filter(|s| line_near(s, q.raw, q.tol_m)).collect(),
None => q.base.segs.iter().chain(q.extra.iter()).filter(|s| line_near(s, q.raw, q.tol_m)).collect(),
None => q.bases.iter().flat_map(|b| b.segs.iter()).chain(q.extra.iter()).filter(|s| line_near(s, q.raw, q.tol_m)).collect(),
};
for i in 0..near.len() {
for j in i + 1..near.len() {
@@ -260,9 +263,9 @@ mod tests {
fn endpunkt_vor_kante_schnitt_nur_nahe_geraden() {
let segs = segs_from(&[0.0, 0.0, 10.0, 0.0, 5.0, -5.0, 5.0, 5.0, 100.0, 50.0, 200.0, 50.0]);
let base = SnapSet::new(segs[..1].to_vec());
let q = SnapQuery { base: &base, extra: &segs[1..], int_segs: None, raw: (5.05, 0.02), tol_m: 0.2, px_per_m: 100.0, flags: 31, last: None };
let q = SnapQuery { bases: &[&base], extra: &segs[1..], int_segs: None, raw: (5.05, 0.02), tol_m: 0.2, px_per_m: 100.0, flags: 31, last: None };
let o = snap_segments(&q);
assert_eq!(o.dwell, Some(0));
assert_eq!(o.dwell, Some(segs[0]));
assert_eq!(o.a, None);
let b = o.b.unwrap();
assert_eq!((b.x, b.y, b.kind), (5.0, 0.0, K_INTERSECTION));
+670
View File
@@ -0,0 +1,670 @@
//! Fang-Kandidaten aus dem Modell ([K4] S3, vorher `baseSegments`/`collectCircles`/`roomAnchors`/
//! `ellipseCenters` in `src/tools/snapping.ts`) und die Fang-Abfrage je Mausbewegung.
//!
//! **Sammeln** (einmal je Dokument-Stand, Geschoss und sichtbaren Ebenen, [`SnapCache::hold`]): zwei
//! Teile, damit eine Änderung an Wänden nicht die (vielen) Zeichnungen neu sammelt und umgekehrt:
//! - Modell: Strecken der Wandachsen und Schichtgrenzen, Raum-, Decken- (mit Aussparungen), Dach-,
//! Treppen- und Stützen-Umrisse (Reihenfolge wie bisher), Kreise der runden Stützen und der
//! Wendeltreppen-Bögen, Raum-Stempel-Anker (fixer Anker, sonst Flächenschwerpunkt).
//! - Zeichnungen: Strecken (Linie, Konstruktionslinie/Strahl weit verlängert, Polylinie (Sehnen),
//! Rechteck, Bezier/Spline tesselliert), Kreise/Bögen, Ellipsen-Mittelpunkte.
//!
//! Schlüssel: Epoche + Feld-Stände des Dokuments (`Revs`), Geschoss, Ebenen-Codes. Ein unverändertes
//! Dokument liefert dieselbe Nummer; TS fragt je Mausbewegung nur noch mit ihr.
//!
//! **Abfrage** ([`query`]): Strecken-Fang (`snap.rs`) über beide Teile plus Entwurf und Blatt-
//! Geometrie; ab mehr als 2000 Zeichnungen im Projekt (Nahmodus, wie bisher) nur die Strecken bis
//! `6 · tol` vom Cursor, nach Abstand sortiert, Schnittpunkte unter den 64 nächsten. Dazu die
//! Blöcke Raum-Anker (Endpunkt) und Kreise (Mittelpunkt, Quadranten, Bogen-Endpunkte, Tangente vom
//! letzten Punkt) samt Ellipsen-Mittelpunkten. Bewertung wie in TS (`consider`); TS führt die Blöcke
//! in seiner Reihenfolge mit Teilpunkten, Parallele und Entwurfspunkten zusammen.
use crate::jsmath::hypot2;
use crate::jsnum;
use crate::model::{ColumnProfile, Drawing2DGeom, Project, SplineMode, Vec2, WallReferenceLine};
use crate::snap::{snap_segments, Best, Cand, SnapQuery, SnapSet, F_ENDPOINT, K_CENTER, K_ENDPOINT, K_QUADRANT, K_TANGENT};
use std::collections::HashSet;
use std::rc::Rc;
/// Mittelpunkt/Quadranten (Kreise, Ellipsen).
pub const F_CENTER: u32 = 32;
/// Tangente vom letzten Punkt an Kreise/Bögen.
pub const F_TANGENT: u32 = 64;
/// Strecken-Fang überhaupt (eine der Strecken-Arten oder Parallele aktiv: Verweilen braucht ihn).
pub const F_SEGS: u32 = 128;
/// Ab so vielen Zeichnungen im Projekt: nur Strecken in Cursornähe (`LARGE_DRAWINGS`).
const LARGE_DRAWINGS: usize = 2000;
/// Verlängerung von Konstruktionslinie/Strahl (Meter).
const XLINE_EXT: f64 = 1000.0;
type Seg = [f64; 4];
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Circle {
pub cx: f64,
pub cy: f64,
pub r: f64,
/// Bogen `(a0, a1)`; `None` = Vollkreis.
pub arc: Option<(f64, f64)>,
}
/// Gesammelte Kandidaten eines Teils.
#[derive(Default)]
pub struct SnapPart {
pub segs: SnapSet,
pub circles: Vec<Circle>,
pub anchors: Vec<(f64, f64)>,
pub ellipses: Vec<(f64, f64)>,
}
fn seg(a: &Vec2, b: &Vec2) -> Seg {
[a.x, a.y, b.x, b.y]
}
/// Kanten eines geschlossenen Polygons (`closedPolySegs`).
fn closed_poly(pts: &[Vec2], out: &mut Vec<Seg>) {
for w in pts.windows(2) {
out.push(seg(&w[0], &w[1]));
}
if pts.len() > 2 {
out.push(seg(&pts[pts.len() - 1], &pts[0]));
}
}
fn chain(pts: &[Vec2], out: &mut Vec<Seg>) {
for w in pts.windows(2) {
out.push(seg(&w[0], &w[1]));
}
}
fn flat(pts: &[Vec2]) -> Vec<f64> {
pts.iter().flat_map(|p| [p.x, p.y]).collect()
}
fn pts_of(f: &[f64]) -> Vec<Vec2> {
f.chunks_exact(2).map(|c| Vec2 { x: c[0], y: c[1] }).collect()
}
/// Schichtgrenzen einer Wand (`wallLayerBoundarySegments`): äussere Fläche, jede Fuge, innere Fläche,
/// je parallel zur Achse um den kumulierten Versatz entlang der linken Normalen.
pub fn wall_layer_segments(p: &Project, w: &crate::model::Wall, out: &mut Vec<Seg>) {
let Some(wt) = p.wall_type(w) else { return };
let total = wt.layers.iter().fold(0.0, |s, l| s + l.thickness);
let half = total / 2.0;
let ref_off = match (w.reference_offset, &w.reference_line) {
(Some(v), _) => jsnum::max(-half, jsnum::min(half, v)),
(None, Some(WallReferenceLine::Left)) => half,
(None, Some(WallReferenceLine::Right)) => -half,
_ => 0.0,
};
let (dx, dy) = (w.end.x - w.start.x, w.end.y - w.start.y);
let l = hypot2(dx, dy);
let l = if l == 0.0 || l.is_nan() { 1.0 } else { l };
let (ux, uy) = (dx / l, dy / l);
let (nx, ny) = (-uy, ux);
let boundary = |o: f64| [w.start.x + nx * o, w.start.y + ny * o, w.end.x + nx * o, w.end.y + ny * o];
let mut off = ref_off - total / 2.0;
out.push(boundary(off));
for layer in &wt.layers {
off += layer.thickness;
out.push(boundary(off));
}
}
/// Modell-Teil eines Geschosses (alles ausser den 2D-Zeichnungen).
pub fn collect_model(p: &Project, level: &str, codes: &HashSet<String>) -> SnapPart {
let vis = |floor: &str, code: &str| floor == level && codes.contains(code);
let mut segs: Vec<Seg> = Vec::new();
for w in &p.walls {
if vis(&w.floor_id, &w.category_code) {
segs.push(seg(&w.start, &w.end));
wall_layer_segments(p, w, &mut segs);
}
}
let mut anchors = Vec::new();
for r in p.rooms.as_deref().unwrap_or(&[]) {
if vis(&r.floor_id, &r.category_code) {
closed_poly(&r.boundary, &mut segs);
}
}
for c in p.ceilings.as_deref().unwrap_or(&[]) {
if vis(&c.floor_id, &c.category_code) {
closed_poly(&c.outline, &mut segs);
for hole in c.openings.as_deref().unwrap_or(&[]) {
closed_poly(hole, &mut segs);
}
}
}
for r in p.roofs.as_deref().unwrap_or(&[]) {
if vis(&r.floor_id, &r.category_code) {
closed_poly(&r.outline, &mut segs);
}
}
let mut stair_arcs = Vec::new();
for s in p.stairs.as_deref().unwrap_or(&[]) {
if !vis(&s.floor_id, &s.category_code) {
continue;
}
// `stairOutline`: `[0, n, Punkte…]` Polygon, `[1, 4 Punkte, 2 × (cx, cy, r, a0, a1)]` Wendel.
let f = crate::stair::outline(&s.encode());
match f.first() {
Some(&k) if k == 0.0 && f.len() >= 2 => {
let n = f[1] as usize;
closed_poly(&pts_of(&f[2..(2 + 2 * n).min(f.len())]), &mut segs);
}
Some(_) if f.len() >= 19 => {
segs.push([f[1], f[2], f[3], f[4]]);
segs.push([f[5], f[6], f[7], f[8]]);
for k in 0..2 {
let j = 9 + 5 * k;
stair_arcs.push(Circle { cx: f[j], cy: f[j + 1], r: f[j + 2], arc: Some((f[j + 3], f[j + 4])) });
}
}
_ => {}
}
}
let mut circles = Vec::new();
for col in p.columns.as_deref().unwrap_or(&[]) {
if !vis(&col.floor_id, &col.category_code) {
continue;
}
match col.profile {
ColumnProfile::Rect { .. } => closed_poly(&crate::model3d::column_footprint(col), &mut segs),
ColumnProfile::Round { radius } => circles.push(Circle { cx: col.position.x, cy: col.position.y, r: radius, arc: None }),
}
}
circles.extend(stair_arcs);
for r in p.rooms.as_deref().unwrap_or(&[]) {
if vis(&r.floor_id, &r.category_code) && r.boundary.len() >= 3 {
anchors.push(match &r.stamp_anchor {
Some(a) => (a.x, a.y),
None => {
let c = crate::room_area::evaluate(&r.boundary.iter().map(|p| [p.x, p.y]).collect::<Vec<_>>(), 0.0).centroid;
(c[0], c[1])
}
});
}
}
SnapPart { segs: SnapSet::new(segs), circles, anchors, ellipses: Vec::new() }
}
/// Strecken einer Zeichnung (`drawingSegs`).
fn drawing_segs(g: &Drawing2DGeom, out: &mut Vec<Seg>) {
match g {
Drawing2DGeom::Line { a, b } => out.push(seg(a, b)),
Drawing2DGeom::Xline { a, b } | Drawing2DGeom::Ray { a, b } => {
let (dx, dy) = (b.x - a.x, b.y - a.y);
let len = hypot2(dx, dy);
if len > 1e-6 {
let (ux, uy) = (dx / len, dy / len);
let end = [b.x + ux * XLINE_EXT, b.y + uy * XLINE_EXT];
if matches!(g, Drawing2DGeom::Xline { .. }) {
out.push([a.x - ux * XLINE_EXT, a.y - uy * XLINE_EXT, end[0], end[1]]);
} else {
out.push([a.x, a.y, end[0], end[1]]);
}
}
}
Drawing2DGeom::Polyline { pts, closed, .. } => {
chain(pts, out);
if *closed && pts.len() > 2 {
out.push(seg(&pts[pts.len() - 1], &pts[0]));
}
}
Drawing2DGeom::Rect { min, max } => {
let (c2, c4) = (Vec2 { x: max.x, y: min.y }, Vec2 { x: min.x, y: max.y });
out.extend([seg(min, &c2), seg(&c2, max), seg(max, &c4), seg(&c4, min)]);
}
Drawing2DGeom::Bezier { pts } => {
if pts.len() < 4 {
chain(pts, out);
} else {
chain(&pts_of(&crate::curves::bezier_chain(&flat(pts), 24.0)), out);
}
}
Drawing2DGeom::Spline { pts, closed, mode } => {
let closed = *closed && pts.len() > 2;
let s = if pts.len() < 3 {
pts.clone()
} else if *mode == Some(SplineMode::Control) {
pts_of(&crate::curves::uniform_bspline(&flat(pts), closed, 16.0))
} else {
pts_of(&crate::curves::catmull_rom(&flat(pts), closed, 16.0))
};
chain(&s, out);
if closed && !s.is_empty() {
out.push(seg(&s[s.len() - 1], &s[0]));
}
}
_ => {}
}
}
/// Zeichnungs-Teil eines Geschosses.
pub fn collect_drawings(p: &Project, level: &str, codes: &HashSet<String>) -> SnapPart {
let mut segs: Vec<Seg> = Vec::new();
let mut circles = Vec::new();
let mut ellipses = Vec::new();
for d in &p.drawings2d {
if d.level_id != level || !codes.contains(&d.category_code) {
continue;
}
match &d.geom {
Drawing2DGeom::Circle { center, r } => circles.push(Circle { cx: center.x, cy: center.y, r: *r, arc: None }),
Drawing2DGeom::Arc { center, r, a0, a1 } => circles.push(Circle { cx: center.x, cy: center.y, r: *r, arc: Some((*a0, *a1)) }),
Drawing2DGeom::Ellipse { center, .. } => ellipses.push((center.x, center.y)),
g => drawing_segs(g, &mut segs),
}
}
SnapPart { segs: SnapSet::new(segs), circles, anchors: Vec::new(), ellipses }
}
/// Die Kandidaten eines Geschosses: Modell, Zeichnungen, Nahmodus.
#[derive(Clone)]
pub struct LevelSnap {
pub model: Rc<SnapPart>,
pub drawings: Rc<SnapPart>,
pub near_mode: bool,
}
/// Eingabe einer Abfrage je Mausbewegung.
pub struct ModelQuery<'a> {
/// Entwurfs-Strecken (Polylinie/Wand im Bau).
pub draft: &'a [Seg],
/// Blatt-Geometrie in Cursornähe (schon vorausgewählt, nächste zuerst).
pub sheet: &'a [Seg],
pub raw: (f64, f64),
pub tol_m: f64,
pub px_per_m: f64,
pub flags: u32,
pub last: Option<(f64, f64)>,
}
/// Ergebnis: nächste Strecke (Verweilen) und die Blöcke in TS-Reihenfolge.
#[derive(Debug, Default, PartialEq)]
pub struct ModelOut {
pub dwell: Option<Seg>,
/// Lot vom letzten Punkt, Strecken-Endpunkte.
pub a: Option<Cand>,
/// Raum-Stempel-Anker (Endpunkt).
pub anchors: Option<Cand>,
/// Mitte, Schnitt, Kante.
pub b: Option<Cand>,
/// Kreise (Mittelpunkt, Quadranten, Bogen-Endpunkte, Tangente), Ellipsen-Mittelpunkte.
pub c: Option<Cand>,
}
/// Abstand Punkt–Strecke (`pointSegDist` in `geometry/drawingIndex.ts`).
fn point_seg_dist(p: (f64, f64), s: &Seg) -> f64 {
let (dx, dy) = (s[2] - s[0], s[3] - s[1]);
let len2 = dx * dx + dy * dy;
let t = if len2 > 0.0 { ((p.0 - s[0]) * dx + (p.1 - s[1]) * dy) / len2 } else { 0.0 };
let t = jsnum::max(0.0, jsnum::min(1.0, t));
hypot2(p.0 - (s[0] + t * dx), p.1 - (s[1] + t * dy))
}
const TAU: f64 = std::f64::consts::PI * 2.0;
fn norm(x: f64) -> f64 {
((x % TAU) + TAU) % TAU
}
fn on_circle(c: &Circle, ang: f64) -> (f64, f64) {
(c.cx + c.r * jsnum::cos(ang), c.cy + c.r * jsnum::sin(ang))
}
fn in_arc(c: &Circle, ang: f64) -> bool {
let Some((a0, a1)) = c.arc else { return true };
let s = norm(a1 - a0);
// `norm(…) || TAU`: 0 und NaN → Vollkreis.
let sweep = if s == 0.0 || s.is_nan() { TAU } else { s };
norm(ang - a0) <= sweep + 1e-9
}
pub fn query(ls: &LevelSnap, q: &ModelQuery) -> ModelOut {
let mut out = ModelOut::default();
if q.flags & F_SEGS != 0 {
let o = if ls.near_mode {
let int_r = q.tol_m * 6.0;
let mut cand: Vec<(Seg, f64)> = Vec::new();
for part in [&ls.model, &ls.drawings] {
for k in part.segs.near(q.raw.0, q.raw.1, int_r) {
let s = part.segs.segs[k as usize];
let d = point_seg_dist(q.raw, &s);
if d <= int_r {
cand.push((s, d));
}
}
}
for s in q.draft {
let d = point_seg_dist(q.raw, s);
if d <= int_r {
cand.push((*s, d));
}
}
cand.sort_by(|x, y| x.1.total_cmp(&y.1));
let mut segs: Vec<Seg> = cand.iter().filter(|e| e.1 <= q.tol_m).map(|e| e.0).collect();
let mut ints: Vec<Seg> = cand.iter().take(64).map(|e| e.0).collect();
segs.extend_from_slice(q.sheet);
ints.extend_from_slice(q.sheet);
let sq = SnapQuery { bases: &[], extra: &segs, int_segs: Some(&ints), raw: q.raw, tol_m: q.tol_m, px_per_m: q.px_per_m, flags: q.flags, last: q.last };
snap_segments(&sq)
} else {
let extra: Vec<Seg> = q.draft.iter().chain(q.sheet.iter()).copied().collect();
let sq = SnapQuery {
bases: &[&ls.model.segs, &ls.drawings.segs],
extra: &extra,
int_segs: None,
raw: q.raw,
tol_m: q.tol_m,
px_per_m: q.px_per_m,
flags: q.flags,
last: q.last,
};
snap_segments(&sq)
};
out.dwell = o.dwell;
out.a = o.a;
out.b = o.b;
}
if q.flags & F_ENDPOINT != 0 {
let mut best = Best::new(q.raw, q.tol_m, q.px_per_m);
for &(x, y) in &ls.model.anchors {
best.consider(x, y, K_ENDPOINT);
}
out.anchors = best.best;
}
let (center, endpoint, tangent) = (q.flags & F_CENTER != 0, q.flags & F_ENDPOINT != 0, q.flags & F_TANGENT != 0);
if center || endpoint || tangent {
let mut best = Best::new(q.raw, q.tol_m, q.px_per_m);
for c in ls.drawings.circles.iter().chain(ls.model.circles.iter()) {
if center {
best.consider(c.cx, c.cy, K_CENTER);
for k in 0..4 {
let ang = k as f64 * (std::f64::consts::PI / 2.0);
if in_arc(c, ang) {
let (x, y) = on_circle(c, ang);
best.consider(x, y, K_QUADRANT);
}
}
}
if let (true, Some((a0, a1))) = (endpoint, c.arc) {
let (x, y) = on_circle(c, a0);
best.consider(x, y, K_ENDPOINT);
let (x, y) = on_circle(c, a1);
best.consider(x, y, K_ENDPOINT);
}
if let (true, Some((lx, ly))) = (tangent, q.last) {
let (dx, dy) = (lx - c.cx, ly - c.cy);
let d = hypot2(dx, dy);
if d > c.r + 1e-9 {
let theta = jsnum::atan2(dy, dx);
let at_c = jsnum::acos(jsnum::min(1.0, c.r / d));
for sign in [1.0, -1.0] {
let ang = theta + sign * at_c;
if in_arc(c, ang) {
let (x, y) = on_circle(c, ang);
best.consider(x, y, K_TANGENT);
}
}
}
}
}
if center {
for &(x, y) in &ls.drawings.ellipses {
best.consider(x, y, K_CENTER);
}
}
out.c = best.best;
}
out
}
/// Schlüssel eines gesammelten Teils.
#[derive(Clone, PartialEq, Debug)]
struct PartKey {
doc: u32,
epoch: u64,
revs: Vec<u64>,
level: String,
codes: String,
}
/// Felder, aus denen der Modell-Teil sammelt (ändert sich eines, wird neu gesammelt).
const MODEL_FIELDS: [&str; 7] = ["walls", "wallTypes", "rooms", "ceilings", "roofs", "stairs", "columns"];
const DRAWING_FIELDS: [&str; 1] = ["drawings2d"];
/// So viele Teile je Art und abgelegte Geschosse bleiben (älteste fallen weg).
const KEEP: usize = 6;
/// Gesammelte Teile und abgelegte Geschosse (Nummer ≥ 1) über die Aufrufe hinweg.
#[derive(Default)]
pub struct SnapCache {
model: Vec<(PartKey, Rc<SnapPart>)>,
drawings: Vec<(PartKey, Rc<SnapPart>)>,
held: Vec<(u32, LevelSnap)>,
next: u32,
}
fn cached(list: &mut Vec<(PartKey, Rc<SnapPart>)>, key: PartKey, build: impl FnOnce() -> SnapPart) -> Rc<SnapPart> {
if let Some(i) = list.iter().position(|e| e.0 == key) {
let e = list.remove(i);
let part = e.1.clone();
list.push(e);
return part;
}
let part = Rc::new(build());
list.push((key, part.clone()));
if list.len() > KEEP {
list.remove(0);
}
part
}
impl SnapCache {
/// Kandidaten des Geschosses `level` (sichtbare Ebenen `codes`) im Dokument `doc` (Nummer `doc_id`)
/// sammeln bzw. wiederverwenden; Nummer für [`SnapCache::get`]. Dieselbe Nummer, solange sich die
/// betroffenen Felder nicht ändern.
pub fn hold(&mut self, doc_id: u32, doc: &mut crate::document::Document, level: &str, codes: &[String]) -> u32 {
let mut sorted: Vec<&str> = codes.iter().map(String::as_str).collect();
sorted.sort_unstable();
sorted.dedup();
let codes_key = sorted.join("\n");
let set: HashSet<String> = sorted.iter().map(|s| (*s).to_owned()).collect();
let near_mode = doc.root().get("drawings2d").and_then(|v| v.as_array()).map_or(0, Vec::len) > LARGE_DRAWINGS;
let key = |fields: &[&str], revs: &crate::document::Revs| PartKey {
doc: doc_id,
epoch: revs.epoch(),
revs: fields.iter().map(|f| revs.field(f)).collect(),
level: level.to_owned(),
codes: codes_key.clone(),
};
let (mk, dk) = (key(&MODEL_FIELDS, doc.revs()), key(&DRAWING_FIELDS, doc.revs()));
let model = cached(&mut self.model, mk, || doc.project().map(|p| collect_model(p, level, &set)).unwrap_or_default());
let drawings = cached(&mut self.drawings, dk, || doc.project().map(|p| collect_drawings(p, level, &set)).unwrap_or_default());
if let Some(e) = self.held.iter().find(|e| Rc::ptr_eq(&e.1.model, &model) && Rc::ptr_eq(&e.1.drawings, &drawings) && e.1.near_mode == near_mode) {
return e.0;
}
self.next = self.next.wrapping_add(1).max(1);
self.held.push((self.next, LevelSnap { model, drawings, near_mode }));
if self.held.len() > KEEP {
self.held.remove(0);
}
self.next
}
/// Abgelegtes Geschoss (`None` = Nummer unbekannt oder verdrängt).
pub fn get(&self, id: u32) -> Option<&LevelSnap> {
self.held.iter().find(|e| e.0 == id).map(|e| &e.1)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::document::Document;
use crate::snap::{F_INTERSECTION, F_MIDPOINT, F_ON_EDGE, F_PERPENDICULAR, K_INTERSECTION};
use serde_json::json;
fn doc(v: serde_json::Value) -> Document {
Document::from_json(&v.to_string()).unwrap()
}
fn base() -> serde_json::Value {
json!({
"id": "p", "name": "P", "lineStyles": [], "hatches": [], "components": [],
"wallTypes": [{"id": "aw", "name": "AW", "layers": [{"componentId": "c", "thickness": 0.1}, {"componentId": "c", "thickness": 0.15}, {"componentId": "c", "thickness": 0.2}]}],
"drawingLevels": [{"id": "eg", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 2.6, "cutHeight": 1.0, "baseElevation": 0}],
"layers": [{"code": "20", "name": "W", "color": "#000", "lw": 0.5, "visible": true, "locked": false}],
"walls": [], "openings": [], "ceilings": [], "stairs": [], "rooms": [], "drawings2d": [], "context": []
})
}
fn wall(r: Option<&str>) -> serde_json::Value {
let mut w = json!({"id": "w", "type": "wall", "floorId": "eg", "categoryCode": "20", "start": {"x": 0, "y": 0}, "end": {"x": 10, "y": 0}, "wallTypeId": "aw", "height": 2.6});
if let Some(r) = r {
w["referenceLine"] = json!(r);
}
w
}
fn codes() -> Vec<String> {
vec!["20".into()]
}
#[test]
fn schichtgrenzen_der_wand_wie_im_grundriss() {
// Gesamt 0.45; Mitte: −0.225, −0.125, +0.025, +0.225; links: +0, +0.1, +0.25, +0.45.
for (r, offs) in [(None, [-0.225, -0.125, 0.025, 0.225]), (Some("left"), [0.0, 0.1, 0.25, 0.45]), (Some("right"), [-0.45, -0.35, -0.2, 0.0])] {
let mut v = base();
v["walls"] = json!([wall(r)]);
let mut d = doc(v);
let p = d.project().unwrap();
let mut segs = Vec::new();
wall_layer_segments(p, &p.walls[0], &mut segs);
assert_eq!(segs.len(), 4);
for (s, o) in segs.iter().zip(offs) {
assert!((s[1] - o).abs() < 1e-12 && (s[3] - o).abs() < 1e-12, "{r:?}: {s:?} ≠ {o}");
assert_eq!((s[0], s[2]), (0.0, 10.0));
}
}
// Freier Fugen-Versatz übersteuert die Referenzlinie, auf ±T/2 geklemmt.
for (off, first) in [(0.15, 0.15 - 0.225), (5.0, 0.0), (-5.0, -0.45)] {
let mut v = base();
v["walls"] = json!([wall(Some("left"))]);
v["walls"][0]["referenceOffset"] = json!(off);
let mut d = doc(v);
let p = d.project().unwrap();
let mut segs = Vec::new();
wall_layer_segments(p, &p.walls[0], &mut segs);
assert!((segs[0][1] - first).abs() < 1e-12, "{off}: {segs:?}");
}
// Unbekannter Wandtyp: keine Schichtgrenzen (die Achse bleibt).
let mut v = base();
v["walls"] = json!([wall(None)]);
v["walls"][0]["wallTypeId"] = json!("fehlt");
let mut d = doc(v);
let ls = {
let mut c = SnapCache::default();
let id = c.hold(1, &mut d, "eg", &codes());
c.get(id).unwrap().clone()
};
assert_eq!(ls.model.segs.segs, vec![[0.0, 0.0, 10.0, 0.0]]);
}
fn q(raw: (f64, f64), flags: u32, last: Option<(f64, f64)>) -> ModelQuery<'static> {
ModelQuery { draft: &[], sheet: &[], raw, tol_m: 0.2, px_per_m: 100.0, flags, last }
}
#[test]
fn kreise_anker_zeichnungen_und_reihenfolge_der_bloecke() {
let mut v = base();
v["rooms"] = json!([{"id": "r", "floorId": "eg", "categoryCode": "20", "siaCategory": "HNF", "name": "R", "color": "#fff",
"boundary": [{"x": 0, "y": 0}, {"x": 4, "y": 0}, {"x": 4, "y": 2}, {"x": 0, "y": 2}]}]);
v["drawings2d"] = json!([
{"id": "c", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "circle", "center": {"x": 10, "y": 10}, "r": 1}},
{"id": "a", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "arc", "center": {"x": 20, "y": 0}, "r": 1, "a0": 0, "a1": 1.5707963267948966}},
{"id": "e", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "ellipse", "center": {"x": 30, "y": 0}, "rx": 2, "ry": 1, "rotation": 0}},
{"id": "x", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "xline", "a": {"x": 0, "y": 5}, "b": {"x": 1, "y": 5}}},
{"id": "h", "levelId": "og", "categoryCode": "20", "geom": {"shape": "line", "a": {"x": 0, "y": 7}, "b": {"x": 1, "y": 7}}}
]);
let mut d = doc(v);
let mut cache = SnapCache::default();
let id = cache.hold(1, &mut d, "eg", &codes());
let ls = cache.get(id).unwrap();
assert_eq!(ls.model.anchors, vec![(2.0, 1.0)]);
assert_eq!(ls.drawings.ellipses, vec![(30.0, 0.0)]);
assert_eq!(ls.drawings.circles.len(), 2);
// Konstruktionslinie weit verlängert; die Linie auf „og“ fehlt.
assert_eq!(ls.drawings.segs.segs, vec![[-1000.0, 5.0, 1001.0, 5.0]]);
let all = F_SEGS | F_ENDPOINT | F_MIDPOINT | F_INTERSECTION | F_ON_EDGE | F_PERPENDICULAR | F_CENTER | F_TANGENT;
assert_eq!(query(ls, &q((2.05, 1.0), all, None)).anchors.unwrap().kind, K_ENDPOINT);
assert_eq!(query(ls, &q((11.0, 10.05), all, None)).c.unwrap().kind, K_QUADRANT);
assert_eq!(query(ls, &q((10.0, 10.05), all, None)).c.unwrap().kind, K_CENTER);
// Bogen: Quadrant bei 0 und π/2 (im Bogen), Endpunkte schlagen Quadranten (Priorität).
assert_eq!(query(ls, &q((21.0, 0.05), all, None)).c.unwrap().kind, K_ENDPOINT);
assert_eq!(query(ls, &q((30.05, 0.0), all, None)).c.unwrap().kind, K_CENTER);
// Tangente vom letzten Punkt (10, 13) an den Kreis um (10, 10), r = 1.
let t = query(ls, &q((10.95, 10.35), F_TANGENT, Some((10.0, 13.0)))).c.unwrap();
assert_eq!(t.kind, K_TANGENT);
// Schnitt Raumkante y = 2 mit … keiner; Kante des Raums trifft.
let o = query(ls, &q((2.0, 2.05), all, None));
assert_eq!(o.dwell, Some([4.0, 2.0, 0.0, 2.0]));
assert!(o.b.is_some());
// Ohne Strecken-Fang: kein Verweilen, keine Blöcke A/B.
let o = query(ls, &q((2.0, 2.05), F_ENDPOINT, None));
assert!(o.dwell.is_none() && o.a.is_none() && o.b.is_none());
}
#[test]
fn gleiche_nummer_solange_nichts_relevantes_aendert_teile_einzeln_neu() {
let mut v = base();
v["walls"] = json!([wall(None)]);
v["drawings2d"] = json!([{"id": "l", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "line", "a": {"x": 0, "y": 5}, "b": {"x": 1, "y": 5}}}]);
let mut d = doc(v);
let mut cache = SnapCache::default();
let a = cache.hold(1, &mut d, "eg", &codes());
assert_eq!(cache.hold(1, &mut d, "eg", &codes()), a);
// Andere Ebenen-Codes → andere Sammlung; Reihenfolge der Codes egal.
let b = cache.hold(1, &mut d, "eg", &["20".into(), "99".into()]);
assert_ne!(a, b);
assert_eq!(cache.hold(1, &mut d, "eg", &["99".into(), "20".into()]), b);
// Unbeteiligtes Feld geändert: dieselbe Nummer.
d.apply(&crate::ops::ops_from_json(&json!([{"kind": "setField", "key": "parcelArea", "value": 5}])).unwrap()).unwrap();
assert_eq!(cache.hold(1, &mut d, "eg", &codes()), a);
// Wand geändert: Modell-Teil neu, Zeichnungs-Teil bleibt.
let draw_before = cache.get(a).unwrap().drawings.clone();
let mut w = wall(None);
w["end"] = json!({"x": 12, "y": 0});
d.apply(&[crate::ops::Op::Replace { collection: "walls".into(), entity: w }]).unwrap();
let c = cache.hold(1, &mut d, "eg", &codes());
assert_ne!(c, a);
let ls = cache.get(c).unwrap();
assert!(Rc::ptr_eq(&ls.drawings, &draw_before));
assert_eq!(ls.model.segs.segs[0], [0.0, 0.0, 12.0, 0.0]);
// Ein anderes Dokument unter derselben Nummer (neu geöffnet) sammelt neu.
let mut d2 = doc(base());
let e = cache.hold(1, &mut d2, "eg", &codes());
assert!(cache.get(e).unwrap().model.segs.segs.is_empty());
}
#[test]
fn nahmodus_nur_nahe_strecken_schnitt_unter_den_naechsten() {
let mut v = base();
let mut ds = Vec::new();
for i in 0..2001 {
let x = i as f64 * 3.0;
ds.push(json!({"id": format!("d{i}"), "levelId": "eg", "categoryCode": "20", "geom": {"shape": "line", "a": {"x": x, "y": -1}, "b": {"x": x, "y": 1}}}));
}
ds.push(json!({"id": "h", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "line", "a": {"x": -10, "y": 0}, "b": {"x": 7000, "y": 0}}}));
v["drawings2d"] = json!(ds);
let mut d = doc(v);
let mut cache = SnapCache::default();
let id = cache.hold(1, &mut d, "eg", &codes());
let ls = cache.get(id).unwrap();
assert!(ls.near_mode);
let o = query(ls, &q((3000.06, 0.04), F_SEGS | F_INTERSECTION | F_ON_EDGE, None));
let b = o.b.unwrap();
assert_eq!((b.x, b.y, b.kind), (3000.0, 0.0, K_INTERSECTION));
}
}
+2 -105
View File
@@ -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<f64> {
let v = *self.buf.get(self.i)?;
self.i += 1;
Some(v)
}
fn count(&mut self) -> Option<usize> {
count(self.f()?)
}
fn pts(&mut self, n: usize) -> Option<Vec<Vec2>> {
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<usize> {
if v.is_finite() && v >= 0.0 && v.fract() == 0.0 && v < 1e9 {
Some(v as usize)
} else {
None
}
}
fn pts(buf: &[f64]) -> Option<Vec<Vec2>> {
if buf.len() % 2 != 0 {
return None;
@@ -55,12 +19,6 @@ fn pts(buf: &[f64]) -> Option<Vec<Vec2>> {
Some(buf.chunks_exact(2).map(|c| Vec2::new(c[0], c[1])).collect())
}
fn pt_lists(buf: &[f64]) -> Option<Vec<Vec<Vec2>>> {
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<TangentTarget> {
match *buf {
[kind, ax, ay, bx, by] if kind == 0.0 => {
@@ -86,25 +44,6 @@ fn enc_pts(pts: &[Vec2]) -> Vec<f64> {
out
}
fn enc_pt_lists(lists: &[Vec<Vec2>]) -> Vec<f64> {
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<f64> {
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<f64> {
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<f64> {
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<f64> {
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<f64> {
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<f64> {
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());
}
}
+33 -46
View File
@@ -1,33 +1,24 @@
//! Bindungen des Objektfangs (`crate::snap`). Die Fang-Strecken eines Projekt-Geschosses legt TS
//! einmal ab (`snap_segs_hold`) und gibt sie frei, wenn es sie ersetzt (`snap_segs_release`).
//! Je Mausbewegung `snap_eval`; unbekannte Nummer oder kaputte Eingabe → leeres Ergebnis.
//! Bindungen des Objektfangs ([K4] S3, `crate::snap_model`): die Kandidaten eines Geschosses sammelt
//! der Kern aus dem Dokument (`doc_snap_hold`, gleiche Nummer solange sich die betroffenen Felder
//! nicht ändern); je Mausbewegung `snap_query`. Unbekannte Nummer oder kaputte Eingabe → leeres
//! Ergebnis (TS sammelt dann neu).
use crate::snap::{segs_from, snap_segments, Cand, SnapQuery, SnapSet};
use crate::snap::{segs_from, Cand};
use crate::snap_model::{query, ModelQuery, SnapCache};
use super::document::with_doc;
use std::cell::RefCell;
use wasm_bindgen::prelude::wasm_bindgen;
thread_local! {
static SETS: RefCell<(u32, Vec<(u32, SnapSet)>)> = const { RefCell::new((0, Vec::new())) };
static CACHE: RefCell<SnapCache> = RefCell::new(SnapCache::default());
}
/// Strecken `[ax, ay, bx, by, …]` ablegen; Nummer ≥ 1 (0 = kaputte Eingabe).
/// Kandidaten des Geschosses `level` mit den sichtbaren Ebenen `codes` (durch `\n` getrennt) im
/// Dokument `h`; Nummer ≥ 1 für [`snap_query`] (0 = Dokument nicht offen).
#[wasm_bindgen]
pub fn snap_segs_hold(flat: &[f64]) -> u32 {
if flat.len() % 4 != 0 {
return 0;
}
SETS.with(|h| {
let mut h = h.borrow_mut();
h.0 = h.0.wrapping_add(1).max(1);
let id = h.0;
h.1.push((id, SnapSet::new(segs_from(flat))));
id
})
}
#[wasm_bindgen]
pub fn snap_segs_release(id: u32) {
SETS.with(|h| h.borrow_mut().1.retain(|e| e.0 != id));
pub fn doc_snap_hold(h: u32, level: &str, codes: &str) -> u32 {
let codes: Vec<String> = if codes.is_empty() { Vec::new() } else { codes.split('\n').map(str::to_owned).collect() };
with_doc(h, |d| CACHE.with(|c| c.borrow_mut().hold(h, d, level, &codes))).unwrap_or(0)
}
fn push(out: &mut Vec<f64>, c: Option<Cand>) {
@@ -37,44 +28,40 @@ fn push(out: &mut Vec<f64>, c: Option<Cand>) {
}
}
/// Fang über abgelegte (`held`, 0 = keine) + Zusatz-Strecken. `int_mode` 1: Schnittpunkte nur
/// aus `int_segs`, sonst aus denselben Strecken. `flags` s. `snap::F_*`; letzter Punkt NaN =
/// keiner. Ergebnis: `[nächste Strecke (−1), ax, ay, bx, by, Block A (x, y, Art, distPx,
/// Punktzahl), Block B (…)]` (NaN = kein Kandidat); leer = Fehler (Nummer unbekannt).
/// Fang je Mausbewegung über das abgelegte Geschoss `held` plus Entwurfs- und Blatt-Strecken
/// (`[ax, ay, bx, by, …]`). `flags`: `snap::F_*` und `snap_model::F_*`; letzter Punkt NaN = keiner.
/// Ergebnis (25 Zahlen): `[nächste Strecke (1|−1), ax, ay, bx, by]`, dann je Block `[x, y, Art,
/// distPx, Punktzahl]` (NaN = kein Kandidat): A (Lot, Endpunkte), Raum-Anker, B (Mitte, Schnitt,
/// Kante), C (Kreise, Ellipsen). Leer = Nummer unbekannt bzw. kaputte Eingabe.
#[wasm_bindgen]
#[allow(clippy::too_many_arguments)]
pub fn snap_eval(held: u32, extra: &[f64], int_mode: u32, int_segs: &[f64], rx: f64, ry: f64, tol_m: f64, px_per_m: f64, flags: u32, lx: f64, ly: f64) -> Vec<f64> {
if extra.len() % 4 != 0 || int_segs.len() % 4 != 0 {
pub fn snap_query(held: u32, draft: &[f64], sheet: &[f64], rx: f64, ry: f64, tol_m: f64, px_per_m: f64, flags: u32, lx: f64, ly: f64) -> Vec<f64> {
if draft.len() % 4 != 0 || sheet.len() % 4 != 0 {
return Vec::new();
}
let extra = segs_from(extra);
let ints = segs_from(int_segs);
let run = |base: &SnapSet| -> Vec<f64> {
let q = SnapQuery {
base,
extra: &extra,
int_segs: (int_mode == 1).then_some(&ints[..]),
let (draft, sheet) = (segs_from(draft), segs_from(sheet));
CACHE.with(|c| {
let c = c.borrow();
let Some(ls) = c.get(held) else { return Vec::new() };
let q = ModelQuery {
draft: &draft,
sheet: &sheet,
raw: (rx, ry),
tol_m,
px_per_m,
flags,
last: (!lx.is_nan() && !ly.is_nan()).then_some((lx, ly)),
};
let o = snap_segments(&q);
let mut out = Vec::with_capacity(15);
let o = query(ls, &q);
let mut out = Vec::with_capacity(25);
match o.dwell {
Some(i) => {
let s = if i < base.segs.len() { base.segs[i] } else { extra[i - base.segs.len()] };
out.extend_from_slice(&[i as f64, s[0], s[1], s[2], s[3]]);
}
Some(s) => out.extend_from_slice(&[1.0, s[0], s[1], s[2], s[3]]),
None => out.extend_from_slice(&[-1.0, f64::NAN, f64::NAN, f64::NAN, f64::NAN]),
}
push(&mut out, o.a);
push(&mut out, o.anchors);
push(&mut out, o.b);
push(&mut out, o.c);
out
};
if held == 0 {
return run(&SnapSet::default());
}
SETS.with(|h| h.borrow().1.iter().find(|e| e.0 == held).map(|e| run(&e.1))).unwrap_or_default()
})
}
+10 -40
View File
@@ -156,7 +156,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";
@@ -187,13 +187,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,
@@ -1324,25 +1318,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<string, Drawing2D[]>();
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([]);
@@ -1540,24 +1520,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([]);
};
+5 -14
View File
@@ -36,20 +36,17 @@ export {
export {
type DrawingIndex,
buildDrawingIndex,
drawingsNear,
drawingsWithinDistance,
isIndexable,
nearestInDrawings,
pointSegDist as pointSegDist__geometry_drawingIndex,
} from "../geometry/drawingIndex";
export {
type SegSnapCand,
type SegSnapResult,
holdSnapSegments,
releaseSnapSegments,
snapOnSegments,
} from "../geometry/snapSegments";
type ModelSnapCand,
type ModelSnapResult,
holdModelSnap,
queryModelSnap,
} from "../geometry/modelSnap";
export {
type Fillet,
@@ -58,11 +55,6 @@ export {
offsetSegment,
pointSegmentDistance,
polylineEdges,
removeSegment,
removeSegmentWithBulge,
splitAtIntersections,
splitClosedByChord,
splitPolylineAtParam,
tangentCircleCenters,
vecEqual,
} from "../geometry/kernel2d";
@@ -132,7 +124,6 @@ export {
MIN_STEPS,
defaultStepCount,
stairGeometry,
stairOutline,
} from "../geometry/stair";
export {
+30 -4
View File
@@ -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.
+2 -2
View File
@@ -122,7 +122,7 @@ describe("pasteElementClipboard", () => {
it("fügt Wand + Öffnung mit NEUEN, verknüpften IDs auf dem aktiven Geschoss ein", () => {
const p = project();
const clip = collectElementClipboard(p, { ...emptySel(), wallIds: ["w1"] })!;
const { ops, pastedIds } = pasteElementClipboard(clip, "og");
const { ops, pastedIds } = pasteElementClipboard(p, clip, "og");
const next = applyOps(p, ops);
expect(next.walls.length).toBe(2);
expect(next.openings!.length).toBe(2);
@@ -139,7 +139,7 @@ describe("pasteElementClipboard", () => {
it("Originale bleiben unverändert (immutabel)", () => {
const p = project();
const clip = collectElementClipboard(p, { ...emptySel(), wallIds: ["w1"] })!;
pasteElementClipboard(clip, "og");
pasteElementClipboard(p, clip, "og");
expect(p.walls.length).toBe(1);
expect(p.walls[0].id).toBe("w1");
});
+36 -83
View File
@@ -30,8 +30,8 @@ import type {
Stair,
Wall,
} from "../model/types";
import { uniqueId } from "../tools/types";
import { addItems } from "../core";
import { uniqueStamp } from "../tools/types";
import { documentFor } from "../core/document";
import type { CoreOp } from "../core";
/** Auswahl-IDs je Bauteil-Art, wie sie die 9 Auswahl-Kanäle des Stores liefern. */
@@ -144,94 +144,47 @@ export interface PastedIds {
columnIds: string[];
}
/** Projekt-Liste → Feld in {@link PastedIds}. */
const PASTED_KEY: Record<string, keyof PastedIds> = {
walls: "wallIds",
drawings2d: "drawingIds",
ceilings: "ceilingIds",
roofs: "roofIds",
openings: "openingIds",
stairs: "stairIds",
rooms: "roomIds",
extrudedSolids: "extrudedSolidIds",
columns: "columnIds",
};
/**
* Fügt eine Zwischenablage ins Projekt ein: Klone mit neuen IDs auf dem
* AKTIVEN Geschoss (`activeLevelId`), an denselben Modell-Koordinaten. Liefert
* die Ops (Anhängen je Liste) + die neuen IDs (für die Nachauswahl).
* Fügt eine Zwischenablage ins Projekt ein ([K4] S3: gerechnet im Kern, `cmd_paste.rs`): Klone mit
* neuen IDs auf dem AKTIVEN Geschoss (`activeLevelId`), an denselben Modell-Koordinaten; Öffnungen
* an die mitkopierte Wirtswand umgehängt. Liefert die Ops (Anhängen je Liste) + die neuen IDs (für
* die Nachauswahl). `project` bestimmt nur das Kern-Dokument der Anfrage.
*/
export function pasteElementClipboard(
project: Project,
clip: ElementClipboard,
activeLevelId: string,
): { ops: CoreOp[]; pastedIds: PastedIds } {
const wallIdMap = new Map<string, string>();
const newWalls: Wall[] = clip.walls.map((w) => {
const id = uniqueId("W");
wallIdMap.set(w.id, id);
return { ...w, id, floorId: activeLevelId };
});
const newDrawings: Drawing2D[] = clip.drawings.map((d) => ({
...d,
id: uniqueId("dr2d"),
levelId: activeLevelId,
}));
const newCeilings: Ceiling[] = clip.ceilings.map((c) => ({
...c,
id: uniqueId("C"),
floorId: activeLevelId,
}));
const newRoofs: Roof[] = clip.roofs.map((r) => ({
...r,
id: uniqueId("RF"),
floorId: activeLevelId,
}));
// Nur Öffnungen mit einer erfolgreich mitkopierten Wirtswand ergeben eine
// gültige neue Öffnung (sollte durch `collectElementClipboard` immer
// gegeben sein — Map-Miss defensiv übersprungen statt eine kaputte
// Öffnung ohne Wirt zu erzeugen).
const newOpenings: Opening[] = [];
for (const o of clip.openings) {
const hostWallId = wallIdMap.get(o.hostWallId);
if (!hostWallId) continue;
newOpenings.push({ ...o, id: uniqueId("O"), hostWallId });
}
const newStairs: Stair[] = clip.stairs.map((s) => ({
...s,
id: uniqueId("ST"),
floorId: activeLevelId,
}));
const newRooms: Room[] = clip.rooms.map((r) => ({
...r,
id: uniqueId("RM"),
floorId: activeLevelId,
}));
const newExtrudedSolids: ExtrudedSolid[] = clip.extrudedSolids.map((s) => ({
...s,
id: uniqueId("extrude"),
levelId: activeLevelId,
}));
const newColumns: Column[] = clip.columns.map((c) => ({
...c,
id: uniqueId("column"),
floorId: activeLevelId,
}));
// Wände vor Öffnungen (Wirtswand zuerst), sonst Reihenfolge der Projekt-Listen.
const ops: CoreOp[] = [
...addItems("walls", newWalls),
...addItems("drawings2d", newDrawings),
...addItems("ceilings", newCeilings),
...addItems("roofs", newRoofs),
...addItems("openings", newOpenings),
...addItems("stairs", newStairs),
...addItems("rooms", newRooms),
...addItems("extrudedSolids", newExtrudedSolids),
...addItems("columns", newColumns),
];
return {
ops,
pastedIds: {
wallIds: newWalls.map((w) => w.id),
drawingIds: newDrawings.map((d) => d.id),
ceilingIds: newCeilings.map((c) => c.id),
roofIds: newRoofs.map((r) => r.id),
openingIds: newOpenings.map((o) => o.id),
stairIds: newStairs.map((s) => s.id),
roomIds: newRooms.map((r) => r.id),
extrudedSolidIds: newExtrudedSolids.map((s) => s.id),
columnIds: newColumns.map((c) => c.id),
},
const ops = documentFor(project).cmdOps({ cmd: "paste", clip, levelId: activeLevelId, stamp: uniqueStamp() });
const pastedIds: PastedIds = {
wallIds: [],
drawingIds: [],
ceilingIds: [],
roofIds: [],
openingIds: [],
stairIds: [],
roomIds: [],
extrudedSolidIds: [],
columnIds: [],
};
for (const op of ops) {
const key = op.kind === "add" ? PASTED_KEY[op.collection] : undefined;
if (op.kind === "add" && key) for (const e of op.items) pastedIds[key].push((e as { id: string }).id);
}
return { ops, pastedIds };
}
export { EMPTY_CLIPBOARD };
+55 -16
View File
@@ -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]));
});
});
+25 -257
View File
@@ -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<string>();
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 };
+3 -7
View File
@@ -1,8 +1,8 @@
// Raster-Index über die Bounding-Boxen von Linien-/Polylinien-Zeichnungen
// (Drawing2D). Abfragen prüfen nur die Zeichnungen in Cursornähe statt alle —
// bei einem Kataster-Import ~10^5 Zeichnungen / 3,7 Mio. Strecken. Genutzt für
// Hover/Pick/Marquee (plan/planView/underlayAccess.ts) und den Objektfang
// (tools/snapping.ts).
// Hover/Pick/Marquee (plan/planView/underlayAccess.ts); der Objektfang hat seinen
// eigenen Index im Kern (`snap_model.rs`). `pointSegDist` nutzt der Fang für die Blatt-Geometrie.
import type { Drawing2D, Vec2 } from "../model/types";
import { drawingBox } from "./drawingBounds";
@@ -47,10 +47,6 @@ const TARGET_PER_CELL = 4;
const MAX_CELLS = 2_000_000;
const MAX_CELLS_PER_DRAWING = 256;
/** Ob eine Zeichnung vom Index erfasst wird (Linie/Polylinie mit Punkten). */
export const isIndexable = (d: Drawing2D): boolean =>
d.geom.shape === "line" || d.geom.shape === "polyline";
export function buildDrawingIndex(drawings: readonly Drawing2D[]): DrawingIndex | null {
if (drawings.length === 0) return null;
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
@@ -104,7 +100,7 @@ export function buildDrawingIndex(drawings: readonly Drawing2D[]): DrawingIndex
* Indizes der Zeichnungen, deren Bounding-Box (um `r` erweitert) den Punkt `m`
* enthält — Kandidaten, jede höchstens einmal.
*/
export function drawingsNear(index: DrawingIndex, m: Vec2, r: number): number[] {
function drawingsNear(index: DrawingIndex, m: Vec2, r: number): number[] {
const { minX, minY, cell, cols, rows, cellStart, items, long, drawings } = index;
const out: number[] = [];
const seen = new Set<number>();
-86
View File
@@ -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)));
}
@@ -1,10 +1,11 @@
// Objektfang auf Strecken im Kern ([K3d], `core/src/snap.rs`): gleiche Wahl wie die einfache
// Suche über alle Strecken/Paare (Raster-Vorauswahl und Geraden-Filter für Schnittpunkte dürfen
// nichts ändern). (Gleichheit zur früheren TS-Fassung von computeSnap: 2600 Abfragen, s. TODO [K3d].)
// Objektfang aus dem Modell im Kern ([K4] S3, `core/src/snap_model.rs` + `snap.rs`): gleiche Wahl wie
// die einfache Suche über alle Strecken/Paare (Raster-Vorauswahl und Geraden-Filter für Schnittpunkte
// dürfen nichts ändern), gleiche Nummer solange das Dokument gleich bleibt.
import { describe, expect, it } from "vitest";
import { holdSnapSegments, releaseSnapSegments, snapOnSegments, type SnapSeg } from "./snapSegments";
import type { Vec2 } from "../model/types";
import { holdModelSnap, queryModelSnap, type SnapSeg } from "./modelSnap";
import { sampleProject } from "../model/sampleProject";
import type { Drawing2D, Project, Vec2 } from "../model/types";
const PRIORITY: Record<string, number> = { perpendicular: 1, endpoint: 7, midpoint: 3, intersection: 5, onEdge: 0 };
@@ -55,10 +56,21 @@ function brute(segs: SnapSeg[], raw: Vec2, tolM: number, pxPerM: number, last: V
return { a: a.get(), b: b.get() };
}
describe("snapOnSegments (Kern)", () => {
const LEVEL = sampleProject.drawingLevels[0].id;
const CODE = "01";
function lineProject(segs: SnapSeg[]): Project {
const drawings: Drawing2D[] = segs.map(([a, b], i) => ({ id: `l${i}`, type: "drawing2d", levelId: LEVEL, categoryCode: CODE, geom: { shape: "line", a, b } }));
return { ...sampleProject, walls: [], rooms: [], ceilings: [], roofs: [], stairs: [], columns: [], drawings2d: drawings };
}
const flags = { segs: true, perpendicular: true, endpoint: true, midpoint: true, intersection: true, onEdge: true, center: false, tangent: false };
describe("Objektfang aus dem Modell (Kern)", () => {
it("gleich wie die Suche über alle Strecken und Paare (Zufallsdaten)", () => {
let seed = 3;
const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
const codes = new Set([CODE]);
for (let run = 0; run < 8; run++) {
const segs: SnapSeg[] = [];
for (let i = 0; i < 300; i++) {
@@ -67,36 +79,31 @@ describe("snapOnSegments (Kern)", () => {
const k = rnd();
segs.push(k < 0.4 ? [{ x, y }, { x: x + rnd() * 5, y }] : k < 0.8 ? [{ x, y }, { x, y: y + rnd() * 5 }] : [{ x, y }, { x: x + rnd() * 30 - 15, y: y + rnd() * 30 - 15 }]);
}
const base = segs.slice(0, 250);
const extra = segs.slice(250);
const h = holdSnapSegments(base);
const p = lineProject(segs.slice(0, 250));
const draft = segs.slice(250);
const h = holdModelSnap(p, LEVEL, codes);
expect(holdModelSnap(p, LEVEL, codes)).toBe(h);
for (let q = 0; q < 25; q++) {
const raw = { x: rnd() * 20, y: rnd() * 20 };
const tolM = 0.05 + rnd() * 0.5;
const last = rnd() < 0.5 ? { x: rnd() * 20, y: rnd() * 20 } : null;
const r = snapOnSegments(h, extra, null, { raw, tolM, pxPerMeter: 100, perpendicular: true, endpoint: true, midpoint: true, intersection: true, onEdge: true, lastPoint: last })!;
const r = queryModelSnap(h, draft, [], { raw, tolM, pxPerMeter: 100, lastPoint: last, ...flags })!;
const e = brute(segs, raw, tolM, 100, last);
expect(r.a).toEqual(e.a);
expect(r.b).toEqual(e.b);
}
releaseSnapSegments(h);
expect(snapOnSegments(h, [], null, { raw: { x: 0, y: 0 }, tolM: 1, pxPerMeter: 1, perpendicular: false, endpoint: true, midpoint: false, intersection: false, onEdge: false, lastPoint: null })).toBeNull();
}
}, 60_000);
expect(queryModelSnap(987654, [], [], { raw: { x: 0, y: 0 }, tolM: 1, pxPerMeter: 1, lastPoint: null, ...flags })).toBeNull();
}, 60_000);
it("nächste Strecke für das Verweilen", () => {
const r = snapOnSegments(0, [[{ x: 0, y: 0 }, { x: 10, y: 0 }], [{ x: 5, y: -5 }, { x: 5, y: 5 }]], null, {
raw: { x: 5.05, y: 0.02 },
tolM: 0.2,
pxPerMeter: 100,
perpendicular: false,
endpoint: true,
midpoint: true,
intersection: true,
onEdge: true,
lastPoint: null,
})!;
const p = lineProject([[{ x: 0, y: 0 }, { x: 10, y: 0 }]]);
const h = holdModelSnap(p, LEVEL, new Set([CODE]));
const r = queryModelSnap(h, [[{ x: 5, y: -5 }, { x: 5, y: 5 }]], [], { raw: { x: 5.05, y: 0.02 }, tolM: 0.2, pxPerMeter: 100, lastPoint: null, ...flags })!;
expect(r.nearest).toEqual([{ x: 0, y: 0 }, { x: 10, y: 0 }]);
expect(r.b?.kind).toBe("intersection");
// Ohne sichtbare Ebene: keine Strecken.
const h2 = holdModelSnap(p, LEVEL, new Set(["xx"]));
expect(queryModelSnap(h2, [], [], { raw: { x: 5.05, y: 0.02 }, tolM: 0.2, pxPerMeter: 100, lastPoint: null, ...flags })!.nearest).toBeNull();
});
});
+115
View File
@@ -0,0 +1,115 @@
// Objektfang aus dem Modell über den Kern ([K4] S3, `src-tauri/core/src/snap_model.rs` + `snap.rs`):
// Der Kern sammelt die Fang-Kandidaten eines Geschosses (Wandachsen, Schichtgrenzen, Umrisse von
// Raum/Decke/Dach/Treppe/Stütze, 2D-Zeichnungen, Kreise/Bögen, Raum-Anker, Ellipsen-Mittelpunkte)
// einmal je Dokument-Stand ({@link holdModelSnap}); je Mausbewegung gehen nur Cursor, Toleranz und
// die Zusatzstrecken (Entwurf, Blatt-Geometrie) über die Grenze ({@link queryModelSnap}). Die
// Bildschirm-Toleranz, Verweilen/Teilpunkte, Parallele, Raster und Winkel bleiben in
// `tools/snapping.ts`.
import type { Project, Vec2 } from "../model/types";
import { core } from "../engine/coreWasm";
import { documentFor } from "../core/document";
export type SnapSeg = [Vec2, Vec2];
/** Fang-Arten des Kerns (Code → Name wie `SnapKind`). */
const KINDS = ["perpendicular", "endpoint", "midpoint", "intersection", "onEdge", "center", "quadrant", "tangent"] as const;
export type ModelSnapKind = (typeof KINDS)[number];
export interface ModelSnapCand {
point: Vec2;
kind: ModelSnapKind;
distPx: number;
/** `distPx − Priorität` (kleiner gewinnt). */
score: number;
}
/** Ergebnis in der Reihenfolge, in der `computeSnap` die Kandidaten zusammenführt. */
export interface ModelSnapResult {
/** Nächste Strecke innerhalb der Toleranz (Lotfusspunkt-Abstand) oder null (Verweilen). */
nearest: SnapSeg | null;
/** Lot vom letzten Punkt, Strecken-Endpunkte. */
a: ModelSnapCand | null;
/** Raum-Stempel-Anker (Endpunkt). */
anchors: ModelSnapCand | null;
/** Mittelpunkte, Schnittpunkte, Punkt auf der Kante. */
b: ModelSnapCand | null;
/** Kreise/Bögen (Mittelpunkt, Quadranten, Bogen-Endpunkte, Tangente), Ellipsen-Mittelpunkte. */
c: ModelSnapCand | null;
}
export interface ModelSnapQuery {
raw: Vec2;
tolM: number;
pxPerMeter: number;
/** Strecken-Fang überhaupt (auch nur für Verweilen/Parallele). */
segs: boolean;
perpendicular: boolean;
endpoint: boolean;
midpoint: boolean;
intersection: boolean;
onEdge: boolean;
center: boolean;
tangent: boolean;
lastPoint: Vec2 | null;
}
function flat(segs: readonly SnapSeg[]): Float64Array {
const out = new Float64Array(segs.length * 4);
for (let i = 0; i < segs.length; i++) {
const [a, b] = segs[i];
out[4 * i] = a.x;
out[4 * i + 1] = a.y;
out[4 * i + 2] = b.x;
out[4 * i + 3] = b.y;
}
return out;
}
/**
* Kandidaten des Geschosses `levelId` (sichtbare Ebenen `codes`) im Kern sammeln bzw. wiederfinden:
* dieselbe Nummer, solange sich die betroffenen Felder des Dokuments nicht ändern. 0 = kein Dokument.
*/
export function holdModelSnap(project: Project, levelId: string, codes: ReadonlySet<string>): number {
const doc = documentFor(project);
return doc.id ? core().doc_snap_hold(doc.id, levelId, [...codes].join("\n")) : 0;
}
const cand = (f: Float64Array, k: number): ModelSnapCand | null =>
Number.isNaN(f[k + 2]) ? null : { point: { x: f[k], y: f[k + 1] }, kind: KINDS[f[k + 2]], distPx: f[k + 3], score: f[k + 4] };
/**
* Fang je Mausbewegung über die abgelegten Kandidaten `held` plus Entwurfs- (`draft`) und
* Blatt-Strecken (`sheet`, nahe am Cursor, nächste zuerst). null, wenn `held` nicht (mehr) im Kern liegt.
*/
export function queryModelSnap(held: number, draft: readonly SnapSeg[], sheet: readonly SnapSeg[], q: ModelSnapQuery): ModelSnapResult | null {
const flags =
(q.perpendicular ? 1 : 0) |
(q.endpoint ? 2 : 0) |
(q.midpoint ? 4 : 0) |
(q.intersection ? 8 : 0) |
(q.onEdge ? 16 : 0) |
(q.center ? 32 : 0) |
(q.tangent ? 64 : 0) |
(q.segs ? 128 : 0);
const f = core().snap_query(
held,
flat(draft),
flat(sheet),
q.raw.x,
q.raw.y,
q.tolM,
q.pxPerMeter,
flags,
q.lastPoint ? q.lastPoint.x : NaN,
q.lastPoint ? q.lastPoint.y : NaN,
);
if (f.length < 25) return null;
return {
nearest: f[0] >= 0 ? [{ x: f[1], y: f[2] }, { x: f[3], y: f[4] }] : null,
a: cand(f, 5),
anchors: cand(f, 10),
b: cand(f, 15),
c: cand(f, 20),
};
}
-95
View File
@@ -1,95 +0,0 @@
// Objektfang auf Strecken über den Kern ([K3d], `src-tauri/core/src/snap.rs`): Lotfusspunkt,
// Endpunkte, Mittelpunkte, Schnittpunkte, Punkt auf der Kante und die nächste Strecke (Verweilen).
// Die Strecken eines Projekt-Geschosses liegen einmal im Kern ({@link holdSnapSegments}); je
// Mausbewegung gehen nur Cursor und Zusatzstrecken über die Grenze. Die Sammlung der Strecken
// und die übrigen Fang-Arten (Raster, Winkel, Kreise, Teilpunkte) bleiben in `tools/snapping.ts`.
import type { Vec2 } from "../model/types";
import { core } from "../engine/coreWasm";
export type SnapSeg = [Vec2, Vec2];
/** Fang-Arten des Kerns (Code → Name wie `SnapKind`). */
const KINDS = ["perpendicular", "endpoint", "midpoint", "intersection", "onEdge"] as const;
export type SegSnapKind = (typeof KINDS)[number];
export interface SegSnapCand {
point: Vec2;
kind: SegSnapKind;
distPx: number;
/** `distPx − Priorität` (kleiner gewinnt). */
score: number;
}
export interface SegSnapResult {
/** Nächste Strecke innerhalb der Toleranz (Lotfusspunkt-Abstand) oder null. */
nearest: SnapSeg | null;
/** Block A: Lot vom letzten Punkt, Endpunkte der Strecken. */
a: SegSnapCand | null;
/** Block B: Mittelpunkte, Schnittpunkte, Punkt auf der Kante. */
b: SegSnapCand | null;
}
export interface SegSnapQuery {
raw: Vec2;
tolM: number;
pxPerMeter: number;
perpendicular: boolean;
endpoint: boolean;
midpoint: boolean;
intersection: boolean;
onEdge: boolean;
lastPoint: Vec2 | null;
}
function flat(segs: readonly SnapSeg[]): Float64Array {
const out = new Float64Array(segs.length * 4);
for (let i = 0; i < segs.length; i++) {
const [a, b] = segs[i];
out[4 * i] = a.x;
out[4 * i + 1] = a.y;
out[4 * i + 2] = b.x;
out[4 * i + 3] = b.y;
}
return out;
}
/** Strecken im Kern ablegen; Nummer für {@link snapOnSegments} (freigeben: {@link releaseSnapSegments}). */
export function holdSnapSegments(segs: readonly SnapSeg[]): number {
return core().snap_segs_hold(flat(segs));
}
export function releaseSnapSegments(id: number): void {
if (id) core().snap_segs_release(id);
}
const cand = (f: Float64Array, k: number): SegSnapCand | null =>
Number.isNaN(f[k + 2]) ? null : { point: { x: f[k], y: f[k + 1] }, kind: KINDS[f[k + 2]], distPx: f[k + 3], score: f[k + 4] };
/**
* Fang über die abgelegten Strecken `held` (0 = keine) und `extra` (in dieser Reihenfolge);
* Schnittpunkte aus `intSegs` (null = aus denselben Strecken). null, wenn `held` nicht (mehr) im
* Kern liegt.
*/
export function snapOnSegments(held: number, extra: readonly SnapSeg[], intSegs: readonly SnapSeg[] | null, q: SegSnapQuery): SegSnapResult | null {
const flags = (q.perpendicular ? 1 : 0) | (q.endpoint ? 2 : 0) | (q.midpoint ? 4 : 0) | (q.intersection ? 8 : 0) | (q.onEdge ? 16 : 0);
const f = core().snap_eval(
held,
flat(extra),
intSegs ? 1 : 0,
intSegs ? flat(intSegs) : new Float64Array(0),
q.raw.x,
q.raw.y,
q.tolM,
q.pxPerMeter,
flags,
q.lastPoint ? q.lastPoint.x : NaN,
q.lastPoint ? q.lastPoint.y : NaN,
);
if (f.length < 15) return null;
return {
nearest: f[0] >= 0 ? [{ x: f[1], y: f[2] }, { x: f[3], y: f[4] }] : null,
a: cand(f, 5),
b: cand(f, 10),
};
}
+4 -25
View File
@@ -1,10 +1,10 @@
// Unit-Tests für die Wand-/Decken-Resolver: Referenzlinie (`wallReferenceOffset`) und die UK/OK der
// Decken über den Kern (`verticalExtents`, Regeln `model/helpers.rs::heights`).
// Unit-Tests für die UK/OK der Decken über den Kern (`verticalExtents`, Regeln
// `model/helpers.rs::heights`). Die Referenzlinie der Wand rechnet der Kern (`joins.rs::reference_offset`,
// Fang: `snap_model.rs::wall_layer_segments`).
import { describe, it, expect } from "vitest";
import { wallReferenceOffset } from "./wall";
import { verticalExtents } from "../geometry/grips";
import type { Ceiling, Project, Wall } from "./types";
import type { Ceiling, Project } from "./types";
/** Minimalprojekt mit einem Geschoss (baseElevation 0, floorHeight 2.6) und
* einem einschichtigen Wandtyp (0.2 m), den die Decke als Aufbau nutzt. */
@@ -116,24 +116,3 @@ describe("UK/OK einer Decke", () => {
expect(zBottom).toBeCloseTo(2.9); // baseElevation(og)=2.8 + offset(0.1)
});
});
describe("wallReferenceOffset", () => {
const w = (extra: Partial<Wall>): Wall => ({ referenceLine: "center", ...extra } as Wall);
const T = 0.4; // Gesamtdicke → half = 0.2
it("bildet die benannten Linien ab (aussen/mitte/innen)", () => {
expect(wallReferenceOffset(w({ referenceLine: "left" }), T)).toBeCloseTo(0.2, 6);
expect(wallReferenceOffset(w({ referenceLine: "center" }), T)).toBeCloseTo(0, 6);
expect(wallReferenceOffset(w({ referenceLine: "right" }), T)).toBeCloseTo(-0.2, 6);
});
it("übersteuert die Referenzlinie mit einem freien Fugen-Versatz", () => {
// Fuge z. B. nach einer 0.05-Aussenschale: offset = half − 0.05 = 0.15.
expect(wallReferenceOffset(w({ referenceLine: "left", referenceOffset: 0.15 }), T)).toBeCloseTo(0.15, 6);
});
it("klemmt den Fugen-Versatz auf ±halbe Dicke", () => {
expect(wallReferenceOffset(w({ referenceOffset: 5 }), T)).toBeCloseTo(0.2, 6);
expect(wallReferenceOffset(w({ referenceOffset: -5 }), T)).toBeCloseTo(-0.2, 6);
});
});
-37
View File
@@ -1,37 +0,0 @@
// Wand-Resolver: Versatz der Achse über die Dicke (Referenzlinie). Die vertikale Ausdehnung (UK/OK)
// rechnet der Kern (`model/helpers.rs::heights`; TS: Abfrage `verticalExtents`, `geometry/grips.ts`).
//
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import type { Wall } from "./types";
/**
* Versatz der Schichtstapelung entlang der linken Normalen `+n` (leftNormal),
* sodass die Achse auf der gewünschten Wandfläche liegt. Die Schichten werden
* normalerweise symmetrisch von `−T/2` (außen, +n-Seite) bis `+T/2` (innen)
* gestapelt; dieser Versatz wird ZUSÄTZLICH auf jeden Schicht-Offset addiert.
*
* • "center" → 0 (Schichten symmetrisch um die Achse — Default).
* • "left" → +T/2 (Achse auf der +n-/„außen"-Fläche; Wand liegt auf −n).
* • "right" → −T/2 (Achse auf der −n-/„innen"-Fläche; Wand liegt auf +n).
*
* Die Schicht-Offsets laufen von −T/2 (= +n außen) nach +T/2 (= −n innen).
* Für "left" soll die −T/2-Kante (außen) auf der Achse liegen → +T/2 addieren,
* sodass die Schichten von 0…T (alle auf der −n-Seite) liegen.
*/
export function wallReferenceOffset(
wall: Wall,
totalThickness: number,
): number {
const half = totalThickness / 2;
// Freier Fugen-Versatz (Schichttrennlinie als Referenz) übersteuert die
// benannte Referenzlinie. Auf die Wanddicke geklemmt, damit die Achse nie
// ausserhalb der Wand landet.
if (wall.referenceOffset != null) {
return Math.max(-half, Math.min(half, wall.referenceOffset));
}
const ref = wall.referenceLine ?? "center";
if (ref === "left") return +half;
if (ref === "right") return -half;
return 0;
}
+11 -4
View File
@@ -28,7 +28,7 @@ import {
isClipboardEmpty,
pasteElementClipboard,
} from "../editors/elementClipboard";
import type { ElementClipboard, ElementSelectionIds } from "../editors/elementClipboard";
import type { ElementClipboard, ElementSelectionIds, PastedIds } from "../editors/elementClipboard";
import { parseClipboardText, serializeClipboardText } from "../editors/elementClipboardSerialize";
import { matchesShortcut, type ShortcutId, type ShortcutOverrides } from "./keyboardShortcuts";
@@ -549,7 +549,7 @@ export function useElementClipboardShortcut(
setElementClipboard: (c: ElementClipboard | null) => void,
activeLevelId: string,
project: Project,
applyChange: (ops: readonly CoreOp[]) => void,
applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[])) => void,
setSelected: {
wallIds: (ids: string[]) => void;
drawingIds: (ids: string[]) => void;
@@ -588,8 +588,15 @@ export function useElementClipboardShortcut(
e.preventDefault();
const paste = (clip: ElementClipboard | null) => {
if (!clip || isClipboardEmpty(clip)) return;
const { ops, pastedIds } = pasteElementClipboard(clip, activeLevelId);
applyChange(ops);
// Kern rechnet auf dem aktuellen Store-Projekt; die neuen ids für die Nachauswahl.
const out: { ids?: PastedIds } = {};
applyChange((p) => {
const r = pasteElementClipboard(p, clip, activeLevelId);
out.ids = r.pastedIds;
return r.ops;
});
const pastedIds = out.ids;
if (!pastedIds) return;
setSelected.wallIds(pastedIds.wallIds);
setSelected.drawingIds(pastedIds.drawingIds);
setSelected.ceilingIds(pastedIds.ceilingIds);
+131
View File
@@ -0,0 +1,131 @@
// [K4] Messung: Objektfang je Mausbewegung (`computeSnap`) auf grossen Projekten — 3000 Wände +
// 20 000 Zeichnungen (Nahmodus), 3000 Wände + 1500 Zeichnungen (Normalmodus) und ein Kataster mit
// 150 000 Linien/Polylinien. Werte gehen nach stderr (TODO [K4]); geprüft wird vor allem, dass der
// Fang etwas findet. Die Grenzen sind grosszügig (Container unter Last).
import { describe, expect, it } from "vitest";
import { computeSnap, type SnapInput } from "./snapping";
import { DEFAULT_SNAP } from "./types";
import { sampleProject } from "../model/sampleProject";
import { getState } from "../state/appStore";
import { generatePlan, replaceItem } from "../core";
import type { Drawing2D, Project, Vec2, Wall } from "../model/types";
function wallsAndDrawings(nDrawings: number): Project {
const base = sampleProject.walls;
const walls: Wall[] = Array.from({ length: 3000 }, (_, i) => ({
...base[i % base.length],
id: `w${i}`,
floorId: sampleProject.drawingLevels[0].id,
start: { x: (i % 60) * 4, y: Math.floor(i / 60) * 4 },
end: { x: (i % 60) * 4 + 4, y: Math.floor(i / 60) * 4 },
}));
const level = sampleProject.drawingLevels[0].id;
const drawings: Drawing2D[] = Array.from({ length: nDrawings }, (_, i) => ({
id: `d${i}`,
type: "drawing2d",
levelId: level,
categoryCode: sampleProject.layers[0].code,
geom: { shape: "polyline", closed: false, pts: [{ x: (i % 200) * 1.2, y: Math.floor(i / 200) * 2 + 0.5 }, { x: (i % 200) * 1.2 + 1, y: Math.floor(i / 200) * 2 + 1.5 }, { x: (i % 200) * 1.2 + 2, y: Math.floor(i / 200) * 2 + 0.5 }] },
}));
return { ...structuredClone(sampleProject), walls, drawings2d: drawings };
}
/** Kataster: 150 000 Zeichnungen (Linien und geschlossene Parzellen) auf ~4 × 4 km. */
function cadastre(): Project {
const level = sampleProject.drawingLevels[0].id;
const drawings: Drawing2D[] = [];
for (let i = 0; i < 150000; i++) {
const x = (i % 400) * 10;
const y = Math.floor(i / 400) * 10;
drawings.push({
id: `k${i}`,
type: "drawing2d",
levelId: level,
categoryCode: sampleProject.layers[0].code,
geom:
i % 3 === 0
? { shape: "line", a: { x, y }, b: { x: x + 10, y: y + 3 } }
: { shape: "polyline", closed: true, pts: [{ x, y }, { x: x + 9, y }, { x: x + 9, y: y + 8 }, { x, y: y + 9 }] },
});
}
return { ...structuredClone(sampleProject), walls: [], drawings2d: drawings };
}
function input(project: Project, raw: Vec2, lastPoint: Vec2 | null): SnapInput {
return {
raw,
project,
levelId: project.drawingLevels[0].id,
visibleCodes: CODES.get(project)!,
settings: { ...DEFAULT_SNAP, perpendicular: true, tangent: true },
draftPoints: lastPoint ? [lastPoint] : [],
lastPoint,
pxPerMeter: 40,
shift: false,
ctrl: false,
};
}
const CODES = new Map<Project, Set<string>>();
/** Mittelwert (µs) je Mausbewegung: kleinster aus `rounds` Läufen à `n` Positionen. */
function bench(project: Project, at: (k: number) => Vec2, n = 400, rounds = 3): { us: number; hits: number } {
let best = Infinity;
let hits = 0;
for (let r = 0; r < rounds; r++) {
hits = 0;
const t = performance.now();
for (let k = 0; k < n; k++) if (computeSnap(input(project, at(k), { x: 1, y: 1 }))) hits++;
best = Math.min(best, ((performance.now() - t) * 1000) / n);
}
return { us: best, hits };
}
function measure(name: string, project: Project, at: (k: number) => Vec2, out: string[]): void {
// Über den Store (wie in der App): das Dokument ist offen, Änderungen gehen als Ops hinein.
getState().loadProject(project);
const p = getState().project;
CODES.set(p, new Set(p.layers.map((l) => l.code)));
// Wie in der App: der Plan steht, bevor das erste Werkzeug fängt (typisierte Sicht im Kern gebaut).
generatePlan(p, p.drawingLevels[0].id, CODES.get(p)!).primitives.length;
const t0 = performance.now();
computeSnap(input(p, at(0), null));
const first = performance.now() - t0;
const { us, hits } = bench(p, at);
expect(hits).toBeGreaterThan(0);
// Nach einer Änderung (Griff ziehen: eine Wand bzw. eine Zeichnung je Schritt): erster Fang danach.
const step = (change: () => void): number => {
let sum = 0;
for (let k = 0; k < 5; k++) {
change();
const p2 = getState().project;
CODES.set(p2, CODES.get(p)!);
const t = performance.now();
computeSnap(input(p2, at(k), { x: 1, y: 1 }));
sum += performance.now() - t;
}
return sum / 5;
};
let k = 0;
const wallMs = p.walls.length
? step(() => {
const w = getState().project.walls[7];
getState().applyChange([replaceItem("walls", { ...w, end: { x: w.end.x + 0.01 * ++k, y: w.end.y } })]);
})
: NaN;
const drawMs = step(() => {
const d = getState().project.drawings2d[11];
getState().applyChange([replaceItem("drawings2d", { ...d, categoryCode: d.categoryCode })]);
});
out.push(`${name}: erster Fang ${first.toFixed(1)} ms, je Mausbewegung ${us.toFixed(0)} µs (${hits} Treffer), nach Wand-Änderung ${wallMs.toFixed(1)} ms, nach Zeichnungs-Änderung ${drawMs.toFixed(1)} ms`);
}
describe("Messung Objektfang je Mausbewegung", () => {
it("3000 Wände + 20 000 / 1500 Zeichnungen, Kataster 150 000", { timeout: 600000 }, () => {
const out: string[] = [];
const wave = (k: number): Vec2 => ({ x: (k * 7.31) % 230, y: ((k * 3.17) % 190) + 0.02 });
measure("3000 Wände + 20 000 Zeichnungen", wallsAndDrawings(20000), wave, out);
measure("3000 Wände + 1500 Zeichnungen", wallsAndDrawings(1500), wave, out);
measure("Kataster 150 000", cadastre(), (k) => ({ x: (k * 37.3) % 3990, y: ((k * 11.9) % 3700) + 0.05 }), out);
process.stderr.write(`Fang:\n ${out.join("\n ")}\n`);
});
});
+38 -33
View File
@@ -10,7 +10,7 @@
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { computeSnap, snapCommonAngle, wallLayerBoundarySegments } from "./snapping";
import { computeSnap, snapCommonAngle } from "./snapping";
import { DEFAULT_SNAP } from "./types";
import type { Ceiling, Column, Drawing2D, Project, Roof, Room, Stair, Vec2, Wall } from "../model/types";
@@ -70,43 +70,48 @@ function wall(id: string, start: Vec2, end: Vec2, referenceLine?: Wall["referenc
};
}
describe("wallLayerBoundarySegments", () => {
it("liefert layers.length+1 Grenzlinien mit kumulierten Offsets (referenceLine=center)", () => {
const w = wall("W1", { x: 0, y: 0 }, { x: 4, y: 0 });
const segs = wallLayerBoundarySegments(wallProject(w), w);
expect(segs).toHaveLength(4); // 3 Schichten → 4 Grenzlinien
// Achse horizontal → leftNormal = (0,1); Offset erscheint als y-Koordinate.
const offsets = segs.map(([a]) => a.y);
expect(offsets[0]).toBeCloseTo(-0.225, 9); // −T/2 (Aussenfläche)
expect(offsets[1]).toBeCloseTo(-0.125, 9); // −T/2 + 0.10
expect(offsets[2]).toBeCloseTo(0.025, 9); // −T/2 + 0.10 + 0.15
expect(offsets[3]).toBeCloseTo(0.225, 9); // +T/2 (Aussenfläche, innen)
// Jede Grenzlinie läuft parallel zur Achse über die volle Wandlänge.
for (const [a, b] of segs) {
expect(a.y).toBeCloseTo(b.y, 9);
expect(a.x).toBeCloseTo(0, 9);
expect(b.x).toBeCloseTo(4, 9);
}
/** Fang an `raw` auf dem Wand-Projekt (nur Objekt-Fang, kein Raster/Winkel). */
function snapWall(w: Wall, raw: Vec2) {
return computeSnap({
raw,
project: wallProject(w),
levelId: "eg",
visibleCodes: new Set(["20"]),
settings: { ...DEFAULT_SNAP, grid: false, commonAngles: false, ortho: false },
draftPoints: [],
lastPoint: null,
pxPerMeter: 100,
shift: false,
ctrl: false,
});
}
it("verschiebt die Offsets um wallReferenceOffset bei referenceLine=left/right", () => {
const wLeft = wall("W1", { x: 0, y: 0 }, { x: 4, y: 0 }, "left");
const offLeft = wallLayerBoundarySegments(wallProject(wLeft), wLeft).map(([a]) => a.y);
// refOff = +T/2 = 0.225 → Offsets laufen von 0 bis T (0.45).
expect(offLeft[0]).toBeCloseTo(0, 9);
expect(offLeft[3]).toBeCloseTo(0.45, 9);
describe("Wand-Schichtgrenzen als Fang-Strecken (Kern `snap_model.rs`)", () => {
// Achse horizontal → leftNormal = (0,1); die Grenzen liegen bei y = Offset, jede über die volle Länge.
const cases: [Wall["referenceLine"], number[]][] = [
["center", [-0.225, -0.125, 0.025, 0.225]], // −T/2, −T/2 + 0.10, … +T/2
["left", [0, 0.1, 0.25, 0.45]], // refOff = +T/2
["right", [-0.45, -0.35, -0.2, 0]], // refOff = −T/2
];
for (const [ref, offsets] of cases) {
it(`fängt die Endpunkte aller layers.length+1 Grenzlinien (referenceLine=${ref})`, () => {
const w = wall("W1", { x: 0, y: 0 }, { x: 4, y: 0 }, ref);
for (const o of offsets) {
for (const x of [0, 4]) {
const r = snapWall(w, { x: x + 0.004, y: o + 0.004 });
expect(r?.kind).toBe("endpoint");
expect(r!.point.x).toBeCloseTo(x, 9);
expect(r!.point.y).toBeCloseTo(o, 9);
}
}
});
}
const wRight = wall("W1", { x: 0, y: 0 }, { x: 4, y: 0 }, "right");
const offRight = wallLayerBoundarySegments(wallProject(wRight), wRight).map(([a]) => a.y);
// refOff = −T/2 = −0.225 → Offsets laufen von −0.45 bis 0.
expect(offRight[0]).toBeCloseTo(-0.45, 9);
expect(offRight[3]).toBeCloseTo(0, 9);
});
it("liefert eine leere Liste bei unbekanntem Wandtyp (kein Crash im Snap-Pfad)", () => {
it("unbekannter Wandtyp: nur die Achse, keine Grenzlinien (kein Crash im Snap-Pfad)", () => {
const w = wall("W1", { x: 0, y: 0 }, { x: 4, y: 0 });
w.wallTypeId = "unknown";
expect(wallLayerBoundarySegments(wallProject(w), w)).toEqual([]);
expect(snapWall(w, { x: 4.004, y: -0.13 })).toBeNull();
expect(snapWall(w, { x: 4.004, y: 0.004 })?.point).toEqual({ x: 4, y: 0 });
});
});
+59 -412
View File
@@ -6,22 +6,15 @@
// Prioritäts-Reihenfolge (Vorrang bei nahem Abstand): endpoint > intersection >
// midpoint > onEdge > grid; ortho/Winkelraster ist eine Projektion (überlagert).
import type { Drawing2D, Project, Vec2, Wall } from "../model/types";
import { getWallType, wallTypeThickness } from "../model/types";
import { add, leftNormal, normalize, scale, sub } from "../model/geometry";
import { wallReferenceOffset } from "../model/wall";
import { centroid as roomCentroid } from "../core";
import { columnFootprint } from "../core";
import { stairOutline } from "../core";
import type { Project, Vec2 } from "../model/types";
import type { SnapKind, SnapResult, SnapSettings } from "./types";
import { sampleBezierChain, sampleCatmullRom, sampleUniformBSpline } from "../core";
import { buildDrawingIndex, drawingsNear, isIndexable, pointSegDist__geometry_drawingIndex as pointSegDist, type DrawingIndex } from "../core";
import { pointSegDist__geometry_drawingIndex as pointSegDist } from "../core";
import { sheetSnapSegments } from "./sheetSnapGeometry";
import { holdSnapSegments, releaseSnapSegments, snapOnSegments, type SegSnapCand } from "../core";
import { holdModelSnap, queryModelSnap, type ModelSnapCand } from "../core";
const dist = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y);
/** Bildschirm-px-Bonus je Snap-Art: höher = gewinnt knappe Vergleiche. */
/** Bildschirm-px-Bonus je Snap-Art: höher = gewinnt knappe Vergleiche (Kern: `snap.rs::priority`). */
const PRIORITY: Record<SnapKind, number> = {
endpoint: 7,
intersection: 5,
@@ -52,154 +45,9 @@ export interface SnapInput {
ctrl: boolean;
}
/** Eine Strecke als Snap-Quelle (Wandachse oder 2D-Segment). */
/** Eine Strecke als Snap-Quelle (Entwurf, Blatt-Geometrie, Verweil-Referenz). */
type Seg = [Vec2, Vec2];
/**
* Schichttrennlinien einer Wand: für jede kumulierte Schichtgrenze (inkl.
* beider Aussenflächen) eine zur Achse parallele Strecke, um den Betrag
* entlang `leftNormal(u)` verschoben. Spiegelt EXAKT die Offset-Berechnung aus
* `generatePlan.ts` (`addWallPoche`): Start bei `refOff − total/2`
* (`wallReferenceOffset`), danach je Schicht `+= layer.thickness` aufsummiert.
* Liefert `layers.length + 1` Segmente (leer bei unbekanntem Wandtyp).
*/
export function wallLayerBoundarySegments(project: Project, wall: Wall): Seg[] {
let wt;
try {
wt = getWallType(project, wall);
} catch {
return [];
}
const total = wallTypeThickness(wt);
const refOff = wallReferenceOffset(wall, total);
const u = normalize(sub(wall.end, wall.start));
const n = leftNormal(u);
const out: Seg[] = [];
let off = refOff - total / 2;
const boundary = (o: number): Seg => [
add(wall.start, scale(n, o)),
add(wall.end, scale(n, o)),
];
out.push(boundary(off)); // äussere Fläche
for (const layer of wt.layers) {
off += layer.thickness;
out.push(boundary(off)); // Schichtfuge (letzte = innere Fläche)
}
return out;
}
/** Kanten eines geschlossenen Polygons (Schlusspunkt nicht dupliziert). */
function closedPolySegs(pts: Vec2[]): Seg[] {
const segs: Seg[] = [];
for (let i = 0; i < pts.length - 1; i++) segs.push([pts[i], pts[i + 1]]);
if (pts.length > 2) segs.push([pts[pts.length - 1], pts[0]]);
return segs;
}
/** Strecken EINER Zeichnung (Fangkandidaten), je nach Form. */
function drawingSegs(d: Drawing2D, segs: Seg[]): void {
const g = d.geom;
if (g.shape === "line") segs.push([g.a, g.b]);
else if (g.shape === "xline") {
// Weit verlängert (wie beim Rendern) — Lot-/Nächster-Punkt-Snap soll
// entlang der ganzen (optisch unendlichen) Linie greifen, nicht nur
// zwischen den beiden gesetzten Punkten.
const dx = g.b.x - g.a.x, dy = g.b.y - g.a.y;
const len = Math.hypot(dx, dy);
if (len > 1e-6) {
const ux = dx / len, uy = dy / len, ext = 1000;
segs.push([
{ x: g.a.x - ux * ext, y: g.a.y - uy * ext },
{ x: g.b.x + ux * ext, y: g.b.y + uy * ext },
]);
}
}
else if (g.shape === "ray") {
// Wie xline, aber NUR über `b` hinaus verlängert (Anker `a` bleibt fest).
const dx = g.b.x - g.a.x, dy = g.b.y - g.a.y;
const len = Math.hypot(dx, dy);
if (len > 1e-6) {
const ux = dx / len, uy = dy / len, ext = 1000;
segs.push([g.a, { x: g.b.x + ux * ext, y: g.b.y + uy * ext }]);
}
}
else if (g.shape === "polyline") {
for (let i = 0; i < g.pts.length - 1; i++) segs.push([g.pts[i], g.pts[i + 1]]);
if (g.closed && g.pts.length > 2) segs.push([g.pts[g.pts.length - 1], g.pts[0]]);
} else if (g.shape === "rect") {
const c1 = g.min, c3 = g.max;
const c2 = { x: g.max.x, y: g.min.y }, c4 = { x: g.min.x, y: g.max.y };
segs.push([c1, c2], [c2, c3], [c3, c4], [c4, c1]);
} else if (g.shape === "bezier") {
const pts = sampleBezierChain(g.pts);
for (let i = 0; i < pts.length - 1; i++) segs.push([pts[i], pts[i + 1]]);
} else if (g.shape === "spline") {
const closed = g.closed && g.pts.length > 2;
const pts = g.mode === "control" ? sampleUniformBSpline(g.pts, closed) : sampleCatmullRom(g.pts, closed);
for (let i = 0; i < pts.length - 1; i++) segs.push([pts[i], pts[i + 1]]);
if (closed) segs.push([pts[pts.length - 1], pts[0]]);
}
}
/** Kreise/Bögen/Ellipsen & Co.: bei grossen Projekten ohne die vielen Linien. */
function nonLineDrawings(all: readonly Drawing2D[]): readonly Drawing2D[] {
return all.length > LARGE_DRAWINGS ? getSnapIndex(all).others : all;
}
/** Ab so vielen Zeichnungen: nur Strecken in Cursornähe (Raster-Index) statt aller. */
const LARGE_DRAWINGS = 2000;
interface SnapDrawingIndex {
/** Linien/Polylinien (Massenfall), räumlich indiziert. */
index: DrawingIndex | null;
/** Alle übrigen Formen (Kreis, Bogen, Rechteck, Spline, …) — wenige, immer geprüft. */
others: Drawing2D[];
}
const snapIndexCache = new WeakMap<readonly Drawing2D[], SnapDrawingIndex>();
/** Index je `drawings2d`-Array-Identität (Projekt-Updates teilen unveränderte Arrays). */
function getSnapIndex(drawings: readonly Drawing2D[]): SnapDrawingIndex {
let c = snapIndexCache.get(drawings);
if (!c) {
const indexable: Drawing2D[] = [];
const others: Drawing2D[] = [];
for (const d of drawings) (isIndexable(d) ? indexable : others).push(d);
c = { index: buildDrawingIndex(indexable), others };
snapIndexCache.set(drawings, c);
}
return c;
}
/**
* Zeichnungen des Geschosses, die für den Fang in Frage kommen: bei grossen
* Projekten (Kataster-Import, ~10^5 Zeichnungen) nur die in `r` Umkreis von `at`
* (+ alle Nicht-Linien-Formen), sonst alle.
*/
function snapDrawings(input: SnapInput, near?: { at: Vec2; r: number }): Drawing2D[] {
const all = input.project.drawings2d;
const ok = (d: Drawing2D) => d.levelId === input.levelId && input.visibleCodes.has(d.categoryCode);
const out: Drawing2D[] = [];
if (near && all.length > LARGE_DRAWINGS) {
const c = getSnapIndex(all);
if (c.index) {
for (const i of drawingsNear(c.index, near.at, near.r)) {
const d = c.index.drawings[i];
if (ok(d)) out.push(d);
}
}
for (const d of c.others) if (ok(d)) out.push(d);
return out;
}
for (const d of all) if (ok(d)) out.push(d);
return out;
}
/** Sammelt alle sichtbaren Strecken des Geschosses (Wandachsen + 2D-Segmente) samt Entwurf. */
function collectSegments(input: SnapInput, near?: { at: Vec2; r: number }): Seg[] {
const segs = baseSegments(input, near);
for (const seg of draftSegments(input)) segs.push(seg);
return segs;
}
/** Bereits gesetzte Draft-Segmente (Polylinie/Wand im Bau). */
function draftSegments(input: SnapInput): Seg[] {
const segs: Seg[] = [];
@@ -210,155 +58,29 @@ function draftSegments(input: SnapInput): Seg[] {
}
/**
* Was je Projekt/Geschoss/Sichtbarkeit gleich bleibt, einmal gesammelt (lief sonst bei jeder
* Mausbewegung über alle Wände, Räume, Treppen, Stützen): die Strecken ohne Entwurf (im Kern
* abgelegt, erst bei Bedarf), Raum-Stempel-Anker, Kreise/Bögen, Ellipsen-Mittelpunkte. Die
* letzten paar Einträge bleiben, ältere werden freigegeben.
* Nummer der im Kern gesammelten Fang-Kandidaten je Projekt/Geschoss/Sichtbarkeit (`modelSnap.ts`):
* ohne Kern-Aufruf, solange dasselbe Projekt-Objekt gefragt wird; nach einer Änderung liefert der
* Kern dieselbe Nummer, wenn die betroffenen Felder gleich geblieben sind.
*/
interface LevelSnap {
interface LevelHold {
project: Project;
levelId: string;
codes: Set<string>;
/** Abgelegte Strecken im Kern (0 = noch nicht). */
hold: number;
anchors: Vec2[] | null;
circles: CircleGeom[] | null;
ellipses: Vec2[] | null;
held: number;
}
const levelSnaps: LevelSnap[] = [];
const MAX_LEVEL_SNAPS = 4;
function levelSnap(input: SnapInput): LevelSnap {
let e = levelSnaps.find((h) => h.project === input.project && h.levelId === input.levelId && h.codes === input.visibleCodes);
const levelHolds: LevelHold[] = [];
const MAX_LEVEL_HOLDS = 4;
function levelHold(input: SnapInput, fresh: boolean): number {
let e = levelHolds.find((h) => h.project === input.project && h.levelId === input.levelId && h.codes === input.visibleCodes);
if (e && !fresh) return e.held;
const held = holdModelSnap(input.project, input.levelId, input.visibleCodes);
if (!e) {
e = { project: input.project, levelId: input.levelId, codes: input.visibleCodes, hold: 0, anchors: null, circles: null, ellipses: null };
levelSnaps.push(e);
while (levelSnaps.length > MAX_LEVEL_SNAPS) releaseSnapSegments(levelSnaps.shift()!.hold);
e = { project: input.project, levelId: input.levelId, codes: input.visibleCodes, held };
levelHolds.push(e);
if (levelHolds.length > MAX_LEVEL_HOLDS) levelHolds.shift();
}
return e;
}
function heldBaseSegments(input: SnapInput, fresh: boolean): number {
const e = levelSnap(input);
if (e.hold && !fresh) return e.hold;
releaseSnapSegments(e.hold);
e.hold = holdSnapSegments(baseSegments(input));
return e.hold;
}
/** Raum-Stempel-Anker (fixer Anker, sonst Flächenschwerpunkt) des Geschosses. */
function roomAnchors(input: SnapInput): Vec2[] {
const e = levelSnap(input);
if (!e.anchors) {
e.anchors = [];
for (const room of input.project.rooms ?? []) {
if (room.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(room.categoryCode)) continue;
if (room.boundary.length < 3) continue;
e.anchors.push(room.stampAnchor ?? roomCentroid(room.boundary));
}
}
return e.anchors;
}
function levelCircles(input: SnapInput): CircleGeom[] {
const e = levelSnap(input);
return (e.circles ??= collectCircles(input));
}
function ellipseCenters(input: SnapInput): Vec2[] {
const e = levelSnap(input);
if (!e.ellipses) {
e.ellipses = [];
for (const d of nonLineDrawings(input.project.drawings2d)) {
if (d.levelId !== input.levelId) continue;
if (!input.visibleCodes.has(d.categoryCode)) continue;
if (d.geom.shape === "ellipse") e.ellipses.push(d.geom.center);
}
}
return e.ellipses;
}
/** Sichtbare Strecken des Geschosses ohne Entwurf (Wandachsen, Schichtgrenzen, Umrisse, 2D). */
function baseSegments(input: SnapInput, near?: { at: Vec2; r: number }): Seg[] {
const segs: Seg[] = [];
for (const w of input.project.walls) {
if (w.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(w.categoryCode)) continue;
segs.push([w.start, w.end]);
for (const seg of wallLayerBoundarySegments(input.project, w)) segs.push(seg);
}
// Raum-/Decken-/Dach-/Treppen-/Stützen-Umrisse: bisher komplett blind (nur
// der Raum-Stempel-Anker war als Endpunkt fangbar, s. u.) — eine Wand oder
// Bemassung liess sich nicht bündig an eine Raum-/Dachkante setzen.
for (const room of input.project.rooms ?? []) {
if (room.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(room.categoryCode)) continue;
segs.push(...closedPolySegs(room.boundary));
}
for (const c of input.project.ceilings ?? []) {
if (c.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(c.categoryCode)) continue;
segs.push(...closedPolySegs(c.outline));
for (const hole of c.openings ?? []) segs.push(...closedPolySegs(hole));
}
for (const r of input.project.roofs ?? []) {
if (r.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(r.categoryCode)) continue;
segs.push(...closedPolySegs(r.outline));
}
for (const s of input.project.stairs ?? []) {
if (s.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(s.categoryCode)) continue;
const { polygon, spiral } = stairOutline(s, 0);
if (polygon) segs.push(...closedPolySegs(polygon));
else if (spiral) for (const line of spiral.lines) segs.push(line); // Innen-/Aussenbögen s. collectCircles
}
for (const col of input.project.columns ?? []) {
if (col.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(col.categoryCode)) continue;
if (col.profile.kind === "rect") segs.push(...closedPolySegs(columnFootprint(col)));
// Runde Stützen: s. collectCircles (Zentrum/Quadranten statt Vieleck-Kanten).
}
for (const d of snapDrawings(input, near)) drawingSegs(d, segs);
return segs;
}
/** Kreis-/Bogen-Geometrie für Center-/Quadrant-/Endpunkt-Snaps. `arc=null` =
* Vollkreis (keine Endpunkte, alle vier Quadranten). */
interface CircleGeom {
center: Vec2;
r: number;
arc: { a0: number; a1: number } | null;
}
/**
* Sammelt sichtbare Kreise/Bögen des aktiven Geschosses: `drawings2d`
* (circle/arc), runde Stützen (Zentrum/Quadranten statt Vieleck-Näherung)
* und die Innen-/Aussenbögen von Wendeltreppen (s. `stairOutline`).
*/
function collectCircles(input: SnapInput): CircleGeom[] {
const out: CircleGeom[] = [];
for (const d of nonLineDrawings(input.project.drawings2d)) {
if (d.levelId !== input.levelId) continue;
if (!input.visibleCodes.has(d.categoryCode)) continue;
const g = d.geom;
if (g.shape === "circle") out.push({ center: g.center, r: g.r, arc: null });
else if (g.shape === "arc")
out.push({ center: g.center, r: g.r, arc: { a0: g.a0, a1: g.a1 } });
}
for (const col of input.project.columns ?? []) {
if (col.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(col.categoryCode)) continue;
if (col.profile.kind === "round") {
out.push({ center: col.position, r: col.profile.radius, arc: null });
}
}
for (const s of input.project.stairs ?? []) {
if (s.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(s.categoryCode)) continue;
const { spiral } = stairOutline(s, 0);
if (!spiral) continue;
for (const a of spiral.arcs) {
out.push({ center: { x: a.cx, y: a.cy }, r: a.r, arc: { a0: a.a0, a1: a.a1 } });
}
}
return out;
e.held = held;
return held;
}
// ── Verweil-Erkennung fürs Teilpunkte-Snapping ("divide") ───────────────────
@@ -441,79 +163,56 @@ export function computeSnap(input: SnapInput): SnapResult | null {
settings.endpoint ||
settings.perpendicular ||
settings.parallel;
// Bei grossen Projekten (Kataster-Import: ~10^5 Zeichnungen, Mio. Strecken) NUR
// die Strecken in Cursornähe — vorher wurde bei JEDER Mausbewegung die ganze
// Liste gebaut und der Schnittpunkt-Fang prüfte ALLE Paare (O(N²): die Seite
// blockierte beim ersten Klick eines Zeichenwerkzeugs). Kleine Projekte bleiben
// exakt wie bisher.
// Strecken-Fang (Lot, Endpunkte, Mitte, Schnitt, Kante, nächste Strecke) rechnet der Kern
// (`geometry/snapSegments.ts`): bei normalen Projekten über die dort abgelegten Strecken des
// Geschosses (`held`) plus Entwurf, sonst über die hier vorausgewählten nahen Strecken.
const nearMode = input.project.drawings2d.length > LARGE_DRAWINGS;
const intRadius = tolM * 6;
let held = 0;
let segs: Seg[] = [];
let intSegs: Seg[] | null = null;
// Abgeleitete Blatt-Geometrie (Schnitt/Ansicht, s. sheetSnapGeometry.ts): nur die Strecken in
// Cursornähe — eine Ansicht hat schnell Tausende Kanten, der paarweise Schnittpunkt-Fang bliebe
// sonst nicht flüssig.
let sheetNear: Seg[] = [];
if (needSegs) {
if (nearMode) {
const cand = collectSegments(input, { at: raw, r: intRadius });
const withDist = cand
.map((seg) => ({ seg, d: pointSegDist(raw, seg[0], seg[1]) }))
.filter((e) => e.d <= intRadius)
.sort((x, y) => x.d - y.d);
segs = withDist.filter((e) => e.d <= tolM).map((e) => e.seg);
// Schnittpunkte nur unter den nächsten Strecken (paarweise → quadratisch).
intSegs = withDist.slice(0, 64).map((e) => e.seg);
} else {
held = heldBaseSegments(input, false);
segs = draftSegments(input);
}
// Abgeleitete Blatt-Geometrie (Schnitt/Ansicht, s. sheetSnapGeometry.ts):
// nur die Strecken in Cursornähe — eine Ansicht hat schnell Tausende Kanten,
// der paarweise Schnittpunkt-Fang bliebe sonst nicht flüssig.
const sheet = sheetSnapSegments(input.levelId);
if (sheet.length > 0) {
const near = sheet
const intRadius = tolM * 6;
sheetNear = sheet
.map((seg) => ({ seg, d: pointSegDist(raw, seg[0], seg[1]) }))
.filter((e) => e.d <= intRadius)
.sort((x, y) => x.d - y.d)
.slice(0, 64)
.map((e) => e.seg);
if (near.length > 0) {
segs = segs.concat(near);
if (intSegs) intSegs = intSegs.concat(near);
}
}
}
let segSnap: ReturnType<typeof snapOnSegments> = null;
if (needSegs) {
const q = {
raw,
tolM,
pxPerMeter,
perpendicular: settings.perpendicular,
endpoint: settings.endpoint,
midpoint: settings.midpoint,
intersection: settings.intersection,
onEdge: settings.onEdge,
lastPoint: settings.perpendicular ? input.lastPoint : null,
};
segSnap = snapOnSegments(held, segs, intSegs, q);
// Abgelegte Strecken verdrängt/freigegeben: neu ablegen und nochmals.
if (!segSnap && held) segSnap = snapOnSegments(heldBaseSegments(input, true), segs, intSegs, q);
}
// Modell-Fang im Kern (`modelSnap.ts`): Strecken (Lot, Endpunkte, Mitte, Schnitt, Kante, nächste
// Strecke), Raum-Anker, Kreise/Bögen/Ellipsen; bei grossen Projekten (> 2000 Zeichnungen) nur die
// Strecken in Cursornähe.
const q = {
raw,
tolM,
pxPerMeter,
segs: needSegs,
perpendicular: settings.perpendicular,
endpoint: settings.endpoint,
midpoint: settings.midpoint,
intersection: settings.intersection,
onEdge: settings.onEdge,
center: settings.center,
tangent: settings.tangent,
lastPoint: input.lastPoint,
};
const draft = needSegs ? draftSegments(input) : [];
let m = queryModelSnap(levelHold(input, false), draft, sheetNear, q);
// Abgelegte Kandidaten verdrängt: neu ablegen und nochmals.
if (!m) m = queryModelSnap(levelHold(input, true), draft, sheetNear, q);
// Kern-Kandidat übernehmen, wenn er besser ist (gleiche Regel wie `consider`).
const offer = (c: SegSnapCand | null | undefined) => {
const offer = (c: ModelSnapCand | null | undefined) => {
if (c && c.score < bestScore) {
bestScore = c.score;
best = { point: c.point, kind: c.kind, distPx: c.distPx, refA: c.kind === "perpendicular" ? input.lastPoint ?? undefined : undefined };
const ref = c.kind === "perpendicular" || c.kind === "tangent" ? input.lastPoint ?? undefined : undefined;
best = { point: c.point, kind: c.kind, distPx: c.distPx, refA: ref };
}
};
// Teilpunkt-Verweilerkennung: braucht dieselben Strecken wie oben. Ohne sie
// (alle Objekt-Snap-Arten aus) bleiben "divide"/"parallel" ebenfalls inaktiv
// — konsistent dazu, dass dann ohnehin keine Linien-bezogenen Snaps gelten.
const revealed = updateDwell(segSnap?.nearest ?? null, settings.hoverDivideDelayMs);
const revealed = updateDwell(m?.nearest ?? null, settings.hoverDivideDelayMs);
if (revealed) {
const [a, b] = revealed;
const n = Math.max(2, Math.round(settings.hoverDivideCount));
@@ -555,72 +254,20 @@ export function computeSnap(input: SnapInput): SnapResult | null {
// perpendicular: Lotfusspunkt VOM LETZTEN PUNKT (nicht vom Cursor wie
// "onEdge") auf nahe Strecken — die Strecke lastPoint→Fangpunkt steht im
// rechten Winkel zur Referenz-Strecke; dann die Strecken-Endpunkte (Kern, Block A).
offer(segSnap?.a);
offer(m?.a);
// endpoint (Draft-Knoten + Raum-Stempel-Anker).
// endpoint: Draft-Knoten, dann Raum-Stempel-Anker (Kern).
if (settings.endpoint) {
for (const p of input.draftPoints) consider(p, "endpoint");
// Raum-Stempel-Anker (fixer Anker, sonst Flächenschwerpunkt) des Geschosses.
for (const p of roomAnchors(input)) consider(p, "endpoint");
offer(m?.anchors);
}
// midpoint, intersection (paarweise Geraden-Schnitt der Strecken, nahe am Cursor), onEdge
// (Lotfußpunkt auf nahe Strecken; niedrige Priorität) — Kern, Block B.
offer(segSnap?.b);
offer(m?.b);
// Kreis-/Bogen-Snaps: Mittelpunkt + Quadranten (Ost/Nord/West/Süd); bei Bögen
// nur die Quadranten IM Bogen-Bereich, plus die beiden Bogen-Endpunkte. Center/
// Quadrant hängen an der `center`-Einstellung, die Endpunkte an `endpoint`,
// die Tangentenpunkte an `tangent` (+ zwingend `lastPoint`).
if (settings.center || settings.endpoint || settings.tangent) {
const TAU = Math.PI * 2;
const norm = (x: number) => ((x % TAU) + TAU) % TAU;
const onCircle = (c: CircleGeom, ang: number): Vec2 => ({
x: c.center.x + c.r * Math.cos(ang),
y: c.center.y + c.r * Math.sin(ang),
});
const inArc = (c: CircleGeom, ang: number): boolean => {
if (!c.arc) return true;
const sweep = norm(c.arc.a1 - c.arc.a0) || TAU;
return norm(ang - c.arc.a0) <= sweep + 1e-9;
};
for (const c of levelCircles(input)) {
if (settings.center) {
consider(c.center, "center");
// Volle CCW-Spanne (0 ⇒ Vollkreis); Quadrant nur, wenn im Bogen liegt.
for (let q = 0; q < 4; q++) {
const ang = q * (Math.PI / 2);
if (inArc(c, ang)) consider(onCircle(c, ang), "quadrant");
}
}
if (settings.endpoint && c.arc) {
consider(onCircle(c, c.arc.a0), "endpoint");
consider(onCircle(c, c.arc.a1), "endpoint");
}
// Tangente von aussen (lastPoint) an den Kreis: klassische Konstruktion
// — zwei Lösungen, Dreieck center/lastPoint/Tangentenpunkt ist bei T
// rechtwinklig, daher angAtC = acos(r/d) der Winkel zwischen center→
// lastPoint und center→T. Innerhalb/auf dem Kreis (d ≤ r) gibt es keine
// Tangente von aussen.
if (settings.tangent && input.lastPoint) {
const dx = input.lastPoint.x - c.center.x;
const dy = input.lastPoint.y - c.center.y;
const d = Math.hypot(dx, dy);
if (d > c.r + 1e-9) {
const thetaCP = Math.atan2(dy, dx);
const angAtC = Math.acos(Math.min(1, c.r / d));
for (const sign of [1, -1]) {
const ang = thetaCP + sign * angAtC;
if (inArc(c, ang)) consider(onCircle(c, ang), "tangent", input.lastPoint);
}
}
}
}
// Ellipse: nur der Mittelpunkt (keine Quadranten — bei gedrehter Ellipse
// wären die "Achsenpunkte" ohnehin keine Kreis-Quadranten mehr).
if (settings.center) {
for (const p of ellipseCenters(input)) consider(p, "center");
}
}
// Kreis-/Bogen-Snaps (Kern): Mittelpunkt + Quadranten (nur im Bogen-Bereich), Bogen-Endpunkte,
// Tangentenpunkte vom letzten Punkt; Ellipsen nur Mittelpunkt.
offer(m?.c);
if (best) return best;