Merge [76] PDF-Import: Kreise/Boegen erkennen, Strichmuster als Linienstil, Clip-Pfade, Zwei-Punkt-Kalibrierung

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-28 16:02:13 +00:00
commit ed428261bc
18 files changed
+1782 -36

No files matched your search

+14
View File
@@ -1632,6 +1632,20 @@ export const de = {
"import.pdf.images": "{n} Bilder auf der Seite werden nicht übernommen.",
"import.pdf.note": "Linien kommen als 2D-Zeichnung (fangbar), Ebenen nach Farbe und Strichstärke. Als Rasterbild stattdessen: Werkzeug „Bild/PDF“.",
"import.pdf.loading": "PDF wird gelesen …",
"import.pdf.title": "PDF importieren",
"import.pdf.dashStyleName": "PDF-Strich {pattern} mm",
"import.pdf.cal.open": "Massstab durch Messen …",
"import.pdf.cal.close": "Messen schliessen",
"import.pdf.cal.hint": "Zwei Punkte einer bekannten Strecke anklicken (Fang an Linienpunkten, Kreismitte, Quadranten). Mausrad zoomt, Ziehen verschiebt.",
"import.pdf.cal.pick1": "Ersten Punkt anklicken",
"import.pdf.cal.pick2": "Zweiten Punkt anklicken",
"import.pdf.cal.measured": "Strecke auf dem Blatt: {mm} mm",
"import.pdf.cal.trueLength": "Wahre Länge (m)",
"import.pdf.cal.result": "ergibt Massstab 1:{scale}",
"import.pdf.cal.apply": "Massstab übernehmen",
"import.pdf.cal.reset": "Neu messen",
"import.pdf.cal.fit": "Ganze Seite",
"import.pdf.cal.canvas": "Seitenvorschau zum Messen",
"import.layouts.heading": "Papierbereich (Layouts)",
"import.layouts.model": "Modellraum (Zeichnung)",
"import.layouts.entities": "{n} Objekte",
+14
View File
@@ -1619,6 +1619,20 @@ export const en: Record<TranslationKey, string> = {
"import.pdf.images": "{n} images on the page are not imported.",
"import.pdf.note": "Lines come in as a 2D drawing (snappable), layers by colour and line weight. For a raster image instead: tool “Image/PDF”.",
"import.pdf.loading": "Reading PDF …",
"import.pdf.title": "Import PDF",
"import.pdf.dashStyleName": "PDF dash {pattern} mm",
"import.pdf.cal.open": "Set scale by measuring …",
"import.pdf.cal.close": "Close measuring",
"import.pdf.cal.hint": "Click two points of a known distance (snaps to line points, circle centres, quadrants). Wheel zooms, drag pans.",
"import.pdf.cal.pick1": "Click the first point",
"import.pdf.cal.pick2": "Click the second point",
"import.pdf.cal.measured": "Distance on the sheet: {mm} mm",
"import.pdf.cal.trueLength": "True length (m)",
"import.pdf.cal.result": "gives scale 1:{scale}",
"import.pdf.cal.apply": "Apply scale",
"import.pdf.cal.reset": "Measure again",
"import.pdf.cal.fit": "Whole page",
"import.pdf.cal.canvas": "Page preview for measuring",
"import.layouts.heading": "Paper space (layouts)",
"import.layouts.model": "Model space (drawing)",
"import.layouts.entities": "{n} objects",
+2
View File
@@ -47,6 +47,8 @@ export interface DxfImportResult {
layerLineWeights?: Record<string, number>;
/** Füllfarbe je Layer (PDF-Import [76]): gefüllte Konturen dieses Layers bekommen sie statt des Grau. */
layerFillColors?: Record<string, string>;
/** Strichmuster je Layer in Papier-mm, an/aus/an/aus (PDF-Import [76], Operator `d`) — wird zum Linienstil. */
layerDashes?: Record<string, number[]>;
/** `$INSUNITS` der Datei (0 = ohne Einheit, 4 = mm, 5 = cm, 6 = m …), roh wie gelesen. */
insUnits?: number;
/**
+4
View File
@@ -38,6 +38,8 @@ export function contoursToDrawings(
fallbackCode: string,
layerToCode: (layerName: string) => string,
fillColorOf?: (layerName: string) => string | undefined,
/** Linienstil-Id je Layer (PDF-Strichmuster [76]); `undefined` = Kategorie-Default. */
lineStyleOf?: (layerName: string) => string | undefined,
): Drawing2D[] {
const out: Drawing2D[] = [];
for (const set of sets) {
@@ -56,6 +58,8 @@ export function contoursToDrawings(
categoryCode,
geom,
};
const lineStyleId = lineStyleOf?.(layerName);
if (lineStyleId) drawing.lineStyleId = lineStyleId;
// Aus einer HATCH stammende Kontur → geschlossene, gefüllte Form. Vollton-
// Füllung als restylebarer Default (neutrales Grau); Umriss bleibt Kategorie.
if (contour.filled && geom.shape === "polyline") {
+127
View File
@@ -0,0 +1,127 @@
// [76] Zwei-Punkt-Kalibrierung und Fangindex des PDF-Imports sowie Strichmuster → Linienstil.
import { describe, expect, it } from "vitest";
import type { LineStyle } from "../model/types";
import {
buildSnapIndex,
collectSnapPoints,
formatScale,
pdfDistance,
pdfPaperMm,
pdfScaleFromDistance,
} from "./pdfCalibrate";
import { planDashLineStyles, sameDash } from "./pdfLineStyles";
import { PT_TO_MM, type PdfVectorPage, type PdfVectorPath } from "./pdfVector";
const path = (pts: [number, number][], extra: Partial<PdfVectorPath> = {}): PdfVectorPath => ({
pts: pts.map(([x, y]) => ({ x, y })),
closed: false,
stroke: "#000000",
fill: null,
evenOdd: false,
lineWidth: 1,
dash: [],
...extra,
});
const page = (paths: PdfVectorPath[]): PdfVectorPage => ({
pageCount: 1,
pageIndex: 0,
width: 600,
height: 400,
mediaBox: [0, 0, 600, 400],
cropBox: [0, 0, 600, 400],
rotate: 0,
truncated: false,
images: 0,
paths,
texts: [],
});
describe("Kalibrierung", () => {
it("rechnet aus Strecke und wahrer Länge den Massstab", () => {
// 100 pt = 35.2778 mm Papier; 3.527778 m wahr → 1:100
const a = { x: 10, y: 10 };
const b = { x: 110, y: 10 };
expect(pdfDistance(a, b)).toBe(100);
expect(pdfPaperMm(a, b)).toBeCloseTo(100 * PT_TO_MM, 9);
expect(pdfScaleFromDistance(a, b, (100 * PT_TO_MM * 100) / 1000)).toBeCloseTo(100, 9);
// schiefe Strecke 3-4-5: 500 pt
const s = pdfScaleFromDistance({ x: 0, y: 0 }, { x: 300, y: 400 }, 17.64);
expect(s).toBeCloseTo((17.64 * 1000) / (500 * PT_TO_MM), 9);
expect(formatScale(98.7123)).toBe("98.71");
expect(formatScale(100)).toBe("100");
});
it("verwirft Nulllänge und unsinnige Eingaben", () => {
const a = { x: 5, y: 5 };
expect(pdfScaleFromDistance(a, a, 10)).toBeNull();
expect(pdfScaleFromDistance(a, { x: 6, y: 5 }, 0)).toBeNull();
expect(pdfScaleFromDistance(a, { x: 6, y: 5 }, -3)).toBeNull();
expect(pdfScaleFromDistance(a, { x: 6, y: 5 }, Number.NaN)).toBeNull();
expect(pdfScaleFromDistance(a, { x: Number.NaN, y: 5 }, 3)).toBeNull();
});
});
describe("Fangindex", () => {
const circle: PdfVectorPath = path(
[
[140, 100],
[100, 140],
[60, 100],
[100, 60],
],
{ closed: true, curve: { kind: "circle", cx: 100, cy: 100, r: 40, a0: 0, a1: 2 * Math.PI } },
);
const p = page([path([[10, 10], [200, 10]]), path([[200, 10], [200, 300]]), circle]);
it("sammelt Ecken, Kreismitte und Quadranten", () => {
const { xs } = collectSnapPoints(p);
expect(xs.length).toBe(2 + 2 + 4 + 5);
});
it("findet den nächsten Punkt im Radius, sonst nichts", () => {
const idx = buildSnapIndex(p);
expect(idx.nearest(11, 9, 3)).toEqual({ x: 10, y: 10 });
expect(idx.nearest(199.5, 299, 3)).toEqual({ x: 200, y: 300 });
expect(idx.nearest(101, 99, 3)).toEqual({ x: 100, y: 100 }); // Kreismitte
expect(idx.nearest(300, 200, 3)).toBeNull();
expect(idx.nearest(11, 9, 0)).toBeNull();
});
it("kommt mit leerer Seite und Punkten ausserhalb der Seite zurecht", () => {
expect(buildSnapIndex(page([])).nearest(1, 1, 5)).toBeNull();
const out = buildSnapIndex(page([path([[-50, -50], [900, 900]])]));
expect(out.nearest(-49, -49, 5)).toEqual({ x: -50, y: -50 });
expect(out.nearest(899, 901, 5)).toEqual({ x: 900, y: 900 });
});
});
describe("Strichmuster → Linienstil", () => {
const solid: LineStyle = { id: "thin", name: "Volllinie", weight: 0.13, color: "#111", dash: null };
const dashed: LineStyle = { id: "d", name: "Strich", weight: 0.02, color: "#111", dash: [1, 0.7] };
it("vergleicht mit Toleranz", () => {
expect(sameDash([1.05, 0.7], [1, 0.7])).toBe(true);
expect(sameDash([3, 1], [1, 3])).toBe(false);
expect(sameDash([1, 1], [1, 1, 1, 1])).toBe(false);
});
it("nimmt vorhandenen Stil mit gleichem Muster, legt sonst genau einen neuen an", () => {
const plan = planDashLineStyles(
{ a: [1.05, 0.7], b: [2.8, 1.4], c: [2.8, 1.4], d: [0.05, 0.7, 2.8, 0.7] },
[solid, dashed],
);
expect(plan.styleByLayer.get("a")).toBe("d");
expect(plan.created).toHaveLength(2);
expect(plan.styleByLayer.get("b")).toBe(plan.styleByLayer.get("c"));
const made = plan.created[0];
expect(made).toMatchObject({ dash: [2.8, 1.4], weight: 0.02 });
expect(made.id).toBe("pdf-dash-2_8_1_4");
expect(plan.created[1].dash).toEqual([0.05, 0.7, 2.8, 0.7]);
});
it("ohne Muster nichts", () => {
expect(planDashLineStyles(undefined, [solid])).toEqual({ created: [], styleByLayer: new Map() });
});
});
+128
View File
@@ -0,0 +1,128 @@
// Zwei-Punkt-Kalibrierung des PDF-Imports ([76]): Massstab aus einer gemessenen Strecke, Fangindex
// über die gelesenen Pfadpunkte der Seite. Reine Rechnung ohne UI (Dialog: `ui/PdfCalibrate.tsx`).
//
// Alle Koordinaten in PDF-pt der angezeigten Seite (Ursprung links unten, y nach oben).
import type { PdfVectorPage } from "./pdfVector";
import { PT_TO_MM } from "./pdfVector";
export interface Pt {
x: number;
y: number;
}
/** Abstand zweier Punkte. */
export function pdfDistance(a: Pt, b: Pt): number {
return Math.hypot(b.x - a.x, b.y - a.y);
}
/** Länge der gemessenen Strecke auf dem Blatt in Papier-mm. */
export function pdfPaperMm(a: Pt, b: Pt): number {
return pdfDistance(a, b) * PT_TO_MM;
}
/**
* Massstabszahl (1:n), bei der die Strecke a–b im Modell `trueLengthM` Meter misst.
* `null` bei Nulllänge oder unsinnigen Eingaben.
*/
export function pdfScaleFromDistance(a: Pt, b: Pt, trueLengthM: number): number | null {
const mm = pdfPaperMm(a, b);
if (!(mm > 1e-9) || !Number.isFinite(mm) || !(trueLengthM > 0) || !Number.isFinite(trueLengthM)) return null;
const n = (trueLengthM * 1000) / mm;
return Number.isFinite(n) && n > 0 ? n : null;
}
/** Massstabszahl für die Anzeige („98.7", „100"): auf 0.01 gerundet, ohne Nullen. */
export function formatScale(n: number): string {
return String(Math.round(n * 100) / 100);
}
/** Höchstzahl Fangpunkte (Schutz gegen riesige Seiten). */
const MAX_SNAP_POINTS = 2_000_000;
/** Räumlicher Index der Pfadpunkte: Gitter (CSR), Abfrage nach nächstem Punkt im Radius. */
export interface SnapIndex {
count: number;
nearest(x: number, y: number, radius: number): Pt | null;
}
/**
* Fangpunkte einer Seite: alle Pfadpunkte (Ecken), bei erkannten Kreisen/Bögen zusätzlich Mittelpunkt
* und Quadranten (bzw. Endpunkte), damit sich auch an runden Bauteilen messen lässt.
*/
export function collectSnapPoints(page: PdfVectorPage): { xs: Float64Array; ys: Float64Array } {
let n = 0;
for (const p of page.paths) n += p.pts.length + (p.curve ? 5 : 0);
n = Math.min(n, MAX_SNAP_POINTS);
const xs = new Float64Array(n);
const ys = new Float64Array(n);
let i = 0;
const add = (x: number, y: number) => {
if (i < n && Number.isFinite(x) && Number.isFinite(y)) {
xs[i] = x;
ys[i++] = y;
}
};
for (const p of page.paths) {
for (const q of p.pts) add(q.x, q.y);
const c = p.curve;
if (c) {
add(c.cx, c.cy);
if (c.kind === "circle") {
add(c.cx + c.r, c.cy);
add(c.cx, c.cy + c.r);
add(c.cx - c.r, c.cy);
add(c.cx, c.cy - c.r);
} else {
add(c.cx + c.r * Math.cos(c.a0), c.cy + c.r * Math.sin(c.a0));
add(c.cx + c.r * Math.cos(c.a1), c.cy + c.r * Math.sin(c.a1));
}
}
}
return { xs: xs.subarray(0, i), ys: ys.subarray(0, i) };
}
export function buildSnapIndex(page: PdfVectorPage): SnapIndex {
const { xs, ys } = collectSnapPoints(page);
const n = xs.length;
const w = Math.max(page.width, 1);
const h = Math.max(page.height, 1);
// ≈ 1 Punkt je Zelle im Mittel, höchstens 512 × 512 Zellen.
const cells = Math.max(1, Math.min(512, Math.round(Math.sqrt(n / 2)) || 1));
const cw = w / cells;
const ch = h / cells;
const cellX = (x: number) => Math.min(cells - 1, Math.max(0, Math.floor(x / cw)));
const cellY = (y: number) => Math.min(cells - 1, Math.max(0, Math.floor(y / ch)));
const start = new Int32Array(cells * cells + 1);
for (let k = 0; k < n; k++) start[cellY(ys[k]) * cells + cellX(xs[k]) + 1]++;
for (let c = 0; c < cells * cells; c++) start[c + 1] += start[c];
const fill = start.slice(0, cells * cells);
const items = new Int32Array(n);
for (let k = 0; k < n; k++) items[fill[cellY(ys[k]) * cells + cellX(xs[k])]++] = k;
return {
count: n,
nearest(x, y, radius) {
if (n === 0 || !(radius > 0)) return null;
const x0 = cellX(x - radius);
const x1 = cellX(x + radius);
const y0 = cellY(y - radius);
const y1 = cellY(y + radius);
let best = -1;
let bestD = radius * radius;
for (let cy = y0; cy <= y1; cy++) {
for (let cx = x0; cx <= x1; cx++) {
const c = cy * cells + cx;
for (let q = start[c]; q < start[c + 1]; q++) {
const k = items[q];
const d = (xs[k] - x) ** 2 + (ys[k] - y) ** 2;
if (d <= bestD) {
bestD = d;
best = k;
}
}
}
}
return best < 0 ? null : { x: xs[best], y: ys[best] };
},
};
}
+55
View File
@@ -0,0 +1,55 @@
// PDF-Strichmuster → Linienstile ([76], Operator `d`). Der PDF-Import liefert je Ebene ein Muster in
// Papier-mm (`DxfImportResult.layerDashes`); hier wird es einem vorhandenen Linienstil mit gleichem
// Muster zugeordnet oder als neuer Strichmuster-Stil angelegt. Ohne Änderung am Modell: ein
// `LineStyle` mit `dash` (mm Papier, an/aus/an/aus) ist schon vorgesehen, das Drawing2D trägt
// `lineStyleId`. Das Muster hängt nicht vom Plan-Massstab ab (Papier-mm wie im PDF).
import type { LineStyle } from "../model/types";
import { t } from "../i18n";
import { pdfDashLabel } from "./pdfVector";
/** Relative bzw. absolute (mm) Toleranz beim Vergleich zweier Muster. */
const REL_TOL = 0.15;
const ABS_TOL = 0.06;
/** Gleiches Muster (gleiche Länge, jedes Glied innerhalb der Toleranz)? */
export function sameDash(a: readonly number[], b: readonly number[]): boolean {
return a.length === b.length && a.every((v, i) => Math.abs(v - b[i]) <= Math.max(ABS_TOL, REL_TOL * Math.max(v, b[i])));
}
export interface DashStylePlan {
/** Neu anzulegende Linienstile (am Projekt anhängen, bevor die Zeichnungen verweisen). */
created: LineStyle[];
/** Ebenenname → Linienstil-Id (vorhanden oder neu). */
styleByLayer: Map<string, string>;
}
/** Ordnet jedem Muster einen Linienstil zu; gleiche Muster teilen sich einen. */
export function planDashLineStyles(
layerDashes: Readonly<Record<string, number[]>> | undefined,
existing: readonly LineStyle[],
): DashStylePlan {
const created: LineStyle[] = [];
const styleByLayer = new Map<string, string>();
if (!layerDashes) return { created, styleByLayer };
const usedIds = new Set(existing.map((l) => l.id));
for (const [layer, dash] of Object.entries(layerDashes)) {
if (dash.length < 2) continue;
const known = [...existing, ...created].find(
(l) => (l.kind ?? "dash") === "dash" && l.dash !== null && sameDash(l.dash, dash),
);
if (known) {
styleByLayer.set(layer, known.id);
continue;
}
const label = pdfDashLabel(dash);
const base = `pdf-dash-${label.replace(/[^0-9a-z]+/gi, "_")}`;
let id = base;
for (let n = 2; usedIds.has(id); n++) id = `${base}-${n}`;
usedIds.add(id);
// Haarlinien-Default wie bei neuen Linienstilen; Strichstärke und Farbe kommen von der Ebene.
created.push({ id, name: t("import.pdf.dashStyleName", { pattern: label }), weight: 0.02, color: "#1a1a1a", dash: [...dash] });
styleByLayer.set(layer, id);
}
return { created, styleByLayer };
}
+48 -2
View File
@@ -67,12 +67,12 @@ describe("Vektor-PDF-Import", () => {
const k = pdfMetersPerPt(100);
expect(k).toBeCloseTo(0.0352778, 6);
const layers = distinctImportLayers(res.contours, res.texts ?? []).sort();
expect(layers).toEqual(["PDF 0.18 #ff0000 (- -)", "PDF 0.50 #000000", "PDF Fläche #808080", "PDF Text #000000"]);
expect(layers).toEqual(["PDF 0.18 #ff0000 (Strich 1.05/0.7)", "PDF 0.50 #000000", "PDF Fläche #808080", "PDF Text #000000"]);
expect(res.layerLineWeights?.["PDF 0.50 #000000"]).toBe(0.5);
expect(pdfLineWeightMm(0.5)).toBe(0.18);
const plan = planImportCategories(layers, [], "Import plan.pdf", res.layerColors, res.layerLineWeights);
const cat = plan.parent?.children?.find((c) => c.name === "PDF 0.18 #ff0000 (- -)");
const cat = plan.parent?.children?.find((c) => c.name === "PDF 0.18 #ff0000 (Strich 1.05/0.7)");
expect(cat).toMatchObject({ color: "#ff0000", lw: 0.18 });
const code = (l: string) => plan.codeByLayer.get(l) ?? "00";
const drawings = contoursToDrawings(res.contours, "eg", "byLayer", "00", code, (l) => res.layerFillColors?.[l]);
@@ -84,6 +84,12 @@ describe("Vektor-PDF-Import", () => {
expect(line.a.x).toBeCloseTo(72 * k, 9);
expect(line.b.x - line.a.x).toBeCloseTo(3.527778, 5); // 100 pt = 35.28 mm Papier = 3.53 m bei 1:100
}
// Strichmuster → Linienstil: nur die gestrichelte Ebene bekommt eine lineStyleId.
const styled = contoursToDrawings(res.contours, "eg", "byLayer", "00", code, undefined, (l) =>
res.layerDashes?.[l] ? "pdf-dash" : undefined,
);
expect(styled.filter((d) => d.lineStyleId === "pdf-dash")).toHaveLength(1);
expect(res.layerDashes?.["PDF 0.18 #ff0000 (Strich 1.05/0.7)"]).toEqual([1.05, 0.7]);
const fill = drawings.find((d) => d.fillColor);
expect(fill?.fillColor).toBe("#808080");
const texts = textsToDrawings(res.texts ?? [], "eg", "byLayer", "00", code);
@@ -114,4 +120,44 @@ describe("Vektor-PDF-Import", () => {
expect(isPdfFile("x.bin", good)).toBe(true);
expect(isPdfFile("x.dxf")).toBe(false);
});
it("Kreis und Bogen aus Bézier-Folgen kommen als echte Kurven (Fang an Mitte/Quadrant)", () => {
const k = 0.5522847498 * 40;
const [cx, cy, r] = [200, 300, 40];
const circle =
`${cx + r} ${cy} m ${cx + r} ${cy + k} ${cx + k} ${cy + r} ${cx} ${cy + r} c ` +
`${cx - k} ${cy + r} ${cx - r} ${cy + k} ${cx - r} ${cy} c ` +
`${cx - r} ${cy - k} ${cx - k} ${cy - r} ${cx} ${cy - r} c ` +
`${cx + k} ${cy - r} ${cx + r} ${cy - k} ${cx + r} ${cy} c h S `;
const arc = `100 100 m 100 ${100 + k} ${60 + k} 140 60 140 c S`; // Viertelbogen um (60,100), r 40
const page = readPdfVectorPage(makePdf(circle + arc));
expect(page.paths).toHaveLength(2);
expect(page.paths[0].curve).toMatchObject({ kind: "circle" });
expect(page.paths[0].curve?.cx).toBeCloseTo(cx, 3);
expect(page.paths[0].curve?.r).toBeCloseTo(r, 3);
expect(page.paths[1].curve).toMatchObject({ kind: "arc" });
expect(page.paths[1].curve?.a1).toBeCloseTo(Math.PI / 2, 3);
const res = pdfPageToImport(page, 100);
const m = pdfMetersPerPt(100);
const contours = res.contours[0].contours;
expect(contours[0].curve).toMatchObject({ kind: "circle" });
expect(contours[0].curve?.cx).toBeCloseTo(cx * m, 9);
expect(contours[0].curve?.r).toBeCloseTo(r * m, 9);
const drawings = contoursToDrawings(res.contours, "eg", "active", "00", () => "00");
expect(drawings[0].geom).toMatchObject({ shape: "circle" });
expect(drawings[1].geom).toMatchObject({ shape: "arc" });
});
it("Strichmuster: Muster in Papier-mm je Ebene, Clip-Rechteck beschneidet", () => {
const page = readPdfVectorPage(
makePdf("50 50 100 100 re W n 1 0 0 RG [8 4] 0 d 0 100 m 300 100 l S"),
);
expect(page.paths).toHaveLength(1);
expect(page.paths[0].pts).toEqual([{ x: 50, y: 100 }, { x: 150, y: 100 }]);
const res = pdfPageToImport(page, 50);
const layer = Object.keys(res.layerDashes ?? {})[0];
expect(layer).toMatch(/Strich 2\.8\/1\.4/);
expect(res.layerDashes?.[layer]).toEqual([2.8, 1.4]);
});
});
+45 -6
View File
@@ -6,7 +6,9 @@
// und damit auch Fangziele (anders als die gerasterte PDF-Unterlage aus `pdfImport.ts`, die bleibt).
//
// Ebenen: gruppiert nach Strichstärke (Papier-mm) und Farbe, z. B. „PDF 0.35 #000000"; gestrichelte
// Linien mit „(- -)"; Flächen als „PDF Fläche #rrggbb" (Füllfarbe), Texte als „PDF Text #rrggbb".
// Linien mit Muster in Papier-mm, z. B. „PDF 0.18 #ff0000 (Strich 0.9/0.6)" (daraus wird beim Import
// ein Linienstil, s. `pdfLineStyles.ts`); Flächen als „PDF Fläche #rrggbb" (Füllfarbe), Texte als
// „PDF Text #rrggbb". Kreise/Bögen aus Bézier-Folgen kommen als echte Kurven (`Contour.curve`) an.
// Massstab: 1 pt = 25.4/72 mm Papier; Modell-Meter = pt × 25.4/72/1000 × Massstabszahl.
import type { Contour, ContourSet, ImportedText } from "../model/types";
@@ -20,6 +22,16 @@ export const PT_TO_MM = 25.4 / 72;
/** Gängige Massstäbe für den Import-Dialog. */
export const PDF_SCALES = [1, 20, 50, 100, 200, 500, 1000] as const;
/** Kreis oder Kreisbogen (pt, Radiant, CCW von `a0` nach `a1`), von Rust aus Bézier-Folgen erkannt. */
export interface PdfVectorCurve {
kind: "circle" | "arc";
cx: number;
cy: number;
r: number;
a0: number;
a1: number;
}
export interface PdfVectorPath {
/** Punkte in pt (angezeigte Seite, y nach oben). */
pts: { x: number; y: number }[];
@@ -31,8 +43,10 @@ export interface PdfVectorPath {
evenOdd: boolean;
/** Linienbreite in pt (0 = Haarlinie). */
lineWidth: number;
/** Strichmuster in pt (leer = durchgezogen). */
/** Strichmuster in pt (leer = durchgezogen, sonst gerade Länge: an/aus/an/aus …). */
dash: number[];
/** Erkannter Kreis/Bogen; `pts` bleibt das tessellierte Vieleck. */
curve?: PdfVectorCurve;
}
export interface PdfVectorText {
@@ -93,7 +107,7 @@ export function decodePdfPage(geom: Float64Array, strings: readonly string[]): P
let i = 0;
const num = () => geom[i++];
const str = () => strings[geom[i++]] ?? "";
if (num() !== 1) throw new Error("Unbekanntes PDF-Importformat (Version).");
if (num() !== 2) throw new Error("Unbekanntes PDF-Importformat (Version).");
const pageCount = num();
const pageIndex = num();
const width = num();
@@ -116,6 +130,11 @@ export function decodePdfPage(geom: Float64Array, strings: readonly string[]): P
const pts = new Array(np);
for (let p = 0; p < np; p++) pts[p] = { x: geom[i + 2 * p], y: geom[i + 2 * p + 1] };
i += 2 * np;
let curve: PdfVectorCurve | undefined;
if (flags & 16) {
curve = { kind: flags & 32 ? "circle" : "arc", cx: geom[i], cy: geom[i + 1], r: geom[i + 2], a0: geom[i + 3], a1: geom[i + 4] };
i += 5;
}
paths.push({
pts,
closed: (flags & 1) !== 0,
@@ -124,6 +143,7 @@ export function decodePdfPage(geom: Float64Array, strings: readonly string[]): P
evenOdd: (flags & 8) !== 0,
lineWidth,
dash,
...(curve ? { curve } : {}),
});
}
const texts: PdfVectorText[] = [];
@@ -145,10 +165,21 @@ export function pdfLineWeightMm(lineWidthPt: number): number {
return Math.round(lineWidthPt * PT_TO_MM * 100) / 100;
}
/** Ebenenname einer gestrichenen Linie (Stärke + Farbe, gestrichelt markiert). */
/** Strichmuster in Papier-mm (an/aus/an/aus …), auf 0.05 mm gerundet; Punkte (an = 0) bleiben 0. */
export function pdfDashMm(dashPt: readonly number[]): number[] {
return dashPt.map((d) => Math.round((d * PT_TO_MM) / 0.05) * 0.05).map((d) => Math.round(d * 100) / 100);
}
/** Kurzschrift eines Strichmusters für Ebenen-/Stilnamen: „0.9/0.6". */
export function pdfDashLabel(dashMm: readonly number[]): string {
return dashMm.map((d) => String(Math.round(d * 100) / 100)).join("/");
}
/** Ebenenname einer gestrichenen Linie (Stärke + Farbe, ggf. Strichmuster in Papier-mm). */
export function pdfStrokeLayer(p: Pick<PdfVectorPath, "lineWidth" | "stroke" | "dash">): string {
const lw = pdfLineWeightMm(p.lineWidth).toFixed(2);
return `PDF ${lw} ${p.stroke ?? "#000000"}${p.dash.length ? " (- -)" : ""}`;
const dash = p.dash.length ? ` (Strich ${pdfDashLabel(pdfDashMm(p.dash))})` : "";
return `PDF ${lw} ${p.stroke ?? "#000000"}${dash}`;
}
export interface PdfImportOptions {
@@ -167,6 +198,7 @@ export function pdfPageToImport(page: PdfVectorPage, scale: number, opts: PdfImp
const layerColors: Record<string, string> = {};
const layerLineWeights: Record<string, number> = {};
const layerFillColors: Record<string, string> = {};
const layerDashes: Record<string, number[]> = {};
const contours: Contour[] = [];
const pageArea = page.width * page.height;
const counts: Record<string, number> = {};
@@ -184,7 +216,13 @@ export function pdfPageToImport(page: PdfVectorPage, scale: number, opts: PdfImp
const layer = pdfStrokeLayer(p);
layerColors[layer] = p.stroke;
layerLineWeights[layer] = Math.max(0.05, pdfLineWeightMm(p.lineWidth));
contours.push({ z: 0, pts: toM(p.pts), closed: p.closed, layer });
if (p.dash.length) layerDashes[layer] ??= pdfDashMm(p.dash);
const contour: Contour = { z: 0, pts: toM(p.pts), closed: p.closed, layer };
if (p.curve) {
const c = p.curve;
contour.curve = { kind: c.kind, cx: c.cx * k, cy: c.cy * k, r: c.r * k, a0: c.a0, a1: c.a1 };
}
contours.push(contour);
counts.stroke = (counts.stroke ?? 0) + 1;
}
}
@@ -214,6 +252,7 @@ export function pdfPageToImport(page: PdfVectorPage, scale: number, opts: PdfImp
layerColors,
layerLineWeights,
layerFillColors,
layerDashes,
diagnostics: {
entityCounts: { PATH: counts.stroke ?? 0, FILL: counts.fill ?? 0, TEXT: texts.length, IMAGE: page.images },
total: page.paths.length + page.texts.length,
+12
View File
@@ -21,6 +21,7 @@ import { buildDrawings } from "../ui/ImportDialog";
import { distinctImportLayers, planImportCategories } from "../io/dxfToDrawings";
import type { ImportDecision, PdfImportOptions } from "../ui/ImportDialog";
import { isPdfFile, pdfPageToImport, readPdfVectorPage } from "../io/pdfVector";
import { planDashLineStyles } from "../io/pdfLineStyles";
import type { PdfVectorPage } from "../io/pdfVector";
import { exportScheduleCsv } from "../export/exportSchedule";
import { exportIfcSpf } from "../export/exportIfc";
@@ -297,6 +298,7 @@ export function useProjectFileActions(
widthPt: page.width,
heightPt: page.height,
images: page.images,
preview: page,
},
});
@@ -693,12 +695,22 @@ export function useProjectFileActions(
setProject((p) => ({ ...p, layers: [...p.layers, parent] }));
}
}
// PDF-Strichmuster ([76]): passenden Linienstil nehmen oder Strichmuster-Stil anlegen (vor den Zeichnungen).
const dashPlan = planDashLineStyles(decision.parsed.layerDashes, project.lineStyles);
if (dashPlan.created.length) {
const created = dashPlan.created;
setProject((p) => ({
...p,
lineStyles: [...p.lineStyles, ...created.filter((c) => !p.lineStyles.some((l) => l.id === c.id))],
}));
}
let drawings = buildDrawings(
decision,
levelId,
project,
activeCategoryCode,
codeByLayer,
dashPlan.styleByLayer,
);
// Platzierung „viewCenter": den Gesamt-Umriss so verschieben, dass seine
// Mitte auf die Mitte des aktuellen Ausschnitts fällt (sonst bleibt alles an
+36
View File
@@ -8462,3 +8462,39 @@ body {
font-size: 12px;
color: var(--ink-2);
}
/* PDF-Import: Zwei-Punkt-Kalibrierung ([76]) */
.imp-cal {
display: flex;
flex-direction: column;
gap: 7px;
}
.imp-cal-canvas {
display: block;
border: 1px solid var(--border);
border-radius: 7px;
cursor: crosshair;
touch-action: none;
}
.imp-cal-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.imp-cal-row .imp-note {
flex: 1 1 auto;
}
.imp-cal-small {
padding: 4px 12px;
font-size: 12px;
}
.imp-cal-toggle {
align-self: flex-start;
padding: 5px 14px;
font-size: 12px;
}
.imp-cal-len {
flex: 0 0 9em;
width: 9em;
}
+22 -2
View File
@@ -29,6 +29,8 @@ import {
import type { CategoryMode } from "../io/dxfToDrawings";
import { Dropdown } from "./Dropdown";
import { PDF_SCALES, PT_TO_MM } from "../io/pdfVector";
import type { PdfVectorPage } from "../io/pdfVector";
import { PdfCalibrate } from "./PdfCalibrate";
/** Vektor-PDF ([76]): Seite und Massstab, nach denen `parsed` aus dem PDF abgeleitet wurde. */
export interface PdfImportOptions {
@@ -42,6 +44,8 @@ export interface PdfImportOptions {
heightPt: number;
/** Bilder auf der Seite (werden nicht übernommen). */
images: number;
/** Die gelesene Seite — Vorschau und Fangpunkte der Zwei-Punkt-Kalibrierung. */
preview: PdfVectorPage;
}
/** Strukturierte Import-Entscheidung, die der Dialog beim Bestätigen liefert. */
@@ -197,6 +201,8 @@ export function ImportDialog({
const [applying, setApplying] = useState(false);
// Freier PDF-Massstab (Texteingabe „1:75" oder „75"), angewandt bei Enter/Verlassen.
const [customScaleText, setCustomScaleText] = useState("");
// Zwei-Punkt-Kalibrierung ([76]) aufgeklappt?
const [calibrating, setCalibrating] = useState(false);
const applyCustomScale = () => {
const n = Number(customScaleText.trim().replace(/^1\s*:\s*/, ""));
if (pdf && onPdfChange && Number.isFinite(n) && n > 0) onPdfChange(pdf.page, n);
@@ -226,11 +232,11 @@ export function ImportDialog({
className="imp-dialog"
role="dialog"
aria-modal="true"
aria-label={t("import.title")}
aria-label={pdf ? t("import.pdf.title") : t("import.title")}
onClick={(e) => e.stopPropagation()}
>
<header className="imp-head">
<span className="imp-head-title">{t("import.title")}</span>
<span className="imp-head-title">{pdf ? t("import.pdf.title") : t("import.title")}</span>
<button
className="imp-close"
onClick={onClose}
@@ -359,6 +365,18 @@ export function ImportDialog({
}}
/>
</div>
<button className="imp-btn imp-cal-toggle" onClick={() => setCalibrating((o) => !o)} aria-expanded={calibrating}>
{calibrating ? t("import.pdf.cal.close") : t("import.pdf.cal.open")}
</button>
{calibrating && (
<PdfCalibrate
page={pdf.preview}
onApply={(n) => {
setCalibrating(false);
onPdfChange(pdf.page, n);
}}
/>
)}
<div className="imp-note">
{t("import.pdf.size", {
w: Math.round(pdf.widthPt * PT_TO_MM),
@@ -559,6 +577,7 @@ export function buildDrawings(
project: Project,
activeCategoryCode: string,
codeByLayer?: ReadonlyMap<string, string>,
lineStyleByLayer?: ReadonlyMap<string, string>,
) {
// Layer-Name → Kategorie-Code: bevorzugt eine Kategorie mit demselben Namen
// (case-insensitiv), sonst der aktive Code. Identifier bleiben so stabil.
@@ -582,6 +601,7 @@ export function buildDrawings(
activeCategoryCode,
layerToCode,
fillColors ? (layer) => fillColors[layer] : undefined,
lineStyleByLayer ? (layer) => lineStyleByLayer.get(layer) : undefined,
);
const fromTexts = textsToDrawings(
decision.parsed.texts ?? [],
+300
View File
@@ -0,0 +1,300 @@
// Zwei-Punkt-Kalibrierung im PDF-Import-Dialog ([76]): Vorschau der gelesenen Pfade auf einem Canvas,
// zwei Punkte anklicken (Fang an Pfadpunkten, Kreismitten, Quadranten), wahre Länge eingeben → Massstab.
// Rechnung und Fangindex: `io/pdfCalibrate.ts`. Mausrad zoomt um den Zeiger, Ziehen verschiebt.
import { useEffect, useMemo, useRef, useState } from "react";
import { t } from "../i18n";
import type { PdfVectorPage } from "../io/pdfVector";
import { buildSnapIndex, formatScale, pdfPaperMm, pdfScaleFromDistance } from "../io/pdfCalibrate";
import type { Pt } from "../io/pdfCalibrate";
const HEIGHT = 280;
const SNAP_PX = 10;
const DRAG_PX = 4;
interface View {
/** Seitenpunkt (pt) in der Mitte der Fläche. */
cx: number;
cy: number;
/** Bildschirm-Pixel je pt. */
zoom: number;
}
/** Fast weisse Striche auf dem Papier-Hintergrund sichtbar halten. */
function visibleStroke(c: string): string {
const v = parseInt(c.slice(1), 16);
const [r, g, b] = [(v >> 16) & 255, (v >> 8) & 255, v & 255];
return r + g + b > 690 ? "#b8b8b8" : c;
}
interface Layers {
strokes: [string, Path2D][];
fills: [string, Path2D][];
}
function buildLayers(page: PdfVectorPage): Layers {
const strokes = new Map<string, Path2D>();
const fills = new Map<string, Path2D>();
const trace = (path: Path2D, pts: { x: number; y: number }[], closed: boolean) => {
path.moveTo(pts[0].x, pts[0].y);
for (let i = 1; i < pts.length; i++) path.lineTo(pts[i].x, pts[i].y);
if (closed) path.closePath();
};
for (const p of page.paths) {
if (p.pts.length < 2) continue;
if (p.fill && p.closed) {
// Weisse Seitenhintergründe nicht über die Linien malen.
if (p.fill === "#ffffff") continue;
const g = fills.get(p.fill) ?? new Path2D();
fills.set(p.fill, g);
trace(g, p.pts, true);
}
if (p.stroke) {
const c = visibleStroke(p.stroke);
const g = strokes.get(c) ?? new Path2D();
strokes.set(c, g);
trace(g, p.pts, p.closed);
}
}
return { strokes: [...strokes], fills: [...fills] };
}
function fitView(page: PdfVectorPage, w: number): View {
const zoom = Math.min(w / page.width, HEIGHT / page.height) * 0.96;
return { cx: page.width / 2, cy: page.height / 2, zoom: Math.max(zoom, 1e-6) };
}
export interface PdfCalibrateProps {
page: PdfVectorPage;
/** Berechnete Massstabszahl übernehmen. */
onApply: (scale: number) => void;
}
export function PdfCalibrate({ page, onApply }: PdfCalibrateProps) {
const wrapRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const [width, setWidth] = useState(480);
const [view, setView] = useState<View>(() => fitView(page, 480));
const [pts, setPts] = useState<Pt[]>([]);
const [hover, setHover] = useState<{ p: Pt; snapped: boolean } | null>(null);
const [lenText, setLenText] = useState("");
const drag = useRef<{ x: number; y: number; view: View; moved: boolean } | null>(null);
const layers = useMemo(() => buildLayers(page), [page]);
const index = useMemo(() => buildSnapIndex(page), [page]);
// Breite der Fläche folgen; beim ersten Mass die Seite einpassen.
useEffect(() => {
const el = wrapRef.current;
if (!el) return;
const apply = () => {
const w = Math.max(200, Math.floor(el.clientWidth));
setWidth((old) => {
if (old !== w) setView(fitView(page, w));
return w;
});
};
apply();
if (typeof ResizeObserver === "undefined") return;
const ro = new ResizeObserver(apply);
ro.observe(el);
return () => ro.disconnect();
}, [page]);
// Neue Seite: Messung und Ansicht zurücksetzen.
useEffect(() => {
setPts([]);
setHover(null);
setView(fitView(page, width));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [page]);
const toPage = (sx: number, sy: number): Pt => ({
x: view.cx + (sx - width / 2) / view.zoom,
y: view.cy - (sy - HEIGHT / 2) / view.zoom,
});
const toScreen = (p: Pt): [number, number] => [width / 2 + (p.x - view.cx) * view.zoom, HEIGHT / 2 - (p.y - view.cy) * view.zoom];
// Zeichnen.
useEffect(() => {
const canvas = canvasRef.current;
const ctx = canvas?.getContext("2d");
if (!canvas || !ctx) return;
const dpr = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(HEIGHT * dpr);
const css = getComputedStyle(canvas);
const accent = css.getPropertyValue("--accent").trim() || "#c2410c";
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.fillStyle = css.getPropertyValue("--panel-2").trim() || "#d4cfc8";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Seitenraum: y nach oben.
ctx.setTransform(dpr * view.zoom, 0, 0, -dpr * view.zoom, dpr * (width / 2 - view.cx * view.zoom), dpr * (HEIGHT / 2 + view.cy * view.zoom));
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, page.width, page.height);
ctx.globalAlpha = 0.3;
for (const [c, path] of layers.fills) {
ctx.fillStyle = c;
ctx.fill(path);
}
ctx.globalAlpha = 1;
ctx.lineWidth = 1 / view.zoom;
ctx.lineJoin = "round";
for (const [c, path] of layers.strokes) {
ctx.strokeStyle = c;
ctx.stroke(path);
}
// Messung im Bildschirmraum.
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.lineWidth = 1.5;
ctx.strokeStyle = accent;
ctx.fillStyle = accent;
if (pts.length === 2) {
const [x0, y0] = toScreen(pts[0]);
const [x1, y1] = toScreen(pts[1]);
ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.lineTo(x1, y1);
ctx.stroke();
}
for (const p of pts) {
const [x, y] = toScreen(p);
ctx.beginPath();
ctx.arc(x, y, 4, 0, Math.PI * 2);
ctx.fill();
}
if (hover && pts.length < 2) {
const [x, y] = toScreen(hover.p);
ctx.strokeStyle = hover.snapped ? "#16a34a" : accent;
ctx.lineWidth = 2;
ctx.strokeRect(x - 5, y - 5, 10, 10);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [page, layers, view, pts, hover, width]);
// Mausrad zoomt um den Zeiger (nicht-passiver Listener, damit die Seite nicht mitscrollt).
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const onWheel = (e: WheelEvent) => {
e.preventDefault();
const r = canvas.getBoundingClientRect();
const sx = e.clientX - r.left;
const sy = e.clientY - r.top;
setView((v) => {
const f = Math.exp(-e.deltaY * 0.0015);
const fit = fitView(page, width).zoom;
const zoom = Math.min(fit * 600, Math.max(fit * 0.5, v.zoom * f));
// Der Seitenpunkt unter dem Zeiger bleibt stehen.
const px = v.cx + (sx - width / 2) / v.zoom;
const py = v.cy - (sy - HEIGHT / 2) / v.zoom;
return { zoom, cx: px - (sx - width / 2) / zoom, cy: py + (sy - HEIGHT / 2) / zoom };
});
};
canvas.addEventListener("wheel", onWheel, { passive: false });
return () => canvas.removeEventListener("wheel", onWheel);
}, [page, width]);
const local = (e: React.PointerEvent) => {
const r = (e.currentTarget as HTMLCanvasElement).getBoundingClientRect();
return { sx: e.clientX - r.left, sy: e.clientY - r.top };
};
const pickAt = (sx: number, sy: number) => {
const raw = toPage(sx, sy);
const snap = index.nearest(raw.x, raw.y, SNAP_PX / view.zoom);
return { p: snap ?? raw, snapped: snap !== null };
};
const onPointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {
const { sx, sy } = local(e);
drag.current = { x: sx, y: sy, view, moved: false };
e.currentTarget.setPointerCapture?.(e.pointerId);
};
const onPointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {
const { sx, sy } = local(e);
const d = drag.current;
if (d) {
const dx = sx - d.x;
const dy = sy - d.y;
if (d.moved || Math.hypot(dx, dy) > DRAG_PX) {
d.moved = true;
setView({ zoom: d.view.zoom, cx: d.view.cx - dx / d.view.zoom, cy: d.view.cy + dy / d.view.zoom });
return;
}
}
setHover(pickAt(sx, sy));
};
const onPointerUp = (e: React.PointerEvent<HTMLCanvasElement>) => {
const d = drag.current;
drag.current = null;
if (!d || d.moved) return;
const { sx, sy } = local(e);
const { p } = pickAt(sx, sy);
// Dritter Klick beginnt eine neue Messung.
setPts((old) => (old.length >= 2 ? [p] : [...old, p]));
};
const trueLen = Number(lenText.trim().replace(",", "."));
const scale = pts.length === 2 ? pdfScaleFromDistance(pts[0], pts[1], trueLen) : null;
const status =
pts.length === 0 ? t("import.pdf.cal.pick1") : pts.length === 1 ? t("import.pdf.cal.pick2") : null;
return (
<div className="imp-cal" ref={wrapRef}>
<div className="imp-note">{t("import.pdf.cal.hint")}</div>
<canvas
ref={canvasRef}
className="imp-cal-canvas"
style={{ width: "100%", height: HEIGHT }}
role="img"
aria-label={t("import.pdf.cal.canvas")}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerLeave={() => {
setHover(null);
drag.current = null;
}}
/>
<div className="imp-cal-row">
{status && <span className="imp-note">{status}</span>}
{pts.length === 2 && (
<span className="imp-note">{t("import.pdf.cal.measured", { mm: pdfPaperMm(pts[0], pts[1]).toFixed(1) })}</span>
)}
<button className="imp-btn imp-cal-small" onClick={() => setView(fitView(page, width))}>
{t("import.pdf.cal.fit")}
</button>
{pts.length > 0 && (
<button className="imp-btn imp-cal-small" onClick={() => setPts([])}>
{t("import.pdf.cal.reset")}
</button>
)}
</div>
{pts.length === 2 && (
<div className="imp-cal-row">
<input
className="imp-input imp-cal-len"
type="text"
inputMode="decimal"
placeholder={t("import.pdf.cal.trueLength")}
aria-label={t("import.pdf.cal.trueLength")}
value={lenText}
onChange={(e) => setLenText(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && scale) onApply(Math.round(scale * 100) / 100);
}}
autoFocus
/>
{scale && <span className="imp-note">{t("import.pdf.cal.result", { scale: formatScale(scale) })}</span>}
<button
className="imp-btn primary imp-cal-small"
disabled={!scale}
onClick={() => scale && onApply(Math.round(scale * 100) / 100)}
>
{t("import.pdf.cal.apply")}
</button>
</div>
)}
</div>
);
}