From cae605093093107b6221200bfa0840da325a8684 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 11:16:44 +0000 Subject: [PATCH] =?UTF-8?q?[C2]=20DXF/DWG:=20$INSUNITS=20angewendet,=20SOL?= =?UTF-8?q?ID/TRACE/DIMENSION/LEADER/MULTILEADER/ATTRIB=20im=20Import,=20E?= =?UTF-8?q?xport=20mit=20echten=20HATCH-Entit=C3=A4ten?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- TODO.md | 25 ++- scripts/validate-dxf.py | 7 + src-tauri/fileio/src/export.rs | 203 ++++++++++++++++- src-tauri/fileio/src/import.rs | 237 +++++++++++++++++++- src-tauri/fileio/src/import_tests.rs | 297 ++++++++++++++++++++++++- src/export/exportDxf.ezdxf.test.ts | 30 +++ src/export/exportDxf.gradient.test.ts | 12 +- src/export/exportDxf.roundtrip.test.ts | 27 ++- src/export/exportDxf.ts | 158 ++++++------- src/io/dxfParser.test.ts | 60 +++++ src/io/dxfParser.ts | 18 +- src/io/dxfParserAsync.ts | 2 +- 12 files changed, 966 insertions(+), 110 deletions(-) diff --git a/TODO.md b/TODO.md index 314e95f8..4b05e217 100644 --- a/TODO.md +++ b/TODO.md @@ -364,7 +364,16 @@ Code-Übernahme Lizenz der Abhängigkeiten prüfen, Pflicht [51]. Reihenfolge, Ebenen, Strichstärken, True-Color, Koordinaten ≤ 5e-7 m (Rundung des alten Writers auf 6 Stellen; neu volle f64). Neu: 2D-Texte als TEXT (fehlten bisher), CLI exportiert georeferenziert wie die App. Gegencheck ezdxf (`scripts/validate-dxf.py`, Test übersprungen ohne `pip install ezdxf`): 0 Auditor-Fehler. - Offen: Binär-DXF-Export, echte HATCH-Entitäten statt Schraffurlinien. + Offen: Binär-DXF-Export. + - ✅ **Export: echte HATCH-Entitäten** (28.10.): Schraffuren (`pattern` diagonal/Kreuz/Dämmung/frei, auch + gestrichelt) und Vollfüllungen gehen als HATCH ins DXF/DWG statt als einzelne geklippte Linien: Rand = + geschlossene Polylinienkante des Plan-Polygons, Musterzeilen aus Winkel und Linienabstand (Versatz schon + gedreht, Strich-/Lückenfolge als `dash_lengths`), Vordergrundfarbe als True-Color, Ebene `HATCH`, vor dem + Umriss gezeichnet (neuer flacher Datensatz `REC_HATCH`, `export.rs`). Zufallsstriche (`random`) haben + kein Musteräquivalent und bleiben Linien; Bild-/Verlauf-Schraffur wie bisher nur Umriss. Geprüft: + acadrust-Rundreise DXF und DWG, ezdxf (Auditor 0 Fehler, Rand/Farbe/Musterzeilen), libredwg zählt gleiche + Typen. Offen: Aussehen in AutoCAD/BricsCAD selbst nicht geprüft (Musterphase ab Ursprung bei + LV95-Koordinaten); Verlauf als echte Gradient-HATCH möglich (acadrust kann es), noch nicht umgesetzt. - ✅ **DXF-Import in Rust** (28.10.): statt eigenem Tag-Reader acadrust (ASCII und Binär, R12–2018+, Code-Seiten) in `fileio/src/import.rs` → flacher f64-Puffer + String-Tabelle, dekodiert in `io/dxfParser.ts` (Rückgabetyp unverändert, neu `insUnits`). dxf-parser entfernt; Aufteilung grosser @@ -372,9 +381,19 @@ Code-Übernahme Lizenz der Abhängigkeiten prüfen, Pflicht [51]. Text, ab 4 MB). Abweichungen zum alten Parser (alle gewollt): Bulges tesselliert, Kreise/Bögen/ Schraffuren in Blöcken behalten Kurve/Füllung, Ebene „0" in Blöcken erbt die INSERT-Ebene (sonst eigene), Meshes je Ebene und auch aus Blöcken, MESH/Polygon-Mesh trianguliert, nur Modellraum (kein - Papierbereich), periodische Splines. Offen: Texte/ATTRIB in Blöcken nur als TEXT/MTEXT, SOLID/ - DIMENSION/LEADER nicht abgebildet, `$INSUNITS` nur gemeldet (Koordinaten bleiben 1:1), DXF am Stück + Papierbereich), periodische Splines. Offen: DXF am Stück ≈ 1,2–1,6× langsamer als dxf-parser (acadrust-Tokenizer; dank Aufteilung ab 4 MB insgesamt schneller). + - ✅ **Import verfeinert** (28.10.): `$INSUNITS` wird angewendet (mm, cm, m, Zoll, Fuss, … → Meter für + Koordinaten, Radien, Texthöhen, Meshes; 0/unbekannt/fehlend = 1:1 wie bisher; `insUnits` bleibt roh, + neu `unitScale`; Puffer-Version 2). Neu abgebildet: SOLID/TRACE als gefüllte Flächen (Eckenfolge 1-2-4-3, + Dreieck bei 3 = 4), DIMENSION über den Anonymblock `*D…` (Linien + Text; ohne Block nur der Messwert), + LEADER und MULTILEADER als Linienzug (zur Anschlussstelle geordnet, mit Landestrecke) plus MULTILEADER-Text, + ATTRIB an INSERTs und ATTDEF in Blöcken als Text (ATTDEF nur ohne passendes ATTRIB, unsichtbare entfallen). + Geprüft: Rust-Tests über Modell, ASCII-DXF und DWG-Rundreise; vitest `dxfParser.test.ts`; Swisstopo- + Kacheln (INSUNITS 6) unverändert. Offen: Pfeilspitzen/Spline-Führungslinien, Bemassung ohne Anonymblock + (nur Text), Block-/Tabellen-Inhalt von MULTILEADER, ATTRIB-Textausrichtung nur über den zweiten + Ausrichtungspunkt; keine echte Bemassungs-/Mehrdateien-Probe aus AutoCAD (nur synthetisch erzeugt); ein + Import-Dialog-Hinweis „Datei in mm, umgerechnet“ fehlt (`unitScale` steht bereit). - ○ **[C3] MCP an die laufende App** (`--connect 127.0.0.1:7979`, Werkzeuge `screenshot`, `ui_click`, `render` → PNG, `execute` = jeder Befehl mit JSON): genau die fehlende Hälfte von [9]; setzt [6] voraus. · M - ○ **[C4] CLI-Skripte** (`run --script`, `--cmd` mehrfach mit `{last}`, `convert`): Befehle headless diff --git a/scripts/validate-dxf.py b/scripts/validate-dxf.py index 50788428..2998c535 100644 --- a/scripts/validate-dxf.py +++ b/scripts/validate-dxf.py @@ -31,6 +31,13 @@ def main(path: str) -> int: item["r"] = e.dxf.radius if t == "ARC": item["angles"] = [e.dxf.start_angle, e.dxf.end_angle] + elif t == "HATCH": + item["solid"] = bool(e.dxf.solid_fill) + item["paths"] = len(e.paths) + item["pattern_lines"] = len(e.pattern.lines) if e.pattern else 0 + item["rgb"] = list(e.rgb) if e.dxf.hasattr("true_color") else None + first = e.paths[0] if len(e.paths) else None + item["pts"] = [[v[0], v[1]] for v in first.vertices] if first is not None and hasattr(first, "vertices") else [] elif t == "TEXT": item["text"] = e.dxf.text item["at"] = [e.dxf.insert.x, e.dxf.insert.y] diff --git a/src-tauri/fileio/src/export.rs b/src-tauri/fileio/src/export.rs index b1def871..ca02b4d2 100644 --- a/src-tauri/fileio/src/export.rs +++ b/src-tauri/fileio/src/export.rs @@ -27,15 +27,26 @@ // ARC = 4, layer, cx, cy, r, start (rad), end (rad) (gegen den Uhrzeigersinn, DXF-Konvention) // CIRCLE = 5, layer, cx, cy, r // TEXT = 6, layer, text_idx, x, y, height, rotation (rad) +// HATCH = 7, layer, mode (0 = Vollfüllung, 1 = Linienmuster), rgb (0xRRGGBB, −1 = nach Ebene), +// n_dash, d0 … d(n_dash−1) (Strichmuster in m: an, aus, an, aus …; 0 = durchgezogen), +// n_fam, (angle (rad), spacing (m)) × n_fam, n, x0, y0, … x(n−1), y(n−1) (äusserer Rand) // // `layer` ist der Index des LAYER-Datensatzes (Reihenfolge des Auftretens, ab 0), er muss vorher -// stehen. Schraffuren übergibt TS als geklippte LINE-Datensätze auf einer eigenen Ebene (Dossier-Muster, -// Strichelung und Zufallsstriche haben kein DXF-Musteräquivalent; so wie bisher). +// stehen. Schraffuren sind echte HATCH-Entitäten ([C2], 28.10.): Vollfüllung (`SOLID`) oder ein +// Linienmuster, das hier aus Winkel und Linienabstand der Dossier-Schraffur gebaut wird (je Linienschar +// eine Musterzeile, Basispunkt Ursprung — wie die Phase der bisherigen Schraffurlinien; Versatz = +// Abstand senkrecht zur Linie, schon gedreht, wie DXF es speichert). Der Rand ist eine geschlossene +// Polylinien-Kante. Zufallsstriche (`random`) haben kein Musteräquivalent: TS gibt sie weiter als +// LINE-Datensätze aus. // // Fehlerverhalten: ein kaputter Puffer (falsche Version, unbekannter Datensatz, abgeschnitten, Index // ausserhalb) ergibt einen Fehler, nie einen Panic. Einzelne Entitäten mit NaN/∞ werden übersprungen // (der alte Writer schrieb dafür „0.0“ — eine Linie zum Nullpunkt ist schlechter als keine). +use acadrust::entities::{ + BoundaryEdge, BoundaryPath, BoundaryPathFlags, Hatch, HatchPattern, HatchPatternLine, HatchPatternType, + PolylineEdge, +}; use acadrust::{ Arc, CadDocument, Circle, Color, DwgWriter, DxfVersion, DxfWriter, EntityType, Layer, Line, LineWeight, LwPolyline, Text, Vector2, Vector3, @@ -50,6 +61,7 @@ pub const REC_POLYLINE: f64 = 3.0; pub const REC_ARC: f64 = 4.0; pub const REC_CIRCLE: f64 = 5.0; pub const REC_TEXT: f64 = 6.0; +pub const REC_HATCH: f64 = 7.0; /// DXF-Ausgabeversion (s. Kopf). pub const DXF_VERSION: DxfVersion = DxfVersion::AC1032; @@ -154,6 +166,41 @@ fn layer_color(rgb: f64) -> Color { Color::from_rgb((v >> 16) as u8, (v >> 8) as u8, v as u8) } +/// Obergrenzen gegen Unsinn im Puffer (Musterzeilen und Striche je Schraffur). +const MAX_HATCH_FAMILIES: usize = 8; +const MAX_HATCH_DASHES: usize = 16; + +/// HATCH aus Rand und Muster. `families` = (Winkel in rad, Linienabstand in m); `dashes` = Strichmuster +/// in m (an, aus, …), leer = durchgezogen. Leere Schar-Liste = Vollfüllung. +fn make_hatch(pts: &[f64], solid: bool, families: &[(f64, f64)], dashes: &[f64]) -> Hatch { + let mut hatch = if solid { + Hatch::solid() + } else { + let mut pattern = HatchPattern::new("DOSSIER"); + pattern.description = "Dossier-Schraffur".to_string(); + for &(angle, spacing) in families { + pattern.add_line(HatchPatternLine { + angle, + base_point: Vector2::new(0.0, 0.0), + // Versatz zur nächsten Linie: Abstand senkrecht zur Richtung, im Weltsystem. + offset: Vector2::new(-spacing * angle.sin(), spacing * angle.cos()), + // DXF: positiv = Strich, negativ = Lücke. + dash_lengths: dashes.iter().enumerate().map(|(i, d)| if i % 2 == 0 { *d } else { -*d }).collect(), + }); + } + let mut h = Hatch::with_pattern(pattern); + h.pattern_type = HatchPatternType::Custom; + h + }; + let mut path = BoundaryPath::with_flags(BoundaryPathFlags::from_bits(1 | 2)); // äusserer Rand, Polylinie + path.add_edge(BoundaryEdge::Polyline(PolylineEdge::new( + pts.chunks_exact(2).map(|p| Vector2::new(p[0], p[1])).collect(), + true, + ))); + hatch.add_path(path); + hatch +} + /// Baut aus der flachen Zeichnung ein acadrust-Dokument (Einheit Meter, metrisch). pub fn build_document(flat: &[f64], strings: &str) -> Result { let strs: Vec<&str> = if strings.is_empty() { Vec::new() } else { strings.split('\0').collect() }; @@ -215,6 +262,38 @@ pub fn build_document(flat: &[f64], strings: &str) -> Result 0.0).then(|| { EntityType::Text(Text::with_value(value, Vector3::new(v[0], v[1], 0.0)).with_height(v[2]).with_rotation(v[3])) }) + } else if tag == REC_HATCH { + let mode = r.f()?; + let rgb = r.f()?; + let n_dash = r.idx()?; + if n_dash > MAX_HATCH_DASHES { + return Err(format!("zu viele Striche ({n_dash}) bei {}", r.pos - 1)); + } + let dashes = r.take(n_dash)?; + let n_fam = r.idx()?; + if n_fam > MAX_HATCH_FAMILIES { + return Err(format!("zu viele Linienscharen ({n_fam}) bei {}", r.pos - 1)); + } + let fam = r.take(n_fam.checked_mul(2).ok_or("Überlauf")?)?; + let n = r.idx()?; + let pts = r.take(n.checked_mul(2).ok_or("Überlauf")?)?; + let solid = mode == 0.0; + let families: Vec<(f64, f64)> = fam.chunks_exact(2).map(|f| (f[0], f[1])).collect(); + // Muster nur mit endlichen, positiven Abständen und Strichen (sonst rechnet CAD ins Leere). + let valid = n >= 3 + && all_finite(pts) + && (solid + || (!families.is_empty() + && families.iter().all(|(a, s)| a.is_finite() && s.is_finite() && *s > 1e-6) + && dashes.iter().all(|d| d.is_finite() && *d >= 0.0) + && (dashes.is_empty() || dashes.iter().sum::() > 1e-9))); + valid.then(|| { + let mut h = make_hatch(pts, solid, &families, dashes); + if rgb.is_finite() && (0.0..=16_777_215.0).contains(&rgb) { + h.common.color = layer_color(rgb); + } + EntityType::Hatch(Box::new(h)) + }) } else { return Err(format!("unbekannter Datensatz {tag} bei {}", r.pos - 1)); }; @@ -445,4 +524,124 @@ mod tests { let doc = read_dxf(export_dxf(&flat, "P").unwrap()); assert_eq!(doc.entities().count(), 1); } + + /// HATCH-Rundreise: Vollfüllung und Linienmuster (zwei Scharen, gestrichelt) mit Rand, Farbe, Ebene. + fn hatch_sample() -> (Vec, String) { + let (e, n) = (E, N); + let flat = vec![ + FLAT_VERSION, + REC_LAYER, 0.0, -1.0, 13.0, + // Vollfüllung, Farbe 0x336699 + REC_HATCH, 0.0, 0.0, 0x33_66_99 as f64, 0.0, 0.0, 4.0, e, n, e + 4.0, n, e + 4.0, n + 3.0, e, n + 3.0, + // Kreuzschraffur 45° / 135° (Abstand 0.1 m), durchgezogen, Farbe nach Ebene + REC_HATCH, 0.0, 1.0, -1.0, 0.0, 2.0, std::f64::consts::FRAC_PI_4, 0.1, 3.0 * std::f64::consts::FRAC_PI_4, 0.1, + 4.0, e, n, e + 4.0, n, e + 4.0, n + 3.0, e, n + 3.0, + // Gestrichelt: 0.05 an, 0.02 aus + REC_HATCH, 0.0, 1.0, 0x11_11_11 as f64, 2.0, 0.05, 0.02, 1.0, 0.0, 0.25, + 3.0, e, n, e + 2.0, n, e + 1.0, n + 1.0, + ]; + (flat, "HATCH".to_string()) + } + + fn check_hatches(doc: &CadDocument) { + let hs: Vec<&Hatch> = doc.entities().filter_map(|x| if let EntityType::Hatch(h) = x { Some(h.as_ref()) } else { None }).collect(); + assert_eq!(hs.len(), 3); + // Vollfüllung + assert!(hs[0].is_solid); + assert_eq!(hs[0].common.color.rgb(), Some((0x33, 0x66, 0x99))); + assert_eq!(hs[0].common.layer, "HATCH"); + // Kreuzschraffur + assert!(!hs[1].is_solid); + assert_eq!(hs[1].pattern.lines.len(), 2); + let l0 = &hs[1].pattern.lines[0]; + assert!((l0.angle - std::f64::consts::FRAC_PI_4).abs() < 1e-9); + // Versatz: Abstand 0.1 senkrecht zur 45°-Richtung. + assert!((l0.offset.x + 0.1 * std::f64::consts::FRAC_PI_4.sin()).abs() < 1e-9); + assert!((l0.offset.y - 0.1 * std::f64::consts::FRAC_PI_4.cos()).abs() < 1e-9); + assert!(l0.dash_lengths.is_empty()); + assert!(matches!(hs[1].common.color, Color::ByLayer)); + // Gestrichelt: positiv = Strich, negativ = Lücke + let l = &hs[2].pattern.lines[0]; + assert_eq!(l.dash_lengths, vec![0.05, -0.02]); + assert!((l.offset.y - 0.25).abs() < 1e-9 && l.offset.x.abs() < 1e-9); + // Rand: eine Polylinienkante, Koordinaten bitgleich + for h in &hs { + assert_eq!(h.paths.len(), 1); + assert!(!h.paths[0].edges.is_empty()); + } + let edge = |h: &Hatch| match &h.paths[0].edges[0] { + BoundaryEdge::Polyline(p) => p.vertices.iter().map(|v| (v.x, v.y)).collect::>(), + // Beim Lesen aus DXF/DWG darf der Rand auch als Linienkanten kommen. + BoundaryEdge::Line(_) => h + .paths[0] + .edges + .iter() + .filter_map(|e| if let BoundaryEdge::Line(l) = e { Some((l.start.x, l.start.y)) } else { None }) + .collect(), + _ => panic!("unerwartete Randkante"), + }; + let first = edge(hs[0]); + assert_eq!(first.len(), 4); + assert_eq!(first[0], (E, N)); + assert_eq!(first[2], (E + 4.0, N + 3.0)); + } + + #[test] + fn hatch_roundtrip_dxf_und_dwg() { + let (flat, strings) = hatch_sample(); + check_hatches(&read_dxf(export_dxf(&flat, &strings).unwrap())); + check_hatches(&read_dwg(export_dwg(&flat, &strings).unwrap())); + } + + #[test] + fn hatch_dxf_text_hat_hatch_und_musterzeilen() { + let (flat, strings) = hatch_sample(); + let text = String::from_utf8(export_dxf(&flat, &strings).unwrap()).unwrap(); + // Entität = Gruppencode 0 mit Wert HATCH (der Ebenenname HATCH steht unter Code 2/8). + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let entities = lines.windows(2).filter(|w| w[0] == "0" && w[1] == "HATCH").count(); + assert_eq!(entities, 3); + assert!(text.contains("DOSSIER")); + } + + #[test] + fn kaputte_hatches_werden_verworfen_oder_sind_fehler() { + let head = [FLAT_VERSION, REC_LAYER, 0.0, -1.0, 13.0]; + let sq = [4.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]; + let mk = |pre: &[f64]| { + let mut v = head.to_vec(); + v.push(REC_HATCH); + v.extend_from_slice(pre); + v.extend_from_slice(&sq); + v + }; + // Muster ohne Scharen, Abstand 0, NaN-Winkel, negativer/leerer Strich: übersprungen. + for pre in [ + &[0.0, 1.0, -1.0, 0.0, 0.0][..], + &[0.0, 1.0, -1.0, 0.0, 1.0, 0.5, 0.0], + &[0.0, 1.0, -1.0, 0.0, 1.0, f64::NAN, 0.1], + &[0.0, 1.0, -1.0, 1.0, -0.1, 1.0, 0.5, 0.1], + &[0.0, 1.0, -1.0, 2.0, 0.0, 0.0, 1.0, 0.5, 0.1], + ] { + let doc = read_dxf(export_dxf(&mk(pre), "P").unwrap()); + assert_eq!(doc.entities().count(), 0, "{pre:?}"); + } + // Rand mit NaN oder < 3 Punkten: übersprungen. + let mut bad = head.to_vec(); + bad.extend_from_slice(&[REC_HATCH, 0.0, 0.0, -1.0, 0.0, 0.0, 3.0, 0.0, 0.0, 1.0, f64::NAN, 1.0, 1.0]); + assert_eq!(read_dxf(export_dxf(&bad, "P").unwrap()).entities().count(), 0); + let mut two = head.to_vec(); + two.extend_from_slice(&[REC_HATCH, 0.0, 0.0, -1.0, 0.0, 0.0, 2.0, 0.0, 0.0, 1.0, 1.0]); + assert_eq!(read_dxf(export_dxf(&two, "P").unwrap()).entities().count(), 0); + // Zu viele Scharen/Striche, abgeschnitten: Fehler statt Panic. + assert!(export_dxf(&mk(&[0.0, 1.0, -1.0, 0.0, 99.0]), "P").is_err()); + assert!(export_dxf(&mk(&[0.0, 1.0, -1.0, 99.0]), "P").is_err()); + assert!(export_dxf(&[FLAT_VERSION, REC_LAYER, 0.0, -1.0, 13.0, REC_HATCH, 0.0, 0.0, -1.0, 0.0, 0.0, 5.0, 1.0], "P").is_err()); + // Farbe ausserhalb → ByLayer statt Absturz. + let mut col = head.to_vec(); + col.extend_from_slice(&[REC_HATCH, 0.0, 0.0, 1e12, 0.0, 0.0]); + col.extend_from_slice(&sq); + let doc = read_dxf(export_dxf(&col, "P").unwrap()); + assert!(matches!(doc.entities().next().unwrap().as_entity().common().color, Color::ByLayer)); + } } diff --git a/src-tauri/fileio/src/import.rs b/src-tauri/fileio/src/import.rs index cdf93f24..8212888a 100644 --- a/src-tauri/fileio/src/import.rs +++ b/src-tauri/fileio/src/import.rs @@ -11,6 +11,11 @@ // • INSERT rekursiv aufgelöst (Basispunkt, Skalierung, Drehung, Raster), Ebene „0" erbt die // Ebene der Referenz (CAD-Regel), Tiefe begrenzt. // • Ebenenfarben, $INSUNITS, Entity-Histogramm (Diagnose). +// • SOLID/TRACE (gefüllte 3-/4-Ecke) als gefüllte geschlossene Konturen, DIMENSION über den +// Anonymblock (`*D…`) als Linien/Text, LEADER/MULTILEADER als Linien (+ Text), ATTRIB (an INSERTs) +// und ATTDEF (in Blöcken ohne passendes ATTRIB) als Text. +// • `$INSUNITS` wird angewendet: alle Koordinaten, Radien und Texthöhen kommen in Metern an +// (`unit_scale`); 0/unbekannt = Faktor 1 (1:1 wie bisher). // // Übergabe an JS als flacher f64-Puffer + String-Tabelle (`encode`), Aufbau dort beschrieben. // Kaputte Dateien ergeben `Err(String)`; die Geometrie-Abbildung selbst ist panikfrei (alle @@ -22,8 +27,9 @@ use std::io::Cursor; use std::sync::Arc; use acadrust::entities::{ - BoundaryEdge, BoundaryPath, Ellipse, Hatch, Insert, LwPolyline, Mesh, PolyfaceMesh, - Spline, + AttributeDefinition, AttributeEntity, BoundaryEdge, BoundaryPath, Dimension, Ellipse, Hatch, + HorizontalAlignment, Insert, Leader, LwPolyline, Mesh, MultiLeader, PolyfaceMesh, Solid, Spline, + VerticalAlignment, }; use acadrust::entities::polygon_mesh::PolygonMesh; use acadrust::io::dxf::DxfReaderConfiguration; @@ -83,8 +89,10 @@ pub struct MeshBucket { #[derive(Debug, Clone, PartialEq)] pub struct ImportData { pub kind: SourceKind, - /// `$INSUNITS` (0 = ohne Einheit, 1 = Zoll, 4 = mm, 5 = cm, 6 = m …). + /// `$INSUNITS` (0 = ohne Einheit, 1 = Zoll, 4 = mm, 5 = cm, 6 = m …) — roh aus der Datei. pub ins_units: i16, + /// Faktor, mit dem alle Längen auf Meter umgerechnet wurden ([`unit_scale`]); 1 bei 0/unbekannt. + pub unit_scale: f64, /// Ebene → Farbe `0xRRGGBB` (nur Ebenen mit Farbe), in Tabellenreihenfolge. pub layer_colors: Vec<(String, u32)>, pub contours: Vec, @@ -162,6 +170,37 @@ pub fn import_owned(bytes: Vec) -> Result { // ── Abbildung ───────────────────────────────────────────────────────────────── +/// Meter je Zeicheneinheit nach `$INSUNITS` (AutoCAD-Codes). 0 (ohne Einheit) und Unbekanntes +/// ergeben 1.0: die Koordinaten bleiben dann wie in der Datei. +pub fn unit_scale(ins_units: i16) -> f64 { + match ins_units { + 1 | 22 => 0.0254, // Zoll (22 = US-Survey-Zoll, Unterschied < 1e-5) + 2 => 0.3048, // Fuss + 3 => 1609.344, // Meile + 4 => 0.001, // Millimeter + 5 => 0.01, // Zentimeter + 6 => 1.0, // Meter + 7 => 1000.0, // Kilometer + 8 => 2.54e-8, // Mikrozoll + 9 => 2.54e-5, // Mil + 10 => 0.9144, // Yard + 11 => 1e-10, // Ångström + 12 => 1e-9, // Nanometer + 13 => 1e-6, // Mikrometer + 14 => 0.1, // Dezimeter + 15 => 10.0, // Dekameter + 16 => 100.0, // Hektometer + 17 => 1e9, // Gigameter + 18 => 1.495_978_707e11, // Astronomische Einheit + 19 => 9.460_730_472_580_8e15, // Lichtjahr + 20 => 3.085_677_581_491_4e16, // Parsec + 21 => 1200.0 / 3937.0, // US-Survey-Fuss + 23 => 3600.0 / 3937.0, // US-Survey-Yard + 24 => 6_336_000.0 / 3937.0, // US-Survey-Meile + _ => 1.0, + } +} + /// 2D-Affinabbildung + z: `[x', y'] = M·[x, y] + t`, `z' = z·zs + zo`. #[derive(Debug, Clone, Copy)] struct Xf { @@ -238,6 +277,9 @@ struct Mapper<'a> { counts: Vec<(String, u32)>, count_index: HashMap<&'static str, usize>, total: u32, + /// ATTRIB-Tags (grossgeschrieben) des gerade aufgelösten INSERT: dazu gehörige ATTDEFs im Block + /// zeigen nicht ihren Vorgabewert (AutoCAD zeichnet statt dessen das ATTRIB der Referenz). + insert_tags: Vec>, } /// Ganzes Dokument abbilden: Modellraum (ohne Papierbereich), INSERTs aufgelöst. @@ -251,14 +293,18 @@ pub fn map_document(kind: SourceKind, doc: &CadDocument) -> ImportData { counts: Vec::new(), count_index: HashMap::new(), total: 0, + insert_tags: Vec::new(), }; + let scale = unit_scale(doc.header.insertion_units); + let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 }; + let root = Xf { m00: scale, m11: scale, zs: scale, ..IDENTITY }; let model: Vec<&EntityType> = if doc.block_records.get("*Model_Space").is_some() { doc.model_space_entities().collect() } else { doc.entities().collect() }; for e in model { - m.entity(e, &IDENTITY, None, 0); + m.entity(e, &root, None, 0); } let layer_colors = doc .layers @@ -269,6 +315,7 @@ pub fn map_document(kind: SourceKind, doc: &CadDocument) -> ImportData { ImportData { kind, ins_units: doc.header.insertion_units, + unit_scale: scale, layer_colors, contours: m.contours, texts: m.texts, @@ -422,6 +469,12 @@ impl<'a> Mapper<'a> { EntityType::PolygonMesh(p) => self.polygon_mesh(p, layer, xf), EntityType::Mesh(mesh) => self.mesh(mesh, layer, xf), EntityType::Insert(ins) => self.insert(ins, layer, xf, depth), + EntityType::Solid(sol) => self.solid(sol, layer, xf), + EntityType::Dimension(dim) => self.dimension(dim, layer, xf, depth), + EntityType::Leader(l) => self.leader(l, layer, xf), + EntityType::MultiLeader(ml) => self.multileader(ml, layer, xf), + EntityType::AttributeEntity(a) => self.attrib(a, layer, xf), + EntityType::AttributeDefinition(a) => self.attdef(a, layer, xf, depth), _ => {} } } @@ -619,6 +672,150 @@ impl<'a> Mapper<'a> { } } + /// SOLID/TRACE: gefülltes 3-/4-Eck. DXF speichert die Ecken als 1, 2, 4, 3 (Schleife ohne + /// Überkreuzung: erste, zweite, vierte, dritte); fallen dritte und vierte Ecke zusammen, ist es + /// ein Dreieck. + fn solid(&mut self, s: &Solid, layer: &str, xf: &Xf) { + let mut cs = vec![s.first_corner, s.second_corner]; + if s.fourth_corner != s.third_corner { + cs.push(s.fourth_corner); + } + cs.push(s.third_corner); + if !cs.iter().all(finite2) { + return; + } + let pts: Vec<[f64; 2]> = cs.iter().map(|c| [c.x, c.y]).collect(); + self.push_filled(layer, fz(s.first_corner.z), pts, xf); + } + + /// Gefüllte, geschlossene Kontur (SOLID/TRACE; wie ein HATCH-Rand). + fn push_filled(&mut self, layer: &str, z: f64, pts: Vec<[f64; 2]>, xf: &Xf) { + let before = self.contours.len(); + self.push_contour(layer, z, pts, true, xf); + if self.contours.len() > before { + if let Some(c) = self.contours.last_mut() { + c.filled = true; + } + } + } + + /// DIMENSION: die Zeichnung steht im Anonymblock (`*D…`, Gruppencode 2) in Weltkoordinaten; er + /// wird wie ein INSERT ohne Verschiebung aufgelöst. Ohne Block (oder leer) bleibt der Massstext. + fn dimension(&mut self, d: &Dimension, layer: &str, xf: &Xf, depth: usize) { + if depth >= MAX_INSERT_DEPTH { + return; + } + let base = d.base(); + let doc = self.doc; + let entities: Vec<&EntityType> = doc + .block_records + .get(&base.block_name) + .map(|b| b.entity_handles.iter().filter_map(|h| doc.get_entity(*h)).collect()) + .unwrap_or_default(); + if !entities.is_empty() { + for e in entities { + self.entity(e, xf, Some(layer), depth + 1); + } + return; + } + // Rückfall: nur der Text (Benutzertext, sonst gemessener Wert); `<>` = Messwert. + let measure = format_measure(base.actual_measurement); + let value = match &base.user_text { + Some(t) if !t.is_empty() => t.replace("<>", &measure), + _ => measure, + }; + self.text(&value, base.text_middle_point, DEFAULT_TEXT_HEIGHT, base.text_rotation, layer, xf); + } + + /// LEADER: Führungslinie als offener Linienzug (Pfeilspitze und Spline-Form entfallen). + fn leader(&mut self, l: &Leader, layer: &str, xf: &Xf) { + let pts: Vec<[f64; 2]> = l.vertices.iter().filter(|v| finite2(v)).map(|v| [v.x, v.y]).collect(); + let z = l.vertices.iter().find(|v| v.z.is_finite()).map(|v| v.z).unwrap_or(0.0); + self.push_contour(layer, z, pts, false, xf); + } + + /// MULTILEADER: je Führungslinie ein Linienzug (zur Anschlussstelle hin geordnet, mit + /// Landestrecke), dazu der Text der Annotation. + fn multileader(&mut self, ml: &MultiLeader, layer: &str, xf: &Xf) { + let ctx = &ml.context; + for root in &ctx.leader_roots { + let cp = root.connection_point; + let landing = if ml.enable_landing && root.landing_distance.is_finite() && root.landing_distance != 0.0 { + let d = root.direction; + let len = (d.x * d.x + d.y * d.y).sqrt(); + (len > 1e-12 && finite2(&cp)) + .then(|| [cp.x + d.x / len * root.landing_distance, cp.y + d.y / len * root.landing_distance]) + } else { + None + }; + for line in &root.lines { + let mut pts: Vec<[f64; 2]> = line.points.iter().filter(|p| finite2(p)).map(|p| [p.x, p.y]).collect(); + if pts.is_empty() { + continue; + } + if finite2(&cp) { + let d2 = |p: &[f64; 2]| (p[0] - cp.x).powi(2) + (p[1] - cp.y).powi(2); + if d2(&pts[0]) < d2(&pts[pts.len() - 1]) { + pts.reverse(); // letzter Punkt = Anschlussstelle + } + if d2(&pts[pts.len() - 1]) > 1e-18 { + pts.push([cp.x, cp.y]); + } + if let Some(l) = landing { + pts.push(l); + } + } + let z = line.points.iter().find(|p| p.z.is_finite()).map(|p| p.z).unwrap_or(0.0); + self.push_contour(layer, z, pts, false, xf); + } + } + if ctx.has_text_contents && !ctx.text_string.trim().is_empty() { + let h = [ctx.text_height, ml.text_height] + .into_iter() + .find(|h| *h > 0.0 && h.is_finite()) + .unwrap_or(DEFAULT_TEXT_HEIGHT); + let clean = sanitize_mtext(&ctx.text_string); + self.text(&clean, ctx.text_location, h, ctx.text_rotation, layer, xf); + } + } + + /// ATTRIB (Wert eines Block-Attributs, steht in Weltkoordinaten): als Text; unsichtbare entfallen. + /// Bei ausgerichtetem Text (nicht links/Grundlinie) gilt der zweite Ausrichtungspunkt. + fn attrib(&mut self, a: &AttributeEntity, layer: &str, xf: &Xf) { + if a.flags.invisible || a.value.is_empty() { + return; + } + let at = text_anchor(a.horizontal_alignment, a.vertical_alignment, a.insertion_point, a.alignment_point); + let h = if a.height > 0.0 && a.height.is_finite() { a.height } else { DEFAULT_TEXT_HEIGHT }; + let value = match &a.embedded_mtext { + Some(m) if a.is_multiline => sanitize_mtext(&m.value), + _ => a.value.clone(), + }; + self.text(&value, at, h, a.rotation, layer, xf); + } + + /// ATTDEF: in einem Block zeigt AutoCAD den Vorgabewert nur, wenn die Referenz kein passendes + /// ATTRIB trägt (oder das Attribut konstant ist); ausserhalb eines Blocks gilt Wert bzw. Tag. + fn attdef(&mut self, a: &AttributeDefinition, layer: &str, xf: &Xf, depth: usize) { + if a.flags.invisible { + return; + } + let covered = depth > 0 + && !a.flags.constant + && self.insert_tags.last().is_some_and(|tags| tags.contains(&a.tag.to_ascii_uppercase())); + if covered { + return; + } + let value = if a.default_value.is_empty() { a.tag.as_str() } else { a.default_value.as_str() }; + if value.is_empty() { + return; + } + let at = text_anchor(a.horizontal_alignment, a.vertical_alignment, a.insertion_point, a.alignment_point); + let h = if a.height > 0.0 && a.height.is_finite() { a.height } else { DEFAULT_TEXT_HEIGHT }; + self.text(value, at, h, a.rotation, layer, xf); + } + + /// INSERT: Block-Inhalt je Rasterzelle mit `Welt = P + R(θ)·(S·(p − Basis) + Versatz)`. fn insert(&mut self, ins: &Insert, layer: &str, xf: &Xf, depth: usize) { if depth >= MAX_INSERT_DEPTH { @@ -649,6 +846,7 @@ impl<'a> Mapper<'a> { let dc = num(ins.column_spacing, 0.0); let dr = num(ins.row_spacing, 0.0); let entities: Vec<&EntityType> = block.entity_handles.iter().filter_map(|h| doc.get_entity(*h)).collect(); + self.insert_tags.push(ins.attributes.iter().map(|a| a.tag.to_ascii_uppercase()).collect()); for row in 0..nr { for col in 0..nc { let offx = col as f64 * dc; @@ -676,9 +874,37 @@ impl<'a> Mapper<'a> { } } } + self.insert_tags.pop(); + // ATTRIBs der Referenz stehen schon in Weltkoordinaten (nicht unter der Block-Abbildung). + for a in &ins.attributes { + self.count("ATTRIB"); + let own = a.common.layer.as_str(); + let attr_layer = if own == "0" || own.is_empty() { layer } else { own }; + self.attrib(a, attr_layer, xf); + } } } +/// Ankerpunkt eines ATTRIB/ATTDEF: bei ausgerichtetem Text (nicht links/Grundlinie) der zweite +/// Ausrichtungspunkt, sonst der Einfügepunkt. +fn text_anchor(h: HorizontalAlignment, v: VerticalAlignment, ins: Vector3, align: Vector3) -> Vector3 { + let aligned = h != HorizontalAlignment::Left || v != VerticalAlignment::Baseline; + if aligned && finite2(&align) && (align.x != 0.0 || align.y != 0.0) { + align + } else { + ins + } +} + +/// Messwert als Text (höchstens 3 Nachkommastellen, ohne Nullen am Ende). +fn format_measure(v: f64) -> String { + if !v.is_finite() { + return String::new(); + } + let s = format!("{v:.3}"); + s.trim_end_matches('0').trim_end_matches('.').to_string() +} + fn push_vertex(b: &mut MeshBucket, xf: &Xf, v: &Vector3) -> u32 { let idx = (b.positions.len() / 3) as u32; let [x, y] = xf.xy(if v.x.is_finite() { v.x } else { 0.0 }, if v.y.is_finite() { v.y } else { 0.0 }); @@ -1023,12 +1249,13 @@ pub fn encode(data: &ImportData) -> (Vec, Vec) { (strings.len() - 1) as f64 }; let mut g: Vec = Vec::with_capacity(16 + data.contours.iter().map(|c| 4 + c.pts.len() * 2).sum::()); - g.push(1.0); + g.push(2.0); g.push(match data.kind { SourceKind::Dxf => 0.0, SourceKind::Dwg => 1.0, }); g.push(f64::from(data.ins_units)); + g.push(data.unit_scale); g.push(f64::from(data.total)); g.push(data.layer_colors.len() as f64); for (name, rgb) in &data.layer_colors { diff --git a/src-tauri/fileio/src/import_tests.rs b/src-tauri/fileio/src/import_tests.rs index a6016793..2da23cb5 100644 --- a/src-tauri/fileio/src/import_tests.rs +++ b/src-tauri/fileio/src/import_tests.rs @@ -2,7 +2,10 @@ // Schraffuren, Meshes, Texte), dazu Bulges, Binär-DXF und DWG per Rundreise (acadrust schreibt). use super::*; -use acadrust::entities::{Block, Face3D, Line, LwVertex, Text as AText}; +use acadrust::entities::{ + AttributeDefinition, AttributeEntity, Block, Dimension, DimensionLinear, Face3D, Leader, Line, LwVertex, + MultiLeaderBuilder, Solid, Text as AText, +}; use acadrust::tables::BlockRecord; use acadrust::{DwgWriter, DxfWriter, Handle, Vector2}; @@ -313,10 +316,11 @@ fn kodierung_aufbau() { )) .unwrap(); let (g, s) = encode(&d); - assert_eq!(g[0], 1.0); + assert_eq!(g[0], 2.0); assert_eq!(g[1], 0.0); + assert_eq!(g[3], 1.0); // Einheitenfaktor (ohne $INSUNITS: 1) // Schichtfarben/Zählungen überspringen bis zur Kontur. - let mut i = 4; + let mut i = 5; let n_lc = g[i] as usize; i += 1 + 2 * n_lc; let n_counts = g[i] as usize; @@ -341,3 +345,290 @@ fn periodische_spline_geschlossen() { assert!((a[0] - b[0]).hypot(a[1] - b[1]) < 2.0); assert!(sample_periodic(&cps, &[0.0, 1.0], 3).is_none()); } + +// ── $INSUNITS ──────────────────────────────────────────────────────────────── + +/// DXF mit Kopf-Variable `$INSUNITS` und einer Linie, einem Kreis (r = 2) und einem Text (h = 1). +fn dxf_units(units: &str) -> Vec { + let mut l = vec!["0", "SECTION", "2", "HEADER", "9", "$INSUNITS", "70", units, "0", "ENDSEC"]; + l.extend(["0", "SECTION", "2", "ENTITIES"]); + l.extend(["0", "LINE", "8", "0", "10", "1000", "20", "2000", "30", "500", "11", "3000", "21", "2000", "31", "500"]); + l.extend(["0", "CIRCLE", "8", "0", "10", "0", "20", "0", "30", "0", "40", "2"]); + l.extend(["0", "TEXT", "8", "0", "10", "100", "20", "200", "30", "0", "40", "1", "1", "T"]); + l.extend(["0", "ENDSEC", "0", "EOF"]); + l.join("\n").into_bytes() +} + +fn plain_line(d: &ImportData) -> &Contour { + d.contours.iter().find(|c| c.curve.is_none()).unwrap() +} + +#[test] +fn einheiten_faktoren() { + assert_eq!(unit_scale(0), 1.0); + assert_eq!(unit_scale(6), 1.0); + assert_eq!(unit_scale(4), 0.001); + assert_eq!(unit_scale(5), 0.01); + assert_eq!(unit_scale(1), 0.0254); + assert_eq!(unit_scale(2), 0.3048); + assert_eq!(unit_scale(14), 0.1); + assert_eq!(unit_scale(7), 1000.0); + assert_eq!(unit_scale(-3), 1.0); + assert_eq!(unit_scale(999), 1.0); +} + +#[test] +fn insunits_millimeter_rechnet_in_meter() { + let d = import_bytes(&dxf_units("4")).unwrap(); + assert_eq!((d.ins_units, d.unit_scale), (4, 0.001)); + let line = plain_line(&d); + assert!(close(line.pts[0][0], 1.0) && close(line.pts[0][1], 2.0) && close(line.pts[1][0], 3.0)); + assert!(close(line.z, 0.5)); + let circle = d.contours.iter().find(|c| c.curve.is_some()).unwrap().curve.unwrap(); + assert!(close(circle.r, 0.002)); + assert!(close(d.texts[0].x, 0.1) && close(d.texts[0].y, 0.2) && close(d.texts[0].height, 0.001)); +} + +#[test] +fn insunits_zentimeter_und_zoll() { + let d = import_bytes(&dxf_units("5")).unwrap(); + assert!(close(plain_line(&d).pts[1][0], 30.0)); + let d = import_bytes(&dxf_units("1")).unwrap(); + assert!(close(plain_line(&d).pts[0][0], 25.4)); +} + +#[test] +fn insunits_meter_ohne_einheit_und_unbekannt_bleiben_unveraendert() { + for u in ["6", "0", "77"] { + let d = import_bytes(&dxf_units(u)).unwrap(); + assert_eq!(d.unit_scale, 1.0, "{u}"); + let line = plain_line(&d); + assert_eq!((line.pts[0][0], line.pts[1][0]), (1000.0, 3000.0), "{u}"); + } + // Ohne $INSUNITS im Kopf: wie bisher 1:1. + let d = import_bytes(&dxf(&[], &[&["0", "LINE", "8", "0", "10", "5", "20", "0", "30", "0", "11", "6", "21", "0", "31", "0"]])).unwrap(); + assert_eq!(d.unit_scale, 1.0); + assert_eq!(d.contours[0].pts[0][0], 5.0); +} + +#[test] +fn insunits_wirkt_auch_in_bloecken_und_meshes() { + let mut doc = CadDocument::new(); + doc.header.insertion_units = 4; + add_block(&mut doc, "B", vec![EntityType::Line(Line::from_points(Vector3::ZERO, Vector3::new(1000.0, 0.0, 0.0)))]); + let mut ins = Insert::new("B", Vector3::new(2000.0, 0.0, 0.0)); + ins.rotation = std::f64::consts::FRAC_PI_2; + doc.add_entity(EntityType::Insert(ins)).unwrap(); + doc.add_entity(EntityType::Face3D(Face3D::new( + Vector3::new(0.0, 0.0, 1000.0), + Vector3::new(1000.0, 0.0, 1000.0), + Vector3::new(1000.0, 1000.0, 1000.0), + Vector3::new(0.0, 1000.0, 1000.0), + ))) + .unwrap(); + let d = map_document(SourceKind::Dxf, &doc); + let c = only_contour(&d); + assert!(close(c.pts[0][0], 2.0) && close(c.pts[1][0], 2.0) && close(c.pts[1][1], 1.0)); + assert!(close(d.meshes[0].positions[2], 1.0) && close(d.meshes[0].positions[3], 1.0)); +} + +// ── SOLID/TRACE, DIMENSION, LEADER, MULTILEADER, ATTRIB/ATTDEF ────────────────── + +/// Legt einen Block mit Inhalt an (Eintrag in der Blocktabelle + BLOCK-Marke + Entitäten). +fn add_block(doc: &mut CadDocument, name: &str, entities: Vec) { + let mut record = BlockRecord::new(name); + record.handle = doc.allocate_handle(); + let owner: Handle = record.handle; + doc.block_records.add(record).unwrap(); + let mut marker = Block::new(name, Vector3::ZERO); + marker.common.owner_handle = owner; + let marker_handle = doc.add_entity(EntityType::Block(marker)).unwrap(); + doc.block_records.get_mut(name).unwrap().block_entity_handle = marker_handle; + for mut e in entities { + e.common_mut().owner_handle = owner; + doc.add_entity(e).unwrap(); + } +} + +fn v(x: f64, y: f64) -> Vector3 { + Vector3::new(x, y, 0.0) +} + +/// Dokument als (Modell direkt, ASCII-DXF, DWG) — alle drei Wege müssen dasselbe liefern. +fn all_paths(doc: &CadDocument) -> Vec { + vec![ + map_document(SourceKind::Dxf, doc), + import_bytes(&DxfWriter::new(doc).write_to_vec().unwrap()).unwrap(), + import_bytes(&DwgWriter::write_to_vec(doc).unwrap()).unwrap(), + ] +} + +#[test] +fn solid_viereck_in_dxf_reihenfolge_und_dreieck() { + let mut doc = CadDocument::new(); + doc.layers.add(acadrust::Layer::new("S")).unwrap(); + // Ecken 1, 2, 3, 4 wie in der Datei: Umlaufreihenfolge ist 1, 2, 4, 3. + let mut quad = Solid::new(v(0.0, 0.0), v(2.0, 0.0), v(0.0, 1.0), v(2.0, 1.0)); + quad.common.layer = "S".into(); + doc.add_entity(EntityType::Solid(quad)).unwrap(); + doc.add_entity(EntityType::Solid(Solid::new(v(5.0, 0.0), v(6.0, 0.0), v(5.0, 1.0), v(5.0, 1.0)))).unwrap(); + for d in all_paths(&doc) { + assert_eq!(d.contours.len(), 2, "{:?}", d.contours); + let q = &d.contours[0]; + assert!(q.filled && q.closed); + assert_eq!(q.layer, "S"); + assert_eq!(q.pts, vec![[0.0, 0.0], [2.0, 0.0], [2.0, 1.0], [0.0, 1.0]]); + let t = &d.contours[1]; + assert!(t.filled && t.closed); + assert_eq!(t.pts, vec![[5.0, 0.0], [6.0, 0.0], [5.0, 1.0]]); + } +} + +#[test] +fn trace_wird_wie_solid_gelesen() { + let d = import_bytes(&dxf( + &[], + &[&["0", "TRACE", "8", "T", "10", "0", "20", "0", "30", "0", "11", "1", "21", "0", "31", "0", "12", "0", "22", "1", "32", "0", "13", "1", "23", "1", "33", "0"]], + )) + .unwrap(); + let c = only_contour(&d); + assert!(c.filled && c.closed); + assert_eq!(c.pts, vec![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]); +} + +/// Bemassung samt Anonymblock `*D1` (Massline + Hilfslinie + Massstext). +fn dim_doc() -> CadDocument { + let mut doc = CadDocument::new(); + add_block( + &mut doc, + "*D1", + vec![ + EntityType::Line(Line::from_points(v(0.0, 1.0), v(4.0, 1.0))), + EntityType::Line(Line::from_points(v(0.0, 0.0), v(0.0, 1.2))), + EntityType::Text(AText::with_value("4.00", v(2.0, 1.1)).with_height(0.18)), + ], + ); + let mut dim = DimensionLinear::new(v(0.0, 0.0), v(4.0, 0.0)); + dim.base.block_name = "*D1".into(); + dim.base.common.layer = "Bem".into(); + doc.add_entity(EntityType::Dimension(Box::new(Dimension::Linear(dim)))).unwrap(); + doc +} + +#[test] +fn bemassung_ueber_anonymblock() { + for d in all_paths(&dim_doc()) { + assert_eq!(d.contours.len(), 2, "{:?}", d.contours); + assert!(d.contours.iter().all(|c| c.layer == "Bem" || c.layer == "0")); + assert!(d.contours.iter().any(|c| close(c.pts[1][0], 4.0))); + assert_eq!(d.texts.len(), 1); + assert_eq!(d.texts[0].text, "4.00"); + assert!(close(d.texts[0].height, 0.18)); + assert!(d.entity_counts.iter().any(|(n, _)| n.starts_with("DIMENSION"))); + } +} + +#[test] +fn bemassung_ohne_block_zeigt_massstext() { + let mut doc = CadDocument::new(); + let mut dim = DimensionLinear::new(v(0.0, 0.0), v(3.5, 0.0)); + dim.base.text_middle_point = v(1.75, 0.5); + doc.add_entity(EntityType::Dimension(Box::new(Dimension::Linear(dim)))).unwrap(); + let d = map_document(SourceKind::Dxf, &doc); + assert!(d.contours.is_empty()); + assert_eq!(d.texts.len(), 1); + assert_eq!(d.texts[0].text, "3.5"); + assert!(close(d.texts[0].x, 1.75)); +} + +#[test] +fn bemassung_in_millimetern_wird_umgerechnet() { + let mut doc = dim_doc(); + doc.header.insertion_units = 4; + let d = map_document(SourceKind::Dxf, &doc); + assert!(d.contours.iter().any(|c| close(c.pts[1][0], 0.004))); + assert!(close(d.texts[0].height, 0.00018)); +} + +#[test] +fn leader_linienzug() { + let mut doc = CadDocument::new(); + doc.layers.add(acadrust::Layer::new("F")).unwrap(); + let l = Leader::new().with_vertex(v(0.0, 0.0)).with_vertex(v(1.0, 1.0)).with_vertex(v(2.0, 1.0)).with_layer("F"); + doc.add_entity(EntityType::Leader(l)).unwrap(); + let d = map_document(SourceKind::Dxf, &doc); + let c = only_contour(&d); + assert_eq!(c.layer, "F"); + assert!(!c.closed); + assert_eq!(c.pts, vec![[0.0, 0.0], [1.0, 1.0], [2.0, 1.0]]); +} + +#[test] +fn multileader_linie_und_text() { + let mut doc = CadDocument::new(); + let ml = MultiLeaderBuilder::new() + .text("Beton C25/30", v(3.0, 2.0)) + .text_height(0.2) + .leader_line(vec![v(0.0, 0.0), v(2.0, 1.5)]) + .build(); + doc.add_entity(EntityType::MultiLeader(Box::new(ml))).unwrap(); + let d = map_document(SourceKind::Dxf, &doc); + assert!(!d.contours.is_empty(), "keine Führungslinie"); + let c = &d.contours[0]; + assert!(!c.closed && c.pts.len() >= 2); + assert!(c.pts.iter().any(|p| close(p[0], 0.0) && close(p[1], 0.0))); + assert_eq!(d.texts.len(), 1); + assert_eq!(d.texts[0].text, "Beton C25/30"); + assert!(close(d.texts[0].height, 0.2)); + assert!(close(d.texts[0].x, 3.0) && close(d.texts[0].y, 2.0)); +} + +/// Block mit ATTDEFs (Raumnummer, Fläche, unsichtbar) und einem INSERT mit nur einem ATTRIB. +fn attrib_doc() -> CadDocument { + let mut doc = CadDocument::new(); + let nr = AttributeDefinition::new("NR".into(), "Nummer".into(), "000".into()).with_position(v(0.5, 0.5)).with_height(0.2); + let area = AttributeDefinition::new("FLAECHE".into(), "Fläche".into(), "0 m²".into()).with_position(v(0.5, 0.1)).with_height(0.1); + let hidden = AttributeDefinition::new("GEHEIM".into(), "".into(), "x".into()).with_invisible(); + let frame = Line::from_points(v(0.0, 0.0), v(1.0, 0.0)); + add_block( + &mut doc, + "RAUM", + vec![ + EntityType::Line(frame), + EntityType::AttributeDefinition(nr), + EntityType::AttributeDefinition(area), + EntityType::AttributeDefinition(hidden), + ], + ); + let mut ins = Insert::new("RAUM", v(10.0, 20.0)); + // ATTRIB-Positionen stehen in Weltkoordinaten. + ins.attributes.push(AttributeEntity::new("NR".into(), "101".into()).with_position(v(10.5, 20.5)).with_height(0.2)); + doc.add_entity(EntityType::Insert(ins)).unwrap(); + doc +} + +#[test] +fn attrib_und_attdef_als_text() { + let doc = attrib_doc(); + let paths = [map_document(SourceKind::Dxf, &doc), import_bytes(&DxfWriter::new(&doc).write_to_vec().unwrap()).unwrap()]; + for d in paths { + // NR kommt als ATTRIB (101, Weltposition), nicht als Vorgabewert 000; FLAECHE hat kein + // ATTRIB → Vorgabewert mit der Einfügeverschiebung; GEHEIM ist unsichtbar. + let mut texts: Vec<(&str, f64, f64)> = d.texts.iter().map(|t| (t.text.as_str(), t.x, t.y)).collect(); + texts.sort_by(|a, b| a.0.cmp(b.0)); + assert_eq!(texts.len(), 2, "{texts:?}"); + assert_eq!(texts[0].0, "0 m²"); + assert!(close(texts[0].1, 10.5) && close(texts[0].2, 20.1), "{texts:?}"); + assert_eq!(texts[1].0, "101"); + assert!(close(texts[1].1, 10.5) && close(texts[1].2, 20.5), "{texts:?}"); + } +} + +#[test] +fn attrib_in_zentimeterzeichnung() { + let mut doc = attrib_doc(); + doc.header.insertion_units = 5; // cm + let d = map_document(SourceKind::Dxf, &doc); + let a = d.texts.iter().find(|t| t.text == "101").unwrap(); + assert!(close(a.x, 0.105) && close(a.height, 0.002)); +} diff --git a/src/export/exportDxf.ezdxf.test.ts b/src/export/exportDxf.ezdxf.test.ts index ca8d51a3..9ce19cd3 100644 --- a/src/export/exportDxf.ezdxf.test.ts +++ b/src/export/exportDxf.ezdxf.test.ts @@ -25,6 +25,10 @@ interface EzEntity { pts?: number[][]; closed?: boolean; text?: string; + solid?: boolean; + paths?: number; + pattern_lines?: number; + rgb?: number[] | null; } interface EzResult { version: string; @@ -92,4 +96,30 @@ describe.skipIf(!hasEzdxf)("DXF-Export gegen ezdxf", { timeout: 60_000 }, () => expect.objectContaining({ type: "TEXT", layer: `${cat0.code}_Gelände_Süd`, text: "Grünfläche ≥ 30 %" }), ]); }); + + it("HATCH: Vollfüllung, Kreuzschraffur und gestrichelt — ezdxf liest Rand, Farbe, Musterzeilen ohne Auditor-Fehler", () => { + const sq = [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }, { x: 0, y: 3 }]; + const poly = (hatch: object) => ({ + kind: "polygon", pts: sq, fill: "#eee", stroke: "#111", strokeWidthMm: 0.25, + hatch: { pattern: "crosshatch", scale: 1, angle: 45, color: "#336699", lineWeight: 0.13, dash: null, ...hatch }, + }); + const plan = { + primitives: [poly({ pattern: "solid" }), poly({}), poly({ pattern: "diagonal", dash: [2, 1] })], + bounds: { minX: 0, minY: 0, maxX: 4, maxY: 3 }, + } as unknown as Plan; + const r = ezdxfRead("hatch", buildPlanDxf(plan, sampleProject)); + expect(r.result, r.err).not.toBeNull(); + expect(r.result!.errors).toEqual([]); + expect(r.status).toBe(0); + const hs = r.result!.entities.filter((e) => e.type === "HATCH"); + expect(hs.length).toBe(3); + expect(hs.map((h) => h.solid)).toEqual([true, false, false]); + expect(hs.map((h) => h.pattern_lines)).toEqual([0, 2, 1]); + for (const h of hs) { + expect(h.layer).toBe("HATCH"); + expect(h.paths).toBe(1); + expect(h.rgb).toEqual([0x33, 0x66, 0x99]); + expect(h.pts).toEqual(sq.map((p) => [p.x, p.y])); + } + }); }); diff --git a/src/export/exportDxf.gradient.test.ts b/src/export/exportDxf.gradient.test.ts index 27995a7b..817cb166 100644 --- a/src/export/exportDxf.gradient.test.ts +++ b/src/export/exportDxf.gradient.test.ts @@ -9,7 +9,7 @@ import { describe, expect, it } from "vitest"; import "../engine/fileioWasm.setup"; import { buildPlanDxf } from "./exportDxf"; -import { readDxf } from "./cadReadBack.testutil"; +import { nums, readDxf } from "./cadReadBack.testutil"; import { sampleProject } from "../model/sampleProject"; import type { Plan } from "../plan/generatePlan"; import type { HatchRender } from "../plan/generatePlan/shared"; @@ -49,10 +49,13 @@ function polyWith(hatchOver: Partial = {}): Plan["primitives"][numb } describe("buildPlanDxf — Verlauf-Schraffur", () => { - it("vektor+crosshatch: erzeugt Musterlinien (Gegenprobe)", () => { + it("vektor+crosshatch: erzeugt eine HATCH-Entität mit zwei Musterzeilen (Gegenprobe)", () => { const dxf = buildPlanDxf(planWith([polyWith()]), sampleProject); - expect(countEntities(dxf, "LINE")).toBeGreaterThan(0); - expect(countEntities(dxf, "LWPOLYLINE")).toBe(1); // nur der Umriss + expect(countEntities(dxf, "HATCH")).toBe(1); + expect(countEntities(dxf, "LINE")).toBe(0); // keine einzelnen Schraffurlinien mehr + expect(countEntities(dxf, "LWPOLYLINE")).toBe(1); // der Umriss + const h = readDxf(dxf).entities.find((e) => e.type === "HATCH")!; + expect(nums(h, 53).map((a) => Math.round(a))).toEqual([0, 90]); }); it("gradient: KEINE Musterlinien, nur die Umriss-Polylinie", () => { @@ -66,6 +69,7 @@ describe("buildPlanDxf — Verlauf-Schraffur", () => { sampleProject, ); expect(countEntities(dxf, "LINE")).toBe(0); + expect(countEntities(dxf, "HATCH")).toBe(0); expect(countEntities(dxf, "LWPOLYLINE")).toBe(1); // Umriss bleibt erhalten }); }); diff --git a/src/export/exportDxf.roundtrip.test.ts b/src/export/exportDxf.roundtrip.test.ts index 7e8caa3c..f11c8e10 100644 --- a/src/export/exportDxf.roundtrip.test.ts +++ b/src/export/exportDxf.roundtrip.test.ts @@ -31,6 +31,12 @@ function flatCounts(plan: Plan, project: Project): Record { 4: ["ARC", () => 7], 5: ["CIRCLE", () => 5], 6: ["TEXT", () => 7], + // HATCH: tag, layer, mode, rgb, n_dash, dash…, n_fam, (angle, spacing)…, n, pts… + 7: ["HATCH", (i) => { + const nd = flat[i + 4]; + const nf = flat[i + 5 + nd]; + return 5 + nd + 1 + 2 * nf + 1 + 2 * flat[i + 5 + nd + 1 + 2 * nf]; + }], }; const out: Record = {}; for (let i = 1; i < flat.length; ) { @@ -64,7 +70,26 @@ describe("DXF-Export (R2018 über acadrust)", () => { expect(dxf.entities.every((e) => dxf.layers.has(e.layer))).toBe(true); }); - it("ohne Schraffuren: nur die HATCH-Linien fallen weg", () => { + it("Schraffuren sind echte HATCH-Entitäten mit Rand, Farbe und Muster", () => { + const hatches = readDxf(buildPlanDxf(plan, sampleProject)).entities.filter((e) => e.type === "HATCH"); + expect(hatches.length).toBeGreaterThan(0); + for (const h of hatches) { + expect(h.layer).toBe("HATCH"); + expect(Number(str(h, 91))).toBe(1); // ein Randpfad + expect(nums(h, 10).length).toBeGreaterThanOrEqual(3); // Polylinien-Rand + } + const solid = hatches.filter((h) => Number(str(h, 70)) === 1); + const pattern = hatches.filter((h) => Number(str(h, 70)) === 0); + for (const h of pattern) { + expect(Number(str(h, 78))).toBeGreaterThanOrEqual(1); // Musterzeilen + expect(nums(h, 53).length).toBeGreaterThanOrEqual(1); + const [ox, oy] = [nums(h, 45), nums(h, 46)]; + for (let i = 0; i < ox.length; i++) expect(Math.hypot(ox[i], oy[i])).toBeGreaterThanOrEqual(0.02 - 1e-9); // Linienabstand ≥ 2 cm + } + expect(solid.length + pattern.length).toBe(hatches.length); + }); + + it("ohne Schraffuren: alle HATCH-Entitäten (und Zufallsstriche) fallen weg, der Rest bleibt", () => { const withH = readDxf(buildPlanDxf(plan, sampleProject)).entities; const without = readDxf(buildPlanDxf(plan, sampleProject, { includeHatches: false })).entities; expect(without.some((e) => e.layer === "HATCH")).toBe(false); diff --git a/src/export/exportDxf.ts b/src/export/exportDxf.ts index 6bba17c1..676f2c3c 100644 --- a/src/export/exportDxf.ts +++ b/src/export/exportDxf.ts @@ -25,7 +25,7 @@ import { fileio, loadFileio } from "../engine/fileioWasm"; export interface ExportDxfOptions { /** Titel/Geschossname (nur als Kommentar-freundlicher Dateiname genutzt). */ title?: string; - /** Schraffurlinien mit ausgeben (true) oder nur Umrisse/Flächen (false). */ + /** Schraffuren (echte HATCH-Entitäten: Vollfüllung, Linienmuster) mit ausgeben (true) oder nur Umrisse (false). */ includeHatches?: boolean; /** Dateiname des Downloads (mit/ohne Endung). */ fileName?: string; @@ -53,6 +53,7 @@ const REC_POLYLINE = 3; const REC_ARC = 4; const REC_CIRCLE = 5; const REC_TEXT = 6; +const REC_HATCH = 7; /** * Sammelt Ebenen und Entitäten als flachen Zahlenpuffer + Zeichenkettenliste. Ebenen sind @@ -107,6 +108,26 @@ export class FlatDrawing { this.nums.push(REC_TEXT, this.layer(layer), this.str(value), at.x, at.y, height, rotation); } + /** + * Schraffur als echte HATCH-Entität (äusserer Rand `pts`, geschlossen). `solid` = Vollfüllung; + * sonst Linienmuster aus `families` (Winkel in Radiant, Linienabstand in Metern; je Schar eine + * Musterzeile) mit optionalem Strichmuster `dashes` (Meter: an, aus, …; leer = durchgezogen). + * `rgb` null = Farbe der Ebene. + */ + addHatch( + layer: string, + pts: Vec2[], + opts: { solid: boolean; rgb: number | null; families?: { angle: number; spacing: number }[]; dashes?: number[] }, + ): void { + if (pts.length < 3) return; + const families = opts.solid ? [] : (opts.families ?? []); + const dashes = opts.solid ? [] : (opts.dashes ?? []); + this.nums.push(REC_HATCH, this.layer(layer), opts.solid ? 0 : 1, opts.rgb ?? -1, dashes.length, ...dashes, families.length); + for (const f of families) this.nums.push(f.angle, f.spacing); + this.nums.push(pts.length); + for (const p of pts) this.nums.push(p.x, p.y); + } + /** Argumente für die Rust-Bindungen. */ args(): [Float64Array, string] { return [Float64Array.from(this.nums), this.strings.join("\0")]; @@ -266,37 +287,38 @@ function emitPrimitive( case "polygon": { const pts = p.pts; if (pts.length < 2) break; - // Kreis-Approximationen (viele Segmente) bleiben als geschlossene Polylinie — - // masshaltig und robust. Geschlossene Ringe bekommen das Ring-Flag. - dxf.addPolyline(layer, pts, true); - // Schraffur als geklippte Linien (optional). Vollfüllung/„none" tragen keine - // sichtbaren Musterlinien → wir geben nur echte Muster (nicht solid/none) aus. - // Bild-/Verlauf-Schraffur (kind==="image"/"gradient"): DXF trägt weder - // Rasterbilder noch (hier) echte Farbverläufe → FALLBACK ohne - // Musterlinien (nur die Umriss-Polylinie oben). Random-Vektor: - // deterministische Streu-Striche (Modell-Meter, identischer Seed wie Bildschirm/PDF). - if ( - includeHatches && - p.hatch.kind !== "image" && - p.hatch.kind !== "gradient" && - p.hatch.pattern !== "none" && - p.hatch.pattern !== "solid" - ) { - const cycle = dashCycleMeters(p.hatch.dash); - const segs: Seg[] = - p.hatch.lines === "random" - ? buildRandomHatchRuns(pts, p.hatch) - .filter((r) => r.length >= 2) - .map((r) => ({ a: r[0], b: r[r.length - 1] })) - : hatchSegments(pts, p.hatch); - for (const seg of segs) { - if (cycle) { - for (const d of dashSeg(seg, cycle)) dxf.addLine(LAYER_HATCH, d.a, d.b); - } else { - dxf.addLine(LAYER_HATCH, seg.a, seg.b); + // Schraffur ([C2], 28.10.) als echte HATCH-Entität UNTER dem Umriss (Zeichenreihenfolge der + // Datei): Vollfüllung bzw. Linienmuster (diagonal/Kreuz/Dämmung/frei, auch gestrichelt) mit dem + // Polygon als Rand und der aufgelösten Vordergrundfarbe. Bild-/Verlauf-Schraffur (kind==="image"/ + // "gradient") trägt DXF nicht → FALLBACK ohne Muster (nur der Umriss). Random-Vektor + // (deterministische Streu-Striche, Modell-Meter, identischer Seed wie Bildschirm/PDF) hat kein + // Musteräquivalent → bleibt als einzelne Linien auf dem HATCH-Layer. + if (includeHatches && p.hatch.kind !== "image" && p.hatch.kind !== "gradient" && pts.length >= 3) { + const h = p.hatch; + if (h.pattern === "solid") { + dxf.addHatch(LAYER_HATCH, pts, { solid: true, rgb: rgbOrNull(h.color) }); + } else if (h.pattern !== "none" && h.lines === "random") { + const cycle = dashCycleMeters(h.dash); + const segs: Seg[] = buildRandomHatchRuns(pts, h) + .filter((r) => r.length >= 2) + .map((r) => ({ a: r[0], b: r[r.length - 1] })); + for (const seg of segs) { + if (cycle) { + for (const d of dashSeg(seg, cycle)) dxf.addLine(LAYER_HATCH, d.a, d.b); + } else { + dxf.addLine(LAYER_HATCH, seg.a, seg.b); + } + } + } else if (h.pattern !== "none") { + const families = hatchFamilies(h); + if (families.length > 0) { + dxf.addHatch(LAYER_HATCH, pts, { solid: false, rgb: rgbOrNull(h.color), families, dashes: dashCycleMeters(h.dash) ?? [] }); } } } + // Kreis-Approximationen (viele Segmente) bleiben als geschlossene Polylinie — + // masshaltig und robust. Geschlossene Ringe bekommen das Ring-Flag. + dxf.addPolyline(layer, pts, true); break; } } @@ -331,10 +353,10 @@ function angleRad(c: Vec2, p: Vec2): number { return a < 0 ? a + 2 * Math.PI : a; } -// ── Schraffur als geklippte Vektorlinien (Meter) ──────────────────────────── -// Wie planToPrintSvg, aber in WELT-Metern statt Papier-mm. Die Kachelgrösse der -// Bildschirm-PlanView (8 bzw. 10 Einheiten × scale, 1 Einheit = 1/90 m) wird -// direkt in einen Meter-Linienabstand übersetzt. +// ── Schraffur-Muster in Metern ─────────────────────────────────────────────── +// Die Kachelgrösse der Bildschirm-PlanView (8 bzw. 10 Einheiten × scale, 1 Einheit = 1/90 m) wird +// direkt in einen Meter-Linienabstand übersetzt (`hatchFamilies`); die Zufallsstriche und das +// Strichmuster laufen weiter über geklippte Segmente (`dashSeg`). interface Seg { a: Vec2; @@ -379,63 +401,21 @@ function dashSeg(seg: Seg, cycle: number[]): Seg[] { return out; } -function hatchSegments( - poly: Vec2[], - hatch: Extract["hatch"], -): Seg[] { +/** + * Linienscharen einer Vektor-Schraffur als (Winkel in Radiant, Abstand in Metern): wie Bildschirm + * und PDF eine Schar (diagonal, frei), Kreuzschraffur zusätzlich um 90° gedreht, Dämmung zusätzlich + * bei −45°. Kachelgrösse wie `hatchSegments` früher: (8 bzw. 10) × scale / 90 m, mindestens 2 cm. + */ +function hatchFamilies(hatch: Extract["hatch"]): { angle: number; spacing: number }[] { const unitM = 1 / 90; const tileM = (hatch.pattern === "insulation" ? 10 : 8) * hatch.scale * unitM; const spacing = Math.max(0.02, tileM); // Mindestabstand in Metern + if (!Number.isFinite(spacing)) return []; const angle = (hatch.angle * Math.PI) / 180; - const segs: Seg[] = []; - fillParallel(poly, angle, spacing, segs); - if (hatch.pattern === "crosshatch") fillParallel(poly, angle + Math.PI / 2, spacing, segs); - if (hatch.pattern === "insulation") fillParallel(poly, angle - Math.PI / 4, spacing, segs); - return segs; -} - -/** - * Füllt ein Polygon mit parallelen Linien (Winkel/Abstand) und klippt jede Linie - * per Scanline auf das Polygon. Robust für konvexe wie einfache konkave Polygone. - */ -function fillParallel(poly: Vec2[], angle: number, spacing: number, out: Seg[]): void { - if (poly.length < 3 || spacing <= 0) return; - const dir = { x: Math.cos(angle), y: Math.sin(angle) }; - const nrm = { x: -dir.y, y: dir.x }; - let tMin = Infinity; - let tMax = -Infinity; - for (const p of poly) { - const t = p.x * nrm.x + p.y * nrm.y; - if (t < tMin) tMin = t; - if (t > tMax) tMax = t; - } - const start = Math.ceil(tMin / spacing) * spacing; - for (let t = start; t <= tMax; t += spacing) { - const xs: number[] = []; - for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { - const a = poly[j]; - const b = poly[i]; - const ta = a.x * nrm.x + a.y * nrm.y; - const tb = b.x * nrm.x + b.y * nrm.y; - if (ta === tb) continue; - const f = (t - ta) / (tb - ta); - if (f < 0 || f > 1) continue; - const px = a.x + (b.x - a.x) * f; - const py = a.y + (b.y - a.y) * f; - xs.push(px * dir.x + py * dir.y); - } - if (xs.length < 2) continue; - xs.sort((u, v) => u - v); - for (let k = 0; k + 1 < xs.length; k += 2) { - const u0 = xs[k]; - const u1 = xs[k + 1]; - if (u1 - u0 < 1e-6) continue; - out.push({ - a: { x: nrm.x * t + dir.x * u0, y: nrm.y * t + dir.y * u0 }, - b: { x: nrm.x * t + dir.x * u1, y: nrm.y * t + dir.y * u1 }, - }); - } - } + const out = [{ angle, spacing }]; + if (hatch.pattern === "crosshatch") out.push({ angle: angle + Math.PI / 2, spacing }); + if (hatch.pattern === "insulation") out.push({ angle: angle - Math.PI / 4, spacing }); + return out; } // ── Farb-/Strich-Umrechnung ───────────────────────────────────────────────── @@ -448,6 +428,12 @@ export function rgbFromHex(hex: string): number { return parseInt(m[1], 16); } +/** "#rrggbb" → 0xRRGGBB, bei unlesbarer Farbe (z. B. "none") null = Farbe der Ebene. */ +function rgbOrNull(hex: string): number | null { + const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim()); + return m ? parseInt(m[1], 16) : null; +} + /** Millimeter → DXF-LWEIGHT (1/100 mm), gerundet auf gültige Stufen ≥ 0. */ export function mmToLwe(mm: number): number { return Math.max(0, Math.round(mm * 100)); diff --git a/src/io/dxfParser.test.ts b/src/io/dxfParser.test.ts index 6f96c237..08e9d02b 100644 --- a/src/io/dxfParser.test.ts +++ b/src/io/dxfParser.test.ts @@ -602,3 +602,63 @@ describe("parseDxf — Polyface-Mesh (POLYLINE Flag 64, swissBUILDINGS3D-Format) expect(res.meshes[0].indices).toEqual([0, 1, 2]); }); }); + +describe("parseDxf — $INSUNITS", () => { + /** DXF mit Kopf-Variable $INSUNITS, einer Linie (Koordinaten in Zeicheneinheiten) und einem Text. */ + const withUnits = (units: number | null): string => { + const head = units === null ? [] : ["0", "SECTION", "2", "HEADER", "9", "$INSUNITS", "70", `${units}`, "0", "ENDSEC"]; + const body = dxf( + ["0", "LINE", "8", "0", "10", "1000", "20", "2000", "30", "0", "11", "3000", "21", "2000", "31", "0"], + ["0", "TEXT", "8", "0", "10", "100", "20", "200", "30", "0", "40", "50", "1", "Raum"], + ); + return [...head, body].join("\n"); + }; + + it("Millimeter → Meter (Koordinaten, Texthöhe), unitScale 0.001", () => { + const res = parseDxf(withUnits(4)); + expect(res.insUnits).toBe(4); + expect(res.unitScale).toBe(0.001); + const c = res.contours[0].contours[0]; + expect(c.pts[0].x).toBeCloseTo(1, 12); + expect(c.pts[1].x).toBeCloseTo(3, 12); + expect(c.pts[0].y).toBeCloseTo(2, 12); + const t = res.texts![0]; + expect(t.at.x).toBeCloseTo(0.1, 12); + expect(t.height).toBeCloseTo(0.05, 12); + }); + + it("Zentimeter und Zoll", () => { + expect(parseDxf(withUnits(5)).contours[0].contours[0].pts[1].x).toBeCloseTo(30, 12); + expect(parseDxf(withUnits(1)).contours[0].contours[0].pts[0].x).toBeCloseTo(25.4, 12); + }); + + it("Meter, ohne Einheit (0), unbekannt und fehlend bleiben 1:1", () => { + for (const u of [6, 0, 77, null]) { + const res = parseDxf(withUnits(u)); + expect(res.unitScale, `${u}`).toBe(1); + expect(res.contours[0].contours[0].pts[0].x, `${u}`).toBe(1000); + } + }); +}); + +describe("parseDxf — SOLID/TRACE", () => { + it("SOLID (Eckenfolge 1,2,4,3) → gefüllte geschlossene Kontur → Drawing2D mit Füllung", () => { + const res = parseDxf( + dxf(["0", "SOLID", "8", "S", "10", "0", "20", "0", "30", "0", "11", "2", "21", "0", "31", "0", "12", "0", "22", "1", "32", "0", "13", "2", "23", "1", "33", "0"]), + ); + const c = res.contours[0].contours[0]; + expect(c.filled).toBe(true); + expect(c.closed).toBe(true); + expect(c.pts).toEqual([{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 1 }, { x: 0, y: 1 }]); + const [d] = contoursToDrawings(res.contours, "L", "active", "01", () => "01"); + expect(d.fillColor).toBeDefined(); + }); + + it("Dreieck: dritte = vierte Ecke", () => { + const c = onlyContour( + dxf(["0", "TRACE", "8", "S", "10", "0", "20", "0", "30", "0", "11", "1", "21", "0", "31", "0", "12", "0", "22", "1", "32", "0", "13", "0", "23", "1", "33", "0"]), + ); + expect(c.pts).toHaveLength(3); + expect(c.filled).toBe(true); + }); +}); diff --git a/src/io/dxfParser.ts b/src/io/dxfParser.ts index 11be3923..8b84049c 100644 --- a/src/io/dxfParser.ts +++ b/src/io/dxfParser.ts @@ -5,9 +5,10 @@ // semantisch. Rust liest DXF (ASCII und Binär, R12–2018+) und DWG (R13–2018) und liefert einen // flachen Puffer + String-Tabelle; hier wird daraus `DxfImportResult` (Konturen, Texte, Meshes, // Ebenenfarben, Diagnose, $INSUNITS). Abgebildet werden LINE, LWPOLYLINE/POLYLINE (inkl. Bulges), -// ARC/CIRCLE (mit wahrer Kurve), ELLIPSE, SPLINE, HATCH (gefüllte Ränder), TEXT/MTEXT, 3DFACE, +// ARC/CIRCLE (mit wahrer Kurve), ELLIPSE, SPLINE, HATCH und SOLID/TRACE (gefüllte Flächen), TEXT/MTEXT, +// ATTRIB/ATTDEF, DIMENSION (über den Anonymblock), LEADER/MULTILEADER (Linien + Text), 3DFACE, // Polyface-/Polygon-Mesh, MESH; INSERT wird rekursiv aufgelöst (Basispunkt, Skalierung, Drehung, -// Raster; Ebene „0" erbt die Ebene der Referenz). +// Raster; Ebene „0" erbt die Ebene der Referenz). `$INSUNITS` rechnet Rust auf Meter um. // // `parseDxf` ist synchron und verlangt das geladene Modul (`loadFileio()`); die App ruft es im // Web-Worker (`dxfParserAsync.ts`), Tests laden es per `loadFileioForTests()`. @@ -38,8 +39,14 @@ export interface DxfImportResult { diagnostics?: ImportDiagnostics; /** Farbe je DXF-Layer (Hex) aus der LAYER-Tabelle — für neu angelegte Kategorien. */ layerColors?: Record; - /** `$INSUNITS` der Datei (0 = ohne Einheit, 4 = mm, 5 = cm, 6 = m …); Koordinaten bleiben 1:1. */ + /** `$INSUNITS` der Datei (0 = ohne Einheit, 4 = mm, 5 = cm, 6 = m …), roh wie gelesen. */ insUnits?: number; + /** + * Meter je Zeicheneinheit nach `$INSUNITS` (mm 0.001, cm 0.01, m 1, Zoll 0.0254 …). Rust hat + * Koordinaten, Radien und Texthöhen damit schon in Meter umgerechnet; hier nur zur Anzeige + * („Datei in mm, umgerechnet“). 0/unbekannt = 1, die Koordinaten bleiben dann 1:1. + */ + unitScale?: number; } let importSeq = 0; @@ -78,9 +85,10 @@ export function decodeImport(geom: Float64Array, strings: readonly string[], idP let i = 0; const num = () => geom[i++]; const str = () => strings[geom[i++]] ?? ""; - if (num() !== 1) throw new Error("Unbekanntes Importformat (Version)."); + if (num() !== 2) throw new Error("Unbekanntes Importformat (Version)."); const fmt = num() === 1 ? "DWG" : "DXF"; const insUnits = num(); + const unitScale = num(); const total = num(); const layerColors: Record = {}; @@ -155,5 +163,5 @@ export function decodeImport(geom: Float64Array, strings: readonly string[], idP contours, }); } - return { meshes, contours: contourSets, texts, layerColors, diagnostics: { entityCounts, total }, insUnits }; + return { meshes, contours: contourSets, texts, layerColors, diagnostics: { entityCounts, total }, insUnits, unitScale }; } diff --git a/src/io/dxfParserAsync.ts b/src/io/dxfParserAsync.ts index d32045c2..6f3510dc 100644 --- a/src/io/dxfParserAsync.ts +++ b/src/io/dxfParserAsync.ts @@ -67,7 +67,7 @@ function mergeResults(results: DxfImportResult[]): DxfImportResult { } diagnostics.total += r.diagnostics?.total ?? 0; } - return { meshes, contours, texts, layerColors, diagnostics, insUnits: results[0]?.insUnits }; + return { meshes, contours, texts, layerColors, diagnostics, insUnits: results[0]?.insUnits, unitScale: results[0]?.unitScale }; } function toArrayBuffer(data: string | ArrayBuffer): ArrayBuffer {