[K3d] DXF-/DWG-Sammler im Kern: plan_dxf.rs liest Plan-Puffer und Projekt-Dokument

Ebenen, Linientypen, Textstile, Bemassungen (DIMSTYLE/DIMENSION), Türen/Fenster und Blockinstanzen
(BLOCK/INSERT/ATTRIB), Schraffuren (HATCH, Verlauf, Zufallsstriche), Papierbereich: die flache
Zeichnung entsteht im Kern und geht über TS an fileio (Schreibung unverändert dort). TS behält das
Text-Layout (Zeilen der Raumstempel, Absätze/Wörter der Einzeltexte, Schriftfamilie) und schickt es
flach mit; der Spaltenumbruch läuft im Kern (blocklokale Grösse). FlatDrawing-Klasse, Sammler und
dxfCadParts (ausser fontNameOf) in TS gelöscht, Tests nach Rust.

Gleichheit (temporärer Test gegen die alte TS-Fassung): flache Zeichnung Zahl für Zahl und
Zeichenketten gleich über 451 Fälle (Beispiel + Fachplaner-Projekt, 3 Geschosse × 3 Detailgrade ×
mono × 3 Optionssätze, 300 Zufallspläne mit allen Primitiv-/Schraffur-Arten, Zusatz-Primitive,
bigSample(8)); DXF/Binär byte-gleich; CLI dxf/dwg (--binary, --scale, --dim-unit cm, --layout)
36 Dateien byte-gleich zur CLI des Hauptstands.

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-29 01:49:28 +00:00
1 parent 70bb23f2bc
commit 9a3d07158b
9 files changed
+1609 -1072

No files matched your search

