diff --git a/scripts/validate-dxf.py b/scripts/validate-dxf.py index 07cd5054..aeea0d22 100644 --- a/scripts/validate-dxf.py +++ b/scripts/validate-dxf.py @@ -60,12 +60,77 @@ def main(path: str) -> int: item["text"] = e.dxf.text item["at"] = [e.dxf.insert.x, e.dxf.insert.y] item["height"] = e.dxf.height + item["style"] = e.dxf.style + item["halign"] = e.dxf.halign + item["valign"] = e.dxf.valign + item["rotation"] = e.dxf.rotation + if e.dxf.hasattr("align_point"): + item["align_point"] = [e.dxf.align_point.x, e.dxf.align_point.y] + elif t == "INSERT": + item["name"] = e.dxf.name + item["at"] = [e.dxf.insert.x, e.dxf.insert.y] + item["rotation"] = e.dxf.rotation + item["scale"] = [e.dxf.xscale, e.dxf.yscale] + item["attribs"] = {a.dxf.tag: a.dxf.text for a in e.attribs} + elif t == "DIMENSION": + item["dimtype"] = e.dimtype + item["block"] = e.dxf.geometry + item["dimstyle"] = e.dxf.dimstyle + item["defpoint"] = [e.dxf.defpoint.x, e.dxf.defpoint.y] + item["p1"] = [e.dxf.defpoint2.x, e.dxf.defpoint2.y] + item["p2"] = [e.dxf.defpoint3.x, e.dxf.defpoint3.y] + item["measurement"] = e.dxf.actual_measurement + if e.dxf.hasattr("linetype"): + item["linetype"] = e.dxf.linetype entities.append(item) layers = { l.dxf.name: {"lineweight": l.dxf.lineweight, "rgb": l.rgb and list(l.rgb)} for l in doc.layers } + blocks = {} + for b in doc.blocks: + n = {} + for be in b: + n[be.dxftype()] = n.get(be.dxftype(), 0) + 1 + blocks[b.name] = {"entities": n, "anonymous": b.name.startswith("*D")} + styles = {st.dxf.name: (st.dxf.font if st.dxf.hasattr("font") else None) for st in doc.styles} + ttf = {} + for st in doc.styles: + try: + ttf[st.dxf.name] = st.get_extended_font_data()[0] + except Exception: + pass + linetypes = {lt.dxf.name: list(lt.pattern_tags.tags and [t.value for t in lt.pattern_tags.tags if t.code == 49]) for lt in doc.linetypes} + dimstyles = { + d.dxf.name: {k: d.dxf.get(k) for k in ("dimscale", "dimtxt", "dimtsz", "dimexo", "dimexe", "dimgap", "dimtad", "dimdec", "dimlfac", "dimtxsty")} + for d in doc.dimstyles + } + layouts = {} + for lay in doc.layouts: + if lay.name == "Model": + continue + vps = [ + { + "id": v.dxf.id, + "center": [v.dxf.center.x, v.dxf.center.y], + "size": [v.dxf.width, v.dxf.height], + "view_center": [v.dxf.view_center_point.x, v.dxf.view_center_point.y], + "view_height": v.dxf.view_height, + } + for v in lay.viewports() + ] + dl = lay.dxf_layout.dxf + layouts[lay.name] = { + "viewports": vps, + "paper": [dl.paper_width, dl.paper_height] if dl.hasattr("paper_width") else None, + } out = { "version": doc.dxfversion, + "blocks": blocks, + "styles": styles, + "fonts": ttf, + "linetypes": linetypes, + "dimstyles": dimstyles, + "layouts": layouts, "insunits": doc.header.get("$INSUNITS"), "errors": [str(err.message) for err in auditor.errors], "layers": layers, diff --git a/src-tauri/fileio/src/export.rs b/src-tauri/fileio/src/export.rs index aeede03d..f179a2fc 100644 --- a/src-tauri/fileio/src/export.rs +++ b/src-tauri/fileio/src/export.rs @@ -451,6 +451,7 @@ pub fn build_document(flat: &[f64], strings: &str) -> Result 0.0 { st.width_factor = width; @@ -485,7 +486,11 @@ pub fn build_document(flat: &[f64], strings: &str) -> Result { + it("erste echte Familie, ohne Anführungszeichen; generische/Variablen übersprungen", () => { + expect(fontNameOf('"Helvetica Neue", Arial, sans-serif')).toBe("Helvetica Neue"); + expect(fontNameOf("var(--font-ui, sans-serif)")).toBeNull(); + expect(fontNameOf("sans-serif, Arial")).toBe("Arial"); + expect(fontNameOf("'Source Sans 3'")).toBe("Source Sans 3"); + expect(fontNameOf(undefined)).toBeNull(); + expect(fontNameOf("")).toBeNull(); + }); +}); + +describe("Linientypen", () => { + it("Papier-mm × Massstab → Meter (Strich +, Lücke −); ungerade Muster werden verdoppelt", () => { + expect(dashToLtypeMeters([3, 1], 100)!.map((v) => Math.round(v * 1e6) / 1e6)).toEqual([0.3, -0.1]); + expect(dashToLtypeMeters([2, 1, 0.5], 50)!.map((v) => Math.round(v * 1e6) / 1e6)).toEqual([0.1, -0.05, 0.025, -0.1, 0.05, -0.025]); + expect(dashToLtypeMeters([], 100)).toBeNull(); + expect(dashToLtypeMeters([0, 0], 100)).toBeNull(); + // Punkt (Strich 0) bleibt 0, Lücke nie 0 + const dot = dashToLtypeMeters([0, 0], 100); + expect(dot).toBeNull(); + expect(dashToLtypeMeters([0, 1], 100)![0]).toBe(0); + }); + + it("Name: Projekt-Linienstil mit gleichem Muster, sonst DOSSIER_STRICH_…", () => { + const styles = [{ id: "a", name: " Strichlinie ", weight: 0.1, color: "#000", dash: [3, 1] }] as LineStyle[]; + expect(ltypeNameFor([3, 1], styles)).toBe("Strichlinie"); + expect(ltypeNameFor([2, 0.5], styles)).toBe("DOSSIER_STRICH_2_0.5"); + }); +}); + +describe("Papierbereich", () => { + it("kleinstes Format, das den Ausschnitt samt Rand aufnimmt", () => { + // 20 m × 12 m bei 1:100 = 200 × 120 mm + 20 mm Rand → A4 quer + expect(paperFor(20, 12, 100)).toMatchObject({ name: "A4", paperW: 297, paperH: 210, vpW: 277, vpH: 190 }); + // 30 m × 18 m bei 1:100 → 300 × 180 (+20): A3 + expect(paperFor(30, 18, 100).name).toBe("A3"); + // Hochformat, wenn nur so passend + expect(paperFor(12, 20, 100)).toMatchObject({ name: "A4", paperW: 210, paperH: 297 }); + // grösser als A0: Sonderformat in 10-mm-Schritten + const big = paperFor(200, 100, 50); + expect(big.name).toBe("Sonder"); + expect(big.paperW % 10).toBe(0); + }); +}); + +describe("primitiveToLocal", () => { + const frame = { origin: { x: 10, y: 5 }, rot: Math.PI / 2, scale: 2 }; + it("Linie, Bogen, Kreis, Text: verschoben, gedreht, skaliert", () => { + const line = { kind: "line", a: { x: 10, y: 5 }, b: { x: 10, y: 9 }, cls: "x", weightMm: 0.1 } as Primitive; + const l = primitiveToLocal(line, frame) as Extract; + expect(l.a.x).toBeCloseTo(0, 12); + expect(l.a.y).toBeCloseTo(0, 12); + expect(l.b.x).toBeCloseTo(2, 12); // 4 m in Richtung +y = lokale +x, durch Skalierung 2 + expect(l.b.y).toBeCloseTo(0, 12); + const text = { kind: "drawingText", at: { x: 10, y: 5 }, text: "a", heightM: 0.4, angle: Math.PI / 2, color: "#000" } as Primitive; + const t = primitiveToLocal(text, frame) as Extract; + expect(t.heightM).toBeCloseTo(0.2, 12); + expect(t.angle).toBeCloseTo(0, 12); + const circle = { kind: "drawingCircle", center: { x: 10, y: 7 }, r: 1, fill: "none", stroke: "#000", weightMm: 0.1 } as Primitive; + const c = primitiveToLocal(circle, frame) as Extract; + expect(c.r).toBeCloseTo(0.5, 12); + expect(c.center.x).toBeCloseTo(1, 12); + }); + it("andere Primitivarten (Raumstempel, Bild) gehören nicht in Blöcke", () => { + expect(primitiveToLocal({ kind: "drawingImage" } as Primitive, frame)).toBeNull(); + }); + it("roundKey: auf 1 mm gerundet", () => { + expect(roundKey([1.0001, 2])).toBe(roundKey([1.0004, 2])); + expect(roundKey([1.0001, 2])).not.toBe(roundKey([1.002, 2])); + }); +}); diff --git a/src/export/dxfCadParts.ts b/src/export/dxfCadParts.ts new file mode 100644 index 00000000..94c24a2e --- /dev/null +++ b/src/export/dxfCadParts.ts @@ -0,0 +1,129 @@ +// Bausteine des Fachplaner-Exports ([C2], 28.10.): reine Hilfsfunktionen für `exportDxf.ts` — +// Schriftname aus CSS-Familie, Linientyp-Namen aus Strichmustern, Umrechnung von Plan-Primitiven in ein +// lokales Koordinatensystem (für Blöcke) und Papierformate. Keine Abhängigkeit vom Writer. + +import type { Primitive } from "../plan/generatePlan"; +import type { LineStyle, Vec2 } from "../model/types"; + +/** Erste Schriftfamilie aus einem CSS-`font-family`-Wert ohne Anführungszeichen; generische Familien/CSS-Variablen → null. */ +export function fontNameOf(css: string | undefined | null): string | null { + if (!css) return null; + // `var(--font-ui, sans-serif)` enthält selbst ein Komma: vor dem Teilen entfernen. + for (const raw of css.replace(/var\([^)]*\)/g, "").split(",")) { + const name = raw.trim().replace(/^["']|["']$/g, "").trim(); + if (!name) continue; + if (/^(sans-serif|serif|monospace|cursive|fantasy|system-ui|ui-sans-serif|inherit|initial)$/i.test(name)) continue; + return name; + } + return null; +} + +/** Strichmuster (Papier-mm, an/aus/…) → DXF-Linientyp-Elemente in Modell-Metern (Strich +, Lücke −, Punkt 0). */ +export function dashToLtypeMeters(dashMm: number[], scaleDenominator: number): number[] | null { + let pat = dashMm.map((d) => (Number.isFinite(d) ? Math.max(0, d) : 0)); + if (pat.length === 0 || pat.every((d) => d === 0)) return null; + if (pat.length % 2 === 1) pat = pat.concat(pat); + const k = scaleDenominator / 1000; + const out: number[] = []; + for (let i = 0; i < pat.length; i++) { + const len = pat[i] * k; + out.push(i % 2 === 0 ? len : -Math.max(len, 1e-6)); + } + // Eine Lücke von 0 ergäbe ein Muster ohne Unterbrechung; mindestens 1 µm. + return out; +} + +/** Zahl für Namen: höchstens 2 Nachkommastellen, ohne Nullen am Ende. */ +function n2(v: number): string { + return String(Math.round(v * 100) / 100); +} + +/** + * Name des Linientyps zu einem Strichmuster: der Name des Projekt-Linienstils mit demselben Muster, sonst + * `DOSSIER_STRICH__…` (Papier-mm). + */ +export function ltypeNameFor(dashMm: number[], styles: readonly LineStyle[]): string { + const same = (a: number[], b: number[]) => a.length === b.length && a.every((v, i) => Math.abs(v - b[i]) < 1e-9); + const hit = styles.find((s) => s.dash && s.dash.length > 0 && (s.kind ?? "dash") === "dash" && same(s.dash, dashMm)); + if (hit && hit.name.trim()) return hit.name.trim(); + return `DOSSIER_STRICH_${dashMm.map(n2).join("_")}`; +} + +// ── Lokales Koordinatensystem (Blöcke) ──────────────────────────────────────── + +/** Abbildung Modell → blocklokal: Verschiebung `-origin`, Drehung `-rot`, Skalierung `1/scale`. */ +export interface LocalFrame { + origin: Vec2; + /** Drehung des Blocks im Modell (Radiant). */ + rot: number; + scale: number; +} + +function toLocal(f: LocalFrame, p: Vec2): Vec2 { + const c = Math.cos(f.rot); + const s = Math.sin(f.rot); + const dx = p.x - f.origin.x; + const dy = p.y - f.origin.y; + return { x: (dx * c + dy * s) / f.scale, y: (-dx * s + dy * c) / f.scale }; +} + +/** Primitive im lokalen System des Blocks (nur Geometrie-Arten, die in Blöcken vorkommen); andere → null. */ +export function primitiveToLocal(p: Primitive, f: LocalFrame): Primitive | null { + const rotDeg = (f.rot * 180) / Math.PI; + switch (p.kind) { + case "line": + return { ...p, a: toLocal(f, p.a), b: toLocal(f, p.b), motif: undefined, zigzag: p.zigzag && { amplitude: p.zigzag.amplitude / f.scale, wavelength: p.zigzag.wavelength / f.scale } }; + case "arc": + return { ...p, center: toLocal(f, p.center), from: toLocal(f, p.from), to: toLocal(f, p.to), r: p.r / f.scale }; + case "polygon": + return { ...p, pts: p.pts.map((q) => toLocal(f, q)), hatch: { ...p.hatch, angle: p.hatch.angle - rotDeg } }; + case "drawingCircle": + return { ...p, center: toLocal(f, p.center), r: p.r / f.scale }; + case "drawingArc": + return { ...p, center: toLocal(f, p.center), r: p.r / f.scale, a0: p.a0 - f.rot, a1: p.a1 - f.rot }; + case "drawingText": + return { ...p, at: toLocal(f, p.at), heightM: p.heightM / f.scale, angle: p.angle - f.rot, wrapWidth: p.wrapWidth && p.wrapWidth / f.scale }; + default: + return null; + } +} + +/** Schlüssel gleicher lokaler Geometrie: Zahlen auf 1 mm gerundet (Blöcke teilen sich nur identische Inhalte). */ +export function roundKey(nums: readonly number[]): string { + let out = ""; + for (const v of nums) out += `${Math.round(v * 1000)},`; + return out; +} + +// ── Papierbereich ──────────────────────────────────────────────────────────── + +/** Papierformate (mm, quer) in aufsteigender Grösse. */ +const PAPER_SIZES: [string, number, number][] = [ + ["A4", 297, 210], + ["A3", 420, 297], + ["A2", 594, 420], + ["A1", 841, 594], + ["A0", 1189, 841], +]; + +/** + * Papier und Ansichtsfenster für einen Ausschnitt der Grösse `w` × `h` Meter im Massstab 1:`scale`: + * kleinstes A-Format (quer, sonst hoch), das den Ausschnitt mit `margin` mm Rand aufnimmt; ist keines + * gross genug, ein Sonderformat in Vielfachen von 10 mm. Das Fenster füllt das Papier abzüglich Rand. + */ +export function paperFor( + w: number, + h: number, + scale: number, + margin = 10, +): { paperW: number; paperH: number; vpW: number; vpH: number; name: string } { + const needW = (w * 1000) / scale + 2 * margin; + const needH = (h * 1000) / scale + 2 * margin; + for (const [name, pw, ph] of PAPER_SIZES) { + if (needW <= pw && needH <= ph) return { paperW: pw, paperH: ph, vpW: pw - 2 * margin, vpH: ph - 2 * margin, name }; + if (needW <= ph && needH <= pw) return { paperW: ph, paperH: pw, vpW: ph - 2 * margin, vpH: pw - 2 * margin, name }; + } + const pw = Math.ceil(needW / 10) * 10; + const ph = Math.ceil(needH / 10) * 10; + return { paperW: pw, paperH: ph, vpW: pw - 2 * margin, vpH: ph - 2 * margin, name: "Sonder" }; +} diff --git a/src/export/exportDxf.cad.test.ts b/src/export/exportDxf.cad.test.ts new file mode 100644 index 00000000..aa48c60b --- /dev/null +++ b/src/export/exportDxf.cad.test.ts @@ -0,0 +1,251 @@ +// Fachplaner-Export ([C2], 28.10.): DIMENSION mit Anonymblock und DIMSTYLE, BLOCK/INSERT/ATTRIB für Türen, +// Fenster und Möbelblöcke, Linientypen, Textstile, Papierbereich — gegengelesen mit ezdxf (Auditor, wie +// ein CAD-Programm die Datei sieht), libredwg (DWG) und dem eigenen DXF-Import. ezdxf-Teile werden ohne +// `pip install ezdxf` übersprungen (Muster `exportDxf.ezdxf.test.ts`). + +import "../engine/fileioWasm.setup"; +import { describe, expect, it } from "vitest"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { buildPlanDwg, buildPlanDxf, buildPlanDxfBinary, collectPlanDrawing } from "./exportDxf"; +import { countByType, libreDwgReader, readDxf } from "./cadReadBack.testutil"; +import { parseDxf } from "../io/dxfParser"; +import { sampleProject } from "../model/sampleProject"; +import { generatePlan } from "../plan/generatePlan"; +import { flattenCategories } from "../model/types"; +import type { Drawing2D, Project } from "../model/types"; + +const hasEzdxf = spawnSync("python3", ["-c", "import ezdxf"]).status === 0; +const allCodes = (p: Project) => new Set(flattenCategories(p.layers).map((l) => l.code)); + +/** Demo-Haus plus Bemassungskette, gestrichelte Linie, Möbelblock (2 Instanzen), Text mit Schrift. */ +function cadProject(): Project { + const code = "90"; + const d = (id: string, geom: Drawing2D["geom"], extra: Partial = {}): Drawing2D => + ({ id, type: "drawing2d", levelId: "eg", categoryCode: code, geom, ...extra }) as Drawing2D; + return { + ...sampleProject, + lineStyles: [...sampleProject.lineStyles, { id: "ls-dash", name: "Strichlinie 0.3/0.1", weight: 0.13, color: "#000000", dash: [3, 1] }], + textStyles: [{ id: "body", label: "Text", marks: { font: '"Helvetica Neue", Arial, sans-serif' } }], + blockDefs: [ + { + id: "bd-sofa", + name: "Sofa", + geom2d: [ + { shape: "rect", min: { x: -0.9, y: -0.4 }, max: { x: 0.9, y: 0.4 } }, + { shape: "line", a: { x: -0.9, y: 0.2 }, b: { x: 0.9, y: 0.2 } }, + ], + }, + ], + drawings2d: [ + d("dim1", { shape: "dimension", pts: [{ x: 0, y: -1 }, { x: 2, y: -1 }, { x: 5, y: -1 }], offset: -0.8 }), + d("dash1", { shape: "line", a: { x: 0, y: -2 }, b: { x: 4, y: -2 } }, { lineStyleId: "ls-dash" }), + d("sofa1", { shape: "block", blockDefId: "bd-sofa", at: { x: 1.5, y: 1 }, rotation: 0 }), + d("sofa2", { shape: "block", blockDefId: "bd-sofa", at: { x: 3.5, y: 2.5 }, rotation: Math.PI / 2, scale: 1.5 }), + d("txt1", { shape: "text", at: { x: 1, y: 4 }, text: "Müller & Söhne", height: 0.2, angle: 0 }), + ], + }; +} + +interface Ez { + version: string; + errors: string[]; + entities: Array & { type: string; layer: string }>; + blocks: Record; anonymous: boolean }>; + styles: Record; + fonts: Record; + linetypes: Record; + dimstyles: Record>; + layouts: Record; paper: number[] | null }>; +} + +function ezdxf(name: string, data: string | Uint8Array): { status: number | null; r: Ez; err: string } { + const dir = mkdtempSync(join(tmpdir(), "dossier-cad-")); + const file = join(dir, `${name}.dxf`); + writeFileSync(file, data); + const p = spawnSync("python3", ["scripts/validate-dxf.py", file], { encoding: "utf8", timeout: 60_000 }); + let r = null as unknown as Ez; + try { + r = JSON.parse(p.stdout) as Ez; + } catch { + /* Fehlertext unten */ + } + return { status: p.status, r, err: `${p.stdout}\n${p.stderr}` }; +} + +describe("Fachplaner-Export: Sammler", () => { + const project = cadProject(); + const plan = generatePlan(project, "eg", allCodes(project)); + + it("Bemassung, Blöcke und Öffnungen werden zu CAD-Objekten statt zu losen Linien", () => { + const { model, blocks } = collectPlanDrawing(plan, project).stats(); + expect(model.DIMENSION).toBe(2); // zwei Segmente der Kette + expect(model.INSERT).toBe(3 + 2); // Tür + 2 Fenster des Demo-Hauses, 2 Sofas + expect(blocks.LINE).toBeGreaterThan(0); + // Bemassung: ihre Linien/Texte stehen nicht zusätzlich lose im Modellbereich. + const dimPrims = plan.primitives.filter((p) => "drawingId" in p && p.drawingId === "dim1").length; + expect(dimPrims).toBeGreaterThan(0); + const loose = collectPlanDrawing({ ...plan, primitives: plan.primitives.filter((p) => !("drawingId" in p && p.drawingId === "dim1")) }, project).stats(); + expect(loose.model.LINE).toBe(model.LINE); + expect(loose.model.TEXT).toBe(model.TEXT); + }); + + it("Massstab und Einheit wirken auf Stil und Masszahl", () => { + const [flat] = collectPlanDrawing(plan, project, { scaleDenominator: 50, dimUnit: "cm" }).args(); + expect(flat.length).toBeGreaterThan(0); + const dxf = readDxf(buildPlanDxf(plan, project, { scaleDenominator: 50, dimUnit: "cm" })); + expect(dxf.entities.filter((e) => e.type === "DIMENSION").length).toBe(2); + }); +}); + +describe.skipIf(!hasEzdxf)("Fachplaner-Export gegen ezdxf", { timeout: 60_000 }, () => { + const project = cadProject(); + const plan = generatePlan(project, "eg", allCodes(project)); + const read = (opts = {}) => { + const x = ezdxf("cad", buildPlanDxf(plan, project, opts)); + expect(x.r, x.err).not.toBeNull(); + expect(x.r.errors).toEqual([]); + expect(x.status).toBe(0); + return x.r; + }; + + it("DIMENSION: ausgerichtet, mit *D-Block (Hilfslinien, Masslinie, 2 Striche, Zahl) und Stil 1:100", () => { + const r = read(); + const dims = r.entities.filter((e) => e.type === "DIMENSION"); + expect(dims.map((d) => d.measurement as number)).toEqual([expect.closeTo(2, 9), expect.closeTo(3, 9)]); + for (const d of dims) { + expect((d.dimtype as number) & 7).toBe(1); // ausgerichtet + expect(d.dimstyle).toBe("DOSSIER_1-100"); + const block = r.blocks[d.block as string]; + expect(block?.anonymous, String(d.block)).toBe(true); + expect(block.entities).toEqual({ LINE: 5, TEXT: 1 }); + } + const st = r.dimstyles["DOSSIER_1-100"]; + expect(st).toMatchObject({ dimscale: 100, dimtad: 1, dimdec: 2, dimlfac: 1, dimtxsty: "DOSSIER" }); + expect(st.dimtxt as number).toBeCloseTo(0.004, 9); // 4 mm Papier + expect(st.dimtsz as number).toBeCloseTo(0.0015, 9); // Architekturstrich 3 mm + }); + + it("Bemassungsstil im Massstab 1:50 und in cm", () => { + const r = read({ scaleDenominator: 50, dimUnit: "cm" }); + const st = r.dimstyles["DOSSIER_1-50_cm"]; + expect(st).toMatchObject({ dimscale: 50, dimdec: 0, dimlfac: 100 }); + const block = r.blocks[r.entities.find((e) => e.type === "DIMENSION")!.block as string]; + expect(block.entities.TEXT).toBe(1); + }); + + it("Türen/Fenster: INSERT in Wandrichtung mit Attributen, Block mit Geometrie", () => { + const r = read(); + const ins = r.entities.filter((e) => e.type === "INSERT" && !(e.name as string).startsWith("Sofa")); + expect(ins.length).toBe(3); + const door = ins.find((i) => (i.attribs as Record).TYP === "Tür")!; + expect(door.name).toBe("Tuer_90x210"); + expect(door.attribs).toMatchObject({ ID: "D1", BREITE_M: "0.90", HOEHE_M: "2.10", TYPENAME: expect.any(String) }); + expect(door.layer).toMatch(/^21_/); // Ebene der Kategorie „Türen/Fenster“ + expect(r.blocks[door.name as string].entities.LINE).toBeGreaterThan(0); + const win = ins.find((i) => (i.attribs as Record).TYP === "Fenster")!; + expect(win.attribs).toMatchObject({ BRUESTUNG_M: "0.90" }); + }); + + it("Möbelblock: ein BLOCK je Definition, zwei INSERTs mit Drehung und Skalierung", () => { + const r = read(); + const sofas = r.entities.filter((e) => e.type === "INSERT" && e.name === "Sofa"); + expect(sofas.length).toBe(2); + expect(sofas[0].at).toEqual([1.5, 1]); + expect(sofas[1].rotation as number).toBeCloseTo(90, 9); + expect(sofas[1].scale).toEqual([1.5, 1.5]); + expect(r.blocks.Sofa.entities).toEqual({ LINE: 5 }); // Rechteck = 4 Linien + 1 Linie, lokal + // Geometrie lokal um den Einfügepunkt (Rechteck −0.9…0.9), nicht an der Weltlage + const sofaLines = r.entities.filter((e) => e.type === "LINE" && Math.abs((e.pts as number[][])[0][0] - 1.5) < 1.0 && Math.abs((e.pts as number[][])[0][1] - 1) < 0.5 && e.layer.startsWith("90_")); + expect(sofaLines.length).toBe(0); // keine losen Linien an der Weltlage + }); + + it("Strichmuster → Linientyp mit dem Namen des Projekt-Linienstils (Papier-mm × Massstab)", () => { + const r = read(); + const lt = r.linetypes["Strichlinie_0.3_0.1"]; + expect(lt).toBeDefined(); + expect(lt.map((v) => Math.round(v * 1e6) / 1e6)).toEqual([0.3, -0.1]); // 3 mm / 1 mm Papier bei 1:100 + const line = r.entities.find((e) => e.type === "LINE" && e.linetype === "Strichlinie_0.3_0.1"); + expect(line).toBeDefined(); + // 1:50 halbiert die Längen + const r50 = read({ scaleDenominator: 50 }); + expect(r50.linetypes["Strichlinie_0.3_0.1"].map((v) => Math.round(v * 1e6) / 1e6)).toEqual([0.15, -0.05]); + }); + + it("Textstile: Schriftname aus dem Projekt, Fallback Arial; Umlaute", () => { + const r = read(); + expect(r.fonts.DOSSIER).toBe("Helvetica Neue"); + const text = r.entities.find((e) => e.type === "TEXT" && e.text === "Müller & Söhne")!; + expect(text).toBeDefined(); + expect(text.style).toBe("DOSSIER"); + expect(text.halign).toBe(0); + const noFont = ezdxf("cad2", buildPlanDxf(plan, { ...project, textStyles: [] })); + expect(noFont.status, noFont.err).toBe(0); + expect(noFont.r.fonts.DOSSIER).toBe("Arial"); + }); + + it("Raumstempel: Name und Fläche als zentrierte TEXTe im Massstab (Punkt → Meter)", () => { + const r = read(); + const stamps = r.entities.filter((e) => e.type === "TEXT" && e.halign === 1); + expect(stamps.length).toBeGreaterThan(0); + const texts = stamps.map((e) => e.text as string); + expect(texts.some((t) => /m²/.test(t))).toBe(true); + for (const s of stamps) expect(s.height as number).toBeGreaterThan(0.2); // 10 pt bei 1:100 ≈ 0.35 m + }); + + it("Papierbereich: Layout mit Ansichtsfenster im Planmassstab", () => { + const r = read({ paperLayout: true }); + const name = Object.keys(r.layouts).find((n) => n.startsWith("Plan_1-100"))!; + expect(name).toBeDefined(); + const vp = r.layouts[name].viewports.find((v) => v.id === 2)!; + expect(vp).toBeDefined(); + const [pw, ph] = r.layouts[name].paper!; + expect(vp.center[0]).toBeCloseTo(pw / 2, 6); + // Ausschnitt in Metern = Fenstergrösse (mm) / 10 (1:100) + expect(vp.view_height).toBeCloseTo(vp.size[1] / 10, 6); + expect(ph).toBeGreaterThan(0); + }); + + it("Binär-DXF trägt dieselben Objekte", () => { + const asc = ezdxf("asc", buildPlanDxf(plan, project)); + const bin = ezdxf("bin", buildPlanDxfBinary(plan, project)); + expect(bin.r.errors).toEqual([]); + expect(bin.status, bin.err).toBe(0); + expect(bin.r.entities).toEqual(asc.r.entities); + expect(Object.keys(bin.r.blocks)).toEqual(Object.keys(asc.r.blocks)); + }); +}); + +describe("Fachplaner-Export: DWG (libredwg) und eigener Import", () => { + const project = cadProject(); + const plan = generatePlan(project, "eg", allCodes(project)); + + it("DWG R2018: DIMENSION, INSERT, Blöcke und Umlaute kommen an", async () => { + const db = (await libreDwgReader())(buildPlanDwg(plan, project, { paperLayout: true })); + const counts = countByType(db.entities); + expect(counts.DIMENSION).toBe(2); + expect(counts.INSERT).toBeGreaterThanOrEqual(5); + const text = db.entities.find((e) => e.type === "TEXT" && e.text?.startsWith("Müller")); + expect(text?.text).toBe("Müller & Söhne"); + }); + + it("DXF-Import: Masszahlen, Möbelgeometrie und Türgeometrie kommen wieder an", () => { + const imp = parseDxf(buildPlanDxf(plan, project)); + const texts = (imp.texts ?? []).map((t) => t.text); + expect(texts).toContain("2.00"); + expect(texts).toContain("3.00"); + expect(texts).toContain("Müller & Söhne"); + // Möbel + Türen/Fenster sind als Geometrie vorhanden (Blöcke werden aufgelöst) + const lineCount = imp.contours.reduce((n, c) => n + c.contours.length, 0); + expect(lineCount).toBeGreaterThan(50); + expect(imp.diagnostics?.entityCounts.DIMENSION ?? imp.diagnostics?.entityCounts.INSERT).toBeDefined(); + }); + + it("DXF-Import: Papierbereich wird als Layout erkannt", () => { + // Das Layout hat nur ein Ansichtsfenster (kein eigener Inhalt) und steht darum nicht in der Liste, ist aber lesbar. + const dxf = buildPlanDxf(plan, project, { paperLayout: true }); + expect(() => parseDxf(dxf, "", "Plan_1-100")).not.toThrow(); + }); +}); diff --git a/src/export/exportDxf.ezdxf.test.ts b/src/export/exportDxf.ezdxf.test.ts index 58f9536b..3995e536 100644 --- a/src/export/exportDxf.ezdxf.test.ts +++ b/src/export/exportDxf.ezdxf.test.ts @@ -66,7 +66,11 @@ describe.skipIf(!hasEzdxf)("DXF-Export gegen ezdxf", { timeout: 60_000 }, () => expect(r.status).toBe(0); expect(r.result!.version).toBe("AC1032"); expect(r.result!.insunits).toBe(6); - const polys = plan.primitives.filter((p): p is Extract => p.kind === "polygon"); + // Ohne unsichtbare Pick-Bänder und ohne Öffnungs-Polygone (Fensterrahmen liegen im Block, nicht im Modellbereich). + const polys = plan.primitives.filter( + (p): p is Extract => + p.kind === "polygon" && !p.openingId && !(p.stroke === "none" && p.fill === "none" && p.hatch.pattern === "none"), + ); const ezPolys = r.result!.entities.filter((e) => e.type === "LWPOLYLINE"); expect(ezPolys.length).toBe(polys.length); for (let i = 0; i < polys.length; i++) { diff --git a/src/export/exportDxf.roundtrip.test.ts b/src/export/exportDxf.roundtrip.test.ts index f11c8e10..fde38420 100644 --- a/src/export/exportDxf.roundtrip.test.ts +++ b/src/export/exportDxf.roundtrip.test.ts @@ -21,32 +21,15 @@ import { projectToWorldCoords } from "../model/geoRebase"; const allCodes = (p: Project) => new Set(flattenCategories(p.layers).map((l) => l.code)); -/** Was die flache Zeichnung an Entitäten trägt (Zählung je Typ, aus dem Puffer). */ +/** Was die flache Zeichnung an Entitäten im Modellbereich trägt (Zählung je Typ, im Sammler mitgeführt). */ function flatCounts(plan: Plan, project: Project): Record { - const [flat] = collectPlanDrawing(plan, project).args(); - const names: Record number]> = { - 1: ["", () => 4], - 2: ["LINE", () => 6], - 3: ["LWPOLYLINE", (i) => 4 + 2 * flat[i + 3]], - 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; ) { - const [name, len] = names[flat[i]]; - if (name) out[name] = (out[name] ?? 0) + 1; - i += len(i); - } - return out; + return collectPlanDrawing(plan, project).stats().model; } +/** Polygone, die der Export schreibt: unsichtbare Pick-Bänder (weder Füllung noch Umriss noch Schraffur) entfallen. */ +const visiblePolys = (polys: Extract[]) => + polys.filter((p) => !p.openingId && !(p.stroke === "none" && p.fill === "none" && p.hatch.pattern === "none" && p.hatch.kind !== "gradient")); + describe("DXF-Export (R2018 über acadrust)", () => { const plan = generatePlan(sampleProject, "eg", allCodes(sampleProject)); @@ -66,7 +49,11 @@ describe("DXF-Export (R2018 über acadrust)", () => { it("jede übergebene Entität kommt an (Typ, Anzahl, Reihenfolge der Ebenen)", () => { const dxf = readDxf(buildPlanDxf(plan, sampleProject)); - expect(countByType(dxf.entities)).toEqual(flatCounts(plan, sampleProject)); + // ATTRIB/SEQEND hängen an den INSERTs (Türen/Fenster) und zählen nicht als eigene Entitäten des Plans. + const { ATTRIB, SEQEND, ...entities } = countByType(dxf.entities); + expect(ATTRIB ?? 0).toBeGreaterThanOrEqual(entities.INSERT ?? 0); // jede Tür/jedes Fenster trägt Attribute + expect(SEQEND ?? 0).toBe(entities.INSERT ?? 0); + expect(entities).toEqual(flatCounts(plan, sampleProject)); expect(dxf.entities.every((e) => dxf.layers.has(e.layer))).toBe(true); }); @@ -104,7 +91,7 @@ describe("Georeferenz (LV95)", () => { }; const world = projectToWorldCoords(anchored); const plan = generatePlan(world, "eg", allCodes(world)); - const polys = plan.primitives.filter((p): p is Extract => p.kind === "polygon"); + const polys = visiblePolys(plan.primitives.filter((p): p is Extract => p.kind === "polygon")); it("DXF: Polylinien-Koordinaten bitgleich zum Plan (f64, keine Rundung)", () => { const ents = readDxf(buildPlanDxf(plan, world)).entities.filter((e) => e.type === "LWPOLYLINE"); diff --git a/src/export/exportDxf.ts b/src/export/exportDxf.ts index 9f8516e8..12003f3a 100644 --- a/src/export/exportDxf.ts +++ b/src/export/exportDxf.ts @@ -14,13 +14,29 @@ // DWG = R2018 — Begründung im Kopf von export.rs. Der frühere TS-Text-Writer // (`dxfWriter.ts`) ist gelöscht. Das Format-Modul wird nachgeladen: vor `buildPlanDxf`/ // `buildPlanDwg` einmal `await loadFileio()` (savePlanDxf und die CLI tun das). +// +// Fachplaner-Export (28.10., [C2]): damit in AutoCAD/BricsCAD weitergearbeitet werden kann, entstehen +// statt loser Linien dort, wo das Modell die Information trägt, CAD-Objekte: +// - Bemassungen (`Drawing2D {shape:"dimension"}`) → je Segment eine DIMENSION samt Anonymblock `*D…` und +// Bemassungsstil (DIMSTYLE: Texthöhe/Strich/Abstände in Papier-mm, DIMSCALE = Massstab); +// - Türen/Fenster (Primitive mit `openingId`) → BLOCK + INSERT in der Wandrichtung, gleiche Geometrie +// teilt sich einen Block, ATTRIBs (Breite, Höhe, Typ, ID); +// - Blockinstanzen (`Drawing2D {shape:"block"}`, Möbel/Symbole/Nordpfeil) → BLOCK je Definition + INSERT; +// - Strichmuster → Linientypen (Name des Projekt-Linienstils), Texte → Textstile mit Schriftname und +// Ausrichtung (Raumstempel mit Fläche als TEXT, links/Mitte/rechts), optional Papierbereich. +// Alles andere (Wände, Umrisse, Schraffuren) bleibt wie bisher Linie/Polylinie/HATCH. import type { Plan, Primitive } from "../plan/generatePlan"; -import type { LayerCategory, Project, Vec2 } from "../model/types"; +import type { Drawing2D, LayerCategory, Opening, Project, Vec2 } from "../model/types"; +import type { Marks } from "../text/richText"; import { flattenCategories } from "../model/types"; +import { DEFAULT_SCALE_DENOMINATOR, DIM_DEFAULTS_MM, dimTextFrame, dimTextPos, mmToModel } from "../model/dimension"; import { buildRandomHatchRuns, zigzagPoints, motifPoints } from "../plan/glPlan/glPlanHatch"; import { plainText } from "../text/richText"; +import { docToLines } from "../text/renderHtml"; import { fileio, loadFileio } from "../engine/fileioWasm"; +import { dashToLtypeMeters, fontNameOf, ltypeNameFor, paperFor, primitiveToLocal, roundKey } from "./dxfCadParts"; +import type { LocalFrame } from "./dxfCadParts"; export interface ExportDxfOptions { /** Titel/Geschossname (nur als Kommentar-freundlicher Dateiname genutzt). */ @@ -29,6 +45,16 @@ export interface ExportDxfOptions { includeHatches?: boolean; /** Dateiname des Downloads (mit/ohne Endung). */ fileName?: string; + /** + * Massstabsnenner (100 = 1:100): macht aus Papier-Millimetern Modell-Meter — Texthöhe/Striche der + * Bemassung, Strichmuster der Linientypen, Schriftgrösse der Raumstempel, Massstab des Ansichtsfensters. + * Default 1:100 (wie `generatePlan`). + */ + scaleDenominator?: number; + /** Einheit der Masszahl: Meter (Default, wie im Plan „3.25") oder Zentimeter („325"). */ + dimUnit?: "m" | "cm"; + /** Zusätzlich ein Layout (Papierbereich) mit Ansichtsfenster im Planmassstab anlegen. */ + paperLayout?: boolean; } /** Ausgabeformat des Modell-Space-Exports. */ @@ -44,10 +70,14 @@ const LAYER_HATCH = "HATCH"; const LAYER_SYMBOLS = "SYMBOLS"; const LAYER_CONTEXT = "CONTEXT"; const LAYER_DEFAULT = "PLAN"; +/** Schnittführungs-Symbole (Primitive mit `cls === "section-line"`). */ +const LAYER_SECTIONS = "SECTIONS"; /** Sammel-Layer für Extrusions-Footprints (truck-Integration) — die Quell- * Drawing2D wird beim Extrudieren entfernt, es gibt also keine categoryCode * mehr nachzuschlagen; eigener Layer statt Absturz in LAYER_DEFAULT. */ const LAYER_EXTRUSION = "EXTRUSION"; +/** Ebene „0": Inhalt von Blöcken (erbt die Ebene des INSERT). */ +const LAYER_ZERO = "0"; // ── Flache Zeichnung (Gegenstück zu src-tauri/fileio/src/export.rs) ───────── @@ -60,60 +90,180 @@ const REC_CIRCLE = 5; const REC_TEXT = 6; const REC_HATCH = 7; const REC_GRADIENT = 8; +const REC_LTYPE = 9; +const REC_LAYER_LTYPE = 10; +const REC_PEN = 11; +const REC_STYLE = 12; +const REC_TEXT2 = 13; +const REC_DIMSTYLE = 14; +const REC_DIM = 15; +const REC_BLOCK = 16; +const REC_BLOCK_END = 17; +const REC_INSERT = 18; +const REC_LAYOUT = 19; + +/** Zustand, den eine Zeichnung und die Blockinhalte, die in sie hineingespleisst werden, teilen. */ +interface FlatShared { + /** Der Zahlenpuffer der Hauptzeichnung: Definitionen (Ebenen, Linientypen, Stile) landen immer hier, in Reihenfolge ihrer Indizes. */ + root: number[]; + strings: string[]; + strIdx: Map; + layers: Map; + ltypes: Map; + styles: Map; + dimStyles: Map; + blocks: Set; + /** Entitäten in Blockdefinitionen (Zählung für Tests). */ + blockCounts: Record; +} + +/** Eine Textzeile der Raumstempel/Textfelder für `addText2`. */ +export interface TextAlignOpts { + /** 0 links, 1 Mitte, 2 rechts (Anker = Einfügepunkt). */ + halign?: 0 | 1 | 2; + /** Textstil-Index aus {@link FlatDrawing.addTextStyle}; −1 = Standard. */ + style?: number; +} /** * Sammelt Ebenen und Entitäten als flachen Zahlenpuffer + Zeichenkettenliste. Ebenen sind * idempotent über den Namen; eine unbekannte Ebene wird mit Standardwerten (ACI 7, 0.25 mm) * angelegt — wie beim früheren Writer. Namen bereinigt Rust (`sanitize_layer_name`). + * + * `new FlatDrawing(parent)` ist ein Blockinhalt: er teilt Ebenen, Linientypen, Stile und Zeichenketten + * (dedupliziert, gleiche Eingabe ⇒ gleiche Indizes) mit der Hauptzeichnung, hat aber einen eigenen + * Entitätspuffer, der mit {@link defineBlock} an die Stelle der Blockdefinition kommt. */ export class FlatDrawing { - private nums: number[] = [FLAT_VERSION]; - private strings: string[] = []; - private layers = new Map(); + private sh: FlatShared; + private nums: number[]; + /** Aktueller Linientyp (PEN) dieses Puffers; −1 = nach Ebene. */ + private pen = -1; + /** Entitäten dieses Puffers je Typ (Tests). */ + private counts: Record = {}; + + constructor(parent?: FlatDrawing) { + if (parent) { + this.sh = parent.sh; + this.nums = []; + } else { + this.nums = [FLAT_VERSION]; + this.sh = { + root: this.nums, + strings: [], + strIdx: new Map(), + layers: new Map(), + ltypes: new Map(), + styles: new Map(), + dimStyles: new Map(), + blocks: new Set(), + blockCounts: {}, + }; + } + } private str(s: string): number { - this.strings.push(s.replace(/\0/g, "")); - return this.strings.length - 1; + const clean = s.replace(/\0/g, ""); + const known = this.sh.strIdx.get(clean); + if (known !== undefined) return known; + this.sh.strings.push(clean); + this.sh.strIdx.set(clean, this.sh.strings.length - 1); + return this.sh.strings.length - 1; + } + + private bump(kind: string): void { + this.counts[kind] = (this.counts[kind] ?? 0) + 1; + } + + /** Anzahl Entitäten im Modellbereich je Typ (INSERT/DIMENSION zählen je als eine) und in Blöcken (Summe je Typ). */ + stats(): { model: Record; blocks: Record } { + return { model: { ...this.counts }, blocks: { ...this.sh.blockCounts } }; } /** Legt eine Ebene an (`rgb` 0xRRGGBB oder null = ACI 7, `lineWeight` in 1/100 mm). */ addLayer(name: string, rgb: number | null, lineWeight: number): number { - const known = this.layers.get(name); + const known = this.sh.layers.get(name); if (known !== undefined) return known; - const idx = this.layers.size; - this.layers.set(name, idx); - this.nums.push(REC_LAYER, this.str(name), rgb ?? -1, lineWeight); + const idx = this.sh.layers.size; + this.sh.layers.set(name, idx); + this.sh.root.push(REC_LAYER, this.str(name), rgb ?? -1, lineWeight); return idx; } private layer(name: string): number { - return this.layers.get(name) ?? this.addLayer(name, null, 25); + return this.sh.layers.get(name) ?? this.addLayer(name, null, 25); + } + + /** + * Linientyp (Elemente in Metern: Strich +, Lücke −, Punkt 0; mindestens zwei Elemente), idempotent + * über den Namen. Gibt den Index für {@link setPen}/{@link setLayerLinetype} zurück. + */ + addLinetype(name: string, elements: number[]): number { + const known = this.sh.ltypes.get(name); + if (known !== undefined) return known; + const idx = this.sh.ltypes.size; + this.sh.ltypes.set(name, idx); + this.sh.root.push(REC_LTYPE, this.str(name), elements.length, ...elements); + return idx; + } + + /** Standard-Linientyp einer bereits angelegten Ebene. */ + setLayerLinetype(layerName: string, ltype: number): void { + this.sh.root.push(REC_LAYER_LTYPE, this.layer(layerName), ltype); + } + + /** Linientyp für die folgenden Linien/Bögen/Kreise/Polylinien (−1 = nach Ebene). Schreibt nur bei Änderung. */ + setPen(ltype: number): void { + if (ltype === this.pen) return; + this.pen = ltype; + this.nums.push(REC_PEN, ltype); + } + + /** Textstil mit TrueType-Schriftname (CAD löst ihn über das Betriebssystem auf), idempotent über den Namen. */ + addTextStyle(name: string, font: string, bold = false, italic = false): number { + const known = this.sh.styles.get(name); + if (known !== undefined) return known; + const idx = this.sh.styles.size; + this.sh.styles.set(name, idx); + this.sh.root.push(REC_STYLE, this.str(name), this.str(font), bold ? 1 : 0, italic ? 1 : 0, 1); + return idx; } addLine(layer: string, a: Vec2, b: Vec2): void { + this.bump("LINE"); this.nums.push(REC_LINE, this.layer(layer), a.x, a.y, b.x, b.y); } addPolyline(layer: string, pts: Vec2[], closed: boolean): void { if (pts.length < 2) return; + this.bump("LWPOLYLINE"); this.nums.push(REC_POLYLINE, this.layer(layer), closed ? 1 : 0, pts.length); for (const p of pts) this.nums.push(p.x, p.y); } /** Bogen gegen den Uhrzeigersinn von `start` nach `end` (Radiant). */ addArc(layer: string, center: Vec2, r: number, start: number, end: number): void { + this.bump("ARC"); this.nums.push(REC_ARC, this.layer(layer), center.x, center.y, r, start, end); } addCircle(layer: string, center: Vec2, r: number): void { + this.bump("CIRCLE"); this.nums.push(REC_CIRCLE, this.layer(layer), center.x, center.y, r); } /** Einzeiliger Text (Höhe in Metern, Drehung in Radiant). */ addText(layer: string, at: Vec2, height: number, rotation: number, value: string): void { + this.bump("TEXT"); this.nums.push(REC_TEXT, this.layer(layer), this.str(value), at.x, at.y, height, rotation); } + /** Einzeiliger Text mit Ausrichtung (Anker = Einfügepunkt, Grundlinie) und Textstil. */ + addText2(layer: string, at: Vec2, height: number, rotation: number, value: string, o: TextAlignOpts = {}): void { + this.bump("TEXT"); + this.nums.push(REC_TEXT2, this.layer(layer), this.str(value), at.x, at.y, height, rotation, o.halign ?? 0, o.style ?? -1); + } + /** * 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 @@ -126,6 +276,7 @@ export class FlatDrawing { opts: { solid: boolean; rgb: number | null; families?: { angle: number; spacing: number }[]; dashes?: number[] }, ): void { if (pts.length < 3) return; + this.bump("HATCH"); 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); @@ -141,16 +292,117 @@ export class FlatDrawing { */ addGradient(layer: string, pts: Vec2[], g: { rgb1: number; rgb2: number; angle: number; radial: boolean }): void { if (pts.length < 3) return; + this.bump("HATCH"); 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); } + /** + * Bemassungsstil (Papier-Meter, s. `export_dim.rs`), idempotent über `name`. `textStyle` = Index aus + * {@link addTextStyle} oder −1; `post` = Format mit `<>` als Platzhalter der Zahl (oder leer). + */ + addDimStyle( + name: string, + d: { textStyle: number; scale: number; txt: number; tick: number; exo: number; exe: number; gap: number; dec: number; lfac: number; post?: string }, + ): number { + const known = this.sh.dimStyles.get(name); + if (known !== undefined) return known; + const idx = this.sh.dimStyles.size; + this.sh.dimStyles.set(name, idx); + this.sh.root.push( + REC_DIMSTYLE, this.str(name), d.textStyle, d.scale, d.txt, d.tick, d.exo, d.exe, d.gap, d.dec, d.lfac, + d.post ? this.str(d.post) : -1, + ); + return idx; + } + + /** + * Ausgerichtete Bemassung (DIMENSION + Anonymblock `*D…`) zwischen `p1` und `p2`; `onLine` = ein Punkt + * auf der Masslinie (legt Seite und Abstand fest), `textAt` = freie Lage der Masszahl (Mitte). + */ + addDimension(layer: string, dimStyle: number, p1: Vec2, p2: Vec2, onLine: Vec2, textAt?: Vec2): void { + this.bump("DIMENSION"); + this.nums.push(REC_DIM, this.layer(layer), dimStyle, p1.x, p1.y, p2.x, p2.y, onLine.x, onLine.y, textAt ? 1 : 0, textAt?.x ?? 0, textAt?.y ?? 0); + } + + /** Ob ein Block dieses Namens schon definiert ist. */ + hasBlock(name: string): boolean { + return this.sh.blocks.has(name); + } + + /** + * Blockdefinition: der Inhalt `content` (ein `new FlatDrawing(this)`) kommt mit blocklokalen Koordinaten + * an diese Stelle. `atts` = Attributdefinitionen (unsichtbar; Wert je INSERT). + */ + defineBlock(name: string, description: string, atts: { tag: string; prompt: string; def: string }[], content: FlatDrawing): void { + if (this.sh.blocks.has(name)) return; + this.sh.blocks.add(name); + this.nums.push(REC_BLOCK, this.str(name), description ? this.str(description) : -1, atts.length); + for (const a of atts) this.nums.push(this.str(a.tag), this.str(a.prompt), this.str(a.def), 0, 0, 0.1); + // Der Block beginnt mit „nach Ebene“; danach gilt der Linientyp, mit dem sein Inhalt endete. + this.nums.push(REC_PEN, -1); + for (const v of content.nums) this.nums.push(v); + this.nums.push(REC_BLOCK_END); + this.pen = content.pen; + for (const [k, n] of Object.entries(content.counts)) this.sh.blockCounts[k] = (this.sh.blockCounts[k] ?? 0) + n; + } + + /** Inhalt eines Blocks als Schlüssel: gleiche Zahlen (auf 1 mm gerundet) ⇒ gleicher Block. */ + contentKey(): string { + return roundKey(this.nums); + } + + /** Blockeinfügung mit Attributwerten (`tag` → Wert). */ + addInsert(layer: string, name: string, at: Vec2, rotation: number, scale: number, values: { tag: string; value: string }[] = []): void { + this.bump("INSERT"); + this.nums.push(REC_INSERT, this.layer(layer), this.str(name), at.x, at.y, rotation, scale, scale, values.length); + for (const v of values) this.nums.push(this.str(v.tag), this.str(v.value)); + } + + /** + * Papierbereich: Layout `name` (Papier in mm) mit einem Ansichtsfenster auf den Modellbereich. + * `vp` = Mittelpunkt und Grösse des Fensters auf dem Papier (mm), `view` = Mittelpunkt des Ausschnitts im Modell. + */ + addLayout(name: string, paperW: number, paperH: number, vp: { cx: number; cy: number; w: number; h: number }, view: Vec2, scaleDenominator: number): void { + this.nums.push(REC_LAYOUT, this.str(name), paperW, paperH, vp.cx, vp.cy, vp.w, vp.h, view.x, view.y, scaleDenominator); + } + /** Argumente für die Rust-Bindungen. */ args(): [Float64Array, string] { - return [Float64Array.from(this.nums), this.strings.join("\0")]; + return [Float64Array.from(this.nums), this.sh.strings.join("\0")]; } } +// ── Plan → flache Zeichnung ───────────────────────────────────────────────── + +/** Gemeinsamer Zustand beim Sammeln eines Plans. */ +interface Ctx { + project: Project; + scale: number; + includeHatches: boolean; + dimUnit: "m" | "cm"; + /** Ebenenname je Kategorie-Code. */ + layerNameByCode: Map; + /** Kategorie-Code je Zeichen-Element / Raum (für Ebenen). */ + codeByDrawing: Map; + codeByRoom: Map; + /** Linientyp-Index zu einem Strichmuster (−1 = durchgezogen). */ + ltypeOf: (dxf: FlatDrawing, dash: number[] | null | undefined) => number; + /** Textstil-Index zu einer Formatierung. */ + styleOf: (dxf: FlatDrawing, marks?: Marks) => number; +} + +/** Eine Zeile einer (Rich-)Text-Ausgabe. */ +interface OutLine { + text: string; + /** Schrifthöhe (Meter). */ + height: number; + align: 0 | 1 | 2; + marks?: Marks; + /** Versatz der Grundlinie vom Anker nach unten (Meter, ≥ 0 für spätere Zeilen). */ + down: number; +} + /** * Baut aus einem Plan + Projekt die flache Zeichnung (Meter-Modell-Space). * Reihenfolge der Primitive bleibt erhalten. @@ -161,6 +413,7 @@ export function collectPlanDrawing( opts: ExportDxfOptions = {}, ): FlatDrawing { const includeHatches = opts.includeHatches ?? true; + const scale = opts.scaleDenominator && Number.isFinite(opts.scaleDenominator) && opts.scaleDenominator > 0 ? opts.scaleDenominator : DEFAULT_SCALE_DENOMINATOR; const dxf = new FlatDrawing(); // 1) Layer aus den Kategorie-Ebenen anlegen (Code+Name als Layer-Name, Farbe, @@ -177,8 +430,10 @@ export function collectPlanDrawing( dxf.addLayer(LAYER_HATCH, 0x888888, 13); dxf.addLayer(LAYER_CONTEXT, 0x9aa3ad, 10); dxf.addLayer(LAYER_DEFAULT, 0x111111, 18); + dxf.addLayer(LAYER_SECTIONS, 0x111111, 18); // Warmes Orange, identisch zum 3D-/Grundriss-Footprint der Extrusionen (EXTRUSION_STROKE/EXTRUSION_RGB). dxf.addLayer(LAYER_EXTRUSION, rgbFromHex("#d98c40"), 13); + dxf.addLayer(LAYER_ZERO, null, 25); // Blockinhalt; „0" gibt es in jeder Datei, der Eintrag legt nur den Index fest // 2) Rückverweise Primitiv → Kategorie: Wände/2D-Elemente tragen nur ihre ID im // Plan; die Kategorie liegt am Projekt-Objekt. Damit landet jede Wand-/Drawing- @@ -189,6 +444,8 @@ export function collectPlanDrawing( for (const d of project.drawings2d) codeByDrawing.set(d.id, d.categoryCode); const codeByColumn = new Map(); for (const c of project.columns ?? []) codeByColumn.set(c.id, c.categoryCode); + const codeByRoom = new Map(); + for (const r of project.rooms ?? []) codeByRoom.set(r.id, r.categoryCode); const drawingLayer = (id: string | undefined, fallback: string): string => id ? (layerNameByCode.get(codeByDrawing.get(id) ?? "") ?? LAYER_DEFAULT) : fallback; @@ -202,22 +459,250 @@ export function collectPlanDrawing( } if (p.kind === "line") { if (p.cls === "context-line") return LAYER_CONTEXT; + if (p.cls === "section-line") return LAYER_SECTIONS; // Tür-Blatt/-Rahmen und Wand-Achsen: Symbol-Sammellayer. return drawingLayer(p.drawingId, LAYER_SYMBOLS); } // Texte von 2D-Elementen: Ebene ihrer Kategorie. if (p.kind === "drawingText") return drawingLayer(p.drawingId, LAYER_SYMBOLS); + if (p.kind === "text") return p.roomId ? (layerNameByCode.get(codeByRoom.get(p.roomId) ?? "") ?? LAYER_SYMBOLS) : LAYER_SYMBOLS; // Bögen: Tür-Schwenkbogen → Symbole. return LAYER_SYMBOLS; }; - // 3) Jedes Primitiv in Entities übersetzen. - for (const p of plan.primitives) { - emitPrimitive(dxf, p, layerFor(p), includeHatches); + // Standard-Schrift: erste im Projekt hinterlegte Schrift der Textstile, sonst Arial. + const defaultFont = (project.textStyles ?? []).map((s) => fontNameOf(s.marks.font)).find((f) => f) ?? "Arial"; + const ctx: Ctx = { + project, + scale, + includeHatches, + dimUnit: opts.dimUnit ?? "m", + layerNameByCode, + codeByDrawing, + codeByRoom, + ltypeOf: (d, dash) => { + if (!dash || dash.length === 0) return -1; + const el = dashToLtypeMeters(dash, scale); + return el ? d.addLinetype(ltypeNameFor(dash, project.lineStyles), el) : -1; + }, + styleOf: (d, marks) => { + const family = fontNameOf(marks?.font) ?? defaultFont; + const bold = !!marks?.bold; + const italic = !!marks?.italic; + const plain = family === defaultFont && !bold && !italic; + const name = plain ? "DOSSIER" : `DOSSIER_${family}${bold ? "_B" : ""}${italic ? "_I" : ""}`; + return d.addTextStyle(name, family, bold, italic); + }, + }; + + // 3) Gruppen: Bemassungen, Blockinstanzen und Öffnungen werden zu CAD-Objekten statt zu losen Primitiven. + const dimById = new Map(); + const blockById = new Map(); + for (const d of project.drawings2d) { + if (d.geom?.shape === "dimension") dimById.set(d.id, d); + else if (d.geom?.shape === "block") blockById.set(d.id, d); } + const openingById = new Map(); + for (const o of project.openings ?? []) openingById.set(o.id, o); + const groupKeyOf = (p: Primitive): string | null => { + const did = "drawingId" in p ? p.drawingId : undefined; + if (did && dimById.has(did)) return `d:${did}`; + if (did && blockById.has(did)) return `b:${did}`; + const oid = "openingId" in p ? p.openingId : undefined; + if (oid && openingById.has(oid)) return `o:${oid}`; + return null; + }; + const groups = new Map(); + for (const p of plan.primitives) { + const k = groupKeyOf(p); + if (!k) continue; + const g = groups.get(k); + if (g) g.push(p); + else groups.set(k, [p]); + } + const blockNames = new BlockNames(); + const doneGroups = new Set(); + + // 4) Jedes Primitiv in Entities übersetzen. + for (const p of plan.primitives) { + const key = groupKeyOf(p); + if (key) { + if (doneGroups.has(key)) continue; + doneGroups.add(key); + const prims = groups.get(key) ?? []; + if (key.startsWith("d:")) emitDimensions(dxf, ctx, dimById.get(key.slice(2))!, drawingLayer(key.slice(2), LAYER_DEFAULT)); + else if (key.startsWith("b:")) { + const d = blockById.get(key.slice(2))!; + if (!emitBlockInstance(dxf, ctx, d, prims, drawingLayer(d.id, LAYER_DEFAULT), blockNames)) for (const q of prims) emitPrimitive(dxf, ctx, q, layerFor(q), LAYER_HATCH); + } else { + const o = openingById.get(key.slice(2))!; + if (!emitOpening(dxf, ctx, o, prims, layerNameByCode.get(o.categoryCode) ?? LAYER_SYMBOLS, blockNames)) for (const q of prims) emitPrimitive(dxf, ctx, q, layerFor(q), LAYER_HATCH); + } + continue; + } + emitPrimitive(dxf, ctx, p, layerFor(p), LAYER_HATCH); + } + dxf.setPen(-1); + + // 5) Papierbereich (optional): ein Layout mit Ansichtsfenster im Planmassstab auf die Plan-Ausdehnung. + if (opts.paperLayout) addPaperLayout(dxf, plan, scale); return dxf; } +/** Eindeutige Blocknamen: gleiche Schlüssel teilen sich einen Namen, verschiedene Inhalte mit gleichem Wunschnamen werden nummeriert. */ +class BlockNames { + private byKey = new Map(); + private used = new Set(); + /** Name zum Schlüssel; `fresh` = der Block muss noch definiert werden. */ + name(key: string, wish: string): { name: string; fresh: boolean } { + const known = this.byKey.get(key); + if (known) return { name: known, fresh: false }; + let name = wish; + for (let i = 2; this.used.has(name.toLowerCase()); i++) name = `${wish}_${i}`; + this.used.add(name.toLowerCase()); + this.byKey.set(key, name); + return { name, fresh: true }; + } +} + +/** Papierbereich auf die Ausdehnung des Plans (Meter) im Massstab `scale`. */ +function addPaperLayout(dxf: FlatDrawing, plan: Plan, scale: number): void { + const b = plan.bounds; + const w = b.maxX - b.minX; + const h = b.maxY - b.minY; + if (![b.minX, b.minY, b.maxX, b.maxY].every(Number.isFinite) || w <= 0 || h <= 0) return; + const margin = 10; + const paper = paperFor(w, h, scale, margin); + dxf.addLayout( + `Plan 1-${scale}`, + paper.paperW, + paper.paperH, + { cx: paper.paperW / 2, cy: paper.paperH / 2, w: paper.vpW, h: paper.vpH }, + { x: (b.minX + b.maxX) / 2, y: (b.minY + b.maxY) / 2 }, + scale, + ); +} + +/** Format einer Länge für Attribute: Meter, 2 Nachkommastellen. */ +function m2(v: number): string { + return Number.isFinite(v) ? v.toFixed(2) : ""; +} + +/** Bemassungskette → je Segment eine DIMENSION; Stil aus den Papier-mm-Feinheiten und dem Massstab. */ +function emitDimensions(dxf: FlatDrawing, ctx: Ctx, d: Drawing2D, layer: string): void { + const g = d.geom; + if (g.shape !== "dimension") return; + const th = g.textHeightMm ?? DIM_DEFAULTS_MM.textHeight; + const tick = g.tickLenMm ?? DIM_DEFAULTS_MM.tickLen; + const gap = g.gapMm ?? DIM_DEFAULTS_MM.gap; + const over = g.overshootMm ?? DIM_DEFAULTS_MM.overshoot; + if (![th, tick, gap, over].every((v) => Number.isFinite(v) && v >= 0) || th <= 0) return; + const cm = ctx.dimUnit === "cm"; + const isDefault = th === DIM_DEFAULTS_MM.textHeight && tick === DIM_DEFAULTS_MM.tickLen && gap === DIM_DEFAULTS_MM.gap && over === DIM_DEFAULTS_MM.overshoot; + const variant = isDefault ? "" : `_${th}-${tick}-${gap}-${over}`.replace(/\./g, ","); + const name = `DOSSIER_1-${ctx.scale}${cm ? "_cm" : ""}${variant}`; + const style = dxf.addDimStyle(name, { + textStyle: ctx.styleOf(dxf), + scale: ctx.scale, + txt: th / 1000, + tick: tick / 1000, + exo: gap / 1000, + exe: over / 1000, + gap: (th * 0.6) / 1000, // Unterkante der Zahl 0.6 × Texthöhe über der Masslinie, wie im Plan + dec: cm ? 0 : 2, + lfac: cm ? 100 : 1, + }); + const mm = (v: number) => mmToModel(v, ctx.scale); + const textH = mm(th); + for (let i = 0; i + 1 < g.pts.length; i++) { + const a = g.pts[i]; + const b = g.pts[i + 1]; + const len = Math.hypot(b.x - a.x, b.y - a.y); + if (len < 1e-6) continue; + const nx = -(b.y - a.y) / len; + const ny = (b.x - a.x) / len; + const onLine = { x: a.x + nx * g.offset, y: a.y + ny * g.offset }; + // Von Hand verschobene Masszahl: Mitte = Grundlinienpunkt des Plans + halbe Texthöhe quer zur Linie. + const o = g.textOffsetsMm?.[i]; + let textAt: Vec2 | undefined; + if (o && (o.along !== 0 || o.perp !== 0)) { + const base = dimTextPos(a, b, g.offset, textH, { along: mm(o.along), perp: mm(o.perp) }); + const up = dimTextFrame(a, b, g.offset, textH).up; + textAt = { x: base.x + up.x * (textH / 2), y: base.y + up.y * (textH / 2) }; + } + dxf.addDimension(layer, style, a, b, onLine, textAt); + } +} + +/** Blockinstanz (`Drawing2D {shape:"block"}`) → BLOCK je Definition (lokale Geometrie) + INSERT. */ +function emitBlockInstance(dxf: FlatDrawing, ctx: Ctx, d: Drawing2D, prims: Primitive[], layer: string, names: BlockNames): boolean { + const g = d.geom; + if (g.shape !== "block") return false; + const def = ctx.project.blockDefs?.find((b) => b.id === g.blockDefId); + const s = g.scale ?? 1; + if (!def || !(s > 0) || !Number.isFinite(s) || !Number.isFinite(g.rotation) || !Number.isFinite(g.at.x) || !Number.isFinite(g.at.y)) return false; + const { name, fresh } = names.name(`blockdef:${def.id}`, def.name.trim() || "Block"); + if (fresh) { + const frame: LocalFrame = { origin: g.at, rot: g.rotation, scale: s }; + const content = new FlatDrawing(dxf); + for (const p of prims) { + const lp = primitiveToLocal(p, frame); + if (lp) emitPrimitive(content, ctx, lp, LAYER_ZERO, LAYER_ZERO); + } + content.setPen(-1); + dxf.defineBlock(name, def.name, [], content); + } + dxf.addInsert(layer, name, g.at, g.rotation, s); + return true; +} + +/** Tür/Fenster → BLOCK (Geometrie in der Wandrichtung, am ersten Pfosten verankert) + INSERT mit Attributen. */ +function emitOpening(dxf: FlatDrawing, ctx: Ctx, o: Opening, prims: Primitive[], layer: string, names: BlockNames): boolean { + const wall = ctx.project.walls.find((w) => w.id === o.hostWallId); + if (!wall) return false; + const len = Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y); + if (len < 1e-6 || !Number.isFinite(o.position)) return false; + const ux = (wall.end.x - wall.start.x) / len; + const uy = (wall.end.y - wall.start.y) / len; + const origin = { x: wall.start.x + ux * o.position, y: wall.start.y + uy * o.position }; + const rot = Math.atan2(uy, ux); + const frame: LocalFrame = { origin, rot, scale: 1 }; + const content = new FlatDrawing(dxf); + for (const p of prims) { + const lp = primitiveToLocal(p, frame); + if (lp) emitPrimitive(content, ctx, lp, LAYER_ZERO, LAYER_ZERO); + } + content.setPen(-1); + const isDoor = o.kind === "door"; + const kindName = !isDoor ? "Fenster" : o.doorType === "wandoeffnung" ? "Wandoeffnung" : "Tuer"; + const cm = (v: number) => String(Math.round(v * 100)); + const wish = `${kindName}_${cm(o.width)}x${cm(o.height)}`; + const { name, fresh } = names.name(`${kindName}:${content.contentKey()}`, wish); + const atts = [ + { tag: "ID", prompt: "Kennung", def: "" }, + { tag: "TYP", prompt: "Art", def: kindName }, + { tag: "TYPENAME", prompt: "Typ", def: "" }, + { tag: "BREITE_M", prompt: "Breite [m]", def: "" }, + { tag: "HOEHE_M", prompt: "Hoehe [m]", def: "" }, + ...(isDoor ? [] : [{ tag: "BRUESTUNG_M", prompt: "Bruestung [m]", def: "" }]), + ]; + if (fresh) { + const label = !isDoor ? "Fenster" : o.doorType === "wandoeffnung" ? "Wandöffnung" : "Tür"; + dxf.defineBlock(name, `${label} ${m2(o.width)} × ${m2(o.height)} m`, atts, content); + } + const typeName = (isDoor ? ctx.project.doorTypes : ctx.project.windowTypes)?.find((t) => t.id === o.typeId)?.name ?? ""; + const label = !isDoor ? "Fenster" : o.doorType === "wandoeffnung" ? "Wandöffnung" : "Tür"; + dxf.addInsert(layer, name, origin, rot, 1, [ + { tag: "ID", value: o.id }, + { tag: "TYP", value: label }, + { tag: "TYPENAME", value: typeName }, + { tag: "BREITE_M", value: m2(o.width) }, + { tag: "HOEHE_M", value: m2(o.height) }, + ...(isDoor ? [] : [{ tag: "BRUESTUNG_M", value: m2(o.sillHeight) }]), + ]); + return true; +} + /** * Baut aus einem Plan + Projekt einen vollständigen DXF-String (R2018 ASCII, Meter-Modell-Space). * Verlangt das geladene Format-Modul (`await loadFileio()`). @@ -270,13 +755,70 @@ function layerName(c: LayerCategory): string { return `${c.code}_${c.name}`; } -/** Schreibt ein Plan-Primitiv als passende Entity(en). */ +/** Stempel-/Textzeilen eines Primitivs `text` (Raumstempel): Rich-Text-Doc + Live-Zeilen, vertikal um den Anker zentriert wie in der Plan-Ansicht. */ +function stampLines(p: Extract, scale: number): OutLine[] { + const unitPerPt = (0.0254 / 72) * scale; // 1 pt Papier in Modell-Metern + const baseFs = p.basePt * unitPerPt; + const lineGap = baseFs * 1.3; + const docLines = docToLines(p.doc, { x: 0, y: 0, lineHeight: lineGap, unitPerPt, basePt: p.basePt, color: p.color }); + const lines = [ + ...docLines.map((l) => ({ align: l.align, lineHeight: l.lineHeight, ts: l.tspans })), + ...p.extraLines.map((l) => ({ align: l.align, lineHeight: lineGap, ts: [{ text: l.text, fontSize: baseFs * 0.8, fontFamily: undefined as string | undefined, fontWeight: undefined as string | undefined, fontStyle: undefined as string | undefined }] })), + ]; + if (lines.length === 0) return []; + const totalH = baseFs + lines.slice(1).reduce((s, l) => s + l.lineHeight, 0); + let down = -totalH / 2 + baseFs * 0.8; + const out: OutLine[] = []; + lines.forEach((l, k) => { + if (k > 0) down += l.lineHeight; + const text = l.ts.map((t) => t.text).join(""); + const first = l.ts[0]; + if (!text.trim() || !first) return; + out.push({ + text, + height: Math.max(...l.ts.map((t) => t.fontSize)), + align: l.align === "center" ? 1 : l.align === "right" ? 2 : 0, + marks: { font: first.fontFamily, bold: first.fontWeight === "700", italic: first.fontStyle === "italic" }, + down, + }); + }); + return out; +} + +/** Zeilen eines `drawingText`: Absätze bzw. Zeilenumbrüche, bei Spaltenbreite wortweise umbrochen; Zeilenabstand wie die Plan-Ansicht (1.25 × Höhe). */ +function drawingTextLines(p: Extract): OutLine[] { + const paragraphs = p.doc ? plainText(p.doc).split("\n") : p.text.split(/\r?\n/); + const lines: string[] = []; + if (p.wrapWidth && p.wrapWidth > 0) { + const maxChars = Math.max(1, Math.floor(p.wrapWidth / (p.heightM * 0.55))); + for (const para of paragraphs) { + let line = ""; + for (const word of para.split(/\s+/)) { + if (line === "") line = word; + else if (line.length + 1 + word.length <= maxChars) line += ` ${word}`; + else { + lines.push(line); + line = word; + } + } + lines.push(line); + } + } else { + lines.push(...paragraphs); + } + const marks = p.marks ?? p.doc?.paragraphs[0]?.runs[0]?.marks; + return lines.map((text, k) => ({ text, height: p.heightM, align: 0 as const, marks, down: k * p.heightM * 1.25 })); +} + +/** Schreibt ein Plan-Primitiv als passende Entity(en). `hatchLayer` = Ebene der Schraffuren (in Blöcken „0"). */ function emitPrimitive( dxf: FlatDrawing, + ctx: Ctx, p: Primitive, layer: string, - includeHatches: boolean, + hatchLayer: string, ): void { + const includeHatches = ctx.includeHatches; switch (p.kind) { case "line": if (p.zigzag) { @@ -284,40 +826,61 @@ function emitPrimitive( // Modell-Meter über dieselbe Kopplung wie das Strichmuster unten). const amp = p.zigzag.amplitude * DASH_MM_TO_M; const wav = p.zigzag.wavelength * DASH_MM_TO_M; + dxf.setPen(-1); dxf.addPolyline(layer, zigzagPoints(p.a, p.b, amp, wav), false); } else if (p.motif) { // Custom-Motiv → offene Polylinie (Papier-mm → Modell-Meter, wie unten). + dxf.setPen(-1); dxf.addPolyline(layer, motifPoints(p.a, p.b, p.motif, DASH_MM_TO_M), false); } else { + dxf.setPen(ctx.ltypeOf(dxf, p.dash)); dxf.addLine(layer, p.a, p.b); } break; case "arc": + dxf.setPen(ctx.ltypeOf(dxf, p.dash)); emitArc(dxf, p, layer); break; // Gezeichnete Kreise/Bögen (2D-Elemente). `drawingArc` läuft per Konvention // immer CCW von a0 nach a1 (s. planView/primitives), genau wie DXF-Bögen. case "drawingCircle": + dxf.setPen(ctx.ltypeOf(dxf, p.dash)); dxf.addCircle(layer, p.center, p.r); break; case "drawingArc": + dxf.setPen(ctx.ltypeOf(dxf, p.dash)); dxf.addArc(layer, p.center, p.r, p.a0, p.a1); break; - // 2D-Text (neu mit [C2]; der alte Writer liess Texte weg): einzeiliger TEXT, - // Ankerpunkt = Einfügepunkt, Absätze eines Rich-Text-Felds mit Leerzeichen verbunden. + // 2D-Text: TEXT mit Textstil (Schriftname aus den Formatierungen, sonst Projekt-Schrift/Arial), linksbündig an + // der Grundlinie wie in der Plan-Ansicht; mehrere Absätze/Spaltenbreite als mehrere Zeilen darunter. case "drawingText": { - const value = p.doc ? plainText(p.doc) : p.text; - if (value.trim() && p.heightM > 0) dxf.addText(layer, p.at, p.heightM, p.angle, value); + const lines = drawingTextLines(p); + const dir = { x: Math.sin(p.angle), y: -Math.cos(p.angle) }; // „nach unten“ im gedrehten Text + for (const l of lines) { + if (!l.text.trim() || !(l.height > 0)) continue; + const at = { x: p.at.x + dir.x * l.down, y: p.at.y + dir.y * l.down }; + dxf.addText2(layer, at, l.height, p.angle, l.text, { style: ctx.styleOf(dxf, l.marks) }); + } + break; + } + + // Raumstempel (Name, Nutzung, Fläche): je Zeile ein TEXT, links/Mitte/rechts wie im Plan, um den Anker zentriert. + case "text": { + for (const l of stampLines(p, ctx.scale)) { + dxf.addText2(layer, { x: p.at.x, y: p.at.y - l.down }, l.height, 0, l.text, { halign: l.align, style: ctx.styleOf(dxf, l.marks) }); + } break; } case "polygon": { const pts = p.pts; if (pts.length < 2) break; + // Unsichtbare Pick-Bänder (Dach-Traufe, Kontext-Hülle, Schnittlinie): weder Füllung noch Umriss noch Schraffur. + if (p.stroke === "none" && p.fill === "none" && p.hatch.pattern === "none" && p.hatch.kind !== "gradient") 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. Verlauf-Schraffur (kind==="gradient") @@ -331,33 +894,35 @@ function emitPrimitive( 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" }); + dxf.addGradient(hatchLayer, 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) }); + dxf.addHatch(hatchLayer, 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] })); + dxf.setPen(-1); for (const seg of segs) { if (cycle) { - for (const d of dashSeg(seg, cycle)) dxf.addLine(LAYER_HATCH, d.a, d.b); + for (const d of dashSeg(seg, cycle)) dxf.addLine(hatchLayer, d.a, d.b); } else { - dxf.addLine(LAYER_HATCH, seg.a, seg.b); + dxf.addLine(hatchLayer, 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) ?? [] }); + dxf.addHatch(hatchLayer, 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.setPen(-1); dxf.addPolyline(layer, pts, true); break; }