truck: B-Rep-Kern (Extrusion mit Loechern, Ebenen-Extrusion, Rotation, Loft, Grundkoerper, B-Rep-Boolean) + STEP-Export/-Import (WASM) + Projekt-STEP-Export (Kern)

This commit is contained in:
karim committed 2026-10-23 13:13:11 +02:00
1 parent ed6bb8a3c6
commit b87451c3e5
5 files changed
+995

No files matched your search

+614
View File
@@ -0,0 +1,614 @@
// Echte B-Rep-Volumenkörper über truck (0.6): Extrusion (mit Löchern), Rotation,
// Loft, Grundkörper, Boolesche Operationen auf B-Rep-Ebene (truck-shapeops) sowie
// STEP-Export/-Import (truck-stepio). Ergebnisse werden mit truck-meshalgo zu
// Dreiecks-Meshes tesselliert (kompatibel mit `render3d::MeshInput`).
//
// Koordinaten: Modell-Meter, Z = Höhe (wie `lib.rs`). Alle Eingaben kommen als
// serde-Spezifikation ({@link SolidSpec}), damit TS ganze Bäume (Boolean über
// Extrusionen …) in EINEM Aufruf beschreiben kann.
//
// Boolesche B-Rep-Operationen sind upstream nur bei Körpern in allgemeiner Lage
// robust: bündige/koinzidente Flächen liefern `None` (s. `bool_op`) — dafür bleibt
// die Mesh-Ebenen-CSG (`boolean.rs`, csgrs) der Gebäude-Standardweg.
use serde::{Deserialize, Serialize};
use std::f64::consts::PI;
use truck_meshalgo::prelude::*;
use truck_modeling::*;
use truck_shapeops::{and, or};
use crate::MeshOutput;
/// `truck_modeling::*` bringt ein eigenes (einparametriges) `Result` mit — hier das std-Result.
type Res<T> = std::result::Result<T, String>;
/// Toleranz der B-Rep-Booleans (Meter).
const BOOL_TOL: f64 = 0.005;
/// Ein Loft-Schnitt: Höhe `z` + geschlossener Ring [x0,y0,x1,y1,…] (alle Schnitte
/// eines Lofts mit gleicher Punktanzahl).
#[derive(Deserialize, Clone, Debug)]
pub struct LoftSection {
pub z: f64,
pub points: Vec<f64>,
}
#[derive(Deserialize, Clone, Copy, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum BoolKind {
Union,
Difference,
Intersection,
}
fn default_angle() -> f64 {
360.0
}
/// Beschreibung eines Volumenkörpers.
#[derive(Deserialize, Clone, Debug)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum SolidSpec {
/// Prisma: Außenring + beliebig viele Löcher, +Z um `height`.
Extrude {
points: Vec<f64>,
#[serde(default)]
holes: Vec<Vec<f64>>,
height: f64,
#[serde(default)]
z0: f64,
},
/// Prisma in einer beliebigen Ebene: Ring/Löcher in (u,v)-Koordinaten, platziert über
/// `origin` + `uAxis`/`vAxis` (3D-Richtungen), extrudiert um `depth` entlang u×v.
/// So entstehen Wände mit Fenster-/Türöffnungen OHNE Boolean (Wandansicht als Profil).
ExtrudePlane {
points: Vec<f64>,
#[serde(default)]
holes: Vec<Vec<f64>>,
origin: [f64; 3],
#[serde(rename = "uAxis")]
u_axis: [f64; 3],
#[serde(rename = "vAxis")]
v_axis: [f64; 3],
depth: f64,
},
/// Rotationskörper: Profil = geschlossener Ring aus (r, z)-Paaren in der
/// Halbebene r ≥ 0, gedreht um die Z-Achse durch (cx, cy).
Revolve {
profile: Vec<f64>,
#[serde(default)]
cx: f64,
#[serde(default)]
cy: f64,
#[serde(default = "default_angle", rename = "angleDeg")]
angle_deg: f64,
},
/// Loft (Übergang) zwischen ≥ 2 Ringen gleicher Punktanzahl, mit ebenen Deckeln.
Loft { sections: Vec<LoftSection> },
Cuboid { min: [f64; 3], max: [f64; 3] },
Sphere { center: [f64; 3], r: f64 },
Cylinder { cx: f64, cy: f64, z0: f64, r: f64, height: f64 },
Cone { cx: f64, cy: f64, z0: f64, r: f64, height: f64 },
Torus { center: [f64; 3], major: f64, minor: f64 },
/// Boolesche Operation zweier Körper (B-Rep).
Boolean {
op: BoolKind,
a: Box<SolidSpec>,
b: Box<SolidSpec>,
},
/// Verschiebung eines Körpers.
Translate { v: [f64; 3], solid: Box<SolidSpec> },
}
fn pairs(flat: &[f64]) -> Res<Vec<(f64, f64)>> {
if flat.len() % 2 != 0 {
return Err("Punktliste muss x/y-Paare enthalten".into());
}
let mut v: Vec<(f64, f64)> = flat.chunks(2).map(|c| (c[0], c[1])).collect();
if v.len() >= 2 {
let (f, l) = (v[0], *v.last().unwrap());
if (f.0 - l.0).abs() < 1e-10 && (f.1 - l.1).abs() < 1e-10 {
v.pop();
}
}
if v.len() < 3 {
return Err("mindestens 3 eindeutige Punkte".into());
}
Ok(v)
}
fn ring_wire(ring: &[(f64, f64)], z: f64) -> Wire {
let verts: Vec<Vertex> = ring
.iter()
.map(|&(x, y)| builder::vertex(Point3::new(x, y, z)))
.collect();
let n = verts.len();
(0..n)
.map(|i| builder::line(&verts[i], &verts[(i + 1) % n]))
.collect()
}
fn signed_area(ring: &[(f64, f64)]) -> f64 {
let n = ring.len();
(0..n)
.map(|i| {
let (a, b) = (ring[i], ring[(i + 1) % n]);
a.0 * b.1 - b.0 * a.1
})
.sum::<f64>()
/ 2.0
}
/// Prisma aus Ring + Löchern. Außenring wird CCW, Löcher CW ausgerichtet.
fn extrude(points: &[f64], holes: &[Vec<f64>], height: f64, z0: f64) -> Res<Solid> {
if height <= 0.0 {
return Err("height muss > 0 sein".into());
}
let mut outer = pairs(points)?;
if signed_area(&outer) < 0.0 {
outer.reverse();
}
let mut wires = vec![ring_wire(&outer, z0)];
for h in holes {
let mut hole = pairs(h)?;
if signed_area(&hole) > 0.0 {
hole.reverse();
}
wires.push(ring_wire(&hole, z0));
}
let face = builder::try_attach_plane(&wires).map_err(|e| format!("{e}"))?;
Ok(builder::tsweep(&face, Vector3::new(0.0, 0.0, height)))
}
/// Prisma in beliebiger Ebene (s. {@link SolidSpec::ExtrudePlane}).
fn extrude_plane(
points: &[f64],
holes: &[Vec<f64>],
origin: [f64; 3],
u: [f64; 3],
v: [f64; 3],
depth: f64,
) -> Res<Solid> {
if depth == 0.0 {
return Err("depth darf nicht 0 sein".into());
}
let (uu, vv) = (Vector3::new(u[0], u[1], u[2]), Vector3::new(v[0], v[1], v[2]));
let normal = uu.cross(vv);
if normal.magnitude() < 1e-9 {
return Err("uAxis und vAxis dürfen nicht parallel sein".into());
}
let o = Point3::new(origin[0], origin[1], origin[2]);
let place = |r: &[(f64, f64)]| -> Wire {
let verts: Vec<Vertex> = r
.iter()
.map(|&(a, b)| builder::vertex(o + uu * a + vv * b))
.collect();
let n = verts.len();
(0..n).map(|i| builder::line(&verts[i], &verts[(i + 1) % n])).collect()
};
let mut outer = pairs(points)?;
if signed_area(&outer) < 0.0 {
outer.reverse(); // CCW in (u,v) ⇒ Flächennormale = u×v
}
let mut wires = vec![place(&outer)];
for h in holes {
let mut hole = pairs(h)?;
if signed_area(&hole) > 0.0 {
hole.reverse();
}
wires.push(place(&hole));
}
let face = builder::try_attach_plane(&wires).map_err(|e| format!("{e}"))?;
let dir = normal.normalize() * depth;
Ok(builder::tsweep(&face, dir))
}
fn revolve(profile: &[f64], cx: f64, cy: f64, angle_deg: f64) -> Res<Solid> {
let ring = pairs(profile)?;
if ring.iter().any(|&(r, _)| r < -1e-9) {
return Err("Profil muss in der Halbebene r >= 0 liegen".into());
}
let verts: Vec<Vertex> = ring
.iter()
.map(|&(r, z)| builder::vertex(Point3::new(r, 0.0, z)))
.collect();
let n = verts.len();
let wire: Wire = (0..n)
.map(|i| builder::line(&verts[i], &verts[(i + 1) % n]))
.collect();
let face = builder::try_attach_plane(&[wire]).map_err(|e| format!("{e}"))?;
let angle = angle_deg.to_radians().clamp(1e-3, 2.0 * PI);
let s = builder::rsweep(&face, Point3::origin(), Vector3::unit_z(), Rad(angle));
Ok(builder::translated(&s, Vector3::new(cx, cy, 0.0)))
}
fn loft(sections: &[LoftSection]) -> Res<Solid> {
if sections.len() < 2 {
return Err("Loft braucht mindestens 2 Schnitte".into());
}
let mut rings: Vec<(f64, Vec<(f64, f64)>)> = Vec::new();
for s in sections {
let mut r = pairs(&s.points)?;
if signed_area(&r) < 0.0 {
r.reverse();
}
rings.push((s.z, r));
}
let n = rings[0].1.len();
if rings.iter().any(|(_, r)| r.len() != n) {
return Err("alle Loft-Schnitte brauchen dieselbe Punktanzahl".into());
}
let wires: Vec<Wire> = rings.iter().map(|(z, r)| ring_wire(r, *z)).collect();
let mut shell = Shell::new();
for w in wires.windows(2) {
let part = builder::try_wire_homotopy(&w[0], &w[1]).map_err(|e| format!("{e}"))?;
shell.extend(part);
}
let bottom = builder::try_attach_plane(&[wires[0].clone()]).map_err(|e| format!("{e}"))?;
let top = builder::try_attach_plane(&[wires[wires.len() - 1].clone()])
.map_err(|e| format!("{e}"))?;
// Orientierung probieren: eine der vier Kappen-Kombinationen ergibt einen
// geschlossenen, orientierbaren Rand.
for (inv_b, inv_t) in [(true, false), (false, true), (false, false), (true, true)] {
let mut sh = shell.clone();
let mut b = bottom.clone();
let mut t = top.clone();
if inv_b {
b.invert();
}
if inv_t {
t.invert();
}
sh.push(b);
sh.push(t);
if let Ok(s) = Solid::try_new(vec![sh]) {
return Ok(s);
}
}
Err("Loft ergibt keinen geschlossenen Körper".into())
}
fn sphere(center: [f64; 3], r: f64) -> Res<Solid> {
if r <= 0.0 {
return Err("r muss > 0 sein".into());
}
// Wie in der truck-Doku: Halbkreis um X (Pole auf der Y-Achse), dann um Y gedreht.
let v = builder::vertex(Point3::new(0.0, r, 0.0));
let half: Wire = builder::rsweep(&v, Point3::origin(), Vector3::unit_x(), Rad(PI));
// `cone` entfernt die entarteten Pol-Kanten (rsweep würde sie als Kanten behalten).
let shell: Shell = builder::cone(&half, Vector3::unit_y(), Rad(2.0 * PI));
// Pole sind entartete Kanten: `try_new` lehnt solche Schalen ab, `new` (wie in der truck-Doku) nicht.
let s = Solid::new(vec![shell]);
Ok(builder::translated(&s, Vector3::new(center[0], center[1], center[2])))
}
fn cylinder(cx: f64, cy: f64, z0: f64, r: f64, height: f64) -> Res<Solid> {
if r <= 0.0 || height <= 0.0 {
return Err("r und height müssen > 0 sein".into());
}
let v = builder::vertex(Point3::new(r, 0.0, 0.0));
let circle: Wire = builder::rsweep(&v, Point3::origin(), Vector3::unit_z(), Rad(2.0 * PI));
let face = builder::try_attach_plane(&[circle]).map_err(|e| format!("{e}"))?;
let s = builder::tsweep(&face, Vector3::new(0.0, 0.0, height));
Ok(builder::translated(&s, Vector3::new(cx, cy, z0)))
}
fn cone(cx: f64, cy: f64, z0: f64, r: f64, height: f64) -> Res<Solid> {
// Profil: (0,0) – (r,0) – (0,h), gedreht um Z.
let s = revolve(&[0.0, 0.0, r, 0.0, 0.0, height], 0.0, 0.0, 360.0)?;
Ok(builder::translated(&s, Vector3::new(cx, cy, z0)))
}
fn torus(center: [f64; 3], major: f64, minor: f64) -> Res<Solid> {
if minor <= 0.0 || major <= minor {
return Err("Torus: major > minor > 0".into());
}
let v = builder::vertex(Point3::new(major + minor, 0.0, 0.0));
let circle: Wire = builder::rsweep(
&v,
Point3::new(major, 0.0, 0.0),
Vector3::unit_y(),
Rad(2.0 * PI),
);
let face = builder::try_attach_plane(&[circle]).map_err(|e| format!("{e}"))?;
let s: Solid = builder::rsweep(&face, Point3::origin(), Vector3::unit_z(), Rad(2.0 * PI));
Ok(builder::translated(&s, Vector3::new(center[0], center[1], center[2])))
}
fn cuboid(min: [f64; 3], max: [f64; 3]) -> Res<Solid> {
if (0..3).any(|i| max[i] - min[i] <= 0.0) {
return Err("Quader: max muss > min sein".into());
}
let v = builder::vertex(Point3::new(min[0], min[1], min[2]));
let e = builder::tsweep(&v, Vector3::new(max[0] - min[0], 0.0, 0.0));
let f = builder::tsweep(&e, Vector3::new(0.0, max[1] - min[1], 0.0));
Ok(builder::tsweep(&f, Vector3::new(0.0, 0.0, max[2] - min[2])))
}
/// Boolesche Operation auf B-Rep-Ebene (truck-shapeops). `None`-Ergebnis des
/// Upstream (typisch bei koinzidenten Flächen) wird zu einer Fehlermeldung.
pub fn bool_op(a: &Solid, b: &Solid, op: BoolKind) -> Res<Solid> {
let r = match op {
BoolKind::Union => or(a, b, BOOL_TOL),
BoolKind::Intersection => and(a, b, BOOL_TOL),
BoolKind::Difference => {
let mut inv = b.clone();
inv.not();
and(a, &inv, BOOL_TOL)
}
};
r.ok_or_else(|| {
"B-Rep-Boolean fehlgeschlagen (koinzidente/entartete Flächen — Schneidkörper überstehen lassen)"
.to_string()
})
}
/// Baut den Volumenkörper aus der Spezifikation.
pub fn build_solid(spec: &SolidSpec) -> Res<Solid> {
match spec {
SolidSpec::Extrude { points, holes, height, z0 } => extrude(points, holes, *height, *z0),
SolidSpec::ExtrudePlane { points, holes, origin, u_axis, v_axis, depth } => {
extrude_plane(points, holes, *origin, *u_axis, *v_axis, *depth)
}
SolidSpec::Revolve { profile, cx, cy, angle_deg } => revolve(profile, *cx, *cy, *angle_deg),
SolidSpec::Loft { sections } => loft(sections),
SolidSpec::Cuboid { min, max } => cuboid(*min, *max),
SolidSpec::Sphere { center, r } => sphere(*center, *r),
SolidSpec::Cylinder { cx, cy, z0, r, height } => cylinder(*cx, *cy, *z0, *r, *height),
SolidSpec::Cone { cx, cy, z0, r, height } => cone(*cx, *cy, *z0, *r, *height),
SolidSpec::Torus { center, major, minor } => torus(*center, *major, *minor),
SolidSpec::Boolean { op, a, b } => bool_op(&build_solid(a)?, &build_solid(b)?, *op),
SolidSpec::Translate { v, solid } => {
Ok(builder::translated(&build_solid(solid)?, Vector3::new(v[0], v[1], v[2])))
}
}
}
/// Tesselliert ein B-Rep-Mesh (Polygon-Mesh → Dreiecke) mit Sehnenabweichung `tol`.
pub fn mesh_of_polygon(poly: &PolygonMesh) -> MeshOutput {
let positions: Vec<f32> = poly
.positions()
.iter()
.flat_map(|p| [p.x as f32, p.y as f32, p.z as f32])
.collect();
let mut indices: Vec<u32> = Vec::new();
for t in poly.tri_faces() {
indices.extend_from_slice(&[t[0].pos as u32, t[1].pos as u32, t[2].pos as u32]);
}
for q in poly.quad_faces() {
indices.extend_from_slice(&[q[0].pos as u32, q[1].pos as u32, q[2].pos as u32]);
indices.extend_from_slice(&[q[0].pos as u32, q[2].pos as u32, q[3].pos as u32]);
}
for f in poly.other_faces() {
for i in 1..f.len().saturating_sub(1) {
indices.extend_from_slice(&[f[0].pos as u32, f[i].pos as u32, f[i + 1].pos as u32]);
}
}
MeshOutput { positions, indices }
}
pub fn mesh_of_solid(solid: &Solid, tol: f64) -> MeshOutput {
let poly = solid.triangulation(tol.max(1e-4)).to_polygon();
mesh_of_polygon(&poly)
}
/// Spezifikation → Mesh.
pub fn solid_mesh_core(spec: &SolidSpec, tol: f64) -> Res<MeshOutput> {
let solid = build_solid(spec)?;
Ok(mesh_of_solid(&solid, tol))
}
// ── STEP ─────────────────────────────────────────────────────────────────────
/// Kopfdaten der STEP-Datei.
#[derive(Deserialize, Default)]
pub struct StepHeader {
#[serde(default)]
pub file_name: String,
#[serde(default)]
pub organization_system: String,
}
/// Exportiert Körper als STEP-Datei (ISO 10303-42 B-Rep).
pub fn export_step_core(specs: &[SolidSpec], header: &StepHeader) -> Res<String> {
use truck_stepio::out::{CompleteStepDisplay, StepHeaderDescriptor, StepModels};
let solids: Vec<Solid> = specs.iter().map(build_solid).collect::<std::result::Result<_, String>>()?;
let compressed: Vec<_> = solids.iter().map(|s| s.compress()).collect();
let mut models: StepModels<'_, Point3, Curve, Surface> = StepModels::default();
for c in &compressed {
models.push_solid(c);
}
let display = CompleteStepDisplay::new(
models,
StepHeaderDescriptor {
file_name: header.file_name.clone(),
organization_system: if header.organization_system.is_empty() {
"dossier".to_owned()
} else {
header.organization_system.clone()
},
..Default::default()
},
);
Ok(display.to_string())
}
/// Ein eingelesener STEP-Körper (Shell) als Mesh.
#[derive(Serialize)]
pub struct StepMesh {
pub positions: Vec<f32>,
pub indices: Vec<u32>,
}
/// Liest eine STEP-Datei und tesselliert alle Shells (relative Toleranz `rel_tol` der
/// Bounding-Box-Diagonale, z. B. 0.001).
pub fn import_step_core(text: &str, rel_tol: f64) -> Res<Vec<StepMesh>> {
let table = truck_stepio::r#in::Table::from_step(text)
.ok_or_else(|| "STEP-Datei konnte nicht gelesen werden".to_string())?;
let mut out = Vec::new();
let mut idxs: Vec<&u64> = table.shell.keys().collect();
idxs.sort();
for idx in idxs {
let holder = &table.shell[idx];
let Ok(shell) = table.to_compressed_shell(holder) else {
continue; // nicht lesbare Shell überspringen
};
let pre = shell.triangulation(0.01).to_polygon();
let diag = pre.bounding_box().diameter();
let tol = if diag.is_finite() && diag > 0.0 { diag * rel_tol.max(1e-6) } else { 0.01 };
let mut poly = shell.triangulation(tol).to_polygon();
poly.put_together_same_attrs(TOLERANCE * 50.0)
.remove_degenerate_faces()
.remove_unused_attrs();
let m = mesh_of_polygon(&poly);
if !m.indices.is_empty() {
out.push(StepMesh { positions: m.positions, indices: m.indices });
}
}
if out.is_empty() {
return Err("keine Körper in der STEP-Datei gefunden".into());
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
fn volume(m: &MeshOutput) -> f64 {
// Gauss: Summe der signierten Tetraeder-Volumen zum Ursprung.
let p = |i: u32| {
let k = i as usize * 3;
(m.positions[k] as f64, m.positions[k + 1] as f64, m.positions[k + 2] as f64)
};
m.indices
.chunks(3)
.map(|t| {
let (a, b, c) = (p(t[0]), p(t[1]), p(t[2]));
(a.0 * (b.1 * c.2 - b.2 * c.1) - a.1 * (b.0 * c.2 - b.2 * c.0)
+ a.2 * (b.0 * c.1 - b.1 * c.0))
/ 6.0
})
.sum::<f64>()
.abs()
}
fn ring(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec<f64> {
vec![x0, y0, x1, y0, x1, y1, x0, y1]
}
#[test]
fn extrude_mit_loch_hat_richtiges_volumen() {
let spec = SolidSpec::Extrude {
points: ring(0.0, 0.0, 4.0, 3.0),
holes: vec![ring(1.0, 1.0, 2.0, 2.0)],
height: 2.0,
z0: 0.0,
};
let m = solid_mesh_core(&spec, 0.01).unwrap();
assert!((volume(&m) - (12.0 - 1.0) * 2.0).abs() < 1e-3, "{}", volume(&m));
}
#[test]
fn zylinder_und_kugel_volumen() {
let cyl = solid_mesh_core(
&SolidSpec::Cylinder { cx: 0.0, cy: 0.0, z0: 0.0, r: 1.0, height: 2.0 },
0.002,
)
.unwrap();
assert!((volume(&cyl) - PI * 2.0).abs() / (PI * 2.0) < 0.01, "{}", volume(&cyl));
let sph = solid_mesh_core(&SolidSpec::Sphere { center: [0.0; 3], r: 1.0 }, 0.002).unwrap();
assert!((volume(&sph) - 4.0 / 3.0 * PI).abs() / (4.0 / 3.0 * PI) < 0.02, "{}", volume(&sph));
}
#[test]
fn rotationskoerper_kegel() {
let c = solid_mesh_core(
&SolidSpec::Cone { cx: 0.0, cy: 0.0, z0: 0.0, r: 1.0, height: 3.0 },
0.002,
)
.unwrap();
let expect = PI * 1.0 * 3.0 / 3.0;
assert!((volume(&c) - expect).abs() / expect < 0.02, "{}", volume(&c));
}
#[test]
fn torus_volumen() {
let t = solid_mesh_core(&SolidSpec::Torus { center: [0.0; 3], major: 2.0, minor: 0.5 }, 0.002)
.unwrap();
let expect = 2.0 * PI * PI * 2.0 * 0.5 * 0.5;
assert!((volume(&t) - expect).abs() / expect < 0.02, "{}", volume(&t));
}
#[test]
fn loft_quadrat_zu_quadrat_ist_pyramidenstumpf() {
let spec = SolidSpec::Loft {
sections: vec![
LoftSection { z: 0.0, points: ring(0.0, 0.0, 2.0, 2.0) },
LoftSection { z: 3.0, points: ring(0.5, 0.5, 1.5, 1.5) },
],
};
let m = solid_mesh_core(&spec, 0.01).unwrap();
// Pyramidenstumpf: h/3 (A1 + A2 + sqrt(A1 A2)) = 1 * (4 + 1 + 2)
assert!((volume(&m) - 7.0).abs() < 1e-3, "{}", volume(&m));
}
#[test]
fn boolean_wand_minus_fenster_ueberstehend() {
let wall = SolidSpec::Cuboid { min: [0.0, 0.0, 0.0], max: [5.0, 0.3, 2.6] };
let win = SolidSpec::Cuboid { min: [1.0, -0.1, 0.9], max: [2.2, 0.4, 2.1] };
let spec = SolidSpec::Boolean { op: BoolKind::Difference, a: Box::new(wall), b: Box::new(win) };
let m = solid_mesh_core(&spec, 0.01).unwrap();
let expect = 5.0 * 0.3 * 2.6 - 1.2 * 0.3 * 1.2;
assert!((volume(&m) - expect).abs() < 1e-3, "{}", volume(&m));
}
#[test]
fn boolean_bei_koinzidenten_flaechen_meldet_fehler() {
let wall = SolidSpec::Cuboid { min: [0.0, 0.0, 0.0], max: [5.0, 0.3, 2.6] };
let win = SolidSpec::Cuboid { min: [1.0, 0.0, 0.9], max: [2.2, 0.3, 2.1] };
let spec = SolidSpec::Boolean { op: BoolKind::Difference, a: Box::new(wall), b: Box::new(win) };
assert!(solid_mesh_core(&spec, 0.01).is_err());
}
/// Wand 5 × 2,6 m, 0,3 m dick, mit Fenster 1,2 × 1,2 m als Loch im Wandprofil.
fn wand_mit_fenster() -> SolidSpec {
SolidSpec::ExtrudePlane {
points: vec![0.0, 0.0, 5.0, 0.0, 5.0, 2.6, 0.0, 2.6],
holes: vec![vec![1.0, 0.9, 2.2, 0.9, 2.2, 2.1, 1.0, 2.1]],
origin: [0.0, 0.0, 0.0],
u_axis: [1.0, 0.0, 0.0],
v_axis: [0.0, 0.0, 1.0],
depth: -0.3, // u×v = −Y; negativ ⇒ +Y
}
}
#[test]
fn wand_mit_fensterloch_ohne_boolean_hat_das_richtige_volumen() {
let m = solid_mesh_core(&wand_mit_fenster(), 0.01).unwrap();
let expect = (5.0 * 2.6 - 1.2 * 1.2) * 0.3;
assert!((volume(&m) - expect).abs() < 1e-3, "{}", volume(&m));
}
#[test]
fn step_roundtrip_erhaelt_das_volumen() {
let step = export_step_core(&[wand_mit_fenster()], &StepHeader::default()).unwrap();
assert!(step.starts_with("ISO-10303-21;"));
let back = import_step_core(&step, 0.001).unwrap();
assert_eq!(back.len(), 1);
let m = MeshOutput { positions: back[0].positions.clone(), indices: back[0].indices.clone() };
let expect = (5.0 * 2.6 - 1.2 * 1.2) * 0.3;
assert!((volume(&m) - expect).abs() < 0.01, "{}", volume(&m));
}
#[test]
fn extrude_json_spezifikation_wird_gelesen() {
let json = r#"{"kind":"extrude","points":[0,0,1,0,1,1,0,1],"height":2}"#;
let spec: SolidSpec = serde_json::from_str(json).unwrap();
assert!(solid_mesh_core(&spec, 0.01).is_ok());
let rev = r#"{"kind":"revolve","profile":[0,0,1,0,1,1,0,1],"angleDeg":180}"#;
let spec: SolidSpec = serde_json::from_str(rev).unwrap();
assert!(solid_mesh_core(&spec, 0.01).is_ok());
}
}
+47
View File
@@ -12,6 +12,7 @@ use serde::{Deserialize, Serialize};
use truck_modeling::*;
mod boolean;
pub mod brep;
pub use boolean::{boolean_mesh_core, BooleanMeshInput, BooleanMeshOutput};
/// Flaches [x0,y0, x1,y1, …] Array + Höhe → Extrusion.
@@ -358,6 +359,52 @@ mod web {
serde_json::to_string(&mesh).map_err(|e| JsError::new(&e.to_string()))
}
/// B-Rep-Körper aus einer Spezifikation (s. `brep::SolidSpec`) → Mesh.
/// Input JSON: `{ "spec": {kind:"extrude",…}, "tol": 0.01 }`
#[wasm_bindgen]
pub fn build_solid_mesh(input_json: &str) -> std::result::Result<String, JsError> {
#[derive(serde::Deserialize)]
struct In {
spec: brep::SolidSpec,
#[serde(default = "default_tol")]
tol: f64,
}
fn default_tol() -> f64 {
0.01
}
let i: In = serde_json::from_str(input_json).map_err(|e| JsError::new(&e.to_string()))?;
let mesh = brep::solid_mesh_core(&i.spec, i.tol).map_err(|e| JsError::new(&e))?;
serde_json::to_string(&mesh).map_err(|e| JsError::new(&e.to_string()))
}
/// Exportiert Körper als STEP-Text (ISO 10303-42).
/// Input JSON: `{ "solids": [spec, …], "fileName": "haus.stp", "organizationSystem": "dossier" }`
#[wasm_bindgen]
pub fn export_step(input_json: &str) -> std::result::Result<String, JsError> {
#[derive(serde::Deserialize)]
struct In {
solids: Vec<brep::SolidSpec>,
#[serde(default, rename = "fileName")]
file_name: String,
#[serde(default, rename = "organizationSystem")]
organization_system: String,
}
let i: In = serde_json::from_str(input_json).map_err(|e| JsError::new(&e.to_string()))?;
brep::export_step_core(
&i.solids,
&brep::StepHeader { file_name: i.file_name, organization_system: i.organization_system },
)
.map_err(|e| JsError::new(&e))
}
/// Liest STEP-Text und tesselliert alle Körper (`relTol` = Toleranz relativ zur
/// Bounding-Box-Diagonale, Default 0.001). Output JSON: `[{positions, indices}, …]`.
#[wasm_bindgen]
pub fn import_step(text: &str, rel_tol: f64) -> std::result::Result<String, JsError> {
let meshes = brep::import_step_core(text, rel_tol).map_err(|e| JsError::new(&e))?;
serde_json::to_string(&meshes).map_err(|e| JsError::new(&e.to_string()))
}
/// Boolesche Operation zwischen zwei Dreiecks-Meshes (Mesh-Ebenen-CSG via
/// csgrs). Input JSON: `{ "a_positions": […], "a_indices": […],
/// "b_positions": […], "b_indices": […], "op": "union"|"difference"|"intersection" }`
+55
View File
@@ -68,3 +68,58 @@ export async function booleanMesh(
);
return JSON.parse(json) as BooleanMeshResult;
}
// ── B-Rep-Körper (truck 0.6): Spezifikation → Mesh / STEP ────────────────────
/** Ein Loft-Schnitt: Höhe + geschlossener Ring [x0,y0,x1,y1,…]. */
export interface LoftSectionSpec {
z: number;
points: number[];
}
/**
* Beschreibung eines Volumenkörpers (1:1 `brep::SolidSpec` in `trucksolid`). Koordinaten
* in Modell-Metern, Z = Höhe. `Boolean` arbeitet auf B-Rep-Ebene und scheitert bei
* bündigen Flächen — Schneidkörper überstehen lassen, oder `ExtrudePlane` mit Loch nutzen.
*/
export type SolidSpec =
| { kind: "extrude"; points: number[]; holes?: number[][]; height: number; z0?: number }
| {
kind: "extrudePlane";
points: number[];
holes?: number[][];
origin: [number, number, number];
uAxis: [number, number, number];
vAxis: [number, number, number];
depth: number;
}
| { kind: "revolve"; profile: number[]; cx?: number; cy?: number; angleDeg?: number }
| { kind: "loft"; sections: LoftSectionSpec[] }
| { kind: "cuboid"; min: [number, number, number]; max: [number, number, number] }
| { kind: "sphere"; center: [number, number, number]; r: number }
| { kind: "cylinder"; cx: number; cy: number; z0: number; r: number; height: number }
| { kind: "cone"; cx: number; cy: number; z0: number; r: number; height: number }
| { kind: "torus"; center: [number, number, number]; major: number; minor: number }
| { kind: "boolean"; op: "union" | "difference" | "intersection"; a: SolidSpec; b: SolidSpec }
| { kind: "translate"; v: [number, number, number]; solid: SolidSpec };
/** Tesselliert einen B-Rep-Körper (Sehnenabweichung `tol` Meter). */
export async function buildSolidMesh(spec: SolidSpec, tol = 0.01): Promise<ExtrudedMesh> {
const m = await getModule();
return JSON.parse(m.build_solid_mesh(JSON.stringify({ spec, tol }))) as ExtrudedMesh;
}
/** Exportiert Körper als STEP-Text (ISO 10303-42 B-Rep). */
export async function exportStepSolids(
solids: SolidSpec[],
fileName = "",
): Promise<string> {
const m = await getModule();
return m.export_step(JSON.stringify({ solids, fileName, organizationSystem: "dossier" }));
}
/** Liest STEP-Text und liefert je Körper ein Dreiecks-Mesh (`relTol` relativ zur Diagonale). */
export async function importStepMeshes(text: string, relTol = 0.001): Promise<ExtrudedMesh[]> {
const m = await getModule();
return JSON.parse(m.import_step(text, relTol)) as ExtrudedMesh[];
}
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { sampleProject } from "../model/sampleProject";
import { projectSolidSpecs, wallProfile } from "./exportStep";
describe("wallProfile", () => {
it("Fenster im Inneren wird zum Loch, Tür am Wandfuss zur Kerbe im Aussenring", () => {
const p = wallProfile(5, 2.6, [
{ from: 1, to: 2.2, zBottom: 0.9, zTop: 2.1 }, // Fenster
{ from: 3, to: 3.9, zBottom: 0, zTop: 2.1 }, // Tür
], 0);
expect(p.holes).toHaveLength(1);
expect(p.holes[0]).toEqual([1, 0.9, 2.2, 0.9, 2.2, 2.1, 1, 2.1]);
// Aussenring: Start, Kerbe (4 Punkte), Ecken rechts/oben
expect(p.outer).toEqual([0, 0, 3, 0, 3, 2.1, 3.9, 2.1, 3.9, 0, 5, 0, 5, 2.6, 0, 2.6]);
});
it("überlappende Kerben werden zusammengefasst, Öffnungen ausserhalb der Wand geklemmt", () => {
const p = wallProfile(4, 2.5, [
{ from: 1, to: 2, zBottom: 0, zTop: 2 },
{ from: 1.8, to: 3, zBottom: 0, zTop: 2.2 },
{ from: 3.9, to: 6, zBottom: 0, zTop: 2 },
], 0);
expect(p.outer.slice(0, 10)).toEqual([0, 0, 1, 0, 1, 2.2, 3, 2.2, 3, 0]);
});
it("Öffnung bis zum Wandkopf wird um 1 mm gekappt (kein Randkontakt)", () => {
const p = wallProfile(5, 2.6, [{ from: 1, to: 2, zBottom: 1, zTop: 2.6 }], 0);
expect(p.holes[0][5]).toBeCloseTo(2.599, 6);
});
});
describe("projectSolidSpecs", () => {
it("Demo-Haus liefert Wände, Decke, Dach und Treppe als B-Rep-Spezifikationen", () => {
const specs = projectSolidSpecs(sampleProject);
const kinds = specs.reduce<Record<string, number>>((m, s) => ((m[s.kind] = (m[s.kind] ?? 0) + 1), m), {});
expect(kinds.extrudePlane).toBeGreaterThan(10); // Wandlagen + Dachflächen
expect(kinds.extrude).toBeGreaterThan(0); // Decke + Tritte
});
});
describe("STEP-Export Ende-zu-Ende (truck-WASM)", () => {
it("Demo-Haus → STEP-Text → wieder einlesbar, ISO-Kopf, Körper vorhanden", async () => {
const mod: any = await import("../engine/pkgTruck/trucksolid.js");
await mod.default({ module_or_path: readFileSync("src/engine/pkgTruck/trucksolid_bg.wasm") });
const specs = projectSolidSpecs(sampleProject);
const step: string = mod.export_step(JSON.stringify({ solids: specs, fileName: "demo.stp" }));
expect(step.startsWith("ISO-10303-21;")).toBe(true);
const back = JSON.parse(mod.import_step(step, 0.002)) as Array<{ positions: number[]; indices: number[] }>;
expect(back.length).toBeGreaterThan(5);
expect(back.every((m) => m.indices.length >= 12)).toBe(true);
}, 60_000);
});
+226
View File
@@ -0,0 +1,226 @@
// STEP-Export (ISO 10303-42 B-Rep) des Gebäudemodells über truck (trucksolid-WASM).
//
// Reiner Kern: `projectSolidSpecs(project)` liefert die Körper als {@link SolidSpec}
// (kein WASM, testbar), `exportProjectStep` serialisiert sie über truck-stepio.
//
// • Wände: je Materiallage ein Körper. Das Wandprofil (Achse × Höhe) wird mit den
// Öffnungen als Löcher bzw. Kerben (Türen am Wandfuss) in der Wandebene gebildet und
// um die Lagendicke extrudiert — OHNE Boolean (B-Rep-Booleans scheitern an den
// bündigen Laibungsflächen). Gehrungen/Anschlüsse stecken schon in `start`/`end`.
// • Decken + Treppentritte: Umriss-Prisma zwischen `zBottom` und `zTop`.
// • Dächer: je Dachfläche eine Platte der Gesamt-Schichtdicke (nach unten).
// • Extrusionen: Prisma bzw. verjüngter Körper (Loft) des Profils.
//
// Koordinaten: Modell-Meter, X/Y = Grundriss, Z = Höhe (wie die Eingabe von render3d).
import type { Project } from "../model/types";
import { getFloor, roofLayers } from "../model/types";
import { projectToModel3d } from "../plan/toWalls3d";
import type { RWall } from "../plan/toWalls3d";
import { roofBaseElevation, roofGeometry } from "../geometry/roof";
import { exportStepSolids } from "../engine/truckSolid";
import type { SolidSpec } from "../engine/truckSolid";
const EPS = 1e-6;
/** Schicht/Öffnung so dünn, dass sie als nicht vorhanden gilt. */
const MIN_THICKNESS = 1e-4;
/**
* Wandprofil (u = Achse, v = Höhe über Wandfuss) mit Öffnungen: Löcher, die ganz im Profil
* liegen; Öffnungen am Wandfuss (Türen) als Kerben im Aussenring. Öffnungen am Wandkopf
* werden um 1 mm gekappt (ein Loch darf den Rand nicht berühren).
*/
export function wallProfile(
length: number,
height: number,
holes: Array<{ from: number; to: number; zBottom: number; zTop: number }>,
baseElevation: number,
): { outer: number[]; holes: number[][] } {
const inner: number[][] = [];
const notches: Array<[number, number, number]> = []; // [from, to, top]
const cut = 1e-3;
for (const h of holes) {
const u0 = Math.max(0, Math.min(length, h.from));
const u1 = Math.max(0, Math.min(length, h.to));
if (u1 - u0 < MIN_THICKNESS) continue;
const v0 = h.zBottom - baseElevation;
const v1 = Math.min(height - cut, h.zTop - baseElevation);
if (v1 - Math.max(v0, 0) < MIN_THICKNESS) continue;
if (v0 <= cut) notches.push([u0, u1, v1]);
else inner.push([u0, v0, u1, v0, u1, v1, u0, v1]);
}
// Kerben sortieren und überlappende zusammenfassen.
notches.sort((a, b) => a[0] - b[0]);
const merged: Array<[number, number, number]> = [];
for (const n of notches) {
const last = merged[merged.length - 1];
if (last && n[0] <= last[1] + EPS) {
last[1] = Math.max(last[1], n[1]);
last[2] = Math.max(last[2], n[2]);
} else merged.push([...n]);
}
// Aussenring CCW in (u,v): Wandfuss links→rechts mit Kerben, dann Kopf rechts→links.
const outer: number[] = [0, 0];
for (const [a, b, top] of merged) {
outer.push(a, 0, a, top, b, top, b, 0);
}
outer.push(length, 0, length, height, 0, height);
return { outer, holes: inner };
}
function wallSpec(w: RWall): SolidSpec | null {
const dx = w.end[0] - w.start[0];
const dy = w.end[1] - w.start[1];
const len = Math.hypot(dx, dy);
if (len < MIN_THICKNESS || w.height < MIN_THICKNESS || w.thickness < MIN_THICKNESS) return null;
const ux = dx / len;
const uy = dy / len;
// u × v (v = +Z) = (uy, −ux, 0): Extrusionsrichtung. Ursprung = eine Wandfläche.
const nx = uy;
const ny = -ux;
const prof = wallProfile(len, w.height, w.holes ?? [], w.baseElevation);
return {
kind: "extrudePlane",
points: prof.outer,
holes: prof.holes,
origin: [
w.start[0] - (nx * w.thickness) / 2,
w.start[1] - (ny * w.thickness) / 2,
w.baseElevation,
],
uAxis: [ux, uy, 0],
vAxis: [0, 0, 1],
depth: w.thickness,
};
}
/** Alle Bauteile des Projekts als B-Rep-Spezifikationen (reiner Kern, kein WASM). */
export function projectSolidSpecs(project: Project): SolidSpec[] {
const out: SolidSpec[] = [];
const model = projectToModel3d(project, { layeredWalls: true });
for (const w of model.walls) {
const s = wallSpec(w);
if (s) out.push(s);
}
for (const s of model.slabs) {
if (s.outline.length < 3 || s.zTop - s.zBottom < MIN_THICKNESS) continue;
out.push({
kind: "extrude",
points: s.outline.flatMap((p) => [p[0], p[1]]),
height: s.zTop - s.zBottom,
z0: s.zBottom,
});
}
for (const roof of project.roofs ?? []) {
const total = roofLayers(project, roof).reduce((sum, l) => sum + Math.max(0, l.thickness), 0);
if (total < MIN_THICKNESS) continue;
const g = roofGeometry(roof, roofBaseElevation(project, roof));
for (const pl of g.planes) {
const p = pl.pts;
if (p.length < 3) continue;
// Lokales Koordinatensystem der (ebenen, konvexen) Dachfläche.
const e1 = sub(p[1], p[0]);
const e2 = sub(p[2], p[0]);
let n = cross(e1, e2);
const nl = Math.hypot(n[0], n[1], n[2]);
if (nl < EPS) continue;
n = [n[0] / nl, n[1] / nl, n[2] / nl];
if (n[2] < 0) n = [-n[0], -n[1], -n[2]]; // Normale nach oben
const el = Math.hypot(e1[0], e1[1], e1[2]);
const u: [number, number, number] = [e1[0] / el, e1[1] / el, e1[2] / el];
const v = cross(n, u); // u × v = n
out.push({
kind: "extrudePlane",
points: p.flatMap((q) => {
const d = sub(q, p[0]);
return [dot(d, u), dot(d, v)];
}),
origin: [p[0][0], p[0][1], p[0][2]],
uAxis: u,
vAxis: [v[0], v[1], v[2]],
depth: -total, // nach unten (Eindeckung oben)
});
}
}
for (const solid of project.extrudedSolids ?? []) {
if (solid.points.length < 3 || solid.height <= 0) continue;
let baseZ = 0;
if (solid.levelId) {
try {
baseZ = getFloor(project, solid.levelId).baseElevation ?? 0;
} catch {
baseZ = 0;
}
}
const taper = Math.min(1, Math.max(0, solid.taper ?? 0));
const flat = solid.points.flatMap((p) => [p.x, p.y]);
if (taper < 1e-6) {
out.push({ kind: "extrude", points: flat, height: solid.height, z0: baseZ });
} else if (taper < 1 - 1e-6) {
// Verjüngung: oberer Ring linear zum Schwerpunkt skaliert (Loft Boden → Kopf).
const cx = solid.points.reduce((s, p) => s + p.x, 0) / solid.points.length;
const cy = solid.points.reduce((s, p) => s + p.y, 0) / solid.points.length;
const top = solid.points.flatMap((p) => [
cx + (p.x - cx) * (1 - taper),
cy + (p.y - cy) * (1 - taper),
]);
out.push({
kind: "loft",
sections: [
{ z: baseZ, points: flat },
{ z: baseZ + solid.height, points: top },
],
});
}
}
return out;
}
type V3 = [number, number, number];
const sub = (a: ArrayLike<number>, b: ArrayLike<number>): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
const dot = (a: ArrayLike<number>, b: ArrayLike<number>): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a: ArrayLike<number>, b: ArrayLike<number>): V3 => [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
/** Ergebnis des Projekt-Exports. */
export interface StepExportResult {
text: string;
/** Anzahl exportierter Körper. */
count: number;
/** Körper, die truck nicht bauen konnte (Index + Meldung) — beim Export übersprungen. */
skipped: Array<{ index: number; error: string }>;
}
/**
* Exportiert das Projekt als STEP-Text. Körper, die truck nicht bauen kann (entartete
* Profile …), werden einzeln übersprungen statt den ganzen Export zu verwerfen.
*/
export async function exportProjectStep(project: Project, fileName = ""): Promise<StepExportResult> {
const specs = projectSolidSpecs(project);
const good: SolidSpec[] = [];
const skipped: StepExportResult["skipped"] = [];
// Erst alle zusammen versuchen (Normalfall); nur bei Fehler einzeln prüfen.
try {
const text = await exportStepSolids(specs, fileName || project.name);
return { text, count: specs.length, skipped };
} catch {
/* einzeln weiter */
}
for (let i = 0; i < specs.length; i++) {
try {
await exportStepSolids([specs[i]], "");
good.push(specs[i]);
} catch (e) {
skipped.push({ index: i, error: e instanceof Error ? e.message : String(e) });
}
}
const text = await exportStepSolids(good, fileName || project.name);
return { text, count: good.length, skipped };
}