[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

+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;