diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 2b694b2b..604411fc 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -58,6 +58,8 @@ pub mod plan_section; pub mod voids; pub mod curves; pub mod skeleton; +pub mod plan_parts; +pub mod plan_scene; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/plan_buf.rs b/src-tauri/core/src/plan_buf.rs index 496b6567..07f9c785 100644 --- a/src-tauri/core/src/plan_buf.rs +++ b/src-tauri/core/src/plan_buf.rs @@ -212,7 +212,7 @@ impl PlanBuf { // ── Farben (früher `parseColor` in TS) ─────────────────────────────────────────────────────────── /// JS `parseInt(s, 16)` (Leerraum, Vorzeichen, `0x`, längster Ziffern-Präfix; NaN ohne Ziffer). -fn js_parse_hex(units: &[u16]) -> f64 { +pub(crate) fn js_parse_hex(units: &[u16]) -> f64 { let s = String::from_utf16_lossy(units); let t = s.trim_start_matches(crate::plan::overrides::js_space); let (neg, t) = match t.as_bytes().first() { @@ -391,7 +391,7 @@ impl<'a> Reader<'a> { } /// Nicht-negative ganze Zahl als Index/Anzahl. -fn whole(v: f64) -> Option { +pub(crate) fn whole(v: f64) -> Option { if !(v >= 0.0) || v.fract() != 0.0 || v > (u32::MAX as f64) { return None; } @@ -473,17 +473,17 @@ pub struct View<'a> { } /// Ein Primitiv-Eintrag, roh gelesen (Indizes noch nicht aufgelöst). -struct Rec { - tag: u32, - flags: u32, - pick: (u32, i32), +pub(crate) struct Rec { + pub(crate) tag: u32, + pub(crate) flags: u32, + pub(crate) pick: (u32, i32), /// Feste Felder nach dem Kopf (je Typ, s. Format). - f: Vec, - dash: Option<(usize, usize)>, - nse: Option<(usize, usize)>, - zigzag: Option<(f64, f64)>, - motif: Option<(f64, usize, usize)>, - ids: Option<(usize, usize)>, + pub(crate) f: Vec, + pub(crate) dash: Option<(usize, usize)>, + pub(crate) nse: Option<(usize, usize)>, + pub(crate) zigzag: Option<(f64, f64)>, + pub(crate) motif: Option<(f64, usize, usize)>, + pub(crate) ids: Option<(usize, usize)>, } fn fixed_len(tag: u32) -> Option { @@ -561,6 +561,11 @@ impl<'a> View<'a> { self.n_prims == 0 } + /// Anzahl Einträge der String-Tabelle. + pub(crate) fn n_strings(&self) -> usize { + self.n_strings + } + pub fn bounds(&self) -> Option<[f64; 4]> { self.bounds } @@ -609,7 +614,7 @@ impl<'a> View<'a> { Some(Some(self.string(whole(idx)?)?)) } - fn pool(&self, off: usize, n: usize) -> Option> { + pub(crate) fn pool(&self, off: usize, n: usize) -> Option> { if off.checked_add(n)? > self.n_pool { return None; } @@ -620,13 +625,13 @@ impl<'a> View<'a> { Some(out) } - fn pool_pts(&self, off: usize, n: usize) -> Option> { + pub(crate) fn pool_pts(&self, off: usize, n: usize) -> Option> { let l = self.pool(off, n.checked_mul(2)?)?; Some(l.chunks_exact(2).map(|c| V2 { x: c[0], y: c[1] }).collect()) } /// Hatch-Einträge: (JSON-String-Index, Hatch, Farb-String-Index). - fn hatch_table(&self) -> Option> { + pub(crate) fn hatch_table(&self) -> Option> { let mut r = Reader { w: self.w, pos: self.hatches_at, end: self.hatches_end }; let mut out = Vec::with_capacity(self.n_hatches); for _ in 0..self.n_hatches { @@ -643,7 +648,7 @@ impl<'a> View<'a> { Some(out) } - fn rec(&self, i: usize) -> Option { + pub(crate) fn rec(&self, i: usize) -> Option { if i >= self.n_prims { return None; } diff --git a/src-tauri/core/src/plan_parts.rs b/src-tauri/core/src/plan_parts.rs new file mode 100644 index 00000000..7d337ad7 --- /dev/null +++ b/src-tauri/core/src/plan_parts.rs @@ -0,0 +1,111 @@ +//! Zusammengesetzter Plan ([K3d]): ein Grundriss besteht aus Abschnitten mehrerer Plan-Puffer +//! (Kern-Puffer aus `planDomains` je Geschoss, dazu ein Puffer mit dem, was TS noch selbst +//! erzeugt: 2D-Zeichnungen, Schatten, Baurecht, zerlegte Polygone). Die Verbraucher im Kern +//! (Render-Szene `plan_scene`, Auswahl `plan_pick`, SVG-Export `plan_svg`) laufen über die +//! Abschnitte in Zeichenreihenfolge; der Index eines Primitivs im zusammengesetzten Plan ist +//! seine Stelle in `Plan.primitives` auf der TS-Seite. +//! +//! Eingabe der Bindungen: Abschnitte als Tripel `[Puffer-Nr, von, bis)` (Nummer = gehaltener +//! Puffer, s. `web/plan_buf.rs`), gedimmte Bereiche als Paare `[von, bis)` im zusammengesetzten +//! Index (wie `Plan.greyedRanges`: dort gilt `greyed = true`). + +use crate::plan_buf::{whole, Rec, View, F_GREYED, F_GREYED_SET, F_IDS}; + +/// Ein Abschnitt `[from, to)` eines Puffers. +pub struct Part<'a> { + pub view: View<'a>, + pub from: usize, + pub to: usize, + /// Gelesene Strings (Index → Text; `None` = noch nicht gelesen). + strs: Vec>, +} + +impl<'a> Part<'a> { + pub fn new(view: View<'a>, from: usize, to: usize) -> Option> { + if from > to || to > view.len() { + return None; + } + let n = view.n_strings(); + Some(Part { view, from, to, strs: vec![None; n] }) + } + + /// String `idx` (−1 = fehlt → `None`); kaputter Index → `None`. + pub fn str(&mut self, idx: f64) -> Option<&str> { + let i = whole(idx)?; + if i >= self.strs.len() { + return None; + } + if self.strs[i].is_none() { + self.strs[i] = Some(self.view.string(i)?); + } + self.strs[i].as_deref() + } +} + +/// Abschnitte aus `[nr, von, bis, …]` bilden; `buf(nr)` liefert die Bytes des Puffers. +pub fn parts_from<'a>(segs: &[f64], buf: impl Fn(u32) -> Option<&'a [u8]>) -> Option>> { + if segs.len() % 3 != 0 { + return None; + } + let mut out = Vec::with_capacity(segs.len() / 3); + for s in segs.chunks_exact(3) { + let nr = whole(s[0])? as u32; + let view = View::parse(buf(nr)?)?; + out.push(Part::new(view, whole(s[1])?, whole(s[2])?)?); + } + Some(out) +} + +/// Gedimmte Bereiche aus `[von, bis, …]` (sortiert, wie `Plan.greyedRanges`). +pub fn ranges_from(flat: &[f64]) -> Option> { + if flat.len() % 2 != 0 { + return None; + } + flat.chunks_exact(2).map(|c| Some((whole(c[0])?, whole(c[1])?))).collect() +} + +/// Liegt `i` in einem der Bereiche? +pub fn in_ranges(ranges: &[(usize, usize)], i: usize) -> bool { + ranges.iter().any(|&(a, b)| i >= a && i < b) +} + +/// `greyed` eines Eintrags: `Some(true/false)` gesetzt, `None` fehlt; in einem gedimmten Bereich +/// immer `Some(true)` (wie `greyedClone` in `generatePlan.ts`). +pub(crate) fn greyed_of(rec: &Rec, forced: bool) -> Option { + if forced { + return Some(true); + } + (rec.flags & F_GREYED_SET != 0).then_some(rec.flags & F_GREYED != 0) +} + +/// Alle Pick-Ids eines Eintrags als (Art 1…11, String-Index), erste aus dem Kopf. +pub(crate) fn pick_ids(view: &View, rec: &Rec) -> Option> { + let mut out = Vec::new(); + if rec.pick.0 > 0 { + out.push((rec.pick.0, rec.pick.1 as f64)); + } + if rec.flags & F_IDS != 0 { + if let Some((o, n)) = rec.ids { + let l = view.pool(o, n.checked_mul(2)?)?; + for c in l.chunks_exact(2) { + let k = whole(c[0])? as u32; + if k == 0 || k > 11 { + return None; + } + out.push((k, c[1])); + } + } + } + Some(out) +} + +/// String-Index der Pick-Id der Art `kind` (1 wall · 2 drawing · …) oder `None`. +pub(crate) fn pick_id(view: &View, rec: &Rec, kind: u32) -> Option { + if rec.pick.0 == kind { + return Some(rec.pick.1 as f64); + } + if rec.flags & F_IDS == 0 { + return None; + } + pick_ids(view, rec)?.into_iter().find(|e| e.0 == kind).map(|e| e.1) +} diff --git a/src-tauri/core/src/plan_scene.rs b/src-tauri/core/src/plan_scene.rs new file mode 100644 index 00000000..fdd57e7e --- /dev/null +++ b/src-tauri/core/src/plan_scene.rs @@ -0,0 +1,886 @@ +//! Render-Szene aus dem Plan-Puffer ([K3d], früher `planToRenderScene` in +//! `src/plan/toRenderScene.ts`): Füllungen, Umrisse, Polylinien, Bögen und Linien für render2d, +//! direkt aus den Abschnitten eines zusammengesetzten Plans ([`crate::plan_parts`]) — ohne Umweg +//! über `Primitive[]`. Texte setzt TS (Text-Layout bleibt dort) und gibt sie fertig mit. +//! +//! Bitgleich zur TS-Fassung: Farben wie `toRgba`, CSS-Klassen-Farben/-Deckkraft, Dimmen, +//! Maler-Reihenfolge `z`, Verkettung der 2D-Zeichenlinien, Kantenläufe mit Naht über +//! Polygon-Grenzen hinweg, Schraffur-Läufe, Zickzack/Motiv, Kreis-Tessellierung. +//! +//! Zwei Ausgaben: [`encode_scene_bin`] (render2d-Szene v1, s. `render2d/src/scene_bin.rs`) und +//! [`encode_scene_f64`] (verlustfrei für den Druck-/SVG-Export und `--format json`): +//! ```text +//! [nFills, nOutlines, nPolylines, nArcs, nLines] +//! Füllung n, z, r, g, b, a, x, y … +//! Umriss n, z, widthMm, dash, r, g, b, a, x, y … +//! Polylinie n, z, widthMm, dash, r, g, b, a, x, y … +//! Bogen r, widthMm, dash, r, g, b, a, cx, cy, fx, fy, tx, ty +//! Linie z, widthMm, dash, r, g, b, a, ax, ay, bx, by +//! dash = −2 (Feld fehlt) · −1 (null) · k ≥ 0 (k Werte folgen) +//! ``` + +use crate::hatch::{self, v2, HatchKind, Motif, Pattern, V2, DASH_MM_TO_M}; +use crate::jsnum; +use crate::plan::overrides::js_trim; +use crate::plan_buf::{js_parse_hex, whole, Rec, F_COLOR, F_DASH_LIST, F_DASH_NULL, F_MOTIF, F_NSE, F_ZIGZAG}; +use crate::plan_buf::{T_ARC, T_CIRCLE, T_DRAWING_ARC, T_DRAWING_TEXT, T_IMAGE, T_LINE, T_POLYGON, T_TEXT}; +use crate::plan_parts::{greyed_of, in_ranges, pick_id, Part}; +use std::collections::HashMap; +use std::f64::consts::PI; + +pub type Rgba = [f64; 4]; + +/// Strichmuster eines Szenen-Elements. +#[derive(Clone, Debug, PartialEq)] +pub enum SDash { + /// Feld fehlt (Umrisse, Schraffur-Läufe, Zickzack/Motiv, Nähte). + Absent, + Null, + List(Vec), +} + +impl SDash { + fn list(&self) -> &[f64] { + match self { + SDash::List(l) => l, + _ => &[], + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct SFill { + pub pts: Vec, + pub color: Rgba, + pub z: f64, +} + +/// Umriss (geschlossen) oder Polylinie (offen). +#[derive(Clone, Debug, PartialEq)] +pub struct SStroke { + pub pts: Vec, + pub color: Rgba, + pub width_mm: f64, + pub dash: SDash, + pub z: f64, + /// `widthMm` in Bildschirm-Einheiten (render2d-Flag; heute von keinem Primitiv gesetzt). + pub width_screen: bool, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct SArc { + pub center: V2, + pub from: V2, + pub to: V2, + pub r: f64, + pub color: Rgba, + pub width_mm: f64, + pub dash: SDash, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct SLine { + pub a: V2, + pub b: V2, + pub color: Rgba, + pub width_mm: f64, + pub dash: SDash, + pub z: f64, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Scene { + pub fills: Vec, + pub outlines: Vec, + pub polylines: Vec, + pub arcs: Vec, + pub lines: Vec, +} + +// ── Farben (wie `toRgba`/`withOpacity` der TS-Fassung) ────────────────────────────────────────── + +const DEFAULT_LINE: &str = "#1a1a1a"; +const INK: Rgba = [0.1, 0.1, 0.1, 1.0]; +/// Fester Grauton gedimmter Primitive (wie `GREY_RGB` in `gpu_compile.rs`). +const GREY_RGB: f64 = 0.549; + +/// CSS-Strichfarbe je Linienklasse (Spiegel der `.plan-svg .`-Regeln in styles.css). +fn cls_stroke(cls: Option<&str>) -> Option<&'static str> { + match cls? { + "door-leaf" | "door-swing" | "door-frame" | "window-glass" => Some("#1a1a1a"), + "wall-axis" => Some("#4a453e"), + _ => None, + } +} + +fn cls_opacity(cls: Option<&str>) -> f64 { + match cls { + Some("wall-axis") => 0.85, + Some("context-line") => 0.7, + _ => 1.0, + } +} + +/// Hex-/Namens-Farbe → RGBA (0…1) oder `None` bei "none"/leer — wie `toRgba(input, 1)`. +pub fn to_rgba(input: Option<&str>) -> Option { + let input = input?; + if input.is_empty() { + return None; + } + let alpha = 1.0; + let mut h: String = js_trim(input).to_lowercase(); + if h == "none" || h == "transparent" { + return None; + } + if !h.starts_with('#') { + h = match h.as_str() { + "black" => "#000000".into(), + "white" => "#ffffff".into(), + "red" => "#ff0000".into(), + _ => return Some([0.0, 0.0, 0.0, alpha]), + }; + } + let mut u: Vec = h.encode_utf16().skip(1).collect(); + if u.len() == 3 || u.len() == 4 { + u = u.iter().flat_map(|&c| [c, c]).collect(); + } + if u.len() != 6 && u.len() != 8 { + return Some([0.0, 0.0, 0.0, alpha]); + } + let r = js_parse_hex(&u[0..2]) / 255.0; + let g = js_parse_hex(&u[2..4]) / 255.0; + let b = js_parse_hex(&u[4..6]) / 255.0; + let a = if u.len() == 8 { js_parse_hex(&u[6..8]) / 255.0 } else { alpha }; + if ![r, g, b, a].iter().all(|v| v.is_finite()) { + return Some([0.0, 0.0, 0.0, alpha]); + } + Some([r, g, b, a]) +} + +fn with_opacity(col: Rgba, cls: Option<&str>, greyed: bool) -> Rgba { + let o = cls_opacity(cls); + let rgb = if greyed { [GREY_RGB, GREY_RGB, GREY_RGB, col[3]] } else { col }; + if o == 1.0 { + rgb + } else { + [rgb[0], rgb[1], rgb[2], rgb[3] * o] + } +} + +fn with_fill_opacity(col: Rgba, greyed: bool) -> Rgba { + if greyed { + [1.0, 1.0, 1.0, col[3]] + } else { + col + } +} + +/// Strichfarbe einer line/arc: CSS-Klassen-Farbe > Modell-Farbe > Tinte. +fn stroke_color_for(cls: Option<&str>, color: Option<&str>) -> Rgba { + to_rgba(Some(cls_stroke(cls).or(color).unwrap_or(DEFAULT_LINE))).unwrap_or(INK) +} + +// ── Schlüssel wie JS-Strings von Zahlen ───────────────────────────────────────────────────────── + +/// Zahl als Schlüssel mit der Gleichheit von `String(x)`: −0 = 0, alle NaN gleich. +#[inline] +fn num_key(x: f64) -> u64 { + if x.is_nan() { + 0x7ff8_0000_0000_0000 + } else if x == 0.0 { + 0 + } else { + x.to_bits() + } +} + +/// Gleichheit wie `JSON.stringify(a ?? null) === JSON.stringify(b ?? null)` für Strichmuster. +fn same_dash_json(a: &SDash, b: &SDash) -> bool { + match (a, b) { + (SDash::List(x), SDash::List(y)) => { + x.len() == y.len() && x.iter().zip(y).all(|(p, q)| (!p.is_finite() && !q.is_finite()) || p == q) + } + (SDash::List(_), _) | (_, SDash::List(_)) => false, + _ => true, + } +} + +#[inline] +fn same_pt(a: V2, b: V2) -> bool { + (a.x - b.x).abs() < 1e-6 && (a.y - b.y).abs() < 1e-6 +} + +// ── Kantenläufe (wie `visibleEdgeRuns`/`stitchRuns`) ──────────────────────────────────────────── + +/// Sichtbare Kantenläufe eines Rings (die Kanten aus `no_stroke` fehlen). +pub fn visible_edge_runs(pts: &[V2], no_stroke: &[f64]) -> Vec> { + let n = pts.len(); + let nf = n as f64; + let mut skip: Vec = no_stroke.iter().map(|&i| num_key(((i % nf) + nf) % nf)).collect(); + skip.sort_unstable(); + skip.dedup(); + if skip.len() >= n || n < 2 { + return Vec::new(); + } + let visible = |i: isize| -> bool { + let k = ((i as f64 % nf) + nf) % nf; + skip.binary_search(&num_key(k)).is_err() + }; + let mut runs = Vec::new(); + for s in 0..n as isize { + if !visible(s) || visible(s - 1 + n as isize) { + continue; + } + let mut run = vec![pts[s as usize]]; + let mut j = s; + while visible(j) && ((j - s) as usize) < n { + run.push(pts[((j + 1) as usize) % n]); + j += 1; + } + runs.push(run); + } + runs +} + +const STITCH_EPS: f64 = 1e-5; + +#[inline] +fn cell_of(p: V2) -> (f64, f64) { + (jsnum::round(p.x / STITCH_EPS), jsnum::round(p.y / STITCH_EPS)) +} + +#[inline] +fn stitch_key(p: V2) -> (u64, u64) { + let (x, y) = cell_of(p); + (num_key(x), num_key(y)) +} + +/// Näht Kantenläufe über Polygon-Grenzen hinweg zusammen (genau zwei Enden je Stelle). +/// Ergebnis: (Punkte, geschlossen). Gleiche Wahl wie die lineare Suche der TS-Fassung (der +/// erste passende Lauf in Pool-Reihenfolge); ein Raster über den Endpunkten findet die Kandidaten. +pub fn stitch_runs(runs: Vec>) -> Vec<(Vec, bool)> { + let mut end_count: HashMap<(u64, u64), u32> = HashMap::new(); + for r in &runs { + for p in [r[0], r[r.len() - 1]] { + *end_count.entry(stitch_key(p)).or_insert(0) += 1; + } + } + let joinable = |p: V2| end_count.get(&stitch_key(p)) == Some(&2); + // Raster: Zelle (gerundet) → Läufe mit einem Ende darin. `same_pt` (< 1e-6) liegt höchstens + // eine Zelle daneben. + let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); + let cell_int = |p: V2| -> Option<(i64, i64)> { + let (x, y) = cell_of(p); + (x.is_finite() && y.is_finite() && x.abs() < 9e15 && y.abs() < 9e15).then_some((x as i64, y as i64)) + }; + // Enden ausserhalb des Rasters (NaN/riesig) — immer prüfen. + let mut wild: Vec = Vec::new(); + for (i, r) in runs.iter().enumerate() { + for p in [r[0], r[r.len() - 1]] { + match cell_int(p) { + Some(c) => grid.entry(c).or_default().push(i), + None => wild.push(i), + } + } + } + let mut used = vec![false; runs.len()]; + let mut out = Vec::new(); + let mut cand: Vec = Vec::new(); + for seed in 0..runs.len() { + if used[seed] { + continue; + } + used[seed] = true; + let mut chain = runs[seed].clone(); + let mut extended = true; + while extended && !(chain.len() > 2 && same_pt(chain[0], chain[chain.len() - 1])) { + extended = false; + let head = chain[0]; + let tail = chain[chain.len() - 1]; + cand.clear(); + for p in [tail, head] { + if let Some((cx, cy)) = cell_int(p) { + for dx in -1..=1 { + for dy in -1..=1 { + if let Some(l) = grid.get(&(cx + dx, cy + dy)) { + cand.extend(l.iter().copied().filter(|&i| !used[i])); + } + } + } + } else { + // Kein Raster-Platz: alle Läufe prüfen (wie die lineare Suche). + cand.extend((0..runs.len()).filter(|&i| !used[i])); + } + } + cand.extend(wild.iter().copied().filter(|&i| !used[i])); + cand.sort_unstable(); + cand.dedup(); + let jt = joinable(tail); + let jh = joinable(head); + for &ci in &cand { + let c = &runs[ci]; + let cs = c[0]; + let ce = c[c.len() - 1]; + if jt && same_pt(tail, cs) { + chain.extend_from_slice(&c[1..]); + } else if jt && same_pt(tail, ce) { + chain.extend(c.iter().rev().skip(1).copied()); + } else if jh && same_pt(head, ce) { + let mut n = c.clone(); + n.extend_from_slice(&chain[1..]); + chain = n; + } else if jh && same_pt(head, cs) { + let mut n: Vec = c.iter().rev().copied().collect(); + n.extend_from_slice(&chain[1..]); + chain = n; + } else { + continue; + } + used[ci] = true; + extended = true; + break; + } + } + let closed = chain.len() > 3 && same_pt(chain[0], chain[chain.len() - 1]); + if closed { + chain.pop(); + } + out.push((chain, closed)); + } + out +} + +// ── Szene ──────────────────────────────────────────────────────────────────────────────────────── + +/// Quelle eines laufenden, verketteten 2D-Zeichnungs-Zugs. +struct RunSrc { + cls: Option, + color: Option, + weight: f64, + dash: SDash, + greyed: bool, +} + +struct EdgeGroup { + color: Rgba, + width_mm: f64, + runs: Vec>, + z: f64, +} + +struct Builder { + s: Scene, + zc: f64, + cur: Option<(Vec, RunSrc)>, + groups: Vec, + group_of: HashMap<[u64; 5], usize>, +} + +impl Builder { + fn z(&mut self) -> f64 { + let z = self.zc; + self.zc += 1.0; + z + } + + fn flush(&mut self) { + if let Some((pts, src)) = self.cur.take() { + if pts.len() >= 2 { + let col = with_opacity(stroke_color_for(src.cls.as_deref(), src.color.as_deref()), src.cls.as_deref(), src.greyed); + let closed = pts.len() > 2 && same_pt(pts[0], pts[pts.len() - 1]); + let dash = match src.dash { + SDash::Absent => SDash::Null, + d => d, + }; + let z = self.z(); + if closed { + let mut p = pts; + p.pop(); + self.s.outlines.push(SStroke { pts: p, color: col, width_mm: src.weight, dash, z, width_screen: false }); + } else { + self.s.polylines.push(SStroke { pts, color: col, width_mm: src.weight, dash, z, width_screen: false }); + } + } + } + } + + fn edge_run(&mut self, run: Vec, color: Rgba, width_mm: f64, z: f64) { + let k = [num_key(color[0]), num_key(color[1]), num_key(color[2]), num_key(color[3]), num_key(width_mm)]; + let gi = match self.group_of.get(&k) { + Some(&g) => g, + None => { + self.groups.push(EdgeGroup { color, width_mm, runs: Vec::new(), z }); + self.group_of.insert(k, self.groups.len() - 1); + self.groups.len() - 1 + } + }; + let g = &mut self.groups[gi]; + g.runs.push(run); + g.z = jsnum::max(g.z, z); + } +} + +/// Strichmuster eines Eintrags (`dash ?? null`). +fn dash_of(part: &Part, rec: &Rec) -> Option { + if rec.flags & F_DASH_NULL != 0 { + Some(SDash::Null) + } else if rec.flags & F_DASH_LIST != 0 { + let (o, n) = rec.dash?; + Some(SDash::List(part.view.pool(o, n)?)) + } else { + Some(SDash::Null) + } +} + +/// Render-Szene aus den Abschnitten; `None` bei kaputtem Puffer. +pub fn build_scene(parts: &mut [Part], greyed_ranges: &[(usize, usize)]) -> Option { + let mut b = Builder { s: Scene::default(), zc: 0.0, cur: None, groups: Vec::new(), group_of: HashMap::new() }; + let mut gi = 0usize; // Index im zusammengesetzten Plan + for part in parts.iter_mut() { + // Farben dieses Puffers (String-Index → RGBA), einmal je String. + let mut colors: HashMap> = HashMap::new(); + let mut hatches: Option> = None; + for i in part.from..part.to { + let forced = !greyed_ranges.is_empty() && in_ranges(greyed_ranges, gi); + gi += 1; + let rec = part.view.rec(i)?; + let greyed = greyed_of(&rec, forced) == Some(true); + let f = rec.f.clone(); + let mut color = |part: &mut Part, idx: f64| -> Option { + if idx < 0.0 { + return None; + } + let k = idx as i64; + if let Some(c) = colors.get(&k) { + return *c; + } + let c = to_rgba(part.str(idx)); + colors.insert(k, c); + c + }; + match rec.tag { + T_POLYGON => { + b.flush(); + let pts = part.view.pool_pts(whole(f[5])?, whole(f[6])?)?; + if pts.len() < 2 { + continue; + } + if let Some(fc) = color(part, f[0]) { + if pts.len() >= 3 { + let z = b.z(); + b.s.fills.push(SFill { pts: pts.clone(), color: with_fill_opacity(fc, greyed), z }); + } + } + if f[3] != -1.0 { + if hatches.is_none() { + hatches = Some(part.view.hatch_table()?); + } + let (_, h, hc) = hatches.as_ref()?.get(whole(f[3])?)?.clone(); + if h.kind != HatchKind::Image && h.kind != HatchKind::Gradient && h.pattern != Pattern::None && h.pattern != Pattern::Solid { + let hatch_col = with_opacity(color(part, hc as f64).unwrap_or(INK), None, greyed); + let hatch_mm = if h.line_weight > 0.0 { h.line_weight } else { 0.13 }; + let runs = if pts.len() < 3 { Vec::new() } else { hatch::build_hatch_runs(&pts, &h) }; + let runs = hatch::apply_dash_runs(runs, &h.dash); + let hz = b.z(); + for run in runs { + if run.len() >= 2 { + b.s.polylines.push(SStroke { pts: run, color: hatch_col, width_mm: hatch_mm, dash: SDash::Absent, z: hz, width_screen: false }); + } + } + } + } + if let Some(raw) = color(part, f[1]) { + let w = f[2]; + if w > 0.0 { + let sc = with_opacity(raw, None, greyed); + let nse = match (rec.flags & F_NSE != 0, rec.nse) { + (true, Some((o, n))) => part.view.pool(o, n)?, + _ => Vec::new(), + }; + if nse.is_empty() { + let z = b.z(); + b.s.outlines.push(SStroke { pts, color: sc, width_mm: w, dash: SDash::Absent, z, width_screen: false }); + } else { + let rz = b.z(); + for run in visible_edge_runs(&pts, &nse) { + b.edge_run(run, sc, w, rz); + } + } + } + } + } + T_LINE => { + let cls = part.str(f[0]).map(str::to_owned); + let col_s = if rec.flags & F_COLOR != 0 { part.str(f[1]).map(str::to_owned) } else { None }; + let a = v2(f[4], f[5]); + let bb = v2(f[6], f[7]); + let w = f[2]; + if rec.flags & F_ZIGZAG != 0 { + b.flush(); + let (amp, wav) = rec.zigzag?; + let zp = hatch::zigzag_points(a, bb, amp * DASH_MM_TO_M, wav * DASH_MM_TO_M).unwrap_or_else(|| vec![a, bb]); + let col = with_opacity(stroke_color_for(cls.as_deref(), col_s.as_deref()), cls.as_deref(), greyed); + if zp.len() >= 2 { + let z = b.z(); + b.s.polylines.push(SStroke { pts: zp, color: col, width_mm: w, dash: SDash::Absent, z, width_screen: false }); + } + } else if rec.flags & F_MOTIF != 0 { + b.flush(); + let (length, o, n) = rec.motif?; + let m = Motif { length, points: part.view.pool_pts(o, n)? }; + let mp = hatch::motif_points(a, bb, &m, DASH_MM_TO_M); + let col = with_opacity(stroke_color_for(cls.as_deref(), col_s.as_deref()), cls.as_deref(), greyed); + if mp.len() >= 2 { + let z = b.z(); + b.s.polylines.push(SStroke { pts: mp, color: col, width_mm: w, dash: SDash::Absent, z, width_screen: false }); + } + } else { + let dash = dash_of(part, &rec)?; + let drawing = match pick_id(&part.view, &rec, 2) { + Some(s) => part.str(s).is_some_and(|s| !s.is_empty()), + None => false, + }; + if drawing { + let src = RunSrc { cls, color: col_s, weight: w, dash, greyed }; + let cont = match &b.cur { + Some((pts, c)) => { + c.cls == src.cls + && c.weight == src.weight + && c.color.as_deref().unwrap_or("") == src.color.as_deref().unwrap_or("") + && same_dash_json(&c.dash, &src.dash) + && same_pt(pts[pts.len() - 1], a) + } + None => false, + }; + if cont { + b.cur.as_mut()?.0.push(bb); + } else { + b.flush(); + b.cur = Some((vec![a, bb], src)); + } + } else { + b.flush(); + let col = with_opacity(stroke_color_for(cls.as_deref(), col_s.as_deref()), cls.as_deref(), greyed); + let z = b.z(); + b.s.lines.push(SLine { a, b: bb, color: col, width_mm: w, dash, z }); + } + } + } + T_ARC => { + b.flush(); + let cls = part.str(f[0]).map(str::to_owned); + let col = with_opacity(stroke_color_for(cls.as_deref(), None), cls.as_deref(), greyed); + let dash = dash_of(part, &rec)?; + b.s.arcs.push(SArc { center: v2(f[4], f[5]), from: v2(f[6], f[7]), to: v2(f[8], f[9]), r: f[10], color: col, width_mm: f[2], dash }); + } + T_CIRCLE | T_DRAWING_ARC => { + b.flush(); + let circle = rec.tag == T_CIRCLE; + let stroke = if circle { f[1] } else { f[0] }; + let col = with_opacity(color(part, stroke).unwrap_or(INK), None, greyed); + let (w, c, r) = if circle { (f[2], v2(f[4], f[5]), f[6]) } else { (f[1], v2(f[3], f[4]), f[5]) }; + let tau = PI * 2.0; + let a0 = if circle { 0.0 } else { f[6] }; + let sweep = if circle { tau } else { (((f[7] - f[6]) % tau) + tau) % tau }; + let n = jsnum::max(8.0, (sweep / (PI / 32.0)).ceil()); + let mut pts = Vec::new(); + let mut k = 0.0f64; + while k <= n { + let t = a0 + (sweep * k) / n; + pts.push(v2(c.x + r * jsnum::cos(t), c.y + r * jsnum::sin(t))); + k += 1.0; + } + let dash = dash_of(part, &rec)?; + let z = b.z(); + b.s.polylines.push(SStroke { pts, color: col, width_mm: w, dash, z, width_screen: false }); + } + // Text, Einzeltext, Bild: Zeilen setzt TS; hier nur den Linienzug abschliessen + // (Textpfad und Platzhalter berühren ihn nicht, wie in der TS-Fassung). + T_TEXT | T_DRAWING_TEXT | T_IMAGE => b.flush(), + _ => {} + } + } + } + b.flush(); + let groups = std::mem::take(&mut b.groups); + for g in groups { + for (pts, closed) in stitch_runs(g.runs) { + if pts.len() < 2 { + continue; + } + let s = SStroke { pts, color: g.color, width_mm: g.width_mm, dash: SDash::Absent, z: g.z, width_screen: false }; + if closed { + b.s.outlines.push(s); + } else { + b.s.polylines.push(s); + } + } + } + Some(b.s) +} + +// ── Ausgaben ───────────────────────────────────────────────────────────────────────────────────── + +/// Eine Textzeile (von TS gesetzt) für die render2d-Szene. +pub struct SText { + pub pos: V2, + pub size_mm: f64, + pub color: Rgba, + /// 0 links · 1 Mitte · 2 rechts + pub align: u32, + pub content: Vec, +} + +/// Texte aus `[x, y, sizeMm, r, g, b, a, align, nBytes]*` und den UTF-8-Bytes; `None` bei Unsinn. +pub fn texts_from(nums: &[f64], bytes: &[u8]) -> Option> { + if nums.len() % 9 != 0 { + return None; + } + let mut out = Vec::with_capacity(nums.len() / 9); + let mut o = 0usize; + for t in nums.chunks_exact(9) { + let n = whole(t[8])?; + let content = bytes.get(o..o.checked_add(n)?)?.to_vec(); + o += n; + out.push(SText { pos: v2(t[0], t[1]), size_mm: t[2], color: [t[3], t[4], t[5], t[6]], align: whole(t[7])? as u32, content }); + } + (o == bytes.len()).then_some(out) +} + +/// `z >>> 0` (ToUint32). +fn u32_of(z: f64) -> u32 { + jsnum::to_int32(z) as u32 +} + +/// render2d-Szene v1 (Format s. `render2d/src/scene_bin.rs`), gleiche Bytes wie die frühere +/// TS-Kodierung `encodeRenderScene`. +pub fn encode_scene_bin(s: &Scene, texts: &[SText]) -> Vec { + let mut n_pts = 0usize; + let mut n_dash = 0usize; + for f in &s.fills { + n_pts += f.pts.len(); + } + for o in s.outlines.iter().chain(&s.polylines) { + n_pts += o.pts.len(); + n_dash += o.dash.list().len(); + } + for a in &s.arcs { + n_dash += a.dash.list().len(); + } + for l in &s.lines { + n_dash += l.dash.list().len(); + } + n_pts += s.arcs.len() * 3 + s.lines.len() * 2 + texts.len(); + let str_bytes: usize = texts.iter().map(|t| t.content.len()).sum(); + let words = s.fills.len() * 6 + s.outlines.len() * 8 + s.polylines.len() * 9 + s.arcs.len() * 7 + s.lines.len() * 7 + texts.len() * 8; + let total = 48 + n_pts * 16 + n_dash * 4 + words * 4 + str_bytes; + let mut pts: Vec = Vec::with_capacity(n_pts * 16); + let mut dash: Vec = Vec::with_capacity(n_dash * 4); + let mut rec: Vec = Vec::with_capacity(words * 4); + let mut strs: Vec = Vec::with_capacity(str_bytes); + let pt = |pts: &mut Vec, p: V2| { + pts.extend_from_slice(&p.x.to_le_bytes()); + pts.extend_from_slice(&p.y.to_le_bytes()); + }; + let u = |rec: &mut Vec, v: u32| rec.extend_from_slice(&v.to_le_bytes()); + let f = |rec: &mut Vec, v: f64| rec.extend_from_slice(&(v as f32).to_le_bytes()); + let col = |rec: &mut Vec, c: &Rgba| { + for &v in c { + rec.extend_from_slice(&(v as f32).to_le_bytes()); + } + }; + let dashes = |dash: &mut Vec, d: &SDash| -> u32 { + let l = d.list(); + for &v in l { + dash.extend_from_slice(&(v as f32).to_le_bytes()); + } + l.len() as u32 + }; + for x in &s.fills { + u(&mut rec, x.pts.len() as u32); + u(&mut rec, u32_of(x.z)); + col(&mut rec, &x.color); + for &p in &x.pts { + pt(&mut pts, p); + } + } + for x in &s.outlines { + u(&mut rec, x.pts.len() as u32); + u(&mut rec, u32_of(x.z)); + f(&mut rec, x.width_mm); + let n = dashes(&mut dash, &x.dash); + u(&mut rec, n); + col(&mut rec, &x.color); + for &p in &x.pts { + pt(&mut pts, p); + } + } + for x in &s.polylines { + u(&mut rec, x.pts.len() as u32); + u(&mut rec, u32_of(x.z)); + f(&mut rec, x.width_mm); + let n = dashes(&mut dash, &x.dash); + u(&mut rec, n); + u(&mut rec, x.width_screen as u32); + col(&mut rec, &x.color); + for &p in &x.pts { + pt(&mut pts, p); + } + } + for a in &s.arcs { + f(&mut rec, a.r); + f(&mut rec, a.width_mm); + let n = dashes(&mut dash, &a.dash); + u(&mut rec, n); + col(&mut rec, &a.color); + pt(&mut pts, a.center); + pt(&mut pts, a.from); + pt(&mut pts, a.to); + } + for l in &s.lines { + f(&mut rec, l.width_mm); + let n = dashes(&mut dash, &l.dash); + u(&mut rec, n); + u(&mut rec, u32_of(l.z)); + col(&mut rec, &l.color); + pt(&mut pts, l.a); + pt(&mut pts, l.b); + } + for t in texts { + f(&mut rec, t.size_mm); + u(&mut rec, t.align); + u(&mut rec, strs.len() as u32); + u(&mut rec, t.content.len() as u32); + col(&mut rec, &t.color); + pt(&mut pts, t.pos); + strs.extend_from_slice(&t.content); + } + let mut out = Vec::with_capacity(total); + out.extend_from_slice(b"DR2S"); + for v in [1u32, s.fills.len() as u32, s.outlines.len() as u32, s.polylines.len() as u32, s.arcs.len() as u32, s.lines.len() as u32, texts.len() as u32, n_pts as u32, n_dash as u32, str_bytes as u32, 0] { + out.extend_from_slice(&v.to_le_bytes()); + } + out.extend_from_slice(&pts); + out.extend_from_slice(&dash); + out.extend_from_slice(&rec); + out.extend_from_slice(&strs); + out +} + +fn push_dash(out: &mut Vec, d: &SDash) { + match d { + SDash::Absent => out.push(-2.0), + SDash::Null => out.push(-1.0), + SDash::List(l) => { + out.push(l.len() as f64); + out.extend_from_slice(l); + } + } +} + +/// Verlustfreie Ausgabe (Format s. Dateikopf). +pub fn encode_scene_f64(s: &Scene) -> Vec { + let mut out = vec![s.fills.len() as f64, s.outlines.len() as f64, s.polylines.len() as f64, s.arcs.len() as f64, s.lines.len() as f64]; + for x in &s.fills { + out.extend_from_slice(&[x.pts.len() as f64, x.z]); + out.extend_from_slice(&x.color); + for p in &x.pts { + out.extend_from_slice(&[p.x, p.y]); + } + } + for x in s.outlines.iter().chain(&s.polylines) { + out.extend_from_slice(&[x.pts.len() as f64, x.z, x.width_mm]); + push_dash(&mut out, &x.dash); + out.extend_from_slice(&x.color); + for p in &x.pts { + out.extend_from_slice(&[p.x, p.y]); + } + } + for a in &s.arcs { + out.extend_from_slice(&[a.r, a.width_mm]); + push_dash(&mut out, &a.dash); + out.extend_from_slice(&a.color); + out.extend_from_slice(&[a.center.x, a.center.y, a.from.x, a.from.y, a.to.x, a.to.y]); + } + for l in &s.lines { + out.extend_from_slice(&[l.z, l.width_mm]); + push_dash(&mut out, &l.dash); + out.extend_from_slice(&l.color); + out.extend_from_slice(&[l.a.x, l.a.y, l.b.x, l.b.y]); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn farben_wie_to_rgba() { + assert_eq!(to_rgba(Some("#fff")), Some([1.0, 1.0, 1.0, 1.0])); + assert_eq!(to_rgba(Some(" Black ")), Some([0.0, 0.0, 0.0, 1.0])); + assert_eq!(to_rgba(Some("none")), None); + assert_eq!(to_rgba(Some("")), None); + assert_eq!(to_rgba(None), None); + assert_eq!(to_rgba(Some("rgb(1,2,3)")), Some([0.0, 0.0, 0.0, 1.0])); + assert_eq!(to_rgba(Some("#12345")), Some([0.0, 0.0, 0.0, 1.0])); + assert_eq!(to_rgba(Some("#zz0000")), Some([0.0, 0.0, 0.0, 1.0])); + let c = to_rgba(Some("#ff000080")).unwrap(); + assert_eq!(c[3], 128.0 / 255.0); + } + + /// Beispielszene; MUSS mit `sample()` in `render2d/src/scene_bin.rs` übereinstimmen + /// (gemeinsame Bytes: `render2d/tests/fixtures/scene_v1.bin`). + fn sample() -> (Scene, Vec) { + let st = |pts: Vec, color: Rgba, width_mm: f64, dash: SDash, z: f64, width_screen: bool| SStroke { pts, color, width_mm, dash, z, width_screen }; + let s = Scene { + fills: vec![ + SFill { pts: vec![v2(0.0, 0.0), v2(4.0, 0.0), v2(4.0, 3.0)], color: [0.5, 0.25, 0.75, 1.0], z: 0.0 }, + SFill { pts: vec![v2(1.5, 1.5), v2(2.5, 1.5), v2(2.5, 2.5), v2(1.5, 2.5)], color: [1.0, 1.0, 1.0, 0.5], z: 7.0 }, + ], + outlines: vec![st(vec![v2(0.0, 0.0), v2(4.0, 0.0), v2(4.0, 3.0)], [0.0, 0.0, 0.0, 1.0], 0.25, SDash::List(vec![2.0, 1.0]), 1.0, false)], + polylines: vec![ + st(vec![v2(0.0, 0.0), v2(1.0, 1.0)], [0.25, 0.25, 0.25, 1.0], 0.5, SDash::Null, 2.0, false), + st(vec![v2(5.0, 5.0), v2(6.0, 5.0), v2(6.0, 6.0)], [0.5, 0.5, 0.5, 1.0], 1.0, SDash::List(vec![1.0]), 3.0, true), + ], + arcs: vec![SArc { center: v2(1.0, 1.0), from: v2(2.0, 1.0), to: v2(1.0, 2.0), r: 1.0, color: [1.0, 0.0, 0.0, 1.0], width_mm: 0.125, dash: SDash::Absent }], + lines: vec![SLine { a: v2(0.0, 0.0), b: v2(2600000.5, 1200000.25), color: [0.0, 0.5, 0.0, 1.0], width_mm: 0.35, dash: SDash::List(vec![3.0, 1.0, 0.5, 1.0]), z: 4.0 }], + }; + let t = |x: f64, y: f64, content: &str, size_mm: f64, color: Rgba, align: u32| SText { pos: v2(x, y), size_mm, color, align, content: content.as_bytes().to_vec() }; + let texts = vec![ + t(1.0, 2.0, "Küche 12,5 m²", 2.5, [0.0, 0.0, 0.0, 1.0], 1), + t(3.0, 4.0, "", 2.0, [0.0, 0.0, 0.0, 1.0], 2), + t(5.0, 6.0, "A", 1.0, [0.0, 0.0, 1.0, 1.0], 0), + ]; + (s, texts) + } + + #[test] + fn szene_bin_wie_fixture() { + const FIXTURE: &[u8] = include_bytes!("../../render2d/tests/fixtures/scene_v1.bin"); + let (s, t) = sample(); + assert_eq!(encode_scene_bin(&s, &t), FIXTURE); + // Leere Szene = reiner Kopf; Landeskoordinaten bleiben f64. + assert_eq!(encode_scene_bin(&Scene::default(), &[]).len(), 48); + let mut l = Scene::default(); + l.lines.push(SLine { a: v2(2600000.123456, 1200000.654321), b: v2(0.0, 0.0), color: [0.0; 4], width_mm: 0.1, dash: SDash::Null, z: 0.0 }); + let b = encode_scene_bin(&l, &[]); + assert_eq!(f64::from_le_bytes(b[48..56].try_into().unwrap()), 2600000.123456); + } + + #[test] + fn kantenlaeufe_und_naht() { + let sq = vec![v2(0.0, 0.0), v2(1.0, 0.0), v2(1.0, 1.0), v2(0.0, 1.0)]; + // Kante 3 (0,1)→(0,0) unterdrückt: ein Lauf über drei Kanten. + let runs = visible_edge_runs(&sq, &[3.0]); + assert_eq!(runs, vec![vec![v2(0.0, 0.0), v2(1.0, 0.0), v2(1.0, 1.0), v2(0.0, 1.0)]]); + assert!(visible_edge_runs(&sq, &[0.0, 1.0, 2.0, 3.0]).is_empty()); + // Zwei Läufe, die sich zu einem Ring schliessen. + let a = vec![v2(0.0, 0.0), v2(1.0, 0.0), v2(1.0, 1.0)]; + let b = vec![v2(1.0, 1.0), v2(0.0, 1.0), v2(0.0, 0.0)]; + let s = stitch_runs(vec![a, b]); + assert_eq!(s.len(), 1); + assert!(s[0].1); + assert_eq!(s[0].0.len(), 4); + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 0d13f959..2d3fd99c 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -32,6 +32,7 @@ mod voids; mod curves; mod hatch; mod skeleton; +mod plan_scene; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/plan_buf.rs b/src-tauri/core/src/web/plan_buf.rs index 7ed99649..c8610c42 100644 --- a/src-tauri/core/src/web/plan_buf.rs +++ b/src-tauri/core/src/web/plan_buf.rs @@ -6,13 +6,14 @@ //! ein verdrängter Puffer liefert leere Ergebnisse, TS übergibt ihn dann neu. use std::cell::RefCell; +use std::rc::Rc; use wasm_bindgen::prelude::wasm_bindgen; -const MAX_HELD: usize = 8; +const MAX_HELD: usize = 64; const MAX_HELD_BYTES: usize = 96 << 20; thread_local! { - static HELD: RefCell<(u32, Vec<(u32, Vec)>)> = const { RefCell::new((0, Vec::new())) }; + static HELD: RefCell<(u32, Vec<(u32, Rc<[u8]>)>)> = const { RefCell::new((0, Vec::new())) }; } /// Plan-Puffer lesen und neu schreiben (Hin-und-zurück-Prüfung der TS-Kodierung); leer bei @@ -32,7 +33,7 @@ pub fn plan_buf_hold(buf: &[u8]) -> u32 { let mut h = h.borrow_mut(); h.0 = h.0.wrapping_add(1).max(1); let id = h.0; - h.1.push((id, buf.to_vec())); + h.1.push((id, Rc::from(buf))); let mut bytes: usize = h.1.iter().map(|e| e.1.len()).sum(); while h.1.len() > MAX_HELD || (bytes > MAX_HELD_BYTES && h.1.len() > 1) { bytes -= h.1.remove(0).1.len(); @@ -51,3 +52,31 @@ pub fn plan_buf_release(id: u32) { pub(crate) fn with_held(id: u32, f: impl FnOnce(&[u8]) -> R) -> Option { HELD.with(|h| h.borrow().1.iter().find(|e| e.0 == id).map(|e| f(&e.1))) } + +/// Gehaltenen Puffer `id` teilen (bleibt am Leben, auch wenn er verdrängt wird); `None`, wenn er +/// nicht (mehr) da ist. +pub(crate) fn held_rc(id: u32) -> Option> { + HELD.with(|h| h.borrow().1.iter().find(|e| e.0 == id).map(|e| e.1.clone())) +} + +/// Die Puffer der Abschnitte `[nr, von, bis, …]` (s. `plan_parts`) in Abschnitts-Reihenfolge; +/// `None`, wenn einer fehlt oder die Liste kaputt ist. +pub(crate) fn held_for_segs(segs: &[f64]) -> Option)>> { + if segs.len() % 3 != 0 { + return None; + } + let mut out: Vec<(u32, Rc<[u8]>)> = Vec::new(); + for s in segs.chunks_exact(3) { + let nr = crate::plan_buf::whole(s[0])? as u32; + if !out.iter().any(|e| e.0 == nr) { + out.push((nr, held_rc(nr)?)); + } + } + Some(out) +} + +/// Ist der Puffer `id` noch gehalten? +#[wasm_bindgen] +pub fn plan_buf_is_held(id: u32) -> bool { + HELD.with(|h| h.borrow().1.iter().any(|e| e.0 == id)) +} diff --git a/src-tauri/core/src/web/plan_scene.rs b/src-tauri/core/src/web/plan_scene.rs new file mode 100644 index 00000000..f57ce18e --- /dev/null +++ b/src-tauri/core/src/web/plan_scene.rs @@ -0,0 +1,34 @@ +//! Bindungen der Render-Szene (`crate::plan_scene`) auf gehaltenen Plan-Puffern. Abschnitte als +//! `[Puffer-Nr, von, bis, …]`, gedimmte Bereiche als `[von, bis, …]` (s. `plan_parts`). Fehlt +//! ein Puffer (verdrängt) oder ist eine Eingabe kaputt, ist das Ergebnis leer — TS legt die +//! Puffer dann neu ab und fragt nochmals. + +use crate::plan_parts::{parts_from, ranges_from}; +use crate::plan_scene::{build_scene, encode_scene_bin, encode_scene_f64, texts_from, Scene}; +use wasm_bindgen::prelude::wasm_bindgen; + +fn scene_of(segs: &[f64], greyed: &[f64]) -> Option { + let held = super::plan_buf::held_for_segs(segs)?; + let mut parts = parts_from(segs, |nr| held.iter().find(|e| e.0 == nr).map(|e| &*e.1))?; + build_scene(&mut parts, &ranges_from(greyed)?) +} + +/// render2d-Szene v1 (Bytes für `set_scene_bin`/`push_native_scene`); Texte fertig gesetzt aus +/// TS: `[x, y, sizeMm, r, g, b, a, align, nBytes]*` + UTF-8-Bytes. Leer = Fehler. +#[wasm_bindgen] +pub fn plan_scene_bin(segs: &[f64], greyed: &[f64], text_nums: &[f64], text_bytes: &[u8]) -> Vec { + let Some(texts) = texts_from(text_nums, text_bytes) else { return Vec::new() }; + match scene_of(segs, greyed) { + Some(s) => encode_scene_bin(&s, &texts), + None => Vec::new(), + } +} + +/// Verlustfreie Szene (Format s. `plan_scene`) für Export und `--format json`. Leer = Fehler. +#[wasm_bindgen] +pub fn plan_scene_f64(segs: &[f64], greyed: &[f64]) -> Vec { + match scene_of(segs, greyed) { + Some(s) => encode_scene_f64(&s), + None => Vec::new(), + } +} diff --git a/src-tauri/render2d/src/scene_bin.rs b/src-tauri/render2d/src/scene_bin.rs index 89c62611..d5caa39a 100644 --- a/src-tauri/render2d/src/scene_bin.rs +++ b/src-tauri/render2d/src/scene_bin.rs @@ -1,4 +1,4 @@ -// Binaerformat der Plan-Szene (Version 1): TS schreibt (`src/plan/renderSceneBin.ts`), +// Binaerformat der Plan-Szene (Version 1): der Kern schreibt (`core/src/plan_scene.rs`), // Rust liest — ersetzt den JSON-Weg zwischen Webview und render2d. Alles little-endian. // // Aufbau (alle Abschnitte lueckenlos hintereinander, kein Fuellmaterial): @@ -214,7 +214,7 @@ pub fn decode_scene(bytes: &[u8]) -> Result { mod tests { use super::*; - /// Beispielszene; MUSS mit `sampleScene()` in `src/plan/renderSceneBin.test.ts` + /// Beispielszene; MUSS mit `sample()` in `core/src/plan_scene.rs` /// uebereinstimmen (gemeinsame Bytes: `tests/fixtures/scene_v1.bin`). fn sample() -> Scene { Scene { diff --git a/src-tauri/render2d/src/web.rs b/src-tauri/render2d/src/web.rs index 4274a36c..cb8e566f 100644 --- a/src-tauri/render2d/src/web.rs +++ b/src-tauri/render2d/src/web.rs @@ -133,8 +133,8 @@ impl WebPlanRenderer { }) } - /// Setzt die zu zeichnende Szene aus dem Binaerformat von `scene_bin.rs` (TS-Seite: - /// `src/plan/renderSceneBin.ts`). Fremde Version/kaputte Daten → Fehler, die alte + /// Setzt die zu zeichnende Szene aus dem Binaerformat von `scene_bin.rs` (Schreiber: + /// `src-tauri/core/src/plan_scene.rs`). Fremde Version/kaputte Daten → Fehler, die alte /// Szene bleibt. Re-tesselliert + laedt die GPU-Puffer; ruft NICHT selbst `render`. pub fn set_scene_bin(&mut self, bytes: &[u8]) -> Result<(), JsValue> { let scene = decode_scene(bytes).map_err(|e| JsValue::from_str(&format!("Szene lesen: {e}")))?; diff --git a/src/core/extra.ts b/src/core/extra.ts index 9c8a5556..26d37bd7 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -39,7 +39,6 @@ export { sunPosition, shadowPolygons, shadowOfPrism, projectLatLon } from "../an export type { SunPosition } from "../analysis/sun"; export { checkSiteRules, allowedArea, multiPolygonArea, buildingFootprint, modelTop } from "../analysis/siteRules"; export type { SiteCheck } from "../analysis/siteRules"; -export { encodeRenderScene } from "../plan/renderSceneBin"; export { sampleProject } from "../model/sampleProject"; export { parseDxf } from "../io/dxfParser"; export { contoursToDrawings, textsToDrawings, planImportCategories, distinctImportLayers } from "../io/dxfToDrawings"; diff --git a/src/core/index.ts b/src/core/index.ts index 1ef8ca4b..041a3d81 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -290,6 +290,7 @@ export { } from "../plan/toElevation"; export { + planSceneBin, planToRenderScene, } from "../plan/toRenderScene"; diff --git a/src/plan/planBuf.ts b/src/plan/planBuf.ts index 4c6ccea4..0cadd6fb 100644 --- a/src/plan/planBuf.ts +++ b/src/plan/planBuf.ts @@ -178,6 +178,12 @@ export interface EncodeOptions { * (tag 0). Schneller; {@link decodePlanBuf} kann so einen Puffer nicht vollständig lesen. */ lean?: boolean; + /** + * `false`: Texte/Bilder ohne JSON (String-Index −1), aber mit Typ und Pick-Ids — für Kern- + * Verbraucher, die Texte nicht lesen (Render-Szene, Auswahl). {@link decodePlanBuf} kann so + * einen Puffer nicht lesen. Standard `true`. + */ + textJson?: boolean; /** Gruppen `[start, end)` in den Kopf schreiben. */ groups?: ReadonlyArray; bounds?: readonly [number, number, number, number]; @@ -186,6 +192,7 @@ export interface EncodeOptions { /** Primitive → Plan-Puffer v2 (Format s. Dateikopf). */ export function encodePlanBuf(prims: readonly Primitive[], opts: EncodeOptions = {}): Uint8Array { const lean = opts.lean === true; + const textJson = opts.textJson !== false; const strParts: string[] = []; const strTab = new F64Writer(64); const strIdx = new Map(); @@ -385,7 +392,7 @@ export function encodePlanBuf(prims: readonly Primitive[], opts: EncodeOptions = } const tag = p.kind === "text" ? 6 : p.kind === "drawingText" ? 7 : p.kind === "drawingTextPath" ? 8 : 9; head(tag, 0, p); - w.push(str(JSON.stringify(p))); + w.push(textJson ? str(JSON.stringify(p)) : -1); } } } diff --git a/src/plan/planParts.ts b/src/plan/planParts.ts new file mode 100644 index 00000000..a0938a9b --- /dev/null +++ b/src/plan/planParts.ts @@ -0,0 +1,152 @@ +/** + * Zusammengesetzter Plan für Kern-Verbraucher ([K3d], Rust: `src-tauri/core/src/plan_parts.rs`): + * die Primitive eines {@link Plan} als Abschnitte gehaltener Plan-Puffer, in Zeichenreihenfolge. + * Was unverändert aus einem Kern-Puffer stammt (`Plan.bufRuns`, Objekt-Identität geprüft), geht + * ohne Umweg über Objekte; der Rest (2D-Zeichnungen, Schatten, Baurecht, zerlegte Polygone, + * gedimmte Klone) wird einmal in einen eigenen Puffer geschrieben. Der Index eines Primitivs im + * Kern ist seine Stelle in `plan.primitives`. + * + * Abschnitte reisen als `[Puffer-Nr, von, bis, …]` (Nr = `plan_buf_hold`), gedimmte Bereiche + * (`Plan.greyedRanges`) als `[von, bis, …]`. Verdrängt der Kern einen Puffer, liefert er ein + * leeres Ergebnis; {@link withPlanParts} legt dann alles neu ab und fragt nochmals. + */ + +import type { Plan, PlanBufRun, Primitive } from "./generatePlan"; +import { encodePlanBuf } from "./planBuf"; +import { core } from "../engine/coreWasm"; + +/** Ein im Kern ablegbarer Puffer (Kern-Ergebnis `DecodedPlanBuf` oder eigener). */ +interface HoldableBuf { + bytes: Uint8Array; + hold: number; +} + +export interface PlanParts { + bufs: HoldableBuf[]; + /** Abschnitte `[Index in bufs, von, bis, …]`. */ + segs: number[]; + /** Anzahl Primitive (= `plan.primitives.length`). */ + count: number; +} + +/** Unveränderte Kern-Abschnitte (Objekt-Identität) in Plan-Reihenfolge. */ +function verifiedRuns(primitives: readonly Primitive[], runs: readonly PlanBufRun[] | undefined) { + const out: Array<{ start: number; end: number; buf: PlanBufRun["buf"]; from: number }> = []; + for (const r of runs ?? []) { + const n = Math.min(r.to - r.from, primitives.length - r.at); + let k = 0; + while (k < n) { + while (k < n && primitives[r.at + k] !== r.buf.prims[r.from + k]) k++; + const k0 = k; + while (k < n && primitives[r.at + k] === r.buf.prims[r.from + k]) k++; + if (k > k0) out.push({ start: r.at + k0, end: r.at + k, buf: r.buf, from: r.from + k0 }); + } + } + out.sort((a, b) => a.start - b.start); + // Überlappungen (sollte es nicht geben) verwerfen. + const clean: typeof out = []; + let last = 0; + for (const s of out) { + if (s.start < last) continue; + clean.push(s); + last = s.end; + } + return clean; +} + +const cache = new WeakMap(); + +/** + * 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). + */ +export function planParts(plan: Plan, texts = false): PlanParts { + const prims = plan.primitives; + let c = cache.get(prims); + if (!c) { + c = { text: null, noText: null }; + cache.set(prims, c); + } + const hit = texts ? c.text : c.noText; + if (hit) return hit; + const runs = verifiedRuns(prims, plan.bufRuns); + const bufs: HoldableBuf[] = []; + const bufIdx = new Map(); + const idx = (b: HoldableBuf): number => { + let i = bufIdx.get(b); + if (i === undefined) { + i = bufs.length; + bufs.push(b); + bufIdx.set(b, i); + } + return i; + }; + // Lücken zwischen den Kern-Abschnitten sammeln: [Plan-Start, Plan-Ende, Start im eigenen Puffer]. + const rest: Primitive[] = []; + const gaps: Array<[number, number, number]> = []; + let at = 0; + const gap = (end: number) => { + if (end <= at) return; + gaps.push([at, end, rest.length]); + for (let i = at; i < end; i++) rest.push(prims[i]); + }; + for (const r of runs) { + gap(r.start); + at = r.end; + } + gap(prims.length); + const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts }), hold: 0 } : null; + const segs: number[] = []; + let gi = 0; + let ri = 0; + // Abschnitte in Plan-Reihenfolge zusammenführen. + while (gi < gaps.length || ri < runs.length) { + const g = gaps[gi]; + const r = runs[ri]; + if (r === undefined || (g !== undefined && g[0] < r.start)) { + segs.push(idx(own!), g[2], g[2] + (g[1] - g[0])); + gi++; + } else { + segs.push(idx(r.buf), r.from, r.from + (r.end - r.start)); + ri++; + } + } + const out: PlanParts = { bufs, segs, count: prims.length }; + if (texts) c.text = out; + else c.noText = out; + return out; +} + +/** Gedimmte Bereiche flach (`Plan.greyedRanges`). */ +export function greyedFlat(plan: Plan): Float64Array { + const r = plan.greyedRanges ?? []; + const out = new Float64Array(r.length * 2); + r.forEach(([a, b], i) => { + out[2 * i] = a; + out[2 * i + 1] = b; + }); + return out; +} + +/** Abschnitte mit den Kern-Nummern der Puffer (legt fehlende ab). */ +function heldSegs(parts: PlanParts, fresh: boolean): Float64Array { + const c = core(); + for (const b of parts.bufs) if (!b.hold || (fresh && !c.plan_buf_is_held(b.hold))) b.hold = c.plan_buf_hold(b.bytes); + const s = new Float64Array(parts.segs.length); + for (let i = 0; i < parts.segs.length; i += 3) { + s[i] = parts.bufs[parts.segs[i]].hold; + s[i + 1] = parts.segs[i + 1]; + s[i + 2] = parts.segs[i + 2]; + } + return s; +} + +/** + * Kern-Aufruf mit den gehaltenen Abschnitten. `call` liefert ein leeres Ergebnis, wenn ein + * Puffer verdrängt ist — dann werden alle neu abgelegt und es wird einmal wiederholt. + */ +export function withPlanParts(parts: PlanParts, call: (segs: Float64Array) => T): T { + const out = call(heldSegs(parts, false)); + if (out.length > 0 || parts.segs.length === 0) return out; + return call(heldSegs(parts, true)); +} diff --git a/src/plan/randomPrims.testing.ts b/src/plan/randomPrims.testing.ts new file mode 100644 index 00000000..e5982822 --- /dev/null +++ b/src/plan/randomPrims.testing.ts @@ -0,0 +1,177 @@ +// Testhilfe ([K3d]): deterministische Zufalls-Primitive aller Arten für Gleichheitstests der +// Kern-Verbraucher (Render-Szene, Auswahl, SVG-Export) — Polygone mit allen Schraffur-Arten, +// unterdrückten Kanten, Farben in allen Schreibweisen, verkettete 2D-Zeichenlinien, Zickzack, +// Motiv, Strichmuster (fehlend/null/Liste), Bögen, Kreise, Texte, Bilder, gedimmt/deckend. + +import type { HatchRender, Plan, Primitive } from "./generatePlan"; +import type { Vec2 } from "../model/types"; + +export function rng(seed: number): () => number { + let s = seed >>> 0; + return () => { + s = (s + 0x6d2b79f5) >>> 0; + let t = s; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +const COLORS = ["#1a1a1a", "#fff", "#ff000080", "#abc", "#12345", "none", "", "black", "red", " White ", "rgb(1,2,3)", "#zz0000", "#336699", "transparent"]; +const CLS = ["wall", "door-leaf", "door-swing", "wall-axis", "context-line", "draw2d", "window-glass", "stair-line"]; +const PATTERNS: HatchRender["pattern"][] = ["diagonal", "crosshatch", "insulation", "custom", "solid", "none"]; + +export function randomPrims(seed: number, n: number, span = 20): Primitive[] { + const r = rng(seed); + const pick = (a: readonly T[]): T => a[Math.floor(r() * a.length)]; + const pt = (): Vec2 => ({ x: (r() - 0.5) * span, y: (r() - 0.5) * span }); + const dash = (): number[] | null | undefined => { + const k = r(); + return k < 0.4 ? undefined : k < 0.6 ? null : k < 0.7 ? [] : [0.5 + r(), 0.2 + r(), ...(r() < 0.3 ? [0.1] : [])]; + }; + const greyed = (): boolean | undefined => (r() < 0.6 ? undefined : r() < 0.5); + const hatch = (): HatchRender => { + const h: HatchRender = { + pattern: pick(PATTERNS), + scale: r() < 0.1 ? 0 : 0.5 + r() * 2, + angle: Math.floor(r() * 180), + color: pick(COLORS), + lineWeight: r() < 0.2 ? 0 : 0.05 + r() * 0.3, + dash: r() < 0.6 ? null : [0.5 + r(), 0.3], + }; + if (r() < 0.2) h.kind = pick(["vector", "image", "gradient"] as const); + if (r() < 0.2) h.lines = "random"; + if (r() < 0.3) h.origin = pt(); + if (h.pattern === "custom") h.motif = { points: [{ x: 0, y: 0 }, { x: 0.5, y: 0.3 }, { x: 1, y: 0 }], length: 1 }; + return h; + }; + const ring = (): Vec2[] => { + const c = pt(); + const k = 3 + Math.floor(r() * 5); + const rad = 0.3 + r() * 3; + const out: Vec2[] = []; + for (let i = 0; i < k; i++) { + const a = (i / k) * Math.PI * 2; + out.push({ x: c.x + Math.cos(a) * rad * (0.6 + r() * 0.4), y: c.y + Math.sin(a) * rad * (0.6 + r() * 0.4) }); + } + return out; + }; + const out: Primitive[] = []; + const ids = ["d1", "d2", "d3", ""]; + let last: Vec2 | null = null; + while (out.length < n) { + const k = r(); + if (k < 0.25) { + const pts = ring(); + const p: Primitive = { + kind: "polygon", + pts: r() < 0.05 ? pts.slice(0, 2) : pts, + fill: pick(COLORS), + stroke: pick(COLORS), + strokeWidthMm: r() < 0.1 ? 0 : 0.1 + r() * 0.5, + hatch: hatch(), + }; + if (r() < 0.4) delete (p as { hatch?: HatchRender }).hatch; + const g = greyed(); + if (g !== undefined) p.greyed = g; + if (r() < 0.2) p.opacity = r(); + if (r() < 0.4) p.noStrokeEdges = Array.from({ length: Math.floor(r() * pts.length) }, () => Math.floor(r() * pts.length * 2) - 1); + if (r() < 0.3) p.wallId = `w${Math.floor(r() * 5)}`; + else if (r() < 0.3) p.roomId = `r${Math.floor(r() * 5)}`; + else if (r() < 0.2) p.drawingId = pick(ids); + if (r() < 0.1) p.stairId = "s1"; + out.push(p); + } else if (k < 0.7) { + // Linien, oft als Zug (Ende = nächster Anfang). + const a: Vec2 = last && r() < 0.6 ? { ...last } : pt(); + const b: Vec2 = { x: a.x + (r() - 0.5) * 3, y: a.y + (r() - 0.5) * 3 }; + const p: Primitive = { kind: "line", a, b, cls: pick(CLS), weightMm: r() < 0.5 ? 0.25 : 0.18 }; + const d = dash(); + if (d !== undefined) p.dash = d; + if (r() < 0.5) p.color = pick(COLORS); + if (r() < 0.6) p.drawingId = pick(ids); + else if (r() < 0.3) p.openingId = "o1"; + if (r() < 0.05) p.zigzag = { amplitude: 0.5 + r(), wavelength: 2 + r() * 3 }; + else if (r() < 0.05) p.motif = { points: [{ x: 0, y: 0 }, { x: 0.5, y: 0.5 }, { x: 1, y: 0 }], length: 1 + r() }; + const g = greyed(); + if (g !== undefined) p.greyed = g; + out.push(p); + last = b; + } else if (k < 0.78) { + const c = pt(); + const rad = 0.5 + r(); + const a0 = r() * 6; + const a1 = a0 + r() * 3; + const p: Primitive = { + kind: "arc", + center: c, + from: { x: c.x + rad * Math.cos(a0), y: c.y + rad * Math.sin(a0) }, + to: { x: c.x + rad * Math.cos(a1), y: c.y + rad * Math.sin(a1) }, + r: rad, + cls: pick(CLS), + weightMm: 0.18, + }; + const d = dash(); + if (d !== undefined) p.dash = d; + if (r() < 0.5) p.openingId = "o2"; + const g = greyed(); + if (g !== undefined) p.greyed = g; + out.push(p); + } else if (k < 0.86) { + const circle = r() < 0.5; + const c = pt(); + const g = greyed(); + const d = dash(); + if (circle) { + const p: Primitive = { kind: "drawingCircle", center: c, r: 0.2 + r() * 2, fill: pick(COLORS), stroke: pick(COLORS), weightMm: 0.25 }; + if (d !== undefined) p.dash = d; + if (g !== undefined) p.greyed = g; + if (r() < 0.7) p.drawingId = pick(ids); + out.push(p); + } else { + const p: Primitive = { kind: "drawingArc", center: c, r: 0.2 + r() * 2, a0: (r() - 0.5) * 10, a1: (r() - 0.5) * 10, stroke: pick(COLORS), weightMm: 0.25 }; + if (d !== undefined) p.dash = d; + if (g !== undefined) p.greyed = g; + if (r() < 0.7) p.drawingId = pick(ids); + out.push(p); + } + } else if (k < 0.92) { + const g = greyed(); + if (r() < 0.5) { + const p = { + kind: "text", + at: pt(), + doc: { version: 1, paragraphs: [{ align: "center", runs: [{ text: `Raum ${out.length}`, marks: {} }] }] }, + extraLines: r() < 0.5 ? [{ text: "12.5 m²", align: "center" }] : [], + basePt: 8 + Math.floor(r() * 6), + color: pick(COLORS), + roomId: "r1", + } as unknown as Primitive; + if (g !== undefined) (p as { greyed?: boolean }).greyed = g; + out.push(p); + } else { + const p: Primitive = { kind: "drawingText", at: pt(), text: `T ${out.length}\nzwei`, heightM: 0.2 + r(), angle: r() < 0.5 ? 0 : r(), color: pick(COLORS), drawingId: pick(ids) }; + if (r() < 0.3) p.wrapWidth = 1 + r() * 2; + if (g !== undefined) p.greyed = g; + out.push(p); + } + } else if (k < 0.95) { + const a = pt(); + out.push({ kind: "drawingImage", min: a, max: { x: a.x + 1, y: a.y + 1 }, src: "data:image/png;base64,AA", opacity: r(), drawingId: pick(ids) }); + } else if (k < 0.97) { + out.push({ kind: "drawingTextPath", pathPts: [pt(), pt()], text: "Pfad", heightM: 0.3, color: "#000", drawingId: "d1" }); + } else { + // Exakte Wiederholung des letzten Polygons mit unterdrückten Kanten (Naht über Grenzen). + const sq: Vec2[] = [pt()]; + sq.push({ x: sq[0].x + 1, y: sq[0].y }, { x: sq[0].x + 1, y: sq[0].y + 1 }, { x: sq[0].x, y: sq[0].y + 1 }); + const sq2 = [sq[1], { x: sq[1].x + 1, y: sq[1].y }, { x: sq[1].x + 1, y: sq[2].y }, sq[2]]; + out.push({ kind: "polygon", pts: sq, fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [1], wallId: "wx" } as Primitive); + out.push({ kind: "polygon", pts: sq2, fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [3], wallId: "wy" } as Primitive); + } + } + return out; +} + +export function planOf(primitives: Primitive[], greyedRanges?: Array<[number, number]>): Plan { + return { primitives, bounds: { minX: -10, minY: -10, maxX: 10, maxY: 10 }, ...(greyedRanges ? { greyedRanges } : {}) }; +} diff --git a/src/plan/renderSceneBin.test.ts b/src/plan/renderSceneBin.test.ts deleted file mode 100644 index fb0ffcf2..00000000 --- a/src/plan/renderSceneBin.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { readFileSync, writeFileSync } from "node:fs"; -import { encodeRenderScene, SCENE_BIN_VERSION } from "./renderSceneBin"; -import type { RScene } from "./toRenderScene"; - -const FIXTURE = new URL("../../src-tauri/render2d/tests/fixtures/scene_v1.bin", import.meta.url); - -/** Beispielszene; MUSS mit `sample()` in `src-tauri/render2d/src/scene_bin.rs` übereinstimmen. */ -function sampleScene(): RScene { - return { - fills: [ - { pts: [[0, 0], [4, 0], [4, 3]], color: [0.5, 0.25, 0.75, 1], z: 0 }, - { pts: [[1.5, 1.5], [2.5, 1.5], [2.5, 2.5], [1.5, 2.5]], color: [1, 1, 1, 0.5], z: 7 }, - ], - outlines: [{ pts: [[0, 0], [4, 0], [4, 3]], color: [0, 0, 0, 1], widthMm: 0.25, dash: [2, 1], z: 1 }], - polylines: [ - { pts: [[0, 0], [1, 1]], color: [0.25, 0.25, 0.25, 1], widthMm: 0.5, dash: null, z: 2 }, - { pts: [[5, 5], [6, 5], [6, 6]], color: [0.5, 0.5, 0.5, 1], widthMm: 1, dash: [1], z: 3, widthScreen: true }, - ], - arcs: [{ center: [1, 1], from: [2, 1], to: [1, 2], r: 1, color: [1, 0, 0, 1], widthMm: 0.125 }], - lines: [{ a: [0, 0], b: [2600000.5, 1200000.25], color: [0, 0.5, 0, 1], widthMm: 0.35, dash: [3, 1, 0.5, 1], z: 4 }], - texts: [ - { pos: [1, 2], content: "Küche 12,5 m²", sizeMm: 2.5, color: [0, 0, 0, 1], align: "center" }, - { pos: [3, 4], content: "", sizeMm: 2, color: [0, 0, 0, 1], align: "right" }, - { pos: [5, 6], content: "A", sizeMm: 1, color: [0, 0, 1, 1], align: "left" }, - ], - images: [], - bounds: { minX: 0, minY: 0, maxX: 1, maxY: 1 }, - }; -} - -const empty = (): RScene => ({ - fills: [], outlines: [], polylines: [], arcs: [], lines: [], texts: [], images: [], - bounds: { minX: 0, minY: 0, maxX: 0, maxY: 0 }, -}); - -describe("encodeRenderScene", () => { - it("liefert byte-genau die Fixture, die der Rust-Dekodierer liest", () => { - const bytes = encodeRenderScene(sampleScene()); - if (process.env.UPDATE_SCENE_FIXTURE) writeFileSync(FIXTURE, bytes); - expect(Buffer.from(bytes).equals(readFileSync(FIXTURE))).toBe(true); - }); - - it("schreibt Kopf, Zähler und die exakte Länge", () => { - const bytes = encodeRenderScene(sampleScene()); - const h = new Uint32Array(bytes.buffer, bytes.byteOffset, 12); - expect(String.fromCharCode(...bytes.subarray(0, 4))).toBe("DR2S"); - expect(h[1]).toBe(SCENE_BIN_VERSION); - expect([...h.subarray(2, 8)]).toEqual([2, 1, 2, 1, 1, 3]); - const nPts = 3 + 4 + 3 + 2 + 3 + 3 + 2 + 3; - expect(h[8]).toBe(nPts); - expect(h[9]).toBe(2 + 1 + 4); - expect(h[10]).toBe(new TextEncoder().encode("Küche 12,5 m²A").length); - const words = 2 * 6 + 8 + 2 * 9 + 7 + 7 + 3 * 8; - expect(bytes.length).toBe(48 + nPts * 16 + 7 * 4 + words * 4 + h[10]); - }); - - it("behält Koordinaten als f64 (LV95-gross)", () => { - const s = empty(); - s.lines.push({ a: [2600000.123456, 1200000.654321], b: [0, 0], color: [0, 0, 0, 1], widthMm: 0.1, z: 0 }); - const bytes = encodeRenderScene(s); - const pts = new Float64Array(bytes.buffer, bytes.byteOffset + 48, 4); - expect(pts[0]).toBe(2600000.123456); - expect(pts[1]).toBe(1200000.654321); - }); - - it("kodiert die leere Szene als reinen Kopf und wirft bei Unsinn nicht", () => { - expect(encodeRenderScene(empty()).length).toBe(48); - const s = empty(); - s.fills.push({ pts: [], color: [NaN, 0, 0, 1], z: -1 }); - s.texts.push({ pos: [Infinity, 0], content: "\u{1F600}", sizeMm: 1, color: [0, 0, 0, 1], align: "left" }); - expect(() => encodeRenderScene(s)).not.toThrow(); - }); -}); - -/** Zufallsszene (deterministisch) für die Messung. */ -function bigScene(nLines: number, nFills: number, nTexts: number): RScene { - let seed = 42; - const rnd = () => ((seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) >>> 8) / 16777216; - const s = empty(); - for (let i = 0; i < nLines; i++) { - const x = rnd() * 500, y = rnd() * 500; - s.lines.push({ a: [x, y], b: [x + rnd(), y + rnd()], color: [0.1, 0.1, 0.1, 1], widthMm: 0.18, dash: i % 10 === 0 ? [2, 1] : null, z: i % 50 }); - } - for (let i = 0; i < nFills; i++) { - const x = rnd() * 500, y = rnd() * 500; - s.fills.push({ pts: [0, 1, 2, 3, 4, 5].map((k) => [x + k * rnd(), y + k * rnd()] as [number, number]), color: [0.8, 0.8, 0.75, 1], z: i % 50 }); - } - for (let i = 0; i < nTexts; i++) { - s.texts.push({ pos: [rnd() * 500, rnd() * 500], content: `Raum ${i} 12,5 m²`, sizeMm: 2, color: [0, 0, 0, 1], align: "center" }); - } - return s; -} - -describe("Messung JSON gegen Binär (Kodierung, Node)", () => { - it("kodiert kleine und grosse Szene und gibt die Zeiten aus", () => { - const best = (f: () => unknown) => { - let b = Infinity; - for (let i = 0; i < 5; i++) { - const t = performance.now(); - f(); - b = Math.min(b, performance.now() - t); - } - return b; - }; - for (const [name, sc] of [ - ["klein (200 Linien, 50 Füllungen, 20 Texte)", bigScene(200, 50, 20)], - ["gross (200000 Linien, 20000 Füllungen, 1000 Texte)", bigScene(200_000, 20_000, 1000)], - ] as const) { - const json = JSON.stringify(sc); - const bin = encodeRenderScene(sc); - const tj = best(() => JSON.stringify(sc)); - const tb = best(() => encodeRenderScene(sc)); - console.log(`${name}: JSON ${(json.length / 1024) | 0} KB ${tj.toFixed(2)} ms | binär ${(bin.length / 1024) | 0} KB ${tb.toFixed(2)} ms`); - expect(bin.length).toBeLessThan(json.length); - } - }); -}); diff --git a/src/plan/renderSceneBin.ts b/src/plan/renderSceneBin.ts deleted file mode 100644 index e054e2b7..00000000 --- a/src/plan/renderSceneBin.ts +++ /dev/null @@ -1,157 +0,0 @@ -// Binärkodierung der Render-Szene (`RScene`) für render2d — Gegenstück zu -// `src-tauri/render2d/src/scene_bin.rs` (dort steht die Formatbeschreibung; beide Seiten -// müssen Version und Aufbau gleich halten, die gemeinsame Fixture -// `src-tauri/render2d/tests/fixtures/scene_v1.bin` prüft das in beiden Tests). -// -// Zweiphasig: erst Zähler (Punkte, Strichmuster, Strings), dann ein einziger Puffer, in den -// über typisierte Sichten geschrieben wird (kein DataView je Wert, keine Zwischenarrays). -// Little-endian setzen wir voraus (alle Zielplattformen); `LITTLE_ENDIAN` prüft das einmal. - -import type { RScene, RTextAlign } from "./toRenderScene"; - -export const SCENE_BIN_VERSION = 1; -const HEADER_BYTES = 48; -const ALIGN: Record = { left: 0, center: 1, right: 2 }; - -const LITTLE_ENDIAN = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1; - -const textEncoder = new TextEncoder(); - -/** Kodiert die Szene (ohne `images`/`bounds`, die der Renderer nicht kennt). */ -export function encodeRenderScene(scene: RScene): Uint8Array { - if (!LITTLE_ENDIAN) throw new Error("Szenenkodierung setzt Little-Endian voraus"); - const { fills, outlines, polylines, arcs, lines, texts } = scene; - - let nPts = 0; - let nDash = 0; - for (const f of fills) nPts += f.pts.length; - for (const o of outlines) { - nPts += o.pts.length; - nDash += o.dash?.length ?? 0; - } - for (const p of polylines) { - nPts += p.pts.length; - nDash += p.dash?.length ?? 0; - } - for (const a of arcs) nDash += a.dash?.length ?? 0; - for (const l of lines) nDash += l.dash?.length ?? 0; - nPts += arcs.length * 3 + lines.length * 2 + texts.length; - - const strs: Uint8Array[] = new Array(texts.length); - let strBytes = 0; - for (let i = 0; i < texts.length; i++) { - strs[i] = textEncoder.encode(texts[i].content); - strBytes += strs[i].length; - } - - const words = - fills.length * 6 + outlines.length * 8 + polylines.length * 9 + arcs.length * 7 + lines.length * 7 + texts.length * 8; - const ptsOff = HEADER_BYTES; - const dashOff = ptsOff + nPts * 16; - const recOff = dashOff + nDash * 4; - const strOff = recOff + words * 4; - const total = strOff + strBytes; - if (total > 0xffffffff || nPts > 0xffffffff) throw new Error("Szene zu gross für das Binärformat"); - - const buf = new ArrayBuffer(total); - const bytes = new Uint8Array(buf); - const hdr = new Uint32Array(buf, 0, HEADER_BYTES / 4); - const pts = new Float64Array(buf, ptsOff, nPts * 2); - const dash = new Float32Array(buf, dashOff, nDash); - const u32 = new Uint32Array(buf, recOff, words); - const f32 = new Float32Array(buf, recOff, words); - - bytes.set([0x44, 0x52, 0x32, 0x53], 0); // "DR2S" - hdr[1] = SCENE_BIN_VERSION; - hdr[2] = fills.length; - hdr[3] = outlines.length; - hdr[4] = polylines.length; - hdr[5] = arcs.length; - hdr[6] = lines.length; - hdr[7] = texts.length; - hdr[8] = nPts; - hdr[9] = nDash; - hdr[10] = strBytes; - hdr[11] = 0; - - let pi = 0; // Index in pts (Doubles) - let di = 0; // Index in dash - let w = 0; // Index in u32/f32 - const ring = (a: ArrayLike) => { - for (let i = 0; i < a.length; i++) { - pts[pi++] = a[i][0]; - pts[pi++] = a[i][1]; - } - }; - const col = (c: readonly number[]) => { - f32[w++] = c[0]; - f32[w++] = c[1]; - f32[w++] = c[2]; - f32[w++] = c[3]; - }; - const dashes = (d: readonly number[] | null | undefined): number => { - if (!d || d.length === 0) return 0; - for (let i = 0; i < d.length; i++) dash[di++] = d[i]; - return d.length; - }; - - for (const f of fills) { - u32[w++] = f.pts.length; - u32[w++] = f.z >>> 0; - col(f.color); - ring(f.pts); - } - for (const o of outlines) { - u32[w++] = o.pts.length; - u32[w++] = o.z >>> 0; - f32[w++] = o.widthMm; - u32[w++] = dashes(o.dash); - col(o.color); - ring(o.pts); - } - for (const p of polylines) { - u32[w++] = p.pts.length; - u32[w++] = p.z >>> 0; - f32[w++] = p.widthMm; - u32[w++] = dashes(p.dash); - u32[w++] = p.widthScreen ? 1 : 0; - col(p.color); - ring(p.pts); - } - for (const a of arcs) { - f32[w++] = a.r; - f32[w++] = a.widthMm; - u32[w++] = dashes(a.dash); - col(a.color); - pts[pi++] = a.center[0]; - pts[pi++] = a.center[1]; - pts[pi++] = a.from[0]; - pts[pi++] = a.from[1]; - pts[pi++] = a.to[0]; - pts[pi++] = a.to[1]; - } - for (const l of lines) { - f32[w++] = l.widthMm; - u32[w++] = dashes(l.dash); - u32[w++] = l.z >>> 0; - col(l.color); - pts[pi++] = l.a[0]; - pts[pi++] = l.a[1]; - pts[pi++] = l.b[0]; - pts[pi++] = l.b[1]; - } - let so = 0; - for (let i = 0; i < texts.length; i++) { - const t = texts[i]; - f32[w++] = t.sizeMm; - u32[w++] = ALIGN[t.align] ?? 0; - u32[w++] = so; - u32[w++] = strs[i].length; - col(t.color); - pts[pi++] = t.pos[0]; - pts[pi++] = t.pos[1]; - bytes.set(strs[i], strOff + so); - so += strs[i].length; - } - return bytes; -} diff --git a/src/plan/toRenderScene.test.ts b/src/plan/toRenderScene.test.ts new file mode 100644 index 00000000..2bd0e453 --- /dev/null +++ b/src/plan/toRenderScene.test.ts @@ -0,0 +1,70 @@ +// Render-Szene aus dem Kern ([K3d], `core/src/plan_scene.rs`): Verkettung der 2D-Zeichenlinien, +// Kantennaht über Polygon-Grenzen, gedimmte Bereiche ohne Klonen, Binärszene passt zur +// Objekt-Szene, verdrängte Puffer werden neu abgelegt. (Bitgleich zur früheren TS-Fassung +// geprüft: Beispielprojekt, 400 Zufallslisten, grosses Projekt — s. TODO [K3d].) + +import { describe, expect, it } from "vitest"; +import { planSceneBin, planToRenderScene } from "./toRenderScene"; +import { generatePlan, generateVisibleLevelsPlan, materializeGreyed, materializeUnderlay } from "./generatePlan"; +import type { Primitive } from "./generatePlan"; +import { sampleProject } from "../model/sampleProject"; +import { flattenCategories } from "../model/types"; +import { planOf, randomPrims } from "./randomPrims.testing"; +import { planParts } from "./planParts"; +import { core } from "../engine/coreWasm"; + +const codes = new Set(flattenCategories(sampleProject.layers).map((c) => c.code)); + +const line = (ax: number, ay: number, bx: number, by: number, extra: Partial = {}): Primitive => + ({ kind: "line", a: { x: ax, y: ay }, b: { x: bx, y: by }, cls: "draw2d", weightMm: 0.25, drawingId: "d", ...extra }) as Primitive; + +describe("planToRenderScene (Kern)", () => { + it("verkettet 2D-Zeichenlinien zu Polylinie bzw. Umriss", () => { + const open = planToRenderScene(planOf([line(0, 0, 1, 0), line(1, 0, 1, 1), line(5, 5, 6, 6, { drawingId: undefined })])); + expect(open.polylines.map((p) => p.pts.length)).toEqual([3]); + expect(open.lines.length).toBe(1); + const ring = planToRenderScene(planOf([line(0, 0, 1, 0), line(1, 0, 1, 1), line(1, 1, 0, 0)])); + expect(ring.outlines.map((o) => o.pts.length)).toEqual([3]); + expect(ring.outlines[0].dash).toBeNull(); + }); + + it("näht unterdrückte Kanten zweier Polygone zu einem Ring", () => { + const a: Primitive = { kind: "polygon", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }], fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [1] }; + const b: Primitive = { kind: "polygon", pts: [{ x: 1, y: 0 }, { x: 2, y: 0 }, { x: 2, y: 1 }, { x: 1, y: 1 }], fill: "#eee", stroke: "#000", strokeWidthMm: 0.35, noStrokeEdges: [3] }; + const s = planToRenderScene(planOf([a, b])); + expect(s.fills.length).toBe(2); + expect(s.outlines.length).toBe(1); + expect(s.outlines[0].pts.length).toBe(6); + expect(s.outlines[0].z).toBe(3); + }); + + it("gedimmte Bereiche wirken wie materialisiertes `greyed`", () => { + for (let seed = 1; seed < 30; seed++) { + const prims = randomPrims(seed, 40); + const plan = planOf(prims, [[2, 15], [20, 33]]); + expect(JSON.stringify(planToRenderScene(plan))).toBe(JSON.stringify(planToRenderScene(materializeGreyed(plan, true)))); + expect(Buffer.from(planSceneBin(plan)).equals(Buffer.from(planSceneBin(materializeGreyed(plan, true))))).toBe(true); + } + const over = generateVisibleLevelsPlan(sampleProject, "og", codes, undefined, "mittel", false, false, () => ({ render: true, greyed: true, locked: false }), 100, true); + const plan = materializeUnderlay(over); + expect(plan.greyedRanges?.length).toBeGreaterThan(0); + expect(JSON.stringify(planToRenderScene(plan))).toBe(JSON.stringify(planToRenderScene(materializeGreyed(plan, true)))); + }); + + it("Binärszene: Zähler wie die Objekt-Szene", () => { + const plan = generatePlan(sampleProject, "eg", codes); + const s = planToRenderScene(plan); + const b = planSceneBin(plan); + const h = new Uint32Array(b.buffer, b.byteOffset, 12); + expect(String.fromCharCode(...b.subarray(0, 4))).toBe("DR2S"); + expect([...h.subarray(1, 8)]).toEqual([1, s.fills.length, s.outlines.length, s.polylines.length, s.arcs.length, s.lines.length, s.texts.length]); + expect(s.fills.length).toBeGreaterThan(10); + }); + + it("verdrängte Puffer werden neu abgelegt", () => { + const plan = generatePlan(sampleProject, "eg", codes); + const before = planSceneBin(plan); + for (const buf of planParts(plan).bufs) core().plan_buf_release(buf.hold); + expect(Buffer.from(planSceneBin(plan)).equals(Buffer.from(before))).toBe(true); + }); +}); diff --git a/src/plan/toRenderScene.ts b/src/plan/toRenderScene.ts index e3103326..0c7cd1c4 100644 --- a/src/plan/toRenderScene.ts +++ b/src/plan/toRenderScene.ts @@ -1,30 +1,24 @@ -// Flacht einen {@link Plan} (die eine Wahrheit aus generatePlan) auf das -// GPU-nahe Szenenformat des nativen render2d-Renderers ab: Füllpolygone, -// Umrisse, Linien und Textzeilen. Text wird zeilenweise geflacht (Rich-Text-Doc -// + Live-Zusatzzeilen) — die echten Glyphen rastert der Rust-Renderer über -// einen GPU-Glyphen-Atlas (glyphon/cosmic-text), keine Vektor-Ersatzschrift. +// Render-Szene eines {@link Plan} für render2d (Browser über WASM/WebGPU, natives Fenster über +// `push_native_scene`) und für den Druck-/SVG-Export. Die Geometrie (Füllungen, Umrisse, +// Polylinien, Bögen, Linien samt Maler-Reihenfolge `z`, Verkettung, Kantennaht, Schraffur-Läufe, +// Zickzack/Motiv) rechnet der Kern direkt aus dem Plan-Puffer ([K3d], `src-tauri/core/src/ +// plan_scene.rs`, über die Abschnitte aus `planParts.ts`) — ohne Umweg über `Primitive[]`. Hier +// bleibt das Text-Layout (Rich-Text-Zeilen + Live-Zusatzzeilen, die Glyphen rastert render2d) +// und das Durchreichen eingebetteter Bilder. // -// Das erzeugte Objekt matcht 1:1 die serde-Structs render2d::types::Scene +// Das Szenen-Objekt matcht 1:1 die serde-Structs render2d::types::Scene // { fills:[{pts,color}], outlines:[{pts,color,widthMm,dash}], // polylines:[{pts,color,widthMm,dash}], arcs:[{center,from,to,r,color,widthMm,dash}], // lines:[{a,b,color,widthMm,dash}], texts:[{pos,content,sizeMm,color,align}] } -// mit Point = [x,y] (Meter) und Rgba = [r,g,b,a] (0..1). -// -// Bögen werden NICHT hier tessellliert: der Rust-Renderer zeichnet sie -// mathematisch exakt per SDF-Fragment-Shader (`shaders::ARC_WGSL`, eine -// analytische Instanz je Bogen) — bei jeder Vergrößerung ein echter Kreis statt -// eines Vielecks, ohne Neu-Tessellierung. Strichmuster -// (`dash`, mm Papier) werden ebenfalls unverändert durchgereicht — das geometrische -// Zerschneiden in Teilstücke (`applyDashRuns`-Algorithmus) passiert erst NACH der -// Bogen-Tessellierung in Rust (`tessellate::split_dash`), damit die Phase über die -// gesamte (ggf. verkettete oder adaptiv tessellierte) Strecke durchläuft. +// mit Point = [x,y] (Meter) und Rgba = [r,g,b,a] (0..1). Bögen bleiben unvortesselliert +// (render2d zeichnet sie per SDF-Shader), Strichmuster (Papier-mm) werden durchgereicht. -import type { Plan, Primitive } from "./generatePlan"; -import { applyDashRuns, buildHatchRuns, zigzagPoints, motifPoints, DASH_MM_TO_M } from "./glPlan/glPlanHatch"; +import type { Plan } from "./generatePlan"; +import { inGreyedRange } from "./generatePlan"; import { docToLines, wrapDocToLines } from "../text/renderHtml"; import { docFromText } from "../text/richText"; - -type LinePrim = Extract; +import { core } from "../engine/coreWasm"; +import { greyedFlat, planParts, withPlanParts } from "./planParts"; export type RPoint = [number, number]; export type RRgba = [number, number, number, number]; @@ -133,57 +127,15 @@ export interface RScene { bounds: RBounds; } -const DEFAULT_LINE = "#1a1a1a"; - /** - * Strichfarben/-deckkraft je CSS-Klasse — Spiegel der `.plan-svg .`-Regeln - * in styles.css: Im SVG-Pfad ÜBERSTIMMT eine CSS-`stroke`-Property das inline - * gesetzte `stroke`-Attribut (Präsentationsattribut), d. h. für diese Klassen - * gilt IMMER die CSS-Farbe. Klassen ohne CSS-`stroke` (draw2d, stair-*, - * context-line) behalten die Modell-Farbe; context-line trägt zusätzlich - * `opacity: 0.7`, wall-axis `opacity: 0.85`. - */ -const CLS_STROKE: Record = { - "door-leaf": "#1a1a1a", - "door-swing": "#1a1a1a", - "door-frame": "#1a1a1a", - "window-glass": "#1a1a1a", - "wall-axis": "#4a453e", // var(--accent) des hellen Standard-Themes -}; -const CLS_OPACITY: Record = { - "wall-axis": 0.85, - "context-line": 0.7, -}; - -/** - * Fester Grauton gedimmter (greyed) Primitive — ECHTE Umfärbung statt - * Deckkraft (dünne Haarlinien auf dem hellen Zeichenblatt wären bei reiner - * Transparenz kaum erkennbar gedimmt). Gleicher Ton wie GREYED_COLOR in - * PlanView.tsx / GREY_RGB in glPlanCompile.ts (#8c8c8c ≈ 0.549). + * Fester Grauton gedimmter (greyed) Texte — gleicher Ton wie GREYED_COLOR in PlanView.tsx und + * `GREY_RGB` im Kern (#8c8c8c ≈ 0.549). */ const GREY_RGB = 0.549; -/** Farbe mit Klassen-Deckkraft multiplizieren, bei Greyed-Dimmung auf den festen Grauton umfärben. */ -function withOpacity(col: RRgba, cls: string | undefined, greyed: boolean | undefined): RRgba { - const o = cls ? CLS_OPACITY[cls] ?? 1 : 1; - const rgb: RRgba = greyed ? [GREY_RGB, GREY_RGB, GREY_RGB, col[3]] : col; - return o === 1 ? rgb : [rgb[0], rgb[1], rgb[2], rgb[3] * o]; -} - -/** - * Wie `withOpacity`, aber für FLÄCHEN-Füllung: gedimmte Flächen bleiben WEISS - * statt grau eingefärbt — nur der Umriss (weiterhin `withOpacity`) macht das - * Element als gedimmt erkennbar (Nutzer-Wunsch: "im Hintergrund nicht als - * graue Fläche gefüllt, sondern weiss mit nur den Linien sichtbar"). - */ -function withFillOpacity(col: RRgba, greyed: boolean | undefined): RRgba { - return greyed ? [1, 1, 1, col[3]] : col; -} - -/** Strichfarbe einer line/arc-Primitive: CSS-Klassen-Farbe > Modell-Farbe > Tinte. */ -function strokeColorFor(cls: string | undefined, color: string | undefined): RRgba { - const css = cls ? CLS_STROKE[cls] : undefined; - return toRgba(css ?? color ?? DEFAULT_LINE, 1) ?? [0.1, 0.1, 0.1, 1]; +/** Textfarbe gedimmt: auf den festen Grauton umfärben (Deckkraft bleibt). */ +function greyedColor(col: RRgba, greyed: boolean | undefined): RRgba { + return greyed ? [GREY_RGB, GREY_RGB, GREY_RGB, col[3]] : col; } /** 1 Punkt (pt) in Papier-Millimetern. */ @@ -194,8 +146,7 @@ const PT_TO_MM = 25.4 / 72; * Modus: dort belegt 1 pt Schrift (1/72)·0.0254·100 Modell-Meter. Der native * Renderer rechnet im Anzeigemodus mit `paper_scale_n = 100`, damit ist * `sizeMm = pt · PT_TO_MM` exakt die Browser-Darstellung. Für Aufrufer MIT - * Massstabskontext (z. B. PDF-Export) übersteuert `planToRenderScene`s - * `paperScaleN`-Parameter diesen Default — siehe `mmToM` dort. + * Massstabskontext (z. B. PDF-Export) übersteuert `paperScaleN` diesen Default. */ const STAMP_DEFAULT_N = 100; @@ -208,7 +159,7 @@ const NAMED: Record = { transparent: "none", }; -/** Hex/Named-Farbe → [r,g,b,a] in 0..1, oder null bei "none"/leer. */ +/** Hex/Named-Farbe → [r,g,b,a] in 0..1, oder null bei "none"/leer (Kern: `plan_scene::to_rgba`). */ function toRgba(input: string | undefined, alpha = 1): RRgba | null { if (!input) return null; let h = input.trim().toLowerCase(); @@ -232,318 +183,23 @@ function toRgba(input: string | undefined, alpha = 1): RRgba | null { return [r, g, b, a]; } -/** Zwei Modell-Punkte (Meter) als gleich behandeln (Verkettungs-Toleranz). */ -function samePt(a: RPoint, b: RPoint): boolean { - return Math.abs(a[0] - b[0]) < 1e-6 && Math.abs(a[1] - b[1]) < 1e-6; -} - -/** Gleicher Linienstil (für das Verketten aufeinanderfolgender 2D-Zeichenlinien). */ -function sameLineStyle(a: LinePrim, b: LinePrim): boolean { - return ( - a.cls === b.cls && - a.weightMm === b.weightMm && - (a.color ?? "") === (b.color ?? "") && - JSON.stringify(a.dash ?? null) === JSON.stringify(b.dash ?? null) - ); -} - /** - * Zerlegt einen Polygon-Ring in zusammenhängende Läufe SICHTBARER Kanten (die - * `noStroke`-Kanten werden ausgelassen). Jeder Lauf beginnt an einer sichtbaren - * Kante, deren Vorgänger unterdrückt ist. Portiert aus PlanView.visibleEdgeRuns — - * so bekommen die inneren Ecken eine Gehrung statt Stumpfkappen. + * Textzeilen und eingebettete Bilder eines Plans in Zeichenreihenfolge. Layout wie im SVG-Pfad + * (PlanView, case "text"): Rich-Text-Zeilen + Live-Zusatzzeilen, Block vertikal um den Anker + * zentriert, Zeilenvorschub 1.3·Basisgröße; Einzeltexte (`drawingText`) top-down ab `at` mit + * `heightM` als Basisgrösse. `paperScaleN` (1:N) rechnet Papier-mm in Modell-Meter um. */ -function visibleEdgeRuns(pts: RPoint[], noStroke: number[]): RPoint[][] { - const n = pts.length; - const skip = new Set(noStroke.map((i) => ((i % n) + n) % n)); - if (skip.size >= n || n < 2) return []; - const visible = (i: number) => !skip.has(((i % n) + n) % n); - const runs: RPoint[][] = []; - for (let s = 0; s < n; s++) { - if (!visible(s) || visible(s - 1 + n)) continue; // kein Lauf-Anfang - const run: RPoint[] = [pts[s]]; - let j = s; - while (visible(j) && j - s < n) { - run.push(pts[(j + 1) % n]); - j++; - } - runs.push(run); - } - return runs; -} - -/** - * Näht sichtbare Kantenläufe ÜBER Polygon-Grenzen hinweg zusammen: Läufe mit - * koinzidenten Endpunkten (und GENAU zwei beteiligten Enden — T-Stösse bleiben - * unangetastet) werden zu einer Kette verbunden, ggf. mit Richtungsumkehr. - * Schliesst sich eine Kette, wird sie als geschlossener Ring markiert. So - * bekommt eine Wandecke, deren zwei Schenkel aus VERSCHIEDENEN Wand-Polygonen - * stammen, dieselbe Gehrung wie die inneren Ecken eines einzelnen Laufs - * (statt zweier Stumpfkappen, die eine Kerbe bilden). - */ -function stitchRuns(runs: RPoint[][]): { pts: RPoint[]; closed: boolean }[] { - const eps = 1e-5; - const key = (p: RPoint) => `${Math.round(p[0] / eps)},${Math.round(p[1] / eps)}`; - // Endpunkt-Belegung zählen: verkettet wird nur, wo genau ZWEI Enden liegen. - const endCount = new Map(); - for (const r of runs) { - for (const p of [r[0], r[r.length - 1]]) { - endCount.set(key(p), (endCount.get(key(p)) ?? 0) + 1); - } - } - const joinable = (p: RPoint) => endCount.get(key(p)) === 2; - - const pool = runs.map((pts) => ({ pts, used: false })); - const out: { pts: RPoint[]; closed: boolean }[] = []; - for (const seed of pool) { - if (seed.used) continue; - seed.used = true; - let chain = seed.pts; - let extended = true; - while (extended && !(chain.length > 2 && samePt(chain[0], chain[chain.length - 1]))) { - extended = false; - const head = chain[0]; - const tail = chain[chain.length - 1]; - for (const cand of pool) { - if (cand.used) continue; - const cs = cand.pts[0]; - const ce = cand.pts[cand.pts.length - 1]; - if (joinable(tail) && samePt(tail, cs)) { - chain = chain.concat(cand.pts.slice(1)); - } else if (joinable(tail) && samePt(tail, ce)) { - chain = chain.concat([...cand.pts].reverse().slice(1)); - } else if (joinable(head) && samePt(head, ce)) { - chain = cand.pts.concat(chain.slice(1)); - } else if (joinable(head) && samePt(head, cs)) { - chain = [...cand.pts].reverse().concat(chain.slice(1)); - } else { - continue; - } - cand.used = true; - extended = true; - break; - } - } - const closed = chain.length > 3 && samePt(chain[0], chain[chain.length - 1]); - out.push({ pts: closed ? chain.slice(0, -1) : chain, closed }); - } - return out; -} - -/** - * Wandelt einen Plan in eine native render2d-Szene um. Zusammenhängende Umriss- - * und Zeichnungskanten werden zu OFFENEN Polylinien verkettet (gehrte Ecken); - * nur genuin einzelne Segmente (Türblätter, Referenzlinien) bleiben `lines`. - * - * `paperScaleN` ist der Massstab-Nenner N (1:N), mit dem die vertikale - * Zeilenposition mehrzeiliger Stempel-Texte in Modell-Meter umgerechnet wird - * (Papier-mm sind massstabsunabhängig, ihre Weltgrösse aber nicht — analog zu - * PlanViews `nRef`, s. `PlanView.tsx` case "text"). Default 100 für Aufrufer - * ohne Massstabskontext (WASM-Viewport, `nativeSync.ts`). - */ -export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): RScene { +export function planSceneTexts(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): { texts: RText[]; images: RImage[] } { const mmToM = paperScaleN / 1000; // Papier-mm → Modell-Meter beim gewählten Massstab. - const fills: RFill[] = []; - const outlines: ROutline[] = []; - const polylines: RPolyline[] = []; - const arcs: RArc[] = []; - const lines: RLine[] = []; const texts: RText[] = []; const images: RImage[] = []; - - // Sichtbare Umriss-Läufe werden erst GESAMMELT (nach Stil gruppiert) und am - // Ende über Polygon-Grenzen hinweg zusammengenäht — erst dadurch bekommen - // Wand-zu-Wand-Ecken (zwei Polygone!) eine Gehrung statt einer Kerbe. - const edgeRunGroups = new Map(); - const collectEdgeRun = (run: RPoint[], color: RRgba, widthMm: number, z: number) => { - const k = `${color.join(",")}|${widthMm}`; - let g = edgeRunGroups.get(k); - if (!g) { - g = { color, widthMm, runs: [], z }; - edgeRunGroups.set(k, g); - } - g.runs.push(run); - // Die Kette zeichnet, wenn ihr SPÄTESTER Beitrag im SVG zeichnen würde. - g.z = Math.max(g.z, z); - }; - - // Maler-Reihenfolge: läuft in EXAKT der Reihenfolge mit, in der der SVG-Pfad - // die Elemente zeichnet (Primitive in Array-Reihenfolge; je Polygon Füllung → - // Schraffur → Umriss). Jedes emittierte Szenen-Element bekommt das nächste z. - let zc = 0; - - // Laufender, verketteter 2D-Zeichnungs-Zug (gleiche drawingId + Stil, End-an-Start). - let curPts: RPoint[] | null = null; - let curSrc: LinePrim | null = null; - const flushRun = () => { - if (curPts && curSrc && curPts.length >= 2) { - const col = withOpacity(strokeColorFor(curSrc.cls, curSrc.color), curSrc.cls, curSrc.greyed); - const closed = curPts.length > 2 && samePt(curPts[0], curPts[curPts.length - 1]); - const dash = curSrc.dash ?? null; - if (closed) { - outlines.push({ pts: curPts.slice(0, -1), color: col, widthMm: curSrc.weightMm, dash, z: zc++ }); - } else { - polylines.push({ pts: curPts, color: col, widthMm: curSrc.weightMm, dash, z: zc++ }); - } - } - curPts = null; - curSrc = null; - }; - - for (const p of plan.primitives) { - if (p.kind === "polygon") { - flushRun(); - const pts: RPoint[] = p.pts.map((v) => [v.x, v.y]); - if (pts.length < 2) continue; - - // Füllung - const fillCol = toRgba(p.fill, 1); - if (fillCol && pts.length >= 3) { - fills.push({ pts, color: withFillOpacity(fillCol, p.greyed), z: zc++ }); - } - - // Schraffur: die aufs Polygon geclippten Musterlinien wie im Browser - // (glPlanHatch — identische Geometrie), als Polylinien. "none"/"solid" - // brauchen keine Linien (solid deckt die Füllung farbig ab). Bild-/ - // Verlauf-Schraffuren (kind==="image"/"gradient") kann die render2d- - // Szene nicht tragen (keine Textur/kein echter Verlauf) → FALLBACK: nur - // die neutrale Poché-Füllung (oben), keine Musterlinien. Der Random- - // Untermodus läuft transparent über `buildHatchRuns` (Streu-Striche). - if ( - p.hatch && - p.hatch.kind !== "image" && - p.hatch.kind !== "gradient" && - p.hatch.pattern !== "none" && - p.hatch.pattern !== "solid" - ) { - const hatchCol = withOpacity( - toRgba(p.hatch.color, 1) ?? [0.1, 0.1, 0.1, 1], - undefined, - p.greyed, - ); - // Strichbreite: ein GEWÖHNLICHER Papier-mm-Stift (0.02 mm), wie jede - // andere Linie — nicht mehr an die Musterkachel/Bildschirm-px - // gekoppelt (siehe RPolyline.widthScreen-Kommentar). - const hatchMm = p.hatch.lineWeight > 0 ? p.hatch.lineWeight : 0.13; - const runs = applyDashRuns(buildHatchRuns(p.pts, p.hatch), p.hatch.dash); - // Alle Musterläufe eines Polygons teilen EIN z (überlappen einander nicht). - const hatchZ = zc++; - for (const run of runs) { - if (run.length >= 2) { - polylines.push({ - pts: run.map((v) => [v.x, v.y]), - color: hatchCol, - widthMm: hatchMm, - z: hatchZ, - }); - } - } - } - - // Umriss - const strokeColRaw = toRgba(p.stroke, 1); - if (strokeColRaw && p.strokeWidthMm > 0) { - const strokeCol = withOpacity(strokeColRaw, undefined, p.greyed); - const suppressed = p.noStrokeEdges ?? []; - if (suppressed.length === 0) { - // Ganzer Ring → geschlossener, gehrter Umriss. - outlines.push({ pts, color: strokeCol, widthMm: p.strokeWidthMm, z: zc++ }); - } else { - // Nur die sichtbaren Kanten — sammeln, die Naht ans Ende verschoben. - const runZ = zc++; - for (const run of visibleEdgeRuns(pts, suppressed)) { - collectEdgeRun(run, strokeCol, p.strokeWidthMm, runZ); - } - } - } - } else if (p.kind === "line") { - if (p.zigzag) { - // Zickzack-Linie: als Polylinie tesselliert (render2d kennt keinen - // Zickzack-Primitiv). amplitude/wavelength sind Papier-mm → Modell-Meter - // über dieselbe Kopplung wie Strichmuster (DASH_MM_TO_M). Nicht verketten. - flushRun(); - const amp = p.zigzag.amplitude * DASH_MM_TO_M; - const wav = p.zigzag.wavelength * DASH_MM_TO_M; - const zpts = zigzagPoints(p.a, p.b, amp, wav); - const col = withOpacity(strokeColorFor(p.cls, p.color), p.cls, p.greyed); - if (zpts.length >= 2) { - polylines.push({ - pts: zpts.map((v) => [v.x, v.y]), - color: col, - widthMm: p.weightMm, - z: zc++, - }); - } - } else if (p.motif) { - // Custom-Motiv: entlang der Linie gekachelt (Papier-mm → Modell-Meter via - // DASH_MM_TO_M) → Polylinie. Nicht verketten (wie Zickzack). - flushRun(); - const mpts = motifPoints(p.a, p.b, p.motif, DASH_MM_TO_M); - const col = withOpacity(strokeColorFor(p.cls, p.color), p.cls, p.greyed); - if (mpts.length >= 2) { - polylines.push({ - pts: mpts.map((v) => [v.x, v.y]), - color: col, - widthMm: p.weightMm, - z: zc++, - }); - } - } else if (p.drawingId) { - // Aufeinanderfolgende 2D-Zeichenlinien gleicher drawingId/Stil verketten. - const a: RPoint = [p.a.x, p.a.y]; - const b: RPoint = [p.b.x, p.b.y]; - if (curPts && curSrc && sameLineStyle(curSrc, p) && samePt(curPts[curPts.length - 1], a)) { - curPts.push(b); - } else { - flushRun(); - curPts = [a, b]; - curSrc = p; - } - } else { - // Genuin einzelnes Segment (Türblatt, Referenzlinie, Symbol) → Stumpfkappen ok. - flushRun(); - const col = withOpacity(strokeColorFor(p.cls, p.color), p.cls, p.greyed); - lines.push({ a: [p.a.x, p.a.y], b: [p.b.x, p.b.y], color: col, widthMm: p.weightMm, dash: p.dash ?? null, z: zc++ }); - } - } else if (p.kind === "arc") { - flushRun(); - // Farbe wie im SVG: CSS-Klassen-Regel (z. B. .door-swing → #1a1a1a). - const col = withOpacity(strokeColorFor(p.cls, undefined), p.cls, p.greyed); - // Bogen unvortessellliert an Rust übergeben (`RArc`) — die exakte runde - // Darstellung (analytischer SDF-Shader, `ARC_WGSL`) und ein evtl. Strich- - // muster übernimmt der native Renderer (`compile_scene`) drüben. - arcs.push({ - center: [p.center.x, p.center.y], - from: [p.from.x, p.from.y], - to: [p.to.x, p.to.y], - r: p.r, - color: col, - widthMm: p.weightMm, - dash: p.dash ?? null, - }); - } else if (p.kind === "drawingCircle" || p.kind === "drawingArc") { - // Der native Renderer hat kein Kreis-/Bogen-Primitiv → hier tessellieren - // (der SVG-Pfad zeichnet sie glatt). Kreis = voller Umlauf, Bogen = a0..a1. - flushRun(); - const col = withOpacity(toRgba(p.stroke, 1) ?? [0.1, 0.1, 0.1, 1], undefined, p.greyed); - const TAU = Math.PI * 2; - const a0 = p.kind === "drawingArc" ? p.a0 : 0; - const sweep = p.kind === "drawingArc" ? (((p.a1 - p.a0) % TAU) + TAU) % TAU : TAU; - const N = Math.max(8, Math.ceil(sweep / (Math.PI / 32))); - const pts: RPoint[] = []; - for (let i = 0; i <= N; i++) { - const t = a0 + (sweep * i) / N; - pts.push([p.center.x + p.r * Math.cos(t), p.center.y + p.r * Math.sin(t)]); - } - polylines.push({ pts, color: col, widthMm: p.weightMm, dash: p.dash ?? null, z: zc++ }); - } else if (p.kind === "text") { - // "text": zeilenweise flachen — die ECHTEN Glyphen rastert der Rust- - // Renderer über einen GPU-Glyphen-Atlas (glyphon, dieselbe Font-Familie - // wie im Browser). Layout identisch zum SVG-Pfad in PlanView (case - // "text"): Rich-Text-Zeilen + Live-Zusatzzeilen, Block vertikal um den - // Anker zentriert, Zeilenvorschub 1.3·Basisgröße. - flushRun(); - const defCol = withOpacity(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], undefined, p.greyed); + const ranges = plan.greyedRanges; + const prims = plan.primitives; + for (let i = 0; i < prims.length; i++) { + const p = prims[i]; + 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); // unitPerPt = PT_TO_MM → tspan.fontSize ist direkt die Papier-mm-Größe. const docLines = docToLines(p.doc, { x: 0, @@ -560,14 +216,8 @@ export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAUL // Runs einer Zeile werden zusammengelegt (ein Buffer je Zeile); // Größe/Farbe des größten bzw. ersten Runs gelten für die Zeile. content: line.tspans.map((t) => t.text).join(""), - sizeMm: line.tspans.length - ? Math.max(...line.tspans.map((t) => t.fontSize)) - : baseMm, - color: withOpacity( - toRgba(line.tspans[0]?.fill ?? p.color, 1) ?? defCol, - undefined, - p.greyed, - ), + sizeMm: line.tspans.length ? Math.max(...line.tspans.map((t) => t.fontSize)) : baseMm, + color: greyedColor(toRgba(line.tspans[0]?.fill ?? p.color, 1) ?? defCol, greyed), align: line.align, }); } @@ -592,14 +242,11 @@ export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAUL }); } } else if (p.kind === "drawingText") { - // Modellverankerter Einzeltext (Text-Werkzeug/DXF-Import) — wie "text" - // oben zeilenweise geflacht, aber TOP-DOWN ab `at` (kein vertikal - // zentrierter Block) und `heightM` (Modell-Meter) als Basisgrösse statt - // `basePt` (Papier-Punkt) — der Text bleibt so, wie bisher, massstabsfrei - // an der Modellgeometrie verankert (kein Papier-Punkt-Bezug nötig). - flushRun(); + // Modellverankerter Einzeltext (Text-Werkzeug/DXF-Import): top-down ab `at`, `heightM` + // (Modell-Meter) als Basisgrösse — massstabsfrei an der Modellgeometrie verankert. + const greyed = p.greyed || inGreyedRange(ranges, i); const doc = p.doc ?? docFromText(p.text, p.marks ?? {}); - const defCol = withOpacity(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], undefined, p.greyed); + const defCol = greyedColor(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], greyed); const unitPerPt = PT_TO_MM * mmToM; // pt (Run-Override) -> Papier-mm -> Modell-Meter. const basePt = unitPerPt > 0 ? p.heightM / unitPerPt : 0; const lineHeight = p.heightM * 1.25; @@ -618,48 +265,132 @@ export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAUL if (k > 0) dy += line.lineHeight; const content = line.tspans.map((t) => t.text).join(""); if (!content.trim()) return; - const sizeM = line.tspans.length - ? Math.max(...line.tspans.map((t) => t.fontSize)) - : p.heightM; + const sizeM = line.tspans.length ? Math.max(...line.tspans.map((t) => t.fontSize)) : p.heightM; texts.push({ pos: [p.at.x, p.at.y - dy], content, sizeMm: unitPerPt > 0 ? sizeM / mmToM : sizeM, - color: withOpacity( - toRgba(line.tspans[0]?.fill ?? p.color, 1) ?? defCol, - undefined, - p.greyed, - ), + color: greyedColor(toRgba(line.tspans[0]?.fill ?? p.color, 1) ?? defCol, greyed), align: line.align, }); }); } else if (p.kind === "drawingImage") { - // Eingebettetes Rasterbild — keine Rust-Textur (s. `RImage`); wird vom - // GPU-Backend ignoriert (`useGpuRenderer` schaltet bei Bildern im Plan - // ohnehin auf den SVG-Pfad um), `sceneToPrintSvg.ts` liest es für den PDF-Export. - flushRun(); - images.push({ - min: [p.min.x, p.min.y], - max: [p.max.x, p.max.y], - src: p.src, - opacity: p.opacity, - }); + // Eingebettetes Rasterbild — keine Rust-Textur (s. `RImage`); `sceneToPrintSvg.ts` liest es. + images.push({ min: [p.min.x, p.min.y], max: [p.max.x, p.max.y], src: p.src, opacity: p.opacity }); } } - flushRun(); - - // Gesammelte Umriss-Läufe polygonübergreifend zusammennähen: geschlossene - // Ketten als Ring (Gehrung auch an der Naht), offene als Polylinie. - for (const g of edgeRunGroups.values()) { - for (const chain of stitchRuns(g.runs)) { - if (chain.pts.length < 2) continue; - if (chain.closed) { - outlines.push({ pts: chain.pts, color: g.color, widthMm: g.widthMm, z: g.z }); - } else { - polylines.push({ pts: chain.pts, color: g.color, widthMm: g.widthMm, z: g.z }); - } - } - } - - return { fills, outlines, polylines, arcs, lines, texts, images, bounds: { ...plan.bounds } }; + return { texts, images }; +} + +const ALIGN: Record = { left: 0, center: 1, right: 2 }; +const textEncoder = new TextEncoder(); + +/** Leere render2d-Szene (nur Kopf), falls der Kern nichts liefern kann. */ +function emptySceneBin(): Uint8Array { + const b = new Uint8Array(48); + b.set([0x44, 0x52, 0x32, 0x53], 0); // "DR2S" + new DataView(b.buffer).setUint32(4, 1, true); + return b; +} + +/** + * render2d-Szene (Binärformat v1, `render2d/src/scene_bin.rs`) für `set_scene_bin` bzw. + * `push_native_scene`. Geometrie aus dem Kern, Texte aus {@link planSceneTexts}; + * `plan.greyedRanges` gelten wie materialisiertes `greyed`. + */ +export function planSceneBin(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): Uint8Array { + const { texts } = planSceneTexts(plan, paperScaleN); + const nums = new Float64Array(texts.length * 9); + const strs = texts.map((t) => textEncoder.encode(t.content)); + let nBytes = 0; + for (const s of strs) nBytes += s.length; + const bytes = new Uint8Array(nBytes); + let o = 0; + texts.forEach((t, i) => { + nums.set([t.pos[0], t.pos[1], t.sizeMm, t.color[0], t.color[1], t.color[2], t.color[3], ALIGN[t.align] ?? 0, strs[i].length], i * 9); + bytes.set(strs[i], o); + o += strs[i].length; + }); + const greyed = greyedFlat(plan); + const out = withPlanParts(planParts(plan), (segs) => core().plan_scene_bin(segs, greyed, nums, bytes)); + return out.length ? out : emptySceneBin(); +} + +type SceneGeometry = Pick; + +/** Verlustfreie Kern-Szene (Format s. `plan_scene.rs`) → Szenen-Objekte (Feldreihenfolge wie früher). */ +function decodeSceneF64(f: Float64Array): SceneGeometry { + const out: SceneGeometry = { fills: [], outlines: [], polylines: [], arcs: [], lines: [] }; + if (f.length < 5) return out; + let k = 5; + const pts = (n: number): RPoint[] => { + const r: RPoint[] = new Array(n); + for (let i = 0; i < n; i++, k += 2) r[i] = [f[k], f[k + 1]]; + return r; + }; + const color = (): RRgba => { + const c: RRgba = [f[k], f[k + 1], f[k + 2], f[k + 3]]; + k += 4; + return c; + }; + /** −2 fehlt (undefined) · −1 null · n Werte. */ + const dash = (): number[] | null | undefined => { + const n = f[k++]; + if (n === -2) return undefined; + if (n === -1) return null; + const d = Array.from(f.subarray(k, k + n)); + k += n; + return d; + }; + for (let i = 0; i < f[0]; i++) { + const n = f[k]; + const z = f[k + 1]; + k += 2; + const c = color(); + out.fills.push({ pts: pts(n), color: c, z }); + } + for (let j = 0; j < 2; j++) { + const list = j === 0 ? out.outlines : out.polylines; + for (let i = 0; i < f[1 + j]; i++) { + const n = f[k]; + const z = f[k + 1]; + const widthMm = f[k + 2]; + k += 3; + const d = dash(); + const c = color(); + const p = pts(n); + list.push(d === undefined ? { pts: p, color: c, widthMm, z } : { pts: p, color: c, widthMm, dash: d, z }); + } + } + for (let i = 0; i < f[3]; i++) { + const r = f[k]; + const widthMm = f[k + 1]; + k += 2; + const d = dash() ?? null; + const c = color(); + const [center, from, to] = pts(3); + out.arcs.push({ center, from, to, r, color: c, widthMm, dash: d }); + } + for (let i = 0; i < f[4]; i++) { + const z = f[k]; + const widthMm = f[k + 1]; + k += 2; + const d = dash() ?? null; + const c = color(); + const [a, b] = pts(2); + out.lines.push({ a, b, color: c, widthMm, dash: d, z }); + } + return out; +} + +/** + * Plan → Render-Szene als Objekte (Druck-/SVG-Export, `dossier-cli plan --format json`). + * `paperScaleN` ist der Massstab-Nenner N (1:N) für die Zeilenlage der Texte (s. + * {@link planSceneTexts}). + */ +export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): RScene { + const greyed = greyedFlat(plan); + const geo = decodeSceneF64(withPlanParts(planParts(plan), (segs) => core().plan_scene_f64(segs, greyed))); + const { texts, images } = planSceneTexts(plan, paperScaleN); + return { ...geo, texts, images, bounds: { ...plan.bounds } }; } diff --git a/src/views/plan/nativeSync.ts b/src/views/plan/nativeSync.ts index d8d9a7fe..fdc3d9ae 100644 --- a/src/views/plan/nativeSync.ts +++ b/src/views/plan/nativeSync.ts @@ -1,7 +1,7 @@ // Live-Spiegelung in die nativen wgpu-Fenster (src-tauri/src/native.rs): schiebt // die AKTUELL sichtbare 2D-Szene bzw. die geflachten 3D-Wände debounced per // Tauri-Command an die native Event-Loop. Es wird EXAKT dieselbe Ableitung -// benutzt wie für die Browser-Ansicht (planToRenderScene auf dem sichtbaren +// benutzt wie für die Browser-Ansicht (planSceneBin aus dem Kern auf dem sichtbaren // Plan, projectToWalls3d aufs Projekt) — 1:1-Parität inkl. Türschwenk, // Fenster-Symbolen und Raumstempel-Text (echte Glyphen via GPU-Atlas in Rust). // @@ -10,9 +10,9 @@ // geschluckt (console.debug), damit die App nie daran scheitert. import type { Plan } from "../../core"; -import { materializeGreyed, materializeUnderlay } from "../../core"; +import { materializeUnderlay } from "../../core"; import type { Project } from "../../model/types"; -import { encodeRenderScene, planToRenderScene } from "../../core"; +import { planSceneBin } from "../../core"; import { projectToModel3d, TRUCK_MESH_READY_EVENT } from "../../core"; /** Sammel-Fenster: Modelländerungen werden gebündelt gepusht (nicht je Frame). */ @@ -71,9 +71,9 @@ export function pushNativeScene(plan: Plan): void { clearTimeout(sceneTimer); sceneTimer = setTimeout(async () => { if (!(await isNativeEnabled())) return; - // planToRenderScene liest `greyed` am Primitiv → gedimmte Referenz-Ebenen materialisieren. - // Binärpuffer als Request-Body (Rust: `render2d::scene_bin`), kein JSON. - void invokeNative("push_native_scene", encodeRenderScene(planToRenderScene(materializeGreyed(materializeUnderlay(plan), true)))); + // Szene aus dem Kern (Plan-Puffer, gedimmte Referenz-Ebenen über `greyedRanges`), als + // Binärpuffer im Request-Body (Rust: `render2d::scene_bin`), kein JSON. + void invokeNative("push_native_scene", planSceneBin(materializeUnderlay(plan))); }, DEBOUNCE_MS); } diff --git a/src/views/plan/useWasmPlanRenderer.ts b/src/views/plan/useWasmPlanRenderer.ts index 3d822b07..b6cc13b5 100644 --- a/src/views/plan/useWasmPlanRenderer.ts +++ b/src/views/plan/useWasmPlanRenderer.ts @@ -14,7 +14,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import type { Plan } from "../../core"; -import { encodeRenderScene, planToRenderScene } from "../../core"; +import { planSceneBin } from "../../core"; interface ViewBox { x: number; @@ -115,7 +115,7 @@ export function useWasmPlanRenderer( const r = rendererRef.current; if (!r || !plan) return; try { - r.set_scene_bin(encodeRenderScene(planToRenderScene(plan))); + r.set_scene_bin(planSceneBin(plan)); } catch (e) { console.warn("render2d set_scene_bin fehlgeschlagen:", e); }