Merge origin/master

This commit is contained in:
Claude committed 2026-10-30 08:15:43 +00:00
commit 62b2619f79
42 files changed
+2950 -83

No files matched your search

+39 -2
View File
@@ -1356,7 +1356,26 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
- ◐ **[T3] Wendeltreppe/Wendelfläche** + Handlauf-Sweep. · M — 30.10.: Ortbeton-Wendeltreppe mit echter Wendelfläche (Schraubenuntersicht, ebene Tritte, `stairs3d::spiral_mesh`), Handlauf als Schraubensweep samt Pfosten (links/rechts/beide nach Drehsinn), Mittelsäule `Stair.centerColumn` (Radius, Objekt-Info; als Block in 3D/Schnitt). Tests Rust (Volumen, Punkte auf der Schraube, Sweep-Radius, Säule). Plansymbol (Bögen, Schnittlinie, Pfeil) war schon da und im CLI-SVG geprüft; nicht in der Tauri-App. Offen: Säule im Grundriss, IFC/Mengen der Wendelfläche, Handlauf-Profil rund.
- ○ **[T4] Import-Meshes glätten oder kantig** (`add_smooth_normals`). · S — Stand 30.10.: nicht begonnen. Braucht Renderer-Änderung (`render3d::append_context_mesh` rechnet nur Flächennormalen) + Feld an `ImportedMesh`/`RMesh`/`MeshInput` + WASM/Metal-Neubau; Verschweissen ([T5]) als Voraussetzung ist da.
- ✅ **[T5] Import reparieren** (`put_together_same_attrs`, Healing). · S — 30.10.: `mesh_repair.rs` im Mesh-Import (`decode_mesh`): Ecken verschweissen (0.01 mm), entartete Dreiecke entfernen, Löcher bis 8 Randkanten in fast geschlossenen Netzen (Randanteil ≤ 5 %) per Fächer schliessen, Orientierung nach aussen; Zähler im Importbericht (`repaired`, Meldung). Tests Rust (Suppe, Entartete, Loch/Orientierung, offene Fläche bleibt, Bericht). Gilt für OBJ/STL/glTF/PLY, nicht für IFC/DXF/STEP. Nicht in der App getestet. Offen: Verschweissen über Zellgrenzen, Schalter/Schwellen im Import-Dialog, Normalen-Ausrichtung widersprüchlich orientierter Flächen.
- ○ **[T6] Glattes Gelände aus Höhenlinien** + Gelände-Prisma für Aushub (= [68]). · L
- ◐ **[T6] Glattes Gelände aus Höhenlinien** + Gelände-Prisma für Aushub (= [68]). (30.10.) Kern `terrain.rs`:
Konturen verdichtet und als Bruchkanten erzwungen (constrained Delaunay: Sloan-Kantentausch auf `delaunay.rs`,
danach Lawson nur an freien Kanten; konkave Ränder: lange Randsplitter weg), flache Dreiecke (Kuppen/Mulden/
Talböden) mit Schwerpunkt aus Eckgradienten, begrenzt auf ±0.45·Äquidistanz (keine neuen Höhenlinien); Glättung
durch adaptive Kantenteilung (rissfrei 1→2/3/4) mit Hermite-Mittelpunkt aus 1-Ring-Gradienten, ohne Überschwingen
(Mittelpunkt streng zwischen den Endhöhen, Kontur-Kanten exakt). Optionen `smooth`/`maxEdge`/`breaklines`
(`terrain_from_contours_opts_json`, Panel „Glätten"); Befehl `terrain` und Panel nutzen es (Standard: 2 Stufen).
Neue Felder `TerrainMesh.contourInterval`/`contourIndexEvery`: Grundriss zeichnet Höhenlinien aus dem Netz
(samt Baugruben) neu, Zähllinien dicker und beschriftet (2 mm Papier, lesbar gedreht); Rahmen wie bisher.
Schnitt: gestaltetes Terrain (Baugruben) ausgezogen, gewachsenes gestrichelt, SIA-Erdreich-Band 1.5 m darunter
([109] `std-h-erdreich`) ohne Gebäude-Inneres; Grundlinie entfällt mit Gelände. Ansicht: Silhouette des Geländes
vor dem Gebäude (obere Hüllkurve), darunter verdeckt (Papierfläche). 3D/Export/Pick: geändertes Netz. Höhenbezug:
ist `referenceElevationMasl` gesetzt und liegt das Gelände in m ü. M., gilt Modell = roh − Referenz (3D, Schnitt,
Baurecht; Höhenlinien-Beschriftung roh). Gelände-Prisma (`terrain::prism`, dicht, Volumen per Divergenzsatz).
Tests: Rust (Bruchkanten, Kegelhügel ohne Überschwingen/flache Dreiecke, Prisma dicht, Unsinn), vitest.
Geprüft im Linux-Container (CLI-Grundriss/-Schnitt/-Ansicht eines Hügels mit Baugrube angesehen; Erdreich-Schraffur
über den Kern-Generator gerendert, das CLI-SVG zeigt keine Schraffuren), nicht in der Tauri-App.
Offen: swissALTI3D-Raster wird nicht geglättet (nur Äquidistanz 1 m gesetzt); Natural-Neighbour/Clough-Tocher statt
Hermite-Teilung; Höhenlinien unter der Beschriftung nicht unterbrochen; Luftbild-Farben fallen auf geändertem
Gelände weg; Erdreich-Band fest 1.5 m (nicht bis zur Planunterkante). · L
- ✅ **[T7] Rotationskörper/Loft im UI** (API besteht). · S–M — 30.10.: Befehle `revolve` (Profil + Achse aus 2 Plan-Punkten + Winkel; Achse waagrecht auf Höhe r_max, Profil auf einer Seite) und `loft` (≥ 2 Profile der Reihe nach, gleichmässig über die Höhe; Punktzahl durch Kantenteilung angeglichen) in `cmd_solid.rs`/`cmds/{revolve,loft}.ts`, Körper als `ExtrudedSolid.brep` (Objekt-Info, STEP, Kennwerte wie die Grundkörper); Kürzel `rev`/`lf`, Werkzeugpalette 3D. Tests Rust (Spezifikation, Ops, truck-Volumen/STEP), vitest (Befehlsablauf). Nicht in der Tauri-App getestet. Offen: Achse senkrecht/beliebig im Raum, Loft mit Führungskurve, Profil-Startpunkt-Ausrichtung beim Loft.
- ✅ **[T8] Kollisionsprüfung im 3D zeigen** (heute nur Marker im Grundriss). · S — 30.10.: Treffer in Sitzung (`panels/clashSession.ts`), Panel „Kollisionen" (`ClashPanel`: Liste, Klick wählt beide Bauteile und fährt die 3D-Kamera auf die Durchdringung, `cameraBridge.focusCamera`), im 3D rote Hüllquader aller Treffer (`clashHighlightLines` in `viewportContent`); Prüflauf öffnet das Panel, Marker im Grundriss bleiben. Tests vitest (Linien, Auswahl, Kamera-Fokus). Nicht im echten WebGPU-Viewport/Tauri geprüft. Offen: Hüllquader statt exakter Durchdringungsgeometrie, Panel-Name zeigt Ids statt Bauteilnamen, Wiederholung/Ignorieren einzelner Treffer.
@@ -1824,12 +1843,30 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
## Priorität 4 — später
Alle ○: [27] Punktwolken (Leser ✅ [B9], Anzeige ◐ s. u., Modell offen) · [28] Phasen · [29] Bauteillisten (◐, Export vorhanden; Fenster-/Türliste ✅ [97]) · [43] Verknüpfte
Modelle · [44] Aus Datei einfügen · [45] Favoriten · [68] Gelände mit Baugrube (= [T6]) · [71] U-Werte (✅ s. u.) ·
Modelle · [44] Aus Datei einfügen · [45] Favoriten · [68] Gelände mit Baugrube (◐ s. u.) · [71] U-Werte (✅ s. u.) ·
[72] Graue Energie KBOB · [73] eBKP-H · [74] SIA 500 · [75] Fluchtwege VKF · [83] Befehlspalette ·
[85] Makro-Rekorder · [86] Pipette · [87] Fang mit Begründung · [48] Web-Worker
(◐, DXF-Parser, IFC-Import) · [52] Icons (◐, `CommandIcon.tsx`) · [56] Startparameter · [89] Git-freundliches
Format · [90] Versionsvergleich · [91] Assistent · [92] Speckle.
- ◐ **[68] Baugrube / Geländebearbeitung.** (30.10.) Kontext-Objekt `excavation` (Rust-Modell, `ContextObject`):
Sohle (`outline`, `bottom` m ±0.00), Böschung `slope` (Standard 45°, je Kante `edgeSlopes`), Schüttung `fillSlope`
(33.7°), Bermen `bermWidth`/`bermHeight`. Neues Gelände = clamp(t, b − d·tan β, b + H(d)) mit d = Abstand zum
Umriss (Ecken als Kegel) — dasselbe Element schneidet ein (Abtrag) und schüttet auf (Auftrag, Planie am Hang).
Kern `excavation.rs`: Netz im Wirkbereich neu trianguliert (Raster mit exakter Höhe, Sohle und Böschungsoberkante
als Bruchkanten, aussen Original-TIN samt Kanten), zwischengespeichert je Netz. Mengen (Abfrage
`excavationQuantities`): Abtrag/Auftrag als Integral der exakten Funktion (Raster-Mittelpunkte), Hinterfüllung =
Abtrag ausserhalb der Gebäude-Grundfläche; Test gegen die analytische Formel (10×10×3 m, 45°: 508.27 m³, < 0.2 %)
und gegen die Prisma-Differenz des Netzes (< 2 %). Grundriss: Sohle, Böschungsoberkante, Böschungsschraffur
(lang/halb, an Ecken gefächert); Schnitt/Ansicht/3D über das geänderte Gelände. Befehl `excavation`
(Alias baugrube/aushub; Sohle = Geschoss − 0.30 m), Panel „Gelände & Kontext" (Sohle, Neigungen, Bermen, Mengen),
Layout-Tabelle „Erdarbeiten" ([111], Quelle `earthworks`), CLI `kennzahlen` → `erdarbeiten`.
Baurecht ([63]): Geländehöhen an der Fassade (gewachsen/gestaltet, Ecken + alle ≤ 2 m), massgebendes Terrain =
tiefster gewachsener Punkt an der Fassade (vereinfacht), Gesamthöhe dagegen geprüft (ohne Gelände wie bisher ±0.00).
Offen: Mengen je Baugrube gegen das gewachsene Terrain (Überlagerungen doppelt); Arbeitsraum als Abstand;
senkrechter Verbau (Spundwand) nur als 89.5°-Böschung; Griffe/Objekt-Info für den Umriss; IVHB-Terrain nach
kantonalem Recht (Lotrechte statt tiefster Fassadenpunkt); nicht in der Tauri-App geprüft.
- ◐ **[107] Manifold für Körper-Booleans (Schritt 1: trucksolid).** (30.10.) `manifold-rust` `=0.19.1` (Apache-2.0,
exakter Modus) ersetzt den csgrs-Fallback in `src-tauri/trucksolid/src/boolean.rs`; csgrs, die Git-Abhängigkeit
und nalgebra sind entfernt, `NOTICE` ergänzt. Reihenfolge unverändert: truck-B-Rep zuerst (exakte Flächen/STEP),
+80 -30
View File
@@ -451,46 +451,70 @@ fn voidbox_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
/// Gelände-TIN aus Höhenlinien (`generateTerrainFromContours`): alle endlichen Stützpunkte, Delaunay
/// über (x, y), Höhe der Kontur je Punkt; Null-Flächen-Dreiecke verworfen.
pub fn terrain_from_contours(contours: &[Value], id: &str) -> Value {
let (mut xs, mut ys, mut zs) = (Vec::new(), Vec::new(), Vec::new());
for c in contours {
let z = num_of(field(c, "z"));
let z = if z.is_finite() { z } else { 0.0 };
for p in arr(field(c, "pts")) {
let (x, y) = xy(p);
if !x.is_finite() || !y.is_finite() {
continue;
terrain_from_contours_with(contours, id, crate::terrain::TerrainOpts::default())
}
/// Gelände aus Höhenlinien ([T6], `terrain.rs`): Konturen als Bruchkanten (constrained Delaunay),
/// flache Dreiecke behoben, adaptiv geglättet (ohne Überschwingen). Äquidistanz der Plan-Höhenlinien =
/// kleinster Höhenabstand der Konturen. Unter drei Punkten ein leeres Netz.
pub fn terrain_from_contours_with(contours: &[Value], id: &str, o: crate::terrain::TerrainOpts) -> Value {
let cs: Vec<crate::terrain::ContourIn> = contours
.iter()
.map(|c| {
let z = num_of(field(c, "z"));
crate::terrain::ContourIn {
z: if z.is_finite() { z } else { 0.0 },
pts: arr(field(c, "pts")).iter().map(xy).filter(|p| p.0.is_finite() && p.1.is_finite()).map(|p| [p.0, p.1]).collect(),
closed: truthy(field(c, "closed")),
}
xs.push(x);
ys.push(y);
zs.push(z);
}
}
if xs.len() < 3 {
})
.collect();
let t = crate::terrain::terrain_from_contours(&cs, &[], o);
if t.tris.is_empty() {
return json!({ "id": id, "type": "terrainMesh", "name": "Gelände", "categoryCode": "02", "positions": [], "indices": [] });
}
let coords: Vec<f64> = xs.iter().zip(&ys).flat_map(|(x, y)| [*x, *y]).collect();
let tri = crate::delaunay::triangulate(&coords);
let positions: Vec<Value> = (0..xs.len()).flat_map(|i| [js_num(xs[i]), js_num(ys[i]), js_num(zs[i])]).collect();
let mut indices = Vec::new();
for t in tri.chunks_exact(3) {
let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize);
let area2 = ((xs[b] - xs[a]) * (ys[c] - ys[a]) - (xs[c] - xs[a]) * (ys[b] - ys[a])).abs();
if area2 <= 1e-9 {
continue;
}
indices.extend([Value::from(t[0]), Value::from(t[1]), Value::from(t[2])]);
}
let (pos, idx) = t.to_flat(0.0);
let iv = crate::terrain::interval_of(&cs.iter().map(|c| c.z).collect::<Vec<_>>());
obj(vec![
("id", s(id)),
("type", s("terrainMesh")),
("name", s("Gelände")),
("layer", s("Terrain")),
("categoryCode", s("02")),
("positions", Value::Array(positions)),
("indices", Value::Array(indices)),
("positions", Value::Array(pos.into_iter().map(js_num).collect())),
("indices", Value::Array(idx.into_iter().map(Value::from).collect())),
("contourInterval", js_num(iv)),
])
}
/// [68] Baugrube aus dem gezeichneten Umriss (≥ 3 Punkte; 2 Punkte = Rechteck). Sohle = Geschoss-
/// Unterkante − 0.30 m (Magerbeton + Bodenplatte), Böschung 45°.
fn excavation_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
let mut pts: Vec<V> = pts_of(v, "pts").into_iter().filter(|p| p.0.is_finite() && p.1.is_finite()).collect();
if pts.len() == 2 {
pts = rect_corners(pts[0], pts[1]).to_vec();
}
let area2: f64 = (0..pts.len()).map(|i| pts[i].0 * pts[(i + 1) % pts.len()].1 - pts[(i + 1) % pts.len()].0 * pts[i].1).sum();
if pts.len() < 3 || area2.abs() < 0.02 {
return Vec::new();
}
let base = arr(root.get("floors")).iter().find(|f| field(f, "id").and_then(Value::as_str) == Some(ctx.level)).map_or(0.0, |f| num_or(field(f, "baseElevation"), 0.0));
let n = arr(root.get("context")).iter().filter(|o| field(o, "type").and_then(Value::as_str) == Some("excavation")).count();
add_op(
"context",
vec![obj(vec![
("id", s(&ids.next("excavation"))),
("type", s("excavation")),
("name", s(&format!("Baugrube {}", n + 1))),
("layer", s("Terrain")),
("categoryCode", s("02")),
("outline", pvs(&pts)),
("bottom", js_num(base - 0.3)),
("slope", js_num(crate::excavation::DEFAULT_SLOPE)),
])],
)
}
fn terrain_ops(root: &Map<String, Value>, ids: &mut IdGen) -> Vec<Op> {
let Some(set) = arr(root.get("context")).iter().find(|o| field(o, "type").and_then(Value::as_str) == Some("contourSet")) else {
return Vec::new();
@@ -750,6 +774,7 @@ pub fn ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) ->
"solidbool" => solidbool_ops(root, v, ids),
"voidbox" => voidbox_ops(v, ctx, ids),
"terrain" => terrain_ops(root, ids),
"excavation" => excavation_ops(root, v, ctx, ids),
"ceilingOpening" => ceiling_opening_ops(root, v, ctx),
"roofHole" => roof_hole_ops(root, v, ctx),
"roofWindow" => roof_window_ops(root, v, ctx, ids),
@@ -867,12 +892,37 @@ mod tests {
assert!(run("eg", 9.0).is_empty());
}
/// [68] Baugrube: Umriss (2 Punkte = Rechteck), Sohle = Geschoss − 0.30, als Kontext-Objekt.
#[test]
fn baugrube_befehl() {
let root = json!({"floors": [{"id": "ug", "baseElevation": -3.0}]});
let root = root.as_object().unwrap();
let run = |pts: Value| {
let mut ids = IdGen::new("s");
let ctx = Ctx { level: "ug", floor_height: None, cat: "", wall_type: "", text_height: 0.25, symbol: 1.0 };
ops(root, &json!({"cmd": "excavation", "pts": pts}), &ctx, &mut ids).unwrap()
};
let o = run(json!([{"x": 0, "y": 0}, {"x": 10, "y": 8}]));
let Op::Add { collection, items, .. } = &o[0] else { panic!() };
assert_eq!(collection, "context");
assert_eq!((items[0]["type"].as_str(), items[0]["bottom"].as_f64()), (Some("excavation"), Some(-3.3)));
assert_eq!(items[0]["outline"].as_array().unwrap().len(), 4);
assert!(run(json!([{"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 2, "y": 0}])).is_empty());
}
#[test]
fn gelaende_aus_hoehenlinien() {
let c = json!([{"z": 1, "pts": [{"x": 0, "y": 0}, {"x": 4, "y": 0}]}, {"z": 2, "pts": [{"x": 0, "y": 3}, {"x": 4, "y": 3}]}]);
let raw = terrain_from_contours_with(c.as_array().unwrap(), "t", crate::terrain::TerrainOpts { smooth: 0, max_edge: 100.0, breaklines: true });
assert_eq!(raw["indices"].as_array().unwrap().len(), 6);
assert_eq!(raw["positions"][2], 1);
assert_eq!(raw["contourInterval"], 1);
// Standard: verdichtet und geglättet, Höhen bleiben im Bereich der Konturen.
let t = terrain_from_contours(c.as_array().unwrap(), "t");
assert_eq!(t["indices"].as_array().unwrap().len(), 6);
assert_eq!(t["positions"][2], 1);
let pos = t["positions"].as_array().unwrap();
assert!(t["indices"].as_array().unwrap().len() > 6);
assert!(pos.iter().skip(2).step_by(3).all(|z| (1.0..=2.0).contains(&z.as_f64().unwrap())));
assert!(terrain_from_contours(&[], "t")["indices"].as_array().unwrap().is_empty());
}
/// [T7] Rotationskörper: Achse waagrecht im Plan, Profil auf einer Seite, Matrix bildet lokal x → Quer, z → Achse ab.
+711
View File
@@ -0,0 +1,711 @@
//! Baugrube / Geländebearbeitung ([68], [T6]): ein Umriss (Sohle) auf fester Höhe, Böschungen bis zum
//! Gelände (Abtrag) bzw. Schüttungen bis zum Gelände (Auftrag), optional mit Bermen.
//!
//! Neue Geländehöhe am Punkt p: clamp(t(p), b − d·tan β, b + H(d)) mit d = Abstand zum Umriss (innen 0),
//! H(d) = Böschungsprofil (Neigung α der nächsten Kante, je `bermHeight` eine Berme der Breite
//! `bermWidth`), β = Schüttungswinkel. Innen gilt damit überall die Sohle b; die Ecken der Böschung sind
//! Kegel (wie beim Aushub mit dem Bagger).
//!
//! • Netz: das Gelände wird im Wirkbereich neu trianguliert — Rasterpunkte (exakte neue Höhe), Umriss
//! und Böschungsoberkante (Schnitt Böschung/Gelände) als Bruchkanten, ausserhalb das Original-TIN
//! samt seinen Kanten. Ergebnis je Gelände-Netz zwischengespeichert ([`site_terrain`]).
//! • Mengen: Abtrag/Auftrag als Integral von (t − neu) über ein feines Raster (Mittelpunktregel auf der
//! exakten Funktion, nicht auf dem Netz); Hinterfüllung = Abtrag ausserhalb der Gebäude-Grundfläche.
//! Jede Baugrube wird gegen das gewachsene Terrain gerechnet.
use crate::model::{ContextObject, Excavation, Project, TerrainMesh};
use crate::terrain::{constrained_tin, datum, isolines, P2, Tin, TinIndex};
use std::cell::RefCell;
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
pub const DEFAULT_SLOPE: f64 = 45.0;
pub const DEFAULT_FILL_SLOPE: f64 = 33.7;
fn tan_deg(a: f64) -> f64 {
a.clamp(5.0, 89.5).to_radians().tan()
}
/// Baugrube im Höhenbezug des Netzes.
#[derive(Clone, Debug)]
pub struct ExSpec {
/// Umriss gegen den Uhrzeigersinn.
pub ring: Vec<P2>,
pub bottom: f64,
pub cut_tan: Vec<f64>,
pub fill_tan: f64,
pub berm_w: f64,
pub berm_h: f64,
}
fn seg_dist(p: P2, a: P2, b: P2) -> f64 {
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
let l2 = dx * dx + dy * dy;
let t = if l2 > 0.0 { (((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };
(p[0] - a[0] - t * dx).hypot(p[1] - a[1] - t * dy)
}
pub fn point_in_ring(p: P2, r: &[P2]) -> bool {
let mut inside = false;
let n = r.len();
let mut j = n.wrapping_sub(1);
for i in 0..n {
let (a, b) = (r[i], r[j]);
if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0] {
inside = !inside;
}
j = i;
}
inside
}
fn signed_area(r: &[P2]) -> f64 {
let n = r.len();
(0..n).map(|i| r[i][0] * r[(i + 1) % n][1] - r[(i + 1) % n][0] * r[i][1]).sum::<f64>() / 2.0
}
impl ExSpec {
/// Aus dem Modell; `dz` = Höhenbezug des Netzes ([`datum`]). `None` bei kaputtem Umriss.
pub fn of(e: &Excavation, dz: f64) -> Option<ExSpec> {
let mut ring: Vec<P2> = e.outline.iter().map(|v| [v.x, v.y]).filter(|p| p[0].is_finite() && p[1].is_finite()).collect();
ring.dedup_by(|a, b| (a[0] - b[0]).hypot(a[1] - b[1]) < 1e-9);
if ring.len() > 2 && (ring[0][0] - ring[ring.len() - 1][0]).hypot(ring[0][1] - ring[ring.len() - 1][1]) < 1e-9 {
ring.pop();
}
if ring.len() < 3 || !e.bottom.is_finite() || signed_area(&ring).abs() < 1e-6 {
return None;
}
let n = ring.len();
let slope = e.slope.filter(|s| s.is_finite() && *s > 0.0).unwrap_or(DEFAULT_SLOPE);
let mut cut_tan: Vec<f64> = (0..n).map(|i| tan_deg(e.edge_slopes.as_ref().and_then(|v| v.get(i)).copied().filter(|s| s.is_finite() && *s > 0.0).unwrap_or(slope))).collect();
if signed_area(&ring) < 0.0 {
// Kante i (p_i → p_i+1) wird nach dem Umdrehen Kante n−2−i (mod n).
ring.reverse();
let old = cut_tan.clone();
for i in 0..n {
cut_tan[(2 * n - 2 - i) % n] = old[i];
}
}
let bw = e.berm_width.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(0.0);
let bh = e.berm_height.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(0.0);
Some(ExSpec {
ring,
bottom: e.bottom + dz,
cut_tan,
fill_tan: tan_deg(e.fill_slope.filter(|s| s.is_finite() && *s > 0.0).unwrap_or(DEFAULT_FILL_SLOPE)),
berm_w: if bh > 0.0 { bw } else { 0.0 },
berm_h: if bw > 0.0 { bh } else { 0.0 },
})
}
/// Abstand zum Umriss (innen 0) und Index der nächsten Kante.
pub fn dist(&self, p: P2) -> (f64, usize) {
if point_in_ring(p, &self.ring) {
return (0.0, 0);
}
let n = self.ring.len();
(0..n).map(|i| (seg_dist(p, self.ring[i], self.ring[(i + 1) % n]), i)).fold((f64::INFINITY, 0), |a, b| if b.0 < a.0 { b } else { a })
}
/// Böschungsprofil: Höhe über der Sohle im Abstand d bei Neigung tan.
fn profile(&self, d: f64, tan: f64) -> f64 {
if self.berm_w > 0.0 {
let run = self.berm_h / tan;
let period = run + self.berm_w;
let k = (d / period).floor();
k * self.berm_h + (d - k * period).min(run) * tan
} else {
d * tan
}
}
/// Abstand, bei dem das Profil die Höhe h erreicht (Umkehrung von [`profile`]).
fn reach(&self, h: f64, tan: f64) -> f64 {
if !(h > 0.0) {
return 0.0;
}
if self.berm_w > 0.0 {
let k = (h / self.berm_h).floor();
k * (self.berm_h / tan + self.berm_w) + (h - k * self.berm_h) / tan
} else {
h / tan
}
}
/// Neue Geländehöhe zur alten Höhe `t` am Punkt p.
pub fn apply(&self, t: f64, p: P2) -> f64 {
let (d, i) = self.dist(p);
let hi = self.bottom + self.profile(d, self.cut_tan[i]);
let lo = self.bottom - d * self.fill_tan;
t.max(lo).min(hi)
}
fn bbox(&self) -> [f64; 4] {
let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
for p in &self.ring {
b = [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])];
}
b
}
/// Wirkbereich: grösster Abstand vom Umriss, in dem das Gelände geändert wird.
pub fn reach_in(&self, orig: &Tin, idx: &TinIndex) -> f64 {
let b = self.bbox();
let min_tan = self.cut_tan.iter().copied().fold(f64::INFINITY, f64::min);
let mut r = 0.0;
for _ in 0..6 {
let (mut lo, mut hi) = (self.bottom, self.bottom);
for (p, z) in orig.xy.iter().zip(&orig.z) {
if p[0] >= b[0] - r && p[0] <= b[2] + r && p[1] >= b[1] - r && p[1] <= b[3] + r {
lo = lo.min(*z);
hi = hi.max(*z);
}
}
// Zwischen den Ecken (grosse Dreiecke): Stichproben im Bereich.
for j in 0..=24 {
for i in 0..=24 {
let (x, y) = (b[0] - r + (b[2] - b[0] + 2.0 * r) * i as f64 / 24.0, b[1] - r + (b[3] - b[1] + 2.0 * r) * j as f64 / 24.0);
if let Some(z) = idx.z_at(x, y) {
lo = lo.min(z);
hi = hi.max(z);
}
}
}
let nr = self.reach(hi - self.bottom, min_tan).max((self.bottom - lo) / self.fill_tan).min(2000.0);
if nr <= r + 1e-6 {
return nr;
}
r = nr;
}
r
}
}
/// Regelmässiges Raster über einem Rechteck (Knoten).
struct Grid {
x0: f64,
y0: f64,
s: f64,
nx: usize,
ny: usize,
}
impl Grid {
fn new(b: [f64; 4], s: f64, max_nodes: usize) -> Grid {
let (w, h) = (b[2] - b[0], b[3] - b[1]);
let mut s = s;
while ((w / s).ceil() + 1.0) * ((h / s).ceil() + 1.0) > max_nodes as f64 {
s *= 1.25;
}
Grid { x0: b[0], y0: b[1], s, nx: (w / s).ceil() as usize + 1, ny: (h / s).ceil() as usize + 1 }
}
fn at(&self, i: usize, j: usize) -> P2 {
[self.x0 + i as f64 * self.s, self.y0 + j as f64 * self.s]
}
/// TIN des Rasters mit den Werten `v` (NaN = fehlt; Zellen nur mit vier Werten).
fn tin(&self, v: &[f64]) -> Tin {
let mut t = Tin { xy: Vec::with_capacity(v.len()), z: v.to_vec(), tris: Vec::new() };
for j in 0..self.ny {
for i in 0..self.nx {
t.xy.push(self.at(i, j));
}
}
for j in 0..self.ny.saturating_sub(1) {
for i in 0..self.nx.saturating_sub(1) {
let k = (j * self.nx + i) as u32;
let q = [k, k + 1, k + 1 + self.nx as u32, k + self.nx as u32];
if q.iter().all(|&i| v[i as usize].is_finite()) {
t.tris.push([q[0], q[1], q[2]]);
t.tris.push([q[0], q[2], q[3]]);
}
}
}
t
}
}
/// Ergebnis einer Baugrube auf einem Netz.
#[derive(Clone, Debug)]
pub struct Excavated {
pub tin: Tin,
/// Böschungsoberkante (Abtrag) bzw. Böschungsfuss (Auftrag) im Gelände.
pub daylight: Vec<Vec<P2>>,
pub reach: f64,
pub step: f64,
}
/// Wendet eine Baugrube auf ein Netz an. `None`, wenn sie das Netz nicht trifft.
pub fn excavate(orig: &Tin, ex: &ExSpec) -> Option<Excavated> {
let idx = TinIndex::new(orig);
let c = ex.ring.iter().fold([0.0, 0.0], |a, p| [a[0] + p[0], a[1] + p[1]]);
let c = [c[0] / ex.ring.len() as f64, c[1] / ex.ring.len() as f64];
if idx.z_at(c[0], c[1]).is_none() && ex.ring.iter().all(|p| idx.z_at(p[0], p[1]).is_none()) {
return None;
}
let r = ex.reach_in(orig, &idx);
let b = ex.bbox();
let s0 = (((b[2] - b[0] + 2.0 * r) * (b[3] - b[1] + 2.0 * r)).sqrt() / 120.0).clamp(0.15, 2.0);
let reg = [b[0] - r - s0, b[1] - r - s0, b[2] + r + s0, b[3] + r + s0];
let g = Grid::new(reg, s0, 250_000);
let s = g.s;
let mut t_val = vec![f64::NAN; g.nx * g.ny];
let mut d_val = vec![f64::INFINITY; g.nx * g.ny];
let (mut cut_phi, mut fill_phi) = (vec![f64::NAN; g.nx * g.ny], vec![f64::NAN; g.nx * g.ny]);
for j in 0..g.ny {
for i in 0..g.nx {
let p = g.at(i, j);
let k = j * g.nx + i;
let Some(t) = idx.z_at(p[0], p[1]) else { continue };
let (d, e) = ex.dist(p);
t_val[k] = t;
d_val[k] = d;
cut_phi[k] = t - (ex.bottom + ex.profile(d, ex.cut_tan[e]));
fill_phi[k] = (ex.bottom - d * ex.fill_tan) - t;
}
}
let mut pts: Vec<[f64; 3]> = Vec::new();
let mut cons: Vec<(u32, u32)> = Vec::new();
let chain = |line: &[P2], z: &dyn Fn(P2) -> Option<f64>, pts: &mut Vec<[f64; 3]>, cons: &mut Vec<(u32, u32)>| {
let mut prev: Option<u32> = None;
for &p in line {
match z(p) {
Some(h) => {
pts.push([p[0], p[1], h]);
let k = pts.len() as u32 - 1;
if let Some(q) = prev {
cons.push((q, k));
}
prev = Some(k);
}
None => prev = None,
}
}
};
// 1. Umriss der Sohle, verdichtet.
let n = ex.ring.len();
let mut ring_pts: Vec<P2> = Vec::new();
for i in 0..n {
let (a, q) = (ex.ring[i], ex.ring[(i + 1) % n]);
let steps = ((a[0] - q[0]).hypot(a[1] - q[1]) / s).ceil().max(1.0) as usize;
for k in 0..steps {
let f = k as f64 / steps as f64;
ring_pts.push([a[0] + (q[0] - a[0]) * f, a[1] + (q[1] - a[1]) * f]);
}
}
ring_pts.push(ring_pts[0]);
let bottom = ex.bottom;
chain(&ring_pts, &|p| idx.z_at(p[0], p[1]).map(|t| ex.apply(t, p).min(bottom).max(bottom)), &mut pts, &mut cons);
// 2. Böschungsoberkante / -fuss: Nullinien von t − hi bzw. lo − t ausserhalb des Umrisses.
let mut daylight = Vec::new();
for phi in [&cut_phi, &fill_phi] {
let gt = g.tin(phi);
for l in isolines(&gt, 1e12, 0.0) {
let mut part: Vec<P2> = Vec::new();
let flush = |part: &mut Vec<P2>, daylight: &mut Vec<Vec<P2>>| {
if part.len() >= 2 {
daylight.push(std::mem::take(part));
} else {
part.clear();
}
};
let mut pl = l.pts.clone();
if l.closed {
pl.push(pl[0]);
}
for p in pl {
if ex.dist(p).0 > 1e-6 {
part.push(p);
} else {
flush(&mut part, &mut daylight);
}
}
flush(&mut part, &mut daylight);
}
}
for l in &daylight {
chain(l, &|p| idx.z_at(p[0], p[1]), &mut pts, &mut cons);
}
// 3. Rasterpunkte im Wirkbereich.
for j in 0..g.ny {
for i in 0..g.nx {
let k = j * g.nx + i;
if t_val[k].is_finite() && d_val[k] <= r + s {
let p = g.at(i, j);
pts.push([p[0], p[1], ex.apply(t_val[k], p)]);
}
}
}
// 4. Original ausserhalb samt Kanten.
let mut keep = vec![u32::MAX; orig.xy.len()];
for (i, p) in orig.xy.iter().enumerate() {
if ex.dist(*p).0 > r + 1.5 * s {
keep[i] = pts.len() as u32;
pts.push([p[0], p[1], orig.z[i]]);
}
}
let mut seen: HashSet<(u32, u32)> = HashSet::new();
for tr in &orig.tris {
for k in 0..3 {
let (a, b) = (keep[tr[k] as usize], keep[tr[(k + 1) % 3] as usize]);
if a != u32::MAX && b != u32::MAX && seen.insert((a.min(b), a.max(b))) {
cons.push((a, b));
}
}
}
let (mut tin, _) = constrained_tin(&pts, &cons, 0.3 * s, 0.0);
// Dreiecke ausserhalb des Original-Netzes (konkave Ränder) weg.
let xy = tin.xy.clone();
tin.tris.retain(|tr| {
let c = tr.iter().fold([0.0, 0.0], |a, &i| [a[0] + xy[i as usize][0] / 3.0, a[1] + xy[i as usize][1] / 3.0]);
idx.z_at(c[0], c[1]).is_some()
});
Some(Excavated { tin, daylight, reach: r, step: s })
}
// ── Mengen ───────────────────────────────────────────────────────────────────
/// Abtrag, Auftrag, Hinterfüllung (m³) und Sohlenfläche (m²).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Volumes {
pub cut: f64,
pub fill: f64,
pub backfill: f64,
pub bottom_area: f64,
}
/// Integriert (t − neu) über ein Raster der Weite ≤ `h` (Mittelpunkte, höchstens ~1.5 Mio. Proben).
/// `footprint`: Gebäude-Grundfläche (Ringe); Abtrag darin zählt nicht zur Hinterfüllung.
pub fn volumes(orig: &Tin, ex: &ExSpec, h: f64, footprint: &[Vec<P2>]) -> Volumes {
let idx = TinIndex::new(orig);
let r = ex.reach_in(orig, &idx);
let b = ex.bbox();
let reg = [b[0] - r, b[1] - r, b[2] + r, b[3] + r];
let (w, hh) = (reg[2] - reg[0], reg[3] - reg[1]);
let mut h = h.max(1e-3);
while (w / h).ceil() * (hh / h).ceil() > 1.5e6 {
h *= 1.2;
}
let (nx, ny) = ((w / h).ceil() as usize, (hh / h).ceil() as usize);
let (hx, hy) = (w / nx as f64, hh / ny as f64);
let cell = hx * hy;
let mut v = Volumes { bottom_area: signed_area(&ex.ring).abs(), ..Default::default() };
for j in 0..ny {
for i in 0..nx {
let p = [reg[0] + (i as f64 + 0.5) * hx, reg[1] + (j as f64 + 0.5) * hy];
let Some(t) = idx.z_at(p[0], p[1]) else { continue };
let dz = t - ex.apply(t, p);
if dz > 0.0 {
v.cut += dz * cell;
if !footprint.iter().any(|f| point_in_ring(p, f)) {
v.backfill += dz * cell;
}
} else {
v.fill -= dz * cell;
}
}
}
v
}
// ── Gelände mit Baugruben, zwischengespeichert ──────────────────────────────
/// Gelände-Netz samt angewandten Baugruben (Höhen roh, Modell = roh − `datum`).
#[derive(Debug)]
pub struct SiteTerrain {
pub datum: f64,
pub orig: Tin,
/// Gelände nach allen Baugruben; `None`, wenn keine das Netz trifft.
pub modified: Option<Tin>,
/// (Baugrube, Spezifikation, Böschungsoberkante)
pub items: Vec<(String, ExSpec, Vec<Vec<P2>>)>,
}
impl SiteTerrain {
pub fn current(&self) -> &Tin {
self.modified.as_ref().unwrap_or(&self.orig)
}
}
pub fn excavations(p: &Project) -> Vec<&Excavation> {
p.context.as_deref().unwrap_or(&[]).iter().filter_map(|c| if let ContextObject::Excavation(e) = c { Some(e) } else { None }).collect()
}
pub fn terrains(p: &Project) -> Vec<&TerrainMesh> {
p.context.as_deref().unwrap_or(&[]).iter().filter_map(|c| if let ContextObject::TerrainMesh(t) = c { Some(t) } else { None }).collect()
}
type Cache = Vec<(u64, Rc<SiteTerrain>)>;
thread_local! {
static CACHE: RefCell<Cache> = const { RefCell::new(Vec::new()) };
}
fn hash_of(p: &Project, t: &TerrainMesh, ex: &[&Excavation]) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
for v in t.positions.iter().chain(&t.indices) {
v.to_bits().hash(&mut h);
}
p.reference_elevation_masl.map(f64::to_bits).hash(&mut h);
for e in ex {
serde_json::to_string(e).unwrap_or_default().hash(&mut h);
}
h.finish()
}
/// Gelände-Netz `t` mit allen Baugruben des Projekts (zwischengespeichert, Schlüssel = Inhalt).
pub fn site_terrain(p: &Project, t: &TerrainMesh) -> Rc<SiteTerrain> {
let ex = excavations(p);
let key = hash_of(p, t, &ex);
if let Some(hit) = CACHE.with(|c| c.borrow().iter().find(|(k, _)| *k == key).map(|(_, v)| v.clone())) {
return hit;
}
let orig = Tin::from_flat(&t.positions, &t.indices);
let dz = datum(p.reference_elevation_masl, &orig.z);
let mut cur: Option<Tin> = None;
let mut items = Vec::new();
for e in ex {
let Some(spec) = ExSpec::of(e, dz) else { continue };
let base = cur.as_ref().unwrap_or(&orig);
if let Some(r) = excavate(base, &spec) {
items.push((e.id.clone(), spec, r.daylight));
cur = Some(r.tin);
}
}
let st = Rc::new(SiteTerrain { datum: dz, orig, modified: cur, items });
CACHE.with(|c| {
let mut c = c.borrow_mut();
c.insert(0, (key, st.clone()));
c.truncate(4);
});
st
}
/// Gelände-Netz im Modellbezug samt Baugruben (flach: Positionen, Indizes) und ob es geändert wurde.
/// Ohne Baugrube und ohne Höhenbezug das Original (ohne Kopie).
pub fn terrain_model_mesh<'a>(p: &Project, t: &'a TerrainMesh) -> (std::borrow::Cow<'a, [f64]>, std::borrow::Cow<'a, [f64]>, bool) {
use std::borrow::Cow;
let st = site_terrain(p, t);
if st.modified.is_none() && st.datum == 0.0 {
return (Cow::Borrowed(&t.positions), Cow::Borrowed(&t.indices), false);
}
let (pos, idx) = st.current().to_flat(-st.datum);
(Cow::Owned(pos), Cow::Owned(idx), st.modified.is_some())
}
/// Mengen je Baugrube (gegen das gewachsene Terrain des ersten Netzes, das sie trifft).
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExQty {
pub id: String,
pub name: String,
pub bottom: f64,
pub bottom_area: f64,
pub cut: f64,
pub fill: f64,
pub backfill: f64,
}
pub fn quantities(p: &Project) -> Vec<ExQty> {
let fp: Vec<Vec<P2>> = crate::site_rules::building_footprint(p).iter().flat_map(|poly| poly.first().map(|r| r.iter().map(|v| [v.x, v.y]).collect::<Vec<P2>>())).collect();
let mut out = Vec::new();
for e in excavations(p) {
for t in terrains(p) {
let st = site_terrain(p, t);
let Some((_, spec, _)) = st.items.iter().find(|(id, ..)| *id == e.id) else { continue };
let h = (spec.ring.iter().map(|q| q[0]).fold(f64::NEG_INFINITY, f64::max) - spec.ring.iter().map(|q| q[0]).fold(f64::INFINITY, f64::min)).max(1.0) / 400.0;
let v = volumes(&st.orig, spec, h.clamp(0.02, 0.5), &fp);
out.push(ExQty { id: e.id.clone(), name: e.name.clone(), bottom: e.bottom, bottom_area: v.bottom_area, cut: v.cut, fill: v.fill, backfill: v.backfill });
break;
}
}
out
}
/// Höhe des gewachsenen (`designed = false`) bzw. gestalteten Terrains im Modellbezug; `None` ohne Gelände.
pub fn terrain_z(p: &Project, x: f64, y: f64, designed: bool) -> Option<f64> {
for t in terrains(p) {
let st = site_terrain(p, t);
let tin = if designed { st.current() } else { &st.orig };
if let Some(z) = TinIndex::new(tin).z_at(x, y) {
return Some(z - st.datum);
}
}
None
}
// ── Grundriss: Böschungsschraffur ────────────────────────────────────────────
/// Böschungsschraffur: Striche von der Oberkante zur Unterkante, abwechselnd lang und halb, im Abstand
/// `spacing` entlang des Umrisses (an konvexen Ecken gefächert). `t` = Gelände vor dieser Baugrube.
pub fn slope_hatch(t: &Tin, ex: &ExSpec, spacing: f64) -> Vec<(P2, P2)> {
let idx = TinIndex::new(t);
let r = ex.reach_in(t, &idx).max(spacing);
let step = (spacing / 4.0).max(0.02);
// Länge des geänderten Bereichs entlang des Strahls q + n·L; Vorzeichen: Abtrag (true) / Auftrag.
let ray = |q: P2, n: P2| -> Option<(f64, bool)> {
let mut last: Option<(f64, bool)> = None;
let mut l = step / 2.0;
while l <= r + step {
let p = [q[0] + n[0] * l, q[1] + n[1] * l];
let tz = idx.z_at(p[0], p[1])?;
let dz = tz - ex.apply(tz, p);
if dz.abs() < 1e-6 {
break;
}
last = Some((l, dz > 0.0));
l += step;
}
last
};
let n = ex.ring.len();
let normal = |i: usize| {
let (a, b) = (ex.ring[i], ex.ring[(i + 1) % n]);
let l = (b[0] - a[0]).hypot(b[1] - a[1]).max(1e-12);
[(b[1] - a[1]) / l, -(b[0] - a[0]) / l]
};
let mut rays: Vec<(P2, P2)> = Vec::new();
for i in 0..n {
let (a, b) = (ex.ring[i], ex.ring[(i + 1) % n]);
let len = (b[0] - a[0]).hypot(b[1] - a[1]);
let nn = normal(i);
let k = (len / spacing).floor() as usize;
let off = (len - k as f64 * spacing) / 2.0;
for s in 0..=k {
let f = (off + s as f64 * spacing) / len.max(1e-12);
if f <= 1e-9 || f >= 1.0 - 1e-9 {
continue;
}
rays.push(([a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f], nn));
}
// Fächer an der konvexen Ecke b.
let n2 = normal((i + 1) % n);
let cross = nn[0] * n2[1] - nn[1] * n2[0];
if cross > 1e-9 {
let a0 = nn[1].atan2(nn[0]);
let mut a1 = n2[1].atan2(n2[0]);
if a1 < a0 {
a1 += std::f64::consts::TAU;
}
let mid = [((a0 + a1) / 2.0).cos(), ((a0 + a1) / 2.0).sin()];
let lm = ray(b, mid).map_or(0.0, |r| r.0);
let m = ((a1 - a0) * lm / spacing).floor() as usize;
for s in 0..=m {
let ang = a0 + (a1 - a0) * s as f64 / m.max(1) as f64;
rays.push((b, [ang.cos(), ang.sin()]));
}
}
}
let mut out = Vec::new();
for (k, (q, nn)) in rays.into_iter().enumerate() {
let Some((l, cut)) = ray(q, nn) else { continue };
let far = [q[0] + nn[0] * l, q[1] + nn[1] * l];
let (top, bot) = if cut { (far, q) } else { (q, far) };
let f = if k % 2 == 0 { 1.0 } else { 0.5 };
out.push((top, [top[0] + (bot[0] - top[0]) * f, top[1] + (bot[1] - top[1]) * f]));
}
out
}
/// Gelände vor der Baugrube `id` (für die Schraffur); `None`, wenn sie das Netz nicht trifft.
pub fn terrain_before(st: &SiteTerrain, id: &str) -> Option<Tin> {
let pos = st.items.iter().position(|(i, ..)| i == id)?;
if pos == 0 {
return Some(st.orig.clone());
}
let mut cur = st.orig.clone();
for (_, spec, _) in &st.items[..pos] {
cur = excavate(&cur, spec)?.tin;
}
Some(cur)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::Vec2;
use crate::terrain::{mesh_volume, prism, watertight};
fn flat(z: f64, half: f64) -> Tin {
Tin { xy: vec![[-half, -half], [half, -half], [half, half], [-half, half]], z: vec![z; 4], tris: vec![[0, 1, 2], [0, 2, 3]] }
}
fn square(e: f64, bottom: f64) -> Excavation {
Excavation {
id: "bg".into(),
outline: vec![Vec2 { x: -e, y: -e }, Vec2 { x: e, y: -e }, Vec2 { x: e, y: e }, Vec2 { x: -e, y: e }],
bottom,
slope: Some(45.0),
..Default::default()
}
}
#[test]
fn aushub_wie_analytisch() {
// 10 × 10 m, 3 m tief, 45°: V = A·h + U·h²/(2 tan α) + π h³/(3 tan² α).
let ex = ExSpec::of(&square(5.0, -3.0), 0.0).unwrap();
let t = flat(0.0, 50.0);
let exact = 100.0 * 3.0 + 40.0 * 9.0 / 2.0 + std::f64::consts::PI * 27.0 / 3.0;
let v = volumes(&t, &ex, 0.02, &[]);
assert!((v.cut - exact).abs() < 2e-3 * exact, "{} vs {exact}", v.cut);
assert!(v.fill.abs() < 1e-9 && (v.bottom_area - 100.0).abs() < 1e-9);
// Hinterfüllung: ohne Gebäude = Abtrag; mit Gebäude 10 × 10 = Abtrag − 300.
assert!((v.backfill - v.cut).abs() < 1e-9);
let fp = vec![vec![[-5.0, -5.0], [5.0, -5.0], [5.0, 5.0], [-5.0, 5.0]]];
let v2 = volumes(&t, &ex, 0.02, &fp);
assert!((v.cut - v2.backfill - 300.0).abs() < 1.0, "{}", v2.backfill);
// Netz: dicht als Prisma, Volumen-Differenz ≈ Aushub.
let r = excavate(&t, &ex).unwrap();
let (v0, f0) = prism(&t, -10.0);
let (v1, f1) = prism(&r.tin, -10.0);
assert!(watertight(&f1));
let dv = mesh_volume(&v0, &f0) - mesh_volume(&v1, &f1);
assert!((dv - exact).abs() < 0.02 * exact, "{dv} vs {exact}");
// Sohle und Böschungsoberkante: Oberkante als geschlossener Ring bei d = 3.
let z = TinIndex::new(&r.tin).z_at(0.0, 0.0).unwrap();
assert!((z + 3.0).abs() < 1e-9);
assert!(!r.daylight.is_empty());
for l in &r.daylight {
for q in l {
assert!((ex.dist(*q).0 - 3.0).abs() < 0.1, "{q:?}");
}
}
}
#[test]
fn auftrag_am_hang_und_bermen() {
// Hang 10 %: Plattform auf ±0 schneidet bergseits ein und wird talseits geschüttet.
let t = Tin { xy: vec![[-50.0, -50.0], [50.0, -50.0], [50.0, 50.0], [-50.0, 50.0]], z: vec![-5.0, -5.0, 5.0, 5.0], tris: vec![[0, 1, 2], [0, 2, 3]] };
let ex = ExSpec::of(&square(5.0, 0.0), 0.0).unwrap();
let v = volumes(&t, &ex, 0.05, &[]);
assert!(v.cut > 10.0 && v.fill > 10.0, "{v:?}");
// Bermen verlängern die Böschung: mehr Aushub als ohne.
let mut e = square(5.0, -6.0);
let base = volumes(&flat(0.0, 60.0), &ExSpec::of(&e, 0.0).unwrap(), 0.05, &[]).cut;
e.berm_width = Some(1.0);
e.berm_height = Some(2.0);
let sp = ExSpec::of(&e, 0.0).unwrap();
assert!((sp.profile(2.0, 1.0) - 2.0).abs() < 1e-12 && (sp.profile(2.5, 1.0) - 2.0).abs() < 1e-12 && (sp.profile(3.5, 1.0) - 2.5).abs() < 1e-12);
assert!((sp.reach(2.5, 1.0) - 3.5).abs() < 1e-12);
assert!(volumes(&flat(0.0, 60.0), &sp, 0.05, &[]).cut > base);
}
#[test]
fn schraffur_und_unsinn() {
let t = flat(0.0, 50.0);
let mut e = square(5.0, -3.0);
// Umlaufsinn im Uhrzeigersinn: Kantenneigungen wandern mit.
e.outline.reverse();
e.edge_slopes = Some(vec![60.0, 45.0, 45.0, 45.0]);
let ex = ExSpec::of(&e, 0.0).unwrap();
// Kante 0 war (−5,5)→(5,5) (oben); dort steiler: Böschung kürzer.
let h = slope_hatch(&t, &ex, 0.5);
assert!(h.len() > 40);
let top: Vec<_> = h.iter().filter(|(a, _)| a[1] > 5.0 + 1e-6 && a[0].abs() < 4.0).collect();
assert!(!top.is_empty() && top.iter().all(|(a, _)| a[1] < 5.0 + 3.0 / 60f64.to_radians().tan() + 0.2));
assert!(ExSpec::of(&Excavation { outline: vec![Vec2 { x: 0.0, y: 0.0 }], ..Default::default() }, 0.0).is_none());
assert!(ExSpec::of(&Excavation { bottom: f64::NAN, ..square(1.0, 0.0) }, 0.0).is_none());
// Ausserhalb des Netzes: nichts.
let far = ExSpec::of(&Excavation { outline: square(1.0, 0.0).outline.iter().map(|v| Vec2 { x: v.x + 500.0, y: v.y }).collect(), ..square(1.0, 0.0) }, 0.0).unwrap();
assert!(excavate(&t, &far).is_none());
}
}
+1
View File
@@ -63,6 +63,7 @@ fn shift_context(o: &mut ContextObject, dx: f64, dy: f64) {
}
ContextObject::ImportedMesh(m) => shift_positions(&mut m.positions, dx, dy),
ContextObject::TerrainMesh(m) => shift_positions(&mut m.positions, dx, dy),
ContextObject::Excavation(e) => shift_all(&mut e.outline, dx, dy),
}
}
+2
View File
@@ -8,6 +8,8 @@ pub mod export_schedule;
pub mod opening_schedule;
pub mod u_value;
pub mod sheet_table;
pub mod terrain;
pub mod excavation;
pub mod flat;
pub mod flat_write;
pub mod polygon_bool;
+6 -2
View File
@@ -485,10 +485,14 @@ pub fn mesh_export_data(src: &Project, opt: &MeshOptions) -> Result<Flat, String
if opt.context {
for obj in p.context.as_deref().unwrap_or(&[]) {
let (terrain, id, name, color, positions, indices) = match obj {
ContextObject::TerrainMesh(m) => (true, &m.id, &m.name, None, &m.positions, &m.indices),
ContextObject::ImportedMesh(m) => (false, &m.id, &m.name, m.color.as_deref(), &m.positions, &m.indices),
ContextObject::TerrainMesh(m) => {
let (pos, idx, _) = crate::excavation::terrain_model_mesh(&p, m);
(true, &m.id, &m.name, None, pos, idx)
}
ContextObject::ImportedMesh(m) => (false, &m.id, &m.name, m.color.as_deref(), std::borrow::Cow::Borrowed(m.positions.as_slice()), std::borrow::Cow::Borrowed(m.indices.as_slice())),
_ => continue,
};
let (positions, indices) = (&*positions, &*indices);
if positions.len() < 9 || indices.len() < 3 {
continue;
}
+50
View File
@@ -4124,6 +4124,9 @@ pub enum LayoutTableSource {
/// Bauteilliste mit U-Werten ([71]).
#[serde(rename = "elements")]
Elements,
/// [68] Erdarbeiten: Baugruben mit Abtrag/Auftrag/Hinterfüllung.
#[serde(rename = "earthworks")]
Earthworks,
#[serde(other)]
#[ts(skip)]
Unknown,
@@ -5091,6 +5094,53 @@ pub struct TerrainMesh {
#[serde(rename = "vertexColors", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub vertex_colors: Option<Vec<f64>>,
/// [T6] Äquidistanz der Höhenlinien im Grundriss in m (aus dem Netz neu erzeugt, inkl. Baugruben).
/// Fehlt der Wert oder ist er ≤ 0, zeigt der Grundriss nur den Rahmen.
#[serde(rename = "contourInterval", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub contour_interval: Option<f64>,
/// [T6] Jede n-te Höhenlinie ist Zähllinie (dicker, beschriftet). Default 5.
#[serde(rename = "contourIndexEvery", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub contour_index_every: Option<f64>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
}
/// [68] Baugrube / Geländebearbeitung: Sohle als Umriss auf der Höhe `bottom` (m, Modell ±0.00).
/// Ausserhalb steigt die Böschung mit `slope` (Grad, Default 45; je Kante `edgeSlopes`, 0 = Default)
/// bis zum Gelände (Abtrag); liegt das Gelände tiefer, fällt eine Schüttung mit `fillSlope` (Default
/// 33.7 ≈ 2:3) bis zum Gelände (Auftrag). Bermen: alle `bermHeight` m Höhe eine waagrechte Berme der
/// Breite `bermWidth`. Schneidet jedes Gelände-Netz, das den Umriss enthält.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
#[serde(default)]
pub struct Excavation {
pub id: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub layer: Option<String>,
#[serde(rename = "categoryCode", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub category_code: Option<String>,
pub outline: Vec<Vec2>,
pub bottom: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub slope: Option<f64>,
#[serde(rename = "fillSlope", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub fill_slope: Option<f64>,
#[serde(rename = "edgeSlopes", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub edge_slopes: Option<Vec<f64>>,
#[serde(rename = "bermWidth", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub berm_width: Option<f64>,
#[serde(rename = "bermHeight", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub berm_height: Option<f64>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
+2
View File
@@ -527,6 +527,8 @@ pub enum ContextObject {
TerrainMesh(TerrainMesh),
#[serde(rename = "image")]
Image(ContextImage),
#[serde(rename = "excavation")]
Excavation(Excavation),
}
impl Default for Drawing2DGeom {
+18 -10
View File
@@ -1713,14 +1713,18 @@ pub fn emit_context_meshes(p: &Project) -> Vec<RMesh> {
let mut out = Vec::new();
for obj in p.context.as_deref().unwrap_or(&[]) {
match obj {
ContextObject::TerrainMesh(m) if m.positions.len() >= 9 && m.indices.len() >= 3 => out.push(RMesh {
positions: m.positions.clone(),
indices: indices_u32(&m.indices),
kind: "terrain",
color: TERRAIN_RGB,
vertex_colors: m.vertex_colors.clone().filter(|v| !v.is_empty()),
material_index: None,
}),
ContextObject::TerrainMesh(m) if m.positions.len() >= 9 && m.indices.len() >= 3 => {
// [T6] Baugruben schneiden das Gelände; Höhen im Modellbezug (Luftbild-Farben nur ungeändert).
let (pos, idx, changed) = crate::excavation::terrain_model_mesh(p, m);
out.push(RMesh {
positions: pos.into_owned(),
indices: indices_u32(&idx),
kind: "terrain",
color: TERRAIN_RGB,
vertex_colors: if changed { None } else { m.vertex_colors.clone().filter(|v| !v.is_empty()) },
material_index: None,
})
}
ContextObject::ImportedMesh(m) if m.positions.len() >= 9 && m.indices.len() >= 3 => out.push(RMesh {
positions: m.positions.clone(),
indices: indices_u32(&m.indices),
@@ -1983,10 +1987,14 @@ pub fn pick_geometry(p: &Project) -> Result<PickGeometry, String> {
let mut context_meshes = Vec::new();
for obj in p.context.as_deref().unwrap_or(&[]) {
let (pos, idx, id) = match obj {
ContextObject::TerrainMesh(m) => (&m.positions, &m.indices, &m.id),
ContextObject::ImportedMesh(m) => (&m.positions, &m.indices, &m.id),
ContextObject::TerrainMesh(m) => {
let (pos, idx, _) = crate::excavation::terrain_model_mesh(p, m);
(pos, idx, &m.id)
}
ContextObject::ImportedMesh(m) => (std::borrow::Cow::Borrowed(m.positions.as_slice()), std::borrow::Cow::Borrowed(m.indices.as_slice()), &m.id),
_ => continue,
};
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]] };
let mut tris: Vec<Tri> = Vec::new();
+128
View File
@@ -65,6 +65,7 @@ pub fn plan_context(c: &Ctx, out: &mut Vec<Primitive>) {
ContextObject::ContourSet(s) => s.category_code.as_deref(),
ContextObject::TerrainMesh(t) => t.category_code.as_deref(),
ContextObject::Image(i) => i.category_code.as_deref(),
ContextObject::Excavation(e) => e.category_code.as_deref(),
};
if code.is_some_and(|k| !c.shown(k)) {
continue;
@@ -99,12 +100,109 @@ pub fn plan_context(c: &Ctx, out: &mut Vec<Primitive>) {
}
out.push(pick_band(q, Some(&t.id), None));
}
terrain_contours(c, t, out);
}
ContextObject::Excavation(e) => excavation_lines(c, e, out),
ContextObject::Image(_) => {}
}
}
}
const TERRAIN_INK: &str = "#7a5b3a";
const EXCAVATION_INK: &str = "#1f242c";
fn ink_line(a: Vec2, b: Vec2, w: f64, color: &str, dash: Option<Vec<f64>>) -> Primitive {
Primitive::Line { a, b, cls: "context-line".into(), weight_mm: w, dash: dash.map(Some), zigzag: None, motif: None, color: Some(color.into()), drawing_id: None, opening_id: None, stair_id: None, greyed: None, opacity: None }
}
/// [T6] Höhenlinien aus dem Gelände-Netz (samt Baugruben) in der Äquidistanz `contourInterval`; jede
/// `contourIndexEvery`-te ist Zähllinie (dicker, mit Höhenangabe, lesbar gedreht).
fn terrain_contours(c: &Ctx, t: &TerrainMesh, out: &mut Vec<Primitive>) {
let Some(iv) = t.contour_interval.filter(|v| v.is_finite() && *v > 0.0) else { return };
let every = t.contour_index_every.filter(|v| v.is_finite() && *v >= 1.0).map_or(5, |v| v.round() as i64);
let st = crate::excavation::site_terrain(c.p, t);
let text_h = 0.002 * c.a.scale.max(1.0);
for l in crate::terrain::isolines(st.current(), iv, 0.0) {
let k = (l.level / iv).round() as i64;
let index = k.rem_euclid(every) == 0;
let w = if index { 0.25 } else { 0.1 };
let n = l.pts.len();
let segs = if l.closed { n } else { n - 1 };
for i in 0..segs {
let (a, b) = (l.pts[i], l.pts[(i + 1) % n]);
out.push(ink_line(v2(a[0], a[1]), v2(b[0], b[1]), w, TERRAIN_INK, None));
}
if !index {
continue;
}
// Beschriftung in der Mitte der Linie (nur, wenn sie lang genug ist).
let len: f64 = (0..segs).map(|i| (l.pts[(i + 1) % n][0] - l.pts[i][0]).hypot(l.pts[(i + 1) % n][1] - l.pts[i][1])).sum();
if len < 12.0 * text_h {
continue;
}
let mut acc = 0.0;
for i in 0..segs {
let (a, b) = (l.pts[i], l.pts[(i + 1) % n]);
let d = (b[0] - a[0]).hypot(b[1] - a[1]);
if acc + d >= len / 2.0 && d > 0.0 {
let f = (len / 2.0 - acc) / d;
let mut ang = (b[1] - a[1]).atan2(b[0] - a[0]);
if ang > std::f64::consts::FRAC_PI_2 || ang <= -std::f64::consts::FRAC_PI_2 {
ang += std::f64::consts::PI;
}
// Text mittig auf die Linie (Breite ≈ 0.6 · Höhe je Zeichen, Grundlinie ≈ −0.35 · Höhe).
let text = crate::js_fmt::to_fixed(l.level, if iv.fract() == 0.0 { 0 } else { 1 });
let half = 0.3 * text_h * text.chars().count() as f64;
let (c, s) = (ang.cos(), ang.sin());
let m = (a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f);
out.push(Primitive::DrawingText {
at: v2(m.0 - c * half + s * 0.35 * text_h, m.1 - s * half - c * 0.35 * text_h),
text,
height_m: text_h,
angle: ang,
color: TERRAIN_INK.into(),
marks: None,
wrap_width: None,
doc: None,
drawing_id: None,
greyed: None,
opacity: None,
});
break;
}
acc += d;
}
}
}
/// [68] Baugrube im Grundriss: Sohle (Böschungsfuss) und Böschungsoberkante, Böschungsschraffur.
fn excavation_lines(c: &Ctx, e: &Excavation, out: &mut Vec<Primitive>) {
let ring: Vec<Vec2> = e.outline.iter().copied().filter(|q| q.x.is_finite() && q.y.is_finite()).collect();
if ring.len() < 3 {
return;
}
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));
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);
let Some((_, spec, daylight)) = st.items.iter().find(|(id, ..)| *id == e.id) else { continue };
for l in daylight {
for w in l.windows(2) {
out.push(ink_line(v2(w[0][0], w[0][1]), v2(w[1][0], w[1][1]), 0.18, EXCAVATION_INK, None));
}
}
if let Some(before) = crate::excavation::terrain_before(&st, &e.id) {
for (a, b) in crate::excavation::slope_hatch(&before, spec, spacing) {
out.push(ink_line(v2(a[0], a[1]), v2(b[0], b[1]), 0.1, EXCAVATION_INK, None));
}
}
break;
}
}
/// Kurz-Tag eines Schnitt-Labels: letztes Wort des Namens, sonst der ganze (getrimmte) Name.
pub fn section_label_tag(name: &str) -> String {
let t = js_trim(name);
@@ -185,6 +283,36 @@ pub fn plan_section_lines(c: &Ctx, out: &mut Vec<Primitive>) {
mod tests {
use super::*;
/// [T6]/[68] Höhenlinien (Zähllinien dicker + beschriftet) und Baugrube (Sohle, Oberkante, Schraffur).
#[test]
fn hoehenlinien_und_baugrube() {
// Ebene schräg: z = x/10 über 0..40 m → Linien bei x = 10, 20, 30 (Äquidistanz 1), Zähllinie bei 0/5 m.
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()),
contour_interval: Some(1.0),
..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 p = Project { context: Some(vec![ContextObject::TerrainMesh(t), ContextObject::Excavation(pit)]), ..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);
let w = |m: f64| out.iter().filter(|q| matches!(q, Primitive::Line { weight_mm, color: Some(c), .. } if *weight_mm == m && c == TERRAIN_INK)).count();
assert!(w(0.1) > 4 && w(0.25) > 0, "{} {}", w(0.1), w(0.25));
let labels: Vec<&str> = out.iter().filter_map(|q| if let Primitive::DrawingText { text, .. } = q { Some(text.as_str()) } else { None }).collect();
assert!(labels.contains(&"5"), "{labels:?}");
let ex = out.iter().filter(|q| matches!(q, Primitive::Line { color: Some(c), .. } if c == EXCAVATION_INK)).count();
assert!(ex > 20, "{ex}");
}
#[test]
fn label_tag_wie_ts() {
assert_eq!(section_label_tag("Schnitt A"), "A");
+99 -1
View File
@@ -659,6 +659,78 @@ fn poly_prim(pts: Vec<Vec2>, fill: &str, stroke: &str, w: f64, opening: Option<&
pr
}
/// [T6] Obere Hüllkurve des Geländes (samt Baugruben) in der Ansicht: Dreiecke mit Tiefe in [0, `depth_max`]
/// und u im Bereich `range`, abgetastet in ≤ 800 Spalten.
fn terrain_silhouette(p: &Project, t: &TerrainMesh, frame: &[f64; 9], range: (f64, f64), depth_max: f64) -> Vec<Vec<[f64; 2]>> {
let (fp, fnrm, fu) = ([frame[0], frame[1], frame[2]], [frame[3], frame[4], frame[5]], [frame[6], frame[7], frame[8]]);
let (pos, idx, _) = crate::excavation::terrain_model_mesh(p, t);
let proj = |i: usize| -> (f64, f64, f64) {
let q = [pos[3 * i], pos[3 * i + 1], pos[3 * i + 2]];
let w = [q[0] - fp[0], q[2] - fp[1], q[1] - fp[2]];
(w[0] * fu[0] + w[1] * fu[1] + w[2] * fu[2], q[2], w[0] * fnrm[0] + w[1] * fnrm[1] + w[2] * fnrm[2])
};
let (u0, u1) = range;
if !(u1 > u0) {
return Vec::new();
}
let n = 800usize;
let du = (u1 - u0) / n as f64;
let mut env = vec![f64::NEG_INFINITY; n + 1];
let nv = pos.len() / 3;
for tr in idx.chunks_exact(3) {
if !tr.iter().all(|v| *v >= 0.0 && (*v as usize) < nv) {
continue;
}
let q = [proj(tr[0] as usize), proj(tr[1] as usize), proj(tr[2] as usize)];
if q.iter().all(|v| v.2 < 0.0) || q.iter().all(|v| v.2 > depth_max) {
continue;
}
let lo = q.iter().map(|v| v.0).fold(f64::INFINITY, f64::min).max(u0);
let hi = q.iter().map(|v| v.0).fold(f64::NEG_INFINITY, f64::max).min(u1);
if !(hi >= lo) {
continue;
}
let (k0, k1) = (((lo - u0) / du).ceil() as usize, (((hi - u0) / du).floor() as usize).min(n));
for (k, e) in env.iter_mut().enumerate().take(k1 + 1).skip(k0) {
let u = u0 + k as f64 * du;
for i in 0..3 {
let (a, b) = (q[i], q[(i + 1) % 3]);
if (a.0 - u) * (b.0 - u) <= 0.0 && a.0 != b.0 {
let z = a.1 + (b.1 - a.1) * (u - a.0) / (b.0 - a.0);
*e = e.max(z);
}
}
}
}
let mut out: Vec<Vec<[f64; 2]>> = Vec::new();
let mut cur: Vec<[f64; 2]> = Vec::new();
for (k, z) in env.iter().enumerate() {
if z.is_finite() {
cur.push([u0 + k as f64 * du, *z]);
} else if cur.len() > 1 {
out.push(std::mem::take(&mut cur));
} else {
cur.clear();
}
}
if cur.len() > 1 {
out.push(cur);
}
// Kollineare Zwischenpunkte weglassen (Raster), Form bleibt.
for l in &mut out {
let mut s: Vec<[f64; 2]> = vec![l[0]];
for i in 1..l.len() - 1 {
let (a, b, c) = (s[s.len() - 1], l[i], l[i + 1]);
if ((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])).abs() > 1e-9 {
s.push(b);
}
}
s.push(l[l.len() - 1]);
*l = s;
}
out
}
/// `generateElevationPlan`: Primitive und Ausmass; `None` ohne Ansichtslinie.
pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono: bool, vis: &Visibility, scale: f64) -> Result<Option<(Vec<Primitive>, [f64; 4])>, String> {
let Some(plane) = level.plane() else { return Ok(None) };
@@ -1031,7 +1103,33 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono:
a.seq.cmp(&b.seq)
});
let mut prims: Vec<Primitive> = items.into_iter().map(|it| it.prim).collect();
if acc.min_x.is_finite() && acc.min_y.is_finite() {
// [T6] Gelände-Silhouette (gestaltetes Terrain) zwischen Ansichtsebene und vorderster Gebäudefläche; was
// darunter liegt, verdeckt das Gelände (Papierfläche über dem Gebäude).
let depth_max = faces.iter().map(|f| f.depth_min).fold(f64::INFINITY, f64::min) + 0.3;
let mut has_terrain = false;
if acc.min_x.is_finite() && depth_max.is_finite() && !crate::excavation::terrains(p).is_empty() {
let terrain_shown = |c: Option<&str>| c.is_none_or(|c| !vis.has_vis || !vis.has_display || (vis.visible(c) && vis.render(c)));
for t in crate::excavation::terrains(p) {
if !terrain_shown(t.category_code.as_deref()) {
continue;
}
for l in terrain_silhouette(p, t, &frame, (acc.min_x - 6.0, acc.max_x + 6.0), depth_max) {
has_terrain = true;
let low = l.iter().map(|q| q[1]).fold(acc.min_y, f64::min) - 1.0;
let mut ring: Vec<Vec2> = 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()));
for w in l.windows(2) {
acc.add(w[0][0], w[0][1]);
acc.add(w[1][0], w[1][1]);
prims.push(line(v2(w[0][0], w[0][1]), v2(w[1][0], w[1][1]), "elevation-terrain", GROUND_MM, GROUND_INK));
}
}
}
}
// Mit Gelände ersetzt die Silhouette die Grundlinie ([T6]).
if acc.min_x.is_finite() && acc.min_y.is_finite() && !has_terrain {
prims.push(line(v2(acc.min_x, acc.min_y), v2(acc.max_x, acc.min_y), "elevation-ground", GROUND_MM, GROUND_INK));
}
Ok(Some((prims, acc.bounds())))
+5
View File
@@ -436,6 +436,11 @@ pub fn extra_bounds(p: &Project, extra: &[(Primitive, u32)]) -> Bounds {
}
ContextObject::ImportedMesh(m) => mesh_bounds(&m.positions, &mut b),
ContextObject::TerrainMesh(m) => mesh_bounds(&m.positions, &mut b),
ContextObject::Excavation(e) => {
for q in &e.outline {
b.acc(q.x, q.y);
}
}
}
}
b
+141 -11
View File
@@ -24,6 +24,9 @@ const SECTION_VISIBLE_MM: f64 = 0.18;
const SECTION_GROUND_MM: f64 = 0.5;
const SECTION_HIDDEN_MM: f64 = 0.13;
const SECTION_HIDDEN_DASH: [f64; 2] = [0.12, 0.08];
/// [T6] gewachsenes Terrain im Schnitt: gestrichelt, dünner als das gestaltete.
const SECTION_NATURAL_MM: f64 = 0.25;
const SECTION_NATURAL_DASH: [f64; 2] = [0.4, 0.2];
/// Achswinkel geschnittener Wände/Decken für wandrelative Muster (s. `toSection.ts`).
const SECTION_WALL_AXIS_ANGLE_DEG: f64 = 90.0;
/// Decken liegen: wandbezogene Muster laufen waagrecht entlang der Schicht ([109]; vorher 90° wie Wände,
@@ -183,6 +186,8 @@ pub struct Edge {
pub struct Profile {
pub category: Option<String>,
pub pts: Vec<[f64; 2]>,
/// [T6] gewachsenes Terrain (gestrichelt), nur wenn Baugruben das Gelände ändern.
pub natural: bool,
}
/// Ergebnis eines Schnitts (`SectionOutput`).
@@ -192,6 +197,8 @@ pub struct Output {
pub visible: Vec<Edge>,
pub hidden: Vec<Edge>,
pub profiles: Vec<Profile>,
/// [T6] Erdreich unter dem gestalteten Terrain (Band, ohne Gebäude-Inneres), mit Schraffur.
pub earth: Vec<(Vec<[f64; 2]>, HatchRender)>,
}
/// Ein truck-Körper (aus TS, asynchron gebaut): Index in `extrudedSolids` + Netz.
@@ -1492,14 +1499,85 @@ fn append_terrain_profiles(out: &mut Output, p: &Project, base: (f64, f64), u: (
if t.positions.len() < 9 {
continue;
}
let (_, lines) = cut_mesh(&t.positions, &t.indices, base, u);
for line in lines {
let parts = match range {
Some((lo, hi)) => clip_line_to_u(&line, lo - TERRAIN_MARGIN, hi + TERRAIN_MARGIN),
None => vec![line],
};
for pts in parts {
out.profiles.push(Profile { category: t.category_code.clone(), pts });
// [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)];
if st.modified.is_some() {
meshes.push((st.orig.to_flat(-st.datum), true));
}
for ((pos, idx), natural) in meshes {
let (_, lines) = cut_mesh(&pos, &idx, base, u);
for line in lines {
let parts = match range {
Some((lo, hi)) => clip_line_to_u(&line, lo - TERRAIN_MARGIN, hi + TERRAIN_MARGIN),
None => vec![line],
};
for pts in parts {
out.profiles.push(Profile { category: t.category_code.clone(), pts, natural });
}
}
}
}
append_earth(out, p, base, u);
}
/// Tiefe des Erdreich-Bands unter der Geländelinie (m).
const EARTH_BAND: f64 = 1.5;
/// [T6]/[109] Erdreich: Band unter dem gestalteten Terrain mit SIA-Erdreich-Schraffur, ohne das
/// Gebäude-Innere (Grundfläche im Schnitt, von der tiefsten Schnittfläche aufwärts); die geschnittenen
/// Bauteile selbst liegen ohnehin darüber.
fn append_earth(out: &mut Output, p: &Project, base: (f64, f64), u: (f64, f64)) {
let mut band: Vec<crate::flat::Polygon> = Vec::new();
for pr in out.profiles.iter().filter(|pr| !pr.natural && pr.pts.len() >= 2) {
let mut ring = pr.pts.clone();
ring.extend(pr.pts.iter().rev().map(|q| [q[0], q[1] - EARTH_BAND]));
band.push(vec![ring]);
}
if band.is_empty() {
return;
}
let mut band = crate::polygon_bool::union(&band);
// Gebäude-Inneres: Abschnitte der Schnittlinie in der Grundfläche.
let mut holes: Vec<crate::flat::Polygon> = Vec::new();
for poly in crate::site_rules::building_footprint(p) {
let mut ts: Vec<f64> = Vec::new();
for ring in &poly {
let n = ring.len();
for i in 0..n {
let (a, b) = (ring[i], ring[(i + 1) % n]);
// Schnitt der Geraden base + s·u mit der Kante a–b.
let (ex, ey) = (b.x - a.x, b.y - a.y);
let den = u.0 * ey - u.1 * ex;
if den.abs() < 1e-12 {
continue;
}
let (wx, wy) = (a.x - base.0, a.y - base.1);
let s_ = (wx * ey - wy * ex) / den;
let t_ = (wx * u.1 - wy * u.0) / den;
if (0.0..1.0).contains(&t_) {
ts.push(s_);
}
}
}
ts.sort_by(|a, b| a.total_cmp(b));
for w in ts.chunks_exact(2) {
let (u0, u1) = (w[0], w[1]);
let low = out.cuts.iter().flat_map(|c| c.pts.iter()).filter(|q| q[0] >= u0 - 1e-6 && q[0] <= u1 + 1e-6).map(|q| q[1]).fold(f64::INFINITY, f64::min);
if low.is_finite() {
holes.push(vec![vec![[u0, low], [u1, low], [u1, 1e4], [u0, 1e4]]]);
}
}
}
if !holes.is_empty() {
band = crate::polygon_bool::difference(&band, &holes);
}
let hatch = super::style::resolve_hatch(p, "std-h-erdreich", None, None, None)
.unwrap_or(HatchRender { pattern: HatchPattern::Earth, scale: 1.0, angle: 45.0, color: HATCH_INK.into(), line_weight: 0.1, ..no_hatch_base() });
for poly in band {
if let Some(outer) = poly.into_iter().next() {
if outer.len() >= 3 {
out.earth.push((outer, hatch.clone()));
}
}
}
@@ -1608,7 +1686,7 @@ pub fn compute_section(p: &Project, level: &LevelSpec, bodies: &[BodyMesh]) -> R
let cuts = subtract_voids_in_section(cuts, p, base, u);
let mut cuts = parallel_reveal_cuts(cuts, p, &plane, &walls)?;
append_body_sections(&mut cuts, p, bodies, base, u);
let mut out = Output { cuts, visible, hidden, profiles: Vec::new() };
let mut out = Output { cuts, visible, hidden, profiles: Vec::new(), earth: Vec::new() };
append_terrain_profiles(&mut out, p, base, u);
if let Some(d) = level.depth {
filter_by_depth(&mut out, p, &plane, d, &walls, &slabs, &slabs_r);
@@ -1691,6 +1769,14 @@ pub fn section_primitives(out: &Output, mono: bool, hidden_lines: bool, vis: &Vi
let mut prims = Vec::new();
let mut acc = Acc::new();
let shown = |code: &str| vis.visible(code) && vis.render(code);
// [T6] Erdreich zuerst (unter allem), ohne Umriss; Kategorie wie das Gelände.
let terrain_shown = out.profiles.iter().all(|pr| pr.category.as_deref().is_none_or(shown));
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));
}
}
for cp in &out.cuts {
if cp.pts.len() < 3 {
continue;
@@ -1740,7 +1826,13 @@ pub fn section_primitives(out: &Output, mono: bool, hidden_lines: bool, vis: &Vi
for w in pr.pts.windows(2) {
acc.add(w[0][0], w[0][1]);
acc.add(w[1][0], w[1][1]);
prims.push(line(v2(w[0][0], w[0][1]), v2(w[1][0], w[1][1]), "section-terrain", SECTION_GROUND_MM, SECTION_INK));
let mut l = line(v2(w[0][0], w[0][1]), v2(w[1][0], w[1][1]), "section-terrain", if pr.natural { SECTION_NATURAL_MM } else { SECTION_GROUND_MM }, SECTION_INK);
if pr.natural {
if let Primitive::Line { dash, .. } = &mut l {
*dash = Some(Some(SECTION_NATURAL_DASH.to_vec()));
}
}
prims.push(l);
}
}
if hidden_lines {
@@ -1759,7 +1851,8 @@ pub fn section_primitives(out: &Output, mono: bool, hidden_lines: bool, vis: &Vi
acc.add(e.b[0], e.b[1]);
prims.push(line(v2(e.a[0], e.a[1]), v2(e.b[0], e.b[1]), "section-visible", SECTION_VISIBLE_MM, SECTION_VISIBLE_INK));
}
if acc.min_x.is_finite() && acc.max_x > acc.min_x {
// Mit Gelände ersetzt die Geländelinie die Grundlinie ([T6]).
if acc.min_x.is_finite() && acc.max_x > acc.min_x && !(terrain_shown && !out.profiles.is_empty()) {
prims.push(line(v2(acc.min_x, acc.min_y), v2(acc.max_x, acc.min_y), "section-ground", SECTION_GROUND_MM, SECTION_INK));
}
(prims, acc.bounds())
@@ -2456,6 +2549,43 @@ mod tests {
assert!(seams <= 4, "senkrechte Kanten: {seams}");
}
/// [T6]/[68] Gelände mit Baugrube: gestaltetes + gewachsenes Terrain, Erdreich ohne Gebäude-Inneres;
/// Fassaden-Geländehöhen fürs Baurecht.
#[test]
fn gelaende_mit_baugrube_im_schnitt() {
let mut p = sample();
let flat = TerrainMesh {
id: "t".into(),
positions: vec![-50.0, -50.0, 0.0, 50.0, -50.0, 0.0, 50.0, 50.0, 0.0, -50.0, 50.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![Vec2 { x: -1.0, y: -1.0 }, Vec2 { x: 6.0, y: -1.0 }, Vec2 { x: 6.0, y: 5.0 }, Vec2 { x: -1.0, y: 5.0 }],
bottom: -2.0,
..Default::default()
};
p.context = Some(vec![ContextObject::TerrainMesh(flat), ContextObject::Excavation(pit)]);
let out = compute_section(&p, &level(&p, "schnitt-a"), &[]).unwrap().unwrap();
assert!(out.profiles.iter().any(|pr| pr.natural) && out.profiles.iter().any(|pr| !pr.natural));
let designed_min = out.profiles.iter().filter(|pr| !pr.natural).flat_map(|pr| pr.pts.iter().map(|q| q[1])).fold(f64::INFINITY, f64::min);
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)));
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<f64> = 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::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)));
}
#[test]
fn beschnittene_baender_behalten_ihre_ebene() {
// Von der Dominanz beschnittene Wand-/Deckenstücke tragen ihre Kategorie weiter: Ebene aus → weg.
+1
View File
@@ -23,6 +23,7 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
json(&room_program::layout(p, &opt))
}
("siteCheck", _) => json(&site_rules::check_project(p)),
("excavationQuantities", _) => json(&crate::excavation::quantities(p)),
("buildingFootprint", _) => json(&site_rules::building_footprint(p)),
("modelTop", _) => json(&site_rules::model_top(p)),
("shadows", 2) => json(&site_rules::area_out(&sun::shadow_polygons_project(p, sun::SunPosition { azimuth: args[0], elevation: args[1] }))),
+24 -1
View File
@@ -86,6 +86,15 @@ const ELEMENTS: &[Col] = &[
c("ext", "openings.col.ext", 1.4, false, false),
];
const EARTHWORKS: &[Col] = &[
c("name", "sheetTable.col.name", 2.4, false, true),
c("bottom", "sheetTable.col.bottom", 1.3, true, true),
c("area", "sheetTable.col.area", 1.3, true, true),
c("cut", "sheetTable.col.cut", 1.4, true, true),
c("fill", "sheetTable.col.fill", 1.4, true, true),
c("backfill", "sheetTable.col.backfill", 1.6, true, true),
];
/// Schlüssel der Werttexte (Art, aussen/innen, Aufschlag …).
pub const VALUE_KEYS: &[&str] = &[
"sheetTable.v.window",
@@ -111,6 +120,7 @@ pub fn catalog(source: LayoutTableSource) -> &'static [Col] {
LayoutTableSource::Areas => AREAS,
LayoutTableSource::Rooms => ROOMS,
LayoutTableSource::Elements => ELEMENTS,
LayoutTableSource::Earthworks => EARTHWORKS,
}
}
@@ -118,7 +128,7 @@ pub fn catalog(source: LayoutTableSource) -> &'static [Col] {
pub fn catalog_json() -> Value {
let one = |s: &[Col]| s.iter().map(|k| json!({"id": k.id, "key": k.key, "numeric": k.numeric, "default": k.default})).collect::<Vec<_>>();
json!({
"sources": {"openings": one(OPENINGS), "areas": one(AREAS), "rooms": one(ROOMS), "elements": one(ELEMENTS)},
"sources": {"openings": one(OPENINGS), "areas": one(AREAS), "rooms": one(ROOMS), "elements": one(ELEMENTS), "earthworks": one(EARTHWORKS)},
"valueKeys": VALUE_KEYS,
})
}
@@ -250,9 +260,22 @@ fn data_of(p: &Project, t: &LayoutTable, lb: &Labels) -> Data {
LayoutTableSource::Areas => areas_data(p, lb),
LayoutTableSource::Rooms => rooms_data(p),
LayoutTableSource::Elements => elements_data(p, lb),
LayoutTableSource::Earthworks => earthworks_data(p, lb),
}
}
/// [68] Erdarbeiten je Baugrube (m³ gegen das gewachsene Terrain) mit Summenzeile.
fn earthworks_data(p: &Project, lb: &Labels) -> Data {
let q = crate::excavation::quantities(p);
let mut rows: Vec<Vec<Cell>> = q.iter().map(|e| vec![txt(e.name.clone()), num(e.bottom, 2), num(e.bottom_area, 1), num(e.cut, 1), num(e.fill, 1), num(e.backfill, 1)]).collect();
let total_last = q.len() > 1;
if total_last {
let s = |f: fn(&crate::excavation::ExQty) -> f64| q.iter().map(f).sum::<f64>();
rows.push(vec![txt(lb.get("sheetTable.v.total")), num(f64::NAN, 2), num(s(|e| e.bottom_area), 1), num(s(|e| e.cut), 1), num(s(|e| e.fill), 1), num(s(|e| e.backfill), 1)]);
}
Data { rows, total_last }
}
/// Gewählte Spalten als Indizes in den Katalog (unbekannte Kennungen fallen weg; leer ⇒ Standard).
fn column_indices(t: &LayoutTable) -> Vec<usize> {
let cat = catalog(t.source);
+46 -1
View File
@@ -340,6 +340,43 @@ pub struct SiteCheckOut {
pub violation_area: f64,
pub max_top: Option<f64>,
pub height_exceeded: bool,
/// [T6] Geländehöhen an der Fassade (Grundfläche, Ecken + alle ≤ 2 m), Modellbezug; leer ohne Gelände.
pub facade_terrain: Vec<FacadePoint>,
/// Tiefster Punkt des gewachsenen Terrains an der Fassade (massgebendes Terrain, vereinfacht).
pub terrain_min: Option<f64>,
/// Gesamthöhe über dem massgebenden Terrain (`maxTop − terrainMin`); ohne Gelände `None` (dann gilt ±0.00).
pub height_above_terrain: Option<f64>,
}
/// Fassadenpunkt mit gewachsenem und gestaltetem Terrain (Modellbezug; `None` ausserhalb des Geländes).
#[derive(Debug, Serialize)]
pub struct FacadePoint {
pub x: f64,
pub y: f64,
pub natural: Option<f64>,
pub designed: Option<f64>,
}
/// Geländehöhen an der Fassade: Ecken der Aussenringe der Grundfläche und Zwischenpunkte (≤ 2 m).
pub fn facade_terrain(p: &Project) -> Vec<FacadePoint> {
if crate::excavation::terrains(p).is_empty() {
return Vec::new();
}
let mut out = Vec::new();
for poly in building_footprint(p) {
let Some(ring) = poly.first() else { continue };
let n = ring.len();
for i in 0..n {
let (a, b) = (ring[i], ring[(i + 1) % n]);
let k = (hypot2(b.x - a.x, b.y - a.y) / 2.0).ceil().max(1.0) as usize;
for j in 0..k {
let f = j as f64 / k as f64;
let (x, y) = (a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f);
out.push(FacadePoint { x, y, natural: crate::excavation::terrain_z(p, x, y, false), designed: crate::excavation::terrain_z(p, x, y, true) });
}
}
}
out
}
/// Prüft das Modell gegen `siteRules`; `None` ohne (gültiges) Baurecht.
@@ -351,7 +388,12 @@ pub fn check_project(p: &Project) -> Option<SiteCheckOut> {
setbacks: (0..r.parcel.len()).map(|i| r.setbacks.as_ref().and_then(|s| s.get(i)).copied().unwrap_or(r.default_setback)).collect(),
lines: r.building_lines.as_deref().unwrap_or(&[]).iter().map(|l| BuildingLine { a: [l.a.x, l.a.y], b: [l.b.x, l.b.y] }).collect(),
};
let c = check_site_rules(&rules, &footprint_parts(p), r.max_height.unwrap_or(f64::NAN), max_top.unwrap_or(f64::NAN))?;
let facade = facade_terrain(p);
let terrain_min = facade.iter().filter_map(|f| f.natural).reduce(f64::min);
let height_above_terrain = max_top.zip(terrain_min).map(|(t, g)| t - g);
// Mit Gelände zählt die Höhe über dem massgebenden Terrain, sonst über ±0.00.
let top_for_check = height_above_terrain.or(max_top);
let c = check_site_rules(&rules, &footprint_parts(p), r.max_height.unwrap_or(f64::NAN), top_for_check.unwrap_or(f64::NAN))?;
Some(SiteCheckOut {
parcel_area: c.parcel_area,
allowed: area_out(&c.allowed),
@@ -360,5 +402,8 @@ pub fn check_project(p: &Project) -> Option<SiteCheckOut> {
violation_area: c.violation_area,
max_top,
height_exceeded: c.height_exceeded,
facade_terrain: facade,
terrain_min,
height_above_terrain,
})
}
File diff suppressed because it is too large. Load diff
+13
View File
@@ -70,3 +70,16 @@ pub fn terrain_from_contours_json(contours_json: &str, id: &str) -> String {
let c: Value = serde_json::from_str(contours_json).unwrap_or(Value::Null);
crate::cmd_solid::terrain_from_contours(c.as_array().map(Vec::as_slice).unwrap_or(&[]), id).to_string()
}
/// Wie [`terrain_from_contours_json`] mit Optionen ([T6]): `smooth` Glättungsstufen (0–4), `max_edge` grösste
/// Kante in m (≤ 0 automatisch), `breaklines` ≠ 0 erzwingt die Konturen als Bruchkanten.
#[wasm_bindgen]
pub fn terrain_from_contours_opts_json(contours_json: &str, id: &str, smooth: f64, max_edge: f64, breaklines: f64) -> String {
let c: Value = serde_json::from_str(contours_json).unwrap_or(Value::Null);
let o = crate::terrain::TerrainOpts {
smooth: if smooth.is_finite() { smooth.clamp(0.0, 4.0) as u32 } else { 2 },
max_edge: if max_edge.is_finite() { max_edge } else { 0.0 },
breaklines: breaklines != 0.0,
};
crate::cmd_solid::terrain_from_contours_with(c.as_array().map(Vec::as_slice).unwrap_or(&[]), id, o).to_string()
}
+2
View File
@@ -1650,6 +1650,7 @@ export default function App() {
removeContextObject,
removeContextObjects,
generateTerrain,
patchContextObject,
moveGripOf,
moveElementByOf,
moveEdgeOf,
@@ -3246,6 +3247,7 @@ export default function App() {
removeContextObject,
removeContextObjects,
generateTerrain,
patchContextObject,
commitTransformOn,
setElementColor,
setElementWeight,
+66
View File
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import type { Project } from "../model/types";
import { sampleProject } from "../model/sampleProject";
import { excavationQuantities } from "./excavation";
import { generateTerrainFromContours } from "../model/terrain";
/** Flaches Gelände 100 × 100 m auf ±0 und eine Baugrube 10 × 10 m, 3 m tief, 45°. */
function project(): Project {
return {
...sampleProject,
walls: [],
context: [
{
id: "t",
type: "terrainMesh",
name: "Gelände",
positions: [-50, -50, 0, 50, -50, 0, 50, 50, 0, -50, 50, 0],
indices: [0, 1, 2, 0, 2, 3],
},
{
id: "bg",
type: "excavation",
name: "Baugrube",
outline: [
{ x: -5, y: -5 },
{ x: 5, y: -5 },
{ x: 5, y: 5 },
{ x: -5, y: 5 },
],
bottom: -3,
slope: 45,
},
],
};
}
describe("[68] Baugrube", () => {
it("Abtrag wie analytisch (Kegelecken)", () => {
const [q] = excavationQuantities(project());
const exact = 300 + (40 * 9) / 2 + (Math.PI * 27) / 3;
expect(q.id).toBe("bg");
expect(Math.abs(q.cut - exact) / exact).toBeLessThan(0.01);
expect(q.fill).toBeCloseTo(0, 6);
expect(q.bottomArea).toBeCloseTo(100, 6);
});
it("ohne Baugrube leer", () => {
expect(excavationQuantities({ ...sampleProject, context: [] })).toEqual([]);
});
});
describe("[T6] Gelände aus Höhenlinien", () => {
it("glättet ohne Überschwingen und setzt die Äquidistanz", () => {
const ring = (r: number) =>
Array.from({ length: 32 }, (_, i) => ({ x: r * Math.cos((i / 32) * 2 * Math.PI), y: r * Math.sin((i / 32) * 2 * Math.PI) }));
const contours = [0, 1, 2, 3].map((k) => ({ z: k, pts: ring(40 - 10 * k), closed: true }));
const raw = generateTerrainFromContours(contours, { smooth: 0 });
const smooth = generateTerrainFromContours(contours);
expect(smooth.contourInterval).toBe(1);
expect(smooth.indices.length).toBeGreaterThan(raw.indices.length);
const zs = smooth.positions.filter((_, i) => i % 3 === 2);
expect(Math.min(...zs)).toBeGreaterThanOrEqual(-1e-9);
expect(Math.max(...zs)).toBeLessThan(3.5);
expect(Math.max(...zs)).toBeGreaterThan(3);
});
});
+26
View File
@@ -0,0 +1,26 @@
// Erdarbeiten ([68]): Mengen der Baugruben aus dem Rust-Kern (`src-tauri/core/src/excavation.rs`).
// Abtrag/Auftrag je Baugrube gegen das gewachsene Terrain (Integral über ein feines Raster der exakten
// Böschungsfunktion), Hinterfüllung = Abtrag ausserhalb der Gebäude-Grundfläche.
import type { Project } from "../model/types";
import { documentFor } from "../core/document";
export interface ExcavationQuantity {
id: string;
name: string;
/** Sohle (m, Modell ±0.00). */
bottom: number;
/** Sohlenfläche (m²). */
bottomArea: number;
/** Abtrag (m³). */
cut: number;
/** Auftrag/Schüttung (m³). */
fill: number;
/** Hinterfüllung (m³). */
backfill: number;
}
export function excavationQuantities(project: Project): ExcavationQuantity[] {
if (!(project.context ?? []).some((o) => o.type === "excavation")) return [];
return documentFor(project).query<ExcavationQuantity[]>("excavationQuantities");
}
+6
View File
@@ -57,6 +57,12 @@ export interface SiteCheck {
violationArea: number;
maxTop: number | null;
heightExceeded: boolean;
/** [T6] Geländehöhen an der Fassade (gewachsen/gestaltet, Modellbezug); leer ohne Gelände. */
facadeTerrain: { x: number; y: number; natural: number | null; designed: number | null }[];
/** Tiefstes gewachsenes Terrain an der Fassade (massgebendes Terrain, vereinfacht). */
terrainMin: number | null;
/** Gesamthöhe über dem massgebenden Terrain; mit Gelände prüft die Höhe dagegen statt gegen ±0.00. */
heightAboveTerrain: number | null;
}
/** Prüft das Modell gegen `project.siteRules`; `null` ohne (gültiges) Baurecht. Rechnung im Rust-Kern (`site_rules.rs`). */
+4 -1
View File
@@ -84,6 +84,7 @@ import {
addProgramSheet,
defaultSheetLabels,
checkSiteRules,
excavationQuantities,
exportStl,
exportGlb,
exportGltf,
@@ -683,7 +684,9 @@ async function execute(project: Project, file: string, command: string, rest: st
const k = computeKennzahlen(project);
const prog = checkRoomProgram(project);
const baurecht = checkSiteRules(project);
out(args, JSON.stringify({ kennzahlen: k, raumprogramm: prog, baurecht }, null, 2), `${project.name || "projekt"}-kennzahlen.json`);
// [68] Erdarbeiten je Baugrube (Abtrag/Auftrag/Hinterfüllung, m³).
const erdarbeiten = excavationQuantities(project);
out(args, JSON.stringify({ kennzahlen: k, raumprogramm: prog, baurecht, erdarbeiten }, null, 2), `${project.name || "projekt"}-kennzahlen.json`);
return 0;
}
case "raumprogramm": {
+109
View File
@@ -0,0 +1,109 @@
// Baugrube ([68]) — Umriss der Sohle per Klicks; der Kern (`cmd_solid.rs`) legt ein Kontext-Objekt
// `excavation` an (Sohle = Geschoss-Unterkante − 0.30 m, Böschung 45°), das jedes Gelände-Netz unter dem
// Umriss schneidet. Sohle, Böschung und Bermen danach im Panel „Gelände & Kontext".
//
// Schritte:
// 1) „Erster Punkt der Baugrubensohle:" → Punkt
// 2) „Nächster Punkt …" → Punkt … Schliessen per Klick auf den Startpunkt, Option „Schliessen" oder
// Enter (≥ 3 Punkte; bei genau 2 Punkten: Rechteck aus den Ecken).
import type { Command, CommandContext, CommandResult, CommandState, CmdOption, DraftShape, ToolDraft, Vec2 } from "../types";
import { createMutation } from "../createCore";
const EPS = 1e-6;
const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schliesst die Kontur
const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
interface HoleIdle extends CommandState {
phase: "start";
}
interface HoleDrawing extends CommandState {
phase: "next";
points: Vec2[];
cursor: Vec2 | null;
}
type HoleState = HoleIdle | HoleDrawing;
const CLOSE: CmdOption = { id: "close", labelKey: "cmd.polyline.close" };
const UNDO: CmdOption = { id: "undo", labelKey: "cmd.polyline.undo" };
/** Vorschau: Kontur (ab 3 Punkten geschlossen) + Gummiband. */
function holeDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft {
const pts = cursor ? [...points, cursor] : points;
const preview: DraftShape[] = [{ kind: "poly", pts, closed: pts.length >= 3 }];
const draft: ToolDraft = { preview, vertices: points };
const last = points[points.length - 1];
if (cursor && last && dist(last, cursor) >= EPS) draft.hud = { at: cursor, text: `${dist(last, cursor).toFixed(2)} m` };
return draft;
}
/**
* Commit (Kern, `cmd_solid.rs`): Baugrube aus dem Umriss (≥ 3 Punkte wie gezeichnet, 2 Punkte als Rechteck);
* entartet → nichts.
*/
const excavationOps = (points: Vec2[], ctx: CommandContext) => createMutation(ctx, { cmd: "excavation", pts: points });
const idle = (): [CommandState, CommandResult] => [{ phase: "start", lastPoint: null } as HoleIdle, { draft: null, done: true }];
const finish = (points: Vec2[], ctx: CommandContext): [CommandState, CommandResult] => [
{ phase: "start", lastPoint: null } as HoleIdle,
{ draft: null, done: true, commit: excavationOps(points, ctx) },
];
export const excavationCommand: Command = {
name: "excavation",
labelKey: "cmd.excavation.label",
floorOnly: true,
prompt: (s) => ((s as HoleState).phase === "next" ? "cmd.excavation.next" : "cmd.excavation.start"),
accepts: (s) => ((s as HoleState).phase === "next" ? ["point", "option"] : ["point"]),
options: (s) => {
const ps = s as HoleState;
if (ps.phase !== "next") return [];
return ps.points.length >= 3 ? [CLOSE, UNDO] : [UNDO];
},
init: (): HoleIdle => ({ phase: "start", lastPoint: null }),
onInput: (state, input, ctx): [CommandState, CommandResult] => {
const s = state as HoleState;
if (input.kind === "option") {
if (s.phase !== "next") return [s, { draft: null }];
if (input.id === "undo") {
const pts = s.points.slice(0, -1);
if (pts.length === 0) return [{ phase: "start", lastPoint: null } as HoleIdle, { draft: null }];
const ns: HoleDrawing = { phase: "next", points: pts, cursor: s.cursor, lastPoint: pts[pts.length - 1] };
return [ns, { draft: holeDraft(pts, s.cursor) }];
}
if (input.id === "close" && s.points.length >= 3) return finish(s.points, ctx);
return [s, { draft: holeDraft(s.points, s.cursor) }];
}
if (input.kind !== "point") return [s, { draft: s.phase === "next" ? holeDraft(s.points, s.cursor) : null }];
const pt = input.point;
if (s.phase !== "next") {
const ns: HoleDrawing = { phase: "next", points: [pt], cursor: pt, lastPoint: pt };
return [ns, { draft: holeDraft([pt], pt) }];
}
// Klick nahe Startpunkt schliesst den Umriss.
if (s.points.length >= 3 && dist(s.points[0], pt) < CLOSE_HIT) return finish(s.points, ctx);
// Null-Strecke ignorieren.
if (dist(s.points[s.points.length - 1], pt) < EPS) return [s, { draft: holeDraft(s.points, s.cursor) }];
const points = [...s.points, pt];
const ns: HoleDrawing = { phase: "next", points, cursor: pt, lastPoint: pt };
return [ns, { draft: holeDraft(points, pt) }];
},
onMove: (state, point): [CommandState, CommandResult] => {
const s = state as HoleState;
if (s.phase !== "next") return [s, { draft: null }];
const ns: HoleDrawing = { ...s, cursor: point };
return [ns, { draft: holeDraft(s.points, point) }];
},
// Enter/Rechtsklick: ≥ 3 Punkte Polygon, 2 Punkte Rechteck.
onConfirm: (state, ctx): [CommandState, CommandResult] => {
const s = state as HoleState;
if (s.phase === "next" && s.points.length >= 2) return finish(s.points, ctx);
return idle();
},
onCancel: (): [CommandState, CommandResult] => idle(),
};
+4
View File
@@ -63,6 +63,7 @@ import { chamferCommand } from "./cmds/chamfer";
import { multilineCommand } from "./cmds/multiline";
import { importCommand } from "./cmds/import";
import { terrainCommand } from "./cmds/terrain";
import { excavationCommand } from "./cmds/excavation";
import { measureCommand } from "./cmds/measure";
import { sectionLineCommand, viewLineCommand } from "./cmds/sectionline";
import { georefCommand } from "./cmds/georef";
@@ -132,6 +133,7 @@ export const COMMANDS: Record<string, Command> = {
multiline: multilineCommand,
import: importCommand,
terrain: terrainCommand,
excavation: excavationCommand,
measure: measureCommand,
sectionline: sectionLineCommand,
viewline: viewLineCommand,
@@ -265,6 +267,8 @@ export const ALIASES: Record<string, string> = {
parallel: "multiline",
imp: "import",
ter: "terrain",
baugrube: "excavation",
aushub: "excavation",
schnittlinie: "sectionline",
ansichtslinie: "viewline",
bezugspunkt: "georef",
+1
View File
@@ -68,6 +68,7 @@ export type QueryName =
| "programLayout"
| "ivhb"
| "siteCheck"
| "excavationQuantities"
| "buildingFootprint"
| "modelTop"
| "shadows"
+1
View File
@@ -44,6 +44,7 @@ export type { AreaReport, AreaReportOptions } from "../export/areaReport";
export { sunPosition, shadowPolygons, shadowOfPrism, projectLatLon } from "../analysis/sun";
export type { SunPosition } from "../analysis/sun";
export { checkSiteRules, allowedArea, multiPolygonArea, buildingFootprint, modelTop } from "../analysis/siteRules";
export { excavationQuantities, type ExcavationQuantity } from "../analysis/excavation";
export type { SiteCheck } from "../analysis/siteRules";
export { sampleProject } from "../model/sampleProject";
export { parseDxf } from "../io/dxfParser";
+4 -4
View File
@@ -53,12 +53,12 @@ describe("Tabellen auf dem Blatt ([111])", () => {
expect(b.prims.filter((x) => x.k === "text" && x.s === tableLabels(p)["openings.col.mark"]).length).toBe(1);
});
it("alle vier Quellen liefern Primitive; Katalog nennt die Spalten", () => {
it("alle Quellen liefern Primitive; Katalog nennt die Spalten", () => {
const cat = tableCatalog(sampleProject);
expect(Object.keys(cat.sources).sort()).toEqual(["areas", "elements", "openings", "rooms"]);
const p = withTables((["openings", "areas", "rooms", "elements"] as const).map((source) => table({ id: source, source })));
expect(Object.keys(cat.sources).sort()).toEqual(["areas", "earthworks", "elements", "openings", "rooms"]);
const p = withTables((["openings", "areas", "rooms", "elements", "earthworks"] as const).map((source) => table({ id: source, source })));
const out = sheetTables(p, "L1");
expect(out.map((o) => o.id)).toEqual(["openings", "areas", "rooms", "elements"]);
expect(out.map((o) => o.id)).toEqual(["openings", "areas", "rooms", "elements", "earthworks"]);
for (const o of out) expect(o.prims.some((x) => x.k === "text")).toBe(true);
});
+1 -1
View File
@@ -38,7 +38,7 @@ interface Catalog {
valueKeys: string[];
}
export const TABLE_SOURCES: readonly LayoutTableSource[] = ["openings", "areas", "rooms", "elements"];
export const TABLE_SOURCES: readonly LayoutTableSource[] = ["openings", "areas", "rooms", "elements", "earthworks"];
export function tableSourceLabel(s: LayoutTableSource): string {
return t(`sheetTable.source.${s}`);
+25
View File
@@ -1616,6 +1616,9 @@ export const de = {
"cmd.ceilingOpening.start": "Erste Ecke der Aussparung (in einer Decke):",
"cmd.ceilingOpening.corner": "Gegenecke:",
"cmd.roofHole.label": "Dachhof",
"cmd.excavation.label": "Baugrube",
"cmd.excavation.start": "Erster Punkt der Baugrubensohle:",
"cmd.excavation.next": "Nächster Punkt (Enter bei 2 Punkten = Rechteck, ab 3 Punkten Polygon):",
"cmd.roofHole.start": "Erster Punkt des Innenhofs (im Dach):",
"cmd.roofHole.next": "Nächster Punkt (Enter bei 2 Punkten = Rechteck, ab 3 Punkten Polygon):",
"cmd.roof.shape.sattel": "Satteldach",
@@ -1980,6 +1983,20 @@ export const de = {
"site.type.mesh": "Mesh",
"site.type.contours": "Konturen",
"site.type.terrain": "Gelände",
"site.type.excavation": "Baugrube",
"site.smooth": "Glätten",
"site.smooth.hint": "Höhenlinien als Bruchkanten, flache Dreiecke behoben, Fläche ohne Überschwingen geglättet",
"site.excavation.draw": "Baugrube zeichnen",
"site.excavation.hint": "Umriss der Sohle zeichnen; Böschungen schneiden das Gelände",
"site.contourInterval": "Äquidistanz [m]",
"site.contourIndexEvery": "Zähllinie jede",
"site.excavation.bottom": "Sohle [m]",
"site.excavation.slope": "Böschung [°]",
"site.excavation.fillSlope": "Schüttung [°]",
"site.excavation.bermWidth": "Berme [m]",
"site.excavation.bermHeight": "Berme alle [m]",
"site.excavation.qty": "Abtrag {cut} m³ · Auftrag {fill} m³ · Hinterfüllung {backfill} m³",
"site.excavation.noTerrain": "Kein Gelände unter der Baugrube",
"site.type.image": "Luftbild",
"site.group.image": "Luftbild",
"site.dwgHint": "DWG? Zuerst mit dem gratis ODA File Converter in DXF umwandeln.",
@@ -2425,6 +2442,7 @@ export const de = {
"siteRules.inside": "Gebäude innerhalb der zulässigen Fläche",
"siteRules.heightOk": "Höhe {top} m ≤ {max} m",
"siteRules.heightOver": "Höhe {top} m über {max} m",
"siteRules.terrainAtFacade": "Massgebendes Terrain an der Fassade: {z} m (Höhe darüber gemessen)",
"siteRules.defaultSetback": "Grenzabstand",
"siteRules.maxHeight": "Gesamthöhe max.",
"siteRules.edges": "Grenzabstand je Kante ({n})",
@@ -2766,6 +2784,7 @@ export const de = {
"sheetTable.source.areas": "Flächentabelle (SIA 416)",
"sheetTable.source.rooms": "Raumprogramm Soll/Ist",
"sheetTable.source.elements": "Bauteile mit U-Wert",
"sheetTable.source.earthworks": "Erdarbeiten (Baugruben)",
"sheetTable.filter": "Zeigen",
"sheetTable.filter.all": "Fenster und Türen",
"sheetTable.filter.window": "Nur Fenster",
@@ -2813,6 +2832,11 @@ export const de = {
"sheetTable.col.diffPct": "Diff. [%]",
"sheetTable.col.buildup": "Aufbau",
"sheetTable.col.area": "Fläche [m²]",
"sheetTable.col.name": "Bezeichnung",
"sheetTable.col.bottom": "Sohle [m]",
"sheetTable.col.cut": "Abtrag [m³]",
"sheetTable.col.fill": "Auftrag [m³]",
"sheetTable.col.backfill": "Hinterfüllung [m³]",
"sheetTable.col.thickness": "Dicke [cm]",
"sheetTable.v.window": "Fenster",
"sheetTable.v.door": "Tür",
@@ -2998,6 +3022,7 @@ export const de = {
"history.cmd.revcloud": "Revisionswolke",
"history.cmd.roof": "Dach zeichnen",
"history.cmd.roofHole": "Dachöffnung",
"history.cmd.excavation": "Baugrube",
"history.cmd.room": "Raum zeichnen",
"history.cmd.roomInside": "Raum aus Umriss",
"history.cmd.scalebar": "Massstabsbalken",
+25
View File
@@ -1605,6 +1605,9 @@ export const en: Record<TranslationKey, string> = {
"cmd.ceilingOpening.start": "First corner of the opening (inside a slab):",
"cmd.ceilingOpening.corner": "Opposite corner:",
"cmd.roofHole.label": "Roof court",
"cmd.excavation.label": "Excavation",
"cmd.excavation.start": "First point of the excavation bottom:",
"cmd.excavation.next": "Next point (Enter with 2 points = rectangle, 3 or more = polygon):",
"cmd.roofHole.start": "First point of the courtyard (inside the roof):",
"cmd.roofHole.next": "Next point (Enter with 2 points = rectangle, 3 or more = polygon):",
"cmd.roof.shape.sattel": "Gable roof",
@@ -1968,6 +1971,20 @@ export const en: Record<TranslationKey, string> = {
"site.type.mesh": "Mesh",
"site.type.contours": "Contours",
"site.type.terrain": "Terrain",
"site.type.excavation": "Excavation",
"site.smooth": "Smooth",
"site.smooth.hint": "Contours as breaklines, flat triangles fixed, surface smoothed without overshoot",
"site.excavation.draw": "Draw excavation",
"site.excavation.hint": "Draw the outline of the pit bottom; slopes cut the terrain",
"site.contourInterval": "Contour interval [m]",
"site.contourIndexEvery": "Index contour every",
"site.excavation.bottom": "Bottom [m]",
"site.excavation.slope": "Slope [°]",
"site.excavation.fillSlope": "Fill slope [°]",
"site.excavation.bermWidth": "Berm [m]",
"site.excavation.bermHeight": "Berm every [m]",
"site.excavation.qty": "Cut {cut} m³ · Fill {fill} m³ · Backfill {backfill} m³",
"site.excavation.noTerrain": "No terrain below the excavation",
"site.type.image": "Aerial",
"site.group.image": "Aerial imagery",
"site.dwgHint": "DWG? Convert it to DXF first with the free ODA File Converter.",
@@ -2375,6 +2392,7 @@ export const en: Record<TranslationKey, string> = {
"siteRules.inside": "Building inside the buildable area",
"siteRules.heightOk": "Height {top} m ≤ {max} m",
"siteRules.heightOver": "Height {top} m exceeds {max} m",
"siteRules.terrainAtFacade": "Reference terrain at the façade: {z} m (height measured from it)",
"siteRules.defaultSetback": "Boundary distance",
"siteRules.maxHeight": "Max. total height",
"siteRules.edges": "Distance per edge ({n})",
@@ -2753,6 +2771,7 @@ export const en: Record<TranslationKey, string> = {
"sheetTable.source.areas": "Area table (SIA 416)",
"sheetTable.source.rooms": "Room program target/actual",
"sheetTable.source.elements": "Elements with U-value",
"sheetTable.source.earthworks": "Earthworks (excavations)",
"sheetTable.filter": "Show",
"sheetTable.filter.all": "Windows and doors",
"sheetTable.filter.window": "Windows only",
@@ -2800,6 +2819,11 @@ export const en: Record<TranslationKey, string> = {
"sheetTable.col.diffPct": "Diff. [%]",
"sheetTable.col.buildup": "Build-up",
"sheetTable.col.area": "Area [m²]",
"sheetTable.col.name": "Name",
"sheetTable.col.bottom": "Bottom [m]",
"sheetTable.col.cut": "Cut [m³]",
"sheetTable.col.fill": "Fill [m³]",
"sheetTable.col.backfill": "Backfill [m³]",
"sheetTable.col.thickness": "Thickness [cm]",
"sheetTable.v.window": "Window",
"sheetTable.v.door": "Door",
@@ -2984,6 +3008,7 @@ export const en: Record<TranslationKey, string> = {
"history.cmd.revcloud": "Revision cloud",
"history.cmd.roof": "Draw roof",
"history.cmd.roofHole": "Roof opening",
"history.cmd.excavation": "Excavation",
"history.cmd.room": "Draw room",
"history.cmd.roomInside": "Room from outline",
"history.cmd.scalebar": "Scale bar",
+25 -6
View File
@@ -19,14 +19,32 @@ let terrainSeq = 0;
export const TERRAIN_LAYER = "Terrain";
/**
* Erzeugt ein TIN aus Konturen (Rust-Kern, `cmd_solid.rs::terrain_from_contours`): alle endlichen
* Stützpunkte der Konturen als Vertices (Z = Kontur-Höhe, nicht endlich → 0), 2D-Delaunay über die
* (x, y)-Projektion (`delaunay.rs`), Dreiecke mit (nahezu) null Fläche verworfen. Offene und
* geschlossene Konturen gleich; unter 3 Punkten ein leeres Mesh.
* Erzeugt ein Gelände aus Konturen (Rust-Kern, `terrain.rs`): Konturen verdichtet und als Bruchkanten
* erzwungen (constrained Delaunay), flache Dreiecke behoben, adaptiv geglättet ohne Überschwingen.
* `contourInterval` = kleinster Höhenabstand der Konturen (Höhenlinien im Grundriss). Unter 3 Punkten
* ein leeres Mesh.
*/
export function generateTerrainFromContours(contours: Contour[]): TerrainMesh {
export function generateTerrainFromContours(contours: Contour[], opts: TerrainOptions = {}): TerrainMesh {
const id = `terrain-${Date.now()}-${terrainSeq++}`;
return JSON.parse(core().terrain_from_contours_json(toMarkedJson(contours), id)) as TerrainMesh;
const json = core().terrain_from_contours_opts_json(
toMarkedJson(contours),
id,
opts.smooth ?? 2,
opts.maxEdge ?? 0,
opts.breaklines === false ? 0 : 1,
);
return JSON.parse(json) as TerrainMesh;
}
/**
* [T6] Optionen der Gelände-Erzeugung (`terrain.rs`): `smooth` = Glättungsstufen 0–4 (0 = reines TIN mit
* Bruchkanten, Standard 2), `maxEdge` = Verdichtung/grösste Kante in m (0 = automatisch), `breaklines` =
* Höhenlinien als Bruchkanten erzwingen (Standard ja).
*/
export interface TerrainOptions {
smooth?: number;
maxEdge?: number;
breaklines?: boolean;
}
/**
@@ -91,5 +109,6 @@ export function terrainMeshFromGrid(grid: TerrainGrid): TerrainMesh {
categoryCode: TERRAIN_CATEGORY.code,
positions,
indices,
contourInterval: 1,
};
}
+31 -2
View File
@@ -453,7 +453,7 @@ export type ContextImage = {
};
/** Kontext-Objekt (Tag `type`). */
export type ContextObject = ImportedMesh | ContourSet | TerrainMesh | ContextImage;
export type ContextObject = ImportedMesh | ContourSet | TerrainMesh | ContextImage | Excavation;
/**
* Eine einzelne Kontur (Höhenlinie / Polylinie) auf konstanter Höhe `z`. `pts`
@@ -1117,6 +1117,28 @@ export type DrawingLevelKind = "floor" | "section" | "elevation" | "drawing";
*/
export type EndMark = "none" | "arrow" | "arrowOpen" | "dot" | "tick" | "square";
/**
* [68] Baugrube / Geländebearbeitung: Sohle als Umriss auf der Höhe `bottom` (m, Modell ±0.00).
* Ausserhalb steigt die Böschung mit `slope` (Grad, Default 45; je Kante `edgeSlopes`, 0 = Default)
* bis zum Gelände (Abtrag); liegt das Gelände tiefer, fällt eine Schüttung mit `fillSlope` (Default
* 33.7 ≈ 2:3) bis zum Gelände (Auftrag). Bermen: alle `bermHeight` m Höhe eine waagrechte Berme der
* Breite `bermWidth`. Schneidet jedes Gelände-Netz, das den Umriss enthält.
*/
export type Excavation = {
type: "excavation";
id: string;
name: string;
layer?: string;
categoryCode?: string;
outline: Array<Vec2>;
bottom: number;
slope?: number;
fillSlope?: number;
edgeSlopes?: Array<number>;
bermWidth?: number;
bermHeight?: number;
};
/** Ein extrudierter Körper: geschlossenes Profil (Modell-Meter) + Höhe. */
export type ExtrudedSolid = {
id: string;
@@ -1627,7 +1649,7 @@ export type LayoutTable = {
};
/** Quelle einer Blatt-Tabelle ([111]). */
export type LayoutTableSource = "openings" | "areas" | "rooms" | "elements";
export type LayoutTableSource = "openings" | "areas" | "rooms" | "elements" | "earthworks";
/**
* Einfache Textfelder des Titelblocks (Master). Alle optional — leere Felder
@@ -2950,6 +2972,13 @@ export type TerrainMesh = {
* statt mit der Grundfarbe. Fehlt es, bleibt das Gelände einfarbig.
*/
vertexColors?: Array<number>;
/**
* [T6] Äquidistanz der Höhenlinien im Grundriss in m (aus dem Netz neu erzeugt, inkl. Baugruben).
* Fehlt der Wert oder ist er ≤ 0, zeigt der Grundriss nur den Rahmen.
*/
contourInterval?: number;
/** [T6] Jede n-te Höhenlinie ist Zähllinie (dicker, beschriftet). Default 5. */
contourIndexEvery?: number;
};
/** Ein zusammenhängender Textabschnitt mit einheitlicher Formatierung. */
+121 -2
View File
@@ -13,7 +13,7 @@
// Bezeichner englisch, UI-Text/Kommentare deutsch (CONVENTIONS.md). Alle sichtbaren
// Texte über t(...).
import { useState } from "react";
import { useMemo, useState } from "react";
import { t } from "../i18n";
import type { TranslationKey } from "../i18n";
import { usePanelHost } from "./host";
@@ -26,6 +26,7 @@ import { openContextImportWindowNative } from "../native/contextImportWindow";
import { SunStudySection } from "./SunStudySection";
import { SiteRulesSection } from "./SiteRulesSection";
import { PointCloudSection } from "./PointCloudSection";
import { excavationQuantities } from "../core";
/** Typ-spezifisches Badge-Label (i18n-Key) je Kontext-Objekt-Art. */
function typeBadgeKey(obj: ContextObject): TranslationKey {
@@ -38,6 +39,8 @@ function typeBadgeKey(obj: ContextObject): TranslationKey {
return "site.type.terrain";
case "image":
return "site.type.image";
case "excavation":
return "site.type.excavation";
}
}
@@ -53,9 +56,42 @@ function layerOf(obj: ContextObject): string {
return t("site.group.contours");
case "image":
return t("site.group.image");
case "excavation":
return t("site.group.terrain");
}
}
/** 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 (
<label className="site-prop">
<span>{props.label}</span>
<input
type="number"
step={props.step}
min={props.min}
placeholder={props.placeholder}
value={props.value ?? ""}
onChange={(e) => {
const raw = e.target.value.trim();
if (raw === "") return props.onChange(undefined);
const v = Number(raw);
if (Number.isFinite(v)) props.onChange(v);
}}
/>
</label>
);
}
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[] = [];
@@ -73,6 +109,15 @@ 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 <div className="site-qty">{t("site.excavation.noTerrain")}</div>;
return (
<div className="site-qty">
{t("site.excavation.qty", { cut: fmt1(q.cut), fill: fmt1(q.fill), backfill: fmt1(q.backfill) })}
</div>
);
}
export function SitePanel() {
const host = usePanelHost();
const notify = useStore((s) => s.notify);
@@ -89,9 +134,16 @@ export function SitePanel() {
? selectedSet
: (contourSets[0]?.id ?? "");
// [T6] Glätten beim Erzeugen (Bruchkanten werden immer erzwungen).
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;
const id = host.onGenerateTerrain(effectiveSet);
const id = host.onGenerateTerrain(effectiveSet, { smooth: smooth ? 2 : 0 });
if (id === null) {
// Kein sinnvolles TIN — ruhiger Hinweis als Toast (keine harte Fehlerbox;
// window.alert wäre im Tauri-WKWebView ohnehin wirkungslos).
@@ -153,11 +205,22 @@ export function SitePanel() {
{contourSets[0].name}
</span>
)}
<label className="site-check" title={t("site.smooth.hint")}>
<input type="checkbox" checked={smooth} onChange={(e) => setSmooth(e.target.checked)} />
{t("site.smooth")}
</label>
<button type="button" className="site-btn" onClick={onGenerate}>
{t("site.generateTerrain")}
</button>
</div>
)}
{objects.some((o) => o.type === "terrainMesh") && (
<div className="site-actions">
<button type="button" className="site-btn" title={t("site.excavation.hint")} onClick={() => host.onStartExcavation()}>
{t("site.excavation.draw")}
</button>
</div>
)}
<div className="site-sep" />
<SunStudySection />
@@ -213,6 +276,62 @@ export function SitePanel() {
>
×
</button>
{obj.type === "terrainMesh" && (
<div className="site-props">
<NumField
label={t("site.contourInterval")}
value={obj.contourInterval}
step={0.5}
min={0}
placeholder="—"
onChange={patch(obj.id, "contourInterval")}
/>
<NumField
label={t("site.contourIndexEvery")}
value={obj.contourIndexEvery}
step={1}
min={1}
placeholder="5"
onChange={patch(obj.id, "contourIndexEvery")}
/>
</div>
)}
{obj.type === "excavation" && (
<div className="site-props">
<NumField
label={t("site.excavation.bottom")}
value={obj.bottom}
step={0.05}
onChange={(v) => v !== undefined && patch(obj.id, "bottom")(v)}
/>
<NumField label={t("site.excavation.slope")} value={obj.slope} step={5} min={5} placeholder="45" onChange={patch(obj.id, "slope")} />
<NumField
label={t("site.excavation.fillSlope")}
value={obj.fillSlope}
step={5}
min={5}
placeholder="33.7"
onChange={patch(obj.id, "fillSlope")}
/>
<NumField
label={t("site.excavation.bermWidth")}
value={obj.bermWidth}
step={0.25}
min={0}
placeholder="—"
onChange={patch(obj.id, "bermWidth")}
/>
<NumField
label={t("site.excavation.bermHeight")}
value={obj.bermHeight}
step={0.5}
min={0}
placeholder="—"
onChange={patch(obj.id, "bermHeight")}
/>
<ExcavationQty q={quantities.find((x) => x.id === obj.id)} />
</div>
)}
</li>
))}
</ul>
+4 -1
View File
@@ -84,11 +84,14 @@ export function SiteRulesSection() {
{rules.maxHeight !== undefined && check.maxTop !== null && (
<div>
{t(check.heightExceeded ? "siteRules.heightOver" : "siteRules.heightOk", {
top: fmt(check.maxTop, 2),
top: fmt(check.heightAboveTerrain ?? check.maxTop, 2),
max: fmt(rules.maxHeight, 2),
})}
</div>
)}
{check.terrainMin !== null && (
<div>{t("siteRules.terrainAtFacade", { z: fmt(check.terrainMin, 2) })}</div>
)}
</div>
)}
+1 -1
View File
@@ -355,7 +355,7 @@ const TOOLS_2D: ToolId[] = [
"image",
];
const TOOLS_3D: ToolId[] = ["wall", "ceiling", "window", "door", "stair", "room"];
const COMMANDS_3D = ["column", "ceilingopening", "roof", "roofhole", "roofwindow", "dormer", "extrude", "revolve", "loft", "solid", "solidbool", "sectionline", "viewline", "autodim"];
const COMMANDS_3D = ["column", "ceilingopening", "roof", "roofhole", "roofwindow", "dormer", "extrude", "revolve", "loft", "solid", "solidbool", "sectionline", "viewline", "autodim", "excavation"];
const COMMANDS_EDIT = ["move", "copy", "array", "rotate", "mirror", "offset", "multiline", "trim", "break", "extend", "fillet", "chamfer", "join", "defblock", "measure"];
type ToolsView = "list" | "icons";
+6 -1
View File
@@ -40,6 +40,7 @@ import type {
WallType,
} from "../model/types";
import type { MeasurementReadout, SnapSettings, ToolId } from "../tools/types";
import type { TerrainOptions } from "../model/terrain";
import type { Selection } from "../state/selectionInfo";
import type { TextStylePreset } from "../text/richText";
import type { ScheduleKind } from "../export/exportSchedule";
@@ -583,7 +584,11 @@ export interface PanelHostValue {
* Erzeugt aus einem ContourSet (per ID) ein Gelände-TIN. Liefert die neue
* TerrainMesh-ID oder null (unbekannte ID / kein sinnvolles TIN).
*/
onGenerateTerrain: (contourSetId: string) => string | null;
onGenerateTerrain: (contourSetId: string, opts?: TerrainOptions) => string | null;
/** [T6]/[68] Ändert Felder eines Kontext-Objekts (Äquidistanz, Baugruben-Sohle …). */
onPatchContextObject: (id: string, patch: Record<string, unknown>, coalesceKey?: string) => void;
/** [68] Startet den Befehl „Baugrube" (Umriss zeichnen). */
onStartExcavation: () => void;
/**
* Setzt/ersetzt den Georeferenzierungs-Bezug (`Project.geoAnchor`) — welcher
* Modell-Punkt welcher realen LV95-Koordinate entspricht. `undefined` löscht
+11 -6
View File
@@ -9,9 +9,9 @@
//
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import { generateTerrainFromContours } from "../model/terrain";
import { generateTerrainFromContours, type TerrainOptions } from "../model/terrain";
import type { ContextObject, Project } from "../model/types";
import { addItems, fieldOps, removeItems } from "../core/opsBuild";
import { addItems, fieldOps, patchItem, removeItems } from "../core/opsBuild";
import type { CoreOp } from "../core/ops";
import { ensureContextCategories } from "../model/contextCategories";
import type { StoreApi } from "./store";
@@ -32,7 +32,9 @@ export interface SiteSlice {
* weiteres Kontext-Objekt hinzu. Liefert die ID des neuen TerrainMesh, oder
* null, wenn der ContourSet nicht existiert / kein Mesh entsteht.
*/
generateTerrain: (contourSetId: string) => string | null;
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<string, unknown>, coalesceKey?: string) => void;
/** Leert die gesamte Kontext-Schicht. */
clearContext: () => void;
}
@@ -44,7 +46,7 @@ export interface SiteSlice {
*/
type SiteSliceDeps = {
project: Project;
applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[])) => void;
applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[]), coalesceKey?: string) => void;
};
export function createSiteSlice(
@@ -81,13 +83,16 @@ export function createSiteSlice(
get().applyChange((p) => removeItems(p, "context", ids));
},
generateTerrain: (contourSetId) => {
patchContextObject: (id, patch, coalesceKey) =>
get().applyChange((p) => patchItem(p, "context", id, (o) => ({ ...o, ...patch }) as ContextObject), coalesceKey),
generateTerrain: (contourSetId, opts) => {
const ctx = get().project.context ?? [];
const set = ctx.find(
(o) => o.id === contourSetId && o.type === "contourSet",
);
if (!set || set.type !== "contourSet") return null;
const terrain = generateTerrainFromContours(set.contours);
const terrain = generateTerrainFromContours(set.contours, opts);
if (terrain.indices.length === 0) return null; // kein sinnvolles TIN
addToContext([terrain]);
return terrain.id;
+4
View File
@@ -169,6 +169,7 @@ export function usePanelHostBase(opts: {
| "removeContextObject"
| "removeContextObjects"
| "generateTerrain"
| "patchContextObject"
| "commitTransformOn"
| "setElementColor"
| "setElementWeight"
@@ -293,6 +294,7 @@ export function usePanelHostBase(opts: {
removeContextObject,
removeContextObjects,
generateTerrain,
patchContextObject,
commitTransformOn,
setElementColor,
setElementWeight,
@@ -1087,6 +1089,8 @@ export function usePanelHostBase(opts: {
onRemoveContextObject: removeContextObject,
onRemoveContextObjects: removeContextObjects,
onGenerateTerrain: generateTerrain,
onPatchContextObject: patchContextObject,
onStartExcavation: () => onRunCommand("excavation"),
onSetGeoAnchor: (anchor) => {
applyChange((p) => setFieldIfChanged(p, "geoAnchor", anchor));
},
+4
View File
@@ -48,6 +48,8 @@ function contextObjectsBounds(objs: ContextObject[]): Vec2[] | null {
} else if (obj.type === "image") {
acc(obj.min.x, obj.min.y);
acc(obj.max.x, obj.max.y);
} else if (obj.type === "excavation") {
for (const p of obj.outline) acc(p.x, p.y);
} else {
// importedMesh / terrainMesh: flaches (x,y,z…)-Array, Stride 3.
const pos = obj.positions;
@@ -351,6 +353,7 @@ export function useProjectActions(
const removeContextObject = useStore((s) => s.removeContextObject);
const removeContextObjects = useStore((s) => s.removeContextObjects);
const generateTerrain = useStore((s) => s.generateTerrain);
const patchContextObject = useStore((s) => s.patchContextObject);
const moveGripOf = useStore((s) => s.moveGripOf);
const moveElementByOf = useStore((s) => s.moveElementByOf);
const moveEdgeOf = useStore((s) => s.moveEdgeOf);
@@ -465,6 +468,7 @@ export function useProjectActions(
removeContextObject,
removeContextObjects,
generateTerrain,
patchContextObject,
moveGripOf,
moveElementByOf,
moveEdgeOf,
+28
View File
@@ -4945,11 +4945,39 @@ body {
}
.site-panel .site-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
padding: 4px 6px;
border-radius: 5px;
}
/* [T6]/[68] Felder von Gelände und Baugrube unter der Zeile. */
.site-panel .site-props {
flex: 1 0 100%;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 4px 8px;
font-size: 11px;
}
.site-panel .site-prop {
display: flex;
align-items: center;
justify-content: space-between;
gap: 4px;
}
.site-panel .site-prop input {
width: 64px;
}
.site-panel .site-qty {
grid-column: 1 / -1;
color: var(--text-dim, inherit);
}
.site-panel .site-check {
display: flex;
align-items: center;
gap: 3px;
font-size: 11px;
}
.site-panel .site-row:hover {
background: var(--accent-dim);
}
+9
View File
@@ -182,6 +182,15 @@ export function CommandIcon({ name }: { name: string }) {
<line x1="8" y1="3" x2="8" y2="9" strokeDasharray="1.5 1.5" />
</svg>
);
case "excavation":
// Baugrube: Geländelinie mit Grube, Böschungen schräg.
return (
<svg {...common}>
<polyline points="1,5 4,5 6.5,11 9.5,11 12,5 15,5" />
<line x1="4.8" y1="6.5" x2="3.6" y2="6.5" />
<line x1="11.2" y1="6.5" x2="12.4" y2="6.5" />
</svg>
);
case "roofhole":
// Dachhof: Dach-Umriss mit ausgespartem Innenhof.
return (