Merge [70] Flaechentabelle (Flaechenarten nach SIA 416) und IVHB-Kennziffern in Rust, Panel, CSV/SVG/PDF, CLI kennzahlen --sia416 --ivhb
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
20 files changed
+1692
-25
No files matched your search
@@ -352,7 +352,24 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
|
||||
- ✅ **[41] Massenmodelle.** `analysis/kennzahlen.ts`: GF/aGF je Geschoss, GV aus Körpern.
|
||||
- ✅ **[61] Raumprogramm gegen Modell.** `checkRoomProgram`, Editor im Flächenbilanz-Panel (27.10.).
|
||||
- ✅ **[62] Kennzahlenleiste.** Flächenbilanz-Panel: GF/aGF/GV/AZ/ÜZ, Parzellenfläche, je Geschoss (27.10.).
|
||||
- ◐ **[70] Flächentabellen SIA 416 / IVHB.** SIA-416-Bilanz vorhanden (CSV); IVHB offen. IFC (28.10., [B5]): SIA-416-Zonen und Geschoss-GF/NGF als Qto im IFC-Export. · M
|
||||
- ✅ **[70] Flächentabellen (Flächenarten nach SIA 416) / IVHB.** (28.10.) Kern `core/src/flaechen.rs`
|
||||
(Abfragen `areaTable`, `ivhb`), Fassade `analysis/areaTable.ts`, Bericht `export/areaReport.ts`
|
||||
(CSV mit Rückleser, SVG, Vektor-PDF), Abschnitt im Flächenbilanz-Panel (`AreaTableSection.tsx`),
|
||||
CLI `kennzahlen --sia416 --ivhb --format json|csv|svg|pdf [--agsf --gruenflaeche --agf-basis --untergeschosse]`.
|
||||
Tabelle je Geschoss und total: HNF, NNF, NF, VF, FF, NGF, KF, GF, AGF, GV. GF = NGF + KF (Norm); KF aus
|
||||
Wandgrundrissen (abzüglich Räume) + KGF-Räumen hergeleitet. IVHB: GFZ, AZ (aGF-Basis wählbar), BMZ, ÜZ, GZ,
|
||||
Gesamt-/Fassadenhöhe; aGSF = Eingabe, sonst Parzellenfläche/-grenze.
|
||||
Offen / Annahmen: (a) Die ältere Bilanz (`room_area::rollup`, Kennzahlenleiste [62], IFC-Qto) rechnet die AGF
|
||||
noch in die GF — nach SIA 416 gehört sie nicht dazu; angleichen, sobald IFC/Leiste mitgezogen werden.
|
||||
(b) Eingaben aGSF/Grünfläche/aGF-Basis/UG-Anrechnung liegen nur in der Ansicht; Vorschlag Modellfeld
|
||||
`Project.ivhb?: { agsf?, greenArea?, agfBasis?, includeUnderground? }` (+ `KNOWN_KEYS`), damit sie mit dem
|
||||
Projekt gespeichert werden. (c) Massgebendes Terrain = ±0.00 (kein Geländemodell → Baumasse, Höhen).
|
||||
(d) Fassadenhöhe = höchste Wandoberkante (Schnittlinie Fassade/Dach nicht ausgewertet); ÜZ ohne
|
||||
Vorsprünge/Dachüberstände; Stützen/Schächte nur als KGF-Raum in der KF; GV = GF × Geschosshöhe bzw. Körper.
|
||||
(e) Eigene Raumtypen (Büro, Wohnen …): nur Zuordnung Typ → Flächenart in `flaechen::area_kind`, die Tabelle
|
||||
bleibt. (f) Als Layout-Element (Tabelle im Blatt) offen: Layout-Annotationen kennen nur Linie/Rechteck/
|
||||
Text/Bild; bis dahin eigener PDF-/SVG-Export. (g) IVHB-Wortlaut (Anhang 1, Ziff. 5/8) vor Behördenabgabe
|
||||
gegen die kantonale Bauverordnung prüfen. IFC (28.10., [B5]): SIA-416-Zonen und Geschoss-GF/NGF als Qto im IFC-Export. · M
|
||||
- ○ **[42] Varianten.** · L
|
||||
- ✅ **[63] Baulinien, Grenzabstände, zulässige Hülle.** (27.10.) Parzelle/Baulinien aus Auswahl,
|
||||
Grenzabstand pauschal und je Kante, Gesamthöhe; zulässige Fläche und Verstösse im Grundriss.
|
||||
|
||||
@@ -0,0 +1,695 @@
|
||||
//! Flächen- und Kennzahl-Nachweise ([70]): Flächentabelle (Flächenarten nach SIA 416) und
|
||||
//! IVHB-Kennziffern.
|
||||
//!
|
||||
//! # Flächenarten (SIA 416, Ausgabe 2003, „Flächen und Volumen von Gebäuden")
|
||||
//!
|
||||
//! ```text
|
||||
//! GF Geschossfläche = NGF + KF (allseitig umschlossene, überdeckte Grundrissebenen)
|
||||
//! NGF Nettogeschossfl. = NF + VF + FF
|
||||
//! NF Nutzfläche = HNF + NNF
|
||||
//! KF Konstruktionsfläche (Wände, Stützen, Schächte-Wandungen)
|
||||
//! AGF Aussengeschossfläche — NICHT Teil der GF, wird separat ausgewiesen
|
||||
//! GV Gebäudevolumen
|
||||
//! ```
|
||||
//!
|
||||
//! Grundlage der Rechnung ist die *Flächenart* eines Raums (Index in `room_area::CATEGORIES`).
|
||||
//! Wie ein Raum zu seiner Flächenart kommt, steht an genau einer Stelle: [`area_kind`]. Kommen
|
||||
//! später eigene Raumtypen (Büro, Wohnen, Technik …) dazu, genügt dort eine Zuordnung
|
||||
//! Typ → Flächenart; die Tabelle selbst bleibt unverändert.
|
||||
//!
|
||||
//! Abweichung zur älteren Bilanz in `room_area::rollup`/`kennzahlen::compute`: Dort zählt die AGF
|
||||
//! zur „GF". Nach SIA 416 gehört sie nicht dazu (AGF = nicht allseitig umschlossene Flächen).
|
||||
//! Die Tabelle hier folgt der Norm; die alte Bilanz bleibt unverändert.
|
||||
//!
|
||||
//! ## Herleitung aus dem Modell
|
||||
//!
|
||||
//! • HNF/NNF/VF/FF/AGF: Summe der Raumflächen je Geschoss und Flächenart.
|
||||
//! • KF: Räume der Flächenart KGF (von Hand gezeichnete Konstruktionsfläche) vereinigt mit den
|
||||
//! Wandgrundrissen des Geschosses, abzüglich der übrigen Räume (damit eine in einen Raum
|
||||
//! hineingezeichnete Wand nicht doppelt zählt). Wandgrundriss = Rechteck um die Wandachse mit
|
||||
//! der Wanddicke; Wandenden, die auf einer anderen Wand enden, werden um deren halbe Dicke
|
||||
//! verlängert (Eckschluss). Stützen und Schächte fehlen — als KGF-Raum zeichnen.
|
||||
//! • GF = NGF + KF (Summe der Teile, nicht aus einem Umriss gemessen).
|
||||
//! • GV je Geschoss ≈ GF × `floorHeight` (Rohbau-Geschosshöhe OK–OK, ohne Dachaufbauten). Gibt es
|
||||
//! freie Körper (Massenmodell), so ist deren Volumen (Abzugskörper abgezogen) das GV
|
||||
//! ([`GvSource::Solids`]). Beides ist eine Näherung der Hüllenvolumenrechnung der Norm.
|
||||
//!
|
||||
//! # IVHB (Interkantonale Vereinbarung über die Harmonisierung der Baubegriffe, 22.9.2005)
|
||||
//!
|
||||
//! Begriffe und Messweisen im Anhang 1 der IVHB (Höhenmasse, Nutzungsziffern). Die Ziffern sind
|
||||
//! Verhältnisse zur anrechenbaren Grundstücksfläche (aGSF). Der genaue Wortlaut ist vor einer
|
||||
//! Eingabe bei der Behörde gegen die kantonale Bauverordnung zu prüfen.
|
||||
//!
|
||||
//! • AZ = anrechenbare Geschossfläche (aGF) / aGSF. Was als aGF zählt, regeln die Kantone;
|
||||
//! deshalb ist die Basis wählbar ([`AgfBasis`]) und die Anrechnung unterirdischer Geschosse
|
||||
//! eine Option.
|
||||
//! • GFZ = Σ GF (inkl. Konstruktionsflächen) / aGSF — die Geschossflächenziffer dem Namen nach;
|
||||
//! die IVHB selbst kennt nur AZ, GFZ steht in einzelnen kantonalen Bauordnungen.
|
||||
//! • BMZ = Baumasse / aGSF. Baumasse = oberirdisches Gebäudevolumen über dem massgebenden
|
||||
//! Terrain; das Modell hat kein Terrain, als massgebendes Terrain gilt ±0.00.
|
||||
//! • ÜZ = anrechenbare Gebäudefläche (aGbF) / aGSF. aGbF = vereinigte Grundfläche (Wände,
|
||||
//! Räume, freie Körper) der oberirdischen Geschosse; Vorsprünge und Dachüberstände fehlen im
|
||||
//! Modell.
|
||||
//! • GZ = anrechenbare Grünfläche / aGSF. Grünfläche ist nicht aus dem Modell ableitbar
|
||||
//! (kein Terrain-/Bepflanzungsmodell): reines Eingabefeld.
|
||||
//! • Gesamthöhe = höchster Punkt über dem massgebenden Terrain (±0.00). Fassadenhöhe hier als
|
||||
//! höchste Wandoberkante genähert (die Schnittlinie Fassade/Dach wird nicht ausgewertet).
|
||||
//! • aGSF: Eingabe, sonst `Project.parcelArea`, sonst die Fläche der Parzellengrenze des
|
||||
//! Baurechts. Abzüge (Strassen, Wald …) macht der Mensch in der Eingabe.
|
||||
//!
|
||||
//! Keine Werte werden erfunden: Fehlt die aGSF, sind alle Ziffern `None`.
|
||||
|
||||
use crate::flat::Polygon;
|
||||
use crate::flat_read::signed_area;
|
||||
use crate::kennzahlen::{self, RoomIn, SolidIn, CATEGORIES};
|
||||
use crate::model::{DrawingLevel, DrawingLevelKind, Project, Room};
|
||||
use crate::polygon_bool;
|
||||
use crate::site_rules::{multi_polygon_area, wall_corners};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// Flächenart-Indizes (Reihenfolge `room_area::CATEGORIES`).
|
||||
const HNF: usize = 0;
|
||||
const NNF: usize = 1;
|
||||
const VF: usize = 2;
|
||||
const FF: usize = 3;
|
||||
const KGF: usize = 4;
|
||||
const AGF: usize = 5;
|
||||
|
||||
/// Flächenart eines Raums (Index in `room_area::CATEGORIES`, `CATEGORIES` = zählt nicht).
|
||||
/// Einzige Stelle der Zuordnung Raum → Flächenart; heute folgt sie dem Feld `siaCategory`.
|
||||
fn area_kind(r: &Room) -> usize {
|
||||
kennzahlen::category_index(r.sia_category)
|
||||
}
|
||||
|
||||
fn finite(v: f64) -> f64 {
|
||||
if v.is_finite() {
|
||||
v
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Woher das Gebäudevolumen kommt.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GvSource {
|
||||
/// Summe der freien Körper (Massenmodell).
|
||||
Solids,
|
||||
/// Σ GF × Geschosshöhe.
|
||||
Levels,
|
||||
}
|
||||
|
||||
/// Eine Zeile der Flächentabelle (ein Geschoss oder die Summe).
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AreaRow {
|
||||
pub level_id: String,
|
||||
pub name: String,
|
||||
/// Oberkante ≤ ±0.00 (Untergeschoss); in der Summenzeile `false`.
|
||||
pub underground: bool,
|
||||
pub hnf: f64,
|
||||
pub nnf: f64,
|
||||
pub nf: f64,
|
||||
pub vf: f64,
|
||||
pub ff: f64,
|
||||
pub ngf: f64,
|
||||
pub kf: f64,
|
||||
pub gf: f64,
|
||||
pub agf: f64,
|
||||
/// Geschosshöhe (m), in der Summenzeile 0.
|
||||
pub height: f64,
|
||||
/// GF × Geschosshöhe; in der Summenzeile die Summe.
|
||||
pub gv: f64,
|
||||
pub rooms: usize,
|
||||
}
|
||||
|
||||
impl AreaRow {
|
||||
fn add(&mut self, o: &AreaRow) {
|
||||
self.hnf += o.hnf;
|
||||
self.nnf += o.nnf;
|
||||
self.nf += o.nf;
|
||||
self.vf += o.vf;
|
||||
self.ff += o.ff;
|
||||
self.ngf += o.ngf;
|
||||
self.kf += o.kf;
|
||||
self.gf += o.gf;
|
||||
self.agf += o.agf;
|
||||
self.gv += o.gv;
|
||||
self.rooms += o.rooms;
|
||||
}
|
||||
}
|
||||
|
||||
/// Flächentabelle.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AreaTable {
|
||||
/// Geschosse von unten nach oben.
|
||||
pub levels: Vec<AreaRow>,
|
||||
pub total: AreaRow,
|
||||
/// Gebäudevolumen (m³) gemäss `gv_source`.
|
||||
pub gv: f64,
|
||||
pub gv_source: GvSource,
|
||||
/// Hinweise (Schlüssel, die die UI übersetzt): Annahmen, die in die Zahlen eingehen.
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Geschosse (Art `floor`) von unten nach oben.
|
||||
fn floors_sorted(p: &Project) -> Vec<&DrawingLevel> {
|
||||
let mut f: Vec<&DrawingLevel> = p.drawing_levels.iter().filter(|l| l.kind == DrawingLevelKind::Floor).collect();
|
||||
f.sort_by(|a, b| a.base_elevation.unwrap_or(0.0).partial_cmp(&b.base_elevation.unwrap_or(0.0)).unwrap_or(std::cmp::Ordering::Equal));
|
||||
f
|
||||
}
|
||||
|
||||
fn level_height(l: &DrawingLevel) -> f64 {
|
||||
finite(l.floor_height.unwrap_or(0.0)).max(0.0)
|
||||
}
|
||||
|
||||
fn is_underground(l: &DrawingLevel) -> bool {
|
||||
l.base_elevation.unwrap_or(0.0) + level_height(l) <= 1e-9
|
||||
}
|
||||
|
||||
/// Wandgrundrisse eines Geschosses, Enden auf anderen Wänden um deren halbe Dicke verlängert.
|
||||
fn wall_polygons(p: &Project, level_id: &str) -> Vec<Polygon> {
|
||||
struct W {
|
||||
s: [f64; 2],
|
||||
e: [f64; 2],
|
||||
t: f64,
|
||||
}
|
||||
let ws: Vec<W> = p
|
||||
.walls
|
||||
.iter()
|
||||
.filter(|w| w.floor_id == level_id)
|
||||
.map(|w| W { s: [w.start.x, w.start.y], e: [w.end.x, w.end.y], t: finite(p.wall_thickness(w, 0.2)).max(0.0) })
|
||||
.filter(|w| w.s.iter().chain(w.e.iter()).all(|v| v.is_finite()) && (w.e[0] - w.s[0]).hypot(w.e[1] - w.s[1]) > 1e-9)
|
||||
.collect();
|
||||
// Abstand eines Punktes zur Strecke.
|
||||
let dist = |q: [f64; 2], a: [f64; 2], b: [f64; 2]| {
|
||||
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
|
||||
let l2 = dx * dx + dy * dy;
|
||||
let u = (((q[0] - a[0]) * dx + (q[1] - a[1]) * dy) / l2).clamp(0.0, 1.0);
|
||||
(q[0] - (a[0] + u * dx)).hypot(q[1] - (a[1] + u * dy))
|
||||
};
|
||||
const EPS: f64 = 1e-3;
|
||||
ws.iter()
|
||||
.enumerate()
|
||||
.map(|(i, w)| {
|
||||
let ext = |q: [f64; 2]| ws.iter().enumerate().filter(|(j, o)| *j != i && dist(q, o.s, o.e) <= EPS).map(|(_, o)| o.t / 2.0).fold(0.0, f64::max);
|
||||
let (dx, dy) = (w.e[0] - w.s[0], w.e[1] - w.s[1]);
|
||||
let l = dx.hypot(dy);
|
||||
let (ux, uy) = (dx / l, dy / l);
|
||||
let (a, b) = (ext(w.s), ext(w.e));
|
||||
let s = crate::model::Vec2 { x: w.s[0] - ux * a, y: w.s[1] - uy * a };
|
||||
let e = crate::model::Vec2 { x: w.e[0] + ux * b, y: w.e[1] + uy * b };
|
||||
vec![wall_corners(s, e, w.t)]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Räume eines Geschosses als Polygone, gefiltert nach Flächenart.
|
||||
fn room_polygons(p: &Project, level_id: &str, keep: impl Fn(usize) -> bool) -> Vec<Polygon> {
|
||||
p.rooms
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.filter(|r| r.floor_id == level_id && r.boundary.len() >= 3 && keep(area_kind(r)))
|
||||
.filter(|r| r.boundary.iter().all(|v| v.x.is_finite() && v.y.is_finite()))
|
||||
.map(|r| vec![r.boundary.iter().map(|v| [v.x, v.y]).collect()])
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Konstruktionsfläche eines Geschosses (siehe Moduldoku).
|
||||
fn construction_area(p: &Project, level_id: &str) -> f64 {
|
||||
let mut kf_parts = wall_polygons(p, level_id);
|
||||
kf_parts.extend(room_polygons(p, level_id, |c| c == KGF));
|
||||
if kf_parts.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let rooms = room_polygons(p, level_id, |c| c != KGF && c != AGF);
|
||||
finite(multi_polygon_area(&polygon_bool::difference(&kf_parts, &rooms))).max(0.0)
|
||||
}
|
||||
|
||||
fn solids_in(p: &Project) -> Vec<SolidIn> {
|
||||
p.extruded_solids
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.map(|s| SolidIn {
|
||||
subtract: s.operation.as_deref() == Some("subtract"),
|
||||
points: if s.circle.is_some() { vec![] } else { s.points.iter().map(|v| [v.x, v.y]).collect() },
|
||||
circle_r: s.circle.as_ref().map_or(f64::NAN, |c| c.r),
|
||||
height: s.height,
|
||||
taper: s.taper.unwrap_or(0.0),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Flächentabelle des Projekts.
|
||||
pub fn area_table(p: &Project) -> AreaTable {
|
||||
let floors = floors_sorted(p);
|
||||
let mut idx: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
|
||||
for (i, l) in floors.iter().enumerate() {
|
||||
idx.entry(l.id.as_str()).or_insert(i);
|
||||
}
|
||||
let rooms: Vec<RoomIn> = p
|
||||
.rooms
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.filter_map(|r| idx.get(r.floor_id.as_str()).map(|&level| RoomIn { level, category: area_kind(r), boundary: r.boundary.iter().map(|v| [v.x, v.y]).collect() }))
|
||||
.collect();
|
||||
let solids = solids_in(p);
|
||||
let sums = kennzahlen::area_sums(floors.len(), &rooms, &solids, f64::NAN, &[]);
|
||||
|
||||
let mut levels = Vec::with_capacity(floors.len());
|
||||
let mut any_walls = false;
|
||||
for (i, l) in floors.iter().enumerate() {
|
||||
let c: [f64; CATEGORIES] = sums.by_level[i];
|
||||
let nf = c[HNF] + c[NNF];
|
||||
let ngf = nf + c[VF] + c[FF];
|
||||
let kf = construction_area(p, &l.id);
|
||||
any_walls |= p.walls.iter().any(|w| w.floor_id == l.id);
|
||||
let gf = ngf + kf;
|
||||
let height = level_height(l);
|
||||
levels.push(AreaRow {
|
||||
level_id: l.id.clone(),
|
||||
name: l.name.clone(),
|
||||
underground: is_underground(l),
|
||||
hnf: c[HNF],
|
||||
nnf: c[NNF],
|
||||
nf,
|
||||
vf: c[VF],
|
||||
ff: c[FF],
|
||||
ngf,
|
||||
kf,
|
||||
gf,
|
||||
agf: c[AGF],
|
||||
height,
|
||||
gv: gf * height,
|
||||
rooms: rooms.iter().filter(|r| r.level == i).count(),
|
||||
});
|
||||
}
|
||||
let mut total = AreaRow::default();
|
||||
for l in &levels {
|
||||
total.add(l);
|
||||
}
|
||||
let has_solids = solids.iter().any(|s| !s.subtract);
|
||||
let (gv, gv_source) = if has_solids { (sums.gv, GvSource::Solids) } else { (total.gv, GvSource::Levels) };
|
||||
let mut notes = vec!["agfSeparate".to_string()];
|
||||
if any_walls {
|
||||
notes.push("kfFromWalls".to_string());
|
||||
}
|
||||
notes.push(if gv_source == GvSource::Solids { "gvSolids" } else { "gvLevels" }.to_string());
|
||||
AreaTable { levels, total, gv, gv_source, notes }
|
||||
}
|
||||
|
||||
// ── IVHB ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Welche Fläche als „anrechenbare Geschossfläche" der AZ zählt (kantonal verschieden).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgfBasis {
|
||||
/// GF inkl. Konstruktionsflächen (Mauer- und Wandquerschnitte).
|
||||
Gf,
|
||||
/// NGF = NF + VF + FF (häufig: AZ nach altem Recht).
|
||||
#[default]
|
||||
Ngf,
|
||||
/// Nur NF = HNF + NNF.
|
||||
Nf,
|
||||
}
|
||||
|
||||
/// Eingaben und Optionen der IVHB-Rechnung; was das Modell nicht hergibt, kommt hierher.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct IvhbOptions {
|
||||
/// Anrechenbare Grundstücksfläche (m²); sonst Parzellenfläche des Projekts.
|
||||
pub agsf: Option<f64>,
|
||||
/// Anrechenbare Grünfläche (m²).
|
||||
pub green_area: Option<f64>,
|
||||
/// Basis der aGF für die AZ.
|
||||
pub agf_basis: AgfBasis,
|
||||
/// Unterirdische Geschosse in aGF/GFZ mitrechnen (Default: nein).
|
||||
pub include_underground: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgsfSource {
|
||||
Input,
|
||||
ParcelArea,
|
||||
ParcelRing,
|
||||
None,
|
||||
}
|
||||
|
||||
/// IVHB-Kennziffern.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Ivhb {
|
||||
pub agsf: Option<f64>,
|
||||
pub agsf_source: AgsfSource,
|
||||
pub agf_basis: AgfBasis,
|
||||
pub include_underground: bool,
|
||||
/// Summe der angerechneten Geschossflächen GF (für die GFZ).
|
||||
pub gf_sum: f64,
|
||||
/// Anrechenbare Geschossfläche (m²) nach `agf_basis`.
|
||||
pub agf: f64,
|
||||
pub baumasse: f64,
|
||||
/// Anrechenbare Gebäudefläche (m²).
|
||||
pub agbf: f64,
|
||||
pub green_area: Option<f64>,
|
||||
pub az: Option<f64>,
|
||||
pub gfz: Option<f64>,
|
||||
pub bmz: Option<f64>,
|
||||
pub uz: Option<f64>,
|
||||
pub gz: Option<f64>,
|
||||
/// Höchster Punkt über ±0.00.
|
||||
pub total_height: Option<f64>,
|
||||
/// Höchste Wandoberkante über ±0.00 (Näherung der Fassadenhöhe).
|
||||
pub facade_height: Option<f64>,
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
fn positive(v: Option<f64>) -> Option<f64> {
|
||||
v.filter(|x| x.is_finite() && *x > 0.0)
|
||||
}
|
||||
|
||||
/// Oberirdisches Volumen eines Körpers von `base` bis `base + height` (Prisma/Kegelstumpf).
|
||||
fn solid_volume_above(s: &SolidIn, base: f64) -> f64 {
|
||||
let h = finite(s.height);
|
||||
if h <= 0.0 || base + h <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let full = kennzahlen::solid_volume(&s.points, s.circle_r, s.height, s.taper);
|
||||
if base >= 0.0 {
|
||||
return finite(full);
|
||||
}
|
||||
// Schnitt bei Bruchteil f der Höhe: Massstab k(f) = 1 − t·f, Teilstumpf von f bis 1.
|
||||
let f = -base / h;
|
||||
let t = if s.taper.is_nan() { 0.0 } else { s.taper.clamp(0.0, 1.0) };
|
||||
let area = if s.circle_r.is_finite() { std::f64::consts::PI * s.circle_r * s.circle_r } else { signed_area(&s.points).abs() };
|
||||
let (k0, k1) = (1.0 - t * f, 1.0 - t);
|
||||
finite(area * (h + base) * (k0 * k0 + k0 * k1 + k1 * k1) / 3.0)
|
||||
}
|
||||
|
||||
/// Vereinigte Grundfläche der oberirdischen Bauteile (Wände, Räume, positive Körper).
|
||||
fn above_ground_footprint(p: &Project) -> f64 {
|
||||
let mut parts: Vec<Polygon> = Vec::new();
|
||||
for l in p.drawing_levels.iter().filter(|l| l.kind == DrawingLevelKind::Floor && !is_underground(l)) {
|
||||
parts.extend(wall_polygons(p, &l.id));
|
||||
parts.extend(room_polygons(p, &l.id, |c| c < CATEGORIES));
|
||||
}
|
||||
for s in p.extruded_solids.as_deref().unwrap_or(&[]) {
|
||||
if s.operation.as_deref() == Some("subtract") || s.points.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let base = p.floor(&s.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0)) + s.base_offset.unwrap_or(0.0);
|
||||
if base + s.height > 0.0 {
|
||||
parts.push(vec![s.points.iter().map(|v| [v.x, v.y]).collect()]);
|
||||
}
|
||||
}
|
||||
if parts.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
finite(multi_polygon_area(&polygon_bool::union(&parts))).max(0.0)
|
||||
}
|
||||
|
||||
/// IVHB-Kennziffern des Projekts.
|
||||
pub fn ivhb(p: &Project, opt: &IvhbOptions) -> Ivhb {
|
||||
let t = area_table(p);
|
||||
let floors = floors_sorted(p);
|
||||
let counted = |row: &&AreaRow| opt.include_underground || !row.underground;
|
||||
|
||||
let gf_sum: f64 = t.levels.iter().filter(counted).map(|r| r.gf).sum();
|
||||
let agf: f64 = t
|
||||
.levels
|
||||
.iter()
|
||||
.filter(counted)
|
||||
.map(|r| match opt.agf_basis {
|
||||
AgfBasis::Gf => r.gf,
|
||||
AgfBasis::Ngf => r.ngf,
|
||||
AgfBasis::Nf => r.nf,
|
||||
})
|
||||
.sum();
|
||||
|
||||
// Baumasse: oberirdisches Volumen.
|
||||
let baumasse = if t.gv_source == GvSource::Solids {
|
||||
p.extruded_solids
|
||||
.as_deref()
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.zip(solids_in(p))
|
||||
.map(|(s, si)| {
|
||||
let base = p.floor(&s.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0)) + s.base_offset.unwrap_or(0.0);
|
||||
let v = solid_volume_above(&si, base);
|
||||
if si.subtract {
|
||||
-v
|
||||
} else {
|
||||
v
|
||||
}
|
||||
})
|
||||
.sum::<f64>()
|
||||
.max(0.0)
|
||||
} else {
|
||||
floors
|
||||
.iter()
|
||||
.zip(&t.levels)
|
||||
.map(|(l, r)| {
|
||||
let (base, h) = (l.base_elevation.unwrap_or(0.0), r.height);
|
||||
let frac = if h <= 0.0 || base >= 0.0 { 1.0 } else { ((base + h) / h).clamp(0.0, 1.0) };
|
||||
r.gv * frac
|
||||
})
|
||||
.sum()
|
||||
};
|
||||
|
||||
let agbf = above_ground_footprint(p);
|
||||
|
||||
let ring: Vec<[f64; 2]> = p.site_rules.as_ref().map(|r| r.parcel.iter().map(|v| [v.x, v.y]).collect()).unwrap_or_default();
|
||||
let ring_area = if ring.len() >= 3 { finite(signed_area(&ring).abs()) } else { 0.0 };
|
||||
let (agsf, agsf_source) = if let Some(a) = positive(opt.agsf) {
|
||||
(Some(a), AgsfSource::Input)
|
||||
} else if let Some(a) = positive(p.parcel_area) {
|
||||
(Some(a), AgsfSource::ParcelArea)
|
||||
} else if ring_area > 0.0 {
|
||||
(Some(ring_area), AgsfSource::ParcelRing)
|
||||
} else {
|
||||
(None, AgsfSource::None)
|
||||
};
|
||||
let ratio = |x: f64| agsf.map(|a| x / a);
|
||||
let green_area = opt.green_area.filter(|g| g.is_finite() && *g >= 0.0);
|
||||
|
||||
let total_height = crate::site_rules::model_top(p);
|
||||
let facade_height = p
|
||||
.walls
|
||||
.iter()
|
||||
.map(|w| p.wall_vertical_extent(w).1)
|
||||
.filter(|v| v.is_finite())
|
||||
.fold(None, |m: Option<f64>, v| Some(m.map_or(v, |x| x.max(v))));
|
||||
|
||||
let mut notes = vec!["terrainZero".to_string()];
|
||||
if agsf_source == AgsfSource::None {
|
||||
notes.push("agsfMissing".to_string());
|
||||
}
|
||||
if green_area.is_none() {
|
||||
notes.push("greenInput".to_string());
|
||||
}
|
||||
if !opt.include_underground {
|
||||
notes.push("aboveGroundOnly".to_string());
|
||||
}
|
||||
Ivhb {
|
||||
agsf,
|
||||
agsf_source,
|
||||
agf_basis: opt.agf_basis,
|
||||
include_underground: opt.include_underground,
|
||||
gf_sum,
|
||||
agf,
|
||||
baumasse,
|
||||
agbf,
|
||||
green_area,
|
||||
az: ratio(agf),
|
||||
gfz: ratio(gf_sum),
|
||||
bmz: ratio(baumasse),
|
||||
uz: ratio(agbf),
|
||||
gz: green_area.and_then(ratio),
|
||||
total_height,
|
||||
facade_height,
|
||||
notes,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn close(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-4
|
||||
}
|
||||
|
||||
/// Einfaches Haus: Achsen 10 × 8 m, Wände 0.3 m, Räume innen 9.7 × 7.7 m.
|
||||
/// EG (HNF 9.7×4 = 38.8, NNF 9.7×1.7 = 16.49, VF 9.7×2 = 19.4), OG (HNF 74.69),
|
||||
/// UG (FF 74.69) unter ±0.00. Geschosshöhe 2.6 m.
|
||||
fn house() -> Project {
|
||||
let json = r#"{
|
||||
"drawingLevels":[
|
||||
{"id":"ug","name":"UG","kind":"floor","visible":true,"locked":false,"baseElevation":-2.6,"floorHeight":2.6},
|
||||
{"id":"eg","name":"EG","kind":"floor","visible":true,"locked":false,"baseElevation":0,"floorHeight":2.6},
|
||||
{"id":"og","name":"OG","kind":"floor","visible":true,"locked":false,"baseElevation":2.6,"floorHeight":2.6}],
|
||||
"wallTypes":[{"id":"wt","name":"W","layers":[{"componentId":"c","thickness":0.3}]}],
|
||||
"walls":[],"rooms":[]
|
||||
}"#;
|
||||
let mut p: Project = serde_json::from_str(json).unwrap();
|
||||
let v = |x: f64, y: f64| serde_json::json!({"x": x, "y": y});
|
||||
let mut walls = vec![];
|
||||
let mut rooms = vec![];
|
||||
for lvl in ["ug", "eg", "og"] {
|
||||
let pts = [(0.0, 0.0), (10.0, 0.0), (10.0, 8.0), (0.0, 8.0)];
|
||||
for i in 0..4 {
|
||||
let (a, b) = (pts[i], pts[(i + 1) % 4]);
|
||||
walls.push(serde_json::json!({"id":format!("w-{lvl}-{i}"),"type":"wall","floorId":lvl,"categoryCode":"x","start":v(a.0,a.1),"end":v(b.0,b.1),"wallTypeId":"wt","height":2.6}));
|
||||
}
|
||||
let room = |id: &str, cat: &str, y0: f64, y1: f64| {
|
||||
serde_json::json!({"id":format!("{id}-{lvl}"),"type":"room","floorId":lvl,"categoryCode":"x","siaCategory":cat,"name":id,"color":"#fff",
|
||||
"boundary":[v(0.15,y0),v(9.85,y0),v(9.85,y1),v(0.15,y1)]})
|
||||
};
|
||||
match lvl {
|
||||
"eg" => {
|
||||
rooms.push(room("a", "HNF", 0.15, 4.15));
|
||||
rooms.push(room("b", "NNF", 4.15, 5.85));
|
||||
rooms.push(room("c", "VF", 5.85, 7.85));
|
||||
}
|
||||
"og" => rooms.push(room("a", "HNF", 0.15, 7.85)),
|
||||
_ => rooms.push(room("a", "FF", 0.15, 7.85)),
|
||||
}
|
||||
}
|
||||
p.walls = serde_json::from_value(serde_json::Value::Array(walls)).unwrap();
|
||||
p.rooms = Some(serde_json::from_value(serde_json::Value::Array(rooms)).unwrap());
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flaechentabelle_einfaches_haus() {
|
||||
let t = area_table(&house());
|
||||
assert_eq!(t.levels.len(), 3);
|
||||
let eg = &t.levels[1];
|
||||
assert_eq!(eg.name, "EG");
|
||||
assert!(close(eg.hnf, 38.8) && close(eg.nnf, 16.49) && close(eg.vf, 19.4) && close(eg.ff, 0.0));
|
||||
assert!(close(eg.nf, 55.29) && close(eg.ngf, 74.69));
|
||||
// KF = 10.3·8.3 − 9.7·7.7 = 85.49 − 74.69
|
||||
assert!(close(eg.kf, 10.8), "kf {}", eg.kf);
|
||||
assert!(close(eg.gf, 85.49));
|
||||
assert!(close(eg.gf, eg.ngf + eg.kf));
|
||||
assert!(close(eg.gv, 85.49 * 2.6));
|
||||
assert!(t.levels[0].underground && !t.levels[1].underground);
|
||||
assert!(close(t.levels[0].ff, 74.69) && close(t.levels[0].ngf, 74.69));
|
||||
assert!(close(t.total.gf, 3.0 * 85.49));
|
||||
assert!(close(t.total.ngf, 3.0 * 74.69));
|
||||
assert!(close(t.total.kf, 3.0 * 10.8));
|
||||
assert!(close(t.total.hnf, 38.8 + 74.69));
|
||||
assert!(close(t.gv, 3.0 * 85.49 * 2.6));
|
||||
assert_eq!(t.gv_source, GvSource::Levels);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agf_zaehlt_nicht_zur_gf() {
|
||||
let mut p = house();
|
||||
let mut rooms = p.rooms.take().unwrap();
|
||||
let mut balkon = rooms[0].clone();
|
||||
balkon.id = "balkon".into();
|
||||
balkon.floor_id = "eg".into();
|
||||
balkon.sia_category = crate::model::SiaCategory::AGF;
|
||||
balkon.boundary = vec![crate::model::Vec2 { x: 0.0, y: -2.0 }, crate::model::Vec2 { x: 3.0, y: -2.0 }, crate::model::Vec2 { x: 3.0, y: -0.15 }, crate::model::Vec2 { x: 0.0, y: -0.15 }];
|
||||
rooms.push(balkon);
|
||||
p.rooms = Some(rooms);
|
||||
let t = area_table(&p);
|
||||
assert!(close(t.levels[1].agf, 3.0 * 1.85));
|
||||
assert!(close(t.levels[1].gf, 85.49));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn konstruktionsraum_zaehlt_zur_kf() {
|
||||
let mut p = house();
|
||||
let mut rooms = p.rooms.take().unwrap();
|
||||
let mut schacht = rooms[0].clone();
|
||||
schacht.id = "schacht".into();
|
||||
schacht.sia_category = crate::model::SiaCategory::KGF;
|
||||
schacht.floor_id = "eg".into();
|
||||
schacht.boundary = vec![crate::model::Vec2 { x: 20.0, y: 0.0 }, crate::model::Vec2 { x: 21.0, y: 0.0 }, crate::model::Vec2 { x: 21.0, y: 1.0 }, crate::model::Vec2 { x: 20.0, y: 1.0 }];
|
||||
rooms.push(schacht);
|
||||
p.rooms = Some(rooms);
|
||||
assert!(close(area_table(&p).levels[1].kf, 11.8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volumen_aus_koerpern() {
|
||||
let mut p = house();
|
||||
p.extruded_solids = Some(
|
||||
serde_json::from_value(serde_json::json!([{"id":"s","type":"extrudedSolid","levelId":"eg","points":[{"x":0,"y":0},{"x":10,"y":0},{"x":10,"y":8},{"x":0,"y":8}],"height":8.0}])).unwrap(),
|
||||
);
|
||||
let t = area_table(&p);
|
||||
assert_eq!(t.gv_source, GvSource::Solids);
|
||||
assert!(close(t.gv, 640.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ivhb_ziffern_von_hand() {
|
||||
let p = house();
|
||||
// aGSF = 400 m²; oberirdisch = EG + OG.
|
||||
let o = IvhbOptions { agsf: Some(400.0), green_area: Some(160.0), agf_basis: AgfBasis::Ngf, include_underground: false };
|
||||
let r = ivhb(&p, &o);
|
||||
assert_eq!(r.agsf_source, AgsfSource::Input);
|
||||
assert!(close(r.gf_sum, 2.0 * 85.49));
|
||||
assert!(close(r.gfz.unwrap(), 2.0 * 85.49 / 400.0));
|
||||
assert!(close(r.agf, 2.0 * 74.69));
|
||||
assert!(close(r.az.unwrap(), 2.0 * 74.69 / 400.0));
|
||||
// Baumasse = oberirdisches GV = 2 Geschosse × 85.49 × 2.6 (UG liegt unter ±0.00).
|
||||
assert!(close(r.baumasse, 2.0 * 85.49 * 2.6));
|
||||
assert!(close(r.bmz.unwrap(), 2.0 * 85.49 * 2.6 / 400.0));
|
||||
assert!(close(r.agbf, 85.49), "agbf {}", r.agbf);
|
||||
assert!(close(r.uz.unwrap(), 85.49 / 400.0));
|
||||
assert!(close(r.gz.unwrap(), 0.4));
|
||||
// Wände 2.6 m hoch → OK OG = 2.6 + 2.6.
|
||||
assert!(close(r.total_height.unwrap(), 5.2) && close(r.facade_height.unwrap(), 5.2));
|
||||
let r2 = ivhb(&p, &IvhbOptions { include_underground: true, agf_basis: AgfBasis::Gf, ..o.clone() });
|
||||
assert!(close(r2.agf, 3.0 * 85.49) && close(r2.gfz.unwrap(), 3.0 * 85.49 / 400.0));
|
||||
assert!(close(r2.baumasse, 2.0 * 85.49 * 2.6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ivhb_agsf_quellen_und_fehlende_eingaben() {
|
||||
let mut p = house();
|
||||
let r = ivhb(&p, &IvhbOptions::default());
|
||||
assert_eq!(r.agsf_source, AgsfSource::None);
|
||||
assert!(r.az.is_none() && r.gfz.is_none() && r.bmz.is_none() && r.uz.is_none() && r.gz.is_none());
|
||||
assert!(r.notes.contains(&"agsfMissing".to_string()));
|
||||
p.parcel_area = Some(500.0);
|
||||
let r = ivhb(&p, &IvhbOptions::default());
|
||||
assert_eq!(r.agsf_source, AgsfSource::ParcelArea);
|
||||
assert!(r.gz.is_none() && r.uz.is_some());
|
||||
let r = ivhb(&p, &IvhbOptions { agsf: Some(250.0), ..Default::default() });
|
||||
assert_eq!(r.agsf, Some(250.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn baumasse_koerper_ueber_terrain() {
|
||||
let s = SolidIn { subtract: false, points: vec![[0.0, 0.0], [10.0, 0.0], [10.0, 8.0], [0.0, 8.0]], circle_r: f64::NAN, height: 6.0, taper: 0.0 };
|
||||
assert!(close(solid_volume_above(&s, -2.0), 320.0));
|
||||
assert!(close(solid_volume_above(&s, 1.0), 480.0));
|
||||
assert!(close(solid_volume_above(&s, -6.0), 0.0));
|
||||
// Pyramide, Höhe 6: ganz oberirdisch = Vollvolumen; halb versenkt: obere Hälfte = 1/8.
|
||||
let py = SolidIn { taper: 1.0, ..s };
|
||||
assert!(close(solid_volume_above(&py, 0.0), 160.0));
|
||||
assert!(close(solid_volume_above(&py, -3.0), 160.0 / 8.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsinn_ohne_panik() {
|
||||
let mut p = house();
|
||||
p.walls[0].start.x = f64::NAN;
|
||||
p.parcel_area = Some(f64::NAN);
|
||||
let t = area_table(&p);
|
||||
assert!(t.total.gf.is_finite());
|
||||
let r = ivhb(&p, &IvhbOptions { agsf: Some(-1.0), green_area: Some(f64::NAN), ..Default::default() });
|
||||
assert!(r.az.is_none() && r.gz.is_none());
|
||||
let empty = Project::default();
|
||||
assert_eq!(area_table(&empty).levels.len(), 0);
|
||||
assert!(ivhb(&empty, &IvhbOptions::default()).total_height.is_none());
|
||||
}
|
||||
}
|
||||
@@ -162,7 +162,7 @@ pub struct Kennzahlen {
|
||||
pub uez: Option<f64>,
|
||||
}
|
||||
|
||||
fn category_index(c: SiaCategory) -> usize {
|
||||
pub(crate) fn category_index(c: SiaCategory) -> usize {
|
||||
match c {
|
||||
SiaCategory::HNF => 0,
|
||||
SiaCategory::NNF => 1,
|
||||
|
||||
@@ -15,6 +15,7 @@ pub mod sun;
|
||||
pub mod site_rules;
|
||||
pub mod auto_dimensions;
|
||||
pub mod kennzahlen;
|
||||
pub mod flaechen;
|
||||
pub mod bulge;
|
||||
pub mod stair;
|
||||
pub mod joins;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! antwortet. TS ruft sie über `ProjectDocument.query(name, args, text)`.
|
||||
|
||||
use crate::model::Project;
|
||||
use crate::{export_schedule, kennzahlen, model3d, site_rules, sun};
|
||||
use crate::{export_schedule, flaechen, kennzahlen, model3d, site_rules, sun};
|
||||
|
||||
fn json<T: serde::Serialize>(v: &T) -> Result<String, String> {
|
||||
serde_json::to_string(v).map_err(|e| e.to_string())
|
||||
@@ -12,6 +12,11 @@ fn json<T: serde::Serialize>(v: &T) -> Result<String, String> {
|
||||
pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String, String> {
|
||||
match (name, args.len()) {
|
||||
("kennzahlen", _) => json(&kennzahlen::compute(p)),
|
||||
("areaTable", _) => json(&flaechen::area_table(p)),
|
||||
("ivhb", _) => {
|
||||
let opt: flaechen::IvhbOptions = if text.trim().is_empty() { Default::default() } else { serde_json::from_str(text).map_err(|e| format!("ivhb: {e}"))? };
|
||||
json(&flaechen::ivhb(p, &opt))
|
||||
}
|
||||
("siteCheck", _) => json(&site_rules::check_project(p)),
|
||||
("buildingFootprint", _) => json(&site_rules::building_footprint(p)),
|
||||
("modelTop", _) => json(&site_rules::model_top(p)),
|
||||
|
||||
@@ -264,7 +264,7 @@ pub fn area_out(polys: &[Polygon]) -> AreaOut {
|
||||
polys.iter().map(|p| p.iter().map(|r| r.iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect()).collect()).collect()
|
||||
}
|
||||
|
||||
fn wall_corners(start: Vec2, end: Vec2, thickness: f64) -> Vec<[f64; 2]> {
|
||||
pub(crate) fn wall_corners(start: Vec2, end: Vec2, thickness: f64) -> Vec<[f64; 2]> {
|
||||
let h = thickness / 2.0;
|
||||
let (dx, dy) = (end.x - start.x, end.y - start.y);
|
||||
let l = hypot2(dx, dy);
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
// Flächentabelle und IVHB-Kennziffern ([70]). Rechnet der Kern auf dem Projekt-Dokument
|
||||
// (`src-tauri/core/src/flaechen.rs`; Herleitung und Quellen stehen dort im Modulkopf).
|
||||
// Diese Datei ist nur die typisierte Fassade.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { documentFor } from "../core/document";
|
||||
|
||||
/** Eine Zeile der Flächentabelle: ein Geschoss oder die Summe (Flächenarten nach SIA 416). */
|
||||
export interface AreaRow {
|
||||
levelId: string;
|
||||
name: string;
|
||||
/** Oberkante ≤ ±0.00. */
|
||||
underground: boolean;
|
||||
hnf: number;
|
||||
nnf: number;
|
||||
/** NF = HNF + NNF. */
|
||||
nf: number;
|
||||
vf: number;
|
||||
ff: number;
|
||||
/** NGF = NF + VF + FF. */
|
||||
ngf: number;
|
||||
/** Konstruktionsfläche (aus Wandgrundrissen und KGF-Räumen). */
|
||||
kf: number;
|
||||
/** GF = NGF + KF. */
|
||||
gf: number;
|
||||
/** Aussengeschossfläche — nicht Teil der GF. */
|
||||
agf: number;
|
||||
height: number;
|
||||
/** GF × Geschosshöhe. */
|
||||
gv: number;
|
||||
rooms: number;
|
||||
}
|
||||
|
||||
export type GvSource = "solids" | "levels";
|
||||
|
||||
export interface AreaTable {
|
||||
levels: AreaRow[];
|
||||
total: AreaRow;
|
||||
/** Gebäudevolumen (m³) gemäss `gvSource`. */
|
||||
gv: number;
|
||||
gvSource: GvSource;
|
||||
/** Hinweis-Schlüssel (Annahmen der Rechnung). */
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
/** Welche Fläche als „anrechenbare Geschossfläche" der AZ zählt (kantonal verschieden). */
|
||||
export type AgfBasis = "gf" | "ngf" | "nf";
|
||||
|
||||
/** Eingaben, die das Modell nicht hergibt. */
|
||||
export interface IvhbOptions {
|
||||
/** Anrechenbare Grundstücksfläche (m²); sonst Parzellenfläche / Parzellengrenze. */
|
||||
agsf?: number;
|
||||
/** Anrechenbare Grünfläche (m²). */
|
||||
greenArea?: number;
|
||||
agfBasis?: AgfBasis;
|
||||
/** Unterirdische Geschosse mitrechnen. */
|
||||
includeUnderground?: boolean;
|
||||
}
|
||||
|
||||
export type AgsfSource = "input" | "parcelArea" | "parcelRing" | "none";
|
||||
|
||||
export interface Ivhb {
|
||||
agsf: number | null;
|
||||
agsfSource: AgsfSource;
|
||||
agfBasis: AgfBasis;
|
||||
includeUnderground: boolean;
|
||||
gfSum: number;
|
||||
agf: number;
|
||||
baumasse: number;
|
||||
agbf: number;
|
||||
greenArea: number | null;
|
||||
az: number | null;
|
||||
gfz: number | null;
|
||||
bmz: number | null;
|
||||
uz: number | null;
|
||||
gz: number | null;
|
||||
totalHeight: number | null;
|
||||
facadeHeight: number | null;
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
/** SIA-416-Flächentabelle je Geschoss und total. */
|
||||
export function computeAreaTable(project: Project): AreaTable {
|
||||
return documentFor(project).query<AreaTable>("areaTable");
|
||||
}
|
||||
|
||||
/** IVHB-Kennziffern (GFZ, AZ, BMZ, ÜZ, GZ, Höhen). */
|
||||
export function computeIvhb(project: Project, options: IvhbOptions = {}): Ivhb {
|
||||
return documentFor(project).query<Ivhb>("ivhb", [], JSON.stringify(options));
|
||||
}
|
||||
+35
-1
@@ -11,7 +11,7 @@
|
||||
// dossier-cli <projekt.obp> elevation <Name> [--out ansicht.svg]
|
||||
// dossier-cli <projekt.obp> ifc [--ebkph] [--ebenen] (IFC mit eBKP-H-Hauptgruppen bzw. Modell-Ebenen als Klassifikation)
|
||||
// --schema 4|2x3: IFC4 (Standard) oder IFC2x3 (Coordination View 2.0)
|
||||
// dossier-cli <projekt.obp> dxf [--binary] [--scale 100] [--dim-unit cm] [--layout]|dwg|ifc|step|obj|stl|glb|gltf|schedule|kennzahlen|sun [--level EG] [--out datei]
|
||||
// dossier-cli <projekt.obp> dxf [--binary] [--scale 100] [--dim-unit cm] [--layout]|dwg|ifc|step|obj|stl|glb|gltf|schedule|kennzahlen [--sia416] [--ivhb] [--format json|csv|svg|pdf] [--agsf m2] [--gruenflaeche m2] [--agf-basis gf|ngf|nf] [--untergeschosse]|sun [--level EG] [--out datei]
|
||||
// glb/gltf = glTF 2.0 (Y-up, Meter, Geschoss als Eltern; --flat ohne Geschoss-Knoten)
|
||||
// dossier-cli convert <eingabe> <ausgabe> [--cmd "befehl"]… Format nach Endung: dxf/dwg/ifc/obp → obp-Import,
|
||||
// obp → dxf/dwg/ifc/obj/stl/glb/gltf/step; --cmd: weitere Befehle
|
||||
@@ -63,6 +63,12 @@ import {
|
||||
exportProjectStep,
|
||||
exportScheduleCsv,
|
||||
computeKennzahlen,
|
||||
computeAreaTable,
|
||||
computeIvhb,
|
||||
buildAreaReport,
|
||||
areaReportToCsv,
|
||||
areaReportToSvg,
|
||||
buildAreaReportPdf,
|
||||
sunPosition,
|
||||
shadowPolygons,
|
||||
projectLatLon,
|
||||
@@ -620,6 +626,34 @@ async function execute(project: Project, file: string, command: string, rest: st
|
||||
out(args, exportGltf(project, { byLevel: !args.flags.has("flat") }), `${project.name || "projekt"}.gltf`);
|
||||
return 0;
|
||||
case "kennzahlen": {
|
||||
// --sia416 / --ivhb: Flächentabelle bzw. IVHB-Kennziffern [70]; --format json|csv|svg|pdf (Default json).
|
||||
if (args.flags.has("sia416") || args.flags.has("ivhb")) {
|
||||
const num = (k: string): number | undefined => {
|
||||
const v = args.flags.get(k);
|
||||
if (v === undefined) return undefined;
|
||||
const n = Number(v.replace(",", "."));
|
||||
if (!Number.isFinite(n)) throw new Error(`--${k}: keine Zahl`);
|
||||
return n;
|
||||
};
|
||||
const basis = args.flags.get("agf-basis") ?? "ngf";
|
||||
if (basis !== "gf" && basis !== "ngf" && basis !== "nf") throw new Error("--agf-basis: gf, ngf oder nf");
|
||||
const ivhbOptions = { agsf: num("agsf"), greenArea: num("gruenflaeche"), agfBasis: basis, includeUnderground: args.flags.has("untergeschosse") } as const;
|
||||
const wantAreas = args.flags.has("sia416");
|
||||
const wantIvhb = args.flags.has("ivhb");
|
||||
const format = args.flags.get("format") ?? "json";
|
||||
const stem = `${project.name || "projekt"}-flaechen`;
|
||||
if (format === "json") {
|
||||
const json = { ...(wantAreas ? { flaechentabelle: computeAreaTable(project) } : {}), ...(wantIvhb ? { ivhb: computeIvhb(project, ivhbOptions) } : {}) };
|
||||
out(args, JSON.stringify(json, null, 2), `${stem}.json`);
|
||||
return 0;
|
||||
}
|
||||
const report = buildAreaReport(project, { areas: wantAreas, ivhb: wantIvhb, ivhbOptions });
|
||||
if (format === "csv") out(args, areaReportToCsv(report), `${stem}.csv`);
|
||||
else if (format === "svg") out(args, areaReportToSvg(report), `${stem}.svg`);
|
||||
else if (format === "pdf") out(args, new Uint8Array(buildAreaReportPdf(report).output("arraybuffer")), `${stem}.pdf`);
|
||||
else throw new Error("--format: json, csv, svg oder pdf");
|
||||
return 0;
|
||||
}
|
||||
const k = computeKennzahlen(project);
|
||||
const prog = checkRoomProgram(project);
|
||||
const baurecht = checkSiteRules(project);
|
||||
|
||||
@@ -11,6 +11,8 @@ import { diffToOps } from "./ops";
|
||||
/** Abfragen des Kerns (`queries.rs`). */
|
||||
export type QueryName =
|
||||
| "kennzahlen"
|
||||
| "areaTable"
|
||||
| "ivhb"
|
||||
| "siteCheck"
|
||||
| "buildingFootprint"
|
||||
| "modelTop"
|
||||
|
||||
@@ -24,6 +24,10 @@ export type { CoreOp } from "./ops";
|
||||
export type { Project, DrawingLevel } from "../model/types";
|
||||
export { computeKennzahlen, checkRoomProgram, solidVolume } from "../analysis/kennzahlen";
|
||||
export type { Kennzahlen, ProgramCheck } from "../analysis/kennzahlen";
|
||||
export { computeAreaTable, computeIvhb } from "../analysis/areaTable";
|
||||
export type { AreaTable, AreaRow, Ivhb, IvhbOptions, AgfBasis } from "../analysis/areaTable";
|
||||
export { buildAreaReport, areaReportToCsv, parseAreaReportCsv, areaReportToSvg, buildAreaReportPdf } from "../export/areaReport";
|
||||
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";
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Project, Room, Wall } from "../model/types";
|
||||
import { computeAreaTable, computeIvhb } from "../analysis/areaTable";
|
||||
import { areaReportToCsv, areaReportToSvg, buildAreaReport, buildAreaReportPdf, cellText, layoutAreaReport, parseAreaReportCsv } from "./areaReport";
|
||||
|
||||
// Einfaches Haus: Achsen 10 × 8 m, Wände 0.3 m, EG-Räume innen 9.7 × 7.7 m (Handrechnung siehe flaechen.rs).
|
||||
function house(): Project {
|
||||
const base = structuredClone(sampleProject) as Project;
|
||||
const wt = base.wallTypes[0]!;
|
||||
const type = { ...wt, id: "w30", layers: [{ ...wt.layers[0]!, thickness: 0.3 }] };
|
||||
const pts = [[0, 0], [10, 0], [10, 8], [0, 8]] as const;
|
||||
const walls = pts.map((a, i): Wall => {
|
||||
const b = pts[(i + 1) % 4]!;
|
||||
return { ...(base.walls[0] as Wall), id: `hw${i}`, floorId: "eg", start: { x: a[0], y: a[1] }, end: { x: b[0], y: b[1] }, wallTypeId: "w30", height: 2.6, bottom: undefined, top: undefined };
|
||||
});
|
||||
const room = (id: string, cat: Room["siaCategory"], y0: number, y1: number): Room => ({
|
||||
...(base.rooms![0] as Room), id, floorId: "eg", siaCategory: cat, name: id,
|
||||
boundary: [{ x: 0.15, y: y0 }, { x: 9.85, y: y0 }, { x: 9.85, y: y1 }, { x: 0.15, y: y1 }],
|
||||
});
|
||||
return { ...base, name: "Haus", wallTypes: [type], walls, rooms: [room("a", "HNF", 0.15, 4.15), room("b", "NNF", 4.15, 5.85), room("c", "VF", 5.85, 7.85)], openings: [], extrudedSolids: undefined, roofs: undefined, parcelArea: 400 };
|
||||
}
|
||||
|
||||
describe("computeAreaTable", () => {
|
||||
it("einfaches Haus: Flächenarten, KF aus den Wänden, GF = NGF + KF", () => {
|
||||
const t = computeAreaTable(house());
|
||||
const eg = t.levels.find((l) => l.levelId === "eg")!;
|
||||
expect(eg.hnf).toBeCloseTo(38.8, 4);
|
||||
expect(eg.nnf).toBeCloseTo(16.49, 4);
|
||||
expect(eg.vf).toBeCloseTo(19.4, 4);
|
||||
expect(eg.ngf).toBeCloseTo(74.69, 4);
|
||||
expect(eg.kf).toBeCloseTo(10.8, 4);
|
||||
expect(eg.gf).toBeCloseTo(85.49, 4);
|
||||
expect(t.total.gf).toBeCloseTo(85.49, 4);
|
||||
expect(t.gvSource).toBe("levels");
|
||||
expect(t.gv).toBeCloseTo(85.49 * 2.6, 3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeIvhb", () => {
|
||||
it("Ziffern aus Parzellenfläche, Eingaben überschreiben", () => {
|
||||
const p = house();
|
||||
const v = computeIvhb(p);
|
||||
expect(v.agsfSource).toBe("parcelArea");
|
||||
expect(v.gfz).toBeCloseTo(85.49 / 400, 5);
|
||||
expect(v.az).toBeCloseTo(74.69 / 400, 5);
|
||||
expect(v.uz).toBeCloseTo(85.49 / 400, 5);
|
||||
expect(v.gz).toBeNull();
|
||||
const w = computeIvhb(p, { agsf: 200, greenArea: 100, agfBasis: "gf" });
|
||||
expect(w.agsfSource).toBe("input");
|
||||
expect(w.az).toBeCloseTo(85.49 / 200, 5);
|
||||
expect(w.gz).toBeCloseTo(0.5, 9);
|
||||
});
|
||||
it("ohne Parzelle keine Ziffern", () => {
|
||||
const { parcelArea: _p, ...p } = house();
|
||||
const v = computeIvhb(p as Project);
|
||||
expect(v.agsf).toBeNull();
|
||||
expect(v.az).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Bericht", () => {
|
||||
const report = buildAreaReport(house(), { areas: true, ivhb: true, ivhbOptions: { greenArea: 160 } });
|
||||
|
||||
it("hat Flächentabelle, Kennziffern, Höhen und Fussnoten", () => {
|
||||
expect(report.sections).toHaveLength(3);
|
||||
const areas = report.sections[0]!;
|
||||
expect(areas.columns).toContain("NGF");
|
||||
expect(areas.rows.at(-1)!.total).toBe(true);
|
||||
expect(report.notes.some((n) => n.includes("SIA 416"))).toBe(true);
|
||||
});
|
||||
|
||||
it("CSV-Rundreise gibt die ausgegebenen Zahlen zurück", () => {
|
||||
const csv = areaReportToCsv(report);
|
||||
const back = parseAreaReportCsv(csv);
|
||||
expect(back.title).toBe(report.title);
|
||||
expect(back.projectName).toBe("Haus");
|
||||
expect(back.sections).toHaveLength(report.sections.length);
|
||||
report.sections.forEach((s, i) => {
|
||||
expect(back.sections[i]!.heading).toBe(s.heading);
|
||||
expect(back.sections[i]!.columns).toEqual(s.columns);
|
||||
s.rows.forEach((r, j) => {
|
||||
r.cells.forEach((c, k) => {
|
||||
const got = back.sections[i]!.rows[j]![k];
|
||||
if (typeof c === "string") expect(got).toBe(c);
|
||||
else expect(got).toBe(c.n === null ? null : Number(cellText(c)));
|
||||
});
|
||||
});
|
||||
});
|
||||
expect(back.notes).toEqual(report.notes);
|
||||
});
|
||||
|
||||
it("CSV: Felder mit Semikolon und Anführungszeichen bleiben heil", () => {
|
||||
const r = { ...report, projectName: 'Haus "A"; Süd' };
|
||||
expect(parseAreaReportCsv(areaReportToCsv(r)).projectName).toBe('Haus "A"; Süd');
|
||||
});
|
||||
|
||||
it("SVG und PDF entstehen aus derselben Seitenaufteilung", () => {
|
||||
const svg = areaReportToSvg(report);
|
||||
expect(svg.startsWith("<svg")).toBe(true);
|
||||
expect(svg).toContain("NGF");
|
||||
const lay = layoutAreaReport(report);
|
||||
expect(lay.pages.length).toBeGreaterThanOrEqual(1);
|
||||
const pdf = buildAreaReportPdf(report);
|
||||
expect(pdf.getNumberOfPages()).toBe(lay.pages.length);
|
||||
expect(pdf.output("arraybuffer").byteLength).toBeGreaterThan(1000);
|
||||
});
|
||||
|
||||
it("viele Geschosse laufen auf eine zweite Seite", () => {
|
||||
const sec = report.sections[0]!;
|
||||
const rows = Array.from({ length: 60 }, (_, i) => ({ cells: [`G${i}`, ...sec.rows[0]!.cells.slice(1)] }));
|
||||
const lay = layoutAreaReport({ ...report, sections: [{ ...sec, rows }] });
|
||||
expect(lay.pages.length).toBeGreaterThan(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,364 @@
|
||||
// Flächen- und Kennzahlen-Nachweis ([70]): ein Berichtsmodell (Tabellen mit Zahlen), daraus CSV,
|
||||
// SVG und PDF (Vektor, jsPDF) — alle Ausgaben haben dieselbe Quelle.
|
||||
//
|
||||
// • `buildAreaReport`: rechnet über den Kern (`analysis/areaTable.ts`) und beschriftet mit `t()`.
|
||||
// • `areaReportToCsv` / `parseAreaReportCsv`: CSV mit „;" und Punkt als Dezimaltrenner; die
|
||||
// Rückwärtsrichtung gibt die Zahlen so zurück, wie sie ausgegeben wurden (gerundet).
|
||||
// • `layoutAreaReport`: Seitenaufteilung in Papier-mm (A4 quer); `areaReportToSvg` und
|
||||
// `buildAreaReportPdf` zeichnen dieselben Primitive.
|
||||
//
|
||||
// Die Flächenarten folgen SIA 416, die Kennziffern der IVHB; Herleitung im Kern (`flaechen.rs`).
|
||||
|
||||
import { jsPDF } from "jspdf";
|
||||
import type { Project } from "../model/types";
|
||||
import { t } from "../i18n";
|
||||
import { computeAreaTable, computeIvhb } from "../analysis/areaTable";
|
||||
import type { AreaRow, IvhbOptions } from "../analysis/areaTable";
|
||||
|
||||
/** Zelle: Text oder Zahl (`d` Nachkommastellen, `null` = nicht berechenbar). */
|
||||
export type Cell = string | { n: number | null; d: number };
|
||||
|
||||
export interface ReportRow {
|
||||
cells: Cell[];
|
||||
/** Summenzeile (fett, Linie darüber). */
|
||||
total?: boolean;
|
||||
}
|
||||
|
||||
export interface ReportSection {
|
||||
heading: string;
|
||||
columns: string[];
|
||||
/** Relative Spaltenbreiten (Länge = columns). */
|
||||
widths: number[];
|
||||
rows: ReportRow[];
|
||||
}
|
||||
|
||||
export interface AreaReport {
|
||||
title: string;
|
||||
projectName: string;
|
||||
sections: ReportSection[];
|
||||
/** Fussnoten (Quellen, Annahmen). */
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
export interface AreaReportOptions {
|
||||
/** Flächentabelle aufnehmen (Default ja). */
|
||||
areas?: boolean;
|
||||
/** IVHB-Kennziffern aufnehmen (Default nein). */
|
||||
ivhb?: boolean;
|
||||
ivhbOptions?: IvhbOptions;
|
||||
}
|
||||
|
||||
const num = (n: number | null | undefined, d: number): Cell => ({ n: n === undefined || n === null || !Number.isFinite(n) ? null : n, d });
|
||||
|
||||
const AREA_COLUMNS = ["HNF", "NNF", "NF", "VF", "FF", "NGF", "KF", "GF", "AGF", "GV"];
|
||||
|
||||
function areaCells(r: AreaRow): Cell[] {
|
||||
return [r.hnf, r.nnf, r.nf, r.vf, r.ff, r.ngf, r.kf, r.gf, r.agf].map((v) => num(v, 2)).concat(num(r.gv, 1));
|
||||
}
|
||||
|
||||
/** Baut den Bericht aus dem Projekt. */
|
||||
export function buildAreaReport(project: Project, opts: AreaReportOptions = {}): AreaReport {
|
||||
const sections: ReportSection[] = [];
|
||||
const notes: string[] = [];
|
||||
const addNotes = (keys: string[]) => {
|
||||
for (const k of keys) {
|
||||
const text = t(`areas.note.${k}`);
|
||||
if (!notes.includes(text)) notes.push(text);
|
||||
}
|
||||
};
|
||||
if (opts.areas ?? true) {
|
||||
const table = computeAreaTable(project);
|
||||
const rows: ReportRow[] = table.levels.map((l) => ({ cells: [l.name, ...areaCells(l)] }));
|
||||
// Summenzeile: das GV ist das Gebäudevolumen gemäss Quelle (Körper oder Geschosse).
|
||||
rows.push({ total: true, cells: [t("areas.total"), ...areaCells(table.total).slice(0, 9), num(table.gv, 1)] });
|
||||
sections.push({
|
||||
heading: `${t("areas.table")} [m², GV m³]`,
|
||||
columns: [t("areas.level"), ...AREA_COLUMNS],
|
||||
widths: [3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2.4],
|
||||
rows,
|
||||
});
|
||||
notes.push(t("areas.foot.sia"));
|
||||
addNotes(table.notes);
|
||||
}
|
||||
if (opts.ivhb) {
|
||||
const v = computeIvhb(project, opts.ivhbOptions);
|
||||
const basis = t(`areas.basis.${v.agfBasis}`);
|
||||
const ratio = (key: string, formula: string, numerator: number | null, value: number | null): ReportRow => ({
|
||||
cells: [t(`areas.ratio.${key}`), formula, num(numerator, 2), num(v.agsf, 2), num(value, 3)],
|
||||
});
|
||||
sections.push({
|
||||
heading: `${t("areas.ivhb.title")} · ${t("areas.agsf.source")}: ${t(`areas.src.${v.agsfSource}`)}`,
|
||||
columns: [t("areas.col.ratio"), t("areas.col.formula"), t("areas.col.numerator"), t("areas.col.agsf"), t("areas.col.value")],
|
||||
widths: [4, 3.2, 1.6, 1.6, 1.2],
|
||||
rows: [
|
||||
ratio("gfz", t("areas.formula.gfz"), v.gfSum, v.gfz),
|
||||
ratio("az", t("areas.formula.az", { basis }), v.agf, v.az),
|
||||
ratio("bmz", t("areas.formula.bmz"), v.baumasse, v.bmz),
|
||||
ratio("uz", t("areas.formula.uz"), v.agbf, v.uz),
|
||||
ratio("gz", t("areas.formula.gz"), v.greenArea, v.gz),
|
||||
],
|
||||
});
|
||||
sections.push({
|
||||
heading: t("areas.heights"),
|
||||
columns: [t("areas.col.ratio"), "[m]"],
|
||||
widths: [6, 1.5],
|
||||
rows: [
|
||||
{ cells: [t("areas.height.total"), num(v.totalHeight, 2)] },
|
||||
{ cells: [t("areas.height.facade"), num(v.facadeHeight, 2)] },
|
||||
],
|
||||
});
|
||||
notes.push(t("areas.foot.ivhb"));
|
||||
addNotes(v.notes);
|
||||
}
|
||||
return { title: t("areas.title"), projectName: project.name ?? "", sections, notes };
|
||||
}
|
||||
|
||||
// ── CSV ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
function csvField(v: string): string {
|
||||
return /[",\n\r;]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
|
||||
}
|
||||
|
||||
/** Zelle als Text, so wie sie ausgegeben wird (Punkt als Dezimaltrenner, `null` = leer). */
|
||||
export function cellText(c: Cell): string {
|
||||
if (typeof c === "string") return c;
|
||||
return c.n === null ? "" : c.n.toFixed(c.d);
|
||||
}
|
||||
|
||||
/** CSV des Berichts: Titel, Projekt, dann je Abschnitt Überschrift, Kopf, Zeilen; Fussnoten mit „* ". */
|
||||
export function areaReportToCsv(report: AreaReport, delimiter = ";"): string {
|
||||
const line = (cells: string[]) => cells.map(csvField).join(delimiter);
|
||||
const out: string[] = [line([report.title]), line([report.projectName]), ""];
|
||||
for (const s of report.sections) {
|
||||
out.push(line([s.heading]), line(s.columns));
|
||||
for (const r of s.rows) out.push(line(r.cells.map(cellText)));
|
||||
out.push("");
|
||||
}
|
||||
for (const n of report.notes) out.push(line([`* ${n}`]));
|
||||
return out.join("\n") + "\n";
|
||||
}
|
||||
|
||||
export interface ParsedSection {
|
||||
heading: string;
|
||||
columns: string[];
|
||||
/** Zahlen als `number` (Zelle leer → `null` an Zahlenstellen), Texte als `string`. */
|
||||
rows: (string | number | null)[][];
|
||||
}
|
||||
|
||||
export interface ParsedReport {
|
||||
title: string;
|
||||
projectName: string;
|
||||
sections: ParsedSection[];
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
/** Zerlegt CSV-Text in Zeilen von Feldern (Anführungszeichen, Trenner, Zeilenumbruch im Feld). */
|
||||
function parseCsvRows(text: string, delimiter: string): string[][] {
|
||||
const rows: string[][] = [];
|
||||
let row: string[] = [];
|
||||
let field = "";
|
||||
let quoted = false;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const c = text[i]!;
|
||||
if (quoted) {
|
||||
if (c === '"') {
|
||||
if (text[i + 1] === '"') {
|
||||
field += '"';
|
||||
i++;
|
||||
} else quoted = false;
|
||||
} else field += c;
|
||||
} else if (c === '"') quoted = true;
|
||||
else if (c === delimiter) {
|
||||
row.push(field);
|
||||
field = "";
|
||||
} else if (c === "\n" || c === "\r") {
|
||||
if (c === "\r" && text[i + 1] === "\n") i++;
|
||||
row.push(field);
|
||||
rows.push(row);
|
||||
row = [];
|
||||
field = "";
|
||||
} else field += c;
|
||||
}
|
||||
if (field !== "" || row.length > 0) {
|
||||
row.push(field);
|
||||
rows.push(row);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
const NUMBER = /^-?\d+(\.\d+)?$/;
|
||||
|
||||
/** Liest eine mit {@link areaReportToCsv} geschriebene CSV zurück (Rundreise). */
|
||||
export function parseAreaReportCsv(text: string, delimiter = ";"): ParsedReport {
|
||||
const rows = parseCsvRows(text, delimiter);
|
||||
// Blöcke zwischen Leerzeilen (eine Leerzeile = ein Feld "").
|
||||
const blocks: string[][][] = [];
|
||||
let cur: string[][] = [];
|
||||
for (const r of rows) {
|
||||
if (r.length === 1 && r[0] === "") {
|
||||
if (cur.length) blocks.push(cur);
|
||||
cur = [];
|
||||
} else cur.push(r);
|
||||
}
|
||||
if (cur.length) blocks.push(cur);
|
||||
const head = blocks.shift() ?? [];
|
||||
const result: ParsedReport = { title: head[0]?.[0] ?? "", projectName: head[1]?.[0] ?? "", sections: [], notes: [] };
|
||||
for (const b of blocks) {
|
||||
if (b[0]?.[0]?.startsWith("* ")) {
|
||||
for (const r of b) result.notes.push(r[0]!.slice(2));
|
||||
continue;
|
||||
}
|
||||
result.sections.push({
|
||||
heading: b[0]?.[0] ?? "",
|
||||
columns: b[1] ?? [],
|
||||
rows: b.slice(2).map((r) => r.map((c, i) => (NUMBER.test(c) ? Number(c) : i === 0 || c !== "" ? c : null))),
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── Seitenaufteilung (Papier-mm) und Ausgabe ─────────────────────────────────
|
||||
|
||||
type Prim =
|
||||
| { k: "text"; x: number; y: number; s: string; size: number; bold?: boolean; align?: "left" | "right" }
|
||||
| { k: "line"; x1: number; y1: number; x2: number; y2: number; w: number };
|
||||
|
||||
export interface ReportLayoutOptions {
|
||||
/** Blattgrösse in mm (Default A4 quer). */
|
||||
width?: number;
|
||||
height?: number;
|
||||
margin?: number;
|
||||
}
|
||||
|
||||
/** Zeilenumbruch nach Zeichenzahl (Helvetica ≈ 0.5 em je Zeichen). */
|
||||
function wrap(text: string, maxMm: number, sizePt: number): string[] {
|
||||
const per = Math.max(10, Math.floor(maxMm / (sizePt * 0.3528 * 0.5)));
|
||||
const words = text.split(/\s+/);
|
||||
const lines: string[] = [];
|
||||
let cur = "";
|
||||
for (const w of words) {
|
||||
if (cur && (cur + " " + w).length > per) {
|
||||
lines.push(cur);
|
||||
cur = w;
|
||||
} else cur = cur ? cur + " " + w : w;
|
||||
}
|
||||
if (cur) lines.push(cur);
|
||||
return lines;
|
||||
}
|
||||
|
||||
/** Teilt den Bericht in Seiten mit Zeichen-Primitiven. */
|
||||
export function layoutAreaReport(report: AreaReport, o: ReportLayoutOptions = {}): { width: number; height: number; pages: Prim[][] } {
|
||||
const width = o.width ?? 297;
|
||||
const height = o.height ?? 210;
|
||||
const m = o.margin ?? 12;
|
||||
const inner = width - 2 * m;
|
||||
const rowH = 6;
|
||||
const pages: Prim[][] = [[]];
|
||||
let y = m;
|
||||
const page = () => pages[pages.length - 1]!;
|
||||
const ensure = (h: number) => {
|
||||
if (y + h > height - m) {
|
||||
pages.push([]);
|
||||
y = m;
|
||||
}
|
||||
};
|
||||
|
||||
page().push({ k: "text", x: m, y: y + 5, s: report.title, size: 15, bold: true });
|
||||
y += 8;
|
||||
if (report.projectName) {
|
||||
page().push({ k: "text", x: m, y: y + 4, s: report.projectName, size: 10 });
|
||||
y += 6;
|
||||
}
|
||||
y += 4;
|
||||
|
||||
for (const s of report.sections) {
|
||||
ensure(rowH * 3 + 6);
|
||||
page().push({ k: "text", x: m, y: y + 4, s: s.heading, size: 10, bold: true });
|
||||
y += 7;
|
||||
const sum = s.widths.reduce((a, b) => a + b, 0);
|
||||
const xs: number[] = [];
|
||||
let x = m;
|
||||
for (const w of s.widths) {
|
||||
xs.push(x);
|
||||
x += (w / sum) * inner;
|
||||
}
|
||||
xs.push(x);
|
||||
const drawRow = (cells: string[], bold: boolean, numeric: boolean[], line: "top" | "bottom" | "none") => {
|
||||
ensure(rowH);
|
||||
if (line === "top") page().push({ k: "line", x1: m, y1: y, x2: m + inner, y2: y, w: 0.35 });
|
||||
cells.forEach((c, i) => {
|
||||
const right = numeric[i] === true;
|
||||
page().push({ k: "text", x: right ? xs[i + 1]! - 1.5 : xs[i]! + 1.5, y: y + 4.2, s: c, size: 8.5, bold, align: right ? "right" : "left" });
|
||||
});
|
||||
y += rowH;
|
||||
if (line === "bottom") page().push({ k: "line", x1: m, y1: y, x2: m + inner, y2: y, w: 0.35 });
|
||||
};
|
||||
const isNum = (i: number) => s.rows.some((r) => typeof r.cells[i] === "object");
|
||||
const numeric = s.columns.map((_, i) => isNum(i));
|
||||
drawRow(s.columns, true, numeric, "none");
|
||||
page().push({ k: "line", x1: m, y1: y, x2: m + inner, y2: y, w: 0.35 });
|
||||
for (const r of s.rows) {
|
||||
drawRow(r.cells.map((c) => (typeof c === "string" ? c : c.n === null ? "–" : c.n.toFixed(c.d))), r.total === true, numeric, r.total ? "top" : "none");
|
||||
}
|
||||
page().push({ k: "line", x1: m, y1: y, x2: m + inner, y2: y, w: 0.35 });
|
||||
y += 6;
|
||||
}
|
||||
|
||||
for (const n of report.notes) {
|
||||
const lines = wrap(n, inner, 7.5);
|
||||
ensure(lines.length * 3.4 + 1);
|
||||
for (const l of lines) {
|
||||
page().push({ k: "text", x: m, y: y + 2.8, s: l, size: 7.5 });
|
||||
y += 3.4;
|
||||
}
|
||||
y += 1;
|
||||
}
|
||||
const total = pages.length;
|
||||
pages.forEach((p, i) => {
|
||||
p.push({ k: "text", x: width - m, y: height - m / 2, s: `${i + 1} / ${total}`, size: 7, align: "right" });
|
||||
});
|
||||
return { width, height, pages };
|
||||
}
|
||||
|
||||
const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
|
||||
/** SVG der ersten Seite (Papier-mm, viewBox in mm); `page` wählt eine andere. */
|
||||
export function areaReportToSvg(report: AreaReport, page = 0, o: ReportLayoutOptions = {}): string {
|
||||
const lay = layoutAreaReport(report, o);
|
||||
const prims = lay.pages[Math.min(page, lay.pages.length - 1)] ?? [];
|
||||
const body = prims
|
||||
.map((p) =>
|
||||
p.k === "line"
|
||||
? `<line x1="${p.x1}" y1="${p.y1}" x2="${p.x2}" y2="${p.y2}" stroke="#111" stroke-width="${p.w}"/>`
|
||||
: `<text x="${p.x}" y="${p.y}" font-size="${(p.size * 0.3528).toFixed(3)}" font-family="Helvetica, Arial, sans-serif" font-weight="${p.bold ? 700 : 400}" text-anchor="${p.align === "right" ? "end" : "start"}" fill="#111">${esc(p.s)}</text>`,
|
||||
)
|
||||
.join("\n");
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" width="${lay.width}mm" height="${lay.height}mm" viewBox="0 0 ${lay.width} ${lay.height}">\n<rect width="${lay.width}" height="${lay.height}" fill="#fff"/>\n${body}\n</svg>\n`;
|
||||
}
|
||||
|
||||
/** Die eingebaute Helvetica kennt nur WinAnsi: Zeichen ausserhalb ersetzen. */
|
||||
function pdfSafe(s: string): string {
|
||||
return s.replace(/Σ/g, "Sum").replace(/≈/g, "~").replace(/[–−]/g, "-");
|
||||
}
|
||||
|
||||
/** Vektor-PDF des Berichts (A4 quer, eine oder mehrere Seiten). */
|
||||
export function buildAreaReportPdf(report: AreaReport, o: ReportLayoutOptions = {}): jsPDF {
|
||||
const lay = layoutAreaReport(report, o);
|
||||
const doc = new jsPDF({ unit: "mm", format: [lay.width, lay.height], orientation: lay.width > lay.height ? "landscape" : "portrait", compress: true });
|
||||
lay.pages.forEach((prims, i) => {
|
||||
if (i > 0) doc.addPage([lay.width, lay.height], lay.width > lay.height ? "landscape" : "portrait");
|
||||
doc.setTextColor(17, 17, 17);
|
||||
doc.setDrawColor(17, 17, 17);
|
||||
for (const p of prims) {
|
||||
if (p.k === "line") {
|
||||
doc.setLineWidth(p.w);
|
||||
doc.line(p.x1, p.y1, p.x2, p.y2);
|
||||
} else {
|
||||
doc.setFont("helvetica", p.bold ? "bold" : "normal");
|
||||
doc.setFontSize(p.size);
|
||||
doc.text(pdfSafe(p.s), p.x, p.y, { align: p.align ?? "left" });
|
||||
}
|
||||
}
|
||||
});
|
||||
return doc;
|
||||
}
|
||||
+54
-1
@@ -1582,11 +1582,64 @@ export const de = {
|
||||
|
||||
// ── Flächenbilanz (SIA 416) ──────────────────────────────────────────────
|
||||
"nav.roomBalance": "Flächenbilanz",
|
||||
"balance.title": "Flächenbilanz (SIA 416)",
|
||||
"balance.title": "Flächenbilanz",
|
||||
"balance.rooms": "Räume",
|
||||
"balance.summary": "Bilanz",
|
||||
"balance.export": "CSV exportieren",
|
||||
"balance.empty": "Keine Räume vorhanden. Mit dem Raum-Werkzeug erstellen.",
|
||||
"areas.title": "Flächen- und Kennzahlen-Nachweis",
|
||||
"areas.table": "Flächentabelle",
|
||||
"areas.level": "Geschoss",
|
||||
"areas.total": "Total",
|
||||
"areas.gv": "Gebäudevolumen GV",
|
||||
"areas.ivhb.title": "Kennziffern (IVHB)",
|
||||
"areas.col.ratio": "Kennziffer",
|
||||
"areas.col.formula": "Berechnung",
|
||||
"areas.col.numerator": "Zähler",
|
||||
"areas.col.agsf": "aGSF [m²]",
|
||||
"areas.col.value": "Wert",
|
||||
"areas.ratio.gfz": "GFZ Geschossflächenziffer",
|
||||
"areas.ratio.az": "AZ Ausnützungsziffer",
|
||||
"areas.ratio.bmz": "BMZ Baumassenziffer",
|
||||
"areas.ratio.uz": "ÜZ Überbauungsziffer",
|
||||
"areas.ratio.gz": "GZ Grünflächenziffer",
|
||||
"areas.formula.gfz": "Σ GF / aGSF",
|
||||
"areas.formula.az": "aGF ({basis}) / aGSF",
|
||||
"areas.formula.bmz": "Baumasse [m³] / aGSF",
|
||||
"areas.formula.uz": "aGbF / aGSF",
|
||||
"areas.formula.gz": "Grünfläche / aGSF",
|
||||
"areas.heights": "Höhen über ±0.00",
|
||||
"areas.height.total": "Gesamthöhe",
|
||||
"areas.height.facade": "Fassadenhöhe (höchste Wandoberkante, genähert)",
|
||||
"areas.agsf.source": "Anrechenbare Grundstücksfläche aGSF",
|
||||
"areas.src.input": "Eingabe",
|
||||
"areas.src.parcelArea": "Parzellenfläche des Projekts",
|
||||
"areas.src.parcelRing": "Fläche der Parzellengrenze",
|
||||
"areas.src.none": "nicht gesetzt",
|
||||
"areas.note.agfSeparate": "Die Aussengeschossfläche AGF gehört nicht zur GF und wird separat ausgewiesen.",
|
||||
"areas.note.kfFromWalls": "KF aus den Wandgrundrissen (abzüglich Räume) und KGF-Räumen hergeleitet; Stützen und Schächte nur als KGF-Raum.",
|
||||
"areas.note.gvSolids": "GV = Volumen der freien Körper (Massenmodell).",
|
||||
"areas.note.gvLevels": "GV ≈ GF × Geschosshöhe je Geschoss.",
|
||||
"areas.note.terrainZero": "Massgebendes Terrain = ±0.00 (kein Geländemodell).",
|
||||
"areas.note.agsfMissing": "Ohne anrechenbare Grundstücksfläche sind keine Ziffern berechenbar.",
|
||||
"areas.note.greenInput": "Die Grünfläche ist nicht aus dem Modell ableitbar und muss eingegeben werden.",
|
||||
"areas.note.aboveGroundOnly": "Unterirdische Geschosse sind in GFZ/AZ nicht angerechnet.",
|
||||
"areas.foot.sia": "Flächenarten nach SIA 416 (2003): GF = NGF + KF, NGF = NF + VF + FF, NF = HNF + NNF.",
|
||||
"areas.foot.ivhb": "Begriffe nach IVHB, Anhang 1; das kantonale Recht kann abweichen (Anrechnung der Flächen, Gebäudeteile).",
|
||||
"areas.basis.gf": "GF",
|
||||
"areas.basis.ngf": "NGF",
|
||||
"areas.basis.nf": "NF",
|
||||
"areas.agsfInput": "Anrechenbare Grundstücksfläche",
|
||||
"areas.agsfInput.hint": "Leer: Parzellenfläche bzw. Parzellengrenze des Projekts.",
|
||||
"areas.greenInput": "Grünfläche",
|
||||
"areas.greenInput.hint": "Anrechenbare Grünfläche; nicht aus dem Modell ableitbar.",
|
||||
"areas.basisInput": "aGF der AZ",
|
||||
"areas.includeUnderground": "Untergeschosse anrechnen",
|
||||
"areas.exportCsv": "CSV",
|
||||
"areas.exportPdf": "PDF",
|
||||
"areas.exportPdf.fail": "PDF konnte nicht erstellt werden.",
|
||||
"areas.noLevels": "Keine Geschosse mit Räumen.",
|
||||
"areas.page": "Seite {n}",
|
||||
// ── Raum-Stempel-Editor ──────────────────────────────────────────────────
|
||||
"room.stamp.editTitle": "Raum-Stempel bearbeiten",
|
||||
"room.stamp.close": "Schliessen",
|
||||
|
||||
+54
-1
@@ -1570,11 +1570,64 @@ export const en: Record<TranslationKey, string> = {
|
||||
|
||||
// Area balance (SIA 416).
|
||||
"nav.roomBalance": "Area balance",
|
||||
"balance.title": "Area balance (SIA 416)",
|
||||
"balance.title": "Area balance",
|
||||
"balance.rooms": "Rooms",
|
||||
"balance.summary": "Balance",
|
||||
"balance.export": "Export CSV",
|
||||
"balance.empty": "No rooms yet. Create one with the room tool.",
|
||||
"areas.title": "Area and ratio statement",
|
||||
"areas.table": "Area table",
|
||||
"areas.level": "Level",
|
||||
"areas.total": "Total",
|
||||
"areas.gv": "Building volume GV",
|
||||
"areas.ivhb.title": "Ratios (IVHB)",
|
||||
"areas.col.ratio": "Ratio",
|
||||
"areas.col.formula": "Calculation",
|
||||
"areas.col.numerator": "Numerator",
|
||||
"areas.col.agsf": "aGSF [m²]",
|
||||
"areas.col.value": "Value",
|
||||
"areas.ratio.gfz": "GFZ gross floor area ratio",
|
||||
"areas.ratio.az": "AZ utilisation ratio",
|
||||
"areas.ratio.bmz": "BMZ building mass ratio",
|
||||
"areas.ratio.uz": "ÜZ site coverage ratio",
|
||||
"areas.ratio.gz": "GZ green area ratio",
|
||||
"areas.formula.gfz": "Σ GF / aGSF",
|
||||
"areas.formula.az": "aGF ({basis}) / aGSF",
|
||||
"areas.formula.bmz": "building mass [m³] / aGSF",
|
||||
"areas.formula.uz": "aGbF / aGSF",
|
||||
"areas.formula.gz": "green area / aGSF",
|
||||
"areas.heights": "Heights above ±0.00",
|
||||
"areas.height.total": "Overall height",
|
||||
"areas.height.facade": "Facade height (highest wall top, approximated)",
|
||||
"areas.agsf.source": "Creditable plot area aGSF",
|
||||
"areas.src.input": "input",
|
||||
"areas.src.parcelArea": "parcel area of the project",
|
||||
"areas.src.parcelRing": "area of the parcel boundary",
|
||||
"areas.src.none": "not set",
|
||||
"areas.note.agfSeparate": "The external floor area AGF is not part of GF and is shown separately.",
|
||||
"areas.note.kfFromWalls": "KF derived from wall footprints (minus rooms) and KGF rooms; columns and shafts only as a KGF room.",
|
||||
"areas.note.gvSolids": "GV = volume of the free solids (massing model).",
|
||||
"areas.note.gvLevels": "GV ≈ GF × storey height per level.",
|
||||
"areas.note.terrainZero": "Reference terrain = ±0.00 (no terrain model).",
|
||||
"areas.note.agsfMissing": "Without a creditable plot area no ratios can be computed.",
|
||||
"areas.note.greenInput": "The green area cannot be derived from the model and must be entered.",
|
||||
"areas.note.aboveGroundOnly": "Underground levels are not credited in GFZ/AZ.",
|
||||
"areas.foot.sia": "Area types per SIA 416 (2003): GF = NGF + KF, NGF = NF + VF + FF, NF = HNF + NNF.",
|
||||
"areas.foot.ivhb": "Terms per IVHB, annex 1; cantonal law may differ (crediting of areas, building parts).",
|
||||
"areas.basis.gf": "GF",
|
||||
"areas.basis.ngf": "NGF",
|
||||
"areas.basis.nf": "NF",
|
||||
"areas.agsfInput": "Creditable plot area",
|
||||
"areas.agsfInput.hint": "Empty: parcel area or parcel boundary of the project.",
|
||||
"areas.greenInput": "Green area",
|
||||
"areas.greenInput.hint": "Creditable green area; cannot be derived from the model.",
|
||||
"areas.basisInput": "aGF for AZ",
|
||||
"areas.includeUnderground": "Credit underground levels",
|
||||
"areas.exportCsv": "CSV",
|
||||
"areas.exportPdf": "PDF",
|
||||
"areas.exportPdf.fail": "Could not create the PDF.",
|
||||
"areas.noLevels": "No levels with rooms.",
|
||||
"areas.page": "Page {n}",
|
||||
// Room stamp editor.
|
||||
"room.stamp.editTitle": "Edit room stamp",
|
||||
"room.stamp.close": "Close",
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
// Flächentabelle (Flächenarten je Geschoss) und IVHB-Kennziffern im Flächenbilanz-Panel ([70]).
|
||||
//
|
||||
// • Die Tabellen stammen aus demselben Berichtsmodell wie CSV und PDF (`buildAreaReport`):
|
||||
// was hier steht, steht auch im Export.
|
||||
// • Eingaben, die das Modell nicht hergibt (anrechenbare Grundstücksfläche, Grünfläche, Basis der
|
||||
// aGF, Untergeschosse), liegen nur in der Ansicht (nicht im Projekt).
|
||||
// Herleitung der Zahlen: `src-tauri/core/src/flaechen.rs`.
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { t } from "../i18n";
|
||||
import { usePanelHost } from "./host";
|
||||
import { areaReportToCsv, buildAreaReport, buildAreaReportPdf } from "../core";
|
||||
import type { AgfBasis } from "../core";
|
||||
import { DEFAULT_AREA_INPUTS, ivhbOptionsOf, type AreaInputs } from "./areaInputs";
|
||||
import { downloadCsv } from "./downloadFile";
|
||||
import { useStore } from "../state/appStore";
|
||||
|
||||
const BASES: AgfBasis[] = ["ngf", "gf", "nf"];
|
||||
|
||||
export function AreaTableSection() {
|
||||
const host = usePanelHost();
|
||||
const project = host.project;
|
||||
const [inputs, setInputs] = useState<AreaInputs>(DEFAULT_AREA_INPUTS);
|
||||
const notify = useStore((s) => s.notify);
|
||||
const report = useMemo(
|
||||
() => buildAreaReport(project, { areas: true, ivhb: true, ivhbOptions: ivhbOptionsOf(inputs) }),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[project, inputs],
|
||||
);
|
||||
const set = (patch: Partial<AreaInputs>) => setInputs((i) => ({ ...i, ...patch }));
|
||||
const stem = `${project.name || "projekt"}-flaechen`;
|
||||
|
||||
const exportPdf = () => {
|
||||
try {
|
||||
buildAreaReportPdf(report).save(`${stem}.pdf`);
|
||||
} catch {
|
||||
notify(t("areas.exportPdf.fail"));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="area-section">
|
||||
<div className="balance-head">
|
||||
<span className="balance-section-label">{t("areas.title")}</span>
|
||||
<span className="area-actions">
|
||||
<button type="button" className="balance-export" onClick={() => downloadCsv(`${stem}.csv`, areaReportToCsv(report))}>
|
||||
{t("areas.exportCsv")}
|
||||
</button>
|
||||
<button type="button" className="balance-export" onClick={exportPdf}>
|
||||
{t("areas.exportPdf")}
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{report.sections.map((s, si) => (
|
||||
<div key={si} className="area-block">
|
||||
<div className="area-heading">{s.heading}</div>
|
||||
<div className="area-scroll">
|
||||
<table className="area-table">
|
||||
<thead>
|
||||
<tr>
|
||||
{s.columns.map((c, i) => (
|
||||
<th key={i} className={i === 0 ? "" : "num"}>
|
||||
{c}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{s.rows.map((r, ri) => (
|
||||
<tr key={ri} className={r.total ? "total" : ""}>
|
||||
{r.cells.map((c, ci) =>
|
||||
typeof c === "string" ? (
|
||||
<td key={ci}>{c}</td>
|
||||
) : (
|
||||
<td key={ci} className="num">
|
||||
{c.n === null ? "–" : c.n.toFixed(c.d)}
|
||||
</td>
|
||||
),
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<div className="area-inputs">
|
||||
<label className="kz-parcel">
|
||||
<span>{t("areas.agsfInput")}</span>
|
||||
<input type="text" inputMode="decimal" className="kz-input kz-num" value={inputs.agsf} title={t("areas.agsfInput.hint")} onChange={(e) => set({ agsf: e.target.value })} />
|
||||
<span>m²</span>
|
||||
</label>
|
||||
<label className="kz-parcel">
|
||||
<span>{t("areas.greenInput")}</span>
|
||||
<input type="text" inputMode="decimal" className="kz-input kz-num" value={inputs.greenArea} title={t("areas.greenInput.hint")} onChange={(e) => set({ greenArea: e.target.value })} />
|
||||
<span>m²</span>
|
||||
</label>
|
||||
<label className="kz-parcel">
|
||||
<span>{t("areas.basisInput")}</span>
|
||||
<select className="kz-input" value={inputs.agfBasis} onChange={(e) => set({ agfBasis: e.target.value as AgfBasis })}>
|
||||
{BASES.map((b) => (
|
||||
<option key={b} value={b}>
|
||||
{t(`areas.basis.${b}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="kz-parcel">
|
||||
<span>{t("areas.includeUnderground")}</span>
|
||||
<input type="checkbox" checked={inputs.includeUnderground} onChange={(e) => set({ includeUnderground: e.target.checked })} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<ul className="area-notes">
|
||||
{report.notes.map((n, i) => (
|
||||
<li key={i}>{n}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
// Inhalts-Panel „Flächenbilanz" (SIA 416) — listet alle Räume gruppiert nach
|
||||
// ihrer SIA-416-Blatt-Kategorie mit Zwischen-/Gesamtsummen und bietet einen
|
||||
// Inhalts-Panel „Flächenbilanz" — listet alle Räume gruppiert nach
|
||||
// ihrer Flächenart (SIA 416) mit Zwischen-/Gesamtsummen und bietet einen
|
||||
// CSV-Export, darüber die Kennzahlenleiste mit Parzelle und Raumprogramm
|
||||
// (KennzahlenSection). Fläche/Bilanz werden LIVE aus den Raum-Umrissen abgeleitet
|
||||
// (geometry/roomArea: evaluateRoom/balance/roomsToCsv) — nie gespeichert.
|
||||
@@ -13,6 +13,8 @@ import { balance, evaluateRoom, roomsToCsv, siaLabelFull } from "../core";
|
||||
import type { Room } from "../model/types";
|
||||
import { roomDisplayName } from "../model/roomStamp";
|
||||
import { KennzahlenSection } from "./KennzahlenSection";
|
||||
import { AreaTableSection } from "./AreaTableSection";
|
||||
import { downloadCsv } from "./downloadFile";
|
||||
|
||||
/** Löst je Raum die anrechenbare (Netto-)Fläche + Kategorie auf. */
|
||||
function roomAreas(rooms: Room[]): { category: Room["siaCategory"]; area: number }[] {
|
||||
@@ -30,22 +32,6 @@ function floorNameOf(
|
||||
return levels.find((z) => z.id === floorId)?.name ?? floorId;
|
||||
}
|
||||
|
||||
/** Stösst den Download einer CSV-Datei an (reiner Client, Blob-URL). */
|
||||
function downloadCsv(fileName: string, content: string): void {
|
||||
// BOM voranstellen, damit Excel UTF-8 (Umlaute/„m²") korrekt liest.
|
||||
const blob = new Blob(["" + content], {
|
||||
type: "text/csv;charset=utf-8;",
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = fileName;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
export function RoomBalancePanel() {
|
||||
const host = usePanelHost();
|
||||
const rooms = host.project.rooms ?? [];
|
||||
@@ -55,6 +41,7 @@ export function RoomBalancePanel() {
|
||||
return (
|
||||
<div className="balance-panel">
|
||||
<KennzahlenSection />
|
||||
<AreaTableSection />
|
||||
<div className="balance-empty">{t("balance.empty")}</div>
|
||||
</div>
|
||||
);
|
||||
@@ -87,6 +74,9 @@ export function RoomBalancePanel() {
|
||||
{/* Kennzahlenleiste, Parzelle und Raumprogramm. */}
|
||||
<KennzahlenSection />
|
||||
|
||||
{/* Flächentabelle und IVHB-Kennziffern. */}
|
||||
<AreaTableSection />
|
||||
|
||||
{/* Raumliste (je Raum: Name · Geschoss · SIA · Fläche). */}
|
||||
<div className="balance-section-label">{t("balance.rooms")}</div>
|
||||
<div className="balance-table">
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DEFAULT_AREA_INPUTS, ivhbOptionsOf, parseAreaNumber } from "./areaInputs";
|
||||
|
||||
describe("Flächen-Eingaben", () => {
|
||||
it("Komma und Punkt, leer und Unsinn", () => {
|
||||
expect(parseAreaNumber("412,5")).toBe(412.5);
|
||||
expect(parseAreaNumber(" 300.25 ")).toBe(300.25);
|
||||
expect(parseAreaNumber("")).toBeUndefined();
|
||||
expect(parseAreaNumber("abc")).toBeUndefined();
|
||||
expect(parseAreaNumber("-3")).toBeUndefined();
|
||||
expect(parseAreaNumber("Infinity")).toBeUndefined();
|
||||
});
|
||||
it("Optionen für den Kern", () => {
|
||||
expect(ivhbOptionsOf(DEFAULT_AREA_INPUTS)).toEqual({ agsf: undefined, greenArea: undefined, agfBasis: "ngf", includeUnderground: false });
|
||||
expect(ivhbOptionsOf({ agsf: "500", greenArea: "120,5", agfBasis: "gf", includeUnderground: true })).toEqual({
|
||||
agsf: 500,
|
||||
greenArea: 120.5,
|
||||
agfBasis: "gf",
|
||||
includeUnderground: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
// Eingaben und Hilfen des Flächen-Nachweises im Flächenbilanz-Panel ([70]).
|
||||
|
||||
import type { AgfBasis, IvhbOptions } from "../core";
|
||||
|
||||
/** Eingaben, die das Modell nicht hergibt; als Text, damit halbfertiges Tippen erhalten bleibt. */
|
||||
export interface AreaInputs {
|
||||
agsf: string;
|
||||
greenArea: string;
|
||||
agfBasis: AgfBasis;
|
||||
includeUnderground: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_AREA_INPUTS: AreaInputs = { agsf: "", greenArea: "", agfBasis: "ngf", includeUnderground: false };
|
||||
|
||||
/** Zahl aus einer Eingabe (Komma oder Punkt); leer/ungültig/negativ → undefined. */
|
||||
export function parseAreaNumber(text: string): number | undefined {
|
||||
const s = text.trim().replace(",", ".");
|
||||
if (s === "") return undefined;
|
||||
const v = Number(s);
|
||||
return Number.isFinite(v) && v >= 0 ? v : undefined;
|
||||
}
|
||||
|
||||
/** Eingaben → Optionen für den Kern. */
|
||||
export function ivhbOptionsOf(i: AreaInputs): IvhbOptions {
|
||||
return { agsf: parseAreaNumber(i.agsf), greenArea: parseAreaNumber(i.greenArea), agfBasis: i.agfBasis, includeUnderground: i.includeUnderground };
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Stösst den Download einer Datei an (reiner Client, Blob-URL).
|
||||
|
||||
export function downloadFile(fileName: string, blob: Blob): void {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = fileName;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
/** CSV mit BOM, damit Excel UTF-8 (Umlaute/„m²") korrekt liest. */
|
||||
export function downloadCsv(fileName: string, content: string): void {
|
||||
downloadFile(fileName, new Blob(["" + content], { type: "text/csv;charset=utf-8;" }));
|
||||
}
|
||||
@@ -8498,3 +8498,59 @@ body {
|
||||
flex: 0 0 9em;
|
||||
width: 9em;
|
||||
}
|
||||
|
||||
/* Flächentabelle und IVHB-Kennziffern (Flächenbilanz-Panel, AreaTableSection). */
|
||||
.area-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.area-actions {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
}
|
||||
.area-heading {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--ink-2);
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
.area-scroll {
|
||||
overflow-x: auto;
|
||||
}
|
||||
.area-table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
font-size: 11px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.area-table th,
|
||||
.area-table td {
|
||||
padding: 2px 5px;
|
||||
white-space: nowrap;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.area-table th {
|
||||
color: var(--ink-2);
|
||||
font-weight: 600;
|
||||
}
|
||||
.area-table .num {
|
||||
text-align: right;
|
||||
}
|
||||
.area-table tr.total td {
|
||||
font-weight: 700;
|
||||
border-top: 1px solid var(--ink-2);
|
||||
}
|
||||
.area-inputs {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.area-notes {
|
||||
margin: 0;
|
||||
padding-left: 16px;
|
||||
font-size: 10px;
|
||||
color: var(--ink-2);
|
||||
}
|
||||
Reference in new issue
Block a user