Files
DOSSIER/src-tauri/core/src/plan/print_svg.rs
T
Claude 7a980d32d3 [166] Dämm-Striche (EPS/XPS) quer zur Wand in allen Ausgaben
Ursache: Die Ausgaben lasen den Schraffur-Winkel von Geraden-/Kreuzscharen um 90° verschieden.
Szene (Bildschirm render2d, PDF-Export sceneToPrintSvg) und SVG-Kachel: Winkel 0 = Musterlinie
senkrecht; CLI-SVG (plan/svg.rs), Druck-SVG der Layout-Blätter (plan/print_svg.rs, hatch_lines)
und DXF-HATCH: Winkel 0 = Linie waagrecht. Darum pendelte der Standard „Dämmstoffe (SIA-Linien)"
zwischen 0° und 90° (5.11. auf 90° nach dem CLI-Bild: dort quer, auf dem Bildschirm/PDF längs).
Zusätzlich ignorierten CLI-/Druck-SVG die polare Schraffur der Bogenwand (Striche im Sehnenwinkel),
und die Anschlag-Nasen an Öffnungen einer Bogenwand standen im Winkel der abgewickelten Ersatzwand.

Fix:
- plan/svg.rs, plan/print_svg.rs: alle Vektor-Schraffuren über hatch::build_hatch_runs (wie Szene);
  eigene Linienschar hatch_lines/fill_parallel/is_generated entfernt.
- plan/dxf.rs: Scharwinkel = 90° − Schraffur-Winkel (Lesart der Szene), in [0°, 180°).
- standards.rs: std-h-daemmstoffe-sia wieder 0° relativ zur Wand (= quer).
- project_format.rs: beim Laden 90° dieser Standard-Schraffur auf 0° zurückgestellt (Dateien 5.–9.11.).
- plan/walls.rs: Schichtstücke an Öffnungen einer Bogenwand polar schraffiert (polar_layer_pieces).

Test: plan/hatch_dir_tests.rs prüft die tatsächlich gezeichneten Linien der Dämmschicht in Szene,
CLI-SVG und Druck-SVG (1:50 und 1:20): gerade Wand in 9 Drehlagen, Bogen (4), Ecken 90/135/60° gedreht,
Y, T, Y mit Bogenast, kollinear, Wand an/durch Stütze (auch rund, schräg), Fenster mit Anschlag in
schräger Wand und Bogenwand — Winkel zur lokalen Wandachse 90° ± 1°; Schnitt mit Wand, Decke und
geneigtem Dach (quer zur Schicht). Vorher: Szene längs (0°), Bogen-Nasen 54°.
Goldens: komplex-model3d (Hash, Schraffur-Winkel im 3D-Modell); DXF-Test Kreuzschar [90, 0].

Geprüft: cargo test Kern, tsc, vitest; Musterhaus komplex EG/OG 1:50/1:20 und Schnitt A-A 1:50
als Szene und CLI-SVG vorher/nachher angesehen (Linux/Chromium), weiche Dämmung/Zickzack angesehen.
Nicht geprüft: Tauri-App/Mac, render3d-Live-Schnitt.
2026-11-09 15:53:53 +00:00

