[193] Netzpunkte: aktiver Punkt per Griff-Klick, Höhe setzen und Löschen (Neuvernetzen) im Kontextmenü, Griffe im Ausschnitt grosser Netze, Zuschnitt auf Polygon

Kern: mesh_point_delete (Ohr-Triangulation des Lochs). Hinweistext für offene Höhenlinien (Minimum 2) korrigiert.
Nicht in der Tauri-App getestet.

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-11-12 05:54:24 +00:00
1 parent c18fdae4e8
commit 3016f7b42b
21 files changed
+649 -12

No files matched your search

+1 -1
View File
@@ -85,7 +85,7 @@ Wer zu einer ID mehr wissen will (Entscheide, Tests, Bilder), sucht dort nach `*
gedämpft (render3d hat nur `set_ghost` für die Hülle); natives Mac-3D-Fenster bekommt nur den Ebenen-Baum, nicht
den Darstellungsmodus; Datei-Exporte (OBJ/glTF/IFC/STEP) bleiben vollständig; kein e2e (3D-Pick headless unzuverlässig);
nicht in der Tauri-App/auf dem Mac geprüft. · M
- ◐ **[193]** Anwählen/Bearbeiten von Gelände & Co. (12.11., Maintainer, PRIO; Stand 11.11.): **erledigt** — Cmd+A nimmt Gelände, Höhenlinien, Baugrube, Netze, Bilder mit (sichtbare, nicht gesperrte Klasse; reine Funktion `state/selectAll.ts`) und die Schattenfläche der Sonnenstudie (`site: sunStudy`); Entf löscht sie in einem Undo-Schritt (Schatten: blendet `sunStudy.show` aus). Die „nicht lösch-/anwählbare Schraffur" war der Schatten der Sonnenstudie (abgeleitet aus den Geschossen, die Cmd+A nicht erfasst, Loch = Treppenöffnung); er war schon anwählbar ([137]), aber Entf tat nichts. Verschieben/Kopieren/Drehen/Spiegeln für Kontext-Elemente (Kern `cmd_transform.rs`, `contextIds`; Baugrube, Höhenlinien, Netze, Bild); Objekt-Info: Höhenversatz für Gelände/Netz/Höhenlinien/Baugrube und Höhe je Höhenlinie (`state/contextHeight.ts`, TS-Hilfe, später in den Kern). Baugrube war im Grundriss schon anwählbar (Kern-Pick) und hat Eckgriffe (`useGripEditing`); e2e `selectAllContext.spec.ts`. **Update 11.11. (Rest):** Höhen-Helfer nach Rust (`cmd_context.rs`: `contextOffset`/`contourZ`, TS-Fassung `contextHeight.ts` gelöscht; Store `offsetContextHeight`/`setContourHeight`); Maus-Ziehen im Plan für gewählte Kontext-Elemente (Baugrube, Höhenlinien, Netze, Bild: Vorschau und Ops aus dem Kern-Transform, Fang auf den ersten Punkt, ein Undo-Schritt, `moveContextBy`); Höhenlinien-Punkte als Griffe (`contourGrip`/`contourInsert` in `grips.rs`, Einfüge-Rauten wie [26], ein Undo-Schritt je Zug; ab 600 Punkten keine Griffe, ab 100 keine Rauten); Entf und Cmd+A auf den Ansichts-Schlagschatten (`viewShadows`) blenden `shadows` der Ansicht aus. e2e `contextDrag.spec.ts`. **Update 12.11. (Rest):** Höhenlinien-Punkt löschen im Rechtsklick-Menü („Ecke löschen", gleiche Mechanik wie [26]: `ringDelete`/`ringTidy` mit `kind: "contours"`, Kern `grips.rs::contour_ring_edit`, Minimum offen 2 / geschlossen 3); eingefügte oder gezogene Punkte, die auf einem Nachbarn oder der Nachbargeraden landen, entfallen beim Setzen im selben Undo-Schritt. Gelände-Netz (`terrainMesh`/`importedMesh`): Netzpunkte als Griffe im Grundriss (`meshGrip`, bis 600 Punkte, grössere Netze ohne Griffe), Höhe je Netzpunkt in der Objekt-Info (Nummer + Höhe, Befehl `meshPointZ`), Zuschneiden auf die Parzelle (Befehl `meshCrop`, Schwerpunkt-Test, Punkte und `vertexColors` werden bereinigt; Knopf in der Objekt-Info). **Offen:** Netzpunkt-Höhe direkt am Griff wählen (statt Nummer in der Objekt-Info); Zuschneiden auf frei gezeichnetes Rechteck/Polygon (Kern kann Polygon, UI nur Parzelle); Griffe nur im Ausschnitt für grosse Netze; Aufräumen/Löschen einzelner Netzpunkte (Dreiecke neu vernetzen). Nicht in der Tauri-App getestet. · M
- ◐ **[193]** Anwählen/Bearbeiten von Gelände & Co. (12.11., Maintainer, PRIO; Stand 11.11.): **erledigt** — Cmd+A nimmt Gelände, Höhenlinien, Baugrube, Netze, Bilder mit (sichtbare, nicht gesperrte Klasse; reine Funktion `state/selectAll.ts`) und die Schattenfläche der Sonnenstudie (`site: sunStudy`); Entf löscht sie in einem Undo-Schritt (Schatten: blendet `sunStudy.show` aus). Die „nicht lösch-/anwählbare Schraffur" war der Schatten der Sonnenstudie (abgeleitet aus den Geschossen, die Cmd+A nicht erfasst, Loch = Treppenöffnung); er war schon anwählbar ([137]), aber Entf tat nichts. Verschieben/Kopieren/Drehen/Spiegeln für Kontext-Elemente (Kern `cmd_transform.rs`, `contextIds`; Baugrube, Höhenlinien, Netze, Bild); Objekt-Info: Höhenversatz für Gelände/Netz/Höhenlinien/Baugrube und Höhe je Höhenlinie (`state/contextHeight.ts`, TS-Hilfe, später in den Kern). Baugrube war im Grundriss schon anwählbar (Kern-Pick) und hat Eckgriffe (`useGripEditing`); e2e `selectAllContext.spec.ts`. **Update 11.11. (Rest):** Höhen-Helfer nach Rust (`cmd_context.rs`: `contextOffset`/`contourZ`, TS-Fassung `contextHeight.ts` gelöscht; Store `offsetContextHeight`/`setContourHeight`); Maus-Ziehen im Plan für gewählte Kontext-Elemente (Baugrube, Höhenlinien, Netze, Bild: Vorschau und Ops aus dem Kern-Transform, Fang auf den ersten Punkt, ein Undo-Schritt, `moveContextBy`); Höhenlinien-Punkte als Griffe (`contourGrip`/`contourInsert` in `grips.rs`, Einfüge-Rauten wie [26], ein Undo-Schritt je Zug; ab 600 Punkten keine Griffe, ab 100 keine Rauten); Entf und Cmd+A auf den Ansichts-Schlagschatten (`viewShadows`) blenden `shadows` der Ansicht aus. e2e `contextDrag.spec.ts`. **Update 12.11. (Rest):** Höhenlinien-Punkt löschen im Rechtsklick-Menü („Ecke löschen", gleiche Mechanik wie [26]: `ringDelete`/`ringTidy` mit `kind: "contours"`, Kern `grips.rs::contour_ring_edit`, Minimum offen 2 / geschlossen 3); eingefügte oder gezogene Punkte, die auf einem Nachbarn oder der Nachbargeraden landen, entfallen beim Setzen im selben Undo-Schritt. Gelände-Netz (`terrainMesh`/`importedMesh`): Netzpunkte als Griffe im Grundriss (`meshGrip`, bis 600 Punkte, grössere Netze ohne Griffe), Höhe je Netzpunkt in der Objekt-Info (Nummer + Höhe, Befehl `meshPointZ`), Zuschneiden auf die Parzelle (Befehl `meshCrop`, Schwerpunkt-Test, Punkte und `vertexColors` werden bereinigt; Knopf in der Objekt-Info). **Update 12.11. (Netz-Reste):** Klick auf einen Netzpunkt-Griff macht ihn zum aktiven Punkt (`activeMeshPoint`; die Objekt-Info füllt Nummer und Höhe vor), Rechtsklick auf den Griff: „Höhe setzen …" (Overlay-Eingabe, `meshPointZ`) und „Netzpunkt löschen" (Kern `cmd_context.rs::mesh_point_delete`, Befehl `meshPointDelete`: Dreiecke um den Punkt entfallen, das Loch wird per Ohr-Triangulation neu vernetzt; am Netzrand schliesst die Sehne, entartete Dreiecke entfallen; auch als Knopf in der Objekt-Info); grosse Netze (>600 Punkte) bekommen Griffe für die Punkte im sichtbaren Ausschnitt (+50 % Rand, höchstens 600, der Mitte nächste; `geometry/meshPick.ts`, Ausschnitt-Brücke `state/planViewport.ts` aus `PlanView`, 150 ms verzögert); eigener Hinweis „Mindestens zwei Punkte bleiben" für offene Höhenlinien; Befehl `meshcrop` („Netz zuschneiden": Polygon oder zwei Ecken = Rechteck, Knopf „Auf Polygon zuschneiden …" in der Objekt-Info). **Offen:** Löschen mehrerer Netzpunkte auf einmal; Netz-Ausdünnen/Aufräumen. Nicht in der Tauri-App getestet. · M
- ◐ **[198]** T-Stoss: gleiche Schichten verschmelzen (12.11.). Ursache: jede Wand zeichnete ihre Umriss-/Fugenlinie einzeln, am T-Stoss blieb ein Stück Wandumriss der Durchgangswand unter dem Innenputz des Abzweigs (Putz an Putz). Jetzt streicht `plan/seams.rs` nach dem Zeichnen alle Linien/Polygonkanten, die zwei Flächen gleichen Stils (Füllung + Schraffur ohne Ursprung) VERSCHIEDENER Bauteile trennen (Probe beidseits, Linie muss auf dem Rand beider Flächen liegen); Teilstücke werden zu Linien `wall-outline`/`section-joint`. Grundriss (`walls.rs`, Bänder + schwarze Sammelfläche ab 1:100), Schnitt (`section/primitives.rs`, feine Fugen; schwere Schnittkante unberührt) — Bildschirm, Druck, SVG gleich (gleiche Primitive). Materialwechsel und Fugen eigener Schichten einer Wand bleiben. Tests `plan/wall_merge_tests.rs` (T, Ecke, Kreuzung, Gegenprobe, Materialwechsel), `section/tests.rs`; Goldens nachgeführt. Offen: Flächen werden nicht per Boolean vereinigt (Schraffur-Phase je Wand; verschieden orientierte Schraffur gilt als anderer Stil, Linie bleibt); durchlaufende, nicht verbundene Wand durch Wand (Überlappung) unberührt; Ansicht nicht angesehen; nicht in der Tauri-App/auf dem Mac. · M
- ◐ **[195b]** Objekteinstellungen als ECHTES Nebenfenster (Wunsch Maintainer, 12.11.). **Stand 12.11.:** Unter Tauri öffnet T (bzw. Menü) das native Fenster `object-settings` (`native/objectSettingsWindow.ts`, Fensterseite `ObjectSettingsWindowApp.tsx`, Protokoll `objectSettingsSync.ts`); Browser/Electron behalten das schwebende Panel. Architektur (schlankste ohne Doppelspur): das Fenster lädt denselben Store als SPIEGEL (Projekt-Leseansicht als Feld-Differenz `projectDelta` + Laden ins eigene Kern-Dokument, Auswahl, aktive Ebene, Wert-Felder des Panel-Hosts, Fokus-Abschnitt von T) und rendert unverändert `ObjectSettingsPanel`; Store-Änderungen dort rechnen ihre Ops auf dem Spiegel und gehen über `state/changeSink.ts` ans Hauptfenster (`applyChange`, Undo je Änderung, `coalesceKey` bleibt), Host-Handler per Proxy (`remoteHost`) ebenso; Cmd+Z/Shift+Cmd+Z im Fenster wirken auf den Verlauf des Hauptfensters, Meldungen erscheinen dort. Auswahlwechsel und Undo im Hauptfenster kommen als Sync (30 ms gebündelt, nur bei offenem Fenster, ohne React-Abo in `App`). Mehrfachwerte: Schraffur (Attribute) und Wandtyp/Dicke („gemischt“), Wandtyp gilt für alle gewählten Wände (ein Schritt). **Stand 12.11. (2):** „gemischt“ auch für Decke (Typ/Dicke/UK/OK), Dach (Typ/Neigung), Öffnung (Typ/Breite/Höhe/Brüstung) und Wand-UK/OK (`mixedValues.ts`, Marke `MixedMark`); die Setter dafür (`elementAttributesHost`, `patchAll`) ändern alle gewählten Elemente gleicher Art in EINEM Undo-Schritt (Dicken per `groupChanges`; Dach nur Typ/Neigung), ein nicht angefasstes gemischtes Feld bleibt unverändert; `deriveSelection` führt bei mehreren Decken/Öffnungen/Dächern mit dem ersten Element (vorher: keine Info, also kein Abschnitt). `OpeningEditorDialog` ist weg: der Editor ist der Abschnitt „Fenster-/Türeditor“ im Bereich „Objekt“ (`panels/objectInfo/OpeningEditor.tsx`, ⚙ klappt ihn auf; Host-Handler `onPatchWindowType/DoorType/onSaveOpeningStyle`; „Als Stil speichern“ mit Eingabezeile statt `window.prompt`); `setOpeningEditorId`/Dialog-State entfernt. **12.11. Ops-Strom:** das Hauptfenster schickt die vom Kern-Dokument angenommenen Ops (Commit/Griff/Befehl/Import/Undo/Redo, `ProjectDocument.onChange`) mit laufender Nummer `seq`; das Fenster führt sie ohne Verlauf nach (`applyRemote` = `doc_apply` + `applyOps`, kein Rust nötig). Rückfall Feld-Differenz + Vollabgleich bei Laden/Neu, grossem Verlaufsschritt ohne Ops; Lücke in `seq` oder abgelehnte Ops → Fenster fordert den ganzen Stand an. Messung Grossgebäude (1832 Wände, Linux-Container): Sync einer Wandänderung 0.4 ms statt 56 ms. Tests `native/objectSettingsSync.test.ts`, `objectSettingsWindow.render.test.ts`, `state/mixedValues.test.ts`, `panelHost/elementAttributesHost.test.ts`. **Stand 12.11. (3):** Mehrfachauswahl setzt jetzt auch Referenzlinie/Fugen-Versatz/Terminierung/Dachanschluss/Aussen+tragend (Wand, Decke), alle Öffnungs-Felder (nur Öffnungen GLEICHER Art Fenster/Tür; Position und Dach-/Deckenfenster-Lage bewusst nur das erste), den Fenster-/Türeditor (`onPatchOpening`, Typ-Zuweisung; ein Undo-Schritt), Treppe, Raum (SIA, Nutzung, Oberflächen; der Name bleibt je Raum eigen, Feld gesperrt), Stütze und Körper (`patchAll`/`mapAll`, `targetIds` im `elementAttributesHost`); `deriveSelection` führt auch bei mehreren Treppen/Räumen/Körpern/Stützen mit dem ersten Element; „gemischt“ für Referenzlinie, Treppe (Typ/Form/Breite/Stufen/Steighöhe), Öffnungs-Anschlag/Aufschlag/Richtung/Flügel, Raum-SIA, Höhe von Stütze/Körper. Dach-Kanten, Gauben und Innenhöfe sind dachspezifisch: nur bei EINEM Dach angeboten. Tests `native/objectSettingsSync.test.ts`, `objectSettingsWindow.render.test.ts`, `state/mixedValues.test.ts`, `panelHost/elementAttributesHost.test.ts`, `objectInfo/OpeningEditor.render.test.ts`. **Offen:** NICHT auf macOS gebaut/getestet (nur vitest/tsc im Linux-Container; Capability `object-settings` ergänzt, kein Rust); kein Messwert (Live-Mass) im Fenster; Gelände/Baugrube haben keinen Setter im Objekt-Info (nichts umgestellt). **Stand 12.11. (4):** Dach: bei Mehrfachauswahl gelten ALLE Felder für alle gewählten Dächer (Form, Firstrichtung, Dicke, Traufhöhe, Überstände, Mansarde, Halbwalm, Attika; ein Undo-Schritt je Änderung) ausser den dachspezifischen Umriss/Breite/Tiefe, Kanten, Gauben, Höfe; „gemischt“ für alle diese Felder (`selectionRoofValues`). Decke geprüft: Aussen/tragend und Randlage wirken schon auf alle, Öffnungen (Aussparungen) sind je Decke eigen und bleiben beim ersten. · L
- ◐ **[194]** Texte exakt synchron beim Zoomen (12.11., Maintainer Mac: Texte immer leicht verzögert; Nachfolger [145]).
+135 -1
View File
@@ -111,10 +111,111 @@ pub fn mesh_crop(e: &Value, poly: &[f64]) -> Option<Value> {
Some(out)
}
/// Doppelte Fläche des Dreiecks (x,y), positiv = gegen den Uhrzeigersinn.
fn area2(a: (f64, f64), b: (f64, f64), c: (f64, f64)) -> f64 {
(b.0 - a.0) * (c.1 - a.1) - (b.1 - a.1) * (c.0 - a.0)
}
/// Ohr-Triangulation eines Polygons (Punktnummern `poly` in Umlaufrichtung, Drehsinn `sign` = ±1 wie die Netz-Dreiecke).
/// Findet sich kein Ohr (entartet), wird der Rest als Fächer vom ersten Punkt aus gefüllt.
fn ear_clip(pts: &[(f64, f64)], poly: &[usize], sign: f64) -> Vec<[usize; 3]> {
let mut rest: Vec<usize> = poly.to_vec();
let mut out = Vec::new();
while rest.len() > 3 {
let n = rest.len();
let ear = (0..n).find(|&k| {
let (a, b, c) = (rest[(k + n - 1) % n], rest[k], rest[(k + 1) % n]);
if area2(pts[a], pts[b], pts[c]) * sign <= 1e-12 {
return false;
}
!rest.iter().any(|&q| {
q != a && q != b && q != c && {
let (d1, d2, d3) = (area2(pts[a], pts[b], pts[q]) * sign, area2(pts[b], pts[c], pts[q]) * sign, area2(pts[c], pts[a], pts[q]) * sign);
d1 >= 0.0 && d2 >= 0.0 && d3 >= 0.0
}
})
});
match ear {
Some(k) => {
out.push([rest[(k + n - 1) % n], rest[k], rest[(k + 1) % n]]);
rest.remove(k);
}
None => {
for w in 1..n - 1 {
out.push([rest[0], rest[w], rest[w + 1]]);
}
return out;
}
}
}
if rest.len() == 3 && area2(pts[rest[0]], pts[rest[1]], pts[rest[2]]).abs() > 1e-12 {
out.push([rest[0], rest[1], rest[2]]);
}
out
}
/// Netzpunkt `index` löschen: seine Dreiecke fallen weg, das entstehende Loch (Rand der Dreiecke um den Punkt) wird
/// per Ohr-Triangulation neu vernetzt (am Netzrand schliesst die Sehne zwischen den beiden Randpunkten). Ist der Rand
/// um den Punkt nicht eine einfache Kette/Schleife (nicht-mannigfaltig), bleibt das Loch offen. Punkt, `vertexColors`
/// und Indizes werden nachgeführt; ein Netz mit weniger als drei Punkten danach = keine Änderung.
pub fn mesh_point_delete(e: &Value, index: usize) -> Option<Value> {
if !matches!(kind(e), "terrainMesh" | "importedMesh") {
return None;
}
let pos: Vec<f64> = arr(field(e, "positions")).iter().map(|v| num_of(Some(v))).collect();
let idx: Vec<usize> = arr(field(e, "indices")).iter().map(|v| num_of(Some(v))).map(|f| if f >= 0.0 && f.fract() == 0.0 { f as usize } else { usize::MAX }).collect();
let nv = pos.len() / 3;
if index >= nv || nv <= 3 || idx.len() % 3 != 0 || idx.iter().any(|&i| i >= nv) || pos.iter().any(|v| !v.is_finite()) {
return None;
}
let xy: Vec<(f64, f64)> = (0..nv).map(|i| (pos[3 * i], pos[3 * i + 1])).collect();
let mut tris: Vec<[usize; 3]> = Vec::new();
let mut rim: Vec<(usize, usize)> = Vec::new(); // gerichtete Randkanten a->b der Dreiecke (v, a, b)
let mut sign_sum = 0.0;
for t in idx.chunks_exact(3) {
let Some(k) = t.iter().position(|&i| i == index) else {
tris.push([t[0], t[1], t[2]]);
continue;
};
let (a, b) = (t[(k + 1) % 3], t[(k + 2) % 3]);
sign_sum += area2(xy[index], xy[a], xy[b]);
rim.push((a, b));
}
if !rim.is_empty() && sign_sum != 0.0 {
// Kanten zu einer Kette (offen, Rand) bzw. Schleife (innen) verbinden; jeder Punkt darf nur einmal beginnen/enden.
let mut next = std::collections::HashMap::new();
let mut has_in = std::collections::HashSet::new();
let mut simple = true;
for &(a, b) in &rim {
simple &= next.insert(a, b).is_none() && has_in.insert(b);
}
let start = rim.iter().map(|r| r.0).find(|a| !has_in.contains(a)).unwrap_or(rim[0].0);
let mut poly = vec![start];
while let Some(&n) = next.get(poly.last().unwrap()) {
if n == start || poly.len() > rim.len() {
break;
}
poly.push(n);
}
if simple && poly.len() == rim.len() {
tris.extend(ear_clip(&xy, &poly, sign_sum.signum()));
}
}
let remap = |i: usize| if i > index { i - 1 } else { i };
let new_idx: Vec<Value> = tris.iter().flatten().map(|&i| js_num(remap(i) as f64)).collect();
let drop3 = |src: &[Value]| -> Vec<Value> { src.iter().enumerate().filter(|(i, _)| i / 3 != index).map(|(_, v)| v.clone()).collect() };
let mut out = with(&with(e, "positions", Value::Array(drop3(arr(field(e, "positions"))))), "indices", Value::Array(new_idx));
if let Some(vc) = field(e, "vertexColors").and_then(Value::as_array).filter(|c| c.len() == nv * 3) {
out = with(&out, "vertexColors", Value::Array(drop3(vc)));
}
Some(out)
}
/// Ops der Höhen-/Netz-Befehle (`None` = fremder Befehl).
pub fn ops(root: &Map<String, Value>, v: &Value) -> Option<Vec<Op>> {
let cmd = v.get("cmd").and_then(Value::as_str)?;
if !matches!(cmd, "contextOffset" | "contourZ" | "meshPointZ" | "meshCrop") {
if !matches!(cmd, "contextOffset" | "contourZ" | "meshPointZ" | "meshCrop" | "meshPointDelete") {
return None;
}
let num = |k: &str| v.get(k).and_then(Value::as_f64).unwrap_or(f64::NAN);
@@ -126,6 +227,7 @@ pub fn ops(root: &Map<String, Value>, v: &Value) -> Option<Vec<Op>> {
"contextOffset" => height_offset(e, num("dz")),
"contourZ" => contour_height(e, index()?, num("z")),
"meshPointZ" => mesh_point_height(e, index()?, num("z")),
"meshPointDelete" => mesh_point_delete(e, index()?),
_ => {
let poly: Vec<f64> = v.get("poly").and_then(Value::as_array)?.iter().map(|x| x.as_f64().unwrap_or(f64::NAN)).collect();
mesh_crop(e, &poly)
@@ -198,6 +300,38 @@ mod tests {
assert!(cut(json!([0, 0, 1])).is_empty());
}
#[test]
fn netzpunkt_loeschen_vernetzt_das_loch() {
let mut r = root();
// Innenpunkt 4 (Mitte) eines Quadrats 0..2 mit vier Dreiecken -> Loch = Quadrat, zwei Dreiecke, Punkt weg.
r.insert("context".into(), json!([{"id":"q","type":"terrainMesh",
"positions":[0,0,0, 2,0,0, 2,2,0, 0,2,0, 1,1,9],
"indices":[0,1,4, 1,2,4, 2,3,4, 3,0,4], "vertexColors":[0,0,0, 1,1,1, 2,2,2, 3,3,3, 4,4,4]}]));
let del = |r: &Map<String, Value>, i: usize| ops(r, &json!({"cmd":"meshPointDelete","id":"q","index":i})).unwrap().iter().map(|o| o.to_json()).collect::<Vec<_>>();
let o = del(&r, 4);
let e = &o[0]["entity"];
assert_eq!(e["positions"].as_array().unwrap().len(), 12);
assert_eq!(e["vertexColors"].as_array().unwrap().len(), 12);
let ix: Vec<f64> = e["indices"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
assert_eq!(ix.len(), 6);
// Fläche bleibt 4, Drehsinn (gegen den Uhrzeigersinn) bleibt.
let p: Vec<f64> = e["positions"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
let a2: f64 = ix.chunks(3).map(|t| area2((p[3 * t[0] as usize], p[3 * t[0] as usize + 1]), (p[3 * t[1] as usize], p[3 * t[1] as usize + 1]), (p[3 * t[2] as usize], p[3 * t[2] as usize + 1]))).sum();
assert!((a2 - 8.0).abs() < 1e-9, "{a2}");
// Eckpunkt 0 am Netzrand: Dreiecke (0,1,4) und (3,0,4) fallen weg, Sehne 1-4-3 ist entartet (kollinear) und entfällt -> 2 Dreiecke, kein Index >= 4.
let o = del(&r, 0);
let e = &o[0]["entity"];
let ix: Vec<f64> = e["indices"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
assert_eq!(ix.len(), 6);
assert!(ix.iter().all(|&i| i < 4.0));
assert_eq!(e["positions"].as_array().unwrap().len(), 12);
// ungültig: Index ausserhalb, Netz mit nur drei Punkten, fremde Art
assert!(del(&r, 5).is_empty());
assert!(run(json!({"cmd":"meshPointDelete","id":"tm","index":0})).is_empty());
assert!(run(json!({"cmd":"meshPointDelete","id":"hl","index":0})).is_empty());
}
#[test]
fn hoehe_einer_linie() {
let o = run(json!({"cmd":"contourZ","id":"hl","index":1,"z":510}));
+58
View File
@@ -0,0 +1,58 @@
// [193] Netz auf frei gezeichnetes Polygon zuschneiden: Voraussetzung ein gewähltes Netz, Kern-Befehl `meshCrop`.
import { describe, expect, it } from "vitest";
import { sampleProject } from "../../model/sampleProject";
import type { ContextObject, Project } from "../../model/types";
import type { CommandContext, CmdInput } from "../types";
import { meshCropCommand } from "./meshcrop";
const mesh = {
id: "tm", type: "terrainMesh", categoryCode: "02", name: "Gelände",
positions: [0, 0, 1, 2, 0, 2, 2, 2, 3, 0, 2, 4], indices: [0, 1, 2, 0, 2, 3],
} as unknown as ContextObject;
const proj: Project = { ...sampleProject, context: [mesh] };
function ctxOf(p: Project, contextIds: string[]): CommandContext {
return {
project: p,
level: p.drawingLevels.find((l) => l.kind === "floor")!,
defaultCategoryCode: p.layers[0].code,
activeLineStyleId: "solid",
activeWallTypeId: p.wallTypes[0]?.id ?? "",
lastPoint: null,
selection: { wallIds: [], drawingId: null, drawingIds: [], contextIds } as unknown as CommandContext["selection"],
};
}
function draw(ctx: CommandContext, pts: [number, number][]) {
let st = meshCropCommand.init();
for (const [x, y] of pts) st = meshCropCommand.onInput(st, { kind: "point", point: { x, y } } as CmdInput, ctx)[0];
return meshCropCommand.onConfirm(st, ctx)[1];
}
describe("[193] Netz zuschneiden (Befehl)", () => {
it("ohne gewähltes Netz startet er nicht", () => {
expect(meshCropCommand.precondition?.(ctxOf(proj, []))).toBe("cmd.meshcrop.noMesh");
expect(meshCropCommand.precondition?.(ctxOf(proj, ["nix"]))).toBe("cmd.meshcrop.noMesh");
expect(meshCropCommand.precondition?.(ctxOf(proj, ["tm"]))).toBeNull();
});
it("Polygon um die linke Hälfte: ein Dreieck bleibt", () => {
const ctx = ctxOf(proj, ["tm"]);
const res = draw(ctx, [[-1, -1], [1, -1], [1, 3], [-1, 3]]);
expect(res.done).toBe(true);
expect(res.commit).toBeDefined();
const out = res.commit!(proj);
expect((out.context![0] as unknown as { indices: number[] }).indices).toEqual([0, 1, 2]);
});
it("Polygon um alles / ausserhalb: nichts, mit Hinweis", () => {
const ctx = ctxOf(proj, ["tm"]);
const all = draw(ctx, [[-1, -1], [3, -1], [3, 3], [-1, 3]]);
expect(all.commit).toBeUndefined();
expect(all.notice?.key).toBe("cmd.meshcrop.nothing");
const far = draw(ctx, [[10, 10], [11, 10], [11, 11]]);
expect(far.commit).toBeUndefined();
});
it("zwei Punkte = Rechteck aus den Ecken", () => {
const res = draw(ctxOf(proj, ["tm"]), [[-1, -1], [1, 3]]);
expect(res.commit).toBeDefined();
});
});
+129
View File
@@ -0,0 +1,129 @@
// Netz zuschneiden ([193]) — frei gezeichnetes Polygon (oder Rechteck aus zwei Ecken); behalten werden die Dreiecke des
// gewählten Geländes/Netzes, deren Schwerpunkt im Polygon liegt (Kern `cmd_context.rs`, Befehl `meshCrop`).
//
// Schritte:
// 1) „Erster Punkt des Zuschnitts:" → Punkt
// 2) „Nächster Punkt …" → Punkt … Abschluss per Klick auf den Startpunkt, Option „Schliessen" oder Enter
// (≥ 3 Punkte; bei genau 2 Punkten: Rechteck aus den Ecken).
// Meldungen statt stillem Scheitern: ohne gewähltes Netz startet der Befehl nicht; schneidet das Polygon nichts ab
// (oder bliebe nichts übrig), entsteht keine Änderung und es erscheint ein Hinweis.
import type { Command, CommandContext, CommandResult, CommandState, CmdOption, DraftShape, ToolDraft, Vec2 } from "../types";
import { createMutation } from "../createCore";
import { documentFor } from "../../core/document";
const EPS = 1e-6;
const CLOSE_HIT = 0.08; // Modell-Meter: Klick nahe Startpunkt schliesst die Kontur
const dist = (a: Vec2, b: Vec2): number => Math.hypot(b.x - a.x, b.y - a.y);
interface CropIdle extends CommandState {
phase: "start";
}
interface CropDrawing extends CommandState {
phase: "next";
points: Vec2[];
cursor: Vec2 | null;
}
type CropState = CropIdle | CropDrawing;
const CLOSE: CmdOption = { id: "close", labelKey: "cmd.polyline.close" };
const UNDO: CmdOption = { id: "undo", labelKey: "cmd.polyline.undo" };
/** Das einzeln gewählte Gelände/Netz (id), sonst `null`. */
function targetMesh(ctx: CommandContext): string | null {
const ids = ctx.selection.contextIds ?? [];
if (ids.length !== 1) return null;
const o = (ctx.project.context ?? []).find((c) => c.id === ids[0]);
return o && (o.type === "terrainMesh" || o.type === "importedMesh") ? o.id : null;
}
/** Vorschau: Kontur (ab 3 Punkten geschlossen) + Gummiband. */
function cropDraft(points: Vec2[], cursor: Vec2 | null): ToolDraft {
const pts = cursor ? [...points, cursor] : points;
const preview: DraftShape[] = [{ kind: "poly", pts, closed: pts.length >= 3 }];
const draft: ToolDraft = { preview, vertices: points };
const last = points[points.length - 1];
if (cursor && last && dist(last, cursor) >= EPS) draft.hud = { at: cursor, text: `${dist(last, cursor).toFixed(2)} m` };
return draft;
}
/** Polygon als flache Liste; 2 Punkte = Rechteck aus den Ecken. */
function polyOf(points: Vec2[]): number[] {
if (points.length === 2) {
const [a, b] = points;
return [a.x, a.y, b.x, a.y, b.x, b.y, a.x, b.y];
}
return points.flatMap((q) => [q.x, q.y]);
}
function finishResult(points: Vec2[], ctx: CommandContext): CommandResult {
const id = targetMesh(ctx);
const poly = polyOf(points);
if (!id || poly.length < 6) return { draft: null, done: true, notice: { key: "cmd.meshcrop.noMesh", kind: "warning" } };
if (documentFor(ctx.project).cmdOps({ cmd: "meshCrop", id, poly }).length === 0) {
return { draft: null, done: true, notice: { key: "cmd.meshcrop.nothing", kind: "warning" } };
}
return { draft: null, done: true, commit: createMutation(ctx, { cmd: "meshCrop", id, poly }), notice: { key: "cmd.meshcrop.done", kind: "info" } };
}
const idle = (): [CommandState, CommandResult] => [{ phase: "start", lastPoint: null } as CropIdle, { draft: null, done: true }];
const finish = (points: Vec2[], ctx: CommandContext): [CommandState, CommandResult] => [
{ phase: "start", lastPoint: null } as CropIdle,
finishResult(points, ctx),
];
export const meshCropCommand: Command = {
name: "meshcrop",
labelKey: "cmd.meshcrop.label",
floorOnly: true,
prompt: (s) => ((s as CropState).phase === "next" ? "cmd.meshcrop.next" : "cmd.meshcrop.start"),
accepts: (s) => ((s as CropState).phase === "next" ? ["point", "option"] : ["point"]),
options: (s) => {
const ps = s as CropState;
if (ps.phase !== "next") return [];
return ps.points.length >= 3 ? [CLOSE, UNDO] : [UNDO];
},
precondition: (ctx) => (targetMesh(ctx) ? null : "cmd.meshcrop.noMesh"),
init: (): CropIdle => ({ phase: "start", lastPoint: null }),
onInput: (state, input, ctx): [CommandState, CommandResult] => {
const s = state as CropState;
if (input.kind === "option") {
if (s.phase !== "next") return [s, { draft: null }];
if (input.id === "undo") {
const pts = s.points.slice(0, -1);
if (pts.length === 0) return [{ phase: "start", lastPoint: null } as CropIdle, { draft: null }];
const ns: CropDrawing = { phase: "next", points: pts, cursor: s.cursor, lastPoint: pts[pts.length - 1] };
return [ns, { draft: cropDraft(pts, s.cursor) }];
}
if (input.id === "close" && s.points.length >= 3) return finish(s.points, ctx);
return [s, { draft: cropDraft(s.points, s.cursor) }];
}
if (input.kind !== "point") return [s, { draft: s.phase === "next" ? cropDraft(s.points, s.cursor) : null }];
const pt = input.point;
if (s.phase !== "next") {
const ns: CropDrawing = { phase: "next", points: [pt], cursor: pt, lastPoint: pt };
return [ns, { draft: cropDraft([pt], pt) }];
}
if (s.points.length >= 3 && dist(s.points[0], pt) < CLOSE_HIT) return finish(s.points, ctx);
if (dist(s.points[s.points.length - 1], pt) < EPS) return [s, { draft: cropDraft(s.points, s.cursor) }];
const points = [...s.points, pt];
const ns: CropDrawing = { phase: "next", points, cursor: pt, lastPoint: pt };
return [ns, { draft: cropDraft(points, pt) }];
},
onMove: (state, point): [CommandState, CommandResult] => {
const s = state as CropState;
if (s.phase !== "next") return [s, { draft: null }];
const ns: CropDrawing = { ...s, cursor: point };
return [ns, { draft: cropDraft(s.points, point) }];
},
onConfirm: (state, ctx): [CommandState, CommandResult] => {
const s = state as CropState;
if (s.phase === "next" && s.points.length >= 2) return finish(s.points, ctx);
return idle();
},
onCancel: (): [CommandState, CommandResult] => idle(),
};
+3
View File
@@ -68,6 +68,7 @@ import { multilineCommand } from "./cmds/multiline";
import { importCommand } from "./cmds/import";
import { terrainCommand } from "./cmds/terrain";
import { excavationCommand } from "./cmds/excavation";
import { meshCropCommand } from "./cmds/meshcrop";
import { measureCommand } from "./cmds/measure";
import { sectionLineCommand, viewLineCommand } from "./cmds/sectionline";
import { georefCommand } from "./cmds/georef";
@@ -149,6 +150,7 @@ export const COMMANDS: Record<string, Command> = {
praesentation: presentationCommand,
terrain: terrainCommand,
excavation: excavationCommand,
meshcrop: meshCropCommand,
measure: measureCommand,
sectionline: sectionLineCommand,
viewline: viewLineCommand,
@@ -302,6 +304,7 @@ export const ALIASES: Record<string, string> = {
ter: "terrain",
baugrube: "excavation",
aushub: "excavation",
netzzuschnitt: "meshcrop",
schnittlinie: "sectionline",
ansichtslinie: "viewline",
bezugspunkt: "georef",
+2
View File
@@ -93,3 +93,5 @@ export { standardOverrideRules } from "../model/standards";
export { standardModelViews } from "../model/standards";
export { recognizeMutation, recognizeReport, recognizeSourceLevels } from "../io/recognizeDrawing";
export type { RecognizeOptions, RecognizeReport, RecognizeUnclear } from "../io/recognizeDrawing";
export { meshGripIndices, growRect, nearestMeshVertex, meshTolerance } from "../geometry/meshPick";
export type { MeshRect } from "../geometry/meshPick";
+35
View File
@@ -0,0 +1,35 @@
import { describe, it, expect } from "vitest";
import { growRect, meshGripIndices, meshTolerance, nearestMeshVertex } from "./meshPick";
// 10 x 10 Raster, Punkt i = (i % 10, floor(i / 10)), z = 0
const grid = Array.from({ length: 100 }, (_, i) => [i % 10, Math.floor(i / 10), 0]).flat();
describe("meshGripIndices", () => {
it("kleine Netze: alle Punkte, ohne Ausschnitt", () => {
expect(meshGripIndices(grid, null, 100)).toHaveLength(100);
});
it("grosses Netz ohne Ausschnitt: keine Griffe", () => {
expect(meshGripIndices(grid, null, 50)).toEqual([]);
});
it("grosses Netz: nur Punkte im Ausschnitt", () => {
const r = meshGripIndices(grid, { x0: -0.5, y0: -0.5, x1: 1.5, y1: 1.5 }, 4);
expect(r).toEqual([0, 1, 10, 11]);
});
it("Obergrenze: die der Mitte nächsten bleiben; aktiver Punkt immer dabei", () => {
const r = meshGripIndices(grid, { x0: -1, y0: -1, x1: 10, y1: 10 }, 4, 99);
expect(r).toHaveLength(5);
expect(r).toContain(99);
expect(r).toContain(55);
});
});
describe("nearestMeshVertex / Toleranz", () => {
it("findet den nächsten Punkt innerhalb der Toleranz", () => {
expect(nearestMeshVertex(grid, { x: 3.1, y: 2.05 }, 0.3)).toBe(23);
expect(nearestMeshVertex(grid, { x: 3.5, y: 2.5 }, 0.3)).toBeNull();
});
it("Toleranz und Ausschnitt", () => {
expect(meshTolerance(grid)).toBeCloseTo(Math.hypot(9, 9) * 0.02, 9);
expect(growRect({ x0: 0, y0: 0, x1: 10, y1: 20 }, 0.5)).toEqual({ x0: -5, y0: -10, x1: 15, y1: 30 });
});
});
+71
View File
@@ -0,0 +1,71 @@
// [193] Netzpunkte (Gelände/Netz) im Grundriss: welche bekommen Griffe, welcher liegt unter dem Zeiger.
// Reine Hilfen auf der flachen `positions`-Liste (x, y, z, …); Bearbeiten selbst läuft über Kern-Ops/-Befehle.
export interface MeshRect {
x0: number;
y0: number;
x1: number;
y1: number;
}
/**
* Nummern der Netzpunkte, die einen Griff bekommen: alle bis `cap` Punkte; bei grösseren Netzen die Punkte im Ausschnitt
* `rect` (Modell-Meter), die `cap` der Ausschnittsmitte nächsten. `always` (z. B. der aktive Punkt) bleibt dabei.
* Ohne Ausschnitt und über `cap` Punkten: leer.
*/
export function meshGripIndices(positions: ArrayLike<number>, rect: MeshRect | null, cap: number, always: number | null = null): number[] {
const n = Math.floor(positions.length / 3);
if (n <= cap) return Array.from({ length: n }, (_, i) => i);
if (!rect) return [];
const cx = (rect.x0 + rect.x1) / 2;
const cy = (rect.y0 + rect.y1) / 2;
const inside: { i: number; d: number }[] = [];
for (let i = 0; i < n; i++) {
const x = positions[3 * i];
const y = positions[3 * i + 1];
if (x >= rect.x0 && x <= rect.x1 && y >= rect.y0 && y <= rect.y1) inside.push({ i, d: (x - cx) ** 2 + (y - cy) ** 2 });
}
if (inside.length > cap) {
inside.sort((a, b) => a.d - b.d);
inside.length = cap;
}
const out = inside.map((q) => q.i).sort((a, b) => a - b);
if (always != null && always >= 0 && always < n && !out.includes(always)) out.push(always);
return out;
}
/** Ausschnitt um `margin` (Anteil der Kantenlänge je Seite) vergrössert, damit kleines Schwenken die Griffe nicht erneuert. */
export function growRect(r: MeshRect, margin: number): MeshRect {
const dx = (r.x1 - r.x0) * margin;
const dy = (r.y1 - r.y0) * margin;
return { x0: r.x0 - dx, y0: r.y0 - dy, x1: r.x1 + dx, y1: r.y1 + dy };
}
/** Nummer des Netzpunkts, der `pt` am nächsten liegt (höchstens `tol` Meter entfernt), sonst `null`. */
export function nearestMeshVertex(positions: ArrayLike<number>, pt: { x: number; y: number }, tol: number): number | null {
const n = Math.floor(positions.length / 3);
let best: number | null = null;
let bd = tol * tol;
for (let i = 0; i < n; i++) {
const d = (positions[3 * i] - pt.x) ** 2 + (positions[3 * i + 1] - pt.y) ** 2;
if (d <= bd) {
bd = d;
best = i;
}
}
return best;
}
/** Klick-Toleranz für Netzpunkte: 2 % der Netzdiagonale, mindestens 5 cm (wie `toleranceFor` der Umrisse). */
export function meshTolerance(positions: ArrayLike<number>): number {
const n = Math.floor(positions.length / 3);
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (let i = 0; i < n; i++) {
minX = Math.min(minX, positions[3 * i]);
maxX = Math.max(maxX, positions[3 * i]);
minY = Math.min(minY, positions[3 * i + 1]);
maxY = Math.max(maxY, positions[3 * i + 1]);
}
if (!Number.isFinite(minX)) return 0.05;
return Math.max(0.05, Math.hypot(maxX - minX, maxY - minY) * 0.02);
}
+16
View File
@@ -1080,6 +1080,14 @@ export const de = {
"ctx.insertCorner": "Ecke einfügen",
"ctx.deleteCorner": "Ecke löschen",
"ctx.deleteCorner.min": "Mindestens drei Ecken bleiben.",
"ctx.deleteCorner.minOpen": "Mindestens zwei Punkte bleiben (offene Linie).",
"ctx.meshPointHeight": "Höhe setzen …",
"ctx.meshPointDelete": "Netzpunkt löschen",
"ctx.meshPointDelete.hint": "Entfernt den Punkt und vernetzt das entstehende Loch neu",
"ctx.meshPointDelete.min": "Mindestens drei Netzpunkte bleiben.",
"site.meshPointHeight.title": "Höhe des Netzpunkts",
"site.meshPointHeight.label": "Höhe von Netzpunkt {n} (m)",
"site.meshPointDelete": "Punkt löschen",
"ctx.vertexType.corner": "Eckpunkt",
"ctx.vertexType.arc": "Bogenpunkt",
"ctx.vertexType.spline": "Splinepunkt",
@@ -1974,6 +1982,14 @@ export const de = {
"cmd.excavation.fillOnly": "Baugrube angelegt, aber die Sohle {bottom} m liegt über dem Gelände: nur Aufschüttung — Sohle in der Objekt-Info tiefer setzen",
"cmd.terrain.noContours": "Kein Gelände erzeugt: es gibt keine Höhenlinien (DXF importieren oder Standort importieren)",
"cmd.excavation.label": "Baugrube",
"cmd.meshcrop.label": "Netz zuschneiden",
"cmd.meshcrop.start": "Erster Punkt des Zuschnitts (Polygon oder zwei Ecken für ein Rechteck):",
"cmd.meshcrop.next": "Nächster Punkt (Enter oder Startpunkt schliesst):",
"cmd.meshcrop.noMesh": "Zuerst ein Gelände bzw. Netz im Plan wählen",
"cmd.meshcrop.nothing": "Nichts zuzuschneiden: Das Polygon enthält das ganze Netz oder keinen Dreiecks-Schwerpunkt.",
"cmd.meshcrop.done": "Netz zugeschnitten (Rückgängig stellt es wieder her)",
"site.meshCrop.draw": "Auf Polygon zuschneiden …",
"site.meshCrop.draw.hint": "Polygon oder Rechteck im Plan zeichnen; Dreiecke ausserhalb entfallen",
"cmd.excavation.start": "Erster Punkt der Baugrubensohle:",
"cmd.excavation.next": "Nächster Punkt (Enter bei 2 Punkten = Rechteck, ab 3 Punkten Polygon):",
"cmd.roofHole.start": "Erster Punkt des Innenhofs (im Dach):",
+16
View File
@@ -1075,6 +1075,14 @@ export const en: Record<TranslationKey, string> = {
"ctx.insertCorner": "Insert corner",
"ctx.deleteCorner": "Delete corner",
"ctx.deleteCorner.min": "At least three corners remain.",
"ctx.deleteCorner.minOpen": "At least two points remain (open line).",
"ctx.meshPointHeight": "Set height …",
"ctx.meshPointDelete": "Delete mesh point",
"ctx.meshPointDelete.hint": "Removes the point and re-meshes the resulting hole",
"ctx.meshPointDelete.min": "At least three mesh points remain.",
"site.meshPointHeight.title": "Mesh point height",
"site.meshPointHeight.label": "Height of mesh point {n} (m)",
"site.meshPointDelete": "Delete point",
"ctx.vertexType.corner": "Corner point",
"ctx.vertexType.arc": "Arc point",
"ctx.vertexType.spline": "Spline point",
@@ -1963,6 +1971,14 @@ export const en: Record<TranslationKey, string> = {
"cmd.excavation.fillOnly": "Excavation created, but its bottom {bottom} m lies above the terrain: fill only — lower the bottom in Object Info",
"cmd.terrain.noContours": "No terrain generated: there are no contour lines (import a DXF or the site)",
"cmd.excavation.label": "Excavation",
"cmd.meshcrop.label": "Crop mesh",
"cmd.meshcrop.start": "First point of the crop (polygon, or two corners for a rectangle):",
"cmd.meshcrop.next": "Next point (Enter or the start point closes):",
"cmd.meshcrop.noMesh": "Select a terrain or mesh in the plan first",
"cmd.meshcrop.nothing": "Nothing to crop: the polygon contains the whole mesh or no triangle centroid.",
"cmd.meshcrop.done": "Mesh cropped (undo restores it)",
"site.meshCrop.draw": "Crop to polygon …",
"site.meshCrop.draw.hint": "Draw a polygon or rectangle in the plan; triangles outside are removed",
"cmd.excavation.start": "First point of the excavation bottom:",
"cmd.excavation.next": "Next point (Enter with 2 points = rectangle, 3 or more = polygon):",
"cmd.roofHole.start": "First point of the courtyard (inside the roof):",
+8
View File
@@ -80,6 +80,8 @@ export function AppContextMenu(props: {
resetDimensionTexts,
} = props.selCmds;
const project = useStore((s) => s.project);
const deleteMeshPoint = useStore((s) => s.deleteMeshPoint);
const setMeshHeightPrompt = useStore((s) => s.setMeshHeightPrompt);
const { selectionAllLocked, selectionLayerCodes, selectionAllNoPrint, attachedDimensionIds, movedDimTextIds } = selectionMenuState(
project,
selection,
@@ -180,6 +182,12 @@ export function AppContextMenu(props: {
})(),
insertRingVertex,
deleteRingVertex,
selectedMesh: (() => {
const ctx = selection.contextObjects.length === 1 ? (project.context ?? []).find((x) => x.id === selection.contextObjects[0]) : undefined;
return ctx && (ctx.type === "terrainMesh" || ctx.type === "importedMesh") ? { id: ctx.id, positions: ctx.positions } : null;
})(),
askMeshPointHeight: (id, index) => setMeshHeightPrompt({ id, index }),
deleteMeshPoint: (id, index) => { deleteMeshPoint(id, index); },
insertPolylinePoint: insertDrawingPoint,
deletePolylinePoint: deleteDrawingPoint,
setPolylineVertexType,
+28 -2
View File
@@ -9,7 +9,7 @@
import { t } from "../i18n";
import { canSetVertexType, vertexTypeOf, type PolylineVertexType, type RingKind } from "../core";
import { nearestPolylineTarget, toleranceFor } from "../core";
import { meshTolerance, nearestMeshVertex, nearestPolylineTarget, toleranceFor } from "../core";
import type { LayerCategory, Project, Vec2 } from "../model/types";
import { flattenCategories } from "../model/types";
import { findCategory } from "../model/layers";
@@ -93,6 +93,10 @@ export interface MenuActions {
selectedRing?: { kind: RingKind; id: string; rings: { pts: Vec2[]; off: number; closed?: boolean }[] } | null;
insertRingVertex?: (kind: RingKind, id: string, seg: number, pt: Vec2) => void;
deleteRingVertex?: (kind: RingKind, id: string, index: number) => void;
/** [193] Einzeln gewähltes Gelände-/Netz-Element: Rechtsklick auf einen Netzpunkt → „Höhe setzen …" / „Netzpunkt löschen". */
selectedMesh?: { id: string; positions: number[] } | null;
askMeshPointHeight?: (id: string, index: number) => void;
deleteMeshPoint?: (id: string, index: number) => void;
deleteSectionBend?: (id: string, index: number) => void;
/** Ob eine Element-Stil-Zwischenablage gefüllt ist (aktiviert „Einfügen"). */
hasDrawingStyleClipboard: boolean;
@@ -381,13 +385,35 @@ function planMenuItems(
label: t("ctx.deleteCorner"),
icon: <MenuIcon name="do_not_disturb_on" />,
disabled: !enabled,
title: enabled ? undefined : t("ctx.deleteCorner.min"),
title: enabled ? undefined : t(closed ? "ctx.deleteCorner.min" : "ctx.deleteCorner.minOpen"),
onClick: () => a.deleteRingVertex?.(ring.kind, ring.id, off + hit.index),
});
}
break;
}
}
// [193] Netzpunkt unter dem Zeiger: Höhe setzen (Overlay-Eingabe) bzw. Punkt löschen (Loch wird neu vernetzt).
const mesh = a.selectedMesh;
const meshHit = mesh ? nearestMeshVertex(mesh.positions, model, meshTolerance(mesh.positions)) : null;
if (mesh && meshHit != null) {
if (a.askMeshPointHeight) {
pointItems.push({
label: t("ctx.meshPointHeight"),
icon: <MenuIcon name="height" />,
onClick: () => a.askMeshPointHeight?.(mesh.id, meshHit),
});
}
if (a.deleteMeshPoint) {
const enabled = mesh.positions.length / 3 > 3;
pointItems.push({
label: t("ctx.meshPointDelete"),
icon: <MenuIcon name="do_not_disturb_on" />,
disabled: !enabled,
title: enabled ? t("ctx.meshPointDelete.hint") : t("ctx.meshPointDelete.min"),
onClick: () => a.deleteMeshPoint?.(mesh.id, meshHit),
});
}
}
// Eigenschaften übertragen — dasselbe Muster wie im Ebenen-Menü, nur für
// 2D-Elemente. Kopieren ab einem gewählten Element, Einfügen sobald etwas
// in der Zwischenablage liegt.
+23 -1
View File
@@ -11,7 +11,7 @@ import { useStore } from "../state/appStore";
import type { ContextObject } from "../model/types";
import { flattenCategories } from "../model/types";
import { resmoothGridTerrain } from "../model/terrain";
import { useMemo, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import type { ExcavationQuantity } from "../core";
/** Zahl-Eingabe für ein Feld eines Kontext-Objekts (leer = Standard, ungültig = keine Änderung). */
@@ -67,11 +67,19 @@ const RESMOOTH_PASSES = [1, 2, 4] as const;
/** [193] Netzpunkt wählen (Nummer ab 1) und seine Höhe setzen; Zuschneiden des Netzes auf die Parzelle. */
function MeshPointFields({ obj }: { obj: Extract<ContextObject, { positions: number[] }> }) {
const host = usePanelHost();
const setMeshPointHeight = useStore((s) => s.setMeshPointHeight);
const cropMesh = useStore((s) => s.cropMesh);
const notify = useStore((s) => s.notify);
const parcel = useStore((s) => s.project.siteRules?.parcel);
const deleteMeshPoint = useStore((s) => s.deleteMeshPoint);
const active = useStore((s) => s.activeMeshPoint);
const [nr, setNr] = useState("1");
// Klick auf einen Netzpunkt-Griff im Grundriss wählt den Punkt: Nummer (und damit Höhe) vorausgefüllt.
const activeIndex = active?.id === obj.id ? active.index : null;
useEffect(() => {
if (activeIndex != null) setNr(String(activeIndex + 1));
}, [activeIndex]);
const n = Math.floor(obj.positions.length / 3);
const i = Math.round(Number(nr)) - 1;
const valid = Number.isFinite(i) && i >= 0 && i < n;
@@ -95,6 +103,17 @@ function MeshPointFields({ obj }: { obj: Extract<ContextObject, { positions: num
}}
/>
</label>
<button
type="button"
data-testid="mesh-point-delete"
disabled={!valid || n <= 3}
title={t("ctx.meshPointDelete.hint")}
onClick={() => {
if (valid) deleteMeshPoint(obj.id, i);
}}
>
{t("site.meshPointDelete")}
</button>
<button
type="button"
data-testid="mesh-crop-parcel"
@@ -106,6 +125,9 @@ function MeshPointFields({ obj }: { obj: Extract<ContextObject, { positions: num
>
{t("site.meshCrop")}
</button>
<button type="button" data-testid="mesh-crop-polygon" title={t("site.meshCrop.draw.hint")} onClick={() => host.onRunCommand("meshcrop")}>
{t("site.meshCrop.draw")}
</button>
</>
);
}
+13
View File
@@ -79,4 +79,17 @@ describe("Gelände-Netz: Punkte und Zuschnitt [193]", () => {
const crop = documentFor(p).cmdOps({ cmd: "meshCrop", id: "tm", poly: [-1, -1, 1, -1, 1, 3, -1, 3] });
expect(JSON.stringify(crop)).toContain('"indices":[0,1,2]');
});
it("Netzpunkt löschen vernetzt das Loch neu und führt Nummern nach", () => {
// Quadrat 0..2 mit Mittelpunkt (Nr. 4): ohne ihn bleiben zwei Dreiecke über den vier Ecken.
const sq = {
id: "sq", type: "terrainMesh", categoryCode: "02", name: "Gelände",
positions: [0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 2, 0, 1, 1, 9], indices: [0, 1, 4, 1, 2, 4, 2, 3, 4, 3, 0, 4],
} as unknown as ContextObject;
const p: Project = { ...sampleProject, context: [sq] };
const ops = documentFor(p).cmdOps({ cmd: "meshPointDelete", id: "sq", index: 4 });
expect(ops).toHaveLength(1);
const j = JSON.stringify(ops);
expect(j).toContain('"positions":[0,0,0,2,0,0,2,2,0,0,2,0]');
expect(documentFor(p).cmdOps({ cmd: "meshPointDelete", id: "sq", index: 9 })).toHaveLength(0);
});
});
+38
View File
@@ -0,0 +1,38 @@
// [193] Sichtbarer Ausschnitt des Grundrisses in Modell-Metern, für Griffe grosser Netze (nur Punkte im Bild).
// Die Kamera lebt in `PlanView`; diese kleine Brücke meldet sie (verzögert, damit Schwenken nicht jeden Frame neu
// rechnet) an `useGripEditing`. Kein Zustand im Store: reiner Anzeige-Ausschnitt, ändert das Projekt nie.
import type { MeshRect } from "../core";
let current: MeshRect | null = null;
const listeners = new Set<() => void>();
let timer: ReturnType<typeof setTimeout> | null = null;
/** viewBox (Bild-px, y nach unten, `PX_PER_M` je Meter) → Modell-Rechteck. */
export function viewBoxToMeshRect(v: { x: number; y: number; w: number; h: number }, pxPerM: number): MeshRect {
return { x0: v.x / pxPerM, x1: (v.x + v.w) / pxPerM, y0: -(v.y + v.h) / pxPerM, y1: -v.y / pxPerM };
}
function sameRect(a: MeshRect | null, b: MeshRect): boolean {
return !!a && a.x0 === b.x0 && a.y0 === b.y0 && a.x1 === b.x1 && a.y1 === b.y1;
}
/** Neuen Ausschnitt melden; Abonnenten erfahren es nach kurzer Ruhe (gleiche Werte = keine Meldung). */
export function publishPlanViewport(r: MeshRect, delayMs = 150): void {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
if (sameRect(current, r)) return;
current = r;
listeners.forEach((l) => l());
}, delayMs);
}
export function getPlanViewport(): MeshRect | null {
return current;
}
export function subscribePlanViewport(l: () => void): () => void {
listeners.add(l);
return () => listeners.delete(l);
}
+26
View File
@@ -40,6 +40,14 @@ export interface SiteSlice {
setContourHeight: (id: string, index: number, z: number, coalesceKey?: string) => void;
/** [193] Höhe eines Netzpunkts (Vertex-Nummer ab 0) setzen. */
setMeshPointHeight: (id: string, index: number, z: number, coalesceKey?: string) => void;
/** [193] Netzpunkt löschen; sein Loch wird neu vernetzt (Kern `cmd_context.rs`); false = nichts geändert. */
deleteMeshPoint: (id: string, index: number) => boolean;
/** [193] Aktiver Netzpunkt (Klick auf den Griff): die Objekt-Info zeigt seine Nummer und Höhe. */
activeMeshPoint: { id: string; index: number } | null;
setActiveMeshPoint: (p: { id: string; index: number } | null) => void;
/** [193] Offene Höhen-Eingabe für einen Netzpunkt (Rechtsklick auf den Griff, „Höhe setzen …"). */
meshHeightPrompt: { id: string; index: number } | null;
setMeshHeightPrompt: (p: { id: string; index: number } | null) => void;
/** [193] Netz auf ein Polygon (Modell-Meter) zuschneiden; false = nichts geändert. */
cropMesh: (id: string, poly: Vec2[]) => boolean;
/** [193] Kontext-Elemente um `delta` verschieben (Maus-Ziehen im Plan; Kern `cmd_transform.rs`), ein Undo-Schritt. */
@@ -120,6 +128,24 @@ export function createSiteSlice(
if (ops.length) get().applyChange(ops, coalesceKey);
},
deleteMeshPoint: (id, index) => {
const ops = documentFor(get().project).cmdOps({ cmd: "meshPointDelete", id, index });
if (ops.length) {
get().applyChange(ops);
api.set({ activeMeshPoint: null, meshHeightPrompt: null }); // Nummern verschieben sich
}
return ops.length > 0;
},
activeMeshPoint: null,
setActiveMeshPoint: (p) => {
const cur = get().activeMeshPoint;
if (cur?.id === p?.id && cur?.index === p?.index) return;
api.set({ activeMeshPoint: p });
},
meshHeightPrompt: null,
setMeshHeightPrompt: (p) => api.set({ meshHeightPrompt: p }),
cropMesh: (id, poly) => {
const ops = documentFor(get().project).cmdOps({ cmd: "meshCrop", id, poly: poly.flatMap((q) => [q.x, q.y]) });
if (ops.length) get().applyChange(ops);
+19 -7
View File
@@ -46,7 +46,9 @@ import type { BodyTarget } from "../views/plan/PlanView";
import type { CommandLineHandle } from "../ui/CommandLine";
import type { CommandEngine } from "../commands/engine";
import { single } from "./selection";
import { getState as storeState } from "./appStore";
import { getState as storeState, useStore } from "./appStore";
import { getPlanViewport, subscribePlanViewport } from "./planViewport";
import { growRect, meshGripIndices } from "../core";
import { patchItem, verticalExtents } from "../core";
import { treeGripPatch, treeGripPoints } from "./treeGrips";
import type { Selection } from "./selection";
@@ -202,6 +204,9 @@ export function useGripEditing(opts: {
return o && (o.type === "terrainMesh" || o.type === "importedMesh") ? o : null;
})()
: null;
// [193] Aktiver Netzpunkt und sichtbarer Ausschnitt (nur für Netze über der Griff-Grenze abonniert).
const activeMeshPoint = useStore((st) => st.activeMeshPoint);
const meshViewport = useSyncExternalStore(subscribePlanViewport, () => (selectedMesh && selectedMesh.positions.length / 3 > 600 ? getPlanViewport() : null));
const selectedTreeId = single(selection, "trees");
const selectedTree = selectedTreeId ? (project.trees ?? []).find((x) => x.id === selectedTreeId) : undefined;
// [176] Schnitt-/Ansichtslinie im Grundriss: Griffe an Anfang, Knickpunkten (`bendPoints`) und Ende.
@@ -548,15 +553,17 @@ export function useGripEditing(opts: {
}
return pts;
}
// [193] Gelände-Netz: jeder Netzpunkt ein Griff (xy; die Höhe steht in der Objekt-Info). Grosse Netze (swissALTI3D
// mit tausenden Punkten) bekommen keine Griffe — dort hilft Zuschneiden auf das Grundstück.
// [193] Gelände-Netz: Netzpunkte als Griffe (xy; die Höhe: Klick auf den Griff wählt den Punkt, dann die Objekt-Info
// bzw. Rechtsklick „Höhe setzen …"). Bis MAX_CONTOUR_GRIPS Punkte alle, grössere Netze (swissALTI3D) nur im
// sichtbaren Ausschnitt (mit Rand, die der Mitte nächsten, höchstens MAX_CONTOUR_GRIPS).
if (selectedMesh && !selectedCeiling && effectiveDrawingIds.length === 0 && selectedWallIds.length === 0) {
const n = Math.floor(selectedMesh.positions.length / 3);
if (n > MAX_CONTOUR_GRIPS) return [];
const active = activeMeshPoint?.id === selectedMesh.id ? activeMeshPoint.index : null;
const rect = n > MAX_CONTOUR_GRIPS && meshViewport ? growRect(meshViewport, 0.5) : null;
const pts: Vec2[] = [];
for (let i = 0; i < n; i++) {
for (const i of meshGripIndices(selectedMesh.positions, rect, MAX_CONTOUR_GRIPS, active)) {
pts.push({ x: selectedMesh.positions[3 * i], y: selectedMesh.positions[3 * i + 1] });
gripOwners.push({ localIndex: i });
gripOwners.push({ localIndex: i }); // = Netzpunkt-Nummer (bei Ausschnitt ≠ Griff-Index)
gripOwnerRange.push([0, n - 1]);
}
return pts;
@@ -1170,7 +1177,7 @@ export function useGripEditing(opts: {
const applyGrip = (index: number, pt: Vec2, arcLength?: number) => {
// [193] Höhenlinien-Punkt bzw. Einfüge-Raute: nur Vorschau, das Projekt ändert sich beim Setzen (ein Undo-Schritt).
if (selectedMesh) {
pendingContourRef.current = { id: selectedMesh.id, index, pt, mesh: true };
pendingContourRef.current = { id: selectedMesh.id, index: gripOwners[index]?.localIndex ?? index, pt, mesh: true };
return;
}
if (selectedContourSet) {
@@ -1685,6 +1692,11 @@ export function useGripEditing(opts: {
};
const gripHandlers = {
/** [193] Griff gepackt: bei Netzpunkten wird der Punkt zum aktiven (Objekt-Info, Rechtsklick-Höhe). */
onGripGrab: (index: number) => {
const vi = gripOwners[index]?.localIndex;
if (selectedMesh && vi != null) storeState().setActiveMeshPoint({ id: selectedMesh.id, index: vi });
},
onGripMove: (index: number, raw: Vec2, pxPerMeter: number, mods: ToolMods) => {
sectionPxRef.current = pxPerMeter;
// Schnitt/Ansicht ([187]): Höhen-Griff (Wand, Öffnung, Decke).
+22
View File
@@ -134,6 +134,13 @@ export function AppDialogs(props: {
const needsProject = resourcesOpen || !!importState || settingsOpen;
const subscribed = useStore((s) => (needsProject ? s.project : null));
const project = subscribed ?? getState().project;
// [193] Höhe eines Netzpunkts (Rechtsklick auf den Griff): Overlay-Eingabe statt window.prompt.
const meshHeightPrompt = useStore((s) => s.meshHeightPrompt);
const meshPromptZ = useStore((s) => {
const p = s.meshHeightPrompt;
const o = p ? (s.project.context ?? []).find((c) => c.id === p.id) : undefined;
return p && o && "positions" in o ? o.positions[3 * p.index + 2] : undefined;
});
return (
<>
{/* Frei schwebendes, NICHT-modales Ressourcen-Fenster: kein Backdrop, der
@@ -292,6 +299,21 @@ export function AppDialogs(props: {
/>
)}
{meshHeightPrompt && meshPromptZ !== undefined && (
<PromptDialog
title={t("site.meshPointHeight.title")}
label={t("site.meshPointHeight.label", { n: meshHeightPrompt.index + 1 })}
defaultValue={String(Math.round(meshPromptZ * 1000) / 1000)}
type="number"
onConfirm={(v) => {
const z = Number(v.replace(",", "."));
if (Number.isFinite(z)) getState().setMeshPointHeight(meshHeightPrompt.id, meshHeightPrompt.index, z);
getState().setMeshHeightPrompt(null);
}}
onClose={() => getState().setMeshHeightPrompt(null)}
/>
)}
{pendingCopyMode && (
<PromptDialog
title={t(pendingCopyMode === "array" ? "transform.mode.array" : "transform.mode.distribute")}
+3
View File
@@ -16,6 +16,7 @@ import { contentFontBaselineFromTop, TEXT_LINE_HEIGHT_MULT } from "../../text/fo
import { textFrameCorners } from "../../text/textFrame";
import { RichTextEditor } from "../../editors/RichTextEditor";
import { LiveMeet, LiveValue } from "./planView/liveMeet";
import { publishPlanViewport, viewBoxToMeshRect } from "../../state/planViewport";
import { DEFAULT_MARQUEE_COLOR, DEFAULT_SNAP_COLOR } from "../../theme/accents";
import { type ViewBox__plan_planView_geometry as ViewBox, PX_PER_M, PAD, toScreen, meetScale, defaultViewFor } from "../../core";
import {
@@ -174,6 +175,8 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// Aktueller Ausschnitt; treibt die viewBox des SVG. Initial = eingepasst.
const [view, setView] = useState<ViewBox>(defaultView);
// [193] Sichtbarer Ausschnitt (Modell-Meter) für die Netzpunkt-Griffe grosser Netze (verzögert gemeldet).
useEffect(() => publishPlanViewport(viewBoxToMeshRect(view, PX_PER_M)), [view]);
// [26] Kante unter dem Cursor (Kanten-Anfasser); gezeichnet wird sie nur für Flächen-Elemente
// (Dach, Decke, Raum, Baugrube), deren Kanten-Indizes Griff-Indizes sind.
const [hoverEdge, setHoverEdge] = useState<EdgeGrip | null>(null);
+2
View File
@@ -455,6 +455,8 @@ export interface GripHandlers {
* Modellpunkt unter dem Cursor.
*/
onEdgeMove(edge: EdgeGrip, raw: Vec2, pxPerMeter: number, mods: ToolMods): void;
/** Griff `index` wurde gepackt (Klick), noch vor dem ersten Ziehen. */
onGripGrab?(index: number): void;
onGripEnd(): void;
/**
* Bewaffneten Punkt-Griff verwerfen (Escape): setzt den Punkt exakt auf
@@ -252,6 +252,7 @@ export function usePlanPointer(inp: UsePlanPointerArgs) {
// und folgt via normalem Hover-onPointerMove weiter dem Cursor (s.
// Kommentar an der gripDrag-Deklaration).
gripDrag.current = { pointerId: e.pointerId, index: gi, origin: grips![gi], startX: e.clientX, startY: e.clientY };
gripHandlers?.onGripGrab?.(gi);
return;
}
// Linke Taste auf einem Kanten-Anfasser (Dreieck): Seite ziehen. KEIN