diff --git a/TODO.md b/TODO.md index eccbaa30..3108a78f 100644 --- a/TODO.md +++ b/TODO.md @@ -411,16 +411,22 @@ 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. + - ✅ **Binär-DXF-Export** (28.10.): `export_dxf_binary` (acadrust `DxfWriter::new_binary`, R2018 UTF-8), + Dialog-Format „DXF binär“, CLI `dxf --binary`. Rundreise acadrust + ezdxf (gleiche Entitäten/Ebenen wie + ASCII, 0 Auditor-Fehler, kleiner als der Text). Offen: in AutoCAD/BricsCAD selbst nicht geöffnet. + - ✅ **Verlauf als echte Gradient-HATCH** (28.10.): `kind === "gradient"` → neuer Datensatz `REC_GRADIENT` + (`export.rs`): Name LINEAR/SPHERICAL, Farbstützen 0/1, Winkel = SVG-Richtung der Ansicht. ezdxf liest + Name, Rotation und beide Farben. Offen: Aussehen/Richtung in AutoCAD selbst ungeprüft (Winkel 0 = + Farbe 1 links angenommen); mehr als zwei Farbstützen kennt das Modell nicht. - ✅ **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: + kein Musteräquivalent und bleiben Linien; Bild-Schraffur wie bisher nur Umriss (Verlauf: s. u.). 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. + LV95-Koordinaten); Verlauf siehe unten (jetzt Gradient-HATCH). - ✅ **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 diff --git a/scripts/validate-dxf.py b/scripts/validate-dxf.py index 2998c535..07cd5054 100644 --- a/scripts/validate-dxf.py +++ b/scripts/validate-dxf.py @@ -15,7 +15,14 @@ from ezdxf import recover def main(path: str) -> int: - doc, auditor = recover.readfile(path) + # recover.readfile liest nur ASCII; Binär-DXF ("AutoCAD Binary DXF") geht über readfile + Audit. + with open(path, "rb") as fh: + binary = fh.read(18) == b"AutoCAD Binary DXF" + if binary: + doc = ezdxf.readfile(path) + auditor = doc.audit() + else: + doc, auditor = recover.readfile(path) msp = doc.modelspace() entities = [] for e in msp: @@ -36,6 +43,17 @@ def main(path: str) -> int: 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 + g = e.gradient + item["gradient"] = ( + { + "name": g.name, + "rotation": g.rotation, + "color1": list(g.color1), + "color2": list(g.color2), + } + if g is not None + 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": diff --git a/src-tauri/fileio/src/export.rs b/src-tauri/fileio/src/export.rs index ca02b4d2..a4b5b58b 100644 --- a/src-tauri/fileio/src/export.rs +++ b/src-tauri/fileio/src/export.rs @@ -31,12 +31,16 @@ // 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) // +// GRADIENT = 8, layer, rgb1 (0xRRGGBB), rgb2 (0xRRGGBB), angle (rad, Richtung rgb1 → rgb2, DXF-Konvention), +// kind (0 = linear, 1 = radial: rgb1 in der Mitte, rgb2 am Rand), n, x0, y0, … (äusserer Rand) +// // `layer` ist der Index des LAYER-Datensatzes (Reihenfolge des Auftretens, ab 0), er muss vorher // 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 +// Polylinien-Kante. Farbverläufe (GRADIENT, [C2], 28.10.) sind echte Gradient-HATCHs (Gruppencodes +// 450–470: Name LINEAR bzw. SPHERICAL, zwei Farbstützen 0 und 1, Winkel in Radiant). 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 @@ -44,8 +48,8 @@ // (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, + BoundaryEdge, BoundaryPath, BoundaryPathFlags, Hatch, HatchGradientPattern, HatchPattern, HatchPatternLine, + HatchPatternType, PolylineEdge, }; use acadrust::{ Arc, CadDocument, Circle, Color, DwgWriter, DxfVersion, DxfWriter, EntityType, Layer, Line, @@ -62,6 +66,7 @@ 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; +pub const REC_GRADIENT: f64 = 8.0; /// DXF-Ausgabeversion (s. Kopf). pub const DXF_VERSION: DxfVersion = DxfVersion::AC1032; @@ -192,12 +197,34 @@ fn make_hatch(pts: &[f64], solid: bool, families: &[(f64, f64)], dashes: &[f64]) h.pattern_type = HatchPatternType::Custom; h }; + add_outer_boundary(&mut hatch, pts); + hatch +} + +/// Äusserer Rand als geschlossene Polylinien-Kante. +fn add_outer_boundary(hatch: &mut Hatch, pts: &[f64]) { 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); +} + +/// Zweifarben-Verlauf als Gradient-HATCH (wie AutoCAD: Muster „SOLID“ + Gradient-Gruppencodes). +/// `radial` = Kugelverlauf (`SPHERICAL`), sonst `LINEAR` mit Drehwinkel `angle` (rad). +fn make_gradient_hatch(pts: &[f64], rgb1: u32, rgb2: u32, angle: f64, radial: bool) -> Hatch { + let mut hatch = Hatch::solid(); + let mut g = HatchGradientPattern::new(); + g.enabled = true; + g.angle = if radial { 0.0 } else { angle }; + g.shift = 0.0; + g.is_single_color = false; + g.name = if radial { "SPHERICAL" } else { "LINEAR" }.to_string(); + g.add_color(0.0, layer_color(rgb1 as f64)); + g.add_color(1.0, layer_color(rgb2 as f64)); + hatch.gradient_color = g; + add_outer_boundary(&mut hatch, pts); hatch } @@ -294,6 +321,17 @@ pub fn build_document(flat: &[f64], strings: &str) -> Result= 3 && all_finite(pts) && angle.is_finite() && in_range(rgb1) && in_range(rgb2)).then(|| { + EntityType::Hatch(Box::new(make_gradient_hatch(pts, rgb1 as u32, rgb2 as u32, angle, kind == 1.0))) + }) } else { return Err(format!("unbekannter Datensatz {tag} bei {}", r.pos - 1)); }; @@ -314,6 +352,16 @@ pub fn export_dxf(flat: &[f64], strings: &str) -> Result, String> { .map_err(|e| format!("DXF schreiben: {e}")) } +/// Flache Zeichnung → Binär-DXF-Bytes (R2018, UTF-8). acadrust hebt R2000/R2004 bei Binär-DXF selbst auf +/// R2010 an (BricsCAD lehnt die alten Köpfe ab); R2018 ist davon unberührt. +pub fn export_dxf_binary(flat: &[f64], strings: &str) -> Result, String> { + let doc = build_document(flat, strings)?; + DxfWriter::new_binary(&doc) + .with_version(DXF_VERSION) + .write_to_vec() + .map_err(|e| format!("Binär-DXF schreiben: {e}")) +} + /// Flache Zeichnung → DWG-Bytes (R2018). pub fn export_dwg(flat: &[f64], strings: &str) -> Result, String> { export_dwg_version(flat, strings, DWG_VERSION) @@ -341,6 +389,12 @@ mod web { super::export_dxf(flat, strings).unwrap_or_default() } + /// Flache Zeichnung → Binär-DXF-Bytes (R2018); leer bei kaputtem Puffer. + #[wasm_bindgen] + pub fn export_dxf_binary_flat(flat: &[f64], strings: &str) -> Vec { + super::export_dxf_binary(flat, strings).unwrap_or_default() + } + /// Flache Zeichnung → DWG-Bytes (R2018); leer bei kaputtem Puffer. #[wasm_bindgen] pub fn export_dwg_flat(flat: &[f64], strings: &str) -> Vec { @@ -644,4 +698,90 @@ mod tests { let doc = read_dxf(export_dxf(&col, "P").unwrap()); assert!(matches!(doc.entities().next().unwrap().as_entity().common().color, Color::ByLayer)); } + + /// Verlauf-HATCH: linear (45°) und radial, Farben, Name, Rand — DXF, Binär-DXF und DWG. + fn gradient_sample() -> (Vec, String) { + let (e, n) = (E, N); + let flat = vec![ + FLAT_VERSION, + REC_LAYER, 0.0, -1.0, 13.0, + REC_GRADIENT, 0.0, 0xff_ff_ff as f64, 0x00_33_99 as f64, std::f64::consts::FRAC_PI_4, 0.0, + 4.0, e, n, e + 4.0, n, e + 4.0, n + 3.0, e, n + 3.0, + REC_GRADIENT, 0.0, 0xff_00_00 as f64, 0x00_00_ff as f64, 0.0, 1.0, + 3.0, e, n, e + 2.0, n, e + 1.0, n + 1.0, + ]; + (flat, "HATCH".to_string()) + } + + fn check_gradients(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(), 2); + for h in &hs { + assert!(h.gradient_color.enabled); + assert_eq!(h.gradient_color.colors.len(), 2); + assert_eq!(h.common.layer, "HATCH"); + assert_eq!(h.paths.len(), 1); + } + let g = &hs[0].gradient_color; + assert_eq!(g.name, "LINEAR"); + assert!((g.angle - std::f64::consts::FRAC_PI_4).abs() < 1e-9); + assert_eq!(g.colors[0].color.rgb(), Some((0xff, 0xff, 0xff))); + assert_eq!(g.colors[1].color.rgb(), Some((0x00, 0x33, 0x99))); + assert_eq!(hs[1].gradient_color.name, "SPHERICAL"); + assert_eq!(hs[1].gradient_color.colors[0].color.rgb(), Some((0xff, 0, 0))); + } + + #[test] + fn gradient_roundtrip_dxf_binary_und_dwg() { + let (flat, strings) = gradient_sample(); + check_gradients(&read_dxf(export_dxf(&flat, &strings).unwrap())); + let bin = export_dxf_binary(&flat, &strings).unwrap(); + assert!(bin.starts_with(b"AutoCAD Binary DXF")); + check_gradients(&read_dxf(bin)); + check_gradients(&read_dwg(export_dwg(&flat, &strings).unwrap())); + } + + #[test] + fn gradient_dxf_text_hat_gruppencodes_450_bis_470() { + let (flat, strings) = gradient_sample(); + let text = String::from_utf8(export_dxf(&flat, &strings).unwrap()).unwrap(); + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let has = |code: &str, val: &str| lines.windows(2).any(|w| w[0] == code && w[1] == val); + assert!(has("450", "1") && has("470", "LINEAR") && has("470", "SPHERICAL") && has("453", "2")); + } + + #[test] + fn kaputte_gradienten_werden_verworfen() { + 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]; + for pre in [ + [f64::NAN, 0.0, 0.0, 0.0], + [0.0, 1e12, 0.0, 0.0], + [0.0, 0.0, f64::INFINITY, 0.0], + ] { + let mut v = head.to_vec(); + v.push(REC_GRADIENT); + v.push(0.0); + v.extend_from_slice(&pre); + v.extend_from_slice(&sq); + assert_eq!(read_dxf(export_dxf(&v, "P").unwrap()).entities().count(), 0, "{pre:?}"); + } + // Weniger als 3 Randpunkte und abgeschnittener Puffer. + let mut two = head.to_vec(); + two.extend_from_slice(&[REC_GRADIENT, 0.0, 0.0, 0.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); + let mut cut = head.to_vec(); + cut.extend_from_slice(&[REC_GRADIENT, 0.0, 0.0, 0.0, 0.0]); + assert!(export_dxf(&cut, "P").is_err()); + assert!(export_dxf_binary(&cut, "P").is_err()); + } + + #[test] + fn binary_dxf_mit_allen_datensatzarten() { + let (flat, strings) = sample(); + let bin = export_dxf_binary(&flat, &strings).unwrap(); + check(&read_dxf(bin)); + let (flat, strings) = hatch_sample(); + check_hatches(&read_dxf(export_dxf_binary(&flat, &strings).unwrap())); + } } diff --git a/src/cli/main.ts b/src/cli/main.ts index 698b4b25..e0338271 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -8,7 +8,7 @@ // dossier-cli plan [--level EG] [--scale 100] [--out eg.svg] // dossier-cli section [--out schnitt.svg] (braucht render3d-WASM) // dossier-cli elevation [--out ansicht.svg] -// dossier-cli dxf|dwg|ifc|step|obj|stl|schedule|kennzahlen|sun [--level EG] [--out datei] +// dossier-cli dxf [--binary]|dwg|ifc|step|obj|stl|schedule|kennzahlen|sun [--level EG] [--out datei] // dossier-cli import-ifc [--out neu.obp] [--group product|class] // IFC als Kontext-Meshes ([B3]); Bericht als JSON auf stdout // dossier-cli model3d [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png) @@ -23,6 +23,7 @@ import { fileURLToPath } from "node:url"; import { buildPlanDxf, buildPlanDwg, + buildPlanDxfBinary, loadFileio, readIfc, ifcToImportedMeshes, @@ -221,7 +222,8 @@ export async function run(argv: string[]): Promise { const world = projectToWorldCoords(project); const plan = generatePlan(world, lvl.id, allCodes); await loadFileio(); - if (command === "dxf") out(args, buildPlanDxf(plan, world), `${lvl.name}.dxf`); + if (command === "dxf" && args.flags.has("binary")) out(args, buildPlanDxfBinary(plan, world), `${lvl.name}.dxf`); + else if (command === "dxf") out(args, buildPlanDxf(plan, world), `${lvl.name}.dxf`); else out(args, buildPlanDwg(plan, world), `${lvl.name}.dwg`); return 0; } diff --git a/src/core/extra.ts b/src/core/extra.ts index f50ec927..53fdb450 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -5,6 +5,7 @@ export { parseProjectFile, serializeProject, PROJECT_FORMAT_VERSION } from "../i export { exportIfcSpf } from "../export/exportIfc"; export { buildPlanDxf } from "../export/exportDxf"; export { buildPlanDwg } from "../export/exportDxf"; +export { buildPlanDxfBinary } from "../export/exportDxf"; export { loadFileio } from "../engine/fileioWasm"; export { readIfc, ifcToImportedMeshes } from "../io/ifcImport"; export { projectGeoOrigin } from "../model/geoRebase"; diff --git a/src/export/exportDxf.ezdxf.test.ts b/src/export/exportDxf.ezdxf.test.ts index 9ce19cd3..58f9536b 100644 --- a/src/export/exportDxf.ezdxf.test.ts +++ b/src/export/exportDxf.ezdxf.test.ts @@ -9,7 +9,7 @@ import { spawnSync } from "node:child_process"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { buildPlanDxf } from "./exportDxf"; +import { buildPlanDxf, buildPlanDxfBinary } from "./exportDxf"; import { sampleProject } from "../model/sampleProject"; import { generatePlan } from "../plan/generatePlan"; import type { Plan } from "../plan/generatePlan"; @@ -29,6 +29,7 @@ interface EzEntity { paths?: number; pattern_lines?: number; rgb?: number[] | null; + gradient?: { name: string; rotation: number; color1: number[]; color2: number[] } | null; } interface EzResult { version: string; @@ -38,7 +39,7 @@ interface EzResult { entities: EzEntity[]; } -function ezdxfRead(name: string, dxf: string): { status: number | null; result: EzResult | null; err: string } { +function ezdxfRead(name: string, dxf: string | Uint8Array): { status: number | null; result: EzResult | null; err: string } { const dir = mkdtempSync(join(tmpdir(), "dossier-dxf-")); const file = join(dir, `${name}.dxf`); writeFileSync(file, dxf); @@ -122,4 +123,50 @@ describe.skipIf(!hasEzdxf)("DXF-Export gegen ezdxf", { timeout: 60_000 }, () => expect(h.pts).toEqual(sq.map((p) => [p.x, p.y])); } }); + + const gradPlan = (): Plan => { + const sq = [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }, { x: 0, y: 3 }]; + const poly = (gradient: object) => ({ + kind: "polygon", pts: sq, fill: "#eee", stroke: "#111", strokeWidthMm: 0.25, + hatch: { pattern: "crosshatch", scale: 1, angle: 0, color: "#336699", lineWeight: 0.13, dash: null, kind: "gradient", gradient }, + }); + return { + primitives: [ + poly({ color1: "#ffffff", color2: "#003399", angle: 90, type: "linear" }), + poly({ color1: "#f00", color2: "#00f", angle: 0, type: "radial" }), + ], + bounds: { minX: 0, minY: 0, maxX: 4, maxY: 3 }, + } as unknown as Plan; + }; + + it("Verlauf: ezdxf liest echte Gradient-HATCHs (linear, radial) ohne Auditor-Fehler", () => { + const r = ezdxfRead("gradient", buildPlanDxf(gradPlan(), 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(2); + expect(hs[0].gradient).toMatchObject({ name: "LINEAR", color1: [255, 255, 255], color2: [0, 0x33, 0x99] }); + expect(hs[0].gradient!.rotation).toBeCloseTo(90, 6); + expect(hs[1].gradient).toMatchObject({ name: "SPHERICAL", color1: [255, 0, 0], color2: [0, 0, 255] }); + }); + + it("Binär-DXF: ezdxf liest dieselbe Zeichnung wie die ASCII-Fassung ohne Auditor-Fehler", () => { + const plan = generatePlan(sampleProject, "eg", new Set(flattenCategories(sampleProject.layers).map((l) => l.code))); + const asc = ezdxfRead("bin-asc", buildPlanDxf(plan, sampleProject)); + const bin = ezdxfRead("bin-bin", buildPlanDxfBinary(plan, sampleProject)); + expect(bin.result, bin.err).not.toBeNull(); + expect(bin.result!.errors).toEqual([]); + expect(bin.status).toBe(0); + expect(bin.result!.entities).toEqual(asc.result!.entities); + expect(Object.keys(bin.result!.layers)).toEqual(Object.keys(asc.result!.layers)); + // und kleiner als der Text + expect(buildPlanDxfBinary(plan, sampleProject).length).toBeLessThan(buildPlanDxf(plan, sampleProject).length); + }); + + it("Binär-DXF mit Verlauf: Gradient bleibt erhalten", () => { + const r = ezdxfRead("bin-grad", buildPlanDxfBinary(gradPlan(), sampleProject)); + expect(r.result!.errors).toEqual([]); + expect(r.result!.entities.filter((e) => e.type === "HATCH").map((h) => h.gradient?.name)).toEqual(["LINEAR", "SPHERICAL"]); + }); }); diff --git a/src/export/exportDxf.gradient.test.ts b/src/export/exportDxf.gradient.test.ts index 817cb166..ab38cbf7 100644 --- a/src/export/exportDxf.gradient.test.ts +++ b/src/export/exportDxf.gradient.test.ts @@ -1,15 +1,14 @@ /** * DXF-Export von Verlauf-Schraffuren (`HatchStyle.kind === "gradient"`). - * DXF trägt keine echten Farbverläufe (wie bereits bei Bild-Schraffuren - * akzeptiert) — der Export muss auf die reine Umriss-Polylinie zurückfallen - * und darf KEINE (aus dem stehengebliebenen `pattern`-Feld abgeleiteten) - * Musterlinien mehr ausgeben. + * Verläufe gehen als echte Gradient-HATCH ins DXF ([C2], 28.10.: Gruppencodes 450–470); + * es dürfen KEINE (aus dem stehengebliebenen `pattern`-Feld abgeleiteten) Musterlinien + * mehr ausgegeben werden. Ohne lesbare Farben bleibt es beim Umriss. */ import { describe, expect, it } from "vitest"; import "../engine/fileioWasm.setup"; import { buildPlanDxf } from "./exportDxf"; -import { nums, readDxf } from "./cadReadBack.testutil"; +import { num, nums, readDxf, str } from "./cadReadBack.testutil"; import { sampleProject } from "../model/sampleProject"; import type { Plan } from "../plan/generatePlan"; import type { HatchRender } from "../plan/generatePlan/shared"; @@ -58,7 +57,7 @@ describe("buildPlanDxf — Verlauf-Schraffur", () => { expect(nums(h, 53).map((a) => Math.round(a))).toEqual([0, 90]); }); - it("gradient: KEINE Musterlinien, nur die Umriss-Polylinie", () => { + it("gradient: eine Gradient-HATCH (LINEAR, zwei Farben, Winkel) plus Umriss, keine Musterlinien", () => { const dxf = buildPlanDxf( planWith([ polyWith({ @@ -69,7 +68,42 @@ describe("buildPlanDxf — Verlauf-Schraffur", () => { sampleProject, ); expect(countEntities(dxf, "LINE")).toBe(0); - expect(countEntities(dxf, "HATCH")).toBe(0); + expect(countEntities(dxf, "HATCH")).toBe(1); expect(countEntities(dxf, "LWPOLYLINE")).toBe(1); // Umriss bleibt erhalten + const h = readDxf(dxf).entities.find((e) => e.type === "HATCH")!; + expect(str(h, 470)).toBe("LINEAR"); + expect(num(h, 460)).toBeCloseTo(Math.PI / 4, 9); + expect(nums(h, 463)).toEqual([0, 1]); + expect(nums(h, 421)).toEqual([0xffffff, 0x000000]); + }); + + it("gradient radial: SPHERICAL; 3-stellige Farben werden erweitert", () => { + const dxf = buildPlanDxf( + planWith([polyWith({ kind: "gradient", gradient: { color1: "#f00", color2: "#00f", angle: 0, type: "radial" } })]), + sampleProject, + ); + const h = readDxf(dxf).entities.find((e) => e.type === "HATCH")!; + expect(str(h, 470)).toBe("SPHERICAL"); + expect(nums(h, 421)).toEqual([0xff0000, 0x0000ff]); + }); + + it("gradient ohne lesbare Farbe oder ohne Parameter: nur der Umriss", () => { + for (const hatch of [ + polyWith({ kind: "gradient", gradient: { color1: "none", color2: "#000000", angle: 0, type: "linear" } }), + polyWith({ kind: "gradient" }), + ]) { + const dxf = buildPlanDxf(planWith([hatch]), sampleProject); + expect(countEntities(dxf, "HATCH")).toBe(0); + expect(countEntities(dxf, "LWPOLYLINE")).toBe(1); + } + }); + + it("gradient ohne Schraffuren-Option: nur der Umriss", () => { + const dxf = buildPlanDxf( + planWith([polyWith({ kind: "gradient", gradient: { color1: "#fff", color2: "#000", angle: 0, type: "linear" } })]), + sampleProject, + { includeHatches: false }, + ); + expect(countEntities(dxf, "HATCH")).toBe(0); }); }); diff --git a/src/export/exportDxf.ts b/src/export/exportDxf.ts index 676f2c3c..9f8516e8 100644 --- a/src/export/exportDxf.ts +++ b/src/export/exportDxf.ts @@ -32,7 +32,12 @@ export interface ExportDxfOptions { } /** Ausgabeformat des Modell-Space-Exports. */ -export type CadExportFormat = "dxf" | "dwg"; +export type CadExportFormat = "dxf" | "dxfbin" | "dwg"; + +/** Dateiendung zum Ausgabeformat (Binär-DXF trägt ebenfalls `.dxf`). */ +export function cadExtension(format: CadExportFormat): "dxf" | "dwg" { + return format === "dwg" ? "dwg" : "dxf"; +} /** Sammel-Layer-Namen für Primitive ohne eigene Kategorie. */ const LAYER_HATCH = "HATCH"; @@ -54,6 +59,7 @@ const REC_ARC = 4; const REC_CIRCLE = 5; const REC_TEXT = 6; const REC_HATCH = 7; +const REC_GRADIENT = 8; /** * Sammelt Ebenen und Entitäten als flachen Zahlenpuffer + Zeichenkettenliste. Ebenen sind @@ -128,6 +134,17 @@ export class FlatDrawing { for (const p of pts) this.nums.push(p.x, p.y); } + /** + * Zweifarben-Verlauf als echte Gradient-HATCH-Entität (Rand `pts`, geschlossen). `rgb1`/`rgb2` = + * 0xRRGGBB; `angle` (Radiant) = Richtung von `rgb1` nach `rgb2` (nur linear); `radial`: `rgb1` in der + * Mitte, `rgb2` am Rand. + */ + addGradient(layer: string, pts: Vec2[], g: { rgb1: number; rgb2: number; angle: number; radial: boolean }): void { + if (pts.length < 3) return; + this.nums.push(REC_GRADIENT, this.layer(layer), g.rgb1, g.rgb2, g.angle, g.radial ? 1 : 0, 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")]; @@ -213,6 +230,15 @@ export function buildPlanDxf( return new TextDecoder().decode(writeCad("dxf", collectPlanDrawing(plan, project, opts))); } +/** Wie {@link buildPlanDxf}, aber als Binär-DXF (R2018, Bytes; deutlich kleiner und schneller zu lesen). */ +export function buildPlanDxfBinary( + plan: Plan, + project: Project, + opts: ExportDxfOptions = {}, +): Uint8Array { + return writeCad("dxfbin", collectPlanDrawing(plan, project, opts)); +} + /** Wie {@link buildPlanDxf}, aber als DWG (R2018, Bytes). */ export function buildPlanDwg( plan: Plan, @@ -226,10 +252,15 @@ export function buildPlanDwg( function writeCad(format: CadExportFormat, drawing: FlatDrawing): Uint8Array { const m = fileio(); const [flat, strings] = drawing.args(); - const bytes = format === "dxf" ? m.export_dxf_flat(flat, strings) : m.export_dwg_flat(flat, strings); + const bytes = + format === "dxf" + ? m.export_dxf_flat(flat, strings) + : format === "dxfbin" + ? m.export_dxf_binary_flat(flat, strings) + : m.export_dwg_flat(flat, strings); if (bytes.length === 0) { const why = m.export_check_flat(flat, strings); - throw new Error(`${format.toUpperCase()}-Export fehlgeschlagen${why ? `: ${why}` : ""}`); + throw new Error(`${cadExtension(format).toUpperCase()}-Export fehlgeschlagen${why ? `: ${why}` : ""}`); } return bytes; } @@ -289,11 +320,20 @@ function emitPrimitive( if (pts.length < 2) break; // 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 + // Polygon als Rand und der aufgelösten Vordergrundfarbe. Verlauf-Schraffur (kind==="gradient") + // als echte Gradient-HATCH (zwei Farben, linear/radial); ohne lesbare Farben oder Bild- + // Schraffur (kind==="image") trägt DXF das 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) { + if (includeHatches && p.hatch.kind === "gradient" && pts.length >= 3) { + const g = p.hatch.gradient; + const rgb1 = g ? rgbOrNull(g.color1) : null; + const rgb2 = g ? rgbOrNull(g.color2) : null; + if (g && rgb1 !== null && rgb2 !== null && Number.isFinite(g.angle)) { + // Richtung wie der SVG-Verlauf der Ansicht: Vektor (cos, sin) in Plan-Koordinaten = DXF-Winkel. + dxf.addGradient(LAYER_HATCH, pts, { rgb1, rgb2, angle: (g.angle * Math.PI) / 180, radial: g.type === "radial" }); + } + } else if (includeHatches && p.hatch.kind !== "image" && pts.length >= 3) { const h = p.hatch; if (h.pattern === "solid") { dxf.addHatch(LAYER_HATCH, pts, { solid: true, rgb: rgbOrNull(h.color) }); @@ -430,8 +470,10 @@ export function rgbFromHex(hex: string): number { /** "#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; + const m = /^#?([0-9a-f]{6}|[0-9a-f]{3})$/i.exec(hex.trim()); + if (!m) return null; + const h = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1]; + return parseInt(h, 16); } /** Millimeter → DXF-LWEIGHT (1/100 mm), gerundet auf gültige Stufen ≥ 0. */ @@ -448,12 +490,13 @@ export async function savePlanDxf( await loadFileio(); const format = opts.format ?? "dxf"; const data = writeCad(format, collectPlanDrawing(plan, project, opts)); + const ext = cadExtension(format); const name = (opts.fileName ?? "grundriss").replace(/\.(dxf|dwg)$/i, ""); - const blob = new Blob([data as BlobPart], { type: format === "dxf" ? "application/dxf" : "image/vnd.dwg" }); + const blob = new Blob([data as BlobPart], { type: ext === "dxf" ? "application/dxf" : "image/vnd.dwg" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; - a.download = `${name}.${format}`; + a.download = `${name}.${ext}`; document.body.appendChild(a); a.click(); document.body.removeChild(a); diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 95548559..571d366e 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1703,6 +1703,7 @@ export const de = { "exportDxf.hatches.no": "Nur Umrisse", "exportDxf.format": "Format", "exportDxf.format.dxf": "DXF (AutoCAD 2018, Text)", + "exportDxf.format.dxfbin": "DXF binär (AutoCAD 2018, kompakt)", "exportDxf.format.dwg": "DWG (AutoCAD 2018)", "exportDxf.failed": "Export fehlgeschlagen", "exportDxf.unitsNote": diff --git a/src/i18n/en.ts b/src/i18n/en.ts index e4b7c3d6..b3f0a862 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1691,6 +1691,7 @@ export const en: Record = { "exportDxf.hatches.no": "Outlines only", "exportDxf.format": "Format", "exportDxf.format.dxf": "DXF (AutoCAD 2018, text)", + "exportDxf.format.dxfbin": "DXF binary (AutoCAD 2018, compact)", "exportDxf.format.dwg": "DWG (AutoCAD 2018)", "exportDxf.failed": "Export failed", "exportDxf.unitsNote": diff --git a/src/ui/ExportDxfDialog.tsx b/src/ui/ExportDxfDialog.tsx index 4f43af65..3d7e5739 100644 --- a/src/ui/ExportDxfDialog.tsx +++ b/src/ui/ExportDxfDialog.tsx @@ -13,7 +13,7 @@ import type { CadExportFormat } from "../export/exportDxf"; /** Entscheidung, die der Dialog beim Bestätigen liefert. */ export interface ExportDxfDecision { - /** Dateiformat: DXF (R2018 ASCII) oder DWG (R2018). */ + /** Dateiformat: DXF (R2018 ASCII), Binär-DXF (R2018) oder DWG (R2018). */ format: CadExportFormat; includeHatches: boolean; /** „nur Auswahl" statt des ganzen Plans (nur relevant, wenn `selectionCount > 0`). */ @@ -78,10 +78,11 @@ export function ExportDxfDialog({
{t("exportDxf.format")}
setFormat(v === "dwg" ? "dwg" : "dxf")} + onChange={(v) => setFormat(v === "dwg" ? "dwg" : v === "dxfbin" ? "dxfbin" : "dxf")} title={t("exportDxf.format")} options={[ { value: "dxf", label: t("exportDxf.format.dxf") }, + { value: "dxfbin", label: t("exportDxf.format.dxfbin") }, { value: "dwg", label: t("exportDxf.format.dwg") }, ]} />