[K4] S3 Split und Segment löschen im Kern (cmd_split.rs); Segment löschen ersetzt jetzt an Ort und Stelle

cutSegment lieferte ein Element mit neuer id als replace: der Kern hängte es an, das Original blieb stehen. Jetzt behält das Element id und Attribute. TS-Rechnung, Kernel-Fassaden und k2_*-Bindungen für Split/Segment löschen gelöscht. Gleichheit (einmalig, Test gelöscht): 2808 Split- und 9000 Segment-Fälle.
This commit is contained in:
Claude committed 2026-10-29 14:05:42 +00:00
1 parent 4c45331e67
commit ddff1ede18
11 files changed
+528 -513

No files matched your search

+10 -40
View File
@@ -157,7 +157,7 @@ import { usePanelHostBase } from "./state/usePanelHostBase";
import { useDockDragState } from "./state/useDockDragState";
import { useMouseSelectionHandlers } from "./state/useMouseSelectionHandlers";
import { activeGroupOps, containingGroupId, EMPTY_MEMBERSHIP } from "./state/groupActions";
import { addItems, fieldOps, opsMutation, patchItem, patchItems, removeItems, replaceItem, replaceWithMany, setFieldIfChanged } from "./core";
import { addItems, fieldOps, opsMutation, patchItem, patchItems, removeItems, setFieldIfChanged } from "./core";
import type { GroupMembership, MemberKind } from "./state/groupActions";
import { isLocked, lockMembersOps } from "./state/objectLock";
import { useProjectFileActions } from "./state/useProjectFileActions";
@@ -188,13 +188,7 @@ import {
import type { EngineHost, EngineMods } from "./commands/engine";
import type { CommandContext } from "./commands/types";
import { t, useT } from "./i18n";
import {
cutSegment,
nearestEdgeIndex,
splitDrawing,
toPolyForm,
} from "./editors/splitJoin";
import type { PolyForm } from "./editors/splitJoin";
import { cutSegmentOps, splitOps } from "./editors/splitJoin";
import {
countClosedAreas,
differenceDrawings,
@@ -1325,25 +1319,11 @@ export default function App() {
// Ergebnis; neue Elemente werden ausgewählt. Wände sind ausgenommen (no-op).
const runSplit = (ids: string[]) => {
if (ids.length === 0) return;
const idSet = new Set(ids);
const newIds: string[] = [];
let newIds: string[] = [];
applyChange((p) => {
newIds.length = 0;
const replacements = new Map<string, Drawing2D[]>();
for (const d of p.drawings2d) {
if (!idSet.has(d.id)) continue;
const others: PolyForm[] = [];
for (const o of p.drawings2d) {
if (o.id === d.id || o.levelId !== d.levelId) continue;
const f = toPolyForm(o.geom);
if (f) others.push(f);
}
const pieces = splitDrawing(d, others);
for (const piece of pieces) newIds.push(piece.id);
replacements.set(d.id, pieces);
}
// Jedes Quell-Drawing wird an derselben Stelle durch seine Teile ersetzt.
return replaceWithMany(p, "drawings2d", replacements);
const r = splitOps(p, ids);
newIds = r.selectIds;
return r.ops;
});
setSelectedDrawingIds(newIds);
setSelectedWallIds([]);
@@ -1541,24 +1521,14 @@ export default function App() {
// Alt+Klick im Grundriss = Segment löschen (Schere): PlanView meldet das
// getroffene Drawing2D + den Modellpunkt; App ermittelt daraus die nächst-
// gelegene Kante (nearestEdgeIndex) und entfernt sie. Geschlossene Form →
// gelegene Kante (Kern `cmd_split.rs`) und entfernt sie. Geschlossene Form →
// offene Polylinie; bleiben <2 Punkte übrig, wird das Element gelöscht.
const onSegmentCut = (drawingId: string, model: Vec2) => {
const src = project.drawings2d.find((d) => d.id === drawingId);
if (!src) return;
const edgeIndex = nearestEdgeIndex(src.geom, model);
if (edgeIndex === null) return;
let removed = false;
applyChange((p) => {
removed = false;
const d = p.drawings2d.find((x) => x.id === drawingId);
if (!d) return [];
const next = cutSegment(d, edgeIndex);
if (next === null) {
removed = true;
return removeItems(p, "drawings2d", [drawingId]);
}
return [replaceItem("drawings2d", next)];
const r = cutSegmentOps(p, drawingId, model);
removed = r.removed;
return r.ops;
});
if (removed) setSelectedDrawingIds([]);
};
-5
View File
@@ -58,11 +58,6 @@ export {
offsetSegment,
pointSegmentDistance,
polylineEdges,
removeSegment,
removeSegmentWithBulge,
splitAtIntersections,
splitClosedByChord,
splitPolylineAtParam,
tangentCircleCenters,
vecEqual,
} from "../geometry/kernel2d";
+30 -4
View File
@@ -1,5 +1,5 @@
// 2D-Boolean-Operationen (Union / Subtract / Intersect) für GESCHLOSSENE
// 2D-Zeichenelemente (Drawing2D). Ergänzt Split/Join (`splitJoin.ts`). Wandelt
// 2D-Zeichenelemente (Drawing2D). Ergänzt Split/Join (Kern `cmd_split.rs`/`cmd_edit.rs`). Wandelt
// Drawing2D ↔ Ring-/Polygon-Format der Polygon-Booleans des Rust-Kerns (`polygonBool`, i_overlay) und liefert
// neue Drawing2D-Listen. Stil-, Kategorie- und Level-Attribute werden geerbt
// (vom ersten bzw. Basis-Element).
@@ -21,8 +21,34 @@ type MultiPolygon = polygonClipping.MultiPolygon;
type Polygon = polygonClipping.Polygon;
type Ring = polygonClipping.Ring;
import type { Drawing2D, Drawing2DGeom, Vec2 } from "../model/types";
import { toPolyForm } from "./splitJoin";
import type { PolyForm } from "./splitJoin";
import { hasRealBulge } from "../core";
/** Polylinien-Darstellung einer geschlossenen Zeichnung (Stützpunkte). */
interface PolyForm {
pts: Vec2[];
closed: boolean;
}
/**
* Stützpunkte einer Zeichnung: Linie, Polylinie ohne Bögen, Rechteck; sonst `null` (Kreis, Bogen,
* Text …; Polylinien mit Bögen würden zu Sehnen entarten).
*/
function toPolyForm(geom: Drawing2DGeom): PolyForm | null {
switch (geom.shape) {
case "line":
return { pts: [geom.a, geom.b], closed: false };
case "polyline":
if (hasRealBulge(geom.bulge)) return null;
return { pts: geom.pts.slice(), closed: geom.closed };
case "rect":
return {
pts: [geom.min, { x: geom.max.x, y: geom.min.y }, geom.max, { x: geom.min.x, y: geom.max.y }],
closed: true,
};
default:
return null;
}
}
/** Ist die Geometrie eines Drawing2D eine GESCHLOSSENE Fläche (für Boolean)? */
export function isClosedArea(geom: Drawing2DGeom): boolean {
@@ -33,7 +59,7 @@ export function isClosedArea(geom: Drawing2DGeom): boolean {
/**
* Wandelt ein geschlossenes Drawing2D in ein Kern-`Polygon`
* (Ring-Liste). Reuse: `toPolyForm` aus splitJoin liefert die Stützpunkte. Der
* (Ring-Liste). `toPolyForm` liefert die Stützpunkte. Der
* Ring wird als `[x,y]`-Paare gebildet; der Kern schließt selbst
* (erster==letzter ist nicht erforderlich, aber unschädlich). Liefert `null`,
* wenn die Form nicht geschlossen ist oder zu wenige Punkte hat.
+55 -16
View File
@@ -3,7 +3,8 @@
* erhalten bleiben (nicht mehr stillschweigend zu Geraden entarten).
*/
import { describe, it, expect } from "vitest";
import { cutSegment, nearestEdgeIndex } from "./splitJoin";
import { cutSegmentOps, splitOps } from "./splitJoin";
import { getState } from "../state/appStore";
import type { Drawing2D, Project } from "../model/types";
import { documentFor } from "../core/document";
import { applyOps } from "../core/ops";
@@ -67,7 +68,15 @@ describe("Join — bulge-Erhalt", () => {
});
});
describe("cutSegment / nearestEdgeIndex — bulge-Erhalt", () => {
/** Segment löschen über den Kern: die geänderte Zeichnung (null = gelöscht). */
function cut(src: Drawing2D, at: { x: number; y: number }): Drawing2D | null {
const p = { ...sampleProject, drawings2d: [src] } as Project;
const next = applyOps(p, cutSegmentOps(p, src.id, at).ops).drawings2d;
expect(next.length).toBeLessThanOrEqual(1);
return next[0] ?? null;
}
describe("Segment löschen (Kern `cmd_split.rs`) — bulge-Erhalt", () => {
it("Segment-Löschen an einer GERADEN Kante lässt den Bogen der Nachbarkante unangetastet (offen)", () => {
// 4 Kanten: Bogen(0->1), gerade(1->2), gerade(2->3), gerade(3->4). Löscht Kante 1
// (das längere, punktreichere Reststück rechts wird behalten, s. removeSegmentWithBulge).
@@ -76,28 +85,58 @@ describe("cutSegment / nearestEdgeIndex — bulge-Erhalt", () => {
[{ x: -1, y: 0 }, { x: 1, y: 0 }, { x: 2, y: 0 }, { x: 3, y: 0 }, { x: 4, y: 0 }],
[1, 0, 0, 0],
);
const out = cutSegment(src, 1);
const out = cut(src, { x: 1.5, y: 0.01 });
expect(out).not.toBeNull();
if (!out || out.geom.shape !== "polyline") return;
// Rechtes (längeres) Stück bleibt: [2,0] -> [3,0] -> [4,0], keine Kante mehr mit Bogen.
expect(out.geom.pts).toEqual([{ x: 2, y: 0 }, { x: 3, y: 0 }, { x: 4, y: 0 }]);
// fromPolyForm lässt das bulge-Feld ganz weg, wenn kein echter Bogen mehr übrig ist.
// Das bulge-Feld fällt ganz weg, wenn kein echter Bogen mehr übrig ist.
expect(out.geom.bulge).toBeUndefined();
});
it("Segment-Löschen an der BOGEN-Kante selbst entfernt genau diesen Bogen", () => {
const src = poly("a", [{ x: -1, y: 0 }, { x: 1, y: 0 }, { x: 2, y: 0 }], [1, 0]);
const out = cutSegment(src, 0);
expect(out).not.toBeNull();
if (!out || out.geom.shape !== "polyline") return;
expect(out.geom.pts).toEqual([{ x: 1, y: 0 }, { x: 2, y: 0 }]);
expect(out.geom.bulge?.[0] ?? 0).toBeCloseTo(0, 6);
});
it("nearestEdgeIndex trifft die Bogen-Kante auch, wenn der Klickpunkt neben der Sehne liegt (auf dem Bogen)", () => {
// Halbkreis von (-1,0) nach (1,0), bulge=1 -> Apex bei (0,1).
// Halbkreis (-1,0)→(1,0) mit bulge 1 (Scheitel bei (0,-1)), dann gerade nach (1,2).
const src = poly("a", [{ x: -1, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 2 }], [1, 0]);
const idx = nearestEdgeIndex(src.geom, { x: 0, y: 0.95 });
expect(idx).toBe(0); // Bogen-Kante, nicht die gerade Kante 1
// Der Klickpunkt liegt am Bogen, aber näher an der geraden Kante als an der Sehne: getroffen wird
// der Bogen (Abstand gegen die Kurve gemessen).
const out = cut(src, { x: 0.7, y: -0.65 });
expect(out).not.toBeNull();
if (!out) return;
expect(out.geom).toEqual({ shape: "line", a: { x: 1, y: 0 }, b: { x: 1, y: 2 } });
});
});
describe("Segment löschen ersetzt an Ort und Stelle", () => {
it("das Element behält id und Attribute, die Liste bleibt gleich lang (Store)", () => {
// Früher erzeugte cutSegment ein Element mit NEUER id als `replace` → angehängt, Original blieb.
const d: Drawing2D = {
id: "p", type: "drawing2d", levelId: "eg", categoryCode: "20", color: "#f00", opacity: 0.5,
geom: { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 1 }], closed: false },
};
getState().loadProject({ ...sampleProject, drawings2d: [d] } as Project);
getState().applyChange((p) => cutSegmentOps(p, "p", { x: 1.9, y: 1 }).ops);
const after = getState().project.drawings2d;
expect(after.length).toBe(1);
expect(after[0]).toEqual({ ...d, geom: { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], closed: false } });
getState().undo();
expect(getState().project.drawings2d).toEqual([d]);
});
});
describe("Split (Kern `cmd_split.rs`)", () => {
it("teilt an den Schnittpunkten, Stücke an der Stelle des Originals, Auswahl = Stücke", () => {
const a: Drawing2D = { id: "a", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 10, y: 0 } } };
const b: Drawing2D = { id: "b", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: 4, y: -1 }, b: { x: 4, y: 1 } } };
const z: Drawing2D = { id: "z", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "circle", center: { x: 0, y: 0 }, r: 1 } };
const p = { ...sampleProject, drawings2d: [a, b, z] } as Project;
const { ops, selectIds } = splitOps(p, ["a", "z"]);
const next = applyOps(p, ops).drawings2d;
expect(next.map((d) => d.geom)).toEqual([
{ shape: "line", a: { x: 0, y: 0 }, b: { x: 4, y: 0 } },
{ shape: "line", a: { x: 4, y: 0 }, b: { x: 10, y: 0 } },
b.geom,
z.geom,
]);
expect(new Set(selectIds)).toEqual(new Set(["z", next[0].id, next[1].id]));
});
});
+25 -257
View File
@@ -1,269 +1,37 @@
// Editier-Operationen Split / Segment-Löschen für 2D-Zeichenelemente (Join: Kern `cmd_edit.rs`)
// (Drawing2D). Wandeln Drawing2D ↔ {pts, closed}, rufen den reinen Geometrie-
// Kernel (`../geometry/kernel2d`) und liefern neue Drawing2D-Listen. Stil-,
// Kategorie- und Level-Attribute der Quelle werden geerbt.
// Split / Segment löschen für 2D-Zeichenelemente — Fassade über den Kern ([K4] S3,
// `src-tauri/core/src/cmd_split.rs`; Join: `cmd_edit.rs`). Der Kern rechnet auf dem Dokument des
// Projekts und liefert Ops; hier nur die Anfrage und die ids für die Nachauswahl.
//
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import type { Drawing2D, Drawing2DGeom, Vec2 } from "../model/types";
import { removeSegment, removeSegmentWithBulge, splitAtIntersections, splitClosedByChord, splitPolylineAtParam, vecEqual } from "../core";
import { bulgeArcPoints, hasRealBulge } from "../core";
/** Eine Polylinien-Darstellung eines Drawing2D (für die Kernel-Funktionen). */
export interface PolyForm {
pts: Vec2[];
closed: boolean;
/** Bogen-Segmente (DXF-bulge, s. `geometry/bulge.ts`) — nur bei `toPolyFormAllowBulge`. */
bulge?: number[];
}
import type { Project, Vec2 } from "../model/types";
import type { CoreOp } from "../core";
import { documentFor } from "../core/document";
import { uniqueStamp } from "../tools/types";
/**
* Wandelt die Geometrie eines Drawing2D in eine Polylinien-Form `{pts, closed}`.
* Nur line/polyline/rect werden unterstützt (circle/arc/text → `null`).
* Split der Zeichnungen `ids` an ihren Schnittpunkten mit den übrigen Zeichnungen des Geschosses
* (ohne Schnitt an der Mitte). Die Stücke ersetzen das Original an seiner Stelle. `selectIds`: die
* Stücke und die nicht teilbaren gewählten Zeichnungen (Nachauswahl).
*/
export function toPolyForm(geom: Drawing2DGeom): PolyForm | null {
switch (geom.shape) {
case "line":
return { pts: [geom.a, geom.b], closed: false };
case "polyline":
// Bogen-Segmente (bulge) hier noch nicht unterstützt — Split/Segment-
// Löschen bauen pts komplett neu auf und würden bestehende Bögen
// stillschweigend zu Geraden entarten lassen, s. offset.ts. (Join hat
// eine eigene, bulge-erhaltende Variante, s. `toPolyFormAllowBulge`.)
if (hasRealBulge(geom.bulge)) return null;
return { pts: geom.pts.slice(), closed: geom.closed };
case "rect":
return {
pts: [
geom.min,
{ x: geom.max.x, y: geom.min.y },
geom.max,
{ x: geom.min.x, y: geom.max.y },
],
closed: true,
};
default:
return null;
export function splitOps(project: Project, ids: readonly string[]): { ops: CoreOp[]; selectIds: string[] } {
const ops = documentFor(project).cmdOps({ cmd: "split", ids, stamp: uniqueStamp() });
const removed = new Set<string>();
const added: string[] = [];
for (const op of ops) {
if (op.kind === "remove") for (const id of op.ids) removed.add(id);
if (op.kind === "add") for (const e of op.items) added.push((e as { id: string }).id);
}
const have = new Set(project.drawings2d.map((d) => d.id));
return { ops, selectIds: [...ids.filter((id) => have.has(id) && !removed.has(id)), ...added] };
}
/**
* Wie {@link toPolyForm}, aber lässt Bogen-Segmente (bulge) durch — für Segment-Löschen
* (`cutSegment`/`nearestEdgeIndex`), das den bulge an seinem Punktepaar mitträgt.
* Segment löschen (Alt+Klick): die dem Modellpunkt `at` nächste Kante der Zeichnung `id` fällt weg
* (geschlossen → offen; Bögen bleiben). Das Element behält id und Attribute; bleiben weniger als
* zwei Punkte, wird es gelöscht (`removed`).
*/
function toPolyFormAllowBulge(geom: Drawing2DGeom): PolyForm | null {
if (geom.shape === "polyline") return { pts: geom.pts.slice(), closed: geom.closed, bulge: geom.bulge };
return toPolyForm(geom);
export function cutSegmentOps(project: Project, id: string, at: Vec2): { ops: CoreOp[]; removed: boolean } {
const ops = documentFor(project).cmdOps({ cmd: "cutSegment", id, at });
return { ops, removed: ops.some((op) => op.kind === "remove") };
}
/**
* Baut aus einer Polylinien-Form die passende Drawing2D-Geometrie. Zwei Punkte +
* offen → `line`; sonst `polyline` (geschlossen oder offen). Rechtecke werden
* NICHT rekonstruiert (nach dem Schneiden sind die Teile beliebige Polygone).
*/
export function fromPolyForm(form: PolyForm): Drawing2DGeom {
const pts = form.pts;
if (pts.length === 2 && !form.closed && !hasRealBulge(form.bulge)) {
return { shape: "line", a: pts[0], b: pts[1] };
}
const geom: Drawing2DGeom = { shape: "polyline", pts, closed: form.closed };
if (hasRealBulge(form.bulge)) geom.bulge = form.bulge;
return geom;
}
let counter = 0;
/** Eindeutige Drawing2D-ID (zeitbasiert + Zähler, damit ein Split nicht kollidiert). */
function newId(prefix: string): string {
counter += 1;
return `${prefix}-${Date.now()}-${counter}`;
}
/** Übernimmt Stil-/Kategorie-/Level-Attribute der Quelle auf ein neues Drawing2D. */
function inherit(src: Drawing2D, geom: Drawing2DGeom): Drawing2D {
const out: Drawing2D = {
id: newId("d2d"),
type: "drawing2d",
levelId: src.levelId,
categoryCode: src.categoryCode,
geom,
};
if (src.lineStyleId !== undefined) out.lineStyleId = src.lineStyleId;
if (src.color !== undefined) out.color = src.color;
if (src.weightMm !== undefined) out.weightMm = src.weightMm;
// Füllung/Schraffur nur an geschlossene Ergebnisse weitergeben.
const closed =
geom.shape === "polyline" ? geom.closed : geom.shape === "rect";
if (closed) {
if (src.hatchId !== undefined) out.hatchId = src.hatchId;
if (src.fillColor !== undefined) out.fillColor = src.fillColor;
}
return out;
}
/**
* Split eines Drawing2D gegen alle ANDEREN Elemente (`others`, als PolyForm).
* • Trifft das Ziel andere Elemente, wird an den Schnittpunkten geteilt
* (geschlossen + 2 Schnitte → zwei GESCHLOSSENE Polygone via Sehne).
* • Ohne Schnitt: Fallback — an der Kanten-MITTE der „längsten" Kante teilen
* (offen → zwei Stücke; geschlossen → an einer Kantenmitte + der gegenüber-
* liegenden Kantenmitte zu zwei geschlossenen Hälften).
* Liefert ≥2 neue Drawing2D, oder `[src]` (unverändert), wenn keine Teilung
* möglich war (z. B. nicht-polyline Form). Stil/Kategorie/Level werden geerbt.
*/
export function splitDrawing(
src: Drawing2D,
others: PolyForm[],
): Drawing2D[] {
const form = toPolyForm(src.geom);
if (!form) return [src];
const otherPts = others.map((o) =>
// Geschlossene als Ring (erster==letzter) übergeben, damit der Kernel die
// Schlusskante als Kante erkennt.
o.closed && o.pts.length > 2 ? [...o.pts, o.pts[0]] : o.pts,
);
let pieces = splitAtIntersections(form.pts, form.closed, otherPts);
// Kein Schnitt-Ergebnis (eine Liste, identisch zur Quelle) → Fallback.
const noCut = pieces.length < 2;
if (noCut) {
pieces = fallbackSplit(form);
}
if (pieces.length < 2) return [src];
// Jedes Stück: geschlossen bleibt geschlossen NUR, wenn das Original
// geschlossen war UND der Schnitt zwei geschlossene Hälften erzeugte
// (Sehnen-Split / Fallback-geschlossen). Bei offenem Aufschneiden sind die
// Stücke offen.
const piecesClosed = form.closed && isClosedSplit(form, pieces);
return pieces.map((pts) =>
inherit(src, fromPolyForm({ pts, closed: piecesClosed })),
);
}
/**
* Heuristik: erzeugte der Schnitt zwei GESCHLOSSENE Hälften (Sehnen-Split)?
* Wahr, wenn das Original geschlossen war und genau zwei Stücke entstanden
* (Chord-Split) — diese sollen wieder geschlossen sein. Bei mehr Stücken
* (geschlossen an >2 Schnitten aufgetrennt) bleiben sie offen.
*/
function isClosedSplit(form: PolyForm, pieces: Vec2[][]): boolean {
return form.closed && pieces.length === 2;
}
/**
* Fallback ohne Schnitt mit anderen Elementen: an der Mitte teilen.
* • Offen: längste Kante an t=0.5 in zwei offene Stücke.
* • Geschlossen: an den Mitten zweier „gegenüberliegender" Kanten in zwei
* geschlossene Polygone (Sehne zwischen den beiden Kantenmitten).
*/
function fallbackSplit(form: PolyForm): Vec2[][] {
const n = form.pts.length;
if (n < 2) return [form.pts];
if (!form.closed) {
// Längste Kante suchen.
let best = 0;
let bestLen = -1;
for (let i = 0; i < n - 1; i++) {
const d = dist(form.pts[i], form.pts[i + 1]);
if (d > bestLen) {
bestLen = d;
best = i;
}
}
return splitPolylineAtParam(form.pts, false, best, 0.5);
}
// Geschlossen: Kante 0 und die „gegenüberliegende" Kante.
const i = 0;
const j = Math.max(1, Math.floor(n / 2)) % n;
if (i === j) return [form.pts];
// Direkt den Kernel-Chord-Split nutzen.
const res = splitClosedHalf(form.pts, i, j);
return res ?? [form.pts];
}
/** Geschlossenes Polygon an den Mitten der Kanten i und j halbieren. */
function splitClosedHalf(pts: Vec2[], i: number, j: number): Vec2[][] | null {
// Reuse: splitClosedByChord ist im Kernel; hier über splitAtIntersections-Form
// nachzubauen wäre umständlich — direkt importieren.
const res = chordSplit(pts, i, 0.5, j, 0.5);
return res;
}
function chordSplit(
pts: Vec2[],
i: number,
ti: number,
j: number,
tj: number,
): Vec2[][] | null {
const r = splitClosedByChord(pts, i, ti, j, tj);
return r ? [r[0], r[1]] : null;
}
const dist = (a: Vec2, b: Vec2): number =>
Math.hypot(a.x - b.x, a.y - b.y);
/**
* Segment-Löschen (Schere): entfernt das Segment `edgeIndex` aus einem
* Drawing2D. Geschlossene Form → offene Polylinie. Liefert das geänderte
* Drawing2D, oder `null`, wenn weniger als 2 Punkte übrig blieben (Element
* komplett löschen) bzw. die Form nicht unterstützt wird. Bogen-Segmente
* (bulge) bleiben dabei an ihrem Punktepaar erhalten (s. `removeSegmentWithBulge`).
*/
export function cutSegment(src: Drawing2D, edgeIndex: number): Drawing2D | null {
const form = toPolyFormAllowBulge(src.geom);
if (!form) return src; // nicht unterstützte Form unverändert lassen
const res = hasRealBulge(form.bulge)
? removeSegmentWithBulge(form.pts, form.bulge!, form.closed, edgeIndex)
: removeSegment(form.pts, form.closed, edgeIndex);
if (res.pts.length < 2) return null;
return inherit(src, fromPolyForm(res));
}
/**
* Liefert den Index der Kante eines Drawing2D, die dem Modellpunkt `p` am
* nächsten liegt (für Alt+Klick = Segment-Löschen). `null`, wenn die Form keine
* Kanten hat (circle/arc/text) oder zu wenige Punkte. Bei Bogen-Segmenten
* (bulge) wird der Abstand gegen die tessellierte Bogenkurve gemessen (nicht
* gegen die Sehne), der Index bleibt aber der der ORIGINAL-Kante — wichtig,
* da `cutSegment` denselben Index gegen das bulge-Array auflöst.
*/
export function nearestEdgeIndex(geom: Drawing2DGeom, p: Vec2): number | null {
const form = toPolyFormAllowBulge(geom);
if (!form || form.pts.length < 2) return null;
const n = form.pts.length;
const edgeCount = form.closed ? n : n - 1;
let best: number | null = null;
let bestD = Infinity;
for (let i = 0; i < edgeCount; i++) {
const a = form.pts[i];
const b = form.pts[(i + 1) % n];
const arcPts = hasRealBulge(form.bulge) ? bulgeArcPoints(a, b, form.bulge?.[i]) : [a, b];
for (let k = 0; k < arcPts.length - 1; k++) {
const d = segDist(p, arcPts[k], arcPts[k + 1]);
if (d < bestD) {
bestD = d;
best = i;
}
}
}
return best;
}
/** Abstand Punkt → Strecke (lokal, klein gehalten). */
function segDist(p: Vec2, a: Vec2, b: Vec2): number {
const abx = b.x - a.x;
const aby = b.y - a.y;
const l2 = abx * abx + aby * aby;
let t = l2 > 0 ? ((p.x - a.x) * abx + (p.y - a.y) * aby) / l2 : 0;
t = Math.max(0, Math.min(1, t));
const cx = a.x + abx * t;
const cy = a.y + aby * t;
return Math.hypot(p.x - cx, p.y - cy);
}
// `vecEqual` re-export für etwaige Aufrufer (Auswahl-Vergleich).
export { vecEqual };
-86
View File
@@ -45,45 +45,12 @@ function encPts(pts: Vec2[]): Float64Array {
return out;
}
/** Fehlende/`null`-Einträge → 0 (Gerade), wie im Rust-Kern. */
function encBulge(bulge: (number | undefined)[] | undefined): Float64Array {
return Float64Array.from(bulge ?? [], (b) => b ?? 0);
}
/** Liste von Punktlisten: `[n, (n_pts, xy…)…]`. */
function encPtLists(lists: Vec2[][]): Float64Array {
const out: number[] = [lists.length];
for (const l of lists) {
out.push(l.length);
for (const p of l) out.push(p.x, p.y);
}
return Float64Array.from(out);
}
function decPts(buf: Float64Array, from = 0, count = (buf.length - from) / 2): Vec2[] {
const out: Vec2[] = [];
for (let k = 0; k < count; k++) out.push({ x: buf[from + 2 * k], y: buf[from + 2 * k + 1] });
return out;
}
function decPtLists(buf: Float64Array): Vec2[][] {
const n = buf[0] ?? 0;
const out: Vec2[][] = [];
let i = 1;
for (let k = 0; k < n; k++) {
const m = buf[i++];
out.push(decPts(buf, i, m));
i += 2 * m;
}
return out;
}
/** `[n_pts, xy…, bulge…]`. */
function decPtsBulge(buf: Float64Array): { pts: Vec2[]; bulge: number[] } {
const n = buf[0] ?? 0;
return { pts: decPts(buf, 1, n), bulge: Array.from(buf.subarray(1 + 2 * n)) };
}
// ── Punkt/Strecke, Fläche ───────────────────────────────────────────────────
/** Abstand von p zur Strecke a→b. */
@@ -164,56 +131,3 @@ export function filletCorner(corner: Vec2, p1: Vec2, p2: Vec2, r: number): Fille
endAngle: f[8],
};
}
// ── Split / Segment löschen ─────────────────────────────────────────────────
/**
* Teilt eine Polylinie an P = lerp(pts[edgeIndex], pts[edgeIndex+1], t). Offen → zwei
* offene Stücke; geschlossen → eine offene, bei P aufgeschnittene Polylinie.
*/
export function splitPolylineAtParam(pts: Vec2[], closed: boolean, edgeIndex: number, t: number): Vec2[][] {
return decPtLists(core().k2_split_polyline_at_param(encPts(pts), closed, edgeIndex, t));
}
/**
* Teilt ein geschlossenes Polygon an zwei Randpunkten (Kanten i/j, Parameter ti/tj) über die
* Sehne in zwei geschlossene Polygone; null bei i==j.
*/
export function splitClosedByChord(
pts: Vec2[],
i: number,
ti: number,
j: number,
tj: number,
): [Vec2[], Vec2[]] | null {
const r = decPtLists(core().k2_split_closed_by_chord(encPts(pts), i, ti, j, tj));
return r.length === 2 ? [r[0], r[1]] : null;
}
/**
* Entfernt das Segment `edgeIndex`. Offen: innere Kante → das punktreichere Stück bleibt,
* Randkante → End-Vertex fällt weg. Geschlossen: an der Kante zur offenen Polylinie aufgetrennt.
*/
export function removeSegment(pts: Vec2[], closed: boolean, edgeIndex: number): { pts: Vec2[]; closed: boolean } {
return { pts: decPts(core().k2_remove_segment(encPts(pts), closed, edgeIndex)), closed: false };
}
/** Wie {@link removeSegment}, trägt aber das bulge-Array mit (bulge bleibt an seinem Punktepaar). */
export function removeSegmentWithBulge(
pts: Vec2[],
bulge: number[],
closed: boolean,
edgeIndex: number,
): { pts: Vec2[]; closed: boolean; bulge: number[] } {
const r = decPtsBulge(core().k2_remove_segment_with_bulge(encPts(pts), encBulge(bulge), closed, edgeIndex));
return { pts: r.pts, closed: false, bulge: r.bulge };
}
/**
* Teilt das Ziel an allen Schnittpunkten mit `others`. Geschlossen + genau zwei Schnitte →
* zwei geschlossene Polygone; offen → Stücke an den Schnittpunkten.
*/
export function splitAtIntersections(targetPts: Vec2[], closed: boolean, others: Vec2[][]): Vec2[][] {
return decPtLists(core().k2_split_at_intersections(encPts(targetPts), closed, encPtLists(others)));
}