Merge [K3d] Render-Szene, Picken, Objektfang und SVG-Export aus dem Plan-Puffer im Kern (Szene gross 3125 -> 133 ms, Fang 27,6 s -> 0,8 ms pro Mausbewegung)

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-28 23:50:32 +00:00
commit 775d756a6c
39 files changed
+3858 -1471

No files matched your search

-1
View File
@@ -39,7 +39,6 @@ export { sunPosition, shadowPolygons, shadowOfPrism, projectLatLon } from "../an
export type { SunPosition } from "../analysis/sun";
export { checkSiteRules, allowedArea, multiPolygonArea, buildingFootprint, modelTop } from "../analysis/siteRules";
export type { SiteCheck } from "../analysis/siteRules";
export { encodeRenderScene } from "../plan/renderSceneBin";
export { sampleProject } from "../model/sampleProject";
export { parseDxf } from "../io/dxfParser";
export { contoursToDrawings, textsToDrawings, planImportCategories, distinctImportLayers } from "../io/dxfToDrawings";
+12 -11
View File
@@ -45,6 +45,14 @@ export {
pointSegDist as pointSegDist__geometry_drawingIndex,
} from "../geometry/drawingIndex";
export {
type SegSnapCand,
type SegSnapResult,
holdSnapSegments,
releaseSnapSegments,
snapOnSegments,
} from "../geometry/snapSegments";
export {
mvGeom,
reversesOrientation,
@@ -264,18 +272,10 @@ export {
} from "../plan/planView/geometry";
export {
type ClientMap,
type OwnerField,
type OwnerIndex,
buildOwnerIndex,
ownedBy,
} from "../plan/planView/ownerIndex";
export {
buildSegmentIndex,
nearestSegment,
pointSegDist as pointSegDist__plan_planView_segmentIndex,
segmentsNear,
} from "../plan/planView/segmentIndex";
PlanPickIndex,
} from "../plan/planView/planPick";
export {
marqueeHitUnderlay,
@@ -290,6 +290,7 @@ export {
} from "../plan/toElevation";
export {
planSceneBin,
planToRenderScene,
} from "../plan/toRenderScene";
+7 -91
View File
@@ -1,11 +1,13 @@
// Plan → SVG-TEXT ohne DOM (für `dossier-cli` und Referenzbild-Tests, lessons-bimcraft [4]/[17]).
// Der Druck-Export (`planToPrintSvg`) baut ein DOM-Element für svg2pdf; dieser Serializer ist
// Der Druck-Export (`sceneToPrintSvg`) baut ein DOM-Element für svg2pdf; dieser Serializer ist
// die schlanke, headless Variante: Koordinaten in Metern (Y nach oben → SVG gespiegelt),
// Strichstärken aus Papier-mm über den Massstab umgerechnet. Schraffur-Muster werden nicht
// ausgebreitet (nur Grundfüllung), Bilder fehlen — gedacht für Kontrolle und Diffs, nicht für Druck.
// Geschrieben vom Kern direkt aus dem Plan-Puffer ([K3d], `src-tauri/core/src/plan_svg.rs`).
import type { Plan, Primitive } from "../plan/generatePlan";
import { plainText } from "../text/richText";
import type { Plan } from "../plan/generatePlan";
import { planParts, withPlanParts } from "../plan/planParts";
import { core } from "../engine/coreWasm";
export interface SvgStringOptions {
/** Massstab-Nenner N (1:N) — bestimmt die Umrechnung Papier-mm → Meter. Default 100. */
@@ -14,94 +16,8 @@ export interface SvgStringOptions {
marginM?: number;
}
const esc = (s: string): string =>
s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
const num = (v: number): string => (Number.isFinite(v) ? String(Math.round(v * 1e5) / 1e5) : "0");
export function planToSvgString(plan: Plan, opts: SvgStringOptions = {}): string {
const n = opts.scaleDenominator ?? 100;
const margin = opts.marginM ?? 0.5;
const mmToM = n / 1000; // 1 mm Papier = n/1000 m Modell
const b = plan.bounds;
const x0 = b.minX - margin;
const w = b.maxX - b.minX + 2 * margin;
const h = b.maxY - b.minY + 2 * margin;
// Y spiegeln: svgY = (maxY + margin) − y
const top = b.maxY + margin;
const X = (x: number): string => num(x);
const Y = (y: number): string => num(top - y);
const dashAttr = (d: number[] | null | undefined): string =>
d && d.length ? ` stroke-dasharray="${d.map((v) => num(v * mmToM)).join(" ")}"` : "";
const op = (p: { opacity?: number; greyed?: boolean }): string =>
p.greyed ? ' opacity="0.35"' : p.opacity !== undefined && p.opacity < 1 ? ` opacity="${num(p.opacity)}"` : "";
const out: string[] = [];
for (const p of plan.primitives as Primitive[]) {
switch (p.kind) {
case "polygon": {
if (p.pts.length < 3) break;
const pts = p.pts.map((q) => `${X(q.x)},${Y(q.y)}`).join(" ");
out.push(
`<polygon points="${pts}" fill="${esc(p.fill)}" stroke="${esc(p.stroke)}" stroke-width="${num(p.strokeWidthMm * mmToM)}" stroke-linejoin="round"${op(p)}/>`,
);
break;
}
case "line":
out.push(
`<line x1="${X(p.a.x)}" y1="${Y(p.a.y)}" x2="${X(p.b.x)}" y2="${Y(p.b.y)}" stroke="${esc(p.color ?? "#000")}" stroke-width="${num(p.weightMm * mmToM)}"${dashAttr(p.dash)}${op(p)}/>`,
);
break;
case "arc": {
// Bogen von `from` nach `to` um `center`, gegen den Uhrzeigersinn im Modell.
const a0 = Math.atan2(p.from.y - p.center.y, p.from.x - p.center.x);
let sweep = Math.atan2(p.to.y - p.center.y, p.to.x - p.center.x) - a0;
while (sweep < 0) sweep += Math.PI * 2;
out.push(
`<path d="M ${X(p.from.x)} ${Y(p.from.y)} A ${num(p.r)} ${num(p.r)} 0 ${sweep > Math.PI ? 1 : 0} 0 ${X(p.to.x)} ${Y(p.to.y)}" fill="none" stroke="#000" stroke-width="${num(p.weightMm * mmToM)}"${dashAttr(p.dash)}${op(p)}/>`,
);
break;
}
case "drawingCircle":
out.push(
`<circle cx="${X(p.center.x)}" cy="${Y(p.center.y)}" r="${num(p.r)}" fill="${esc(p.fill)}" stroke="${esc(p.stroke)}" stroke-width="${num(p.weightMm * mmToM)}"${dashAttr(p.dash)}${op(p)}/>`,
);
break;
case "drawingArc": {
const sx = p.center.x + p.r * Math.cos(p.a0);
const sy = p.center.y + p.r * Math.sin(p.a0);
const ex = p.center.x + p.r * Math.cos(p.a1);
const ey = p.center.y + p.r * Math.sin(p.a1);
let sweep = p.a1 - p.a0;
while (sweep < 0) sweep += Math.PI * 2;
out.push(
`<path d="M ${X(sx)} ${Y(sy)} A ${num(p.r)} ${num(p.r)} 0 ${sweep > Math.PI ? 1 : 0} 0 ${X(ex)} ${Y(ey)}" fill="none" stroke="${esc(p.stroke)}" stroke-width="${num(p.weightMm * mmToM)}"${dashAttr(p.dash)}${op(p)}/>`,
);
break;
}
case "drawingText":
out.push(
`<text x="${X(p.at.x)}" y="${Y(p.at.y)}" font-size="${num(p.heightM)}" fill="${esc(p.color)}" font-family="sans-serif" transform="rotate(${num(-(p.angle * 180) / Math.PI)} ${X(p.at.x)} ${Y(p.at.y)})"${op(p)}>${esc(p.text)}</text>`,
);
break;
case "text": {
const size = (p.basePt * 0.3528) * mmToM; // pt → mm Papier → m Modell
const lines = [plainText(p.doc), ...p.extraLines.map((l) => l.text)].filter((s) => s);
lines.forEach((ln, i) =>
out.push(
`<text x="${X(p.at.x)}" y="${num(top - p.at.y + i * size * 1.2)}" font-size="${num(size)}" fill="${esc(p.color)}" font-family="sans-serif" text-anchor="middle"${op(p)}>${esc(ln)}</text>`,
),
);
break;
}
default:
break; // Bilder, Textpfade: im headless SVG nicht dargestellt
}
}
return (
`<?xml version="1.0" encoding="UTF-8"?>\n` +
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${num(x0)} 0 ${num(w)} ${num(h)}" width="${num(w * 1000 / n)}mm" height="${num(h * 1000 / n)}mm">\n` +
`<rect x="${num(x0)}" y="0" width="${num(w)}" height="${num(h)}" fill="#ffffff"/>\n` +
out.join("\n") +
`\n</svg>\n`
);
const o = Float64Array.from([opts.scaleDenominator ?? 100, opts.marginM ?? 0.5, b.minX, b.minY, b.maxX, b.maxY]);
return withPlanParts(planParts(plan, true), (segs) => core().plan_svg_string(segs, o));
}
+102
View File
@@ -0,0 +1,102 @@
// Objektfang auf Strecken im Kern ([K3d], `core/src/snap.rs`): gleiche Wahl wie die einfache
// Suche über alle Strecken/Paare (Raster-Vorauswahl und Geraden-Filter für Schnittpunkte dürfen
// nichts ändern). (Gleichheit zur früheren TS-Fassung von computeSnap: 2600 Abfragen, s. TODO [K3d].)
import { describe, expect, it } from "vitest";
import { holdSnapSegments, releaseSnapSegments, snapOnSegments, type SnapSeg } from "./snapSegments";
import type { Vec2 } from "../model/types";
const PRIORITY: Record<string, number> = { perpendicular: 1, endpoint: 7, midpoint: 3, intersection: 5, onEdge: 0 };
/** Einfache Fassung (alle Strecken, alle Paare) — Block A (Lot, Endpunkte) und Block B (Mitte, Schnitt, Kante). */
function brute(segs: SnapSeg[], raw: Vec2, tolM: number, pxPerM: number, last: Vec2 | null) {
const perp = (p: Vec2, a: Vec2, b: Vec2): Vec2 => {
const dx = b.x - a.x, dy = b.y - a.y;
const len2 = dx * dx + dy * dy;
if (len2 < 1e-12) return a;
const t = Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2));
return { x: a.x + dx * t, y: a.y + dy * t };
};
const block = () => {
let best: { point: Vec2; kind: string; distPx: number; score: number } | null = null;
let bestScore = Infinity;
const consider = (point: Vec2, kind: string) => {
const d = Math.hypot(point.x - raw.x, point.y - raw.y);
if (d > tolM) return;
const score = d * pxPerM - PRIORITY[kind];
if (score < bestScore) {
bestScore = score;
best = { point, kind, distPx: d * pxPerM, score };
}
};
return { consider, get: () => best };
};
const a = block();
if (last) for (const [p, q] of segs) a.consider(perp(last, p, q), "perpendicular");
for (const [p, q] of segs) {
a.consider(p, "endpoint");
a.consider(q, "endpoint");
}
const b = block();
for (const [p, q] of segs) b.consider({ x: (p.x + q.x) / 2, y: (p.y + q.y) / 2 }, "midpoint");
for (let i = 0; i < segs.length; i++) {
for (let j = i + 1; j < segs.length; j++) {
const [p, q] = segs[i];
const [r, s] = segs[j];
const da = { x: q.x - p.x, y: q.y - p.y };
const db = { x: s.x - r.x, y: s.y - r.y };
const den = da.x * db.y - da.y * db.x;
if (Math.abs(den) < 1e-9) continue;
const t = ((r.x - p.x) * db.y - (r.y - p.y) * db.x) / den;
b.consider({ x: p.x + da.x * t, y: p.y + da.y * t }, "intersection");
}
}
for (const [p, q] of segs) b.consider(perp(raw, p, q), "onEdge");
return { a: a.get(), b: b.get() };
}
describe("snapOnSegments (Kern)", () => {
it("gleich wie die Suche über alle Strecken und Paare (Zufallsdaten)", () => {
let seed = 3;
const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
for (let run = 0; run < 8; run++) {
const segs: SnapSeg[] = [];
for (let i = 0; i < 300; i++) {
const x = rnd() * 20, y = rnd() * 20;
// Viele achsparallele Strecken (Wände), einige lange schräge (Verlängerungen schneiden weit weg).
const k = rnd();
segs.push(k < 0.4 ? [{ x, y }, { x: x + rnd() * 5, y }] : k < 0.8 ? [{ x, y }, { x, y: y + rnd() * 5 }] : [{ x, y }, { x: x + rnd() * 30 - 15, y: y + rnd() * 30 - 15 }]);
}
const base = segs.slice(0, 250);
const extra = segs.slice(250);
const h = holdSnapSegments(base);
for (let q = 0; q < 25; q++) {
const raw = { x: rnd() * 20, y: rnd() * 20 };
const tolM = 0.05 + rnd() * 0.5;
const last = rnd() < 0.5 ? { x: rnd() * 20, y: rnd() * 20 } : null;
const r = snapOnSegments(h, extra, null, { raw, tolM, pxPerMeter: 100, perpendicular: true, endpoint: true, midpoint: true, intersection: true, onEdge: true, lastPoint: last })!;
const e = brute(segs, raw, tolM, 100, last);
expect(r.a).toEqual(e.a);
expect(r.b).toEqual(e.b);
}
releaseSnapSegments(h);
expect(snapOnSegments(h, [], null, { raw: { x: 0, y: 0 }, tolM: 1, pxPerMeter: 1, perpendicular: false, endpoint: true, midpoint: false, intersection: false, onEdge: false, lastPoint: null })).toBeNull();
}
}, 60_000);
it("nächste Strecke für das Verweilen", () => {
const r = snapOnSegments(0, [[{ x: 0, y: 0 }, { x: 10, y: 0 }], [{ x: 5, y: -5 }, { x: 5, y: 5 }]], null, {
raw: { x: 5.05, y: 0.02 },
tolM: 0.2,
pxPerMeter: 100,
perpendicular: false,
endpoint: true,
midpoint: true,
intersection: true,
onEdge: true,
lastPoint: null,
})!;
expect(r.nearest).toEqual([{ x: 0, y: 0 }, { x: 10, y: 0 }]);
expect(r.b?.kind).toBe("intersection");
});
});
+95
View File
@@ -0,0 +1,95 @@
// Objektfang auf Strecken über den Kern ([K3d], `src-tauri/core/src/snap.rs`): Lotfusspunkt,
// Endpunkte, Mittelpunkte, Schnittpunkte, Punkt auf der Kante und die nächste Strecke (Verweilen).
// Die Strecken eines Projekt-Geschosses liegen einmal im Kern ({@link holdSnapSegments}); je
// Mausbewegung gehen nur Cursor und Zusatzstrecken über die Grenze. Die Sammlung der Strecken
// und die übrigen Fang-Arten (Raster, Winkel, Kreise, Teilpunkte) bleiben in `tools/snapping.ts`.
import type { Vec2 } from "../model/types";
import { core } from "../engine/coreWasm";
export type SnapSeg = [Vec2, Vec2];
/** Fang-Arten des Kerns (Code → Name wie `SnapKind`). */
const KINDS = ["perpendicular", "endpoint", "midpoint", "intersection", "onEdge"] as const;
export type SegSnapKind = (typeof KINDS)[number];
export interface SegSnapCand {
point: Vec2;
kind: SegSnapKind;
distPx: number;
/** `distPx − Priorität` (kleiner gewinnt). */
score: number;
}
export interface SegSnapResult {
/** Nächste Strecke innerhalb der Toleranz (Lotfusspunkt-Abstand) oder null. */
nearest: SnapSeg | null;
/** Block A: Lot vom letzten Punkt, Endpunkte der Strecken. */
a: SegSnapCand | null;
/** Block B: Mittelpunkte, Schnittpunkte, Punkt auf der Kante. */
b: SegSnapCand | null;
}
export interface SegSnapQuery {
raw: Vec2;
tolM: number;
pxPerMeter: number;
perpendicular: boolean;
endpoint: boolean;
midpoint: boolean;
intersection: boolean;
onEdge: boolean;
lastPoint: Vec2 | null;
}
function flat(segs: readonly SnapSeg[]): Float64Array {
const out = new Float64Array(segs.length * 4);
for (let i = 0; i < segs.length; i++) {
const [a, b] = segs[i];
out[4 * i] = a.x;
out[4 * i + 1] = a.y;
out[4 * i + 2] = b.x;
out[4 * i + 3] = b.y;
}
return out;
}
/** Strecken im Kern ablegen; Nummer für {@link snapOnSegments} (freigeben: {@link releaseSnapSegments}). */
export function holdSnapSegments(segs: readonly SnapSeg[]): number {
return core().snap_segs_hold(flat(segs));
}
export function releaseSnapSegments(id: number): void {
if (id) core().snap_segs_release(id);
}
const cand = (f: Float64Array, k: number): SegSnapCand | null =>
Number.isNaN(f[k + 2]) ? null : { point: { x: f[k], y: f[k + 1] }, kind: KINDS[f[k + 2]], distPx: f[k + 3], score: f[k + 4] };
/**
* Fang über die abgelegten Strecken `held` (0 = keine) und `extra` (in dieser Reihenfolge);
* Schnittpunkte aus `intSegs` (null = aus denselben Strecken). null, wenn `held` nicht (mehr) im
* Kern liegt.
*/
export function snapOnSegments(held: number, extra: readonly SnapSeg[], intSegs: readonly SnapSeg[] | null, q: SegSnapQuery): SegSnapResult | null {
const flags = (q.perpendicular ? 1 : 0) | (q.endpoint ? 2 : 0) | (q.midpoint ? 4 : 0) | (q.intersection ? 8 : 0) | (q.onEdge ? 16 : 0);
const f = core().snap_eval(
held,
flat(extra),
intSegs ? 1 : 0,
intSegs ? flat(intSegs) : new Float64Array(0),
q.raw.x,
q.raw.y,
q.tolM,
q.pxPerMeter,
flags,
q.lastPoint ? q.lastPoint.x : NaN,
q.lastPoint ? q.lastPoint.y : NaN,
);
if (f.length < 15) return null;
return {
nearest: f[0] >= 0 ? [{ x: f[1], y: f[2] }, { x: f[3], y: f[4] }] : null,
a: cand(f, 5),
b: cand(f, 10),
};
}
+12 -2
View File
@@ -178,6 +178,14 @@ export interface EncodeOptions {
* (tag 0). Schneller; {@link decodePlanBuf} kann so einen Puffer nicht vollständig lesen.
*/
lean?: boolean;
/**
* `false`: Texte/Bilder ohne JSON (String-Index −1), aber mit Typ und Pick-Ids — für Kern-
* Verbraucher, die Texte nicht lesen (Render-Szene, Auswahl). {@link decodePlanBuf} kann so
* einen Puffer nicht lesen. Standard `true`.
*/
textJson?: boolean;
/** `false`: Schraffuren ohne JSON (nur das Hatch-Format, wie `lean`). Standard `true`. */
hatchJson?: boolean;
/** Gruppen `[start, end)` in den Kopf schreiben. */
groups?: ReadonlyArray<readonly [number, number]>;
bounds?: readonly [number, number, number, number];
@@ -186,6 +194,8 @@ export interface EncodeOptions {
/** Primitive → Plan-Puffer v2 (Format s. Dateikopf). */
export function encodePlanBuf(prims: readonly Primitive[], opts: EncodeOptions = {}): Uint8Array {
const lean = opts.lean === true;
const textJson = opts.textJson !== false;
const hatchJson = !lean && opts.hatchJson !== false;
const strParts: string[] = [];
const strTab = new F64Writer(64);
const strIdx = new Map<string, number>();
@@ -210,7 +220,7 @@ export function encodePlanBuf(prims: readonly Primitive[], opts: EncodeOptions =
let i = hatchIdx.get(h);
if (i === undefined) {
i = hatchIdx.size;
hatchW.push(lean ? -1 : str(JSON.stringify(h)));
hatchW.push(hatchJson ? str(JSON.stringify(h)) : -1);
writeHatch(hatchW, h, str(h.color));
hatchIdx.set(h, i);
}
@@ -385,7 +395,7 @@ export function encodePlanBuf(prims: readonly Primitive[], opts: EncodeOptions =
}
const tag = p.kind === "text" ? 6 : p.kind === "drawingText" ? 7 : p.kind === "drawingTextPath" ? 8 : 9;
head(tag, 0, p);
w.push(str(JSON.stringify(p)));
w.push(textJson ? str(JSON.stringify(p)) : -1);
}
}
}
+154
View File
@@ -0,0 +1,154 @@
/**
* Zusammengesetzter Plan für Kern-Verbraucher ([K3d], Rust: `src-tauri/core/src/plan_parts.rs`):
* die Primitive eines {@link Plan} als Abschnitte gehaltener Plan-Puffer, in Zeichenreihenfolge.
* Was unverändert aus einem Kern-Puffer stammt (`Plan.bufRuns`, Objekt-Identität geprüft), geht
* ohne Umweg über Objekte; der Rest (2D-Zeichnungen, Schatten, Baurecht, zerlegte Polygone,
* gedimmte Klone) wird einmal in einen eigenen Puffer geschrieben. Der Index eines Primitivs im
* Kern ist seine Stelle in `plan.primitives`.
*
* Abschnitte reisen als `[Puffer-Nr, von, bis, …]` (Nr = `plan_buf_hold`), gedimmte Bereiche
* (`Plan.greyedRanges`) als `[von, bis, …]`. Verdrängt der Kern einen Puffer, liefert er ein
* leeres Ergebnis; {@link withPlanParts} legt dann alles neu ab und fragt nochmals.
*/
import type { Plan, PlanBufRun, Primitive } from "./generatePlan";
import { encodePlanBuf } from "./planBuf";
import { core } from "../engine/coreWasm";
/** Ein im Kern ablegbarer Puffer (Kern-Ergebnis `DecodedPlanBuf` oder eigener). */
interface HoldableBuf {
bytes: Uint8Array;
hold: number;
}
export interface PlanParts {
bufs: HoldableBuf[];
/** Abschnitte `[Index in bufs, von, bis, …]`. */
segs: number[];
/** Anzahl Primitive (= `plan.primitives.length`). */
count: number;
}
/** Unveränderte Kern-Abschnitte (Objekt-Identität) in Plan-Reihenfolge. */
function verifiedRuns(primitives: readonly Primitive[], runs: readonly PlanBufRun[] | undefined) {
const out: Array<{ start: number; end: number; buf: PlanBufRun["buf"]; from: number }> = [];
for (const r of runs ?? []) {
const n = Math.min(r.to - r.from, primitives.length - r.at);
let k = 0;
while (k < n) {
while (k < n && primitives[r.at + k] !== r.buf.prims[r.from + k]) k++;
const k0 = k;
while (k < n && primitives[r.at + k] === r.buf.prims[r.from + k]) k++;
if (k > k0) out.push({ start: r.at + k0, end: r.at + k, buf: r.buf, from: r.from + k0 });
}
}
out.sort((a, b) => a.start - b.start);
// Überlappungen (sollte es nicht geben) verwerfen.
const clean: typeof out = [];
let last = 0;
for (const s of out) {
if (s.start < last) continue;
clean.push(s);
last = s.end;
}
return clean;
}
const cache = new WeakMap<readonly Primitive[], { text: PlanParts | null; noText: PlanParts | null }>();
/**
* Abschnitte eines Plans; einmal je `plan.primitives` (und Modus) gebaut. `texts`: der eigene
* Puffer trägt Texte/Bilder mit JSON (SVG-Export) — sonst nur deren Typ (Szene, Auswahl).
*/
export function planParts(plan: Plan, texts = false): PlanParts {
const prims = plan.primitives;
let c = cache.get(prims);
if (!c) {
c = { text: null, noText: null };
cache.set(prims, c);
}
const hit = texts ? c.text : c.noText;
if (hit) return hit;
const runs = verifiedRuns(prims, plan.bufRuns);
const bufs: HoldableBuf[] = [];
const bufIdx = new Map<HoldableBuf, number>();
const idx = (b: HoldableBuf): number => {
let i = bufIdx.get(b);
if (i === undefined) {
i = bufs.length;
bufs.push(b);
bufIdx.set(b, i);
}
return i;
};
// Lücken zwischen den Kern-Abschnitten sammeln: [Plan-Start, Plan-Ende, Start im eigenen Puffer].
const rest: Primitive[] = [];
const gaps: Array<[number, number, number]> = [];
let at = 0;
const gap = (end: number) => {
if (end <= at) return;
gaps.push([at, end, rest.length]);
for (let i = at; i < end; i++) rest.push(prims[i]);
};
for (const r of runs) {
gap(r.start);
at = r.end;
}
gap(prims.length);
const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts, hatchJson: false }), hold: 0 } : null;
const segs: number[] = [];
let gi = 0;
let ri = 0;
// Abschnitte in Plan-Reihenfolge zusammenführen.
while (gi < gaps.length || ri < runs.length) {
const g = gaps[gi];
const r = runs[ri];
if (r === undefined || (g !== undefined && g[0] < r.start)) {
segs.push(idx(own!), g[2], g[2] + (g[1] - g[0]));
gi++;
} else {
segs.push(idx(r.buf), r.from, r.from + (r.end - r.start));
ri++;
}
}
const out: PlanParts = { bufs, segs, count: prims.length };
if (texts) c.text = out;
else c.noText = out;
return out;
}
/** Gedimmte Bereiche flach (`Plan.greyedRanges`). */
export function greyedFlat(plan: Plan): Float64Array {
const r = plan.greyedRanges ?? [];
const out = new Float64Array(r.length * 2);
r.forEach(([a, b], i) => {
out[2 * i] = a;
out[2 * i + 1] = b;
});
return out;
}
/**
* Abschnitte mit den Kern-Nummern der Puffer; legt fehlende ab (`fresh`: auch verdrängte).
*/
export function heldSegs(parts: PlanParts, fresh: boolean): Float64Array {
const c = core();
for (const b of parts.bufs) if (!b.hold || (fresh && !c.plan_buf_is_held(b.hold))) b.hold = c.plan_buf_hold(b.bytes);
const s = new Float64Array(parts.segs.length);
for (let i = 0; i < parts.segs.length; i += 3) {
s[i] = parts.bufs[parts.segs[i]].hold;
s[i + 1] = parts.segs[i + 1];
s[i + 2] = parts.segs[i + 2];
}
return s;
}
/**
* Kern-Aufruf mit den gehaltenen Abschnitten. `call` liefert ein leeres Ergebnis, wenn ein
* Puffer verdrängt ist — dann werden alle neu abgelegt und es wird einmal wiederholt.
*/
export function withPlanParts<T extends { length: number }>(parts: PlanParts, call: (segs: Float64Array) => T): T {
const out = call(heldSegs(parts, false));
if (out.length > 0 || parts.segs.length === 0) return out;
return call(heldSegs(parts, true));
}
-44
View File
@@ -1,44 +0,0 @@
import { describe, it, expect } from "vitest";
import type { Primitive } from "../generatePlan";
import { buildOwnerIndex, ownedBy } from "./ownerIndex";
const line = (drawingId: string): Primitive =>
({ kind: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 }, cls: "draw2d", weightMm: 0.1, drawingId }) as Primitive;
const poly = (extra: Record<string, string>): Primitive =>
({ kind: "polygon", pts: [], fill: "#fff", stroke: "#000", strokeWidthMm: 0.1, ...extra }) as unknown as Primitive;
describe("ownerIndex", () => {
const prims: Primitive[] = [
poly({ wallId: "w1" }),
line("d1"),
poly({ roomId: "r1" }),
line("d2"),
poly({ wallId: "w2", openingId: "o1" }),
line("d1"),
];
const idx = buildOwnerIndex(prims);
it("findet Primitive je Besitzer-ID in Plan-Reihenfolge", () => {
expect(ownedBy(idx, prims, "drawingId", ["d1"])).toEqual([prims[1], prims[5]]);
expect(ownedBy(idx, prims, "wallId", ["w2", "w1"])).toEqual([prims[0], prims[4]]);
expect(ownedBy(idx, prims, "roomId", ["r1"])).toEqual([prims[2]]);
});
it("ein Primitiv kann mehrere Besitzer-Felder tragen (ausser Zeichnungs-Primitive)", () => {
expect(ownedBy(idx, prims, "openingId", ["o1"])).toEqual([prims[4]]);
expect(ownedBy(idx, prims, "wallId", ["w2"])).toEqual([prims[4]]);
});
it("liefert nichts für unbekannte IDs/leere Mengen und gleicht dem früheren filter()", () => {
expect(ownedBy(idx, prims, "drawingId", ["x"])).toEqual([]);
expect(ownedBy(idx, prims, "wallId", [])).toEqual([]);
const ids = new Set(["d2", "w1"]);
const viaFilter = prims.filter(
(p) => ids.has((p as any).drawingId) || ids.has((p as any).wallId),
);
const viaIndex = [...ownedBy(idx, prims, "drawingId", ids), ...ownedBy(idx, prims, "wallId", ids)].sort(
(a, b) => prims.indexOf(a) - prims.indexOf(b),
);
expect(viaIndex).toEqual(viaFilter);
});
});
-66
View File
@@ -1,66 +0,0 @@
// Besitzer-Index über die Primitive eines Plans: welche Primitive gehören zu
// Wand/Decke/Raum/Zeichnung/…-ID X? Die Auswahl-Hervorhebung in PlanView hat
// das bisher mit je einem `plan.primitives.filter(...)` PRO Elementart gelöst —
// zehn Durchgänge über alle Primitive bei jeder Plan-Änderung (bei einem
// Kataster-Import 3,7 Mio. → ~300 ms pro Änderung). Der Index braucht EINEN
// Durchgang je Plan; danach kostet jede Abfrage nur die Treffer.
import type { Primitive } from "../generatePlan";
export const OWNER_FIELDS = [
"wallId",
"drawingId",
"ceilingId",
"openingId",
"stairId",
"roomId",
"roofId",
"contextObjectId",
"sectionLineId",
"extrudedSolidId",
"columnId",
] as const;
export type OwnerField = (typeof OWNER_FIELDS)[number];
export type OwnerIndex = Record<OwnerField, Map<string, number[]>>;
export function buildOwnerIndex(prims: readonly Primitive[]): OwnerIndex {
const index = Object.fromEntries(OWNER_FIELDS.map((f) => [f, new Map<string, number[]>()])) as OwnerIndex;
const add = (field: OwnerField, id: string, i: number) => {
const m = index[field];
const list = m.get(id);
if (list) list.push(i);
else m.set(id, [i]);
};
for (let i = 0; i < prims.length; i++) {
const rec = prims[i] as unknown as Record<OwnerField, unknown>;
// Schnellpfad: Primitive aus 2D-Zeichnungen (der Massenfall) tragen NUR eine
// drawingId, nie eine andere Besitzer-ID (s. generatePlan/drawing2d.ts).
const did = rec.drawingId;
if (typeof did === "string") {
add("drawingId", did, i);
continue;
}
for (const f of OWNER_FIELDS) {
const v = rec[f];
if (typeof v === "string") add(f, v, i);
}
}
return index;
}
/** Primitive, deren `field` in `ids` liegt — in Plan-Reihenfolge (wie `filter`). */
export function ownedBy(
index: OwnerIndex,
prims: readonly Primitive[],
field: OwnerField,
ids: Iterable<string>,
): Primitive[] {
const hits: number[] = [];
for (const id of ids) {
const list = index[field].get(id);
if (list) for (const i of list) hits.push(i);
}
hits.sort((a, b) => a - b);
return hits.map((i) => prims[i]);
}
+132
View File
@@ -0,0 +1,132 @@
// Auswahl über den Kern ([K3d], `core/src/plan_pick.rs`): nächstes Segment, Segmente im Umkreis,
// Polygone unter dem Punkt (mit Pick-Feld), Symbol-Linien in Pixeln, Kreis-/Bogen-Ringe und
// Besitzer — gegen einfache lineare Suchen. (Gleichheit zur früheren TS-Fassung — segmentIndex,
// ownerIndex, PlanView-Schleifen — mit Beispielprojekt, 150 Zufallsplänen und grossem Projekt
// geprüft, s. TODO [K3d].)
import { describe, it, expect } from "vitest";
import type { Plan, Primitive } from "../generatePlan";
import { generatePlan } from "../generatePlan";
import { PlanPickIndex } from "./planPick";
import { pointInPolygon } from "./geometry";
import { sampleProject } from "../../model/sampleProject";
import { flattenCategories } from "../../model/types";
const plan = (primitives: Primitive[]): Plan => ({ primitives, bounds: { minX: 0, minY: 0, maxX: 1, maxY: 1 } });
const line = (ax: number, ay: number, bx: number, by: number, drawingId: string | undefined = "d"): Primitive =>
({ kind: "line", a: { x: ax, y: ay }, b: { x: bx, y: by }, cls: "draw2d", weightMm: 0.18, drawingId }) as Primitive;
const poly = (pts: Array<[number, number]>, extra: Record<string, string> = {}): Primitive =>
({ kind: "polygon", pts: pts.map(([x, y]) => ({ x, y })), fill: "#fff", stroke: "#000", strokeWidthMm: 0.1, ...extra }) as unknown as Primitive;
function bruteForce(prims: Primitive[], m: { x: number; y: number }, maxDist: number): number | null {
let best: number | null = null;
let bestDist = maxDist;
prims.forEach((p, i) => {
if (p.kind !== "line" || !p.drawingId) return;
const dx = p.b.x - p.a.x, dy = p.b.y - p.a.y;
const len2 = dx * dx + dy * dy;
const t = len2 > 0 ? Math.max(0, Math.min(1, ((m.x - p.a.x) * dx + (m.y - p.a.y) * dy) / len2)) : 0;
const d = Math.hypot(m.x - (p.a.x + t * dx), m.y - (p.a.y + t * dy));
if (d < bestDist) {
bestDist = d;
best = i;
}
});
return best;
}
describe("PlanPickIndex: Segmente", () => {
it("nächstes Segment wie die lineare Suche (Zufallsdaten, Überlauf-Segment, Nicht-2D-Strich)", () => {
let seed = 1;
const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
const prims: Primitive[] = [];
for (let i = 0; i < 20000; i++) {
const x = rnd() * 1000, y = rnd() * 1000;
prims.push(line(x, y, x + (rnd() - 0.5) * 20, y + (rnd() - 0.5) * 20));
}
prims.push(line(-5000, -5000, 5000, 5000));
prims.push(line(500, 500, 501, 501, undefined));
const ix = new PlanPickIndex(plan(prims));
for (let k = 0; k < 500; k++) {
const m = { x: rnd() * 1100 - 50, y: rnd() * 1100 - 50 };
expect(ix.nearestSegment(m, 3)?.i ?? null).toBe(bruteForce(prims, m, 3));
}
ix.release();
});
it("nichts ausserhalb der Toleranz, nichts ohne 2D-Linien", () => {
const ix = new PlanPickIndex(plan([line(0, 0, 10, 0)]));
expect(ix.nearestSegment({ x: 5, y: 0.5 }, 1)).toEqual({ i: 0, dist: 0.5 });
expect(ix.nearestSegment({ x: 5, y: 2 }, 1)).toBeNull();
expect(ix.nearestSegment({ x: 500, y: 500 }, 1)).toBeNull();
expect(new PlanPickIndex(plan([])).nearestSegment({ x: 0, y: 0 }, 1)).toBeNull();
});
it("alle Segmente in Reichweite, nächste zuerst", () => {
const prims: Primitive[] = [line(0, 0, 10, 0, "a"), line(0, 0.5, 10, 0.5, "b"), line(0, 5, 10, 5, "c"), line(-2000, -2000, 2000, 2000, "long")];
for (let i = 0; i < 300; i++) prims.push(line(50 + i, 50, 51 + i, 51, `f${i}`));
const hits = new PlanPickIndex(plan(prims)).segmentsNear({ x: 5, y: 0.2 }, 1);
expect(hits.map((h) => (prims[h.i] as { drawingId?: string }).drawingId)).toEqual(["a", "b"]);
expect(hits[0].dist).toBeLessThanOrEqual(hits[1].dist);
});
});
describe("PlanPickIndex: Polygone, Symbole, Ringe, Besitzer", () => {
const prims: Primitive[] = [
poly([[0, 0], [4, 0], [4, 4], [0, 4]], { roomId: "r1" }),
poly([[1, 1], [3, 1], [3, 3], [1, 3]], { wallId: "w1", openingId: "o1" }),
line(0, 0, 1, 0, "d1"),
poly([[2, 2], [5, 2], [5, 5], [2, 5]], { stairId: "s1" }),
{ kind: "line", a: { x: 10, y: 0 }, b: { x: 10, y: 5 }, cls: "door-leaf", weightMm: 0.25, openingId: "o2" } as Primitive,
{ kind: "drawingCircle", center: { x: 20, y: 0 }, r: 1, fill: "none", stroke: "#000", weightMm: 0.25, drawingId: "c1" } as Primitive,
{ kind: "drawingCircle", center: { x: 30, y: 0 }, r: 1, fill: "#f00", stroke: "#000", weightMm: 0.25, drawingId: "c2" } as Primitive,
line(0, 0, 1, 0, "d1"),
poly([[0, 0], [1, 0], [1, 1]], { roomId: "" }),
];
const ix = new PlanPickIndex(plan(prims));
it("Polygone unter dem Punkt: oberstes zuerst, mit Feld-Filter (leere Id zählt nicht)", () => {
const m = { x: 2.5, y: 2.5 };
const all = prims.flatMap((p, i) => (p.kind === "polygon" && pointInPolygon(m, p.pts) ? [i] : [])).reverse();
expect(ix.polygonsAt(m)).toEqual(all);
expect(ix.topPolygon(m)).toBe(3);
expect(ix.topPolygon(m, "roomId")).toBe(0);
expect(ix.bottomPolygon(m, "openingId")).toBe(1);
expect(ix.topPolygon({ x: 0.8, y: 0.2 }, "roomId")).toBe(0);
expect(ix.topPolygon({ x: 50, y: 50 })).toBeNull();
});
it("Symbol-Linie in Client-Pixeln", () => {
const map = { left: 0, top: 0, viewX: 0, viewY: 0, scale: 1 };
// Linie bei x = 10 m → 900 px; Punkt 3 px daneben.
expect(ix.nearestSymbolPx(["openingId"], [], map, { x: 903, y: -200 }, 6)).toBe(4);
expect(ix.nearestSymbolPx(["openingId"], [], map, { x: 910, y: -200 }, 6)).toBeNull();
expect(ix.nearestSymbolPx(["stairId"], [], map, { x: 903, y: -200 }, 6)).toBeNull();
});
it("Ringe: leerer Kreis nur am Rand, gefüllter auch innen", () => {
expect(ix.ringsNear({ x: 21.01, y: 0 }, 100, 6).map((r) => r.i)).toEqual([5]);
expect(ix.ringsNear({ x: 20, y: 0 }, 100, 6)).toEqual([]);
expect(ix.ringsNear({ x: 30, y: 0 }, 100, 6)).toEqual([{ i: 6, dpx: 0 }]);
});
it("Besitzer in Plan-Reihenfolge (Zeichnungs-Primitive nur über drawingId)", () => {
expect(ix.ownedBy("drawingId", ["d1"])).toEqual([prims[2], prims[7]]);
expect(ix.ownedBy("wallId", ["w1"])).toEqual([prims[1]]);
expect(ix.ownedBy("openingId", ["o1", "o2"])).toEqual([prims[1], prims[4]]);
expect(ix.ownedBy("roomId", [""])).toEqual([prims[8]]);
expect(ix.ownedBy("roomId", ["x"])).toEqual([]);
expect(ix.ownedBy("wallId", [])).toEqual([]);
});
it("Beispielprojekt: Kern-Abschnitte und eigener Puffer gemischt", () => {
const codes = new Set(flattenCategories(sampleProject.layers).map((c) => c.code));
const p = generatePlan(sampleProject, "eg", codes);
const pi = new PlanPickIndex(p);
const wall = p.primitives.findIndex((q) => q.kind === "polygon" && !!q.wallId);
const w = p.primitives[wall] as Extract<Primitive, { kind: "polygon" }>;
expect(pi.ownedBy("wallId", [w.wallId!])).toEqual(p.primitives.filter((q) => (q as { wallId?: string }).wallId === w.wallId));
pi.release();
});
});
+149
View File
@@ -0,0 +1,149 @@
// Auswahl/Picken im Grundriss über den Kern ([K3d], `src-tauri/core/src/plan_pick.rs`): ein
// räumlicher Index je Plan (2D-Zeichenlinien, Polygone, Symbol-Linien, Kreise/Bögen, Besitzer),
// gebaut direkt aus den Plan-Puffern (`planParts.ts`). TS fragt nur ab; Ergebnisse sind Indizes in
// `plan.primitives`. Ersetzt `segmentIndex.ts`, `ownerIndex.ts` und die Schleifen über alle
// Primitive bei jeder Mausbewegung (Treffer, Raum/Dach/Treppe/Öffnung …).
//
// Lebensdauer: der Index liegt im Kern, bis {@link PlanPickIndex.release} ihn freigibt (PlanView
// gibt den alten frei, sobald ein neuer Plan einen neuen braucht).
import type { Vec2 } from "../../model/types";
import type { Plan, Primitive } from "../generatePlan";
import { heldSegs, planParts } from "../planParts";
import { core } from "../../engine/coreWasm";
/** Pick-Felder eines Primitivs (Besitzer-Ids). */
export const OWNER_FIELDS = [
"wallId",
"drawingId",
"ceilingId",
"openingId",
"stairId",
"roomId",
"roofId",
"contextObjectId",
"sectionLineId",
"extrudedSolidId",
"columnId",
] as const;
export type OwnerField = (typeof OWNER_FIELDS)[number];
/** Pick-Art im Plan-Puffer (s. `plan_buf.rs`). */
const KIND: Record<OwnerField, number> = {
wallId: 1,
drawingId: 2,
ceilingId: 3,
openingId: 4,
stairId: 5,
roomId: 6,
extrudedSolidId: 7,
contextObjectId: 8,
columnId: 9,
roofId: 10,
sectionLineId: 11,
};
/** Bit-Maske der Felder (0 = keine Einschränkung). */
const mask = (fields: readonly OwnerField[]): number => fields.reduce((m, f) => m | (1 << KIND[f]), 0);
/** Abbildung Modell → Client-Pixel (`toScreen` + `vbToClient` der PlanView). */
export interface ClientMap {
/** `rect.left + offX` */
left: number;
/** `rect.top + offY` */
top: number;
viewX: number;
viewY: number;
scale: number;
}
export class PlanPickIndex {
private id = 0;
readonly prims: readonly Primitive[];
constructor(private readonly plan: Plan) {
this.prims = plan.primitives;
}
/** Kern-Index (lazy beim ersten Abfragen gebaut). */
private ix(): number {
if (this.id) return this.id;
const c = core();
const parts = planParts(this.plan);
this.id = c.pick_index_build(heldSegs(parts, false));
if (!this.id) this.id = c.pick_index_build(heldSegs(parts, true));
return this.id;
}
/** Kern-Index freigeben (danach baut eine Abfrage ihn neu). */
release(): void {
if (this.id) core().pick_index_release(this.id);
this.id = 0;
}
/**
* Nächstes Segment einer 2D-Zeichnung (`line` mit `drawingId`) mit Abstand < `maxDist` (Meter):
* Index und Abstand, oder null.
*/
nearestSegment(m: Vec2, maxDist: number): { i: number; dist: number } | null {
const f = core().pick_nearest_segment(this.ix(), m.x, m.y, maxDist);
return f.length === 2 ? { i: f[0], dist: f[1] } : null;
}
/** Alle solchen Segmente mit Abstand < `maxDist`, nächste zuerst. */
segmentsNear(m: Vec2, maxDist: number): Array<{ i: number; dist: number }> {
const f = core().pick_segments_near(this.ix(), m.x, m.y, maxDist);
const out: Array<{ i: number; dist: number }> = [];
for (let k = 0; k + 1 < f.length; k += 2) out.push({ i: f[k], dist: f[k + 1] });
return out;
}
/**
* Polygone, die `m` enthalten, oberstes (zuletzt gezeichnetes) zuerst; mit `fields` nur solche
* mit einer nicht-leeren Id eines dieser Felder.
*/
polygonsAt(m: Vec2, ...fields: OwnerField[]): number[] {
return Array.from(core().pick_polygons_at(this.ix(), m.x, m.y, mask(fields)));
}
/** Oberstes Polygon unter `m` (s. {@link polygonsAt}) oder null. */
topPolygon(m: Vec2, ...fields: OwnerField[]): number | null {
const l = this.polygonsAt(m, ...fields);
return l.length ? l[0] : null;
}
/** Unterstes (zuerst gezeichnetes) Polygon unter `m` oder null. */
bottomPolygon(m: Vec2, ...fields: OwnerField[]): number | null {
const l = this.polygonsAt(m, ...fields);
return l.length ? l[l.length - 1] : null;
}
/**
* Nächste Symbol-Linie mit einer Id aus `lineFields` (bzw. Bogen über die Sehne `from → to` mit
* `arcFields`) zum Client-Punkt, Abstand in Pixeln < `maxPx`; erster bei Gleichstand.
*/
nearestSymbolPx(lineFields: OwnerField[], arcFields: OwnerField[], map: ClientMap, client: { x: number; y: number }, maxPx: number): number | null {
const i = core().pick_nearest_symbol_px(this.ix(), mask(lineFields), mask(arcFields), map.left, map.top, map.viewX, map.viewY, map.scale, client.x, client.y, maxPx);
return i >= 0 ? i : null;
}
/**
* Kreise/Bögen der 2D-Zeichnung (`drawingCircle`/`drawingArc` mit `drawingId`), deren Ring
* näher als `tolPx` Pixel liegt (gefüllte Kreise auch innen; Bögen nur in ihrer Spanne mit
* `tolPx`-Saum) — in Plan-Reihenfolge, Abstand in Pixeln.
*/
ringsNear(m: Vec2, pxPerM: number, tolPx: number): Array<{ i: number; dpx: number }> {
const f = core().pick_rings_near(this.ix(), m.x, m.y, pxPerM, tolPx);
const out: Array<{ i: number; dpx: number }> = [];
for (let k = 0; k + 1 < f.length; k += 2) out.push({ i: f[k], dpx: f[k + 1] });
return out;
}
/** Primitive, deren `field` in `ids` liegt — in Plan-Reihenfolge. */
ownedBy(field: OwnerField, ids: Iterable<string>): Primitive[] {
const list = [...ids];
if (list.length === 0) return [];
const hits = core().pick_owned_by(this.ix(), KIND[field], list.map((s) => "\u0000" + s).join(""));
return Array.from(hits, (i) => this.prims[i]);
}
}
-75
View File
@@ -1,75 +0,0 @@
import { describe, it, expect } from "vitest";
import type { Primitive } from "../generatePlan";
import { buildSegmentIndex, nearestSegment } from "./segmentIndex";
const line = (ax: number, ay: number, bx: number, by: number, drawingId = "d"): Primitive => ({
kind: "line",
a: { x: ax, y: ay },
b: { x: bx, y: by },
cls: "draw2d",
weightMm: 0.18,
drawingId,
});
function bruteForce(prims: Primitive[], m: { x: number; y: number }, maxDist: number): number | null {
let best: number | null = null;
let bestDist = maxDist;
prims.forEach((p, i) => {
if (p.kind !== "line" || !p.drawingId) return;
const dx = p.b.x - p.a.x, dy = p.b.y - p.a.y;
const len2 = dx * dx + dy * dy;
const t = len2 > 0 ? Math.max(0, Math.min(1, ((m.x - p.a.x) * dx + (m.y - p.a.y) * dy) / len2)) : 0;
const d = Math.hypot(m.x - (p.a.x + t * dx), m.y - (p.a.y + t * dy));
if (d < bestDist) {
bestDist = d;
best = i;
}
});
return best;
}
describe("segmentIndex", () => {
it("liefert dasselbe Ergebnis wie die lineare Suche (Zufallsdaten)", () => {
let seed = 1;
const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
const prims: Primitive[] = [];
for (let i = 0; i < 20000; i++) {
const x = rnd() * 1000, y = rnd() * 1000;
prims.push(line(x, y, x + (rnd() - 0.5) * 20, y + (rnd() - 0.5) * 20));
}
// Ein sehr langes Segment (landet in der Überlauf-Liste) + ein Nicht-2D-Strich.
prims.push(line(-5000, -5000, 5000, 5000));
prims.push({ ...line(500, 500, 501, 501), drawingId: undefined } as Primitive);
const idx = buildSegmentIndex(prims)!;
expect(idx.long.length).toBe(1);
for (let k = 0; k < 500; k++) {
const m = { x: rnd() * 1100 - 50, y: rnd() * 1100 - 50 };
expect(nearestSegment(idx, prims, m, 3)).toBe(bruteForce(prims, m, 3));
}
});
it("null ohne indizierbare Linien", () => {
expect(buildSegmentIndex([])).toBeNull();
});
it("findet nichts ausserhalb der Toleranz", () => {
const prims = [line(0, 0, 10, 0)];
const idx = buildSegmentIndex(prims)!;
expect(nearestSegment(idx, prims, { x: 5, y: 0.5 }, 1)).toBe(0);
expect(nearestSegment(idx, prims, { x: 5, y: 2 }, 1)).toBeNull();
expect(nearestSegment(idx, prims, { x: 500, y: 500 }, 1)).toBeNull();
});
});
describe("segmentsNear (alle Treffer, nächster zuerst)", () => {
it("liefert alle Segmente in Reichweite, sortiert, und entspricht der linearen Suche", async () => {
const { segmentsNear } = await import("./segmentIndex");
const prims: Primitive[] = [line(0, 0, 10, 0, "a"), line(0, 0.5, 10, 0.5, "b"), line(0, 5, 10, 5, "c"), line(-2000, -2000, 2000, 2000, "long")];
for (let i = 0; i < 300; i++) prims.push(line(50 + i, 50, 51 + i, 51, `f${i}`));
const idx = buildSegmentIndex(prims)!;
const hits = segmentsNear(idx, prims, { x: 5, y: 0.2 }, 1);
expect(hits.map((h) => (prims[h.i] as any).drawingId)).toEqual(["a", "b"].concat(hits.length > 2 ? ["long"] : []).slice(0, hits.length));
expect(hits[0].dist).toBeLessThanOrEqual(hits[1].dist);
expect(hits.every((h) => h.dist < 1)).toBe(true);
});
});
-163
View File
@@ -1,163 +0,0 @@
// Uniformes Raster über die 'line'-Primitive eines Plans (Modell-Meter), damit
// Nächstes-Segment-Abfragen unter dem Cursor nur die Segmente der umliegenden
// Zellen prüfen statt ALLE Primitive. Ein Kataster-Import liefert 3,7 Mio.
// Segmente; die frühere lineare Suche lief bei JEDER Mausbewegung über alle.
//
// Speicher als CSR (Zell-Offsets + flacher Index-Array, Typed Arrays) statt
// eines Arrays pro Zelle: Millionen kleiner JS-Arrays wären selbst teuer.
import type { Vec2 } from "../../model/types";
import type { Primitive } from "../generatePlan";
export interface SegmentIndex {
minX: number;
minY: number;
cell: number;
cols: number;
rows: number;
/** cellStart[c]..cellStart[c+1] = Bereich in `items` für Zelle c. */
cellStart: Uint32Array;
/** Primitiv-Indizes, nach Zelle gruppiert. */
items: Uint32Array;
/** Segmente, deren Bounding-Box zu viele Zellen überdeckt — immer geprüft. */
long: Uint32Array;
}
/** Ziel: im Mittel so viele Segmente je Zelle. */
const TARGET_PER_CELL = 8;
/** Obergrenze der Zellzahl (Speicher für `cellStart`). */
const MAX_CELLS = 4_000_000;
/** Ab so vielen überdeckten Zellen landet ein Segment in `long` statt im Raster. */
const MAX_CELLS_PER_SEGMENT = 1024;
/** Ob ein Primitiv in den Index gehört (2D-Zeichenlinien, s. Hover-Teilpunkte). */
const indexed = (p: Primitive): p is Extract<Primitive, { kind: "line" }> =>
p.kind === "line" && !!p.drawingId;
export function buildSegmentIndex(prims: readonly Primitive[]): SegmentIndex | null {
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
let n = 0;
for (const p of prims) {
if (!indexed(p)) continue;
n++;
minX = Math.min(minX, p.a.x, p.b.x);
maxX = Math.max(maxX, p.a.x, p.b.x);
minY = Math.min(minY, p.a.y, p.b.y);
maxY = Math.max(maxY, p.a.y, p.b.y);
}
if (n === 0) return null;
const w = Math.max(maxX - minX, 1e-6);
const h = Math.max(maxY - minY, 1e-6);
const cellCount = Math.min(MAX_CELLS, Math.max(1, Math.ceil(n / TARGET_PER_CELL)));
let cell = Math.sqrt((w * h) / cellCount);
if (!(cell > 0)) cell = Math.max(w, h);
const cols = Math.max(1, Math.ceil(w / cell));
const rows = Math.max(1, Math.ceil(h / cell));
const cx = (x: number) => Math.min(cols - 1, Math.max(0, Math.floor((x - minX) / cell)));
const cy = (y: number) => Math.min(rows - 1, Math.max(0, Math.floor((y - minY) / cell)));
// Zwei Durchläufe (zählen, dann füllen) — jedes Segment landet in jeder Zelle,
// die seine Bounding-Box berührt.
const counts = new Uint32Array(cols * rows + 1);
const long: number[] = [];
for (let i = 0; i < prims.length; i++) {
const p = prims[i];
if (!indexed(p)) continue;
const x0 = cx(Math.min(p.a.x, p.b.x)), x1 = cx(Math.max(p.a.x, p.b.x));
const y0 = cy(Math.min(p.a.y, p.b.y)), y1 = cy(Math.max(p.a.y, p.b.y));
if ((x1 - x0 + 1) * (y1 - y0 + 1) > MAX_CELLS_PER_SEGMENT) {
long.push(i);
continue;
}
for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) counts[y * cols + x + 1]++;
}
const longSet = new Set(long);
for (let c = 1; c < counts.length; c++) counts[c] += counts[c - 1];
const cellStart = counts;
const fill = cellStart.slice(0, cols * rows);
const items = new Uint32Array(cellStart[cols * rows]);
for (let i = 0; i < prims.length; i++) {
const p = prims[i];
if (!indexed(p) || longSet.has(i)) continue;
const x0 = cx(Math.min(p.a.x, p.b.x)), x1 = cx(Math.max(p.a.x, p.b.x));
const y0 = cy(Math.min(p.a.y, p.b.y)), y1 = cy(Math.max(p.a.y, p.b.y));
for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) items[fill[y * cols + x]++] = i;
}
return { minX, minY, cell, cols, rows, cellStart, items, long: Uint32Array.from(long) };
}
export function pointSegDist(p: Vec2, a: Vec2, b: Vec2): number {
const dx = b.x - a.x, dy = b.y - a.y;
const len2 = dx * dx + dy * dy;
let t = len2 > 0 ? ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2 : 0;
t = Math.max(0, Math.min(1, t));
return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));
}
/**
* Nächstes indiziertes Segment zu `m` (Modell-Meter) mit Abstand < `maxDist`
* (Modell-Meter), oder null. Liefert den Primitiv-Index.
*/
export function nearestSegment(
index: SegmentIndex,
prims: readonly Primitive[],
m: Vec2,
maxDist: number,
): number | null {
const { minX, minY, cell, cols, rows, cellStart, items, long } = index;
let best: number | null = null;
let bestDist = maxDist;
const consider = (i: number) => {
const p = prims[i] as Extract<Primitive, { kind: "line" }>;
const d = pointSegDist(m, p.a, p.b);
if (d < bestDist) {
bestDist = d;
best = i;
}
};
for (const i of long) consider(i);
const x0 = Math.floor((m.x - maxDist - minX) / cell);
const x1 = Math.floor((m.x + maxDist - minX) / cell);
const y0 = Math.floor((m.y - maxDist - minY) / cell);
const y1 = Math.floor((m.y + maxDist - minY) / cell);
if (x1 < 0 || y1 < 0 || x0 >= cols || y0 >= rows) return best;
for (let y = Math.max(0, y0); y <= Math.min(rows - 1, y1); y++) {
for (let x = Math.max(0, x0); x <= Math.min(cols - 1, x1); x++) {
const c = y * cols + x;
for (let k = cellStart[c]; k < cellStart[c + 1]; k++) consider(items[k]);
}
}
return best;
}
/** ALLE indizierten Segmente mit Abstand < `maxDist` (Modell-Einheiten), nächste zuerst. */
export function segmentsNear(
index: SegmentIndex,
prims: readonly Primitive[],
m: Vec2,
maxDist: number,
): Array<{ i: number; dist: number }> {
const { minX, minY, cell, cols, rows, cellStart, items, long } = index;
const found = new Map<number, number>();
const consider = (i: number) => {
const p = prims[i] as Extract<Primitive, { kind: "line" }>;
const d = pointSegDist(m, p.a, p.b);
if (d < maxDist) found.set(i, d);
};
for (const i of long) consider(i);
const x0 = Math.floor((m.x - maxDist - minX) / cell);
const x1 = Math.floor((m.x + maxDist - minX) / cell);
const y0 = Math.floor((m.y - maxDist - minY) / cell);
const y1 = Math.floor((m.y + maxDist - minY) / cell);
if (!(x1 < 0 || y1 < 0 || x0 >= cols || y0 >= rows)) {
for (let y = Math.max(0, y0); y <= Math.min(rows - 1, y1); y++) {
for (let x = Math.max(0, x0); x <= Math.min(cols - 1, x1); x++) {
const c = y * cols + x;
for (let k = cellStart[c]; k < cellStart[c + 1]; k++) consider(items[k]);
}
}
}
return [...found].map(([i, dist]) => ({ i, dist })).sort((a, b) => a.dist - b.dist);
}
+4 -4
View File
@@ -5,7 +5,7 @@ import { describe, it, expect } from "vitest";
import type { Drawing2D, Project } from "../../model/types";
import { generatePlan, materializeUnderlay } from "../generatePlan";
import { marqueeHitDrawings } from "./geometry";
import { buildSegmentIndex, nearestSegment } from "./segmentIndex";
import { PlanPickIndex } from "./planPick";
import { buildDrawingIndex, marqueeHitUnderlay, nearestInDrawings } from "./underlayAccess";
let seed = 7;
@@ -53,12 +53,12 @@ describe("underlayAccess == Primitiv-Varianten", () => {
it("nächstes Segment == Segment-Index der Primitive", () => {
const idx = buildDrawingIndex(under)!;
const segIdx = buildSegmentIndex(normal.primitives)!;
const segIdx = new PlanPickIndex(normal);
for (let k = 0; k < 400; k++) {
const m = { x: rnd() * 540 - 20, y: rnd() * 540 - 20 };
const a = nearestInDrawings(idx, m, 2);
const bi = nearestSegment(segIdx, normal.primitives, m, 2);
const b = bi === null ? null : (normal.primitives[bi] as any);
const bi = segIdx.nearestSegment(m, 2);
const b = bi === null ? null : (normal.primitives[bi.i] as any);
expect(a?.drawing.id ?? null).toBe(b?.drawingId ?? null);
}
});
+177
View File
@@ -0,0 +1,177 @@
// Testhilfe ([K3d]): deterministische Zufalls-Primitive aller Arten für Gleichheitstests der
// Kern-Verbraucher (Render-Szene, Auswahl, SVG-Export) — Polygone mit allen Schraffur-Arten,
// unterdrückten Kanten, Farben in allen Schreibweisen, verkettete 2D-Zeichenlinien, Zickzack,
// Motiv, Strichmuster (fehlend/null/Liste), Bögen, Kreise, Texte, Bilder, gedimmt/deckend.
import type { HatchRender, Plan, Primitive } from "./generatePlan";
import type { Vec2 } from "../model/types";
export function rng(seed: number): () => number {
let s = seed >>> 0;
return () => {
s = (s + 0x6d2b79f5) >>> 0;
let t = s;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const COLORS = ["#1a1a1a", "#fff", "#ff000080", "#abc", "#12345", "none", "", "black", "red", " White ", "rgb(1,2,3)", "#zz0000", "#336699", "transparent"];
const CLS = ["wall", "door-leaf", "door-swing", "wall-axis", "context-line", "draw2d", "window-glass", "stair-line"];
const PATTERNS: HatchRender["pattern"][] = ["diagonal", "crosshatch", "insulation", "custom", "solid", "none"];
export function randomPrims(seed: number, n: number, span = 20): Primitive[] {
const r = rng(seed);
const pick = <T,>(a: readonly T[]): T => a[Math.floor(r() * a.length)];
const pt = (): Vec2 => ({ x: (r() - 0.5) * span, y: (r() - 0.5) * span });
const dash = (): number[] | null | undefined => {
const k = r();
return k < 0.4 ? undefined : k < 0.6 ? null : k < 0.7 ? [] : [0.5 + r(), 0.2 + r(), ...(r() < 0.3 ? [0.1] : [])];
};
const greyed = (): boolean | undefined => (r() < 0.6 ? undefined : r() < 0.5);
const hatch = (): HatchRender => {
const h: HatchRender = {
pattern: pick(PATTERNS),
scale: r() < 0.1 ? 0 : 0.5 + r() * 2,
angle: Math.floor(r() * 180),
color: pick(COLORS),
lineWeight: r() < 0.2 ? 0 : 0.05 + r() * 0.3,
dash: r() < 0.6 ? null : [0.5 + r(), 0.3],
};
if (r() < 0.2) h.kind = pick(["vector", "image", "gradient"] as const);
if (r() < 0.2) h.lines = "random";
if (r() < 0.3) h.origin = pt();
if (h.pattern === "custom") h.motif = { points: [{ x: 0, y: 0 }, { x: 0.5, y: 0.3 }, { x: 1, y: 0 }], length: 1 };
return h;
};
const ring = (): Vec2[] => {
const c = pt();
const k = 3 + Math.floor(r() * 5);
const rad = 0.3 + r() * 3;
const out: Vec2[] = [];
for (let i = 0; i < k; i++) {
const a = (i / k) * Math.PI * 2;
out.push({ x: c.x + Math.cos(a) * rad * (0.6 + r() * 0.4), y: c.y + Math.sin(a) * rad * (0.6 + r() * 0.4) });
}
return out;
};
const out: Primitive[] = [];
const ids = ["d1", "d2", "d3", ""];
let last: Vec2 | null = null;
while (out.length < n) {
const k = r();
if (k < 0.25) {
const pts = ring();
const p: Primitive = {
kind: "polygon",
pts: r() < 0.05 ? pts.slice(0, 2) : pts,
fill: pick(COLORS),
stroke: pick(COLORS),
strokeWidthMm: r() < 0.1 ? 0 : 0.1 + r() * 0.5,
hatch: hatch(),
};
if (r() < 0.4) delete (p as { hatch?: HatchRender }).hatch;
const g = greyed();
if (g !== undefined) p.greyed = g;
if (r() < 0.2) p.opacity = r();
if (r() < 0.4) p.noStrokeEdges = Array.from({ length: Math.floor(r() * pts.length) }, () => Math.floor(r() * pts.length * 2) - 1);
if (r() < 0.3) p.wallId = `w${Math.floor(r() * 5)}`;
else if (r() < 0.3) p.roomId = `r${Math.floor(r() * 5)}`;
else if (r() < 0.2) p.drawingId = pick(ids);
if (r() < 0.1) p.stairId = "s1";
out.push(p);
} else if (k < 0.7) {
// Linien, oft als Zug (Ende = nächster Anfang).
const a: Vec2 = last && r() < 0.6 ? { ...last } : pt();
const b: Vec2 = { x: a.x + (r() - 0.5) * 3, y: a.y + (r() - 0.5) * 3 };
const p: Primitive = { kind: "line", a, b, cls: pick(CLS), weightMm: r() < 0.5 ? 0.25 : 0.18 };
const d = dash();
if (d !== undefined) p.dash = d;
if (r() < 0.5) p.color = pick(COLORS);
if (r() < 0.6) p.drawingId = pick(ids);
else if (r() < 0.3) p.openingId = "o1";
if (r() < 0.05) p.zigzag = { amplitude: 0.5 + r(), wavelength: 2 + r() * 3 };
else if (r() < 0.05) p.motif = { points: [{ x: 0, y: 0 }, { x: 0.5, y: 0.5 }, { x: 1, y: 0 }], length: 1 + r() };
const g = greyed();
if (g !== undefined) p.greyed = g;
out.push(p);
last = b;
} else if (k < 0.78) {
const c = pt();
const rad = 0.5 + r();
const a0 = r() * 6;
const a1 = a0 + r() * 3;
const p: Primitive = {
kind: "arc",
center: c,
from: { x: c.x + rad * Math.cos(a0), y: c.y + rad * Math.sin(a0) },
to: { x: c.x + rad * Math.cos(a1), y: c.y + rad * Math.sin(a1) },
r: rad,
cls: pick(CLS),
weightMm: 0.18,
};
const d = dash();
if (d !== undefined) p.dash = d;
if (r() < 0.5) p.openingId = "o2";
const g = greyed();
if (g !== undefined) p.greyed = g;
out.push(p);
} else if (k < 0.86) {
const circle = r() < 0.5;
const c = pt();
const g = greyed();
const d = dash();
if (circle) {
const p: Primitive = { kind: "drawingCircle", center: c, r: 0.2 + r() * 2, fill: pick(COLORS), stroke: pick(COLORS), weightMm: 0.25 };
if (d !== undefined) p.dash = d;
if (g !== undefined) p.greyed = g;
if (r() < 0.7) p.drawingId = pick(ids);
out.push(p);
} else {
const p: Primitive = { kind: "drawingArc", center: c, r: 0.2 + r() * 2, a0: (r() - 0.5) * 10, a1: (r() - 0.5) * 10, stroke: pick(COLORS), weightMm: 0.25 };
if (d !== undefined) p.dash = d;
if (g !== undefined) p.greyed = g;
if (r() < 0.7) p.drawingId = pick(ids);
out.push(p);
}
} else if (k < 0.92) {
const g = greyed();
if (r() < 0.5) {
const p = {
kind: "text",
at: pt(),
doc: { version: 1, paragraphs: [{ align: "center", runs: [{ text: `Raum ${out.length}`, marks: {} }] }] },
extraLines: r() < 0.5 ? [{ text: "12.5 m²", align: "center" }] : [],
basePt: 8 + Math.floor(r() * 6),
color: pick(COLORS),
roomId: "r1",
} as unknown as Primitive;
if (g !== undefined) (p as { greyed?: boolean }).greyed = g;
out.push(p);
} else {
const p: Primitive = { kind: "drawingText", at: pt(), text: `T ${out.length}\nzwei`, heightM: 0.2 + r(), angle: r() < 0.5 ? 0 : r(), color: pick(COLORS), drawingId: pick(ids) };
if (r() < 0.3) p.wrapWidth = 1 + r() * 2;
if (g !== undefined) p.greyed = g;
out.push(p);
}
} else if (k < 0.95) {
const a = pt();
out.push({ kind: "drawingImage", min: a, max: { x: a.x + 1, y: a.y + 1 }, src: "data:image/png;base64,AA", opacity: r(), drawingId: pick(ids) });
} else if (k < 0.97) {
out.push({ kind: "drawingTextPath", pathPts: [pt(), pt()], text: "Pfad", heightM: 0.3, color: "#000", drawingId: "d1" });
} else {
// Exakte Wiederholung des letzten Polygons mit unterdrückten Kanten (Naht über Grenzen).
const sq: Vec2[] = [pt()];
sq.push({ x: sq[0].x + 1, y: sq[0].y }, { x: sq[0].x + 1, y: sq[0].y + 1 }, { x: sq[0].x, y: sq[0].y + 1 });
const sq2 = [sq[1], { x: sq[1].x + 1, y: sq[1].y }, { x: sq[1].x + 1, y: sq[2].y }, sq[2]];
out.push({ kind: "polygon", pts: sq, fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [1], wallId: "wx" } as Primitive);
out.push({ kind: "polygon", pts: sq2, fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [3], wallId: "wy" } as Primitive);
}
}
return out;
}
export function planOf(primitives: Primitive[], greyedRanges?: Array<[number, number]>): Plan {
return { primitives, bounds: { minX: -10, minY: -10, maxX: 10, maxY: 10 }, ...(greyedRanges ? { greyedRanges } : {}) };
}
-118
View File
@@ -1,118 +0,0 @@
import { describe, expect, it } from "vitest";
import { readFileSync, writeFileSync } from "node:fs";
import { encodeRenderScene, SCENE_BIN_VERSION } from "./renderSceneBin";
import type { RScene } from "./toRenderScene";
const FIXTURE = new URL("../../src-tauri/render2d/tests/fixtures/scene_v1.bin", import.meta.url);
/** Beispielszene; MUSS mit `sample()` in `src-tauri/render2d/src/scene_bin.rs` übereinstimmen. */
function sampleScene(): RScene {
return {
fills: [
{ pts: [[0, 0], [4, 0], [4, 3]], color: [0.5, 0.25, 0.75, 1], z: 0 },
{ pts: [[1.5, 1.5], [2.5, 1.5], [2.5, 2.5], [1.5, 2.5]], color: [1, 1, 1, 0.5], z: 7 },
],
outlines: [{ pts: [[0, 0], [4, 0], [4, 3]], color: [0, 0, 0, 1], widthMm: 0.25, dash: [2, 1], z: 1 }],
polylines: [
{ pts: [[0, 0], [1, 1]], color: [0.25, 0.25, 0.25, 1], widthMm: 0.5, dash: null, z: 2 },
{ pts: [[5, 5], [6, 5], [6, 6]], color: [0.5, 0.5, 0.5, 1], widthMm: 1, dash: [1], z: 3, widthScreen: true },
],
arcs: [{ center: [1, 1], from: [2, 1], to: [1, 2], r: 1, color: [1, 0, 0, 1], widthMm: 0.125 }],
lines: [{ a: [0, 0], b: [2600000.5, 1200000.25], color: [0, 0.5, 0, 1], widthMm: 0.35, dash: [3, 1, 0.5, 1], z: 4 }],
texts: [
{ pos: [1, 2], content: "Küche 12,5 m²", sizeMm: 2.5, color: [0, 0, 0, 1], align: "center" },
{ pos: [3, 4], content: "", sizeMm: 2, color: [0, 0, 0, 1], align: "right" },
{ pos: [5, 6], content: "A", sizeMm: 1, color: [0, 0, 1, 1], align: "left" },
],
images: [],
bounds: { minX: 0, minY: 0, maxX: 1, maxY: 1 },
};
}
const empty = (): RScene => ({
fills: [], outlines: [], polylines: [], arcs: [], lines: [], texts: [], images: [],
bounds: { minX: 0, minY: 0, maxX: 0, maxY: 0 },
});
describe("encodeRenderScene", () => {
it("liefert byte-genau die Fixture, die der Rust-Dekodierer liest", () => {
const bytes = encodeRenderScene(sampleScene());
if (process.env.UPDATE_SCENE_FIXTURE) writeFileSync(FIXTURE, bytes);
expect(Buffer.from(bytes).equals(readFileSync(FIXTURE))).toBe(true);
});
it("schreibt Kopf, Zähler und die exakte Länge", () => {
const bytes = encodeRenderScene(sampleScene());
const h = new Uint32Array(bytes.buffer, bytes.byteOffset, 12);
expect(String.fromCharCode(...bytes.subarray(0, 4))).toBe("DR2S");
expect(h[1]).toBe(SCENE_BIN_VERSION);
expect([...h.subarray(2, 8)]).toEqual([2, 1, 2, 1, 1, 3]);
const nPts = 3 + 4 + 3 + 2 + 3 + 3 + 2 + 3;
expect(h[8]).toBe(nPts);
expect(h[9]).toBe(2 + 1 + 4);
expect(h[10]).toBe(new TextEncoder().encode("Küche 12,5 m²A").length);
const words = 2 * 6 + 8 + 2 * 9 + 7 + 7 + 3 * 8;
expect(bytes.length).toBe(48 + nPts * 16 + 7 * 4 + words * 4 + h[10]);
});
it("behält Koordinaten als f64 (LV95-gross)", () => {
const s = empty();
s.lines.push({ a: [2600000.123456, 1200000.654321], b: [0, 0], color: [0, 0, 0, 1], widthMm: 0.1, z: 0 });
const bytes = encodeRenderScene(s);
const pts = new Float64Array(bytes.buffer, bytes.byteOffset + 48, 4);
expect(pts[0]).toBe(2600000.123456);
expect(pts[1]).toBe(1200000.654321);
});
it("kodiert die leere Szene als reinen Kopf und wirft bei Unsinn nicht", () => {
expect(encodeRenderScene(empty()).length).toBe(48);
const s = empty();
s.fills.push({ pts: [], color: [NaN, 0, 0, 1], z: -1 });
s.texts.push({ pos: [Infinity, 0], content: "\u{1F600}", sizeMm: 1, color: [0, 0, 0, 1], align: "left" });
expect(() => encodeRenderScene(s)).not.toThrow();
});
});
/** Zufallsszene (deterministisch) für die Messung. */
function bigScene(nLines: number, nFills: number, nTexts: number): RScene {
let seed = 42;
const rnd = () => ((seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) >>> 8) / 16777216;
const s = empty();
for (let i = 0; i < nLines; i++) {
const x = rnd() * 500, y = rnd() * 500;
s.lines.push({ a: [x, y], b: [x + rnd(), y + rnd()], color: [0.1, 0.1, 0.1, 1], widthMm: 0.18, dash: i % 10 === 0 ? [2, 1] : null, z: i % 50 });
}
for (let i = 0; i < nFills; i++) {
const x = rnd() * 500, y = rnd() * 500;
s.fills.push({ pts: [0, 1, 2, 3, 4, 5].map((k) => [x + k * rnd(), y + k * rnd()] as [number, number]), color: [0.8, 0.8, 0.75, 1], z: i % 50 });
}
for (let i = 0; i < nTexts; i++) {
s.texts.push({ pos: [rnd() * 500, rnd() * 500], content: `Raum ${i} 12,5 m²`, sizeMm: 2, color: [0, 0, 0, 1], align: "center" });
}
return s;
}
describe("Messung JSON gegen Binär (Kodierung, Node)", () => {
it("kodiert kleine und grosse Szene und gibt die Zeiten aus", () => {
const best = (f: () => unknown) => {
let b = Infinity;
for (let i = 0; i < 5; i++) {
const t = performance.now();
f();
b = Math.min(b, performance.now() - t);
}
return b;
};
for (const [name, sc] of [
["klein (200 Linien, 50 Füllungen, 20 Texte)", bigScene(200, 50, 20)],
["gross (200000 Linien, 20000 Füllungen, 1000 Texte)", bigScene(200_000, 20_000, 1000)],
] as const) {
const json = JSON.stringify(sc);
const bin = encodeRenderScene(sc);
const tj = best(() => JSON.stringify(sc));
const tb = best(() => encodeRenderScene(sc));
console.log(`${name}: JSON ${(json.length / 1024) | 0} KB ${tj.toFixed(2)} ms | binär ${(bin.length / 1024) | 0} KB ${tb.toFixed(2)} ms`);
expect(bin.length).toBeLessThan(json.length);
}
});
});
-157
View File
@@ -1,157 +0,0 @@
// Binärkodierung der Render-Szene (`RScene`) für render2d — Gegenstück zu
// `src-tauri/render2d/src/scene_bin.rs` (dort steht die Formatbeschreibung; beide Seiten
// müssen Version und Aufbau gleich halten, die gemeinsame Fixture
// `src-tauri/render2d/tests/fixtures/scene_v1.bin` prüft das in beiden Tests).
//
// Zweiphasig: erst Zähler (Punkte, Strichmuster, Strings), dann ein einziger Puffer, in den
// über typisierte Sichten geschrieben wird (kein DataView je Wert, keine Zwischenarrays).
// Little-endian setzen wir voraus (alle Zielplattformen); `LITTLE_ENDIAN` prüft das einmal.
import type { RScene, RTextAlign } from "./toRenderScene";
export const SCENE_BIN_VERSION = 1;
const HEADER_BYTES = 48;
const ALIGN: Record<RTextAlign, number> = { left: 0, center: 1, right: 2 };
const LITTLE_ENDIAN = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
const textEncoder = new TextEncoder();
/** Kodiert die Szene (ohne `images`/`bounds`, die der Renderer nicht kennt). */
export function encodeRenderScene(scene: RScene): Uint8Array {
if (!LITTLE_ENDIAN) throw new Error("Szenenkodierung setzt Little-Endian voraus");
const { fills, outlines, polylines, arcs, lines, texts } = scene;
let nPts = 0;
let nDash = 0;
for (const f of fills) nPts += f.pts.length;
for (const o of outlines) {
nPts += o.pts.length;
nDash += o.dash?.length ?? 0;
}
for (const p of polylines) {
nPts += p.pts.length;
nDash += p.dash?.length ?? 0;
}
for (const a of arcs) nDash += a.dash?.length ?? 0;
for (const l of lines) nDash += l.dash?.length ?? 0;
nPts += arcs.length * 3 + lines.length * 2 + texts.length;
const strs: Uint8Array[] = new Array(texts.length);
let strBytes = 0;
for (let i = 0; i < texts.length; i++) {
strs[i] = textEncoder.encode(texts[i].content);
strBytes += strs[i].length;
}
const words =
fills.length * 6 + outlines.length * 8 + polylines.length * 9 + arcs.length * 7 + lines.length * 7 + texts.length * 8;
const ptsOff = HEADER_BYTES;
const dashOff = ptsOff + nPts * 16;
const recOff = dashOff + nDash * 4;
const strOff = recOff + words * 4;
const total = strOff + strBytes;
if (total > 0xffffffff || nPts > 0xffffffff) throw new Error("Szene zu gross für das Binärformat");
const buf = new ArrayBuffer(total);
const bytes = new Uint8Array(buf);
const hdr = new Uint32Array(buf, 0, HEADER_BYTES / 4);
const pts = new Float64Array(buf, ptsOff, nPts * 2);
const dash = new Float32Array(buf, dashOff, nDash);
const u32 = new Uint32Array(buf, recOff, words);
const f32 = new Float32Array(buf, recOff, words);
bytes.set([0x44, 0x52, 0x32, 0x53], 0); // "DR2S"
hdr[1] = SCENE_BIN_VERSION;
hdr[2] = fills.length;
hdr[3] = outlines.length;
hdr[4] = polylines.length;
hdr[5] = arcs.length;
hdr[6] = lines.length;
hdr[7] = texts.length;
hdr[8] = nPts;
hdr[9] = nDash;
hdr[10] = strBytes;
hdr[11] = 0;
let pi = 0; // Index in pts (Doubles)
let di = 0; // Index in dash
let w = 0; // Index in u32/f32
const ring = (a: ArrayLike<readonly [number, number]>) => {
for (let i = 0; i < a.length; i++) {
pts[pi++] = a[i][0];
pts[pi++] = a[i][1];
}
};
const col = (c: readonly number[]) => {
f32[w++] = c[0];
f32[w++] = c[1];
f32[w++] = c[2];
f32[w++] = c[3];
};
const dashes = (d: readonly number[] | null | undefined): number => {
if (!d || d.length === 0) return 0;
for (let i = 0; i < d.length; i++) dash[di++] = d[i];
return d.length;
};
for (const f of fills) {
u32[w++] = f.pts.length;
u32[w++] = f.z >>> 0;
col(f.color);
ring(f.pts);
}
for (const o of outlines) {
u32[w++] = o.pts.length;
u32[w++] = o.z >>> 0;
f32[w++] = o.widthMm;
u32[w++] = dashes(o.dash);
col(o.color);
ring(o.pts);
}
for (const p of polylines) {
u32[w++] = p.pts.length;
u32[w++] = p.z >>> 0;
f32[w++] = p.widthMm;
u32[w++] = dashes(p.dash);
u32[w++] = p.widthScreen ? 1 : 0;
col(p.color);
ring(p.pts);
}
for (const a of arcs) {
f32[w++] = a.r;
f32[w++] = a.widthMm;
u32[w++] = dashes(a.dash);
col(a.color);
pts[pi++] = a.center[0];
pts[pi++] = a.center[1];
pts[pi++] = a.from[0];
pts[pi++] = a.from[1];
pts[pi++] = a.to[0];
pts[pi++] = a.to[1];
}
for (const l of lines) {
f32[w++] = l.widthMm;
u32[w++] = dashes(l.dash);
u32[w++] = l.z >>> 0;
col(l.color);
pts[pi++] = l.a[0];
pts[pi++] = l.a[1];
pts[pi++] = l.b[0];
pts[pi++] = l.b[1];
}
let so = 0;
for (let i = 0; i < texts.length; i++) {
const t = texts[i];
f32[w++] = t.sizeMm;
u32[w++] = ALIGN[t.align] ?? 0;
u32[w++] = so;
u32[w++] = strs[i].length;
col(t.color);
pts[pi++] = t.pos[0];
pts[pi++] = t.pos[1];
bytes.set(strs[i], strOff + so);
so += strs[i].length;
}
return bytes;
}
+70
View File
@@ -0,0 +1,70 @@
// Render-Szene aus dem Kern ([K3d], `core/src/plan_scene.rs`): Verkettung der 2D-Zeichenlinien,
// Kantennaht über Polygon-Grenzen, gedimmte Bereiche ohne Klonen, Binärszene passt zur
// Objekt-Szene, verdrängte Puffer werden neu abgelegt. (Bitgleich zur früheren TS-Fassung
// geprüft: Beispielprojekt, 400 Zufallslisten, grosses Projekt — s. TODO [K3d].)
import { describe, expect, it } from "vitest";
import { planSceneBin, planToRenderScene } from "./toRenderScene";
import { generatePlan, generateVisibleLevelsPlan, materializeGreyed, materializeUnderlay } from "./generatePlan";
import type { Primitive } from "./generatePlan";
import { sampleProject } from "../model/sampleProject";
import { flattenCategories } from "../model/types";
import { planOf, randomPrims } from "./randomPrims.testing";
import { planParts } from "./planParts";
import { core } from "../engine/coreWasm";
const codes = new Set(flattenCategories(sampleProject.layers).map((c) => c.code));
const line = (ax: number, ay: number, bx: number, by: number, extra: Partial<Primitive> = {}): Primitive =>
({ kind: "line", a: { x: ax, y: ay }, b: { x: bx, y: by }, cls: "draw2d", weightMm: 0.25, drawingId: "d", ...extra }) as Primitive;
describe("planToRenderScene (Kern)", () => {
it("verkettet 2D-Zeichenlinien zu Polylinie bzw. Umriss", () => {
const open = planToRenderScene(planOf([line(0, 0, 1, 0), line(1, 0, 1, 1), line(5, 5, 6, 6, { drawingId: undefined })]));
expect(open.polylines.map((p) => p.pts.length)).toEqual([3]);
expect(open.lines.length).toBe(1);
const ring = planToRenderScene(planOf([line(0, 0, 1, 0), line(1, 0, 1, 1), line(1, 1, 0, 0)]));
expect(ring.outlines.map((o) => o.pts.length)).toEqual([3]);
expect(ring.outlines[0].dash).toBeNull();
});
it("näht unterdrückte Kanten zweier Polygone zu einem Ring", () => {
const a: Primitive = { kind: "polygon", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }], fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [1] } as Primitive;
const b: Primitive = { kind: "polygon", pts: [{ x: 1, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 1 }, { x: 1, y: 1 }], fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [3] } as Primitive;
const s = planToRenderScene(planOf([a, b]));
expect(s.fills.length).toBe(2);
expect(s.outlines.length).toBe(1);
expect(s.outlines[0].pts.length).toBe(6);
expect(s.outlines[0].z).toBe(3);
});
it("gedimmte Bereiche wirken wie materialisiertes `greyed`", () => {
for (let seed = 1; seed < 30; seed++) {
const prims = randomPrims(seed, 40);
const plan = planOf(prims, [[2, 15], [20, 33]]);
expect(JSON.stringify(planToRenderScene(plan))).toBe(JSON.stringify(planToRenderScene(materializeGreyed(plan, true))));
expect(Buffer.from(planSceneBin(plan)).equals(Buffer.from(planSceneBin(materializeGreyed(plan, true))))).toBe(true);
}
const over = generateVisibleLevelsPlan(sampleProject, "og", codes, undefined, "mittel", false, false, () => ({ render: true, greyed: true, locked: false }), 100, true);
const plan = materializeUnderlay(over);
expect(plan.greyedRanges?.length).toBeGreaterThan(0);
expect(JSON.stringify(planToRenderScene(plan))).toBe(JSON.stringify(planToRenderScene(materializeGreyed(plan, true))));
});
it("Binärszene: Zähler wie die Objekt-Szene", () => {
const plan = generatePlan(sampleProject, "eg", codes);
const s = planToRenderScene(plan);
const b = planSceneBin(plan);
const h = new Uint32Array(b.buffer, b.byteOffset, 12);
expect(String.fromCharCode(...b.subarray(0, 4))).toBe("DR2S");
expect([...h.subarray(1, 8)]).toEqual([1, s.fills.length, s.outlines.length, s.polylines.length, s.arcs.length, s.lines.length, s.texts.length]);
expect(s.fills.length).toBeGreaterThan(10);
});
it("verdrängte Puffer werden neu abgelegt", () => {
const plan = generatePlan(sampleProject, "eg", codes);
const before = planSceneBin(plan);
for (const buf of planParts(plan).bufs) core().plan_buf_release(buf.hold);
expect(Buffer.from(planSceneBin(plan)).equals(Buffer.from(before))).toBe(true);
});
});
+157 -426
View File
@@ -1,30 +1,24 @@
// Flacht einen {@link Plan} (die eine Wahrheit aus generatePlan) auf das
// GPU-nahe Szenenformat des nativen render2d-Renderers ab: Füllpolygone,
// Umrisse, Linien und Textzeilen. Text wird zeilenweise geflacht (Rich-Text-Doc
// + Live-Zusatzzeilen) — die echten Glyphen rastert der Rust-Renderer über
// einen GPU-Glyphen-Atlas (glyphon/cosmic-text), keine Vektor-Ersatzschrift.
// Render-Szene eines {@link Plan} für render2d (Browser über WASM/WebGPU, natives Fenster über
// `push_native_scene`) und für den Druck-/SVG-Export. Die Geometrie (Füllungen, Umrisse,
// Polylinien, Bögen, Linien samt Maler-Reihenfolge `z`, Verkettung, Kantennaht, Schraffur-Läufe,
// Zickzack/Motiv) rechnet der Kern direkt aus dem Plan-Puffer ([K3d], `src-tauri/core/src/
// plan_scene.rs`, über die Abschnitte aus `planParts.ts`) — ohne Umweg über `Primitive[]`. Hier
// bleibt das Text-Layout (Rich-Text-Zeilen + Live-Zusatzzeilen, die Glyphen rastert render2d)
// und das Durchreichen eingebetteter Bilder.
//
// Das erzeugte Objekt matcht 1:1 die serde-Structs render2d::types::Scene
// Das Szenen-Objekt matcht 1:1 die serde-Structs render2d::types::Scene
// { fills:[{pts,color}], outlines:[{pts,color,widthMm,dash}],
// polylines:[{pts,color,widthMm,dash}], arcs:[{center,from,to,r,color,widthMm,dash}],
// lines:[{a,b,color,widthMm,dash}], texts:[{pos,content,sizeMm,color,align}] }
// mit Point = [x,y] (Meter) und Rgba = [r,g,b,a] (0..1).
//
// Bögen werden NICHT hier tessellliert: der Rust-Renderer zeichnet sie
// mathematisch exakt per SDF-Fragment-Shader (`shaders::ARC_WGSL`, eine
// analytische Instanz je Bogen) — bei jeder Vergrößerung ein echter Kreis statt
// eines Vielecks, ohne Neu-Tessellierung. Strichmuster
// (`dash`, mm Papier) werden ebenfalls unverändert durchgereicht — das geometrische
// Zerschneiden in Teilstücke (`applyDashRuns`-Algorithmus) passiert erst NACH der
// Bogen-Tessellierung in Rust (`tessellate::split_dash`), damit die Phase über die
// gesamte (ggf. verkettete oder adaptiv tessellierte) Strecke durchläuft.
// mit Point = [x,y] (Meter) und Rgba = [r,g,b,a] (0..1). Bögen bleiben unvortesselliert
// (render2d zeichnet sie per SDF-Shader), Strichmuster (Papier-mm) werden durchgereicht.
import type { Plan, Primitive } from "./generatePlan";
import { applyDashRuns, buildHatchRuns, zigzagPoints, motifPoints, DASH_MM_TO_M } from "./glPlan/glPlanHatch";
import type { Plan } from "./generatePlan";
import { inGreyedRange } from "./generatePlan";
import { docToLines, wrapDocToLines } from "../text/renderHtml";
import { docFromText } from "../text/richText";
type LinePrim = Extract<Primitive, { kind: "line" }>;
import { core } from "../engine/coreWasm";
import { greyedFlat, planParts, withPlanParts } from "./planParts";
export type RPoint = [number, number];
export type RRgba = [number, number, number, number];
@@ -133,57 +127,15 @@ export interface RScene {
bounds: RBounds;
}
const DEFAULT_LINE = "#1a1a1a";
/**
* Strichfarben/-deckkraft je CSS-Klasse — Spiegel der `.plan-svg .<cls>`-Regeln
* in styles.css: Im SVG-Pfad ÜBERSTIMMT eine CSS-`stroke`-Property das inline
* gesetzte `stroke`-Attribut (Präsentationsattribut), d. h. für diese Klassen
* gilt IMMER die CSS-Farbe. Klassen ohne CSS-`stroke` (draw2d, stair-*,
* context-line) behalten die Modell-Farbe; context-line trägt zusätzlich
* `opacity: 0.7`, wall-axis `opacity: 0.85`.
*/
const CLS_STROKE: Record<string, string> = {
"door-leaf": "#1a1a1a",
"door-swing": "#1a1a1a",
"door-frame": "#1a1a1a",
"window-glass": "#1a1a1a",
"wall-axis": "#4a453e", // var(--accent) des hellen Standard-Themes
};
const CLS_OPACITY: Record<string, number> = {
"wall-axis": 0.85,
"context-line": 0.7,
};
/**
* Fester Grauton gedimmter (greyed) Primitive — ECHTE Umfärbung statt
* Deckkraft (dünne Haarlinien auf dem hellen Zeichenblatt wären bei reiner
* Transparenz kaum erkennbar gedimmt). Gleicher Ton wie GREYED_COLOR in
* PlanView.tsx / GREY_RGB in glPlanCompile.ts (#8c8c8c ≈ 0.549).
* Fester Grauton gedimmter (greyed) Texte — gleicher Ton wie GREYED_COLOR in PlanView.tsx und
* `GREY_RGB` im Kern (#8c8c8c ≈ 0.549).
*/
const GREY_RGB = 0.549;
/** Farbe mit Klassen-Deckkraft multiplizieren, bei Greyed-Dimmung auf den festen Grauton umfärben. */
function withOpacity(col: RRgba, cls: string | undefined, greyed: boolean | undefined): RRgba {
const o = cls ? CLS_OPACITY[cls] ?? 1 : 1;
const rgb: RRgba = greyed ? [GREY_RGB, GREY_RGB, GREY_RGB, col[3]] : col;
return o === 1 ? rgb : [rgb[0], rgb[1], rgb[2], rgb[3] * o];
}
/**
* Wie `withOpacity`, aber für FLÄCHEN-Füllung: gedimmte Flächen bleiben WEISS
* statt grau eingefärbt — nur der Umriss (weiterhin `withOpacity`) macht das
* Element als gedimmt erkennbar (Nutzer-Wunsch: "im Hintergrund nicht als
* graue Fläche gefüllt, sondern weiss mit nur den Linien sichtbar").
*/
function withFillOpacity(col: RRgba, greyed: boolean | undefined): RRgba {
return greyed ? [1, 1, 1, col[3]] : col;
}
/** Strichfarbe einer line/arc-Primitive: CSS-Klassen-Farbe > Modell-Farbe > Tinte. */
function strokeColorFor(cls: string | undefined, color: string | undefined): RRgba {
const css = cls ? CLS_STROKE[cls] : undefined;
return toRgba(css ?? color ?? DEFAULT_LINE, 1) ?? [0.1, 0.1, 0.1, 1];
/** Textfarbe gedimmt: auf den festen Grauton umfärben (Deckkraft bleibt). */
function greyedColor(col: RRgba, greyed: boolean | undefined): RRgba {
return greyed ? [GREY_RGB, GREY_RGB, GREY_RGB, col[3]] : col;
}
/** 1 Punkt (pt) in Papier-Millimetern. */
@@ -194,8 +146,7 @@ const PT_TO_MM = 25.4 / 72;
* Modus: dort belegt 1 pt Schrift (1/72)·0.0254·100 Modell-Meter. Der native
* Renderer rechnet im Anzeigemodus mit `paper_scale_n = 100`, damit ist
* `sizeMm = pt · PT_TO_MM` exakt die Browser-Darstellung. Für Aufrufer MIT
* Massstabskontext (z. B. PDF-Export) übersteuert `planToRenderScene`s
* `paperScaleN`-Parameter diesen Default — siehe `mmToM` dort.
* Massstabskontext (z. B. PDF-Export) übersteuert `paperScaleN` diesen Default.
*/
const STAMP_DEFAULT_N = 100;
@@ -208,7 +159,7 @@ const NAMED: Record<string, string> = {
transparent: "none",
};
/** Hex/Named-Farbe → [r,g,b,a] in 0..1, oder null bei "none"/leer. */
/** Hex/Named-Farbe → [r,g,b,a] in 0..1, oder null bei "none"/leer (Kern: `plan_scene::to_rgba`). */
function toRgba(input: string | undefined, alpha = 1): RRgba | null {
if (!input) return null;
let h = input.trim().toLowerCase();
@@ -232,318 +183,23 @@ function toRgba(input: string | undefined, alpha = 1): RRgba | null {
return [r, g, b, a];
}
/** Zwei Modell-Punkte (Meter) als gleich behandeln (Verkettungs-Toleranz). */
function samePt(a: RPoint, b: RPoint): boolean {
return Math.abs(a[0] - b[0]) < 1e-6 && Math.abs(a[1] - b[1]) < 1e-6;
}
/** Gleicher Linienstil (für das Verketten aufeinanderfolgender 2D-Zeichenlinien). */
function sameLineStyle(a: LinePrim, b: LinePrim): boolean {
return (
a.cls === b.cls &&
a.weightMm === b.weightMm &&
(a.color ?? "") === (b.color ?? "") &&
JSON.stringify(a.dash ?? null) === JSON.stringify(b.dash ?? null)
);
}
/**
* Zerlegt einen Polygon-Ring in zusammenhängende Läufe SICHTBARER Kanten (die
* `noStroke`-Kanten werden ausgelassen). Jeder Lauf beginnt an einer sichtbaren
* Kante, deren Vorgänger unterdrückt ist. Portiert aus PlanView.visibleEdgeRuns —
* so bekommen die inneren Ecken eine Gehrung statt Stumpfkappen.
* Textzeilen und eingebettete Bilder eines Plans in Zeichenreihenfolge. Layout wie im SVG-Pfad
* (PlanView, case "text"): Rich-Text-Zeilen + Live-Zusatzzeilen, Block vertikal um den Anker
* zentriert, Zeilenvorschub 1.3·Basisgröße; Einzeltexte (`drawingText`) top-down ab `at` mit
* `heightM` als Basisgrösse. `paperScaleN` (1:N) rechnet Papier-mm in Modell-Meter um.
*/
function visibleEdgeRuns(pts: RPoint[], noStroke: number[]): RPoint[][] {
const n = pts.length;
const skip = new Set(noStroke.map((i) => ((i % n) + n) % n));
if (skip.size >= n || n < 2) return [];
const visible = (i: number) => !skip.has(((i % n) + n) % n);
const runs: RPoint[][] = [];
for (let s = 0; s < n; s++) {
if (!visible(s) || visible(s - 1 + n)) continue; // kein Lauf-Anfang
const run: RPoint[] = [pts[s]];
let j = s;
while (visible(j) && j - s < n) {
run.push(pts[(j + 1) % n]);
j++;
}
runs.push(run);
}
return runs;
}
/**
* Näht sichtbare Kantenläufe ÜBER Polygon-Grenzen hinweg zusammen: Läufe mit
* koinzidenten Endpunkten (und GENAU zwei beteiligten Enden — T-Stösse bleiben
* unangetastet) werden zu einer Kette verbunden, ggf. mit Richtungsumkehr.
* Schliesst sich eine Kette, wird sie als geschlossener Ring markiert. So
* bekommt eine Wandecke, deren zwei Schenkel aus VERSCHIEDENEN Wand-Polygonen
* stammen, dieselbe Gehrung wie die inneren Ecken eines einzelnen Laufs
* (statt zweier Stumpfkappen, die eine Kerbe bilden).
*/
function stitchRuns(runs: RPoint[][]): { pts: RPoint[]; closed: boolean }[] {
const eps = 1e-5;
const key = (p: RPoint) => `${Math.round(p[0] / eps)},${Math.round(p[1] / eps)}`;
// Endpunkt-Belegung zählen: verkettet wird nur, wo genau ZWEI Enden liegen.
const endCount = new Map<string, number>();
for (const r of runs) {
for (const p of [r[0], r[r.length - 1]]) {
endCount.set(key(p), (endCount.get(key(p)) ?? 0) + 1);
}
}
const joinable = (p: RPoint) => endCount.get(key(p)) === 2;
const pool = runs.map((pts) => ({ pts, used: false }));
const out: { pts: RPoint[]; closed: boolean }[] = [];
for (const seed of pool) {
if (seed.used) continue;
seed.used = true;
let chain = seed.pts;
let extended = true;
while (extended && !(chain.length > 2 && samePt(chain[0], chain[chain.length - 1]))) {
extended = false;
const head = chain[0];
const tail = chain[chain.length - 1];
for (const cand of pool) {
if (cand.used) continue;
const cs = cand.pts[0];
const ce = cand.pts[cand.pts.length - 1];
if (joinable(tail) && samePt(tail, cs)) {
chain = chain.concat(cand.pts.slice(1));
} else if (joinable(tail) && samePt(tail, ce)) {
chain = chain.concat([...cand.pts].reverse().slice(1));
} else if (joinable(head) && samePt(head, ce)) {
chain = cand.pts.concat(chain.slice(1));
} else if (joinable(head) && samePt(head, cs)) {
chain = [...cand.pts].reverse().concat(chain.slice(1));
} else {
continue;
}
cand.used = true;
extended = true;
break;
}
}
const closed = chain.length > 3 && samePt(chain[0], chain[chain.length - 1]);
out.push({ pts: closed ? chain.slice(0, -1) : chain, closed });
}
return out;
}
/**
* Wandelt einen Plan in eine native render2d-Szene um. Zusammenhängende Umriss-
* und Zeichnungskanten werden zu OFFENEN Polylinien verkettet (gehrte Ecken);
* nur genuin einzelne Segmente (Türblätter, Referenzlinien) bleiben `lines`.
*
* `paperScaleN` ist der Massstab-Nenner N (1:N), mit dem die vertikale
* Zeilenposition mehrzeiliger Stempel-Texte in Modell-Meter umgerechnet wird
* (Papier-mm sind massstabsunabhängig, ihre Weltgrösse aber nicht — analog zu
* PlanViews `nRef`, s. `PlanView.tsx` case "text"). Default 100 für Aufrufer
* ohne Massstabskontext (WASM-Viewport, `nativeSync.ts`).
*/
export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): RScene {
export function planSceneTexts(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): { texts: RText[]; images: RImage[] } {
const mmToM = paperScaleN / 1000; // Papier-mm → Modell-Meter beim gewählten Massstab.
const fills: RFill[] = [];
const outlines: ROutline[] = [];
const polylines: RPolyline[] = [];
const arcs: RArc[] = [];
const lines: RLine[] = [];
const texts: RText[] = [];
const images: RImage[] = [];
// Sichtbare Umriss-Läufe werden erst GESAMMELT (nach Stil gruppiert) und am
// Ende über Polygon-Grenzen hinweg zusammengenäht — erst dadurch bekommen
// Wand-zu-Wand-Ecken (zwei Polygone!) eine Gehrung statt einer Kerbe.
const edgeRunGroups = new Map<string, { color: RRgba; widthMm: number; runs: RPoint[][]; z: number }>();
const collectEdgeRun = (run: RPoint[], color: RRgba, widthMm: number, z: number) => {
const k = `${color.join(",")}|${widthMm}`;
let g = edgeRunGroups.get(k);
if (!g) {
g = { color, widthMm, runs: [], z };
edgeRunGroups.set(k, g);
}
g.runs.push(run);
// Die Kette zeichnet, wenn ihr SPÄTESTER Beitrag im SVG zeichnen würde.
g.z = Math.max(g.z, z);
};
// Maler-Reihenfolge: läuft in EXAKT der Reihenfolge mit, in der der SVG-Pfad
// die Elemente zeichnet (Primitive in Array-Reihenfolge; je Polygon Füllung →
// Schraffur → Umriss). Jedes emittierte Szenen-Element bekommt das nächste z.
let zc = 0;
// Laufender, verketteter 2D-Zeichnungs-Zug (gleiche drawingId + Stil, End-an-Start).
let curPts: RPoint[] | null = null;
let curSrc: LinePrim | null = null;
const flushRun = () => {
if (curPts && curSrc && curPts.length >= 2) {
const col = withOpacity(strokeColorFor(curSrc.cls, curSrc.color), curSrc.cls, curSrc.greyed);
const closed = curPts.length > 2 && samePt(curPts[0], curPts[curPts.length - 1]);
const dash = curSrc.dash ?? null;
if (closed) {
outlines.push({ pts: curPts.slice(0, -1), color: col, widthMm: curSrc.weightMm, dash, z: zc++ });
} else {
polylines.push({ pts: curPts, color: col, widthMm: curSrc.weightMm, dash, z: zc++ });
}
}
curPts = null;
curSrc = null;
};
for (const p of plan.primitives) {
if (p.kind === "polygon") {
flushRun();
const pts: RPoint[] = p.pts.map((v) => [v.x, v.y]);
if (pts.length < 2) continue;
// Füllung
const fillCol = toRgba(p.fill, 1);
if (fillCol && pts.length >= 3) {
fills.push({ pts, color: withFillOpacity(fillCol, p.greyed), z: zc++ });
}
// Schraffur: die aufs Polygon geclippten Musterlinien wie im Browser
// (glPlanHatch — identische Geometrie), als Polylinien. "none"/"solid"
// brauchen keine Linien (solid deckt die Füllung farbig ab). Bild-/
// Verlauf-Schraffuren (kind==="image"/"gradient") kann die render2d-
// Szene nicht tragen (keine Textur/kein echter Verlauf) → FALLBACK: nur
// die neutrale Poché-Füllung (oben), keine Musterlinien. Der Random-
// Untermodus läuft transparent über `buildHatchRuns` (Streu-Striche).
if (
p.hatch &&
p.hatch.kind !== "image" &&
p.hatch.kind !== "gradient" &&
p.hatch.pattern !== "none" &&
p.hatch.pattern !== "solid"
) {
const hatchCol = withOpacity(
toRgba(p.hatch.color, 1) ?? [0.1, 0.1, 0.1, 1],
undefined,
p.greyed,
);
// Strichbreite: ein GEWÖHNLICHER Papier-mm-Stift (0.02 mm), wie jede
// andere Linie — nicht mehr an die Musterkachel/Bildschirm-px
// gekoppelt (siehe RPolyline.widthScreen-Kommentar).
const hatchMm = p.hatch.lineWeight > 0 ? p.hatch.lineWeight : 0.13;
const runs = applyDashRuns(buildHatchRuns(p.pts, p.hatch), p.hatch.dash);
// Alle Musterläufe eines Polygons teilen EIN z (überlappen einander nicht).
const hatchZ = zc++;
for (const run of runs) {
if (run.length >= 2) {
polylines.push({
pts: run.map((v) => [v.x, v.y]),
color: hatchCol,
widthMm: hatchMm,
z: hatchZ,
});
}
}
}
// Umriss
const strokeColRaw = toRgba(p.stroke, 1);
if (strokeColRaw && p.strokeWidthMm > 0) {
const strokeCol = withOpacity(strokeColRaw, undefined, p.greyed);
const suppressed = p.noStrokeEdges ?? [];
if (suppressed.length === 0) {
// Ganzer Ring → geschlossener, gehrter Umriss.
outlines.push({ pts, color: strokeCol, widthMm: p.strokeWidthMm, z: zc++ });
} else {
// Nur die sichtbaren Kanten — sammeln, die Naht ans Ende verschoben.
const runZ = zc++;
for (const run of visibleEdgeRuns(pts, suppressed)) {
collectEdgeRun(run, strokeCol, p.strokeWidthMm, runZ);
}
}
}
} else if (p.kind === "line") {
if (p.zigzag) {
// Zickzack-Linie: als Polylinie tesselliert (render2d kennt keinen
// Zickzack-Primitiv). amplitude/wavelength sind Papier-mm → Modell-Meter
// über dieselbe Kopplung wie Strichmuster (DASH_MM_TO_M). Nicht verketten.
flushRun();
const amp = p.zigzag.amplitude * DASH_MM_TO_M;
const wav = p.zigzag.wavelength * DASH_MM_TO_M;
const zpts = zigzagPoints(p.a, p.b, amp, wav);
const col = withOpacity(strokeColorFor(p.cls, p.color), p.cls, p.greyed);
if (zpts.length >= 2) {
polylines.push({
pts: zpts.map((v) => [v.x, v.y]),
color: col,
widthMm: p.weightMm,
z: zc++,
});
}
} else if (p.motif) {
// Custom-Motiv: entlang der Linie gekachelt (Papier-mm → Modell-Meter via
// DASH_MM_TO_M) → Polylinie. Nicht verketten (wie Zickzack).
flushRun();
const mpts = motifPoints(p.a, p.b, p.motif, DASH_MM_TO_M);
const col = withOpacity(strokeColorFor(p.cls, p.color), p.cls, p.greyed);
if (mpts.length >= 2) {
polylines.push({
pts: mpts.map((v) => [v.x, v.y]),
color: col,
widthMm: p.weightMm,
z: zc++,
});
}
} else if (p.drawingId) {
// Aufeinanderfolgende 2D-Zeichenlinien gleicher drawingId/Stil verketten.
const a: RPoint = [p.a.x, p.a.y];
const b: RPoint = [p.b.x, p.b.y];
if (curPts && curSrc && sameLineStyle(curSrc, p) && samePt(curPts[curPts.length - 1], a)) {
curPts.push(b);
} else {
flushRun();
curPts = [a, b];
curSrc = p;
}
} else {
// Genuin einzelnes Segment (Türblatt, Referenzlinie, Symbol) → Stumpfkappen ok.
flushRun();
const col = withOpacity(strokeColorFor(p.cls, p.color), p.cls, p.greyed);
lines.push({ a: [p.a.x, p.a.y], b: [p.b.x, p.b.y], color: col, widthMm: p.weightMm, dash: p.dash ?? null, z: zc++ });
}
} else if (p.kind === "arc") {
flushRun();
// Farbe wie im SVG: CSS-Klassen-Regel (z. B. .door-swing → #1a1a1a).
const col = withOpacity(strokeColorFor(p.cls, undefined), p.cls, p.greyed);
// Bogen unvortessellliert an Rust übergeben (`RArc`) — die exakte runde
// Darstellung (analytischer SDF-Shader, `ARC_WGSL`) und ein evtl. Strich-
// muster übernimmt der native Renderer (`compile_scene`) drüben.
arcs.push({
center: [p.center.x, p.center.y],
from: [p.from.x, p.from.y],
to: [p.to.x, p.to.y],
r: p.r,
color: col,
widthMm: p.weightMm,
dash: p.dash ?? null,
});
} else if (p.kind === "drawingCircle" || p.kind === "drawingArc") {
// Der native Renderer hat kein Kreis-/Bogen-Primitiv → hier tessellieren
// (der SVG-Pfad zeichnet sie glatt). Kreis = voller Umlauf, Bogen = a0..a1.
flushRun();
const col = withOpacity(toRgba(p.stroke, 1) ?? [0.1, 0.1, 0.1, 1], undefined, p.greyed);
const TAU = Math.PI * 2;
const a0 = p.kind === "drawingArc" ? p.a0 : 0;
const sweep = p.kind === "drawingArc" ? (((p.a1 - p.a0) % TAU) + TAU) % TAU : TAU;
const N = Math.max(8, Math.ceil(sweep / (Math.PI / 32)));
const pts: RPoint[] = [];
for (let i = 0; i <= N; i++) {
const t = a0 + (sweep * i) / N;
pts.push([p.center.x + p.r * Math.cos(t), p.center.y + p.r * Math.sin(t)]);
}
polylines.push({ pts, color: col, widthMm: p.weightMm, dash: p.dash ?? null, z: zc++ });
} else if (p.kind === "text") {
// "text": zeilenweise flachen — die ECHTEN Glyphen rastert der Rust-
// Renderer über einen GPU-Glyphen-Atlas (glyphon, dieselbe Font-Familie
// wie im Browser). Layout identisch zum SVG-Pfad in PlanView (case
// "text"): Rich-Text-Zeilen + Live-Zusatzzeilen, Block vertikal um den
// Anker zentriert, Zeilenvorschub 1.3·Basisgröße.
flushRun();
const defCol = withOpacity(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], undefined, p.greyed);
const ranges = plan.greyedRanges;
const prims = plan.primitives;
for (let i = 0; i < prims.length; i++) {
const p = prims[i];
if (p.kind === "text") {
const greyed = p.greyed || inGreyedRange(ranges, i);
const defCol = greyedColor(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], greyed);
// unitPerPt = PT_TO_MM → tspan.fontSize ist direkt die Papier-mm-Größe.
const docLines = docToLines(p.doc, {
x: 0,
@@ -560,14 +216,8 @@ export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAUL
// Runs einer Zeile werden zusammengelegt (ein Buffer je Zeile);
// Größe/Farbe des größten bzw. ersten Runs gelten für die Zeile.
content: line.tspans.map((t) => t.text).join(""),
sizeMm: line.tspans.length
? Math.max(...line.tspans.map((t) => t.fontSize))
: baseMm,
color: withOpacity(
toRgba(line.tspans[0]?.fill ?? p.color, 1) ?? defCol,
undefined,
p.greyed,
),
sizeMm: line.tspans.length ? Math.max(...line.tspans.map((t) => t.fontSize)) : baseMm,
color: greyedColor(toRgba(line.tspans[0]?.fill ?? p.color, 1) ?? defCol, greyed),
align: line.align,
});
}
@@ -592,14 +242,11 @@ export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAUL
});
}
} else if (p.kind === "drawingText") {
// Modellverankerter Einzeltext (Text-Werkzeug/DXF-Import) — wie "text"
// oben zeilenweise geflacht, aber TOP-DOWN ab `at` (kein vertikal
// zentrierter Block) und `heightM` (Modell-Meter) als Basisgrösse statt
// `basePt` (Papier-Punkt) — der Text bleibt so, wie bisher, massstabsfrei
// an der Modellgeometrie verankert (kein Papier-Punkt-Bezug nötig).
flushRun();
// Modellverankerter Einzeltext (Text-Werkzeug/DXF-Import): top-down ab `at`, `heightM`
// (Modell-Meter) als Basisgrösse — massstabsfrei an der Modellgeometrie verankert.
const greyed = p.greyed || inGreyedRange(ranges, i);
const doc = p.doc ?? docFromText(p.text, p.marks ?? {});
const defCol = withOpacity(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], undefined, p.greyed);
const defCol = greyedColor(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], greyed);
const unitPerPt = PT_TO_MM * mmToM; // pt (Run-Override) -> Papier-mm -> Modell-Meter.
const basePt = unitPerPt > 0 ? p.heightM / unitPerPt : 0;
const lineHeight = p.heightM * 1.25;
@@ -618,48 +265,132 @@ export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAUL
if (k > 0) dy += line.lineHeight;
const content = line.tspans.map((t) => t.text).join("");
if (!content.trim()) return;
const sizeM = line.tspans.length
? Math.max(...line.tspans.map((t) => t.fontSize))
: p.heightM;
const sizeM = line.tspans.length ? Math.max(...line.tspans.map((t) => t.fontSize)) : p.heightM;
texts.push({
pos: [p.at.x, p.at.y - dy],
content,
sizeMm: unitPerPt > 0 ? sizeM / mmToM : sizeM,
color: withOpacity(
toRgba(line.tspans[0]?.fill ?? p.color, 1) ?? defCol,
undefined,
p.greyed,
),
color: greyedColor(toRgba(line.tspans[0]?.fill ?? p.color, 1) ?? defCol, greyed),
align: line.align,
});
});
} else if (p.kind === "drawingImage") {
// Eingebettetes Rasterbild — keine Rust-Textur (s. `RImage`); wird vom
// GPU-Backend ignoriert (`useGpuRenderer` schaltet bei Bildern im Plan
// ohnehin auf den SVG-Pfad um), `sceneToPrintSvg.ts` liest es für den PDF-Export.
flushRun();
images.push({
min: [p.min.x, p.min.y],
max: [p.max.x, p.max.y],
src: p.src,
opacity: p.opacity,
});
// Eingebettetes Rasterbild — keine Rust-Textur (s. `RImage`); `sceneToPrintSvg.ts` liest es.
images.push({ min: [p.min.x, p.min.y], max: [p.max.x, p.max.y], src: p.src, opacity: p.opacity });
}
}
flushRun();
// Gesammelte Umriss-Läufe polygonübergreifend zusammennähen: geschlossene
// Ketten als Ring (Gehrung auch an der Naht), offene als Polylinie.
for (const g of edgeRunGroups.values()) {
for (const chain of stitchRuns(g.runs)) {
if (chain.pts.length < 2) continue;
if (chain.closed) {
outlines.push({ pts: chain.pts, color: g.color, widthMm: g.widthMm, z: g.z });
} else {
polylines.push({ pts: chain.pts, color: g.color, widthMm: g.widthMm, z: g.z });
}
}
}
return { fills, outlines, polylines, arcs, lines, texts, images, bounds: { ...plan.bounds } };
return { texts, images };
}
const ALIGN: Record<RTextAlign, number> = { left: 0, center: 1, right: 2 };
const textEncoder = new TextEncoder();
/** Leere render2d-Szene (nur Kopf), falls der Kern nichts liefern kann. */
function emptySceneBin(): Uint8Array {
const b = new Uint8Array(48);
b.set([0x44, 0x52, 0x32, 0x53], 0); // "DR2S"
new DataView(b.buffer).setUint32(4, 1, true);
return b;
}
/**
* render2d-Szene (Binärformat v1, `render2d/src/scene_bin.rs`) für `set_scene_bin` bzw.
* `push_native_scene`. Geometrie aus dem Kern, Texte aus {@link planSceneTexts};
* `plan.greyedRanges` gelten wie materialisiertes `greyed`.
*/
export function planSceneBin(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): Uint8Array {
const { texts } = planSceneTexts(plan, paperScaleN);
const nums = new Float64Array(texts.length * 9);
const strs = texts.map((t) => textEncoder.encode(t.content));
let nBytes = 0;
for (const s of strs) nBytes += s.length;
const bytes = new Uint8Array(nBytes);
let o = 0;
texts.forEach((t, i) => {
nums.set([t.pos[0], t.pos[1], t.sizeMm, t.color[0], t.color[1], t.color[2], t.color[3], ALIGN[t.align] ?? 0, strs[i].length], i * 9);
bytes.set(strs[i], o);
o += strs[i].length;
});
const greyed = greyedFlat(plan);
const out = withPlanParts(planParts(plan), (segs) => core().plan_scene_bin(segs, greyed, nums, bytes));
return out.length ? out : emptySceneBin();
}
type SceneGeometry = Pick<RScene, "fills" | "outlines" | "polylines" | "arcs" | "lines">;
/** Verlustfreie Kern-Szene (Format s. `plan_scene.rs`) → Szenen-Objekte (Feldreihenfolge wie früher). */
function decodeSceneF64(f: Float64Array): SceneGeometry {
const out: SceneGeometry = { fills: [], outlines: [], polylines: [], arcs: [], lines: [] };
if (f.length < 5) return out;
let k = 5;
const pts = (n: number): RPoint[] => {
const r: RPoint[] = new Array(n);
for (let i = 0; i < n; i++, k += 2) r[i] = [f[k], f[k + 1]];
return r;
};
const color = (): RRgba => {
const c: RRgba = [f[k], f[k + 1], f[k + 2], f[k + 3]];
k += 4;
return c;
};
/** −2 fehlt (undefined) · −1 null · n Werte. */
const dash = (): number[] | null | undefined => {
const n = f[k++];
if (n === -2) return undefined;
if (n === -1) return null;
const d = Array.from(f.subarray(k, k + n));
k += n;
return d;
};
for (let i = 0; i < f[0]; i++) {
const n = f[k];
const z = f[k + 1];
k += 2;
const c = color();
out.fills.push({ pts: pts(n), color: c, z });
}
for (let j = 0; j < 2; j++) {
const list = j === 0 ? out.outlines : out.polylines;
for (let i = 0; i < f[1 + j]; i++) {
const n = f[k];
const z = f[k + 1];
const widthMm = f[k + 2];
k += 3;
const d = dash();
const c = color();
const p = pts(n);
list.push(d === undefined ? { pts: p, color: c, widthMm, z } : { pts: p, color: c, widthMm, dash: d, z });
}
}
for (let i = 0; i < f[3]; i++) {
const r = f[k];
const widthMm = f[k + 1];
k += 2;
const d = dash() ?? null;
const c = color();
const [center, from, to] = pts(3);
out.arcs.push({ center, from, to, r, color: c, widthMm, dash: d });
}
for (let i = 0; i < f[4]; i++) {
const z = f[k];
const widthMm = f[k + 1];
k += 2;
const d = dash() ?? null;
const c = color();
const [a, b] = pts(2);
out.lines.push({ a, b, color: c, widthMm, dash: d, z });
}
return out;
}
/**
* Plan → Render-Szene als Objekte (Druck-/SVG-Export, `dossier-cli plan --format json`).
* `paperScaleN` ist der Massstab-Nenner N (1:N) für die Zeilenlage der Texte (s.
* {@link planSceneTexts}).
*/
export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): RScene {
const greyed = greyedFlat(plan);
const geo = decodeSceneF64(withPlanParts(planParts(plan), (segs) => core().plan_scene_f64(segs, greyed)));
const { texts, images } = planSceneTexts(plan, paperScaleN);
return { ...geo, texts, images, bounds: { ...plan.bounds } };
}
+128 -84
View File
@@ -8,7 +8,7 @@
import type { Drawing2D, Project, Vec2, Wall } from "../model/types";
import { getWallType, wallTypeThickness } from "../model/types";
import { add, leftNormal, lineIntersect, normalize, scale, sub } from "../model/geometry";
import { add, leftNormal, normalize, scale, sub } from "../model/geometry";
import { wallReferenceOffset } from "../model/wall";
import { centroid as roomCentroid } from "../core";
import { columnFootprint } from "../core";
@@ -17,9 +17,9 @@ import type { SnapKind, SnapResult, SnapSettings } from "./types";
import { sampleBezierChain, sampleCatmullRom, sampleUniformBSpline } from "../core";
import { buildDrawingIndex, drawingsNear, isIndexable, pointSegDist__geometry_drawingIndex as pointSegDist, type DrawingIndex } from "../core";
import { sheetSnapSegments } from "./sheetSnapGeometry";
import { holdSnapSegments, releaseSnapSegments, snapOnSegments, type SegSnapCand } from "../core";
const dist = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y);
const mid = (a: Vec2, b: Vec2): Vec2 => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
/** Bildschirm-px-Bonus je Snap-Art: höher = gewinnt knappe Vergleiche. */
const PRIORITY: Record<SnapKind, number> = {
@@ -193,8 +193,89 @@ function snapDrawings(input: SnapInput, near?: { at: Vec2; r: number }): Drawing
return out;
}
/** Sammelt alle sichtbaren Strecken des Geschosses (Wandachsen + 2D-Segmente). */
/** Sammelt alle sichtbaren Strecken des Geschosses (Wandachsen + 2D-Segmente) samt Entwurf. */
function collectSegments(input: SnapInput, near?: { at: Vec2; r: number }): Seg[] {
const segs = baseSegments(input, near);
for (const seg of draftSegments(input)) segs.push(seg);
return segs;
}
/** Bereits gesetzte Draft-Segmente (Polylinie/Wand im Bau). */
function draftSegments(input: SnapInput): Seg[] {
const segs: Seg[] = [];
for (let i = 0; i < input.draftPoints.length - 1; i++) {
segs.push([input.draftPoints[i], input.draftPoints[i + 1]]);
}
return segs;
}
/**
* Was je Projekt/Geschoss/Sichtbarkeit gleich bleibt, einmal gesammelt (lief sonst bei jeder
* Mausbewegung über alle Wände, Räume, Treppen, Stützen): die Strecken ohne Entwurf (im Kern
* abgelegt, erst bei Bedarf), Raum-Stempel-Anker, Kreise/Bögen, Ellipsen-Mittelpunkte. Die
* letzten paar Einträge bleiben, ältere werden freigegeben.
*/
interface LevelSnap {
project: Project;
levelId: string;
codes: Set<string>;
/** Abgelegte Strecken im Kern (0 = noch nicht). */
hold: number;
anchors: Vec2[] | null;
circles: CircleGeom[] | null;
ellipses: Vec2[] | null;
}
const levelSnaps: LevelSnap[] = [];
const MAX_LEVEL_SNAPS = 4;
function levelSnap(input: SnapInput): LevelSnap {
let e = levelSnaps.find((h) => h.project === input.project && h.levelId === input.levelId && h.codes === input.visibleCodes);
if (!e) {
e = { project: input.project, levelId: input.levelId, codes: input.visibleCodes, hold: 0, anchors: null, circles: null, ellipses: null };
levelSnaps.push(e);
while (levelSnaps.length > MAX_LEVEL_SNAPS) releaseSnapSegments(levelSnaps.shift()!.hold);
}
return e;
}
function heldBaseSegments(input: SnapInput, fresh: boolean): number {
const e = levelSnap(input);
if (e.hold && !fresh) return e.hold;
releaseSnapSegments(e.hold);
e.hold = holdSnapSegments(baseSegments(input));
return e.hold;
}
/** Raum-Stempel-Anker (fixer Anker, sonst Flächenschwerpunkt) des Geschosses. */
function roomAnchors(input: SnapInput): Vec2[] {
const e = levelSnap(input);
if (!e.anchors) {
e.anchors = [];
for (const room of input.project.rooms ?? []) {
if (room.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(room.categoryCode)) continue;
if (room.boundary.length < 3) continue;
e.anchors.push(room.stampAnchor ?? roomCentroid(room.boundary));
}
}
return e.anchors;
}
function levelCircles(input: SnapInput): CircleGeom[] {
const e = levelSnap(input);
return (e.circles ??= collectCircles(input));
}
function ellipseCenters(input: SnapInput): Vec2[] {
const e = levelSnap(input);
if (!e.ellipses) {
e.ellipses = [];
for (const d of nonLineDrawings(input.project.drawings2d)) {
if (d.levelId !== input.levelId) continue;
if (!input.visibleCodes.has(d.categoryCode)) continue;
if (d.geom.shape === "ellipse") e.ellipses.push(d.geom.center);
}
}
return e.ellipses;
}
/** Sichtbare Strecken des Geschosses ohne Entwurf (Wandachsen, Schichtgrenzen, Umrisse, 2D). */
function baseSegments(input: SnapInput, near?: { at: Vec2; r: number }): Seg[] {
const segs: Seg[] = [];
for (const w of input.project.walls) {
if (w.floorId !== input.levelId) continue;
@@ -235,10 +316,6 @@ function collectSegments(input: SnapInput, near?: { at: Vec2; r: number }): Seg[
// Runde Stützen: s. collectCircles (Zentrum/Quadranten statt Vieleck-Kanten).
}
for (const d of snapDrawings(input, near)) drawingSegs(d, segs);
// Bereits gesetzte Draft-Segmente (Polylinie/Wand im Bau).
for (let i = 0; i < input.draftPoints.length - 1; i++) {
segs.push([input.draftPoints[i], input.draftPoints[i + 1]]);
}
return segs;
}
@@ -284,16 +361,6 @@ function collectCircles(input: SnapInput): CircleGeom[] {
return out;
}
/** Lotfußpunkt von p auf die Strecke a-b, auf das Segment geklemmt. */
function perpFoot(p: Vec2, a: Vec2, b: Vec2): Vec2 {
const dx = b.x - a.x, dy = b.y - a.y;
const len2 = dx * dx + dy * dy;
if (len2 < 1e-12) return a;
let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2;
t = Math.max(0, Math.min(1, t));
return { x: a.x + dx * t, y: a.y + dy * t };
}
// ── Verweil-Erkennung fürs Teilpunkte-Snapping ("divide") ───────────────────
// Modul-weiter Zustand (wie `lastCoalesceKey` in projectSlice.ts) statt in
// SnapInput/computeSnap-Parametern: computeSnap wird von mehreren, völlig
@@ -322,28 +389,14 @@ let acquiredParallelSeg: Seg | null = null;
const segKey = (seg: Seg): string =>
`${seg[0].x},${seg[0].y}|${seg[1].x},${seg[1].y}`;
/** Nächstgelegene Strecke zu `raw` innerhalb der Fangtoleranz (Meter), oder null. */
function nearestSegment(raw: Vec2, segs: Seg[], tolM: number): Seg | null {
let best: Seg | null = null;
let bestD = tolM;
for (const seg of segs) {
const d = dist(perpFoot(raw, seg[0], seg[1]), raw);
if (d < bestD) {
bestD = d;
best = seg;
}
}
return best;
}
/**
* Verankert/verwirft den Verweil-Zustand für den aktuellen Cursor und liefert
* die "freigegebene" Strecke (Teilpunkte fangbar), sobald der Cursor lange
* genug (`delayMs`) auf DERSELBEN Strecke geblieben ist — sonst `null`. Ein
* Streckenwechsel (auch zu "keine Strecke") setzt die Verweildauer zurück.
* `seg` ist die nächste Strecke innerhalb der Fangtoleranz (aus dem Kern) oder null.
*/
function updateDwell(raw: Vec2, segs: Seg[], delayMs: number, tolM: number): Seg | null {
const seg = nearestSegment(raw, segs, tolM);
function updateDwell(seg: Seg | null, delayMs: number): Seg | null {
const key = seg ? segKey(seg) : null;
const now = Date.now();
if (key !== dwellSegKey) {
@@ -393,10 +446,14 @@ export function computeSnap(input: SnapInput): SnapResult | null {
// Liste gebaut und der Schnittpunkt-Fang prüfte ALLE Paare (O(N²): die Seite
// blockierte beim ersten Klick eines Zeichenwerkzeugs). Kleine Projekte bleiben
// exakt wie bisher.
// Strecken-Fang (Lot, Endpunkte, Mitte, Schnitt, Kante, nächste Strecke) rechnet der Kern
// (`geometry/snapSegments.ts`): bei normalen Projekten über die dort abgelegten Strecken des
// Geschosses (`held`) plus Entwurf, sonst über die hier vorausgewählten nahen Strecken.
const nearMode = input.project.drawings2d.length > LARGE_DRAWINGS;
const intRadius = tolM * 6;
let held = 0;
let segs: Seg[] = [];
let intSegs: Seg[] = [];
let intSegs: Seg[] | null = null;
if (needSegs) {
if (nearMode) {
const cand = collectSegments(input, { at: raw, r: intRadius });
@@ -408,8 +465,8 @@ export function computeSnap(input: SnapInput): SnapResult | null {
// Schnittpunkte nur unter den nächsten Strecken (paarweise → quadratisch).
intSegs = withDist.slice(0, 64).map((e) => e.seg);
} else {
segs = collectSegments(input);
intSegs = segs;
held = heldBaseSegments(input, false);
segs = draftSegments(input);
}
// Abgeleitete Blatt-Geometrie (Schnitt/Ansicht, s. sheetSnapGeometry.ts):
// nur die Strecken in Cursornähe — eine Ansicht hat schnell Tausende Kanten,
@@ -423,17 +480,40 @@ export function computeSnap(input: SnapInput): SnapResult | null {
.slice(0, 64)
.map((e) => e.seg);
if (near.length > 0) {
const shared = intSegs === segs;
segs = segs.concat(near);
intSegs = shared ? segs : intSegs.concat(near);
if (intSegs) intSegs = intSegs.concat(near);
}
}
}
let segSnap: ReturnType<typeof snapOnSegments> = null;
if (needSegs) {
const q = {
raw,
tolM,
pxPerMeter,
perpendicular: settings.perpendicular,
endpoint: settings.endpoint,
midpoint: settings.midpoint,
intersection: settings.intersection,
onEdge: settings.onEdge,
lastPoint: settings.perpendicular ? input.lastPoint : null,
};
segSnap = snapOnSegments(held, segs, intSegs, q);
// Abgelegte Strecken verdrängt/freigegeben: neu ablegen und nochmals.
if (!segSnap && held) segSnap = snapOnSegments(heldBaseSegments(input, true), segs, intSegs, q);
}
// Kern-Kandidat übernehmen, wenn er besser ist (gleiche Regel wie `consider`).
const offer = (c: SegSnapCand | null | undefined) => {
if (c && c.score < bestScore) {
bestScore = c.score;
best = { point: c.point, kind: c.kind, distPx: c.distPx, refA: c.kind === "perpendicular" ? input.lastPoint ?? undefined : undefined };
}
};
// Teilpunkt-Verweilerkennung: braucht dieselben Strecken wie oben. Ohne sie
// (alle Objekt-Snap-Arten aus) bleiben "divide"/"parallel" ebenfalls inaktiv
// — konsistent dazu, dass dann ohnehin keine Linien-bezogenen Snaps gelten.
const revealed = updateDwell(raw, segs, settings.hoverDivideDelayMs, tolM);
const revealed = updateDwell(segSnap?.nearest ?? null, settings.hoverDivideDelayMs);
if (revealed) {
const [a, b] = revealed;
const n = Math.max(2, Math.round(settings.hoverDivideCount));
@@ -474,50 +554,18 @@ export function computeSnap(input: SnapInput): SnapResult | null {
// perpendicular: Lotfusspunkt VOM LETZTEN PUNKT (nicht vom Cursor wie
// "onEdge") auf nahe Strecken — die Strecke lastPoint→Fangpunkt steht im
// rechten Winkel zur Referenz-Strecke.
if (settings.perpendicular && input.lastPoint) {
for (const [a, b] of segs) {
consider(perpFoot(input.lastPoint, a, b), "perpendicular", input.lastPoint);
}
}
// rechten Winkel zur Referenz-Strecke; dann die Strecken-Endpunkte (Kern, Block A).
offer(segSnap?.a);
// endpoint (Strecken-Endpunkte + Draft-Knoten + Raum-Stempel-Anker).
// endpoint (Draft-Knoten + Raum-Stempel-Anker).
if (settings.endpoint) {
for (const [a, b] of segs) {
consider(a, "endpoint");
consider(b, "endpoint");
}
for (const p of input.draftPoints) consider(p, "endpoint");
// Raum-Stempel-Anker (fixer Anker, sonst Flächenschwerpunkt) des Geschosses.
for (const room of input.project.rooms ?? []) {
if (room.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(room.categoryCode)) continue;
if (room.boundary.length < 3) continue;
consider(room.stampAnchor ?? roomCentroid(room.boundary), "endpoint");
}
}
// midpoint.
if (settings.midpoint) {
for (const [a, b] of segs) consider(mid(a, b), "midpoint");
}
// intersection (paarweise Geraden-Schnitt der Strecken, nahe am Cursor).
if (settings.intersection) {
for (let i = 0; i < intSegs.length; i++) {
for (let j = i + 1; j < intSegs.length; j++) {
const [a, b] = intSegs[i];
const [c, d] = intSegs[j];
const x = lineIntersect(a, { x: b.x - a.x, y: b.y - a.y }, c, {
x: d.x - c.x,
y: d.y - c.y,
});
if (x) consider(x, "intersection");
}
}
}
// onEdge (Lotfußpunkt auf nahe Strecken; niedrige Priorität).
if (settings.onEdge) {
for (const [a, b] of segs) consider(perpFoot(raw, a, b), "onEdge");
for (const p of roomAnchors(input)) consider(p, "endpoint");
}
// midpoint, intersection (paarweise Geraden-Schnitt der Strecken, nahe am Cursor), onEdge
// (Lotfußpunkt auf nahe Strecken; niedrige Priorität) — Kern, Block B.
offer(segSnap?.b);
// Kreis-/Bogen-Snaps: Mittelpunkt + Quadranten (Ost/Nord/West/Süd); bei Bögen
// nur die Quadranten IM Bogen-Bereich, plus die beiden Bogen-Endpunkte. Center/
@@ -535,7 +583,7 @@ export function computeSnap(input: SnapInput): SnapResult | null {
const sweep = norm(c.arc.a1 - c.arc.a0) || TAU;
return norm(ang - c.arc.a0) <= sweep + 1e-9;
};
for (const c of collectCircles(input)) {
for (const c of levelCircles(input)) {
if (settings.center) {
consider(c.center, "center");
// Volle CCW-Spanne (0 ⇒ Vollkreis); Quadrant nur, wenn im Bogen liegt.
@@ -570,11 +618,7 @@ export function computeSnap(input: SnapInput): SnapResult | null {
// Ellipse: nur der Mittelpunkt (keine Quadranten — bei gedrehter Ellipse
// wären die "Achsenpunkte" ohnehin keine Kreis-Quadranten mehr).
if (settings.center) {
for (const d of nonLineDrawings(input.project.drawings2d)) {
if (d.levelId !== input.levelId) continue;
if (!input.visibleCodes.has(d.categoryCode)) continue;
if (d.geom.shape === "ellipse") consider(d.geom.center, "center");
}
for (const p of ellipseCenters(input)) consider(p, "center");
}
}
+86 -198
View File
@@ -31,7 +31,7 @@ import { isGpuText } from "../../core";
import { LiveMeet, LiveValue, createMeetStore, createValueStore } from "./planView/liveMeet";
import { useWasmPlanRenderer } from "./useWasmPlanRenderer";
import { DEFAULT_MARQUEE_COLOR, DEFAULT_SNAP_COLOR } from "../../theme/accents";
import { type ViewBox__plan_planView_geometry as ViewBox, PX_PER_M, PAD, toScreen, clamp, meetScale, scaleFromView, viewForScale, viewForCamera, fitBoxFor, pointInPolygon, pointSegDistPx, marqueeHit, marqueeHitDrawings, type ModelRect, marqueeHitCeilings, marqueeHitRooms, marqueeHitStairs } from "../../core";
import { type ViewBox__plan_planView_geometry as ViewBox, PX_PER_M, PAD, toScreen, clamp, meetScale, scaleFromView, viewForScale, viewForCamera, fitBoxFor, marqueeHit, marqueeHitDrawings, type ModelRect, marqueeHitCeilings, marqueeHitRooms, marqueeHitStairs } from "../../core";
import {
polyUsesPattern,
HatchPattern,
@@ -44,8 +44,7 @@ import { DraftOverlay } from "./planView/overlays";
import { PlanRulers } from "./planView/PlanRulers";
import { PlanGrid } from "./planView/PlanGrid";
import { expandRegion, indexedInRegion, regionContains, type Bounds } from "../../core";
import { buildSegmentIndex, nearestSegment, pointSegDist__plan_planView_segmentIndex as pointSegDist, segmentsNear } from "../../core";
import { buildOwnerIndex, ownedBy, type OwnerField, type OwnerIndex } from "../../core";
import { PlanPickIndex, type ClientMap, type OwnerField } from "../../core";
import { buildDrawingIndex, drawingsWithinDistance, marqueeHitUnderlay, nearestInDrawings, type DrawingIndex } from "../../core";
import { endBusyAfterPaint } from "../../state/busyStore";
import { createCursorStore, useCursorValue, type CursorStore } from "../../state/cursorStore";
@@ -760,17 +759,19 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// zoomen (view schrumpft stark — reines "liegt noch drin" reicht hier
// NICHT, ein View, der nur kleiner wird, bleibt sonst fälschlich innerhalb
// der alten, zu grosszügigen Region) wird neu gerechnet.
// Raster-Index der 2D-Zeichenlinien für Hover-/Pick-Abfragen (s. segmentIndex.ts).
// LAZY (erst beim ersten Hover/Klick je Plan): der Aufbau kostet bei 3,7 Mio.
// Segmenten ~250 ms und lief sonst bei JEDEM Plan-/Ebenenwechsel.
const segmentIndexRef = useRef<{ prims: readonly Primitive[]; index: ReturnType<typeof buildSegmentIndex> } | null>(null);
const getSegmentIndex = () => {
const cached = segmentIndexRef.current;
if (cached && cached.prims === planRaw.primitives) return cached.index;
const index = buildSegmentIndex(planRaw.primitives);
segmentIndexRef.current = { prims: planRaw.primitives, index };
return index;
// Auswahl-Index im Kern (s. planView/planPick.ts): 2D-Zeichenlinien, Polygone, Symbol-Linien,
// Kreise/Bögen und Besitzer über `plan.primitives` (dieselben Indizes). LAZY: der Kern baut ihn
// erst bei der ersten Abfrage je Plan; der vorige wird dann freigegeben.
const pickIndexRef = useRef<PlanPickIndex | null>(null);
const getPick = (): PlanPickIndex => {
const cached = pickIndexRef.current;
if (cached && cached.prims === plan.primitives) return cached;
cached?.release();
const ix = new PlanPickIndex(plan);
pickIndexRef.current = ix;
return ix;
};
useEffect(() => () => pickIndexRef.current?.release(), []);
const svgRef = useRef<SVGSVGElement | null>(null);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
@@ -831,6 +832,17 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
const lines = !useGpuRenderer || wantWasm;
return materializeGreyed(lines ? materializeUnderlay(planRaw) : planRaw, lines);
}, [planRaw, useGpuRenderer, wantWasm]);
// Einzeltexte und Bilder (eigene Bbox-Treffer): einmal je Plan gesammelt statt bei jeder
// Mausbewegung über alle Primitive zu laufen.
const textImageIdx = useMemo(() => {
const texts: number[] = [];
const images: number[] = [];
plan.primitives.forEach((p, i) => {
if (p.kind === "drawingText") texts.push(i);
else if (p.kind === "drawingImage") images.push(i);
});
return { texts, images };
}, [plan.primitives]);
// Kompakte Linien-Unterlage (nur im reinen WebGL-Modus noch als `plan.underlay`
// vorhanden): Hover/Pick/Marquee/Hervorhebung greifen direkt auf die Zeichnungen
@@ -1347,6 +1359,11 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
const top = rect?.top ?? 0;
return { x: left + offX + (vbX - view.x) * scale, y: top + offY + (vbY - view.y) * scale };
};
// Abbildung Modell → Client-Pixel (toScreen + vbToClient) für Pixel-Abfragen im Kern.
const clientMap = (): ClientMap => {
const { rect, scale, offX, offY } = measure(view);
return { left: (rect?.left ?? 0) + offX, top: (rect?.top ?? 0) + offY, viewX: view.x, viewY: view.y, scale };
};
// Index des Griffs unter dem Cursor (Bildschirm-Pixel) oder null.
const gripAt = (clientX: number, clientY: number): number | null => {
if (!grips) return null;
@@ -1410,13 +1427,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// Reihenfolge testen, damit das zuletzt gezeichnete (oberste) zuerst trifft.
const hitTest = (clientX: number, clientY: number): number | null => {
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
const prims = plan.primitives;
for (let i = prims.length - 1; i >= 0; i--) {
const p = prims[i];
if (p.kind === "polygon" && pointInPolygon(m, p.pts)) return i;
}
return null;
return getPick().topPolygon(viewToModel(v.x, v.y));
};
// Irgendein Element (Wand/Decke/Raum/Treppe/Stütze/Dach/2D) unter dem
@@ -1443,64 +1454,32 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
return did ? { drawingId: did } : null;
};
// Abstand (Bildschirm-Pixel) eines Klicks vom Ring eines Kreis/Bogen-2D-
// Elements — bei gefüllten Kreisen zählt auch INNERHALB als Treffer (d=0).
// Bögen zusätzlich auf ihre Winkel-Spanne begrenzt (CCW, Modell-Radiant, s.
// toRenderScene.ts für dieselbe Normalisierung).
const distToDrawingRing = (
clientX: number,
clientY: number,
p: Extract<Primitive, { kind: "drawingCircle" | "drawingArc" }>,
): number => {
const m = rawModelAt(clientX, clientY);
const distFromCenter = Math.hypot(m.x - p.center.x, m.y - p.center.y);
if (p.kind === "drawingArc") {
const TAU = Math.PI * 2;
const sweep = (((p.a1 - p.a0) % TAU) + TAU) % TAU || TAU;
const ang = Math.atan2(m.y - p.center.y, m.x - p.center.x);
const rel = (((ang - p.a0) % TAU) + TAU) % TAU;
// Kleiner Winkel-Toleranzsaum (in Bogenmass, radiusabhängig), damit die
// Enden eines kurzen Bogens nicht unerreichbar schmal werden.
const angTolRad = distFromCenter > 1e-6 ? LINE_PICK_PX / (currentPxPerMeter() * Math.max(distFromCenter, 0.05)) : Infinity;
if (rel > sweep + angTolRad && TAU - rel > angTolRad) return Infinity;
}
const filled = p.kind === "drawingCircle" && p.fill !== "none";
const dMeters = filled ? Math.max(0, distFromCenter - p.r) : Math.abs(distFromCenter - p.r);
return dMeters * currentPxPerMeter();
};
// Nächstgelegenes 2D-Zeichenelement (Drawing2D) zum Cursor per Linien-Nähe in
// Bildschirm-Pixeln (zoom-unabhängige Toleranz). Liefert die drawingId oder null.
const pickDrawing = (clientX: number, clientY: number): string | null => {
let bestId: string | null = null;
let bestDist = LINE_PICK_PX;
const segmentIndex = getSegmentIndex();
if (segmentIndex) {
const pxPerM = currentPxPerMeter();
const m = rawModelAt(clientX, clientY);
const i = nearestSegment(segmentIndex, plan.primitives, m, LINE_PICK_PX / pxPerM);
if (i !== null) {
const p = plan.primitives[i] as Extract<Primitive, { kind: "line" }>;
bestId = p.drawingId!;
bestDist = pointSegDist(m, p.a, p.b) * pxPerM;
}
const pick = getPick();
const pxPerM = currentPxPerMeter();
const m = rawModelAt(clientX, clientY);
const seg = pick.nearestSegment(m, LINE_PICK_PX / pxPerM);
if (seg) {
bestId = (plan.primitives[seg.i] as Extract<Primitive, { kind: "line" }>).drawingId!;
bestDist = seg.dist * pxPerM;
}
const uIndex = getUnderlayIndex();
if (uIndex) {
const pxPerM = currentPxPerMeter();
const hit = nearestInDrawings(uIndex, rawModelAt(clientX, clientY), bestDist / pxPerM);
const hit = nearestInDrawings(uIndex, m, bestDist / pxPerM);
if (hit) {
bestId = hit.drawing.id;
bestDist = hit.dist * pxPerM;
}
}
for (const p of plan.primitives) {
if ((p.kind === "drawingCircle" || p.kind === "drawingArc") && p.drawingId) {
const d = distToDrawingRing(clientX, clientY, p);
if (d < bestDist) {
bestDist = d;
bestId = p.drawingId;
}
// Kreise/Bögen (Ring-Abstand wie früher `distToDrawingRing`), in Plan-Reihenfolge.
for (const { i, dpx } of pick.ringsNear(m, pxPerM, LINE_PICK_PX)) {
if (dpx < bestDist) {
bestDist = dpx;
bestId = (plan.primitives[i] as Extract<Primitive, { kind: "drawingCircle" | "drawingArc" }>).drawingId!;
}
}
if (bestId) return bestId;
@@ -1519,14 +1498,11 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
const maxDist = LINE_PICK_PX / currentPxPerMeter();
let best: { a: Vec2; b: Vec2 } | null = null;
let bestDist = maxDist;
const segmentIndex = getSegmentIndex();
if (segmentIndex) {
const i = nearestSegment(segmentIndex, plan.primitives, m, maxDist);
if (i !== null) {
const p = plan.primitives[i] as Extract<Primitive, { kind: "line" }>;
best = { a: p.a, b: p.b };
bestDist = pointSegDist(m, p.a, p.b);
}
const seg = getPick().nearestSegment(m, maxDist);
if (seg) {
const p = plan.primitives[seg.i] as Extract<Primitive, { kind: "line" }>;
best = { a: p.a, b: p.b };
bestDist = seg.dist;
}
const uIndex = getUnderlayIndex();
if (uIndex) {
@@ -1541,7 +1517,8 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// Winkel wird vernachlässigt (meist waagrecht). Liefert die drawingId oder null.
const pickDrawingText = (clientX: number, clientY: number): string | null => {
const m = rawModelAt(clientX, clientY);
for (const p of plan.primitives) {
for (const i of textImageIdx.texts) {
const p = plan.primitives[i];
if (p.kind !== "drawingText" || !p.drawingId) continue;
const singleW = Math.max(1, p.text.length) * p.heightM * 0.6;
// Textspalte: Breite = wrapWidth, Höhe = geschätzte Zeilenzahl · Zeilenhöhe.
@@ -1566,8 +1543,8 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// oder null.
const pickDrawingImage = (clientX: number, clientY: number): string | null => {
const m = rawModelAt(clientX, clientY);
for (let i = plan.primitives.length - 1; i >= 0; i--) {
const p = plan.primitives[i];
for (let k = textImageIdx.images.length - 1; k >= 0; k--) {
const p = plan.primitives[textImageIdx.images[k]];
if (p.kind !== "drawingImage" || !p.drawingId) continue;
if (m.x >= p.min.x && m.x <= p.max.x && m.y >= p.min.y && m.y <= p.max.y) {
return p.drawingId;
@@ -1580,33 +1557,14 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// `openingId` per Bildschirm-Nähe, plus getroffene Fenster-Rahmen (Polygon mit
// openingId, per Punkt-in-Polygon). Liefert die openingId oder null.
const pickOpening = (clientX: number, clientY: number): string | null => {
let bestId: string | null = null;
let bestDist = LINE_PICK_PX;
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
for (const p of plan.primitives) {
if (p.kind === "line" && p.openingId) {
const a = vbToClient(toScreen(p.a).x, toScreen(p.a).y);
const b = vbToClient(toScreen(p.b).x, toScreen(p.b).y);
const d = pointSegDistPx({ x: clientX, y: clientY }, a, b);
if (d < bestDist) {
bestDist = d;
bestId = p.openingId;
}
} else if (p.kind === "arc" && p.openingId) {
// Bogen: über from→to als Sehne annähern (ausreichend für die Auswahl).
const a = vbToClient(toScreen(p.from).x, toScreen(p.from).y);
const b = vbToClient(toScreen(p.to).x, toScreen(p.to).y);
const d = pointSegDistPx({ x: clientX, y: clientY }, a, b);
if (d < bestDist) {
bestDist = d;
bestId = p.openingId;
}
} else if (p.kind === "polygon" && p.openingId && pointInPolygon(m, p.pts)) {
return p.openingId;
}
}
return bestId;
const pick = getPick();
// Getroffener Rahmen (das zuerst gezeichnete Polygon) hat Vorrang vor Symbol-Linien.
const hit = pick.bottomPolygon(m, "openingId");
if (hit !== null) return (plan.primitives[hit] as { openingId?: string }).openingId!;
const i = pick.nearestSymbolPx(["openingId"], ["openingId"], clientMap(), { x: clientX, y: clientY }, LINE_PICK_PX);
return i === null ? null : (plan.primitives[i] as { openingId?: string }).openingId!;
};
// Nächstgelegene Treppe zum Cursor: getroffenes Tritt-/Podest-Polygon (per
@@ -1614,67 +1572,35 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
const pickStair = (clientX: number, clientY: number): string | null => {
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
for (const p of plan.primitives) {
if (p.kind === "polygon" && p.stairId && pointInPolygon(m, p.pts)) {
return p.stairId;
}
}
let bestId: string | null = null;
let bestDist = LINE_PICK_PX;
for (const p of plan.primitives) {
if (p.kind === "line" && p.stairId) {
const a = vbToClient(toScreen(p.a).x, toScreen(p.a).y);
const b = vbToClient(toScreen(p.b).x, toScreen(p.b).y);
const d = pointSegDistPx({ x: clientX, y: clientY }, a, b);
if (d < bestDist) {
bestDist = d;
bestId = p.stairId;
}
}
}
return bestId;
const pick = getPick();
const hit = pick.bottomPolygon(m, "stairId");
if (hit !== null) return (plan.primitives[hit] as { stairId?: string }).stairId!;
const i = pick.nearestSymbolPx(["stairId"], [], clientMap(), { x: clientX, y: clientY }, LINE_PICK_PX);
return i === null ? null : (plan.primitives[i] as { stairId?: string }).stairId!;
};
// Getroffener Raum: die Raum-Fläche (Polygon mit `roomId`) per Punkt-in-Polygon.
// Bei überlappenden Räumen gewinnt der zuletzt gezeichnete (oberste).
const pickRoom = (clientX: number, clientY: number): string | null => {
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
for (let i = plan.primitives.length - 1; i >= 0; i--) {
const p = plan.primitives[i];
if (p.kind === "polygon" && p.roomId && pointInPolygon(m, p.pts)) {
return p.roomId;
}
}
return null;
const i = getPick().topPolygon(viewToModel(v.x, v.y), "roomId");
return i === null ? null : (plan.primitives[i] as { roomId?: string }).roomId!;
};
// Getroffenes Dach: das unsichtbare Traufe-Pick-Polygon per Punkt-in-Polygon
// (die sichtbaren Dachlinien allein wären schwer exakt zu treffen).
const pickRoof = (clientX: number, clientY: number): string | null => {
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
for (let i = plan.primitives.length - 1; i >= 0; i--) {
const p = plan.primitives[i];
if (p.kind === "polygon" && p.roofId && pointInPolygon(m, p.pts)) {
return p.roofId;
}
}
return null;
const i = getPick().topPolygon(viewToModel(v.x, v.y), "roofId");
return i === null ? null : (plan.primitives[i] as { roofId?: string }).roofId!;
};
// Getroffene Schnitt-/Ansichtslinie: ihr schmales, unsichtbares Pick-Band
// (Polygon mit sectionLineId) per Punkt-in-Polygon.
const pickSectionLine = (clientX: number, clientY: number): string | null => {
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
for (let i = plan.primitives.length - 1; i >= 0; i--) {
const p = plan.primitives[i];
if (p.kind === "polygon" && p.sectionLineId && pointInPolygon(m, p.pts)) {
return p.sectionLineId;
}
}
return null;
const i = getPick().topPolygon(viewToModel(v.x, v.y), "sectionLineId");
return i === null ? null : (plan.primitives[i] as { sectionLineId?: string }).sectionLineId!;
};
// Getroffenes Kontext-Objekt (importiertes Gebäude/Terrain): sein unsichtbares
@@ -1683,14 +1609,8 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// dünnen Umrisslinie.
const pickContextObject = (clientX: number, clientY: number): string | null => {
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
for (let i = plan.primitives.length - 1; i >= 0; i--) {
const p = plan.primitives[i];
if (p.kind === "polygon" && p.contextObjectId && pointInPolygon(m, p.pts)) {
return p.contextObjectId;
}
}
return null;
const i = getPick().topPolygon(viewToModel(v.x, v.y), "contextObjectId");
return i === null ? null : (plan.primitives[i] as { contextObjectId?: string }).contextObjectId!;
};
// Getroffener extrudierter Körper (truck-Integration): der Footprint-Umriss
@@ -1698,28 +1618,16 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// trotzdem als FLÄCHE anklickbar (analog Raum, nicht nur auf der Linie).
const pickExtrudedSolid = (clientX: number, clientY: number): string | null => {
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
for (let i = plan.primitives.length - 1; i >= 0; i--) {
const p = plan.primitives[i];
if (p.kind === "polygon" && p.extrudedSolidId && pointInPolygon(m, p.pts)) {
return p.extrudedSolidId;
}
}
return null;
const i = getPick().topPolygon(viewToModel(v.x, v.y), "extrudedSolidId");
return i === null ? null : (plan.primitives[i] as { extrudedSolidId?: string }).extrudedSolidId!;
};
// Getroffene Stütze (Tragwerk): ihr Querschnitt ist eine gefüllte Poché
// (Polygon mit columnId) — per Punkt-in-Polygon als FLÄCHE anklickbar.
const pickColumn = (clientX: number, clientY: number): string | null => {
const v = clientToView(clientX, clientY, view);
const m = viewToModel(v.x, v.y);
for (let i = plan.primitives.length - 1; i >= 0; i--) {
const p = plan.primitives[i];
if (p.kind === "polygon" && p.columnId && pointInPolygon(m, p.pts)) {
return p.columnId;
}
}
return null;
const i = getPick().topPolygon(viewToModel(v.x, v.y), "columnId");
return i === null ? null : (plan.primitives[i] as { columnId?: string }).columnId!;
};
// Liegt der Cursor auf dem KÖRPER eines GEWÄHLTEN Elements (Wand-Poché bzw.
@@ -2311,16 +2219,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
}, [pickList]);
/** Alle Polygone unter dem Cursor, oberstes zuerst. */
const hitTestAll = (clientX: number, clientY: number): number[] => {
const m = rawModelAt(clientX, clientY);
const prims = plan.primitives;
const out: number[] = [];
for (let i = prims.length - 1; i >= 0; i--) {
const p = prims[i];
if (p.kind === "polygon" && pointInPolygon(m, p.pts)) out.push(i);
}
return out;
};
const hitTestAll = (clientX: number, clientY: number): number[] => getPick().polygonsAt(rawModelAt(clientX, clientY));
/** Bezeichnung eines 2D-Elements nach Form (Linie/Fläche/Text/Kreis/…). */
const drawingLabel = (id: string): string => {
@@ -2355,20 +2254,15 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
const m = rawModelAt(clientX, clientY);
const tol = LINE_PICK_PX / pxPerM;
const found: Array<{ id: string; d: number }> = [];
const segIdx = getSegmentIndex();
if (segIdx) {
for (const { i, dist } of segmentsNear(segIdx, plan.primitives, m, tol)) {
const id = (plan.primitives[i] as Extract<Primitive, { kind: "line" }>).drawingId;
if (id) found.push({ id, d: dist });
}
const pick = getPick();
for (const { i, dist } of pick.segmentsNear(m, tol)) {
const id = (plan.primitives[i] as Extract<Primitive, { kind: "line" }>).drawingId;
if (id) found.push({ id, d: dist });
}
const uIdx = getUnderlayIndex();
if (uIdx) for (const h of drawingsWithinDistance(uIdx, m, tol)) found.push({ id: h.drawing.id, d: h.dist });
for (const p of plan.primitives) {
if ((p.kind === "drawingCircle" || p.kind === "drawingArc") && p.drawingId) {
const dpx = distToDrawingRing(clientX, clientY, p);
if (dpx < LINE_PICK_PX) found.push({ id: p.drawingId, d: dpx / pxPerM });
}
for (const { i, dpx } of pick.ringsNear(m, pxPerM, LINE_PICK_PX)) {
found.push({ id: (plan.primitives[i] as Extract<Primitive, { kind: "drawingCircle" | "drawingArc" }>).drawingId!, d: dpx / pxPerM });
}
const textId = pickDrawingText(clientX, clientY);
if (textId) found.push({ id: textId, d: tol * 2 });
@@ -2779,21 +2673,15 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// gewählten Wand umrandet. Ohne Wand-Auswahl greift die lokale Klick-
// Hervorhebung (ein einzelnes Polygon per hitIndex), z. B. für Polygone ohne
// Wandbezug.
// Besitzer-Index (s. planView/ownerIndex.ts): EIN Durchgang je Plan, lazy beim
// ersten Bedarf — statt je Elementart ein `plan.primitives.filter`.
const ownerIndexRef = useRef<{ prims: readonly Primitive[]; index: OwnerIndex } | null>(null);
// Besitzer über den Auswahl-Index im Kern (s. planView/planPick.ts) — statt je Elementart ein
// `plan.primitives.filter`.
const primsOwnedBy = <K extends Primitive>(
field: OwnerField,
ids: ReadonlyArray<string> | undefined,
keep: (p: Primitive) => p is K,
): K[] => {
if (!ids || ids.length === 0) return [];
let cached = ownerIndexRef.current;
if (!cached || cached.prims !== plan.primitives) {
cached = { prims: plan.primitives, index: buildOwnerIndex(plan.primitives) };
ownerIndexRef.current = cached;
}
return ownedBy(cached.index, plan.primitives, field, ids).filter(keep);
return getPick().ownedBy(field, ids).filter(keep);
};
const highlightPolys = useMemo(() => {
+6 -6
View File
@@ -1,7 +1,7 @@
// Live-Spiegelung in die nativen wgpu-Fenster (src-tauri/src/native.rs): schiebt
// die AKTUELL sichtbare 2D-Szene bzw. die geflachten 3D-Wände debounced per
// Tauri-Command an die native Event-Loop. Es wird EXAKT dieselbe Ableitung
// benutzt wie für die Browser-Ansicht (planToRenderScene auf dem sichtbaren
// benutzt wie für die Browser-Ansicht (planSceneBin aus dem Kern auf dem sichtbaren
// Plan, projectToWalls3d aufs Projekt) — 1:1-Parität inkl. Türschwenk,
// Fenster-Symbolen und Raumstempel-Text (echte Glyphen via GPU-Atlas in Rust).
//
@@ -10,9 +10,9 @@
// geschluckt (console.debug), damit die App nie daran scheitert.
import type { Plan } from "../../core";
import { materializeGreyed, materializeUnderlay } from "../../core";
import { materializeUnderlay } from "../../core";
import type { Project } from "../../model/types";
import { encodeRenderScene, planToRenderScene } from "../../core";
import { planSceneBin } from "../../core";
import { projectToModel3d, TRUCK_MESH_READY_EVENT } from "../../core";
/** Sammel-Fenster: Modelländerungen werden gebündelt gepusht (nicht je Frame). */
@@ -71,9 +71,9 @@ export function pushNativeScene(plan: Plan): void {
clearTimeout(sceneTimer);
sceneTimer = setTimeout(async () => {
if (!(await isNativeEnabled())) return;
// planToRenderScene liest `greyed` am Primitiv → gedimmte Referenz-Ebenen materialisieren.
// Binärpuffer als Request-Body (Rust: `render2d::scene_bin`), kein JSON.
void invokeNative("push_native_scene", encodeRenderScene(planToRenderScene(materializeGreyed(materializeUnderlay(plan), true))));
// Szene aus dem Kern (Plan-Puffer, gedimmte Referenz-Ebenen über `greyedRanges`), als
// Binärpuffer im Request-Body (Rust: `render2d::scene_bin`), kein JSON.
void invokeNative("push_native_scene", planSceneBin(materializeUnderlay(plan)));
}, DEBOUNCE_MS);
}
+2 -2
View File
@@ -14,7 +14,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
import type { Plan } from "../../core";
import { encodeRenderScene, planToRenderScene } from "../../core";
import { planSceneBin } from "../../core";
interface ViewBox {
x: number;
@@ -115,7 +115,7 @@ export function useWasmPlanRenderer(
const r = rendererRef.current;
if (!r || !plan) return;
try {
r.set_scene_bin(encodeRenderScene(planToRenderScene(plan)));
r.set_scene_bin(planSceneBin(plan));
} catch (e) {
console.warn("render2d set_scene_bin fehlgeschlagen:", e);
}