[176] Geknickter Schnitt: Knick per Mittel-Griff einfügen, per Kontextmenü löschen, Aufräumen nach dem Ziehen; Grundriss-Unterlage folgt den Knicken

Mittel-Griff je Segment (Ziehen fügt den Knick ein), Kern-Ops sectionBendInsert/sectionBendDelete/sectionLineTidy
(Knick auf Nachbarpunkt oder Geraden entfällt auch im Modell, Toleranz 6 Bildschirm-Pixel), ein Undo-Schritt je Zug.
Kontextmenü Knick einfügen/löschen. Unterlage im Schnitt (underlay_for_level) je Segment abgewickelt und an den
Winkelhalbierenden zugeschnitten. e2e/sectionBend.spec.ts. Goldens unverändert (Drift der komplex-Grundrisse besteht schon vorher).
This commit is contained in:
Claude committed 2026-11-10 18:20:48 +00:00
1 parent 1b9e01bc00
commit e53a2089dc
14 files changed
+452 -21

No files matched your search

+6 -3
View File
@@ -140,9 +140,12 @@ Wer zu einer ID mehr wissen will (Entscheide, Tests, Bilder), sucht dort nach `*
(`plan/section/unfold.rs`): je Segment eigene Ebene, Schnittflächen auf den u-Bereich, Projektion an den Winkelhalbierenden
der Knicke zugeschnitten, Teilbilder aneinander (u = abgewickelte Länge), dünne Knicklinie (0.13 mm) je Knick; Öffnungen,
Achsen je Segment geschnitten, Bäume nach Mitte zugeordnet. Werkzeug: Schnitt nimmt weitere Klicks als Knicke, Enter/Doppelklick
beendet (Ansicht weiter zwei Klicks); Griffe an Anfang, Knicken, Ende (`grips.rs` `sectionLineGrip`). Offen: Grundriss-Unterlage
im Schnitt (`underlay.rs`) und 3D-Live-Schnitt folgen der Endpunkt-Verbindung; Knick einfügen/löschen am bestehenden Schnitt
(nur Ziehen); optionale dünne Ansichtsebene; Mac-/Tauri-Ansicht nicht geprüft.
beendet (Ansicht weiter zwei Klicks); Griffe an Anfang, Knicken, Ende (`grips.rs` `sectionLineGrip`). Knick einfügen/löschen (10.11.):
Mittel-Griff je Segment (Ziehen fügt den Knick ein, `sectionBendInsert`), Kontextmenü „Knick einfügen/löschen" (`sectionBendDelete`),
nach dem Ziehen entfallen Knicke auf einem Nachbarpunkt/der Geraden auch im Modell (`sectionLineTidy`, 5 mm bzw. 6 Bildschirm-Pixel); je Aktion ein Undo-Schritt
(gemeinsamer coalesceKey). Grundriss-Unterlage im Schnitt (`plan/underlay.rs` `underlay_for_level`) folgt den Knicken (je Segment
abgewickelt, an den Winkelhalbierenden zugeschnitten, `unfold::clip_plan_prims`). Offen: 3D-Live-Schnitt folgt der
Endpunkt-Verbindung; Mittel-Griffe sehen aus wie Eckgriffe; optionale dünne Ansichtsebene; Mac-/Tauri-Ansicht nicht geprüft.
L-Marke (10.11., Wunsch Maintainer): Markentyp
`DrawingLevel.markerStyle` ("arrow" Basis | "lAngle") mit Vorgabe `ModelViewOption.sectionMarks.style` (Ebene > Modelldarstellung >
Pfeil; `Options::section_marker`); L = je Ende kräftiger langer Schenkel (12 mm) längs der Linie nach innen + kurzer (6 mm) in
+72
View File
@@ -0,0 +1,72 @@
// [176] Knick am bestehenden Schnitt per Griff einfügen: Schnittlinie wählen, Mittel-Griff ziehen (Knick entsteht,
// ein Undo-Schritt), Knick zurück auf die Gerade ziehen (Knick entfällt wieder). Bildschirm-Punkte aus der
// viewBox-Abbildung des SVG-Overlays (wie kataster.spec.ts).
import type { Page } from "@playwright/test";
import { blurFocus, commandInput, expect, finishCommand, startNewProject, test, typeCommand } from "./app";
async function screenOf(page: Page, x: number, y: number): Promise<{ x: number; y: number }> {
return page.locator("svg.plan-svg").evaluate(
(el, [mx, my]) => {
const [vx, vy, vw, vh] = el.getAttribute("viewBox")!.split(/\s+/).map(Number);
const ox = Number(el.getAttribute("data-origin-x") ?? 0);
const oy = Number(el.getAttribute("data-origin-y") ?? 0);
const r = el.getBoundingClientRect();
const s = Math.min(r.width / vw, r.height / vh);
return { x: r.left + (r.width - vw * s) / 2 + (mx * 90 - ox - vx) * s, y: r.top + (r.height - vh * s) / 2 + (-my * 90 - oy - vy) * s };
},
[x, y],
);
}
async function gripCentres(page: Page): Promise<{ x: number; y: number }[]> {
const c = await page.locator(".plan-grip").evaluateAll((els) =>
els.map((e) => {
const r = e.getBoundingClientRect();
return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
}),
);
return c.sort((a, b) => a.x - b.x || a.y - b.y);
}
/** Griff ziehen: ein Griff bleibt nach dem Loslassen „bewaffnet" und folgt dem Zeiger, bis ein Klick ihn setzt. */
async function dragGrip(page: Page, from: { x: number; y: number }, to: { x: number; y: number }): Promise<void> {
await page.mouse.move(from.x, from.y);
await page.mouse.down();
await page.mouse.move(to.x, to.y, { steps: 6 });
await page.mouse.up();
await page.mouse.click(to.x, to.y);
}
test("Schnitt: Mittel-Griff ziehen fügt einen Knick ein, Zurückziehen auf die Gerade entfernt ihn, Rückgängig", async ({ page }) => {
await startNewProject(page);
await commandInput(page).focus();
await typeCommand(page, "schnittlinie");
await typeCommand(page, "0,0");
await typeCommand(page, "10,0");
await finishCommand(page); // Schnitt: weitere Klicks wären Knicke, Enter beendet
await blurFocus(page);
await page.locator('[title="Auf Plan einpassen"]').first().click();
// Schnittlinie wählen (kräftiges Endstück am Anfang): Griffe Anfang, Ende + ein Mittel-Griff.
const at = await screenOf(page, 0.4, 0);
await page.mouse.click(at.x, at.y);
await expect(page.locator(".plan-grip")).toHaveCount(3);
const [start, mid, end] = await gripCentres(page);
expect(Math.abs(mid.x - (start.x + end.x) / 2)).toBeLessThan(2);
// Mittel-Griff nach unten ziehen: Knick (jetzt Anfang, Knick, Ende + zwei Mittel-Griffe).
await dragGrip(page, mid, { x: mid.x, y: mid.y + 40 });
await expect(page.locator(".plan-grip")).toHaveCount(5);
// Rückgängig: ein Schritt nimmt Einfügen und Zug zusammen weg.
await blurFocus(page);
await page.keyboard.press("Control+z");
await expect(page.locator(".plan-grip")).toHaveCount(3);
// Wieder einfügen, dann den Knick auf die Gerade zurückziehen: er entfällt.
await dragGrip(page, mid, { x: mid.x, y: mid.y + 40 });
await expect(page.locator(".plan-grip")).toHaveCount(5);
const bend = (await gripCentres(page)).find((g) => Math.abs(g.x - mid.x) < 3 && g.y > mid.y + 20)!;
await dragGrip(page, bend, { x: mid.x, y: mid.y + 1 });
await expect(page.locator(".plan-grip")).toHaveCount(3);
});
+123
View File
@@ -110,6 +110,8 @@ pub struct Request {
fy: N,
/// [T2] Getippte Bogenlänge (Tab) beim Endpunkt-Griff einer Bogenwand; fehlt = NaN = Cursor.
arc_length: N,
/// [176] Aufräum-Abstand (m) für `sectionLineTidy` (Zeiger-Genauigkeit der Ansicht); fehlt = NaN = 5 mm.
tol: N,
thickness: N,
pt: [N; 2],
delta: [N; 2],
@@ -133,6 +135,7 @@ impl Request {
"fx" => self.fx.0,
"fy" => self.fy.0,
"arcLength" => self.arc_length.0,
"tol" => self.tol.0,
_ => self.thickness.0,
}
}
@@ -264,6 +267,22 @@ pub fn run(lk: &Lookup, req: &Request) -> Result<GripResult, String> {
let (index, (x, y)) = (r.n("index"), r.p("pt"));
patch("drawingLevels", r.s("id"), &|e| section_line_grip(e, index, x, y)).into()
}
// [176] Knick einfügen (Mittel-Griff von Segment `seg` gezogen), löschen (Kontextmenü am Knick-Griff,
// `index` wie bei `sectionLineGrip`) bzw. aufräumen (nach dem Ziehen: Knicke auf einem Nachbarpunkt
// oder auf der Geraden zwischen den Nachbarn entfallen).
"sectionBendInsert" => {
let (seg, (x, y)) = (r.n("seg"), r.p("pt"));
patch("drawingLevels", r.s("id"), &|e| section_bend_edit(e, SectionBendEdit::Insert(seg, x, y))).into()
}
"sectionBendDelete" => {
let index = r.n("index");
patch("drawingLevels", r.s("id"), &|e| section_bend_edit(e, SectionBendEdit::Delete(index))).into()
}
"sectionLineTidy" => {
let tol = r.n("tol");
let tol = if tol.is_finite() { tol.clamp(BEND_TIDY_M, 1.0) } else { BEND_TIDY_M };
patch("drawingLevels", r.s("id"), &|e| section_bend_edit(e, SectionBendEdit::Tidy(tol))).into()
}
"excavationGrip" => {
let (index, (x, y)) = (r.n("index"), r.p("pt"));
patch("context", r.s("id"), &|e| {
@@ -456,6 +475,72 @@ fn section_line_grip(e: &Value, index: f64, x: f64, y: f64) -> Option<Value> {
Some(with(e, "bendPoints", replace_at(bends, (i - 1) as f64, &pt(x, y))))
}
enum SectionBendEdit {
Insert(f64, f64, f64),
Delete(f64),
Tidy(f64),
}
/// Mindest-Abstand (m), unter dem ein Knick als auf dem Nachbarpunkt bzw. der Geraden zwischen den Nachbarn gilt
/// (die Hülle gibt beim Ziehen die Zeiger-Genauigkeit der Ansicht mit, `tol`).
const BEND_TIDY_M: f64 = 0.005;
/// [176] Knickpunkte einer Schnittlinie ändern; `None`, wenn nichts zu tun ist.
fn section_bend_edit(e: &Value, edit: SectionBendEdit) -> Option<Value> {
let line = field(e, "linePoints")?.as_array()?;
if line.len() < 2 {
return None;
}
let mut bends: Vec<Value> = field(e, "bendPoints").and_then(Value::as_array).cloned().unwrap_or_default();
match edit {
SectionBendEdit::Insert(seg, x, y) => {
let j = index_in(seg, bends.len() + 1)?;
if !(x.is_finite() && y.is_finite()) {
return None;
}
bends.insert(j, pt(x, y));
}
SectionBendEdit::Delete(index) => {
let i = index_in(index, bends.len() + 2)?;
if i == 0 || i == bends.len() + 1 {
return None;
}
bends.remove(i - 1);
}
SectionBendEdit::Tidy(tol) => {
let before = bends.len();
loop {
let mut pts: Vec<(f64, f64)> = vec![xy(&line[0])];
pts.extend(bends.iter().map(xy));
pts.push(xy(&line[1]));
// Knick i (Punkt i+1) mit den Nachbarn i und i+2.
let bad = (0..bends.len()).find(|&i| {
let (a, b, c) = (pts[i], pts[i + 1], pts[i + 2]);
let (dx, dy) = (c.0 - a.0, c.1 - a.1);
let len2 = dx * dx + dy * dy;
let t = if len2 > 0.0 { ((b.0 - a.0) * dx + (b.1 - a.1) * dy) / len2 } else { 0.0 };
let (qx, qy) = (a.0 + t.clamp(0.0, 1.0) * dx, a.1 + t.clamp(0.0, 1.0) * dy);
(b.0 - qx).hypot(b.1 - qy) < tol
});
match bad {
Some(i) => {
bends.remove(i);
}
None => break,
}
}
if bends.len() == before {
return None;
}
}
}
if bends.is_empty() {
// Ohne Knicke fällt das Feld weg (altes 2-Punkt-Format).
return Some(with_opt(e, vec![("bendPoints", None)]));
}
Some(with(e, "bendPoints", Value::Array(bends)))
}
fn wall_moved(w: &Value, dx: f64, dy: f64) -> Value {
let s = moved(field(w, "start").unwrap_or(&Value::Null), dx, dy);
let e = moved(field(w, "end").unwrap_or(&Value::Null), dx, dy);
@@ -1589,6 +1674,44 @@ mod tests {
assert!(entity(&res).get("bendPoints").is_none());
}
/// [176] Knick einfügen / löschen / aufräumen am bestehenden Schnitt.
#[test]
fn schnittlinie_knick_einfuegen_loeschen_aufraeumen() {
let lv = json!({"id": "s", "kind": "section", "linePoints": [{"x": 0, "y": 0}, {"x": 6, "y": 10}], "bendPoints": [{"x": 6, "y": 0}]});
let gerade = json!({"id": "g", "kind": "section", "linePoints": [{"x": 0, "y": 0}, {"x": 10, "y": 0}]});
let r = root(json!({"drawingLevels": [lv, gerade]}));
let ent = |v: Value| run(&Lookup::plain(&r), &rq(v)).unwrap().ops.first().map(|o| o.to_json()["entity"].clone());
// Gerade Linie: Segment 0 → erster Knick.
let e = ent(json!({"op": "sectionBendInsert", "id": "g", "seg": 0, "pt": [5, 3]})).unwrap();
assert_eq!(e["bendPoints"], json!([{"x": 5, "y": 3}]));
// Mit Knick: Segment 1 (zwischen Knick und Ende) → Knick an Stelle 1, Reihenfolge bleibt.
let e = ent(json!({"op": "sectionBendInsert", "id": "s", "seg": 1, "pt": [7, 4]})).unwrap();
assert_eq!(e["bendPoints"], json!([{"x": 6, "y": 0}, {"x": 7, "y": 4}]));
let e = ent(json!({"op": "sectionBendInsert", "id": "s", "seg": 0, "pt": [3, -1]})).unwrap();
assert_eq!(e["bendPoints"], json!([{"x": 3, "y": -1}, {"x": 6, "y": 0}]));
assert!(ent(json!({"op": "sectionBendInsert", "id": "s", "seg": 2, "pt": [1, 1]})).is_none());
// Löschen: Knick-Griff 1; Anfang/Ende lassen sich nicht löschen; ohne Knicke fällt das Feld weg.
let e = ent(json!({"op": "sectionBendDelete", "id": "s", "index": 1})).unwrap();
assert!(e.get("bendPoints").is_none());
assert!(ent(json!({"op": "sectionBendDelete", "id": "s", "index": 0})).is_none());
assert!(ent(json!({"op": "sectionBendDelete", "id": "s", "index": 2})).is_none());
// Aufräumen: Knick auf der Geraden bzw. auf dem Nachbarpunkt entfällt, ein echter Knick bleibt.
let r2 = root(json!({"drawingLevels": [
{"id": "a", "kind": "section", "linePoints": [{"x": 0, "y": 0}, {"x": 10, "y": 0}], "bendPoints": [{"x": 5, "y": 0.001}]},
{"id": "b", "kind": "section", "linePoints": [{"x": 0, "y": 0}, {"x": 10, "y": 0}], "bendPoints": [{"x": 0, "y": 0}, {"x": 5, "y": 3}]},
{"id": "c", "kind": "section", "linePoints": [{"x": 0, "y": 0}, {"x": 10, "y": 0}], "bendPoints": [{"x": 5, "y": 3}]},
{"id": "d", "kind": "section", "linePoints": [{"x": 0, "y": 0}, {"x": 10, "y": 0}], "bendPoints": [{"x": 5, "y": 0.02}]}
]}));
let tidy = |id: &str| run(&Lookup::plain(&r2), &rq(json!({"op": "sectionLineTidy", "id": id}))).unwrap().ops.first().map(|o| o.to_json()["entity"].clone());
// Mit Ansichts-Toleranz (3 cm) entfällt auch ein Knick, der nur 2 cm neben der Geraden liegt (ohne: bleibt).
assert!(tidy("d").is_none());
let grob = run(&Lookup::plain(&r2), &rq(json!({"op": "sectionLineTidy", "id": "d", "tol": 0.03}))).unwrap().ops.first().map(|o| o.to_json()["entity"].clone());
assert!(grob.unwrap().get("bendPoints").is_none());
assert!(tidy("a").unwrap().get("bendPoints").is_none());
assert_eq!(tidy("b").unwrap()["bendPoints"], json!([{"x": 5, "y": 3}]));
assert!(tidy("c").is_none());
}
#[test]
fn wand_griff_und_sperre() {
let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}, "extra": 1}]}));
+91
View File
@@ -315,6 +315,97 @@ pub fn clip_prims(prims: Vec<Primitive>, s: Option<&Strip>) -> Vec<Primitive> {
out
}
/// [176] Grundriss-Unterlage: Primitive eines Segments in dessen Ansichtskoordinaten (x = u, y = Tiefe hinter
/// der Ebene) auf den ganzen Streifen schneiden (u-Bereich und Winkelhalbierende) und in die Abwicklung
/// schieben. Flächen und Linien geometrisch, alles andere nach Anker.
pub fn clip_plan_prims(prims: Vec<Primitive>, s: &Strip) -> Vec<Primitive> {
let g = |h: &[f64; 3], x: f64, y: f64| h[0] * x + h[1] * y - h[2];
let mut out = Vec::with_capacity(prims.len());
for mut q in prims {
let keep = match &mut q {
Primitive::Polygon { pts, no_stroke_edges, .. } => {
let p2: Vec<[f64; 2]> = pts.iter().map(|p| [p.x, p.y]).collect();
match clip_poly_u(&p2, no_stroke_edges.as_deref(), s.lo, s.hi) {
Some((mut cur, nse)) => {
let mut flags = vec![false; cur.len()];
for &k in nse.as_deref().unwrap_or(&[]) {
if let Some(f) = flags.get_mut(k as usize) {
*f = true;
}
}
for h in &s.half {
if cur.iter().all(|q| g(h, q[0], q[1]) <= 0.0) {
continue;
}
(cur, flags) = clip_ring(&cur, &flags, &|q| g(h, q[0], q[1]), &|a, b, t| lerp2(a, b, t), true);
if cur.len() < 3 {
break;
}
}
if cur.len() < 3 {
false
} else {
let nse: Vec<f64> = flags.iter().enumerate().filter(|(_, f)| **f).map(|(i, _)| i as f64).collect();
*pts = cur.into_iter().map(|p| Vec2 { x: p[0], y: p[1] }).collect();
*no_stroke_edges = (!nse.is_empty()).then_some(nse);
true
}
}
None => false,
}
}
Primitive::Line { a, b, .. } => match clip_line_to_u(&[[a.x, a.y], [b.x, b.y]], s.lo, s.hi).first() {
Some(l) if l.len() == 2 => {
let (mut p, mut r) = (l[0], l[1]);
let mut ok = true;
for h in &s.half {
let (gp, gr) = (g(h, p[0], p[1]), g(h, r[0], r[1]));
if gp > 0.0 && gr > 0.0 {
ok = false;
break;
}
if gp > 0.0 {
p = lerp2(&p, &r, gp / (gp - gr));
} else if gr > 0.0 {
r = lerp2(&p, &r, gp / (gp - gr));
}
}
if ok {
*a = Vec2 { x: p[0], y: p[1] };
*b = Vec2 { x: r[0], y: r[1] };
}
ok
}
_ => false,
},
other => {
let (u, w) = anchor_pt(other);
u >= s.lo - 1e-9 && u <= s.hi + 1e-9 && s.half.iter().all(|h| g(h, u, w) <= 1e-9)
}
};
if keep {
shift_prim(&mut q, s.offset);
out.push(q);
}
}
out
}
/// Anker (x, y) eines Primitivs.
fn anchor_pt(q: &Primitive) -> (f64, f64) {
match q {
Primitive::Polygon { pts, .. } => {
let n = pts.len().max(1) as f64;
(pts.iter().map(|p| p.x).sum::<f64>() / n, pts.iter().map(|p| p.y).sum::<f64>() / n)
}
Primitive::Line { a, b, .. } => (0.5 * (a.x + b.x), 0.5 * (a.y + b.y)),
Primitive::Arc { center, .. } | Primitive::DrawingCircle { center, .. } | Primitive::DrawingArc { center, .. } => (center.x, center.y),
Primitive::Text { at, .. } | Primitive::DrawingText { at, .. } => (at.x, at.y),
Primitive::DrawingTextPath { path_pts, .. } => path_pts.first().map_or((0.0, 0.0), |p| (p.x, p.y)),
Primitive::DrawingImage { min, max, .. } => (0.5 * (min.x + max.x), 0.5 * (min.y + max.y)),
}
}
/// Ganze Gruppe (z. B. ein Baum) behalten, wenn ihre Mitte im Streifen liegt; verschoben.
pub fn keep_group(prims: Vec<Primitive>, s: Option<&Strip>) -> Vec<Primitive> {
let Some(s) = s else { return prims };
+55 -7
View File
@@ -12,6 +12,7 @@
use super::prim::Primitive;
use crate::jsmath::hypot2;
use crate::jsnum::{atan2, max, min};
use super::section::LevelSpec;
use crate::model::Vec2;
/// Abstand (Meter) zwischen tiefster Schnitt-/Ansichtskante und Grundriss-Oberkante.
@@ -147,14 +148,38 @@ fn as_reference(pr: Primitive) -> Primitive {
/// bei `section_min_y` liegt (`planUnderlayPrimitives`): gedimmt, ohne Auswahl-Ids, dazu die
/// Schnittlinie. Ohne gültige Linie leer.
pub fn underlay_primitives(line: Option<[Vec2; 2]>, direction_sign: Option<f64>, plan: impl IntoIterator<Item = Primitive>, section_min_y: f64) -> Vec<Primitive> {
underlay_for_level(&LevelSpec { line, direction_sign, ..Default::default() }, plan, section_min_y)
}
/// Wie [`underlay_primitives`] für eine ganze Schnittebene; mit Knickpunkten ([176]) je Segment mit dessen
/// Ebene abgebildet, auf den Streifen zugeschnitten und abgewickelt (wie der Schnitt selbst).
pub fn underlay_for_level(level: &LevelSpec, plan: impl IntoIterator<Item = Primitive>, section_min_y: f64) -> Vec<Primitive> {
let (line, direction_sign) = (level.line, level.direction_sign);
let Some(line) = line else { return vec![] };
let Some(base) = section_map(line, direction_sign) else { return vec![] };
let mut mapped = Vec::new();
let mut top = f64::NEG_INFINITY;
for pr in plan {
let Some(q) = map_primitive(&base, pr) else { continue };
max_y(&q, &mut top);
mapped.push(q);
let bent = super::section::unfold::segments(level);
let plan: Vec<Primitive> = plan.into_iter().collect();
match &bent {
None => {
for pr in plan {
let Some(q) = map_primitive(&base, pr) else { continue };
max_y(&q, &mut top);
mapped.push(q);
}
}
Some(segs) => {
for (seg, strip) in segs {
let (Some(l), Some(strip)) = (seg.line, strip) else { continue };
let Some(m) = section_map(l, direction_sign) else { continue };
let part: Vec<Primitive> = plan.iter().cloned().filter_map(|pr| map_primitive(&m, pr)).collect();
for q in super::section::unfold::clip_plan_prims(part, strip) {
max_y(&q, &mut top);
mapped.push(q);
}
}
}
}
// Die Schnittlinie (w = 0) liegt immer mit in der Unterlage.
if 0.0 > top {
@@ -165,7 +190,11 @@ pub fn underlay_primitives(line: Option<[Vec2; 2]>, direction_sign: Option<f64>,
let shift_map = SectionMap { p0: o, u: Vec2 { x: 1.0, y: 0.0 }, n: Vec2 { x: 0.0, y: 1.0 }, theta: 0.0, dy: shift };
let mut out: Vec<Primitive> = mapped.into_iter().filter_map(|q| map_primitive(&shift_map, q)).map(as_reference).collect();
let [l0, l1] = line;
let len = hypot2(l1.x - l0.x, l1.y - l0.y);
// Länge der (abgewickelten) Linie: Summe der Segmente.
let len = match &bent {
Some(segs) => segs.iter().filter_map(|(s, _)| s.line).map(|[a, b]| hypot2(b.x - a.x, b.y - a.y)).sum(),
None => hypot2(l1.x - l0.x, l1.y - l0.y),
};
out.push(Primitive::Line {
a: Vec2 { x: 0.0, y: shift },
b: Vec2 { x: len, y: shift },
@@ -206,11 +235,11 @@ pub fn plan_out_primitives(out: &super::domains::PlanOut) -> Result<Vec<Primitiv
/// Argumente aus dem Abfrage-Text: die `planDomains`-Argumente des Geschosses plus `level` (Schnitt/
/// Ansicht) und `minY` (tiefste Kante des Schnitts).
pub fn parse_args(text: &str) -> Result<(Option<[Vec2; 2]>, Option<f64>, f64), String> {
pub fn parse_args(text: &str) -> Result<(super::section::LevelSpec, f64), String> {
let v: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("planUnderlay: {e}"))?;
let level = super::section::LevelSpec::from_json(v.get("level").unwrap_or(&serde_json::Value::Null));
let min_y = v.get("minY").and_then(|x| x.as_f64()).ok_or("planUnderlay: minY fehlt")?;
Ok((level.line, level.direction_sign, min_y))
Ok((level, min_y))
}
/// Plan-Puffer (eine Gruppe) der Unterlage.
@@ -311,4 +340,23 @@ mod tests {
// Blick nach −x: θ = −90°, das Muster dreht um +90°.
assert!((hatch.angle - 100.0).abs() < 1e-9, "{}", hatch.angle);
}
/// [176] Geknickte Schnittlinie: die Unterlage folgt den Segmenten (je Segment abgewickelt, nichts doppelt).
#[test]
fn geknickte_linie_wickelt_die_unterlage_ab() {
let lv = LevelSpec { line: Some([v(0.0, 0.0), v(6.0, 6.0)]), bends: vec![v(6.0, 0.0)], direction_sign: Some(1.0), ..Default::default() };
// Ein Strich im ersten Streifen (u = 1, Tiefe 2), einer im zweiten (u = 3 ab Knick, Tiefe −2).
let plan = vec![line(v(1.0, 2.0), v(1.0, 2.5)), line(v(8.0, 3.0), v(8.0, 3.5))];
let out = underlay_for_level(&lv, plan.clone(), 0.0);
let xs: Vec<f64> = out.iter().filter_map(|q| if let Primitive::Line { a, cls, .. } = q { (cls == "t").then_some(a.x) } else { None }).collect();
assert_eq!(xs.len(), 2, "jeder Strich genau einmal: {xs:?}");
assert!((xs[0] - 1.0).abs() < 1e-9 && (xs[1] - 9.0).abs() < 1e-9, "{xs:?}");
// Abgewickelte Linie = Summe der Segmente (6 + 6).
let Primitive::Line { a, b, cls, .. } = out.last().unwrap() else { panic!() };
assert_eq!(cls, "section-underlay-line");
assert!((b.x - a.x - 12.0).abs() < 1e-9);
// Ohne Knick bleibt alles beim Alten.
let gerade = LevelSpec { bends: vec![], ..lv };
assert_eq!(underlay_for_level(&gerade, plan.clone(), 0.0).len(), underlay_primitives(gerade.line, Some(1.0), plan, 0.0).len());
}
}
+4 -4
View File
@@ -312,10 +312,10 @@ pub fn run_bin(p: &Project, name: &str, args: &[f64], text: &str) -> Result<Vec<
// Grundriss-Unterlage unter Schnitt/Ansicht: `planDomains`-Argumente + `level`, `minY`.
("planUnderlay", 1) => {
let a = domains::PlanArgs::parse_in(p, args[0], text)?;
let (line, sign, min_y) = crate::plan::underlay::parse_args(text)?;
let (level, min_y) = crate::plan::underlay::parse_args(text)?;
let bytes = domains::plan_domains_buf(p, &a)?;
let prims = crate::plan::buf::View::parse(&bytes).and_then(|v| v.prims()).ok_or("planUnderlay: Plan-Puffer unlesbar")?;
Ok(crate::plan::underlay::underlay_buf(&crate::plan::underlay::underlay_primitives(line, sign, prims, min_y)))
Ok(crate::plan::underlay::underlay_buf(&crate::plan::underlay::underlay_for_level(&level, prims, min_y)))
}
// Umriss-Linien der 3D-Auswahl (`highlight3d.rs`): `text` = JSON der ids je Art + `rgb`; Antwort f32-LE.
("selectionHighlight", _) => {
@@ -345,12 +345,12 @@ pub fn run_bin_doc(d: &mut crate::document::Document, name: &str, args: &[f64],
if name == "planUnderlay" && args.len() == 1 {
// Der Grundriss kommt aus den Plan-Caches (wie `generatePlan` desselben Geschosses).
let mut a = crate::plan::domains::PlanArgs::parse(args[0], text)?;
let (line, sign, min_y) = crate::plan::underlay::parse_args(text)?;
let (level, min_y) = crate::plan::underlay::parse_args(text)?;
let (p, revs, cache) = d.project_cached().map_err(model_err)?;
a.apply_model_view(p);
let out = crate::plan::domains::plan_domains_cached(p, revs, cache, &a, &Default::default())?;
let prims = crate::plan::underlay::plan_out_primitives(&out)?;
return Ok(crate::plan::underlay::underlay_buf(&crate::plan::underlay::underlay_primitives(line, sign, prims, min_y)));
return Ok(crate::plan::underlay::underlay_buf(&crate::plan::underlay::underlay_for_level(&level, prims, min_y)));
}
run_bin(d.project().map_err(model_err)?, name, args, text)
}
+3
View File
@@ -31,6 +31,9 @@ export type GripRequest =
| { op: "excavationGrip"; id: string; index: number; pt: P }
// [176] Schnittlinie: 0 = Anfang, dann `bendPoints`, zuletzt das Ende.
| { op: "sectionLineGrip"; id: string; index: number; pt: P }
| { op: "sectionBendInsert"; id: string; seg: number; pt: P }
| { op: "sectionBendDelete"; id: string; index: number }
| { op: "sectionLineTidy"; id: string; tol?: number }
// [151] Parameter-Griff einer Podesttreppe (Kern `grip_drag::stair_param_drag`).
| { op: "stairParam"; id: string; index: number; pt: P }
| { op: "excavationEdge"; id: string; a: number; b: number; delta: P }
+2
View File
@@ -1030,6 +1030,8 @@ export const de = {
"ctx.print": "Drucken",
"ctx.insertPoint": "Punkt einfügen",
"ctx.deletePoint": "Punkt löschen",
"ctx.insertBend": "Knick einfügen",
"ctx.deleteBend": "Knick löschen",
"ctx.vertexType.corner": "Eckpunkt",
"ctx.vertexType.arc": "Bogenpunkt",
"ctx.vertexType.spline": "Splinepunkt",
+2
View File
@@ -1025,6 +1025,8 @@ export const en: Record<TranslationKey, string> = {
"ctx.print": "Print",
"ctx.insertPoint": "Insert point",
"ctx.deletePoint": "Delete point",
"ctx.insertBend": "Insert bend",
"ctx.deleteBend": "Delete bend",
"ctx.vertexType.corner": "Corner point",
"ctx.vertexType.arc": "Arc point",
"ctx.vertexType.spline": "Spline point",
+10
View File
@@ -57,6 +57,8 @@ export function AppContextMenu(props: {
deleteLevel,
reorderDrawings,
insertDrawingPoint,
insertSectionBend,
deleteSectionBend,
deleteDrawingPoint,
setPolylineVertexType,
reorderDrawingLevels,
@@ -139,6 +141,14 @@ export function AppContextMenu(props: {
? { id: d.id, pts: d.geom.pts, closed: d.geom.closed, bulge: d.geom.bulge }
: null;
})(),
// [176] Geknickte Schnittlinie: Knick einfügen/löschen am gewählten Schnitt.
selectedSectionLine: (() => {
if (selection.sectionLines.length !== 1) return null;
const l = project.drawingLevels.find((x) => x.id === selection.sectionLines[0] && x.linePoints);
return l?.linePoints ? { id: l.id, pts: [l.linePoints[0], ...(l.bendPoints ?? []), l.linePoints[1]] } : null;
})(),
insertSectionBend,
deleteSectionBend,
insertPolylinePoint: insertDrawingPoint,
deletePolylinePoint: deleteDrawingPoint,
setPolylineVertexType,
+21
View File
@@ -86,6 +86,10 @@ export interface MenuActions {
* anderes selektiert ist; dann entfallen die beiden Einträge.
*/
selectedPolyline: { id: string; pts: Vec2[]; closed: boolean; bulge?: number[] } | null;
/** [176] Einzeln gewählte Schnittlinie: Anfang, Knickpunkte, Ende (für „Knick einfügen/löschen"). */
selectedSectionLine?: { id: string; pts: Vec2[] } | null;
insertSectionBend?: (id: string, seg: number, pt: Vec2) => void;
deleteSectionBend?: (id: string, index: number) => void;
/** Ob eine Element-Stil-Zwischenablage gefüllt ist (aktiviert „Einfügen"). */
hasDrawingStyleClipboard: boolean;
/** Kopiert das Aussehen des ERSTEN gewählten 2D-Elements. */
@@ -315,6 +319,23 @@ function planMenuItems(
typeItem("spline", "ctx.vertexType.spline", "gesture"),
);
}
// [176] Schnittlinie: Knick am Klick einfügen bzw. den getroffenen Knick löschen (Anfang/Ende nicht).
const sec = a.selectedSectionLine;
const secTarget = sec ? nearestPolylineTarget({ pts: sec.pts, closed: false }, model, toleranceFor({ pts: sec.pts, closed: false })) : null;
if (sec && secTarget?.kind === "segment" && a.insertSectionBend) {
pointItems.push({
label: t("ctx.insertBend"),
icon: <MenuIcon name="add_circle" />,
onClick: () => a.insertSectionBend?.(sec.id, secTarget.segIndex, secTarget.at),
});
}
if (sec && secTarget?.kind === "vertex" && secTarget.index > 0 && secTarget.index < sec.pts.length - 1 && a.deleteSectionBend) {
pointItems.push({
label: t("ctx.deleteBend"),
icon: <MenuIcon name="do_not_disturb_on" />,
onClick: () => a.deleteSectionBend?.(sec.id, secTarget.index),
});
}
// Eigenschaften übertragen — dasselbe Muster wie im Ebenen-Menü, nur für
// 2D-Elemente. Kopieren ab einem gewählten Element, Einfügen sobald etwas
// in der Zwischenablage liegt.
+12 -2
View File
@@ -387,7 +387,13 @@ export interface ProjectSlice {
/** [68] Baugrube: Umriss-Ecke ziehen (Index = Ecke; Index = Eckenzahl: Sohlenhöhe). */
moveExcavationGrip: (id: string, index: number, pt: Vec2) => void;
/** [176] Griff einer Schnittlinie: 0 = Anfang, dann die Knickpunkte, zuletzt das Ende. */
moveSectionLineGrip: (id: string, index: number, pt: Vec2) => void;
moveSectionLineGrip: (id: string, index: number, pt: Vec2, coalesceKey?: string) => void;
/** [176] Knick in Segment `seg` (Mittel-Griff) einfügen; `coalesceKey` fasst den anschliessenden Zug zusammen. */
insertSectionBend: (id: string, seg: number, pt: Vec2, coalesceKey?: string) => void;
/** [176] Knick löschen (`index` wie bei {@link moveSectionLineGrip}; Anfang/Ende lassen sich nicht löschen). */
deleteSectionBend: (id: string, index: number) => void;
/** [176] Nach dem Ziehen: Knicke auf einem Nachbarpunkt oder auf der Geraden entfernen. */
tidySectionLine: (id: string, coalesceKey?: string, tol?: number) => void;
moveExcavationEdge: (id: string, aIndex: number, bIndex: number, delta: Vec2) => void;
/** Verschiebt eine Decke (ganzer Umriss) um `delta`. */
moveCeilingBy: (ceilingId: string, delta: Vec2) => void;
@@ -1242,7 +1248,11 @@ export function createProjectSlice(
applyGrip({ op: "ceilingGrip", id: ceilingId, index, pt: gripPt(pt) }, `moveCeilingGrip:${ceilingId}:${index}`),
moveExcavationGrip: (id, index, pt) => applyGrip({ op: "excavationGrip", id, index, pt: gripPt(pt) }, `moveExcavationGrip:${id}:${index}`),
moveSectionLineGrip: (id, index, pt) => applyGrip({ op: "sectionLineGrip", id, index, pt: gripPt(pt) }, `moveSectionLineGrip:${id}:${index}`),
moveSectionLineGrip: (id, index, pt, coalesceKey) =>
applyGrip({ op: "sectionLineGrip", id, index, pt: gripPt(pt) }, coalesceKey ?? `moveSectionLineGrip:${id}:${index}`),
insertSectionBend: (id, seg, pt, coalesceKey) => applyGrip({ op: "sectionBendInsert", id, seg, pt: gripPt(pt) }, coalesceKey),
deleteSectionBend: (id, index) => applyGrip({ op: "sectionBendDelete", id, index }),
tidySectionLine: (id, coalesceKey, tol) => applyGrip({ op: "sectionLineTidy", id, ...(tol != null ? { tol } : {}) }, coalesceKey),
moveExcavationEdge: (id, aIndex, bIndex, delta) =>
applyGrip({ op: "excavationEdge", id, a: aIndex, b: bIndex, delta: gripPt(delta) }, `moveExcavationEdge:${id}:${aIndex}:${bIndex}`),
+47 -5
View File
@@ -181,8 +181,17 @@ export function useGripEditing(opts: {
const selectedSectionLine = modelEditable && selectedSectionLineId
? project.drawingLevels.find((l) => l.id === selectedSectionLineId && l.linePoints)
: undefined;
const sectionLineGrips = (l: NonNullable<typeof selectedSectionLine>): Vec2[] =>
l.linePoints ? [l.linePoints[0], ...(l.bendPoints ?? []), l.linePoints[1]] : [];
// Dahinter je Segment ein Mittel-Griff: Ziehen fügt dort einen Knick ein (Index = Punktzahl + Segment).
const sectionLineGrips = (l: NonNullable<typeof selectedSectionLine>): Vec2[] => {
if (!l.linePoints) return [];
const pts = [l.linePoints[0], ...(l.bendPoints ?? []), l.linePoints[1]];
const mids = pts.slice(1).map((q, i) => ({ x: (pts[i].x + q.x) / 2, y: (pts[i].y + q.y) / 2 }));
return [...pts, ...mids];
};
/** Laufender Zug an einer Schnittlinie: gemeinsamer Undo-Schlüssel, bei Mittel-Griff der eingefügte Knick. */
/** Pixel je Meter beim letzten Zug (Aufräum-Toleranz). */
const sectionPxRef = useRef(0);
const sectionDragRef = useRef<{ id: string; key: string; midIndex: number; bendIndex: number } | null>(null);
// Mit gezeigter Beschriftung dazu ihr Griff (`labelOffset`, s. `treeGrips.ts`).
const treeGrips = (tr: NonNullable<typeof selectedTree>): Vec2[] => treeGripPoints(tr, scaleDenominator);
const selectedRoomId = single(selection, "rooms");
@@ -324,7 +333,8 @@ export function useGripEditing(opts: {
}
if (selectedSectionLine && effectiveDrawingIds.length === 0 && selectedWallIds.length === 0) {
const pts = sectionLineGrips(selectedSectionLine);
pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); });
const nCorner = (selectedSectionLine.bendPoints?.length ?? 0) + 2;
pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push(i < nCorner ? [0, nCorner - 1] : [nCorner, pts.length - 1]); });
return pts;
}
// [68] Baugrube: Umriss-Ecken + Sohlen-Griff (Lage: Schwerpunkt, y um die Sohlenhöhe versetzt).
@@ -925,7 +935,25 @@ export function useGripEditing(opts: {
}
// [176] Schnittlinie: Endpunkt bzw. Knickpunkt live, ein Undo-Schritt je Zug (Kern `grips.rs`).
if (selectedSectionLine && effectiveDrawingIds.length === 0 && selectedWallIds.length === 0) {
storeState().moveSectionLineGrip(selectedSectionLine.id, index, pt);
const l = selectedSectionLine;
const nCorner = (l.bendPoints?.length ?? 0) + 2;
let drag = sectionDragRef.current;
if (!drag || drag.id !== l.id) {
drag = { id: l.id, key: `sectionLineDrag:${l.id}:${Date.now()}`, midIndex: -1, bendIndex: -1 };
sectionDragRef.current = drag;
}
if (drag.midIndex === index) {
// Mittel-Griff, Knick schon eingefügt: er folgt dem Zeiger (Index zählt gegen die alte Punktzahl).
storeState().moveSectionLineGrip(l.id, drag.bendIndex, pt, drag.key);
} else if (index < nCorner) {
storeState().moveSectionLineGrip(l.id, index, pt, drag.key);
} else {
// Erster Zug an einem Mittel-Griff: Knick in dieses Segment einfügen (Griff-Index des Knicks = Segment + 1).
const seg = index - nCorner;
drag.midIndex = index;
drag.bendIndex = seg + 1;
storeState().insertSectionBend(l.id, seg, pt, drag.key);
}
return;
}
// [68] Baugrube: Sohlen-Griff sofort (Höhe), Ecken als Vorschau bis zum Setzen.
@@ -1166,7 +1194,15 @@ export function useGripEditing(opts: {
// Aufräumen nach Abschluss/Verwerfen eines Griff- ODER Kanten-Drags (geteilt
// von onGripEnd/onGripCancel/onEdgeEnd/onEdgeCancel — nie beide gleichzeitig
// aktiv, ein gemeinsames Aufräumen ist daher unschädlich und einfacher).
// [176] Nach einem Zug an einer Schnittlinie: Knicke auf einem Nachbarpunkt / auf der Geraden entfernen
// (gleicher Undo-Schritt wie der Zug).
const tidySectionDrag = () => {
const drag = sectionDragRef.current;
// Zeiger-Genauigkeit: ca. 6 Pixel der Ansicht.
if (drag) storeState().tidySectionLine(drag.id, drag.key, sectionPxRef.current > 0 ? 6 / sectionPxRef.current : undefined);
};
const endEditing = () => {
sectionDragRef.current = null;
setDraft(null);
edgeAppliedDeltaRef.current = null; // Kanten-Drag beendet → Anker zurücksetzen
moveCoincidentRef.current = null; // Körper-Koinzidenz-Gruppe verwerfen
@@ -1262,6 +1298,7 @@ export function useGripEditing(opts: {
const gripHandlers = {
onGripMove: (index: number, raw: Vec2, pxPerMeter: number, mods: ToolMods) => {
sectionPxRef.current = pxPerMeter;
// Schnitt/Ansicht: Höhen-Griff (Wand-Oberkante, Fenster Ober-/Unterkante).
if (!modelEditable && sheet) {
const g = sheetHeightGrips[index];
@@ -1286,6 +1323,7 @@ export function useGripEditing(opts: {
// AKTUELLE — hier noch unveränderte — Position als Flucht-Bezugspunkt
// verankern (s. Kommentar an gripOriginRef).
if (gripDragInfoRef.current === null) {
sectionDragRef.current = null; // [176] neuer Zug: eigener Undo-Schlüssel, kein eingefügter Knick
gripOriginRef.current = grips[index];
const op0 = selectedOpeningId ? (project.openings ?? []).find((o) => o.id === selectedOpeningId) : undefined;
const dir0 = op0 ? openingWallDir() : null;
@@ -1517,6 +1555,7 @@ export function useGripEditing(opts: {
onGripEnd: () => {
commitPendingGrip();
commitPendingBody();
tidySectionDrag();
endEditing();
},
// Bewaffneten Punkt-Griff verwerfen (Escape): exakt auf `origin`
@@ -1530,7 +1569,10 @@ export function useGripEditing(opts: {
pendingGripRef.current = null;
pendingWallGripRef.current = null;
pendingAreaGripRef.current = null;
} else applyGrip(index, origin);
} else if (sectionDragRef.current) {
applyGrip(index, origin);
tidySectionDrag();
} else if (!selectedSectionLine) applyGrip(index, origin);
endEditing();
},
onEdgeEnd: () => {
+4
View File
@@ -126,6 +126,8 @@ export function useProjectActions(
const setCustomPaletteVisible = useStore((s) => s.setCustomPaletteVisible);
const setBuiltinPaletteVisible = useStore((s) => s.setBuiltinPaletteVisible);
const insertDrawingPoint = useStore((s) => s.insertDrawingPoint);
const insertSectionBend = useStore((s) => s.insertSectionBend);
const deleteSectionBend = useStore((s) => s.deleteSectionBend);
const deleteDrawingPoint = useStore((s) => s.deleteDrawingPoint);
const setPolylineVertexType = useStore((s) => s.setPolylineVertexType);
// Wandstile: immutable Patch eines Wandtyps (z. B. Schichtfugen-Stile). Kein
@@ -444,6 +446,8 @@ export function useProjectActions(
setCustomPaletteVisible,
setBuiltinPaletteVisible,
insertDrawingPoint,
insertSectionBend,
deleteSectionBend,
deleteDrawingPoint,
setPolylineVertexType,
patchWallType,