diff --git a/TODO.md b/TODO.md index 6949cbbd..a4525572 100644 --- a/TODO.md +++ b/TODO.md @@ -85,7 +85,7 @@ Wer zu einer ID mehr wissen will (Entscheide, Tests, Bilder), sucht dort nach `* gedämpft (render3d hat nur `set_ghost` für die Hülle); natives Mac-3D-Fenster bekommt nur den Ebenen-Baum, nicht den Darstellungsmodus; Datei-Exporte (OBJ/glTF/IFC/STEP) bleiben vollständig; kein e2e (3D-Pick headless unzuverlässig); nicht in der Tauri-App/auf dem Mac geprüft. · M -- ◐ **[193]** Anwählen/Bearbeiten von Gelände & Co. (12.11., Maintainer, PRIO; Stand 11.11.): **erledigt** — Cmd+A nimmt Gelände, Höhenlinien, Baugrube, Netze, Bilder mit (sichtbare, nicht gesperrte Klasse; reine Funktion `state/selectAll.ts`) und die Schattenfläche der Sonnenstudie (`site: sunStudy`); Entf löscht sie in einem Undo-Schritt (Schatten: blendet `sunStudy.show` aus). Die „nicht lösch-/anwählbare Schraffur" war der Schatten der Sonnenstudie (abgeleitet aus den Geschossen, die Cmd+A nicht erfasst, Loch = Treppenöffnung); er war schon anwählbar ([137]), aber Entf tat nichts. Verschieben/Kopieren/Drehen/Spiegeln für Kontext-Elemente (Kern `cmd_transform.rs`, `contextIds`; Baugrube, Höhenlinien, Netze, Bild); Objekt-Info: Höhenversatz für Gelände/Netz/Höhenlinien/Baugrube und Höhe je Höhenlinie (`state/contextHeight.ts`, TS-Hilfe, später in den Kern). Baugrube war im Grundriss schon anwählbar (Kern-Pick) und hat Eckgriffe (`useGripEditing`); e2e `selectAllContext.spec.ts`. **Offen:** Punkte einer Höhenlinie per Griff ziehen; Gelände-Netz zuschneiden/Punkte editieren; Ziehen im Plan ohne Befehl (Drag-Move) für Kontext; Höhen-Helfer nach Rust; „Entf" auf Baurechtslinie/Ansichtsschatten blendet noch nichts aus. · M +- ◐ **[193]** Anwählen/Bearbeiten von Gelände & Co. (12.11., Maintainer, PRIO; Stand 11.11.): **erledigt** — Cmd+A nimmt Gelände, Höhenlinien, Baugrube, Netze, Bilder mit (sichtbare, nicht gesperrte Klasse; reine Funktion `state/selectAll.ts`) und die Schattenfläche der Sonnenstudie (`site: sunStudy`); Entf löscht sie in einem Undo-Schritt (Schatten: blendet `sunStudy.show` aus). Die „nicht lösch-/anwählbare Schraffur" war der Schatten der Sonnenstudie (abgeleitet aus den Geschossen, die Cmd+A nicht erfasst, Loch = Treppenöffnung); er war schon anwählbar ([137]), aber Entf tat nichts. Verschieben/Kopieren/Drehen/Spiegeln für Kontext-Elemente (Kern `cmd_transform.rs`, `contextIds`; Baugrube, Höhenlinien, Netze, Bild); Objekt-Info: Höhenversatz für Gelände/Netz/Höhenlinien/Baugrube und Höhe je Höhenlinie (`state/contextHeight.ts`, TS-Hilfe, später in den Kern). Baugrube war im Grundriss schon anwählbar (Kern-Pick) und hat Eckgriffe (`useGripEditing`); e2e `selectAllContext.spec.ts`. **Update 11.11. (Rest):** Höhen-Helfer nach Rust (`cmd_context.rs`: `contextOffset`/`contourZ`, TS-Fassung `contextHeight.ts` gelöscht; Store `offsetContextHeight`/`setContourHeight`); Maus-Ziehen im Plan für gewählte Kontext-Elemente (Baugrube, Höhenlinien, Netze, Bild: Vorschau und Ops aus dem Kern-Transform, Fang auf den ersten Punkt, ein Undo-Schritt, `moveContextBy`); Höhenlinien-Punkte als Griffe (`contourGrip`/`contourInsert` in `grips.rs`, Einfüge-Rauten wie [26], ein Undo-Schritt je Zug; ab 600 Punkten keine Griffe, ab 100 keine Rauten); Entf und Cmd+A auf den Ansichts-Schlagschatten (`viewShadows`) blenden `shadows` der Ansicht aus. e2e `contextDrag.spec.ts`. **Offen:** Gelände-Netz zuschneiden/Punkte editieren; Höhenlinien-Punkt löschen (Kontextmenü); Aufräumen eingefügter Punkte beim Zurückziehen. · M - ○ **[192]** Ebenen/Klassen schnell schalten (12.11., Maintainer): Rechtsklick im Ebenen-Panel „Nur diese Ebene anzeigen“, „Diese ausblenden“, „Alle einblenden“; Rechtsklick auf Objekt (Plan/Schnitt/3D) „Ebene des Objekts isolieren/ausblenden“, „Alle Ebenen einblenden“ (stellt Zustand vor dem Isolieren wieder her); optional Kürzel. Sonnet. · S - ○ **[197]** Cmd+3/4 Nachbesserung (12.11., Maintainer): (1) Kamera bleibt bei Cmd+3/Cmd+4 exakt stehen (kein Einpassen; Einpassen nur mit Cmd+Shift+F); (2) Dachfenster/Deckenöffnungen bleiben bei „nur Auswahl“ (eine Wand) sichtbar → Öffnungen nur mit sichtbarem Wirt (Wand, Dach, Decke) oder selbst gewählt (`model3d::ElementSelection`). e2e. · S - ○ **[196]** (12.11., Maintainer, PRIO) (1) Raster-Bodenschraffur in Gebäudeform (mit Loch an der Wendeltreppe) im EG-Grundriss lässt sich weder anwählen noch löschen — Vermutung: Ansichtsschraffur der Decke des darunterliegenden Geschosses (UG-Decke von oben) bzw. Bodenbelag; klären (Musterhaus komplex EG), Pick wählt das Quell-Element (auch wenn es zu einem anderen Geschoss gehört), Entf löscht es bzw. Hinweis. (2) Zeichnungsebenen-Panel: Auge/„sichtbar“ bei einer Ansicht blendet bei den Grundrissen alle Geschosse ein → Auge schaltet nur die eigene Ebene. (3) Auge eines Geschosses aus → Geschoss fehlt auch im 3D (heute zeigt 3D immer alle Geschosse; Filter wie Klassen [180] im 3D-Cache-Ausgang). e2e für alles. · S diff --git a/e2e/contextDrag.spec.ts b/e2e/contextDrag.spec.ts new file mode 100644 index 00000000..b6b37151 --- /dev/null +++ b/e2e/contextDrag.spec.ts @@ -0,0 +1,91 @@ +// [193] Kontext-Elemente mit der Maus bearbeiten (Mac-Befund: Baugrube/Höhenlinien liessen sich nur über den Befehl +// „Verschieben" versetzen, Höhenlinien-Punkte gar nicht): Baugrube anklicken und im Plan ziehen → verschoben, ein Undo-Schritt; +// Höhenlinien-Satz wählen, einen Punkt per Griff ziehen → ein Undo-Schritt. +import type { Page } from "@playwright/test"; +import { blurFocus, discardIfAsked, elementRows, expect, fileMenu, openTab, showSnapshot, test } from "./app"; +import type {} from "../src/state/testHooks"; // Typ von window.__dossierTest + +async function modelToClient(page: Page, x: number, y: number): Promise<{ x: number; y: number }> { + return page.locator("svg.plan-svg").first().evaluate( + (el, [x, y]) => { + 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 + (x * 90 - ox - vx) * s, y: r.top + (r.height - vh * s) / 2 + (-y * 90 - oy - vy) * s }; + }, + [x, y], + ); +} + +const ctx = (page: Page) => page.evaluate(() => window.__dossierTest!.context()); +const objInfo = (page: Page) => page.locator(".objinfo-panel").first(); +const firstOf = async (page: Page, type: string) => (await ctx(page)).find((c) => c.type === type)!.first!; + +async function openComplex(page: Page): Promise { + await page.goto("/?dossierTest"); + await page.getByRole("button", { name: /Neues Projekt/ }).first().click(); + await expect(page.getByRole("group", { name: "Befehlszeile" })).toBeVisible(); + await fileMenu(page, /Musterhaus \(komplex\)/); + await discardIfAsked(page); + await expect(page.locator(".project-name")).toHaveText("Musterhaus komplex", { timeout: 30_000 }); + await expect(page.locator("svg.plan-svg").first()).toBeVisible({ timeout: 30_000 }); +} + +test("Musterhaus komplex: Baugrube anklicken und mit der Maus ziehen, Rückgängig", async ({ page }) => { + test.setTimeout(120_000); + await openComplex(page); + await showSnapshot(page, "EG 1:100"); + await openTab(page, "Objekt-Info"); + // Klick in die Südwest-Böschung der Baugrube (ausserhalb der Sohle, weg von Wänden und Griffen). + const at = await modelToClient(page, -1.6, 4); + await expect(async () => { + await page.keyboard.press("Escape"); + await page.mouse.click(at.x, at.y); + await expect(objInfo(page)).toContainText("Baugrube", { timeout: 1000 }); + }).toPass({ timeout: 30_000 }); + + const p0 = await firstOf(page, "excavation"); + await page.mouse.move(at.x, at.y); + await page.mouse.down(); + await page.mouse.move(at.x + 30, at.y - 20, { steps: 8 }); + await page.mouse.move(at.x + 60, at.y - 40, { steps: 8 }); + await page.mouse.up(); + await expect.poll(async () => (await firstOf(page, "excavation")).x).toBeGreaterThan(p0.x + 0.2); + const p1 = await firstOf(page, "excavation"); + expect(p1.y).toBeGreaterThan(p0.y + 0.1); + // Es bleibt ein Element, nur verschoben. + expect((await ctx(page)).filter((c) => c.type === "excavation")).toHaveLength(1); + + await blurFocus(page); + await page.keyboard.press("ControlOrMeta+z"); + expect(await firstOf(page, "excavation")).toEqual(p0); +}); + +test("Musterhaus komplex: Höhenlinien-Punkt per Griff ziehen, ein Undo-Schritt", async ({ page }) => { + test.setTimeout(120_000); + await openComplex(page); + await showSnapshot(page, "Situation 1:500"); + await openTab(page, "Elemente"); + await elementRows(page).filter({ hasText: "Höhenlinien (Vermessung)" }).first().click(); + const grips = page.locator(".plan-grip:not(.plan-grip-insert)"); + await expect.poll(() => grips.count(), { timeout: 30_000 }).toBeGreaterThan(20); + + const p0 = await firstOf(page, "contourSet"); + const g = await modelToClient(page, p0.x, p0.y); + // Ein Griff bleibt nach dem Loslassen „bewaffnet" und folgt dem Zeiger, bis ein Klick ihn setzt. + await page.mouse.move(g.x, g.y); + await page.mouse.down(); + await page.mouse.move(g.x + 10, g.y - 6, { steps: 6 }); + await page.mouse.up(); + await page.mouse.click(g.x + 10, g.y - 6); + await expect.poll(async () => (await firstOf(page, "contourSet")).x).not.toBe(p0.x); + const p1 = await firstOf(page, "contourSet"); + + // Ein Undo-Schritt für den ganzen Zug. + await blurFocus(page); + await page.keyboard.press("ControlOrMeta+z"); + expect(await firstOf(page, "contourSet")).toEqual(p0); + expect(p1).not.toEqual(p0); +}); diff --git a/src-tauri/core/src/README.md b/src-tauri/core/src/README.md index 9b8824ef..83843365 100644 --- a/src-tauri/core/src/README.md +++ b/src-tauri/core/src/README.md @@ -72,6 +72,7 @@ Neues Modul: `.rs` und `mod` in `lib.rs`, Bindungen in `web/.rs` u | `cmd_create.rs` | Zeichenbefehle für Bauteile: neue Elemente, Vorschau, Treffer | | `cmd_draw.rs`, `cmd_edit.rs`, `cmd_split.rs`, `cmd_paste.rs` | 2D zeichnen und bemassen, bearbeiten, teilen, einfügen | | `cmd_transform.rs`, `cmd_wall_edit.rs`, `cmd_solid.rs` | Transformieren; Wände bearbeiten; Körper, Gelände, Sonderbefehle | +| `cmd_context.rs` | [193] Höhenversatz und Höhe je Höhenlinie von Gelände-/Umgebungs-Elementen (`contextOffset`, `contourZ`) | | `grips.rs`, `grip_drag.rs` | Griffe: Geometrie und Rechnung je Mausschritt | | `sheet_height.rs` | [187] Höhen-Griffe im Schnitt/in der Ansicht (Wand, Öffnung, Decke): Vorschau-Kanten, Fang an Koten, Änderung am Bauteil (Griff-Anfrage `sheetHeight`) | | `snap.rs`, `snap_model.rs` | Objektfang | diff --git a/src-tauri/core/src/cmd_context.rs b/src-tauri/core/src/cmd_context.rs new file mode 100644 index 00000000..a69cbd04 --- /dev/null +++ b/src-tauri/core/src/cmd_context.rs @@ -0,0 +1,124 @@ +//! [193] Höhe von Gelände-/Umgebungs-Elementen als Befehle (vorher `src/state/contextHeight.ts`): +//! `contextOffset` versetzt alle Höhen eines Elements um `dz` (Netz-z, Höhenlinien-z, Baugruben-Sohle), +//! `contourZ` setzt die Höhe einer einzelnen Höhenlinie. Ergebnis: ein `Replace` des Elements in `context` +//! (leer = Art ohne Höhe, keine Änderung oder ungültige Eingabe). + +use crate::json_util::{arr, field, js_num, num_of, with}; +use crate::ops::{id_of, Op}; +use serde_json::{Map, Value}; + +fn element<'a>(root: &'a Map, id: &str) -> Option<&'a Value> { + arr(root.get("context")).iter().find(|e| id_of(e) == Some(id)) +} + +fn kind(e: &Value) -> &str { + field(e, "type").and_then(Value::as_str).unwrap_or("") +} + +/// Alle Höhen von `e` um `dz` Meter versetzt; `None` bei Art ohne Höhe oder `dz` = 0/ungültig. +pub fn height_offset(e: &Value, dz: f64) -> Option { + if !dz.is_finite() || dz == 0.0 { + return None; + } + match kind(e) { + "terrainMesh" | "importedMesh" => { + let pos: Vec = arr(field(e, "positions")) + .iter() + .enumerate() + .map(|(i, v)| if i % 3 == 2 { js_num(num_of(Some(v)) + dz) } else { v.clone() }) + .collect(); + Some(with(e, "positions", Value::Array(pos))) + } + "contourSet" => { + let cs: Vec = arr(field(e, "contours")).iter().map(|c| with(c, "z", js_num(num_of(field(c, "z")) + dz))).collect(); + Some(with(e, "contours", Value::Array(cs))) + } + "excavation" => Some(with(e, "bottom", js_num(num_of(field(e, "bottom")) + dz))), + _ => None, + } +} + +/// Höhe der Höhenlinie `index` eines Höhenlinien-Satzes auf `z` setzen. +pub fn contour_height(e: &Value, index: usize, z: f64) -> Option { + if kind(e) != "contourSet" || !z.is_finite() { + return None; + } + let cs = arr(field(e, "contours")); + let c = cs.get(index)?; + if num_of(field(c, "z")) == z { + return None; + } + let mut out = cs.to_vec(); + out[index] = with(c, "z", js_num(z)); + Some(with(e, "contours", Value::Array(out))) +} + +/// Ops der Höhen-Befehle (`None` = fremder Befehl). +pub fn ops(root: &Map, v: &Value) -> Option> { + let cmd = v.get("cmd").and_then(Value::as_str)?; + if cmd != "contextOffset" && cmd != "contourZ" { + return None; + } + let num = |k: &str| v.get(k).and_then(Value::as_f64).unwrap_or(f64::NAN); + let patched = v.get("id").and_then(Value::as_str).and_then(|id| element(root, id)).and_then(|e| { + if cmd == "contextOffset" { + height_offset(e, num("dz")) + } else { + let i = num("index"); + if i.is_finite() && i >= 0.0 { contour_height(e, i as usize, num("z")) } else { None } + } + }); + Some(patched.map(|entity| vec![Op::Replace { collection: "context".into(), entity }]).unwrap_or_default()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn root() -> Map { + json!({"context":[ + {"id":"tm","type":"terrainMesh","positions":[0,0,5, 1,0,6, 0,1,7],"indices":[0,1,2]}, + {"id":"hl","type":"contourSet","contours":[{"z":500,"pts":[],"closed":false},{"z":501,"pts":[],"closed":false}]}, + {"id":"bg","type":"excavation","bottom":-3,"outline":[]}, + {"id":"im","type":"image"}]}) + .as_object() + .unwrap() + .clone() + } + + fn run(v: Value) -> Vec { + ops(&root(), &v).unwrap().iter().map(|o| o.to_json()).collect() + } + + #[test] + fn versatz_je_art() { + let o = run(json!({"cmd":"contextOffset","id":"tm","dz":-1.5})); + assert_eq!(o[0]["entity"]["positions"], json!([0, 0, 3.5, 1, 0, 4.5, 0, 1, 5.5])); + assert_eq!(o[0]["entity"]["indices"], json!([0, 1, 2])); + let o = run(json!({"cmd":"contextOffset","id":"hl","dz":2})); + assert_eq!(o[0]["entity"]["contours"][0]["z"], json!(502)); + assert_eq!(o[0]["entity"]["contours"][1]["z"], json!(503)); + let o = run(json!({"cmd":"contextOffset","id":"bg","dz":0.5})); + assert_eq!(o[0]["entity"]["bottom"], json!(-2.5)); + assert_eq!(o[0]["collection"], "context"); + } + + #[test] + fn keine_aenderung() { + assert!(run(json!({"cmd":"contextOffset","id":"hl","dz":0})).is_empty()); + assert!(run(json!({"cmd":"contextOffset","id":"im","dz":1})).is_empty()); + assert!(run(json!({"cmd":"contextOffset","id":"nix","dz":1})).is_empty()); + assert!(run(json!({"cmd":"contextOffset","id":"hl"})).is_empty()); + } + + #[test] + fn hoehe_einer_linie() { + let o = run(json!({"cmd":"contourZ","id":"hl","index":1,"z":510})); + assert_eq!(o[0]["entity"]["contours"][0]["z"], json!(500)); + assert_eq!(o[0]["entity"]["contours"][1]["z"], json!(510)); + assert!(run(json!({"cmd":"contourZ","id":"hl","index":1,"z":501})).is_empty()); + assert!(run(json!({"cmd":"contourZ","id":"hl","index":7,"z":1})).is_empty()); + assert!(run(json!({"cmd":"contourZ","id":"tm","index":0,"z":1})).is_empty()); + } +} diff --git a/src-tauri/core/src/commands.rs b/src-tauri/core/src/commands.rs index d8731494..ce781c47 100644 --- a/src-tauri/core/src/commands.rs +++ b/src-tauri/core/src/commands.rs @@ -35,6 +35,9 @@ pub fn ops(root: &Map, p: &Project, text: &str) -> Result if let Some(ops) = crate::cmd_create::ops(root, p, &v) { return Ok(ops); } + if let Some(ops) = crate::cmd_context::ops(root, &v) { + return Ok(ops); + } Ok(match cmd { "transform" => crate::cmd_transform::transform_ops(root, p, &parse(&v, cmd)?), "align" => crate::cmd_transform::align_ops(root, &ids("ids"), &s("mode")), diff --git a/src-tauri/core/src/grips.rs b/src-tauri/core/src/grips.rs index 7e5f5a5c..0361127d 100644 --- a/src-tauri/core/src/grips.rs +++ b/src-tauri/core/src/grips.rs @@ -306,6 +306,15 @@ pub fn run(lk: &Lookup, req: &Request) -> Result { }) .into() } + // [193] Höhenlinien-Punkt ziehen bzw. einfügen: flacher Index über alle Linien des Satzes (Punkt-Index bzw. Segment-Index). + "contourGrip" => { + let (index, (x, y)) = (r.n("index"), r.p("pt")); + patch("context", r.s("id"), &|e| contour_edit(e, index, Some((x, y)), false)).into() + } + "contourInsert" => { + let (seg, (x, y)) = (r.n("seg"), r.p("pt")); + patch("context", r.s("id"), &|e| contour_edit(e, seg, Some((x, y)), true)).into() + } "excavationEdge" => { let (a, b, (dx, dy)) = (r.n("a"), r.n("b"), r.p("delta")); patch("context", r.s("id"), &|e| Some(with(e, "outline", move_polygon_edge(field(e, "outline")?.as_array()?, a, b, dx, dy, true)?))).into() @@ -1350,6 +1359,39 @@ fn shift_edge_list(e: Value, field_name: &str, off: usize, shift: &EdgeShift) -> with(&e, field_name, Value::Array(v)) } +/// [193] Punkt `flat` (flach über alle Linien eines Höhenlinien-Satzes) auf `at` setzen bzw. (`insert`) hinter dem +/// Punkt `flat` einen Punkt einfügen (Segment von `flat` zum Nachfolger; geschlossen: der letzte schliesst zum Anfang, +/// offen: der letzte hat kein Segment). Eine wahre Kurve (`curve`) fällt weg. +fn contour_edit(e: &Value, flat: f64, at: Option<(f64, f64)>, insert: bool) -> Option { + let (x, y) = at.filter(|(x, y)| x.is_finite() && y.is_finite())?; + if field(e, "type").and_then(Value::as_str) != Some("contourSet") { + return None; + } + let cs = arr(field(e, "contours")); + let mut off = 0usize; + for (ci, c) in cs.iter().enumerate() { + let pts = arr(field(c, "pts")); + let closed = truthy(field(c, "closed")); + let count = pts.len(); + let has_seg = |i: usize| count >= 2 && (closed || i + 1 < count); + if let Some(i) = index_in(flat - off as f64, count).filter(|i| !insert || has_seg(*i)) { + let new_pts = if insert { + let mut v = pts.to_vec(); + v.insert(i + 1, pt(x, y)); + Value::Array(v) + } else { + replace_at(pts, i as f64, &pt(x, y)) + }; + let nc = with_opt(&with(c, "pts", new_pts), vec![("curve", None)]); + let mut out = cs.to_vec(); + out[ci] = nc; + return Some(with(e, "contours", Value::Array(out))); + } + off += count; + } + None +} + /// [26] Ecke einfügen/löschen/aufräumen an einem Umriss-Element (s. `ringInsert`). fn ring_edit(e: &Value, kind: &str, flat: f64, edit: &RingEdit) -> Option { if truthy(field(e, "locked")) { @@ -1935,6 +1977,28 @@ mod tests { assert_eq!(e["outline"][2], json!({"x": 4, "y": 4})); } + /// [193] Höhenlinien-Satz: Punkt ziehen (flacher Index über alle Linien) und Punkt hinter einem Segment einfügen. + #[test] + fn hoehenlinien_griffe() { + let r = root(json!({"context": [{"id": "hl", "type": "contourSet", "contours": [ + {"z": 1, "closed": false, "pts": [{"x": 0, "y": 0}, {"x": 2, "y": 0}, {"x": 4, "y": 0}]}, + {"z": 2, "closed": true, "curve": {"cx": 0, "cy": 0}, "pts": [{"x": 0, "y": 1}, {"x": 2, "y": 1}, {"x": 2, "y": 3}]}]}]})); + let ent = |v: Value| run(&Lookup::plain(&r), &rq(v)).unwrap().ops.first().map(|o| o.to_json()["entity"].clone()); + let e = ent(json!({"op": "contourGrip", "id": "hl", "index": 4, "pt": [9, 9]})).unwrap(); + assert_eq!(e["contours"][1]["pts"][1], json!({"x": 9, "y": 9})); + assert!(e["contours"][1].get("curve").is_none()); + assert_eq!(e["contours"][0]["pts"][1], json!({"x": 2, "y": 0})); + assert!(ent(json!({"op": "contourGrip", "id": "hl", "index": 6, "pt": [9, 9]})).is_none()); + // Offene Linie: Segmente ab Punkt 0 und 1 (Punkt 2 hat keins); geschlossene: ab 3, 4, 5 (5 schliesst zum Anfang). + assert!(ent(json!({"op": "contourInsert", "id": "hl", "seg": 2, "pt": [3, 1]})).is_none()); + let e = ent(json!({"op": "contourInsert", "id": "hl", "seg": 1, "pt": [3, 1]})).unwrap(); + assert_eq!(e["contours"][0]["pts"].as_array().unwrap().len(), 4); + assert_eq!(e["contours"][0]["pts"][2], json!({"x": 3, "y": 1})); + let e = ent(json!({"op": "contourInsert", "id": "hl", "seg": 5, "pt": [1, 2]})).unwrap(); + assert_eq!(e["contours"][1]["pts"][3], json!({"x": 1, "y": 2})); + assert!(ent(json!({"op": "contourInsert", "id": "hl", "seg": 6, "pt": [1, 2]})).is_none()); + } + /// [26] Dach: Ecken und Kanten von Umriss und Hof über den flachen Index; schiefer Umriss bleibt schief. #[test] fn dach_griffe_umriss_und_hof() { diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index d6800aba..c743806d 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -123,6 +123,7 @@ pub mod import_context; pub mod import_ifc; pub mod cmd_paste; pub mod cmd_split; +pub mod cmd_context; pub mod cmd_wall_edit; pub mod snap_model; pub mod solid_specs; diff --git a/src/geometry/grips.ts b/src/geometry/grips.ts index 5f9e4d71..fee51ae1 100644 --- a/src/geometry/grips.ts +++ b/src/geometry/grips.ts @@ -19,7 +19,7 @@ import type { SheetHeightKind } from "./gripDrag"; type P = [number, number]; /** Elemente mit Umriss-Ring, an denen sich Ecken einfügen/löschen lassen (geschlossene Polylinie eingeschlossen). */ -export type RingKind = "roof" | "ceiling" | "room" | "excavation" | "polyline"; +export type RingKind = "roof" | "ceiling" | "room" | "excavation" | "polyline" | "contours"; /** Eine Griff-Änderung für den Kern (`grips.rs::run`); Zahlen dürfen NaN/±∞ sein (Marken). */ export type GripRequest = @@ -33,6 +33,9 @@ export type GripRequest = | { op: "roomStamp"; id: string; delta: P; pt?: P } | { op: "ceilingEdge" | "roomEdge"; id: string; a: number; b: number; delta: P } | { op: "excavationGrip"; id: string; index: number; pt: P } + // [193] Höhenlinien-Satz: Punkt (flacher Index über alle Linien) ziehen bzw. hinter Punkt `seg` einfügen (Kern `contour_edit`). + | { op: "contourGrip"; id: string; index: number; pt: P } + | { op: "contourInsert"; id: string; seg: number; pt: P } // [26] Dach: Ecke bzw. Kante von Umriss/Hof, flacher Index (erst `outline`, dann `holes` Ring für Ring). | { op: "roofVertex"; id: string; index: number; pt: P } | { op: "roofEdge"; id: string; a: number; b: number; delta: P } diff --git a/src/panels/ContextObjectProps.tsx b/src/panels/ContextObjectProps.tsx index 7d88afb6..8cd2f3f0 100644 --- a/src/panels/ContextObjectProps.tsx +++ b/src/panels/ContextObjectProps.tsx @@ -12,7 +12,6 @@ import type { ContextObject } from "../model/types"; import { flattenCategories } from "../model/types"; import { resmoothGridTerrain } from "../model/terrain"; import { useMemo, useState } from "react"; -import { contourHeightPatch, heightOffsetPatch } from "../state/contextHeight"; import type { ExcavationQuantity } from "../core"; /** Zahl-Eingabe für ein Feld eines Kontext-Objekts (leer = Standard, ungültig = keine Änderung). */ @@ -68,12 +67,12 @@ const RESMOOTH_PASSES = [1, 2, 4] as const; /** [193] Höhenversatz (alle Höhen um dz) und, bei Höhenlinien, die Höhe je Linie. */ function HeightFields({ obj }: { obj: ContextObject }) { - const host = usePanelHost(); + const offsetContextHeight = useStore((s) => s.offsetContextHeight); + const setContourHeight = useStore((s) => s.setContourHeight); const [dz, setDz] = useState(""); if (obj.type === "image") return null; const apply = () => { - const patch = dz.trim() === "" ? null : heightOffsetPatch(obj, Number(dz.replace(",", "."))); - if (patch) host.onPatchContextObject(obj.id, patch); + if (dz.trim() !== "") offsetContextHeight(obj.id, Number(dz.replace(",", "."))); setDz(""); }; return ( @@ -104,8 +103,7 @@ function HeightFields({ obj }: { obj: ContextObject }) { data-testid={`contour-z-${i}`} value={c.z} onChange={(e) => { - const patch = e.target.value.trim() === "" ? null : contourHeightPatch(obj, i, Number(e.target.value)); - if (patch) host.onPatchContextObject(obj.id, patch, `site-${obj.id}-contourZ-${i}`); + if (e.target.value.trim() !== "") setContourHeight(obj.id, i, Number(e.target.value), `site-${obj.id}-contourZ-${i}`); }} /> diff --git a/src/state/contextDrag.ts b/src/state/contextDrag.ts new file mode 100644 index 00000000..22852a7a --- /dev/null +++ b/src/state/contextDrag.ts @@ -0,0 +1,23 @@ +// [193] Maus-Ziehen von Gelände-/Umgebungs-Elementen im Plan: Bezugspunkt für den Fang. +// Das Verschieben selbst (Ops) und die Vorschau stammen aus dem Kern (`cmd_transform.rs`). + +import type { Project, Vec2 } from "../model/types"; + +/** Ein Punkt des Elements (erste Ecke / erster Punkt / Rahmen-Ecke), der beim Ziehen am Fang teilnimmt. */ +export function contextAnchor(project: Project, id: string): Vec2 | null { + const o = (project.context ?? []).find((c) => c.id === id); + if (!o) return null; + switch (o.type) { + case "excavation": + return o.outline[0] ?? null; + case "contourSet": + return o.contours.find((c) => c.pts.length > 0)?.pts[0] ?? null; + case "terrainMesh": + case "importedMesh": + return o.positions.length >= 2 ? { x: o.positions[0], y: o.positions[1] } : null; + case "image": + return o.min; + default: + return null; + } +} diff --git a/src/state/contextEdit.test.ts b/src/state/contextEdit.test.ts new file mode 100644 index 00000000..941707c5 --- /dev/null +++ b/src/state/contextEdit.test.ts @@ -0,0 +1,60 @@ +// [193] Gelände & Co.: Höhenversatz/Höhe je Höhenlinie (Kern `cmd_context.rs`), Punkte einer Höhenlinie per Griff +// (Kern `grips.rs::contour_edit`), Verschieben über den Kern, Bezugspunkt für den Fang beim Ziehen im Plan. + +import { describe, expect, it } from "vitest"; +import { documentFor } from "../core/document"; +import { sampleProject } from "../model/sampleProject"; +import type { ContextObject, ContourSet, Excavation, Project } from "../model/types"; +import { contextAnchor } from "./contextDrag"; +import { transformOps } from "../tools/transform"; + +const hl = { + id: "hl", + type: "contourSet", + categoryCode: "02", + name: "Höhenlinien", + contours: [ + { z: 500, closed: false, pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 4, y: 0 }] }, + { z: 501, closed: true, pts: [{ x: 0, y: 1 }, { x: 2, y: 1 }, { x: 2, y: 3 }] }, + ], +} as ContourSet; +const pit = { id: "bg", type: "excavation", categoryCode: "07", name: "Baugrube", outline: [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 4 }], bottom: -2 } as Excavation; +const project = (): Project => ({ ...sampleProject, context: [hl, pit] as ContextObject[] }); + +function commit(base: Project, req: object, id: string): T { + const r = documentFor(base).commitGrip(base, req, undefined, 1); + if ("problems" in r) throw new Error(r.problems.join(";")); + return r.project.context!.find((c) => c.id === id) as T; +} + +describe("Höhen über den Kern", () => { + it("Höhenversatz und Höhe je Linie als Ops", () => { + const p = project(); + expect(documentFor(p).cmdOps({ cmd: "contextOffset", id: "bg", dz: 1.5 })).toHaveLength(1); + expect(documentFor(p).cmdOps({ cmd: "contextOffset", id: "bg", dz: 0 })).toEqual([]); + const z = documentFor(p).cmdOps({ cmd: "contourZ", id: "hl", index: 1, z: 510 }); + expect(JSON.stringify(z)).toContain("510"); + expect(documentFor(p).cmdOps({ cmd: "contourZ", id: "hl", index: 1, z: 501 })).toEqual([]); + }); +}); + +describe("Höhenlinien: Punkte per Griff", () => { + it("Punkt ziehen (flacher Index über alle Linien) und Punkt einfügen", () => { + const p = project(); + expect(commit(p, { op: "contourGrip", id: "hl", index: 4, pt: [9, 9] }, "hl").contours[1].pts[1]).toEqual({ x: 9, y: 9 }); + const ins = commit(p, { op: "contourInsert", id: "hl", seg: 1, pt: [3, 1] }, "hl"); + expect(ins.contours[0].pts).toHaveLength(4); + expect(ins.contours[0].pts[2]).toEqual({ x: 3, y: 1 }); + }); +}); + +describe("Kontext verschieben (Maus-Ziehen im Plan)", () => { + it("ein Op-Satz verschiebt alle gewählten Elemente; Bezugspunkt je Art", () => { + const p = project(); + const ops = transformOps(p, { wallIds: [], drawingId: null, contextIds: ["bg", "hl"] }, "move", [{ x: 0, y: 0 }, { x: 3, y: -1 }], "move", 1); + expect(ops).toHaveLength(2); + expect(contextAnchor(p, "bg")).toEqual({ x: 0, y: 0 }); + expect(contextAnchor(p, "hl")).toEqual({ x: 0, y: 0 }); + expect(contextAnchor(p, "nix")).toBeNull(); + }); +}); diff --git a/src/state/contextHeight.test.ts b/src/state/contextHeight.test.ts deleted file mode 100644 index fe023bb5..00000000 --- a/src/state/contextHeight.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { contourHeightPatch, heightOffsetPatch } from "./contextHeight"; -import type { ContextObject } from "../model/types"; - -const base = { id: "a", name: "A", categoryCode: "02" }; -const set = { ...base, type: "contourSet", contours: [{ z: 500, pts: [], closed: false }, { z: 501, pts: [], closed: false }] } as ContextObject; - -describe("Höhe von Gelände-Elementen", () => { - it("Netz: nur z wird versetzt", () => { - const o = { ...base, type: "terrainMesh", positions: [0, 0, 5, 1, 0, 6, 0, 1, 7], indices: [0, 1, 2] } as ContextObject; - expect(heightOffsetPatch(o, -1.5)).toEqual({ positions: [0, 0, 3.5, 1, 0, 4.5, 0, 1, 5.5] }); - }); - it("Höhenlinien und Baugrube", () => { - expect(heightOffsetPatch(set, 2)).toEqual({ contours: [{ z: 502, pts: [], closed: false }, { z: 503, pts: [], closed: false }] }); - expect(heightOffsetPatch({ ...base, type: "excavation", outline: [], bottom: -3 } as ContextObject, 0.5)).toEqual({ bottom: -2.5 }); - }); - it("keine Änderung bei 0/NaN; Höhe einer Linie", () => { - expect(heightOffsetPatch(set, 0)).toBeNull(); - expect(heightOffsetPatch(set, NaN)).toBeNull(); - expect(contourHeightPatch(set, 1, 510)).toEqual({ contours: [{ z: 500, pts: [], closed: false }, { z: 510, pts: [], closed: false }] }); - expect(contourHeightPatch(set, 1, 501)).toBeNull(); - expect(contourHeightPatch(set, 7, 1)).toBeNull(); - }); -}); diff --git a/src/state/contextHeight.ts b/src/state/contextHeight.ts deleted file mode 100644 index 218f76f4..00000000 --- a/src/state/contextHeight.ts +++ /dev/null @@ -1,29 +0,0 @@ -// [193] Höhe von Gelände-/Umgebungs-Elementen ändern: Höhenversatz (alle z um dz) und die Höhe einer einzelnen -// Höhenlinie. Liefert Feld-Patches für `patchContextObject`; `null` = Art ohne Höhe (Luftbild) oder keine Änderung. - -import type { ContextObject, Contour } from "../model/types"; - -/** Alle Höhen des Elements um `dz` Meter versetzen: Netz-z, Höhenlinien-z, Baugruben-Sohle. */ -export function heightOffsetPatch(obj: ContextObject, dz: number): Record | null { - if (!Number.isFinite(dz) || dz === 0) return null; - switch (obj.type) { - case "terrainMesh": - case "importedMesh": { - const pos = obj.positions.slice(); - for (let i = 2; i < pos.length; i += 3) pos[i] += dz; - return { positions: pos }; - } - case "contourSet": - return { contours: obj.contours.map((c): Contour => ({ ...c, z: c.z + dz })) }; - case "excavation": - return { bottom: obj.bottom + dz }; - default: - return null; - } -} - -/** Höhe der Höhenlinie `index` eines Höhenlinien-Satzes setzen. */ -export function contourHeightPatch(obj: ContextObject, index: number, z: number): Record | null { - if (obj.type !== "contourSet" || !Number.isFinite(z) || !obj.contours[index] || obj.contours[index].z === z) return null; - return { contours: obj.contours.map((c, i): Contour => (i === index ? { ...c, z } : c)) }; -} diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index a197de34..47c71a33 100644 --- a/src/state/projectSlice.ts +++ b/src/state/projectSlice.ts @@ -1276,13 +1276,14 @@ export function createProjectSlice( : kind === "ceiling" ? { op: "ceilingGrip", id, index, pt: p } : kind === "room" ? { op: "roomGrip", id, index, pt: p } : kind === "excavation" ? { op: "excavationGrip", id, index, pt: p } + : kind === "contours" ? { op: "contourGrip", id, index, pt: p } : { op: "moveGrip", drawingId: id, wallId: null, index, pt: p, scale: DEFAULT_SCALE_DENOMINATOR }; applyGrip(req, coalesceKey ?? `moveRingVertex:${kind}:${id}:${index}`); }, insertRingVertex: (kind, id, seg, pt, coalesceKey) => - applyGrip(kind === "polyline" ? { op: "insertPoint", id, seg, pt: gripPt(pt) } : { op: "ringInsert", kind, id, seg, pt: gripPt(pt) }, coalesceKey), + applyGrip(kind === "contours" ? { op: "contourInsert", id, seg, pt: gripPt(pt) } : kind === "polyline" ? { op: "insertPoint", id, seg, pt: gripPt(pt) } : { op: "ringInsert", kind, id, seg, pt: gripPt(pt) }, coalesceKey), deleteRingVertex: (kind, id, index) => - applyGrip(kind === "polyline" ? { op: "deletePoint", id, index } : { op: "ringDelete", kind, id, index }), + kind === "contours" ? undefined : applyGrip(kind === "polyline" ? { op: "deletePoint", id, index } : { op: "ringDelete", kind, id, index }), tidyRingVertex: (kind, id, index, coalesceKey, tol) => applyGrip({ op: "ringTidy", kind, id, index, ...(tol != null ? { tol } : {}) }, coalesceKey), tidySectionLine: (id, coalesceKey, tol) => applyGrip({ op: "sectionLineTidy", id, ...(tol != null ? { tol } : {}) }, coalesceKey), diff --git a/src/state/selectAll.test.ts b/src/state/selectAll.test.ts index a3a03369..a63af755 100644 --- a/src/state/selectAll.test.ts +++ b/src/state/selectAll.test.ts @@ -49,4 +49,10 @@ describe("selectAllIds", () => { const ogWall = p.walls.find((w) => w.floorId === "og")!; expect(ids.walls).not.toContain(ogWall.id); }); + + it("wählt den Schlagschatten einer Ansicht mit (Entf schaltet ihn ab), solange er eingeschaltet ist", () => { + expect(selectAllIds(p, "ansicht-sued").site).toEqual(["viewShadows"]); + const off = { ...p, drawingLevels: p.drawingLevels.map((l) => (l.id === "ansicht-sued" ? { ...l, shadows: false } : l)) }; + expect(selectAllIds(off, "ansicht-sued").site).toEqual([]); + }); }); diff --git a/src/state/selectAll.ts b/src/state/selectAll.ts index 3d57139a..8442cc01 100644 --- a/src/state/selectAll.ts +++ b/src/state/selectAll.ts @@ -38,7 +38,8 @@ export function selectAllIds(project: Project, levelId: string): Partial l.id === levelId); - const site = project.sunStudy?.show && level?.kind === "floor" ? ["sunStudy"] : []; + // [193] dito der Schlagschatten der Ansicht (`DrawingLevel.shadows`), nur in einer Ansicht. + const site = project.sunStudy?.show && level?.kind === "floor" ? ["sunStudy"] : level?.kind === "elevation" && level.shadows ? ["viewShadows"] : []; return { site, walls: wallIds, diff --git a/src/state/siteSlice.ts b/src/state/siteSlice.ts index b58d7822..43100742 100644 --- a/src/state/siteSlice.ts +++ b/src/state/siteSlice.ts @@ -9,7 +9,9 @@ // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import { generateTerrainFromContours, resmoothGridTerrain, type TerrainOptions } from "../model/terrain"; -import type { ContextObject, Project } from "../model/types"; +import type { ContextObject, Project, Vec2 } from "../model/types"; +import { documentFor } from "../core/document"; +import { transformOps } from "../tools/transform"; import { addItems, fieldOps, patchItem, removeItems } from "../core/opsBuild"; import type { CoreOp } from "../core/ops"; import { ensureContextCategories } from "../model/contextCategories"; @@ -32,6 +34,12 @@ export interface SiteSlice { * null, wenn der ContourSet nicht existiert / kein Mesh entsteht. */ generateTerrain: (contourSetId: string, opts?: TerrainOptions) => string | null; + /** [193] Alle Höhen eines Elements um `dz` Meter versetzen (Netz-z, Höhenlinien-z, Baugruben-Sohle; Kern `cmd_context.rs`). */ + offsetContextHeight: (id: string, dz: number) => void; + /** [193] Höhe der Höhenlinie `index` eines Höhenlinien-Satzes setzen (Kern `cmd_context.rs`); `coalesceKey` für Tippen. */ + setContourHeight: (id: string, index: number, z: number, coalesceKey?: string) => void; + /** [193] Kontext-Elemente um `delta` verschieben (Maus-Ziehen im Plan; Kern `cmd_transform.rs`), ein Undo-Schritt. */ + moveContextBy: (ids: string[], delta: Vec2) => void; /** [T6]/[68] Ändert Felder eines Kontext-Objekts (Gelände, Baugrube) in einem Schritt; `coalesceKey` für Tippen. */ patchContextObject: (id: string, patch: Record, coalesceKey?: string) => void; /** @@ -93,6 +101,22 @@ export function createSiteSlice( get().applyChange((p) => removeItems(p, "context", ids)); }, + offsetContextHeight: (id, dz) => { + const ops = documentFor(get().project).cmdOps({ cmd: "contextOffset", id, dz }); + if (ops.length) get().applyChange(ops); + }, + + setContourHeight: (id, index, z, coalesceKey) => { + const ops = documentFor(get().project).cmdOps({ cmd: "contourZ", id, index, z }); + if (ops.length) get().applyChange(ops, coalesceKey); + }, + + moveContextBy: (ids, delta) => { + if (ids.length === 0 || (delta.x === 0 && delta.y === 0)) return; + const ops = transformOps(get().project, { wallIds: [], drawingId: null, contextIds: ids }, "move", [{ x: 0, y: 0 }, delta], "move", 1); + if (ops.length) get().applyChange(ops); + }, + patchContextObject: (id, patch, coalesceKey) => get().applyChange((p) => patchItem(p, "context", id, (o) => ({ ...o, ...patch }) as ContextObject), coalesceKey), diff --git a/src/state/testHooks.ts b/src/state/testHooks.ts index 7db9653c..d3073c01 100644 --- a/src/state/testHooks.ts +++ b/src/state/testHooks.ts @@ -46,7 +46,7 @@ declare global { modelView: () => string | undefined; /** [173] Schnitt der aktiven Ebene (1:50, Detailgrad der Anzeige): Zahl der Wand-Schnittflächen und ihre Fläche (m²). */ sectionWalls: () => Promise<{ n: number; area: number }>; - /** [193] Gelände-/Umgebungs-Elemente (Art, Id, bei der Baugrube die erste Umrissecke). */ + /** [193] Gelände-/Umgebungs-Elemente (Art, Id, bei der Baugrube die erste Umrissecke, bei Höhenlinien der erste Punkt). */ context: () => { id: string; type: string; first?: { x: number; y: number } }[]; /** [193] Gefüllte Flächen (Füllfarbe gesetzt) im Grundriss der aktiven Ebene (alle Kategorien, 1:100); bei 0 ist nichts Gefülltes mehr zu sehen. */ planFills: () => number; @@ -112,7 +112,7 @@ export function installTestHooks(): void { return generatePlan(s.project, s.activeLevelId, codes, undefined, s.detail, false, false, true, 50).primitives.filter((q) => q.kind === "line" && q.cls === cls).length; }, context: () => - (getState().project.context ?? []).map((c) => ({ id: c.id, type: c.type, first: c.type === "excavation" ? c.outline[0] : undefined })), + (getState().project.context ?? []).map((c) => ({ id: c.id, type: c.type, first: c.type === "excavation" ? c.outline[0] : c.type === "contourSet" ? c.contours[0]?.pts[0] : undefined })), planFills: () => { const s = getState(); const codes = new Set(); diff --git a/src/state/useGripEditing.ts b/src/state/useGripEditing.ts index 208aad3e..a5f17a53 100644 --- a/src/state/useGripEditing.ts +++ b/src/state/useGripEditing.ts @@ -35,7 +35,8 @@ import { wallGripPoints, type GripLocks, } from "../core"; -import { areaMovePreview, drawingMovePreview } from "../tools/transform"; +import { areaMovePreview, drawingMovePreview, transformPreview } from "../tools/transform"; +import { contextAnchor } from "./contextDrag"; import type { DraftShape, SnapResult, SnapSettings, ToolDraft, ToolMods } from "../tools/types"; import { computeSnap } from "../tools/snapping"; import { useCommandTabShortcut } from "./useKeyboardShortcuts"; @@ -185,6 +186,14 @@ export function useGripEditing(opts: { const selectedOpeningId = single(selection, "openings"); const selectedStairId = single(selection, "stairs"); // [149] Baum: Griff in der Stammmitte (verschieben) und am Kronenrand (Kronendurchmesser). + // [193] Einzeln gewählter Höhenlinien-Satz: Punkte als Griffe (Kern `grips.rs::contour_edit`). + const selectedContourSetId = modelEditable && selection.contextObjects.length === 1 ? selection.contextObjects[0] : null; + const selectedContourSet = selectedContourSetId + ? (() => { + const o = (project.context ?? []).find((c) => c.id === selectedContourSetId); + return o && o.type === "contourSet" ? o : null; + })() + : null; const selectedTreeId = single(selection, "trees"); const selectedTree = selectedTreeId ? (project.trees ?? []).find((x) => x.id === selectedTreeId) : undefined; // [176] Schnitt-/Ansichtslinie im Grundriss: Griffe an Anfang, Knickpunkten (`bendPoints`) und Ende. @@ -343,6 +352,7 @@ export function useGripEditing(opts: { })(); const MAX_INSERT_GRIP_POINTS = 100; // Kataster-Umrisse mit tausenden Punkten: keine Rauten + const MAX_CONTOUR_GRIPS = 600; // Höhenlinien-Sätze mit tausenden Punkten: gar keine Punkt-Griffe /** Anteil entlang der Kante, an dem der Einfüge-Griff sitzt (neben dem Kanten-Anfasser in der Mitte). */ const INSERT_AT = 0.25; /** @@ -425,6 +435,28 @@ export function useGripEditing(opts: { pushInsertGrips(out, roofRings(selectedRoof), { kind: "roof", id: selectedRoof.id }); return out; } + // [193] Höhenlinien: jeder Punkt ein Griff (flacher Index über alle Linien), dazu je Segment eine Einfüge-Raute. + // Kataster-grosse Sätze (hunderte Punkte) bekommen keine Griffe bzw. keine Rauten. + if (selectedContourSet && !selectedCeiling && effectiveDrawingIds.length === 0 && selectedWallIds.length === 0) { + const lines = selectedContourSet.contours; + const pts: Vec2[] = lines.flatMap((c) => c.pts); + if (pts.length > MAX_CONTOUR_GRIPS) return []; + pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); }); + if (pts.length <= MAX_INSERT_GRIP_POINTS) { + let off = 0; + const rings: { pts: Vec2[]; off: number }[] = []; + const noSeg = new Set(); + for (const c of lines) { + if (c.pts.length >= 2) { + rings.push({ pts: c.pts, off }); + if (!c.closed) noSeg.add(off + c.pts.length - 1); + } + off += c.pts.length; + } + pushInsertGrips(pts, rings, { kind: "contours", id: selectedContourSet.id }, {}, (seg) => !noSeg.has(seg)); + } + return pts; + } // [68] Baugrube: Umriss-Ecken + Sohlen-Griff (Lage: Schwerpunkt, y um die Sohlenhöhe versetzt). if (modelEditable && selectedExcavation && !selectedCeiling && effectiveDrawingIds.length === 0 && selectedWallIds.length === 0) { const pts = excavationGripPoints(selectedExcavation); @@ -695,6 +727,10 @@ export function useGripEditing(opts: { const pendingAreaGripRef = useRef<{ kind: "room" | "ceiling" | "excavation" | "roof"; id: string; index: number; flat: number; pt: Vec2 } | null>(null); const pendingAreaMoveRef = useRef<{ kind: "ceiling" | "room" | "stair"; id: string; total: Vec2 } | null>(null); const pendingWallMoveRef = useRef<{ wallId: string; total: Vec2 } | null>(null); + /** [193] Aufgeschobenes Ziehen von Gelände-/Umgebungs-Elementen: ungefangenes und gefangenes Gesamt-Delta. */ + const pendingContextMoveRef = useRef<{ ids: string[]; raw: Vec2; total: Vec2; anchor: Vec2 | null } | null>(null); + /** [193] Zug an einem Höhenlinien-Punkt (bzw. einer Einfüge-Raute: `insertSeg`): Vorschau bis zum Setzen, dann EIN Undo-Schritt. */ + const pendingContourRef = useRef<{ id: string; index: number; pt: Vec2; insertSeg?: number } | null>(null); /** Aufgeschobene Öffnungs-Verschiebung im Schnitt/in der Ansicht (neue `position`). */ const pendingOpeningMoveRef = useRef<{ id: string; position: number } | null>(null); /** Aufgeschobene Höhen-Änderung im Schnitt (Kante `kind` auf die Höhe `y`, Kern `sheetHeight`). */ @@ -1020,6 +1056,14 @@ export function useGripEditing(opts: { // Editier-Dispatch: bei gewählter Decke auf die Decken-Aktionen umleiten, sonst // auf die Wand/2D-Aktionen. So teilen Plan- UND 3D-Griffe denselben Pfad. const applyGrip = (index: number, pt: Vec2, arcLength?: number) => { + // [193] Höhenlinien-Punkt bzw. Einfüge-Raute: nur Vorschau, das Projekt ändert sich beim Setzen (ein Undo-Schritt). + if (selectedContourSet) { + const ins = gripOwners[index]; + pendingContourRef.current = ins?.insertSeg != null + ? { id: selectedContourSet.id, index: ins.insertSeg + 1, pt, insertSeg: ins.insertSeg } + : { id: selectedContourSet.id, index, pt }; + return; + } // [26] Einfüge-Raute am Umriss (Dach, Decke, Raum, Baugrube, geschlossene Polylinie): der erste Zug fügt die Ecke // ein, danach folgt sie dem Zeiger; Einfügen, Zug und Aufräumen sind ein Undo-Schritt (gleicher Schlüssel). const rd = ringDragRef.current; @@ -1143,6 +1187,23 @@ export function useGripEditing(opts: { /** Vorschau-Form des ausstehenden Eckpunkt-Zugs (leer, wenn keiner läuft). */ const gripPreviewShapes = (): DraftShape[] => { + const pc = pendingContourRef.current; + if (pc && selectedContourSet?.id === pc.id) { + // Die betroffene Höhenlinie mit dem gezogenen (bzw. eingefügten) Punkt als Linienzug. + let off = 0; + for (const c of selectedContourSet.contours) { + if (pc.index >= off && pc.index < off + c.pts.length + (pc.insertSeg != null ? 1 : 0) && (pc.insertSeg == null || pc.insertSeg >= off)) { + const local = pc.index - off; + const pts = pc.insertSeg != null ? [...c.pts.slice(0, local), pc.pt, ...c.pts.slice(local)] : c.pts.map((q, i) => (i === local ? pc.pt : q)); + const out: DraftShape[] = []; + for (let i = 0; i + 1 < pts.length; i++) out.push({ kind: "line", a: pts[i], b: pts[i + 1] }); + if (c.closed && pts.length > 2) out.push({ kind: "line", a: pts[pts.length - 1], b: pts[0] }); + return out; + } + off += c.pts.length; + } + return []; + } const pa = pendingAreaGripRef.current; if (pa?.kind === "roof" && selectedRoof) { return roofRings(selectedRoof).map(({ pts, off }) => ({ @@ -1201,6 +1262,12 @@ export function useGripEditing(opts: { const ph = pendingSheetHeightRef.current; pendingSheetHeightRef.current = null; if (ph) sheetHeightGrip(ph.kind, ph.id, ph.y, ph.free); + const pc = pendingContourRef.current; + pendingContourRef.current = null; + if (pc) { + if (pc.insertSeg != null) storeState().insertRingVertex("contours", pc.id, pc.insertSeg, pc.pt); + else storeState().moveRingVertex("contours", pc.id, pc.index, pc.pt); + } const pa = pendingAreaGripRef.current; pendingAreaGripRef.current = null; if (pa) { @@ -1267,6 +1334,9 @@ export function useGripEditing(opts: { const pom = pendingOpeningMoveRef.current; pendingOpeningMoveRef.current = null; if (pom) slideOpening(pom.id, { position: pom.position }); + const pcm = pendingContextMoveRef.current; + pendingContextMoveRef.current = null; + if (pcm) storeState().moveContextBy(pcm.ids, pcm.total); const pa = pendingAreaMoveRef.current; pendingAreaMoveRef.current = null; if (pa && (pa.total.x !== 0 || pa.total.y !== 0)) { @@ -1365,6 +1435,8 @@ export function useGripEditing(opts: { const endEditing = () => { sectionDragRef.current = null; ringDragRef.current = null; + pendingContourRef.current = null; + pendingContextMoveRef.current = null; setDraft(null); edgeAppliedDeltaRef.current = null; // Kanten-Drag beendet → Anker zurücksetzen moveCoincidentRef.current = null; // Körper-Koinzidenz-Gruppe verwerfen @@ -1599,7 +1671,31 @@ export function useGripEditing(opts: { delta: Vec2, target?: BodyTarget, mods?: ToolMods, + pxPerMeter?: number, ) => { + // [193] Gelände-/Umgebungs-Elemente: Gesamt-Delta (mit Fang des Bezugspunkts) + Vorschau, Projekt erst beim Loslassen. + if (target?.contextIds && modelEditable) { + const prev = pendingContextMoveRef.current; + const same = prev && prev.ids.join("\n") === target.contextIds.join("\n"); + const anchor = same ? prev!.anchor : contextAnchor(project, target.contextIds[0]); + let raw = same ? { x: prev!.raw.x + delta.x, y: prev!.raw.y + delta.y } : delta; + if (mods?.shift) { + raw = Math.abs(raw.x) >= Math.abs(raw.y) ? { x: raw.x, y: 0 } : { x: 0, y: raw.y }; + } + let total = raw; + let hit: SnapResult | null = null; + if (anchor && pxPerMeter && !mods?.shift) { + hit = snapFor({ x: anchor.x + raw.x, y: anchor.y + raw.y }, pxPerMeter, mods ?? { shift: false, ctrl: false, alt: false }); + if (hit?.point) total = { x: hit.point.x - anchor.x, y: hit.point.y - anchor.y }; + } + pendingContextMoveRef.current = { ids: target.contextIds, raw, total, anchor }; + setDraft({ + preview: transformPreview(project, { wallIds: [], drawingId: null, contextIds: target.contextIds }, "move", [{ x: 0, y: 0 }, total], "move", 1), + vertices: [], + snap: hit, + }); + return; + } // Shift = Ortho: das Delta auf die dominante Achse (H/V) zwingen — // dieselbe Regel wie beim freien Kanten-Zug (onEdgeMove) und beim // Vertex-Griff (onGripMove). Bisher wirkte Shift beim Körper-Verschieben @@ -1751,7 +1847,8 @@ export function useGripEditing(opts: { // Ausstehender Zug: einfach verwerfen (das Projekt wurde nie verändert). if (pendingSheetHeightRef.current) { pendingSheetHeightRef.current = null; - } else if (pendingGripRef.current || pendingWallGripRef.current || pendingAreaGripRef.current) { + } else if (pendingGripRef.current || pendingWallGripRef.current || pendingAreaGripRef.current || pendingContourRef.current) { + pendingContourRef.current = null; pendingGripRef.current = null; pendingWallGripRef.current = null; pendingAreaGripRef.current = null; diff --git a/src/state/useSelectionCommands.ts b/src/state/useSelectionCommands.ts index 139fe33b..2803a767 100644 --- a/src/state/useSelectionCommands.ts +++ b/src/state/useSelectionCommands.ts @@ -11,7 +11,7 @@ import { useMemo } from "react"; import type { Drawing2D, DrawingLevel, Project, Vec2 } from "../model/types"; import type { Selection } from "./selection"; -import { addItems, cmdMutation, fieldOps, opsMutation, patchItems, removeItems } from "../core"; +import { addItems, cmdMutation, fieldOps, opsMutation, patchItem, patchItems, removeItems } from "../core"; import type { ToolId } from "../tools/types"; import type { DrawingStyle } from "../editors/matchProps"; import { applyDrawingStyleOps, readDrawingStyle } from "../editors/matchProps"; @@ -155,6 +155,10 @@ export function useSelectionCommands(opts: { const siteHide: ReturnType = []; if (selection.site.includes("sunStudy") && project.sunStudy?.show) siteHide.push(...fieldOps(project, "sunStudy", { ...project.sunStudy, show: false })); if (selection.site.includes("siteRules") && project.siteRules && project.siteRules.show !== false) siteHide.push(...fieldOps(project, "siteRules", { ...project.siteRules, show: false })); + // Schlagschatten der Ansicht (`viewShadows`): schaltet `shadows` der aktiven Ansicht aus. + if (selection.site.includes("viewShadows") && project.drawingLevels.find((l) => l.id === activeLevel.id)?.shadows) { + siteHide.push(...patchItem(project, "drawingLevels", activeLevel.id, { shadows: false })); + } setProject( opsMutation((p) => [ ...siteHide, diff --git a/src/views/plan/PlanView.tsx b/src/views/plan/PlanView.tsx index e3fafabf..9bc8de46 100644 --- a/src/views/plan/PlanView.tsx +++ b/src/views/plan/PlanView.tsx @@ -321,6 +321,7 @@ export const PlanView = forwardRef( selectedCeilingIds, selectedStairIds, selectedWallIds, + selectedContextObjectIds, selectedDrawingIds, selectedDrawingId, getUnderlayIds, diff --git a/src/views/plan/planView/types.ts b/src/views/plan/planView/types.ts index e6579a4e..cd5a0eb1 100644 --- a/src/views/plan/planView/types.ts +++ b/src/views/plan/planView/types.ts @@ -430,6 +430,8 @@ export interface BodyTarget { ceilingId?: string; /** Nur im Schnitt/in der Ansicht (`sheetBodies`). */ stairId?: string; + /** [193] Gelände-/Umgebungs-Elemente (alle gewählten, das gegriffene liegt darunter). */ + contextIds?: string[]; } export interface GripHandlers { @@ -445,6 +447,7 @@ export interface GripHandlers { delta: Vec2, target?: BodyTarget, mods?: ToolMods, + pxPerMeter?: number, ): void; /** * Eine SEITE (Kante) ziehen: verschiebt beide Vertices der Kante senkrecht diff --git a/src/views/plan/planView/usePlanPicking.ts b/src/views/plan/planView/usePlanPicking.ts index 02b04b2e..89bf9751 100644 --- a/src/views/plan/planView/usePlanPicking.ts +++ b/src/views/plan/planView/usePlanPicking.ts @@ -34,6 +34,7 @@ export interface UsePlanPickingArgs { selectedCeilingIds: string[]; selectedStairIds: string[]; selectedWallIds: string[]; + selectedContextObjectIds: string[]; selectedDrawingIds: string[]; selectedDrawingId: string | null; getUnderlayIds: () => Map | null; @@ -58,6 +59,7 @@ export function usePlanPicking(inp: UsePlanPickingArgs) { selectedCeilingIds, selectedStairIds, selectedWallIds, + selectedContextObjectIds, selectedDrawingIds, selectedDrawingId, getUnderlayIds, @@ -375,6 +377,11 @@ export function usePlanPicking(inp: UsePlanPickingArgs) { const id = pickDrawing(clientX, clientY); if (id && selDraws.has(id)) return { drawingId: id }; } + // [193] Gewähltes Gelände-/Umgebungs-Element unter dem Cursor: alle gewählten Kontext-Elemente ziehen mit. + if (selectedContextObjectIds.length) { + const sel = new Set(selectedContextObjectIds); + if (contextIdsAt(clientX, clientY).some((id) => sel.has(id))) return { contextIds: selectedContextObjectIds }; + } return null; }; diff --git a/src/views/plan/planView/usePlanPointer.ts b/src/views/plan/planView/usePlanPointer.ts index 73cafe03..7ccdedaa 100644 --- a/src/views/plan/planView/usePlanPointer.ts +++ b/src/views/plan/planView/usePlanPointer.ts @@ -474,7 +474,7 @@ export function usePlanPointer(inp: UsePlanPointerArgs) { if (md && md.pointerId === p.pointerId) { const delta = { x: raw.x - md.last.x, y: raw.y - md.last.y }; if (delta.x !== 0 || delta.y !== 0) { - gripHandlers!.onMoveBody(delta, md.target, mods); + gripHandlers!.onMoveBody(delta, md.target, mods, currentPxPerMeter()); md.last = raw; } return;