796 lines
36 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Druck-SVG eines Plans für Layout-Viewports und den PDF-Altpfad ([K3d], früher der Primitiv-Teil
//! von `src/export/planToPrintSvg.ts`): liest den zusammengesetzten Plan ([`crate::plan::parts`]) und
//! liefert die SVG-Knoten in Papier-Millimetern als flache Anweisungsliste, die TS 1:1 als DOM-Knoten
//! anlegt (gleiche Elemente, Attribute und Reihenfolge wie die TS-Fassung — die Zahlen formatiert wie
//! `String(Math.round(v * 1000) / 1000)`). Schraffuren als geklippte Vektorlinien, Zickzack/Motiv als
//! Polylinie, Bögen als `<path>`.
//!
//! In TS bleiben: der `<svg>`-Rahmen und das weisse Blatt und die Bild-Schraffur-`<pattern>`
//! (laufende Ids im Dokument). Einzeltexte und Raumstempel setzt der Kern (`crate::text_layout`,
//! Zeilen als `<tspan>` je Zeile mit je einem `<tspan>` je Run/Wort), Grössen in Papier-mm.
//!
//! Format: Datensätze getrennt durch `\x1e`, Felder durch `\x1f`:
//! - `E`, Ebene (0 = ins `<svg>`, 1 = in die offene Gruppe), Tag, dann Name/Wert-Paare;
//! - `G`, Deckkraft (leer = keine) — öffnet eine `<g>`; `g` schliesst sie (hängt sie ans `<svg>`);
//! - `I`, Punkte-Attribut, Bild-JSON — Bild-Schraffur: `<pattern>` anlegen und ein Polygon damit füllen;
//! - `X`, Name/Wert-Paare — `<text>` ins `<svg>` (wird der offene Text);
//! - `L`, Inhalt (leer = keiner), Name/Wert-Paare — Zeilen-`<tspan>` in den offenen Text (wird die
//! offene Zeile);
//! - `R`, Inhalt, Name/Wert-Paare — Run-`<tspan>` in die offene Zeile.
//!
//! Texte, die selbst `\x1e`/`\x1f` enthalten, zerfallen dabei (Steuerzeichen kommen in Plantexten
//! nicht vor).
use crate::hatch::{self, Hatch, Motif, Pattern, V2};
use crate::js_fmt::js_number;
use crate::jsnum;
use crate::plan::buf::{whole, Rec, View, F_COLOR, F_DASH_NULL, F_OPACITY, T_ARC, T_CIRCLE, T_DRAWING_ARC, T_DRAWING_TEXT, T_IMAGE, T_LINE, T_POLYGON, T_TEXT};
use crate::plan::parts::{greyed_of, Part};
use crate::plan::text::{SingleText, StampText};
use crate::text_layout::{place_lines, stamp_block, stamp_line_offsets, wrap_doc_to_lines, Line, LayoutOpts, LineAlign, PT_TO_MM, TEXT_LINE_HEIGHT_MULT};
use std::f64::consts::PI;
/// Optionen: Massstab-Nenner, Blatt (mm) und Ausmass des Plans (`Plan.bounds`).
pub struct PrintOptions {
pub scale_denominator: f64,
pub page_w: f64,
pub page_h: f64,
pub bounds: [f64; 4],
}
/// Standard-Stift-Stufen (mm).
const PEN_STEPS: [f64; 7] = [0.13, 0.18, 0.25, 0.35, 0.5, 0.7, 1.0];
const MIN_PEN_MM: f64 = 0.13;
/// Mm-Strichstärke auf die nächste Stift-Stufe (`quantizePen`).
pub(super) fn quantize_pen(mm: f64) -> f64 {
let w = jsnum::max(MIN_PEN_MM, mm);
for s in PEN_STEPS {
if w <= s + 1e-6 {
return s;
}
}
PEN_STEPS[PEN_STEPS.len() - 1]
}
/// `String(Math.round(v * 1000) / 1000)`.
fn r3(v: f64) -> String {
js_number(jsnum::round(v * 1000.0) / 1000.0)
}
/// Strichmuster als Attribut (`dash.map(round).join(" ")`).
fn dash_attr(d: &[f64]) -> String {
d.iter().map(|v| r3(*v)).collect::<Vec<_>>().join(" ")
}
/// Anweisungsliste.
struct Out {
recs: Vec<String>,
/// Volle Einzel-Linien je (Farbe, Stift, Deckkraft) zum Zusammennähen ([146]): Wand-Umrisse zweier
/// Wände treffen sich als EIN Zug mit Ecke; jeder Zug steht an der Stelle seiner spätesten Linie.
solid: Vec<((String, String, String), Vec<Vec<V2>>, Vec<usize>)>,
/// [153] Laufender gestrichelter Zug: aneinander anschliessende Linien gleicher Darstellung
/// (Farbe, Stift, Muster in mm, Deckkraft) werden EIN `<polyline>` mit Musterphase.
dash_run: Option<((String, String, Vec<f64>, String), Vec<V2>)>,
}
impl Out {
fn rec(&mut self, fields: &[&str]) {
self.flush_dash();
self.recs.push(fields.join("\u{1f}"));
}
/// Gestrichelte Linie (Papier-mm) an den laufenden Zug hängen oder einen neuen beginnen.
fn dash_line(&mut self, key: (String, String, Vec<f64>, String), a: V2, b: V2) {
if let Some((k, pts)) = self.dash_run.as_mut() {
if *k == key && pts.last().is_some_and(|p| (p.x - a.x).abs() < 1e-9 && (p.y - a.y).abs() < 1e-9) {
pts.push(b);
return;
}
}
self.flush_dash();
self.dash_run = Some((key, vec![a, b]));
}
/// Schreibt den laufenden gestrichelten Zug ([`super::line_pattern::phase`]: Enden auf einem Strich).
fn flush_dash(&mut self) {
let Some(((color, pen, dash, o), pts)) = self.dash_run.take() else { return };
let len: f64 = pts.windows(2).map(|w| crate::jsmath::hypot2(w[1].x - w[0].x, w[1].y - w[0].y)).sum();
let pen_mm: f64 = pen.parse().unwrap_or(0.0);
let mut attrs = if pts.len() == 2 { line_attrs(pts[0], pts[1], &color, pen_mm, Some(&dash)) } else { polyline_attrs(&pts, &color, pen_mm, Some(&dash)) };
let ph = super::line_pattern::phase(len, &dash);
if ph > 1e-9 {
attrs.push(("stroke-dashoffset", r3(ph)));
}
if !o.is_empty() {
attrs.push(("opacity", o));
}
let tag = if pts.len() == 2 { "line" } else { "polyline" };
let mut f: Vec<&str> = vec!["E", "0", tag];
for (k, v) in &attrs {
f.push(k);
f.push(v);
}
self.recs.push(f.join("\u{1f}"));
}
fn defer_solid(&mut self, key: (String, String, String), a: V2, b: V2) {
self.flush_dash();
self.recs.push(String::new());
let slot = self.recs.len() - 1;
let gi = match self.solid.iter().position(|g| g.0 == key) {
Some(g) => g,
None => {
self.solid.push((key, Vec::new(), Vec::new()));
self.solid.len() - 1
}
};
self.solid[gi].1.push(vec![a, b]);
self.solid[gi].2.push(slot);
}
fn finish(mut self) -> String {
self.flush_dash();
for ((color, pen, o), runs, slots) in std::mem::take(&mut self.solid) {
for (pts, closed, members) in crate::plan::scene::stitch_runs_members(&runs) {
let slot = members.iter().map(|&m| slots[m]).max().unwrap_or(0);
let line = pts.len() == 2 && !closed;
let mut attrs = if line {
vec![("x1", r3(pts[0].x)), ("y1", r3(pts[0].y)), ("x2", r3(pts[1].x)), ("y2", r3(pts[1].y)), ("stroke", color.clone()), ("stroke-width", pen.clone())]
} else {
vec![("points", pts_attr(&pts)), ("fill", "none".to_string()), ("stroke", color.clone()), ("stroke-width", pen.clone())]
};
if !o.is_empty() {
attrs.push(("opacity", o.clone()));
}
let tag = if line { "line" } else if closed { "polygon" } else { "polyline" };
let mut f: Vec<&str> = vec!["E", "0", tag];
for (k, v) in &attrs {
f.push(k);
f.push(v);
}
let r = f.join("\u{1f}");
if self.recs[slot].is_empty() {
self.recs[slot] = r;
} else {
self.recs[slot].push('\u{1e}');
self.recs[slot].push_str(&r);
}
}
}
self.recs.retain(|r| !r.is_empty());
self.recs.join("\u{1e}")
}
/// Datensatz aus festen Feldern und Name/Wert-Paaren.
fn tagged(&mut self, head: &[&str], attrs: &[(&str, String)]) {
let mut f: Vec<&str> = head.to_vec();
for (k, v) in attrs {
f.push(k);
f.push(v);
}
self.rec(&f);
}
fn el(&mut self, depth: u8, tag: &str, attrs: &[(&str, String)]) {
let d = depth.to_string();
let mut f: Vec<&str> = vec!["E", &d, tag];
for (k, v) in attrs {
f.push(k);
f.push(v);
}
self.rec(&f);
}
}
/// Papier-Abbildung (Welt-Meter → mm, Y gespiegelt, zentriert).
#[derive(Clone, Copy)]
struct Map {
off_x: f64,
off_y: f64,
min_x: f64,
max_y: f64,
k: f64,
}
impl Map {
fn at(&self, x: f64, y: f64) -> V2 {
V2 { x: self.off_x + (x - self.min_x) * self.k, y: self.off_y + (self.max_y - y) * self.k }
}
}
fn pts_attr(p: &[V2]) -> String {
p.iter().map(|q| format!("{},{}", r3(q.x), r3(q.y))).collect::<Vec<_>>().join(" ")
}
/// `#rrggbbaa` (Raumfüllung) → `#rrggbb` + Deckkraft: svg2pdf (Layout-PDF, [93]) kennt keine
/// 8-stellige Hex-Farbe und füllte deckend dunkel (Raumstempel darunter verschwanden).
fn split_alpha(color: &str) -> (String, Option<String>) {
let b = color.as_bytes();
if b.len() == 9 && b[0] == b'#' && b[1..].iter().all(|c| c.is_ascii_hexdigit()) {
if let Ok(a) = u8::from_str_radix(&color[7..9], 16) {
return (color[..7].to_string(), Some(js_number(crate::jsnum::round(a as f64 / 255.0 * 1000.0) / 1000.0)));
}
}
(color.to_string(), None)
}
fn poly_node(pts: &str, fill: &str, stroke: &str, stroke_mm: f64) -> Vec<(&'static str, String)> {
let (fill, fill_opacity) = split_alpha(fill);
let opaque = fill_opacity.is_none();
let mut a = vec![("points", pts.to_string()), ("fill", fill)];
if let Some(o) = fill_opacity {
a.push(("fill-opacity", o));
}
if stroke != "none" && stroke_mm > 0.0 {
a.push(("stroke", stroke.to_string()));
a.push(("stroke-width", js_number(stroke_mm)));
} else if opaque && super::svg::seam_fill(&a[1].1) {
// [157] Dunkle, deckende Fläche: Haarstrich in der Füllfarbe gegen die Fuge zur Nachbarfläche.
a.push(("stroke", a[1].1.clone()));
a.push(("stroke-width", js_number(super::svg::SEAM_MM)));
} else {
a.push(("stroke", "none".to_string()));
}
a
}
/// Polygon mit Füllung und Strich; mit `nse` (nicht gestrichene Kanten, [146]) die Füllung ohne Strich
/// und die sichtbaren Kantenläufe als offene Linienzüge — wie das Plan-SVG (`plan/svg.rs`).
fn poly_stroked(out: &mut Out, attr: &str, pts_mm: &[V2], nse: &[f64], fill: &str, stroke: &str, stroke_mm: f64) {
if nse.is_empty() || stroke_mm <= 0.0 || stroke == "none" {
out.el(1, "polygon", &poly_node(attr, fill, stroke, stroke_mm));
return;
}
out.el(1, "polygon", &poly_node(attr, fill, "none", 0.0));
poly_outline(out, pts_mm, nse, stroke, stroke_mm);
}
/// Nur der Umriss (Füllung oder Schraffur liegt schon darunter).
fn poly_outline(out: &mut Out, pts_mm: &[V2], nse: &[f64], stroke: &str, stroke_mm: f64) {
if nse.is_empty() {
out.el(1, "polygon", &poly_node(&pts_attr(pts_mm), "none", stroke, stroke_mm));
return;
}
for run in crate::plan::scene::visible_edge_runs(pts_mm, nse) {
out.el(1, "polyline", &polyline_attrs(&run, stroke, stroke_mm, None));
}
}
fn line_attrs(a: V2, b: V2, color: &str, stroke_mm: f64, dash: Option<&[f64]>) -> Vec<(&'static str, String)> {
let mut v = vec![
("x1", r3(a.x)),
("y1", r3(a.y)),
("x2", r3(b.x)),
("y2", r3(b.y)),
("stroke", color.to_string()),
("stroke-width", js_number(stroke_mm)),
];
push_dash(&mut v, dash);
v
}
fn polyline_attrs(pts: &[V2], color: &str, stroke_mm: f64, dash: Option<&[f64]>) -> Vec<(&'static str, String)> {
let mut v = vec![
("points", pts_attr(pts)),
("fill", "none".to_string()),
("stroke", color.to_string()),
("stroke-width", js_number(stroke_mm)),
];
push_dash(&mut v, dash);
v
}
/// Strichmuster + runde Kappe bei Punkten. Sonst erben Enden und Ecken die Projekt-Einstellung
/// ([146]) vom `<svg>`, das TS anlegt (`planToPrintSvg.ts`).
fn push_dash(v: &mut Vec<(&'static str, String)>, dash: Option<&[f64]>) {
if let Some(d) = dash.filter(|d| !d.is_empty()) {
v.push(("stroke-dasharray", dash_attr(d)));
if d.iter().any(|x| *x == 0.0) {
v.push(("stroke-linecap", "round".to_string()));
}
}
}
/// Strichmuster der Schraffurlinien in Papier-mm: dieselben Modell-Längen wie Szene/Chunk-Pfad
/// (`hatch::hatch_dash` × `DASH_MM_TO_M`), nur auf das Blatt (`mm_per_m`) abgebildet.
pub(super) fn hatch_dash_paper(h: &Hatch, mm_per_m: f64) -> Vec<f64> {
hatch::hatch_dash(h).iter().map(|d| jsnum::max(0.0, *d) * hatch::DASH_MM_TO_M * mm_per_m).collect()
}
fn num(o: &serde_json::Value, k: &str) -> f64 {
o.get(k).and_then(|x| x.as_f64()).unwrap_or(f64::NAN)
}
/// Deckkraft-Attribut (`dim · max(0, objOpacity)`, nur unter 1).
fn opacity_of(greyed: bool, obj: f64) -> String {
let combined = (if greyed { 0.3 } else { 1.0 }) * jsnum::max(0.0, obj);
if combined < 1.0 {
js_number(combined)
} else {
String::new()
}
}
/// Ein Eintrag als Knoten.
fn entry(out: &mut Out, view: &View, i: usize, hatches: &[(i32, Hatch, i32)], m: Map) -> Option<()> {
let rec: Rec = view.rec(i)?;
let f = &rec.f;
let k = m.k;
let s = |idx: f64| -> Option<String> {
if idx == -1.0 {
Some("undefined".to_string())
} else {
view.string(whole(idx)?)
}
};
let dash = |rec: &Rec| -> Option<Option<Vec<f64>>> {
if rec.flags & F_DASH_NULL != 0 {
return Some(None);
}
match rec.dash {
Some((o, n)) => Some(Some(view.pool(o, n)?)),
None => Some(None),
}
};
let greyed = greyed_of(&rec, false) == Some(true);
let obj = |at: usize| if rec.flags & F_OPACITY != 0 { f[at] } else { 1.0 };
match rec.tag {
T_POLYGON => {
let pts: Vec<V2> = view.pool(whole(f[5])?, whole(f[6])?.checked_mul(2)?)?.chunks_exact(2).map(|c| V2 { x: c[0], y: c[1] }).collect();
let opacity = opacity_of(greyed, obj(4));
let pts_mm: Vec<V2> = pts.iter().map(|p| m.at(p.x, p.y)).collect();
let attr = pts_attr(&pts_mm);
let nse: Vec<f64> = match rec.nse {
Some((o, n)) => view.pool(o, n)?.into_iter().filter(|e| e.is_finite() && *e >= 0.0).collect(),
None => Vec::new(),
};
let sw = f[2];
let stroke_mm = if sw > 0.0 { quantize_pen(sw) } else { 0.0 };
let fill = s(f[0])?;
let stroke = s(f[1])?;
out.rec(&["G", &opacity]);
// Ohne Schraffur-Eintrag wie „none“.
let (json, h, color) = if f[3] >= 0.0 { hatches.get(whole(f[3])?)?.clone() } else { (-1, empty_hatch(), -1) };
let image: Option<String> = if h.kind == hatch::HatchKind::Image && json >= 0 {
let j: serde_json::Value = serde_json::from_str(&view.string(json as usize)?).ok()?;
j.get("image").filter(|v| v.is_object()).map(|v| v.to_string())
} else {
None
};
let hatch_color = if color >= 0 { view.string(color as usize)? } else { "undefined".to_string() };
if let Some(img) = image {
if fill != "none" {
out.el(1, "polygon", &poly_node(&attr, &fill, "none", 0.0));
}
out.rec(&["I", &attr, &img]);
if stroke_mm > 0.0 {
poly_outline(out, &pts_mm, &nse, &stroke, stroke_mm);
}
} else if h.pattern == Pattern::None {
poly_stroked(out, &attr, &pts_mm, &nse, &fill, &stroke, stroke_mm);
} else if h.pattern == Pattern::Solid {
poly_stroked(out, &attr, &pts_mm, &nse, &hatch_color, &stroke, stroke_mm);
} else {
if fill != "none" {
out.el(1, "polygon", &poly_node(&attr, &fill, "none", 0.0));
}
let pen = quantize_pen(h.line_weight);
let hdash = hatch_dash_paper(&h, k);
if h.random {
for run in hatch::build_random_hatch_runs(&pts, &h, None) {
if run.len() < 2 {
continue;
}
let (a, b) = (run[0], run[run.len() - 1]);
out.el(1, "line", &line_attrs(m.at(a.x, a.y), m.at(b.x, b.y), &hatch_color, pen, Some(&hdash)));
}
} else {
// Alle Vektor-Schraffuren aus dem Kern-Generator: dieselben Linien wie Szene, PDF-Export und
// Chunk-Pfad ([109] Schicht-/Streumuster; [166] auch Geraden-/Kreuzschar und Motiv: die
// frühere eigene Linienschar las den Winkel um 90° verdreht — Dämm-Striche längs statt quer —
// und kannte die polare Schraffur der Bogenwand nicht).
for run in hatch::build_hatch_runs(&pts, &h) {
let p: Vec<V2> = run.iter().map(|q| m.at(q.x, q.y)).collect();
match p.len() {
0 | 1 => {}
2 => out.el(1, "line", &line_attrs(p[0], p[1], &hatch_color, pen, Some(&hdash))),
_ => out.el(1, "polyline", &polyline_attrs(&p, &hatch_color, pen, Some(&hdash))),
}
}
}
if stroke_mm > 0.0 {
poly_outline(out, &pts_mm, &nse, &stroke, stroke_mm);
}
}
out.rec(&["g"]);
}
T_LINE => {
let a = m.at(f[4], f[5]);
let b = m.at(f[6], f[7]);
let color = if rec.flags & F_COLOR != 0 { s(f[1])? } else { "#111111".to_string() };
let pen = quantize_pen(f[2]);
let d = dash(&rec)?;
let mut attrs = if let Some((amp, wav)) = rec.zigzag {
let p = hatch::zigzag_points(a, b, amp, wav).unwrap_or_else(|| vec![a, b]);
polyline_attrs(&p, &color, pen, d.as_deref())
} else if let Some((length, o, n)) = rec.motif {
let pts: Vec<V2> = view.pool(o, n.checked_mul(2)?)?.chunks_exact(2).map(|c| V2 { x: c[0], y: c[1] }).collect();
let p = hatch::motif_points_opt(a, b, &Motif { points: pts, length }, 1.0).unwrap_or_else(|| vec![a, b]);
polyline_attrs(&p, &color, pen, d.as_deref())
} else {
let o = opacity_of(greyed, obj(3));
if d.as_deref().is_none_or(|d| d.is_empty()) && pen > 0.0 {
out.defer_solid((color, js_number(pen), o), a, b);
return Some(());
}
if let Some(dd) = d.as_ref().filter(|d| !d.is_empty()) {
out.dash_line((color, js_number(pen), dd.clone(), o), a, b);
return Some(());
}
line_attrs(a, b, &color, pen, d.as_deref())
};
let tag = if rec.zigzag.is_some() || rec.motif.is_some() { "polyline" } else { "line" };
let o = opacity_of(greyed, obj(3));
if !o.is_empty() {
attrs.push(("opacity", o));
}
out.el(0, tag, &attrs);
}
T_ARC => {
let c = m.at(f[4], f[5]);
let from = m.at(f[6], f[7]);
let to = m.at(f[8], f[9]);
let r = f[10] * k;
let cross = (from.x - c.x) * (to.y - c.y) - (from.y - c.y) * (to.x - c.x);
let sweep = if cross > 0.0 { 1 } else { 0 };
let d = format!("M {} {} A {} {} 0 0 {} {} {}", r3(from.x), r3(from.y), r3(r), r3(r), sweep, r3(to.x), r3(to.y));
let mut attrs = vec![("d", d), ("fill", "none".to_string()), ("stroke", "#111111".to_string()), ("stroke-width", js_number(quantize_pen(f[2])))];
push_dash(&mut attrs, dash(&rec)?.as_deref());
let o = opacity_of(greyed, obj(3));
if !o.is_empty() {
attrs.push(("opacity", o));
}
out.el(0, "path", &attrs);
}
T_CIRCLE => {
let c = m.at(f[4], f[5]);
let fill = s(f[0])?;
let mut attrs = vec![
("cx", r3(c.x)),
("cy", r3(c.y)),
("r", r3(f[6] * k)),
("fill", if !fill.is_empty() && fill != "none" { fill } else { "none".to_string() }),
("stroke", s(f[1])?),
("stroke-width", js_number(quantize_pen(f[2]))),
];
push_dash(&mut attrs, dash(&rec)?.as_deref());
let o = opacity_of(greyed, obj(3));
if !o.is_empty() {
attrs.push(("opacity", o));
}
out.el(0, "circle", &attrs);
}
T_DRAWING_ARC => {
let tau = PI * 2.0;
let (cx, cy, r, a0, a1) = (f[3], f[4], f[5], f[6], f[7]);
let from = m.at(cx + r * jsnum::cos(a0), cy + r * jsnum::sin(a0));
let to = m.at(cx + r * jsnum::cos(a1), cy + r * jsnum::sin(a1));
let rr = r * k;
let sweep = (((a1 - a0) % tau) + tau) % tau;
let large = if sweep > PI { 1 } else { 0 };
let d = format!("M {} {} A {} {} 0 {} 1 {} {}", r3(from.x), r3(from.y), r3(rr), r3(rr), large, r3(to.x), r3(to.y));
let mut attrs = vec![("d", d), ("fill", "none".to_string()), ("stroke", s(f[0])?), ("stroke-width", js_number(quantize_pen(f[1])))];
push_dash(&mut attrs, dash(&rec)?.as_deref());
let o = opacity_of(greyed, obj(2));
if !o.is_empty() {
attrs.push(("opacity", o));
}
out.el(0, "path", &attrs);
}
T_TEXT => {
let js = view.string(whole(f[0])?)?;
let j: serde_json::Value = serde_json::from_str(&js).ok()?;
let jg = j.get("greyed").and_then(|g| g.as_bool()).unwrap_or(false);
let obj = j.get("opacity").and_then(|o| o.as_f64()).unwrap_or(1.0);
if let Ok(t) = serde_json::from_str::<StampText>(&js) {
stamp_node(out, &t, m, opacity_of(jg, obj));
}
}
T_DRAWING_TEXT | T_IMAGE => {
let js = view.string(whole(f[0])?)?;
let j: serde_json::Value = serde_json::from_str(&js).ok()?;
let jg = j.get("greyed").and_then(|g| g.as_bool()).unwrap_or(false);
if rec.tag == T_DRAWING_TEXT {
let obj = j.get("opacity").and_then(|o| o.as_f64()).unwrap_or(1.0);
if let Ok(t) = serde_json::from_str::<SingleText>(&js) {
text_node(out, &t, m, opacity_of(jg, obj));
}
} else {
let (min, max) = (j.get("min")?, j.get("max")?);
let (x0, y0, x1, y1) = (num(min, "x"), num(min, "y"), num(max, "x"), num(max, "y"));
let w = (x1 - x0) * k;
let h = (y1 - y0) * k;
if w <= 0.0 || h <= 0.0 {
return Some(());
}
let tl = m.at(x0, y1);
let mut attrs = vec![
("href", j.get("src").and_then(|v| v.as_str()).unwrap_or("undefined").to_string()),
("x", r3(tl.x)),
("y", r3(tl.y)),
("width", r3(w)),
("height", r3(h)),
("preserveAspectRatio", "none".to_string()),
];
// Bilder: eigene Deckkraft getrennt (gedimmt × 0.45), sonst nur das Dimmen.
let op = num(&j, "opacity");
if op < 1.0 {
attrs.push(("opacity", js_number(op * if jg { 0.45 } else { 1.0 })));
} else {
let o = opacity_of(jg, 1.0);
if !o.is_empty() {
attrs.push(("opacity", o));
}
}
out.el(0, "image", &attrs);
}
}
_ => {}
}
Some(())
}
/// Einzeltext (Text-Werkzeug/DXF-Import, auch Masszahlen und Koten) als `<text>` mit
/// `<tspan>`-Zeilen (früher `drawingTextNode` in `planToPrintSvg.ts`): Grösse in Papier-mm (Höhe ×
/// mm je Meter, wie die Plan-Ansicht beim Massstab), bei Spaltenbreite wortweise umbrochen
/// (Run-Grenzen bleiben), gedreht um den Anker. Run-eigene `sizePt` wie in der SVG-Plan-Ansicht als
/// Modell-pt (1 pt = 0.0254/72 m), also auch × mm je Meter.
fn text_node(out: &mut Out, t: &SingleText, m: Map, opacity: String) {
let k = m.k;
let c = m.at(t.at.x, t.at.y);
let unit_per_pt = (0.0254 / 72.0) * k;
// Basisgrösse in Modell-pt (bis 30.10. `height_m / unit_per_pt`: Meter durch mm je pt — die
// Runs kamen in Metern statt Papier-mm heraus, im Layout k-mal zu klein).
let base_pt = if unit_per_pt > 0.0 { t.height_m * k / unit_per_pt } else { 0.0 };
let wrap = t.wrap().map(|w| w * k);
let o = LayoutOpts { line_height: t.height_m * k * TEXT_LINE_HEIGHT_MULT, unit_per_pt, base_pt, color: t.color.as_deref().unwrap_or("#000000") };
let lines = wrap_doc_to_lines(&t.doc(), &o, wrap);
if lines.is_empty() {
return;
}
let mut attrs: Vec<(&str, String)> = Vec::new();
let deg = -(t.angle * 180.0) / PI;
if deg != 0.0 && !deg.is_nan() {
attrs.push(("transform", format!("rotate({} {} {})", r3(deg), r3(c.x), r3(c.y))));
}
if !opacity.is_empty() {
attrs.push(("opacity", opacity));
}
out.tagged(&["X"], &attrs);
let at = place_lines(lines.iter().map(|l| (l.align, l.line_height)), c.x, c.y, wrap);
for (line, (x, y)) in lines.iter().zip(at) {
let content = if line.tspans.is_empty() { "\u{200b}" } else { "" };
line_node(out, line, content, x, y);
}
}
/// Zeilen-`<tspan>` mit je einem Run-`<tspan>`.
fn line_node(out: &mut Out, line: &Line, content: &str, x: f64, y: f64) {
out.tagged(&["L", content], &[("x", r3(x)), ("y", r3(y)), ("text-anchor", line.align.anchor().to_string())]);
for ts in &line.tspans {
let mut a: Vec<(&str, String)> = vec![("font-size", r3(ts.font_size)), ("fill", ts.fill.clone())];
if let Some(w) = ts.font_weight() {
a.push(("font-weight", w.to_string()));
}
if let Some(st) = ts.font_style() {
a.push(("font-style", st.to_string()));
}
a.push(("font-family", ts.font_family.clone().unwrap_or_else(|| "Helvetica, Arial, sans-serif".to_string())));
if let Some(d) = ts.text_decoration {
a.push(("text-decoration", d.to_string()));
}
out.tagged(&["R", &ts.text], &a);
}
}
/// Raumstempel als `<text>` (fehlte im Druck-SVG bis 30.10.): wie die Plan-Ansicht im Druckmodus —
/// Rich-Text-Zeilen und Live-Zeilen (Fläche, Nutzung) als Block um den Anker zentriert
/// ([`stamp_block`]), Grösse in Papier-pt (unabhängig vom Massstab).
fn stamp_node(out: &mut Out, t: &StampText, m: Map, opacity: String) {
let c = m.at(t.at.x, t.at.y);
let extra: Vec<(&str, LineAlign)> = t.extra_lines.iter().map(|l| (l.text.as_str(), LineAlign::of(Some(l.align)))).collect();
let placed = stamp_block(&t.doc, &extra, t.base_pt, PT_TO_MM, t.color.as_deref().unwrap_or("#000000"), c.y);
if placed.is_empty() {
return;
}
let attrs: Vec<(&str, String)> = if opacity.is_empty() { Vec::new() } else { vec![("opacity", opacity)] };
out.tagged(&["X"], &attrs);
// [140] Zeilen im gemessenen, um den Anker zentrierten Block (`stamp_line_offsets`).
for (p, dx) in placed.iter().zip(stamp_line_offsets(&placed)) {
line_node(out, &p.line, "", c.x + dx, p.y);
}
}
fn empty_hatch() -> Hatch {
Hatch {
pattern: Pattern::None,
kind: hatch::HatchKind::Vector,
random: false,
scale: 1.0,
angle: 0.0,
line_weight: 0.0,
origin: None,
seed: None,
density: None,
length_min: None,
length_max: None,
dash: Vec::new(),
motif: None,
polar: None,
}
}
/// Anweisungsliste des Druck-SVG (Format s. Modulkopf); `None` bei kaputtem Puffer.
pub fn print_svg_ops(parts: &mut [Part], o: &PrintOptions) -> Option<String> {
let k = 1000.0 / o.scale_denominator;
let [min_x, min_y, max_x, max_y] = o.bounds;
let content_w = (max_x - min_x) * k;
let content_h = (max_y - min_y) * k;
let m = Map { off_x: (o.page_w - content_w) / 2.0, off_y: (o.page_h - content_h) / 2.0, min_x, max_y, k };
let mut out = Out { recs: Vec::new(), solid: Vec::new(), dash_run: None };
for part in parts.iter_mut() {
let hatches = part.view.hatch_table()?;
for i in part.from..part.to {
entry(&mut out, &part.view, i, &hatches, m)?;
}
}
Some(out.finish())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn schwarze_flaeche_mit_haarstrich() {
// [157] Dunkle deckende Fläche ohne Strich: Haarstrich in der Füllfarbe (keine helle Fuge im PDF).
let a = poly_node("0,0 1,0 1,1", "#0f0f0f", "none", 0.0);
assert!(a.contains(&("stroke", "#0f0f0f".to_string())) && a.contains(&("stroke-width", "0.05".to_string())), "{a:?}");
let b = poly_node("0,0 1,0 1,1", "#ffffff", "none", 0.0);
assert!(b.contains(&("stroke", "none".to_string())), "{b:?}");
let c = poly_node("0,0 1,0 1,1", "#0f0f0f", "#222", 0.35);
assert!(c.contains(&("stroke", "#222".to_string())), "{c:?}");
}
#[test]
fn raumfuellung_mit_alpha_als_deckkraft() {
let a = poly_node("0,0 1,0 1,1", "#4a6fa526", "none", 0.0);
assert!(a.contains(&("fill", "#4a6fa5".to_string())));
assert!(a.contains(&("fill-opacity", "0.149".to_string())));
let b = poly_node("0,0 1,0 1,1", "#ffffff", "none", 0.0);
assert!(b.iter().all(|e| e.0 != "fill-opacity"));
}
#[test]
fn stift_stufen_und_runden() {
assert_eq!(quantize_pen(0.0), 0.13);
assert_eq!(quantize_pen(0.2), 0.25);
assert_eq!(quantize_pen(3.0), 1.0);
assert_eq!(r3(1.23456), "1.235");
assert_eq!(r3(-0.0001), "0");
assert_eq!(dash_attr(&[2.0, 0.5]), "2 0.5");
// Schraffur-Strich im Druck = Modell-Länge der Szene auf dem Blatt (1:50 → 20 mm je m).
let mut h = empty_hatch();
h.scale = 0.35;
h.dash = vec![1.0, 0.7];
let d = hatch_dash_paper(&h, 20.0);
assert!((d[0] - 0.35 * hatch::DASH_MM_TO_M * 20.0).abs() < 1e-12);
assert!((d[1] / d[0] - 0.7).abs() < 1e-12);
}
#[test]
fn einzeltext_als_zeilen_und_runs() {
let js = "{\"kind\":\"drawingText\",\"at\":{\"x\":1,\"y\":2},\"text\":\"aa bb\",\"heightM\":0.5,\"angle\":0.5,\"color\":\"#123\",\"wrapWidth\":2,\"marks\":{\"bold\":true}}";
let t: SingleText = serde_json::from_str(js).unwrap();
let m = Map { off_x: 0.0, off_y: 0.0, min_x: 0.0, max_y: 10.0, k: 10.0 };
let mut out = Out { recs: Vec::new(), solid: Vec::new(), dash_run: None };
text_node(&mut out, &t, m, "0.5".into());
let s = out.finish();
let recs: Vec<Vec<&str>> = s.split('\u{1e}').map(|r| r.split('\u{1f}').collect()).collect();
// Drehung um den Anker (10, 80 mm), eine Zeile (Spalte 20 mm), je Wort/Leerraum ein Run.
assert_eq!(recs[0], ["X", "transform", "rotate(-28.648 10 80)", "opacity", "0.5"]);
assert_eq!(recs[1], ["L", "", "x", "10", "y", "80", "text-anchor", "start"]);
// Run-Grösse in Papier-mm: 0.5 m × 10 mm/m (wie die Plan-Ansicht beim Massstab).
assert_eq!(recs[2], ["R", "aa", "font-size", "5", "fill", "#123", "font-weight", "700", "font-family", "Helvetica, Arial, sans-serif"]);
assert_eq!((recs[3][1], recs[4][1], recs.len()), (" ", "bb", 5));
}
#[test]
fn einzeltext_umbruch_und_zeilen_in_papier_mm() {
// Spalte 2 m = 20 mm, Höhe 0.25 m = 2.5 mm: «aaaa bbbb» (je 4 × 2.5 × 0.55 = 5.5 mm) passt in
// eine Zeile; Run mit eigener Grösse 72 pt = 1 Modell-Zoll = 0.254 mm bei 10 mm/m.
let js = r##"{"at":{"x":0,"y":10},"text":"","heightM":0.25,"angle":0,"wrapWidth":2,"doc":{"version":1,"paragraphs":[{"runs":[{"text":"aaaa bbbb","marks":{}}]},{"runs":[{"text":"c","marks":{"sizePt":72}}],"lineHeight":2}]}}"##;
let t: SingleText = serde_json::from_str(js).unwrap();
let m = Map { off_x: 0.0, off_y: 0.0, min_x: 0.0, max_y: 10.0, k: 10.0 };
let mut out = Out { recs: Vec::new(), solid: Vec::new(), dash_run: None };
text_node(&mut out, &t, m, String::new());
let s = out.finish();
let recs: Vec<Vec<&str>> = s.split('\u{1e}').map(|r| r.split('\u{1f}').collect()).collect();
let lines: Vec<&Vec<&str>> = recs.iter().filter(|r| r[0] == "L").collect();
assert_eq!(lines.len(), 2);
// Absatz-Zeilenhöhe 2 × Basisgrösse (2.5 mm).
assert_eq!((lines[0][5], lines[1][5]), ("0", "5"));
let sizes: Vec<&str> = recs.iter().filter(|r| r[0] == "R").map(|r| r[3]).collect();
assert_eq!(sizes, ["2.5", "2.5", "2.5", "0.254"]);
}
#[test]
fn raumstempel_als_block_in_papier_pt() {
let js = r##"{"at":{"x":2,"y":3},"doc":{"version":1,"paragraphs":[{"runs":[{"text":"Wohnen","marks":{"bold":true}}],"align":"center"}]},"extraLines":[{"text":"17.01 m²","align":"center"}],"basePt":10,"color":"#333"}"##;
let t: StampText = serde_json::from_str(js).unwrap();
let m = Map { off_x: 0.0, off_y: 0.0, min_x: 0.0, max_y: 10.0, k: 20.0 };
let mut out = Out { recs: Vec::new(), solid: Vec::new(), dash_run: None };
stamp_node(&mut out, &t, m, "0.3".into());
let s = out.finish();
let recs: Vec<Vec<&str>> = s.split('\u{1e}').map(|r| r.split('\u{1f}').collect()).collect();
assert_eq!(recs[0], ["X", "opacity", "0.3"]);
// Anker (40, 140 mm); 10 pt = 3.528 mm, Live-Zeile 0.8 ×; Block um den Anker zentriert.
assert_eq!(&recs[1][..4], ["L", "", "x", "40"]);
assert_eq!(recs[1][7], "middle");
assert_eq!(recs[2], ["R", "Wohnen", "font-size", "3.528", "fill", "#333", "font-weight", "700", "font-family", "Helvetica, Arial, sans-serif"]);
assert_eq!((recs[4][1], recs[4][3]), ("17.01 m²", "2.822"));
let y0: f64 = recs[1][5].parse().unwrap();
let y1: f64 = recs[3][5].parse().unwrap();
assert!(y0 < 140.0 && y1 > 140.0 && (y1 - y0 - 10.0 * PT_TO_MM * 1.3).abs() < 1e-3);
}
/// [146] Nicht gestrichene Kanten (`noStrokeEdges`) bleiben im Druck-SVG ohne Strich: Füllung ohne
/// Umriss, die übrigen Kanten als offener Linienzug.
#[test]
fn ungestrichene_kante_ohne_strich() {
use crate::model::Vec2;
use crate::plan::buf::{View, Writer};
use crate::plan::prim::Primitive;
let v = |x: f64, y: f64| Vec2 { x, y };
let mut w = Writer::new(false);
let g = w.begin_group();
w.push(&Primitive::Polygon {
pts: vec![v(0.0, 0.0), v(1.0, 0.0), v(1.0, 1.0), v(0.0, 1.0)],
fill: "#fff".into(),
stroke: "#123456".into(),
stroke_width_mm: 0.5,
hatch: crate::plan::style::no_hatch(),
greyed: None,
opacity: None,
no_stroke_edges: Some(vec![3.0]),
wall_id: None,
drawing_id: None,
ceiling_id: None,
opening_id: None,
stair_id: None,
room_id: None,
extruded_solid_id: None,
context_object_id: None,
column_id: None,
roof_id: None,
section_line_id: None,
});
w.end_group(g);
let bytes = w.finish();
let view = View::parse(&bytes).unwrap();
let n = view.len();
let mut parts = vec![Part::new(view, 0, n).unwrap()];
let o = PrintOptions { scale_denominator: 1000.0, page_w: 10.0, page_h: 10.0, bounds: [0.0, 0.0, 1.0, 1.0] };
let ops = print_svg_ops(&mut parts, &o).unwrap();
let recs: Vec<&str> = ops.split('\x1e').collect();
let poly = recs.iter().find(|r| r.contains("\x1fpolygon")).expect("Füllung");
assert!(!poly.contains("#123456"), "Füllung ohne Strich: {poly:?}");
let line = recs.iter().find(|r| r.contains("\x1fpolyline")).expect("Kantenzug");
assert!(line.contains("#123456"), "{line:?}");
// Drei sichtbare Kanten = vier Punkte; die vierte Kante (0,1)→(0,0) fehlt.
let pts = line.split('\x1f').skip_while(|x| *x != "points").nth(1).unwrap();
assert_eq!(pts.split(' ').count(), 4, "{pts}");
}
}