diff --git a/TODO.md b/TODO.md index 6222a091..138171fa 100644 --- a/TODO.md +++ b/TODO.md @@ -61,7 +61,12 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern Reihenfolge (Entscheid 27.10.: Risiko klein halten, Verbraucher zuerst): - ◐ **[K3b] Verbraucher auf Binärpuffer.** Plan-Puffer-Format (TS schreibt vorerst, Rust liest); GPU-Kompilierung (`glPlanCompile`/`glPlanHatch`) in Rust, Vertex-Puffer bitgleich zur TS-Ausgabe; - render2d bekommt die Szene binär statt JSON. Danach Mac-Test (Bildfehler-Risiko liegt hier). + render2d bekommt die Szene binär statt JSON — **fertig**: `scene_bin.rs`/`renderSceneBin.ts` + (Format v1: Kopf mit Magie+Version, f64-Punktepool, f32-Farben, String-Tabelle; Fixture + `render2d/tests/fixtures/scene_v1.bin` in beiden Tests), `set_scene_bin` ersetzt `set_scene(json)`, + `push_native_scene` (Nicht-macOS) ebenfalls binär (Linux-Container konnte `src-tauri` nicht bauen: gdk fehlt). + Gross (200k Linien, 20k Füllungen, 1000 Texte): Kodieren 311 → 15 ms, Rust-Lesen 70 → 14 ms, 33,9 → 14,3 MB. + Danach Mac-Test (Bildfehler-Risiko liegt hier). - ○ **[K3a] Plan-Erzeugung in Rust** (Wand-Poché, Öffnungssymbole, Decken, Treppen, Dächer, Räume, 2D-Zeichnung, Kontext, Schnittlinien) direkt in den Plan-Puffer; JS-Objekte nur noch für Export/Overlay. - ○ **[K3c] Schnitt und Ansicht** (`toSection`, `toElevation`, `meshSection`) im selben Puffer-Format. diff --git a/src-tauri/render2d/Cargo.toml b/src-tauri/render2d/Cargo.toml index cd84113a..c4a8e869 100644 --- a/src-tauri/render2d/Cargo.toml +++ b/src-tauri/render2d/Cargo.toml @@ -49,7 +49,6 @@ web = [ "dep:web-sys", "dep:js-sys", "dep:console_error_panic_hook", - "dep:serde_json", ] # Offscreen-Renderpfad (kein Fenster/Surface): Adapter/Device ohne Surface, @@ -61,9 +60,6 @@ headless = ["render", "dep:image"] [dependencies] serde = { version = "1", features = ["derive"] } -# JSON-Szene (dieselbe Ableitung wie der native Push): im Web-Pfad zur Laufzeit -# geparst; optional, nur mit Feature "web". -serde_json = { version = "1", optional = true } # --- GPU (nur mit Feature "render") ------------------------------------------ # Standard-Features von wgpu (wgsl, webgpu, dx12, metal + target-spezifisch diff --git a/src-tauri/render2d/src/lib.rs b/src-tauri/render2d/src/lib.rs index 1b4c6189..2b720f06 100644 --- a/src-tauri/render2d/src/lib.rs +++ b/src-tauri/render2d/src/lib.rs @@ -14,6 +14,7 @@ pub mod demo; pub mod ortho; +pub mod scene_bin; pub mod shaders; pub mod tessellate; pub mod types; diff --git a/src-tauri/render2d/src/scene_bin.rs b/src-tauri/render2d/src/scene_bin.rs new file mode 100644 index 00000000..89c62611 --- /dev/null +++ b/src-tauri/render2d/src/scene_bin.rs @@ -0,0 +1,493 @@ +// Binaerformat der Plan-Szene (Version 1): TS schreibt (`src/plan/renderSceneBin.ts`), +// Rust liest — ersetzt den JSON-Weg zwischen Webview und render2d. Alles little-endian. +// +// Aufbau (alle Abschnitte lueckenlos hintereinander, kein Fuellmaterial): +// Kopf, 48 Byte: magic "DR2S" | version u32 | n_fills n_outlines n_polylines n_arcs +// n_lines n_texts (je u32) | n_pts u32 | n_dash u32 | str_bytes u32 | 0 u32 +// Punkte: n_pts x (x f64, y f64) in Modell-Metern (LV95-gross moeglich). Gemeinsamer +// Pool, der der Reihe nach verbraucht wird: Fuellungen, Umrisse, Polylinien +// (je `n` Punkte), Boegen (je 3: Mitte, von, nach), Linien (je 2), Texte (je 1). +// Strichmuster: n_dash x f32, Pool in Reihenfolge Umrisse, Polylinien, Boegen, Linien. +// Datensaetze: je Kategorie ein Feld aus 4-Byte-Woertern (u32/f32), Reihenfolge wie oben: +// Fuellung [n, z, r g b a] 6 Woerter +// Umriss [n, z, widthMm, dashLen, r g b a] 8 +// Polylinie [n, z, widthMm, dashLen, flags, rgba] 9 (flags Bit0 = widthScreen) +// Bogen [r, widthMm, dashLen, rgba] 7 +// Linie [widthMm, dashLen, z, rgba] 7 +// Text [sizeMm, align(0 l,1 c,2 r), strOff, strLen, rgba] 8 +// Strings: str_bytes UTF-8-Bytes; Texte verweisen mit Byte-Offset und -Laenge hinein. +// `dashLen` 0 = durchgezogen (None). Punkte werden beim Lesen auf f32 gekuerzt (wie bisher +// beim JSON-Weg), Farben und Masse sind f32. Nicht-endliche Zahlen gelten als kaputte Daten. +// Fremde Version, falsche Laenge, Offsets ausserhalb → `Err`, nie Panic. + +use crate::types::{Arc, FillPolygon, Line, Outline, Point, Polyline, Rgba, Scene, Text, TextAlign}; + +/// Magie am Anfang jeder Szene. +pub const MAGIC: [u8; 4] = *b"DR2S"; +/// Aktuelle Formatversion. +pub const VERSION: u32 = 1; +const HEADER: usize = 48; + +/// Liest 4-Byte-Woerter; die Gesamtlaenge ist vorab geprueft, Zugriffe bleiben im Puffer. +struct Reader<'a> { + b: &'a [u8], + pos: usize, +} + +impl Reader<'_> { + fn u32(&mut self) -> u32 { + let v = u32::from_le_bytes([self.b[self.pos], self.b[self.pos + 1], self.b[self.pos + 2], self.b[self.pos + 3]]); + self.pos += 4; + v + } + fn f32(&mut self) -> Result { + let v = f32::from_bits(self.u32()); + if v.is_finite() { + Ok(v) + } else { + Err("nicht-endliche Zahl".into()) + } + } + fn rgba(&mut self) -> Result { + Ok([self.f32()?, self.f32()?, self.f32()?, self.f32()?]) + } +} + +/// Punkt-Pool: liest der Reihe nach f64-Paare. +struct Points<'a> { + b: &'a [u8], + next: usize, + total: usize, +} + +impl Points<'_> { + fn take(&mut self, n: usize) -> Result, String> { + if n > self.total - self.next { + return Err("Punkt-Pool zu klein".into()); + } + let mut v = Vec::with_capacity(n); + for i in self.next..self.next + n { + let o = i * 16; + let x = f64::from_le_bytes(self.b[o..o + 8].try_into().unwrap()); + let y = f64::from_le_bytes(self.b[o + 8..o + 16].try_into().unwrap()); + if !x.is_finite() || !y.is_finite() { + return Err("nicht-endliche Koordinate".into()); + } + v.push([x as f32, y as f32]); + } + self.next += n; + Ok(v) + } +} + +/// Strichmuster-Pool. +struct Dashes { + v: Vec, + next: usize, +} + +impl Dashes { + fn take(&mut self, n: u32) -> Result>, String> { + if n == 0 { + return Ok(None); + } + let n = n as usize; + if n > self.v.len() - self.next { + return Err("Strichmuster-Pool zu klein".into()); + } + let s = self.v[self.next..self.next + n].to_vec(); + self.next += n; + Ok(Some(s)) + } +} + +/// Liest eine Szene (Format siehe Dateikopf). Gibt bei jedem Formatfehler `Err` zurueck. +pub fn decode_scene(bytes: &[u8]) -> Result { + if bytes.len() < HEADER { + return Err("Szene zu kurz".into()); + } + if bytes[0..4] != MAGIC { + return Err("keine Szene (Magie falsch)".into()); + } + let mut r = Reader { b: bytes, pos: 4 }; + let version = r.u32(); + if version != VERSION { + return Err(format!("Szenenversion {version} nicht unterstuetzt (erwartet {VERSION})")); + } + let n_fills = r.u32() as u64; + let n_outlines = r.u32() as u64; + let n_polylines = r.u32() as u64; + let n_arcs = r.u32() as u64; + let n_lines = r.u32() as u64; + let n_texts = r.u32() as u64; + let n_pts = r.u32() as u64; + let n_dash = r.u32() as u64; + let str_bytes = r.u32() as u64; + let _reserved = r.u32(); + + // Gesamtlaenge in u64 vorab pruefen (u32-Zaehler * kleine Faktoren laufen nicht + // ueber), bevor irgendetwas alloziert wird. + let words = n_fills * 6 + n_outlines * 8 + n_polylines * 9 + n_arcs * 7 + n_lines * 7 + n_texts * 8; + let expected = HEADER as u64 + n_pts * 16 + n_dash * 4 + words * 4 + str_bytes; + if expected != bytes.len() as u64 { + return Err(format!("Szenenlaenge {} statt {expected}", bytes.len())); + } + let n_pts = n_pts as usize; + let mut pts = Points { b: &bytes[HEADER..HEADER + n_pts * 16], next: 0, total: n_pts }; + r.pos = HEADER + n_pts * 16; + let mut dashes = Dashes { v: Vec::with_capacity(n_dash as usize), next: 0 }; + for _ in 0..n_dash { + dashes.v.push(r.f32()?); + } + let str_start = bytes.len() - str_bytes as usize; + let strings = std::str::from_utf8(&bytes[str_start..]).map_err(|_| "Strings: kein UTF-8".to_string())?; + + let mut scene = Scene::default(); + for _ in 0..n_fills { + let n = r.u32() as usize; + let z = r.u32(); + let color = r.rgba()?; + scene.fills.push(FillPolygon { pts: pts.take(n)?, color, z }); + } + for _ in 0..n_outlines { + let n = r.u32() as usize; + let z = r.u32(); + let width_mm = r.f32()?; + let dl = r.u32(); + let color = r.rgba()?; + scene.outlines.push(Outline { pts: pts.take(n)?, color, width_mm, dash: dashes.take(dl)?, z }); + } + for _ in 0..n_polylines { + let n = r.u32() as usize; + let z = r.u32(); + let width_mm = r.f32()?; + let dl = r.u32(); + let flags = r.u32(); + let color = r.rgba()?; + scene.polylines.push(Polyline { + pts: pts.take(n)?, + color, + width_mm, + width_screen: flags & 1 != 0, + dash: dashes.take(dl)?, + z, + }); + } + for _ in 0..n_arcs { + let radius = r.f32()?; + let width_mm = r.f32()?; + let dl = r.u32(); + let color = r.rgba()?; + let p = pts.take(3)?; + scene.arcs.push(Arc { center: p[0], from: p[1], to: p[2], r: radius, color, width_mm, dash: dashes.take(dl)? }); + } + for _ in 0..n_lines { + let width_mm = r.f32()?; + let dl = r.u32(); + let z = r.u32(); + let color = r.rgba()?; + let p = pts.take(2)?; + scene.lines.push(Line { a: p[0], b: p[1], color, width_mm, dash: dashes.take(dl)?, z }); + } + for _ in 0..n_texts { + let size_mm = r.f32()?; + let align = match r.u32() { + 0 => TextAlign::Left, + 1 => TextAlign::Center, + 2 => TextAlign::Right, + _ => return Err("Text: Ausrichtung unbekannt".into()), + }; + let off = r.u32() as usize; + let len = r.u32() as usize; + let color = r.rgba()?; + let end = off.checked_add(len).filter(|&e| e <= strings.len()).ok_or("Text ausserhalb der Tabelle")?; + let content = strings.get(off..end).ok_or("Text: Offset mitten im Zeichen")?.to_string(); + scene.texts.push(Text { pos: pts.take(1)?[0], content, size_mm, color, align }); + } + if pts.next != n_pts || dashes.next != dashes.v.len() { + return Err("Pools nicht vollstaendig verbraucht".into()); + } + Ok(scene) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Beispielszene; MUSS mit `sampleScene()` in `src/plan/renderSceneBin.test.ts` + /// uebereinstimmen (gemeinsame Bytes: `tests/fixtures/scene_v1.bin`). + fn sample() -> Scene { + Scene { + fills: vec![ + FillPolygon { pts: vec![[0.0, 0.0], [4.0, 0.0], [4.0, 3.0]], color: [0.5, 0.25, 0.75, 1.0], z: 0 }, + FillPolygon { pts: vec![[1.5, 1.5], [2.5, 1.5], [2.5, 2.5], [1.5, 2.5]], color: [1.0, 1.0, 1.0, 0.5], z: 7 }, + ], + outlines: vec![Outline { + pts: vec![[0.0, 0.0], [4.0, 0.0], [4.0, 3.0]], + color: [0.0, 0.0, 0.0, 1.0], + width_mm: 0.25, + dash: Some(vec![2.0, 1.0]), + z: 1, + }], + polylines: vec![ + Polyline { pts: vec![[0.0, 0.0], [1.0, 1.0]], color: [0.25, 0.25, 0.25, 1.0], width_mm: 0.5, width_screen: false, dash: None, z: 2 }, + Polyline { pts: vec![[5.0, 5.0], [6.0, 5.0], [6.0, 6.0]], color: [0.5, 0.5, 0.5, 1.0], width_mm: 1.0, width_screen: true, dash: Some(vec![1.0]), z: 3 }, + ], + arcs: vec![Arc { center: [1.0, 1.0], from: [2.0, 1.0], to: [1.0, 2.0], r: 1.0, color: [1.0, 0.0, 0.0, 1.0], width_mm: 0.125, dash: None }], + lines: vec![Line { a: [0.0, 0.0], b: [2600000.5, 1200000.25], color: [0.0, 0.5, 0.0, 1.0], width_mm: 0.35, dash: Some(vec![3.0, 1.0, 0.5, 1.0]), z: 4 }], + texts: vec![ + Text { pos: [1.0, 2.0], content: "Küche 12,5 m²".into(), size_mm: 2.5, color: [0.0, 0.0, 0.0, 1.0], align: TextAlign::Center }, + Text { pos: [3.0, 4.0], content: String::new(), size_mm: 2.0, color: [0.0, 0.0, 0.0, 1.0], align: TextAlign::Right }, + Text { pos: [5.0, 6.0], content: "A".into(), size_mm: 1.0, color: [0.0, 0.0, 1.0, 1.0], align: TextAlign::Left }, + ], + } + } + + const FIXTURE: &[u8] = include_bytes!("../tests/fixtures/scene_v1.bin"); + + /// `Scene` hat kein `PartialEq`; der JSON-Vergleich deckt alle Felder ab. + fn assert_same(a: &Scene, b: &Scene) { + assert_eq!(serde_json::to_string(a).unwrap(), serde_json::to_string(b).unwrap()); + } + + #[test] + fn decodes_ts_fixture_to_expected_scene() { + assert_same(&decode_scene(FIXTURE).unwrap(), &sample()); + } + + #[test] + fn empty_scene_decodes() { + let mut b = Vec::new(); + b.extend_from_slice(&MAGIC); + b.extend_from_slice(&VERSION.to_le_bytes()); + b.extend_from_slice(&[0u8; 40]); + assert_same(&decode_scene(&b).unwrap(), &Scene::default()); + } + + #[test] + fn rejects_foreign_version_magic_and_truncation() { + let mut v = FIXTURE.to_vec(); + v[4] = 2; + assert!(decode_scene(&v).unwrap_err().contains("version")); + let mut m = FIXTURE.to_vec(); + m[0] = b'X'; + assert!(decode_scene(&m).is_err()); + assert!(decode_scene(&[]).is_err()); + for cut in 0..FIXTURE.len() { + assert!(decode_scene(&FIXTURE[..cut]).is_err(), "cut {cut}"); + } + let mut longer = FIXTURE.to_vec(); + longer.push(0); + assert!(decode_scene(&longer).is_err()); + } + + #[test] + fn rejects_huge_counts_without_allocating() { + let mut v = FIXTURE[..HEADER].to_vec(); + for i in 0..9 { + let o = 8 + i * 4; + v[o..o + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + } + assert!(decode_scene(&v).is_err()); + } + + #[test] + fn corrupted_bytes_never_panic() { + for i in 0..FIXTURE.len() { + for x in [0x00u8, 0xFF, 0x7F, 0x80] { + let mut v = FIXTURE.to_vec(); + v[i] = x; + let _ = decode_scene(&v); + } + } + let mut seed = 0x1234_5678u32; + for len in [48usize, 49, 100, 400] { + let mut v: Vec = (0..len) + .map(|_| { + seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); + (seed >> 24) as u8 + }) + .collect(); + v[0..4].copy_from_slice(&MAGIC); + v[4..8].copy_from_slice(&VERSION.to_le_bytes()); + let _ = decode_scene(&v); + } + } + + #[test] + fn rejects_nonfinite_and_bad_text() { + let mut v = FIXTURE.to_vec(); + v[HEADER..HEADER + 8].copy_from_slice(&f64::NAN.to_le_bytes()); + assert!(decode_scene(&v).is_err()); + // Der letzte Datensatz-Block vor der String-Tabelle sind die 3 Texte (je 32 Byte). + let str_bytes = u32::from_le_bytes(FIXTURE[40..44].try_into().unwrap()) as usize; + let text0 = FIXTURE.len() - str_bytes - 3 * 32; + let mut a = FIXTURE.to_vec(); + a[text0 + 4..text0 + 8].copy_from_slice(&9u32.to_le_bytes()); + assert!(decode_scene(&a).unwrap_err().contains("Ausrichtung")); + let mut b = FIXTURE.to_vec(); + b[text0 + 12..text0 + 16].copy_from_slice(&1000u32.to_le_bytes()); + assert!(decode_scene(&b).is_err()); + let mut c = FIXTURE.to_vec(); + let last = c.len() - 1; + c[last] = 0xFF; + assert!(decode_scene(&c).is_err()); + } +} + +/// Test-Kodierer (Spiegel von `encodeRenderScene` in TS): fuer Hin-und-zurueck-Tests und +/// die Messung; die App kodiert nur auf der TS-Seite. +#[cfg(test)] +mod roundtrip { + use super::*; + use std::time::Instant; + + fn encode(s: &Scene) -> Vec { + let (mut pts, mut dash, mut rec, mut strs) = (Vec::new(), Vec::new(), Vec::new(), Vec::::new()); + let w = |rec: &mut Vec, v: u32| rec.extend_from_slice(&v.to_le_bytes()); + let wf = |rec: &mut Vec, v: f32| rec.extend_from_slice(&v.to_le_bytes()); + let p = |pts: &mut Vec, q: &Point| { + pts.extend_from_slice(&(q[0] as f64).to_le_bytes()); + pts.extend_from_slice(&(q[1] as f64).to_le_bytes()); + }; + let d = |rec: &mut Vec, dash: &mut Vec, v: &Option>| { + let v = v.as_deref().unwrap_or(&[]); + rec.extend_from_slice(&(v.len() as u32).to_le_bytes()); + for x in v { + dash.extend_from_slice(&x.to_le_bytes()); + } + }; + let c = |rec: &mut Vec, c: &Rgba| c.iter().for_each(|x| rec.extend_from_slice(&x.to_le_bytes())); + for f in &s.fills { + w(&mut rec, f.pts.len() as u32); + w(&mut rec, f.z); + c(&mut rec, &f.color); + f.pts.iter().for_each(|q| p(&mut pts, q)); + } + for o in &s.outlines { + w(&mut rec, o.pts.len() as u32); + w(&mut rec, o.z); + wf(&mut rec, o.width_mm); + d(&mut rec, &mut dash, &o.dash); + c(&mut rec, &o.color); + o.pts.iter().for_each(|q| p(&mut pts, q)); + } + for o in &s.polylines { + w(&mut rec, o.pts.len() as u32); + w(&mut rec, o.z); + wf(&mut rec, o.width_mm); + d(&mut rec, &mut dash, &o.dash); + w(&mut rec, o.width_screen as u32); + c(&mut rec, &o.color); + o.pts.iter().for_each(|q| p(&mut pts, q)); + } + for a in &s.arcs { + wf(&mut rec, a.r); + wf(&mut rec, a.width_mm); + d(&mut rec, &mut dash, &a.dash); + c(&mut rec, &a.color); + [a.center, a.from, a.to].iter().for_each(|q| p(&mut pts, q)); + } + for l in &s.lines { + wf(&mut rec, l.width_mm); + d(&mut rec, &mut dash, &l.dash); + w(&mut rec, l.z); + c(&mut rec, &l.color); + [l.a, l.b].iter().for_each(|q| p(&mut pts, q)); + } + for t in &s.texts { + wf(&mut rec, t.size_mm); + w(&mut rec, t.align as u32); + w(&mut rec, strs.len() as u32); + w(&mut rec, t.content.len() as u32); + c(&mut rec, &t.color); + p(&mut pts, &t.pos); + strs.extend_from_slice(t.content.as_bytes()); + } + let mut out = Vec::new(); + out.extend_from_slice(&MAGIC); + for v in [ + VERSION, + 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, + s.texts.len() as u32, + (pts.len() / 16) as u32, + (dash.len() / 4) as u32, + strs.len() as u32, + 0, + ] { + out.extend_from_slice(&v.to_le_bytes()); + } + out.extend(pts); + out.extend(dash); + out.extend(rec); + out.extend(strs); + out + } + + /// Zufallsszene mit f32-genauen Koordinaten (damit der f64-Umweg verlustfrei ist). + fn big(n_lines: usize, n_fills: usize, n_texts: usize) -> Scene { + let mut seed = 42u32; + let mut rnd = move || { + seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); + ((seed >> 8) as f32) / 16777216.0 + }; + let mut s = Scene::default(); + for i in 0..n_lines { + let (x, y) = (rnd() * 500.0, rnd() * 500.0); + let dash = if i % 10 == 0 { Some(vec![2.0, 1.0]) } else { None }; + s.lines.push(Line { a: [x, y], b: [x + rnd(), y + rnd()], color: [0.1, 0.1, 0.1, 1.0], width_mm: 0.18, dash, z: (i % 50) as u32 }); + } + for i in 0..n_fills { + let (x, y) = (rnd() * 500.0, rnd() * 500.0); + let pts = (0..6).map(|k| [x + k as f32 * rnd(), y + rnd() * k as f32]).collect(); + s.fills.push(FillPolygon { pts, color: [0.8, 0.8, 0.75, 1.0], z: (i % 50) as u32 }); + } + for i in 0..n_texts { + s.texts.push(Text { pos: [rnd() * 500.0, rnd() * 500.0], content: format!("Raum {i} 12,5 m²"), size_mm: 2.0, color: [0.0, 0.0, 0.0, 1.0], align: TextAlign::Center }); + } + s + } + + fn same(a: &Scene, b: &Scene) -> bool { + serde_json::to_string(a).unwrap() == serde_json::to_string(b).unwrap() + } + + #[test] + fn random_scene_roundtrips() { + let s = big(500, 100, 30); + assert!(same(&decode_scene(&encode(&s)).unwrap(), &s)); + } + + /// Messung: `cargo test --release scene_bin::roundtrip::measure -- --ignored --nocapture` + #[test] + #[ignore] + fn measure() { + for (name, s) in [ + ("klein (200 Linien, 50 Fuellungen, 20 Texte)", big(200, 50, 20)), + ("gross (200000 Linien, 20000 Fuellungen, 1000 Texte)", big(200_000, 20_000, 1000)), + ] { + let json = serde_json::to_string(&s).unwrap(); + let bin = encode(&s); + let best = |f: &dyn Fn()| { + (0..5) + .map(|_| { + let t = Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1000.0 + }) + .fold(f64::MAX, f64::min) + }; + let tj = best(&|| { + std::hint::black_box(serde_json::from_str::(&json).unwrap()); + }); + let tb = best(&|| { + std::hint::black_box(decode_scene(&bin).unwrap()); + }); + println!("{name}: JSON {} KB parse {tj:.2} ms | binaer {} KB decode {tb:.2} ms", json.len() / 1024, bin.len() / 1024); + } + } +} diff --git a/src-tauri/render2d/src/web.rs b/src-tauri/render2d/src/web.rs index 8e11b619..4274a36c 100644 --- a/src-tauri/render2d/src/web.rs +++ b/src-tauri/render2d/src/web.rs @@ -6,17 +6,17 @@ // // Ablauf im Frontend (siehe src/plan/useWasmPlanRenderer.ts): // const r = await WebPlanRenderer.new(canvas, undefined); -// r.set_scene(JSON.stringify(planToRenderScene(plan))); +// r.set_scene_bin(encodeRenderScene(planToRenderScene(plan))); // r.set_view_box(x, y, w, h); r.resize(px_w, px_h); r.render(); // -// Szenenformat = dieselbe serde-Struct wie der native Push (render2d::types::Scene), -// als JSON-String hereingereicht. Pan/Zoom aendern nur die ViewBox (kein Re-Tess). +// Szenenformat = Binaerpuffer (`scene_bin.rs`), dekodiert zu render2d::types::Scene. Pan/Zoom aendern nur die ViewBox (kein Re-Tess). use wasm_bindgen::prelude::*; use web_sys::HtmlCanvasElement; use crate::gpu::Renderer; -use crate::types::{Scene, ViewBox}; +use crate::scene_bin::decode_scene; +use crate::types::ViewBox; /// Eingebettete Plan-Schrift (Inter). cosmic-text findet auf wasm KEINE /// Systemfonts — ohne eingebettete Bytes bliebe der Grundriss textlos. Die @@ -76,7 +76,7 @@ impl WebPlanRenderer { // NUR die auflösungsbezogenen Felder (Textur-/Viewport-Grössen) auf die // Adapter-Werte an, `max_buffer_size` bleibt unberührt klein. Für diese // App irrelevant (nur `Backends::BROWSER_WEBGPU`, kein WebGL2-Fallback), - // aber real limitierend für grosse `set_scene`-Tessellierungen (Nutzer- + // aber real limitierend für grosse `set_scene_bin`-Tessellierungen (Nutzer- // Report 2026-10-09, Kataster-Import). Stattdessen direkt die ECHTEN // Adapter-Limits anfordern (s. render3d/src/web.rs, gleicher Fix). let (device, queue) = adapter @@ -133,12 +133,11 @@ impl WebPlanRenderer { }) } - /// Setzt die zu zeichnende Szene aus einem JSON-String (Format = - /// render2d::types::Scene, identisch zum nativen Push). Re-tesselliert + laedt - /// die GPU-Puffer; ruft NICHT selbst `render` — das macht der Aufrufer. - pub fn set_scene(&mut self, json: &str) -> Result<(), JsValue> { - let scene: Scene = serde_json::from_str(json) - .map_err(|e| JsValue::from_str(&format!("Szene parsen: {e}")))?; + /// 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 + /// 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}")))?; self.renderer.upload_scene(&self.device, &scene); Ok(()) } diff --git a/src-tauri/render2d/tests/fixtures/scene_v1.bin b/src-tauri/render2d/tests/fixtures/scene_v1.bin new file mode 100644 index 00000000..3df870ab Binary files /dev/null and b/src-tauri/render2d/tests/fixtures/scene_v1.bin differ diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 2b4bcdec..fcb6040f 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -42,27 +42,31 @@ fn release_project_lock(path: String, state: State) { // die aktuelle 2D-Szene bzw. die 3D-Waende hierher. Auf macOS (nur native2d) // geht das direkt an `native_tauri_window` (Tauri-Fenster als Surface); sonst // (Linux, oder native3d auf jeder Plattform) ueber `native.rs`s -// EventLoopProxy in die winit-Loop. Die Payload kommt als rohes JSON -// (`serde_json::Value`) an und wird erst dort in die render2d-/render3d-Typen -// deserialisiert — so existieren beide Commands unter EINEM cfg, egal welche -// Feature-Kombination gebaut wird. +// EventLoopProxy in die winit-Loop. Die 2D-Szene kommt als roher Binaerpuffer +// (`render2d::scene_bin`, Body des Requests), die 3D-Waende als JSON-Wert — +// beide Commands existieren unter EINEM cfg, egal welche Feature-Kombination +// gebaut wird. #[cfg(any(feature = "native2d", feature = "native3d"))] #[tauri::command] -fn push_native_scene(app: tauri::AppHandle, scene: serde_json::Value) { +fn push_native_scene(app: tauri::AppHandle, request: tauri::ipc::Request<'_>) { #[cfg(all(feature = "native2d", target_os = "macos"))] { // macOS: die 2D-Ansicht laeuft ueber `native_embed` (Chunk-Upload), nicht - // ueber eine JSON-Szene. - let _ = (&app, &scene); + // ueber eine Szene. + let _ = (&app, &request); } #[cfg(all(feature = "native2d", not(target_os = "macos")))] { let _ = &app; - native::push_scene(scene); + if let tauri::ipc::InvokeBody::Raw(bytes) = request.body() { + native::push_scene(bytes); + } else { + eprintln!("push_native_scene: Rohdaten erwartet"); + } } #[cfg(not(feature = "native2d"))] { - let _ = (app, scene); + let _ = (app, request); } } diff --git a/src-tauri/src/native.rs b/src-tauri/src/native.rs index 519af50f..32a8e5ac 100644 --- a/src-tauri/src/native.rs +++ b/src-tauri/src/native.rs @@ -58,12 +58,12 @@ enum UserEvent { /// Solange die Loop noch nicht steht, verpuffen Pushes bewusst still. static PROXY: OnceLock> = OnceLock::new(); -/// Webview-Push der 2D-Szene (JSON = `render2d::types::Scene`). Parse-Fehler +/// Webview-Push der 2D-Szene (Binaerformat `render2d::scene_bin`). Formatfehler /// werden geloggt, ein fehlender Proxy still ignoriert (Loop startet noch). #[cfg(feature = "native2d")] -pub fn push_scene(value: serde_json::Value) { +pub fn push_scene(bytes: &[u8]) { let Some(proxy) = PROXY.get() else { return }; - match serde_json::from_value::(value) { + match render2d::scene_bin::decode_scene(bytes) { Ok(scene) => { let _ = proxy.send_event(UserEvent::Scene2d(scene)); } diff --git a/src/core/extra.ts b/src/core/extra.ts index daf1ba8d..423f9a5e 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -19,3 +19,4 @@ 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"; diff --git a/src/plan/renderSceneBin.test.ts b/src/plan/renderSceneBin.test.ts new file mode 100644 index 00000000..fb0ffcf2 --- /dev/null +++ b/src/plan/renderSceneBin.test.ts @@ -0,0 +1,118 @@ +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 new file mode 100644 index 00000000..e054e2b7 --- /dev/null +++ b/src/plan/renderSceneBin.ts @@ -0,0 +1,157 @@ +// 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/views/plan/nativeSync.ts b/src/views/plan/nativeSync.ts index a3a40888..d8d9a7fe 100644 --- a/src/views/plan/nativeSync.ts +++ b/src/views/plan/nativeSync.ts @@ -12,7 +12,7 @@ import type { Plan } from "../../core"; import { materializeGreyed, materializeUnderlay } from "../../core"; import type { Project } from "../../model/types"; -import { planToRenderScene } from "../../core"; +import { encodeRenderScene, planToRenderScene } from "../../core"; import { projectToModel3d, TRUCK_MESH_READY_EVENT } from "../../core"; /** Sammel-Fenster: Modelländerungen werden gebündelt gepusht (nicht je Frame). */ @@ -48,7 +48,7 @@ function isNativeEnabled(): Promise { } /** Geguardeter Invoke (Muster wie src/compute): nie werfen, Fehler nur debuggen. */ -async function invokeNative(cmd: string, args: Record): Promise { +async function invokeNative(cmd: string, args: Record | Uint8Array): Promise { try { // @ts-ignore optionales Paket const mod = await import(/* @vite-ignore */ "@tauri-apps/api/core").catch(() => null); @@ -72,7 +72,8 @@ export function pushNativeScene(plan: Plan): void { sceneTimer = setTimeout(async () => { if (!(await isNativeEnabled())) return; // planToRenderScene liest `greyed` am Primitiv → gedimmte Referenz-Ebenen materialisieren. - void invokeNative("push_native_scene", { scene: planToRenderScene(materializeGreyed(materializeUnderlay(plan), true)) }); + // Binärpuffer als Request-Body (Rust: `render2d::scene_bin`), kein JSON. + void invokeNative("push_native_scene", encodeRenderScene(planToRenderScene(materializeGreyed(materializeUnderlay(plan), true)))); }, DEBOUNCE_MS); } diff --git a/src/views/plan/useWasmPlanRenderer.ts b/src/views/plan/useWasmPlanRenderer.ts index e967c5c3..3d822b07 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 { planToRenderScene } from "../../core"; +import { encodeRenderScene, planToRenderScene } from "../../core"; interface ViewBox { x: number; @@ -25,7 +25,7 @@ interface ViewBox { /** Minimal-Typ des WASM-Exports (das echte .d.ts entsteht erst mit `build:engine`). */ interface WebPlanRendererLike { - set_scene(json: string): void; + set_scene_bin(bytes: Uint8Array): void; set_view_box(x: number, y: number, w: number, h: number): void; set_paper_scale(n: number): void; set_text_scale(n: number): void; @@ -115,9 +115,9 @@ export function useWasmPlanRenderer( const r = rendererRef.current; if (!r || !plan) return; try { - r.set_scene(JSON.stringify(planToRenderScene(plan))); + r.set_scene_bin(encodeRenderScene(planToRenderScene(plan))); } catch (e) { - console.warn("render2d set_scene fehlgeschlagen:", e); + console.warn("render2d set_scene_bin fehlgeschlagen:", e); } }, []);