[K4] S2: 3D-Modell (Waende, Decken, Treppen, Stuetzen, Daecher, Oeffnungen, Kontext) rechnet komplett auf dem Dokument (model3d.rs, queries.rs); TS-Sammler und unbenutzte Bindungen geloescht

This commit is contained in:
karim committed 2026-10-28 02:06:10 +01:00
1 parent 0817697e19
commit 8995ea161d
35 files changed
+545 -2269

No files matched your search

+6 -1
View File
@@ -130,7 +130,12 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
`deny_unknown_fields`), `Document::project()` als gecachte typisierte Sicht, `documentFor(project)` (TS) hält ein gemeinsames
Dokument per Differenz aktuell. Verbraucher bisher: Kennzahlen (`kennzahlen.rs::compute`), Baurecht-Prüfung/Footprint/Modellhöhe (`site_rules.rs`); Abfragen laufen
über `doc_query`, Modell-Nachschlagen in `model/helpers.rs`. TS-Sammler gelöscht.
Nächste: Sonnenstand/Schatten, Raumprogramm, danach Plan/Schnitt/Ansicht, 3D, Export.
Sonnenstand/Schatten ebenso. **3D-Modell komplett** (28.10.): `model3d.rs` (Wände mit Verschneidung/Bändern/Öffnungen, Decken, Treppen,
Stützen, Dächer inkl. Schnitt-Schichten, Öffnungs-Einbauteile, Kontext) → `projectToModel3d` holt die Teile per `doc_query`
(`queries.rs`), nur die truck-Körper (async) fügt TS ein; TS-Sammler `toWalls3d/{bands,ceilings,columns,openings,stairs,roofs}.ts`
gelöscht, unbenutzte Bindungen/Kodierer entfernt. Hin-und-her-Vergleich mit der TS-Fassung lief über Zufallsprojekte, danach
prüft die bestehende Suite (2123 Tests) den neuen Weg. Das Modell ist tolerant (fehlende Felder = Standardwert).
Nächste: Plan/Schnitt/Ansicht-Sammler (generatePlan, toSection, toElevation), Export (IFC/DXF/SVG), Raumprogramm.
Ziel: Plan/Schnitt/Ansicht, 3D, Export rechnen mit `doc`-Handle statt flach gesammelter Arrays; TS-Sammler/-Adapter werden gelöscht
([K3d] hängt hier dran: Plan-Puffer v2 mit Pick-IDs und vollem Primitive-Umfang).
- ○ **S3 Änderungen kommen aus Rust**: Befehle (Zustandsautomaten, Werkzeuge) erzeugen Ops im Kern; Undo/Redo, Validierung
+4 -2
View File
@@ -155,7 +155,8 @@ def rust_enum(name, lits):
while v in seen: v = f"{base}{n}"; n += 1
seen.add(v)
lines.append(f' #[serde(rename = {json.dumps(l, ensure_ascii=False)})]\n {v},')
return ("#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]\n"
lines[0] = " #[default]\n" + lines[0]
return ("#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]\n"
f"pub enum {name} {{\n" + "\n".join(lines) + "\n}\n")
def rtype(t, ctx):
@@ -228,7 +229,8 @@ def emit_struct(name, fields):
r = f"Option<{r}>"
a = f" #[serde({', '.join(attrs)})]\n" if attrs else ""
lines.append(f"{a} pub {rn}: {r},")
out_items.append("#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n"
out_items.append("#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]\n"
+ '#[serde(default)]\n'
+ '#[cfg_attr(test, serde(deny_unknown_fields))]\n'
+ f"pub struct {name} {{\n" + "\n".join(lines) + "\n}\n")
-15
View File
@@ -76,21 +76,6 @@ pub fn ceilings(buf: &[f64]) -> Vec<CeilingSlabs> {
out
}
pub fn encode(c: &[CeilingSlabs]) -> Vec<f64> {
let mut out = vec![c.len() as f64];
for d in c {
out.push(d.ceiling as f64);
out.push(d.ring.len() as f64);
for p in &d.ring {
out.extend(*p);
}
out.push(d.slabs.len() as f64);
for (l, zb, zt) in &d.slabs {
out.extend([*l as f64, *zb, *zt]);
}
}
out
}
#[cfg(test)]
mod tests {
+1
View File
@@ -33,6 +33,7 @@ pub mod jsnum;
pub mod hatch;
pub mod hatch_flat;
pub mod plan_buf;
pub mod queries;
pub mod gpu_compile;
pub mod plan_stairs;
pub mod plan_walls;
+2 -26
View File
@@ -1,33 +1,9 @@
//! Gemeinsame Mesh-Ausgabe der 3D-Ableitungen (`stairs3d`, `columns3d`): ein Dreiecksnetz je
//! Eingabeelement, flach kodiert als `[n, (quelle, nPos, nIdx, positionen…, indizes…)…]`.
//! `quelle` ist der Index des Elements in der Eingabe, damit TS Farbe und Id zuordnen kann.
//! Eingabeelement. `src` ist der Index des Elements in der Eingabe, damit `model3d` Farbe und Id
//! zuordnen kann.
pub struct Mesh {
pub src: usize,
pub positions: Vec<f64>,
pub indices: Vec<u32>,
}
pub fn encode_meshes(meshes: &[Mesh]) -> Vec<f64> {
let total: usize = meshes.iter().map(|m| 3 + m.positions.len() + m.indices.len()).sum();
let mut out = Vec::with_capacity(1 + total);
out.push(meshes.len() as f64);
for m in meshes {
out.extend([m.src as f64, m.positions.len() as f64, m.indices.len() as f64]);
out.extend(&m.positions);
out.extend(m.indices.iter().map(|&i| i as f64));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kodierung() {
let m = Mesh { src: 2, positions: vec![0.0, 1.0, 2.0], indices: vec![0, 0, 0] };
assert_eq!(encode_meshes(&[m]), vec![1.0, 2.0, 3.0, 3.0, 0.0, 1.0, 2.0, 0.0, 0.0, 0.0]);
assert_eq!(encode_meshes(&[]), vec![0.0]);
}
}
File diff suppressed because it is too large. Load diff
+12
View File
@@ -271,3 +271,15 @@ pub enum ContextObject {
#[serde(rename = "image")]
Image(ContextImage),
}
impl Default for Drawing2DGeom {
fn default() -> Self {
Drawing2DGeom::Pointmarker { at: Vec2::default() }
}
}
impl Default for ColumnProfile {
fn default() -> Self {
ColumnProfile::Rect { width: 0.0, depth: 0.0 }
}
}
+111 -4
View File
@@ -244,6 +244,11 @@ pub struct RWall {
/// Textur-Karten-URLs der Bauteile in der Reihenfolge des ersten Auftretens: Wandtypen, dann
/// Decken, dann Dächer (`wallMaterialColorMaps`).
pub fn wall_material_color_maps(p: &Project) -> Vec<String> {
material_color_maps(p, None)
}
/// Wie [`wall_material_color_maps`]; `only_roof` beschränkt die Dächer auf eines (IFC-Export).
pub fn material_color_maps(p: &Project, only_roof: Option<&str>) -> Vec<String> {
let mut seen = std::collections::HashSet::new();
let mut list = Vec::new();
let mut consider = |id: &str| {
@@ -267,7 +272,7 @@ pub fn wall_material_color_maps(p: &Project) -> Vec<String> {
}
}
}
for r in p.roofs.as_deref().unwrap_or(&[]) {
for r in p.roofs.as_deref().unwrap_or(&[]).iter().filter(|r| only_roof.is_none_or(|id| r.id == id)) {
for l in p.roof_layers(r) {
if !l.component_id.is_empty() {
consider(&l.component_id);
@@ -990,10 +995,10 @@ fn roof_color(p: &Project, override_color: Option<Rgb>, component_id: &str) -> R
}
/// Dächer als geschlossene, geschichtete Dreiecks-Meshes (`emitRoofs`).
pub fn emit_roofs(p: &Project) -> Result<Vec<RMesh>, String> {
let maps = wall_material_color_maps(p);
pub fn emit_roofs(p: &Project, only_roof: Option<&str>) -> Result<Vec<RMesh>, String> {
let maps = material_color_maps(p, only_roof);
let mut out = Vec::new();
for roof in p.roofs.as_deref().unwrap_or(&[]) {
for roof in p.roofs.as_deref().unwrap_or(&[]).iter().filter(|r| only_roof.is_none_or(|id| r.id == id)) {
let eaves_z = p.roof_base_elevation(roof);
let g = crate::roof::roof_geometry(&roof.params(), eaves_z);
let override_color = roof.color.as_deref().filter(|c| !c.is_empty()).map(|c| hex_to_rgb(c, ROOF_RGB));
@@ -1051,10 +1056,112 @@ pub fn emit_roof_cut_layers(p: &Project) -> Result<Vec<RRoofLayer>, String> {
Ok(out)
}
// ── Kontext und Bündel ──────────────────────────────────────────────────────
const TERRAIN_RGB: Rgb = [169.0 / 255.0, 176.0 / 255.0, 162.0 / 255.0];
const IMPORTED_RGB: Rgb = [159.0 / 255.0, 166.0 / 255.0, 174.0 / 255.0];
fn indices_u32(v: &[f64]) -> Vec<u32> {
v.iter().map(|&i| i as u32).collect()
}
/// Rohe Kontext-Meshes: Gelände-TIN und importierte Volumen (`emitMeshes`).
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::ImportedMesh(m) if m.positions.len() >= 9 && m.indices.len() >= 3 => out.push(RMesh {
positions: m.positions.clone(),
indices: indices_u32(&m.indices),
kind: "imported",
color: IMPORTED_RGB,
vertex_colors: None,
material_index: None,
}),
_ => {}
}
}
out
}
/// Das 3D-Modell in Teilen: TS fügt die truck-Körper (asynchron) zwischen Kontext und Stützen ein.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Parts {
pub walls: Vec<RWall>,
pub slabs: Vec<RSlab>,
pub context_meshes: Vec<RMesh>,
pub column_meshes: Vec<RMesh>,
pub opening_meshes: Vec<RMesh>,
pub stair_meshes: Vec<RMesh>,
pub stair_railings: Vec<RMesh>,
pub roof_meshes: Vec<RMesh>,
pub roof_layers: Vec<RRoofLayer>,
}
/// `detail`: 0 grob, 1 mittel, 2 fein.
pub fn parts(p: &Project, layered: bool, detail: f64, for_section: bool) -> Result<Parts, String> {
let mut slabs = emit_slabs(p);
slabs.extend(emit_stairs(p, for_section));
Ok(Parts {
walls: emit_walls(p, layered)?,
slabs,
context_meshes: emit_context_meshes(p),
column_meshes: emit_columns(p),
opening_meshes: emit_opening_meshes(p, detail),
stair_meshes: emit_stair_meshes(p),
stair_railings: emit_stair_railings(p),
roof_meshes: emit_roofs(p, None)?,
roof_layers: emit_roof_cut_layers(p)?,
})
}
#[cfg(test)]
mod tests {
use super::*;
/// Walmdach 12×7 m: zwei Trapeze + zwei Walm-Dreiecke, First (3,3)-(8,3).
fn walm_planes() -> Vec<Vec<V3>> {
vec![
vec![[-0.5, -0.5, 5.2], [11.5, -0.5, 5.2], [8.0, 3.0, 7.061], [3.0, 3.0, 7.061]],
vec![[-0.5, 6.5, 5.2], [11.5, 6.5, 5.2], [8.0, 3.0, 7.061], [3.0, 3.0, 7.061]],
vec![[-0.5, -0.5, 5.2], [-0.5, 6.5, 5.2], [3.0, 3.0, 7.061]],
vec![[11.5, -0.5, 5.2], [11.5, 6.5, 5.2], [8.0, 3.0, 7.061]],
]
}
fn near(a: V3, b: V3) -> bool {
hypot(&[a[0] - b[0], a[1] - b[1], a[2] - b[2]]) < 1e-6
}
#[test]
fn gehrung_erkennt_first_und_grate_als_geteilt() {
let planes = walm_planes();
let m = Mitre::new(&planes);
assert_eq!(m.shared[0], vec![false, true, true, true]); // Traufe, Grat, First, Grat
assert_eq!(m.shared[2], vec![false, true, true]);
}
#[test]
fn unterseiten_treffen_sich_am_first_apex() {
let planes = walm_planes();
let m = Mitre::new(&planes);
let d = 0.27;
let (a, b, c) = (m.at(0, d)[3], m.at(1, d)[3], m.at(2, d)[2]);
assert!(near(a, b) && near(a, c));
assert!(a[2] < 7.061);
assert_eq!(m.at(0, 0.0), planes[0]);
assert!(m.at(0, 0.2)[0][2] < 5.2);
}
#[test]
fn beispielprojekt_hat_decken_und_gueltige_farben() {
let p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap();
+4 -21
View File
@@ -1005,23 +1005,6 @@ pub fn opening_meshes_flat(buf: &[f64]) -> Vec<f64> {
out
}
/// Flache Bindung von [`frame_ring_quads`]: `[n, (u, h) × 4 …]`; Eckstoss wie oben.
pub fn frame_ring_quads_flat(from: f64, to: f64, z_b: f64, z_t: f64, w: f64, join: f64, bottom: bool) -> Vec<f64> {
let join = match join as i64 {
1 => CornerJoin::Horizontal,
2 => CornerJoin::Mitre,
_ => CornerJoin::Vertical,
};
let qs = frame_ring_quads(from, to, z_b, z_t, w, join, bottom);
let mut out = vec![qs.len() as f64];
for q in qs {
for [u, h] in q {
out.push(u);
out.push(h);
}
}
out
}
#[cfg(test)]
mod tests {
@@ -1220,9 +1203,9 @@ mod tests {
assert_eq!(out.len(), 1 + 25);
assert_eq!(out[0], 1.0);
assert_eq!(out[1], Part::Glass as i32 as f64);
let ring = frame_ring_quads_flat(0.0, 1.0, 0.0, 1.0, 0.1, 0.0, true);
assert_eq!(ring[0], 4.0);
assert_eq!(&ring[1..9], &[0.0, 0.0, 0.1, 0.0, 0.0, 1.0, 0.1, 1.0]);
let ring = frame_ring_quads(0.0, 1.0, 0.0, 1.0, 0.1, CornerJoin::Vertical, true);
assert_eq!(ring.len(), 4);
assert_eq!(ring[0], [[0.0, 0.0], [0.1, 0.0], [0.0, 1.0], [0.1, 1.0]]);
}
#[test]
@@ -1241,6 +1224,6 @@ mod tests {
let mut big = vec![2.0, 1.0, 0.0, 0.0, 5.0, 0.0, 1.0, 1.0, 4.0, 0.0, 2.0, 1.0, 0.3, 1.0];
big.extend([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1e12, 2.0, f64::NAN, 1.0, 1e12, 1e12]);
assert!(opening_meshes_flat(&big)[0] >= 0.0);
let _ = frame_ring_quads_flat(f64::NAN, f64::INFINITY, -1.0, 1.0, -3.0, 9.0, false);
let _ = frame_ring_quads(f64::NAN, f64::INFINITY, -1.0, 1.0, -3.0, CornerJoin::Mitre, false);
}
}
+32
View File
@@ -0,0 +1,32 @@
//! Abfragen auf dem Projekt-Dokument ([K4] S2): eine Tabelle von Name → Rechnung, die als JSON
//! antwortet. TS ruft sie über `ProjectDocument.query(name, args, text)`.
use crate::model::Project;
use crate::{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())
}
/// Führt die Abfrage `name` aus. `args`: Zahlen, `text`: ein Text (z. B. eine id).
pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String, String> {
match (name, args.len()) {
("kennzahlen", _) => json(&kennzahlen::compute(p)),
("siteCheck", _) => json(&site_rules::check_project(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] }))),
("materialMaps", _) => json(&model3d::wall_material_color_maps(p)),
("slabs", _) => json(&model3d::emit_slabs(p)),
("columnMeshes", _) => json(&model3d::emit_columns(p)),
("walls", 1) => json(&model3d::emit_walls(p, args[0] != 0.0)?),
("openingMeshes", 1) => json(&model3d::emit_opening_meshes(p, args[0])),
("stairSlabs", 1) => json(&model3d::emit_stairs(p, args[0] != 0.0)),
("stairMeshes", _) => json(&model3d::emit_stair_meshes(p)),
("stairRailings", _) => json(&model3d::emit_stair_railings(p)),
("roofMeshes", _) => json(&model3d::emit_roofs(p, if text.is_empty() { None } else { Some(text) })?),
("roofCutLayers", _) => json(&model3d::emit_roof_cut_layers(p)?),
("model3dParts", 3) => json(&model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?),
_ => Err(format!("Unbekannte Abfrage: {name}")),
}
}
-10
View File
@@ -491,16 +491,6 @@ pub fn railings(buf: &[f64]) -> Vec<Mesh> {
out
}
pub fn encode_slabs(slabs: &[Slab]) -> Vec<f64> {
let mut out = vec![slabs.len() as f64];
for s in slabs {
out.extend([s.src as f64, if s.monolith { 1.0 } else { 0.0 }, s.z_bottom, s.z_top, s.pts.len() as f64]);
for p in &s.pts {
out.extend(*p);
}
}
out
}
#[cfg(test)]
mod tests {
-175
View File
@@ -640,160 +640,6 @@ fn emit_band_piece(em: &mut Emitter, li: usize, off: f64, cutouts: &[OpeningIn],
em.push(li, a, bb, zb, zt, off, holes, [zt - zt_start, zt - zt_end]);
}
// ── Flache Kodierung ─────────────────────────────────────────────────────────
//
// Geschosse: [nGeschosse, (nDecken, (zBottom, zTop, nPkt, (x, y)…, typOk, nSchichten,
// (dicke, prio|NaN)…)…, nDächer, (traufZ, schichtdicke, nPkt, (x, y)…, nFlächen,
// (m, (x, y, z)…)…)…)…]
// Wände: [nWände, (geschoss, sx, sy, ex, ey, zBottom, zTop, layered, stacked, refKind, refValue,
// dickeHülle, terminierung (0 beide, 1 unten, 2 oben), nBänder, (dicke, prio|NaN)…,
// nÖffnungen, (from, to, zBottom, zTop, rücksprung)…, <Cuts wie joins::encode_cuts>)…]
// geschoss: Index in die Geschosse (ausserhalb = ohne Decken/Dächer).
// Ausgabe: [nWände, (nKörper, (band, x1, y1, x2, y2, zBottom, zTop, schräg 0/1, drop0, drop1,
// nLöcher, (from, to, zBottom, zTop)…)…)…] — nWände < Eingabe, wenn der Puffer mittendrin
// kaputt ist; eine Wand mit ungültigen Werten (NaN …) hat keine Körper.
use crate::flat_read::Reader;
fn fin(v: &[f64]) -> bool {
v.iter().all(|x| x.is_finite())
}
/// Liest die Decken und Dächer eines Geschosses; einzelne ungültige fallen weg.
fn decode_context(r: &mut Reader) -> Option<FloorContext> {
let nc = r.count()?;
let mut ceilings = Vec::with_capacity(nc.min(1 << 12));
for _ in 0..nc {
let (czb, czt) = (r.num()?, r.num()?);
let outline = r.ring()?;
let type_ok = r.num()? != 0.0;
let nl = r.count()?;
let mut layers = Vec::with_capacity(nl.min(1 << 10));
let mut ok = fin(&[czb, czt]) && outline.iter().all(|p| fin(p));
for _ in 0..nl {
let (t, p) = (r.num()?, r.num()?);
ok &= t.is_finite() && !p.is_infinite();
layers.push((t, (!p.is_nan()).then_some(p)));
}
if ok {
let outline = outline.into_iter().map(|p| Vec2::new(p[0], p[1])).collect();
ceilings.push(CeilingIn { z_bottom: czb, z_top: czt, outline, layers: type_ok.then_some(layers) });
}
}
let nr = r.count()?;
let mut roofs = Vec::with_capacity(nr.min(1 << 12));
for _ in 0..nr {
let (ez, total) = (r.num()?, r.num()?);
let eaves = r.ring()?;
let np = r.count()?;
let mut planes = Vec::with_capacity(np.min(1 << 12));
for _ in 0..np {
let m = r.count()?;
planes.push(r.points3(m)?);
}
if fin(&[ez, total]) && eaves.iter().all(|p| fin(p)) && planes.iter().flatten().all(|p| fin(p)) {
roofs.push(RoofIn { eaves_z: ez, total_thickness: total, eaves, planes });
}
}
Some(FloorContext::new(ceilings, roofs))
}
/// Liest eine Wand: `None` = Puffer kaputt (Abbruch), `Some((geschoss, None))` = Werte ungültig.
fn decode_wall(r: &mut Reader) -> Option<(f64, Option<WallIn>)> {
let floor = r.num()?;
let (sx, sy, ex, ey, zb, zt) = (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?);
let (layered, stacked, kind, value, thick, term) = (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?);
let mut ok = fin(&[sx, sy, ex, ey, zb, zt, thick]);
let reference = match kind as i64 {
1 => Reference::Left,
2 => Reference::Right,
3 => {
ok &= value.is_finite();
Reference::Offset(value)
}
_ => Reference::Center,
};
let termination = match term as i64 {
1 => Termination::Below,
2 => Termination::Above,
_ => Termination::Both,
};
let nb = r.count()?;
let mut bands = Vec::with_capacity(nb.min(1 << 10));
for _ in 0..nb {
let (t, p) = (r.num()?, r.num()?);
ok &= t.is_finite() && !p.is_infinite();
bands.push(BandIn { thickness: t, priority: (!p.is_nan()).then_some(p) });
}
let no = r.count()?;
let mut openings = Vec::with_capacity(no.min(1 << 12));
for _ in 0..no {
let o = [r.num()?, r.num()?, r.num()?, r.num()?];
let recess = r.num()? != 0.0;
ok &= fin(&o);
openings.push(OpeningIn { from: o[0], to: o[1], z_bottom: o[2], z_top: o[3], recess_inner_layer: recess });
}
let cuts = crate::joins::decode_cuts(r)?;
let wall = WallIn {
start: Vec2::new(sx, sy),
end: Vec2::new(ex, ey),
z_bottom: zb,
z_top: zt,
layered: layered != 0.0,
stacked: stacked != 0.0,
reference,
thickness_safe: thick,
termination,
bands,
openings,
cuts,
};
Some((floor, ok.then_some(wall)))
}
fn encode_pieces(out: &mut Vec<f64>, pieces: &[Piece]) {
out.push(pieces.len() as f64);
for p in pieces {
out.extend([p.band as f64, p.start.x, p.start.y, p.end.x, p.end.y, p.z_bottom, p.z_top]);
match p.top_drop {
Some([d0, d1]) => out.extend([1.0, d0, d1]),
None => out.extend([0.0, 0.0, 0.0]),
}
out.push(p.holes.len() as f64);
for h in &p.holes {
out.extend(h);
}
}
}
/// Wände + Geschosse flach → Körper je Wand flach (s. Kodierung oben); nie ein Panic.
pub fn wall_bands_flat(walls: &[f64], floors: &[f64]) -> Vec<f64> {
let mut fr = Reader::new(floors);
let mut contexts = Vec::new();
if let Some(n) = fr.count() {
for _ in 0..n {
match decode_context(&mut fr) {
Some(c) => contexts.push(c),
None => break,
}
}
}
let empty = FloorContext::default();
let mut out = vec![0.0];
let mut r = Reader::new(walls);
let Some(n) = r.count() else { return out };
let mut done = 0usize;
for _ in 0..n {
let Some((floor, wall)) = decode_wall(&mut r) else { break };
let ctx = if floor >= 0.0 && floor.fract() == 0.0 { contexts.get(floor as usize).unwrap_or(&empty) } else { &empty };
let pieces = wall.map(|w| wall_bands(&w, ctx)).unwrap_or_default();
encode_pieces(&mut out, &pieces);
done += 1;
}
out[0] = done as f64;
out
}
#[cfg(test)]
mod tests {
use super::*;
@@ -929,9 +775,6 @@ mod tests {
#[test]
fn unsinn_ohne_panic() {
assert_eq!(wall_bands_flat(&[], &[]), vec![0.0]);
assert_eq!(wall_bands_flat(&[f64::NAN; 40], &[f64::NAN]), vec![0.0]);
assert_eq!(wall_bands_flat(&[0.0; 3], &[1.0, 5.0]), vec![0.0]);
// Nulllänge, umgekehrte Höhen, Öffnung ausserhalb, Bänder ohne Dicke, entartete Decke/Dach.
let mut w = base((1.0, 1.0), (1.0, 1.0), vec![band(0.2, 50.0)]);
assert!(bands_of(&w).is_empty());
@@ -947,23 +790,5 @@ mod tests {
);
let _ = wall_bands(&w, &ctx);
// Flach: zwei Wände (die zweite mit NaN-Koordinate → keine Körper), ein Geschoss.
let wall = |x: f64| {
let mut b = vec![0.0, x, 1.0, 2.0, 1.0, 0.0, 2.0, 1.0, 1.0, 0.0, 0.0, 0.2, 0.0, 1.0, 0.2, 50.0, 0.0];
crate::joins::encode_cuts(&mut b, &WallCuts::default());
b
};
let mut buf = vec![2.0];
buf.extend(wall(1.0));
buf.extend(wall(f64::NAN));
let floors = [1.0, 0.0, 0.0];
let out = wall_bands_flat(&buf, &floors);
assert_eq!(out[0], 2.0);
assert_eq!(out[1], 1.0); // ein Körper
assert_eq!(*out.last().unwrap(), 0.0); // zweite Wand: keine Körper
// Abgeschnittener Puffer: nur die vollständige erste Wand.
assert_eq!(wall_bands_flat(&buf[..buf.len() - 1], &floors)[0], 1.0);
// Kaputte Geschosse: Wände ohne Decken/Dächer.
assert_eq!(wall_bands_flat(&buf, &[3.0, 1.0])[0], 2.0);
}
}
-10
View File
@@ -1,10 +0,0 @@
//! Bindung der Decken im 3D (`crate::ceilings3d`). Kodierung s. dort.
use crate::ceilings3d as c;
use wasm_bindgen::prelude::wasm_bindgen;
/// Deckenumrisse (mit eingefügten Aussparungen) und Schicht-z-Spannen; Unsinn → leer.
#[wasm_bindgen]
pub fn ceilings3d_flat(ceilings: &[f64]) -> Vec<f64> {
c::encode(&c::ceilings(ceilings))
}
-11
View File
@@ -1,11 +0,0 @@
//! Bindung der Stützen im 3D (`crate::columns3d`). Kodierung s. dort.
use crate::columns3d as c;
use crate::mesh3d::encode_meshes;
use wasm_bindgen::prelude::wasm_bindgen;
/// Prisma-Meshes aller Stützen aus Querschnitt und Höhen; Unsinn → leer.
#[wasm_bindgen]
pub fn columns3d_flat(columns: &[f64]) -> Vec<f64> {
encode_meshes(&c::columns(columns))
}
+14 -34
View File
@@ -62,44 +62,24 @@ pub fn doc_json(h: u32) -> String {
with_doc(h, |d| d.to_json()).unwrap_or_default()
}
/// Abfrage auf dem typisierten Projekt; Ergebnis als JSON, leer bei Fehler (Dokument nicht offen,
/// Modell passt nicht, unbekannte Abfrage). Abfragen: `kennzahlen`, `siteCheck` (`null` ohne
/// Baurecht), `buildingFootprint`, `modelTop` (`null` ohne Bauteile).
/// Abfrage auf dem typisierten Projekt; Ergebnis als JSON. Fehler (Dokument nicht offen, Modell
/// passt nicht, unbekannte Abfrage, Rechenfehler) kommen als Text mit vorangestelltem `\u{1}`.
/// Abfragen s. `crate::queries`.
#[wasm_bindgen]
pub fn doc_query(h: u32, name: &str) -> String {
doc_query_args(h, name, &[])
doc_query_args(h, name, &[], "")
}
/// Wie [`doc_query`] mit Zahlenargumenten. `shadows`: `[azimut, höhe]` → vereinigter Boden-Schatten.
/// Wie [`doc_query`] mit Zahlen- und Textargument.
#[wasm_bindgen]
pub fn doc_query_args(h: u32, name: &str, args: &[f64]) -> String {
use crate::{kennzahlen, site_rules, sun};
let args = args.to_vec();
let name = name.to_owned();
with_doc(h, move |d| {
let p = d.project().ok()?;
let json = match name.as_str() {
"kennzahlen" => serde_json::to_string(&kennzahlen::compute(&p)),
"siteCheck" => serde_json::to_string(&site_rules::check_project(&p)),
"buildingFootprint" => serde_json::to_string(&site_rules::building_footprint(&p)),
"modelTop" => serde_json::to_string(&site_rules::model_top(&p)),
"walls" if args.len() == 1 => crate::model3d::emit_walls(&p, args[0] != 0.0).map_err(|_| ()).and_then(|w| serde_json::to_string(&w).map_err(|_| ())).map_err(|_| serde_json::Error::io(std::io::Error::other("walls"))),
"openingMeshes" if args.len() == 1 => serde_json::to_string(&crate::model3d::emit_opening_meshes(&p, args[0])),
"stairSlabs" if args.len() == 1 => serde_json::to_string(&crate::model3d::emit_stairs(&p, args[0] != 0.0)),
"stairMeshes" => serde_json::to_string(&crate::model3d::emit_stair_meshes(&p)),
"stairRailings" => serde_json::to_string(&crate::model3d::emit_stair_railings(&p)),
"roofMeshes" => crate::model3d::emit_roofs(&p).map_err(|e| serde_json::Error::io(std::io::Error::other(e))).and_then(|v| serde_json::to_string(&v)),
"roofCutLayers" => crate::model3d::emit_roof_cut_layers(&p).map_err(|e| serde_json::Error::io(std::io::Error::other(e))).and_then(|v| serde_json::to_string(&v)),
"slabs" => serde_json::to_string(&crate::model3d::emit_slabs(&p)),
"columnMeshes" => serde_json::to_string(&crate::model3d::emit_columns(&p)),
"shadows" if args.len() == 2 => {
let polys = sun::shadow_polygons_project(&p, sun::SunPosition { azimuth: args[0], elevation: args[1] });
serde_json::to_string(&site_rules::area_out(&polys))
}
_ => return None,
};
json.ok()
pub fn doc_query_args(h: u32, name: &str, args: &[f64], text: &str) -> String {
let result = with_doc(h, |d| {
let p = d.project().map_err(|e| format!("Projekt passt nicht zum Kern-Modell: {e}"))?;
crate::queries::run(&p, name, args, text)
})
.flatten()
.unwrap_or_default()
.unwrap_or_else(|| Err("Dokument nicht offen".to_string()));
match result {
Ok(json) => json,
Err(e) => format!("\u{1}{e}"),
}
}
-5
View File
@@ -13,15 +13,10 @@ mod kennzahlen;
mod bulge;
mod stair;
mod joins;
mod wall_bands;
mod room_area;
mod room_boundary;
mod polygon_holes;
mod stairs3d;
mod ceilings3d;
mod columns3d;
mod drawing2d_3d;
mod openings3d;
mod wall_mesh_cut;
mod plan_buf;
mod gpu_compile;
-15
View File
@@ -1,15 +0,0 @@
//! Bindungen der Öffnungs-Einbauteile in 3D (`crate::openings3d`). Kodierung s. dort.
use wasm_bindgen::prelude::wasm_bindgen;
/// Wände mit Öffnungen (+ Detailgrad) flach → Quader (Bauteil-Klasse, 8 Ecken) flach; nie ein Panic.
#[wasm_bindgen]
pub fn opening_meshes_flat(buf: &[f64]) -> Vec<f64> {
crate::openings3d::opening_meshes_flat(buf)
}
/// Rahmen-Ring als Vierecke (u, h) flach: `[n, (u, h) × 4 …]`.
#[wasm_bindgen]
pub fn frame_ring_quads_flat(from: f64, to: f64, z_b: f64, z_t: f64, w: f64, join: f64, bottom: bool) -> Vec<f64> {
crate::openings3d::frame_ring_quads_flat(from, to, z_b, z_t, w, join, bottom)
}
-12
View File
@@ -31,15 +31,3 @@ pub fn site_multi_polygon_area(polys: &[f64]) -> f64 {
pub fn site_allowed_area(rules: &[f64]) -> Vec<f64> {
encode(&read_rules(rules).map(|r| site_rules::allowed_area(&r)).unwrap_or_default())
}
/// `[gültig, Parzelle, zulässig, Verstoss, HöheÜberschritten, …flat(zulässig), …flat(Verstösse)]`;
/// ungültig → `[0]`. `footprint` = Teile der Gebäude-Grundfläche (`flat`), `max_top` NaN = keine.
#[wasm_bindgen]
pub fn site_check(rules: &[f64], footprint: &[f64], max_height: f64, max_top: f64) -> Vec<f64> {
let (Some(r), Some(fp)) = (read_rules(rules), decode(footprint)) else { return vec![0.0] };
let Some(c) = site_rules::check_site_rules(&r, &fp, max_height, max_top) else { return vec![0.0] };
let mut out = vec![1.0, c.parcel_area, c.allowed_area, c.violation_area, if c.height_exceeded { 1.0 } else { 0.0 }];
out.extend(encode(&c.allowed));
out.extend(encode(&c.violations));
out
}
-23
View File
@@ -1,23 +0,0 @@
//! Bindungen der Treppen im 3D (`crate::stairs3d`). Kodierung s. dort.
use crate::mesh3d::encode_meshes;
use crate::stairs3d as s;
use wasm_bindgen::prelude::wasm_bindgen;
/// Tritt-Prismen und Podeste aller Treppen als Slabs; `for_section`: auch gerade Betontreppen.
#[wasm_bindgen]
pub fn stairs3d_slabs_flat(stairs: &[f64], for_section: bool) -> Vec<f64> {
s::encode_slabs(&s::slabs(stairs, for_section))
}
/// Glatte Laufplatte gerader Betontreppen als Meshes.
#[wasm_bindgen]
pub fn stairs3d_meshes_flat(stairs: &[f64]) -> Vec<f64> {
encode_meshes(&s::slab_meshes(stairs))
}
/// Handlauf und Pfosten gerader Treppen als Quader-Meshes.
#[wasm_bindgen]
pub fn stairs3d_railings_flat(stairs: &[f64]) -> Vec<f64> {
encode_meshes(&s::railings(stairs))
}
+1 -32
View File
@@ -2,8 +2,7 @@
use crate::flat_read::pairs;
use crate::flat::{decode, encode};
use crate::flat_read::Reader;
use crate::sun::{self, Prism, SunPosition};
use crate::sun::{self, SunPosition};
use wasm_bindgen::prelude::wasm_bindgen;
/// `[azimut, höhe]` in Grad.
@@ -20,36 +19,6 @@ pub fn sun_shadow_of_prism(footprint: &[f64], z_bottom: f64, z_top: f64, azimuth
r.into_iter().flatten().collect()
}
fn read_prisms(buf: &[f64]) -> Option<Vec<Prism>> {
let mut r = Reader::new(buf);
let n = r.count()?;
let mut out = Vec::with_capacity(n.min(1 << 16));
for _ in 0..n {
let (z_bottom, z_top) = (r.num()?, r.num()?);
out.push(Prism { footprint: r.ring()?, z_bottom, z_top });
}
Some(out)
}
fn read_clouds(buf: &[f64]) -> Option<Vec<Vec<[f64; 3]>>> {
let mut r = Reader::new(buf);
let n = r.count()?;
let mut out = Vec::with_capacity(n.min(1 << 16));
for _ in 0..n {
let k = r.count()?;
out.push(r.points3(k)?);
}
Some(out)
}
/// Prismen `[n, (zUnten, zOben, nPkt, x, y, …)…]` und Punktwolken `[n, (nPkt, x, y, z, …)…]`
/// → vereinigter Schatten (Polygone, `flat`-Kodierung).
#[wasm_bindgen]
pub fn sun_shadow_union(prisms: &[f64], clouds: &[f64], azimuth: f64, elevation: f64) -> Vec<f64> {
let (Some(p), Some(c)) = (read_prisms(prisms), read_clouds(clouds)) else { return encode(&[]) };
encode(&sun::shadow_union(&p, &c, SunPosition { azimuth, elevation }))
}
/// Ein Polygon (`flat`, erstes Polygon zählt) → lochfreie Teile (`flat`, je ein Ring).
#[wasm_bindgen]
pub fn sun_without_holes(poly: &[f64]) -> Vec<f64> {
-9
View File
@@ -1,9 +0,0 @@
//! Bindungen der Wand-Schichtbänder (`crate::wall_bands`). Kodierung s. dort.
use wasm_bindgen::prelude::wasm_bindgen;
/// Wände + Geschosse (Decken, Dächer) flach → Körper je Wand flach; nie ein Panic.
#[wasm_bindgen]
pub fn wall_bands_flat(walls: &[f64], floors: &[f64]) -> Vec<f64> {
crate::wall_bands::wall_bands_flat(walls, floors)
}
+32 -6
View File
@@ -8,6 +8,25 @@ import type { Project } from "../model/types";
import { core } from "../engine/coreWasm";
import { diffToOps } from "./ops";
/** Abfragen des Kerns (`queries.rs`). */
export type QueryName =
| "kennzahlen"
| "siteCheck"
| "buildingFootprint"
| "modelTop"
| "shadows"
| "materialMaps"
| "slabs"
| "columnMeshes"
| "walls"
| "openingMeshes"
| "stairSlabs"
| "stairMeshes"
| "stairRailings"
| "roofMeshes"
| "roofCutLayers"
| "model3dParts";
export class ProjectDocument {
private handle = 0;
private mirror: Project;
@@ -46,13 +65,20 @@ export class ProjectDocument {
}
/**
* Abfrage auf dem typisierten Projekt im Kern. Das Ergebnis ist JSON; ein Fehler (Projekt passt
* nicht zum Modell, unbekannte Abfrage) wirft.
* Abfrage auf dem typisierten Projekt im Kern (`queries.rs`); `args` Zahlen, `text` ein Text
* (z. B. eine id). Das Ergebnis ist JSON; Fehler im Kern (Projekt passt nicht zum Modell,
* Rechenfehler) werfen mit der Meldung des Kerns.
*/
query<T>(name: "kennzahlen" | "siteCheck" | "buildingFootprint" | "modelTop" | "shadows" | "slabs" | "columnMeshes" | "walls" | "openingMeshes" | "stairSlabs" | "stairMeshes" | "stairRailings" | "roofMeshes" | "roofCutLayers", args: number[] = []): T {
const text = this.handle ? core().doc_query_args(this.handle, name, Float64Array.from(args)) : "";
if (!text) throw new Error(`Kern-Abfrage „${name}": Projekt passt nicht zum Kern-Modell`);
return JSON.parse(text) as T;
query<T>(name: QueryName, args: number[] = [], text = ""): T {
return JSON.parse(this.queryJson(name, args, text)) as T;
}
/** Wie {@link query}, aber das JSON als Text (spart das Parsen, wenn es nur weitergereicht wird). */
queryJson(name: QueryName, args: number[] = [], text = ""): string {
if (!this.handle) throw new Error(`Kern-Abfrage „${name}": Dokument nicht offen`);
const out = core().doc_query_args(this.handle, name, Float64Array.from(args), text);
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
return out;
}
/** Das Dokument als JSON-Text (Test, Export). */
+3 -3
View File
@@ -76,7 +76,7 @@ import type { RWall } from "../plan/toWalls3d";
import { isWatertight, wallCutMeshes, type CutMesh } from "../plan/wallMeshCut";
import { evaluateRoom } from "../geometry/roomArea";
import { columnFootprint } from "../geometry/column";
import { emitRoofs } from "../plan/toWalls3d/roofs";
import { roofMeshes } from "../plan/toWalls3d";
// ── IFC-GUID (Base64-Kompression, 22 Zeichen) ───────────────────────────────
// Standard-Kompressionsalgorithmus (IfcOpenShell guid.compress): das erste
@@ -830,7 +830,7 @@ export function exportIfcSpf(projectIn: Project): string {
}
// ── Dächer → IfcRoof ───────────────────────────────────────────────────
// Dieselben geschlossenen Schicht-Meshes wie das 3D (`emitRoofs`: Dachflächen je Schicht,
// Dieselben geschlossenen Schicht-Meshes wie das 3D (`roofMeshes`: Dachflächen je Schicht,
// an First/Grat gehrt), zu EINEM Face-Set je Dach vereint. Modell-Koordinaten sind bereits
// Z-oben (kein Achsentausch wie bei den Wänden); die Wicklung wird so gewählt, dass das Volumen
// positiv ist — nur dann ist das Face-Set als geschlossen markiert.
@@ -846,7 +846,7 @@ export function exportIfcSpf(projectIn: Project): string {
const structure = resolveStructure(roof.floorId);
const positions: number[] = [];
const indices: number[] = [];
for (const mesh of emitRoofs({ ...project, roofs: [roof] })) {
for (const mesh of roofMeshes(project, roof.id)) {
const base = positions.length / 3;
for (let i = 0; i < mesh.positions.length; i += 3) {
positions.push(mesh.positions[i], mesh.positions[i + 1], mesh.positions[i + 2] - structure.baseElevation);
-159
View File
@@ -1,159 +0,0 @@
import { describe, expect, it } from "vitest";
import { sampleProject } from "../model/sampleProject";
import { documentFor } from "../core/document";
import { emitSlabs } from "./toWalls3d/ceilings";
import { emitColumns } from "./toWalls3d/columns";
import { projectToWalls3d } from "./toWalls3d";
import { emitOpeningMeshes } from "./toWalls3d/openings";
import { emitRoofs, emitRoofCutLayers } from "./toWalls3d/roofs";
import { emitStairs, emitStairMeshes, emitStairRailings } from "./toWalls3d/stairs";
const plain = <T,>(v: T): T => JSON.parse(JSON.stringify(v));
let seed = 21;
const rnd = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296);
const pick = <T,>(a: T[]) => a[Math.floor(rnd() * a.length)];
describe("model3d walls", () => {
it("sample project both paths", () => {
const doc = documentFor(sampleProject);
for (const layered of [true, false]) {
expect(doc.query<unknown[]>("walls", [layered ? 1 : 0])).toEqual(plain(projectToWalls3d(sampleProject, layered)));
}
});
it("random walls/openings/ceilings/roofs", () => {
let n = 0;
for (let t = 0; t < 150; t++) {
const lvl = sampleProject.drawingLevels.filter((l) => l.kind === "floor");
const pts = [[0, 0], [6, 0], [6, 4], [0, 4], [3, 0], [3, 4], [8, 2], [-2, 2]];
const walls = Array.from({ length: 2 + Math.floor(rnd() * 6) }, (_, k) => {
const a = pick(pts), b = pick(pts);
return { ...sampleProject.walls[0], id: "w" + k, floorId: pick(lvl).id, start: { x: a[0], y: a[1] }, end: { x: b[0], y: b[1] + (a[1] === b[1] && a[0] === b[0] ? 1 : 0) },
wallTypeId: pick(sampleProject.wallTypes).id,
...(rnd() < 0.3 ? { referenceLine: pick(["left", "right", "center"]) } : {}),
...(rnd() < 0.15 ? { referenceOffset: rnd() * 0.3 - 0.15 } : {}),
...(rnd() < 0.2 ? { sliceTermination: pick(["below", "above", "both"]) } : {}),
height: pick([2.5, 2.6, 3]) };
});
const openings = walls.flatMap((w, k) => rnd() < 0.6 ? [{ id: "o" + k, type: "opening", hostWallId: w.id, categoryCode: "21", kind: pick(["window", "door"]),
...(rnd() < 0.5 ? { typeId: pick(["window-standard", "window-double", "door-standard", "door-entry"]) } : {}),
position: rnd() * 2, width: 0.6 + rnd(), height: 1.2 + rnd(), sillHeight: pick([0, 0.9]) }] : []);
const ceilings = Array.from({ length: Math.floor(rnd() * 3) }, (_, k) => ({ id: "c" + k, type: "ceiling", floorId: pick(lvl).id, categoryCode: "20",
outline: [{ x: -1, y: -1 }, { x: 7, y: -1 }, { x: 7, y: 5 }, { x: -1, y: 5 }], wallTypeId: sampleProject.wallTypes[0].id,
...(sampleProject.ceilingTypes?.length && rnd() < 0.5 ? { ceilingTypeId: pick(sampleProject.ceilingTypes).id } : {}) }));
const roofs = rnd() < 0.5 ? [{ id: "R1", type: "roof", floorId: pick(lvl).id, categoryCode: "35", outline: [{ x: -1, y: -1 }, { x: 7, y: -1 }, { x: 7, y: 5 }, { x: -1, y: 5 }],
shape: pick(["sattel", "walm", "pult", "flach"]), pitchDeg: 30, overhang: 0.3, ridgeAxis: pick(["x", "y"]), thickness: 0.2 }] : [];
const kinds = ["fest", "dreh", "kipp", "drehkipp", "schiebe"];
const wts = Array.from({ length: 2 }, (_, k) => ({ ...sampleProject.windowTypes![0], id: "wt" + k, kind: pick(kinds), wingCount: 1 + Math.floor(rnd() * 3),
frameWidth: rnd() < 0.5 ? pick([0.04, 0.06, 0.09]) : undefined, transomHeight: rnd() < 0.5 ? pick([0.2, 0.4]) : undefined,
mullionRows: rnd() < 0.5 ? pick([1, 2, 3]) : undefined, mullionCols: rnd() < 0.5 ? pick([1, 2]) : undefined,
sillBoard: pick(["keine", "innen", "aussen", "beide", undefined]), glazingPanes: pick([1, 2, 3, undefined]), glazing: pick(["einfach", "zweifach", "dreifach"]),
frameCornerJoin: pick(["vertikal", "horizontal", "gehrung", undefined]), insetFromFace: rnd() < 0.5 ? 0.1 : undefined, insetFace: pick(["aussen", "innen", undefined]),
innerLayerRecess: rnd() < 0.3 ? true : undefined, shading: rnd() < 0.4 ? { create: true, kind: "rollladen", box: { width: 1, height: 0.2, depth: 0.2 } } : undefined,
sashes: rnd() < 0.6 ? Array.from({ length: 1 + Math.floor(rnd() * 3) }, () => ({ kind: pick(["fluegel", "fluegel", "pfosten"]), autoWidth: pick([true, false, undefined]), width: rnd() < 0.5 ? 0.4 : undefined, postWidth: rnd() < 0.5 ? 0.08 : undefined, opening: pick([...kinds, undefined]), hingeSide: pick(["left", "right", undefined]) })) : undefined }));
const dts = Array.from({ length: 2 }, (_, k) => ({ ...sampleProject.doorTypes![0], id: "dt" + k, leafStyle: pick(["glatt", "glas", "kassette"]), glazingRatio: rnd() < 0.5 ? pick([0.3, 1]) : undefined,
frameKind: pick(["zarge", "blockrahmen", undefined]), threshold: pick([true, false, undefined]), leafCount: pick([1, 2]) , panelCols: rnd() < 0.5 ? 2 : undefined, panelRows: rnd() < 0.5 ? 3 : undefined }));
const openings2 = openings.map((o: any) => ({ ...o, ...(rnd() < 0.8 ? { typeId: o.kind === "door" ? pick(dts).id : pick(wts).id } : {}), ...(rnd() < 0.3 ? { wingCount: 2 } : {}) }));
const project: any = { ...sampleProject, walls, openings: openings2, ceilings, roofs, windowTypes: wts, doorTypes: dts };
const doc = documentFor(project);
for (const [dc, dn] of [[0, "grob"], [1, "mittel"], [2, "fein"]] as const) {
expect(doc.query<unknown[]>("openingMeshes", [dc])).toEqual(plain(emitOpeningMeshes(project, dn)));
}
for (const layered of [true, false]) {
let want: unknown;
try { want = plain(projectToWalls3d(project, layered)); } catch { want = undefined; }
if (want === undefined) { expect(() => doc.query("walls", [layered ? 1 : 0])).toThrow(); continue; }
expect(doc.query<unknown[]>("walls", [layered ? 1 : 0])).toEqual(want);
n += (want as unknown[]).length;
}
}
expect(n).toBeGreaterThan(500);
});
});
describe("model3d stairs", () => {
it("random", () => {
let n = 0;
for (let t = 0; t < 200; t++) {
const lvl = sampleProject.drawingLevels.filter((l) => l.kind === "floor");
const types = Array.from({ length: 3 }, (_, k) => ({ id: "st" + k, name: "t", structure: pick(["massiv", "beton", "wange", "aufgesattelt", "spindel"]), closedRisers: rnd() < 0.5,
treadThickness: pick([0.04, 0.06]), nosing: rnd() < 0.5 ? 0.03 : undefined, railing: pick(["keine", "links", "rechts", "beide", undefined]), defaultWidth: 1 }));
const stairs = Array.from({ length: 1 + Math.floor(rnd() * 3) }, (_, k) => {
const shape = pick(["straight", "L", "spiral"]);
return { id: "s" + k, type: "stair", floorId: pick(lvl).id, categoryCode: "25", shape, start: { x: rnd() * 5, y: rnd() * 5 }, dir: pick([{ x: 1, y: 0 }, { x: 0, y: 1 }, { x: -1, y: 0 }]),
runLength: 2 + rnd() * 3, ...(shape === "L" ? { run2Length: 1.5, turn: pick([1, -1]) } : {}), ...(shape === "spiral" ? { center: { x: 2, y: 2 }, radius: 1.2, sweep: 4 } : {}),
width: 1, stepCount: 8 + Math.floor(rnd() * 8), ...(rnd() < 0.5 ? { totalRise: 2.6 } : {}), ...(rnd() < 0.5 ? { up: pick([true, false]) } : {}),
...(rnd() < 0.7 ? { typeId: pick(types).id } : {}), ...(rnd() < 0.3 ? { referenz: pick(["links", "rechts", "mitte"]) } : {}) };
});
const project: any = { ...sampleProject, stairs, stairTypes: types };
const doc = documentFor(project);
for (const fs of [false, true]) {
const a = doc.query<unknown[]>("stairSlabs", [fs ? 1 : 0]);
const b = plain(emitStairs(project, { forSection: fs }));
expect(a).toEqual(b);
n += b.length;
}
expect(doc.query("stairMeshes")).toEqual(plain(emitStairMeshes(project)));
expect(doc.query("stairRailings")).toEqual(plain(emitStairRailings(project)));
}
expect(n).toBeGreaterThan(300);
});
});
describe("model3d roofs", () => {
it("random", () => {
let n = 0;
const L = [{ x: 0, y: 0 }, { x: 11, y: 0 }, { x: 11, y: 4 }, { x: 8, y: 4 }, { x: 8, y: 6 }, { x: 0, y: 6 }];
const R = [{ x: 0, y: 0 }, { x: 8, y: 0 }, { x: 8, y: 5 }, { x: 0, y: 5 }];
for (let t = 0; t < 200; t++) {
const lvl = sampleProject.drawingLevels.filter((l) => l.kind === "floor");
const roofTypes = sampleProject.roofTypes ?? [];
const roofs = Array.from({ length: 1 + Math.floor(rnd() * 2) }, (_, k) => ({ id: "R" + k, type: "roof", floorId: pick(lvl).id, categoryCode: "35", outline: pick([L, R]),
shape: pick(["sattel", "walm", "pult", "flach", "mansarde", "zelt"]), pitchDeg: 10 + Math.floor(rnd() * 40), overhang: rnd() * 0.5, ridgeAxis: pick(["x", "y"]), thickness: pick([0.1, 0.2]),
...(roofTypes.length && rnd() < 0.7 ? { roofTypeId: pick(roofTypes).id } : {}), ...(rnd() < 0.3 ? { color: "#aa3322" } : {}), ...(rnd() < 0.3 ? { baseElevation: 3 } : {}) }));
const project: any = { ...sampleProject, roofs };
const doc = documentFor(project);
const a = doc.query<unknown[]>("roofMeshes");
const b = plain(emitRoofs(project));
expect(a).toEqual(b);
expect(plain(doc.query("roofCutLayers"))).toEqual(plain(emitRoofCutLayers(project)));
n += b.length;
}
expect(n).toBeGreaterThan(100);
});
});
describe("model3d slabs/columns", () => {
it("random", () => {
let ns = 0, nc = 0;
for (let t = 0; t < 200; t++) {
const lvl = sampleProject.drawingLevels.filter((l) => l.kind === "floor");
const ceilings = Array.from({ length: Math.floor(rnd() * 4) }, (_, k) => ({
id: "c" + k, type: "ceiling", floorId: pick(lvl).id, categoryCode: "20",
outline: [{ x: 0, y: 0 }, { x: 5 + k, y: 0 }, { x: 5 + k, y: 4 }, { x: 0, y: 4 }],
...(rnd() < 0.5 ? { openings: [[{ x: 1, y: 1 }, { x: 2, y: 1 }, { x: 2, y: 2 }, { x: 1, y: 2 }]] } : {}),
wallTypeId: sampleProject.wallTypes[0].id,
...(rnd() < 0.5 && sampleProject.ceilingTypes?.length ? { ceilingTypeId: pick(sampleProject.ceilingTypes).id } : {}),
...(rnd() < 0.3 ? { thickness: 0.25 } : {}),
...(rnd() < 0.2 ? { top: { mode: "custom", z: 3.1 } } : {}),
}));
const columns = Array.from({ length: Math.floor(rnd() * 4) }, (_, k) => ({
id: "k" + k, type: "column", floorId: pick(lvl).id, categoryCode: "20",
position: { x: k, y: 1 }, rotation: rnd() * 3, height: pick([0, 2.5, 3]),
profile: pick([{ kind: "rect", width: 0.3, depth: 0.4 }, { kind: "round", radius: 0.2 }]),
...(rnd() < 0.5 ? { componentId: pick(sampleProject.components).id } : {}),
...(rnd() < 0.3 ? { componentId: "nope" } : {}),
}));
const project: any = { ...sampleProject, ceilings, columns };
const doc = documentFor(project);
const a = doc.query<unknown[]>("slabs");
const b = plain(emitSlabs(project));
expect(a).toEqual(b);
const c = doc.query<unknown[]>("columnMeshes");
const d = plain(emitColumns(project));
expect(c).toEqual(d);
ns += b.length; nc += d.length;
}
expect(ns).toBeGreaterThan(100);
expect(nc).toBeGreaterThan(100);
});
});
+59 -109
View File
@@ -40,7 +40,7 @@
// truck-Extrusionen, freie 2D-Geometrie) hat ihre eigene Datei unter
// `toWalls3d/` — siehe dort für die konkrete Emissions-Logik je Bauteil.
import type { Project, Vec2, Wall } from "../model/types";
import type { Project, Vec2 } from "../model/types";
import { getWallType, wallTypeThickness } from "../model/types";
import { stairVerticalExtent } from "../model/wall";
import { openingJambs, openingVerticalExtent } from "../geometry/opening";
@@ -48,14 +48,10 @@ import type { DetailLevel } from "../model/viewTypes";
import { stairBBox, stairGeometry } from "../geometry/stair";
import { roofBaseElevation, roofGeometry } from "../geometry/roof";
import type { Vec3 as RoofVec3 } from "../geometry/roof";
import { computeJoins } from "../model/joins";
import type { WallCuts } from "../model/joins";
import { documentFor } from "../core/document";
import type { PickOpening, PickRoof, PickStair, PickContextMesh, PickDrawingSeg } from "./pickTypes";
import {
EPS,
IMPORTED_RGB,
TERRAIN_RGB,
wallMaterialColorMaps,
type RMesh,
type RModel3d,
type RRgb,
@@ -63,20 +59,14 @@ import {
type RVec2,
type RWall,
} from "./toWalls3d/shared";
import { emitWalls } from "./toWalls3d/bands";
import { emitSlabs } from "./toWalls3d/ceilings";
import { emitStairMeshes, emitStairRailings, emitStairs } from "./toWalls3d/stairs";
import { emitExtrudedSolids, TRUCK_MESH_READY_EVENT } from "./toWalls3d/extrusions";
import { applyVoids3d } from "./toWalls3d/voids3d";
import { emitDrawingLineVerts, pickDrawingSegs } from "./toWalls3d/drawing2d";
import { emitColumns } from "./toWalls3d/columns";
import { emitRoofCutLayers, emitRoofs } from "./toWalls3d/roofs";
import { emitOpeningMeshes } from "./toWalls3d/openings";
// Re-Export des gemeinsamen Vokabulars — externe Konsumenten (viewport/,
// export/, toSection.ts, nativeSync.ts, …) importieren weiterhin
// ausschliesslich von hier, unverändert zur Zeit vor dem Domänen-Split.
export { wallMaterialColorMaps, TRUCK_MESH_READY_EVENT };
export { TRUCK_MESH_READY_EVENT };
// 2D-Boden-Spuren gehen NICHT über `RModel3d`, sondern als LineList über den
// binären `set_drawing_lines`-Kanal (s. dortige Funktionsdoc) — der Viewport
// holt sie direkt hier ab.
@@ -90,87 +80,34 @@ type RoofPickVec3 = [number, number, number];
type RVec3 = [number, number, number];
/**
* Emittiert die rohen Kontext-Meshes eines Projekts: Gelände-TINs (`terrainMesh`)
* und importierte Volumen (`importedMesh`) aus `project.context`, plus alle
* übrigen Kontext-Mesh-Domänen (truck-Extrusionen, Stützen, 2D-Boden-Spuren).
* `contourSet` bleibt außen vor — das sind nur 2D-Linien (Höhenlinien/
* Footprints), keine Dreiecksmeshes. Die `positions`/`indices` der Geo-Meshes
* werden 1:1 durchgereicht (Modell-Koordinaten, x,y,z=Höhe); render3d bildet
* sie selbst nach world ab.
*/
function emitMeshes(project: Project): RMesh[] {
const out: RMesh[] = [];
for (const obj of project.context ?? []) {
if (obj.type === "terrainMesh" || obj.type === "importedMesh") {
// Leere/entartete Meshes überspringen (render3d würde sie ohnehin verwerfen).
if (obj.positions.length < 9 || obj.indices.length < 3) continue;
out.push({
positions: obj.positions,
indices: obj.indices,
kind: obj.type === "terrainMesh" ? "terrain" : "imported",
color: obj.type === "terrainMesh" ? TERRAIN_RGB : IMPORTED_RGB,
// Luftbild-Drape: das Gelände-TIN kann Pro-Vertex-Farben tragen (beim
// Import aus dem Luftbild gesampelt) — dann zeigt render3d das Ortho
// statt der Flächen-Grundfarbe.
vertexColors:
obj.type === "terrainMesh" && obj.vertexColors?.length
? obj.vertexColors
: undefined,
});
}
}
// 2D-Zeichnungen sind hier bewusst NICHT dabei: sie gehen als LineList über
// den binären `set_drawing_lines`-Kanal (s. `emitDrawingLineVerts`), weil ein
// Kataster-Import als Meshes im JSON-Modell weder serialisierbar noch
// speicherbar wäre (s. dortige Funktionsdoc).
//
// KEIN `out.push(...emitX(project))`: der Spread-Operator sprengt bei grossen
// Arrays die Argumentzahl-Grenze von `push` (RangeError "Maximum call stack
// size exceeded") — dieselbe, bereits dokumentierte Falle wie in
// `swissBuildings3d.ts::concatMeshes`/`dwgParser.ts`.
for (const m of emitExtrudedSolids(project)) out.push(m);
for (const m of emitColumns(project)) out.push(m);
return out;
}
/**
* Nur die Wände (Rückwärts-Kompatibilität / bestehende Aufrufer). Zerlegt Wände
* mit Öffnungen in Teilquader.
* Nur die Wände (Rückwärts-Kompatibilität / bestehende Aufrufer). Zerlegt Wände mit Öffnungen in
* Teilquader bzw. (layered) in Schicht-Bänder. Rechnet der Kern auf dem Projekt-Dokument
* (`model3d.rs`: Verschneidung je Geschoss, Bänder, Öffnungen, Decken-/Dach-Dominanz).
*/
export function projectToWalls3d(project: Project, layered = true): RWall[] {
const out: RWall[] = [];
// Verschneidungs-Schnittlinien PRO GESCHOSS berechnen (wie generatePlan.ts sie
// je Grundriss auf der gefilterten Wandmenge bildet) — nur für den layered-3D-
// Pfad. Nach Geschoss gruppieren, damit deckungsgleiche Wände verschiedener
// Geschosse (z. B. EG/OG an identischen XY-Knoten) NICHT fälschlich verschneiden.
// Der Schnitt-Pfad (layered=false) bekommt KEINE Cuts (unverändert, seine
// Dominanz macht toSection.ts). Anders als im 2D wird hier NICHT nach
// Sichtbarkeit gefiltert — 3D zeigt alle Wände, alle nehmen an den Joins teil.
const joins = layered ? computeJoinsByFloor(project) : undefined;
emitWalls(out, project, project.walls, layered, joins);
return out;
return documentFor(project).query<RWall[]>("walls", [layered ? 1 : 0]);
}
/**
* Berechnet `computeJoins` getrennt je Geschoss (`wall.floorId`) und führt
* die Ergebnis-Maps zu einer flachen `wallId → WallCuts` zusammen. So bilden nur
* Wände desselben Geschosses gemeinsame Ecken/T-Stösse (identisch zur 2D-Semantik,
* wo `generatePlan` je Grundriss aufruft).
* Textur-Karten-URLs der Bauteile in der Reihenfolge des ersten Auftretens (Wandtypen, Decken,
* Dächer): die Position + 1 ist die Textur-Ebene (`materialIndex`). Memoisiert je Projekt-Referenz.
*/
function computeJoinsByFloor(project: Project): Map<string, WallCuts> {
const byFloor = new Map<string, Wall[]>();
for (const w of project.walls) {
const key = w.floorId ?? "";
const list = byFloor.get(key);
if (list) list.push(w);
else byFloor.set(key, [w]);
const materialMapCache = new WeakMap<Project, string[]>();
export function wallMaterialColorMaps(project: Project): string[] {
let maps = materialMapCache.get(project);
if (!maps) {
maps = documentFor(project).query<string[]>("materialMaps");
materialMapCache.set(project, maps);
}
const merged = new Map<string, WallCuts>();
for (const walls of byFloor.values()) {
const cuts = computeJoins(project, walls);
for (const [id, wc] of cuts) merged.set(id, wc);
}
return merged;
return maps;
}
/**
* Dach-Meshes (geschlossene, geschichtete Körper je Dachschicht); `onlyRoofId` beschränkt auf ein
* Dach (IFC-Export). Rechnet der Kern.
*/
export function roofMeshes(project: Project, onlyRoofId?: string): RMesh[] {
return documentFor(project).query<RMesh[]>("roofMeshes", [], onlyRoofId ?? "");
}
/**
@@ -210,33 +147,46 @@ export interface Model3dOptions {
export function projectToModel3d(project: Project, opts: Model3dOptions = {}): RModel3d {
const layered = opts.layeredWalls ?? true;
const detail = opts.detail ?? "fein";
const parts = documentFor(project).query<Model3dParts>(
"model3dParts",
[layered ? 1 : 0, DETAIL_CODE[detail] ?? 3, opts.forSection ? 1 : 0],
);
// Die truck-Körper (asynchron, mit Cache) kommen zwischen Kontext-Meshes und Stützen.
const meshes: RMesh[] = [...parts.contextMeshes];
for (const m of emitExtrudedSolids(project)) meshes.push(m);
for (const m of parts.columnMeshes) meshes.push(m);
for (const m of parts.openingMeshes) meshes.push(m);
for (const m of parts.stairMeshes) meshes.push(m);
for (const m of parts.stairRailings) meshes.push(m);
for (const m of parts.roofMeshes) meshes.push(m);
const model: RModel3d = {
walls: projectToWalls3d(project, layered),
// Decken + Treppen (Treppentritte als extrudierte Slabs) — so wird die Treppe
// auch im WASM/wgpu-Renderer sichtbar (der three.js-Pfad rendert sie separat).
slabs: [...emitSlabs(project), ...emitStairs(project, { forSection: opts.forSection })],
// Kontext-Meshes (Terrain/Import) + Fenster-/Tür-Glasscheiben (eigenes Mesh
// je Scheibe) + Rahmen-/Sprossen-Riegel typisierter Öffnungen (Zarge/
// Blendrahmen/Kämpfer/Mittelpfosten, s. emitOpeningMeshes) + glatte Beton-
// Laufplatten (gerade Betontreppen als Mesh) + Dachflächen/-giebel
// (s. emitRoofs) — pickGeometry/Highlight nutzen `meshes` bewusst NICHT (man
// wählt Wand/Öffnung/Treppe; Treppen-Pick läuft über die pickGeometry-Boxen).
meshes: [
...emitMeshes(project),
...emitOpeningMeshes(project, detail),
...emitStairMeshes(project),
...emitStairRailings(project),
...emitRoofs(project),
],
// Dach-Schicht-Eingabe für den 3D-Live-Schnitt (render3d::roof_cut) — s.
// Kopfkommentar bei `RRoofLayer`/`emitRoofCutLayers`: getrennt von `meshes`,
// weil `section.rs` beliebige Dreiecksnetze nicht schneiden kann.
roofLayers: emitRoofCutLayers(project),
walls: parts.walls,
// Decken + Treppen (Treppentritte als extrudierte Slabs), Kontext-Meshes, Öffnungs-Einbauteile,
// Betonlaufplatten, Handläufe und Dachflächen: alles aus dem Kern; Dach-Schichten für den
// 3D-Live-Schnitt getrennt (`roofLayers`).
slabs: parts.slabs,
meshes,
roofLayers: parts.roofLayers,
};
if (opts.voids) applyVoids3d(model, project);
return model;
}
/** Teile des 3D-Modells aus dem Kern (`model3d::Parts`). */
interface Model3dParts {
walls: RWall[];
slabs: RSlab[];
contextMeshes: RMesh[];
columnMeshes: RMesh[];
openingMeshes: RMesh[];
stairMeshes: RMesh[];
stairRailings: RMesh[];
roofMeshes: RMesh[];
roofLayers: RModel3d["roofLayers"];
}
const DETAIL_CODE: Record<string, number> = { grob: 0, mittel: 1, fein: 2 };
/**
* Pick-Geometrie für den TS-seitigen 3D-Raycast (siehe viewport/raycast3d): die
* Wand-Teilquader (mit `wallId`) und Decken-Prismen (mit `ceilingId`) desselben
@@ -340,7 +290,7 @@ export function pickGeometry(
const drawings = pickDrawingSegs(project);
return {
walls: projectToWalls3d(project),
slabs: emitSlabs(project),
slabs: documentFor(project).query<RSlab[]>("slabs"),
openings,
stairs,
roofs,
-346
View File
@@ -1,346 +0,0 @@
// Wand-Domäne der 3D-Ableitung (SCHICHTEN → Bänder → Boxen, siehe Moduldoc in
// `../../toWalls3d.ts`): löst den Schichtaufbau EINER Wand in quer zur Dicke
// gestapelte Materialbänder auf und emittiert daraus Wandkörper — inklusive
// aller materialbewussten Verschneidungen (Gehrungs-/Anschluss-Cuts an L-/
// T-Stössen, Durchgangswand-Span-Cutouts, Decken-Dominanz pro Schicht, Dach-
// Unterkanten-Kappung mit schräger Oberkante). Das 3D-Pendant zu
// `generatePlan/walls.ts::addWallPoche`.
//
// Gerechnet wird im Rust-Kern (`src-tauri/core/src/wall_bands.rs`); hier bleiben
// das Sammeln aus dem `Project` (Wandtyp, Öffnungen, Decken- und Dachaufbau,
// Höhen), die flache Übergabe und die Darstellungs-Metadaten je Band (Farbe,
// Schraffur, Material, Schnitt-Stil).
import type { Project, Wall } from "../../model/types";
import {
getCeilingType,
getComponent,
getWallType,
getWindowType,
openingsOfWall,
roofLayers,
wallTypeThickness,
} from "../../model/types";
import { ceilingVerticalExtent, wallVerticalExtent } from "../../model/wall";
import { openingInterval, openingVerticalExtent } from "../../geometry/opening";
import { roofBaseElevation, roofGeometry, roofPlanesFlat } from "../../geometry/roof";
import { writeWallCuts, type WallCuts } from "../../model/joins";
import { FlatReader, FlatWriter } from "../../geometry/coreFlat";
import { core } from "../../engine/coreWasm";
import {
WALL_RGB,
dominantLayerColor,
dominantLayerHatch,
hexToRgb,
resolveComponentHatch,
resolveComponentMaterialLayer,
resolveCutLineStyle,
type RCutMeta,
type RHatch,
type RHole,
type RRgb,
type RWall,
} from "./shared";
/**
* Achswinkel einer GESCHNITTENEN Wand im Schnitt-Koordinatensystem (Modell-
* Konvention, identisch zu `SECTION_WALL_AXIS_ANGLE_DEG` in toSection.ts): das
* Wand-Band steht vertikal (Achse entlang v, atan2(1,0) = 90°). Damit drehen
* `relativeToWall`-Muster (Dämmung, Backstein) im 3D-Schnitt genauso mit der Wand
* wie im 2D-Schnitt (`splitWallLayers` → `resolveHatch(…, 90, …)`). Für DECKEN gibt
* es keinen Wandachsen-Bezug — dort bleibt der Winkel absolut (`emitSlabs` ruft
* `resolveComponentHatch` ohne Achswinkel, wie `splitSlabLayers` → `resolveHatch(…,
* undefined, …)`), sodass die liegende Boden-Dämmung vertikal statt horizontal läuft.
*/
const SECTION_WALL_AXIS_ANGLE_DEG = 90;
/**
* Eine quer zur Wanddicke gestapelte Materiallage als 3D-Band: eigene Dicke und
* Materialfarbe. Den Mitten-Versatz (Stapel um die Achse, Referenzlinie) rechnet
* der Kern (`wall_bands.rs`); jede Lage wird dort pro Achsen-Teilstück zu einer
* eigenen Voll-Box.
*/
interface WallBand {
thickness: number;
color: RRgb;
/** Schnitt-Schraffur des Band-Bauteils (siehe {@link RHatch}). */
hatch?: RHatch;
/** Material-Textur-Ebene des Band-Bauteils (1-basiert, siehe `wallMaterialColorMaps`). */
materialIndex?: number;
/**
* Verschneidungs-Rang dieser Materiallage (`Component.joinPriority`) — treibt
* die per-Schicht-Dominanz gegen Decken im layered-3D-Pfad (s. `wall_bands.rs`):
* eine Decke mit STRIKT höherer
* `joinPriority` schneidet nur die Bänder mit niedrigerem Rang aus ihrem
* z-Intervall (der Kern höherer Priorität läuft durch). `undefined` (kein
* auflösbarer WallType / synthetisches Fallback-Band) ⇒ keine Decken-
* Subtraktion (konservativ, wie das frühere Trim-Verhalten bei unbekanntem Typ).
*/
priority?: number;
/**
* Bauteil-Identität dieser Materiallage (`Component.id`) — treibt die MERGE-Regel
* der Schnitt-Boolean-Dominanz (gleiche Komponente + Priorität verschmelzen, keine
* innere Trennlinie). Reist als `RCutMeta.componentId` mit.
*/
componentId?: string;
/** Farbe der Schnitt-Umrisslinie dieser Schicht (aus `jointLineStyleId`, sonst Default). */
cutLineColor?: RRgb;
/** Strichstärke der Schnitt-Umrisslinie in mm-Papier (aus `jointLineStyleId`, sonst Default). */
cutLineWeight?: number;
}
/**
* Baut die {@link RCutMeta}-Nutzlast eines Wand-Bandes (Priorität/Identität/
* Schnittkanten-Stil), oder `undefined`, wenn das Band keinerlei Schnitt-Metadaten
* trägt (z. B. das Fallback-Vollkörper-Band ohne auflösbaren WallType). Nur gesetzte
* Felder werden übernommen, damit `#[serde(default)]` auf der Rust-Seite greift.
*/
function bandCutMeta(b: WallBand): RCutMeta | undefined {
const meta: RCutMeta = {};
if (b.priority !== undefined) meta.joinPriority = b.priority;
if (b.componentId !== undefined) meta.componentId = b.componentId;
if (b.cutLineColor !== undefined) meta.lineColor = b.cutLineColor;
if (b.cutLineWeight !== undefined) meta.lineWeight = b.cutLineWeight;
return Object.keys(meta).length > 0 ? meta : undefined;
}
/**
* Löst den Schichtstapel EINER Wand auf: je Materiallage ein {@link WallBand}
* mit ihrer Dicke und Component-Farbe (`stacked: true`). Der Kern stapelt die
* Lagen um die Wandachse und verschiebt den Stapel um den Referenzversatz
* (`Wall.referenceLine`/`referenceOffset`), wie der 2D-Plan und die Gehrungs-
* Cuts. Gesamtdicke = SUMME der Lagen-Dicken (lückenlos). Kein auflösbarer
* WallType / keine Lagen ⇒ EIN Vollkörper-Band über die volle Dicke im neutralen
* Grundton (`stacked: false`, ebenfalls Referenz-versetzt).
*/
function resolveWallBands(project: Project, wall: Wall, layered = true): { bands: WallBand[]; stacked: boolean } {
try {
const wt = getWallType(project, wall);
if (wt.layers.length > 0) {
// Gesamtdicke = Summe der Lagen (konsistent mit den Offsets); wenn diese
// von wallTypeThickness abwiche, gewinnt die Lagen-Summe (keine Lücken).
const total = wt.layers.reduce((s, l) => s + l.thickness, 0);
// Schnitt-Eingabe (layered=false): EINE Voll-Box über die ganze Dicke statt
// je Lage eine Box. So bleibt die Emission 1:1 Wand→Rechteck — passend zu
// `wallSegmentOwners`/`splitWallLayers` in toSection.ts, die die Schicht-
// Zerlegung TS-seitig aus diesem einen Rechteck machen. (Der 3D-Viewer ruft
// mit Default layered=true auf und bekommt unverändert die Schicht-Bänder.)
if (!layered) {
const dominant = wt.layers.reduce((best, l) => (l.thickness > best.thickness ? l : best));
const band: WallBand = {
thickness: total,
color: dominantLayerColor(wt.layers, project, WALL_RGB),
hatch: dominantLayerHatch(wt.layers, project, SECTION_WALL_AXIS_ANGLE_DEG),
materialIndex: resolveComponentMaterialLayer(project, dominant.componentId),
};
return { bands: [band], stacked: false };
}
const bands: WallBand[] = [];
for (const l of wt.layers) {
const comp = getComponent(project, l.componentId);
const color = hexToRgb(comp.color);
const lineStyle = resolveCutLineStyle(project, l.jointLineStyleId);
bands.push({
thickness: l.thickness,
color,
priority: comp.joinPriority,
componentId: comp.id,
cutLineColor: lineStyle?.color,
cutLineWeight: lineStyle?.weight,
hatch: resolveComponentHatch(project, l.componentId, SECTION_WALL_AXIS_ANGLE_DEG),
materialIndex: resolveComponentMaterialLayer(project, l.componentId),
});
}
return { bands, stacked: true };
}
// WallType ohne Schichten: EIN Vollkörper über die Typ-Gesamtdicke.
return { bands: [{ thickness: wallTypeThickness(wt), color: WALL_RGB }], stacked: false };
} catch {
// Kein auflösbarer WallType: EIN Vollkörper mit Default-Dicke/Grundton.
return { bands: [{ thickness: 0.2, color: WALL_RGB }], stacked: false };
}
}
/**
* Setzt `topAngle` (Draufsicht): wie der 2D-Grundriss — das Muster folgt der Wandachse
* (`relativeToWall`), `resolveHatch` zieht den Wandwinkel ab (SVG-Konvention, y nach unten);
* render3d rechnet in Modell-Winkeln (gegen den Uhrzeigersinn), daher das Vorzeichen.
*/
function withTopAngle(h: RHatch, dx: number, dy: number): RHatch {
if (h.baseAngle === undefined) return h;
const wallAngle = (Math.atan2(dy, dx) * 180) / Math.PI;
const svgAngle = h.relativeToWall ? h.baseAngle - wallAngle : h.baseAngle;
// Parallel-/Kreuzschar (diagonal=2, crosshatch=3): die 2D-Kachel trägt bei Winkel 0 eine
// SENKRECHTE Musterlinie (glPlanHatch: Basisrichtung (0,−1)), der 3D-Shader bei Winkel 0
// eine HORIZONTALE → um 90° versetzen. Die Dämmungs-Welle (4) läuft in beiden entlang u.
const quarter = h.pattern === 2 || h.pattern === 3 ? 90 : 0;
return { ...h, topAngle: -svgAngle + quarter };
}
/**
* Dicke einer Wand für die grobe Grundriss-Hülle (Decken-Vorfilter im Kern):
* Summe der WallType-Schichtdicken, sonst der Fallback-Grundton-Dicke aus
* {@link resolveWallBands} (0.2 m), falls kein WallType auflösbar ist. Auch von
* `openings.ts::emitOpeningMeshes` genutzt (Rahmen-Tiefe auf die Wanddicke
* klemmen).
*/
export function wallThicknessSafe(project: Project, wall: Wall): number {
try {
return wallTypeThickness(getWallType(project, wall));
} catch {
return 0.2;
}
}
/** `Wall.sliceTermination` → Kodierung im Kern (0 = beide/Standard). */
const TERMINATION = { below: 1, above: 2 } as const;
/**
* Schreibt Decken und Dächer EINES Geschosses (Kodierung `wall_bands.rs`): Decken
* mit z-Ausdehnung, Umriss und Schichten samt Rang (NaN = Bauteil unbekannt,
* Typ-Flag 0 = Deckentyp unbekannt); Dächer mit Traufhöhe, Schichtdicke, Traufe
* und Flächen. Ob und wo eine Decke ein Band schneidet bzw. ein Dach die Oberkante
* kappt, entscheidet der Kern.
*/
function writeFloor(w: FlatWriter, project: Project, floorId: string | undefined): void {
const ceilings = (project.ceilings ?? []).filter((c) => c.floorId === floorId && c.outline && c.outline.length >= 3);
w.num(ceilings.length);
for (const c of ceilings) {
const ext = ceilingVerticalExtent(project, c);
w.num(ext.zBottom, ext.zTop).ring(c.outline);
let layers;
try {
layers = getCeilingType(project, c).layers;
} catch {
w.num(0, 0);
continue;
}
w.num(1, layers.length);
for (const l of layers) {
let prio = Number.NaN;
try {
prio = getComponent(project, l.componentId).joinPriority;
} catch {
// Unbekanntes Bauteil: diese Deckenschicht schneidet nicht.
}
w.num(l.thickness, prio);
}
}
const roofs = (project.roofs ?? []).filter((r) => r.floorId === floorId);
w.num(roofs.length);
for (const r of roofs) {
const eavesZ = roofBaseElevation(project, r);
const geo = roofGeometry(r, eavesZ);
const total = roofLayers(project, r).reduce((s, l) => s + Math.max(0, l.thickness), 0);
w.num(eavesZ, total).ring(geo.eaves);
const planes = roofPlanesFlat(geo);
for (let i = 0; i < planes.length; i++) w.num(planes[i]);
}
}
/**
* Emittiert die Wandkörper der Wände `walls` in EINEM Kern-Aufruf (Decken/Dächer je
* Geschoss nur einmal übergeben). Reihenfolge der Körper wie Wand für Wand.
*
* ZWEI PFADE je `layered`:
* • layered=true (3D-Viewer, Default): EIN Körper pro Schicht-Band über die
* VOLLE Achse mit allen Öffnungen als echte `holes` (render3d stanzt sie in
* die Langseiten), dazu die materialbewussten Verschneidungen (End-Cuts/Merge
* an L-/T-Stössen aus `joins`, Durchgangswand-Span-Cutouts, Decken-Dominanz
* pro Schicht, schräge Oberkante unter Dächern als `topDrop`).
* • layered=false (Schnitt-Pfad, `computeSection`): Pfeiler/Brüstung/Sturz-
* Segmentierung (EIN Voll-Band je Segment), passend zu
* `toSection.ts::wallSegmentOwners`. Keine Löcher, keine Cuts.
*/
export function emitWalls(
out: RWall[],
project: Project,
walls: readonly Wall[],
layered = true,
joins?: Map<string, WallCuts>,
): void {
const w = new FlatWriter().num(walls.length);
const floors = new FlatWriter();
const floorIndex = new Map<string | undefined, number>();
const bandsOf: WallBand[][] = [];
for (const wall of walls) {
const { bands, stacked } = resolveWallBands(project, wall, layered);
bandsOf.push(bands);
const { zBottom, zTop } = wallVerticalExtent(project, wall);
let floor = -1;
if (layered) {
floor = floorIndex.get(wall.floorId) ?? -1;
if (floor < 0) {
floor = floorIndex.size;
floorIndex.set(wall.floorId, floor);
writeFloor(floors, project, wall.floorId);
}
}
w.num(floor, wall.start.x, wall.start.y, wall.end.x, wall.end.y, zBottom, zTop, layered ? 1 : 0, stacked ? 1 : 0);
if (wall.referenceOffset != null) w.num(3, wall.referenceOffset);
else w.num(wall.referenceLine === "left" ? 1 : wall.referenceLine === "right" ? 2 : 0, 0);
const term = wall.sliceTermination === "below" || wall.sliceTermination === "above" ? TERMINATION[wall.sliceTermination] : 0;
w.num(wallThicknessSafe(project, wall), term, bands.length);
for (const b of bands) w.num(b.thickness, b.priority ?? Number.NaN);
// Öffnungen (Fenster und Türen): Achsen-Intervall + vertikale Ausdehnung.
const slot = w.slot();
let nOpenings = 0;
for (const op of openingsOfWall(project, wall.id)) {
const iv = openingInterval(wall, op);
if (!iv) continue;
const v = openingVerticalExtent(project, wall, op);
const recess = op.kind === "window" && getWindowType(project, op)?.innerLayerRecess === true;
w.num(iv.from, iv.to, v.zBottom, v.zTop, recess ? 1 : 0);
nOpenings++;
}
w.set(slot, nOpenings);
writeWallCuts(w, layered ? joins?.get(wall.id) : undefined);
}
const floorBuf = new FlatWriter().num(floorIndex.size).done();
const r = new FlatReader(core().wall_bands_flat(w.done(), concat(floorBuf, floors.done())));
const nWalls = Math.min(r.count(), walls.length);
for (let i = 0; i < nWalls; i++) {
const wall = walls[i];
const bands = bandsOf[i];
const dx = wall.end.x - wall.start.x;
const dy = wall.end.y - wall.start.y;
for (let n = r.count(); n > 0; n--) {
const b = bands[r.num()];
const start: [number, number] = [r.num(), r.num()];
const end: [number, number] = [r.num(), r.num()];
const zb = r.num();
const zt = r.num();
const sloped = r.num() === 1;
const topDrop: [number, number] = [r.num(), r.num()];
const holes: RHole[] = [];
for (let k = r.count(); k > 0; k--) holes.push({ from: r.num(), to: r.num(), zBottom: r.num(), zTop: r.num() });
if (!b) continue;
const cut = bandCutMeta(b);
out.push({
start,
end,
thickness: b.thickness,
height: zt - zb,
baseElevation: zb,
...(sloped ? { topDrop } : {}),
color: b.color,
layers: [],
wallId: wall.id,
...(b.hatch ? { hatch: withTopAngle(b.hatch, dx, dy) } : {}),
...(b.materialIndex != null ? { materialIndex: b.materialIndex } : {}),
...(holes.length > 0 ? { holes } : {}),
...(cut ? { cut } : {}),
});
}
}
}
function concat(a: Float64Array, b: Float64Array): Float64Array {
const out = new Float64Array(a.length + b.length);
out.set(a);
out.set(b, a.length);
return out;
}
-106
View File
@@ -1,106 +0,0 @@
// Decken-Domäne der 3D-Ableitung: extrudiert `project.ceilings` zu geschichteten
// Deckenplatten (eine RSlab je Materiallage, oben→unten gestapelt) — das 3D-
// Pendant zu `generatePlan/ceilings.ts::addCeilingPoche`.
//
// Die Rechnung (Aussparungen über den Brücken-Trick in EINEN einfachen Umriss, derselbe Ring für
// ALLE Schichten; z-Spanne proportional auf die Schichten verteilt) steht in Rust
// (`src-tauri/core/src/ceilings3d.rs`). Hier nur: aus dem `Project` sammeln und je Schicht
// Farbe, Schraffur und Schnitt-Metadaten zuordnen.
import type { Ceiling, Layer, Project } from "../../model/types";
import { getCeilingType, getComponent } from "../../model/types";
import { ceilingVerticalExtent } from "../../model/wall";
import { core } from "../../engine/coreWasm";
import { FlatWriter } from "../../geometry/coreFlat";
import {
SLAB_RGB,
hexToRgb,
resolveComponentHatch,
resolveCutLineStyle,
type RCutMeta,
type RRgb,
type RSlab,
type RVec2,
} from "./shared";
/** Emittiert die Deckenplatten eines Projekts (falls vorhanden). */
export function emitSlabs(project: Project): RSlab[] {
const ceilings: Ceiling[] = [];
const layersOf: (Layer[] | undefined)[] = [];
const w = new FlatWriter();
const count = w.slot();
for (const c of project.ceilings ?? []) {
if (!c.outline || c.outline.length < 3) continue;
// zBottom/zTop (und damit die Deckendicke) berechnet ceilingVerticalExtent
// bereits über ceilingThickness (respektiert Typ-Dicke + Übersteuerung).
const { zBottom, zTop } = ceilingVerticalExtent(project, c);
// Kein auflösbarer Deckentyp ⇒ keine Lagen ⇒ EIN Vollkörper-Slab in SLAB_RGB.
let layers: Layer[] | undefined;
try {
layers = getCeilingType(project, c).layers;
} catch {
layers = undefined;
}
w.ring(c.outline);
const openings = c.openings ?? [];
w.num(openings.length);
for (const o of openings) w.ring(o);
w.num(zBottom, zTop, layers?.length ?? 0);
for (const l of layers ?? []) w.num(l.thickness);
ceilings.push(c);
layersOf.push(layers);
}
if (ceilings.length === 0) return [];
w.set(count, ceilings.length);
const f = core().ceilings3d_flat(w.done());
const out: RSlab[] = [];
let i = 1;
for (let n = f.length ? f[0] : 0; n > 0; n--) {
const ci = f[i++];
const c = ceilings[ci];
const layers = layersOf[ci];
const nPts = f[i++];
const outline: RVec2[] = new Array(nPts);
for (let k = 0; k < nPts; k++, i += 2) outline[k] = [f[i], f[i + 1]];
for (let s = f[i++]; s > 0; s--, i += 3) {
const layerIdx = f[i];
const zBottom = f[i + 1];
const zTop = f[i + 2];
if (layerIdx < 0 || !layers) {
out.push({ outline, zBottom, zTop, color: SLAB_RGB, ceilingId: c.id });
continue;
}
const l = layers[layerIdx];
let color: RRgb = SLAB_RGB;
let cut: RCutMeta | undefined;
try {
const comp = getComponent(project, l.componentId);
color = hexToRgb(comp.color);
// Schnitt-Metadaten der Schicht: joinPriority + Identität (für die
// Boolean-Dominanz/MERGE) + Schnittkanten-Stil aus jointLineStyleId.
const lineStyle = resolveCutLineStyle(project, l.jointLineStyleId);
cut = {
joinPriority: comp.joinPriority,
componentId: comp.id,
...(lineStyle?.color ? { lineColor: lineStyle.color } : {}),
...(lineStyle?.weight != null ? { lineWeight: lineStyle.weight } : {}),
};
} catch {
color = SLAB_RGB;
cut = undefined;
}
const hatch = resolveComponentHatch(project, l.componentId);
out.push({
outline,
zBottom,
zTop,
color,
ceilingId: c.id,
...(hatch ? { hatch } : {}),
...(cut ? { cut } : {}),
});
}
}
return out;
}
-90
View File
@@ -1,90 +0,0 @@
// Stützen-Domäne der 3D-Ableitung (Tragwerk): extrudiert `project.columns` zu
// parametrischen Prisma-Meshes (Rechteck-Box bzw. tesselliertes Kreis-Prisma).
//
// Das Prisma (Mantel-Quads, Deckel als Dreiecksfächer) rechnet Rust
// (`src-tauri/core/src/columns3d.rs`); hier nur Querschnitt und Höhen sammeln und einfärben.
import type { Column, Project, Vec2 } from "../../model/types";
import { getComponent } from "../../model/types";
import { columnFootprint } from "../../geometry/column";
import { columnVerticalExtent } from "../../model/wall";
import { core } from "../../engine/coreWasm";
import { hexToRgb, type RMesh, type RRgb } from "./shared";
/** Neutraler Beton-/Tragwerks-Grauton für Stützen (Fallback ohne Bauteil-Farbe). */
const COLUMN_RGB: RRgb = [0.7, 0.7, 0.72];
/**
* 3D-Farbe einer Stütze: die Bauteil-Albedo (`Component.color`), falls ein
* `componentId` auflösbar ist, sonst der neutrale Tragwerks-Grauton {@link
* COLUMN_RGB}. Eine explizite `column.color` (Grundriss-Umrissfarbe) wirkt
* bewusst NICHT auf die 3D-Fläche (nur der 2D-Umriss), damit die 3D-Darstellung
* material-/neutral bleibt — analog Wand (Umrissfarbe ≠ 3D-Albedo).
*/
function columnColor3d(project: Project, col: Column): RRgb {
if (col.componentId) {
try {
return hexToRgb(getComponent(project, col.componentId).color, COLUMN_RGB);
} catch {
return COLUMN_RGB;
}
}
return COLUMN_RGB;
}
/**
* Extrudiert `project.columns` (Tragwerk) zu parametrischen Prisma-Meshes —
* Rechteck-Box bzw. tesselliertes Kreis-Prisma, je Profil. SYNCHRON (anders als
* die truck-Extrusion der `ExtrudedSolid`s, s. `../extrusions.ts`): die
* Kontur kommt aus `columnFootprint`, die vertikale Lage aus
* `columnVerticalExtent` (UK/OK-Anker bzw. Geschoss-UK + Höhe). `positions` in MODELL-Metern
* (x, y, z=Höhe); render3d rendert Kontext-Meshes doppelseitig, die Winding-Reihenfolge ist
* unerheblich. Rust/render3d bleibt unverändert (Kontext-Mesh-Pfad).
*/
export function emitColumns(project: Project): RMesh[] {
const cols: Column[] = [];
const feet: Vec2[][] = [];
const zs: number[] = [];
let doubles = 1;
for (const col of project.columns ?? []) {
if (col.height <= 0) continue;
const { zBottom, zTop } = columnVerticalExtent(project, col);
const foot = columnFootprint(col);
cols.push(col);
feet.push(foot);
zs.push(zBottom, zTop);
doubles += 3 + 2 * foot.length;
}
if (cols.length === 0) return [];
const buf = new Float64Array(doubles);
buf[0] = cols.length;
let w = 1;
for (let k = 0; k < cols.length; k++) {
const foot = feet[k];
buf[w++] = zs[2 * k];
buf[w++] = zs[2 * k + 1];
buf[w++] = foot.length;
for (const p of foot) {
buf[w++] = p.x;
buf[w++] = p.y;
}
}
const f = core().columns3d_flat(buf);
const out: RMesh[] = [];
let i = 1;
for (let n = f.length ? f[0] : 0; n > 0; n--) {
const col = cols[f[i]];
const nPos = f[i + 1];
const nIdx = f[i + 2];
i += 3;
const positions: number[] = [];
for (let k = 0; k < nPos; k++) positions.push(f[i + k]);
i += nPos;
const indices: number[] = [];
for (let k = 0; k < nIdx; k++) indices.push(f[i + k]);
i += nIdx;
out.push({ positions, indices, kind: "extrusion", color: columnColor3d(project, col) });
}
return out;
}
-37
View File
@@ -1,37 +0,0 @@
import { describe, expect, it } from "vitest";
import type { FrameCornerJoin } from "../../model/types";
import { frameRingQuads } from "./openings";
type Q = ReturnType<typeof frameRingQuads>[number];
// Eckenfolge (from,UK),(to,UK),(from,OK),(to,OK) → als Ring 0,1,3,2.
const ring = (q: Q) => [q[0], q[1], q[3], q[2]];
const area = (q: Q) => {
const r = ring(q);
let a = 0;
for (let i = 0; i < 4; i++) a += r[i][0] * r[(i + 1) % 4][1] - r[(i + 1) % 4][0] * r[i][1];
return Math.abs(a) / 2;
};
describe("frameRingQuads", () => {
const modes: FrameCornerJoin[] = ["vertikal", "horizontal", "gehrung"];
for (const mode of modes) {
it(`${mode}: Profile decken genau den Ring ab (keine Überlappung)`, () => {
const qs = frameRingQuads(0, 1.2, 0.9, 2.1, 0.06, mode, true);
expect(qs.length).toBe(4);
const total = qs.reduce((a, q) => a + area(q), 0);
const ringArea = 1.2 * 1.2 - (1.2 - 0.12) * (1.2 - 0.12);
expect(total).toBeCloseTo(ringArea, 9);
});
it(`${mode}: ohne Schwelle (Tür) drei Profile`, () => {
const qs = frameRingQuads(0, 1.0, 0, 2.1, 0.06, mode, false);
expect(qs.length).toBe(3);
const total = qs.reduce((a, q) => a + area(q), 0);
expect(total).toBeCloseTo(1.0 * 2.1 - (1.0 - 0.12) * (2.1 - 0.06), 9);
});
}
it("vertikal: Pfosten laufen durch, Riegel dazwischen", () => {
const [left] = frameRingQuads(0, 1, 0, 1, 0.1, "vertikal", true);
expect(left[0]).toEqual([0, 0]);
expect(left[3]).toEqual([0.1, 1]);
});
});
-201
View File
@@ -1,201 +0,0 @@
// Öffnungs-Domäne der 3D-Ableitung: Glasscheibe(n)/Türblatt, Rahmen-/Sprossen-
// Riegel (Zarge/Blendrahmen/Kämpfer/Mittelpfosten/Flügelrahmen + SIA-Symbole),
// Fensterbänke, Zargen-Umgriff, Schwellenprofil und der Rollladen-/Sonnenschutz-
// kasten typisierter Tür-/Fensteröffnungen — das 3D-Pendant zu
// `generatePlan/openings.ts`.
//
// Gerechnet wird im Rust-Kern (`src-tauri/core/src/openings3d.rs`, Kodierung
// dort); hier bleiben das Sammeln aus dem `Project` (Tür-/Fenstertyp, Flügel-
// tabelle, Öffnungs-Intervall und -Höhe, Wanddicke), die flache Übergabe aller
// Wände in EINEM Kern-Aufruf und die Farbe je Bauteil-Klasse.
//
// Die Quader liegen in MODELL-Metern (x, y, z = Höhe); render3d bildet sie nach
// world ab und rendert sie doppelseitig (Winding egal). `kind: "extrusion"`
// (NICHT "imported"): die Nord-Achsen-Negation in `append_context_mesh` gilt nur
// für echte Import-Rohdaten, Öffnungs-Quader entstehen orientierungserhaltend aus
// der Wandachse (Fund 2026-09-27).
import type { DoorType, FrameCornerJoin, Opening, Project, WindowType } from "../../model/types";
import { getDoorType, getWindowType, glazingPanesOf } from "../../model/types";
import { openingInterval, openingVerticalExtent } from "../../geometry/opening";
import type { DetailLevel } from "../../model/viewTypes";
import { FlatReader, FlatWriter } from "../../geometry/coreFlat";
import { core } from "../../engine/coreWasm";
import type { RMesh, RRgb } from "./shared";
import { wallThicknessSafe } from "./bands";
/**
* Farbe je Bauteil-Klasse (Index = `Part` in `openings3d.rs`): Glas (hell,
* bläulich), Rahmen (helles, warmes Grau), Rollladenkasten, Fensterbank/
* Schwelle (Stein-Grau), SIA-Symbole (dunkle Linien auf dem Glas), Türblatt
* (warm, hell).
*/
const PART_RGB: readonly RRgb[] = [
[0.62, 0.76, 0.85],
[0.85, 0.85, 0.83],
[0.88, 0.88, 0.9],
[0.8, 0.8, 0.78],
[0.25, 0.27, 0.3],
[0.93, 0.9, 0.85],
];
/** Dreiecke eines Öffnungs-Quaders (Ecken-Bits: bit0 = Achse, bit1 = Höhe, bit2 = quer). */
const OPENING_BOX_TRIS: readonly number[] = [
0, 1, 3, 0, 3, 2, // quer nMin
4, 5, 7, 4, 7, 6, // quer nMax
0, 1, 5, 0, 5, 4, // UK
2, 3, 7, 2, 7, 6, // OK
0, 2, 6, 0, 6, 4, // from
1, 3, 7, 1, 7, 5, // to
];
const DETAIL_CODE: Record<string, number> = { grob: 0, mittel: 1, fein: 2 };
const JOIN_CODE: Record<string, number> = { horizontal: 1, gehrung: 2 };
const OPENING_KIND_CODE: Record<string, number> = { dreh: 1, kipp: 2, drehkipp: 3, fest: 4, schiebe: 5 };
const SILL_BOARD_CODE: Record<string, number> = { keine: 1, innen: 2, beide: 3 };
/** Fehlender Wert → NaN (der Kern setzt dort den Default). */
const opt = (v: number | null | undefined): number => v ?? Number.NaN;
const flag = (b: boolean): number => (b ? 1 : 0);
const openingKindCode = (k: string | undefined): number => (k ? OPENING_KIND_CODE[k] ?? 6 : 0);
/** Gemeinsame Typwerte (Kodierung `openings3d.rs`). */
function writeCommon(w: FlatWriter, t: DoorType | WindowType): void {
w.num(
opt(t.frameDepth),
opt(t.insetFromFace),
flag((t.insetFace ?? "aussen") === "innen"),
JOIN_CODE[t.frameCornerJoin ?? ""] ?? 0,
opt(t.frameWidth),
opt(t.transomHeight),
);
}
function writeOpening(w: FlatWriter, project: Project, op: Opening): void {
if (op.kind === "window") {
const wt = getWindowType(project, op);
if (!wt) {
w.num(0);
return;
}
w.num(1);
writeCommon(w, wt);
const shading = wt.shading?.create ? wt.shading.box : undefined;
w.num(
glazingPanesOf(wt),
opt(wt.mullionRows),
opt(wt.mullionCols),
SILL_BOARD_CODE[wt.sillBoard ?? ""] ?? 0,
flag(!!shading),
shading?.width ?? 0,
shading?.height ?? 0,
shading?.depth ?? 0,
op.wingCount ?? wt.wingCount ?? 1,
openingKindCode(wt.kind),
);
const sashes = wt.sashes ?? [];
w.num(sashes.length);
for (const s of sashes) {
w.num(
s.kind === "fluegel" ? 0 : s.kind === "pfosten" ? 1 : 2,
flag(s.autoWidth === false),
opt(s.width),
opt(s.postWidth),
openingKindCode(s.opening),
flag((s.hingeSide ?? "left") === "left"),
);
}
return;
}
const dt = getDoorType(project, op);
if (!dt) {
w.num(0);
return;
}
w.num(1);
writeCommon(w, dt);
w.num(
flag(dt.threshold === true),
opt(dt.leafCount),
dt.leafStyle === "glas" ? 1 : dt.leafStyle === "kassette" ? 2 : 0,
opt(dt.glazingRatio),
flag((dt.frameKind ?? "zarge") === "zarge"),
opt(dt.panelCols),
opt(dt.panelRows),
);
}
/**
* Alle Öffnungs-Einbauteile eines Projekts als rohe Quader-Meshes, in EINEM
* Kern-Aufruf. Reihenfolge wie früher: erst Glas/Türblätter aller Wände, dann
* Rahmen/Sprossen/Bänke/Zargen (nicht bei „grob"), dann Rollladenkästen (nicht
* bei „grob").
*
* • Ohne auflösbaren Typ: Fenster = EINE Vollscheibe mittig in der Wand, Tür =
* offenes Loch, kein Rahmen (Rückwärtskompatibilität).
* • „mittel": Blendrahmen + Oberlicht-Kämpfer + Flügelrahmen + Fensterbank/
* Zargen-Umgriff/Schwellenprofil, keine Sprossen, keine SIA-Symbole.
* • „fein": zusätzlich Flügel-Mittelpfosten, Kämpfer-Zeilen und SIA-Symbole.
*/
export function emitOpeningMeshes(project: Project, detail: DetailLevel = "fein"): RMesh[] {
const byWall = new Map<string, Opening[]>();
for (const op of project.openings ?? []) {
const list = byWall.get(op.hostWallId);
if (list) list.push(op);
else byWall.set(op.hostWallId, [op]);
}
const w = new FlatWriter().num(DETAIL_CODE[detail] ?? 3, project.walls.length);
for (const wall of project.walls) {
w.num(wall.start.x, wall.start.y, wall.end.x, wall.end.y);
const slot = w.slot();
let count = 0;
let thickness: number | undefined;
for (const op of byWall.get(wall.id) ?? []) {
const iv = openingInterval(wall, op);
if (!iv) continue;
const vert = openingVerticalExtent(project, wall, op);
thickness ??= wallThicknessSafe(project, wall);
w.num(iv.from, iv.to, vert.zBottom, vert.zTop, flag(op.kind !== "window"), thickness);
writeOpening(w, project, op);
count++;
}
w.set(slot, count);
}
const buf = core().opening_meshes_flat(w.done());
const out: RMesh[] = [];
const n = new FlatReader(buf).count();
for (let k = 0, i = 1; k < n && i + 25 <= buf.length; k++, i += 25) {
const positions = new Array<number>(24);
for (let j = 0; j < 24; j++) positions[j] = buf[i + 1 + j];
out.push({ positions, indices: [...OPENING_BOX_TRIS], kind: "extrusion", color: PART_RGB[buf[i]] ?? PART_RGB[1] });
}
return out;
}
/**
* Rahmen-Ring (Pfosten links/rechts, Riegel oben, Riegel unten nur bei
* `bottom`) über das Feld `[from,to]×[zB,zT]` mit Profilbreite `w`, ohne
* überlappende Profile; `join` bestimmt die durchlaufenden Glieder. Glieder als
* (u,h)-Vierecke: (from,UK), (to,UK), (from,OK), (to,OK). Rechnet im Kern.
*/
export function frameRingQuads(
from: number,
to: number,
zB: number,
zT: number,
w: number,
join: FrameCornerJoin,
bottom: boolean,
): Array<[[number, number], [number, number], [number, number], [number, number]]> {
const r = new FlatReader(core().frame_ring_quads_flat(from, to, zB, zT, w, JOIN_CODE[join] ?? 0, bottom));
const out: Array<[[number, number], [number, number], [number, number], [number, number]]> = [];
for (let n = r.count(); n > 0; n--) {
out.push([
[r.num(), r.num()],
[r.num(), r.num()],
[r.num(), r.num()],
[r.num(), r.num()],
]);
}
return out;
}
-36
View File
@@ -1,36 +0,0 @@
import { describe, expect, it } from "vitest";
import type { Vec3 } from "../../geometry/roof";
import { mitredRoofOffsets } from "./roofs";
// Walmdach 12×7 m: zwei Trapeze + zwei Walm-Dreiecke, First (3,3)-(8,3).
const planes: Vec3[][] = [
[[-0.5, -0.5, 5.2], [11.5, -0.5, 5.2], [8, 3, 7.061], [3, 3, 7.061]],
[[-0.5, 6.5, 5.2], [11.5, 6.5, 5.2], [8, 3, 7.061], [3, 3, 7.061]],
[[-0.5, -0.5, 5.2], [-0.5, 6.5, 5.2], [3, 3, 7.061]],
[[11.5, -0.5, 5.2], [11.5, 6.5, 5.2], [8, 3, 7.061]],
];
const near = (a: Vec3, b: Vec3) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]) < 1e-6;
describe("mitredRoofOffsets", () => {
const m = mitredRoofOffsets(planes);
it("erkennt First und Grate als geteilte Kanten, Traufen als frei", () => {
expect(m.shared[0]).toEqual([false, true, true, true]); // Traufe, Grat, First, Grat
expect(m.shared[2]).toEqual([false, true, true]);
});
it("Unterseiten treffen sich am First-Apex in EINEM Punkt (Gehrung statt Durchdringung)", () => {
const d = 0.27;
const apexA = m.at(0, d)[3]; // (3,3) der Trapezfläche
const apexB = m.at(1, d)[3];
const apexC = m.at(2, d)[2]; // Walm-Spitze
expect(near(apexA, apexB)).toBe(true);
expect(near(apexA, apexC)).toBe(true);
expect(apexA[2]).toBeLessThan(7.061);
});
it("Versatz 0 = Originalfläche, freie Traufecke bleibt senkrecht versetzt", () => {
expect(m.at(0, 0)).toEqual(planes[0]);
const eaves = m.at(0, 0.2)[0];
// Traufecke (−0.5,−0.5) teilt den Grat mit dem Walm → gehrt, aber Höhe unter der Traufe.
expect(eaves[2]).toBeLessThan(5.2);
});
});
+3 -3
View File
@@ -1,8 +1,8 @@
// Dach-Meshes (`emitRoofs`) sind je Schicht geschlossene, nach aussen gewundene Körper — Voraussetzung
// Dach-Meshes (`roofMeshes`) sind je Schicht geschlossene, nach aussen gewundene Körper — Voraussetzung
// für Closed-Face-Sets im IFC und korrektes Rückseiten-Culling.
import { describe, expect, it } from "vitest";
import { emitRoofs } from "./roofs";
import { roofMeshes } from "../toWalls3d";
import { isWatertight } from "../wallMeshCut";
import { sampleProject } from "../../model/sampleProject";
import type { Project, Roof, RoofShape } from "../../model/types";
@@ -37,7 +37,7 @@ describe("Dach-Meshes geschlossen und nach aussen gewunden", () => {
for (const axis of ["x", "y"] as const) {
it(`${shape} (First ${axis})`, () => {
const p: Project = { ...sampleProject, roofs: [roof(shape, axis)] };
const meshes = emitRoofs(p);
const meshes = roofMeshes(p);
expect(meshes.length).toBeGreaterThan(0);
for (const m of meshes) {
const c = closure(m);
-298
View File
@@ -1,298 +0,0 @@
// Dach-Domäne der 3D-Ableitung: emittiert Dächer (`project.roofs`) als
// geschlossene, geschichtete Dreiecks-Meshes (Eindeckung → innen) aus den
// geneigten Dachflächen (`RoofGeometry.planes`) — jede Schicht ein eigener
// solider Slab mit ihrer Bauteilfarbe/-textur.
import type { Project } from "../../model/types";
import { getComponent, roofLayers } from "../../model/types";
import { roofBaseElevation, roofGeometry } from "../../geometry/roof";
import type { Vec3 as RoofVec3 } from "../../geometry/roof";
import {
EPS,
hexToRgb,
resolveComponentMaterialLayer,
resolveCutLineStyle,
type RCutMeta,
type RMesh,
type RRgb,
type RRoofLayer,
} from "./shared";
/** Warmer Terrakotta-Grauton für Dachflächen/-giebel — hebt das Dach klar von Wand/Decke/Kontext ab. */
const ROOF_RGB: RRgb = [0.72, 0.45, 0.36];
/**
* Trianguliert ein KONVEXES 3D-Polygon per Dreiecks-Fächer ab Vertex 0 und hängt
* die Dreiecke an `positions`/`indices` an. `roofGeometry` (Vertrag in
* `geometry/roof.ts`) liefert für `planes`/`gables` ausschliesslich konvexe
* Polygone (Dreieck/Quader bei den meisten Formen, ein Fünfeck-Giebel bei
* Mansarde) — ein Fächer trianguliert diese korrekt, ohne Ear-Clipping.
*/
function pushFanTriangles(positions: number[], indices: number[], pts: RoofVec3[], flip = false): void {
if (pts.length < 3) return;
const base = positions.length / 3;
for (const p of pts) positions.push(p[0], p[1], p[2]);
for (let i = 1; i < pts.length - 1; i++) {
if (flip) indices.push(base, base + i + 1, base + i);
else indices.push(base, base + i, base + i + 1);
}
}
/**
* Robuste Flächennormale (Newell) einer Polygon-Ebene in MODELL-Koordinaten
* ([x, y, z=Höhe]), nach OBEN orientiert (positive Höhen-Komponente) — für die
* Dach-Dickenversetzung (Unterseite = Oberseite − Normale·Dicke).
*/
function planeNormalUp(pts: RoofVec3[]): [number, number, number] {
let nx = 0;
let ny = 0;
let nz = 0;
for (let i = 0; i < pts.length; i++) {
const c = pts[i];
const d = pts[(i + 1) % pts.length];
nx += (c[1] - d[1]) * (c[2] + d[2]);
ny += (c[2] - d[2]) * (c[0] + d[0]);
nz += (c[0] - d[0]) * (c[1] + d[1]);
}
const len = Math.hypot(nx, ny, nz) || 1;
const u: [number, number, number] = [nx / len, ny / len, nz / len];
return u[2] < 0 ? [-u[0], -u[1], -u[2]] : u;
}
/**
* Gehrte Versatz-Ecken für ALLE Dachflächen eines Daches: liefert je Fläche die
* um `d` (Meter, entlang der Flächennormalen nach innen) versetzten Ecken —
* aber an Kanten, die sich zwei Flächen teilen (First/Grat/Knick), NICHT
* stur entlang der EIGENEN Normalen, sondern auf der Gehrung: die Ecke liegt im
* Schnitt der versetzten Ebenen beider Flächen. Vorher durchdrangen sich die
* Slabs benachbarter Flächen am First, ihre Stirnflächen lagen deckungsgleich
* auf der Nachbar-Oberseite (Störtriangle am First-Apex im „Schattiert mit
* Kanten"-Modus). Freie Kanten (Traufe/Ortgang) behalten die senkrechte
* Stirnfläche. `shared[i][k]` = Kante k→k+1 von Fläche i ist geteilt.
*/
export function mitredRoofOffsets(planes: RoofVec3[][]): {
at: (i: number, d: number) => RoofVec3[];
shared: boolean[][];
} {
const r = (v: number) => Math.round(v * 1e5);
const pk = (p: RoofVec3) => `${r(p[0])},${r(p[1])},${r(p[2])}`;
const ek = (a: RoofVec3, b: RoofVec3) => {
const ka = pk(a);
const kb = pk(b);
return ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`;
};
const edgeOwners = new Map<string, number[]>();
planes.forEach((pts, i) => {
for (let k = 0; k < pts.length; k++) {
const key = ek(pts[k], pts[(k + 1) % pts.length]);
const list = edgeOwners.get(key);
if (list) list.push(i);
else edgeOwners.set(key, [i]);
}
});
const normals = planes.map((pts) => planeNormalUp(pts));
const neighbor = planes.map((pts, i) =>
pts.map((p, k) => {
const owners = edgeOwners.get(ek(p, pts[(k + 1) % pts.length])) ?? [];
const j = owners.find((o) => o !== i);
return j === undefined ? -1 : j;
}),
);
const shared = neighbor.map((row) => row.map((j) => j >= 0));
const dot = (a: RoofVec3, b: RoofVec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a: RoofVec3, b: RoofVec3): RoofVec3 => [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
// Ebene (Normale m, Abstand c: m·x = c) der Kante k→k+1 von Fläche i beim Versatz d:
// geteilt → versetzte Nachbarebene (Gehrung), frei → senkrechte Stirnebene.
const edgePlane = (i: number, k: number, d: number): [RoofVec3, number] => {
const pts = planes[i];
const a = pts[k];
const b = pts[(k + 1) % pts.length];
const j = neighbor[i][k];
if (j >= 0) return [normals[j], dot(normals[j], planes[j][0]) - d];
const dir: RoofVec3 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
const m = cross(dir, normals[i]);
return [m, dot(m, a)];
};
// Schnittpunkt dreier Ebenen (Cramer über Kreuzprodukte), null wenn entartet.
const solve = (rows: Array<[RoofVec3, number]>): RoofVec3 | null => {
const [[a, ca], [b, cb], [c, cc]] = rows;
const bc = cross(b, c);
const det = dot(a, bc);
if (Math.abs(det) < 1e-9) return null;
const cxa = cross(c, a);
const axb = cross(a, b);
return [
(ca * bc[0] + cb * cxa[0] + cc * axb[0]) / det,
(ca * bc[1] + cb * cxa[1] + cc * axb[1]) / det,
(ca * bc[2] + cb * cxa[2] + cc * axb[2]) / det,
];
};
const at = (i: number, d: number): RoofVec3[] => {
const pts = planes[i];
const n = normals[i];
if (d <= EPS) return pts.map((p) => [p[0], p[1], p[2]]);
const own: [RoofVec3, number] = [n, dot(n, pts[0]) - d];
return pts.map((p, k) => {
const prev = (k + pts.length - 1) % pts.length;
const fallback: RoofVec3 = [p[0] - n[0] * d, p[1] - n[1] * d, p[2] - n[2] * d];
if (!shared[i][prev] && !shared[i][k]) return fallback;
const q = solve([own, edgePlane(i, prev, d), edgePlane(i, k, d)]);
// Ausreisser (fast parallele Ebenen) abfangen: nicht weiter als ein paar
// Dicken von der senkrechten Lösung entfernt.
if (!q || Math.hypot(q[0] - fallback[0], q[1] - fallback[1], q[2] - fallback[2]) > 4 * d + 0.5) {
return fallback;
}
return q;
});
};
return { at, shared };
}
/**
* Slab einer Dachfläche zwischen fertigen Ober-/Unterseiten-Ecken (gleiche
* Reihenfolge). Stirnflächen nur an FREIEN Kanten (`shared[k]` = false) — an
* geteilten Kanten stossen die Nachbarflächen auf Gehrung, eine Stirnfläche
* läge dort im Inneren des Dachs.
*/
function pushRoofSlabBetween(
positions: number[],
indices: number[],
top: RoofVec3[],
bottom: RoofVec3[],
shared: boolean[],
): void {
// Wicklung nach aussen (geschlossener Körper, s. roofWinding.test.ts): Umlaufsinn der
// Oberseite von oben gesehen (Newell, Höhen-Komponente). Gegen den Uhrzeigersinn ⇒ Oberseite
// wie gegeben, Unterseite umgekehrt, Stirnfläche je Kante i→j als top[i], bottom[i], bottom[j],
// top[j] (Normale zeigt rechts der Kante = aussen); im Uhrzeigersinn alles gespiegelt.
let nz = 0;
for (let i = 0; i < top.length; i++) {
const a = top[i];
const b = top[(i + 1) % top.length];
nz += (a[0] - b[0]) * (a[1] + b[1]);
}
const ccw = nz > 0;
pushFanTriangles(positions, indices, top, !ccw);
pushFanTriangles(positions, indices, bottom, ccw);
for (let i = 0; i < top.length; i++) {
if (shared[i]) continue;
const j = (i + 1) % top.length;
const base = positions.length / 3;
positions.push(top[i][0], top[i][1], top[i][2]);
positions.push(bottom[i][0], bottom[i][1], bottom[i][2]);
positions.push(bottom[j][0], bottom[j][1], bottom[j][2]);
positions.push(top[j][0], top[j][1], top[j][2]);
if (ccw) indices.push(base, base + 1, base + 2, base, base + 2, base + 3);
else indices.push(base, base + 2, base + 1, base, base + 3, base + 2);
}
}
/**
* Emittiert Dächer (`project.roofs`) als geschlossene Dreiecks-Meshes: sowohl die
* geneigten Dachflächen (`RoofGeometry.planes`) als auch die Giebelflächen
* (`RoofGeometry.gables`) — erst zusammen bilden sie einen von aussen
* geschlossenen Körper (die Giebel schliessen die offenen Enden bei Sattel/
* Mansarde, die First-/Grat-/Knicklinien sind reine Grundriss-Hilfslinien und
* werden hier nicht gebraucht). Traufhöhe über `roofBaseElevation`
* (Override oder Geschoss-Oberkante), Flächen über `roofGeometry`. Farbe:
* `roof.color` (falls gültiges Hex), sonst {@link ROOF_RGB}. `positions` in
* MODELL-Metern (x, y, z=Höhe); render3d rendert Kontext-Meshes doppelseitig,
* die Winding-Reihenfolge ist also unerheblich.
*/
export function emitRoofs(project: Project): RMesh[] {
const out: RMesh[] = [];
for (const roof of project.roofs ?? []) {
const eavesZ = roofBaseElevation(project, roof);
const g = roofGeometry(roof, eavesZ);
const overrideColor = roof.color ? hexToRgb(roof.color, ROOF_RGB) : null;
// Schichtaufbau (aussen/Eindeckung → innen). Jede Schicht wird zu einem
// eigenen RMesh mit ihrer Bauteilfarbe, entlang der Flächennormalen unter die
// vorige gestapelt. Leere componentId (einschichtige thickness-Fallback) ⇒
// Default-Dachfarbe. Eine Roof.color-Übersteuerung gilt für alle Schichten.
const layers = roofLayers(project, roof);
const mitre = mitredRoofOffsets(g.planes.map((pl) => pl.pts));
layers.reduce((offsetAbove, layer) => {
const t = Math.max(0, layer.thickness);
if (t <= EPS) return offsetAbove;
const color =
overrideColor ??
(layer.componentId ? hexToRgb(getComponent(project, layer.componentId).color, ROOF_RGB) : ROOF_RGB);
// Material-Textur-Ebene fürs Textured-Rendering (z. B. echte Dachziegel-
// Textur der Eindeckung) — nur wenn KEIN Farb-Override greift (Override
// = bewusst eine einheitliche Farbe für alle Schichten, kein Bauteil-Bezug).
const materialIndex =
!overrideColor && layer.componentId
? resolveComponentMaterialLayer(project, layer.componentId)
: undefined;
const positions: number[] = [];
const indices: number[] = [];
g.planes.forEach((plane, i) => {
// Oberseite dieser Schicht = Dachfläche um `offsetAbove` nach innen
// versetzt, Unterseite um `offsetAbove + t` — an First/Grat gehrt.
if (plane.pts.length < 3) return;
const top = mitre.at(i, offsetAbove);
const bottom = mitre.at(i, offsetAbove + t);
pushRoofSlabBetween(positions, indices, top, bottom, mitre.shared[i]);
});
if (indices.length > 0) out.push({ positions, indices, kind: "extrusion", color, materialIndex });
return offsetAbove + t;
}, 0);
// Giebel-ENDFÜLLUNG bewusst NICHT mehr emittieren: die dreieckige Giebelfläche
// wurde früher als papierdünne Einzelfläche gebaut ("komischer Abschluss" an
// den Sattel-/Mansard-Enden) und lag zudem deckungsgleich vor der Giebelwand,
// die ohnehin bis an die Dach-Unterkante hochgeklemmt wird (s.
// `../bands.ts::clipPieceToRoofs`) — also doppelt und optisch als dünne
// 2D-Schicht sichtbar. Es wird nur noch das Dach SELBST (die geneigten
// Slab-Flächen) konstruiert; der Giebel entsteht aus der Wand darunter.
}
return out;
}
/**
* Baut die Dach-Schicht-Eingabe für den 3D-Live-Schnitt (`RRoofLayer[]`,
* `render3d::roof_cut::cut_roof_layer`) — GETRENNT von {@link emitRoofs} (dem
* Render-Mesh), weil `section.rs` beliebige Dreiecksnetze nicht schneiden
* kann (nur Wand-Boxen/Decken-Polygone; eine Dachfläche ist kein vertikales
* Prisma, s. `RRoofLayer`-Doc in `shared.ts`). EIN Eintrag je (Dach, Schicht,
* geneigte Fläche) — ein mehrflächiges Dach (Sattel/Walm/Mansarde) hat
* mehrere `g.planes`, jede mit ihrer eigenen Normalen, anders als beim
* gemeinsam tessellierten Render-Mesh also KEIN zusammengefasster Eintrag.
* Punkte/Normalen bleiben in MODELL-Metern (wie `emitRoofs`) — render3d macht
* den Modell->Welt-Wechsel selbst (dieselbe Konvention wie `RMesh`).
*/
export function emitRoofCutLayers(project: Project): RRoofLayer[] {
const out: RRoofLayer[] = [];
for (const roof of project.roofs ?? []) {
const eavesZ = roofBaseElevation(project, roof);
const g = roofGeometry(roof, eavesZ);
const overrideColor = roof.color ? hexToRgb(roof.color, ROOF_RGB) : null;
const layers = roofLayers(project, roof);
layers.reduce((offsetAbove, layer) => {
const t = Math.max(0, layer.thickness);
if (t <= EPS) return offsetAbove;
const color =
overrideColor ??
(layer.componentId ? hexToRgb(getComponent(project, layer.componentId).color, ROOF_RGB) : ROOF_RGB);
const lineStyle = resolveCutLineStyle(project, layer.jointLineStyleId);
const cut: RCutMeta | undefined =
lineStyle && (lineStyle.color !== undefined || lineStyle.weight !== undefined)
? { lineColor: lineStyle.color, lineWeight: lineStyle.weight }
: undefined;
for (const plane of g.planes) {
const nrm = planeNormalUp(plane.pts);
const top: RoofVec3[] = plane.pts.map((p) => [
p[0] - nrm[0] * offsetAbove,
p[1] - nrm[1] * offsetAbove,
p[2] - nrm[2] * offsetAbove,
]);
out.push({ polygon: top, normal: nrm, thickness: t, color, cut });
}
return offsetAbove + t;
}, 0);
}
return out;
}
+1 -180
View File
@@ -1,15 +1,12 @@
// Gemeinsame Grundlage der 3D-Ableitung: das Serde-Vokabular (`RWall`/`RSlab`/
// `RMesh`/…, matcht 1:1 render3d::types) sowie die Farb-/Schraffur-/Material-
// Auflösung, die über mehrere Bauteil-Domänen hinweg identisch gelten muss
// (Hex→RGB, dominante Schicht, Schnitt-Schraffur, Material-Textur-Ebene).
// (Hex→RGB). Die Ableitung selbst rechnet der Rust-Kern (`src-tauri/core/src/model3d.rs`).
//
// Jede Datei unter `toWalls3d/` importiert von hier, NIE von `../toWalls3d`
// selbst — das hielte die Orchestrator-Datei (`toWalls3d.ts`) andernfalls in
// einem Zirkelimport mit jeder einzelnen Domäne.
import type { HatchPattern, Layer, Project } from "../../model/types";
import { getCeilingType, getComponent, getWallType, roofLayers } from "../../model/types";
import { resolveHatch } from "../generatePlan";
import type { Vec3 as RoofVec3 } from "../../geometry/roof";
export type RVec2 = [number, number];
@@ -60,144 +57,6 @@ export interface RHatch {
topAngle?: number;
}
/** Bildet ein 2D-{@link HatchPattern} auf die Muster-Id von {@link RHatch}/CAP_WGSL ab. */
function hatchPatternId(p: HatchPattern): number {
switch (p) {
case "solid":
return 1;
case "diagonal":
return 2;
case "crosshatch":
return 3;
case "insulation":
return 4;
case "none":
default:
return 0;
}
}
/**
* Löst die Schnitt-Schraffur eines Bauteils (per `Component.hatchId`) zu einem
* {@link RHatch} auf — dasselbe Muster/Winkel/Skalierung wie der 2D-Schnitt
* (`generatePlan.ts::resolveHatch`, hier bewusst NICHT aufgerufen: nur die drei
* render3d-relevanten Felder werden direkt aus dem `HatchStyle` gezogen, die
* Farbe bleibt monochrom im Shader). `undefined`, wenn das Bauteil/die Schraffur
* nicht auflösbar ist (der Cap-Shader fällt dann auf sein Diagonalmuster zurück).
*/
export function resolveComponentHatch(
project: Project,
componentId: string,
axisAngleDeg?: number,
): RHatch | undefined {
try {
const comp = getComponent(project, componentId);
if (!comp.hatchId) return undefined;
// GENAU der 2D-Schnitt-Pfad (`splitWallLayers`/`splitSlabLayers` →
// `resolveHatch`): `axisAngleDeg` = 90 für WAND-Bänder (die geschnittene Wand
// steht vertikal, `relativeToWall`-Muster drehen mit), `undefined` für DECKEN
// (kein Wandachsen-Bezug → absoluter Winkel). Wir übernehmen den ENDWINKEL
// (`HatchRender.angle`, bereits relativeToWall-korrigiert) UND die Musterlinien-
// Stärke (`lineWeight`, aus dem LineStyle) — nicht mehr den rohen Hatch-Winkel.
const hr = resolveHatch(project, comp.hatchId, axisAngleDeg);
// Wandbezug für die Draufsicht: Grundwinkel + ob das Muster der Wandachse folgt.
const abs = resolveHatch(project, comp.hatchId, undefined);
const relativeToWall = resolveHatch(project, comp.hatchId, 90).angle !== abs.angle;
return {
pattern: hatchPatternId(hr.pattern),
angle: hr.angle,
scale: hr.scale,
lineWeight: hr.lineWeight,
baseAngle: abs.angle,
relativeToWall,
};
} catch {
return undefined;
}
}
/**
* Schnitt-Schraffur der dicksten (dominanten) Schicht eines Schichtstapels.
* `axisAngleDeg` wie {@link resolveComponentHatch} (90 für Wand, undefined für Decke).
*/
export function dominantLayerHatch(
layers: Layer[],
project: Project,
axisAngleDeg?: number,
): RHatch | undefined {
if (layers.length === 0) return undefined;
const dominant = layers.reduce((best, l) => (l.thickness > best.thickness ? l : best));
return resolveComponentHatch(project, dominant.componentId, axisAngleDeg);
}
/**
* Geordnete Liste der EINDEUTIGEN Material-Farbkarten-URLs (`Component.material.
* color`), die von Wand-/Decken-Bauteilen des Projekts benutzt werden — in
* deterministischer First-Seen-Reihenfolge über `project.walls` (Wandtyp-Schichten)
* dann `project.ceilings`. Die POSITION in dieser Liste (+1) ist der Textur-Array-
* Index (`WallInput.materialIndex`, 1-basiert; Ebene 0 = Fallback-Schachbrett), den
* sowohl {@link resolveComponentMaterialLayer} (Zuweisung je Band) als auch der
* JS-Decoder (`viewport/materialTextures`) verwenden — so stimmen Band-Index und
* hochgeladene Textur-Ebene ohne separaten Map-Transport überein. Memoisiert je
* Projekt-REFERENZ (der Store ist immutabel — jede Änderung liefert ein neues
* Objekt, also kein Stale-Risiko), damit die per-Band-Auflösung nicht quadratisch wird.
*/
const materialMapCache = new WeakMap<Project, string[]>();
export function wallMaterialColorMaps(project: Project): string[] {
const cached = materialMapCache.get(project);
if (cached) return cached;
const seen = new Set<string>();
const list: string[] = [];
const consider = (componentId: string): void => {
try {
const url = getComponent(project, componentId).material?.color;
if (url && !seen.has(url)) {
seen.add(url);
list.push(url);
}
} catch {
// Unauflösbares Bauteil überspringen.
}
};
for (const w of project.walls) {
try {
for (const l of getWallType(project, w).layers) consider(l.componentId);
} catch {
// Kein auflösbarer Wandtyp.
}
}
for (const c of project.ceilings ?? []) {
try {
for (const l of getCeilingType(project, c).layers) consider(l.componentId);
} catch {
// Kein auflösbarer Deckentyp.
}
}
for (const r of project.roofs ?? []) {
for (const l of roofLayers(project, r)) {
if (l.componentId) consider(l.componentId);
}
}
materialMapCache.set(project, list);
return list;
}
/**
* Textur-Array-Ebene (1-basiert) der Material-Farbkarte eines Bauteils, oder
* `undefined`, wenn das Bauteil kein Material mit Farbkarte trägt. Ebene 0 ist das
* Fallback-Schachbrett — deshalb `indexOf + 1`. Siehe {@link wallMaterialColorMaps}.
*/
export function resolveComponentMaterialLayer(project: Project, componentId: string): number | undefined {
try {
const url = getComponent(project, componentId).material?.color;
if (!url) return undefined;
const idx = wallMaterialColorMaps(project).indexOf(url);
return idx >= 0 ? idx + 1 : undefined;
} catch {
return undefined;
}
}
/**
* Ein rechteckiges LOCH (Fenster/Tür) in EINEM Wandkörper — matcht 1:1
* render3d::types::Hole. KONVENTION: `from`/`to` sind Achsen-Meter ab
@@ -407,41 +266,3 @@ export function hexToRgb(hex: string, fallback: RRgb = WALL_RGB): RRgb {
const v = parseInt(m[1], 16);
return [((v >> 16) & 0xff) / 255, ((v >> 8) & 0xff) / 255, (v & 0xff) / 255];
}
/**
* Repräsentative Bauteilfarbe eines Schichtaufbaus: die Farbe der DICKSTEN
* Schicht (i. d. R. die tragende/dominante Schicht, z. B. Mauerwerk/Beton) —
* einfache Näherung, solange Wände/Decken als EIN Vollkörper emittiert werden
* (kein Schicht-Rendering in 3D). Fällt auf `fallback` zurück, wenn keine
* Schicht vorhanden ist oder deren Component nicht auflösbar ist.
*/
export function dominantLayerColor(layers: Layer[], project: Project, fallback: RRgb): RRgb {
if (layers.length === 0) return fallback;
const dominant = layers.reduce((best, l) => (l.thickness > best.thickness ? l : best));
try {
return hexToRgb(getComponent(project, dominant.componentId).color, fallback);
} catch {
return fallback;
}
}
/**
* Löst den Schnitt-UMRISSLINIEN-Stil einer Schicht aus ihrem
* `Layer.jointLineStyleId` (LineStyle) auf: Farbe (hex→RGB 0..1) + Strichstärke
* (mm-Papier) — dieselbe Quelle wie die 2D-Schichtfuge (`generatePlan/walls.ts`).
* Fehlt der Verweis/LineStyle, `undefined` (der 3D-Cut fällt dann auf seinen
* Default-Schnittkanten-Stil zurück, siehe `section_fill::build_cut_cap_lines`).
* Bewusst tolerant (`find` statt `getLineStyle`), wie im 2D — ein verwaister
* Verweis darf den 3D-Push nicht werfen. Von {@link ../bands.resolveWallBands}
* UND `../ceilings.emitSlabs` genutzt (Wand- wie Deckenschicht teilen dieselbe
* Fugen-Auflösung).
*/
export function resolveCutLineStyle(
project: Project,
jointLineStyleId: string | undefined,
): { color?: RRgb; weight?: number } | undefined {
if (!jointLineStyleId) return undefined;
const ls = project.lineStyles.find((l) => l.id === jointLineStyleId);
if (!ls) return undefined;
return { color: hexToRgb(ls.color, DRAWING_LINE_FALLBACK_RGB), weight: ls.weight };
}
-160
View File
@@ -1,160 +0,0 @@
// Treppen-Domäne der 3D-Ableitung: emittiert Treppen als extrudierte RSlabs
// (Tritte + Podest, tragart-abhängige Untersicht) — der WASM/wgpu-Renderer
// kennt sonst KEINE Treppen (nur Wände/Decken/Meshes). Für Ortbeton-Läufe
// zusätzlich ein glattes Dreiecks-Mesh der schrägen Laufplatten-Untersicht, und für gerade
// Läufe Handlauf + Pfosten (`StairType.railing`).
//
// Die ganze Rechnung (Tritt-Prismen je Tragart, Nasen-Verlängerung `StairType.nosing`, dünne
// Setzstufen-Platten `closedRisers`, Podest, Soffit-Scheiben im Schnitt, Laufplatten-Mesh,
// Handlauf/Pfosten-Quader) steht in Rust (`src-tauri/core/src/stairs3d.rs`, Treppengeometrie aus
// `kernel2d`). Hier nur: aus dem `Project` sammeln und die Ergebnisse einfärben.
// `ceilingId` trägt bei den Slabs die Treppen-Id (nur TS-seitiges Tagging; render3d ignoriert
// das Feld, und der Pick läuft separat über `pickGeometry`).
import type { Project, Stair, StairType } from "../../model/types";
import { getStairType } from "../../model/types";
import { stairVerticalExtent } from "../../model/wall";
import { encodeStair } from "../../geometry/stair";
import { core } from "../../engine/coreWasm";
import { SLAB_RGB, hexToRgb, type RMesh, type RRgb, type RSlab, type RVec2 } from "./shared";
/** Neutraler Beton-Grauton für Treppen (wie der Three.js-Pfad `addStairMeshes`). */
const STAIR_RGB: RRgb = hexToRgb("#9aa0a6", SLAB_RGB);
/** Neutrales Metallgrau für Handlauf + Pfosten. */
const RAIL_RGB: RRgb = hexToRgb("#74797f", SLAB_RGB);
const STRUCTURE = { massiv: 0, beton: 1, wange: 2, aufgesattelt: 2, spindel: 2 } as const;
const RAILING = { keine: 0, links: 1, rechts: 2, beide: 3 } as const;
/**
* Flache Rust-Eingabe der Treppen (Aufbau: `stairs3d.rs`); `null` ohne Treppen. `wanted` wählt
* nur vor, welche Treppen sich lohnen (spart den WASM-Aufruf); die Regeln selbst prüft Rust.
*/
function stairInput(
project: Project,
wanted: (stair: Stair, st: StairType | undefined) => boolean = () => true,
): { stairs: Stair[]; buf: Float64Array } | null {
const stairs: Stair[] = [];
const types: (StairType | undefined)[] = [];
for (const stair of project.stairs ?? []) {
const st = getStairType(project, stair);
if (!wanted(stair, st)) continue;
stairs.push(stair);
types.push(st);
}
if (stairs.length === 0) return null;
const buf = new Float64Array(1 + 23 * stairs.length);
buf[0] = stairs.length;
stairs.forEach((stair, k) => {
const { zBottom, zTop } = stairVerticalExtent(project, stair);
const st = types[k];
const o = 1 + 23 * k;
buf.set(encodeStair(stair), o);
buf[o + 16] = zBottom;
buf[o + 17] = zTop;
buf[o + 18] = STRUCTURE[st?.structure ?? "massiv"] ?? 2;
buf[o + 19] = st?.treadThickness ?? 0.04;
buf[o + 20] = st?.nosing ?? 0;
buf[o + 21] = st?.closedRisers ? 1 : 0;
buf[o + 22] = RAILING[st?.railing ?? "keine"] ?? 0;
});
return { stairs, buf };
}
/** Rust-Meshes `[n, (treppe, nPos, nIdx, positionen…, indizes…)…]` → `RMesh[]`. */
function meshesOf(f: Float64Array, color: RRgb): RMesh[] {
const out: RMesh[] = [];
let i = 1;
for (let n = f.length ? f[0] : 0; n > 0; n--) {
const nPos = f[i + 1];
const nIdx = f[i + 2];
i += 3;
const positions: number[] = [];
for (let k = 0; k < nPos; k++) positions.push(f[i + k]);
i += nPos;
const indices: number[] = [];
for (let k = 0; k < nIdx; k++) indices.push(f[i + k]);
i += nIdx;
out.push({ positions, indices, kind: "extrusion", color });
}
return out;
}
/**
* Emittiert Treppen als RSlabs (extrudierte Grundriss-Polygone) — der WASM/wgpu-
* Renderer kennt sonst KEINE Treppen (nur Wände/Decken/Meshes), sodass Treppen im
* Standard-3D unsichtbar blieben. Jeder Tritt ist ein extrudiertes Polygon; das
* ist exakt eine RSlab. Tragart über `getStairType`:
* • "massiv" / kein Typ — Vollblock je Tritt von der Treppen-UK bis zur Tritt-OK
* (gestuftes Massiv, Treppe auf Erdreich/Sockel).
* • "beton" — Ortbeton-Laufplatte: je Tritt ein Block von der SCHRÄGEN Untersicht
* (eine Stufe + Laufplattendicke unter der Tritt-OK, an der Treppen-UK gekappt)
* bis zur Tritt-OK. Die stufig gestapelten Blöcke bilden die schräge, UNTEN
* OFFENE Untersicht der klassischen Betontreppe.
* • "wange"/"aufgesattelt"/"spindel" — nur eine dünne Tritt-Platte der Dicke
* `treadThickness` an der Tritt-OK, darunter offen.
* Podest (L/Wendel) als Vollblock bis zur halben Steighöhe. Bei OFFENEN
* Tragarten wird die Vorderkante jedes Tritts zusätzlich um `StairType.nosing`
* (Trittkanten-Überstand) verlängert und — bei `StairType.closedRisers` — eine dünne
* Setzstufen-Platte an der Rückkante ergänzt. Massiv/Beton bilden EIN Körper
* (`monolith`, s. render3d `SlabInput::monolith`).
*/
export function emitStairs(
project: Project,
/**
* `forSection`: auch gerade Betontreppen als Tritt-Prismen liefern (deren
* glatte Laufplatte ist im 3D ein Mesh, das der Schnitt-Extraktor nicht
* schneiden kann — ohne diese Näherung fehlte die Treppe im Schnitt ganz).
*/
opts: { forSection?: boolean } = {},
): RSlab[] {
const input = stairInput(project);
if (!input) return [];
const f = core().stairs3d_slabs_flat(input.buf, !!opts.forSection);
const out: RSlab[] = [];
let i = 1;
for (let n = f.length ? f[0] : 0; n > 0; n--) {
const stair = input.stairs[f[i]];
const monolith = f[i + 1] !== 0;
const zBottom = f[i + 2];
const zTop = f[i + 3];
const nPts = f[i + 4];
i += 5;
const outline: RVec2[] = new Array(nPts);
for (let k = 0; k < nPts; k++, i += 2) outline[k] = [f[i], f[i + 1]];
out.push({
outline,
zBottom,
zTop,
color: STAIR_RGB,
ceilingId: stair.id,
...(monolith ? { monolith: stair.id } : {}),
});
}
return out;
}
/**
* Glatte Ortbeton-Laufplatte (Tragart "beton") als echtes Dreiecks-Mesh — nur für
* GERADE Läufe. Anders als die stufige Slab-Näherung ({@link emitStairs}) entsteht
* eine SPIEGELGLATTE schräge Untersicht: je Tritt ein konvexes Prisma mit
* HORIZONTALER Oberkante (= Trittfläche) und SCHRÄGER Unterkante auf EINER
* gemeinsamen Soffit-Geraden. Positions in MODELL-Metern (x, y, z=Höhe); render3d bildet
* nach world (x, z, y) ab.
*/
export function emitStairMeshes(project: Project): RMesh[] {
// Nur gerade Betontreppen haben eine glatte Laufplatte.
const input = stairInput(project, (s, st) => st?.structure === "beton" && s.shape === "straight");
return input ? meshesOf(core().stairs3d_meshes_flat(input.buf), STAIR_RGB) : [];
}
/**
* Handlauf + Pfosten (`StairType.railing`: "keine"|"links"|"rechts"|"beide"). Nur für GERADE
* Läufe: dort liegt die Vorderkante jedes Tritts exakt auf der linearen Rampen-Geraden, ein
* gerades, schräges Segment je Seite + ein Pfosten je Trittvorderkante genügen. L-Läufe und
* Wendeltreppen bleiben bewusst aussen vor (eigener Folgeschritt).
*/
export function emitStairRailings(project: Project): RMesh[] {
const input = stairInput(project, (s, st) => s.shape === "straight" && (st?.railing ?? "keine") !== "keine");
return input ? meshesOf(core().stairs3d_railings_flat(input.buf), RAIL_RGB) : [];
}