[K4][G10] Merge: Aufräumen (tote TS-/Rust-Doppelspuren), id-Index, Commit ohne Kopie, Punkttyp im Kern; Tests unter Last stabil
CLAUDE.md: Dokument im Kern, Modulkarte nachgeführt. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
53 files changed
+1293
-1043
No files matched your search
@@ -236,7 +236,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 };
|
||||
}
|
||||
@@ -255,7 +255,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 };
|
||||
}
|
||||
@@ -338,7 +338,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;
|
||||
}
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ export { exportObj, exportStl, exportGlb, exportGltf } from "../export/exportMes
|
||||
export { exportProjectStep } from "../export/exportStep";
|
||||
export { planToSvgString } from "../export/planToSvgString";
|
||||
export { setWasmBytesProvider } from "../engine/wasmSource";
|
||||
export { initCore, coreReady } from "../engine/coreWasm";
|
||||
export { initCore } from "../engine/coreWasm";
|
||||
export { applyOps, validateProject, validateOps } from "./ops";
|
||||
export { projectWarnings } from "./ops";
|
||||
export type { CoreOp } from "./ops";
|
||||
|
||||
@@ -9,7 +9,6 @@ export {
|
||||
bulgeArc,
|
||||
bulgeArcPoints,
|
||||
bulgePolylinePoints,
|
||||
bulgeBetweenAngles,
|
||||
bulgeFromSagittaPoint,
|
||||
bulgePointAt,
|
||||
bulgeThroughPoint,
|
||||
@@ -80,7 +79,6 @@ export {
|
||||
} from "../geometry/lineSegments";
|
||||
|
||||
export {
|
||||
openingVerticalExtent,
|
||||
} from "../geometry/opening";
|
||||
export { autoExteriorDimensions } from "../geometry/autoDimensions";
|
||||
export * as polygonBool from "../geometry/polygonBool";
|
||||
@@ -95,7 +93,6 @@ export {
|
||||
type PolylineVertexType,
|
||||
canSetVertexType,
|
||||
vertexTypeOf,
|
||||
withVertexType,
|
||||
} from "../geometry/polylineVertexType";
|
||||
|
||||
export {
|
||||
@@ -238,7 +235,6 @@ export {
|
||||
meetScale,
|
||||
mmToPx,
|
||||
pointInPolygon,
|
||||
pointSegDistPx,
|
||||
printStrokeVb,
|
||||
scaleFromView,
|
||||
toScreen,
|
||||
|
||||
@@ -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). */
|
||||
|
||||
@@ -24,10 +24,6 @@ export function initCoreSync(bytes: BufferSource): void {
|
||||
ready = true;
|
||||
}
|
||||
|
||||
export function coreReady(): boolean {
|
||||
return ready;
|
||||
}
|
||||
|
||||
/** Der geladene Kern; wirft, wenn `initCore()` noch nicht gelaufen ist (Programmierfehler). */
|
||||
export function core(): CoreModule {
|
||||
if (!ready) throw new Error("Rust-Kern nicht geladen: initCore() muss vor der ersten Kern-Funktion laufen.");
|
||||
|
||||
@@ -70,37 +70,6 @@ export async function extrudeCircle(
|
||||
return JSON.parse(json) as ExtrudedMesh;
|
||||
}
|
||||
|
||||
export type BooleanOp = "union" | "difference" | "intersection";
|
||||
|
||||
export interface BooleanMeshResult {
|
||||
positions: number[];
|
||||
indices: number[];
|
||||
empty: boolean;
|
||||
}
|
||||
|
||||
/** Boolesche Operation zweier Dreiecks-Meshes (Mesh-Ebenen-CSG via csgrs,
|
||||
* truck-Integration Phase 4). Beide Meshes müssen konsistent nach außen
|
||||
* gewundene Dreiecke haben (Rechte-Hand-Regel) — sonst liefert csgrs ein
|
||||
* falsches Ergebnis, ohne das zu erkennen. */
|
||||
export async function booleanMesh(
|
||||
a: ExtrudedMesh,
|
||||
b: ExtrudedMesh,
|
||||
op: BooleanOp,
|
||||
): Promise<BooleanMeshResult> {
|
||||
const json = await guarded((m) =>
|
||||
m.boolean_mesh(
|
||||
JSON.stringify({
|
||||
a_positions: a.positions,
|
||||
a_indices: a.indices,
|
||||
b_positions: b.positions,
|
||||
b_indices: b.indices,
|
||||
op,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return JSON.parse(json) as BooleanMeshResult;
|
||||
}
|
||||
|
||||
// ── B-Rep-Körper (truck 0.6): Spezifikation → Mesh / STEP ────────────────────
|
||||
|
||||
/** Ein Loft-Schnitt: Höhe + geschlossener Ring [x0,y0,x1,y1,…]. */
|
||||
|
||||
@@ -120,21 +120,6 @@ export function arcThroughPoints(a: Vec2, through: Vec2, b: Vec2): ArcParams | n
|
||||
return toArcParams(core().arc_through_points(a.x, a.y, through.x, through.y, b.x, b.y));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulge-Wert für den Teilbogen desselben Kreises (center, r) von Winkel `aFrom` zu `aTo`, in der
|
||||
* durch `sweepSign` vorgegebenen Schwenkrichtung (+1 = CCW, −1 = CW), z. B. beim Zuschneiden/
|
||||
* Offsetten eines Bogen-Segments.
|
||||
*/
|
||||
export function bulgeBetweenAngles(
|
||||
center: Vec2,
|
||||
r: number,
|
||||
aFrom: number,
|
||||
aTo: number,
|
||||
sweepSign: 1 | -1,
|
||||
): number {
|
||||
return core().bulge_between_angles(center.x, center.y, r, aFrom, aTo, sweepSign);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kreisbogen durch zwei Endpunkte `a`→`b` mit vorgegebenem Radius `r` (Methode „Start-Ende-
|
||||
* Radius"). `near` (typischerweise der Cursor) wählt die Seite der Sehne; es entsteht immer der
|
||||
|
||||
@@ -32,44 +32,11 @@ export function normalizeOutline(pts: Vec2[]): Vec2[] | null {
|
||||
return isCCW(clean) ? clean : clean.slice().reverse();
|
||||
}
|
||||
|
||||
/** Ob ein Umriss ein gültiges (nicht entartetes) Deckenpolygon bildet. */
|
||||
export function isValidOutline(pts: Vec2[]): boolean {
|
||||
const norm = normalizeOutline(pts);
|
||||
return norm != null && ceilingArea(norm) >= MIN_CEILING_AREA;
|
||||
}
|
||||
|
||||
/** Fläche eines Deckenumrisses in m² (immer positiv). */
|
||||
export function ceilingArea(pts: Vec2[]): number {
|
||||
return Math.abs(signedArea(pts));
|
||||
}
|
||||
|
||||
/** Schwerpunkt (Zentroid) des Umriss-Polygons (für HUD/Beschriftung). */
|
||||
export function outlineCentroid(pts: Vec2[]): Vec2 {
|
||||
const a = signedArea(pts);
|
||||
if (Math.abs(a) < 1e-12) {
|
||||
// Entartet: einfacher Mittelwert der Punkte.
|
||||
let sx = 0,
|
||||
sy = 0;
|
||||
for (const p of pts) {
|
||||
sx += p.x;
|
||||
sy += p.y;
|
||||
}
|
||||
const n = pts.length || 1;
|
||||
return { x: sx / n, y: sy / n };
|
||||
}
|
||||
let cx = 0,
|
||||
cy = 0;
|
||||
for (let i = 0; i < pts.length; i++) {
|
||||
const p = pts[i];
|
||||
const q = pts[(i + 1) % pts.length];
|
||||
const cr = p.x * q.y - q.x * p.y;
|
||||
cx += (p.x + q.x) * cr;
|
||||
cy += (p.y + q.y) * cr;
|
||||
}
|
||||
const f = 1 / (6 * a);
|
||||
return { x: cx * f, y: cy * f };
|
||||
}
|
||||
|
||||
/**
|
||||
* Punkt-in-Polygon-Test (Ray-Casting) für einen geschlossenen Umriss — dient dem
|
||||
* Body-Select einer Decke im Grundriss/3D. Randpunkte gelten als innen genug.
|
||||
|
||||
@@ -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. */
|
||||
@@ -112,8 +113,8 @@ export interface VerticalExtent {
|
||||
}
|
||||
|
||||
/**
|
||||
* UK/OK von Wänden und Decken aus dem Kern (`selection_info.rs::vertical_extents`, Regeln wie
|
||||
* `wallVerticalExtent`/`ceilingVerticalExtent`): Geschoss-Bindungen und Deckentypen aus `project`, die
|
||||
* UK/OK von Wänden und Decken aus dem Kern (`selection_info.rs::vertical_extents`, Regeln
|
||||
* `model/helpers.rs::heights`): Geschoss-Bindungen und Deckentypen aus `project`, die
|
||||
* Elemente selbst als ganze Fassung (auch gerade gezogene, noch nicht übernommene — 3D-Griffe).
|
||||
*/
|
||||
export function verticalExtents(
|
||||
|
||||
+4
-34
@@ -1,7 +1,7 @@
|
||||
// Geometrie-Helfer für Öffnungen (Fenster/Türen) — reine Funktionen, die eine
|
||||
// `Opening` relativ zu ihrer Wirts-Wand in konkrete Welt-Geometrie auflösen:
|
||||
// • die Öffnungs-Lücke entlang der Wandachse (from/to in Metern),
|
||||
// • die vertikale Lage (UK/OK der Öffnung, absolut in Metern).
|
||||
// • die Öffnungs-Lücke entlang der Wandachse (from/to in Metern), die Pfosten.
|
||||
// (Die vertikale Lage rechnet der Kern: `model3d.rs`/`plan/section.rs`, UK/OK der Wand: `model/helpers.rs::heights`.)
|
||||
//
|
||||
// Da JEDE Größe aus der aktuellen Wandachse (`wall.start`/`wall.end`) abgeleitet
|
||||
// wird, folgt eine Öffnung ihrer Wand automatisch, sobald die Wand bewegt wird —
|
||||
@@ -9,9 +9,8 @@
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import type { Opening, Project, Vec2, Wall } from "../model/types";
|
||||
import { along, leftNormal, normalize, sub } from "../model/geometry";
|
||||
import { wallVerticalExtent } from "../model/wall";
|
||||
import type { Opening, Vec2, Wall } from "../model/types";
|
||||
import { along } from "../model/geometry";
|
||||
|
||||
/** Achslänge einer Wand (Meter). */
|
||||
export function wallAxisLength(wall: Wall): number {
|
||||
@@ -34,29 +33,6 @@ export function openingInterval(
|
||||
return { from, to };
|
||||
}
|
||||
|
||||
/**
|
||||
* Vertikale Lage einer Öffnung (absolute Z-Werte in Metern) relativ zur Wand-UK.
|
||||
* Türen sitzen am Boden (sillHeight 0); Fenster ab Brüstung. Die OK wird auf die
|
||||
* Wand-OK geklemmt, damit die Öffnung nie über den Wandkopf hinausragt.
|
||||
*/
|
||||
export function openingVerticalExtent(
|
||||
project: Project,
|
||||
wall: Wall,
|
||||
o: Opening,
|
||||
): { zBottom: number; zTop: number } {
|
||||
const { zBottom, zTop } = wallVerticalExtent(project, wall);
|
||||
const sill = Math.max(0, o.sillHeight);
|
||||
const oBottom = zBottom + sill;
|
||||
const oTop = Math.min(zTop, oBottom + o.height);
|
||||
return { zBottom: oBottom, zTop: oTop };
|
||||
}
|
||||
|
||||
/** Einheits-Laufrichtung (u) und linke Normale (n) der Wandachse. */
|
||||
export function wallAxisFrame(wall: Wall): { u: Vec2; n: Vec2 } {
|
||||
const u = normalize(sub(wall.end, wall.start));
|
||||
return { u, n: leftNormal(u) };
|
||||
}
|
||||
|
||||
/** Die beiden Pfosten-Punkte (auf der Achse) einer Öffnung im Grundriss. */
|
||||
export function openingJambs(
|
||||
wall: Wall,
|
||||
@@ -70,9 +46,3 @@ export function openingJambs(
|
||||
};
|
||||
}
|
||||
|
||||
/** Mittelpunkt einer Öffnung im Grundriss (Achse) — für HUD/Auswahl-Anker. */
|
||||
export function openingCenter(wall: Wall, o: Opening): Vec2 | null {
|
||||
const iv = openingInterval(wall, o);
|
||||
if (!iv) return null;
|
||||
return along(wall.start, wall.end, (iv.from + iv.to) / 2);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -19,8 +19,6 @@
|
||||
import type { Stair, Vec2 } from "../model/types";
|
||||
import { core } from "../engine/coreWasm";
|
||||
|
||||
/** SIA-nahe Schrittregel: gute Steigungshöhe ≈ 0.17 m, Auftritt ≈ 0.29 m. */
|
||||
export const IDEAL_RISER = 0.17;
|
||||
export const IDEAL_TREAD = 0.29;
|
||||
export const MIN_STEPS = 2;
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { exportIfcSpf, ifcGuid } from "../export/exportIfc";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { ceilingVerticalExtent } from "../model/wall";
|
||||
import { verticalExtents } from "../geometry/grips";
|
||||
import { polygonArea } from "../geometry/roomArea";
|
||||
import { wallMeshVolumes } from "../export/meshScene.testutil";
|
||||
import { formatIfcReport, handleIfcWorkerRequest, ifcToImportedMeshes, readIfc, type IfcProduct, type IfcWorkerRequest } from "./ifcImport";
|
||||
@@ -100,7 +100,7 @@ describe("IFC-Import: Rundreise mit dem eigenen Export", () => {
|
||||
const slabsExpected = (sampleProject.ceilings ?? [])
|
||||
.filter((c) => c.outline.length >= 3)
|
||||
.map((c) => {
|
||||
const { zBottom, zTop } = ceilingVerticalExtent(sampleProject, c);
|
||||
const { zBottom, zTop } = verticalExtents(sampleProject, [], [c]).ceilings[0];
|
||||
return Math.abs(polygonArea(c.outline)) * Math.max(zTop - zBottom, 0.001);
|
||||
})
|
||||
.sort((a, b) => a - b);
|
||||
|
||||
@@ -346,17 +346,6 @@ export function meshObjectsToImportedMeshes(objects: readonly MeshObject[], file
|
||||
});
|
||||
}
|
||||
|
||||
/** Datei-Bytes → Kontext-Meshes + Bericht. */
|
||||
export async function meshBytesToImportedMeshes(
|
||||
bytes: Uint8Array,
|
||||
fileName: string,
|
||||
read?: MeshReadOptions,
|
||||
place?: MeshToContextOptions,
|
||||
): Promise<{ meshes: ImportedMesh[]; report: MeshImportReport }> {
|
||||
const { objects, report } = await readMesh(bytes, fileName, read);
|
||||
return { meshes: meshObjectsToImportedMeshes(objects, fileName, place), report };
|
||||
}
|
||||
|
||||
/** Bericht als kurzer Text; `tr` übersetzt (Kern kennt kein i18n, die Hülle reicht `t` herein). */
|
||||
export function formatMeshReport(
|
||||
r: MeshImportReport,
|
||||
|
||||
@@ -18,7 +18,6 @@ import type {
|
||||
BuiltinPaletteBanks,
|
||||
Ceiling,
|
||||
CeilingType,
|
||||
Column,
|
||||
Component,
|
||||
DoorType,
|
||||
DrawingLevel,
|
||||
@@ -30,8 +29,6 @@ import type {
|
||||
RichTextDoc,
|
||||
Roof,
|
||||
SashDef,
|
||||
Stair,
|
||||
StairType,
|
||||
Vec2,
|
||||
Wall,
|
||||
WallType,
|
||||
@@ -204,35 +201,6 @@ export const glazingPanesOf = (wt: WindowType): 1 | 2 | 3 => {
|
||||
return wt.glazing === "dreifach" ? 3 : wt.glazing === "zweifach" ? 2 : 1;
|
||||
};
|
||||
|
||||
/** Löst den {@link StairType} einer Treppe auf, oder `undefined`. */
|
||||
export const getStairType = (project: Project, stair: Stair): StairType | undefined =>
|
||||
stair.typeId ? (project.stairTypes ?? []).find((t) => t.id === stair.typeId) : undefined;
|
||||
|
||||
/** Alle Öffnungen einer Wand (leere Liste, wenn keine oder `openings` fehlt). */
|
||||
export const openingsOfWall = (project: Project, wallId: string): Opening[] =>
|
||||
(project.openings ?? []).filter((o) => o.hostWallId === wallId);
|
||||
|
||||
/** Menschenlesbarer Standardname einer Öffnung (Fenster/Tür + Breite×Höhe). */
|
||||
export const openingLabel = (o: Opening): string =>
|
||||
`${o.kind === "door" ? "Tür" : "Fenster"} ${(o.width * 100).toFixed(0)}×${(
|
||||
o.height * 100
|
||||
).toFixed(0)}`;
|
||||
|
||||
/** Menschenlesbarer Standardname einer Stütze (Profil + Masse in cm). */
|
||||
export const columnLabel = (c: Column): string => {
|
||||
if (c.profile.kind === "round") {
|
||||
return `Stütze Ø${(c.profile.radius * 200).toFixed(0)}`;
|
||||
}
|
||||
return `Stütze ${(c.profile.width * 100).toFixed(0)}×${(c.profile.depth * 100).toFixed(0)}`;
|
||||
};
|
||||
|
||||
/** Liefert ein Bauteil-Material (Component) per ID oder wirft. */
|
||||
export const getComponent = (project: Project, id: string): Component => {
|
||||
const c = project.components.find((co) => co.id === id);
|
||||
if (!c) throw new Error(`Unbekanntes Bauteil-Material: ${id}`);
|
||||
return c;
|
||||
};
|
||||
|
||||
/** Liefert eine Schraffur (HatchStyle) per ID oder wirft. */
|
||||
export const getHatch = (project: Project, id: string): HatchStyle => {
|
||||
const h = project.hatches.find((ht) => ht.id === id);
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// Unit-Tests für die Wand-/Decken-Resolver (wallVerticalExtent /
|
||||
// ceilingVerticalExtent): reine Datenschicht, kein React/Store.
|
||||
// Unit-Tests für die Wand-/Decken-Resolver: Referenzlinie (`wallReferenceOffset`) und die UK/OK der
|
||||
// Decken über den Kern (`verticalExtents`, Regeln `model/helpers.rs::heights`).
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { ceilingVerticalExtent, wallReferenceOffset } from "./wall";
|
||||
import { wallReferenceOffset } from "./wall";
|
||||
import { verticalExtents } from "../geometry/grips";
|
||||
import type { Ceiling, Project, Wall } from "./types";
|
||||
|
||||
/** Minimalprojekt mit einem Geschoss (baseElevation 0, floorHeight 2.6) und
|
||||
@@ -68,7 +69,10 @@ function makeCeiling(overrides?: Partial<Ceiling>): Ceiling {
|
||||
};
|
||||
}
|
||||
|
||||
describe("ceilingVerticalExtent", () => {
|
||||
/** UK/OK einer Decke (Kern-Abfrage). */
|
||||
const ceilingVerticalExtent = (p: Project, c: Ceiling) => verticalExtents(p, [], [c]).ceilings[0];
|
||||
|
||||
describe("UK/OK einer Decke", () => {
|
||||
it("ohne top/bottom: OK = Geschoss-Oberkante, UK = OK − Dicke (heutiges Verhalten)", () => {
|
||||
const project = makeProject();
|
||||
const ceiling = makeCeiling();
|
||||
|
||||
+3
-92
@@ -1,12 +1,9 @@
|
||||
// Wand-Resolver: leitet aus den (optionalen) Wand-Attributen die konkreten
|
||||
// geometrischen Größen ab — Versatz der Achse über die Dicke (Referenzlinie)
|
||||
// und die vertikale Ausdehnung (UK..OK). Alle Defaults entsprechen exakt dem
|
||||
// bisherigen Verhalten, sodass bestehende Wände unverändert rendern.
|
||||
// Wand-Resolver: Versatz der Achse über die Dicke (Referenzlinie). Die vertikale Ausdehnung (UK/OK)
|
||||
// rechnet der Kern (`model/helpers.rs::heights`; TS: Abfrage `verticalExtents`, `geometry/grips.ts`).
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import type { Ceiling, Column, Project, VerticalAnchor, Wall } from "./types";
|
||||
import { ceilingThickness, getFloor } from "./types";
|
||||
import type { Wall } from "./types";
|
||||
|
||||
/**
|
||||
* Versatz der Schichtstapelung entlang der linken Normalen `+n` (leftNormal),
|
||||
@@ -38,89 +35,3 @@ export function wallReferenceOffset(
|
||||
if (ref === "right") return -half;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Löst einen VerticalAnchor zu einem absoluten Z (Meter) auf oder `null`. */
|
||||
function resolveAnchor(
|
||||
project: Project,
|
||||
anchor: VerticalAnchor | undefined,
|
||||
): number | null {
|
||||
if (!anchor) return null;
|
||||
if (anchor.mode === "custom") return anchor.z;
|
||||
// "floor": baseElevation des gebundenen Geschosses (+ optionalem Offset).
|
||||
const floor = project.drawingLevels.find((z) => z.id === anchor.floorId);
|
||||
if (!floor) return null;
|
||||
return (floor.baseElevation ?? 0) + (anchor.offset ?? 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vertikale Ausdehnung der Wand (absolute Z-Werte in Metern).
|
||||
* • zBottom: aus `wall.bottom`, sonst baseElevation des Wand-Geschosses
|
||||
* (= heutiges Verhalten).
|
||||
* • zTop: aus `wall.top`, sonst `zBottom + wall.height` (= heute).
|
||||
* Sind beide UK/OK ungesetzt, liefert dies exakt `[baseElevation, base+height]`.
|
||||
*/
|
||||
export function wallVerticalExtent(
|
||||
project: Project,
|
||||
wall: Wall,
|
||||
): { zBottom: number; zTop: number } {
|
||||
// Geschoss-baseElevation als Default-UK (heutiges Verhalten). Fehlt das
|
||||
// Geschoss, 0 als sicherer Rückfall.
|
||||
let floorBase = 0;
|
||||
try {
|
||||
floorBase = getFloor(project, wall.floorId).baseElevation ?? 0;
|
||||
} catch {
|
||||
floorBase = 0;
|
||||
}
|
||||
const zBottom = resolveAnchor(project, wall.bottom) ?? floorBase;
|
||||
const zTop = resolveAnchor(project, wall.top) ?? zBottom + wall.height;
|
||||
return { zBottom, zTop };
|
||||
}
|
||||
|
||||
/**
|
||||
* Vertikale Ausdehnung einer Decke (absolute Z-Werte in Metern).
|
||||
* • zTop: aus `ceiling.top`, sonst Oberkante des Geschosses
|
||||
* (baseElevation + floorHeight) — also bündig mit dem Wandkopf.
|
||||
* • zBottom: aus `ceiling.bottom`, sonst zTop − Deckendicke (die Decke
|
||||
* wächst nach UNTEN — heutiges Verhalten). Die `thickness` bleibt bei
|
||||
* gesetztem `bottom` rein informativ (dient nicht mehr der UK-Ableitung).
|
||||
* Fehlt das Geschoss, dient 0 als sicherer Rückfall für die Oberkante.
|
||||
*/
|
||||
export function ceilingVerticalExtent(
|
||||
project: Project,
|
||||
ceiling: Ceiling,
|
||||
): { zBottom: number; zTop: number } {
|
||||
let floorTop = 0;
|
||||
try {
|
||||
const floor = getFloor(project, ceiling.floorId);
|
||||
floorTop = (floor.baseElevation ?? 0) + (floor.floorHeight ?? 0);
|
||||
} catch {
|
||||
floorTop = 0;
|
||||
}
|
||||
const zTop = resolveAnchor(project, ceiling.top) ?? floorTop;
|
||||
const zBottom =
|
||||
resolveAnchor(project, ceiling.bottom) ??
|
||||
zTop - ceilingThickness(project, ceiling);
|
||||
return { zBottom, zTop };
|
||||
}
|
||||
|
||||
/**
|
||||
* Vertikale Ausdehnung einer Stütze (absolute Z-Werte in Metern) — dieselbe
|
||||
* Regel wie {@link wallVerticalExtent}:
|
||||
* • zBottom: aus `column.bottom`, sonst baseElevation des Geschosses.
|
||||
* • zTop: aus `column.top`, sonst `zBottom + column.height`.
|
||||
* Fehlt das Geschoss, dient 0 als sicherer Rückfall für die Unterkante.
|
||||
*/
|
||||
export function columnVerticalExtent(
|
||||
project: Project,
|
||||
column: Column,
|
||||
): { zBottom: number; zTop: number } {
|
||||
let floorBase = 0;
|
||||
try {
|
||||
floorBase = getFloor(project, column.floorId).baseElevation ?? 0;
|
||||
} catch {
|
||||
floorBase = 0;
|
||||
}
|
||||
const zBottom = resolveAnchor(project, column.bottom) ?? floorBase;
|
||||
const zTop = resolveAnchor(project, column.top) ?? zBottom + column.height;
|
||||
return { zBottom, zTop };
|
||||
}
|
||||
+1
-24
@@ -5,13 +5,12 @@
|
||||
* Querschnitt.
|
||||
* • 3D (projectToModel3d/emitColumns): eine Stütze wird zu einem Prisma-Mesh
|
||||
* (Rechteck-Box bzw. Kreis-Prisma) mit der erwarteten vertikalen Ausdehnung.
|
||||
* • Vertikale Lage (columnVerticalExtent): Geschoss-Default sowie UK/OK-Anker.
|
||||
* (Vertikale Lage: Rust-Tests `model/helpers.rs::heights`.)
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { generatePlan } from "./generatePlan";
|
||||
import { projectToModel3d } from "./toWalls3d";
|
||||
import { columnVerticalExtent } from "../model/wall";
|
||||
import { columnFootprint } from "../geometry/column";
|
||||
import type { Column, Project } from "../model/types";
|
||||
|
||||
@@ -125,28 +124,6 @@ describe("Stütze — 3D (projectToModel3d / emitColumns)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Stütze — vertikale Lage (columnVerticalExtent)", () => {
|
||||
it("nutzt Geschoss-UK + Höhe als Default", () => {
|
||||
const { zBottom, zTop } = columnVerticalExtent(
|
||||
projectWithColumn(rectColumn),
|
||||
rectColumn,
|
||||
);
|
||||
expect(zBottom).toBeCloseTo(0, 6);
|
||||
expect(zTop).toBeCloseTo(3, 6);
|
||||
});
|
||||
|
||||
it("bindet UK/OK an Anker (custom + floor)", () => {
|
||||
const anchored: Column = {
|
||||
...rectColumn,
|
||||
bottom: { mode: "custom", z: 0.5 },
|
||||
top: { mode: "floor", floorId: "og" }, // baseElevation OG = 3
|
||||
};
|
||||
const { zBottom, zTop } = columnVerticalExtent(projectWithColumn(anchored), anchored);
|
||||
expect(zBottom).toBeCloseTo(0.5, 6);
|
||||
expect(zTop).toBeCloseTo(3, 6);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Stütze — Footprint-Helfer (columnFootprint)", () => {
|
||||
it("tesselliert ein rundes Profil als 32-Eck um die Position", () => {
|
||||
const round: Column = { ...rectColumn, profile: { kind: "round", radius: 0.15 } };
|
||||
|
||||
@@ -42,9 +42,6 @@ export type DetailLevel = "grob" | "mittel" | "fein";
|
||||
/** Stroke-Farbe der Schicht-Polygone (neutrales Schwarz, geteilte Tinte mit der Schraffur). */
|
||||
export const POCHE_STROKE = "#1a1a1a";
|
||||
|
||||
/** Tinte für den Schwarz-Weiss-Modus: einheitliches Dunkel für alle Striche. */
|
||||
export const MONO_INK = "#111111";
|
||||
|
||||
// ── Linienstärken in PAPIER-Millimeter (vgl. docs/design/plans-output.md §3.2) ──
|
||||
// Alle Stricharten sind in mm Papier definiert; die PlanView rechnet sie über
|
||||
// dpi = 96 in konstante Bildschirm-Pixel um (non-scaling-stroke), damit Linien
|
||||
@@ -58,7 +55,6 @@ export const LAYER_LINE_MM = 0.02;
|
||||
// seit [K3d] im Kern (`src-tauri/core/src/plan/style.rs`).
|
||||
/** Default-Umrandungs-Strichstärke (mm), falls die Kategorie keine lw trägt
|
||||
(Grundeinstellung für „normale Elemente"). */
|
||||
export const WALL_FALLBACK_MM = 0.18;
|
||||
|
||||
/**
|
||||
* Aufgelöste Schraffur eines Polygons — alle Werte stammen aus einer
|
||||
|
||||
@@ -144,24 +144,6 @@ export function buildHatchRuns(poly: Vec2[], hatch: HatchRender): HatchRun[] {
|
||||
return toRuns(core().hatch_runs_flat(flat(poly), encodeHatch(hatch)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Streut kurze Striche deterministisch und MODELLRAUM-STABIL über ein Polygon (eine Zelle des
|
||||
* absoluten Gitters je Strich, Lage/Winkel/Länge aus `hash(ix, iy, seed)`), aufs Polygon geclippt.
|
||||
*/
|
||||
export function scatterStrokes(
|
||||
poly: Vec2[],
|
||||
cell: number,
|
||||
baseAngleRad: number,
|
||||
seed: number,
|
||||
strokeLen: number,
|
||||
lenMin?: number,
|
||||
lenMax?: number,
|
||||
): HatchRun[] {
|
||||
return toRuns(
|
||||
core().scatter_strokes_flat(flat(poly), cell, baseAngleRad, seed, strokeLen, lenMin ?? NaN, lenMax ?? NaN),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Random-Vektor-Schraffur eines Polygons (Kies/Splitt): Dichte und Strichlänge an die Kachel
|
||||
* (8·scale px) gekoppelt, Seed nur aus Muster-Parametern + `hatch.seed`.
|
||||
|
||||
@@ -16,30 +16,6 @@
|
||||
/** RGBA-Farbe, Komponenten in [0,1]. */
|
||||
export type Rgba = [number, number, number, number];
|
||||
|
||||
/** Shader-Programm mit kompiliertem Programm + Attribut-/Uniform-Orten. */
|
||||
export interface ShaderProgram {
|
||||
program: WebGLProgram;
|
||||
attribs: {
|
||||
position?: GLint;
|
||||
/** Bildschirm-Raum-Miter-Bisektor (Einheits-Versatzrichtung) für Linien. */
|
||||
normal?: GLint;
|
||||
/** Seite der Linie: +1 oder -1. */
|
||||
side?: GLint;
|
||||
/** Miter-Längenfaktor 1/cos(θ/2) (1 = gerade). */
|
||||
miter?: GLint;
|
||||
};
|
||||
uniforms: {
|
||||
viewProj?: WebGLUniformLocation | null;
|
||||
color?: WebGLUniformLocation | null;
|
||||
/** Basis-Strichbreite in Geräte-Pixeln (bei strokeScale=1). */
|
||||
strokePx?: WebGLUniformLocation | null;
|
||||
/** Zoom-Skalierung der Strichbreite (>1 = reingezoomt → dicker, Papier). */
|
||||
strokeScale?: WebGLUniformLocation | null;
|
||||
/** Zeichenpuffer-Größe in Geräte-Pixeln [w,h] (px→Clip-Umrechnung). */
|
||||
viewportPx?: WebGLUniformLocation | null;
|
||||
};
|
||||
}
|
||||
|
||||
/** Ein Zeichen-Batch: zusammenhängender Index-Bereich mit einer Farbe. */
|
||||
export interface FillBatch {
|
||||
startIndex: number;
|
||||
|
||||
@@ -207,21 +207,6 @@ export function pointInPolygon(pt: Vec2, poly: Vec2[]): boolean {
|
||||
return inside;
|
||||
}
|
||||
|
||||
/** Abstand Punkt→Strecke (alle in denselben Koordinaten, hier Client-Pixel). */
|
||||
export function pointSegDistPx(
|
||||
p: { x: number; y: number },
|
||||
a: { x: number; y: number },
|
||||
b: { x: number; y: number },
|
||||
): number {
|
||||
const dx = b.x - a.x;
|
||||
const dy = b.y - a.y;
|
||||
const len2 = dx * dx + dy * dy;
|
||||
if (len2 < 1e-9) return Math.hypot(p.x - a.x, p.y - a.y);
|
||||
let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2;
|
||||
t = Math.max(0, Math.min(1, t));
|
||||
return Math.hypot(p.x - (a.x + dx * t), p.y - (a.y + dy * t));
|
||||
}
|
||||
|
||||
/** Achsenparalleles Rechteck in Modell-Metern (Auswahl-Marquee). */
|
||||
export interface ModelRect {
|
||||
minX: number;
|
||||
|
||||
@@ -243,10 +243,6 @@ export interface RModel3d {
|
||||
|
||||
/** Warmer, neutraler Wand-Grundton (wie render3d default). */
|
||||
export const WALL_RGB: RRgb = [0.82, 0.8, 0.76];
|
||||
/** Etwas hellerer, kühlerer Ton für Deckenplatten (heben sich von Wänden ab). */
|
||||
export const SLAB_RGB: RRgb = [0.86, 0.86, 0.88];
|
||||
/** Fallback-Farbe für 2D-Zeichnungen ohne color/lineStyle/Kategorie (wie drawing2DColor in Viewport3D.tsx, "#888888"). */
|
||||
export const DRAWING_LINE_FALLBACK_RGB: RRgb = [0x88 / 255, 0x88 / 255, 0x88 / 255];
|
||||
|
||||
/** Ignoriere entartete vertikale Ausschnitte (Rundungsrauschen). */
|
||||
export const EPS = 1e-4;
|
||||
|
||||
@@ -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;
|
||||
@@ -1055,15 +1055,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