diff --git a/TODO.md b/TODO.md index 5b8b613d..e2e53963 100644 --- a/TODO.md +++ b/TODO.md @@ -107,7 +107,8 @@ Wer zu einer ID mehr wissen will (Entscheide, Tests, Bilder), sucht dort nach `* schaltet Ebenen (persistent, undo-bar), nicht einzelne Elemente temporär; kein Cmd+E/F2 (keine Funktion dahinter); nicht in der Tauri-App geprüft. · S - ○ **[189]** Panels neu ordnen + Einstellungsdialog (12.11., Maintainer): Attribute-Panel unten links nur Gestaltung (Stift, Füllung, Linienstil, Schraffur); BIM-/Bauteil-Infos (Typ, Schichten, Masse, Kennwerte, IFC/Psets, Material …) in die Objekt-Info. Taste T bei Auswahl öffnet direkt den Einstellungsdialog des Objekts (wie Archicad Cmd+T), v. a. für Fenster/Türen, deren Einstellungen heute nur über das Attribute-Panel erreichbar sind. · M -- ○ **[187]** Griffe im Schnitt/in der Ansicht (12.11., Maintainer): angewählte Elemente haben dort kaum Fasspunkte (Decken, Gelände, Dächer …). Wie Archicad: Decke OK/UK (Höhe/Dicke), Wand OK (Höhe), Öffnung Brüstung/Sturz, Dach Traufe/First bzw. Neigung, Treppe An-/Austritt, Gelände-Profilpunkte (falls Modell es erlaubt); ein Undo-Schritt je Zug, Fang + Tab-Eingabe wie im Grundriss. · L +- ◐ **[187]** Griffe im Schnitt/in der Ansicht (12.11., Maintainer): angewählte Elemente haben dort kaum Fasspunkte (Decken, Gelände, Dächer …). Wie Archicad: Decke OK/UK (Höhe/Dicke), Wand OK (Höhe), Öffnung Brüstung/Sturz, Dach Traufe/First bzw. Neigung, Treppe An-/Austritt, Gelände-Profilpunkte (falls Modell es erlaubt); ein Undo-Schritt je Zug, Fang + Tab-Eingabe wie im Grundriss. · L + Teil 1 (12.11.): Höhen-Griffe im Schnitt/in der Ansicht für Decke (OK = Höhenlage über die `top`-Bindung, bei gebundener UK ändert sie die Dicke; UK = Dicke über den Deckentyp wie in der Objekt-Info bzw. UK-Bindung), Wand (OK, neu UK mit festgehaltener OK) und Öffnung (Brüstung, Sturz). Rechnung im Kern (`sheet_height.rs`, Griff-Anfrage `sheetHeight`, ein Undo-Schritt je Zug, Mindestmasse, gesperrte Bauteile ohne Griffe), Fang auf Geschoss-Koten (8 px) und Geometrie des Schnitts, Tab tippt die Kote (absolutes Z), Zug-Anzeige „Kote · Höhe". Offen (Teil 2): Dach (Traufe/First bzw. Neigung), Treppe (An-/Austritt), Gelände-Profilpunkte; Wand-UK-Griff ändert nur die Bindung `bottom` (Verbund mit Nachbarwänden/Geschosswechsel nicht bedacht); nicht in der Tauri-App geprüft. · L (Navigator, Kürzel, Ebenen-Panel) behält Zoom und Ausschnitt exakt — Geschosse teilen sich den Einpass-Schlüssel (`viewTabs.ts::planFitKey`, `PlanView` `fitKey`; Schnitt/Ansicht/Zeichnung/neues Projekt passen weiter ein). Cmd/Ctrl+5 Geschoss tiefer, Cmd/Ctrl+6 höher im Grundriss- und 3D-Reiter (`stepFloor`/`adjacentFloorId`, nach diff --git a/e2e/sectionGrips.spec.ts b/e2e/sectionGrips.spec.ts new file mode 100644 index 00000000..93e6fd44 --- /dev/null +++ b/e2e/sectionGrips.spec.ts @@ -0,0 +1,169 @@ +// [187] Höhen-Griffe im Schnitt: angewählte Decken, Wände und Fenster haben im Schnitt Fasspunkte (Archicad-Art). +// Musterhaus komplex, Schnitt A-A (x = 3): Decke EG → OK-Griff (Höhenlage) und UK-Griff (Dicke), Fenster eg-f1 → +// Brüstung und Sturz, Wand eg-aw-s → Ober-/Unterkante; je Zug ein Undo-Schritt; Tab tippt die Kote. +import type { Page } from "@playwright/test"; +import { blurFocus, discardIfAsked, expect, fileMenu, showSnapshot, test } from "./app"; +import type {} from "../src/state/testHooks"; + +test.use({ viewport: { width: 1600, height: 1000 } }); + +const heights = (page: Page) => page.evaluate(() => window.__dossierTest!.heights()); +const ceiling = async (page: Page, id: string) => (await heights(page)).ceilings.find((c) => c.id === id)!; +const opening = async (page: Page, id: string) => (await heights(page)).openings.find((o) => o.id === id)!; +const wall = async (page: Page, id: string) => (await heights(page)).walls.find((w) => w.id === id)!; +const r3 = (x: number) => Math.round(x * 1000) / 1000; + +/** Griffe lesen, sobald sie ruhen: nach Undo rechnet der Schnitt asynchron neu, bis dahin stehen sie an alter Stelle. */ +async function gripCentres(page: Page): Promise<{ x: number; y: number }[]> { + const read = async () => + ( + await page.locator(".plan-grip").evaluateAll((els) => + els.map((e) => { + const r = e.getBoundingClientRect(); + return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }; + }), + ) + ).sort((a, b) => a.x - b.x || a.y - b.y); + let prev = JSON.stringify(await read()); + let same = 0; + for (let i = 0; i < 60 && same < 6; i++) { + await page.waitForTimeout(300); + const cur = JSON.stringify(await read()); + same = cur === prev ? same + 1 : 0; + prev = cur; + } + return JSON.parse(prev); +} + +/** Griff ziehen: er bleibt nach dem Loslassen bewaffnet und folgt dem Zeiger, bis ein Klick ihn setzt. */ +async function dragGrip(page: Page, from: { x: number; y: number }, dy: number): Promise { + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(from.x, from.y + dy, { steps: 8 }); + await page.mouse.up(); + await page.mouse.click(from.x, from.y + dy); +} + +/** Rückgängig; der Schnitt rechnet danach asynchron neu, bis dahin stehen die Griffe an alter Stelle. */ +async function undo(page: Page) { + await blurFocus(page); + await page.keyboard.press("ControlOrMeta+z"); + await page.waitForTimeout(4000); +} + +async function select(page: Page, patch: Record) { + await blurFocus(page); + // setSelection mischt: die anderen Arten leeren, sonst bleibt z. B. das Fenster gewählt + await page.evaluate((p) => window.__dossierTest!.select({ walls: [], openings: [], ceilings: [], ...p }), patch); +} + +test("Schnitt A-A: Decke, Fenster und Wand haben Höhen-Griffe, Zug = ein Undo-Schritt", async ({ page }) => { + test.setTimeout(180_000); + 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 showSnapshot(page, "Schnitt A-A"); + await expect(page.locator("svg.plan-svg").first()).toBeVisible({ timeout: 30_000 }); + await page.waitForTimeout(1000); + + // Decke EG: zwei Griffe nebeneinander (OK links, UK rechts). + const c0 = await ceiling(page, "c-eg"); + await select(page, { ceilings: ["c-eg"] }); + await expect(page.locator(".plan-grip")).toHaveCount(2); + const [ok, uk] = await gripCentres(page); + expect(ok.x).toBeLessThan(uk.x); + + // OK nach oben: Höhenlage ändert sich, die Dicke bleibt (ohne UK-Bindung wandert die Platte). + await dragGrip(page, ok, -30); + const c1 = await ceiling(page, "c-eg"); + expect(c1.zTop).toBeGreaterThan(c0.zTop + 0.05); + expect(r3(c1.thickness)).toBe(r3(c0.thickness)); + await undo(page); + await expect.poll(async () => (await ceiling(page, "c-eg")).zTop).toBe(c0.zTop); + + // UK nach unten: die Decke wird dicker, die OK bleibt; ein Undo-Schritt stellt alles her. + await select(page, { ceilings: ["c-eg"] }); + await expect(page.locator(".plan-grip")).toHaveCount(2); + const [, uk2] = await gripCentres(page); + await dragGrip(page, uk2, 25); + const c2 = await ceiling(page, "c-eg"); + expect(c2.thickness).toBeGreaterThan(c0.thickness + 0.03); + expect(c2.zTop).toBe(c0.zTop); + await undo(page); + await expect.poll(async () => r3((await ceiling(page, "c-eg")).thickness)).toBe(r3(c0.thickness)); + expect((await ceiling(page, "c-eg")).zTop).toBe(c0.zTop); + + // Fenster eg-f1 (x 1.6–3.4, vom Schnitt getroffen): Sturz und Brüstung. + const f0 = await opening(page, "eg-f1"); + await select(page, { openings: ["eg-f1"] }); + await expect(page.locator(".plan-grip")).toHaveCount(2); + const [top, bottom] = (await gripCentres(page)).sort((a, b) => a.y - b.y); + await dragGrip(page, top, -20); + expect((await opening(page, "eg-f1")).height).toBeGreaterThan(f0.height + 0.05); + await undo(page); + await expect.poll(async () => (await opening(page, "eg-f1")).height).toBe(f0.height); + await select(page, { openings: ["eg-f1"] }); + await expect(page.locator(".plan-grip")).toHaveCount(2); + const [, bottom2] = (await gripCentres(page)).sort((a, b) => a.y - b.y); + await dragGrip(page, bottom2, 20); + const f1 = await opening(page, "eg-f1"); + expect(f1.sillHeight).toBeLessThan(f0.sillHeight - 0.05); + // Oberkante bleibt: Brüstung + Höhe unverändert. + expect(r3(f1.sillHeight + f1.height)).toBe(r3(f0.sillHeight + f0.height)); + await undo(page); + await expect.poll(async () => (await opening(page, "eg-f1")).sillHeight).toBe(f0.sillHeight); + void bottom; + + // Wand eg-aw-s: Oberkante und Unterkante. + const w0 = await wall(page, "eg-aw-s"); + await select(page, { walls: ["eg-aw-s"] }); + await expect(page.locator(".plan-grip")).toHaveCount(2); + const [wt, wb] = (await gripCentres(page)).sort((a, b) => a.y - b.y); + await dragGrip(page, wt, -45); + expect((await wall(page, "eg-aw-s")).zTop).toBeGreaterThan(w0.zTop + 0.05); + await undo(page); + await expect.poll(async () => (await wall(page, "eg-aw-s")).zTop).toBe(w0.zTop); + await select(page, { walls: ["eg-aw-s"] }); + const [, wb2] = (await gripCentres(page)).sort((a, b) => a.y - b.y); + await dragGrip(page, wb2, 20); + const w1 = await wall(page, "eg-aw-s"); + expect(w1.zBottom).toBeLessThan(w0.zBottom - 0.05); + expect(r3(w1.zTop)).toBe(r3(w0.zTop)); // Oberkante bleibt + await undo(page); + await expect.poll(async () => (await wall(page, "eg-aw-s")).zBottom).toBe(w0.zBottom); + void wb; +}); + +test("Schnitt A-A: Tab tippt die Kote der Decken-Oberkante", async ({ page }) => { + test.setTimeout(180_000); + 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 showSnapshot(page, "Schnitt A-A"); + await expect(page.locator("svg.plan-svg").first()).toBeVisible({ timeout: 30_000 }); + await page.waitForTimeout(1000); + + const c0 = await ceiling(page, "c-eg"); + await select(page, { ceilings: ["c-eg"] }); + await expect(page.locator(".plan-grip")).toHaveCount(2); + const [ok] = await gripCentres(page); + await page.mouse.move(ok.x, ok.y); + await page.mouse.down(); + await page.mouse.move(ok.x, ok.y - 15, { steps: 5 }); + await page.mouse.up(); + // Tab friert die Kote ein und öffnet das Feld „Kote“; die getippte Zahl setzt die Oberkante exakt. + await page.keyboard.press("Tab"); + const target = r3(c0.zTop + 0.4); + await page.keyboard.type(String(target)); + await page.keyboard.press("Enter"); + await page.mouse.click(ok.x, ok.y - 15); + await expect.poll(async () => r3((await ceiling(page, "c-eg")).zTop)).toBe(target); + await undo(page); + await expect.poll(async () => (await ceiling(page, "c-eg")).zTop).toBe(c0.zTop); +}); diff --git a/src-tauri/core/src/README.md b/src-tauri/core/src/README.md index 20176aca..9b8824ef 100644 --- a/src-tauri/core/src/README.md +++ b/src-tauri/core/src/README.md @@ -73,6 +73,7 @@ Neues Modul: `.rs` und `mod` in `lib.rs`, Bindungen in `web/.rs` u | `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 | | `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 | | `selection_info.rs`, `selection_filter.rs` | Objekt-Info der Auswahl; Export „nur Auswahl" | | `dim_assoc.rs`, `magic_wand.rs`, `polyline_vertex.rs`, `drawing_recognize.rs` | assoziative Bemassung, Zauberstab, Punkttypen, Bauteile aus Zeichnung erkennen | diff --git a/src-tauri/core/src/grip_drag.rs b/src-tauri/core/src/grip_drag.rs index 377feec5..d9bc04c0 100644 --- a/src-tauri/core/src/grip_drag.rs +++ b/src-tauri/core/src/grip_drag.rs @@ -8,7 +8,7 @@ //! Nachbarkanten ([`axis_lock`]); //! - Kanten-Griff: geführte Kante (nur entlang der Aussennormale, Raster/Geometrie-Snap) bzw. freie Kante //! (Ortho, Raster), mit oder ohne gelockte Felder ([`edge_target`]); -//! - Höhen-Griffe im Schnitt (Wand-Oberkante, Fenster Ober-/Unterkante, [`sheet_height`]); +//! - Höhen-Griffe im Schnitt ([187], Wand, Öffnung, Decke: `crate::sheet_height`); //! - Öffnung entlang der Wirtswand ([`opening_slide_sheet`]; der Griff-Zug selbst: `crate::opening_slide`), Griff-Lagen von //! Öffnung, Treppe, Bogenwand und Baugrube; //! - koinzidente Ecken anderer gewählter Elemente beim Körper-Verschieben ([`coincident`]). @@ -171,45 +171,6 @@ pub fn edge_target(edge: Edge, raw: P, d: EdgeDrive) -> P { add(anchor, scale(edge.normal, offset)) } -/// Art eines Höhen-Griffs im Schnitt/in der Ansicht. -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum HeightGrip { - WallTop, - OpeningTop, - OpeningBottom, -} - -/// Ergebnis eines Höhen-Griff-Zugs: neue Ober-/Unterkante im Blatt und die Werte fürs Bauteil -/// (Wand/Öffnung `height`; Fenster-Unterkante zusätzlich `sill_height`), auf mm gerundet. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct HeightDrag { - pub top: f64, - pub bottom: f64, - pub height: f64, - pub sill_height: Option, -} - -/// Höhen-Griff auf die Blatt-Höhe `y` ziehen (1-cm-Raster, `free` = Strg ohne Raster). `base` = Geschoss- -/// Höhe, `top`/`bottom` = heutige Ober-/Unterkante im Blatt. Mindestmasse: Wand 0.30 m, Öffnung 0.20 m. -pub fn sheet_height(kind: HeightGrip, base: f64, top: f64, bottom: f64, y: f64, free: bool) -> HeightDrag { - let v = if free { y } else { jsnum::round(y * 100.0) / 100.0 }; - let mm = |x: f64| jsnum::round(x * 1000.0) / 1000.0; - match kind { - HeightGrip::WallTop => { - let t = jsnum::max(base + 0.3, v); - HeightDrag { top: t, bottom, height: mm(t - base), sill_height: None } - } - HeightGrip::OpeningTop => { - let t = jsnum::max(bottom + 0.2, v); - HeightDrag { top: t, bottom, height: mm(t - bottom), sill_height: None } - } - HeightGrip::OpeningBottom => { - let b = jsnum::min(top - 0.2, jsnum::max(base, v)); - HeightDrag { top, bottom: b, height: mm(top - b), sill_height: Some(mm(b - base)) } - } - } -} - /// Mittelpunkt-Griff einer Öffnung (Breite `width`, `position` = Abstand des ersten Pfostens) auf der Wandachse. pub fn opening_wall_grip(ws: P, we: P, bulge: f64, position: f64, width: f64) -> P { // Bogenwand ([T2], [144]): Punkt auf dem Bogen bei der Bogenlänge der Öffnungsmitte. @@ -666,27 +627,6 @@ mod tests { assert!(close(p, (3.0, 1.0))); } - #[test] - fn hoehen_griffe() { - // Wand: 1-cm-Raster, Mindesthöhe 0.30 über dem Geschoss. - let r = sheet_height(HeightGrip::WallTop, 3.0, 5.6, 3.0, 5.7349, false); - assert_eq!((r.top, r.height, r.sill_height), (5.73, 2.73, None)); - let r = sheet_height(HeightGrip::WallTop, 3.0, 5.6, 3.0, 2.0, false); - assert_eq!(r.height, 0.3); - // Strg: ohne Raster. - assert_eq!(sheet_height(HeightGrip::WallTop, 0.0, 2.0, 0.0, 2.3456, true).height, 2.346); - // Fenster oben: Mindesthöhe 0.20 über der Unterkante. - let r = sheet_height(HeightGrip::OpeningTop, 0.0, 2.1, 0.9, 0.5, false); - assert_eq!((r.top, r.height), (1.1, 0.2)); - // Fenster unten: zwischen Geschoss und Oberkante − 0.20, Oberkante bleibt. - let r = sheet_height(HeightGrip::OpeningBottom, 0.0, 2.1, 0.9, 0.6, false); - assert_eq!((r.bottom, r.top, r.sill_height, r.height), (0.6, 2.1, Some(0.6), 1.5)); - let r = sheet_height(HeightGrip::OpeningBottom, 0.0, 2.1, 0.9, -1.0, false); - assert_eq!(r.sill_height, Some(0.0)); - let r = sheet_height(HeightGrip::OpeningBottom, 0.0, 2.1, 0.9, 3.0, false); - assert_eq!(r.height, 0.2); - } - #[test] fn oeffnung_entlang_der_wand() { let (s, e) = ((0.0, 0.0), (5.0, 0.0)); diff --git a/src-tauri/core/src/grips.rs b/src-tauri/core/src/grips.rs index 20f487b8..7e5f5a5c 100644 --- a/src-tauri/core/src/grips.rs +++ b/src-tauri/core/src/grips.rs @@ -463,6 +463,9 @@ pub fn run(lk: &Lookup, req: &Request) -> Result { } vec![replace("drawings2d", with_geom(d, with_all(g, fields)))].into() } + // [187] Höhen-Griff im Schnitt/in der Ansicht: `kind` = wallTop | wallBottom | openingTop | openingBottom | + // ceilingTop | ceilingBottom, `a` = Blatt-Höhe (absolutes Z), `free` ohne 1-cm-Raster (`sheet_height.rs`). + "sheetHeight" => crate::sheet_height::ops(lk, r.s("kind").unwrap_or(""), r.s("id").unwrap_or(""), r.n("a"), r.free, r.s("newId").unwrap_or(""), &req.new_name).into(), "wallThickness" => wall_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.new_name.clone()).into(), "ceilingThickness" => ceiling_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.new_name.clone()).into(), // [144] Wandöffnung gleiten lassen: Griff-Zug nach `pt` bzw. Objekt-Info-Position `a` (ab @@ -1561,7 +1564,7 @@ fn wall_thickness(root: &Map, wall_id: &str, thickness: f64, new_ /// Dicke einer einschichtigen Decke (`setCeilingThickness`), analog zur Wand; der geteilte /// Alt-Wandtyp (`Ceiling.wallTypeId`) wird nie verändert. -fn ceiling_thickness(root: &Map, ceiling_id: &str, thickness: f64, new_id: &str, new_name: Value) -> Vec { +pub(crate) fn ceiling_thickness(root: &Map, ceiling_id: &str, thickness: f64, new_id: &str, new_name: Value) -> Vec { if !thickness.is_finite() || thickness <= 0.0 { return vec![]; } diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index f861bc6d..d6800aba 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -104,6 +104,7 @@ pub mod wasm_alloc; pub mod text_layout; pub mod grips; pub mod grip_drag; +pub mod sheet_height; pub mod json_util; pub mod selection_info; pub mod project_refs; diff --git a/src-tauri/core/src/selection_info.rs b/src-tauri/core/src/selection_info.rs index 1e9096be..5610a737 100644 --- a/src-tauri/core/src/selection_info.rs +++ b/src-tauri/core/src/selection_info.rs @@ -281,7 +281,7 @@ fn floor_name(floor: Option<&Value>, fallback: Option<&Value>) -> Option } /// UK/OK-Bindung (`resolveAnchor`): absolutes Z oder `None` (Rückfall des Aufrufers). -fn anchor(root: &Map, a: Option<&Value>) -> Option { +pub(crate) fn anchor(root: &Map, a: Option<&Value>) -> Option { let a = a.filter(|a| truthy(Some(a)))?; if str_of(field(a, "mode")) == Some("custom") { // `return anchor.z` — fehlend/null fällt beim `??` des Aufrufers zurück. @@ -300,14 +300,14 @@ fn num_or(v: Option<&Value>, d: f64) -> f64 { } /// (UK, OK) einer Wand oder Stütze: UK aus `bottom` sonst Geschoss-Basis, OK aus `top` sonst UK + Höhe. -fn vertical_extent(root: &Map, el: &Value) -> (f64, f64) { +pub(crate) fn vertical_extent(root: &Map, el: &Value) -> (f64, f64) { let floor_base = level(root, field(el, "floorId")).map_or(0.0, |f| num_or(field(f, "baseElevation"), 0.0)); heights::element(floor_base, anchor(root, field(el, "bottom")), anchor(root, field(el, "top")), num_of(field(el, "height"))) } /// (UK, OK) einer Decke (`ceilingVerticalExtent`): OK aus `top` sonst Geschoss-Oberkante (Basis + Höhe), UK aus /// `bottom` sonst OK − `thickness` (die Decke wächst nach unten). -fn ceiling_extent(root: &Map, c: &Value, thickness: f64) -> (f64, f64) { +pub(crate) fn ceiling_extent(root: &Map, c: &Value, thickness: f64) -> (f64, f64) { let floor_top = level(root, field(c, "floorId")).map_or(0.0, |f| num_or(field(f, "baseElevation"), 0.0) + num_or(field(f, "floorHeight"), 0.0)); heights::ceiling(floor_top, anchor(root, field(c, "bottom")), anchor(root, field(c, "top")), || thickness) } @@ -344,7 +344,7 @@ fn ceiling_type<'a>(root: &'a Map, c: &Value) -> Result<&'a Value } /// Deckendicke (`ceilingThickness`): `thickness` > 0, sonst Typ-Dicke, sonst 0.2. -fn ceiling_thickness(root: &Map, c: &Value) -> f64 { +pub(crate) fn ceiling_thickness(root: &Map, c: &Value) -> f64 { if nn(field(c, "thickness")).is_some() && num_of(field(c, "thickness")) > 0.0 { return num_of(field(c, "thickness")); } diff --git a/src-tauri/core/src/sheet_height.rs b/src-tauri/core/src/sheet_height.rs new file mode 100644 index 00000000..706e8eb1 --- /dev/null +++ b/src-tauri/core/src/sheet_height.rs @@ -0,0 +1,304 @@ +//! [187] Höhen-Griffe im Schnitt und in der Ansicht: Kante des gewählten Bauteils auf die Blatt-Höhe `y` (absolutes Z, +//! Meter) ziehen. Der Kern rechnet aus der Höhe die Änderung am Bauteil — wie im Grundriss, nicht in der Hülle: +//! +//! | Griff | Wirkung | +//! |---|---| +//! | `wallTop` | Wandhöhe (`height`); ist die Oberkante gebunden (`top`), wandert die Bindung mit | +//! | `wallBottom` | Unterkante (`bottom`-Bindung), die Oberkante bleibt stehen (`height` rechnet nach) | +//! | `openingTop` | lichte Höhe (`height`) | +//! | `openingBottom` | Brüstung (`sillHeight`) bei gleicher Oberkante (Fenster) | +//! | `ceilingTop` | Höhenlage: Oberkante-Bindung (`top`); ohne UK-Bindung zieht die Dicke die Unterkante mit | +//! | `ceilingBottom` | Dicke (über den Deckentyp, wie die Objekt-Info) bzw. die UK-Bindung, falls es eine gibt | +//! +//! Raster 1 cm (`free` = ohne), Mindestmasse: Wand 0.30 m, Öffnung 0.20 m, Decke 0.05 m. Bindungen bleiben in ihrer +//! Art (Geschoss + Versatz bleibt Geschoss + Versatz, absolut bleibt absolut); ohne Bindung entsteht eine +//! Geschoss-Bindung des eigenen Geschosses. Gesperrte Bauteile ändern sich nicht. + +use crate::document::Lookup; +use crate::json_util::{field, js_num, num_of, truthy, with, with_all}; +use crate::jsnum; +use crate::ops::Op; +use crate::selection_info::{anchor, ceiling_extent, ceiling_thickness as ceiling_thickness_of, vertical_extent}; +use serde_json::{json, Map, Value}; + +const MIN_WALL: f64 = 0.3; +const MIN_OPENING: f64 = 0.2; +const MIN_CEILING: f64 = 0.05; + +/// Art eines Höhen-Griffs (Reihenfolge = Index der Bindung `grip_sheet_height`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Kind { + WallTop, + OpeningTop, + OpeningBottom, + WallBottom, + /// Decke OK, UK nicht gebunden: die ganze Platte wandert (Dicke bleibt). + CeilingTop, + /// Decke OK bei gebundener UK: die Dicke ändert sich. + CeilingTopFixed, + CeilingBottom, +} + +impl Kind { + pub fn from_index(i: u32) -> Option { + use Kind::*; + [WallTop, OpeningTop, OpeningBottom, WallBottom, CeilingTop, CeilingTopFixed, CeilingBottom].get(i as usize).copied() + } +} + +/// Griff auf die Blatt-Höhe `y` ziehen (1-cm-Raster, `free` = ohne): neue `(Oberkante, Unterkante)` im Blatt. +/// `top`/`bottom` = heutige Kanten, `base` = tiefste erlaubte Brüstungskante (UK der Wand; nur `OpeningBottom`). +/// Mindestmasse: Wand 0.30 m, Öffnung 0.20 m, Decke 0.05 m. +pub fn drag(kind: Kind, base: f64, top: f64, bottom: f64, y: f64, free: bool) -> (f64, f64) { + let v = if free { y } else { jsnum::round(y * 100.0) / 100.0 }; + match kind { + Kind::WallTop => (jsnum::max(bottom + MIN_WALL, v), bottom), + Kind::WallBottom => (top, jsnum::min(top - MIN_WALL, v)), + Kind::OpeningTop => (jsnum::max(bottom + MIN_OPENING, v), bottom), + Kind::OpeningBottom => (top, jsnum::min(top - MIN_OPENING, jsnum::max(base, v))), + Kind::CeilingTop => (v, bottom + (v - top)), + Kind::CeilingTopFixed => (jsnum::max(bottom + MIN_CEILING, v), bottom), + Kind::CeilingBottom => (top, jsnum::min(top - MIN_CEILING, v)), + } +} + +fn mm(x: f64) -> f64 { + jsnum::round(x * 1000.0) / 1000.0 +} + +fn replace(collection: &str, entity: Value) -> Op { + Op::Replace { collection: collection.into(), entity } +} + +/// Bindung auf das absolute Z `z` setzen, in der Art der bisherigen: Geschoss + Versatz bleibt Geschoss (Versatz zur +/// Basis des Geschosses), absolut bleibt absolut; ohne Bindung (oder unbekanntes Geschoss) das eigene Geschoss. +fn anchor_to(root: &Map, existing: Option<&Value>, own_floor: Option<&Value>, z: f64) -> Value { + let base_of = |floor_id: Option<&Value>| { + let id = floor_id?.as_str()?; + let f = root.get("drawingLevels")?.as_array()?.iter().find(|l| field(l, "id").and_then(Value::as_str) == Some(id))?; + Some((id.to_string(), field(f, "baseElevation").map_or(0.0, |b| num_of(Some(b))))) + }; + let existing = existing.filter(|a| truthy(Some(a))); + if existing.and_then(|a| field(a, "mode")).and_then(Value::as_str) == Some("custom") { + return json!({ "mode": "custom", "z": js_num(mm(z)) }); + } + match base_of(existing.and_then(|a| field(a, "floorId"))).or_else(|| base_of(own_floor)) { + Some((floor_id, base)) => json!({ "mode": "floor", "floorId": floor_id, "offset": js_num(mm(z - base)) }), + None => json!({ "mode": "custom", "z": js_num(mm(z)) }), + } +} + +/// Fang an die nächste Kote (Geschoss-Basis/-Oberkante …) innerhalb `tol` Metern; sonst `y` selbst. +pub fn snap_level(y: f64, levels: &[f64], tol: f64) -> f64 { + if !y.is_finite() || !tol.is_finite() { + return y; + } + levels.iter().copied().filter(|l| l.is_finite() && (l - y).abs() <= tol).min_by(|a, b| (a - y).abs().total_cmp(&(b - y).abs())).unwrap_or(y) +} + +/// Die Ops für den Zug von `kind` an Bauteil `id` auf die Blatt-Höhe `y`. `new_id`/`new_name`: Deckentyp, falls die +/// Dicke einen eigenen braucht (`ceilingThickness`). Leer bei unbekanntem Bauteil/Art, Sperre, Unsinn oder wenn sich +/// nichts ändert. +pub fn ops(lk: &Lookup, kind: &str, id: &str, y: f64, free: bool, new_id: &str, new_name: &Value) -> Vec { + if !y.is_finite() { + return vec![]; + } + let root = lk.root; + let locked = |e: &Value| truthy(field(e, "locked")); + match kind { + "wallTop" | "wallBottom" => { + let Some(w) = lk.find("walls", id).filter(|w| !locked(w)) else { return vec![] }; + let (zb, zt) = vertical_extent(root, w); + let floor = field(w, "floorId"); + let new = if kind == "wallTop" { + let z = drag(Kind::WallTop, zb, zt, zb, y, free).0; + let mut f = vec![("height", js_num(mm(z - zb)))]; + if truthy(field(w, "top")) { + f.push(("top", anchor_to(root, field(w, "top"), floor, z))); + } + with_all(w, f) + } else { + let z = drag(Kind::WallBottom, zb, zt, zb, y, free).1; + with_all(w, vec![("height", js_num(mm(zt - z))), ("bottom", anchor_to(root, field(w, "bottom"), floor, z))]) + }; + if new == *w { vec![] } else { vec![replace("walls", new)] } + } + "openingTop" | "openingBottom" => { + let Some(o) = lk.find("openings", id).filter(|o| !locked(o)) else { return vec![] }; + let Some(w) = field(o, "hostWallId").and_then(Value::as_str).and_then(|h| lk.find("walls", h)) else { return vec![] }; + let base = vertical_extent(root, w).0; + let sill = Some(num_of(field(o, "sillHeight"))).filter(|s| s.is_finite()).map_or(0.0, |s| s.max(0.0)); + let (bottom, top) = (base + sill, base + sill + num_of(field(o, "height"))); + let new = if kind == "openingTop" { + let t = drag(Kind::OpeningTop, base, top, bottom, y, free).0; + with(o, "height", js_num(mm(t - bottom))) + } else { + if field(o, "kind").and_then(Value::as_str) == Some("door") { + return vec![]; + } + let b = drag(Kind::OpeningBottom, base, top, bottom, y, free).1; + with_all(o, vec![("sillHeight", js_num(mm(b - base))), ("height", js_num(mm(top - b)))]) + }; + if new == *o { vec![] } else { vec![replace("openings", new)] } + } + "ceilingTop" | "ceilingBottom" => { + let Some(c) = lk.find("ceilings", id).filter(|c| !locked(c)) else { return vec![] }; + let (zb, zt) = ceiling_extent(root, c, ceiling_thickness_of(root, c)); + let floor = field(c, "floorId"); + let bound_bottom = truthy(field(c, "bottom")) && anchor(root, field(c, "bottom")).is_some(); + if kind == "ceilingTop" { + // Mit fester UK-Bindung ändert sich die Dicke, die UK bleibt; sonst wandert die ganze Platte. + let z = drag(if bound_bottom { Kind::CeilingTopFixed } else { Kind::CeilingTop }, zb, zt, zb, y, free).0; + let new = with(c, "top", anchor_to(root, field(c, "top"), floor, z)); + return if new == *c { vec![] } else { vec![replace("ceilings", new)] }; + } + let z = drag(Kind::CeilingBottom, zb, zt, zb, y, free).1; + if bound_bottom { + let new = with(c, "bottom", anchor_to(root, field(c, "bottom"), floor, z)); + return if new == *c { vec![] } else { vec![replace("ceilings", new)] }; + } + let t = mm(zt - z); + if (t - mm(zt - zb)).abs() < 1e-9 { + return vec![]; + } + // Eigenes `thickness` der Decke übersteuert den Typ: dann nur dieses Feld. + if num_of(field(c, "thickness")) > 0.0 { + return vec![replace("ceilings", with(c, "thickness", js_num(t)))]; + } + // `{t}` im Namen des neuen Typs = die Dicke (zwei Stellen). + let name = new_name.as_str().map_or_else(|| new_name.clone(), |n| Value::from(n.replace("{t}", &format!("{t:.2}")))); + crate::grips::ceiling_thickness(root, id, t, new_id, name) + } + _ => vec![], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn root() -> Map { + json!({ + "drawingLevels": [ + {"id": "eg", "kind": "floor", "baseElevation": 0.0, "floorHeight": 2.6}, + {"id": "og", "kind": "floor", "baseElevation": 3.0, "floorHeight": 2.6} + ], + "walls": [ + {"id": "w1", "floorId": "eg", "height": 2.6}, + {"id": "w2", "floorId": "eg", "height": 2.6, "top": {"mode": "floor", "floorId": "og", "offset": 0}}, + {"id": "w3", "floorId": "eg", "height": 2.6, "locked": true} + ], + "openings": [ + {"id": "f1", "hostWallId": "w1", "kind": "window", "sillHeight": 0.9, "height": 1.2}, + {"id": "t1", "hostWallId": "w1", "kind": "door", "sillHeight": 0, "height": 2.1} + ], + "wallTypes": [{"id": "wt", "layers": [{"thickness": 0.2}]}], + "ceilingTypes": [{"id": "ct", "layers": [{"thickness": 0.25}]}, {"id": "ct2", "layers": [{"thickness": 0.25}]}], + "ceilings": [ + {"id": "c1", "floorId": "eg", "wallTypeId": "wt", "ceilingTypeId": "ct"}, + {"id": "c2", "floorId": "eg", "wallTypeId": "wt", "ceilingTypeId": "ct2", "bottom": {"mode": "custom", "z": 2.3}}, + {"id": "c3", "floorId": "eg", "wallTypeId": "wt", "thickness": 0.3} + ] + }) + .as_object() + .unwrap() + .clone() + } + + fn run(kind: &str, id: &str, y: f64) -> Vec { + let r = root(); + ops(&Lookup::plain(&r), kind, id, y, false, "ct-neu", &json!("Neu")) + } + + fn entity(ops: &[Op]) -> Value { + match ops.first() { + Some(Op::Replace { entity, .. }) => entity.clone(), + other => panic!("replace erwartet, war {other:?}"), + } + } + + #[test] + fn wand_oberkante_setzt_hoehe_und_bindung() { + let e = entity(&run("wallTop", "w1", 3.0449)); + assert_eq!(e["height"], json!(3.04)); + assert!(e.get("top").is_none(), "ohne Bindung keine neue"); + // gebundene OK: Bindung wandert mit (Versatz zur Geschoss-Basis des Bezugsgeschosses). + let e = entity(&run("wallTop", "w2", 3.5)); + assert_eq!(e["top"], json!({"mode": "floor", "floorId": "og", "offset": 0.5})); + assert_eq!(e["height"], json!(3.5)); + // Mindesthöhe 0.30 + assert_eq!(entity(&run("wallTop", "w1", -2.0))["height"], json!(0.3)); + } + + #[test] + fn wand_unterkante_haelt_die_oberkante() { + let e = entity(&run("wallBottom", "w1", -0.5)); + assert_eq!(e["bottom"], json!({"mode": "floor", "floorId": "eg", "offset": -0.5})); + assert_eq!(e["height"], json!(3.1)); // OK bleibt bei 2.6 + assert_eq!(entity(&run("wallBottom", "w1", 9.0))["height"], json!(0.3)); + } + + #[test] + fn vorschau_und_fang() { + // Wand: Mindesthöhe 0.30 über der UK, 1-cm-Raster; Strg ohne Raster. + assert_eq!(drag(Kind::WallTop, 3.0, 5.6, 3.0, 5.7349, false), (5.73, 3.0)); + assert_eq!(drag(Kind::WallTop, 3.0, 5.6, 3.0, 2.0, false).0, 3.3); + assert_eq!(drag(Kind::WallTop, 0.0, 2.0, 0.0, 2.3456, true).0, 2.3456); + // Fenster unten: zwischen Wand-UK und Oberkante − 0.20, Oberkante bleibt. + assert_eq!(drag(Kind::OpeningBottom, 0.0, 2.1, 0.9, 0.6, false), (2.1, 0.6)); + assert_eq!(drag(Kind::OpeningBottom, 0.0, 2.1, 0.9, -1.0, false).1, 0.0); + // Decke OK: Platte wandert / UK gebunden bleibt. + assert_eq!(drag(Kind::CeilingTop, 0.0, 2.6, 2.35, 2.8, false), (2.8, 2.55)); + assert_eq!(drag(Kind::CeilingTopFixed, 0.0, 2.6, 2.35, 2.0, false), (2.4, 2.35)); + assert_eq!(snap_level(2.63, &[0.0, 2.6, 3.0], 0.05), 2.6); + assert_eq!(snap_level(2.8, &[0.0, 2.6, 3.0], 0.05), 2.8); + assert_eq!(snap_level(f64::NAN, &[0.0], 0.05).is_nan(), true); + } + + #[test] + fn gesperrt_unbekannt_unsinn() { + assert!(run("wallTop", "w3", 3.0).is_empty()); + assert!(run("wallTop", "nix", 3.0).is_empty()); + assert!(run("wallTop", "w1", f64::NAN).is_empty()); + assert!(run("unbekannt", "w1", 3.0).is_empty()); + assert!(run("wallTop", "w1", 2.6).is_empty(), "keine Änderung = keine Op"); + } + + #[test] + fn oeffnung_bruestung_und_sturz() { + let e = entity(&run("openingTop", "f1", 2.4)); + assert_eq!(e["height"], json!(1.5)); + let e = entity(&run("openingBottom", "f1", 0.6)); + assert_eq!((e["sillHeight"].clone(), e["height"].clone()), (json!(0.6), json!(1.5))); + // Brüstung nie unter die Wand-UK, Höhe mindestens 0.20. + assert_eq!(entity(&run("openingBottom", "f1", -1.0))["sillHeight"], json!(0)); + assert_eq!(entity(&run("openingBottom", "f1", 5.0))["height"], json!(0.2)); + assert!(run("openingBottom", "t1", 0.5).is_empty(), "Türen haben keine Brüstung"); + } + + #[test] + fn decke_oberkante_ist_hoehenlage() { + // Ohne UK-Bindung wandert die Platte (Dicke bleibt): OK 2.6 → 2.8 als Versatz zur Geschoss-Basis. + let e = entity(&run("ceilingTop", "c1", 2.8)); + assert_eq!(e["top"], json!({"mode": "floor", "floorId": "eg", "offset": 2.8})); + // Mit UK-Bindung bleibt die UK, Mindestdicke 0.05. + let e = entity(&run("ceilingTop", "c2", 2.0)); + assert_eq!(e["top"]["offset"], json!(2.35)); + } + + #[test] + fn decke_unterkante_ist_dicke() { + // UK 2.35 → 2.2: Dicke 0.25 → 0.4 über den (exklusiven) Typ. + let ops = run("ceilingBottom", "c1", 2.2); + let Op::Replace { collection, entity: ty } = &ops[0] else { panic!() }; + assert_eq!(collection, "ceilingTypes"); + assert_eq!(ty["layers"][0]["thickness"], json!(0.4)); + // Eigenes `thickness` der Decke: nur dieses Feld. + let e = entity(&run("ceilingBottom", "c3", 2.0)); + assert_eq!(e["thickness"], json!(0.6)); + // UK gebunden: Bindung versetzen. + let e = entity(&run("ceilingBottom", "c2", 2.1)); + assert_eq!(e["bottom"], json!({"mode": "custom", "z": 2.1})); + } + +} diff --git a/src-tauri/core/src/web/grip_drag.rs b/src-tauri/core/src/web/grip_drag.rs index 992117f7..c3b7a42a 100644 --- a/src-tauri/core/src/web/grip_drag.rs +++ b/src-tauri/core/src/web/grip_drag.rs @@ -2,7 +2,7 @@ //! Puffer `[x0, y0, …]`; NaN = „fehlt" (ungelockter Wert, kein Snap, kein Zentrum). Kaputte Puffer ergeben //! ein leeres Ergebnis. -use crate::grip_drag::{self as gd, Edge, EdgeDrive, HeightGrip, P}; +use crate::grip_drag::{self as gd, Edge, EdgeDrive, P}; use wasm_bindgen::prelude::wasm_bindgen; fn opt(v: f64) -> Option { @@ -108,18 +108,23 @@ pub fn grip_edge_target( vec![p.0, p.1] } -/// Höhen-Griff im Schnitt (`kind` 0 Wand-Oberkante, 1 Öffnung oben, 2 Öffnung unten): `[oben, unten, höhe, -/// brüstung]` (Brüstung NaN, wenn sie sich nicht ändert); `[]` bei unbekannter Art. +/// Höhen-Griff im Schnitt ([187], `sheet_height::Kind`: 0 Wand OK, 1 Öffnung oben, 2 Öffnung unten, 3 Wand UK, 4 Decke OK +/// (Platte wandert), 5 Decke OK bei gebundener UK, 6 Decke UK): neue `[oben, unten]` im Blatt; `[]` bei unbekannter Art +/// oder Unsinn (NaN). #[wasm_bindgen] pub fn grip_sheet_height(kind: u32, base: f64, top: f64, bottom: f64, y: f64, free: bool) -> Vec { - let k = match kind { - 0 => HeightGrip::WallTop, - 1 => HeightGrip::OpeningTop, - 2 => HeightGrip::OpeningBottom, - _ => return vec![], - }; - let r = gd::sheet_height(k, base, top, bottom, y, free); - vec![r.top, r.bottom, r.height, r.sill_height.unwrap_or(f64::NAN)] + let Some(k) = crate::sheet_height::Kind::from_index(kind) else { return vec![] }; + if ![base, top, bottom, y].iter().all(|v| v.is_finite()) { + return vec![]; + } + let (t, b) = crate::sheet_height::drag(k, base, top, bottom, y, free); + vec![t, b] +} + +/// Fang einer Blatt-Höhe `y` auf die nächste Kote aus `levels` innerhalb `tol` (Meter): die Kote, sonst `y`. +#[wasm_bindgen] +pub fn grip_snap_height(y: f64, levels: &[f64], tol: f64) -> f64 { + crate::sheet_height::snap_level(y, levels, tol) } /// Mittelpunkt-Griff einer Öffnung auf der Wandachse `s → e`: `[x, y]`. diff --git a/src/core/extra.ts b/src/core/extra.ts index 281e43d6..b3b5952a 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -74,7 +74,7 @@ export { drawingVertices, gripPt, openEdges, polylineEdgeGrips, ringEdges } from export { verticalExtents } from "../geometry/grips"; export type { VerticalExtent } from "../geometry/grips"; export type { GripRequest, RingKind } from "../geometry/grips"; -export { clampInside, coincidentGripPoints, excavationGripPoints, gripArcWallRadius, gripArcWallResize, gripArcWallTarget, gripAxisLock, gripEdgeTarget, gripPolar, gripPolarPoint, openingGripPoint, openingSheetSlide, openingTypedPosition, sheetHeightDrag, stairMoveHandle, stairParamPoints, wallGripPoints } from "../geometry/gripDrag"; +export { clampInside, coincidentGripPoints, excavationGripPoints, gripArcWallRadius, gripArcWallResize, gripArcWallTarget, gripAxisLock, gripEdgeTarget, gripPolar, gripPolarPoint, openingGripPoint, openingSheetSlide, openingTypedPosition, sheetHeightDrag, snapSheetHeight, stairMoveHandle, stairParamPoints, wallGripPoints } from "../geometry/gripDrag"; export type { EdgeDrive, GripLocks, SheetHeightKind } from "../geometry/gripDrag"; export { openingPreviewProject, openingPreviewSvgs } from "../plan/openingPreview"; export type { OpeningPreviewSvgs } from "../plan/openingPreview"; diff --git a/src/geometry/gripDrag.test.ts b/src/geometry/gripDrag.test.ts index 0747ad42..be5167fa 100644 --- a/src/geometry/gripDrag.test.ts +++ b/src/geometry/gripDrag.test.ts @@ -14,6 +14,7 @@ import { openingSheetSlide, openingTypedPosition, sheetHeightDrag, + snapSheetHeight, wallGripPoints, } from "./gripDrag"; @@ -44,10 +45,17 @@ describe("Griff-Zug (Kern)", () => { expect(gripEdgeTarget(free, { x: 3.2, y: 1.4 }, { shift: true })).toEqual({ x: 3.2, y: 1 }); }); - it("Höhen-Griffe: Patch je Art", () => { - expect(sheetHeightDrag("wallTop", { base: 3, top: 5.6, bottom: 3 }, 5.7349, false)).toEqual({ top: 5.73, bottom: 3, patch: { height: 2.73 } }); - const r = sheetHeightDrag("openingBottom", { base: 0, top: 2.1, bottom: 0.9 }, 0.6, false); - expect(r.patch).toEqual({ sillHeight: 0.6, height: 1.5 }); + it("Höhen-Griffe: Vorschau je Art, Fang", () => { + expect(sheetHeightDrag("wallTop", { base: 3, top: 5.6, bottom: 3 }, 5.7349, false)).toEqual({ top: 5.73, bottom: 3 }); + expect(sheetHeightDrag("openingBottom", { base: 0, top: 2.1, bottom: 0.9 }, 0.6, false)).toEqual({ top: 2.1, bottom: 0.6 }); + // Decke: OK schiebt die Platte, bei gebundener UK ändert sie die Dicke; UK ändert die Dicke. + const slab = { base: 0, top: 2.6, bottom: 2.35 }; + expect(sheetHeightDrag("ceilingTop", slab, 2.8, false)).toEqual({ top: 2.8, bottom: 2.55 }); + expect(sheetHeightDrag("ceilingTop", { ...slab, bottomFixed: true }, 2.8, false)).toEqual({ top: 2.8, bottom: 2.35 }); + expect(sheetHeightDrag("ceilingBottom", slab, 2.2, false)).toEqual({ top: 2.6, bottom: 2.2 }); + expect(sheetHeightDrag("wallBottom", { base: 0, top: 2.6, bottom: 0 }, -0.5, false)).toEqual({ top: 2.6, bottom: -0.5 }); + expect(snapSheetHeight(2.63, [0, 2.6, 3], 0.05)).toBe(2.6); + expect(snapSheetHeight(2.8, [0, 2.6, 3], 0.05)).toBe(2.8); }); it("Öffnung entlang der Wand und im Schnitt", () => { diff --git a/src/geometry/gripDrag.ts b/src/geometry/gripDrag.ts index a99aba3c..db5a0f24 100644 --- a/src/geometry/gripDrag.ts +++ b/src/geometry/gripDrag.ts @@ -108,23 +108,31 @@ export function gripEdgeTarget(edge: EdgeGrip, raw: Vec2, d: EdgeDrive = {}): Ve ); } -/** Art eines Höhen-Griffs im Schnitt/in der Ansicht. */ -export type SheetHeightKind = "wallTop" | "openingTop" | "openingBottom"; +/** Art eines Höhen-Griffs im Schnitt/in der Ansicht ([187]; Index = `sheet_height::Kind` im Kern). */ +export type SheetHeightKind = "wallTop" | "openingTop" | "openingBottom" | "wallBottom" | "ceilingTop" | "ceilingBottom"; + +const SHEET_KIND = { wallTop: 0, openingTop: 1, openingBottom: 2, wallBottom: 3, ceilingTop: 4, ceilingBottom: 6 } as const; /** - * Höhen-Griff auf die Blatt-Höhe `y` ziehen (1-cm-Raster, `free` = ohne): neue Ober-/Unterkante im Blatt und - * der Patch fürs Bauteil (`height`, Fenster-Unterkante zusätzlich `sillHeight`; mm-genau). + * Höhen-Griff auf die Blatt-Höhe `y` ziehen (1-cm-Raster, `free` = ohne): neue Ober-/Unterkante im Blatt für die + * Vorschau (Mindestmasse im Kern). `base` = tiefste Brüstungskante (UK der Wand), `bottomFixed` = Decke mit + * gebundener Unterkante (OK ändert dann die Dicke statt die Platte zu verschieben). Die Änderung am Bauteil + * rechnet der Kern beim Loslassen (Griff-Anfrage `sheetHeight`). */ export function sheetHeightDrag( kind: SheetHeightKind, - g: { base: number; top: number; bottom: number }, + g: { base: number; top: number; bottom: number; bottomFixed?: boolean }, y: number, free: boolean, -): { top: number; bottom: number; patch: Record } { - const k = kind === "wallTop" ? 0 : kind === "openingTop" ? 1 : 2; +): { top: number; bottom: number } { + const k = kind === "ceilingTop" && g.bottomFixed ? 5 : SHEET_KIND[kind]; const f = core().grip_sheet_height(k, g.base, g.top, g.bottom, y, free); - const patch: Record = kind === "openingBottom" ? { sillHeight: f[3], height: f[2] } : { height: f[2] }; - return { top: f[0], bottom: f[1], patch }; + return f.length ? { top: f[0], bottom: f[1] } : { top: g.top, bottom: g.bottom }; +} + +/** Fang einer Blatt-Höhe auf die nächste Kote aus `levels` innerhalb `tol` Metern. */ +export function snapSheetHeight(y: number, levels: readonly number[], tol: number): number { + return core().grip_snap_height(y, Float64Array.from(levels), tol); } /** diff --git a/src/geometry/grips.ts b/src/geometry/grips.ts index 880018d8..5f9e4d71 100644 --- a/src/geometry/grips.ts +++ b/src/geometry/grips.ts @@ -13,6 +13,7 @@ import { core } from "../engine/coreWasm"; import { toMarkedJson } from "../core/ops"; import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension"; import { textFrameCorners } from "../text/textFrame"; +import type { SheetHeightKind } from "./gripDrag"; /** Punkt als `[x, y]` (Anfragen an den Kern). */ type P = [number, number]; @@ -50,6 +51,8 @@ export type GripRequest = | { op: "insertPoint"; id: string; seg: number; pt: P } | { op: "deletePoint"; id: string; index: number } | { op: "vertexType"; id: string; index: number; vertexType: "corner" | "arc" | "spline" } + // [187] Höhen-Griff im Schnitt/in der Ansicht: Kante `kind` auf die Blatt-Höhe `a` (absolutes Z) ziehen (Kern `sheet_height.rs`). + | { op: "sheetHeight"; kind: SheetHeightKind; id: string; a: number; free?: boolean; newId: string; newName: string } | { op: "wallThickness" | "ceilingThickness"; id: string; thickness: number; newId: string; newName: string } // [144] Wandöffnung gleiten lassen (Kern `opening_slide`): Griff-Zug nach `pt` bzw. Position `a` ab Wandanfang. | { op: "openingSlide"; id: string; pt: P } diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 21908cb1..ab71ef22 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -2320,6 +2320,8 @@ export const de = { "edit.cutSegment.label": "Segment löschen", // Tab-Feld-Zyklus (Präzisionseingabe): geordnete Zahlenfelder je Schritt. "cmd.field.length": "Länge", + "cmd.field.level": "Kote", + "grip.sheetHeight": "Kote {z} m · Höhe {d} m", "cmd.field.angle": "Winkel", "cmd.field.width": "Breite", "cmd.field.height": "Höhe", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 864899d9..36c5ed68 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -2308,6 +2308,8 @@ export const en: Record = { "edit.cutSegment.label": "Delete segment", // Tab field cycle (precision input): ordered numeric fields per step. "cmd.field.length": "Length", + "cmd.field.level": "Level", + "grip.sheetHeight": "Level {z} m · height {d} m", "cmd.field.angle": "Angle", "cmd.field.width": "Width", "cmd.field.height": "Height", diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index c397d53f..a197de34 100644 --- a/src/state/projectSlice.ts +++ b/src/state/projectSlice.ts @@ -63,7 +63,7 @@ import { reorderByIds } from "../model/reorder"; import { transformMutation } from "../tools/transform"; import type { CopyMode, TransformOp, TransformSelection } from "../tools/transform"; import { uniqueId } from "../tools/types"; -import { gripPt, type GripRequest, type RingKind } from "../core"; +import { gripPt, type GripRequest, type RingKind, type SheetHeightKind } from "../core"; import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension"; import { DEFAULT_PRESETS, type TextStylePreset } from "../text/richText"; import { t } from "../i18n"; @@ -420,6 +420,8 @@ export interface ProjectSlice { ) => void; /** Setzt die Gesamtdicke einer Decke (thickness-Übersteuerung, Meter). */ setCeilingThickness: (ceilingId: string, thickness: number) => void; + /** [187] Höhen-Griff im Schnitt/in der Ansicht: Kante `kind` des Bauteils `id` auf die Blatt-Höhe `y` (absolutes Z) ziehen. */ + sheetHeightGrip: (kind: SheetHeightKind, id: string, y: number, free?: boolean) => void; // ── Öffnungs-Editieren (Object-Info-Panel) ──────────────────────────────── /** Generischer immutabler Patch auf eine Öffnung (per ID). */ @@ -1310,6 +1312,17 @@ export function createProjectSlice( newName: t("default.ceilingTypeSingle", { thickness: thickness.toFixed(2) }), }), + sheetHeightGrip: (kind, id, y, free) => + applyGrip({ + op: "sheetHeight", + kind, + id, + a: y, + free: !!free, + newId: `ct-${Date.now()}`, + newName: t("default.ceilingTypeSingle", { thickness: "{t}" }), // {t} setzt der Kern ein + }), + // ── Öffnungs-Editieren ──────────────────────────────────────────────── updateOpening: (id, patch) => applyChange((p) => patchItem(p, "openings", id, patch)), slideOpening: (id, to, coalesceKey) => diff --git a/src/state/testHooks.ts b/src/state/testHooks.ts index cd3bfa17..7db9653c 100644 --- a/src/state/testHooks.ts +++ b/src/state/testHooks.ts @@ -5,7 +5,8 @@ import { core, coreEpoch, coreReady } from "../engine/coreWasm"; import { getState } from "./appStore"; import { storeDocument } from "./historySlice"; -import { computeSection, generatePlan, generateSectionPlan, pickGeometry, projectToModel3d } from "../core"; +import { ceilingThickness } from "../model/types"; +import { computeSection, generatePlan, verticalExtents, generateSectionPlan, pickGeometry, projectToModel3d } from "../core"; import { getViewStateBridge } from "./viewTabs"; import { getView3dFilter, toFilter3d } from "./view3dFilter"; @@ -27,6 +28,12 @@ declare global { selected: () => { drawings: string[]; groups: string[]; all: string }; /** [144] Öffnungen (id, Wirtswand, Lage ab Wandanfang). */ openings: () => { id: string; hostWallId: string; position: number }[]; + /** [187] Höhen von Decken (UK/OK/Dicke), Wänden (UK/OK) und Fenstern (Brüstung/Höhe) aus dem Kern, in Metern (absolutes Z). */ + heights: () => { + ceilings: { id: string; zBottom: number; zTop: number; thickness: number }[]; + walls: { id: string; zBottom: number; zTop: number }[]; + openings: { id: string; sillHeight: number; height: number }[]; + }; /** [144] Auswahl setzen (wie ein Klick), z. B. `{ openings: ["D1"] }`. */ select: (patch: Record) => void; /** [144] Punkte einer Bemassung (Kette) — folgt sie der Öffnung? */ @@ -76,6 +83,16 @@ export function installTestHooks(): void { polylines: (prefix) => getState().project.drawings2d.flatMap((d) => (d.id.startsWith(prefix) && d.geom.shape === "polyline" ? [{ id: d.id, pts: d.geom.pts }] : [])), openings: () => (getState().project.openings ?? []).map((o) => ({ id: o.id, hostWallId: o.hostWallId, position: o.position })), + heights: () => { + const p = getState().project; + const ceilings = p.ceilings ?? []; + const ext = verticalExtents(p, p.walls, ceilings); + return { + ceilings: ceilings.map((c, i) => ({ id: c.id, zBottom: ext.ceilings[i].zBottom, zTop: ext.ceilings[i].zTop, thickness: ceilingThickness(p, c) })), + walls: p.walls.map((w, i) => ({ id: w.id, zBottom: ext.walls[i].zBottom, zTop: ext.walls[i].zTop })), + openings: (p.openings ?? []).map((o) => ({ id: o.id, sillHeight: o.sillHeight, height: o.height })), + }; + }, select: (patch) => getState().setSelection(patch), dimPts: (id) => { const g = getState().project.drawings2d.find((d) => d.id === id)?.geom; diff --git a/src/state/useGripEditing.ts b/src/state/useGripEditing.ts index 6c9505b6..208aad3e 100644 --- a/src/state/useGripEditing.ts +++ b/src/state/useGripEditing.ts @@ -5,10 +5,11 @@ // // Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). -import { useRef, useState, type RefObject } from "react"; +import { useRef, useState, useSyncExternalStore, type RefObject } from "react"; import { useEventBundle, useSameData } from "./useEvent"; import { leftNormal, normalize, scale, sub, wallCorners } from "../model/geometry"; -import type { RingKind } from "../core"; +import type { RingKind, SheetHeightKind } from "../core"; +import { t } from "../i18n"; import type { Ceiling, Drawing2D, EdgeGrip, Excavation, Project, Roof, Room, Vec2, Wall } from "../model/types"; import { wallTypeThickness } from "../model/types"; import { bulgeArcPoints, drawingVertices, surfaceOpeningGripPatch, surfaceOpeningGrips, surfaceOpeningInfo, wallArcBand } from "../core"; @@ -28,6 +29,7 @@ import { openingSheetSlide, openingTypedPosition, sheetHeightDrag, + snapSheetHeight, stairMoveHandle, stairParamPoints, wallGripPoints, @@ -37,13 +39,13 @@ import { areaMovePreview, drawingMovePreview } from "../tools/transform"; import type { DraftShape, SnapResult, SnapSettings, ToolDraft, ToolMods } from "../tools/types"; import { computeSnap } from "../tools/snapping"; import { useCommandTabShortcut } from "./useKeyboardShortcuts"; -import { sheetOwnerOutlines } from "../tools/sheetSnapGeometry"; +import { sheetOutlinesVersion, sheetOwnerOutlines, subscribeSheetOutlines } from "../tools/sheetSnapGeometry"; import type { BodyTarget } from "../views/plan/PlanView"; import type { CommandLineHandle } from "../ui/CommandLine"; import type { CommandEngine } from "../commands/engine"; import { single } from "./selection"; import { getState as storeState } from "./appStore"; -import { patchItem } from "../core"; +import { patchItem, verticalExtents } from "../core"; import { treeGripPatch, treeGripPoints } from "./treeGrips"; import type { Selection } from "./selection"; @@ -105,8 +107,8 @@ export function useGripEditing(opts: { updateOpening: (id: string, patch: Record) => void; /** [144] Wandöffnung gleiten lassen (Kern: Wand, Bogenwand, Nachbaröffnungen). */ slideOpening: (id: string, to: { position: number } | { pt: Vec2 }, coalesceKey?: string) => void; - /** Wand ändern (Höhen-Griff im Schnitt); `coalesceKey` fasst einen Zug zu EINEM Undo-Schritt. */ - updateWall: (id: string, patch: Partial, coalesceKey?: string) => void; + /** [187] Höhen-Griff im Schnitt/in der Ansicht anwenden (Kern `sheet_height.rs`); EIN Aufruf je Zug. */ + sheetHeightGrip: (kind: SheetHeightKind, id: string, y: number, free?: boolean) => void; moveStairBy: (id: string, delta: Vec2) => void; /** [151] Parameter-Griff einer Podesttreppe ziehen (Index ohne den Bewegpunkt). */ dragStairParam?: (id: string, index: number, pt: Vec2) => void; @@ -164,7 +166,7 @@ export function useGripEditing(opts: { commandLineRef, updateOpening, slideOpening, - updateWall, + sheetHeightGrip, moveStairBy, moveRoomGrip, moveCeilingGrip, @@ -178,6 +180,8 @@ export function useGripEditing(opts: { moveCeilingBy, moveElementByOf, } = opts; + // [187] Die Höhen-Griffe stehen an den gezeichneten Umrissen des Schnitts, die sich asynchron erneuern. + useSyncExternalStore(subscribeSheetOutlines, sheetOutlinesVersion); const selectedOpeningId = single(selection, "openings"); const selectedStairId = single(selection, "stairs"); // [149] Baum: Griff in der Stammmitte (verschieben) und am Kronenrand (Kronendurchmesser). @@ -268,7 +272,7 @@ export function useGripEditing(opts: { // an Ober- und Unterkante (Höhe bzw. Brüstung, Oberkante bleibt stehen); Tür nur oben. // Alles in Blatt-Koordinaten (u, Höhe über ±0.00). Projekt erst beim Loslassen. type SheetHeightGrip = { - kind: "wallTop" | "openingTop" | "openingBottom"; + kind: SheetHeightKind; id: string; pt: Vec2; u0: number; @@ -276,10 +280,15 @@ export function useGripEditing(opts: { base: number; top: number; bottom: number; + /** Decke mit gebundener Unterkante: die Oberkante ändert dann die Dicke statt die Platte zu verschieben. */ + bottomFixed?: boolean; }; + // [187] Höhen-Griffe im Schnitt/in der Ansicht: Wand (Ober-/Unterkante), Öffnung (Brüstung, Sturz), Decke (Ober-/ + // Unterkante). Breite (u, entlang der Schnittlinie) aus den gezeichneten Umrissen, Höhen (v) aus dem Modell; die + // Änderung am Bauteil rechnet der Kern beim Loslassen (`sheetHeight`). Gesperrte Bauteile haben keine. const sheetHeightGrips: SheetHeightGrip[] = (() => { if (modelEditable || !sheet) return []; - const bbox = (kind: "wall" | "opening", id: string) => { + const bbox = (kind: "wall" | "opening" | "ceiling", id: string) => { const polys = sheetOwnerOutlines(sheet.levelId, kind, id); if (polys.length === 0) return null; let u0 = Infinity, u1 = -Infinity, v0 = Infinity, v1 = -Infinity; @@ -289,28 +298,45 @@ export function useGripEditing(opts: { } return { u0, u1, v0, v1 }; }; - const floorBase = (floorId: string) => project.drawingLevels.find((l) => l.id === floorId)?.baseElevation ?? 0; + // Höhen aus dem Modell (nicht aus den gezeichneten Umrissen: ein von Fenstern oder Decken zerschnittener Rest + // reicht nicht von UK bis OK), nur die Breite (u) kommt aus dem Blatt. if (selectedOpeningId) { const op = (project.openings ?? []).find((o) => o.id === selectedOpeningId); const w = op && project.walls.find((x) => x.id === op.hostWallId); const bb = op && bbox("opening", op.id); if (!op || !w || !bb || op.locked) return []; - const base = floorBase(w.floorId); + const base = verticalExtents(project, [w]).walls[0].zBottom; + const bottom = base + Math.max(0, op.sillHeight || 0); + const top = bottom + op.height; const mid = (bb.u0 + bb.u1) / 2; - const out: SheetHeightGrip[] = [ - { kind: "openingTop", id: op.id, pt: { x: mid, y: bb.v1 }, u0: bb.u0, u1: bb.u1, base, top: bb.v1, bottom: bb.v0 }, - ]; - if (op.kind === "window") { - out.push({ kind: "openingBottom", id: op.id, pt: { x: mid, y: bb.v0 }, u0: bb.u0, u1: bb.u1, base, top: bb.v1, bottom: bb.v0 }); - } + const common = { id: op.id, u0: bb.u0, u1: bb.u1, base, top, bottom }; + const out: SheetHeightGrip[] = [{ kind: "openingTop", pt: { x: mid, y: top }, ...common }]; + if (op.kind === "window") out.push({ kind: "openingBottom", pt: { x: mid, y: bottom }, ...common }); return out; } if (selectedWallId && selectedWallIds.length <= 1) { const w = project.walls.find((x) => x.id === selectedWallId); const bb = w && bbox("wall", w.id); if (!w || !bb || w.locked) return []; + const { zBottom, zTop } = verticalExtents(project, [w]).walls[0]; + const mid = (bb.u0 + bb.u1) / 2; + const common = { id: w.id, u0: bb.u0, u1: bb.u1, base: zBottom, top: zTop, bottom: zBottom }; return [ - { kind: "wallTop", id: w.id, pt: { x: (bb.u0 + bb.u1) / 2, y: bb.v1 }, u0: bb.u0, u1: bb.u1, base: floorBase(w.floorId), top: bb.v1, bottom: bb.v0 }, + { kind: "wallTop", pt: { x: mid, y: zTop }, ...common }, + { kind: "wallBottom", pt: { x: mid, y: zBottom }, ...common }, + ]; + } + if (selectedCeilingId) { + const c = (project.ceilings ?? []).find((x) => x.id === selectedCeilingId); + const bb = c && bbox("ceiling", c.id); + if (!c || !bb || c.locked) return []; + const { zBottom, zTop } = verticalExtents(project, [], [c]).ceilings[0]; + // Dünne Platte: die zwei Griffe sitzen nebeneinander (Drittelspunkte), nicht übereinander. + const at = (f: number) => bb.u0 + (bb.u1 - bb.u0) * f; + const common = { id: c.id, u0: bb.u0, u1: bb.u1, base: zBottom, top: zTop, bottom: zBottom, bottomFixed: !!c.bottom }; + return [ + { kind: "ceilingTop", pt: { x: at(1 / 3), y: zTop }, ...common }, + { kind: "ceilingBottom", pt: { x: at(2 / 3), y: zBottom }, ...common }, ]; } return []; @@ -671,8 +697,10 @@ export function useGripEditing(opts: { const pendingWallMoveRef = useRef<{ wallId: string; total: Vec2 } | 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 (Wand `height` bzw. Öffnung `height`/`sillHeight`). */ - const pendingSheetHeightRef = useRef<{ kind: "wall" | "opening"; id: string; patch: Record } | null>(null); + /** Aufgeschobene Höhen-Änderung im Schnitt (Kante `kind` auf die Höhe `y`, Kern `sheetHeight`). */ + const pendingSheetHeightRef = useRef<{ kind: SheetHeightKind; id: string; y: number; free: boolean } | null>(null); + /** [187] Kote der gezogenen Kante im laufenden Höhen-Zug (Tab-Feld „Kote“). */ + const sheetDragRef = useRef<{ z: number } | null>(null); /** Laufendes Blatt-Delta (u, Meter) eines Zugs im Schnitt (s. moveInSheet). */ const sheetDuRef = useRef<{ id: string; du: number } | null>(null); const pendingBodyRef = useRef<{ drawingId: string; total: Vec2 } | null>(null); @@ -712,6 +740,11 @@ export function useGripEditing(opts: { const ge = gripEdit; const info = gripDragInfoRef.current; if (!ge || !info) return []; + // [187] Höhen-Zug im Schnitt: ein Feld, die Kote der gezogenen Kante (m, absolutes Z). + if (!modelEditable && sheet) { + const live = sheetDragRef.current?.z ?? 0; + return [{ id: "length", labelKey: "cmd.field.level", value: ge.locks.length ?? live, locked: ge.locks.length != null, active: true }]; + } const apex = arcWallApex(info.index); if (apex) { const live = gripArcWallRadius(apex, gripFreeRef.current, undefined, info.raw)?.radius ?? 0; @@ -802,6 +835,12 @@ export function useGripEditing(opts: { const cycleGripEditField = () => { const info = gripDragInfoRef.current; if (!info) return; + if (!modelEditable && sheet) { + // [187] Höhen-Zug: Tab friert die Kote ein (danach zählt nur der getippte Wert, Maus wirkt nicht mehr). + const z = sheetDragRef.current?.z; + if (z != null) setGripEdit((prev) => prev ?? { anchor: { x: 0, y: 0 }, active: "length", locks: { length: z } }); + return; + } const anchor = resolveGripAnchor(info.index); if (!anchor) return; // ohne Anker keine polare Eingabe möglich const wallDir = openingWallDir(); @@ -851,6 +890,11 @@ export function useGripEditing(opts: { const ge = gripEditRef.current; const info = gripDragInfoRef.current; if (!ge || !info) return; + if (!modelEditable && sheet) { + setGripEdit({ ...ge, locks: { length: value } }); + applySheetHeight(info.index, value, true); + return; + } const locks = { ...ge.locks, [ge.active]: value }; const next = ge.active === "length" && !arcWallEnd(info.index) && !arcWallApex(info.index) ? "angle" : "length"; setGripEdit({ ...ge, locks, active: next }); @@ -1156,10 +1200,7 @@ export function useGripEditing(opts: { const commitPendingGripChanges = () => { const ph = pendingSheetHeightRef.current; pendingSheetHeightRef.current = null; - if (ph) { - if (ph.kind === "wall") updateWall(ph.id, ph.patch as Partial); - else updateOpening(ph.id, ph.patch); - } + if (ph) sheetHeightGrip(ph.kind, ph.id, ph.y, ph.free); const pa = pendingAreaGripRef.current; pendingAreaGripRef.current = null; if (pa) { @@ -1334,6 +1375,8 @@ export function useGripEditing(opts: { pendingAreaMoveRef.current = null; pendingWallMoveRef.current = null; pendingOpeningMoveRef.current = null; + pendingSheetHeightRef.current = null; + sheetDragRef.current = null; sheetDuRef.current = null; pendingBodyRef.current = null; pendingEdgeRef.current = null; @@ -1417,28 +1460,48 @@ export function useGripEditing(opts: { setDraft({ preview, vertices: [], snap: null }); }; + /** + * [187] Höhen-Zug anwenden: nur Vorschau und HUD (das Projekt ändert sich beim Loslassen, EIN Undo-Schritt). + * `y` = Blatt-Höhe (absolutes Z); `free` ohne 1-cm-Raster. + */ + const applySheetHeight = (index: number, y: number, free: boolean, snapResult: SnapResult | null = null) => { + const g = sheetHeightGrips[index]; + if (!g) return; + const { top, bottom } = sheetHeightDrag(g.kind, g, y, free); + const z = g.kind.endsWith("Top") ? top : bottom; + pendingSheetHeightRef.current = { kind: g.kind, id: g.id, y, free }; + sheetDragRef.current = { z }; + setDraft({ + preview: [{ + kind: "poly", + pts: [{ x: g.u0, y: bottom }, { x: g.u1, y: bottom }, { x: g.u1, y: top }, { x: g.u0, y: top }], + closed: true, + }], + vertices: [], + snap: snapResult, + hud: { at: { x: g.pt.x, y: z }, text: t("grip.sheetHeight", { z: z.toFixed(2), d: (top - bottom).toFixed(2) }) }, + }); + }; + const gripHandlers = { onGripMove: (index: number, raw: Vec2, pxPerMeter: number, mods: ToolMods) => { sectionPxRef.current = pxPerMeter; - // Schnitt/Ansicht: Höhen-Griff (Wand-Oberkante, Fenster Ober-/Unterkante). + // Schnitt/Ansicht ([187]): Höhen-Griff (Wand, Öffnung, Decke). if (!modelEditable && sheet) { - const g = sheetHeightGrips[index]; - if (!g) return; - // 1-cm-Raster, Strg = frei; Mindestmasse und mm-Rundung im Kern (`sheetHeightDrag`). - const { top: newTop, bottom: newBottom, patch } = sheetHeightDrag(g.kind, g, raw.y, !!mods.ctrl); - pendingSheetHeightRef.current = { kind: g.kind === "wallTop" ? "wall" : "opening", id: g.id, patch }; - const bottom = g.kind === "wallTop" ? g.bottom : newBottom; - setDraft({ - preview: [{ - kind: "poly", - pts: [{ x: g.u0, y: bottom }, { x: g.u1, y: bottom }, { x: g.u1, y: newTop }, { x: g.u0, y: newTop }], - closed: true, - }], - vertices: [], - snap: null, - hud: { at: { x: (g.u0 + g.u1) / 2, y: g.kind === "openingBottom" ? newBottom : newTop }, text: `${(newTop - bottom).toFixed(2)} m` }, - }); - return; + gripDragInfoRef.current = { index, raw }; + const typed = gripEditRef.current?.locks.length; // Tab: getippte Kote + if (typed != null) return applySheetHeight(index, typed, true); + if (mods.ctrl) return applySheetHeight(index, raw.y, true); + // Fang: erst Geschoss-Koten, dann Geometrie des Schnitts (Kanten, Ecken, Höhenkoten), sonst 1-cm-Raster. + const tol = 8 / Math.max(pxPerMeter, 1e-9); + const levels = project.drawingLevels.flatMap((l) => + l.kind === "floor" ? [l.baseElevation ?? 0, (l.baseElevation ?? 0) + (l.floorHeight ?? 0)] : [], + ); + const lv = snapSheetHeight(raw.y, levels, tol); + if (lv !== raw.y) return applySheetHeight(index, lv, true); + const sn = snapFor(raw, pxPerMeter, mods); + const geo = !!sn && sn.kind !== "grid" && sn.kind !== "ortho"; + return applySheetHeight(index, geo ? sn!.point.y : raw.y, geo, geo ? sn : null); } // Erster Move-Event nach dem Grab (gripDragInfoRef noch leer): die // AKTUELLE — hier noch unveränderte — Position als Flucht-Bezugspunkt diff --git a/src/state/useProjectActions.ts b/src/state/useProjectActions.ts index 57a95c4c..04b03813 100644 --- a/src/state/useProjectActions.ts +++ b/src/state/useProjectActions.ts @@ -384,6 +384,7 @@ export function useProjectActions( const moveCeilingEdge = useStore((s) => s.moveCeilingEdge); const updateCeiling = useStore((s) => s.updateCeiling); const setCeilingThickness = useStore((s) => s.setCeilingThickness); + const sheetHeightGrip = useStore((s) => s.sheetHeightGrip); const updateStair = useStore((s) => s.updateStair); const moveStairBy = useStore((s) => s.moveStairBy); const dragStairParam = useStore((s) => s.dragStairParam); @@ -508,6 +509,7 @@ export function useProjectActions( moveCeilingEdge, updateCeiling, setCeilingThickness, + sheetHeightGrip, updateStair, moveStairBy, dragStairParam, diff --git a/src/tools/sheetSnapGeometry.ts b/src/tools/sheetSnapGeometry.ts index 4844d18d..0d0c15a9 100644 --- a/src/tools/sheetSnapGeometry.ts +++ b/src/tools/sheetSnapGeometry.ts @@ -14,6 +14,20 @@ const byLevel = new Map(); /** Je Ebene: Umriss-Polygone je Bauteil (`wall:` / `ceiling:`) — Vorschau beim Ziehen im Schnitt. */ const outlinesByLevel = new Map>(); +// [187] Die Umrisse ändern sich asynchron (der Schnitt rechnet nach Undo/Änderung neu): Höhen-Griffe, die daraus stehen, +// müssen mitziehen — Version + Abo für `useSyncExternalStore`. +let outlinesVersion = 0; +const outlineListeners = new Set<() => void>(); +const bumpOutlines = () => { + outlinesVersion++; + outlineListeners.forEach((l) => l()); +}; +export function subscribeSheetOutlines(l: () => void): () => void { + outlineListeners.add(l); + return () => void outlineListeners.delete(l); +} +export const sheetOutlinesVersion = (): number => outlinesVersion; + /** Strecken der Ebene `levelId` setzen (leeres Array/`null` = entfernen). */ export function setSheetSnapSegments(levelId: string, segs: SnapSeg[] | null): void { if (!segs || segs.length === 0) byLevel.delete(levelId); @@ -68,7 +82,7 @@ export type SheetOwnerKind = "wall" | "ceiling" | "opening" | "stair"; */ export function setSheetOwnerOutlines(levelId: string, prims: readonly Primitive[] | null): void { if (!prims) { - outlinesByLevel.delete(levelId); + if (outlinesByLevel.delete(levelId)) bumpOutlines(); return; } const map = new Map(); @@ -85,6 +99,7 @@ export function setSheetOwnerOutlines(levelId: string, prims: readonly Primitive else if (p.ceilingId) add(`ceiling:${p.ceilingId}`, p.pts); } outlinesByLevel.set(levelId, map); + bumpOutlines(); } /** Schnittflächen eines Bauteils im Blatt der Ebene `levelId` (leer, wenn nicht geschnitten). */ diff --git a/src/views/ViewportCenter.tsx b/src/views/ViewportCenter.tsx index 2baad3af..b81030eb 100644 --- a/src/views/ViewportCenter.tsx +++ b/src/views/ViewportCenter.tsx @@ -136,7 +136,7 @@ export function ViewportCenter(props: { commandLineRef, updateOpening: pa.updateOpening, slideOpening: pa.slideOpening, - updateWall: pa.updateWall, + sheetHeightGrip: pa.sheetHeightGrip, moveStairBy: pa.moveStairBy, dragStairParam: pa.dragStairParam, moveRoomGrip: pa.moveRoomGrip,