diff --git a/TODO.md b/TODO.md index f2d51030..79b297d1 100644 --- a/TODO.md +++ b/TODO.md @@ -149,9 +149,13 @@ Wer zu einer ID mehr wissen will (Entscheide, Tests, Bilder), sucht dort nach `* - ◐ **[146]** Linienenden/-ecken. Druck-SVG achtet seit 9.11. auf `noStrokeEdges` (offene Kantenzüge, Test `ungestrichene_kante_ohne_strich`); Nähen in Metal-Chunks nur innerhalb eines Chunks (Kern `plan/line_ends.rs`, `render2d`). · M - ◐ **[153]** Strichmuster in Papier-mm. Bögen mit Phase seit 9.11. ([169]: Plan-/Druck-SVG, PDF, Bogen-Shader; seit - 10.11. auch Ellipsenbögen, Länge numerisch), - Kreise ohne (geschlossen), DXF/DWG ohne Phase je Objekt, - Metal-Chunks verketten nur über das Ketten-Flag, React-SVG-Ansicht ohne Phase. · M + 10.11. auch Ellipsenbögen, Länge numerisch). (11.11.) Vollkreise: Muster auf ganze Wiederholungen über den Umfang + gestreckt (`line_pattern::fit_closed`, Naht schliesst) in Plan-SVG, Druck-SVG/PDF (`sceneToPrintSvg.ts` für Ringzüge + der Szene), Bildschirm-Szene (`scene.rs`), DXF/DWG (eigener Linientyp je Radius `…_R`) und React-SVG-Ansicht + (`dashVb.ts`: Phase für Linien/Bögen/Zug, Ring gestreckt). DXF/DWG kennen keine Musterphase je Objekt (Muster beginnt am + Entitätsanfang; Linientyp-Skalierung nur über Gruppe 48, die das flache Format nicht trägt) — Linien/Bögen bleiben dort + ohne Phase, begründet. Offen: Metal-Chunks verketten nur über das Ketten-Flag; geschlossene Polylinien/Ellipsen ohne + Streckung; nur im Linux-Container geprüft. · M - ◐ **[155]** Treppensymbol. (10.11.) Lauflinie hinter der Bruchlinie gestrichelt wie die Tritte (Pfeil bleibt ausgezogen); Raumstempel weichen allen Treppen-Linien aus (`stamp_obstacles_with` nimmt `d.stairs` ganz, Test `stempel_weichen_den_treppenlinien_aus`). (11.11.) Freier Lochring ohne Wand und Austritt: geschlossener Zug mit Gehrung an der Naht (`offset_polyline` erkennt geschlossene Züge, 3D-Rohr ohne Deckel; Test `freier_ring_ist_geschlossen_mit_gehrung`); offene Enden stehen rechtwinklig. (11.11.) diff --git a/src-tauri/core/src/plan/dxf.rs b/src-tauri/core/src/plan/dxf.rs index 2d3fcd48..5806651e 100644 --- a/src-tauri/core/src/plan/dxf.rs +++ b/src-tauri/core/src/plan/dxf.rs @@ -897,6 +897,24 @@ impl Ctx<'_> { } } + /// [153] Linientyp eines gestrichelten Vollkreises vom Radius `r` (Modell-Meter): Muster auf ganze + /// Wiederholungen über den Umfang gestreckt, eigener Linientyp je Radius (`…_R`). DXF/DWG kennen keine + /// Musterphase je Objekt (das Muster beginnt am Entitätsanfang); so schliesst die Naht des Kreises trotzdem. + fn ltype_of_circle(&mut self, dash: &[f64], r: f64) -> f64 { + let k = self.o.scale / 1000.0; + if dash.is_empty() || !(k > 0.0) || !(r > 0.0) { + return self.ltype_of(dash); + } + let fit = crate::plan::line_pattern::fit_closed(dash, std::f64::consts::TAU * r / k); + match dash_to_ltype_meters(&fit, self.o.scale) { + Some(el) => { + let name = format!("{}_R{}", ltype_name_for(dash, &self.project.line_styles), jsnum::round(r * 1000.0)); + self.flat.add_linetype(&name, &el) + } + None => -1.0, + } + } + fn style_of(&mut self, s: Option<&TextStyleIn>) -> f64 { let (family, bold, italic) = match s { Some(s) => (s.family.clone(), s.bold, s.italic), @@ -940,7 +958,7 @@ impl Ctx<'_> { } } Prim::Circle { center, r, dash } => { - let lt = self.ltype_of(dash); + let lt = self.ltype_of_circle(dash, *r); self.flat.set_pen(b, lt); self.flat.add_circle(b, layer, *center, *r); } @@ -1668,6 +1686,24 @@ mod tests { assert_eq!(ltype_name_for(&[3.0, 1.0], &[st("Zz", Some(LineStyleKind::Zigzag)), st(" ", None)]), "DOSSIER_STRICH_3_1"); } + /// [153] Gestrichelter Vollkreis: eigener Linientyp je Radius, Muster auf ganze Wiederholungen über den Umfang. + #[test] + fn kreis_linientyp_mit_ganzen_wiederholungen() { + let project = Project::default(); + let o = DxfOptions { scale: 100.0, include_hatches: false, dim_cm: false, paper_layout: false, bounds: [0.0; 4], default_font: "Arial".into(), floor: String::new(), table_labels: String::new() }; + let mut cx = Ctx { project: &project, o: &o, flat: Flat::new() }; + let a = cx.ltype_of_circle(&[2.0, 1.0], 0.73); + let b = cx.ltype_of_circle(&[2.0, 1.0], 0.73); + let c = cx.ltype_of_circle(&[2.0, 1.0], 1.5); + assert!(a >= 0.0 && a == b && c != a, "{a} {b} {c}"); + assert_eq!(cx.ltype_of_circle(&[], 1.0), -1.0); + // Elemente des ersten Linientyps: Summe × Wiederholungen = Umfang (Modell-Meter). + let el = cx.flat.root.windows(3).position(|w| w[0] == REC_LTYPE).map(|i| &cx.flat.root[i + 3..i + 5]).unwrap(); + let total = el[0].abs() + el[1].abs(); + let reps = std::f64::consts::TAU * 0.73 / total; + assert!((reps - reps.round()).abs() < 1e-6 && reps.round() >= 1.0, "{el:?} {reps}"); + } + #[test] fn blocklokal_verschoben_gedreht_skaliert() { let f = Frame { origin: V2 { x: 10.0, y: 5.0 }, rot: PI / 2.0, scale: 2.0 }; diff --git a/src-tauri/core/src/plan/line_pattern.rs b/src-tauri/core/src/plan/line_pattern.rs index 9fa56834..e8722ace 100644 --- a/src-tauri/core/src/plan/line_pattern.rs +++ b/src-tauri/core/src/plan/line_pattern.rs @@ -107,6 +107,21 @@ pub fn phase(len: f64, dash: &[f64]) -> f64 { best_p } +/// Muster für einen **geschlossenen** Zug der Länge `len` (gleiche Einheit wie `dash`, Kreis: Umfang): auf +/// ganze Wiederholungen gestreckt, so dass es an der Naht nahtlos schliesst (Strich läuft über den Anfang +/// weiter, keine halbe Lücke). Ungerade Muster werden verdoppelt ([`cycle`]); Wiederholungen = gerundet, +/// mindestens 1. Ohne gültiges Muster oder Länge unverändert. +pub fn fit_closed(dash: &[f64], len: f64) -> Vec { + let Some(cyc) = cycle(dash) else { return dash.to_vec() }; + let total: f64 = cyc.iter().sum(); + if !(len > 0.0) || !len.is_finite() { + return dash.to_vec(); + } + let n = (len / total).round().max(1.0); + let k = len / (n * total); + cyc.iter().map(|v| v * k).collect() +} + /// Phase in Papier-mm für einen Zug der Modell-Länge `len_m` bei 1:`scale_n` (Muster in Papier-mm). pub fn phase_mm(len_m: f64, dash_mm: &[f64], scale_n: f64) -> f64 { let k = mm_to_m(scale_n); @@ -158,6 +173,24 @@ mod tests { assert_eq!(cycle(&[]), None); } + #[test] + fn geschlossener_zug_hat_ganze_wiederholungen() { + // Umfang 31.4 mm, Muster 3 mm: 10 Wiederholungen à 3.14 mm. + let d = fit_closed(&HIDDEN, 31.4); + assert_eq!(d.len(), 2); + assert!((d.iter().sum::() * 10.0 - 31.4).abs() < 1e-9, "{d:?}"); + assert!((d[0] / d[1] - 2.0).abs() < 1e-9, "Verhältnis bleibt"); + // Kürzer als ein Muster: genau eine Wiederholung. + let d = fit_closed(&HIDDEN, 1.0); + assert!((d.iter().sum::() - 1.0).abs() < 1e-9); + // Ungerade Länge wird verdoppelt, Punkte bleiben Punkte. + assert_eq!(fit_closed(&[3.0], 12.0).len(), 2); + assert_eq!(fit_closed(&DOTTED, 10.0)[0], 0.0); + // Unsinn: unverändert. + assert_eq!(fit_closed(&HIDDEN, f64::NAN), HIDDEN.to_vec()); + assert_eq!(fit_closed(&[], 5.0), Vec::::new()); + } + #[test] fn kurzes_stueck_ist_ein_strich() { // kürzer als ein Strich: ganz Strich (Phase 0). @@ -255,6 +288,57 @@ mod tests { assert!(p.first().unwrap().0 < 1e-9 && p.last().is_some_and(|q| (q.1 - 60.0).abs() < 1e-9), "{p:?}"); } + /// [153] Gestrichelter Vollkreis: Plan-SVG, Druck-SVG und Bildschirm-Szene strecken das Muster auf ganze + /// Wiederholungen über den Umfang (Naht schliesst), in jedem Massstab. + #[test] + fn gestrichelter_kreis_schliesst_an_der_naht() { + use crate::model::Vec2; + use crate::plan::buf::Writer; + use crate::plan::line_ends::LineEnds; + use crate::plan::print_svg::{print_svg_ops, PrintOptions}; + use crate::plan::prim::Primitive; + use crate::plan::svg::{plan_svg, SvgOptions}; + for n in [50.0, 100.0, 200.0] { + let k = mm_to_m(n); + let r_mm = 7.3; // Umfang 45.87 mm, Muster 3 mm + let circ_mm = std::f64::consts::TAU * r_mm; + let mut w = Writer::new(false); + let g = w.begin_group(); + w.push(&Primitive::DrawingCircle { center: Vec2 { x: 20.0 * k, y: 20.0 * k }, r: r_mm * k, fill: "none".into(), stroke: "#000".into(), weight_mm: 0.18, dash: Some(Some(HIDDEN.to_vec())), drawing_id: None, greyed: None, opacity: None }); + w.end_group(g); + let bytes = w.finish(); + let whole = |d: &[f64]| { + let reps = circ_mm / d.iter().sum::(); + (reps - reps.round()).abs() < 1e-3 && reps.round() >= 1.0 + }; + let o = SvgOptions { scale_denominator: n, margin_m: 0.0, min_x: 0.0, min_y: 0.0, max_x: 40.0 * k, max_y: 40.0 * k, hatch: false, line_ends: LineEnds::default() }; + let svg = plan_svg(&mut parts(&bytes), &o).unwrap(); + let el = svg.lines().find(|l| l.starts_with(" = attr(el, "stroke-dasharray").unwrap().split(' ').map(|x| x.parse::().unwrap() / k).collect(); + assert!(whole(&d), "Plan-SVG 1:{n}: {d:?}"); + assert!(attr(el, "stroke-dashoffset").is_none(), "Kreis ohne Phase"); + let po = PrintOptions { scale_denominator: n, page_w: 100.0, page_h: 100.0, bounds: [0.0, 0.0, 40.0 * k, 40.0 * k] }; + let ops = print_svg_ops(&mut parts(&bytes), &po).unwrap(); + let rec: Vec<&str> = ops.split('\u{1e}').map(|r| r.split('\u{1f}').collect::>()).find(|f| f.contains(&"circle")).unwrap(); + let i = rec.iter().position(|x| *x == "stroke-dasharray").unwrap(); + let d: Vec = rec[i + 1].split(' ').map(|x| x.parse().unwrap()).collect(); + assert!(whole(&d), "Druck-SVG 1:{n}: {d:?}"); + } + // Bildschirm-Szene (Bezug 1:100, Papier-mm × 0.1 = Meter). + let r = 0.73; // 7.3 mm × 0.1 + let mut w = Writer::new(false); + let g = w.begin_group(); + w.push(&Primitive::DrawingCircle { center: Vec2 { x: 2.0, y: 2.0 }, r, fill: "none".into(), stroke: "#000".into(), weight_mm: 0.18, dash: Some(Some(HIDDEN.to_vec())), drawing_id: None, greyed: None, opacity: None }); + w.end_group(g); + let bytes = w.finish(); + let sc = crate::plan::scene::build_scene(&mut parts(&bytes), &[]).unwrap(); + let pl = &sc.polylines[0]; + let crate::plan::scene::SDash::List(d) = &pl.dash else { panic!("Strichliste erwartet") }; + let len: f64 = pl.pts.windows(2).map(|q| ((q[1].x - q[0].x).powi(2) + (q[1].y - q[0].y).powi(2)).sqrt()).sum::() / 0.1; + let reps = len / d.iter().sum::(); + assert!((reps - reps.round()).abs() < 1e-6 && reps.round() >= 1.0, "Szene: {d:?} {reps}"); + } + /// Gleiche Werte wie `render2d::tessellate::tests::musterphase_enden_auf_strich` (Shader-Spiegel). #[test] fn phase_wie_render2d() { diff --git a/src-tauri/core/src/plan/print_svg.rs b/src-tauri/core/src/plan/print_svg.rs index bce55aa9..200c2f3d 100644 --- a/src-tauri/core/src/plan/print_svg.rs +++ b/src-tauri/core/src/plan/print_svg.rs @@ -534,7 +534,9 @@ fn entry(out: &mut Out, view: &View, i: usize, hatches: &[(i32, Hatch, i32)], m: ("stroke", s(f[1])?), ("stroke-width", js_number(quantize_pen(f[2]))), ]; - push_dash(&mut attrs, dash(&rec)?.as_deref()); + // [153] Vollkreis: Muster auf ganze Wiederholungen über den Umfang gestreckt (Naht schliesst). + let dd = dash(&rec)?.map(|d| super::line_pattern::fit_closed(&d, f[6] * k * PI * 2.0)); + push_dash(&mut attrs, dd.as_deref()); let o = opacity_of(greyed, obj(3)); if !o.is_empty() { attrs.push(("opacity", o)); diff --git a/src-tauri/core/src/plan/scene.rs b/src-tauri/core/src/plan/scene.rs index 3e9152aa..f666d7f8 100644 --- a/src-tauri/core/src/plan/scene.rs +++ b/src-tauri/core/src/plan/scene.rs @@ -625,7 +625,13 @@ pub fn build_scene(parts: &mut [Part], greyed_ranges: &[(usize, usize)]) -> Opti pts.push(v2(c.x + r * jsnum::cos(t), c.y + r * jsnum::sin(t))); k += 1.0; } - let dash = dash_of(part, &rec)?; + let mut dash = dash_of(part, &rec)?; + // [153] Vollkreis: Muster auf ganze Wiederholungen über den Umfang gestreckt, die Naht schliesst + // (Bildschirm-Bezug wie render2d: Papier-mm × `LINE_DASH_MM_TO_M` = Meter). + if let (true, SDash::List(l)) = (circle, &dash) { + let len: f64 = pts.windows(2).map(|q| crate::jsmath::hypot2(q[1].x - q[0].x, q[1].y - q[0].y)).sum(); + dash = SDash::List(super::line_pattern::fit_closed(l, len / crate::gpu_compile::LINE_DASH_MM_TO_M)); + } let z = b.z(); b.s.polylines.push(SStroke { pts, color: col, width_mm: w, dash, z, width_screen: false }); } diff --git a/src-tauri/core/src/plan/svg.rs b/src-tauri/core/src/plan/svg.rs index 5eb65ed8..65d80e99 100644 --- a/src-tauri/core/src/plan/svg.rs +++ b/src-tauri/core/src/plan/svg.rs @@ -227,6 +227,21 @@ fn arc_dash_offset(part: &Part, rec: &crate::plan::buf::Rec, len_m: f64, mm_to_m } } +/// [153] `stroke-dasharray` eines gestrichelten Vollkreises vom Umfang `circ_m`: Muster auf ganze Wiederholungen +/// gestreckt ([`super::line_pattern::fit_closed`]), damit es an der Naht schliesst; `None` ohne Strichliste. +fn circle_dash_attr(part: &Part, rec: &crate::plan::buf::Rec, circ_m: f64, mm_to_m: f64) -> Option { + if rec.flags & F_DASH_LIST == 0 || !(mm_to_m > 0.0) { + return None; + } + let d = rec.dash.and_then(|(o, n)| part.view.pool(o, n))?; + if d.is_empty() { + return None; + } + let fit = super::line_pattern::fit_closed(&d, circ_m / mm_to_m); + let cap = if fit.iter().any(|v| *v == 0.0) { " stroke-linecap=\"round\"" } else { "" }; + Some(format!(" stroke-dasharray=\"{}\"{cap}", fit.iter().map(|v| num(v * mm_to_m)).collect::>().join(" "))) +} + /// Gestrichelter Zug aus aneinander anschliessenden Linien gleicher Darstellung ([153]). struct DashRun { /// Attribute ohne Geometrie (Farbe, Breite, Muster, Deckkraft). @@ -459,7 +474,7 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option { T_CIRCLE => { let fill = esc(part.str(f[0]).unwrap_or("")); let stroke = esc(part.str(f[1]).unwrap_or("")); - let dash = dash_attr(part)?; + let dash = circle_dash_attr(part, &rec, f[6] * PI * 2.0, mm_to_m).map_or_else(|| dash_attr(part), Some)?; out.push(format!( "", xs(f[4]), diff --git a/src-tauri/core/src/web/line_pattern.rs b/src-tauri/core/src/web/line_pattern.rs index 9fa5d6e5..8526ec4e 100644 --- a/src-tauri/core/src/web/line_pattern.rs +++ b/src-tauri/core/src/web/line_pattern.rs @@ -15,6 +15,18 @@ pub fn line_dash_phase(len_mm: f64, dash_mm: &[f64]) -> f64 { } } +/// [153] Strichmuster eines geschlossenen Zugs der Länge `len` (gleiche Einheit wie `dash_mm`, Papier-mm), +/// auf ganze Wiederholungen gestreckt (Kern `fit_closed`); bei Unsinn unverändert, nie Panic. +#[wasm_bindgen] +pub fn line_dash_fit_closed(len_mm: f64, dash_mm: &[f64]) -> Vec { + let d = crate::plan::line_pattern::fit_closed(dash_mm, len_mm); + if d.iter().all(|v| v.is_finite()) { + d + } else { + dash_mm.to_vec() + } +} + /// [169] SVG-Pfad (`d`) eines Zugs in Papier-mm (`[x0, y0, x1, y1, …]`, Y nach unten) mit erkannten Bögen /// (`crate::plan::arc_fit`): Kreis bzw. Strecken und `A`-Befehle; leer, wenn kein Bogen erkannt wurde oder /// die Eingabe Unsinn ist (dann bleibt `polygon`/`polyline`). `tol` = Toleranz in mm. diff --git a/src/core/index.ts b/src/core/index.ts index 7def392c..8f2a6a5a 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -204,7 +204,7 @@ export { viewForScale, visibleEdgeRuns, } from "../plan/planView/geometry"; -export { PLAN_DASH_VAR, dashArrayCss, fitDashToPeriod, hatchDashVb, lineDashVb } from "../plan/planView/dashVb"; +export { PLAN_DASH_VAR, dashArrayCss, dashOffsetCss, fitDashToPeriod, hatchDashVb, lineDashOffsetVb, lineDashVb, ringDashVb } from "../plan/planView/dashVb"; export { type ClientMap, diff --git a/src/export/sceneToPrintSvg.dash.test.ts b/src/export/sceneToPrintSvg.dash.test.ts index 6947909b..9fcd8376 100644 --- a/src/export/sceneToPrintSvg.dash.test.ts +++ b/src/export/sceneToPrintSvg.dash.test.ts @@ -84,4 +84,19 @@ describe("Druck-SVG: Kreise und Bögen", () => { const arc = paths.find((p) => p.attrs.has("stroke-dasharray"))!; expect(arc.attrs.get("stroke-dashoffset")).toBeDefined(); }); + + it("Vollkreis: Muster auf ganze Wiederholungen über den Umfang, ohne Phase", () => { + for (const n of [50, 100, 200]) { + const r = (7.3 * n) / 1000; // 7.3 mm Radius auf dem Papier + const pts: [number, number][] = []; + for (let i = 0; i <= 96; i++) pts.push([r * Math.cos((2 * Math.PI * i) / 96), r * Math.sin((2 * Math.PI * i) / 96)]); + const sc = { fills: [], outlines: [], polylines: [{ pts, color: [0, 0, 0, 1], widthMm: 0.18, dash: [2, 1], z: 0, widthScreen: false }], arcs: [], lines: [], texts: [], images: [], bounds: { minX: -r, minY: -r, maxX: r, maxY: r } } as unknown as RScene; + const svg = sceneToPrintSvg(sc, { scaleDenominator: n, pageWidthMm: 100, pageHeightMm: 100 }).svg as unknown as FakeEl; + const el = svg.children.find((c) => c.tag !== "defs" && c.attrs.has("stroke-dasharray"))!; + const d = el.attrs.get("stroke-dasharray")!.split(" ").map(Number); + const reps = (2 * Math.PI * 7.3) / (d[0] + d[1]); + expect(Math.abs(reps - Math.round(reps))).toBeLessThan(0.02); + expect(el.attrs.has("stroke-dashoffset")).toBe(false); + } + }); }); diff --git a/src/export/sceneToPrintSvg.ts b/src/export/sceneToPrintSvg.ts index ce72ae8c..24ebd00b 100644 --- a/src/export/sceneToPrintSvg.ts +++ b/src/export/sceneToPrintSvg.ts @@ -301,14 +301,33 @@ function appendStroke( if (dash && dash.length) { // Strichmuster ist bereits in Papier-mm definiert (siehe `toRenderScene.ts`: // „unveraendert durchgereicht"), also direkt uebernehmen. - el.setAttribute("stroke-dasharray", dash.map((d) => round(d)).join(" ")); + const mm = pts.map((p) => map(p)); + // [153] Vollkreis (Zug, dessen Ende am Anfang liegt): Muster auf ganze Wiederholungen gestreckt, die Naht + // schliesst; keine Phase noetig. + const ring = closed || isRing(mm); + const useDash = !closed && ring ? ringDash(mm, dash) : dash; + el.setAttribute("stroke-dasharray", useDash.map((d) => round(d)).join(" ")); // Punkte (Strich 0) brauchen runde Enden, sonst unsichtbar ([96]). - if (dash.some((d) => d === 0)) el.setAttribute("stroke-linecap", "round"); - setDashOffset(el, pts.map((p) => map(p)), closed, dash); + if (useDash.some((d) => d === 0)) el.setAttribute("stroke-linecap", "round"); + if (closed || !ring) setDashOffset(el, mm, closed, dash); } svg.appendChild(el); } +/** Offener Zug mit Ende auf dem Anfang (tesselierter Vollkreis der Szene, mindestens 8 Punkte). */ +function isRing(ptsMm: [number, number][]): boolean { + const n = ptsMm.length; + if (n < 8) return false; + return Math.hypot(ptsMm[n - 1][0] - ptsMm[0][0], ptsMm[n - 1][1] - ptsMm[0][1]) < 1e-6; +} + +/** [153] Muster des Rings auf ganze Wiederholungen über seine Länge gestreckt (Kern `plan::line_pattern::fit_closed`). */ +function ringDash(ptsMm: [number, number][], dash: number[]): number[] { + let len = 0; + for (let i = 0; i + 1 < ptsMm.length; i++) len += Math.hypot(ptsMm[i + 1][0] - ptsMm[i][0], ptsMm[i + 1][1] - ptsMm[i][1]); + return Array.from(core().line_dash_fit_closed(len, Float64Array.from(dash))); +} + /** * [153] Musterphase eines gestrichelten Zugs (Papier-mm-Punkte): Kern `plan::line_pattern::phase`, * damit beide Enden möglichst auf einem Strich liegen — gleich wie Plan-/Druck-SVG und Bildschirm. diff --git a/src/plan/planView/dashVb.test.ts b/src/plan/planView/dashVb.test.ts index 93b9184b..291461ad 100644 --- a/src/plan/planView/dashVb.test.ts +++ b/src/plan/planView/dashVb.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "vitest"; -import { dashArrayCss, fitDashToPeriod, hatchDashVb, lineDashVb } from "./dashVb"; +import { dashArrayCss, dashOffsetCss, fitDashToPeriod, hatchDashVb, lineDashOffsetVb, lineDashVb, ringDashVb } from "./dashVb"; import { PX_PER_M } from "./geometry"; describe("Strichmuster im Modell-Raum (SVG-Pfad)", () => { @@ -27,4 +27,15 @@ describe("Strichmuster im Modell-Raum (SVG-Pfad)", () => { expect(f[0] + f[1]).toBeCloseTo(8 / 2, 9); expect(fitDashToPeriod([], 8)).toEqual([]); }); + + it("[153] Phase in viewBox-Einheiten = Kern-Phase in Papier-mm, Ring mit ganzen Wiederholungen", () => { + // 10 mm lang bei 1:100 mit [2, 1]: Phase 0.5 mm (Kern `phase`). + const k = (100 / 1000) * PX_PER_M; + expect(lineDashOffsetVb([2, 1], 100, 10 * k)).toBeCloseTo(0.5 * k, 6); + expect(lineDashOffsetVb([2, 1], 100, 0)).toBe(0); + expect(dashOffsetCss(0, true)).toBeUndefined(); + expect(dashOffsetCss(3, false)).toBe("3"); + const ring = ringDashVb([2, 1], 100, 31.4 * k); + expect((ring[0] + ring[1]) * 10).toBeCloseTo(31.4 * k, 6); + }); }); diff --git a/src/plan/planView/dashVb.ts b/src/plan/planView/dashVb.ts index ff781dfc..b05bd0f8 100644 --- a/src/plan/planView/dashVb.ts +++ b/src/plan/planView/dashVb.ts @@ -5,6 +5,7 @@ import { PX_PER_M } from "./geometry"; import { DASH_MM_TO_M } from "../glPlan/glPlanHatch"; +import { core } from "../../engine/coreWasm"; /** CSS-Variable am Plan-SVG: CSS-px je viewBox-Einheit (meet), für Muster unter `non-scaling-stroke`. */ export const PLAN_DASH_VAR = "--plan-dash-k"; @@ -44,3 +45,37 @@ export function dashArrayCss(vb: readonly number[], nonScaling: boolean): string const r = (v: number) => Math.round(v * 1e4) / 1e4; return vb.map((v) => (nonScaling ? `calc(var(${PLAN_DASH_VAR}, 1) * ${r(v)}px)` : `${r(v)}`)).join(" "); } + +/** viewBox-Einheiten je Papier-mm im Plot-Massstab 1:`plotN` (ohne gültiges N: 1:100). */ +function vbPerMm(plotN: number): number { + const n = Number.isFinite(plotN) && plotN > 0 ? plotN : 100; + return (n / 1000) * PX_PER_M; +} + +/** + * [153] Musterphase (viewBox-Einheiten) eines gestrichelten Zugs der Länge `lenVb`: Kern + * `plan::line_pattern::phase`, beide Enden möglichst auf einem Strich — gleich wie Plan-/Druck-SVG und Bildschirm. + */ +export function lineDashOffsetVb(dash: readonly number[], plotN: number, lenVb: number): number { + if (!dash.length || !(lenVb > 0) || !Number.isFinite(lenVb)) return 0; + const k = vbPerMm(plotN); + const ph = core().line_dash_phase(lenVb / k, Float64Array.from(dash)); + return Number.isFinite(ph) ? ph * k : 0; +} + +/** + * [153] Muster (viewBox-Einheiten) eines Rings der Länge `lenVb` (Vollkreis als Zug, Ende = Anfang) auf ganze + * Wiederholungen gestreckt: die Naht schliesst (Kern `fit_closed`). + */ +export function ringDashVb(dash: readonly number[], plotN: number, lenVb: number): number[] { + if (!dash.length || !(lenVb > 0) || !Number.isFinite(lenVb)) return lineDashVb(dash, plotN); + const k = vbPerMm(plotN); + return lineDashVb(Array.from(core().line_dash_fit_closed(lenVb / k, Float64Array.from(dash))), plotN); +} + +/** `stroke-dashoffset` als CSS-Wert (wie [`dashArrayCss`]); `undefined` ohne Phase. */ +export function dashOffsetCss(vb: number, nonScaling: boolean): string | undefined { + if (!(vb > 1e-9)) return undefined; + const r = Math.round(vb * 1e4) / 1e4; + return nonScaling ? `calc(var(${PLAN_DASH_VAR}, 1) * ${r}px)` : `${r}`; +} diff --git a/src/views/plan/planView/primitives.tsx b/src/views/plan/planView/primitives.tsx index d99aa426..b0c7a749 100644 --- a/src/views/plan/planView/primitives.tsx +++ b/src/views/plan/planView/primitives.tsx @@ -13,7 +13,7 @@ import { quantizePen } from "../../../export/sceneToPrintSvg"; import { buildHatchRuns, buildRandomHatchRuns, zigzagPoints, motifPoints, DASH_MM_TO_M } from "../../../core"; import { dashHasDot } from "../../../core"; import { HAIRLINE_PX, PX_PER_M, mmToPx, printStrokeVb, visibleEdgeRuns } from "../../../core"; -import { dashArrayCss, fitDashToPeriod, hatchDashVb, lineDashVb } from "../../../core"; +import { dashArrayCss, dashOffsetCss, fitDashToPeriod, hatchDashVb, lineDashOffsetVb, lineDashVb, ringDashVb } from "../../../core"; /** Basis-Kachelmaß (viewBox-Einheiten) einer Bild-Schraffur bei scaleX/scaleY = 1. */ const IMG_TILE_VB = 40; @@ -400,7 +400,12 @@ export function DrawingRunShape({ : mmToPx(run.weightMm); const vfx = print ? undefined : ("non-scaling-stroke" as const); // Linientyp in Papier-mm im Plot-Massstab: fest im Modell-Raum (Bildschirm = Druckansicht). - const dashStr = run.dash && run.dash.length ? dashArrayCss(lineDashVb(run.dash, paperScale ?? 100), !print) : undefined; + // Musterphase ([153]): Länge des Zugs in viewBox-Einheiten; Vollkreis (Ende = Anfang) mit ganzen Wiederholungen. + const runLen = (v: { x: number; y: number }[]): number => { + let l = 0; + for (let i = 0; i + 1 < v.length + (run.closed ? 1 : 0); i++) l += Math.hypot(v[(i + 1) % v.length].x - v[i].x, v[(i + 1) % v.length].y - v[i].y); + return l; + }; // Zickzack-/Custom-Motiv-Lauf: im MODELL-Raum tessellieren (Papier-mm → // Modell-Meter via DASH_MM_TO_M), dann toScreen. Sonst die Roh-Stützpunkte. const modelPts = run.zigzag @@ -413,7 +418,17 @@ export function DrawingRunShape({ : run.motif ? motifPoints(run.pts[0], run.pts[run.pts.length - 1], run.motif, DASH_MM_TO_M) : run.pts; - const pts = modelPts.map(toScreen).map((s) => `${s.x},${s.y}`).join(" "); + const scrPts = modelPts.map(toScreen); + const pts = scrPts.map((s) => `${s.x},${s.y}`).join(" "); + const plotN = paperScale ?? 100; + const ring = + !run.closed && scrPts.length >= 8 && Math.hypot(scrPts[scrPts.length - 1].x - scrPts[0].x, scrPts[scrPts.length - 1].y - scrPts[0].y) < 1e-6; + const dashStr = + run.dash && run.dash.length + ? dashArrayCss(ring ? ringDashVb(run.dash, plotN, runLen(scrPts)) : lineDashVb(run.dash, plotN), !print) + : undefined; + const dashOff = run.dash && run.dash.length && !ring ? dashOffsetCss(lineDashOffsetVb(run.dash, plotN, runLen(scrPts)), !print) : undefined; + const dashSt = dashStr ? { strokeDasharray: dashStr, ...(dashOff ? { strokeDashoffset: dashOff } : {}) } : undefined; // Punktmuster (dash enthält eine 0): runde Kappe, damit die 0-Längen-Segmente // als Dots erscheinen (Punktlinie / Strich-Punkt). const cap = dashHasDot(run.dash) ? ("round" as const) : undefined; @@ -425,7 +440,7 @@ export function DrawingRunShape({ fill="none" stroke={stroke} strokeWidth={sw} - style={dashStr ? { strokeDasharray: dashStr } : undefined} + style={dashSt} strokeLinecap={cap} vectorEffect={vfx} /> @@ -436,7 +451,7 @@ export function DrawingRunShape({ fill="none" stroke={stroke} strokeWidth={sw} - style={dashStr ? { strokeDasharray: dashStr } : undefined} + style={dashSt} strokeLinecap={cap} vectorEffect={vfx} /> @@ -512,9 +527,18 @@ export function renderPrimitive( // sonst wie bisher in Bildschirm-px (non-scaling). // Linientypen in Papier-mm im Plot-Massstab: fest im Modell-Raum, auch unter non-scaling-stroke // (über die meet-Variable am SVG) — der Rhythmus gleicht bei jedem Zoom der Druckansicht. - const dashOf = (dash: number[] | null | undefined): { strokeDasharray: string } | undefined => { + const dashOf = (dash: number[] | null | undefined, lenVb?: number): { strokeDasharray: string; strokeDashoffset?: string } | undefined => { if (!dash || !dash.length) return undefined; const css = dashArrayCss(lineDashVb(dash, paperScale ?? 100), !print); + if (!css) return undefined; + // [153] Musterphase des Zugs (Linie, Bogen): beide Enden möglichst auf einem Strich. + const off = lenVb ? dashOffsetCss(lineDashOffsetVb(dash, paperScale ?? 100, lenVb), !print) : undefined; + return { strokeDasharray: css, ...(off ? { strokeDashoffset: off } : {}) }; + }; + // [153] Vollkreis: Muster auf ganze Wiederholungen über den Umfang gestreckt (Naht schliesst), ohne Phase. + const ringStyle = (dash: number[] | null | undefined, lenVb: number): { strokeDasharray: string } | undefined => { + if (!dash || !dash.length) return undefined; + const css = dashArrayCss(ringDashVb(dash, paperScale ?? 100, lenVb), !print); return css ? { strokeDasharray: css } : undefined; }; switch (p.kind) { @@ -673,7 +697,7 @@ export function renderPrimitive( className={p.cls} stroke={p.color} strokeWidth={weight(p.weightMm)} - style={dashOf(p.dash)} + style={dashOf(p.dash, Math.hypot(b.x - a.x, b.y - a.y))} strokeLinecap={dashHasDot(p.dash) ? "round" : undefined} vectorEffect={vfx} /> @@ -696,7 +720,7 @@ export function renderPrimitive( d={d} className={p.cls} strokeWidth={weight(p.weightMm)} - style={dashOf(p.dash)} + style={dashOf(p.dash, r * Math.min(Math.PI, Math.abs(Math.atan2(cross, v1.x * v2.x + v1.y * v2.y))))} strokeLinecap={dashHasDot(p.dash) ? "round" : undefined} vectorEffect={vfx} /> @@ -895,7 +919,8 @@ export function renderPrimitive( fill={p.fill} stroke={p.stroke} strokeWidth={weight(p.weightMm)} - style={dashOf(p.dash)} + style={ringStyle(p.dash, 2 * Math.PI * r)} + strokeLinecap={dashHasDot(p.dash) ? "round" : undefined} vectorEffect={vfx} /> ); @@ -923,7 +948,7 @@ export function renderPrimitive( fill="none" stroke={p.stroke} strokeWidth={weight(p.weightMm)} - style={dashOf(p.dash)} + style={dashOf(p.dash, rPx * sweep)} strokeLinecap={dashHasDot(p.dash) ? "round" : undefined} vectorEffect={vfx} />