[K3c][14][12] Merge: Strichmuster auch auf dem Chunk-Weg (native Mac-Anzeige), kaputte Projekte lassen keine Abfrage mehr abbrechen, validate warnt

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-29 12:42:37 +00:00
commit 3ddb36c7f1
40 files changed
+2150 -324

No files matched your search

+7 -12
View File
@@ -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<String> = 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"))
}
+358 -16
View File
@@ -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<f64> {
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<f32>,
@@ -58,6 +93,9 @@ pub struct GpuOut {
pub line_verts: Vec<u32>,
pub line_idx: Vec<u32>,
pub line_batches: Vec<LineBatch>,
/// Strich-Instanzen ([`DASH_INST_FLOATS`] je Segment), s. Modulkopf.
pub dash_inst: Vec<f32>,
pub dash_batches: Vec<DashBatch>,
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<u32>,
line_idx: Vec<u32>,
line_batches: Vec<LineBatch>,
dash_inst: Vec<f32>,
dash_batches: Vec<DashBatch>,
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::<f64>() * 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<Vec<f64>> {
let pat: Vec<f64> = 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<f64> = 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<V2> = 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<f64>) -> 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<f64> = (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<Prim> = 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<f64> = (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);
}
}
+3 -20
View File
@@ -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<Flat, String> {
// 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<Flat, String>
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]
+1
View File
@@ -87,6 +87,7 @@ pub mod text_layout;
pub mod plan_text;
pub mod grips;
pub mod selection_info;
pub mod project_refs;
#[cfg(feature = "web")]
mod web;
+20 -3
View File
@@ -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<bool> = 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<f64> = 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<Flat, String
let mut p = src.clone();
let mut groups: Vec<Group> = 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);
}
}
+29
View File
@@ -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<Component> =
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<WallType> = 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)
}
+336
View File
@@ -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<String>) -> 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<Seg>, ok: &dyn Fn(&Value) -> bool, dropped: &mut Vec<String>) -> 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<String, Value> = 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<Seg>, items: Vec<(String, Value)>, ok: &dyn Fn(&Value) -> bool, dropped: &mut Vec<String>) {
if items.is_empty() {
return;
}
let keys: Vec<String> = 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<Seg>, items: Vec<Value>, ok: &dyn Fn(&Value) -> bool, dropped: &mut Vec<String>) {
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<String> {
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<String, Value>) -> (Project, Vec<String>) {
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<String, Value> {
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::<Vec<_>>(), ["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());
}
}
+1
View File
@@ -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;
+18 -17
View File
@@ -433,19 +433,19 @@ fn compute_joins_by_floor(p: &Project) -> Result<HashMap<String, WallCuts>, Stri
let mut jw: Vec<JoinWall> = 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::<Vec<_>>()
});
.collect::<Vec<_>>(),
);
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<HashMap<String, WallCuts>, 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<Rgb>, 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<PickGeometry, String> {
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);
+9 -11
View File
@@ -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<f64>, fg: Option<&str>) -> Result<HatchRender, String> {
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<f64>, 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<Primitive>, 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 {
+3 -5
View File
@@ -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<Vec2>| -> 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));
+2 -1
View File
@@ -150,7 +150,8 @@ fn collect_roof_faces(p: &Project, frame: &[f64; 9]) -> Result<Vec<Face>, 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,
},
};
+8 -12
View File
@@ -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<Cut>, 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<Cut>, 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<f64> = 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),
+3 -5
View File
@@ -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<f64>, foreground: Option<&str>, placement: Option<(Option<f64>, Option<f64>, Option<Vec2>)>) -> Option<HatchRender> {
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 {
+11 -25
View File
@@ -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<Vec<WallCuts>, 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<Primitive>, 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()));
+13 -3
View File
@@ -162,6 +162,8 @@ pub enum Prim {
chain: bool,
zigzag: Option<(f64, f64)>,
motif: Option<Motif>,
/// Strichmuster (Papier-mm, wie im Puffer); `None` = durchgezogen.
dash: Option<Vec<f64>>,
},
Arc {
style: Style,
@@ -171,6 +173,7 @@ pub enum Prim {
from: V2,
to: V2,
r: f64,
dash: Option<Vec<f64>>,
},
Circle {
style: Style,
@@ -179,6 +182,7 @@ pub enum Prim {
weight_mm: f64,
center: V2,
r: f64,
dash: Option<Vec<f64>>,
},
DrawingArc {
style: Style,
@@ -188,6 +192,7 @@ pub enum Prim {
r: f64,
a0: f64,
a1: f64,
dash: Option<Vec<f64>>,
},
}
@@ -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,
};
+272
View File
@@ -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<String, Value>) -> Vec<String> {
let (p, dropped) = lenient::project_lenient(root);
let mut out: Vec<String> = 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<Item = &'a T>, 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<String> {
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<String>, 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<String>, pens: &HashSet<&str>, what: &str, owner: &str, ps: [&Option<String>; 3]) {
for x in ps {
miss(out, what, owner, "Stift", x.as_deref().unwrap_or(""), pens);
}
}
let none: Option<String> = 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<String>| {
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<String, Value> {
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::<String>::new());
}
}
+2 -5
View File
@@ -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<f64>) -> Option<HatchCore> {
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,
+1
View File
@@ -39,6 +39,7 @@ mod parametric_walls;
mod reorder;
mod text_layout;
mod grips;
mod project_refs;
use wasm_bindgen::prelude::wasm_bindgen;
+17
View File
@@ -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::<Value>(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()
}