+1
View File
@@ -63,6 +63,7 @@ pub mod plan_scene;
pub mod plan_pick;
pub mod snap;
pub mod plan_svg;
pub mod plan_dxf;
#[cfg(feature = "web")]
mod web;
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -11,7 +11,7 @@ thread_local! {
static DOCS: RefCell<Vec<Option<Document>>> = const { RefCell::new(Vec::new()) };
}
fn with_doc<R>(h: u32, f: impl FnOnce(&mut Document) -> R) -> Option<R> {
pub(crate) fn with_doc<R>(h: u32, f: impl FnOnce(&mut Document) -> R) -> Option<R> {
DOCS.with(|d| d.borrow_mut().get_mut((h as usize).checked_sub(1)?)?.as_mut().map(f))
}
+1
View File
@@ -36,6 +36,7 @@ mod plan_scene;
mod plan_pick;
mod snap;
mod plan_svg;
mod plan_dxf;
use wasm_bindgen::prelude::wasm_bindgen;
+36
View File
@@ -0,0 +1,36 @@
//! Bindung des DXF-Sammlers (`crate::plan_dxf`) auf gehaltenen Plan-Puffern (Abschnitte wie
//! `plan_parts`) und dem Projekt-Dokument. Leeres Ergebnis = Puffer fehlt (TS legt neu ab und
//! fragt nochmals), Dokument nicht offen/unpassend oder kaputte Eingabe — nie Panic.
use crate::plan_dxf::{collect, encode, texts_from, DxfOptions};
use crate::plan_parts::parts_from;
use wasm_bindgen::prelude::wasm_bindgen;
/// Flache Zeichnung (Format `plan_dxf::encode`). `opts` = `[Massstab, Schraffuren 0/1, cm 0/1,
/// Papierbereich 0/1, minX, minY, maxX, maxY]`; `text_nums`/`text_strs` = Text-Eingabe
/// (`plan_dxf::texts_from`, Texte je mit `\0` davor); `default_font` = Standard-Schrift.
#[wasm_bindgen]
pub fn plan_dxf_flat(doc: u32, segs: &[f64], text_nums: &[f64], text_strs: &str, opts: &[f64], default_font: &str) -> Vec<u8> {
let Ok([scale, hatches, cm, layout, min_x, min_y, max_x, max_y]) = <[f64; 8]>::try_from(opts) else { return Vec::new() };
if !(scale.is_finite() && scale > 0.0) {
return Vec::new();
}
let strs: Vec<&str> = text_strs.split('\0').skip(1).collect();
let Some(texts) = texts_from(text_nums, &strs) else { return Vec::new() };
let Some(held) = super::plan_buf::held_for_segs(segs) else { return Vec::new() };
let Some(mut parts) = parts_from(segs, |nr| held.iter().find(|e| e.0 == nr).map(|e| &*e.1)) else { return Vec::new() };
let o = DxfOptions {
scale,
include_hatches: hatches != 0.0,
dim_cm: cm != 0.0,
paper_layout: layout != 0.0,
bounds: [min_x, min_y, max_x, max_y],
default_font: default_font.to_string(),
};
super::document::with_doc(doc, |d| {
let p = d.project().ok()?;
collect(&mut parts, &texts, p, &o).map(|f| encode(&f))
})
.flatten()
.unwrap_or_default()
}
+1 -64
View File
@@ -1,7 +1,5 @@
import { describe, expect, it } from "vitest";
import { dashToLtypeMeters, fontNameOf, ltypeNameFor, paperFor, primitiveToLocal, roundKey } from "./dxfCadParts";
import type { LineStyle } from "../model/types";
import type { Primitive } from "../plan/generatePlan";
import { fontNameOf } from "./dxfCadParts";
describe("fontNameOf", () => {
it("erste echte Familie, ohne Anführungszeichen; generische/Variablen übersprungen", () => {
@@ -13,64 +11,3 @@ describe("fontNameOf", () => {
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<Primitive, { kind: "line" }>;
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<Primitive, { kind: "drawingText" }>;
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<Primitive, { kind: "drawingCircle" }>;
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]));
});
});
+3 -116
View File
@@ -1,9 +1,6 @@
// 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";
// Baustein des Fachplaner-Exports ([C2], 28.10.): Schriftname aus CSS-Familie (Text-Layout bleibt TS).
// Linientypen, blocklokale Primitive, Papierformate und der Sammler selbst liegen seit [K3d] im Kern
// (`src-tauri/core/src/plan_dxf.rs`).
/** 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 {
@@ -17,113 +14,3 @@ export function fontNameOf(css: string | undefined | null): string | null {
}
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_<an>_<aus>…` (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" };
}
+114 -888
View File
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -59,7 +59,7 @@ const cache = new WeakMap<object, { text: PlanParts | null; noText: PlanParts |
/**
* Abschnitte eines Plans; einmal je Plan (lazy, s. `planLazy.ts`) bzw. je `plan.primitives` (und
* Modus) gebaut. `texts`: der eigene Puffer trägt Texte/Bilder mit JSON (SVG-Export, Auswahl) —
* Modus) gebaut. `texts`: der eigene Puffer trägt Texte/Bilder und Schraffuren mit JSON (SVG-/DXF-Export, Auswahl) —
* sonst nur deren Typ (Szene). Ein lazy Plan wird dabei nicht gelesen.
*/
export function planParts(plan: Plan, texts = false): PlanParts {
@@ -82,7 +82,7 @@ export function planParts(plan: Plan, texts = false): PlanParts {
function partsFromPieces(pieces: readonly PlanPiece[], texts: boolean): PlanParts {
const rest: Primitive[] = [];
for (const pc of pieces) if (!isBufPiece(pc)) for (const p of pc) rest.push(p);
const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts, hatchJson: false }), hold: 0 } : null;
const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts, hatchJson: texts }), hold: 0 } : null;
const bufs: HoldableBuf[] = [];
const segs: number[] = [];
let ownAt = 0;
@@ -133,7 +133,7 @@ function partsFromRuns(plan: Plan, texts: boolean): PlanParts {
at = r.end;
}
gap(prims.length);
const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts, hatchJson: false }), hold: 0 } : null;
const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts, hatchJson: texts }), hold: 0 } : null;
const segs: number[] = [];
let gi = 0;
let ri = 0;