From 5c1062ef842263633d5134b8bf31116e05af35b6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 23:25:06 +0000 Subject: [PATCH] [K3b] Plan-Puffer-Format und GPU-Kompilierung in Rust (plan_buf.rs, gpu_compile.rs, hatch.rs) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Plan-Puffer v1 (src/plan/planBuf.ts schreibt, plan_buf.rs liest): Magie + Version, Farb- und Schraffur-Tabellen, ein Eintrag je Primitiv (Text/Bild als Platzhalter), Linienzug-Flag statt Pick-IDs; fremde Versionen ergeben ein leeres Ergebnis. - GPU-Kompilierung (Ear-Clipping, Striche mit runden Kappen/Ecken, Schraffur inkl. Random/Motiv/Dämmung, Strichmuster, Zickzack, Bögen/Kreise) in Rust; glPlanCompile.ts und glPlanHatch.ts sind Fassaden mit unveränderten Signaturen, ein Kern-Aufruf je Chunk. - jsnum.rs: JS-Zahlsemantik (Math.min/max/round, ToInt32), Trigonometrie im Web-Build über Math der JS-Engine — Ausgabe bitgleich zur bisherigen TS-Fassung (temporärer Vergleich über Beispielprojekt, Zufallsprojekte und Zufalls-Primitive, danach gelöscht). --- CLAUDE.md | 2 + TODO.md | 13 + src-tauri/core/src/gpu_compile.rs | 946 ++++++++++++++++++++++++++ src-tauri/core/src/hatch.rs | 786 +++++++++++++++++++++ src-tauri/core/src/hatch_flat.rs | 60 ++ src-tauri/core/src/jsnum.rs | 158 +++++ src-tauri/core/src/lib.rs | 5 + src-tauri/core/src/plan_buf.rs | 666 ++++++++++++++++++ src-tauri/core/src/web/gpu_compile.rs | 16 + src-tauri/core/src/web/hatch.rs | 90 +++ src-tauri/core/src/web/mod.rs | 3 + src-tauri/core/src/web/plan_buf.rs | 10 + src/plan/glPlan/glPlanCompile.ts | 835 ++--------------------- src/plan/glPlan/glPlanHatch.ts | 781 +++------------------ src/plan/planBuf.test.ts | 138 ++++ src/plan/planBuf.ts | 356 ++++++++++ src/views/plan/nativeGl.ts | 4 +- 17 files changed, 3426 insertions(+), 1443 deletions(-) create mode 100644 src-tauri/core/src/gpu_compile.rs create mode 100644 src-tauri/core/src/hatch.rs create mode 100644 src-tauri/core/src/hatch_flat.rs create mode 100644 src-tauri/core/src/jsnum.rs create mode 100644 src-tauri/core/src/plan_buf.rs create mode 100644 src-tauri/core/src/web/gpu_compile.rs create mode 100644 src-tauri/core/src/web/hatch.rs create mode 100644 src-tauri/core/src/web/plan_buf.rs create mode 100644 src/plan/planBuf.test.ts create mode 100644 src/plan/planBuf.ts diff --git a/CLAUDE.md b/CLAUDE.md index f31dc41b..bd5ae229 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -38,6 +38,8 @@ Der ganze Kern wandert nach Rust (`src-tauri/core`, Crate `dossier-core`); die U sie flach an Rust. - **truck** (`src-tauri/trucksolid`, 3D-B-Rep) bleibt eigenes WASM-Modul (Panic-Isolation, `guarded()`). 2D-Flächen-Booleans laufen über den Kern (i_overlay), 3D-Körper über truck — nicht vermischen. +- **Bitgleich zu TS:** JS-Zahlsemantik über `jsnum.rs` (`Math.min/max/round`, ToInt32; `sin/cos/atan2/acos` + im Web-Build über `Math` der JS-Engine) und `jsmath.rs` (`Math.hypot`); Rechenreihenfolge wie in TS. - **Genauigkeit:** i_overlay rechnet auf einem Ganzzahlraster (≈ Ausdehnung/2³⁰); Tests mit 1e-6 m statt 1e-9. ## Architektur (harte Grenze, vom Test `src/core/boundary.test.ts` geprüft) diff --git a/TODO.md b/TODO.md index 6222a091..f8a67eda 100644 --- a/TODO.md +++ b/TODO.md @@ -62,6 +62,19 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern - ◐ **[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). + - ✅ (27.10.) Teil 1: Plan-Puffer-Format v1 (`plan_buf.rs` ↔ `src/plan/planBuf.ts`, Magie+Version, + Farb-/Schraffur-Tabellen, ein Eintrag je Primitiv, Text/Bild als Platzhalter, keine Pick-IDs) und + GPU-Kompilierung in Rust (`gpu_compile.rs`, `hatch.rs`, `jsnum.rs`). `glPlanCompile.ts`/`glPlanHatch.ts` + sind Fassaden (Signaturen gleich, auch `buildHatchRuns`/`applyDashRuns`/`zigzagPoints`/`motifPoints`/ + `triangulate` für toRenderScene/Druck-SVG/DXF/Mesh). Ein Kern-Aufruf je Chunk. Bitgleich (Vertex-/ + Index-Puffer, Batches, Ursprung, Bounds; gepackt + ungepackt): Beispielprojekt (alle Ebenen × + Detailgrade × Modi × LOD, Chunks), 30 Zufallsprojekte (+ Unterlage), 460 Zufalls-Primitivlisten (alle + Schraffurtypen, Random/Motiv/Dämmung, Strichmuster, Zickzack, noStrokeEdges, greyed/opacity, + Landeskoordinaten), Schraffur-Fassade einzeln — 8 GB Puffer verglichen. Trigonometrie läuft im Web-Build + über `Math` der JS-Engine (musl-libm wich ab, auch in der Topologie). Leistung (Node, Min. über + Wiederholungen): Beispiel-EG 1,5 → 0,8 ms, 100k Linien + 3000 Schraffurflächen 3,9 → 1,8 s, nur + Schraffur ~2×, nur Linien 104 → 81 ms (davon Kodieren in TS 7–29 ms). **Offen:** Mac-Test (Metal), + Teil 2 (render2d binär, paralleler Agent). - ○ **[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/core/src/gpu_compile.rs b/src-tauri/core/src/gpu_compile.rs new file mode 100644 index 00000000..91a9fc52 --- /dev/null +++ b/src-tauri/core/src/gpu_compile.rs @@ -0,0 +1,946 @@ +//! GPU-Kompilierung des Grundrisses ([K3b], früher `glPlanCompile.ts`): Plan-Puffer +//! (`plan_buf`) → Vertex-/Index-Puffer und Zeichen-Batches für den nativen Metal-Renderer +//! (`native_embed.rs`/`render2d/chunks.rs`) und den WebGL-Pfad. +//! +//! - Polygone → Ear-Clipping (konkav-fähig) in Bildschirm-Raum (`sx = mx·90`, `sy = −my·90`), +//! relativ zum ersten abgelegten Punkt (lokaler Ursprung gegen f32-Auflösungsverlust). +//! - Striche → butt-endige Segment-Quads mit Normale + Seiten-Flag (bildschirmkonstante Breite +//! im Shader), runde Joins/Kappen als Fächer; Schraffur, Zickzack, Motive, Bögen und Kreise +//! werden vorher zu Linienzügen tesselliert (`hatch`). +//! - Batches: aufeinanderfolgende Indizes gleicher Farbe (+ Breite) werden zusammengefasst. +//! +//! Ausgabe (`compile_flat`) als EIN `u32`-Puffer (eine Kopie über die WASM-Grenze): +//! ```text +//! [M, 0, meta (M × f64 als je zwei u32, little-endian), fillPos (f32-Bits), fillIdx, +//! lineVerts (f32-Bits bzw. gepackt), lineIdx] +//! meta = [originX, originY, minX, minY, maxX, maxY, nFillPos, nFillIdx, nLineVerts, nLineIdx, +//! nFillBatches, nLineBatches, +//! nFillBatches × (start, count, r, g, b, a), +//! nLineBatches × (start, count, r, g, b, a, strokeMm, screenPx)] +//! ``` +//! Linien-Vertices: 6 × f32 (x, y, nx, ny, side, miter=1) oder gepackt 3 Wörter (x, y als +//! f32-Bits, dann snorm8 nx | ny | side | miter=127). +//! Die Rechenreihenfolge folgt der TS-Fassung Operation für Operation: Vertex-Puffer bitgleich. + +use crate::hatch::{self, v2, Hatch, HatchKind, Pattern, Run, V2, DASH_MM_TO_M}; +use crate::jsmath::hypot2; +use crate::jsnum; +use crate::plan_buf::{self, PlanBuf, Prim, Style}; +use std::f64::consts::PI; + +const PX_PER_M: f64 = 90.0; +/// Grauton gedimmter Linien (wie `GREY_RGB` in `toRenderScene.ts`). +pub const GREY_RGB: f64 = 0.549; +const DEFAULT_INK: [f64; 4] = [0.1, 0.1, 0.1, 1.0]; + +type Rgba = [f64; 4]; + +pub struct FillBatch { + pub start: u32, + pub count: u32, + pub color: Rgba, +} + +pub struct LineBatch { + pub start: u32, + pub count: u32, + pub color: Rgba, + pub stroke_mm: f64, + pub screen_px: bool, +} + +/// Ergebnis der Kompilierung (Bildschirm-Raum relativ zu `origin`). +pub struct GpuOut { + pub fill_pos: Vec, + pub fill_idx: Vec, + pub fill_batches: Vec, + /// f32-Bits (ungepackt, 6 je Vertex) bzw. gepackte Wörter (3 je Vertex). + pub line_verts: Vec, + pub line_idx: Vec, + pub line_batches: Vec, + pub origin: (f64, f64), + /// Modell-Bounds (Meter): (minX, minY, maxX, maxY), ±∞ wenn leer. + pub bounds: (f64, f64, f64, f64), +} + +// ── Triangulierung ───────────────────────────────────────────────────────── + +fn signed_area(pts: &[V2]) -> f64 { + let n = pts.len(); + let mut a = 0.0; + let mut j = n - 1; + for i in 0..n { + a += pts[j].x * pts[i].y - pts[i].x * pts[j].y; + j = i; + } + a / 2.0 +} + +#[inline] +fn cross(a: V2, b: V2, c: V2) -> f64 { + (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) +} + +#[inline] +fn point_in_tri(a: V2, b: V2, c: V2, p: V2) -> bool { + let d1 = cross(a, b, p); + let d2 = cross(b, c, p); + let d3 = cross(c, a, p); + let has_neg = d1 < 0.0 || d2 < 0.0 || d3 < 0.0; + let has_pos = d1 > 0.0 || d2 > 0.0 || d3 > 0.0; + !(has_neg && has_pos) +} + +/// Ear-Clipping eines einfachen (lochfreien) Polygons, konvex oder konkav. Indizes auf `pts`; +/// leer bei < 3 Ecken. Enthalten-Test nur gegen reflexe Ecken, Ohren per verketteter Liste. +pub fn triangulate(pts: &[V2]) -> Vec { + let n = pts.len(); + if n < 3 { + return Vec::new(); + } + let mut order: Vec = (0..n).collect(); + if signed_area(pts) < 0.0 { + order.reverse(); + } + let mut next = vec![0usize; n]; + let mut prev = vec![0usize; n]; + for i in 0..n { + next[order[i]] = order[(i + 1) % n]; + prev[order[i]] = order[(i + n - 1) % n]; + } + // Reflex-Menge: Liste + Position (Reihenfolge ist für das Ergebnis belanglos — nur „liegt + // irgendeine reflexe Ecke im Ohr?“ zählt). + let mut reflex: Vec = Vec::new(); + let mut pos = vec![usize::MAX; n]; + let is_reflex = |i: usize, prev: &[usize], next: &[usize]| cross(pts[prev[i]], pts[i], pts[next[i]]) <= 0.0; + fn add(i: usize, reflex: &mut Vec, pos: &mut [usize]) { + if pos[i] == usize::MAX { + pos[i] = reflex.len(); + reflex.push(i); + } + } + fn del(i: usize, reflex: &mut Vec, pos: &mut [usize]) { + let p = pos[i]; + if p != usize::MAX { + let last = *reflex.last().unwrap(); + reflex.swap_remove(p); + if last != i { + pos[last] = p; + } + pos[i] = usize::MAX; + } + } + for &i in &order { + if is_reflex(i, &prev, &next) { + add(i, &mut reflex, &mut pos); + } + } + let mut tris: Vec = Vec::new(); + let mut remaining = n; + let mut i = order[0]; + let mut no_ear_streak = 0usize; + let mut guard: u64 = 0; + let max_guard = (n as u64) * (n as u64) + 16; + while remaining > 3 && { + let g = guard; + guard += 1; + g < max_guard + } { + let a = prev[i]; + let b = i; + let c = next[i]; + let mut is_ear = pos[b] == usize::MAX; + if is_ear { + for &vi in &reflex { + if vi == a || vi == b || vi == c { + continue; + } + if point_in_tri(pts[a], pts[b], pts[c], pts[vi]) { + is_ear = false; + break; + } + } + } + if is_ear { + tris.extend_from_slice(&[a as u32, b as u32, c as u32]); + next[a] = c; + prev[c] = a; + del(b, &mut reflex, &mut pos); + remaining -= 1; + if is_reflex(a, &prev, &next) { + add(a, &mut reflex, &mut pos); + } else { + del(a, &mut reflex, &mut pos); + } + if is_reflex(c, &prev, &next) { + add(c, &mut reflex, &mut pos); + } else { + del(c, &mut reflex, &mut pos); + } + i = a; + no_ear_streak = 0; + } else { + i = c; + no_ear_streak += 1; + if no_ear_streak > remaining { + break; + } + } + } + if remaining == 3 { + tris.extend_from_slice(&[prev[i] as u32, i as u32, next[i] as u32]); + } + tris +} + +// ── Farben ───────────────────────────────────────────────────────────────── + +/// Gedimmt → fester Grauton; Objekt-Deckkraft in den Alphakanal (wie `dim` in TS). +fn dim(color: Rgba, s: &Style) -> Rgba { + let c = if s.greyed { [GREY_RGB, GREY_RGB, GREY_RGB, color[3]] } else { color }; + match s.opacity { + Some(o) if !(o >= 1.0) => [c[0], c[1], c[2], c[3] * jsnum::max(0.0, o)], + _ => c, + } +} + +/// Wie `dim`, aber gedimmte Flächen bleiben weiss. +fn dim_fill(color: Rgba, s: &Style) -> Rgba { + let c = if s.greyed { [1.0, 1.0, 1.0, color[3]] } else { color }; + match s.opacity { + Some(o) if !(o >= 1.0) => [c[0], c[1], c[2], c[3] * jsnum::max(0.0, o)], + _ => c, + } +} + +#[inline] +fn same_rgba(a: &Rgba, b: &Rgba) -> bool { + a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3] +} + +/// `weightMm || 0.18`. +#[inline] +fn weight_or_default(w: f64) -> f64 { + if w == 0.0 || w.is_nan() { + 0.18 + } else { + w + } +} + +/// `Math.round(Math.max(-1, Math.min(1, v)) * 127) & 0xff`. Der Wert liegt in [−127, 127], NaN +/// ergibt 0; das Vorzeichen einer Null spielt nach `& 0xff` keine Rolle. +#[inline] +fn snorm8(v: f64) -> u32 { + if v.is_nan() { + return 0; + } + let x = (if v > 1.0 { + 1.0 + } else if v < -1.0 { + -1.0 + } else { + v + }) * 127.0; + let c = x.ceil(); + let r = if c - 0.5 > x { c - 1.0 } else { c }; + ((r as i32) & 0xff) as u32 +} + +/// Gepacktes Normalen-Wort: snorm8 nx | ny | side | miter (=127). +#[inline] +fn normal_word(nx: f64, ny: f64, side: f64) -> u32 { + snorm8(nx) | (snorm8(ny) << 8) | (snorm8(side) << 16) | (127 << 24) +} + +/// Fächer-Zentrum (1, 0, 0) gepackt. +const CENTER_WORD: u32 = 127 | (127 << 24); + +#[inline] +fn left_normal(d: V2) -> V2 { + v2(-d.y, d.x) +} + +// ── Kompilierer ──────────────────────────────────────────────────────────── + +struct Compiler { + packed: bool, + fill_pos: Vec, + fill_idx: Vec, + fill_batches: Vec, + line_verts: Vec, + line_idx: Vec, + line_batches: Vec, + origin_x: f64, + origin_y: f64, + origin_set: bool, + min_x: f64, + min_y: f64, + max_x: f64, + max_y: f64, + /// Wiederverwendeter Punktpuffer für `stroke_polyline`. + scratch: Vec, + seg_dir: Vec>, + seg_ang: Vec<[Option; 2]>, +} + +impl Compiler { + #[inline] + fn scr(&mut self, p: V2) -> V2 { + let sx = p.x * PX_PER_M; + let sy = -p.y * PX_PER_M; + if !self.origin_set { + self.origin_x = sx; + self.origin_y = sy; + self.origin_set = true; + } + v2(sx - self.origin_x, sy - self.origin_y) + } + + #[inline] + fn track(&mut self, mx: f64, my: f64) { + if mx < self.min_x { + self.min_x = mx; + } + if my < self.min_y { + self.min_y = my; + } + if mx > self.max_x { + self.max_x = mx; + } + if my > self.max_y { + self.max_y = my; + } + } + + fn add_fill_batch(&mut self, count: usize, color: Rgba) { + if let Some(last) = self.fill_batches.last_mut() { + if same_rgba(&last.color, &color) { + last.count += count as u32; + return; + } + } + self.fill_batches.push(FillBatch { start: (self.fill_idx.len() - count) as u32, count: count as u32, color }); + } + + fn add_line_batch(&mut self, count: usize, color: Rgba, stroke_mm: f64, screen_px: bool) { + if let Some(last) = self.line_batches.last_mut() { + if last.stroke_mm == stroke_mm && last.screen_px == screen_px && same_rgba(&last.color, &color) { + last.count += count as u32; + return; + } + } + self.line_batches.push(LineBatch { start: (self.line_idx.len() - count) as u32, count: count as u32, color, stroke_mm, screen_px }); + } + + #[inline] + fn push_vert(&mut self, p: V2, nx: f64, ny: f64, side: f64) -> u32 { + let w = if self.packed { normal_word(nx, ny, side) } else { 0 }; + self.push_vert_w(p, w, nx, ny, side) + } + + /// Wie `push_vert`, mit bereits gepacktem Normalen-Wort `w` (nur im gepackten Layout benutzt). + #[inline] + fn push_vert_w(&mut self, p: V2, w: u32, nx: f64, ny: f64, side: f64) -> u32 { + if self.packed { + self.line_verts.extend_from_slice(&[(p.x as f32).to_bits(), (p.y as f32).to_bits(), w]); + (self.line_verts.len() / 3 - 1) as u32 + } else { + self.line_verts.extend_from_slice(&[ + (p.x as f32).to_bits(), + (p.y as f32).to_bits(), + (nx as f32).to_bits(), + (ny as f32).to_bits(), + (side as f32).to_bits(), + 1.0f32.to_bits(), + ]); + (self.line_verts.len() / 6 - 1) as u32 + } + } + + /// Kreisbogen-Fächer um `p` (Radius = halbe Strichbreite im Shader). + fn add_fan_arc(&mut self, p: V2, a_from: f64, a_to: f64, stroke_mm: f64) { + let delta = a_to - a_from; + let step_angle = if stroke_mm <= 0.35 { PI / 3.0 } else { PI / 10.0 }; + let steps = jsnum::max(1.0, (delta.abs() / step_angle).ceil()); + let i_center = self.push_vert_w(p, CENTER_WORD, 1.0, 0.0, 0.0); + let mut prev = self.push_vert(p, jsnum::cos(a_from), jsnum::sin(a_from), 1.0); + let mut s = 1.0; + while s <= steps { + let t = a_from + (delta * s) / steps; + let cur = self.push_vert(p, jsnum::cos(t), jsnum::sin(t), 1.0); + self.line_idx.extend_from_slice(&[i_center, prev, cur]); + prev = cur; + s += 1.0; + } + } + + /// Zusammenhängender Linienzug (Modell-Meter) mit runden Kappen/Ecken. + fn stroke_polyline(&mut self, pts_m: &[V2], closed: bool, color: Rgba, stroke_mm: f64, screen_px: bool) { + let mut s_pts = std::mem::take(&mut self.scratch); + s_pts.clear(); + for &p in pts_m { + let s = self.scr(p); + if let Some(l) = s_pts.last() { + if (l.x - s.x).abs() < 1e-6 && (l.y - s.y).abs() < 1e-6 { + continue; + } + } + s_pts.push(s); + self.track(p.x, p.y); + } + if closed && s_pts.len() > 1 { + let f = s_pts[0]; + let l = s_pts[s_pts.len() - 1]; + if (f.x - l.x).abs() < 1e-6 && (f.y - l.y).abs() < 1e-6 { + s_pts.pop(); + } + } + let k = s_pts.len(); + if k < 2 { + self.scratch = s_pts; + return; + } + let start_idx_len = self.line_idx.len(); + let segs = if closed { k } else { k - 1 }; + let mut seg_dir = std::mem::take(&mut self.seg_dir); + seg_dir.clear(); + for i in 0..segs { + let from = s_pts[i]; + let to = s_pts[(i + 1) % k]; + let dx = to.x - from.x; + let dy = to.y - from.y; + let len = hypot2(dx, dy); + seg_dir.push(if len < 1e-9 { None } else { Some(v2(dx / len, dy / len)) }); + } + for i in 0..segs { + let Some(d) = seg_dir[i] else { continue }; + let n = left_normal(d); + let a = s_pts[i]; + let b = s_pts[(i + 1) % k]; + let (wp, wm) = if self.packed { (normal_word(n.x, n.y, 1.0), normal_word(n.x, n.y, -1.0)) } else { (0, 0) }; + let i0 = self.push_vert_w(a, wp, n.x, n.y, 1.0); + let i1 = self.push_vert_w(a, wm, n.x, n.y, -1.0); + let i2 = self.push_vert_w(b, wp, n.x, n.y, 1.0); + let i3 = self.push_vert_w(b, wm, n.x, n.y, -1.0); + self.line_idx.extend_from_slice(&[i0, i1, i2, i1, i3, i2]); + } + // Winkel der (ggf. gespiegelten) Segment-Normalen: jede Normale dient zwei Ecken bzw. + // einer Ecke und einer Kappe — `atan2` nur einmal je Segment und Richtung (gleiche + // Eingabe, also derselbe Wert). + let mut seg_ang = std::mem::take(&mut self.seg_ang); + seg_ang.clear(); + seg_ang.resize(segs, [None, None]); + let mut ang = |seg: usize, sign: f64| -> f64 { + let slot = if sign > 0.0 { 0 } else { 1 }; + if let Some(a) = seg_ang[seg][slot] { + return a; + } + let n = left_normal(seg_dir[seg].unwrap_or(v2(0.0, 0.0))); + let a = jsnum::atan2(sign * n.y, sign * n.x); + seg_ang[seg][slot] = Some(a); + a + }; + for v in 0..k { + let has_in = closed || v > 0; + let has_out = closed || v < k - 1; + let i_in = (v + segs - 1) % segs; + let i_out = v % segs; + let d_in = if has_in { seg_dir[i_in] } else { None }; + let d_out = if has_out { seg_dir[i_out] } else { None }; + let p = s_pts[v]; + match (d_in, d_out) { + (Some(d1), Some(d2)) => { + // Runder Übergang nur auf der äusseren Seite der Ecke. + let turn = d1.x * d2.y - d1.y * d2.x; + let dot = d1.x * d2.x + d1.y * d2.y; + if turn.abs() < 1e-6 && dot > 0.0 { + continue; + } + if dot < -0.9999 { + // ~180°-Umkehr: voller Kreis. + let a0 = ang(i_in, 1.0); + self.add_fan_arc(p, a0, a0 + 2.0 * PI, stroke_mm); + continue; + } + let outer = if turn > 0.0 { -1.0 } else { 1.0 }; + let a1 = ang(i_in, outer); + let a2 = ang(i_out, outer); + let mut delta = a2 - a1; + while delta <= -PI { + delta += 2.0 * PI; + } + while delta > PI { + delta -= 2.0 * PI; + } + if delta.abs() < 1e-4 { + continue; + } + self.add_fan_arc(p, a1, a1 + delta, stroke_mm); + } + // Runde Kappen an offenen Enden (Start bulgt rückwärts, Ende vorwärts). + (None, Some(_)) => { + let a0 = ang(i_out, 1.0); + self.add_fan_arc(p, a0, a0 + PI, stroke_mm); + } + (Some(_), None) => { + let a0 = ang(i_in, 1.0); + self.add_fan_arc(p, a0, a0 + -PI, stroke_mm); + } + (None, None) => {} + } + } + let count = self.line_idx.len() - start_idx_len; + self.add_line_batch(count, color, stroke_mm, screen_px); + self.scratch = s_pts; + self.seg_dir = seg_dir; + self.seg_ang = seg_ang; + } + + /// Polygon-Umriss ohne die Kanten in `no_stroke` (offene Züge, gerade Enden an Lücken). + fn stroke_polygon_outline(&mut self, pts: &[V2], color: Rgba, stroke_mm: f64, no_stroke: &[f64]) { + let n = pts.len(); + if no_stroke.is_empty() || n < 2 { + self.stroke_polyline(pts, true, color, stroke_mm, false); + return; + } + let nf = n as f64; + // Menge wie `new Set(noStroke.map(i => ((i % n) + n) % n))` (SameValueZero). + let mut keys: Vec = no_stroke + .iter() + .map(|&i| { + let k = ((i % nf) + nf) % nf; + // −0/+0 und alle NaN sind je derselbe Schlüssel. + if k.is_nan() { + f64::NAN + } else if k == 0.0 { + 0.0 + } else { + k + } + }) + .collect(); + let mut skip = vec![false; n]; + for &kk in &keys { + if kk >= 0.0 && kk < nf && kk.fract() == 0.0 { + skip[kk as usize] = true; + } + } + keys.sort_by(|a, b| a.total_cmp(b)); + keys.dedup_by(|a, b| a.to_bits() == b.to_bits()); + if keys.len() >= n { + return; + } + let visible = |i: usize| !skip[i % n]; + let mut run: Vec = Vec::new(); + for s in 0..n { + if !visible(s) || visible(s + n - 1) { + continue; + } + run.clear(); + run.push(pts[s]); + let mut j = s; + while visible(j) { + run.push(pts[(j + 1) % n]); + j += 1; + if j - s >= n { + break; + } + } + self.stroke_polyline(&run, false, color, stroke_mm, false); + } + } + + fn push_fill(&mut self, pts: &[V2], tris: &[u32], color: Rgba) { + let base = (self.fill_pos.len() / 2) as u32; + for &pt in pts { + let s = self.scr(pt); + self.fill_pos.push(s.x as f32); + self.fill_pos.push(s.y as f32); + self.track(pt.x, pt.y); + } + for &t in tris { + self.fill_idx.push(base + t); + } + self.add_fill_batch(tris.len(), color); + } +} + +/// Segmentzahl eines Bogens: Sagitta < ~0.5 px über `px_per_meter`, sonst fester Rückfall. +fn arc_segments(r: f64, sweep_abs: f64, px_per_meter: f64, min_fallback: f64) -> f64 { + if px_per_meter > 0.0 { + let r_px = r * px_per_meter; + let theta = if r_px > 0.5 { 2.0 * jsnum::acos(1.0 - 0.5 / r_px) } else { PI }; + jsnum::min(2048.0, jsnum::max(8.0, (sweep_abs / theta).ceil())) + } else { + jsnum::max(min_fallback, ((sweep_abs / (PI / 2.0)) * 16.0).ceil()) + } +} + +fn color_or_ink(plan: &PlanBuf, idx: i32) -> Rgba { + plan.color(idx).unwrap_or(DEFAULT_INK) +} + +/// Hatch zeichnet Musterlinien (nicht Bild/Verlauf, nicht none/solid)? +fn hatch_draws_lines(h: &Hatch) -> bool { + h.kind != HatchKind::Image && h.kind != HatchKind::Gradient && h.pattern != Pattern::None && h.pattern != Pattern::Solid +} + +/// Kompiliert die Primitive eines Plan-Puffers. `px_per_meter` steuert nur die Bogen- +/// Tessellierung (0 = zoomunabhängig). `packed` = kompakte Linien-Vertices (nativer Renderer). +pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool) -> GpuOut { + let mut c = Compiler { + packed, + fill_pos: Vec::new(), + fill_idx: Vec::new(), + fill_batches: Vec::new(), + line_verts: Vec::new(), + line_idx: Vec::new(), + line_batches: Vec::new(), + origin_x: 0.0, + origin_y: 0.0, + origin_set: false, + min_x: f64::INFINITY, + min_y: f64::INFINITY, + max_x: f64::NEG_INFINITY, + max_y: f64::NEG_INFINITY, + scratch: Vec::new(), + seg_dir: Vec::new(), + seg_ang: Vec::new(), + }; + let prims = &plan.prims; + let plain_line = |p: &Prim| matches!(p, Prim::Line { zigzag: None, motif: None, .. }); + + // Zusammenhängende, gleich gestylte Einzel-Linien eines Elements als EIN Zug (zwei echte + // Kappen statt 2N). Läuft VOR allen anderen Primitiven, wie in der TS-Fassung. + let mut merged = vec![false; prims.len()]; + let mut pts: Vec = Vec::new(); + let mut i = 0; + while i < prims.len() { + let Prim::Line { style, color, weight_mm, a, b, zigzag: None, motif: None, .. } = &prims[i] else { + i += 1; + continue; + }; + pts.clear(); + pts.push(*a); + pts.push(*b); + let mut j = i + 1; + while j < prims.len() { + match &prims[j] { + Prim::Line { chain: true, a: aj, b: bj, .. } if plain_line(&prims[j]) => { + let last = pts[pts.len() - 1]; + if aj.x != last.x || aj.y != last.y { + break; + } + pts.push(*bj); + j += 1; + } + _ => break, + } + } + if j - i > 1 { + let col = dim(color_or_ink(plan, *color), style); + c.stroke_polyline(&pts, false, col, weight_or_default(*weight_mm), false); + for m in merged.iter_mut().take(j).skip(i) { + *m = true; + } + } + i = j; + } + + for (idx, prim) in prims.iter().enumerate() { + if merged[idx] { + continue; + } + match prim { + Prim::Placeholder => {} + Prim::Polygon { style, fill, stroke, stroke_width_mm, hatch, pts, no_stroke_edges } => { + if let Some(fc) = plan.color(*fill) { + let tris = triangulate(pts); + if !tris.is_empty() { + c.push_fill(pts, &tris, dim_fill(fc, style)); + } + } + if let Some(h) = (*hatch >= 0).then(|| plan.hatches.get(*hatch as usize)).flatten() { + if hatch_draws_lines(&h.hatch) { + let hatch_color = dim(color_or_ink(plan, h.color), style); + let hatch_mm = if h.hatch.line_weight > 0.0 { h.hatch.line_weight } else { 0.13 }; + let runs: Vec = hatch::apply_dash_runs(hatch::build_hatch_runs(pts, &h.hatch), &h.hatch.dash); + for run in &runs { + c.stroke_polyline(run, false, hatch_color, hatch_mm, false); + } + } + } + if let Some(sc) = plan.color(*stroke) { + if *stroke_width_mm > 0.0 && pts.len() >= 2 { + c.stroke_polygon_outline(pts, dim(sc, style), *stroke_width_mm, no_stroke_edges); + } + } + } + Prim::Line { style, color, weight_mm, a, b, zigzag, motif, .. } => { + let col = dim(color_or_ink(plan, *color), style); + let w = weight_or_default(*weight_mm); + if let Some((amp, wav)) = zigzag { + let zpts = hatch::zigzag_points(*a, *b, amp * DASH_MM_TO_M, wav * DASH_MM_TO_M).unwrap_or_else(|| vec![*a, *b]); + c.stroke_polyline(&zpts, false, col, w, false); + } else if let Some(m) = motif { + let mpts = hatch::motif_points(*a, *b, m, DASH_MM_TO_M); + c.stroke_polyline(&mpts, false, col, w, false); + } else { + c.stroke_polyline(&[*a, *b], false, col, w, false); + } + } + Prim::Arc { style, color, weight_mm, center, from, to, r, .. } => { + let col = dim(color_or_ink(plan, *color), style); + let stroke_mm = weight_or_default(*weight_mm); + let a0 = jsnum::atan2(from.y - center.y, from.x - center.x); + let a1 = jsnum::atan2(to.y - center.y, to.x - center.x); + let mut d = a1 - a0; + while d <= -PI { + d += 2.0 * PI; + } + while d > PI { + d -= 2.0 * PI; + } + let segs = arc_segments(*r, d.abs(), px_per_meter, 4.0); + let mut arc_pts = vec![*from]; + let mut k = 1.0; + while k <= segs { + let t = a0 + (d * k) / segs; + arc_pts.push(v2(center.x + r * jsnum::cos(t), center.y + r * jsnum::sin(t))); + k += 1.0; + } + c.stroke_polyline(&arc_pts, false, col, stroke_mm, false); + } + Prim::Circle { style, fill, stroke, weight_mm, center, r, .. } => { + draw_circle_like(&mut c, plan, style, Some(*fill), *stroke, *weight_mm, *center, *r, None, px_per_meter); + } + Prim::DrawingArc { style, stroke, weight_mm, center, r, a0, a1, .. } => { + draw_circle_like(&mut c, plan, style, None, *stroke, *weight_mm, *center, *r, Some((*a0, *a1)), px_per_meter); + } + } + } + + GpuOut { + fill_pos: c.fill_pos, + fill_idx: c.fill_idx, + fill_batches: c.fill_batches, + line_verts: c.line_verts, + line_idx: c.line_idx, + line_batches: c.line_batches, + origin: (c.origin_x, c.origin_y), + bounds: (c.min_x, c.min_y, c.max_x, c.max_y), + } +} + +/// 2D-Kreis (`fill` gesetzt, geschlossen) bzw. 2D-Bogen (`arc` = (a0, a1), CCW, offen). +#[allow(clippy::too_many_arguments)] +fn draw_circle_like( + c: &mut Compiler, + plan: &PlanBuf, + style: &Style, + fill: Option, + stroke: i32, + weight_mm: f64, + center: V2, + r: f64, + arc: Option<(f64, f64)>, + px_per_meter: f64, +) { + let stroke_col = dim(color_or_ink(plan, stroke), style); + let stroke_mm = weight_or_default(weight_mm); + const TAU: f64 = PI * 2.0; + let (a0, sweep) = match arc { + Some((a0, a1)) => { + let s = ((a1 - a0) % TAU + TAU) % TAU; + (a0, if s == 0.0 || s.is_nan() { TAU } else { s }) + } + None => (0.0, TAU), + }; + let segs = arc_segments(r, sweep, px_per_meter, 8.0); + let mut pts = Vec::new(); + let mut i = 0.0; + while i <= segs { + let t = a0 + (sweep * i) / segs; + pts.push(v2(center.x + r * jsnum::cos(t), center.y + r * jsnum::sin(t))); + i += 1.0; + } + if let Some(fi) = fill { + if let Some(fc) = plan.color(fi) { + // Ring ohne den doppelten Schlusspunkt (`pts.slice(0, segs)`). + let n = if segs >= 0.0 { (segs as usize).min(pts.len()) } else { 0 }; + let ring = &pts[..n]; + let tris = triangulate(ring); + if !tris.is_empty() { + c.push_fill(ring, &tris, dim_fill(fc, style)); + } + } + } + c.stroke_polyline(&pts, fill.is_some(), stroke_col, stroke_mm, false); +} + +/// Flache Ausgabe (s. Modulkopf); leer bei unlesbarem Plan-Puffer. +pub fn compile_flat(buf: &[f64], px_per_meter: f64, packed: bool) -> Vec { + let Some(plan) = plan_buf::decode(buf) else { return Vec::new() }; + let o = compile(&plan, px_per_meter, packed); + let mut meta: Vec = vec![ + o.origin.0, + o.origin.1, + o.bounds.0, + o.bounds.1, + o.bounds.2, + o.bounds.3, + o.fill_pos.len() as f64, + o.fill_idx.len() as f64, + o.line_verts.len() as f64, + o.line_idx.len() as f64, + o.fill_batches.len() as f64, + o.line_batches.len() as f64, + ]; + for b in &o.fill_batches { + meta.extend_from_slice(&[b.start as f64, b.count as f64, b.color[0], b.color[1], b.color[2], b.color[3]]); + } + for b in &o.line_batches { + meta.extend_from_slice(&[ + b.start as f64, + b.count as f64, + b.color[0], + b.color[1], + b.color[2], + b.color[3], + b.stroke_mm, + if b.screen_px { 1.0 } else { 0.0 }, + ]); + } + let mut out = Vec::with_capacity(2 + meta.len() * 2 + o.fill_pos.len() + o.fill_idx.len() + o.line_verts.len() + o.line_idx.len()); + out.push(meta.len() as u32); + out.push(0); + for m in &meta { + let bits = m.to_bits(); + out.push(bits as u32); + out.push((bits >> 32) as u32); + } + out.extend(o.fill_pos.iter().map(|v| v.to_bits())); + out.extend_from_slice(&o.fill_idx); + out.extend_from_slice(&o.line_verts); + out.extend_from_slice(&o.line_idx); + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::plan_buf::HatchEntry; + + fn st() -> Style { + Style { greyed: false, opacity: None } + } + + fn line(ax: f64, bx: f64, chain: bool) -> Prim { + Prim::Line { + style: st(), + color: 0, + weight_mm: 0.18, + a: v2(ax, 0.0), + b: v2(bx, 0.0), + dash: vec![], + chain, + zigzag: None, + motif: None, + } + } + + fn plan(prims: Vec) -> PlanBuf { + PlanBuf { colors: vec![[0.0, 0.0, 0.0, 1.0], [0.5, 0.5, 0.5, 1.0]], hatches: vec![], prims } + } + + fn line_idx_count(p: &PlanBuf) -> u32 { + compile(p, 90.0, false).line_batches.iter().map(|b| b.count).sum() + } + + #[test] + fn triangulierung_konvex_konkav() { + let sq = [v2(0.0, 0.0), v2(1.0, 0.0), v2(1.0, 1.0), v2(0.0, 1.0)]; + assert_eq!(triangulate(&sq).len(), 6); + let l = [v2(0.0, 0.0), v2(2.0, 0.0), v2(2.0, 1.0), v2(1.0, 1.0), v2(1.0, 2.0), v2(0.0, 2.0)]; + let t = triangulate(&l); + assert_eq!(t.len(), 12); + let area: f64 = t.chunks(3).map(|c| cross(l[c[0] as usize], l[c[1] as usize], l[c[2] as usize]).abs() / 2.0).sum(); + assert!((area - 3.0).abs() < 1e-12); + let mut cw = l; + cw.reverse(); + assert_eq!(triangulate(&cw).len(), 12); + assert!(triangulate(&sq[..2]).is_empty()); + } + + #[test] + fn linienzug_wird_zusammengefasst() { + let single = line_idx_count(&plan(vec![line(0.0, 1.0, false)])); + let merged = line_idx_count(&plan(vec![line(0.0, 1.0, false), line(1.0, 2.0, true), line(2.0, 3.0, true)])); + assert_eq!(merged, single + 2 * 6); + let apart = line_idx_count(&plan(vec![line(0.0, 1.0, false), line(1.0, 2.0, false)])); + assert_eq!(apart, 2 * single); + } + + #[test] + fn polygon_mit_fuellung_schraffur_umriss() { + let mut p = plan(vec![Prim::Polygon { + style: Style { greyed: true, opacity: Some(0.5) }, + fill: 1, + stroke: 0, + stroke_width_mm: 0.5, + hatch: 0, + pts: vec![v2(0.0, 0.0), v2(1.0, 0.0), v2(1.0, 1.0), v2(0.0, 1.0)], + no_stroke_edges: vec![0.0], + }]); + p.hatches.push(HatchEntry { + hatch: Hatch { + pattern: Pattern::Diagonal, + kind: HatchKind::Vector, + random: false, + scale: 1.0, + angle: 45.0, + line_weight: 0.0, + origin: None, + seed: None, + density: None, + length_min: None, + length_max: None, + dash: vec![], + motif: None, + }, + color: -1, + }); + let o = compile(&p, 90.0, true); + assert_eq!(o.fill_idx.len(), 6); + assert_eq!(o.fill_batches[0].color, [1.0, 1.0, 1.0, 0.5]); + // Schraffur (0.13 mm, grau) und Umriss (0.5 mm) als eigene Batches. + assert_eq!(o.line_batches.len(), 2); + assert_eq!(o.line_batches[0].color, [GREY_RGB, GREY_RGB, GREY_RGB, 0.5]); + assert_eq!(o.line_batches[0].stroke_mm, 0.13); + assert_eq!(o.line_batches[1].stroke_mm, 0.5); + assert_eq!(o.line_verts.len() % 3, 0); + assert_eq!(o.origin, (0.0, 0.0)); + } + + #[test] + fn kreis_und_bogen() { + let p = plan(vec![ + Prim::Circle { style: st(), fill: 1, stroke: 0, weight_mm: 0.0, center: v2(1.0, 1.0), r: 1.0, dash: vec![] }, + Prim::DrawingArc { style: st(), stroke: 0, weight_mm: 0.5, center: v2(0.0, 0.0), r: 1.0, a0: 0.0, a1: 0.0, dash: vec![] }, + Prim::Placeholder, + ]); + let o = compile(&p, 0.0, false); + assert!(!o.fill_idx.is_empty()); + assert_eq!(o.line_batches.len(), 2); + assert_eq!(o.bounds, (-1.0, -1.0, 2.0, 2.0)); + } + + #[test] + fn kaputter_puffer_leer() { + assert!(compile_flat(&[1.0, 2.0, 3.0], 90.0, true).is_empty()); + let enc = plan_buf::encode(&plan(vec![line(0.0, f64::NAN, false)])); + let out = compile_flat(&enc, 90.0, true); + assert!(!out.is_empty()); + } +} diff --git a/src-tauri/core/src/hatch.rs b/src-tauri/core/src/hatch.rs new file mode 100644 index 00000000..1a718c99 --- /dev/null +++ b/src-tauri/core/src/hatch.rs @@ -0,0 +1,786 @@ +//! Schraffur- und Linienmuster-Geometrie des Grundrisses ([K3b], früher `glPlanHatch.ts`): +//! Linie/Segment/Polylinie gegen ein (konkaves) Polygon clippen (even-odd, halb-offene Kanten), +//! Geradenscharen (diagonal/kreuz/eigenes Motiv), Dämmungswelle, deterministische Random- +//! Schraffur (mulberry32, modellraum-stabil), Strichmuster (`apply_dash_runs`), Zickzack und +//! Motiv-Kachelung entlang einer Strecke. +//! +//! Alles in Modell-Metern; die Muster bilden die SVG-``-Kacheln 1:1 nach (Bildschirm- +//! Raum `sx = mx·90`, Kachel 8·scale px bzw. 14×10·scale px). Die Rechenreihenfolge folgt der +//! TS-Fassung Operation für Operation (Bitgleichheit, s. `jsnum`). + +use crate::jsmath::hypot2; +use crate::jsnum; +use std::f64::consts::PI; + +/// Punkt in Modell-Metern. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct V2 { + pub x: f64, + pub y: f64, +} + +#[inline] +pub const fn v2(x: f64, y: f64) -> V2 { + V2 { x, y } +} + +/// Zusammenhängender Linienzug (≥ 2 Punkte). +pub type Run = Vec; + +/// Bildschirm-Einheiten je Meter (wie `PlanView.toScreen`). +pub const PX_PER_M: f64 = 90.0; +/// px (Bildschirm-Raum) → Meter. +pub const PX_TO_M: f64 = 1.0 / PX_PER_M; +/// mm-Papier → Modell-Meter des Musterraums (wie SVG-`dashArray`: `dash·(1/0.13)` px). +pub const DASH_MM_TO_M: f64 = (1.0 / 0.13) * PX_TO_M; + +/// Muster einer Schraffur (`HatchPattern`). Unbekannte Muster zeichnen wie `Diagonal`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Pattern { + None = 0, + Solid = 1, + Diagonal = 2, + Crosshatch = 3, + Insulation = 4, + Custom = 5, +} + +impl Pattern { + pub fn from_code(c: f64) -> Pattern { + match c as i64 { + 0 => Pattern::None, + 1 => Pattern::Solid, + 3 => Pattern::Crosshatch, + 4 => Pattern::Insulation, + 5 => Pattern::Custom, + _ => Pattern::Diagonal, + } + } +} + +/// Schraffur-Typ (`HatchRender.kind`): Vektor, Bild, Verlauf. Bild/Verlauf zeichnet die GPU +/// nicht als Linien (Rückfall auf die Füllung). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum HatchKind { + Vector = 0, + Image = 1, + Gradient = 2, +} + +impl HatchKind { + pub fn from_code(c: f64) -> HatchKind { + match c as i64 { + 1 => HatchKind::Image, + 2 => HatchKind::Gradient, + _ => HatchKind::Vector, + } + } +} + +/// Wiederhol-Motiv: offene Polylinie einer Einheitszelle, `x` entlang, `y` quer. +#[derive(Clone, Debug, PartialEq)] +pub struct Motif { + pub points: Vec, + pub length: f64, +} + +/// Aufgelöste Schraffur (`HatchRender`) ohne Farbe/Bild/Verlauf-Details. +#[derive(Clone, Debug, PartialEq)] +pub struct Hatch { + pub pattern: Pattern, + pub kind: HatchKind, + /// `lines === "random"`. + pub random: bool, + pub scale: f64, + pub angle: f64, + pub line_weight: f64, + pub origin: Option, + pub seed: Option, + pub density: Option, + pub length_min: Option, + pub length_max: Option, + /// Strichmuster der Musterlinien (mm); leer = durchgezogen. + pub dash: Vec, + pub motif: Option, +} + +// ── Clipping ──────────────────────────────────────────────────────────────── + +fn bbox(poly: &[V2]) -> (f64, f64, f64, f64) { + let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for p in poly { + if p.x < min_x { + min_x = p.x; + } + if p.y < min_y { + min_y = p.y; + } + if p.x > max_x { + max_x = p.x; + } + if p.y > max_y { + max_y = p.y; + } + } + (min_x, min_y, max_x, max_y) +} + +/// Unendliche Linie (Aufpunkt `p0`, Einheitsrichtung `dir`) gegen ein einfaches Polygon: +/// innenliegende Segmente (even-odd, halb-offene Kantenkonvention an Ecken). +pub fn clip_line_to_polygon(p0: V2, dir: V2, poly: &[V2]) -> Vec<(V2, V2)> { + let n = poly.len(); + if n < 3 { + return Vec::new(); + } + let nx = -dir.y; + let ny = dir.x; + let side = |p: V2| (p.x - p0.x) * nx + (p.y - p0.y) * ny; + let mut ts: Vec = Vec::new(); + for i in 0..n { + let a = poly[i]; + let b = poly[(i + 1) % n]; + let sa = side(a); + let sb = side(b); + if sa > 0.0 && sb > 0.0 { + continue; + } + if sa < 0.0 && sb < 0.0 { + continue; + } + if sa == 0.0 && sb == 0.0 { + continue; + } + if sa == 0.0 && sb < 0.0 { + continue; + } + if sb == 0.0 && sa < 0.0 { + continue; + } + let denom = sa - sb; + let u = if denom != 0.0 { sa / denom } else { 0.0 }; + let ix = a.x + (b.x - a.x) * u; + let iy = a.y + (b.y - a.y) * u; + ts.push((ix - p0.x) * dir.x + (iy - p0.y) * dir.y); + } + if ts.len() < 2 { + return Vec::new(); + } + // Wie `Array.sort((x, y) => x - y)`: stabil, NaN-Vergleiche zählen als gleich. + ts.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal)); + let mut segs = Vec::new(); + let mut i = 0; + while i + 1 < ts.len() { + let t0 = ts[i]; + let t1 = ts[i + 1]; + i += 2; + if t1 - t0 < 1e-9 { + continue; + } + segs.push((v2(p0.x + dir.x * t0, p0.y + dir.y * t0), v2(p0.x + dir.x * t1, p0.y + dir.y * t1))); + } + segs +} + +/// Endliches Segment [a,b] gegen ein (konkaves) Polygon: innenliegende Teilstücke. +pub fn clip_segment_to_polygon(a: V2, b: V2, poly: &[V2]) -> Vec<(V2, V2)> { + let dx = b.x - a.x; + let dy = b.y - a.y; + let len = hypot2(dx, dy); + if len < 1e-12 { + return Vec::new(); + } + let dir = v2(dx / len, dy / len); + let mut out = Vec::new(); + for (sa, sb) in clip_line_to_polygon(a, dir, poly) { + let t0 = (sa.x - a.x) * dir.x + (sa.y - a.y) * dir.y; + let t1 = (sb.x - a.x) * dir.x + (sb.y - a.y) * dir.y; + let lo = jsnum::max(0.0, jsnum::min(t0, t1)); + let hi = jsnum::min(len, jsnum::max(t0, t1)); + if hi - lo < 1e-9 { + continue; + } + out.push((v2(a.x + dir.x * lo, a.y + dir.y * lo), v2(a.x + dir.x * hi, a.y + dir.y * hi))); + } + out +} + +/// Polylinie gegen ein (konkaves) Polygon als zusammenhängende Innen-Läufe. +pub fn clip_polyline_to_polygon(pts: &[V2], poly: &[V2]) -> Vec { + if pts.len() < 2 || poly.len() < 3 { + return Vec::new(); + } + const EPS: f64 = 1e-9; + let near = |p: V2, q: V2| (p.x - q.x).abs() < EPS && (p.y - q.y).abs() < EPS; + let mut runs: Vec = Vec::new(); + let mut cur: Option = None; + fn close_run(cur: &mut Option, runs: &mut Vec) { + if let Some(c) = cur.take() { + if c.len() >= 2 { + runs.push(c); + } + } + } + for i in 0..pts.len() - 1 { + let a = pts[i]; + let b = pts[i + 1]; + for (sa, sb) in clip_segment_to_polygon(a, b, poly) { + let dx = b.x - a.x; + let dy = b.y - a.y; + let ta = (sa.x - a.x) * dx + (sa.y - a.y) * dy; + let tb = (sb.x - a.x) * dx + (sb.y - a.y) * dy; + let s = if ta <= tb { sa } else { sb }; + let e = if ta <= tb { sb } else { sa }; + match cur.as_mut() { + Some(c) if near(*c.last().unwrap(), s) => c.push(e), + _ => { + close_run(&mut cur, &mut runs); + cur = Some(vec![s, e]); + } + } + } + if let Some(c) = cur.as_ref() { + if !near(*c.last().unwrap(), b) { + close_run(&mut cur, &mut runs); + } + } + } + close_run(&mut cur, &mut runs); + runs +} + +/// Schar paralleler, aufs Polygon geclippter Linien (Richtung `angle_rad`, Abstand `spacing_m`, +/// Phase `offset_m`, Raster-Anker `anchor` = Modellursprung bzw. `hatchOrigin`). +pub fn hatch_line_family(poly: &[V2], angle_rad: f64, spacing_m: f64, offset_m: f64, anchor: V2) -> Vec<(V2, V2)> { + if poly.len() < 3 || spacing_m <= 1e-9 { + return Vec::new(); + } + let (min_x, min_y, max_x, max_y) = bbox(poly); + if !(max_x > min_x) && !(max_y > min_y) { + return Vec::new(); + } + let dir = v2(jsnum::cos(angle_rad), jsnum::sin(angle_rad)); + let nrm = v2(-dir.y, dir.x); + let center = anchor; + let (mut d_min, mut d_max) = (f64::INFINITY, f64::NEG_INFINITY); + for p in poly { + let d = (p.x - center.x) * nrm.x + (p.y - center.y) * nrm.y; + if d < d_min { + d_min = d; + } + if d > d_max { + d_max = d; + } + } + let mut segs = Vec::new(); + let first = ((d_min - offset_m) / spacing_m).floor() - 1.0; + let last = ((d_max - offset_m) / spacing_m).ceil() + 1.0; + // Unendliche Ausdehnung (TS lief hier endlos): nichts zeichnen. + if !(last - first).is_finite() { + return segs; + } + let mut k = first; + while k <= last { + let d = offset_m + k * spacing_m; + let p0 = v2(center.x + nrm.x * d, center.y + nrm.y * d); + segs.extend(clip_line_to_polygon(p0, dir, poly)); + k += 1.0; + } + segs +} + +fn rotate(v: V2, rad: f64) -> V2 { + let c = jsnum::cos(rad); + let s = jsnum::sin(rad); + v2(v.x * c - v.y * s, v.x * s + v.y * c) +} + +/// SVG-Drehung (im Uhrzeigersinn, Grad) → Modellwinkel (Bogenmass, CCW). +fn to_model_angle_rad(screen_deg: f64) -> f64 { + (-screen_deg * PI) / 180.0 +} + +// ── Strichmuster ──────────────────────────────────────────────────────────── + +/// Zerlegt Läufe entlang eines Strichmusters (`dash` in mm-Papier, [an, aus, …]; ungerade +/// Länge wird verdoppelt). Die Phase läuft über Stützpunkte hinweg durch. +pub fn apply_dash_runs(runs: Vec, dash: &[f64]) -> Vec { + if dash.is_empty() { + return runs; + } + let pat: Vec = dash.iter().map(|&d| jsnum::max(0.0, d) * DASH_MM_TO_M).filter(|&d| d > 0.0).collect(); + if pat.is_empty() { + return runs; + } + let cycle: Vec = if pat.len() % 2 == 0 { pat } else { pat.iter().chain(pat.iter()).copied().collect() }; + let mut total = 0.0; + for &d in &cycle { + total += d; + } + if total <= 1e-9 { + return runs; + } + let mut out: Vec = Vec::new(); + for run in &runs { + if run.len() < 2 { + continue; + } + let mut idx = 0usize; + let mut dash_left = cycle[0]; + let mut on = true; + let mut piece: Option = Some(vec![run[0]]); + for i in 0..run.len() - 1 { + let mut a = run[i]; + let b = run[i + 1]; + let mut seg_len = hypot2(b.x - a.x, b.y - a.y); + if seg_len < 1e-12 { + continue; + } + let ux = (b.x - a.x) / seg_len; + let uy = (b.y - a.y) / seg_len; + while seg_len > 1e-9 { + let step = jsnum::min(seg_len, dash_left); + let mid = v2(a.x + ux * step, a.y + uy * step); + if on { + piece.get_or_insert_with(|| vec![a]).push(mid); + } + a = mid; + seg_len -= step; + dash_left -= step; + if dash_left <= 1e-9 { + if on { + if let Some(p) = piece.take() { + if p.len() >= 2 { + out.push(p); + } + } + } + on = !on; + idx += 1; + dash_left = cycle[idx % cycle.len()]; + if on { + piece = Some(vec![a]); + } + } + } + } + if let Some(p) = piece.take() { + if p.len() >= 2 { + out.push(p); + } + } + } + out +} + +// ── Muster ────────────────────────────────────────────────────────────────── + +/// Schraffur eines Polygons als zusammenhängende Läufe (Modell-Meter); Bild/Verlauf liefern +/// hier keine Linien (die Aufrufer filtern sie vorher). +pub fn build_hatch_runs(poly: &[V2], hatch: &Hatch) -> Vec { + if poly.len() < 3 { + return Vec::new(); + } + let pattern = hatch.pattern; + if pattern == Pattern::None || pattern == Pattern::Solid { + return Vec::new(); + } + let scale = if hatch.scale > 1e-6 { hatch.scale } else { 1.0 }; + if hatch.kind == HatchKind::Vector && hatch.random { + return build_random_hatch_runs(poly, hatch, Some(scale)); + } + if pattern == Pattern::Insulation { + return insulation_runs(poly, hatch, scale); + } + let spacing_m = 8.0 * scale * PX_TO_M; + let rot = to_model_angle_rad(hatch.angle); + let dir1 = rotate(v2(0.0, -1.0), rot); + let a1 = jsnum::atan2(dir1.y, dir1.x); + let anchor = hatch.origin.unwrap_or(v2(0.0, 0.0)); + let mut runs: Vec = hatch_line_family(poly, a1, spacing_m, 0.0, anchor) + .into_iter() + .map(|(a, b)| match (&hatch.motif, pattern) { + (Some(m), Pattern::Custom) => motif_points(a, b, m, scale * DASH_MM_TO_M), + _ => vec![a, b], + }) + .collect(); + if pattern == Pattern::Crosshatch { + for (a, b) in hatch_line_family(poly, a1 + PI / 2.0, spacing_m, 0.0, anchor) { + runs.push(vec![a, b]); + } + } + runs +} + +/// Dämmungswelle (Kachel 14×10·scale px, zwei quadratische Béziers je Welle). +fn insulation_runs(poly: &[V2], hatch: &Hatch, scale: f64) -> Vec { + let rot = to_model_angle_rad(hatch.angle); + let wavelength = 14.0 * scale * PX_TO_M; + let row_gap = 10.0 * scale * PX_TO_M; + let u_dir = rotate(v2(1.0, 0.0), rot); + let v_dir = rotate(v2(0.0, 1.0), rot); + let (mut u_min, mut u_max, mut v_min, mut v_max) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY); + for p in poly { + let u = p.x * u_dir.x + p.y * u_dir.y; + let v = p.x * v_dir.x + p.y * v_dir.y; + if u < u_min { + u_min = u; + } + if u > u_max { + u_max = u; + } + if v < v_min { + v_min = v; + } + if v > v_max { + v_max = v; + } + } + if !(u_max > u_min) || !(v_max > v_min) { + return Vec::new(); + } + const STEPS: f64 = 22.0; + let du = wavelength / STEPS; + let to_world = |u: f64, v: f64| v2(u_dir.x * u + v_dir.x * v, u_dir.y * u + v_dir.y * v); + let first_row = (v_min / row_gap - 0.5).floor() - 1.0; + let last_row = (v_max / row_gap - 0.5).ceil() + 1.0; + let u_start = ((u_min - wavelength) / du).floor() * du; + let u_end = u_max + wavelength; + if !(last_row - first_row).is_finite() || !(u_end - u_start).is_finite() { + return Vec::new(); + } + let half = wavelength / 2.0; + let wave_at = |u: f64| -> f64 { + let phase = ((u % wavelength) + wavelength) % wavelength; + let t = (phase % half) / half; + let mag = 12.0 * scale * PX_TO_M * t * (1.0 - t); + if phase < half { + mag + } else { + -mag + } + }; + let mut runs = Vec::new(); + let mut r = first_row; + while r <= last_row { + let v_base = (r + 0.5) * row_gap; + let mut wave_pts = Vec::new(); + let mut u = u_start; + while u <= u_end + 1e-9 { + wave_pts.push(to_world(u, v_base + wave_at(u))); + u += du; + } + runs.extend(clip_polyline_to_polygon(&wave_pts, poly)); + r += 1.0; + } + runs +} + +// ── Random-Schraffur ──────────────────────────────────────────────────────── + +/// mulberry32 (deterministischer 32-bit-PRNG). +struct Mulberry32 { + a: u32, +} + +impl Mulberry32 { + fn next(&mut self) -> f64 { + self.a = self.a.wrapping_add(0x6d2b79f5); + let a = self.a; + let mut t = (a ^ (a >> 15)).wrapping_mul(1 | a); + t = t.wrapping_add((t ^ (t >> 7)).wrapping_mul(61 | t)) ^ t; + ((t ^ (t >> 14)) as f64) / 4294967296.0 + } +} + +/// Faltet Kennwerte (gequantelt ·1000) zu einem 32-bit-Seed (FNV-artig). +fn hash_seed(vals: &[f64]) -> u32 { + let mut h: u32 = 0x811c9dc5; + for &v in vals { + let q = jsnum::to_int32(jsnum::round(v * 1000.0)) as u32; + h ^= q & 0xffff; + h = h.wrapping_mul(0x01000193); + h ^= (q >> 16) & 0xffff; + h = h.wrapping_mul(0x01000193); + } + h +} + +/// Hash einer Modellraum-Zelle (absolute Indizes) plus Seed. +fn hash_cell(ix: f64, iy: f64, seed: f64) -> u32 { + let mut h: u32 = 0x811c9dc5 ^ (jsnum::to_int32(seed) as u32); + h = (h ^ jsnum::to_int32(ix) as u32).wrapping_mul(0x01000193); + h = (h ^ jsnum::to_int32(iy) as u32).wrapping_mul(0x01000193); + h ^= h >> 15; + h = h.wrapping_mul(0x2c1b3c6d); + h ^= h >> 12; + h +} + +/// Streut kurze Striche modellraum-stabil über ein Polygon (eine Zelle je Strich). +pub fn scatter_strokes( + poly: &[V2], + cell: f64, + base_angle_rad: f64, + seed: f64, + stroke_len: f64, + len_min: Option, + len_max: Option, +) -> Vec { + if poly.len() < 3 || cell <= 1e-9 || stroke_len <= 1e-9 { + return Vec::new(); + } + let (min_x, min_y, max_x, max_y) = bbox(poly); + if !(max_x > min_x) || !(max_y > min_y) { + return Vec::new(); + } + let mut eff = cell; + let mut ix0 = (min_x / eff).floor(); + let mut ix1 = (max_x / eff).floor(); + let mut iy0 = (min_y / eff).floor(); + let mut iy1 = (max_y / eff).floor(); + const MAX_CELLS: f64 = 250000.0; + let cells = (ix1 - ix0 + 1.0) * (iy1 - iy0 + 1.0); + if cells > MAX_CELLS { + eff = cell * (cells / MAX_CELLS).sqrt(); + ix0 = (min_x / eff).floor(); + ix1 = (max_x / eff).floor(); + iy0 = (min_y / eff).floor(); + iy1 = (max_y / eff).floor(); + } + if !(ix1 - ix0).is_finite() || !(iy1 - iy0).is_finite() { + return Vec::new(); + } + let range = match (len_min, len_max) { + (Some(lo), Some(hi)) if lo > 1e-9 && hi >= lo => Some((lo, hi)), + _ => None, + }; + let mut runs = Vec::new(); + let mut iy = iy0; + while iy <= iy1 { + let mut ix = ix0; + while ix <= ix1 { + let mut rnd = Mulberry32 { a: hash_cell(ix, iy, seed) }; + let cx = (ix + rnd.next()) * eff; + let cy = (iy + rnd.next()) * eff; + let ang = base_angle_rad + (rnd.next() * 2.0 - 1.0) * PI; + let len = match range { + Some((lo, hi)) => lo + rnd.next() * (hi - lo), + None => stroke_len * (0.6 + 0.8 * rnd.next()), + }; + let half = len * 0.5; + let dx = jsnum::cos(ang) * half; + let dy = jsnum::sin(ang) * half; + let a = v2(cx - dx, cy - dy); + let b = v2(cx + dx, cy + dy); + for (sa, sb) in clip_segment_to_polygon(a, b, poly) { + runs.push(vec![sa, sb]); + } + ix += 1.0; + } + iy += 1.0; + } + runs +} + +/// Random-Vektor-Schraffur (Kies/Splitt), Dichte/Strichlänge an die Kachel (8·scale px) gekoppelt. +pub fn build_random_hatch_runs(poly: &[V2], hatch: &Hatch, scale: Option) -> Vec { + let s = scale.unwrap_or(if hatch.scale > 1e-6 { hatch.scale } else { 1.0 }); + let density = match hatch.density { + Some(d) if d > 1e-6 => d, + _ => 1.0, + }; + let cell = (8.0 * s * PX_TO_M) / density; + let stroke_len = cell * 1.1; + let seed = hash_seed(&[hatch.angle, s, density, hatch.seed.unwrap_or(0.0)]); + let base = to_model_angle_rad(hatch.angle); + let len_min = hatch.length_min.map(|v| v * DASH_MM_TO_M); + let len_max = hatch.length_max.map(|v| v * DASH_MM_TO_M); + scatter_strokes(poly, cell, base, seed as f64, stroke_len, len_min, len_max) +} + +// ── Zickzack / Motiv ──────────────────────────────────────────────────────── + +/// Zickzack (Dreieckswelle [0,+A,0,−A] je Viertel-Wellenlänge) entlang [a,b]. `None` = +/// entartet (Aufrufer nimmt `[a, b]`). +pub fn zigzag_points(a: V2, b: V2, amplitude: f64, wavelength: f64) -> Option> { + let dx = b.x - a.x; + let dy = b.y - a.y; + let l = hypot2(dx, dy); + if l < 1e-12 || wavelength <= 1e-9 || amplitude <= 0.0 { + return None; + } + let ux = dx / l; + let uy = dy / l; + let nx = -uy; + let ny = ux; + let quarter = wavelength / 4.0; + let steps = jsnum::max(1.0, jsnum::round(l / quarter)); + const TRI: [f64; 4] = [0.0, 1.0, 0.0, -1.0]; + let mut pts = Vec::new(); + let mut i = 0.0f64; + while i <= steps { + let t = jsnum::min(l, i * quarter); + let off = amplitude * TRI[(i as u64 % 4) as usize]; + pts.push(v2(a.x + ux * t + nx * off, a.y + uy * t + ny * off)); + i += 1.0; + } + // (TS warf hier bei NaN-Länge; ohne Punkte gilt die Strecke.) + let last = *pts.last()?; + if (last.x - b.x).abs() > 1e-9 || (last.y - b.y).abs() > 1e-9 { + pts.push(v2(b.x, b.y)); + } + Some(pts) +} + +/// Kachelt ein Motiv entlang [a,b] (Punkte und Länge ·`scale`), am Ende exakt bei `L` +/// geclippt. `None` = entartet (Aufrufer nimmt `[a, b]`). +pub fn motif_points(a: V2, b: V2, motif: &Motif, scale: f64) -> Vec { + motif_points_opt(a, b, motif, scale).unwrap_or_else(|| vec![a, b]) +} + +pub fn motif_points_opt(a: V2, b: V2, motif: &Motif, scale: f64) -> Option> { + let dx = b.x - a.x; + let dy = b.y - a.y; + let l = hypot2(dx, dy); + let cell = motif.length * scale; + if l < 1e-12 || cell <= 1e-9 || motif.points.len() < 2 { + return None; + } + let ux = dx / l; + let uy = dy / l; + let nx = -uy; + let ny = ux; + let to_world = |ax: f64, off: f64| v2(a.x + ux * ax + nx * off, a.y + uy * ax + ny * off); + let mut out = Vec::new(); + let reps = (l / cell).ceil() + 1.0; + let mut last: Option<(f64, f64)> = None; + let mut r = 0.0f64; + while r < reps { + let base = r * cell; + for p in &motif.points { + let ax = base + p.x * scale; + let off = p.y * scale; + if let Some((lax, loff)) = last { + if (ax - lax).abs() < 1e-9 && (off - loff).abs() < 1e-9 { + continue; + } + } + if ax > l + 1e-9 { + if let Some((lax, loff)) = last { + if ax > lax + 1e-12 && l - lax > 1e-9 { + let tt = (l - lax) / (ax - lax); + out.push(to_world(l, loff + (off - loff) * tt)); + } + } + return if out.len() >= 2 { Some(out) } else { None }; + } + out.push(to_world(ax, off)); + last = Some((ax, off)); + } + r += 1.0; + } + if out.len() >= 2 { + Some(out) + } else { + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn square() -> Vec { + vec![v2(0.0, 0.0), v2(1.0, 0.0), v2(1.0, 1.0), v2(0.0, 1.0)] + } + + fn hatch(pattern: Pattern) -> Hatch { + Hatch { + pattern, + kind: HatchKind::Vector, + random: false, + scale: 1.0, + angle: 45.0, + line_weight: 0.13, + origin: None, + seed: None, + density: None, + length_min: None, + length_max: None, + dash: Vec::new(), + motif: None, + } + } + + #[test] + fn linie_durch_quadrat() { + let s = clip_line_to_polygon(v2(-1.0, 0.5), v2(1.0, 0.0), &square()); + assert_eq!(s.len(), 1); + assert!((s[0].0.x - 0.0).abs() < 1e-12 && (s[0].1.x - 1.0).abs() < 1e-12); + assert!(clip_line_to_polygon(v2(-1.0, 5.0), v2(1.0, 0.0), &square()).is_empty()); + } + + #[test] + fn konkav_zwei_stuecke() { + // U-Form: Linie bei y=0.75 trifft beide Schenkel. + let u = vec![v2(0.0, 0.0), v2(3.0, 0.0), v2(3.0, 1.0), v2(2.0, 1.0), v2(2.0, 0.5), v2(1.0, 0.5), v2(1.0, 1.0), v2(0.0, 1.0)]; + assert_eq!(clip_line_to_polygon(v2(-1.0, 0.75), v2(1.0, 0.0), &u).len(), 2); + } + + #[test] + fn muster_liefern_linien() { + let sq = square(); + assert!(!build_hatch_runs(&sq, &hatch(Pattern::Diagonal)).is_empty()); + let d = build_hatch_runs(&sq, &hatch(Pattern::Diagonal)).len(); + assert!(build_hatch_runs(&sq, &hatch(Pattern::Crosshatch)).len() > d); + assert!(!build_hatch_runs(&sq, &hatch(Pattern::Insulation)).is_empty()); + assert!(build_hatch_runs(&sq, &hatch(Pattern::Solid)).is_empty()); + assert!(build_hatch_runs(&sq, &hatch(Pattern::None)).is_empty()); + let mut r = hatch(Pattern::Diagonal); + r.random = true; + let a = build_hatch_runs(&sq, &r); + assert!(!a.is_empty()); + assert_eq!(a, build_hatch_runs(&sq, &r)); + r.seed = Some(8.0); + assert_ne!(a, build_hatch_runs(&sq, &r)); + } + + #[test] + fn unendliches_polygon_haengt_nicht() { + let p = vec![v2(0.0, 0.0), v2(f64::INFINITY, 0.0), v2(1.0, 1.0)]; + assert!(build_hatch_runs(&p, &hatch(Pattern::Diagonal)).is_empty()); + assert!(build_hatch_runs(&p, &hatch(Pattern::Insulation)).is_empty()); + } + + #[test] + fn strichmuster_zerlegt() { + let run = vec![v2(0.0, 0.0), v2(1.0, 0.0)]; + let on = 0.5 / DASH_MM_TO_M; // 0.5 m an, 0.5 m aus → genau ein Strich + let out = apply_dash_runs(vec![run.clone()], &[on]); + assert_eq!(out.len(), 1); + assert!((out[0][1].x - 0.5).abs() < 1e-9); + assert_eq!(apply_dash_runs(vec![run.clone()], &[]).len(), 1); + assert_eq!(apply_dash_runs(vec![run], &[0.0, -1.0]).len(), 1); + } + + #[test] + fn zickzack_und_motiv() { + let z = zigzag_points(v2(0.0, 0.0), v2(8.0, 0.0), 1.0, 4.0).unwrap(); + assert_eq!(z.len(), 9); + assert_eq!(z[1], v2(1.0, 1.0)); + assert!(zigzag_points(v2(0.0, 0.0), v2(1.0, 0.0), 0.0, 4.0).is_none()); + let m = Motif { points: vec![v2(0.0, 0.0), v2(2.0, 1.0), v2(4.0, 0.0)], length: 4.0 }; + let p = motif_points(v2(0.0, 0.0), v2(12.0, 0.0), &m, 1.0); + assert_eq!(p.first(), Some(&v2(0.0, 0.0))); + assert_eq!(p.last(), Some(&v2(12.0, 0.0))); + let short = Motif { points: vec![v2(0.0, 0.0)], length: 4.0 }; + assert_eq!(motif_points(v2(0.0, 0.0), v2(4.0, 0.0), &short, 1.0), vec![v2(0.0, 0.0), v2(4.0, 0.0)]); + } + + #[test] + fn mulberry_wie_js() { + // Referenz aus JS: mulberry32(1)() = 0.6270739405881613 + let mut r = Mulberry32 { a: 1 }; + assert_eq!(r.next(), 0.6270739405881613); + } +} diff --git a/src-tauri/core/src/hatch_flat.rs b/src-tauri/core/src/hatch_flat.rs new file mode 100644 index 00000000..0a0381c7 --- /dev/null +++ b/src-tauri/core/src/hatch_flat.rs @@ -0,0 +1,60 @@ +//! Flache Kodierung von Punkten, Segmenten und Läufen für die Schraffur-Bindungen +//! (`[x, y, …]`, `[ax, ay, bx, by, …]`, `[n, x, y, …(n Punkte), n, …]`). Kaputte Eingaben +//! (ungerade Länge, Anzahl über das Pufferende) werden abgeschnitten, nie ein Panic. + +use crate::hatch::{v2, Run, V2}; + +pub fn pts(buf: &[f64]) -> Vec { + buf.chunks_exact(2).map(|c| v2(c[0], c[1])).collect() +} + +pub fn segs_out(segs: &[(V2, V2)]) -> Vec { + let mut out = Vec::with_capacity(segs.len() * 4); + for (a, b) in segs { + out.extend_from_slice(&[a.x, a.y, b.x, b.y]); + } + out +} + +pub fn runs_out(runs: &[Run]) -> Vec { + let mut out = Vec::new(); + for r in runs { + out.push(r.len() as f64); + for p in r { + out.push(p.x); + out.push(p.y); + } + } + out +} + +pub fn runs_in(buf: &[f64]) -> Vec { + let mut out = Vec::new(); + let mut i = 0; + while i < buf.len() { + let n = buf[i]; + if !(n >= 0.0) || n.fract() != 0.0 { + break; + } + let end = match (n as usize).checked_mul(2).and_then(|k| k.checked_add(i + 1)) { + Some(e) if e <= buf.len() => e, + _ => break, + }; + out.push(pts(&buf[i + 1..end])); + i = end; + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn laeufe_hin_und_zurueck() { + let r = vec![vec![v2(0.0, 1.0), v2(2.0, 3.0)], vec![v2(4.0, 5.0)]]; + assert_eq!(runs_in(&runs_out(&r)), r); + assert_eq!(runs_in(&[5.0, 1.0]), Vec::::new()); + assert_eq!(pts(&[1.0, 2.0, 3.0]), vec![v2(1.0, 2.0)]); + } +} diff --git a/src-tauri/core/src/jsnum.rs b/src-tauri/core/src/jsnum.rs new file mode 100644 index 00000000..21eb917c --- /dev/null +++ b/src-tauri/core/src/jsnum.rs @@ -0,0 +1,158 @@ +//! Zahl-Semantik von JavaScript für bitgleiche Portierungen ([K3b] GPU-Kompilierung, Schraffur). +//! +//! - `Math.min/max` liefern bei NaN NaN (Rust `f64::min/max` ignorieren NaN). +//! - `Math.round` rundet halbe Werte Richtung +∞ (Rust `round` weg von 0). +//! - `x | 0` ist ToInt32 (Rest modulo 2³², Rust `as i32` sättigt). +//! - Trigonometrie: im Web-Build (wasm32 + Feature "web") ruft der Kern `Math.cos/sin/atan2/acos` +//! der laufenden JS-Engine. Nur so sind die Werte bitgleich zur bisherigen TS-Fassung — V8 +//! (glibc-abgeleitete sin/cos), JavaScriptCore (System-libm von macOS) und Rusts libm (musl) +//! unterscheiden sich in einzelnen Fällen in der letzten Stelle. Nativ (`cargo test`, Tauri) +//! gilt die Rust-Standardbibliothek. + +#[cfg(all(feature = "web", target_arch = "wasm32"))] +mod trig { + use wasm_bindgen::prelude::wasm_bindgen; + + #[wasm_bindgen] + extern "C" { + #[wasm_bindgen(js_namespace = Math, js_name = cos)] + fn js_cos(x: f64) -> f64; + #[wasm_bindgen(js_namespace = Math, js_name = sin)] + fn js_sin(x: f64) -> f64; + #[wasm_bindgen(js_namespace = Math, js_name = atan2)] + fn js_atan2(y: f64, x: f64) -> f64; + #[wasm_bindgen(js_namespace = Math, js_name = acos)] + fn js_acos(x: f64) -> f64; + } + + #[inline] + pub fn cos(x: f64) -> f64 { + js_cos(x) + } + #[inline] + pub fn sin(x: f64) -> f64 { + js_sin(x) + } + #[inline] + pub fn atan2(y: f64, x: f64) -> f64 { + js_atan2(y, x) + } + #[inline] + pub fn acos(x: f64) -> f64 { + js_acos(x) + } +} + +#[cfg(not(all(feature = "web", target_arch = "wasm32")))] +mod trig { + #[inline] + pub fn cos(x: f64) -> f64 { + x.cos() + } + #[inline] + pub fn sin(x: f64) -> f64 { + x.sin() + } + #[inline] + pub fn atan2(y: f64, x: f64) -> f64 { + y.atan2(x) + } + #[inline] + pub fn acos(x: f64) -> f64 { + x.acos() + } +} + +pub use trig::{acos, atan2, cos, sin}; + +/// `Math.min(a, b)` (NaN gewinnt; −0 < +0). +#[inline] +pub fn min(a: f64, b: f64) -> f64 { + if a.is_nan() || b.is_nan() { + f64::NAN + } else if a < b || (a == b && a.is_sign_negative()) { + a + } else { + b + } +} + +/// `Math.max(a, b)` (NaN gewinnt; +0 > −0). +#[inline] +pub fn max(a: f64, b: f64) -> f64 { + if a.is_nan() || b.is_nan() { + f64::NAN + } else if a > b || (a == b && a.is_sign_positive()) { + a + } else { + b + } +} + +/// `Math.round(x)`: halbe Werte Richtung +∞, −0 bleibt −0, Werte in (−0.5, 0) → −0. +#[inline] +pub fn round(x: f64) -> f64 { + if !x.is_finite() || x == 0.0 { + return x; + } + if x > 0.0 && x < 0.5 { + return 0.0; + } + if x < 0.0 && x >= -0.5 { + return -0.0; + } + let r = x.ceil(); + if r - 0.5 > x { + r - 1.0 + } else { + r + } +} + +/// ToInt32 (`x | 0`). +#[inline] +pub fn to_int32(x: f64) -> i32 { + // Schneller Weg im i32-Bereich (`as` schneidet wie ToInt32 Richtung 0 ab; NaN → 0). + if (-2147483648.0..=2147483647.0).contains(&x) { + return x as i32; + } + if !x.is_finite() { + return 0; + } + let t = x.trunc(); + let m = t.rem_euclid(4294967296.0); + (m as u64 as u32) as i32 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rundung_wie_js() { + assert_eq!(round(2.5), 3.0); + assert_eq!(round(-2.5), -2.0); + assert_eq!(round(-0.5).to_bits(), (-0.0f64).to_bits()); + assert_eq!(round(0.49999999999999994), 0.0); + assert_eq!(round(-126.5), -126.0); + assert!(round(f64::NAN).is_nan()); + } + + #[test] + fn min_max_wie_js() { + assert!(min(1.0, f64::NAN).is_nan()); + assert!(max(f64::NAN, 1.0).is_nan()); + assert_eq!(max(0.0, -0.0).to_bits(), 0.0f64.to_bits()); + assert_eq!(min(0.0, -0.0).to_bits(), (-0.0f64).to_bits()); + assert_eq!(max(-1.0, min(1.0, 3.0)), 1.0); + } + + #[test] + fn int32_wie_js() { + assert_eq!(to_int32(4294967296.0 + 5.0), 5); + assert_eq!(to_int32(2147483648.0), -2147483648); + assert_eq!(to_int32(-1.7), -1); + assert_eq!(to_int32(f64::NAN), 0); + assert_eq!(to_int32(-4294967297.0), -1); + } +} diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index a61806ac..a349b5f0 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -28,6 +28,11 @@ pub mod columns3d; pub mod drawing2d_3d; pub mod openings3d; pub mod wall_mesh_cut; +pub mod jsnum; +pub mod hatch; +pub mod hatch_flat; +pub mod plan_buf; +pub mod gpu_compile; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/plan_buf.rs b/src-tauri/core/src/plan_buf.rs new file mode 100644 index 00000000..61027b6d --- /dev/null +++ b/src-tauri/core/src/plan_buf.rs @@ -0,0 +1,666 @@ +//! Plan-Puffer ([K3b]): kompakte Binärkodierung der zeichnungsrelevanten Plan-Primitive als +//! flacher `f64`-Puffer (TS schreibt ihn heute in `src/plan/planBuf.ts`, später erzeugt Rust ihn +//! direkt, [K3a]). Pick-IDs gehören nicht hinein (Picken bleibt vorerst TS); dafür hat jedes +//! Primitiv genau einen Eintrag, damit Indizes und Bereiche (`greyedRanges`, Chunks) gleich bleiben. +//! +//! ```text +//! Kopf [MAGIC, VERSION, nColors, nHatches, nPrims] +//! MAGIC = 0x504C4231 ("PLB1"), VERSION = 1 — fremde Werte → Puffer abgelehnt +//! Farben nColors × [r, g, b, a] (0..1, aus dem Farbtext in TS geparst) +//! Schraffuren nHatches × Hatch +//! Primitive nPrims × Prim +//! +//! Hatch [pattern, kind, flags, scale, angle, colorIdx, lineWeight, originX, originY, +//! seed, density, lengthMin, lengthMax, nDash, dash…, (Motiv: length, nPts, x,y…)] +//! pattern 0 none · 1 solid · 2 diagonal · 3 crosshatch · 4 insulation · 5 custom +//! kind 0 vector · 1 image · 2 gradient (Bild/Verlauf: GPU fällt auf die Füllung zurück) +//! flags 1 random · 2 origin · 4 seed · 8 density · 16 lengthMin · 32 lengthMax · 64 Motiv +//! (Felder ohne Flag stehen auf 0 und gelten als „nicht gesetzt“) +//! +//! Prim [tag, flags, …] flags 1 greyed · 2 opacity gesetzt · 4 setzt den Linienzug der +//! vorigen Linie fort · 8 Zickzack · 16 Motiv +//! 0 Platzhalter [0] (Text, Bild … — zeichnet die GPU nicht) +//! 1 polygon [1, flags, fillIdx, strokeIdx, strokeWidthMm, hatchIdx, opacity, +//! nPts, x,y…, nNoStroke, kante…] +//! 2 line [2, flags, colorIdx, weightMm, opacity, ax, ay, bx, by, nDash, dash…, +//! (Zickzack: amplitude, wavelength), (Motiv: length, nPts, x,y…)] +//! 3 arc [3, flags, colorIdx, weightMm, opacity, cx, cy, fromX, fromY, toX, toY, r, +//! nDash, dash…] +//! 4 drawingCircle [4, flags, fillIdx, strokeIdx, weightMm, opacity, cx, cy, r, nDash, dash…] +//! 5 drawingArc [5, flags, strokeIdx, weightMm, opacity, cx, cy, r, a0, a1, nDash, dash…] +//! ``` +//! Farb-/Schraffur-Index −1 = keine (Farbtext ungültig, "none", fehlende Schraffur). Längen in +//! Metern, Strichstärken/Strichmuster/Zickzack/Motiv in Papier-mm, Winkel von drawingArc in +//! Bogenmass, Schraffur-Winkel in Grad (SVG-Drehsinn). Ohne opacity-Flag steht 1 im Feld. +//! Fehlende Strichstärke (`undefined`) wird NaN (der Verbraucher nimmt dann seinen Standard). +//! Flag 4 (Linienzug): TS prüft gleiches Element (`drawingId`), gleiche Farbe/Stärke/greyed/ +//! opacity/Strichmuster und Anfang = Ende der vorigen Linie; der Verbraucher prüft die Lage nach. + +use crate::hatch::{Hatch, HatchKind, Motif, Pattern, V2}; + +pub const MAGIC: f64 = 1_347_174_961.0; // 0x504C4231 +pub const VERSION: f64 = 1.0; + +pub const FLAG_GREYED: u32 = 1; +pub const FLAG_OPACITY: u32 = 2; +pub const FLAG_CHAIN: u32 = 4; +pub const FLAG_ZIGZAG: u32 = 8; +pub const FLAG_MOTIF: u32 = 16; + +const HF_RANDOM: u32 = 1; +const HF_ORIGIN: u32 = 2; +const HF_SEED: u32 = 4; +const HF_DENSITY: u32 = 8; +const HF_LEN_MIN: u32 = 16; +const HF_LEN_MAX: u32 = 32; +const HF_MOTIF: u32 = 64; + +/// Gemeinsame Darstellungs-Attribute. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Style { + pub greyed: bool, + /// `None` = nicht gesetzt (deckend). + pub opacity: Option, +} + +/// Schraffur samt Farbindex. +#[derive(Clone, Debug, PartialEq)] +pub struct HatchEntry { + pub hatch: Hatch, + pub color: i32, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Prim { + Placeholder, + Polygon { + style: Style, + fill: i32, + stroke: i32, + stroke_width_mm: f64, + hatch: i32, + pts: Vec, + no_stroke_edges: Vec, + }, + Line { + style: Style, + color: i32, + weight_mm: f64, + a: V2, + b: V2, + dash: Vec, + /// Setzt den Linienzug der vorigen Linie fort (gleiches Element und gleicher Stil). + chain: bool, + zigzag: Option<(f64, f64)>, + motif: Option, + }, + Arc { + style: Style, + color: i32, + weight_mm: f64, + center: V2, + from: V2, + to: V2, + r: f64, + dash: Vec, + }, + Circle { + style: Style, + fill: i32, + stroke: i32, + weight_mm: f64, + center: V2, + r: f64, + dash: Vec, + }, + DrawingArc { + style: Style, + stroke: i32, + weight_mm: f64, + center: V2, + r: f64, + a0: f64, + a1: f64, + dash: Vec, + }, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PlanBuf { + pub colors: Vec<[f64; 4]>, + pub hatches: Vec, + pub prims: Vec, +} + +impl PlanBuf { + pub fn color(&self, idx: i32) -> Option<[f64; 4]> { + if idx < 0 { + None + } else { + self.colors.get(idx as usize).copied() + } + } +} + +// ── Lesen ─────────────────────────────────────────────────────────────────── + +struct Reader<'a> { + buf: &'a [f64], + pos: usize, +} + +impl<'a> Reader<'a> { + fn f(&mut self) -> Option { + let v = *self.buf.get(self.pos)?; + self.pos += 1; + Some(v) + } + /// Nicht-negative ganze Anzahl, höchstens so gross wie der Rest des Puffers × `per`. + fn count(&mut self, per: usize) -> Option { + let v = self.f()?; + if !(v >= 0.0) || v.fract() != 0.0 { + return None; + } + let n = v as usize; + if n.checked_mul(per)? > self.buf.len() - self.pos { + return None; + } + Some(n) + } + fn idx(&mut self) -> Option { + let v = self.f()?; + if v.fract() != 0.0 || !(v >= -1.0) || v > i32::MAX as f64 { + return None; + } + Some(v as i32) + } + fn flags(&mut self) -> Option { + let v = self.f()?; + if !(v >= 0.0) || v.fract() != 0.0 || v > u32::MAX as f64 { + return None; + } + Some(v as u32) + } + fn v2(&mut self) -> Option { + Some(V2 { x: self.f()?, y: self.f()? }) + } + fn list(&mut self) -> Option> { + let n = self.count(1)?; + let s = self.buf[self.pos..self.pos + n].to_vec(); + self.pos += n; + Some(s) + } + fn pts(&mut self) -> Option> { + let n = self.count(2)?; + let mut out = Vec::with_capacity(n); + for _ in 0..n { + out.push(self.v2()?); + } + Some(out) + } + fn motif(&mut self) -> Option { + let length = self.f()?; + Some(Motif { length, points: self.pts()? }) + } + fn style(flags: u32, opacity: f64) -> Style { + Style { greyed: flags & FLAG_GREYED != 0, opacity: if flags & FLAG_OPACITY != 0 { Some(opacity) } else { None } } + } +} + +fn opt(flags: u32, bit: u32, v: f64) -> Option { + if flags & bit != 0 { + Some(v) + } else { + None + } +} + +/// Einen Schraffur-Eintrag lesen (auch für die Einzel-Bindungen der Schraffur-Fassade). +fn read_hatch(r: &mut Reader) -> Option { + let pattern = Pattern::from_code(r.f()?); + let kind = HatchKind::from_code(r.f()?); + let flags = r.flags()?; + let scale = r.f()?; + let angle = r.f()?; + let color = r.idx()?; + let line_weight = r.f()?; + let origin = r.v2()?; + let seed = r.f()?; + let density = r.f()?; + let length_min = r.f()?; + let length_max = r.f()?; + let dash = r.list()?; + let motif = if flags & HF_MOTIF != 0 { Some(r.motif()?) } else { None }; + Some(HatchEntry { + hatch: Hatch { + pattern, + kind, + random: flags & HF_RANDOM != 0, + scale, + angle, + line_weight, + origin: if flags & HF_ORIGIN != 0 { Some(origin) } else { None }, + seed: opt(flags, HF_SEED, seed), + density: opt(flags, HF_DENSITY, density), + length_min: opt(flags, HF_LEN_MIN, length_min), + length_max: opt(flags, HF_LEN_MAX, length_max), + dash, + motif, + }, + color, + }) +} + +/// Einzelne Schraffur (Format wie ein Hatch-Eintrag des Plan-Puffers) ab `buf[0]`. +pub fn decode_hatch(buf: &[f64]) -> Option<(Hatch, usize)> { + let mut r = Reader { buf, pos: 0 }; + let h = read_hatch(&mut r)?; + Some((h.hatch, r.pos)) +} + +fn read_prim(r: &mut Reader) -> Option { + let tag = r.f()?; + if tag == 0.0 { + return Some(Prim::Placeholder); + } + let flags = r.flags()?; + Some(match tag as i64 { + 1 => { + let fill = r.idx()?; + let stroke = r.idx()?; + let stroke_width_mm = r.f()?; + let hatch = r.idx()?; + let opacity = r.f()?; + let pts = r.pts()?; + let no_stroke_edges = r.list()?; + Prim::Polygon { style: Reader::style(flags, opacity), fill, stroke, stroke_width_mm, hatch, pts, no_stroke_edges } + } + 2 => { + let color = r.idx()?; + let weight_mm = r.f()?; + let opacity = r.f()?; + let a = r.v2()?; + let b = r.v2()?; + let dash = r.list()?; + let zigzag = if flags & FLAG_ZIGZAG != 0 { Some((r.f()?, r.f()?)) } else { None }; + let motif = if flags & FLAG_MOTIF != 0 { Some(r.motif()?) } else { None }; + Prim::Line { style: Reader::style(flags, opacity), color, weight_mm, a, b, dash, chain: flags & FLAG_CHAIN != 0, zigzag, motif } + } + 3 => { + let color = r.idx()?; + let weight_mm = r.f()?; + let opacity = r.f()?; + let center = r.v2()?; + let from = r.v2()?; + let to = r.v2()?; + let rad = r.f()?; + let dash = r.list()?; + Prim::Arc { style: Reader::style(flags, opacity), color, weight_mm, center, from, to, r: rad, dash } + } + 4 => { + let fill = r.idx()?; + let stroke = r.idx()?; + let weight_mm = r.f()?; + let opacity = r.f()?; + let center = r.v2()?; + let rad = r.f()?; + let dash = r.list()?; + Prim::Circle { style: Reader::style(flags, opacity), fill, stroke, weight_mm, center, r: rad, dash } + } + 5 => { + let stroke = r.idx()?; + let weight_mm = r.f()?; + let opacity = r.f()?; + let center = r.v2()?; + let rad = r.f()?; + let a0 = r.f()?; + let a1 = r.f()?; + let dash = r.list()?; + Prim::DrawingArc { style: Reader::style(flags, opacity), stroke, weight_mm, center, r: rad, a0, a1, dash } + } + _ => return None, + }) +} + +/// Puffer lesen; `None` bei fremder Magie/Version oder kaputtem Puffer (nie ein Panic). +pub fn decode(buf: &[f64]) -> Option { + let mut r = Reader { buf, pos: 0 }; + if r.f()? != MAGIC || r.f()? != VERSION { + return None; + } + let n_colors = r.count(4)?; + let n_hatches = r.count(1)?; + let n_prims = r.count(1)?; + let mut colors = Vec::with_capacity(n_colors); + for _ in 0..n_colors { + colors.push([r.f()?, r.f()?, r.f()?, r.f()?]); + } + let mut hatches = Vec::with_capacity(n_hatches); + for _ in 0..n_hatches { + hatches.push(read_hatch(&mut r)?); + } + let mut prims = Vec::with_capacity(n_prims); + for _ in 0..n_prims { + prims.push(read_prim(&mut r)?); + } + if r.pos != buf.len() { + return None; + } + Some(PlanBuf { colors, hatches, prims }) +} + +// ── Schreiben (Rust-Erzeuger ab [K3a]; heute für Hin-und-zurück-Tests) ────── + +fn put_list(out: &mut Vec, l: &[f64]) { + out.push(l.len() as f64); + out.extend_from_slice(l); +} + +fn put_pts(out: &mut Vec, pts: &[V2]) { + out.push(pts.len() as f64); + for p in pts { + out.push(p.x); + out.push(p.y); + } +} + +fn style_flags(s: &Style) -> u32 { + (if s.greyed { FLAG_GREYED } else { 0 }) | (if s.opacity.is_some() { FLAG_OPACITY } else { 0 }) +} + +fn write_hatch(out: &mut Vec, e: &HatchEntry) { + let h = &e.hatch; + let mut flags = 0; + if h.random { + flags |= HF_RANDOM; + } + if h.origin.is_some() { + flags |= HF_ORIGIN; + } + if h.seed.is_some() { + flags |= HF_SEED; + } + if h.density.is_some() { + flags |= HF_DENSITY; + } + if h.length_min.is_some() { + flags |= HF_LEN_MIN; + } + if h.length_max.is_some() { + flags |= HF_LEN_MAX; + } + if h.motif.is_some() { + flags |= HF_MOTIF; + } + let o = h.origin.unwrap_or(V2 { x: 0.0, y: 0.0 }); + out.extend_from_slice(&[ + h.pattern as u8 as f64, + h.kind as u8 as f64, + flags as f64, + h.scale, + h.angle, + e.color as f64, + h.line_weight, + o.x, + o.y, + h.seed.unwrap_or(0.0), + h.density.unwrap_or(0.0), + h.length_min.unwrap_or(0.0), + h.length_max.unwrap_or(0.0), + ]); + put_list(out, &h.dash); + if let Some(m) = &h.motif { + out.push(m.length); + put_pts(out, &m.points); + } +} + +pub fn encode(p: &PlanBuf) -> Vec { + let mut out = vec![MAGIC, VERSION, p.colors.len() as f64, p.hatches.len() as f64, p.prims.len() as f64]; + for c in &p.colors { + out.extend_from_slice(c); + } + for h in &p.hatches { + write_hatch(&mut out, h); + } + for prim in &p.prims { + match prim { + Prim::Placeholder => out.push(0.0), + Prim::Polygon { style, fill, stroke, stroke_width_mm, hatch, pts, no_stroke_edges } => { + out.extend_from_slice(&[ + 1.0, + style_flags(style) as f64, + *fill as f64, + *stroke as f64, + *stroke_width_mm, + *hatch as f64, + style.opacity.unwrap_or(1.0), + ]); + put_pts(&mut out, pts); + put_list(&mut out, no_stroke_edges); + } + Prim::Line { style, color, weight_mm, a, b, dash, chain, zigzag, motif } => { + let mut flags = style_flags(style); + if *chain { + flags |= FLAG_CHAIN; + } + if zigzag.is_some() { + flags |= FLAG_ZIGZAG; + } + if motif.is_some() { + flags |= FLAG_MOTIF; + } + out.extend_from_slice(&[2.0, flags as f64, *color as f64, *weight_mm, style.opacity.unwrap_or(1.0), a.x, a.y, b.x, b.y]); + put_list(&mut out, dash); + if let Some((amp, wav)) = zigzag { + out.push(*amp); + out.push(*wav); + } + if let Some(m) = motif { + out.push(m.length); + put_pts(&mut out, &m.points); + } + } + Prim::Arc { style, color, weight_mm, center, from, to, r, dash } => { + out.extend_from_slice(&[ + 3.0, + style_flags(style) as f64, + *color as f64, + *weight_mm, + style.opacity.unwrap_or(1.0), + center.x, + center.y, + from.x, + from.y, + to.x, + to.y, + *r, + ]); + put_list(&mut out, dash); + } + Prim::Circle { style, fill, stroke, weight_mm, center, r, dash } => { + out.extend_from_slice(&[ + 4.0, + style_flags(style) as f64, + *fill as f64, + *stroke as f64, + *weight_mm, + style.opacity.unwrap_or(1.0), + center.x, + center.y, + *r, + ]); + put_list(&mut out, dash); + } + Prim::DrawingArc { style, stroke, weight_mm, center, r, a0, a1, dash } => { + out.extend_from_slice(&[ + 5.0, + style_flags(style) as f64, + *stroke as f64, + *weight_mm, + style.opacity.unwrap_or(1.0), + center.x, + center.y, + *r, + *a0, + *a1, + ]); + put_list(&mut out, dash); + } + } + } + out +} + +/// Lesen und neu schreiben (Hin-und-zurück-Prüfung der TS-Kodierung); leer bei kaputtem Puffer. +pub fn recode(buf: &[f64]) -> Vec { + decode(buf).map(|p| encode(&p)).unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::hatch::v2; + + fn style() -> Style { + Style { greyed: true, opacity: Some(0.5) } + } + + fn sample() -> PlanBuf { + PlanBuf { + colors: vec![[0.1, 0.2, 0.3, 1.0], [1.0, 1.0, 1.0, 0.25]], + hatches: vec![ + HatchEntry { + hatch: Hatch { + pattern: Pattern::Custom, + kind: HatchKind::Vector, + random: true, + scale: 2.0, + angle: 30.0, + line_weight: 0.13, + origin: Some(v2(1.0, 2.0)), + seed: Some(7.0), + density: Some(1.5), + length_min: Some(0.5), + length_max: Some(2.0), + dash: vec![1.0, 0.5], + motif: Some(Motif { points: vec![v2(0.0, 0.0), v2(1.0, 1.0)], length: 2.0 }), + }, + color: 0, + }, + HatchEntry { + hatch: Hatch { + pattern: Pattern::Insulation, + kind: HatchKind::Gradient, + random: false, + scale: 1.0, + angle: 0.0, + line_weight: 0.0, + origin: None, + seed: None, + density: None, + length_min: None, + length_max: None, + dash: vec![], + motif: None, + }, + color: -1, + }, + ], + prims: vec![ + Prim::Placeholder, + Prim::Polygon { + style: style(), + fill: 1, + stroke: 0, + stroke_width_mm: 0.35, + hatch: 0, + pts: vec![v2(0.0, 0.0), v2(1.0, 0.0), v2(0.0, 1.0)], + no_stroke_edges: vec![1.0, 2.0], + }, + Prim::Line { + style: Style { greyed: false, opacity: None }, + color: -1, + weight_mm: f64::NAN, + a: v2(0.0, 0.0), + b: v2(3.0, 4.0), + dash: vec![2.0], + chain: true, + zigzag: Some((1.0, 4.0)), + motif: Some(Motif { points: vec![v2(0.0, 0.0), v2(2.0, 1.0)], length: 4.0 }), + }, + Prim::Arc { + style: style(), + color: 0, + weight_mm: 0.25, + center: v2(0.0, 0.0), + from: v2(1.0, 0.0), + to: v2(0.0, 1.0), + r: 1.0, + dash: vec![], + }, + Prim::Circle { style: style(), fill: -1, stroke: 1, weight_mm: 0.18, center: v2(5.0, 5.0), r: 2.0, dash: vec![] }, + Prim::DrawingArc { + style: style(), + stroke: 0, + weight_mm: 0.18, + center: v2(5.0, 5.0), + r: 2.0, + a0: 0.0, + a1: 3.0, + dash: vec![0.5, 0.5], + }, + ], + } + } + + /// NaN-feste Gleichheit über die Bits der Kodierung. + fn bits(v: &[f64]) -> Vec { + v.iter().map(|x| x.to_bits()).collect() + } + + #[test] + fn hin_und_zurueck_je_typ() { + let p = sample(); + let enc = encode(&p); + let back = decode(&enc).expect("lesbar"); + assert_eq!(bits(&encode(&back)), bits(&enc)); + assert_eq!(back.prims.len(), 6); + assert_eq!(back.colors, p.colors); + assert_eq!(back.hatches, p.hatches); + // Je Typ einzeln (NaN-Stärke der Linie über die Bits). + for (i, prim) in p.prims.iter().enumerate() { + if i == 2 { + continue; + } + assert_eq!(&back.prims[i], prim); + } + if let Prim::Line { weight_mm, chain, zigzag, .. } = &back.prims[2] { + assert!(weight_mm.is_nan()); + assert!(*chain); + assert_eq!(*zigzag, Some((1.0, 4.0))); + } else { + panic!("Linie erwartet"); + } + } + + #[test] + fn fremde_version_und_kaputte_puffer() { + let mut enc = encode(&sample()); + assert!(decode(&enc[..enc.len() - 1]).is_none()); + let mut extra = enc.clone(); + extra.push(0.0); + assert!(decode(&extra).is_none()); + enc[1] = 2.0; + assert!(decode(&enc).is_none()); + enc[1] = VERSION; + enc[0] = 0.0; + assert!(decode(&enc).is_none()); + assert!(decode(&[]).is_none()); + // Riesige Anzahl ohne Daten: kein Speicher-Absturz. + assert!(decode(&[MAGIC, VERSION, 1e15, 0.0, 0.0]).is_none()); + assert!(decode(&[MAGIC, VERSION, 0.0, 0.0, 1.0, 9.0, 0.0]).is_none()); + assert!(decode(&[MAGIC, VERSION, 0.0, 0.0, f64::NAN]).is_none()); + assert_eq!(recode(&[1.0, 2.0]), Vec::::new()); + } +} diff --git a/src-tauri/core/src/web/gpu_compile.rs b/src-tauri/core/src/web/gpu_compile.rs new file mode 100644 index 00000000..99216b83 --- /dev/null +++ b/src-tauri/core/src/web/gpu_compile.rs @@ -0,0 +1,16 @@ +//! Bindungen der GPU-Kompilierung (`crate::gpu_compile`). Ausgabe-Layout s. dort. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Plan-Puffer (ein Chunk) → Vertex-/Index-/Batch-Daten als ein `u32`-Puffer; leer bei +/// unlesbarem Puffer. +#[wasm_bindgen] +pub fn gpu_compile_flat(buf: &[f64], px_per_meter: f64, packed_lines: bool) -> Vec { + crate::gpu_compile::compile_flat(buf, px_per_meter, packed_lines) +} + +/// Ear-Clipping eines Rings `[x, y, …]` → Dreiecks-Indizes. +#[wasm_bindgen] +pub fn triangulate_flat(pts: &[f64]) -> Vec { + crate::gpu_compile::triangulate(&crate::hatch_flat::pts(pts)) +} diff --git a/src-tauri/core/src/web/hatch.rs b/src-tauri/core/src/web/hatch.rs new file mode 100644 index 00000000..45e83c37 --- /dev/null +++ b/src-tauri/core/src/web/hatch.rs @@ -0,0 +1,90 @@ +//! Bindungen der Schraffur-/Linienmuster-Geometrie (`crate::hatch`) für die TS-Fassade +//! `glPlanHatch.ts`. Punkte als `[x, y, …]`, Läufe als `[n, x, y, …(n Punkte), n, …]`, +//! Segmente als `[ax, ay, bx, by, …]`, Schraffur im Hatch-Format des Plan-Puffers. + +use crate::hatch::{self, v2, Motif}; +use crate::hatch_flat::{pts, runs_in, runs_out, segs_out}; +use wasm_bindgen::prelude::wasm_bindgen; + +fn opt(v: f64) -> Option { + if v.is_nan() { + None + } else { + Some(v) + } +} + +#[wasm_bindgen] +pub fn hatch_runs_flat(poly: &[f64], hatch_buf: &[f64]) -> Vec { + match crate::plan_buf::decode_hatch(hatch_buf) { + Some((h, _)) => runs_out(&hatch::build_hatch_runs(&pts(poly), &h)), + None => Vec::new(), + } +} + +/// `scale` NaN = aus der Schraffur. +#[wasm_bindgen] +pub fn random_hatch_runs_flat(poly: &[f64], hatch_buf: &[f64], scale: f64) -> Vec { + match crate::plan_buf::decode_hatch(hatch_buf) { + Some((h, _)) => runs_out(&hatch::build_random_hatch_runs(&pts(poly), &h, opt(scale))), + None => Vec::new(), + } +} + +#[wasm_bindgen] +pub fn dash_runs_flat(runs: &[f64], dash: &[f64]) -> Vec { + runs_out(&hatch::apply_dash_runs(runs_in(runs), dash)) +} + +/// Leer = entartet (Aufrufer nimmt `[a, b]`). +#[wasm_bindgen] +pub fn zigzag_points_flat(ax: f64, ay: f64, bx: f64, by: f64, amplitude: f64, wavelength: f64) -> Vec { + match hatch::zigzag_points(v2(ax, ay), v2(bx, by), amplitude, wavelength) { + Some(p) => p.iter().flat_map(|q| [q.x, q.y]).collect(), + None => Vec::new(), + } +} + +/// Leer = entartet (Aufrufer nimmt `[a, b]`). +#[wasm_bindgen] +pub fn motif_points_flat(ax: f64, ay: f64, bx: f64, by: f64, motif_pts: &[f64], length: f64, scale: f64) -> Vec { + let m = Motif { points: pts(motif_pts), length }; + match hatch::motif_points_opt(v2(ax, ay), v2(bx, by), &m, scale) { + Some(p) => p.iter().flat_map(|q| [q.x, q.y]).collect(), + None => Vec::new(), + } +} + +#[wasm_bindgen] +pub fn clip_line_to_polygon_flat(px: f64, py: f64, dx: f64, dy: f64, poly: &[f64]) -> Vec { + segs_out(&hatch::clip_line_to_polygon(v2(px, py), v2(dx, dy), &pts(poly))) +} + +#[wasm_bindgen] +pub fn clip_segment_to_polygon_flat(ax: f64, ay: f64, bx: f64, by: f64, poly: &[f64]) -> Vec { + segs_out(&hatch::clip_segment_to_polygon(v2(ax, ay), v2(bx, by), &pts(poly))) +} + +#[wasm_bindgen] +pub fn clip_polyline_to_polygon_flat(line: &[f64], poly: &[f64]) -> Vec { + runs_out(&hatch::clip_polyline_to_polygon(&pts(line), &pts(poly))) +} + +#[wasm_bindgen] +pub fn hatch_line_family_flat(poly: &[f64], angle_rad: f64, spacing_m: f64, offset_m: f64, ax: f64, ay: f64) -> Vec { + segs_out(&hatch::hatch_line_family(&pts(poly), angle_rad, spacing_m, offset_m, v2(ax, ay))) +} + +/// `len_min`/`len_max` NaN = nicht gesetzt. +#[wasm_bindgen] +pub fn scatter_strokes_flat( + poly: &[f64], + cell: f64, + base_angle_rad: f64, + seed: f64, + stroke_len: f64, + len_min: f64, + len_max: f64, +) -> Vec { + runs_out(&hatch::scatter_strokes(&pts(poly), cell, base_angle_rad, seed, stroke_len, opt(len_min), opt(len_max))) +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 061b7659..574f5710 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -23,6 +23,9 @@ mod columns3d; mod drawing2d_3d; mod openings3d; mod wall_mesh_cut; +mod plan_buf; +mod gpu_compile; +mod hatch; 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 new file mode 100644 index 00000000..f421c499 --- /dev/null +++ b/src-tauri/core/src/web/plan_buf.rs @@ -0,0 +1,10 @@ +//! Bindungen des Plan-Puffers (`crate::plan_buf`). Format s. dort. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// Plan-Puffer lesen und neu schreiben (Hin-und-zurück-Prüfung der TS-Kodierung); leer bei +/// fremder Version oder kaputtem Puffer. +#[wasm_bindgen] +pub fn plan_buf_recode(buf: &[f64]) -> Vec { + crate::plan_buf::recode(buf) +} diff --git a/src/plan/glPlan/glPlanCompile.ts b/src/plan/glPlan/glPlanCompile.ts index 87e0c29a..e171cb04 100644 --- a/src/plan/glPlan/glPlanCompile.ts +++ b/src/plan/glPlan/glPlanCompile.ts @@ -1,802 +1,109 @@ /** - * Tessellierung: wandelt Plan-`Primitive` in GPU-fertige Puffer. - * • Polygone → echtes Ear-Clipping (konkav-fähig), Bildschirm-Raum-Dreiecke - * • Linien → Quad mit Normale + Seiten-Flag (bildschirmkonstante Breite) + * Tessellierung: wandelt Plan-`Primitive` in GPU-fertige Puffer — Fassade über den Rust-Kern + * ([K3b], `src-tauri/core/src/gpu_compile.rs`). TS kodiert die Primitive eines Chunks in den + * Plan-Puffer (`../planBuf.ts`), Rust tesselliert (Ear-Clipping, Striche mit runden Kappen/Ecken, + * Schraffur, Zickzack, Motive, Bögen, Kreise) und liefert Vertex-/Index-/Batch-Daten flach zurück; + * hier werden sie nur noch hochgeladen. * - * Koordinaten: alles wird in BILDSCHIRM-Raum abgelegt (wie `toScreen`): - * sx = mx·PX_PER_M, sy = -my·PX_PER_M. - * Damit ist die Projektion eine reine viewBox-Orthografie (siehe glPlanRender). + * Koordinaten: alles in BILDSCHIRM-Raum (wie `toScreen`): sx = mx·PX_PER_M, sy = -my·PX_PER_M, + * relativ zum lokalen Ursprung (`origin`, erster abgelegter Punkt). */ import type { Primitive } from '../generatePlan'; import type { Vec2 } from '../../model/types'; import type { BufferGl, GpuGeometry, Rgba } from './glPlanTypes'; -import { applyDashRuns, buildHatchRuns, zigzagPoints, motifPoints, DASH_MM_TO_M } from './glPlanHatch'; - -const PX_PER_M = 90; +import { encodePlanBuf } from '../planBuf'; +import { core } from '../../engine/coreWasm'; /** - * Wachsender Typed-Array-Puffer statt `number[]` für die Vertex-/Index-Daten. - * Normale JS-Arrays sind in V8/JSC praktisch auf ~134 Mio. Elemente begrenzt - * (`FixedArray::kMaxLength`) — ein ganzer Kataster-Import (3,7 Mio. Linien- - * Segmente, reproduziert mit der 439-MB-Luzerner-DXF) überschreitet das beim - * Linien-Vertexpuffer (`RangeError: Invalid array length`). Typed Arrays haben - * diese Grenze nicht und brauchen nur 4 statt 8 Byte je Wert. Die hochgeladenen - * Daten sind identisch: der Upload hat schon bisher nach Float32/Uint32 gewandelt. - */ -class GrowBuffer { - private buf: T; - length = 0; - constructor(private readonly make: (n: number) => T) { - this.buf = make(1024); - } - private ensure(extra: number): void { - const need = this.length + extra; - if (need <= this.buf.length) return; - let cap = this.buf.length * 2; - while (cap < need) cap *= 2; - const next = this.make(cap); - next.set(this.buf.subarray(0, this.length)); - this.buf = next; - } - push1(a: number): void { - this.ensure(1); - this.buf[this.length++] = a; - } - push2(a: number, b: number): void { - this.ensure(2); - const o = this.length; - this.buf[o] = a; - this.buf[o + 1] = b; - this.length = o + 2; - } - push3(a: number, b: number, c: number): void { - this.ensure(3); - const o = this.length; - this.buf[o] = a; - this.buf[o + 1] = b; - this.buf[o + 2] = c; - this.length = o + 3; - } - push6(a: number, b: number, c: number, d: number, e: number, f: number): void { - this.ensure(6); - const o = this.length; - this.buf[o] = a; - this.buf[o + 1] = b; - this.buf[o + 2] = c; - this.buf[o + 3] = d; - this.buf[o + 4] = e; - this.buf[o + 5] = f; - this.length = o + 6; - } - /** Gefüllter Bereich (View, keine Kopie). */ - view(): T { - return this.buf.subarray(0, this.length) as T; - } -} - -/** Modell-Meter → Bildschirm-Raum (identisch zu PlanView.toScreen). */ -function toScreen(p: Vec2): Vec2 { - return { x: p.x * PX_PER_M, y: -p.y * PX_PER_M }; -} - -/** Signierte Fläche (Shoelace); >0 = CCW (Modell-Y nach oben). */ -function signedArea(pts: Vec2[]): number { - let a = 0; - for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { - a += pts[j].x * pts[i].y - pts[i].x * pts[j].y; - } - return a / 2; -} - -/** Kreuzprodukt (b-a)×(c-a). */ -function cross(a: Vec2, b: Vec2, c: Vec2): number { - return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); -} - -/** Liegt p im (a,b,c)-Dreieck? (CCW-orientiert). */ -function pointInTri(a: Vec2, b: Vec2, c: Vec2, p: Vec2): boolean { - const d1 = cross(a, b, p); - const d2 = cross(b, c, p); - const d3 = cross(c, a, p); - const hasNeg = d1 < 0 || d2 < 0 || d3 < 0; - const hasPos = d1 > 0 || d2 > 0 || d3 > 0; - return !(hasNeg && hasPos); -} - -/** - * Ear-Clipping-Triangulierung eines einfachen (lochfreien) Polygons. Robust für - * konvexe UND konkave Ringe. Gibt Dreiecks-Indizes (0-basiert auf `pts`) - * zurück; [] bei <3 Ecken oder Degeneration. - * - * PERFORMANCE (Nutzer-Report 2026-10: App hängt nach Import einer grossen - * Kataster-DXF, 69k Konturen): die naive Fassung war O(n) Ohren × O(n) - * Kandidatensuche × O(n) Enthalten-Test (plus O(n) `Array.splice` pro Ohr) - * — für ein paar Dutzend Handzeichnungs-Ecken unmerklich, aber bei einem - * einzelnen gefüllten Polygon mit tausenden Stützpunkten (z. B. eine - * detaillierte Parzellen-/Flächen-HATCH-Kontur aus einer amtlichen - * Vermessung) effektiv O(n³) — EIN solches Polygon konnte die App für - * Minuten einfrieren. Fix, ohne das Ergebnis zu ändern: nur REFLEXE (konkave) - * Ecken können in einem Ohr liegen (Standard-Resultat der Ear-Clipping- - * Literatur) — der Enthalten-Test scannt daher nur die (meist kleine) - * Reflex-Menge statt aller Ecken, und das Abschneiden eines Ohrs läuft über - * eine verkettete Liste (O(1)) statt `splice` (O(n)). Für überwiegend konvexe - * Polygone (die Mehrheit realer Gebäude-/Parzellen-Umrisse) sinkt die - * Gesamtkosten dadurch von O(n³) auf nahe O(n · r) mit r = Anzahl Reflex- - * Ecken (oft einstellig, unabhängig von n); echter Worst-Case (ALLE Ecken - * reflex, z. B. ein Zickzack) bleibt bei O(n²) — nie schlechter als vorher. + * Ear-Clipping-Triangulierung eines einfachen (lochfreien) Polygons, konvex oder konkav. + * Dreiecks-Indizes (0-basiert auf `pts`); [] bei <3 Ecken oder Degeneration. */ export function triangulate(pts: Vec2[]): number[] { - const n = pts.length; - if (n < 3) return []; - - // Ohr-Test unten nutzt cross>0 = konvex, was CCW voraussetzt. Bei CW-Polygonen - // die Reihenfolge umdrehen (Triangulierung ist raum-affin-invariant, die - // Indizes gelten danach auch für die Bildschirm-Raum-Vertices). - const order: number[] = []; - for (let i = 0; i < n; i++) order.push(i); - if (signedArea(pts) < 0) order.reverse(); // <0 = CW → auf CCW drehen - - // Doppelt verkettete Liste über die (ggf. gedrehte) Reihenfolge — macht das - // Entfernen eines abgeschnittenen Ohrs O(1) (Nachbarn neu verknüpfen statt - // Array-splice). - const next = new Int32Array(n); - const prev = new Int32Array(n); - for (let i = 0; i < n; i++) { - next[order[i]] = order[(i + 1) % n]; - prev[order[i]] = order[(i - 1 + n) % n]; + if (pts.length < 3) return []; + const flat = new Float64Array(pts.length * 2); + for (let i = 0; i < pts.length; i++) { + flat[2 * i] = pts[i].x; + flat[2 * i + 1] = pts[i].y; } - - const isReflex = (i: number): boolean => cross(pts[prev[i]], pts[i], pts[next[i]]) <= 0; - const reflex = new Set(); - for (const i of order) if (isReflex(i)) reflex.add(i); - - const tris: number[] = []; - let remaining = n; - let i = order[0]; - let noEarStreak = 0; - let guard = 0; - const maxGuard = n * n + 16; - - while (remaining > 3 && guard++ < maxGuard) { - const a = prev[i]; - const b = i; - const c = next[i]; - // Konvexe Ecke (nicht reflex) UND kein anderer (notwendig reflexer) - // Vertex im Ohr-Dreieck → gültiges Ohr. - let isEar = !reflex.has(b); - if (isEar) { - for (const vi of reflex) { - if (vi === a || vi === b || vi === c) continue; - if (pointInTri(pts[a], pts[b], pts[c], pts[vi])) { - isEar = false; - break; - } - } - } - - if (isEar) { - tris.push(a, b, c); - next[a] = c; - prev[c] = a; - reflex.delete(b); - remaining--; - // Nachbarn können durch die neue Kante ihre Konvexität wechseln (in - // beide Richtungen) — Reflex-Menge entsprechend nachführen. - if (isReflex(a)) reflex.add(a); else reflex.delete(a); - if (isReflex(c)) reflex.add(c); else reflex.delete(c); - i = a; // nach einem Schnitt zuerst den Vorgänger erneut prüfen (üblich) - noEarStreak = 0; - } else { - i = c; - // Kein Ohr nach einer vollen Runde über den Restring gefunden → - // degeneriert (z. B. selbstüberschneidend). Abbrechen statt endlos - // weiterzusuchen (kein Crash, wie zuvor). - if (++noEarStreak > remaining) break; - } - } - if (remaining === 3) tris.push(prev[i], i, next[i]); - return tris; + return Array.from(core().triangulate_flat(flat)); } /** - * Farbe → RGBA[0..1]; ungültig/"none"/"transparent" → null. - * Unterstützt "#rgb", "#rrggbb", "#rrggbbaa" und "rgb()/rgba()". - */ -function parseColor(hex: string | undefined): Rgba | null { - if (!hex) return null; - const s = hex.trim().toLowerCase(); - if (s === 'none' || s === 'transparent') return null; - - if (s.startsWith('rgb')) { - const m = s.match(/[\d.]+/g); - if (!m || m.length < 3) return null; - const a = m.length >= 4 ? parseFloat(m[3]) : 1; - return [+m[0] / 255, +m[1] / 255, +m[2] / 255, a > 1 ? a / 255 : a]; - } - - let h = s[0] === '#' ? s.slice(1) : s; - if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2]; - if (h.length !== 6 && h.length !== 8) return null; - const r = parseInt(h.slice(0, 2), 16); - const g = parseInt(h.slice(2, 4), 16); - const b = parseInt(h.slice(4, 6), 16); - const a = h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1; - if (isNaN(r) || isNaN(g) || isNaN(b)) return null; - return [r / 255, g / 255, b / 255, a]; -} - -/** - * 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 toRenderScene.ts (#8c8c8c ≈ 0.549). - */ -export const GREY_RGB = 0.549; - -/** - * Färbt auf den festen Grauton um, wenn das Primitiv im Darstellungsmodus - * „grau" ist, und multipliziert die Objekt-Transparenz (`Drawing2D.opacity`) - * in den Alphakanal. Beides ist unabhängig: gedimmt wird UMGEFÄRBT (damit - * dünne Linien erkennbar bleiben), transparent wird über Alpha. - */ -function dim(color: Rgba, greyed: boolean | undefined, opacity?: number): Rgba { - const c: Rgba = greyed ? [GREY_RGB, GREY_RGB, GREY_RGB, color[3]] : color; - if (opacity === undefined || opacity >= 1) return c; - return [c[0], c[1], c[2], c[3] * Math.max(0, opacity)]; -} - -/** - * Wie `dim`, aber für FLÄCHEN-Füllung: gedimmte Flächen bleiben WEISS statt - * grau eingefärbt — nur der Umriss (weiterhin `dim`) 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 dimFill(color: Rgba, greyed: boolean | undefined, opacity?: number): Rgba { - const c: Rgba = greyed ? [1, 1, 1, color[3]] : color; - if (opacity === undefined || opacity >= 1) return c; - return [c[0], c[1], c[2], c[3] * Math.max(0, opacity)]; -} - -/** - * Tessellliert Plan-Primitive zu GPU-Geometrie (MVP: gefüllte Polygone + - * bildschirmkonstante Striche). Text/Bögen bleiben im SVG-Overlay. + * Tesselliert Plan-Primitive zu GPU-Geometrie (Füllungen + bildschirmkonstante Striche). + * Text/Bilder bleiben im Overlay. */ export function compilePrimitivesToGpu( gl: BufferGl, primitives: Primitive[], - // Bildschirm-Massstab (Geräte-px je Modell-Meter) beim aktuellen Zoom. Steuert - // NUR die adaptive Bogen-Tessellierung (siehe 'arc'-Zweig): je stärker - // hineingezoomt, desto mehr Segmente, damit der Bogen rund statt facettiert - // erscheint. 0 → zoom-unabhängiger Rückfall (fixe 16 Segmente je 90°), z. B. - // wenn der Aufrufer den Massstab (noch) nicht kennt. + // Bildschirm-Massstab (Geräte-px je Modell-Meter) beim aktuellen Zoom. Steuert NUR die + // adaptive Bogen-Tessellierung; 0 → zoom-unabhängiger Rückfall (16 Segmente je 90°). pxPerMeter = 0, ): GpuGeometry { - // Füll-Puffer (Bildschirm-Raum Positionen + Indizes). - const fillPos = new GrowBuffer((n) => new Float32Array(n)); - const fillIdx = new GrowBuffer((n) => new Uint32Array(n)); + const packed = gl.packedLineVertices === true; + const out = core().gpu_compile_flat(encodePlanBuf(primitives), pxPerMeter, packed); + return uploadCompiled(gl, out); +} + +/** Flache Kern-Ausgabe (Layout s. `gpu_compile.rs`) → hochgeladene `GpuGeometry`. */ +function uploadCompiled(gl: BufferGl, out: Uint32Array): GpuGeometry { + if (out.length < 2) { + return { + fill: { positionBuffer: null, indexBuffer: null, batches: [] }, + line: { vertexBuffer: null, indexBuffer: null, batches: [] }, + origin: { x: 0, y: 0 }, + bounds: { minX: 0, minY: 0, maxX: 1, maxY: 1 }, + }; + } + const m = out[0]; + const meta = new Float64Array(out.buffer, out.byteOffset + 8, m); + const [originX, originY, minX, minY, maxX, maxY, nFillPos, nFillIdx, nLineVerts, nLineIdx, nFill, nLine] = meta; + let k = 12; const fillBatches: GpuGeometry['fill']['batches'] = []; - - // Linien-Puffer: interleaved [x,y, nx,ny, side, miter] (6 Float32) — oder, wenn - // der Aufrufer es verlangt (nativer Renderer), kompakt 3 Wörter je Vertex: - // [x, y (float32-Bits), nx|ny|side|miter als 4 × snorm8]. - const packedLines = gl.packedLineVertices === true; - const lineVerts = new GrowBuffer((n) => new Float32Array(n)); - const lineVertsPacked = new GrowBuffer((n) => new Uint32Array(n)); - const bitsF32 = new Float32Array(1); - const bitsU32 = new Uint32Array(bitsF32.buffer); - const f2u = (v: number): number => { - bitsF32[0] = v; - return bitsU32[0]; - }; - const snorm8 = (v: number): number => Math.round(Math.max(-1, Math.min(1, v)) * 127) & 0xff; - const lineIdx = new GrowBuffer((n) => new Uint32Array(n)); - - // LOKALER URSPRUNG dieser Geometrie: alle Vertices werden relativ zum ersten - // Punkt abgelegt, der Renderer zieht den Ursprung beim Zeichnen in doppelter - // Genauigkeit von der Ansicht ab (s. glPlanRender.ts). Hintergrund: Vertices - // sind float32; bei Landeskoordinaten (~2,7 Mio. m × 90 px/m = 2,4·10⁸) beträgt - // die Auflösung dort ~16 Einheiten → Linien sprangen/verzerrten beim - // Hineinzoomen ("Ansicht bugt"). Relativ zu einem Punkt im Chunk bleiben die - // Werte klein, auch wenn die Zeichnung weit vom Nullpunkt liegt. - let originX = 0; - let originY = 0; - let originSet = false; - const scr = (p: Vec2): Vec2 => { - const s = toScreen(p); - if (!originSet) { - originX = s.x; - originY = s.y; - originSet = true; - } - return { x: s.x - originX, y: s.y - originY }; - }; + for (let i = 0; i < nFill; i++, k += 6) { + fillBatches.push({ + startIndex: meta[k], + indexCount: meta[k + 1], + color: [meta[k + 2], meta[k + 3], meta[k + 4], meta[k + 5]] as Rgba, + }); + } const lineBatches: GpuGeometry['line']['batches'] = []; - - let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; - const track = (mx: number, my: number) => { - if (mx < minX) minX = mx; - if (my < minY) minY = my; - if (mx > maxX) maxX = mx; - if (my > maxY) maxY = my; - }; - - const sameRgba = (a: Rgba, b: Rgba): boolean => - a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3]; - - // Ordnungserhaltendes Batch-Merging: aufeinanderfolgende Indizes gleicher Farbe - // (+ Breite bei Linien) werden zu EINEM Draw-Call zusammengefasst (Reihenfolge - // bleibt exakt → korrekte Z-/Alpha-Überlagerung, nur viel weniger State-Wechsel). - const addFillBatch = (count: number, color: Rgba) => { - const last = fillBatches[fillBatches.length - 1]; - if (last && sameRgba(last.color, color)) last.indexCount += count; - else fillBatches.push({ startIndex: fillIdx.length - count, indexCount: count, color }); - }; - const addLineBatch = (count: number, color: Rgba, strokeMm: number, screenPx: boolean) => { - const last = lineBatches[lineBatches.length - 1]; - if (last && last.strokeMm === strokeMm && !!last.screenPx === screenPx && sameRgba(last.color, color)) - last.indexCount += count; - else - lineBatches.push({ - startIndex: lineIdx.length - count, - indexCount: count, - color, - strokeMm, - screenPx, - }); - }; - - /** - * Zeichnet einen zusammenhängenden Linienzug (Bildschirm-Raum) mit ECHTEN - * RUNDEN Kappen/Ecken (wie SVG `stroke-linecap/linejoin: round` und der - * Vektor-PDF-Pfad) statt eckigem Butt-Cap/Gehrung: - * • jedes Segment ist ein eigenständiges Quad mit BUTT-Enden (eigene - * Segment-Normale, keine Miter-Verlängerung); - * • an jedem inneren Stützpunkt füllt ein Dreiecksfächer (Radius = halbe - * Strichbreite) die Außenseite der Ecke rund auf (Innenseite überlappt - * unsichtbar, wie bei jedem Disjoint-Segment-Liniendicken-Ansatz); - * • an offenen Enden (nicht `closed`) sitzt ein Halbkreis-Fächer als runde - * Kappe. - * Die tatsächliche Pixel-Breite bleibt bildschirmkonstant: alle Fächer-/Quad- - * Vertices tragen nur eine EINHEITS-Richtung (`normal`) + `side`-Skalar; der - * Vertex-Shader multipliziert im Clip-Raum mit der aktuellen Strichbreite - * (`strokePx*strokeScale`) — die Tessellierung selbst kennt keine Pixelmasse. - * `closed` schließt den Ring (letzter↔erster Punkt). Vertex-Layout unverändert: - * [x,y, bx,by, side, miter] (miter bleibt hier immer 1, s. Shader-Vertrag). - */ - const strokePolyline = ( - ptsM: Vec2[], - closed: boolean, - color: Rgba, - strokeMm: number, - screenPx = false, - ) => { - // Auf Bildschirm-Raum abbilden + aufeinanderfolgende Duplikate entfernen. - const S: Vec2[] = []; - for (const p of ptsM) { - const s = scr(p); - if (S.length && Math.abs(S[S.length - 1].x - s.x) < 1e-6 && Math.abs(S[S.length - 1].y - s.y) < 1e-6) - continue; - S.push(s); - track(p.x, p.y); - } - if (closed && S.length > 1) { - const f = S[0], l = S[S.length - 1]; - if (Math.abs(f.x - l.x) < 1e-6 && Math.abs(f.y - l.y) < 1e-6) S.pop(); - } - const k = S.length; - if (k < 2) return; - - const dir = (from: Vec2, to: Vec2): Vec2 | null => { - const dx = to.x - from.x, dy = to.y - from.y; - const len = Math.hypot(dx, dy); - return len < 1e-9 ? null : { x: dx / len, y: dy / len }; - }; - const leftNormal = (d: Vec2): Vec2 => ({ x: -d.y, y: d.x }); - - const startIdxLen = lineIdx.length; - const vBase = packedLines ? lineVertsPacked.length / 3 : lineVerts.length / 6; - let vcount = 0; - const pushVert = (p: Vec2, nx: number, ny: number, side: number): number => { - if (packedLines) { - lineVertsPacked.push3( - f2u(p.x), - f2u(p.y), - (snorm8(nx) | (snorm8(ny) << 8) | (snorm8(side) << 16) | (127 << 24)) >>> 0, - ); - } else { - lineVerts.push6(p.x, p.y, nx, ny, side, 1); - } - vcount++; - return vBase + vcount - 1; - }; - - const segs = closed ? k : k - 1; - const segDir: (Vec2 | null)[] = []; - for (let i = 0; i < segs; i++) segDir.push(dir(S[i], S[(i + 1) % k])); - - // Segment-Quads: butt-endig, jedes mit seiner EIGENEN Normale (kein - // gemeinsamer Bisektor mehr — Ecken werden separat durch Fächer geschlossen). - for (let i = 0; i < segs; i++) { - const d = segDir[i]; - if (!d) continue; // entartetes (Länge-0) Segment - const n = leftNormal(d); - const a = S[i], b = S[(i + 1) % k]; - const i0 = pushVert(a, n.x, n.y, +1); - const i1 = pushVert(a, n.x, n.y, -1); - const i2 = pushVert(b, n.x, n.y, +1); - const i3 = pushVert(b, n.x, n.y, -1); - lineIdx.push6(i0, i1, i2, i1, i3, i2); - } - - // Kreisbogen-Fächer (Zentrum = Vertex, Radius = halbe Strichbreite, per - // Shader skaliert): `side=0` am Zentrum (kein Versatz), `side=1` an den - // Randpunkten (voller Versatz in Richtung (cosθ,sinθ)). - const addFanArc = (p: Vec2, aFrom: number, aTo: number) => { - const delta = aTo - aFrom; - // Dünne Striche (≤ 0.35 mm, nur wenige Pixel breit): grobe Rundung genügt - // und spart ~3× Vertices je Kappe/Ecke (Speicher bei Kataster-Importen). - const stepAngle = strokeMm <= 0.35 ? Math.PI / 3 : Math.PI / 10; - const steps = Math.max(1, Math.ceil(Math.abs(delta) / stepAngle)); - const iCenter = pushVert(p, 1, 0, 0); - let prev = pushVert(p, Math.cos(aFrom), Math.sin(aFrom), 1); - for (let s = 1; s <= steps; s++) { - const t = aFrom + (delta * s) / steps; - const cur = pushVert(p, Math.cos(t), Math.sin(t), 1); - lineIdx.push3(iCenter, prev, cur); - prev = cur; - } - }; - - // Runder Join an einem inneren Stützpunkt: Fächer NUR auf der konvexen - // (äußeren) Seite der Ecke — die konkave Seite überlappt bereits durch die - // beiden Segment-Quads (kein Loch, keine zusätzliche Geometrie nötig). - const addRoundJoin = (p: Vec2, d1: Vec2, d2: Vec2) => { - const turn = d1.x * d2.y - d1.y * d2.x; - const dot = d1.x * d2.x + d1.y * d2.y; - if (Math.abs(turn) < 1e-6 && dot > 0) return; // praktisch gerade - const n1 = leftNormal(d1), n2 = leftNormal(d2); - if (dot < -0.9999) { - // ~180°-Umkehr: Außenseite mehrdeutig → voller Kreis (robust, entspricht - // zwei gestapelten Rund-Kappen an derselben Stelle). - const a0 = Math.atan2(n1.y, n1.x); - addFanArc(p, a0, a0 + 2 * Math.PI); - return; - } - const outer = turn > 0 ? -1 : 1; - const u1 = { x: outer * n1.x, y: outer * n1.y }; - const u2 = { x: outer * n2.x, y: outer * n2.y }; - const a1 = Math.atan2(u1.y, u1.x); - let a2 = Math.atan2(u2.y, u2.x); - let delta = a2 - a1; - while (delta <= -Math.PI) delta += 2 * Math.PI; - while (delta > Math.PI) delta -= 2 * Math.PI; - if (Math.abs(delta) < 1e-4) return; - addFanArc(p, a1, a1 + delta); - }; - - // Runde Kappe an einem offenen Ende: Halbkreis, der auf der Außenseite - // (weg von der Linie) bulgt. - const addRoundCap = (p: Vec2, n: Vec2, sweepSign: 1 | -1) => { - const a0 = Math.atan2(n.y, n.x); - addFanArc(p, a0, a0 + sweepSign * Math.PI); - }; - - for (let v = 0; v < k; v++) { - const hasIn = closed || v > 0; - const hasOut = closed || v < k - 1; - const dIn = hasIn ? segDir[(v - 1 + segs) % segs] : null; - const dOut = hasOut ? segDir[v % segs] : null; - if (dIn && dOut) { - addRoundJoin(S[v], dIn, dOut); - } else if (dOut && !dIn) { - // Start-Kappe: bulgt rückwärts (weg vom ersten Segment). - addRoundCap(S[v], leftNormal(dOut), 1); - } else if (dIn && !dOut) { - // End-Kappe: bulgt vorwärts (weg vom letzten Segment). - addRoundCap(S[v], leftNormal(dIn), -1); - } - } - - addLineBatch(lineIdx.length - startIdxLen, color, strokeMm, screenPx); - }; - - /** Einzelnes Segment als (ungehrter, rund gekapptes) 2-Punkt-Zug. */ - const pushLine = (aM: Vec2, bM: Vec2, color: Rgba, strokeMm: number) => - strokePolyline([aM, bM], false, color, strokeMm); - - /** - * Strichelt den Umriss eines Polygons, wobei die Kanten in `noStroke` - * ÜBERSPRUNGEN werden (Kante `i` = pts[i]→pts[i+1]). Die Füllung bleibt das - * volle Polygon; nur innere Gehrungs-Stirnkanten am Wandknoten entfallen. Die - * sichtbaren Kanten werden als zusammenhängende OFFENE Züge gestrichelt → an - * den weggelassenen Kanten laufen die Enden gerade aus (keine Gehrung über die - * Naht = keine überschießende Barbe). Leeres `noStroke` ⇒ geschlossener, - * gehrter Umriss wie bisher. - */ - const strokePolygonOutline = ( - ptsM: Vec2[], - color: Rgba, - strokeMm: number, - noStroke: number[] | undefined, - ) => { - const n = ptsM.length; - if (!noStroke || noStroke.length === 0 || n < 2) { - strokePolyline(ptsM, true, color, strokeMm); - return; - } - const skip = new Set(noStroke.map((i) => ((i % n) + n) % n)); - if (skip.size >= n) return; // alle Kanten unterdrückt → nichts zeichnen - // Sichtbare Kanten zu zusammenhängenden Läufen bündeln; ein Lauf beginnt an - // einer sichtbaren Kante, deren Vorgänger übersprungen ist. - const visible = (i: number) => !skip.has(((i % n) + n) % n); - for (let s = 0; s < n; s++) { - if (!visible(s) || visible(s - 1 + n)) continue; // kein Lauf-Anfang - const run: Vec2[] = [ptsM[s]]; - let j = s; - while (visible(j)) { - run.push(ptsM[(j + 1) % n]); - j++; - if (j - s >= n) break; // voller Umlauf (kann bei skip.size≥1 nicht sein) - } - strokePolyline(run, false, color, strokeMm); - } - }; - - // Zusammenhängende, gleich gestylte 'line'-Primitive (typischerweise die - // EINZELNEN Segmente einer importierten Polylinie/Kontur — s. `seg()` in - // `generatePlan/drawing2d.ts`, das pro Punktpaar ein eigenes 'line'-Primitiv - // erzeugt) werden hier VOR dem Stricheln zu EINEM zusammenhängenden Zug - // zusammengefasst. Grund: `strokePolyline` setzt an jedem OFFENEN Ende einen - // vollen Rundkappen-Fächer (`addRoundCap`, s. u.); bei N unabhängigen - // 2-Punkt-Segmenten macht das aus einer durchgehenden Kontur 2N teure - // Kappen statt der 2 echten Enden + (N-1) günstigerer Rund-ÜBERGÄNGE - // (`addRoundJoin`, nur auf der Aussenseite). Bei einem Kataster-Import mit - // Millionen solcher Segmente (reproduziert mit der echten 439-MB-Luzerner- - // Datei: 69'107 Konturen, Ø ~53 Punkte → 3,68 Mio. 'line'-Primitive) hat das - // den Linien-Vertexpuffer bis zur `RangeError: Invalid array length` - // aufgebläht. NUR eine Rendering-Optimierung — `primitives[i]` bleibt für - // Auswahl/Hit-Testing (PlanView.tsx indiziert direkt in `plan.primitives`) - // unverändert einzeln adressierbar; am Primitiv-Modell ändert sich nichts, - // nur daran, wie die GPU-Geometrie daraus kompiliert wird. - const mergedLineRun = new Set(); - { - let i = 0; - while (i < primitives.length) { - const p0 = primitives[i]; - if (p0.kind !== 'line' || p0.zigzag || p0.motif) { - i++; - continue; - } - const pts: Vec2[] = [p0.a, p0.b]; - let j = i + 1; - while (j < primitives.length) { - const pj = primitives[j]; - if ( - pj.kind !== 'line' || - pj.zigzag || - pj.motif || - // `drawingId` MUSS übereinstimmen: ohne das verketten sich sonst - // ZWEI VERSCHIEDENE (gleich gestylte) Drawing2D-Elemente, die - // zufällig einen Eckpunkt teilen (bei Kataster-Daten der Normalfall - // — Nachbarparzellen teilen Grenzpunkte) zu EINEM künstlichen, - // potenziell riesigen Polylinienzug — genau das hat beim echten - // Luzerner Import einen einzelnen `strokePolyline`-Aufruf auf - // Milliarden Vertices aufgebläht (`RangeError: Invalid array - // length`, reproduziert). - pj.drawingId !== p0.drawingId || - pj.color !== p0.color || - pj.weightMm !== p0.weightMm || - pj.greyed !== p0.greyed || - pj.opacity !== p0.opacity || - pj.dash !== p0.dash || - pj.a.x !== pts[pts.length - 1].x || - pj.a.y !== pts[pts.length - 1].y - ) { - break; - } - pts.push(pj.b); - j++; - } - if (j - i > 1) { - const color = dim(parseColor(p0.color) ?? [0.1, 0.1, 0.1, 1], p0.greyed, p0.opacity); - strokePolyline(pts, false, color, p0.weightMm || 0.18); - for (let k = i; k < j; k++) mergedLineRun.add(k); - } - i = j; - } + for (let i = 0; i < nLine; i++, k += 8) { + lineBatches.push({ + startIndex: meta[k], + indexCount: meta[k + 1], + color: [meta[k + 2], meta[k + 3], meta[k + 4], meta[k + 5]] as Rgba, + strokeMm: meta[k + 6], + screenPx: meta[k + 7] === 1, + }); } + let off = out.byteOffset + 8 + m * 8; + const fillPos = new Float32Array(out.buffer, off, nFillPos); + off += nFillPos * 4; + const fillIdx = new Uint32Array(out.buffer, off, nFillIdx); + off += nFillIdx * 4; + // Gepackte Linien-Vertices sind Wörter, ungepackte f32 — die Bytes sind dieselben. + const lineVerts = new Uint32Array(out.buffer, off, nLineVerts); + off += nLineVerts * 4; + const lineIdx = new Uint32Array(out.buffer, off, nLineIdx); - for (let primIdx = 0; primIdx < primitives.length; primIdx++) { - const prim = primitives[primIdx]; - if (mergedLineRun.has(primIdx)) continue; - if (prim.kind === 'polygon') { - // Füllung (falls vorhanden). - const fill = parseColor(prim.fill); - if (fill) { - const tris = triangulate(prim.pts); - if (tris.length) { - const base = fillPos.length / 2; - for (const pt of prim.pts) { - const s = scr(pt); - fillPos.push2(s.x, s.y); - track(pt.x, pt.y); - } - for (const t of tris) fillIdx.push1(base + t); - addFillBatch(tris.length, dimFill(fill, prim.greyed, prim.opacity)); - } - } - // Schraffur (nach der Füllung, vor/passend zum Umriss — wie der SVG stapelt): - // das Muster wird in echte Linien-Geometrie (Modell-Meter) tesselliert und - // aufs Polygon geclippt (konkav-fähig, even-odd). Musterlinien fließen als - // zusammenhängende Läufe in `strokePolyline` → glatte, RUND gekappte/ - // -verbundene Übergänge (insb. die Dämmungswelle bleibt spitzenfrei). - // BREITE — die Schraffur ist jetzt ein GEWÖHNLICHER Papier-mm-Stift, mit - // derselben LineStyle-Stärke (0.02 mm) wie die Wand-Schichtfugen, und - // läuft durch dieselbe STANDARD-Pipeline wie jede andere Linie - // (screenPx=false). `paperScaleForGl` liefert im Bildschirm-/Haarlinien- - // Modus den reziproken `meet`-Massstab, wodurch `mmToDevicePx` dort - // zoomunabhängig konstant bleibt — die Schraffur erscheint als konstante - // Haarlinie wie jede Wandlinie, und im Druckmodus als echte 0.02 mm, - // deckungsgleich mit den Schichtfugen in beiden Modi. - // `hatch.dash` wird geometrisch (Strich/Lücke) aufgelöst, da die GL- - // Linien-Pipeline kein Dash kennt. - // Bild-/Verlauf-Schraffur (kind==="image"/"gradient"): WebGL2-Ebene kennt - // weder Muster-Textur noch echten Farbverlauf → FALLBACK auf die neutrale - // Poché-Füllung (oben), keine Musterlinien. Der Random-Untermodus läuft - // transparent über `buildHatchRuns` (Streu-Striche). - if ( - prim.hatch && - prim.hatch.kind !== 'image' && - prim.hatch.kind !== 'gradient' && - prim.hatch.pattern !== 'none' && - prim.hatch.pattern !== 'solid' - ) { - const hatchColor = dim(parseColor(prim.hatch.color) ?? [0.1, 0.1, 0.1, 1], prim.greyed, prim.opacity); - const hatchMm = prim.hatch.lineWeight > 0 ? prim.hatch.lineWeight : 0.13; - const runs = applyDashRuns(buildHatchRuns(prim.pts, prim.hatch), prim.hatch.dash); - for (const run of runs) strokePolyline(run, false, hatchColor, hatchMm, false); - } - // Umriss (crispe Kante) — geschlossener Ring, GEHRT (kein Stufen-Cap an - // Ecken). Breite = ECHTE Papier-mm; der Renderer rechnet massstabs-/ - // zoomrichtig in px (wie SVG-printStrokeVb → GL == SVG). - const stroke = parseColor(prim.stroke); - if (stroke && prim.strokeWidthMm > 0 && prim.pts.length >= 2) { - strokePolygonOutline(prim.pts, dim(stroke, prim.greyed, prim.opacity), prim.strokeWidthMm, prim.noStrokeEdges); - } - } else if (prim.kind === 'line') { - const color = dim(parseColor(prim.color) ?? [0.1, 0.1, 0.1, 1], prim.greyed, prim.opacity); - if (prim.zigzag) { - // Zickzack-Linie → gehrter Polylinienzug (amplitude/wavelength Papier-mm - // → Modell-Meter über dieselbe Kopplung wie Strichmuster). - const amp = prim.zigzag.amplitude * DASH_MM_TO_M; - const wav = prim.zigzag.wavelength * DASH_MM_TO_M; - const zpts = zigzagPoints(prim.a, prim.b, amp, wav); - strokePolyline(zpts, false, color, prim.weightMm || 0.18); - } else if (prim.motif) { - // Custom-Motiv → gehrter Polylinienzug (Papier-mm → Modell-Meter, wie Zickzack). - const mpts = motifPoints(prim.a, prim.b, prim.motif, DASH_MM_TO_M); - strokePolyline(mpts, false, color, prim.weightMm || 0.18); - } else { - pushLine(prim.a, prim.b, color, prim.weightMm || 0.18); - } - } else if (prim.kind === 'arc') { - // Bogen → ein gehrter Polylinienzug (glatt, keine Segment-Stufen). - const color = dim( - parseColor((prim as { color?: string }).color) ?? [0.1, 0.1, 0.1, 1], - prim.greyed, - prim.opacity, - ); - const strokeMm = prim.weightMm || 0.18; - const c = prim.center; - const a0 = Math.atan2(prim.from.y - c.y, prim.from.x - c.x); - const a1 = Math.atan2(prim.to.y - c.y, prim.to.x - c.x); - // Kürzeste Drehrichtung (Delta nach (-π, π]). - let d = a1 - a0; - while (d <= -Math.PI) d += 2 * Math.PI; - while (d > Math.PI) d -= 2 * Math.PI; - // Bildschirm-adaptive Tessellierung (LOD): der Bogen-Radius in Geräte-px - // ist rPx = r · pxPerMeter. Der Segment-Winkel θ wird so gewählt, dass die - // Sagitta (Sehnen-Ausbauchung) rPx·(1−cos(θ/2)) unter ~0.5 px bleibt → - // θ = 2·acos(1 − 0.5/rPx). Weit weg (kleiner rPx) = wenige Segmente (billig, - // Facetten unsichtbar); hineingezoomt = viele Segmente = runder Bogen — wie - // im CAD. Geklammert auf [8, 2048]. pxPerMeter=0 → fixer Rückfall (16/90°). - // Der Aufrufer (PlanView) re-tesselliert nur bei LOD-Bucket-Wechseln, nicht - // je Frame; Pan/Zoom bleibt reines Matrix-Update. - let segs: number; - if (pxPerMeter > 0) { - const rPx = prim.r * pxPerMeter; - // Für sehr kleine rPx ist 0.5/rPx ≥ 1 (kein realer acos) → Minimum greift. - const theta = rPx > 0.5 ? 2 * Math.acos(1 - 0.5 / rPx) : Math.PI; - segs = Math.min(2048, Math.max(8, Math.ceil(Math.abs(d) / theta))); - } else { - segs = Math.max(4, Math.ceil((Math.abs(d) / (Math.PI / 2)) * 16)); - } - const arcPts: Vec2[] = [prim.from]; - for (let i = 1; i <= segs; i++) { - const t = a0 + (d * i) / segs; - arcPts.push({ x: c.x + prim.r * Math.cos(t), y: c.y + prim.r * Math.sin(t) }); - } - strokePolyline(arcPts, false, color, strokeMm); - } else if (prim.kind === 'drawingCircle' || prim.kind === 'drawingArc') { - // 2D-Zeichnungs-Kreis/-Bogen (Kreis-/Bogen-Werkzeug ODER DXF-Import). Der - // SVG-Pfad zeichnet sie als glattes /; die WebGL-Ebene kennt - // kein Kreis-Primitiv → hier bildschirm-adaptiv tessellieren (wie 'arc'). - // Kreis = voller Umlauf (geschlossen, optional gefüllt), Bogen = a0..a1 (CCW, - // offen). OHNE diesen Zweig blieben gezeichnete Kreise/Bögen im GL unsichtbar. - const stroke = dim(parseColor(prim.stroke) ?? [0.1, 0.1, 0.1, 1], prim.greyed, prim.opacity); - const strokeMm = prim.weightMm || 0.18; - const c = prim.center; - const TAU = Math.PI * 2; - const a0 = prim.kind === 'drawingArc' ? prim.a0 : 0; - const sweep = - prim.kind === 'drawingArc' - ? ((prim.a1 - prim.a0) % TAU + TAU) % TAU || TAU - : TAU; - // Segmentzahl wie im 'arc'-Zweig: Sagitta < ~0.5 px (LOD über pxPerMeter). - let segs: number; - if (pxPerMeter > 0) { - const rPx = prim.r * pxPerMeter; - const theta = rPx > 0.5 ? 2 * Math.acos(1 - 0.5 / rPx) : Math.PI; - segs = Math.min(2048, Math.max(8, Math.ceil(sweep / theta))); - } else { - segs = Math.max(8, Math.ceil((sweep / (Math.PI / 2)) * 16)); - } - const pts: Vec2[] = []; - for (let i = 0; i <= segs; i++) { - const t = a0 + (sweep * i) / segs; - pts.push({ x: c.x + prim.r * Math.cos(t), y: c.y + prim.r * Math.sin(t) }); - } - // Vollton-Füllung nur beim geschlossenen Kreis (Bogen ist offen). - if (prim.kind === 'drawingCircle') { - const fill = parseColor(prim.fill); - if (fill) { - const ring = pts.slice(0, segs); // ohne den doppelten Schlusspunkt - const tris = triangulate(ring); - if (tris.length) { - const base = fillPos.length / 2; - for (const pt of ring) { - const s = scr(pt); - fillPos.push2(s.x, s.y); - track(pt.x, pt.y); - } - for (const t of tris) fillIdx.push1(base + t); - addFillBatch(tris.length, dimFill(fill, prim.greyed, prim.opacity)); - } - } - } - strokePolyline(pts, prim.kind === 'drawingCircle', stroke, strokeMm); - } - // Text: bleibt im SVG-Overlay (scharfe Schrift, DOM-Hit-Test). - } - - // Puffer hochladen. - const uploadArray = (data: GrowBuffer | GrowBuffer): WebGLBuffer | null => { + const upload = (target: number, data: ArrayBufferView & { length: number }): WebGLBuffer | null => { if (!data.length) return null; const buf = gl.createBuffer(); if (!buf) return null; - gl.bindBuffer(gl.ARRAY_BUFFER, buf); - gl.bufferData(gl.ARRAY_BUFFER, data.view(), gl.STATIC_DRAW); + gl.bindBuffer(target, buf); + gl.bufferData(target, data, gl.STATIC_DRAW); return buf; }; - const uploadIndex = (data: GrowBuffer): WebGLBuffer | null => { - if (!data.length) return null; - const buf = gl.createBuffer(); - if (!buf) return null; - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buf); - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data.view(), gl.STATIC_DRAW); - return buf; - }; - return { fill: { - positionBuffer: uploadArray(fillPos), - indexBuffer: uploadIndex(fillIdx), + positionBuffer: upload(gl.ARRAY_BUFFER, fillPos), + indexBuffer: upload(gl.ELEMENT_ARRAY_BUFFER, fillIdx), batches: fillBatches, }, line: { - vertexBuffer: uploadArray(packedLines ? lineVertsPacked : lineVerts), - indexBuffer: uploadIndex(lineIdx), + vertexBuffer: upload(gl.ARRAY_BUFFER, gl.packedLineVertices === true ? lineVerts : new Float32Array(lineVerts.buffer, lineVerts.byteOffset, lineVerts.length)), + indexBuffer: upload(gl.ELEMENT_ARRAY_BUFFER, lineIdx), batches: lineBatches, }, origin: { x: originX, y: originY }, diff --git a/src/plan/glPlan/glPlanHatch.ts b/src/plan/glPlan/glPlanHatch.ts index e173338c..cc5f7f93 100644 --- a/src/plan/glPlan/glPlanHatch.ts +++ b/src/plan/glPlan/glPlanHatch.ts @@ -1,33 +1,23 @@ /** - * Schraffur-Tessellierung für den GPU-Grundriss: wandelt ein Polygon mit - * aufgelöster {@link HatchRender} in eine Schar echter Linien-Segmente (Modell- - * Meter), die anschließend über `strokePolyline`/`pushLine` in die Linien-Puffer - * fließen. Damit rendert die GPU-Ebene dieselben Muster wie der SVG-``- - * Renderer, nur als tessellierte Geometrie statt als Kachel-Füllung. + * Schraffur- und Linienmuster-Geometrie des Grundrisses — Fassade über den Rust-Kern ([K3b], + * `src-tauri/core/src/hatch.rs`). Wandelt ein Polygon mit aufgelöster {@link HatchRender} in eine + * Schar echter Linienzüge (Modell-Meter), die die GPU-Kompilierung, `toRenderScene`, der Druck- + * SVG- und der DXF-Export zeichnen; dazu Strichmuster, Zickzack und Motiv-Kachelung. * - * KOORDINATEN & MASSSTAB (muss deckungsgleich zum SVG sein): - * • Der SVG-`` ist in BILDSCHIRM-Raum (viewBox-px, `sx = mx·PX_PER_M`) - * definiert; Kachelgröße = `8·scale` px (diagonal/cross) bzw. `14×10·scale` px - * (insulation), gedreht per `rotate(angle)` (im Uhrzeigersinn, Bildschirm-Y - * nach unten). Die Muster-GEOMETRIE skaliert also mit dem Zoom (Papier). - * • Wir erzeugen die Muster direkt in MODELL-Metern: ein px in Bildschirm-Raum - * entspricht `1/PX_PER_M` m. So passen Abstand/Winkel exakt zum SVG, und die - * Segmente lassen sich unverändert an `strokePolyline` (Papier-mm-Breite) - * übergeben. - * • Die STRICHBREITE bleibt in Papier-mm (`hatch.lineWeight`) — genau wie beim - * SVG-Muster, das `hatchStrokePx(lineWeight)` als non-scaling-artige Breite - * zeichnet. + * KOORDINATEN & MASSSTAB (deckungsgleich zum SVG-``): die Muster entstehen direkt in + * Modell-Metern (1 px Bildschirm-Raum = 1/90 m), Kachel 8·scale px (diagonal/kreuz) bzw. + * 14×10·scale px (Dämmung), Raster-Anker = Modellursprung bzw. `hatch.origin`. Strichstärken + * bleiben Papier-mm. */ import type { Vec2 } from '../../model/types'; import type { HatchRender } from '../generatePlan'; +import { encodeHatch } from '../planBuf'; +import { core } from '../../engine/coreWasm'; /** Bildschirm-Einheiten (viewBox-px) je Meter — identisch zu PlanView.toScreen. */ const PX_PER_M = 90; -/** px (Bildschirm-Raum) → Meter (Modell-Raum). */ -const PX_TO_M = 1 / PX_PER_M; - /** Ein Linien-Segment in Modell-Metern. */ export interface HatchSegment { a: Vec2; @@ -35,553 +25,128 @@ export interface HatchSegment { } /** - * Ein zusammenhängender Linienzug in Modell-Metern (≥2 Punkte). Gerade - * Musterlinien (diagonal/crosshatch) sind 2-Punkt-Läufe; die Dämmungs-Welle ist - * ein langer, an den Polygonkanten geclippter Lauf. Läufe fließen als EIN gehrter - * Streifen in `strokePolyline` → glatte Übergänge statt Butt-Cap-Stufen. + * Ein zusammenhängender Linienzug in Modell-Metern (≥2 Punkte). Gerade Musterlinien sind + * 2-Punkt-Läufe; die Dämmungs-Welle ist ein langer, an den Polygonkanten geclippter Lauf. */ export type HatchRun = Vec2[]; /** - * Achsen-ausgerichtetes Bounding-Rechteck eines Polygons (Modell-Meter). - * Leeres Polygon → degeneriert (min>max), der Aufrufer erzeugt dann keine Linien. + * Faktor mm-Papier → Modell-Meter des Musterraums, identisch zum SVG-`dashArray` (dort + * `dash·(1/0.13)` px). */ -function bbox(poly: Vec2[]): { minX: number; minY: number; maxX: number; maxY: number } { - let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; - for (const p of poly) { - if (p.x < minX) minX = p.x; - if (p.y < minY) minY = p.y; - if (p.x > maxX) maxX = p.x; - if (p.y > maxY) maxY = p.y; +export const DASH_MM_TO_M = (1 / 0.13) * (1 / PX_PER_M); + +function flat(pts: readonly Vec2[]): Float64Array { + const out = new Float64Array(pts.length * 2); + for (let i = 0; i < pts.length; i++) { + out[2 * i] = pts[i].x; + out[2 * i + 1] = pts[i].y; } - return { minX, minY, maxX, maxY }; + return out; } -/** - * Schneidet eine UNENDLICHE Linie (Aufpunkt `p0`, Einheits-Richtung `dir`) mit - * einem einfachen (auch KONKAVEN) Polygon und liefert die INNERHALB liegenden - * Segmente. Vorgehen (robustes Even-Odd-Scanline-Prinzip): - * 1. Für jede Polygon-Kante den Schnitt-Parameter `t` (entlang `dir`) berechnen, - * bei dem die Linie die Kante quert. - * 2. Alle `t` sortieren; aufeinanderfolgende Paare (t0,t1),(t2,t3),… liegen im - * Inneren (even-odd) → als Segmente zurückgeben. - * Das ist für beliebige konkave Polygone korrekt, weil eine Gerade ein einfaches - * Polygon stets in eine gerade Anzahl Kanten schneidet und die Innen-Intervalle - * sich mit jeder Kreuzung ein-/ausschalten. - * - * Robustheit an Ecken: Ein Schnitt wird nur gezählt, wenn die Linie die Kante - * ECHT quert (die beiden Endpunkte liegen auf verschiedenen Seiten). Berührungen - * genau am Eckpunkt werden über eine halb-offene Kanten-Konvention (das untere - * Kanten-Ende zählt, das obere nicht) vermieden, sodass keine doppelten oder - * fehlenden Kreuzungen entstehen. - */ -export function clipLineToPolygon(p0: Vec2, dir: Vec2, poly: Vec2[]): HatchSegment[] { - const n = poly.length; - if (n < 3) return []; - - // Senkrechte zur Richtung: side(p) = vorzeichenbehaftete Distanz zur Linie. - const nx = -dir.y; - const ny = dir.x; - const side = (p: Vec2) => (p.x - p0.x) * nx + (p.y - p0.y) * ny; - - const ts: number[] = []; - for (let i = 0; i < n; i++) { - const a = poly[i]; - const b = poly[(i + 1) % n]; - const sa = side(a); - const sb = side(b); - - // Beide echt auf derselben Seite → keine Kreuzung. - if (sa > 0 && sb > 0) continue; - if (sa < 0 && sb < 0) continue; - - // Halb-offene Konvention gegen Doppel-/Fehlzählung an Eckpunkten: - // • Kante liegt exakt AUF der Linie → ignorieren. - // • Berührung genau an einem Endpunkt (side==0) zählt nur, wenn der ANDERE - // Endpunkt echt oberhalb (>0) liegt. So gehört ein Eckpunkt eindeutig zur - // Kante darunter und wird genau EINMAL gezählt. - if (sa === 0 && sb === 0) continue; - if (sa === 0 && sb < 0) continue; - if (sb === 0 && sa < 0) continue; - - // Parameter `t` entlang `dir` am Schnittpunkt: Nullstelle von side auf der - // Kante interpolieren, dann auf `dir` projizieren. - const denom = sa - sb; - const u = denom !== 0 ? sa / denom : 0; // Anteil a→b bis side==0 - const ix = a.x + (b.x - a.x) * u; - const iy = a.y + (b.y - a.y) * u; - const t = (ix - p0.x) * dir.x + (iy - p0.y) * dir.y; - ts.push(t); - } - - if (ts.length < 2) return []; - ts.sort((x, y) => x - y); - - const segs: HatchSegment[] = []; - for (let i = 0; i + 1 < ts.length; i += 2) { - const t0 = ts[i]; - const t1 = ts[i + 1]; - if (t1 - t0 < 1e-9) continue; // entartetes Intervall (Tangente an Ecke) - segs.push({ - a: { x: p0.x + dir.x * t0, y: p0.y + dir.y * t0 }, - b: { x: p0.x + dir.x * t1, y: p0.y + dir.y * t1 }, - }); - } - return segs; +function toPts(f: Float64Array): Vec2[] { + const out: Vec2[] = new Array(f.length >> 1); + for (let i = 0; i < out.length; i++) out[i] = { x: f[2 * i], y: f[2 * i + 1] }; + return out; } -/** - * Schneidet ein ENDLICHES Segment [a,b] gegen ein (konkaves) Polygon und liefert - * die innenliegenden Teilstücke. Baut auf {@link clipLineToPolygon} auf: erst die - * Innen-Intervalle der Trägergeraden bestimmen, dann mit [a,b] (Parameterbereich - * [0,len]) verschneiden. - */ -export function clipSegmentToPolygon(a: Vec2, b: Vec2, poly: Vec2[]): HatchSegment[] { - const dx = b.x - a.x; - const dy = b.y - a.y; - const len = Math.hypot(dx, dy); - if (len < 1e-12) return []; - const dir: Vec2 = { x: dx / len, y: dy / len }; - const full = clipLineToPolygon(a, dir, poly); +function toSegs(f: Float64Array): HatchSegment[] { const out: HatchSegment[] = []; - for (const seg of full) { - // Parameter der Innen-Intervall-Enden entlang `dir` (ab Aufpunkt a). - const t0 = (seg.a.x - a.x) * dir.x + (seg.a.y - a.y) * dir.y; - const t1 = (seg.b.x - a.x) * dir.x + (seg.b.y - a.y) * dir.y; - const lo = Math.max(0, Math.min(t0, t1)); - const hi = Math.min(len, Math.max(t0, t1)); - if (hi - lo < 1e-9) continue; - out.push({ - a: { x: a.x + dir.x * lo, y: a.y + dir.y * lo }, - b: { x: a.x + dir.x * hi, y: a.y + dir.y * hi }, - }); + for (let i = 0; i + 3 < f.length; i += 4) out.push({ a: { x: f[i], y: f[i + 1] }, b: { x: f[i + 2], y: f[i + 3] } }); + return out; +} + +/** `[n, x, y, …, n, …]` → Läufe. */ +function toRuns(f: Float64Array): HatchRun[] { + const out: HatchRun[] = []; + let i = 0; + while (i < f.length) { + const n = f[i++]; + const run: Vec2[] = new Array(n); + for (let k = 0; k < n; k++, i += 2) run[k] = { x: f[i], y: f[i + 1] }; + out.push(run); + } + return out; +} + +function runsFlat(runs: readonly HatchRun[]): Float64Array { + let n = 0; + for (const r of runs) n += 1 + 2 * r.length; + const out = new Float64Array(n); + let i = 0; + for (const r of runs) { + out[i++] = r.length; + for (const p of r) { + out[i++] = p.x; + out[i++] = p.y; + } } return out; } /** - * Schneidet eine ZUSAMMENHÄNGENDE Polylinie `pts` gegen ein (auch KONKAVES) - * einfaches Polygon und liefert die innenliegenden Teile als CONTINUOUS runs - * (jeder Lauf = Vec2[] mit ≥2 Punkten). Anders als segmentweises Clippen bleiben - * aufeinanderfolgende Innen-Segmente in EINEM Lauf verbunden — die interne - * Tessellierung (z. B. Sinus-Stützpunkte) wird NICHT an jedem Vertex zerrissen. - * Nur ein echtes Austreten aus dem Polygon (bzw. eine Lücke) beginnt einen neuen - * Lauf. Nutzt dieselbe Even-Odd-/halb-offene-Kanten-Konvention wie - * {@link clipLineToPolygon} via {@link clipSegmentToPolygon}. - * - * Verfahren: jede Polylinien-Kante wird geclippt; die (in Laufrichtung - * sortierten) Innenstücke werden an den laufenden Lauf angehängt, solange ihr - * Anfang bündig ans bisherige Lauf-Ende anschließt. Sobald ein Innenstück nicht - * am Lauf-Ende beginnt (Wiedereintritt nach einem Austritt) oder die Kante gar - * kein Innenstück liefert (komplett außen), wird der Lauf abgeschlossen. + * Schneidet eine UNENDLICHE Linie (Aufpunkt `p0`, Einheits-Richtung `dir`) mit einem einfachen + * (auch konkaven) Polygon und liefert die innenliegenden Segmente (even-odd, halb-offene + * Kantenkonvention an Ecken). */ -export function clipPolylineToPolygon(pts: Vec2[], poly: Vec2[]): HatchRun[] { - if (pts.length < 2 || poly.length < 3) return []; - const EPS = 1e-9; - const near = (p: Vec2, q: Vec2) => Math.abs(p.x - q.x) < EPS && Math.abs(p.y - q.y) < EPS; +export function clipLineToPolygon(p0: Vec2, dir: Vec2, poly: Vec2[]): HatchSegment[] { + if (poly.length < 3) return []; + return toSegs(core().clip_line_to_polygon_flat(p0.x, p0.y, dir.x, dir.y, flat(poly))); +} - const runs: HatchRun[] = []; - let cur: HatchRun | null = null; - - const closeRun = () => { - if (cur && cur.length >= 2) runs.push(cur); - cur = null; - }; - - for (let i = 0; i + 1 < pts.length; i++) { - const a = pts[i]; - const b = pts[i + 1]; - // Innenstücke dieser Kante, in Laufrichtung a→b sortiert (clipSegment liefert - // sie bereits entlang der Trägergeraden geordnet; a→b ist die positive Richtung). - const pieces = clipSegmentToPolygon(a, b, poly); - for (const seg of pieces) { - // Kante in Laufrichtung orientieren (clipSegment kann a/b vertauschen). - const dx = b.x - a.x, dy = b.y - a.y; - const ta = (seg.a.x - a.x) * dx + (seg.a.y - a.y) * dy; - const tb = (seg.b.x - a.x) * dx + (seg.b.y - a.y) * dy; - const s = ta <= tb ? seg.a : seg.b; - const e = ta <= tb ? seg.b : seg.a; - - if (cur && near(cur[cur.length - 1], s)) { - // Nahtloser Anschluss ans Lauf-Ende → nur den neuen Endpunkt anhängen. - cur.push(e); - } else { - // Neuer Lauf (erster Innenteil oder Wiedereintritt nach Austritt). - closeRun(); - cur = [s, e]; - } - } - // Endete diese Kante NICHT genau am Polygonrand-Innenstück bis b (d. h. das - // letzte Innenstück reicht nicht bis zum Kantenende b), so tritt der Lauf hier - // aus dem Polygon → beim nächsten Innenteil beginnt ein neuer Lauf. - if (cur && !near(cur[cur.length - 1], b)) closeRun(); - } - closeRun(); - return runs; +/** Schneidet ein ENDLICHES Segment [a,b] gegen ein (konkaves) Polygon. */ +export function clipSegmentToPolygon(a: Vec2, b: Vec2, poly: Vec2[]): HatchSegment[] { + return toSegs(core().clip_segment_to_polygon_flat(a.x, a.y, b.x, b.y, flat(poly))); } /** - * Erzeugt eine Schar paralleler, aufs Polygon geclippter Linien-Segmente: - * Richtung `angleRad` (Modell-Raum, gegen den Uhrzeigersinn), Abstand `spacingM` - * (Meter) senkrecht zur Richtung, Phasen-Versatz `offsetM` (Meter, entlang der - * Normalen). Deckt das Polygon vollständig ab (über dessen projizierte Ausdehnung). + * Schneidet eine zusammenhängende Polylinie gegen ein (konkaves) Polygon; die Innenteile bleiben + * zusammenhängende Läufe (nur ein echtes Austreten beginnt einen neuen Lauf). + */ +export function clipPolylineToPolygon(pts: Vec2[], poly: Vec2[]): HatchRun[] { + if (pts.length < 2 || poly.length < 3) return []; + return toRuns(core().clip_polyline_to_polygon_flat(flat(pts), flat(poly))); +} + +/** + * Schar paralleler, aufs Polygon geclippter Linien: Richtung `angleRad` (Modell, CCW), Abstand + * `spacingM`, Phasen-Versatz `offsetM`, Raster-Anker `anchor` (Default Modellursprung — wie das + * SVG-`userSpaceOnUse`-Muster; ein Objekt verschiebt ihn über `Drawing2D.hatchOrigin`). */ export function hatchLineFamily( poly: Vec2[], angleRad: number, spacingM: number, offsetM = 0, - /** - * Ankerpunkt des Rasters. Default ist der MODELL-URSPRUNG (s. Kommentar - * unten); ein Objekt kann ihn über `Drawing2D.hatchOrigin` verschieben, - * um das Muster z. B. an einer Raumecke ansetzen zu lassen. - */ anchor: Vec2 = { x: 0, y: 0 }, ): HatchSegment[] { - if (poly.length < 3 || spacingM <= 1e-9) return []; - const bb = bbox(poly); - if (!(bb.maxX > bb.minX) && !(bb.maxY > bb.minY)) return []; - - const dir: Vec2 = { x: Math.cos(angleRad), y: Math.sin(angleRad) }; - const nrm: Vec2 = { x: -dir.y, y: dir.x }; // Linien-Normale (Scan-Richtung) - - // Rechtwinklige Projektion aller Ecken auf die Normale → Abdeckungsbereich. - // ANKER = MODELL-URSPRUNG (nicht die Polygon-Mitte): der SVG-`` ist - // `userSpaceOnUse`, sein Kachelgitter liegt global im viewBox-Raum fest - // (Ursprung (0,0) = Modell-Ursprung). Nur mit demselben Anker liegen die - // Musterlinien deckungsgleich zum SVG-Referenzpfad — und benachbarte Polygone - // teilen dieselbe Muster-Phase statt je eigener (bbox-abhängiger) Versätze. - const center: Vec2 = anchor; - let dMin = Infinity, dMax = -Infinity; - for (const p of poly) { - const d = (p.x - center.x) * nrm.x + (p.y - center.y) * nrm.y; - if (d < dMin) dMin = d; - if (d > dMax) dMax = d; - } - - const segs: HatchSegment[] = []; - // Raster so wählen, dass es den Bereich (inkl. Versatz) sicher deckt. - const first = Math.floor((dMin - offsetM) / spacingM) - 1; - const last = Math.ceil((dMax - offsetM) / spacingM) + 1; - for (let k = first; k <= last; k++) { - const d = offsetM + k * spacingM; - const p0: Vec2 = { x: center.x + nrm.x * d, y: center.y + nrm.y * d }; - for (const s of clipLineToPolygon(p0, dir, poly)) segs.push(s); - } - return segs; -} - -/** 2D-Vektor um `rad` drehen (gegen den Uhrzeigersinn, Modell-Konvention). */ -function rotate(v: Vec2, rad: number): Vec2 { - const c = Math.cos(rad), s = Math.sin(rad); - return { x: v.x * c - v.y * s, y: v.x * s + v.y * c }; + return toSegs(core().hatch_line_family_flat(flat(poly), angleRad, spacingM, offsetM, anchor.x, anchor.y)); } /** - * Faktor mm-Papier → px-Musterraum, identisch zum SVG-`dashArray` (dort - * `dash·(1/0.13)`). Ein 0.13-mm-Strich entspricht ~1 px Kachelmaß; dividiert man - * mit `PX_TO_M`, ergeben sich die Strichlängen in Modell-Metern (skalieren mit - * dem Zoom wie die Kachel selbst — genau wie die SVG-Schraffur). - */ -export const DASH_MM_TO_M = (1 / 0.13) * PX_TO_M; - -/** - * Zerlegt zusammenhängende Läufe entlang eines Strichmusters (`dash`, in mm- - * Papier) in die durchgezogenen Teil-Läufe. `dash` ist eine Sequenz - * [an, aus, an, …]; ungerade Längen werden (wie SVG/Canvas) verdoppelt. Leeres/ - * ungültiges Muster → Läufe unverändert (durchgezogen). Die Phase läuft ENTLANG - * DES GESAMTEN LAUFS durch (über Stützpunkt-Ecken hinweg), sodass die Striche - * einer gekrümmten Musterlinie (Dämmungswelle) gleichmäßig und ecken-übergreifend - * verteilt sind. Jedes „an"-Stück wird als eigener (kurzer) Lauf ausgegeben und - * kann selbst über mehrere Stützpunkt-Segmente reichen. + * Zerlegt zusammenhängende Läufe entlang eines Strichmusters (`dash` in mm-Papier, [an, aus, …]; + * ungerade Längen werden verdoppelt). Die Phase läuft über Stützpunkte hinweg durch. Leeres/ + * ungültiges Muster → Läufe unverändert. */ export function applyDashRuns(runs: HatchRun[], dash: number[] | null): HatchRun[] { if (!dash || dash.length === 0) return runs; - // Musterlängen in Meter; nicht-positive/ungültige Werte verwerfen. - const pat = dash.map((d) => Math.max(0, d) * DASH_MM_TO_M).filter((d) => d > 0); - if (pat.length === 0) return runs; - // Ungerade Länge → verdoppeln (Standard-Dash-Semantik). - const cycle = pat.length % 2 === 0 ? pat : pat.concat(pat); - const total = cycle.reduce((s, d) => s + d, 0); - if (total <= 1e-9) return runs; - - const out: HatchRun[] = []; - for (const run of runs) { - if (run.length < 2) continue; - // Bogenlänge je Stützpunkt vorab, um Dash-Positionen auf Segmente abzubilden. - let idx = 0; // gerade Index = „an", ungerade = „aus" - let dashLeft = cycle[0]; // verbleibende Länge im aktuellen Dash-Zustand - let on = true; - let piece: Vec2[] | null = [run[0]]; // aktuell offenes „an"-Stück - - const flush = () => { - if (piece && piece.length >= 2) out.push(piece); - piece = null; - }; - - for (let i = 0; i + 1 < run.length; i++) { - let a = run[i]; - const b = run[i + 1]; - let segLen = Math.hypot(b.x - a.x, b.y - a.y); - if (segLen < 1e-12) continue; - let ux = (b.x - a.x) / segLen, uy = (b.y - a.y) / segLen; - // Segment ggf. an Dash-Grenzen zerschneiden. - while (segLen > 1e-9) { - const step = Math.min(segLen, dashLeft); - const mid: Vec2 = { x: a.x + ux * step, y: a.y + uy * step }; - if (on) { - if (!piece) piece = [a]; - piece.push(mid); - } - // Vorrücken. - a = mid; - segLen -= step; - dashLeft -= step; - if (dashLeft <= 1e-9) { - // Dash-Zustand wechseln. - if (on) flush(); - on = !on; - idx++; - dashLeft = cycle[idx % cycle.length]; - if (on) piece = [a]; // neues „an"-Stück beginnt hier - } - } - } - flush(); - } - return out; + return toRuns(core().dash_runs_flat(runsFlat(runs), Float64Array.from(dash))); } /** - * SVG-`rotate(angleDeg)` (im Uhrzeigersinn, Bildschirm-Y nach unten) → Winkel im - * MODELL-Raum (gegen den Uhrzeigersinn, Modell-Y nach oben). Da die Bildschirm- - * Abbildung Y spiegelt (`sy=-my`), kehrt sich der Drehsinn um: eine im Bildschirm - * um +angle (CW) gedrehte Musterrichtung entspricht im Modell −angle relativ zur - * gewählten Basisrichtung. - */ -function toModelAngleRad(screenDeg: number): number { - return (-screenDeg * Math.PI) / 180; -} - -/** - * Baut die Schraffur eines Polygons als zusammenhängende Läufe ({@link HatchRun}, - * Modell-Meter). Bildet die SVG-``-Geometrie 1:1 nach: - * • diagonal — eine Schar; SVG-Kachel 8·scale px mit senkrechter Musterlinie - * (x-konstant), gedreht um `angle`. Abstand = 8·scale px. Jede - * Musterlinie ist ein gerader 2-Punkt-Lauf. - * • crosshatch — zwei Scharen (90° versetzt), gleicher Abstand. - * • insulation — weiche Wellenlinie, Kachel 14×10·scale px, gedreht um `angle`; - * als DURCHGEHENDE Polylinie tesselliert und in kontinuierliche - * Läufe geclippt (glatte gehrte Übergänge statt Butt-Cap-Stufen). - * • solid/none — keine Linien (Vollfüllung/Umriss übernimmt der Aufrufer). - * - * Skala 0/negativ wird auf 1 geklemmt (kein Division-durch-Null, keine leere - * Kachel), damit degeneriert konfigurierte Hatches trotzdem sichtbar bleiben. + * Schraffur eines Polygons als zusammenhängende Läufe (Modell-Meter): diagonal (eine Schar), + * crosshatch (zwei Scharen), insulation (Welle), custom (Motiv je Musterlinie), Random-Untermodus + * (gestreute Striche); solid/none sowie Bild/Verlauf liefern keine Linien-Geometrie des Musters. */ export function buildHatchRuns(poly: Vec2[], hatch: HatchRender): HatchRun[] { - if (poly.length < 3) return []; - const pattern = hatch.pattern; - if (pattern === 'none' || pattern === 'solid') return []; - - const scale = hatch.scale > 1e-6 ? hatch.scale : 1; - - // Random-Vektor-Untermodus (Kies/Splitt): kurze, deterministisch gestreute - // Striche statt der regelmäßigen Parallel-/Kreuzschar. Bild-/Verlauf- - // Schraffuren (kind==="image"/"gradient") werden hier NICHT als Vektorlinien - // erzeugt — sie fallen im Aufrufer auf eine neutrale Füllung zurück - // (RScene/GL kennen weder Textur noch echten Farbverlauf). - if (hatch.kind !== 'image' && hatch.kind !== 'gradient' && hatch.lines === 'random') { - return buildRandomHatchRuns(poly, hatch, scale); - } - - if (pattern === 'insulation') { - return insulationRuns(poly, hatch, scale); - } - - // diagonal / crosshatch: parallele Geradenscharen. - // Die SVG-Kachel ist 8·scale px; die Musterlinie läuft senkrecht (y-Achse der - // Kachel), Abstand also 8·scale px in x. In Metern: (8·scale)/PX_PER_M. - const spacingM = 8 * scale * PX_TO_M; - - // Kachel-Basisrichtung: die Linie läuft in der SVG-Kachel entlang +Y - // (Bildschirm, nach unten). Im Modell (Y gespiegelt) entspricht das (0,-1). - // Zusätzlich um `angle` (SVG-CW) gedreht → Modell-CCW um −angle. - const rot = toModelAngleRad(hatch.angle); - const dir1 = rotate({ x: 0, y: -1 }, rot); - const a1 = Math.atan2(dir1.y, dir1.x); - // Gerade Musterlinien → 2-Punkt-Läufe (visuell identisch zu Butt-Cap-Segmenten). - // „custom" mit gesetztem Motiv: jede Musterlinie wird per `motifPoints` entlang - // ihrer eigenen Länge tesselliert (Papier-mm → Modell-Meter über dieselbe - // Kopplung wie bei Linien-Motiven, DASH_MM_TO_M, zusätzlich mit `scale` - // verknüpft — konsistent zur Zeilenabstand-Formel oben). Ohne Motiv (frisch - // angelegter Hatch) fällt „custom" auf gerade Linien zurück (kein Absturz). - const anchor = hatch.origin ?? { x: 0, y: 0 }; - const runs: HatchRun[] = hatchLineFamily(poly, a1, spacingM, 0, anchor).map((s) => - pattern === 'custom' && hatch.motif - ? motifPoints(s.a, s.b, hatch.motif, scale * DASH_MM_TO_M) - : [s.a, s.b], - ); - - if (pattern === 'crosshatch') { - // Zweite Schar: die SVG-Kachel trägt zusätzlich eine horizontale Linie - // (x-Achse der Kachel) → 90° zur ersten, gleicher Abstand. - for (const s of hatchLineFamily(poly, a1 + Math.PI / 2, spacingM, 0, anchor)) runs.push([s.a, s.b]); - } - return runs; + if (poly.length < 3 || hatch.pattern === 'none' || hatch.pattern === 'solid') return []; + return toRuns(core().hatch_runs_flat(flat(poly), encodeHatch(hatch))); } /** - * Dämmungs-Schraffur (Wellenlinie): die SVG-Kachel ist 14×10·scale px und trägt - * pro Kachel eine weiche Bézier-Welle. Wir bilden sie als Scharwellen nach: eine - * Schar paralleler „Musterachsen" im Abstand der Kachelhöhe (10·scale px), auf - * jeder Achse eine tessellierte Sinuswelle mit Wellenlänge = Kachelbreite - * (14·scale px) und weicher Amplitude. Jede Wellen-Polylinie wird als - * DURCHGEHENDER Zug aufs Polygon geclippt ({@link clipPolylineToPolygon}), sodass - * benachbarte Wellen-Stützpunkte in EINEM Lauf verbunden bleiben. Der Compiler - * strokt den Lauf als gehrten Streifen → glatte, spitzenfreie Welle. Die Welle - * endet exakt an den Polygonkanten (even-odd-Clipping, konkav-fähig). - */ -function insulationRuns(poly: Vec2[], hatch: HatchRender, scale: number): HatchRun[] { - const rot = toModelAngleRad(hatch.angle); - - // Muster-Parameter in Metern (aus den SVG-px-Werten der Kachel). - const wavelength = 14 * scale * PX_TO_M; // Kachelbreite - const rowGap = 10 * scale * PX_TO_M; // Kachelhöhe → Zeilenabstand - - // Lokales Muster-Koordinatensystem: u entlang der Welle, v quer (Zeilen). - // ANKER = MODELL-URSPRUNG, wie beim SVG-`userSpaceOnUse`-Pattern (siehe - // hatchLineFamily): so liegen Wellen-Phase UND Zeilenraster deckungsgleich - // zum SVG-Referenzpfad und über alle Polygone hinweg in EINEM Gitter. - const uDir = rotate({ x: 1, y: 0 }, rot); - const vDir = rotate({ x: 0, y: 1 }, rot); - - // Abdeckungsbereich in (u,v) über die Polygon-Ecken bestimmen. - let uMin = Infinity, uMax = -Infinity, vMin = Infinity, vMax = -Infinity; - for (const p of poly) { - const u = p.x * uDir.x + p.y * uDir.y; - const v = p.x * vDir.x + p.y * vDir.y; - if (u < uMin) uMin = u; - if (u > uMax) uMax = u; - if (v < vMin) vMin = v; - if (v > vMax) vMax = v; - } - if (!(uMax > uMin) || !(vMax > vMin)) return []; - - // Feinheit der Wellen-Tessellierung (Segmente je Wellenlänge). Höher als beim - // segmentweisen Ansatz, da die Läufe jetzt glatt gehrt werden → weichere Welle. - const STEPS = 22; - const du = wavelength / STEPS; - - const runs: HatchRun[] = []; - const toWorld = (u: number, v: number): Vec2 => ({ - x: uDir.x * u + vDir.x * v, - y: uDir.y * u + vDir.y * v, - }); - - // Die Wellen-Mittellinie liegt in der SVG-Kachel bei y = h/2 (my = 5·scale), - // die Zeilen also auf HALBEN Rasterlinien: v = (r + 0.5)·rowGap. - const firstRow = Math.floor(vMin / rowGap - 0.5) - 1; - const lastRow = Math.ceil(vMax / rowGap - 0.5) + 1; - const uStart = Math.floor((uMin - wavelength) / du) * du; - const uEnd = uMax + wavelength; - - // EXAKT die SVG-Wellenform: die Kachel zeichnet zwei quadratische Béziers - // `M0 5s Q 3.5s -1s 7s 5s Q 10.5s 11s 14s 5s`. Deren x(t) ist LINEAR (7s·t je - // Halbwelle), die Auslenkung eine Parabel ±12s·t(1−t) (Scheitel ±3s) — also - // Halbwellen-Parabeln statt einer Sinuskurve (flachere Kämme, steilere - // Nulldurchgänge). Erste Halbwelle: Kamm nach OBEN (Bildschirm) = +v (Modell). - const half = wavelength / 2; - const waveAt = (u: number): number => { - const phase = ((u % wavelength) + wavelength) % wavelength; - const t = (phase % half) / half; - const mag = 12 * scale * PX_TO_M * t * (1 - t); - return phase < half ? mag : -mag; - }; - - for (let r = firstRow; r <= lastRow; r++) { - const vBase = (r + 0.5) * rowGap; - // Ganze Welle als EINE Polylinie tessellieren, dann DURCHGEHEND clippen. - // Das u-Raster ist an Vielfachen von du = λ/22 ausgerichtet → die Null- - // durchgänge (Vielfache von λ/2 = 11·du) liegen exakt auf Stützpunkten. - const wavePts: Vec2[] = []; - for (let u = uStart; u <= uEnd + 1e-9; u += du) { - wavePts.push(toWorld(u, vBase + waveAt(u))); - } - for (const run of clipPolylineToPolygon(wavePts, poly)) runs.push(run); - } - return runs; -} - -// ── Random-Vektor-Schraffur (deterministisch) ──────────────────────────────── - -/** - * Deterministischer 32-bit-PRNG (mulberry32). Gleicher Seed ⇒ gleiche Folge — - * KEIN `Math.random()`: die Random-Schraffur muss über Re-Renders/Print - * reproduzierbar sein (sonst flackert der Splitt und der Druck ist nicht - * deterministisch). - */ -function mulberry32(seed: number): () => number { - let a = seed >>> 0; - return () => { - a |= 0; - a = (a + 0x6d2b79f5) | 0; - let t = Math.imul(a ^ (a >>> 15), 1 | a); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; -} - -/** - * Faltet mehrere Fließkomma-Kennwerte zu einem stabilen 32-bit-Seed. Die Werte - * werden gequantelt (·1000, gerundet), damit numerisches Rauschen den Seed nicht - * verschiebt — gleiche Fläche/gleiche Hatch-Parameter ⇒ gleicher Seed ⇒ gleiche - * Streuung. - */ -function hashSeed(...vals: number[]): number { - let h = 0x811c9dc5; - for (const v of vals) { - const q = Math.round(v * 1000) | 0; - h ^= q & 0xffff; - h = Math.imul(h, 0x01000193); - h ^= (q >>> 16) & 0xffff; - h = Math.imul(h, 0x01000193); - } - return h >>> 0; -} - -/** - * Deterministischer Hash EINER Modellraum-Zelle (`ix`,`iy` = absolute Zell-Indizes - * `floor(x/cell)`/`floor(y/cell)`) plus `seed`. Ergebnis ist ein 32-bit-Seed für - * {@link mulberry32}. Zentraler Baustein der modellraum-stabilen Streuung: der - * Zell-Inhalt hängt NUR an den absoluten Zell-Indizes + Seed — NICHT an der - * Bounding-Box der Fläche. Dadurch bleibt ein Strich beim Vergrößern/Verschieben - * der Fläche an derselben Zelle „verankert". - */ -function hashCell(ix: number, iy: number, seed: number): number { - let h = (0x811c9dc5 ^ (seed | 0)) >>> 0; - h = Math.imul(h ^ (ix | 0), 0x01000193); - h = Math.imul(h ^ (iy | 0), 0x01000193); - h ^= h >>> 15; - h = Math.imul(h, 0x2c1b3c6d); - h ^= h >>> 12; - return h >>> 0; -} - -/** - * Streut kurze Striche gleichmäßig-zufällig (aber DETERMINISTISCH) über ein - * Polygon — MODELLRAUM-STABIL: Der Modellraum wird in ein regelmäßiges Gitter der - * Zellgröße `cell` gekachelt (absolutes Gitter, Ursprung = Modell-Ursprung). Über - * die Zellen, die die Polygon-Bounding-Box überdecken, wird iteriert (nur aus - * Performance-Gründen); PRO Zelle liefert {@link hashCell}(ix,iy,seed) einen festen - * PRNG, aus dem Lage (innerhalb der Zelle), Orientierung (um `baseAngleRad` ± π) - * und Länge folgen. Jeder Strich wird aufs Polygon geclippt - * ({@link clipSegmentToPolygon}, konkav-fähig). - * - * Folge: Beim Vergrößern der Fläche bleiben bestehende Striche STEHEN (gleiche - * Zelle ⇒ gleicher Strich), am Rand kommen neue dazu; die Dichte (Striche pro - * Fläche) bleibt konstant; beim Verschieben wandert nichts. „Neu würfeln" (neuer - * `seed`) verschiebt das ganze Feld. Einheiten-agnostisch (Aufrufer gibt `cell`/ - * `strokeLen` in Modell-Metern bzw. Papier-mm). Ausgabe = 2-Punkt-Läufe. + * Streut kurze Striche deterministisch und MODELLRAUM-STABIL über ein Polygon (eine Zelle des + * absoluten Gitters je Strich, Lage/Winkel/Länge aus `hash(ix, iy, seed)`), aufs Polygon geclippt. */ export function scatterStrokes( poly: Vec2[], @@ -592,132 +157,32 @@ export function scatterStrokes( lenMin?: number, lenMax?: number, ): HatchRun[] { - if (poly.length < 3 || cell <= 1e-9 || strokeLen <= 1e-9) return []; - const bb = bbox(poly); - if (!(bb.maxX > bb.minX) || !(bb.maxY > bb.minY)) return []; - - // Absolute Zell-Indizes, die die Bounding-Box überdecken (Modell-Ursprung als - // Gitter-Anker → verschiebe-invariant). - let eff = cell; - let ix0 = Math.floor(bb.minX / eff); - let ix1 = Math.floor(bb.maxX / eff); - let iy0 = Math.floor(bb.minY / eff); - let iy1 = Math.floor(bb.maxY / eff); - // Sicherheits-Cap gegen pathologisch große Flächen / winzige Zellen: Zellgröße - // gröber machen, bis die Zellzahl unter dem Limit liegt (uniform, nur grober). - const MAX_CELLS = 250000; - let cells = (ix1 - ix0 + 1) * (iy1 - iy0 + 1); - if (cells > MAX_CELLS) { - eff = cell * Math.sqrt(cells / MAX_CELLS); - ix0 = Math.floor(bb.minX / eff); - ix1 = Math.floor(bb.maxX / eff); - iy0 = Math.floor(bb.minY / eff); - iy1 = Math.floor(bb.maxY / eff); - } - - // Explizite Längen-Spanne (falls gesetzt) validieren; sonst die scale-abhängige - // Variation (±40 % um `strokeLen`) beibehalten. - const hasRange = - lenMin != null && lenMax != null && lenMin > 1e-9 && lenMax >= lenMin; - - const runs: HatchRun[] = []; - for (let iy = iy0; iy <= iy1; iy++) { - for (let ix = ix0; ix <= ix1; ix++) { - const rnd = mulberry32(hashCell(ix, iy, seed)); - // Strich-Mittelpunkt innerhalb der Zelle (absolutes Gitter). - const cx = (ix + rnd()) * eff; - const cy = (iy + rnd()) * eff; - // Orientierung frei (± π um die Basisrichtung). - const ang = baseAngleRad + (rnd() * 2 - 1) * Math.PI; - // Länge: explizite Spanne [lenMin,lenMax] oder Default (±40 % um strokeLen). - const len = hasRange - ? lenMin! + rnd() * (lenMax! - lenMin!) - : strokeLen * (0.6 + 0.8 * rnd()); - const half = len * 0.5; - const dx = Math.cos(ang) * half; - const dy = Math.sin(ang) * half; - const a: Vec2 = { x: cx - dx, y: cy - dy }; - const b: Vec2 = { x: cx + dx, y: cy + dy }; - for (const seg of clipSegmentToPolygon(a, b, poly)) runs.push([seg.a, seg.b]); - } - } - return runs; + return toRuns( + core().scatter_strokes_flat(flat(poly), cell, baseAngleRad, seed, strokeLen, lenMin ?? NaN, lenMax ?? NaN), + ); } /** - * Random-Vektor-Schraffur eines Polygons in Modell-Metern (Kies/Splitt). Dichte - * und Strichlänge sind — wie die Parallelschar — an die Kachelgröße (`8·scale` px) - * gekoppelt, damit `scale`/`density` die Streudichte steuern. Die Streuung ist - * MODELLRAUM-STABIL (siehe {@link scatterStrokes}): der Seed hängt NUR an den - * Muster-Parametern (Winkel/Scale/Dichte) plus dem expliziten `hatch.seed` — NICHT - * an der Bounding-Box. Dadurch verankern sich die Striche im Modellraum; beim - * Vergrößern der Fläche bleiben sie stehen und die Dichte bleibt konstant. + * Random-Vektor-Schraffur eines Polygons (Kies/Splitt): Dichte und Strichlänge an die Kachel + * (8·scale px) gekoppelt, Seed nur aus Muster-Parametern + `hatch.seed`. */ export function buildRandomHatchRuns(poly: Vec2[], hatch: HatchRender, scale?: number): HatchRun[] { - const s = scale ?? (hatch.scale > 1e-6 ? hatch.scale : 1); - // Dichte: Multiplikator auf den Grundabstand (>1 = dichter → kleinere Zelle). - // Fehlt/ungültig ⇒ 1 ⇒ heutiges Verhalten. - const density = hatch.density != null && hatch.density > 1e-6 ? hatch.density : 1; - const cell = (8 * s * PX_TO_M) / density; // Meter, wie der Parallel-Schar-Abstand - const strokeLen = cell * 1.1; // Default-Strich ~ Kachelmaß (wenn keine Längenspanne) - // Fester Seed NUR aus Muster-Parametern + explizitem `hatch.seed` (KEINE bbox): - // „Neu würfeln" (neuer seed) ⇒ anderes Feld, aber gleicher seed + gleiche - // Muster-Parameter ⇒ identisches, modellraum-verankertes Feld über alle - // Renderpfade — unabhängig von Lage/Größe der Fläche. - const seed = hashSeed(hatch.angle, s, density, hatch.seed ?? 0); - const base = toModelAngleRad(hatch.angle); - // Explizite Längenspanne (mm-Papier → Modell-Meter, wie das Dash-Muster). - const lenMin = hatch.lengthMin != null ? hatch.lengthMin * DASH_MM_TO_M : undefined; - const lenMax = hatch.lengthMax != null ? hatch.lengthMax * DASH_MM_TO_M : undefined; - return scatterStrokes(poly, cell, base, seed, strokeLen, lenMin, lenMax); + return toRuns(core().random_hatch_runs_flat(flat(poly), encodeHatch(hatch), scale ?? NaN)); } -// ── Zickzack-/Wellen-Linie ─────────────────────────────────────────────────── - /** - * Tesselliert die Strecke [a,b] zu einem Zickzack (Dreieckswelle) mit `amplitude` - * (Ausschlag quer, Einheit wie a/b) und `wavelength` (Periodenlänge längs). Rein - * geometrisch, einheiten-agnostisch: der Aufrufer übergibt amplitude/wavelength - * in der Zielkoordinaten-Einheit. Die Auslenkung folgt dem Muster [0,+A,0,−A] je - * Viertel-Wellenlänge; Start liegt auf der Achse, das Ende exakt auf `b`. + * Zickzack (Dreieckswelle [0,+A,0,−A] je Viertel-Wellenlänge) entlang [a,b]; Einheiten wie + * a/b. Start auf der Achse, Ende exakt auf `b`. */ export function zigzagPoints(a: Vec2, b: Vec2, amplitude: number, wavelength: number): Vec2[] { - const dx = b.x - a.x; - const dy = b.y - a.y; - const L = Math.hypot(dx, dy); - if (L < 1e-12 || wavelength <= 1e-9 || amplitude <= 0) return [a, b]; - const ux = dx / L; - const uy = dy / L; - const nx = -uy; // linke Normale (Ausschlagachse) - const ny = ux; - const quarter = wavelength / 4; - const steps = Math.max(1, Math.round(L / quarter)); - const tri = [0, 1, 0, -1]; - const pts: Vec2[] = []; - for (let i = 0; i <= steps; i++) { - const t = Math.min(L, i * quarter); - const off = amplitude * tri[i % 4]; - pts.push({ x: a.x + ux * t + nx * off, y: a.y + uy * t + ny * off }); - } - const last = pts[pts.length - 1]; - if (Math.abs(last.x - b.x) > 1e-9 || Math.abs(last.y - b.y) > 1e-9) { - pts.push({ x: b.x, y: b.y }); - } - return pts; + const f = core().zigzag_points_flat(a.x, a.y, b.x, b.y, amplitude, wavelength); + return f.length ? toPts(f) : [a, b]; } /** - * Kachelt ein frei gezeichnetes Motiv (offene Polylinie in einer Einheitszelle) - * entlang der Strecke [a,b] und liefert die zusammenhängende Polylinie. Rein - * geometrisch/einheiten-agnostisch (die Verallgemeinerung von {@link zigzagPoints}): - * • `motif.points` sind die Stützpunkte der Zelle; `x` läuft 0..`motif.length` - * ENTLANG der Linie (= Wiederhollänge), `y` = Versatz quer zur Linie (linke - * Normale `n = (-u.y, u.x)`). - * • `scale` skaliert Punkte UND Länge in die Zielkoordinaten-Einheit (z. B. - * Papier-mm → Modell-Meter via `DASH_MM_TO_M`); der Print-SVG-Pfad übergibt 1. - * Das Motiv wird alle `length·scale` wiederholt; am Segment-Ende exakt bei `L` - * geclippt (letztes Segment interpoliert), sodass die Linie nicht über `b` - * hinausläuft. Degeneriert (leeres Motiv, Länge 0, Nullstrecke) → `[a, b]`. + * Kachelt ein frei gezeichnetes Motiv (`points` in der Einheitszelle: x entlang, y quer; + * Wiederhollänge `length`, beides ·`scale`) entlang [a,b], am Ende exakt geclippt. Entartet → + * `[a, b]`. */ export function motifPoints( a: Vec2, @@ -725,44 +190,6 @@ export function motifPoints( motif: { points: Vec2[]; length: number }, scale = 1, ): Vec2[] { - const dx = b.x - a.x; - const dy = b.y - a.y; - const L = Math.hypot(dx, dy); - const cell = motif.length * scale; - if (L < 1e-12 || cell <= 1e-9 || motif.points.length < 2) return [a, b]; - const ux = dx / L; - const uy = dy / L; - const nx = -uy; // linke Normale (Ausschlagachse) - const ny = ux; - const toWorld = (ax: number, off: number): Vec2 => ({ - x: a.x + ux * ax + nx * off, - y: a.y + uy * ax + ny * off, - }); - - const out: Vec2[] = []; - const reps = Math.ceil(L / cell) + 1; - let last: { ax: number; off: number } | null = null; - for (let r = 0; r < reps; r++) { - const base = r * cell; - for (let i = 0; i < motif.points.length; i++) { - const p = motif.points[i]; - const ax = base + p.x * scale; - const off = p.y * scale; - // Naht-Duplikat (Zellenende r == Zellenanfang r+1) überspringen. - if (last && Math.abs(ax - last.ax) < 1e-9 && Math.abs(off - last.off) < 1e-9) { - continue; - } - if (ax > L + 1e-9) { - // Letztes Segment am Segmentende clippen: last→p bei ax = L interpolieren. - if (last && ax > last.ax + 1e-12 && L - last.ax > 1e-9) { - const tt = (L - last.ax) / (ax - last.ax); - out.push(toWorld(L, last.off + (off - last.off) * tt)); - } - return out.length >= 2 ? out : [a, b]; - } - out.push(toWorld(ax, off)); - last = { ax, off }; - } - } - return out.length >= 2 ? out : [a, b]; + const f = core().motif_points_flat(a.x, a.y, b.x, b.y, flat(motif.points), motif.length, scale); + return f.length ? toPts(f) : [a, b]; } diff --git a/src/plan/planBuf.test.ts b/src/plan/planBuf.test.ts new file mode 100644 index 00000000..fce7a0d3 --- /dev/null +++ b/src/plan/planBuf.test.ts @@ -0,0 +1,138 @@ +// Plan-Puffer [K3b]: TS kodiert, Rust liest und schreibt neu — Hin und zurück muss jede Zahl +// erhalten (je Primitiv-Typ), fremde Versionen werden sauber abgelehnt. + +import { describe, it, expect } from "vitest"; +import { encodePlanBuf, encodeHatch, parseColor, PLAN_BUF_MAGIC, PLAN_BUF_VERSION } from "./planBuf"; +import { core } from "../engine/coreWasm"; +import type { HatchRender, Primitive } from "./generatePlan"; + +const hatch: HatchRender = { + pattern: "custom", + scale: 2, + angle: 30, + color: "#336699", + lineWeight: 0.13, + dash: [0.35, 0.3], + kind: "vector", + lines: "random", + origin: { x: 1, y: -2 }, + seed: 7, + density: 1.5, + lengthMin: 0.5, + lengthMax: 2, + motif: { points: [{ x: 0, y: 0 }, { x: 1, y: 1 }], length: 2 }, +}; + +const dash = [1, 0.5]; + +const PRIMS: Record = { + polygon: { + kind: "polygon", + pts: [{ x: 0, y: 0 }, { x: 2, y: 0 }, { x: 1, y: 1.5 }], + fill: "#ffcc00", + stroke: "rgba(10, 20, 30, 0.5)", + strokeWidthMm: 0.35, + hatch, + greyed: true, + opacity: 0.4, + noStrokeEdges: [0, 2], + wallId: "w1", + }, + line: { kind: "line", a: { x: 0, y: 0 }, b: { x: 3, y: 4 }, cls: "c", weightMm: 0.25, color: "#000", dash, drawingId: "d" }, + zigzag: { kind: "line", a: { x: 0, y: 0 }, b: { x: 3, y: 4 }, cls: "c", weightMm: 0.25, zigzag: { amplitude: 1, wavelength: 4 } }, + motif: { + kind: "line", + a: { x: 0, y: 0 }, + b: { x: 3, y: 4 }, + cls: "c", + weightMm: undefined as unknown as number, + motif: { points: [{ x: 0, y: 0 }, { x: 2, y: 1 }], length: 4 }, + }, + arc: { kind: "arc", center: { x: 0, y: 0 }, from: { x: 1, y: 0 }, to: { x: 0, y: 1 }, r: 1, cls: "c", weightMm: 0.18, opacity: 0.5 }, + drawingCircle: { kind: "drawingCircle", center: { x: 5, y: 5 }, r: 2, fill: "none", stroke: "#123", weightMm: 0.18, dash: [2] }, + drawingArc: { kind: "drawingArc", center: { x: 5, y: 5 }, r: 2, a0: 0, a1: 3, stroke: "#123", weightMm: 0.5, greyed: true }, + text: { kind: "drawingText", at: { x: 0, y: 0 }, text: "x", heightM: 1, angle: 0, color: "#000" }, + image: { kind: "drawingImage", min: { x: 0, y: 0 }, max: { x: 1, y: 1 }, src: "", opacity: 1 }, +}; + +/** Gleichheit Zahl für Zahl (NaN = NaN, −0 ≠ +0). */ +function sameBits(a: Float64Array, b: Float64Array): boolean { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) if (!Object.is(a[i], b[i])) return false; + return true; +} + +describe("Plan-Puffer", () => { + for (const [name, prim] of Object.entries(PRIMS)) { + it(`Hin und zurück: ${name}`, () => { + const buf = encodePlanBuf([prim]); + expect(buf[0]).toBe(PLAN_BUF_MAGIC); + expect(buf[1]).toBe(PLAN_BUF_VERSION); + expect(buf[4]).toBe(1); + expect(sameBits(core().plan_buf_recode(buf), buf)).toBe(true); + }); + } + + it("Hin und zurück: alle Typen gemischt, ein Eintrag je Primitiv", () => { + const prims = Object.values(PRIMS); + const buf = encodePlanBuf(prims); + expect(buf[4]).toBe(prims.length); + expect(sameBits(core().plan_buf_recode(buf), buf)).toBe(true); + }); + + it("Texte und Bilder sind Platzhalter (nur der Typ-Eintrag 0)", () => { + expect(Array.from(encodePlanBuf([PRIMS.text, PRIMS.image]))).toEqual([PLAN_BUF_MAGIC, PLAN_BUF_VERSION, 0, 0, 2, 0, 0]); + }); + + it("Farben werden einmal geparst und geteilt, ungültige ergeben −1", () => { + const a = { ...PRIMS.line, color: "#ff0000" } as Primitive; + const b = { ...PRIMS.line, color: "nonsense" } as Primitive; + const buf = encodePlanBuf([a, a, b]); + expect(buf[2]).toBe(1); + expect(Array.from(buf.subarray(5, 9))).toEqual(parseColor("#ff0000")); + }); + + it("Linienzug-Flag: nur gleiches Element, gleicher Stil und lückenlos", () => { + const seg = (ax: number, bx: number, extra: object = {}): Primitive => + ({ kind: "line", a: { x: ax, y: 0 }, b: { x: bx, y: 0 }, cls: "c", weightMm: 0.18, color: "#000", drawingId: "d", ...extra }) as Primitive; + const flagsOf = (prims: Primitive[]) => { + const buf = encodePlanBuf(prims); + const out: number[] = []; + let i = 5 + buf[2] * 4; + for (let k = 0; k < prims.length; k++) { + out.push(buf[i + 1] & 4); + i += 9 + 1 + buf[i + 9]; + } + return out; + }; + expect(flagsOf([seg(0, 1), seg(1, 2), seg(2, 3)])).toEqual([0, 4, 4]); + expect(flagsOf([seg(0, 1), seg(1.5, 2)])).toEqual([0, 0]); + expect(flagsOf([seg(0, 1), seg(1, 2, { drawingId: "e" })])).toEqual([0, 0]); + expect(flagsOf([seg(0, 1), seg(1, 2, { weightMm: 0.5 })])).toEqual([0, 0]); + expect(flagsOf([seg(0, 1), seg(1, 2, { greyed: false })])).toEqual([0, 0]); + expect(flagsOf([seg(0, 1, { dash: [1] }), seg(1, 2, { dash: [1] })])).toEqual([0, 0]); + }); + + it("fremde Version oder kaputter Puffer → leeres Ergebnis, kein Absturz", () => { + const buf = encodePlanBuf(Object.values(PRIMS)); + const wrong = buf.slice(); + wrong[1] = PLAN_BUF_VERSION + 1; + expect(core().plan_buf_recode(wrong).length).toBe(0); + expect(core().gpu_compile_flat(wrong, 90, true).length).toBe(0); + expect(core().plan_buf_recode(buf.subarray(0, buf.length - 3)).length).toBe(0); + expect(core().gpu_compile_flat(new Float64Array([1, 2, 3]), 90, false).length).toBe(0); + // Danach arbeitet der Kern normal weiter. + expect(sameBits(core().plan_buf_recode(buf), buf)).toBe(true); + }); + + it("Einzel-Schraffur hat dasselbe Format wie ein Hatch-Eintrag", () => { + const h = encodeHatch(hatch); + const buf = encodePlanBuf([PRIMS.polygon]); + const colors = buf[2]; + // Im Plan-Puffer steht der Farbindex statt −1. + const inPlan = buf.slice(5 + colors * 4, 5 + colors * 4 + h.length); + expect(inPlan[5]).toBeGreaterThanOrEqual(0); + inPlan[5] = -1; + expect(sameBits(inPlan, h)).toBe(true); + }); +}); diff --git a/src/plan/planBuf.ts b/src/plan/planBuf.ts new file mode 100644 index 00000000..be336b59 --- /dev/null +++ b/src/plan/planBuf.ts @@ -0,0 +1,356 @@ +/** + * Plan-Puffer ([K3b]): kompakte Binärkodierung der zeichnungsrelevanten Plan-Primitive als + * flacher `Float64Array`. TS schreibt ihn vorerst aus `Plan.primitives`, der Rust-Kern liest ihn + * (`src-tauri/core/src/plan_buf.rs`, dort dieselbe Formatbeschreibung) — heute für die GPU- + * Kompilierung (`glPlan/glPlanCompile.ts`), ab [K3a] erzeugt Rust ihn direkt. + * + * ```text + * Kopf [MAGIC, VERSION, nColors, nHatches, nPrims] + * MAGIC = 0x504C4231 ("PLB1"), VERSION = 1 — Rust lehnt fremde Werte ab (leeres Ergebnis) + * Farben nColors × [r, g, b, a] (0..1, hier aus dem Farbtext geparst) + * Schraffuren nHatches × Hatch + * Primitive nPrims × Prim (genau ein Eintrag je Primitiv → Indizes bleiben gleich) + * + * Hatch [pattern, kind, flags, scale, angle, colorIdx, lineWeight, originX, originY, + * seed, density, lengthMin, lengthMax, nDash, dash…, (Motiv: length, nPts, x,y…)] + * pattern 0 none · 1 solid · 2 diagonal (auch unbekannt) · 3 crosshatch · 4 insulation · 5 custom + * kind 0 vector · 1 image · 2 gradient (Bild/Verlauf: GPU fällt auf die Füllung zurück) + * flags 1 random · 2 origin · 4 seed · 8 density · 16 lengthMin · 32 lengthMax · 64 Motiv + * (Felder ohne Flag stehen auf 0 und gelten als „nicht gesetzt") + * + * Prim [tag, flags, …] flags 1 greyed · 2 opacity gesetzt · 4 setzt den Linienzug der + * vorigen Linie fort · 8 Zickzack · 16 Motiv + * 0 Platzhalter [0] (Text, Bild … — zeichnet die GPU nicht) + * 1 polygon [1, flags, fillIdx, strokeIdx, strokeWidthMm, hatchIdx, opacity, + * nPts, x,y…, nNoStroke, kante…] + * 2 line [2, flags, colorIdx, weightMm, opacity, ax, ay, bx, by, nDash, dash…, + * (Zickzack: amplitude, wavelength), (Motiv: length, nPts, x,y…)] + * 3 arc [3, flags, colorIdx, weightMm, opacity, cx, cy, fromX, fromY, toX, toY, r, + * nDash, dash…] + * 4 drawingCircle [4, flags, fillIdx, strokeIdx, weightMm, opacity, cx, cy, r, nDash, dash…] + * 5 drawingArc [5, flags, strokeIdx, weightMm, opacity, cx, cy, r, a0, a1, nDash, dash…] + * ``` + * Farb-/Schraffur-Index −1 = keine (Farbtext ungültig, "none", fehlende Schraffur). Längen in + * Metern, Strichstärken/Strichmuster/Zickzack/Motiv in Papier-mm, Winkel von drawingArc in + * Bogenmass, Schraffur-Winkel in Grad (SVG-Drehsinn). Ohne opacity-Flag steht 1 im Feld; fehlende + * Zahlen (`undefined`) werden NaN, der Verbraucher nimmt dann wie bisher seinen Standard. + * Flag 4 (Linienzug): gleiches Element (`drawingId`), gleiche Farbe/Stärke/greyed/opacity/ + * Strichmuster (Referenz) und Anfang = Ende der vorigen Linie — dann zeichnet die GPU die + * Einzelsegmente als EINEN Zug (zwei echte Kappen statt 2N). Pick-IDs stehen NICHT im Puffer + * (Picken bleibt vorerst TS). + */ + +import type { HatchRender, Primitive } from "./generatePlan"; +import type { Vec2 } from "../model/types"; + +export const PLAN_BUF_MAGIC = 0x504c4231; +export const PLAN_BUF_VERSION = 1; + +/** RGBA-Farbe, Komponenten in [0,1]. */ +export type PlanRgba = [number, number, number, number]; + +const FLAG_GREYED = 1; +const FLAG_OPACITY = 2; +const FLAG_CHAIN = 4; +const FLAG_ZIGZAG = 8; +const FLAG_MOTIF = 16; + +/** + * Farbe → RGBA[0..1]; ungültig/"none"/"transparent" → null. + * Unterstützt "#rgb", "#rrggbb", "#rrggbbaa" und "rgb()/rgba()". + */ +export function parseColor(hex: string | undefined): PlanRgba | null { + if (!hex) return null; + const s = hex.trim().toLowerCase(); + if (s === "none" || s === "transparent") return null; + + if (s.startsWith("rgb")) { + const m = s.match(/[\d.]+/g); + if (!m || m.length < 3) return null; + const a = m.length >= 4 ? parseFloat(m[3]) : 1; + return [+m[0] / 255, +m[1] / 255, +m[2] / 255, a > 1 ? a / 255 : a]; + } + + let h = s[0] === "#" ? s.slice(1) : s; + if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2]; + if (h.length !== 6 && h.length !== 8) return null; + const r = parseInt(h.slice(0, 2), 16); + const g = parseInt(h.slice(2, 4), 16); + const b = parseInt(h.slice(4, 6), 16); + const a = h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1; + if (isNaN(r) || isNaN(g) || isNaN(b)) return null; + return [r / 255, g / 255, b / 255, a]; +} + +/** Wachsender `Float64Array`-Schreiber. */ +class F64Writer { + buf = new Float64Array(1024); + length = 0; + private grow(need: number): void { + let cap = this.buf.length * 2; + while (cap < need) cap *= 2; + const next = new Float64Array(cap); + next.set(this.buf.subarray(0, this.length)); + this.buf = next; + } + push(v: number): void { + if (this.length + 1 > this.buf.length) this.grow(this.length + 1); + this.buf[this.length++] = v; + } + /** Platz für `n` weitere Werte; liefert den Startindex (danach direkt in `buf` schreiben). */ + reserve(n: number): number { + if (this.length + n > this.buf.length) this.grow(this.length + n); + const o = this.length; + this.length += n; + return o; + } + list(l: readonly number[] | null | undefined): void { + const n = l ? l.length : 0; + const o = this.reserve(n + 1); + this.buf[o] = n; + for (let i = 0; i < n; i++) this.buf[o + 1 + i] = l![i]; + } + pts(p: readonly Vec2[]): void { + const n = p.length; + const o = this.reserve(2 * n + 1); + const b = this.buf; + b[o] = n; + for (let i = 0; i < n; i++) { + b[o + 1 + 2 * i] = p[i].x; + b[o + 2 + 2 * i] = p[i].y; + } + } +} + +const PATTERN_CODE: Record = { + none: 0, + solid: 1, + diagonal: 2, + crosshatch: 3, + insulation: 4, + custom: 5, +}; + +/** Eine Schraffur im Hatch-Format (auch Eingabe der Einzel-Bindungen in `glPlanHatch.ts`). */ +function writeHatch(w: F64Writer, h: HatchRender, colorIdx: number): void { + let flags = 0; + if (h.lines === "random") flags |= 1; + if (h.origin != null) flags |= 2; + if (h.seed != null) flags |= 4; + if (h.density != null) flags |= 8; + if (h.lengthMin != null) flags |= 16; + if (h.lengthMax != null) flags |= 32; + if (h.motif) flags |= 64; + const o = w.reserve(13); + const b = w.buf; + b[o] = PATTERN_CODE[h.pattern] ?? 2; + b[o + 1] = h.kind === "image" ? 1 : h.kind === "gradient" ? 2 : 0; + b[o + 2] = flags; + b[o + 3] = h.scale; + b[o + 4] = h.angle; + b[o + 5] = colorIdx; + b[o + 6] = h.lineWeight; + b[o + 7] = h.origin != null ? h.origin.x : 0; + b[o + 8] = h.origin != null ? h.origin.y : 0; + b[o + 9] = h.seed ?? 0; + b[o + 10] = h.density ?? 0; + b[o + 11] = h.lengthMin ?? 0; + b[o + 12] = h.lengthMax ?? 0; + w.list(h.dash); + if (h.motif) { + w.push(h.motif.length); + w.pts(h.motif.points); + } +} + +/** Einzelne Schraffur kodieren (Farbe −1) — Eingabe der Schraffur-Bindungen des Kerns. */ +export function encodeHatch(h: HatchRender): Float64Array { + const w = new F64Writer(); + writeHatch(w, h, -1); + return w.buf.subarray(0, w.length); +} + +/** Zwischenspeicher Farbtext → Farbindex-Eintrag (geparste Farbe oder null). */ +const colorCache = new Map(); + +type LinePrim = Extract; + +const isPlainLine = (p: Primitive | undefined): p is LinePrim => + p !== undefined && p.kind === "line" && !p.zigzag && !p.motif; + +/** Setzt `p` den Linienzug von `prev` fort (gleiches Element und gleicher Stil, lückenlos)? */ +function chainsPrev(prev: Primitive | undefined, p: LinePrim): boolean { + return ( + isPlainLine(prev) && + p.drawingId === prev.drawingId && + p.color === prev.color && + p.weightMm === prev.weightMm && + p.greyed === prev.greyed && + p.opacity === prev.opacity && + p.dash === prev.dash && + p.a.x === prev.b.x && + p.a.y === prev.b.y + ); +} + +/** Primitive → Plan-Puffer (Format s. Dateikopf). */ +export function encodePlanBuf(prims: readonly Primitive[]): Float64Array { + const colors: PlanRgba[] = []; + const colorIdx = new Map(); + let lastColor: string | undefined; + let lastColorIdx = -1; + const color = (s: string | undefined): number => { + if (!s) return -1; + if (s === lastColor) return lastColorIdx; + let i = colorIdx.get(s); + if (i !== undefined) { + lastColor = s; + lastColorIdx = i; + return i; + } + let c = colorCache.get(s); + if (c === undefined) { + c = parseColor(s); + if (colorCache.size > 4096) colorCache.clear(); + colorCache.set(s, c); + } + i = c ? colors.push(c) - 1 : -1; + colorIdx.set(s, i); + return i; + }; + const hatchW = new F64Writer(); + const hatchIdx = new Map(); + const hatch = (h: HatchRender | undefined): number => { + if (!h) return -1; + let i = hatchIdx.get(h); + if (i === undefined) { + i = hatchIdx.size; + writeHatch(hatchW, h, color(h.color)); + hatchIdx.set(h, i); + } + return i; + }; + const style = (greyed: boolean | undefined, opacity: number | undefined): number => + (greyed ? FLAG_GREYED : 0) | (opacity !== undefined ? FLAG_OPACITY : 0); + const op = (opacity: number | undefined): number => (opacity !== undefined ? opacity : 1); + + const w = new F64Writer(); + for (let i = 0; i < prims.length; i++) { + const p = prims[i]; + switch (p.kind) { + case "polygon": { + const fill = color(p.fill); + const stroke = color(p.stroke); + const h = hatch(p.hatch); + const o = w.reserve(7); + const b = w.buf; + b[o] = 1; + b[o + 1] = style(p.greyed, p.opacity); + b[o + 2] = fill; + b[o + 3] = stroke; + b[o + 4] = p.strokeWidthMm; + b[o + 5] = h; + b[o + 6] = op(p.opacity); + w.pts(p.pts); + w.list(p.noStrokeEdges); + break; + } + case "line": { + let flags = style(p.greyed, p.opacity); + if (isPlainLine(p) && chainsPrev(prims[i - 1], p)) flags |= FLAG_CHAIN; + if (p.zigzag) flags |= FLAG_ZIGZAG; + if (p.motif) flags |= FLAG_MOTIF; + const c = color(p.color); + const o = w.reserve(9); + const b = w.buf; + b[o] = 2; + b[o + 1] = flags; + b[o + 2] = c; + b[o + 3] = p.weightMm; + b[o + 4] = op(p.opacity); + b[o + 5] = p.a.x; + b[o + 6] = p.a.y; + b[o + 7] = p.b.x; + b[o + 8] = p.b.y; + w.list(p.dash); + if (p.zigzag) { + w.push(p.zigzag.amplitude); + w.push(p.zigzag.wavelength); + } + if (p.motif) { + w.push(p.motif.length); + w.pts(p.motif.points); + } + break; + } + case "arc": { + const c = color((p as { color?: string }).color); + const o = w.reserve(12); + const b = w.buf; + b[o] = 3; + b[o + 1] = style(p.greyed, p.opacity); + b[o + 2] = c; + b[o + 3] = p.weightMm; + b[o + 4] = op(p.opacity); + b[o + 5] = p.center.x; + b[o + 6] = p.center.y; + b[o + 7] = p.from.x; + b[o + 8] = p.from.y; + b[o + 9] = p.to.x; + b[o + 10] = p.to.y; + b[o + 11] = p.r; + w.list(p.dash); + break; + } + case "drawingCircle": { + const fill = color(p.fill); + const stroke = color(p.stroke); + const o = w.reserve(9); + const b = w.buf; + b[o] = 4; + b[o + 1] = style(p.greyed, p.opacity); + b[o + 2] = fill; + b[o + 3] = stroke; + b[o + 4] = p.weightMm; + b[o + 5] = op(p.opacity); + b[o + 6] = p.center.x; + b[o + 7] = p.center.y; + b[o + 8] = p.r; + w.list(p.dash); + break; + } + case "drawingArc": { + const stroke = color(p.stroke); + const o = w.reserve(10); + const b = w.buf; + b[o] = 5; + b[o + 1] = style(p.greyed, p.opacity); + b[o + 2] = stroke; + b[o + 3] = p.weightMm; + b[o + 4] = op(p.opacity); + b[o + 5] = p.center.x; + b[o + 6] = p.center.y; + b[o + 7] = p.r; + b[o + 8] = p.a0; + b[o + 9] = p.a1; + w.list(p.dash); + break; + } + default: + // Text, Bild …: Platzhalter, damit Indizes/Bereiche gleich bleiben. + w.push(0); + } + } + + const head = 5 + colors.length * 4; + const out = new Float64Array(head + hatchW.length + w.length); + out[0] = PLAN_BUF_MAGIC; + out[1] = PLAN_BUF_VERSION; + out[2] = colors.length; + out[3] = hatchIdx.size; + out[4] = prims.length; + for (let i = 0; i < colors.length; i++) out.set(colors[i], 5 + i * 4); + out.set(hatchW.buf.subarray(0, hatchW.length), head); + out.set(w.buf.subarray(0, w.length), head + hatchW.length); + return out; +} diff --git a/src/views/plan/nativeGl.ts b/src/views/plan/nativeGl.ts index 61e83b74..00fbc598 100644 --- a/src/views/plan/nativeGl.ts +++ b/src/views/plan/nativeGl.ts @@ -1,8 +1,8 @@ /** * Puffer-Attrappe für den NATIVEN Plan-Renderer (macOS, src-tauri/src/native_embed.rs). * - * Kompilierung (`compilePrimitivesToGpu`) und Chunk-Cache (`GpuChunkCache`) laufen - * unverändert in TypeScript und sprechen nur diese vier Puffer-Funktionen an + * Kompilierung (`compilePrimitivesToGpu`, Rechenteil im Rust-Kern) und Chunk-Cache + * (`GpuChunkCache`) sprechen nur diese vier Puffer-Funktionen an * (`BufferGl`). Statt eines GL-Kontexts liegen die Bytes danach in Rust: jeder * Puffer geht EINMAL als Rohdaten über die Tauri-Schnittstelle (kein JSON); pro * Frame wandert danach nur noch der Ausschnitt.