diff --git a/TODO.md b/TODO.md index 5856f5da..105347a8 100644 --- a/TODO.md +++ b/TODO.md @@ -85,7 +85,20 @@ 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 -- ○ **[185]** Navigation wie Archicad (12.11., Wunsch Maintainer): Grundriss-Geschosswechsel behält Zoom/Ausschnitt exakt; Cmd+5 Geschoss runter, Cmd+6 hoch; Cmd+3 mit Auswahl (aus Grundriss/Schnitt/3D) → 3D-Tab nur mit der Auswahl (Tab-Titel „3D · Auswahl“), ohne Auswahl → wieder alles; Cmd+4 blendet gewählte Objekte im 3D temporär aus (zurück mit Cmd+3). Sonnet. · M +- ◐ **[185]** Navigation wie Archicad (12.11., Wunsch Maintainer). Umgesetzt (12.11.): Geschosswechsel im Grundriss + (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 + `baseElevation`); Cmd/Ctrl+3 „Auswahl in 3D zeigen" (wechselt/öffnet den 3D-Reiter, Titel „3D · Auswahl", Kamera + passt ein; ohne Auswahl wieder alles), Cmd/Ctrl+4 blendet die Auswahl im 3D aus (nicht anwählbar, Auswahl leer). + Zustand rein UI (`state/view3dFilter.ts`, nicht in der Datei, kein Undo; Projektwechsel setzt zurück); Kern + `model3d::ElementSelection` im `ClassFilter` (Text `{"only", "hideIds"}`: Teile, Cache, Pick, Spuren, Muster; + gewählte Wand zeigt ihre Öffnungen, gewählte Öffnung bringt ihren Wirt mit). Kürzel umbelegbar (Einstellungen, + Gruppe „Navigation"), natives Menü Ansicht mit denselben Kürzeln. Nebenbei: `PlanViewHandle.pxPerMeter` las die + erste viewBox (Reiter/Ausschnitte merkten den Start-Zoom statt des aktuellen), jetzt aus der Ref. Tests `model3d/classes.rs` + (`element_auswahl_*`), `viewTabs.test.ts`, `view3dFilter.test.ts`, `toWalls3d.classes.test.ts`, e2e + `navigation185.spec.ts`. Offen: natives Mac-3D-Fenster kennt den Element-Filter nicht; Ebenen-Panel-Wechsel nicht + einzeln e2e geprüft; nicht in der Tauri-App/auf dem Mac geprüft (Menü-Kürzel vs. Browser-Kürzel). · M - ◐ **[133]** Musterhaus komplex: Rest. Skalieren-Kopie lässt `position`/Breite unverändert (10.11.: Skalieren skaliert `position`/`width` der Wandöffnungen bei Kopie und Original, Test `skalieren_skaliert_oeffnungen`). 11.11.: Schraffur- Ausbreiten: Vollfläche füllt in Schraffurfarbe, Bild-Schraffur als ``/`` (CLI `--hatch`; Druck/PDF hatte diff --git a/e2e/navigation185.spec.ts b/e2e/navigation185.spec.ts new file mode 100644 index 00000000..3a18af4d --- /dev/null +++ b/e2e/navigation185.spec.ts @@ -0,0 +1,97 @@ +// [185] Navigation wie Archicad: Geschosswechsel per Ctrl/Cmd+6 behält Zoom und Ausschnitt exakt; Ctrl/Cmd+3 zeigt die +// Auswahl allein im 3D (Reiter „3D · Auswahl"), Ctrl/Cmd+4 blendet sie aus, Ctrl/Cmd+3 ohne Auswahl zeigt wieder alles. +// Das 3D-Bild ist headless leer (kein WebGPU): geprüft wird über den Store und die 3D-Teile/Pick-Geometrie. +import { discardIfAsked, drawingTab, drawingTabs, expect, fileMenu, openTab, test } from "./app"; + +test("Geschoss per Ctrl+6/5 mit gleichem Ausschnitt, Auswahl in 3D zeigen/ausblenden", async ({ page }) => { + test.setTimeout(150_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 }); + const tabs = drawingTabs(page).getByRole("tab"); + const nav = (name: string) => page.locator(".nav-row").filter({ hasText: name }).first(); + const cam = () => page.evaluate(() => window.__dossierTest!.viewCamera()); + const v3d = () => page.evaluate(() => window.__dossierTest!.view3d()); + + await openTab(page, "Zeichnungsebenen"); + await nav("Erdgeschoss").click(); + const plan = page.locator("svg.plan-svg").first(); + await expect(plan).toBeVisible({ timeout: 30_000 }); + const eg = (await cam()).levelId; + + // Zoomen und verschieben (Rad an einer Stelle abseits der Mitte). + await page.waitForTimeout(500); + const fitted = await cam(); + const box = (await plan.boundingBox())!; + await page.mouse.move(box.x + box.width * 0.3, box.y + box.height * 0.4); + for (let i = 0; i < 3; i++) { + await page.mouse.wheel(0, -240); + await page.waitForTimeout(120); + } + await page.waitForTimeout(500); + const before = await cam(); + expect(before.center && before.pxPerMeter).toBeTruthy(); + expect(before.pxPerMeter, "Rad hat gezoomt").not.toBeCloseTo(fitted.pxPerMeter!, 3); + + // Ctrl+6: Obergeschoss im selben Reiter, gleicher Ausschnitt. + await page.keyboard.press("Control+6"); + await expect(drawingTab(page, "Obergeschoss")).toHaveAttribute("aria-selected", "true"); + await expect(tabs).toHaveCount(1); + await page.waitForTimeout(500); + const after = await cam(); + expect(after.levelId).not.toBe(eg); + expect(after.pxPerMeter).toBeCloseTo(before.pxPerMeter!, 6); + expect(after.center!.x).toBeCloseTo(before.center!.x, 6); + expect(after.center!.y).toBeCloseTo(before.center!.y, 6); + expect(after.scale).toBe(before.scale); + + // Ctrl+5: zurück ins Erdgeschoss, Ausschnitt weiter gleich. + await page.keyboard.press("Control+5"); + await expect(drawingTab(page, "Erdgeschoss")).toHaveAttribute("aria-selected", "true"); + await page.waitForTimeout(300); + const back = await cam(); + expect(back.levelId).toBe(eg); + expect(back.center!.x).toBeCloseTo(before.center!.x, 6); + expect(back.pxPerMeter).toBeCloseTo(before.pxPerMeter!, 6); + await page.keyboard.press("Control+6"); + await expect(drawingTab(page, "Obergeschoss")).toHaveAttribute("aria-selected", "true"); + + // Wand wählen → Ctrl+3: 3D-Reiter „3D · Auswahl", nur diese Wand im Modell und im Pick. + const all = await v3d(); + expect(all.only).toBeNull(); + expect(all.walls.length).toBeGreaterThan(3); + const wall = all.walls[0]; + await page.evaluate((id) => window.__dossierTest!.select({ walls: [id] }), wall); + await page.keyboard.press("Control+3"); + await expect(drawingTab(page, "3D · Auswahl")).toHaveAttribute("aria-selected", "true"); + await expect(tabs).toHaveCount(2); + const only = await v3d(); + expect(only.only).toEqual([wall]); + expect(only.walls).toEqual([wall]); + expect(only.pickWalls).toEqual([wall]); + + // Ctrl+4: die gewählte Wand ausblenden (nicht mehr im Modell, nicht anwählbar), Auswahl leer. + await page.keyboard.press("Control+4"); + await expect.poll(async () => (await v3d()).hidden).toEqual([wall]); + const hidden = await v3d(); + expect(hidden.walls).toEqual([]); + expect(hidden.pickWalls).toEqual([]); + expect(JSON.parse((await page.evaluate(() => window.__dossierTest!.selected())).all).walls).toEqual([]); + + // Ctrl+3 ohne Auswahl: wieder alles, normaler 3D-Reiter. + await page.keyboard.press("Control+3"); + await expect(drawingTab(page, "3D · Obergeschoss")).toHaveAttribute("aria-selected", "true"); + await expect(tabs).toHaveCount(2); + const again = await v3d(); + expect(again.only).toBeNull(); + expect(again.hidden).toEqual([]); + expect(again.walls).toEqual(all.walls); + + // Ctrl+5 im 3D-Reiter: aktives Geschoss wechselt, bleibt 3D. + await page.keyboard.press("Control+5"); + await expect(drawingTab(page, "3D · Erdgeschoss")).toHaveAttribute("aria-selected", "true"); + await expect(tabs).toHaveCount(2); +}); diff --git a/src-tauri/core/src/model3d/classes.rs b/src-tauri/core/src/model3d/classes.rs index 7804933e..cc1cd3c9 100644 --- a/src-tauri/core/src/model3d/classes.rs +++ b/src-tauri/core/src/model3d/classes.rs @@ -44,6 +44,21 @@ impl Owner { } } +/// [185] Element-Auswahl im 3D (rein UI, nicht im Projekt): „Auswahl in 3D zeigen" (`only`, `None` = alle) und +/// temporär ausgeblendete Elemente (`hide`). Wirkt wie eine ausgeblendete Klasse: fehlt in Teilen und Pick. +#[derive(Debug, Clone, Default)] +pub struct ElementSelection { + pub only: Option>, + pub hide: HashSet, +} + +impl ElementSelection { + /// Keine Einschränkung. + pub fn is_empty(&self) -> bool { + self.only.is_none() && self.hide.is_empty() + } +} + /// Ausgeblendete Klassen und die ids der Elemente darauf. #[derive(Debug, Clone, Default)] pub struct ClassFilter { @@ -59,14 +74,29 @@ impl ClassFilter { /// Ebenen-Baum des Projekts plus die Codes `extra` (Darstellungsmodus des Aufrufers). pub fn new(p: &Project, extra: &[String]) -> ClassFilter { + ClassFilter::with_elements(p, extra, &ElementSelection::default()) + } + + /// Wie [`Self::new`], dazu die Element-Auswahl `sel` ([185]): nur `only` zeigen, `hide` ausblenden. + pub fn with_elements(p: &Project, extra: &[String], sel: &ElementSelection) -> ClassFilter { let mut codes: HashSet = hidden_category_codes(&p.layers).into_iter().map(String::from).collect(); codes.extend(extra.iter().cloned()); let mut ids = HashSet::new(); - if codes.is_empty() { + if codes.is_empty() && sel.is_empty() { return ClassFilter { codes, ids }; } + // Gewählte Öffnungen bringen ihren Wirt mit (eine Öffnung ohne Wand gibt es im 3D nicht). + let only: Option> = sel.only.as_ref().map(|o| { + let mut s: HashSet<&str> = o.iter().map(String::as_str).collect(); + for op in p.openings.as_deref().unwrap_or(&[]) { + if o.contains(&op.id) { + s.insert(op.host_wall_id.as_str()); + } + } + s + }); let mut add = |code: &str, id: &str| { - if codes.contains(code) { + if codes.contains(code) || sel.hide.contains(id) || only.as_ref().is_some_and(|o| !o.contains(id)) { ids.insert(id.to_owned()); } }; @@ -97,31 +127,33 @@ impl ClassFilter { for d in &p.drawings2d { add(&d.category_code, &d.id); } - // Öffnungen nach den Wirten (Wand, Dach, Decke), die jetzt schon in `ids` stehen. + // Öffnungen nach den Wirten (Wand, Dach, Decke), die jetzt schon in `ids` stehen; mit `only` zeigt + // ein gewählter Wirt seine Öffnungen. let hidden_openings: Vec = p .openings .as_deref() .unwrap_or(&[]) .iter() - .filter(|o| codes.contains(&o.category_code) || ids.contains(&o.host_wall_id)) + .filter(|o| codes.contains(&o.category_code) || sel.hide.contains(&o.id) || ids.contains(&o.host_wall_id)) .map(|o| o.id.clone()) .collect(); ids.extend(hidden_openings); ClassFilter { codes, ids } } - /// `text` der 3D-Abfragen: `{"hide": [codes], …}` (fehlt/kein JSON: nur der Ebenen-Baum). + /// `text` der 3D-Abfragen: `{"hide": [codes], "only": [ids], "hideIds": [ids], …}` (fehlt/kein JSON: + /// nur der Ebenen-Baum; `only` fehlt/`null` = alle Elemente, [185]). pub fn from_text(p: &Project, text: &str) -> ClassFilter { let t = text.trim(); - let extra: Vec = if t.starts_with('{') { - serde_json::from_str::(t) - .ok() - .and_then(|v| v.get("hide").and_then(|a| a.as_array()).map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect())) - .unwrap_or_default() - } else { - Vec::new() + let v = if t.starts_with('{') { serde_json::from_str::(t).ok() } else { None }; + let list = |key: &str| -> Option> { + v.as_ref() + .and_then(|v| v.get(key)) + .and_then(|a| a.as_array()) + .map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect()) }; - ClassFilter::new(p, &extra) + let sel = ElementSelection { only: list("only").map(|o| o.into_iter().collect()), hide: list("hideIds").unwrap_or_default().into_iter().collect() }; + ClassFilter::with_elements(p, &list("hide").unwrap_or_default(), &sel) } /// Kein Element ausgeblendet. @@ -247,6 +279,62 @@ mod tests { [col, tree, stair, lines] } + /// [185] Element-Auswahl: `only` zeigt nur die genannten Elemente, `hideIds` blendet sie aus — in Teilen und Pick. + #[test] + fn element_auswahl_only_und_hide_ids() { + let p = project(&[]); + let ids = ["k1", "T1", "s1", "L"]; + for gap in [0.0, 2.0] { + for (k, id) in ids.into_iter().enumerate() { + for (text, shown) in [(format!(r#"{{"only":["{id}"]}}"#), true), (format!(r#"{{"hideIds":["{id}"]}}"#), false)] { + let f = ClassFilter::from_text(&p, &text); + let got = counts(&p, &f, gap); + for (i, n) in got.iter().enumerate() { + // `only`: nur das genannte Element da; `hideIds`: nur das genannte fehlt. + assert_eq!(*n > 0, (i == k) == shown, "{text}, Abstand {gap}: {got:?}"); + } + let mut g = crate::explode3d::pick_geometry(&p, gap).unwrap(); + f.retain_pick(&mut g); + let picks = [g.columns.len(), g.trees.len(), g.stairs.len() + g.stair_meshes.len(), g.drawings.len()]; + for (i, n) in picks.iter().enumerate() { + assert_eq!(*n > 0, (i == k) == shown, "Pick {text}, Abstand {gap}: {picks:?}"); + } + } + } + } + // Leere Auswahl `only: []` zeigt nichts, `only: null` alles. + assert!(counts(&p, &ClassFilter::from_text(&p, r#"{"only":[]}"#), 0.0).iter().all(|&n| n == 0)); + assert!(counts(&p, &ClassFilter::from_text(&p, r#"{"only":null}"#), 0.0).iter().all(|&n| n > 0)); + } + + /// [185] Gewählte Wand zeigt ihre Öffnungen; gewählte Öffnung bringt ihren Wirt mit; ausgeblendete Wand nimmt sie mit. + #[test] + fn element_auswahl_oeffnungen_folgen_dem_wirt() { + let mut p = project(&[]); + let mut v = serde_json::to_value(&p).unwrap(); + v["walls"] = serde_json::json!([ + {"id": "w1", "type": "wall", "floorId": "EG", "categoryCode": "20", "start": {"x": 0, "y": 0}, "end": {"x": 5, "y": 0}, "wallTypeId": "aw", "height": 2.8}, + {"id": "w2", "type": "wall", "floorId": "EG", "categoryCode": "20", "start": {"x": 0, "y": 4}, "end": {"x": 5, "y": 4}, "wallTypeId": "aw", "height": 2.8}]); + v["wallTypes"] = serde_json::json!([{"id": "aw", "name": "AW", "layers": [{"componentId": "c", "thickness": 0.2}]}]); + v["openings"] = serde_json::json!([{"id": "o1", "type": "opening", "kind": "window", "hostWallId": "w1", "categoryCode": "40", "position": 2.0, "width": 1.0, "height": 1.2, "sillHeight": 0.9}]); + p = match serde_json::from_value(v) { + Ok(p) => p, + Err(e) => panic!("Projekt: {e}"), + }; + let f = ClassFilter::from_text(&p, r#"{"only":["w1"]}"#); + assert!(!f.hides("w1") && !f.hides("o1") && f.hides("w2") && f.hides("k1")); + let f = ClassFilter::from_text(&p, r#"{"only":["o1"]}"#); + assert!(!f.hides("w1") && !f.hides("o1") && f.hides("w2")); + let f = ClassFilter::from_text(&p, r#"{"hideIds":["w1"]}"#); + assert!(f.hides("w1") && f.hides("o1") && !f.hides("w2")); + let f = ClassFilter::from_text(&p, r#"{"hideIds":["o1"]}"#); + assert!(!f.hides("w1") && f.hides("o1")); + let mut g = crate::explode3d::pick_geometry(&p, 0.0).unwrap(); + ClassFilter::from_text(&p, r#"{"only":["w2"]}"#).retain_pick(&mut g); + assert!(g.walls.iter().all(|w| w.wall_id == "w2") && !g.walls.is_empty()); + assert!(g.openings.is_empty() && g.columns.is_empty()); + } + /// Jede Klasse einzeln aus (Ebenen-Baum bzw. `hide`): nur ihr Teil fehlt im 3D (auch in der Explosion) und im Pick. #[test] fn klasse_aus_teil_fehlt_in_parts_und_pick() { diff --git a/src/DrawingTabs.tsx b/src/DrawingTabs.tsx index 56f50748..e7145dac 100644 --- a/src/DrawingTabs.tsx +++ b/src/DrawingTabs.tsx @@ -13,6 +13,7 @@ import { memo } from "react"; import type { ViewSnapshot } from "./model/types"; import { useStore } from "./state/appStore"; import { tabTitle, type ViewTab, type ViewTabsState } from "./state/viewTabs"; +import { isSelectionMode, useView3dFilter } from "./state/view3dFilter"; import { t } from "./i18n"; /** Handler-Bündel der Reiterleiste (Host-Handler in state/usePanelHostBase.ts). */ @@ -33,11 +34,15 @@ export const DrawingTabs = memo(function DrawingTabs({ handlers }: { handlers: V const { tabs, onActivate, onNew, onClose, autoName } = handlers; const liveLevelId = useStore((s) => s.activeLevelId); const liveIs3d = useStore((s) => s.viewType === "perspektive"); + // [185] „Auswahl in 3D zeigen": 3D-Reiter heissen „3D · Auswahl". + const selection3d = isSelectionMode(useView3dFilter()); // 3D-Reiter heissen „3D · Geschoss" (der aktive liest die Live-Ansicht). const title = (tab: ViewTab) => - tabTitle(tab, snapshots, (tb) => - tb.id === tabs.activeId ? autoName(liveIs3d ? liveLevelId : undefined, liveIs3d) : autoName(tb.state?.activeLevelId, tb.state?.viewType === "perspektive"), - ); + tabTitle(tab, snapshots, (tb) => { + const is3d = tb.id === tabs.activeId ? liveIs3d : tb.state?.viewType === "perspektive"; + if (is3d && selection3d) return t("tabs.3dSelection"); + return tb.id === tabs.activeId ? autoName(liveIs3d ? liveLevelId : undefined, liveIs3d) : autoName(tb.state?.activeLevelId, tb.state?.viewType === "perspektive"); + }); const closable = tabs.tabs.length > 1; return ( diff --git a/src/core/index.ts b/src/core/index.ts index 986d46fd..6d9c9eee 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -263,5 +263,7 @@ export { } from "../plan/toWalls3d"; export type { Model3dPart } from "../plan/toWalls3d"; export { hiddenClassCodes } from "../plan/toWalls3d"; +export { filter3d } from "../plan/toWalls3d"; +export type { Filter3d, Hide3d } from "../plan/toWalls3d"; export * from "./extra"; diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 4d0604e5..6a5802df 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -117,6 +117,10 @@ export const de = { "menu.view.floorplan": "Grundriss", "menu.view.perspective": "Perspektive", "menu.view.referenceLines": "Referenzlinien", + "menu.view.floorDown": "Geschoss tiefer", + "menu.view.floorUp": "Geschoss höher", + "menu.view.showSelection3d": "Auswahl in 3D zeigen", + "menu.view.hideSelection3d": "Auswahl im 3D ausblenden", "menu.window": "Fenster", "menu.window.resources": "Ressourcen", "menu.window.settings": "Einstellungen", @@ -342,6 +346,7 @@ export const de = { // ── Dokument-Tabs (Zeichnungen/Blätter) ───────────────────────────────── "tabs.drawings": "Zeichnungen", "tabs.3d": "3D", + "tabs.3dSelection": "3D · Auswahl", "tabs.add": "Neuer Reiter mit der aktuellen Ansicht", "tabs.close": "Reiter „{name}\" schliessen", @@ -3029,6 +3034,7 @@ export const de = { "settings.keyboardShortcuts.category.transform": "Transformieren", "settings.keyboardShortcuts.category.group": "Gruppieren", "settings.keyboardShortcuts.category.tools": "Werkzeuge", + "settings.keyboardShortcuts.category.navigation": "Navigation", "shortcut.undo": "Rückgängig", "shortcut.redo": "Wiederholen", @@ -3057,6 +3063,10 @@ export const de = { "shortcut.toolWindow": "Werkzeug: Fenster", "shortcut.toolDoor": "Werkzeug: Tür", "shortcut.toolRoom": "Werkzeug: Raum", + "shortcut.floorDown": "Geschoss tiefer", + "shortcut.floorUp": "Geschoss höher", + "shortcut.showSelection3d": "Auswahl in 3D zeigen (ohne Auswahl: alles)", + "shortcut.hideSelection3d": "Auswahl im 3D ausblenden", "settings.section.update": "Update", "settings.update.autoCheck": "Automatisch nach Updates suchen", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index df9a3429..ec3f02c4 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -116,6 +116,10 @@ export const en: Record = { "menu.view.floorplan": "Floor plan", "menu.view.perspective": "Perspective", "menu.view.referenceLines": "Reference lines", + "menu.view.floorDown": "Story down", + "menu.view.floorUp": "Story up", + "menu.view.showSelection3d": "Show selection in 3D", + "menu.view.hideSelection3d": "Hide selection in 3D", "menu.window": "Window", "menu.window.resources": "Resources", "menu.window.settings": "Settings", @@ -340,6 +344,7 @@ export const en: Record = { // Document tabs (drawings/sheets). "tabs.drawings": "Drawings", "tabs.3d": "3D", + "tabs.3dSelection": "3D · Selection", "tabs.add": "New tab with the current view", "tabs.close": "Close tab “{name}”", @@ -3016,6 +3021,7 @@ export const en: Record = { "settings.keyboardShortcuts.category.transform": "Transform", "settings.keyboardShortcuts.category.group": "Grouping", "settings.keyboardShortcuts.category.tools": "Tools", + "settings.keyboardShortcuts.category.navigation": "Navigation", "shortcut.undo": "Undo", "shortcut.redo": "Redo", @@ -3044,6 +3050,10 @@ export const en: Record = { "shortcut.toolWindow": "Tool: Window", "shortcut.toolDoor": "Tool: Door", "shortcut.toolRoom": "Tool: Room", + "shortcut.floorDown": "Story down", + "shortcut.floorUp": "Story up", + "shortcut.showSelection3d": "Show selection in 3D (no selection: everything)", + "shortcut.hideSelection3d": "Hide selection in 3D", "settings.section.update": "Update", "settings.update.autoCheck": "Check for updates automatically", diff --git a/src/native/appMenu.ts b/src/native/appMenu.ts index ed5d6339..5c7f3345 100644 --- a/src/native/appMenu.ts +++ b/src/native/appMenu.ts @@ -55,6 +55,12 @@ export interface NativeAppMenuHandlers { onViewType: (v: ViewType) => void; onView3d: (v: View3d) => void; onReferenceLines: (v: boolean) => void; + /** [185] Geschoss tiefer (−1, Cmd+5) / höher (+1, Cmd+6) im Grundriss-/3D-Reiter. */ + onFloorStep?: (dir: 1 | -1) => void; + /** [185] Auswahl in 3D zeigen (Cmd+3; ohne Auswahl alles). */ + onShowSelection3d?: () => void; + /** [185] Auswahl im 3D ausblenden (Cmd+4). */ + onHideSelection3d?: () => void; onToggleResources: () => void; onOpenSettings: () => void; @@ -341,6 +347,28 @@ export function useNativeAppMenu( ...view3dItems, await PredefinedMenuItem.new({ item: "Separator" }), referenceLinesItem, + // [185] Navigation wie Archicad (dieselben Kürzel laufen im Browser über `useViewNavigationShortcuts`). + await PredefinedMenuItem.new({ item: "Separator" }), + await MenuItem.new({ + text: t("menu.view.floorDown"), + accelerator: "CmdOrCtrl+5", + action: () => handlersRef.current.onFloorStep?.(-1), + }), + await MenuItem.new({ + text: t("menu.view.floorUp"), + accelerator: "CmdOrCtrl+6", + action: () => handlersRef.current.onFloorStep?.(1), + }), + await MenuItem.new({ + text: t("menu.view.showSelection3d"), + accelerator: "CmdOrCtrl+3", + action: () => handlersRef.current.onShowSelection3d?.(), + }), + await MenuItem.new({ + text: t("menu.view.hideSelection3d"), + accelerator: "CmdOrCtrl+4", + action: () => handlersRef.current.onHideSelection3d?.(), + }), ], }); diff --git a/src/plan/toWalls3d.classes.test.ts b/src/plan/toWalls3d.classes.test.ts index 54792311..371738a2 100644 --- a/src/plan/toWalls3d.classes.test.ts +++ b/src/plan/toWalls3d.classes.test.ts @@ -79,4 +79,31 @@ describe("3D nach Klassen ([180])", () => { expect(s.has("20") && s.has("21") && s.has("31")).toBe(true); expect(s.has("30")).toBe(false); }); + + it("[185] Element-Auswahl: `only` zeigt nur die Wand (samt ihren Öffnungen), `hideIds` blendet sie aus — Modell, Teile und Pick", () => { + const host = (p.openings ?? [])[0].hostWallId; + const hostOf = new Map((p.openings ?? []).map((o) => [o.id, o.hostWallId])); + const others = p.walls.filter((w) => w.id !== host).length; + const wallIds = (m: ReturnType) => new Set(m.walls.map((w) => w.wallId)); + const only = projectToModel3d(p, { hide: { only: [host] } }); + expect([...wallIds(only)]).toEqual([host]); + expect(only.slabs).toHaveLength(0); + expect(roofs(only)).toBe(0); + const g = pickGeometry(p, 0, { only: [host] }); + expect(new Set(g.walls.map((w) => w.wallId))).toEqual(new Set([host])); + expect(g.openings.length).toBeGreaterThan(0); + expect(g.openings.every((o) => hostOf.get(o.openingId) === host)).toBe(true); + expect(g.slabs).toHaveLength(0); + const parts = projectToModel3dParts(p, { hide: { only: [host] } })!; + expect(parts.flatMap((x) => x.walls ?? []).every((w) => w.wallId === host)).toBe(true); + + const hid = projectToModel3d(p, { hide: { hideIds: [host] } }); + expect(wallIds(hid).has(host)).toBe(false); + expect(wallIds(hid).size).toBe(others); + const gh = pickGeometry(p, 0, { hideIds: [host] }); + expect(gh.walls.some((w) => w.wallId === host)).toBe(false); + expect(gh.openings.some((o) => hostOf.get(o.openingId) === host)).toBe(false); + // Kein Filter: alles wieder da. + expect(wallIds(projectToModel3d(p, { hide: { only: null, hideIds: [] } })).size).toBe(p.walls.length); + }); }); diff --git a/src/plan/toWalls3d.ts b/src/plan/toWalls3d.ts index 5f0a1281..24497589 100644 --- a/src/plan/toWalls3d.ts +++ b/src/plan/toWalls3d.ts @@ -72,7 +72,7 @@ export function emitDrawingLineVerts( /** Explosionsabstand ([65]): Spuren heben sich mit ihrem Geschoss; 0 = aus. */ explode = 0, /** [180] Zusätzlich ausgeblendete Klassen (Darstellungsmodus), s. {@link Model3dOptions.hide}. */ - hide?: readonly string[], + hide?: Hide3d, ): Float32Array { return documentFor(project).drawingLineVerts(explodeGap(explode), classFilterText(hide)); } @@ -82,17 +82,44 @@ export function emitDrawingLineVerts( * Ebenen-Baum aus sind (Ebenen-Panel, Kombinationen, Vorlagen); `hide` ergänzt die, die der Darstellungsmodus * nicht zeichnet (`categoryDisplay(code).render === false`). */ -export function classFilterText(hide?: readonly string[], extra?: Record): string { - const h = hide && hide.length ? { hide } : {}; - return hide?.length || extra ? JSON.stringify({ ...extra, ...h }) : ""; +export function classFilterText(hide?: Hide3d, extra?: Record): string { + const f = filter3d(hide); + const h: Record = f.hide?.length ? { hide: f.hide } : {}; + // [185] Element-Auswahl: `only` (nur diese Elemente) und `hideIds` (temporär ausgeblendet), s. `model3d::ElementSelection`. + if (f.only) h.only = f.only; + if (f.hideIds?.length) h.hideIds = f.hideIds; + return Object.keys(h).length || extra ? JSON.stringify({ ...extra, ...h }) : ""; +} + +/** + * [185] 3D-Filter: Klassen-Codes (`hide`, wie bisher) und die Element-Auswahl der 3D-Ansicht — `only` = nur diese + * Element-ids zeigen („Auswahl in 3D zeigen", `null`/fehlt = alle), `hideIds` = temporär ausgeblendete. Rein UI. + */ +export interface Filter3d { + hide?: readonly string[]; + only?: readonly string[] | null; + hideIds?: readonly string[]; +} + +/** Klassen-Codes (bisherige Form) oder der volle {@link Filter3d}. */ +export type Hide3d = readonly string[] | Filter3d; + +/** {@link Hide3d} als {@link Filter3d}. */ +export function filter3d(hide?: Hide3d): Filter3d { + if (!hide) return {}; + return isCodeList(hide) ? { hide } : hide; +} + +function isCodeList(h: Hide3d): h is readonly string[] { + return Array.isArray(h); } /** * [180] Ausgeblendete Klassen-Codes (Ebenen-Baum samt Elternklassen, dazu `hide`) — für die 3D-Zutaten, die * nicht aus dem Kern-Modell kommen (Schatten, Baurechts-Hülle); die Teile filtert der Kern. */ -export function hiddenClassCodes(project: Project, hide?: readonly string[]): Set { - const out = new Set(hide ?? []); +export function hiddenClassCodes(project: Project, hide?: Hide3d): Set { + const out = new Set(filter3d(hide).hide ?? []); const visible = collectVisibleCodes(project.layers ?? []); for (const c of flattenCategories(project.layers ?? [])) if (!visible.has(c.code)) out.add(c.code); return out; @@ -116,7 +143,7 @@ export function emitSurfacePatternLines( /** Explosionsabstand ([65]): Linien heben sich mit dem Geschoss ihres Bauteils; 0 = aus. */ explode = 0, /** [180] Zusätzlich ausgeblendete Klassen, s. {@link Model3dOptions.hide}. */ - hide?: readonly string[], + hide?: Hide3d, ): Float32Array { return documentFor(project).surfacePatternLines(explodeGap(explode), classFilterText(hide)); } @@ -193,9 +220,9 @@ export interface Model3dOptions { /** * [180] Klassen, die zusätzlich zum Ebenen-Baum nicht gezeichnet werden (Darstellungsmodus des Ebenen-Panels). * Ausgeblendete Klassen fehlen im Modell, in der Pick-Geometrie und im Export der Ansicht (Kern filtert nach dem - * Cache, Umschalten rechnet keine Wand neu). + * Cache, Umschalten rechnet keine Wand neu). [185] Auch als {@link Filter3d} mit Element-Auswahl. */ - hide?: readonly string[]; + hide?: Hide3d; } /** Das volle 3D-Modell: Wände (mit Öffnungen) + Deckenplatten + Kontext-Meshes. */ @@ -337,7 +364,7 @@ export function pickGeometry( /** Explosionsabstand ([65]) wie bei {@link projectToModel3d}; 0 = aus. */ explode = 0, /** [180] Zusätzlich ausgeblendete Klassen (nicht anwählbar), s. {@link Model3dOptions.hide}. */ - hide?: readonly string[], + hide?: Hide3d, ): { walls: RWall[]; slabs: RSlab[]; diff --git a/src/state/README.md b/src/state/README.md index e93c3dab..41b44e4b 100644 --- a/src/state/README.md +++ b/src/state/README.md @@ -66,6 +66,7 @@ in `ProjectSync`. | `viewTemplates.ts` | Ansichtsvorlagen als Ops | | `viewSnapshots.ts`, `viewSnapshotFolders.ts`, `viewTabs.ts` | Ausschnitte, ihre Ordner, Zeichnungs-Reiter (mit dem Projekt als `uiState.viewTabs` gesichert, [136]); Reiter-Arten und Navigations-Regeln ([182]) | | `tabNavigation.ts` | Navigator/Grundriss-/3D-Knöpfe/Layouts wählen den passenden Reiter (`openLevel`, `switchViewType`, `openLayoutTab`, [182]) | +| `view3dFilter.ts` | 3D-Element-Filter ([185], rein UI): „Auswahl in 3D zeigen" (Cmd/Ctrl+3) und temporär ausgeblendete Elemente (Cmd/Ctrl+4); Geschoss-Kürzel Cmd/Ctrl+5/6 in `tabNavigation.ts` | | `groupActions.ts` | Gruppen erzeugen, auflösen, betreten | | `exportScope.ts`, `objectLock.ts` | Export „nur Auswahl"; Objekt-Sperre | | `autosave.ts`, `projectStore.ts`, `recentProjects.ts`, `startupGuard.ts` | Autosave und Wiederherstellen, IndexedDB, zuletzt geöffnet, Start-Protokoll | diff --git a/src/state/keyboardShortcuts.ts b/src/state/keyboardShortcuts.ts index 3dae05fb..30f9d4fa 100644 --- a/src/state/keyboardShortcuts.ts +++ b/src/state/keyboardShortcuts.ts @@ -48,7 +48,11 @@ export type ShortcutId = | "toolCeiling" | "toolWindow" | "toolDoor" - | "toolRoom"; + | "toolRoom" + | "floorDown" + | "floorUp" + | "showSelection3d" + | "hideSelection3d"; export type ShortcutCategory = | "general" @@ -57,7 +61,8 @@ export type ShortcutCategory = | "boolean" | "transform" | "group" - | "tools"; + | "tools" + | "navigation"; export interface ShortcutDef { id: ShortcutId; @@ -204,6 +209,11 @@ export const SHORTCUT_DEFS: ShortcutDef[] = [ defaultCombo: "0", bareKeyOnly: true, }, + // [185] Navigation wie Archicad. + { id: "floorDown", category: "navigation", labelKey: "shortcut.floorDown", defaultCombo: "mod+5" }, + { id: "floorUp", category: "navigation", labelKey: "shortcut.floorUp", defaultCombo: "mod+6" }, + { id: "showSelection3d", category: "navigation", labelKey: "shortcut.showSelection3d", defaultCombo: "mod+3" }, + { id: "hideSelection3d", category: "navigation", labelKey: "shortcut.hideSelection3d", defaultCombo: "mod+4" }, ]; const DEFS_BY_ID = new Map(SHORTCUT_DEFS.map((d) => [d.id, d])); diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index 8177d3eb..c397d53f 100644 --- a/src/state/projectSlice.ts +++ b/src/state/projectSlice.ts @@ -72,6 +72,7 @@ import { createHistorySlice, historyPatch, labelCommit, storeDocument } from "./ import type { HistorySlice } from "./historySlice"; import { opsLabel } from "./historyLabels"; import { resetViewTabs, restoreViewTabsFromProject } from "./viewTabs"; +import { resetView3dFilter } from "./view3dFilter"; import type { NotifyKind } from "./notifySlice"; /** Felder, die diese Slice in den RootState beisteuert. */ @@ -658,6 +659,7 @@ export function createProjectSlice( doc.load(next); set({ project: next, projectEpoch: get().projectEpoch + 1, ...historyPatch(doc) }); resetViewTabs(); // [136] neues Projekt: ein Reiter mit der aktuellen Ansicht + resetView3dFilter(); // [185] keine 3D-Element-Auswahl aus dem vorigen Projekt }, openProjectFile: (text) => { @@ -666,6 +668,7 @@ export function createProjectSlice( if (r.ok) { set({ project: r.project, projectEpoch: get().projectEpoch + 1, ...historyPatch(doc) }); restoreViewTabsFromProject(r.project); // [136] gesicherte Reiter, sonst ein Reiter + resetView3dFilter(); // [185] } return r; }, diff --git a/src/state/tabNavigation.ts b/src/state/tabNavigation.ts index 45b62c8c..f669110f 100644 --- a/src/state/tabNavigation.ts +++ b/src/state/tabNavigation.ts @@ -6,12 +6,15 @@ import type { ViewType } from "../model/viewTypes"; import { sheetLevelOf } from "../model/layoutModel"; import { getState } from "./appStore"; import type { ViewSnapshotState } from "./viewSnapshots"; -import { getViewStateBridge, getViewTabs, navigateToLevel, setViewTabs, switchViewKind, type TabNav } from "./viewTabs"; +import { getViewStateBridge, getViewTabs, navigateToLevel, setViewTabs, stepFloor, switchViewKind, type TabNav } from "./viewTabs"; +import { getView3dFilter, hideSelection3d, selectionIds3d, setView3dFilter, showSelection3d } from "./view3dFilter"; +import { clearKinds } from "./selection"; -function run(nav: (live: ViewSnapshotState) => TabNav): void { +function run(nav: (live: ViewSnapshotState) => TabNav | null): void { const bridge = getViewStateBridge(); if (!bridge) return; const r = nav(bridge.live()); + if (!r) return; setViewTabs(r.next); if (r.setLevel) { // Gleicher Reiter: nur das Geschoss wechselt, die Art (Grundriss/3D) bleibt. @@ -39,3 +42,26 @@ export function openLayoutTab(layoutId: string): void { const sheet = sheetLevelOf(getState().project, layoutId); if (sheet) openLevel(sheet.id); } + +/** [185] Cmd/Ctrl+5 (−1) bzw. Cmd/Ctrl+6 (+1): im Grundriss-/3D-Reiter ein Geschoss tiefer/höher (Zoom bleibt). */ +export function stepActiveFloor(dir: 1 | -1): void { + run((live) => stepFloor(getViewTabs(), live, getState().project.drawingLevels, dir)); +} + +/** + * [185] Cmd/Ctrl+3 „Auswahl in 3D zeigen": mit Auswahl zeigt der 3D-Reiter nur diese (Titel „3D · Auswahl"), ohne + * Auswahl wieder alles; wechselt in den 3D-Reiter bzw. öffnet ihn, die Kamera passt sich ein. + */ +export function showSelectionIn3d(): void { + setView3dFilter(showSelection3d(getView3dFilter(), selectionIds3d(getState().selection))); + switchViewType("perspektive"); +} + +/** [185] Cmd/Ctrl+4: gewählte Elemente im 3D temporär ausblenden (nicht anwählbar, kein Undo-Schritt); Auswahl leeren. */ +export function hideSelectionIn3d(): void { + const st = getState(); + const ids = selectionIds3d(st.selection); + if (!ids.length) return; + setView3dFilter(hideSelection3d(getView3dFilter(), ids)); + st.setSelection(clearKinds("walls", "ceilings", "openings", "stairs", "solids", "columns", "roofs", "contextObjects", "trees", "drawings", "groups")); +} diff --git a/src/state/testHooks.ts b/src/state/testHooks.ts index 02ba74a4..ffa4fa6a 100644 --- a/src/state/testHooks.ts +++ b/src/state/testHooks.ts @@ -5,7 +5,9 @@ import { core, coreEpoch, coreReady } from "../engine/coreWasm"; import { getState } from "./appStore"; import { storeDocument } from "./historySlice"; -import { computeSection, generatePlan, generateSectionPlan } from "../core"; +import { computeSection, generatePlan, generateSectionPlan, pickGeometry, projectToModel3d } from "../core"; +import { getViewStateBridge } from "./viewTabs"; +import { getView3dFilter, toFilter3d } from "./view3dFilter"; declare global { interface Window { @@ -37,6 +39,10 @@ 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 }>; + /** [185] Darstellungszustand der Plan-Ansicht: aktive Ebene, Bildmitte (Modell-m), Zoom (px/m), Massstab. */ + viewCamera: () => { levelId: string; center: { x: number; y: number } | null; pxPerMeter: number | null; scale: number }; + /** [185] 3D-Element-Filter (Store) und die Wand-ids des 3D-Modells bzw. der Pick-Geometrie mit ihm. */ + view3d: () => { only: string[] | null; hidden: string[]; walls: string[]; pickWalls: string[] }; }; } } @@ -90,6 +96,27 @@ export function installTestHooks(): void { const area = (pts: { x: number; y: number }[]) => Math.abs(pts.reduce((a, p, i) => a + p.x * pts[(i + 1) % pts.length].y - pts[(i + 1) % pts.length].x * p.y, 0)) / 2; return { n: polys.length, area: polys.reduce((a, q) => a + (q.kind === "polygon" ? area(q.pts) : 0), 0) }; }, + viewCamera: () => { + const st = getViewStateBridge()?.live(); + return { + levelId: getState().activeLevelId, + center: st?.cameraCenter ?? null, + pxPerMeter: st?.cameraPxPerMeter ?? null, + scale: getState().scaleDenominator, + }; + }, + view3d: () => { + const f = getView3dFilter(); + const p = getState().project; + const hide = toFilter3d(f, []); + const uniq = (ids: string[]) => [...new Set(ids)].sort(); + return { + only: f.only, + hidden: f.hidden, + walls: uniq(projectToModel3d(p, { hide }).walls.map((w) => w.wallId)), + pickWalls: uniq(pickGeometry(p, 0, hide).walls.map((w) => w.wallId)), + }; + }, selected: () => ({ drawings: [...getState().selection.drawings], groups: [...getState().selection.groups], all: JSON.stringify(getState().selection) }), }; } diff --git a/src/state/useKeyboardShortcuts.ts b/src/state/useKeyboardShortcuts.ts index f12c84a1..f379ad1a 100644 --- a/src/state/useKeyboardShortcuts.ts +++ b/src/state/useKeyboardShortcuts.ts @@ -32,6 +32,7 @@ import { import type { ElementClipboard, ElementSelectionIds, PastedIds } from "../editors/elementClipboard"; import { parseClipboardText, serializeClipboardText } from "../editors/elementClipboardSerialize"; import { matchesShortcut, type ShortcutId, type ShortcutOverrides } from "./keyboardShortcuts"; +import { hideSelectionIn3d, showSelectionIn3d, stepActiveFloor } from "./tabNavigation"; const isEditableTarget = (e: KeyboardEvent): boolean => { const el = e.target as HTMLElement | null; @@ -643,3 +644,31 @@ export function useGroupShortcut( // eslint-disable-next-line react-hooks/exhaustive-deps }, [currentSelection, selectedGroupIds, overrides]); } + +/** + * [185] Navigation wie Archicad: Cmd/Ctrl+5 Geschoss tiefer, Cmd/Ctrl+6 höher (Grundriss- und 3D-Reiter, Zoom + * bleibt), Cmd/Ctrl+3 Auswahl in 3D zeigen (ohne Auswahl: alles), Cmd/Ctrl+4 Auswahl im 3D ausblenden. Unter Tauri + * fängt das native Menü dieselben Kürzel ab (`native/appMenu.ts`). + */ +export function useViewNavigationShortcuts(overrides: ShortcutOverrides): void { + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + // Die (oft fokussierte) Befehlszeile tippt keine Cmd/Ctrl-Ziffern: dort gelten die Kürzel. + if (isEditableTarget(e) && !(e.target as HTMLElement).classList.contains("cmdline-input")) return; + const fn = matchesShortcut(e, "floorDown", overrides) + ? () => stepActiveFloor(-1) + : matchesShortcut(e, "floorUp", overrides) + ? () => stepActiveFloor(1) + : matchesShortcut(e, "showSelection3d", overrides) + ? showSelectionIn3d + : matchesShortcut(e, "hideSelection3d", overrides) + ? hideSelectionIn3d + : null; + if (!fn) return; + e.preventDefault(); + fn(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [overrides]); +} diff --git a/src/state/useNativeMenu.ts b/src/state/useNativeMenu.ts index 60e1a22c..a612be2e 100644 --- a/src/state/useNativeMenu.ts +++ b/src/state/useNativeMenu.ts @@ -17,6 +17,7 @@ import { t } from "../i18n"; import { getState, type RootState } from "./appStore"; import { openMeshFileDialog } from "./meshImportStore"; import { openPointCloudFileDialog } from "./pointCloudStore"; +import { hideSelectionIn3d, showSelectionIn3d, stepActiveFloor } from "./tabNavigation"; import type { useDialogState } from "./useDialogState"; import type { useProjectFileActions } from "./useProjectFileActions"; import type { useTopBarState } from "./useTopBarState"; @@ -156,6 +157,9 @@ export function useNativeMenu(opts: { onViewType: setViewType, onView3d: setView3d, onReferenceLines: setReferenceLines, + onFloorStep: stepActiveFloor, + onShowSelection3d: showSelectionIn3d, + onHideSelection3d: hideSelectionIn3d, onToggleResources: () => toggleResources(), onOpenSettings: () => openSettings(), onOpenPanel: (panelId) => setLayout((l) => revealPanel(l, panelId)), diff --git a/src/state/useSelectionCommands.ts b/src/state/useSelectionCommands.ts index 164441aa..51c1cf25 100644 --- a/src/state/useSelectionCommands.ts +++ b/src/state/useSelectionCommands.ts @@ -30,6 +30,7 @@ import { useSelectAllAndDeleteShortcut, useSplitJoinShortcut, useTransformShortcuts, + useViewNavigationShortcuts, } from "./useKeyboardShortcuts"; import { TRANSFORM_COMMANDS } from "./useToolInput"; import { getState, type RootState } from "./appStore"; @@ -304,6 +305,8 @@ export function useSelectionCommands(opts: { applyGroupSelection, shortcutOverrides, ); + // [185] Cmd/Ctrl+3/4/5/6: Auswahl in 3D zeigen/ausblenden, Geschoss tiefer/höher. + useViewNavigationShortcuts(shortcutOverrides); // Doppelklick auf ein gruppiertes Element → Gruppe betreten (Isolation): // alles ausserhalb wird gedimmt/gesperrt gerendert (s. viewportContent.tsx/ diff --git a/src/state/view3dFilter.test.ts b/src/state/view3dFilter.test.ts new file mode 100644 index 00000000..b7e472f9 --- /dev/null +++ b/src/state/view3dFilter.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from "vitest"; +import { fromIdLists, EMPTY_SELECTION, mergeSelection } from "./selection"; +import { + NO_VIEW3D_FILTER, + getView3dFilter, + hideSelection3d, + isSelectionMode, + resetView3dFilter, + selectionIds3d, + setView3dFilter, + showSelection3d, + toFilter3d, +} from "./view3dFilter"; + +describe("3D-Element-Filter [185]", () => { + it("selectionIds3d: nur Arten, die im 3D vorkommen, ohne Doppel", () => { + const sel = mergeSelection(EMPTY_SELECTION, { + ...fromIdLists({ wallIds: ["w1", "w2"], openingIds: ["o1"] }), + rooms: ["r1"], + sectionLines: ["s1"], + groups: ["g1"], + drawings: ["w1"], + }); + expect(selectionIds3d(sel)).toEqual(["w1", "w2", "o1"]); + }); + + it("Cmd+3 mit Auswahl: nur diese, Ausgeblendetes vergessen, Kamera einpassen; ohne Auswahl: alles", () => { + const hidden = hideSelection3d(NO_VIEW3D_FILTER, ["x"]); + const a = showSelection3d(hidden, ["w1", "w1", "o1"]); + expect(a).toMatchObject({ only: ["w1", "o1"], hidden: [] }); + expect(isSelectionMode(a)).toBe(true); + expect(a.fitSeq).toBe(hidden.fitSeq + 1); + const b = showSelection3d(a, []); + expect(b).toMatchObject({ only: null, hidden: [] }); + expect(isSelectionMode(b)).toBe(false); + expect(b.fitSeq).toBe(a.fitSeq + 1); + }); + + it("Cmd+4: blendet zusätzlich aus, im Auswahl-Modus auch; ohne ids unverändert", () => { + const a = hideSelection3d(NO_VIEW3D_FILTER, ["w1"]); + expect(a).toMatchObject({ only: null, hidden: ["w1"], fitSeq: 0 }); + expect(hideSelection3d(a, ["w1"])).toBe(a); + expect(hideSelection3d(a, [])).toBe(a); + const b = hideSelection3d(showSelection3d(a, ["w2", "w3"]), ["w3"]); + expect(b).toMatchObject({ only: ["w2", "w3"], hidden: ["w3"] }); + }); + + it("toFilter3d: Klassen plus Element-Auswahl für den Kern", () => { + expect(toFilter3d(NO_VIEW3D_FILTER, ["31"])).toEqual({ hide: ["31"], only: null, hideIds: [] }); + expect(toFilter3d(showSelection3d(NO_VIEW3D_FILTER, ["w1"]), [])).toEqual({ hide: [], only: ["w1"], hideIds: [] }); + }); + + it("Store: setzen und beim Projektwechsel zurücksetzen", () => { + setView3dFilter(showSelection3d(NO_VIEW3D_FILTER, ["w1"])); + expect(isSelectionMode(getView3dFilter())).toBe(true); + resetView3dFilter(); + expect(getView3dFilter()).toBe(NO_VIEW3D_FILTER); + }); +}); diff --git a/src/state/view3dFilter.ts b/src/state/view3dFilter.ts new file mode 100644 index 00000000..fcb7b150 --- /dev/null +++ b/src/state/view3dFilter.ts @@ -0,0 +1,85 @@ +// [185] Element-Filter der 3D-Ansicht wie Archicad: „Auswahl in 3D zeigen" (Cmd/Ctrl+3) zeigt nur die gewählten +// Elemente, Cmd/Ctrl+4 blendet die gewählten temporär aus; Cmd/Ctrl+3 ohne Auswahl zeigt wieder alles. +// +// Reiner UI-Zustand (nicht im Projekt, kein Op, kein Undo-Schritt), wirkt zusätzlich zum Klassen-Filter ([180]): +// der Kern blendet die Elemente in Teilen und Pick aus (`model3d::ElementSelection`, Text `{"only", "hideIds"}`). +// Ein neu geladenes Projekt beginnt ohne Filter (`resetView3dFilter`). +// +// Pure Funktionen + ein kleiner externer Store (Muster viewTabs.ts). + +import { useSyncExternalStore } from "react"; +import type { Filter3d } from "../core"; +import type { Selection, SelectionKind } from "./selection"; + +export interface View3dFilter { + /** Nur diese Element-ids zeigen; `null` = alle. */ + only: string[] | null; + /** Temporär ausgeblendete Element-ids. */ + hidden: string[]; + /** Zählt die Anfragen „Kamera auf das Gezeigte einpassen" (der 3D-Viewport passt bei jeder Änderung ein). */ + fitSeq: number; +} + +export const NO_VIEW3D_FILTER: View3dFilter = Object.freeze({ only: null, hidden: [], fitSeq: 0 }) as View3dFilter; + +/** Element-Arten, die im 3D vorkommen (Räume, Schnittlinien, Lage-Darstellung und Gruppen nicht). */ +const KINDS_3D: readonly SelectionKind[] = ["walls", "ceilings", "openings", "stairs", "solids", "columns", "roofs", "contextObjects", "trees", "drawings"]; + +/** Element-ids der Auswahl, die im 3D vorkommen (ohne Doppel, in Wahl-Reihenfolge). */ +export function selectionIds3d(sel: Selection): string[] { + return [...new Set(KINDS_3D.flatMap((k) => sel[k]))]; +} + +/** Ist der Auswahl-Modus („3D · Auswahl") aktiv? */ +export function isSelectionMode(f: View3dFilter): boolean { + return f.only !== null; +} + +/** + * Cmd/Ctrl+3: mit Auswahl nur diese zeigen (ausgeblendete werden vergessen), ohne Auswahl alles zeigen. Beide Male + * passt der 3D-Viewport die Kamera ein. + */ +export function showSelection3d(f: View3dFilter, ids: readonly string[]): View3dFilter { + return ids.length ? { only: [...new Set(ids)], hidden: [], fitSeq: f.fitSeq + 1 } : { only: null, hidden: [], fitSeq: f.fitSeq + 1 }; +} + +/** Cmd/Ctrl+4: die Elemente `ids` zusätzlich ausblenden (Kamera bleibt). Ohne ids unverändert. */ +export function hideSelection3d(f: View3dFilter, ids: readonly string[]): View3dFilter { + if (!ids.length) return f; + const hidden = [...new Set([...f.hidden, ...ids])]; + return hidden.length === f.hidden.length ? f : { ...f, hidden }; +} + +/** Filter für die 3D-Abfragen: Klassen-Codes `hide` plus Element-Auswahl (Kern `ClassFilter::from_text`). */ +export function toFilter3d(f: View3dFilter, hide: readonly string[]): Filter3d { + return { hide, only: f.only, hideIds: f.hidden }; +} + +// ── Store ─────────────────────────────────────────────────────────────────── + +let current: View3dFilter = NO_VIEW3D_FILTER; +const listeners = new Set<() => void>(); + +export function getView3dFilter(): View3dFilter { + return current; +} + +export function setView3dFilter(next: View3dFilter): void { + if (next === current) return; + current = next; + for (const l of listeners) l(); +} + +/** Neues/geöffnetes Projekt: keine Element-Auswahl im 3D. */ +export function resetView3dFilter(): void { + setView3dFilter(NO_VIEW3D_FILTER); +} + +function subscribe(l: () => void): () => void { + listeners.add(l); + return () => listeners.delete(l); +} + +export function useView3dFilter(): View3dFilter { + return useSyncExternalStore(subscribe, getView3dFilter, getView3dFilter); +} diff --git a/src/state/viewTabs.test.ts b/src/state/viewTabs.test.ts index 31ecd72b..8a02589e 100644 --- a/src/state/viewTabs.test.ts +++ b/src/state/viewTabs.test.ts @@ -14,6 +14,9 @@ import { navigateToLevel, switchViewKind, tabKindOf, + adjacentFloorId, + planFitKey, + stepFloor, isPlanKindActive, openTab, restoreViewTabs, @@ -299,3 +302,40 @@ describe("Reiter-Arten und Navigation [182]", () => { expect(n.apply).toMatchObject({ viewType: "grundriss", activeLevelId: "eg" }); }); }); + +describe("Geschoss-Navigation wie Archicad [185]", () => { + // Liste absichtlich nicht nach Höhe sortiert: UG unten, DG oben. + const levels = [ + { id: "eg", kind: "floor" as const, baseElevation: 0 }, + { id: "sec", kind: "section" as const }, + { id: "dg", kind: "floor" as const, baseElevation: 6 }, + { id: "og", kind: "floor" as const, baseElevation: 3 }, + { id: "ug", kind: "floor" as const, baseElevation: -3 }, + ]; + const live = (activeLevelId: string, viewType: "grundriss" | "perspektive" = "grundriss"): ViewSnapshotState => + ({ ...st(activeLevelId), viewType, cameraCenter: { x: 1, y: 2 }, cameraPxPerMeter: 40 }) as ViewSnapshotState; + + it("adjacentFloorId: nach Höhe, am Rand null, Nicht-Geschoss null", () => { + expect(adjacentFloorId(levels, "eg", 1)).toBe("og"); + expect(adjacentFloorId(levels, "og", 1)).toBe("dg"); + expect(adjacentFloorId(levels, "dg", 1)).toBeNull(); + expect(adjacentFloorId(levels, "eg", -1)).toBe("ug"); + expect(adjacentFloorId(levels, "ug", -1)).toBeNull(); + expect(adjacentFloorId(levels, "sec", 1)).toBeNull(); + }); + + it("stepFloor: Grundriss und 3D bleiben im Reiter, Schnitt tut nichts", () => { + const s = initialTabs(); + expect(stepFloor(s, live("eg"), levels, 1)).toEqual({ next: s, apply: null, setLevel: "og" }); + expect(stepFloor(s, live("eg", "perspektive"), levels, -1)).toEqual({ next: s, apply: null, setLevel: "ug" }); + expect(stepFloor(s, live("dg"), levels, 1)).toBeNull(); + expect(stepFloor(s, live("sec"), levels, 1)).toBeNull(); + }); + + it("planFitKey: Geschosse teilen den Schlüssel (Zoom bleibt), andere Ebenen und neues Projekt passen ein", () => { + expect(planFitKey(levels[0], 1)).toBe(planFitKey(levels[3], 1)); + expect(planFitKey(levels[0], 1)).not.toBe(planFitKey(levels[0], 2)); + expect(planFitKey(levels[1], 1)).not.toBe(planFitKey(levels[0], 1)); + expect(planFitKey({ id: "x", kind: "drawing" }, 1)).not.toBe(planFitKey({ id: "y", kind: "drawing" }, 1)); + }); +}); diff --git a/src/state/viewTabs.ts b/src/state/viewTabs.ts index cdaaac9e..0fa5ecc8 100644 --- a/src/state/viewTabs.ts +++ b/src/state/viewTabs.ts @@ -223,6 +223,52 @@ export function switchViewKind( return openNew(stored, noCamera({ ...live, viewType: want, activeLevelId: levelId })); } +/** + * [185] Nächstes Geschoss über (`dir` = +1, Cmd/Ctrl+6) bzw. unter (−1, Cmd/Ctrl+5) dem aktiven, nach Höhe + * (`baseElevation`, gleich hoch: Reihenfolge der Liste). `null` am obersten/untersten Geschoss oder wenn die aktive + * Ebene kein Geschoss ist. + */ +export function adjacentFloorId( + levels: readonly Pick[], + activeId: string, + dir: 1 | -1, +): string | null { + const floors = levels + .map((l, i) => ({ l, i })) + .filter(({ l }) => l.kind === "floor") + .sort((a, b) => (a.l.baseElevation ?? 0) - (b.l.baseElevation ?? 0) || a.i - b.i) + .map(({ l }) => l.id); + const at = floors.indexOf(activeId); + if (at < 0) return null; + return floors[at + dir] ?? null; +} + +/** + * [185] Cmd/Ctrl+5 (`dir` −1) bzw. Cmd/Ctrl+6 (+1): im Grundriss- oder 3D-Reiter ein Geschoss tiefer/höher, im + * selben Reiter (Art, Zoom und Ausschnitt bleiben). Sonst (Schnitt, Ansicht, Zeichnung; oberstes/unterstes + * Geschoss) `null`. + */ +export function stepFloor( + s: ViewTabsState, + live: ViewSnapshotState, + levels: readonly Pick[], + dir: 1 | -1, +): TabNav | null { + const kind = tabKindOf(live, levels); + if (kind !== "plan" && kind !== "3d") return null; + const id = adjacentFloorId(levels, live.activeLevelId, dir); + return id ? navigateToLevel(s, live, levels, id) : null; +} + +/** + * [185] Schlüssel, bei dessen Wechsel die Plan-Ansicht neu einpasst. Geschosse teilen sich einen: der Wechsel in ein + * anderes Geschoss im selben Reiter behält Zoom und Ausschnitt exakt (wie Archicad); Schnitt, Ansicht, Zeichnung und + * ein neu geladenes Projekt (`epoch`) passen ein. + */ +export function planFitKey(level: Pick, epoch: number): string { + return `${level.kind === "floor" ? "floors" : `level:${level.id}`}#${epoch}`; +} + /** Verbindet den aktiven Reiter mit einem Ausschnitt (Klick im Panel / Speichern). */ export function linkActiveTab(s: ViewTabsState, snapshotId: string): ViewTabsState { return { diff --git a/src/ui/SettingsDialog.tsx b/src/ui/SettingsDialog.tsx index 6f77e1ba..0a11f981 100644 --- a/src/ui/SettingsDialog.tsx +++ b/src/ui/SettingsDialog.tsx @@ -581,6 +581,7 @@ const CATEGORY_ORDER: ShortcutCategory[] = [ "transform", "group", "tools", + "navigation", ]; /** diff --git a/src/viewport/Wasm3DViewport.tsx b/src/viewport/Wasm3DViewport.tsx index 3e44151b..69657e6f 100644 --- a/src/viewport/Wasm3DViewport.tsx +++ b/src/viewport/Wasm3DViewport.tsx @@ -46,6 +46,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { Project, Wall, Drawing2D, Ceiling, Roof, Vec2 } from "../model/types"; import { roofBaseElevation, roofGeometry, verticalExtents } from "../core"; import { projectToModel3d, pickGeometry, draftWorldLines, explodeFloorOffsets, hiddenClassCodes } from "../core"; +import type { Hide3d } from "../core"; +import { toFilter3d, useView3dFilter } from "../state/view3dFilter"; import type { DetailLevel, RenderMode, View3d } from "../model/viewTypes"; import type { ToolDraft } from "../tools/types"; import { hudSegments, type HudFieldsState } from "../tools/hudFormat"; @@ -309,7 +311,7 @@ function computeGripsAt( * müssen auf dieselbe Distanz/dasselbe Ziel kommen, damit der Orbit-Zustand * (hier) nahtlos an die exakte Praeset-Kamera (dort) anschliesst. */ -function fitTargetDist(project: Project, hide?: readonly string[]): { +function fitTargetDist(project: Project, hide?: Hide3d): { target: [number, number, number]; dist: number; } { @@ -601,7 +603,14 @@ export function Wasm3DViewport({ explodeRef.current = explode; // [180] Ausgeblendete Klassen: Inhalt statt Identität als Abhängigkeit (der Aufrufer baut die Liste je Render). const hiddenKey = (hiddenCodes ?? []).join("\u0001"); - const hide = useMemo(() => (hiddenKey ? hiddenKey.split("\u0001") : []), [hiddenKey]); + // [185] Element-Auswahl („Auswahl in 3D zeigen", temporär ausgeblendet) kommt dazu; ohne sie bleibt `hide` die + // Code-Liste (gleicher Text an den Kern wie bisher). + const elementFilter = useView3dFilter(); + const { only: onlyIds, hidden: hiddenIds, fitSeq } = elementFilter; + const hide = useMemo(() => { + const codes = hiddenKey ? hiddenKey.split("\u0001") : []; + return onlyIds || hiddenIds.length ? toFilter3d({ only: onlyIds, hidden: hiddenIds, fitSeq: 0 }, codes) : codes; + }, [hiddenKey, onlyIds, hiddenIds]); const hideRef = useRef(hide); hideRef.current = hide; // Versatz je Geschoss ([65]) für Griffe und gezogene Höhen (Modell bleibt unversetzt). @@ -712,6 +721,15 @@ export function Wasm3DViewport({ applyPreset(); }, [ready, applyPreset]); + // [185] „Auswahl in 3D zeigen" / alles zeigen: Kamera auf das Gezeigte einpassen (das Modell ist im Effekt oben + // schon mit dem neuen Filter eingespielt). + const fitSeqRef = useRef(fitSeq); + useEffect(() => { + if (!ready || fitSeqRef.current === fitSeq) return; + fitSeqRef.current = fitSeq; + fitCameraRef.current(); + }, [ready, fitSeq]); + // Kamera-Brücke ([BCF]): Lesen/Setzen der Orbit-Kamera, Schnappschuss und Schnitt von aussen // (`cameraBridge.ts`). Der Orbit-Zustand ist die Wahrheit; nach einem Preset ist er aus der // Rust-Preset-Kamera geseedet (s. `applyPreset`). diff --git a/src/viewport/useWasm3dRenderer.ts b/src/viewport/useWasm3dRenderer.ts index 58d5a187..0898181c 100644 --- a/src/viewport/useWasm3dRenderer.ts +++ b/src/viewport/useWasm3dRenderer.ts @@ -19,7 +19,8 @@ import { useCallback, useEffect, useRef, useState } from "react"; import type { ContextImage, Project } from "../model/types"; -import { emitDrawingLineVerts, emitSurfacePatternLines, hiddenClassCodes, projectToModel3d, projectToModel3dParts, siteEnvelope3d } from "../core"; +import { emitDrawingLineVerts, emitSurfacePatternLines, filter3d, hiddenClassCodes, projectToModel3d, projectToModel3dParts, siteEnvelope3d } from "../core"; +import type { Hide3d } from "../core"; import { Model3dPartsSync } from "./model3dPartsSync"; import type { DetailLevel } from "../model/viewTypes"; import { loadEngine3d } from "../engine/engine3d"; @@ -199,7 +200,7 @@ const partsSyncs = new WeakMap(); * und werden in render3d neu vernetzt und hochgeladen), sonst bzw. bei älteren WASM-Builds und nach * einem Fehler das ganze Modell über `set_model`. */ -function syncModel3d(r: WebModelRendererLike, project: Project, detail: DetailLevel | undefined, explode: number, hide?: readonly string[]): void { +function syncModel3d(r: WebModelRendererLike, project: Project, detail: DetailLevel | undefined, explode: number, hide?: Hide3d): void { let sync = partsSyncs.get(r); if (!sync) partsSyncs.set(r, (sync = new Model3dPartsSync())); try { @@ -270,8 +271,9 @@ export function useWasm3dRenderer( /** Modell bei Projektänderung neu setzen (re-extrudiert in Rust). `detail` * steuert den Öffnungs-Detailgrad (grob/mittel/fein) im 3D wie im Grundriss. `hide`: Klassen, die der - * Darstellungsmodus nicht zeichnet ([180]; die im Ebenen-Baum ausgeschalteten blendet der Kern selbst aus). */ - const updateModel = useCallback((project: Project, detail?: DetailLevel, explode = 0, hide?: readonly string[]) => { + * Darstellungsmodus nicht zeichnet ([180]; die im Ebenen-Baum ausgeschalteten blendet der Kern selbst aus), + * dazu die Element-Auswahl ([185], {@link Hide3d}). */ + const updateModel = useCallback((project: Project, detail?: DetailLevel, explode = 0, hide?: Hide3d) => { const r = rendererRef.current; if (!r || !project) return; syncModel3d(r, project, detail, explode, hide); @@ -290,7 +292,9 @@ export function useWasm3dRenderer( if (typeof r.set_ghost === "function") { try { // Zulässige Hülle (Baurecht) liegt wie im Grundriss auf `01 Vermessung` ([180]). - r.set_ghost(hiddenClassCodes(project, hide).has("01") ? new Float32Array(0) : siteEnvelope3d(project)); + // [185] „Auswahl in 3D zeigen": nur die gewählten Elemente, keine Hülle. + const off = hiddenClassCodes(project, hide).has("01") || !!filter3d(hide).only; + r.set_ghost(off ? new Float32Array(0) : siteEnvelope3d(project)); } catch (e) { console.warn("render3d set_ghost fehlgeschlagen:", e); } diff --git a/src/views/plan/PlanView.tsx b/src/views/plan/PlanView.tsx index 891b361e..e3fafabf 100644 --- a/src/views/plan/PlanView.tsx +++ b/src/views/plan/PlanView.tsx @@ -95,6 +95,7 @@ export const PlanView = forwardRef( { plan: planRaw, resetKey, + fitKey, onCursor, onScale, onSelect, @@ -180,10 +181,12 @@ export const PlanView = forwardRef( // zurücksetzen — NICHT bei jeder Bounds-Änderung durch Editieren (sonst // „wandert" die Ansicht beim Verschieben/Löschen mit). `defaultView` ist beim // resetKey-Wechsel bereits frisch (neues Geschoss), daher direkt anwendbar. + // [185] Geschosswechsel: gleicher `fitKey`, der Ausschnitt bleibt exakt stehen (wie Archicad). + const viewKey = fitKey ?? resetKey; useEffect(() => { setView(defaultView); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [resetKey]); + }, [viewKey]); // [165] Renderer-Anbindung: Pick-Index, Engine-Wahl (nativ/WASM/SVG), Plan-Aufbereitung, Culling, Papier-Massstab, GL-Effekte. const { getPick, @@ -226,7 +229,7 @@ export const PlanView = forwardRef( view, hairline, onScale, - resetKey, + resetKey: viewKey, // Papier-Massstab folgt dem Einpassen }); // [165] Steuerhandle, Zieh-Zustände, Koordinaten-Umrechnung und Griff-Treffer. const { diff --git a/src/views/plan/planView/types.ts b/src/views/plan/planView/types.ts index 086690b6..e6579a4e 100644 --- a/src/views/plan/planView/types.ts +++ b/src/views/plan/planView/types.ts @@ -222,6 +222,11 @@ export interface PlanViewProps { * Einpassen stehen (kein Auto-Reset). */ resetKey?: string; + /** + * [185] Schlüssel nur für das Einpassen (fehlt: `resetKey`). Geschosse teilen sich einen (`planFitKey`): der + * Geschosswechsel behält Zoom und Ausschnitt exakt, Pick-Zyklus u. ä. folgen weiter `resetKey`. + */ + fitKey?: string; /** * Meldet die Cursor-Position in Modell-Koordinaten (Meter) nach oben, bzw. * `null`, wenn der Zeiger die Fläche verlässt. Optional — ohne Callback diff --git a/src/views/plan/planView/usePlanCoords.ts b/src/views/plan/planView/usePlanCoords.ts index 716d01dd..61d133c0 100644 --- a/src/views/plan/planView/usePlanCoords.ts +++ b/src/views/plan/planView/usePlanCoords.ts @@ -100,7 +100,9 @@ export function usePlanCoords(inp: UsePlanCoordsArgs) { // nächste Massstab gewählt wird); Rad-Zoom lässt ihn unberührt. if (n > 0) setPaperScale(n); }, - pxPerMeter: () => currentPxPerMeter(), + // [185] Aus der frischen viewBox (Ref): `currentPxPerMeter` sähe im stabilen Handle die erste viewBox + // (Reiter/Ausschnitte merkten sonst den Start-Zoom statt des aktuellen). + pxPerMeter: () => (meetScale(viewRef.current, canvasRef.current ?? svgRef.current) ?? 1) * PX_PER_M, viewCenterModel: () => { // Mitte der frischen viewBox (aus Ref) → Modell (inverse toScreen). const v = viewRef.current; diff --git a/src/views/viewportContent.tsx b/src/views/viewportContent.tsx index 07dfe77f..81b89319 100644 --- a/src/views/viewportContent.tsx +++ b/src/views/viewportContent.tsx @@ -42,6 +42,7 @@ import { clashHighlightLines } from "../analysis/clash"; import { useClashSession } from "../panels/clashSession"; import { applyGroupDimmingToPlan } from "../state/groupActions"; import { useStore } from "../state/appStore"; +import { planFitKey } from "../state/viewTabs"; import { PlanView } from "./plan/PlanView"; import type { GripHandlers, @@ -872,6 +873,7 @@ function LevelPlanView({ describePick={describePick} onPickHint={setPickHint} resetKey={`${level.id}#${projectEpoch}`} + fitKey={planFitKey(level, projectEpoch)} onCursor={onCursor} onScale={onScale} selection={selection}