[K4] Leistung: id-Suche indiziert (Kern-Index, Treffer-Positionen für applyOps), Commit ohne Kopie (Verlauf nur inverse Ops), Dach-Firsthöhe nach Inhalt gemerkt, Polylinien-Punkttyp im Kern
Objekt-Info und Griffe suchen über den Positions-Index des Dokuments (Lookup), TS-applyOps übernimmt die vom Kern getroffenen Positionen (doc_last_hits). Commit verschiebt die Ops ins Dokument; Redo entsteht beim Rückgängigmachen als Inverse der Inversen. setPolylineVertexType rechnet polyline_vertex.rs (bitgleich, 143 880 Fälle), TS-withVertexType gelöscht.
This commit is contained in:
22 files changed
+1168
-538
No files matched your search
@@ -234,7 +234,7 @@ export class ProjectDocument {
|
||||
}
|
||||
return { problems };
|
||||
}
|
||||
const project = applyOps(base, ops);
|
||||
const project = applyOps(base, ops, core().doc_last_hits(this.handle));
|
||||
this.mirror = project;
|
||||
return { project };
|
||||
}
|
||||
@@ -253,7 +253,7 @@ export class ProjectDocument {
|
||||
const r = fromMarkedJson<{ ops: CoreOp[]; notice?: string } | { problems: string[] }>(out);
|
||||
if ("problems" in r) return r;
|
||||
if (r.ops.length === 0) return { project: base, ops: r.ops, notice: r.notice };
|
||||
const project = applyOps(base, r.ops);
|
||||
const project = applyOps(base, r.ops, core().doc_last_hits(this.handle));
|
||||
this.mirror = project;
|
||||
return { project, ops: r.ops, notice: r.notice };
|
||||
}
|
||||
@@ -294,7 +294,7 @@ export class ProjectDocument {
|
||||
}
|
||||
const json = core()[fn](this.handle);
|
||||
if (!json) return null;
|
||||
const project = applyOps(base, JSON.parse(json) as CoreOp[]);
|
||||
const project = applyOps(base, JSON.parse(json) as CoreOp[], core().doc_last_hits(this.handle));
|
||||
this.mirror = project;
|
||||
return project;
|
||||
}
|
||||
|
||||
@@ -112,7 +112,6 @@ export {
|
||||
type PolylineVertexType,
|
||||
canSetVertexType,
|
||||
vertexTypeOf,
|
||||
withVertexType,
|
||||
} from "../geometry/polylineVertexType";
|
||||
|
||||
export {
|
||||
|
||||
@@ -128,3 +128,44 @@ describe("applyOps (schnelle Fassung) = Referenz", () => {
|
||||
expect(out.walls).toEqual([{ id: "a", z: 1 }, { id: "b" }, { id: "c" }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyOps: id-Index über die Aufrufe hinweg", () => {
|
||||
it("Ketten und Verzweigungen grosser Listen (geteilter Index) = Referenz", () => {
|
||||
const walls = Array.from({ length: 200 }, (_, i) => ({ ...sampleProject.walls[0], id: `w${i}` }));
|
||||
const big: Project = { ...sampleProject, walls, drawings2d: [] };
|
||||
const r = rng(7);
|
||||
const history: Project[] = [big];
|
||||
for (let step = 0; step < 600; step++) {
|
||||
// Meist auf dem letzten Stand weiter, manchmal auf einem älteren (Undo-Basis, fremde Projekte).
|
||||
const base = r() < 0.7 ? history[history.length - 1] : history[Math.floor(r() * history.length)];
|
||||
const ids = ["w0", "w5", "w199", "w150", `n${Math.floor(r() * 40)}`, `n${Math.floor(r() * 40)}`];
|
||||
const ops: CoreOp[] = [];
|
||||
for (let k = 0, n = 1 + Math.floor(r() * 4); k < n; k++) {
|
||||
const x = r();
|
||||
const id = ids[Math.floor(r() * ids.length)];
|
||||
if (x < 0.6) ops.push({ kind: "replace", collection: "walls", entity: { id, v: step } });
|
||||
else if (x < 0.8) ops.push({ kind: "add", collection: "walls", items: [{ id: `n${Math.floor(r() * 40)}` }] });
|
||||
else if (x < 0.9) ops.push({ kind: "add", collection: "walls", items: [{ id }], at: Math.floor(r() * 300) });
|
||||
else ops.push({ kind: "remove", collection: "walls", ids: [id] });
|
||||
}
|
||||
// Positions-Hinweise des Kerns (erstes Vorkommen, wie `Document::last_hits`): richtig, auf ein
|
||||
// anderes Element, ausserhalb oder fehlend — das Ergebnis bleibt gleich.
|
||||
let hits: number[] | undefined;
|
||||
if (r() < 0.6) {
|
||||
hits = [];
|
||||
let cur = base;
|
||||
for (const op of ops) {
|
||||
const list = cur.walls as unknown as Entity[];
|
||||
const first = op.kind === "replace" ? list.findIndex((e) => e.id === op.entity.id) : -1;
|
||||
const other = list.findIndex((e, i) => i >= Math.floor(r() * list.length) && op.kind === "replace" && e.id !== op.entity.id);
|
||||
const x = r();
|
||||
hits.push(x < 0.6 ? first : x < 0.8 ? other : x < 0.9 ? list.length + 3 : -1);
|
||||
cur = referenceApplyOps(cur, [op]);
|
||||
}
|
||||
}
|
||||
const a = applyOps(base, ops, hits);
|
||||
expect(JSON.stringify(a.walls)).toBe(JSON.stringify(referenceApplyOps(base, ops).walls));
|
||||
history.push(a);
|
||||
}
|
||||
});
|
||||
});
|
||||
+76
-35
@@ -37,25 +37,79 @@ export type CoreOp =
|
||||
|
||||
/**
|
||||
* Wendet eine Op-Folge rein an (kein Zugriff auf Store/UI). Unberührte Listen und Elemente behalten
|
||||
* ihre Identität. Innerhalb eines Aufrufs wird jede Liste höchstens einmal kopiert und für
|
||||
* `replace`-Serien (Auswahl verschieben: hunderte Elemente) über einen id-Index angesprochen —
|
||||
* Ergebnis gleich der einfachen Fassung (Test `ops.apply.test.ts`).
|
||||
* ihre Identität. Innerhalb eines Aufrufs wird jede Liste höchstens einmal kopiert. `replace` findet
|
||||
* sein Element über `hits` (je Op die Position, die der Kern beim Anwenden getroffen hat,
|
||||
* `ProjectDocument`; wird nachgeprüft) oder sonst über {@link indexOfId} — ein Griff-Schritt an einer
|
||||
* grossen Liste sucht so nicht linear. Ergebnis gleich der einfachen Fassung (Test `ops.apply.test.ts`).
|
||||
*/
|
||||
export function applyOps(project: Project, ops: readonly CoreOp[]): Project {
|
||||
export function applyOps(project: Project, ops: readonly CoreOp[], hits?: ArrayLike<number>): Project {
|
||||
if (ops.length === 0) return project;
|
||||
const st: ApplyState = { cur: { ...(project as unknown as Record<string, unknown>) }, owned: new Set(), index: new Map() };
|
||||
for (const op of ops) applyOne(st, op);
|
||||
const st: ApplyState = { cur: { ...(project as unknown as Record<string, unknown>) }, owned: new Set(), hit: -1 };
|
||||
for (let k = 0; k < ops.length; k++) {
|
||||
st.hit = hits?.[k] ?? -1;
|
||||
applyOne(st, ops[k]);
|
||||
}
|
||||
return st.cur as unknown as Project;
|
||||
}
|
||||
|
||||
/** Zustand eines `applyOps`-Aufrufs: `cur` ist eine eigene Kopie der obersten Ebene; Listen in
|
||||
* `owned` wurden in diesem Aufruf neu angelegt (dürfen verändert werden), `index` = id → Position
|
||||
* (erstes Vorkommen) solcher Listen. */
|
||||
* `owned` wurden in diesem Aufruf neu angelegt (dürfen verändert werden); `hit` = vermutete Position
|
||||
* des Elements der laufenden `replace`-Op (−1 = keine). */
|
||||
interface ApplyState {
|
||||
cur: Record<string, unknown>;
|
||||
owned: Set<string>;
|
||||
/** `null` = einmal linear gesucht, der Index wird bei der nächsten Suche gebaut. */
|
||||
index: Map<string, Map<string, number> | null>;
|
||||
hit: number;
|
||||
}
|
||||
|
||||
// ── id-Index der Listen ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* id → Position (erstes Vorkommen) je Liste, für Suchen ohne Positions-Hinweis des Kerns (Op-Bauer,
|
||||
* `findItem`). Listen der Leseansicht ändern sich nie (jede Änderung legt eine neue an); eine Kopie mit
|
||||
* denselben Positionen (`replace`, `add` am Ende) übernimmt den Index der Vorlage samt der neuen ids.
|
||||
* Teilen sich so mehrere Listen einen Index, enthält er die ids jeder von ihnen; ein Treffer wird an
|
||||
* der Liste nachgeprüft (sonst lineare Suche), kein Eintrag heisst „nicht enthalten". Der Index kostet
|
||||
* in V8 etwa das Zwanzigfache einer linearen Suche (20 000 Elemente ≈ 6 ms): gebaut wird er erst bei
|
||||
* der zweiten Suche in derselben Listen-Linie (`null` = einmal linear gesucht).
|
||||
*/
|
||||
const ID_INDEX = new WeakMap<readonly unknown[], Map<unknown, number> | null>();
|
||||
|
||||
/** Ab dieser Länge wird ein Index gebaut (darunter ist die lineare Suche billiger). */
|
||||
const INDEX_MIN_LEN = 32;
|
||||
|
||||
/** Position des ersten Elements mit `id` in `list` (−1 = keins); Index je Listen-Linie gemerkt. */
|
||||
export function indexOfId(list: readonly unknown[], id: unknown): number {
|
||||
const linear = () => list.findIndex((e) => (e as Entity | null)?.id === id);
|
||||
if (list.length < INDEX_MIN_LEN) return linear();
|
||||
let idx = ID_INDEX.get(list);
|
||||
if (idx === undefined) {
|
||||
ID_INDEX.set(list, null);
|
||||
return linear();
|
||||
}
|
||||
if (idx === null) {
|
||||
idx = new Map();
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const k = (list[i] as Entity | null)?.id;
|
||||
if (!idx.has(k)) idx.set(k, i);
|
||||
}
|
||||
ID_INDEX.set(list, idx);
|
||||
}
|
||||
const i = idx.get(id);
|
||||
if (i === undefined) return -1;
|
||||
return (list[i] as Entity | null)?.id === id ? i : linear();
|
||||
}
|
||||
|
||||
/** `copy` hat dieselben Positionen wie `src` (plus Elemente am Ende): Index (bzw. Such-Marke) übernehmen. */
|
||||
function shareIndex(src: readonly unknown[], copy: readonly unknown[]): void {
|
||||
const idx = ID_INDEX.get(src);
|
||||
if (idx === undefined) return;
|
||||
if (idx !== null) {
|
||||
for (let i = src.length; i < copy.length; i++) {
|
||||
const k = (copy[i] as Entity | null)?.id;
|
||||
if (!idx.has(k)) idx.set(k, i);
|
||||
}
|
||||
}
|
||||
ID_INDEX.set(copy, idx);
|
||||
}
|
||||
|
||||
function listOf(cur: Record<string, unknown>, collection: string): Entity[] {
|
||||
@@ -63,11 +117,10 @@ function listOf(cur: Record<string, unknown>, collection: string): Entity[] {
|
||||
return Array.isArray(v) ? (v as Entity[]) : [];
|
||||
}
|
||||
|
||||
/** Setzt `collection` auf eine neue (eigene) Liste; ein vorhandener Index verfällt. */
|
||||
/** Setzt `collection` auf eine neue (eigene) Liste. */
|
||||
function putList(st: ApplyState, collection: string, list: Entity[]): void {
|
||||
st.cur[collection] = list;
|
||||
st.owned.add(collection);
|
||||
st.index.delete(collection);
|
||||
}
|
||||
|
||||
function applyOne(st: ApplyState, op: CoreOp): void {
|
||||
@@ -76,7 +129,6 @@ function applyOne(st: ApplyState, op: CoreOp): void {
|
||||
case "setField": {
|
||||
// Der Wert gehört dem Aufrufer: nie verändern.
|
||||
st.owned.delete(op.key);
|
||||
st.index.delete(op.key);
|
||||
if (op.value !== undefined && op.at !== undefined && !(op.key in cur)) {
|
||||
// Neues Feld an Position `at` (wie `shift_insert` im Kern).
|
||||
const entries = Object.entries(cur);
|
||||
@@ -91,7 +143,9 @@ function applyOne(st: ApplyState, op: CoreOp): void {
|
||||
case "add": {
|
||||
const list = listOf(cur, op.collection);
|
||||
const at = op.at === undefined ? list.length : Math.max(0, Math.min(list.length, op.at));
|
||||
putList(st, op.collection, [...list.slice(0, at), ...op.items, ...list.slice(at)]);
|
||||
const next = [...list.slice(0, at), ...op.items, ...list.slice(at)];
|
||||
if (at === list.length) shareIndex(list, next);
|
||||
putList(st, op.collection, next);
|
||||
return;
|
||||
}
|
||||
case "replace": {
|
||||
@@ -99,30 +153,17 @@ function applyOne(st: ApplyState, op: CoreOp): void {
|
||||
let list: Entity[];
|
||||
if (st.owned.has(c)) list = cur[c] as Entity[];
|
||||
else {
|
||||
list = listOf(cur, c).slice();
|
||||
const src = listOf(cur, c);
|
||||
list = src.slice();
|
||||
shareIndex(src, list);
|
||||
putList(st, c, list);
|
||||
}
|
||||
// Erste Suche in dieser Liste linear (ein Drag-Schritt), ab der zweiten über den Index.
|
||||
let idx = st.index.get(c);
|
||||
let at: number | undefined;
|
||||
if (idx === undefined) {
|
||||
st.index.set(c, null);
|
||||
const i = list.findIndex((e) => e?.id === op.entity.id);
|
||||
at = i < 0 ? undefined : i;
|
||||
} else {
|
||||
if (idx === null) {
|
||||
idx = new Map();
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const id = list[i]?.id;
|
||||
if (!idx.has(id)) idx.set(id, i);
|
||||
}
|
||||
st.index.set(c, idx);
|
||||
}
|
||||
at = idx.get(op.entity.id);
|
||||
}
|
||||
if (at === undefined) {
|
||||
idx?.set(op.entity.id, list.length);
|
||||
const h = st.hit;
|
||||
const at = h >= 0 && h < list.length && list[h]?.id === op.entity.id ? h : indexOfId(list, op.entity.id);
|
||||
if (at < 0) {
|
||||
list.push(op.entity);
|
||||
const idx = ID_INDEX.get(list);
|
||||
if (idx && !idx.has(op.entity.id)) idx.set(op.entity.id, list.length - 1);
|
||||
} else list[at] = op.entity;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// {@link opsMutation} die Ops mit — `setProject` nimmt dann die Ops ohne Differenz.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { applyOps } from "./ops";
|
||||
import { applyOps, indexOfId } from "./ops";
|
||||
import type { CoreOp } from "./ops";
|
||||
|
||||
/** Projekt-Felder, die Listen von Elementen mit `id` sind (walls, drawings2d, rooms, …). */
|
||||
@@ -34,7 +34,9 @@ export function itemsOf<K extends EntityCollection>(p: Project, collection: K):
|
||||
|
||||
/** Element `id` aus `collection` (erstes Vorkommen). */
|
||||
export function findItem<K extends EntityCollection>(p: Project, collection: K, id: string): EntityOf<K> | undefined {
|
||||
return itemsOf(p, collection).find((e) => (e as { id: string }).id === id);
|
||||
const list = itemsOf(p, collection);
|
||||
const i = indexOfId(list, id);
|
||||
return i < 0 ? undefined : list[i];
|
||||
}
|
||||
|
||||
/** Ersetzt ein Element (gleiche id, Position bleibt). */
|
||||
|
||||
@@ -28,6 +28,7 @@ export type GripRequest =
|
||||
| { op: "ceilingEdge" | "roomEdge"; id: string; a: number; b: number; delta: P }
|
||||
| { op: "insertPoint"; id: string; seg: number; pt: P }
|
||||
| { op: "deletePoint"; id: string; index: number }
|
||||
| { op: "vertexType"; id: string; index: number; vertexType: "corner" | "arc" | "spline" }
|
||||
| { op: "wallThickness" | "ceilingThickness"; id: string; thickness: number; newId: string; newName: string };
|
||||
|
||||
/** Punkt als Anfrage-Paar. */
|
||||
|
||||
@@ -1,59 +1,61 @@
|
||||
// Punkttypen einer Polylinie: Rechnung im Kern (`polyline_vertex.rs`, eigene Rust-Tests); hier die
|
||||
// Fassade für das Kontextmenü und die Store-Aktion `setPolylineVertexType` (Griff-Änderung im Kern).
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { bulgeArc, bulgeArcPoints } from "./bulge";
|
||||
import { canSetVertexType, vertexTypeOf, withVertexType } from "./polylineVertexType";
|
||||
import { canSetVertexType, vertexTypeOf } from "./polylineVertexType";
|
||||
import { getState } from "../state/appStore";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Drawing2D, Vec2 } from "../model/types";
|
||||
|
||||
const g = { pts: [{ x: 0, y: 0 }, { x: 2, y: 1 }, { x: 4, y: 0 }, { x: 6, y: 1 }], closed: false };
|
||||
|
||||
/** Setzt den Punkttyp über den Store und liefert die Bulges (fehlend = alle gerade). */
|
||||
function setType(pts: Vec2[], closed: boolean, i: number, type: "corner" | "arc" | "spline", bulge?: number[]): number[] | undefined {
|
||||
const d = { id: "pl", levelId: sampleProject.drawingLevels[0].id, categoryCode: "01", geom: { shape: "polyline", pts, closed, ...(bulge ? { bulge } : {}) } };
|
||||
getState().loadProject({ ...structuredClone(sampleProject), drawings2d: [d as Drawing2D] });
|
||||
getState().setPolylineVertexType("pl", i, type);
|
||||
const geom = getState().project.drawings2d[0].geom;
|
||||
return geom.shape === "polyline" ? geom.bulge : undefined;
|
||||
}
|
||||
|
||||
describe("Punkttypen einer Polylinie", () => {
|
||||
it("Eckpunkt setzt beide Nachbarsegmente gerade", () => {
|
||||
const b = withVertexType({ ...g, bulge: [0.3, -0.2, 0.1] }, 1, "corner");
|
||||
expect(b).toEqual([0, 0, 0.1]);
|
||||
expect(setType(g.pts, false, 1, "corner", [0.3, -0.2, 0.1])).toEqual([0, 0, 0.1]);
|
||||
expect(setType(g.pts, false, 1, "corner", [0.3, -0.2, 0])).toBeUndefined();
|
||||
});
|
||||
|
||||
it("Bogenpunkt: beide Segmente liegen auf EINEM Kreis durch die drei Punkte", () => {
|
||||
const b = withVertexType(g, 1, "arc");
|
||||
const b = setType(g.pts, false, 1, "arc")!;
|
||||
const a1 = bulgeArc(g.pts[0], g.pts[1], b[0])!;
|
||||
const a2 = bulgeArc(g.pts[1], g.pts[2], b[1])!;
|
||||
expect(a1).not.toBeNull();
|
||||
expect(Math.hypot(a1.center.x - a2.center.x, a1.center.y - a2.center.y)).toBeLessThan(1e-6);
|
||||
expect(a1.r).toBeCloseTo(a2.r, 6);
|
||||
expect(vertexTypeOf({ ...g, bulge: b }, 1)).toBe("arc");
|
||||
// Die Bögen bauchen NACH OBEN aus (Punkt 1 liegt oben) — kein Zickzack über den Kreis
|
||||
const mid1 = bulgeArcPoints(g.pts[0], g.pts[1], b[0]);
|
||||
const apex = mid1[mid1.length / 2 | 0];
|
||||
expect(apex.y).toBeGreaterThan(0.5);
|
||||
expect(mid1[(mid1.length / 2) | 0].y).toBeGreaterThan(0.5);
|
||||
});
|
||||
|
||||
it("Splinepunkt: Tangenten beider Segmente im Punkt stimmen überein", () => {
|
||||
const g = { pts: [{ x: 0, y: 0 }, { x: 2, y: 1 }, { x: 5, y: 0.2 }], closed: false };
|
||||
const b = withVertexType(g, 1, "spline");
|
||||
// exakte Tangenten aus den Bögen (senkrecht zum Radius, Richtung nach Umlaufsinn)
|
||||
const tan = (a: { x: number; y: number }, c: { x: number; y: number }, bb: number, atEnd: boolean) => {
|
||||
const arc = bulgeArc(a, c, bb)!;
|
||||
const ang = atEnd ? arc.a0 + arc.sweep : arc.a0;
|
||||
const sg = Math.sign(arc.sweep);
|
||||
return Math.atan2(Math.cos(ang) * sg, -Math.sin(ang) * sg);
|
||||
};
|
||||
const t1 = tan(g.pts[0], g.pts[1], b[0], true);
|
||||
const t2 = tan(g.pts[1], g.pts[2], b[1], false);
|
||||
expect(Math.abs(t1 - t2)).toBeLessThan(1e-6);
|
||||
// Tangente = Richtung Vorgänger→Nachfolger
|
||||
expect(Math.abs(t2 - Math.atan2(0.2, 5))).toBeLessThan(1e-6);
|
||||
expect(vertexTypeOf({ ...g, bulge: b }, 1)).toBe("spline");
|
||||
});
|
||||
|
||||
it("offene Enden: Bogen/Spline nicht möglich, Ecke schon", () => {
|
||||
it("Splinepunkt: Typ wird erkannt, offene Enden lassen nur die Ecke zu", () => {
|
||||
const pts = [{ x: 0, y: 0 }, { x: 2, y: 1 }, { x: 5, y: 0.2 }];
|
||||
expect(vertexTypeOf({ pts, closed: false, bulge: setType(pts, false, 1, "spline") }, 1)).toBe("spline");
|
||||
expect(vertexTypeOf(g, 1)).toBe("corner");
|
||||
expect(canSetVertexType(g, 0, "arc")).toBe(false);
|
||||
expect(canSetVertexType(g, 3, "spline")).toBe(false);
|
||||
expect(canSetVertexType(g, 0, "corner")).toBe(true);
|
||||
expect(canSetVertexType(g, 1, "spline")).toBe(true);
|
||||
});
|
||||
|
||||
it("geschlossene Polylinie: erster Punkt hat beide Nachbarn", () => {
|
||||
const sq = { pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }], closed: true };
|
||||
const b = withVertexType(sq, 0, "arc");
|
||||
it("geschlossene Polylinie: erster Punkt hat beide Nachbarn; gesperrt ändert nichts", () => {
|
||||
const sq = [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }];
|
||||
const b = setType(sq, true, 0, "arc")!;
|
||||
expect(b.length).toBe(4);
|
||||
expect(b[3]).not.toBe(0);
|
||||
expect(b[0]).not.toBe(0);
|
||||
expect(b[1]).toBe(0);
|
||||
const depth = getState().undoDepth;
|
||||
getState().updateDrawing2D("pl", { locked: true });
|
||||
getState().setPolylineVertexType("pl", 0, "corner");
|
||||
expect(getState().undoDepth).toBe(depth + 1);
|
||||
});
|
||||
});
|
||||
@@ -1,19 +1,11 @@
|
||||
// Punkttypen einer Polylinie (ArchiCAD/Vectorworks-artig): Eckpunkt, Bogenpunkt,
|
||||
// Splinepunkt. Rein als Umrechnung der Segment-Bögen (`bulge`) der beiden am Punkt
|
||||
// anliegenden Segmente — alle Renderer/Exporte verstehen Bulges bereits, es gibt
|
||||
// also kein neues Geometrie-Feld.
|
||||
//
|
||||
// • Eckpunkt: beide Segmente gerade (bulge 0).
|
||||
// • Bogenpunkt: EIN Kreisbogen durch Vorgänger, Punkt und Nachfolger.
|
||||
// • Splinepunkt: tangential glatter Übergang — die Tangente im Punkt ist parallel
|
||||
// zur Verbindung Vorgänger→Nachfolger (wie bei einer Catmull-Rom-Kurve), beide
|
||||
// Segmente werden zu Bögen, die diese Tangente teilen.
|
||||
//
|
||||
// Die Bögen werden über ihren SCHEITELPUNKT bestimmt und mit `bulgeFromSagittaPoint`
|
||||
// in einen Bulge übersetzt — so bleibt die Vorzeichen-Konvention an EINER Stelle.
|
||||
// Punkttypen einer Polylinie (ArchiCAD/Vectorworks-artig): Eckpunkt, Bogenpunkt, Splinepunkt — als
|
||||
// Umrechnung der Segment-Bögen (`bulge`) der beiden am Punkt anliegenden Segmente. Gerechnet im
|
||||
// Rust-Kern (`src-tauri/core/src/polyline_vertex.rs`): das Setzen als Griff-Änderung auf dem Dokument
|
||||
// (Store `setPolylineVertexType`, Anfrage `vertexType`), die Abfrage für das Kontextmenü hier über die
|
||||
// Bindung `polyline_vertex_info`.
|
||||
|
||||
import type { Vec2 } from "../model/types";
|
||||
import { bulgeArc, bulgeFromSagittaPoint } from "./bulge";
|
||||
import { core } from "../engine/coreWasm";
|
||||
|
||||
export type PolylineVertexType = "corner" | "arc" | "spline";
|
||||
|
||||
@@ -23,160 +15,24 @@ interface PolylineLike {
|
||||
bulge?: number[];
|
||||
}
|
||||
|
||||
const EPS = 1e-9;
|
||||
const TYPES: PolylineVertexType[] = ["corner", "arc", "spline"];
|
||||
|
||||
/** Indizes des ein- und ausgehenden Segments von Punkt `i` (null = keins). */
|
||||
function adjacentSegments(n: number, closed: boolean, i: number): { inSeg: number | null; outSeg: number | null } {
|
||||
const inSeg = i > 0 ? i - 1 : closed ? n - 1 : null;
|
||||
const outSeg = i < n - 1 ? i : closed ? n - 1 : null;
|
||||
return { inSeg, outSeg };
|
||||
}
|
||||
|
||||
/** Nachbarpunkte von `i` (null an offenen Enden). */
|
||||
function neighbors(g: PolylineLike, i: number): { prev: Vec2 | null; next: Vec2 | null } {
|
||||
const n = g.pts.length;
|
||||
const prev = i > 0 ? g.pts[i - 1] : g.closed ? g.pts[n - 1] : null;
|
||||
const next = i < n - 1 ? g.pts[i + 1] : g.closed ? g.pts[0] : null;
|
||||
return { prev, next };
|
||||
}
|
||||
|
||||
const cross = (a: Vec2, b: Vec2) => a.x * b.y - a.y * b.x;
|
||||
const sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y });
|
||||
|
||||
/** Umkreismittelpunkt von a,b,c (null bei kollinearen Punkten). */
|
||||
function circumcenter(a: Vec2, b: Vec2, c: Vec2): Vec2 | null {
|
||||
const d = 2 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));
|
||||
if (Math.abs(d) < EPS) return null;
|
||||
const a2 = a.x * a.x + a.y * a.y, b2 = b.x * b.x + b.y * b.y, c2 = c.x * c.x + c.y * c.y;
|
||||
return {
|
||||
x: (a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d,
|
||||
y: (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulge des Kreisbogens a→b auf dem Kreis um `c`, und zwar des Bogens, der NICHT
|
||||
* durch `other` läuft (Scheitel auf der anderen Seite der Sehne als `other`).
|
||||
*/
|
||||
function bulgeOnCircle(a: Vec2, b: Vec2, c: Vec2, other: Vec2): number {
|
||||
const r = Math.hypot(a.x - c.x, a.y - c.y);
|
||||
const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
|
||||
let u = sub(mid, c);
|
||||
let len = Math.hypot(u.x, u.y);
|
||||
if (len < EPS) {
|
||||
const d = sub(b, a);
|
||||
u = { x: -d.y, y: d.x };
|
||||
len = Math.hypot(u.x, u.y);
|
||||
/** `[typ, ecke, bogen, spline]` des Kerns (typ −1 = gemischt/kein Punkt; danach setzbar 1/0). */
|
||||
function info(g: PolylineLike, i: number): Float64Array {
|
||||
const pts = new Float64Array(g.pts.length * 2);
|
||||
for (let k = 0; k < g.pts.length; k++) {
|
||||
pts[2 * k] = g.pts[k].x;
|
||||
pts[2 * k + 1] = g.pts[k].y;
|
||||
}
|
||||
u = { x: u.x / len, y: u.y / len };
|
||||
const side = (p: Vec2) => Math.sign(cross(sub(b, a), sub(p, a)));
|
||||
const cand1 = { x: c.x + u.x * r, y: c.y + u.y * r };
|
||||
const cand2 = { x: c.x - u.x * r, y: c.y - u.y * r };
|
||||
const apex = side(cand1) !== side(other) ? cand1 : cand2;
|
||||
return bulgeFromSagittaPoint(a, b, apex);
|
||||
}
|
||||
|
||||
/** Tangente (Fahrtrichtung a→b) des Bulge-Bogens am Anfang bzw. Ende. */
|
||||
function arcTangent(a: Vec2, b: Vec2, bulge: number, atEnd: boolean): Vec2 {
|
||||
const arc = bulgeArc(a, b, bulge);
|
||||
if (!arc) {
|
||||
const d = sub(b, a);
|
||||
const l = Math.hypot(d.x, d.y) || 1;
|
||||
return { x: d.x / l, y: d.y / l };
|
||||
}
|
||||
const ang = atEnd ? arc.a0 + arc.sweep : arc.a0;
|
||||
const s = Math.sign(arc.sweep) || 1;
|
||||
return { x: -Math.sin(ang) * s, y: Math.cos(ang) * s };
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulge des Bogens a→b mit gegebener Tangente `t` am Ende (atEnd) bzw. Anfang.
|
||||
* Betrag aus dem Winkel Sehne↔Tangente, Vorzeichen NUMERISCH gewählt (die
|
||||
* Variante, deren tatsächliche Tangente zu `t` passt).
|
||||
*/
|
||||
function bulgeWithTangent(a: Vec2, b: Vec2, t: Vec2, atEnd: boolean): number {
|
||||
const c = sub(b, a);
|
||||
const ang = Math.abs(Math.atan2(cross(c, t), c.x * t.x + c.y * t.y));
|
||||
const mag = Math.abs(bulgeFromApexAngle(a, b, ang));
|
||||
if (mag < 1e-9) return 0;
|
||||
const dot = (v: Vec2) => v.x * t.x + v.y * t.y;
|
||||
return dot(arcTangent(a, b, mag, atEnd)) >= dot(arcTangent(a, b, -mag, atEnd)) ? mag : -mag;
|
||||
}
|
||||
|
||||
const bulgeWithEndTangent = (a: Vec2, b: Vec2, t: Vec2) => bulgeWithTangent(a, b, t, true);
|
||||
const bulgeWithStartTangent = (a: Vec2, b: Vec2, t: Vec2) => bulgeWithTangent(a, b, t, false);
|
||||
|
||||
/**
|
||||
* Bogen über der Sehne a→b mit halbem Öffnungswinkel |half| (Sehne↔Tangente);
|
||||
* Vorzeichen: >0 Scheitel links der Sehne, <0 rechts. Über den Scheitelpunkt in
|
||||
* einen Bulge übersetzt.
|
||||
*/
|
||||
function bulgeFromApexAngle(a: Vec2, b: Vec2, half: number): number {
|
||||
if (Math.abs(half) < 1e-6) return 0;
|
||||
// Begrenzen: knapp unter einem Halbkreis je Segment (sonst kippt der Bogen).
|
||||
const h2 = Math.max(-Math.PI / 2 + 0.01, Math.min(Math.PI / 2 - 0.01, half));
|
||||
const d = sub(b, a);
|
||||
const chord = Math.hypot(d.x, d.y);
|
||||
if (chord < EPS) return 0;
|
||||
const left = { x: -d.y / chord, y: d.x / chord };
|
||||
const s = (chord / 2) * Math.tan(h2 / 2); // Pfeilhöhe
|
||||
const apex = { x: (a.x + b.x) / 2 + left.x * s, y: (a.y + b.y) / 2 + left.y * s };
|
||||
return bulgeFromSagittaPoint(a, b, apex);
|
||||
return core().polyline_vertex_info(pts, Float64Array.from(g.bulge ?? []), !!g.closed, i);
|
||||
}
|
||||
|
||||
/** Ist Punkttyp `type` am Punkt `i` möglich? (Bogen/Spline brauchen beide Nachbarn.) */
|
||||
export function canSetVertexType(g: PolylineLike, i: number, type: PolylineVertexType): boolean {
|
||||
if (i < 0 || i >= g.pts.length) return false;
|
||||
if (type === "corner") return true;
|
||||
const { prev, next } = neighbors(g, i);
|
||||
return !!prev && !!next;
|
||||
return info(g, i)[1 + TYPES.indexOf(type)] === 1;
|
||||
}
|
||||
|
||||
/** Aktueller Typ (Heuristik): beide Nachbarsegmente gerade → Eckpunkt, sonst null (gemischt). */
|
||||
export function vertexTypeOf(g: PolylineLike, i: number): PolylineVertexType | null {
|
||||
const { inSeg, outSeg } = adjacentSegments(g.pts.length, g.closed, i);
|
||||
const b = (k: number | null) => (k === null ? 0 : g.bulge?.[k] ?? 0);
|
||||
if (Math.abs(b(inSeg)) < 1e-9 && Math.abs(b(outSeg)) < 1e-9) return "corner";
|
||||
const { prev, next } = neighbors(g, i);
|
||||
if (!prev || !next || inSeg === null || outSeg === null) return null;
|
||||
const a1 = bulgeArc(prev, g.pts[i], b(inSeg));
|
||||
const a2 = bulgeArc(g.pts[i], next, b(outSeg));
|
||||
if (a1 && a2 && Math.hypot(a1.center.x - a2.center.x, a1.center.y - a2.center.y) < 1e-6 * (1 + a1.r)) return "arc";
|
||||
return "spline";
|
||||
}
|
||||
|
||||
/** Neue Bulge-Liste mit Punkttyp `type` an Punkt `i` (Eingabe bleibt unverändert). */
|
||||
export function withVertexType(g: PolylineLike, i: number, type: PolylineVertexType): number[] {
|
||||
const n = g.pts.length;
|
||||
const segCount = g.closed ? n : n - 1;
|
||||
const bulge = Array.from({ length: segCount }, (_, k) => g.bulge?.[k] ?? 0);
|
||||
if (!canSetVertexType(g, i, type)) return bulge;
|
||||
const { inSeg, outSeg } = adjacentSegments(n, g.closed, i);
|
||||
const q = g.pts[i];
|
||||
const { prev, next } = neighbors(g, i);
|
||||
if (type === "corner") {
|
||||
if (inSeg !== null) bulge[inSeg] = 0;
|
||||
if (outSeg !== null) bulge[outSeg] = 0;
|
||||
return bulge;
|
||||
}
|
||||
const p = prev!, r = next!;
|
||||
if (type === "arc") {
|
||||
const c = circumcenter(p, q, r);
|
||||
if (!c) {
|
||||
bulge[inSeg!] = 0;
|
||||
bulge[outSeg!] = 0;
|
||||
return bulge;
|
||||
}
|
||||
bulge[inSeg!] = bulgeOnCircle(p, q, c, r);
|
||||
bulge[outSeg!] = bulgeOnCircle(q, r, c, p);
|
||||
return bulge;
|
||||
}
|
||||
// spline: Tangente parallel zu prev→next
|
||||
const t = sub(r, p);
|
||||
const tl = Math.hypot(t.x, t.y);
|
||||
if (tl < EPS) return bulge;
|
||||
const tu = { x: t.x / tl, y: t.y / tl };
|
||||
bulge[inSeg!] = bulgeWithEndTangent(p, q, tu);
|
||||
bulge[outSeg!] = bulgeWithStartTangent(q, r, tu);
|
||||
return bulge;
|
||||
return TYPES[info(g, i)[0]] ?? null;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// [K4] Messung: Objekt-Info (`deriveSelection`), Griff-Schritte und grosse Polylinien auf einem grossen
|
||||
// Projekt (3000 Wände + 20 000 Zeichnungen, 40 Dächer) über den Store. Werte gehen nach stderr (TODO [K4]);
|
||||
// die Grenzen sind grosszügig (Container unter Last), geprüft wird vor allem das Ergebnis.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getState } from "./appStore";
|
||||
import { deriveSelection } from "./selectionInfo";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Drawing2D, Project, Roof, Wall } from "../model/types";
|
||||
|
||||
const st = () => getState();
|
||||
|
||||
function bigProject(): Project {
|
||||
const base = sampleProject.walls;
|
||||
const walls: Wall[] = Array.from({ length: 3000 }, (_, i) => ({
|
||||
...base[i % base.length],
|
||||
id: `w${i}`,
|
||||
start: { x: i, y: 0 },
|
||||
end: { x: i + 1, y: 0 },
|
||||
}));
|
||||
const level = sampleProject.drawingLevels[0].id;
|
||||
const drawings: Drawing2D[] = Array.from({ length: 20000 }, (_, i) => ({
|
||||
id: `d${i}`,
|
||||
levelId: level,
|
||||
categoryCode: "01",
|
||||
geom:
|
||||
i === 19000
|
||||
? {
|
||||
shape: "polyline",
|
||||
closed: false,
|
||||
pts: Array.from({ length: 5000 }, (_, k) => ({ x: k * 0.1, y: Math.sin(k / 50) })),
|
||||
}
|
||||
: { shape: "polyline", closed: false, pts: [{ x: i, y: 1 }, { x: i + 1, y: 2 }, { x: i + 2, y: 1 }] },
|
||||
})) as Drawing2D[];
|
||||
const roof = sampleProject.roofs![0];
|
||||
const roofs: Roof[] = Array.from({ length: 40 }, (_, i) => ({
|
||||
...roof,
|
||||
id: `r${i}`,
|
||||
outline: roof.outline.map((p) => ({ x: p.x + i * 10, y: p.y })),
|
||||
}));
|
||||
return { ...structuredClone(sampleProject), walls, drawings2d: drawings, roofs };
|
||||
}
|
||||
|
||||
/** Kleinster Mittelwert (µs) aus `rounds` Läufen à `n` Aufrufen. */
|
||||
function bench(n: number, fn: (i: number) => void, rounds = 3): number {
|
||||
let best = Infinity;
|
||||
for (let i = 0; i < Math.ceil(n / 4); i++) fn(i); // Aufwärmen (JIT, Caches)
|
||||
for (let r = 0; r < rounds; r++) {
|
||||
const t = performance.now();
|
||||
for (let i = 0; i < n; i++) fn(i);
|
||||
best = Math.min(best, ((performance.now() - t) * 1000) / n);
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
const sel = (p: Project, k: { wall?: string; drawing?: string; roof?: string }) =>
|
||||
deriveSelection(p, k.wall ? [k.wall] : [], k.drawing ?? null, null, null, null, null, null, null, k.roof ?? null);
|
||||
|
||||
describe("Messung Objekt-Info und Griffe, 3000 Wände + 20 000 Zeichnungen", () => {
|
||||
it("Objekt-Info, Griff-Schritte, Polylinien-Punkttyp", { timeout: 120000 }, () => {
|
||||
st().loadProject(bigProject());
|
||||
const p = st().project;
|
||||
const out: string[] = [];
|
||||
for (const i of [10, 1500, 2990]) {
|
||||
expect(sel(p, { wall: `w${i}` })?.kind).toBe("wall");
|
||||
out.push(`Info Wand ${i} ${bench(200, () => sel(p, { wall: `w${i}` })).toFixed(0)} µs`);
|
||||
}
|
||||
expect(sel(p, { drawing: "d10000" })?.kind).toBe("drawing2d");
|
||||
out.push(`Info Zeichnung 10000 ${bench(200, () => sel(p, { drawing: "d10000" })).toFixed(0)} µs`);
|
||||
expect(sel(p, { roof: "r20" })?.kind).toBe("roof");
|
||||
out.push(`Info Dach (40 im Wechsel) ${bench(200, (i) => sel(p, { roof: `r${i % 40}` })).toFixed(0)} µs`);
|
||||
|
||||
for (const i of [10, 1500, 2990]) {
|
||||
const us = bench(50, (k) => st().moveGripOf(null, `w${i}`, 0, { x: i + (k % 7) * 0.01, y: 0.5 }));
|
||||
out.push(`Griff Wand ${i} ${us.toFixed(0)} µs`);
|
||||
}
|
||||
expect(st().project.walls[1500].start.y).toBe(0.5);
|
||||
const big = (k: number) => st().moveGripOf("d19000", null, 2500, { x: 250 + (k % 5) * 0.01, y: 3 });
|
||||
out.push(`Griff Polylinie 5000 Punkte ${(bench(20, big) / 1000).toFixed(2)} ms`);
|
||||
out.push(`Griff Zeichnung 15000 ${bench(50, (k) => st().moveGripOf("d15000", null, 1, { x: 15001, y: 2 + (k % 5) * 0.01 })).toFixed(0)} µs`);
|
||||
|
||||
const types = ["arc", "spline", "corner"] as const;
|
||||
out.push(
|
||||
`Punkttyp Polylinie 5000 Punkte ${(bench(20, (k) => st().setPolylineVertexType("d19000", 100 + k, types[k % 3])) / 1000).toFixed(2)} ms`,
|
||||
);
|
||||
out.push(`Punkttyp kleine Polylinie ${bench(50, (k) => st().setPolylineVertexType("d12000", 1, types[k % 3])).toFixed(0)} µs`);
|
||||
st().setPolylineVertexType("d12000", 1, "arc");
|
||||
expect((st().project.drawings2d[12000].geom as { bulge?: number[] }).bulge?.length).toBe(2);
|
||||
st().setPolylineVertexType("d12000", 1, "corner");
|
||||
expect((st().project.drawings2d[12000].geom as { bulge?: number[] }).bulge).toBeUndefined();
|
||||
|
||||
process.stderr.write(`Objekt-Info/Griffe (Store): ${out.join(", ")}\n`);
|
||||
});
|
||||
});
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
setField,
|
||||
setFieldIfChanged,
|
||||
} from "../core";
|
||||
import { withVertexType, type PolylineVertexType } from "../core";
|
||||
import type { PolylineVertexType } from "../core";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import {
|
||||
addChildByCode,
|
||||
@@ -218,7 +218,7 @@ export interface ProjectSlice {
|
||||
deleteDrawingPoint: (drawingId: string, index: number) => void;
|
||||
/**
|
||||
* Punkttyp eines Polylinien-Stützpunkts setzen (Eckpunkt/Bogenpunkt/Splinepunkt),
|
||||
* s. `geometry/polylineVertexType.ts` — rechnet nur die Bulges der beiden
|
||||
* im Kern (`polyline_vertex.rs`, Griff-Änderung `vertexType`) — rechnet nur die Bulges der beiden
|
||||
* anliegenden Segmente um.
|
||||
*/
|
||||
setPolylineVertexType: (drawingId: string, index: number, type: PolylineVertexType) => void;
|
||||
@@ -1037,15 +1037,7 @@ export function createProjectSlice(
|
||||
applyGrip({ op: "insertPoint", id: drawingId, seg: segIndex, pt: gripPt(pt) }),
|
||||
|
||||
setPolylineVertexType: (drawingId, index, type) =>
|
||||
applyChange((p) =>
|
||||
patchItem(p, "drawings2d", drawingId, (d) => {
|
||||
if (d.geom.shape !== "polyline" || d.locked) return d;
|
||||
const g = d.geom;
|
||||
const bulge = withVertexType(g, index, type);
|
||||
const { bulge: _old, ...rest } = g;
|
||||
return { ...d, geom: bulge.some((b) => b !== 0) ? { ...rest, bulge } : rest };
|
||||
}),
|
||||
),
|
||||
applyGrip({ op: "vertexType", id: drawingId, index, vertexType: type }),
|
||||
|
||||
deleteDrawingPoint: (drawingId, index) => applyGrip({ op: "deletePoint", id: drawingId, index }),
|
||||
|
||||
|
||||
@@ -547,25 +547,8 @@ export function deriveSelection(
|
||||
columnId: selectedColumnId,
|
||||
roofId: selectedRoofId,
|
||||
contextObjectId: selectedContextObjectId,
|
||||
// Lage in der Leseansicht (= Reihenfolge im Dokument): erspart dem Kern die lineare Suche.
|
||||
at: {} as Record<string, number>,
|
||||
};
|
||||
const P = project as unknown as Record<string, { id: string }[] | undefined>;
|
||||
const hint = (list: string, id: string | null | undefined) => {
|
||||
if (!id) return;
|
||||
const i = (P[list] ?? []).findIndex((x) => x.id === id);
|
||||
if (i >= 0) args.at[list] = i;
|
||||
};
|
||||
hint("context", selectedContextObjectId);
|
||||
hint("drawings2d", selectedDrawingId);
|
||||
hint("extrudedSolids", selectedExtrudedSolidId);
|
||||
hint("columns", selectedColumnId);
|
||||
hint("openings", selectedOpeningId);
|
||||
hint("walls", selectedWallIds[0]);
|
||||
hint("ceilings", selectedCeilingId);
|
||||
hint("roofs", selectedRoofId);
|
||||
hint("stairs", selectedStairId);
|
||||
hint("rooms", selectedRoomId);
|
||||
// Das Element sucht der Kern über den Positions-Index des Dokuments (keine lineare Suche).
|
||||
let sel: Selection | null;
|
||||
try {
|
||||
sel = documentFor(project).queryRootMarked<Selection | null>("selectionInfo", JSON.stringify(args));
|
||||
|
||||
Reference in new issue
Block a user