diff --git a/src-tauri/core/src/plan_pick.rs b/src-tauri/core/src/plan_pick.rs index 3f4efd69..876a9a41 100644 --- a/src-tauri/core/src/plan_pick.rs +++ b/src-tauri/core/src/plan_pick.rs @@ -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>, interned: HashMap, + /// 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>, +} + +/// 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 { + 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 { + 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 { + 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 { + 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 { + let mut order: Vec<(String, bool)> = Vec::new(); + let mut at: HashMap = 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 { + let skip_n: Vec = skip.iter().filter_map(|s| self.interned.get(*s).copied()).collect(); + let names: HashMap = self.interned.iter().map(|(k, v)| (*v, k.as_str())).collect(); + let boxes: HashMap = 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)> = Vec::new(); + let mut at: HashMap = HashMap::new(); + for &(gi, tag, id) in &self.draw_items { + if skip_n.contains(&id) { + continue; + } + let pts: Vec = 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 { + 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)); + } } diff --git a/src-tauri/core/src/web/plan_pick.rs b/src-tauri/core/src/web/plan_pick.rs index 3f45177c..4937cbb3 100644 --- a/src-tauri/core/src/web/plan_pick.rs +++ b/src-tauri/core/src/web/plan_pick.rs @@ -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 { 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 { + 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() +} diff --git a/src/core/index.ts b/src/core/index.ts index c1e9ab95..e94cad46 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -254,11 +254,6 @@ export { type ViewBox as ViewBox__plan_planView_geometry, clamp, fitBoxFor, - marqueeHit, - marqueeHitCeilings, - marqueeHitDrawings, - marqueeHitRooms, - marqueeHitStairs, meetScale, mmToPx, pointInPolygon, @@ -277,6 +272,14 @@ export { PlanPickIndex, } from "../plan/planView/planPick"; +export { + planCount, + planPrimAt, + planTextEntries, + planWithExtra, + type TextEntryPrim, +} from "../plan/planLazy"; + export { marqueeHitUnderlay, } from "../plan/planView/underlayAccess"; diff --git a/src/plan/planLazy.test.ts b/src/plan/planLazy.test.ts new file mode 100644 index 00000000..2c89745c --- /dev/null +++ b/src/plan/planLazy.test.ts @@ -0,0 +1,75 @@ +// Lazy Plan ([K3d], `planLazy.ts`): `generatePlan` liest die Kern-Primitive erst bei Bedarf; die +// Verbraucher im Kern (Szene, Auswahl, 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 { 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); + ix.drawingTextAt({ x: 1.2, y: 2 }); + ix.release(); + 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); + }); +}); diff --git a/src/plan/planView/geometry.test.ts b/src/plan/planView/geometry.test.ts index 6cb20cb7..cc27b89c 100644 --- a/src/plan/planView/geometry.test.ts +++ b/src/plan/planView/geometry.test.ts @@ -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 }; diff --git a/src/plan/planView/geometry.ts b/src/plan/planView/geometry.ts index 402361e1..0a822882 100644 --- a/src/plan/planView/geometry.ts +++ b/src/plan/planView/geometry.ts @@ -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(); - 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): 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[] { - const byDrawing = new Map(); - 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 { diff --git a/src/plan/planView/marquee.test.ts b/src/plan/planView/marquee.test.ts index 613c65f0..2d55e486 100644 --- a/src/plan/planView/marquee.test.ts +++ b/src/plan/planView/marquee.test.ts @@ -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" }; diff --git a/src/plan/planView/planPick.ts b/src/plan/planView/planPick.ts index ce1b4b51..865b807e 100644 --- a/src/plan/planView/planPick.ts +++ b/src/plan/planView/planPick.ts @@ -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 = { + 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[] { + 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)); } } diff --git a/src/plan/planView/underlayAccess.test.ts b/src/plan/planView/underlayAccess.test.ts index 32235861..d8be8f47 100644 --- a/src/plan/planView/underlayAccess.test.ts +++ b/src/plan/planView/underlayAccess.test.ts @@ -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()); } } diff --git a/src/plan/toRenderScene.ts b/src/plan/toRenderScene.ts index 0c7cd1c4..ca14294c 100644 --- a/src/plan/toRenderScene.ts +++ b/src/plan/toRenderScene.ts @@ -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); diff --git a/src/views/plan/PlanView.tsx b/src/views/plan/PlanView.tsx index 4a5fc7dc..44e058a4 100644 --- a/src/views/plan/PlanView.tsx +++ b/src/views/plan/PlanView.tsx @@ -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( const pickIndexRef = useRef(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( // 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( 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( // 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( 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(() => { if (!needsCull) return null; @@ -1116,7 +1107,7 @@ export const PlanView = forwardRef( }, 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( 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( const m = rawModelAt(clientX, clientY); const seg = pick.nearestSegment(m, LINE_PICK_PX / pxPerM); if (seg) { - bestId = (plan.primitives[seg.i] as Extract).drawingId!; + bestId = (planPrimAt(plan, seg.i) as Extract).drawingId!; bestDist = seg.dist * pxPerM; } const uIndex = getUnderlayIndex(); @@ -1479,7 +1470,7 @@ export const PlanView = forwardRef( for (const { i, dpx } of pick.ringsNear(m, pxPerM, LINE_PICK_PX)) { if (dpx < bestDist) { bestDist = dpx; - bestId = (plan.primitives[i] as Extract).drawingId!; + bestId = (planPrimAt(plan, i) as Extract).drawingId!; } } if (bestId) return bestId; @@ -1500,7 +1491,7 @@ export const PlanView = forwardRef( let bestDist = maxDist; const seg = getPick().nearestSegment(m, maxDist); if (seg) { - const p = plan.primitives[seg.i] as Extract; + const p = planPrimAt(plan, seg.i) as Extract; best = { a: p.a, b: p.b }; bestDist = seg.dist; } @@ -1513,44 +1504,20 @@ export const PlanView = forwardRef( }; // 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( 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( 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( 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( 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( 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( 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( 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( 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( // 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( 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( // 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( // 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( 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( ? 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( 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( 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).drawingId; + const id = (planPrimAt(plan, i) as Extract).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).drawingId!, d: dpx / pxPerM }); + found.push({ id: (planPrimAt(plan, i) as Extract).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( 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( 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( cycleRef.current = { x: e.clientX, y: e.clientY, - prims: plan.primitives, + plan, items, idx, model, @@ -2511,11 +2474,11 @@ export const PlanView = forwardRef( }; 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( return primsOwnedBy("wallId", selectedWallIds, (p): p is Extract => 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( // 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( Layout stimmt. */} {editTextId && (() => { - const prim = plan.primitives.find( - (p): p is Extract => - p.kind === "drawingText" && p.drawingId === editTextId, - ); + const prim = planTextEntries(plan) + .map((e) => e.p) + .find((p): p is Extract => 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 diff --git a/src/views/plan/useNativePlanRenderer.ts b/src/views/plan/useNativePlanRenderer.ts index 0e835a5b..687a1656 100644 --- a/src/views/plan/useNativePlanRenderer.ts +++ b/src/views/plan/useNativePlanRenderer.ts @@ -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) => { diff --git a/src/views/viewportContent.tsx b/src/views/viewportContent.tsx index 568016ca..55c2bf97 100644 --- a/src/views/viewportContent.tsx +++ b/src/views/viewportContent.tsx @@ -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).