diff --git a/TODO.md b/TODO.md index 3dd43a7b..007a56e7 100644 --- a/TODO.md +++ b/TODO.md @@ -2594,6 +2594,38 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). „robust"/„Lösung"/„nicht nur" (Textprüfung des Pakets gilt bisher nur für die Startseite). Bilder der Fenster- und Türliste: das SVG von `schedule --openings --format svg` überlappt Spalten (Textbreiten), darum zeigt die Startseite dort einen Grundriss-Ausschnitt. Englisch: `[languages.en]`, `content.en/`. Mac-Screenshots (Metal, echtes 3D). · M +- ◐ **[137] Alles Sichtbare anwählbar.** (5.11., Mac-Befund am Musterhaus komplex: „Schatten und gewachsenes Terrain lassen sich + nicht anwählen und bearbeiten") **Bestand** (Klick im Plan / im 3D, Objekt-Info, Bearbeiten; vorher → jetzt): + | Element | Grundriss | Schnitt/Ansicht | 3D | Objekt-Info / Bearbeiten | + |---|---|---|---|---| + | Wand, Öffnung, Decke, Dach, Treppe | ✓ (in Situation/mit sichtbarem Gelände: Wand/Decke vom Gelände-Rahmen verdeckt ✗ → ✓) | ✓ (Ansicht: Wand unter Schlagschatten ✗ → ✓) | ✓ | ✓ Felder, Griffe | + | Raum | ✓ | – | – (nicht dargestellt) | ✓ | + | Stütze | ✓ | ✓ | ✗ → ✓ | ✓ | + | Freie Körper (Loft, Rotation, Abzug) | ✓ (Umriss) | ✓ | ✗ (truck-Netze in TS, offen) | ✓ | + | 2D: Bemassung, Koten, Text, Hinweis, Wolke, Nordpfeil-Block, Detail, Kataster, Strasse, Bäume | ✓ (Linien; leere Kreise/Konturen am Rand, leere Konturfläche unter Gelände meint das Gelände) | ✓ eigene | Linien-Spur | ✓ | + | Achsraster | ✓ | ✗ (Projektion ohne Id, offen) | Spur (`show3d`) | ✓ | + | Gelände (TerrainMesh) | Rahmen-Band, Objekt-Info nur LV95 → ✓ mit Optionen | ✗ → ✓ (Erdreich-Band, Geländefläche) | ✓ | ✗ → ✓ Sichtbar (Kategorie), Glättung, Äquidistanz, Zähllinie, Erdreich-Band | + | Höhenlinien-Satz (contourSet) | ✗ → ✓ (Rahmen unter dem Gelände, Cmd/Strg+Klick-Liste) | – | – | Typ, LV95 | + | Baugrube, Böschungen, Rühlwand (excavation) | ✗ (Band nur Sohle, unter dem Gelände-Rahmen) → ✓ Wirkbereich zuoberst | über Gelände | ✗ → ✓ (Dreiecke im Wirkbereich) | Typ ohne Übersetzung → ✓ alle Felder, Mengen; Griffe (bestehend) | + | Schatten (Sonnenstudie) | ✗ → ✓ Pseudo-Auswahl `site` | – | – (kein Schatten im 3D, [64]) | ✓ Sonnenstand: Schalter, Datum, Uhrzeit (Undo) | + | Baurecht: Parzelle, zulässige Fläche, Baulinie | ✗ → ✓ (unsichtbare Bänder ±1.5 mm) | – | – | ✓ Baurecht-Einstellungen; Verstösse (rot) bleiben Anzeige, Klick geht hindurch | + | Schnitt-/Ansichtsmarker | ✓ | – | – | ✓ | + **Umsetzung:** Kern `plan/context.rs` (Pick-Bänder: Baugrube = konvexe Hülle aus Sohle und Böschungsoberkante + `excavation::affected_hull`, zuletzt gezeichnet; Höhenlinien-Rahmen), `plan/extras.rs` (Schattenflächen mit Pick-Id + `@sunStudy`, Baurechts-Bänder `@siteRules` — im Feld `contextObjectId`, `@` = keine Element-Id), `plan/section.rs`/ + `elevation.rs` (Erdreich-Band bzw. Geländefläche mit Gelände-Id), `model3d::pick_geometry` (Baugruben-Dreiecke über + `excavation::owner_at`, Stützen `columns`). `TerrainMesh.smooth`/`sourceId` (Rust-Modell, Befehl `terrain` setzt sie); + `siteSlice.regenerateTerrain` erzeugt das Netz mit anderer Glättung neu (gleiche Id, ein Undo-Schritt). TS: Auswahl-Art + `site` (`"sunStudy"`/`"siteRules"`), Objekt-Info zeigt `SunStudySection`/`SiteRulesSection` bzw. `ContextObjectProps` + (gemeinsam mit dem Panel „Gelände & Kontext"); `PlanView.hitTest` überspringt Flächen ohne Bauteil-Id und unsichtbare + Pick-Bänder (vorher verdeckten Gelände-Rahmen, Schlagschatten der Ansicht und Verstoss-Flächen die Bauteile). + Tests: Rust (Pick-Bänder Gelände/Baugrube/Höhenlinien, Schatten/Baurecht, 3D Baugrube und Stützen, Schnitt/Ansicht), + vitest `siteSelection.test.ts` (Plan-Pick im Musterhaus komplex, Objekt-Info Baugrube, Neu-Glätten mit Undo), e2e + `siteSelect.spec.ts` (Gelände in der Situation wählen, Glättung ändern, Undo; Schatten im EG wählen, Uhrzeit ändern, + Undo); Goldens EG (unsichtbare Bänder). Geprüft im Linux-Container (Chromium), 3D-Pick nur als Unit-Test (headless kein + WebGPU), nicht in der Tauri-App. Offen: freie Körper im 3D-Pick; Achsraster in Schnitt/Ansicht; „Gelände sichtbar" + schaltet die ganze Kategorie; Glättung nur mit Höhenlinien-Satz (swissALTI3D-Netze nicht); in der dichten Situation + 1:500 gehen 2D-Elemente (Bemassung) vor — Schatten/Gelände dort per Cmd/Strg+Klick-Liste. · M ## Priorität 4 — später diff --git a/e2e/siteSelect.spec.ts b/e2e/siteSelect.spec.ts new file mode 100644 index 00000000..05d7cd36 --- /dev/null +++ b/e2e/siteSelect.spec.ts @@ -0,0 +1,68 @@ +// [137] Alles Sichtbare anwählbar (Mac-Befund: „Schatten und gewachsenes Terrain lassen sich nicht anwählen +// und bearbeiten"): im Musterhaus komplex das Gelände (Situation 1:500) und einen Schatten (EG 1:100) per +// Klick in den Plan wählen; die Objekt-Info zeigt ihre Einstellungen, je eine wird geändert und rückgängig +// gemacht. Gepickt wird im Kern auf dem Plan-Puffer (headless ok); Bildschirm-Punkte aus der viewBox- +// Abbildung des SVG-Overlays wie in `kataster.spec.ts`. +import type { Page } from "@playwright/test"; +import { blurFocus, discardIfAsked, expect, fileMenu, openTab, showSnapshot, startNewProject, test } from "./app"; + +async function clickModel(page: Page, x: number, y: number): Promise { + const p = await page.locator("svg.plan-svg").first().evaluate( + (el, [x, y]) => { + const [vx, vy, vw, vh] = el.getAttribute("viewBox")!.split(/\s+/).map(Number); + const ox = Number(el.getAttribute("data-origin-x") ?? 0); + const oy = Number(el.getAttribute("data-origin-y") ?? 0); + const r = el.getBoundingClientRect(); + const s = Math.min(r.width / vw, r.height / vh); + return { x: r.left + (r.width - vw * s) / 2 + (x * 90 - ox - vx) * s, y: r.top + (r.height - vh * s) / 2 + (-y * 90 - oy - vy) * s }; + }, + [x, y], + ); + await page.mouse.click(p.x, p.y); +} + +const objInfo = (page: Page) => page.locator(".objinfo-panel").first(); + +test("Musterhaus komplex: Gelände und Schatten anwählen und bearbeiten (mit Undo)", async ({ page }) => { + test.setTimeout(120_000); + await startNewProject(page); + await fileMenu(page, /Musterhaus \(komplex\)/); + await discardIfAsked(page); + await expect(page.locator(".project-name")).toHaveText("Musterhaus komplex", { timeout: 30_000 }); + await openTab(page, "Objekt-Info"); + + // Gelände: Situation 1:500, Klick in den Garten (Südwest, innerhalb der Parzelle, weg von Linien). + await showSnapshot(page, "Situation 1:500"); + await expect(page.locator("svg.plan-svg").first()).toBeVisible({ timeout: 30_000 }); + const smooth = objInfo(page).getByTestId("terrain-smooth"); + await expect(async () => { + await page.keyboard.press("Escape"); + await clickModel(page, -12, -10); + await expect(smooth).toBeVisible({ timeout: 1000 }); + }).toPass({ timeout: 30_000 }); + await expect(objInfo(page)).toContainText("Gelände"); + await expect(objInfo(page).getByTestId("terrain-visible")).toBeChecked(); + await expect(smooth).toHaveValue("2"); + await smooth.selectOption("0"); + await expect(smooth).toHaveValue("0"); + await blurFocus(page); + await page.keyboard.press("ControlOrMeta+z"); + await expect(smooth).toHaveValue("2"); + + // Schatten: EG 1:100, Klick nördlich des Eingangs (Schlagschatten am 21. Juni, 10 Uhr). + await showSnapshot(page, "EG 1:100"); + await openTab(page, "Objekt-Info"); + const time = objInfo(page).locator(".sun-time"); + await expect(async () => { + await page.keyboard.press("Escape"); + await clickModel(page, 0, 15); + await expect(time).toBeVisible({ timeout: 1000 }); + }).toPass({ timeout: 30_000 }); + await expect(objInfo(page)).toContainText("Schatten (Sonnenstand)"); + await expect(time).toHaveText("10:00"); + await objInfo(page).getByRole("slider", { name: "Uhrzeit" }).fill("840"); + await expect(time).toHaveText("14:00"); + await blurFocus(page); + await page.keyboard.press("ControlOrMeta+z"); + await expect(time).toHaveText("10:00"); +}); diff --git a/src-tauri/core/src/cmd_solid.rs b/src-tauri/core/src/cmd_solid.rs index cfb044ea..7f9d96ce 100644 --- a/src-tauri/core/src/cmd_solid.rs +++ b/src-tauri/core/src/cmd_solid.rs @@ -485,6 +485,7 @@ pub fn terrain_from_contours_with(contours: &[Value], id: &str, o: crate::terrai ("positions", Value::Array(pos.into_iter().map(js_num).collect())), ("indices", Value::Array(idx.into_iter().map(Value::from).collect())), ("contourInterval", js_num(iv)), + ("smooth", Value::from(o.smooth)), ]) } @@ -520,10 +521,14 @@ fn terrain_ops(root: &Map, ids: &mut IdGen) -> Vec { let Some(set) = arr(root.get("context")).iter().find(|o| field(o, "type").and_then(Value::as_str) == Some("contourSet")) else { return Vec::new(); }; - let t = terrain_from_contours(arr(field(set, "contours")), &ids.next("terrain")); + let mut t = terrain_from_contours(arr(field(set, "contours")), &ids.next("terrain")); if arr(field(&t, "indices")).is_empty() { return Vec::new(); } + // [137] Quelle merken: die Objekt-Info glättet das Gelände aus diesen Höhenlinien neu. + if let (Some(m), Some(src)) = (t.as_object_mut(), field(set, "id").cloned()) { + m.insert("sourceId".into(), src); + } add_op("context", vec![t]) } diff --git a/src-tauri/core/src/excavation.rs b/src-tauri/core/src/excavation.rs index 586430fb..8f52327a 100644 --- a/src-tauri/core/src/excavation.rs +++ b/src-tauri/core/src/excavation.rs @@ -729,6 +729,54 @@ pub fn terrain_before(st: &SiteTerrain, id: &str) -> Option { Some(cur) } +// ── Auswahl ([137]) ────────────────────────────────────────────────────────── + +/// [137] Baugrube, die das Gelände am Punkt (x, y) ändert (Sohle oder Böschung/Schüttung), sonst `None`. +/// `idx` = Index des gewachsenen Netzes (`st.orig`); die Baugruben wirken der Reihe nach wie im Netz. +pub fn owner_at<'a>(st: &'a SiteTerrain, idx: &TinIndex, x: f64, y: f64) -> Option<&'a str> { + let p = [x, y]; + let mut z = idx.z_at(x, y); + for (id, spec, _) in &st.items { + if point_in_ring(p, &spec.ring) { + return Some(id); + } + if let Some(t) = z { + let n = spec.apply(t, p); + if (n - t).abs() > 0.005 { + return Some(id); + } + z = Some(n); + } + } + None +} + +/// [137] Wirkbereich einer Baugrube im Grundriss (Pick-Fläche): konvexe Hülle aus Sohle und +/// Böschungsoberkante, gegen den Uhrzeigersinn. Leer, wenn sie kein Gelände trifft. +pub fn affected_hull(st: &SiteTerrain, id: &str) -> Vec { + let Some((_, spec, daylight)) = st.items.iter().find(|(i, ..)| i == id) else { return Vec::new() }; + let mut pts: Vec = spec.ring.iter().chain(daylight.iter().flatten()).copied().filter(|q| q[0].is_finite() && q[1].is_finite()).collect(); + pts.sort_by(|a, b| a[0].total_cmp(&b[0]).then(a[1].total_cmp(&b[1]))); + pts.dedup(); + if pts.len() < 3 { + return pts; + } + let cross = |o: P2, a: P2, b: P2| (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]); + let mut hull: Vec = Vec::with_capacity(pts.len() + 1); + for pass in 0..2 { + let start = hull.len(); + let it: Box> = if pass == 0 { Box::new(pts.iter()) } else { Box::new(pts.iter().rev()) }; + for &q in it { + while hull.len() >= start + 2 && cross(hull[hull.len() - 2], hull[hull.len() - 1], q) <= 0.0 { + hull.pop(); + } + hull.push(q); + } + hull.pop(); + } + hull +} + #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/core/src/explode3d.rs b/src-tauri/core/src/explode3d.rs index 190377d6..7c636206 100644 --- a/src-tauri/core/src/explode3d.rs +++ b/src-tauri/core/src/explode3d.rs @@ -207,6 +207,12 @@ pub fn pick_geometry(p: &Project, gap: f64) -> Result { v[1] += dz; } } + for c in &mut g.columns { + let dz = ex.of(&c.column_id); + for v in c.tris.iter_mut().flatten() { + v[1] += dz; + } + } Ok(g) } diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs index 2ed32e27..a78b756f 100644 --- a/src-tauri/core/src/model/generated.rs +++ b/src-tauri/core/src/model/generated.rs @@ -5197,6 +5197,15 @@ pub struct TerrainMesh { #[serde(rename = "earthDepth", default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub earth_depth: Option, + /// [137] Glättungsstufe, mit der das Netz aus Höhenlinien erzeugt wurde (0 = roh, 1–4 Kantenteilungen). + /// Fehlt bei importierten Netzen (swissALTI3D) — dann gibt es nichts neu zu glätten. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub smooth: Option, + /// [137] Quelle: Id des Höhenlinien-Satzes (`contourSet`), aus dem das Netz erzeugt wurde. + #[serde(rename = "sourceId", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub source_id: Option, #[serde(flatten)] #[ts(skip)] pub extra: Extra, diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index cf319a0e..d1e99c43 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -2331,6 +2331,14 @@ pub struct PickContextMesh { pub context_object_id: String, } +/// [137] Stütze für den 3D-Pick: Welt-Dreiecke ihres Prismas. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PickColumn { + pub tris: Vec, + pub column_id: String, +} + #[derive(Debug, Serialize)] pub struct PickGeometry { pub walls: Vec, @@ -2340,6 +2348,8 @@ pub struct PickGeometry { pub roofs: Vec, #[serde(rename = "contextMeshes")] pub context_meshes: Vec, + /// [137] Stützen (vorher im 3D nicht anwählbar). + pub columns: Vec, pub drawings: Vec, } @@ -2425,17 +2435,49 @@ pub fn pick_geometry(p: &Project) -> Result { let (pos, idx) = (&*pos, &*idx); let vcount = pos.len() / 3; let at = |i: usize| -> V3 { [pos[i * 3], pos[i * 3 + 2], -pos[i * 3 + 1]] }; + // [137] Dreiecke im Wirkbereich einer Baugrube (Sohle, Böschungen) wählen die Baugrube. + let site = match obj { + ContextObject::TerrainMesh(m) => Some(crate::excavation::site_terrain(p, m)), + _ => None, + }; + let site = site.filter(|st| !st.items.is_empty()); + let orig_idx = site.as_ref().map(|st| crate::terrain::TinIndex::new(&st.orig)); + let boxes: Vec<[f64; 4]> = site.as_ref().map_or_else(Vec::new, |st| { + st.items + .iter() + .map(|(eid, ..)| crate::excavation::affected_hull(st, eid).iter().fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |b, q| [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[0]), b[3].max(q[1])])) + .collect() + }); let mut tris: Vec = Vec::new(); + let mut owned: Vec<(String, Vec)> = Vec::new(); for t in idx.chunks_exact(3) { let ok = |v: f64| v >= 0.0 && v.fract() == 0.0 && (v as usize) < vcount; if !(ok(t[0]) && ok(t[1]) && ok(t[2])) { continue; } - tris.push([at(t[0] as usize), at(t[1] as usize), at(t[2] as usize)]); + let tri = [at(t[0] as usize), at(t[1] as usize), at(t[2] as usize)]; + let owner = match (&site, &orig_idx) { + (Some(st), Some(oi)) => { + let (cx, cy) = ((tri[0][0] + tri[1][0] + tri[2][0]) / 3.0, -(tri[0][2] + tri[1][2] + tri[2][2]) / 3.0); + let near = boxes.iter().any(|b| cx >= b[0] - 0.01 && cx <= b[2] + 0.01 && cy >= b[1] - 0.01 && cy <= b[3] + 0.01); + if near { crate::excavation::owner_at(st, oi, cx, cy) } else { None } + } + _ => None, + }; + match owner { + Some(eid) => match owned.iter_mut().find(|(i, _)| i == eid) { + Some((_, l)) => l.push(tri), + None => owned.push((eid.to_string(), vec![tri])), + }, + None => tris.push(tri), + } } if !tris.is_empty() { context_meshes.push(PickContextMesh { tris, context_object_id: id.clone() }); } + for (eid, tris) in owned { + context_meshes.push(PickContextMesh { tris, context_object_id: eid }); + } } Ok(PickGeometry { walls: emit_walls(p, true)?, @@ -2444,10 +2486,33 @@ pub fn pick_geometry(p: &Project) -> Result { stairs, roofs, context_meshes, + columns: pick_columns(p), drawings: pick_drawing_segs(p, &HashMap::new()), }) } +/// [137] Stützen als Welt-Dreiecke (Prisma aus Querschnitt und Höhenlage, wie [`emit_columns`]). +fn pick_columns(p: &Project) -> Vec { + let mut out = Vec::new(); + for col in p.columns.as_deref().unwrap_or(&[]) { + if !(col.height > 0.0) { + continue; + } + let (z0, z1) = p.column_vertical_extent(col); + let foot: Vec<[f64; 2]> = column_footprint(col).iter().map(|q| [q.x, q.y]).collect(); + if foot.len() < 3 || !(z0.is_finite() && z1.is_finite()) { + continue; + } + let (pos, idx) = crate::columns3d::prism(&foot, z0, z1); + let at = |i: u32| -> V3 { let i = i as usize * 3; [pos[i], pos[i + 2], -pos[i + 1]] }; + let tris: Vec = idx.chunks_exact(3).filter(|t| t.iter().all(|&i| (i as usize) * 3 + 2 < pos.len())).map(|t| [at(t[0]), at(t[1]), at(t[2])]).collect(); + if !tris.is_empty() { + out.push(PickColumn { tris, column_id: col.id.clone() }); + } + } + out +} + #[cfg(test)] mod tests { use super::*; @@ -2500,6 +2565,49 @@ mod tests { assert!(emit_context_meshes(&pp(false)).is_empty()); } + /// [137] 3D-Picken: Dreiecke der Baugrube (Sohle, Böschung) tragen die Id der Baugrube, das übrige + /// Gelände die des Netzes. + #[test] + fn pick_gelaende_und_baugrube_im_3d() { + let t = crate::model::TerrainMesh { + id: "t".into(), + positions: vec![0.0, 0.0, 0.0, 60.0, 0.0, 6.0, 60.0, 40.0, 6.0, 0.0, 40.0, 0.0], + indices: vec![0.0, 1.0, 2.0, 0.0, 2.0, 3.0], + ..Default::default() + }; + let v = |x: f64, y: f64| crate::model::Vec2 { x, y }; + let pit = crate::model::Excavation { id: "bg".into(), outline: vec![v(20.0, 15.0), v(30.0, 15.0), v(30.0, 25.0), v(20.0, 25.0)], bottom: 1.0, ..Default::default() }; + let p = Project { context: Some(vec![ContextObject::Excavation(pit), ContextObject::TerrainMesh(t)]), ..Default::default() }; + let g = pick_geometry(&p).unwrap(); + let of = |id: &str| g.context_meshes.iter().find(|m| m.context_object_id == id).map(|m| m.tris.clone()).unwrap_or_default(); + let (bg, terr) = (of("bg"), of("t")); + assert!(!bg.is_empty() && !terr.is_empty(), "{} {}", bg.len(), terr.len()); + // Welt (x, z, −y): alle Baugruben-Dreiecke liegen im Wirkbereich (x 18…32, y 13…27), Sohle auf 1 m dabei. + for tri in &bg { + let (cx, cy) = ((tri[0][0] + tri[1][0] + tri[2][0]) / 3.0, -(tri[0][2] + tri[1][2] + tri[2][2]) / 3.0); + assert!((17.0..=33.0).contains(&cx) && (12.0..=28.0).contains(&cy), "{cx} {cy}"); + } + assert!(bg.iter().any(|tri| tri.iter().all(|q| (q[1] - 1.0).abs() < 1e-6))); + } + + /// [137] Stützen sind im 3D anwählbar: ihr Prisma kommt mit Id in die Pick-Geometrie (Welt: x, Höhe, −y). + #[test] + fn pick_stuetzen_im_3d() { + let p: Project = serde_json::from_value(serde_json::json!({ + "id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "layers": [], "openings": [], "walls": [], + "drawingLevels": [{"id": "EG", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3.0, "baseElevation": 0.0}], + "columns": [{"id": "k1", "type": "column", "floorId": "EG", "categoryCode": "25", "position": {"x": 2, "y": 3}, "profile": {"kind": "rect", "width": 0.3, "depth": 0.3}, "rotation": 0, "height": 2.5}], + "drawings2d": [] + })) + .unwrap(); + let g = pick_geometry(&p).unwrap(); + assert_eq!(g.columns.len(), 1); + assert_eq!(g.columns[0].column_id, "k1"); + let v: Vec<&V3> = g.columns[0].tris.iter().flatten().collect(); + assert!(v.iter().all(|q| (q[0] - 2.0).abs() <= 0.15 + 1e-9 && (q[2] + 3.0).abs() <= 0.15 + 1e-9 && q[1] >= -1e-9 && q[1] <= 2.5 + 1e-9)); + assert!(v.iter().any(|q| (q[1] - 2.5).abs() < 1e-9)); + } + /// [T4] Import-Mesh glatt: Knickwinkel geht ans 3D (Vorgabe 30°), kantig ohne; JSON `creaseAngle`. #[test] fn import_mesh_glatt_mit_knickwinkel() { diff --git a/src-tauri/core/src/plan/context.rs b/src-tauri/core/src/plan/context.rs index ea8467fa..515fd692 100644 --- a/src-tauri/core/src/plan/context.rs +++ b/src-tauri/core/src/plan/context.rs @@ -59,6 +59,9 @@ fn bbox_corners(positions: &[f64]) -> Option> { /// Kontext-Schicht (`addContextContours`). Objekte ohne Kategorie bleiben immer sichtbar. pub fn plan_context(c: &Ctx, out: &mut Vec) { + // [137] Pick-Flächen der Baugruben zuletzt (zuoberst): sie liegen im Rahmen des Geländes, das sonst + // jeden Klick in der Grube fängt. + let mut late: Vec = Vec::new(); for obj in c.p.context.as_deref().unwrap_or(&[]) { let code = match obj { ContextObject::ImportedMesh(m) => m.category_code.as_deref(), @@ -72,6 +75,11 @@ pub fn plan_context(c: &Ctx, out: &mut Vec) { } match obj { ContextObject::ContourSet(s) => { + // [137] Rahmen als Pick-Fläche (unter dem daraus erzeugten Gelände; Cmd+Klick schaltet durch). + let all: Vec = s.contours.iter().flat_map(|k| k.pts.iter().flat_map(|q| [q.x, q.y, 0.0])).collect(); + if let Some(pts) = bbox_corners(&all) { + out.push(pick_band(pts, Some(&s.id), None)); + } for k in &s.contours { let pts = &k.pts; if pts.len() < 2 { @@ -102,10 +110,11 @@ pub fn plan_context(c: &Ctx, out: &mut Vec) { } terrain_contours(c, t, out); } - ContextObject::Excavation(e) => excavation_lines(c, e, out), + ContextObject::Excavation(e) => excavation_lines(c, e, out, &mut late), ContextObject::Image(_) => {} } } + out.append(&mut late); } const TERRAIN_INK: &str = "#7a5b3a"; @@ -185,7 +194,7 @@ fn terrain_contours(c: &Ctx, t: &TerrainMesh, out: &mut Vec) { } /// [68] Baugrube im Grundriss: Sohle (Böschungsfuss) und Böschungsoberkante, Böschungsschraffur. -fn excavation_lines(c: &Ctx, e: &Excavation, out: &mut Vec) { +fn excavation_lines(c: &Ctx, e: &Excavation, out: &mut Vec, bands: &mut Vec) { let ring: Vec = e.outline.iter().copied().filter(|q| q.x.is_finite() && q.y.is_finite()).collect(); if ring.len() < 3 { return; @@ -193,7 +202,10 @@ fn excavation_lines(c: &Ctx, e: &Excavation, out: &mut Vec) { for i in 0..ring.len() { out.push(ink_line(ring[i], ring[(i + 1) % ring.len()], 0.25, EXCAVATION_INK, None)); } - out.push(pick_band(ring.clone(), Some(&e.id), None)); + // [137] Pick-Fläche = Wirkbereich (Sohle + Böschungen), ohne Gelände nur die Sohle. + let hull = crate::excavation::terrains(c.p).into_iter().map(|t| crate::excavation::affected_hull(&crate::excavation::site_terrain(c.p, t), &e.id)).find(|h| h.len() >= 3); + let band = hull.map_or_else(|| ring.clone(), |h| h.iter().map(|q| v2(q[0], q[1])).collect()); + bands.push(pick_band(band, Some(&e.id), None)); let spacing = (0.004 * c.a.scale.max(1.0)).max(0.2); for t in crate::excavation::terrains(c.p) { let st = crate::excavation::site_terrain(c.p, t); @@ -292,6 +304,52 @@ pub fn plan_section_lines(c: &Ctx, out: &mut Vec) { mod tests { use super::*; + /// Oberstes Kontext-Pick-Band unter dem Punkt (wie `PickIndex::polygons_at` mit Maske „Kontext"). + fn top_context(out: &[Primitive], x: f64, y: f64) -> Option { + out.iter().rev().find_map(|q| match q { + Primitive::Polygon { pts, context_object_id: Some(id), .. } => { + let flat: Vec = pts.iter().flat_map(|v| [v.x, v.y]).collect(); + crate::plan::pick::point_in_polygon(x, y, &flat).then(|| id.clone()) + } + _ => None, + }) + } + + /// [137] Auswahl im Grundriss: Klick in die Baugrube (Sohle und Böschung) wählt die Baugrube, auch wenn + /// das Gelände in der Liste später kommt; daneben das Gelände; ausserhalb des Geländes die Höhenlinien. + #[test] + fn auswahl_gelaende_baugrube_hoehenlinien() { + let t = TerrainMesh { + id: "t".into(), + positions: vec![0.0, 0.0, 0.0, 60.0, 0.0, 6.0, 60.0, 40.0, 6.0, 0.0, 40.0, 0.0], + indices: vec![0.0, 1.0, 2.0, 0.0, 2.0, 3.0], + category_code: Some("02".into()), + ..Default::default() + }; + let pit = Excavation { + id: "bg".into(), + outline: vec![v2(20.0, 15.0), v2(30.0, 15.0), v2(30.0, 25.0), v2(20.0, 25.0)], + bottom: 1.0, + ..Default::default() + }; + let cs = ContourSet { + id: "hl".into(), + contours: vec![Contour { z: 0.0, pts: vec![v2(-20.0, -5.0), v2(80.0, 50.0)], ..Default::default() }], + ..Default::default() + }; + // Reihenfolge wie im Musterhaus komplex: Höhenlinien, Baugrube, dann das daraus erzeugte Gelände. + let p = Project { context: Some(vec![ContextObject::ContourSet(cs), ContextObject::Excavation(pit), ContextObject::TerrainMesh(t)]), ..Default::default() }; + let a = super::super::domains::PlanArgs::parse(1.0, r#"{"show": ["02"], "scale": 100}"#).unwrap(); + let mut out = Vec::new(); + plan_context(&Ctx::new(&p, &a), &mut out); + assert_eq!(top_context(&out, 25.0, 20.0).as_deref(), Some("bg"), "Sohle"); + // Ostseite: Gelände 3 m bei x = 30, Sohle 1 m → 2 m Böschung (45°) bis x ≈ 32. + assert_eq!(top_context(&out, 31.0, 20.0).as_deref(), Some("bg"), "Böschung"); + assert_eq!(top_context(&out, 50.0, 5.0).as_deref(), Some("t"), "Gelände"); + assert_eq!(top_context(&out, -10.0, 0.0).as_deref(), Some("hl"), "Höhenlinien"); + assert_eq!(top_context(&out, -30.0, 0.0), None); + } + /// [T6]/[68] Höhenlinien (Zähllinien dicker + beschriftet) und Baugrube (Sohle, Oberkante, Schraffur). #[test] fn hoehenlinien_und_baugrube() { diff --git a/src-tauri/core/src/plan/domains.rs b/src-tauri/core/src/plan/domains.rs index 8843e47a..7249db3a 100644 --- a/src-tauri/core/src/plan/domains.rs +++ b/src-tauri/core/src/plan/domains.rs @@ -798,7 +798,7 @@ pub fn plan_domains_buf(p: &Project, a: &PlanArgs) -> Result, String> { /// beim projektglobalen Aufruf (`global`). fn extras_of(p: &Project, a: &PlanArgs) -> (Vec<(Primitive, u32)>, Vec) { if a.global { - super::extras::site_and_shadow(p, &a.floor, a.sun_when) + super::extras::site_and_shadow(p, &a.floor, a.sun_when, a.scale) } else { (Vec::new(), Vec::new()) } diff --git a/src-tauri/core/src/plan/elevation.rs b/src-tauri/core/src/plan/elevation.rs index 0cbe9416..d9376145 100644 --- a/src-tauri/core/src/plan/elevation.rs +++ b/src-tauri/core/src/plan/elevation.rs @@ -1524,7 +1524,12 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono: let mut ring: Vec = l.iter().map(|q| v2(q[0], q[1])).collect(); ring.push(v2(l[l.len() - 1][0], low)); ring.push(v2(l[0][0], low)); - prims.push(polygon(ring, "#ffffff", "none", 0.0, no_hatch())); + // [137] Die Geländefläche wählt das Gelände (Pick-Id). + let mut mask = polygon(ring, "#ffffff", "none", 0.0, no_hatch()); + if let Primitive::Polygon { context_object_id, .. } = &mut mask { + *context_object_id = Some(t.id.clone()); + } + prims.push(mask); for w in l.windows(2) { acc.add(w[0][0], w[0][1]); acc.add(w[1][0], w[1][1]); diff --git a/src-tauri/core/src/plan/extras.rs b/src-tauri/core/src/plan/extras.rs index 0e4dc594..bae4814f 100644 --- a/src-tauri/core/src/plan/extras.rs +++ b/src-tauri/core/src/plan/extras.rs @@ -11,6 +11,11 @@ use crate::jsnum; use crate::model::*; use std::collections::HashMap; +/// [137] Pick-Ids der abgeleiteten Lage-Darstellung (im Feld `contextObjectId`, mit `@` — keine Element-Id +/// beginnt so): Schattenflächen wählen den Sonnenstand, die Baurechtslinien (unsichtbare Bänder) das Baurecht. +pub const SITE_PICK_SUN: &str = "@sunStudy"; +pub const SITE_PICK_RULES: &str = "@siteRules"; + /// Füllfarbe der Schattenflächen. pub const SUN_SHADOW_FILL: &str = "#3a4a66"; const SUN_SHADOW_OPACITY: f64 = 0.28; @@ -91,7 +96,11 @@ pub fn sun_shadow(p: &Project, floor: &str, when_ms: Option, out: &mut Vec< let sun = crate::sun::sun_position(lat, lon, t); for poly in crate::sun::shadow_polygons_project(p, sun) { for r in crate::sun::without_holes(&poly) { - out.push(flat_polygon(ring_pts(&r), SUN_SHADOW_FILL, SUN_SHADOW_OPACITY)); + let mut q = flat_polygon(ring_pts(&r), SUN_SHADOW_FILL, SUN_SHADOW_OPACITY); + if let Primitive::Polygon { context_object_id, .. } = &mut q { + *context_object_id = Some(SITE_PICK_SUN.into()); + } + out.push(q); } } } @@ -129,10 +138,27 @@ fn ring_lines(out: &mut Vec<(Primitive, u32)>, pts: &[Vec2], cls: &str, color: & } } +/// [137] Unsichtbares Rechteck der halben Breite `half` um die Strecke a–b mit der Pick-Id des Baurechts. +fn seg_band(a: Vec2, b: Vec2, half: f64) -> Option { + let (dx, dy) = (b.x - a.x, b.y - a.y); + let l = dx.hypot(dy); + if !(l > 1e-9) { + return None; + } + let (nx, ny) = (-dy / l * half, dx / l * half); + let pts = vec![Vec2 { x: a.x + nx, y: a.y + ny }, Vec2 { x: b.x + nx, y: b.y + ny }, Vec2 { x: b.x - nx, y: b.y - ny }, Vec2 { x: a.x - nx, y: a.y - ny }]; + let mut q = flat_polygon(pts, "none", 1.0); + if let Primitive::Polygon { context_object_id, opacity, .. } = &mut q { + *context_object_id = Some(SITE_PICK_RULES.into()); + *opacity = None; + } + Some(q) +} + /// Unterste Gruppe: Schatten, dann Parzellengrenze (Strich-Punkt) und zulässige Fläche /// (gestrichelt); mit Strichmuster-Kennung je Primitiv. Dazu die Verstösse (Gebäude-Grundfläche /// ausserhalb der zulässigen Fläche) für die oberste Gruppe. -pub fn site_and_shadow(p: &Project, floor: &str, when_ms: Option) -> (Vec<(Primitive, u32)>, Vec) { +pub fn site_and_shadow(p: &Project, floor: &str, when_ms: Option, scale: f64) -> (Vec<(Primitive, u32)>, Vec) { let mut shadow = Vec::new(); sun_shadow(p, floor, when_ms, &mut shadow); let mut under: Vec<(Primitive, u32)> = shadow.into_iter().map(|q| (q, 0)).collect(); @@ -146,6 +172,16 @@ pub fn site_and_shadow(p: &Project, floor: &str, when_ms: Option) -> (Vec<( ring_lines(&mut under, ring, SITE_ALLOWED_CLS, ALLOWED_COLOR, 0.25, &ALLOWED_DASH, r); } } + // [137] Unsichtbare Pick-Bänder (±1.5 mm Papier) über den Linien: ein Klick wählt das Baurecht. + let half = 0.0015 * if scale.is_finite() && scale > 0.0 { scale } else { 100.0 }; + let rings = std::iter::once(rules.parcel.as_slice()).chain(check.allowed.iter().flatten().map(|r| r.as_slice())); + for ring in rings { + for i in 0..ring.len() { + if let Some(band) = seg_band(ring[i], ring[(i + 1) % ring.len()], half) { + under.push((band, 0)); + } + } + } for poly in &check.violations { let rings: Vec> = poly.iter().map(|r| r.iter().map(|q| [q.x, q.y]).collect()).collect(); for ring in crate::sun::without_holes(&rings) { @@ -528,14 +564,59 @@ mod tests { serde_json::from_value(v).unwrap() }; p.site_rules = Some(rules(serde_json::json!({}))); - let n0 = site_and_shadow(&p, &floor, None).1.len(); + let n0 = site_and_shadow(&p, &floor, None, 100.0).1.len(); p.site_rules = Some(rules(serde_json::json!({"profileAngle": 10.0, "profileHeight": 0.01}))); let c = crate::site_rules::check_project(&p).unwrap(); assert!(c.profile_exceeded); - let n1 = site_and_shadow(&p, &floor, None).1.len(); + let n1 = site_and_shadow(&p, &floor, None, 100.0).1.len(); assert!(n1 > n0, "{n0} {n1}"); } + /// Oberste Fläche mit Pick-Id unter dem Punkt (wie `PickIndex::polygons_at`, Maske „Kontext"). + fn top_pick(prims: &[(Primitive, u32)], x: f64, y: f64) -> Option { + prims.iter().rev().find_map(|(q, _)| match q { + Primitive::Polygon { pts, context_object_id: Some(id), .. } => { + let flat: Vec = pts.iter().flat_map(|v| [v.x, v.y]).collect(); + crate::plan::pick::point_in_polygon(x, y, &flat).then(|| id.clone()) + } + _ => None, + }) + } + + /// [137] Schattenflächen tragen die Pick-Id des Sonnenstands, die Baurechtslinien unsichtbare Bänder mit der + /// des Baurechts (Klick darauf öffnet deren Einstellungen); ohne sichtbare Studie bzw. in einem anderen + /// Geschoss nichts. + #[test] + fn klick_auf_schatten_und_baurecht() { + let mut p = sample(); + let floor = ground_floor_id(&p).unwrap().to_string(); + p.sun_study = Some(SunStudy { when: "2026-12-21T09:00:00Z".into(), show: true, ..Default::default() }); + let when = Some(1_797_843_600_000.0); // 2026-12-21T09:00:00Z + let (under, _) = site_and_shadow(&p, &floor, when, 100.0); + let shadows: Vec<&Primitive> = under.iter().map(|(q, _)| q).filter(|q| matches!(q, Primitive::Polygon { fill, .. } if fill == SUN_SHADOW_FILL)).collect(); + assert!(!shadows.is_empty()); + assert!(shadows.iter().all(|q| matches!(q, Primitive::Polygon { context_object_id: Some(id), .. } if id == SITE_PICK_SUN))); + // Ein Punkt in der ersten Schattenfläche (Raster über ihr Ausmass). + let Primitive::Polygon { pts, .. } = shadows[0] else { panic!() }; + let flat: Vec = pts.iter().flat_map(|v| [v.x, v.y]).collect(); + let (x0, x1) = pts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |a, v| (a.0.min(v.x), a.1.max(v.x))); + let (y0, y1) = pts.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |a, v| (a.0.min(v.y), a.1.max(v.y))); + let inside = (0..400).map(|k| (x0 + (x1 - x0) * ((k % 20) as f64 + 0.5) / 20.0, y0 + (y1 - y0) * ((k / 20) as f64 + 0.5) / 20.0)).find(|q| crate::plan::pick::point_in_polygon(q.0, q.1, &flat)).unwrap(); + assert_eq!(top_pick(&under, inside.0, inside.1).as_deref(), Some(SITE_PICK_SUN)); + assert_eq!(top_pick(&under, 1e4, 1e4), None); + assert!(site_and_shadow(&p, "anderes-geschoss", when, 100.0).0.is_empty()); + p.sun_study.as_mut().unwrap().show = false; + assert_eq!(top_pick(&site_and_shadow(&p, &floor, when, 100.0).0, inside.0, inside.1), None); + // Baurecht: Parzellengrenze bei x = −30, Grenzabstand 3 m → zulässige Fläche ab x = −27; Band ±0.15 m bei 1:100. + p.site_rules = Some(serde_json::from_value(serde_json::json!({"parcel": [{"x": -30, "y": -30}, {"x": 40, "y": -30}, {"x": 40, "y": 40}, {"x": -30, "y": 40}], "defaultSetback": 3.0})).unwrap()); + let (under, _) = site_and_shadow(&p, &floor, when, 100.0); + assert_eq!(top_pick(&under, -30.1, 5.0).as_deref(), Some(SITE_PICK_RULES)); + assert_eq!(top_pick(&under, -27.0, 5.0).as_deref(), Some(SITE_PICK_RULES), "zulässige Fläche"); + assert_eq!(top_pick(&under, -28.5, 5.0), None); + // Massstab 1:500: Band ±0.75 m. + assert_eq!(top_pick(&site_and_shadow(&p, &floor, when, 500.0).0, -29.4, 5.0).as_deref(), Some(SITE_PICK_RULES)); + } + #[test] fn strichstaerken_faktor() { let mut on = sample(); diff --git a/src-tauri/core/src/plan/section.rs b/src-tauri/core/src/plan/section.rs index 3229ed30..cd567347 100644 --- a/src-tauri/core/src/plan/section.rs +++ b/src-tauri/core/src/plan/section.rs @@ -206,6 +206,8 @@ pub struct Output { pub profiles: Vec, /// [T6] Erdreich unter dem gestalteten Terrain (Band, ohne Gebäude-Inneres), mit Schraffur. pub earth: Vec<(Vec<[f64; 2]>, HatchRender)>, + /// [137] Gelände, zu dem das Erdreich-Band gehört (Pick-Id: Klick ins Band wählt das Gelände). + pub terrain_id: Option, } /// Ein truck-Körper (aus TS, asynchron gebaut): Index in `extrudedSolids` + Netz. @@ -1839,6 +1841,7 @@ fn append_terrain_profiles(out: &mut Output, p: &Project, base: (f64, f64), u: ( if t.positions.len() < 9 { continue; } + out.terrain_id.get_or_insert_with(|| t.id.clone()); // [T6] Gelände samt Baugruben, Höhen im Modellbezug; das gewachsene Terrain gestrichelt dazu. let st = crate::excavation::site_terrain(p, t); let mut meshes = vec![(st.current().to_flat(-st.datum), false)]; @@ -2182,7 +2185,7 @@ pub fn compute_section(p: &Project, level: &LevelSpec, bodies: &[BodyMesh]) -> R // Projektion hinter der Ebene exakt ([G4]); die Schnittflächen verdecken, was hinter ihnen liegt. let (mut visible, hidden) = projection_edges(p, &plane, &walls_r, &wi, &slabs_r, &bodies, &cuts, level.hidden_lines, level.depth); shaped_projection(&mut visible, p, &walls_r, &plane); - let mut out = Output { cuts, visible, hidden, profiles: Vec::new(), earth: Vec::new() }; + let mut out = Output { cuts, visible, hidden, profiles: Vec::new(), earth: Vec::new(), terrain_id: None }; append_terrain_profiles(&mut out, p, base, u); Ok(Some(out)) } @@ -2267,7 +2270,11 @@ pub fn section_primitives(out: &Output, mono: bool, hidden_lines: bool, vis: &Vi if terrain_shown { for (ring, hatch) in &out.earth { let hatch = if mono { HatchRender { color: SECTION_INK.into(), ..hatch.clone() } } else { hatch.clone() }; - prims.push(polygon(ring.iter().map(|q| v2(q[0], q[1])).collect(), "none", "none", 0.0, hatch)); + let mut q = polygon(ring.iter().map(|q| v2(q[0], q[1])).collect(), "none", "none", 0.0, hatch); + if let Primitive::Polygon { context_object_id, .. } = &mut q { + *context_object_id = out.terrain_id.clone(); + } + prims.push(q); } } for cp in &out.cuts { @@ -3318,13 +3325,14 @@ mod tests { assert!((designed_min + 2.0).abs() < 1e-6, "{designed_min}"); assert!(!out.earth.is_empty()); let (prims, _) = section_primitives(&out, false, false, &Visibility::default()); - assert!(prims.iter().any(|q| matches!(q, Primitive::Polygon { hatch, .. } if hatch.pattern == HatchPattern::Earth))); + // [137] Das Erdreich-Band und die Geländefläche der Ansicht wählen das Gelände. + assert!(prims.iter().any(|q| matches!(q, Primitive::Polygon { hatch, context_object_id: Some(id), .. } if hatch.pattern == HatchPattern::Earth && id == "t"))); assert!(prims.iter().any(|q| matches!(q, Primitive::Line { cls, dash: Some(Some(_)), .. } if cls == "section-terrain"))); let (ep, _) = super::super::elevation::elevation_primitives(&p, &level(&p, "ansicht-sued"), false, false, &Visibility::default(), 100.0).unwrap().unwrap(); let sil: Vec = ep.iter().filter_map(|q| if let Primitive::Line { cls, a, b, .. } = q { (cls == "elevation-terrain").then_some(a.y.min(b.y)) } else { None }).collect(); // Die Ansichtslinie (y = −2) liegt in der Böschung: die Silhouette taucht vor dem Gebäude ein, nie unter die Sohle. assert!(!sil.is_empty() && sil.iter().all(|z| *z <= 1e-6 && *z >= -2.0 - 1e-6) && sil.iter().any(|z| *z < -0.5), "{sil:?}"); - assert!(ep.iter().any(|q| matches!(q, Primitive::Polygon { fill, .. } if fill == "#ffffff"))); + assert!(ep.iter().any(|q| matches!(q, Primitive::Polygon { fill, context_object_id: Some(id), .. } if fill == "#ffffff" && id == "t"))); assert!(!ep.iter().any(|q| matches!(q, Primitive::Line { cls, .. } if cls == "elevation-ground"))); let f = crate::site_rules::facade_terrain(&p); assert!(!f.is_empty() && f.iter().all(|q| q.natural == Some(0.0) && q.designed.is_some_and(|z| (z + 2.0).abs() < 1e-6))); diff --git a/src/core/index.ts b/src/core/index.ts index dd9c02ec..c55fba58 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -161,6 +161,7 @@ export { export { DRAWING_PICK_TOLERANCE, type PickContextMesh, + type PickColumnMesh, type PickDrawingSeg, type PickOpening, type PickRoof, diff --git a/src/i18n/de.ts b/src/i18n/de.ts index f0068026..b6dc77d2 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -457,6 +457,10 @@ export const de = { "objinfo.kind.column": "Stütze", "objinfo.kind.roof": "Dach", "objinfo.kind.contextObject": "Kontext-Objekt", + "objinfo.kind.sunStudy": "Schatten (Sonnenstand)", + "objinfo.kind.siteRules": "Baurecht", + "objinfo.sunStudy.hint": "Schatten werden aus dem Modell abgeleitet — Datum und Uhrzeit hier ändern.", + "objinfo.siteRules.hint": "Parzellengrenze und zulässige Fläche kommen aus dem Baurecht — hier bearbeiten.", // ── Kontext-Objekt-Attribute (Object-Info-Panel) ──────────────────────── "objinfo.contextObject.section": "Georeferenzierung", "objinfo.contextObject.type": "Art", @@ -464,6 +468,7 @@ export const de = { "objinfo.contextObject.type.terrainMesh": "Gelände", "objinfo.contextObject.type.contourSet": "Höhenlinien", "objinfo.contextObject.type.image": "Luftbild", + "objinfo.contextObject.type.excavation": "Baugrube", "objinfo.contextObject.lv95E": "LV95 Ost (E)", "objinfo.contextObject.lv95N": "LV95 Nord (N)", "objinfo.contextObject.noAnchor": "Kein Standort-Bezug im Projekt", @@ -2087,6 +2092,12 @@ export const de = { "site.excavation.shoring": "Verbau (senkrecht), Kante", "site.excavation.shoringHint": "Gewählte Kanten: senkrechte Wand (Spundwand) statt Böschung", "site.earthDepth": "Erdreich-Band im Schnitt [m]", + "site.terrain.visible": "Gelände sichtbar", + "site.terrain.visible.hint": "Blendet die Kategorie {name} ein oder aus (alle Ansichten, ein Undo-Schritt)", + "site.terrain.smooth": "Glättung", + "site.terrain.smooth.hint": "Gelände aus den Höhenlinien neu erzeugen (Bruchkanten bleiben, ein Undo-Schritt)", + "site.terrain.smooth.raw": "roh (ohne Glättung)", + "site.terrain.smooth.level": "Stufe {n}", "site.type.image": "Luftbild", "site.group.image": "Luftbild", "site.dwgHint": "DWG? Zuerst mit dem gratis ODA File Converter in DXF umwandeln.", @@ -2174,6 +2185,9 @@ export const de = { "pick.kind.room": "Raum", "pick.kind.roof": "Dach", "pick.kind.context": "Kontext-Objekt", + "pick.kind.site": "Lage", + "pick.site.sunStudy": "Schatten (Sonnenstand)", + "pick.site.siteRules": "Baurecht", "pick.shape.line": "Linie", "pick.shape.polyline": "Polylinie", "pick.shape.area": "Fläche", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index d6582352..d553963f 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -455,6 +455,10 @@ export const en: Record = { "objinfo.kind.column": "Column", "objinfo.kind.roof": "Roof", "objinfo.kind.contextObject": "Context object", + "objinfo.kind.sunStudy": "Shadow (sun position)", + "objinfo.kind.siteRules": "Building regulations", + "objinfo.sunStudy.hint": "Shadows are derived from the model — change date and time here.", + "objinfo.siteRules.hint": "Parcel boundary and buildable area come from the building regulations — edit them here.", // ── Context object attributes (object info panel) ─────────────────────── "objinfo.contextObject.section": "Georeferencing", "objinfo.contextObject.type": "Type", @@ -462,6 +466,7 @@ export const en: Record = { "objinfo.contextObject.type.terrainMesh": "Terrain", "objinfo.contextObject.type.contourSet": "Contours", "objinfo.contextObject.type.image": "Aerial image", + "objinfo.contextObject.type.excavation": "Excavation", "objinfo.contextObject.lv95E": "LV95 East (E)", "objinfo.contextObject.lv95N": "LV95 North (N)", "objinfo.contextObject.noAnchor": "No location reference in project", @@ -2073,6 +2078,12 @@ export const en: Record = { "site.excavation.shoring": "Shoring (vertical), edge", "site.excavation.shoringHint": "Selected edges: vertical wall (sheet piling) instead of a slope", "site.earthDepth": "Earth band in section [m]", + "site.terrain.visible": "Terrain visible", + "site.terrain.visible.hint": "Shows or hides the category {name} (all views, one undo step)", + "site.terrain.smooth": "Smoothing", + "site.terrain.smooth.hint": "Regenerate the terrain from its contour lines (breaklines kept, one undo step)", + "site.terrain.smooth.raw": "raw (no smoothing)", + "site.terrain.smooth.level": "Level {n}", "site.excavation.qty": "Cut {cut} m³ · Fill {fill} m³ · Backfill {backfill} m³", "site.excavation.noTerrain": "No terrain below the excavation", "site.type.image": "Aerial", @@ -2162,6 +2173,9 @@ export const en: Record = { "pick.kind.room": "Room", "pick.kind.roof": "Roof", "pick.kind.context": "Context object", + "pick.kind.site": "Site", + "pick.site.sunStudy": "Shadow (sun position)", + "pick.site.siteRules": "Building regulations", "pick.shape.line": "Line", "pick.shape.polyline": "Polyline", "pick.shape.area": "Area", diff --git a/src/model/types.generated.ts b/src/model/types.generated.ts index 9f39af88..cc9088b5 100644 --- a/src/model/types.generated.ts +++ b/src/model/types.generated.ts @@ -3112,6 +3112,13 @@ export type TerrainMesh = { contourIndexEvery?: number; /** [T6] Tiefe des Erdreich-Bands im Schnitt unter dem Gelände in m (Default 1.5). */ earthDepth?: number; + /** + * [137] Glättungsstufe, mit der das Netz aus Höhenlinien erzeugt wurde (0 = roh, 1–4 Kantenteilungen). + * Fehlt bei importierten Netzen (swissALTI3D) — dann gibt es nichts neu zu glätten. + */ + smooth?: number; + /** [137] Quelle: Id des Höhenlinien-Satzes (`contourSet`), aus dem das Netz erzeugt wurde. */ + sourceId?: string; }; /** Ein zusammenhängender Textabschnitt mit einheitlicher Formatierung. */ diff --git a/src/panels/ContextObjectProps.tsx b/src/panels/ContextObjectProps.tsx new file mode 100644 index 00000000..bc164c0d --- /dev/null +++ b/src/panels/ContextObjectProps.tsx @@ -0,0 +1,156 @@ +// Einstellungen eines Kontext-Objekts (importiertes Mesh, Gelände, Baugrube) — gemeinsam für die Liste im +// Panel „Gelände & Kontext" und die Objekt-Info ([137]: ein angeklicktes Gelände bzw. eine Baugrube zeigt +// dort dieselben Felder). Gelände zusätzlich: Sichtbarkeit seiner Kategorie und Glättung (aus den +// Höhenlinien neu erzeugt, ein Undo-Schritt). +// +// Bezeichner englisch, UI-Text/Kommentare deutsch. Alle sichtbaren Texte über t(...). + +import { t } from "../i18n"; +import { usePanelHost } from "./host"; +import { useStore } from "../state/appStore"; +import type { ContextObject } from "../model/types"; +import { flattenCategories } from "../model/types"; +import type { ExcavationQuantity } from "../core"; + +/** Zahl-Eingabe für ein Feld eines Kontext-Objekts (leer = Standard, ungültig = keine Änderung). */ +export function NumField(props: { + label: string; + value: number | undefined; + step: number; + min?: number; + placeholder?: string; + onChange: (v: number | undefined) => void; +}) { + return ( + + ); +} + +const fmt1 = (v: number) => v.toLocaleString("de-CH", { maximumFractionDigits: 1, minimumFractionDigits: 1 }); + +function ExcavationQty({ q }: { q: ExcavationQuantity | undefined }) { + if (!q) return
{t("site.excavation.noTerrain")}
; + return ( +
+ {t("site.excavation.qty", { cut: fmt1(q.cut), fill: fmt1(q.fill), backfill: fmt1(q.backfill) })} +
+ ); +} + +/** Glättungsstufen der Gelände-Erzeugung (`terrain.rs`, 0 = roh). */ +const SMOOTH_LEVELS = [0, 1, 2, 3] as const; + +/** Felder eines Kontext-Objekts; `null` für Arten ohne eigene Einstellungen (Höhenlinien, Luftbild). */ +export function ContextObjectProps({ obj, quantities }: { obj: ContextObject; quantities: readonly ExcavationQuantity[] }) { + const host = usePanelHost(); + const notify = useStore((s) => s.notify); + const regenerateTerrain = useStore((s) => s.regenerateTerrain); + const patch = (field: string) => (v: number | undefined) => host.onPatchContextObject(obj.id, { [field]: v }, `site-${obj.id}-${field}`); + + if (obj.type === "importedMesh") { + // [T4] Glatt oder kantig schattieren, Knickwinkel je Mesh (Vorgabe 30°). + return ( +
+ + {obj.smoothShading === true && ( + + )} +
+ ); + } + + if (obj.type === "terrainMesh") { + const cat = obj.categoryCode ? flattenCategories(host.project.layers).find((c) => c.code === obj.categoryCode) : undefined; + const hasSource = (host.project.context ?? []).some((o) => o.type === "contourSet"); + return ( +
+ {cat && ( + + )} + {hasSource && ( + + )} + + + +
+ ); + } + + if (obj.type === "excavation") { + return ( +
+ v !== undefined && patch("bottom")(v)} /> + + + + + +
+ {t("site.excavation.shoring")} + + {obj.outline.map((_, i) => ( + + ))} + +
+ x.id === obj.id)} /> +
+ ); + } + return null; +} diff --git a/src/panels/ObjectInfoPanel.tsx b/src/panels/ObjectInfoPanel.tsx index 61a9770d..0704158d 100644 --- a/src/panels/ObjectInfoPanel.tsx +++ b/src/panels/ObjectInfoPanel.tsx @@ -59,6 +59,11 @@ import type { WallInfo, } from "../state/selectionInfo"; import type { MeasurementReadout } from "../tools/types"; +import { useStore } from "../state/appStore"; +import { excavationQuantities } from "../core"; +import { ContextObjectProps } from "./ContextObjectProps"; +import { SunStudySection } from "./SunStudySection"; +import { SiteRulesSection } from "./SiteRulesSection"; // ── Bezugspunkt-Raster ─────────────────────────────────────────────────────── // Neun Anker als 3×3-Raster. Zeile 0 = oben (fy=0), Spalte 0 = links (fx=0). @@ -91,7 +96,27 @@ export function ObjectInfoPanel() { // (das Mess-Werkzeug erzeugt kein Element). Hat Vorrang vor dem Leerzustand. const m = host.measurement; + // [137] Lage-Darstellung angeklickt (Schattenfläche / Baurechtslinie): Einstellungen der Quelle. + const site = useStore((s) => s.selection.site); + const ctxObj = sel?.kind === "contextObject" ? (host.project.context ?? []).find((o) => o.id === sel.id) : undefined; + const quantities = useMemo( + () => (ctxObj?.type === "excavation" ? excavationQuantities(host.project) : []), + [ctxObj?.type, host.project], + ); + // ── Leerzustand ─────────────────────────────────────────────────────────── + if (sel === null && site.length > 0) { + const sun = site[0] === "sunStudy"; + return ( +
+
+ {t(sun ? "objinfo.kind.sunStudy" : "objinfo.kind.siteRules")} +
+
{t(sun ? "objinfo.sunStudy.hint" : "objinfo.siteRules.hint")}
+
{sun ? : }
+
+ ); + } if (sel === null) { return (
@@ -340,6 +365,11 @@ export function ObjectInfoPanel() { {t("objinfo.contextObject.type")} {t(`objinfo.contextObject.type.${sel.contextObject.objType}`)}
+ {ctxObj && ( +
+ +
+ )} {sel.contextObject.lv95Center ? ( <>
diff --git a/src/panels/SitePanel.tsx b/src/panels/SitePanel.tsx index da592218..9b8c1b8e 100644 --- a/src/panels/SitePanel.tsx +++ b/src/panels/SitePanel.tsx @@ -27,6 +27,7 @@ import { SunStudySection } from "./SunStudySection"; import { SiteRulesSection } from "./SiteRulesSection"; import { PointCloudSection } from "./PointCloudSection"; import { excavationQuantities } from "../core"; +import { ContextObjectProps } from "./ContextObjectProps"; /** Typ-spezifisches Badge-Label (i18n-Key) je Kontext-Objekt-Art. */ function typeBadgeKey(obj: ContextObject): TranslationKey { @@ -61,37 +62,6 @@ function layerOf(obj: ContextObject): string { } } -/** Zahl-Eingabe für ein Feld eines Kontext-Objekts (leer = Standard, ungültig = keine Änderung). */ -function NumField(props: { - label: string; - value: number | undefined; - step: number; - min?: number; - placeholder?: string; - onChange: (v: number | undefined) => void; -}) { - return ( - - ); -} - -const fmt1 = (v: number) => v.toLocaleString("de-CH", { maximumFractionDigits: 1, minimumFractionDigits: 1 }); - /** Gruppiert Kontext-Objekte nach Ebene, Reihenfolge des ersten Auftretens. */ function groupByLayer(objects: ContextObject[]): { layer: string; items: ContextObject[] }[] { const order: string[] = []; @@ -109,15 +79,6 @@ function groupByLayer(objects: ContextObject[]): { layer: string; items: Context return order.map((layer) => ({ layer, items: byLayer.get(layer)! })); } -function ExcavationQty({ q }: { q: { cut: number; fill: number; backfill: number } | undefined }) { - if (!q) return
{t("site.excavation.noTerrain")}
; - return ( -
- {t("site.excavation.qty", { cut: fmt1(q.cut), fill: fmt1(q.fill), backfill: fmt1(q.backfill) })} -
- ); -} - export function SitePanel() { const host = usePanelHost(); // Gewählte Kontext-Objekte schmal aus dem Store ([121], [130]). @@ -140,8 +101,6 @@ export function SitePanel() { const [smooth, setSmooth] = useState(true); // [68] Mengen der Baugruben (Kern), nur neu, wenn sich das Projekt ändert. const quantities = useMemo(() => excavationQuantities(host.project), [host.project]); - const patch = (id: string, field: string) => (v: number | undefined) => - host.onPatchContextObject(id, { [field]: v }, `site-${id}-${field}`); const onGenerate = () => { if (!effectiveSet) return; @@ -278,122 +237,7 @@ export function SitePanel() { > × - {obj.type === "importedMesh" && ( - // [T4] Glatt oder kantig schattieren, Knickwinkel je Mesh (Vorgabe 30°). -
- - {obj.smoothShading === true && ( - - )} -
- )} - {obj.type === "terrainMesh" && ( -
- - - -
- )} - {obj.type === "excavation" && ( -
- v !== undefined && patch(obj.id, "bottom")(v)} - /> - - - - - -
- {t("site.excavation.shoring")} - - {obj.outline.map((_, i) => ( - - ))} - -
- x.id === obj.id)} /> -
- )} + ))} diff --git a/src/plan/__golden__/komplex-grundriss-eg-100.txt b/src/plan/__golden__/komplex-grundriss-eg-100.txt index 088db910..b2f36a5f 100644 --- a/src/plan/__golden__/komplex-grundriss-eg-100.txt +++ b/src/plan/__golden__/komplex-grundriss-eg-100.txt @@ -1,10 +1,10 @@ viewBox -41.5 0 95 63.6 -bytes 146250 +bytes 147364 circle 16 line 832 path 68 -polygon 249 +polygon 257 rect 1 svg 1 text 121 -hash 51b01852d2618ab4 +hash 45e68ce965a49c5d diff --git a/src/plan/__golden__/komplex-grundriss-eg-50.txt b/src/plan/__golden__/komplex-grundriss-eg-50.txt index fc83cfe3..d8369cef 100644 --- a/src/plan/__golden__/komplex-grundriss-eg-50.txt +++ b/src/plan/__golden__/komplex-grundriss-eg-50.txt @@ -1,10 +1,10 @@ viewBox -41.5 0 95 63.6 -bytes 146660 +bytes 147796 circle 16 line 832 path 68 -polygon 249 +polygon 257 rect 1 svg 1 text 121 -hash d9e3d1d506de326b +hash dea353f151ea1cc1 diff --git a/src/plan/pickLabels.ts b/src/plan/pickLabels.ts index 1f050e22..cc28cc9f 100644 --- a/src/plan/pickLabels.ts +++ b/src/plan/pickLabels.ts @@ -8,7 +8,7 @@ import { flattenCategories } from "../model/types"; /** Art eines auswählbaren Objekts an einer Klickstelle (Reihenfolge = Standard-Priorität). */ export type PickKind = | "section" | "opening" | "wall" | "column" | "drawing" | "solid" - | "ceiling" | "stair" | "room" | "roof" | "context"; + | "ceiling" | "stair" | "room" | "roof" | "site" | "context"; type WithCategory = { id: string; categoryCode?: string }; @@ -25,7 +25,8 @@ function collection(project: Project, kind: PickKind): readonly WithCategory[] { case "column": return p.columns ?? []; case "context": return p.context ?? []; case "solid": return p.extrudedSolids ?? []; - case "section": return []; + case "section": + case "site": return []; } } diff --git a/src/plan/pickTypes.ts b/src/plan/pickTypes.ts index ebdb3da5..c50e1e46 100644 --- a/src/plan/pickTypes.ts +++ b/src/plan/pickTypes.ts @@ -96,3 +96,9 @@ export interface PickContextMesh { tris: ReadonlyArray; contextObjectId: string; } + +/** [137] Stütze für den Raycast: WORLD-Dreiecke ihres Prismas (Konvention wie {@link PickContextMesh}). */ +export interface PickColumnMesh { + tris: ReadonlyArray; + columnId: string; +} diff --git a/src/plan/toWalls3d.ts b/src/plan/toWalls3d.ts index ca859ae3..37436933 100644 --- a/src/plan/toWalls3d.ts +++ b/src/plan/toWalls3d.ts @@ -44,7 +44,7 @@ import type { Project, Vec2 } from "../model/types"; import type { DetailLevel } from "../model/viewTypes"; import { documentFor } from "../core/document"; import { coreEpoch } from "../engine/coreWasm"; -import type { PickOpening, PickRoof, PickStair, PickContextMesh, PickDrawingSeg } from "./pickTypes"; +import type { PickOpening, PickRoof, PickStair, PickContextMesh, PickColumnMesh, PickDrawingSeg } from "./pickTypes"; import { type RMesh, type RModel3d, @@ -328,6 +328,7 @@ export function pickGeometry( stairs: PickStair[]; roofs: PickRoof[]; contextMeshes: PickContextMesh[]; + columns: PickColumnMesh[]; drawings: PickDrawingSeg[]; } { return documentFor(project).query("pickGeometry", [explodeGap(explode)]); diff --git a/src/state/selection.ts b/src/state/selection.ts index f07352dd..f4cdd0f0 100644 --- a/src/state/selection.ts +++ b/src/state/selection.ts @@ -32,6 +32,11 @@ export interface Selection { contextObjects: string[]; /** Schnitt-/Ansichtslinien (DrawingLevel-Ids). */ sectionLines: string[]; + /** + * [137] Abgeleitete Lage-Darstellung (kein Modellelement): `"sunStudy"` (Schattenfläche angeklickt) + * bzw. `"siteRules"` (Baurechtslinie) — die Objekt-Info zeigt die Einstellungen der Quelle. + */ + site: string[]; /** * Gewählte Gruppen — rein informativ (Bounding-Box, Doppelklick-Ziel); die * Mitglieder stehen zusätzlich in den übrigen Arten (s. `groupActions.ts`). @@ -54,6 +59,7 @@ export const SELECTION_KINDS: readonly SelectionKind[] = [ "roofs", "contextObjects", "sectionLines", + "site", "groups", ]; diff --git a/src/state/siteSelection.test.ts b/src/state/siteSelection.test.ts new file mode 100644 index 00000000..91d7d2b2 --- /dev/null +++ b/src/state/siteSelection.test.ts @@ -0,0 +1,80 @@ +// [137] Alles Sichtbare anwählbar (Musterhaus komplex): Klick im Grundriss auf Baugrube, Gelände, +// Schatten und Baurechtslinien; Objekt-Info der Baugrube; Gelände neu glätten mit Undo. + +import { beforeAll, describe, expect, it } from "vitest"; +import { buildComplexSampleProject } from "../model/sampleProjectComplex"; +import { collectVisibleCodes } from "../model/layers"; +import { generatePlan } from "../plan/generatePlan"; +import { PlanPickIndex } from "../plan/planView/planPick"; +import { planPrimAt } from "../plan/planLazy"; +import { deriveSelection } from "./selectionInfo"; +import { getState, setState } from "./appStore"; +import type { Project, TerrainMesh } from "../model/types"; + +let p: Project; +let terrainId: string; +beforeAll(() => { + p = buildComplexSampleProject(); + terrainId = p.context!.find((c) => c.type === "terrainMesh")!.id; +}); + +/** Pick-Ids (Feld `contextObjectId`) unter (x, y) im EG 1:500, oberste zuerst — wie `PlanView.contextIdsAt`. */ +const idsAt = (proj: Project, pts: [number, number][]): string[][] => { + const plan = generatePlan(proj, "eg", collectVisibleCodes(proj.layers), undefined, "mittel", false, false, true, 500); + const ix = new PlanPickIndex(plan); + const out = pts.map(([x, y]) => ix.polygonsAt({ x, y }, "contextObjectId").map((i) => (planPrimAt(plan, i) as { contextObjectId?: string }).contextObjectId!)); + ix.release(); + return out; +}; +/** Erstes Kontext-Objekt (ohne Lage-Darstellung `@…`). */ +const contextAt = (proj: Project, x: number, y: number): string | null => idsAt(proj, [[x, y]])[0].find((id) => !id.startsWith("@")) ?? null; + +describe("[137] Grundriss: Kontext anwählen", () => { + it("Baugrube (Sohle und Böschung) vor dem Gelände, daneben das Gelände", () => { + expect(contextAt(p, 8, -0.5)).toBe("baugrube"); + // Südwest-Böschung: ausserhalb der Sohle (Arbeitsraum 0.8 m um −0.36), noch im Wirkbereich. + expect(contextAt(p, -1.6, 4)).toBe("baugrube"); + expect(contextAt(p, 25, -10)).toBe(terrainId); + }); + + it("Objekt-Info der Baugrube: Kontext-Objekt der Art Baugrube", () => { + const sel = deriveSelection(p, { contextObjects: ["baugrube"] }); + expect(sel?.kind).toBe("contextObject"); + expect(sel?.contextObject?.objType).toBe("excavation"); + }); +}); + +describe("[137] Schatten und Baurecht anwählen", () => { + it("Parzellengrenze → Baurecht, Schattenfläche → Sonnenstand (Pick-Ids im Plan)", () => { + // Westgrenze der Parzelle von (−14, −12) nach (−15, 24): bei y = 6 liegt sie auf x = −14.5. + const grid: [number, number][] = []; + for (let y = 22; y >= -4; y -= 1) for (let x = -10; x <= 26; x += 1) grid.push([x, y]); + const [parcel, far, ...rest] = idsAt(p, [[-14.5, 6], [-40, -40], ...grid]); + expect(parcel).toContain("@siteRules"); + expect(far).toEqual([]); + // Schatten (21. Juni, 10 Uhr): irgendwo neben dem Haus. + expect(rest.some((ids) => ids.includes("@sunStudy"))).toBe(true); + // Studie aus: keine Schatten-Ids mehr. + const off = idsAt({ ...p, sunStudy: { ...p.sunStudy!, show: false } }, grid); + expect(off.some((ids) => ids.includes("@sunStudy"))).toBe(false); + }); +}); + +describe("[137] Gelände neu glätten", () => { + it("andere Stufe ersetzt das Netz (gleiche Id), Undo stellt es wieder her", () => { + const terrain = () => getState().project.context!.find((c) => c.id === terrainId) as TerrainMesh; + setState({ project: p, undoDepth: 0, redoDepth: 0, canUndo: false, canRedo: false }); + getState().clearHistory(); + const before = terrain(); + expect(before.smooth).toBe(2); + expect(before.sourceId).toBe("hoehenlinien"); + expect(getState().regenerateTerrain(terrainId, 0)).toBe(true); + const raw = terrain(); + expect(raw.smooth).toBe(0); + expect(raw.indices.length).toBeLessThan(before.indices.length); + expect(raw.contourInterval).toBe(before.contourInterval); + getState().undo(); + expect(terrain().indices.length).toBe(before.indices.length); + expect(terrain().smooth).toBe(2); + }); +}); diff --git a/src/state/siteSlice.ts b/src/state/siteSlice.ts index fd332646..3cb12c2f 100644 --- a/src/state/siteSlice.ts +++ b/src/state/siteSlice.ts @@ -35,6 +35,12 @@ export interface SiteSlice { generateTerrain: (contourSetId: string, opts?: TerrainOptions) => string | null; /** [T6]/[68] Ändert Felder eines Kontext-Objekts (Gelände, Baugrube) in einem Schritt; `coalesceKey` für Tippen. */ patchContextObject: (id: string, patch: Record, coalesceKey?: string) => void; + /** + * [137] Gelände `terrainId` aus seinen Höhenlinien (`sourceId`, sonst dem ersten Höhenlinien-Satz) mit + * Glättungsstufe `smooth` (0 = roh) neu erzeugen — gleiche Id und Einstellungen, ein Undo-Schritt. + * `false`, wenn es keine Quelle gibt oder kein Netz entsteht. + */ + regenerateTerrain: (terrainId: string, smooth: number) => boolean; /** Leert die gesamte Kontext-Schicht. */ clearContext: () => void; } @@ -94,10 +100,25 @@ export function createSiteSlice( if (!set || set.type !== "contourSet") return null; const terrain = generateTerrainFromContours(set.contours, opts); if (terrain.indices.length === 0) return null; // kein sinnvolles TIN - addToContext([terrain]); + addToContext([{ ...terrain, sourceId: set.id }]); return terrain.id; }, + regenerateTerrain: (terrainId, smooth) => { + const ctx = get().project.context ?? []; + const terrain = ctx.find((o) => o.id === terrainId && o.type === "terrainMesh"); + if (!terrain || terrain.type !== "terrainMesh") return false; + const sets = ctx.filter((o) => o.type === "contourSet"); + const set = sets.find((o) => o.id === terrain.sourceId) ?? sets[0]; + if (!set || set.type !== "contourSet") return false; + const fresh = generateTerrainFromContours(set.contours, { smooth }); + if (fresh.indices.length === 0) return false; + get().applyChange((p) => + patchItem(p, "context", terrainId, (o) => ({ ...o, positions: fresh.positions, indices: fresh.indices, smooth, sourceId: set.id }) as ContextObject), + ); + return true; + }, + clearContext: () => get().applyChange((p) => fieldOps(p, "context", [])), }; } diff --git a/src/state/useMouseSelectionHandlers.ts b/src/state/useMouseSelectionHandlers.ts index 5c24dea6..a73e6089 100644 --- a/src/state/useMouseSelectionHandlers.ts +++ b/src/state/useMouseSelectionHandlers.ts @@ -206,6 +206,7 @@ export function useMouseSelectionHandlers(opts: { column: "columns", roof: "roofs", context: "contextObjects", + site: "site", } as const satisfies Record; type Kind = keyof typeof channels; const target: { kind: Kind; id: string } | null = sel.sectionLineId @@ -286,7 +287,9 @@ export function useMouseSelectionHandlers(opts: { ? ["roofs", sel.roofId] : sel.contextObjectId ? ["contextObjects", sel.contextObjectId] - : null; + : sel.siteId + ? ["site", sel.siteId] + : null; setSelection({ ...clearKinds(), groups: [], ...(one ? { [one[0]]: [one[1]] } : {}) }); }; // Links-Drag (Marquee) im Grundriss: die getroffene Wand-MENGE übernehmen @@ -380,6 +383,10 @@ export function useMouseSelectionHandlers(opts: { setSelection({ ...clearKinds(), stairs: [hit.id] }); return; } + if (hit.kind === "column") { + setSelection({ ...clearKinds(), columns: [hit.id] }); + return; + } if (hit.kind === "roof") { // Schnittlinien bleiben hier (wie bisher) gewählt. setSelection({ ...clearKinds(...ELEMENT_KINDS.filter((k) => k !== "sectionLines")), roofs: [hit.id] }); diff --git a/src/viewport/Wasm3DViewport.tsx b/src/viewport/Wasm3DViewport.tsx index 040ae7e9..d366cd19 100644 --- a/src/viewport/Wasm3DViewport.tsx +++ b/src/viewport/Wasm3DViewport.tsx @@ -81,7 +81,7 @@ import { /** Ein per 3D-Klick getroffenes Bauteil, oder null (Leerraum). */ export type Pick3dHit = - | { kind: "wall" | "ceiling" | "opening" | "stair" | "roof" | "contextObject" | "drawing"; id: string } + | { kind: "wall" | "ceiling" | "opening" | "stair" | "roof" | "contextObject" | "drawing" | "column"; id: string } | null; /** Klick-vs-Drag-Schwelle (Pixel): bleibt die Maus zwischen pointerdown und @@ -1406,7 +1406,7 @@ export function Wasm3DViewport({ const ndc = toNdc(clientX, clientY); if (!cb || !o || !ndc) return; const ray = cameraRay(orbitCamera(o), ndc.ndcX, ndc.ndcY, ndc.aspect); - const { walls, slabs, openings, stairs, roofs, contextMeshes, drawings } = pickGeometry( + const { walls, slabs, openings, stairs, roofs, contextMeshes, drawings, columns } = pickGeometry( projectRef.current, explodeRef.current, ); @@ -1414,7 +1414,7 @@ export function Wasm3DViewport({ // Meshes + freie 2D-Zeichnungen (Linie/Polylinie/Rechteck, s. // `pickDrawingSegs`) — sonst wären im WASM-Viewport 2D-Elemente NIE // anwählbar gewesen (Nutzer-Report). - const hit = pickNearest(ray, walls, slabs, openings, stairs, roofs, contextMeshes, drawings); + const hit = pickNearest(ray, walls, slabs, openings, stairs, roofs, contextMeshes, drawings, columns); cb(hit ? { kind: hit.kind, id: hit.id } : null, additive); }; diff --git a/src/viewport/raycast3d.ts b/src/viewport/raycast3d.ts index 465b86e4..bda0df8f 100644 --- a/src/viewport/raycast3d.ts +++ b/src/viewport/raycast3d.ts @@ -18,7 +18,7 @@ import { DRAWING_PICK_TOLERANCE } from "../core"; -import type { Vec3, PickWall, PickOpening, PickDrawingSeg, PickSlab, PickStair, PickRoof, PickContextMesh } from "../core"; +import type { Vec3, PickWall, PickOpening, PickDrawingSeg, PickSlab, PickStair, PickRoof, PickContextMesh, PickColumnMesh } from "../core"; /** Kamera-Parameter für den Pick-Strahl (Teilmenge von Camera3d). */ export interface RayCamera { @@ -42,7 +42,7 @@ export interface Ray { /** Ergebnis eines Picks: getroffenes Bauteil + Distanz entlang des Strahls. */ export interface PickHit { - kind: "wall" | "ceiling" | "opening" | "stair" | "roof" | "contextObject" | "drawing"; + kind: "wall" | "ceiling" | "opening" | "stair" | "roof" | "contextObject" | "drawing" | "column"; id: string; t: number; /** Bei `kind:"opening"` dieselbe Id wie `id` (ausdrucksstärkerer Zugriff). */ @@ -357,6 +357,7 @@ export function pickNearest( roofs?: readonly PickRoof[], contextMeshes?: readonly PickContextMesh[], drawings?: readonly PickDrawingSeg[], + columns?: readonly PickColumnMesh[], ): PickHit | null; /** * Nächstes getroffenes Bauteil (kleinstes t) über Wände, Decken, Öffnungen und @@ -376,6 +377,7 @@ export function pickNearest( roofs: readonly PickRoof[] = [], contextMeshes: readonly PickContextMesh[] = [], drawings: readonly PickDrawingSeg[] = [], + columns: readonly PickColumnMesh[] = [], ): PickHit | null { const TIE_EPS = 1e-6; let hit: PickHit | null = null; @@ -426,6 +428,11 @@ export function pickNearest( consider({ kind: "contextObject", id: m.contextObjectId, t, contextObjectId: m.contextObjectId }, 1); } } + // [137] Stützen: Prisma-Dreiecke, Rang wie Wand/Decke. + for (const c of columns) { + const t = rayContextMeshTris(ray, { tris: c.tris, contextObjectId: c.columnId }); + if (t !== null) consider({ kind: "column", id: c.columnId, t }, 1); + } return hit; } diff --git a/src/views/plan/PlanView.tsx b/src/views/plan/PlanView.tsx index a12b1b2e..5999c6fe 100644 --- a/src/views/plan/PlanView.tsx +++ b/src/views/plan/PlanView.tsx @@ -189,7 +189,7 @@ export interface PlanViewHandle { const PICK_ORDER: readonly PickKind[] = [ "section", "opening", "wall", "column", "drawing", "solid", - "ceiling", "stair", "room", "roof", "context", + "ceiling", "stair", "room", "roof", "site", "context", ]; /** Ein Objekt unter dem Cursor — für das Durchschalten übereinanderliegender Objekte. */ @@ -218,6 +218,7 @@ const EMPTY_PICK: PickIds = { roofId: null, sectionLineId: null, contextObjectId: null, + siteId: null, }; /** Mac: Cmd+Klick; sonst Strg+Klick (Alt+Klick ist die Schere, Ctrl+Klick unter macOS das Kontextmenü). */ @@ -292,6 +293,11 @@ export interface PlanSelection { * (alle anderen gehen vor, analog `roofId`); sonst `null`. */ contextObjectId: string | null; + /** + * [137] Getroffene Lage-Darstellung (Schattenfläche → `"sunStudy"`, Baurechtslinie → `"siteRules"`), + * wenn kein Element höherer Priorität getroffen wurde; Vorrang vor Kontext-Objekten (sie liegt darüber). + */ + siteId?: string | null; /** * War beim Klick Shift gedrückt? Dann ERWEITERT der Aufrufer (App) die * Auswahl um das getroffene Element (bzw. schaltet es ab/zu), statt sie zu @@ -675,6 +681,7 @@ export const PlanView = forwardRef( columns: selectedColumnIds, groups: selectedGroupIds, drawings: selectedDrawingIds, + site: selectedSite, } = selection; const selectedDrawingId = single(selection, "drawings"); // Linke Maustaste liegt beim Werkzeug/der Transformation, wenn App das meldet @@ -1407,9 +1414,27 @@ export const PlanView = forwardRef( // Trefferprüfung: liefert den Index des obersten Polygon-Primitivs unter dem // Cursor (Modellpunkt in einem Schicht-Polygon) oder null. In umgekehrter // Reihenfolge testen, damit das zuletzt gezeichnete (oberste) zuerst trifft. + // [137] Übersprungen werden Flächen ohne Bauteil: Darstellung ohne Id (Schlagschatten der Ansicht, + // Baurechts-Verstösse, Muster) und unsichtbare Pick-Bänder (Gelände-Rahmen, Baugrube, Schatten, Schnittlinie) + // — sie lagen sonst über Wänden und Decken und machten diese unwählbar. Eine sichtbare Kontext-Fläche + // (Gelände in der Ansicht) verdeckt dagegen wie bisher. const hitTest = (clientX: number, clientY: number): number | null => { const v = clientToView(clientX, clientY, view); - return getPick().topPolygon(viewToModel(v.x, v.y)); + // Unter einem Gelände-/Baugruben-Band zählt die leere Innenfläche einer 2D-Kontur (z. B. Parzelle) nicht: + // dort meint der Klick das Gelände (die Kontur bleibt über ihre Linie wählbar) — wie vor [137]. + const pick = getPick(); + let underBand = false; + for (const i of pick.polygonsAt(viewToModel(v.x, v.y))) { + const p = pick.prim(i); + if (p?.kind !== "polygon") continue; + if (p.wallId || p.drawingId || p.ceilingId || p.openingId || p.stairId || p.roomId || p.extrudedSolidId || p.columnId || p.roofId) { + const emptyArea = p.drawingId && p.fill === "none" && (!p.hatch || p.hatch.pattern === "none"); + return underBand && emptyArea ? null : i; + } + if ((p.contextObjectId || p.sectionLineId) && p.fill !== "none") return i; + if (p.contextObjectId && !p.contextObjectId.startsWith("@")) underBand = true; + } + return null; }; // Irgendein Element (Wand/Decke/Raum/Treppe/Stütze/Dach/2D) unter dem @@ -1565,12 +1590,24 @@ export const PlanView = forwardRef( // Grundriss-Pick-Band (Bounding-Box) per Punkt-in-Polygon — macht es wie eine // Wand irgendwo innerhalb seiner Fläche anklickbar, nicht nur exakt auf der // dünnen Umrisslinie. - const pickContextObject = (clientX: number, clientY: number): string | null => { + // Pick-Ids unter dem Cursor im Feld `contextObjectId`, oberste zuerst. Die abgeleitete Lage-Darstellung + // ([137], Kern `plan/extras.rs`) trägt dort `@sunStudy`/`@siteRules` (Schattenflächen, Baurechts-Bänder). + const contextIdsAt = (clientX: number, clientY: number): string[] => { const v = clientToView(clientX, clientY, view); - const i = getPick().topPolygon(viewToModel(v.x, v.y), "contextObjectId"); - return i === null ? null : (planPrimAt(plan, i) as { contextObjectId?: string }).contextObjectId!; + const pick = getPick(); + return pick.polygonsAt(viewToModel(v.x, v.y), "contextObjectId").map((i) => (pick.prim(i) as { contextObjectId?: string }).contextObjectId!); }; + // [137] Getroffene Lage-Darstellung: Quelle `"sunStudy"`/`"siteRules"` (Baurechtslinie vor Schatten) oder null. + const pickSiteAt = (clientX: number, clientY: number): string | null => { + const ids = contextIdsAt(clientX, clientY).filter((id) => id.startsWith("@")); + const id = ids.find((x) => x === "@siteRules") ?? ids[0]; + return id ? id.slice(1) : null; + }; + + const pickContextObject = (clientX: number, clientY: number): string | null => + contextIdsAt(clientX, clientY).find((id) => !id.startsWith("@")) ?? null; + // Getroffener extrudierter Körper (truck-Integration): der Footprint-Umriss // ist ein reiner Haarlinien-Umriss (fill:"none"), aber per Punkt-in-Polygon // trotzdem als FLÄCHE anklickbar (analog Raum, nicht nur auf der Linie). @@ -2119,8 +2156,13 @@ export const PlanView = forwardRef( // Kontext-Objekt (Gebäude/Terrain) als ALLERLETZTE Priorität — seine // Bbox-Pick-Fläche kann grosszügig überlappen, daher erst wenn wirklich // nichts anderes getroffen wurde. - const contextObjectId = + // [137] Schatten/Baurechtslinien (Lage-Darstellung) über dem Gelände, unter allen Bauteilen. + const siteId = openingId || wallId || columnId || drawingId || extrudedSolidId || ceilingId || stairId || roomId || roofId + ? null + : pickSiteAt(clientX, clientY); + const contextObjectId = + openingId || wallId || columnId || drawingId || extrudedSolidId || ceilingId || stairId || roomId || roofId || siteId ? null : pickContextObject(clientX, clientY); return { @@ -2136,6 +2178,7 @@ export const PlanView = forwardRef( roofId, sectionLineId: null, contextObjectId, + siteId, }; }; @@ -2236,7 +2279,7 @@ export const PlanView = forwardRef( const key = `${kind}:${id}`; if (seen.has(key)) return; seen.add(key); - const base = kind === "drawing" ? drawingLabel(id) : t(`pick.kind.${kind}`); + const base = kind === "drawing" ? drawingLabel(id) : kind === "site" ? t(id === "siteRules" ? "pick.site.siteRules" : "pick.site.sunStudy") : t(`pick.kind.${kind}`); const cat = describePick?.(kind, id); out.push({ kind, id, hitIndex, label: cat ? `${base} · ${cat}` : base }); }; @@ -2251,6 +2294,7 @@ export const PlanView = forwardRef( add("stair", dp.stairId, dp.hitIndex); add("room", dp.roomId, dp.hitIndex); add("roof", dp.roofId, dp.hitIndex); + add("site", dp.siteId, dp.hitIndex); add("context", dp.contextObjectId, dp.hitIndex); const first = out.slice(); // 2) Alles Übrige an dieser Stelle, nach Standard-Priorität sortiert. @@ -2272,7 +2316,8 @@ export const PlanView = forwardRef( addRest("stair", p.stairId, idx); addRest("room", p.roomId, idx); addRest("roof", p.roofId, idx); - addRest("context", p.contextObjectId, idx); + if (p.contextObjectId?.startsWith("@")) addRest("site", p.contextObjectId.slice(1), idx); + else addRest("context", p.contextObjectId, idx); addRest("section", p.sectionLineId, idx); } for (const id of nearDrawingIds(clientX, clientY)) addRest("drawing", id, null); @@ -2282,6 +2327,7 @@ export const PlanView = forwardRef( addRest("stair", pickStair(clientX, clientY), null); addRest("room", pickRoom(clientX, clientY), null); addRest("roof", pickRoof(clientX, clientY), null); + addRest("site", pickSiteAt(clientX, clientY), null); addRest("context", pickContextObject(clientX, clientY), null); addRest("section", pickSectionLine(clientX, clientY), null); // Stabil nach Standard-Priorität ordnen (innerhalb einer Art bleibt die Fundreihenfolge). @@ -2317,6 +2363,7 @@ export const PlanView = forwardRef( roofId: c.kind === "roof" ? c.id : null, sectionLineId: c.kind === "section" ? c.id : null, contextObjectId: c.kind === "context" ? c.id : null, + siteId: c.kind === "site" ? c.id : null, }); }; @@ -2794,14 +2841,12 @@ export const PlanView = forwardRef( // Hervorhebung der selektierten Kontext-Objekte (Gebäude/Terrain): das // (unsichtbare) Bbox-Pick-Band mit contextObjectId als Akzentkontur // überzeichnen — analog zur Dach-/Raum-Auswahl. + // [137] Gewählte Lage-Darstellung (Schatten/Baurecht): ihre Flächen bzw. Bänder (`@…`-Ids) ebenso. const highlightContextObjectPolys = useMemo(() => { - const ids = - selectedContextObjectIds && selectedContextObjectIds.length - ? new Set(selectedContextObjectIds) - : null; - if (!ids) return []; - return primsOwnedBy("contextObjectId", selectedContextObjectIds, (p): p is Extract => p.kind === "polygon"); - }, [plan, selectedContextObjectIds]); + const ids = [...(selectedContextObjectIds ?? []), ...(selectedSite ?? []).map((s) => "@" + s)]; + if (!ids.length) return []; + return primsOwnedBy("contextObjectId", ids, (p): p is Extract => p.kind === "polygon"); + }, [plan, selectedContextObjectIds, selectedSite]); // Hervorhebung der selektierten Schnitt-/Ansichtslinie: das (unsichtbare) // Pick-Band (Polygon mit sectionLineId) mit Akzentkontur überzeichnen. @@ -2838,7 +2883,8 @@ export const PlanView = forwardRef( // Primitive des per Listen-Hover vorgemerkten Objekts (Vorschau-Hervorhebung). const hoverPrims = useMemo((): Primitive[] => { if (!hoverPick) return []; - const field: Record = { + if (hoverPick.kind === "site") return primsOwnedBy("contextObjectId", ["@" + hoverPick.id], (_p): _p is Primitive => true); + const field: Record, OwnerField> = { wall: "wallId", drawing: "drawingId", ceiling: "ceilingId", opening: "openingId", stair: "stairId", room: "roomId", roof: "roofId", context: "contextObjectId", section: "sectionLineId", solid: "extrudedSolidId", column: "columnId", diff --git a/src/views/viewportContent.tsx b/src/views/viewportContent.tsx index d1e947a2..a74eccfa 100644 --- a/src/views/viewportContent.tsx +++ b/src/views/viewportContent.tsx @@ -828,6 +828,7 @@ function LevelPlanView({ [project], ); + // Live-Spiegelung in die nativen wgpu-Fenster (No-op ohne Tauri, debounced): // EXAKT der sichtbare Plan (gleiches Geschoss, gleicher Detailgrad) fürs // 2D-Fenster, die Projekt-Wände fürs 3D-Fenster.