[143] DXF/DWG-Import: Höhenlinien als Gelände-Höhenlinien (contourSet) statt 2D-Zeichnung

Erkennung per Layer-Name, Erhebung/konstantem Z (3D-Polylinien) und Höhentexten
(Kern import_terrain.rs); Option im Import-Dialog, Zähler in Dialog und Meldung.
This commit is contained in:
Claude committed 2026-11-09 15:47:11 +00:00
1 parent e716554213
commit c35b031b41
17 files changed
+555 -16

No files matched your search

+1 -1
View File
@@ -95,7 +95,7 @@ Neues Modul: `<modul>.rs` und `mod` in `lib.rs`, Bindungen in `web/<modul>.rs` u
| Datei | Inhalt |
|---|---|
| `import_ifc.rs`, `import_context.rs` | IFC zu Bauteilen bzw. Kontext-Netzen (gelesen hat vorher `fileio`) |
| `import_drawing.rs`, `geo_mesh.rs` | DXF/DWG-Zeichnungen ins Projekt; swissBUILDINGS3D-Netze |
| `import_drawing.rs`, `import_terrain.rs`, `geo_mesh.rs` | DXF/DWG-Zeichnungen ins Projekt (`import_terrain`: Höhenlinien erkennen, [143]); swissBUILDINGS3D-Netze |
| `ifc_data.rs`, `ifc_quantities.rs`, `ifc_stairs.rs` | IFC-Export-Sammler, Basismengen, Treppen |
| `mesh_data.rs` | Sammler für OBJ, STL, glTF |
| `export_schedule.rs`, `opening_schedule.rs` | Bauteilliste, Fenster- und Türliste |
+69 -6
View File
@@ -24,6 +24,8 @@ use std::collections::{HashMap, HashSet};
/// Kategorie generischer Importe (`GENERIC_IMPORT_CATEGORY`, „10 Situation").
pub const GENERIC_IMPORT_CODE: &str = "10";
/// [143] Kategorie der importierten Gelände-Höhenlinien (02 Gelände).
const TERRAIN_CATEGORY: &str = "02";
/// Füllfarbe aus HATCH importierter Flächen (`DXF_HATCH_FILL`).
const DXF_HATCH_FILL: &str = "#c8c8c8";
/// Papier-Millimeter je PDF-Punkt.
@@ -74,6 +76,8 @@ pub struct Contour {
pub closed: bool,
pub filled: bool,
pub curve: Option<Curve>,
/// [143] Höhe wechselt entlang der Linie (3D-Polylinie mit Gefälle): keine Höhenlinie.
pub z_varies: bool,
pub pts: Vec<[f64; 2]>,
/// Polylinie mit Bögen: Stützpunkte + DXF-Bulge je Stützpunkt.
pub bulge: Option<(Vec<[f64; 2]>, Vec<f64>)>,
@@ -180,7 +184,7 @@ pub fn decode_drawing(geom: &[f64], strings: &[String], id_prefix: &str, now: f6
let layer = r.str()?;
let flags = jsnum::to_int32(r.num()?);
let z = r.num()?;
let mut c = Contour { layer, z, closed: flags & 1 != 0, filled: flags & 2 != 0, curve: None, pts: Vec::new(), bulge: None };
let mut c = Contour { layer, z, closed: flags & 1 != 0, filled: flags & 2 != 0, curve: None, z_varies: flags & 16 != 0, pts: Vec::new(), bulge: None };
if flags & 4 != 0 {
let circle = r.num()? == 1.0;
let v = r.take(5)?;
@@ -391,7 +395,7 @@ pub fn pdf_to_import(page: &PdfPage, scale: f64, with_texts: bool) -> DrawingImp
if !out.layer_line_weights.get(&layer).is_some_and(|v| !v.is_null()) {
out.layer_line_weights.insert(layer.clone(), json!(0.05));
}
out.contours.push(Contour { layer, z: 0.0, closed: true, filled: true, curve: None, pts: to_m(&p.pts), bulge: None });
out.contours.push(Contour { layer, z: 0.0, closed: true, filled: true, curve: None, z_varies: false, pts: to_m(&p.pts), bulge: None });
n_fill += 1.0;
}
}
@@ -403,7 +407,7 @@ pub fn pdf_to_import(page: &PdfPage, scale: f64, with_texts: bool) -> DrawingImp
out.layer_dashes.push((layer.clone(), pdf_dash_mm(&p.dash)));
}
let curve = p.curve.as_ref().map(|c| Curve { circle: c.circle, cx: c.cx * k, cy: c.cy * k, r: c.r * k, a0: c.a0, a1: c.a1 });
out.contours.push(Contour { layer, z: 0.0, closed: p.closed, filled: false, curve, pts: to_m(&p.pts), bulge: None });
out.contours.push(Contour { layer, z: 0.0, closed: p.closed, filled: false, curve, z_varies: false, pts: to_m(&p.pts), bulge: None });
n_stroke += 1.0;
}
}
@@ -571,6 +575,14 @@ pub fn summary_json(d: &DrawingImport) -> Value {
m.insert("layout".into(), l.clone().into());
}
m.insert("recovered".into(), d.recovered.into());
// [143] Erkannte Gelände-Höhenlinien (Dialog: Option „Höhenlinien als Gelände übernehmen").
let det = crate::import_terrain::detect(d);
if !det.lines.is_empty() {
m.insert("terrainContours".into(), det.lines.len().into());
if det.from_texts > 0 {
m.insert("terrainFromTexts".into(), det.from_texts.into());
}
}
Value::Object(m)
}
@@ -684,6 +696,13 @@ pub struct Decision {
pub parent_name: String,
#[serde(default)]
pub dash_style_template: String,
/// [143] Erkannte Höhenlinien (`import_terrain::detect`) als Gelände-Höhenlinien (`contourSet`) statt als
/// 2D-Zeichnung übernehmen.
#[serde(default)]
pub terrain_contours: bool,
/// [143] Name des Höhenlinien-Satzes (übersetzt von der Hülle); leer = „Höhenlinien".
#[serde(default)]
pub terrain_name: String,
}
/// Ergebnis von [`import_ops`].
@@ -693,6 +712,8 @@ pub struct ImportResult {
pub level_id: String,
pub drawings: usize,
pub meshes: usize,
/// [143] Höhenlinien, die als Gelände (`contourSet`) übernommen wurden.
pub terrain_contours: usize,
}
fn layer_list(root: &Map<String, Value>) -> Vec<Value> {
@@ -885,8 +906,15 @@ pub fn import_ops(root: &Map<String, Value>, d: &DrawingImport, dec: &Decision,
(Some(c), Some(b)) => (c[0] - (b[0] + b[2]) / 2.0, c[1] - (b[1] + b[3]) / 2.0),
_ => (0.0, 0.0),
};
// [143] Höhenlinien nicht als Zeichnung, sondern als Gelände-Höhenlinien.
let det = if dec.terrain_contours { crate::import_terrain::detect(d) } else { Default::default() };
let terrain_idx: HashSet<usize> = det.lines.iter().map(|(i, _)| *i).collect();
let terrain_text: HashSet<usize> = det.used_texts.iter().copied().collect();
let mut drawings = Vec::with_capacity(d.contours.len() + d.texts.len());
for c in &d.contours {
for (ci, c) in d.contours.iter().enumerate() {
if terrain_idx.contains(&ci) {
continue;
}
let Some(geom) = contour_geom(c, dx, dy) else { continue };
let is_polyline = geom.get("shape").and_then(Value::as_str) == Some("polyline");
let mut o = Map::new();
@@ -906,7 +934,10 @@ pub fn import_ops(root: &Map<String, Value>, d: &DrawingImport, dec: &Decision,
}
drawings.push(Value::Object(o));
}
for t in &d.texts {
for (ti, t) in d.texts.iter().enumerate() {
if terrain_text.contains(&ti) {
continue;
}
drawings.push(json!({
"id": format!("dxf2d-{stamp}-{}", next_seq()),
"type": "drawing2d",
@@ -919,6 +950,38 @@ pub fn import_ops(root: &Map<String, Value>, d: &DrawingImport, dec: &Decision,
if !drawings.is_empty() {
ops.push(Op::Add { collection: "drawings2d".into(), items: drawings, at: None });
}
if !det.lines.is_empty() {
let contours: Vec<Value> = det
.lines
.iter()
.map(|&(i, z)| {
let c = &d.contours[i];
let mut o = Map::new();
o.insert("z".into(), js_num(z));
o.insert("pts".into(), c.pts.iter().map(|&p| pt(p, dx, dy)).collect::<Vec<_>>().into());
o.insert("closed".into(), c.closed.into());
if c.layer != "0" && !c.layer.is_empty() {
o.insert("layer".into(), c.layer.clone().into());
}
Value::Object(o)
})
.collect();
let name = if dec.terrain_name.trim().is_empty() { "Höhenlinien" } else { dec.terrain_name.trim() };
ops.push(Op::Add {
collection: "context".into(),
items: vec![json!({
"id": format!("dxf-contours-{stamp}-{}", next_seq()),
"type": "contourSet",
"name": name,
"categoryCode": TERRAIN_CATEGORY,
"contours": contours,
})],
at: None,
});
if crate::import_context::ensure_context_categories(&mut layers, [TERRAIN_CATEGORY]) {
layers_changed = true;
}
}
let mut n_meshes = 0;
if dec.import_meshes && !d.meshes.is_empty() {
let meshes = mesh_values(d);
@@ -931,7 +994,7 @@ pub fn import_ops(root: &Map<String, Value>, d: &DrawingImport, dec: &Decision,
if layers_changed {
ops.push(Op::SetField { key: "layers".into(), value: Some(Value::Array(layers)), at: None });
}
ImportResult { ops, level_id, drawings: n_drawings, meshes: n_meshes }
ImportResult { ops, level_id, drawings: n_drawings, meshes: n_meshes, terrain_contours: det.lines.len() }
}
#[cfg(test)]
+109
View File
@@ -259,3 +259,112 @@ fn zeitmessung_kataster() {
doc.commit(r.ops, None, 0.0, false).unwrap();
eprintln!("commit {:?}", t.elapsed());
}
// ── [143] Höhenlinien als Gelände ────────────────────────────────────────────
fn line(layer: &str, z: f64, pts: &[[f64; 2]]) -> Contour {
Contour { layer: layer.into(), z, closed: false, filled: false, curve: None, z_varies: false, pts: pts.to_vec(), bulge: None }
}
fn text(layer: &str, s: &str, x: f64, y: f64) -> Text {
Text { layer: layer.into(), text: s.into(), x, y, height: 0.5, angle: 0.0 }
}
#[test]
fn hoehenlinien_layername_und_erhebung() {
use crate::import_terrain::{detect, is_contour_layer_name};
for n in ["Höhenlinien", "HL", "A-CONTOUR_5m", "Kote", "hoehenlinie_neu", "ISO-Linien"] {
assert!(is_contour_layer_name(n), "{n}");
}
for n in ["Wände", "0", "Strassen", "Hilfslinien", "Text"] {
assert!(!is_contour_layer_name(n), "{n}");
}
let d = DrawingImport {
contours: vec![
line("Höhenlinien", 432.0, &[[0.0, 0.0], [5.0, 1.0], [9.0, 0.0]]),
line("Höhenlinien", 433.0, &[[0.0, 3.0], [9.0, 3.0]]),
line("Wände", 0.0, &[[0.0, 0.0], [1.0, 0.0]]),
],
..Default::default()
};
let det = detect(&d);
assert_eq!(det.lines, vec![(0, 432.0), (1, 433.0)]);
}
#[test]
fn hoehenlinien_ohne_hinweis_nur_bei_eindeutigem_muster() {
use crate::import_terrain::detect;
let mk = |zs: &[f64]| DrawingImport {
contours: zs.iter().enumerate().map(|(i, &z)| line("Linien", z, &[[0.0, i as f64], [4.0, i as f64]])).collect(),
..Default::default()
};
assert_eq!(detect(&mk(&[430.0, 431.0, 432.0])).lines.len(), 3);
assert!(detect(&mk(&[430.0, 431.0])).lines.is_empty(), "zu wenige Linien");
assert!(detect(&mk(&[3.0, 3.0, 3.0])).lines.is_empty(), "eine Höhe = Geschossdecke o. Ä.");
assert!(detect(&mk(&[0.0, 0.0, 0.0])).lines.is_empty(), "ohne Höhe");
// 3D-Polylinie mit Gefälle ist keine Höhenlinie.
let mut d = mk(&[430.0, 431.0, 432.0, 433.0]);
d.contours[1].z_varies = true;
assert_eq!(detect(&d).lines.len(), 3);
}
#[test]
fn hoehenlinien_aus_hoehentexten() {
use crate::import_terrain::{detect, parse_height};
assert_eq!(parse_height("432.50"), Some(432.5));
assert_eq!(parse_height(" +432,5 m "), Some(432.5));
assert_eq!(parse_height("-1.2"), Some(-1.2));
assert_eq!(parse_height("EG 432"), None);
assert_eq!(parse_height(""), None);
let d = DrawingImport {
contours: vec![
line("Höhenlinien", 0.0, &[[0.0, 0.0], [10.0, 0.0]]),
line("Höhenlinien", 0.0, &[[0.0, 5.0], [10.0, 5.0]]),
line("Höhenlinien", 0.0, &[[0.0, 50.0], [10.0, 50.0]]), // ohne Text
],
texts: vec![text("Beschriftung", "432.5", 5.0, 0.2), text("Beschriftung", "433,0", 5.0, 4.9), text("Beschriftung", "Haus", 5.0, 0.1), text("Beschriftung", "99", 80.0, 80.0)],
..Default::default()
};
let det = detect(&d);
assert_eq!(det.lines, vec![(0, 432.5), (1, 433.0)]);
assert_eq!(det.used_texts, vec![0, 1]);
assert_eq!(det.from_texts, 2);
}
#[test]
fn import_hoehenlinien_als_contour_set() {
let d = DrawingImport {
contours: vec![
line("Höhenlinien", 432.0, &[[0.0, 0.0], [5.0, 1.0], [9.0, 0.0]]),
line("Höhenlinien", 433.0, &[[0.0, 3.0], [9.0, 3.0]]),
line("Wände", 0.0, &[[0.0, 0.0], [1.0, 0.0]]),
],
texts: vec![text("Wände", "Haus", 1.0, 1.0)],
..Default::default()
};
let dec = |on: bool| decision(json!({"target": {"kind": "new", "name": "HL"}, "categoryMode": "active", "activeCategoryCode": "20", "terrainContours": on, "terrainName": "Höhenlinien (Import)"}));
let r = import_ops(&project(), &d, &dec(true), 1000.0);
assert_eq!(r.terrain_contours, 2);
assert_eq!(r.drawings, 2, "Wand-Linie und Text bleiben Zeichnung");
let set = r
.ops
.iter()
.find_map(|o| match o {
Op::Add { collection, items, .. } if collection == "context" => Some(items[0].clone()),
_ => None,
})
.expect("contourSet");
assert_eq!(set["type"], json!("contourSet"));
assert_eq!(set["name"], json!("Höhenlinien (Import)"));
assert_eq!(set["contours"].as_array().unwrap().len(), 2);
assert_eq!(set["contours"][0]["z"], json!(432));
assert_eq!(set["contours"][0]["layer"], json!("Höhenlinien"));
assert_eq!(set["contours"][1]["pts"].as_array().unwrap().len(), 2);
// Kategorie 02 Gelände wird angelegt.
assert!(r.ops.iter().any(|o| matches!(o, Op::SetField { key, .. } if key == "layers")));
// Ohne die Option bleibt alles Zeichnung.
let r = import_ops(&project(), &d, &dec(false), 1000.0);
assert_eq!((r.terrain_contours, r.drawings), (0, 4));
assert!(!r.ops.iter().any(|o| matches!(o, Op::Add { collection, .. } if collection == "context")));
assert_eq!(summary_json(&d)["terrainContours"], json!(2));
}
+145
View File
@@ -0,0 +1,145 @@
//! [143] Höhenlinien im DXF/DWG-Import erkennen: Aus den gelesenen Konturen werden Gelände-Höhenlinien
//! (`contourSet` der Kontext-Schicht, Grundlage für „Gelände erzeugen" und „Baugrube erstellen") statt einer
//! 2D-Zeichnung.
//!
//! Erkannt wird in drei Stufen (reine Funktionen auf [`DrawingImport`], keine Ops):
//! 1. **Layer-Name** als Hinweis (`Höhenlinie`, `HL`, `Contour`, `Kote` …): Konturen mit Höhe ≠ 0 zählen dazu.
//! 2. **Layer ohne Hinweis**, aber mit eindeutigem Muster: mindestens drei offene/geschlossene Linienzüge,
//! alle mit konstanter Höhe ≠ 0 und mindestens zwei verschiedenen Höhen.
//! 3. **Höhentexte** als Ersatz, wenn die Höhe fehlt (Hinweis-Layer, Höhe 0): eine Zahl als Text nahe der Linie
//! („432.50", „432,5 m") gibt der Linie ihre Höhe; der Text wird dann nicht mehr als Zeichnung übernommen.
//!
//! Nie Höhenlinien sind Kreise/Bögen, Schraffuren und 3D-Polylinien mit wechselnder Höhe (`z_varies`).
use crate::import_drawing::{Contour, DrawingImport};
use std::collections::{HashMap, HashSet};
/// Ergebnis der Erkennung: Index der Kontur in `DrawingImport::contours` und ihre Höhe, dazu die Texte,
/// die als Höhe verbraucht wurden.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct TerrainDetection {
pub lines: Vec<(usize, f64)>,
/// Indizes in `DrawingImport::texts`, die als Höhenangabe gedient haben.
pub used_texts: Vec<usize>,
/// Davon Linien, deren Höhe aus einem Text stammt.
pub from_texts: usize,
}
/// Höhenwerte ausserhalb dieser Spanne (m) sind keine Höhenangaben.
const MIN_Z: f64 = -500.0;
const MAX_Z: f64 = 9000.0;
/// Hinweis aus dem Layer-Namen: ganze Wörter (`HL`, `Kote`, `Iso`) oder Wortteile (`Höhenlinien_5m`, `Contours`).
pub fn is_contour_layer_name(name: &str) -> bool {
let low = name.to_lowercase().replace('ö', "oe").replace('ü', "ue").replace('ä', "ae").replace('ß', "ss");
const PARTS: [&str; 9] = ["hoehenlinie", "hoehenkurve", "hoehenkote", "contour", "isohypse", "isolinie", "hoehenschicht", "niveaulinie", "elevation"];
if PARTS.iter().any(|p| low.contains(p)) {
return true;
}
const WORDS: [&str; 8] = ["hl", "kote", "koten", "iso", "kurve", "kurven", "gelaendelinie", "terrain"];
low.split(|c: char| !c.is_alphanumeric()).any(|w| WORDS.contains(&w))
}
fn is_candidate(c: &Contour) -> bool {
c.curve.is_none() && !c.filled && !c.z_varies && c.pts.len() >= 2 && c.z.is_finite() && c.z > MIN_Z && c.z < MAX_Z
}
/// Zahl in einem Text („432.50", „+432,5", „432.5 m", „432.5 m ü. M.") oder `None`.
pub fn parse_height(text: &str) -> Option<f64> {
let t = text.trim();
let t = t.strip_suffix("m ü. M.").or_else(|| t.strip_suffix("m ü.M.")).or_else(|| t.strip_suffix("müM")).or_else(|| t.strip_suffix("m.ü.M.")).unwrap_or(t);
let t = t.trim().strip_suffix('m').unwrap_or(t).trim();
let t = t.strip_prefix('+').unwrap_or(t);
if t.is_empty() || !t.chars().all(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | '-')) || !t.chars().any(|c| c.is_ascii_digit()) {
return None;
}
let v: f64 = t.replace(',', ".").parse().ok()?;
(v.is_finite() && v > MIN_Z && v < MAX_Z).then_some(v)
}
fn dist_point_seg(p: [f64; 2], a: [f64; 2], b: [f64; 2]) -> f64 {
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
let l2 = dx * dx + dy * dy;
let t = if l2 > 0.0 { (((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };
(p[0] - (a[0] + t * dx)).hypot(p[1] - (a[1] + t * dy))
}
fn dist_to_line(p: [f64; 2], c: &Contour) -> f64 {
let mut best = f64::INFINITY;
for w in c.pts.windows(2) {
best = best.min(dist_point_seg(p, w[0], w[1]));
}
if c.closed && c.pts.len() > 2 {
best = best.min(dist_point_seg(p, c.pts[c.pts.len() - 1], c.pts[0]));
}
best
}
/// Erkennt die Höhenlinien des Imports (s. Moduldoku). Leer, wenn nichts Eindeutiges gefunden wird.
pub fn detect(d: &DrawingImport) -> TerrainDetection {
let mut out = TerrainDetection::default();
// Kandidaten je Layer.
let mut by_layer: HashMap<&str, Vec<usize>> = HashMap::new();
for (i, c) in d.contours.iter().enumerate() {
if is_candidate(c) {
by_layer.entry(c.layer.as_str()).or_default().push(i);
}
}
let mut direct: HashSet<usize> = HashSet::new();
let mut need_text: Vec<usize> = Vec::new();
for (layer, idx) in &by_layer {
if is_contour_layer_name(layer) {
for &i in idx {
if d.contours[i].z != 0.0 {
direct.insert(i);
} else {
need_text.push(i);
}
}
} else if idx.len() >= 3 && idx.iter().all(|&i| d.contours[i].z != 0.0) {
let mut zs: Vec<i64> = idx.iter().map(|&i| (d.contours[i].z * 100.0).round() as i64).collect();
zs.sort_unstable();
zs.dedup();
if zs.len() >= 2 {
direct.extend(idx.iter().copied());
}
}
}
// Stufe 3: Höhentexte für Linien ohne Höhe.
let mut from_text: HashMap<usize, (f64, f64, usize)> = HashMap::new(); // Linie → (Abstand, Höhe, Text)
if !need_text.is_empty() {
for (ti, t) in d.texts.iter().enumerate() {
let Some(z) = parse_height(&t.text) else { continue };
if !(t.x.is_finite() && t.y.is_finite()) {
continue;
}
let tol = (2.5 * t.height.max(0.0)).max(0.25);
let mut best: Option<(usize, f64)> = None;
for &ci in &need_text {
let dist = dist_to_line([t.x, t.y], &d.contours[ci]);
if dist <= tol && best.map_or(true, |(_, bd)| dist < bd) {
best = Some((ci, dist));
}
}
if let Some((ci, dist)) = best {
let e = from_text.entry(ci).or_insert((f64::INFINITY, z, ti));
if dist < e.0 {
*e = (dist, z, ti);
}
}
}
}
let mut used: HashSet<usize> = HashSet::new();
let mut lines: Vec<(usize, f64)> = direct.into_iter().map(|i| (i, d.contours[i].z)).collect();
for (ci, (_, z, ti)) in &from_text {
lines.push((*ci, *z));
used.insert(*ti);
}
lines.sort_by_key(|(i, _)| *i);
out.from_texts = from_text.len();
out.lines = lines;
let mut ut: Vec<usize> = used.into_iter().collect();
ut.sort_unstable();
out.used_texts = ut;
out
}
+1
View File
@@ -111,6 +111,7 @@ pub mod cmd_draw;
pub mod cmd_solid;
pub mod polyline_vertex;
pub mod import_drawing;
pub mod import_terrain;
pub mod import_context;
pub mod import_ifc;
pub mod cmd_paste;
+2 -2
View File
@@ -76,7 +76,7 @@ pub fn import_drawing_meshes(geom: &[f64], strings_json: &str, source_json: &str
}
/// Bestätigten Zeichnungs-Import (DXF/DWG/PDF) als EINEN Undo-Schritt ins Dokument `h` übernehmen.
/// `decision_json` s. [`Decision`]. Antwort: `{"ops":[…],"levelId":"…","drawings":n,"meshes":n}`.
/// `decision_json` s. [`Decision`]. Antwort: `{"ops":[…],"levelId":"…","drawings":n,"meshes":n,"terrainContours":n}`.
#[wasm_bindgen]
pub fn doc_import_drawing(h: u32, geom: &[f64], strings_json: &str, source_json: &str, decision_json: &str, key: &str, now_ms: f64) -> String {
let now = now_of(now_ms);
@@ -90,7 +90,7 @@ pub fn doc_import_drawing(h: u32, geom: &[f64], strings_json: &str, source_json:
};
with_doc(h, |doc| {
let r = imp::import_ops(doc.root(), &d, &dec, now);
let extra = [("levelId", Value::from(r.level_id)), ("drawings", r.drawings.into()), ("meshes", r.meshes.into())];
let extra = [("levelId", Value::from(r.level_id)), ("drawings", r.drawings.into()), ("meshes", r.meshes.into()), ("terrainContours", r.terrain_contours.into())];
commit(doc, r.ops, &extra, key, now)
})
.unwrap_or_else(|| err("Dokument nicht offen"))
+28 -1
View File
@@ -80,6 +80,9 @@ pub struct Contour {
pub closed: bool,
pub filled: bool,
pub curve: Option<Curve>,
/// [143] Die Höhen der Stützpunkte sind nicht einheitlich (3D-Polylinie mit Gefälle): `z` ist dann nur der
/// erste Wert und die Kontur keine Höhenlinie.
pub z_varies: bool,
/// Polylinie mit Bögen (LWPOLYLINE/POLYLINE, Schraffur-Rand aus einer Polylinie): die Stützpunkte
/// `[x, y, bulge]` (abgebildet, in Metern), damit die 2D-Zeichnung echte Bogen-Segmente bekommt
/// statt des fein zerlegten Linienzugs (`pts` bleibt tesselliert für Kontext und Fang). Nur wenn
@@ -535,6 +538,15 @@ fn finite2(p: &Vector3) -> bool {
p.x.is_finite() && p.y.is_finite()
}
/// [143] Wechselt die Höhe der Stützpunkte (mehr als 1 mm)?
fn z_varies(verts: &[(Vector3, f64)]) -> bool {
let mut zs = verts.iter().filter(|(v, _)| finite2(v)).map(|(v, _)| fz(v.z));
match zs.next() {
Some(first) => zs.any(|z| (z - first).abs() > 1e-3),
None => false,
}
}
fn fz(z: f64) -> f64 {
if z.is_finite() {
z
@@ -589,10 +601,20 @@ impl<'a> Mapper<'a> {
closed,
filled: false,
curve: None,
z_varies: false,
bulge_verts: None,
});
}
/// [143] Kennzeichnet die zuletzt angelegte Kontur als „Höhe wechselt".
fn mark_z_varies(&mut self, varies: bool) {
if varies {
if let Some(c) = self.contours.last_mut() {
c.z_varies = true;
}
}
}
/// Polylinie mit Bulges: tesselliert wie bisher, dazu (wenn sinnvoll) die Stützpunkte mit Bulge
/// ([`Contour::bulge_verts`]).
fn push_bulged(&mut self, layer: &str, z: f64, verts: &[(Vector3, f64)], closed: bool, xf: &Xf) {
@@ -650,7 +672,9 @@ impl<'a> Mapper<'a> {
p.vertices.iter().filter(|v| v.flags & 16 == 0).map(|v| (v.position, 0.0)).collect();
let z = verts.iter().find(|(v, _)| finite2(v)).map(|(v, _)| fz(v.z)).unwrap_or(fz(p.elevation));
let pts = bulge_points(&verts, false);
let varies = z_varies(&verts);
self.push_contour(layer, z, pts, p.flags.closed, xf);
self.mark_z_varies(varies);
}
EntityType::Polyline(p) => {
let verts: Vec<(Vector3, f64)> = p
@@ -661,7 +685,9 @@ impl<'a> Mapper<'a> {
.collect();
let z = verts.iter().find(|(v, _)| finite2(v)).map(|(v, _)| fz(v.z)).unwrap_or(0.0);
let pts = bulge_points(&verts, false);
let varies = z_varies(&verts);
self.push_contour(layer, z, pts, p.flags.is_closed(), xf);
self.mark_z_varies(varies);
}
EntityType::Arc(a) => self.arc(a.center, a.radius, a.start_angle, a.end_angle, layer, xf),
EntityType::Circle(c) => self.circle(c.center, c.radius, layer, xf),
@@ -1916,7 +1942,8 @@ pub fn encode(data: &ImportData) -> (Vec<f64>, Vec<String>) {
let flags = u8::from(c.closed)
| (u8::from(c.filled) << 1)
| (u8::from(c.curve.is_some()) << 2)
| (u8::from(c.bulge_verts.is_some()) << 3);
| (u8::from(c.bulge_verts.is_some()) << 3)
| (u8::from(c.z_varies) << 4);
g.push(f64::from(flags));
g.push(c.z);
if let Some(cv) = c.curve {
+33
View File
@@ -1021,3 +1021,36 @@ fn kodierung_bulge_stuetzpunkte() {
assert_eq!(g[j], 4.0);
assert_eq!(&g[j + 1..j + 4], &[2_600_000.0, 1_200_000.0, 0.12]);
}
// ── [143] Höhenlinien: Erhebung und konstantes Z ─────────────────────────────
#[test]
fn lwpolyline_erhebung_gruppe_38() {
let d = import_bytes(&dxf(
&[],
&[&["0", "LWPOLYLINE", "8", "Hoehenlinie", "90", "3", "70", "0", "38", "432.5", "10", "0", "20", "0", "10", "5", "20", "1", "10", "9", "20", "0"]],
))
.unwrap();
let c = only_contour(&d);
assert_eq!(c.z, 432.5);
assert!(!c.z_varies);
}
#[test]
fn polyline3d_konstantes_und_wechselndes_z() {
fn pl<'a>(zs: [&'a str; 3]) -> Vec<&'a str> {
let mut v = vec!["0", "POLYLINE", "8", "HL", "70", "8"];
for (i, z) in zs.iter().enumerate() {
let x = ["0", "5", "9"][i];
v.extend(["0", "VERTEX", "8", "HL", "70", "32", "10", x, "20", "1", "30", z]);
}
v.extend(["0", "SEQEND"]);
v
}
let d = import_bytes(&dxf(&[], &[&pl(["430", "430", "430"])])).unwrap();
let c = only_contour(&d);
assert_eq!(c.z, 430.0);
assert!(!c.z_varies);
let d = import_bytes(&dxf(&[], &[&pl(["430", "431", "432"])])).unwrap();
assert!(only_contour(&d).z_varies);
}