[K3d] Auswahl/Picken im Kern auf dem Plan-Puffer (räumlicher Index)
core/src/plan_pick.rs (+ web/plan_pick.rs, TS-Fassade src/plan/planView/planPick.ts): Index je Plan über die Abschnitte gehaltener Plan-Puffer — Raster der 2D-Zeichenlinien (gleiche Zellen/Reihenfolge wie segmentIndex.ts → gleiche Treffer), Polygone unter dem Punkt (oberstes/ unterstes, mit Pick-Feld), Symbol-Linien/-Bögen in Client-Pixeln, Kreis-/Bogen-Ringe, Besitzer (ownedBy). PlanView fragt nur noch ab (hitTest, pickRoom/Roof/Stair/Opening/…, pickDrawing, nearDrawingIds, Hervorhebung); segmentIndex.ts, ownerIndex.ts und die Schleifen über alle Primitive je Mausbewegung gelöscht. Gleich zur alten Fassung (25k Abfragen: Beispielprojekt + Überlagerung, 150 Zufallspläne, grosses Projekt). Grosses Projekt + 100k 2D-Linien: alle Hover-Abfragen zusammen 90 ms → 30 µs je Mausbewegung, Aufbau ~100 ms (lazy). Kern-only-Puffer ohne Schraffur-JSON (hatchJson: false). Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
17 files changed
+1173
-567
No files matched your search
+4
-1
@@ -184,6 +184,8 @@ export interface EncodeOptions {
|
||||
* 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];
|
||||
@@ -193,6 +195,7 @@ export interface EncodeOptions {
|
||||
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>();
|
||||
@@ -217,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);
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ export function planParts(plan: Plan, texts = false): PlanParts {
|
||||
at = r.end;
|
||||
}
|
||||
gap(prims.length);
|
||||
const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts }), hold: 0 } : null;
|
||||
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;
|
||||
@@ -128,8 +128,10 @@ export function greyedFlat(plan: Plan): Float64Array {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Abschnitte mit den Kern-Nummern der Puffer (legt fehlende ab). */
|
||||
function heldSegs(parts: PlanParts, fresh: boolean): Float64Array {
|
||||
/**
|
||||
* 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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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]);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -29,8 +29,8 @@ describe("planToRenderScene (Kern)", () => {
|
||||
});
|
||||
|
||||
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] };
|
||||
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] };
|
||||
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);
|
||||
|
||||
Reference in new issue
Block a user