[K3d] Merge: Rahmenauswahl, Text-/Bild-Treffer, DXF und Druck-SVG aus dem Plan-Puffer, Plan träge dekodiert
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
30 files changed
+3213
-1851
No files matched your search
@@ -206,6 +206,36 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
(`exportDxf.ts`, 1000 Zeilen Stil/Layer-Logik) und `planToPrintSvg.ts` (Layout-PDF/LayoutSheet; nicht auf `sceneToPrintSvg`
|
||||
umgestellt, weil die Ausgabe dann nicht mehr byte-gleich wäre). `generatePlan` dekodiert den Kern-Puffer weiter vollständig
|
||||
(für diese Verbraucher); fällt, wenn sie den Puffer lesen bzw. das Modell nach Rust zieht [K4].
|
||||
✅ (29.10.) **Letzte Verbraucher lesen den Puffer, `generatePlan` liest lazy.**
|
||||
- Lazy Plan (`src/plan/planLazy.ts`): `generatePlan`, `generateVisibleLevelsPlan`, `materializeUnderlay` und
|
||||
`planWithExtra` (Überlagerungen in `viewportContent`) setzen den Plan aus Stücken zusammen (Kern-Abschnitte +
|
||||
TS-Listen); `plan.primitives` entsteht erst beim ersten Zugriff. `decodePlanBuf` liest Einträge, Texte und
|
||||
Schraffur-JSON bei Bedarf (`prim(i)`, `tag(i)`); `planPrimAt` (ein Eintrag), `planTextEntries` (nur Texte/Bilder,
|
||||
aus den Typ-Kennungen), `planCount`. `planParts` nimmt die Stücke direkt (keine Identitätsprüfung). Abzugskörper,
|
||||
Mono und Strichstärken-Massstab bleiben auf der Liste (sie ändern Primitive).
|
||||
- Auswahl (`plan_pick.rs`): Rahmen-Auswahl über Polygone je Pick-Art und über 2D-Zeichnungen (Linien, Polygone,
|
||||
abgetastete Kreise/Bögen, Text-/Bild-Rahmen, Unterlage ausgenommen), Einzeltext-/Bild-Treffer, Form einer
|
||||
Zeichnung (`drawingLabel`). `marqueeHit*`/`marqueeHitDrawings` in TS gelöscht.
|
||||
- PlanView: Einzelzugriffe über `planPrimAt`; mit GPU kommen SVG-Kandidaten/Culling nur aus den Text-Einträgen
|
||||
(Culling selbst bleibt TS über diese wenigen); `planSceneTexts` und die native Text-Sync lesen nur Text-Einträge.
|
||||
- DXF/DWG (`plan_dxf.rs`): Sammler (Ebenen, Linientypen, Textstile, DIMENSION, BLOCK/INSERT/ATTRIB, HATCH, Verlauf,
|
||||
Zufallsstriche, Papierbereich) im Kern aus Puffer + Projekt-Dokument; TS liefert nur das Text-Layout flach mit und
|
||||
gibt die flache Zeichnung an fileio. `FlatDrawing`-Klasse und `dxfCadParts` (ausser `fontNameOf`) gelöscht.
|
||||
- Druck-SVG/Layout-Viewport (`plan_print_svg.rs`): Knoten als Anweisungsliste, TS legt sie als DOM an (Rahmen,
|
||||
Bild-`<pattern>`, Einzeltexte bleiben TS). Nicht auf `sceneToPrintSvg` umgestellt (Ausgabe bliebe nicht gleich) —
|
||||
nicht nötig, der Puffer-Weg ist gleich.
|
||||
Gleichheit (temporäre Paritätstests gegen die alten TS-Fassungen, danach entfernt): Rahmen-/Text-Treffer 53 870
|
||||
Abfragen (200 Zufallspläne, Beispiel EG/OG/UG, Überlagerung, bigSample(6)); DXF-Zeichnung Zahl für Zahl in 451 Fällen
|
||||
(Beispiel + Fachplaner-Projekt × Geschosse × Detailgrade × mono × Optionen, 300 Zufallspläne, bigSample(8)), DXF/
|
||||
Binär byte-gleich, CLI `dxf`/`dwg` (--binary, --scale, --dim-unit cm, --layout) 36 Dateien byte-gleich zur CLI des
|
||||
Hauptstands; Druck-SVG 475 Pläne gleich (DOM serialisiert). Bleibende Tests: `planLazy.test.ts` (Kern-Verbraucher
|
||||
lesen nicht), Marquee-/Text-Tests über den Kern, Rust-Tests für Rechteck-Treffer, Linientypen, Papier, blocklokal.
|
||||
Messung (Node, Linux-Container, `--no-opt`, Min/Median, alt und neu im selben Lauf): `generatePlan` Beispiel-EG
|
||||
0,38–0,42/0,43–0,65 → 0,30–0,33/0,35–0,40 ms; grosses Projekt (bigSampleProject 20×20) 228–241/285–294 →
|
||||
158–160/166–176 ms; mit Render-Szene (`planSceneBin`, WASM-Ansicht) 396–472 → 324–352 ms.
|
||||
Bleibt: der native macOS-Pfad (`useNativePlanRenderer`/`GpuChunkCache`) liest die Liste weiter (nicht in der Tauri-App
|
||||
geprüft); SVG-Rückfall ohne GPU, Geschoss-Überlagerung mit gedimmten Ebenen (`materializeGreyed`), Gruppen-Isolation,
|
||||
Schnitt/Ansicht-Overlays in `viewportContent` und Abzugskörper/Mono/Massstab lesen die Liste (dann wie bisher).
|
||||
Nachteile (bewusst): Übergang mit doppelter Datenhaltung, Format muss TS/Rust gleich bleiben
|
||||
(Versionsnummer + Hin-und-zurück-Tests), Text-Layout bleibt bis [K4] in TS.
|
||||
- ◐ **[K4] Modell und Ops in Rust** [2]; TS bekommt die Typen generiert (z. B. `ts-rs`). · XL
|
||||
@@ -241,6 +271,8 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
noch die dekodierten `Primitive[]`.
|
||||
Nachtrag 28.10.: render2d-Szene, Auswahl, Fang und SVG-Text-Export lesen den Puffer im Kern ([K3d]); Overlay/Texte, DXF und
|
||||
Layout-PDF noch über `Primitive[]`.
|
||||
Nachtrag 29.10.: auch Rahmen-Auswahl, Text-/Bild-Treffer, Overlay-Texte, DXF/DWG und Druck-SVG lesen den Puffer im
|
||||
Kern; `generatePlan` liest die Kern-Primitive nur noch bei Bedarf ([K3d]).
|
||||
- ◐ **S3 Änderungen kommen aus Rust**: Befehle (Zustandsautomaten, Werkzeuge) erzeugen Ops im Kern; Undo/Redo, Validierung
|
||||
(`validateOps`) und Gruppen/Ebenen-Logik wandern nach Rust; `diffToOps` entfällt, TS hält nur noch eine Leseansicht.
|
||||
**Erste Etappe (28.10.): Ops, Prüfung, Undo/Redo im Kern.** `core/src/ops.rs` (Op, Prüfung bitgleich zur TS-Fassung — gleiche
|
||||
|
||||
@@ -63,6 +63,8 @@ pub mod plan_scene;
|
||||
pub mod plan_pick;
|
||||
pub mod snap;
|
||||
pub mod plan_svg;
|
||||
pub mod plan_dxf;
|
||||
pub mod plan_print_svg;
|
||||
|
||||
#[cfg(feature = "web")]
|
||||
mod web;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -19,8 +19,9 @@
|
||||
|
||||
use crate::jsmath::hypot;
|
||||
use crate::jsnum;
|
||||
use crate::plan_buf::{whole, View, F_IDS, T_ARC, T_CIRCLE, T_DRAWING_ARC, T_LINE, T_POLYGON};
|
||||
use crate::plan_buf::{whole, View, F_IDS, T_ARC, T_CIRCLE, T_DRAWING_ARC, T_DRAWING_TEXT, T_IMAGE, T_LINE, T_POLYGON, T_TEXT_PATH};
|
||||
use crate::plan_parts::pick_ids;
|
||||
use std::cell::OnceCell;
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
@@ -294,6 +295,31 @@ pub struct PickIndex {
|
||||
/// (Art, Id) → Indizes aufsteigend.
|
||||
owners: HashMap<(u32, u32), Vec<u32>>,
|
||||
interned: HashMap<String, u32>,
|
||||
/// Einträge mit nicht-leerer `drawingId` (Linie, Polygon, Kreis, Bogen, Text, Textpfad, Bild):
|
||||
/// (Index, Typ, Id-Nummer) in Plan-Reihenfolge — Rahmen-Auswahl und Text-/Bild-Treffer.
|
||||
draw_items: Vec<(u32, u32, u32)>,
|
||||
/// Rahmen von `drawingText`/`drawingImage` mit `drawingId` (aus dem Text-JSON, bei Bedarf).
|
||||
text_boxes: OnceCell<Vec<TextBox>>,
|
||||
}
|
||||
|
||||
/// Rahmen eines Einzeltexts (wie die Einzelklick-Box in PlanView) bzw. eines Bilds.
|
||||
#[derive(Clone, Copy)]
|
||||
struct TextBox {
|
||||
gi: u32,
|
||||
image: bool,
|
||||
min_x: f64,
|
||||
min_y: f64,
|
||||
max_x: f64,
|
||||
max_y: f64,
|
||||
}
|
||||
|
||||
/// Achsenparalleles Rechteck (Modell-Meter) der Rahmen-Auswahl.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Rect {
|
||||
pub min_x: f64,
|
||||
pub min_y: f64,
|
||||
pub max_x: f64,
|
||||
pub max_y: f64,
|
||||
}
|
||||
|
||||
/// Bounding-Box, NaN ausgelassen (wie `f64::min`).
|
||||
@@ -328,6 +354,8 @@ impl PickIndex {
|
||||
ring_ix: BoxIndex::default(),
|
||||
owners: HashMap::new(),
|
||||
interned: HashMap::new(),
|
||||
draw_items: Vec::new(),
|
||||
text_boxes: OnceCell::new(),
|
||||
};
|
||||
// Segment-Raster wie `buildSegmentIndex` (Ausmass mit Math.min/max, NaN steckt an).
|
||||
let mut seg_boxes: Vec<(u32, f64, f64, f64, f64)> = Vec::new();
|
||||
@@ -394,6 +422,11 @@ impl PickIndex {
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(id) = drawing {
|
||||
if mask & (1 << 2) != 0 && matches!(tag, T_LINE | T_POLYGON | T_CIRCLE | T_DRAWING_ARC | T_DRAWING_TEXT | T_TEXT_PATH | T_IMAGE) {
|
||||
ix.draw_items.push((g, tag, id));
|
||||
}
|
||||
}
|
||||
let f = |k: usize| view.word(at + 4 + k);
|
||||
match tag {
|
||||
T_LINE => {
|
||||
@@ -676,6 +709,249 @@ impl PickIndex {
|
||||
hits.sort_unstable();
|
||||
hits
|
||||
}
|
||||
|
||||
/// Text-JSON eines Eintrags (Texte, Textpfade, Bilder); `None` ohne JSON oder kaputt.
|
||||
fn json(&self, gi: u32) -> Option<serde_json::Value> {
|
||||
let (v, i) = self.locate(gi)?;
|
||||
let si = v.word(v.rec_at(i)? + 4)?;
|
||||
serde_json::from_str(&v.string(whole(si)?)?).ok()
|
||||
}
|
||||
|
||||
/// Text-/Bild-Rahmen (einmal je Index, beim ersten Gebrauch aus dem JSON gelesen).
|
||||
fn boxes(&self) -> &[TextBox] {
|
||||
self.text_boxes.get_or_init(|| {
|
||||
let mut out = Vec::new();
|
||||
for &(gi, tag, _) in &self.draw_items {
|
||||
if tag != T_DRAWING_TEXT && tag != T_IMAGE {
|
||||
continue;
|
||||
}
|
||||
let Some(j) = self.json(gi) else { continue };
|
||||
let num = |o: &serde_json::Value, k: &str| o.get(k).and_then(|x| x.as_f64()).unwrap_or(f64::NAN);
|
||||
let pt = |k: &str| j.get(k).map_or((f64::NAN, f64::NAN), |o| (num(o, "x"), num(o, "y")));
|
||||
if tag == T_IMAGE {
|
||||
let (a, b) = pt("min");
|
||||
let (c, d) = pt("max");
|
||||
out.push(TextBox { gi, image: true, min_x: a, min_y: b, max_x: c, max_y: d });
|
||||
} else {
|
||||
let (ax, ay) = pt("at");
|
||||
let h = num(&j, "heightM");
|
||||
let len = j.get("text").and_then(|t| t.as_str()).map_or(0, |t| t.encode_utf16().count()) as f64;
|
||||
// `p.wrapWidth && p.wrapWidth > 0` (fehlend/0/NaN → keine Spalte).
|
||||
let wrap = j.get("wrapWidth").and_then(|x| x.as_f64()).filter(|w| *w > 0.0);
|
||||
let single_w = jsnum::max(1.0, len) * h * 0.6;
|
||||
let w = wrap.unwrap_or(single_w);
|
||||
let lines = match wrap {
|
||||
Some(ww) => jsnum::max(1.0, (single_w / ww).ceil()),
|
||||
None => 1.0,
|
||||
};
|
||||
let pad = h * 0.6;
|
||||
out.push(TextBox {
|
||||
gi,
|
||||
image: false,
|
||||
min_x: ax - pad,
|
||||
min_y: ay - lines * h * 1.25 - pad,
|
||||
max_x: ax + w + pad,
|
||||
max_y: ay + h * 0.4 + pad,
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
})
|
||||
}
|
||||
|
||||
/// Erster `drawingText` (mit `drawingId`) in Plan-Reihenfolge, dessen Rahmen `(x, y)` enthält
|
||||
/// (wie `pickDrawingText` in PlanView).
|
||||
pub fn drawing_text_at(&self, x: f64, y: f64) -> Option<u32> {
|
||||
self.boxes().iter().find(|b| !b.image && x >= b.min_x && x <= b.max_x && y >= b.min_y && y <= b.max_y).map(|b| b.gi)
|
||||
}
|
||||
|
||||
/// Oberstes (zuletzt gezeichnetes) Bild mit `drawingId`, das `(x, y)` enthält.
|
||||
pub fn drawing_image_at(&self, x: f64, y: f64) -> Option<u32> {
|
||||
self.boxes().iter().rev().find(|b| b.image && x >= b.min_x && x <= b.max_x && y >= b.min_y && y <= b.max_y).map(|b| b.gi)
|
||||
}
|
||||
|
||||
/// Typ des ersten Eintrags einer Zeichnung, der eine Form benennt (Linie, Polygon, Text,
|
||||
/// Textpfad, Kreis, Bogen, Bild — wie `drawingLabel`); `None` ohne solchen.
|
||||
pub fn drawing_kind(&self, id: &str) -> Option<u32> {
|
||||
let n = self.interned.get(id)?;
|
||||
for &gi in self.owners.get(&(2, *n))? {
|
||||
let (v, i) = self.locate(gi)?;
|
||||
let tag = whole(v.word(v.rec_at(i)?)?)? as u32;
|
||||
if matches!(tag, T_LINE | T_POLYGON | T_DRAWING_TEXT | T_TEXT_PATH | T_CIRCLE | T_DRAWING_ARC | T_IMAGE) {
|
||||
return Some(tag);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Rahmen-Auswahl über Polygone mit einer Id der Pick-Art `kind` (wie `marqueeHitByField`):
|
||||
/// `crossing` = ein Band berührt das Rechteck, sonst alle Bänder ganz darin. Ids in der
|
||||
/// Reihenfolge ihres ersten Auftretens.
|
||||
pub fn marquee_polygons(&self, kind: u32, rect: Rect, crossing: bool) -> Vec<String> {
|
||||
let mut order: Vec<(String, bool)> = Vec::new();
|
||||
let mut at: HashMap<String, usize> = HashMap::new();
|
||||
for p in &self.polys {
|
||||
let Some((v, i)) = self.locate(p.gi) else { continue };
|
||||
let Some(rec) = v.rec(i) else { continue };
|
||||
let Some(ids) = pick_ids(&v, &rec) else { continue };
|
||||
let Some(&(_, si)) = ids.iter().find(|e| e.0 == kind) else { continue };
|
||||
let Some(id) = whole(si).and_then(|k| v.string(k)) else { continue };
|
||||
let Some(pts) = self.polygon_pts(p.gi) else { continue };
|
||||
let hit = if crossing { poly_touches_rect(&pts, rect) } else { poly_enclosed_by_rect(&pts, rect) };
|
||||
match at.get(&id) {
|
||||
// crossing: irgendein Band; Fenster: alle Bänder.
|
||||
Some(&k) => order[k].1 = if crossing { order[k].1 || hit } else { order[k].1 && hit },
|
||||
None => {
|
||||
at.insert(id.clone(), order.len());
|
||||
order.push((id, hit));
|
||||
}
|
||||
}
|
||||
}
|
||||
order.into_iter().filter(|e| e.1).map(|e| e.0).collect()
|
||||
}
|
||||
|
||||
/// Rahmen-Auswahl über 2D-Zeichnungen (wie `marqueeHitDrawings`): je Zeichnung alle Punkte
|
||||
/// (Linien-Enden, Polygon-Ecken, abgetastete Kreise/Bögen, Text-/Bild-Rahmen); `skip` =
|
||||
/// Zeichnungen, die der Aufrufer selbst prüft. Ids in der Reihenfolge ihres ersten Auftretens.
|
||||
pub fn marquee_drawings(&self, rect: Rect, crossing: bool, skip: &[&str]) -> Vec<String> {
|
||||
let skip_n: Vec<u32> = skip.iter().filter_map(|s| self.interned.get(*s).copied()).collect();
|
||||
let names: HashMap<u32, &str> = self.interned.iter().map(|(k, v)| (*v, k.as_str())).collect();
|
||||
let boxes: HashMap<u32, TextBox> = if self.draw_items.iter().any(|e| e.1 == T_DRAWING_TEXT || e.1 == T_IMAGE) {
|
||||
self.boxes().iter().map(|b| (b.gi, *b)).collect()
|
||||
} else {
|
||||
HashMap::new()
|
||||
};
|
||||
let mut order: Vec<(u32, Vec<f64>)> = Vec::new();
|
||||
let mut at: HashMap<u32, usize> = HashMap::new();
|
||||
for &(gi, tag, id) in &self.draw_items {
|
||||
if skip_n.contains(&id) {
|
||||
continue;
|
||||
}
|
||||
let pts: Vec<f64> = match tag {
|
||||
T_LINE => match self.line(gi) {
|
||||
Some(l) => l.to_vec(),
|
||||
None => continue,
|
||||
},
|
||||
T_POLYGON => match self.polygon_pts(gi) {
|
||||
Some(p) => p,
|
||||
None => continue,
|
||||
},
|
||||
T_CIRCLE => match self.fields::<3>(gi, 4) {
|
||||
Some([cx, cy, r]) => ring_sample_points(cx, cy, r, None),
|
||||
None => continue,
|
||||
},
|
||||
T_DRAWING_ARC => match self.fields::<5>(gi, 3) {
|
||||
Some([cx, cy, r, a0, a1]) => ring_sample_points(cx, cy, r, Some((a0, a1))),
|
||||
None => continue,
|
||||
},
|
||||
// Bild: min, (max.x, min.y), max, (min.x, max.y) — Text: dieselbe Umlaufrichtung.
|
||||
T_DRAWING_TEXT | T_IMAGE => match boxes.get(&gi) {
|
||||
Some(b) => vec![b.min_x, b.min_y, b.max_x, b.min_y, b.max_x, b.max_y, b.min_x, b.max_y],
|
||||
None => continue,
|
||||
},
|
||||
_ => continue,
|
||||
};
|
||||
match at.get(&id) {
|
||||
Some(&k) => order[k].1.extend_from_slice(&pts),
|
||||
None => {
|
||||
at.insert(id, order.len());
|
||||
order.push((id, pts));
|
||||
}
|
||||
}
|
||||
}
|
||||
order
|
||||
.into_iter()
|
||||
.filter(|(_, pts)| if crossing { poly_touches_rect(pts, rect) } else { poly_enclosed_by_rect(pts, rect) })
|
||||
.filter_map(|(id, _)| names.get(&id).map(|s| s.to_string()))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Punkte auf einem Kreis-/Bogen-Ring (wie `ringSamplePoints`): Vollkreis 32 Schritte, Bogen
|
||||
/// anteilig (mindestens 4), Endpunkt inklusive.
|
||||
fn ring_sample_points(cx: f64, cy: f64, r: f64, arc: Option<(f64, f64)>) -> Vec<f64> {
|
||||
let tau = std::f64::consts::PI * 2.0;
|
||||
let (start, sweep, steps) = match arc {
|
||||
None => (0.0, tau, 32.0),
|
||||
Some((a0, a1)) => {
|
||||
let mut sw = (((a1 - a0) % tau) + tau) % tau;
|
||||
if sw == 0.0 || sw.is_nan() {
|
||||
sw = tau;
|
||||
}
|
||||
(a0, sw, jsnum::max(4.0, jsnum::round((sw / tau) * 32.0)))
|
||||
}
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0.0;
|
||||
while i <= steps {
|
||||
let a = start + (sweep * i) / steps;
|
||||
out.push(cx + r * jsnum::cos(a));
|
||||
out.push(cy + r * jsnum::sin(a));
|
||||
i += 1.0;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Alle Ecken im Rechteck (`polyEnclosedByRect`); leer → nein.
|
||||
fn poly_enclosed_by_rect(poly: &[f64], r: Rect) -> bool {
|
||||
if poly.len() < 2 {
|
||||
return false;
|
||||
}
|
||||
poly.chunks_exact(2).all(|p| p[0] >= r.min_x && p[0] <= r.max_x && p[1] >= r.min_y && p[1] <= r.max_y)
|
||||
}
|
||||
|
||||
/// Orientierung (b − a) × (c − a) (`cross3`).
|
||||
fn cross3(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)
|
||||
}
|
||||
|
||||
/// `onSegment` bei kollinearen Punkten.
|
||||
fn on_segment(a: (f64, f64), b: (f64, f64), p: (f64, f64)) -> bool {
|
||||
jsnum::min(a.0, b.0) <= p.0 && p.0 <= jsnum::max(a.0, b.0) && jsnum::min(a.1, b.1) <= p.1 && p.1 <= jsnum::max(a.1, b.1)
|
||||
}
|
||||
|
||||
/// `segmentsIntersect` (inkl. Berührung).
|
||||
fn segments_intersect(a: (f64, f64), b: (f64, f64), c: (f64, f64), d: (f64, f64)) -> bool {
|
||||
let d1 = cross3(c, d, a);
|
||||
let d2 = cross3(c, d, b);
|
||||
let d3 = cross3(a, b, c);
|
||||
let d4 = cross3(a, b, d);
|
||||
if ((d1 > 0.0 && d2 < 0.0) || (d1 < 0.0 && d2 > 0.0)) && ((d3 > 0.0 && d4 < 0.0) || (d3 < 0.0 && d4 > 0.0)) {
|
||||
return true;
|
||||
}
|
||||
(d1 == 0.0 && on_segment(c, d, a)) || (d2 == 0.0 && on_segment(c, d, b)) || (d3 == 0.0 && on_segment(a, b, c)) || (d4 == 0.0 && on_segment(a, b, d))
|
||||
}
|
||||
|
||||
/// Polygon und Rechteck berühren sich (`polyTouchesRect`): Ecke im Rechteck, Rechteck-Ecke im
|
||||
/// Polygon oder Kantenschnitt.
|
||||
fn poly_touches_rect(poly: &[f64], r: Rect) -> bool {
|
||||
for p in poly.chunks_exact(2) {
|
||||
if p[0] >= r.min_x && p[0] <= r.max_x && p[1] >= r.min_y && p[1] <= r.max_y {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
let corners = [(r.min_x, r.min_y), (r.max_x, r.min_y), (r.max_x, r.max_y), (r.min_x, r.max_y)];
|
||||
for c in corners {
|
||||
if point_in_polygon(c.0, c.1, poly) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
let n = poly.len() / 2;
|
||||
if n == 0 {
|
||||
return false;
|
||||
}
|
||||
let mut j = n - 1;
|
||||
for i in 0..n {
|
||||
let a = (poly[2 * j], poly[2 * j + 1]);
|
||||
let b = (poly[2 * i], poly[2 * i + 1]);
|
||||
for k in 0..4 {
|
||||
if segments_intersect(a, b, corners[k], corners[(k + 1) % 4]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
j = i;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -690,4 +966,28 @@ mod tests {
|
||||
assert_eq!(point_seg_dist(0.5, 1.0, 0.0, 0.0, 1.0, 0.0), 1.0);
|
||||
assert_eq!(point_seg_dist_px(3.0, 4.0, 0.0, 0.0, 0.0, 0.0), 5.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rechteck_beruehrt_und_umschliesst() {
|
||||
let r = Rect { min_x: 0.0, min_y: 0.0, max_x: 2.0, max_y: 2.0 };
|
||||
let inner = [0.5, 0.5, 1.5, 0.5, 1.5, 1.5];
|
||||
let around = [-1.0, -1.0, 3.0, -1.0, 3.0, 3.0, -1.0, 3.0];
|
||||
let crossing = [-1.0, 1.0, 3.0, 1.0];
|
||||
assert!(poly_enclosed_by_rect(&inner, r) && poly_touches_rect(&inner, r));
|
||||
// Rechteck ganz im Polygon: Ecke im Polygon.
|
||||
assert!(!poly_enclosed_by_rect(&around, r) && poly_touches_rect(&around, r));
|
||||
// Strecke quer durch: nur Kantenschnitt.
|
||||
assert!(poly_touches_rect(&crossing, r));
|
||||
assert!(!poly_touches_rect(&[5.0, 5.0, 6.0, 6.0], r));
|
||||
assert!(!poly_enclosed_by_rect(&[], r));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ring_abtastung_vollkreis_und_bogen() {
|
||||
assert_eq!(ring_sample_points(0.0, 0.0, 1.0, None).len(), 2 * 33);
|
||||
// Viertelbogen: 8 Schritte, Endpunkt inklusive.
|
||||
let q = ring_sample_points(0.0, 0.0, 2.0, Some((0.0, std::f64::consts::FRAC_PI_2)));
|
||||
assert_eq!(q.len(), 2 * 9);
|
||||
assert!(q.chunks_exact(2).all(|p| p[0] >= -1e-12 && p[1] >= -1e-12));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
//! Druck-SVG eines Plans für Layout-Viewports und den PDF-Altpfad ([K3d], früher der Primitiv-Teil
|
||||
//! von `src/export/planToPrintSvg.ts`): liest den zusammengesetzten Plan ([`crate::plan_parts`]) und
|
||||
//! liefert die SVG-Knoten in Papier-Millimetern als flache Anweisungsliste, die TS 1:1 als DOM-Knoten
|
||||
//! anlegt (gleiche Elemente, Attribute und Reihenfolge wie die TS-Fassung — die Zahlen formatiert wie
|
||||
//! `String(Math.round(v * 1000) / 1000)`). Schraffuren als geklippte Vektorlinien, Zickzack/Motiv als
|
||||
//! Polylinie, Bögen als `<path>`.
|
||||
//!
|
||||
//! In TS bleiben: der `<svg>`-Rahmen und das weisse Blatt, die Bild-Schraffur-`<pattern>` (laufende
|
||||
//! Ids im Dokument) und die Einzeltexte (Text-Layout `wrapDocToLines`). Dafür stehen Anweisungen in
|
||||
//! der Liste.
|
||||
//!
|
||||
//! Format: Datensätze getrennt durch `\x1e`, Felder durch `\x1f`:
|
||||
//! - `E`, Ebene (0 = ins `<svg>`, 1 = in die offene Gruppe), Tag, dann Name/Wert-Paare;
|
||||
//! - `G`, Deckkraft (leer = keine) — öffnet eine `<g>`; `g` schliesst sie (hängt sie ans `<svg>`);
|
||||
//! - `I`, Punkte-Attribut, Bild-JSON — Bild-Schraffur: `<pattern>` anlegen und ein Polygon damit füllen;
|
||||
//! - `T`, Plan-Index, Deckkraft — Einzeltext an dieser Stelle.
|
||||
|
||||
use crate::hatch::{self, Hatch, Motif, Pattern, V2};
|
||||
use crate::js_fmt::js_number;
|
||||
use crate::jsnum;
|
||||
use crate::plan_buf::{whole, Rec, View, F_COLOR, F_DASH_NULL, F_OPACITY, T_ARC, T_CIRCLE, T_DRAWING_ARC, T_DRAWING_TEXT, T_IMAGE, T_LINE, T_POLYGON};
|
||||
use crate::plan_parts::{greyed_of, Part};
|
||||
use std::f64::consts::PI;
|
||||
|
||||
/// Optionen: Massstab-Nenner, Blatt (mm) und Ausmass des Plans (`Plan.bounds`).
|
||||
pub struct PrintOptions {
|
||||
pub scale_denominator: f64,
|
||||
pub page_w: f64,
|
||||
pub page_h: f64,
|
||||
pub bounds: [f64; 4],
|
||||
}
|
||||
|
||||
/// Standard-Stift-Stufen (mm).
|
||||
const PEN_STEPS: [f64; 7] = [0.13, 0.18, 0.25, 0.35, 0.5, 0.7, 1.0];
|
||||
const MIN_PEN_MM: f64 = 0.13;
|
||||
|
||||
/// Mm-Strichstärke auf die nächste Stift-Stufe (`quantizePen`).
|
||||
fn quantize_pen(mm: f64) -> f64 {
|
||||
let w = jsnum::max(MIN_PEN_MM, mm);
|
||||
for s in PEN_STEPS {
|
||||
if w <= s + 1e-6 {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
PEN_STEPS[PEN_STEPS.len() - 1]
|
||||
}
|
||||
|
||||
/// `String(Math.round(v * 1000) / 1000)`.
|
||||
fn r3(v: f64) -> String {
|
||||
js_number(jsnum::round(v * 1000.0) / 1000.0)
|
||||
}
|
||||
|
||||
/// Strichmuster als Attribut (`dash.map(round).join(" ")`).
|
||||
fn dash_attr(d: &[f64]) -> String {
|
||||
d.iter().map(|v| r3(*v)).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// Anweisungsliste.
|
||||
struct Out {
|
||||
s: String,
|
||||
first: bool,
|
||||
}
|
||||
|
||||
impl Out {
|
||||
fn rec(&mut self, fields: &[&str]) {
|
||||
if !self.first {
|
||||
self.s.push('\u{1e}');
|
||||
}
|
||||
self.first = false;
|
||||
self.s.push_str(&fields.join("\u{1f}"));
|
||||
}
|
||||
|
||||
fn el(&mut self, depth: u8, tag: &str, attrs: &[(&str, String)]) {
|
||||
let d = depth.to_string();
|
||||
let mut f: Vec<&str> = vec!["E", &d, tag];
|
||||
for (k, v) in attrs {
|
||||
f.push(k);
|
||||
f.push(v);
|
||||
}
|
||||
self.rec(&f);
|
||||
}
|
||||
}
|
||||
|
||||
/// Papier-Abbildung (Welt-Meter → mm, Y gespiegelt, zentriert).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Map {
|
||||
off_x: f64,
|
||||
off_y: f64,
|
||||
min_x: f64,
|
||||
max_y: f64,
|
||||
k: f64,
|
||||
}
|
||||
|
||||
impl Map {
|
||||
fn at(&self, x: f64, y: f64) -> V2 {
|
||||
V2 { x: self.off_x + (x - self.min_x) * self.k, y: self.off_y + (self.max_y - y) * self.k }
|
||||
}
|
||||
}
|
||||
|
||||
fn pts_attr(p: &[V2]) -> String {
|
||||
p.iter().map(|q| format!("{},{}", r3(q.x), r3(q.y))).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
fn poly_node(pts: &str, fill: &str, stroke: &str, stroke_mm: f64) -> Vec<(&'static str, String)> {
|
||||
let mut a = vec![("points", pts.to_string()), ("fill", fill.to_string())];
|
||||
if stroke != "none" && stroke_mm > 0.0 {
|
||||
a.push(("stroke", stroke.to_string()));
|
||||
a.push(("stroke-width", js_number(stroke_mm)));
|
||||
a.push(("stroke-linejoin", "round".to_string()));
|
||||
} else {
|
||||
a.push(("stroke", "none".to_string()));
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
fn line_attrs(a: V2, b: V2, color: &str, stroke_mm: f64, dash: Option<&[f64]>) -> Vec<(&'static str, String)> {
|
||||
let mut v = vec![
|
||||
("x1", r3(a.x)),
|
||||
("y1", r3(a.y)),
|
||||
("x2", r3(b.x)),
|
||||
("y2", r3(b.y)),
|
||||
("stroke", color.to_string()),
|
||||
("stroke-width", js_number(stroke_mm)),
|
||||
("stroke-linecap", "round".to_string()),
|
||||
];
|
||||
if let Some(d) = dash.filter(|d| !d.is_empty()) {
|
||||
v.push(("stroke-dasharray", dash_attr(d)));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn polyline_attrs(pts: &[V2], color: &str, stroke_mm: f64, dash: Option<&[f64]>) -> Vec<(&'static str, String)> {
|
||||
let mut v = vec![
|
||||
("points", pts_attr(pts)),
|
||||
("fill", "none".to_string()),
|
||||
("stroke", color.to_string()),
|
||||
("stroke-width", js_number(stroke_mm)),
|
||||
("stroke-linecap", "round".to_string()),
|
||||
("stroke-linejoin", "round".to_string()),
|
||||
];
|
||||
if let Some(d) = dash.filter(|d| !d.is_empty()) {
|
||||
v.push(("stroke-dasharray", dash_attr(d)));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Strichmuster + runde Kappe bei Punkten (Bögen, Kreise).
|
||||
fn push_dash(v: &mut Vec<(&'static str, String)>, dash: Option<&[f64]>) {
|
||||
if let Some(d) = dash.filter(|d| !d.is_empty()) {
|
||||
v.push(("stroke-dasharray", dash_attr(d)));
|
||||
if d.iter().any(|x| *x == 0.0) {
|
||||
v.push(("stroke-linecap", "round".to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parallele Linien im Winkel/Abstand, aufs Polygon geklippt (`fillParallel`).
|
||||
fn fill_parallel(poly: &[V2], angle: f64, spacing: f64, out: &mut Vec<(V2, V2)>) {
|
||||
if poly.len() < 3 || spacing <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let dir = V2 { x: jsnum::cos(angle), y: jsnum::sin(angle) };
|
||||
let nrm = V2 { x: -dir.y, y: dir.x };
|
||||
let mut t_min = f64::INFINITY;
|
||||
let mut t_max = f64::NEG_INFINITY;
|
||||
for p in poly {
|
||||
let t = p.x * nrm.x + p.y * nrm.y;
|
||||
if t < t_min {
|
||||
t_min = t;
|
||||
}
|
||||
if t > t_max {
|
||||
t_max = t;
|
||||
}
|
||||
}
|
||||
let mut t = (t_min / spacing).ceil() * spacing;
|
||||
while t <= t_max {
|
||||
let mut xs: Vec<f64> = Vec::new();
|
||||
let n = poly.len();
|
||||
let mut j = n - 1;
|
||||
for i in 0..n {
|
||||
let a = poly[j];
|
||||
let b = poly[i];
|
||||
j = i;
|
||||
let ta = a.x * nrm.x + a.y * nrm.y;
|
||||
let tb = b.x * nrm.x + b.y * nrm.y;
|
||||
if ta == tb {
|
||||
continue;
|
||||
}
|
||||
let f = (t - ta) / (tb - ta);
|
||||
if f < 0.0 || f > 1.0 {
|
||||
continue;
|
||||
}
|
||||
let px = a.x + (b.x - a.x) * f;
|
||||
let py = a.y + (b.y - a.y) * f;
|
||||
xs.push(px * dir.x + py * dir.y);
|
||||
}
|
||||
if xs.len() >= 2 {
|
||||
// `xs.sort((u, v) => u - v)`: stabil; NaN zählt als gleich.
|
||||
xs.sort_by(|u, v| (u - v).partial_cmp(&0.0).unwrap_or(std::cmp::Ordering::Equal));
|
||||
let mut k = 0;
|
||||
while k + 1 < xs.len() {
|
||||
let (u0, u1) = (xs[k], xs[k + 1]);
|
||||
k += 2;
|
||||
if u1 - u0 < 1e-6 {
|
||||
continue;
|
||||
}
|
||||
out.push((V2 { x: nrm.x * t + dir.x * u0, y: nrm.y * t + dir.y * u0 }, V2 { x: nrm.x * t + dir.x * u1, y: nrm.y * t + dir.y * u1 }));
|
||||
}
|
||||
}
|
||||
t += spacing;
|
||||
}
|
||||
}
|
||||
|
||||
/// Schraffurlinien in Papier-mm (`hatchLines`).
|
||||
fn hatch_lines(poly_mm: &[V2], h: &Hatch, mm_per_m: f64) -> Vec<(V2, V2)> {
|
||||
let unit_mm = (1.0 / 90.0) * mm_per_m;
|
||||
let tile_mm = (if h.pattern == Pattern::Insulation { 10.0 } else { 8.0 }) * h.scale * unit_mm;
|
||||
let spacing = jsnum::max(0.5, tile_mm);
|
||||
let angle = (h.angle * PI) / 180.0;
|
||||
let mut segs = Vec::new();
|
||||
fill_parallel(poly_mm, angle, spacing, &mut segs);
|
||||
if h.pattern == Pattern::Crosshatch {
|
||||
fill_parallel(poly_mm, angle + PI / 2.0, spacing, &mut segs);
|
||||
}
|
||||
if h.pattern == Pattern::Insulation {
|
||||
fill_parallel(poly_mm, angle - PI / 4.0, spacing, &mut segs);
|
||||
}
|
||||
segs
|
||||
}
|
||||
|
||||
fn num(o: &serde_json::Value, k: &str) -> f64 {
|
||||
o.get(k).and_then(|x| x.as_f64()).unwrap_or(f64::NAN)
|
||||
}
|
||||
|
||||
/// Deckkraft-Attribut (`dim · max(0, objOpacity)`, nur unter 1).
|
||||
fn opacity_of(greyed: bool, obj: f64) -> String {
|
||||
let combined = (if greyed { 0.3 } else { 1.0 }) * jsnum::max(0.0, obj);
|
||||
if combined < 1.0 {
|
||||
js_number(combined)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Ein Eintrag als Knoten.
|
||||
fn entry(out: &mut Out, view: &View, i: usize, gi: usize, hatches: &[(i32, Hatch, i32)], m: Map) -> Option<()> {
|
||||
let rec: Rec = view.rec(i)?;
|
||||
let f = &rec.f;
|
||||
let k = m.k;
|
||||
let s = |idx: f64| -> Option<String> {
|
||||
if idx == -1.0 {
|
||||
Some("undefined".to_string())
|
||||
} else {
|
||||
view.string(whole(idx)?)
|
||||
}
|
||||
};
|
||||
let dash = |rec: &Rec| -> Option<Option<Vec<f64>>> {
|
||||
if rec.flags & F_DASH_NULL != 0 {
|
||||
return Some(None);
|
||||
}
|
||||
match rec.dash {
|
||||
Some((o, n)) => Some(Some(view.pool(o, n)?)),
|
||||
None => Some(None),
|
||||
}
|
||||
};
|
||||
let greyed = greyed_of(&rec, false) == Some(true);
|
||||
let obj = |at: usize| if rec.flags & F_OPACITY != 0 { f[at] } else { 1.0 };
|
||||
match rec.tag {
|
||||
T_POLYGON => {
|
||||
let pts: Vec<V2> = view.pool(whole(f[5])?, whole(f[6])?.checked_mul(2)?)?.chunks_exact(2).map(|c| V2 { x: c[0], y: c[1] }).collect();
|
||||
let opacity = opacity_of(greyed, obj(4));
|
||||
let pts_mm: Vec<V2> = pts.iter().map(|p| m.at(p.x, p.y)).collect();
|
||||
let attr = pts_attr(&pts_mm);
|
||||
let sw = f[2];
|
||||
let stroke_mm = if sw > 0.0 { quantize_pen(sw) } else { 0.0 };
|
||||
let fill = s(f[0])?;
|
||||
let stroke = s(f[1])?;
|
||||
out.rec(&["G", &opacity]);
|
||||
// Ohne Schraffur-Eintrag wie „none“.
|
||||
let (json, h, color) = if f[3] >= 0.0 { hatches.get(whole(f[3])?)?.clone() } else { (-1, empty_hatch(), -1) };
|
||||
let image: Option<String> = if h.kind == hatch::HatchKind::Image && json >= 0 {
|
||||
let j: serde_json::Value = serde_json::from_str(&view.string(json as usize)?).ok()?;
|
||||
j.get("image").filter(|v| v.is_object()).map(|v| v.to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let hatch_color = if color >= 0 { view.string(color as usize)? } else { "undefined".to_string() };
|
||||
if let Some(img) = image {
|
||||
if fill != "none" {
|
||||
out.el(1, "polygon", &poly_node(&attr, &fill, "none", 0.0));
|
||||
}
|
||||
out.rec(&["I", &attr, &img]);
|
||||
if stroke_mm > 0.0 {
|
||||
out.el(1, "polygon", &poly_node(&attr, "none", &stroke, stroke_mm));
|
||||
}
|
||||
} else if h.pattern == Pattern::None {
|
||||
out.el(1, "polygon", &poly_node(&attr, &fill, &stroke, stroke_mm));
|
||||
} else if h.pattern == Pattern::Solid {
|
||||
out.el(1, "polygon", &poly_node(&attr, &hatch_color, &stroke, stroke_mm));
|
||||
} else {
|
||||
if fill != "none" {
|
||||
out.el(1, "polygon", &poly_node(&attr, &fill, "none", 0.0));
|
||||
}
|
||||
let pen = quantize_pen(h.line_weight);
|
||||
if h.random {
|
||||
for run in hatch::build_random_hatch_runs(&pts, &h, None) {
|
||||
if run.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let (a, b) = (run[0], run[run.len() - 1]);
|
||||
out.el(1, "line", &line_attrs(m.at(a.x, a.y), m.at(b.x, b.y), &hatch_color, pen, None));
|
||||
}
|
||||
} else {
|
||||
// Strichmuster der Schraffur (null und [] gleich: keins).
|
||||
for (a, b) in hatch_lines(&pts_mm, &h, k) {
|
||||
out.el(1, "line", &line_attrs(a, b, &hatch_color, pen, Some(&h.dash)));
|
||||
}
|
||||
}
|
||||
if stroke_mm > 0.0 {
|
||||
out.el(1, "polygon", &poly_node(&attr, "none", &stroke, stroke_mm));
|
||||
}
|
||||
}
|
||||
out.rec(&["g"]);
|
||||
}
|
||||
T_LINE => {
|
||||
let a = m.at(f[4], f[5]);
|
||||
let b = m.at(f[6], f[7]);
|
||||
let color = if rec.flags & F_COLOR != 0 { s(f[1])? } else { "#111111".to_string() };
|
||||
let pen = quantize_pen(f[2]);
|
||||
let d = dash(&rec)?;
|
||||
let mut attrs = if let Some((amp, wav)) = rec.zigzag {
|
||||
let p = hatch::zigzag_points(a, b, amp, wav).unwrap_or_else(|| vec![a, b]);
|
||||
polyline_attrs(&p, &color, pen, d.as_deref())
|
||||
} else if let Some((length, o, n)) = rec.motif {
|
||||
let pts: Vec<V2> = view.pool(o, n.checked_mul(2)?)?.chunks_exact(2).map(|c| V2 { x: c[0], y: c[1] }).collect();
|
||||
let p = hatch::motif_points_opt(a, b, &Motif { points: pts, length }, 1.0).unwrap_or_else(|| vec![a, b]);
|
||||
polyline_attrs(&p, &color, pen, d.as_deref())
|
||||
} else {
|
||||
line_attrs(a, b, &color, pen, d.as_deref())
|
||||
};
|
||||
let tag = if rec.zigzag.is_some() || rec.motif.is_some() { "polyline" } else { "line" };
|
||||
let o = opacity_of(greyed, obj(3));
|
||||
if !o.is_empty() {
|
||||
attrs.push(("opacity", o));
|
||||
}
|
||||
out.el(0, tag, &attrs);
|
||||
}
|
||||
T_ARC => {
|
||||
let c = m.at(f[4], f[5]);
|
||||
let from = m.at(f[6], f[7]);
|
||||
let to = m.at(f[8], f[9]);
|
||||
let r = f[10] * k;
|
||||
let cross = (from.x - c.x) * (to.y - c.y) - (from.y - c.y) * (to.x - c.x);
|
||||
let sweep = if cross > 0.0 { 1 } else { 0 };
|
||||
let d = format!("M {} {} A {} {} 0 0 {} {} {}", r3(from.x), r3(from.y), r3(r), r3(r), sweep, r3(to.x), r3(to.y));
|
||||
let mut attrs = vec![("d", d), ("fill", "none".to_string()), ("stroke", "#111111".to_string()), ("stroke-width", js_number(quantize_pen(f[2])))];
|
||||
push_dash(&mut attrs, dash(&rec)?.as_deref());
|
||||
let o = opacity_of(greyed, obj(3));
|
||||
if !o.is_empty() {
|
||||
attrs.push(("opacity", o));
|
||||
}
|
||||
out.el(0, "path", &attrs);
|
||||
}
|
||||
T_CIRCLE => {
|
||||
let c = m.at(f[4], f[5]);
|
||||
let fill = s(f[0])?;
|
||||
let mut attrs = vec![
|
||||
("cx", r3(c.x)),
|
||||
("cy", r3(c.y)),
|
||||
("r", r3(f[6] * k)),
|
||||
("fill", if !fill.is_empty() && fill != "none" { fill } else { "none".to_string() }),
|
||||
("stroke", s(f[1])?),
|
||||
("stroke-width", js_number(quantize_pen(f[2]))),
|
||||
];
|
||||
push_dash(&mut attrs, dash(&rec)?.as_deref());
|
||||
let o = opacity_of(greyed, obj(3));
|
||||
if !o.is_empty() {
|
||||
attrs.push(("opacity", o));
|
||||
}
|
||||
out.el(0, "circle", &attrs);
|
||||
}
|
||||
T_DRAWING_ARC => {
|
||||
let tau = PI * 2.0;
|
||||
let (cx, cy, r, a0, a1) = (f[3], f[4], f[5], f[6], f[7]);
|
||||
let from = m.at(cx + r * jsnum::cos(a0), cy + r * jsnum::sin(a0));
|
||||
let to = m.at(cx + r * jsnum::cos(a1), cy + r * jsnum::sin(a1));
|
||||
let rr = r * k;
|
||||
let sweep = (((a1 - a0) % tau) + tau) % tau;
|
||||
let large = if sweep > PI { 1 } else { 0 };
|
||||
let d = format!("M {} {} A {} {} 0 {} 1 {} {}", r3(from.x), r3(from.y), r3(rr), r3(rr), large, r3(to.x), r3(to.y));
|
||||
let mut attrs = vec![("d", d), ("fill", "none".to_string()), ("stroke", s(f[0])?), ("stroke-width", js_number(quantize_pen(f[1])))];
|
||||
push_dash(&mut attrs, dash(&rec)?.as_deref());
|
||||
let o = opacity_of(greyed, obj(2));
|
||||
if !o.is_empty() {
|
||||
attrs.push(("opacity", o));
|
||||
}
|
||||
out.el(0, "path", &attrs);
|
||||
}
|
||||
T_DRAWING_TEXT | T_IMAGE => {
|
||||
let j: serde_json::Value = serde_json::from_str(&view.string(whole(f[0])?)?).ok()?;
|
||||
let jg = j.get("greyed").and_then(|g| g.as_bool()).unwrap_or(false);
|
||||
if rec.tag == T_DRAWING_TEXT {
|
||||
let obj = j.get("opacity").and_then(|o| o.as_f64()).unwrap_or(1.0);
|
||||
out.rec(&["T", &gi.to_string(), &opacity_of(jg, obj)]);
|
||||
} else {
|
||||
let (min, max) = (j.get("min")?, j.get("max")?);
|
||||
let (x0, y0, x1, y1) = (num(min, "x"), num(min, "y"), num(max, "x"), num(max, "y"));
|
||||
let w = (x1 - x0) * k;
|
||||
let h = (y1 - y0) * k;
|
||||
if w <= 0.0 || h <= 0.0 {
|
||||
return Some(());
|
||||
}
|
||||
let tl = m.at(x0, y1);
|
||||
let mut attrs = vec![
|
||||
("href", j.get("src").and_then(|v| v.as_str()).unwrap_or("undefined").to_string()),
|
||||
("x", r3(tl.x)),
|
||||
("y", r3(tl.y)),
|
||||
("width", r3(w)),
|
||||
("height", r3(h)),
|
||||
("preserveAspectRatio", "none".to_string()),
|
||||
];
|
||||
// Bilder: eigene Deckkraft getrennt (gedimmt × 0.45), sonst nur das Dimmen.
|
||||
let op = num(&j, "opacity");
|
||||
if op < 1.0 {
|
||||
attrs.push(("opacity", js_number(op * if jg { 0.45 } else { 1.0 })));
|
||||
} else {
|
||||
let o = opacity_of(jg, 1.0);
|
||||
if !o.is_empty() {
|
||||
attrs.push(("opacity", o));
|
||||
}
|
||||
}
|
||||
out.el(0, "image", &attrs);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn empty_hatch() -> Hatch {
|
||||
Hatch {
|
||||
pattern: Pattern::None,
|
||||
kind: hatch::HatchKind::Vector,
|
||||
random: false,
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
line_weight: 0.0,
|
||||
origin: None,
|
||||
seed: None,
|
||||
density: None,
|
||||
length_min: None,
|
||||
length_max: None,
|
||||
dash: Vec::new(),
|
||||
motif: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Anweisungsliste des Druck-SVG (Format s. Modulkopf); `None` bei kaputtem Puffer.
|
||||
pub fn print_svg_ops(parts: &mut [Part], o: &PrintOptions) -> Option<String> {
|
||||
let k = 1000.0 / o.scale_denominator;
|
||||
let [min_x, min_y, max_x, max_y] = o.bounds;
|
||||
let content_w = (max_x - min_x) * k;
|
||||
let content_h = (max_y - min_y) * k;
|
||||
let m = Map { off_x: (o.page_w - content_w) / 2.0, off_y: (o.page_h - content_h) / 2.0, min_x, max_y, k };
|
||||
let mut out = Out { s: String::new(), first: true };
|
||||
let mut gi = 0usize;
|
||||
for part in parts.iter_mut() {
|
||||
let hatches = part.view.hatch_table()?;
|
||||
for i in part.from..part.to {
|
||||
entry(&mut out, &part.view, i, gi, &hatches, m)?;
|
||||
gi += 1;
|
||||
}
|
||||
}
|
||||
Some(out.s)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stift_stufen_und_runden() {
|
||||
assert_eq!(quantize_pen(0.0), 0.13);
|
||||
assert_eq!(quantize_pen(0.2), 0.25);
|
||||
assert_eq!(quantize_pen(3.0), 1.0);
|
||||
assert_eq!(r3(1.23456), "1.235");
|
||||
assert_eq!(r3(-0.0001), "0");
|
||||
assert_eq!(dash_attr(&[2.0, 0.5]), "2 0.5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schraffur_parallel_geklippt() {
|
||||
let sq = [V2 { x: 0.0, y: 0.0 }, V2 { x: 10.0, y: 0.0 }, V2 { x: 10.0, y: 10.0 }, V2 { x: 0.0, y: 10.0 }];
|
||||
let mut segs = Vec::new();
|
||||
fill_parallel(&sq, 0.0, 2.0, &mut segs);
|
||||
// Waagrechte Linien bei y = 0, 2, …, 10 über die volle Breite.
|
||||
assert_eq!(segs.len(), 6);
|
||||
assert!(segs.iter().all(|(a, b)| (b.x - a.x - 10.0).abs() < 1e-9 || (a.x - b.x - 10.0).abs() < 1e-9));
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ thread_local! {
|
||||
static DOCS: RefCell<Vec<Option<Document>>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
fn with_doc<R>(h: u32, f: impl FnOnce(&mut Document) -> R) -> Option<R> {
|
||||
pub(crate) fn with_doc<R>(h: u32, f: impl FnOnce(&mut Document) -> R) -> Option<R> {
|
||||
DOCS.with(|d| d.borrow_mut().get_mut((h as usize).checked_sub(1)?)?.as_mut().map(f))
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,8 @@ mod plan_scene;
|
||||
mod plan_pick;
|
||||
mod snap;
|
||||
mod plan_svg;
|
||||
mod plan_dxf;
|
||||
mod plan_print_svg;
|
||||
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
//! Bindung des DXF-Sammlers (`crate::plan_dxf`) auf gehaltenen Plan-Puffern (Abschnitte wie
|
||||
//! `plan_parts`) und dem Projekt-Dokument. Leeres Ergebnis = Puffer fehlt (TS legt neu ab und
|
||||
//! fragt nochmals), Dokument nicht offen/unpassend oder kaputte Eingabe — nie Panic.
|
||||
|
||||
use crate::plan_dxf::{collect, encode, texts_from, DxfOptions};
|
||||
use crate::plan_parts::parts_from;
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
/// Flache Zeichnung (Format `plan_dxf::encode`). `opts` = `[Massstab, Schraffuren 0/1, cm 0/1,
|
||||
/// Papierbereich 0/1, minX, minY, maxX, maxY]`; `text_nums`/`text_strs` = Text-Eingabe
|
||||
/// (`plan_dxf::texts_from`, Texte je mit `\0` davor); `default_font` = Standard-Schrift.
|
||||
#[wasm_bindgen]
|
||||
pub fn plan_dxf_flat(doc: u32, segs: &[f64], text_nums: &[f64], text_strs: &str, opts: &[f64], default_font: &str) -> Vec<u8> {
|
||||
let Ok([scale, hatches, cm, layout, min_x, min_y, max_x, max_y]) = <[f64; 8]>::try_from(opts) else { return Vec::new() };
|
||||
if !(scale.is_finite() && scale > 0.0) {
|
||||
return Vec::new();
|
||||
}
|
||||
let strs: Vec<&str> = text_strs.split('\0').skip(1).collect();
|
||||
let Some(texts) = texts_from(text_nums, &strs) else { return Vec::new() };
|
||||
let Some(held) = super::plan_buf::held_for_segs(segs) else { return Vec::new() };
|
||||
let Some(mut parts) = parts_from(segs, |nr| held.iter().find(|e| e.0 == nr).map(|e| &*e.1)) else { return Vec::new() };
|
||||
let o = DxfOptions {
|
||||
scale,
|
||||
include_hatches: hatches != 0.0,
|
||||
dim_cm: cm != 0.0,
|
||||
paper_layout: layout != 0.0,
|
||||
bounds: [min_x, min_y, max_x, max_y],
|
||||
default_font: default_font.to_string(),
|
||||
};
|
||||
super::document::with_doc(doc, |d| {
|
||||
let p = d.project().ok()?;
|
||||
collect(&mut parts, &texts, p, &o).map(|f| encode(&f))
|
||||
})
|
||||
.flatten()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
//! (`pick_index_release`); er hält seine Puffer selbst, Verdrängen im Puffer-Speicher stört ihn
|
||||
//! nicht. Unbekannter Index oder kaputte Eingabe → leeres Ergebnis bzw. −1, nie Panic.
|
||||
|
||||
use crate::plan_pick::{ClientMap, PickIndex};
|
||||
use crate::plan_pick::{ClientMap, PickIndex, Rect};
|
||||
use std::cell::RefCell;
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
@@ -74,3 +74,43 @@ pub fn pick_owned_by(id: u32, kind: u32, ids: &str) -> Vec<u32> {
|
||||
let list: Vec<&str> = ids.split('\0').skip(1).collect();
|
||||
with(id, |ix| ix.owned_by(kind, &list)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Erster Einzeltext (`drawingText` mit `drawingId`) unter dem Punkt oder −1.
|
||||
#[wasm_bindgen]
|
||||
pub fn pick_drawing_text(id: u32, x: f64, y: f64) -> f64 {
|
||||
with(id, |ix| ix.drawing_text_at(x, y)).flatten().map_or(-1.0, |i| i as f64)
|
||||
}
|
||||
|
||||
/// Oberstes Bild (`drawingImage` mit `drawingId`) unter dem Punkt oder −1.
|
||||
#[wasm_bindgen]
|
||||
pub fn pick_drawing_image(id: u32, x: f64, y: f64) -> f64 {
|
||||
with(id, |ix| ix.drawing_image_at(x, y)).flatten().map_or(-1.0, |i| i as f64)
|
||||
}
|
||||
|
||||
/// Typ-Kennung des ersten formgebenden Eintrags der Zeichnung `drawing` oder 0.
|
||||
#[wasm_bindgen]
|
||||
pub fn pick_drawing_kind(id: u32, drawing: &str) -> u32 {
|
||||
with(id, |ix| ix.drawing_kind(drawing)).flatten().unwrap_or(0)
|
||||
}
|
||||
|
||||
fn rect_of(r: &[f64]) -> Option<Rect> {
|
||||
let [min_x, min_y, max_x, max_y] = <[f64; 4]>::try_from(r).ok()?;
|
||||
Some(Rect { min_x, min_y, max_x, max_y })
|
||||
}
|
||||
|
||||
/// Rahmen-Auswahl über Polygone der Pick-Art `kind` (`rect` = `[minX, minY, maxX, maxY]`):
|
||||
/// Ids, jede mit `\0` davor.
|
||||
#[wasm_bindgen]
|
||||
pub fn pick_marquee_polygons(id: u32, kind: u32, rect: &[f64], crossing: bool) -> String {
|
||||
let Some(r) = rect_of(rect) else { return String::new() };
|
||||
with(id, |ix| ix.marquee_polygons(kind, r, crossing)).unwrap_or_default().iter().map(|s| format!("\0{s}")).collect()
|
||||
}
|
||||
|
||||
/// Rahmen-Auswahl über 2D-Zeichnungen; `skip` = Ids (jede mit `\0` davor), die der Aufrufer
|
||||
/// selbst prüft. Ergebnis wie [`pick_marquee_polygons`].
|
||||
#[wasm_bindgen]
|
||||
pub fn pick_marquee_drawings(id: u32, rect: &[f64], crossing: bool, skip: &str) -> String {
|
||||
let Some(r) = rect_of(rect) else { return String::new() };
|
||||
let skip: Vec<&str> = skip.split('\0').skip(1).collect();
|
||||
with(id, |ix| ix.marquee_drawings(r, crossing, &skip)).unwrap_or_default().iter().map(|s| format!("\0{s}")).collect()
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Bindung des Druck-SVG (`crate::plan_print_svg`) auf gehaltenen Plan-Puffern (Abschnitte wie
|
||||
//! `plan_parts`). Ergebnis `"1"` + Anweisungsliste; leer = Puffer fehlt (TS legt neu ab und fragt
|
||||
//! nochmals) oder kaputte Eingabe — nie Panic.
|
||||
|
||||
use crate::plan_parts::parts_from;
|
||||
use crate::plan_print_svg::{print_svg_ops, PrintOptions};
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
/// `opts` = `[Massstab-Nenner, Blattbreite mm, Blatthöhe mm, minX, minY, maxX, maxY]`.
|
||||
#[wasm_bindgen]
|
||||
pub fn plan_print_svg_ops(segs: &[f64], opts: &[f64]) -> String {
|
||||
let Ok([n, w, h, min_x, min_y, max_x, max_y]) = <[f64; 7]>::try_from(opts) else { return String::new() };
|
||||
let Some(held) = super::plan_buf::held_for_segs(segs) else { return String::new() };
|
||||
let Some(mut parts) = parts_from(segs, |nr| held.iter().find(|e| e.0 == nr).map(|e| &*e.1)) else { return String::new() };
|
||||
let o = PrintOptions { scale_denominator: n, page_w: w, page_h: h, bounds: [min_x, min_y, max_x, max_y] };
|
||||
match print_svg_ops(&mut parts, &o) {
|
||||
Some(s) => format!("1{s}"),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
+8
-5
@@ -263,11 +263,6 @@ export {
|
||||
type ViewBox as ViewBox__plan_planView_geometry,
|
||||
clamp,
|
||||
fitBoxFor,
|
||||
marqueeHit,
|
||||
marqueeHitCeilings,
|
||||
marqueeHitDrawings,
|
||||
marqueeHitRooms,
|
||||
marqueeHitStairs,
|
||||
meetScale,
|
||||
mmToPx,
|
||||
pointInPolygon,
|
||||
@@ -286,6 +281,14 @@ export {
|
||||
PlanPickIndex,
|
||||
} from "../plan/planView/planPick";
|
||||
|
||||
export {
|
||||
planCount,
|
||||
planPrimAt,
|
||||
planTextEntries,
|
||||
planWithExtra,
|
||||
type TextEntryPrim,
|
||||
} from "../plan/planLazy";
|
||||
|
||||
export {
|
||||
marqueeHitUnderlay,
|
||||
} from "../plan/planView/underlayAccess";
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { dashToLtypeMeters, fontNameOf, ltypeNameFor, paperFor, primitiveToLocal, roundKey } from "./dxfCadParts";
|
||||
import type { LineStyle } from "../model/types";
|
||||
import type { Primitive } from "../plan/generatePlan";
|
||||
import { fontNameOf } from "./dxfCadParts";
|
||||
|
||||
describe("fontNameOf", () => {
|
||||
it("erste echte Familie, ohne Anführungszeichen; generische/Variablen übersprungen", () => {
|
||||
@@ -13,64 +11,3 @@ describe("fontNameOf", () => {
|
||||
expect(fontNameOf("")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Linientypen", () => {
|
||||
it("Papier-mm × Massstab → Meter (Strich +, Lücke −); ungerade Muster werden verdoppelt", () => {
|
||||
expect(dashToLtypeMeters([3, 1], 100)!.map((v) => Math.round(v * 1e6) / 1e6)).toEqual([0.3, -0.1]);
|
||||
expect(dashToLtypeMeters([2, 1, 0.5], 50)!.map((v) => Math.round(v * 1e6) / 1e6)).toEqual([0.1, -0.05, 0.025, -0.1, 0.05, -0.025]);
|
||||
expect(dashToLtypeMeters([], 100)).toBeNull();
|
||||
expect(dashToLtypeMeters([0, 0], 100)).toBeNull();
|
||||
// Punkt (Strich 0) bleibt 0, Lücke nie 0
|
||||
const dot = dashToLtypeMeters([0, 0], 100);
|
||||
expect(dot).toBeNull();
|
||||
expect(dashToLtypeMeters([0, 1], 100)![0]).toBe(0);
|
||||
});
|
||||
|
||||
it("Name: Projekt-Linienstil mit gleichem Muster, sonst DOSSIER_STRICH_…", () => {
|
||||
const styles = [{ id: "a", name: " Strichlinie ", weight: 0.1, color: "#000", dash: [3, 1] }] as LineStyle[];
|
||||
expect(ltypeNameFor([3, 1], styles)).toBe("Strichlinie");
|
||||
expect(ltypeNameFor([2, 0.5], styles)).toBe("DOSSIER_STRICH_2_0.5");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Papierbereich", () => {
|
||||
it("kleinstes Format, das den Ausschnitt samt Rand aufnimmt", () => {
|
||||
// 20 m × 12 m bei 1:100 = 200 × 120 mm + 20 mm Rand → A4 quer
|
||||
expect(paperFor(20, 12, 100)).toMatchObject({ name: "A4", paperW: 297, paperH: 210, vpW: 277, vpH: 190 });
|
||||
// 30 m × 18 m bei 1:100 → 300 × 180 (+20): A3
|
||||
expect(paperFor(30, 18, 100).name).toBe("A3");
|
||||
// Hochformat, wenn nur so passend
|
||||
expect(paperFor(12, 20, 100)).toMatchObject({ name: "A4", paperW: 210, paperH: 297 });
|
||||
// grösser als A0: Sonderformat in 10-mm-Schritten
|
||||
const big = paperFor(200, 100, 50);
|
||||
expect(big.name).toBe("Sonder");
|
||||
expect(big.paperW % 10).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("primitiveToLocal", () => {
|
||||
const frame = { origin: { x: 10, y: 5 }, rot: Math.PI / 2, scale: 2 };
|
||||
it("Linie, Bogen, Kreis, Text: verschoben, gedreht, skaliert", () => {
|
||||
const line = { kind: "line", a: { x: 10, y: 5 }, b: { x: 10, y: 9 }, cls: "x", weightMm: 0.1 } as Primitive;
|
||||
const l = primitiveToLocal(line, frame) as Extract<Primitive, { kind: "line" }>;
|
||||
expect(l.a.x).toBeCloseTo(0, 12);
|
||||
expect(l.a.y).toBeCloseTo(0, 12);
|
||||
expect(l.b.x).toBeCloseTo(2, 12); // 4 m in Richtung +y = lokale +x, durch Skalierung 2
|
||||
expect(l.b.y).toBeCloseTo(0, 12);
|
||||
const text = { kind: "drawingText", at: { x: 10, y: 5 }, text: "a", heightM: 0.4, angle: Math.PI / 2, color: "#000" } as Primitive;
|
||||
const t = primitiveToLocal(text, frame) as Extract<Primitive, { kind: "drawingText" }>;
|
||||
expect(t.heightM).toBeCloseTo(0.2, 12);
|
||||
expect(t.angle).toBeCloseTo(0, 12);
|
||||
const circle = { kind: "drawingCircle", center: { x: 10, y: 7 }, r: 1, fill: "none", stroke: "#000", weightMm: 0.1 } as Primitive;
|
||||
const c = primitiveToLocal(circle, frame) as Extract<Primitive, { kind: "drawingCircle" }>;
|
||||
expect(c.r).toBeCloseTo(0.5, 12);
|
||||
expect(c.center.x).toBeCloseTo(1, 12);
|
||||
});
|
||||
it("andere Primitivarten (Raumstempel, Bild) gehören nicht in Blöcke", () => {
|
||||
expect(primitiveToLocal({ kind: "drawingImage" } as Primitive, frame)).toBeNull();
|
||||
});
|
||||
it("roundKey: auf 1 mm gerundet", () => {
|
||||
expect(roundKey([1.0001, 2])).toBe(roundKey([1.0004, 2]));
|
||||
expect(roundKey([1.0001, 2])).not.toBe(roundKey([1.002, 2]));
|
||||
});
|
||||
});
|
||||
+3
-116
@@ -1,9 +1,6 @@
|
||||
// Bausteine des Fachplaner-Exports ([C2], 28.10.): reine Hilfsfunktionen für `exportDxf.ts` —
|
||||
// Schriftname aus CSS-Familie, Linientyp-Namen aus Strichmustern, Umrechnung von Plan-Primitiven in ein
|
||||
// lokales Koordinatensystem (für Blöcke) und Papierformate. Keine Abhängigkeit vom Writer.
|
||||
|
||||
import type { Primitive } from "../plan/generatePlan";
|
||||
import type { LineStyle, Vec2 } from "../model/types";
|
||||
// Baustein des Fachplaner-Exports ([C2], 28.10.): Schriftname aus CSS-Familie (Text-Layout bleibt TS).
|
||||
// Linientypen, blocklokale Primitive, Papierformate und der Sammler selbst liegen seit [K3d] im Kern
|
||||
// (`src-tauri/core/src/plan_dxf.rs`).
|
||||
|
||||
/** Erste Schriftfamilie aus einem CSS-`font-family`-Wert ohne Anführungszeichen; generische Familien/CSS-Variablen → null. */
|
||||
export function fontNameOf(css: string | undefined | null): string | null {
|
||||
@@ -17,113 +14,3 @@ export function fontNameOf(css: string | undefined | null): string | null {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Strichmuster (Papier-mm, an/aus/…) → DXF-Linientyp-Elemente in Modell-Metern (Strich +, Lücke −, Punkt 0). */
|
||||
export function dashToLtypeMeters(dashMm: number[], scaleDenominator: number): number[] | null {
|
||||
let pat = dashMm.map((d) => (Number.isFinite(d) ? Math.max(0, d) : 0));
|
||||
if (pat.length === 0 || pat.every((d) => d === 0)) return null;
|
||||
if (pat.length % 2 === 1) pat = pat.concat(pat);
|
||||
const k = scaleDenominator / 1000;
|
||||
const out: number[] = [];
|
||||
for (let i = 0; i < pat.length; i++) {
|
||||
const len = pat[i] * k;
|
||||
out.push(i % 2 === 0 ? len : -Math.max(len, 1e-6));
|
||||
}
|
||||
// Eine Lücke von 0 ergäbe ein Muster ohne Unterbrechung; mindestens 1 µm.
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Zahl für Namen: höchstens 2 Nachkommastellen, ohne Nullen am Ende. */
|
||||
function n2(v: number): string {
|
||||
return String(Math.round(v * 100) / 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Name des Linientyps zu einem Strichmuster: der Name des Projekt-Linienstils mit demselben Muster, sonst
|
||||
* `DOSSIER_STRICH_<an>_<aus>…` (Papier-mm).
|
||||
*/
|
||||
export function ltypeNameFor(dashMm: number[], styles: readonly LineStyle[]): string {
|
||||
const same = (a: number[], b: number[]) => a.length === b.length && a.every((v, i) => Math.abs(v - b[i]) < 1e-9);
|
||||
const hit = styles.find((s) => s.dash && s.dash.length > 0 && (s.kind ?? "dash") === "dash" && same(s.dash, dashMm));
|
||||
if (hit && hit.name.trim()) return hit.name.trim();
|
||||
return `DOSSIER_STRICH_${dashMm.map(n2).join("_")}`;
|
||||
}
|
||||
|
||||
// ── Lokales Koordinatensystem (Blöcke) ────────────────────────────────────────
|
||||
|
||||
/** Abbildung Modell → blocklokal: Verschiebung `-origin`, Drehung `-rot`, Skalierung `1/scale`. */
|
||||
export interface LocalFrame {
|
||||
origin: Vec2;
|
||||
/** Drehung des Blocks im Modell (Radiant). */
|
||||
rot: number;
|
||||
scale: number;
|
||||
}
|
||||
|
||||
function toLocal(f: LocalFrame, p: Vec2): Vec2 {
|
||||
const c = Math.cos(f.rot);
|
||||
const s = Math.sin(f.rot);
|
||||
const dx = p.x - f.origin.x;
|
||||
const dy = p.y - f.origin.y;
|
||||
return { x: (dx * c + dy * s) / f.scale, y: (-dx * s + dy * c) / f.scale };
|
||||
}
|
||||
|
||||
/** Primitive im lokalen System des Blocks (nur Geometrie-Arten, die in Blöcken vorkommen); andere → null. */
|
||||
export function primitiveToLocal(p: Primitive, f: LocalFrame): Primitive | null {
|
||||
const rotDeg = (f.rot * 180) / Math.PI;
|
||||
switch (p.kind) {
|
||||
case "line":
|
||||
return { ...p, a: toLocal(f, p.a), b: toLocal(f, p.b), motif: undefined, zigzag: p.zigzag && { amplitude: p.zigzag.amplitude / f.scale, wavelength: p.zigzag.wavelength / f.scale } };
|
||||
case "arc":
|
||||
return { ...p, center: toLocal(f, p.center), from: toLocal(f, p.from), to: toLocal(f, p.to), r: p.r / f.scale };
|
||||
case "polygon":
|
||||
return { ...p, pts: p.pts.map((q) => toLocal(f, q)), hatch: { ...p.hatch, angle: p.hatch.angle - rotDeg } };
|
||||
case "drawingCircle":
|
||||
return { ...p, center: toLocal(f, p.center), r: p.r / f.scale };
|
||||
case "drawingArc":
|
||||
return { ...p, center: toLocal(f, p.center), r: p.r / f.scale, a0: p.a0 - f.rot, a1: p.a1 - f.rot };
|
||||
case "drawingText":
|
||||
return { ...p, at: toLocal(f, p.at), heightM: p.heightM / f.scale, angle: p.angle - f.rot, wrapWidth: p.wrapWidth && p.wrapWidth / f.scale };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Schlüssel gleicher lokaler Geometrie: Zahlen auf 1 mm gerundet (Blöcke teilen sich nur identische Inhalte). */
|
||||
export function roundKey(nums: readonly number[]): string {
|
||||
let out = "";
|
||||
for (const v of nums) out += `${Math.round(v * 1000)},`;
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── Papierbereich ────────────────────────────────────────────────────────────
|
||||
|
||||
/** Papierformate (mm, quer) in aufsteigender Grösse. */
|
||||
const PAPER_SIZES: [string, number, number][] = [
|
||||
["A4", 297, 210],
|
||||
["A3", 420, 297],
|
||||
["A2", 594, 420],
|
||||
["A1", 841, 594],
|
||||
["A0", 1189, 841],
|
||||
];
|
||||
|
||||
/**
|
||||
* Papier und Ansichtsfenster für einen Ausschnitt der Grösse `w` × `h` Meter im Massstab 1:`scale`:
|
||||
* kleinstes A-Format (quer, sonst hoch), das den Ausschnitt mit `margin` mm Rand aufnimmt; ist keines
|
||||
* gross genug, ein Sonderformat in Vielfachen von 10 mm. Das Fenster füllt das Papier abzüglich Rand.
|
||||
*/
|
||||
export function paperFor(
|
||||
w: number,
|
||||
h: number,
|
||||
scale: number,
|
||||
margin = 10,
|
||||
): { paperW: number; paperH: number; vpW: number; vpH: number; name: string } {
|
||||
const needW = (w * 1000) / scale + 2 * margin;
|
||||
const needH = (h * 1000) / scale + 2 * margin;
|
||||
for (const [name, pw, ph] of PAPER_SIZES) {
|
||||
if (needW <= pw && needH <= ph) return { paperW: pw, paperH: ph, vpW: pw - 2 * margin, vpH: ph - 2 * margin, name };
|
||||
if (needW <= ph && needH <= pw) return { paperW: ph, paperH: pw, vpW: ph - 2 * margin, vpH: pw - 2 * margin, name };
|
||||
}
|
||||
const pw = Math.ceil(needW / 10) * 10;
|
||||
const ph = Math.ceil(needH / 10) * 10;
|
||||
return { paperW: pw, paperH: ph, vpW: pw - 2 * margin, vpH: ph - 2 * margin, name: "Sonder" };
|
||||
}
|
||||
+114
-888
File diff suppressed because it is too large.
Load diff
+54
-427
@@ -19,14 +19,20 @@
|
||||
// Pattern oft nicht sauber), sondern als echte, auf das Polygon geklippte
|
||||
// Vektorlinien direkt ins SVG. So bleibt das PDF rein vektoriell und scharf.
|
||||
//
|
||||
// Seit [K3d] (29.10.) rechnet der Kern die Knoten aus den Plan-Puffern
|
||||
// (`src-tauri/core/src/plan_print_svg.rs`, Anweisungsliste); hier bleiben der
|
||||
// <svg>-Rahmen, die Bild-<pattern> (laufende Ids) und die Einzeltexte
|
||||
// (Text-Layout `wrapDocToLines`). Ausgabe unverändert (gleiche Knoten/Attribute).
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import type { HatchRender, Plan, Primitive } from "../plan/generatePlan";
|
||||
import type { Vec2 } from "../model/types";
|
||||
import { buildRandomHatchRuns, zigzagPoints, motifPoints } from "../plan/glPlan/glPlanHatch";
|
||||
import { dashHasDot } from "../geometry/lineSegments";
|
||||
import { wrapDocToLines, type SvgLine } from "../text/renderHtml";
|
||||
import { docFromText } from "../text/richText";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import { planParts, withPlanParts } from "../plan/planParts";
|
||||
import { planPrimAt } from "../plan/planLazy";
|
||||
|
||||
/** SVG-Namespace für die programmatisch erzeugten Knoten. */
|
||||
const SVG_NS = "http://www.w3.org/2000/svg";
|
||||
@@ -77,41 +83,6 @@ function ensureImagePattern(
|
||||
return id;
|
||||
}
|
||||
|
||||
/** `<polyline>`-Knoten (mm-Koordinaten) — für Zickzack-Linien/-Läufe. */
|
||||
function polylineNode(
|
||||
pts: Vec2[],
|
||||
color: string,
|
||||
strokeMm: number,
|
||||
dash: number[] | null | undefined,
|
||||
): SVGElement {
|
||||
const el = document.createElementNS(SVG_NS, "polyline");
|
||||
el.setAttribute("points", pts.map((p) => `${round(p.x)},${round(p.y)}`).join(" "));
|
||||
el.setAttribute("fill", "none");
|
||||
el.setAttribute("stroke", color);
|
||||
el.setAttribute("stroke-width", String(strokeMm));
|
||||
el.setAttribute("stroke-linecap", "round");
|
||||
el.setAttribute("stroke-linejoin", "round");
|
||||
if (dash && dash.length) el.setAttribute("stroke-dasharray", dash.map((d) => round(d)).join(" "));
|
||||
return el;
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard-Stift-Stufen (mm). Beliebige Kategorie-Strichstärken werden auf die
|
||||
* NÄCHSTHÖHERE dieser ISO-nahen Stufen gequantelt, damit der Plan saubere,
|
||||
* unterscheidbare Linienstärken trägt (dünne Hilfslinien ≠ dicke Umrisse).
|
||||
*/
|
||||
const PEN_STEPS = [0.13, 0.18, 0.25, 0.35, 0.5, 0.7, 1.0] as const;
|
||||
|
||||
/** Untergrenze einer sichtbaren Druck-Strichstärke (mm) — vermeidet 0-Linien. */
|
||||
const MIN_PEN_MM = 0.13;
|
||||
|
||||
/** Quantelt eine mm-Strichstärke auf die nächste Stift-Stufe (≥ MIN_PEN_MM). */
|
||||
function quantizePen(mm: number): number {
|
||||
const w = Math.max(MIN_PEN_MM, mm);
|
||||
for (const step of PEN_STEPS) if (w <= step + 1e-6) return step;
|
||||
return PEN_STEPS[PEN_STEPS.length - 1];
|
||||
}
|
||||
|
||||
/** Ergebnis des Print-SVG-Aufbaus: das Element + Blattmasse (mm). */
|
||||
export interface PrintSvg {
|
||||
/** Das fertige, in mm bemaßte <svg>-Element (für svg2pdf). */
|
||||
@@ -200,10 +171,11 @@ export function planToPrintSvg(plan: Plan, opts: PrintSvgOptions): PrintSvg {
|
||||
bg.setAttribute("fill", "#ffffff");
|
||||
svg.appendChild(bg);
|
||||
|
||||
// Jedes Primitiv in mm-Knoten übersetzen.
|
||||
for (const p of plan.primitives) {
|
||||
appendPrimitive(svg, p, map, k);
|
||||
}
|
||||
// Jedes Primitiv in mm-Knoten übersetzen (Kern, Anweisungsliste s. `plan_print_svg.rs`).
|
||||
const o = Float64Array.of(n, opts.pageWidthMm, opts.pageHeightMm, b.minX, b.minY, b.maxX, b.maxY);
|
||||
const ops = withPlanParts(planParts(plan, true), (segs) => core().plan_print_svg_ops(segs, o));
|
||||
if (!ops) throw new Error("Druck-SVG: Plan im Kern unlesbar");
|
||||
applyOps(svg, ops.slice(1), plan, map, k);
|
||||
|
||||
return {
|
||||
svg,
|
||||
@@ -213,93 +185,50 @@ export function planToPrintSvg(plan: Plan, opts: PrintSvgOptions): PrintSvg {
|
||||
};
|
||||
}
|
||||
|
||||
/** Schreibt ein einzelnes Primitiv (mit ggf. Schraffur) in das SVG. */
|
||||
function appendPrimitive(
|
||||
svg: SVGSVGElement,
|
||||
p: Primitive,
|
||||
map: Mapper,
|
||||
mmPerM: number,
|
||||
): void {
|
||||
// Gedimmt (0.3) und Objekt-Transparenz multiplizieren sich; Bilder tragen
|
||||
// ihre eigene Deckkraft separat (s. dortiger Zweig).
|
||||
const objOpacity = p.kind === "drawingImage" ? 1 : (p.opacity ?? 1);
|
||||
const dim = p.greyed ? 0.3 : 1;
|
||||
const combined = dim * Math.max(0, objOpacity);
|
||||
const opacity = combined < 1 ? String(combined) : undefined;
|
||||
switch (p.kind) {
|
||||
case "polygon":
|
||||
appendPolygon(svg, p, map, mmPerM, opacity);
|
||||
break;
|
||||
case "line": {
|
||||
const a = map(p.a);
|
||||
const b = map(p.b);
|
||||
// Zickzack-Linie (amplitude/wavelength sind Papier-mm = mm-Zielraum) →
|
||||
// Polylinie; sonst gerade (ggf. gestrichelte) Linie wie bisher.
|
||||
// Zickzack/Custom-Motiv sind in Papier-mm definiert = mm-Zielraum (scale 1).
|
||||
const ln = p.zigzag
|
||||
? polylineNode(
|
||||
zigzagPoints(a, b, p.zigzag.amplitude, p.zigzag.wavelength),
|
||||
p.color ?? "#111111",
|
||||
quantizePen(p.weightMm),
|
||||
p.dash,
|
||||
)
|
||||
: p.motif
|
||||
? polylineNode(
|
||||
motifPoints(a, b, p.motif),
|
||||
p.color ?? "#111111",
|
||||
quantizePen(p.weightMm),
|
||||
p.dash,
|
||||
)
|
||||
: lineNode(a, b, p.color ?? "#111111", quantizePen(p.weightMm), p.dash, mmPerM);
|
||||
if (opacity) ln.setAttribute("opacity", opacity);
|
||||
svg.appendChild(ln);
|
||||
break;
|
||||
}
|
||||
case "arc": {
|
||||
const node = arcNode(p, map, mmPerM);
|
||||
if (opacity) node.setAttribute("opacity", opacity);
|
||||
svg.appendChild(node);
|
||||
break;
|
||||
}
|
||||
case "drawingCircle": {
|
||||
const c = map(p.center);
|
||||
const el = document.createElementNS(SVG_NS, "circle");
|
||||
el.setAttribute("cx", String(round(c.x)));
|
||||
el.setAttribute("cy", String(round(c.y)));
|
||||
el.setAttribute("r", String(round(p.r * mmPerM)));
|
||||
el.setAttribute("fill", p.fill && p.fill !== "none" ? p.fill : "none");
|
||||
el.setAttribute("stroke", p.stroke);
|
||||
el.setAttribute("stroke-width", String(quantizePen(p.weightMm)));
|
||||
if (p.dash && p.dash.length) {
|
||||
el.setAttribute("stroke-dasharray", p.dash.map((x) => round(x)).join(" "));
|
||||
if (dashHasDot(p.dash)) el.setAttribute("stroke-linecap", "round");
|
||||
/**
|
||||
* Legt die Knoten der Kern-Anweisungsliste an (Format s. `plan_print_svg.rs`): Elemente mit ihren
|
||||
* Attributen in Reihenfolge, Gruppen, Bild-Schraffuren (`<pattern>` hier) und Einzeltexte (Layout hier).
|
||||
*/
|
||||
function applyOps(svg: SVGSVGElement, ops: string, plan: Plan, map: Mapper, mmPerM: number): void {
|
||||
if (!ops) return;
|
||||
let g: SVGElement | null = null;
|
||||
for (const rec of ops.split("\u001e")) {
|
||||
const f = rec.split("\u001f");
|
||||
switch (f[0]) {
|
||||
case "E": {
|
||||
const el = document.createElementNS(SVG_NS, f[2]) as SVGElement;
|
||||
for (let i = 3; i + 1 < f.length; i += 2) el.setAttribute(f[i], f[i + 1]);
|
||||
(f[1] === "1" && g ? g : svg).appendChild(el);
|
||||
break;
|
||||
}
|
||||
if (opacity) el.setAttribute("opacity", opacity);
|
||||
svg.appendChild(el);
|
||||
break;
|
||||
}
|
||||
case "drawingArc": {
|
||||
const node = drawingArcNode(p, map, mmPerM);
|
||||
if (opacity) node.setAttribute("opacity", opacity);
|
||||
svg.appendChild(node);
|
||||
break;
|
||||
}
|
||||
case "drawingText": {
|
||||
const node = drawingTextNode(p, map, mmPerM);
|
||||
if (node) {
|
||||
if (opacity) node.setAttribute("opacity", opacity);
|
||||
svg.appendChild(node);
|
||||
case "G":
|
||||
g = document.createElementNS(SVG_NS, "g") as SVGElement;
|
||||
if (f[1]) g.setAttribute("opacity", f[1]);
|
||||
break;
|
||||
case "g":
|
||||
if (g) svg.appendChild(g);
|
||||
g = null;
|
||||
break;
|
||||
case "I": {
|
||||
// Bild-Schraffur: gekacheltes <pattern> über die Fläche.
|
||||
const patId = ensureImagePattern(svg, JSON.parse(f[2]) as NonNullable<HatchRender["image"]>);
|
||||
const el = document.createElementNS(SVG_NS, "polygon");
|
||||
el.setAttribute("points", f[1]);
|
||||
el.setAttribute("fill", `url(#${patId})`);
|
||||
el.setAttribute("stroke", "none");
|
||||
g?.appendChild(el);
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "drawingImage": {
|
||||
const node = drawingImageNode(p, map, mmPerM);
|
||||
if (node) {
|
||||
if (p.opacity < 1) node.setAttribute("opacity", String(p.opacity * (p.greyed ? 0.45 : 1)));
|
||||
else if (opacity) node.setAttribute("opacity", opacity);
|
||||
svg.appendChild(node);
|
||||
case "T": {
|
||||
const p = planPrimAt(plan, Number(f[1]));
|
||||
if (p?.kind !== "drawingText") break;
|
||||
const node = drawingTextNode(p, map, mmPerM);
|
||||
if (node) {
|
||||
if (f[2]) node.setAttribute("opacity", f[2]);
|
||||
svg.appendChild(node);
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -371,309 +300,7 @@ function drawingTextNode(
|
||||
return el;
|
||||
}
|
||||
|
||||
/** Eingebettetes Rasterbild (Data-URL) als achsparalleles `<image>`. */
|
||||
function drawingImageNode(
|
||||
p: Extract<Primitive, { kind: "drawingImage" }>,
|
||||
map: Mapper,
|
||||
mmPerM: number,
|
||||
): SVGImageElement | null {
|
||||
const w = (p.max.x - p.min.x) * mmPerM;
|
||||
const h = (p.max.y - p.min.y) * mmPerM;
|
||||
if (w <= 0 || h <= 0) return null;
|
||||
const topLeft = map({ x: p.min.x, y: p.max.y });
|
||||
const el = document.createElementNS(SVG_NS, "image");
|
||||
el.setAttribute("href", p.src);
|
||||
el.setAttribute("x", String(round(topLeft.x)));
|
||||
el.setAttribute("y", String(round(topLeft.y)));
|
||||
el.setAttribute("width", String(round(w)));
|
||||
el.setAttribute("height", String(round(h)));
|
||||
el.setAttribute("preserveAspectRatio", "none");
|
||||
return el;
|
||||
}
|
||||
|
||||
/**
|
||||
* Polygon mit Füllung/Umriss/Schraffur. Reihenfolge wie in der PlanView:
|
||||
* • pattern "none" → reine Füllung (oder „none") + Umriss.
|
||||
* • pattern "solid" → Vollfüllung in der Hatch-Farbe + Umriss.
|
||||
* • Linien/Kreuz/Dämmung → Grundfüllung, dann geklippte Schraffurlinien, dann Umriss.
|
||||
*/
|
||||
function appendPolygon(
|
||||
svg: SVGSVGElement,
|
||||
p: Extract<Primitive, { kind: "polygon" }>,
|
||||
map: Mapper,
|
||||
mmPerM: number,
|
||||
opacity: string | undefined,
|
||||
): void {
|
||||
const ptsMm = p.pts.map(map);
|
||||
const ptsAttr = ptsMm.map((s) => `${round(s.x)},${round(s.y)}`).join(" ");
|
||||
const strokeMm = p.strokeWidthMm > 0 ? quantizePen(p.strokeWidthMm) : 0;
|
||||
|
||||
const g = document.createElementNS(SVG_NS, "g");
|
||||
if (opacity) g.setAttribute("opacity", opacity);
|
||||
|
||||
const pattern = p.hatch.pattern;
|
||||
if (p.hatch.kind === "image" && p.hatch.image) {
|
||||
// Bild-Schraffur: gekacheltes <pattern> mit <image> (scaleX/scaleY/rotation)
|
||||
// über die Fläche, unabhängig vom `pattern`-Feld. Grundfüllung darunter,
|
||||
// Umriss obenauf.
|
||||
if (p.fill !== "none") g.appendChild(polyNode(ptsAttr, p.fill, "none", 0));
|
||||
const patId = ensureImagePattern(svg, p.hatch.image);
|
||||
g.appendChild(polyNode(ptsAttr, `url(#${patId})`, "none", 0));
|
||||
if (strokeMm > 0) g.appendChild(polyNode(ptsAttr, "none", p.stroke, strokeMm));
|
||||
} else if (pattern === "none") {
|
||||
g.appendChild(polyNode(ptsAttr, p.fill, p.stroke, strokeMm));
|
||||
} else if (pattern === "solid") {
|
||||
g.appendChild(polyNode(ptsAttr, p.hatch.color, p.stroke, strokeMm));
|
||||
} else {
|
||||
// Grundfüllung (ohne Umriss), dann die geklippten Schraffurlinien, dann der
|
||||
// Umriss obenauf (separat, damit er die Schraffur-Enden überdeckt).
|
||||
if (p.fill !== "none") {
|
||||
g.appendChild(polyNode(ptsAttr, p.fill, "none", 0));
|
||||
}
|
||||
if (p.hatch.lines === "random") {
|
||||
// Random-Vektor (Kies/Splitt): deterministische Streu-Striche. Wird im
|
||||
// MODELL-Raum erzeugt (identischer Seed/Geometrie wie Bildschirm/GL/PDF)
|
||||
// und dann nach Papier-mm abgebildet.
|
||||
for (const run of buildRandomHatchRuns(p.pts, p.hatch)) {
|
||||
if (run.length < 2) continue;
|
||||
g.appendChild(
|
||||
lineNode(
|
||||
map(run[0]),
|
||||
map(run[run.length - 1]),
|
||||
p.hatch.color,
|
||||
quantizePen(p.hatch.lineWeight),
|
||||
null,
|
||||
mmPerM,
|
||||
),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
for (const seg of hatchLines(ptsMm, p.hatch, mmPerM)) {
|
||||
g.appendChild(
|
||||
lineNode(
|
||||
seg.a,
|
||||
seg.b,
|
||||
p.hatch.color,
|
||||
quantizePen(p.hatch.lineWeight),
|
||||
p.hatch.dash,
|
||||
mmPerM,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (strokeMm > 0) {
|
||||
g.appendChild(polyNode(ptsAttr, "none", p.stroke, strokeMm));
|
||||
}
|
||||
}
|
||||
|
||||
svg.appendChild(g);
|
||||
}
|
||||
|
||||
/** Erzeugt einen <polygon>-Knoten (mm-Koordinaten als Attribut-String). */
|
||||
function polyNode(
|
||||
ptsAttr: string,
|
||||
fill: string,
|
||||
stroke: string,
|
||||
strokeMm: number,
|
||||
): SVGElement {
|
||||
const el = document.createElementNS(SVG_NS, "polygon");
|
||||
el.setAttribute("points", ptsAttr);
|
||||
el.setAttribute("fill", fill);
|
||||
if (stroke !== "none" && strokeMm > 0) {
|
||||
el.setAttribute("stroke", stroke);
|
||||
el.setAttribute("stroke-width", String(strokeMm));
|
||||
el.setAttribute("stroke-linejoin", "round");
|
||||
} else {
|
||||
el.setAttribute("stroke", "none");
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
/** Erzeugt einen <line>-Knoten in mm; Strichmuster (mm Welt → mm Papier). */
|
||||
function lineNode(
|
||||
a: Vec2,
|
||||
b: Vec2,
|
||||
color: string,
|
||||
strokeMm: number,
|
||||
dash: number[] | null | undefined,
|
||||
_mmPerM: number,
|
||||
): SVGElement {
|
||||
const el = document.createElementNS(SVG_NS, "line");
|
||||
el.setAttribute("x1", String(round(a.x)));
|
||||
el.setAttribute("y1", String(round(a.y)));
|
||||
el.setAttribute("x2", String(round(b.x)));
|
||||
el.setAttribute("y2", String(round(b.y)));
|
||||
el.setAttribute("stroke", color);
|
||||
el.setAttribute("stroke-width", String(strokeMm));
|
||||
el.setAttribute("stroke-linecap", "round");
|
||||
if (dash && dash.length) {
|
||||
// Strichmuster ist in mm Papier definiert (wie weightMm), daher direkt.
|
||||
el.setAttribute("stroke-dasharray", dash.map((d) => round(d)).join(" "));
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
/**
|
||||
* Erzeugt einen Bogen als <path> (A-Kommando). Der Bogen-Radius ist in Metern →
|
||||
* Papier-mm. Drehrichtung aus dem Kreuzprodukt im Papier-Raum (Y nach unten).
|
||||
*/
|
||||
function arcNode(
|
||||
p: Extract<Primitive, { kind: "arc" }>,
|
||||
map: Mapper,
|
||||
mmPerM: number,
|
||||
): SVGElement {
|
||||
const c = map(p.center);
|
||||
const from = map(p.from);
|
||||
const to = map(p.to);
|
||||
const r = p.r * mmPerM;
|
||||
const v1 = { x: from.x - c.x, y: from.y - c.y };
|
||||
const v2 = { x: to.x - c.x, y: to.y - c.y };
|
||||
const cross = v1.x * v2.y - v1.y * v2.x;
|
||||
const sweep = cross > 0 ? 1 : 0;
|
||||
const d = `M ${round(from.x)} ${round(from.y)} A ${round(r)} ${round(r)} 0 0 ${sweep} ${round(to.x)} ${round(to.y)}`;
|
||||
const el = document.createElementNS(SVG_NS, "path");
|
||||
el.setAttribute("d", d);
|
||||
el.setAttribute("fill", "none");
|
||||
el.setAttribute("stroke", "#111111");
|
||||
el.setAttribute("stroke-width", String(quantizePen(p.weightMm)));
|
||||
if (p.dash && p.dash.length) {
|
||||
el.setAttribute("stroke-dasharray", p.dash.map((x) => round(x)).join(" "));
|
||||
// Punktmuster (dash enthält eine 0): runde Kappe → Dots am Bogen.
|
||||
if (dashHasDot(p.dash)) el.setAttribute("stroke-linecap", "round");
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
/**
|
||||
* `drawingArc` → glatter SVG-Bogen. Konvention wie im Bildschirm-Renderer
|
||||
* (`planView/primitives.tsx`): die Winkel laufen im MODELL immer gegen den
|
||||
* Uhrzeigersinn von `a0` nach `a1`; da die Ziel-Y-Achse gespiegelt ist, wird
|
||||
* daraus am Papier ein Uhrzeigersinn-Bogen (sweep-flag 1). `large-arc` aus
|
||||
* der normierten Spannweite.
|
||||
*/
|
||||
function drawingArcNode(
|
||||
p: Extract<Primitive, { kind: "drawingArc" }>,
|
||||
map: Mapper,
|
||||
mmPerM: number,
|
||||
): SVGElement {
|
||||
const TAU = Math.PI * 2;
|
||||
const from = map({ x: p.center.x + p.r * Math.cos(p.a0), y: p.center.y + p.r * Math.sin(p.a0) });
|
||||
const to = map({ x: p.center.x + p.r * Math.cos(p.a1), y: p.center.y + p.r * Math.sin(p.a1) });
|
||||
const r = p.r * mmPerM;
|
||||
const sweep = (((p.a1 - p.a0) % TAU) + TAU) % TAU;
|
||||
const largeArc = sweep > Math.PI ? 1 : 0;
|
||||
const el = document.createElementNS(SVG_NS, "path");
|
||||
el.setAttribute(
|
||||
"d",
|
||||
`M ${round(from.x)} ${round(from.y)} A ${round(r)} ${round(r)} 0 ${largeArc} 1 ${round(to.x)} ${round(to.y)}`,
|
||||
);
|
||||
el.setAttribute("fill", "none");
|
||||
el.setAttribute("stroke", p.stroke);
|
||||
el.setAttribute("stroke-width", String(quantizePen(p.weightMm)));
|
||||
if (p.dash && p.dash.length) {
|
||||
el.setAttribute("stroke-dasharray", p.dash.map((x) => round(x)).join(" "));
|
||||
if (dashHasDot(p.dash)) el.setAttribute("stroke-linecap", "round");
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
/** Auf 3 Nachkommastellen runden (kompaktes, exaktes SVG). */
|
||||
function round(v: number): number {
|
||||
return Math.round(v * 1000) / 1000;
|
||||
}
|
||||
|
||||
// ── Schraffur als geklippte Vektorlinien ─────────────────────────────────────
|
||||
|
||||
interface Seg {
|
||||
a: Vec2;
|
||||
b: Vec2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Erzeugt die Schraffurlinien eines Polygons (in Papier-mm), auf das Polygon
|
||||
* geklippt. Die Kachelgrösse der Bildschirm-PlanView (8 px bzw. 14 px bei
|
||||
* „insulation", × Maßstab) wird hier in einen mm-Linienabstand übersetzt, damit
|
||||
* der Druck der Bildschirm-Dichte nahekommt:
|
||||
* • diagonal/crosshatch: parallele Linienscharen im Winkel `angle`.
|
||||
* • crosshatch: zusätzlich die um 90° gedrehte Schar.
|
||||
* • insulation: vereinfacht als eine dichtere diagonale Schar (echte Wellen-
|
||||
* linie wäre als Pfad möglich; eine Linienschar liest sich im Druck sauber
|
||||
* und bleibt rein vektoriell — offener Punkt im Report).
|
||||
*/
|
||||
function hatchLines(polyMm: Vec2[], hatch: HatchRender, mmPerM: number): Seg[] {
|
||||
// Kachel der PlanView: 8 viewBox-Einheiten (= px bei dpi-Bezug) × scale. In der
|
||||
// PlanView ist 1 viewBox-Einheit = 1/PX_PER_M m = 1/90 m. Auf Papier sind das
|
||||
// (1/90)·mmPerM mm. So bleibt die Strich-Dichte massstäblich konsistent.
|
||||
const unitMm = (1 / 90) * mmPerM;
|
||||
const tileMm = (hatch.pattern === "insulation" ? 10 : 8) * hatch.scale * unitMm;
|
||||
const spacing = Math.max(0.5, tileMm); // Mindestabstand, sonst zu dicht
|
||||
|
||||
const angle = (hatch.angle * Math.PI) / 180;
|
||||
const segs: Seg[] = [];
|
||||
fillParallel(polyMm, angle, spacing, segs);
|
||||
if (hatch.pattern === "crosshatch") {
|
||||
fillParallel(polyMm, angle + Math.PI / 2, spacing, segs);
|
||||
}
|
||||
if (hatch.pattern === "insulation") {
|
||||
// Zweite, gegenläufige Schar deutet die Dämmungs-Textur an (dichter Filz).
|
||||
fillParallel(polyMm, angle - Math.PI / 4, spacing, segs);
|
||||
}
|
||||
return segs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Füllt das Polygon mit parallelen Linien im gegebenen Winkel/Abstand und klippt
|
||||
* jede Linie auf das Polygon (Scanline über die Polygon-Schnittpunkte). Robust
|
||||
* für konvexe wie konkave (einfache) Polygone.
|
||||
*/
|
||||
function fillParallel(
|
||||
poly: Vec2[],
|
||||
angle: number,
|
||||
spacing: number,
|
||||
out: Seg[],
|
||||
): void {
|
||||
if (poly.length < 3 || spacing <= 0) return;
|
||||
// Linienrichtung d und Normale nrm (Projektionsachse).
|
||||
const dir = { x: Math.cos(angle), y: Math.sin(angle) };
|
||||
const nrm = { x: -dir.y, y: dir.x };
|
||||
|
||||
// Projektion der Polygonpunkte auf die Normale → [tMin, tMax]-Band der Linien.
|
||||
let tMin = Infinity;
|
||||
let tMax = -Infinity;
|
||||
for (const p of poly) {
|
||||
const t = p.x * nrm.x + p.y * nrm.y;
|
||||
if (t < tMin) tMin = t;
|
||||
if (t > tMax) tMax = t;
|
||||
}
|
||||
// Linien an t = tMin + i·spacing; für jede die Schnitt-Intervalle ermitteln.
|
||||
const start = Math.ceil(tMin / spacing) * spacing;
|
||||
for (let t = start; t <= tMax; t += spacing) {
|
||||
const xs: number[] = []; // Parameter entlang dir der Schnittpunkte
|
||||
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
|
||||
const a = poly[j];
|
||||
const b = poly[i];
|
||||
const ta = a.x * nrm.x + a.y * nrm.y;
|
||||
const tb = b.x * nrm.x + b.y * nrm.y;
|
||||
// Schneidet die Kante das Niveau t?
|
||||
if (ta === tb) continue;
|
||||
const f = (t - ta) / (tb - ta);
|
||||
if (f < 0 || f > 1) continue;
|
||||
const px = a.x + (b.x - a.x) * f;
|
||||
const py = a.y + (b.y - a.y) * f;
|
||||
xs.push(px * dir.x + py * dir.y); // Position entlang dir
|
||||
}
|
||||
if (xs.length < 2) continue;
|
||||
xs.sort((u, v) => u - v);
|
||||
// Paarweise Intervalle = Polygon-Inneres entlang der Linie.
|
||||
for (let k = 0; k + 1 < xs.length; k += 2) {
|
||||
const u0 = xs[k];
|
||||
const u1 = xs[k + 1];
|
||||
if (u1 - u0 < 1e-6) continue;
|
||||
// Punkt = t·nrm + u·dir.
|
||||
out.push({
|
||||
a: { x: nrm.x * t + dir.x * u0, y: nrm.y * t + dir.y * u0 },
|
||||
b: { x: nrm.x * t + dir.x * u1, y: nrm.y * t + dir.y * u1 },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
+73
-66
@@ -53,7 +53,8 @@ import {
|
||||
type HatchRender,
|
||||
type Primitive,
|
||||
} from "./generatePlan/shared";
|
||||
import { subtractVoidsInPlan } from "./voids";
|
||||
import { subtractVoidsInPlan, voidPrisms } from "./voids";
|
||||
import { isBufPiece, lazyPlan, piecesOf, planCount, planFields, type PlanPiece } from "./planLazy";
|
||||
import { addSunShadow } from "./generatePlan/sunShadow";
|
||||
import { addSiteRules, addSiteViolations } from "./generatePlan/siteRules";
|
||||
import { lineWeightFactor, scalePrimitiveWeights } from "./lineWeightScale";
|
||||
@@ -211,11 +212,6 @@ export interface PlanBufRun {
|
||||
to: number;
|
||||
}
|
||||
|
||||
/** Kern-Abschnitte um `shift` verschieben (beim Zusammensetzen mehrerer Pläne). */
|
||||
function shiftRuns(runs: readonly PlanBufRun[] | undefined, shift: number, into: PlanBufRun[]): void {
|
||||
for (const r of runs ?? []) into.push({ ...r, at: r.at + shift });
|
||||
}
|
||||
|
||||
/**
|
||||
* Eine Gruppe kompakt gehaltener Zeichnungen. Ihre Linien entstehen erst beim
|
||||
* Kompilieren eines GPU-Chunks (kurzlebig, `build`), nicht als dauerhafte
|
||||
@@ -254,26 +250,17 @@ export function materializeUnderlay(plan: Plan): Plan {
|
||||
for (const pr of g.build(g.drawings)) target.push(pr);
|
||||
if (g.tint && target.length > from) (g.above ? aboveGreyed : belowGreyed).push([from, target.length]);
|
||||
}
|
||||
const primitives: Primitive[] = [];
|
||||
for (const pr of below) primitives.push(pr);
|
||||
for (const pr of plan.primitives) primitives.push(pr);
|
||||
for (const pr of above) primitives.push(pr);
|
||||
// Stücke statt Kopie (s. `planLazy.ts`): die Primitive des Plans werden dabei nicht gelesen.
|
||||
const n = planCount(plan);
|
||||
const shifted = (plan.greyedRanges ?? []).map(([a, b]): [number, number] => [a + below.length, b + below.length]);
|
||||
const aboveShift = below.length + plan.primitives.length;
|
||||
const aboveShift = below.length + n;
|
||||
const ranges = [
|
||||
...belowGreyed,
|
||||
...shifted,
|
||||
...aboveGreyed.map(([a, b]): [number, number] => [a + aboveShift, b + aboveShift]),
|
||||
];
|
||||
const bufRuns: PlanBufRun[] = [];
|
||||
shiftRuns(plan.bufRuns, below.length, bufRuns);
|
||||
return {
|
||||
...plan,
|
||||
primitives,
|
||||
underlay: undefined,
|
||||
greyedRanges: ranges.length ? ranges : undefined,
|
||||
bufRuns: bufRuns.length ? bufRuns : undefined,
|
||||
};
|
||||
const { underlay: _u, greyedRanges: _g, ...fields } = planFields(plan);
|
||||
return lazyPlan({ ...fields, ...(ranges.length ? { greyedRanges: ranges } : {}) }, [below, ...piecesOf(plan), above]);
|
||||
}
|
||||
|
||||
/** Ob Index `i` in einem der (sortierten, disjunkten) Bereiche liegt. */
|
||||
@@ -412,15 +399,14 @@ export function generatePlan(
|
||||
// Der Kern liefert alles in EINEM Plan-Puffer (Gruppen in dieser Reihenfolge); die Abschnitte
|
||||
// merkt sich der Plan (`bufRuns`), damit die GPU sie direkt aus dem Puffer kompiliert.
|
||||
const dom = planDomains(project, floorId, visibleCodes, categoryDisplay, detail, showReferenceLines, includeGlobal);
|
||||
const runs: PlanBufRun[] = [];
|
||||
// Der Plan entsteht aus Stücken ([K3d], `planLazy.ts`): TS-Listen und Kern-Abschnitte; die
|
||||
// Kern-Primitive werden erst gelesen, wenn ein Verbraucher sie als Objekte braucht.
|
||||
const pieces: PlanPiece[] = [primitives];
|
||||
const pushGroups = (first: number, last: number): void => {
|
||||
if (!dom.buf) return;
|
||||
const from = dom.buf.groups[first][0];
|
||||
const to = dom.buf.groups[last][1];
|
||||
const at = primitives.length;
|
||||
const src = dom.buf.prims;
|
||||
for (let i = from; i < to; i++) primitives.push(src[i]);
|
||||
if (to > from) runs.push({ at, buf: dom.buf, from, to });
|
||||
if (to > from) pieces.push({ buf: dom.buf, from, to });
|
||||
};
|
||||
// Decken, Dächer, Räume; Wände (Poché, Referenzlinie) mit ihren Öffnungs-Symbolen, je Wand
|
||||
// nacheinander; Treppen (Tritte + Lauflinie + Auf-/Abpfeil mit dem Grundriss-Schnitt, über der
|
||||
@@ -428,6 +414,8 @@ export function generatePlan(
|
||||
pushGroups(G_CEILINGS, G_COLUMNS);
|
||||
|
||||
// 2D-Zeichengeometrie zuletzt (über der Poché).
|
||||
const drawingPrims: Primitive[] = [];
|
||||
pieces.push(drawingPrims);
|
||||
const compact = compactUnderlay && !mono && !forPrint;
|
||||
// Kompakte Unterlage PRO KATEGORIE gruppiert: das Ein-/Ausblenden einer Ebene
|
||||
// entfernt dann nur deren Gruppe — die Chunks aller anderen Ebenen bleiben
|
||||
@@ -437,13 +425,13 @@ export function generatePlan(
|
||||
for (const d of drawings) {
|
||||
const greyed = categoryDisplay(d.categoryCode).greyed;
|
||||
if (compact && isCompactUnderlayEligible(d)) {
|
||||
addDrawing2DWithoutLines(primitives, project, d, greyed, lwByCode, colorByCode, catByCode, scaleDenominator);
|
||||
addDrawing2DWithoutLines(drawingPrims, project, d, greyed, lwByCode, colorByCode, catByCode, scaleDenominator);
|
||||
const key = `${greyed ? 1 : 0}:${d.categoryCode}`;
|
||||
const grp = underGroups.get(key);
|
||||
if (grp) grp.ds.push(d);
|
||||
else underGroups.set(key, { ds: [d], greyed });
|
||||
} else {
|
||||
addDrawing2D(primitives, project, d, greyed, lwByCode, colorByCode, catByCode, scaleDenominator, !mono);
|
||||
addDrawing2D(drawingPrims, project, d, greyed, lwByCode, colorByCode, catByCode, scaleDenominator, !mono);
|
||||
}
|
||||
}
|
||||
const underlay: UnderlayGroup[] = [];
|
||||
@@ -474,18 +462,10 @@ export function generatePlan(
|
||||
// Sichtbarkeit über die Kategorie "90" (Referenzen).
|
||||
pushGroups(G_SOLIDS, G_SECTIONS);
|
||||
|
||||
// Schwarz-Weiss (mono): nachträglich alle Farben auf reine Tinte zwingen.
|
||||
// Element-/Kategorie-/Hatch-Farben werden ignoriert, Füllungen werden weiss,
|
||||
// Musterlinien/Striche schwarz — so entsteht ein reiner S/W-Plan.
|
||||
// Abzugskörper (Aussparungen/Durchbrüche): von Wand-/Stützen-/Decken-Poché abziehen.
|
||||
// Ersetzte Primitive erkennt der GPU-Pfad selbst (Identität); verschiebt das Zerlegen die
|
||||
// Indizes, werden die Kern-Abschnitte neu ausgerichtet.
|
||||
if (subtractVoidsInPlan(primitives, project, (floor?.baseElevation ?? 0) + (floor?.cutHeight ?? 1.0))) realignRuns(primitives, runs);
|
||||
|
||||
// Baurechts-Verstösse über allem (Signal, soll nicht unter der Wand-Poché verschwinden).
|
||||
if (includeGlobal) addSiteViolations(primitives, project, floorId);
|
||||
|
||||
if (mono) toMono(primitives);
|
||||
const violations: Primitive[] = [];
|
||||
if (includeGlobal) addSiteViolations(violations, project, floorId);
|
||||
pieces.push(violations);
|
||||
|
||||
// Georeferenzierte Luftbilder als Hintergrund-Ebenen (nur interaktive Ansicht,
|
||||
// nicht Teil der Vektor-Primitive) — im Mono-Modus ausgeblendet (reiner S/W-Plan).
|
||||
@@ -514,13 +494,41 @@ export function generatePlan(
|
||||
ctx: [...g.ctx, lwf],
|
||||
build: (ds: Drawing2D[]) => g.build(ds).map((p) => scalePrimitiveWeights(p, lwf)),
|
||||
}));
|
||||
// Mono färbt die Objekte um, der Massstab ersetzt sie: dann gilt der Puffer nicht mehr.
|
||||
const keepRuns = !mono && lwf === 1 && runs.length > 0;
|
||||
return {
|
||||
primitives: lwf === 1 ? primitives : primitives.map((p) => scalePrimitiveWeights(p, lwf)),
|
||||
const rest = {
|
||||
bounds: computeBounds(project, drawings, dom.buf?.bounds, primitives.slice(0, underlayCount)),
|
||||
backgroundImages,
|
||||
...(scaledUnderlay.length ? { underlay: scaledUnderlay } : {}),
|
||||
};
|
||||
const hasVoids = voidPrisms(project).length > 0;
|
||||
// Ohne Abzugskörper, Mono und Strichstärken-Massstab bleibt der Plan lazy: die Kern-Primitive
|
||||
// werden erst bei Bedarf gelesen.
|
||||
if (!hasVoids && !mono && lwf === 1) return lazyPlan(rest, pieces);
|
||||
|
||||
// Sonst wie bisher als Liste: die Schritte unten verändern Primitive.
|
||||
const all: Primitive[] = [];
|
||||
const runs: PlanBufRun[] = [];
|
||||
for (const pc of pieces) {
|
||||
if (isBufPiece(pc)) {
|
||||
runs.push({ at: all.length, buf: pc.buf, from: pc.from, to: pc.to });
|
||||
for (let i = pc.from; i < pc.to; i++) all.push(pc.buf.prim(i));
|
||||
} else for (const pr of pc) all.push(pr);
|
||||
}
|
||||
// Abzugskörper (Aussparungen/Durchbrüche): von Wand-/Stützen-/Decken-Poché abziehen.
|
||||
// Ersetzte Primitive erkennt der GPU-Pfad selbst (Identität); verschiebt das Zerlegen die
|
||||
// Indizes, werden die Kern-Abschnitte neu ausgerichtet. Die Baurechts-Verstösse liegen über
|
||||
// allem und haben keine Bauteil-Id — das Abziehen lässt sie unverändert.
|
||||
if (hasVoids && subtractVoidsInPlan(all, project, (floor?.baseElevation ?? 0) + (floor?.cutHeight ?? 1.0))) realignRuns(all, runs);
|
||||
|
||||
// Schwarz-Weiss (mono): nachträglich alle Farben auf reine Tinte zwingen.
|
||||
// Element-/Kategorie-/Hatch-Farben werden ignoriert, Füllungen werden weiss,
|
||||
// Musterlinien/Striche schwarz — so entsteht ein reiner S/W-Plan.
|
||||
if (mono) toMono(all);
|
||||
|
||||
// Mono färbt die Objekte um, der Massstab ersetzt sie: dann gilt der Puffer nicht mehr.
|
||||
const keepRuns = !mono && lwf === 1 && runs.length > 0;
|
||||
return {
|
||||
primitives: lwf === 1 ? all : all.map((p) => scalePrimitiveWeights(p, lwf)),
|
||||
...rest,
|
||||
...(keepRuns ? { bufRuns: runs } : {}),
|
||||
};
|
||||
}
|
||||
@@ -593,10 +601,13 @@ export function generateVisibleLevelsPlan(
|
||||
? project.drawingLevels.filter((l) => l.kind === active.kind && l.id !== activeLevelId)
|
||||
: [];
|
||||
|
||||
const primitives: Primitive[] = [];
|
||||
// Stücke der Ebenen hintereinander (lazy, s. `planLazy.ts`): die Primitive werden dabei nicht
|
||||
// gelesen. Früher eine `for`-Schleife statt `push(...p.primitives)` (Argumentzahl-Grenze bei
|
||||
// Kataster-Importen) — die Stücke umgehen beides.
|
||||
const pieces: PlanPiece[] = [];
|
||||
let count = 0;
|
||||
const greyedRanges: Array<[number, number]> = [];
|
||||
const underlay: UnderlayGroup[] = [];
|
||||
const bufRuns: PlanBufRun[] = [];
|
||||
const bounds = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
|
||||
const extend = (b: Plan["bounds"]) => {
|
||||
bounds.minX = Math.min(bounds.minX, b.minX);
|
||||
@@ -624,20 +635,15 @@ export function generateVisibleLevelsPlan(
|
||||
compactUnderlay,
|
||||
);
|
||||
for (const g of p.underlay ?? []) underlay.push({ ...g, tint: d.greyed, above: false });
|
||||
// KEIN `primitives.push(...p.primitives)`: bei grossen Importen (z. B. ein
|
||||
// Kataster-DXF einer ganzen Stadt, hunderttausende Drawing2D-Elemente →
|
||||
// ebenso viele Primitives) sprengt der Spread-Operator die Argumentzahl-
|
||||
// Grenze von `push` (RangeError "Maximum call stack size exceeded") — s.
|
||||
// dieselbe, bereits dokumentierte Falle in `swissBuildings3d.ts::concatMeshes`/
|
||||
// `dwgParser.ts`. Reine `for`-Schleife ist unbegrenzt sicher.
|
||||
const from = primitives.length;
|
||||
for (const pr of p.primitives) primitives.push(pr);
|
||||
shiftRuns(p.bufRuns, from, bufRuns);
|
||||
if (d.greyed && primitives.length > from) greyedRanges.push([from, primitives.length]);
|
||||
const from = count;
|
||||
const n = planCount(p);
|
||||
for (const pc of piecesOf(p)) pieces.push(pc);
|
||||
count += n;
|
||||
if (d.greyed && n > 0) greyedRanges.push([from, count]);
|
||||
// Leere Ebenen melden als Platzhalter (0,0)–(1,1) — NICHT mitzählen: sonst zog
|
||||
// jede leere Nachbar-Ebene den Ausschnitt bis zum Ursprung (bei Landes-
|
||||
// koordinaten ~2,7 Mio. m daneben → "Einpassen" zeigte nichts).
|
||||
if (p.primitives.length > 0 || p.underlay) extend(p.bounds);
|
||||
if (n > 0 || p.underlay) extend(p.bounds);
|
||||
}
|
||||
|
||||
const activePlan = generatePlan(
|
||||
@@ -653,20 +659,21 @@ export function generateVisibleLevelsPlan(
|
||||
false,
|
||||
compactUnderlay,
|
||||
);
|
||||
shiftRuns(activePlan.bufRuns, primitives.length, bufRuns);
|
||||
for (const pr of activePlan.primitives) primitives.push(pr);
|
||||
const activeCount = planCount(activePlan);
|
||||
for (const pc of piecesOf(activePlan)) pieces.push(pc);
|
||||
for (const g of activePlan.underlay ?? []) underlay.push(g);
|
||||
// Aktive Ebene leer UND keine Nachbar-Ebene mit Inhalt → Platzhalter-Ausmass.
|
||||
if (activePlan.primitives.length > 0 || activePlan.underlay || bounds.minX === Infinity) extend(activePlan.bounds);
|
||||
if (activeCount > 0 || activePlan.underlay || bounds.minX === Infinity) extend(activePlan.bounds);
|
||||
|
||||
return {
|
||||
primitives,
|
||||
bounds,
|
||||
backgroundImages: activePlan.backgroundImages,
|
||||
...(greyedRanges.length ? { greyedRanges } : {}),
|
||||
...(underlay.length ? { underlay } : {}),
|
||||
...(bufRuns.length ? { bufRuns } : {}),
|
||||
};
|
||||
return lazyPlan(
|
||||
{
|
||||
bounds,
|
||||
backgroundImages: activePlan.backgroundImages,
|
||||
...(greyedRanges.length ? { greyedRanges } : {}),
|
||||
...(underlay.length ? { underlay } : {}),
|
||||
},
|
||||
pieces,
|
||||
);
|
||||
}
|
||||
|
||||
// ── Schnitt/Ansicht (abgeleitete Projektion aus render3d::section) ──────────────
|
||||
|
||||
@@ -140,7 +140,7 @@ describe("Plan-Puffer v2", () => {
|
||||
const prims = Object.values(PRIMS);
|
||||
const lean = encodePlanBuf(prims, { lean: true });
|
||||
expect(lean.byteLength).toBeLessThan(encodePlanBuf(prims).byteLength);
|
||||
expect(() => decodePlanBuf(lean)).toThrow();
|
||||
expect(() => decodePlanBuf(lean).prims).toThrow();
|
||||
// Die GPU-Kompilierung liest beide gleich.
|
||||
const a = core().gpu_compile_flat(lean, 0, prims.length, 90, true);
|
||||
const b = core().gpu_compile_flat(encodePlanBuf(prims), 0, prims.length, 90, true);
|
||||
|
||||
+56
-13
@@ -446,10 +446,21 @@ export function encodePlanBuf(prims: readonly Primitive[], opts: EncodeOptions =
|
||||
return new Uint8Array(out);
|
||||
}
|
||||
|
||||
/** Gelesener Plan-Puffer (Kern-Ergebnis); `bytes` bleibt für die GPU-Kompilierung erhalten. */
|
||||
/**
|
||||
* Gelesener Plan-Puffer (Kern-Ergebnis); `bytes` bleibt für die GPU-Kompilierung erhalten.
|
||||
* Die Primitive entstehen erst bei Bedarf ([K3d]): `prim(i)` liest einen Eintrag, `prims` alle
|
||||
* (dieselben Objekte — einmal gelesen, bleibt ein Eintrag dasselbe Objekt).
|
||||
*/
|
||||
export interface DecodedPlanBuf {
|
||||
bytes: Uint8Array;
|
||||
prims: Primitive[];
|
||||
/** Alle Primitive (beim ersten Zugriff gelesen). */
|
||||
readonly prims: Primitive[];
|
||||
/** Anzahl Einträge. */
|
||||
count: number;
|
||||
/** Eintrag `i` als Primitiv (gelesen bei Bedarf, danach gemerkt). */
|
||||
prim(i: number): Primitive;
|
||||
/** Typ-Kennung des Eintrags `i` (1 polygon · 2 line · … · 6 text · 7 drawingText · 8 drawingTextPath · 9 drawingImage). */
|
||||
tag(i: number): number;
|
||||
groups: Array<[number, number]>;
|
||||
bounds?: [number, number, number, number];
|
||||
/** Inhalts-Hash je Primitiv (vom Kern; Schlüssel des GPU-Chunk-Caches) oder null. */
|
||||
@@ -458,7 +469,6 @@ export interface DecodedPlanBuf {
|
||||
hold: number;
|
||||
}
|
||||
|
||||
/** UTF-16-Einheiten → ein String (exakt, auch einzelne Surrogate). */
|
||||
function unitsToString(u: Uint16Array): string {
|
||||
let s = "";
|
||||
for (let i = 0; i < u.length; i += 8192) {
|
||||
@@ -499,11 +509,13 @@ export function decodePlanBuf(input: Uint8Array): DecodedPlanBuf {
|
||||
const nF64 = poolAt + nPool;
|
||||
if (!Number.isInteger(nF64) || bytes.byteLength !== nF64 * 8 + nUnits * 2) bad("Länge");
|
||||
const f = new Float64Array(bytes.buffer, bytes.byteOffset, nF64);
|
||||
const all = unitsToString(new Uint16Array(bytes.buffer, bytes.byteOffset + nF64 * 8, nUnits));
|
||||
// Texte erst beim ersten Zugriff als ein String gelesen.
|
||||
let all: string | null = null;
|
||||
const strs: Array<string | undefined> = new Array(nStrings);
|
||||
const S = (i: number): string => {
|
||||
let s = strs[i];
|
||||
if (s === undefined) {
|
||||
all ??= unitsToString(new Uint16Array(bytes.buffer, bytes.byteOffset + nF64 * 8, nUnits));
|
||||
const o = f[strAt + 2 * i];
|
||||
s = all.slice(o, o + f[strAt + 2 * i + 1]);
|
||||
strs[i] = s;
|
||||
@@ -511,13 +523,23 @@ export function decodePlanBuf(input: Uint8Array): DecodedPlanBuf {
|
||||
return s;
|
||||
};
|
||||
// Schraffuren: einmal je Eintrag aus dem JSON (geteilt von allen Polygonen).
|
||||
const hatchList: HatchRender[] = [];
|
||||
// JSON je Schraffur erst beim ersten Polygon, das sie braucht (dann geteilt).
|
||||
const hatchJs: number[] = [];
|
||||
const hatchObjs: Array<HatchRender | undefined> = new Array(nHatches);
|
||||
const hatchAtIdx = (h: number): HatchRender => {
|
||||
let o = hatchObjs[h];
|
||||
if (o === undefined) {
|
||||
const js = hatchJs[h];
|
||||
o = js >= 0 ? (JSON.parse(S(js)) as HatchRender) : (undefined as unknown as HatchRender);
|
||||
hatchObjs[h] = o;
|
||||
}
|
||||
return o;
|
||||
};
|
||||
let k = hatchAt;
|
||||
for (let i = 0; i < nHatches; i++) {
|
||||
// [jsonStr, pattern, kind, flags, scale, angle, color, lineWeight, ox, oy, seed, density,
|
||||
// lengthMin, lengthMax, nDash, dash…, (Motiv: length, nPts, x,y…)]
|
||||
const js = f[k];
|
||||
hatchList.push(js >= 0 ? (JSON.parse(S(js)) as HatchRender) : (undefined as unknown as HatchRender));
|
||||
hatchJs.push(f[k]);
|
||||
const hf = f[k + 3];
|
||||
k += 15 + f[k + 14];
|
||||
if (hf & 64) k += 2 + 2 * f[k + 1];
|
||||
@@ -551,8 +573,7 @@ export function decodePlanBuf(input: Uint8Array): DecodedPlanBuf {
|
||||
found.sort((a, b) => a[0] - b[0]);
|
||||
for (const [kk, id] of found) o[PICK_KEYS[kk - 1]] = id;
|
||||
};
|
||||
const prims: Primitive[] = new Array(nPrims);
|
||||
for (let i = 0; i < nPrims; i++) {
|
||||
const read = (i: number): Primitive => {
|
||||
let r = recAt + f[offAt + i];
|
||||
const tag = f[r];
|
||||
const fl = f[r + 1];
|
||||
@@ -563,7 +584,7 @@ export function decodePlanBuf(input: Uint8Array): DecodedPlanBuf {
|
||||
switch (tag) {
|
||||
case 1: {
|
||||
o = { kind: "polygon", pts: pts(f[r + 5], f[r + 6]), fill: S(f[r]), stroke: S(f[r + 1]), strokeWidthMm: f[r + 2] };
|
||||
if (f[r + 3] >= 0) o.hatch = hatchList[f[r + 3]];
|
||||
if (f[r + 3] >= 0) o.hatch = hatchAtIdx(f[r + 3]);
|
||||
if (fl & F_GREYED_SET) o.greyed = (fl & F_GREYED) !== 0;
|
||||
if (fl & F_OPACITY) o.opacity = f[r + 4];
|
||||
let t = r + 7;
|
||||
@@ -653,11 +674,33 @@ export function decodePlanBuf(input: Uint8Array): DecodedPlanBuf {
|
||||
default:
|
||||
bad(`Primitiv-Typ ${tag}`);
|
||||
}
|
||||
prims[i] = o as unknown as Primitive;
|
||||
}
|
||||
return o as unknown as Primitive;
|
||||
};
|
||||
// Einmal gelesene Einträge bleiben dieselben Objekte (Identität zählt für `Plan.bufRuns`).
|
||||
const cache: Array<Primitive | undefined> = new Array(nPrims);
|
||||
const prim = (i: number): Primitive => {
|
||||
if (!(i >= 0 && i < nPrims)) bad(`Eintrag ${i}`);
|
||||
let p = cache[i];
|
||||
if (p === undefined) {
|
||||
p = read(i);
|
||||
cache[i] = p;
|
||||
}
|
||||
return p;
|
||||
};
|
||||
let allPrims: Primitive[] | null = null;
|
||||
return {
|
||||
bytes,
|
||||
prims,
|
||||
get prims(): Primitive[] {
|
||||
if (!allPrims) {
|
||||
const out: Primitive[] = new Array(nPrims);
|
||||
for (let i = 0; i < nPrims; i++) out[i] = prim(i);
|
||||
allPrims = out;
|
||||
}
|
||||
return allPrims;
|
||||
},
|
||||
count: nPrims,
|
||||
prim,
|
||||
tag: (i: number): number => f[recAt + f[offAt + i]],
|
||||
groups,
|
||||
bounds: flags & 2 ? [hd[12], hd[13], hd[14], hd[15]] : undefined,
|
||||
hashes: hashes ? new Float64Array(bytes.buffer, bytes.byteOffset + hashAt * 8, nPrims) : null,
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
// Lazy Plan ([K3d], `planLazy.ts`): `generatePlan` liest die Kern-Primitive erst bei Bedarf; die
|
||||
// Verbraucher im Kern (Szene, Auswahl, SVG, DXF, Druck-SVG) und die Text-Einträge kommen ohne aus.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { generatePlan, generateVisibleLevelsPlan, materializeUnderlay, type Primitive } from "./generatePlan";
|
||||
import { isLazyUnread, planCount, planPrimAt, planTextEntries, planWithExtra } from "./planLazy";
|
||||
import { planSceneBin, planToRenderScene } from "./toRenderScene";
|
||||
import { planToSvgString } from "../export/planToSvgString";
|
||||
import { PlanPickIndex } from "./planView/planPick";
|
||||
import { collectPlanDrawing } from "../export/exportDxf";
|
||||
import { planToPrintSvg } from "../export/planToPrintSvg";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { flattenCategories, type Project } from "../model/types";
|
||||
|
||||
const codes = (p: Project) => new Set(flattenCategories(p.layers).map((c) => c.code));
|
||||
|
||||
const withText: Project = {
|
||||
...sampleProject,
|
||||
drawings2d: [
|
||||
...sampleProject.drawings2d,
|
||||
{ id: "t1", type: "drawing2d", levelId: "eg", categoryCode: "60", geom: { shape: "text", at: { x: 1, y: 2 }, text: "Hallo", height: 0.3, angle: 0 } },
|
||||
{ id: "l1", type: "drawing2d", levelId: "eg", categoryCode: "60", geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 3, y: 1 } } },
|
||||
] as Project["drawings2d"],
|
||||
};
|
||||
|
||||
describe("lazy Plan", () => {
|
||||
it("Verbraucher im Kern lesen die Primitive nicht", () => {
|
||||
const plan = generatePlan(withText, "eg", codes(withText));
|
||||
expect(isLazyUnread(plan)).toBe(true);
|
||||
planSceneBin(plan);
|
||||
planToRenderScene(plan);
|
||||
planToSvgString(plan);
|
||||
const ix = new PlanPickIndex(plan);
|
||||
ix.topPolygon({ x: 2, y: 2 });
|
||||
ix.marquee("wallId", { minX: -100, minY: -100, maxX: 100, maxY: 100 }, false);
|
||||
expect(ix.drawingTextAt({ x: 1.2, y: 2 })).not.toBeNull();
|
||||
ix.release();
|
||||
expect(collectPlanDrawing(plan, withText).stats().model.TEXT).toBeGreaterThan(0);
|
||||
// Druck-SVG mit minimalem DOM-Ersatz (Node ohne DOM).
|
||||
const el = (): Record<string, unknown> => ({ setAttribute() {}, appendChild: (c: unknown) => c, insertBefore: (c: unknown) => c, querySelector: () => null, firstChild: null });
|
||||
const g = globalThis as { document?: unknown };
|
||||
const prev = g.document;
|
||||
g.document = { createElementNS: () => el() };
|
||||
try {
|
||||
planToPrintSvg(plan, { scaleDenominator: 100, pageWidthMm: 420, pageHeightMm: 297 });
|
||||
} finally {
|
||||
g.document = prev;
|
||||
}
|
||||
expect(planTextEntries(plan).length).toBeGreaterThan(0);
|
||||
expect(planPrimAt(plan, 0)).toBeDefined();
|
||||
expect(isLazyUnread(plan)).toBe(true);
|
||||
});
|
||||
|
||||
it("Einzelzugriff, Text-Einträge und Anzahl == gelesene Liste (dieselben Objekte)", () => {
|
||||
for (const l of ["eg", "og"]) {
|
||||
const plan = generatePlan(withText, l, codes(withText));
|
||||
const n = planCount(plan);
|
||||
const single = Array.from({ length: n }, (_, i) => planPrimAt(plan, i));
|
||||
const texts = planTextEntries(plan);
|
||||
expect(plan.primitives.length).toBe(n);
|
||||
single.forEach((p, i) => expect(p).toBe(plan.primitives[i]));
|
||||
const want = plan.primitives
|
||||
.map((p, i) => ({ p, i }))
|
||||
.filter((e) => e.p.kind === "text" || e.p.kind === "drawingText" || e.p.kind === "drawingTextPath" || e.p.kind === "drawingImage");
|
||||
expect(texts.map((e) => e.i)).toEqual(want.map((e) => e.i));
|
||||
texts.forEach((e, k) => expect(e.p).toBe(want[k].p));
|
||||
expect(planPrimAt(plan, n)).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it("Überlagerung, kompakte Unterlage und Anhängen bleiben lazy und gleich", () => {
|
||||
const plan = generateVisibleLevelsPlan(withText, "og", codes(withText), undefined, "mittel", false, false, undefined, 100, true);
|
||||
expect(isLazyUnread(plan)).toBe(true);
|
||||
const mat = materializeUnderlay(plan);
|
||||
const extra: Primitive = { kind: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 1 }, cls: "x", weightMm: 0.1 };
|
||||
const ext = planWithExtra(mat, [extra], [extra]);
|
||||
expect(isLazyUnread(mat) && isLazyUnread(ext)).toBe(true);
|
||||
expect(ext.primitives).toEqual([extra, ...mat.primitives, extra]);
|
||||
expect(ext.greyedRanges).toEqual(mat.greyedRanges?.map(([a, b]) => [a + 1, b + 1]));
|
||||
// Eager zum Vergleich: dieselbe Liste wie die gelesene.
|
||||
expect(plan.primitives.length).toBe(planCount(plan));
|
||||
});
|
||||
|
||||
it("Mono bleibt eine gewöhnliche Liste", () => {
|
||||
const plan = generatePlan(sampleProject, "eg", codes(sampleProject), undefined, "mittel", false, true);
|
||||
expect(isLazyUnread(plan)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,216 @@
|
||||
/**
|
||||
* Plan mit lazy gelesenen Primitiven ([K3d]): `generatePlan` setzt einen Plan aus Stücken zusammen
|
||||
* — Abschnitten eines Kern-Plan-Puffers (`planDomains`) und Listen, die TS selbst erzeugt
|
||||
* (2D-Zeichnungen, Schatten, Baurecht). `plan.primitives` entsteht erst beim ersten Zugriff; die
|
||||
* Verbraucher im Kern (Szene, Auswahl, Fang, SVG, DXF) lesen die Stücke direkt (`planParts.ts`),
|
||||
* Einzelzugriffe gehen über {@link planPrimAt}, Texte/Bilder über {@link planTextEntries}.
|
||||
*
|
||||
* Wer einen Plan umbaut (`{ ...plan, primitives: … }`), bekommt einen gewöhnlichen Plan; die
|
||||
* Stücke gelten nur für das Objekt, das {@link lazyPlan} erzeugt hat. Die gelesene Liste
|
||||
* `primitives` eines solchen Plans wird nicht verändert (Konvention wie bei allen Plänen).
|
||||
*/
|
||||
|
||||
import type { Plan, PlanBufRun, Primitive } from "./generatePlan";
|
||||
import type { DecodedPlanBuf } from "./planBuf";
|
||||
|
||||
/** Abschnitt `[from, to)` eines Kern-Puffers. */
|
||||
export interface BufPiece {
|
||||
buf: DecodedPlanBuf;
|
||||
from: number;
|
||||
to: number;
|
||||
}
|
||||
|
||||
/** Ein Stück: Kern-Abschnitt oder eine Liste von TS-Primitiven. */
|
||||
export type PlanPiece = BufPiece | readonly Primitive[];
|
||||
|
||||
export function isBufPiece(p: PlanPiece): p is BufPiece {
|
||||
return !Array.isArray(p);
|
||||
}
|
||||
|
||||
const pieceLen = (p: PlanPiece): number => (isBufPiece(p) ? p.to - p.from : p.length);
|
||||
|
||||
interface LazyState {
|
||||
pieces: PlanPiece[];
|
||||
/** Erster Plan-Index je Stück. */
|
||||
starts: number[];
|
||||
count: number;
|
||||
}
|
||||
|
||||
const lazyState = new WeakMap<Plan, LazyState>();
|
||||
/** Lazy Pläne, deren `primitives` schon gelesen wurden. */
|
||||
const readPlans = new WeakSet<Plan>();
|
||||
|
||||
/**
|
||||
* Plan aus Stücken; `primitives` wird beim ersten Zugriff gelesen (und bleibt dann dieselbe
|
||||
* Liste). `bufRuns` folgen aus den Kern-Abschnitten.
|
||||
*/
|
||||
export function lazyPlan(rest: Omit<Plan, "primitives" | "bufRuns">, pieces: readonly PlanPiece[]): Plan {
|
||||
const ps: PlanPiece[] = [];
|
||||
for (const p of pieces) {
|
||||
// Leere Stücke weglassen; Kern-Abschnitte bleiben getrennt wie erzeugt (Chunk-Grenzen der GPU).
|
||||
if (pieceLen(p) > 0) ps.push(p);
|
||||
}
|
||||
const starts: number[] = [];
|
||||
const runs: PlanBufRun[] = [];
|
||||
let count = 0;
|
||||
for (const p of ps) {
|
||||
starts.push(count);
|
||||
if (isBufPiece(p)) runs.push({ at: count, buf: p.buf, from: p.from, to: p.to });
|
||||
count += pieceLen(p);
|
||||
}
|
||||
const plan = {} as Plan;
|
||||
let mat: Primitive[] | null = null;
|
||||
Object.defineProperty(plan, "primitives", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
get(): Primitive[] {
|
||||
if (!mat) {
|
||||
const out: Primitive[] = new Array(count);
|
||||
let k = 0;
|
||||
for (const p of ps) {
|
||||
if (isBufPiece(p)) {
|
||||
for (let i = p.from; i < p.to; i++) out[k++] = p.buf.prim(i);
|
||||
} else {
|
||||
for (const q of p) out[k++] = q;
|
||||
}
|
||||
}
|
||||
mat = out;
|
||||
readPlans.add(plan);
|
||||
}
|
||||
return mat;
|
||||
},
|
||||
set(v: Primitive[]) {
|
||||
// Ersetzt: ab jetzt ein gewöhnlicher Plan.
|
||||
Object.defineProperty(plan, "primitives", { value: v, writable: true, enumerable: true, configurable: true });
|
||||
lazyState.delete(plan);
|
||||
},
|
||||
});
|
||||
Object.assign(plan, rest);
|
||||
if (runs.length) plan.bufRuns = runs;
|
||||
else delete plan.bufRuns;
|
||||
lazyState.set(plan, { pieces: ps, starts, count });
|
||||
return plan;
|
||||
}
|
||||
|
||||
/** Stücke eines lazy Plans (oder null bei einem gewöhnlichen Plan). */
|
||||
export function lazyPieces(plan: Plan): readonly PlanPiece[] | null {
|
||||
return lazyState.get(plan)?.pieces ?? null;
|
||||
}
|
||||
|
||||
/** Ist `plan` ein lazy Plan, dessen `primitives` noch nicht gelesen wurden? (Messung/Tests.) */
|
||||
export function isLazyUnread(plan: Plan): boolean {
|
||||
return lazyState.has(plan) && !readPlans.has(plan);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stücke eines beliebigen Plans: lazy → seine Stücke; sonst die Liste, an den (per
|
||||
* Objekt-Identität geprüften) Kern-Abschnitten `bufRuns` zerlegt.
|
||||
*/
|
||||
export function piecesOf(plan: Plan): readonly PlanPiece[] {
|
||||
const lazy = lazyPieces(plan);
|
||||
if (lazy) return lazy;
|
||||
const prims = plan.primitives;
|
||||
const out: PlanPiece[] = [];
|
||||
let at = 0;
|
||||
const runs = [...(plan.bufRuns ?? [])].sort((a, b) => a.at - b.at);
|
||||
for (const r of runs) {
|
||||
if (r.at < at) continue;
|
||||
const n = Math.min(r.to - r.from, prims.length - r.at);
|
||||
let ok = n > 0;
|
||||
for (let k = 0; ok && k < n; k++) ok = prims[r.at + k] === r.buf.prims[r.from + k];
|
||||
if (!ok) continue;
|
||||
if (r.at > at) out.push(prims.slice(at, r.at));
|
||||
out.push({ buf: r.buf, from: r.from, to: r.from + n });
|
||||
at = r.at + n;
|
||||
}
|
||||
if (at < prims.length) out.push(at === 0 ? prims : prims.slice(at));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Anzahl Primitive (ohne sie zu lesen). */
|
||||
export function planCount(plan: Plan): number {
|
||||
const s = lazyState.get(plan);
|
||||
return s ? s.count : plan.primitives.length;
|
||||
}
|
||||
|
||||
/** Primitiv `i` (bei einem lazy Plan nur dieser Eintrag gelesen); `undefined` ausserhalb. */
|
||||
export function planPrimAt(plan: Plan, i: number): Primitive | undefined {
|
||||
const s = lazyState.get(plan);
|
||||
if (!s) return plan.primitives[i];
|
||||
if (!(i >= 0 && i < s.count) || !Number.isInteger(i)) return undefined;
|
||||
// Letztes Stück mit Start ≤ i.
|
||||
let lo = 0;
|
||||
let hi = s.starts.length - 1;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi + 1) >> 1;
|
||||
if (s.starts[mid] <= i) lo = mid;
|
||||
else hi = mid - 1;
|
||||
}
|
||||
const p = s.pieces[lo];
|
||||
const k = i - s.starts[lo];
|
||||
return isBufPiece(p) ? p.buf.prim(p.from + k) : p[k];
|
||||
}
|
||||
|
||||
/** Text-/Bild-Primitive (`text`, `drawingText`, `drawingTextPath`, `drawingImage`). */
|
||||
export type TextEntryPrim = Extract<Primitive, { kind: "text" | "drawingText" | "drawingTextPath" | "drawingImage" }>;
|
||||
|
||||
/** Typ-Kennungen der Text-/Bild-Einträge im Plan-Puffer (6…9, s. `plan_buf.rs`). */
|
||||
const TEXT_TAG_MIN = 6;
|
||||
const TEXT_TAG_MAX = 9;
|
||||
|
||||
const isTextKind = (p: Primitive): p is TextEntryPrim =>
|
||||
p.kind === "text" || p.kind === "drawingText" || p.kind === "drawingTextPath" || p.kind === "drawingImage";
|
||||
|
||||
const textCache = new WeakMap<Plan, ReadonlyArray<{ i: number; p: TextEntryPrim }>>();
|
||||
|
||||
/**
|
||||
* Text- und Bild-Einträge eines Plans in Zeichenreihenfolge mit ihrem Plan-Index — bei einem
|
||||
* lazy Plan aus den Typ-Kennungen der Puffer gelesen (nur diese Einträge werden dekodiert).
|
||||
* Einmal je Plan.
|
||||
*/
|
||||
export function planTextEntries(plan: Plan): ReadonlyArray<{ i: number; p: TextEntryPrim }> {
|
||||
let out = textCache.get(plan);
|
||||
if (out) return out;
|
||||
const list: Array<{ i: number; p: TextEntryPrim }> = [];
|
||||
const s = lazyState.get(plan);
|
||||
if (s) {
|
||||
s.pieces.forEach((pc, n) => {
|
||||
const at = s.starts[n];
|
||||
if (isBufPiece(pc)) {
|
||||
for (let j = pc.from; j < pc.to; j++) {
|
||||
const t = pc.buf.tag(j);
|
||||
if (t >= TEXT_TAG_MIN && t <= TEXT_TAG_MAX) list.push({ i: at + j - pc.from, p: pc.buf.prim(j) as TextEntryPrim });
|
||||
}
|
||||
} else {
|
||||
pc.forEach((p, k) => {
|
||||
if (isTextKind(p)) list.push({ i: at + k, p });
|
||||
});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
plan.primitives.forEach((p, i) => {
|
||||
if (isTextKind(p)) list.push({ i, p });
|
||||
});
|
||||
}
|
||||
out = list;
|
||||
textCache.set(plan, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan um Primitive davor/danach ergänzt, ohne die Primitive des Plans zu lesen (Überlagerungen
|
||||
* der Ansicht). Gedimmte Bereiche wandern mit.
|
||||
*/
|
||||
export function planWithExtra(plan: Plan, before: readonly Primitive[], after: readonly Primitive[], patch: Partial<Omit<Plan, "primitives" | "bufRuns">> = {}): Plan {
|
||||
const rest = planFields(plan);
|
||||
const shift = before.length;
|
||||
const greyed = plan.greyedRanges?.map(([a, b]): [number, number] => [a + shift, b + shift]);
|
||||
return lazyPlan({ ...rest, ...(greyed ? { greyedRanges: greyed } : {}), ...patch }, [before, ...piecesOf(plan), after]);
|
||||
}
|
||||
|
||||
/** Alle Felder eines Plans ausser `primitives` und `bufRuns`, ohne den Getter auszulösen. */
|
||||
export function planFields(plan: Plan): Omit<Plan, "primitives" | "bufRuns"> {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const k of Object.keys(plan)) if (k !== "primitives" && k !== "bufRuns") out[k] = (plan as unknown as Record<string, unknown>)[k];
|
||||
return out as unknown as Omit<Plan, "primitives" | "bufRuns">;
|
||||
}
|
||||
+46
-11
@@ -13,6 +13,7 @@
|
||||
|
||||
import type { Plan, PlanBufRun, Primitive } from "./generatePlan";
|
||||
import { encodePlanBuf } from "./planBuf";
|
||||
import { isBufPiece, lazyPieces, type PlanPiece } from "./planLazy";
|
||||
import { core } from "../engine/coreWasm";
|
||||
|
||||
/** Ein im Kern ablegbarer Puffer (Kern-Ergebnis `DecodedPlanBuf` oder eigener). */
|
||||
@@ -54,21 +55,58 @@ function verifiedRuns(primitives: readonly Primitive[], runs: readonly PlanBufRu
|
||||
return clean;
|
||||
}
|
||||
|
||||
const cache = new WeakMap<readonly Primitive[], { text: PlanParts | null; noText: PlanParts | null }>();
|
||||
const cache = new WeakMap<object, { text: PlanParts | null; noText: PlanParts | null }>();
|
||||
|
||||
/**
|
||||
* Abschnitte eines Plans; einmal je `plan.primitives` (und Modus) gebaut. `texts`: der eigene
|
||||
* Puffer trägt Texte/Bilder mit JSON (SVG-Export) — sonst nur deren Typ (Szene, Auswahl).
|
||||
* Abschnitte eines Plans; einmal je Plan (lazy, s. `planLazy.ts`) bzw. je `plan.primitives` (und
|
||||
* Modus) gebaut. `texts`: der eigene Puffer trägt Texte/Bilder und Schraffuren mit JSON (SVG-/DXF-Export, Auswahl) —
|
||||
* sonst nur deren Typ (Szene). Ein lazy Plan wird dabei nicht gelesen.
|
||||
*/
|
||||
export function planParts(plan: Plan, texts = false): PlanParts {
|
||||
const prims = plan.primitives;
|
||||
let c = cache.get(prims);
|
||||
const lazy = lazyPieces(plan);
|
||||
const key: object = lazy ? plan : plan.primitives;
|
||||
let c = cache.get(key);
|
||||
if (!c) {
|
||||
c = { text: null, noText: null };
|
||||
cache.set(prims, c);
|
||||
cache.set(key, c);
|
||||
}
|
||||
const hit = texts ? c.text : c.noText;
|
||||
if (hit) return hit;
|
||||
const out = lazy ? partsFromPieces(lazy, texts) : partsFromRuns(plan, texts);
|
||||
if (texts) c.text = out;
|
||||
else c.noText = out;
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Abschnitte aus den Stücken eines lazy Plans: TS-Listen zusammen in einen eigenen Puffer. */
|
||||
function partsFromPieces(pieces: readonly PlanPiece[], texts: boolean): PlanParts {
|
||||
const rest: Primitive[] = [];
|
||||
for (const pc of pieces) if (!isBufPiece(pc)) for (const p of pc) rest.push(p);
|
||||
const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts, hatchJson: texts }), hold: 0 } : null;
|
||||
const bufs: HoldableBuf[] = [];
|
||||
const segs: number[] = [];
|
||||
let ownAt = 0;
|
||||
let count = 0;
|
||||
for (const pc of pieces) {
|
||||
if (isBufPiece(pc)) {
|
||||
let i = bufs.indexOf(pc.buf);
|
||||
if (i < 0) i = bufs.push(pc.buf) - 1;
|
||||
segs.push(i, pc.from, pc.to);
|
||||
count += pc.to - pc.from;
|
||||
} else if (pc.length) {
|
||||
let i = bufs.indexOf(own!);
|
||||
if (i < 0) i = bufs.push(own!) - 1;
|
||||
segs.push(i, ownAt, ownAt + pc.length);
|
||||
ownAt += pc.length;
|
||||
count += pc.length;
|
||||
}
|
||||
}
|
||||
return { bufs, segs, count };
|
||||
}
|
||||
|
||||
/** Abschnitte eines gewöhnlichen Plans über die (per Objekt-Identität geprüften) `bufRuns`. */
|
||||
function partsFromRuns(plan: Plan, texts: boolean): PlanParts {
|
||||
const prims = plan.primitives;
|
||||
const runs = verifiedRuns(prims, plan.bufRuns);
|
||||
const bufs: HoldableBuf[] = [];
|
||||
const bufIdx = new Map<HoldableBuf, number>();
|
||||
@@ -95,7 +133,7 @@ export function planParts(plan: Plan, texts = false): PlanParts {
|
||||
at = r.end;
|
||||
}
|
||||
gap(prims.length);
|
||||
const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts, hatchJson: false }), hold: 0 } : null;
|
||||
const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts, hatchJson: texts }), hold: 0 } : null;
|
||||
const segs: number[] = [];
|
||||
let gi = 0;
|
||||
let ri = 0;
|
||||
@@ -111,10 +149,7 @@ export function planParts(plan: Plan, texts = false): PlanParts {
|
||||
ri++;
|
||||
}
|
||||
}
|
||||
const out: PlanParts = { bufs, segs, count: prims.length };
|
||||
if (texts) c.text = out;
|
||||
else c.noText = out;
|
||||
return out;
|
||||
return { bufs, segs, count: prims.length };
|
||||
}
|
||||
|
||||
/** Gedimmte Bereiche flach (`Plan.greyedRanges`). */
|
||||
|
||||
@@ -1,13 +1,24 @@
|
||||
/**
|
||||
* `marqueeHitDrawings` — Rahmenauswahl von 2D-Zeichenelementen. Vorher fehlten
|
||||
* Rahmenauswahl von 2D-Zeichenelementen (`PlanPickIndex.marqueeDrawings`). Vorher fehlten
|
||||
* drawingCircle/drawingArc/drawingText/drawingImage komplett (nur line/polygon
|
||||
* abgedeckt) — Regressionsschutz für den Nachzieh-Fix (2D-Vervollständigung,
|
||||
* Fund A).
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { marqueeHitDrawings, type ModelRect } from "./geometry";
|
||||
import type { ModelRect } from "./geometry";
|
||||
import type { Primitive } from "../generatePlan";
|
||||
import { PlanPickIndex } from "./planPick";
|
||||
|
||||
/** Rahmen-Auswahl über 2D-Zeichnungen im Kern ([K3d], `PlanPickIndex.marqueeDrawings`). */
|
||||
function marqueeHitDrawings(prims: Primitive[], rect: ModelRect, crossing: boolean): string[] {
|
||||
const ix = new PlanPickIndex({ primitives: prims, bounds: { minX: 0, minY: 0, maxX: 1, maxY: 1 } });
|
||||
try {
|
||||
return ix.marqueeDrawings(rect, crossing);
|
||||
} finally {
|
||||
ix.release();
|
||||
}
|
||||
}
|
||||
|
||||
const encloseRect: ModelRect = { minX: -10, minY: -10, maxX: 10, maxY: 10 };
|
||||
const missRect: ModelRect = { minX: 20, minY: 20, maxX: 30, maxY: 30 };
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
// Keine JSX, kein Komponenten-/Closure-Zugriff — pure Funktionen + Konstanten.
|
||||
|
||||
import type { Vec2 } from "../../model/types";
|
||||
import type { Primitive } from "../generatePlan";
|
||||
|
||||
/** Rechteckiger Ausschnitt in SVG-Benutzerkoordinaten (viewBox-Einheiten). */
|
||||
export interface ViewBox {
|
||||
@@ -231,142 +230,9 @@ export interface ModelRect {
|
||||
maxY: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bestimmt die vom Auswahl-Rechteck getroffenen Wand-IDs nach CAD-Konvention:
|
||||
* • crossing = false (links→rechts): nur Wände, deren Polygone VOLLSTÄNDIG im
|
||||
* Rechteck liegen (jeder Eckpunkt enthalten).
|
||||
* • crossing = true (rechts→links): zusätzlich Wände, die das Rechteck nur
|
||||
* BERÜHREN/kreuzen (Überlappung der Polygone mit dem Rechteck).
|
||||
* Getestet wird je Wand über ALLE ihre Polygon-Bänder; ein Treffer eines Bandes
|
||||
* genügt. Liefert eindeutige IDs in Auftreten-Reihenfolge.
|
||||
*/
|
||||
export function marqueeHit(
|
||||
prims: Primitive[],
|
||||
rect: ModelRect,
|
||||
crossing: boolean,
|
||||
): string[] {
|
||||
return marqueeHitByField(prims, "wallId", rect, crossing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generische Variante von {@link marqueeHit} für ein beliebiges Polygon-ID-
|
||||
* Feld (`ceilingId`/`roomId`/`stairId`/`columnId`/`roofId`/…) — dieselbe
|
||||
* window/crossing-Konvention, nur auf ein anderes Element bezogen. Deckt
|
||||
* Nutzer-Report: „Auswahlrahmen kann Decken/Räume/Treppen nicht anwählen"
|
||||
* (bisher nur Wände über `marqueeHit`, alles andere fehlte komplett).
|
||||
*/
|
||||
function marqueeHitByField(
|
||||
prims: Primitive[],
|
||||
field: "wallId" | "ceilingId" | "roomId" | "stairId" | "columnId" | "roofId",
|
||||
rect: ModelRect,
|
||||
crossing: boolean,
|
||||
): string[] {
|
||||
const byId = new Map<string, Vec2[][]>();
|
||||
for (const p of prims) {
|
||||
if (p.kind !== "polygon") continue;
|
||||
const id = p[field];
|
||||
if (id == null) continue;
|
||||
const list = byId.get(id);
|
||||
if (list) list.push(p.pts);
|
||||
else byId.set(id, [p.pts]);
|
||||
}
|
||||
const out: string[] = [];
|
||||
for (const [id, polys] of byId) {
|
||||
const hit = crossing
|
||||
? polys.some((poly) => polyTouchesRect(poly, rect))
|
||||
: polys.every((poly) => polyEnclosedByRect(poly, rect));
|
||||
if (hit) out.push(id);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Vom Auswahl-Rechteck getroffene Decken-IDs (gleiche Konvention wie {@link marqueeHit}). */
|
||||
export function marqueeHitCeilings(prims: Primitive[], rect: ModelRect, crossing: boolean): string[] {
|
||||
return marqueeHitByField(prims, "ceilingId", rect, crossing);
|
||||
}
|
||||
|
||||
/** Vom Auswahl-Rechteck getroffene Raum-IDs (gleiche Konvention wie {@link marqueeHit}). */
|
||||
export function marqueeHitRooms(prims: Primitive[], rect: ModelRect, crossing: boolean): string[] {
|
||||
return marqueeHitByField(prims, "roomId", rect, crossing);
|
||||
}
|
||||
|
||||
/** Vom Auswahl-Rechteck getroffene Treppen-IDs (gleiche Konvention wie {@link marqueeHit}). */
|
||||
export function marqueeHitStairs(prims: Primitive[], rect: ModelRect, crossing: boolean): string[] {
|
||||
return marqueeHitByField(prims, "stairId", rect, crossing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vom Auswahl-Rechteck getroffene 2D-Zeichenelement-IDs (gleiche window/crossing-
|
||||
* Konvention wie {@link marqueeHit}). Sammelt je Drawing2D ALLE seine Punkte aus
|
||||
* den Linien-/Polygon-Primitiven; crossing = irgendein Punkt/Kante im Rechteck,
|
||||
* window = alle Punkte vollständig eingeschlossen.
|
||||
*/
|
||||
/** Punkte auf einem Kreis-/Bogen-Ring (Modell-Meter), für Marquee-Zwecke abgetastet. */
|
||||
function ringSamplePoints(center: Vec2, r: number, a0?: number, a1?: number): Vec2[] {
|
||||
const TAU = Math.PI * 2;
|
||||
const full = a0 === undefined || a1 === undefined;
|
||||
const start = full ? 0 : a0;
|
||||
const sweep = full ? TAU : (((a1 - a0) % TAU) + TAU) % TAU || TAU;
|
||||
const steps = full ? 32 : Math.max(4, Math.round((sweep / TAU) * 32));
|
||||
const pts: Vec2[] = [];
|
||||
for (let i = 0; i <= steps; i++) {
|
||||
const a = start + (sweep * i) / steps;
|
||||
pts.push({ x: center.x + r * Math.cos(a), y: center.y + r * Math.sin(a) });
|
||||
}
|
||||
return pts;
|
||||
}
|
||||
|
||||
/** Bounding-Box-Eckpunkte eines `drawingText`-Primitivs, analog zur Einzelklick-Bbox in PlanView.tsx. */
|
||||
function drawingTextBboxPoints(p: Extract<Primitive, { kind: "drawingText" }>): Vec2[] {
|
||||
const singleW = Math.max(1, p.text.length) * p.heightM * 0.6;
|
||||
const w = p.wrapWidth && p.wrapWidth > 0 ? p.wrapWidth : singleW;
|
||||
const lines = p.wrapWidth && p.wrapWidth > 0 ? Math.max(1, Math.ceil(singleW / p.wrapWidth)) : 1;
|
||||
const pad = p.heightM * 0.6;
|
||||
const minX = p.at.x - pad;
|
||||
const maxX = p.at.x + w + pad;
|
||||
const minY = p.at.y - lines * p.heightM * 1.25 - pad;
|
||||
const maxY = p.at.y + p.heightM * 0.4 + pad;
|
||||
return [{ x: minX, y: minY }, { x: maxX, y: minY }, { x: maxX, y: maxY }, { x: minX, y: maxY }];
|
||||
}
|
||||
|
||||
export function marqueeHitDrawings(
|
||||
prims: Primitive[],
|
||||
rect: ModelRect,
|
||||
crossing: boolean,
|
||||
/** Zeichnungen, die der Aufrufer selbst prüft (kompakte Unterlage) — hier überspringen. */
|
||||
skipIds?: ReadonlyMap<string, unknown>,
|
||||
): string[] {
|
||||
const byDrawing = new Map<string, Vec2[]>();
|
||||
const collect = (id: string, pts: Vec2[]) => {
|
||||
const list = byDrawing.get(id);
|
||||
if (list) list.push(...pts);
|
||||
else byDrawing.set(id, [...pts]);
|
||||
};
|
||||
for (const p of prims) {
|
||||
if (skipIds && "drawingId" in p && p.drawingId && skipIds.has(p.drawingId)) continue;
|
||||
if (p.kind === "line" && p.drawingId) collect(p.drawingId, [p.a, p.b]);
|
||||
else if (p.kind === "polygon" && p.drawingId) collect(p.drawingId, p.pts);
|
||||
else if (p.kind === "drawingCircle" && p.drawingId) collect(p.drawingId, ringSamplePoints(p.center, p.r));
|
||||
else if (p.kind === "drawingArc" && p.drawingId) collect(p.drawingId, ringSamplePoints(p.center, p.r, p.a0, p.a1));
|
||||
else if (p.kind === "drawingText" && p.drawingId) collect(p.drawingId, drawingTextBboxPoints(p));
|
||||
else if (p.kind === "drawingImage" && p.drawingId) {
|
||||
collect(p.drawingId, [
|
||||
p.min,
|
||||
{ x: p.max.x, y: p.min.y },
|
||||
p.max,
|
||||
{ x: p.min.x, y: p.max.y },
|
||||
]);
|
||||
}
|
||||
}
|
||||
const out: string[] = [];
|
||||
for (const [id, pts] of byDrawing) {
|
||||
const hit = crossing
|
||||
? polyTouchesRect(pts, rect)
|
||||
: polyEnclosedByRect(pts, rect);
|
||||
if (hit) out.push(id);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// Rahmen-Auswahl über Plan-Primitive (Wände, Decken, Räume, Treppen, 2D-Zeichnungen) läuft im
|
||||
// Kern ([K3d], `PlanPickIndex.marquee`/`marqueeDrawings`, `plan_pick.rs`); hier bleiben die
|
||||
// Rechteck-Tests für die kompakte Unterlage (`underlayAccess.ts`).
|
||||
|
||||
/** Orientierung des Tripels (a,b,c): >0 CCW, <0 CW, 0 kollinear. */
|
||||
function cross3(a: Vec2, b: Vec2, c: Vec2): number {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* `marqueeHitCeilings`/`marqueeHitRooms`/`marqueeHitStairs` — Nutzer-Report:
|
||||
* Rahmen-Auswahl über Decken/Räume/Treppen (`PlanPickIndex.marquee`) — Nutzer-Report:
|
||||
* "Auswahlrahmen kann nicht alle Elemente anwählen, z.B. Decken, Räume und
|
||||
* Treppen nicht". Vorher las das Auswahl-Rechteck nur `wallId`/`drawingId`
|
||||
* aus den Polygon-Primitiven; die anderen ID-Felder (die dieselben
|
||||
@@ -7,8 +7,24 @@
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { marqueeHit, marqueeHitCeilings, marqueeHitRooms, marqueeHitStairs } from "./geometry";
|
||||
import type { Primitive } from "../generatePlan";
|
||||
import type { ModelRect } from "./geometry";
|
||||
import { PlanPickIndex } from "./planPick";
|
||||
|
||||
// Rahmen-Auswahl im Kern ([K3d], `plan_pick.rs`) über einen Plan aus diesen Primitiven.
|
||||
type Field = "wallId" | "ceilingId" | "roomId" | "stairId";
|
||||
const hit = (field: Field) => (prims: Primitive[], rect: ModelRect, crossing: boolean): string[] => {
|
||||
const ix = new PlanPickIndex({ primitives: prims, bounds: { minX: 0, minY: 0, maxX: 1, maxY: 1 } });
|
||||
try {
|
||||
return ix.marquee(field, rect, crossing);
|
||||
} finally {
|
||||
ix.release();
|
||||
}
|
||||
};
|
||||
const marqueeHit = hit("wallId");
|
||||
const marqueeHitCeilings = hit("ceilingId");
|
||||
const marqueeHitRooms = hit("roomId");
|
||||
const marqueeHitStairs = hit("stairId");
|
||||
|
||||
const NO_HATCH = { pattern: "none" as const, color: "#000" };
|
||||
|
||||
|
||||
@@ -10,7 +10,9 @@
|
||||
import type { Vec2 } from "../../model/types";
|
||||
import type { Plan, Primitive } from "../generatePlan";
|
||||
import { heldSegs, planParts } from "../planParts";
|
||||
import { planPrimAt } from "../planLazy";
|
||||
import { core } from "../../engine/coreWasm";
|
||||
import type { ModelRect } from "./geometry";
|
||||
|
||||
/** Pick-Felder eines Primitivs (Besitzer-Ids). */
|
||||
export const OWNER_FIELDS = [
|
||||
@@ -57,19 +59,37 @@ export interface ClientMap {
|
||||
scale: number;
|
||||
}
|
||||
|
||||
/** Typ-Kennung im Plan-Puffer → `kind` (s. `plan_buf.rs`). */
|
||||
const TAG_KIND: Record<number, Primitive["kind"]> = {
|
||||
1: "polygon",
|
||||
2: "line",
|
||||
3: "arc",
|
||||
4: "drawingCircle",
|
||||
5: "drawingArc",
|
||||
6: "text",
|
||||
7: "drawingText",
|
||||
8: "drawingTextPath",
|
||||
9: "drawingImage",
|
||||
};
|
||||
|
||||
/** Ids aus einer Kern-Antwort (jede mit `\0` davor). */
|
||||
const splitIds = (s: string): string[] => (s ? s.split("\0").slice(1) : []);
|
||||
|
||||
export class PlanPickIndex {
|
||||
private id = 0;
|
||||
readonly prims: readonly Primitive[];
|
||||
|
||||
constructor(private readonly plan: Plan) {
|
||||
this.prims = plan.primitives;
|
||||
constructor(readonly plan: Plan) {}
|
||||
|
||||
/** Primitiv `i` des Plans (bei einem lazy Plan nur dieser Eintrag gelesen). */
|
||||
prim(i: number): Primitive | undefined {
|
||||
return planPrimAt(this.plan, i);
|
||||
}
|
||||
|
||||
/** Kern-Index (lazy beim ersten Abfragen gebaut). */
|
||||
/** Kern-Index (lazy beim ersten Abfragen gebaut). Texte/Bilder mit JSON (Rahmen-Treffer). */
|
||||
private ix(): number {
|
||||
if (this.id) return this.id;
|
||||
const c = core();
|
||||
const parts = planParts(this.plan);
|
||||
const parts = planParts(this.plan, true);
|
||||
this.id = c.pick_index_build(heldSegs(parts, false));
|
||||
if (!this.id) this.id = c.pick_index_build(heldSegs(parts, true));
|
||||
return this.id;
|
||||
@@ -144,6 +164,42 @@ export class PlanPickIndex {
|
||||
const list = [...ids];
|
||||
if (list.length === 0) return [];
|
||||
const hits = core().pick_owned_by(this.ix(), KIND[field], list.map((s) => "\u0000" + s).join(""));
|
||||
return Array.from(hits, (i) => this.prims[i]);
|
||||
return Array.from(hits, (i) => planPrimAt(this.plan, i)!);
|
||||
}
|
||||
|
||||
/** Erster Einzeltext (`drawingText` mit `drawingId`), dessen Rahmen `m` enthält, oder null. */
|
||||
drawingTextAt(m: Vec2): number | null {
|
||||
const i = core().pick_drawing_text(this.ix(), m.x, m.y);
|
||||
return i >= 0 ? i : null;
|
||||
}
|
||||
|
||||
/** Oberstes Bild (`drawingImage` mit `drawingId`) unter `m` oder null. */
|
||||
drawingImageAt(m: Vec2): number | null {
|
||||
const i = core().pick_drawing_image(this.ix(), m.x, m.y);
|
||||
return i >= 0 ? i : null;
|
||||
}
|
||||
|
||||
/** Art des ersten formgebenden Primitivs einer Zeichnung (Linie, Polygon, Text, …) oder null. */
|
||||
drawingKind(drawingId: string): Primitive["kind"] | null {
|
||||
return TAG_KIND[core().pick_drawing_kind(this.ix(), drawingId)] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rahmen-Auswahl über Polygone mit Id im Feld `field` (CAD-Konvention): `crossing` = ein Band
|
||||
* berührt das Rechteck, sonst liegen alle Bänder ganz darin. Ids in Auftreten-Reihenfolge.
|
||||
*/
|
||||
marquee(field: "wallId" | "ceilingId" | "roomId" | "stairId" | "columnId" | "roofId", rect: ModelRect, crossing: boolean): string[] {
|
||||
const r = Float64Array.of(rect.minX, rect.minY, rect.maxX, rect.maxY);
|
||||
return splitIds(core().pick_marquee_polygons(this.ix(), KIND[field], r, crossing));
|
||||
}
|
||||
|
||||
/**
|
||||
* Rahmen-Auswahl über 2D-Zeichnungen (alle Punkte je Zeichnung: Linien, Polygone, abgetastete
|
||||
* Kreise/Bögen, Text-/Bild-Rahmen); `skipIds` prüft der Aufrufer selbst (kompakte Unterlage).
|
||||
*/
|
||||
marqueeDrawings(rect: ModelRect, crossing: boolean, skipIds?: Iterable<string>): string[] {
|
||||
const r = Float64Array.of(rect.minX, rect.minY, rect.maxX, rect.maxY);
|
||||
const skip = skipIds ? [...skipIds].map((s) => "\0" + s).join("") : "";
|
||||
return splitIds(core().pick_marquee_drawings(this.ix(), r, crossing, skip));
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import type { Drawing2D, Project } from "../../model/types";
|
||||
import { generatePlan, materializeUnderlay } from "../generatePlan";
|
||||
import { marqueeHitDrawings } from "./geometry";
|
||||
import { PlanPickIndex } from "./planPick";
|
||||
import { buildDrawingIndex, marqueeHitUnderlay, nearestInDrawings } from "./underlayAccess";
|
||||
|
||||
@@ -63,13 +62,14 @@ describe("underlayAccess == Primitiv-Varianten", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("Marquee (crossing + window) == marqueeHitDrawings über die Primitive", () => {
|
||||
it("Marquee (crossing + window) == Rahmen-Auswahl im Kern über die Primitive", () => {
|
||||
const matIx = new PlanPickIndex(mat);
|
||||
for (const crossing of [true, false]) {
|
||||
for (let k = 0; k < 40; k++) {
|
||||
const x = rnd() * 450, y = rnd() * 450, w = 5 + rnd() * 120, h = 5 + rnd() * 120;
|
||||
const rect = { minX: x, minY: y, maxX: x + w, maxY: y + h };
|
||||
const a = new Set(marqueeHitUnderlay(under, rect, crossing));
|
||||
const b = new Set(marqueeHitDrawings(mat.primitives, rect, crossing));
|
||||
const b = new Set(matIx.marqueeDrawings(rect, crossing));
|
||||
expect([...a].sort()).toEqual([...b].sort());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import { docToLines, wrapDocToLines } from "../text/renderHtml";
|
||||
import { docFromText } from "../text/richText";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import { greyedFlat, planParts, withPlanParts } from "./planParts";
|
||||
import { planTextEntries } from "./planLazy";
|
||||
|
||||
export type RPoint = [number, number];
|
||||
export type RRgba = [number, number, number, number];
|
||||
@@ -194,9 +195,8 @@ export function planSceneTexts(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N
|
||||
const texts: RText[] = [];
|
||||
const images: RImage[] = [];
|
||||
const ranges = plan.greyedRanges;
|
||||
const prims = plan.primitives;
|
||||
for (let i = 0; i < prims.length; i++) {
|
||||
const p = prims[i];
|
||||
// Nur die Text-/Bild-Einträge ([K3d], aus den Typ-Kennungen des Plan-Puffers).
|
||||
for (const { i, p } of planTextEntries(plan)) {
|
||||
if (p.kind === "text") {
|
||||
const greyed = p.greyed || inGreyedRange(ranges, i);
|
||||
const defCol = greyedColor(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], greyed);
|
||||
|
||||
+61
-99
@@ -31,7 +31,7 @@ import { isGpuText } from "../../core";
|
||||
import { LiveMeet, LiveValue, createMeetStore, createValueStore } from "./planView/liveMeet";
|
||||
import { useWasmPlanRenderer } from "./useWasmPlanRenderer";
|
||||
import { DEFAULT_MARQUEE_COLOR, DEFAULT_SNAP_COLOR } from "../../theme/accents";
|
||||
import { type ViewBox__plan_planView_geometry as ViewBox, PX_PER_M, PAD, toScreen, clamp, meetScale, scaleFromView, viewForScale, viewForCamera, fitBoxFor, marqueeHit, marqueeHitDrawings, type ModelRect, marqueeHitCeilings, marqueeHitRooms, marqueeHitStairs } from "../../core";
|
||||
import { type ViewBox__plan_planView_geometry as ViewBox, PX_PER_M, PAD, toScreen, clamp, meetScale, scaleFromView, viewForScale, viewForCamera, fitBoxFor, type ModelRect } from "../../core";
|
||||
import {
|
||||
polyUsesPattern,
|
||||
HatchPattern,
|
||||
@@ -45,6 +45,7 @@ import { PlanRulers } from "./planView/PlanRulers";
|
||||
import { PlanGrid } from "./planView/PlanGrid";
|
||||
import { expandRegion, indexedInRegion, regionContains, type Bounds } from "../../core";
|
||||
import { PlanPickIndex, type ClientMap, type OwnerField } from "../../core";
|
||||
import { planPrimAt, planTextEntries } from "../../core";
|
||||
import { buildDrawingIndex, drawingsWithinDistance, marqueeHitUnderlay, nearestInDrawings, type DrawingIndex } from "../../core";
|
||||
import { endBusyAfterPaint } from "../../state/busyStore";
|
||||
import { createCursorStore, useCursorValue, type CursorStore } from "../../state/cursorStore";
|
||||
@@ -765,7 +766,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
const pickIndexRef = useRef<PlanPickIndex | null>(null);
|
||||
const getPick = (): PlanPickIndex => {
|
||||
const cached = pickIndexRef.current;
|
||||
if (cached && cached.prims === plan.primitives) return cached;
|
||||
if (cached && cached.plan === plan) return cached;
|
||||
cached?.release();
|
||||
const ix = new PlanPickIndex(plan);
|
||||
pickIndexRef.current = ix;
|
||||
@@ -813,9 +814,10 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
// Primitiv in render2d, s. toRenderScene.ts `RImage`-Kommentar) — dieselbe
|
||||
// SVG-Fallback-Regel wie bei georeferenzierten Luftbildern.
|
||||
// useMemo: lief sonst bei JEDEM Render über alle Primitive (3,7 Mio. bei Kataster).
|
||||
// Texte/Bilder aus den Typ-Kennungen des Plan-Puffers (`planTextEntries`), ohne alle Primitive zu lesen.
|
||||
const hasDrawingImages = useMemo(
|
||||
() => planRaw.primitives.some((p) => p.kind === "drawingImage"),
|
||||
[planRaw.primitives],
|
||||
() => planTextEntries(planRaw).some((e) => e.p.kind === "drawingImage"),
|
||||
[planRaw],
|
||||
);
|
||||
// Engine WIRKLICH aktiv? Steuert das Umschalten SVG↔GPU: bei false rendert der
|
||||
// volle SVG-Pfad (Fallback), bei true übernimmt die GPU-Ebene + Text-Overlay.
|
||||
@@ -832,18 +834,6 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
const lines = !useGpuRenderer || wantWasm;
|
||||
return materializeGreyed(lines ? materializeUnderlay(planRaw) : planRaw, lines);
|
||||
}, [planRaw, useGpuRenderer, wantWasm]);
|
||||
// Einzeltexte und Bilder (eigene Bbox-Treffer): einmal je Plan gesammelt statt bei jeder
|
||||
// Mausbewegung über alle Primitive zu laufen.
|
||||
const textImageIdx = useMemo(() => {
|
||||
const texts: number[] = [];
|
||||
const images: number[] = [];
|
||||
plan.primitives.forEach((p, i) => {
|
||||
if (p.kind === "drawingText") texts.push(i);
|
||||
else if (p.kind === "drawingImage") images.push(i);
|
||||
});
|
||||
return { texts, images };
|
||||
}, [plan.primitives]);
|
||||
|
||||
// Kompakte Linien-Unterlage (nur im reinen WebGL-Modus noch als `plan.underlay`
|
||||
// vorhanden): Hover/Pick/Marquee/Hervorhebung greifen direkt auf die Zeichnungen
|
||||
// zu, Strukturen entstehen LAZY je Plan (s. planView/underlayAccess.ts).
|
||||
@@ -885,11 +875,12 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
// bei jedem Render über ALLE Primitive — bei einem Kataster-Import 3,7 Mio.
|
||||
// GL-Linien, von denen das SVG keine einzige zeichnet (gemessen: 120–170 ms
|
||||
// je Zoom-Schritt allein fürs Culling, für am Ende ~500 sichtbare Texte).
|
||||
// Mit GPU zeichnet das SVG nur Texte: dann kommen die Kandidaten aus den Text-Einträgen des
|
||||
// Plan-Puffers (`planTextEntries`, [K3d]) — die übrigen Primitive werden nicht gelesen.
|
||||
const svgCandidates = useMemo(() => {
|
||||
const out: Array<{ p: Primitive; i: number }> = [];
|
||||
const prims = plan.primitives;
|
||||
for (let i = 0; i < prims.length; i++) {
|
||||
const p = prims[i];
|
||||
const items: ReadonlyArray<{ p: Primitive; i: number }> = useGpuRenderer ? planTextEntries(plan) : plan.primitives.map((p, i) => ({ p, i }));
|
||||
for (const { p, i } of items) {
|
||||
const drawnElsewhere = useGpuRenderer
|
||||
? wantWasm
|
||||
? p.kind !== "drawingText"
|
||||
@@ -900,7 +891,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
if (!drawnElsewhere) out.push({ p, i });
|
||||
}
|
||||
return out;
|
||||
}, [plan.primitives, useGpuRenderer, wantWasm, wantNative, nativeHook.gpuTexts]);
|
||||
}, [plan, useGpuRenderer, wantWasm, wantNative, nativeHook.gpuTexts]);
|
||||
const needsCull = svgCandidates.length > CULL_THRESHOLD;
|
||||
const [cullState, setCullState] = useState<CullState | null>(() => {
|
||||
if (!needsCull) return null;
|
||||
@@ -1116,7 +1107,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
},
|
||||
fitSelection: () => {
|
||||
const sel = selectedRef.current;
|
||||
const prim = sel !== null ? planRef.current.primitives[sel] : undefined;
|
||||
const prim = sel !== null ? planPrimAt(planRef.current, sel) : undefined;
|
||||
if (prim && prim.kind === "polygon") {
|
||||
setView(fitBoxFor(prim.pts, toScreenRef.current));
|
||||
} else {
|
||||
@@ -1439,8 +1430,8 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
const anyGroupableHit = (clientX: number, clientY: number): GroupableHit | null => {
|
||||
const idx = hitTest(clientX, clientY);
|
||||
if (idx !== null) {
|
||||
const p = plan.primitives[idx];
|
||||
if (p.kind === "polygon") {
|
||||
const p = planPrimAt(plan, idx);
|
||||
if (p?.kind === "polygon") {
|
||||
if (p.wallId) return { wallId: p.wallId };
|
||||
if (p.ceilingId) return { ceilingId: p.ceilingId };
|
||||
if (p.roomId) return { roomId: p.roomId };
|
||||
@@ -1464,7 +1455,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
const m = rawModelAt(clientX, clientY);
|
||||
const seg = pick.nearestSegment(m, LINE_PICK_PX / pxPerM);
|
||||
if (seg) {
|
||||
bestId = (plan.primitives[seg.i] as Extract<Primitive, { kind: "line" }>).drawingId!;
|
||||
bestId = (planPrimAt(plan, seg.i) as Extract<Primitive, { kind: "line" }>).drawingId!;
|
||||
bestDist = seg.dist * pxPerM;
|
||||
}
|
||||
const uIndex = getUnderlayIndex();
|
||||
@@ -1479,7 +1470,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
for (const { i, dpx } of pick.ringsNear(m, pxPerM, LINE_PICK_PX)) {
|
||||
if (dpx < bestDist) {
|
||||
bestDist = dpx;
|
||||
bestId = (plan.primitives[i] as Extract<Primitive, { kind: "drawingCircle" | "drawingArc" }>).drawingId!;
|
||||
bestId = (planPrimAt(plan, i) as Extract<Primitive, { kind: "drawingCircle" | "drawingArc" }>).drawingId!;
|
||||
}
|
||||
}
|
||||
if (bestId) return bestId;
|
||||
@@ -1500,7 +1491,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
let bestDist = maxDist;
|
||||
const seg = getPick().nearestSegment(m, maxDist);
|
||||
if (seg) {
|
||||
const p = plan.primitives[seg.i] as Extract<Primitive, { kind: "line" }>;
|
||||
const p = planPrimAt(plan, seg.i) as Extract<Primitive, { kind: "line" }>;
|
||||
best = { a: p.a, b: p.b };
|
||||
bestDist = seg.dist;
|
||||
}
|
||||
@@ -1513,44 +1504,20 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
};
|
||||
|
||||
// Trifft der Klick ein Text-2D-Element (kind "drawingText")? Grosszügige Modell-
|
||||
// Bounding-Box um den Ankerpunkt (Text hat keine Linien-Geometrie zum Anfassen);
|
||||
// Winkel wird vernachlässigt (meist waagrecht). Liefert die drawingId oder null.
|
||||
// Bounding-Box um den Ankerpunkt (Text hat keine Linien-Geometrie zum Anfassen; Winkel
|
||||
// vernachlässigt) — im Kern (`plan_pick.rs`). Liefert die drawingId oder null.
|
||||
const pickDrawingText = (clientX: number, clientY: number): string | null => {
|
||||
const m = rawModelAt(clientX, clientY);
|
||||
for (const i of textImageIdx.texts) {
|
||||
const p = plan.primitives[i];
|
||||
if (p.kind !== "drawingText" || !p.drawingId) continue;
|
||||
const singleW = Math.max(1, p.text.length) * p.heightM * 0.6;
|
||||
// Textspalte: Breite = wrapWidth, Höhe = geschätzte Zeilenzahl · Zeilenhöhe.
|
||||
const w = p.wrapWidth && p.wrapWidth > 0 ? p.wrapWidth : singleW;
|
||||
const lines =
|
||||
p.wrapWidth && p.wrapWidth > 0 ? Math.max(1, Math.ceil(singleW / p.wrapWidth)) : 1;
|
||||
const pad = p.heightM * 0.6;
|
||||
const minX = p.at.x - pad;
|
||||
const maxX = p.at.x + w + pad;
|
||||
// Baseline am Anker; Text läuft nach unten (Zeilen) und etwas nach oben (Oberlängen).
|
||||
const minY = p.at.y - lines * p.heightM * 1.25 - pad;
|
||||
const maxY = p.at.y + p.heightM * 0.4 + pad;
|
||||
if (m.x >= minX && m.x <= maxX && m.y >= minY && m.y <= maxY) {
|
||||
return p.drawingId;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
const pick = getPick();
|
||||
const i = pick.drawingTextAt(rawModelAt(clientX, clientY));
|
||||
return i === null ? null : ((pick.prim(i) as { drawingId?: string }).drawingId ?? null);
|
||||
};
|
||||
|
||||
// Trifft der Klick ein Bild-2D-Element (kind "drawingImage")? Reine
|
||||
// Bounding-Box-Prüfung (achsparallel, keine Rotation). Liefert die drawingId
|
||||
// oder null.
|
||||
// Trifft der Klick ein Bild-2D-Element (kind "drawingImage")? Reine Bounding-Box-Prüfung
|
||||
// (achsparallel, oberstes zuerst). Liefert die drawingId oder null.
|
||||
const pickDrawingImage = (clientX: number, clientY: number): string | null => {
|
||||
const m = rawModelAt(clientX, clientY);
|
||||
for (let k = textImageIdx.images.length - 1; k >= 0; k--) {
|
||||
const p = plan.primitives[textImageIdx.images[k]];
|
||||
if (p.kind !== "drawingImage" || !p.drawingId) continue;
|
||||
if (m.x >= p.min.x && m.x <= p.max.x && m.y >= p.min.y && m.y <= p.max.y) {
|
||||
return p.drawingId;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
const pick = getPick();
|
||||
const i = pick.drawingImageAt(rawModelAt(clientX, clientY));
|
||||
return i === null ? null : ((pick.prim(i) as { drawingId?: string }).drawingId ?? null);
|
||||
};
|
||||
|
||||
// Nächstgelegene Öffnung (Fenster/Tür) zum Cursor: Linien-/Bogen-Primitive mit
|
||||
@@ -1562,9 +1529,9 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
const pick = getPick();
|
||||
// Getroffener Rahmen (das zuerst gezeichnete Polygon) hat Vorrang vor Symbol-Linien.
|
||||
const hit = pick.bottomPolygon(m, "openingId");
|
||||
if (hit !== null) return (plan.primitives[hit] as { openingId?: string }).openingId!;
|
||||
if (hit !== null) return (planPrimAt(plan, hit) as { openingId?: string }).openingId!;
|
||||
const i = pick.nearestSymbolPx(["openingId"], ["openingId"], clientMap(), { x: clientX, y: clientY }, LINE_PICK_PX);
|
||||
return i === null ? null : (plan.primitives[i] as { openingId?: string }).openingId!;
|
||||
return i === null ? null : (planPrimAt(plan, i) as { openingId?: string }).openingId!;
|
||||
};
|
||||
|
||||
// Nächstgelegene Treppe zum Cursor: getroffenes Tritt-/Podest-Polygon (per
|
||||
@@ -1574,9 +1541,9 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
const m = viewToModel(v.x, v.y);
|
||||
const pick = getPick();
|
||||
const hit = pick.bottomPolygon(m, "stairId");
|
||||
if (hit !== null) return (plan.primitives[hit] as { stairId?: string }).stairId!;
|
||||
if (hit !== null) return (planPrimAt(plan, hit) as { stairId?: string }).stairId!;
|
||||
const i = pick.nearestSymbolPx(["stairId"], [], clientMap(), { x: clientX, y: clientY }, LINE_PICK_PX);
|
||||
return i === null ? null : (plan.primitives[i] as { stairId?: string }).stairId!;
|
||||
return i === null ? null : (planPrimAt(plan, i) as { stairId?: string }).stairId!;
|
||||
};
|
||||
|
||||
// Getroffener Raum: die Raum-Fläche (Polygon mit `roomId`) per Punkt-in-Polygon.
|
||||
@@ -1584,7 +1551,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
const pickRoom = (clientX: number, clientY: number): string | null => {
|
||||
const v = clientToView(clientX, clientY, view);
|
||||
const i = getPick().topPolygon(viewToModel(v.x, v.y), "roomId");
|
||||
return i === null ? null : (plan.primitives[i] as { roomId?: string }).roomId!;
|
||||
return i === null ? null : (planPrimAt(plan, i) as { roomId?: string }).roomId!;
|
||||
};
|
||||
|
||||
// Getroffenes Dach: das unsichtbare Traufe-Pick-Polygon per Punkt-in-Polygon
|
||||
@@ -1592,7 +1559,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
const pickRoof = (clientX: number, clientY: number): string | null => {
|
||||
const v = clientToView(clientX, clientY, view);
|
||||
const i = getPick().topPolygon(viewToModel(v.x, v.y), "roofId");
|
||||
return i === null ? null : (plan.primitives[i] as { roofId?: string }).roofId!;
|
||||
return i === null ? null : (planPrimAt(plan, i) as { roofId?: string }).roofId!;
|
||||
};
|
||||
|
||||
// Getroffene Schnitt-/Ansichtslinie: ihr schmales, unsichtbares Pick-Band
|
||||
@@ -1600,7 +1567,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
const pickSectionLine = (clientX: number, clientY: number): string | null => {
|
||||
const v = clientToView(clientX, clientY, view);
|
||||
const i = getPick().topPolygon(viewToModel(v.x, v.y), "sectionLineId");
|
||||
return i === null ? null : (plan.primitives[i] as { sectionLineId?: string }).sectionLineId!;
|
||||
return i === null ? null : (planPrimAt(plan, i) as { sectionLineId?: string }).sectionLineId!;
|
||||
};
|
||||
|
||||
// Getroffenes Kontext-Objekt (importiertes Gebäude/Terrain): sein unsichtbares
|
||||
@@ -1610,7 +1577,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
const pickContextObject = (clientX: number, clientY: number): string | null => {
|
||||
const v = clientToView(clientX, clientY, view);
|
||||
const i = getPick().topPolygon(viewToModel(v.x, v.y), "contextObjectId");
|
||||
return i === null ? null : (plan.primitives[i] as { contextObjectId?: string }).contextObjectId!;
|
||||
return i === null ? null : (planPrimAt(plan, i) as { contextObjectId?: string }).contextObjectId!;
|
||||
};
|
||||
|
||||
// Getroffener extrudierter Körper (truck-Integration): der Footprint-Umriss
|
||||
@@ -1619,7 +1586,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
const pickExtrudedSolid = (clientX: number, clientY: number): string | null => {
|
||||
const v = clientToView(clientX, clientY, view);
|
||||
const i = getPick().topPolygon(viewToModel(v.x, v.y), "extrudedSolidId");
|
||||
return i === null ? null : (plan.primitives[i] as { extrudedSolidId?: string }).extrudedSolidId!;
|
||||
return i === null ? null : (planPrimAt(plan, i) as { extrudedSolidId?: string }).extrudedSolidId!;
|
||||
};
|
||||
|
||||
// Getroffene Stütze (Tragwerk): ihr Querschnitt ist eine gefüllte Poché
|
||||
@@ -1627,7 +1594,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
const pickColumn = (clientX: number, clientY: number): string | null => {
|
||||
const v = clientToView(clientX, clientY, view);
|
||||
const i = getPick().topPolygon(viewToModel(v.x, v.y), "columnId");
|
||||
return i === null ? null : (plan.primitives[i] as { columnId?: string }).columnId!;
|
||||
return i === null ? null : (planPrimAt(plan, i) as { columnId?: string }).columnId!;
|
||||
};
|
||||
|
||||
// Liegt der Cursor auf dem KÖRPER eines GEWÄHLTEN Elements (Wand-Poché bzw.
|
||||
@@ -1642,7 +1609,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
// der Wirtswand, die im Blatt dahinter liegt).
|
||||
if (sheetBodies) {
|
||||
const hi = hitTest(clientX, clientY);
|
||||
const p = hi !== null ? plan.primitives[hi] : null;
|
||||
const p = hi !== null ? planPrimAt(plan, hi) ?? null : null;
|
||||
if (p && "openingId" in p && p.openingId && selectedOpeningIds?.includes(p.openingId)) {
|
||||
return { openingId: p.openingId };
|
||||
}
|
||||
@@ -1657,8 +1624,8 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
if (selWalls.size) {
|
||||
const hi = hitTest(clientX, clientY);
|
||||
if (hi !== null) {
|
||||
const p = plan.primitives[hi];
|
||||
if (p.kind === "polygon" && p.wallId && selWalls.has(p.wallId)) {
|
||||
const p = planPrimAt(plan, hi);
|
||||
if (p?.kind === "polygon" && p.wallId && selWalls.has(p.wallId)) {
|
||||
return { wallId: p.wallId };
|
||||
}
|
||||
}
|
||||
@@ -1679,7 +1646,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
// Polygon-Punkte allein sonst ein anderes Ergebnis lieferten) + Unterlage.
|
||||
const marqueeHitAll = (rect: ModelRect, crossing: boolean): string[] => {
|
||||
const ids = getUnderlayIds();
|
||||
const fromPrims = marqueeHitDrawings(plan.primitives, rect, crossing, ids ?? undefined);
|
||||
const fromPrims = getPick().marqueeDrawings(rect, crossing, ids?.keys());
|
||||
const u = getUnderlay();
|
||||
return u ? [...fromPrims, ...marqueeHitUnderlay(u.drawings, rect, crossing)] : fromPrims;
|
||||
};
|
||||
@@ -2096,7 +2063,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
// Kontext). Liefert nur die Ids + Polygon-Index; `model`/`shift` ergänzt der Aufrufer.
|
||||
const defaultPick = (clientX: number, clientY: number): PickIds => {
|
||||
const hitIndex = hitTest(clientX, clientY);
|
||||
const hit = hitIndex !== null ? plan.primitives[hitIndex] : undefined;
|
||||
const hit = hitIndex !== null ? planPrimAt(plan, hitIndex) : undefined;
|
||||
// Öffnung (Fenster/Tür) zuerst: ihr Symbol sitzt in der ausgesparten Lücke
|
||||
// bzw. schlägt über die Wand — ein Klick nahe am Symbol wählt die Öffnung.
|
||||
// Schnitt-/Ansichtslinie zuerst: ihr schmales Band liegt über allem, ein
|
||||
@@ -2195,7 +2162,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
const cycleRef = useRef<{
|
||||
x: number;
|
||||
y: number;
|
||||
prims: readonly Primitive[];
|
||||
plan: Plan;
|
||||
items: PickCandidate[];
|
||||
idx: number;
|
||||
model: Vec2;
|
||||
@@ -2232,9 +2199,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
? t("pick.shape.area")
|
||||
: t("pick.shape.polyline");
|
||||
}
|
||||
for (const p of plan.primitives) {
|
||||
if (!("drawingId" in p) || p.drawingId !== id) continue;
|
||||
switch (p.kind) {
|
||||
switch (getPick().drawingKind(id)) {
|
||||
case "line": return t("pick.shape.line");
|
||||
case "polygon": return t("pick.shape.area");
|
||||
case "drawingText":
|
||||
@@ -2242,10 +2207,8 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
case "drawingCircle": return t("pick.shape.circle");
|
||||
case "drawingArc": return t("pick.shape.arc");
|
||||
case "drawingImage": return t("pick.shape.image");
|
||||
default: break;
|
||||
}
|
||||
default: return t("pick.kind.drawing");
|
||||
}
|
||||
return t("pick.kind.drawing");
|
||||
};
|
||||
|
||||
/** IDs ALLER 2D-Elemente nahe am Cursor (nächste zuerst). */
|
||||
@@ -2256,13 +2219,13 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
const found: Array<{ id: string; d: number }> = [];
|
||||
const pick = getPick();
|
||||
for (const { i, dist } of pick.segmentsNear(m, tol)) {
|
||||
const id = (plan.primitives[i] as Extract<Primitive, { kind: "line" }>).drawingId;
|
||||
const id = (planPrimAt(plan, i) as Extract<Primitive, { kind: "line" }>).drawingId;
|
||||
if (id) found.push({ id, d: dist });
|
||||
}
|
||||
const uIdx = getUnderlayIndex();
|
||||
if (uIdx) for (const h of drawingsWithinDistance(uIdx, m, tol)) found.push({ id: h.drawing.id, d: h.dist });
|
||||
for (const { i, dpx } of pick.ringsNear(m, pxPerM, LINE_PICK_PX)) {
|
||||
found.push({ id: (plan.primitives[i] as Extract<Primitive, { kind: "drawingCircle" | "drawingArc" }>).drawingId!, d: dpx / pxPerM });
|
||||
found.push({ id: (planPrimAt(plan, i) as Extract<Primitive, { kind: "drawingCircle" | "drawingArc" }>).drawingId!, d: dpx / pxPerM });
|
||||
}
|
||||
const textId = pickDrawingText(clientX, clientY);
|
||||
if (textId) found.push({ id: textId, d: tol * 2 });
|
||||
@@ -2306,8 +2269,8 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
if (out.length > before) rest.push(out.pop()!);
|
||||
};
|
||||
for (const idx of hitTestAll(clientX, clientY)) {
|
||||
const p = plan.primitives[idx];
|
||||
if (p.kind !== "polygon") continue;
|
||||
const p = planPrimAt(plan, idx);
|
||||
if (p?.kind !== "polygon") continue;
|
||||
addRest("opening", p.openingId, idx);
|
||||
addRest("wall", p.wallId, idx);
|
||||
addRest("column", p.columnId, idx);
|
||||
@@ -2373,7 +2336,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
const prev = cycleRef.current;
|
||||
const same =
|
||||
prev &&
|
||||
prev.prims === plan.primitives &&
|
||||
prev.plan === plan &&
|
||||
Math.hypot(e.clientX - prev.x, e.clientY - prev.y) <= 5;
|
||||
let items: PickCandidate[];
|
||||
let idx: number;
|
||||
@@ -2396,7 +2359,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
cycleRef.current = {
|
||||
x: e.clientX,
|
||||
y: e.clientY,
|
||||
prims: plan.primitives,
|
||||
plan,
|
||||
items,
|
||||
idx,
|
||||
model,
|
||||
@@ -2511,11 +2474,11 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
};
|
||||
if (onMarquee) {
|
||||
onMarquee({
|
||||
wallIds: marqueeHit(plan.primitives, rect, crossing),
|
||||
wallIds: getPick().marquee("wallId", rect, crossing),
|
||||
drawingIds: marqueeHitAll(rect, crossing),
|
||||
ceilingIds: marqueeHitCeilings(plan.primitives, rect, crossing),
|
||||
roomIds: marqueeHitRooms(plan.primitives, rect, crossing),
|
||||
stairIds: marqueeHitStairs(plan.primitives, rect, crossing),
|
||||
ceilingIds: getPick().marquee("ceilingId", rect, crossing),
|
||||
roomIds: getPick().marquee("roomId", rect, crossing),
|
||||
stairIds: getPick().marquee("stairId", rect, crossing),
|
||||
crossing,
|
||||
});
|
||||
}
|
||||
@@ -2689,7 +2652,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
return primsOwnedBy("wallId", selectedWallIds, (p): p is Extract<Primitive, { kind: "polygon" }> => p.kind === "polygon");
|
||||
}
|
||||
if (selected !== null) {
|
||||
const p = plan.primitives[selected];
|
||||
const p = planPrimAt(plan, selected);
|
||||
if (p && p.kind === "polygon") return [p];
|
||||
}
|
||||
return [];
|
||||
@@ -2955,8 +2918,8 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
// sonst weiterhin in der ORIGINAL-Bauteilfarbe erscheinen.
|
||||
const hatched = useMemo(() => {
|
||||
const list: HatchedPoly[] = [];
|
||||
// Im WebGL-Modus zeichnet das SVG nur Texte (keine Polygone → keine Muster).
|
||||
if (useGpuRenderer && !wantWasm) return list;
|
||||
// Mit GPU (nativ oder WASM) zeichnet das SVG nur Texte (keine Polygone → keine Muster).
|
||||
if (useGpuRenderer) return list;
|
||||
plan.primitives.forEach((p, i) => {
|
||||
if (p.kind === "polygon" && polyUsesPattern(p.hatch)) {
|
||||
// Verlauf-Schraffuren tragen ihre eigentliche Farbe in `gradient.color1/
|
||||
@@ -3596,10 +3559,9 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
Layout stimmt. */}
|
||||
{editTextId &&
|
||||
(() => {
|
||||
const prim = plan.primitives.find(
|
||||
(p): p is Extract<Primitive, { kind: "drawingText" }> =>
|
||||
p.kind === "drawingText" && p.drawingId === editTextId,
|
||||
);
|
||||
const prim = planTextEntries(plan)
|
||||
.map((e) => e.p)
|
||||
.find((p): p is Extract<Primitive, { kind: "drawingText" }> => p.kind === "drawingText" && p.drawingId === editTextId);
|
||||
if (!prim) return null;
|
||||
const doc = prim.doc ?? docFromText(prim.text, prim.marks ?? {});
|
||||
// WYSIWYG: Position, Breite, Feldhöhe UND Schriftgrösse folgen alle dem
|
||||
|
||||
@@ -17,6 +17,7 @@ import type { Primitive } from "../../core";
|
||||
import { NativeGl, type NativeInvoke } from './nativeGl';
|
||||
import { readCssColor } from './cssColor';
|
||||
import { NativeTextSync } from "../../core";
|
||||
import { planTextEntries } from "../../core";
|
||||
|
||||
/** Läuft die App in einer Tauri-Webview? */
|
||||
const isTauri = (): boolean => typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window;
|
||||
@@ -89,7 +90,8 @@ export function useNativePlanRenderer(
|
||||
const pushTexts = useCallback((plan: Plan | null) => {
|
||||
const invoke = invokeRef.current;
|
||||
if (!invoke || !plan || textsDisabled.current) return;
|
||||
const { upsert, remove } = textSync.current.delta(plan.primitives, excludedText.current);
|
||||
// Nur die Text-Einträge (`planTextEntries`, [K3d]) — nicht alle Primitive.
|
||||
const { upsert, remove } = textSync.current.delta(planTextEntries(plan).map((e) => e.p), excludedText.current);
|
||||
if (upsert.length === 0 && remove.length === 0) return;
|
||||
void invoke('native2d_texts', { upsert, remove })
|
||||
.then((ok) => {
|
||||
|
||||
@@ -22,6 +22,7 @@ import type {
|
||||
import { categoryNameForPick } from "../core";
|
||||
import type { PickKind } from "../core";
|
||||
import { generatePlan, generateSectionPlan, generateVisibleLevelsPlan } from "../core";
|
||||
import { planWithExtra } from "../core";
|
||||
import type { CategoryDisplayResolver, Plan, Primitive } from "../core";
|
||||
import type { RichTextDoc } from "../text/richText";
|
||||
import { computeSection, sameSectionInputs, sameSectionLine } from "../core";
|
||||
@@ -818,10 +819,8 @@ function LevelPlanView({
|
||||
// handhabbar; PlanView materialisiert sie, wo echte Primitive nötig sind.
|
||||
true,
|
||||
);
|
||||
const withOverlay =
|
||||
overlayPrimitives.length === 0
|
||||
? p
|
||||
: { ...p, primitives: [...p.primitives, ...overlayPrimitives] };
|
||||
// Überlagerung anhängen, ohne die Primitive des Plans zu lesen (lazy, [K3d]).
|
||||
const withOverlay = overlayPrimitives.length === 0 ? p : planWithExtra(p, [], overlayPrimitives);
|
||||
// Gruppen-Isolation ("Gruppe betreten"): alles ausserhalb der aktiven
|
||||
// Gruppe gedimmt, s. state/groupActions.ts::applyGroupDimmingToPlan (die
|
||||
// kompakte Linien-Unterlage bleibt dabei kompakt).
|
||||
|
||||
Reference in new issue
Block a user