[128] Merge: Griff-Zugrechnung im Kern (grip_drag.rs)

This commit is contained in:
Claude committed 2026-11-05 01:40:42 +00:00
commit 48e7bc48f9
10 files changed
+949 -304

No files matched your search

+12
View File
@@ -1178,6 +1178,18 @@ Prüfung des ganzen Programms (Rust-Kern, TS-Hülle, Build/Sicherheit), nur Code
Bäume, Löschen, Nachfahren, Ordner-PDF, Titelblock) lag schon im Kern ([K4] S3); der Rest sind Fabriken und
Listen-`map`/`filter` ohne Logik — bewusst in TS gelassen. **Offen: Griffe** (`useGripEditing.ts`, anderer Agent).
Geprüft: cargo test (Kern), vitest; nicht in der Tauri-App.
5.11. Griffe, Teil 1: die Zug-Rechnung je Mausschritt liegt im Kern (`grip_drag.rs`, Bindungen `web/grip_drag.rs`,
Fassade `geometry/gripDrag.ts`): Länge/Winkel-Felder und Punkt aus Locks, Shift-Achsen-Lock (Welt-H/V + Flucht
der Nachbarkanten, Polygon-Nachbarn), Kanten-Ziel (geführt: Normale, Geometrie-Snap vor Raster; frei: Ortho/
Raster; gelockt), Höhen-Griffe im Schnitt (Mindestmasse, cm-Raster, mm-Rundung), Öffnung entlang der Wand
(Griff-Lage, Klemmen, im Schnitt mit u-Faktor), Bewegpunkt Treppe, Bogenwand-Scheitel, Baugruben-Griffe,
koinzidente Ecken beim Körper-Verschieben. TS-Fassungen gelöscht. `useGripEditing.ts` 1598 → 1395 Zeilen.
**Offen (bewusst TS):** Zusammenstellen der Griff-/Kanten-Listen je Auswahl (`gripOwners`, Bereiche; braucht
`drawingVertices` mit der Schrift-Metrik der Hülle für Textspalten), Höhen-Griff-Lagen aus `sheetOwnerOutlines`
(Hülle), Vorschau-Formen und das Aufschieben/Anwenden der Züge (Refs, `applyEdgeToward` additiv) — das ist
React-/Zustands-Leim. Möglicher nächster Schritt: Griff-Listen als Dokument-Abfrage (Text-Ecken als Eingabe).
Geprüft: cargo test (Kern), tsc, vitest, e2e (Griffe: aiBridge, dimAssoc, grid, kataster, layoutSheet, editing,
roof, renderCount); Golden unverändert; nicht in der Tauri-App.
- ✅ **[129] Grenze schärfen.** (3.11.) `i18n/translate.ts` (React-frei: `t`, Sprache, Wörterbücher), `i18n/index.ts` re-exportiert
und hält nur `useT`; Kern-Dateien importieren `i18n/translate`. `net/` in `CORE_DIRS`, neuer Test prüft transitive
relative Importe (Ausnahmelisten leer). · S
+441
View File
@@ -0,0 +1,441 @@
//! Griff-Ziehen ([128]): die reine Rechnung je Mausschritt eines 2D-Griff-Zugs (vorher in
//! `src/state/useGripEditing.ts`). Die Hülle hält nur Zustand (Locks, ausstehende Züge, Vorschau) und
//! fragt hier, wohin ein Griff fällt:
//!
//! - Länge/Winkel-Eingabe (Tab-Felder): Punkt aus Anker + gelockten Werten ([`polar_point`]), Anzeige-
//! Werte ([`polar`]);
//! - Shift-Achsen-Lock eines Eckpunkts: Welt-H/V am Nachbar-Griff plus die Flucht der beiden fixen
//! Nachbarkanten ([`axis_lock`]);
//! - Kanten-Griff: geführte Kante (nur entlang der Aussennormale, Raster/Geometrie-Snap) bzw. freie Kante
//! (Ortho, Raster), mit oder ohne gelockte Felder ([`edge_target`]);
//! - Höhen-Griffe im Schnitt (Wand-Oberkante, Fenster Ober-/Unterkante, [`sheet_height`]);
//! - Öffnung entlang der Wirtswand ([`opening_slide`], [`opening_slide_sheet`]), Griff-Lagen von
//! Öffnung, Treppe, Bogenwand und Baugrube;
//! - koinzidente Ecken anderer gewählter Elemente beim Körper-Verschieben ([`coincident`]).
//!
//! Zahlen wie in JS (`jsnum`: min/max/round, Trigonometrie über libm); NaN steht für „fehlt".
use crate::jsmath::hypot2;
use crate::jsnum;
use std::f64::consts::PI;
pub type P = (f64, f64);
fn sub(a: P, b: P) -> P {
(a.0 - b.0, a.1 - b.1)
}
fn add(a: P, b: P) -> P {
(a.0 + b.0, a.1 + b.1)
}
fn scale(a: P, s: f64) -> P {
(a.0 * s, a.1 * s)
}
fn dot(a: P, b: P) -> f64 {
a.0 * b.0 + a.1 * b.1
}
/// `normalize` aus `model/geometry.ts`: Nullvektor bleibt null (Länge 0 → 1).
fn normalize(a: P) -> P {
let l = hypot2(a.0, a.1);
let l = if l == 0.0 || l.is_nan() { 1.0 } else { l };
(a.0 / l, a.1 / l)
}
/// Winkel in Grad (−180, 180] wie `Math.atan2(dy, dx) * 180 / Math.PI`.
fn deg(dx: f64, dy: f64) -> f64 {
(jsnum::atan2(dy, dx) * 180.0) / PI
}
/// Länge, Winkel (Grad, [0, 360)) und Abstand entlang `normal` von `anchor` nach `p` (Felder, Cursor-HUD).
pub fn polar(anchor: P, p: P, normal: P) -> (f64, f64, f64) {
let (dx, dy) = sub(p, anchor);
let ang = ((deg(dx, dy) % 360.0) + 360.0) % 360.0;
(hypot2(dx, dy), ang, dx * normal.0 + dy * normal.1)
}
/// Punkt aus Anker + Länge/Winkel (Grad); ungelockte Werte (`None`) folgen dem rohen Cursor `raw`.
pub fn polar_point(anchor: P, length: Option<f64>, angle: Option<f64>, raw: P) -> P {
let (dx, dy) = sub(raw, anchor);
let length = length.unwrap_or_else(|| hypot2(dx, dy));
let a = angle.unwrap_or_else(|| deg(dx, dy)) * (PI / 180.0);
(anchor.0 + jsnum::cos(a) * length, anchor.1 + jsnum::sin(a) * length)
}
/// Die fixen Polygon-Nachbarn des Punkts `i` eines Rings (`closed`) bzw. einer Kette: (vorher, nachher).
pub fn ring_neighbors(n: usize, i: usize, closed: bool) -> (Option<usize>, Option<usize>) {
let prev = if i > 0 { Some(i - 1) } else if closed && n > 0 { Some(n - 1) } else { None };
let next = if i + 1 < n { Some(i + 1) } else if closed { Some(0) } else { None };
let prev = prev.filter(|&p| p != i);
let next = next.filter(|&q| q != i && Some(q) != prev);
(prev, next)
}
/// `raw` auf die nächstliegende Achse (Stützpunkt, Richtung) projizieren; entartete Richtungen zählen nicht.
fn closest_axis_point(raw: P, candidates: &[(P, P)]) -> Option<P> {
let mut best = None;
let mut best_dist = f64::INFINITY;
for &(point, dir) in candidates {
let len = hypot2(dir.0, dir.1);
if len < 1e-9 {
continue;
}
let u = (dir.0 / len, dir.1 / len);
let rel = sub(raw, point);
let t = rel.0 * u.0 + rel.1 * u.1;
let proj = add(point, scale(u, t));
let dist = hypot2(raw.0 - proj.0, raw.1 - proj.1);
if dist < best_dist {
best_dist = dist;
best = Some(proj);
}
}
best
}
/// Shift-Achsen-Lock eines gezogenen Punkt-Griffs: Welt-H/V durch den Nachbar-Griff `anchor` und — bei einem
/// Vielecks-Eckpunkt (`ring` = Punkte des Elements, `index` = gezogener Punkt, `origin` = Lage vor dem Zug) —
/// die Flucht der beiden fixen Nachbarkanten in ihrer ursprünglichen Richtung. Die nächstliegende Achse gewinnt.
pub fn axis_lock(raw: P, anchor: P, origin: Option<P>, ring: &[P], index: usize, closed: bool) -> P {
let mut c = vec![(anchor, (1.0, 0.0)), (anchor, (0.0, 1.0))];
if let Some(o) = origin {
if index < ring.len() {
let (prev, next) = ring_neighbors(ring.len(), index, closed);
if let Some(p) = prev.map(|k| ring[k]) {
c.push((p, sub(o, p)));
}
if let Some(q) = next.map(|k| ring[k]) {
c.push((q, sub(q, o)));
}
}
}
// H/V sind nie entartet: es gibt immer einen Treffer.
closest_axis_point(raw, &c).unwrap_or(raw)
}
/// Kanten-Griff (Mitte `mid` beim Grab, Aussennormale `normal`; `free` = offene Kette).
#[derive(Clone, Copy, Debug)]
pub struct Edge {
pub mid: P,
pub normal: P,
pub free: bool,
}
/// Wie die Maus/Tastatur einen Kanten-Griff führt.
#[derive(Clone, Copy, Debug, Default)]
pub struct EdgeDrive {
/// Feld-Controller offen: Ziel aus Anker + Locks (fehlende Werte folgen dem Cursor), ohne Raster/Ortho.
pub locked: bool,
pub length: Option<f64>,
pub angle: Option<f64>,
pub shift: bool,
/// Rasterweite (0 = kein Raster).
pub grid: f64,
/// Gefangener Geometrie-Snap (nur geführte Kanten).
pub snapped: Option<P>,
}
/// Zielpunkt eines Kanten-Zugs relativ zum Anker `edge.mid`. Geführt: nur die Komponente entlang der
/// Normale (Geometrie-Snap vor Raster); frei: voller Cursor, Shift = Ortho zum Anker, Raster auf das Delta.
pub fn edge_target(edge: Edge, raw: P, d: EdgeDrive) -> P {
let anchor = edge.mid;
if d.locked {
if edge.free {
return polar_point(anchor, d.length, d.angle, raw);
}
let len = d.length.unwrap_or_else(|| dot(sub(raw, anchor), edge.normal));
return add(anchor, scale(edge.normal, len));
}
let gs = d.grid;
if edge.free {
let mut pt = raw;
if d.shift {
let (dx, dy) = sub(raw, anchor);
pt = if dx.abs() >= dy.abs() { (raw.0, anchor.1) } else { (anchor.0, raw.1) };
}
if gs > 0.0 {
let dx = jsnum::round((pt.0 - anchor.0) / gs) * gs;
let dy = jsnum::round((pt.1 - anchor.1) / gs) * gs;
pt = (anchor.0 + dx, anchor.1 + dy);
}
return pt;
}
let cursor = d.snapped.unwrap_or(raw);
let rel = sub(cursor, anchor);
let mut offset = rel.0 * edge.normal.0 + rel.1 * edge.normal.1;
if d.snapped.is_none() && gs > 0.0 {
offset = jsnum::round(offset / gs) * gs;
}
add(anchor, scale(edge.normal, offset))
}
/// Art eines Höhen-Griffs im Schnitt/in der Ansicht.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HeightGrip {
WallTop,
OpeningTop,
OpeningBottom,
}
/// Ergebnis eines Höhen-Griff-Zugs: neue Ober-/Unterkante im Blatt und die Werte fürs Bauteil
/// (Wand/Öffnung `height`; Fenster-Unterkante zusätzlich `sill_height`), auf mm gerundet.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct HeightDrag {
pub top: f64,
pub bottom: f64,
pub height: f64,
pub sill_height: Option<f64>,
}
/// Höhen-Griff auf die Blatt-Höhe `y` ziehen (1-cm-Raster, `free` = Strg ohne Raster). `base` = Geschoss-
/// Höhe, `top`/`bottom` = heutige Ober-/Unterkante im Blatt. Mindestmasse: Wand 0.30 m, Öffnung 0.20 m.
pub fn sheet_height(kind: HeightGrip, base: f64, top: f64, bottom: f64, y: f64, free: bool) -> HeightDrag {
let v = if free { y } else { jsnum::round(y * 100.0) / 100.0 };
let mm = |x: f64| jsnum::round(x * 1000.0) / 1000.0;
match kind {
HeightGrip::WallTop => {
let t = jsnum::max(base + 0.3, v);
HeightDrag { top: t, bottom, height: mm(t - base), sill_height: None }
}
HeightGrip::OpeningTop => {
let t = jsnum::max(bottom + 0.2, v);
HeightDrag { top: t, bottom, height: mm(t - bottom), sill_height: None }
}
HeightGrip::OpeningBottom => {
let b = jsnum::min(top - 0.2, jsnum::max(base, v));
HeightDrag { top, bottom: b, height: mm(top - b), sill_height: Some(mm(b - base)) }
}
}
}
/// Mittelpunkt-Griff einer Öffnung (Breite `width`, `position` = Abstand des ersten Pfostens) auf der Wandachse.
pub fn opening_wall_grip(ws: P, we: P, position: f64, width: f64) -> P {
add(ws, scale(normalize(sub(we, ws)), position + width / 2.0))
}
/// Neue `position` einer Öffnung, deren Mittelpunkt-Griff nach `pt` gezogen wird: auf die Wandachse
/// projiziert und auf [0, Wandlänge − Breite] geklemmt. `None` bei einer Wand ohne Länge.
pub fn opening_slide(ws: P, we: P, width: f64, pt: P) -> Option<f64> {
let d = sub(we, ws);
let len = hypot2(d.0, d.1);
if !(len > 1e-9) {
return None;
}
let axis = scale(d, 1.0 / len);
let t = dot(sub(pt, ws), axis);
Some(jsnum::max(0.0, jsnum::min(len - width, t - width / 2.0)))
}
/// Öffnung im Schnitt-Blatt waagrecht ziehen: Blatt-Delta `du` (gesamt, entlang der Schnitt-Achse `u_axis`)
/// → neue `position` (geklemmt) und das dazu passende, tatsächlich wirksame Blatt-Delta. `None`, wenn die
/// Wand fast quer zur Schnittlinie steht (|u · Wandrichtung| < 0.15).
pub fn opening_slide_sheet(ws: P, we: P, u_axis: P, position: f64, width: f64, du: f64) -> Option<(f64, f64)> {
let axis = normalize(sub(we, ws));
let factor = dot(u_axis, axis);
if factor.abs() < 0.15 {
return None;
}
let len = hypot2(we.0 - ws.0, we.1 - ws.1);
let pos = jsnum::max(0.0, jsnum::min(len - width, position + du * factor));
Some((pos, (pos - position) / factor))
}
/// Bewegpunkt einer Treppe: Wendeltreppe im Zentrum (sonst Start), sonst Mitte des ersten Laufs.
pub fn stair_handle(spiral: bool, center: Option<P>, start: P, dir: P, run_length: f64) -> P {
if spiral {
return center.unwrap_or(start);
}
add(start, scale(normalize(dir), run_length / 2.0))
}
/// Griffe einer Wand: Start, Ende und bei einer Bogenwand ([T2]) der Bogenscheitel (Pfeilhöhe = halbe
/// Sehne · bulge, links der Sehne).
pub fn wall_grips(s: P, e: P, bulge: f64) -> Vec<P> {
if bulge == 0.0 || bulge.is_nan() {
return vec![s, e];
}
let h = hypot2(e.0 - s.0, e.1 - s.1) / 2.0;
let d = sub(e, s);
let apex = add(scale(add(s, e), 0.5), scale(normalize((-d.1, d.0)), h * bulge));
vec![s, e, apex]
}
/// [68] Griffe einer Baugrube: Umriss-Ecken, dann der Sohlen-Griff (Eckpunkt-Mittel, y + Sohlenhöhe).
pub fn excavation_grips(outline: &[P], bottom: f64) -> Vec<P> {
let n = outline.len().max(1) as f64;
let cx = outline.iter().fold(0.0, |a, q| a + q.0) / n;
let cy = outline.iter().fold(0.0, |a, q| a + q.1) / n;
let mut out = outline.to_vec();
out.push((cx, cy + bottom));
out
}
/// Toleranz für gemeinsame Ecken beim Körper-Verschieben (m, wie beim 3D-Zug).
pub const COINCIDENT_TOL: f64 = 0.05;
/// Koinzidente Punkte anderer gewählter Elemente (`groups`, je Element seine Griff-Punkte) an jeder Ecke
/// (`corners`) des verschobenen Elements: (Element, Punkt) in der Reihenfolge Ecke → Element → Punkt,
/// jeder Punkt höchstens einmal.
pub fn coincident(corners: &[P], groups: &[Vec<P>]) -> Vec<(usize, usize)> {
let mut out: Vec<(usize, usize)> = Vec::new();
for c in corners {
for (g, pts) in groups.iter().enumerate() {
for (i, q) in pts.iter().enumerate() {
if hypot2(c.0 - q.0, c.1 - q.1) <= COINCIDENT_TOL && !out.contains(&(g, i)) {
out.push((g, i));
}
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn close(a: P, b: P) -> bool {
(a.0 - b.0).abs() < 1e-12 && (a.1 - b.1).abs() < 1e-12
}
#[test]
fn polar_werte() {
let (l, a, o) = polar((1.0, 1.0), (1.0, 3.0), (0.0, 1.0));
assert_eq!((l, a, o), (2.0, 90.0, 2.0));
// Winkel immer in [0, 360).
assert_eq!(polar((0.0, 0.0), (0.0, -1.0), (1.0, 0.0)).1, 270.0);
assert_eq!(polar((0.0, 0.0), (-1.0, -0.0), (1.0, 0.0)).1, 180.0);
}
#[test]
fn polar_punkt_mit_und_ohne_lock() {
// Beide gelockt: Cursor zählt nicht.
assert!(close(polar_point((1.0, 0.0), Some(2.0), Some(90.0), (9.0, 9.0)), (1.0, 2.0)));
// Nur Länge gelockt: Richtung vom Cursor.
assert!(close(polar_point((0.0, 0.0), Some(5.0), None, (3.0, 0.0)), (5.0, 0.0)));
// Nur Winkel gelockt: Länge vom Cursor.
assert!(close(polar_point((0.0, 0.0), None, Some(180.0), (0.0, 2.0)), (-2.0, 0.0)));
// Nichts gelockt: der Cursor selbst.
assert!(close(polar_point((0.0, 0.0), None, None, (0.3, -0.4)), (0.3, -0.4)));
}
#[test]
fn nachbarn_ring_und_kette() {
assert_eq!(ring_neighbors(4, 0, true), (Some(3), Some(1)));
assert_eq!(ring_neighbors(4, 3, true), (Some(2), Some(0)));
assert_eq!(ring_neighbors(4, 0, false), (None, Some(1)));
assert_eq!(ring_neighbors(4, 3, false), (Some(2), None));
// Zweipunkt-Ring: der zweite Nachbar wäre derselbe Punkt.
assert_eq!(ring_neighbors(2, 0, true), (Some(1), None));
assert_eq!(ring_neighbors(1, 0, true), (None, None));
}
#[test]
fn achsen_lock_welt_und_flucht() {
// Ohne Ring: Welt-H/V durch den Anker.
assert!(close(axis_lock((3.0, 0.4), (0.0, 0.0), None, &[], 0, false), (3.0, 0.0)));
assert!(close(axis_lock((0.2, 3.0), (0.0, 0.0), None, &[], 0, false), (0.0, 3.0)));
// Schräge Nachbarkante (0,0)→(1,1), Eckpunkt 1 vorher bei (1,1): Flucht der Kante gewinnt.
let ring = [(0.0, 0.0), (1.0, 1.0), (1.0, 3.0)];
let p = axis_lock((2.1, 1.9), (0.0, 0.0), Some((1.0, 1.0)), &ring, 1, false);
assert!(close(p, (2.0, 2.0)), "{p:?}");
// Koinzidenter Nachbar (Richtung null) wird übersprungen.
let ring = [(1.0, 1.0), (1.0, 1.0)];
assert!(close(axis_lock((3.0, 0.4), (0.0, 0.0), Some((1.0, 1.0)), &ring, 1, false), (3.0, 0.0)));
}
#[test]
fn kante_gefuehrt_raster_und_snap() {
let e = Edge { mid: (0.0, 0.0), normal: (0.0, 1.0), free: false };
// Nur die Normalen-Komponente zählt, Raster 0.5.
let p = edge_target(e, (7.0, 1.3), EdgeDrive { grid: 0.5, ..Default::default() });
assert!(close(p, (0.0, 1.5)));
// Geometrie-Snap gewinnt vor dem Raster.
let p = edge_target(e, (7.0, 1.3), EdgeDrive { grid: 0.5, snapped: Some((2.0, 1.27)), ..Default::default() });
assert!(close(p, (0.0, 1.27)));
// Gelockt: der Feldwert, ohne Raster.
let p = edge_target(e, (7.0, 1.3), EdgeDrive { locked: true, length: Some(0.25), grid: 0.5, ..Default::default() });
assert!(close(p, (0.0, 0.25)));
// Gelockt ohne Wert: live entlang der Normale.
let p = edge_target(e, (7.0, 1.3), EdgeDrive { locked: true, ..Default::default() });
assert!(close(p, (0.0, 1.3)));
}
#[test]
fn kante_frei_ortho_und_raster() {
let e = Edge { mid: (1.0, 1.0), normal: (0.0, 1.0), free: true };
let p = edge_target(e, (3.2, 1.4), EdgeDrive { shift: true, ..Default::default() });
assert!(close(p, (3.2, 1.0)));
let p = edge_target(e, (3.2, 1.4), EdgeDrive { grid: 1.0, ..Default::default() });
assert!(close(p, (3.0, 1.0)));
let p = edge_target(e, (3.2, 1.4), EdgeDrive { locked: true, length: Some(2.0), angle: Some(0.0), ..Default::default() });
assert!(close(p, (3.0, 1.0)));
}
#[test]
fn hoehen_griffe() {
// Wand: 1-cm-Raster, Mindesthöhe 0.30 über dem Geschoss.
let r = sheet_height(HeightGrip::WallTop, 3.0, 5.6, 3.0, 5.7349, false);
assert_eq!((r.top, r.height, r.sill_height), (5.73, 2.73, None));
let r = sheet_height(HeightGrip::WallTop, 3.0, 5.6, 3.0, 2.0, false);
assert_eq!(r.height, 0.3);
// Strg: ohne Raster.
assert_eq!(sheet_height(HeightGrip::WallTop, 0.0, 2.0, 0.0, 2.3456, true).height, 2.346);
// Fenster oben: Mindesthöhe 0.20 über der Unterkante.
let r = sheet_height(HeightGrip::OpeningTop, 0.0, 2.1, 0.9, 0.5, false);
assert_eq!((r.top, r.height), (1.1, 0.2));
// Fenster unten: zwischen Geschoss und Oberkante − 0.20, Oberkante bleibt.
let r = sheet_height(HeightGrip::OpeningBottom, 0.0, 2.1, 0.9, 0.6, false);
assert_eq!((r.bottom, r.top, r.sill_height, r.height), (0.6, 2.1, Some(0.6), 1.5));
let r = sheet_height(HeightGrip::OpeningBottom, 0.0, 2.1, 0.9, -1.0, false);
assert_eq!(r.sill_height, Some(0.0));
let r = sheet_height(HeightGrip::OpeningBottom, 0.0, 2.1, 0.9, 3.0, false);
assert_eq!(r.height, 0.2);
}
#[test]
fn oeffnung_entlang_der_wand() {
let (s, e) = ((0.0, 0.0), (5.0, 0.0));
assert!(close(opening_wall_grip(s, e, 1.0, 1.2), (1.6, 0.0)));
assert_eq!(opening_slide(s, e, 1.2, (2.6, 3.0)), Some(2.0));
// Geklemmt an beide Enden.
assert_eq!(opening_slide(s, e, 1.2, (-3.0, 0.0)), Some(0.0));
assert_eq!(opening_slide(s, e, 1.2, (9.0, 0.0)), Some(3.8));
assert_eq!(opening_slide(s, s, 1.2, (1.0, 0.0)), None);
}
#[test]
fn oeffnung_im_schnitt() {
let (s, e) = ((0.0, 0.0), (5.0, 0.0));
// Schnitt-Achse gegen die Wand: Faktor −1.
assert_eq!(opening_slide_sheet(s, e, (-1.0, 0.0), 1.0, 1.2, 0.5), Some((0.5, 0.5)));
// Geklemmt: wirksames Delta passt zur Klemmung.
assert_eq!(opening_slide_sheet(s, e, (1.0, 0.0), 1.0, 1.2, 10.0), Some((3.8, 2.8)));
// Quer geschnittene Wand: keine Bewegung.
assert_eq!(opening_slide_sheet(s, e, (0.1, 0.995), 1.0, 1.2, 1.0), None);
}
#[test]
fn treppe_wand_baugrube() {
assert!(close(stair_handle(false, None, (1.0, 1.0), (0.0, 2.0), 4.0), (1.0, 3.0)));
assert!(close(stair_handle(true, Some((5.0, 5.0)), (1.0, 1.0), (0.0, 2.0), 4.0), (5.0, 5.0)));
assert!(close(stair_handle(true, None, (1.0, 1.0), (0.0, 2.0), 4.0), (1.0, 1.0)));
assert_eq!(wall_grips((0.0, 0.0), (4.0, 0.0), 0.0).len(), 2);
let g = wall_grips((0.0, 0.0), (4.0, 0.0), 0.5);
assert!(close(g[2], (2.0, 1.0)), "{g:?}");
let pit = [(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)];
let g = excavation_grips(&pit, -2.0);
assert_eq!(g.len(), 5);
assert!(close(g[4], (2.0, 0.0)));
assert!(close(excavation_grips(&[], 1.0)[0], (0.0, 1.0)));
}
#[test]
fn koinzidente_ecken() {
let corners = [(0.0, 0.0), (4.0, 0.0)];
let groups = vec![vec![(4.03, 0.0), (4.0, 3.0)], vec![(9.0, 9.0)], vec![(0.0, 0.04), (0.0, 0.02), (4.0, 0.0)]];
assert_eq!(coincident(&corners, &groups), vec![(2, 0), (2, 1), (0, 0), (2, 2)]);
}
}
+1
View File
@@ -94,6 +94,7 @@ pub use dossier_hatch::ugrid;
pub mod wasm_alloc;
pub mod text_layout;
pub mod grips;
pub mod grip_drag;
pub mod json_util;
pub mod selection_info;
pub mod project_refs;
+164
View File
@@ -0,0 +1,164 @@
//! Bindungen der Griff-Zug-Rechnung (`crate::grip_drag`, [128]): Punkte als Zahlenpaare bzw. flache
//! Puffer `[x0, y0, …]`; NaN = „fehlt" (ungelockter Wert, kein Snap, kein Zentrum). Kaputte Puffer ergeben
//! ein leeres Ergebnis.
use crate::grip_drag::{self as gd, Edge, EdgeDrive, HeightGrip, P};
use wasm_bindgen::prelude::wasm_bindgen;
fn opt(v: f64) -> Option<f64> {
(!v.is_nan()).then_some(v)
}
fn opt_p(x: f64, y: f64) -> Option<P> {
(!x.is_nan() && !y.is_nan()).then_some((x, y))
}
fn pts(f: &[f64]) -> Vec<P> {
f.chunks_exact(2).map(|c| (c[0], c[1])).collect()
}
fn flat(v: &[P]) -> Vec<f64> {
v.iter().flat_map(|p| [p.0, p.1]).collect()
}
/// `[länge, winkel°, abstand entlang (nx, ny)]` von `(ax, ay)` nach `(px, py)`.
#[wasm_bindgen]
pub fn grip_polar(ax: f64, ay: f64, px: f64, py: f64, nx: f64, ny: f64) -> Vec<f64> {
let (l, a, o) = gd::polar((ax, ay), (px, py), (nx, ny));
vec![l, a, o]
}
/// Punkt aus Anker + Länge/Winkel° (NaN = folgt dem Cursor `(rx, ry)`): `[x, y]`.
#[wasm_bindgen]
pub fn grip_polar_point(ax: f64, ay: f64, length: f64, angle: f64, rx: f64, ry: f64) -> Vec<f64> {
let p = gd::polar_point((ax, ay), opt(length), opt(angle), (rx, ry));
vec![p.0, p.1]
}
/// Shift-Achsen-Lock (`grip_drag::axis_lock`): Ursprung `(ox, oy)` NaN = noch keiner; `ring` = Punkte des
/// Elements (leer = keine Polygon-Nachbarn), `index` = gezogener Punkt darin. `[x, y]`.
#[wasm_bindgen]
#[allow(clippy::too_many_arguments)]
pub fn grip_axis_lock(rx: f64, ry: f64, ax: f64, ay: f64, ox: f64, oy: f64, ring: &[f64], index: f64, closed: bool) -> Vec<f64> {
let ring = pts(ring);
let i = if index >= 0.0 && index.fract() == 0.0 && index < ring.len() as f64 { index as usize } else { usize::MAX };
let p = gd::axis_lock((rx, ry), (ax, ay), opt_p(ox, oy), &ring, i, closed);
vec![p.0, p.1]
}
/// Zielpunkt eines Kanten-Zugs (`grip_drag::edge_target`): Kante `mid`/`normal`/`free`, Cursor, Feld-Controller
/// (`locked`, Länge/Winkel NaN = live), Shift, Raster (0 = aus), Geometrie-Snap (NaN = keiner). `[x, y]`.
#[wasm_bindgen]
#[allow(clippy::too_many_arguments)]
pub fn grip_edge_target(
mx: f64,
my: f64,
nx: f64,
ny: f64,
free: bool,
rx: f64,
ry: f64,
locked: bool,
length: f64,
angle: f64,
shift: bool,
grid: f64,
sx: f64,
sy: f64,
) -> Vec<f64> {
let edge = Edge { mid: (mx, my), normal: (nx, ny), free };
let grid = if grid.is_finite() && grid > 0.0 { grid } else { 0.0 };
let d = EdgeDrive { locked, length: opt(length), angle: opt(angle), shift, grid, snapped: opt_p(sx, sy) };
let p = gd::edge_target(edge, (rx, ry), d);
vec![p.0, p.1]
}
/// Höhen-Griff im Schnitt (`kind` 0 Wand-Oberkante, 1 Öffnung oben, 2 Öffnung unten): `[oben, unten, höhe,
/// brüstung]` (Brüstung NaN, wenn sie sich nicht ändert); `[]` bei unbekannter Art.
#[wasm_bindgen]
pub fn grip_sheet_height(kind: u32, base: f64, top: f64, bottom: f64, y: f64, free: bool) -> Vec<f64> {
let k = match kind {
0 => HeightGrip::WallTop,
1 => HeightGrip::OpeningTop,
2 => HeightGrip::OpeningBottom,
_ => return vec![],
};
let r = gd::sheet_height(k, base, top, bottom, y, free);
vec![r.top, r.bottom, r.height, r.sill_height.unwrap_or(f64::NAN)]
}
/// Mittelpunkt-Griff einer Öffnung auf der Wandachse `s → e`: `[x, y]`.
#[wasm_bindgen]
pub fn grip_opening_point(sx: f64, sy: f64, ex: f64, ey: f64, position: f64, width: f64) -> Vec<f64> {
let p = gd::opening_wall_grip((sx, sy), (ex, ey), position, width);
vec![p.0, p.1]
}
/// Neue Öffnungs-`position` beim Ziehen des Mittelpunkt-Griffs nach `(px, py)`: `[position]`, `[]` = Wand ohne Länge.
#[wasm_bindgen]
pub fn grip_opening_slide(sx: f64, sy: f64, ex: f64, ey: f64, width: f64, px: f64, py: f64) -> Vec<f64> {
gd::opening_slide((sx, sy), (ex, ey), width, (px, py)).map(|p| vec![p]).unwrap_or_default()
}
/// Öffnung im Schnitt-Blatt (`grip_drag::opening_slide_sheet`): `[position, wirksames du]`, `[]` = keine Bewegung.
#[wasm_bindgen]
#[allow(clippy::too_many_arguments)]
pub fn grip_opening_slide_sheet(sx: f64, sy: f64, ex: f64, ey: f64, ux: f64, uy: f64, position: f64, width: f64, du: f64) -> Vec<f64> {
gd::opening_slide_sheet((sx, sy), (ex, ey), (ux, uy), position, width, du).map(|(p, d)| vec![p, d]).unwrap_or_default()
}
/// Bewegpunkt einer Treppe (Zentrum NaN = keines): `[x, y]`.
#[wasm_bindgen]
#[allow(clippy::too_many_arguments)]
pub fn grip_stair_handle(spiral: bool, cx: f64, cy: f64, sx: f64, sy: f64, dx: f64, dy: f64, run_length: f64) -> Vec<f64> {
let p = gd::stair_handle(spiral, opt_p(cx, cy), (sx, sy), (dx, dy), run_length);
vec![p.0, p.1]
}
/// Griffe einer Wand (Bogenwand mit Scheitel-Griff): `[x0, y0, …]`.
#[wasm_bindgen]
pub fn grip_wall_points(sx: f64, sy: f64, ex: f64, ey: f64, bulge: f64) -> Vec<f64> {
flat(&gd::wall_grips((sx, sy), (ex, ey), bulge))
}
/// Griffe einer Baugrube (Umriss `[x0, y0, …]`, dann der Sohlen-Griff): `[x0, y0, …]`.
#[wasm_bindgen]
pub fn grip_excavation_points(outline: &[f64], bottom: f64) -> Vec<f64> {
flat(&gd::excavation_grips(&pts(outline), bottom))
}
/// Koinzidente Punkte anderer Elemente an den Ecken `corners` (`[x0, y0, …]`); `groups` = je Element
/// `[n, x0, y0, …]` hintereinander. Antwort `[element, punkt, …]`; `[]` bei kaputtem Puffer.
#[wasm_bindgen]
pub fn grip_coincident(corners: &[f64], groups: &[f64]) -> Vec<f64> {
let mut gs: Vec<Vec<P>> = Vec::new();
let mut i = 0;
while i < groups.len() {
let n = groups[i];
if !(n >= 0.0 && n.fract() == 0.0) {
return vec![];
}
let end = i + 1 + 2 * n as usize;
if end > groups.len() {
return vec![];
}
gs.push(pts(&groups[i + 1..end]));
i = end;
}
gd::coincident(&pts(corners), &gs).into_iter().flat_map(|(g, k)| [g as f64, k as f64]).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kaputte_puffer_leer() {
assert!(grip_coincident(&[0.0, 0.0], &[3.0, 1.0]).is_empty());
assert!(grip_coincident(&[0.0, 0.0], &[f64::NAN]).is_empty());
assert_eq!(grip_coincident(&[0.0, 0.0], &[1.0, 0.01, 0.0, 0.0]), vec![0.0, 0.0]);
assert!(grip_sheet_height(7, 0.0, 1.0, 0.0, 1.0, false).is_empty());
// Unsinniger Index: keine Polygon-Nachbarn, nur Welt-H/V.
assert_eq!(grip_axis_lock(3.0, 0.4, 0.0, 0.0, 1.0, 1.0, &[0.0, 0.0, 1.0, 1.0], f64::NAN, true), vec![3.0, 0.0]);
}
}
+1
View File
@@ -38,6 +38,7 @@ mod parametric_walls;
mod reorder;
mod text_layout;
mod grips;
mod grip_drag;
mod project_refs;
mod commands;
mod import;
+2
View File
@@ -68,6 +68,8 @@ export { drawingVertices, gripPt, openEdges, polylineEdgeGrips, ringEdges } from
export { verticalExtents } from "../geometry/grips";
export type { VerticalExtent } from "../geometry/grips";
export type { GripRequest } from "../geometry/grips";
export { coincidentGripPoints, excavationGripPoints, gripAxisLock, gripEdgeTarget, gripPolar, gripPolarPoint, openingGripPoint, openingSheetSlide, openingSlidePosition, sheetHeightDrag, stairMoveHandle, wallGripPoints } from "../geometry/gripDrag";
export type { EdgeDrive, GripLocks, SheetHeightKind } from "../geometry/gripDrag";
export { openingPreviewProject, openingPreviewSvgs } from "../plan/openingPreview";
export type { OpeningPreviewSvgs } from "../plan/openingPreview";
export { surfaceOpeningInfo, surfaceOpeningGrips, surfaceOpeningGripPatch } from "../plan/surfaceOpening";
+67
View File
@@ -0,0 +1,67 @@
// Fassade der Griff-Zug-Rechnung ([128], Kern `grip_drag.rs`): Übergabe an den Kern und zurück.
import { describe, expect, it } from "vitest";
import {
coincidentGripPoints,
gripAxisLock,
gripEdgeTarget,
gripPolar,
gripPolarPoint,
openingGripPoint,
openingSheetSlide,
openingSlidePosition,
sheetHeightDrag,
wallGripPoints,
} from "./gripDrag";
const wall = { start: { x: 0, y: 0 }, end: { x: 5, y: 0 } };
describe("Griff-Zug (Kern)", () => {
it("Länge/Winkel und Punkt aus Locks", () => {
expect(gripPolar({ x: 1, y: 1 }, { x: 1, y: 3 }, { x: 0, y: 1 })).toEqual({ length: 2, angleDeg: 90, offset: 2 });
const p = gripPolarPoint({ x: 0, y: 0 }, { length: 5 }, { x: 3, y: 0 });
expect(p.x).toBeCloseTo(5, 12);
expect(p.y).toBeCloseTo(0, 12);
});
it("Shift-Achsen-Lock: Flucht der Nachbarkante, ohne Ring nur H/V", () => {
const ring = [{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 1, y: 3 }];
const p = gripAxisLock({ x: 2.1, y: 1.9 }, { x: 0, y: 0 }, { x: 1, y: 1 }, ring, 1, false);
expect(p.x).toBeCloseTo(2, 12);
expect(p.y).toBeCloseTo(2, 12);
expect(gripAxisLock({ x: 3, y: 0.4 }, { x: 0, y: 0 }, null, null, -1, false)).toEqual({ x: 3, y: 0 });
});
it("Kanten-Ziel: geführt mit Raster/Snap, frei mit Ortho, gelockt", () => {
const guided = { mid: { x: 0, y: 0 }, normal: { x: 0, y: 1 }, aIndex: 0, bIndex: 1 };
expect(gripEdgeTarget(guided, { x: 7, y: 1.3 }, { grid: 0.5 })).toEqual({ x: 0, y: 1.5 });
expect(gripEdgeTarget(guided, { x: 7, y: 1.3 }, { grid: 0.5, snapped: { x: 2, y: 1.27 } })).toEqual({ x: 0, y: 1.27 });
expect(gripEdgeTarget(guided, { x: 7, y: 1.3 }, { locks: { length: 0.25 } })).toEqual({ x: 0, y: 0.25 });
const free = { ...guided, mid: { x: 1, y: 1 }, free: true };
expect(gripEdgeTarget(free, { x: 3.2, y: 1.4 }, { shift: true })).toEqual({ x: 3.2, y: 1 });
});
it("Höhen-Griffe: Patch je Art", () => {
expect(sheetHeightDrag("wallTop", { base: 3, top: 5.6, bottom: 3 }, 5.7349, false)).toEqual({ top: 5.73, bottom: 3, patch: { height: 2.73 } });
const r = sheetHeightDrag("openingBottom", { base: 0, top: 2.1, bottom: 0.9 }, 0.6, false);
expect(r.patch).toEqual({ sillHeight: 0.6, height: 1.5 });
});
it("Öffnung entlang der Wand und im Schnitt", () => {
expect(openingGripPoint(wall, { position: 1, width: 1.2 })).toEqual({ x: 1.6, y: 0 });
expect(openingSlidePosition(wall, { width: 1.2 }, { x: 2.6, y: 3 })).toBe(2);
expect(openingSlidePosition({ start: wall.start, end: wall.start }, { width: 1.2 }, { x: 1, y: 0 })).toBeNull();
expect(openingSheetSlide(wall, { position: 1, width: 1.2 }, { x: -1, y: 0 }, 0.5)).toEqual({ position: 0.5, du: 0.5 });
expect(openingSheetSlide(wall, { position: 1, width: 1.2 }, { x: 0.1, y: 0.995 }, 1)).toBeNull();
});
it("Wand-Griffe und koinzidente Ecken", () => {
expect(wallGripPoints({ ...wall })).toHaveLength(2);
const g = wallGripPoints({ start: { x: 0, y: 0 }, end: { x: 4, y: 0 }, bulge: 0.5 });
expect(g[2].x).toBeCloseTo(2, 12);
expect(g[2].y).toBeCloseTo(1, 12);
const corners = [{ x: 0, y: 0 }, { x: 4, y: 0 }];
const groups = [[{ x: 4.03, y: 0 }, { x: 4, y: 3 }], [], [{ x: 0, y: 0.04 }]];
expect(coincidentGripPoints(corners, groups)).toEqual([{ group: 2, index: 0 }, { group: 0, index: 0 }]);
});
});
+160
View File
@@ -0,0 +1,160 @@
// Griff-Zug-Rechnung ([128]): dünne Fassade über den Rust-Kern (`src-tauri/core/src/grip_drag.rs`,
// Bindungen `web/grip_drag.rs`). Wohin ein gezogener Griff fällt (Länge/Winkel-Felder, Shift-Achsen-Lock,
// Kanten-Griffe, Höhen-Griffe im Schnitt, Öffnung entlang der Wand, koinzidente Ecken) rechnet der Kern;
// `state/useGripEditing.ts` hält nur Zustand und Vorschau.
import type { EdgeGrip, Excavation, Opening, Stair, Vec2, Wall } from "../model/types";
import { core } from "../engine/coreWasm";
const v = (f: ArrayLike<number>, i = 0): Vec2 => ({ x: f[i], y: f[i + 1] });
function flat(pts: readonly Vec2[]): Float64Array {
const f = new Float64Array(pts.length * 2);
for (let i = 0; i < pts.length; i++) {
f[2 * i] = pts[i].x;
f[2 * i + 1] = pts[i].y;
}
return f;
}
function points(f: ArrayLike<number>): Vec2[] {
const out: Vec2[] = new Array(f.length >> 1);
for (let i = 0; i < out.length; i++) out[i] = v(f, 2 * i);
return out;
}
/** Gelockte Länge (m) / Winkel (Grad) des Feld-Controllers; fehlend = folgt dem Cursor. */
export interface GripLocks {
length?: number;
angle?: number;
}
/** Länge, Winkel (Grad, [0, 360)) und Abstand entlang `normal` von `anchor` nach `p` (Felder, HUD). */
export function gripPolar(anchor: Vec2, p: Vec2, normal: Vec2 = { x: 0, y: 0 }): { length: number; angleDeg: number; offset: number } {
const f = core().grip_polar(anchor.x, anchor.y, p.x, p.y, normal.x, normal.y);
return { length: f[0], angleDeg: f[1], offset: f[2] };
}
/** Punkt aus Anker + gelockter Länge/Winkel; ungelockte Werte folgen dem rohen Cursor `raw`. */
export function gripPolarPoint(anchor: Vec2, locks: GripLocks, raw: Vec2): Vec2 {
return v(core().grip_polar_point(anchor.x, anchor.y, locks.length ?? NaN, locks.angle ?? NaN, raw.x, raw.y));
}
/**
* Shift-Achsen-Lock eines Punkt-Griffs: Welt-H/V durch den Nachbar-Griff `anchor`, bei einem Vielecks-
* Eckpunkt (`ring` = Punkte des Elements, `index` darin, `origin` = Lage vor dem Zug) zusätzlich die Flucht
* der beiden fixen Nachbarkanten. Die nächstliegende Achse gewinnt.
*/
export function gripAxisLock(raw: Vec2, anchor: Vec2, origin: Vec2 | null, ring: readonly Vec2[] | null, index: number, closed: boolean): Vec2 {
const f = ring && origin ? flat(ring) : new Float64Array();
return v(core().grip_axis_lock(raw.x, raw.y, anchor.x, anchor.y, origin?.x ?? NaN, origin?.y ?? NaN, f, index, closed));
}
/** Führung eines Kanten-Zugs (s. {@link gripEdgeTarget}). */
export interface EdgeDrive {
/** Feld-Controller offen: Ziel aus Anker + Locks, ohne Raster/Ortho. */
locks?: GripLocks | null;
shift?: boolean;
/** Rasterweite (0 = aus). */
grid?: number;
/** Gefangener Geometrie-Snap (nur geführte Kanten). */
snapped?: Vec2 | null;
}
/**
* Zielpunkt eines Kanten-Zugs relativ zum Anker `edge.mid`: geführte Kante nur entlang der Normale
* (Geometrie-Snap vor Raster), freie Kante (`edge.free`) voller Cursor mit Ortho/Raster.
*/
export function gripEdgeTarget(edge: EdgeGrip, raw: Vec2, d: EdgeDrive = {}): Vec2 {
const { mid, normal } = edge;
const l = d.locks;
const s = d.snapped;
return v(
core().grip_edge_target(
mid.x, mid.y, normal.x, normal.y, !!edge.free, raw.x, raw.y,
!!l, l?.length ?? NaN, l?.angle ?? NaN, !!d.shift, d.grid ?? 0, s?.x ?? NaN, s?.y ?? NaN,
),
);
}
/** Art eines Höhen-Griffs im Schnitt/in der Ansicht. */
export type SheetHeightKind = "wallTop" | "openingTop" | "openingBottom";
/**
* Höhen-Griff auf die Blatt-Höhe `y` ziehen (1-cm-Raster, `free` = ohne): neue Ober-/Unterkante im Blatt und
* der Patch fürs Bauteil (`height`, Fenster-Unterkante zusätzlich `sillHeight`; mm-genau).
*/
export function sheetHeightDrag(
kind: SheetHeightKind,
g: { base: number; top: number; bottom: number },
y: number,
free: boolean,
): { top: number; bottom: number; patch: Record<string, number> } {
const k = kind === "wallTop" ? 0 : kind === "openingTop" ? 1 : 2;
const f = core().grip_sheet_height(k, g.base, g.top, g.bottom, y, free);
const patch: Record<string, number> = kind === "openingBottom" ? { sillHeight: f[3], height: f[2] } : { height: f[2] };
return { top: f[0], bottom: f[1], patch };
}
/** Mittelpunkt-Griff einer Öffnung auf der Achse ihrer Wirtswand. */
export function openingGripPoint(w: Pick<Wall, "start" | "end">, op: Pick<Opening, "position" | "width">): Vec2 {
return v(core().grip_opening_point(w.start.x, w.start.y, w.end.x, w.end.y, op.position, op.width));
}
/** Neue `position` beim Ziehen des Öffnungs-Griffs nach `pt` (auf die Wand geklemmt); null = Wand ohne Länge. */
export function openingSlidePosition(w: Pick<Wall, "start" | "end">, op: Pick<Opening, "width">, pt: Vec2): number | null {
const f = core().grip_opening_slide(w.start.x, w.start.y, w.end.x, w.end.y, op.width, pt.x, pt.y);
return f.length ? f[0] : null;
}
/**
* Öffnung im Schnitt-Blatt waagrecht ziehen: Blatt-Delta `du` (gesamt, entlang `uAxis`) → neue `position`
* und das wirksame Delta (nach dem Klemmen); null, wenn die Wand fast quer zur Schnittlinie steht.
*/
export function openingSheetSlide(
w: Pick<Wall, "start" | "end">,
op: Pick<Opening, "position" | "width">,
uAxis: Vec2,
du: number,
): { position: number; du: number } | null {
const f = core().grip_opening_slide_sheet(w.start.x, w.start.y, w.end.x, w.end.y, uAxis.x, uAxis.y, op.position, op.width, du);
return f.length ? { position: f[0], du: f[1] } : null;
}
/** Bewegpunkt einer Treppe (Mitte des ersten Laufs, Wendeltreppe im Zentrum). */
export function stairMoveHandle(st: Stair): Vec2 {
const c = st.center;
return v(core().grip_stair_handle(st.shape === "spiral", c?.x ?? NaN, c?.y ?? NaN, st.start.x, st.start.y, st.dir?.x ?? 0, st.dir?.y ?? 0, st.runLength));
}
/** Griffe einer Wand: Start, Ende, bei einer Bogenwand ([T2]) der Bogenscheitel. */
export function wallGripPoints(w: Pick<Wall, "start" | "end" | "bulge">): Vec2[] {
return points(core().grip_wall_points(w.start.x, w.start.y, w.end.x, w.end.y, w.bulge ?? 0));
}
/** Griff-Punkte einer Baugrube: Umriss-Ecken, dann der Sohlen-Griff (Schwerpunkt, y + Sohlenhöhe). */
export function excavationGripPoints(e: Excavation): Vec2[] {
return points(core().grip_excavation_points(flat(e.outline), e.bottom));
}
/**
* Koinzidente Punkte anderer Elemente (`groups`, je Element seine Griff-Punkte) an den Ecken `corners` des
* verschobenen Elements (Toleranz 5 cm): `{group, index}` je Punkt, ohne Doppel.
*/
export function coincidentGripPoints(corners: readonly Vec2[], groups: readonly (readonly Vec2[])[]): { group: number; index: number }[] {
if (corners.length === 0 || groups.length === 0) return [];
const n = groups.reduce((a, g) => a + 1 + 2 * g.length, 0);
const f = new Float64Array(n);
let k = 0;
for (const g of groups) {
f[k++] = g.length;
for (const p of g) {
f[k++] = p.x;
f[k++] = p.y;
}
}
const r = core().grip_coincident(flat(corners), f);
const out: { group: number; index: number }[] = [];
for (let i = 0; i + 1 < r.length; i += 2) out.push({ group: r[i], index: r[i + 1] });
return out;
}
+1 -1
View File
@@ -4,7 +4,7 @@ import { describe, expect, it } from "vitest";
import { documentFor } from "../core/document";
import { sampleProject } from "../model/sampleProject";
import type { Excavation, Project } from "../model/types";
import { excavationGripPoints } from "./useGripEditing";
import { excavationGripPoints } from "../core";
const pit: Excavation = {
id: "bg",
+100 -303
View File
@@ -7,15 +7,30 @@
import { useRef, useState, type RefObject } from "react";
import { useEventBundle, useSameData } from "./useEvent";
import { add, dot, leftNormal, normalize, scale, sub, wallCorners } from "../model/geometry";
import type { Ceiling, Drawing2D, EdgeGrip, Excavation, Project, Room, Stair, Vec2 } from "../model/types";
import { leftNormal, normalize, scale, sub, wallCorners } from "../model/geometry";
import type { Ceiling, Drawing2D, EdgeGrip, Excavation, Project, Room, Vec2 } from "../model/types";
import { wallTypeThickness } from "../model/types";
import { bulgeArcPoints, drawingVertices, surfaceOpeningGripPatch, surfaceOpeningGrips, surfaceOpeningInfo, wallArcBand } from "../core";
import { gripDrawingIdsFor } from "./gripLimits";
import { openEdges, polylineEdgeGrips, ringEdges } from "../core";
import {
coincidentGripPoints,
excavationGripPoints,
gripAxisLock,
gripEdgeTarget,
gripPolar,
gripPolarPoint,
openingGripPoint,
openingSheetSlide,
openingSlidePosition,
sheetHeightDrag,
stairMoveHandle,
wallGripPoints,
type GripLocks,
} from "../core";
import { areaMovePreview, drawingMovePreview } from "../tools/transform";
import type { DraftShape, SnapResult, SnapSettings, ToolDraft, ToolMods } from "../tools/types";
import { applyAngleConstraint, computeSnap } from "../tools/snapping";
import { computeSnap } from "../tools/snapping";
import { useCommandTabShortcut } from "./useKeyboardShortcuts";
import { sheetOwnerOutlines } from "../tools/sheetSnapGeometry";
import type { BodyTarget } from "../views/plan/PlanView";
@@ -32,18 +47,15 @@ export interface GripEditFieldsState {
active: boolean;
}
/** Scheitel eines Bogens a→b (Modell-Bulge: Pfeilhöhe = halbe Sehne · bulge, links der Sehne). */
function arcApex(a: Vec2, b: Vec2, bulge: number): Vec2 {
const h = Math.hypot(b.x - a.x, b.y - a.y) / 2;
return add(scale(add(a, b), 0.5), scale(normalize(leftNormal(sub(b, a))), h * bulge));
}
/** Griff-Punkte einer Baugrube: Umriss-Ecken, dann der Sohlen-Griff (Schwerpunkt, y + Sohlenhöhe; Kern `grips.rs`). */
export function excavationGripPoints(e: Excavation): Vec2[] {
const n = Math.max(1, e.outline.length);
const cx = e.outline.reduce((a, q) => a + q.x, 0) / n;
const cy = e.outline.reduce((a, q) => a + q.y, 0) / n;
return [...e.outline, { x: cx, y: cy + e.bottom }];
/** Länge/Winkel-Felder des Befehlsfelds (Live-Werte `live`, gelockte aus `ed.locks`). */
function polarFields(
ed: { active: "length" | "angle"; locks: GripLocks },
live: { length: number; angleDeg: number },
): GripEditFieldsState[] {
return [
{ id: "length", labelKey: "cmd.field.length", value: ed.locks.length ?? live.length, locked: ed.locks.length != null, active: ed.active === "length" },
{ id: "angle", labelKey: "cmd.field.angle", value: ed.locks.angle ?? live.angleDeg, locked: ed.locks.angle != null, active: ed.active === "angle" },
];
}
export function useGripEditing(opts: {
@@ -154,15 +166,8 @@ export function useGripEditing(opts: {
const { walls: selectedWallIds, drawings: selectedDrawingIds } = selection;
const groupChanges = opts.groupChanges ?? ((fn: () => void) => fn());
// Bewegpunkt (Move-Handle) einer Treppe: liegt auf der Treppe (Mitte des
// ersten Laufs bei gerade/L, Zentrum bei Wendel) und verschiebt beim Ziehen
// die GANZE Treppe (moveStairBy mit dem Delta). Ein einzelner, gut sichtbarer
// Griff — analog zum Öffnungs-Mittelpunkt.
const stairMoveHandle = (st: Stair): Vec2 => {
if (st.shape === "spiral") return st.center ?? st.start;
const d = normalize(st.dir);
return add(st.start, scale(d, st.runLength / 2));
};
// Bewegpunkt einer Treppe (`stairMoveHandle`, Kern `grip_drag.rs`): liegt auf der Treppe und verschiebt
// beim Ziehen die GANZE Treppe (moveStairBy mit dem Delta) — analog zum Öffnungs-Mittelpunkt.
// Welchem Element + lokalem Vertex-Index ein Griff im flachen `grips`-Array
// gehört (Mehrfachauswahl, Nutzer-Report: Griffe verschwanden komplett,
@@ -263,8 +268,7 @@ export function useGripEditing(opts: {
}
const w = op && project.walls.find((x) => x.id === op.hostWallId);
if (op && w) {
const axis = normalize(sub(w.end, w.start));
const pt = add(w.start, scale(axis, op.position + op.width / 2));
const pt = openingGripPoint(w, op);
gripOwners.push({ localIndex: 0 });
gripOwnerRange.push([0, 0]);
return [pt];
@@ -344,7 +348,7 @@ export function useGripEditing(opts: {
for (const id of selectedWallIds) {
const w = project.walls.find((x) => x.id === id);
// Bogenwand ([T2]): dritter Griff im Bogenscheitel (zieht den Bogen durch den Punkt).
if (w) pushGroup(w.bulge ? [w.start, w.end, arcApex(w.start, w.end, w.bulge)] : [w.start, w.end], { wallId: id });
if (w) pushGroup(wallGripPoints(w), { wallId: id });
}
}
return out;
@@ -455,10 +459,7 @@ export function useGripEditing(opts: {
// mitgeführt (gemeinsame Ecke bleibt verbunden). Lazy beim ersten Move-Event
// bestimmt (Snapshot der Selektion), je Drag in onGripEnd zurückgesetzt. null =
// noch nicht bestimmt.
const moveCoincidentRef = useRef<
| { drawingId: string | null; wallId: string | null; index: number; pos: Vec2 }[]
| null
>(null);
const moveCoincidentRef = useRef<{ drawingId: string | null; wallId: string | null; index: number; pos: Vec2 }[] | null>(null);
// Eckpunkte eines selektierten Elements (Wand: start/end; 2D: drawingVertices).
const elementCorners = (drawingId: string | null, wallId: string | null): Vec2[] => {
if (drawingId) {
@@ -471,42 +472,23 @@ export function useGripEditing(opts: {
}
return [];
};
// Koinzidente Sibling-Vertices (unter den ÜBRIGEN gewählten Elementen) an JEDER
// Ecke des verschobenen Elements. Toleranz wie beim 3D-Drag (gemeinsame Ecke).
const COINCIDENT_TOL_2D = 0.05; // m
const findMoveCoincident2D = (
selfDrawingId: string | null,
selfWallId: string | null,
): { drawingId: string | null; wallId: string | null; index: number; pos: Vec2 }[] => {
// Koinzidente Sibling-Vertices (unter den ÜBRIGEN gewählten Elementen) an JEDER Ecke des verschobenen
// Elements (Kern `coincidentGripPoints`, Toleranz wie beim 3D-Drag): hier nur die Kandidaten sammeln.
type CoincidentVertex = { drawingId: string | null; wallId: string | null; index: number; pos: Vec2 };
const findMoveCoincident2D = (selfDrawingId: string | null, selfWallId: string | null): CoincidentVertex[] => {
const corners = elementCorners(selfDrawingId, selfWallId);
if (corners.length === 0) return [];
const near = (p: Vec2, q: Vec2) => Math.hypot(p.x - q.x, p.y - q.y) <= COINCIDENT_TOL_2D;
const seen = new Set<string>();
const out: { drawingId: string | null; wallId: string | null; index: number; pos: Vec2 }[] = [];
const add2 = (drawingId: string | null, wallId: string | null, index: number, pos: Vec2) => {
const key = `${drawingId ?? ""}|${wallId ?? ""}|${index}`;
if (seen.has(key)) return;
seen.add(key);
out.push({ drawingId, wallId, index, pos: { ...pos } });
};
for (const corner of corners) {
for (const id of selectedWallIds) {
if (id === selfWallId) continue;
const w = project.walls.find((x) => x.id === id);
if (!w) continue;
if (near(corner, w.start)) add2(null, id, 0, w.start);
if (near(corner, w.end)) add2(null, id, 1, w.end);
}
for (const id of selectedDrawingIds) {
if (id === selfDrawingId) continue;
const d = project.drawings2d.find((x) => x.id === id);
if (!d) continue;
drawingVertices(d, scaleDenominator).forEach((v, i) => {
if (near(corner, v)) add2(id, null, i, v);
});
}
const owners: { drawingId: string | null; wallId: string | null }[] = [];
const groups: Vec2[][] = [];
for (const id of selectedWallIds) {
const w = id !== selfWallId ? project.walls.find((x) => x.id === id) : undefined;
if (w) { owners.push({ drawingId: null, wallId: id }); groups.push([w.start, w.end]); }
}
return out;
for (const id of selectedDrawingIds) {
const d = id !== selfDrawingId ? project.drawings2d.find((x) => x.id === id) : undefined;
if (d) { owners.push({ drawingId: id, wallId: null }); groups.push(drawingVertices(d, scaleDenominator)); }
}
return coincidentGripPoints(corners, groups).map(({ group, index }) => ({ ...owners[group], index, pos: { ...groups[group][index] } }));
};
// Editieren läuft AD-HOC (gripHandlers → moveGripOf), NICHT durch die Engine.
@@ -557,47 +539,15 @@ export function useGripEditing(opts: {
// mitdriften).
const gripOriginRef = useRef<Vec2 | null>(null);
// Endpunkt aus Anker + (gelockten/Live-)Länge/Winkel — wie lineEndFromFields,
// hier für den Vertex-Drag. Ungelockte Größen folgen dem rohen Cursor `raw`.
const gripEditPoint = (
anchor: Vec2,
locks: { length?: number; angle?: number },
raw: Vec2,
): Vec2 => {
const DEG = Math.PI / 180;
const dx = raw.x - anchor.x;
const dy = raw.y - anchor.y;
const length = locks.length != null ? locks.length : Math.hypot(dx, dy);
const angleDeg = locks.angle != null ? locks.angle : (Math.atan2(dy, dx) * 180) / Math.PI;
const a = angleDeg * DEG;
return { x: anchor.x + Math.cos(a) * length, y: anchor.y + Math.sin(a) * length };
};
// Endpunkt aus Anker + (gelockten/Live-)Länge/Winkel (Kern `gripPolarPoint`) — wie lineEndFromFields.
const gripEditPoint = gripPolarPoint;
// Felder fürs Befehlsfeld während des Vertex-Drags (Live ODER gelockt).
const gripEditFields = (): GripEditFieldsState[] => {
const ge = gripEdit;
const info = gripDragInfoRef.current;
if (!ge || !info) return [];
const dx = info.raw.x - ge.anchor.x;
const dy = info.raw.y - ge.anchor.y;
const liveLen = Math.hypot(dx, dy);
const liveAng = ((((Math.atan2(dy, dx) * 180) / Math.PI) % 360) + 360) % 360;
return [
{
id: "length",
labelKey: "cmd.field.length",
value: ge.locks.length ?? liveLen,
locked: ge.locks.length != null,
active: ge.active === "length",
},
{
id: "angle",
labelKey: "cmd.field.angle",
value: ge.locks.angle ?? liveAng,
locked: ge.locks.angle != null,
active: ge.active === "angle",
},
];
return polarFields(ge, gripPolar(ge.anchor, info.raw));
};
// Fixer Bezug (Anker) für Länge/Winkel eines gezogenen Punkt-Griffs. Normal
@@ -621,30 +571,12 @@ export function useGripEditing(opts: {
return refIndex != null ? grips[refIndex] : null;
};
// Die beiden (fixen) Polygon-Nachbarn eines gezogenen Punkt-Griffs — für die
// Flucht-Kandidaten unten. Anders als `neighborGripIndex` (EIN Nachbar,
// reicht für Länge/Winkel-Anker) werden hier BEIDE gebraucht: ein Vielecks-
// Eckpunkt hängt an ZWEI Kanten, jede liefert eine eigene mögliche Flucht-
// Richtung. Kennt geschlossene Ringe (rect/geschlossene Polylinie/Raum/
// Decke — Nachbar 0/n-1 wickelt um) vs. offene Ketten (offene Polylinie/
// Linie — Enden haben nur einen Nachbarn). Kreis/Bogen/Wand/Öffnung/Treppe
// haben keine Polygon-Nachbarn (kein Vielecks-Eckpunkt) → {null,null}.
const ringNeighborPts = (
pts: Vec2[],
i: number,
closed: boolean,
): { prev: Vec2 | null; next: Vec2 | null } => {
const n = pts.length;
const prevIdx = i > 0 ? i - 1 : closed ? n - 1 : null;
const nextIdx = i < n - 1 ? i + 1 : closed ? 0 : null;
return {
prev: prevIdx != null && prevIdx !== i ? pts[prevIdx] : null,
next: nextIdx != null && nextIdx !== i && nextIdx !== prevIdx ? pts[nextIdx] : null,
};
};
const resolvePolygonNeighbors = (index: number): { prev: Vec2 | null; next: Vec2 | null } => {
// Punkte + Ring-Art des Elements eines gezogenen Punkt-Griffs — für die Flucht-Kandidaten des Shift-
// Achsen-Locks (Kern `gripAxisLock`: Welt-H/V plus die Flucht der beiden fixen Nachbarkanten). Geschlossen:
// rect/geschlossene Polylinie/Raum/Decke (Nachbar 0/n-1 wickelt um); offen: Polylinie/Linie. Kreis/Bogen/
// Wand/Öffnung/Treppe haben keine Polygon-Nachbarn → null.
const resolvePolygonRing = (index: number): { pts: Vec2[]; index: number; closed: boolean } | null => {
const owner = gripOwners[index];
const none = { prev: null, next: null };
if (!owner?.drawingId && !owner?.wallId) {
// Raum/Decke (exklusiv) — kein Owner, `localIndex` fehlt dann auch, also
// ist der flache `index` selbst der Ring-Index.
@@ -655,44 +587,18 @@ export function useGripEditing(opts: {
: selectedRoom
? selectedRoom.boundary
: null;
return pts ? ringNeighborPts(pts, owner?.localIndex ?? index, true) : none;
return pts ? { pts, index: owner?.localIndex ?? index, closed: true } : null;
}
if (owner.wallId) return none; // Wand: nur 2 Punkte, kein Vielecks-Nachbar
const d = project.drawings2d.find((x) => x.id === owner.drawingId);
const g = d?.geom;
if (!g) return none;
if (g.shape === "polyline" || g.shape === "spline")
return ringNeighborPts(g.pts, owner.localIndex, !!g.closed);
if (owner.wallId) return null; // Wand: nur 2 Punkte, kein Vielecks-Nachbar
const g = project.drawings2d.find((x) => x.id === owner.drawingId)?.geom;
if (!g) return null;
const i = owner.localIndex;
if (g.shape === "polyline" || g.shape === "spline") return { pts: g.pts, index: i, closed: !!g.closed };
if (g.shape === "rect" || g.shape === "image") {
const corners = [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }];
return ringNeighborPts(corners, owner.localIndex, true);
return { pts: [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }], index: i, closed: true };
}
if (g.shape === "line") return ringNeighborPts([g.a, g.b], owner.localIndex, false);
return none; // circle/arc: kein Vielecks-Eckpunkt
};
// Rohen Cursor `raw` auf die nächstliegende von mehreren Kandidaten-Achsen
// projizieren (jeweils Stützpunkt + Richtung) — "nächstliegend" = kleinster
// senkrechter Abstand von `raw` zur (unendlich verlängerten) Achse. Deckt
// Shift-Ortho (Welt-H/V) UND Flucht-Snap (Richtung anliegender, fixer
// Kanten) in einem einheitlichen Mechanismus ab.
const closestAxisPoint = (raw: Vec2, candidates: { point: Vec2; dir: Vec2 }[]): Vec2 | null => {
let best: Vec2 | null = null;
let bestDist = Infinity;
for (const c of candidates) {
const len = Math.hypot(c.dir.x, c.dir.y);
if (len < 1e-9) continue; // entartete Richtung (koinzidenter Nachbar) → überspringen
const u = { x: c.dir.x / len, y: c.dir.y / len };
const rel = sub(raw, c.point);
const t = rel.x * u.x + rel.y * u.y;
const proj = add(c.point, scale(u, t));
const dist = Math.hypot(raw.x - proj.x, raw.y - proj.y);
if (dist < bestDist) {
bestDist = dist;
best = proj;
}
}
return best;
if (g.shape === "line") return { pts: [g.a, g.b], index: i, closed: false };
return null; // circle/arc: kein Vielecks-Eckpunkt
};
// Stabiler Ref auf cycleGripEditField (der globale Tab-Handler hat leere Deps).
@@ -716,11 +622,8 @@ export function useGripEditing(opts: {
if (!anchor) return; // ohne Anker keine polare Eingabe möglich
setGripEdit((prev) => {
if (!prev) {
const frozen = grips[info.index];
const dx = frozen.x - anchor.x;
const dy = frozen.y - anchor.y;
const angle = ((Math.atan2(dy, dx) * 180) / Math.PI + 360) % 360;
return { anchor, active: "length", locks: { length: Math.hypot(dx, dy), angle } };
const { length, angleDeg: angle } = gripPolar(anchor, grips[info.index]);
return { anchor, active: "length", locks: { length, angle } };
}
const active = prev.active === "length" ? "angle" : "length";
const locks = { ...prev.locks };
@@ -767,19 +670,9 @@ export function useGripEditing(opts: {
// Letzter roher Cursor + der gezogene Kanten-Griff (Momentaufnahme vom Grab).
const edgeDragInfoRef = useRef<{ edge: EdgeGrip; raw: Vec2 } | null>(null);
// Zielpunkt aus Anker + (gelockten/Live-)Werten — bei freien Kanten wie ein
// Punkt-Griff (polar), bei geführten Kanten nur entlang der festen Normale.
const edgeEditPoint = (
edge: EdgeGrip,
anchor: Vec2,
locks: { length?: number; angle?: number },
raw: Vec2,
): Vec2 => {
if (edge.free) return gripEditPoint(anchor, locks, raw);
const live = dot(sub(raw, anchor), edge.normal);
const len = locks.length != null ? locks.length : live;
return add(anchor, scale(edge.normal, len));
};
// Zielpunkt aus Anker (= `edge.mid`) + (gelockten/Live-)Werten — bei freien Kanten wie ein Punkt-Griff
// (polar), bei geführten Kanten nur entlang der festen Normale (Kern `gripEdgeTarget`).
const edgeEditPoint = (edge: EdgeGrip, locks: GripLocks, raw: Vec2): Vec2 => gripEdgeTarget(edge, raw, { locks });
// Felder fürs Befehlsfeld während des Kanten-Drags. Geführte Kanten zeigen
// NUR "Länge" (kein Winkel — der ist durch die feste Normale vorgegeben).
@@ -788,38 +681,11 @@ export function useGripEditing(opts: {
const info = edgeDragInfoRef.current;
if (!ee || !info) return [];
const { edge, raw } = info;
const live = gripPolar(ee.anchor, raw, edge.normal);
if (!edge.free) {
const live = dot(sub(raw, ee.anchor), edge.normal);
return [
{
id: "length",
labelKey: "cmd.field.length",
value: ee.locks.length ?? live,
locked: ee.locks.length != null,
active: true,
},
];
return [{ id: "length", labelKey: "cmd.field.length", value: ee.locks.length ?? live.offset, locked: ee.locks.length != null, active: true }];
}
const dx = raw.x - ee.anchor.x;
const dy = raw.y - ee.anchor.y;
const liveLen = Math.hypot(dx, dy);
const liveAng = ((((Math.atan2(dy, dx) * 180) / Math.PI) % 360) + 360) % 360;
return [
{
id: "length",
labelKey: "cmd.field.length",
value: ee.locks.length ?? liveLen,
locked: ee.locks.length != null,
active: ee.active === "length",
},
{
id: "angle",
labelKey: "cmd.field.angle",
value: ee.locks.angle ?? liveAng,
locked: ee.locks.angle != null,
active: ee.active === "angle",
},
];
return polarFields(ee, live);
};
const cycleEdgeEditFieldRef = useRef<() => void>(() => {});
@@ -835,15 +701,9 @@ export function useGripEditing(opts: {
setEdgeEdit((prev) => {
if (!prev) {
const anchor = edge.mid;
const frozen = edgeEditPoint(edge, anchor, {}, raw);
const dx = frozen.x - anchor.x;
const dy = frozen.y - anchor.y;
if (edge.free) {
const angle = ((Math.atan2(dy, dx) * 180) / Math.PI + 360) % 360;
return { anchor, active: "length", locks: { length: Math.hypot(dx, dy), angle } };
}
const offset = dx * edge.normal.x + dy * edge.normal.y;
return { anchor, active: "length", locks: { length: offset } };
const frozen = gripPolar(anchor, edgeEditPoint(edge, {}, raw), edge.normal);
if (edge.free) return { anchor, active: "length", locks: { length: frozen.length, angle: frozen.angleDeg } };
return { anchor, active: "length", locks: { length: frozen.offset } };
}
if (!edge.free) return prev; // geführte Kante: nur ein Feld, nichts zu zykeln
const active = prev.active === "length" ? "angle" : "length";
@@ -877,7 +737,7 @@ export function useGripEditing(opts: {
const locks = { ...ee.locks, [ee.active]: value };
const next = edge.free ? (ee.active === "length" ? "angle" : "length") : ee.active;
setEdgeEdit({ ...ee, locks, active: next });
const pt = edgeEditPoint(edge, ee.anchor, locks, raw);
const pt = edgeEditPoint(edge, locks, raw);
applyEdgeToward(edge, ee.anchor, pt);
};
@@ -906,16 +766,8 @@ export function useGripEditing(opts: {
return;
}
const w = op && project.walls.find((x) => x.id === op.hostWallId);
if (op && w) {
const d = sub(w.end, w.start);
const len = Math.hypot(d.x, d.y);
if (len > 1e-9) {
const axis = scale(d, 1 / len);
const t = dot(sub(pt, w.start), axis);
const pos = Math.max(0, Math.min(len - op.width, t - op.width / 2));
updateOpening(op.id, { position: pos });
}
}
const pos = op && w ? openingSlidePosition(w, op, pt) : null;
if (op && pos != null) updateOpening(op.id, { position: pos });
return;
}
// Treppe: den Bewegpunkt verfolgen → ganze Treppe um das Delta (Ziel −
@@ -1135,23 +987,16 @@ export function useGripEditing(opts: {
const hudFor = (index: number, pt: Vec2): NonNullable<ToolDraft["hud"]> | undefined => {
const anchor = resolveGripAnchor(index);
if (!anchor) return undefined;
const dx = pt.x - anchor.x;
const dy = pt.y - anchor.y;
const angleDeg = ((Math.atan2(dy, dx) * 180) / Math.PI + 360) % 360;
return { at: pt, length: Math.hypot(dx, dy), angleDeg };
const { length, angleDeg } = gripPolar(anchor, pt);
return { at: pt, length, angleDeg };
};
// Dasselbe für einen gezogenen Kanten-Griff: freie Kanten zeigen Länge+Winkel
// (wie ein Punkt-Griff), geführte Kanten nur EINEN Wert (Abstand entlang der
// Normale) — dafür reicht das HUD-Schema nicht (length+angleDeg gehören
// zusammen), daher als freier Text `Δ: …m`.
const edgeHudFor = (edge: EdgeGrip, anchor: Vec2, pt: Vec2): NonNullable<ToolDraft["hud"]> => {
const dx = pt.x - anchor.x;
const dy = pt.y - anchor.y;
if (edge.free) {
const angleDeg = ((Math.atan2(dy, dx) * 180) / Math.PI + 360) % 360;
return { at: pt, length: Math.hypot(dx, dy), angleDeg };
}
const offset = dx * edge.normal.x + dy * edge.normal.y;
const { length, angleDeg, offset } = gripPolar(anchor, pt, edge.normal);
if (edge.free) return { at: pt, length, angleDeg };
return { at: pt, text: `Δ: ${offset.toFixed(3)}m` };
};
@@ -1235,15 +1080,11 @@ export function useGripEditing(opts: {
const op = (project.openings ?? []).find((o) => o.id === openingId);
const w = op && project.walls.find((x) => x.id === op.hostWallId);
if (!op || !w || op.locked) return;
const axis = normalize(sub(w.end, w.start));
const factor = dot(sh.uAxis, axis);
if (Math.abs(factor) < 0.15) return;
const prevDu = sheetDuRef.current && sheetDuRef.current.id === openingId ? sheetDuRef.current.du : 0;
const len = Math.hypot(w.end.x - w.start.x, w.end.y - w.start.y);
// Auf die Wand klemmen (Öffnung bleibt drin) — auch die Vorschau.
const rawPos = op.position + (prevDu + delta.x) * factor;
const pos = Math.max(0, Math.min(len - op.width, rawPos));
const du = (pos - op.position) / factor;
// Auf die Wand geklemmt (Öffnung bleibt drin) — auch die Vorschau.
const slide = openingSheetSlide(w, op, sh.uAxis, prevDu + delta.x);
if (!slide) return;
const { position: pos, du } = slide;
sheetDuRef.current = { id: openingId, du };
pendingOpeningMoveRef.current = { id: openingId, position: pos };
const preview: DraftShape[] = sheetOwnerOutlines(sh.levelId, "opening", openingId).map((pts) => ({
@@ -1260,23 +1101,9 @@ export function useGripEditing(opts: {
if (!modelEditable && sheet) {
const g = sheetHeightGrips[index];
if (!g) return;
const v = mods.ctrl ? raw.y : Math.round(raw.y * 100) / 100; // 1-cm-Raster, Strg = frei
let newTop = g.top;
let newBottom = g.bottom;
if (g.kind === "wallTop") {
newTop = Math.max(g.base + 0.3, v);
pendingSheetHeightRef.current = { kind: "wall", id: g.id, patch: { height: Math.round((newTop - g.base) * 1000) / 1000 } };
} else if (g.kind === "openingTop") {
newTop = Math.max(g.bottom + 0.2, v);
pendingSheetHeightRef.current = { kind: "opening", id: g.id, patch: { height: Math.round((newTop - g.bottom) * 1000) / 1000 } };
} else {
newBottom = Math.min(g.top - 0.2, Math.max(g.base, v));
pendingSheetHeightRef.current = {
kind: "opening",
id: g.id,
patch: { sillHeight: Math.round((newBottom - g.base) * 1000) / 1000, height: Math.round((g.top - newBottom) * 1000) / 1000 },
};
}
// 1-cm-Raster, Strg = frei; Mindestmasse und mm-Rundung im Kern (`sheetHeightDrag`).
const { top: newTop, bottom: newBottom, patch } = sheetHeightDrag(g.kind, g, raw.y, !!mods.ctrl);
pendingSheetHeightRef.current = { kind: g.kind === "wallTop" ? "wall" : "opening", id: g.id, patch };
const bottom = g.kind === "wallTop" ? g.bottom : newBottom;
setDraft({
preview: [{
@@ -1327,17 +1154,9 @@ export function useGripEditing(opts: {
// dominiert (kein Snap), damit die Endkoordinate garantiert eine Achse
// trifft — identisch zum bisherigen Ortho-Verhalten.
if (mods.shift && anchor) {
const candidates: { point: Vec2; dir: Vec2 }[] = [
{ point: anchor, dir: { x: 1, y: 0 } },
{ point: anchor, dir: { x: 0, y: 1 } },
];
const origin = gripOriginRef.current;
if (origin) {
const { prev, next } = resolvePolygonNeighbors(index);
if (prev) candidates.push({ point: prev, dir: sub(origin, prev) });
if (next) candidates.push({ point: next, dir: sub(next, origin) });
}
const pt = closestAxisPoint(raw, candidates) ?? applyAngleConstraint(anchor, raw, 90);
const ring = origin ? resolvePolygonRing(index) : null;
const pt = gripAxisLock(raw, anchor, origin, ring?.pts ?? null, ring?.index ?? -1, ring?.closed ?? false);
applyGrip(index, pt);
setDraft({ preview: gripPreviewShapes(), vertices: [], snap: null, hud: hudFor(index, pt) });
return;
@@ -1475,49 +1294,27 @@ export function useGripEditing(opts: {
// `locks` ist ab dem Öffnen (Tab) immer befüllt (s. cycleEdgeEditField),
// die Maus wirkt also erst wieder, sobald ein Feld per Tab gelöst wurde.
if (ee && (ee.locks.length != null || ee.locks.angle != null)) {
const pt = edgeEditPoint(edge, anchor, ee.locks, raw);
const pt = edgeEditPoint(edge, ee.locks, raw);
applyEdgeToward(edge, anchor, pt);
setDraft({ preview: edgePreviewShapes(), vertices: [], snap: null, hud: edgeHudFor(edge, anchor, pt) });
return;
}
// Raster nur ohne Strg und bei eingeschaltetem Raster-Snap.
const grid = !mods.ctrl && snap.enabled && snap.grid && snap.gridSize > 0 ? snap.gridSize : 0;
if (edge.free) {
// Keine Geometrie-Snap-Projektion (keine feste Kanten-Normale, an die
// sich ein gefangener Punkt anlehnen könnte) — der Cursor bewegt den
// Zielpunkt direkt, nur Ortho/Raster wirken.
let pt = raw;
if (mods.shift) {
const dx = raw.x - anchor.x;
const dy = raw.y - anchor.y;
pt = Math.abs(dx) >= Math.abs(dy) ? { x: raw.x, y: anchor.y } : { x: anchor.x, y: raw.y };
}
const gs = snap.gridSize;
if (!mods.ctrl && snap.enabled && snap.grid && gs > 0) {
const dx = Math.round((pt.x - anchor.x) / gs) * gs;
const dy = Math.round((pt.y - anchor.y) / gs) * gs;
pt = { x: anchor.x + dx, y: anchor.y + dy };
}
// Keine Geometrie-Snap-Projektion (keine feste Kanten-Normale, an die sich ein gefangener Punkt
// anlehnen könnte) — der Cursor bewegt den Zielpunkt direkt, nur Ortho/Raster wirken (Kern).
const pt = gripEdgeTarget(edge, raw, { shift: mods.shift, grid });
applyEdgeToward(edge, anchor, pt);
setDraft({ preview: edgePreviewShapes(), vertices: [], snap: null, hud: edgeHudFor(edge, anchor, pt) });
return;
}
// Cursor zuerst durch die Snap-Engine schicken (Ctrl unterdrückt Snap
// wie überall sonst, siehe computeSnap). Ein GEOMETRIE-Snap (Endpunkt/
// Mittelpunkt/Schnittpunkt/…, nicht Raster/Ortho) liefert den gefangenen
// Punkt, der dann auf die Außennormale projiziert wird — so rastet die
// Kante an reale Geometrie statt nur ans Raster.
// Cursor zuerst durch die Snap-Engine schicken (Ctrl unterdrückt Snap wie überall sonst, siehe
// computeSnap). Ein GEOMETRIE-Snap (Endpunkt/Mittelpunkt/Schnittpunkt/…, nicht Raster/Ortho) liefert den
// gefangenen Punkt, den der Kern auf die Aussennormale projiziert (vor dem Raster).
const snapResult = snapFor(raw, pxPerMeter, mods);
const isGeometrySnap = !!snapResult && snapResult.kind !== "grid" && snapResult.kind !== "ortho";
const cursor = isGeometrySnap ? snapResult!.point : raw;
// Senkrechte Projektion von (Cursor − Anker) auf die Außennormale.
const rel = sub(cursor, anchor);
let offset = rel.x * edge.normal.x + rel.y * edge.normal.y;
// Raster-Schritt (Snap) nur, wenn kein Geometrie-Snap gefangen wurde —
// sonst gewinnt der gefangene Punkt.
const step = snap.gridSize;
if (!isGeometrySnap && !mods.ctrl && snap.enabled && snap.grid && step > 0) {
offset = Math.round(offset / step) * step;
}
const pt = add(anchor, scale(edge.normal, offset));
const pt = gripEdgeTarget(edge, raw, { grid, snapped: isGeometrySnap ? snapResult!.point : null });
applyEdgeToward(edge, anchor, pt);
setDraft({
preview: edgePreviewShapes(),