Files
DOSSIER/src-tauri/core/src/highlight3d.rs
T

451 lines
20 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Umriss-Linien der 3D-Auswahl (früher `selectionHighlightLines` in `plan/toWalls3d.ts`): je
//! gewähltes Bauteil die Kanten seiner Hülle als Linienliste `[x, y, z, r, g, b] × 2` (Welt-Meter,
//! y = Höhe), die der 3D-Viewport ohne Tiefentest obenauf zeichnet. Wände/Öffnungen als Quader,
//! Decken/Treppen als Prisma, Dächer als Flächen-/Giebel-Umrisse, freie Körper und importierte Netze als Feature-Kanten
//! (Randkanten + Knick > 15°, [115]), Gelände als Hüllquader.
//! Rechnung und Reihenfolge wie die TS-Fassung (f32 wie `Float32Array`).
use crate::jsmath::hypot2;
use crate::model::{ContextObject, Project};
use crate::model3d::{emit_slabs, emit_walls, pick_openings, pick_stairs};
use std::collections::{HashMap, HashSet};
const EPS: f64 = 1e-4;
/// Grösste Dreieckszahl eines importierten Netzes, dessen Feature-Kanten berechnet werden (sonst Hüllquader).
const MAX_EDGE_TRIS: usize = 200_000;
type V3 = [f64; 3];
/// Gewählte ids je Art und Linienfarbe.
#[derive(serde::Deserialize, Default)]
#[serde(default)]
pub struct Args {
pub walls: Vec<String>,
pub ceilings: Vec<String>,
pub openings: Vec<String>,
pub stairs: Vec<String>,
pub roofs: Vec<String>,
pub context: Vec<String>,
/// [137] Stützen (Prisma über dem Grundriss) und freie Körper ([115]: Feature-Kanten des Kern-Netzes).
pub columns: Vec<String>,
pub solids: Vec<String>,
/// [149] Bäume (Umriss-Prisma Kronendurchmesser × Fuss bis Spitze).
pub trees: Vec<String>,
pub rgb: [f64; 3],
/// Explosionsabstand ([65], `explode3d.rs`; fehlt/0 = aus): Linien folgen dem auseinandergezogenen Modell.
#[serde(default)]
pub explode: f64,
}
const BOX_EDGES: [(usize, usize); 12] = [(0, 1), (0, 2), (0, 4), (1, 3), (1, 5), (2, 3), (2, 6), (3, 7), (4, 5), (4, 6), (5, 7), (6, 7)];
struct Out {
v: Vec<f32>,
rgb: [f64; 3],
}
impl Out {
fn edge(&mut self, a: V3, b: V3) {
let c = self.rgb;
for q in [a, b] {
self.v.extend([q[0], q[1], q[2], c[0], c[1], c[2]].map(|x| x as f32));
}
}
/// Quader um die Achse `start → end` (Dicke quer, Höhe ab `base`).
fn box_edges(&mut self, start: [f64; 2], end: [f64; 2], thickness: f64, height: f64, base: f64) {
let ax = end[0] - start[0];
let az = end[1] - start[1];
let len = hypot2(ax, az);
if len < EPS || height <= EPS || thickness <= EPS {
return;
}
let axis = [ax / len, 0.0, az / len];
let normal = [az / len, 0.0, -ax / len];
let half_len = len / 2.0;
let half_height = height / 2.0;
let half_thick = thickness / 2.0;
let center = [(start[0] + end[0]) / 2.0, base + height / 2.0, (start[1] + end[1]) / 2.0];
let mut corners = [[0.0; 3]; 8];
for (i, c) in corners.iter_mut().enumerate() {
let s_l = if i & 1 != 0 { 1.0 } else { -1.0 };
let s_h = if i & 2 != 0 { 1.0 } else { -1.0 };
let s_t = if i & 4 != 0 { 1.0 } else { -1.0 };
*c = [
center[0] + s_l * half_len * axis[0] + s_t * half_thick * normal[0],
center[1] + s_h * half_height,
center[2] + s_l * half_len * axis[2] + s_t * half_thick * normal[2],
];
}
for (i, j) in BOX_EDGES {
self.edge(corners[i], corners[j]);
}
}
/// Achsparalleler Hüllquader um Welt-Punkte (nichts bei leerer Menge).
fn aabb_edges<'a>(&mut self, pts: impl Iterator<Item = &'a V3>) {
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
for q in pts {
for k in 0..3 {
lo[k] = lo[k].min(q[k]);
hi[k] = hi[k].max(q[k]);
}
}
if !lo[0].is_finite() {
return;
}
let mut c = [[0.0; 3]; 8];
for (i, v) in c.iter_mut().enumerate() {
*v = [if i & 1 != 0 { hi[0] } else { lo[0] }, if i & 2 != 0 { hi[1] } else { lo[1] }, if i & 4 != 0 { hi[2] } else { lo[2] }];
}
for (i, j) in BOX_EDGES {
self.edge(c[i], c[j]);
}
}
/// [115] Feature-Kanten eines Dreiecksnetzes (Modell-Meter, z = Höhe), wie render3d sie zeichnet: Randkanten
/// (ein Dreieck) und Kanten, an denen zwei Flächen mehr als 15° knicken; koplanare Diagonalen und
/// Facettenfugen glatter Rundungen fallen weg. Reihenfolge der Dreiecke (deterministisch).
fn mesh_edges(&mut self, positions: &[f64], indices: &[u32]) {
let nv = positions.len() / 3;
let key = |i: usize| -> [i64; 3] { let q = &positions[i * 3..i * 3 + 3]; [(q[0] * 1e6).round() as i64, (q[1] * 1e6).round() as i64, (q[2] * 1e6).round() as i64] };
let mut ids: HashMap<[i64; 3], usize> = HashMap::new();
let canon: Vec<usize> = (0..nv).map(|i| { let n = ids.len(); *ids.entry(key(i)).or_insert(n) }).collect();
let mut at: HashMap<(usize, usize), usize> = HashMap::new();
let mut edges: Vec<(usize, usize, Vec<V3>)> = Vec::new();
for t in indices.chunks_exact(3) {
let v: Vec<usize> = t.iter().map(|&i| i as usize).collect();
if v.iter().any(|&i| i >= nv) {
continue;
}
let p = |i: usize| [positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]];
let (a, b, c) = (p(v[0]), p(v[1]), p(v[2]));
let (u, w) = ([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]);
let n = [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]];
let l = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
if !(l > 1e-18) {
continue; // entartet
}
let n = [n[0] / l, n[1] / l, n[2] / l];
for (i, j) in [(0, 1), (1, 2), (2, 0)] {
let (ci, cj) = (canon[v[i]], canon[v[j]]);
if ci == cj {
continue;
}
let k = (ci.min(cj), ci.max(cj));
let e = *at.entry(k).or_insert_with(|| { edges.push((v[i], v[j], Vec::new())); edges.len() - 1 });
edges[e].2.push(n);
}
}
const CREASE_COS: f64 = 0.966; // 15°, wie render3d
let world = |i: usize| [positions[i * 3], positions[i * 3 + 2], positions[i * 3 + 1]];
for (i, j, ns) in &edges {
let draw = ns.len() == 1 || ns.iter().enumerate().any(|(x, a)| ns[x + 1..].iter().any(|b| a[0] * b[0] + a[1] * b[1] + a[2] * b[2] < CREASE_COS));
if draw {
self.edge(world(*i), world(*j));
}
}
}
/// Prisma über dem Grundriss `outline` von `z_bottom` bis `z_top`.
fn prism_edges(&mut self, outline: &[[f64; 2]], z_bottom: f64, z_top: f64) {
let n = outline.len();
if n < 3 || z_top - z_bottom <= EPS {
return;
}
let bottom = |i: usize| [outline[i][0], z_bottom, outline[i][1]];
let top = |i: usize| [outline[i][0], z_top, outline[i][1]];
let mut j = n - 1;
for i in 0..n {
self.edge(bottom(j), bottom(i));
self.edge(top(j), top(i));
j = i;
}
for i in 0..n {
self.edge(bottom(i), top(i));
}
}
}
fn set(ids: &[String]) -> HashSet<&str> {
ids.iter().map(String::as_str).collect()
}
/// Linienliste der Hervorhebung (leer, wenn nichts gewählt ist).
pub fn selection_highlight_lines(p: &Project, a: &Args) -> Result<Vec<f32>, String> {
let mut out = Out { v: Vec::new(), rgb: a.rgb };
// Explosionsaxonometrie: die Linien eines Bauteils ab Puffer-Index `from` um seinen Geschoss-Versatz heben (Welt-y).
let ex = crate::explode3d::Explode::new(p, a.explode);
let lift = |out: &mut Out, from: usize, id: &str| {
let dz = ex.as_ref().map_or(0.0, |e| e.of(id)) as f32;
if dz != 0.0 {
for v in out.v[from..].chunks_exact_mut(6) {
v[1] += dz;
}
}
};
let (walls, ceilings, openings, stairs, roofs, context) = (set(&a.walls), set(&a.ceilings), set(&a.openings), set(&a.stairs), set(&a.roofs), set(&a.context));
if !walls.is_empty() {
for w in emit_walls(p, true)? {
if walls.contains(w.wall_id.as_str()) {
let n = out.v.len();
out.box_edges(w.start, w.end, w.thickness, w.height, w.base_elevation);
lift(&mut out, n, &w.wall_id);
}
}
}
if !openings.is_empty() {
for o in pick_openings(p) {
if openings.contains(o.opening_id.as_str()) {
let n = out.v.len();
out.box_edges(o.start, o.end, o.thickness, o.height, o.base_elevation);
lift(&mut out, n, &o.opening_id);
}
}
}
// [137] Öffnungen in Dach/Decke/Gaube: Hüllquader ihrer Teile.
if !openings.is_empty() {
for m in crate::model3d::pick_hosted_openings(p) {
if openings.contains(m.opening_id.as_str()) {
let n = out.v.len();
out.aabb_edges(m.tris.iter().flatten());
lift(&mut out, n, &m.opening_id);
}
}
}
if !ceilings.is_empty() {
for s in emit_slabs(p) {
if ceilings.contains(s.ceiling_id.as_str()) {
let n = out.v.len();
out.prism_edges(&s.outline, s.z_bottom, s.z_top);
lift(&mut out, n, &s.ceiling_id);
}
}
}
if !stairs.is_empty() {
for st in pick_stairs(p) {
if stairs.contains(st.stair_id.as_str()) {
let n = out.v.len();
out.prism_edges(&st.outline, st.z_bottom, st.z_top);
lift(&mut out, n, &st.stair_id);
}
}
}
if !roofs.is_empty() {
for roof in p.roofs.as_deref().unwrap_or(&[]) {
if !roofs.contains(roof.id.as_str()) {
continue;
}
let g = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof));
let n = out.v.len();
for pts in g.planes.iter().chain(g.gables.iter()) {
let m = pts.len();
if m == 0 {
continue;
}
let mut j = m - 1;
for i in 0..m {
let (q, r) = (pts[j], pts[i]);
out.edge([q[0], q[2], q[1]], [r[0], r[2], r[1]]);
j = i;
}
}
lift(&mut out, n, &roof.id);
}
}
let (columns, solids) = (set(&a.columns), set(&a.solids));
for col in p.columns.as_deref().unwrap_or(&[]) {
if columns.contains(col.id.as_str()) {
let (z0, z1) = p.column_vertical_extent(col);
let foot: Vec<[f64; 2]> = crate::model3d::column_footprint(col).iter().map(|q| [q.x, q.y]).collect();
let n = out.v.len();
out.prism_edges(&foot, z0, z1);
lift(&mut out, n, &col.id);
}
}
let trees = set(&a.trees);
if !trees.is_empty() {
let list = p.trees.as_deref().unwrap_or(&[]);
for (i, g) in crate::tree::geoms(p) {
if trees.contains(list[i].id.as_str()) {
let n = out.v.len();
out.prism_edges(&crate::tree::circle(g.c, g.crown_r, 12), g.base, g.top);
lift(&mut out, n, &list[i].id);
}
}
}
for s in p.extruded_solids.as_deref().unwrap_or(&[]) {
if solids.contains(s.id.as_str()) {
let n = out.v.len();
// [115] echte Kanten des Kern-Netzes; ohne Netz (kaputte Beschreibung) bleibt das Prisma.
match crate::solid_mesh::body_mesh_3d(p, s).as_deref().and_then(|m| m.as_ref()) {
Some(m) => out.mesh_edges(&m.positions, &m.indices),
None => {
let z0 = crate::model3d::solid_base_z(p, s);
let foot: Vec<[f64; 2]> = s.points.iter().map(|q| [q.x, q.y]).collect();
out.prism_edges(&foot, z0, z0 + s.height);
}
}
lift(&mut out, n, &s.id);
}
}
if !context.is_empty() {
for obj in p.context.as_deref().unwrap_or(&[]) {
let (pos, id) = match obj {
ContextObject::TerrainMesh(m) => (&m.positions, &m.id),
ContextObject::ImportedMesh(m) => (&m.positions, &m.id),
_ => continue,
};
if !context.contains(id.as_str()) {
continue;
}
// [115] Importierte Netze: Feature-Kanten statt Hüllquader (Gelände bleibt Quader, zu viele Dreiecke).
if let ContextObject::ImportedMesh(m) = obj {
if m.indices.len() / 3 <= MAX_EDGE_TRIS && m.positions.len() >= 9 {
let idx: Vec<u32> = m.indices.iter().map(|&i| if i >= 0.0 && i < u32::MAX as f64 { i as u32 } else { u32::MAX }).collect();
out.mesh_edges(&m.positions, &idx);
continue;
}
}
let (mut min_x, mut max_x, mut min_y, mut max_y, mut min_h, mut max_h) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY);
for c in pos.chunks_exact(3) {
let (x, y, h) = (c[0], c[1], c[2]);
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;
}
if h < min_h {
min_h = h;
}
if h > max_h {
max_h = h;
}
}
if !min_x.is_finite() {
continue;
}
let mut corners = [[0.0; 3]; 8];
for (i, c) in corners.iter_mut().enumerate() {
*c = [if i & 1 != 0 { max_x } else { min_x }, if i & 2 != 0 { max_h } else { min_h }, if i & 4 != 0 { max_y } else { min_y }];
}
for (i, j) in BOX_EDGES {
out.edge(corners[i], corners[j]);
}
}
}
Ok(out.v)
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> Project {
serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap()
}
fn lines(p: &Project, a: serde_json::Value) -> Vec<f32> {
selection_highlight_lines(p, &serde_json::from_value(a).unwrap()).unwrap()
}
#[test]
fn leer_ohne_auswahl() {
let p = sample();
assert!(lines(&p, serde_json::json!({})).is_empty());
assert!(lines(&p, serde_json::json!({"walls": ["gibt-es-nicht"]})).is_empty());
}
#[test]
fn wand_zwoelf_kanten_decke_prisma() {
let p = sample();
let w = emit_walls(&p, true).unwrap();
let id = &w[0].wall_id;
let n = w.iter().filter(|x| &x.wall_id == id).count();
let l = lines(&p, serde_json::json!({"walls": [id], "rgb": [1.0, 0.5, 0.0]}));
assert_eq!(l.len(), n * 12 * 12);
assert_eq!(&l[3..6], &[1.0, 0.5, 0.0]);
let s = &emit_slabs(&p)[0];
let l = lines(&p, serde_json::json!({"ceilings": [s.ceiling_id]}));
assert_eq!(l.len() % (3 * 12) , 0);
assert!(!l.is_empty());
}
/// [137] Gewählte Stützen und freie Körper bekommen im 3D einen Umriss (Prisma: 3 Kanten je Ecke).
#[test]
fn stuetze_und_freier_koerper() {
let p: Project = serde_json::from_value(serde_json::json!({
"id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "layers": [], "openings": [], "walls": [],
"drawingLevels": [{"id": "EG", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3.0, "baseElevation": 0.0}],
"columns": [{"id": "k1", "type": "column", "floorId": "EG", "categoryCode": "25", "position": {"x": 2, "y": 3}, "profile": {"kind": "rect", "width": 0.3, "depth": 0.3}, "rotation": 0, "height": 2.5}],
"extrudedSolids": [{"id": "s1", "type": "extrudedSolid", "levelId": "EG", "points": [{"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 1, "y": 1}], "height": 2.0}],
"drawings2d": []
}))
.unwrap();
assert_eq!(lines(&p, serde_json::json!({"columns": ["k1"]})).len(), 4 * 3 * 12);
let l = lines(&p, serde_json::json!({"solids": ["s1"]}));
// Dreiecks-Prisma: 9 echte Kanten (Deckel-/Boden-Diagonalen fallen weg).
assert_eq!(l.len(), 9 * 2 * 6);
assert!(l.chunks_exact(6).any(|v| (v[1] - 2.0).abs() < 1e-6));
}
fn solid_project(solid: serde_json::Value) -> Project {
serde_json::from_value(serde_json::json!({
"id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "layers": [], "openings": [], "walls": [],
"drawingLevels": [{"id": "EG", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3.0, "baseElevation": 0.0}],
"extrudedSolids": [solid], "drawings2d": []
}))
.unwrap()
}
/// Anzahl Kanten mit `f(a, b)`; Kanten aus `[x,y,z,r,g,b]×2`.
fn count(l: &[f32], f: impl Fn(&[f32], &[f32]) -> bool) -> usize {
l.chunks_exact(12).filter(|s| f(&s[0..3], &s[6..9])).count()
}
/// [115] Zylinder: zwei Kreise (Boden/Deckel) und keine Facettenfugen (Mantel-Längskanten).
#[test]
fn zylinder_zwei_kreise_ohne_facettenfugen() {
let p = solid_project(serde_json::json!({"id": "z", "type": "extrudedSolid", "levelId": "EG", "points": [], "height": 2.0,
"circle": {"center": {"x": 0, "y": 0}, "r": 0.5}}));
let l = lines(&p, serde_json::json!({"solids": ["z"]}));
assert!(!l.is_empty());
let vertical = count(&l, |a, b| (a[0] - b[0]).abs() < 1e-6 && (a[2] - b[2]).abs() < 1e-6);
assert_eq!(vertical, 0, "keine Längsfugen");
let horizontal = count(&l, |a, b| (a[1] - b[1]).abs() < 1e-6);
assert_eq!(l.len() / 12, horizontal, "nur Kreiskanten");
let (bot, top) = (count(&l, |a, _| a[1].abs() < 1e-6), count(&l, |a, _| (a[1] - 2.0).abs() < 1e-6));
assert_eq!(bot, top);
assert!(bot >= 48, "Kreis fein facettiert: {bot}");
}
/// [115] Verjüngter Quader: schräge Kanten (Basis-Ecke → kleinere Deckel-Ecke) statt senkrechtes Prisma.
#[test]
fn verjuengter_koerper_schraege_kanten() {
let p = solid_project(serde_json::json!({"id": "v", "type": "extrudedSolid", "levelId": "EG", "height": 2.0, "taper": 0.5,
"points": [{"x": 0, "y": 0}, {"x": 2, "y": 0}, {"x": 2, "y": 2}, {"x": 0, "y": 2}]}));
let l = lines(&p, serde_json::json!({"solids": ["v"]}));
assert_eq!(l.len() / 12, 12, "Quader-Stumpf: 12 Kanten");
let slanted = count(&l, |a, b| (a[1] - b[1]).abs() > 1e-6 && ((a[0] - b[0]).abs() > 1e-6 || (a[2] - b[2]).abs() > 1e-6));
assert_eq!(slanted, 4, "vier schräge Kanten, kein Prisma");
}
/// [115] Importiertes Netz: Würfel = 12 Feature-Kanten (Diagonalen der Quad-Hälften fehlen).
#[test]
fn importiertes_netz_feature_kanten() {
let pos: Vec<f64> = (0..8).flat_map(|i| [(i & 1) as f64, ((i >> 1) & 1) as f64, ((i >> 2) & 1) as f64]).collect();
let quads = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]];
let idx: Vec<f64> = quads.iter().flat_map(|q| [q[0], q[1], q[2], q[0], q[2], q[3]]).map(|i| i as f64).collect();
let mut p = Project::default();
p.context = Some(vec![ContextObject::ImportedMesh(crate::model::ImportedMesh { id: "m".into(), category_code: "12".into(), positions: pos, indices: idx, ..Default::default() })]);
assert_eq!(lines(&p, serde_json::json!({"context": ["m"]})).len() / 12, 12);
}
}