[K4] S3: Transformation und 2D-Editier-Befehle im Kern (cmd_transform.rs, cmd_edit.rs)
Verschieben/Drehen/Spiegeln/Skalieren/Reihe (alle Elementarten, Vorschau je Mausschritt), Ausrichten/Verteilen, Block definieren, Trim, Extend, Verrunden, Fasen, Bruch, Offset, Join, Auflösen rechnen Treffer, Vorschau und Ops im Kern; TS behält die Zustandsautomaten. cmdMutation + doc_cmd_commit: rechnen und anwenden in einem Kern-Aufruf. Gelöscht: geometry/geomTransform.ts, tools/drawingPreview.ts, transformSolid, joinDrawings und die nicht mehr benutzten Kernel-Fassaden samt Bindungen. Gleichheit über Zufallsprojekte (temporäre Tests, gelöscht) s. TODO.md.
This commit is contained in:
45 files changed
+2612
-2620
No files matched your search
@@ -676,6 +676,39 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
zusammenlegen); `wallCorners` (Plan-Treffer `planHitTest`, Werkzeug-Vorschau, Griff-Vorschau, `voids`, STEP-Export — ein
|
||||
Kern-Aufruf je Wand wäre teurer als die vier Punkte) und `wallReferenceOffset` (Fang, `geometry/opening.ts`). Nicht in
|
||||
der Tauri-App geprüft (3D-Griffe nur über e2e im Browser).
|
||||
**Befehle im Kern (29.10.)** — Transformation und 2D-Editier-Befehle: `commands.rs` (Anfrage `{cmd, …}` →
|
||||
Ops; Wurzel-Abfrage `cmdOps`, `doc_cmd_commit` rechnet UND wendet in einem Kern-Aufruf an, `doc_cmd_query` für
|
||||
Treffer/Vorschau zwischen den Schritten), `cmd_transform.rs` (Verschieben/Drehen/Spiegeln/Skalieren mit
|
||||
Kopie/Reihe/Verteilen für alle Elementarten inkl. B-Rep-Körper, Ausrichten/Verteilen, Block definieren,
|
||||
Vorschau-Formen je Mausschritt `doc_cmd_preview` inkl. Zeichnungs-Primitive und Text-Rahmen),
|
||||
`cmd_edit.rs` (Trim, Extend, Verrunden, Fasen, Bruch, Offset, Join, Auflösen: Treffer, Vorschau, Ops). Die
|
||||
Abbildung reist als affine Beschreibung (`Xf`: Verschiebung/Drehung/Skalierung/Spiegelung — keine allgemeine
|
||||
Matrix, weil sonst die Rechenreihenfolge und damit die Bits nicht mehr der TS-Fassung entsprächen). TS:
|
||||
Zustandsautomaten bleiben, `cmdMutation(req)` (`core/document.ts`) trägt die Anfrage; `setProject` wendet sie
|
||||
über `commitCmd` direkt im Kern an. Neue ids `prefix-Zeit-Zähler-k` (`uniqueStamp`). Gelöscht:
|
||||
`geometry/geomTransform.ts` (`mvGeom`/`scaleGeom`/`scaleFactor`/`reversesOrientation`),
|
||||
`tools/drawingPreview.ts`, `transformSolid`, die TS-Rechnung in `tools/transform.ts`, `editors/align.ts`,
|
||||
`editors/explode.ts`, `defblock`, `trim`/`extend`/`fillet`/`chamfer`/`break`/`offset`/`join`,
|
||||
`joinDrawings`, die nicht mehr benutzten Kernel-Fassaden (`trimPolyline(WithBulge)`, `extend(Bulge)Segment`,
|
||||
`chamferCorner`, `breakCurve`, `nearestOnPolyline`, `offsetPolyline(WithBulge)`, `joinChainsWithBulge`) samt
|
||||
Bindungen und TS-Tests (die Rust-Tests in `kernel2d` und die Befehls-Tests decken sie). Gleichheit (temporäre
|
||||
Tests, gelöscht): 2400 Transformationen über 600 Zufallsprojekte (alle Bauteilarten, 18 Zeichnungs-Formen,
|
||||
Sperren, Dächer bei Drehen/Spiegeln, B-Rep, NaN-Punkte, LV95) — Ops zeichengleich (bis auf ids), 219 000
|
||||
Vorschau-Formen bitgleich, Griff-Vorschauen; 4500 Ausrichten/Verteilen/Block; Editier-Befehle über 500
|
||||
Zufallsprojekte mit denselben Eingabe-Folgen (Entwürfe je Mausschritt und Commits bitgleich): 2213 Trim,
|
||||
1460 Extend, 219 Verrunden, 227 Fasen, 605 Bruch, 1241 Offset, 423 Join, 486 Auflösen. Messung (vitest/WASM
|
||||
`--no-opt`, Container unter starker Last, Werte schwanken ±50 %): Vorschau 300 Zeichnungen verschieben
|
||||
22 → 6 ms, drehen 22 → 8 ms; 300 Wände 0,4–0,9 → 0,5 ms (gleich); Store „300 Wände verschieben“ 8,5 → 10,9 ms
|
||||
(Minimum, im Rauschen; die Kosten liegen beim Klonen der JSON-Elemente im Kern statt beim JSON-Lesen).
|
||||
Abweichung (gewollt): Griff-Vorschau „Element verschieben“ zeigt bei Formen ohne Primitive die einfachen
|
||||
Ersatz-Formen wie die Transformations-Vorschau. Nicht in der Tauri-App geprüft.
|
||||
**Offen (S3, Befehle):** Zeichenbefehle (Wand, Decke, Raum, Treppe, Öffnung, Dach, Stütze, Extrusion, alle
|
||||
2D-Formen, Bemassung, autodim, sectionline, solid/solidbool/voidbox/terrain, ceilingOpening) und die
|
||||
Werkzeug-Commits in `tools/tools.ts` bauen ihre Elemente noch in TS (meist ein Objekt-Literal aus den
|
||||
Klickpunkten); Einfügen (`pasteElementClipboard`), Gruppen-Zuordnung (`activeGroupOps`); Split/Segment
|
||||
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`.
|
||||
- ◐ **S4 Typen aus Rust**: `types.ts` wird aus den Rust-Strukturen erzeugt (ts-rs); Datei-I/O (`projectFormat`, Migration, IFC/DXF/
|
||||
STEP-Ex- und -Import) im Kern.
|
||||
**Typen (28.10.):** Das Rust-Modell (`core/src/model/generated.rs`, `manual.rs`) ist die Quelle; ts-rs 12 (MIT, nur
|
||||
|
||||
@@ -0,0 +1,984 @@
|
||||
//! Editier-Befehle der 2D-Zeichnungen im Kern ([K4] S3, vorher `commands/cmds/{trim,extend,fillet,
|
||||
//! chamfer,break,offset,join}.ts` und `editors/explode.ts`): Treffer-Bestimmung (Kurve, offene Kurve,
|
||||
//! Ecke), die Vorschau-Formen je Mausschritt und die Ops des Commits. Die Geometrie selbst steht in
|
||||
//! `kernel2d` (Trim/Extend mit Bögen, Verrundung, Fasung, Bruch, Offset, Verketten); hier die
|
||||
//! Übersetzung Zeichnung ↔ Kurve, die Auswahl und die Elemente des Ergebnisses.
|
||||
//!
|
||||
//! Rechnung auf der rohen Projekt-Wurzel (Attribute der Quelle bleiben samt Schlüsselreihenfolge;
|
||||
//! unveränderte Punkte werden als dieselben JSON-Werte übernommen wie das Array-Spreizen in TS).
|
||||
|
||||
use crate::cmd_transform::{IdGen, Shapes};
|
||||
use crate::grips::{arr, field, js_num, num_of, num_or, pt, truthy, with, with_all, 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};
|
||||
|
||||
/// Pick-Toleranz für Kurven (Modell-Meter).
|
||||
const HIT_TOL: f64 = 0.25;
|
||||
/// Pick-Toleranz für Ecken (Verrunden/Fasen).
|
||||
const CORNER_TOL: f64 = 0.3;
|
||||
/// Punkt-Gleichheit (`kernel2d::EPS`, `vecEqual`).
|
||||
const EPS_EQ: f64 = 1e-7;
|
||||
/// Echter Bogen ab diesem |bulge| (`hasRealBulge`).
|
||||
const EPS_BULGE: f64 = 1e-9;
|
||||
/// Mindest-Radius/-Distanz der Vorschau (Verrunden/Fasen).
|
||||
const EPS_R: f64 = 1e-6;
|
||||
|
||||
// ── Kurven ───────────────────────────────────────────────────────────────────
|
||||
|
||||
fn p_of(v: &Value) -> P {
|
||||
let (x, y) = xy(v);
|
||||
P::new(x, y)
|
||||
}
|
||||
|
||||
fn ptv(p: P) -> Value {
|
||||
pt(p.x, p.y)
|
||||
}
|
||||
|
||||
fn shape(g: &Value) -> &str {
|
||||
field(g, "shape").and_then(Value::as_str).unwrap_or("")
|
||||
}
|
||||
|
||||
fn geom(d: &Value) -> &Value {
|
||||
field(d, "geom").unwrap_or(&Value::Null)
|
||||
}
|
||||
|
||||
fn level_of(d: &Value) -> Option<&str> {
|
||||
field(d, "levelId").and_then(Value::as_str)
|
||||
}
|
||||
|
||||
fn drawings(root: &Map<String, Value>) -> &[Value] {
|
||||
arr(root.get("drawings2d"))
|
||||
}
|
||||
|
||||
fn find<'a>(root: &'a Map<String, Value>, id: &str) -> Option<&'a Value> {
|
||||
drawings(root).iter().find(|d| id_of(d) == Some(id))
|
||||
}
|
||||
|
||||
/// Bogen-Werte wie `encBulge` (`b ?? 0`).
|
||||
fn nums(b: &[Value]) -> Vec<f64> {
|
||||
b.iter().map(|x| num_of(Some(x))).collect()
|
||||
}
|
||||
|
||||
fn real(b: &[f64]) -> bool {
|
||||
b.iter().any(|x| x.abs() > EPS_BULGE)
|
||||
}
|
||||
|
||||
/// Eine Zeichnung als Kurve: Punkte (roh und als Zahlen), geschlossen, Bogen-Werte (roh).
|
||||
#[derive(Clone)]
|
||||
struct Curve {
|
||||
pts: Vec<P>,
|
||||
raw: Vec<Value>,
|
||||
closed: bool,
|
||||
/// `closed` wie in der Quelle (fehlend = `None`), für Ergebnisse `closed: curve.closed`.
|
||||
closed_raw: Option<Value>,
|
||||
bulge: Option<Vec<Value>>,
|
||||
}
|
||||
|
||||
impl Curve {
|
||||
fn bulge_nums(&self) -> Vec<f64> {
|
||||
self.bulge.as_deref().map(nums).unwrap_or_default()
|
||||
}
|
||||
fn has_bulge(&self) -> bool {
|
||||
real(&self.bulge_nums())
|
||||
}
|
||||
fn of_pts(pts: Vec<P>, closed: bool, bulge: Option<&[f64]>) -> Curve {
|
||||
Curve {
|
||||
raw: pts.iter().map(|p| ptv(*p)).collect(),
|
||||
pts,
|
||||
closed,
|
||||
closed_raw: Some(Value::Bool(closed)),
|
||||
bulge: bulge.map(|b| b.iter().map(|x| js_num(*x)).collect()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Welche Formen ein Befehl als Kurve nimmt.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Take {
|
||||
/// Linie, Polylinie (mit Bögen), Rechteck (Trim, Bruch, Offset).
|
||||
Curve,
|
||||
/// Linie, offene Polylinie (mit Bögen) (Extend).
|
||||
Open,
|
||||
/// Polylinie ohne Bögen, Rechteck (Verrunden, Fasen).
|
||||
Corner,
|
||||
}
|
||||
|
||||
fn rect_curve(g: &Value) -> Curve {
|
||||
let (min, max) = (field(g, "min").cloned().unwrap_or(Value::Null), field(g, "max").cloned().unwrap_or(Value::Null));
|
||||
let (a, b) = (p_of(&min), p_of(&max));
|
||||
let raw = vec![min, pt(b.x, a.y), max, pt(a.x, b.y)];
|
||||
Curve { pts: raw.iter().map(p_of).collect(), raw, closed: true, closed_raw: Some(Value::Bool(true)), bulge: None }
|
||||
}
|
||||
|
||||
fn curve(g: &Value, take: Take) -> Option<Curve> {
|
||||
let poly = || {
|
||||
let raw: Vec<Value> = arr(field(g, "pts")).to_vec();
|
||||
let bulge = field(g, "bulge").and_then(Value::as_array).cloned();
|
||||
Curve { pts: raw.iter().map(p_of).collect(), raw, closed: truthy(field(g, "closed")), closed_raw: field(g, "closed").cloned(), bulge }
|
||||
};
|
||||
match (shape(g), take) {
|
||||
("line", Take::Curve | Take::Open) => {
|
||||
let raw = vec![field(g, "a").cloned().unwrap_or(Value::Null), field(g, "b").cloned().unwrap_or(Value::Null)];
|
||||
Some(Curve { pts: raw.iter().map(p_of).collect(), raw, closed: false, closed_raw: Some(Value::Bool(false)), bulge: None })
|
||||
}
|
||||
("polyline", Take::Curve) => Some(poly()),
|
||||
("polyline", Take::Open) => (!truthy(field(g, "closed"))).then(poly),
|
||||
("polyline", Take::Corner) => Some(poly()).filter(|c| !c.has_bulge()),
|
||||
("rect", Take::Curve | Take::Corner) => Some(rect_curve(g)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `polylineEdges`: Kanten als Paare (Schlusskante bei `closed` und mehr als zwei Punkten).
|
||||
fn polyline_edges(pts: &[P], closed: bool) -> Vec<(P, P)> {
|
||||
let mut out: Vec<(P, P)> = pts.windows(2).map(|w| (w[0], w[1])).collect();
|
||||
if closed && pts.len() > 2 {
|
||||
out.push((pts[pts.len() - 1], pts[0]));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `bulgePolylinePoints` über dieselbe Hülle wie die Bindung (nicht endliche Punkte → leer).
|
||||
fn bulge_points(pts: &[P], bulge: &[f64], closed: bool) -> Vec<P> {
|
||||
let flat: Vec<f64> = pts.iter().flat_map(|p| [p.x, p.y]).collect();
|
||||
crate::bulge::polyline_points(&flat, bulge, closed).chunks_exact(2).map(|c| P::new(c[0], c[1])).collect()
|
||||
}
|
||||
|
||||
/// Trefferkanten: Bögen tesselliert (Klick-/Seiten-Tests entlang der echten Kontur).
|
||||
fn hit_edges(c: &Curve) -> Vec<(P, P)> {
|
||||
let b = c.bulge_nums();
|
||||
if !real(&b) {
|
||||
return polyline_edges(&c.pts, c.closed);
|
||||
}
|
||||
let mut chain = bulge_points(&c.pts, &b, c.closed);
|
||||
if c.closed {
|
||||
if let Some(p0) = c.pts.first() {
|
||||
chain.push(*p0);
|
||||
}
|
||||
}
|
||||
polyline_edges(&chain, false)
|
||||
}
|
||||
|
||||
/// Kanten → Punktfolge (`[e0.a, e0.b, e1.b, …]`).
|
||||
fn chain_of(edges: &[(P, P)]) -> Vec<P> {
|
||||
let mut out = Vec::with_capacity(edges.len() + 1);
|
||||
for (i, (a, b)) in edges.iter().enumerate() {
|
||||
if i == 0 {
|
||||
out.push(*a);
|
||||
}
|
||||
out.push(*b);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn tuples(pts: &[P]) -> Vec<(f64, f64)> {
|
||||
pts.iter().map(|p| (p.x, p.y)).collect()
|
||||
}
|
||||
|
||||
/// Nächste Kurve der Ebene zum Punkt (innerhalb `HIT_TOL`).
|
||||
fn pick_curve<'a>(root: &'a Map<String, Value>, level: &str, at: P, take: Take) -> Option<&'a Value> {
|
||||
let mut best = None;
|
||||
let mut best_d = HIT_TOL;
|
||||
for d in drawings(root) {
|
||||
if level_of(d) != Some(level) {
|
||||
continue;
|
||||
}
|
||||
let Some(c) = curve(geom(d), take) else { continue };
|
||||
for (a, b) in hit_edges(&c) {
|
||||
let dd = k::point_segment_distance(at, a, b);
|
||||
if dd < best_d {
|
||||
best_d = dd;
|
||||
best = Some(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Kette → Zeichengeometrie (`chainToGeom`/`fromPolyForm`): zwei Punkte offen ohne Bogen = Linie.
|
||||
fn chain_geom(pts: Vec<Value>, closed: Value, bulge: Option<Vec<Value>>) -> Value {
|
||||
let b = bulge.as_deref().map(nums).unwrap_or_default();
|
||||
let mut m = Map::new();
|
||||
if pts.len() == 2 && !truthy(Some(&closed)) && !real(&b) {
|
||||
m.insert("shape".into(), "line".into());
|
||||
let mut it = pts.into_iter();
|
||||
m.insert("a".into(), it.next().unwrap_or(Value::Null));
|
||||
m.insert("b".into(), it.next().unwrap_or(Value::Null));
|
||||
return Value::Object(m);
|
||||
}
|
||||
m.insert("shape".into(), "polyline".into());
|
||||
m.insert("pts".into(), Value::Array(pts));
|
||||
m.insert("closed".into(), closed);
|
||||
if real(&b) {
|
||||
m.insert("bulge".into(), Value::Array(bulge.unwrap_or_default()));
|
||||
}
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
fn pts_v(pts: &[P]) -> Vec<Value> {
|
||||
pts.iter().map(|p| ptv(*p)).collect()
|
||||
}
|
||||
|
||||
fn bulge_v(b: &[f64]) -> Vec<Value> {
|
||||
b.iter().map(|x| js_num(*x)).collect()
|
||||
}
|
||||
|
||||
/// `{...src, id, geom}`.
|
||||
fn copy_with(src: &Value, id: String, geom: Value) -> Value {
|
||||
with_all(src, vec![("id", Value::String(id)), ("geom", geom)])
|
||||
}
|
||||
|
||||
fn remove(ids: Vec<String>) -> Op {
|
||||
Op::Remove { collection: "drawings2d".into(), ids }
|
||||
}
|
||||
|
||||
fn add(items: Vec<Value>) -> Option<Op> {
|
||||
(!items.is_empty()).then(|| Op::Add { collection: "drawings2d".into(), items, at: None })
|
||||
}
|
||||
|
||||
fn replace(entity: Value) -> Op {
|
||||
Op::Replace { collection: "drawings2d".into(), entity }
|
||||
}
|
||||
|
||||
/// `{...first(id), geom}` als Ersetzung (`patchItem`).
|
||||
fn patch_geom(root: &Map<String, Value>, id: &str, g: Value) -> Vec<Op> {
|
||||
find(root, id).map(|d| vec![replace(with(d, "geom", g))]).unwrap_or_default()
|
||||
}
|
||||
|
||||
// ── Trim ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Schneider des Trims: alle anderen Kurven der Ebene des Ziels (Bögen zählen mit).
|
||||
fn trim_rest(root: &Map<String, Value>, target: &Value, at: P) -> Option<(Curve, Vec<k::BulgePolyline>)> {
|
||||
let c = curve(geom(target), Take::Curve)?;
|
||||
let (tid, level) = (id_of(target), level_of(target));
|
||||
let cutters: Vec<k::BulgePolyline> = drawings(root)
|
||||
.iter()
|
||||
.filter(|d| id_of(d) != tid && level_of(d) == level && level.is_some())
|
||||
.filter_map(|d| curve(geom(d), Take::Curve))
|
||||
.map(|c| k::BulgePolyline { bulge: c.bulge_nums(), pts: c.pts, closed: c.closed })
|
||||
.collect();
|
||||
let rest = k::trim_polyline_with_bulge(&c.pts, &c.bulge_nums(), c.closed, &cutters, at);
|
||||
Some((c, rest))
|
||||
}
|
||||
|
||||
fn same_chain(a: &k::BulgePolyline, b: &Curve) -> bool {
|
||||
a.closed == b.closed && a.pts.len() == b.pts.len() && a.pts.iter().zip(&b.pts).all(|(p, q)| k::vec_equal(*p, *q, EPS_EQ))
|
||||
}
|
||||
|
||||
/// Trim: das getroffene Stück von Zeichnung `id` entfällt, die Reste ersetzen sie (hinten angehängt).
|
||||
pub fn trim_ops(root: &Map<String, Value>, id: &str, at: P, ids: &mut IdGen) -> Vec<Op> {
|
||||
let Some(target) = find(root, id) else { return vec![] };
|
||||
let Some((c, rest)) = trim_rest(root, target, at) else { return vec![] };
|
||||
if rest.len() == 1 && same_chain(&rest[0], &c) {
|
||||
return vec![];
|
||||
}
|
||||
let parts: Vec<Value> = rest
|
||||
.iter()
|
||||
.filter(|r| r.pts.len() >= 2)
|
||||
.map(|r| copy_with(target, ids.next("dr2d"), chain_geom(pts_v(&r.pts), Value::Bool(r.closed), Some(bulge_v(&r.bulge)))))
|
||||
.collect();
|
||||
let mut ops = vec![remove(vec![id.to_string()])];
|
||||
ops.extend(add(parts));
|
||||
ops
|
||||
}
|
||||
|
||||
/// Vorschau des Trims am Punkt: die verbleibenden Ketten der getroffenen Kurve.
|
||||
pub fn trim_preview(root: &Map<String, Value>, level: &str, at: P, out: &mut Shapes) -> bool {
|
||||
let Some(target) = pick_curve(root, level, at, Take::Curve) else { return false };
|
||||
let Some((_, rest)) = trim_rest(root, target, at) else { return true };
|
||||
for r in rest.iter().filter(|r| r.pts.len() >= 2) {
|
||||
let pts = if real(&r.bulge) { chain_of(&hit_edges(&Curve::of_pts(r.pts.clone(), r.closed, Some(&r.bulge)))) } else { r.pts.clone() };
|
||||
if pts.len() == 2 && !r.closed {
|
||||
out.line((pts[0].x, pts[0].y), (pts[1].x, pts[1].y));
|
||||
} else if r.closed {
|
||||
out.poly(&tuples(&pts));
|
||||
} else {
|
||||
out.poly_open(&tuples(&pts));
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
// ── Extend ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Schneider der Verlängerung: Linien, Polylinien ohne Bögen und Rechtecke der Ebene (ausser dem Ziel).
|
||||
fn extend_cutters(root: &Map<String, Value>, target: &Value) -> Vec<k::Polyline> {
|
||||
let (tid, level) = (id_of(target), level_of(target));
|
||||
let mut out = Vec::new();
|
||||
for d in drawings(root) {
|
||||
if id_of(d) == tid || level_of(d) != level || level.is_none() {
|
||||
continue;
|
||||
}
|
||||
let g = geom(d);
|
||||
match shape(g) {
|
||||
"line" => out.push(k::Polyline { pts: vec![p_of(field(g, "a").unwrap_or(&Value::Null)), p_of(field(g, "b").unwrap_or(&Value::Null))], closed: false }),
|
||||
"polyline" => {
|
||||
let c = curve(g, Take::Curve).expect("Polylinie");
|
||||
if !c.has_bulge() {
|
||||
out.push(k::Polyline { pts: c.pts, closed: c.closed });
|
||||
}
|
||||
}
|
||||
"rect" => {
|
||||
let c = rect_curve(g);
|
||||
out.push(k::Polyline { pts: c.pts, closed: true });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Verlängert das dem Punkt nähere Ende bis zum nächsten Schneider (Bogen-Ende: gleicher Kreis).
|
||||
fn extend_curve(c: &Curve, cutters: &[k::Polyline], at: P) -> Option<Curve> {
|
||||
let n = c.pts.len();
|
||||
if n < 2 {
|
||||
return None;
|
||||
}
|
||||
let ds = hypot2(at.x - c.pts[0].x, at.y - c.pts[0].y);
|
||||
let de = hypot2(at.x - c.pts[n - 1].x, at.y - c.pts[n - 1].y);
|
||||
let start = ds <= de;
|
||||
let seg = if start { 0 } else { n - 2 };
|
||||
let bv = num_or(c.bulge.as_ref().and_then(|b| b.get(seg)), 0.0);
|
||||
let mut next = c.clone();
|
||||
next.closed = false;
|
||||
if bv.abs() > EPS_BULGE {
|
||||
let (p, b) = k::extend_bulge_segment(c.pts[seg], c.pts[seg + 1], bv, !start, cutters)?;
|
||||
let mut bulge = c.bulge.clone().unwrap_or_else(|| vec![Value::from(0); n - 1]);
|
||||
let (pi, bi) = if start { (0, 0) } else { (n - 1, n - 2) };
|
||||
next.raw[pi] = ptv(p);
|
||||
next.pts[pi] = p;
|
||||
if bi >= bulge.len() {
|
||||
bulge.resize(bi + 1, Value::Null);
|
||||
}
|
||||
bulge[bi] = js_num(b);
|
||||
next.bulge = Some(bulge);
|
||||
return Some(next);
|
||||
}
|
||||
let (ia, ib) = if start { (1, 0) } else { (n - 2, n - 1) };
|
||||
let (_, b) = k::extend_segment(c.pts[ia], c.pts[ib], "end", cutters)?;
|
||||
next.raw[ib] = ptv(b);
|
||||
next.pts[ib] = b;
|
||||
Some(next)
|
||||
}
|
||||
|
||||
/// Extend: die Kurve `id` am Ende nahe `at` bis zum nächsten Schneider verlängern.
|
||||
pub fn extend_ops(root: &Map<String, Value>, id: &str, at: P) -> Vec<Op> {
|
||||
let Some(target) = find(root, id) else { return vec![] };
|
||||
let Some(c) = curve(geom(target), Take::Open) else { return vec![] };
|
||||
let Some(next) = extend_curve(&c, &extend_cutters(root, target), at) else { return vec![] };
|
||||
let g = if next.raw.len() == 2 && shape(geom(target)) == "line" && !next.has_bulge() {
|
||||
chain_geom(next.raw, Value::Bool(false), None)
|
||||
} else {
|
||||
let mut m = Map::new();
|
||||
m.insert("shape".into(), "polyline".into());
|
||||
m.insert("pts".into(), Value::Array(next.raw.clone()));
|
||||
m.insert("closed".into(), Value::Bool(false));
|
||||
if next.has_bulge() {
|
||||
m.insert("bulge".into(), Value::Array(next.bulge.clone().unwrap_or_default()));
|
||||
}
|
||||
Value::Object(m)
|
||||
};
|
||||
patch_geom(root, id, g)
|
||||
}
|
||||
|
||||
/// Vorschau der Verlängerung (Bögen tesselliert).
|
||||
pub fn extend_preview(root: &Map<String, Value>, level: &str, at: P, out: &mut Shapes) -> bool {
|
||||
let Some(target) = pick_curve(root, level, at, Take::Open) else { return false };
|
||||
let Some(c) = curve(geom(target), Take::Open) else { return true };
|
||||
let Some(next) = extend_curve(&c, &extend_cutters(root, target), at) else { return true };
|
||||
let pts = if next.has_bulge() { chain_of(&hit_edges(&next)) } else { next.pts.clone() };
|
||||
out.poly_open(&tuples(&pts));
|
||||
true
|
||||
}
|
||||
|
||||
// ── Verrunden / Fasen ────────────────────────────────────────────────────────
|
||||
|
||||
/// Treffer einer Ecke: Zeichnung, Kurve, Eckpunkt-Index.
|
||||
pub struct Corner<'a> {
|
||||
pub drawing: &'a Value,
|
||||
c: Curve,
|
||||
pub index: usize,
|
||||
}
|
||||
|
||||
impl Corner<'_> {
|
||||
pub fn point(&self) -> P {
|
||||
self.c.pts[self.index]
|
||||
}
|
||||
fn neighbors(&self) -> (P, P, P) {
|
||||
let n = self.c.pts.len();
|
||||
(self.c.pts[self.index], self.c.pts[(self.index + n - 1) % n], self.c.pts[(self.index + 1) % n])
|
||||
}
|
||||
}
|
||||
|
||||
/// Nächste Ecke (mit zwei Nachbarn) einer Polylinie/eines Rechtecks der Ebene (innerhalb `CORNER_TOL`).
|
||||
pub fn pick_corner<'a>(root: &'a Map<String, Value>, level: &str, at: P) -> Option<Corner<'a>> {
|
||||
let mut best: Option<(&Value, usize)> = None;
|
||||
let mut best_c = None;
|
||||
let mut best_d = CORNER_TOL;
|
||||
for d in drawings(root) {
|
||||
if level_of(d) != Some(level) {
|
||||
continue;
|
||||
}
|
||||
let Some(c) = curve(geom(d), Take::Corner) else { continue };
|
||||
let n = c.pts.len();
|
||||
let mut hit = false;
|
||||
for i in 0..n {
|
||||
if !c.closed && (i == 0 || i == n - 1) {
|
||||
continue;
|
||||
}
|
||||
let dd = hypot2(c.pts[i].x - at.x, c.pts[i].y - at.y);
|
||||
if dd < best_d {
|
||||
best_d = dd;
|
||||
best = Some((d, i));
|
||||
hit = true;
|
||||
}
|
||||
}
|
||||
if hit {
|
||||
best_c = Some(c);
|
||||
}
|
||||
}
|
||||
let (drawing, index) = best?;
|
||||
Some(Corner { drawing, c: best_c?, index })
|
||||
}
|
||||
|
||||
/// Die Ecke `index` der Zeichnung `id` (Zustand des Befehls zwischen den Schritten).
|
||||
fn corner_of<'a>(root: &'a Map<String, Value>, id: &str, index: f64) -> Option<Corner<'a>> {
|
||||
let d = find(root, id)?;
|
||||
let c = curve(geom(d), Take::Corner)?;
|
||||
let i = (index.fract() == 0.0 && index >= 0.0 && index < c.pts.len() as f64).then_some(index as usize)?;
|
||||
Some(Corner { drawing: d, c, index: i })
|
||||
}
|
||||
|
||||
fn fillet_of(h: &Corner, r: f64) -> Option<k::Fillet> {
|
||||
let (corner, prev, next) = h.neighbors();
|
||||
k::fillet_corner(corner, prev, next, r)
|
||||
}
|
||||
|
||||
fn chamfer_of(h: &Corner, d: f64) -> Option<k::Chamfer> {
|
||||
let (corner, prev, next) = h.neighbors();
|
||||
k::chamfer_corner(corner, prev, next, d)
|
||||
}
|
||||
|
||||
/// Kürzester Schwenk start → end in (−π, π].
|
||||
fn short_delta(f: &k::Fillet) -> f64 {
|
||||
let tau = std::f64::consts::PI * 2.0;
|
||||
let mut delta = f.end_angle - f.start_angle;
|
||||
while delta > std::f64::consts::PI {
|
||||
delta -= tau;
|
||||
}
|
||||
while delta < -std::f64::consts::PI {
|
||||
delta += tau;
|
||||
}
|
||||
delta
|
||||
}
|
||||
|
||||
/// Verrundungs-Bogen als Punktfolge (12 Segmente, kürzester Bogen).
|
||||
fn tessellate(f: &k::Fillet) -> Vec<(f64, f64)> {
|
||||
let delta = short_delta(f);
|
||||
(0..=12)
|
||||
.map(|i| {
|
||||
let a = f.start_angle + (delta * i as f64) / 12.0;
|
||||
(f.center.x + f.radius * jsnum::cos(a), f.center.y + f.radius * jsnum::sin(a))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Ersetzt den Eckpunkt durch zwei Punkte (die übrigen Punkte bleiben die Werte der Quelle).
|
||||
fn split_corner(h: &Corner, a: P, b: P) -> Vec<Value> {
|
||||
let mut pts: Vec<Value> = h.c.raw[..h.index].to_vec();
|
||||
pts.push(ptv(a));
|
||||
pts.push(ptv(b));
|
||||
pts.extend_from_slice(&h.c.raw[h.index + 1..]);
|
||||
pts
|
||||
}
|
||||
|
||||
fn polyline_geom(pts: Vec<Value>, closed: Option<Value>, bulge: Option<Vec<Value>>) -> Value {
|
||||
let mut m = Map::new();
|
||||
m.insert("shape".into(), "polyline".into());
|
||||
m.insert("pts".into(), Value::Array(pts));
|
||||
if let Some(c) = closed {
|
||||
m.insert("closed".into(), c);
|
||||
}
|
||||
if let Some(b) = bulge {
|
||||
m.insert("bulge".into(), Value::Array(b));
|
||||
}
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
/// Verrunden der Ecke `index` von `id` mit Radius `r` (Bogen als bulge zwischen den Tangentenpunkten).
|
||||
pub fn fillet_ops(root: &Map<String, Value>, id: &str, index: f64, r: f64) -> Vec<Op> {
|
||||
let Some(h) = corner_of(root, id, index) else { return vec![] };
|
||||
let Some(f) = fillet_of(&h, r) else { return vec![] };
|
||||
let pts = split_corner(&h, f.tangent_a, f.tangent_b);
|
||||
let edges = if h.c.closed { pts.len() } else { pts.len() - 1 };
|
||||
let mut bulge = vec![Value::from(0); edges];
|
||||
let mid = f.start_angle + short_delta(&f) / 2.0;
|
||||
let apex = (f.center.x + f.radius * jsnum::cos(mid), f.center.y + f.radius * jsnum::sin(mid));
|
||||
let b = crate::bulge::from_sagitta_point(f.tangent_a.x, f.tangent_a.y, f.tangent_b.x, f.tangent_b.y, apex.0, apex.1);
|
||||
if h.index < bulge.len() {
|
||||
bulge[h.index] = js_num(b);
|
||||
}
|
||||
patch_geom(root, id, polyline_geom(pts, h.c.closed_raw.clone(), Some(bulge)))
|
||||
}
|
||||
|
||||
/// Fasen der Ecke `index` von `id` um `d`.
|
||||
pub fn chamfer_ops(root: &Map<String, Value>, id: &str, index: f64, d: f64) -> Vec<Op> {
|
||||
let Some(h) = corner_of(root, id, index) else { return vec![] };
|
||||
let Some(c) = chamfer_of(&h, d) else { return vec![] };
|
||||
patch_geom(root, id, polyline_geom(split_corner(&h, c.a, c.b), h.c.closed_raw.clone(), None))
|
||||
}
|
||||
|
||||
/// Vorschau Verrunden/Fasen einer Ecke (`fillet`: Bogen, sonst die Fasung).
|
||||
fn corner_preview(h: &Corner, fillet: bool, r: f64, out: &mut Shapes) {
|
||||
if r <= EPS_R {
|
||||
return;
|
||||
}
|
||||
if fillet {
|
||||
if let Some(f) = fillet_of(h, r) {
|
||||
out.poly_open(&tessellate(&f));
|
||||
}
|
||||
} else if let Some(c) = chamfer_of(h, r) {
|
||||
out.poly_open(&[(c.a.x, c.a.y), (c.b.x, c.b.y)]);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Bruch ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Offene, bogenfreie Kurve unter dem Punkt (die nächste Kurve muss es sein).
|
||||
pub fn pick_breakable<'a>(root: &'a Map<String, Value>, level: &str, at: P) -> Option<&'a Value> {
|
||||
let d = pick_curve(root, level, at, Take::Curve)?;
|
||||
let c = curve(geom(d), Take::Curve)?;
|
||||
(!c.closed && !c.has_bulge()).then_some(d)
|
||||
}
|
||||
|
||||
fn break_pieces<'a>(root: &'a Map<String, Value>, id: &str, p1: P, p2: P) -> Option<(&'a Value, Vec<Vec<P>>)> {
|
||||
let target = find(root, id)?;
|
||||
let c = curve(geom(target), Take::Curve)?;
|
||||
let h1 = k::nearest_on_polyline(&c.pts, false, p1)?;
|
||||
let h2 = k::nearest_on_polyline(&c.pts, false, p2)?;
|
||||
Some((target, k::break_curve(&c.pts, h1, h2)))
|
||||
}
|
||||
|
||||
/// Bruch zwischen zwei Punkten: die Zeichnung wird durch die Reststücke ersetzt (hinten angehängt).
|
||||
pub fn break_ops(root: &Map<String, Value>, id: &str, p1: P, p2: P, ids: &mut IdGen) -> Vec<Op> {
|
||||
let Some((target, pieces)) = break_pieces(root, id, p1, p2) else { return vec![] };
|
||||
let parts: Vec<Value> = pieces.iter().map(|pts| copy_with(target, ids.next("dr2d"), chain_geom(pts_v(pts), Value::Bool(false), None))).collect();
|
||||
let mut ops = vec![remove(vec![id.to_string()])];
|
||||
ops.extend(add(parts));
|
||||
ops
|
||||
}
|
||||
|
||||
fn break_preview(root: &Map<String, Value>, id: &str, p1: P, p2: P, out: &mut Shapes) {
|
||||
let Some((_, pieces)) = break_pieces(root, id, p1, p2) else { return };
|
||||
for pts in pieces.iter().filter(|p| p.len() >= 2) {
|
||||
if pts.len() == 2 {
|
||||
out.line((pts[0].x, pts[0].y), (pts[1].x, pts[1].y));
|
||||
} else {
|
||||
out.poly_open(&tuples(pts));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Offset ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Seite des Punkts zur Kurve (+1 links, −1 rechts) über die nächste Kante; ohne Kante `last`.
|
||||
fn side_sign(c: &Curve, at: P, last: f64) -> f64 {
|
||||
let mut best = f64::INFINITY;
|
||||
let mut sign = last;
|
||||
for (a, b) in hit_edges(c) {
|
||||
let mid = P::new((a.x + b.x) / 2.0, (a.y + b.y) / 2.0);
|
||||
let dd = k::point_segment_distance(at, a, b);
|
||||
if dd < best {
|
||||
best = dd;
|
||||
let (ux, uy) = (b.x - a.x, b.y - a.y);
|
||||
let l = hypot2(ux, uy);
|
||||
let l = if l == 0.0 || l.is_nan() { 1.0 } else { l };
|
||||
let (nx, ny) = (-(uy / l), ux / l);
|
||||
let s = (at.x - mid.x) * nx + (at.y - mid.y) * ny;
|
||||
sign = if s >= 0.0 { 1.0 } else { -1.0 };
|
||||
}
|
||||
}
|
||||
sign
|
||||
}
|
||||
|
||||
/// Versetzte Kurve um `d` (links positiv; Bögen bleiben konzentrisch).
|
||||
fn offset_curve(c: &Curve, d: f64) -> (Vec<P>, Option<Vec<f64>>) {
|
||||
if !c.closed && c.pts.len() == 2 && !c.has_bulge() {
|
||||
let (a, b) = k::offset_segment(c.pts[0], c.pts[1], d);
|
||||
return (vec![a, b], None);
|
||||
}
|
||||
if c.has_bulge() {
|
||||
let (p, b) = k::offset_polyline_with_bulge(&c.pts, &c.bulge_nums(), d, c.closed);
|
||||
return (p, Some(b));
|
||||
}
|
||||
(k::offset_polyline(&c.pts, d, c.closed), None)
|
||||
}
|
||||
|
||||
/// Offset: eine versetzte Kopie von `id` um `d` anhängen.
|
||||
pub fn offset_ops(root: &Map<String, Value>, id: &str, d: f64, ids: &mut IdGen) -> Vec<Op> {
|
||||
let Some(src) = find(root, id) else { return vec![] };
|
||||
let Some(c) = curve(geom(src), Take::Curve) else { return vec![] };
|
||||
let (pts, bulge) = offset_curve(&c, d);
|
||||
let g = if shape(geom(src)) == "line" && pts.len() == 2 {
|
||||
chain_geom(pts_v(&pts), Value::Bool(false), None)
|
||||
} else {
|
||||
polyline_geom(pts_v(&pts), c.closed_raw.clone(), bulge.filter(|b| real(b)).map(|b| bulge_v(&b)))
|
||||
};
|
||||
add(vec![copy_with(src, ids.next("dr2d"), g)]).into_iter().collect()
|
||||
}
|
||||
|
||||
fn offset_preview(c: &Curve, d: f64, out: &mut Shapes) {
|
||||
let (pts, bulge) = offset_curve(c, d);
|
||||
if pts.len() < 2 {
|
||||
return;
|
||||
}
|
||||
let has = bulge.as_deref().is_some_and(real);
|
||||
if !c.closed && pts.len() == 2 && !has {
|
||||
out.line((pts[0].x, pts[0].y), (pts[1].x, pts[1].y));
|
||||
return;
|
||||
}
|
||||
let tess = if has { chain_of(&hit_edges(&Curve::of_pts(pts, c.closed, bulge.as_deref()))) } else { pts };
|
||||
if c.closed {
|
||||
out.poly(&tuples(&tess));
|
||||
} else {
|
||||
out.poly_open(&tuples(&tess));
|
||||
}
|
||||
}
|
||||
|
||||
// ── Verketten / Auflösen ─────────────────────────────────────────────────────
|
||||
|
||||
/// Übernimmt Ebene, Kategorie und Stil der Quelle auf ein neues Element (`inherit`); Schraffur/Füllung
|
||||
/// nur bei geschlossenen Ergebnissen.
|
||||
fn inherit(src: &Value, g: Value, ids: &mut IdGen) -> Value {
|
||||
let mut m = Map::new();
|
||||
m.insert("id".into(), ids.next("d2d").into());
|
||||
m.insert("type".into(), "drawing2d".into());
|
||||
for k in ["levelId", "categoryCode"] {
|
||||
if let Some(v) = field(src, k) {
|
||||
m.insert(k.into(), v.clone());
|
||||
}
|
||||
}
|
||||
let closed = match shape(&g) {
|
||||
"polyline" => truthy(field(&g, "closed")),
|
||||
"rect" => true,
|
||||
_ => false,
|
||||
};
|
||||
m.insert("geom".into(), g);
|
||||
for k in ["lineStyleId", "color", "weightMm"] {
|
||||
if let Some(v) = field(src, k) {
|
||||
m.insert(k.into(), v.clone());
|
||||
}
|
||||
}
|
||||
if closed {
|
||||
for k in ["hatchId", "fillColor"] {
|
||||
if let Some(v) = field(src, k) {
|
||||
m.insert(k.into(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
/// Join: die gewählten Zeichnungen (ab zwei) an gemeinsamen Endpunkten zu Polylinien verketten (Bögen
|
||||
/// bleiben); nicht verkettbare Formen bleiben und rücken hinter das Ergebnis.
|
||||
pub fn join_ops(root: &Map<String, Value>, ids_sel: &[String], ids: &mut IdGen) -> Vec<Op> {
|
||||
let set: crate::commands::FastSet<&str> = ids_sel.iter().map(String::as_str).collect();
|
||||
let srcs: Vec<&Value> = drawings(root).iter().filter(|d| id_of(d).is_some_and(|i| set.contains(i))).collect();
|
||||
if srcs.len() < 2 {
|
||||
return vec![];
|
||||
}
|
||||
let mut joinable: Vec<(k::BulgeChainInput, &Value)> = Vec::new();
|
||||
let mut pass: Vec<Value> = Vec::new();
|
||||
for d in &srcs {
|
||||
let g = geom(d);
|
||||
let form = match shape(g) {
|
||||
"polyline" => curve(g, Take::Curve).map(|c| k::BulgeChainInput { bulge: c.bulge.as_deref().map(nums), pts: c.pts, closed: c.closed }),
|
||||
"line" | "rect" => curve(g, Take::Curve).map(|c| k::BulgeChainInput { pts: c.pts, closed: c.closed, bulge: None }),
|
||||
_ => None,
|
||||
};
|
||||
match form {
|
||||
Some(f) => joinable.push((f, d)),
|
||||
None => pass.push((*d).clone()),
|
||||
}
|
||||
}
|
||||
let joined: Vec<Value> = if joinable.is_empty() {
|
||||
srcs.iter().map(|d| (*d).clone()).collect()
|
||||
} else {
|
||||
let inputs: Vec<k::BulgeChainInput> = joinable.iter().map(|(f, _)| k::BulgeChainInput { pts: f.pts.clone(), closed: f.closed, bulge: f.bulge.clone() }).collect();
|
||||
let template = joinable[0].1;
|
||||
let mut out: Vec<Value> = k::join_chains_with_bulge(&inputs)
|
||||
.iter()
|
||||
.map(|c| inherit(template, chain_geom(pts_v(&c.pts), Value::Bool(c.closed), Some(bulge_v(&c.bulge))), ids))
|
||||
.collect();
|
||||
out.extend(pass);
|
||||
out
|
||||
};
|
||||
let mut seen = crate::commands::FastSet::default();
|
||||
let drop: Vec<String> = srcs.iter().filter_map(|d| id_of(d)).filter(|i| seen.insert(*i)).map(str::to_owned).collect();
|
||||
let mut ops = vec![remove(drop)];
|
||||
ops.extend(add(joined));
|
||||
ops
|
||||
}
|
||||
|
||||
/// Punkte einer Teilgeometrie abbilden (Block-Auflösung; nur Punkte, keine Grössen).
|
||||
fn map_points(g: &Value, f: &dyn Fn(P) -> P) -> Value {
|
||||
let m = |k: &str| ptv(f(p_of(field(g, k).unwrap_or(&Value::Null))));
|
||||
let ms = |k: &str| Value::Array(arr(field(g, k)).iter().map(|q| ptv(f(p_of(q)))).collect());
|
||||
match shape(g) {
|
||||
"line" | "xline" | "ray" => with_all(g, vec![("a", m("a")), ("b", m("b"))]),
|
||||
"polyline" | "bezier" | "spline" | "dimension" => with(g, "pts", ms("pts")),
|
||||
"rect" | "image" => with_all(g, vec![("min", m("min")), ("max", m("max"))]),
|
||||
"circle" | "arc" | "ellipse" => with(g, "center", m("center")),
|
||||
"text" | "kote" | "detailref" | "scalebar" | "pointmarker" | "block" => with(g, "at", m("at")),
|
||||
_ => g.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Teilgeometrien eines zerlegbaren Elements (Block-Instanz, Polylinie, Rechteck), sonst `None`.
|
||||
fn explode_geom(g: &Value, root: &Map<String, Value>) -> Option<Vec<Value>> {
|
||||
match shape(g) {
|
||||
"block" => {
|
||||
let def_id = field(g, "blockDefId");
|
||||
let def = arr(root.get("blockDefs")).iter().find(|b| def_id.is_some() && field(b, "id") == def_id)?;
|
||||
let parts = arr(field(def, "geom2d"));
|
||||
if parts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let rot = num_of(field(g, "rotation"));
|
||||
let (c, s) = (jsnum::cos(rot), jsnum::sin(rot));
|
||||
let at = p_of(field(g, "at").unwrap_or(&Value::Null));
|
||||
let xf = move |p: P| P::new(at.x + p.x * c - p.y * s, at.y + p.x * s + p.y * c);
|
||||
Some(parts.iter().map(|sub| map_points(sub, &xf)).collect())
|
||||
}
|
||||
"polyline" => {
|
||||
let raw = arr(field(g, "pts"));
|
||||
let n = raw.len();
|
||||
if n < 2 {
|
||||
return None;
|
||||
}
|
||||
let segs = if truthy(field(g, "closed")) && n > 2 { n } else { n - 1 };
|
||||
let bulge = field(g, "bulge").and_then(Value::as_array);
|
||||
let mut out = Vec::with_capacity(segs);
|
||||
for i in 0..segs {
|
||||
let (a, b) = (&raw[i], &raw[(i + 1) % n]);
|
||||
let bv = num_or(bulge.and_then(|b| b.get(i)), 0.0);
|
||||
let (pa, pb) = (p_of(a), p_of(b));
|
||||
let arc = if bv.abs() >= EPS_BULGE { crate::bulge::arc(pa.x, pa.y, pb.x, pb.y, bv) } else { vec![] };
|
||||
let mut m = Map::new();
|
||||
if arc.len() >= 6 {
|
||||
let fwd = arc[5] >= 0.0;
|
||||
m.insert("shape".into(), "arc".into());
|
||||
m.insert("center".into(), pt(arc[0], arc[1]));
|
||||
m.insert("r".into(), js_num(arc[2]));
|
||||
m.insert("a0".into(), js_num(if fwd { arc[3] } else { arc[4] }));
|
||||
m.insert("a1".into(), js_num(if fwd { arc[4] } else { arc[3] }));
|
||||
} else {
|
||||
m.insert("shape".into(), "line".into());
|
||||
m.insert("a".into(), a.clone());
|
||||
m.insert("b".into(), b.clone());
|
||||
}
|
||||
out.push(Value::Object(m));
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
"rect" => {
|
||||
let c = rect_curve(g).raw;
|
||||
let line = |a: &Value, b: &Value| {
|
||||
let mut m = Map::new();
|
||||
m.insert("shape".into(), "line".into());
|
||||
m.insert("a".into(), a.clone());
|
||||
m.insert("b".into(), b.clone());
|
||||
Value::Object(m)
|
||||
};
|
||||
Some(vec![line(&c[0], &c[1]), line(&c[1], &c[2]), line(&c[2], &c[3]), line(&c[3], &c[0])])
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Auflösen: jedes zerlegbare gewählte Element wird an seiner Stelle durch seine Teile ersetzt
|
||||
/// (`replaceWithMany`: ein `remove`, dann je ein `add` an der Endposition).
|
||||
pub fn explode_ops(root: &Map<String, Value>, ids_sel: &[String], ids: &mut IdGen) -> Vec<Op> {
|
||||
let set: crate::commands::FastSet<&str> = ids_sel.iter().map(String::as_str).collect();
|
||||
let mut repl: std::collections::HashMap<&str, Vec<Value>> = std::collections::HashMap::new();
|
||||
for d in drawings(root) {
|
||||
let Some(id) = id_of(d).filter(|i| set.contains(i)) else { continue };
|
||||
let Some(parts) = explode_geom(geom(d), root).filter(|p| !p.is_empty()) else { continue };
|
||||
repl.insert(id, parts.into_iter().map(|g| copy_with(d, ids.next("dr2d"), g)).collect());
|
||||
}
|
||||
replace_with_many(drawings(root), "drawings2d", &repl)
|
||||
}
|
||||
|
||||
/// `replaceWithMany`: Elemente durch je eine Liste neuer Elemente an derselben Stelle ersetzen.
|
||||
fn replace_with_many(list: &[Value], collection: &str, repl: &std::collections::HashMap<&str, Vec<Value>>) -> Vec<Op> {
|
||||
let mut dropped = Vec::new();
|
||||
let mut inserts = Vec::new();
|
||||
let mut len = 0;
|
||||
for e in list {
|
||||
let Some((id, items)) = id_of(e).and_then(|id| repl.get(id).map(|it| (id, it))) else {
|
||||
len += 1;
|
||||
continue;
|
||||
};
|
||||
dropped.push(id.to_string());
|
||||
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: collection.into(), ids: dropped }];
|
||||
for (at, items) in inserts {
|
||||
ops.push(Op::Add { collection: collection.into(), items, at: Some(at) });
|
||||
}
|
||||
ops
|
||||
}
|
||||
|
||||
// ── Anfragen der Hülle ───────────────────────────────────────────────────────
|
||||
|
||||
fn p_arg(v: &Value, k: &str) -> P {
|
||||
let a = v.get(k);
|
||||
let n = |i: usize| a.and_then(|a| a.get(i)).map_or(f64::NAN, |x| num_of(Some(x)));
|
||||
P::new(n(0), n(1))
|
||||
}
|
||||
|
||||
fn n_arg(v: &Value, k: &str) -> f64 {
|
||||
v.get(k).map_or(f64::NAN, |x| num_of(Some(x)))
|
||||
}
|
||||
|
||||
fn s_arg<'a>(v: &'a Value, k: &str) -> &'a str {
|
||||
v.get(k).and_then(Value::as_str).unwrap_or("")
|
||||
}
|
||||
|
||||
/// Ops eines Editier-Befehls (`None` = kein Editier-Befehl).
|
||||
pub fn ops(root: &Map<String, Value>, v: &Value) -> Option<Vec<Op>> {
|
||||
let cmd = s_arg(v, "cmd");
|
||||
let mut ids = IdGen::new(s_arg(v, "stamp"));
|
||||
let list = |k: &str| -> Vec<String> { v.get(k).and_then(|x| serde_json::from_value(x.clone()).ok()).unwrap_or_default() };
|
||||
Some(match cmd {
|
||||
"trim" => trim_ops(root, s_arg(v, "id"), p_arg(v, "pt"), &mut ids),
|
||||
"extend" => extend_ops(root, s_arg(v, "id"), p_arg(v, "pt")),
|
||||
"fillet" => fillet_ops(root, s_arg(v, "id"), n_arg(v, "index"), n_arg(v, "r")),
|
||||
"chamfer" => chamfer_ops(root, s_arg(v, "id"), n_arg(v, "index"), n_arg(v, "d")),
|
||||
"break" => break_ops(root, s_arg(v, "id"), p_arg(v, "p1"), p_arg(v, "p2"), &mut ids),
|
||||
"offset" => offset_ops(root, s_arg(v, "id"), n_arg(v, "d"), &mut ids),
|
||||
"join" => join_ops(root, &list("ids"), &mut ids),
|
||||
"explode" => explode_ops(root, &list("ids"), &mut ids),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Abfragen der Befehle zwischen den Schritten (Treffer, Vorschau): Antwort-JSON. Formen flach wie
|
||||
/// `doc_cmd_preview` (`shapes`), Treffer als `hit` (`null` = keiner).
|
||||
pub fn query(root: &Map<String, Value>, v: &Value) -> Result<Value, String> {
|
||||
use serde_json::json;
|
||||
let q = s_arg(v, "q");
|
||||
let at = p_arg(v, "pt");
|
||||
let level = s_arg(v, "level");
|
||||
let mut s = Shapes::default();
|
||||
let shapes = |s: Shapes| Value::Array(s.buf.iter().map(|x| js_num(*x)).collect());
|
||||
let hit_id = |d: Option<&Value>| d.and_then(id_of).map_or(Value::Null, |i| Value::String(i.into()));
|
||||
Ok(match q {
|
||||
"pickCurve" => json!({ "hit": hit_id(pick_curve(root, level, at, Take::Curve)) }),
|
||||
"pickOpen" => json!({ "hit": hit_id(pick_curve(root, level, at, Take::Open)) }),
|
||||
"pickBreakable" => json!({ "hit": hit_id(pick_breakable(root, level, at)) }),
|
||||
"pickCorner" => {
|
||||
let fillet = s_arg(v, "kind") == "fillet";
|
||||
match pick_corner(root, level, at) {
|
||||
Some(h) => {
|
||||
if v.get("r").is_some() {
|
||||
corner_preview(&h, fillet, n_arg(v, "r"), &mut s);
|
||||
}
|
||||
let p = h.point();
|
||||
json!({ "hit": { "id": id_of(h.drawing), "index": h.index, "corner": [js_num(p.x), js_num(p.y)] }, "shapes": shapes(s) })
|
||||
}
|
||||
None => json!({ "hit": null, "shapes": [] }),
|
||||
}
|
||||
}
|
||||
"corner" => {
|
||||
if let Some(h) = corner_of(root, s_arg(v, "id"), n_arg(v, "index")) {
|
||||
corner_preview(&h, s_arg(v, "kind") == "fillet", n_arg(v, "r"), &mut s);
|
||||
}
|
||||
json!({ "shapes": shapes(s) })
|
||||
}
|
||||
"trim" | "extend" => {
|
||||
let hit = if q == "trim" { trim_preview(root, level, at, &mut s) } else { extend_preview(root, level, at, &mut s) };
|
||||
json!({ "hit": hit, "shapes": shapes(s) })
|
||||
}
|
||||
"break" => {
|
||||
break_preview(root, s_arg(v, "id"), p_arg(v, "p1"), at, &mut s);
|
||||
json!({ "shapes": shapes(s) })
|
||||
}
|
||||
"offset" => {
|
||||
let c = find(root, s_arg(v, "id")).and_then(|d| curve(geom(d), Take::Curve));
|
||||
match c {
|
||||
Some(c) => {
|
||||
let sign = side_sign(&c, at, n_arg(v, "lastSign"));
|
||||
let dist = n_arg(v, "dist");
|
||||
if dist.is_finite() {
|
||||
offset_preview(&c, sign * dist, &mut s);
|
||||
}
|
||||
json!({ "hit": true, "sign": sign, "shapes": shapes(s) })
|
||||
}
|
||||
None => json!({ "hit": false, "shapes": [] }),
|
||||
}
|
||||
}
|
||||
other => return Err(format!("Unbekannte Befehls-Abfrage: {other}")),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn root(v: Value) -> Map<String, Value> {
|
||||
v.as_object().unwrap().clone()
|
||||
}
|
||||
fn line(id: &str, a: (f64, f64), b: (f64, f64)) -> Value {
|
||||
json!({"id": id, "type": "drawing2d", "levelId": "L", "categoryCode": "20", "geom": {"shape": "line", "a": {"x": a.0, "y": a.1}, "b": {"x": b.0, "y": b.1}}})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_schneidet_das_getroffene_stueck_weg() {
|
||||
let r = root(json!({"drawings2d": [line("a", (0.0, 0.0), (10.0, 0.0)), line("b", (5.0, -1.0), (5.0, 1.0))]}));
|
||||
let ops = trim_ops(&r, "a", P::new(8.0, 0.0), &mut IdGen::new("s"));
|
||||
assert_eq!(ops.len(), 2);
|
||||
let items = &ops[1].to_json()["items"];
|
||||
assert_eq!(items[0]["geom"], json!({"shape": "line", "a": {"x": 0, "y": 0}, "b": {"x": 5, "y": 0}}));
|
||||
assert_eq!(items[0]["id"], "dr2d-s-1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extend_bis_zum_schneider() {
|
||||
let r = root(json!({"drawings2d": [line("a", (0.0, 0.0), (4.0, 0.0)), line("b", (5.0, -1.0), (5.0, 1.0))]}));
|
||||
let ops = extend_ops(&r, "a", P::new(3.9, 0.0));
|
||||
assert_eq!(ops[0].to_json()["entity"]["geom"]["b"], json!({"x": 5, "y": 0}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verrunden_setzt_bogen() {
|
||||
let poly = json!({"id": "p", "levelId": "L", "geom": {"shape": "polyline", "pts": [{"x": 0, "y": 0}, {"x": 2, "y": 0}, {"x": 2, "y": 2}], "closed": false}});
|
||||
let r = root(json!({ "drawings2d": [poly] }));
|
||||
let h = pick_corner(&r, "L", P::new(2.1, 0.1)).unwrap();
|
||||
assert_eq!(h.index, 1);
|
||||
let ops = fillet_ops(&r, "p", 1.0, 0.5);
|
||||
let g = &ops[0].to_json()["entity"]["geom"];
|
||||
assert_eq!(g["pts"].as_array().unwrap().len(), 4);
|
||||
assert!(g["bulge"][1].as_f64().unwrap().abs() > 0.1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aufloesen_rechteck_an_ort_und_stelle() {
|
||||
let rect = json!({"id": "r", "geom": {"shape": "rect", "min": {"x": 0, "y": 0}, "max": {"x": 1, "y": 1}}});
|
||||
let r = root(json!({"drawings2d": [line("a", (0.0, 0.0), (1.0, 0.0)), rect]}));
|
||||
let ops = explode_ops(&r, &["r".into()], &mut IdGen::new("s"));
|
||||
assert_eq!(ops.len(), 2);
|
||||
assert_eq!(ops[1].to_json()["at"], 1);
|
||||
assert_eq!(ops[1].to_json()["items"].as_array().unwrap().len(), 4);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,58 @@
|
||||
//! Befehle und Werkzeuge im Kern ([K4] S3): die Zustandsautomaten der Befehle (Eingaben, Optionen,
|
||||
//! Tasten) bleiben in der TS-Hülle; was aus dem Projekt Geometrie oder Ops rechnet, steht hier.
|
||||
//! Eine Anfrage (`cmd` + Argumente, JSON) ergibt Ops (`cmdOps`, Wurzel-Abfrage; `doc_cmd_commit` rechnet
|
||||
//! und wendet im selben Aufruf an) bzw. Vorschau-Formen (`doc_cmd_preview`). Module: `cmd_transform`
|
||||
//! (Verschieben/Drehen/Spiegeln/Skalieren/Reihe, Ausrichten/Verteilen, Block definieren).
|
||||
|
||||
use crate::grips::{result_json, GripResult};
|
||||
use crate::ops::Op;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
fn parse<T: serde::de::DeserializeOwned>(v: &Value, what: &str) -> Result<T, String> {
|
||||
serde_json::from_value(v.clone()).map_err(|e| format!("{what}: {e}"))
|
||||
}
|
||||
|
||||
/// Ops eines Befehls (`text` = JSON `{cmd, …}`, Zahlen dürfen Nicht-endlich-Marken sein).
|
||||
pub fn ops(root: &Map<String, Value>, text: &str) -> Result<Vec<Op>, String> {
|
||||
let v: Value = serde_json::from_str(text).map_err(|e| format!("cmdOps: {e}"))?;
|
||||
let cmd = v.get("cmd").and_then(Value::as_str).unwrap_or("");
|
||||
let ids = |k: &str| -> Vec<String> { v.get(k).and_then(|x| serde_json::from_value(x.clone()).ok()).unwrap_or_default() };
|
||||
let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_string();
|
||||
if let Some(ops) = crate::cmd_edit::ops(root, &v) {
|
||||
return Ok(ops);
|
||||
}
|
||||
Ok(match cmd {
|
||||
"transform" => crate::cmd_transform::transform_ops(root, &parse(&v, cmd)?),
|
||||
"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)?),
|
||||
other => return Err(format!("Unbekannter Befehl: {other}")),
|
||||
})
|
||||
}
|
||||
|
||||
/// Wie [`ops`], als Antwort-JSON `{"ops": […]}` (Zahlen mit Nicht-endlich-Marken).
|
||||
pub fn ops_json(root: &Map<String, Value>, text: &str) -> Result<String, String> {
|
||||
Ok(result_json(&GripResult { ops: ops(root, text)?, notice: None }))
|
||||
}
|
||||
|
||||
/// Schneller Hasher für id-Mengen der Befehle (FNV-1a; je Mausschritt werden Tausende ids geprüft,
|
||||
/// SipHash kostete dort den grössten Teil der Vorschau).
|
||||
#[derive(Default)]
|
||||
pub struct Fnv(u64);
|
||||
|
||||
impl std::hash::Hasher for Fnv {
|
||||
fn finish(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
let mut h = if self.0 == 0 { 0xcbf2_9ce4_8422_2325 } else { self.0 };
|
||||
for b in bytes {
|
||||
h ^= *b as u64;
|
||||
h = h.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
self.0 = h;
|
||||
}
|
||||
}
|
||||
|
||||
/// Menge mit [`Fnv`].
|
||||
pub type FastSet<T> = std::collections::HashSet<T, std::hash::BuildHasherDefault<Fnv>>;
|
||||
@@ -70,7 +70,7 @@ pub fn num_of(v: Option<&Value>) -> f64 {
|
||||
}
|
||||
|
||||
/// `a ?? b` für Zahlen (fehlend/`null` → `b`).
|
||||
fn num_or(v: Option<&Value>, b: f64) -> f64 {
|
||||
pub(crate) fn num_or(v: Option<&Value>, b: f64) -> f64 {
|
||||
match v {
|
||||
None | Some(Value::Null) => b,
|
||||
v => num_of(v),
|
||||
@@ -107,17 +107,17 @@ pub fn xy(v: &Value) -> (f64, f64) {
|
||||
|
||||
/// `{...v, key: val}` (vorhandener Schlüssel behält seine Stelle). Der ersetzte Wert wird nicht kopiert
|
||||
/// (eine grosse Polylinie kostet sonst je Mausschritt eine Kopie mehr).
|
||||
fn with(v: &Value, key: &str, val: Value) -> Value {
|
||||
pub(crate) fn with(v: &Value, key: &str, val: Value) -> Value {
|
||||
with_all(v, vec![(key, val)])
|
||||
}
|
||||
|
||||
/// Wie [`with`] für mehrere Felder in einem Durchgang (`{...v, a, b}`).
|
||||
fn with_all(v: &Value, fields: Vec<(&str, Value)>) -> Value {
|
||||
pub(crate) fn with_all(v: &Value, fields: Vec<(&str, Value)>) -> Value {
|
||||
with_opt(v, fields.into_iter().map(|(k, x)| (k, Some(x))).collect())
|
||||
}
|
||||
|
||||
/// Wie [`with_all`]; `None` = `undefined` (das Feld fällt weg, wie in JSON).
|
||||
fn with_opt(v: &Value, fields: Vec<(&str, Option<Value>)>) -> Value {
|
||||
pub(crate) fn with_opt(v: &Value, fields: Vec<(&str, Option<Value>)>) -> Value {
|
||||
let mut fields: Vec<(&str, Option<Value>, bool)> = fields.into_iter().map(|(k, x)| (k, x, false)).collect();
|
||||
let src = v.as_object();
|
||||
let mut m = Map::with_capacity(src.map_or(0, Map::len) + fields.len());
|
||||
@@ -160,7 +160,7 @@ fn calc(f: f64) -> Pass {
|
||||
Pass { f, v: Some(js_num(f)) }
|
||||
}
|
||||
|
||||
fn arr(v: Option<&Value>) -> &[Value] {
|
||||
pub(crate) fn arr(v: Option<&Value>) -> &[Value] {
|
||||
v.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[])
|
||||
}
|
||||
|
||||
|
||||
@@ -87,6 +87,9 @@ pub mod text_layout;
|
||||
pub mod plan_text;
|
||||
pub mod grips;
|
||||
pub mod selection_info;
|
||||
pub mod commands;
|
||||
pub mod cmd_transform;
|
||||
pub mod cmd_edit;
|
||||
|
||||
#[cfg(feature = "web")]
|
||||
mod web;
|
||||
@@ -99,6 +99,8 @@ pub fn run_root(root: &serde_json::Map<String, serde_json::Value>, name: &str, t
|
||||
json(&crate::selection_filter::filter_patch(root, &m))
|
||||
}
|
||||
// Griff-Änderungen ([K4] S3, `grips.rs`): `text` = JSON der Anfrage; Antwort `{ops, notice}` (ohne Commit).
|
||||
// Befehle ([K4] S3, `commands.rs`): `text` = JSON `{cmd, …}`; Antwort `{ops}`.
|
||||
"cmdOps" => crate::commands::ops_json(root, text),
|
||||
"gripOps" => {
|
||||
let req: crate::grips::Request = serde_json::from_str(text).map_err(|e| format!("gripOps: {e}"))?;
|
||||
Ok(crate::grips::result_json(&crate::grips::run(root, &req)?))
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Bindungen der Befehle im Kern (`crate::commands`): Befehl rechnen und gleich als Benutzer-Änderung
|
||||
//! anwenden (ein Aufruf, keine Op-Übergabe hin und zurück), Vorschau der Transformationen.
|
||||
|
||||
use super::document::with_doc;
|
||||
use serde_json::json;
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
/// Befehl `req_json` (s. `crate::commands::ops`) auf dem Dokument `h` rechnen und mit Verlauf anwenden
|
||||
/// (`key` = coalesceKey, `now_ms` wie `doc_commit`). Antwort: `{"ops":[…]}` (angewendet; leer = nichts
|
||||
/// zu tun) oder `{"problems":[…]}` (zurückgewiesen, Dokument unverändert); Fehler als Text mit `\u{1}` vorn.
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_cmd_commit(h: u32, req_json: &str, key: &str, now_ms: f64) -> String {
|
||||
let key = (!key.is_empty()).then_some(key);
|
||||
let now = if now_ms.is_finite() { now_ms } else { 0.0 };
|
||||
let out = with_doc(h, |d| -> Result<String, String> {
|
||||
let res = crate::grips::GripResult { ops: crate::commands::ops(d.root(), req_json)?, notice: None };
|
||||
let text = crate::grips::result_json(&res);
|
||||
if res.ops.is_empty() {
|
||||
return Ok(text);
|
||||
}
|
||||
// Nicht endliche Ergebnisse stehen als Marken in den Ops (die Prüfung weist sie zurück).
|
||||
let marks = text.contains("\\u0001");
|
||||
match d.commit(res.ops, key, now, marks) {
|
||||
Ok(()) => Ok(text),
|
||||
Err(problems) => Ok(json!({ "problems": problems }).to_string()),
|
||||
}
|
||||
});
|
||||
match out {
|
||||
Some(Ok(t)) => t,
|
||||
Some(Err(e)) => format!("\u{1}{e}"),
|
||||
None => "\u{1}Dokument nicht offen".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Vorschau-Formen einer Transformation (`req_json` wie `cmdOps` mit `cmd: "transform"`, dazu `scale`
|
||||
/// und `top`): flach je Form `[art (0 Linie, 1 Polygon), n, x0, y0, …]`; leer bei Fehler.
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_cmd_preview(h: u32, req_json: &str) -> Vec<f64> {
|
||||
let Ok(req) = serde_json::from_str::<crate::cmd_transform::TransformReq>(req_json) else { return Vec::new() };
|
||||
with_doc(h, |d| {
|
||||
let pending = crate::cmd_transform::preview_pending(d.root(), &req);
|
||||
let p = if pending.has_drawings() { d.project().ok() } else { None };
|
||||
crate::cmd_transform::preview_finish(p, pending, req.scale.0, req.top.0)
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Abfrage eines Befehls zwischen den Schritten (`crate::cmd_edit::query`: Treffer, Vorschau-Formen) auf
|
||||
/// dem Dokument `h`; Antwort-JSON (Zahlen mit Nicht-endlich-Marken), Fehler als Text mit `\u{1}` vorn.
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_cmd_query(h: u32, req_json: &str) -> String {
|
||||
let v: serde_json::Value = match serde_json::from_str(req_json) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return format!("\u{1}Befehls-Abfrage: {e}"),
|
||||
};
|
||||
match with_doc(h, |d| crate::cmd_edit::query(d.root(), &v)) {
|
||||
Some(Ok(v)) => v.to_string(),
|
||||
Some(Err(e)) => format!("\u{1}{e}"),
|
||||
None => "\u{1}Dokument nicht offen".to_string(),
|
||||
}
|
||||
}
|
||||
@@ -3,14 +3,12 @@
|
||||
//! Flache `f64`-Puffer statt JSON:
|
||||
//! - Punktliste `pts`: `[x0, y0, x1, y1, …]`
|
||||
//! - Liste von Punktlisten: `[n, (n_pts, x0, y0, …)…]`
|
||||
//! - Ketten (Polylinien mit bulge): `[n, (closed, n_pts, x0, y0, …, n_bulge, b0, …)…]`;
|
||||
//! `n_bulge = -1` heisst „kein bulge-Array" (nur Eingabe von `k2_join_chains_with_bulge`).
|
||||
//! - „kein Ergebnis" (TS `null`): leerer Puffer.
|
||||
//!
|
||||
//! Kaputte Eingaben (ungerade Längen, falsche Zählungen, ungültige Indizes) ergeben ein
|
||||
//! leeres Ergebnis statt eines Panics.
|
||||
|
||||
use kernel2d::{self as k, BulgeChainInput, BulgePolyline, Polyline, TangentTarget, Vec2};
|
||||
use kernel2d::{self as k, TangentTarget, Vec2};
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
// --- Lesen -------------------------------------------------------------------
|
||||
@@ -39,25 +37,6 @@ impl<'a> Reader<'a> {
|
||||
self.i = end;
|
||||
Some(slice.chunks_exact(2).map(|c| Vec2::new(c[0], c[1])).collect())
|
||||
}
|
||||
fn values(&mut self, n: usize) -> Option<Vec<f64>> {
|
||||
let end = self.i.checked_add(n)?;
|
||||
let slice = self.buf.get(self.i..end)?;
|
||||
self.i = end;
|
||||
Some(slice.to_vec())
|
||||
}
|
||||
/// Kette `closed, n_pts, xy…, n_bulge, b…` (`n_bulge = -1` → None).
|
||||
fn chain(&mut self) -> Option<(Vec<Vec2>, bool, Option<Vec<f64>>)> {
|
||||
let closed = self.f()? != 0.0;
|
||||
let n = self.count()?;
|
||||
let pts = self.pts(n)?;
|
||||
let nb = self.f()?;
|
||||
let bulge = if nb == -1.0 { None } else { Some(self.values(count(nb)?)?) };
|
||||
Some((pts, closed, bulge))
|
||||
}
|
||||
fn chains(&mut self) -> Option<Vec<(Vec<Vec2>, bool, Option<Vec<f64>>)>> {
|
||||
let n = self.count()?;
|
||||
(0..n).map(|_| self.chain()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Nicht-negative ganze Zahl (Zählung/Index) oder None.
|
||||
@@ -76,20 +55,6 @@ fn pts(buf: &[f64]) -> Option<Vec<Vec2>> {
|
||||
Some(buf.chunks_exact(2).map(|c| Vec2::new(c[0], c[1])).collect())
|
||||
}
|
||||
|
||||
fn cutters(buf: &[f64]) -> Option<Vec<Polyline>> {
|
||||
let list = Reader::new(buf).chains()?;
|
||||
Some(list.into_iter().map(|(pts, closed, _)| Polyline { pts, closed }).collect())
|
||||
}
|
||||
|
||||
fn bulge_cutters(buf: &[f64]) -> Option<Vec<BulgePolyline>> {
|
||||
let list = Reader::new(buf).chains()?;
|
||||
Some(
|
||||
list.into_iter()
|
||||
.map(|(pts, closed, bulge)| BulgePolyline { pts, closed, bulge: bulge.unwrap_or_default() })
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn pt_lists(buf: &[f64]) -> Option<Vec<Vec<Vec2>>> {
|
||||
let mut r = Reader::new(buf);
|
||||
let n = r.count()?;
|
||||
@@ -130,26 +95,6 @@ fn enc_pt_lists(lists: &[Vec<Vec2>]) -> Vec<f64> {
|
||||
out
|
||||
}
|
||||
|
||||
fn enc_chains<'a>(chains: impl ExactSizeIterator<Item = (&'a [Vec2], bool, &'a [f64])>) -> Vec<f64> {
|
||||
let mut out = vec![chains.len() as f64];
|
||||
for (pts, closed, bulge) in chains {
|
||||
out.push(if closed { 1.0 } else { 0.0 });
|
||||
out.push(pts.len() as f64);
|
||||
push_pts(&mut out, pts);
|
||||
out.push(bulge.len() as f64);
|
||||
out.extend_from_slice(bulge);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn enc_polylines(list: &[Polyline]) -> Vec<f64> {
|
||||
enc_chains(list.iter().map(|p| (p.pts.as_slice(), p.closed, &[][..])))
|
||||
}
|
||||
|
||||
fn enc_bulge_polylines(list: &[BulgePolyline]) -> Vec<f64> {
|
||||
enc_chains(list.iter().map(|p| (p.pts.as_slice(), p.closed, p.bulge.as_slice())))
|
||||
}
|
||||
|
||||
/// `[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];
|
||||
@@ -196,50 +141,13 @@ pub fn k2_offset_segment(ax: f64, ay: f64, bx: f64, by: f64, d: f64) -> Vec<f64>
|
||||
vec![a.x, a.y, b.x, b.y]
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn k2_offset_polyline(p: &[f64], d: f64, closed: bool) -> Vec<f64> {
|
||||
pts(p).map_or_else(Vec::new, |p| enc_pts(&k::offset_polyline(&p, d, closed)))
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn k2_offset_polyline_with_bulge(p: &[f64], bulge: &[f64], d: f64, closed: bool) -> Vec<f64> {
|
||||
let Some(p) = pts(p) else { return enc_pts_bulge(&[], &[]) };
|
||||
let (out, b) = k::offset_polyline_with_bulge(&p, bulge, d, closed);
|
||||
enc_pts_bulge(&out, &b)
|
||||
}
|
||||
|
||||
// --- Trim / Extend -----------------------------------------------------------
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn k2_trim_polyline(p: &[f64], closed: bool, cut: &[f64], px: f64, py: f64) -> Vec<f64> {
|
||||
let (Some(p), Some(cut)) = (pts(p), cutters(cut)) else { return EMPTY_LIST.to_vec() };
|
||||
enc_polylines(&k::trim_polyline(&p, closed, &cut, Vec2::new(px, py)))
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn k2_trim_polyline_with_bulge(p: &[f64], bulge: &[f64], closed: bool, cut: &[f64], px: f64, py: f64) -> Vec<f64> {
|
||||
let (Some(p), Some(cut)) = (pts(p), bulge_cutters(cut)) else { return EMPTY_LIST.to_vec() };
|
||||
enc_bulge_polylines(&k::trim_polyline_with_bulge(&p, bulge, closed, &cut, Vec2::new(px, py)))
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn k2_extend_segment(a1x: f64, a1y: f64, a2x: f64, a2y: f64, at_end: bool, cut: &[f64]) -> Vec<f64> {
|
||||
let Some(cut) = cutters(cut) else { return Vec::new() };
|
||||
let end = if at_end { "end" } else { "start" };
|
||||
match k::extend_segment(Vec2::new(a1x, a1y), Vec2::new(a2x, a2y), end, &cut) {
|
||||
Some((a, b)) => vec![a.x, a.y, b.x, b.y],
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn k2_extend_bulge_segment(ax: f64, ay: f64, bx: f64, by: f64, bulge: f64, at_end: bool, cut: &[f64]) -> Vec<f64> {
|
||||
let Some(cut) = cutters(cut) else { return Vec::new() };
|
||||
match k::extend_bulge_segment(Vec2::new(ax, ay), Vec2::new(bx, by), bulge, at_end, &cut) {
|
||||
Some((p, b)) => vec![p.x, p.y, b],
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
// --- Ecken -------------------------------------------------------------------
|
||||
|
||||
@@ -262,13 +170,6 @@ pub fn k2_fillet_corner(cx: f64, cy: f64, p1x: f64, p1y: f64, p2x: f64, p2y: f64
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn k2_chamfer_corner(cx: f64, cy: f64, p1x: f64, p1y: f64, p2x: f64, p2y: f64, distance: f64) -> Vec<f64> {
|
||||
match k::chamfer_corner(Vec2::new(cx, cy), Vec2::new(p1x, p1y), Vec2::new(p2x, p2y), distance) {
|
||||
Some(c) => vec![c.a.x, c.a.y, c.b.x, c.b.y],
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
// --- Split / Join / Segment löschen / Bruch ----------------------------------------
|
||||
|
||||
@@ -301,20 +202,7 @@ pub fn k2_remove_segment_with_bulge(p: &[f64], bulge: &[f64], closed: bool, edge
|
||||
enc_pts_bulge(&r.pts, &r.bulge)
|
||||
}
|
||||
|
||||
/// `[edgeIndex, t]` oder leer.
|
||||
#[wasm_bindgen]
|
||||
pub fn k2_nearest_on_polyline(p: &[f64], closed: bool, px: f64, py: f64) -> Vec<f64> {
|
||||
match pts(p).and_then(|p| k::nearest_on_polyline(&p, closed, Vec2::new(px, py))) {
|
||||
Some((e, t)) => vec![e as f64, t],
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn k2_break_curve(p: &[f64], e1: f64, t1: f64, e2: f64, t2: f64) -> Vec<f64> {
|
||||
let (Some(p), Some(e1), Some(e2)) = (pts(p), count(e1), count(e2)) else { return EMPTY_LIST.to_vec() };
|
||||
enc_pt_lists(&k::break_curve(&p, (e1, t1), (e2, t2)))
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn k2_split_at_intersections(target: &[f64], closed: bool, others: &[f64]) -> Vec<f64> {
|
||||
@@ -322,13 +210,6 @@ pub fn k2_split_at_intersections(target: &[f64], closed: bool, others: &[f64]) -
|
||||
enc_pt_lists(&k::split_at_intersections(&target, closed, &others))
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn k2_join_chains_with_bulge(chains: &[f64]) -> Vec<f64> {
|
||||
let Some(list) = Reader::new(chains).chains() else { return EMPTY_LIST.to_vec() };
|
||||
let input: Vec<BulgeChainInput> =
|
||||
list.into_iter().map(|(pts, closed, bulge)| BulgeChainInput { pts, closed, bulge }).collect();
|
||||
enc_bulge_polylines(&k::join_chains_with_bulge(&input))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -336,21 +217,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn kaputte_puffer_ergeben_leere_ergebnisse() {
|
||||
assert!(k2_offset_polyline(&[0.0, 0.0, 1.0], 0.1, false).is_empty());
|
||||
assert_eq!(k2_trim_polyline(&[0.0, 0.0, 1.0, 0.0], false, &[1.0, 0.0, 5.0], 0.0, 0.0), vec![0.0]);
|
||||
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_eq!(k2_join_chains_with_bulge(&[2.0, 0.0, 1.0, 0.0, 0.0, -1.0]), vec![0.0]);
|
||||
assert!(k2_tangent_circle_centers(&[3.0], &[0.0, 0.0, 0.0, 1.0, 0.0], 1.0).is_empty());
|
||||
assert!(k2_nearest_on_polyline(&[f64::NAN], false, 0.0, 0.0).is_empty());
|
||||
assert_eq!(k2_break_curve(&[0.0, 0.0, 1.0, 0.0], 3.0, 0.5, 0.0, 0.5), vec![0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ketten_hin_und_zurueck() {
|
||||
// Zwei offene Ketten, eine ohne bulge (-1) → verbunden, bulge mitgetragen.
|
||||
let input = [2.0, 0.0, 2.0, -1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 2.0, 1.0, 0.0, 3.0, 0.0, -1.0];
|
||||
let out = k2_join_chains_with_bulge(&input);
|
||||
assert_eq!(out, vec![1.0, 0.0, 3.0, -1.0, 0.0, 1.0, 0.0, 3.0, 0.0, 2.0, 1.0, 0.0]);
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ mod parametric_walls;
|
||||
mod reorder;
|
||||
mod text_layout;
|
||||
mod grips;
|
||||
mod commands;
|
||||
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
|
||||
+12
-56
@@ -18,65 +18,21 @@
|
||||
// Ring-Bögen übrig bleibt, ist klick-reihenfolge-abhängig — eigener,
|
||||
// grösserer Scope) und Bogen-Segmente (bulge) — beide s. PENDENZEN.md.
|
||||
|
||||
import type { Drawing2D } from "../../model/types";
|
||||
import { uniqueId } from "../../tools/types";
|
||||
import { addItems, opsMutation, removeItems } from "../../core";
|
||||
import type { CoreOp } from "../../core";
|
||||
import { breakCurve, nearestOnPolyline } from "../../core";
|
||||
import { hasRealBulge } from "../../core";
|
||||
import { chainToGeom, geomToCurve, isTrimmable, pickCurveAt } from "./trim";
|
||||
import type {
|
||||
Command,
|
||||
CommandResult,
|
||||
CommandState,
|
||||
DraftShape,
|
||||
Project,
|
||||
Vec2,
|
||||
} from "../types";
|
||||
// Treffer, Reststücke und Vorschau rechnet der Kern (`src-tauri/core/src/cmd_edit.rs`, [K4] S3,
|
||||
// Geometrie `breakCurve` in `kernel2d`); hier nur der Zustandsautomat.
|
||||
|
||||
/** Trifft der Klick eine offene, bogen-freie Kurve (line/gerade polyline)? */
|
||||
function pickBreakable(project: Project, levelId: string, pt: Vec2): Drawing2D | null {
|
||||
const d = pickCurveAt(project, levelId, pt);
|
||||
if (!d || !isTrimmable(d)) return null;
|
||||
const curve = geomToCurve(d.geom);
|
||||
if (!curve || curve.closed || hasRealBulge(curve.bulge)) return null;
|
||||
return d;
|
||||
}
|
||||
|
||||
function breakOps(p: Project, target: Drawing2D, p1: Vec2, p2: Vec2): CoreOp[] {
|
||||
const curve = geomToCurve(target.geom);
|
||||
if (!curve) return [];
|
||||
const hit1 = nearestOnPolyline(curve.pts, false, p1);
|
||||
const hit2 = nearestOnPolyline(curve.pts, false, p2);
|
||||
if (!hit1 || !hit2) return [];
|
||||
const pieces = breakCurve(curve.pts, hit1, hit2);
|
||||
const replacements: Drawing2D[] = pieces.map((pts) => ({
|
||||
...target,
|
||||
id: uniqueId("dr2d"),
|
||||
geom: chainToGeom({ pts, closed: false }),
|
||||
}));
|
||||
// Ziel raus, Stücke hinten dran.
|
||||
return [...removeItems(p, "drawings2d", [target.id]), ...addItems("drawings2d", replacements)];
|
||||
}
|
||||
|
||||
/** Vorschau der Reststücke (für den Draft). */
|
||||
function breakPreview(target: Drawing2D, p1: Vec2, p2: Vec2): DraftShape[] {
|
||||
const curve = geomToCurve(target.geom);
|
||||
if (!curve) return [];
|
||||
const hit1 = nearestOnPolyline(curve.pts, false, p1);
|
||||
const hit2 = nearestOnPolyline(curve.pts, false, p2);
|
||||
if (!hit1 || !hit2) return [];
|
||||
return breakCurve(curve.pts, hit1, hit2)
|
||||
.filter((pts) => pts.length >= 2)
|
||||
.map((pts) => (pts.length === 2 ? { kind: "line" as const, a: pts[0], b: pts[1] } : { kind: "poly" as const, pts, closed: false }));
|
||||
}
|
||||
import { cmdMutation } from "../../core";
|
||||
import { uniqueStamp } from "../../tools/types";
|
||||
import { cmdQuery, decodeShapes, pair } from "../../tools/coreCmd";
|
||||
import type { Command, CommandResult, CommandState, Vec2 } from "../types";
|
||||
|
||||
interface BreakP1 extends CommandState {
|
||||
phase: "p1";
|
||||
}
|
||||
interface BreakP2 extends CommandState {
|
||||
phase: "p2";
|
||||
target: Drawing2D;
|
||||
/** Getroffene Kurve (id). */
|
||||
target: string;
|
||||
p1: Vec2;
|
||||
cursor: Vec2 | null;
|
||||
}
|
||||
@@ -99,21 +55,21 @@ export const breakCommand: Command = {
|
||||
const s = state as BreakState;
|
||||
if (input.kind !== "point") return [s, { draft: null }];
|
||||
if (s.phase === "p1") {
|
||||
const target = pickBreakable(ctx.project, ctx.level.id, input.point);
|
||||
const target = cmdQuery<{ hit: string | null }>(ctx.project, { q: "pickBreakable", level: ctx.level.id, pt: pair(input.point) }).hit;
|
||||
if (!target) return [s, { draft: null }]; // daneben/ungeeignet → bleibt im ersten Schritt
|
||||
const ns: BreakP2 = { phase: "p2", target, p1: input.point, cursor: input.point, lastPoint: input.point };
|
||||
return [ns, { draft: null }];
|
||||
}
|
||||
// phase "p2"
|
||||
const { target, p1 } = s;
|
||||
return [idle()[0], { draft: null, done: true, commit: opsMutation((p) => breakOps(p, target, p1, input.point)) }];
|
||||
return [idle()[0], { draft: null, done: true, commit: cmdMutation({ cmd: "break", id: target, p1: pair(p1), p2: pair(input.point), stamp: uniqueStamp() }) }];
|
||||
},
|
||||
|
||||
onMove: (state, point): [CommandState, CommandResult] => {
|
||||
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as BreakState;
|
||||
if (s.phase !== "p2") return [s, { draft: null }];
|
||||
const ns: BreakP2 = { ...s, cursor: point };
|
||||
const preview = breakPreview(s.target, s.p1, point);
|
||||
const preview = decodeShapes(cmdQuery<{ shapes: number[] }>(ctx.project, { q: "break", id: s.target, p1: pair(s.p1), pt: pair(point) }).shapes);
|
||||
return [ns, { draft: { preview, vertices: [s.p1] } }];
|
||||
},
|
||||
|
||||
|
||||
@@ -8,11 +8,7 @@
|
||||
// Anders als Fillet braucht Chamfer KEINE Bogen-Tessellierung — die Fasung
|
||||
// ist von Natur aus gerade, also ein exaktes (nicht approximiertes) Ergebnis.
|
||||
|
||||
import type { Drawing2D, Drawing2DGeom } from "../../model/types";
|
||||
import { opsMutation, patchItem } from "../../core";
|
||||
import type { CoreOp } from "../../core";
|
||||
import { hasRealBulge } from "../../core";
|
||||
import { chamferCorner, type Chamfer } from "../../core";
|
||||
import { cmdMutation } from "../../core";
|
||||
import type {
|
||||
Command,
|
||||
CommandContext,
|
||||
@@ -20,98 +16,23 @@ import type {
|
||||
CommandResult,
|
||||
CommandState,
|
||||
DraftShape,
|
||||
Project,
|
||||
ToolDraft,
|
||||
Vec2,
|
||||
} from "../types";
|
||||
import { cornerPreview, pickCorner } from "./cornerHit";
|
||||
import type { CornerHit } from "./cornerHit";
|
||||
|
||||
const HIT_TOL = 0.3; // Modell-Meter: Pick-Toleranz für die Eckenwahl
|
||||
const DEFAULT_DISTANCE = 0.1; // m — Startwert, bis der Nutzer per Maus/Tab einen eigenen setzt
|
||||
const EPS = 1e-6;
|
||||
const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
|
||||
|
||||
interface Curve {
|
||||
pts: Vec2[];
|
||||
closed: boolean;
|
||||
}
|
||||
|
||||
/** Wandelt eine chamfer-fähige 2D-Form (polyline/rect) in eine Punktliste oder null. */
|
||||
function geomToCurve(g: Drawing2DGeom): Curve | null {
|
||||
// Bogen-Segmente (bulge) hier noch nicht unterstützt, s. fillet.ts/offset.ts.
|
||||
if (g.shape === "polyline" && !hasRealBulge(g.bulge)) return { pts: g.pts, closed: g.closed };
|
||||
if (g.shape === "rect") {
|
||||
return {
|
||||
pts: [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }],
|
||||
closed: true,
|
||||
};
|
||||
}
|
||||
return null; // line (keine eigene Ecke), circle/arc/text: nicht chamfer-fähig
|
||||
}
|
||||
|
||||
/** Ein Treffer: das Element + der Eckpunkt-Index (mit gültigen beiden Nachbarn). */
|
||||
interface CornerHit {
|
||||
drawing: Drawing2D;
|
||||
curve: Curve;
|
||||
index: number;
|
||||
}
|
||||
|
||||
/** Nächster Eckpunkt (mit zwei Nachbarn) einer chamfer-fähigen Drawing2D zum Klickpunkt. */
|
||||
function pickCornerAt(project: Project, levelId: string, pt: Vec2): CornerHit | null {
|
||||
let best: CornerHit | null = null;
|
||||
let bestD = HIT_TOL;
|
||||
for (const d of project.drawings2d) {
|
||||
if (d.levelId !== levelId) continue;
|
||||
const curve = geomToCurve(d.geom);
|
||||
if (!curve) continue;
|
||||
const n = curve.pts.length;
|
||||
for (let i = 0; i < n; i++) {
|
||||
// Offene Polylinie: die beiden Endpunkte haben keinen zweiten Nachbarn.
|
||||
if (!curve.closed && (i === 0 || i === n - 1)) continue;
|
||||
const dd = dist(pt, curve.pts[i]);
|
||||
if (dd < bestD) {
|
||||
bestD = dd;
|
||||
best = { drawing: d, curve, index: i };
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Fasungs-Geometrie für einen Treffer + Distanz (oder null, falls unmöglich). */
|
||||
function chamferFor(hit: CornerHit, distance: number): Chamfer | null {
|
||||
const n = hit.curve.pts.length;
|
||||
const prev = hit.curve.pts[(hit.index - 1 + n) % n];
|
||||
const next = hit.curve.pts[(hit.index + 1) % n];
|
||||
const corner = hit.curve.pts[hit.index];
|
||||
return chamferCorner(corner, prev, next, distance);
|
||||
}
|
||||
|
||||
/** Ersetzt den Eckpunkt durch die beiden Fasungs-Punkte (Schenkel↔Schenkel). */
|
||||
function applyChamferPoints(hit: CornerHit, c: Chamfer): Vec2[] {
|
||||
return [
|
||||
...hit.curve.pts.slice(0, hit.index),
|
||||
c.a,
|
||||
c.b,
|
||||
...hit.curve.pts.slice(hit.index + 1),
|
||||
];
|
||||
}
|
||||
|
||||
function chamferDraft(hit: CornerHit, d: number, at: Vec2 | null): ToolDraft {
|
||||
const c = d > EPS ? chamferFor(hit, d) : null;
|
||||
const preview: DraftShape[] = c ? [{ kind: "poly", pts: [c.a, c.b], closed: false }] : [];
|
||||
const draft: ToolDraft = { preview, vertices: [hit.curve.pts[hit.index]] };
|
||||
if (at) draft.hud = { at, text: `D: ${d.toFixed(3)}m${c ? "" : " ✗"}` };
|
||||
/** Entwurf: Vorschau (Kern) + Ecke als Marke + Messwert (✗, wenn die Distanz nicht passt). */
|
||||
function chamferDraft(hit: CornerHit, preview: DraftShape[], v: number, at: Vec2 | null): ToolDraft {
|
||||
const draft: ToolDraft = { preview, vertices: [hit.corner] };
|
||||
if (at) draft.hud = { at, text: `D: ${v.toFixed(3)}m${preview.length ? "" : " ✗"}` };
|
||||
return draft;
|
||||
}
|
||||
|
||||
function chamferOps(p: Project, hit: CornerHit, distance: number): CoreOp[] {
|
||||
const c = chamferFor(hit, distance);
|
||||
if (!c) return []; // Distanz zu gross für die Schenkellänge, oder Ecke (fast) gerade → No-op
|
||||
const pts = applyChamferPoints(hit, c);
|
||||
const geom: Drawing2DGeom = { shape: "polyline", pts, closed: hit.curve.closed };
|
||||
return patchItem(p, "drawings2d", hit.drawing.id, { geom });
|
||||
}
|
||||
|
||||
// ── Zustand ───────────────────────────────────────────────────────────────────
|
||||
const DISTANCE_FIELDS: CommandField[] = [{ id: "distance", labelKey: "cmd.field.distance" }];
|
||||
|
||||
@@ -149,7 +70,7 @@ export const chamferCommand: Command = {
|
||||
if (s.phase === "done") return finish();
|
||||
if (s.phase === "pick") {
|
||||
if (input.kind !== "point") return [s, { draft: null }];
|
||||
const hit = pickCornerAt(ctx.project, ctx.level.id, input.point);
|
||||
const { hit, preview } = pickCorner(ctx.project, ctx.level.id, input.point, "chamfer", DEFAULT_DISTANCE);
|
||||
if (!hit) return [s, { draft: null }]; // daneben geklickt → aktiv bleiben
|
||||
const next: ChamferDistance = {
|
||||
phase: "distance",
|
||||
@@ -157,30 +78,30 @@ export const chamferCommand: Command = {
|
||||
distance: DEFAULT_DISTANCE,
|
||||
lastPoint: input.point,
|
||||
};
|
||||
return [next, { draft: chamferDraft(hit, next.distance, input.point) }];
|
||||
return [next, { draft: chamferDraft(hit, preview, next.distance, input.point) }];
|
||||
}
|
||||
// phase === "distance"
|
||||
let d = s.distance;
|
||||
if (input.kind === "number") d = Math.max(0, input.value);
|
||||
else if (input.kind === "point") d = Math.max(0, dist(s.hit.curve.pts[s.hit.index], input.point));
|
||||
else if (input.kind === "point") d = Math.max(0, dist(s.hit.corner, input.point));
|
||||
else return [s, { draft: null }];
|
||||
return [
|
||||
{ phase: "done", lastPoint: null } as ChamferDone,
|
||||
{ draft: null, done: true, commit: opsMutation((p) => chamferOps(p, s.hit, d)) },
|
||||
{ draft: null, done: true, commit: cmdMutation({ cmd: "chamfer", id: s.hit.id, index: s.hit.index, d }) },
|
||||
];
|
||||
},
|
||||
|
||||
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as ChamferState;
|
||||
if (s.phase === "pick") {
|
||||
const hit = pickCornerAt(ctx.project, ctx.level.id, point);
|
||||
const { hit, preview } = pickCorner(ctx.project, ctx.level.id, point, "chamfer", DEFAULT_DISTANCE);
|
||||
if (!hit) return [s, { draft: null }];
|
||||
return [s, { draft: chamferDraft(hit, DEFAULT_DISTANCE, point) }];
|
||||
return [s, { draft: chamferDraft(hit, preview, DEFAULT_DISTANCE, point) }];
|
||||
}
|
||||
if (s.phase !== "distance") return [s, { draft: null }];
|
||||
const d = Math.max(0, dist(s.hit.curve.pts[s.hit.index], point));
|
||||
const d = Math.max(0, dist(s.hit.corner, point));
|
||||
const ns: ChamferDistance = { ...s, distance: d };
|
||||
return [ns, { draft: chamferDraft(s.hit, d, point) }];
|
||||
return [ns, { draft: chamferDraft(s.hit, cornerPreview(ctx.project, s.hit, "chamfer", d), d, point) }];
|
||||
},
|
||||
|
||||
onConfirm: (): [CommandState, CommandResult] => finish(),
|
||||
@@ -190,12 +111,12 @@ export const chamferCommand: Command = {
|
||||
fieldValues: (state, _locks, cursor): Record<string, number> => {
|
||||
const s = state as ChamferState;
|
||||
if (s.phase !== "distance" || !cursor) return {};
|
||||
return { distance: dist(s.hit.curve.pts[s.hit.index], cursor) };
|
||||
return { distance: dist(s.hit.corner, cursor) };
|
||||
},
|
||||
pointFromFields: (state, locks, cursor) => {
|
||||
const s = state as ChamferState;
|
||||
if (s.phase !== "distance") return null;
|
||||
const corner = s.hit.curve.pts[s.hit.index];
|
||||
const corner = s.hit.corner;
|
||||
const d = "distance" in locks ? Math.max(0, locks.distance) : cursor ? dist(corner, cursor) : 0;
|
||||
if (cursor) {
|
||||
const dd = dist(corner, cursor);
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// Ecken-Treffer für Verrunden/Fasen ([K4] S3): Treffer und Vorschau rechnet der Kern
|
||||
// (`src-tauri/core/src/cmd_edit.rs`); der Befehl merkt sich nur Element, Eckpunkt-Index und die Ecke.
|
||||
|
||||
import type { Project, Vec2 } from "../../model/types";
|
||||
import type { DraftShape } from "../types";
|
||||
import { cmdQuery, decodeShapes, pair } from "../../tools/coreCmd";
|
||||
|
||||
/** Getroffene Ecke: Element, Eckpunkt-Index (mit zwei Nachbarn), Lage der Ecke. */
|
||||
export interface CornerHit {
|
||||
id: string;
|
||||
index: number;
|
||||
corner: Vec2;
|
||||
}
|
||||
|
||||
export type CornerKind = "fillet" | "chamfer";
|
||||
|
||||
/**
|
||||
* Nächste Ecke einer Polylinie/eines Rechtecks der Ebene zum Punkt (Polylinien mit Bögen ausgenommen)
|
||||
* samt Vorschau der Verrundung/Fasung mit `r`.
|
||||
*/
|
||||
export function pickCorner(project: Project, levelId: string, pt: Vec2, kind: CornerKind, r: number): { hit: CornerHit | null; preview: DraftShape[] } {
|
||||
const res = cmdQuery<{ hit: { id: string; index: number; corner: [number, number] } | null; shapes: number[] }>(project, {
|
||||
q: "pickCorner",
|
||||
level: levelId,
|
||||
pt: pair(pt),
|
||||
kind,
|
||||
r,
|
||||
});
|
||||
if (!res.hit) return { hit: null, preview: [] };
|
||||
const { id, index, corner } = res.hit;
|
||||
return { hit: { id, index, corner: { x: corner[0], y: corner[1] } }, preview: decodeShapes(res.shapes) };
|
||||
}
|
||||
|
||||
/** Vorschau der Verrundung/Fasung einer gemerkten Ecke (leer, wenn sie mit `r` nicht geht). */
|
||||
export function cornerPreview(project: Project, hit: CornerHit, kind: CornerKind, r: number): DraftShape[] {
|
||||
return decodeShapes(cmdQuery<{ shapes: number[] }>(project, { q: "corner", kind, id: hit.id, index: hit.index, r }).shapes);
|
||||
}
|
||||
@@ -10,10 +10,10 @@
|
||||
// verschachtelten Blöcke, v1 — s. `BlockDef`-Kopfkommentar in model/types.ts).
|
||||
// Leere/rein-block-Auswahl → No-Op (kein Commit).
|
||||
|
||||
import type { BlockDef, Drawing2D } from "../../model/types";
|
||||
import { addItems, mvGeom, opsMutation, removeItems } from "../../core";
|
||||
import { opsMutation } from "../../core";
|
||||
import type { CoreOp } from "../../core";
|
||||
import { uniqueId } from "../../tools/types";
|
||||
import { documentFor } from "../../core/document";
|
||||
import { uniqueStamp } from "../../tools/types";
|
||||
import type {
|
||||
Command,
|
||||
CommandContext,
|
||||
@@ -29,34 +29,16 @@ function selectedDrawingIds(sel: CommandSelection): string[] {
|
||||
return sel.drawingId ? [sel.drawingId] : [];
|
||||
}
|
||||
|
||||
function nextBlockName(p: Project): string {
|
||||
return `Block ${(p.blockDefs?.length ?? 0) + 1}`;
|
||||
}
|
||||
|
||||
/** Definition anhängen, Quellen raus, Instanz hinten dran — rechnet der Kern (`cmd_transform::defblock_ops`). */
|
||||
function defineOps(p: Project, ids: string[], at: Vec2, ctx: CommandContext): CoreOp[] {
|
||||
const idSet = new Set(ids);
|
||||
// Block-Instanzen als Quelle ausschliessen (keine verschachtelten Blöcke).
|
||||
const srcs = p.drawings2d.filter((d) => idSet.has(d.id) && d.geom.shape !== "block");
|
||||
if (srcs.length === 0) return [];
|
||||
const toLocal = (pt: Vec2): Vec2 => ({ x: pt.x - at.x, y: pt.y - at.y });
|
||||
const def: BlockDef = {
|
||||
id: uniqueId("blk"),
|
||||
name: nextBlockName(p),
|
||||
geom2d: srcs.map((d) => mvGeom(d.geom, toLocal)),
|
||||
};
|
||||
const instance: Drawing2D = {
|
||||
id: uniqueId("dr2d"),
|
||||
type: "drawing2d",
|
||||
return documentFor(p).cmdOps({
|
||||
cmd: "defblock",
|
||||
ids,
|
||||
at: [at.x, at.y],
|
||||
levelId: ctx.level.id,
|
||||
categoryCode: ctx.defaultCategoryCode,
|
||||
geom: { shape: "block", blockDefId: def.id, at, rotation: 0 },
|
||||
};
|
||||
// Definition anhängen, Quellen raus, Instanz hinten dran.
|
||||
return [
|
||||
...addItems("blockDefs", [def]),
|
||||
...removeItems(p, "drawings2d", srcs.map((d) => d.id)),
|
||||
...addItems("drawings2d", [instance]),
|
||||
];
|
||||
stamp: uniqueStamp(),
|
||||
});
|
||||
}
|
||||
|
||||
interface DefblockState extends CommandState {
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
// Teilgeometrien, Polylinie → Segmente, Rechteck → vier Linien). Sofort-Befehl
|
||||
// ohne Punkt-Eingabe (wie Join/Split): wirkt auf die bestehende Auswahl.
|
||||
//
|
||||
// Die eigentliche Zerlegung liegt in `editors/explode.ts` — dort auch, was
|
||||
// Die eigentliche Zerlegung rechnet der Kern (`cmd_edit.rs`, Fassade `editors/explode.ts`) — dort auch, was
|
||||
// bewusst NICHT zerlegt wird (Kreis/Ellipse/Spline/Text/…): diese Elemente
|
||||
// bleiben unverändert stehen, statt zu verschwinden.
|
||||
|
||||
import { explodeOps } from "../../editors/explode";
|
||||
import { opsMutation } from "../../core";
|
||||
import { cmdMutation } from "../../core";
|
||||
import { uniqueStamp } from "../../tools/types";
|
||||
import type { Command, CommandContext, CommandResult, CommandSelection, CommandState } from "../types";
|
||||
|
||||
/** Gewählte 2D-Elemente (Mehrfachauswahl bevorzugt). */
|
||||
@@ -32,7 +32,7 @@ export const explodeCommand: Command = {
|
||||
autoRun: (ctx: CommandContext): CommandResult => {
|
||||
const ids = selectedDrawingIds(ctx.selection);
|
||||
if (ids.length === 0) return { draft: null, done: true };
|
||||
return { draft: null, done: true, commit: opsMutation((p) => explodeOps(p, ids)) };
|
||||
return { draft: null, done: true, commit: cmdMutation({ cmd: "explode", ids, stamp: uniqueStamp() }) };
|
||||
},
|
||||
|
||||
onInput: (): [CommandState, CommandResult] => done(),
|
||||
|
||||
+15
-171
@@ -12,175 +12,20 @@
|
||||
//
|
||||
// Geschlossene Formen (rect, geschlossene polyline) und reine Punktformen
|
||||
// (circle/arc/text) sind nicht extend-fähig — ein geschlossener Ring hat kein
|
||||
// "Ende". Reine Geometrie liegt im Kernel (`extendSegment`/`extendBulgeSegment`);
|
||||
// hier nur Treffer-Bestimmung, Drawing2D ↔ {pts,closed,bulge} und der Commit.
|
||||
// "Ende". Treffer, Schneider und Verlängerung rechnet der Kern
|
||||
// (`src-tauri/core/src/cmd_edit.rs`, [K4] S3, Geometrie `extendSegment`/`extendBulgeSegment`
|
||||
// in `kernel2d`); hier nur der Zustandsautomat.
|
||||
//
|
||||
// Bogen-Enden: ist das äusserste Segment ein echter Bogen (bulge), verlängert
|
||||
// `extendBulgeSegment` denselben Kreis (Mittelpunkt/Radius unverändert, nur
|
||||
// die Schwenk-Spanne wächst) bis zum nächsten Schneider — Cutter bleiben
|
||||
// bewusst GERADE (wie überall bei Trim/Extend, s. `cuttersFor`).
|
||||
// der Kern denselben Kreis (Mittelpunkt/Radius unverändert, nur die
|
||||
// Schwenk-Spanne wächst) bis zum nächsten Schneider — Cutter bleiben bewusst
|
||||
// GERADE (Polylinien mit Bögen schneiden nicht).
|
||||
//
|
||||
// Bezeichner englisch, Kommentare/UI deutsch (CONVENTIONS.md).
|
||||
|
||||
import type { Drawing2D, Drawing2DGeom } from "../../model/types";
|
||||
import { opsMutation, patchItem } from "../../core";
|
||||
import type { CoreOp } from "../../core";
|
||||
import { bulgePolylinePoints, hasRealBulge } from "../../core";
|
||||
import { extendBulgeSegment, extendSegment, pointSegmentDistance, polylineEdges } from "../../core";
|
||||
import type {
|
||||
Command,
|
||||
CommandResult,
|
||||
CommandState,
|
||||
DraftShape,
|
||||
Project,
|
||||
Vec2,
|
||||
} from "../types";
|
||||
|
||||
const HIT_TOL = 0.25; // Modell-Meter: Pick-Toleranz für die Kurvenwahl
|
||||
|
||||
interface Curve {
|
||||
pts: Vec2[];
|
||||
closed: boolean;
|
||||
bulge?: number[];
|
||||
}
|
||||
|
||||
/** Wandelt eine extend-fähige 2D-Form (offen) in eine Punktliste oder null. */
|
||||
function geomToOpenCurve(g: Drawing2DGeom): Curve | null {
|
||||
if (g.shape === "line") return { pts: [g.a, g.b], closed: false };
|
||||
if (g.shape === "polyline" && !g.closed) return { pts: g.pts, closed: false, bulge: g.bulge };
|
||||
return null; // rect/geschlossene polyline/circle/arc/text: kein Ende zum Verlängern
|
||||
}
|
||||
|
||||
/**
|
||||
* Treffer-Kanten einer (evtl. bulge-tragenden) Kurve für Pick/Preview: bei
|
||||
* echten Bogen-Segmenten wird tesselliert (Kreisbogen ≠ Sehne), sonst bleiben
|
||||
* es die rohen Polylinien-Kanten. Wortgetreu wie `offset.ts`/`trim.ts`.
|
||||
*/
|
||||
function curveHitEdges(curve: Curve): [Vec2, Vec2][] {
|
||||
if (!hasRealBulge(curve.bulge)) return polylineEdges(curve.pts, curve.closed);
|
||||
const chain = bulgePolylinePoints(curve.pts, curve.bulge, curve.closed);
|
||||
if (curve.closed) chain.push(curve.pts[0]); // Schlusskante mit-tesselliert, Kette endet am Start
|
||||
return polylineEdges(chain, false);
|
||||
}
|
||||
|
||||
/** Alle trim/extend-fähigen Drawing2D der Ebene als Cutter-Kurven (auch geschlossene). */
|
||||
function cuttersFor(project: Project, levelId: string, exceptId: string): Curve[] {
|
||||
const out: Curve[] = [];
|
||||
for (const d of project.drawings2d) {
|
||||
if (d.id === exceptId) continue;
|
||||
if (d.levelId !== levelId) continue;
|
||||
const g = d.geom;
|
||||
if (g.shape === "line") out.push({ pts: [g.a, g.b], closed: false });
|
||||
// Als Cutter würde eine Bogen-Polylinie fälschlich als Gerade behandelt
|
||||
// (falscher Schnittpunkt) — lieber als Cutter ignorieren als falsch rechnen.
|
||||
else if (g.shape === "polyline" && !hasRealBulge(g.bulge)) out.push({ pts: g.pts, closed: g.closed });
|
||||
else if (g.shape === "rect") {
|
||||
out.push({
|
||||
pts: [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }],
|
||||
closed: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Nächste extend-fähige (offene) Drawing2D der Ebene zum Klickpunkt. */
|
||||
function pickOpenCurveAt(project: Project, levelId: string, pt: Vec2): Drawing2D | null {
|
||||
let best: Drawing2D | null = null;
|
||||
let bestD = HIT_TOL;
|
||||
for (const d of project.drawings2d) {
|
||||
if (d.levelId !== levelId) continue;
|
||||
const curve = geomToOpenCurve(d.geom);
|
||||
if (!curve) continue;
|
||||
for (const [a, b] of curveHitEdges(curve)) {
|
||||
const dd = pointSegmentDistance(pt, a, b);
|
||||
if (dd < bestD) {
|
||||
bestD = dd;
|
||||
best = d;
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verlängert die Kurve am Ende, das dem Klickpunkt am nächsten liegt, bis zum
|
||||
* nächsten Schnitt mit den Cuttern (jenseits dieses Endes). Liefert die neuen
|
||||
* Punkte (+ ggf. bulge-Array), oder `null`, wenn kein Cutter getroffen wird
|
||||
* (kein Effekt). Ist das betroffene ÄUSSERSTE Segment ein echter Bogen, läuft
|
||||
* die Verlängerung über `extendBulgeSegment` (gleicher Kreis, grössere
|
||||
* Schwenk-Spanne) statt über die Geraden-Variante.
|
||||
*/
|
||||
function extendCurve(curve: Curve, cutters: Curve[], pick: Vec2): Curve | null {
|
||||
const n = curve.pts.length;
|
||||
if (n < 2) return null;
|
||||
const distStart = Math.hypot(pick.x - curve.pts[0].x, pick.y - curve.pts[0].y);
|
||||
const distEnd = Math.hypot(pick.x - curve.pts[n - 1].x, pick.y - curve.pts[n - 1].y);
|
||||
const extendStart = distStart <= distEnd;
|
||||
const segIdx = extendStart ? 0 : n - 2; // bulge-Index des äussersten Segments
|
||||
const bulgeVal = curve.bulge?.[segIdx] ?? 0;
|
||||
|
||||
if (Math.abs(bulgeVal) > 1e-9) {
|
||||
const a = curve.pts[segIdx];
|
||||
const b = curve.pts[segIdx + 1];
|
||||
const result = extendBulgeSegment(a, b, bulgeVal, extendStart ? "start" : "end", cutters);
|
||||
if (!result) return null;
|
||||
const nextPts = [...curve.pts];
|
||||
const nextBulge = curve.bulge ? [...curve.bulge] : new Array(n - 1).fill(0);
|
||||
if (extendStart) {
|
||||
nextPts[0] = result.point;
|
||||
nextBulge[0] = result.bulge;
|
||||
} else {
|
||||
nextPts[n - 1] = result.point;
|
||||
nextBulge[n - 2] = result.bulge;
|
||||
}
|
||||
return { pts: nextPts, closed: false, bulge: nextBulge };
|
||||
}
|
||||
|
||||
const idxA = extendStart ? 1 : n - 2;
|
||||
const idxB = extendStart ? 0 : n - 1;
|
||||
const result = extendSegment(curve.pts[idxA], curve.pts[idxB], "end", cutters);
|
||||
if (!result) return null;
|
||||
const next = [...curve.pts];
|
||||
next[idxB] = result[1];
|
||||
return { pts: next, closed: false, bulge: curve.bulge };
|
||||
}
|
||||
|
||||
/** Wendet Extend auf das Projekt an: ersetzt die getroffene Kurve durch ihre verlängerte Form. */
|
||||
function extendOps(p: Project, target: Drawing2D, pick: Vec2): CoreOp[] {
|
||||
const curve = geomToOpenCurve(target.geom);
|
||||
if (!curve) return [];
|
||||
const cutters = cuttersFor(p, target.levelId, target.id);
|
||||
const next = extendCurve(curve, cutters, pick);
|
||||
if (!next) return [];
|
||||
const geom: Drawing2DGeom =
|
||||
next.pts.length === 2 && target.geom.shape === "line" && !hasRealBulge(next.bulge)
|
||||
? { shape: "line", a: next.pts[0], b: next.pts[1] }
|
||||
: {
|
||||
shape: "polyline",
|
||||
pts: next.pts,
|
||||
closed: false,
|
||||
...(hasRealBulge(next.bulge) ? { bulge: next.bulge } : {}),
|
||||
};
|
||||
return patchItem(p, "drawings2d", target.id, { geom });
|
||||
}
|
||||
|
||||
/** Vorschau-Form der verlängerten Kurve (für den Draft — Bogen tesselliert, s. `curveHitEdges`). */
|
||||
function extendPreview(project: Project, target: Drawing2D, pick: Vec2): DraftShape[] {
|
||||
const curve = geomToOpenCurve(target.geom);
|
||||
if (!curve) return [];
|
||||
const cutters = cuttersFor(project, target.levelId, target.id);
|
||||
const next = extendCurve(curve, cutters, pick);
|
||||
if (!next) return [];
|
||||
const pts = hasRealBulge(next.bulge)
|
||||
? curveHitEdges(next).reduce<Vec2[]>((acc, [a, b], i) => {
|
||||
if (i === 0) acc.push(a);
|
||||
acc.push(b);
|
||||
return acc;
|
||||
}, [])
|
||||
: next.pts;
|
||||
return [{ kind: "poly", pts, closed: false }];
|
||||
}
|
||||
import { cmdMutation } from "../../core";
|
||||
import { cmdQuery, decodeShapes, pair } from "../../tools/coreCmd";
|
||||
import type { Command, CommandResult, CommandState } from "../types";
|
||||
|
||||
// ── Zustand ───────────────────────────────────────────────────────────────────
|
||||
// Einziger Schritt „pick": auf die zu verlängernde Kurve (nahe dem Ende) klicken;
|
||||
@@ -211,18 +56,17 @@ export const extendCommand: Command = {
|
||||
const s = state as ExtendState;
|
||||
if (s.phase === "done") return finish();
|
||||
if (input.kind !== "point") return [s, { draft: null }];
|
||||
const target = pickOpenCurveAt(ctx.project, ctx.level.id, input.point);
|
||||
if (!target) return [s, { draft: null }];
|
||||
const pick = input.point;
|
||||
return [s, { draft: null, commit: opsMutation((p) => extendOps(p, target, pick)) }];
|
||||
const { hit } = cmdQuery<{ hit: string | null }>(ctx.project, { q: "pickOpen", level: ctx.level.id, pt: pair(input.point) });
|
||||
if (!hit) return [s, { draft: null }];
|
||||
return [s, { draft: null, commit: cmdMutation({ cmd: "extend", id: hit, pt: pair(input.point) }) }];
|
||||
},
|
||||
|
||||
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as ExtendState;
|
||||
if (s.phase !== "pick") return [s, { draft: null }];
|
||||
const target = pickOpenCurveAt(ctx.project, ctx.level.id, point);
|
||||
if (!target) return [s, { draft: null }];
|
||||
const preview = extendPreview(ctx.project, target, point);
|
||||
const r = cmdQuery<{ hit: boolean; shapes: number[] }>(ctx.project, { q: "extend", level: ctx.level.id, pt: pair(point) });
|
||||
if (!r.hit) return [s, { draft: null }];
|
||||
const preview = decodeShapes(r.shapes);
|
||||
return [s, { draft: { preview, vertices: [], hud: { at: point, text: "↗" } } }];
|
||||
},
|
||||
|
||||
|
||||
+17
-129
@@ -14,11 +14,7 @@
|
||||
// Rechnung geht von geraden Schenkeln aus. Ein rect wird beim ersten Fillet zu
|
||||
// einer polyline (kein reines Rechteck mehr).
|
||||
|
||||
import type { Drawing2D, Drawing2DGeom } from "../../model/types";
|
||||
import { opsMutation, patchItem } from "../../core";
|
||||
import type { CoreOp } from "../../core";
|
||||
import { bulgeFromSagittaPoint, hasRealBulge } from "../../core";
|
||||
import { filletCorner, type Fillet } from "../../core";
|
||||
import { cmdMutation } from "../../core";
|
||||
import type {
|
||||
Command,
|
||||
CommandContext,
|
||||
@@ -26,131 +22,23 @@ import type {
|
||||
CommandResult,
|
||||
CommandState,
|
||||
DraftShape,
|
||||
Project,
|
||||
ToolDraft,
|
||||
Vec2,
|
||||
} from "../types";
|
||||
import { cornerPreview, pickCorner } from "./cornerHit";
|
||||
import type { CornerHit } from "./cornerHit";
|
||||
|
||||
const HIT_TOL = 0.3; // Modell-Meter: Pick-Toleranz für die Eckenwahl
|
||||
const DEFAULT_RADIUS = 0.1; // m — Startwert, bis der Nutzer per Maus/Tab einen eigenen setzt
|
||||
const EPS = 1e-6;
|
||||
const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
|
||||
|
||||
interface Curve {
|
||||
pts: Vec2[];
|
||||
closed: boolean;
|
||||
}
|
||||
|
||||
/** Wandelt eine fillet-fähige 2D-Form (polyline/rect) in eine Punktliste oder null. */
|
||||
function geomToCurve(g: Drawing2DGeom): Curve | null {
|
||||
// Bogen-Segmente (bulge) hier noch nicht unterstützt — der Fillet-Commit
|
||||
// baut die Polylinie komplett neu aus reinen Punkten auf und würde ein
|
||||
// bestehendes bulge-Array an anderen Segmenten sonst stillschweigend
|
||||
// verlieren, s. offset.ts.
|
||||
if (g.shape === "polyline" && !hasRealBulge(g.bulge)) return { pts: g.pts, closed: g.closed };
|
||||
if (g.shape === "rect") {
|
||||
return {
|
||||
pts: [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }],
|
||||
closed: true,
|
||||
};
|
||||
}
|
||||
return null; // line (keine eigene Ecke), circle/arc/text/Bogen-Polylinie: nicht fillet-fähig
|
||||
}
|
||||
|
||||
/** Ein Treffer: das Element + der Eckpunkt-Index (mit gültigen beiden Nachbarn). */
|
||||
interface CornerHit {
|
||||
drawing: Drawing2D;
|
||||
curve: Curve;
|
||||
index: number;
|
||||
}
|
||||
|
||||
/** Nächster Eckpunkt (mit zwei Nachbarn) einer fillet-fähigen Drawing2D zum Klickpunkt. */
|
||||
function pickCornerAt(project: Project, levelId: string, pt: Vec2): CornerHit | null {
|
||||
let best: CornerHit | null = null;
|
||||
let bestD = HIT_TOL;
|
||||
for (const d of project.drawings2d) {
|
||||
if (d.levelId !== levelId) continue;
|
||||
const curve = geomToCurve(d.geom);
|
||||
if (!curve) continue;
|
||||
const n = curve.pts.length;
|
||||
for (let i = 0; i < n; i++) {
|
||||
// Offene Polylinie: die beiden Endpunkte haben keinen zweiten Nachbarn.
|
||||
if (!curve.closed && (i === 0 || i === n - 1)) continue;
|
||||
const dd = dist(pt, curve.pts[i]);
|
||||
if (dd < bestD) {
|
||||
bestD = dd;
|
||||
best = { drawing: d, curve, index: i };
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Verrundungs-Geometrie für einen Treffer + Radius (oder null, falls unmöglich). */
|
||||
function filletFor(hit: CornerHit, r: number): Fillet | null {
|
||||
const n = hit.curve.pts.length;
|
||||
const prev = hit.curve.pts[(hit.index - 1 + n) % n];
|
||||
const next = hit.curve.pts[(hit.index + 1) % n];
|
||||
const corner = hit.curve.pts[hit.index];
|
||||
return filletCorner(corner, prev, next, r);
|
||||
}
|
||||
|
||||
/** Bogen (center/radius/start-/endAngle) als kurze Punktfolge tesselliert (kürzester Bogen). */
|
||||
function tessellateFillet(f: Fillet, segments = 12): Vec2[] {
|
||||
const TAU = Math.PI * 2;
|
||||
let delta = f.endAngle - f.startAngle;
|
||||
while (delta > Math.PI) delta -= TAU;
|
||||
while (delta < -Math.PI) delta += TAU;
|
||||
const pts: Vec2[] = [];
|
||||
for (let i = 0; i <= segments; i++) {
|
||||
const a = f.startAngle + (delta * i) / segments;
|
||||
pts.push({ x: f.center.x + f.radius * Math.cos(a), y: f.center.y + f.radius * Math.sin(a) });
|
||||
}
|
||||
return pts;
|
||||
}
|
||||
|
||||
/** Ersetzt den Eckpunkt durch die beiden Tangentenpunkte (Tangente↔Tangente). */
|
||||
function applyFilletPoints(hit: CornerHit, f: Fillet): Vec2[] {
|
||||
return [
|
||||
...hit.curve.pts.slice(0, hit.index),
|
||||
f.tangentA,
|
||||
f.tangentB,
|
||||
...hit.curve.pts.slice(hit.index + 1),
|
||||
];
|
||||
}
|
||||
|
||||
/** Bulge-Wert des Verrundungs-Bogens (tangentA→tangentB), aus einem echten Bogenpunkt hergeleitet. */
|
||||
function filletBulge(f: Fillet): number {
|
||||
const TAU = Math.PI * 2;
|
||||
let delta = f.endAngle - f.startAngle;
|
||||
while (delta > Math.PI) delta -= TAU;
|
||||
while (delta < -Math.PI) delta += TAU;
|
||||
const mid = f.startAngle + delta / 2;
|
||||
const apex: Vec2 = { x: f.center.x + f.radius * Math.cos(mid), y: f.center.y + f.radius * Math.sin(mid) };
|
||||
return bulgeFromSagittaPoint(f.tangentA, f.tangentB, apex);
|
||||
}
|
||||
|
||||
function filletDraft(hit: CornerHit, r: number, at: Vec2 | null): ToolDraft {
|
||||
const f = r > EPS ? filletFor(hit, r) : null;
|
||||
const preview: DraftShape[] = f
|
||||
? [{ kind: "poly", pts: tessellateFillet(f), closed: false }]
|
||||
: [];
|
||||
const draft: ToolDraft = { preview, vertices: [hit.curve.pts[hit.index]] };
|
||||
if (at) draft.hud = { at, text: `R: ${r.toFixed(3)}m${f ? "" : " ✗"}` };
|
||||
/** Entwurf: Vorschau (Kern) + Ecke als Marke + Messwert (✗, wenn der Radius nicht passt). */
|
||||
function filletDraft(hit: CornerHit, preview: DraftShape[], v: number, at: Vec2 | null): ToolDraft {
|
||||
const draft: ToolDraft = { preview, vertices: [hit.corner] };
|
||||
if (at) draft.hud = { at, text: `R: ${v.toFixed(3)}m${preview.length ? "" : " ✗"}` };
|
||||
return draft;
|
||||
}
|
||||
|
||||
function filletOps(p: Project, hit: CornerHit, r: number): CoreOp[] {
|
||||
const f = filletFor(hit, r);
|
||||
if (!f) return []; // Radius zu gross für die Schenkellänge, oder Ecke (fast) gerade → No-op
|
||||
const pts = applyFilletPoints(hit, f);
|
||||
const edgeCount = hit.curve.closed ? pts.length : pts.length - 1;
|
||||
const bulge = new Array(edgeCount).fill(0);
|
||||
bulge[hit.index] = filletBulge(f); // Kante tangentA→tangentB (an Position hit.index)
|
||||
const geom: Drawing2DGeom = { shape: "polyline", pts, closed: hit.curve.closed, bulge };
|
||||
return patchItem(p, "drawings2d", hit.drawing.id, { geom });
|
||||
}
|
||||
|
||||
// ── Zustand ───────────────────────────────────────────────────────────────────
|
||||
const RADIUS_FIELDS: CommandField[] = [{ id: "radius", labelKey: "cmd.field.radius" }];
|
||||
|
||||
@@ -187,33 +75,33 @@ export const filletCommand: Command = {
|
||||
if (s.phase === "done") return finish();
|
||||
if (s.phase === "pick") {
|
||||
if (input.kind !== "point") return [s, { draft: null }];
|
||||
const hit = pickCornerAt(ctx.project, ctx.level.id, input.point);
|
||||
const { hit, preview } = pickCorner(ctx.project, ctx.level.id, input.point, "fillet", DEFAULT_RADIUS);
|
||||
if (!hit) return [s, { draft: null }]; // daneben geklickt → aktiv bleiben
|
||||
const next: FilletRadius = { phase: "radius", hit, radius: DEFAULT_RADIUS, lastPoint: input.point };
|
||||
return [next, { draft: filletDraft(hit, next.radius, input.point) }];
|
||||
return [next, { draft: filletDraft(hit, preview, next.radius, input.point) }];
|
||||
}
|
||||
// phase === "radius"
|
||||
let r = s.radius;
|
||||
if (input.kind === "number") r = Math.max(0, input.value);
|
||||
else if (input.kind === "point") r = Math.max(0, dist(s.hit.curve.pts[s.hit.index], input.point));
|
||||
else if (input.kind === "point") r = Math.max(0, dist(s.hit.corner, input.point));
|
||||
else return [s, { draft: null }];
|
||||
return [
|
||||
{ phase: "done", lastPoint: null } as FilletDone,
|
||||
{ draft: null, done: true, commit: opsMutation((p) => filletOps(p, s.hit, r)) },
|
||||
{ draft: null, done: true, commit: cmdMutation({ cmd: "fillet", id: s.hit.id, index: s.hit.index, r }) },
|
||||
];
|
||||
},
|
||||
|
||||
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as FilletState;
|
||||
if (s.phase === "pick") {
|
||||
const hit = pickCornerAt(ctx.project, ctx.level.id, point);
|
||||
const { hit, preview } = pickCorner(ctx.project, ctx.level.id, point, "fillet", DEFAULT_RADIUS);
|
||||
if (!hit) return [s, { draft: null }];
|
||||
return [s, { draft: filletDraft(hit, DEFAULT_RADIUS, point) }];
|
||||
return [s, { draft: filletDraft(hit, preview, DEFAULT_RADIUS, point) }];
|
||||
}
|
||||
if (s.phase !== "radius") return [s, { draft: null }];
|
||||
const r = Math.max(0, dist(s.hit.curve.pts[s.hit.index], point));
|
||||
const r = Math.max(0, dist(s.hit.corner, point));
|
||||
const ns: FilletRadius = { ...s, radius: r };
|
||||
return [ns, { draft: filletDraft(s.hit, r, point) }];
|
||||
return [ns, { draft: filletDraft(s.hit, cornerPreview(ctx.project, s.hit, "fillet", r), r, point) }];
|
||||
},
|
||||
|
||||
onConfirm: (): [CommandState, CommandResult] => finish(),
|
||||
@@ -225,12 +113,12 @@ export const filletCommand: Command = {
|
||||
fieldValues: (state, _locks, cursor): Record<string, number> => {
|
||||
const s = state as FilletState;
|
||||
if (s.phase !== "radius" || !cursor) return {};
|
||||
return { radius: dist(s.hit.curve.pts[s.hit.index], cursor) };
|
||||
return { radius: dist(s.hit.corner, cursor) };
|
||||
},
|
||||
pointFromFields: (state, locks, cursor) => {
|
||||
const s = state as FilletState;
|
||||
if (s.phase !== "radius") return null;
|
||||
const corner = s.hit.curve.pts[s.hit.index];
|
||||
const corner = s.hit.corner;
|
||||
const r = "radius" in locks ? Math.max(0, locks.radius) : cursor ? dist(corner, cursor) : 0;
|
||||
if (cursor) {
|
||||
const d = dist(corner, cursor);
|
||||
|
||||
@@ -4,20 +4,13 @@
|
||||
// und getipptes „join" EIN Pfad (§Task C).
|
||||
//
|
||||
// Wände werden nicht verbunden (2D-Editier-Operation); nicht-polyline Formen
|
||||
// (circle/arc/text) reicht `joinDrawings` unverändert durch.
|
||||
// (circle/arc/text) bleiben unverändert und rücken hinter das Ergebnis. Rechnet der
|
||||
// Kern (`src-tauri/core/src/cmd_edit.rs::join_ops`, [K4] S3): die gewählten Quell-
|
||||
// Drawings raus, das Ergebnis hinten dran (ab zwei Elementen).
|
||||
|
||||
import { joinDrawings } from "../../editors/splitJoin";
|
||||
import type { Drawing2D } from "../../model/types";
|
||||
import { addItems, opsMutation, removeItems } from "../../core";
|
||||
import type { CoreOp } from "../../core";
|
||||
import type {
|
||||
Command,
|
||||
CommandContext,
|
||||
CommandResult,
|
||||
CommandSelection,
|
||||
CommandState,
|
||||
Project,
|
||||
} from "../types";
|
||||
import { cmdMutation } from "../../core";
|
||||
import { uniqueStamp } from "../../tools/types";
|
||||
import type { Command, CommandContext, CommandResult, CommandSelection, CommandState } from "../types";
|
||||
|
||||
/** Alle gewählten 2D-Element-IDs (Mehrfachauswahl mit Fallback aufs Einzelelement). */
|
||||
function selectedDrawingIds(sel: CommandSelection): string[] {
|
||||
@@ -25,15 +18,6 @@ function selectedDrawingIds(sel: CommandSelection): string[] {
|
||||
return sel.drawingId ? [sel.drawingId] : [];
|
||||
}
|
||||
|
||||
/** Ops: die gewählten Quell-Drawings raus, das Join-Ergebnis hinten dran. */
|
||||
function joinOps(project: Project, ids: string[]): CoreOp[] {
|
||||
const idSet = new Set(ids);
|
||||
const srcs = project.drawings2d.filter((d) => idSet.has(d.id));
|
||||
if (srcs.length < 2) return []; // <2 → nichts zu verbinden
|
||||
const joined: Drawing2D[] = joinDrawings(srcs);
|
||||
return [...removeItems(project, "drawings2d", idSet), ...addItems("drawings2d", joined)];
|
||||
}
|
||||
|
||||
interface JoinState extends CommandState {
|
||||
phase: "done";
|
||||
}
|
||||
@@ -55,7 +39,7 @@ export const joinCommand: Command = {
|
||||
autoRun: (ctx: CommandContext): CommandResult => {
|
||||
const ids = selectedDrawingIds(ctx.selection);
|
||||
if (ids.length < 2) return { draft: null, done: true };
|
||||
return { draft: null, done: true, commit: opsMutation((p) => joinOps(p, ids)) };
|
||||
return { draft: null, done: true, commit: cmdMutation({ cmd: "join", ids, stamp: uniqueStamp() }) };
|
||||
},
|
||||
|
||||
onInput: (): [CommandState, CommandResult] => done(),
|
||||
|
||||
+26
-161
@@ -13,11 +13,13 @@
|
||||
// Vorzeichen der zuletzt gewählten Seite (Default links/+), bzw. ihr eigenes
|
||||
// Vorzeichen, wenn negativ getippt.
|
||||
|
||||
import type { Drawing2D, Drawing2DGeom } from "../../model/types";
|
||||
import { bulgePolylinePoints, hasRealBulge } from "../../core";
|
||||
import { uniqueId } from "../../tools/types";
|
||||
import { leftNormal, normalize, sub } from "../../model/geometry";
|
||||
import { offsetPolyline, offsetPolylineWithBulge, offsetSegment, pointSegmentDistance, polylineEdges } from "../../core";
|
||||
//
|
||||
// Treffer, Seite, versetzte Geometrie und Vorschau rechnet der Kern (`src-tauri/core/src/cmd_edit.rs`,
|
||||
// [K4] S3, Geometrie `offsetSegment`/`offsetPolyline`/`offsetPolylineWithBulge` in `kernel2d`; Bögen
|
||||
// bleiben konzentrisch); hier der Zustandsautomat und die persistente Distanz/Seite.
|
||||
|
||||
import type { Drawing2D } from "../../model/types";
|
||||
import { uniqueStamp } from "../../tools/types";
|
||||
import type {
|
||||
CmdInput,
|
||||
Command,
|
||||
@@ -25,15 +27,13 @@ import type {
|
||||
CommandResult,
|
||||
CommandSelection,
|
||||
CommandState,
|
||||
DraftShape,
|
||||
Project,
|
||||
Vec2,
|
||||
} from "../types";
|
||||
import { addItems, opsMutation } from "../../core";
|
||||
import type { CoreOp } from "../../core";
|
||||
import { cmdMutation } from "../../core";
|
||||
import { cmdQuery, decodeShapes, pair } from "../../tools/coreCmd";
|
||||
|
||||
const EPS = 1e-6;
|
||||
const HIT_TOL = 0.25; // Modell-Meter: Pick-Toleranz für die Kurvenwahl
|
||||
|
||||
/**
|
||||
* Persistente Offset-Distanz über Aufrufe hinweg (§2.4/§3.6 — Nutzer erwarten,
|
||||
@@ -44,34 +44,6 @@ let lastDistance = 0.5;
|
||||
/** Zuletzt gewählte Seite als Vorzeichen (+1 = links, −1 = rechts). */
|
||||
let lastSign = 1;
|
||||
|
||||
// ── Kurven-Abstraktion: line/polyline/rect → Punktliste + closed ──────────────
|
||||
|
||||
interface Curve {
|
||||
pts: Vec2[];
|
||||
closed: boolean;
|
||||
/** Bogen-Segmente (DXF-bulge, s. `geometry/bulge.ts`) — nur bei polyline. */
|
||||
bulge?: number[];
|
||||
}
|
||||
|
||||
/** Wandelt eine offset-fähige 2D-Form in eine Punktliste (+closed[/bulge]) oder null. */
|
||||
function geomToCurve(g: Drawing2DGeom): Curve | null {
|
||||
if (g.shape === "line") return { pts: [g.a, g.b], closed: false };
|
||||
if (g.shape === "polyline") return { pts: g.pts, closed: g.closed, bulge: g.bulge };
|
||||
if (g.shape === "rect") {
|
||||
// Rechteck als geschlossene 4-Punkt-Polylinie offsetten (Task).
|
||||
return {
|
||||
pts: [
|
||||
g.min,
|
||||
{ x: g.max.x, y: g.min.y },
|
||||
g.max,
|
||||
{ x: g.min.x, y: g.max.y },
|
||||
],
|
||||
closed: true,
|
||||
};
|
||||
}
|
||||
return null; // circle/arc/text: hier nicht offset-fähig
|
||||
}
|
||||
|
||||
/** Ist diese Form offset-fähig (line/polyline/rect)? */
|
||||
function isOffsetable(d: Drawing2D): boolean {
|
||||
const g = d.geom;
|
||||
@@ -86,111 +58,19 @@ function singleSelectedCurve(project: Project, sel: CommandSelection): Drawing2D
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kanten für Klick-Trefftests/Vorschau: bei Bogen-Segmenten (bulge) wird die
|
||||
* Kurve zu Geradenstücken tesselliert (`bulgePolylinePoints`), damit Klick-/Seiten-
|
||||
* Tests entlang der TATSÄCHLICHEN (runden) Kontur funktionieren statt entlang
|
||||
* der geraden Sehne. Die eigentliche Offset-Geometrie bleibt exakt (bulge-
|
||||
* erhaltend, s. `offsetPolylineWithBulge`) — nur diese Hilfsfunktion approximiert.
|
||||
*/
|
||||
function curveHitEdges(curve: Curve): [Vec2, Vec2][] {
|
||||
if (!hasRealBulge(curve.bulge)) return polylineEdges(curve.pts, curve.closed);
|
||||
const chain = bulgePolylinePoints(curve.pts, curve.bulge, curve.closed);
|
||||
if (curve.closed) chain.push(curve.pts[0]); // Schlusskante mit-tesselliert, Kette endet am Start
|
||||
return polylineEdges(chain, false); // Schlusskante (falls closed) ist bereits mit-tesselliert
|
||||
/** Gibt es die Kurve noch (Side-Zustand)? */
|
||||
function hasCurve(project: Project, drawingId: string): boolean {
|
||||
const src = project.drawings2d.find((x) => x.id === drawingId);
|
||||
return !!src && isOffsetable(src);
|
||||
}
|
||||
|
||||
/** Nächstes offset-fähiges Drawing2D zum Klickpunkt (innerhalb Toleranz). */
|
||||
function pickCurveAt(project: Project, levelId: string, pt: Vec2): Drawing2D | null {
|
||||
let best: Drawing2D | null = null;
|
||||
let bestD = HIT_TOL;
|
||||
for (const d of project.drawings2d) {
|
||||
if (d.levelId !== levelId) continue;
|
||||
const curve = geomToCurve(d.geom);
|
||||
if (!curve) continue;
|
||||
for (const [a, b] of curveHitEdges(curve)) {
|
||||
const dd = pointSegmentDistance(pt, a, b);
|
||||
if (dd < bestD) {
|
||||
bestD = dd;
|
||||
best = d;
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
/** Seite (+1 links / −1 rechts) des Punkts zur Kurve und ggf. die Vorschau mit Betrag `dist` (Kern). */
|
||||
function sideOf(project: Project, drawingId: string, pt: Vec2, dist?: number): { sign: number; shapes: number[] } {
|
||||
return cmdQuery<{ sign: number; shapes: number[] }>(project, { q: "offset", id: drawingId, pt: pair(pt), lastSign, ...(dist !== undefined ? { dist } : {}) });
|
||||
}
|
||||
|
||||
/**
|
||||
* Vorzeichen (+links / −rechts) für einen Klickpunkt relativ zur Kurve: die
|
||||
* nächste Kante bestimmen, dann das Vorzeichen der Skalarprojektion von
|
||||
* (klick − Kantenmitte) auf die LINKS-Normale der Kante. So zeigt das Resultat
|
||||
* auf die angeklickte Seite (Konvention `+d = links`).
|
||||
*/
|
||||
function sideSign(curve: Curve, pt: Vec2): number {
|
||||
let bestD = Infinity;
|
||||
let sign = lastSign;
|
||||
for (const [a, b] of curveHitEdges(curve)) {
|
||||
const mid: Vec2 = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
|
||||
const dd = pointSegmentDistance(pt, a, b);
|
||||
if (dd < bestD) {
|
||||
bestD = dd;
|
||||
const u = normalize(sub(b, a));
|
||||
const n = leftNormal(u);
|
||||
const rel = sub(pt, mid);
|
||||
const s = rel.x * n.x + rel.y * n.y;
|
||||
sign = s >= 0 ? 1 : -1;
|
||||
}
|
||||
}
|
||||
return sign;
|
||||
}
|
||||
|
||||
/** Offset einer Kurve um die vorzeichenbehaftete Distanz `d` → neue Geometrie (bulge-erhaltend). */
|
||||
function offsetCurveGeom(curve: Curve, d: number): { pts: Vec2[]; bulge?: number[] } {
|
||||
if (!curve.closed && curve.pts.length === 2 && !hasRealBulge(curve.bulge)) {
|
||||
const [a, b] = offsetSegment(curve.pts[0], curve.pts[1], d);
|
||||
return { pts: [a, b] };
|
||||
}
|
||||
if (hasRealBulge(curve.bulge)) {
|
||||
return offsetPolylineWithBulge(curve.pts, curve.bulge, d, curve.closed);
|
||||
}
|
||||
return { pts: offsetPolyline(curve.pts, d, curve.closed) };
|
||||
}
|
||||
|
||||
/** Versetzte Form als neues Drawing2D (gleiche Attribute, neue ID/Geometrie). */
|
||||
function offsetGeom(src: Drawing2D, d: number): Drawing2DGeom | null {
|
||||
const curve = geomToCurve(src.geom);
|
||||
if (!curve) return null;
|
||||
const { pts, bulge } = offsetCurveGeom(curve, d);
|
||||
if (src.geom.shape === "line" && pts.length === 2) {
|
||||
return { shape: "line", a: pts[0], b: pts[1] };
|
||||
}
|
||||
const geom: Drawing2DGeom = { shape: "polyline", pts, closed: curve.closed };
|
||||
if (bulge && hasRealBulge(bulge)) geom.bulge = bulge;
|
||||
return geom;
|
||||
}
|
||||
|
||||
/** Vorschau-Formen der versetzten Kurve (für den Draft — tesselliert, s. `DraftShape`). */
|
||||
function offsetDraftShapes(curve: Curve, d: number): DraftShape[] {
|
||||
const { pts, bulge } = offsetCurveGeom(curve, d);
|
||||
if (pts.length < 2) return [];
|
||||
if (!curve.closed && pts.length === 2 && !hasRealBulge(bulge)) {
|
||||
return [{ kind: "line", a: pts[0], b: pts[1] }];
|
||||
}
|
||||
const tess = hasRealBulge(bulge)
|
||||
? curveHitEdges({ pts, closed: curve.closed, bulge }).reduce<Vec2[]>((out, [a, b], i) => {
|
||||
if (i === 0) out.push(a);
|
||||
out.push(b);
|
||||
return out;
|
||||
}, [])
|
||||
: pts;
|
||||
return [{ kind: "poly", pts: tess, closed: curve.closed }];
|
||||
}
|
||||
|
||||
function appendOffset(src: Drawing2D, d: number): CoreOp[] {
|
||||
const geom = offsetGeom(src, d);
|
||||
if (!geom) return [];
|
||||
const copy: Drawing2D = { ...src, id: uniqueId("dr2d"), geom };
|
||||
return addItems("drawings2d", [copy]);
|
||||
}
|
||||
/** Versetzte Kopie der Kurve um die vorzeichenbehaftete Distanz `d` anhängen. */
|
||||
const appendOffset = (drawingId: string, d: number) => cmdMutation({ cmd: "offset", id: drawingId, d, stamp: uniqueStamp() });
|
||||
|
||||
// ── Zustand ───────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -214,15 +94,6 @@ const finish = (): [CommandState, CommandResult] => [
|
||||
{ draft: null, done: true },
|
||||
];
|
||||
|
||||
/** Aktuelle Kurve aus dem Side-Zustand (oder null, wenn weg). */
|
||||
function curveOf(project: Project, drawingId: string): { src: Drawing2D; curve: Curve } | null {
|
||||
const src = project.drawings2d.find((x) => x.id === drawingId);
|
||||
if (!src) return null;
|
||||
const curve = geomToCurve(src.geom);
|
||||
if (!curve) return null;
|
||||
return { src, curve };
|
||||
}
|
||||
|
||||
export const offsetCommand: Command = {
|
||||
name: "offset",
|
||||
labelKey: "cmd.offset.label",
|
||||
@@ -260,9 +131,9 @@ export const offsetCommand: Command = {
|
||||
}
|
||||
// Keine Vorselektion → Kurve per Klick wählen.
|
||||
if (input.kind === "point") {
|
||||
const hit = pickCurveAt(ctx.project, ctx.level.id, input.point);
|
||||
const hit = cmdQuery<{ hit: string | null }>(ctx.project, { q: "pickCurve", level: ctx.level.id, pt: pair(input.point) }).hit;
|
||||
if (!hit) return [s, { draft: null }];
|
||||
const ns: OffSide = { phase: "side", drawingId: hit.id, cursor: null, lastPoint: null };
|
||||
const ns: OffSide = { phase: "side", drawingId: hit, cursor: null, lastPoint: null };
|
||||
return [ns, { draft: null }];
|
||||
}
|
||||
return [s, { draft: null }];
|
||||
@@ -302,9 +173,7 @@ function offsetSideInput(
|
||||
input: CmdInput,
|
||||
ctx: CommandContext,
|
||||
): [CommandState, CommandResult] {
|
||||
const cc = curveOf(ctx.project, s.drawingId);
|
||||
if (!cc) return finish();
|
||||
const { src, curve } = cc;
|
||||
if (!hasCurve(ctx.project, s.drawingId)) return finish();
|
||||
|
||||
if (input.kind === "number") {
|
||||
// Getippte Distanz: Betrag merken; Vorzeichen aus der zuletzt gewählten
|
||||
@@ -318,18 +187,18 @@ function offsetSideInput(
|
||||
const d = sign * mag;
|
||||
return [
|
||||
{ phase: "done", lastPoint: null } as OffDone,
|
||||
{ draft: null, done: true, commit: opsMutation(() => appendOffset(src, d)) },
|
||||
{ draft: null, done: true, commit: appendOffset(s.drawingId, d) },
|
||||
];
|
||||
}
|
||||
|
||||
if (input.kind === "point") {
|
||||
// Seite per Klick: Vorzeichen aus der Klickseite, Betrag = letzte Distanz.
|
||||
const sign = sideSign(curve, input.point);
|
||||
const sign = sideOf(ctx.project, s.drawingId, input.point).sign;
|
||||
lastSign = sign;
|
||||
const d = sign * lastDistance;
|
||||
return [
|
||||
{ phase: "done", lastPoint: null } as OffDone,
|
||||
{ draft: null, done: true, commit: opsMutation(() => appendOffset(src, d)) },
|
||||
{ draft: null, done: true, commit: appendOffset(s.drawingId, d) },
|
||||
];
|
||||
}
|
||||
|
||||
@@ -342,12 +211,8 @@ function offsetSideMove(
|
||||
point: Vec2,
|
||||
ctx: CommandContext,
|
||||
): [CommandState, CommandResult] {
|
||||
const cc = curveOf(ctx.project, s.drawingId);
|
||||
if (!cc) return [s, { draft: null }];
|
||||
const { curve } = cc;
|
||||
const sign = sideSign(curve, point);
|
||||
const d = sign * lastDistance;
|
||||
const preview = offsetDraftShapes(curve, d);
|
||||
if (!hasCurve(ctx.project, s.drawingId)) return [s, { draft: null }];
|
||||
const preview = decodeShapes(sideOf(ctx.project, s.drawingId, point, lastDistance).shapes);
|
||||
const ns: OffSide = { ...s, cursor: point };
|
||||
return [
|
||||
ns,
|
||||
|
||||
+14
-219
@@ -10,218 +10,17 @@
|
||||
// • Wiederholend, bis Esc/Enter.
|
||||
//
|
||||
// Linie → wird gekürzt/aufgeteilt; Polylinie → der getroffene Abschnitt fällt
|
||||
// raus (kann die Polylinie in Stücke teilen). Reine Geometrie liegt im Kernel
|
||||
// (`trimPolylineWithBulge`, auch für reine Geraden-Ziele — s. Kopfkommentar
|
||||
// bei `trimCurve`); hier nur Treffer-Bestimmung, Drawing2D ↔ {pts,closed,
|
||||
// bulge} und der Commit. Wände sind ausgenommen (nur Drawing2D). Sowohl
|
||||
// Ziel-Kurve als auch Schneider dürfen Bogen-Segmente (bulge) tragen.
|
||||
// raus (kann die Polylinie in Stücke teilen). Treffer, Schneider, Rest-Ketten und
|
||||
// Vorschau rechnet der Kern (`src-tauri/core/src/cmd_edit.rs`, [K4] S3); hier nur
|
||||
// der Zustandsautomat. Wände sind ausgenommen (nur Drawing2D). Sowohl Ziel-Kurve
|
||||
// als auch Schneider dürfen Bogen-Segmente (bulge) tragen.
|
||||
//
|
||||
// Bezeichner englisch, Kommentare/UI deutsch (CONVENTIONS.md).
|
||||
|
||||
import type { Drawing2D, Drawing2DGeom } from "../../model/types";
|
||||
import { bulgePolylinePoints, hasRealBulge } from "../../core";
|
||||
import { uniqueId } from "../../tools/types";
|
||||
import { addItems, opsMutation, removeItems } from "../../core";
|
||||
import type { CoreOp } from "../../core";
|
||||
import { pointSegmentDistance, polylineEdges, trimPolylineWithBulge, vecEqual } from "../../core";
|
||||
import type {
|
||||
Command,
|
||||
CommandResult,
|
||||
CommandState,
|
||||
DraftShape,
|
||||
Project,
|
||||
Vec2,
|
||||
} from "../types";
|
||||
|
||||
export const HIT_TOL = 0.25; // Modell-Meter: Pick-Toleranz für die Kurvenwahl
|
||||
|
||||
// ── Kurven-Abstraktion: line/polyline/rect → Punktliste + closed ──────────────
|
||||
|
||||
export interface Curve {
|
||||
pts: Vec2[];
|
||||
closed: boolean;
|
||||
/** Bogen-Segmente (DXF-bulge, s. `geometry/bulge.ts`) — nur bei polyline. */
|
||||
bulge?: number[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Wandelt eine trim-fähige 2D-Form in eine Punktliste (+closed[/bulge]) oder
|
||||
* null. Exportiert — `break.ts` (BREAK-Befehl) nutzt dieselbe Kurven-
|
||||
* Abstraktion + Hit-Test wie trim/extend, statt sie zu duplizieren.
|
||||
*/
|
||||
export function geomToCurve(g: Drawing2DGeom): Curve | null {
|
||||
if (g.shape === "line") return { pts: [g.a, g.b], closed: false };
|
||||
if (g.shape === "polyline") return { pts: g.pts, closed: g.closed, bulge: g.bulge };
|
||||
if (g.shape === "rect") {
|
||||
return {
|
||||
pts: [
|
||||
g.min,
|
||||
{ x: g.max.x, y: g.min.y },
|
||||
g.max,
|
||||
{ x: g.min.x, y: g.max.y },
|
||||
],
|
||||
closed: true,
|
||||
};
|
||||
}
|
||||
return null; // circle/arc/text: hier nicht trim-fähig
|
||||
}
|
||||
|
||||
/** Ist diese Form trim-fähig (line/polyline/rect)? Exportiert, s. `geomToCurve`. */
|
||||
export function isTrimmable(d: Drawing2D): boolean {
|
||||
const g = d.geom;
|
||||
return g.shape === "line" || g.shape === "polyline" || g.shape === "rect";
|
||||
}
|
||||
|
||||
/**
|
||||
* Kanten für Klick-Trefftests: bei Bogen-Segmenten (bulge) wird die Kurve zu
|
||||
* Geradenstücken tesselliert, damit der Trefftest entlang der TATSÄCHLICHEN
|
||||
* (runden) Kontur funktioniert statt entlang der geraden Sehne — s. gleiches
|
||||
* Vorgehen in offset.ts (`curveHitEdges`).
|
||||
*/
|
||||
export function curveHitEdges(curve: Curve): [Vec2, Vec2][] {
|
||||
if (!hasRealBulge(curve.bulge)) return polylineEdges(curve.pts, curve.closed);
|
||||
const chain = bulgePolylinePoints(curve.pts, curve.bulge, curve.closed);
|
||||
if (curve.closed) chain.push(curve.pts[0]); // Schlusskante mit-tesselliert, Kette endet am Start
|
||||
return polylineEdges(chain, false);
|
||||
}
|
||||
|
||||
/** Nächstes trim-fähiges Drawing2D der Ebene zum Klickpunkt (innerhalb Toleranz). */
|
||||
export function pickCurveAt(
|
||||
project: Project,
|
||||
levelId: string,
|
||||
pt: Vec2,
|
||||
tol = HIT_TOL,
|
||||
): Drawing2D | null {
|
||||
let best: Drawing2D | null = null;
|
||||
let bestD = tol;
|
||||
for (const d of project.drawings2d) {
|
||||
if (d.levelId !== levelId) continue;
|
||||
if (!isTrimmable(d)) continue;
|
||||
const curve = geomToCurve(d.geom);
|
||||
if (!curve) continue;
|
||||
for (const [a, b] of curveHitEdges(curve)) {
|
||||
const dd = pointSegmentDistance(pt, a, b);
|
||||
if (dd < bestD) {
|
||||
bestD = dd;
|
||||
best = d;
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle anderen trim-fähigen Drawing2D der Ebene als Cutter-Kurven — Bogen-
|
||||
* Segmente (bulge) sind als Schneider zugelassen (`trimPolylineWithBulge`
|
||||
* schneidet Kreis↔Gerade UND Kreis↔Kreis, s. `edgeIntersectTs`).
|
||||
*/
|
||||
function cuttersFor(
|
||||
project: Project,
|
||||
levelId: string,
|
||||
exceptId: string,
|
||||
): Curve[] {
|
||||
const out: Curve[] = [];
|
||||
for (const d of project.drawings2d) {
|
||||
if (d.id === exceptId) continue;
|
||||
if (d.levelId !== levelId) continue;
|
||||
const curve = geomToCurve(d.geom);
|
||||
if (curve) out.push(curve);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Sind zwei Ketten geometrisch identisch (gleiches closed + gleiche Punkte)? */
|
||||
function sameChain(a: { pts: Vec2[]; closed: boolean }, b: Curve): boolean {
|
||||
if (a.closed !== b.closed || a.pts.length !== b.pts.length) return false;
|
||||
for (let i = 0; i < a.pts.length; i++) {
|
||||
if (!vecEqual(a.pts[i], b.pts[i])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Eine getrimmte Rest-Kette als passende Drawing2D-Geometrie. Exportiert, s. `geomToCurve`. */
|
||||
export function chainToGeom(chain: { pts: Vec2[]; closed: boolean; bulge?: number[] }): Drawing2DGeom {
|
||||
if (chain.pts.length === 2 && !chain.closed && !hasRealBulge(chain.bulge)) {
|
||||
return { shape: "line", a: chain.pts[0], b: chain.pts[1] };
|
||||
}
|
||||
const geom: Drawing2DGeom = { shape: "polyline", pts: chain.pts, closed: chain.closed };
|
||||
if (hasRealBulge(chain.bulge)) geom.bulge = chain.bulge;
|
||||
return geom;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wendet einen Trim auf das Projekt an: ersetzt das getroffene Element durch
|
||||
* seine Rest-Ketten (Attribute geerbt). Bleibt nichts übrig, fällt es weg.
|
||||
*/
|
||||
/**
|
||||
* Trimmt eine Kurve gegen ihre Schneider (bulge-erhaltend). Läuft IMMER über
|
||||
* `trimPolylineWithBulge` — sie ist eine echte Obermenge von `trimPolyline`
|
||||
* (Gerade-only ist der Sonderfall bulge=undefined) und wird jetzt auch für
|
||||
* reine Geraden-Ziele gebraucht, sobald ein Bogen-CUTTER im Spiel ist.
|
||||
*/
|
||||
function trimCurve(
|
||||
curve: Curve,
|
||||
cutters: { pts: Vec2[]; closed: boolean; bulge?: number[] }[],
|
||||
pick: Vec2,
|
||||
): { pts: Vec2[]; closed: boolean; bulge?: number[] }[] {
|
||||
return trimPolylineWithBulge(curve.pts, curve.bulge, curve.closed, cutters, pick);
|
||||
}
|
||||
|
||||
function trimOps(
|
||||
p: Project,
|
||||
target: Drawing2D,
|
||||
pick: Vec2,
|
||||
): CoreOp[] {
|
||||
const curve = geomToCurve(target.geom);
|
||||
if (!curve) return [];
|
||||
const cutters = cuttersFor(p, target.levelId, target.id).map((c) => ({
|
||||
pts: c.pts,
|
||||
closed: c.closed,
|
||||
bulge: c.bulge,
|
||||
}));
|
||||
const rest = trimCurve(curve, cutters, pick);
|
||||
// Echtes No-op: genau eine Kette, identisch (gleiche Punkte) zur Quelle →
|
||||
// nichts wurde weggeschnitten (kein Schnitt mit Cuttern).
|
||||
if (rest.length === 1 && sameChain(rest[0], curve)) return [];
|
||||
const replacements: Drawing2D[] = rest
|
||||
.filter((c) => c.pts.length >= 2)
|
||||
.map((c) => ({ ...target, id: uniqueId("dr2d"), geom: chainToGeom(c) }));
|
||||
// Ziel raus, Reste hinten dran (wie bisher: `[...others, ...replacements]`).
|
||||
return [...removeItems(p, "drawings2d", [target.id]), ...addItems("drawings2d", replacements)];
|
||||
}
|
||||
|
||||
/** Vorschau-Formen der NACH dem Trim verbleibenden Ketten (für den Draft — tesselliert, s. `DraftShape`). */
|
||||
function trimPreview(
|
||||
project: Project,
|
||||
target: Drawing2D,
|
||||
pick: Vec2,
|
||||
): DraftShape[] {
|
||||
const curve = geomToCurve(target.geom);
|
||||
if (!curve) return [];
|
||||
const cutters = cuttersFor(project, target.levelId, target.id).map((c) => ({
|
||||
pts: c.pts,
|
||||
closed: c.closed,
|
||||
bulge: c.bulge,
|
||||
}));
|
||||
const rest = trimCurve(curve, cutters, pick);
|
||||
const out: DraftShape[] = [];
|
||||
for (const c of rest) {
|
||||
if (c.pts.length < 2) continue;
|
||||
const pts = hasRealBulge(c.bulge)
|
||||
? curveHitEdges({ pts: c.pts, closed: c.closed, bulge: c.bulge }).reduce<Vec2[]>((acc, [a, b], i) => {
|
||||
if (i === 0) acc.push(a);
|
||||
acc.push(b);
|
||||
return acc;
|
||||
}, [])
|
||||
: c.pts;
|
||||
if (pts.length === 2 && !c.closed) {
|
||||
out.push({ kind: "line", a: pts[0], b: pts[1] });
|
||||
} else {
|
||||
out.push({ kind: "poly", pts, closed: c.closed });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
import { cmdMutation } from "../../core";
|
||||
import { uniqueStamp } from "../../tools/types";
|
||||
import { cmdQuery, decodeShapes, pair } from "../../tools/coreCmd";
|
||||
import type { Command, CommandResult, CommandState } from "../types";
|
||||
|
||||
// ── Zustand ───────────────────────────────────────────────────────────────────
|
||||
// Einziger Schritt „pick": auf den wegzuschneidenden Abschnitt klicken;
|
||||
@@ -252,25 +51,21 @@ export const trimCommand: Command = {
|
||||
const s = state as TrimState;
|
||||
if (s.phase === "done") return finish();
|
||||
if (input.kind !== "point") return [s, { draft: null }];
|
||||
const target = pickCurveAt(ctx.project, ctx.level.id, input.point);
|
||||
if (!target) {
|
||||
const { hit } = cmdQuery<{ hit: string | null }>(ctx.project, { q: "pickCurve", level: ctx.level.id, pt: pair(input.point) });
|
||||
if (!hit) {
|
||||
// Daneben geklickt → Befehl bleibt aktiv (weiter trimmen).
|
||||
return [s, { draft: null }];
|
||||
}
|
||||
const pick = input.point;
|
||||
// Wiederholend: NICHT done — nach dem Commit bleibt „pick" aktiv.
|
||||
return [
|
||||
s,
|
||||
{ draft: null, commit: opsMutation((p) => trimOps(p, target, pick)) },
|
||||
];
|
||||
return [s, { draft: null, commit: cmdMutation({ cmd: "trim", id: hit, pt: pair(input.point), stamp: uniqueStamp() }) }];
|
||||
},
|
||||
|
||||
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
|
||||
const s = state as TrimState;
|
||||
if (s.phase !== "pick") return [s, { draft: null }];
|
||||
const target = pickCurveAt(ctx.project, ctx.level.id, point);
|
||||
if (!target) return [s, { draft: null }];
|
||||
const preview = trimPreview(ctx.project, target, point);
|
||||
const r = cmdQuery<{ hit: boolean; shapes: number[] }>(ctx.project, { q: "trim", level: ctx.level.id, pt: pair(point) });
|
||||
if (!r.hit) return [s, { draft: null }];
|
||||
const preview = decodeShapes(r.shapes);
|
||||
return [
|
||||
s,
|
||||
{
|
||||
|
||||
@@ -10,6 +10,8 @@ import { applyOps, opsToJson } from "./ops";
|
||||
import { fromMarkedJson, toMarkedJson } from "./ops";
|
||||
import type { CoreOp } from "./ops";
|
||||
import { fieldOps } from "./opsBuild";
|
||||
import { opsMutation } from "./opsBuild";
|
||||
import type { ProjectMutation } from "./opsBuild";
|
||||
|
||||
/** Ergebnis des Ladens einer Projektdatei ({@link ProjectDocument.loadFile}). */
|
||||
export type LoadFileResult =
|
||||
@@ -277,6 +279,48 @@ export class ProjectDocument {
|
||||
return fromMarkedJson(out);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ops eines Befehls ([K4] S3, `commands.rs`): `req` = `{cmd, …}` (Zahlen dürfen NaN/±∞ sein), gerechnet
|
||||
* auf dem Stand des Dokuments (ohne Anwenden). Nicht endliche Ergebnisse kommen als Zahlen zurück.
|
||||
*/
|
||||
cmdOps(req: object): CoreOp[] {
|
||||
if (!this.handle) throw new Error("Kern-Abfrage „cmdOps“: Dokument nicht offen");
|
||||
const out = core().doc_query_root(this.handle, "cmdOps", toMarkedJson(req));
|
||||
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
|
||||
return fromMarkedJson<{ ops: CoreOp[] }>(out).ops;
|
||||
}
|
||||
|
||||
/**
|
||||
* Befehl rechnen und anwenden ([K4] S3, `doc_cmd_commit`): wie {@link commitGrip} — ein Kern-Aufruf
|
||||
* statt Ops hin (Rechnung) und zurück (Commit). Ergebnis: neues Projekt und die angewendeten Ops (leer
|
||||
* = nichts zu tun, dann `project === base`) oder die Meldungen der Prüfung.
|
||||
*/
|
||||
commitCmd(base: Project, req: object, coalesceKey: string | undefined, now: number): { project: Project; ops: CoreOp[] } | { problems: string[] } {
|
||||
this.ensure(base);
|
||||
if (!this.handle) return { problems: ["Projekt-Dokument im Kern nicht offen."] };
|
||||
const out = core().doc_cmd_commit(this.handle, toMarkedJson(req), coalesceKey ?? "", now);
|
||||
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
|
||||
const r = fromMarkedJson<{ ops: CoreOp[] } | { problems: string[] }>(out);
|
||||
if ("problems" in r) return r;
|
||||
if (r.ops.length === 0) return { project: base, ops: r.ops };
|
||||
const project = applyOps(base, r.ops);
|
||||
this.mirror = project;
|
||||
return { project, ops: r.ops };
|
||||
}
|
||||
|
||||
/** Abfrage eines Befehls zwischen den Schritten (`doc_cmd_query`: Treffer, Vorschau-Formen), JSON-Antwort. */
|
||||
cmdQuery<T>(req: object): T {
|
||||
if (!this.handle) throw new Error("Kern-Abfrage „cmdQuery“: Dokument nicht offen");
|
||||
const out = core().doc_cmd_query(this.handle, toMarkedJson(req));
|
||||
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
|
||||
return fromMarkedJson<T>(out);
|
||||
}
|
||||
|
||||
/** Vorschau-Formen eines Befehls (`doc_cmd_preview`): flach je Form `[art, n, x0, y0, …]`. */
|
||||
cmdPreview(req: object): Float64Array {
|
||||
return this.handle ? core().doc_cmd_preview(this.handle, toMarkedJson(req)) : new Float64Array(0);
|
||||
}
|
||||
|
||||
/** Einen Schritt zurück auf `base` (= aktuelles Projekt); `null` = nichts rückgängig zu machen. */
|
||||
undo(base: Project): Project | null {
|
||||
return this.jump(base, "doc_undo");
|
||||
@@ -372,3 +416,11 @@ export function documentFor(project: Project): ProjectDocument {
|
||||
else shared.sync(project);
|
||||
return shared;
|
||||
}
|
||||
|
||||
/**
|
||||
* Änderung als Befehls-Anfrage an den Kern ([K4] S3, `commands.rs`): `toOps` rechnet die Ops auf dem
|
||||
* Dokument des Projekts; der Store wendet `coreReq` direkt im Kern an (`ProjectDocument.commitCmd`).
|
||||
*/
|
||||
export function cmdMutation(req: object): ProjectMutation {
|
||||
return Object.assign(opsMutation((p) => documentFor(p).cmdOps(req)), { coreReq: req });
|
||||
}
|
||||
@@ -50,6 +50,7 @@ export type { PdfVectorPage, PdfVectorPath, PdfVectorText } from "../io/pdfVecto
|
||||
export { readMesh, meshObjectsToImportedMeshes, formatMeshReport, isMeshFile, MESH_UNITS, MESH_UNIT_SCALE } from "../io/meshImport";
|
||||
export type { MeshObject, MeshImportReport, MeshUnit, MeshUp, MeshPlacement } from "../io/meshImport";
|
||||
export { addItems, fieldOps, findItem, itemsOf, opsMutation, patchItem, patchItems, removeItems, replaceItem, replaceWithMany, setField, setFieldIfChanged } from "./opsBuild";
|
||||
export { cmdMutation } from "./document";
|
||||
export type { EntityCollection, EntityOf, ProjectMutation } from "./opsBuild";
|
||||
export { EMPTY_MEMBERSHIP, containingGroupId, expandToGroups, isInsideActiveGroup, transitiveMembership } from "../model/groups";
|
||||
export type { GroupMembership, MemberKind } from "../model/groups";
|
||||
|
||||
@@ -53,25 +53,9 @@ export {
|
||||
} from "../geometry/snapSegments";
|
||||
|
||||
export {
|
||||
mvGeom,
|
||||
reversesOrientation,
|
||||
scaleFactor,
|
||||
scaleGeom,
|
||||
} from "../geometry/geomTransform";
|
||||
|
||||
export {
|
||||
type Chamfer,
|
||||
type Fillet,
|
||||
type TangentTarget,
|
||||
breakCurve,
|
||||
chamferCorner,
|
||||
extendBulgeSegment,
|
||||
extendSegment,
|
||||
filletCorner,
|
||||
joinChainsWithBulge,
|
||||
nearestOnPolyline,
|
||||
offsetPolyline,
|
||||
offsetPolylineWithBulge,
|
||||
offsetSegment,
|
||||
pointSegmentDistance,
|
||||
polylineEdges,
|
||||
@@ -81,7 +65,6 @@ export {
|
||||
splitClosedByChord,
|
||||
splitPolylineAtParam,
|
||||
tangentCircleCenters,
|
||||
trimPolylineWithBulge,
|
||||
vecEqual,
|
||||
} from "../geometry/kernel2d";
|
||||
|
||||
@@ -157,7 +140,6 @@ export {
|
||||
|
||||
export {
|
||||
extrudedSolidSpec,
|
||||
transformSolid,
|
||||
} from "../plan/extrudedSolidSpec";
|
||||
|
||||
export {
|
||||
|
||||
@@ -169,7 +169,11 @@ function idTest<E>(ids: ReadonlySet<string> | readonly string[] | ((e: E) => boo
|
||||
// ── Projekt → Projekt mit mitgeführten Ops ─────────────────────────────────
|
||||
|
||||
/** Projekt → Projekt-Funktion, die ihre Ops mitträgt (s. {@link opsMutation}). */
|
||||
export type ProjectMutation = ((p: Project) => Project) & { readonly toOps: (p: Project) => CoreOp[] };
|
||||
export type ProjectMutation = ((p: Project) => Project) & {
|
||||
readonly toOps: (p: Project) => CoreOp[];
|
||||
/** Befehls-Anfrage an den Kern (`cmdMutation`): der Store rechnet und wendet sie in einem Kern-Aufruf an. */
|
||||
readonly coreReq?: object;
|
||||
};
|
||||
|
||||
/**
|
||||
* Verpackt einen Op-Bauer als Projekt → Projekt-Funktion (für Schnittstellen wie
|
||||
|
||||
+6
-88
@@ -1,14 +1,13 @@
|
||||
// Ausrichten und Verteilen der 2D-Auswahl — reine Modell-Funktionen (wie
|
||||
// `editors/explode.ts`), damit sie ohne UI testbar bleiben.
|
||||
// Ausrichten und Verteilen der 2D-Auswahl — Fassade über den Kern ([K4] S3,
|
||||
// `src-tauri/core/src/cmd_transform.rs::align_ops`/`distribute_ops`).
|
||||
//
|
||||
// Beides arbeitet auf den BOUNDING-BOXEN der Elemente (dieselbe Herleitung wie
|
||||
// im Attribut-Panel: Kern `selection_info.rs::geom_bbox`, Abfrage `drawingBBoxes`) und verschiebt sie anschliessend als
|
||||
// im Attribut-Panel: Kern `selection_info.rs::geom_bbox`) und verschiebt sie anschliessend als
|
||||
// Ganzes. Die Form selbst bleibt unangetastet — es wird nur verschoben, nie
|
||||
// skaliert oder verzerrt.
|
||||
|
||||
import type { Drawing2D, Project, Vec2 } from "../model/types";
|
||||
import type { Project } from "../model/types";
|
||||
import { documentFor } from "../core/document";
|
||||
import { mvGeom, patchItems } from "../core";
|
||||
import type { CoreOp } from "../core";
|
||||
|
||||
/** Ausrichtungskante bzw. -achse. */
|
||||
@@ -17,34 +16,6 @@ export type AlignMode = "left" | "right" | "centerX" | "top" | "bottom" | "cente
|
||||
/** Verteilungsachse: gleiche Abstände der Mittelpunkte entlang X bzw. Y. */
|
||||
export type DistributeAxis = "x" | "y";
|
||||
|
||||
interface Boxed {
|
||||
d: Drawing2D;
|
||||
minX: number;
|
||||
minY: number;
|
||||
maxX: number;
|
||||
maxY: number;
|
||||
}
|
||||
|
||||
function boxesOf(project: Project, ids: string[]): Boxed[] {
|
||||
const wanted = new Set(ids);
|
||||
const list = project.drawings2d.filter((d) => wanted.has(d.id));
|
||||
if (list.length === 0) return [];
|
||||
// Je Element `[id, minX, minY, maxX, maxY]`, in Listen-Reihenfolge wie `list`.
|
||||
const b = documentFor(project).queryRootMarked<[string, number, number, number, number][]>("drawingBBoxes", JSON.stringify(ids));
|
||||
return list.map((d, i) => ({ d, minX: b[i][1], minY: b[i][2], maxX: b[i][3], maxY: b[i][4] }));
|
||||
}
|
||||
|
||||
/** Ops: verschiebt die genannten Elemente um je einen eigenen Vektor. */
|
||||
function moveBy(project: Project, deltas: Map<string, Vec2>): CoreOp[] {
|
||||
if (deltas.size === 0) return [];
|
||||
return patchItems(project, "drawings2d", (d) => deltas.has(d.id), (d) => {
|
||||
const delta = deltas.get(d.id)!;
|
||||
if (delta.x === 0 && delta.y === 0) return d;
|
||||
const fn = (p: Vec2): Vec2 => ({ x: p.x + delta.x, y: p.y + delta.y });
|
||||
return { ...d, geom: mvGeom(d.geom, fn) };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Richtet die Elemente an der gemeinsamen Kante bzw. Mittelachse aus. Bezug
|
||||
* ist die Hülle ALLER gewählten Elemente (wie in Grafikprogrammen üblich):
|
||||
@@ -54,43 +25,7 @@ function moveBy(project: Project, deltas: Map<string, Vec2>): CoreOp[] {
|
||||
* ausrichten könnte) — das Projekt bleibt unverändert.
|
||||
*/
|
||||
export function alignOps(project: Project, ids: string[], mode: AlignMode): CoreOp[] {
|
||||
const boxes = boxesOf(project, ids);
|
||||
if (boxes.length < 2) return [];
|
||||
|
||||
const minX = Math.min(...boxes.map((b) => b.minX));
|
||||
const maxX = Math.max(...boxes.map((b) => b.maxX));
|
||||
const minY = Math.min(...boxes.map((b) => b.minY));
|
||||
const maxY = Math.max(...boxes.map((b) => b.maxY));
|
||||
const cx = (minX + maxX) / 2;
|
||||
const cy = (minY + maxY) / 2;
|
||||
|
||||
const deltas = new Map<string, Vec2>();
|
||||
for (const b of boxes) {
|
||||
let dx = 0;
|
||||
let dy = 0;
|
||||
switch (mode) {
|
||||
case "left":
|
||||
dx = minX - b.minX;
|
||||
break;
|
||||
case "right":
|
||||
dx = maxX - b.maxX;
|
||||
break;
|
||||
case "centerX":
|
||||
dx = cx - (b.minX + b.maxX) / 2;
|
||||
break;
|
||||
case "top":
|
||||
dy = maxY - b.maxY;
|
||||
break;
|
||||
case "bottom":
|
||||
dy = minY - b.minY;
|
||||
break;
|
||||
case "centerY":
|
||||
dy = cy - (b.minY + b.maxY) / 2;
|
||||
break;
|
||||
}
|
||||
deltas.set(b.d.id, { x: dx, y: dy });
|
||||
}
|
||||
return moveBy(project, deltas);
|
||||
return documentFor(project).cmdOps({ cmd: "align", ids, mode });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -102,22 +37,5 @@ export function alignOps(project: Project, ids: string[], mode: AlignMode): Core
|
||||
* ohnehin stehen) — das Projekt bleibt unverändert.
|
||||
*/
|
||||
export function distributeOps(project: Project, ids: string[], axis: DistributeAxis): CoreOp[] {
|
||||
const boxes = boxesOf(project, ids);
|
||||
if (boxes.length < 3) return [];
|
||||
|
||||
const center = (b: Boxed) => (axis === "x" ? (b.minX + b.maxX) / 2 : (b.minY + b.maxY) / 2);
|
||||
const sorted = [...boxes].sort((a, b) => center(a) - center(b));
|
||||
const first = center(sorted[0]);
|
||||
const last = center(sorted[sorted.length - 1]);
|
||||
const step = (last - first) / (sorted.length - 1);
|
||||
|
||||
const deltas = new Map<string, Vec2>();
|
||||
sorted.forEach((b, i) => {
|
||||
// Erstes und letztes Element bleiben unangetastet (sie definieren den Bereich).
|
||||
if (i === 0 || i === sorted.length - 1) return;
|
||||
const target = first + step * i;
|
||||
const shift = target - center(b);
|
||||
deltas.set(b.d.id, axis === "x" ? { x: shift, y: 0 } : { x: 0, y: shift });
|
||||
});
|
||||
return moveBy(project, deltas);
|
||||
return documentFor(project).cmdOps({ cmd: "distribute", ids, axis });
|
||||
}
|
||||
@@ -5,10 +5,17 @@
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { explodeGeom, explodeOps } from "./explode";
|
||||
import { explodeOps } from "./explode";
|
||||
import { applyOps } from "../core/ops";
|
||||
|
||||
const explodeDrawings = (p: Project, ids: string[]) => applyOps(p, explodeOps(p, ids));
|
||||
|
||||
/** Teilgeometrien einer Form über die Ops (Kern): `null`, wenn sie nicht zerlegt wird. */
|
||||
function explodeGeom(geom: Drawing2DGeom, project: Project): Drawing2DGeom[] | null {
|
||||
const p = { ...project, drawings2d: [{ id: "d1", type: "drawing2d", levelId: "L", categoryCode: "0", geom }] } as Project;
|
||||
const ops = explodeOps(p, ["d1"]);
|
||||
return ops.length ? applyOps(p, ops).drawings2d.map((d) => d.geom) : null;
|
||||
}
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { bulgeArc } from "../geometry/bulge";
|
||||
import type { Drawing2D, Drawing2DGeom, Project } from "../model/types";
|
||||
|
||||
+8
-115
@@ -1,11 +1,9 @@
|
||||
// Auflösen (Explode) — zerlegt zusammengesetzte 2D-Elemente in ihre Einzelteile.
|
||||
// Reine Modell-Funktion, damit sie ohne Befehl/UI testbar bleibt (wie
|
||||
// `editors/splitJoin.ts`).
|
||||
// Auflösen (Explode) — zerlegt zusammengesetzte 2D-Elemente in ihre Einzelteile. Rechnet der Kern
|
||||
// ([K4] S3, `src-tauri/core/src/cmd_edit.rs::explode_ops`); hier die Fassade.
|
||||
//
|
||||
// Was zerlegt wird:
|
||||
// • Block-Instanz → die Teilgeometrien der Definition, mit Drehung und
|
||||
// Einfügepunkt der Instanz verrechnet (dieselbe Transformation, mit der
|
||||
// der Kern (`plan/drawings.rs`) sie zeichnet).
|
||||
// Einfügepunkt der Instanz verrechnet.
|
||||
// • Polylinie → ein Element je Segment: Gerade zu `line`, ein Bogen-Segment
|
||||
// (`bulge`) zu einem ECHTEN `arc` — der Bogen darf beim Auflösen nicht zur
|
||||
// Sehne zusammenfallen.
|
||||
@@ -15,122 +13,17 @@
|
||||
// Kreis, Ellipse, Spline, Bezier, Text, Bemassung, Bild — sie bleiben
|
||||
// unverändert stehen. Ebenso alles, was kein 2D-Element ist.
|
||||
|
||||
import type { Drawing2D, Drawing2DGeom, Project, Vec2 } from "../model/types";
|
||||
import { bulgeArc, replaceWithMany } from "../core";
|
||||
import type { Project } from "../model/types";
|
||||
import type { CoreOp } from "../core";
|
||||
import { uniqueId } from "../tools/types";
|
||||
|
||||
/** Teilgeometrien EINES Elements, oder `null`, wenn es nicht zerlegbar ist. */
|
||||
export function explodeGeom(geom: Drawing2DGeom, project: Project): Drawing2DGeom[] | null {
|
||||
switch (geom.shape) {
|
||||
case "block": {
|
||||
const def = project.blockDefs?.find((b) => b.id === geom.blockDefId);
|
||||
if (!def || def.geom2d.length === 0) return null;
|
||||
const c = Math.cos(geom.rotation);
|
||||
const s = Math.sin(geom.rotation);
|
||||
const xf = (p: Vec2): Vec2 => ({
|
||||
x: geom.at.x + p.x * c - p.y * s,
|
||||
y: geom.at.y + p.x * s + p.y * c,
|
||||
});
|
||||
return def.geom2d.map((sub) => mapPoints(sub, xf));
|
||||
}
|
||||
|
||||
case "polyline": {
|
||||
const n = geom.pts.length;
|
||||
if (n < 2) return null;
|
||||
const segCount = geom.closed && n > 2 ? n : n - 1;
|
||||
const out: Drawing2DGeom[] = [];
|
||||
for (let i = 0; i < segCount; i++) {
|
||||
const a = geom.pts[i];
|
||||
const b = geom.pts[(i + 1) % n];
|
||||
const arc = bulgeArc(a, b, geom.bulge?.[i] ?? 0);
|
||||
if (arc) {
|
||||
// Echter Bogen statt Sehne: Start-/Endwinkel aus dem Kreis, in der
|
||||
// Reihenfolge, die der Schwenkrichtung entspricht (a0 → a1 läuft in
|
||||
// der `arc`-Form immer gegen den Uhrzeigersinn).
|
||||
const forward = arc.sweep >= 0;
|
||||
out.push({
|
||||
shape: "arc",
|
||||
center: arc.center,
|
||||
r: arc.r,
|
||||
a0: forward ? arc.a0 : arc.a1,
|
||||
a1: forward ? arc.a1 : arc.a0,
|
||||
});
|
||||
} else {
|
||||
out.push({ shape: "line", a, b });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
case "rect": {
|
||||
const { min, max } = geom;
|
||||
const c1 = min;
|
||||
const c2 = { x: max.x, y: min.y };
|
||||
const c3 = max;
|
||||
const c4 = { x: min.x, y: max.y };
|
||||
return [
|
||||
{ shape: "line", a: c1, b: c2 },
|
||||
{ shape: "line", a: c2, b: c3 },
|
||||
{ shape: "line", a: c3, b: c4 },
|
||||
{ shape: "line", a: c4, b: c1 },
|
||||
];
|
||||
}
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Punkte einer Geometrie durch `fn` schicken (nur für die Block-Teilgeometrie nötig). */
|
||||
function mapPoints(geom: Drawing2DGeom, fn: (p: Vec2) => Vec2): Drawing2DGeom {
|
||||
switch (geom.shape) {
|
||||
case "line":
|
||||
case "xline":
|
||||
case "ray":
|
||||
return { ...geom, a: fn(geom.a), b: fn(geom.b) };
|
||||
case "polyline":
|
||||
return { ...geom, pts: geom.pts.map(fn) };
|
||||
case "rect":
|
||||
case "image":
|
||||
return { ...geom, min: fn(geom.min), max: fn(geom.max) };
|
||||
case "circle":
|
||||
case "arc":
|
||||
case "ellipse":
|
||||
return { ...geom, center: fn(geom.center) };
|
||||
case "bezier":
|
||||
case "spline":
|
||||
case "dimension":
|
||||
return { ...geom, pts: geom.pts.map(fn) };
|
||||
case "text":
|
||||
case "kote":
|
||||
case "detailref":
|
||||
case "scalebar":
|
||||
case "pointmarker":
|
||||
return { ...geom, at: fn(geom.at) };
|
||||
case "block":
|
||||
return { ...geom, at: fn(geom.at) };
|
||||
default:
|
||||
return geom;
|
||||
}
|
||||
}
|
||||
import { documentFor } from "../core/document";
|
||||
import { uniqueStamp } from "../tools/types";
|
||||
|
||||
/**
|
||||
* Löst die angegebenen 2D-Elemente auf: jedes zerlegbare Element wird durch
|
||||
* seine Einzelteile ERSETZT (gleiche Ebene/Kategorie und alle Stil-
|
||||
* Übersteuerungen bleiben erhalten), nicht zerlegbare bleiben unangetastet.
|
||||
* Die Reihenfolge im Array bleibt stabil — die Teile stehen an der Stelle des
|
||||
* Originals, damit sich die Zeichenreihenfolge (z-Anordnung) nicht ändert.
|
||||
* Die Teile stehen an der Stelle des Originals (Zeichenreihenfolge bleibt).
|
||||
*/
|
||||
export function explodeOps(project: Project, ids: readonly string[]): CoreOp[] {
|
||||
const wanted = new Set(ids);
|
||||
const replacements = new Map<string, Drawing2D[]>();
|
||||
for (const d of project.drawings2d) {
|
||||
const parts = wanted.has(d.id) ? explodeGeom(d.geom, project) : null;
|
||||
if (!parts || parts.length === 0) continue;
|
||||
// Stil-Eigenschaften der Quelle übernehmen; nur Identität und Geometrie sind neu. `hatchId`/Füllung
|
||||
// bleiben bewusst dran: es geht nichts verloren, falls der Nutzer die Linien wieder schliesst.
|
||||
replacements.set(d.id, parts.map((geom): Drawing2D => ({ ...d, id: uniqueId("dr2d"), geom })));
|
||||
}
|
||||
return replaceWithMany(project, "drawings2d", replacements);
|
||||
return documentFor(project).cmdOps({ cmd: "explode", ids, stamp: uniqueStamp() });
|
||||
}
|
||||
@@ -1,11 +1,19 @@
|
||||
/**
|
||||
* `joinDrawings` — Bogen-Segmente (bulge) müssen beim Verbinden erhalten
|
||||
* bleiben (nicht mehr stillschweigend zu Geraden entarten, s. Kopfkommentar
|
||||
* bei `toPolyFormAllowBulge`).
|
||||
* Verbinden (Join, Kern `cmd_edit.rs::join_ops`) — Bogen-Segmente (bulge) müssen beim Verbinden
|
||||
* erhalten bleiben (nicht mehr stillschweigend zu Geraden entarten).
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { cutSegment, joinDrawings, nearestEdgeIndex } from "./splitJoin";
|
||||
import type { Drawing2D } from "../model/types";
|
||||
import { cutSegment, nearestEdgeIndex } from "./splitJoin";
|
||||
import type { Drawing2D, Project } from "../model/types";
|
||||
import { documentFor } from "../core/document";
|
||||
import { applyOps } from "../core/ops";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
|
||||
/** Join der Elemente über den Kern: die neue Menge der Zeichnungen. */
|
||||
function joinDrawings(srcs: Drawing2D[]): Drawing2D[] {
|
||||
const p = { ...sampleProject, drawings2d: srcs } as Project;
|
||||
return applyOps(p, documentFor(p).cmdOps({ cmd: "join", ids: srcs.map((d) => d.id), stamp: "t" })).drawings2d;
|
||||
}
|
||||
|
||||
function poly(id: string, pts: { x: number; y: number }[], bulge?: number[]): Drawing2D {
|
||||
return {
|
||||
@@ -17,7 +25,7 @@ function poly(id: string, pts: { x: number; y: number }[], bulge?: number[]): Dr
|
||||
};
|
||||
}
|
||||
|
||||
describe("joinDrawings — bulge-Erhalt", () => {
|
||||
describe("Join — bulge-Erhalt", () => {
|
||||
it("zwei offene Ketten (eine mit Bogen) werden verbunden, der Bogen bleibt erhalten", () => {
|
||||
const a = poly("a", [{ x: -1, y: 0 }, { x: 1, y: 0 }], [1]); // Halbkreis
|
||||
const b = poly("b", [{ x: 1, y: 0 }, { x: 3, y: 0 }]); // gerade, schliesst an a's Ende an
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Editier-Operationen Split / Join / Segment-Löschen für 2D-Zeichenelemente
|
||||
// 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.
|
||||
@@ -6,7 +6,7 @@
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import type { Drawing2D, Drawing2DGeom, Vec2 } from "../model/types";
|
||||
import { joinChainsWithBulge, removeSegment, removeSegmentWithBulge, splitAtIntersections, splitClosedByChord, splitPolylineAtParam, vecEqual } from "../core";
|
||||
import { removeSegment, removeSegmentWithBulge, splitAtIntersections, splitClosedByChord, splitPolylineAtParam, vecEqual } from "../core";
|
||||
import { bulgeArcPoints, hasRealBulge } from "../core";
|
||||
|
||||
/** Eine Polylinien-Darstellung eines Drawing2D (für die Kernel-Funktionen). */
|
||||
@@ -48,9 +48,8 @@ export function toPolyForm(geom: Drawing2DGeom): PolyForm | null {
|
||||
}
|
||||
|
||||
/**
|
||||
* Wie {@link toPolyForm}, aber lässt Bogen-Segmente (bulge) durch — nur für
|
||||
* Join (`joinDrawings`), das die Kette per {@link joinChainsWithBulge} bulge-
|
||||
* erhaltend verkettet statt sie geometrisch neu aufzubauen.
|
||||
* 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.
|
||||
*/
|
||||
function toPolyFormAllowBulge(geom: Drawing2DGeom): PolyForm | null {
|
||||
if (geom.shape === "polyline") return { pts: geom.pts.slice(), closed: geom.closed, bulge: geom.bulge };
|
||||
@@ -207,31 +206,6 @@ function chordSplit(
|
||||
const dist = (a: Vec2, b: Vec2): number =>
|
||||
Math.hypot(a.x - b.x, a.y - b.y);
|
||||
|
||||
/**
|
||||
* Join: verbindet mehrere Drawing2D an koinzidenten Endpunkten zu Polylinien
|
||||
* (geschlossen, wenn sich eine Kette schließt). Nicht-polyline Elemente
|
||||
* (circle/arc/text) werden unverändert durchgereicht. Liefert die NEUE Menge
|
||||
* der Drawing2D, die die Eingabe-Elemente ersetzt. Attribute werden vom ersten
|
||||
* verbundenen Quell-Element geerbt.
|
||||
*/
|
||||
export function joinDrawings(srcs: Drawing2D[]): Drawing2D[] {
|
||||
const joinable: { form: PolyForm; src: Drawing2D }[] = [];
|
||||
const passthrough: Drawing2D[] = [];
|
||||
for (const d of srcs) {
|
||||
const form = toPolyFormAllowBulge(d.geom);
|
||||
if (form) joinable.push({ form, src: d });
|
||||
else passthrough.push(d);
|
||||
}
|
||||
if (joinable.length === 0) return srcs;
|
||||
|
||||
const chains = joinChainsWithBulge(joinable.map((j) => j.form));
|
||||
const template = joinable[0].src;
|
||||
const joined = chains.map((c) =>
|
||||
inherit(template, fromPolyForm({ pts: c.pts, closed: c.closed, bulge: c.bulge })),
|
||||
);
|
||||
return [...joined, ...passthrough];
|
||||
}
|
||||
|
||||
/**
|
||||
* Segment-Löschen (Schere): entfernt das Segment `edgeIndex` aus einem
|
||||
* Drawing2D. Geschlossene Form → offene Polylinie. Liefert das geänderte
|
||||
|
||||
@@ -1,166 +0,0 @@
|
||||
// Punkt-Abbildung von 2D-Zeichengeometrie (Verschieben/Spiegeln/Drehen/Skalieren). Reine
|
||||
// Geometrie ohne UI — Quelle für Transformations-Befehle, Block-Rendering und den Plan-Generator.
|
||||
|
||||
import type { Drawing2DGeom, Vec2 } from "../model/types";
|
||||
|
||||
|
||||
/**
|
||||
* Erkennt, ob `fn` die Umlauf-Orientierung umkehrt (Spiegelung) — via
|
||||
* Flächenvorzeichen eines Test-Dreiecks unter `fn` (negativ ⇒ Spiegelung).
|
||||
* Funktioniert für JEDE Isometrie/Similarity (Move/Rotate/Scale erhalten die
|
||||
* Orientierung, Mirror kehrt sie um), ohne dass eine Operation ihre Spiegel-
|
||||
* Eigenschaft explizit markieren müsste.
|
||||
*/
|
||||
export function reversesOrientation(fn: (p: Vec2) => Vec2): boolean {
|
||||
const p0 = fn({ x: 0, y: 0 }), p1 = fn({ x: 1, y: 0 }), p2 = fn({ x: 0, y: 1 });
|
||||
return (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y) < 0;
|
||||
}
|
||||
|
||||
/** Bildet jeden Punkt einer 2D-Zeichengeometrie unter `fn` ab (Move/Mirror/Rotate/Array + Block-Rendering). */
|
||||
/**
|
||||
* Wie {@link mvGeom}, zusätzlich für eine SKALIERUNG: `mvGeom` bildet nur
|
||||
* PUNKTE ab — Radien, Schrifthöhen und der Bemassungs-Abstand sind aber keine
|
||||
* Punkte und blieben sonst unverändert stehen (ein Kreis behielte unter einer
|
||||
* 2×-Skalierung seinen Radius). Diese Funktion zieht die betroffenen
|
||||
* Grössenfelder um denselben Faktor nach.
|
||||
*
|
||||
* Bewusst NICHT angefasst: `bulge` (ein Formverhältnis, skaleninvariant) und
|
||||
* die Papier-mm-Felder von Bemassung/Linienenden — die beziehen sich auf das
|
||||
* Blatt, nicht aufs Modell, und dürfen beim Skalieren des Objekts gleich
|
||||
* bleiben.
|
||||
*/
|
||||
/** Skalierungsfaktor eines `op:"scale"`-Punkte-Tripels bei Interpolation `t`. */
|
||||
export function scaleFactor(pts: Vec2[], t: number): number {
|
||||
const c = pts[0];
|
||||
const ref = Math.hypot(pts[1].x - c.x, pts[1].y - c.y) || 1;
|
||||
const tgt = Math.hypot(pts[2].x - c.x, pts[2].y - c.y);
|
||||
return 1 + (tgt / ref - 1) * t;
|
||||
}
|
||||
|
||||
export const scaleGeom = (geom: Drawing2DGeom, fn: (p: Vec2) => Vec2, f: number): Drawing2DGeom => {
|
||||
const g = mvGeom(geom, fn);
|
||||
switch (g.shape) {
|
||||
case "circle":
|
||||
return { ...g, r: g.r * f };
|
||||
case "arc":
|
||||
return { ...g, r: g.r * f };
|
||||
case "ellipse":
|
||||
return { ...g, rx: g.rx * f, ry: g.ry * f };
|
||||
case "dimension":
|
||||
// `offset` ist der Normalabstand der Masslinie in Modellmass.
|
||||
return { ...g, offset: g.offset * f };
|
||||
case "text":
|
||||
return {
|
||||
...g,
|
||||
height: g.height * f,
|
||||
...(g.width !== undefined ? { width: g.width * f } : {}),
|
||||
};
|
||||
case "scalebar":
|
||||
// Segmentlänge ist eine ECHTE Modell-Distanz (kein Papier-mm-Feld wie
|
||||
// bei Kote/Bemassung) — muss bei einer Modell-Skalierung mitwachsen,
|
||||
// sonst zeigt der Balken nach dem Skalieren die FALSCHE Distanz an.
|
||||
return { ...g, segmentLength: g.segmentLength * f };
|
||||
case "block":
|
||||
// Blockinstanz-Skalierung (s. Typ-Kommentar in model/types.ts) —
|
||||
// ohne diesen Fall wäre der `scale`-Befehl auf eine Blockinstanz ein
|
||||
// kompletter No-Op (kein Feld zum Multiplizieren).
|
||||
return { ...g, scale: (g.scale ?? 1) * f };
|
||||
default:
|
||||
return g;
|
||||
}
|
||||
};
|
||||
|
||||
export const mvGeom = (geom: Drawing2DGeom, fn: (p: Vec2) => Vec2): Drawing2DGeom => {
|
||||
switch (geom.shape) {
|
||||
case "line":
|
||||
case "xline":
|
||||
case "ray":
|
||||
return { ...geom, a: fn(geom.a), b: fn(geom.b) };
|
||||
case "polyline": {
|
||||
const pts = geom.pts.map(fn);
|
||||
if (!geom.bulge) return { ...geom, pts };
|
||||
// Bulge-Vorzeichen ist rein relativ zur Zeichenrichtung definiert (links
|
||||
// von a→b) — eine Spiegelung kehrt die Umlauf-Orientierung um und muss
|
||||
// daher auch jeden Bogen umkehren, sonst wandert er auf die falsche Seite.
|
||||
const bulge = reversesOrientation(fn) ? geom.bulge.map((b) => -b) : geom.bulge;
|
||||
return { ...geom, pts, bulge };
|
||||
}
|
||||
case "rect": {
|
||||
// Achsparallel nur bei reiner Verschiebung erhaltbar; sonst → Polylinie.
|
||||
const c = [
|
||||
geom.min,
|
||||
{ x: geom.max.x, y: geom.min.y },
|
||||
geom.max,
|
||||
{ x: geom.min.x, y: geom.max.y },
|
||||
].map(fn);
|
||||
const axisAligned =
|
||||
Math.abs(c[0].y - c[1].y) < 1e-6 &&
|
||||
Math.abs(c[1].x - c[2].x) < 1e-6 &&
|
||||
Math.abs(c[2].y - c[3].y) < 1e-6;
|
||||
if (axisAligned) {
|
||||
const xs = c.map((p) => p.x), ys = c.map((p) => p.y);
|
||||
return {
|
||||
shape: "rect",
|
||||
min: { x: Math.min(...xs), y: Math.min(...ys) },
|
||||
max: { x: Math.max(...xs), y: Math.max(...ys) },
|
||||
};
|
||||
}
|
||||
return { shape: "polyline", pts: c, closed: true };
|
||||
}
|
||||
case "circle":
|
||||
return { ...geom, center: fn(geom.center) };
|
||||
case "arc":
|
||||
return { ...geom, center: fn(geom.center) };
|
||||
case "ellipse":
|
||||
return { ...geom, center: fn(geom.center) };
|
||||
case "bezier":
|
||||
return { ...geom, pts: geom.pts.map(fn) };
|
||||
case "spline":
|
||||
return { ...geom, pts: geom.pts.map(fn) };
|
||||
case "dimension":
|
||||
return { ...geom, pts: geom.pts.map(fn) };
|
||||
case "kote":
|
||||
return { ...geom, at: fn(geom.at) };
|
||||
case "detailref":
|
||||
return { ...geom, at: fn(geom.at) };
|
||||
case "scalebar":
|
||||
return { ...geom, at: fn(geom.at) };
|
||||
case "pointmarker":
|
||||
return { ...geom, at: fn(geom.at) };
|
||||
case "text":
|
||||
// Leader-Ziel bzw. Pfadpunkte (Text-entlang-Pfad) müssen mitwandern,
|
||||
// sonst zeigt der Pfeil/Pfad nach einem Move/Mirror/Rotate/Array auf die
|
||||
// alte Position.
|
||||
return {
|
||||
...geom,
|
||||
at: fn(geom.at),
|
||||
...(geom.leaderTarget ? { leaderTarget: fn(geom.leaderTarget) } : {}),
|
||||
...(geom.leaderBendPoints ? { leaderBendPoints: geom.leaderBendPoints.map(fn) } : {}),
|
||||
...(geom.pathPts ? { pathPts: geom.pathPts.map(fn) } : {}),
|
||||
};
|
||||
case "block": {
|
||||
// Wie Column: Winkel aus einem transformierten Richtungspunkt zurück-
|
||||
// rechnen, damit Rotate/Mirror auch die Instanz-Ausrichtung mitnehmen
|
||||
// (nicht nur den Einfügepunkt) — reine Translation liesse die Symbole
|
||||
// beim Drehen der Auswahl in der alten Orientierung stehen.
|
||||
const tip = { x: geom.at.x + Math.cos(geom.rotation), y: geom.at.y + Math.sin(geom.rotation) };
|
||||
const nb = fn(geom.at);
|
||||
const nt = fn(tip);
|
||||
return { ...geom, at: nb, rotation: Math.atan2(nt.y - nb.y, nt.x - nb.x) };
|
||||
}
|
||||
case "image": {
|
||||
// Wie Text: nur die Position folgt der Transformation (Zentrum wandert
|
||||
// dorthin, wo `fn` es abbildet); die Box bleibt achsparallel/unverzerrt —
|
||||
// ein Bild kann nicht geschert/rotiert dargestellt werden (kein `angle`-Feld).
|
||||
const oldCenter = { x: (geom.min.x + geom.max.x) / 2, y: (geom.min.y + geom.max.y) / 2 };
|
||||
const newCenter = fn(oldCenter);
|
||||
const dx = newCenter.x - oldCenter.x;
|
||||
const dy = newCenter.y - oldCenter.y;
|
||||
return {
|
||||
...geom,
|
||||
min: { x: geom.min.x + dx, y: geom.min.y + dy },
|
||||
max: { x: geom.max.x + dx, y: geom.max.y + dy },
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,84 +0,0 @@
|
||||
/**
|
||||
* `nearestOnPolyline`/`breakCurve` — Grundlage des BREAK-Befehls (entfernt
|
||||
* den Abschnitt ZWISCHEN zwei Positionen auf einer offenen Punktfolge).
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { breakCurve, nearestOnPolyline } from "./kernel2d";
|
||||
import type { Vec2 } from "../model/types";
|
||||
|
||||
describe("nearestOnPolyline", () => {
|
||||
it("findet die nächste Position auf einer geraden Linie", () => {
|
||||
const pts: Vec2[] = [{ x: 0, y: 0 }, { x: 10, y: 0 }];
|
||||
const hit = nearestOnPolyline(pts, false, { x: 3, y: 1 });
|
||||
expect(hit).not.toBeNull();
|
||||
expect(hit!.edgeIndex).toBe(0);
|
||||
expect(hit!.t).toBeCloseTo(0.3, 6);
|
||||
});
|
||||
|
||||
it("wählt die richtige Kante bei mehreren Segmenten", () => {
|
||||
const pts: Vec2[] = [{ x: 0, y: 0 }, { x: 5, y: 0 }, { x: 5, y: 5 }];
|
||||
const hit = nearestOnPolyline(pts, false, { x: 5, y: 3 });
|
||||
expect(hit).not.toBeNull();
|
||||
expect(hit!.edgeIndex).toBe(1);
|
||||
expect(hit!.t).toBeCloseTo(0.6, 6);
|
||||
});
|
||||
|
||||
it("klemmt t auf [0,1] (Klick jenseits eines Endpunkts)", () => {
|
||||
const pts: Vec2[] = [{ x: 0, y: 0 }, { x: 10, y: 0 }];
|
||||
const hit = nearestOnPolyline(pts, false, { x: 20, y: 0 });
|
||||
expect(hit!.t).toBe(1);
|
||||
});
|
||||
|
||||
it("liefert null bei < 2 Punkten", () => {
|
||||
expect(nearestOnPolyline([{ x: 0, y: 0 }], false, { x: 0, y: 0 })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("breakCurve", () => {
|
||||
const line: Vec2[] = [{ x: 0, y: 0 }, { x: 10, y: 0 }];
|
||||
|
||||
it("entfernt den Abschnitt zwischen zwei Punkten auf einer geraden Linie", () => {
|
||||
const hit1 = nearestOnPolyline(line, false, { x: 3, y: 0 })!;
|
||||
const hit2 = nearestOnPolyline(line, false, { x: 7, y: 0 })!;
|
||||
const pieces = breakCurve(line, hit1, hit2);
|
||||
expect(pieces.length).toBe(2);
|
||||
expect(pieces[0]).toEqual([{ x: 0, y: 0 }, { x: 3, y: 0 }]);
|
||||
expect(pieces[1]).toEqual([{ x: 7, y: 0 }, { x: 10, y: 0 }]);
|
||||
});
|
||||
|
||||
it("Klick-Reihenfolge ist irrelevant (Positionen werden intern sortiert)", () => {
|
||||
const hit1 = nearestOnPolyline(line, false, { x: 7, y: 0 })!; // zuerst der SPÄTERE Punkt geklickt
|
||||
const hit2 = nearestOnPolyline(line, false, { x: 3, y: 0 })!;
|
||||
const pieces = breakCurve(line, hit1, hit2);
|
||||
expect(pieces[0]).toEqual([{ x: 0, y: 0 }, { x: 3, y: 0 }]);
|
||||
expect(pieces[1]).toEqual([{ x: 7, y: 0 }, { x: 10, y: 0 }]);
|
||||
});
|
||||
|
||||
it("Bruch nahe einem Endpunkt liefert nur EIN Reststück (das andere fällt zu kurz aus)", () => {
|
||||
const hit1 = nearestOnPolyline(line, false, { x: 0, y: 0 })!;
|
||||
const hit2 = nearestOnPolyline(line, false, { x: 6, y: 0 })!;
|
||||
const pieces = breakCurve(line, hit1, hit2);
|
||||
expect(pieces.length).toBe(1);
|
||||
expect(pieces[0]).toEqual([{ x: 6, y: 0 }, { x: 10, y: 0 }]);
|
||||
});
|
||||
|
||||
it("funktioniert über mehrere Segmente einer offenen Polylinie hinweg", () => {
|
||||
const poly: Vec2[] = [{ x: 0, y: 0 }, { x: 5, y: 0 }, { x: 5, y: 5 }, { x: 10, y: 5 }];
|
||||
const hit1 = nearestOnPolyline(poly, false, { x: 2, y: 0 })!; // auf Segment 0
|
||||
const hit2 = nearestOnPolyline(poly, false, { x: 8, y: 5 })!; // auf Segment 2
|
||||
const pieces = breakCurve(poly, hit1, hit2);
|
||||
expect(pieces.length).toBe(2);
|
||||
expect(pieces[0]).toEqual([{ x: 0, y: 0 }, { x: 2, y: 0 }]);
|
||||
expect(pieces[1]).toEqual([{ x: 8, y: 5 }, { x: 10, y: 5 }]);
|
||||
});
|
||||
|
||||
it("beide Punkte auf derselben Kante trennen sauber, ohne die übrigen Punkte zu verlieren", () => {
|
||||
const poly: Vec2[] = [{ x: 0, y: 0 }, { x: 10, y: 0 }, { x: 10, y: 10 }];
|
||||
const hit1 = nearestOnPolyline(poly, false, { x: 4, y: 0 })!;
|
||||
const hit2 = nearestOnPolyline(poly, false, { x: 6, y: 0 })!;
|
||||
const pieces = breakCurve(poly, hit1, hit2);
|
||||
expect(pieces.length).toBe(2);
|
||||
expect(pieces[0]).toEqual([{ x: 0, y: 0 }, { x: 4, y: 0 }]);
|
||||
expect(pieces[1]).toEqual([{ x: 6, y: 0 }, { x: 10, y: 0 }, { x: 10, y: 10 }]);
|
||||
});
|
||||
});
|
||||
@@ -1,70 +0,0 @@
|
||||
/**
|
||||
* `extendBulgeSegment` — Verlängerung eines Bogen-Endsegments (DXF-bulge)
|
||||
* über einen Endpunkt hinaus, entlang DESSELBEN Kreises (Mittelpunkt/Radius
|
||||
* unverändert, nur die Schwenk-Spanne wächst) bis zum nächsten geraden
|
||||
* Schneider. Gegenstück zu `extendSegment` (Geraden-only).
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { bulgeArc } from "./bulge";
|
||||
import { extendBulgeSegment } from "./kernel2d";
|
||||
import type { Vec2 } from "../model/types";
|
||||
|
||||
// Halbkreis a=(-1,0) → b=(1,0), bulge=1 ⇒ center=(0,0), r=1, Apex bei (0,1).
|
||||
const A: Vec2 = { x: -1, y: 0 };
|
||||
const B: Vec2 = { x: 1, y: 0 };
|
||||
const BULGE = 1;
|
||||
|
||||
describe("extendBulgeSegment", () => {
|
||||
it("verlängert über `b` hinaus (end='end') bis zum tangentialen Schneider y=-1", () => {
|
||||
const cutter = { pts: [{ x: -10, y: -1 }, { x: 10, y: -1 }], closed: false };
|
||||
const res = extendBulgeSegment(A, B, BULGE, "end", [cutter]);
|
||||
expect(res).not.toBeNull();
|
||||
expect(res!.point.x).toBeCloseTo(0, 6);
|
||||
expect(res!.point.y).toBeCloseTo(-1, 6);
|
||||
// Derselbe Kreis: Rückwärtsprobe über bulgeArc(a, neuer-Endpunkt, neuer bulge).
|
||||
const arc = bulgeArc(A, res!.point, res!.bulge);
|
||||
expect(arc).not.toBeNull();
|
||||
expect(arc!.center.x).toBeCloseTo(0, 6);
|
||||
expect(arc!.center.y).toBeCloseTo(0, 6);
|
||||
expect(arc!.r).toBeCloseTo(1, 6);
|
||||
});
|
||||
|
||||
it("verlängert über `a` hinaus (end='start') symmetrisch, `b` bleibt fest", () => {
|
||||
const cutter = { pts: [{ x: -10, y: -1 }, { x: 10, y: -1 }], closed: false };
|
||||
const res = extendBulgeSegment(A, B, BULGE, "start", [cutter]);
|
||||
expect(res).not.toBeNull();
|
||||
expect(res!.point.x).toBeCloseTo(0, 6);
|
||||
expect(res!.point.y).toBeCloseTo(-1, 6);
|
||||
const arc = bulgeArc(res!.point, B, res!.bulge);
|
||||
expect(arc).not.toBeNull();
|
||||
expect(arc!.center.x).toBeCloseTo(0, 6);
|
||||
expect(arc!.center.y).toBeCloseTo(0, 6);
|
||||
expect(arc!.r).toBeCloseTo(1, 6);
|
||||
});
|
||||
|
||||
it("kein Schneider trifft den Kreis → null (kein Effekt)", () => {
|
||||
// Gerade weit ausserhalb des Einheitskreises, trifft ihn nie.
|
||||
const cutter = { pts: [{ x: -10, y: 5 }, { x: 10, y: 5 }], closed: false };
|
||||
const res = extendBulgeSegment(A, B, BULGE, "end", [cutter]);
|
||||
expect(res).toBeNull();
|
||||
});
|
||||
|
||||
it("Gerade (bulge≈0) liefert null — Aufrufer soll auf extendSegment ausweichen", () => {
|
||||
const cutter = { pts: [{ x: -10, y: -1 }, { x: 10, y: -1 }], closed: false };
|
||||
const res = extendBulgeSegment(A, B, 0, "end", [cutter]);
|
||||
expect(res).toBeNull();
|
||||
});
|
||||
|
||||
it("wählt den NÄCHSTGELEGENEN Schneider in Schwenkrichtung, nicht irgendeinen Treffer", () => {
|
||||
// Zwei Schneider unterhalb: einer nah (Tangente y=-1, delta=π/2 ab b),
|
||||
// einer weiter weg (Gerade x=-3, schneidet den Kreis gar nicht — Kontrolle),
|
||||
// plus ein echter zweiter Treffer weiter entlang der Schwenkrichtung (y=0.999,
|
||||
// sehr nah an a selbst — muss NICHT gewählt werden, da a0 rausgefiltert wird
|
||||
// und der Kreis dort ohnehin nicht geschnitten wird ausserhalb [-1,1]).
|
||||
const near = { pts: [{ x: -10, y: -1 }, { x: 10, y: -1 }], closed: false };
|
||||
const outside = { pts: [{ x: -3, y: -10 }, { x: -3, y: 10 }], closed: false }; // x=-3, ausserhalb r=1
|
||||
const res = extendBulgeSegment(A, B, BULGE, "end", [outside, near]);
|
||||
expect(res).not.toBeNull();
|
||||
expect(res!.point.y).toBeCloseTo(-1, 6); // der einzig echte Treffer (Tangente)
|
||||
});
|
||||
});
|
||||
@@ -1,77 +0,0 @@
|
||||
/**
|
||||
* `offsetPolylineWithBulge` — Offset einer Polylinie mit Bogen-Segmenten
|
||||
* (DXF-bulge). Deckt genau die Fälle ab, die `offsetPolyline` (Geraden-only)
|
||||
* nicht kann: konzentrischer Radius-Offset eines Bogens, und Gehrung
|
||||
* (miter) zwischen Bogen↔Gerade bzw. Bogen↔Bogen.
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { offsetPolylineWithBulge } from "./kernel2d";
|
||||
|
||||
describe("offsetPolylineWithBulge", () => {
|
||||
it("Halbkreis (bulge=1): Offset nach links (+d) vergrössert den Radius, bulge bleibt gleich", () => {
|
||||
// a=(-1,0) → b=(1,0), bulge=1 ⇒ Halbkreis, center=(0,0), r=1 (s. bulge.test.ts).
|
||||
const res = offsetPolylineWithBulge(
|
||||
[{ x: -1, y: 0 }, { x: 1, y: 0 }],
|
||||
[1],
|
||||
0.3,
|
||||
false,
|
||||
);
|
||||
expect(res.pts.length).toBe(2);
|
||||
// Neuer Radius r'=1.3 ⇒ neue Endpunkte bei (±1.3, 0).
|
||||
expect(res.pts[0].x).toBeCloseTo(-1.3, 6);
|
||||
expect(res.pts[0].y).toBeCloseTo(0, 6);
|
||||
expect(res.pts[1].x).toBeCloseTo(1.3, 6);
|
||||
expect(res.pts[1].y).toBeCloseTo(0, 6);
|
||||
// bulge kodiert nur den Öffnungswinkel (unverändert bei gleichem Winkelbereich).
|
||||
expect(res.bulge[0]).toBeCloseTo(1, 6);
|
||||
});
|
||||
|
||||
it("Halbkreis: Offset nach rechts (−d) verkleinert den Radius", () => {
|
||||
const res = offsetPolylineWithBulge(
|
||||
[{ x: -1, y: 0 }, { x: 1, y: 0 }],
|
||||
[1],
|
||||
-0.3,
|
||||
false,
|
||||
);
|
||||
expect(res.pts[0].x).toBeCloseTo(-0.7, 6);
|
||||
expect(res.pts[1].x).toBeCloseTo(0.7, 6);
|
||||
expect(res.bulge[0]).toBeCloseTo(1, 6);
|
||||
});
|
||||
|
||||
it("Gerade ohne bulge bleibt exakt wie offsetPolyline (Geraden-only Fallback deckungsgleich)", () => {
|
||||
const res = offsetPolylineWithBulge(
|
||||
[{ x: 0, y: 0 }, { x: 2, y: 0 }],
|
||||
undefined,
|
||||
0.5,
|
||||
false,
|
||||
);
|
||||
expect(res.pts).toEqual([{ x: 0, y: 0.5 }, { x: 2, y: 0.5 }]);
|
||||
expect(res.bulge).toEqual([0]);
|
||||
});
|
||||
|
||||
it("Gerade → Bogen → Gerade: die Gehrung an der Bogen-Naht liegt auf dem Bogen-Kreis", () => {
|
||||
// Gerade (0,0)→(2,0), Viertelkreisbogen (2,0)→(2,2) mit bulge=tan(45°/2)...
|
||||
// einfacher: Viertelkreis ⇒ Δ=π/2 ⇒ bulge=tan(π/8).
|
||||
const bulge = Math.tan(Math.PI / 8);
|
||||
const pts = [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 2 }];
|
||||
const res = offsetPolylineWithBulge(pts, [0, bulge], 0.2, false);
|
||||
expect(res.pts.length).toBe(3);
|
||||
expect(res.bulge.length).toBe(2);
|
||||
// Erste Kante bleibt gerade.
|
||||
expect(res.bulge[0]).toBeCloseTo(0, 6);
|
||||
// Zweite Kante bleibt ein echter Bogen (nicht 0).
|
||||
expect(Math.abs(res.bulge[1])).toBeGreaterThan(0.01);
|
||||
// Der mittlere (Naht-)Punkt muss näher am Bogen-Zentrum (2,0)... je nach
|
||||
// Seite verschoben, aber jedenfalls NICHT mehr exakt der rohe Eck-Punkt (2,0).
|
||||
expect(res.pts[1]).not.toEqual({ x: 2, y: 0 });
|
||||
});
|
||||
|
||||
it("geschlossene Form (Kreis-artiges Polygon mit einem Bogen-Segment) bleibt geschlossen", () => {
|
||||
// Dreieck mit einer verrundeten Ecke (wie ein Fillet-Ergebnis).
|
||||
const pts = [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }, { x: 0, y: 4 }];
|
||||
const bulge = [0, 0, 0, 0];
|
||||
const res = offsetPolylineWithBulge(pts, bulge, 0.2, true);
|
||||
expect(res.pts.length).toBe(4);
|
||||
expect(res.bulge).toEqual([0, 0, 0, 0]);
|
||||
});
|
||||
});
|
||||
@@ -1,118 +0,0 @@
|
||||
/**
|
||||
* `trimPolylineWithBulge` — Quick-Trim einer Ziel-Kurve mit Bogen-Segmenten
|
||||
* (bulge). Deckt sowohl GERADE als auch BOGEN-Schneider ab (Kreis↔Gerade UND
|
||||
* Kreis↔Kreis, s. `edgeIntersectTs` im Kernel): ein Bogen-Segment wird korrekt
|
||||
* zerschnitten, der verbleibende Teilbogen behält seine Krümmung (neu
|
||||
* hergeleiteter bulge-Wert).
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { bulgeArc } from "./bulge";
|
||||
import { trimPolylineWithBulge } from "./kernel2d";
|
||||
|
||||
describe("trimPolylineWithBulge", () => {
|
||||
it("Halbkreis, gegen eine senkrechte Gerade am Apex getrimmt: die geklickte Hälfte fällt weg", () => {
|
||||
// a=(-1,0) → b=(1,0), bulge=1 ⇒ Halbkreis, center=(0,0), r=1.
|
||||
const pts = [{ x: -1, y: 0 }, { x: 1, y: 0 }];
|
||||
const bulge = [1];
|
||||
const cutter = { pts: [{ x: 0, y: -5 }, { x: 0, y: 5 }], closed: false };
|
||||
// Klick im rechten Viertelbogen (zwischen Apex (0,1) und b=(1,0)).
|
||||
const pick = { x: Math.SQRT1_2, y: Math.SQRT1_2 };
|
||||
const rest = trimPolylineWithBulge(pts, bulge, false, [cutter], pick);
|
||||
expect(rest.length).toBe(1);
|
||||
const [chain] = rest;
|
||||
expect(chain.pts.length).toBe(2);
|
||||
expect(chain.pts[0].x).toBeCloseTo(-1, 6);
|
||||
expect(chain.pts[0].y).toBeCloseTo(0, 6);
|
||||
expect(chain.pts[1].x).toBeCloseTo(0, 6);
|
||||
expect(chain.pts[1].y).toBeCloseTo(1, 6);
|
||||
// Der verbleibende Viertelbogen muss geometrisch exakt auf demselben Kreis
|
||||
// liegen (center=(0,0), r=1) — bulge kodiert weiterhin einen echten Bogen.
|
||||
const arc = bulgeArc(chain.pts[0], chain.pts[1], chain.bulge[0]);
|
||||
expect(arc).not.toBeNull();
|
||||
expect(arc!.center.x).toBeCloseTo(0, 5);
|
||||
expect(arc!.center.y).toBeCloseTo(0, 5);
|
||||
expect(arc!.r).toBeCloseTo(1, 5);
|
||||
});
|
||||
|
||||
it("kein Schnitt mit dem Cutter → Kurve bleibt unverändert (inkl. bulge)", () => {
|
||||
const pts = [{ x: -1, y: 0 }, { x: 1, y: 0 }];
|
||||
const bulge = [1];
|
||||
const cutter = { pts: [{ x: 10, y: -5 }, { x: 10, y: 5 }], closed: false };
|
||||
const rest = trimPolylineWithBulge(pts, bulge, false, [cutter], { x: 0, y: 1 });
|
||||
expect(rest.length).toBe(1);
|
||||
expect(rest[0].pts).toEqual(pts);
|
||||
expect(rest[0].bulge).toEqual([1]);
|
||||
});
|
||||
|
||||
it("gerade Kanten in einer gemischten Kurve bleiben unangetastet (bulge=0)", () => {
|
||||
// Gerade (0,0)→(2,0), dann Halbkreis (2,0)→(4,0) mit bulge=1 (center=(3,0),r=1).
|
||||
const pts = [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 4, y: 0 }];
|
||||
const bulge = [0, 1];
|
||||
const cutter = { pts: [{ x: 1, y: -5 }, { x: 1, y: 5 }], closed: false };
|
||||
const rest = trimPolylineWithBulge(pts, bulge, false, [cutter], { x: 0.5, y: 0 });
|
||||
// Der Schnitt liegt auf der GERADEN ersten Kante bei x=1 → das linke Stück
|
||||
// (0,0)→(1,0), angeklickt, fällt weg; das rechte Stück bleibt (gerade
|
||||
// Restkante + unverändertem Bogen).
|
||||
expect(rest.length).toBe(1);
|
||||
expect(rest[0].pts[0].x).toBeCloseTo(1, 6);
|
||||
expect(rest[0].bulge[0]).toBeCloseTo(0, 6); // Rest der geraden Kante
|
||||
expect(rest[0].bulge[1]).toBeCloseTo(1, 6); // Bogen unverändert
|
||||
});
|
||||
|
||||
it("GERADES Ziel gegen einen BOGEN-Schneider: der Kreis-Schnitt zählt als Cut-Knoten", () => {
|
||||
// Ziel: waagrechte Gerade y=0 von x=-5 bis x=5.
|
||||
const pts = [{ x: -5, y: 0 }, { x: 5, y: 0 }];
|
||||
// Schneider: Bogen von (0,-2) nach (0,2) mit bulge=1 ⇒ center=(0,0), r=2,
|
||||
// bulgt nach LINKS (Apex bei (-2,0)) — kreuzt die Ziel-Gerade exakt einmal
|
||||
// bei (-2,0) (Apex liegt genau auf der Geraden).
|
||||
const cutter = { pts: [{ x: 0, y: -2 }, { x: 0, y: 2 }], closed: false, bulge: [1] };
|
||||
// Klick LINKS vom Schnittpunkt → das linke Stück [-5,-2] fällt weg.
|
||||
const rest = trimPolylineWithBulge(pts, undefined, false, [cutter], { x: -3, y: 0 });
|
||||
expect(rest.length).toBe(1);
|
||||
expect(rest[0].pts[0].x).toBeCloseTo(-2, 6);
|
||||
expect(rest[0].pts[0].y).toBeCloseTo(0, 6);
|
||||
expect(rest[0].pts[1]).toEqual({ x: 5, y: 0 });
|
||||
});
|
||||
|
||||
it("BOGEN-Ziel gegen BOGEN-Schneider: Kreis↔Kreis-Schnitt, Treffer nur innerhalb BEIDER Spannen", () => {
|
||||
// Ziel: oberer Halbkreis, center=(0,0), r=1 (a=(-1,0)→b=(1,0), bulge=1).
|
||||
const targetPts = [{ x: -1, y: 0 }, { x: 1, y: 0 }];
|
||||
const targetBulge = [1];
|
||||
// Schneider: oberer Halbkreis von center=(1,0), r=1 (a=(0,0)→b=(2,0), bulge=1,
|
||||
// per Translationssymmetrie zum Ziel — ebenfalls die obere Hälfte).
|
||||
// Klassischer "Vesica Piscis"-Schnitt zweier Einheitskreise im Abstand 1:
|
||||
// (0.5, ±√3/2) — nur der OBERE Punkt liegt in BEIDEN oberen Halbkreis-Spannen.
|
||||
const cutter = { pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }], closed: false, bulge: [1] };
|
||||
// Klick nahe a=(-1,0) (vor dem Schnittpunkt in Schwenkrichtung) → das
|
||||
// Stück von a bis zum Schnittpunkt fällt weg, der Rest (Schnittpunkt→b) bleibt.
|
||||
const pick = { x: Math.cos((2 * Math.PI) / 3), y: Math.sin((2 * Math.PI) / 3) }; // 120°, vor dem Schnitt bei 60°
|
||||
const rest = trimPolylineWithBulge(targetPts, targetBulge, false, [cutter], pick);
|
||||
expect(rest.length).toBe(1);
|
||||
const [chain] = rest;
|
||||
expect(chain.pts[0].x).toBeCloseTo(0.5, 6);
|
||||
expect(chain.pts[0].y).toBeCloseTo(Math.sqrt(3) / 2, 6);
|
||||
expect(chain.pts[chain.pts.length - 1]).toEqual({ x: 1, y: 0 });
|
||||
// Der verbleibende Bogen liegt weiterhin exakt auf dem ZIEL-Kreis (0,0)/r=1,
|
||||
// NICHT auf dem Schneider-Kreis.
|
||||
const arc = bulgeArc(chain.pts[0], chain.pts[chain.pts.length - 1], chain.bulge[0]);
|
||||
expect(arc).not.toBeNull();
|
||||
expect(arc!.center.x).toBeCloseTo(0, 5);
|
||||
expect(arc!.center.y).toBeCloseTo(0, 5);
|
||||
expect(arc!.r).toBeCloseTo(1, 5);
|
||||
});
|
||||
|
||||
it("Bogen-Schneider ausserhalb seiner eigenen Spanne zählt NICHT als Treffer", () => {
|
||||
// Gleiche Kreis-Geometrie wie oben (Vesica Piscis, Schnitt bei (0.5, ±√3/2)),
|
||||
// aber der Schneider deckt nur den UNTEREN Halbkreis seines Kreises ab
|
||||
// (a=(0,0)→b=(2,0), bulge=-1) — der relevante obere Schnittpunkt (0.5,√3/2)
|
||||
// liegt dann ausserhalb der Schneider-Spanne → kein Cut, Ziel bleibt ganz.
|
||||
const targetPts = [{ x: -1, y: 0 }, { x: 1, y: 0 }];
|
||||
const targetBulge = [1];
|
||||
const cutter = { pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }], closed: false, bulge: [-1] };
|
||||
const pick = { x: 0, y: 1 }; // Apex des Ziel-Bogens
|
||||
const rest = trimPolylineWithBulge(targetPts, targetBulge, false, [cutter], pick);
|
||||
expect(rest.length).toBe(1);
|
||||
expect(rest[0].pts).toEqual(targetPts);
|
||||
expect(rest[0].bulge).toEqual([1]);
|
||||
});
|
||||
});
|
||||
+3
-171
@@ -1,6 +1,7 @@
|
||||
// 2D-Geometrie-Kernel — Fassade über den Rust-Kern (`src-tauri/kernel2d`, gebunden in
|
||||
// `src-tauri/core/src/web/kernel2d.rs`, geladen über `engine/coreWasm.ts`). Offset / Trim /
|
||||
// Extend / Fillet / Fase / Split / Join / Bruch, auch mit Bogen-Segmenten (bulge). Die
|
||||
// Fillet / Split / Segment löschen, auch mit Bogen-Segmenten (bulge); Trim/Extend/Fase/Bruch/
|
||||
// Offset/Join rufen die Editier-Befehle direkt im Kern auf (`core/src/cmd_edit.rs`). Die
|
||||
// Rechenlogik liegt ausschliesslich in Rust; hier wird nur kodiert/dekodiert (flache
|
||||
// Float64Arrays, Formate s. Kopf von `web/kernel2d.rs`).
|
||||
//
|
||||
@@ -35,8 +36,6 @@ export function polylineEdges(pts: Vec2[], closed: boolean): [Vec2, Vec2][] {
|
||||
|
||||
// ── Kodierung ────────────────────────────────────────────────────────────────
|
||||
|
||||
type Cutter = { pts: Vec2[]; closed: boolean; bulge?: (number | undefined)[] };
|
||||
|
||||
function encPts(pts: Vec2[]): Float64Array {
|
||||
const out = new Float64Array(pts.length * 2);
|
||||
for (let i = 0; i < pts.length; i++) {
|
||||
@@ -51,22 +50,6 @@ function encBulge(bulge: (number | undefined)[] | undefined): Float64Array {
|
||||
return Float64Array.from(bulge ?? [], (b) => b ?? 0);
|
||||
}
|
||||
|
||||
/** Ketten: `[n, (closed, n_pts, xy…, n_bulge|-1, b…)…]`. */
|
||||
function encChains(list: Cutter[], keepMissingBulge = false): Float64Array {
|
||||
const out: number[] = [list.length];
|
||||
for (const c of list) {
|
||||
out.push(c.closed ? 1 : 0, c.pts.length);
|
||||
for (const p of c.pts) out.push(p.x, p.y);
|
||||
if (c.bulge === undefined) {
|
||||
out.push(keepMissingBulge ? -1 : 0);
|
||||
} else {
|
||||
out.push(c.bulge.length);
|
||||
for (const b of c.bulge) out.push(b ?? 0);
|
||||
}
|
||||
}
|
||||
return Float64Array.from(out);
|
||||
}
|
||||
|
||||
/** Liste von Punktlisten: `[n, (n_pts, xy…)…]`. */
|
||||
function encPtLists(lists: Vec2[][]): Float64Array {
|
||||
const out: number[] = [lists.length];
|
||||
@@ -95,22 +78,6 @@ function decPtLists(buf: Float64Array): Vec2[][] {
|
||||
return out;
|
||||
}
|
||||
|
||||
function decChains(buf: Float64Array): { pts: Vec2[]; closed: boolean; bulge: number[] }[] {
|
||||
const n = buf[0] ?? 0;
|
||||
const out: { pts: Vec2[]; closed: boolean; bulge: number[] }[] = [];
|
||||
let i = 1;
|
||||
for (let k = 0; k < n; k++) {
|
||||
const closed = buf[i++] !== 0;
|
||||
const m = buf[i++];
|
||||
const pts = decPts(buf, i, m);
|
||||
i += 2 * m;
|
||||
const nb = buf[i++];
|
||||
out.push({ pts, closed, bulge: Array.from(buf.subarray(i, i + nb)) });
|
||||
i += nb;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** `[n_pts, xy…, bulge…]`. */
|
||||
function decPtsBulge(buf: Float64Array): { pts: Vec2[]; bulge: number[] } {
|
||||
const n = buf[0] ?? 0;
|
||||
@@ -147,94 +114,6 @@ export function offsetSegment(a: Vec2, b: Vec2, d: number): [Vec2, Vec2] {
|
||||
return [{ x: r[0], y: r[1] }, { x: r[2], y: r[3] }];
|
||||
}
|
||||
|
||||
/**
|
||||
* Offset einer Polylinie um `d` (links positiv) mit Gehrung; offene und geschlossene
|
||||
* Polylinien, degenerierte Kanten werden übersprungen. Selbstüberschneidungen bei starkem
|
||||
* Offset werden nicht bereinigt.
|
||||
*/
|
||||
export function offsetPolyline(pts: Vec2[], d: number, closed: boolean): Vec2[] {
|
||||
return decPts(core().k2_offset_polyline(encPts(pts), d, closed));
|
||||
}
|
||||
|
||||
/**
|
||||
* Offset einer Polylinie MIT Bogen-Segmenten um `d` (links positiv): Bögen bleiben
|
||||
* konzentrisch, Nachbarkanten werden auf Gehrung geschnitten, der bulge an den Nahtstellen
|
||||
* aus den tatsächlichen Endpunkt-Winkeln neu hergeleitet.
|
||||
*/
|
||||
export function offsetPolylineWithBulge(
|
||||
pts: Vec2[],
|
||||
bulge: (number | undefined)[] | undefined,
|
||||
d: number,
|
||||
closed: boolean,
|
||||
): { pts: Vec2[]; bulge: number[] } {
|
||||
return decPtsBulge(core().k2_offset_polyline_with_bulge(encPts(pts), encBulge(bulge), d, closed));
|
||||
}
|
||||
|
||||
// ── Trim / Extend ───────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Quick-Trim einer ganzen Kurve (offen oder geschlossen): sie wird an allen Schnitten mit
|
||||
* den Cuttern zerlegt, das `pick` nächste Stück entfällt. Offen → 0..2 Reststücke,
|
||||
* geschlossen → ein offenes Reststück. Ohne Schnitt bleibt die Kurve unverändert.
|
||||
*/
|
||||
export function trimPolyline(
|
||||
pts: Vec2[],
|
||||
closed: boolean,
|
||||
cutters: { pts: Vec2[]; closed: boolean }[],
|
||||
pick: Vec2,
|
||||
): { pts: Vec2[]; closed: boolean }[] {
|
||||
return decChains(core().k2_trim_polyline(encPts(pts), closed, encChains(cutters), pick.x, pick.y)).map(
|
||||
({ pts, closed }) => ({ pts, closed }),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wie {@link trimPolyline}, aber Ziel-Kurve UND Schneider dürfen Bogen-Segmente tragen
|
||||
* (Kreis↔Gerade und Kreis↔Kreis; Bogen-Schneider zählen nur innerhalb ihrer Spanne).
|
||||
* Liefert die verbleibenden Ketten inkl. bulge.
|
||||
*/
|
||||
export function trimPolylineWithBulge(
|
||||
pts: Vec2[],
|
||||
bulge: (number | undefined)[] | undefined,
|
||||
closed: boolean,
|
||||
cutters: { pts: Vec2[]; closed: boolean; bulge?: (number | undefined)[] }[],
|
||||
pick: Vec2,
|
||||
): { pts: Vec2[]; closed: boolean; bulge: number[] }[] {
|
||||
return decChains(
|
||||
core().k2_trim_polyline_with_bulge(encPts(pts), encBulge(bulge), closed, encChains(cutters), pick.x, pick.y),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verlängert das gewählte Ende der Strecke a1→a2 bis zur nächsten Schneider-Kante in
|
||||
* Verlängerungsrichtung; null ohne Treffer.
|
||||
*/
|
||||
export function extendSegment(
|
||||
a1: Vec2,
|
||||
a2: Vec2,
|
||||
end: "start" | "end",
|
||||
cutters: { pts: Vec2[]; closed: boolean }[],
|
||||
): [Vec2, Vec2] | null {
|
||||
const r = core().k2_extend_segment(a1.x, a1.y, a2.x, a2.y, end === "end", encChains(cutters));
|
||||
return r.length === 4 ? [{ x: r[0], y: r[1] }, { x: r[2], y: r[3] }] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wie {@link extendSegment} für ein Bogen-Segment a→b (bulge): verlängert den Kreisbogen
|
||||
* (gleicher Mittelpunkt/Radius, gleiche Schwenkrichtung) über das gewählte Ende bis zur
|
||||
* nächsten GERADEN Schneider-Kante. null bei Geraden (bulge≈0) oder ohne Treffer.
|
||||
*/
|
||||
export function extendBulgeSegment(
|
||||
a: Vec2,
|
||||
b: Vec2,
|
||||
bulge: number,
|
||||
end: "start" | "end",
|
||||
cutters: { pts: Vec2[]; closed: boolean }[],
|
||||
): { point: Vec2; bulge: number } | null {
|
||||
const r = core().k2_extend_bulge_segment(a.x, a.y, b.x, b.y, bulge, end === "end", encChains(cutters));
|
||||
return r.length === 3 ? { point: { x: r[0], y: r[1] }, bulge: r[2] } : null;
|
||||
}
|
||||
|
||||
// ── Tangente-Tangente-Radius ────────────────────────────────────────────────
|
||||
|
||||
/** Ein Tangentialobjekt für `tangentCircleCenters`: Gerade (durch a/b, unendlich gedacht) oder Kreis. */
|
||||
@@ -286,24 +165,7 @@ export function filletCorner(corner: Vec2, p1: Vec2, p2: Vec2, r: number): Fille
|
||||
};
|
||||
}
|
||||
|
||||
/** Ergebnis einer Eck-Fasung. */
|
||||
export interface Chamfer {
|
||||
/** Punkt auf dem ersten Schenkel (corner→p1), im Abstand `distance` vom Eck. */
|
||||
a: Vec2;
|
||||
/** Punkt auf dem zweiten Schenkel (corner→p2), im Abstand `distance` vom Eck. */
|
||||
b: Vec2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gleichabstands-Fase der Ecke bei `corner`; null bei (nahezu) kollinearen Schenkeln oder
|
||||
* wenn `distance` länger als ein Schenkel ist.
|
||||
*/
|
||||
export function chamferCorner(corner: Vec2, p1: Vec2, p2: Vec2, distance: number): Chamfer | null {
|
||||
const c = core().k2_chamfer_corner(corner.x, corner.y, p1.x, p1.y, p2.x, p2.y, distance);
|
||||
return c.length === 4 ? { a: { x: c[0], y: c[1] }, b: { x: c[2], y: c[3] } } : null;
|
||||
}
|
||||
|
||||
// ── Split / Join / Segment löschen / Bruch ──────────────────────────────────
|
||||
// ── Split / Segment löschen ─────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Teilt eine Polylinie an P = lerp(pts[edgeIndex], pts[edgeIndex+1], t). Offen → zwei
|
||||
@@ -347,26 +209,6 @@ export function removeSegmentWithBulge(
|
||||
return { pts: r.pts, closed: false, bulge: r.bulge };
|
||||
}
|
||||
|
||||
/** Position auf einer Kurve: Kantenindex + Parameter (0..1) auf dieser Kante. */
|
||||
export interface CurveHit {
|
||||
edgeIndex: number;
|
||||
t: number;
|
||||
}
|
||||
|
||||
/** Nächste Position auf einer (offenen oder geschlossenen) Punktfolge zu `pt`; null bei < 2 Punkten. */
|
||||
export function nearestOnPolyline(pts: Vec2[], closed: boolean, pt: Vec2): CurveHit | null {
|
||||
const r = core().k2_nearest_on_polyline(encPts(pts), closed, pt.x, pt.y);
|
||||
return r.length === 2 ? { edgeIndex: r[0], t: r[1] } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Entfernt den Abschnitt ZWISCHEN zwei Positionen auf einer OFFENEN Kurve (BREAK,
|
||||
* Klick-Reihenfolge egal); bis zu zwei Reststücke.
|
||||
*/
|
||||
export function breakCurve(pts: Vec2[], hit1: CurveHit, hit2: CurveHit): Vec2[][] {
|
||||
return decPtLists(core().k2_break_curve(encPts(pts), hit1.edgeIndex, hit1.t, hit2.edgeIndex, hit2.t));
|
||||
}
|
||||
|
||||
/**
|
||||
* Teilt das Ziel an allen Schnittpunkten mit `others`. Geschlossen + genau zwei Schnitte →
|
||||
* zwei geschlossene Polygone; offen → Stücke an den Schnittpunkten.
|
||||
@@ -375,13 +217,3 @@ export function splitAtIntersections(targetPts: Vec2[], closed: boolean, others:
|
||||
return decPtLists(core().k2_split_at_intersections(encPts(targetPts), closed, encPtLists(others)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Verschmilzt Polylinien an koinzidenten Endpunkten zu längeren Ketten und trägt je Kette
|
||||
* das bulge-Array mit; muss eine Kette umgedreht werden, kehren sich Reihenfolge UND
|
||||
* Vorzeichen ihrer bulge-Werte um. Schliesst sich eine Kette, wird sie `closed`.
|
||||
*/
|
||||
export function joinChainsWithBulge(
|
||||
polylines: { pts: Vec2[]; closed: boolean; bulge?: number[] }[],
|
||||
): { pts: Vec2[]; closed: boolean; bulge: number[] }[] {
|
||||
return decChains(core().k2_join_chains_with_bulge(encChains(polylines, true)));
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { transformSolid } from "./extrudedSolidSpec";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ExtrudedSolid } from "../model/types";
|
||||
import { extrudedSolidSpec, needsBrepPath } from "./extrudedSolidSpec";
|
||||
@@ -49,21 +48,3 @@ describe("extrudedSolidSpec", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("transformSolid", () => {
|
||||
const body = {
|
||||
id: "b", type: "extrudedSolid", points: [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 1 }, { x: 0, y: 1 }], height: 3,
|
||||
brep: { spec: { kind: "cuboid", min: [0, 0, 0], max: [2, 1, 3] }, origin: { x: 0, y: 0 } },
|
||||
} as never;
|
||||
it("Drehung um 90° wickelt die Spezifikation in transform", () => {
|
||||
const r = transformSolid(body, (p) => ({ x: -p.y, y: p.x }));
|
||||
const sp = r.brep!.spec as { kind: string; m: number[] };
|
||||
expect(sp.kind).toBe("transform");
|
||||
expect(sp.m.slice(0, 2)).toEqual([0, -1]);
|
||||
expect(r.brep!.origin).toEqual(r.points[0]);
|
||||
});
|
||||
it("Skalierung skaliert auch die Hoehe", () => {
|
||||
const r = transformSolid(body, (p) => ({ x: p.x * 2, y: p.y * 2 }), 2);
|
||||
expect(r.height).toBe(6);
|
||||
});
|
||||
});
|
||||
@@ -75,29 +75,3 @@ export function extrudedSolidSpec(solid: ExtrudedSolid, floorZ: number): SolidSp
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wendet eine Grundriss-Abbildung `fn` (Drehung/Skalierung/Spiegelung/Verschiebung, um Z)
|
||||
* auf einen Körper an. B-Rep-Körper erhalten ihre Spezifikation als `transform` um die
|
||||
* bisherige Verschiebung gewickelt (Z bleibt erhalten); der Ursprung wandert auf den
|
||||
* neuen ersten Umrisspunkt, damit die Verschiebung wieder 0 ist.
|
||||
*/
|
||||
export function transformSolid(
|
||||
solid: ExtrudedSolid,
|
||||
fn: (p: { x: number; y: number }) => { x: number; y: number },
|
||||
scale = 1,
|
||||
): ExtrudedSolid {
|
||||
const points = solid.points.map(fn);
|
||||
const circle = solid.circle ? { ...solid.circle, center: fn(solid.circle.center), r: solid.circle.r * scale } : undefined;
|
||||
const base: ExtrudedSolid = { ...solid, points, circle };
|
||||
if (!solid.brep) return base;
|
||||
const o = fn({ x: 0, y: 0 });
|
||||
const ex = fn({ x: 1, y: 0 });
|
||||
const ey = fn({ x: 0, y: 1 });
|
||||
const p0 = solid.points[0];
|
||||
const d: [number, number, number] = [p0 ? p0.x - solid.brep.origin.x : 0, p0 ? p0.y - solid.brep.origin.y : 0, 0];
|
||||
const inner = { kind: "translate", v: d, solid: solid.brep.spec };
|
||||
const m = [ex.x - o.x, ey.x - o.x, 0, o.x, ex.y - o.y, ey.y - o.y, 0, o.y, 0, 0, scale, 0];
|
||||
// z-Skalierung gleich der Grundriss-Skalierung (gleichmässig); Spiegelung/Drehung lassen Z.
|
||||
return { ...base, height: solid.height * scale, brep: { ...solid.brep, spec: { kind: "transform", m, solid: inner }, origin: points[0] ?? solid.brep.origin } };
|
||||
}
|
||||
@@ -58,7 +58,7 @@ import {
|
||||
PEN_FALLBACK_WEIGHT,
|
||||
} from "../model/penSets";
|
||||
import { reorderByIds } from "../model/reorder";
|
||||
import { transformOps } from "../tools/transform";
|
||||
import { transformMutation } from "../tools/transform";
|
||||
import type { CopyMode, TransformOp, TransformSelection } from "../tools/transform";
|
||||
import { uniqueId } from "../tools/types";
|
||||
import { gripPt, type GripRequest } from "../core";
|
||||
@@ -502,7 +502,25 @@ export function createProjectSlice(
|
||||
// rufen ohne Key auf und pushen damit IMMER diskret. Das Projekt ändert sich NUR über Ops: der Kern
|
||||
// prüft (NaN, doppelte ids), wendet an und zeichnet den Undo-Schritt auf ([K4] S3).
|
||||
const setProject = (next: ProjectMutation, coalesceKey?: string) =>
|
||||
set((s) => commitOps(s, next.toOps(s.project), coalesceKey));
|
||||
next.coreReq ? applyCmd(next.coreReq, coalesceKey) : set((s) => commitOps(s, next.toOps(s.project), coalesceKey));
|
||||
|
||||
// Befehl ([K4] S3, `commands.rs`): der Kern rechnet ihn auf dem Dokument und wendet ihn im selben
|
||||
// Aufruf an (`cmdMutation`); Prüfung, Verlauf und Meldungen wie `commitOps`.
|
||||
const applyCmd = (req: object, coalesceKey?: string) =>
|
||||
set((s) => {
|
||||
const doc = storeDocument(s.project);
|
||||
const res = doc.commitCmd(s.project, req, coalesceKey, Date.now());
|
||||
if ("problems" in res) {
|
||||
const problems = res.problems;
|
||||
console.warn("Projektänderung verworfen:", problems);
|
||||
queueMicrotask(() => get().notify(`${t("project.change.rejected")} ${problems[0]}`, "error"));
|
||||
return {};
|
||||
}
|
||||
if (res.ops.length === 0) return {};
|
||||
opLog.push(res.ops);
|
||||
if (opLog.length > OP_LOG_LIMIT) opLog.shift();
|
||||
return { project: res.project, ...historyPatch(doc) };
|
||||
});
|
||||
|
||||
// Änderung direkt als Ops (ohne Differenz), s. `ProjectSlice.applyChange`.
|
||||
const applyChange = (
|
||||
@@ -1121,8 +1139,7 @@ export function createProjectSlice(
|
||||
resizeElement: (kind, id, w, h, anchor) => applyGrip({ op: "resize", kind, id, w, h, fx: anchor.fx, fy: anchor.fy }),
|
||||
|
||||
// ── Transformation ─────────────────────────────────────────────────────
|
||||
commitTransformOn: (sel, op, points, copyMode, count) =>
|
||||
applyChange((p) => transformOps(p, sel, op, points, copyMode, count)),
|
||||
commitTransformOn: (sel, op, points, copyMode, count) => setProject(transformMutation(sel, op, points, copyMode, count)),
|
||||
|
||||
// ── Wand-Attribute ─────────────────────────────────────────────────────
|
||||
updateWall: (id, patch, coalesceKey) => applyChange((p) => patchItem(p, "walls", id, patch), coalesceKey),
|
||||
|
||||
@@ -12,9 +12,7 @@ import { wallTypeThickness } from "../model/types";
|
||||
import { drawingVertices } from "../core";
|
||||
import { gripDrawingIdsFor } from "./gripLimits";
|
||||
import { openEdges, polylineEdgeGrips, ringEdges } from "../core";
|
||||
import { areaMovePreview } from "../tools/transform";
|
||||
import { mvGeom } from "../core";
|
||||
import { drawingPreviewShapes } from "../tools/drawingPreview";
|
||||
import { areaMovePreview, drawingMovePreview } from "../tools/transform";
|
||||
import type { DraftShape, SnapResult, SnapSettings, ToolDraft, ToolMods } from "../tools/types";
|
||||
import { applyAngleConstraint, computeSnap } from "../tools/snapping";
|
||||
import { useCommandTabShortcut } from "./useKeyboardShortcuts";
|
||||
@@ -993,8 +991,7 @@ export function useGripEditing(opts: {
|
||||
const d = deferrableDrawing(pend.drawingId);
|
||||
if (!d) return [];
|
||||
const { x: tx, y: ty } = pend.total;
|
||||
const moved = { ...d, geom: mvGeom(d.geom, (q: Vec2) => ({ x: q.x + tx, y: q.y + ty })) };
|
||||
return drawingPreviewShapes(project, moved, scaleDenominator);
|
||||
return drawingMovePreview(project, d.id, { x: tx, y: ty }, scaleDenominator);
|
||||
};
|
||||
|
||||
/** Vorschau eines aufgeschobenen Kanten-Zugs (beide Kanten-Ecken um das Delta versetzt). */
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// Brücke der Befehle/Werkzeuge zum Kern ([K4] S3, `src-tauri/core/src/commands.rs`): Vorschau-Formen
|
||||
// aus flachen Puffern lesen und Abfragen zwischen den Schritten (Treffer, Vorschau) stellen. Die
|
||||
// Zustandsautomaten bleiben in den Befehlen; gerechnet wird im Kern.
|
||||
|
||||
import type { Project, Vec2 } from "../model/types";
|
||||
import type { DraftShape } from "./types";
|
||||
import { documentFor } from "../core/document";
|
||||
|
||||
/** Punkt als Paar (Anfragen an den Kern). */
|
||||
export const pair = (p: Vec2): [number, number] => [p.x, p.y];
|
||||
|
||||
/**
|
||||
* Vorschau-Puffer des Kerns → Formen: je Form `[art, n, x0, y0, …]`, art 0 = Linie (n = 2),
|
||||
* 1 = geschlossenes Polygon, 2 = offener Linienzug.
|
||||
*/
|
||||
export function decodeShapes(f: ArrayLike<number>): DraftShape[] {
|
||||
const out: DraftShape[] = [];
|
||||
let i = 0;
|
||||
while (i + 1 < f.length) {
|
||||
const kind = f[i];
|
||||
const n = f[i + 1];
|
||||
i += 2;
|
||||
const pts: Vec2[] = new Array(n);
|
||||
for (let k = 0; k < n; k++, i += 2) pts[k] = { x: f[i], y: f[i + 1] };
|
||||
out.push(kind === 0 ? { kind: "line", a: pts[0], b: pts[1] } : { kind: "poly", pts, closed: kind === 1 });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Abfrage eines Befehls zwischen den Schritten (`cmd_edit::query`), auf dem Dokument von `project`. */
|
||||
export function cmdQuery<T>(project: Project, req: { q: string } & Record<string, unknown>): T {
|
||||
return documentFor(project).cmdQuery<T>(req);
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Drawing2D, Project } from "../model/types";
|
||||
import { drawingPreviewShapes, primitivesToDraftShapes } from "./drawingPreview";
|
||||
import type { Primitive } from "../plan/generatePlan";
|
||||
|
||||
const project = { lineStyles: [], hatches: [], layers: [], drawings2d: [], blocks: [] } as unknown as Project;
|
||||
const base = { id: "d", levelId: "L", categoryCode: "10" } as unknown as Drawing2D;
|
||||
|
||||
describe("Verschiebe-Vorschau für alle 2D-Formen", () => {
|
||||
it("Kreis → Liniensegmente rundum", () => {
|
||||
const s = drawingPreviewShapes(project, { ...base, geom: { shape: "circle", center: { x: 0, y: 0 }, r: 1 } } as Drawing2D);
|
||||
expect(s.length).toBeGreaterThan(10);
|
||||
expect(s.every((x) => x.kind === "line")).toBe(true);
|
||||
});
|
||||
it("Polylinie mit Bogen-Segment → Bogen abgetastet (nicht nur die Sehne)", () => {
|
||||
const s = drawingPreviewShapes(project, {
|
||||
...base,
|
||||
geom: { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }], closed: false, bulge: [0.5] },
|
||||
} as Drawing2D);
|
||||
expect(s.length).toBeGreaterThan(3);
|
||||
});
|
||||
it("Text → Rahmen-Polygon", () => {
|
||||
const p = { kind: "drawingText", at: { x: 0, y: 0 }, text: "Hallo", heightM: 1, angle: 0, color: "#000" } as unknown as Primitive;
|
||||
const s = primitivesToDraftShapes([p]);
|
||||
expect(s).toHaveLength(1);
|
||||
expect(s[0].kind).toBe("poly");
|
||||
});
|
||||
});
|
||||
@@ -1,89 +0,0 @@
|
||||
// Vorschau-Formen eines (transformierten) 2D-Elements für Verschieben/Kopieren/
|
||||
// Drehen/Spiegeln/Skalieren: das Element läuft durch DIESELBE Primitiv-Erzeugung
|
||||
// wie der Plan (Kern, `drawingPrimitives`), die Primitive werden in einfache Vorschau-Formen
|
||||
// (Linien/Polygone) übersetzt. So hat JEDE Form eine Vorschau — Kreis, Bogen,
|
||||
// Spline, Text, Bemassung, Kote, Block, Polylinien-Bögen … (vorher nur Linie/
|
||||
// Polylinie/Rechteck/Bild, alles andere war beim Verschieben unsichtbar).
|
||||
|
||||
import type { Drawing2D, Project, Vec2 } from "../model/types";
|
||||
import type { Primitive } from "../core";
|
||||
import { drawingPrimitives } from "../core";
|
||||
import { textFrameCorners } from "../text/textFrame";
|
||||
import type { DraftShape } from "./types";
|
||||
|
||||
/** Obergrenze je Element (Schraffur-Muster u. Ä. können sehr viele Linien erzeugen). */
|
||||
const MAX_SHAPES_PER_ITEM = 4000;
|
||||
|
||||
function ringLines(center: Vec2, r: number, a0: number, a1: number, out: DraftShape[]): void {
|
||||
const sweep = a1 - a0;
|
||||
const n = Math.max(8, Math.ceil((Math.abs(sweep) / (Math.PI * 2)) * 48));
|
||||
let prev = { x: center.x + r * Math.cos(a0), y: center.y + r * Math.sin(a0) };
|
||||
for (let i = 1; i <= n; i++) {
|
||||
const a = a0 + (sweep * i) / n;
|
||||
const p = { x: center.x + r * Math.cos(a), y: center.y + r * Math.sin(a) };
|
||||
out.push({ kind: "line", a: prev, b: p });
|
||||
prev = p;
|
||||
}
|
||||
}
|
||||
|
||||
/** Plan-Primitive → Vorschau-Formen. */
|
||||
export function primitivesToDraftShapes(prims: readonly Primitive[]): DraftShape[] {
|
||||
const out: DraftShape[] = [];
|
||||
for (const p of prims) {
|
||||
if (out.length >= MAX_SHAPES_PER_ITEM) break;
|
||||
switch (p.kind) {
|
||||
case "line":
|
||||
out.push({ kind: "line", a: p.a, b: p.b });
|
||||
break;
|
||||
case "polygon":
|
||||
if (p.pts.length >= 2) out.push({ kind: "poly", pts: p.pts, closed: true });
|
||||
break;
|
||||
case "drawingCircle":
|
||||
ringLines(p.center, p.r, 0, Math.PI * 2, out);
|
||||
break;
|
||||
case "drawingArc": {
|
||||
const TAU = Math.PI * 2;
|
||||
const sweep = (((p.a1 - p.a0) % TAU) + TAU) % TAU || TAU;
|
||||
ringLines(p.center, p.r, p.a0, p.a0 + sweep, out);
|
||||
break;
|
||||
}
|
||||
case "arc": {
|
||||
const a0 = Math.atan2(p.from.y - p.center.y, p.from.x - p.center.x);
|
||||
const a1 = Math.atan2(p.to.y - p.center.y, p.to.x - p.center.x);
|
||||
let d = a1 - a0;
|
||||
while (d <= -Math.PI) d += 2 * Math.PI;
|
||||
while (d > Math.PI) d -= 2 * Math.PI;
|
||||
const r = Math.hypot(p.from.x - p.center.x, p.from.y - p.center.y);
|
||||
ringLines(p.center, r, a0, a0 + d, out);
|
||||
break;
|
||||
}
|
||||
case "drawingText":
|
||||
out.push({ kind: "poly", pts: textFrameCorners(p), closed: true });
|
||||
break;
|
||||
case "drawingTextPath":
|
||||
for (let i = 0; i + 1 < p.pathPts.length; i++) out.push({ kind: "line", a: p.pathPts[i], b: p.pathPts[i + 1] });
|
||||
break;
|
||||
case "drawingImage":
|
||||
out.push({
|
||||
kind: "poly",
|
||||
pts: [p.min, { x: p.max.x, y: p.min.y }, p.max, { x: p.min.x, y: p.max.y }],
|
||||
closed: true,
|
||||
});
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Vorschau-Formen eines 2D-Elements (Geometrie bereits transformiert). */
|
||||
export function drawingPreviewShapes(project: Project, d: Drawing2D, scaleDenominator?: number): DraftShape[] {
|
||||
let prims: Primitive[];
|
||||
try {
|
||||
prims = drawingPrimitives(project, d, scaleDenominator);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return primitivesToDraftShapes(prims);
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { commitTransform, rotateGizmoShapes } from "./transform";
|
||||
import { commitTransform, rotateGizmoShapes, transformPreview } from "./transform";
|
||||
import type { TransformSelection } from "./transform";
|
||||
import type { Ceiling, Drawing2D, ExtrudedSolid, Project, Roof, Room, Stair } from "../model/types";
|
||||
|
||||
@@ -469,3 +469,45 @@ describe("rotateGizmoShapes — Dreh-Darstellung (Referenz-/Winkel-Strahl + Radi
|
||||
expect(rotateGizmoShapes({ x: 1, y: 1 }, { x: 1, y: 1 }, { x: 5, y: 5 })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("transformPreview — Vorschau für alle 2D-Formen (Kern, Plan-Primitive)", () => {
|
||||
const sel = (id: string): TransformSelection => ({ wallIds: [], drawingId: id });
|
||||
const at = (geom: Drawing2D["geom"]) => project([{ ...line("d", 0), geom }]);
|
||||
const move = [{ x: 0, y: 0 }, { x: 1, y: 0 }];
|
||||
it("Kreis → Liniensegmente rundum", () => {
|
||||
const s = transformPreview(at({ shape: "circle", center: { x: 0, y: 0 }, r: 1 }), sel("d"), "move", move, "move", 1);
|
||||
expect(s.length).toBeGreaterThan(10);
|
||||
expect(s.every((x) => x.kind === "line")).toBe(true);
|
||||
});
|
||||
it("Polylinie mit Bogen-Segment → Bogen abgetastet (nicht nur die Sehne)", () => {
|
||||
const g = { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }], closed: false, bulge: [0.5] } as Drawing2D["geom"];
|
||||
expect(transformPreview(at(g), sel("d"), "move", move, "move", 1).length).toBeGreaterThan(3);
|
||||
});
|
||||
it("Text → Rahmen-Polygon, verschoben", () => {
|
||||
const s = transformPreview(at({ shape: "text", at: { x: 0, y: 0 }, text: "Hallo", height: 1, angle: 0 }), sel("d"), "move", move, "move", 1);
|
||||
expect(s).toHaveLength(1);
|
||||
expect(s[0].kind).toBe("poly");
|
||||
if (s[0].kind === "poly") expect(s[0].pts[0].x).toBeCloseTo(1, 9);
|
||||
});
|
||||
});
|
||||
|
||||
describe("commitTransform — B-Rep-Körper (Spezifikation als transform gewickelt)", () => {
|
||||
const body = {
|
||||
id: "b", type: "extrudedSolid", points: [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 1 }, { x: 0, y: 1 }], height: 3,
|
||||
brep: { spec: { kind: "cuboid", min: [0, 0, 0], max: [2, 1, 3] }, origin: { x: 0, y: 0 } },
|
||||
} as unknown as ExtrudedSolid;
|
||||
const p = { ...project([]), extrudedSolids: [body] } as Project;
|
||||
const sel: TransformSelection = { wallIds: [], drawingId: null, extrudedSolidId: "b" };
|
||||
it("Drehung um 90°", () => {
|
||||
const r = commitTransform(p, sel, "rotate", [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 0, y: 1 }], "move", 1).extrudedSolids![0];
|
||||
const sp = r.brep!.spec as { kind: string; m: number[] };
|
||||
expect(sp.kind).toBe("transform");
|
||||
expect(sp.m[0]).toBeCloseTo(0, 12);
|
||||
expect(sp.m[1]).toBeCloseTo(-1, 12);
|
||||
expect(r.brep!.origin).toEqual(r.points[0]);
|
||||
});
|
||||
it("Skalierung skaliert auch die Höhe", () => {
|
||||
const r = commitTransform(p, sel, "scale", [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 2, y: 0 }], "move", 1).extrudedSolids![0];
|
||||
expect(r.height).toBe(6);
|
||||
});
|
||||
});
|
||||
+62
-478
@@ -6,36 +6,19 @@
|
||||
// O array — Original bleibt + N Kopien, je um den vollen Schritt versetzt.
|
||||
// P distribute — Original bleibt + N Kopien gleichmäßig zwischen Original und Ziel.
|
||||
//
|
||||
// Bezeichner englisch, UI-Text via t() (CONVENTIONS.md). Reine Funktionen + Geometrie;
|
||||
// die App hält den State und wendet die Ops aus `transformOps` an ([K4] S3).
|
||||
// Die Rechnung (Abbildung, alle Elementarten, Kopien, Vorschau-Formen) steht im Kern
|
||||
// (`src-tauri/core/src/cmd_transform.rs`, [K4] S3); hier die Typen, die Fassade und das Dreh-Gizmo.
|
||||
|
||||
import { transformSolid } from "../core";
|
||||
import type {
|
||||
Ceiling,
|
||||
Column,
|
||||
Drawing2D,
|
||||
Drawing2DGeom,
|
||||
ExtrudedSolid,
|
||||
Project,
|
||||
Roof,
|
||||
Room,
|
||||
Stair,
|
||||
Vec2,
|
||||
Wall,
|
||||
} from "../model/types";
|
||||
import { wallTypeThickness } from "../model/types";
|
||||
import { wallCorners } from "../model/geometry";
|
||||
import { columnFootprint } from "../core";
|
||||
import { stairOutline } from "../core";
|
||||
import type { Project, Vec2 } from "../model/types";
|
||||
import type { DraftShape } from "./types";
|
||||
import { drawingPreviewShapes } from "./drawingPreview";
|
||||
import { mvGeom, reversesOrientation, scaleFactor, scaleGeom } from "../core";
|
||||
import { uniqueId } from "./types";
|
||||
import { uniqueStamp } from "./types";
|
||||
import { decodeShapes, pair } from "./coreCmd";
|
||||
import type { CommandSelection } from "../commands/types";
|
||||
import { applyOps } from "../core";
|
||||
import type { CoreOp } from "../core";
|
||||
import { addItems, opsMutation, patchItems } from "../core";
|
||||
import type { ProjectMutation } from "../core";
|
||||
import type { CoreOp, ProjectMutation } from "../core";
|
||||
import { cmdMutation, documentFor } from "../core/document";
|
||||
import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension";
|
||||
import { contentFontBaselineFromTop, TEXT_LINE_HEIGHT_MULT } from "../text/fontMetrics";
|
||||
|
||||
export type TransformOp = "move" | "rotate" | "mirror" | "scale";
|
||||
export type CopyMode = "move" | "copy" | "array" | "distribute"; // U / I / O / P
|
||||
@@ -101,344 +84,61 @@ export function hasTransformSelection(sel: CommandSelection): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/** Vereinigt `drawingId`/`drawingIds` zu einer eindeutigen ID-Menge (dedupliziert). */
|
||||
function drawingIdSet(sel: TransformSelection): Set<string> {
|
||||
const ids = new Set(sel.drawingIds ?? []);
|
||||
if (sel.drawingId) ids.add(sel.drawingId);
|
||||
return ids;
|
||||
}
|
||||
|
||||
/** Wie viele Klickpunkte die Operation braucht (Drehen = 3, sonst 2). */
|
||||
export const requiredPoints = (op: TransformOp): number => (op === "rotate" ? 3 : 2);
|
||||
|
||||
/**
|
||||
* Punkt-Transformation einer Operation bei „Anteil" t (0..1 oder Vielfache):
|
||||
* • move — Verschiebung um t·Vektor (pts[0]→pts[1]).
|
||||
* • rotate — Drehung um pts[0] um t·(Winkel(pts[2]) − Winkel(pts[1])).
|
||||
* • mirror — Spiegelung an der Achse pts[0]→pts[1] (t wird ignoriert).
|
||||
*/
|
||||
export function transformFn(op: TransformOp, pts: Vec2[], t: number): (p: Vec2) => Vec2 {
|
||||
if (op === "move") {
|
||||
const vx = (pts[1].x - pts[0].x) * t;
|
||||
const vy = (pts[1].y - pts[0].y) * t;
|
||||
return (p) => ({ x: p.x + vx, y: p.y + vy });
|
||||
}
|
||||
if (op === "rotate") {
|
||||
const c = pts[0];
|
||||
const a0 = Math.atan2(pts[1].y - c.y, pts[1].x - c.x);
|
||||
const a1 = Math.atan2(pts[2].y - c.y, pts[2].x - c.x);
|
||||
const ang = (a1 - a0) * t;
|
||||
const cos = Math.cos(ang), sin = Math.sin(ang);
|
||||
return (p) => {
|
||||
const dx = p.x - c.x, dy = p.y - c.y;
|
||||
return { x: c.x + dx * cos - dy * sin, y: c.y + dx * sin + dy * cos };
|
||||
};
|
||||
}
|
||||
if (op === "scale") {
|
||||
// Gleichmässige Skalierung um pts[0]; der Faktor ist das Längenverhältnis
|
||||
// Referenz→Ziel (getippter Faktor wird vom Befehl in solche Punkte
|
||||
// übersetzt). `t` interpoliert für die Vorschau/Reihen-Kopien.
|
||||
const c = pts[0];
|
||||
const f = scaleFactor(pts, t);
|
||||
return (p) => ({ x: c.x + (p.x - c.x) * f, y: c.y + (p.y - c.y) * f });
|
||||
}
|
||||
// mirror: Spiegelung an der Geraden pts[0]→pts[1].
|
||||
const a = pts[0], b = pts[1];
|
||||
const dx = b.x - a.x, dy = b.y - a.y;
|
||||
const len2 = dx * dx + dy * dy || 1;
|
||||
return (p) => {
|
||||
// Projektion von p auf die Achse, dann gespiegelt.
|
||||
const tt = ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2;
|
||||
const fx = a.x + dx * tt, fy = a.y + dy * tt;
|
||||
return { x: 2 * fx - p.x, y: 2 * fy - p.y };
|
||||
const pairs = (pts: readonly Vec2[]): [number, number][] => pts.map(pair);
|
||||
|
||||
/** Vorschau-Formen einer Transformation aus dem Kern (Zeichnungen über die Plan-Primitive). */
|
||||
function previewShapes(
|
||||
project: Project,
|
||||
sel: TransformSelection,
|
||||
op: TransformOp,
|
||||
pts: readonly Vec2[],
|
||||
mode: CopyMode,
|
||||
count: number,
|
||||
opts: { ignoreLock?: boolean; scale?: number } = {},
|
||||
): DraftShape[] {
|
||||
const req = {
|
||||
cmd: "transform",
|
||||
sel,
|
||||
op,
|
||||
pts: pairs(pts),
|
||||
mode,
|
||||
count,
|
||||
ignoreLock: !!opts.ignoreLock,
|
||||
scale: opts.scale ?? DEFAULT_SCALE_DENOMINATOR,
|
||||
top: contentFontBaselineFromTop(TEXT_LINE_HEIGHT_MULT),
|
||||
};
|
||||
return decodeShapes(documentFor(project).cmdPreview(req));
|
||||
}
|
||||
|
||||
/**
|
||||
* Die „Anteile" t der KOPIEN (ohne Original) je Modus. Beim Spiegeln ergeben
|
||||
* Array/Verteilen keine Reihe (Spiegelung ist selbstinvers) → genau eine Kopie.
|
||||
*/
|
||||
export function copyTs(op: TransformOp, mode: CopyMode, count: number): number[] {
|
||||
if (mode === "move") return [];
|
||||
if (op === "mirror") return [1]; // copy/array/distribute → eine gespiegelte Kopie
|
||||
if (mode === "copy") return [1];
|
||||
const n = Math.max(1, Math.floor(count));
|
||||
if (mode === "array") return Array.from({ length: n }, (_, k) => k + 1);
|
||||
// distribute: n Kopien gleichmäßig zwischen Original (0) und Ziel (1).
|
||||
return Array.from({ length: n }, (_, k) => (k + 1) / n);
|
||||
}
|
||||
|
||||
/** Wird beim Modus „move" (U) das Original selbst transformiert? */
|
||||
export const movesOriginal = (mode: CopyMode): boolean => mode === "move";
|
||||
|
||||
// ── Geometrie einer Auswahl ─────────────────────────────────────────────────
|
||||
|
||||
interface SelItem {
|
||||
kind: "wall";
|
||||
wall: Wall;
|
||||
}
|
||||
interface SelDrawingItem {
|
||||
kind: "drawing";
|
||||
drawing: Drawing2D;
|
||||
}
|
||||
interface SelExtrudedItem {
|
||||
kind: "extrudedSolid";
|
||||
solid: ExtrudedSolid;
|
||||
}
|
||||
interface SelColumnItem {
|
||||
kind: "column";
|
||||
column: Column;
|
||||
}
|
||||
interface SelCeilingItem {
|
||||
kind: "ceiling";
|
||||
ceiling: Ceiling;
|
||||
}
|
||||
interface SelRoofItem {
|
||||
kind: "roof";
|
||||
roof: Roof;
|
||||
}
|
||||
interface SelStairItem {
|
||||
kind: "stair";
|
||||
stair: Stair;
|
||||
}
|
||||
interface SelRoomItem {
|
||||
kind: "room";
|
||||
room: Room;
|
||||
}
|
||||
type AnyItem =
|
||||
| SelItem
|
||||
| SelDrawingItem
|
||||
| SelExtrudedItem
|
||||
| SelColumnItem
|
||||
| SelCeilingItem
|
||||
| SelRoofItem
|
||||
| SelStairItem
|
||||
| SelRoomItem;
|
||||
|
||||
// Dach: s. Doku bei TransformSelection.roofIds — Rotate/Mirror ausgenommen
|
||||
// (Umriss-Achsen-Invariante). EINZIGE Stelle, die das entscheidet — sowohl
|
||||
// `gatherItems` als auch der „Original bewegen"-Zweig in `commitTransform`
|
||||
// (der NICHT über `items` läuft, s. dort) müssen dieselbe Funktion befragen,
|
||||
// sonst bricht die Ausnahme an einer der beiden Stellen unbemerkt wieder.
|
||||
function roofTransformAllowed(op: TransformOp): boolean {
|
||||
return op !== "rotate" && op !== "mirror";
|
||||
}
|
||||
|
||||
function gatherItems(project: Project, sel: TransformSelection, op: TransformOp): AnyItem[] {
|
||||
const items: AnyItem[] = [];
|
||||
// Objekt-Sperre (`locked`, s. state/objectLock.ts): gesperrte Elemente
|
||||
// bleiben anwählbar, aber move/copy/mirror/rotate/scale/array lassen sie
|
||||
// unangetastet — dieselbe Semantik wie beim Griff-Ziehen (moveGrip/
|
||||
// moveElementBy in projectSlice.ts).
|
||||
const ids = new Set(sel.wallIds);
|
||||
for (const w of project.walls) if (ids.has(w.id) && !w.locked) items.push({ kind: "wall", wall: w });
|
||||
const drawIds = drawingIdSet(sel);
|
||||
for (const d of project.drawings2d)
|
||||
if (drawIds.has(d.id) && !d.locked) items.push({ kind: "drawing", drawing: d });
|
||||
if (sel.extrudedSolidId) {
|
||||
const s = (project.extrudedSolids ?? []).find((x) => x.id === sel.extrudedSolidId);
|
||||
if (s) items.push({ kind: "extrudedSolid", solid: s });
|
||||
}
|
||||
if (sel.columnId) {
|
||||
const c = (project.columns ?? []).find((x) => x.id === sel.columnId);
|
||||
if (c && !c.locked) items.push({ kind: "column", column: c });
|
||||
}
|
||||
const ceilingIds = new Set(sel.ceilingIds ?? []);
|
||||
for (const c of project.ceilings ?? [])
|
||||
if (ceilingIds.has(c.id) && !c.locked) items.push({ kind: "ceiling", ceiling: c });
|
||||
if (roofTransformAllowed(op)) {
|
||||
const roofIds = new Set(sel.roofIds ?? []);
|
||||
for (const r of project.roofs ?? [])
|
||||
if (roofIds.has(r.id) && !r.locked) items.push({ kind: "roof", roof: r });
|
||||
}
|
||||
const stairIds = new Set(sel.stairIds ?? []);
|
||||
for (const s of project.stairs ?? [])
|
||||
if (stairIds.has(s.id) && !s.locked) items.push({ kind: "stair", stair: s });
|
||||
const roomIds = new Set(sel.roomIds ?? []);
|
||||
for (const r of project.rooms ?? [])
|
||||
if (roomIds.has(r.id) && !r.locked) items.push({ kind: "room", room: r });
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transformiert eine Stütze unter einer affinen Punkt-Abbildung `fn`
|
||||
* (Verschiebung/Drehung/Spiegelung): der Einfügepunkt wandert mit; die Profil-
|
||||
* Drehung folgt der Abbildung, indem ein Richtungsvektor (Länge 1 unter dem
|
||||
* aktuellen Winkel) mit-transformiert und der neue Winkel daraus gemessen wird
|
||||
* — das ergibt für alle drei Operationen die korrekte neue Ausrichtung.
|
||||
*/
|
||||
function mvColumn(col: Column, fn: (p: Vec2) => Vec2): Column {
|
||||
const base = col.position;
|
||||
const rot = col.rotation ?? 0;
|
||||
const tip = { x: base.x + Math.cos(rot), y: base.y + Math.sin(rot) };
|
||||
const nb = fn(base);
|
||||
const nt = fn(tip);
|
||||
return { ...col, position: nb, rotation: Math.atan2(nt.y - nb.y, nt.x - nb.x) };
|
||||
}
|
||||
|
||||
/** Bildet Umriss + Aussparungen einer Decke unter `fn` ab. */
|
||||
function mvCeiling(c: Ceiling, fn: (p: Vec2) => Vec2): Ceiling {
|
||||
return {
|
||||
...c,
|
||||
outline: c.outline.map(fn),
|
||||
...(c.openings ? { openings: c.openings.map((hole) => hole.map(fn)) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Bildet den Umriss eines Dachs unter `fn` ab. NUR für Move/Scale aufgerufen
|
||||
* (s. `TransformSelection.roofIds`) — beide erhalten die Rechteck-/Achsen-
|
||||
* Invariante des Umrisses, daher genügt reines Punkte-Mapping.
|
||||
*/
|
||||
function mvRoof(r: Roof, fn: (p: Vec2) => Vec2): Roof {
|
||||
return { ...r, outline: r.outline.map(fn) };
|
||||
}
|
||||
|
||||
/** Bildet Umriss + Stempel-Anker eines Raums unter `fn` ab. */
|
||||
function mvRoom(r: Room, fn: (p: Vec2) => Vec2): Room {
|
||||
return {
|
||||
...r,
|
||||
boundary: r.boundary.map(fn),
|
||||
...(r.stampAnchor ? { stampAnchor: fn(r.stampAnchor) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Transformiert eine Treppe unter `fn` (Skalierungsfaktor `f`, wie bei
|
||||
* {@link scaleGeom}): Antritt (+ Wendel-Zentrum) wandert mit; die Laufrichtung
|
||||
* folgt wie bei {@link mvColumn} über einen mit-transformierten Richtungs-
|
||||
* punkt. `turn` (L-Treppe) und `sweep` (Wendel) sind umlaufsinn-abhängig und
|
||||
* kippen daher unter einer Spiegelung ({@link reversesOrientation}), bleiben
|
||||
* aber unter Drehung/Verschiebung/Skalierung unverändert. Lauflänge/-breite/
|
||||
* Radius skalieren mit `f`; `totalRise` (eine Gebäudehöhe, Z) bleibt unberührt.
|
||||
*/
|
||||
function mvStair(s: Stair, fn: (p: Vec2) => Vec2, f: number): Stair {
|
||||
const start = fn(s.start);
|
||||
const tip = fn({ x: s.start.x + s.dir.x, y: s.start.y + s.dir.y });
|
||||
const dx = tip.x - start.x, dy = tip.y - start.y;
|
||||
const len = Math.hypot(dx, dy) || 1;
|
||||
const flips = reversesOrientation(fn);
|
||||
return {
|
||||
...s,
|
||||
start,
|
||||
dir: { x: dx / len, y: dy / len },
|
||||
runLength: s.runLength * f,
|
||||
width: s.width * f,
|
||||
...(s.run2Length !== undefined ? { run2Length: s.run2Length * f } : {}),
|
||||
...(s.turn !== undefined ? { turn: (flips ? -s.turn : s.turn) as 1 | -1 } : {}),
|
||||
...(s.center ? { center: fn(s.center) } : {}),
|
||||
...(s.radius !== undefined ? { radius: s.radius * f } : {}),
|
||||
...(s.sweep !== undefined ? { sweep: flips ? -s.sweep : s.sweep } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Vorschau-Umriss einer Treppe unter `fn`. Gerade/L nutzen den echten
|
||||
* `stairOutline`-Kern; Wendel liefert dort Bogensegmente statt eines
|
||||
* Polygons — für die Live-Vorschau genügt ein grob abgetasteter Innen-/
|
||||
* Aussenring (kein Anspruch auf die exakte Stufenkontur).
|
||||
*/
|
||||
function stairPreviewShapes(stair: Stair, fn: (p: Vec2) => Vec2): DraftShape[] {
|
||||
if (stair.shape !== "spiral") {
|
||||
const { polygon } = stairOutline(stair, 0);
|
||||
return polygon ? [{ kind: "poly", pts: polygon.map(fn), closed: true }] : [];
|
||||
}
|
||||
const center = stair.center ?? stair.start;
|
||||
const rIn = Math.max(0, stair.radius ?? 0);
|
||||
const rOut = rIn + stair.width;
|
||||
const sweepDeg = stair.sweep ?? 360;
|
||||
const a0 = Math.atan2(stair.start.y - center.y, stair.start.x - center.x);
|
||||
const steps = Math.max(4, Math.round(Math.abs(sweepDeg) / 15));
|
||||
const outer: Vec2[] = [], inner: Vec2[] = [];
|
||||
for (let i = 0; i <= steps; i++) {
|
||||
const a = a0 + ((sweepDeg * Math.PI) / 180) * (i / steps);
|
||||
outer.push(fn({ x: center.x + Math.cos(a) * rOut, y: center.y + Math.sin(a) * rOut }));
|
||||
inner.push(fn({ x: center.x + Math.cos(a) * rIn, y: center.y + Math.sin(a) * rIn }));
|
||||
}
|
||||
return [{ kind: "poly", pts: [...outer, ...inner.reverse()], closed: true }];
|
||||
}
|
||||
|
||||
/** Vorschau-Formen für ein Element unter der Punkt-Transformation `fn`. */
|
||||
/** Vorschau eines einzelnen Flächen-Elements (Decke/Raum/Treppe) unter einer Verschiebung. */
|
||||
/** Vorschau eines einzelnen Elements unter einer Verschiebung (Griff-Vorschau; Sperre ohne Wirkung). */
|
||||
export function areaMovePreview(
|
||||
project: Project,
|
||||
kind: "ceiling" | "room" | "stair" | "wall",
|
||||
id: string,
|
||||
delta: Vec2,
|
||||
): DraftShape[] {
|
||||
const fn = (p: Vec2): Vec2 => ({ x: p.x + delta.x, y: p.y + delta.y });
|
||||
if (kind === "wall") {
|
||||
const w = project.walls.find((x) => x.id === id);
|
||||
return w ? itemPreview(project, { kind: "wall", wall: w } as AnyItem, fn) : [];
|
||||
}
|
||||
if (kind === "ceiling") {
|
||||
const c = (project.ceilings ?? []).find((x) => x.id === id);
|
||||
return c ? itemPreview(project, { kind: "ceiling", ceiling: c } as AnyItem, fn) : [];
|
||||
}
|
||||
if (kind === "room") {
|
||||
const r = (project.rooms ?? []).find((x) => x.id === id);
|
||||
return r ? itemPreview(project, { kind: "room", room: r } as AnyItem, fn) : [];
|
||||
}
|
||||
const st = (project.stairs ?? []).find((x) => x.id === id);
|
||||
return st ? itemPreview(project, { kind: "stair", stair: st } as AnyItem, fn) : [];
|
||||
const sel: TransformSelection = { wallIds: kind === "wall" ? [id] : [], drawingId: null };
|
||||
if (kind === "ceiling") sel.ceilingIds = [id];
|
||||
if (kind === "room") sel.roomIds = [id];
|
||||
if (kind === "stair") sel.stairIds = [id];
|
||||
return previewShapes(project, sel, "move", [{ x: 0, y: 0 }, delta], "move", 1, { ignoreLock: true });
|
||||
}
|
||||
|
||||
function itemPreview(project: Project, item: AnyItem, fn: (p: Vec2) => Vec2): DraftShape[] {
|
||||
if (item.kind === "wall") {
|
||||
const w = item.wall;
|
||||
const wt = project.wallTypes.find((t) => t.id === w.wallTypeId);
|
||||
const th = wt ? wallTypeThickness(wt) : 0.2;
|
||||
const a = fn(w.start), b = fn(w.end);
|
||||
return [
|
||||
{ kind: "poly", pts: wallCorners(a, b, th), closed: true },
|
||||
{ kind: "line", a, b },
|
||||
];
|
||||
}
|
||||
if (item.kind === "extrudedSolid") {
|
||||
return [{ kind: "poly", pts: item.solid.points.map(fn), closed: true }];
|
||||
}
|
||||
if (item.kind === "column") {
|
||||
return [{ kind: "poly", pts: columnFootprint(item.column).map(fn), closed: true }];
|
||||
}
|
||||
if (item.kind === "ceiling") {
|
||||
return [{ kind: "poly", pts: item.ceiling.outline.map(fn), closed: true }];
|
||||
}
|
||||
if (item.kind === "roof") {
|
||||
return [{ kind: "poly", pts: item.roof.outline.map(fn), closed: true }];
|
||||
}
|
||||
if (item.kind === "room") {
|
||||
return [{ kind: "poly", pts: item.room.boundary.map(fn), closed: true }];
|
||||
}
|
||||
if (item.kind === "stair") {
|
||||
return stairPreviewShapes(item.stair, fn);
|
||||
}
|
||||
const g = mvGeom(item.drawing.geom, fn);
|
||||
// Allgemein: dieselbe Primitiv-Erzeugung wie im Plan (alle Formen, inkl. Bögen
|
||||
// in Polylinien, Text, Bemassung, Kreis …). Fallback unten nur, falls daraus
|
||||
// nichts entsteht.
|
||||
const generic = drawingPreviewShapes(project, { ...item.drawing, geom: g });
|
||||
if (generic.length) return generic;
|
||||
switch (g.shape) {
|
||||
case "line":
|
||||
return [{ kind: "line", a: g.a, b: g.b }];
|
||||
case "polyline": {
|
||||
const out: DraftShape[] = [];
|
||||
for (let i = 0; i < g.pts.length - 1; i++) out.push({ kind: "line", a: g.pts[i], b: g.pts[i + 1] });
|
||||
if (g.closed && g.pts.length > 2) out.push({ kind: "line", a: g.pts[g.pts.length - 1], b: g.pts[0] });
|
||||
return out;
|
||||
}
|
||||
case "rect":
|
||||
case "image":
|
||||
return [{ kind: "poly", pts: [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }], closed: true }];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
/** Vorschau einer verschobenen Zeichnung (aufgeschobenes Körper-Verschieben beim Griff-Ziehen). */
|
||||
export function drawingMovePreview(project: Project, id: string, delta: Vec2, scaleDenominator?: number): DraftShape[] {
|
||||
return previewShapes(project, { wallIds: [], drawingId: id }, "move", [{ x: 0, y: 0 }, delta], "move", 1, {
|
||||
ignoreLock: true,
|
||||
scale: scaleDenominator,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Vorschau aller transformierten Instanzen (bewegtes Original bei U + alle
|
||||
* Kopien). `pts` sind die bisher gesetzten Punkte inkl. Cursor (Länge =
|
||||
* requiredPoints). Liefert die Stütz-/Basis-Punkte separat für Marker.
|
||||
* requiredPoints).
|
||||
*/
|
||||
export function transformPreview(
|
||||
project: Project,
|
||||
@@ -448,15 +148,7 @@ export function transformPreview(
|
||||
mode: CopyMode,
|
||||
count: number,
|
||||
): DraftShape[] {
|
||||
const items = gatherItems(project, sel, op);
|
||||
const shapes: DraftShape[] = [];
|
||||
const instances: number[] = [...copyTs(op, mode, count)];
|
||||
if (movesOriginal(mode)) instances.push(1); // U: Original an Endlage zeigen
|
||||
for (const t of instances) {
|
||||
const fn = transformFn(op, pts, t);
|
||||
for (const item of items) shapes.push(...itemPreview(project, item, fn));
|
||||
}
|
||||
return shapes;
|
||||
return previewShapes(project, sel, op, pts, mode, count);
|
||||
}
|
||||
|
||||
/** Anzahl Segmente des Radius-Kreises in {@link rotateGizmoShapes} — grob
|
||||
@@ -501,9 +193,21 @@ export function rotateGizmoShapes(center: Vec2, refPoint: Vec2, cursor: Vec2): D
|
||||
|
||||
// ── Commit ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Kern-Anfrage einer Transformation (neue ids: `prefix-Stempel-k`). */
|
||||
const transformReq = (sel: TransformSelection, op: TransformOp, pts: readonly Vec2[], mode: CopyMode, count: number) => ({
|
||||
cmd: "transform",
|
||||
sel,
|
||||
op,
|
||||
pts: pairs(pts),
|
||||
mode,
|
||||
count,
|
||||
stamp: uniqueStamp(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Die Transformation als Ops ([K4] S3): `replace` je bewegtem Original (nur bei „move"), `add` der
|
||||
* Kopien je Liste. Liest nur die gewählten Elemente — keine Projekt-Differenz über alle Wände.
|
||||
* Die Transformation als Ops ([K4] S3, Kern `cmd_transform::transform_ops`): `replace` je bewegtem
|
||||
* Original (nur bei „move"), `add` der Kopien je Liste. Gesperrte Elemente bleiben unberührt; Dächer
|
||||
* nur bei Verschieben/Skalieren.
|
||||
*/
|
||||
export function transformOps(
|
||||
project: Project,
|
||||
@@ -513,127 +217,7 @@ export function transformOps(
|
||||
mode: CopyMode,
|
||||
count: number,
|
||||
): CoreOp[] {
|
||||
const items = gatherItems(project, sel, op);
|
||||
if (items.length === 0) return [];
|
||||
const wallIds = new Set(sel.wallIds);
|
||||
// Bei einer Skalierung müssen auch Grössenfelder (Radius/Schrifthöhe/…)
|
||||
// mitziehen — dafür `scaleGeom` statt `mvGeom` (s. dort); analog für
|
||||
// Treppen `mvStair` mit dem Skalierungsfaktor statt Faktor 1.
|
||||
const geomAt = (geom: Drawing2DGeom, fn: (p: Vec2) => Vec2, t: number): Drawing2DGeom =>
|
||||
op === "scale" ? scaleGeom(geom, fn, scaleFactor(pts, t)) : mvGeom(geom, fn);
|
||||
const stairAt = (s: Stair, fn: (p: Vec2) => Vec2, t: number): Stair =>
|
||||
mvStair(s, fn, op === "scale" ? scaleFactor(pts, t) : 1);
|
||||
|
||||
const ceilingIds = new Set(sel.ceilingIds ?? []);
|
||||
const roofIds = new Set(sel.roofIds ?? []);
|
||||
const stairIds = new Set(sel.stairIds ?? []);
|
||||
const roomIds = new Set(sel.roomIds ?? []);
|
||||
const ops: CoreOp[] = [];
|
||||
|
||||
// U (move): Original an die Endlage (t=1) transformieren. Objekt-Sperre
|
||||
// (`locked`) überall mitgeprüft — dieselbe Semantik wie `gatherItems`
|
||||
// oben (das hier ist ein SEPARATER Pfad, der `items` nicht durchläuft,
|
||||
// s. Kommentar bei `roofTransformAllowed`-Nutzung als Präzedenzfall für
|
||||
// genau diese Art von Doppel-Pflege).
|
||||
if (movesOriginal(mode)) {
|
||||
const fn = transformFn(op, pts, 1);
|
||||
ops.push(
|
||||
...patchItems(project, "walls", (w) => wallIds.has(w.id) && !w.locked, (w) => ({
|
||||
...w,
|
||||
start: fn(w.start),
|
||||
end: fn(w.end),
|
||||
})),
|
||||
);
|
||||
const moveDrawIds = drawingIdSet(sel);
|
||||
if (moveDrawIds.size > 0) {
|
||||
ops.push(
|
||||
...patchItems(project, "drawings2d", (d) => moveDrawIds.has(d.id) && !d.locked, (d) => ({
|
||||
...d,
|
||||
geom: geomAt(d.geom, fn, 1),
|
||||
})),
|
||||
);
|
||||
}
|
||||
if (sel.extrudedSolidId) {
|
||||
// Skalierung: `points` (2D-Tesselierung fürs Grundriss-Polygon) UND der
|
||||
// echte Radius `circle.r` (den `toWalls3d.ts` für die runde 3D-Extrusion
|
||||
// nutzt) müssen mitziehen — sonst weicht das 3D-Volumen sichtbar von
|
||||
// der Grundriss-Kontur ab (nur `center` mitzuführen genügt nicht).
|
||||
const f1 = op === "scale" ? scaleFactor(pts, 1) : 1;
|
||||
const solidId = sel.extrudedSolidId;
|
||||
ops.push(...patchItems(project, "extrudedSolids", (s) => s.id === solidId, (s) => transformSolid(s, fn, f1)));
|
||||
}
|
||||
if (sel.columnId) {
|
||||
const columnId = sel.columnId;
|
||||
ops.push(...patchItems(project, "columns", (c) => c.id === columnId && !c.locked, (c) => mvColumn(c, fn)));
|
||||
}
|
||||
if (ceilingIds.size > 0)
|
||||
ops.push(...patchItems(project, "ceilings", (c) => ceilingIds.has(c.id) && !c.locked, (c) => mvCeiling(c, fn)));
|
||||
if (roofIds.size > 0 && roofTransformAllowed(op))
|
||||
ops.push(...patchItems(project, "roofs", (r) => roofIds.has(r.id) && !r.locked, (r) => mvRoof(r, fn)));
|
||||
if (stairIds.size > 0)
|
||||
ops.push(...patchItems(project, "stairs", (s) => stairIds.has(s.id) && !s.locked, (s) => stairAt(s, fn, 1)));
|
||||
if (roomIds.size > 0)
|
||||
ops.push(...patchItems(project, "rooms", (r) => roomIds.has(r.id) && !r.locked, (r) => mvRoom(r, fn)));
|
||||
}
|
||||
|
||||
// Kopien anhängen (I/O/P bzw. mirror copy).
|
||||
const newWalls: Wall[] = [];
|
||||
const newDrawings: Drawing2D[] = [];
|
||||
const newSolids: ExtrudedSolid[] = [];
|
||||
const newColumns: Column[] = [];
|
||||
const newCeilings: Ceiling[] = [];
|
||||
const newRoofs: Roof[] = [];
|
||||
const newStairs: Stair[] = [];
|
||||
const newRooms: Room[] = [];
|
||||
for (const t of copyTs(op, mode, count)) {
|
||||
const fn = transformFn(op, pts, t);
|
||||
for (const item of items) {
|
||||
switch (item.kind) {
|
||||
case "wall": {
|
||||
const w = item.wall;
|
||||
newWalls.push({ ...w, id: uniqueId("W"), start: fn(w.start), end: fn(w.end) });
|
||||
break;
|
||||
}
|
||||
case "drawing": {
|
||||
const d = item.drawing;
|
||||
newDrawings.push({ ...d, id: uniqueId("dr2d"), geom: geomAt(d.geom, fn, t) });
|
||||
break;
|
||||
}
|
||||
case "column":
|
||||
newColumns.push({ ...mvColumn(item.column, fn), id: uniqueId("column") });
|
||||
break;
|
||||
case "ceiling":
|
||||
newCeilings.push({ ...mvCeiling(item.ceiling, fn), id: uniqueId("C") });
|
||||
break;
|
||||
case "roof":
|
||||
newRoofs.push({ ...mvRoof(item.roof, fn), id: uniqueId("RF") });
|
||||
break;
|
||||
case "stair":
|
||||
newStairs.push({ ...stairAt(item.stair, fn, t), id: uniqueId("ST") });
|
||||
break;
|
||||
case "room":
|
||||
newRooms.push({ ...mvRoom(item.room, fn), id: uniqueId("RM") });
|
||||
break;
|
||||
case "extrudedSolid": {
|
||||
const s = item.solid;
|
||||
const f = op === "scale" ? scaleFactor(pts, t) : 1;
|
||||
newSolids.push({ ...transformSolid(s, fn, f), id: uniqueId("extrude") });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ops.push(
|
||||
...addItems("walls", newWalls),
|
||||
...addItems("drawings2d", newDrawings),
|
||||
...addItems("extrudedSolids", newSolids),
|
||||
...addItems("columns", newColumns),
|
||||
...addItems("ceilings", newCeilings),
|
||||
...addItems("roofs", newRoofs),
|
||||
...addItems("stairs", newStairs),
|
||||
...addItems("rooms", newRooms),
|
||||
);
|
||||
return ops;
|
||||
return documentFor(project).cmdOps(transformReq(sel, op, pts, mode, count));
|
||||
}
|
||||
|
||||
/** Wendet die Transformation immutabel auf das Projekt an (Original + Kopien), über {@link transformOps}. */
|
||||
@@ -659,5 +243,5 @@ export function transformMutation(
|
||||
mode: CopyMode,
|
||||
count: number,
|
||||
): ProjectMutation {
|
||||
return opsMutation((p) => transformOps(p, sel, op, pts, mode, count));
|
||||
return cmdMutation(transformReq(sel, op, pts, mode, count));
|
||||
}
|
||||
@@ -372,3 +372,12 @@ export function uniqueId(prefix: string): string {
|
||||
idCounter += 1;
|
||||
return `${prefix}-${Date.now()}-${idCounter}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stempel für ids, die der Kern vergibt (Befehle mit mehreren neuen Elementen, [K4] S3): der Kern
|
||||
* hängt je Element `-k` an (`prefix-Zeit-Zähler-k`, s. `cmd_transform::IdGen`).
|
||||
*/
|
||||
export function uniqueStamp(): string {
|
||||
idCounter += 1;
|
||||
return `${Date.now()}-${idCounter}`;
|
||||
}
|
||||
Reference in new issue
Block a user