From 7ba007f40c9ae8e71a34754ea487b201d93a5845 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 12:26:19 +0000 Subject: [PATCH 1/2] [K3c] Strichmuster im Chunk-Pfad (nativer macOS-Renderer): Instanzen im render2d-Format, gleicher Strich-Shader MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Der Chunk-Pfad (gpu_compile → GpuChunkCache → render2d/chunks.rs) hat Linien-Strichmuster nie gezeichnet (keine Regression von 0516253). Jetzt trägt die GPU-Sicht des Plan-Puffers dash, gpu_compile gibt gestrichelte Züge als DashSegment-Instanzen aus (Phase über Ketten, Länge wie Szenen-Pfad), der Chunk-Renderer zeichnet sie mit DASH_LINE_WGSL in Maler-Reihenfolge (lineAt). render_png: --chunks/--bounds. --- TODO.md | 17 ++ src-tauri/core/src/gpu_compile.rs | 374 ++++++++++++++++++++++- src-tauri/core/src/plan_buf.rs | 16 +- src-tauri/render2d/src/bin/render_png.rs | 51 +++- src-tauri/render2d/src/chunks.rs | 176 +++++++++-- src-tauri/render2d/src/headless.rs | 173 +++++++++++ src/plan/glPlan/glPlanChunks.ts | 1 + src/plan/glPlan/glPlanCompile.test.ts | 19 ++ src/plan/glPlan/glPlanCompile.ts | 19 +- src/plan/glPlan/glPlanTypes.ts | 22 ++ src/views/plan/nativeGl.ts | 11 + src/views/plan/useNativePlanRenderer.ts | 1 + 12 files changed, 827 insertions(+), 53 deletions(-) diff --git a/TODO.md b/TODO.md index 6979d4a9..0273f656 100644 --- a/TODO.md +++ b/TODO.md @@ -153,6 +153,23 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern SVG/PDF/DXF unberührt. Offen: Kern-Seite bleibt (big16 S2: Schnitt-Primitive 0,37 s, `planSceneBin` 0,45 s); der Chunk-Pfad (`gpu_compile.rs`, WebGL/nativ-Chunks) zeichnet Striche weiterhin durchgezogen. Nicht in der Tauri-App/Metal und nicht im Browser-WebGPU angesehen (nur lavapipe/Vulkan headless). + ✅ (29.10.) Strichmuster auch im Chunk-Pfad (nativer macOS-Renderer `useNativePlanRenderer` → `GpuChunkCache` → + `render2d/chunks.rs`). Befund: KEINE Regression des Shader-Merges — der Chunk-Pfad hat Linien-Strichmuster nie + gezeichnet (schon die TS-Fassung `glPlanCompile.ts` vor [K3b] ignorierte `dash`, nur Schraffur-Striche wurden zerlegt; + `0516253` hat `core/gpu_compile.rs` nicht berührt) — auf dem Mac waren verdeckte Kanten, Achsen, gestrichelte + Zeichnungen seit jeher durchgezogen. Jetzt: die GPU-Sicht des Plan-Puffers trägt `dash` (Linie/Bogen/Kreis/2D-Bogen), + `gpu_compile` gibt gestrichelte Züge als Instanzen im render2d-Format aus (16 f32: Segment, Lauflänge, Zug, Muster; + Phase über verkettete Linien, Länge Papier-mm × 0,1 wie der Szenen-Pfad, > 8 Einträge zerlegt die CPU), der + Chunk-Renderer zeichnet sie mit DEMSELBEN `DASH_LINE_WGSL`, in Maler-Reihenfolge mit den Linien verzahnt (`lineAt`; + sonst lagen graue verdeckte Kanten über den Schnittkanten). Flaches Format/`NativeChunkLayout` additiv (`dash_inst`, + `dash_batches`, serde-Vorgaben). Tests: Kern (Instanzen, Phase, Muster-Rückfälle, Maler-Reihenfolge, Deckung auf der + Achse = `apply_dash_runs`-Zerlegung, 150 Zufallsfälle), render2d (Reihenfolge; Chunk-Renderer headless zeichnet + Strich/Lücke), TS-Fassade. Bilder (lavapipe, neu `render_png --chunks/--bounds`): Schnitt mit 752 verdeckten Kanten, + Grundriss, gestrichelte Zeichnungen — Chunk-Pfad vs. Szenen-Pfad 0,00 % abweichend in den Schnitt-Ausschnitten, + Rest = Texte (zeichnet der Chunk-Pfad nicht) und vorbestehende Unterschiede; alt (durchgezogen) sichtbar anders. + Nicht kompiliert: `cad-tauri` mit `native2d` für macOS (Linux-Container: cc kann kein `-arch arm64` für + objc2-exception-helper) — `native_embed.rs` ist unverändert, `render2d` (`window`) für `aarch64-apple-darwin` + per `cargo check` geprüft. Nicht auf Metal/in der Tauri-App angesehen. TS-Fassung gelöscht (29.10.): `toSection.ts`/`toElevation.ts` sind dünne Fassaden (Ebene, Sichtbarkeit, truck-Körper → Abfrage), `sectionOpenings.ts`, `sectionExtras.ts`, `meshSection.ts`, `generateSectionPlan`/`resolve*SectionStyle` in `generatePlan.ts`, `windowSymbol` (opening.ts), `keyhole`/`voidSectionRects`/`subtractVoidsInSection` (voids.ts) und ihre diff --git a/src-tauri/core/src/gpu_compile.rs b/src-tauri/core/src/gpu_compile.rs index 59ac4733..ece8a5d5 100644 --- a/src-tauri/core/src/gpu_compile.rs +++ b/src-tauri/core/src/gpu_compile.rs @@ -16,8 +16,18 @@ //! 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)] +//! nLineBatches × (start, count, r, g, b, a, strokeMm, screenPx), +//! nDashInst, nDashBatches, nDashBatches × (start, count, r, g, b, a, strokeMm, lineAt)] +//! danach (hinter lineIdx): dashInst = nDashInst × 16 f32-Bits //! ``` +//! Gestrichelte Striche (Linien, Bögen, Kreise mit Strichmuster) gehen wie im Szenen-Pfad von +//! render2d (`DashSegment`, `DASH_LINE_WGSL`) je Segment als EINE Instanz an die Strich-Pipeline: +//! `[ax, ay, bx, by, s0, runLen, total, count, dash0..dash7]` in Bildschirm-Einheiten (Punkte relativ +//! zu `origin`), der Fragment-Shader setzt Striche/Lücken/runde Enden. Muster mit mehr als +//! [`MAX_LINE_DASH`] Einträgen (nach Verdoppeln) zerlegt weiter die CPU (`apply_dash_runs`). +//! Muster-Längen wie im Szenen-Pfad: Papier-mm × [`LINE_DASH_MM_TO_M`] (Referenz 1:100). +//! `lineAt` = Anzahl Linien-Indizes vor dem Strich-Batch: der Renderer zeichnet ihn vor dem ersten +//! Linien-Batch mit `start >= lineAt` (Maler-Reihenfolge; kein Linien-Batch überspannt ein `lineAt`). //! 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. @@ -49,6 +59,31 @@ pub struct LineBatch { pub screen_px: bool, } +/// Instanz-Bereich gestrichelter Segmente mit Farbe + Strichbreite (Papier-mm). +pub struct DashBatch { + pub start: u32, + pub count: u32, + pub color: Rgba, + pub stroke_mm: f64, + /// Linien-Indizes vor diesem Batch (Maler-Reihenfolge, s. Modulkopf). + pub line_at: u32, +} + +/// Höchstzahl Einträge eines Strichmusters im Shader (wie `render2d::MAX_LINE_DASH`). +pub const MAX_LINE_DASH: usize = 8; +/// f32 je Strich-Instanz (wie `DashInstance` in render2d: ab, run, dash[8]). +pub const DASH_INST_FLOATS: usize = 16; +/// Papier-mm → Modell-Meter für Linien-Strichmuster: `N/1000` bei der Referenz-Skala 1:100, wie der +/// Szenen-Pfad (`render2d::tessellate`, `DASH_MM_TO_M` dort). Schraffur-Striche nehmen die an die +/// Musterkachel gekoppelte `hatch::DASH_MM_TO_M`. +pub const LINE_DASH_MM_TO_M: f64 = 100.0 / 1000.0; + +/// Strichmuster einer Linie so umgerechnet, dass `hatch::apply_dash_runs` (rechnet mit +/// `hatch::DASH_MM_TO_M`) in [`LINE_DASH_MM_TO_M`] zerlegt. +fn line_dash_for_runs(dash: &[f64]) -> Vec { + dash.iter().map(|d| d * (LINE_DASH_MM_TO_M / DASH_MM_TO_M)).collect() +} + /// Ergebnis der Kompilierung (Bildschirm-Raum relativ zu `origin`). pub struct GpuOut { pub fill_pos: Vec, @@ -58,6 +93,9 @@ pub struct GpuOut { pub line_verts: Vec, pub line_idx: Vec, pub line_batches: Vec, + /// Strich-Instanzen ([`DASH_INST_FLOATS`] je Segment), s. Modulkopf. + pub dash_inst: Vec, + pub dash_batches: Vec, pub origin: (f64, f64), /// Modell-Bounds (Meter): (minX, minY, maxX, maxY), ±∞ wenn leer. pub bounds: (f64, f64, f64, f64), @@ -271,6 +309,8 @@ struct Compiler { line_verts: Vec, line_idx: Vec, line_batches: Vec, + dash_inst: Vec, + dash_batches: Vec, origin_x: f64, origin_y: f64, origin_set: bool, @@ -324,7 +364,9 @@ impl Compiler { } 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() { + // Nicht über einen dazwischen gezeichneten Strich-Batch hinweg zusammenfassen. + let dash_after = self.dash_batches.last().map_or(0, |d| d.line_at); + if let Some(last) = self.line_batches.last_mut().filter(|l| dash_after <= l.start) { if last.stroke_mm == stroke_mm && last.screen_px == screen_px && same_rgba(&last.color, &color) { last.count += count as u32; return; @@ -333,6 +375,97 @@ impl Compiler { self.line_batches.push(LineBatch { start: (self.line_idx.len() - count) as u32, count: count as u32, color, stroke_mm, screen_px }); } + fn add_dash_batch(&mut self, count: usize, color: Rgba, stroke_mm: f64) { + let line_at = self.line_idx.len() as u32; + if let Some(last) = self.dash_batches.last_mut() { + // Nur ohne Linien dazwischen (sonst ginge die Maler-Reihenfolge verloren). + if last.line_at == line_at && last.stroke_mm == stroke_mm && same_rgba(&last.color, &color) { + last.count += count as u32; + return; + } + } + let start = (self.dash_inst.len() / DASH_INST_FLOATS - count) as u32; + self.dash_batches.push(DashBatch { start, count: count as u32, color, stroke_mm, line_at }); + } + + /// Linienzug mit Strichmuster `dash` (Papier-mm): gültiges Muster bis [`MAX_LINE_DASH`] + /// Einträge → Shader-Instanzen; längeres → CPU-Zerlegung; ungültiges/fehlendes → durchgezogen. + fn stroke_styled(&mut self, pts_m: &[V2], closed: bool, dash: Option<&[f64]>, color: Rgba, stroke_mm: f64) { + let Some(d) = dash.filter(|d| !d.is_empty()) else { + return self.stroke_polyline(pts_m, closed, color, stroke_mm, false); + }; + match dash_cycle_m(d) { + Some(cycle) if cycle.len() <= MAX_LINE_DASH => self.stroke_dashed(pts_m, closed, &cycle, color, stroke_mm), + Some(_) => { + let mut run = pts_m.to_vec(); + if closed && pts_m.len() > 2 { + run.push(pts_m[0]); + } + for piece in hatch::apply_dash_runs(vec![run], &line_dash_for_runs(d)) { + self.stroke_polyline(&piece, false, color, stroke_mm, false); + } + } + None => self.stroke_polyline(pts_m, closed, color, stroke_mm, false), + } + } + + /// Gestrichelter Linienzug (Modell-Meter) mit gültigem Zyklus `cycle_m` (Meter, gerade Länge): + /// je Segment eine Instanz mit Lauflänge, Phase über den ganzen Zug (wie `apply_dash_runs`); + /// Segmente kürzer als 1e-12 m entfallen. Ein geschlossener Zug wird um die Schlusskante ergänzt. + fn stroke_dashed(&mut self, pts_m: &[V2], closed: bool, cycle_m: &[f64], color: Rgba, stroke_mm: f64) { + if pts_m.len() < 2 { + return; + } + let close = closed && pts_m.len() > 2 && (pts_m[0].x != pts_m[pts_m.len() - 1].x || pts_m[0].y != pts_m[pts_m.len() - 1].y); + let n_seg = pts_m.len() - 1 + usize::from(close); + let seg = |i: usize| (pts_m[i], pts_m[(i + 1) % pts_m.len()]); + let mut run = 0.0f64; + for i in 0..n_seg { + let (a, b) = seg(i); + let l = hypot2(b.x - a.x, b.y - a.y); + if l >= 1e-12 { + run += l; + } + } + if !(run > 0.0) || !run.is_finite() { + return; + } + let mut dash = [0.0f32; MAX_LINE_DASH]; + for (d, c) in dash.iter_mut().zip(cycle_m) { + *d = (c * PX_PER_M) as f32; + } + let total: f64 = cycle_m.iter().sum::() * PX_PER_M; + let before = self.dash_inst.len(); + let mut s0 = 0.0f64; + for i in 0..n_seg { + let (a, b) = seg(i); + let l = hypot2(b.x - a.x, b.y - a.y); + if !(l >= 1e-12) { + continue; + } + let sa = self.scr(a); + let sb = self.scr(b); + self.track(a.x, a.y); + self.track(b.x, b.y); + self.dash_inst.extend_from_slice(&[ + sa.x as f32, + sa.y as f32, + sb.x as f32, + sb.y as f32, + (s0 * PX_PER_M) as f32, + (run * PX_PER_M) as f32, + total as f32, + cycle_m.len() as f32, + ]); + self.dash_inst.extend_from_slice(&dash); + s0 += l; + } + let n = (self.dash_inst.len() - before) / DASH_INST_FLOATS; + if n > 0 { + self.add_dash_batch(n, color, stroke_mm); + } + } + #[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 }; @@ -566,6 +699,18 @@ impl Compiler { } } +/// Strichmuster (Papier-mm) → Zyklus in Modell-Metern wie `split_dash` in render2d: negative Werte +/// zu 0, Nullen weg, ungerade Länge verdoppelt. `None` = kein gültiges Muster (durchgezogen). +fn dash_cycle_m(dash: &[f64]) -> Option> { + let pat: Vec = dash.iter().map(|&d| jsnum::max(0.0, d) * LINE_DASH_MM_TO_M).filter(|&d| d > 0.0).collect(); + if pat.is_empty() { + return None; + } + let cycle: Vec = if pat.len() % 2 == 0 { pat } else { [pat.as_slice(), pat.as_slice()].concat() }; + let total: f64 = cycle.iter().sum(); + (total > 1e-9 && total.is_finite()).then_some(cycle) +} + /// 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 { @@ -597,6 +742,8 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool) -> GpuOut { line_verts: Vec::new(), line_idx: Vec::new(), line_batches: Vec::new(), + dash_inst: Vec::new(), + dash_batches: Vec::new(), origin_x: 0.0, origin_y: 0.0, origin_set: false, @@ -617,7 +764,7 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool) -> GpuOut { 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 { + let Prim::Line { style, color, weight_mm, a, b, zigzag: None, motif: None, dash, .. } = &prims[i] else { i += 1; continue; }; @@ -640,7 +787,7 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool) -> GpuOut { } 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); + c.stroke_styled(&pts, false, dash.as_deref(), col, weight_or_default(*weight_mm)); for m in merged.iter_mut().take(j).skip(i) { *m = true; } @@ -677,7 +824,7 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool) -> GpuOut { } } } - Prim::Line { style, color, weight_mm, a, b, zigzag, motif, .. } => { + Prim::Line { style, color, weight_mm, a, b, zigzag, motif, dash, .. } => { let col = dim(color_or_ink(plan, *color), style); let w = weight_or_default(*weight_mm); if let Some((amp, wav)) = zigzag { @@ -687,10 +834,10 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool) -> GpuOut { 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); + c.stroke_styled(&[*a, *b], false, dash.as_deref(), col, w); } } - Prim::Arc { style, color, weight_mm, center, from, to, r, .. } => { + Prim::Arc { style, color, weight_mm, center, from, to, r, dash } => { 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); @@ -710,13 +857,13 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool) -> GpuOut { 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); + c.stroke_styled(&arc_pts, false, dash.as_deref(), col, stroke_mm); } - 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::Circle { style, fill, stroke, weight_mm, center, r, dash } => { + draw_circle_like(&mut c, plan, style, Some(*fill), *stroke, *weight_mm, *center, *r, None, px_per_meter, dash.as_deref()); } - 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); + Prim::DrawingArc { style, stroke, weight_mm, center, r, a0, a1, dash } => { + draw_circle_like(&mut c, plan, style, None, *stroke, *weight_mm, *center, *r, Some((*a0, *a1)), px_per_meter, dash.as_deref()); } } } @@ -728,6 +875,8 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool) -> GpuOut { line_verts: c.line_verts, line_idx: c.line_idx, line_batches: c.line_batches, + dash_inst: c.dash_inst, + dash_batches: c.dash_batches, origin: (c.origin_x, c.origin_y), bounds: (c.min_x, c.min_y, c.max_x, c.max_y), } @@ -746,6 +895,7 @@ fn draw_circle_like( r: f64, arc: Option<(f64, f64)>, px_per_meter: f64, + dash: Option<&[f64]>, ) { let stroke_col = dim(color_or_ink(plan, stroke), style); let stroke_mm = weight_or_default(weight_mm); @@ -776,7 +926,7 @@ fn draw_circle_like( } } } - c.stroke_polyline(&pts, fill.is_some(), stroke_col, stroke_mm, false); + c.stroke_styled(&pts, fill.is_some(), dash, stroke_col, stroke_mm); } /// Flache Ausgabe (s. Modulkopf) für die Primitive `[from, to)` eines Plan-Puffers (v2); leer bei @@ -813,7 +963,12 @@ pub fn compile_flat(bytes: &[u8], from: usize, to: usize, px_per_meter: f64, pac 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()); + meta.push((o.dash_inst.len() / DASH_INST_FLOATS) as f64); + meta.push(o.dash_batches.len() as f64); + for b in &o.dash_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, b.line_at as f64]); + } + 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() + o.dash_inst.len()); out.push(meta.len() as u32); out.push(0); for m in &meta { @@ -825,6 +980,7 @@ pub fn compile_flat(bytes: &[u8], from: usize, to: usize, px_per_meter: f64, pac out.extend_from_slice(&o.fill_idx); out.extend_from_slice(&o.line_verts); out.extend_from_slice(&o.line_idx); + out.extend(o.dash_inst.iter().map(|v| v.to_bits())); out } @@ -847,6 +1003,7 @@ mod tests { chain, zigzag: None, motif: None, + dash: None, } } @@ -926,8 +1083,8 @@ mod tests { #[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 }, - 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 }, + Prim::Circle { style: st(), fill: 1, stroke: 0, weight_mm: 0.0, center: v2(1.0, 1.0), r: 1.0, dash: None }, + 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: None }, Prim::Placeholder, ]); let o = compile(&p, 0.0, false); @@ -960,4 +1117,189 @@ mod tests { assert!(compile_flat(&enc, 0, 2, 90.0, true).is_empty(), "Bereich ausserhalb"); assert!(!compile_flat(&enc, 1, 1, 90.0, true).is_empty(), "leerer Bereich = leere Geometrie"); } + // --- Strichmuster im Shader (Chunk-Pfad, gleiche Instanzen wie render2d `DashSegment`) --- + + fn dashed(ax: f64, bx: f64, chain: bool, dash: Vec) -> Prim { + Prim::Line { style: st(), color: 0, weight_mm: 0.25, a: v2(ax, 0.0), b: v2(bx, 0.0), chain, zigzag: None, motif: None, dash: Some(dash) } + } + + /// Instanz `i` als (a, b, s0, run_len, total, count, dash[8]). + fn inst(o: &GpuOut, i: usize) -> &[f32] { + &o.dash_inst[i * DASH_INST_FLOATS..(i + 1) * DASH_INST_FLOATS] + } + + #[test] + fn gestrichelte_linie_als_shader_instanz() { + let o = compile(&plan(vec![dashed(1.0, 4.0, false, vec![0.12, 0.08])]), 90.0, true); + assert!(o.line_idx.is_empty() && o.line_verts.is_empty(), "keine durchgezogenen Striche mehr"); + assert_eq!(o.dash_inst.len(), DASH_INST_FLOATS); + let d = inst(&o, 0); + // Bildschirm-Raum relativ zum Ursprung (erster Punkt). + assert_eq!(o.origin, (90.0, -0.0)); + assert_eq!(&d[..4], &[0.0, 0.0, 270.0, 0.0]); + assert_eq!((d[4], d[5], d[7]), (0.0, 270.0, 2.0)); + let (on, off) = ((0.12 * LINE_DASH_MM_TO_M * PX_PER_M) as f32, (0.08 * LINE_DASH_MM_TO_M * PX_PER_M) as f32); + assert_eq!((d[8], d[9]), (on, off)); + assert!((d[6] - (on + off)).abs() < 1e-4); + assert!(d[10..].iter().all(|&v| v == 0.0)); + assert_eq!(o.dash_batches.len(), 1); + assert_eq!((o.dash_batches[0].start, o.dash_batches[0].count, o.dash_batches[0].stroke_mm), (0, 1, 0.25)); + assert_eq!(o.bounds, (1.0, 0.0, 4.0, 0.0)); + } + + #[test] + fn gestrichelter_zug_phase_laeuft_durch() { + // Verkettete Linien: ein Zug, Phase über die Ecke, ungerades Muster verdoppelt. + let o = compile(&plan(vec![dashed(0.0, 1.0, false, vec![1.0]), dashed(1.0, 3.0, true, vec![1.0])]), 90.0, true); + assert_eq!(o.dash_inst.len(), 2 * DASH_INST_FLOATS); + assert_eq!(inst(&o, 1)[4], 90.0); + assert_eq!(inst(&o, 1)[5], 270.0); + assert_eq!(inst(&o, 1)[7], 2.0); + assert_eq!(o.dash_batches.len(), 1); + assert_eq!(o.dash_batches[0].count, 2); + // Einzeln (nicht verkettet): jede Linie beginnt ihr Muster neu. + let o = compile(&plan(vec![dashed(0.0, 1.0, false, vec![1.0]), dashed(1.0, 3.0, false, vec![1.0])]), 90.0, true); + assert_eq!(inst(&o, 1)[4], 0.0); + assert_eq!(inst(&o, 1)[5], 180.0); + } + + #[test] + fn ungueltiges_muster_durchgezogen_langes_muster_zerlegt() { + let solid = compile(&plan(vec![line(0.0, 1.0, false)]), 90.0, true); + let o = compile(&plan(vec![dashed(0.0, 1.0, false, vec![0.0, -1.0])]), 90.0, true); + assert!(o.dash_inst.is_empty()); + assert_eq!(o.line_idx.len(), solid.line_idx.len(), "Nullmuster = durchgezogen"); + let o = compile(&plan(vec![dashed(0.0, 1.0, false, vec![])]), 90.0, true); + assert!(o.dash_inst.is_empty() && o.line_idx.len() == solid.line_idx.len()); + // 9 Einträge → verdoppelt 18 > MAX_LINE_DASH: CPU-Zerlegung (mehrere Stücke). + let o = compile(&plan(vec![dashed(0.0, 1.0, false, vec![1.0; 9])]), 90.0, true); + assert!(o.dash_inst.is_empty()); + assert!(o.line_idx.len() > 2 * solid.line_idx.len()); + } + + #[test] + fn gestrichelte_boegen_und_kreise() { + let d = Some(vec![2.0, 1.0]); + let p = plan(vec![ + Prim::Arc { style: st(), color: 0, weight_mm: 0.18, center: v2(0.0, 0.0), from: v2(1.0, 0.0), to: v2(0.0, 1.0), r: 1.0, dash: d.clone() }, + Prim::Circle { style: st(), fill: 1, stroke: 0, weight_mm: 0.18, center: v2(3.0, 0.0), r: 1.0, dash: d.clone() }, + Prim::DrawingArc { style: st(), stroke: 0, weight_mm: 0.18, center: v2(0.0, 0.0), r: 2.0, a0: 0.0, a1: 1.0, dash: d }, + ]); + let o = compile(&p, 90.0, true); + assert!(o.line_idx.is_empty(), "alle Striche gestrichelt"); + assert!(!o.fill_idx.is_empty(), "Kreisfüllung bleibt"); + let n = o.dash_inst.len() / DASH_INST_FLOATS; + assert!(n > 20); + // Kreis: geschlossen, die Lauflänge reicht um den ganzen Umfang. + let circle_run = (0..n).map(|i| inst(&o, i)[5]).fold(0.0f32, f32::max); + assert!((circle_run as f64 - 2.0 * PI * PX_PER_M).abs() < 2.0, "Kreisumfang {circle_run}"); + // gleiche Farbe/Breite → ein Batch + assert_eq!(o.dash_batches.len(), 1); + assert_eq!(o.dash_batches[0].count as usize, n); + } + + /// Auf der Achse deckt eine Instanz genau die Stücke der CPU-Zerlegung (`apply_dash_runs`, + /// gleiche Semantik wie die frühere `split_dash`-Zerlegung in render2d): Spiegel des + /// Fragment-Shaders (`DASH_LINE_WGSL`) für y = 0 und Breite → 0. + #[test] + fn deckung_auf_der_achse_wie_zerlegung() { + let mut seed = 777u32; + let mut rnd = || { + seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); + (seed >> 8) as f64 / (1u32 << 24) as f64 + }; + for case in 0..150 { + let n = 1 + (rnd() * 4.0) as usize; + let pat: Vec = (0..n).map(|_| 0.5 + rnd() * 8.0).collect(); + // Zug aus 1–4 kollinearen Stücken entlang x. + let mut xs = vec![0.0]; + for _ in 0..1 + case % 4 { + xs.push(xs[xs.len() - 1] + 0.05 + rnd() * 1.5); + } + let prims: Vec = xs.windows(2).enumerate().map(|(i, w)| dashed(w[0], w[1], i > 0, pat.clone())).collect(); + let o = compile(&plan(prims), 90.0, true); + let runs = hatch::apply_dash_runs(vec![xs.iter().map(|&x| v2(x, 0.0)).collect()], &line_dash_for_runs(&pat)); + let total_len = xs[xs.len() - 1]; + for _ in 0..300 { + let x = rnd() * total_len; + let old = runs.iter().any(|r| x >= r[0].x - 1e-9 && x <= r[r.len() - 1].x + 1e-9); + let new = (0..o.dash_inst.len() / DASH_INST_FLOATS).any(|i| { + let d = inst(&o, i); + let sx = (x * PX_PER_M) as f32 - (d[0] + o.origin.0 as f32); + let (s0, s1) = (d[4], d[4] + (d[2] - d[0])); + let s = d[4] + sx; + if s < s0 || s > s1 { + return false; + } + let (total, cnt) = (d[6], d[7] as usize); + let k = (s / total).floor(); + let m = s - k * total; + let mut acc = 0.0f32; + let mut on = true; + for (j, &len) in d[8..8 + cnt].iter().enumerate() { + if m >= acc && m < acc + len { + on = j % 2 == 0; + } + acc += len; + } + on + }); + // An den Strichgrenzen entscheidet die Rundung — dort nicht vergleichen. + let near_edge = runs.iter().any(|r| (x - r[0].x).abs() < 1e-4 || (x - r[r.len() - 1].x).abs() < 1e-4); + assert!(old == new || near_edge, "Fall {case}: x={x} alt {old} neu {new}"); + } + } + } + + /// Maler-Reihenfolge: Linie, gestrichelte Linie, Linie (gleicher Stil) bleiben drei Batches in + /// dieser Folge — die zweite Linie deckt die gestrichelte (z. B. verdeckte Kante unter einer Wand). + #[test] + fn strich_batches_in_maler_reihenfolge() { + let o = compile(&plan(vec![line(0.0, 1.0, false), dashed(0.0, 1.0, false, vec![2.0, 1.0]), dashed(0.0, 2.0, false, vec![2.0, 1.0]), line(2.0, 3.0, false)]), 90.0, true); + assert_eq!(o.line_batches.len(), 2, "keine Zusammenfassung über den Strich-Batch hinweg"); + assert_eq!(o.dash_batches.len(), 1, "zwei gestrichelte ohne Linie dazwischen = ein Batch"); + assert_eq!(o.dash_batches[0].count, 2); + assert_eq!(o.dash_batches[0].line_at, o.line_batches[0].count); + assert_eq!(o.line_batches[1].start, o.dash_batches[0].line_at); + // Ohne Strich dazwischen werden gleich gestylte Linien weiter zusammengefasst. + let o = compile(&plan(vec![line(0.0, 1.0, false), line(2.0, 3.0, false)]), 90.0, true); + assert_eq!(o.line_batches.len(), 1); + } + + #[test] + fn flache_ausgabe_traegt_strich_instanzen() { + let mut w = plan_buf::Writer::new(false); + w.push(&crate::plan::prim::Primitive::Line { + a: crate::model::Vec2 { x: 0.0, y: 0.0 }, + b: crate::model::Vec2 { x: 2.0, y: 0.0 }, + cls: "c".into(), + weight_mm: 0.35, + dash: Some(Some(vec![3.0, 1.0])), + zigzag: None, + motif: None, + color: Some("#ff0000".into()), + drawing_id: None, + opening_id: None, + stair_id: None, + greyed: None, + opacity: None, + }); + let enc = w.finish(); + let out = compile_flat(&enc, 0, 1, 90.0, true); + let m = out[0] as usize; + let meta: Vec = (0..m).map(|i| f64::from_bits(out[2 + 2 * i] as u64 | ((out[3 + 2 * i] as u64) << 32))).collect(); + let (n_fill, n_line) = (meta[10] as usize, meta[11] as usize); + assert_eq!((n_fill, n_line), (0, 0)); + let k = 12 + 6 * n_fill + 8 * n_line; + assert_eq!(meta[k], 1.0, "eine Instanz"); + assert_eq!(meta[k + 1], 1.0, "ein Strich-Batch"); + assert_eq!(&meta[k + 2..k + 10], &[0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.35, 0.0]); + assert_eq!(meta.len(), k + 10); + let data = &out[2 + 2 * m..]; + let (nfp, nfi, nlv, nli) = (meta[6] as usize, meta[7] as usize, meta[8] as usize, meta[9] as usize); + let dash = &data[nfp + nfi + nlv + nli..]; + assert_eq!(dash.len(), DASH_INST_FLOATS); + assert_eq!(f32::from_bits(dash[2]), 180.0); + assert_eq!(f32::from_bits(dash[7]), 2.0); + } } diff --git a/src-tauri/core/src/plan_buf.rs b/src-tauri/core/src/plan_buf.rs index 25c0215c..22e90843 100644 --- a/src-tauri/core/src/plan_buf.rs +++ b/src-tauri/core/src/plan_buf.rs @@ -162,6 +162,8 @@ pub enum Prim { chain: bool, zigzag: Option<(f64, f64)>, motif: Option, + /// Strichmuster (Papier-mm, wie im Puffer); `None` = durchgezogen. + dash: Option>, }, Arc { style: Style, @@ -171,6 +173,7 @@ pub enum Prim { from: V2, to: V2, r: f64, + dash: Option>, }, Circle { style: Style, @@ -179,6 +182,7 @@ pub enum Prim { weight_mm: f64, center: V2, r: f64, + dash: Option>, }, DrawingArc { style: Style, @@ -188,6 +192,7 @@ pub enum Prim { r: f64, a0: f64, a1: f64, + dash: Option>, }, } @@ -747,6 +752,10 @@ impl<'a> View<'a> { let rec = self.rec(i)?; let greyed = rec.flags & F_GREYED != 0; let f = &rec.f; + let dash = match rec.dash { + Some((o, n)) => Some(self.pool(o, n)?), + None => None, + }; let p = match rec.tag { T_POLYGON => { let style = Style { greyed, opacity: opt(rec.flags, F_OPACITY, f[4]) }; @@ -793,23 +802,24 @@ impl<'a> View<'a> { chain: i > from && rec.flags & F_CHAIN != 0, zigzag: rec.zigzag, motif, + dash, } } T_ARC => { let style = Style { greyed, opacity: opt(rec.flags, F_OPACITY, f[3]) }; let c = color(&mut out, f[1])?; - Prim::Arc { style, color: c, weight_mm: f[2], center: V2 { x: f[4], y: f[5] }, from: V2 { x: f[6], y: f[7] }, to: V2 { x: f[8], y: f[9] }, r: f[10] } + Prim::Arc { style, color: c, weight_mm: f[2], center: V2 { x: f[4], y: f[5] }, from: V2 { x: f[6], y: f[7] }, to: V2 { x: f[8], y: f[9] }, r: f[10], dash } } T_CIRCLE => { let style = Style { greyed, opacity: opt(rec.flags, F_OPACITY, f[3]) }; let fill = color(&mut out, f[0])?; let stroke = color(&mut out, f[1])?; - Prim::Circle { style, fill, stroke, weight_mm: f[2], center: V2 { x: f[4], y: f[5] }, r: f[6] } + Prim::Circle { style, fill, stroke, weight_mm: f[2], center: V2 { x: f[4], y: f[5] }, r: f[6], dash } } T_DRAWING_ARC => { let style = Style { greyed, opacity: opt(rec.flags, F_OPACITY, f[2]) }; let stroke = color(&mut out, f[0])?; - Prim::DrawingArc { style, stroke, weight_mm: f[1], center: V2 { x: f[3], y: f[4] }, r: f[5], a0: f[6], a1: f[7] } + Prim::DrawingArc { style, stroke, weight_mm: f[1], center: V2 { x: f[3], y: f[4] }, r: f[5], a0: f[6], a1: f[7], dash } } _ => Prim::Placeholder, }; diff --git a/src-tauri/render2d/src/bin/render_png.rs b/src-tauri/render2d/src/bin/render_png.rs index aee3c943..10e0705e 100644 --- a/src-tauri/render2d/src/bin/render_png.rs +++ b/src-tauri/render2d/src/bin/render_png.rs @@ -4,9 +4,12 @@ // Session funktioniert. // // Start: cargo run --features headless --bin render_png -- [--out PFAD] [--width N] [--height N] -// [--scene szene.bin] [--crop x0,y0,x1,y1] [--scale N] +// [--scene szene.bin | --chunks a.bin,b.bin…] [--bounds minX,minY,maxX,maxY] [--crop x0,y0,x1,y1] [--scale N] // `--scene`: Szene-Bytes wie für `set_scene_bin` (statt der Demo); Ausschnitt = Ausmass der Szene, // `--crop` wählt daraus einen Teil (Anteile 0..1, y von oben), `--scale` den Papier-Massstab 1:N. +// `--chunks`: GPU-Chunks (je Datei die u32-Ausgabe von `gpu_compile_flat`, gepackt) über den +// Chunk-Renderer des nativen macOS-Pfads (`chunks.rs`); Ausschnitt = Vereinigung der Chunk-Ausmasse. +// `--bounds` (Modell-Meter) ersetzt das Ausmass — für deckungsgleiche Vergleiche Szene ↔ Chunks. #![cfg(feature = "headless")] use render2d::headless::HeadlessRenderer; @@ -21,6 +24,8 @@ fn main() { let mut scene_file: Option = None; let mut crop = [0.0f32, 0.0, 1.0, 1.0]; let mut paper_n = 100.0f32; + let mut chunk_files: Vec = Vec::new(); + let mut bounds_arg: Option<[f32; 4]> = None; let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { @@ -39,6 +44,13 @@ fn main() { } "--out" => out = args.next().unwrap_or(out), "--scene" => scene_file = args.next(), + "--chunks" => chunk_files = args.next().unwrap_or_default().split(',').filter(|f| !f.is_empty()).map(String::from).collect(), + "--bounds" => { + let v: Vec = args.next().unwrap_or_default().split(',').filter_map(|x| x.parse().ok()).collect(); + if v.len() == 4 { + bounds_arg = Some([v[0], v[1], v[2], v[3]]); + } + } "--scale" => paper_n = args.next().and_then(|v| v.parse().ok()).unwrap_or(paper_n), "--crop" => { let v: Vec = args.next().unwrap_or_default().split(',').filter_map(|x| x.parse().ok()).collect(); @@ -51,18 +63,41 @@ fn main() { } let mut renderer = HeadlessRenderer::new().expect("Headless-Renderer initialisieren"); + // Ausmass (Modell-Meter) → Bildschirm-Raum (x·90, −y·90), dann der Ausschnitt. + let view_of = |b: [f32; 4]| { + let (x0, x1) = (b[0] * 90.0, b[2] * 90.0); + let (y0, y1) = (-b[3] * 90.0, -b[1] * 90.0); + let (w, h) = (x1 - x0, y1 - y0); + ViewBox::new(x0 + crop[0] * w, y0 + crop[1] * h, (crop[2] - crop[0]) * w, (crop[3] - crop[1]) * h) + }; + if !chunk_files.is_empty() { + let chunks: Vec> = chunk_files + .iter() + .map(|f| std::fs::read(f).expect("Chunk lesen").chunks_exact(4).map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect()) + .collect(); + let b = bounds_arg.unwrap_or_else(|| { + let mut b = [f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY]; + for c in &chunks { + if let Some(cb) = render2d::headless::chunk_flat_bounds(c) { + b = [b[0].min(cb[0] as f32), b[1].min(cb[1] as f32), b[2].max(cb[2] as f32), b[3].max(cb[3] as f32)]; + } + } + b + }); + let vb = view_of(b); + let view = render2d::chunks::View { x: vb.x as f64, y: vb.y as f64, w: vb.w as f64, h: vb.h as f64 }; + let image = renderer.render_chunks_to_image(&chunks, width, height, view, paper_n as f64).expect("Chunks rendern"); + std::fs::write(&out, image.encode_png()).expect("PNG schreiben"); + println!("render_png: Chunks geschrieben nach {out} ({width}x{height})"); + return; + } let (scene, view_box) = match &scene_file { None => (demo_scene(), initial_view_box()), Some(f) => { let bytes = std::fs::read(f).expect("Szene lesen"); let scene = render2d::scene_bin::decode_scene(&bytes).expect("Szene dekodieren"); - // Ausmass (Modell-Meter) → Bildschirm-Raum (x·90, −y·90), dann der Ausschnitt. - let b = render2d::compile_scene(&scene).bounds; - let (x0, x1) = (b[0] * 90.0, b[2] * 90.0); - let (y0, y1) = (-b[3] * 90.0, -b[1] * 90.0); - let (w, h) = (x1 - x0, y1 - y0); - let vb = ViewBox::new(x0 + crop[0] * w, y0 + crop[1] * h, (crop[2] - crop[0]) * w, (crop[3] - crop[1]) * h); - (scene, vb) + let b = bounds_arg.unwrap_or_else(|| render2d::compile_scene(&scene).bounds); + (scene, view_of(b)) } }; let image = renderer.render_to_image(&scene, width, height, view_box, paper_n); diff --git a/src-tauri/render2d/src/chunks.rs b/src-tauri/render2d/src/chunks.rs index ead6bbaf..a58c4cfd 100644 --- a/src-tauri/render2d/src/chunks.rs +++ b/src-tauri/render2d/src/chunks.rs @@ -7,6 +7,12 @@ // // Linien-Vertices kommen KOMPAKT (12 Byte, s. LINE_PACKED_WGSL). // +// Gestrichelte Striche kommen als Instanzen (je Segment 16 x f32, Format wie +// `DashSegment`/`gpu::DashInstance`) und laufen durch DIESELBE Strich-Pipeline wie +// der Szenen-Pfad (`DASH_LINE_WGSL`: Striche, Luecken, runde Enden im Fragment- +// Shader). Innerhalb eines Chunks in Maler-Reihenfolge mit den Linien verzahnt +// (`DashBatch::line_at`), damit spaetere Striche fruehere gestrichelte decken. +// // Die Webview kompiliert weiterhin (Cache/Chunk-Logik bleibt in TypeScript) und // schickt nur noch die Puffer-BYTES je Chunk einmalig; pro Frame geht nur der // Ausschnitt (viewBox) hierher. Rust haelt die Puffer — kein JSON, kein @@ -17,7 +23,7 @@ use std::collections::HashMap; use bytemuck::{Pod, Zeroable}; use wgpu::util::DeviceExt; -use crate::shaders::FILL_WGSL; +use crate::shaders::{DASH_LINE_WGSL, FILL_WGSL}; /// Graustufe fuer gedimmte Linien (== GREY_RGB in glPlanCompile.ts). const GREY: f32 = 0.549; @@ -175,6 +181,40 @@ pub struct LineBatch { pub device_px: bool, } +/// Instanz-Bereich gestrichelter Segmente (Strich-Pipeline) mit Farbe + Papier-mm. +#[derive(Clone, Debug, serde::Deserialize)] +pub struct DashBatch { + pub start: u32, + pub count: u32, + pub color: [f32; 4], + pub stroke_mm: f32, + /// Maler-Reihenfolge: gezeichnet vor dem ersten Linien-Batch mit `start >= line_at` + /// (Linien-Index-Position beim Erzeugen; kein Linien-Batch ueberspannt sie). + #[serde(default)] + pub line_at: u32, +} + +/// Zeichenfolge der Striche eines Chunks: (gestrichelt?, Batch-Index), Linien und +/// gestrichelte Batches nach `line_at` verzahnt. Fehlen die Puffer einer Art, entfaellt sie. +fn stroke_order(g: &ChunkGeom) -> Vec<(bool, usize)> { + let lines = if g.line_vtx.is_some() && g.line_idx.is_some() { g.line_batches.len() } else { 0 }; + let dashes = if g.dash_inst.is_some() { g.dash_batches.len() } else { 0 }; + let mut out = Vec::with_capacity(lines + dashes); + let mut j = 0; + for i in 0..lines { + while j < dashes && g.dash_batches[j].line_at <= g.line_batches[i].start { + out.push((true, j)); + j += 1; + } + out.push((false, i)); + } + out.extend((j..dashes).map(|k| (true, k))); + out +} + +/// Bytes je Strich-Instanz (16 x f32: ab, run, dash[8]; wie `gpu::DashInstance`). +pub const DASH_INSTANCE_BYTES: u64 = 16 * 4; + /// Ein Chunk (== `GpuGeometry` der Webview): Puffer-IDs statt GL-Puffer. #[derive(Clone, Debug, serde::Deserialize)] pub struct ChunkGeom { @@ -184,6 +224,11 @@ pub struct ChunkGeom { pub line_vtx: Option, pub line_idx: Option, pub line_batches: Vec, + /// Puffer der Strich-Instanzen (gestrichelte Segmente); fehlt ohne Strichmuster. + #[serde(default)] + pub dash_inst: Option, + #[serde(default)] + pub dash_batches: Vec, pub origin: [f64; 2], #[serde(default)] pub greyed: bool, @@ -201,6 +246,7 @@ pub struct View { pub struct ChunkRenderer { fill_pipeline: wgpu::RenderPipeline, line_pipeline: wgpu::RenderPipeline, + dash_pipeline: wgpu::RenderPipeline, bind_group_layout: wgpu::BindGroupLayout, uniform: Option<(wgpu::Buffer, wgpu::BindGroup, u64)>, buffers: HashMap, @@ -338,6 +384,20 @@ impl ChunkRenderer { }, "chunks.line.pipeline", ); + // Gestrichelte Segmente: Instanz-Puffer, Quad aus `vertex_index` (wie gpu.rs). + let dash_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("chunks.dash"), + source: wgpu::ShaderSource::Wgsl(DASH_LINE_WGSL.into()), + }); + let dash_pipeline = make( + &dash_module, + wgpu::VertexBufferLayout { + array_stride: DASH_INSTANCE_BYTES, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &wgpu::vertex_attr_array![0 => Float32x4, 1 => Float32x4, 2 => Float32x4, 3 => Float32x4], + }, + "chunks.dash.pipeline", + ); let text_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("chunks.text"), source: wgpu::ShaderSource::Wgsl(TEXT_WGSL.into()), @@ -387,6 +447,7 @@ impl ChunkRenderer { inst_buf: None, fill_pipeline, line_pipeline, + dash_pipeline, bind_group_layout, uniform: None, buffers: HashMap::new(), @@ -567,20 +628,20 @@ impl ChunkRenderer { blocks.push(Globals { view_proj: proj, color: c, viewport_px: vp, stroke_px: 0.0, stroke_scale: 1.0 }); } } - for g in self.layout.iter().chain(self.highlight.iter()) { - if g.line_vtx.is_none() || g.line_idx.is_none() { - continue; - } + // Striche (Linien + gestrichelte) je Chunk in Maler-Reihenfolge (`stroke_order`). + let orders: Vec> = self.layout.iter().chain(self.highlight.iter()).map(stroke_order).collect(); + for (g, order) in self.layout.iter().chain(self.highlight.iter()).zip(&orders) { let proj = projection(bounds, g.origin); - for b in &g.line_batches { - let c = if g.greyed { [GREY, GREY, GREY, b.color[3]] } else { b.color }; - blocks.push(Globals { - view_proj: proj, - color: c, - viewport_px: vp, - stroke_px: b.stroke_mm, - stroke_scale: if b.device_px { 1.0 } else if b.screen_px { meet as f32 } else { mm_px as f32 }, - }); + for &(dashed, k) in order { + let (color, stroke_mm, scale) = if dashed { + let b = &g.dash_batches[k]; + (b.color, b.stroke_mm, mm_px as f32) + } else { + let b = &g.line_batches[k]; + (b.color, b.stroke_mm, if b.device_px { 1.0 } else if b.screen_px { meet as f32 } else { mm_px as f32 }) + }; + let c = if g.greyed { [GREY, GREY, GREY, color[3]] } else { color }; + blocks.push(Globals { view_proj: proj, color: c, viewport_px: vp, stroke_px: stroke_mm, stroke_scale: scale }); } } @@ -719,19 +780,55 @@ impl ChunkRenderer { block += 1; } } - pass.set_pipeline(&self.line_pipeline); - for g in self.layout.iter().chain(self.highlight.iter()) { - let (Some(p), Some(i)) = (g.line_vtx, g.line_idx) else { continue }; - let (Some(pb), Some(ib)) = (self.buffers.get(&p), self.buffers.get(&i)) else { - block += g.line_batches.len() as u32; - continue; + // Striche je Chunk: Linien-Batches (indiziert) und gestrichelte Segmente (je + // Instanz ein Quad aus 6 Vertices) in Maler-Reihenfolge, Pipeline nur bei Wechsel. + let mut current: Option = None; + for (g, order) in self.layout.iter().chain(self.highlight.iter()).zip(&orders) { + let lines = match (g.line_vtx.and_then(|p| self.buffers.get(&p)), g.line_idx.and_then(|i| self.buffers.get(&i))) { + (Some(pb), Some(ib)) => Some((pb, ib)), + _ => None, }; - pass.set_vertex_buffer(0, pb.slice(..)); - pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32); - for b in &g.line_batches { - pass.set_bind_group(0, ubind, &[block * stride as u32]); - pass.draw_indexed(b.start..b.start + b.count, 0, 0..1); + let dash = g.dash_inst.and_then(|d| self.buffers.get(&d)); + let mut bound_lines = false; + let mut bound_dash = false; + for &(dashed, k) in order { + let this_block = block; block += 1; + if dashed { + let Some(db) = dash else { continue }; + if current != Some(true) { + pass.set_pipeline(&self.dash_pipeline); + current = Some(true); + bound_lines = false; + } + if !bound_dash { + pass.set_vertex_buffer(0, db.slice(..)); + bound_dash = true; + } + let b = &g.dash_batches[k]; + // Bereich gegen die Puffergroesse klemmen (fremde Angaben → nie ausserhalb lesen). + let n_inst = (db.size() / DASH_INSTANCE_BYTES) as u32; + let end = b.start.saturating_add(b.count).min(n_inst); + if b.start < end { + pass.set_bind_group(0, ubind, &[this_block * stride as u32]); + pass.draw(0..6, b.start..end); + } + } else { + let Some((pb, ib)) = lines else { continue }; + if current != Some(false) { + pass.set_pipeline(&self.line_pipeline); + current = Some(false); + bound_dash = false; + } + if !bound_lines { + pass.set_vertex_buffer(0, pb.slice(..)); + pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32); + bound_lines = true; + } + let b = &g.line_batches[k]; + pass.set_bind_group(0, ubind, &[this_block * stride as u32]); + pass.draw_indexed(b.start..b.start + b.count, 0, 0..1); + } } } // Text zuoberst. @@ -762,6 +859,35 @@ impl ChunkRenderer { mod tests { use super::*; + fn lb(start: u32) -> LineBatch { + LineBatch { start, count: 6, color: [0.0; 4], stroke_mm: 0.1, screen_px: false, device_px: false } + } + fn db(line_at: u32) -> DashBatch { + DashBatch { start: 0, count: 1, color: [0.0; 4], stroke_mm: 0.1, line_at } + } + + #[test] + fn striche_in_maler_reihenfolge() { + let g = ChunkGeom { + fill_pos: None, + fill_idx: None, + fill_batches: vec![], + line_vtx: Some(1), + line_idx: Some(2), + line_batches: vec![lb(0), lb(6), lb(12)], + dash_inst: Some(3), + dash_batches: vec![db(0), db(6), db(6), db(18)], + origin: [0.0, 0.0], + greyed: false, + }; + assert_eq!(stroke_order(&g), vec![(true, 0), (false, 0), (true, 1), (true, 2), (false, 1), (false, 2), (true, 3)]); + // Ohne Strich-Puffer: nur Linien; ohne Linien-Puffer: nur gestrichelte. + let only_lines = ChunkGeom { dash_inst: None, ..g.clone() }; + assert_eq!(stroke_order(&only_lines), vec![(false, 0), (false, 1), (false, 2)]); + let only_dash = ChunkGeom { line_idx: None, ..g }; + assert_eq!(stroke_order(&only_dash), vec![(true, 0), (true, 1), (true, 2), (true, 3)]); + } + #[test] fn projection_matches_ts_reference() { // viewBox 0,0,100,50 auf 200x100 px: keine Aspekt-Korrektur noetig. diff --git a/src-tauri/render2d/src/headless.rs b/src-tauri/render2d/src/headless.rs index 10e19e12..a8959602 100644 --- a/src-tauri/render2d/src/headless.rs +++ b/src-tauri/render2d/src/headless.rs @@ -17,6 +17,7 @@ use image::ImageEncoder; +use crate::chunks::{ChunkGeom, ChunkRenderer, DashBatch, FillBatch, LineBatch, View}; use crate::gpu::Renderer; use crate::types::{Scene, ViewBox}; @@ -156,6 +157,39 @@ impl HeadlessRenderer { } } + /// Rendert GPU-Chunks (je Eintrag die flache Ausgabe der Kern-Kompilierung + /// `gpu_compile_flat`, gepackte Linien-Vertices) ueber den Chunk-Renderer, den der + /// native macOS-Pfad benutzt (`chunks.rs`: dieselben Shader und dieselbe + /// Zeichenreihenfolge, nur ohne Metal-Flaeche). `view` in Bildschirm-Einheiten. + /// Fuer Headless-Vergleiche Chunk-Pfad gegen Szenen-Pfad. + pub fn render_chunks_to_image(&self, chunks: &[Vec], width: u32, height: u32, view: View, paper_scale_n: f64) -> Result { + let (width, height) = (width.max(1), height.max(1)); + let mut cr = ChunkRenderer::new(&self.device, COLOR_FORMAT, 4); + let mut layout = Vec::new(); + let mut next_id = 1u32; + for words in chunks { + let (geom, bufs) = chunk_from_flat(words, &mut next_id).ok_or("Chunk-Ausgabe unlesbar")?; + for (id, bytes) in bufs { + cr.upload(&self.device, id, &bytes); + } + layout.push(geom); + } + cr.set_layout(layout); + let texture = self.device.create_texture(&wgpu::TextureDescriptor { + label: Some("headless.chunks.target"), + size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: COLOR_FORMAT, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let tv = texture.create_view(&wgpu::TextureViewDescriptor::default()); + cr.render(&self.device, &self.queue, &tv, view, (width, height), paper_scale_n); + Ok(RgbaImage { width, height, pixels: self.read_pixels(&texture, width, height) }) + } + /// Texture -> gepolsterter Buffer -> straff gepacktes Pixel-Array (Row- /// Alignment-Falle, siehe Modul-Kopf). fn read_pixels(&self, texture: &wgpu::Texture, width: u32, height: u32) -> Vec { @@ -235,3 +269,142 @@ fn align_up(value: u32, align: u32) -> u32 { } ((value + align - 1) / align) * align } + +/// Modell-Ausmass (minX, minY, maxX, maxY, Meter) einer flachen Chunk-Ausgabe (`gpu_compile_flat`). +pub fn chunk_flat_bounds(words: &[u32]) -> Option<[f64; 4]> { + let meta = flat_meta(words)?; + (meta.len() >= 6).then(|| [meta[2], meta[3], meta[4], meta[5]]) +} + +fn flat_meta(words: &[u32]) -> Option> { + let m = *words.first()? as usize; + if words.len() < 2 + 2 * m { + return None; + } + Some((0..m).map(|i| f64::from_bits(words[2 + 2 * i] as u64 | ((words[3 + 2 * i] as u64) << 32))).collect()) +} + +/// Flache Kern-Ausgabe (Layout s. `core/src/gpu_compile.rs`, gepackt) → Layout-Eintrag + Puffer +/// (ID, Bytes) wie sie die Webview an den nativen Renderer schickt (`nativeGl.ts`). +pub fn chunk_from_flat(words: &[u32], next_id: &mut u32) -> Option<(ChunkGeom, Vec<(u32, Vec)>)> { + let meta = flat_meta(words)?; + if meta.len() < 12 { + return None; + } + let n = |v: f64| -> Option { (v >= 0.0 && v.fract() == 0.0).then_some(v as usize) }; + let (nfp, nfi, nlv, nli, nf, nl) = (n(meta[6])?, n(meta[7])?, n(meta[8])?, n(meta[9])?, n(meta[10])?, n(meta[11])?); + let mut k = 12; + let rgba = |m: &[f64]| [m[0] as f32, m[1] as f32, m[2] as f32, m[3] as f32]; + let mut fill_batches = Vec::new(); + for _ in 0..nf { + let b = meta.get(k..k + 6)?; + fill_batches.push(FillBatch { start: b[0] as u32, count: b[1] as u32, color: rgba(&b[2..6]) }); + k += 6; + } + let mut line_batches = Vec::new(); + for _ in 0..nl { + let b = meta.get(k..k + 8)?; + line_batches.push(LineBatch { start: b[0] as u32, count: b[1] as u32, color: rgba(&b[2..6]), stroke_mm: b[6] as f32, screen_px: b[7] == 1.0, device_px: false }); + k += 8; + } + let (nd, ndb) = (meta.get(k).copied().map(n).unwrap_or(Some(0))?, meta.get(k + 1).copied().map(n).unwrap_or(Some(0))?); + k += 2; + let mut dash_batches = Vec::new(); + for _ in 0..ndb { + let b = meta.get(k..k + 8)?; + dash_batches.push(DashBatch { start: b[0] as u32, count: b[1] as u32, color: rgba(&b[2..6]), stroke_mm: b[6] as f32, line_at: b[7] as u32 }); + k += 8; + } + let mut off = 2 + 2 * meta.len(); + let mut bufs = Vec::new(); + let mut take = |len: usize, off: &mut usize| -> Option> { + let w = words.get(*off..*off + len)?; + *off += len; + if len == 0 { + return Some(None); + } + let id = *next_id; + *next_id += 1; + bufs.push((id, w.iter().flat_map(|v| v.to_le_bytes()).collect::>())); + Some(Some(id)) + }; + let fill_pos = take(nfp, &mut off)?; + let fill_idx = take(nfi, &mut off)?; + let line_vtx = take(nlv, &mut off)?; + let line_idx = take(nli, &mut off)?; + let dash_inst = take(nd * 16, &mut off)?; + let geom = ChunkGeom { + fill_pos, + fill_idx, + fill_batches, + line_vtx, + line_idx, + line_batches, + dash_inst, + dash_batches, + origin: [meta[0], meta[1]], + greyed: false, + }; + Some((geom, bufs)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Flache Ausgabe wie `gpu_compile_flat` mit EINER gestrichelten Linie (Instanz) von + /// (0,0) nach (L,0) Bildschirm-Einheiten, Muster an/aus = `on`/`off`. + fn dashed_chunk(len: f32, on: f32, off: f32, stroke_mm: f64) -> Vec { + let mut meta: Vec = vec![0.0, 0.0, 0.0, 0.0, len as f64 / 90.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; + meta.extend_from_slice(&[1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, stroke_mm, 0.0]); + let mut out = vec![meta.len() as u32, 0]; + for m in &meta { + let b = m.to_bits(); + out.push(b as u32); + out.push((b >> 32) as u32); + } + let inst = [0.0, 0.0, len, 0.0, 0.0, len, on + off, 2.0, on, off, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0f32]; + out.extend(inst.iter().map(|v| v.to_bits())); + out + } + + /// Der Chunk-Renderer (nativer macOS-Pfad, hier ueber Vulkan/lavapipe) zeichnet Striche + /// und Luecken: entlang der Achse wechseln gedeckte und freie Pixel im Muster-Takt. + #[test] + fn chunk_renderer_zeichnet_striche_und_luecken() { + let r = match HeadlessRenderer::new() { + Ok(r) => r, + Err(e) => { + eprintln!("uebersprungen, kein Headless-Adapter: {e}"); + return; + } + }; + // 200 Einheiten lang, Muster 20 an / 20 aus; Ansicht 1:1 auf 200x40 px. + let chunk = dashed_chunk(200.0, 20.0, 20.0, 0.05); + let img = r + .render_chunks_to_image(&[chunk], 200, 40, View { x: 0.0, y: -20.0, w: 200.0, h: 40.0 }, 1000.0) + .expect("rendern"); + let px = |x: u32| { + let i = ((20 * img.width + x) * 4) as usize; + img.pixels[i] // Rot-Kanal: Linie schwarz -> 0, Hintergrund weiss -> 255 + }; + // Strich-Mitten (10, 50, 90 …) dunkel, Luecken-Mitten (30, 70, 110 …) hell. + for c in [10u32, 50, 90, 130, 170] { + assert!(px(c) < 80, "Strich bei x={c}: {}", px(c)); + } + for c in [30u32, 70, 110, 150] { + assert!(px(c) > 200, "Luecke bei x={c}: {}", px(c)); + } + } + + #[test] + fn flache_ausgabe_wird_gelesen() { + let mut id = 1; + let (g, bufs) = chunk_from_flat(&dashed_chunk(100.0, 5.0, 5.0, 0.35), &mut id).unwrap(); + assert_eq!(g.dash_inst, Some(1)); + assert_eq!(g.dash_batches.len(), 1); + assert_eq!(bufs[0].1.len(), 64); + assert!(g.line_vtx.is_none() && g.fill_pos.is_none()); + assert!(chunk_from_flat(&[5, 0, 1], &mut id).is_none()); + } +} diff --git a/src/plan/glPlan/glPlanChunks.ts b/src/plan/glPlan/glPlanChunks.ts index 5adb4d29..7434e684 100644 --- a/src/plan/glPlan/glPlanChunks.ts +++ b/src/plan/glPlan/glPlanChunks.ts @@ -165,6 +165,7 @@ function disposeGeometry(gl: BufferGl, g: GpuGeometry): void { gl.deleteBuffer(g.fill.indexBuffer); gl.deleteBuffer(g.line.vertexBuffer); gl.deleteBuffer(g.line.indexBuffer); + if (g.dash) gl.deleteBuffer(g.dash.instanceBuffer); } export interface ChunkStats { diff --git a/src/plan/glPlan/glPlanCompile.test.ts b/src/plan/glPlan/glPlanCompile.test.ts index 6abd4e61..611becd2 100644 --- a/src/plan/glPlan/glPlanCompile.test.ts +++ b/src/plan/glPlan/glPlanCompile.test.ts @@ -57,6 +57,25 @@ describe('compilePrimitivesToGpu: zusammenhängende Linien-Segmente', () => { }); }); +describe('compilePrimitivesToGpu: Strichmuster (Shader-Instanzen wie der Szenen-Pfad)', () => { + it('gestrichelte Linie wird EINE Strich-Instanz statt durchgezogener Striche', () => { + const uploads: ArrayBufferView[] = []; + const gl = { ...glStub, bufferData: (_t: number, d: ArrayBufferView) => uploads.push(d) } as unknown as WebGL2RenderingContext; + const dashed = { ...seg(0, 0, 2, 0, 'a'), dash: [3, 1] } as Primitive; + const g = compilePrimitivesToGpu(gl, [seg(0, 1, 1, 1, 'b'), dashed], 90); + expect(g.dash?.batches).toEqual([{ startInstance: 0, instanceCount: 1, color: [0, 0, 0, 1], strokeMm: 0.18, lineAt: g.line.batches[0].indexCount }]); + const inst = uploads[uploads.length - 1] as Float32Array; + expect(inst.length).toBe(16); + // Lauflänge des Zugs (Bildschirm-Einheiten) und Muster 3/1 mm × 0.1 m/mm × 90. + expect(inst[5]).toBeCloseTo(180, 4); + expect(Array.from(inst.slice(7, 10)).map((v) => +v.toFixed(4))).toEqual([2, 27, 9]); + }); + + it('ohne Strichmuster keine Strich-Geometrie', () => { + expect(compilePrimitivesToGpu(glStub, [seg(0, 0, 1, 0, 'a')], 90).dash).toBeUndefined(); + }); +}); + /** Summierte Dreiecksfläche (Betrag) aus Indizes über pts. */ function triArea(pts: Vec2[], idx: number[]): number { let area = 0; diff --git a/src/plan/glPlan/glPlanCompile.ts b/src/plan/glPlan/glPlanCompile.ts index d158d2c1..ab4fe77c 100644 --- a/src/plan/glPlan/glPlanCompile.ts +++ b/src/plan/glPlan/glPlanCompile.ts @@ -12,7 +12,7 @@ import type { Primitive } from '../generatePlan'; import type { Vec2 } from '../../model/types'; -import type { BufferGl, GpuGeometry, Rgba } from './glPlanTypes'; +import type { BufferGl, DashBatch, GpuGeometry, Rgba } from './glPlanTypes'; import { encodePlanBuf, type DecodedPlanBuf } from '../planBuf'; import { core } from '../../engine/coreWasm'; @@ -94,6 +94,20 @@ function uploadCompiled(gl: BufferGl, out: Uint32Array): GpuGeometry { screenPx: meta[k + 7] === 1, }); } + // Strich-Instanzen (hinter den Linien-Batches; ältere Ausgaben ohne diesen Teil → keine). + const nDash = k < m ? meta[k] : 0; + const nDashBatches = k + 1 < m ? meta[k + 1] : 0; + k += 2; + const dashBatches: DashBatch[] = []; + for (let i = 0; i < nDashBatches; i++, k += 8) { + dashBatches.push({ + startInstance: meta[k], + instanceCount: meta[k + 1], + color: [meta[k + 2], meta[k + 3], meta[k + 4], meta[k + 5]] as Rgba, + strokeMm: meta[k + 6], + lineAt: meta[k + 7], + }); + } let off = out.byteOffset + 8 + m * 8; const fillPos = new Float32Array(out.buffer, off, nFillPos); off += nFillPos * 4; @@ -103,6 +117,8 @@ function uploadCompiled(gl: BufferGl, out: Uint32Array): GpuGeometry { const lineVerts = new Uint32Array(out.buffer, off, nLineVerts); off += nLineVerts * 4; const lineIdx = new Uint32Array(out.buffer, off, nLineIdx); + off += nLineIdx * 4; + const dashInst = new Float32Array(out.buffer, off, nDash * 16); const upload = (target: number, data: ArrayBufferView & { length: number }): WebGLBuffer | null => { if (!data.length) return null; @@ -123,6 +139,7 @@ function uploadCompiled(gl: BufferGl, out: Uint32Array): GpuGeometry { indexBuffer: upload(gl.ELEMENT_ARRAY_BUFFER, lineIdx), batches: lineBatches, }, + ...(nDash > 0 ? { dash: { instanceBuffer: upload(gl.ARRAY_BUFFER, dashInst), batches: dashBatches } } : {}), origin: { x: originX, y: originY }, bounds: { minX: isFinite(minX) ? minX : 0, diff --git a/src/plan/glPlan/glPlanTypes.ts b/src/plan/glPlan/glPlanTypes.ts index 59c82048..3b2bcc44 100644 --- a/src/plan/glPlan/glPlanTypes.ts +++ b/src/plan/glPlan/glPlanTypes.ts @@ -99,10 +99,32 @@ export interface GpuGeometry { indexBuffer: WebGLBuffer | null; batches: LineBatch[]; }; + /** + * Gestrichelte Striche: je Segment EINE Instanz (16 × f32: ax, ay, bx, by, s0, runLen, total, + * count, dash0..7 in Bildschirm-Einheiten relativ zu `origin`); Striche/Lücken setzt der + * Fragment-Shader (`DASH_LINE_WGSL` in render2d). Fehlt bei Geometrie ohne Strichmuster. + */ + dash?: { + instanceBuffer: WebGLBuffer | null; + batches: DashBatch[]; + }; /** Modell-Bounds (Meter) für Debug/Einpassen; nicht render-kritisch. */ bounds: { minX: number; minY: number; maxX: number; maxY: number }; } +/** Ein Strich-Batch: Instanz-Bereich mit Farbe + Papier-Strichbreite (mm). */ +export interface DashBatch { + startInstance: number; + instanceCount: number; + color: Rgba; + strokeMm: number; + /** + * Maler-Reihenfolge: Anzahl Linien-Indizes vor diesem Batch — gezeichnet vor dem ersten + * Linien-Batch mit `startIndex >= lineAt` (kein Linien-Batch überspannt diese Stelle). + */ + lineAt: number; +} + /** Rechteckiger Ausschnitt in Bildschirm-Einheiten (viewBox). */ export interface ViewBox { x: number; diff --git a/src/views/plan/nativeGl.ts b/src/views/plan/nativeGl.ts index 00fbc598..d5c67b60 100644 --- a/src/views/plan/nativeGl.ts +++ b/src/views/plan/nativeGl.ts @@ -24,6 +24,9 @@ export interface NativeChunkLayout { line_vtx: number | null; line_idx: number | null; line_batches: { start: number; count: number; color: number[]; stroke_mm: number; screen_px: boolean; device_px?: boolean }[]; + /** Strich-Instanzen (gestrichelte Segmente, `DASH_LINE_WGSL`), s. `GpuGeometry.dash`. */ + dash_inst?: number | null; + dash_batches?: { start: number; count: number; color: number[]; stroke_mm: number; line_at: number }[]; origin: [number, number]; greyed: boolean; } @@ -193,6 +196,14 @@ export class NativeGl implements BufferGl { stroke_mm: b.strokeMm, screen_px: !!b.screenPx, })), + dash_inst: id(g.dash?.instanceBuffer ?? null), + dash_batches: (g.dash?.batches ?? []).map((b) => ({ + start: b.startInstance, + count: b.instanceCount, + color: b.color, + stroke_mm: b.strokeMm, + line_at: b.lineAt, + })), origin: [g.origin?.x ?? 0, g.origin?.y ?? 0] as [number, number], greyed: !!g.greyed, }; diff --git a/src/views/plan/useNativePlanRenderer.ts b/src/views/plan/useNativePlanRenderer.ts index 687a1656..effc5b68 100644 --- a/src/views/plan/useNativePlanRenderer.ts +++ b/src/views/plan/useNativePlanRenderer.ts @@ -237,6 +237,7 @@ export function useNativePlanRenderer( gl.deleteBuffer(old.fill.indexBuffer); gl.deleteBuffer(old.line.vertexBuffer); gl.deleteBuffer(old.line.indexBuffer); + if (old.dash) gl.deleteBuffer(old.dash.instanceBuffer); highlightGeom.current = null; } if (prims.length) { From 6da3f4b3c12ed7f76e277fc61c1cc7dbd070f98d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 12:26:20 +0000 Subject: [PATCH 2/2] =?UTF-8?q?[14][12]=20Kaputte=20Projekte:=20keine=20Ab?= =?UTF-8?q?frage=20wirft=20mehr,=20validate=20warnt=20vor=20h=C3=A4ngenden?= =?UTF-8?q?=20Verweisen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Kern fällt bei hängenden Wandtypen/Bauteilen/Schraffuren/Linienstilen/Deckentypen auf Vorgaben zurück (Plan, Schnitt, Ansicht, 3D, IFC, Mesh); typisierte Sicht tolerant (model/lenient.rs: nur der Wert, der nicht passt, fällt auf die Vorgabe); Mesh-Export verwirft gebrochene Indizes/NaN-Ecken; projectWarnings (project_refs.rs) für dossier-cli/MCP validate. Fuzz-Test src/core/robustness.test.ts. --- TODO.md | 19 ++ src-tauri/core/src/document.rs | 19 +- src-tauri/core/src/ifc_data.rs | 23 +- src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/mesh_data.rs | 23 +- src-tauri/core/src/model/helpers.rs | 29 ++ src-tauri/core/src/model/lenient.rs | 336 +++++++++++++++++++++++ src-tauri/core/src/model/mod.rs | 1 + src-tauri/core/src/model3d.rs | 35 +-- src-tauri/core/src/plan/domains.rs | 20 +- src-tauri/core/src/plan/drawings.rs | 8 +- src-tauri/core/src/plan/elevation.rs | 3 +- src-tauri/core/src/plan/section.rs | 20 +- src-tauri/core/src/plan/style.rs | 8 +- src-tauri/core/src/plan/walls.rs | 36 +-- src-tauri/core/src/project_refs.rs | 272 ++++++++++++++++++ src-tauri/core/src/style.rs | 7 +- src-tauri/core/src/web/mod.rs | 1 + src-tauri/core/src/web/project_refs.rs | 17 ++ src/cli/cli.test.ts | 14 + src/cli/main.ts | 6 +- src/cli/mcp.ts | 4 +- src/core/extra.ts | 1 + src/core/ops.ts | 10 + src/core/robustness.test.ts | 365 +++++++++++++++++++++++++ src/export/exportIfc.test.ts | 6 +- src/model/layoutModel.ts | 5 +- src/model/richProject.testing.ts | 154 +++++++++++ src/model/types.roundtrip.test.ts | 151 +--------- 29 files changed, 1323 insertions(+), 271 deletions(-) create mode 100644 src-tauri/core/src/model/lenient.rs create mode 100644 src-tauri/core/src/project_refs.rs create mode 100644 src-tauri/core/src/web/project_refs.rs create mode 100644 src/core/robustness.test.ts create mode 100644 src/model/richProject.testing.ts diff --git a/TODO.md b/TODO.md index 0273f656..62c0aca8 100644 --- a/TODO.md +++ b/TODO.md @@ -704,6 +704,25 @@ Frage: WebGPU weiterführen oder wie BIMCraft CPU + native GPU? - ◐ **[14] „Never crash".** TS-Wächter `guarded()` um das truck-WASM (Trap → neu instanziieren, einmal wiederholen). Rust-Kern: Bindungen verwerfen Unsinn statt zu paniken. Offen: Wächter für render3d/render2d/Kern, Rust-Lints `unwrap_used`/`expect_used`/`panic` auf `deny`, Obergrenzen. · M + - ✅ (29.10.) Kaputte Projekte (Datei/Import) bringen keine Abfrage mehr zum Werfen. Fuzz-Test + `src/core/robustness.test.ts`: Beispiel, „alle Element-Arten", 7 Zufallsprojekte, gekacheltes Projekt × 21 + Verderbnisse (hängende Wand-/Decken-/Dach-/Tür-/Treppentypen, Bauteile, Geschosse, Öffnungs-Wand, Schraffur/ + Linienstil/Stift/Stiftsatz, Block, Layout-Master/-Ausschnitt; Gruppen/Ordner, die sich selbst enthalten; leere und + Ein-Punkt-Polygone; NaN/±∞/negativ; fehlende Felder; doppelte ids; falsche Typen; kaputte Schnittlinien/Baurecht/ + Sonne) gegen jede Fassade (Plan aller Ebenen + sichtbare Geschosse, Schnitt, Ansicht, Szene/SVG/DXF je Plan, 3D, + Pick, IFC, OBJ/STL/GLB, Liste, Kennzahlen, Raumprogramm, Flächen/IVHB, Baurecht, Sonne, Layouts, Prüfung, + Speichern/Laden). Vorher u. a. 158 Würfe allein am Beispiel. Ursachen behoben: (1) Kern-Ableitungen fallen bei + hängenden Verweisen auf Vorgaben zurück statt `Err` (`wall_type_or_fallback`/`component_or_fallback`: eine Schicht + 0,2 m, neutrales Grau; fehlende Schraffur → ohne Muster; hängender Linienstil einer Schraffur → 0,13 durchgezogen; + Deckentyp → Rückfall-Schicht; Verschneidung mit Rückfall-Werten; Plan, Schnitt, Ansicht, 3D, IFC, Mesh). (2) Typisierte + Sicht tolerant (`model/lenient.rs`): EIN Wert, der nicht passt (`null` statt Zahl — NaN überlebt JSON nicht —, + Zeichenkette statt Punkt), legte das ganze Dokument lahm; jetzt fällt nur er auf die Vorgabe zurück (Pflichtfelder wie + `Vec2` → 0), nicht lesbare Listenelemente entfallen, die JSON-Wurzel bleibt unverändert. (3) Mesh-Export: gebrochene + Indizes/NaN-Ecken aus Importen sprengten den `fileio`-Leser. (4) TS `visibleCodesFromSnapshot`/`resolveTitleBlock` + ohne `layerVisibility`/`viewports`. `projectWarnings` (Kern `project_refs.rs`) listet hängende Verweise, Zyklen und + ersetzte Werte; `dossier-cli validate` (und MCP `validate`) gibt sie als „Warnung: …" aus (Exit 0, solange keine + Fehler). Kein Panic gefunden. Offen: Hülle (Panels/Editoren) nicht geprüft; Kategorie-Codes ohne Kategorie werden + nicht gewarnt (bewusst, häufig bei Importen). - ✅ **[16] Befehle mit Unsinn füttern.** 27.10.: `commands/hostile.test.ts` füttert alle Befehle; fand 1 Speicher-Explosion (revisionCloud), behoben. · S - ✅ **[22] Fester Check vor Abschluss.** `npm run check` (tsc, vitest, cargo test aller 6 Crates, diff --git a/src-tauri/core/src/document.rs b/src-tauri/core/src/document.rs index b3f71c18..8924e353 100644 --- a/src-tauri/core/src/document.rs +++ b/src-tauri/core/src/document.rs @@ -230,21 +230,23 @@ impl Document { } /// Typisierte Sicht des Projekts (gecacht; nach Ops werden nur die berührten Felder neu gelesen). - /// Fehler = Feld, das dem Modell widerspricht (Meldung von serde). + /// Werte, die dem Modell widersprechen, fallen auf die Vorgabe zurück (`model::lenient`) — das + /// `Result` bleibt für die Aufrufer, ist aber stets `Ok`. pub fn project(&mut self) -> Result<&Project, String> { if self.typed.is_none() { // Die Map wird nur ausgeliehen: `Value::Object` braucht Besitz, daher temporär herausnehmen. let value = Value::Object(std::mem::take(&mut self.root)); - let parsed = Project::deserialize(&value).map_err(|e| e.to_string()); + let parsed = Project::deserialize(&value); if let Value::Object(m) = value { self.root = m; } - self.typed = Some(parsed?); + // Passt ein Wert nicht zum Modell (Datei/Import: `null` statt Zahl, falscher Typ), fällt nur + // er auf die Vorgabe zurück statt das ganze Projekt (`model::lenient`). + self.typed = Some(parsed.unwrap_or_else(|_| crate::model::lenient::project_lenient(&self.root).0)); self.dirty.clear(); self.dirty_items.clear(); } else if !self.dirty.is_empty() || !self.dirty_items.is_empty() { let mut dirty: Vec = self.dirty.drain().collect(); - let mut failed = None; if let Some(t) = self.typed.as_mut() { // Einzelne Elemente (nach `replace`), ausser ihre Liste wird ohnehin ganz gelesen; // geht es nicht (Liste ohne Element-Weg, Element passt nicht), die ganze Liste. @@ -258,16 +260,9 @@ impl Document { } } for key in &dirty { - if let Err(e) = t.set_field(key, self.root.get(key).filter(|v| !v.is_null())) { - failed = Some(e); - break; - } + crate::model::lenient::set_field_lenient(t, key, self.root.get(key).filter(|v| !v.is_null())); } } - if let Some(e) = failed { - self.typed = None; - return Err(e); - } } Ok(self.typed.as_ref().expect("gerade gesetzt")) } diff --git a/src-tauri/core/src/ifc_data.rs b/src-tauri/core/src/ifc_data.rs index 6e3ffce7..f82e2ad3 100644 --- a/src-tauri/core/src/ifc_data.rs +++ b/src-tauri/core/src/ifc_data.rs @@ -487,24 +487,6 @@ fn sia_label(key: &str) -> &'static str { const SIA_CATEGORIES: [SiaCategory; 6] = [SiaCategory::HNF, SiaCategory::NNF, SiaCategory::VF, SiaCategory::FF, SiaCategory::KGF, SiaCategory::AGF]; -/// Gleiche Fehlermeldung wie die Pick-Geometrie des 3D (`pickGeometry`): eine Öffnung in einer Wand -/// mit unbekanntem Wandtyp bricht ab, bevor die Wände gerechnet werden. -pub(crate) fn pick_opening_check(p: &Project) -> Result<(), String> { - for o in p.openings.as_deref().unwrap_or(&[]) { - let Some(wall) = p.walls.iter().find(|w| w.id == o.host_wall_id) else { continue }; - let axis = hypot2(wall.end.x - wall.start.x, wall.end.y - wall.start.y); - let from = max(0.0, min(o.position, axis)); - let to = max(from, min(o.position + o.width, axis)); - if to - from < 1e-4 { - continue; - } - if p.wall_type(wall).is_none() { - return Err(format!("Unbekannter Wandtyp: {}", wall.wall_type_id)); - } - } - Ok(()) -} - /// Der flache IFC-Puffer aus dem Projekt (s. Modulkopf). pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result { // Georeferenziert: die ganze Geometrie auf die echten LV95-Koordinaten (ohne Bezug unverändert). @@ -550,7 +532,6 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result let component_name = |p: &Project, id: &str| -> String { p.component(id).map_or_else(|| id.to_string(), |c| c.name.clone()) }; // ── Wände ────────────────────────────────────────────────────────────── - pick_opening_check(&p)?; let all_bands = model3d::emit_walls(&p, true)?; let mut bands_by_wall: HashMap<&str, Vec<&RWall>> = HashMap::new(); for b in &all_bands { @@ -1053,9 +1034,11 @@ mod tests { let mut p = Project { id: "leer".into(), ..Default::default() }; let f = ifc_export_data(&p, &IfcOptions::default()).unwrap(); assert_eq!(f.nums.last(), Some(&REC_END_COLUMNS)); + // Hängender Wandtyp (Datei/Import): Export mit dem Rückfall-Typ statt Abbruch. p = sample(); p.walls[0].wall_type_id = "fehlt".into(); - assert_eq!(ifc_export_data(&p, &IfcOptions::default()).unwrap_err(), "Unbekannter Wandtyp: fehlt"); + let f = ifc_export_data(&p, &IfcOptions::default()).unwrap(); + assert_eq!(f.nums.last(), Some(&REC_END_COLUMNS)); } #[test] diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 44f1539a..0035ad47 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -85,6 +85,7 @@ pub mod ugrid; pub mod wasm_alloc; pub mod text_layout; pub mod plan_text; +pub mod project_refs; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/mesh_data.rs b/src-tauri/core/src/mesh_data.rs index 229d1354..d16dcee3 100644 --- a/src-tauri/core/src/mesh_data.rs +++ b/src-tauri/core/src/mesh_data.rs @@ -217,7 +217,13 @@ fn append_model_mesh(prim: &mut Prim, positions: &[f64], indices: &[f64], closed i += 3; } let nv = (pos.len() / 3) as f64; - let ok = |v: f64| v >= 0.0 && v < nv; + // Nur ganzzahlige Indizes auf endliche Ecken (Importe/Dateien können Unsinn tragen); die + // übrigen Ecken bleiben endlich (0), damit der Puffer lesbar bleibt. + let bad: Vec = pos.chunks_exact(3).map(|c| !c.iter().all(|v| v.is_finite())).collect(); + for v in pos.iter_mut().filter(|v| !v.is_finite()) { + *v = 0.0; + } + let ok = |v: f64| v >= 0.0 && v < nv && v.fract() == 0.0 && !bad[v as usize]; let mut tri: Vec = Vec::new(); let mut i = 0; while i + 2 < indices.len() { @@ -265,7 +271,6 @@ pub fn mesh_export_data(src: &Project, opt: &MeshOptions) -> Result = Vec::new(); let mut mats = Materials::default(); - crate::ifc_data::pick_opening_check(&p)?; let walls = model3d::emit_walls(&p, true)?; let slabs = model3d::emit_slabs(&p); let levels: Vec<(String, String)> = p.drawing_levels.iter().filter(|l| l.kind == DrawingLevelKind::Floor).map(|l| (l.id.clone(), l.name.clone())).collect(); @@ -518,8 +523,20 @@ mod tests { #[test] fn kaputtes_kontext_netz_ohne_panik() { let mut p = Project { id: "k".into(), ..Default::default() }; - p.context = Some(vec![ContextObject::ImportedMesh(ImportedMesh { id: "m".into(), positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, f64::NAN], indices: vec![0.0, 1.0, 9.0, 0.0, 1.0, 2.0, f64::NAN, 0.0, 1.0], ..Default::default() })]); + p.context = Some(vec![ContextObject::ImportedMesh(ImportedMesh { id: "m".into(), positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, f64::NAN], indices: vec![0.0, 1.0, 9.0, 0.0, 1.0, 2.0, f64::NAN, 0.0, 1.0], ..Default::default() })]); let f = mesh_export_data(&p, &MeshOptions::default()).unwrap(); assert!(f.strings.iter().any(|s| s == "Kontext_m")); } + + /// Gebrochene Indizes und nicht endliche Ecken (Datei/Import) dürfen nicht in den Puffer: der + /// Leser (`fileio`) verlangt ganzzahlige Indizes und endliche Zahlen. + #[test] + fn nur_ganzzahlige_indizes_und_endliche_ecken() { + let mut g = Prim { material: 0.0, positions: Vec::new(), indices: Vec::new() }; + let pos = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, f64::NAN]; + append_model_mesh(&mut g, &pos, &[0.0, 1.0, 2.0, 0.0, 1.5, 2.0, 1.0, 2.0, 3.0], false); + assert_eq!(g.indices, vec![0.0, 2.0, 1.0], "nur das ganzzahlige Dreieck ohne NaN-Ecke"); + assert!(g.positions.iter().all(|v| v.is_finite())); + assert_eq!(g.positions.len(), 12); + } } diff --git a/src-tauri/core/src/model/helpers.rs b/src-tauri/core/src/model/helpers.rs index 6df7c114..65c91583 100644 --- a/src-tauri/core/src/model/helpers.rs +++ b/src-tauri/core/src/model/helpers.rs @@ -9,7 +9,36 @@ use std::collections::HashMap; use crate::roof::{MansardType, RoofParams, Shape}; use crate::roof_skeleton::Axis; +/// Rückfall-Bauteil für hängende Verweise (Datei/Import nennt ein Bauteil, das fehlt): neutrales +/// Grau, keine Schraffur, Verschneidungs-Priorität 0. +static FALLBACK_COMPONENT: std::sync::LazyLock = + std::sync::LazyLock::new(|| Component { name: "?".into(), color: "#bfbfbf".into(), ..Default::default() }); + +/// Rückfall-Wandtyp für hängende Verweise: eine Schicht 0.2 m (wie der Dicken-Rückfall in TS) aus +/// dem [`FALLBACK_COMPONENT`]. +static FALLBACK_WALL_TYPE: std::sync::LazyLock = std::sync::LazyLock::new(|| WallType { + name: "?".into(), + layers: vec![Layer { thickness: 0.2, ..Default::default() }], + ..Default::default() +}); + impl Project { + /// Wandtyp oder — bei hängendem Verweis — der Rückfall-Typ (eine Schicht 0.2 m). Für alle + /// Ableitungen, die nicht an fehlenden Daten scheitern dürfen (Plan, Schnitt, 3D, Exporte). + pub fn wall_type_or_fallback(&self, w: &Wall) -> &WallType { + self.wall_type(w).unwrap_or(&FALLBACK_WALL_TYPE) + } + + /// Bauteil oder — bei hängendem Verweis — das neutrale Rückfall-Bauteil. + pub fn component_or_fallback(&self, id: &str) -> &Component { + self.component(id).unwrap_or(&FALLBACK_COMPONENT) + } + + /// Schichten des Rückfall-Wandtyps (auch für Decken mit hängendem Typ). + pub fn fallback_layers() -> &'static [Layer] { + &FALLBACK_WALL_TYPE.layers + } + pub fn floor(&self, id: &str) -> Option<&DrawingLevel> { self.drawing_levels.iter().find(|l| l.id == id) } diff --git a/src-tauri/core/src/model/lenient.rs b/src-tauri/core/src/model/lenient.rs new file mode 100644 index 00000000..a0b08d94 --- /dev/null +++ b/src-tauri/core/src/model/lenient.rs @@ -0,0 +1,336 @@ +//! Tolerantes Einlesen der typisierten Sicht: Dateien von der Platte und Importe können Werte tragen, +//! die nicht zum Modell passen — `null` statt einer Zahl (NaN überlebt JSON nicht), eine Zeichenkette +//! statt eines Punkts, eine kaputte Form. Ohne Toleranz scheitert das ganze Projekt an EINEM Wert und +//! jede Abfrage wirft. Hier wird nur das Nötige verworfen: der Wert, an dem es scheitert, fällt auf die +//! Vorgabe des Modells zurück (`#[serde(default)]`); lässt sich ein Listenelement gar nicht lesen, +//! entfällt es. Die JSON-Wurzel des Dokuments bleibt unverändert (Speichern verliert nichts). +//! +//! Vorgehen (typunabhängig, nur über Probe-Lesen): erst das ganze Feld, dann je Listenelement; ein +//! Element, das nicht passt, wird von leer aus wieder aufgebaut — Schlüssel (bzw. Listeneinträge) +//! werden in Hälften zugefügt, solange das Probe-Lesen gelingt; ein einzelner Schlüssel, der es +//! scheitern lässt, wird rekursiv repariert oder weggelassen. Aufwand nur im Fehlerfall. + +use super::Project; +use serde_json::{Map, Value}; + +/// Ein Pfadschritt im JSON-Baum. +#[derive(Clone, Debug)] +enum Seg { + Key(String), + Index(usize), +} + +fn get_mut<'a>(v: &'a mut Value, path: &[Seg]) -> Option<&'a mut Value> { + let mut cur = v; + for s in path { + cur = match (s, cur) { + (Seg::Key(k), Value::Object(m)) => m.get_mut(k)?, + (Seg::Index(i), Value::Array(a)) => a.get_mut(*i)?, + _ => return None, + }; + } + Some(cur) +} + +fn path_text(path: &[Seg]) -> String { + let mut s = String::new(); + for p in path { + match p { + Seg::Key(k) => { + if !s.is_empty() { + s.push('.'); + } + s.push_str(k); + } + Seg::Index(i) => s.push_str(&format!("[{i}]")), + } + } + s +} + +/// Repariert `cur` (ganzer Wert, den `ok` prüft) so, dass `ok(cur)` gelingt; verworfene Pfade +/// landen in `dropped`. `false`: auch die Wurzel lässt sich nicht lesen. +fn repair(cur: &mut Value, ok: &dyn Fn(&Value) -> bool, dropped: &mut Vec) -> bool { + if ok(cur) { + return true; + } + let mut path = Vec::new(); + rebuild(cur, &mut path, ok, dropped) +} + +/// Baut den Knoten an `path` von leer aus neu auf (Vorbedingung: das Ganze scheitert mit ihm). +/// `false`: der Knoten lässt sich auch leer nicht lesen — der Aufrufer entfernt ihn. +fn rebuild(cur: &mut Value, path: &mut Vec, ok: &dyn Fn(&Value) -> bool, dropped: &mut Vec) -> bool { + let Some(node) = get_mut(cur, path) else { return false }; + match std::mem::take(node) { + Value::Object(orig) => { + // 1. Leer anfangen (Strukturen mit Vorgaben) und die Schlüssel wieder zufügen. + *get_mut(cur, path).expect("eben gelesen") = Value::Object(Map::new()); + if ok(cur) { + add_keys(cur, path, orig.into_iter().collect(), ok, dropped); + return true; + } + // 2. Pflichtfelder (z. B. `Vec2 {x, y}`): `null` bzw. jeder Nicht-Zahl-Wert als 0. + for zero_all in [false, true] { + let mut subst = Vec::new(); + let candidate: Map = orig + .iter() + .map(|(k, v)| { + let replace = if zero_all { !(v.is_number() || v.is_object() || v.is_array()) } else { v.is_null() }; + if replace { + subst.push(k.clone()); + (k.clone(), Value::from(0.0)) + } else { + (k.clone(), v.clone()) + } + }) + .collect(); + if subst.is_empty() { + continue; + } + *get_mut(cur, path).expect("eben gelesen") = Value::Object(candidate); + if ok(cur) { + for k in subst { + path.push(Seg::Key(k)); + dropped.push(path_text(path)); + path.pop(); + } + return true; + } + } + // 3. Nur die Zeichenketten (Kennungen wie `shape`/`kind`/`type` innerer Enums), dann der Rest. + let (tags, rest): (Vec<(String, Value)>, Vec<(String, Value)>) = orig.into_iter().partition(|(_, v)| v.is_string()); + *get_mut(cur, path).expect("eben gelesen") = Value::Object(tags.into_iter().collect()); + if !ok(cur) { + return false; + } + add_keys(cur, path, rest, ok, dropped); + true + } + Value::Array(orig) => { + *get_mut(cur, path).expect("eben gelesen") = Value::Array(Vec::new()); + if !ok(cur) { + return false; + } + add_items(cur, path, orig, ok, dropped); + true + } + other => { + *get_mut(cur, path).expect("eben gelesen") = other; + false + } + } +} + +/// Fügt `items` (in Hälften) zum Objekt an `path` hinzu, solange `ok` gilt. +fn add_keys(cur: &mut Value, path: &mut Vec, items: Vec<(String, Value)>, ok: &dyn Fn(&Value) -> bool, dropped: &mut Vec) { + if items.is_empty() { + return; + } + let keys: Vec = items.iter().map(|(k, _)| k.clone()).collect(); + let insert_all = |cur: &mut Value, path: &[Seg], items: &[(String, Value)]| { + if let Some(Value::Object(m)) = get_mut(cur, path) { + for (k, v) in items { + m.insert(k.clone(), v.clone()); + } + } + }; + let remove_all = |cur: &mut Value, path: &[Seg], keys: &[String]| { + if let Some(Value::Object(m)) = get_mut(cur, path) { + for k in keys { + m.remove(k); + } + } + }; + insert_all(cur, path, &items); + if ok(cur) { + return; + } + remove_all(cur, path, &keys); + if items.len() == 1 { + let (k, v) = items.into_iter().next().expect("ein Eintrag"); + let container = v.is_object() || v.is_array(); + if let Some(Value::Object(m)) = get_mut(cur, path) { + m.insert(k.clone(), v); + } + path.push(Seg::Key(k.clone())); + let fixed = container && rebuild(cur, path, ok, dropped); + if !fixed { + dropped.push(path_text(path)); + } + path.pop(); + if !fixed { + if let Some(Value::Object(m)) = get_mut(cur, path) { + m.remove(&k); + } + } + return; + } + let mut items = items; + let second = items.split_off(items.len() / 2); + add_keys(cur, path, items, ok, dropped); + add_keys(cur, path, second, ok, dropped); +} + +/// Hängt `items` (in Hälften, Reihenfolge bleibt) an die Liste an `path`, solange `ok` gilt. +fn add_items(cur: &mut Value, path: &mut Vec, items: Vec, ok: &dyn Fn(&Value) -> bool, dropped: &mut Vec) { + if items.is_empty() { + return; + } + let len = |cur: &mut Value, path: &[Seg]| match get_mut(cur, path) { + Some(Value::Array(a)) => a.len(), + _ => 0, + }; + let base = len(cur, path); + if let Some(Value::Array(a)) = get_mut(cur, path) { + a.extend(items.iter().cloned()); + } + if ok(cur) { + return; + } + if let Some(Value::Array(a)) = get_mut(cur, path) { + a.truncate(base); + } + if items.len() == 1 { + let v = items.into_iter().next().expect("ein Eintrag"); + let container = v.is_object() || v.is_array(); + if let Some(Value::Array(a)) = get_mut(cur, path) { + a.push(v); + } + path.push(Seg::Index(base)); + let fixed = container && rebuild(cur, path, ok, dropped); + if !fixed { + dropped.push(path_text(path)); + } + path.pop(); + if !fixed { + if let Some(Value::Array(a)) = get_mut(cur, path) { + a.truncate(base); + } + } + return; + } + let mut items = items; + let second = items.split_off(items.len() / 2); + add_items(cur, path, items, ok, dropped); + add_items(cur, path, second, ok, dropped); +} + +/// Setzt das Feld `key` der typisierten Sicht tolerant (s. Modulkopf). Liefert die verworfenen +/// Pfade (leer, wenn alles passte). Scheitert nie: notfalls gilt die Vorgabe des Felds. +pub fn set_field_lenient(p: &mut Project, key: &str, v: Option<&Value>) -> Vec { + if p.set_field(key, v).is_ok() { + return Vec::new(); + } + let mut dropped = Vec::new(); + let Some(v) = v else { return dropped }; + let probe = |val: &Value| Project::default().set_field(key, Some(val)).is_ok(); + let mut cur = v.clone(); + if let Value::Array(items) = &mut cur { + // Je Element prüfen (Probe mit einer Ein-Element-Liste), kaputte reparieren oder weglassen. + let mut out = Vec::with_capacity(items.len()); + for (i, item) in std::mem::take(items).into_iter().enumerate() { + let mut one = Value::Array(vec![item]); + let mut d = Vec::new(); + let fine = repair(&mut one, &probe, &mut d); + let kept = match one { + Value::Array(mut a) if fine && a.len() == 1 => a.pop(), + _ => None, + }; + dropped.extend(d.into_iter().map(|s| format!("{key}[{i}]{}", s.strip_prefix("[0]").unwrap_or(&s)))); + match kept { + Some(x) => out.push(x), + None => dropped.push(format!("{key}[{i}]")), + } + } + cur = Value::Array(out); + } else { + let mut d = Vec::new(); + if !repair(&mut cur, &probe, &mut d) { + dropped.push(key.to_string()); + let _ = p.set_field(key, None); + return dropped; + } + dropped.extend(d.into_iter().map(|s| if s.is_empty() { key.to_string() } else { format!("{key}.{s}") })); + } + if p.set_field(key, Some(&cur)).is_err() { + dropped.push(key.to_string()); + let _ = p.set_field(key, None); + } + dropped +} + +/// Typisierte Sicht der ganzen JSON-Wurzel, tolerant (s. Modulkopf): erst am Stück, im Fehlerfall +/// Feld für Feld. Liefert die verworfenen Pfade. +pub fn project_lenient(root: &Map) -> (Project, Vec) { + let mut p = Project::default(); + let mut dropped = Vec::new(); + for (k, v) in root { + dropped.extend(set_field_lenient(&mut p, k, Some(v).filter(|v| !v.is_null()))); + } + (p, dropped) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde::Deserialize; + use serde_json::json; + + fn root(v: Value) -> Map { + match v { + Value::Object(m) => m, + _ => unreachable!(), + } + } + + #[test] + fn null_statt_zahl_faellt_auf_vorgabe() { + let r = root(json!({ + "id": "p", "name": "x", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "drawingLevels": [], "layers": [], "drawings2d": [], + "walls": [ + {"id": "w1", "type": "wall", "floorId": "eg", "categoryCode": "20", "start": {"x": null, "y": 2}, "end": {"x": 3, "y": 2}, "wallTypeId": "t", "height": null}, + {"id": "w2", "type": "wall", "floorId": "eg", "categoryCode": "20", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}, "wallTypeId": "t", "height": 2.5} + ] + })); + assert!(Project::deserialize(&Value::Object(r.clone())).is_err(), "Vorbedingung: streng scheitert es"); + let (p, dropped) = project_lenient(&r); + assert_eq!(p.walls.len(), 2); + assert_eq!(p.walls[0].start.y, 2.0, "der Rest des Punkts bleibt"); + assert_eq!(p.walls[0].start.x, 0.0); + assert_eq!(p.walls[0].height, 0.0); + assert_eq!(p.walls[0].end.x, 3.0); + assert_eq!(p.walls[1].height, 2.5); + assert!(dropped.contains(&"walls[0].start.x".to_string()) && dropped.contains(&"walls[0].height".to_string()), "{dropped:?}"); + } + + #[test] + fn falsche_typen_und_kaputte_listen() { + let r = root(json!({ + "id": "p", "lineStyles": "keine Liste", "walls": [ + {"id": "w1", "start": "hier", "height": "hoch"}, + 7, + {"id": "w3", "end": {"x": 1, "y": 1}} + ], + "ceilings": [{"id": "c1", "outline": [{"x": 0, "y": 0}, null, {"x": 1, "y": "a"}, {"x": 1, "y": 1}]}], + "siteRules": {"parcel": [{"x": 0, "y": 0}], "maxHeight": null} + })); + let (p, dropped) = project_lenient(&r); + assert!(p.line_styles.is_empty()); + assert_eq!(p.walls.iter().map(|w| w.id.as_str()).collect::>(), ["w1", "w3"], "nicht lesbares Element entfällt"); + assert_eq!(p.walls[1].end.x, 1.0); + let c = &p.ceilings.as_ref().unwrap()[0]; + assert_eq!(c.outline.len(), 3, "kaputter Punkt entfällt, halber Punkt mit Vorgabe: {:?}", c.outline); + assert_eq!((c.outline[1].x, c.outline[1].y), (1.0, 0.0)); + assert!(p.site_rules.is_some()); + assert!(dropped.iter().any(|d| d == "walls[1]"), "{dropped:?}"); + } + + #[test] + fn passendes_projekt_unveraendert() { + let r = root(json!({"id": "p", "walls": [{"id": "w", "height": 3}]})); + let (p, dropped) = project_lenient(&r); + assert!(dropped.is_empty()); + assert_eq!(p, Project::deserialize(&Value::Object(r)).unwrap()); + } +} diff --git a/src-tauri/core/src/model/mod.rs b/src-tauri/core/src/model/mod.rs index 946b4745..3c97be6f 100644 --- a/src-tauri/core/src/model/mod.rs +++ b/src-tauri/core/src/model/mod.rs @@ -7,6 +7,7 @@ pub mod generated; pub mod helpers; pub mod items; +pub mod lenient; pub mod manual; #[cfg(test)] pub(crate) mod ts_export; diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index 2cb44b13..ec235a4d 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -433,19 +433,19 @@ fn compute_joins_by_floor(p: &Project) -> Result, Stri let mut jw: Vec = Vec::with_capacity(walls.len()); let mut finite = true; for w in walls { - let layers = p.wall_type(w).map(|wt| { - wt.layers + // Hängende Wandtypen/Bauteile (Datei/Import) verschneiden mit den Rückfall-Werten. + let layers = Some( + p.wall_type_or_fallback(w) + .layers .iter() .map(|l| { - let comp = p.component(&l.component_id); - let idx = comp.map(|c| { - let n = comp_index.len() as u32; - *comp_index.entry(c.id.as_str()).or_insert(n) - }); - JoinLayer { thickness: l.thickness, component: idx, priority: comp.map_or(f64::NAN, |c| c.join_priority) } + let comp = p.component_or_fallback(&l.component_id); + let n = comp_index.len() as u32; + let idx = *comp_index.entry(comp.id.as_str()).or_insert(n); + JoinLayer { thickness: l.thickness, component: Some(idx), priority: comp.join_priority } }) - .collect::>() - }); + .collect::>(), + ); let reference = wall_reference(w); finite &= [w.start.x, w.start.y, w.end.x, w.end.y].iter().all(|v| v.is_finite()) && !matches!(reference, Reference::Offset(v) if !v.is_finite()) @@ -464,11 +464,11 @@ fn compute_joins_by_floor(p: &Project) -> Result, Stri merged.insert(w.id.clone(), c); } } - Err(joins::JoinError::UnknownWallType(i)) => return Err(format!("Unbekannter Wandtyp: {}", walls[i].wall_type_id)), - Err(joins::JoinError::UnknownComponent(i)) => { - let bad = walls[i]; - let missing = p.wall_type(bad).and_then(|t| t.layers.iter().find(|l| p.component(&l.component_id).is_none())).map(|l| l.component_id.clone()).unwrap_or_default(); - return Err(format!("Unbekanntes Bauteil-Material: {missing}")); + // Mit den Rückfällen oben nicht mehr erwartet: dann eben ohne Verschneidung. + Err(_) => { + for w in walls { + merged.insert(w.id.clone(), WallCuts::default()); + } } } } @@ -1145,7 +1145,8 @@ fn roof_color(p: &Project, override_color: Option, component_id: &str) -> R if component_id.is_empty() { return Ok(ROOF_RGB); } - p.component(component_id).map(|c| hex_to_rgb(&c.color, ROOF_RGB)).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {component_id}")) + // Hängendes Bauteil (Datei/Import): Dach-Vorgabefarbe. + Ok(p.component(component_id).map_or(ROOF_RGB, |c| hex_to_rgb(&c.color, ROOF_RGB))) } /// Dächer als geschlossene, geschichtete Dreiecks-Meshes (`emitRoofs`). @@ -1444,7 +1445,7 @@ pub fn pick_geometry(p: &Project) -> Result { let Some(wall) = p.walls.iter().find(|w| w.id == o.host_wall_id) else { continue }; let wr = wall_ref(p, wall); let Some((jamb_start, jamb_end)) = opening_geom::opening_jambs(&wr, o.position, o.width) else { continue }; - let thickness = p.wall_type(wall).map(|t| Project::type_thickness(&t.layers)).ok_or_else(|| format!("Unbekannter Wandtyp: {}", wall.wall_type_id))?; + let thickness = Project::type_thickness(&p.wall_type_or_fallback(wall).layers); let (zb, zt) = p.wall_vertical_extent(wall); let o_bottom = zb + o.sill_height.max(0.0); let o_top = zt.min(o_bottom + o.height); diff --git a/src-tauri/core/src/plan/domains.rs b/src-tauri/core/src/plan/domains.rs index e762416b..737b6e58 100644 --- a/src-tauri/core/src/plan/domains.rs +++ b/src-tauri/core/src/plan/domains.rs @@ -215,18 +215,15 @@ fn pv(p: [f64; 2]) -> Vec2 { Vec2 { x: p[0], y: p[1] } } -/// `getComponent` (wirft in TS). +/// `getComponent`; hängender Verweis (Datei/Import) → neutrales Rückfall-Bauteil statt Abbruch. fn component<'a>(p: &'a Project, id: &str) -> Result<&'a Component, String> { - p.component(id).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {id}")) + Ok(p.component_or_fallback(id)) } -/// `resolveHatch` mit der Fehlermeldung von TS (`getHatch`/`getLineStyle` werfen). -pub(super) fn resolve_hatch_or_err(p: &Project, hatch_id: &str, wall_angle_deg: Option, fg: Option<&str>) -> Result { - let h = p.hatch(hatch_id).ok_or_else(|| format!("Unbekannte Schraffur: {hatch_id}"))?; - if let Some(ls) = h.line_style_id.as_deref().filter(|s| !s.is_empty()) { - p.line_style(ls).ok_or_else(|| format!("Unbekannter Linienstil: {ls}"))?; - } - resolve_hatch(p, hatch_id, wall_angle_deg, fg, None).ok_or_else(|| format!("Unbekannte Schraffur: {hatch_id}")) +/// `resolveHatch`; hängende Schraffur (Datei/Import) → ohne Muster statt Abbruch (ein hängender +/// Linienstil der Schraffur fällt in `resolve_hatch` auf die Vorgabe-Strichstärke zurück). +pub(super) fn resolve_hatch_or_none(p: &Project, hatch_id: &str, wall_angle_deg: Option, fg: Option<&str>) -> HatchRender { + resolve_hatch(p, hatch_id, wall_angle_deg, fg, None).unwrap_or_else(no_hatch) } /// Footprints der gezeichneten Wände dieses Geschosses (`buildWallFootprints`). @@ -251,7 +248,8 @@ fn ceiling_layers<'a>(p: &'a Project, c: &Ceiling) -> Result<&'a [Layer], String return Ok(&ct.layers); } } - p.wall_types.iter().find(|t| t.id == c.wall_type_id).map(|t| t.layers.as_slice()).ok_or_else(|| format!("Unbekannter Deckentyp: {}", c.ceiling_type_id.as_deref().unwrap_or(&c.wall_type_id))) + // Hängender Typ (Datei/Import): Rückfall-Schicht statt Abbruch. + Ok(p.wall_types.iter().find(|t| t.id == c.wall_type_id).map_or(Project::fallback_layers(), |t| t.layers.as_slice())) } /// Typname einer Decke für `object_name` (Maps in TS: letzter Eintrag je id gewinnt). @@ -290,7 +288,7 @@ fn ceilings(c: &Ctx, out: &mut Vec, bounds: &mut Bounds) -> Result<() let stroke = color.unwrap_or(POCHE_STROKE); let view_hatch_id = resolve_hatch_id(ce.hatch_id.as_deref(), ce.hatch_source, category, comp.and_then(|k| k.view_hatch_id.as_deref())); let hatch = match (c.a.detail != Detail::Grob, comp, view_hatch_id.filter(|s| !s.is_empty())) { - (true, Some(k), Some(id)) => resolve_hatch_or_err(p, id, None, resolve_foreground(k, ce.foreground.as_deref(), category, ce.foreground_source))?, + (true, Some(k), Some(id)) => resolve_hatch_or_none(p, id, None, resolve_foreground(k, ce.foreground.as_deref(), category, ce.foreground_source)), _ => no_hatch(), }; let fill = match comp { diff --git a/src-tauri/core/src/plan/drawings.rs b/src-tauri/core/src/plan/drawings.rs index b20a8b23..6c227339 100644 --- a/src-tauri/core/src/plan/drawings.rs +++ b/src-tauri/core/src/plan/drawings.rs @@ -8,7 +8,7 @@ //! Ein Block wird über `scale_geom` (Skalierung, Drehung, Verschiebung) rekursiv ausgegeben. //! Texte bleiben Daten (`drawingText`); das Text-Layout macht der Verbraucher. -use super::domains::{resolve_hatch_or_err, Bounds, Ctx}; +use super::domains::{Bounds, Ctx}; use super::overrides::Actions; use super::prim::{HatchRender, Primitive}; use super::style::*; @@ -585,10 +585,8 @@ fn emit_inner(c: &Ctx, d: &Drawing2D, attrs: Attrs, geom: &Drawing2DGeom, greyed // Gefüllte Fläche einer geschlossenen Form (Vollton-Füllung und/oder Schraffur), vor den Strichen. let fill_poly = |em: &mut Em, pts: Vec| -> Result<(), String> { let hatch = match hatch_id.filter(|s| !s.is_empty()) { - Some(h) => { - resolve_hatch_or_err(p, h, None, foreground)?; - resolve_hatch(p, h, None, foreground, Some((d.hatch_angle_deg, d.hatch_scale, d.hatch_origin))).ok_or_else(|| format!("Unbekannte Schraffur: {h}"))? - } + // Hängende Schraffur (Datei/Import): Fläche ohne Muster statt Abbruch. + Some(h) => resolve_hatch(p, h, None, foreground, Some((d.hatch_angle_deg, d.hatch_scale, d.hatch_origin))).unwrap_or_else(no_hatch), None => no_hatch(), }; let pr = polygon(pts, fill_color, "none", 0.0, hatch, em.greyed, Some(em.id)); diff --git a/src-tauri/core/src/plan/elevation.rs b/src-tauri/core/src/plan/elevation.rs index 705fe07a..526274d6 100644 --- a/src-tauri/core/src/plan/elevation.rs +++ b/src-tauri/core/src/plan/elevation.rs @@ -150,7 +150,8 @@ fn collect_roof_faces(p: &Project, frame: &[f64; 9]) -> Result, String let fill = match roof.color.as_deref().filter(|c| !c.is_empty()) { Some(c) => hex_to_rgb(c, ROOF_RGB_FALLBACK), None => match outer.filter(|l| !l.component_id.is_empty()) { - Some(l) => hex_to_rgb(&p.component(&l.component_id).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {}", l.component_id))?.color, ROOF_RGB_FALLBACK), + // Hängendes Bauteil (Datei/Import): Dach-Vorgabefarbe. + Some(l) => p.component(&l.component_id).map_or(ROOF_RGB_FALLBACK, |c| hex_to_rgb(&c.color, ROOF_RGB_FALLBACK)), None => ROOF_RGB_FALLBACK, }, }; diff --git a/src-tauri/core/src/plan/section.rs b/src-tauri/core/src/plan/section.rs index c47a819e..4d702e5c 100644 --- a/src-tauri/core/src/plan/section.rs +++ b/src-tauri/core/src/plan/section.rs @@ -496,10 +496,6 @@ fn rect_of_band(c: &Cut) -> Option<[f64; 4]> { (c.pts.len() >= 3).then(|| bbox(&c.pts)) } -fn missing(what: &str, id: &str) -> String { - format!("{what}: {id}") -} - /// Bauteil-Stil einer Schicht (Füllung, Schraffur) mit dem Override des Elements (`split*Layers`). #[allow(clippy::too_many_arguments)] fn layer_style( @@ -515,7 +511,8 @@ fn layer_style( angle: f64, ) -> Result<(String, HatchRender), String> { let hid = resolve_hatch_id(hatch_id, hatch_source, category, Some(&comp.hatch_id)).unwrap_or(&comp.hatch_id); - let hatch = resolve_hatch(p, hid, Some(angle), resolve_foreground(comp, fg, category, fg_source), None).ok_or_else(|| missing("Unbekannte Schraffur", hid))?; + // Hängende Schraffur (Datei/Import): ohne Muster statt Abbruch. + let hatch = resolve_hatch(p, hid, Some(angle), resolve_foreground(comp, fg, category, fg_source), None).unwrap_or_else(no_hatch); let bg = resolve_background(comp, bg, category, bg_source); let fill = bg.map(String::from).unwrap_or_else(|| poche_fill(hatch.pattern).to_string()); Ok((fill, hatch)) @@ -525,7 +522,7 @@ fn layer_style( /// Jede Schicht ist im Schnitt-Modell eine eigene Platte; ihr Band trägt so genau ihr Bauteil. fn style_slab_layer(cp: &mut Cut, p: &Project, layer: &Layer, owner: &Ceiling) -> Result<(), String> { let category = p.layer_category(&owner.category_code); - let comp = p.component(&layer.component_id).ok_or_else(|| missing("Unbekanntes Bauteil-Material", &layer.component_id))?; + let comp = p.component_or_fallback(&layer.component_id); let (fill, hatch) = layer_style(p, comp, owner.hatch_id.as_deref(), owner.hatch_source, owner.foreground.as_deref(), owner.foreground_source, owner.background.as_deref(), owner.background_source, category, SECTION_SLAB_AXIS_ANGLE_DEG)?; cp.fill = Some(fill); cp.hatch = Some(hatch); @@ -561,7 +558,7 @@ fn split_wall_layers(cp: &Cut, p: &Project, layers: &[Layer], owner: &Wall, u_wo let mut out = Vec::with_capacity(layers.len()); let mut acc = 0.0; for layer in ordered { - let comp = p.component(&layer.component_id).ok_or_else(|| missing("Unbekanntes Bauteil-Material", &layer.component_id))?; + let comp = p.component_or_fallback(&layer.component_id); let (fill, hatch) = layer_style(p, comp, owner.hatch_id.as_deref(), owner.hatch_source, owner.foreground.as_deref(), owner.foreground_source, owner.background.as_deref(), owner.background_source, category, SECTION_WALL_AXIS_ANGLE_DEG)?; let u_left = u_min + acc * scale; acc += layer.thickness; @@ -599,7 +596,7 @@ fn attach_cut_styles(cuts: Vec, p: &Project, plane: &Plane, walls: &[Option cp.source_id = owner.map(|o| o.id.clone()); cp.category = owner.map(|o| o.category_code.clone()); if let Some(o) = owner { - let wt = p.wall_type(o).ok_or_else(|| missing("Unbekannter Wandtyp", &o.wall_type_id))?; + let wt = p.wall_type_or_fallback(o); if wt.layers.len() > 1 { bands.extend(split_wall_layers(&cp, p, &wt.layers, o, u_world)?); continue; @@ -618,7 +615,7 @@ fn attach_cut_styles(cuts: Vec, p: &Project, plane: &Plane, walls: &[Option SlabOwner::Ceiling(o, layer) => { cp.source_id = Some(o.id.clone()); cp.category = Some(o.category_code.clone()); - let layers = ceiling_layers(p, o).ok_or_else(|| missing("Unbekannter Deckentyp", o.ceiling_type_id.as_deref().unwrap_or(&o.wall_type_id)))?; + let layers = ceiling_layers(p, o).unwrap_or(Project::fallback_layers()); if layers.len() > 1 { // Schicht-Platte: Stil genau dieser Schicht; ohne Schicht (Dicke 0) ohne Stil. if let Some(l) = layer.and_then(|i| layers.get(i)) { @@ -1371,8 +1368,7 @@ fn cross_section(p: &Project, wall: &Wall, o: &Opening, p0: (f64, f64), u: (f64, let n0 = rel.0 * n.0 + rel.1 * n.1; let a0 = rel.0 * a.0 + rel.1 * a.1; let ua = u.0 * a.0 + u.1 * a.1; - let wt = p.wall_type(wall).ok_or_else(|| missing("Unbekannter Wandtyp", &wall.wall_type_id))?; - let total = sum_thickness(&wt.layers); + let total = sum_thickness(&p.wall_type_or_fallback(wall).layers); let ref_off = crate::joins::reference_offset(model3d::wall_reference(wall), total); let along = a0 + ((ref_off - n0) / un) * ua; if along < from + 1e-4 || along > to - 1e-4 { @@ -1414,7 +1410,7 @@ fn window_cut(p: &Project, wall: &Wall, o: &Opening, c: &CrossSection) -> Result let mut f_max = f_min + DEFAULT_FRAME_DEPTH; let mut glass: Vec = vec![(f_min + f_max) / 2.0]; // `windowSymbol(project, wall, o, 1, spec, "mittel")`. - let total = sum_thickness(&p.wall_type(wall).ok_or_else(|| missing("Unbekannter Wandtyp", &wall.wall_type_id))?.layers); + let total = sum_thickness(&p.wall_type_or_fallback(wall).layers); let ref_off = crate::joins::reference_offset(model3d::wall_reference(wall), total); let spec = wt.map(|t| crate::opening_geom::WindowSpec { sashes: sashes_of_window_type(t), diff --git a/src-tauri/core/src/plan/style.rs b/src-tauri/core/src/plan/style.rs index 80176473..03b9481d 100644 --- a/src-tauri/core/src/plan/style.rs +++ b/src-tauri/core/src/plan/style.rs @@ -84,13 +84,11 @@ pub fn poche_fill(p: HatchPattern) -> &'static str { } } -/// `resolveHatch`: `None`, wenn Schraffur oder ihr Linienstil fehlen (TS wirft dort — Aufrufer fängt). +/// `resolveHatch`: `None`, wenn die Schraffur fehlt. Ein hängender Linienstil der Schraffur +/// (Datei/Import) zählt wie keiner (Vorgabe-Strichstärke 0.13, durchgezogen). pub fn resolve_hatch(p: &Project, hatch_id: &str, wall_angle_deg: Option, foreground: Option<&str>, placement: Option<(Option, Option, Option)>) -> Option { let h = p.hatch(hatch_id)?; - let ls = match h.line_style_id.as_deref().filter(|s| !s.is_empty()) { - Some(id) => Some(p.line_style(id)?), - None => None, - }; + let ls = h.line_style_id.as_deref().filter(|s| !s.is_empty()).and_then(|id| p.line_style(id)); let (p_angle, p_scale, p_origin) = placement.unwrap_or((None, None, None)); let base_angle = p_angle.unwrap_or(h.angle); let angle = match wall_angle_deg { diff --git a/src-tauri/core/src/plan/walls.rs b/src-tauri/core/src/plan/walls.rs index 87c7d07f..19652f3b 100644 --- a/src-tauri/core/src/plan/walls.rs +++ b/src-tauri/core/src/plan/walls.rs @@ -34,8 +34,9 @@ pub fn opening_label(o: &Opening) -> String { format!("{} {}×{}", if o.kind == ElementKind::Door { "Tür" } else { "Fenster" }, to_fixed(o.width * 100.0, 0), to_fixed(o.height * 100.0, 0)) } +/// Wandtyp; hängender Verweis (Datei/Import) → Rückfall-Typ, nie ein Fehler. fn wall_type<'a>(p: &'a Project, w: &Wall) -> Result<&'a WallType, String> { - p.wall_type(w).ok_or_else(|| format!("Unbekannter Wandtyp: {}", w.wall_type_id)) + Ok(p.wall_type_or_fallback(w)) } /// Verschneidung der gezeichneten Wände (`computeJoins` in TS, gleicher Puffer). Fehler wie die @@ -52,33 +53,18 @@ fn plan_joins(p: &Project, walls: &[EffWall]) -> Result, String> { (None, Some(WallReferenceLine::Right)) => buf.extend([2.0, 0.0]), _ => buf.extend([0.0, 0.0]), } - let Some(wt) = p.wall_type(w) else { - buf.extend([0.0, 0.0]); - continue; - }; + // Hängende Wandtypen/Bauteile (Datei/Import) verschneiden mit den Rückfall-Werten. + let wt = p.wall_type_or_fallback(w); buf.extend([1.0, wt.layers.len() as f64]); for l in &wt.layers { - let comp = p.component(&l.component_id); - let idx = match comp { - Some(c) => { - let n = comp_index.len(); - *comp_index.entry(c.id.as_str()).or_insert(n) as f64 - } - None => -1.0, - }; - buf.extend([l.thickness, idx, comp.map_or(f64::NAN, |c| c.join_priority)]); + let comp = p.component_or_fallback(&l.component_id); + let n = comp_index.len(); + let idx = *comp_index.entry(comp.id.as_str()).or_insert(n) as f64; + buf.extend([l.thickness, idx, comp.join_priority]); } } let out = joins::compute_joins_flat(&buf); - if out.first() == Some(&1.0) { - let bad = out.get(1).and_then(|i| walls.get(*i as usize)); - if let Some(e) = bad { - for l in &wall_type(p, e.w)?.layers { - p.component(&l.component_id).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {}", l.component_id))?; - } - } - return Err("computeJoins: unbekannter Wandtyp oder Bauteil".into()); - } + // Fehler der Verschneidung (mit den Rückfällen oben nicht mehr erwartet): Wände ohne Verschneidung. if out.first() != Some(&0.0) { return Ok(vec![WallCuts::default(); walls.len()]); } @@ -199,9 +185,9 @@ fn wall_poche(c: &Ctx, out: &mut Vec, e: &EffWall, gaps: &[(f64, f64) return Ok(s.clone()); } let layer = wt.layers.get(li).ok_or("Schicht fehlt")?; - let comp = p.component(&layer.component_id).ok_or_else(|| format!("Unbekanntes Bauteil-Material: {}", layer.component_id))?; + let comp = p.component_or_fallback(&layer.component_id); let hid = resolve_hatch_id(w.hatch_id.as_deref(), w.hatch_source, category, Some(&comp.hatch_id)).unwrap_or(&comp.hatch_id); - let hatch = super::domains::resolve_hatch_or_err(p, hid, Some(angle), resolve_foreground(comp, w.foreground.as_deref(), category, w.foreground_source))?; + let hatch = super::domains::resolve_hatch_or_none(p, hid, Some(angle), resolve_foreground(comp, w.foreground.as_deref(), category, w.foreground_source)); let bg = resolve_background(comp, w.background.as_deref(), category, w.background_source); let fill = bg.unwrap_or(if hatch.pattern == HatchPattern::Solid { HATCH_INK } else { HATCH_PAPER }).to_string(); styles.insert(li, (hatch.clone(), fill.clone())); diff --git a/src-tauri/core/src/project_refs.rs b/src-tauri/core/src/project_refs.rs new file mode 100644 index 00000000..8737a216 --- /dev/null +++ b/src-tauri/core/src/project_refs.rs @@ -0,0 +1,272 @@ +//! Warnungen zu einem Projekt, das trotzdem geladen und gerechnet werden kann (`dossier-cli validate`, +//! TS `projectWarnings`): hängende Verweise (Wandtyp, Bauteil, Geschoss, Schraffur, Linienstil, Stift, +//! Gruppe, Layout …), Gruppen/Ordner, die sich selbst enthalten, und Werte, die nicht zum Modell passen +//! (`model::lenient` setzt dort die Vorgabe ein). Die Ableitungen fallen in all diesen Fällen auf +//! Vorgaben zurück — die Warnung sagt, wo. + +use crate::model::{lenient, Drawing2DGeom, Project}; +use serde_json::{Map, Value}; +use std::collections::{HashMap, HashSet}; + +/// Warnungen (deutsch, je eine Zeile) für die JSON-Wurzel eines Projekts. +pub fn project_warnings(root: &Map) -> Vec { + let (p, dropped) = lenient::project_lenient(root); + let mut out: Vec = dropped.into_iter().map(|d| format!("Wert passt nicht zum Modell, Vorgabe verwendet: {d}")).collect(); + out.extend(dangling_refs(&p)); + out +} + +fn ids<'a, T: 'a>(items: impl IntoIterator, id: impl Fn(&'a T) -> &'a str) -> HashSet<&'a str> { + items.into_iter().map(id).collect() +} + +/// Hängende Verweise und Zyklen im typisierten Projekt. +pub fn dangling_refs(p: &Project) -> Vec { + let mut out = Vec::new(); + let levels = ids(&p.drawing_levels, |l| l.id.as_str()); + let wall_types = ids(&p.wall_types, |t| t.id.as_str()); + let ceiling_types = ids(p.ceiling_types.as_deref().unwrap_or(&[]), |t| t.id.as_str()); + let roof_types = ids(p.roof_types.as_deref().unwrap_or(&[]), |t| t.id.as_str()); + let door_types = ids(p.door_types.as_deref().unwrap_or(&[]), |t| t.id.as_str()); + let window_types = ids(p.window_types.as_deref().unwrap_or(&[]), |t| t.id.as_str()); + let stair_types = ids(p.stair_types.as_deref().unwrap_or(&[]), |t| t.id.as_str()); + let components = ids(&p.components, |c| c.id.as_str()); + let hatches = ids(&p.hatches, |h| h.id.as_str()); + let line_styles = ids(&p.line_styles, |l| l.id.as_str()); + let pens = ids(p.pens.as_deref().unwrap_or(&[]), |x| x.id.as_str()); + let block_defs = ids(p.block_defs.as_deref().unwrap_or(&[]), |b| b.id.as_str()); + let walls = ids(&p.walls, |w| w.id.as_str()); + let snapshots = ids(p.view_snapshots.as_deref().unwrap_or(&[]), |s| s.id.as_str()); + let masters = ids(p.master_layouts.as_deref().unwrap_or(&[]), |m| m.id.as_str()); + let layout_folders = ids(p.layout_folders.as_deref().unwrap_or(&[]), |f| f.id.as_str()); + let snapshot_folders = ids(p.view_snapshot_folders.as_deref().unwrap_or(&[]), |f| f.id.as_str()); + + fn miss(out: &mut Vec, what: &str, owner: &str, kind: &str, id: &str, known: &HashSet<&str>) { + if !id.is_empty() && !known.contains(id) { + out.push(format!("{what} „{owner}\": {kind} „{id}\" fehlt.")); + } + } + fn check_pens(out: &mut Vec, pens: &HashSet<&str>, what: &str, owner: &str, ps: [&Option; 3]) { + for x in ps { + miss(out, what, owner, "Stift", x.as_deref().unwrap_or(""), pens); + } + } + let none: Option = None; + + for w in &p.walls { + miss(&mut out, "Wand", &w.id, "Geschoss", &w.floor_id, &levels); + miss(&mut out, "Wand", &w.id, "Wandtyp", &w.wall_type_id, &wall_types); + miss(&mut out, "Wand", &w.id, "Schraffur", w.hatch_id.as_deref().unwrap_or(""), &hatches); + check_pens(&mut out, &pens, "Wand", &w.id, [&w.color_pen_id, &w.foreground_pen_id, &w.background_pen_id]); + } + for o in p.openings.as_deref().unwrap_or(&[]) { + miss(&mut out, "Öffnung", &o.id, "Wand", &o.host_wall_id, &walls); + let types = if door_types.contains(o.type_id.as_deref().unwrap_or("")) { &door_types } else { &window_types }; + miss(&mut out, "Öffnung", &o.id, "Typ", o.type_id.as_deref().unwrap_or(""), types); + check_pens(&mut out, &pens, "Öffnung", &o.id, [&o.color_pen_id, &none, &none]); + } + for c in p.ceilings.as_deref().unwrap_or(&[]) { + miss(&mut out, "Decke", &c.id, "Geschoss", &c.floor_id, &levels); + match c.ceiling_type_id.as_deref().filter(|s| !s.is_empty()) { + Some(t) if ceiling_types.contains(t) => {} + Some(t) if !c.wall_type_id.is_empty() && wall_types.contains(c.wall_type_id.as_str()) => { + out.push(format!("Decke „{}\": Deckentyp „{t}\" fehlt (Wandtyp „{}\" verwendet).", c.id, c.wall_type_id)) + } + Some(t) => out.push(format!("Decke „{}\": Deckentyp „{t}\" fehlt.", c.id)), + None => miss(&mut out, "Decke", &c.id, "Wandtyp", &c.wall_type_id, &wall_types), + } + miss(&mut out, "Decke", &c.id, "Schraffur", c.hatch_id.as_deref().unwrap_or(""), &hatches); + check_pens(&mut out, &pens, "Decke", &c.id, [&c.color_pen_id, &c.foreground_pen_id, &c.background_pen_id]); + } + for r in p.roofs.as_deref().unwrap_or(&[]) { + miss(&mut out, "Dach", &r.id, "Geschoss", &r.floor_id, &levels); + miss(&mut out, "Dach", &r.id, "Dachtyp", r.roof_type_id.as_deref().unwrap_or(""), &roof_types); + } + for s in p.stairs.as_deref().unwrap_or(&[]) { + miss(&mut out, "Treppe", &s.id, "Geschoss", &s.floor_id, &levels); + miss(&mut out, "Treppe", &s.id, "Treppentyp", s.type_id.as_deref().unwrap_or(""), &stair_types); + } + for c in p.columns.as_deref().unwrap_or(&[]) { + miss(&mut out, "Stütze", &c.id, "Geschoss", &c.floor_id, &levels); + miss(&mut out, "Stütze", &c.id, "Bauteil", c.component_id.as_deref().unwrap_or(""), &components); + miss(&mut out, "Stütze", &c.id, "Schraffur", c.hatch_id.as_deref().unwrap_or(""), &hatches); + } + for r in p.rooms.as_deref().unwrap_or(&[]) { + miss(&mut out, "Raum", &r.id, "Geschoss", &r.floor_id, &levels); + } + for d in &p.drawings2d { + miss(&mut out, "Zeichnung", &d.id, "Ebene", &d.level_id, &levels); + miss(&mut out, "Zeichnung", &d.id, "Linienstil", d.line_style_id.as_deref().unwrap_or(""), &line_styles); + miss(&mut out, "Zeichnung", &d.id, "Schraffur", d.hatch_id.as_deref().unwrap_or(""), &hatches); + check_pens(&mut out, &pens, "Zeichnung", &d.id, [&d.color_pen_id, &d.foreground_pen_id, &d.background_pen_id]); + if let Drawing2DGeom::Block { block_def_id, .. } = &d.geom { + miss(&mut out, "Zeichnung", &d.id, "Block", block_def_id, &block_defs); + } + } + for x in p.extruded_solids.as_deref().unwrap_or(&[]) { + miss(&mut out, "Körper", &x.id, "Ebene", &x.level_id, &levels); + } + let type_layers = p + .wall_types + .iter() + .map(|t| ("Wandtyp", &t.id, &t.layers)) + .chain(p.ceiling_types.as_deref().unwrap_or(&[]).iter().map(|t| ("Deckentyp", &t.id, &t.layers))) + .chain(p.roof_types.as_deref().unwrap_or(&[]).iter().map(|t| ("Dachtyp", &t.id, &t.layers))); + for (what, id, layers) in type_layers { + for l in layers { + miss(&mut out, what, id, "Bauteil", &l.component_id, &components); + miss(&mut out, what, id, "Linienstil", l.joint_line_style_id.as_deref().unwrap_or(""), &line_styles); + } + } + for c in &p.components { + miss(&mut out, "Bauteil", &c.id, "Schraffur", &c.hatch_id, &hatches); + miss(&mut out, "Bauteil", &c.id, "Schraffur", c.view_hatch_id.as_deref().unwrap_or(""), &hatches); + check_pens(&mut out, &pens, "Bauteil", &c.id, [&c.color_pen_id, &c.foreground_pen_id, &c.background_pen_id]); + } + for h in &p.hatches { + miss(&mut out, "Schraffur", &h.id, "Linienstil", h.line_style_id.as_deref().unwrap_or(""), &line_styles); + } + for c in p.flat_categories() { + check_pens(&mut out, &pens, "Kategorie", &c.code, [&c.color_pen_id, &none, &none]); + } + let pen_sets = ids(p.pen_sets.as_deref().unwrap_or(&[]), |s| s.id.as_str()); + miss(&mut out, "Projekt", &p.id, "Stiftsatz", p.active_pen_set_id.as_deref().unwrap_or(""), &pen_sets); + for l in p.layouts.as_deref().unwrap_or(&[]) { + miss(&mut out, "Layout", &l.id, "Master", l.master_id.as_deref().unwrap_or(""), &masters); + miss(&mut out, "Layout", &l.id, "Ordner", l.folder_id.as_deref().unwrap_or(""), &layout_folders); + for v in &l.viewports { + miss(&mut out, "Layout", &l.id, "Ausschnitt", &v.snapshot_id, &snapshots); + } + } + for m in p.master_layouts.as_deref().unwrap_or(&[]) { + miss(&mut out, "Master-Layout", &m.id, "Ordner", m.folder_id.as_deref().unwrap_or(""), &layout_folders); + } + for s in p.view_snapshots.as_deref().unwrap_or(&[]) { + miss(&mut out, "Ausschnitt", &s.id, "Geschoss", &s.active_level_id, &levels); + miss(&mut out, "Ausschnitt", &s.id, "Ordner", s.folder_id.as_deref().unwrap_or(""), &snapshot_folders); + } + + // Gruppen: Mitglieder und Zyklen. + let groups = p.groups.as_deref().unwrap_or(&[]); + let group_ids = ids(groups, |g| g.id.as_str()); + let members: [(&str, HashSet<&str>); 7] = [ + ("Zeichnung", ids(&p.drawings2d, |d| d.id.as_str())), + ("Decke", ids(p.ceilings.as_deref().unwrap_or(&[]), |x| x.id.as_str())), + ("Raum", ids(p.rooms.as_deref().unwrap_or(&[]), |x| x.id.as_str())), + ("Treppe", ids(p.stairs.as_deref().unwrap_or(&[]), |x| x.id.as_str())), + ("Stütze", ids(p.columns.as_deref().unwrap_or(&[]), |x| x.id.as_str())), + ("Dach", ids(p.roofs.as_deref().unwrap_or(&[]), |x| x.id.as_str())), + ("Öffnung", ids(p.openings.as_deref().unwrap_or(&[]), |x| x.id.as_str())), + ]; + for g in groups { + for w in &g.wall_ids { + miss(&mut out, "Gruppe", &g.id, "Wand", w, &walls); + } + let lists = [&g.drawing_ids, &g.ceiling_ids, &g.room_ids, &g.stair_ids, &g.column_ids, &g.roof_ids, &g.opening_ids]; + for (list, (kind, known)) in lists.into_iter().zip(&members) { + for id in list { + miss(&mut out, "Gruppe", &g.id, kind, id, known); + } + } + for id in &g.group_ids { + miss(&mut out, "Gruppe", &g.id, "Gruppe", id, &group_ids); + } + } + let children: HashMap<&str, Vec<&str>> = groups.iter().map(|g| (g.id.as_str(), g.group_ids.iter().map(String::as_str).collect())).collect(); + for g in groups { + if reaches(&children, &g.id, &g.id) { + out.push(format!("Gruppe „{}\" enthält sich selbst (über verschachtelte Gruppen).", g.id)); + } + } + // Ordner: Eltern-Ketten ohne Zyklus. + let folder_cycles = |what: &str, parents: HashMap<&str, &str>, out: &mut Vec| { + for &start in parents.keys() { + let mut seen = HashSet::new(); + let mut cur = start; + while let Some(&next) = parents.get(cur) { + if next == start { + out.push(format!("{what} „{start}\" ist sein eigener Vorfahre.")); + break; + } + if !seen.insert(next) { + break; + } + cur = next; + } + } + }; + let lf = p.layout_folders.as_deref().unwrap_or(&[]); + folder_cycles("Layout-Ordner", lf.iter().filter_map(|f| Some((f.id.as_str(), f.parent_id.as_deref()?))).collect(), &mut out); + let sf = p.view_snapshot_folders.as_deref().unwrap_or(&[]); + folder_cycles("Ausschnitt-Ordner", sf.iter().filter_map(|f| Some((f.id.as_str(), f.parent_id.as_deref()?))).collect(), &mut out); + out.sort(); + out.dedup(); + out +} + +/// Erreicht `from` über `children` (ohne sich selbst als Start zu zählen) den Knoten `target`? +fn reaches(children: &HashMap<&str, Vec<&str>>, from: &str, target: &str) -> bool { + let mut stack: Vec<&str> = children.get(from).cloned().unwrap_or_default(); + let mut seen: HashSet<&str> = HashSet::new(); + while let Some(n) = stack.pop() { + if n == target { + return true; + } + if seen.insert(n) { + stack.extend(children.get(n).into_iter().flatten().copied()); + } + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn root(v: Value) -> Map { + match v { + Value::Object(m) => m, + _ => unreachable!(), + } + } + + #[test] + fn haengende_verweise_und_zyklen() { + let r = root(json!({ + "id": "p", + "drawingLevels": [{"id": "eg", "kind": "floor"}], + "wallTypes": [{"id": "aw", "layers": [{"componentId": "beton", "thickness": 0.2}]}], + "components": [], + "walls": [{"id": "w1", "floorId": "eg", "wallTypeId": "nope"}, {"id": "w2", "floorId": "og", "wallTypeId": "aw", "height": null}], + "openings": [{"id": "o1", "hostWallId": "w9"}], + "groups": [ + {"id": "g1", "groupIds": ["g2"], "wallIds": ["w1"]}, + {"id": "g2", "groupIds": ["g1", "g3"]} + ], + "layoutFolders": [{"id": "a", "parentId": "b"}, {"id": "b", "parentId": "a"}, {"id": "c", "parentId": "c"}] + })); + let w = project_warnings(&r); + let has = |s: &str| w.iter().any(|x| x.contains(s)); + assert!(has("Wand „w1\": Wandtyp „nope\" fehlt."), "{w:#?}"); + assert!(has("Wand „w2\": Geschoss „og\" fehlt.")); + assert!(has("Wandtyp „aw\": Bauteil „beton\" fehlt.")); + assert!(has("Öffnung „o1\": Wand „w9\" fehlt.")); + assert!(has("Gruppe „g2\": Gruppe „g3\" fehlt.")); + assert!(has("Gruppe „g1\" enthält sich selbst")); + assert!(has("Layout-Ordner „a\" ist sein eigener Vorfahre.") && has("Layout-Ordner „c\"")); + assert!(has("Vorgabe verwendet: walls[1].height")); + } + + #[test] + fn stimmiges_projekt_ohne_warnung() { + let r = root(json!({ + "id": "p", + "drawingLevels": [{"id": "eg"}], + "wallTypes": [{"id": "aw", "layers": [{"componentId": "beton", "thickness": 0.2}]}], + "components": [{"id": "beton", "hatchId": ""}], + "walls": [{"id": "w1", "floorId": "eg", "wallTypeId": "aw"}] + })); + assert_eq!(project_warnings(&r), Vec::::new()); + } +} diff --git a/src-tauri/core/src/style.rs b/src-tauri/core/src/style.rs index 2a60c14c..ab574047 100644 --- a/src-tauri/core/src/style.rs +++ b/src-tauri/core/src/style.rs @@ -48,7 +48,7 @@ fn pattern_id(p: HatchPattern) -> f64 { } /// Aufgelöste Schraffur (Kern von `resolveHatch`): Muster, Massstab, Endwinkel, Musterlinien-Stärke. -/// `None`, wenn Schraffur oder ihr Linienstil fehlen (TS wirft dort). +/// `None`, wenn die Schraffur fehlt; ein hängender Linienstil zählt wie keiner (0.13). pub struct HatchCore { pub pattern: HatchPattern, pub scale: f64, @@ -58,10 +58,7 @@ pub struct HatchCore { pub fn resolve_hatch_core(p: &Project, hatch_id: &str, wall_angle_deg: Option) -> Option { let h = p.hatch(hatch_id)?; - let ls = match h.line_style_id.as_deref().filter(|s| !s.is_empty()) { - Some(id) => Some(p.line_style(id)?), - None => None, - }; + let ls = h.line_style_id.as_deref().filter(|s| !s.is_empty()).and_then(|id| p.line_style(id)); let base = h.angle; let angle = match wall_angle_deg { Some(w) if h.relative_to_wall == Some(true) => base - w, diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 45e7e646..3db3d61c 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -39,6 +39,7 @@ mod layout_model; mod parametric_walls; mod reorder; mod text_layout; +mod project_refs; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/project_refs.rs b/src-tauri/core/src/web/project_refs.rs new file mode 100644 index 00000000..3d19635e --- /dev/null +++ b/src-tauri/core/src/web/project_refs.rs @@ -0,0 +1,17 @@ +//! Bindung der Projekt-Warnungen (`crate::project_refs`) für die TS-Fassade `projectWarnings` +//! (`src/core/ops.ts`) und `dossier-cli validate`. Eingabe das Projekt als JSON, Ausgabe ein +//! JSON-Array der Warnungen; kaputte Eingaben ergeben eine Warnung, nie einen Panic. + +use serde_json::Value; +use wasm_bindgen::prelude::wasm_bindgen; + +/// Warnungen (hängende Verweise, Zyklen, nicht lesbare Werte) eines Projekts. +#[wasm_bindgen] +pub fn project_warnings(project_json: &str) -> String { + let out = match serde_json::from_str::(project_json) { + Ok(Value::Object(m)) => crate::project_refs::project_warnings(&m), + Ok(_) => vec!["kein JSON-Objekt".to_string()], + Err(e) => vec![e.to_string()], + }; + Value::from(out).to_string() +} diff --git a/src/cli/cli.test.ts b/src/cli/cli.test.ts index 2f525eb2..a4c69a0f 100644 --- a/src/cli/cli.test.ts +++ b/src/cli/cli.test.ts @@ -38,6 +38,20 @@ describe("dossier-cli", () => { expect(JSON.parse(readFileSync(out, "utf8")).formatVersion).toBeGreaterThanOrEqual(1); }); + it("validate meldet hängende Verweise als Warnung, Plan rechnet trotzdem", async () => { + const broken = join(dir, "haengend.obp"); + const p = { ...sampleProject, walls: sampleProject.walls.map((w, i) => (i === 0 ? { ...w, wallTypeId: "nope" } : w)) }; + writeFileSync(broken, serializeProject(p)); + const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + try { + expect(await run([broken, "validate"])).toBe(0); + expect(err.mock.calls.map((c) => String(c[0])).join("")).toContain(`Warnung: Wand „${sampleProject.walls[0].id}": Wandtyp „nope" fehlt.`); + } finally { + err.mockRestore(); + } + expect(await run([broken, "plan", "--out", join(dir, "haengend.svg")])).toBe(0); + }); + it("Plan als SVG", async () => { const out = join(dir, "eg.svg"); expect(await call("plan", "--out", out)).toBe(0); diff --git a/src/cli/main.ts b/src/cli/main.ts index ed5b6578..04337e41 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -110,6 +110,7 @@ import { setWasmBytesProvider, initCore, validateProject, + projectWarnings, sampleProject, } from "../core"; import type { CoreOp, Project } from "../core"; @@ -556,11 +557,14 @@ async function execute(project: Project, file: string, command: string, rest: st } case "validate": { const problems = validateProject(project); + // Hängende Verweise u. Ä.: das Projekt lässt sich rechnen (Vorgaben), aber es soll auffallen. + const warnings = projectWarnings(project); + if (warnings.length) process.stderr.write(warnings.map((w) => `Warnung: ${w}`).join("\n") + "\n"); if (problems.length) { process.stderr.write(problems.join("\n") + "\n"); return 1; } - process.stdout.write("ok\n"); + process.stdout.write(warnings.length ? `ok (${warnings.length} Warnung${warnings.length === 1 ? "" : "en"})\n` : "ok\n"); return 0; } case "migrate": diff --git a/src/cli/mcp.ts b/src/cli/mcp.ts index 12bc8b09..c3699643 100644 --- a/src/cli/mcp.ts +++ b/src/cli/mcp.ts @@ -16,6 +16,7 @@ import { serializeProject, validateOps, validateProject, + projectWarnings, } from "../core"; import type { CoreOp, Project } from "../core"; @@ -124,7 +125,8 @@ export async function callTool(file: string, name: string, args: Record 0); + const warnings = projectWarnings(project).map((w) => `Warnung: ${w}`); + return text([...problems, ...warnings].join("\n") || "ok", problems.length > 0); } default: return text(`unbekanntes Werkzeug: ${name}`, true); diff --git a/src/core/extra.ts b/src/core/extra.ts index 60c8a878..2a6ca181 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -20,6 +20,7 @@ export { planToSvgString } from "../export/planToSvgString"; export { setWasmBytesProvider } from "../engine/wasmSource"; export { initCore, coreReady } from "../engine/coreWasm"; export { applyOps, validateProject, validateOps } from "./ops"; +export { projectWarnings } from "./ops"; export type { CoreOp } from "./ops"; export type { Project, DrawingLevel } from "../model/types"; export { computeKennzahlen, checkRoomProgram, solidVolume } from "../analysis/kennzahlen"; diff --git a/src/core/ops.ts b/src/core/ops.ts index 90b4aad3..e3466b31 100644 --- a/src/core/ops.ts +++ b/src/core/ops.ts @@ -174,6 +174,16 @@ export function validateProject(p: Project): string[] { return problemsOf(core().project_validate(JSON.stringify(p, markNonFinite))); } +/** + * Warnungen zu einem Projekt, das trotzdem geladen und gerechnet wird (Kern `project_refs.rs`): + * hängende Verweise (Wandtyp, Bauteil, Geschoss, Schraffur, Linienstil, Stift, Gruppe, Layout …), + * Gruppen/Ordner, die sich selbst enthalten, und Werte, die nicht zum Modell passen. Die + * Ableitungen setzen dort Vorgaben ein; `dossier-cli validate` meldet die Liste. + */ +export function projectWarnings(p: Project): string[] { + return problemsOf(core().project_warnings(JSON.stringify(p))); +} + /** * Prüft angewendete Ops (nur was sie anfassen, billig genug für jeden Drag-Schritt): nicht * endliche Zahlen in neuen/ersetzten Elementen und `setField`-Zahlen, NEUE doppelte ids in den diff --git a/src/core/robustness.test.ts b/src/core/robustness.test.ts new file mode 100644 index 00000000..5733eba2 --- /dev/null +++ b/src/core/robustness.test.ts @@ -0,0 +1,365 @@ +// Robustheit des Kerns gegen kaputte Projekte: Dateien von der Platte und Importe können hängende +// Verweise (Wandtyp, Bauteil, Geschoss, Gruppe, Schraffur, Linienstil, Stift …), fehlende Felder, +// NaN, leere Polygone, doppelte ids und Zyklen (Gruppen/Ordner, die sich selbst enthalten) tragen. +// Keine Abfrage und keine Fassade darf daran werfen oder (in Rust) in Panik geraten — sie fallen auf +// Vorgaben zurück, wie der übrige tolerante Modell-Code. `validate` meldet die Verweise als Warnung. + +import { beforeAll, describe, expect, it } from "vitest"; +import type { Layout, Project } from "../model/types"; +import { sampleProject } from "../model/sampleProject"; +import { bigSampleProject } from "../plan/bigSampleProject.testing"; +import { randomProject, richProject, rng } from "../model/richProject.testing"; +import { + computeSection, + generateElevationPlan, + generatePlan, + generateSectionPlan, + generateVisibleLevelsPlan, + pickGeometry, + planSceneBin, + planToRenderScene, + projectToModel3d, + wallMaterialColorMaps, +} from "./index"; +import { + buildPlanDxf, + checkRoomProgram, + checkSiteRules, + compareRoomProgram, + computeAreaTable, + computeIvhb, + computeKennzahlen, + exportGlb, + exportIfcSpf, + exportObj, + exportScheduleCsv, + exportStl, + layoutRoomProgram, + parseProjectFile, + planToSvgString, + projectLatLon, + serializeProject, + shadowPolygons, + sunPosition, + validateProject, + buildingFootprint, + modelTop, + projectWarnings, +} from "./extra"; +import { loadFileioForTests } from "../engine/fileioWasm.testing"; +import { buildLayoutTree, buildMasterTree, folderPdfPages, resolveTitleBlock, visibleCodesFromSnapshot } from "../model/layoutModel"; + +type Mut = Record; // eslint-disable-line @typescript-eslint/no-explicit-any + +const clone = (p: Project): Mut => JSON.parse(JSON.stringify(p)) as Mut; +const list = (p: Mut, k: string): Mut[] => (Array.isArray(p[k]) ? (p[k] as Mut[]) : []); + +/** Alle Kategorie-Codes (verschachtelt), wie die CLI. */ +function allCodes(p: Project): Set { + const out = new Set(); + const walk = (ls: unknown): void => { + if (!Array.isArray(ls)) return; + for (const l of ls as Mut[]) { + if (l && typeof l.code === "string") out.add(l.code); + walk(l?.children); + } + }; + walk(p.layers); + return out; +} + +/** Verdorbene Fassungen eines Projekts: Name → Projekt. */ +function corruptions(base: Project, seed: number): [string, Project][] { + const r = rng(seed); + const out: [string, Project][] = []; + const add = (name: string, f: (p: Mut) => void) => { + const p = clone(base); + f(p); + out.push([name, p as unknown as Project]); + }; + const some = (a: T[]): T[] => a.filter((_, i) => i === 0 || r() < 0.5); + + add("Wandtyp hängt", (p) => some(list(p, "walls")).forEach((w) => (w.wallTypeId = "nope"))); + add("alle Wandtypen weg", (p) => (p.wallTypes = [])); + add("Bauteil hängt", (p) => { + for (const k of ["wallTypes", "ceilingTypes", "roofTypes"]) for (const t of list(p, k)) for (const l of t.layers ?? []) l.componentId = "nope"; + }); + add("Bauteile weg", (p) => (p.components = [])); + add("Schraffur/Linienstil hängt", (p) => { + for (const c of list(p, "components")) { + c.hatchId = "nope"; + c.cutHatchId = "nope"; + c.lineStyleId = "nope"; + } + const walk = (ls: Mut[]) => { + for (const l of ls) { + l.hatchId = "nope"; + l.lineStyleId = "nope"; + l.penId = "nope"; + walk(l.children ?? []); + } + }; + walk(list(p, "layers")); + for (const d of list(p, "drawings2d")) { + d.hatchId = "nope"; + d.lineStyleId = "nope"; + d.penId = "nope"; + d.fillPenId = "nope"; + } + p.hatches = []; + p.lineStyles = []; + }); + add("Stifte hängen", (p) => { + p.activePenSetId = "nope"; + p.penSets = [{ id: "ps", name: "x", pens: { nope: { color: "not-a-color", weight: NaN } } }]; + for (const w of list(p, "walls")) w.penId = "nope"; + }); + add("Geschoss hängt", (p) => { + for (const k of ["walls", "stairs", "columns", "ceilings", "rooms"]) for (const e of list(p, k)) e.floorId = "nope"; + for (const k of ["drawings2d", "extrudedSolids"]) for (const e of list(p, k)) e.levelId = "nope"; + for (const e of list(p, "roofs")) e.floorId = "nope"; + for (const w of list(p, "walls")) { + w.bottom = { mode: "floor", floorId: "nope", offset: 0 }; + w.top = { mode: "floor", floorId: "nope2" }; + } + }); + add("Öffnung ohne Wand", (p) => list(p, "openings").forEach((o) => (o.hostWallId = "nope"))); + add("Typen hängen", (p) => { + for (const o of list(p, "openings")) o.typeId = "nope"; + for (const s of list(p, "stairs")) s.typeId = "nope"; + for (const c of list(p, "ceilings")) { + c.ceilingTypeId = "nope"; + c.wallTypeId = "nope"; + } + for (const rf of list(p, "roofs")) rf.roofTypeId = "nope"; + for (const d of list(p, "drawings2d")) if (d.geom?.shape === "block") d.geom.blockDefId = "nope"; + for (const pw of list(p, "parametricWalls")) pw.defaultWallTypeId = "nope"; + }); + add("Gruppen hängen und enthalten sich", (p) => { + p.groups = [ + { id: "g1", name: "A", wallIds: ["nope"], drawingIds: ["nope"], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: ["g1", "g2", "nope"] }, + { id: "g2", name: "B", wallIds: [list(p, "walls")[0]?.id ?? "x"], drawingIds: [], ceilingIds: [], roomIds: [], stairIds: [], columnIds: [], roofIds: [], openingIds: [], groupIds: ["g1"] }, + ]; + }); + add("Ordner zyklisch", (p) => { + p.viewSnapshotFolders = [ + { id: "f1", name: "A", parentId: "f2" }, + { id: "f2", name: "B", parentId: "f1" }, + { id: "f3", name: "C", parentId: "f3" }, + ]; + p.layoutFolders = [ + { id: "lf1", name: "A", kind: "layout", parentId: "lf2" }, + { id: "lf2", name: "B", kind: "layout", parentId: "lf1" }, + { id: "lf3", name: "C", kind: "master", parentId: "lf3" }, + ]; + for (const l of list(p, "layouts")) l.folderId = "lf1"; + for (const m of list(p, "masterLayouts")) m.folderId = "lf3"; + for (const s of list(p, "viewSnapshots")) s.folderId = "f1"; + }); + add("Layouts hängen", (p) => { + for (const l of list(p, "layouts")) { + l.masterId = "nope"; + l.folderId = "nope"; + for (const v of l.viewports ?? []) v.snapshotId = "nope"; + } + for (const s of list(p, "viewSnapshots")) { + s.activeLevelId = "nope"; + s.enabledOverrideRuleIds = ["nope"]; + } + }); + add("leere Polygone", (p) => { + for (const c of list(p, "ceilings")) c.outline = []; + for (const rm of list(p, "rooms")) rm.boundary = []; + for (const rf of list(p, "roofs")) rf.outline = []; + for (const x of list(p, "extrudedSolids")) x.points = []; + if (p.siteRules) p.siteRules.parcel = []; + for (const d of list(p, "drawings2d")) if (Array.isArray(d.geom?.pts)) d.geom.pts = []; + }); + add("Ein-Punkt-Polygone", (p) => { + for (const c of list(p, "ceilings")) c.outline = c.outline?.slice(0, 1) ?? []; + for (const rm of list(p, "rooms")) rm.boundary = rm.boundary?.slice(0, 2) ?? []; + for (const rf of list(p, "roofs")) rf.outline = rf.outline?.slice(0, 2) ?? []; + for (const w of list(p, "walls")) w.end = { ...w.start }; + }); + add("NaN", (p) => { + const ws = list(p, "walls"); + if (ws[0]) ws[0].start = { x: NaN, y: 0 }; + if (ws[1]) ws[1].height = NaN; + for (const c of list(p, "ceilings").slice(0, 1)) c.outline = [{ x: NaN, y: NaN }, { x: 1, y: 0 }, { x: 1, y: 1 }]; + for (const t of list(p, "wallTypes").slice(0, 1)) for (const l of t.layers ?? []) l.thickness = NaN; + for (const lv of list(p, "drawingLevels")) lv.baseElevation = NaN; + for (const o of list(p, "openings").slice(0, 2)) o.width = NaN; + for (const s of list(p, "stairs").slice(0, 1)) s.width = NaN; + }); + add("Unendlich und negativ", (p) => { + for (const w of list(p, "walls").slice(0, 2)) w.height = -3; + for (const t of list(p, "wallTypes")) for (const l of t.layers ?? []) l.thickness = -0.1; + for (const o of list(p, "openings").slice(0, 2)) { + o.width = 1e300; + o.offset = -1e300; + } + for (const s of list(p, "stairs")) { + s.steps = 1e9; + s.width = 0; + } + for (const c of list(p, "columns")) c.height = -1; + }); + add("fehlende Felder", (p) => { + for (const k of ["walls", "openings", "ceilings", "roofs", "stairs", "rooms", "columns", "drawings2d", "extrudedSolids", "wallTypes", "components", "drawingLevels", "hatches", "lineStyles", "layouts", "viewSnapshots"]) { + for (const e of some(list(p, k))) { + const keys = Object.keys(e).filter((x) => x !== "id"); + for (const x of keys) if (r() < 0.4) delete e[x]; + } + } + }); + add("doppelte ids", (p) => { + for (const k of ["walls", "openings", "ceilings", "roofs", "stairs", "rooms", "drawings2d", "wallTypes", "components", "drawingLevels", "hatches", "lineStyles", "layers"]) { + const a = list(p, k); + if (a.length) p[k] = [...a, ...a.map((e) => ({ ...e }))]; + } + }); + add("falsche Typen", (p) => { + for (const w of list(p, "walls").slice(0, 1)) { + w.height = "hoch"; + w.start = null; + } + for (const c of list(p, "ceilings").slice(0, 1)) c.outline = "keine Liste"; + for (const d of list(p, "drawings2d").slice(0, 2)) d.geom = { shape: "unbekannt" }; + for (const lv of list(p, "drawingLevels").slice(0, 1)) lv.kind = "unbekannt"; + }); + add("Schnitt-/Ansichtslinien kaputt", (p) => { + for (const lv of list(p, "drawingLevels")) { + if (lv.kind === "section" || lv.kind === "elevation") { + lv.line = { a: { x: 0, y: 0 }, b: { x: 0, y: 0 } }; + lv.depth = NaN; + } + } + }); + add("Baurecht/Sonne kaputt", (p) => { + p.siteRules = { parcel: [{ x: 0, y: 0 }, { x: NaN, y: 1 }, { x: 1, y: 1 }], setbacks: [NaN, -1], defaultSetback: NaN, buildingLines: [{ a: { x: 0, y: 0 }, b: { x: 0, y: 0 } }], maxHeight: NaN, show: true }; + p.sunStudy = { when: "kein Datum", show: true }; + p.geoAnchor = { lv95: { e: NaN, n: 1e12 }, height: NaN, model: { x: 0, y: 0 } }; + }); + return out; +} + +/** Ruft alle Kern-Abfragen/Fassaden auf ein Projekt auf; liefert die Fehler (Name: Meldung). */ +async function runAll(project: Project): Promise { + const errors: string[] = []; + const run = async (name: string, f: () => unknown): Promise => { + try { + return await f(); + } catch (e) { + errors.push(`${name}: ${e instanceof Error ? e.message : String(e)}`); + return undefined; + } + }; + const codes = allCodes(project); + const levels = Array.isArray(project.drawingLevels) ? project.drawingLevels.filter((l) => l && typeof l === "object") : []; + const plans: unknown[] = []; + for (const l of levels) { + if (l.kind === "section") { + const o = (await run(`computeSection ${l.id}`, () => computeSection(project, l))) as Awaited> | undefined; + if (o) plans.push(await run(`generateSectionPlan ${l.id}`, () => generateSectionPlan(o, false, { visibleCodes: codes, hiddenLines: true, openings: true }))); + } else if (l.kind === "elevation") { + plans.push(await run(`generateElevationPlan ${l.id}`, () => generateElevationPlan(project, l))); + } else { + plans.push(await run(`generatePlan ${l.id}`, () => generatePlan(project, l.id, codes, undefined, "fein", true, false, true, 50))); + await run(`generateVisibleLevelsPlan ${l.id}`, () => generateVisibleLevelsPlan(project, l.id, codes)); + } + } + await run("generatePlan unbekanntes Geschoss", () => generatePlan(project, "nope", codes)); + for (const [i, plan] of plans.entries()) { + if (!plan) continue; + const pl = plan as Parameters[0]; + await run(`planToRenderScene #${i}`, () => planToRenderScene(pl, 100)); + await run(`planSceneBin #${i}`, () => planSceneBin(pl, 100)); + await run(`planToSvgString #${i}`, () => planToSvgString(pl, { scaleDenominator: 100 })); + await run(`buildPlanDxf #${i}`, () => buildPlanDxf(pl, project)); + } + await run("projectToModel3d", () => projectToModel3d(project)); + await run("pickGeometry", () => pickGeometry(project)); + await run("wallMaterialColorMaps", () => wallMaterialColorMaps(project)); + await run("exportIfcSpf", () => exportIfcSpf(project)); + await run("exportObj", () => exportObj(project)); + await run("exportStl", () => exportStl(project)); + await run("exportGlb", () => exportGlb(project)); + await run("exportScheduleCsv", () => exportScheduleCsv(project)); + await run("computeKennzahlen", () => computeKennzahlen(project)); + await run("checkRoomProgram", () => checkRoomProgram(project)); + await run("compareRoomProgram", () => compareRoomProgram(project)); + await run("layoutRoomProgram", () => layoutRoomProgram(project)); + await run("computeAreaTable", () => computeAreaTable(project)); + await run("computeIvhb", () => computeIvhb(project)); + await run("checkSiteRules", () => checkSiteRules(project)); + await run("buildingFootprint", () => buildingFootprint(project)); + await run("modelTop", () => modelTop(project)); + await run("sun", () => { + const { lat, lon } = projectLatLon(project); + return shadowPolygons(project, sunPosition(lat, lon, new Date(Date.UTC(2026, 5, 21, 10)))); + }); + await run("Layouts", () => { + const layouts = Array.isArray(project.layouts) ? project.layouts : []; + const masters = Array.isArray(project.masterLayouts) ? project.masterLayouts : []; + const folders = Array.isArray(project.layoutFolders) ? project.layoutFolders : []; + buildLayoutTree(folders, layouts); + buildMasterTree(folders, masters); + for (const f of folders) folderPdfPages(project, f.id); + for (const l of layouts as Layout[]) { + resolveTitleBlock(project, l, masters.find((m) => m.id === l.masterId), "2026-10-29"); + for (const v of l.viewports ?? []) { + const snap = (project.viewSnapshots ?? []).find((s) => s.id === v.snapshotId); + if (snap) generatePlan(project, snap.activeLevelId ?? "", visibleCodesFromSnapshot(snap)); + } + } + }); + await run("validateProject", () => validateProject(project)); + await run("projectWarnings", () => projectWarnings(project)); + await run("serialize/parse", () => { + const r = parseProjectFile(serializeProject(project)); + if (!r.ok) throw new Error(r.error); + }); + return errors; +} + +describe("Kern robust gegen kaputte Projekte", () => { + beforeAll(async () => { + await loadFileioForTests(); + }); + + const bases: [string, () => Project][] = [ + ["Beispiel", () => sampleProject], + ["alle Element-Arten", () => richProject()], + ...[1, 3, 5, 8, 11, 13, 21].map((seed): [string, () => Project] => [`Zufall ${seed}`, () => randomProject(seed)]), + ["Kacheln 2×2", () => bigSampleProject(2)], + ]; + + for (const [baseName, make] of bases) { + it(`${baseName}: keine Abfrage wirft`, async () => { + const base = make(); + const failures: string[] = []; + for (const [i, [name, p]] of corruptions(base, 7 + baseName.length).entries()) { + for (const e of await runAll(p)) failures.push(`[${name} #${i}] ${e}`); + } + expect(failures).toEqual([]); + }, 240_000); + } + + it("hängender Wandtyp: Plan wie mit dem Rückfall-Typ (kein Werfen, Wand bleibt sichtbar)", () => { + const p = clone(sampleProject); + p.walls[0].wallTypeId = "nope"; + const floor = sampleProject.drawingLevels.find((l) => l.kind === "floor")!; + const plan = generatePlan(p as Project, floor.id, allCodes(sampleProject)); + expect(plan.primitives.some((x) => x.kind === "polygon" && (x as { wallId?: string }).wallId === p.walls[0].id)).toBe(true); + }); + + it("validate meldet hängende Verweise als Warnung", () => { + const p = clone(sampleProject); + p.walls[0].wallTypeId = "nope"; + p.openings[0].hostWallId = "wand-fehlt"; + const w = projectWarnings(p as Project); + expect(w.some((x) => x.includes("nope"))).toBe(true); + expect(w.some((x) => x.includes("wand-fehlt"))).toBe(true); + expect(projectWarnings(sampleProject)).toEqual([]); + }); +}); diff --git a/src/export/exportIfc.test.ts b/src/export/exportIfc.test.ts index f09dd7ef..5a1ae6c4 100644 --- a/src/export/exportIfc.test.ts +++ b/src/export/exportIfc.test.ts @@ -703,10 +703,12 @@ describe("[B5] Pset_*Common mit den Werten aus dem Modell", () => { }); describe("Sammler im Kern ([K4], 29.10.)", () => { - it("Fehler des Kerns kommen mit dessen Meldung (unbekannter Wandtyp)", () => { + it("hängender Wandtyp (Datei/Import): Export mit dem Rückfall-Typ statt Abbruch", () => { const p = fixtureProject(); const broken: Project = { ...p, walls: p.walls.map((w, i) => (i === 0 ? { ...w, wallTypeId: "fehlt" } : w)) }; - expect(() => exportIfcSpf(broken)).toThrow("Unbekannter Wandtyp: fehlt"); + const spf = exportIfcSpf(broken); + expect(spf).toContain("IFCWALL"); + expect(spf).toContain(p.walls[0].id); }); it("zweimal exportieren gibt dieselbe Datei (bis auf den Zeitstempel)", () => { diff --git a/src/model/layoutModel.ts b/src/model/layoutModel.ts index 9e83b58c..3cfce168 100644 --- a/src/model/layoutModel.ts +++ b/src/model/layoutModel.ts @@ -568,7 +568,7 @@ export function resolveTitleBlock( today: string = new Date().toISOString().slice(0, 10), ): ResolvedTitleBlock { const arg = { - layout: { id: layout.id, name: layout.name, planNumber: layout.planNumber, viewports: layout.viewports.slice(0, 1) }, + layout: { id: layout.id, name: layout.name, planNumber: layout.planNumber, viewports: (layout.viewports ?? []).slice(0, 1) }, master: master ? { titleBlock: master.titleBlock } : null, today, }; @@ -581,7 +581,8 @@ export function resolveTitleBlock( */ export function visibleCodesFromSnapshot(snap: ViewSnapshot): Set { const out = new Set(); - for (const [code, visible] of Object.entries(snap.layerVisibility)) { + // Fehlt die Map (Datei/Import), ist nichts sichtbar — kein Absturz. + for (const [code, visible] of Object.entries(snap.layerVisibility ?? {})) { if (visible) out.add(code); } return out; diff --git a/src/model/richProject.testing.ts b/src/model/richProject.testing.ts new file mode 100644 index 00000000..222d7196 --- /dev/null +++ b/src/model/richProject.testing.ts @@ -0,0 +1,154 @@ +// Testhilfe: Beispielprojekt mit allen Element-Arten (`richProject`) und daraus abgeleitete +// Zufallsprojekte (`randomProject`, Listen gemischt/gekürzt, Zahlen verrauscht, optionale Felder weg). +// Genutzt von der Modell-Rundreise und dem Robustheitstest des Kerns. + +import { sampleProject } from "./sampleProject"; +import type { Drawing2DGeom, LayoutAnnotation, ParametricRule, Project, RichTextDoc } from "./types"; + +export const plain = (p: unknown): unknown => JSON.parse(JSON.stringify(p)); + +const doc: RichTextDoc = { + version: 1, + paragraphs: [{ runs: [{ text: "Hallo", marks: { bold: true, sizePt: 9, color: "#112233", super: true } }], align: "center", lineHeight: 1.2 }], +}; + +const geoms: Drawing2DGeom[] = [ + { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } }, + { shape: "xline", a: { x: 0, y: 0 }, b: { x: 1, y: 1 } }, + { shape: "ray", a: { x: 0, y: 0 }, b: { x: 0, y: 1 } }, + { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], closed: true, bulge: [0, 0.5, 0] }, + { shape: "rect", min: { x: 0, y: 0 }, max: { x: 2, y: 1 } }, + { shape: "circle", center: { x: 1, y: 1 }, r: 0.5 }, + { shape: "arc", center: { x: 1, y: 1 }, r: 0.5, a0: 0, a1: 1.5 }, + { shape: "ellipse", center: { x: 1, y: 1 }, rx: 2, ry: 1, rotation: 0.3 }, + { shape: "bezier", pts: [{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 1 }, { x: 3, y: 0 }] }, + { shape: "spline", pts: [{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 0 }], closed: false, mode: "control" }, + { + shape: "dimension", pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }], offset: 0.5, gapMm: 1, overshootMm: 2, tickLenMm: 3, + textHeightMm: 2.5, lineWeightMm: 0.18, extWeightMm: 0.13, tickWeightMm: 0.35, textOffsetsMm: [{ along: 1, perp: -1 }], + }, + { shape: "kote", at: { x: 1, y: 2 }, value: 3.05, kind: "ukRoh", rotation: 0 }, + { shape: "detailref", at: { x: 1, y: 2 }, label: "3", sheetLayoutId: "lay1", sheetLabel: "A-12" }, + { shape: "scalebar", at: { x: 0, y: -2 }, segmentLength: 1, segments: 5 }, + { shape: "pointmarker", at: { x: 2, y: 2 } }, + { + shape: "text", at: { x: 0, y: 3 }, text: "Notiz", height: 0.25, angle: 0.1, width: 2, marks: { italic: true }, doc, + leaderTarget: { x: 1, y: 1 }, leaderBendPoints: [{ x: 0.5, y: 2 }], pathPts: [{ x: 0, y: 3 }, { x: 2, y: 3 }], + }, + { shape: "block", blockDefId: "blk1", at: { x: 5, y: 5 }, rotation: 1.57, scale: 2 }, + { shape: "image", min: { x: 0, y: 0 }, max: { x: 1, y: 1 }, src: "data:image/png;base64,AAAA", opacity: 0.5 }, +]; + +const rules: ParametricRule[] = [ + { type: "grid", spacing: 3, directions: "both", wallTypeId: "wt1", referenceLine: "center", height: 2.8 }, + { type: "module", moduleSize: 1.2, direction: "x", referenceWallId: "w1" }, + { type: "conditional-thickness", condition: "exterior", wallTypeId: "wt1", logic: "or" }, + { type: "reference-line", referenceLine: "left", target: "all" }, + { type: "sequence", rules: [{ type: "reference-line", referenceLine: "right", target: "exterior" }], stopOnMatch: true }, +]; + +const annotations: LayoutAnnotation[] = [ + { kind: "line", id: "a1", x1Mm: 0, y1Mm: 0, x2Mm: 10, y2Mm: 10, color: "#000000", weightMm: 0.25 }, + { kind: "rect", id: "a2", xMm: 1, yMm: 2, widthMm: 30, heightMm: 20 }, + { kind: "text", id: "a3", xMm: 1, yMm: 2, text: "Titel", heightMm: 5, doc, widthMm: 40 }, + { kind: "image", id: "a4", xMm: 1, yMm: 2, widthMm: 30, heightMm: 20, src: "data:image/png;base64,AAAA", opacity: 1 }, +]; + +/** Beispielprojekt, ergänzt um alle Element-Arten, die es selbst nicht enthält. */ +export function richProject(): Project { + const lvl = sampleProject.drawingLevels[0].id; + return { + ...sampleProject, + formatVersion: 2, + textStyles: [{ id: "ts1", label: "Titel", marks: { bold: true, font: "Helvetica", sizePt: 14 } }], + blockDefs: [{ id: "blk1", name: "Nordpfeil", geom2d: geoms.slice(0, 4) }], + pens: [{ id: "pen1", name: "Kontur" }], + penSets: [{ id: "ps1", name: "Standard", pens: { pen1: { color: "#000000", weight: 0.35 } } }], + activePenSetId: "ps1", + customPalettes: [{ id: "pal1", name: "Projekt", colors: ["#ff0000", "#00ff00"], visible: true }], + builtinPaletteBanks: { ral: false, tango: true }, + roomProgram: [{ name: "Wohnen", siaCategory: "HNF", area: 30, count: 2, group: "Wohnung", note: "Süd" }], + roomProgramTolerance: 0.1, + parcelArea: 812, + sunStudy: { when: "2026-06-21T12:00", show: true }, + siteRules: { + parcel: [{ x: -5, y: -5 }, { x: 30, y: -5 }, { x: 30, y: 30 }], + setbacks: [3, 4, 5], defaultSetback: 4, buildingLines: [{ a: { x: 0, y: 0 }, b: { x: 10, y: 0 } }], maxHeight: 15, show: true, + }, + scaleLineWeights: true, + drawings2d: geoms.map((geom, i) => ({ + id: `d${i}`, type: "drawing2d" as const, levelId: lvl, categoryCode: "90", geom, + ...(i % 2 ? { noPrint: true, endMarks: { start: "arrow" as const, end: "dot" as const, sizeMm: 2 }, opacity: 0.8 } : {}), + ...(i % 3 === 0 ? { hatchOrigin: { x: 1, y: 1 }, hatchSource: "layer" as const, weightMm: 0.5, fillColor: "#eeeeee" } : {}), + })), + context: [ + { type: "importedMesh", id: "c1", name: "Nachbar", layer: "L", categoryCode: "95", color: "#aabbcc", ifcGlobalId: "2O2Fr$t4X7Zf8NOew3FLOH", positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [0, 1, 2] }, + { + type: "contourSet", id: "c2", name: "Höhenlinien", contours: [ + { z: 400, pts: [{ x: 0, y: 0 }, { x: 5, y: 1 }], closed: false, layer: "HL", filled: true }, + { z: 401, pts: [], closed: false, curve: { kind: "arc", cx: 0, cy: 0, r: 2, a0: 0, a1: 1 } }, + ], + }, + { type: "terrainMesh", id: "c3", name: "Gelände", positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [0, 1, 2], vertexColors: [1, 0, 0, 0, 1, 0, 0, 0, 1] }, + { type: "image", id: "c4", name: "Luftbild", src: "data:image/png;base64,AAAA", min: { x: 0, y: 0 }, max: { x: 10, y: 10 }, opacity: 0.7, drape: true, filters: { saturation: 0.5, grayscale: 1 } }, + ], + extrudedSolids: [ + { id: "x1", type: "extrudedSolid", levelId: lvl, points: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], height: 2, baseOffset: 0.1, operation: "subtract", taper: 0.1, cornerRadius: 0.05, chamfer: 0.02 }, + { id: "x2", type: "extrudedSolid", levelId: lvl, points: [], height: 1, circle: { center: { x: 3, y: 3 }, r: 0.4 }, brep: { spec: { kind: "box", w: 1, nested: { a: [1, 2] } }, origin: { x: 0, y: 0 }, label: "Quader" } }, + ], + columns: [ + { + id: "col1", type: "column", floorId: lvl, categoryCode: "50", position: { x: 2, y: 2 }, profile: { kind: "round", radius: 0.15 }, + rotation: 0, height: 2.6, bottom: { mode: "floor", floorId: lvl, offset: -0.1 }, top: { mode: "custom", z: 3 }, strokeWeightSource: "object", + }, + { id: "col2", type: "column", floorId: lvl, categoryCode: "50", position: { x: 4, y: 2 }, profile: { kind: "rect", width: 0.3, depth: 0.2 }, rotation: 0.5, height: 2.6 }, + ], + groups: [{ id: "g1", name: "Gruppe", wallIds: [sampleProject.walls[0].id], drawingIds: ["d1"], ceilingIds: [], roomIds: [], stairIds: [], columnIds: ["col1"], roofIds: [], openingIds: [], groupIds: [] }], + parametricWalls: [{ id: "pw1", name: "Raster", description: "Test", rules, defaultWallTypeId: sampleProject.wallTypes[0].id }], + overrideRules: [{ id: "or1", name: "Rot", enabled: true, condition: { type: "layer_name", operator: "contains", value: "Wand" }, actions: { color: "#ff0000", lineweight: 0.5 } }], + viewSnapshots: [{ + id: "vs1", name: "EG", folderId: "vf1", viewType: "grundriss", view3d: "isoBackLeft", fov: 50, scaleDenominator: 100, detail: "fein", activeLevelId: lvl, + layerVisibility: { "10": true, "20": false }, drawingVisibility: { [lvl]: true }, enabledOverrideRuleIds: ["or1"], cameraCenter: { x: 1, y: 2 }, cameraPxPerMeter: 40, + }], + viewSnapshotFolders: [{ id: "vf1", name: "Pläne" }, { id: "vf2", name: "Unter", parentId: "vf1" }], + layouts: [{ id: "lay1", name: "Blatt 1", paper: "a3", orientation: "landscape", planNumber: "A-12", masterId: "m1", folderId: "lf1", viewports: [{ id: "vp1", snapshotId: "vs1", xMm: 10, yMm: 10, widthMm: 200, heightMm: 150, scaleDenominator: 50 }], annotations }], + masterLayouts: [{ id: "m1", name: "Master", paper: "a3", orientation: "landscape", titleBlock: { projectName: "P", sheetName: "S", scale: "1:100", date: "28.10.", author: "K" }, border: true }], + layoutFolders: [{ id: "lf1", name: "Pläne", kind: "layout" }], + referenceElevationMasl: 432.1, + geoAnchor: { lv95: { e: 2600000, n: 1200000 }, height: 432, model: { x: 0, y: 0 }, label: "Bern" }, + }; +} + +/** Zufallsgenerator mit Saat (LCG, reproduzierbar). */ +export function rng(seed: number): () => number { + let x = seed >>> 0; + return () => (x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296; +} + +// Optionale Projekt-Felder (laut Typ) — dürfen in Zufallsprojekten fehlen. +const OPTIONAL_KEYS = [ + "formatVersion", "textStyles", "ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens", "penSets", + "activePenSetId", "customPalettes", "builtinPaletteBanks", "roomProgram", "roomProgramTolerance", "parcelArea", "sunStudy", "siteRules", + "scaleLineWeights", "ceilings", "roofs", "openings", "stairs", "rooms", "context", "extrudedSolids", "columns", "groups", + "parametricWalls", "overrideRules", "viewSnapshots", "viewSnapshotFolders", "layouts", "masterLayouts", "layoutFolders", + "referenceElevationMasl", "geoAnchor", +] as const satisfies readonly (keyof Project)[]; + +/** Zufallsprojekt: Listen gemischt/gekürzt/verdoppelt, Zahlen verrauscht, optionale Felder weggelassen. */ +export function randomProject(seed: number): Project { + const r = rng(seed); + const jitter = (v: unknown, depth = 0): unknown => { + if (typeof v === "number") return r() < 0.5 ? v : Math.round((v + (r() - 0.5) * 10) * 1e6) / 1e6; + if (Array.isArray(v)) { + let a = v.map((x) => jitter(x, depth + 1)); + if (depth === 1 && a.length > 1 && r() < 0.3) a = a.filter(() => r() < 0.7); + if (depth === 1 && r() < 0.2) a = [...a].reverse(); + return a; + } + if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, jitter(x, depth + 1)])); + return v; + }; + const p = jitter(plain(richProject()), 0) as Record; + for (const k of OPTIONAL_KEYS) if (r() < 0.25) delete p[k]; + return p as unknown as Project; +} diff --git a/src/model/types.roundtrip.test.ts b/src/model/types.roundtrip.test.ts index d7d60fba..4d3dfd07 100644 --- a/src/model/types.roundtrip.test.ts +++ b/src/model/types.roundtrip.test.ts @@ -6,9 +6,8 @@ import { describe, expect, it } from "vitest"; import { ProjectDocument } from "../core/document"; import { sampleProject } from "./sampleProject"; -import type { Drawing2DGeom, LayoutAnnotation, ParametricRule, Project, RichTextDoc } from "./types"; - -const plain = (p: unknown): unknown => JSON.parse(JSON.stringify(p)); +import type { Project } from "./types"; +import { plain, randomProject, richProject } from "./richProject.testing"; function viaRust(p: Project): unknown { const d = new ProjectDocument(p); @@ -35,152 +34,6 @@ function diffPaths(a: unknown, b: unknown, path = "", out: string[] = []): strin return out; } -const doc: RichTextDoc = { - version: 1, - paragraphs: [{ runs: [{ text: "Hallo", marks: { bold: true, sizePt: 9, color: "#112233", super: true } }], align: "center", lineHeight: 1.2 }], -}; - -const geoms: Drawing2DGeom[] = [ - { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } }, - { shape: "xline", a: { x: 0, y: 0 }, b: { x: 1, y: 1 } }, - { shape: "ray", a: { x: 0, y: 0 }, b: { x: 0, y: 1 } }, - { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], closed: true, bulge: [0, 0.5, 0] }, - { shape: "rect", min: { x: 0, y: 0 }, max: { x: 2, y: 1 } }, - { shape: "circle", center: { x: 1, y: 1 }, r: 0.5 }, - { shape: "arc", center: { x: 1, y: 1 }, r: 0.5, a0: 0, a1: 1.5 }, - { shape: "ellipse", center: { x: 1, y: 1 }, rx: 2, ry: 1, rotation: 0.3 }, - { shape: "bezier", pts: [{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 1 }, { x: 3, y: 0 }] }, - { shape: "spline", pts: [{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 0 }], closed: false, mode: "control" }, - { - shape: "dimension", pts: [{ x: 0, y: 0 }, { x: 4, y: 0 }], offset: 0.5, gapMm: 1, overshootMm: 2, tickLenMm: 3, - textHeightMm: 2.5, lineWeightMm: 0.18, extWeightMm: 0.13, tickWeightMm: 0.35, textOffsetsMm: [{ along: 1, perp: -1 }], - }, - { shape: "kote", at: { x: 1, y: 2 }, value: 3.05, kind: "ukRoh", rotation: 0 }, - { shape: "detailref", at: { x: 1, y: 2 }, label: "3", sheetLayoutId: "lay1", sheetLabel: "A-12" }, - { shape: "scalebar", at: { x: 0, y: -2 }, segmentLength: 1, segments: 5 }, - { shape: "pointmarker", at: { x: 2, y: 2 } }, - { - shape: "text", at: { x: 0, y: 3 }, text: "Notiz", height: 0.25, angle: 0.1, width: 2, marks: { italic: true }, doc, - leaderTarget: { x: 1, y: 1 }, leaderBendPoints: [{ x: 0.5, y: 2 }], pathPts: [{ x: 0, y: 3 }, { x: 2, y: 3 }], - }, - { shape: "block", blockDefId: "blk1", at: { x: 5, y: 5 }, rotation: 1.57, scale: 2 }, - { shape: "image", min: { x: 0, y: 0 }, max: { x: 1, y: 1 }, src: "data:image/png;base64,AAAA", opacity: 0.5 }, -]; - -const rules: ParametricRule[] = [ - { type: "grid", spacing: 3, directions: "both", wallTypeId: "wt1", referenceLine: "center", height: 2.8 }, - { type: "module", moduleSize: 1.2, direction: "x", referenceWallId: "w1" }, - { type: "conditional-thickness", condition: "exterior", wallTypeId: "wt1", logic: "or" }, - { type: "reference-line", referenceLine: "left", target: "all" }, - { type: "sequence", rules: [{ type: "reference-line", referenceLine: "right", target: "exterior" }], stopOnMatch: true }, -]; - -const annotations: LayoutAnnotation[] = [ - { kind: "line", id: "a1", x1Mm: 0, y1Mm: 0, x2Mm: 10, y2Mm: 10, color: "#000000", weightMm: 0.25 }, - { kind: "rect", id: "a2", xMm: 1, yMm: 2, widthMm: 30, heightMm: 20 }, - { kind: "text", id: "a3", xMm: 1, yMm: 2, text: "Titel", heightMm: 5, doc, widthMm: 40 }, - { kind: "image", id: "a4", xMm: 1, yMm: 2, widthMm: 30, heightMm: 20, src: "data:image/png;base64,AAAA", opacity: 1 }, -]; - -/** Beispielprojekt, ergänzt um alle Element-Arten, die es selbst nicht enthält. */ -function richProject(): Project { - const lvl = sampleProject.drawingLevels[0].id; - return { - ...sampleProject, - formatVersion: 2, - textStyles: [{ id: "ts1", label: "Titel", marks: { bold: true, font: "Helvetica", sizePt: 14 } }], - blockDefs: [{ id: "blk1", name: "Nordpfeil", geom2d: geoms.slice(0, 4) }], - pens: [{ id: "pen1", name: "Kontur" }], - penSets: [{ id: "ps1", name: "Standard", pens: { pen1: { color: "#000000", weight: 0.35 } } }], - activePenSetId: "ps1", - customPalettes: [{ id: "pal1", name: "Projekt", colors: ["#ff0000", "#00ff00"], visible: true }], - builtinPaletteBanks: { ral: false, tango: true }, - roomProgram: [{ name: "Wohnen", siaCategory: "HNF", area: 30, count: 2, group: "Wohnung", note: "Süd" }], - roomProgramTolerance: 0.1, - parcelArea: 812, - sunStudy: { when: "2026-06-21T12:00", show: true }, - siteRules: { - parcel: [{ x: -5, y: -5 }, { x: 30, y: -5 }, { x: 30, y: 30 }], - setbacks: [3, 4, 5], defaultSetback: 4, buildingLines: [{ a: { x: 0, y: 0 }, b: { x: 10, y: 0 } }], maxHeight: 15, show: true, - }, - scaleLineWeights: true, - drawings2d: geoms.map((geom, i) => ({ - id: `d${i}`, type: "drawing2d" as const, levelId: lvl, categoryCode: "90", geom, - ...(i % 2 ? { noPrint: true, endMarks: { start: "arrow" as const, end: "dot" as const, sizeMm: 2 }, opacity: 0.8 } : {}), - ...(i % 3 === 0 ? { hatchOrigin: { x: 1, y: 1 }, hatchSource: "layer" as const, weightMm: 0.5, fillColor: "#eeeeee" } : {}), - })), - context: [ - { type: "importedMesh", id: "c1", name: "Nachbar", layer: "L", categoryCode: "95", color: "#aabbcc", ifcGlobalId: "2O2Fr$t4X7Zf8NOew3FLOH", positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [0, 1, 2] }, - { - type: "contourSet", id: "c2", name: "Höhenlinien", contours: [ - { z: 400, pts: [{ x: 0, y: 0 }, { x: 5, y: 1 }], closed: false, layer: "HL", filled: true }, - { z: 401, pts: [], closed: false, curve: { kind: "arc", cx: 0, cy: 0, r: 2, a0: 0, a1: 1 } }, - ], - }, - { type: "terrainMesh", id: "c3", name: "Gelände", positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [0, 1, 2], vertexColors: [1, 0, 0, 0, 1, 0, 0, 0, 1] }, - { type: "image", id: "c4", name: "Luftbild", src: "data:image/png;base64,AAAA", min: { x: 0, y: 0 }, max: { x: 10, y: 10 }, opacity: 0.7, drape: true, filters: { saturation: 0.5, grayscale: 1 } }, - ], - extrudedSolids: [ - { id: "x1", type: "extrudedSolid", levelId: lvl, points: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }], height: 2, baseOffset: 0.1, operation: "subtract", taper: 0.1, cornerRadius: 0.05, chamfer: 0.02 }, - { id: "x2", type: "extrudedSolid", levelId: lvl, points: [], height: 1, circle: { center: { x: 3, y: 3 }, r: 0.4 }, brep: { spec: { kind: "box", w: 1, nested: { a: [1, 2] } }, origin: { x: 0, y: 0 }, label: "Quader" } }, - ], - columns: [ - { - id: "col1", type: "column", floorId: lvl, categoryCode: "50", position: { x: 2, y: 2 }, profile: { kind: "round", radius: 0.15 }, - rotation: 0, height: 2.6, bottom: { mode: "floor", floorId: lvl, offset: -0.1 }, top: { mode: "custom", z: 3 }, strokeWeightSource: "object", - }, - { id: "col2", type: "column", floorId: lvl, categoryCode: "50", position: { x: 4, y: 2 }, profile: { kind: "rect", width: 0.3, depth: 0.2 }, rotation: 0.5, height: 2.6 }, - ], - groups: [{ id: "g1", name: "Gruppe", wallIds: [sampleProject.walls[0].id], drawingIds: ["d1"], ceilingIds: [], roomIds: [], stairIds: [], columnIds: ["col1"], roofIds: [], openingIds: [], groupIds: [] }], - parametricWalls: [{ id: "pw1", name: "Raster", description: "Test", rules, defaultWallTypeId: sampleProject.wallTypes[0].id }], - overrideRules: [{ id: "or1", name: "Rot", enabled: true, condition: { type: "layer_name", operator: "contains", value: "Wand" }, actions: { color: "#ff0000", lineweight: 0.5 } }], - viewSnapshots: [{ - id: "vs1", name: "EG", folderId: "vf1", viewType: "grundriss", view3d: "isoBackLeft", fov: 50, scaleDenominator: 100, detail: "fein", activeLevelId: lvl, - layerVisibility: { "10": true, "20": false }, drawingVisibility: { [lvl]: true }, enabledOverrideRuleIds: ["or1"], cameraCenter: { x: 1, y: 2 }, cameraPxPerMeter: 40, - }], - viewSnapshotFolders: [{ id: "vf1", name: "Pläne" }, { id: "vf2", name: "Unter", parentId: "vf1" }], - layouts: [{ id: "lay1", name: "Blatt 1", paper: "a3", orientation: "landscape", planNumber: "A-12", masterId: "m1", folderId: "lf1", viewports: [{ id: "vp1", snapshotId: "vs1", xMm: 10, yMm: 10, widthMm: 200, heightMm: 150, scaleDenominator: 50 }], annotations }], - masterLayouts: [{ id: "m1", name: "Master", paper: "a3", orientation: "landscape", titleBlock: { projectName: "P", sheetName: "S", scale: "1:100", date: "28.10.", author: "K" }, border: true }], - layoutFolders: [{ id: "lf1", name: "Pläne", kind: "layout" }], - referenceElevationMasl: 432.1, - geoAnchor: { lv95: { e: 2600000, n: 1200000 }, height: 432, model: { x: 0, y: 0 }, label: "Bern" }, - }; -} - -/** Zufallsgenerator mit Saat (LCG, reproduzierbar). */ -function rng(seed: number): () => number { - let x = seed >>> 0; - return () => (x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296; -} - -// Optionale Projekt-Felder (laut Typ) — dürfen in Zufallsprojekten fehlen. -const OPTIONAL_KEYS = [ - "formatVersion", "textStyles", "ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens", "penSets", - "activePenSetId", "customPalettes", "builtinPaletteBanks", "roomProgram", "roomProgramTolerance", "parcelArea", "sunStudy", "siteRules", - "scaleLineWeights", "ceilings", "roofs", "openings", "stairs", "rooms", "context", "extrudedSolids", "columns", "groups", - "parametricWalls", "overrideRules", "viewSnapshots", "viewSnapshotFolders", "layouts", "masterLayouts", "layoutFolders", - "referenceElevationMasl", "geoAnchor", -] as const satisfies readonly (keyof Project)[]; - -/** Zufallsprojekt: Listen gemischt/gekürzt/verdoppelt, Zahlen verrauscht, optionale Felder weggelassen. */ -function randomProject(seed: number): Project { - const r = rng(seed); - const jitter = (v: unknown, depth = 0): unknown => { - if (typeof v === "number") return r() < 0.5 ? v : Math.round((v + (r() - 0.5) * 10) * 1e6) / 1e6; - if (Array.isArray(v)) { - let a = v.map((x) => jitter(x, depth + 1)); - if (depth === 1 && a.length > 1 && r() < 0.3) a = a.filter(() => r() < 0.7); - if (depth === 1 && r() < 0.2) a = [...a].reverse(); - return a; - } - if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, jitter(x, depth + 1)])); - return v; - }; - const p = jitter(plain(richProject()), 0) as Record; - for (const k of OPTIONAL_KEYS) if (r() < 0.25) delete p[k]; - return p as unknown as Project; -} - describe("Modell-Rundreise TS → Rust → TS ([K4] S4)", () => { it("Beispielprojekt bleibt gleich", () => { const back = viaRust(sampleProject);