Merge rust-core-k4 (Laptop): [K1][K3a][K3c][K3d][K4] Kern-Port; IFC-/Mesh-Export bleibt in fileio (Kern-Duplikate entfernt), Exporte holen 3D-Teile aus dem Dokument

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-28 17:35:14 +00:00
commit 3bf9eea5f9
111 files changed
+14145 -6506

No files matched your search

+63
View File
@@ -31,9 +31,29 @@ dependencies = [
"console_error_panic_hook",
"i_overlay",
"kernel2d",
"serde",
"serde_json",
"wasm-bindgen",
]
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "i_float"
version = "5.0.0"
@@ -76,6 +96,22 @@ version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "048af31de955890c62a8506fec511335a5089e91e1c516537add16f96c507d84"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "kernel2d"
version = "0.1.0"
@@ -89,6 +125,12 @@ version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "once_cell"
version = "1.21.4"
@@ -149,6 +191,21 @@ dependencies = [
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"foldhash",
"indexmap",
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "3.0.9"
@@ -210,3 +267,9 @@ checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
dependencies = [
"unicode-ident",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+2
View File
@@ -19,6 +19,8 @@ web = ["dep:wasm-bindgen", "dep:console_error_panic_hook"]
[dependencies]
i_overlay = { version = "9.1", default-features = false }
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["preserve_order", "float_roundtrip"] }
kernel2d = { path = "../kernel2d" }
wasm-bindgen = { version = "0.2", optional = true }
console_error_panic_hook = { version = "0.1", optional = true }
-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 {
+187
View File
@@ -0,0 +1,187 @@
//! Ellipse, Bezier und Splines tessellieren ([K1]): Port von `src/geometry/curves.ts`. Punkte als flache
//! `[x0, y0, x1, y1, …]`. Rechenreihenfolge wie in TS; `cos/sin/pow` über `jsnum` (bitgleich zur
//! JS-Engine). Unsinn (zu viele Schritte) → leer, nie Panic.
use crate::jsnum::{cos, pow, sin};
const MAX_STEPS: usize = 100_000;
fn pts_of(f: &[f64]) -> Vec<(f64, f64)> {
f.chunks_exact(2).map(|c| (c[0], c[1])).collect()
}
fn flat(p: &[(f64, f64)]) -> Vec<f64> {
p.iter().flat_map(|q| [q.0, q.1]).collect()
}
pub fn ellipse(cx: f64, cy: f64, rx: f64, ry: f64, rotation: f64, n: f64) -> Vec<f64> {
if !(n >= 0.0) || n > MAX_STEPS as f64 {
return Vec::new();
}
let n = n as usize;
let (cos_r, sin_r) = (cos(rotation), sin(rotation));
let mut out = Vec::with_capacity(2 * n);
for i in 0..n {
let t = (i as f64 / n as f64) * std::f64::consts::PI * 2.0;
let lx = rx * cos(t);
let ly = ry * sin(t);
out.push(cx + lx * cos_r - ly * sin_r);
out.push(cy + lx * sin_r + ly * cos_r);
}
out
}
fn cubic_point(p0: (f64, f64), p1: (f64, f64), p2: (f64, f64), p3: (f64, f64), t: f64) -> (f64, f64) {
let u = 1.0 - t;
let a = u * u * u;
let b = 3.0 * u * u * t;
let c = 3.0 * u * t * t;
let d = t * t * t;
(a * p0.0 + b * p1.0 + c * p2.0 + d * p3.0, a * p0.1 + b * p1.1 + c * p2.1 + d * p3.1)
}
pub fn bezier_chain(f: &[f64], segs_per_curve: f64) -> Vec<f64> {
let pts = pts_of(f);
if pts.len() < 4 {
return flat(&pts);
}
if !(segs_per_curve >= 0.0) || segs_per_curve > 4096.0 {
return Vec::new();
}
let segs = segs_per_curve as usize;
let mut out = vec![pts[0]];
let mut i = 0;
while i + 3 < pts.len() {
for s in 1..=segs {
out.push(cubic_point(pts[i], pts[i + 1], pts[i + 2], pts[i + 3], s as f64 / segs as f64));
}
i += 3;
}
flat(&out)
}
fn cr_point(pts: &[(f64, f64)], i: i64, closed: bool) -> (f64, f64) {
let n = pts.len() as i64;
if closed {
return pts[(((i % n) + n) % n) as usize];
}
if i < 0 {
return pts[0];
}
if i >= n {
return pts[(n - 1) as usize];
}
pts[i as usize]
}
pub fn catmull_rom(f: &[f64], closed: bool, segs_per_span: f64) -> Vec<f64> {
let pts = pts_of(f);
if pts.len() < 3 {
return flat(&pts);
}
if !(segs_per_span >= 0.0) || segs_per_span > 4096.0 {
return Vec::new();
}
let segs = segs_per_span as usize;
let mut out: Vec<(f64, f64)> = Vec::new();
let spans = if closed { pts.len() } else { pts.len() - 1 };
for i in 0..spans as i64 {
let p0 = cr_point(&pts, i - 1, closed);
let p1 = cr_point(&pts, i, closed);
let p2 = cr_point(&pts, i + 1, closed);
let p3 = cr_point(&pts, i + 2, closed);
for s in 0..segs {
let t = s as f64 / segs as f64;
let t2 = t * t;
let t3 = t2 * t;
let x = 0.5
* (2.0 * p1.0 + (-p0.0 + p2.0) * t + (2.0 * p0.0 - 5.0 * p1.0 + 4.0 * p2.0 - p3.0) * t2 + (-p0.0 + 3.0 * p1.0 - 3.0 * p2.0 + p3.0) * t3);
let y = 0.5
* (2.0 * p1.1 + (-p0.1 + p2.1) * t + (2.0 * p0.1 - 5.0 * p1.1 + 4.0 * p2.1 - p3.1) * t2 + (-p0.1 + 3.0 * p1.1 - 3.0 * p2.1 + p3.1) * t3);
out.push((x, y));
}
}
if !closed {
out.push(pts[pts.len() - 1]);
}
flat(&out)
}
fn bspline_seg_point(p0: (f64, f64), p1: (f64, f64), p2: (f64, f64), p3: (f64, f64), t: f64) -> (f64, f64) {
let t2 = t * t;
let t3 = t2 * t;
let b0 = pow(1.0 - t, 3.0) / 6.0;
let b1 = (3.0 * t3 - 6.0 * t2 + 4.0) / 6.0;
let b2 = (-3.0 * t3 + 3.0 * t2 + 3.0 * t + 1.0) / 6.0;
let b3 = t3 / 6.0;
(p0.0 * b0 + p1.0 * b1 + p2.0 * b2 + p3.0 * b3, p0.1 * b0 + p1.1 * b1 + p2.1 * b2 + p3.1 * b3)
}
pub fn uniform_bspline(f: &[f64], closed: bool, segs_per_span: f64) -> Vec<f64> {
let pts = pts_of(f);
if pts.len() < 3 {
return flat(&pts);
}
if !(segs_per_span >= 0.0) || segs_per_span > 4096.0 {
return Vec::new();
}
let segs = segs_per_span as usize;
let mut out: Vec<(f64, f64)> = Vec::new();
if closed {
let n = pts.len() as i64;
let at = |i: i64| pts[(((i % n) + n) % n) as usize];
for i in 0..n {
for s in 0..segs {
out.push(bspline_seg_point(at(i - 1), at(i), at(i + 1), at(i + 2), s as f64 / segs as f64));
}
}
return flat(&out);
}
let last = pts[pts.len() - 1];
let mut padded = vec![pts[0], pts[0]];
padded.extend_from_slice(&pts);
padded.push(last);
padded.push(last);
let spans = padded.len() - 3;
for i in 0..spans {
for s in 0..segs {
out.push(bspline_seg_point(padded[i], padded[i + 1], padded[i + 2], padded[i + 3], s as f64 / segs as f64));
}
}
out.push(last);
flat(&out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ellipse_hat_n_punkte_und_beginnt_rechts() {
let e = ellipse(1.0, 2.0, 3.0, 1.0, 0.0, 64.0);
assert_eq!(e.len(), 128);
assert!((e[0] - 4.0).abs() < 1e-12 && (e[1] - 2.0).abs() < 1e-12);
assert!(ellipse(0.0, 0.0, 1.0, 1.0, 0.0, 1e9).is_empty());
}
#[test]
fn bezier_endet_im_letzten_anker() {
let f = [0.0, 0.0, 1.0, 2.0, 2.0, 2.0, 3.0, 0.0];
let b = bezier_chain(&f, 24.0);
assert_eq!(b.len(), 2 * 25);
assert_eq!(&b[b.len() - 2..], &[3.0, 0.0]);
assert_eq!(bezier_chain(&[0.0, 0.0, 1.0, 1.0], 24.0), vec![0.0, 0.0, 1.0, 1.0]);
}
#[test]
fn spline_beruehrt_die_enden_offen() {
let f = [0.0, 0.0, 1.0, 1.0, 2.0, 0.0, 3.0, 1.0];
let c = catmull_rom(&f, false, 16.0);
assert_eq!((c[0], c[1]), (0.0, 0.0));
assert_eq!(&c[c.len() - 2..], &[3.0, 1.0]);
let b = uniform_bspline(&f, false, 16.0);
assert!((b[0]).abs() < 1e-9);
assert_eq!(&b[b.len() - 2..], &[3.0, 1.0]);
assert_eq!(uniform_bspline(&f, true, 16.0).len(), 2 * 4 * 16);
}
}
+538
View File
@@ -0,0 +1,538 @@
//! Delaunay-Triangulierung ([K1]): Port von `delaunator` 5.1.0 (Volodymyr Agafonkin / Mapbox, ISC-Lizenz,
//! https://github.com/mapbox/delaunator) samt exaktem
//! `orient2d` (robust-predicates). Dieselbe Reihenfolge der Schritte wie in JS, damit Dreiecke und
//! deren Indizes bitgleich herauskommen — auch bei kozirkulären Punkten (Raster). Verwendet vom
//! Gelände-TIN (`model/terrain.ts`) und den Kontext-Gebäuden (`io/geoContext.ts`).
//!
//! `triangulate(coords)` mit `coords = [x0, y0, x1, y1 …]` → Dreiecks-Indizes (je drei, gegen den
//! Uhrzeigersinn); leer bei < 3 Punkten, nur kollinearen Punkten oder nicht endlichen Werten.
const EPSILON: f64 = 1.0 / 4503599627370496.0; // 2^-52
const EDGE_STACK_LEN: usize = 512;
// ── exaktes orient2d ───────────────────────────────────────────────────────
fn two_sum(a: f64, b: f64) -> (f64, f64) {
let x = a + b;
let bv = x - a;
let av = x - bv;
(x, (a - av) + (b - bv))
}
fn two_product(a: f64, b: f64) -> (f64, f64) {
let x = a * b;
(x, a.mul_add(b, -x))
}
/// Summe einer Expansion (aufsteigend, nicht überlappend) und eines Doubles.
fn grow(e: &[f64], b: f64) -> Vec<f64> {
let mut out = Vec::with_capacity(e.len() + 1);
let mut q = b;
for &x in e {
let (s, t) = two_sum(q, x);
q = s;
if t != 0.0 {
out.push(t);
}
}
if q != 0.0 || out.is_empty() {
out.push(q);
}
out
}
fn scale(e: &[f64], b: f64) -> Vec<f64> {
let mut out = Vec::with_capacity(2 * e.len());
let (mut q, h) = two_product(e[0], b);
if h != 0.0 {
out.push(h);
}
for &x in &e[1..] {
let (p1, p0) = two_product(x, b);
let (sum, h) = two_sum(q, p0);
if h != 0.0 {
out.push(h);
}
let (q2, h2) = two_sum(p1, sum);
q = q2;
if h2 != 0.0 {
out.push(h2);
}
}
if q != 0.0 || out.is_empty() {
out.push(q);
}
out
}
fn sum(e: &[f64], f: &[f64]) -> Vec<f64> {
let mut out = e.to_vec();
for &x in f {
out = grow(&out, x);
}
out
}
fn estimate_sign(e: &[f64]) -> f64 {
for &x in e.iter().rev() {
if x != 0.0 {
return x;
}
}
0.0
}
/// Wie `orient2d` aus `robust-predicates`: Vorzeichen exakt (negativ, wenn a, b, c gegen den
/// Uhrzeigersinn liegen — Konvention dieses Pakets), Betrag nur die schnelle Näherung.
pub fn orient2d(ax: f64, ay: f64, bx: f64, by: f64, cx: f64, cy: f64) -> f64 {
const EPS: f64 = 1.1102230246251565e-16; // 2^-53
const CCW_ERR_BOUND_A: f64 = (3.0 + 16.0 * EPS) * EPS;
let detleft = (ay - cy) * (bx - cx);
let detright = (ax - cx) * (by - cy);
let det = detleft - detright;
let detsum = (detleft + detright).abs();
if det.abs() >= CCW_ERR_BOUND_A * detsum {
return det;
}
// exakt: (ay-cy)(bx-cx) - (ax-cx)(by-cy); jede Differenz als 2-Term-Expansion
let (acx, acx_t) = two_sum(ax, -cx);
let (bcx, bcx_t) = two_sum(bx, -cx);
let (acy, acy_t) = two_sum(ay, -cy);
let (bcy, bcy_t) = two_sum(by, -cy);
let prod = |a: &[f64; 2], b: &[f64; 2]| -> Vec<f64> { sum(&scale(a, b[0]), &scale(a, b[1])) };
let left = prod(&[acy_t, acy], &[bcx_t, bcx]);
let right = prod(&[acx_t, acx], &[bcy_t, bcy]);
let neg: Vec<f64> = right.iter().map(|v| -v).collect();
estimate_sign(&sum(&left, &neg))
}
// ── Delaunator ─────────────────────────────────────────────────────────────
fn dist(ax: f64, ay: f64, bx: f64, by: f64) -> f64 {
let dx = ax - bx;
let dy = ay - by;
dx * dx + dy * dy
}
fn in_circle(ax: f64, ay: f64, bx: f64, by: f64, cx: f64, cy: f64, px: f64, py: f64) -> bool {
let dx = ax - px;
let dy = ay - py;
let ex = bx - px;
let ey = by - py;
let fx = cx - px;
let fy = cy - py;
let ap = dx * dx + dy * dy;
let bp = ex * ex + ey * ey;
let cp = fx * fx + fy * fy;
dx * (ey * cp - bp * fy) - dy * (ex * cp - bp * fx) + ap * (ex * fy - ey * fx) < 0.0
}
fn circumradius(ax: f64, ay: f64, bx: f64, by: f64, cx: f64, cy: f64) -> f64 {
let dx = bx - ax;
let dy = by - ay;
let ex = cx - ax;
let ey = cy - ay;
let bl = dx * dx + dy * dy;
let cl = ex * ex + ey * ey;
let d = 0.5 / (dx * ey - dy * ex);
let x = (ey * bl - dy * cl) * d;
let y = (dx * cl - ex * bl) * d;
x * x + y * y
}
fn circumcenter(ax: f64, ay: f64, bx: f64, by: f64, cx: f64, cy: f64) -> (f64, f64) {
let dx = bx - ax;
let dy = by - ay;
let ex = cx - ax;
let ey = cy - ay;
let bl = dx * dx + dy * dy;
let cl = ex * ex + ey * ey;
let d = 0.5 / (dx * ey - dy * ex);
(ax + (ey * bl - dy * cl) * d, ay + (dx * cl - ex * bl) * d)
}
fn pseudo_angle(dx: f64, dy: f64) -> f64 {
let p = dx / (dx.abs() + dy.abs());
(if dy > 0.0 { 3.0 - p } else { 1.0 + p }) / 4.0
}
fn quicksort(ids: &mut [u32], dists: &[f64], left: isize, right: isize) {
if right - left <= 20 {
for i in left + 1..=right {
let temp = ids[i as usize];
let temp_dist = dists[temp as usize];
let mut j = i - 1;
while j >= left && dists[ids[j as usize] as usize] > temp_dist {
ids[(j + 1) as usize] = ids[j as usize];
j -= 1;
}
ids[(j + 1) as usize] = temp;
}
} else {
let median = (left + right) >> 1;
let mut i = left + 1;
let mut j = right;
ids.swap(median as usize, i as usize);
if dists[ids[left as usize] as usize] > dists[ids[right as usize] as usize] {
ids.swap(left as usize, right as usize);
}
if dists[ids[i as usize] as usize] > dists[ids[right as usize] as usize] {
ids.swap(i as usize, right as usize);
}
if dists[ids[left as usize] as usize] > dists[ids[i as usize] as usize] {
ids.swap(left as usize, i as usize);
}
let temp = ids[i as usize];
let temp_dist = dists[temp as usize];
loop {
loop {
i += 1;
if !(dists[ids[i as usize] as usize] < temp_dist) {
break;
}
}
loop {
j -= 1;
if !(dists[ids[j as usize] as usize] > temp_dist) {
break;
}
}
if j < i {
break;
}
ids.swap(i as usize, j as usize);
}
ids[(left + 1) as usize] = ids[j as usize];
ids[j as usize] = temp;
if right - i + 1 >= j - left {
quicksort(ids, dists, i, right);
quicksort(ids, dists, left, j - 1);
} else {
quicksort(ids, dists, left, j - 1);
quicksort(ids, dists, i, right);
}
}
}
struct State<'a> {
coords: &'a [f64],
triangles: Vec<u32>,
halfedges: Vec<i32>,
hull_prev: Vec<u32>,
hull_tri: Vec<u32>,
hull_start: usize,
edge_stack: [u32; EDGE_STACK_LEN],
}
impl State<'_> {
fn link(&mut self, a: usize, b: i32) {
self.halfedges[a] = b;
if b != -1 {
self.halfedges[b as usize] = a as i32;
}
}
fn add_triangle(&mut self, i0: u32, i1: u32, i2: u32, a: i32, b: i32, c: i32) -> usize {
let t = self.triangles.len();
self.triangles.extend([i0, i1, i2]);
self.halfedges.extend([-1, -1, -1]);
self.link(t, a);
self.link(t + 1, b);
self.link(t + 2, c);
t
}
fn legalize(&mut self, a_in: usize) -> usize {
let mut a = a_in;
let mut i = 0usize;
let mut ar;
loop {
let b = self.halfedges[a];
let a0 = a - a % 3;
ar = a0 + (a + 2) % 3;
if b == -1 {
if i == 0 {
break;
}
i -= 1;
a = self.edge_stack[i] as usize;
continue;
}
let b = b as usize;
let b0 = b - b % 3;
let al = a0 + (a + 1) % 3;
let bl = b0 + (b + 2) % 3;
let p0 = self.triangles[ar] as usize;
let pr = self.triangles[a] as usize;
let pl = self.triangles[al] as usize;
let p1 = self.triangles[bl] as usize;
let c = self.coords;
let illegal = in_circle(
c[2 * p0], c[2 * p0 + 1], c[2 * pr], c[2 * pr + 1], c[2 * pl], c[2 * pl + 1], c[2 * p1], c[2 * p1 + 1],
);
if illegal {
self.triangles[a] = p1 as u32;
self.triangles[b] = p0 as u32;
let hbl = self.halfedges[bl];
if hbl == -1 {
let mut e = self.hull_start;
loop {
if self.hull_tri[e] as usize == bl {
self.hull_tri[e] = a as u32;
break;
}
e = self.hull_prev[e] as usize;
if e == self.hull_start {
break;
}
}
}
self.link(a, hbl);
let har = self.halfedges[ar];
self.link(b, har);
self.link(ar, bl as i32);
let br = b0 + (b + 1) % 3;
if i < EDGE_STACK_LEN {
self.edge_stack[i] = br as u32;
i += 1;
}
} else {
if i == 0 {
break;
}
i -= 1;
a = self.edge_stack[i] as usize;
}
}
ar
}
}
pub fn triangulate(coords: &[f64]) -> Vec<u32> {
let n = coords.len() >> 1;
if n < 3 || coords.len() != 2 * n || coords.iter().any(|v| !v.is_finite()) {
return Vec::new();
}
let max_triangles = if n * 2 >= 5 { 2 * n - 5 } else { 0 };
let hash_size = (n as f64).sqrt().ceil() as usize;
let mut hull_next = vec![0u32; n];
let mut hull_hash = vec![-1i32; hash_size];
let mut st = State {
coords,
triangles: Vec::with_capacity(max_triangles * 3),
halfedges: Vec::with_capacity(max_triangles * 3),
hull_prev: vec![0u32; n],
hull_tri: vec![0u32; n],
hull_start: 0,
edge_stack: [0; EDGE_STACK_LEN],
};
let mut ids: Vec<u32> = (0..n as u32).collect();
let mut dists = vec![0.0f64; n];
let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for i in 0..n {
let x = coords[2 * i];
let y = coords[2 * i + 1];
if x < min_x {
min_x = x;
}
if y < min_y {
min_y = y;
}
if x > max_x {
max_x = x;
}
if y > max_y {
max_y = y;
}
}
let cx = (min_x + max_x) / 2.0;
let cy = (min_y + max_y) / 2.0;
let (mut i0, mut i1, mut i2) = (0usize, 0usize, 0usize);
let mut min_dist = f64::INFINITY;
for i in 0..n {
let d = dist(cx, cy, coords[2 * i], coords[2 * i + 1]);
if d < min_dist {
i0 = i;
min_dist = d;
}
}
let i0x = coords[2 * i0];
let i0y = coords[2 * i0 + 1];
let mut min_dist = f64::INFINITY;
for i in 0..n {
if i == i0 {
continue;
}
let d = dist(i0x, i0y, coords[2 * i], coords[2 * i + 1]);
if d < min_dist && d > 0.0 {
i1 = i;
min_dist = d;
}
}
let mut i1x = coords[2 * i1];
let mut i1y = coords[2 * i1 + 1];
let mut min_radius = f64::INFINITY;
for i in 0..n {
if i == i0 || i == i1 {
continue;
}
let r = circumradius(i0x, i0y, i1x, i1y, coords[2 * i], coords[2 * i + 1]);
if r < min_radius {
i2 = i;
min_radius = r;
}
}
let mut i2x = coords[2 * i2];
let mut i2y = coords[2 * i2 + 1];
if min_radius == f64::INFINITY {
return Vec::new(); // alle Punkte kollinear: keine Dreiecke
}
if orient2d(i0x, i0y, i1x, i1y, i2x, i2y) < 0.0 {
std::mem::swap(&mut i1, &mut i2);
std::mem::swap(&mut i1x, &mut i2x);
std::mem::swap(&mut i1y, &mut i2y);
}
let (ccx, ccy) = circumcenter(i0x, i0y, i1x, i1y, i2x, i2y);
for i in 0..n {
dists[i] = dist(coords[2 * i], coords[2 * i + 1], ccx, ccy);
}
quicksort(&mut ids, &dists, 0, n as isize - 1);
let hash_key = |x: f64, y: f64| -> usize {
let v = (pseudo_angle(x - ccx, y - ccy) * hash_size as f64).floor();
if v.is_nan() {
0
} else {
(v as i64).rem_euclid(hash_size as i64) as usize
}
};
st.hull_start = i0;
hull_next[i0] = i1 as u32;
st.hull_prev[i2] = i1 as u32;
hull_next[i1] = i2 as u32;
st.hull_prev[i0] = i2 as u32;
hull_next[i2] = i0 as u32;
st.hull_prev[i1] = i0 as u32;
st.hull_tri[i0] = 0;
st.hull_tri[i1] = 1;
st.hull_tri[i2] = 2;
hull_hash[hash_key(i0x, i0y)] = i0 as i32;
hull_hash[hash_key(i1x, i1y)] = i1 as i32;
hull_hash[hash_key(i2x, i2y)] = i2 as i32;
st.add_triangle(i0 as u32, i1 as u32, i2 as u32, -1, -1, -1);
let (mut xp, mut yp) = (0.0f64, 0.0f64);
for k in 0..n {
let i = ids[k] as usize;
let x = coords[2 * i];
let y = coords[2 * i + 1];
if k > 0 && (x - xp).abs() <= EPSILON && (y - yp).abs() <= EPSILON {
continue;
}
xp = x;
yp = y;
if i == i0 || i == i1 || i == i2 {
continue;
}
let mut start = 0usize;
let key = hash_key(x, y);
for j in 0..hash_size {
let s = hull_hash[(key + j) % hash_size];
start = if s < 0 { usize::MAX } else { s as usize };
if s != -1 && start != hull_next[start] as usize {
break;
}
}
if start == usize::MAX {
continue;
}
start = st.hull_prev[start] as usize;
let mut e = start;
let mut found = true;
loop {
let q = hull_next[e] as usize;
if orient2d(x, y, coords[2 * e], coords[2 * e + 1], coords[2 * q], coords[2 * q + 1]) >= 0.0 {
e = q;
if e == start {
found = false;
break;
}
} else {
break;
}
}
if !found {
continue;
}
let mut t = st.add_triangle(e as u32, i as u32, hull_next[e], -1, -1, st.hull_tri[e] as i32);
st.hull_tri[i] = st.legalize(t + 2) as u32;
st.hull_tri[e] = t as u32;
let mut nn = hull_next[e] as usize;
loop {
let q = hull_next[nn] as usize;
if orient2d(x, y, coords[2 * nn], coords[2 * nn + 1], coords[2 * q], coords[2 * q + 1]) < 0.0 {
t = st.add_triangle(nn as u32, i as u32, q as u32, st.hull_tri[i] as i32, -1, st.hull_tri[nn] as i32);
st.hull_tri[i] = st.legalize(t + 2) as u32;
hull_next[nn] = nn as u32;
nn = q;
} else {
break;
}
}
if e == start {
loop {
let q = st.hull_prev[e] as usize;
if orient2d(x, y, coords[2 * q], coords[2 * q + 1], coords[2 * e], coords[2 * e + 1]) < 0.0 {
t = st.add_triangle(q as u32, i as u32, e as u32, -1, st.hull_tri[e] as i32, st.hull_tri[q] as i32);
st.legalize(t + 2);
st.hull_tri[q] = t as u32;
hull_next[e] = e as u32;
e = q;
} else {
break;
}
}
}
st.hull_start = e;
st.hull_prev[i] = e as u32;
hull_next[e] = i as u32;
st.hull_prev[nn] = i as u32;
hull_next[i] = nn as u32;
hull_hash[hash_key(x, y)] = i as i32;
hull_hash[hash_key(coords[2 * e], coords[2 * e + 1])] = e as i32;
}
st.triangles
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quadrat_ergibt_zwei_dreiecke() {
let t = triangulate(&[0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]);
assert_eq!(t.len(), 6);
}
#[test]
fn kollinear_und_zu_wenig_sind_leer() {
assert!(triangulate(&[0.0, 0.0, 1.0, 1.0, 2.0, 2.0]).is_empty());
assert!(triangulate(&[0.0, 0.0, 1.0, 1.0]).is_empty());
assert!(triangulate(&[0.0, f64::NAN, 1.0, 1.0, 2.0, 5.0]).is_empty());
}
#[test]
fn orient_ist_exakt() {
// fast kollinear: nur mit exakter Arithmetik korrekt
let a = (0.5, 0.5);
let b = (12.0, 12.0);
let c = (24.0, 24.0);
assert_eq!(orient2d(a.0, a.1, b.0, b.1, c.0, c.1), 0.0);
assert!(orient2d(0.0, 0.0, 1.0, 0.0, 0.0, 1.0) < 0.0);
assert!(orient2d(0.0, 0.0, 0.0, 1.0, 1.0, 0.0) > 0.0);
}
}
+328
View File
@@ -0,0 +1,328 @@
//! Projekt-Dokument und Ops ([K4], Stufe S1): Rust hält das Projekt als JSON-Baum und wendet die
//! Op-Folgen an, die TS aus `core/ops.ts` erzeugt (`setField`/`add`/`replace`/`remove`/`reorder`).
//! Die Ops werden atomar angewendet und geprüft (doppelte ids); bei Verstoss bleibt das Dokument
//! unverändert. Später lesen die Ableitungen (Plan, Schnitt, 3D, Kennzahlen, Export) direkt dieses
//! Dokument statt flacher TS-Sammler.
//!
//! JSON kennt weder `undefined` noch NaN: fehlende Felder fehlen, nicht endliche Zahlen prüft TS
//! vor dem Senden (`validateOps`).
use crate::model::Project;
use serde::Deserialize;
use serde_json::{Map, Value};
use std::collections::HashSet;
/// Eine Änderung am Projekt (Spiegel von `CoreOp` in `core/ops.ts`).
#[derive(Clone, Debug, PartialEq)]
pub enum Op {
Add { collection: String, items: Vec<Value>, at: Option<usize> },
Replace { collection: String, entity: Value },
Remove { collection: String, ids: Vec<String> },
Reorder { collection: String, ids: Vec<String> },
SetField { key: String, value: Option<Value> },
}
fn id_of(v: &Value) -> Option<&str> {
v.get("id").and_then(Value::as_str)
}
impl Op {
pub fn from_json(v: &Value) -> Result<Op, String> {
let kind = v.get("kind").and_then(Value::as_str).ok_or("Op ohne kind")?;
let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_owned).ok_or(format!("Op {kind}: {k} fehlt"));
let ids = |k: &str| -> Result<Vec<String>, String> {
v.get(k)
.and_then(Value::as_array)
.ok_or(format!("Op {kind}: {k} fehlt"))?
.iter()
.map(|x| x.as_str().map(str::to_owned).ok_or(format!("Op {kind}: {k} enthält Nicht-Text")))
.collect()
};
Ok(match kind {
"add" => {
let items = v.get("items").and_then(Value::as_array).ok_or("Op add: items fehlt")?.clone();
if items.iter().any(|e| id_of(e).is_none()) {
return Err("Op add: Element ohne id".into());
}
let at = match v.get("at") {
None | Some(Value::Null) => None,
Some(a) => Some(a.as_f64().filter(|x| x.is_finite()).map(|x| x.max(0.0) as usize).ok_or("Op add: at ungültig")?),
};
Op::Add { collection: s("collection")?, items, at }
}
"replace" => {
let entity = v.get("entity").cloned().ok_or("Op replace: entity fehlt")?;
if id_of(&entity).is_none() {
return Err("Op replace: Element ohne id".into());
}
Op::Replace { collection: s("collection")?, entity }
}
"remove" => Op::Remove { collection: s("collection")?, ids: ids("ids")? },
"reorder" => Op::Reorder { collection: s("collection")?, ids: ids("ids")? },
"setField" => Op::SetField { key: s("key")?, value: v.get("value").filter(|x| !x.is_null()).cloned() },
other => return Err(format!("Unbekannte Op: {other}")),
})
}
fn key(&self) -> &str {
match self {
Op::Add { collection, .. } | Op::Replace { collection, .. } | Op::Remove { collection, .. } | Op::Reorder { collection, .. } => collection,
Op::SetField { key, .. } => key,
}
}
}
/// Liste mit lauter `id`-tragenden Elementen (leer zählt mit).
fn is_id_list(v: &Value) -> bool {
v.as_array().is_some_and(|a| a.iter().all(|e| id_of(e).is_some()))
}
fn unique_ids(list: &[Value]) -> bool {
let mut seen = HashSet::new();
list.iter().all(|e| seen.insert(id_of(e).unwrap_or("")))
}
fn has_dup(v: Option<&Value>) -> bool {
match v {
Some(v) if is_id_list(v) => !unique_ids(v.as_array().unwrap()),
_ => false,
}
}
#[derive(Clone, Debug, Default)]
pub struct Document {
root: Map<String, Value>,
/// Typisierte Sicht (Cache). Eine Op markiert nur ihr Feld als geändert; `project()` liest dann
/// genau diese Felder neu ein.
typed: Option<Project>,
dirty: HashSet<String>,
}
impl Document {
pub fn from_json(text: &str) -> Result<Document, String> {
match serde_json::from_str::<Value>(text) {
Ok(Value::Object(root)) => Ok(Document { root, typed: None, dirty: HashSet::new() }),
Ok(_) => Err("Projekt ist kein JSON-Objekt".into()),
Err(e) => Err(e.to_string()),
}
}
/// Datei-Text des Projekts (`serializeProject`): Formatversion vorn, Einrückung 2.
pub fn serialize(&self) -> String {
crate::project_format::serialize_project(&self.root)
}
pub fn to_json(&self) -> String {
serde_json::to_string(&self.root).unwrap_or_default()
}
/// Typisierte Sicht des Projekts (gecacht; nach Ops werden nur die berührten Felder neu gelesen).
/// Fehler = Feld, das dem Modell widerspricht (Meldung von serde).
pub fn project(&mut self) -> Result<&Project, String> {
if self.typed.is_none() {
// Die Map wird nur ausgeliehen: `Value::Object` braucht Besitz, daher temporär herausnehmen.
let value = Value::Object(std::mem::take(&mut self.root));
let parsed = Project::deserialize(&value).map_err(|e| e.to_string());
if let Value::Object(m) = value {
self.root = m;
}
self.typed = Some(parsed?);
self.dirty.clear();
} else if !self.dirty.is_empty() {
let dirty: Vec<String> = self.dirty.drain().collect();
let mut failed = None;
if let Some(t) = self.typed.as_mut() {
for key in &dirty {
if let Err(e) = t.set_field(key, self.root.get(key)) {
failed = Some(e);
break;
}
}
}
if let Some(e) = failed {
self.typed = None;
return Err(e);
}
}
Ok(self.typed.as_ref().expect("gerade gesetzt"))
}
pub fn field(&self, key: &str) -> Option<&Value> {
self.root.get(key)
}
fn list_mut(&mut self, collection: &str) -> &mut Vec<Value> {
let slot = self.root.entry(collection.to_owned()).or_insert_with(|| Value::Array(vec![]));
if !slot.is_array() {
*slot = Value::Array(vec![]);
}
slot.as_array_mut().unwrap()
}
fn apply_one(&mut self, op: &Op) {
match op {
Op::SetField { key, value } => match value {
Some(v) => {
self.root.insert(key.clone(), v.clone());
}
None => {
self.root.shift_remove(key);
}
},
Op::Add { collection, items, at } => {
let list = self.list_mut(collection);
let at = at.map_or(list.len(), |a| a.min(list.len()));
list.splice(at..at, items.iter().cloned());
}
Op::Replace { collection, entity } => {
let list = self.list_mut(collection);
let id = id_of(entity);
match list.iter().position(|e| id_of(e) == id) {
Some(i) => list[i] = entity.clone(),
None => list.push(entity.clone()),
}
}
Op::Remove { collection, ids } => {
let drop: HashSet<&str> = ids.iter().map(String::as_str).collect();
self.list_mut(collection).retain(|e| !id_of(e).is_some_and(|i| drop.contains(i)));
}
Op::Reorder { collection, ids } => {
let list = std::mem::take(self.list_mut(collection));
let mut ordered = Vec::with_capacity(list.len());
let mut rest = Vec::new();
let listed: HashSet<&str> = ids.iter().map(String::as_str).collect();
for id in ids {
if let Some(e) = list.iter().find(|e| id_of(e) == Some(id.as_str())) {
ordered.push(e.clone());
}
}
for e in &list {
if !id_of(e).is_some_and(|i| listed.contains(i)) {
rest.push(e.clone());
}
}
ordered.extend(rest);
*self.list_mut(collection) = ordered;
}
}
}
/// Wendet `ops` atomar an. Verstösse (neue doppelte ids) → `Err(Meldungen)`, Dokument unverändert.
pub fn apply(&mut self, ops: &[Op]) -> Result<(), Vec<String>> {
for op in ops {
self.dirty.insert(op.key().to_owned());
}
// Zustand der berührten Felder sichern (Rücknahme) und Alt-Doppelungen merken.
let mut saved: Vec<(String, Option<Value>)> = Vec::new();
let mut had_dup: HashSet<String> = HashSet::new();
for op in ops {
let k = op.key().to_owned();
if !saved.iter().any(|(s, _)| *s == k) {
if has_dup(self.root.get(&k)) {
had_dup.insert(k.clone());
}
saved.push((k.clone(), self.root.get(&k).cloned()));
}
}
for op in ops {
self.apply_one(op);
}
let mut problems = Vec::new();
let mut checked: HashSet<&str> = HashSet::new();
for op in ops {
let (key, is_add, is_set) = match op {
Op::Add { collection, .. } => (collection.as_str(), true, false),
Op::SetField { key, .. } => (key.as_str(), false, true),
_ => continue,
};
if (is_add || is_set) && checked.insert(key) && !had_dup.contains(key) {
if let Some(v) = self.root.get(key) {
let relevant = is_add || v.as_array().is_some_and(|a| !a.is_empty()) && is_id_list(v);
if relevant && is_id_list(v) && !unique_ids(v.as_array().unwrap()) {
problems.push(format!("Doppelte ids in „{key}\"."));
}
}
}
}
if problems.is_empty() {
return Ok(());
}
for (k, old) in saved {
match old {
Some(v) => {
self.root.insert(k, v);
}
None => {
self.root.shift_remove(&k);
}
}
}
Err(problems)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn doc() -> Document {
Document::from_json(r#"{"id":"p","walls":[{"id":"a","x":1},{"id":"b","x":2}],"name":"N"}"#).unwrap()
}
fn ops(v: Value) -> Vec<Op> {
v.as_array().unwrap().iter().map(|o| Op::from_json(o).unwrap()).collect()
}
#[test]
fn ops_wirken_wie_in_ts() {
let mut d = doc();
d.apply(&ops(json!([
{"kind":"replace","collection":"walls","entity":{"id":"b","x":9}},
{"kind":"add","collection":"walls","items":[{"id":"c"}],"at":0},
{"kind":"remove","collection":"walls","ids":["a"]},
{"kind":"setField","key":"name","value":"M"},
{"kind":"setField","key":"id"},
])))
.unwrap();
assert_eq!(d.to_json(), r#"{"name":"M","walls":[{"id":"c"},{"id":"b","x":9}]}"#.replace(r#"{"name":"M","walls""#, r#"{"walls""#).replace("}]}", r#"}],"name":"M"}"#));
d.apply(&ops(json!([{"kind":"reorder","collection":"walls","ids":["b"]}]))).unwrap();
assert_eq!(d.field("walls").unwrap()[0]["id"], "b");
}
#[test]
fn doppelte_ids_werden_zurueckgenommen() {
let mut d = doc();
let before = d.to_json();
let e = d.apply(&ops(json!([{"kind":"add","collection":"walls","items":[{"id":"a"}]}]))).unwrap_err();
assert_eq!(e, vec!["Doppelte ids in „walls\".".to_string()]);
assert_eq!(d.to_json(), before);
}
#[test]
fn alt_doppelungen_bleiben_aenderbar() {
let mut d = Document::from_json(r#"{"walls":[{"id":"a"},{"id":"a"}]}"#).unwrap();
d.apply(&ops(json!([{"kind":"add","collection":"walls","items":[{"id":"z"}]}]))).unwrap();
}
#[test]
fn typisierte_sicht_folgt_den_ops() {
let text = include_str!("../tests/fixtures/sample_project.json");
let mut d = Document::from_json(text).unwrap();
let n = d.project().unwrap().walls.len();
assert!(n > 0);
let id = d.project().unwrap().walls[0].id.clone();
d.apply(&ops(json!([{"kind":"remove","collection":"walls","ids":[id]}]))).unwrap();
assert_eq!(d.project().unwrap().walls.len(), n - 1);
// Feld entfernen und wieder setzen
d.apply(&ops(json!([{"kind":"setField","key":"name"}]))).unwrap();
assert_eq!(d.project().unwrap().name, "");
d.apply(&ops(json!([{"kind":"setField","key":"name","value":"X"}]))).unwrap();
assert_eq!(d.project().unwrap().name, "X");
}
#[test]
fn kaputte_ops_sind_fehler() {
assert!(Op::from_json(&json!({"kind":"add","collection":"w","items":[{"x":1}]})).is_err());
assert!(Op::from_json(&json!({"kind":"nope"})).is_err());
}
}
+258
View File
@@ -0,0 +1,258 @@
//! Bauteilliste ([K4] S2, vorher `src/export/exportSchedule.ts`): eine Zeile je Bauteil-Vorkommen
//! (Wand, Decke, Tür/Fenster, Treppe, Extrusion, Dach, Stütze) mit Kennwerten aus dem Modell, dazu
//! CSV-Ausgabe (RFC 4180, Feldtrenner `;`, Zeilenende CRLF) mit Aggregat je Bauteil-Typ.
use crate::js_fmt::to_fixed;
use crate::jsmath::hypot2;
use crate::jsnum::round;
use crate::model::*;
use serde::Serialize;
/// Eine ausgewertete Zeile (JSON-Form wie `ScheduleRow` in TS).
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduleRow {
pub kind: &'static str,
pub id: String,
pub type_name: String,
pub floor: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub floor_id: Option<String>,
pub length: Option<f64>,
pub height_m: Option<f64>,
pub thickness: Option<f64>,
pub area: Option<f64>,
}
fn polygon_area(pts: &[Vec2]) -> f64 {
let flat: Vec<[f64; 2]> = pts.iter().map(|v| [v.x, v.y]).collect();
crate::room_area::evaluate(&flat, 0.0).gross
}
fn floor_name(p: &Project, floor_id: &str) -> String {
p.floor(floor_id).map_or(floor_id.to_string(), |f| f.name.clone())
}
/// Wertet ALLE Bauteil-Vorkommen aus: Wände, Decken, Öffnungen, Treppen, Extrusionen, Dächer, Stützen.
pub fn schedule_rows(p: &Project) -> Vec<ScheduleRow> {
let mut rows = Vec::new();
for w in &p.walls {
let (type_name, thickness) = match p.wall_type(w) {
Some(t) => (t.name.clone(), Project::type_thickness(&t.layers)),
None => (w.wall_type_id.clone(), 0.0),
};
let length = hypot2(w.end.x - w.start.x, w.end.y - w.start.y);
rows.push(ScheduleRow {
kind: "Wand",
id: w.id.clone(),
type_name,
floor: floor_name(p, &w.floor_id),
floor_id: Some(w.floor_id.clone()),
length: Some(length),
height_m: Some(w.height),
thickness: Some(thickness),
area: Some(length * w.height),
});
}
for c in p.ceilings.as_deref().unwrap_or(&[]) {
let type_name = match crate::model3d::ceiling_type_ref(p, c) {
Some((_, name, _)) => name.to_string(),
None => c.ceiling_type_id.clone().unwrap_or_else(|| c.wall_type_id.clone()),
};
rows.push(ScheduleRow {
kind: "Decke",
id: c.id.clone(),
type_name,
floor: floor_name(p, &c.floor_id),
floor_id: Some(c.floor_id.clone()),
length: None,
height_m: None,
thickness: Some(p.ceiling_thickness(c)),
area: Some(polygon_area(&c.outline)),
});
}
for o in p.openings.as_deref().unwrap_or(&[]) {
let kind = if o.kind == ElementKind::Window { "Fenster" } else { "Tür" };
let host = p.walls.iter().find(|w| w.id == o.host_wall_id);
rows.push(ScheduleRow {
kind,
id: o.id.clone(),
type_name: kind.to_string(),
floor: host.map_or(o.host_wall_id.clone(), |w| floor_name(p, &w.floor_id)),
floor_id: host.map(|w| w.floor_id.clone()),
length: Some(o.width),
height_m: Some(o.height),
thickness: None,
area: Some(o.width * o.height),
});
}
for s in p.stairs.as_deref().unwrap_or(&[]) {
rows.push(ScheduleRow {
kind: "Treppe",
id: s.id.clone(),
type_name: "Treppe".into(),
floor: floor_name(p, &s.floor_id),
floor_id: Some(s.floor_id.clone()),
length: Some(s.run_length + s.run2_length.unwrap_or(0.0)),
height_m: s.total_rise,
thickness: None,
area: None,
});
}
for e in p.extruded_solids.as_deref().unwrap_or(&[]) {
rows.push(ScheduleRow {
kind: "Extrusion",
id: e.id.clone(),
type_name: "Extrusion".into(),
floor: floor_name(p, &e.level_id),
floor_id: Some(e.level_id.clone()),
length: None,
height_m: Some(e.height),
thickness: None,
area: Some(polygon_area(&e.points)),
});
}
for r in p.roofs.as_deref().unwrap_or(&[]) {
let mut type_name = r.roof_type_id.clone().unwrap_or_else(|| shape_name(r.shape).to_string());
if let Some(rt) = r.roof_type_id.as_deref().and_then(|id| p.roof_types.as_deref()?.iter().find(|t| t.id == id)) {
type_name = rt.name.clone();
}
rows.push(ScheduleRow {
kind: "Dach",
id: r.id.clone(),
type_name,
floor: floor_name(p, &r.floor_id),
floor_id: Some(r.floor_id.clone()),
length: None,
height_m: None,
thickness: Some(r.thickness),
area: Some(polygon_area(&r.outline)),
});
}
for c in p.columns.as_deref().unwrap_or(&[]) {
let (type_name, length, thickness) = match &c.profile {
ColumnProfile::Round { radius } => ("Rund", None, radius * 2.0),
ColumnProfile::Rect { width, depth } => ("Rechteck", Some(*width), *depth),
};
rows.push(ScheduleRow {
kind: "Stütze",
id: c.id.clone(),
type_name: type_name.into(),
floor: floor_name(p, &c.floor_id),
floor_id: Some(c.floor_id.clone()),
length,
height_m: Some(c.height),
thickness: Some(thickness),
area: None,
});
}
rows
}
fn shape_name(s: RoofShape) -> &'static str {
match s {
RoofShape::Flach => "flach",
RoofShape::Pult => "pult",
RoofShape::Sattel => "sattel",
RoofShape::Walm => "walm",
RoofShape::Mansarde => "mansarde",
RoofShape::Zelt => "zelt",
RoofShape::Unknown => "",
}
}
/// Ein Feld CSV-sicher quoten: „…" bei , " \n \r ; — `"` wird verdoppelt.
fn csv_field(v: &str) -> String {
if v.contains(['"', ',', '\n', '\r', ';']) {
format!("\"{}\"", v.replace('"', "\"\""))
} else {
v.to_string()
}
}
/// Zahl auf 2 Nachkommastellen, Punkt; leer bei `None`/nicht endlich.
fn fmt_num(v: Option<f64>) -> String {
match v {
Some(x) if x.is_finite() => to_fixed(round(x * 100.0) / 100.0, 2),
_ => String::new(),
}
}
struct Aggregate {
kind: &'static str,
type_name: String,
count: usize,
total_length: f64,
total_area: f64,
}
/// Bauteilliste als CSV (`exportScheduleCsv`): Kopfzeile, eine Zeile je Bauteil, optional Aggregat.
pub fn export_schedule_csv(p: &Project, delimiter: &str, include_summary: bool) -> String {
let rows = schedule_rows(p);
let d = delimiter;
let mut lines: Vec<String> = Vec::new();
let header = ["Typ", "ID", "Bauteil", "Geschoss", "Länge [m]", "Höhe [m]", "Dicke [m]", "Fläche [m²]"];
lines.push(header.iter().map(|h| csv_field(h)).collect::<Vec<_>>().join(d));
for r in &rows {
lines.push(
[csv_field(r.kind), csv_field(&r.id), csv_field(&r.type_name), csv_field(&r.floor), fmt_num(r.length), fmt_num(r.height_m), fmt_num(r.thickness), fmt_num(r.area)].join(d),
);
}
if include_summary && !rows.is_empty() {
lines.push(String::new());
lines.push([csv_field("Zusammenfassung (je Bauteil-Typ)"), "".into(), "".into(), "".into(), "".into(), "".into(), "".into(), "".into()].join(d));
let mut aggs: Vec<Aggregate> = Vec::new();
for r in &rows {
let i = match aggs.iter().position(|a| a.kind == r.kind && a.type_name == r.type_name) {
Some(i) => i,
None => {
aggs.push(Aggregate { kind: r.kind, type_name: r.type_name.clone(), count: 0, total_length: 0.0, total_area: 0.0 });
aggs.len() - 1
}
};
aggs[i].count += 1;
aggs[i].total_length += r.length.unwrap_or(0.0);
aggs[i].total_area += r.area.unwrap_or(0.0);
}
for a in &aggs {
lines.push(
[
csv_field(a.kind),
String::new(),
csv_field(&a.type_name),
csv_field(&format!("{} Stk", a.count)),
if a.total_length > 0.0 { fmt_num(Some(a.total_length)) } else { String::new() },
String::new(),
String::new(),
if a.total_area > 0.0 { fmt_num(Some(a.total_area)) } else { String::new() },
]
.join(d),
);
}
}
lines.join("\r\n")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn beispielprojekt_hat_zeilen_und_csv() {
let p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap();
let rows = schedule_rows(&p);
assert!(rows.iter().any(|r| r.kind == "Wand"));
let csv = export_schedule_csv(&p, ";", true);
assert!(csv.starts_with("Typ;ID;Bauteil;Geschoss;Länge [m];Höhe [m];Dicke [m];Fläche [m²]\r\n"));
assert!(csv.contains("Zusammenfassung (je Bauteil-Typ)"));
assert_eq!(export_schedule_csv(&Project::default(), ";", true), "Typ;ID;Bauteil;Geschoss;Länge [m];Höhe [m];Dicke [m];Fläche [m²]");
}
#[test]
fn csv_quoting() {
assert_eq!(csv_field("a;b"), "\"a;b\"");
assert_eq!(csv_field("a\"b"), "\"a\"\"b\"");
assert_eq!(fmt_num(Some(1.005)), "1.00");
assert_eq!(fmt_num(None), "");
}
}
+64
View File
@@ -0,0 +1,64 @@
//! Schreibhilfe für flache `f64`-Puffer (Gegenstück zu `FlatWriter` in `src/geometry/coreFlat.ts`
//! und zu `flat_read::Reader`): Rust-Sammler bauen damit dieselben Puffer, die die bestehenden
//! Kern-Funktionen (`ceilings3d`, `wall_bands` …) lesen.
use crate::model::Vec2;
#[derive(Default)]
pub struct FlatWriter {
buf: Vec<f64>,
}
impl FlatWriter {
pub fn new() -> Self {
Self::default()
}
pub fn num(&mut self, v: f64) -> &mut Self {
self.buf.push(v);
self
}
pub fn nums(&mut self, v: &[f64]) -> &mut Self {
self.buf.extend_from_slice(v);
self
}
/// Platz für eine erst später bekannte Zahl; mit [`set`](Self::set) nachtragen.
pub fn slot(&mut self) -> usize {
self.buf.push(0.0);
self.buf.len() - 1
}
pub fn set(&mut self, slot: usize, v: f64) -> &mut Self {
self.buf[slot] = v;
self
}
/// Nur die Punkte `x0, y0, x1, y1, …`.
pub fn pts(&mut self, pts: &[Vec2]) -> &mut Self {
for p in pts {
self.buf.push(p.x);
self.buf.push(p.y);
}
self
}
/// Anzahl, dann die Punkte.
pub fn ring(&mut self, pts: &[Vec2]) -> &mut Self {
self.buf.push(pts.len() as f64);
self.pts(pts)
}
pub fn done(self) -> Vec<f64> {
self.buf
}
pub fn len(&self) -> usize {
self.buf.len()
}
pub fn is_empty(&self) -> bool {
self.buf.is_empty()
}
}
+70
View File
@@ -0,0 +1,70 @@
//! Zahlenformatierung wie JavaScript: `Number.prototype.toFixed` rundet exakte Halbwerte AUF
//! (`pick the larger n`), Rusts `{:.N}` zum geraden Nachbarn — bei dyadischen Werten wie 0.0078125
//! (6 Nachkommastellen) verschieden. Exporte (IFC, CSV) müssen byteweise wie die TS-Fassung sein.
/// `x.toFixed(d)` (|x| < 1e21).
pub fn to_fixed(x: f64, d: usize) -> String {
if x.is_nan() {
return "NaN".into();
}
if x.is_infinite() {
return if x > 0.0 { "Infinity".into() } else { "-Infinity".into() };
}
let neg = x < 0.0;
let ax = x.abs();
if ax >= 1e21 {
return format!("{}{}", if neg { "-" } else { "" }, ax);
}
// 25 Stellen mehr als nötig: ein exakter Halbwert zeigt sich als '5' gefolgt von Nullen.
let wide = format!("{:.*}", d + 25, ax);
let (int_part, frac) = wide.split_once('.').expect("Nachkommastellen");
let mut digits: Vec<u8> = int_part.bytes().chain(frac.bytes().take(d)).collect();
let round_up = frac.as_bytes().get(d).is_some_and(|&c| c >= b'5');
if round_up {
let mut i = digits.len();
loop {
if i == 0 {
digits.insert(0, b'1');
break;
}
i -= 1;
if digits[i] == b'9' {
digits[i] = b'0';
} else {
digits[i] += 1;
break;
}
}
}
let int_len = digits.len() - d;
let mut s = String::new();
if neg {
s.push('-');
}
s.push_str(std::str::from_utf8(&digits[..int_len]).expect("ASCII"));
if d > 0 {
s.push('.');
s.push_str(std::str::from_utf8(&digits[int_len..]).expect("ASCII"));
}
s
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rundet_halbwerte_auf_wie_js() {
assert_eq!(to_fixed(0.0078125, 6), "0.007813"); // JS: "0.007813"; Rust {:.6}: 0.007812
assert_eq!(to_fixed(12.5, 0), "13");
assert_eq!(to_fixed(-2.5, 0), "-3");
assert_eq!(to_fixed(0.5, 0), "1");
assert_eq!(to_fixed(1.0, 6), "1.000000");
assert_eq!(to_fixed(0.0, 6), "0.000000");
assert_eq!(to_fixed(-1e-7, 6), "-0.000000");
assert_eq!(to_fixed(9.9999996, 6), "10.000000");
assert_eq!(to_fixed(123.456, 2), "123.46");
assert_eq!(to_fixed(2.675, 2), "2.67"); // 2.675 ist binär 2.67499999… — JS: "2.67"
assert_eq!(to_fixed(1e-9, 6), "0.000000");
}
}
+12 -2
View File
@@ -3,7 +3,7 @@
//! - `Math.min/max` liefern bei NaN NaN (Rust `f64::min/max` ignorieren NaN).
//! - `Math.round` rundet halbe Werte Richtung +∞ (Rust `round` weg von 0).
//! - `x | 0` ist ToInt32 (Rest modulo 2³², Rust `as i32` sättigt).
//! - Trigonometrie: im Web-Build (wasm32 + Feature "web") ruft der Kern `Math.cos/sin/atan2/acos`
//! - `Math.pow` (`x ** 3`) und Trigonometrie: im Web-Build (wasm32 + Feature "web") ruft der Kern `Math.cos/sin/atan2/acos`
//! der laufenden JS-Engine. Nur so sind die Werte bitgleich zur bisherigen TS-Fassung — V8
//! (glibc-abgeleitete sin/cos), JavaScriptCore (System-libm von macOS) und Rusts libm (musl)
//! unterscheiden sich in einzelnen Fällen in der letzten Stelle. Nativ (`cargo test`, Tauri)
@@ -23,6 +23,12 @@ mod trig {
fn js_atan2(y: f64, x: f64) -> f64;
#[wasm_bindgen(js_namespace = Math, js_name = acos)]
fn js_acos(x: f64) -> f64;
#[wasm_bindgen(js_namespace = Math, js_name = pow)]
fn js_pow(x: f64, y: f64) -> f64;
}
#[inline]
pub fn pow(x: f64, y: f64) -> f64 {
js_pow(x, y)
}
#[inline]
@@ -61,9 +67,13 @@ mod trig {
pub fn acos(x: f64) -> f64 {
x.acos()
}
#[inline]
pub fn pow(x: f64, y: f64) -> f64 {
x.powf(y)
}
}
pub use trig::{acos, atan2, cos, sin};
pub use trig::{acos, atan2, cos, pow, sin};
/// `Math.min(a, b)` (NaN gewinnt; −0 < +0).
#[inline]
+120
View File
@@ -133,3 +133,123 @@ mod tests {
assert_eq!(area_sums(0, &[], &[], f64::NAN, &[]), AreaSums { by_level: vec![], gv: 0.0, parcel: None });
}
}
// ── Kennzahlen aus dem Projekt-Dokument ([K4] S2) ───────────────────────────
use crate::model::{DrawingLevelKind, Project, SiaCategory};
use serde::Serialize;
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LevelKennzahlen {
pub level_id: String,
pub name: String,
/// Geschossfläche (SIA 416 GF) aus den Räumen.
pub gf: f64,
/// Anrechenbare Fläche ≈ Nettogeschossfläche NGF.
pub agf: f64,
pub rooms: usize,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Kennzahlen {
pub levels: Vec<LevelKennzahlen>,
pub gf: f64,
pub agf: f64,
pub gv: f64,
pub footprint: f64,
pub az: Option<f64>,
pub uez: Option<f64>,
}
fn category_index(c: SiaCategory) -> usize {
match c {
SiaCategory::HNF => 0,
SiaCategory::NNF => 1,
SiaCategory::VF => 2,
SiaCategory::FF => 3,
SiaCategory::KGF => 4,
SiaCategory::AGF => 5,
SiaCategory::Unknown => CATEGORIES, // zählt nicht
}
}
/// Flächen je Geschoss (SIA 416), Gebäudevolumen, Ausnützungs- und Überbauungsziffer.
pub fn compute(p: &Project) -> Kennzahlen {
let mut floors: Vec<&crate::model::DrawingLevel> = p.drawing_levels.iter().filter(|l| l.kind == DrawingLevelKind::Floor).collect();
floors.sort_by(|a, b| a.base_elevation.unwrap_or(0.0).partial_cmp(&b.base_elevation.unwrap_or(0.0)).unwrap_or(std::cmp::Ordering::Equal));
let mut level_index: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
for (i, l) in floors.iter().enumerate() {
level_index.entry(l.id.as_str()).or_insert(i);
}
let all_rooms = p.rooms.as_deref().unwrap_or(&[]);
let rooms: Vec<&crate::model::Room> = all_rooms.iter().filter(|r| level_index.contains_key(r.floor_id.as_str())).collect();
let rooms_in: Vec<RoomIn> = rooms
.iter()
.map(|r| RoomIn {
level: level_index[r.floor_id.as_str()],
category: category_index(r.sia_category),
boundary: r.boundary.iter().map(|v| [v.x, v.y]).collect(),
})
.collect();
let solids: Vec<SolidIn> = p
.extruded_solids
.as_deref()
.unwrap_or(&[])
.iter()
.map(|s| SolidIn {
subtract: s.operation.as_deref() == Some("subtract"),
points: if s.circle.is_some() { vec![] } else { s.points.iter().map(|v| [v.x, v.y]).collect() },
circle_r: s.circle.as_ref().map_or(f64::NAN, |c| c.r),
height: s.height,
taper: s.taper.unwrap_or(0.0),
})
.collect();
let parcel_ring: Vec<[f64; 2]> = p.site_rules.as_ref().map(|r| r.parcel.iter().map(|v| [v.x, v.y]).collect()).unwrap_or_default();
let sums = area_sums(floors.len(), &rooms_in, &solids, p.parcel_area.unwrap_or(f64::NAN), &parcel_ring);
let levels: Vec<LevelKennzahlen> = floors
.iter()
.enumerate()
.map(|(i, l)| {
let entries: Vec<(usize, f64)> = (0..CATEGORIES).map(|k| (k, sums.by_level[i][k])).collect();
let b = crate::room_area::balance(&entries);
LevelKennzahlen {
level_id: l.id.clone(),
name: l.name.clone(),
gf: b.agg_area[2],
agf: b.agg_area[1],
rooms: rooms.iter().filter(|r| r.floor_id == l.id).count(),
}
})
.collect();
let gf: f64 = levels.iter().map(|l| l.gf).sum();
let agf: f64 = levels.iter().map(|l| l.agf).sum();
let footprint = levels.iter().find(|l| l.gf > 0.0).map_or(0.0, |l| l.gf);
Kennzahlen {
levels,
gf,
agf,
gv: sums.gv,
footprint,
az: sums.parcel.filter(|x| *x != 0.0).map(|x| agf / x),
uez: sums.parcel.filter(|x| *x != 0.0).map(|x| footprint / x),
}
}
#[cfg(test)]
mod doc_tests {
use super::*;
#[test]
fn kennzahlen_des_beispielprojekts() {
let p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap();
let k = compute(&p);
assert!(!k.levels.is_empty());
let sum: f64 = k.levels.iter().map(|l| l.gf).sum();
assert!((k.gf - sum).abs() < 1e-9);
assert!(k.az.is_none() && k.uez.is_none());
let with_parcel = Project { parcel_area: Some(1000.0), ..p };
let k2 = compute(&with_parcel);
assert!((k2.az.unwrap() - k2.agf / 1000.0).abs() < 1e-12);
}
}
+21
View File
@@ -4,7 +4,9 @@
//!
//! Datenübergabe: flache `f64`-Puffer (s. [`flat`]), kein JSON — schnell und ohne Serde-Kosten.
pub mod export_schedule;
pub mod flat;
pub mod flat_write;
pub mod polygon_bool;
pub mod roof;
pub mod roof_skeleton;
@@ -20,6 +22,7 @@ pub mod wall_bands;
pub mod room_area;
pub mod room_boundary;
pub mod polygon_holes;
pub mod js_fmt;
pub mod jsmath;
pub mod stairs3d;
pub mod mesh3d;
@@ -31,8 +34,26 @@ pub mod wall_mesh_cut;
pub mod jsnum;
pub mod hatch;
pub mod hatch_flat;
pub mod plan;
pub mod plan_buf;
pub mod project_format;
pub mod queries;
pub mod gpu_compile;
pub mod plan_stairs;
pub mod plan_walls;
pub mod opening_geom;
pub mod plan_openings;
pub mod delaunay;
pub mod document;
pub mod mesh_section;
pub mod model;
pub mod model3d;
pub mod style;
pub mod plan_elevation;
pub mod plan_misc;
pub mod plan_section;
pub mod voids;
pub mod curves;
#[cfg(feature = "web")]
mod web;
+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]);
}
}
+299
View File
@@ -0,0 +1,299 @@
//! Ebenenschnitt beliebiger Dreiecksnetze ([K3c], vorher `plan/meshSection.ts`): senkrechte Ebene
//! (Schnitt: u entlang der Ebene, v = Höhe) oder waagrechte (Grundriss auf Schnitthöhe). Geschlossene
//! Netze ergeben Ringe, offene (Gelände) Linienzüge. Ecken exakt auf der Ebene werden der „hinteren"
//! Seite zugeschlagen (`d > 0` = vorn), damit sich die Segmente schliessen. Rechenreihenfolge wie in
//! TS (Punkt-Schlüssel auf 1e-6 gerundet mit `Math.round`).
//!
//! ## Schnitt
//! `cut(positions, indices, plane)` mit `plane = [0, px, py, dx, dy]` (senkrecht) oder `[1, z]`
//! (waagrecht) → `[nRinge, (k, u, v …) × nRinge, nZüge, (k, u, v …) × nZüge]`; leer bei Unsinn.
//!
//! ## Ringe → Flächen
//! `rings_to_polygons(in)` mit `in = [n, (k, u, v …) × n]` → `[p, (r, (k, u, v …) × r) × p]`
//! (Aussenring zuerst, dann Löcher; Schachtelungstiefe gerade = aussen).
use crate::jsnum::round;
use std::collections::{HashMap, VecDeque};
type P = (f64, f64);
const QUANT: f64 = 1e6;
fn key(p: P) -> (i64, i64) {
(round(p.0 * QUANT) as i64, round(p.1 * QUANT) as i64)
}
fn chain(segs: &[(P, P)]) -> (Vec<Vec<P>>, Vec<Vec<P>>) {
let mut by_start: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
let mut by_end: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
for (i, s) in segs.iter().enumerate() {
by_start.entry(key(s.0)).or_default().push(i);
by_end.entry(key(s.1)).or_default().push(i);
}
let mut used = vec![false; segs.len()];
fn take(m: &mut HashMap<(i64, i64), Vec<usize>>, k: (i64, i64), used: &[bool]) -> Option<usize> {
let l = m.get_mut(&k)?;
while let Some(i) = l.pop() {
if !used[i] {
return Some(i);
}
}
None
}
let mut rings = Vec::new();
let mut lines = Vec::new();
for i in 0..segs.len() {
if used[i] {
continue;
}
used[i] = true;
let mut pts: VecDeque<P> = VecDeque::from([segs[i].0, segs[i].1]);
let start_key = key(pts[0]);
loop {
let k = key(*pts.back().unwrap());
if k == start_key && pts.len() > 2 {
break;
}
let Some(n) = take(&mut by_start, k, &used) else { break };
used[n] = true;
pts.push_back(segs[n].1);
}
if key(*pts.back().unwrap()) == start_key && pts.len() > 3 {
pts.pop_back();
rings.push(pts.into_iter().collect());
continue;
}
let mut closed = false;
loop {
let k = key(pts[0]);
let Some(n) = take(&mut by_end, k, &used) else { break };
used[n] = true;
pts.push_front(segs[n].0);
if key(pts[0]) == key(*pts.back().unwrap()) {
pts.pop_front();
rings.push(pts.iter().copied().collect());
closed = true;
break;
}
}
if !closed && pts.len() >= 2 {
lines.push(pts.into_iter().collect());
}
}
(rings, lines)
}
pub fn cut(positions: &[f64], indices: &[f64], plane: &[f64]) -> Vec<f64> {
let nv = positions.len() / 3;
let vertical = match plane.first() {
Some(&k) if k == 0.0 && plane.len() == 5 => true,
Some(&k) if k == 1.0 && plane.len() == 2 => false,
_ => return Vec::new(),
};
if positions.iter().chain(indices).chain(plane).any(|v| !v.is_finite())
|| indices.iter().any(|&i| i < 0.0 || i.fract() != 0.0 || i as usize >= nv)
{
return Vec::new();
}
let mut dist = vec![0.0; nv];
let mut c0 = vec![0.0; nv];
let mut c1 = vec![0.0; nv];
for i in 0..nv {
let (x, y, z) = (positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
if vertical {
let (px, py, dx, dy) = (plane[1], plane[2], plane[3], plane[4]);
dist[i] = (x - px) * dy - (y - py) * dx;
c0[i] = (x - px) * dx + (y - py) * dy;
c1[i] = z;
} else {
dist[i] = z - plane[1];
c0[i] = x;
c1[i] = y;
}
}
let mut edge_pt: HashMap<(usize, usize), P> = HashMap::new();
let mut crossing = |a: usize, b: usize| -> P {
let k = if a < b { (a, b) } else { (b, a) };
*edge_pt.entry(k).or_insert_with(|| {
let t = dist[a] / (dist[a] - dist[b]);
(c0[a] + (c0[b] - c0[a]) * t, c1[a] + (c1[b] - c1[a]) * t)
})
};
let mut segs: Vec<(P, P)> = Vec::new();
let mut t = 0;
while t + 2 < indices.len() {
let (a, b, c) = (indices[t] as usize, indices[t + 1] as usize, indices[t + 2] as usize);
t += 3;
let (sa, sb, sc) = (dist[a] > 0.0, dist[b] > 0.0, dist[c] > 0.0);
if sa == sb && sb == sc {
continue;
}
let odd = if sa != sb && sa != sc { a } else if sb != sa && sb != sc { b } else { c };
let o1 = if odd == a { b } else if odd == b { c } else { a };
let o2 = if odd == a { c } else if odd == b { a } else { b };
let p = crossing(odd, o1);
let q = crossing(odd, o2);
if (p.0 - q.0).abs() < 1e-9 && (p.1 - q.1).abs() < 1e-9 {
continue;
}
segs.push(if dist[odd] > 0.0 { (q, p) } else { (p, q) });
}
let (rings, lines) = chain(&segs);
let mut f = vec![rings.len() as f64];
for r in &rings {
push_ring(&mut f, r);
}
f.push(lines.len() as f64);
for l in &lines {
push_ring(&mut f, l);
}
f
}
fn push_ring(f: &mut Vec<f64>, r: &[P]) {
f.push(r.len() as f64);
for p in r {
f.extend([p.0, p.1]);
}
}
fn ring_area(r: &[P]) -> f64 {
let mut a = 0.0;
for i in 0..r.len() {
let p = r[i];
let q = r[(i + 1) % r.len()];
a += p.0 * q.1 - q.0 * p.1;
}
a / 2.0
}
fn point_in_ring(p: P, r: &[P]) -> bool {
let mut inside = false;
let mut j = r.len() - 1;
for i in 0..r.len() {
let (xi, yi) = r[i];
let (xj, yj) = r[j];
if (yi > p.1) != (yj > p.1) && p.0 < ((xj - xi) * (p.1 - yi)) / (yj - yi) + xi {
inside = !inside;
}
j = i;
}
inside
}
pub fn rings_to_polygons(inp: &[f64]) -> Vec<f64> {
if inp.is_empty() || inp.iter().any(|v| !v.is_finite()) || inp[0] < 0.0 {
return Vec::new();
}
let n = inp[0] as usize;
let mut rings: Vec<Vec<P>> = Vec::with_capacity(n);
let mut i = 1;
for _ in 0..n {
let Some(&k) = inp.get(i) else { return Vec::new() };
if k < 0.0 || i + 1 + 2 * k as usize > inp.len() {
return Vec::new();
}
let k = k as usize;
rings.push((0..k).map(|j| (inp[i + 1 + 2 * j], inp[i + 2 + 2 * j])).collect());
i += 1 + 2 * k;
}
if i != inp.len() {
return Vec::new();
}
let mut items: Vec<(Vec<P>, f64)> = rings
.into_iter()
.filter(|r| r.len() >= 3 && ring_area(r).abs() > 1e-12)
.map(|r| {
let a = ring_area(&r).abs();
(r, a)
})
.collect();
items.sort_by(|a, b| (b.1 - a.1).partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal));
let mut depth = vec![0usize; items.len()];
let mut parent: Vec<Option<usize>> = vec![None; items.len()];
for i in 0..items.len() {
for j in (0..i).rev() {
if point_in_ring(items[i].0[0], &items[j].0) {
parent[i] = Some(j);
depth[i] = depth[j] + 1;
break;
}
}
}
let mut out: Vec<Vec<usize>> = Vec::new();
let mut idx: HashMap<usize, usize> = HashMap::new();
for i in 0..items.len() {
if depth[i] % 2 == 0 {
idx.insert(i, out.len());
out.push(vec![i]);
}
}
for i in 0..items.len() {
if depth[i] % 2 == 1 {
if let Some(owner) = parent[i].and_then(|p| idx.get(&p)) {
out[*owner].push(i);
}
}
}
let mut f = vec![out.len() as f64];
for poly in &out {
f.push(poly.len() as f64);
for &r in poly {
push_ring(&mut f, &items[r].0);
}
}
f
}
#[cfg(test)]
mod tests {
use super::*;
/// Würfel 0..2 (12 Dreiecke, nach aussen gewunden).
fn cube() -> (Vec<f64>, Vec<f64>) {
let mut p = Vec::new();
for z in [0.0, 2.0] {
for y in [0.0, 2.0] {
for x in [0.0, 2.0] {
p.extend([x, y, z]);
}
}
}
let f = [
0, 2, 1, 1, 2, 3, 4, 5, 6, 5, 7, 6, 0, 1, 4, 1, 5, 4, 2, 6, 3, 3, 6, 7, 0, 4, 2, 2, 4, 6, 1, 3, 5, 3, 7, 5,
];
(p, f.iter().map(|&i| i as f64).collect())
}
#[test]
fn waagrechter_schnitt_ergibt_einen_ring() {
let (p, f) = cube();
let r = cut(&p, &f, &[1.0, 1.0]);
assert_eq!(r[0], 1.0);
// Die Diagonalen der Seitenflächen liefern Zwischenpunkte: 4 Ecken + 4 Mitten.
assert_eq!(r[1], 8.0);
assert_eq!(r[2 + 16], 0.0); // keine Linienzüge
}
#[test]
fn ebene_ausserhalb_ist_leer_aber_gueltig() {
let (p, f) = cube();
assert_eq!(cut(&p, &f, &[1.0, 10.0]), vec![0.0, 0.0]);
}
#[test]
fn unsinn_ist_leer() {
assert!(cut(&[0.0, 0.0, 0.0], &[0.0, 1.0, 2.0], &[1.0, 0.0]).is_empty());
assert!(cut(&[0.0; 9], &[0.0, 1.0, 2.0], &[7.0]).is_empty());
}
#[test]
fn loch_gehoert_zum_aussenring() {
let outer = [4.0, 0.0, 0.0, 10.0, 0.0, 10.0, 10.0, 0.0, 10.0];
let hole = [4.0, 4.0, 4.0, 6.0, 4.0, 6.0, 6.0, 4.0, 6.0];
let mut inp = vec![2.0];
inp.extend(outer);
inp.extend(hole);
let f = rings_to_polygons(&inp);
assert_eq!(&f[..3], &[1.0, 2.0, 4.0]);
}
}
File diff suppressed because it is too large. Load diff
+216
View File
@@ -0,0 +1,216 @@
//! Abfragen auf dem typisierten Projekt ([K4] S2): Rust-Gegenstück zu den Nachschlage- und
//! Auflösungsfunktionen aus `src/model/types.ts` und `src/model/wall.ts` (`getWallType`,
//! `wallVerticalExtent`, `roofBaseElevation` …). Wo TS wirft und der Aufrufer einen Rückfall
//! einsetzt (try/catch), liefern die Funktionen hier `Option` und der Aufrufer setzt denselben
//! Rückfall ein.
use super::*;
use crate::roof::{MansardType, RoofParams, Shape};
use crate::roof_skeleton::Axis;
impl Project {
pub fn floor(&self, id: &str) -> Option<&DrawingLevel> {
self.drawing_levels.iter().find(|l| l.id == id)
}
pub fn wall_type(&self, w: &Wall) -> Option<&WallType> {
self.wall_types.iter().find(|t| t.id == w.wall_type_id)
}
pub fn component(&self, id: &str) -> Option<&Component> {
self.components.iter().find(|c| c.id == id)
}
pub fn hatch(&self, id: &str) -> Option<&HatchStyle> {
self.hatches.iter().find(|h| h.id == id)
}
pub fn line_style(&self, id: &str) -> Option<&LineStyle> {
self.line_styles.iter().find(|l| l.id == id)
}
pub fn door_type(&self, o: &Opening) -> Option<&DoorType> {
let id = o.type_id.as_deref()?;
self.door_types.as_deref()?.iter().find(|t| t.id == id)
}
pub fn window_type(&self, o: &Opening) -> Option<&WindowType> {
let id = o.type_id.as_deref()?;
self.window_types.as_deref()?.iter().find(|t| t.id == id)
}
pub fn stair_type(&self, s: &Stair) -> Option<&StairType> {
let id = s.type_id.as_deref()?;
self.stair_types.as_deref()?.iter().find(|t| t.id == id)
}
pub fn openings_of_wall<'a>(&'a self, wall_id: &'a str) -> impl Iterator<Item = &'a Opening> + 'a {
self.openings.as_deref().unwrap_or(&[]).iter().filter(move |o| o.host_wall_id == wall_id)
}
/// Alle Kategorien flach (Reihenfolge wie `flattenCategories`).
pub fn flat_categories(&self) -> Vec<&LayerCategory> {
fn walk<'a>(list: &'a [LayerCategory], out: &mut Vec<&'a LayerCategory>) {
for c in list {
out.push(c);
if let Some(ch) = &c.children {
walk(ch, out);
}
}
}
let mut out = Vec::new();
walk(&self.layers, &mut out);
out
}
pub fn layer_category(&self, code: &str) -> Option<&LayerCategory> {
self.flat_categories().into_iter().find(|c| c.code == code)
}
/// Dicke eines Wandtyps (Summe der Schichten).
pub fn type_thickness(layers: &[Layer]) -> f64 {
layers.iter().map(|l| l.thickness).sum()
}
/// Wanddicke; nicht auflösbarer Typ → `fallback` (TS: try/catch mit 0.2).
pub fn wall_thickness(&self, w: &Wall, fallback: f64) -> f64 {
self.wall_type(w).map_or(fallback, |t| Self::type_thickness(&t.layers))
}
/// Deckendicke: `thickness` > 0, sonst Typ-Dicke, sonst 0.2.
pub fn ceiling_thickness(&self, c: &Ceiling) -> f64 {
if let Some(t) = c.thickness.filter(|t| *t > 0.0) {
return t;
}
let layers = c
.ceiling_type_id
.as_deref()
.and_then(|id| self.ceiling_types.as_deref()?.iter().find(|t| t.id == id).map(|t| &t.layers))
.or_else(|| self.wall_types.iter().find(|t| t.id == c.wall_type_id).map(|t| &t.layers));
layers.map_or(0.2, |l| Self::type_thickness(l))
}
/// Schichten eines Dachs; ohne Typ/Schichten eine Schicht mit der Dachdicke.
pub fn roof_layers(&self, r: &Roof) -> Vec<Layer> {
if let Some(id) = r.roof_type_id.as_deref() {
if let Some(rt) = self.roof_types.as_deref().and_then(|v| v.iter().find(|t| t.id == id)) {
if !rt.layers.is_empty() {
return rt.layers.clone();
}
}
}
vec![Layer { component_id: String::new(), thickness: r.thickness.max(0.0), ..Default::default() }]
}
fn resolve_anchor(&self, a: Option<&VerticalAnchor>) -> Option<f64> {
match a? {
VerticalAnchor::Custom { z } => Some(*z),
VerticalAnchor::Floor { floor_id, offset } => {
let f = self.floor(floor_id)?;
Some(f.base_elevation.unwrap_or(0.0) + offset.unwrap_or(0.0))
}
}
}
/// (UK, OK) einer Wand in Metern (`wallVerticalExtent`).
pub fn wall_vertical_extent(&self, w: &Wall) -> (f64, f64) {
let floor_base = self.floor(&w.floor_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0));
let bottom = self.resolve_anchor(w.bottom.as_ref()).unwrap_or(floor_base);
let top = self.resolve_anchor(w.top.as_ref()).unwrap_or(bottom + w.height);
(bottom, top)
}
pub fn ceiling_vertical_extent(&self, c: &Ceiling) -> (f64, f64) {
let floor_top = self.floor(&c.floor_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0) + f.floor_height.unwrap_or(0.0));
let top = self.resolve_anchor(c.top.as_ref()).unwrap_or(floor_top);
let bottom = self.resolve_anchor(c.bottom.as_ref()).unwrap_or(top - self.ceiling_thickness(c));
(bottom, top)
}
pub fn stair_vertical_extent(&self, s: &Stair) -> (f64, f64) {
let (base, floor_height) = self.floor(&s.floor_id).map_or((0.0, 0.0), |f| (f.base_elevation.unwrap_or(0.0), f.floor_height.unwrap_or(0.0)));
let rise = match s.total_rise {
Some(r) if r > 0.0 => r,
_ if floor_height > 0.0 => floor_height,
_ => 2.6,
};
(base, base + rise)
}
pub fn column_vertical_extent(&self, c: &Column) -> (f64, f64) {
let floor_base = self.floor(&c.floor_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0));
let bottom = self.resolve_anchor(c.bottom.as_ref()).unwrap_or(floor_base);
let top = self.resolve_anchor(c.top.as_ref()).unwrap_or(bottom + c.height);
(bottom, top)
}
/// Traufhöhe (absolutes Z): `baseElevation`, sonst Oberkante des Geschosses (`roofBaseElevation`).
pub fn roof_base_elevation(&self, r: &Roof) -> f64 {
if let Some(b) = r.base_elevation {
return b;
}
self.floor(&r.floor_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0) + f.floor_height.unwrap_or(0.0))
}
}
impl Roof {
/// Parameter für die Dachgeometrie (`roof::roof_geometry`).
pub fn params(&self) -> RoofParams {
RoofParams {
outline: self.outline.iter().map(|v| [v.x, v.y]).collect(),
shape: match self.shape {
RoofShape::Flach | RoofShape::Unknown => Shape::Flach,
RoofShape::Pult => Shape::Pult,
RoofShape::Sattel => Shape::Sattel,
RoofShape::Walm => Shape::Walm,
RoofShape::Mansarde => Shape::Mansarde,
RoofShape::Zelt => Shape::Zelt,
},
pitch_deg: self.pitch_deg,
pitch_upper_deg: self.pitch_upper_deg,
mansard_type: match self.mansard_type {
Some(RoofMansardType::Walm) => MansardType::Walm,
Some(RoofMansardType::Zelt) => MansardType::Zelt,
_ => MansardType::Giebel,
},
mansard_knee_ratio: self.mansard_knee_ratio,
half_hip_ratio: self.half_hip_ratio,
overhang: self.overhang,
overhang_gable: self.overhang_gable,
ridge_axis: if self.ridge_axis == RoofRidgeAxis::Y { Axis::Y } else { Axis::X },
}
}
}
impl Stair {
/// Treppen-Parameter als 16 Zahlen (Aufbau: `stair.rs`, `encodeStair` in TS); fehlend = NaN.
pub fn encode(&self) -> [f64; 16] {
let n = |v: Option<f64>| v.unwrap_or(f64::NAN);
[
match self.shape {
StairShape::Straight | StairShape::Unknown => 0.0,
StairShape::L => 1.0,
StairShape::Spiral => 2.0,
},
self.start.x,
self.start.y,
self.dir.x,
self.dir.y,
self.run_length,
n(self.run2_length),
n(self.turn),
n(self.center.map(|c| c.x)),
n(self.center.map(|c| c.y)),
n(self.radius),
n(self.sweep),
self.width,
self.step_count,
self.up.map_or(f64::NAN, |u| if u { 1.0 } else { 0.0 }),
match self.referenz {
Some(StairReferenz::Links) => 1.0,
Some(StairReferenz::Rechts) => 2.0,
_ => 0.0,
},
]
}
}
+308
View File
@@ -0,0 +1,308 @@
//! Von Hand geschriebene Teile des Modells: Typen mit Tag (diskriminierte Unions) und `Vec2`.
//! Gegenstück zu den entsprechenden Typen in `src/model/types.ts`.
use super::generated::*;
use serde::{Deserialize, Serialize};
/// Felder, die das Modell (noch) nicht kennt: bleiben beim Hin-und-zurück erhalten, damit Rust
/// nichts verliert, was neuere Programmstände oder Erweiterungen in die Datei geschrieben haben.
/// In Tests meldet ein unbekanntes Feld sich als Panic — so fällt eine Lücke im Modell auf.
#[derive(Debug, Clone, PartialEq, Default, Serialize)]
pub struct Extra(pub serde_json::Map<String, serde_json::Value>);
impl<'de> Deserialize<'de> for Extra {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let m = serde_json::Map::<String, serde_json::Value>::deserialize(d)?;
#[cfg(test)]
if !m.is_empty() {
panic!("Modell kennt Felder nicht: {:?}", m.keys().collect::<Vec<_>>());
}
Ok(Extra(m))
}
}
impl Extra {
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
#[cfg_attr(test, serde(deny_unknown_fields))]
pub struct Vec2 {
pub x: f64,
pub y: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "mode")]
pub enum VerticalAnchor {
#[serde(rename = "floor")]
Floor {
#[serde(rename = "floorId")]
floor_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
offset: Option<f64>,
},
#[serde(rename = "custom")]
Custom { z: f64 },
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind")]
pub enum ColumnProfile {
#[serde(rename = "rect")]
Rect { width: f64, depth: f64 },
#[serde(rename = "round")]
Round { radius: f64 },
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Offset2 {
pub along: f64,
pub perp: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum KoteKind {
#[serde(rename = "okFertig")]
OkFertig,
#[serde(rename = "ukFertig")]
UkFertig,
#[serde(rename = "okRoh")]
OkRoh,
#[serde(rename = "ukRoh")]
UkRoh,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SplineMode {
Fit,
Control,
}
/// Geometrie eines 2D-Zeichenelements (Tag `shape`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "shape")]
pub enum Drawing2DGeom {
#[serde(rename = "line")]
Line { a: Vec2, b: Vec2 },
#[serde(rename = "xline")]
Xline { a: Vec2, b: Vec2 },
#[serde(rename = "ray")]
Ray { a: Vec2, b: Vec2 },
#[serde(rename = "polyline")]
Polyline {
pts: Vec<Vec2>,
closed: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
bulge: Option<Vec<f64>>,
},
#[serde(rename = "rect")]
Rect { min: Vec2, max: Vec2 },
#[serde(rename = "circle")]
Circle { center: Vec2, r: f64 },
#[serde(rename = "arc")]
Arc { center: Vec2, r: f64, a0: f64, a1: f64 },
#[serde(rename = "ellipse")]
Ellipse { center: Vec2, rx: f64, ry: f64, rotation: f64 },
#[serde(rename = "bezier")]
Bezier { pts: Vec<Vec2> },
#[serde(rename = "spline")]
Spline {
pts: Vec<Vec2>,
closed: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
mode: Option<SplineMode>,
},
#[serde(rename = "dimension")]
Dimension {
pts: Vec<Vec2>,
offset: f64,
#[serde(rename = "gapMm", default, skip_serializing_if = "Option::is_none")]
gap_mm: Option<f64>,
#[serde(rename = "overshootMm", default, skip_serializing_if = "Option::is_none")]
overshoot_mm: Option<f64>,
#[serde(rename = "tickLenMm", default, skip_serializing_if = "Option::is_none")]
tick_len_mm: Option<f64>,
#[serde(rename = "textHeightMm", default, skip_serializing_if = "Option::is_none")]
text_height_mm: Option<f64>,
#[serde(rename = "lineWeightMm", default, skip_serializing_if = "Option::is_none")]
line_weight_mm: Option<f64>,
#[serde(rename = "extWeightMm", default, skip_serializing_if = "Option::is_none")]
ext_weight_mm: Option<f64>,
#[serde(rename = "tickWeightMm", default, skip_serializing_if = "Option::is_none")]
tick_weight_mm: Option<f64>,
#[serde(rename = "textOffsetsMm", default, skip_serializing_if = "Option::is_none")]
text_offsets_mm: Option<Vec<Offset2>>,
},
#[serde(rename = "kote")]
Kote { at: Vec2, value: f64, kind: KoteKind, rotation: f64 },
#[serde(rename = "detailref")]
Detailref {
at: Vec2,
label: String,
#[serde(rename = "sheetLayoutId", default, skip_serializing_if = "Option::is_none")]
sheet_layout_id: Option<String>,
#[serde(rename = "sheetLabel", default, skip_serializing_if = "Option::is_none")]
sheet_label: Option<String>,
},
#[serde(rename = "scalebar")]
Scalebar {
at: Vec2,
#[serde(rename = "segmentLength")]
segment_length: f64,
segments: f64,
},
#[serde(rename = "pointmarker")]
Pointmarker { at: Vec2 },
#[serde(rename = "text")]
Text {
at: Vec2,
text: String,
height: f64,
angle: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
width: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
marks: Option<Marks>,
#[serde(default, skip_serializing_if = "Option::is_none")]
doc: Option<RichTextDoc>,
#[serde(rename = "leaderTarget", default, skip_serializing_if = "Option::is_none")]
leader_target: Option<Vec2>,
#[serde(rename = "leaderBendPoints", default, skip_serializing_if = "Option::is_none")]
leader_bend_points: Option<Vec<Vec2>>,
#[serde(rename = "pathPts", default, skip_serializing_if = "Option::is_none")]
path_pts: Option<Vec<Vec2>>,
},
#[serde(rename = "block")]
Block {
#[serde(rename = "blockDefId")]
block_def_id: String,
at: Vec2,
rotation: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
scale: Option<f64>,
},
#[serde(rename = "image")]
Image {
min: Vec2,
max: Vec2,
src: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
opacity: Option<f64>,
},
}
/// Layout-Beschriftung (Tag `kind`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind")]
pub enum LayoutAnnotation {
#[serde(rename = "line")]
Line {
id: String,
#[serde(rename = "x1Mm")]
x1_mm: f64,
#[serde(rename = "y1Mm")]
y1_mm: f64,
#[serde(rename = "x2Mm")]
x2_mm: f64,
#[serde(rename = "y2Mm")]
y2_mm: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
color: Option<String>,
#[serde(rename = "weightMm", default, skip_serializing_if = "Option::is_none")]
weight_mm: Option<f64>,
},
#[serde(rename = "rect")]
Rect {
id: String,
#[serde(rename = "xMm")]
x_mm: f64,
#[serde(rename = "yMm")]
y_mm: f64,
#[serde(rename = "widthMm")]
width_mm: f64,
#[serde(rename = "heightMm")]
height_mm: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
color: Option<String>,
#[serde(rename = "weightMm", default, skip_serializing_if = "Option::is_none")]
weight_mm: Option<f64>,
},
#[serde(rename = "text")]
Text {
id: String,
#[serde(rename = "xMm")]
x_mm: f64,
#[serde(rename = "yMm")]
y_mm: f64,
text: String,
#[serde(rename = "heightMm")]
height_mm: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
color: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
doc: Option<RichTextDoc>,
#[serde(rename = "widthMm", default, skip_serializing_if = "Option::is_none")]
width_mm: Option<f64>,
},
#[serde(rename = "image")]
Image {
id: String,
#[serde(rename = "xMm")]
x_mm: f64,
#[serde(rename = "yMm")]
y_mm: f64,
#[serde(rename = "widthMm")]
width_mm: f64,
#[serde(rename = "heightMm")]
height_mm: f64,
src: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
opacity: Option<f64>,
},
}
/// Parametrische Wandregel (Tag `type`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum ParametricRule {
#[serde(rename = "grid")]
Grid(GridRule),
#[serde(rename = "module")]
Module(ModuleRule),
#[serde(rename = "conditional-thickness")]
ConditionalThickness(ConditionalThicknessRule),
#[serde(rename = "reference-line")]
ReferenceLine(ReferenceLineRule),
#[serde(rename = "sequence")]
Sequence(SequenceRule),
}
/// Kontext-Objekt (Tag `type`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum ContextObject {
#[serde(rename = "importedMesh")]
ImportedMesh(ImportedMesh),
#[serde(rename = "contourSet")]
ContourSet(ContourSet),
#[serde(rename = "terrainMesh")]
TerrainMesh(TerrainMesh),
#[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 }
}
}
+39
View File
@@ -0,0 +1,39 @@
//! Typisiertes Projektmodell ([K4] S2): Rust-Gegenstück zu `src/model/types.ts`. `generated.rs`
//! entstand aus den TS-Typen (`scripts/gen-rust-model.py`) und wird ab jetzt von Hand gepflegt;
//! Typen mit Tag stehen in `manual.rs`.
pub mod generated;
pub mod helpers;
pub mod manual;
pub use generated::*;
pub use manual::*;
#[cfg(test)]
mod tests {
use super::*;
use serde_json::Value;
/// Zahlen als f64 vergleichbar machen (JS kennt keinen Unterschied zwischen 3 und 3.0).
fn norm(v: &Value) -> Value {
match v {
Value::Number(n) => serde_json::Number::from_f64(n.as_f64().unwrap()).map_or(Value::Null, Value::Number),
Value::Array(a) => Value::Array(a.iter().map(norm).collect()),
Value::Object(o) => Value::Object(o.iter().map(|(k, v)| (k.clone(), norm(v))).collect()),
other => other.clone(),
}
}
fn roundtrip(name: &str, text: &str) {
let raw: Value = serde_json::from_str(text).unwrap();
// `deny_unknown_fields` (nur im Test) meldet jedes Feld, das dem Modell fehlt.
let p: Project = serde_json::from_value(raw.clone()).unwrap_or_else(|e| panic!("{name}: {e}"));
let back = serde_json::to_value(&p).unwrap();
assert_eq!(norm(&back), norm(&raw), "{name}: Hin-und-zurück weicht ab");
}
#[test]
fn beispielprojekt_hin_und_zurueck() {
roundtrip("sample_project", include_str!("../../tests/fixtures/sample_project.json"));
}
}
File diff suppressed because it is too large. Load diff
+329
View File
@@ -0,0 +1,329 @@
//! Öffnungs-Geometrie im Grundriss ([K3a]): Pfosten, Lücke, Türblätter und das Fenster-Symbol
//! (Rahmen, Glaslinien, Flügel- und Stulpmarken). Port von `src/geometry/opening.ts`; Rechen-
//! reihenfolge und Zahlsemantik wie in TS (`Math.hypot` über `jsmath`, `Math.min/max/round`
//! über `jsnum`, `cos/sin` über `jsnum`), damit die Ausgabe bitgleich bleibt.
use crate::jsmath::hypot2;
use crate::jsnum::{cos, max, min, round, sin};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct V {
pub x: f64,
pub y: f64,
}
pub fn v(x: f64, y: f64) -> V {
V { x, y }
}
pub fn sub(a: V, b: V) -> V {
v(a.x - b.x, a.y - b.y)
}
pub fn add(a: V, b: V) -> V {
v(a.x + b.x, a.y + b.y)
}
pub fn scale(a: V, s: f64) -> V {
v(a.x * s, a.y * s)
}
pub fn dot(p: V, q: V) -> f64 {
p.x * q.x + p.y * q.y
}
pub fn normalize(a: V) -> V {
let l = hypot2(a.x, a.y);
let l = if l == 0.0 || l.is_nan() { 1.0 } else { l };
v(a.x / l, a.y / l)
}
pub fn left_normal(a: V) -> V {
v(-a.y, a.x)
}
pub fn along(p1: V, p2: V, d: f64) -> V {
add(p1, scale(normalize(sub(p2, p1)), d))
}
const DEG: f64 = std::f64::consts::PI / 180.0;
const DEFAULT_POST_WIDTH: f64 = 0.06;
const DEFAULT_FRAME_DEPTH: f64 = 0.07;
/// Wand für die Öffnungs-Geometrie: Achse, aufgelöste Dicke und Referenzversatz.
#[derive(Clone, Copy, Debug)]
pub struct WallRef {
pub start: V,
pub end: V,
pub total: f64,
pub ref_off: f64,
}
impl WallRef {
pub fn frame(&self) -> (V, V) {
let u = normalize(sub(self.end, self.start));
(u, left_normal(u))
}
}
/// Öffnungs-Intervall entlang der Achse (auf die Achslänge geklemmt) oder `None` (entartet).
pub fn opening_interval(w: &WallRef, position: f64, width: f64) -> Option<(f64, f64)> {
let axis = hypot2(w.end.x - w.start.x, w.end.y - w.start.y);
let from = max(0.0, min(position, axis));
let to = max(from, min(position + width, axis));
if to - from < 1e-4 {
None
} else {
Some((from, to))
}
}
pub fn opening_jambs(w: &WallRef, position: f64, width: f64) -> Option<(V, V)> {
let (from, to) = opening_interval(w, position, width)?;
Some((along(w.start, w.end, from), along(w.start, w.end, to)))
}
/// Lücken-Rechteck über die volle Wanddicke (jambStart+n/2 → jambEnd+n/2 → jambEnd−n/2 → jambStart−n/2).
pub fn opening_gap_quad(w: &WallRef, position: f64, width: f64) -> Option<Vec<V>> {
let (js, je) = opening_jambs(w, position, width)?;
let n = w.frame().1;
let outer = w.ref_off + w.total / 2.0;
let inner = w.ref_off - w.total / 2.0;
Some(vec![add(js, scale(n, outer)), add(je, scale(n, outer)), add(je, scale(n, inner)), add(js, scale(n, inner))])
}
#[derive(Clone, Copy, Debug)]
pub struct DoorLeaf {
pub hinge: V,
pub open_end: V,
pub closed_end: V,
pub radius: f64,
}
fn compute_leaf(hinge: V, closed_dir: V, swing_dir: V, angle: f64, width: f64) -> DoorLeaf {
let open_dir = v(closed_dir.x * cos(angle) + swing_dir.x * sin(angle), closed_dir.y * cos(angle) + swing_dir.y * sin(angle));
DoorLeaf { hinge, open_end: add(hinge, scale(open_dir, width)), closed_end: add(hinge, scale(closed_dir, width)), radius: width }
}
/// Tür-Parameter: `swing_right`, `open_out`, `hinge_end` (false = Start), `swing_angle` in Grad.
#[derive(Clone, Copy, Debug)]
pub struct DoorParams {
pub swing_right: bool,
pub open_out: bool,
pub hinge_end: bool,
pub swing_angle: f64,
}
/// Türblätter (1 oder 2 Flügel); leer bei entarteter Öffnung.
pub fn door_leaves(w: &WallRef, position: f64, width: f64, p: &DoorParams, leaf_count: f64) -> Vec<DoorLeaf> {
let Some((js, je)) = opening_jambs(w, position, width) else { return Vec::new() };
let (u, n) = w.frame();
let wd = hypot2(je.x - js.x, je.y - js.y);
let swing_sign = if p.swing_right { -1.0 } else { 1.0 };
let dir_sign = if p.open_out { -1.0 } else { 1.0 };
let swing_dir = scale(n, swing_sign * dir_sign);
let angle = p.swing_angle * DEG;
if leaf_count >= 2.0 {
let hw = wd / 2.0;
return vec![compute_leaf(js, u, swing_dir, angle, hw), compute_leaf(je, scale(u, -1.0), swing_dir, angle, hw)];
}
let (hinge, closed_dir) = if p.hinge_end { (je, scale(u, -1.0)) } else { (js, u) };
vec![compute_leaf(hinge, closed_dir, swing_dir, angle, wd)]
}
/// Eintrag der Flügeleinteilung.
#[derive(Clone, Copy, Debug)]
pub struct Sash {
pub post: bool,
/// `false` ⇔ `autoWidth === false`.
pub auto_width: bool,
/// feste Breite (nur wenn `!auto_width`), NaN = nicht gesetzt
pub width: f64,
pub post_width: f64,
pub operable: bool,
}
#[derive(Clone, Debug)]
pub struct WindowSpec {
pub sashes: Vec<Sash>,
pub frame_width: f64,
/// NaN = nicht gesetzt
pub frame_depth: f64,
/// NaN = nicht gesetzt
pub inset_from_face: f64,
pub inset_inner: bool,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Detail {
Grob,
Mittel,
Fein,
}
#[derive(Default, Clone, Debug)]
pub struct WindowSymbol {
pub frame: Vec<V>,
pub glass_lines: Vec<(V, V)>,
pub mullion_lines: Vec<(V, V)>,
pub sash_frames: Vec<Vec<V>>,
pub meeting_marks: Vec<Vec<V>>,
pub jamb_marks: Vec<Vec<V>>,
}
fn or_zero(x: f64) -> f64 {
if x.is_nan() {
0.0
} else {
x
}
}
fn sash_segments(sashes: &[Sash], total_width: f64) -> Vec<(usize, f64, f64)> {
if sashes.is_empty() {
return Vec::new();
}
let post_w = |s: &Sash| max(0.0, if s.post_width.is_nan() { DEFAULT_POST_WIDTH } else { s.post_width });
let fixed_w = |s: &Sash| max(0.0, or_zero(s.width));
let mut fixed_sum = 0.0;
let mut auto_count = 0.0;
for s in sashes {
if s.post {
fixed_sum += post_w(s);
} else if !s.auto_width {
fixed_sum += fixed_w(s);
} else {
auto_count += 1.0;
}
}
let remaining = max(0.0, total_width - fixed_sum);
let auto_width = if auto_count > 0.0 { remaining / auto_count } else { 0.0 };
let mut segs = Vec::with_capacity(sashes.len());
let mut cursor = 0.0;
for (i, s) in sashes.iter().enumerate() {
let w = if s.post {
post_w(s)
} else if !s.auto_width {
fixed_w(s)
} else {
auto_width
};
segs.push((i, cursor, cursor + w));
cursor += w;
}
segs
}
/// Fenster-Symbol; `spec` nur mit auflösbarem Typ (sonst Alt-Pfad mit `wing_count`, NaN = 1).
pub fn window_symbol(
w: &WallRef,
position: f64,
width: f64,
glass_count: f64,
spec: Option<&WindowSpec>,
wing_count: f64,
detail: Detail,
) -> Option<WindowSymbol> {
let (js, je) = opening_jambs(w, position, width)?;
let n = w.frame().1;
let total = w.total;
let ref_off = w.ref_off;
let outer = ref_off + total / 2.0;
let inner = ref_off - total / 2.0;
if let Some(spec) = spec.filter(|s| !s.sashes.is_empty()) {
let fw = max(0.01, spec.frame_width);
let depth = min(total, if !spec.frame_depth.is_nan() && spec.frame_depth > 1e-9 { spec.frame_depth } else { DEFAULT_FRAME_DEPTH });
let inset = max(0.0, or_zero(spec.inset_from_face));
let half_t = total / 2.0;
let sign = if spec.inset_inner { 1.0 } else { -1.0 };
let mut front_rel = sign * (half_t - inset);
let mut back_rel = front_rel - sign * depth;
front_rel = max(-half_t, min(half_t, front_rel));
back_rel = max(-half_t, min(half_t, back_rel));
let frame_outer_n = ref_off + max(front_rel, back_rel);
let frame_inner_n = ref_off + min(front_rel, back_rel);
let band_depth = frame_outer_n - frame_inner_n;
let g_mid_base = (frame_outer_n + frame_inner_n) / 2.0;
let frame = vec![
add(js, scale(n, frame_outer_n)),
add(je, scale(n, frame_outer_n)),
add(je, scale(n, frame_inner_n)),
add(js, scale(n, frame_inner_n)),
];
let mut sym = WindowSymbol { frame, ..Default::default() };
if detail == Detail::Grob {
sym.glass_lines.push((add(js, scale(n, g_mid_base)), add(je, scale(n, g_mid_base))));
return Some(sym);
}
let fein = detail == Detail::Fein;
let axis_width = hypot2(je.x - js.x, je.y - js.y);
let segs = sash_segments(&spec.sashes, axis_width);
let reveal = if fein { min(band_depth * 0.3, fw * 0.7) } else { 0.0 };
let frame_block = |u_center: f64, half_u: f64| -> Vec<V> {
let a = along(js, je, u_center - half_u);
let b = along(js, je, u_center + half_u);
vec![add(a, scale(n, frame_outer_n)), add(b, scale(n, frame_outer_n)), add(b, scale(n, frame_inner_n)), add(a, scale(n, frame_inner_n))]
};
sym.jamb_marks.push(frame_block(fw / 2.0, fw / 2.0));
sym.jamb_marks.push(frame_block(axis_width - fw / 2.0, fw / 2.0));
for i in 0..segs.len().saturating_sub(1) {
let u_pos = segs[i].2;
if fein {
sym.meeting_marks.push(frame_block(u_pos - fw / 2.0, fw / 2.0));
sym.meeting_marks.push(frame_block(u_pos + fw / 2.0, fw / 2.0));
} else {
sym.meeting_marks.push(frame_block(u_pos, fw / 2.0));
}
}
for &(si, from, to) in &segs {
let s = &spec.sashes[si];
if s.post {
continue;
}
let clear_from = from + fw;
let clear_to = to - fw;
if clear_to - clear_from <= 1e-6 {
continue;
}
if !fein {
continue;
}
let g_outer_n = frame_outer_n - if s.operable { reveal } else { 0.0 };
let g_inner_n = frame_inner_n + if s.operable { reveal } else { 0.0 };
if s.operable {
let s_from = along(js, je, clear_from);
let s_to = along(js, je, clear_to);
sym.sash_frames.push(vec![
add(s_from, scale(n, g_outer_n)),
add(s_to, scale(n, g_outer_n)),
add(s_to, scale(n, g_inner_n)),
add(s_from, scale(n, g_inner_n)),
]);
}
}
return Some(sym);
}
// Alt-Pfad
let frame = vec![add(js, scale(n, outer)), add(je, scale(n, outer)), add(je, scale(n, inner)), add(js, scale(n, inner))];
let mut sym = WindowSymbol { frame, ..Default::default() };
let count = max(1.0, glass_count);
let mut i = 0.0;
while i < count {
let spread = total / 8.0;
let off = ref_off + if count == 1.0 { 0.0 } else { (i - (count - 1.0) / 2.0) * spread * 2.0 };
sym.glass_lines.push((add(js, scale(n, off)), add(je, scale(n, off))));
i += 1.0;
}
let wc = if wing_count.is_nan() { 1.0 } else { wing_count };
let wings = max(1.0, min(4.0, round(wc)));
if wings > 1.0 {
let post_depth = total * 0.6;
let p_outer = ref_off + post_depth / 2.0;
let p_inner = ref_off - post_depth / 2.0;
let mut k = 1.0;
while k < wings {
let t = k / wings;
let on_axis = add(js, scale(sub(je, js), t));
sym.mullion_lines.push((add(on_axis, scale(n, p_outer)), add(on_axis, scale(n, p_inner))));
k += 1.0;
}
}
Some(sym)
}
+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);
}
}
+5
View File
@@ -0,0 +1,5 @@
//! Plan-Erzeugung auf dem Projekt-Dokument ([K3d]/[K4]): Rust-Gegenstück zu `src/plan/generatePlan.ts`
//! und `generatePlan/*.ts`.
pub mod prim;
pub mod style;
+198
View File
@@ -0,0 +1,198 @@
//! Plan-Primitive ([K3d]/[K4]): das Austauschformat zwischen Plan-Erzeugung und allen Verbrauchern
//! (Gegenstück zu `Primitive` in `src/plan/generatePlan/shared.ts`). Die JSON-Form ist
//! Zeichen für Zeichen die der TS-Objekte (camelCase, fehlende Felder fehlen).
use crate::model::*;
use serde::Serialize;
/// Aufgelöste Schraffur eines Polygons (`HatchRender`).
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HatchRender {
pub pattern: HatchPattern,
pub scale: f64,
pub angle: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub origin: Option<Vec2>,
pub color: String,
pub line_weight: f64,
pub dash: Option<Vec<f64>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub kind: Option<HatchStyleKind>,
#[serde(skip_serializing_if = "Option::is_none")]
pub lines: Option<HatchStyleLines>,
#[serde(skip_serializing_if = "Option::is_none")]
pub image: Option<HatchStyleImage>,
#[serde(skip_serializing_if = "Option::is_none")]
pub gradient: Option<HatchStyleGradient>,
#[serde(skip_serializing_if = "Option::is_none")]
pub seed: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub density: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub length_min: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub length_max: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub motif: Option<HatchStyleMotif>,
}
/// Zeile unter dem Raum-Stempel.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct StampLine {
pub text: String,
pub align: Align,
}
/// `dash?: number[] | null`: fehlt (`None`), `null` (`Some(None)`) oder Muster.
pub type Dash = Option<Option<Vec<f64>>>;
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "kind")]
pub enum Primitive {
#[serde(rename = "polygon", rename_all = "camelCase")]
Polygon {
pts: Vec<Vec2>,
fill: String,
stroke: String,
stroke_width_mm: f64,
hatch: HatchRender,
#[serde(skip_serializing_if = "Option::is_none")]
greyed: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
opacity: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
no_stroke_edges: Option<Vec<f64>>,
#[serde(skip_serializing_if = "Option::is_none")]
wall_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
drawing_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
ceiling_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
opening_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
stair_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
room_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
extruded_solid_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
context_object_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
column_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
roof_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
section_line_id: Option<String>,
},
#[serde(rename = "line", rename_all = "camelCase")]
Line {
a: Vec2,
b: Vec2,
cls: String,
weight_mm: f64,
#[serde(skip_serializing_if = "Option::is_none")]
dash: Dash,
#[serde(skip_serializing_if = "Option::is_none")]
zigzag: Option<LineStyleZigzag>,
#[serde(skip_serializing_if = "Option::is_none")]
motif: Option<LineStyleMotif>,
#[serde(skip_serializing_if = "Option::is_none")]
color: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
drawing_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
opening_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
stair_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
greyed: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
opacity: Option<f64>,
},
#[serde(rename = "arc", rename_all = "camelCase")]
Arc {
center: Vec2,
from: Vec2,
to: Vec2,
r: f64,
cls: String,
weight_mm: f64,
#[serde(skip_serializing_if = "Option::is_none")]
dash: Dash,
#[serde(skip_serializing_if = "Option::is_none")]
opening_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
stair_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
greyed: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
opacity: Option<f64>,
},
#[serde(rename = "text", rename_all = "camelCase")]
Text {
at: Vec2,
doc: RichTextDoc,
extra_lines: Vec<StampLine>,
base_pt: f64,
color: String,
#[serde(skip_serializing_if = "Option::is_none")]
room_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
greyed: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
opacity: Option<f64>,
},
#[serde(rename = "drawingText", rename_all = "camelCase")]
DrawingText {
at: Vec2,
text: String,
height_m: f64,
angle: f64,
color: String,
#[serde(skip_serializing_if = "Option::is_none")]
marks: Option<Marks>,
#[serde(skip_serializing_if = "Option::is_none")]
wrap_width: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
doc: Option<RichTextDoc>,
#[serde(skip_serializing_if = "Option::is_none")]
drawing_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
greyed: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
opacity: Option<f64>,
},
}
impl Primitive {
/// Setzt `greyed` (für Gruppen, deren Darstellungsmodus gedimmt ist).
pub fn with_greyed(mut self, g: bool) -> Self {
match &mut self {
Primitive::Polygon { greyed, .. } | Primitive::Line { greyed, .. } | Primitive::Arc { greyed, .. } | Primitive::Text { greyed, .. } | Primitive::DrawingText { greyed, .. } => *greyed = Some(g),
}
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::plan::style::no_hatch;
#[test]
fn line_dash_null_und_fehlend_unterscheiden_sich() {
let mk = |dash: Dash| Primitive::Line { a: Vec2 { x: 0.0, y: 0.0 }, b: Vec2 { x: 1.0, y: 0.0 }, cls: "c".into(), weight_mm: 0.1, dash, zigzag: None, motif: None, color: None, drawing_id: None, opening_id: None, stair_id: None, greyed: None, opacity: None };
assert!(!serde_json::to_string(&mk(None)).unwrap().contains("dash"));
assert!(serde_json::to_string(&mk(Some(None))).unwrap().contains("\"dash\":null"));
assert!(serde_json::to_string(&mk(Some(Some(vec![0.4])))).unwrap().contains("\"dash\":[0.4]"));
}
#[test]
fn polygon_tragt_kind_und_camel_case() {
let p = Primitive::Polygon { pts: vec![], fill: "#fff".into(), stroke: "#000".into(), stroke_width_mm: 0.2, hatch: no_hatch(), greyed: None, opacity: None, no_stroke_edges: None, wall_id: Some("w".into()), drawing_id: None, ceiling_id: None, opening_id: None, stair_id: None, room_id: None, extruded_solid_id: None, context_object_id: None, column_id: None, roof_id: None, section_line_id: None };
let s = serde_json::to_string(&p).unwrap();
assert!(s.contains("\"kind\":\"polygon\"") && s.contains("strokeWidthMm") && s.contains("\"wallId\":\"w\""));
}
}
+162
View File
@@ -0,0 +1,162 @@
//! Attribut-Auflösung (By-Layer / By-Object) und Schraffur-Auflösung des Grundriss-Generators —
//! Gegenstück zu `src/plan/generatePlan/shared.ts`.
use super::prim::HatchRender;
use crate::model::*;
pub const POCHE_STROKE: &str = "#1a1a1a";
pub const MONO_INK: &str = "#111111";
pub const LAYER_LINE_MM: f64 = 0.02;
pub const SYMBOL_HAIRLINE_MM: f64 = 0.02;
pub const OVERHEAD_DASH: [f64; 2] = [0.4, 0.25];
pub const ROOF_EAVES_MM: f64 = 0.13;
pub const ROOF_RIDGE_MM: f64 = 0.25;
pub const ROOF_HIP_MM: f64 = 0.18;
pub const ROOF_BREAK_MM: f64 = 0.09;
pub const ROOF_BREAK_DASH: [f64; 2] = [0.12, 0.08];
pub const WALL_FALLBACK_MM: f64 = 0.18;
pub const HATCH_PAPER: &str = "#f0f0f0";
pub const HATCH_INK: &str = "#0f0f0f";
/// Detailgrad der Plan-Darstellung.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Detail {
Grob,
Mittel,
Fein,
}
impl Detail {
pub fn parse(s: &str) -> Detail {
match s {
"grob" => Detail::Grob,
"fein" => Detail::Fein,
_ => Detail::Mittel,
}
}
/// Stärke der Wand-Umrisslinie als Faktor auf die Ebenen-lw.
pub fn outline_factor(self) -> f64 {
match self {
Detail::Grob => 1.6,
Detail::Mittel => 1.0,
Detail::Fein => 0.6,
}
}
/// Stärke der Schichtfugen.
pub fn layer_factor(self) -> f64 {
match self {
Detail::Fein => 0.7,
_ => 1.0,
}
}
}
/// Schraffur-Platzhalter „ohne" (für reine Umriss-/Sammelflächen).
pub fn no_hatch() -> HatchRender {
HatchRender {
pattern: HatchPattern::None,
scale: 1.0,
angle: 0.0,
origin: None,
color: POCHE_STROKE.into(),
line_weight: LAYER_LINE_MM,
dash: None,
kind: None,
lines: None,
image: None,
gradient: None,
seed: None,
density: None,
length_min: None,
length_max: None,
motif: None,
}
}
/// Neutrale Poché-Füllfarbe für ein Muster: „solid" → Tinte, sonst Papier.
pub fn poche_fill(p: HatchPattern) -> &'static str {
if p == HatchPattern::Solid {
HATCH_INK
} else {
HATCH_PAPER
}
}
/// `resolveHatch`: `None`, wenn Schraffur oder ihr Linienstil fehlen (TS wirft dort — Aufrufer fängt).
pub fn resolve_hatch(p: &Project, hatch_id: &str, wall_angle_deg: Option<f64>, foreground: Option<&str>, placement: Option<(Option<f64>, Option<f64>, Option<Vec2>)>) -> Option<HatchRender> {
let h = p.hatch(hatch_id)?;
let ls = match h.line_style_id.as_deref().filter(|s| !s.is_empty()) {
Some(id) => Some(p.line_style(id)?),
None => None,
};
let (p_angle, p_scale, p_origin) = placement.unwrap_or((None, None, None));
let base_angle = p_angle.unwrap_or(h.angle);
let angle = match wall_angle_deg {
Some(w) if h.relative_to_wall == Some(true) => base_angle - w,
_ => base_angle,
};
Some(HatchRender {
pattern: h.pattern,
scale: h.scale * p_scale.unwrap_or(1.0),
angle,
origin: p_origin,
color: foreground.unwrap_or(HATCH_INK).to_string(),
line_weight: ls.map_or(0.13, |l| l.weight),
dash: ls.and_then(|l| l.dash.clone()),
kind: h.kind,
lines: h.lines,
image: h.image.clone(),
gradient: h.gradient.clone(),
seed: h.seed,
density: h.density,
length_min: h.length_min,
length_max: h.length_max,
motif: h.motif.clone(),
})
}
/// Vordergrundfarbe der Schraffur: Override ?? (Quelle „layer" ⇒ Kategorie-Farbe) ?? Bauteil.
pub fn resolve_foreground<'a>(comp: &'a Component, override_: Option<&'a str>, category: Option<&'a LayerCategory>, source: Option<AttributeSource>) -> Option<&'a str> {
if let Some(o) = override_ {
return Some(o);
}
if source == Some(AttributeSource::Layer) {
return category.map(|c| c.color.as_str()).or(comp.foreground.as_deref());
}
comp.foreground.as_deref()
}
/// Hintergrund-/Füllfarbe (Poché-Override), analog [`resolve_foreground`].
pub fn resolve_background<'a>(comp: &'a Component, override_: Option<&'a str>, category: Option<&'a LayerCategory>, source: Option<AttributeSource>) -> Option<&'a str> {
if let Some(o) = override_ {
return Some(o);
}
if source == Some(AttributeSource::Layer) {
return category.map(|c| c.color.as_str()).or(comp.background.as_deref());
}
comp.background.as_deref()
}
/// Schraffur-Referenz: Override ?? (Quelle „layer" ⇒ Kategorie-Schraffur) ?? Rückfall.
pub fn resolve_hatch_id<'a>(override_: Option<&'a str>, source: Option<AttributeSource>, category: Option<&'a LayerCategory>, fallback: Option<&'a str>) -> Option<&'a str> {
if let Some(o) = override_ {
return Some(o);
}
if source == Some(AttributeSource::Layer) {
return category.and_then(|c| c.hatch.as_deref()).or(fallback);
}
fallback
}
/// Strichstärke: Override ?? (Quelle „layer" ⇒ Kategorie-lw) ?? Rückfall.
pub fn resolve_stroke_weight(override_: Option<f64>, source: Option<AttributeSource>, category: Option<&LayerCategory>, fallback: f64) -> f64 {
if let Some(o) = override_ {
return o;
}
if source == Some(AttributeSource::Layer) {
return category.map_or(fallback, |c| c.lw);
}
fallback
}
File diff suppressed because it is too large. Load diff
+278
View File
@@ -0,0 +1,278 @@
//! Kleine Plan-Bausteine ([K3a]): Kontext-Mesh-Fussabdruck und -Rahmen (`generatePlan/context.ts`),
//! Schnittführungs-Symbol (`sections.ts`) und Linienenden (`endMarks.ts`). Stil, Farbe, Pick-IDs und
//! Beschriftungstext setzt TS; Rechenreihenfolge und Zahlsemantik wie dort (`Math.hypot`, `Math.round`).
//!
//! ## Kontext-Mesh
//! `context_footprint(positions, indices)` → `[n, ax, ay, bx, by …]` (Sockelkanten, entdoppelt).
//! `bbox(positions)` → `[minX, minY, maxX, maxY]` oder leer.
//!
//! ## Schnittführung
//! `section_line(p0x, p0y, p1x, p1y, vorzeichen)` → `[n, Eintrag × n]` in Zeichenreihenfolge (leer
//! bei zu kurzer Linie):
//! ```text
//! 2 line [2, art (0 Hauptlinie | 1 Marke), ax, ay, bx, by]
//! 5 label [5, x, y] (Kurz-Tag setzt TS)
//! 1 polygon [1, x0, y0 … x3, y3] (unsichtbares Pick-Band)
//! ```
//!
//! ## Linienende
//! `end_mark(x, y, dx, dy, art, mm, massstab)` → `[verkuerzung, n, Eintrag × n]` (leer = nichts):
//! ```text
//! art 1 arrow · 2 arrowOpen · 3 dot · 4 tick · 5 square
//! 1 polygon [1, nPts, x, y …] gefüllt in Strichfarbe
//! 2 line [2, ax, ay, bx, by]
//! 4 circle [4, cx, cy, r] gefüllt in Strichfarbe
//! ```
use crate::jsmath::hypot2;
use crate::jsnum::round;
use std::collections::HashSet;
const FOOTPRINT_Z_TOL: f64 = 0.6;
const SECTION_MARK_LEN: f64 = 0.6;
const SECTION_PICK_HALF: f64 = 0.3;
const SECTION_LABEL_H: f64 = 0.5;
const ARROW_ASPECT: f64 = 0.32;
/// Ganzzahl-Schlüssel für die Quantisierung; NaN/∞ bekommen feste Platzhalter (wie ihre Textform in JS).
fn qkey(v: f64) -> i64 {
if v.is_nan() {
i64::MIN
} else if v == f64::INFINITY {
i64::MAX
} else if v == f64::NEG_INFINITY {
i64::MIN + 1
} else {
v as i64
}
}
pub fn context_footprint(positions: &[f64], indices: &[f64]) -> Vec<f64> {
let vcount = positions.len() / 3;
if vcount < 3 || indices.len() < 3 {
return Vec::new();
}
let mut min_z = f64::INFINITY;
let mut i = 2;
while i < positions.len() {
if positions[i] < min_z {
min_z = positions[i];
}
i += 3;
}
if !min_z.is_finite() {
return Vec::new();
}
let z_limit = min_z + FOOTPRINT_Z_TOL;
let q = |v: f64| round(v * 100.0);
let mut seen: HashSet<((i64, i64), (i64, i64))> = HashSet::new();
let mut lines: Vec<f64> = Vec::new();
let mut count = 0usize;
let mut edge = |ia: f64, ib: f64, lines: &mut Vec<f64>, count: &mut usize| {
// Indizes wie in TS: Zahlen ohne Prüfung auf Ganzzahligkeit; ausserhalb → Kante verwerfen
if !(ia >= 0.0 && ib >= 0.0) || ia.fract() != 0.0 || ib.fract() != 0.0 {
return;
}
let (ia, ib) = (ia as usize, ib as usize);
if ia >= vcount || ib >= vcount {
return;
}
let za = positions[ia * 3 + 2];
let zb = positions[ib * 3 + 2];
if za > z_limit || zb > z_limit {
return;
}
let (ax, ay) = (positions[ia * 3], positions[ia * 3 + 1]);
let (bx, by) = (positions[ib * 3], positions[ib * 3 + 1]);
let ka = (qkey(q(ax)), qkey(q(ay)));
let kb = (qkey(q(bx)), qkey(q(by)));
if ka == kb {
return;
}
let key = if ka < kb { (ka, kb) } else { (kb, ka) };
if !seen.insert(key) {
return;
}
lines.extend([ax, ay, bx, by]);
*count += 1;
};
let mut k = 0;
while k + 2 < indices.len() {
let (a, b, c) = (indices[k], indices[k + 1], indices[k + 2]);
edge(a, b, &mut lines, &mut count);
edge(b, c, &mut lines, &mut count);
edge(c, a, &mut lines, &mut count);
k += 3;
}
let mut out = vec![count as f64];
out.extend(lines);
out
}
pub fn bbox(positions: &[f64]) -> Vec<f64> {
let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
let mut i = 0;
while i + 2 < positions.len() {
let (x, y) = (positions[i], positions[i + 1]);
if x < min_x {
min_x = x;
}
if x > max_x {
max_x = x;
}
if y < min_y {
min_y = y;
}
if y > max_y {
max_y = y;
}
i += 3;
}
if !min_x.is_finite() {
return Vec::new();
}
vec![min_x, min_y, max_x, max_y]
}
pub fn section_line(p0x: f64, p0y: f64, p1x: f64, p1y: f64, sign: f64) -> Vec<f64> {
if ![p0x, p0y, p1x, p1y, sign].iter().all(|x| x.is_finite()) {
return Vec::new();
}
let (ax, ay) = (p1x - p0x, p1y - p0y);
let len = hypot2(ax, ay);
if len < 1e-6 {
return Vec::new();
}
let (ux, uy) = (ax / len, ay / len);
let (nx, ny) = (-uy, ux);
let (bnx, bny) = (nx * sign, ny * sign);
let mut o: Vec<f64> = Vec::new();
let mut n = 0usize;
let line = |o: &mut Vec<f64>, n: &mut usize, art: f64, a: (f64, f64), b: (f64, f64)| {
o.extend([2.0, art, a.0, a.1, b.0, b.1]);
*n += 1;
};
line(&mut o, &mut n, 0.0, (p0x, p0y), (p1x, p1y));
let half = SECTION_MARK_LEN / 2.0;
for end in [(p0x, p0y), (p1x, p1y)] {
line(&mut o, &mut n, 1.0, (end.0 - nx * half, end.1 - ny * half), (end.0 + nx * half, end.1 + ny * half));
let base = (end.0 + bnx * half, end.1 + bny * half);
let tip = (base.0 + bnx * SECTION_MARK_LEN, base.1 + bny * SECTION_MARK_LEN);
let wing_back = (tip.0 - bnx * SECTION_MARK_LEN * 0.4, tip.1 - bny * SECTION_MARK_LEN * 0.4);
let w = SECTION_MARK_LEN * 0.25;
line(&mut o, &mut n, 1.0, base, tip);
line(&mut o, &mut n, 1.0, tip, (wing_back.0 + ux * w, wing_back.1 + uy * w));
line(&mut o, &mut n, 1.0, tip, (wing_back.0 - ux * w, wing_back.1 - uy * w));
let lx = tip.0 + bnx * SECTION_MARK_LEN * 0.4 - SECTION_LABEL_H * 0.3;
let ly = tip.1 + bny * SECTION_MARK_LEN * 0.4 + SECTION_LABEL_H * 0.5;
o.extend([5.0, lx, ly]);
n += 1;
}
let (ox, oy) = (nx * SECTION_PICK_HALF, ny * SECTION_PICK_HALF);
o.push(1.0);
o.extend([p0x + ox, p0y + oy, p1x + ox, p1y + oy, p1x - ox, p1y - oy, p0x - ox, p0y - oy]);
n += 1;
let mut out = vec![n as f64];
out.extend(o);
out
}
pub fn end_mark(x: f64, y: f64, dx: f64, dy: f64, art: f64, mm: f64, scale_denominator: f64) -> Vec<f64> {
if ![x, y, dx, dy, mm, scale_denominator].iter().all(|v| v.is_finite()) {
return Vec::new();
}
let len = hypot2(dx, dy);
if len < 1e-9 {
return Vec::new();
}
let size = (mm / 1000.0) * scale_denominator;
let (ux, uy) = (dx / len, dy / len);
let (nx, ny) = (-uy, ux);
let base = (x - ux * size, y - uy * size);
let half = size * ARROW_ASPECT;
let wing_a = (base.0 + nx * half, base.1 + ny * half);
let wing_b = (base.0 - nx * half, base.1 - ny * half);
let at = (x, y);
let mut o: Vec<f64> = Vec::new();
let mut n = 0usize;
let mut shorten = 0.0;
let line = |o: &mut Vec<f64>, n: &mut usize, a: (f64, f64), b: (f64, f64)| {
o.extend([2.0, a.0, a.1, b.0, b.1]);
*n += 1;
};
match art as i64 {
1 => {
o.extend([1.0, 3.0, at.0, at.1, wing_a.0, wing_a.1, wing_b.0, wing_b.1]);
n += 1;
shorten = size;
}
2 => {
line(&mut o, &mut n, wing_a, at);
line(&mut o, &mut n, wing_b, at);
}
3 => {
o.extend([4.0, x, y, size * 0.25]);
n += 1;
}
4 => {
let tx = (ux + nx) / std::f64::consts::SQRT_2;
let ty = (uy + ny) / std::f64::consts::SQRT_2;
let h = size / 2.0;
line(&mut o, &mut n, (x - tx * h, y - ty * h), (x + tx * h, y + ty * h));
}
5 => {
let h = size * 0.3;
o.extend([
1.0, 4.0,
x + (ux + nx) * h, y + (uy + ny) * h,
x + (ux - nx) * h, y + (uy - ny) * h,
x + (-ux - nx) * h, y + (-uy - ny) * h,
x + (-ux + nx) * h, y + (-uy + ny) * h,
]);
n += 1;
}
_ => return Vec::new(),
}
let mut out = vec![shorten, n as f64];
out.extend(o);
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sockelkanten_werden_entdoppelt() {
// zwei Dreiecke mit gemeinsamer Kante, alle auf z=0; ein Punkt hoch → Kanten dorthin entfallen
let pos = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 9.0];
let idx = [0.0, 1.0, 2.0, 0.0, 2.0, 3.0, 0.0, 1.0, 4.0];
let f = context_footprint(&pos, &idx);
assert_eq!(f[0], 5.0); // 4 Aussenkanten + Diagonale
assert_eq!(f.len(), 1 + 5 * 4);
}
#[test]
fn unsinn_ohne_panic() {
assert!(context_footprint(&[0.0, 1.0], &[0.0]).is_empty());
assert!(bbox(&[]).is_empty());
assert!(section_line(0.0, 0.0, 0.0, 0.0, 1.0).is_empty());
assert!(section_line(f64::NAN, 0.0, 1.0, 0.0, 1.0).is_empty());
assert!(end_mark(0.0, 0.0, 0.0, 0.0, 1.0, 3.0, 100.0).is_empty());
assert!(end_mark(0.0, 0.0, 1.0, 0.0, 99.0, 3.0, 100.0).is_empty());
}
#[test]
fn schnittlinie_hat_hauptlinie_marken_label_und_pickband() {
let f = section_line(0.0, 0.0, 4.0, 0.0, 1.0);
// 1 Hauptlinie + 2 × (Querstrich + 3 Pfeillinien + Label) + Pick = 12
assert_eq!(f[0], 12.0);
}
#[test]
fn gefuellter_pfeil_verkuerzt_die_linie() {
let a = end_mark(0.0, 0.0, 1.0, 0.0, 1.0, 3.0, 100.0);
assert!((a[0] - 0.3).abs() < 1e-12);
assert_eq!(end_mark(0.0, 0.0, 1.0, 0.0, 2.0, 3.0, 100.0)[0], 0.0);
}
}
+446
View File
@@ -0,0 +1,446 @@
//! Öffnungs-Symbol (Tür/Fenster) im Grundriss ([K3a]): Port von `generatePlan/openings.ts`
//! (`addOpeningSymbol`, `addOpeningFrameBand`). Geometrie aus `opening_geom.rs`. Stil löst TS aus dem
//! Modell: Strichstärken kommen als Zahlen herein, Farben als Platz (Slot) heraus (0 = keine,
//! 1 Strichfarbe, 2 Rahmen, 3 Rahmen-Aufsicht, 4 Flügel/Sprossen, 5 Fensterbank-/Sims-Linie).
//!
//! Eingabe (`f64`): `[sx, sy, ex, ey, dicke, refOff, position, breite, art (0 Fenster | 1 Tür),
//! detail (0 grob | 1 mittel | 2 fein),
//! Tür: schwenkRechts, ausen, anschlagEnde, schwenkwinkel (NaN = 90), wandoeffnung, fluegel,
//! sturz (0 keine | 1 aussen | 2 innen | 3 beide),
//! Rahmen: hat, breite, art (0 Zarge | 1 Blockrahmen), einzug, einzugInnen,
//! Fenster: hatTyp, profilbreite, rahmentiefe (NaN), einzug (NaN), einzugInnen, altFluegel (NaN = 1),
//! glasAlt, sims (0 keine | 1 aussen | 2 innen | 3 beide), simsUnter (0|1), kasten (0|1),
//! kastenBreite, kastenHoehe,
//! Stärken: haar, rahmenHaar, rahmenAufsicht, fluegel, sims,
//! nFluegel, (pfosten, auto, breite, pfostenbreite, oeffenbar) × n]`.
//!
//! Ausgabe `[n, Eintrag × n]` in Zeichenreihenfolge:
//! ```text
//! 1 polygon [1, art (0 Pick-Fläche | 1 Rahmen-Aufsicht), weightMm, farbSlot, nPts, x, y …]
//! 2 line [2, cls, weightMm, farbSlot, strich, ax, ay, bx, by]
//! 3 arc [3, weightMm, cx, cy, fromX, fromY, toX, toY, r] (cls door-swing)
//! cls 0 door-leaf · 1 door-frame · 2 door-lintel · 3 opening-frame · 4 window-glass ·
//! 5 window-mullion · 6 window-sash · 7 window-stulp · 8 window-sill · 9 window-frame ·
//! 10 window-shading
//! strich 0 keiner (Schlüssel fehlt) · 1 Sturz [0.18, 0.09] · 2 Überkopf · 3 gepunktet [0.04, 0.08]
//! ```
use crate::jsmath::hypot2;
use crate::jsnum::{max, min, round};
use crate::opening_geom::*;
use crate::flat_read::Reader;
struct Out {
buf: Vec<f64>,
n: usize,
}
const C_LEAF: f64 = 0.0;
const C_DOOR_FRAME: f64 = 1.0;
const C_LINTEL: f64 = 2.0;
const C_OPENING_FRAME: f64 = 3.0;
const C_GLASS: f64 = 4.0;
const C_MULLION: f64 = 5.0;
const C_SASH: f64 = 6.0;
const C_STULP: f64 = 7.0;
const C_SILL: f64 = 8.0;
const C_WINDOW_FRAME: f64 = 9.0;
const C_SHADING: f64 = 10.0;
impl Out {
fn polygon(&mut self, art: f64, weight: f64, color: f64, pts: &[V]) {
self.n += 1;
self.buf.extend([1.0, art, weight, color, pts.len() as f64]);
for p in pts {
self.buf.extend([p.x, p.y]);
}
}
fn line(&mut self, cls: f64, weight: f64, color: f64, dash: f64, a: V, b: V) {
self.n += 1;
self.buf.extend([2.0, cls, weight, color, dash, a.x, a.y, b.x, b.y]);
}
fn arc(&mut self, weight: f64, c: V, from: V, to: V, r: f64) {
self.n += 1;
self.buf.extend([3.0, weight, c.x, c.y, from.x, from.y, to.x, to.y, r]);
}
/// Geschlossener Linienzug aus Eckpunkten (Kante i → i+1, zuletzt → 0).
fn ring(&mut self, cls: f64, weight: f64, color: f64, pts: &[V]) {
for i in 0..pts.len() {
self.line(cls, weight, color, 0.0, pts[i], pts[(i + 1) % pts.len()]);
}
}
}
pub fn plan_opening(buf: &[f64]) -> Vec<f64> {
plan_opening_inner(buf).unwrap_or_default()
}
fn plan_opening_inner(buf: &[f64]) -> Option<Vec<f64>> {
let mut r = Reader::new(buf);
let (sx, sy, ex, ey, total, ref_off) = (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?);
let (position, width) = (r.num()?, r.num()?);
let is_door = r.num()? != 0.0;
let detail = match r.num()? as i64 {
0 => Detail::Grob,
1 => Detail::Mittel,
_ => Detail::Fein,
};
let door = DoorParams { swing_right: r.num()? != 0.0, open_out: r.num()? != 0.0, hinge_end: r.num()? != 0.0, swing_angle: 0.0 };
let swing_angle = r.num()?;
let door = DoorParams { swing_angle: if swing_angle.is_nan() { 90.0 } else { swing_angle }, ..door };
let wandoeffnung = r.num()? != 0.0;
let leaf_count = r.num()?;
let lintel = r.num()? as i64;
let has_frame = r.num()? != 0.0;
let frame_width = r.num()?;
let frame_block = r.num()? != 0.0;
let frame_inset = r.num()?;
let frame_inset_inner = r.num()? != 0.0;
let has_type = r.num()? != 0.0;
let win_frame_width = r.num()?;
let win_frame_depth = r.num()?;
let win_inset = r.num()?;
let win_inset_inner = r.num()? != 0.0;
let wing_count = r.num()?;
let glass_alt = r.num()?;
let sill_faces = r.num()? as i64;
let sill_under = r.num()? != 0.0;
let shading = r.num()? != 0.0;
let shading_width = r.num()?;
let shading_height = r.num()?;
let (hair, frame_hair, frame_view_w, sash_w, sill_w) = (r.num()?, r.num()?, r.num()?, r.num()?, r.num()?);
let n_sash = r.count()?;
let mut sashes = Vec::with_capacity(n_sash);
for _ in 0..n_sash {
sashes.push(Sash {
post: r.num()? != 0.0,
auto_width: r.num()? != 0.0,
width: r.num()?,
post_width: r.num()?,
operable: r.num()? != 0.0,
});
}
if ![sx, sy, ex, ey, total, ref_off, position, width].iter().all(|x| x.is_finite()) {
return None;
}
let w = WallRef { start: v(sx, sy), end: v(ex, ey), total, ref_off };
let (_, wn) = w.frame();
let mut o = Out { buf: Vec::new(), n: 0 };
if is_door {
let (jamb_start, jamb_end) = opening_jambs(&w, position, width)?;
if let Some(gap) = opening_gap_quad(&w, position, width) {
o.polygon(0.0, 0.0, 0.0, &gap);
}
if !wandoeffnung {
let count = max(1.0, round(if leaf_count.is_nan() { 1.0 } else { leaf_count }));
for leaf in door_leaves(&w, position, width, &door, count) {
o.line(C_LEAF, hair, 0.0, 0.0, leaf.hinge, leaf.open_end);
if detail != Detail::Grob {
o.arc(hair, leaf.hinge, leaf.closed_end, leaf.open_end, leaf.radius);
}
}
}
if detail == Detail::Fein {
let reveal = 0.06;
for jamb in [jamb_start, jamb_end] {
o.line(C_DOOR_FRAME, hair, 0.0, 0.0, add(jamb, scale(wn, reveal)), add(jamb, scale(wn, -reveal)));
}
}
if has_frame {
frame_band(&mut o, &w, position, width, frame_width, frame_block, frame_inset, frame_inset_inner, hair);
}
if lintel != 0 {
let half_d = total / 2.0;
let outer_off = ref_off - half_d;
let inner_off = ref_off + half_d;
let line = |off: f64| (add(jamb_start, scale(wn, off)), add(jamb_end, scale(wn, off)));
if lintel == 1 || lintel == 3 {
let (a, b) = line(outer_off);
o.line(C_LINTEL, hair, 1.0, 1.0, a, b);
}
if lintel == 2 || lintel == 3 {
let (a, b) = line(inner_off);
o.line(C_LINTEL, hair, 1.0, 1.0, a, b);
}
}
return Some(finish(o));
}
// Fenster
let spec = if has_type {
Some(WindowSpec {
sashes,
frame_width: win_frame_width,
frame_depth: win_frame_depth,
inset_from_face: win_inset,
inset_inner: win_inset_inner,
})
} else {
None
};
let sym = window_symbol(&w, position, width, glass_alt, spec.as_ref(), wing_count, detail)?;
if let Some(gap) = opening_gap_quad(&w, position, width) {
o.polygon(0.0, 0.0, 0.0, &gap);
}
if detail == Detail::Grob {
let idx = sym.glass_lines.len() / 2;
if let Some(g) = sym.glass_lines.get(idx).or_else(|| sym.glass_lines.first()) {
o.line(C_GLASS, sash_w, 4.0, 0.0, g.0, g.1);
}
} else {
o.polygon(1.0, frame_view_w, 3.0, &sym.frame);
for (a, b) in &sym.mullion_lines {
o.line(C_MULLION, sash_w, 4.0, 0.0, *a, *b);
}
if detail == Detail::Fein {
for pts in &sym.sash_frames {
o.ring(C_SASH, sash_w, 4.0, pts);
}
}
for mark in &sym.jamb_marks {
o.ring(C_STULP, frame_hair, 2.0, mark);
}
for mark in &sym.meeting_marks {
o.ring(C_STULP, sash_w, 4.0, mark);
}
for (a, b) in &sym.glass_lines {
o.line(C_GLASS, hair, 0.0, 0.0, *a, *b);
}
if detail == Detail::Fein {
if let Some((js, je)) = opening_jambs(&w, position, width) {
let outer_n = min(dot(sub(sym.frame[0], js), wn), dot(sub(sym.frame[2], js), wn));
let (ov, proj) = (0.03, 0.04);
let s0 = along(js, je, -ov);
let s1 = along(je, js, -ov);
let b0 = add(s0, scale(wn, outer_n));
let b1 = add(s1, scale(wn, outer_n));
let b2 = add(s1, scale(wn, outer_n - proj));
let b3 = add(s0, scale(wn, outer_n - proj));
for (a, b) in [(b0, b1), (b1, b2), (b2, b3), (b3, b0)] {
o.line(C_SILL, hair, 1.0, 0.0, a, b);
}
let reveal = 0.06;
for jamb in [js, je] {
o.line(C_WINDOW_FRAME, hair, 1.0, 0.0, add(jamb, scale(wn, reveal)), add(jamb, scale(wn, -reveal)));
}
}
}
}
if detail != Detail::Grob && sill_faces != 0 {
let dash = if sill_under { 2.0 } else { 3.0 };
let pair01_is_outer = dot(sym.frame[0], wn) <= dot(sym.frame[3], wn);
let (outer_pair, inner_pair) = if pair01_is_outer {
((sym.frame[0], sym.frame[1]), (sym.frame[3], sym.frame[2]))
} else {
((sym.frame[3], sym.frame[2]), (sym.frame[0], sym.frame[1]))
};
if sill_faces == 1 || sill_faces == 3 {
o.line(C_SILL, sill_w, 5.0, dash, outer_pair.0, outer_pair.1);
}
if sill_faces == 2 || sill_faces == 3 {
o.line(C_SILL, sill_w, 5.0, dash, inner_pair.0, inner_pair.1);
}
}
if shading {
if let Some((js, je)) = opening_jambs(&w, position, width) {
let (u, nrm) = w.frame();
let outer_face = ref_off - total / 2.0;
let axis_width = hypot2(je.x - js.x, je.y - js.y);
let box_width = if shading_width > 0.0 { shading_width } else { axis_width };
let box_height = max(0.0, shading_height);
let center = add(js, scale(u, axis_width / 2.0));
let half = box_width / 2.0;
let c1 = add(center, scale(u, -half));
let c2 = add(center, scale(u, half));
let p1 = add(c1, scale(nrm, outer_face));
let p2 = add(c2, scale(nrm, outer_face));
let p3 = add(c2, scale(nrm, outer_face + box_height));
let p4 = add(c1, scale(nrm, outer_face + box_height));
for (a, b) in [(p1, p2), (p2, p3), (p3, p4), (p4, p1)] {
o.line(C_SHADING, hair, 1.0, 2.0, a, b);
}
}
}
Some(finish(o))
}
fn finish(o: Out) -> Vec<f64> {
let mut out = Vec::with_capacity(o.buf.len() + 1);
out.push(o.n as f64);
out.extend(o.buf);
out
}
/// Rahmenband einer Tür (Zarge/Blockrahmen) aus dem Typ der Tür.
#[allow(clippy::too_many_arguments)]
fn frame_band(o: &mut Out, w: &WallRef, position: f64, width: f64, frame_width: f64, block: bool, inset_from_face: f64, inset_inner: bool, hair: f64) {
let Some((js, je)) = opening_jambs(w, position, width) else { return };
let n = w.frame().1;
let total = w.total;
let outer_face = w.ref_off - total / 2.0;
let inner_face = w.ref_off + total / 2.0;
let clamped_inset = max(0.0, min(inset_from_face, total));
let near_is_aussen = !inset_inner;
let face_near = if near_is_aussen { outer_face + clamped_inset } else { inner_face - clamped_inset };
let face_far = if near_is_aussen { inner_face } else { outer_face };
let lo = min(face_near, face_far);
let hi = max(face_near, face_far);
let fw = max(0.0, frame_width);
let (band_lo, band_hi, j_start, j_end, weight);
if block {
let depth = min(fw, hi - lo);
band_lo = if near_is_aussen { lo } else { hi - depth };
band_hi = if near_is_aussen { lo + depth } else { hi };
j_start = js;
j_end = je;
weight = hair * 2.2;
} else {
let jamb_span = hypot2(je.x - js.x, je.y - js.y);
let jamb_inset = min(fw, jamb_span / 2.0);
j_start = along(js, je, jamb_inset);
j_end = along(je, js, jamb_inset);
let depth_inset = min(fw, (hi - lo) / 2.0);
band_lo = lo + depth_inset;
band_hi = hi - depth_inset;
weight = hair;
}
let p1 = add(j_start, scale(n, band_lo));
let p2 = add(j_end, scale(n, band_lo));
let p3 = add(j_end, scale(n, band_hi));
let p4 = add(j_start, scale(n, band_hi));
for (a, b) in [(p1, p2), (p2, p3), (p3, p4), (p4, p1)] {
o.line(C_OPENING_FRAME, weight, 1.0, 0.0, a, b);
}
}
// ── Fenster-Symbol als Einzelaufruf (für die Fassade `windowSymbol`, z. B. im Schnitt) ──────────
/// Eingabe `[sx, sy, ex, ey, dicke, refOff, position, breite, glasAnzahl, altFluegel (NaN = 1),
/// detail, hatTyp, profilbreite, rahmentiefe (NaN), einzug (NaN), einzugInnen, nFluegel,
/// (pfosten, auto, breite, pfostenbreite, oeffenbar) × n]`; Ausgabe
/// `[1, Rahmen(4 Punkte), nGlas, 4 Zahlen × n, nPfosten, 4 × n, nFluegelRahmen, (nPts, pts…) × n,
/// nStoss, (nPts, pts…) × n, nLaibung, (nPts, pts…) × n]` oder leer.
pub fn window_symbol_flat(buf: &[f64]) -> Vec<f64> {
(|| {
let mut r = Reader::new(buf);
let (sx, sy, ex, ey, total, ref_off, position, width) =
(r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?);
let glass = r.num()?;
let wings = r.num()?;
let detail = match r.num()? as i64 {
0 => Detail::Grob,
1 => Detail::Mittel,
_ => Detail::Fein,
};
let has_type = r.num()? != 0.0;
let (fw, fd, inset) = (r.num()?, r.num()?, r.num()?);
let inner = r.num()? != 0.0;
let n = r.count()?;
let mut sashes = Vec::with_capacity(n);
for _ in 0..n {
sashes.push(Sash { post: r.num()? != 0.0, auto_width: r.num()? != 0.0, width: r.num()?, post_width: r.num()?, operable: r.num()? != 0.0 });
}
if ![sx, sy, ex, ey, total, ref_off, position, width].iter().all(|x| x.is_finite()) {
return None;
}
let w = WallRef { start: v(sx, sy), end: v(ex, ey), total, ref_off };
let spec = if has_type { Some(WindowSpec { sashes, frame_width: fw, frame_depth: fd, inset_from_face: inset, inset_inner: inner }) } else { None };
let s = window_symbol(&w, position, width, glass, spec.as_ref(), wings, detail)?;
let mut out = vec![1.0];
for p in &s.frame {
out.extend([p.x, p.y]);
}
for list in [&s.glass_lines, &s.mullion_lines] {
out.push(list.len() as f64);
for (a, b) in list.iter() {
out.extend([a.x, a.y, b.x, b.y]);
}
}
for rings in [&s.sash_frames, &s.meeting_marks, &s.jamb_marks] {
out.push(rings.len() as f64);
for pts in rings.iter() {
out.push(pts.len() as f64);
for p in pts {
out.extend([p.x, p.y]);
}
}
}
Some(out)
})()
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
const NAN: f64 = f64::NAN;
/// Wand 0..6 m entlang x, Dicke 0.3, Öffnung ab 1.0 m, 0.9 m breit.
fn input(door: bool, detail: f64, has_type: bool, sashes: &[[f64; 5]]) -> Vec<f64> {
let mut b = vec![0.0, 0.0, 6.0, 0.0, 0.3, 0.0, 1.0, 0.9, door as u8 as f64, detail];
b.extend([0.0, 0.0, 0.0, NAN, 0.0, 1.0, 3.0]); // Tür: links, innen, Start, 90°, normal, 1 Blatt, Sturz beide
b.extend([0.0, 0.06, 0.0, 0.0, 0.0]); // kein Rahmenband
b.extend([has_type as u8 as f64, 0.06, NAN, NAN, 0.0, NAN, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]); // Fenster
b.extend([0.02, 0.02, 0.02, 0.02, 0.02]); // Strichstärken
b.push(sashes.len() as f64);
for s in sashes {
b.extend(s);
}
b
}
fn tags(buf: &[f64]) -> Vec<f64> {
let (mut i, mut t) = (1, Vec::new());
for _ in 0..buf[0] as usize {
t.push(buf[i]);
i += match buf[i] as i64 {
1 => 5 + 2 * buf[i + 4] as usize,
2 => 9,
_ => 9,
};
}
assert_eq!(i, buf.len());
t
}
#[test]
fn tuer_grob_hat_pick_blatt_und_zwei_sturzlinien() {
let t = tags(&plan_opening(&input(true, 0.0, false, &[])));
assert_eq!(t, vec![1.0, 2.0, 2.0, 2.0]);
}
#[test]
fn tuer_fein_hat_bogen_und_anschlagstriche() {
let t = tags(&plan_opening(&input(true, 2.0, false, &[])));
assert_eq!(t.iter().filter(|x| **x == 3.0).count(), 1);
assert_eq!(t.len(), 1 + 1 + 1 + 2 + 2);
}
#[test]
fn fenster_grob_hat_eine_glaslinie() {
let t = tags(&plan_opening(&input(false, 0.0, false, &[])));
assert_eq!(t, vec![1.0, 2.0]);
}
#[test]
fn entartete_oeffnung_und_unsinn_ergeben_leeres_ergebnis() {
let mut b = input(false, 1.0, false, &[]);
b[7] = 0.0;
assert!(plan_opening(&b).is_empty());
assert!(plan_opening(&[1.0]).is_empty());
let mut c = input(true, 1.0, false, &[]);
c[0] = f64::NAN;
assert!(plan_opening(&c).is_empty());
assert!(window_symbol_flat(&[]).is_empty());
}
#[test]
fn typisiertes_fenster_fein_hat_fluegelrahmen() {
let sashes = [[0.0, 1.0, NAN, NAN, 1.0], [0.0, 1.0, NAN, NAN, 1.0]];
let a = plan_opening(&input(false, 2.0, true, &sashes));
let g = plan_opening(&input(false, 1.0, true, &sashes));
assert!(a[0] > g[0]);
}
}
+499
View File
@@ -0,0 +1,499 @@
//! Schnitt-Bänder ([K3c]): Dominanz-Subtraktion und Verschmelzung achsparalleler Schnitt-Rechtecke
//! (`toSection.ts`: `subtractDominantBands`, `mergeSameComponentBands`) sowie die Vereinigung zu
//! Aussenringen (`unionRectOutlines`). Stil, Füllung, Schraffur und Herkunft hängen in TS an den
//! Bändern; Rust rechnet nur auf Rechtecken. Rechenreihenfolge wie in TS.
//!
//! ## Dominanz
//! `dominant_bands(in)` mit `in = [n, Band × n]`, Band = `[gueltig, uMin, uMax, vMin, vMax, prio, comp]`
//! (`gueltig` 0 = weniger als 3 Ecken; `prio` NaN = keine; `comp` < 0 = keine Komponente) →
//! `[m, Eintrag × m]`, Eintrag = `[quelle, istRechteck, uMin, uMax, vMin, vMax]`. `istRechteck` 0 =
//! Quellband unverändert übernehmen, sonst neues Rechteck mit Stil von `quelle`.
//!
//! ## Dach-Schnittspur
//! `roof_segments(base_x, base_y, u_x, u_y, planes)` mit `planes = [n, (k, x, y, z …) × n]` (Modell
//! [x, y, Höhe], konvexe Aufsicht-Polygone) → `[m, (tLo, tHi, zOben0, zOben1, cosNeigung) × m]`: die
//! Spur der senkrechten Schnittebene (Gerade `base + t·u`) je Dachfläche, nach `tLo` sortiert und
//! gleich geneigte, anstossende Teile verschmolzen (`appendRoofSections`).
//!
//! ## Umrisse
//! `union_outlines(in)` mit `in = [n, (uMin, uMax, vMin, vMax) × n]` → `[r, (k, x, y × k) × r]`.
use crate::jsnum::{max, min};
use std::collections::HashMap;
const RECT_EPS: f64 = 1e-6;
#[derive(Clone, Copy)]
struct Rect {
u_min: f64,
u_max: f64,
v_min: f64,
v_max: f64,
}
#[derive(Clone, Copy)]
struct Band {
rect: Option<Rect>,
prio: Option<f64>,
comp: Option<i64>,
}
struct Out {
src: usize,
rect: Option<Rect>,
}
fn subtract_rect(base: Rect, cutter: Rect) -> Vec<Rect> {
let o_min_u = max(base.u_min, cutter.u_min);
let o_max_u = min(base.u_max, cutter.u_max);
let o_min_v = max(base.v_min, cutter.v_min);
let o_max_v = min(base.v_max, cutter.v_max);
if o_max_u - o_min_u <= RECT_EPS || o_max_v - o_min_v <= RECT_EPS {
return vec![base];
}
let mut out = Vec::new();
let mut push = |r: Rect| {
if r.u_max - r.u_min > RECT_EPS && r.v_max - r.v_min > RECT_EPS {
out.push(r);
}
};
push(Rect { u_min: base.u_min, u_max: o_min_u, v_min: base.v_min, v_max: base.v_max });
push(Rect { u_min: o_max_u, u_max: base.u_max, v_min: base.v_min, v_max: base.v_max });
push(Rect { u_min: o_min_u, u_max: o_max_u, v_min: base.v_min, v_max: o_min_v });
push(Rect { u_min: o_min_u, u_max: o_max_u, v_min: o_max_v, v_max: base.v_max });
out
}
fn rect_union_if_rect(a: Rect, b: Rect) -> Option<Rect> {
let e = RECT_EPS;
let a_in_b = b.u_min - a.u_min <= e && a.u_max - b.u_max <= e && b.v_min - a.v_min <= e && a.v_max - b.v_max <= e;
if a_in_b {
return Some(b);
}
let b_in_a = a.u_min - b.u_min <= e && b.u_max - a.u_max <= e && a.v_min - b.v_min <= e && b.v_max - a.v_max <= e;
if b_in_a {
return Some(a);
}
let u_aligned = (a.u_min - b.u_min).abs() <= e && (a.u_max - b.u_max).abs() <= e;
let v_aligned = (a.v_min - b.v_min).abs() <= e && (a.v_max - b.v_max).abs() <= e;
let v_touch = a.v_max >= b.v_min - e && b.v_max >= a.v_min - e;
let u_touch = a.u_max >= b.u_min - e && b.u_max >= a.u_min - e;
if (u_aligned && v_touch) || (v_aligned && u_touch) {
return Some(Rect {
u_min: min(a.u_min, b.u_min),
u_max: max(a.u_max, b.u_max),
v_min: min(a.v_min, b.v_min),
v_max: max(a.v_max, b.v_max),
});
}
None
}
fn merge_same_component(bands: &[Band], list: Vec<Out>) -> Vec<Out> {
let mut out = list;
let mut merged = true;
while merged {
merged = false;
let mut i = 0;
while i < out.len() && !merged {
let bi = bands[out[i].src];
// Verschmolzene Rechtecke erben Komponente/Priorität des Quellbands.
if bi.comp.is_none() || bi.prio.is_none() {
i += 1;
continue;
}
let ri = match out[i].rect.or(bi.rect) {
Some(r) => r,
None => {
i += 1;
continue;
}
};
for j in i + 1..out.len() {
let bj = bands[out[j].src];
if bj.comp != bi.comp || bj.prio != bi.prio {
continue;
}
let rj = match out[j].rect.or(bj.rect) {
Some(r) => r,
None => continue,
};
if let Some(u) = rect_union_if_rect(ri, rj) {
out[i].rect = Some(u);
out.remove(j);
merged = true;
break;
}
}
i += 1;
}
}
out
}
pub fn dominant_bands(inp: &[f64]) -> Vec<f64> {
if inp.is_empty() || !inp[0].is_finite() || inp[0] < 0.0 {
return Vec::new();
}
let n = inp[0] as usize;
if inp.len() != 1 + 7 * n {
return Vec::new();
}
let bands: Vec<Band> = (0..n)
.map(|k| {
let b = &inp[1 + 7 * k..8 + 7 * k];
Band {
rect: (b[0] != 0.0).then_some(Rect { u_min: b[1], u_max: b[2], v_min: b[3], v_max: b[4] }),
prio: (!b[5].is_nan()).then_some(b[5]),
comp: (b[6] >= 0.0).then_some(b[6] as i64),
}
})
.collect();
let mut out: Vec<Out> = Vec::new();
for i in 0..n {
let (base, prio) = match (bands[i].rect, bands[i].prio) {
(Some(r), Some(p)) => (r, p),
_ => {
out.push(Out { src: i, rect: None });
continue;
}
};
let mut pieces = vec![base];
for j in 0..n {
if pieces.is_empty() {
break;
}
if j == i {
continue;
}
let (cutter, other) = match (bands[j].rect, bands[j].prio) {
(Some(c), Some(p)) => (c, p),
_ => continue,
};
if other <= prio {
continue;
}
let mut next = Vec::new();
for p in pieces {
next.extend(subtract_rect(p, cutter));
}
pieces = next;
}
for p in pieces {
out.push(Out { src: i, rect: Some(p) });
}
}
let out = merge_same_component(&bands, out);
let mut f = Vec::with_capacity(1 + 6 * out.len());
f.push(out.len() as f64);
for o in &out {
match o.rect {
Some(r) => f.extend([o.src as f64, 1.0, r.u_min, r.u_max, r.v_min, r.v_max]),
None => f.extend([o.src as f64, 0.0, 0.0, 0.0, 0.0, 0.0]),
}
}
f
}
fn signed_area(ring: &[(f64, f64)]) -> f64 {
let mut a = 0.0;
for i in 0..ring.len() {
let (x0, y0) = ring[i];
let (x1, y1) = ring[(i + 1) % ring.len()];
a += x0 * y1 - x1 * y0;
}
a / 2.0
}
fn sorted_unique(mut v: Vec<f64>) -> Vec<f64> {
v.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
v.dedup_by(|a, b| *a == *b);
v
}
pub fn union_outlines(inp: &[f64]) -> Vec<f64> {
if inp.is_empty() || !inp[0].is_finite() || inp[0] < 0.0 {
return Vec::new();
}
let n = inp[0] as usize;
if inp.len() != 1 + 4 * n || inp.iter().any(|v| !v.is_finite()) {
return Vec::new();
}
let rects: Vec<Rect> = (0..n)
.map(|k| Rect { u_min: inp[1 + 4 * k], u_max: inp[2 + 4 * k], v_min: inp[3 + 4 * k], v_max: inp[4 + 4 * k] })
.collect();
let xs = sorted_unique(rects.iter().flat_map(|r| [r.u_min, r.u_max]).collect());
let ys = sorted_unique(rects.iter().flat_map(|r| [r.v_min, r.v_max]).collect());
if xs.len() < 2 || ys.len() < 2 {
return vec![0.0];
}
let nx = xs.len() - 1;
let ny = ys.len() - 1;
let mut cell = vec![vec![false; ny]; nx];
for i in 0..nx {
for j in 0..ny {
let cx = (xs[i] + xs[i + 1]) / 2.0;
let cy = (ys[j] + ys[j + 1]) / 2.0;
cell[i][j] = rects.iter().any(|r| cx > r.u_min && cx < r.u_max && cy > r.v_min && cy < r.v_max);
}
}
let at = |i: isize, j: isize| i >= 0 && j >= 0 && (i as usize) < nx && (j as usize) < ny && cell[i as usize][j as usize];
// Gerichtete Randkanten in Einfügereihenfolge (wie `Map`: erneutes `set` behält die Position).
let mut keys: Vec<(usize, usize)> = Vec::new();
let mut next: HashMap<(usize, usize), (usize, usize)> = HashMap::new();
let mut set = |k: (usize, usize), v: (usize, usize)| {
if next.insert(k, v).is_none() {
keys.push(k);
}
};
for i in 0..nx {
for j in 0..ny {
if !cell[i][j] {
continue;
}
let (ii, jj) = (i as isize, j as isize);
if !at(ii, jj - 1) {
set((i, j), (i + 1, j));
}
if !at(ii + 1, jj) {
set((i + 1, j), (i + 1, j + 1));
}
if !at(ii, jj + 1) {
set((i + 1, j + 1), (i, j + 1));
}
if !at(ii - 1, jj) {
set((i, j + 1), (i, j));
}
}
}
let mut rings: Vec<Vec<(f64, f64)>> = Vec::new();
let mut used: std::collections::HashSet<(usize, usize)> = std::collections::HashSet::new();
for &start in &keys {
if used.contains(&start) {
continue;
}
let mut ring: Vec<(f64, f64)> = Vec::new();
let mut k = start;
while !used.contains(&k) {
used.insert(k);
ring.push((xs[k.0], ys[k.1]));
match next.get(&k) {
Some(&nk) => k = nk,
None => break,
}
}
let len = ring.len();
let simple: Vec<(f64, f64)> = ring
.iter()
.enumerate()
.filter(|(idx, p)| {
let a = ring[(idx + len - 1) % len];
let b = ring[(idx + 1) % len];
!((a.0 == p.0 && p.0 == b.0) || (a.1 == p.1 && p.1 == b.1))
})
.map(|(_, p)| *p)
.collect();
if simple.len() >= 4 && signed_area(&simple) > 0.0 {
rings.push(simple);
}
}
let mut f = vec![rings.len() as f64];
for r in &rings {
f.push(r.len() as f64);
for p in r {
f.push(p.0);
f.push(p.1);
}
}
f
}
/// Spur-Abschnitt auf einer Dachfläche.
#[derive(Clone, Copy)]
struct RoofSeg {
t_lo: f64,
t_hi: f64,
z_top0: f64,
z_top1: f64,
cos_theta: f64,
}
pub fn roof_segments(bx: f64, by: f64, ux: f64, uy: f64, planes: &[f64]) -> Vec<f64> {
if [bx, by, ux, uy].iter().any(|v| !v.is_finite()) || planes.iter().any(|v| !v.is_finite()) {
return Vec::new();
}
let Some(&n) = planes.first() else { return Vec::new() };
if n < 0.0 || n.fract() != 0.0 {
return Vec::new();
}
let mut segs: Vec<RoofSeg> = Vec::new();
let mut i = 1;
for _ in 0..n as usize {
let Some(&k) = planes.get(i) else { return Vec::new() };
if k < 0.0 || k.fract() != 0.0 || i + 1 + 3 * k as usize > planes.len() {
return Vec::new();
}
let k = k as usize;
let pts: Vec<[f64; 3]> = (0..k).map(|j| [planes[i + 1 + 3 * j], planes[i + 2 + 3 * j], planes[i + 3 + 3 * j]]).collect();
i += 1 + 3 * k;
if k < 3 {
continue;
}
let (mut a, mut b, mut c) = (0.0, 0.0, 0.0);
for q in 0..k {
let cc = pts[q];
let d = pts[(q + 1) % k];
a += (cc[1] - d[1]) * (cc[2] + d[2]);
b += (cc[2] - d[2]) * (cc[0] + d[0]);
c += (cc[0] - d[0]) * (cc[1] + d[1]);
}
if c.abs() < 1e-9 {
continue;
}
let n_len = crate::jsmath::hypot(&[a, b, c]);
let cos_theta = c.abs() / if n_len == 0.0 || n_len.is_nan() { 1.0 } else { n_len };
let z_at = |x: f64, y: f64| -> f64 { pts[0][2] - (a * (x - pts[0][0]) + b * (y - pts[0][1])) / c };
let (mut cx, mut cy) = (0.0, 0.0);
for p in &pts {
cx += p[0];
cy += p[1];
}
cx /= k as f64;
cy /= k as f64;
let (mut t_lo, mut t_hi) = (f64::NEG_INFINITY, f64::INFINITY);
let mut outside = false;
let mut q = 0;
while q < k && !outside {
let pa = pts[q];
let pb = pts[(q + 1) % k];
let mut ex = -(pb[1] - pa[1]);
let mut ey = pb[0] - pa[0];
if ex * (cx - pa[0]) + ey * (cy - pa[1]) < 0.0 {
ex = -ex;
ey = -ey;
}
let denom = ex * ux + ey * uy;
let dist = ex * (bx - pa[0]) + ey * (by - pa[1]);
q += 1;
if denom.abs() < 1e-12 {
if dist < -1e-9 {
outside = true;
}
continue;
}
let t = -dist / denom;
if denom > 0.0 {
t_lo = max(t_lo, t);
} else {
t_hi = min(t_hi, t);
}
}
if outside || t_hi - t_lo <= 1e-6 {
continue;
}
let (x0, y0) = (bx + t_lo * ux, by + t_lo * uy);
let (x1, y1) = (bx + t_hi * ux, by + t_hi * uy);
segs.push(RoofSeg { t_lo, t_hi, z_top0: z_at(x0, y0), z_top1: z_at(x1, y1), cos_theta });
}
if i != planes.len() {
return Vec::new();
}
segs.sort_by(|p, q| (p.t_lo - q.t_lo).partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal));
let slope = |x: &RoofSeg| (x.z_top1 - x.z_top0) / max(x.t_hi - x.t_lo, 1e-12);
let line_z = |x: &RoofSeg, t: f64| x.z_top0 + slope(x) * (t - x.t_lo);
let mut merged: Vec<RoofSeg> = Vec::new();
for sg in segs {
if let Some(last) = merged.last_mut() {
if sg.t_lo <= last.t_hi + 1e-6
&& (line_z(last, sg.t_lo) - sg.z_top0).abs() < 1e-6
&& (slope(&sg) - slope(last)).abs() < 1e-6
&& (sg.cos_theta - last.cos_theta).abs() < 1e-6
{
let hi = max(last.t_hi, sg.t_hi);
let z1 = line_z(last, hi);
last.z_top1 = z1;
last.t_hi = hi;
continue;
}
}
merged.push(sg);
}
let mut f = vec![merged.len() as f64];
for m in &merged {
f.extend([m.t_lo, m.t_hi, m.z_top0, m.z_top1, m.cos_theta]);
}
f
}
#[cfg(test)]
mod tests {
use super::*;
fn band(u0: f64, u1: f64, v0: f64, v1: f64, prio: f64, comp: f64) -> [f64; 7] {
[1.0, u0, u1, v0, v1, prio, comp]
}
#[test]
fn hoehere_prioritaet_schneidet_weg() {
let mut inp = vec![2.0];
inp.extend(band(0.0, 1.0, 0.0, 1.0, 10.0, 0.0));
inp.extend(band(0.0, 1.0, 0.5, 1.0, 100.0, 1.0));
let f = dominant_bands(&inp);
// Basis behält die untere Hälfte, Cutter bleibt ganz.
assert_eq!(f[0], 2.0);
assert_eq!(&f[1..7], &[0.0, 1.0, 0.0, 1.0, 0.0, 0.5]);
}
fn r(u0: f64, u1: f64, v0: f64, v1: f64) -> Rect {
Rect { u_min: u0, u_max: u1, v_min: v0, v_max: v1 }
}
#[test]
fn rechteck_subtraktion() {
// Kein Überlapp, nur Berührung, volle Überdeckung, Ecke, Randstreifen.
assert_eq!(subtract_rect(r(0.0, 1.0, 0.0, 1.0), r(2.0, 3.0, 2.0, 3.0)).len(), 1);
assert_eq!(subtract_rect(r(0.0, 1.0, 0.0, 1.0), r(1.0, 2.0, 0.0, 1.0)).len(), 1);
assert!(subtract_rect(r(1.0, 2.0, 1.0, 2.0), r(0.0, 3.0, 0.0, 3.0)).is_empty());
let ecke = subtract_rect(r(0.0, 2.0, 0.0, 2.0), r(1.0, 3.0, 1.0, 3.0));
let flaeche: f64 = ecke.iter().map(|x| (x.u_max - x.u_min) * (x.v_max - x.v_min)).sum();
assert_eq!((ecke.len(), flaeche), (2, 3.0));
let rand = subtract_rect(r(0.0, 2.0, 0.0, 2.0), r(-1.0, 3.0, 1.0, 3.0));
assert_eq!(rand.len(), 1);
assert_eq!((rand[0].v_min, rand[0].v_max), (0.0, 1.0));
}
#[test]
fn gleiche_komponente_verschmilzt() {
let mut inp = vec![2.0];
inp.extend(band(0.0, 1.0, 0.0, 1.0, 10.0, 3.0));
inp.extend(band(1.0, 2.0, 0.0, 1.0, 10.0, 3.0));
let f = dominant_bands(&inp);
assert_eq!(f[0], 1.0);
assert_eq!(&f[1..7], &[0.0, 1.0, 0.0, 2.0, 0.0, 1.0]);
}
#[test]
fn l_form_ergibt_einen_ring() {
let f = union_outlines(&[2.0, 0.0, 2.0, 0.0, 1.0, 0.0, 1.0, 0.0, 2.0]);
assert_eq!(f[0], 1.0);
assert_eq!(f[1], 6.0);
}
#[test]
fn pultdach_spur() {
// Fläche 0..4 × 0..3, Höhe steigt in x von 3 auf 4 (Neigung 1/4); Schnitt entlang x bei y = 1.
let planes = [1.0, 4.0, 0.0, 0.0, 3.0, 4.0, 0.0, 4.0, 4.0, 3.0, 4.0, 0.0, 3.0, 3.0];
let f = roof_segments(-1.0, 1.0, 1.0, 0.0, &planes);
assert_eq!(f[0], 1.0);
assert_eq!((f[1], f[2]), (1.0, 5.0));
assert!((f[3] - 3.0).abs() < 1e-12 && (f[4] - 4.0).abs() < 1e-12);
}
#[test]
fn unsinn_ist_leer() {
assert!(roof_segments(f64::NAN, 0.0, 1.0, 0.0, &[0.0]).is_empty());
assert!(dominant_bands(&[f64::NAN]).is_empty());
assert!(dominant_bands(&[2.0, 1.0]).is_empty());
assert!(union_outlines(&[1.0, f64::NAN, 1.0, 0.0, 1.0]).is_empty());
}
}
+177
View File
@@ -0,0 +1,177 @@
//! Treppen-Symbol im Grundriss ([K3a]): Tritte, Lauflinie, Pfeil, Podest, SIA-Bruchlinie und
//! Aussenlinie als flache Primitivliste. Port von `src/plan/generatePlan/stairs.ts`; die Geometrie
//! kommt aus `kernel2d` (`stair_geometry`, `stair_cut`, `stair_outline`), Farbe, Pick-ID und
//! Graustufen setzt der Aufrufer.
//!
//! Eingabe: Treppen-Parameter (16 Zahlen, s. `stair.rs`), Gesamt-Steighöhe, Schnitthöhe über der
//! Treppen-UK, Strichstärke `lw_mm` (Papier-mm), `filled_arrow` (0/1).
//!
//! Ausgabe `[n, Eintrag × n]`, Reihenfolge = Zeichenreihenfolge:
//! ```text
//! 1 polygon [1, strokeMm, gefüllt (0 = nur Umriss, 1 = Füllung in Strichfarbe), nPts, x, y …]
//! 2 line [2, cls, weightMm, gestrichelt (0|1), ax, ay, bx, by]
//! 3 arc [3, weightMm, cx, cy, fromX, fromY, toX, toY, r] (cls immer stair-outline)
//! cls 0 stair-outline · 1 stair-tread · 2 stair-break · 3 stair-run · 4 stair-arrow
//! ```
//! Gestrichelte Linien tragen das Strichmuster `[0.12, 0.08]` (Meter, `DASH`).
use crate::jsnum;
use crate::stair::decode_params;
use kernel2d::{stair_cut, stair_geometry, stair_outline, Vec2};
use std::collections::HashSet;
pub const DASH: [f64; 2] = [0.12, 0.08];
const CLS_OUTLINE: f64 = 0.0;
const CLS_TREAD: f64 = 1.0;
const CLS_BREAK: f64 = 2.0;
const CLS_RUN: f64 = 3.0;
const CLS_ARROW: f64 = 4.0;
#[derive(Default)]
struct Out {
buf: Vec<f64>,
n: usize,
}
impl Out {
fn polygon(&mut self, pts: &[Vec2], stroke_mm: f64, filled: bool) {
self.n += 1;
self.buf.extend([1.0, stroke_mm, if filled { 1.0 } else { 0.0 }, pts.len() as f64]);
for p in pts {
self.buf.extend([p.x, p.y]);
}
}
fn line(&mut self, cls: f64, a: Vec2, b: Vec2, weight_mm: f64, dashed: bool) {
self.n += 1;
self.buf.extend([2.0, cls, weight_mm, if dashed { 1.0 } else { 0.0 }, a.x, a.y, b.x, b.y]);
}
fn arc(&mut self, weight_mm: f64, c: Vec2, from: Vec2, to: Vec2, r: f64) {
self.n += 1;
self.buf.extend([3.0, weight_mm, c.x, c.y, from.x, from.y, to.x, to.y, r]);
}
}
pub fn plan_stair(params: &[f64], total_rise: f64, cut_rise: f64, lw_mm: f64, filled_arrow: bool) -> Vec<f64> {
let Some(p) = decode_params(params) else { return Vec::new() };
if !(total_rise.is_finite() && cut_rise.is_finite() && lw_mm.is_finite()) {
return Vec::new();
}
let geo = stair_geometry(&p, total_rise);
let cut = stair_cut(&geo, cut_rise);
let below: HashSet<i64> = cut.below_indices.iter().copied().collect();
let mut o = Out::default();
for tr in &geo.treads {
let is_below = below.contains(&tr.index);
o.polygon(&tr.pts, lw_mm * 0.7, false);
if tr.pts.len() >= 3 {
o.line(CLS_TREAD, tr.pts[1], tr.pts[2], lw_mm * if is_below { 1.0 } else { 0.6 }, !is_below);
}
}
if let Some(l) = &geo.landing {
if l.len() >= 3 {
o.polygon(l, lw_mm * 0.7, false);
}
}
if let Some(lines) = &cut.break_line {
for (a, b) in lines {
o.line(CLS_BREAK, *a, *b, lw_mm, false);
}
}
for w in geo.run_line.windows(2) {
o.line(CLS_RUN, w[0], w[1], lw_mm, false);
}
let (h1, tip, h2) = geo.arrow.head;
if filled_arrow {
o.polygon(&[h1, tip, h2], lw_mm, true);
} else {
o.line(CLS_ARROW, h1, tip, lw_mm, false);
o.line(CLS_ARROW, h2, tip, lw_mm, false);
}
let outline = stair_outline(&p);
if let Some(poly) = &outline.polygon {
if poly.len() >= 3 {
o.polygon(poly, lw_mm, false);
}
}
if let Some(s) = &outline.spiral {
for (a, b) in &s.lines {
o.line(CLS_OUTLINE, *a, *b, lw_mm, false);
}
for (c, r, a0, a1) in &s.arcs {
let from = Vec2::new(c.x + r * jsnum::cos(*a0), c.y + r * jsnum::sin(*a0));
let to = Vec2::new(c.x + r * jsnum::cos(*a1), c.y + r * jsnum::sin(*a1));
o.arc(lw_mm, *c, from, to, *r);
}
}
let mut out = Vec::with_capacity(o.buf.len() + 1);
out.push(o.n as f64);
out.extend(o.buf);
out
}
#[cfg(test)]
mod tests {
use super::*;
const NAN: f64 = f64::NAN;
fn straight() -> Vec<f64> {
vec![0.0, 0.0, 0.0, 1.0, 0.0, 3.0, NAN, NAN, NAN, NAN, NAN, NAN, 1.2, 16.0, NAN, 0.0]
}
/// Zählt Einträge je Tag und prüft, dass der Puffer genau aufgeht.
fn tags(buf: &[f64]) -> Vec<f64> {
let n = buf[0] as usize;
let mut i = 1;
let mut t = Vec::new();
for _ in 0..n {
t.push(buf[i]);
i += match buf[i] as i64 {
1 => 4 + 2 * buf[i + 3] as usize,
2 => 8,
3 => 9,
_ => panic!("unbekannter Tag"),
};
}
assert_eq!(i, buf.len());
t
}
#[test]
fn gerade_treppe_hat_tritte_lauflinie_pfeil_und_aussenlinie() {
let b = plan_stair(&straight(), 2.8, 1.0, 0.25, false);
let t = tags(&b);
// 16 Tritte × (Polygon + Kante) + 2 Bruchstriche + Lauflinie + 2 Pfeilflügel + Aussenlinie
assert_eq!(t.iter().filter(|x| **x == 1.0).count(), 16 + 1);
assert!(t.iter().filter(|x| **x == 2.0).count() >= 16 + 2 + 2);
// erster Tritt liegt unter der Schnittebene: durchgezogen, volle Stärke
assert_eq!(&b[1 + 4 + 8 + 1..][..3], &[1.0, 0.25, 0.0]);
}
#[test]
fn gefuellter_pfeil_ist_ein_dreieck() {
let offen = tags(&plan_stair(&straight(), 2.8, 1.0, 0.25, false));
let voll = tags(&plan_stair(&straight(), 2.8, 1.0, 0.25, true));
assert_eq!(voll.len() + 1, offen.len());
}
#[test]
fn wendel_liefert_boegen() {
let p = vec![2.0, 0.0, 0.0, 1.0, 0.0, 3.0, NAN, NAN, 0.0, 0.0, 1.5, 270.0, 1.0, 14.0, NAN, 0.0];
let t = tags(&plan_stair(&p, 2.8, 1.0, 0.25, false));
assert_eq!(t.iter().filter(|x| **x == 3.0).count(), 2);
}
#[test]
fn unsinn_ergibt_leeres_ergebnis() {
assert!(plan_stair(&[1.0, 2.0], 2.8, 1.0, 0.25, false).is_empty());
assert!(plan_stair(&straight(), NAN, 1.0, 0.25, false).is_empty());
let mut kaputt = straight();
kaputt[1] = NAN;
assert!(plan_stair(&kaputt, 2.8, 1.0, 0.25, false).is_empty());
}
}
+527
View File
@@ -0,0 +1,527 @@
//! Wand-Poché und Decken-Umriss im Grundriss ([K3a]): die Geometrie von `generatePlan/walls.ts`
//! und `ceilings.ts` (Segmente zwischen Öffnungen, Gehrungsbänder, Schichtfugen, Durchgangswand-
//! Aussparungen, Verdeckung von Decken-Umrissen durch Wand-Footprints). Stil (Bauteil, Schraffur,
//! Farbe, Strichstärke, Linienstil der Fuge) löst TS aus dem Modell auf und ordnet ihn über den
//! Schichtindex zu — das Modell bleibt bis [K4] in TS.
//!
//! Rechenreihenfolge und Zahlsemantik wie in TS (`Math.hypot` über `jsmath`, `Math.min/max` über
//! `jsnum`), damit die Ausgabe bitgleich bleibt.
//!
//! ## Wand-Poché
//! Eingabe (alles `f64`): `[sx, sy, ex, ey, dicke, refOff, grob (0|1), nurAnsicht (0|1), nSchichten,
//! dicke × n, startCut, endCut, hatLayerCuts, (je Schicht: start, end, startSide, endSide)×n,
//! nAussparungen, (from, to, offA, offB)×m, nLuecken, (from, to)×k]` mit einer Linie als
//! `[vorhanden (0|1), px, py, dx, dy]`.
//!
//! Ausgabe `[n, Eintrag × n]` in Zeichenreihenfolge:
//! ```text
//! 1 polygon [1, art, schicht, nOhneStrich, kante…, x0,y0 … x3,y3]
//! art 0 Ansichts-Umriss · 1 Sammelfläche (grob) · 2 Schichtband · 3 Wand-Umriss
//! 2 line [2, art, schicht, ax, ay, bx, by]
//! art 0 layer-joint-l · 1 layer-joint · 2 wall-outline
//! ```
//!
//! ## Decken-Umriss
//! Eingabe `[nRing, x, y …, nBruecken, kante…, nFootprints, (ax, ay, ux, uy, mx, my, len, half,
//! refOff)×n]`; Ausgabe `[n, ax, ay, bx, by …]` (freie Teilstücke der Umrisskanten).
use crate::flat_read::Reader;
use crate::jsmath::hypot2;
use crate::jsnum::{max, min};
pub const CUTOUT_EPS: f64 = 1e-9;
#[derive(Clone, Copy, Debug, PartialEq)]
struct V {
x: f64,
y: f64,
}
fn v(x: f64, y: f64) -> V {
V { x, y }
}
fn sub(a: V, b: V) -> V {
v(a.x - b.x, a.y - b.y)
}
fn add(a: V, b: V) -> V {
v(a.x + b.x, a.y + b.y)
}
fn scale(a: V, s: f64) -> V {
v(a.x * s, a.y * s)
}
fn dot(p: V, q: V) -> f64 {
p.x * q.x + p.y * q.y
}
fn cross(p: V, q: V) -> f64 {
p.x * q.y - p.y * q.x
}
fn normalize(a: V) -> V {
let l = hypot2(a.x, a.y);
let l = if l == 0.0 || l.is_nan() { 1.0 } else { l };
v(a.x / l, a.y / l)
}
fn left_normal(a: V) -> V {
v(-a.y, a.x)
}
fn along(p1: V, p2: V, d: f64) -> V {
add(p1, scale(normalize(sub(p2, p1)), d))
}
fn line_intersect(a: V, da: V, b: V, db: V) -> Option<V> {
let denom = cross(da, db);
if denom.abs() < 1e-9 {
return None;
}
let t = cross(sub(b, a), db) / denom;
Some(add(a, scale(da, t)))
}
#[derive(Clone, Copy, Debug)]
struct Line {
point: V,
dir: V,
}
fn clipped_band(start: V, end: V, off_a: f64, off_b: f64, sc: Option<Line>, ec: Option<Line>) -> [V; 4] {
let u = normalize(sub(end, start));
let n = left_normal(u);
let edge_start = |off: f64| {
let base = add(start, scale(n, off));
match sc {
None => base,
Some(c) => line_intersect(base, u, c.point, c.dir).unwrap_or(base),
}
};
let edge_end = |off: f64| {
let base = add(end, scale(n, off));
match ec {
None => base,
Some(c) => line_intersect(base, u, c.point, c.dir).unwrap_or(base),
}
};
[edge_start(off_a), edge_end(off_a), edge_end(off_b), edge_start(off_b)]
}
/// Loch-Intervalle vom Segment `[s,e]` abziehen (wie `subtractIntervals` in TS).
pub fn subtract_intervals(s: f64, e: f64, holes: &[(f64, f64)]) -> Vec<(f64, f64)> {
let mut clipped: Vec<(f64, f64)> = holes
.iter()
.map(|&(a, b)| (max(s, min(a, b)), min(e, max(a, b))))
.filter(|&(a, b)| b > a + CUTOUT_EPS)
.collect();
clipped.sort_by(|p, q| p.0.partial_cmp(&q.0).unwrap_or(std::cmp::Ordering::Equal));
let mut parts = Vec::new();
let mut cursor = s;
for (a, b) in clipped {
if a > cursor + CUTOUT_EPS {
parts.push((cursor, a));
}
if b > cursor {
cursor = b;
}
}
if cursor < e - CUTOUT_EPS {
parts.push((cursor, e));
}
parts
}
#[derive(Clone, Copy, Debug)]
struct Footprint {
a: V,
u: V,
m: V,
len: f64,
half: f64,
ref_off: f64,
}
fn clip_slab(f0: f64, fd: f64, lo: f64, hi: f64) -> Option<(f64, f64)> {
if fd.abs() < 1e-12 {
return if f0 >= lo - CUTOUT_EPS && f0 <= hi + CUTOUT_EPS { Some((0.0, 1.0)) } else { None };
}
let mut ta = (lo - f0) / fd;
let mut tb = (hi - f0) / fd;
if ta > tb {
std::mem::swap(&mut ta, &mut tb);
}
Some((ta, tb))
}
/// Intervall `[t0,t1] ⊆ [0,1]`, über das `pa→pb` im Wand-Footprint liegt.
fn segment_inside(pa: V, pb: V, fp: &Footprint) -> Option<(f64, f64)> {
let d = sub(pb, pa);
let rel = sub(pa, fp.a);
let su = clip_slab(dot(rel, fp.u), dot(d, fp.u), -fp.half, fp.len + fp.half)?;
let sm = clip_slab(dot(rel, fp.m), dot(d, fp.m), fp.ref_off - fp.half, fp.ref_off + fp.half)?;
let t0 = max(max(0.0, su.0), sm.0);
let t1 = min(min(1.0, su.1), sm.1);
if t1 > t0 + CUTOUT_EPS {
Some((t0, t1))
} else {
None
}
}
// ── Decken-Umriss ───────────────────────────────────────────────────────────
pub fn ceiling_outline(buf: &[f64]) -> Vec<f64> {
(|| {
let mut r = Reader::new(buf);
let ring: Vec<V> = r.ring()?.into_iter().map(|p| v(p[0], p[1])).collect();
let n_bridge = r.count()?;
let mut bridge = Vec::with_capacity(n_bridge);
for _ in 0..n_bridge {
bridge.push(r.num()?);
}
let n_fp = r.count()?;
let mut fps = Vec::with_capacity(n_fp);
for _ in 0..n_fp {
let a = [r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?, r.num()?];
fps.push(Footprint { a: v(a[0], a[1]), u: v(a[2], a[3]), m: v(a[4], a[5]), len: a[6], half: a[7], ref_off: a[8] });
}
let n = ring.len();
let mut lines: Vec<f64> = Vec::new();
let mut count = 0usize;
for i in 0..n {
if bridge.contains(&(i as f64)) {
continue;
}
let a = ring[i];
let b = ring[(i + 1) % n];
let holes: Vec<(f64, f64)> = fps.iter().filter_map(|fp| segment_inside(a, b, fp)).collect();
let d = sub(b, a);
for (t0, t1) in subtract_intervals(0.0, 1.0, &holes) {
let p = add(a, scale(d, t0));
let q = add(a, scale(d, t1));
lines.extend([p.x, p.y, q.x, q.y]);
count += 1;
}
}
let mut out = vec![count as f64];
out.extend(lines);
Some(out)
})()
.unwrap_or_default()
}
// ── Wand-Poché ──────────────────────────────────────────────────────────────
struct LayerCuts {
start: Vec<Option<Line>>,
end: Vec<Option<Line>>,
start_side: Vec<Option<Line>>,
end_side: Vec<Option<Line>>,
}
#[derive(Clone, Copy)]
struct Cutout {
from: f64,
to: f64,
off_a: f64,
off_b: f64,
}
fn read_line(r: &mut Reader) -> Option<Option<Line>> {
let has = r.num()?;
let (px, py, dx, dy) = (r.num()?, r.num()?, r.num()?, r.num()?);
Some(if has != 0.0 { Some(Line { point: v(px, py), dir: v(dx, dy) }) } else { None })
}
#[derive(Default)]
struct Out {
buf: Vec<f64>,
n: usize,
}
impl Out {
fn polygon(&mut self, art: f64, layer: usize, no_stroke: &[f64], pts: &[V; 4]) {
self.n += 1;
self.buf.extend([1.0, art, layer as f64, no_stroke.len() as f64]);
self.buf.extend_from_slice(no_stroke);
for p in pts {
self.buf.extend([p.x, p.y]);
}
}
fn line(&mut self, art: f64, layer: usize, a: V, b: V) {
self.n += 1;
self.buf.extend([2.0, art, layer as f64, a.x, a.y, b.x, b.y]);
}
}
const ART_VIEW: f64 = 0.0;
const ART_GROB: f64 = 1.0;
const ART_BAND: f64 = 2.0;
const ART_OUTLINE: f64 = 3.0;
const LINE_JOINT_L: f64 = 0.0;
const LINE_JOINT: f64 = 1.0;
const LINE_OUTLINE: f64 = 2.0;
fn join_edges(sc: Option<Line>, ec: Option<Line>) -> Vec<f64> {
let mut e = Vec::new();
if ec.is_some() {
e.push(1.0);
}
if sc.is_some() {
e.push(3.0);
}
e
}
pub fn wall_poche(buf: &[f64]) -> Vec<f64> {
wall_poche_inner(buf).unwrap_or_default()
}
fn wall_poche_inner(buf: &[f64]) -> Option<Vec<f64>> {
let mut r = Reader::new(buf);
let (sx, sy, ex, ey) = (r.num()?, r.num()?, r.num()?, r.num()?);
let (total, ref_off) = (r.num()?, r.num()?);
let grob = r.num()? != 0.0;
let view_only = r.num()? != 0.0;
let n_layers = r.count()?;
let mut thick = Vec::with_capacity(n_layers);
for _ in 0..n_layers {
thick.push(r.num()?);
}
let start_cut = read_line(&mut r)?;
let end_cut = read_line(&mut r)?;
let has_layer_cuts = r.num()? != 0.0;
let mut layer_cuts = None;
if has_layer_cuts {
let mut lc = LayerCuts { start: vec![], end: vec![], start_side: vec![], end_side: vec![] };
for _ in 0..n_layers {
lc.start.push(read_line(&mut r)?);
lc.end.push(read_line(&mut r)?);
lc.start_side.push(read_line(&mut r)?);
lc.end_side.push(read_line(&mut r)?);
}
layer_cuts = Some(lc);
}
let n_cut = r.count()?;
let mut span_cutouts = Vec::with_capacity(n_cut);
for _ in 0..n_cut {
span_cutouts.push(Cutout { from: r.num()?, to: r.num()?, off_a: r.num()?, off_b: r.num()? });
}
let n_gap = r.count()?;
let mut gaps = Vec::with_capacity(n_gap);
for _ in 0..n_gap {
gaps.push((r.num()?, r.num()?));
}
if !(sx.is_finite() && sy.is_finite() && ex.is_finite() && ey.is_finite() && total.is_finite() && ref_off.is_finite()) {
return None;
}
let wstart = v(sx, sy);
let wend = v(ex, ey);
let axis_len = hypot2(ex - sx, ey - sy);
let mut segments: Vec<(f64, f64)> = Vec::new();
let mut cursor = 0.0;
for &(from, to) in &gaps {
if from > cursor {
segments.push((cursor, from));
}
cursor = max(cursor, to);
}
if cursor < axis_len {
segments.push((cursor, axis_len));
}
let mut o = Out::default();
for &(s, e) in &segments {
let p1 = along(wstart, wend, s);
let p2 = along(wstart, wend, e);
let sc = if s <= 1e-6 { start_cut } else { None };
let ec = if e >= axis_len - 1e-6 { end_cut } else { None };
if view_only {
o.polygon(ART_VIEW, 0, &join_edges(sc, ec), &clipped_band(p1, p2, ref_off - total / 2.0, ref_off + total / 2.0, sc, ec));
continue;
}
if grob {
o.polygon(ART_GROB, 0, &join_edges(sc, ec), &clipped_band(p1, p2, ref_off - total / 2.0, ref_off + total / 2.0, sc, ec));
continue;
}
let band_join_edges = join_edges(sc, ec);
let seg_cutouts: Vec<Cutout> = span_cutouts
.iter()
.filter(|c| min(c.from, c.to) < e - CUTOUT_EPS && max(c.from, c.to) > s + CUTOUT_EPS)
.copied()
.collect();
let axis_pt = |d: f64| if d == s { p1 } else if d == e { p2 } else { along(wstart, wend, d) };
let mut off = ref_off - total / 2.0;
for li in 0..n_layers {
let layer_start_cut = if s <= 1e-6 {
match &layer_cuts {
Some(lc) => lc.start[li],
None => sc,
}
} else {
None
};
let layer_end_cut = if e >= axis_len - 1e-6 {
match &layer_cuts {
Some(lc) => lc.end[li],
None => ec,
}
} else {
None
};
let band_lo = off;
let band_hi = off + thick[li];
let mut band_holes: Vec<(f64, f64)> = Vec::new();
for c in &seg_cutouts {
let c_lo = min(c.off_a, c.off_b);
let c_hi = max(c.off_a, c.off_b);
if band_lo < c_hi - CUTOUT_EPS && band_hi > c_lo + CUTOUT_EPS {
band_holes.push((c.from, c.to));
}
}
for (a, b) in subtract_intervals(s, e, &band_holes) {
let bsc = if a <= s + CUTOUT_EPS { layer_start_cut } else { None };
let bec = if b >= e - CUTOUT_EPS { layer_end_cut } else { None };
o.polygon(ART_BAND, li, &band_join_edges, &clipped_band(axis_pt(a), axis_pt(b), off, off + thick[li], bsc, bec));
}
let side_start = if s <= 1e-6 { layer_cuts.as_ref().and_then(|lc| lc.start_side[li]) } else { None };
let side_end = if e >= axis_len - 1e-6 { layer_cuts.as_ref().and_then(|lc| lc.end_side[li]) } else { None };
if side_start.is_some() || side_end.is_some() {
let u_seg = normalize(sub(p2, p1));
let n_seg = left_normal(u_seg);
let side_point = |base: V, layer_off: f64, cut: Line| {
let pt = add(base, scale(n_seg, layer_off));
line_intersect(pt, u_seg, cut.point, cut.dir).unwrap_or(pt)
};
if let Some(c) = side_start {
o.line(LINE_JOINT_L, li, side_point(p1, off, c), side_point(p1, off + thick[li], c));
}
if let Some(c) = side_end {
o.line(LINE_JOINT_L, li, side_point(p2, off, c), side_point(p2, off + thick[li], c));
}
}
off += thick[li];
if li + 1 < n_layers {
let mut fuge_holes: Vec<(f64, f64)> = Vec::new();
for c in &seg_cutouts {
let c_lo = min(c.off_a, c.off_b);
let c_hi = max(c.off_a, c.off_b);
if off >= c_lo - CUTOUT_EPS && off <= c_hi + CUTOUT_EPS {
fuge_holes.push((c.from, c.to));
}
}
for (a, b) in subtract_intervals(s, e, &fuge_holes) {
let jsc = if a <= s + CUTOUT_EPS { sc } else { None };
let jec = if b >= e - CUTOUT_EPS { ec } else { None };
let jq = clipped_band(axis_pt(a), axis_pt(b), off, off, jsc, jec);
o.line(LINE_JOINT, li, jq[0], jq[1]);
}
}
}
let off_lo = ref_off - total / 2.0;
let off_hi = ref_off + total / 2.0;
let mut holes_hi: Vec<(f64, f64)> = Vec::new();
let mut holes_lo: Vec<(f64, f64)> = Vec::new();
for c in &seg_cutouts {
if (c.off_a - off_hi).abs() < 1e-6 {
holes_hi.push((c.from, c.to));
} else if (c.off_a - off_lo).abs() < 1e-6 {
holes_lo.push((c.from, c.to));
}
}
let mut outline_no_stroke = band_join_edges.clone();
if !holes_hi.is_empty() {
outline_no_stroke.push(2.0);
}
if !holes_lo.is_empty() {
outline_no_stroke.push(0.0);
}
o.polygon(ART_OUTLINE, 0, &outline_no_stroke, &clipped_band(p1, p2, off_lo, off_hi, sc, ec));
let mut near_edge = |edge_off: f64, holes: &[(f64, f64)]| {
for (a, b) in subtract_intervals(s, e, holes) {
let nsc = if a <= s + CUTOUT_EPS { sc } else { None };
let nec = if b >= e - CUTOUT_EPS { ec } else { None };
let jq = clipped_band(axis_pt(a), axis_pt(b), edge_off, edge_off, nsc, nec);
o.line(LINE_OUTLINE, 0, jq[0], jq[1]);
}
};
if !holes_hi.is_empty() {
near_edge(off_hi, &holes_hi);
}
if !holes_lo.is_empty() {
near_edge(off_lo, &holes_lo);
}
}
let mut out = Vec::with_capacity(o.buf.len() + 1);
out.push(o.n as f64);
out.extend(o.buf);
Some(out)
}
#[cfg(test)]
mod tests {
use super::*;
const NO_LINE: [f64; 5] = [0.0; 5];
fn wall(len: f64, grob: bool, gaps: &[(f64, f64)]) -> Vec<f64> {
let mut b = vec![0.0, 0.0, len, 0.0, 0.3, 0.0, grob as u8 as f64, 0.0, 2.0, 0.1, 0.2];
b.extend(NO_LINE);
b.extend(NO_LINE);
b.extend([0.0, 0.0, gaps.len() as f64]);
for g in gaps {
b.extend([g.0, g.1]);
}
b
}
fn count(out: &[f64], tag: f64) -> usize {
let (mut i, mut n) = (1, 0);
for _ in 0..out[0] as usize {
let t = out[i];
if t == tag {
n += 1;
}
i += if t == 1.0 { 4 + out[i + 3] as usize + 8 } else { 7 };
}
assert_eq!(i, out.len());
n
}
#[test]
fn intervalle_abziehen() {
assert_eq!(subtract_intervals(0.0, 5.0, &[]), vec![(0.0, 5.0)]);
assert_eq!(subtract_intervals(0.0, 5.0, &[(1.0, 2.0), (1.5, 3.0)]), vec![(0.0, 1.0), (3.0, 5.0)]);
assert!(subtract_intervals(0.0, 5.0, &[(-1.0, 9.0)]).is_empty());
}
#[test]
fn wand_ohne_luecke_hat_zwei_baender_fuge_und_umriss() {
let o = wall_poche(&wall(4.0, false, &[]));
assert_eq!(count(&o, 1.0), 3); // 2 Bänder + Umriss
assert_eq!(count(&o, 2.0), 1); // 1 Fuge
}
#[test]
fn luecke_teilt_die_wand_in_zwei_segmente() {
let o = wall_poche(&wall(4.0, false, &[(1.0, 2.0)]));
assert_eq!(count(&o, 1.0), 6);
assert_eq!(count(&wall_poche(&wall(4.0, true, &[(1.0, 2.0)])), 1.0), 2);
}
#[test]
fn unsinn_ohne_panic() {
assert!(wall_poche(&[1.0, 2.0]).is_empty());
let mut b = wall(4.0, false, &[]);
b[0] = f64::NAN;
assert!(wall_poche(&b).is_empty());
assert!(ceiling_outline(&[3.0, 0.0]).is_empty());
}
#[test]
fn decken_umriss_wird_von_wand_verdeckt() {
// Quadrat 4×4, Wand entlang der unteren Kante (Mitte y=0, Dicke 0.4)
let mut b = vec![4.0, 0.0, 0.0, 4.0, 0.0, 4.0, 4.0, 0.0, 4.0, 0.0, 1.0];
b.extend([0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 4.0, 0.2, 0.0]);
let o = ceiling_outline(&b);
assert_eq!(o[0], 3.0); // untere Kante entfällt, drei freie Kanten
}
}
+261
View File
@@ -0,0 +1,261 @@
//! Projektdatei-Format (`.obp`/`.obpt`/Alt-`.json`) ([K4] S4-Vorarbeit, vorher
//! `src/io/projectFormat.ts`): Versionierung, Migration und EIN Parser für alle Ladestellen.
//!
//! Regeln: jede gespeicherte Datei trägt `formatVersion`; ältere Dateien (auch ohne = Version 0)
//! laufen durch die Migrationskette; neuere werden mit klarer Meldung ABGELEHNT; tolerant gelesen
//! (fehlende Listen leer ergänzt, unbekannte Felder bleiben erhalten und werden gemeldet). Alles
//! arbeitet auf dem rohen JSON-Baum — das Modell wird erst danach typisiert.
use serde_json::{Map, Value};
/// Aktuelle Version des Dateiformats. Bei jeder Formatänderung erhöhen + Migration anhängen.
pub const PROJECT_FORMAT_VERSION: u64 = 2;
const REQUIRED_ARRAYS: [&str; 3] = ["walls", "layers", "drawingLevels"];
const DEFAULT_ARRAYS: [&str; 5] = ["lineStyles", "hatches", "components", "wallTypes", "drawings2d"];
/// Bekannte Felder von `Project` (für die Meldung unbekannter Felder).
const KNOWN_KEYS: [&str; 46] = [
"formatVersion", "id", "name", "lineStyles", "textStyles", "hatches", "components", "wallTypes",
"ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens",
"penSets", "activePenSetId", "customPalettes", "builtinPaletteBanks", "drawingLevels", "layers",
"walls", "ceilings", "roofs", "openings", "stairs", "rooms", "drawings2d", "context",
"extrudedSolids", "columns", "groups", "parametricWalls", "overrideRules", "viewSnapshots",
"viewSnapshotFolders", "layouts", "masterLayouts", "layoutFolders", "referenceElevationMasl",
"geoAnchor", "roomProgram", "parcelArea", "sunStudy", "siteRules", "scaleLineWeights",
];
/// Ergebnis des Einlesens.
#[derive(Debug, PartialEq)]
pub enum Parsed {
Ok { project: Map<String, Value>, warnings: Vec<String>, migrated_from: Option<u64> },
Err(String),
}
/// JS-`String(v)` für die Meldungen.
fn js_string(v: &Value) -> String {
match v {
Value::Null => "null".into(),
Value::Bool(b) => b.to_string(),
Value::Number(n) => n.as_f64().map_or(n.to_string(), |f| if f.fract() == 0.0 && f.abs() < 1e21 { format!("{}", f as i64) } else { f.to_string() }),
Value::String(s) => s.clone(),
Value::Array(a) => a.iter().map(|x| if x.is_null() { String::new() } else { js_string(x) }).collect::<Vec<_>>().join(","),
Value::Object(_) => "[object Object]".into(),
}
}
/// 1 → 2: Legacy-Türen (`doors`) werden zu Öffnungen (`openings`, kind `door`).
fn migrate_doors(mut raw: Map<String, Value>) -> Map<String, Value> {
let doors: Vec<Value> = raw.get("doors").and_then(Value::as_array).cloned().unwrap_or_default();
raw.shift_remove("doors");
if doors.is_empty() {
return raw;
}
let mut openings: Vec<Value> = raw.get("openings").and_then(Value::as_array).cloned().unwrap_or_default();
let mut taken: std::collections::HashSet<String> = openings.iter().map(|o| o.get("id").map_or("undefined".to_string(), js_string)).collect();
let door_type_id = raw
.get("doorTypes")
.and_then(Value::as_array)
.and_then(|a| a.first())
.and_then(|t| t.get("id"))
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.map(str::to_owned);
for d in &doors {
let mut id = d.get("id").map_or("undefined".to_string(), js_string);
while taken.contains(&id) {
id = format!("{id}-t");
}
taken.insert(id.clone());
let mut o = Map::new();
o.insert("id".into(), Value::String(id));
o.insert("type".into(), "opening".into());
for (k, src) in [("hostWallId", "hostWallId"), ("categoryCode", "categoryCode")] {
if let Some(v) = d.get(src) {
o.insert(k.into(), v.clone());
}
}
o.insert("kind".into(), "door".into());
for k in ["position", "width", "height"] {
if let Some(v) = d.get(k) {
o.insert(k.into(), v.clone());
}
}
o.insert("sillHeight".into(), 0.into());
for k in ["swing", "hinge"] {
if let Some(v) = d.get(k) {
o.insert(k.into(), v.clone());
}
}
if let Some(t) = &door_type_id {
o.insert("typeId".into(), Value::String(t.clone()));
}
openings.push(Value::Object(o));
}
raw.insert("openings".into(), Value::Array(openings));
raw
}
/// Liest eine Projektdatei (Text) tolerant ein, migriert und prüft sie. `now_ms`: Zeitpunkt für
/// eine Ersatz-ID, falls die Datei keine trägt.
pub fn parse_project_file(text: &str, now_ms: f64) -> Parsed {
match serde_json::from_str::<Value>(text) {
Ok(raw) => parse_project_object(raw, now_ms),
Err(e) => Parsed::Err(format!("Die Datei ist kein gültiges JSON ({e}).")),
}
}
/// Wie [`parse_project_file`], für ein bereits geparstes Objekt.
pub fn parse_project_object(raw: Value, now_ms: f64) -> Parsed {
let Value::Object(mut obj) = raw else { return Parsed::Err("Die Datei enthält kein Dossier-Projekt.".into()) };
let mut warnings: Vec<String> = Vec::new();
let mut version: u64 = 0;
if let Some(v) = obj.get("formatVersion") {
match v.as_f64() {
Some(f) if f.fract() == 0.0 && f >= 0.0 => version = f as u64,
_ => return Parsed::Err(format!("Ungültige Formatversion „{}\".", js_string(v))),
}
}
if version > PROJECT_FORMAT_VERSION {
return Parsed::Err(format!(
"Die Datei wurde mit einer neueren Dossier-Version gespeichert (Format {version}, dieses Programm kennt bis {PROJECT_FORMAT_VERSION}). Bitte Dossier aktualisieren."
));
}
for key in REQUIRED_ARRAYS {
if !obj.get(key).is_some_and(Value::is_array) {
return Parsed::Err(format!("Die Datei enthält kein Dossier-Projekt (Liste „{key}\" fehlt)."));
}
}
let migrated_from = (version < PROJECT_FORMAT_VERSION).then_some(version);
for i in version..PROJECT_FORMAT_VERSION {
obj = match i {
1 => migrate_doors(obj),
_ => obj, // 0 → 1: Einführung von `formatVersion`; Inhalt unverändert.
};
}
obj.insert("formatVersion".into(), PROJECT_FORMAT_VERSION.into());
for key in DEFAULT_ARRAYS {
match obj.get(key) {
None => {
obj.insert(key.into(), Value::Array(vec![]));
}
Some(Value::Array(_)) => {}
Some(_) => {
warnings.push(format!("Feld „{key}\" ist keine Liste und wurde geleert."));
obj.insert(key.into(), Value::Array(vec![]));
}
}
}
if !obj.get("id").and_then(Value::as_str).is_some_and(|s| !s.is_empty()) {
obj.insert("id".into(), Value::String(format!("project-{}", to_base36(now_ms.max(0.0) as u64))));
}
if !obj.get("name").is_some_and(Value::is_string) {
obj.insert("name".into(), Value::String(String::new()));
}
let unknown: Vec<&str> = obj.keys().map(String::as_str).filter(|k| !KNOWN_KEYS.contains(k)).collect();
if !unknown.is_empty() {
warnings.push(format!("Unbekannte Felder behalten: {}.", unknown.join(", ")));
}
Parsed::Ok { project: obj, warnings, migrated_from }
}
fn to_base36(mut n: u64) -> String {
if n == 0 {
return "0".into();
}
let mut digits = Vec::new();
while n > 0 {
digits.push(b"0123456789abcdefghijklmnopqrstuvwxyz"[(n % 36) as usize]);
n /= 36;
}
digits.reverse();
String::from_utf8(digits).expect("ASCII")
}
/// Serialisiert ein Projekt für die Datei: aktuelle Formatversion vorne, Einrückung 2.
pub fn serialize_project(project: &Map<String, Value>) -> String {
let mut out = Map::new();
out.insert("formatVersion".into(), PROJECT_FORMAT_VERSION.into());
for (k, v) in project {
if k != "formatVersion" {
out.insert(k.clone(), v.clone());
}
}
serde_json::to_string_pretty(&Value::Object(out)).unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn minimal() -> Value {
json!({"id":"p","name":"N","walls":[],"layers":[],"drawingLevels":[]})
}
#[test]
fn alte_datei_wird_migriert_und_ergaenzt() {
let Parsed::Ok { project, warnings, migrated_from } = parse_project_object(minimal(), 0.0) else { panic!() };
assert_eq!(migrated_from, Some(0));
assert_eq!(project["formatVersion"], 2);
assert_eq!(project["lineStyles"], json!([]));
assert!(warnings.is_empty());
}
#[test]
fn neuere_und_kaputte_dateien_werden_abgelehnt() {
let mut v = minimal();
v["formatVersion"] = json!(99);
assert!(matches!(parse_project_object(v, 0.0), Parsed::Err(m) if m.contains("neueren")));
let mut v = minimal();
v["formatVersion"] = json!("x");
assert_eq!(parse_project_object(v, 0.0), Parsed::Err("Ungültige Formatversion „x\".".into()));
assert!(matches!(parse_project_object(json!([1]), 0.0), Parsed::Err(_)));
assert!(matches!(parse_project_object(json!({"walls":[]}), 0.0), Parsed::Err(m) if m.contains("layers")));
assert!(matches!(parse_project_file("{", 0.0), Parsed::Err(m) if m.starts_with("Die Datei ist kein gültiges JSON")));
}
#[test]
fn tueren_werden_zu_oeffnungen() {
let mut v = minimal();
v["doors"] = json!([{"id":"D1","hostWallId":"W","categoryCode":"21","position":1,"width":0.9,"height":2,"swing":"left","hinge":"start"},{"id":"O1","hostWallId":"W","position":0,"width":1,"height":2}]);
v["openings"] = json!([{"id":"O1"}]);
v["doorTypes"] = json!([{"id":"dt"}]);
let Parsed::Ok { project, .. } = parse_project_object(v, 0.0) else { panic!() };
assert!(!project.contains_key("doors"));
let o = project["openings"].as_array().unwrap();
assert_eq!(o.len(), 3);
assert_eq!(o[1]["id"], "D1");
assert_eq!(o[1]["kind"], "door");
assert_eq!(o[1]["typeId"], "dt");
assert_eq!(o[2]["id"], "O1-t");
}
#[test]
fn unbekannte_felder_bleiben_und_werden_gemeldet() {
let mut v = minimal();
v["zukunft"] = json!(1);
v["hatches"] = json!("kaputt");
let Parsed::Ok { project, warnings, .. } = parse_project_object(v, 0.0) else { panic!() };
assert_eq!(project["zukunft"], 1);
assert_eq!(warnings.len(), 2);
}
#[test]
fn ersatz_id_aus_zeit() {
let mut v = minimal();
v["id"] = json!("");
let Parsed::Ok { project, .. } = parse_project_object(v, 36.0 * 36.0 + 5.0) else { panic!() };
assert_eq!(project["id"], "project-105");
}
#[test]
fn serialisierung_setzt_version_nach_vorn() {
let Value::Object(m) = minimal() else { panic!() };
let s = serialize_project(&m);
assert!(s.starts_with("{\n \"formatVersion\": 2,\n \"id\": \"p\""));
}
}
+35
View File
@@ -0,0 +1,35 @@
//! 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::{export_schedule, 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)?),
("scheduleRows", _) => json(&export_schedule::schedule_rows(p)),
("scheduleCsv", 1) => Ok(export_schedule::export_schedule_csv(p, text, args[0] != 0.0)),
("pickGeometry", _) => json(&model3d::pick_geometry(p)?),
("model3dParts", 3) => json(&model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?),
_ => Err(format!("Unbekannte Abfrage: {name}")),
}
}
+108
View File
@@ -250,3 +250,111 @@ mod tests {
assert!(close(c.violation_area, 0.0) && c.violations.is_empty() && c.height_exceeded);
}
}
// ── Baurecht aus dem Projekt-Dokument ([K4] S2) ─────────────────────────────
use crate::jsmath::hypot2;
use crate::model::{Project, Vec2};
use serde::Serialize;
/// Mehrfach-Fläche mit `Vec2`-Punkten (JSON-Form wie `Area` in TS).
pub type AreaOut = Vec<Vec<Vec<Vec2>>>;
pub fn area_out(polys: &[Polygon]) -> AreaOut {
polys.iter().map(|p| p.iter().map(|r| r.iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect()).collect()).collect()
}
fn wall_corners(start: Vec2, end: Vec2, thickness: f64) -> Vec<[f64; 2]> {
let h = thickness / 2.0;
let (dx, dy) = (end.x - start.x, end.y - start.y);
let l = hypot2(dx, dy);
let l = if l == 0.0 || l.is_nan() { 1.0 } else { l };
let (ux, uy) = (dx / l, dy / l);
let (nx, ny) = (-uy, ux);
vec![
[start.x + nx * h, start.y + ny * h],
[end.x + nx * h, end.y + ny * h],
[end.x + nx * -h, end.y + ny * -h],
[start.x + nx * -h, start.y + ny * -h],
]
}
/// Teile der Gebäude-Grundfläche (Wände aller Geschosse, freie Körper ohne Abzugskörper).
fn footprint_parts(p: &Project) -> Vec<Polygon> {
let mut parts: Vec<Polygon> = Vec::new();
for w in &p.walls {
if hypot2(w.end.x - w.start.x, w.end.y - w.start.y) < 1e-9 {
continue;
}
parts.push(vec![wall_corners(w.start, w.end, p.wall_thickness(w, 0.2))]);
}
for s in p.extruded_solids.as_deref().unwrap_or(&[]) {
if s.operation.as_deref() == Some("subtract") || s.points.len() < 3 {
continue;
}
parts.push(vec![s.points.iter().map(|v| [v.x, v.y]).collect()]);
}
parts
}
/// Grundfläche des Gebäudes (vereinigt).
pub fn building_footprint(p: &Project) -> AreaOut {
let parts = footprint_parts(p);
if parts.is_empty() {
return vec![];
}
area_out(&polygon_bool::union(&parts))
}
/// Höchster Punkt des Modells über ±0.00 (Wände, freie Körper, Dächer); `None` ohne Bauteile.
pub fn model_top(p: &Project) -> Option<f64> {
let mut top = f64::NEG_INFINITY;
for w in &p.walls {
top = top.max(p.wall_vertical_extent(w).1);
}
for s in p.extruded_solids.as_deref().unwrap_or(&[]) {
if s.operation.as_deref() == Some("subtract") {
continue;
}
let base = p.floor(&s.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0));
top = top.max(base + s.base_offset.unwrap_or(0.0) + s.height);
}
for r in p.roofs.as_deref().unwrap_or(&[]) {
let eaves = p.roof_base_elevation(r);
top = top.max(eaves + crate::roof::roof_geometry(&r.params(), eaves).ridge_height);
}
top.is_finite().then_some(top)
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SiteCheckOut {
pub parcel_area: f64,
pub allowed: AreaOut,
pub allowed_area: f64,
pub violations: AreaOut,
pub violation_area: f64,
pub max_top: Option<f64>,
pub height_exceeded: bool,
}
/// Prüft das Modell gegen `siteRules`; `None` ohne (gültiges) Baurecht.
pub fn check_project(p: &Project) -> Option<SiteCheckOut> {
let r = p.site_rules.as_ref()?;
let max_top = model_top(p);
let rules = SiteRules {
parcel: r.parcel.iter().map(|v| [v.x, v.y]).collect(),
setbacks: (0..r.parcel.len()).map(|i| r.setbacks.as_ref().and_then(|s| s.get(i)).copied().unwrap_or(r.default_setback)).collect(),
lines: r.building_lines.as_deref().unwrap_or(&[]).iter().map(|l| BuildingLine { a: [l.a.x, l.a.y], b: [l.b.x, l.b.y] }).collect(),
};
let c = check_site_rules(&rules, &footprint_parts(p), r.max_height.unwrap_or(f64::NAN), max_top.unwrap_or(f64::NAN))?;
Some(SiteCheckOut {
parcel_area: c.parcel_area,
allowed: area_out(&c.allowed),
allowed_area: c.allowed_area,
violations: area_out(&c.violations),
violation_area: c.violation_area,
max_top,
height_exceeded: c.height_exceeded,
})
}
-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 {
+123
View File
@@ -0,0 +1,123 @@
//! Darstellungs-Auflösung aus dem Modell ([K4] S2): Farben, Schraffur und Schnitt-Linienstil, wie sie
//! `src/plan/generatePlan/shared.ts` und `src/plan/toWalls3d/shared.ts` aus dem `Project` ableiten.
use crate::model::{HatchPattern, Project};
use serde::Serialize;
pub type Rgb = [f64; 3];
/// Warmer, neutraler Wand-Grundton (wie render3d).
pub const WALL_RGB: Rgb = [0.82, 0.8, 0.76];
/// Etwas hellerer, kühlerer Ton für Deckenplatten.
pub const SLAB_RGB: Rgb = [0.86, 0.86, 0.88];
/// Fallback-Farbe für Linien ohne Farbe ("#888888").
pub const DRAWING_LINE_FALLBACK_RGB: Rgb = [0x88 as f64 / 255.0, 0x88 as f64 / 255.0, 0x88 as f64 / 255.0];
/// "#rrggbb" → RGB 0..1; ungültiges Format → `fallback`.
pub fn hex_to_rgb(hex: &str, fallback: Rgb) -> Rgb {
let h = hex.strip_prefix('#').unwrap_or(hex);
if h.len() != 6 || !h.bytes().all(|b| b.is_ascii_hexdigit()) {
return fallback;
}
let v = u32::from_str_radix(h, 16).unwrap_or(0);
[((v >> 16) & 0xff) as f64 / 255.0, ((v >> 8) & 0xff) as f64 / 255.0, (v & 0xff) as f64 / 255.0]
}
/// Schnitt-Schraffur eines Bauteil-Bandes für den 3D-Live-Schnitt (`RHatch` in TS).
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RHatch {
pub pattern: f64,
pub angle: f64,
pub scale: f64,
pub line_weight: f64,
pub base_angle: f64,
pub relative_to_wall: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub top_angle: Option<f64>,
}
fn pattern_id(p: HatchPattern) -> f64 {
match p {
HatchPattern::Solid => 1.0,
HatchPattern::Diagonal => 2.0,
HatchPattern::Crosshatch => 3.0,
HatchPattern::Insulation => 4.0,
_ => 0.0,
}
}
/// Aufgelöste Schraffur (Kern von `resolveHatch`): Muster, Massstab, Endwinkel, Musterlinien-Stärke.
/// `None`, wenn Schraffur oder ihr Linienstil fehlen (TS wirft dort).
pub struct HatchCore {
pub pattern: HatchPattern,
pub scale: f64,
pub angle: f64,
pub line_weight: f64,
}
pub fn resolve_hatch_core(p: &Project, hatch_id: &str, wall_angle_deg: Option<f64>) -> Option<HatchCore> {
let h = p.hatch(hatch_id)?;
let ls = match h.line_style_id.as_deref().filter(|s| !s.is_empty()) {
Some(id) => Some(p.line_style(id)?),
None => None,
};
let base = h.angle;
let angle = match wall_angle_deg {
Some(w) if h.relative_to_wall == Some(true) => base - w,
_ => base,
};
Some(HatchCore { pattern: h.pattern, scale: h.scale * 1.0, angle, line_weight: ls.map_or(0.13, |l| l.weight) })
}
/// Schnitt-Schraffur eines Bauteils (`resolveComponentHatch`); `axis_angle_deg` 90 für Wand-Bänder,
/// `None` für Decken.
pub fn resolve_component_hatch(p: &Project, component_id: &str, axis_angle_deg: Option<f64>) -> Option<RHatch> {
let comp = p.component(component_id)?;
if comp.hatch_id.is_empty() {
return None;
}
let hr = resolve_hatch_core(p, &comp.hatch_id, axis_angle_deg)?;
let abs = resolve_hatch_core(p, &comp.hatch_id, None)?;
let relative = resolve_hatch_core(p, &comp.hatch_id, Some(90.0))?.angle != abs.angle;
Some(RHatch {
pattern: pattern_id(hr.pattern),
angle: hr.angle,
scale: hr.scale,
line_weight: hr.line_weight,
base_angle: abs.angle,
relative_to_wall: relative,
top_angle: None,
})
}
/// Schnitt-Schraffur der dicksten Schicht (`dominantLayerHatch`).
pub fn dominant_layer_hatch(p: &Project, layers: &[crate::model::Layer], axis_angle_deg: Option<f64>) -> Option<RHatch> {
let dominant = dominant_layer(layers)?;
resolve_component_hatch(p, &dominant.component_id, axis_angle_deg)
}
/// Dickste Schicht (bei Gleichstand die erste).
pub fn dominant_layer(layers: &[crate::model::Layer]) -> Option<&crate::model::Layer> {
let mut best = layers.first()?;
for l in layers {
if l.thickness > best.thickness {
best = l;
}
}
Some(best)
}
/// Repräsentative Farbe der dicksten Schicht (`dominantLayerColor`).
pub fn dominant_layer_color(p: &Project, layers: &[crate::model::Layer], fallback: Rgb) -> Rgb {
match dominant_layer(layers).and_then(|d| p.component(&d.component_id)) {
Some(c) => hex_to_rgb(&c.color, fallback),
None => fallback,
}
}
/// Stil der Schnitt-Umrisslinie einer Schicht (`resolveCutLineStyle`).
pub fn resolve_cut_line_style(p: &Project, joint_line_style_id: Option<&str>) -> Option<(Rgb, f64)> {
let ls = p.line_styles.iter().find(|l| Some(l.id.as_str()) == joint_line_style_id.filter(|s| !s.is_empty()))?;
Some((hex_to_rgb(&ls.color, DRAWING_LINE_FALLBACK_RGB), ls.weight))
}
+62
View File
@@ -280,3 +280,65 @@ mod tests {
assert_eq!(without_holes(&vec![square(0.0, 0.0, 3.0)]), vec![square(0.0, 0.0, 3.0)]);
}
}
// ── Schatten aus dem Projekt-Dokument ([K4] S2) ─────────────────────────────
use crate::jsmath::hypot2;
use crate::model::Project;
/// Vereinigter Boden-Schatten aller Wände, freien Körper und Dächer des Projekts (leer bei Nacht).
/// Wände und Körper als Prismen, Dächer als Punktwolke (Traufe auf Traufhöhe, Traufe/First/Grate
/// auf Firsthöhe).
pub fn shadow_polygons_project(p: &Project, sun: SunPosition) -> Vec<Polygon> {
let mut prisms: Vec<Prism> = Vec::new();
for w in &p.walls {
let (z_bottom, z_top) = p.wall_vertical_extent(w);
let dx = w.end.x - w.start.x;
let dy = w.end.y - w.start.y;
let len = hypot2(dx, dy);
if len < 1e-9 {
continue;
}
let t = p.wall_thickness(w, 0.2) / 2.0;
let nx = (-dy / len) * t;
let ny = (dx / len) * t;
prisms.push(Prism {
footprint: vec![
[w.start.x + nx, w.start.y + ny],
[w.end.x + nx, w.end.y + ny],
[w.end.x - nx, w.end.y - ny],
[w.start.x - nx, w.start.y - ny],
],
z_bottom,
z_top,
});
}
for s in p.extruded_solids.as_deref().unwrap_or(&[]) {
if s.operation.as_deref() == Some("subtract") {
continue;
}
let base = p.floor(&s.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0));
let z0 = base + s.base_offset.unwrap_or(0.0);
prisms.push(Prism { footprint: s.points.iter().map(|v| [v.x, v.y]).collect(), z_bottom: z0, z_top: z0 + s.height });
}
let mut clouds: Vec<Vec<[f64; 3]>> = Vec::new();
for r in p.roofs.as_deref().unwrap_or(&[]) {
let eaves_z = p.roof_base_elevation(r);
let geo = crate::roof::roof_geometry(&r.params(), eaves_z);
let top = eaves_z + geo.ridge_height;
let mut pts: Vec<[f64; 3]> = Vec::new();
for e in &geo.eaves {
pts.push([e[0], e[1], eaves_z]);
pts.push([e[0], e[1], top]);
}
for l in &geo.ridges {
pts.push([l[0][0], l[0][1], top]);
pts.push([l[1][0], l[1][1], top]);
}
for l in &geo.hips {
pts.push([l[1][0], l[1][1], top]);
}
clouds.push(pts);
}
shadow_union(&prisms, &clouds, sun)
}
+385
View File
@@ -0,0 +1,385 @@
//! Abzugskörper in Grundriss und Schnitt ([K3c], vorher `plan/voids.ts`): Polygon minus Schneider mit
//! Schlüsselloch-Stegen für Löcher, nicht gestrichene Kanten, Strecke ausserhalb von Ringen und die
//! Schnitt-Rechtecke eines senkrechten Prismas. Die Auswahl, welche Körper welches Bauteil treffen,
//! bleibt in TS (Modell). Rechenreihenfolge wie dort.
//!
//! ## Flaches Format
//! Ringliste `[n, (k, x, y …) × n]`.
//! - `keyhole(ringe)` → `[k, x, y …, nStege, i …]` (Ringe offen oder geschlossen).
//! - `subtract_rings(pts, schneider, nicht_gestrichen)`: `pts = [k, x, y …]`, `schneider = Ringliste`,
//! `nicht_gestrichen = [m, i …]` → `[-1]` (keine Überschneidung — Original unverändert) oder
//! `[n, (k, x, y …, m, i …) × n]`.
//! - `segment_outside(ax, ay, bx, by, schneider)` → `[n, (t0, t1) × n]`.
//! - `section_rects(pts, base_x, base_y, u_x, u_y)` → `[n, (u0, u1) × n]`.
//!
//! Abweichung zur TS-Fassung: der Überschneidungstest nahm den Schnitt mit ALLEN Schneidern
//! gleichzeitig; mit zwei getrennten Aussparungen fiel dann jede Subtraktion weg. Jetzt gilt die
//! Vereinigung der Schneider.
use crate::flat_read::{signed_area, Reader};
use crate::jsmath::hypot2;
use crate::jsnum::max;
use crate::polygon_bool;
type Pair = [f64; 2];
const EPS: f64 = 1e-7;
fn open_ring(r: &[Pair]) -> Vec<Pair> {
if r.len() > 1 {
let a = r[0];
let b = r[r.len() - 1];
if (a[0] - b[0]).abs() < EPS && (a[1] - b[1]).abs() < EPS {
return r[..r.len() - 1].to_vec();
}
}
r.to_vec()
}
/// Löcher per Steg in den Aussenring einhängen; liefert Punkte und Stegkanten-Indizes.
pub fn keyhole(poly: &[Vec<Pair>]) -> (Vec<Pair>, Vec<usize>) {
let mut outer = open_ring(&poly[0]);
let mut bridges: Vec<usize> = Vec::new();
let mut holes: Vec<Vec<Pair>> = poly[1..].iter().map(|h| open_ring(h)).filter(|h| h.len() >= 3).collect();
let max_x = |h: &Vec<Pair>| h.iter().fold(f64::NEG_INFINITY, |m, p| max(m, p[0]));
holes.sort_by(|a, b| (max_x(b) - max_x(a)).partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal));
for hole in holes {
let mut hi = 0;
for i in 1..hole.len() {
if hole[i][0] > hole[hi][0] {
hi = i;
}
}
let h = hole[hi];
let mut oi = 0;
let mut best = f64::INFINITY;
for (i, p) in outer.iter().enumerate() {
let d = hypot2(p[0] - h[0], p[1] - h[1]);
if d < best {
best = d;
oi = i;
}
}
let mut hole_seq: Vec<Pair> = hole[hi..].to_vec();
hole_seq.extend_from_slice(&hole[..hi]);
hole_seq.push(h);
let mut next: Vec<Pair> = outer[..=oi].to_vec();
next.extend_from_slice(&hole_seq);
next.push(outer[oi]);
next.extend_from_slice(&outer[oi + 1..]);
let shift = hole_seq.len() + 1;
for b in bridges.iter_mut() {
if *b > oi {
*b += shift;
}
}
bridges.push(oi);
bridges.push(oi + hole_seq.len());
outer = next;
}
(outer, bridges)
}
fn on_segment(a: Pair, b: Pair, p: Pair, q: Pair) -> bool {
let tol = 1e-6;
let dx = q[0] - p[0];
let dy = q[1] - p[1];
let len = hypot2(dx, dy);
if len < EPS {
return false;
}
let dist = |r: Pair| ((r[0] - p[0]) * dy - (r[1] - p[1]) * dx).abs() / len;
let t = |r: Pair| ((r[0] - p[0]) * dx + (r[1] - p[1]) * dy) / (len * len);
dist(a) < tol && dist(b) < tol && t(a) > -tol && t(a) < 1.0 + tol && t(b) > -tol && t(b) < 1.0 + tol
}
/// Math.sign: NaN bleibt NaN, ±0 bleibt 0.
fn js_sign(x: f64) -> f64 {
if x.is_nan() || x == 0.0 {
x
} else {
x.signum()
}
}
pub struct Piece {
pub pts: Vec<Pair>,
pub no_stroke: Vec<usize>,
}
/// `None` = keine Überschneidung (Original unverändert lassen).
pub fn subtract_rings(pts: &[Pair], cutters: &[Vec<Pair>], no_stroke: &[usize]) -> Option<Vec<Piece>> {
if pts.len() < 3 || cutters.is_empty() {
return None;
}
let subject = vec![pts.to_vec()];
let clips: Vec<Vec<Vec<Pair>>> = cutters.iter().filter(|c| c.len() >= 3).map(|c| vec![c.clone()]).collect();
if clips.is_empty() {
return None;
}
let all_clips = polygon_bool::union(&clips);
if polygon_bool::intersection(&[subject.clone()], &all_clips).is_empty() {
return None;
}
let diff = polygon_bool::difference(&[subject], &clips);
let area0 = signed_area(pts).abs();
let mut out = Vec::new();
for poly in &diff {
// Ringe wie im TS-Pfad geschlossen übergeben (der Kern liefert offene Ringe).
let closed: Vec<Vec<Pair>> = poly
.iter()
.map(|r| {
let mut c = r.clone();
if let Some(&f) = r.first() {
c.push(f);
}
c
})
.collect();
let (kp, bridges) = keyhole(&closed);
if kp.len() < 3 || signed_area(&open_ring(&closed[0])).abs() < area0 * 1e-9 {
continue;
}
let same_dir = js_sign(signed_area(&kp)) == js_sign(signed_area(pts)) || signed_area(pts) == 0.0;
let ring_pts: Vec<Pair> = if same_dir { kp } else { kp.into_iter().rev().collect() };
let n = ring_pts.len();
let bridge_set: std::collections::HashSet<usize> = if same_dir {
bridges.iter().copied().collect()
} else {
bridges.iter().map(|&i| (n + n - 2 - i.min(n + n - 2)) % n).collect()
};
let mut ns = Vec::new();
for i in 0..n {
let a = ring_pts[i];
let b = ring_pts[(i + 1) % n];
if bridge_set.contains(&i) {
ns.push(i);
continue;
}
for &e in no_stroke {
if e < pts.len() {
let p = pts[e];
let q = pts[(e + 1) % pts.len()];
if on_segment(a, b, p, q) {
ns.push(i);
break;
}
}
}
}
out.push(Piece { pts: ring_pts, no_stroke: ns });
}
Some(out)
}
fn point_in_ring(x: f64, y: f64, r: &[Pair]) -> bool {
let mut inside = false;
let mut j = r.len().wrapping_sub(1);
for i in 0..r.len() {
let [xi, yi] = r[i];
let [xj, yj] = r[j];
if (yi > y) != (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi {
inside = !inside;
}
j = i;
}
inside
}
/// Teile der Strecke a→b ausserhalb aller Ringe, als Parameter-Intervalle.
pub fn segment_outside(a: Pair, b: Pair, cutters: &[Vec<Pair>]) -> Vec<(f64, f64)> {
let mut ts = vec![0.0, 1.0];
let dx = b[0] - a[0];
let dy = b[1] - a[1];
for r in cutters {
for i in 0..r.len() {
let p = r[i];
let q = r[(i + 1) % r.len()];
let ex = q[0] - p[0];
let ey = q[1] - p[1];
let den = dx * ey - dy * ex;
if den.abs() < 1e-14 {
continue;
}
let t = ((p[0] - a[0]) * ey - (p[1] - a[1]) * ex) / den;
let u = ((p[0] - a[0]) * dy - (p[1] - a[1]) * dx) / den;
if t > 0.0 && t < 1.0 && u >= -1e-9 && u <= 1.0 + 1e-9 {
ts.push(t);
}
}
}
ts.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal));
let mut out: Vec<(f64, f64)> = Vec::new();
for i in 0..ts.len() - 1 {
let (t0, t1) = (ts[i], ts[i + 1]);
if t1 - t0 < 1e-9 {
continue;
}
let tm = (t0 + t1) / 2.0;
let mx = a[0] + dx * tm;
let my = a[1] + dy * tm;
if cutters.iter().any(|r| point_in_ring(mx, my, r)) {
continue;
}
match out.last_mut() {
Some(last) if (last.1 - t0).abs() < 1e-9 => last.1 = t1,
_ => out.push((t0, t1)),
}
}
out
}
/// u-Intervalle der Schnittspur durch ein senkrechtes Prisma (`pts` = Grundriss).
pub fn section_rects(pts: &[Pair], base: Pair, u_dir: Pair) -> Vec<(f64, f64)> {
let n = pts.len();
let side = |p: Pair| (p[0] - base[0]) * u_dir[1] - (p[1] - base[1]) * u_dir[0];
let mut ts: Vec<f64> = Vec::new();
for i in 0..n {
let a = pts[i];
let b = pts[(i + 1) % n];
let sa = side(a);
let sb = side(b);
if (sa > 0.0) == (sb > 0.0) {
continue;
}
let t = sa / (sa - sb);
let px = a[0] + (b[0] - a[0]) * t;
let py = a[1] + (b[1] - a[1]) * t;
ts.push((px - base[0]) * u_dir[0] + (py - base[1]) * u_dir[1]);
}
ts.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let mut out = Vec::new();
let mut i = 0;
while i + 1 < ts.len() {
let (u0, u1) = (ts[i], ts[i + 1]);
i += 2;
if u1 - u0 < 1e-6 {
continue;
}
out.push((u0, u1));
}
out
}
// ── Bindungen (flach) ──────────────────────────────────────────────────────
fn read_rings(r: &mut Reader) -> Option<Vec<Vec<Pair>>> {
let n = r.count()?;
(0..n).map(|_| r.ring()).collect()
}
fn finite(rings: &[Vec<Pair>]) -> bool {
rings.iter().all(|r| r.iter().all(|p| p[0].is_finite() && p[1].is_finite()))
}
fn push_ring(f: &mut Vec<f64>, r: &[Pair]) {
f.push(r.len() as f64);
for p in r {
f.extend(*p);
}
}
pub fn keyhole_flat(inp: &[f64]) -> Vec<f64> {
let mut r = Reader::new(inp);
let Some(rings) = read_rings(&mut r) else { return Vec::new() };
if rings.is_empty() || !finite(&rings) || rings[0].is_empty() {
return Vec::new();
}
let (pts, bridges) = keyhole(&rings);
let mut f = Vec::new();
push_ring(&mut f, &pts);
f.push(bridges.len() as f64);
f.extend(bridges.iter().map(|&b| b as f64));
f
}
pub fn subtract_rings_flat(pts: &[f64], cutters: &[f64], no_stroke: &[f64]) -> Vec<f64> {
let (mut rp, mut rc, mut rn) = (Reader::new(pts), Reader::new(cutters), Reader::new(no_stroke));
let (Some(p), Some(c)) = (rp.ring(), read_rings(&mut rc)) else { return Vec::new() };
let Some(m) = rn.count() else { return Vec::new() };
let Some(ns) = (0..m).map(|_| rn.count()).collect::<Option<Vec<usize>>>() else { return Vec::new() };
if !finite(&c) || !finite(&[p.clone()]) {
return Vec::new();
}
match subtract_rings(&p, &c, &ns) {
None => vec![-1.0],
Some(pieces) => {
let mut f = vec![pieces.len() as f64];
for pc in &pieces {
push_ring(&mut f, &pc.pts);
f.push(pc.no_stroke.len() as f64);
f.extend(pc.no_stroke.iter().map(|&i| i as f64));
}
f
}
}
}
pub fn segment_outside_flat(a: &[f64], cutters: &[f64]) -> Vec<f64> {
let mut rc = Reader::new(cutters);
let Some(c) = read_rings(&mut rc) else { return Vec::new() };
if a.len() != 4 || a.iter().any(|v| !v.is_finite()) || !finite(&c) {
return Vec::new();
}
let parts = segment_outside([a[0], a[1]], [a[2], a[3]], &c);
let mut f = vec![parts.len() as f64];
for (t0, t1) in parts {
f.extend([t0, t1]);
}
f
}
pub fn section_rects_flat(pts: &[f64], base_u: &[f64]) -> Vec<f64> {
let mut r = Reader::new(pts);
let Some(p) = r.ring() else { return Vec::new() };
if base_u.len() != 4 || base_u.iter().any(|v| !v.is_finite()) || !finite(&[p.clone()]) || p.is_empty() {
return Vec::new();
}
let rects = section_rects(&p, [base_u[0], base_u[1]], [base_u[2], base_u[3]]);
let mut f = vec![rects.len() as f64];
for (u0, u1) in rects {
f.extend([u0, u1]);
}
f
}
#[cfg(test)]
mod tests {
use super::*;
fn sq(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec<Pair> {
vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]]
}
#[test]
fn loch_wird_per_steg_eingehaengt() {
let r = subtract_rings(&sq(0.0, 0.0, 4.0, 2.0), &[sq(1.0, 0.5, 2.0, 1.5)], &[]).unwrap();
assert_eq!(r.len(), 1);
assert_eq!(r[0].pts.len(), 10);
assert_eq!(r[0].no_stroke.len(), 2);
}
#[test]
fn ohne_ueberschneidung_none() {
assert!(subtract_rings(&sq(0.0, 0.0, 1.0, 1.0), &[sq(5.0, 5.0, 6.0, 6.0)], &[]).is_none());
}
#[test]
fn zwei_getrennte_aussparungen_wirken_beide() {
let r = subtract_rings(&sq(0.0, 0.0, 10.0, 2.0), &[sq(1.0, -1.0, 2.0, 3.0), sq(6.0, -1.0, 7.0, 3.0)], &[]).unwrap();
assert_eq!(r.len(), 3);
}
#[test]
fn strecke_wird_geteilt() {
let parts = segment_outside([0.0, 0.5], [4.0, 0.5], &[sq(1.0, 0.0, 2.0, 1.0)]);
assert_eq!(parts.len(), 2);
assert!((parts[0].1 - 0.25).abs() < 1e-12 && (parts[1].0 - 0.5).abs() < 1e-12);
}
#[test]
fn unsinn_ist_leer() {
assert!(keyhole_flat(&[f64::NAN]).is_empty());
assert!(subtract_rings_flat(&[3.0, 0.0], &[0.0], &[0.0]).is_empty());
assert!(section_rects_flat(&[3.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0], &[0.0]).is_empty());
}
}
-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))
}
+27
View File
@@ -0,0 +1,27 @@
//! Bindungen der Kurven-Tessellierung (`crate::curves`). Punkte flach `[x0, y0, …]`.
use wasm_bindgen::prelude::wasm_bindgen;
/// Punkte einer (gedrehten) Ellipse, `n` gleichverteilte Parameterschritte.
#[wasm_bindgen]
pub fn curves_ellipse_flat(cx: f64, cy: f64, rx: f64, ry: f64, rotation: f64, n: f64) -> Vec<f64> {
crate::curves::ellipse(cx, cy, rx, ry, rotation, n)
}
/// Kubische Bezier-Kette (Anker·Griff·Griff·Anker …); unter 4 Punkten unverändert.
#[wasm_bindgen]
pub fn curves_bezier_chain_flat(pts: &[f64], segs_per_curve: f64) -> Vec<f64> {
crate::curves::bezier_chain(pts, segs_per_curve)
}
/// Catmull-Rom-Spline durch die Punkte; unter 3 Punkten unverändert.
#[wasm_bindgen]
pub fn curves_catmull_rom_flat(pts: &[f64], closed: bool, segs_per_span: f64) -> Vec<f64> {
crate::curves::catmull_rom(pts, closed, segs_per_span)
}
/// Uniformer kubischer B-Spline über Kontrollpunkten; unter 3 Punkten unverändert.
#[wasm_bindgen]
pub fn curves_uniform_bspline_flat(pts: &[f64], closed: bool, segs_per_span: f64) -> Vec<f64> {
crate::curves::uniform_bspline(pts, closed, segs_per_span)
}
+9
View File
@@ -0,0 +1,9 @@
//! Bindung der Delaunay-Triangulierung (`crate::delaunay`).
use wasm_bindgen::prelude::wasm_bindgen;
/// Delaunay-Dreiecke zu `[x0, y0, x1, y1 …]`; Indizes je drei; leer bei < 3 oder kollinearen Punkten.
#[wasm_bindgen]
pub fn delaunay_flat(coords: &[f64]) -> Vec<f64> {
crate::delaunay::triangulate(coords).into_iter().map(f64::from).collect()
}
+98
View File
@@ -0,0 +1,98 @@
//! Bindungen des Projekt-Dokuments (`crate::document`): Handles in einer Tabelle, damit TS das
//! Projekt nicht bei jedem Aufruf neu übergeben muss.
use crate::document::{Document, Op};
use serde_json::Value;
use std::cell::RefCell;
use wasm_bindgen::prelude::wasm_bindgen;
thread_local! {
static DOCS: RefCell<Vec<Option<Document>>> = const { RefCell::new(Vec::new()) };
}
fn with_doc<R>(h: u32, f: impl FnOnce(&mut Document) -> R) -> Option<R> {
DOCS.with(|d| d.borrow_mut().get_mut((h as usize).checked_sub(1)?)?.as_mut().map(f))
}
/// Öffnet ein Dokument aus Projekt-JSON; Handle ≥ 1, 0 bei Fehler.
#[wasm_bindgen]
pub fn doc_open(json: &str) -> u32 {
let Ok(doc) = Document::from_json(json) else { return 0 };
DOCS.with(|d| {
let mut d = d.borrow_mut();
if let Some(i) = d.iter().position(Option::is_none) {
d[i] = Some(doc);
i as u32 + 1
} else {
d.push(Some(doc));
d.len() as u32
}
})
}
#[wasm_bindgen]
pub fn doc_close(h: u32) {
DOCS.with(|d| {
if let Some(slot) = (h as usize).checked_sub(1).and_then(|i| d.borrow_mut().get_mut(i).map(|s| s.take())) {
drop(slot);
}
});
}
/// Wendet eine Op-Folge (JSON-Array) an. Leerer Text = ok, sonst JSON-Array der Meldungen.
#[wasm_bindgen]
pub fn doc_apply(h: u32, ops_json: &str) -> String {
let parsed: Result<Vec<Op>, String> = serde_json::from_str::<Value>(ops_json)
.map_err(|e| e.to_string())
.and_then(|v| v.as_array().ok_or("Ops sind kein Array".to_string()).and_then(|a| a.iter().map(Op::from_json).collect()));
let problems = match parsed {
Err(e) => vec![e],
Ok(ops) => match with_doc(h, |d| d.apply(&ops)) {
None => vec!["Dokument nicht offen".to_string()],
Some(Ok(())) => return String::new(),
Some(Err(p)) => p,
},
};
Value::from(problems).to_string()
}
/// Das ganze Dokument als JSON (leer, wenn nicht offen).
#[wasm_bindgen]
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. 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, &[], "")
}
/// Wie [`doc_query`] mit Zahlen- und Textargument.
#[wasm_bindgen]
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)
})
.unwrap_or_else(|| Err("Dokument nicht offen".to_string()));
match result {
Ok(json) => json,
Err(e) => format!("\u{1}{e}"),
}
}
/// Boden-Spuren aller 2D-Zeichnungen als LineList-Vertices `[px, py, pz, r, g, b]` (Float32);
/// leer bei Fehler oder ohne Zeichnungen.
#[wasm_bindgen]
pub fn doc_drawing_line_verts(h: u32) -> Vec<f32> {
with_doc(h, |d| d.project().ok().map(|p| crate::model3d::drawing_line_verts(&p))).flatten().unwrap_or_default()
}
/// Das Projekt als Datei-Text (Formatversion vorn, Einrückung 2); leer, wenn das Dokument nicht offen ist.
#[wasm_bindgen]
pub fn doc_serialize(h: u32) -> String {
with_doc(h, |d| d.serialize()).unwrap_or_default()
}
+1 -40
View File
@@ -1,8 +1,7 @@
//! Bindungen der Kennzahlen-Rechenteile (`crate::kennzahlen`).
use crate::flat_read::pairs;
use crate::flat_read::Reader;
use crate::kennzahlen::{self, RoomIn, SolidIn};
use crate::kennzahlen;
use wasm_bindgen::prelude::wasm_bindgen;
/// Grundriss `[x0, y0, …]`, Kreisradius (NaN = kein Kreis), Höhe, Verjüngung → m³.
@@ -10,41 +9,3 @@ use wasm_bindgen::prelude::wasm_bindgen;
pub fn kz_solid_volume(points: &[f64], circle_r: f64, height: f64, taper: f64) -> f64 {
kennzahlen::solid_volume(&pairs(points), circle_r, height, taper)
}
fn read_rooms(buf: &[f64]) -> Option<Vec<RoomIn>> {
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 (level, category) = (r.count()?, r.count()?);
out.push(RoomIn { level, category, boundary: r.ring()? });
}
Some(out)
}
fn read_solids(buf: &[f64]) -> Option<Vec<SolidIn>> {
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 subtract = r.num()? != 0.0;
let (circle_r, height, taper) = (r.num()?, r.num()?, r.num()?);
out.push(SolidIn { subtract, points: r.ring()?, circle_r, height, taper });
}
Some(out)
}
/// Räume `[n, (geschoss, kategorie, nPkt, x, y, …)…]`, Körper
/// `[n, (abzug 0/1, radius|NaN, höhe, verjüngung, nPkt, x, y, …)…]`, Parzellenzahl, Parzellenring
/// `[x0, y0, …]` → `[gv, parzelle|NaN, (6 Kategorie-Summen je Geschoss)…]`.
#[wasm_bindgen]
pub fn kz_area_sums(n_levels: u32, rooms: &[f64], solids: &[f64], parcel_area: f64, parcel_ring: &[f64]) -> Vec<f64> {
let rooms = read_rooms(rooms).unwrap_or_default();
let solids = read_solids(solids).unwrap_or_default();
let s = kennzahlen::area_sums(n_levels.min(1 << 16) as usize, &rooms, &solids, parcel_area, &pairs(parcel_ring));
let mut out = vec![s.gv, s.parcel.unwrap_or(f64::NAN)];
for l in s.by_level {
out.extend(l);
}
out
}
+15
View File
@@ -0,0 +1,15 @@
//! Bindungen des Netz-Ebenenschnitts (`crate::mesh_section`). Layouts s. dort.
use wasm_bindgen::prelude::wasm_bindgen;
/// Schnitt eines Dreiecksnetzes mit einer Ebene; Unsinn → leer.
#[wasm_bindgen]
pub fn mesh_section_cut_flat(positions: &[f64], indices: &[f64], plane: &[f64]) -> Vec<f64> {
crate::mesh_section::cut(positions, indices, plane)
}
/// Ringe → Flächen mit Löchern; Unsinn → leer.
#[wasm_bindgen]
pub fn mesh_section_polygons_flat(input: &[f64]) -> Vec<f64> {
crate::mesh_section::rings_to_polygons(input)
}
+12 -5
View File
@@ -13,18 +13,25 @@ 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 project_format;
mod gpu_compile;
mod plan_stairs;
mod plan_walls;
mod plan_openings;
mod delaunay;
mod document;
mod mesh_section;
mod plan_elevation;
mod plan_misc;
mod plan_section;
mod voids;
mod curves;
mod hatch;
use wasm_bindgen::prelude::wasm_bindgen;
-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)
}
+45
View File
@@ -0,0 +1,45 @@
//! Bindungen der Ansichts-Geometrie (`crate::plan_elevation`). Layouts s. dort.
use wasm_bindgen::prelude::wasm_bindgen;
/// Sichtbare Teilstücke von Segmenten gegen nähere Verdecker; Unsinn → leer.
#[wasm_bindgen]
pub fn elevation_clip_segments_flat(occ: &[f64], segs: &[f64]) -> Vec<f64> {
crate::plan_elevation::clip_segments(occ, segs)
}
/// Ob Punkte hinter einem näheren Verdecker liegen; Unsinn → leer.
#[wasm_bindgen]
pub fn elevation_occluded_points_flat(occ: &[f64], pts: &[f64]) -> Vec<f64> {
crate::plan_elevation::occluded_points(occ, pts)
}
/// Schlagschatten auskragender Flächen auf Fassaden; Unsinn → leer.
#[wasm_bindgen]
pub fn elevation_shadows_flat(walls: &[f64], slabs: &[f64]) -> Vec<f64> {
crate::plan_elevation::shadows(walls, slabs)
}
/// XOR-Umrisskanten frontaler Rechteckgruppen; Unsinn → leer.
#[wasm_bindgen]
pub fn elevation_xor_outline_flat(polys: &[f64]) -> Vec<f64> {
crate::plan_elevation::xor_outline(polys)
}
/// Sichtbare Wand-, Decken- und Dachflächen in Ansichts-Koordinaten; Unsinn → leer.
#[wasm_bindgen]
pub fn elevation_faces_flat(frame: &[f64], walls: &[f64], slabs: &[f64], roofs: &[f64]) -> Vec<f64> {
crate::plan_elevation::faces(frame, walls, slabs, roofs)
}
/// Eck-Verlängerung der Wandenden für die Ansicht; Unsinn → leer.
#[wasm_bindgen]
pub fn elevation_wall_extensions_flat(input: &[f64]) -> Vec<f64> {
crate::plan_elevation::wall_extensions(input)
}
/// Projektion und Aufteilung (Glas, Flügel, Sprossen, Bank, Symbol) der Öffnungen; Unsinn → leer.
#[wasm_bindgen]
pub fn elevation_openings_flat(frame: &[f64], input: &[f64]) -> Vec<f64> {
crate::plan_elevation::openings(frame, input)
}
+27
View File
@@ -0,0 +1,27 @@
//! Bindungen kleiner Plan-Bausteine (`crate::plan_misc`). Layouts s. dort.
use wasm_bindgen::prelude::wasm_bindgen;
/// Grundriss-Fussabdruck eines Meshes (Sockelkanten); Unsinn → leer.
#[wasm_bindgen]
pub fn context_footprint_flat(positions: &[f64], indices: &[f64]) -> Vec<f64> {
crate::plan_misc::context_footprint(positions, indices)
}
/// `[minX, minY, maxX, maxY]` der x/y-Werte eines [x,y,z…]-Arrays; leer ohne Punkte.
#[wasm_bindgen]
pub fn context_bbox_flat(positions: &[f64]) -> Vec<f64> {
crate::plan_misc::bbox(positions)
}
/// Schnittführungs-Symbol einer Linie; leer bei zu kurzer Linie.
#[wasm_bindgen]
pub fn section_line_flat(p0x: f64, p0y: f64, p1x: f64, p1y: f64, sign: f64) -> Vec<f64> {
crate::plan_misc::section_line(p0x, p0y, p1x, p1y, sign)
}
/// Linienende (Pfeil, Punkt, Schrägstrich, Quadrat); leer ohne Wirkung.
#[wasm_bindgen]
pub fn end_mark_flat(x: f64, y: f64, dx: f64, dy: f64, art: f64, mm: f64, scale_denominator: f64) -> Vec<f64> {
crate::plan_misc::end_mark(x, y, dx, dy, art, mm, scale_denominator)
}
+15
View File
@@ -0,0 +1,15 @@
//! Bindungen von Öffnungs-Symbol und Fenster-Symbol (`crate::plan_openings`). Layout s. dort.
use wasm_bindgen::prelude::wasm_bindgen;
/// Tür-/Fenster-Symbol einer Öffnung im Grundriss; Unsinn → leer.
#[wasm_bindgen]
pub fn plan_opening_flat(buf: &[f64]) -> Vec<f64> {
crate::plan_openings::plan_opening(buf)
}
/// Fenster-Symbol (Rahmen, Glas, Flügel, Stulp) einer Öffnung; Unsinn/entartet → leer.
#[wasm_bindgen]
pub fn window_symbol_flat(buf: &[f64]) -> Vec<f64> {
crate::plan_openings::window_symbol_flat(buf)
}
+21
View File
@@ -0,0 +1,21 @@
//! Bindungen der Schnitt-Bänder (`crate::plan_section`). Layouts s. dort.
use wasm_bindgen::prelude::wasm_bindgen;
/// Dominanz-Subtraktion und Verschmelzung der Schnitt-Rechtecke; Unsinn → leer.
#[wasm_bindgen]
pub fn section_dominant_bands_flat(input: &[f64]) -> Vec<f64> {
crate::plan_section::dominant_bands(input)
}
/// Aussenringe der Vereinigung achsparalleler Rechtecke; Unsinn → leer.
#[wasm_bindgen]
pub fn section_union_outlines_flat(input: &[f64]) -> Vec<f64> {
crate::plan_section::union_outlines(input)
}
/// Spur der senkrechten Schnittebene auf den Dachflächen eines Dachs; Unsinn → leer.
#[wasm_bindgen]
pub fn section_roof_segments_flat(base_x: f64, base_y: f64, u_x: f64, u_y: f64, planes: &[f64]) -> Vec<f64> {
crate::plan_section::roof_segments(base_x, base_y, u_x, u_y, planes)
}
+10
View File
@@ -0,0 +1,10 @@
//! Bindung des Treppen-Symbols im Grundriss (`crate::plan_stairs`). Ausgabe-Layout s. dort.
use wasm_bindgen::prelude::wasm_bindgen;
/// Treppen-Parameter (16 Zahlen), Gesamt-Steighöhe, Schnitthöhe über der UK, Strichstärke (mm),
/// gefüllter Pfeil (0/1) → Primitivliste; Unsinn → leer.
#[wasm_bindgen]
pub fn plan_stair_flat(params: &[f64], total_rise: f64, cut_rise: f64, lw_mm: f64, filled_arrow: f64) -> Vec<f64> {
crate::plan_stairs::plan_stair(params, total_rise, cut_rise, lw_mm, filled_arrow != 0.0)
}
+15
View File
@@ -0,0 +1,15 @@
//! Bindungen von Wand-Poché und Decken-Umriss im Grundriss (`crate::plan_walls`). Layout s. dort.
use wasm_bindgen::prelude::wasm_bindgen;
/// Wand-Poché-Geometrie einer Wand; Unsinn → leer.
#[wasm_bindgen]
pub fn plan_wall_poche_flat(buf: &[f64]) -> Vec<f64> {
crate::plan_walls::wall_poche(buf)
}
/// Freie Teilstücke eines Decken-Umrisses gegen Wand-Footprints; Unsinn → leer.
#[wasm_bindgen]
pub fn plan_ceiling_outline_flat(buf: &[f64]) -> Vec<f64> {
crate::plan_walls::ceiling_outline(buf)
}
+22
View File
@@ -0,0 +1,22 @@
//! Bindungen des Projektdatei-Formats (`crate::project_format`).
use crate::project_format::{parse_project_file, Parsed};
use serde_json::{json, Value};
use wasm_bindgen::prelude::wasm_bindgen;
/// Liest eine Projektdatei (Text). Antwort als JSON:
/// `{"ok":true,"project":{…},"warnings":[…],"migratedFrom":null|n}` oder `{"ok":false,"error":"…"}`.
#[wasm_bindgen]
pub fn project_parse(text: &str, now_ms: f64) -> String {
let v: Value = match parse_project_file(text, now_ms) {
Parsed::Ok { project, warnings, migrated_from } => json!({"ok": true, "project": project, "warnings": warnings, "migratedFrom": migrated_from}),
Parsed::Err(error) => json!({"ok": false, "error": error}),
};
v.to_string()
}
/// Aktuelle Version des Dateiformats.
#[wasm_bindgen]
pub fn project_format_version() -> u32 {
crate::project_format::PROJECT_FORMAT_VERSION as u32
}
-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> {
+27
View File
@@ -0,0 +1,27 @@
//! Bindungen der Abzugskörper-Geometrie (`crate::voids`). Layouts s. dort.
use wasm_bindgen::prelude::wasm_bindgen;
/// Löcher als Schlüsselloch-Stege in den Aussenring; Unsinn → leer.
#[wasm_bindgen]
pub fn voids_keyhole_flat(rings: &[f64]) -> Vec<f64> {
crate::voids::keyhole_flat(rings)
}
/// Polygon minus Schneider (mit nicht gestrichenen Kanten); `[-1]` = keine Überschneidung.
#[wasm_bindgen]
pub fn voids_subtract_rings_flat(pts: &[f64], cutters: &[f64], no_stroke: &[f64]) -> Vec<f64> {
crate::voids::subtract_rings_flat(pts, cutters, no_stroke)
}
/// Teile einer Strecke ausserhalb aller Ringe; Unsinn → leer.
#[wasm_bindgen]
pub fn voids_segment_outside_flat(seg: &[f64], cutters: &[f64]) -> Vec<f64> {
crate::voids::segment_outside_flat(seg, cutters)
}
/// Schnitt-Intervalle eines Prismas mit einer senkrechten Ebene; Unsinn → leer.
#[wasm_bindgen]
pub fn voids_section_rects_flat(pts: &[f64], base_u: &[f64]) -> Vec<f64> {
crate::voids::section_rects_flat(pts, base_u)
}
-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)
}
+936
View File
@@ -0,0 +1,936 @@
{
"id": "demo",
"name": "Demo-Haus",
"lineStyles": [
{
"id": "hatch-hair",
"name": "Volllinie 0.02",
"weight": 0.02,
"color": "#1a1a1a",
"dash": null
},
{
"id": "thin",
"name": "Volllinie 0.13",
"weight": 0.13,
"color": "#1a1a1a",
"dash": null
},
{
"id": "medium",
"name": "Volllinie 0.25",
"weight": 0.25,
"color": "#1a1a1a",
"dash": null
},
{
"id": "thick",
"name": "Volllinie 0.5",
"weight": 0.5,
"color": "#0a0a0a",
"dash": null
},
{
"id": "hatch-dash",
"name": "Dämmungsstrich",
"weight": 0.02,
"color": "#1a1a1a",
"dash": [
0.35,
0.3
]
}
],
"hatches": [
{
"id": "none",
"name": "Ohne",
"pattern": "none",
"scale": 1,
"angle": 0,
"color": "#1a1a1a"
},
{
"id": "insulation",
"name": "Wärmedämmung",
"pattern": "insulation",
"scale": 1,
"angle": 0,
"color": "#1a1a1a",
"lineStyleId": "thin"
},
{
"id": "diagonal",
"name": "Diagonal",
"pattern": "diagonal",
"scale": 1,
"angle": 45,
"color": "#1a1a1a",
"lineStyleId": "thin"
},
{
"id": "crosshatch",
"name": "Kreuzschraffur",
"pattern": "crosshatch",
"scale": 1,
"angle": 0,
"color": "#1a1a1a",
"lineStyleId": "thin"
},
{
"id": "solid-concrete",
"name": "Beton (voll)",
"pattern": "solid",
"scale": 1,
"angle": 0,
"color": "#9aa0a6",
"lineStyleId": "thin"
},
{
"id": "sia-concrete",
"name": "Beton (Kreuz)",
"pattern": "crosshatch",
"scale": 0.5,
"angle": 45,
"color": "#1a1a1a",
"lineStyleId": "hatch-hair"
},
{
"id": "sia-brick",
"name": "Backstein (Diagonal)",
"pattern": "diagonal",
"scale": 0.5,
"angle": 45,
"relativeToWall": true,
"color": "#1a1a1a",
"lineStyleId": "hatch-hair"
},
{
"id": "sia-insulation",
"name": "Dämmung (Strich)",
"pattern": "diagonal",
"scale": 0.45,
"angle": 0,
"relativeToWall": true,
"color": "#1a1a1a",
"lineStyleId": "hatch-hair"
}
],
"components": [
{
"id": "render-ext",
"name": "Aussenputz",
"color": "#d8d2c7",
"hatchId": "none",
"joinPriority": 10,
"material": {
"libraryId": "Plaster001",
"color": "/assets/materials/Plaster001/color.jpg",
"normal": "/assets/materials/Plaster001/normal.jpg",
"roughness": "/assets/materials/Plaster001/roughness.jpg",
"displacement": "/assets/materials/Plaster001/displacement.jpg",
"sizeM": 1
}
},
{
"id": "insulation",
"name": "Wärmedämmung",
"color": "#ffffff",
"hatchId": "sia-insulation",
"joinPriority": 20
},
{
"id": "brick",
"name": "Backstein",
"color": "#8c5544",
"hatchId": "sia-brick",
"joinPriority": 50,
"material": {
"libraryId": "Bricks104",
"color": "/assets/materials/Bricks104/color.jpg",
"normal": "/assets/materials/Bricks104/normal.jpg",
"roughness": "/assets/materials/Bricks104/roughness.jpg",
"displacement": "/assets/materials/Bricks104/displacement.jpg",
"ao": "/assets/materials/Bricks104/ao.jpg",
"sizeM": 1
}
},
{
"id": "render-int",
"name": "Innenputz",
"color": "#efece6",
"hatchId": "none",
"joinPriority": 10,
"material": {
"libraryId": "Plaster001",
"color": "/assets/materials/Plaster001/color.jpg",
"normal": "/assets/materials/Plaster001/normal.jpg",
"roughness": "/assets/materials/Plaster001/roughness.jpg",
"displacement": "/assets/materials/Plaster001/displacement.jpg",
"sizeM": 1
}
},
{
"id": "roof-tiles",
"name": "Dachziegel",
"color": "#b8735c",
"hatchId": "sia-brick",
"joinPriority": 15,
"material": {
"libraryId": "RoofingTiles013A",
"color": "/assets/materials/RoofingTiles013A/color.jpg",
"normal": "/assets/materials/RoofingTiles013A/normal.jpg",
"roughness": "/assets/materials/RoofingTiles013A/roughness.jpg",
"displacement": "/assets/materials/RoofingTiles013A/displacement.jpg",
"ao": "/assets/materials/RoofingTiles013A/ao.jpg",
"sizeM": 1
}
},
{
"id": "concrete",
"name": "Beton",
"color": "#9aa0a6",
"hatchId": "sia-concrete",
"joinPriority": 100,
"material": {
"libraryId": "Concrete048",
"color": "/assets/materials/Concrete048/color.jpg",
"normal": "/assets/materials/Concrete048/normal.jpg",
"roughness": "/assets/materials/Concrete048/roughness.jpg",
"displacement": "/assets/materials/Concrete048/displacement.jpg",
"ao": "/assets/materials/Concrete048/ao.jpg",
"sizeM": 1
}
},
{
"id": "screed",
"name": "Zementestrich",
"color": "#c9c2b3",
"hatchId": "diagonal",
"joinPriority": 30
}
],
"wallTypes": [
{
"id": "aw",
"name": "Aussenwand 34.5 cm",
"layers": [
{
"componentId": "render-ext",
"thickness": 0.02
},
{
"componentId": "insulation",
"thickness": 0.16,
"jointLineStyleId": "thin"
},
{
"componentId": "brick",
"thickness": 0.15
},
{
"componentId": "render-int",
"thickness": 0.015
}
]
},
{
"id": "iw",
"name": "Innenwand Mauerwerk verputzt 15 cm",
"layers": [
{
"componentId": "render-int",
"thickness": 0.015
},
{
"componentId": "brick",
"thickness": 0.12
},
{
"componentId": "render-int",
"thickness": 0.015
}
]
}
],
"ceilingTypes": [
{
"id": "dg-massiv",
"name": "Geschossdecke mehrschichtig",
"layers": [
{
"componentId": "screed",
"thickness": 0.06
},
{
"componentId": "insulation",
"thickness": 0.04,
"jointLineStyleId": "thin"
},
{
"componentId": "concrete",
"thickness": 0.2
}
]
}
],
"roofTypes": [
{
"id": "roof-warm",
"name": "Steildach gedämmt",
"layers": [
{
"componentId": "roof-tiles",
"thickness": 0.04
},
{
"componentId": "insulation",
"thickness": 0.22,
"jointLineStyleId": "thin"
},
{
"componentId": "render-int",
"thickness": 0.0125
}
]
}
],
"doorTypes": [
{
"id": "door-standard",
"name": "Zimmertür 0.9 m",
"kind": "dreh",
"leafCount": 1,
"leafStyle": "glatt",
"frameThickness": 0.05,
"frameKind": "zarge",
"frameWidth": 0.06,
"defaultWidth": 0.9,
"defaultHeight": 2
},
{
"id": "door-entry",
"name": "Haustür Blockrahmen (Oberlicht)",
"kind": "dreh",
"leafCount": 1,
"leafStyle": "glas",
"glazingRatio": 0.35,
"frameThickness": 0.07,
"frameKind": "blockrahmen",
"frameWidth": 0.09,
"insetFromFace": 0.14,
"insetFace": "aussen",
"transomHeight": 0.45,
"threshold": true,
"defaultWidth": 1.1,
"defaultHeight": 2.1
}
],
"windowTypes": [
{
"id": "window-standard",
"name": "Fenster 1.2 × 1.4 m",
"kind": "drehkipp",
"wingCount": 1,
"glazing": "zweifach",
"frameThickness": 0.06,
"frameWidth": 0.06,
"defaultSillHeight": 0.9,
"defaultWidth": 1.2,
"defaultHeight": 1.4
},
{
"id": "window-double",
"name": "Fenster 2-flügl. + Oberlicht",
"kind": "drehkipp",
"wingCount": 2,
"mullionRows": 1,
"glazing": "dreifach",
"frameThickness": 0.07,
"frameWidth": 0.07,
"insetFromFace": 0.12,
"insetFace": "aussen",
"transomHeight": 0.4,
"defaultSillHeight": 0.85,
"defaultWidth": 1.8,
"defaultHeight": 1.9
}
],
"stairTypes": [
{
"id": "stair-standard",
"name": "Betontreppe 1.0 m",
"structure": "beton",
"closedRisers": true,
"treadThickness": 0.05,
"nosing": 0.03,
"railing": "keine",
"defaultWidth": 1
},
{
"id": "stair-massiv",
"name": "Massivtreppe (auf Sockel)",
"structure": "massiv",
"closedRisers": true,
"treadThickness": 0.04,
"nosing": 0.03,
"railing": "keine",
"defaultWidth": 1
},
{
"id": "stair-wange-holz",
"name": "Wangentreppe Holz (offen)",
"structure": "wange",
"closedRisers": false,
"treadThickness": 0.05,
"nosing": 0.03,
"railing": "keine",
"defaultWidth": 1
},
{
"id": "stair-aufgesattelt",
"name": "Aufgesattelt (Setzstufen)",
"structure": "aufgesattelt",
"closedRisers": true,
"treadThickness": 0.05,
"nosing": 0.025,
"railing": "keine",
"defaultWidth": 1
}
],
"drawingLevels": [
{
"id": "eg",
"name": "Erdgeschoss",
"kind": "floor",
"visible": true,
"locked": false,
"floorHeight": 2.6,
"cutHeight": 1,
"baseElevation": 0
},
{
"id": "og",
"name": "Obergeschoss",
"kind": "floor",
"visible": true,
"locked": false,
"floorHeight": 2.6,
"cutHeight": 1,
"baseElevation": 2.6
},
{
"id": "schnitt-a",
"name": "Schnitt A",
"kind": "section",
"visible": true,
"locked": false,
"linePoints": [
{
"x": -1,
"y": 2
},
{
"x": 6,
"y": 2
}
],
"directionSign": 1
},
{
"id": "ansicht-sued",
"name": "Ansicht Süd",
"kind": "elevation",
"visible": true,
"locked": false,
"linePoints": [
{
"x": -1,
"y": -2
},
{
"x": 6,
"y": -2
}
],
"directionSign": 1,
"shadows": true
},
{
"id": "detail-1",
"name": "Detail 1",
"kind": "drawing",
"visible": true,
"locked": false
}
],
"layers": [
{
"code": "00",
"name": "Raster",
"color": "#484850",
"lw": 0.13,
"visible": true,
"locked": false
},
{
"code": "01",
"name": "Vermessung",
"color": "#707078",
"lw": 0.18,
"visible": true,
"locked": false
},
{
"code": "05",
"name": "Kontext",
"color": "#707078",
"lw": 0.13,
"visible": true,
"locked": false,
"children": [
{
"code": "10",
"name": "Situation",
"color": "#909090",
"lw": 0.18,
"visible": true,
"locked": false
},
{
"code": "11",
"name": "Strasse",
"color": "#a89070",
"lw": 0.18,
"visible": true,
"locked": false
},
{
"code": "12",
"name": "Gebäude",
"color": "#888888",
"lw": 0.25,
"visible": true,
"locked": false
},
{
"code": "13",
"name": "Bäume",
"color": "#50a050",
"lw": 0.13,
"visible": true,
"locked": false
},
{
"code": "14",
"name": "Höhenlinien",
"color": "#909050",
"lw": 0.18,
"visible": true,
"locked": false
}
]
},
{
"code": "20",
"name": "Wände",
"color": "#0a0a0a",
"lw": 0.35,
"visible": true,
"locked": false,
"children": [
{
"code": "21",
"name": "Türen/Fenster",
"color": "#5080c8",
"lw": 0.25,
"visible": true,
"locked": false
},
{
"code": "22",
"name": "Möbel",
"color": "#909090",
"lw": 0.13,
"visible": true,
"locked": false
},
{
"code": "25",
"name": "Stützen",
"color": "#c87050",
"lw": 0.5,
"visible": true,
"locked": false
}
]
},
{
"code": "30",
"name": "Decken",
"color": "#605850",
"lw": 0.35,
"visible": true,
"locked": false
},
{
"code": "31",
"name": "Dächer",
"color": "#7a4a3a",
"lw": 0.35,
"visible": true,
"locked": false
},
{
"code": "40",
"name": "Treppen",
"color": "#4a6a58",
"lw": 0.35,
"visible": true,
"locked": false
},
{
"code": "35",
"name": "Träger",
"color": "#a87858",
"lw": 0.5,
"visible": true,
"locked": false
},
{
"code": "50",
"name": "Text",
"color": "#d0d0d0",
"lw": 0.13,
"visible": true,
"locked": false
},
{
"code": "60",
"name": "Räume",
"color": "#5a7a9a",
"lw": 0.13,
"visible": true,
"locked": false
},
{
"code": "90",
"name": "Referenzen",
"color": "#585860",
"lw": 0.13,
"visible": true,
"locked": false
},
{
"code": "99",
"name": "Konstruktion",
"color": "#404048",
"lw": 0.13,
"visible": true,
"locked": false
}
],
"walls": [
{
"id": "W1",
"type": "wall",
"floorId": "eg",
"categoryCode": "20",
"start": {
"x": 0,
"y": 0
},
"end": {
"x": 5,
"y": 0
},
"wallTypeId": "aw",
"height": 2.6
},
{
"id": "W2",
"type": "wall",
"floorId": "eg",
"categoryCode": "20",
"start": {
"x": 5,
"y": 0
},
"end": {
"x": 5,
"y": 4
},
"wallTypeId": "aw",
"height": 2.6
},
{
"id": "W3",
"type": "wall",
"floorId": "eg",
"categoryCode": "20",
"start": {
"x": 5,
"y": 4
},
"end": {
"x": 0,
"y": 4
},
"wallTypeId": "aw",
"height": 2.6
},
{
"id": "W4",
"type": "wall",
"floorId": "eg",
"categoryCode": "20",
"start": {
"x": 0,
"y": 4
},
"end": {
"x": 0,
"y": 0
},
"wallTypeId": "aw",
"height": 2.6
},
{
"id": "W9",
"type": "wall",
"floorId": "eg",
"categoryCode": "20",
"start": {
"x": 2.4,
"y": 0
},
"end": {
"x": 2.4,
"y": 4
},
"wallTypeId": "iw",
"height": 2.6
},
{
"id": "W5",
"type": "wall",
"floorId": "og",
"categoryCode": "20",
"start": {
"x": 0,
"y": 0
},
"end": {
"x": 5,
"y": 0
},
"wallTypeId": "aw",
"height": 2.6
},
{
"id": "W6",
"type": "wall",
"floorId": "og",
"categoryCode": "20",
"start": {
"x": 5,
"y": 0
},
"end": {
"x": 5,
"y": 3
},
"wallTypeId": "aw",
"height": 2.6
},
{
"id": "W7",
"type": "wall",
"floorId": "og",
"categoryCode": "20",
"start": {
"x": 5,
"y": 3
},
"end": {
"x": 0,
"y": 3
},
"wallTypeId": "aw",
"height": 2.6
},
{
"id": "W8",
"type": "wall",
"floorId": "og",
"categoryCode": "20",
"start": {
"x": 0,
"y": 3
},
"end": {
"x": 0,
"y": 0
},
"wallTypeId": "aw",
"height": 2.6
}
],
"openings": [
{
"id": "D1",
"type": "opening",
"hostWallId": "W1",
"categoryCode": "21",
"kind": "door",
"typeId": "door-standard",
"position": 0.8,
"width": 0.9,
"height": 2.1,
"sillHeight": 0,
"swing": "left",
"hinge": "start"
},
{
"id": "O1",
"type": "opening",
"hostWallId": "W1",
"categoryCode": "21",
"kind": "window",
"typeId": "window-standard",
"position": 3,
"width": 1,
"height": 1.2,
"sillHeight": 0.9
},
{
"id": "O2",
"type": "opening",
"hostWallId": "W3",
"categoryCode": "21",
"kind": "window",
"typeId": "window-standard",
"position": 0.6,
"width": 1.4,
"height": 1.3,
"sillHeight": 0.9
}
],
"ceilings": [
{
"id": "C1",
"type": "ceiling",
"floorId": "eg",
"categoryCode": "30",
"outline": [
{
"x": 0,
"y": 0
},
{
"x": 5,
"y": 0
},
{
"x": 5,
"y": 4
},
{
"x": 0,
"y": 4
}
],
"wallTypeId": "aw",
"ceilingTypeId": "dg-massiv"
}
],
"roofs": [
{
"id": "RF1",
"type": "roof",
"floorId": "og",
"categoryCode": "31",
"outline": [
{
"x": 0,
"y": 0
},
{
"x": 5,
"y": 0
},
{
"x": 5,
"y": 4
},
{
"x": 0,
"y": 4
}
],
"shape": "sattel",
"pitchDeg": 30,
"overhang": 0.4,
"ridgeAxis": "x",
"thickness": 0.2
}
],
"stairs": [
{
"id": "ST1",
"type": "stair",
"floorId": "eg",
"categoryCode": "40",
"shape": "straight",
"typeId": "stair-standard",
"start": {
"x": 3.7,
"y": 0.4
},
"dir": {
"x": 0,
"y": 1
},
"runLength": 3.2,
"width": 1,
"totalRise": 2.6,
"stepCount": 15,
"up": true
}
],
"rooms": [
{
"id": "R1",
"type": "room",
"floorId": "eg",
"categoryCode": "60",
"siaCategory": "HNF",
"name": "Wohnen",
"boundary": [
{
"x": 0.1725,
"y": 0.1725
},
{
"x": 4.8275,
"y": 0.1725
},
{
"x": 4.8275,
"y": 3.8275
},
{
"x": 0.1725,
"y": 3.8275
}
],
"color": "#6b7280",
"stampAnchor": {
"x": 2.5,
"y": 2
}
}
],
"drawings2d": [],
"context": []
}
-200
View File
@@ -2266,206 +2266,6 @@ pub fn along(p1: Vec2, p2: Vec2, d: f64) -> Vec2 {
add(p1, scale(normalize(sub(p2, p1)), d))
}
/// Achslaenge einer Wand (Port von `wallAxisLength`; Wand → start/end).
pub fn wall_axis_length(start: Vec2, end: Vec2) -> f64 {
(end.x - start.x).hypot(end.y - start.y)
}
/// Oeffnungs-Intervall entlang der Achse (Port von `openingInterval`).
#[derive(Serialize, Deserialize, Clone, Copy, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Interval {
pub from: f64,
pub to: f64,
}
pub fn opening_interval(start: Vec2, end: Vec2, position: f64, width: f64) -> Option<Interval> {
let axis = wall_axis_length(start, end);
let from = position.min(axis).max(0.0);
let to = (position + width).min(axis).max(from);
if to - from < 1e-4 {
return None; // entartet: Breite <= 0 oder vollstaendig ausserhalb der Achse
}
Some(Interval { from, to })
}
/// Einheits-Laufrichtung (u) und linke Normale (n) der Wandachse (Port von
/// `wallAxisFrame`).
#[derive(Serialize, Deserialize, Clone, Copy, Debug)]
pub struct AxisFrame {
pub u: Vec2,
pub n: Vec2,
}
pub fn wall_axis_frame(start: Vec2, end: Vec2) -> AxisFrame {
let u = normalize(sub(end, start));
AxisFrame { u, n: left_normal(u) }
}
/// Die beiden Pfosten-Punkte einer Oeffnung im Grundriss (Port von `openingJambs`).
#[derive(Serialize, Deserialize, Clone, Copy, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Jambs {
pub jamb_start: Vec2,
pub jamb_end: Vec2,
}
pub fn opening_jambs(start: Vec2, end: Vec2, position: f64, width: f64) -> Option<Jambs> {
let iv = opening_interval(start, end, position, width)?;
Some(Jambs {
jamb_start: along(start, end, iv.from),
jamb_end: along(start, end, iv.to),
})
}
/// Luecken-Rechteck-Ecken ueber die volle Wanddicke (Port von `openingGapQuad`).
/// Reihenfolge: jambStart(+n/2) → jambEnd(+n/2) → jambEnd(−n/2) → jambStart(−n/2).
pub fn opening_gap_quad(
start: Vec2,
end: Vec2,
position: f64,
width: f64,
thickness: f64,
ref_offset: f64,
) -> Option<Vec<Vec2>> {
let jambs = opening_jambs(start, end, position, width)?;
let n = wall_axis_frame(start, end).n;
let outer = ref_offset + thickness / 2.0;
let inner = ref_offset - thickness / 2.0;
Some(vec![
add(jambs.jamb_start, scale(n, outer)),
add(jambs.jamb_end, scale(n, outer)),
add(jambs.jamb_end, scale(n, inner)),
add(jambs.jamb_start, scale(n, inner)),
])
}
/// Mittelpunkt einer Oeffnung im Grundriss (Port von `openingCenter`).
pub fn opening_center(start: Vec2, end: Vec2, position: f64, width: f64) -> Option<Vec2> {
let iv = opening_interval(start, end, position, width)?;
Some(along(start, end, (iv.from + iv.to) / 2.0))
}
/// Aufgeloeste Tuer-Symbol-Geometrie im Grundriss (Port von `DoorSymbol`).
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DoorSymbol {
pub hinge: Vec2,
pub open_end: Vec2,
pub closed_end: Vec2,
pub radius: f64,
pub jamb_start: Vec2,
pub jamb_end: Vec2,
pub normal: Vec2,
}
/// Port von `doorSymbol`. `swing`/`opening_dir`/`hinge_side` folgen der TS-
/// `??`-Fallback-Semantik (`None` → TS-Default); `swing_angle` `None` → 90°.
pub fn door_symbol(
start: Vec2,
end: Vec2,
position: f64,
width: f64,
swing: Option<&str>,
opening_dir: Option<&str>,
hinge_side: Option<&str>,
swing_angle: Option<f64>,
) -> Option<DoorSymbol> {
let jambs = opening_jambs(start, end, position, width)?;
let frame = wall_axis_frame(start, end);
let (jamb_start, jamb_end) = (jambs.jamb_start, jambs.jamb_end);
// TS berechnet die Breite NEU aus den geklemmten Pfosten (nicht das rohe
// `o.width`) — bewusst repliziert.
let w = (jamb_end.x - jamb_start.x).hypot(jamb_end.y - jamb_start.y);
let swing_sign = if swing.unwrap_or("left") == "left" { 1.0 } else { -1.0 };
let dir_sign = if opening_dir.unwrap_or("in") == "in" { 1.0 } else { -1.0 };
let swing_dir = scale(frame.n, swing_sign * dir_sign);
let hinge_at_start = hinge_side.unwrap_or("start") == "start";
let hinge = if hinge_at_start { jamb_start } else { jamb_end };
let closed_dir = if hinge_at_start { frame.u } else { scale(frame.u, -1.0) };
let angle = swing_angle.unwrap_or(90.0) * DEG;
let open_dir = Vec2 {
x: closed_dir.x * angle.cos() + swing_dir.x * angle.sin(),
y: closed_dir.y * angle.cos() + swing_dir.y * angle.sin(),
};
Some(DoorSymbol {
hinge,
open_end: add(hinge, scale(open_dir, w)),
closed_end: add(hinge, scale(closed_dir, w)),
radius: w,
jamb_start,
jamb_end,
normal: frame.n,
})
}
/// Aufgeloeste Fenster-Linien im Grundriss (Port von `WindowSymbol`).
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct WindowSymbol {
pub frame: Vec<Vec2>,
pub glass_lines: Vec<(Vec2, Vec2)>,
pub mullion_lines: Vec<(Vec2, Vec2)>,
}
/// Port von `windowSymbol`. `thickness`/`ref_offset` sind bereits aufgeloeste
/// Werte (siehe Modul-Kommentar); `wing_count` `None` → TS-Default `1`.
pub fn window_symbol(
start: Vec2,
end: Vec2,
position: f64,
width: f64,
thickness: f64,
ref_offset: f64,
glass_count: f64,
wing_count: Option<f64>,
) -> Option<WindowSymbol> {
let jambs = opening_jambs(start, end, position, width)?;
let (jamb_start, jamb_end) = (jambs.jamb_start, jambs.jamb_end);
let n = wall_axis_frame(start, end).n;
let outer = ref_offset + thickness / 2.0;
let inner = ref_offset - thickness / 2.0;
let frame_quad = vec![
add(jamb_start, scale(n, outer)),
add(jamb_end, scale(n, outer)),
add(jamb_end, scale(n, inner)),
add(jamb_start, scale(n, inner)),
];
let mut glass_lines: Vec<(Vec2, Vec2)> = Vec::new();
let count = glass_count.max(1.0);
let mut i: i64 = 0;
while (i as f64) < count {
let spread = thickness / 8.0;
let off = if count == 1.0 {
ref_offset
} else {
ref_offset + ((i as f64) - (count - 1.0) / 2.0) * spread * 2.0
};
glass_lines.push((add(jamb_start, scale(n, off)), add(jamb_end, scale(n, off))));
i += 1;
}
let mut mullion_lines: Vec<(Vec2, Vec2)> = Vec::new();
let wings = wing_count.unwrap_or(1.0).round().min(4.0).max(1.0);
if wings > 1.0 {
let post_depth = thickness * 0.6;
let p_outer = ref_offset + post_depth / 2.0;
let p_inner = ref_offset - post_depth / 2.0;
let wings_n = wings as i64;
for k in 1..wings_n {
let t = k as f64 / wings;
let on_axis = add(jamb_start, scale(sub(jamb_end, jamb_start), t));
mullion_lines.push((add(on_axis, scale(n, p_outer)), add(on_axis, scale(n, p_inner))));
}
}
Some(WindowSymbol { frame: frame_quad, glass_lines, mullion_lines })
}
#[cfg(test)]
mod tests {
use super::*;