[K4][K3d] S3 Fang-Kandidaten aus dem Modell im Kern (snap_model.rs), je Dokument-Stand gesammelt

Wände/Schichtgrenzen, Umrisse, 2D-Zeichnungen, Kreise, Raum-Anker, Ellipsen sammelt der Kern in zwei Teilen (Modell/Zeichnungen) je Revs-Stand; je Mausbewegung ein Aufruf snap_query, Nahmodus im Kern. TS behält Toleranz, Verweilen, Parallele, Raster/Winkel. Gelöscht: TS-Sammlung, snapSegments.ts, model/wall.ts, alte Bindungen. Gleichheit (einmalig): 20 100 Abfragen alt/neu gleich. Messung 3000 Wände + 20 000 Zeichnungen 9,7 ms → 23 µs je Mausbewegung.
This commit is contained in:
Claude committed 2026-10-29 15:04:17 +00:00
1 parent ddff1ede18
commit 0ff0f472f9
16 files changed
+1158 -714

No files matched your search

+5 -9
View File
@@ -36,20 +36,17 @@ export {
export {
type DrawingIndex,
buildDrawingIndex,
drawingsNear,
drawingsWithinDistance,
isIndexable,
nearestInDrawings,
pointSegDist as pointSegDist__geometry_drawingIndex,
} from "../geometry/drawingIndex";
export {
type SegSnapCand,
type SegSnapResult,
holdSnapSegments,
releaseSnapSegments,
snapOnSegments,
} from "../geometry/snapSegments";
type ModelSnapCand,
type ModelSnapResult,
holdModelSnap,
queryModelSnap,
} from "../geometry/modelSnap";
export {
type Fillet,
@@ -127,7 +124,6 @@ export {
MIN_STEPS,
defaultStepCount,
stairGeometry,
stairOutline,
} from "../geometry/stair";
export {
+3 -7
View File
@@ -1,8 +1,8 @@
// Raster-Index über die Bounding-Boxen von Linien-/Polylinien-Zeichnungen
// (Drawing2D). Abfragen prüfen nur die Zeichnungen in Cursornähe statt alle —
// bei einem Kataster-Import ~10^5 Zeichnungen / 3,7 Mio. Strecken. Genutzt für
// Hover/Pick/Marquee (plan/planView/underlayAccess.ts) und den Objektfang
// (tools/snapping.ts).
// Hover/Pick/Marquee (plan/planView/underlayAccess.ts); der Objektfang hat seinen
// eigenen Index im Kern (`snap_model.rs`). `pointSegDist` nutzt der Fang für die Blatt-Geometrie.
import type { Drawing2D, Vec2 } from "../model/types";
import { drawingBox } from "./drawingBounds";
@@ -47,10 +47,6 @@ const TARGET_PER_CELL = 4;
const MAX_CELLS = 2_000_000;
const MAX_CELLS_PER_DRAWING = 256;
/** Ob eine Zeichnung vom Index erfasst wird (Linie/Polylinie mit Punkten). */
export const isIndexable = (d: Drawing2D): boolean =>
d.geom.shape === "line" || d.geom.shape === "polyline";
export function buildDrawingIndex(drawings: readonly Drawing2D[]): DrawingIndex | null {
if (drawings.length === 0) return null;
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
@@ -104,7 +100,7 @@ export function buildDrawingIndex(drawings: readonly Drawing2D[]): DrawingIndex
* Indizes der Zeichnungen, deren Bounding-Box (um `r` erweitert) den Punkt `m`
* enthält — Kandidaten, jede höchstens einmal.
*/
export function drawingsNear(index: DrawingIndex, m: Vec2, r: number): number[] {
function drawingsNear(index: DrawingIndex, m: Vec2, r: number): number[] {
const { minX, minY, cell, cols, rows, cellStart, items, long, drawings } = index;
const out: number[] = [];
const seen = new Set<number>();
@@ -1,10 +1,11 @@
// 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].)
// Objektfang aus dem Modell im Kern ([K4] S3, `core/src/snap_model.rs` + `snap.rs`): gleiche Wahl wie
// die einfache Suche über alle Strecken/Paare (Raster-Vorauswahl und Geraden-Filter für Schnittpunkte
// dürfen nichts ändern), gleiche Nummer solange das Dokument gleich bleibt.
import { describe, expect, it } from "vitest";
import { holdSnapSegments, releaseSnapSegments, snapOnSegments, type SnapSeg } from "./snapSegments";
import type { Vec2 } from "../model/types";
import { holdModelSnap, queryModelSnap, type SnapSeg } from "./modelSnap";
import { sampleProject } from "../model/sampleProject";
import type { Drawing2D, Project, Vec2 } from "../model/types";
const PRIORITY: Record<string, number> = { perpendicular: 1, endpoint: 7, midpoint: 3, intersection: 5, onEdge: 0 };
@@ -55,10 +56,21 @@ function brute(segs: SnapSeg[], raw: Vec2, tolM: number, pxPerM: number, last: V
return { a: a.get(), b: b.get() };
}
describe("snapOnSegments (Kern)", () => {
const LEVEL = sampleProject.drawingLevels[0].id;
const CODE = "01";
function lineProject(segs: SnapSeg[]): Project {
const drawings: Drawing2D[] = segs.map(([a, b], i) => ({ id: `l${i}`, type: "drawing2d", levelId: LEVEL, categoryCode: CODE, geom: { shape: "line", a, b } }));
return { ...sampleProject, walls: [], rooms: [], ceilings: [], roofs: [], stairs: [], columns: [], drawings2d: drawings };
}
const flags = { segs: true, perpendicular: true, endpoint: true, midpoint: true, intersection: true, onEdge: true, center: false, tangent: false };
describe("Objektfang aus dem Modell (Kern)", () => {
it("gleich wie die Suche über alle Strecken und Paare (Zufallsdaten)", () => {
let seed = 3;
const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
const codes = new Set([CODE]);
for (let run = 0; run < 8; run++) {
const segs: SnapSeg[] = [];
for (let i = 0; i < 300; i++) {
@@ -67,36 +79,31 @@ describe("snapOnSegments (Kern)", () => {
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);
const p = lineProject(segs.slice(0, 250));
const draft = segs.slice(250);
const h = holdModelSnap(p, LEVEL, codes);
expect(holdModelSnap(p, LEVEL, codes)).toBe(h);
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 r = queryModelSnap(h, draft, [], { raw, tolM, pxPerMeter: 100, lastPoint: last, ...flags })!;
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);
expect(queryModelSnap(987654, [], [], { raw: { x: 0, y: 0 }, tolM: 1, pxPerMeter: 1, lastPoint: null, ...flags })).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,
})!;
const p = lineProject([[{ x: 0, y: 0 }, { x: 10, y: 0 }]]);
const h = holdModelSnap(p, LEVEL, new Set([CODE]));
const r = queryModelSnap(h, [[{ x: 5, y: -5 }, { x: 5, y: 5 }]], [], { raw: { x: 5.05, y: 0.02 }, tolM: 0.2, pxPerMeter: 100, lastPoint: null, ...flags })!;
expect(r.nearest).toEqual([{ x: 0, y: 0 }, { x: 10, y: 0 }]);
expect(r.b?.kind).toBe("intersection");
// Ohne sichtbare Ebene: keine Strecken.
const h2 = holdModelSnap(p, LEVEL, new Set(["xx"]));
expect(queryModelSnap(h2, [], [], { raw: { x: 5.05, y: 0.02 }, tolM: 0.2, pxPerMeter: 100, lastPoint: null, ...flags })!.nearest).toBeNull();
});
});
+115
View File
@@ -0,0 +1,115 @@
// Objektfang aus dem Modell über den Kern ([K4] S3, `src-tauri/core/src/snap_model.rs` + `snap.rs`):
// Der Kern sammelt die Fang-Kandidaten eines Geschosses (Wandachsen, Schichtgrenzen, Umrisse von
// Raum/Decke/Dach/Treppe/Stütze, 2D-Zeichnungen, Kreise/Bögen, Raum-Anker, Ellipsen-Mittelpunkte)
// einmal je Dokument-Stand ({@link holdModelSnap}); je Mausbewegung gehen nur Cursor, Toleranz und
// die Zusatzstrecken (Entwurf, Blatt-Geometrie) über die Grenze ({@link queryModelSnap}). Die
// Bildschirm-Toleranz, Verweilen/Teilpunkte, Parallele, Raster und Winkel bleiben in
// `tools/snapping.ts`.
import type { Project, Vec2 } from "../model/types";
import { core } from "../engine/coreWasm";
import { documentFor } from "../core/document";
export type SnapSeg = [Vec2, Vec2];
/** Fang-Arten des Kerns (Code → Name wie `SnapKind`). */
const KINDS = ["perpendicular", "endpoint", "midpoint", "intersection", "onEdge", "center", "quadrant", "tangent"] as const;
export type ModelSnapKind = (typeof KINDS)[number];
export interface ModelSnapCand {
point: Vec2;
kind: ModelSnapKind;
distPx: number;
/** `distPx − Priorität` (kleiner gewinnt). */
score: number;
}
/** Ergebnis in der Reihenfolge, in der `computeSnap` die Kandidaten zusammenführt. */
export interface ModelSnapResult {
/** Nächste Strecke innerhalb der Toleranz (Lotfusspunkt-Abstand) oder null (Verweilen). */
nearest: SnapSeg | null;
/** Lot vom letzten Punkt, Strecken-Endpunkte. */
a: ModelSnapCand | null;
/** Raum-Stempel-Anker (Endpunkt). */
anchors: ModelSnapCand | null;
/** Mittelpunkte, Schnittpunkte, Punkt auf der Kante. */
b: ModelSnapCand | null;
/** Kreise/Bögen (Mittelpunkt, Quadranten, Bogen-Endpunkte, Tangente), Ellipsen-Mittelpunkte. */
c: ModelSnapCand | null;
}
export interface ModelSnapQuery {
raw: Vec2;
tolM: number;
pxPerMeter: number;
/** Strecken-Fang überhaupt (auch nur für Verweilen/Parallele). */
segs: boolean;
perpendicular: boolean;
endpoint: boolean;
midpoint: boolean;
intersection: boolean;
onEdge: boolean;
center: boolean;
tangent: 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;
}
/**
* Kandidaten des Geschosses `levelId` (sichtbare Ebenen `codes`) im Kern sammeln bzw. wiederfinden:
* dieselbe Nummer, solange sich die betroffenen Felder des Dokuments nicht ändern. 0 = kein Dokument.
*/
export function holdModelSnap(project: Project, levelId: string, codes: ReadonlySet<string>): number {
const doc = documentFor(project);
return doc.id ? core().doc_snap_hold(doc.id, levelId, [...codes].join("\n")) : 0;
}
const cand = (f: Float64Array, k: number): ModelSnapCand | 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 je Mausbewegung über die abgelegten Kandidaten `held` plus Entwurfs- (`draft`) und
* Blatt-Strecken (`sheet`, nahe am Cursor, nächste zuerst). null, wenn `held` nicht (mehr) im Kern liegt.
*/
export function queryModelSnap(held: number, draft: readonly SnapSeg[], sheet: readonly SnapSeg[], q: ModelSnapQuery): ModelSnapResult | null {
const flags =
(q.perpendicular ? 1 : 0) |
(q.endpoint ? 2 : 0) |
(q.midpoint ? 4 : 0) |
(q.intersection ? 8 : 0) |
(q.onEdge ? 16 : 0) |
(q.center ? 32 : 0) |
(q.tangent ? 64 : 0) |
(q.segs ? 128 : 0);
const f = core().snap_query(
held,
flat(draft),
flat(sheet),
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 < 25) return null;
return {
nearest: f[0] >= 0 ? [{ x: f[1], y: f[2] }, { x: f[3], y: f[4] }] : null,
a: cand(f, 5),
anchors: cand(f, 10),
b: cand(f, 15),
c: cand(f, 20),
};
}
-95
View File
@@ -1,95 +0,0 @@
// 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),
};
}
+4 -25
View File
@@ -1,10 +1,10 @@
// Unit-Tests für die Wand-/Decken-Resolver: Referenzlinie (`wallReferenceOffset`) und die UK/OK der
// Decken über den Kern (`verticalExtents`, Regeln `model/helpers.rs::heights`).
// Unit-Tests für die UK/OK der Decken über den Kern (`verticalExtents`, Regeln
// `model/helpers.rs::heights`). Die Referenzlinie der Wand rechnet der Kern (`joins.rs::reference_offset`,
// Fang: `snap_model.rs::wall_layer_segments`).
import { describe, it, expect } from "vitest";
import { wallReferenceOffset } from "./wall";
import { verticalExtents } from "../geometry/grips";
import type { Ceiling, Project, Wall } from "./types";
import type { Ceiling, Project } from "./types";
/** Minimalprojekt mit einem Geschoss (baseElevation 0, floorHeight 2.6) und
* einem einschichtigen Wandtyp (0.2 m), den die Decke als Aufbau nutzt. */
@@ -116,24 +116,3 @@ describe("UK/OK einer Decke", () => {
expect(zBottom).toBeCloseTo(2.9); // baseElevation(og)=2.8 + offset(0.1)
});
});
describe("wallReferenceOffset", () => {
const w = (extra: Partial<Wall>): Wall => ({ referenceLine: "center", ...extra } as Wall);
const T = 0.4; // Gesamtdicke → half = 0.2
it("bildet die benannten Linien ab (aussen/mitte/innen)", () => {
expect(wallReferenceOffset(w({ referenceLine: "left" }), T)).toBeCloseTo(0.2, 6);
expect(wallReferenceOffset(w({ referenceLine: "center" }), T)).toBeCloseTo(0, 6);
expect(wallReferenceOffset(w({ referenceLine: "right" }), T)).toBeCloseTo(-0.2, 6);
});
it("übersteuert die Referenzlinie mit einem freien Fugen-Versatz", () => {
// Fuge z. B. nach einer 0.05-Aussenschale: offset = half − 0.05 = 0.15.
expect(wallReferenceOffset(w({ referenceLine: "left", referenceOffset: 0.15 }), T)).toBeCloseTo(0.15, 6);
});
it("klemmt den Fugen-Versatz auf ±halbe Dicke", () => {
expect(wallReferenceOffset(w({ referenceOffset: 5 }), T)).toBeCloseTo(0.2, 6);
expect(wallReferenceOffset(w({ referenceOffset: -5 }), T)).toBeCloseTo(-0.2, 6);
});
});
-37
View File
@@ -1,37 +0,0 @@
// Wand-Resolver: Versatz der Achse über die Dicke (Referenzlinie). Die vertikale Ausdehnung (UK/OK)
// rechnet der Kern (`model/helpers.rs::heights`; TS: Abfrage `verticalExtents`, `geometry/grips.ts`).
//
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import type { Wall } from "./types";
/**
* Versatz der Schichtstapelung entlang der linken Normalen `+n` (leftNormal),
* sodass die Achse auf der gewünschten Wandfläche liegt. Die Schichten werden
* normalerweise symmetrisch von `−T/2` (außen, +n-Seite) bis `+T/2` (innen)
* gestapelt; dieser Versatz wird ZUSÄTZLICH auf jeden Schicht-Offset addiert.
*
* • "center" → 0 (Schichten symmetrisch um die Achse — Default).
* • "left" → +T/2 (Achse auf der +n-/„außen"-Fläche; Wand liegt auf −n).
* • "right" → −T/2 (Achse auf der −n-/„innen"-Fläche; Wand liegt auf +n).
*
* Die Schicht-Offsets laufen von −T/2 (= +n außen) nach +T/2 (= −n innen).
* Für "left" soll die −T/2-Kante (außen) auf der Achse liegen → +T/2 addieren,
* sodass die Schichten von 0…T (alle auf der −n-Seite) liegen.
*/
export function wallReferenceOffset(
wall: Wall,
totalThickness: number,
): number {
const half = totalThickness / 2;
// Freier Fugen-Versatz (Schichttrennlinie als Referenz) übersteuert die
// benannte Referenzlinie. Auf die Wanddicke geklemmt, damit die Achse nie
// ausserhalb der Wand landet.
if (wall.referenceOffset != null) {
return Math.max(-half, Math.min(half, wall.referenceOffset));
}
const ref = wall.referenceLine ?? "center";
if (ref === "left") return +half;
if (ref === "right") return -half;
return 0;
}
+131
View File
@@ -0,0 +1,131 @@
// [K4] Messung: Objektfang je Mausbewegung (`computeSnap`) auf grossen Projekten — 3000 Wände +
// 20 000 Zeichnungen (Nahmodus), 3000 Wände + 1500 Zeichnungen (Normalmodus) und ein Kataster mit
// 150 000 Linien/Polylinien. Werte gehen nach stderr (TODO [K4]); geprüft wird vor allem, dass der
// Fang etwas findet. Die Grenzen sind grosszügig (Container unter Last).
import { describe, expect, it } from "vitest";
import { computeSnap, type SnapInput } from "./snapping";
import { DEFAULT_SNAP } from "./types";
import { sampleProject } from "../model/sampleProject";
import { getState } from "../state/appStore";
import { generatePlan, replaceItem } from "../core";
import type { Drawing2D, Project, Vec2, Wall } from "../model/types";
function wallsAndDrawings(nDrawings: number): Project {
const base = sampleProject.walls;
const walls: Wall[] = Array.from({ length: 3000 }, (_, i) => ({
...base[i % base.length],
id: `w${i}`,
floorId: sampleProject.drawingLevels[0].id,
start: { x: (i % 60) * 4, y: Math.floor(i / 60) * 4 },
end: { x: (i % 60) * 4 + 4, y: Math.floor(i / 60) * 4 },
}));
const level = sampleProject.drawingLevels[0].id;
const drawings: Drawing2D[] = Array.from({ length: nDrawings }, (_, i) => ({
id: `d${i}`,
type: "drawing2d",
levelId: level,
categoryCode: sampleProject.layers[0].code,
geom: { shape: "polyline", closed: false, pts: [{ x: (i % 200) * 1.2, y: Math.floor(i / 200) * 2 + 0.5 }, { x: (i % 200) * 1.2 + 1, y: Math.floor(i / 200) * 2 + 1.5 }, { x: (i % 200) * 1.2 + 2, y: Math.floor(i / 200) * 2 + 0.5 }] },
}));
return { ...structuredClone(sampleProject), walls, drawings2d: drawings };
}
/** Kataster: 150 000 Zeichnungen (Linien und geschlossene Parzellen) auf ~4 × 4 km. */
function cadastre(): Project {
const level = sampleProject.drawingLevels[0].id;
const drawings: Drawing2D[] = [];
for (let i = 0; i < 150000; i++) {
const x = (i % 400) * 10;
const y = Math.floor(i / 400) * 10;
drawings.push({
id: `k${i}`,
type: "drawing2d",
levelId: level,
categoryCode: sampleProject.layers[0].code,
geom:
i % 3 === 0
? { shape: "line", a: { x, y }, b: { x: x + 10, y: y + 3 } }
: { shape: "polyline", closed: true, pts: [{ x, y }, { x: x + 9, y }, { x: x + 9, y: y + 8 }, { x, y: y + 9 }] },
});
}
return { ...structuredClone(sampleProject), walls: [], drawings2d: drawings };
}
function input(project: Project, raw: Vec2, lastPoint: Vec2 | null): SnapInput {
return {
raw,
project,
levelId: project.drawingLevels[0].id,
visibleCodes: CODES.get(project)!,
settings: { ...DEFAULT_SNAP, perpendicular: true, tangent: true },
draftPoints: lastPoint ? [lastPoint] : [],
lastPoint,
pxPerMeter: 40,
shift: false,
ctrl: false,
};
}
const CODES = new Map<Project, Set<string>>();
/** Mittelwert (µs) je Mausbewegung: kleinster aus `rounds` Läufen à `n` Positionen. */
function bench(project: Project, at: (k: number) => Vec2, n = 400, rounds = 3): { us: number; hits: number } {
let best = Infinity;
let hits = 0;
for (let r = 0; r < rounds; r++) {
hits = 0;
const t = performance.now();
for (let k = 0; k < n; k++) if (computeSnap(input(project, at(k), { x: 1, y: 1 }))) hits++;
best = Math.min(best, ((performance.now() - t) * 1000) / n);
}
return { us: best, hits };
}
function measure(name: string, project: Project, at: (k: number) => Vec2, out: string[]): void {
// Über den Store (wie in der App): das Dokument ist offen, Änderungen gehen als Ops hinein.
getState().loadProject(project);
const p = getState().project;
CODES.set(p, new Set(p.layers.map((l) => l.code)));
// Wie in der App: der Plan steht, bevor das erste Werkzeug fängt (typisierte Sicht im Kern gebaut).
generatePlan(p, p.drawingLevels[0].id, CODES.get(p)!).primitives.length;
const t0 = performance.now();
computeSnap(input(p, at(0), null));
const first = performance.now() - t0;
const { us, hits } = bench(p, at);
expect(hits).toBeGreaterThan(0);
// Nach einer Änderung (Griff ziehen: eine Wand bzw. eine Zeichnung je Schritt): erster Fang danach.
const step = (change: () => void): number => {
let sum = 0;
for (let k = 0; k < 5; k++) {
change();
const p2 = getState().project;
CODES.set(p2, CODES.get(p)!);
const t = performance.now();
computeSnap(input(p2, at(k), { x: 1, y: 1 }));
sum += performance.now() - t;
}
return sum / 5;
};
let k = 0;
const wallMs = p.walls.length
? step(() => {
const w = getState().project.walls[7];
getState().applyChange([replaceItem("walls", { ...w, end: { x: w.end.x + 0.01 * ++k, y: w.end.y } })]);
})
: NaN;
const drawMs = step(() => {
const d = getState().project.drawings2d[11];
getState().applyChange([replaceItem("drawings2d", { ...d, categoryCode: d.categoryCode })]);
});
out.push(`${name}: erster Fang ${first.toFixed(1)} ms, je Mausbewegung ${us.toFixed(0)} µs (${hits} Treffer), nach Wand-Änderung ${wallMs.toFixed(1)} ms, nach Zeichnungs-Änderung ${drawMs.toFixed(1)} ms`);
}
describe("Messung Objektfang je Mausbewegung", () => {
it("3000 Wände + 20 000 / 1500 Zeichnungen, Kataster 150 000", { timeout: 600000 }, () => {
const out: string[] = [];
const wave = (k: number): Vec2 => ({ x: (k * 7.31) % 230, y: ((k * 3.17) % 190) + 0.02 });
measure("3000 Wände + 20 000 Zeichnungen", wallsAndDrawings(20000), wave, out);
measure("3000 Wände + 1500 Zeichnungen", wallsAndDrawings(1500), wave, out);
measure("Kataster 150 000", cadastre(), (k) => ({ x: (k * 37.3) % 3990, y: ((k * 11.9) % 3700) + 0.05 }), out);
process.stderr.write(`Fang:\n ${out.join("\n ")}\n`);
});
});
+38 -33
View File
@@ -10,7 +10,7 @@
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { computeSnap, snapCommonAngle, wallLayerBoundarySegments } from "./snapping";
import { computeSnap, snapCommonAngle } from "./snapping";
import { DEFAULT_SNAP } from "./types";
import type { Ceiling, Column, Drawing2D, Project, Roof, Room, Stair, Vec2, Wall } from "../model/types";
@@ -70,43 +70,48 @@ function wall(id: string, start: Vec2, end: Vec2, referenceLine?: Wall["referenc
};
}
describe("wallLayerBoundarySegments", () => {
it("liefert layers.length+1 Grenzlinien mit kumulierten Offsets (referenceLine=center)", () => {
const w = wall("W1", { x: 0, y: 0 }, { x: 4, y: 0 });
const segs = wallLayerBoundarySegments(wallProject(w), w);
expect(segs).toHaveLength(4); // 3 Schichten → 4 Grenzlinien
// Achse horizontal → leftNormal = (0,1); Offset erscheint als y-Koordinate.
const offsets = segs.map(([a]) => a.y);
expect(offsets[0]).toBeCloseTo(-0.225, 9); // −T/2 (Aussenfläche)
expect(offsets[1]).toBeCloseTo(-0.125, 9); // −T/2 + 0.10
expect(offsets[2]).toBeCloseTo(0.025, 9); // −T/2 + 0.10 + 0.15
expect(offsets[3]).toBeCloseTo(0.225, 9); // +T/2 (Aussenfläche, innen)
// Jede Grenzlinie läuft parallel zur Achse über die volle Wandlänge.
for (const [a, b] of segs) {
expect(a.y).toBeCloseTo(b.y, 9);
expect(a.x).toBeCloseTo(0, 9);
expect(b.x).toBeCloseTo(4, 9);
}
/** Fang an `raw` auf dem Wand-Projekt (nur Objekt-Fang, kein Raster/Winkel). */
function snapWall(w: Wall, raw: Vec2) {
return computeSnap({
raw,
project: wallProject(w),
levelId: "eg",
visibleCodes: new Set(["20"]),
settings: { ...DEFAULT_SNAP, grid: false, commonAngles: false, ortho: false },
draftPoints: [],
lastPoint: null,
pxPerMeter: 100,
shift: false,
ctrl: false,
});
}
it("verschiebt die Offsets um wallReferenceOffset bei referenceLine=left/right", () => {
const wLeft = wall("W1", { x: 0, y: 0 }, { x: 4, y: 0 }, "left");
const offLeft = wallLayerBoundarySegments(wallProject(wLeft), wLeft).map(([a]) => a.y);
// refOff = +T/2 = 0.225 → Offsets laufen von 0 bis T (0.45).
expect(offLeft[0]).toBeCloseTo(0, 9);
expect(offLeft[3]).toBeCloseTo(0.45, 9);
describe("Wand-Schichtgrenzen als Fang-Strecken (Kern `snap_model.rs`)", () => {
// Achse horizontal → leftNormal = (0,1); die Grenzen liegen bei y = Offset, jede über die volle Länge.
const cases: [Wall["referenceLine"], number[]][] = [
["center", [-0.225, -0.125, 0.025, 0.225]], // −T/2, −T/2 + 0.10, … +T/2
["left", [0, 0.1, 0.25, 0.45]], // refOff = +T/2
["right", [-0.45, -0.35, -0.2, 0]], // refOff = −T/2
];
for (const [ref, offsets] of cases) {
it(`fängt die Endpunkte aller layers.length+1 Grenzlinien (referenceLine=${ref})`, () => {
const w = wall("W1", { x: 0, y: 0 }, { x: 4, y: 0 }, ref);
for (const o of offsets) {
for (const x of [0, 4]) {
const r = snapWall(w, { x: x + 0.004, y: o + 0.004 });
expect(r?.kind).toBe("endpoint");
expect(r!.point.x).toBeCloseTo(x, 9);
expect(r!.point.y).toBeCloseTo(o, 9);
}
}
});
}
const wRight = wall("W1", { x: 0, y: 0 }, { x: 4, y: 0 }, "right");
const offRight = wallLayerBoundarySegments(wallProject(wRight), wRight).map(([a]) => a.y);
// refOff = −T/2 = −0.225 → Offsets laufen von −0.45 bis 0.
expect(offRight[0]).toBeCloseTo(-0.45, 9);
expect(offRight[3]).toBeCloseTo(0, 9);
});
it("liefert eine leere Liste bei unbekanntem Wandtyp (kein Crash im Snap-Pfad)", () => {
it("unbekannter Wandtyp: nur die Achse, keine Grenzlinien (kein Crash im Snap-Pfad)", () => {
const w = wall("W1", { x: 0, y: 0 }, { x: 4, y: 0 });
w.wallTypeId = "unknown";
expect(wallLayerBoundarySegments(wallProject(w), w)).toEqual([]);
expect(snapWall(w, { x: 4.004, y: -0.13 })).toBeNull();
expect(snapWall(w, { x: 4.004, y: 0.004 })?.point).toEqual({ x: 4, y: 0 });
});
});
+59 -412
View File
@@ -6,22 +6,15 @@
// Prioritäts-Reihenfolge (Vorrang bei nahem Abstand): endpoint > intersection >
// midpoint > onEdge > grid; ortho/Winkelraster ist eine Projektion (überlagert).
import type { Drawing2D, Project, Vec2, Wall } from "../model/types";
import { getWallType, wallTypeThickness } from "../model/types";
import { add, leftNormal, normalize, scale, sub } from "../model/geometry";
import { wallReferenceOffset } from "../model/wall";
import { centroid as roomCentroid } from "../core";
import { columnFootprint } from "../core";
import { stairOutline } from "../core";
import type { Project, Vec2 } from "../model/types";
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 { pointSegDist__geometry_drawingIndex as pointSegDist } from "../core";
import { sheetSnapSegments } from "./sheetSnapGeometry";
import { holdSnapSegments, releaseSnapSegments, snapOnSegments, type SegSnapCand } from "../core";
import { holdModelSnap, queryModelSnap, type ModelSnapCand } from "../core";
const dist = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y);
/** Bildschirm-px-Bonus je Snap-Art: höher = gewinnt knappe Vergleiche. */
/** Bildschirm-px-Bonus je Snap-Art: höher = gewinnt knappe Vergleiche (Kern: `snap.rs::priority`). */
const PRIORITY: Record<SnapKind, number> = {
endpoint: 7,
intersection: 5,
@@ -52,154 +45,9 @@ export interface SnapInput {
ctrl: boolean;
}
/** Eine Strecke als Snap-Quelle (Wandachse oder 2D-Segment). */
/** Eine Strecke als Snap-Quelle (Entwurf, Blatt-Geometrie, Verweil-Referenz). */
type Seg = [Vec2, Vec2];
/**
* Schichttrennlinien einer Wand: für jede kumulierte Schichtgrenze (inkl.
* beider Aussenflächen) eine zur Achse parallele Strecke, um den Betrag
* entlang `leftNormal(u)` verschoben. Spiegelt EXAKT die Offset-Berechnung aus
* `generatePlan.ts` (`addWallPoche`): Start bei `refOff − total/2`
* (`wallReferenceOffset`), danach je Schicht `+= layer.thickness` aufsummiert.
* Liefert `layers.length + 1` Segmente (leer bei unbekanntem Wandtyp).
*/
export function wallLayerBoundarySegments(project: Project, wall: Wall): Seg[] {
let wt;
try {
wt = getWallType(project, wall);
} catch {
return [];
}
const total = wallTypeThickness(wt);
const refOff = wallReferenceOffset(wall, total);
const u = normalize(sub(wall.end, wall.start));
const n = leftNormal(u);
const out: Seg[] = [];
let off = refOff - total / 2;
const boundary = (o: number): Seg => [
add(wall.start, scale(n, o)),
add(wall.end, scale(n, o)),
];
out.push(boundary(off)); // äussere Fläche
for (const layer of wt.layers) {
off += layer.thickness;
out.push(boundary(off)); // Schichtfuge (letzte = innere Fläche)
}
return out;
}
/** Kanten eines geschlossenen Polygons (Schlusspunkt nicht dupliziert). */
function closedPolySegs(pts: Vec2[]): Seg[] {
const segs: Seg[] = [];
for (let i = 0; i < pts.length - 1; i++) segs.push([pts[i], pts[i + 1]]);
if (pts.length > 2) segs.push([pts[pts.length - 1], pts[0]]);
return segs;
}
/** Strecken EINER Zeichnung (Fangkandidaten), je nach Form. */
function drawingSegs(d: Drawing2D, segs: Seg[]): void {
const g = d.geom;
if (g.shape === "line") segs.push([g.a, g.b]);
else if (g.shape === "xline") {
// Weit verlängert (wie beim Rendern) — Lot-/Nächster-Punkt-Snap soll
// entlang der ganzen (optisch unendlichen) Linie greifen, nicht nur
// zwischen den beiden gesetzten Punkten.
const dx = g.b.x - g.a.x, dy = g.b.y - g.a.y;
const len = Math.hypot(dx, dy);
if (len > 1e-6) {
const ux = dx / len, uy = dy / len, ext = 1000;
segs.push([
{ x: g.a.x - ux * ext, y: g.a.y - uy * ext },
{ x: g.b.x + ux * ext, y: g.b.y + uy * ext },
]);
}
}
else if (g.shape === "ray") {
// Wie xline, aber NUR über `b` hinaus verlängert (Anker `a` bleibt fest).
const dx = g.b.x - g.a.x, dy = g.b.y - g.a.y;
const len = Math.hypot(dx, dy);
if (len > 1e-6) {
const ux = dx / len, uy = dy / len, ext = 1000;
segs.push([g.a, { x: g.b.x + ux * ext, y: g.b.y + uy * ext }]);
}
}
else if (g.shape === "polyline") {
for (let i = 0; i < g.pts.length - 1; i++) segs.push([g.pts[i], g.pts[i + 1]]);
if (g.closed && g.pts.length > 2) segs.push([g.pts[g.pts.length - 1], g.pts[0]]);
} else if (g.shape === "rect") {
const c1 = g.min, c3 = g.max;
const c2 = { x: g.max.x, y: g.min.y }, c4 = { x: g.min.x, y: g.max.y };
segs.push([c1, c2], [c2, c3], [c3, c4], [c4, c1]);
} else if (g.shape === "bezier") {
const pts = sampleBezierChain(g.pts);
for (let i = 0; i < pts.length - 1; i++) segs.push([pts[i], pts[i + 1]]);
} else if (g.shape === "spline") {
const closed = g.closed && g.pts.length > 2;
const pts = g.mode === "control" ? sampleUniformBSpline(g.pts, closed) : sampleCatmullRom(g.pts, closed);
for (let i = 0; i < pts.length - 1; i++) segs.push([pts[i], pts[i + 1]]);
if (closed) segs.push([pts[pts.length - 1], pts[0]]);
}
}
/** Kreise/Bögen/Ellipsen & Co.: bei grossen Projekten ohne die vielen Linien. */
function nonLineDrawings(all: readonly Drawing2D[]): readonly Drawing2D[] {
return all.length > LARGE_DRAWINGS ? getSnapIndex(all).others : all;
}
/** Ab so vielen Zeichnungen: nur Strecken in Cursornähe (Raster-Index) statt aller. */
const LARGE_DRAWINGS = 2000;
interface SnapDrawingIndex {
/** Linien/Polylinien (Massenfall), räumlich indiziert. */
index: DrawingIndex | null;
/** Alle übrigen Formen (Kreis, Bogen, Rechteck, Spline, …) — wenige, immer geprüft. */
others: Drawing2D[];
}
const snapIndexCache = new WeakMap<readonly Drawing2D[], SnapDrawingIndex>();
/** Index je `drawings2d`-Array-Identität (Projekt-Updates teilen unveränderte Arrays). */
function getSnapIndex(drawings: readonly Drawing2D[]): SnapDrawingIndex {
let c = snapIndexCache.get(drawings);
if (!c) {
const indexable: Drawing2D[] = [];
const others: Drawing2D[] = [];
for (const d of drawings) (isIndexable(d) ? indexable : others).push(d);
c = { index: buildDrawingIndex(indexable), others };
snapIndexCache.set(drawings, c);
}
return c;
}
/**
* Zeichnungen des Geschosses, die für den Fang in Frage kommen: bei grossen
* Projekten (Kataster-Import, ~10^5 Zeichnungen) nur die in `r` Umkreis von `at`
* (+ alle Nicht-Linien-Formen), sonst alle.
*/
function snapDrawings(input: SnapInput, near?: { at: Vec2; r: number }): Drawing2D[] {
const all = input.project.drawings2d;
const ok = (d: Drawing2D) => d.levelId === input.levelId && input.visibleCodes.has(d.categoryCode);
const out: Drawing2D[] = [];
if (near && all.length > LARGE_DRAWINGS) {
const c = getSnapIndex(all);
if (c.index) {
for (const i of drawingsNear(c.index, near.at, near.r)) {
const d = c.index.drawings[i];
if (ok(d)) out.push(d);
}
}
for (const d of c.others) if (ok(d)) out.push(d);
return out;
}
for (const d of all) if (ok(d)) out.push(d);
return out;
}
/** 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[] = [];
@@ -210,155 +58,29 @@ function draftSegments(input: SnapInput): Seg[] {
}
/**
* 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.
* Nummer der im Kern gesammelten Fang-Kandidaten je Projekt/Geschoss/Sichtbarkeit (`modelSnap.ts`):
* ohne Kern-Aufruf, solange dasselbe Projekt-Objekt gefragt wird; nach einer Änderung liefert der
* Kern dieselbe Nummer, wenn die betroffenen Felder gleich geblieben sind.
*/
interface LevelSnap {
interface LevelHold {
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;
held: number;
}
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);
const levelHolds: LevelHold[] = [];
const MAX_LEVEL_HOLDS = 4;
function levelHold(input: SnapInput, fresh: boolean): number {
let e = levelHolds.find((h) => h.project === input.project && h.levelId === input.levelId && h.codes === input.visibleCodes);
if (e && !fresh) return e.held;
const held = holdModelSnap(input.project, input.levelId, 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);
e = { project: input.project, levelId: input.levelId, codes: input.visibleCodes, held };
levelHolds.push(e);
if (levelHolds.length > MAX_LEVEL_HOLDS) levelHolds.shift();
}
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;
if (!input.visibleCodes.has(w.categoryCode)) continue;
segs.push([w.start, w.end]);
for (const seg of wallLayerBoundarySegments(input.project, w)) segs.push(seg);
}
// Raum-/Decken-/Dach-/Treppen-/Stützen-Umrisse: bisher komplett blind (nur
// der Raum-Stempel-Anker war als Endpunkt fangbar, s. u.) — eine Wand oder
// Bemassung liess sich nicht bündig an eine Raum-/Dachkante setzen.
for (const room of input.project.rooms ?? []) {
if (room.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(room.categoryCode)) continue;
segs.push(...closedPolySegs(room.boundary));
}
for (const c of input.project.ceilings ?? []) {
if (c.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(c.categoryCode)) continue;
segs.push(...closedPolySegs(c.outline));
for (const hole of c.openings ?? []) segs.push(...closedPolySegs(hole));
}
for (const r of input.project.roofs ?? []) {
if (r.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(r.categoryCode)) continue;
segs.push(...closedPolySegs(r.outline));
}
for (const s of input.project.stairs ?? []) {
if (s.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(s.categoryCode)) continue;
const { polygon, spiral } = stairOutline(s, 0);
if (polygon) segs.push(...closedPolySegs(polygon));
else if (spiral) for (const line of spiral.lines) segs.push(line); // Innen-/Aussenbögen s. collectCircles
}
for (const col of input.project.columns ?? []) {
if (col.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(col.categoryCode)) continue;
if (col.profile.kind === "rect") segs.push(...closedPolySegs(columnFootprint(col)));
// Runde Stützen: s. collectCircles (Zentrum/Quadranten statt Vieleck-Kanten).
}
for (const d of snapDrawings(input, near)) drawingSegs(d, segs);
return segs;
}
/** Kreis-/Bogen-Geometrie für Center-/Quadrant-/Endpunkt-Snaps. `arc=null` =
* Vollkreis (keine Endpunkte, alle vier Quadranten). */
interface CircleGeom {
center: Vec2;
r: number;
arc: { a0: number; a1: number } | null;
}
/**
* Sammelt sichtbare Kreise/Bögen des aktiven Geschosses: `drawings2d`
* (circle/arc), runde Stützen (Zentrum/Quadranten statt Vieleck-Näherung)
* und die Innen-/Aussenbögen von Wendeltreppen (s. `stairOutline`).
*/
function collectCircles(input: SnapInput): CircleGeom[] {
const out: CircleGeom[] = [];
for (const d of nonLineDrawings(input.project.drawings2d)) {
if (d.levelId !== input.levelId) continue;
if (!input.visibleCodes.has(d.categoryCode)) continue;
const g = d.geom;
if (g.shape === "circle") out.push({ center: g.center, r: g.r, arc: null });
else if (g.shape === "arc")
out.push({ center: g.center, r: g.r, arc: { a0: g.a0, a1: g.a1 } });
}
for (const col of input.project.columns ?? []) {
if (col.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(col.categoryCode)) continue;
if (col.profile.kind === "round") {
out.push({ center: col.position, r: col.profile.radius, arc: null });
}
}
for (const s of input.project.stairs ?? []) {
if (s.floorId !== input.levelId) continue;
if (!input.visibleCodes.has(s.categoryCode)) continue;
const { spiral } = stairOutline(s, 0);
if (!spiral) continue;
for (const a of spiral.arcs) {
out.push({ center: { x: a.cx, y: a.cy }, r: a.r, arc: { a0: a.a0, a1: a.a1 } });
}
}
return out;
e.held = held;
return held;
}
// ── Verweil-Erkennung fürs Teilpunkte-Snapping ("divide") ───────────────────
@@ -441,79 +163,56 @@ export function computeSnap(input: SnapInput): SnapResult | null {
settings.endpoint ||
settings.perpendicular ||
settings.parallel;
// Bei grossen Projekten (Kataster-Import: ~10^5 Zeichnungen, Mio. Strecken) NUR
// die Strecken in Cursornähe — vorher wurde bei JEDER Mausbewegung die ganze
// 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[] | null = null;
// Abgeleitete Blatt-Geometrie (Schnitt/Ansicht, s. sheetSnapGeometry.ts): nur die Strecken in
// Cursornähe — eine Ansicht hat schnell Tausende Kanten, der paarweise Schnittpunkt-Fang bliebe
// sonst nicht flüssig.
let sheetNear: Seg[] = [];
if (needSegs) {
if (nearMode) {
const cand = collectSegments(input, { at: raw, r: intRadius });
const withDist = cand
.map((seg) => ({ seg, d: pointSegDist(raw, seg[0], seg[1]) }))
.filter((e) => e.d <= intRadius)
.sort((x, y) => x.d - y.d);
segs = withDist.filter((e) => e.d <= tolM).map((e) => e.seg);
// Schnittpunkte nur unter den nächsten Strecken (paarweise → quadratisch).
intSegs = withDist.slice(0, 64).map((e) => e.seg);
} else {
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,
// der paarweise Schnittpunkt-Fang bliebe sonst nicht flüssig.
const sheet = sheetSnapSegments(input.levelId);
if (sheet.length > 0) {
const near = sheet
const intRadius = tolM * 6;
sheetNear = sheet
.map((seg) => ({ seg, d: pointSegDist(raw, seg[0], seg[1]) }))
.filter((e) => e.d <= intRadius)
.sort((x, y) => x.d - y.d)
.slice(0, 64)
.map((e) => e.seg);
if (near.length > 0) {
segs = segs.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);
}
// Modell-Fang im Kern (`modelSnap.ts`): Strecken (Lot, Endpunkte, Mitte, Schnitt, Kante, nächste
// Strecke), Raum-Anker, Kreise/Bögen/Ellipsen; bei grossen Projekten (> 2000 Zeichnungen) nur die
// Strecken in Cursornähe.
const q = {
raw,
tolM,
pxPerMeter,
segs: needSegs,
perpendicular: settings.perpendicular,
endpoint: settings.endpoint,
midpoint: settings.midpoint,
intersection: settings.intersection,
onEdge: settings.onEdge,
center: settings.center,
tangent: settings.tangent,
lastPoint: input.lastPoint,
};
const draft = needSegs ? draftSegments(input) : [];
let m = queryModelSnap(levelHold(input, false), draft, sheetNear, q);
// Abgelegte Kandidaten verdrängt: neu ablegen und nochmals.
if (!m) m = queryModelSnap(levelHold(input, true), draft, sheetNear, q);
// Kern-Kandidat übernehmen, wenn er besser ist (gleiche Regel wie `consider`).
const offer = (c: SegSnapCand | null | undefined) => {
const offer = (c: ModelSnapCand | 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 };
const ref = c.kind === "perpendicular" || c.kind === "tangent" ? input.lastPoint ?? undefined : undefined;
best = { point: c.point, kind: c.kind, distPx: c.distPx, refA: ref };
}
};
// 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(segSnap?.nearest ?? null, settings.hoverDivideDelayMs);
const revealed = updateDwell(m?.nearest ?? null, settings.hoverDivideDelayMs);
if (revealed) {
const [a, b] = revealed;
const n = Math.max(2, Math.round(settings.hoverDivideCount));
@@ -555,72 +254,20 @@ 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; dann die Strecken-Endpunkte (Kern, Block A).
offer(segSnap?.a);
offer(m?.a);
// endpoint (Draft-Knoten + Raum-Stempel-Anker).
// endpoint: Draft-Knoten, dann Raum-Stempel-Anker (Kern).
if (settings.endpoint) {
for (const p of input.draftPoints) consider(p, "endpoint");
// Raum-Stempel-Anker (fixer Anker, sonst Flächenschwerpunkt) des Geschosses.
for (const p of roomAnchors(input)) consider(p, "endpoint");
offer(m?.anchors);
}
// 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);
offer(m?.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/
// Quadrant hängen an der `center`-Einstellung, die Endpunkte an `endpoint`,
// die Tangentenpunkte an `tangent` (+ zwingend `lastPoint`).
if (settings.center || settings.endpoint || settings.tangent) {
const TAU = Math.PI * 2;
const norm = (x: number) => ((x % TAU) + TAU) % TAU;
const onCircle = (c: CircleGeom, ang: number): Vec2 => ({
x: c.center.x + c.r * Math.cos(ang),
y: c.center.y + c.r * Math.sin(ang),
});
const inArc = (c: CircleGeom, ang: number): boolean => {
if (!c.arc) return true;
const sweep = norm(c.arc.a1 - c.arc.a0) || TAU;
return norm(ang - c.arc.a0) <= sweep + 1e-9;
};
for (const c of levelCircles(input)) {
if (settings.center) {
consider(c.center, "center");
// Volle CCW-Spanne (0 ⇒ Vollkreis); Quadrant nur, wenn im Bogen liegt.
for (let q = 0; q < 4; q++) {
const ang = q * (Math.PI / 2);
if (inArc(c, ang)) consider(onCircle(c, ang), "quadrant");
}
}
if (settings.endpoint && c.arc) {
consider(onCircle(c, c.arc.a0), "endpoint");
consider(onCircle(c, c.arc.a1), "endpoint");
}
// Tangente von aussen (lastPoint) an den Kreis: klassische Konstruktion
// — zwei Lösungen, Dreieck center/lastPoint/Tangentenpunkt ist bei T
// rechtwinklig, daher angAtC = acos(r/d) der Winkel zwischen center→
// lastPoint und center→T. Innerhalb/auf dem Kreis (d ≤ r) gibt es keine
// Tangente von aussen.
if (settings.tangent && input.lastPoint) {
const dx = input.lastPoint.x - c.center.x;
const dy = input.lastPoint.y - c.center.y;
const d = Math.hypot(dx, dy);
if (d > c.r + 1e-9) {
const thetaCP = Math.atan2(dy, dx);
const angAtC = Math.acos(Math.min(1, c.r / d));
for (const sign of [1, -1]) {
const ang = thetaCP + sign * angAtC;
if (inArc(c, ang)) consider(onCircle(c, ang), "tangent", input.lastPoint);
}
}
}
}
// Ellipse: nur der Mittelpunkt (keine Quadranten — bei gedrehter Ellipse
// wären die "Achsenpunkte" ohnehin keine Kreis-Quadranten mehr).
if (settings.center) {
for (const p of ellipseCenters(input)) consider(p, "center");
}
}
// Kreis-/Bogen-Snaps (Kern): Mittelpunkt + Quadranten (nur im Bogen-Bereich), Bogen-Endpunkte,
// Tangentenpunkte vom letzten Punkt; Ellipsen nur Mittelpunkt.
offer(m?.c);
if (best) return best;