[38][112] Achsraster (rechtwinklig/radial, Blasen, Fang, Schnitt/Ansicht, DXF, Griffe), Bemassung an Rasterachsen, Bogenwänden, Treppen; Radius-/Durchmesser-/Bogenlängen-Mass; Autodim für nicht mittige Wände

This commit is contained in:
Claude committed 2026-10-30 09:16:40 +00:00
1 parent 265e3e25a4
commit dfa4e5a32e
41 files changed
+2351 -72

No files matched your search

+23 -3
View File
@@ -1499,8 +1499,15 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
(Befehl `dimdetach`, Kürzel `bml`, Kontextmenü, Objekt-Info). Autodim [81] hängt an Ecken/Leibungen.
Transformieren: Bezüge bleiben bei Verschieben/Drehen zusammen mit den Elementen, sonst (allein, Spiegeln,
Skalieren) gelöst; Kopien hängen an mitkopierten Elementen; ein von Hand gezogener Punkt ist frei.
Offen: Bogenwände/Treppen nicht anhängbar, Achsraster fehlt im Modell; nur Linux/Chromium geprüft (Marke
am Bildschirm nicht auf macOS/Metal angesehen). · L
Nachtrag (30.10.): auch Bogenwände (Enden, Punkt auf Achse/Fläche als Anteil der Bogenlänge, Mittelpunkt, Rand-
Bezug `rim` mit Winkel), Treppen (Umriss-Ecken/-Kanten, bei L-Treppen auch Podest-Ecken/-Kanten; Wendel: die vier
Ecken der Schliesslinien, Mittelpunkt), Rasterachsen und Achsschnittpunkte [112] sind anhängbar. **Radius-,
Durchmesser- und Bogenlängen-Bemassung** (`Dimension.kind`, Befehle `dimradius`/`dimdiameter`/`dimarc`, Kürzel
`rad`/`dm`/`bogenl`): Klick auf den Rand eines 2D-Kreises/-Bogens oder einer Bogenwand (Achse oder Schichtfläche);
Mittelpunkt und Randpunkte hängen an `center`/`rim` und werden einzeln (ohne Kettenprojektion) nachgeführt; DXF als
Linien/Bögen/Text (nicht als DIMENSION). Autodim [81] misst nicht mittige Wände (Referenzlinie/-versatz) jetzt an
der echten Fläche. Offen: Wendeltreppen-Bögen (nur die Schliesslinien-Ecken), Treppenlauf-Mitten, Rand-Bezug auf
Ellipsen/Splines; nur Linux/Chromium geprüft (Marke am Bildschirm nicht auf macOS/Metal angesehen). · L
- ○ **[39] Auswahl gehört zum Modell.** · M
- ◐ **[40] Ansichten duplizieren.** Ebenen duplizieren vorhanden. · S
- ◐ **[76] Vektorfang auf PDF.** (28.10.) Rust `fileio/pdf_object.rs` + `pdf_vector.rs` (eigener Leser:
@@ -1646,7 +1653,8 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
Einzel-Plan-PDF (`exportPdf.ts`) noch ohne Ebenen.
- ◐ **[81] Automatische Aussenbemassung.** (27.10.) Befehl `autodim` (Kürzel `ab`): je Seite Öffnungs-,
Vor-/Rücksprung- und Gesamtkette. Offen: schiefe Wände, Massstab aus der Ansicht statt fest 1:100.
(30.10.) Ketten assoziativ [38] (Ecken/Leibungen, nur mittige Wände).
(30.10.) Ketten assoziativ [38] (Ecken/Leibungen). Nicht mittige Wände
(Referenzlinie links/rechts, -versatz): die Kette misst die echte Fläche (`WallIn.shift`). Offen: Bogenwände als Sehne.
- ✅ **[82] Grafische Legenden.** (30.10.) `Layout.legends` (`LayoutLegend`: Lage, Titel, Arten Schraffur/Material · Linientyp ·
Kategorie, optional Handauswahl `manualKeys`). `analysis/legend.ts`: Einträge automatisch aus den Viewports (Material der
Wand-/Decken-/Dach-Aufbauten und Stützen im gezeigten Geschoss, Schraffuren/Linientypen der Zeichnungen, sichtbare
@@ -1776,6 +1784,18 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
Tabellenbreite nur über das Zahlenfeld (kein Ziehgriff); keine Kopfzeilen-Füllung/Farben; Schrift im PDF nur
Helvetica/Times/Courier (jsPDF-Grundschriften); DXF-Beschriftungen in der Sprache der Oberfläche beim Export;
nicht in der Tauri-App getestet. · S
- ✅ **[112] Achsraster.** (30.10.) Neue 2D-Zeichnungsform `Drawing2DGeom::Grid` (`grid.rs`, Auswahl/Verschieben/Kopieren/
Ebenen/DXF wie jede Zeichnung): rechtwinklig (`a` = Achsen 1, 2, 3 …, `b` = A, B, C …, unregelmässige Abstände, gedreht
um `angle`) oder radial (Strahlen in Grad, Ringe als Bögen/Kreise), `extend` Überstand, `bubbles` Start/Ende/beide,
`bubbleMm` (Papier-mm), `levels` (leer = in allen Geschossen), `show3d` (dünne Spur im 3D). Grundriss: strichpunktierte
Achsen, Blasen mit Beschriftung (Massstab folgt `scale`); Schnitt und Ansicht: Achsen quer zur Blickebene als senkrechte
Linien mit Blase oben (`plan/grid_view.rs`, eigene Gruppe, Massstab über `scaleDenominator`); Fang auf Achsen,
Ringe und Achsschnittpunkte (Endpunkt); Griffe: Ursprung und je Achse das Achsende (zieht die Lage); Bemassung
assoziativ [38] an Achse/Achsschnittpunkt. Befehl `grid` (Kürzel `achsraster`, `achsen`, Werkzeug „Achsraster"):
Ursprung, dann Feldweiten als Text (`6 4.5 3x5`), Option Radial; Attribute-Panel: Blasenseite, Überstand, Blasen-Ø,
Geschosse, 3D. Geprüft im Linux-Container (Rust, vitest, e2e, CLI-SVG Grundriss/Schnitt/Ansicht), nicht in der
Tauri-App/Metal. Offen: Achsbeschriftung je Achse im UI ändern, Blasenseite je Achse, Achsen als Autodim-Vorschlag,
IFC `IfcGrid`, Raster-Versatz je Geschoss. · M
- ◐ **[110] Linientyp ohne Strichstärke.** (30.10., Wunsch Maintainer: „Volllinie 0.5/0.35 soll es nicht
geben") Ein Linienstil ist nur Muster (Volllinie, Strich, Punkt, Zickzack, Motiv) + Farbe; die Stärke trägt
das Element (`Drawing2D.weightMm`, sonst Ebene), die Schraffur (neu `HatchStyle.lineWeight`, Default 0.13),
+79
View File
@@ -0,0 +1,79 @@
// [112]/[38] Achsraster: anlegen (Ursprung + Feldweiten), zwischen zwei Achsen bemassen, Achse am Griff
// verschieben → die Bemassung folgt; Rückgängig stellt beides her.
import { blurFocus, commandInput, expect, openTab, startNewProject, test, typeCommand } from "./app";
import type { Page } from "@playwright/test";
/** Modellpunkt (m) → Client-Pixel (wie `dimAssoc.spec.ts::screenOf`). */
async function screenOf(page: Page, x: number, y: number): Promise<{ x: number; y: number }> {
return page.locator("svg.plan-svg").evaluate(
(el, [mx, my]) => {
const [vx, vy, vw, vh] = el.getAttribute("viewBox")!.split(/\s+/).map(Number);
const ox = Number(el.getAttribute("data-origin-x") ?? 0);
const oy = Number(el.getAttribute("data-origin-y") ?? 0);
const r = el.getBoundingClientRect();
const s = Math.min(r.width / vw, r.height / vh);
return {
x: r.left + (r.width - vw * s) / 2 + (mx * 90 - ox - vx) * s,
y: r.top + (r.height - vh * s) / 2 + (-my * 90 - oy - vy) * s,
};
},
[x, y],
);
}
async function clickModel(page: Page, x: number, y: number): Promise<void> {
const p = await screenOf(page, x, y);
await page.mouse.move(p.x, p.y);
await page.mouse.click(p.x, p.y);
}
const numbers = (page: Page) =>
page.locator("svg.plan-svg text").evaluateAll((els) => els.map((e) => e.textContent ?? "").filter((s) => /^\d+\.\d\d$/.test(s)));
const labels = (page: Page) => page.locator("svg.plan-svg text").evaluateAll((els) => els.map((e) => e.textContent ?? ""));
test("Achsraster anlegen, zwischen zwei Achsen bemassen, Achse verschieben → Mass folgt", async ({ page }) => {
await startNewProject(page);
await openTab(page, "Elemente");
await commandInput(page).focus();
await typeCommand(page, "achsraster");
await expect(page.locator(".cmdline-prompt")).toHaveText(/Ursprung des Achsrasters/);
await typeCommand(page, "0,0");
await expect(page.locator(".cmdline-prompt")).toHaveText(/Feldweiten Achsen 1, 2, 3/);
await typeCommand(page, "6 6");
await expect(page.locator(".cmdline-prompt")).toHaveText(/Feldweiten Achsen A, B, C/);
await typeCommand(page, "5");
await blurFocus(page);
await page.getByTitle("Auf Plan einpassen").click();
// Beschriftungen in den Blasen: 1, 2, 3 und A, B (je an beiden Enden).
await expect.poll(() => labels(page)).toEqual(expect.arrayContaining(["1", "2", "3", "A", "B"]));
// Bemassung der Achsen 1 und 2 (Achsschnittpunkte A/1 und A/2), Abstand 1 m unter dem Raster.
await commandInput(page).focus();
await typeCommand(page, "dim");
await clickModel(page, 0, 0);
await clickModel(page, 6, 0);
await commandInput(page).press("Enter");
await expect(page.locator(".cmdline-prompt")).toHaveText(/Lage der Masslinie/);
await typeCommand(page, "-1");
await expect.poll(() => numbers(page)).toContain("6.00");
// Raster wählen (Klick auf Achse 2), Achsgriff am Achsende nach rechts ziehen: Achse 2 von x = 6 auf 7.5.
await blurFocus(page);
await page.keyboard.press("Escape");
await clickModel(page, 6, 2.5);
await expect.poll(() => page.locator(".plan-grip").count()).toBeGreaterThan(2);
const from = await screenOf(page, 6, 6.5);
const to = await screenOf(page, 7.5, 6.5);
await page.mouse.move(from.x, from.y);
await page.mouse.down();
await page.mouse.move((from.x + to.x) / 2, from.y, { steps: 4 });
await page.mouse.move(to.x, to.y, { steps: 4 });
await page.mouse.up();
await page.mouse.click(to.x, to.y);
await expect.poll(async () => (await numbers(page)).some((v) => Math.abs(Number(v) - 7.5) < 0.1)).toBe(true);
await blurFocus(page);
await page.keyboard.press("ControlOrMeta+z");
await expect.poll(() => numbers(page)).toContain("6.00");
});
+31 -7
View File
@@ -20,6 +20,9 @@ pub struct WallIn {
pub start: Vec2,
pub end: Vec2,
pub thickness: f64,
/// Versatz der Wandmitte von der Achse (links der Laufrichtung positiv): Wände mit Referenzlinie
/// links/rechts oder -versatz liegen nicht mittig auf ihrer Achse.
pub shift: f64,
}
/// Öffnung: Index der Wirtswand in der Wandliste, Leibungspunkte auf der Achse.
@@ -66,8 +69,9 @@ fn wall_rect(w: &WallIn, t: f64, ext_start: f64, ext_end: f64) -> Ring {
let len = dx.hypot(dy);
let (ux, uy) = (dx / len, dy / len);
let (nx, ny) = (-uy * (t / 2.0), ux * (t / 2.0));
let a = [w.start[0] - ux * ext_start, w.start[1] - uy * ext_start];
let b = [w.end[0] + ux * ext_end, w.end[1] + uy * ext_end];
let sh = if w.shift.is_finite() { w.shift } else { 0.0 };
let a = [w.start[0] - ux * ext_start - uy * sh, w.start[1] - uy * ext_start + ux * sh];
let b = [w.end[0] + ux * ext_end - uy * sh, w.end[1] + uy * ext_end + ux * sh];
vec![[a[0] + nx, a[1] + ny], [b[0] + nx, b[1] + ny], [b[0] - nx, b[1] - ny], [a[0] - nx, a[1] - ny]]
}
@@ -185,7 +189,8 @@ pub fn auto_exterior_dimensions(walls: &[WallIn], openings: &[OpeningIn], scale_
continue; // Wand quer zu n
}
let t = if w.thickness.is_finite() && w.thickness > 0.0 { w.thickness } else { 0.3 };
let outer_s = dot(w.start, n) + t / 2.0;
let left = [-dy / len, dx / len];
let outer_s = dot(w.start, n) + (if w.shift.is_finite() { w.shift } else { 0.0 }) * dot(left, n) + t / 2.0;
let (ja, jb) = (dot(o.jamb_start, u), dot(o.jamb_end, u));
if !ja.is_finite() || !jb.is_finite() {
continue;
@@ -239,7 +244,7 @@ mod tests {
/// L-förmiger Grundriss aus 0.3-m-Wänden (Achsen).
fn l_walls() -> Vec<WallIn> {
let axis = [[0.0, 0.0], [10.0, 0.0], [10.0, 6.0], [4.0, 6.0], [4.0, 9.0], [0.0, 9.0]];
(0..axis.len()).map(|i| WallIn { start: axis[i], end: axis[(i + 1) % axis.len()], thickness: 0.3 }).collect()
(0..axis.len()).map(|i| WallIn { start: axis[i], end: axis[(i + 1) % axis.len()], thickness: 0.3, shift: 0.0 }).collect()
}
fn lengths(pts: &[Vec2]) -> Vec<f64> {
pts.windows(2).map(|w| (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1])).collect()
@@ -285,17 +290,36 @@ mod tests {
assert!((south.offset - 1.0).abs() < 1e-12);
}
/// Wand mit Referenzlinie links: die Achse liegt an der Innenkante, die Aussenmasse stimmen trotzdem.
#[test]
fn nicht_mittige_wand_misst_die_echte_flaeche() {
// Achse y = 0, Körper y 0 … 0.3 (shift +0.15), Öffnung 1 … 2 m.
let w = [WallIn { start: [0.0, 0.0], end: [5.0, 0.0], thickness: 0.3, shift: 0.15 }];
let o = OpeningIn { wall: 0, jamb_start: [1.0, 0.0], jamb_end: [2.0, 0.0] };
let dims = auto_exterior_dimensions(&w, &[o], 100.0);
let south = dims.iter().find(|d| d.side == 0 && d.chain == CHAIN_TOTAL).unwrap();
let north = dims.iter().find(|d| d.side == 2 && d.chain == CHAIN_TOTAL).unwrap();
// Masslinie Süd liegt 1.0 m (1:100) vor der Südfläche y = 0; Nord vor y = 0.3.
let south_y = south.pts[0][1] - south.offset * 1.0 * 0.0;
assert!((south_y - 0.0).abs() < 1e-6 || (south_y - 0.3).abs() < 1e-6, "{south_y}");
assert!((north.pts[0][1] - 0.3).abs() < 1e-6, "{:?}", north.pts);
assert!((south.pts[0][1] - 0.0).abs() < 1e-6, "{:?}", south.pts);
// Leibungen der Öffnung hängen an der Nordfläche (y = 0.3), nicht an y = 0.15.
let op = dims.iter().find(|d| d.side == 2 && d.chain == CHAIN_OPENINGS).unwrap();
assert!(op.src.iter().all(|q| (q[1] - 0.3).abs() < 1e-6), "{:?}", op.src);
}
#[test]
fn unsinn_ohne_panik() {
assert!(auto_exterior_dimensions(&[], &[], 100.0).is_empty());
let bad = [
WallIn { start: [f64::NAN, 0.0], end: [1.0, 0.0], thickness: 0.3 },
WallIn { start: [0.0, 0.0], end: [0.0, 0.0], thickness: 0.3 },
WallIn { start: [f64::NAN, 0.0], end: [1.0, 0.0], thickness: 0.3, shift: 0.0 },
WallIn { start: [0.0, 0.0], end: [0.0, 0.0], thickness: 0.3, shift: 0.0 },
];
let o = OpeningIn { wall: 7, jamb_start: [0.0, 0.0], jamb_end: [1.0, 0.0] };
assert!(auto_exterior_dimensions(&bad, &[o], f64::NAN).is_empty());
// Dicke NaN → 0.3; Öffnung mit NaN-Leibung wird übergangen.
let w = [WallIn { start: [0.0, 0.0], end: [5.0, 0.0], thickness: f64::NAN }];
let w = [WallIn { start: [0.0, 0.0], end: [5.0, 0.0], thickness: f64::NAN, shift: 0.0 }];
let o = OpeningIn { wall: 0, jamb_start: [f64::NAN, 0.0], jamb_end: [1.0, 0.0] };
let dims = auto_exterior_dimensions(&w, &[o], 0.0);
assert!(dims.iter().all(|d| d.chain != CHAIN_OPENINGS));
+183 -1
View File
@@ -961,6 +961,127 @@ fn dimension_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGe
}
}
// ── Achsraster ([112]) und Radius-/Bogenmass ([38]) ─────────────────────────
/// Geometrie des neuen Rasters: `at` (Ursprung), `xs`/`ys` (Feldweiten als Text), `radial`, `angle`
/// (Bogenmass), optional `extend`, `bubbles`, `levels`. `None` bei unlesbaren Feldweiten.
fn grid_geom(v: &Value) -> Option<Value> {
let radial = b_of(v, "radial");
let xs = crate::grid::parse_bays(s_of(v, "xs"))?;
let ys = crate::grid::parse_bays(s_of(v, "ys")).or_else(|| (!radial).then(Vec::new).filter(|_| s_of(v, "ys").trim().is_empty()))?;
let (a, b) = crate::grid::axes_from_bays(radial, &xs, &ys);
let list = |l: &[crate::model::GridAxis]| Value::Array(l.iter().map(|x| obj(vec![("label", s(&x.label)), ("pos", js_num(x.pos))])).collect());
let mut f = vec![("shape", s("grid")), ("origin", pt_val(v, "at")), ("angle", js_num(opt_n(v, "angle").unwrap_or(0.0))), ("a", list(&a)), ("b", list(&b))];
if radial {
f.push(("radial", Value::Bool(true)));
}
for k in ["extend", "bubbleMm"] {
if let Some(x) = opt_n(v, k) {
f.push((k, js_num(x)));
}
}
if matches!(s_of(v, "bubbles"), "start" | "end" | "both") {
f.push(("bubbles", s(s_of(v, "bubbles"))));
}
if let Some(l) = v.get("levels").filter(|l| l.as_array().is_some_and(|a| !a.is_empty())) {
f.push(("levels", l.clone()));
}
Some(obj(f))
}
/// Vorschau des Rasters am Cursor: Achsen als Linien, Ringe als Polygonzug.
fn grid_preview(v: &Value, pts: &[V], p: &mut Preview) {
let Some(at) = pts.first() else { return };
let mut v2 = v.clone();
v2["at"] = pv(*at);
let Some(g) = grid_geom(&v2).and_then(|g| serde_json::from_value::<crate::model::Drawing2DGeom>(g).ok()) else { return };
let Some(spec) = crate::grid::Spec::of(&g) else { return };
p.ok = true;
for ax in spec.axes() {
match ax.shape {
crate::grid::Shape::Line { a, b } => p.shapes.line(a, b),
crate::grid::Shape::Arc { c, r, a0, a1 } => {
let n = (((a1 - a0).abs() / (PI / 24.0)).ceil() as usize).clamp(2, 400);
let q: Vec<V> = (0..=n).map(|i| a0 + (a1 - a0) * i as f64 / n as f64).map(|t| (c.0 + r * jsnum::cos(t), c.1 + r * jsnum::sin(t))).collect();
p.shapes.poly_open(&q);
}
}
}
}
fn dim_kind(v: &Value) -> Option<crate::model::DimKind> {
use crate::model::DimKind;
match s_of(v, "kind") {
"radius" => Some(DimKind::Radius),
"diameter" => Some(DimKind::Diameter),
"arc" => Some(DimKind::Arc),
_ => None,
}
}
/// Toleranz beim Treffen eines Kreises/Bogens (Modell-Meter, `tol` der Anfrage).
fn round_tol(v: &Value) -> f64 {
opt_n(v, "tol").filter(|t| *t > 0.0).unwrap_or(0.15)
}
/// Radius-/Durchmesser-/Bogenlängen-Mass: Klicks auf dem Rand eines Kreises, Bogens oder einer
/// Bogenwand; Mittelpunkt und Randpunkte hängen daran (`refs`). Bogenlänge: `side` (Punkt der
/// Masslinie) oder `offset` bestimmt den Abstand vom Bogen.
fn dimround_ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
use crate::model::DimKind;
let Some(kind) = dim_kind(v) else { return Vec::new() };
let clicks: Vec<V> = arr(v.get("pts")).iter().map(pair).collect();
let lk = crate::document::Lookup::plain(root);
let Some((pts, refs)) = crate::dim_assoc::round_dimension(&lk, ctx.level, kind, &clicks, round_tol(v)) else { return Vec::new() };
let offset = match (kind, opt_p(v, "side")) {
(DimKind::Arc, Some(side)) => hypot2(side.0 - pts[0].0, side.1 - pts[0].1) - hypot2(pts[1].0 - pts[0].0, pts[1].1 - pts[0].1),
(DimKind::Arc, None) => opt_n(v, "offset").unwrap_or(0.5),
_ => 0.0,
};
let kind_s = match kind {
DimKind::Radius => "radius",
DimKind::Diameter => "diameter",
DimKind::Arc => "arc",
};
let geom = obj(vec![
("shape", s("dimension")),
("pts", pvs(&pts)),
("offset", js_num(offset)),
("kind", s(kind_s)),
("refs", serde_json::to_value(refs).unwrap_or(Value::Null)),
]);
add_drawing(v, ctx, ids, geom)
}
/// Vorschau: Radius-/Durchmesserlinie bzw. Bogen zwischen den Klicks (Cursor = letzter Punkt).
fn dimround_preview(root: &Map<String, Value>, v: &Value, ctx: &Ctx, pts: &[V], p: &mut Preview) {
use crate::model::DimKind;
let Some(kind) = dim_kind(v) else { return };
let lk = crate::document::Lookup::plain(root);
let tol = round_tol(v);
let arc_phase = kind == DimKind::Arc;
// Klickpunkte: bei der Bogenlänge die ersten zwei (Cursor als zweiter, solange er läuft).
let clicks: Vec<V> = if arc_phase { pts.iter().take(2).copied().collect() } else { pts.iter().take(1).copied().collect() };
let Some((q, _)) = crate::dim_assoc::round_dimension(&lk, ctx.level, kind, &clicks, tol).or_else(|| crate::dim_assoc::round_dimension(&lk, ctx.level, kind, &clicks[..1], tol).filter(|_| arc_phase)) else { return };
p.ok = true;
let c = q[0];
match kind {
DimKind::Radius => p.shapes.line(c, q[1]),
DimKind::Diameter => p.shapes.line((2.0 * c.0 - q[1].0, 2.0 * c.1 - q[1].1), q[1]),
DimKind::Arc => {
let r = hypot2(q[1].0 - c.0, q[1].1 - c.1);
let a0 = angle(c, q[1]);
let a1 = if q.len() > 2 { angle(c, q[2]) } else { a0 };
let sweep = (a1 - a0).rem_euclid(TAU);
let off = pts.get(2).map_or(0.0, |s| hypot2(s.0 - c.0, s.1 - c.1) - r);
let n = ((sweep / (PI / 24.0)).ceil() as usize).clamp(1, 400);
let poly: Vec<V> = (0..=n).map(|i| a0 + sweep * i as f64 / n as f64).map(|t| (c.0 + (r + off) * jsnum::cos(t), c.1 + (r + off) * jsnum::sin(t))).collect();
p.shapes.poly_open(&poly);
p.info.push(r * sweep);
}
}
}
/// Bemassungs-Vorschau. `phase` next: `pts` = Kette + roher Cursor → Kette bis zum (auf die Masslinie
/// projizierten) Cursor, `info = [cx, cy]`; offset: `pts` = Kette + Cursor (oder ohne → Abstand 0),
/// Hilfs- und Masslinien, `info = [Abstand, Summe]`.
@@ -1016,7 +1137,15 @@ fn auto_dims(root: &Map<String, Value>, ctx: &Ctx, prefix: &str, scale: f64) ->
let tid = field(w, "wallTypeId").and_then(Value::as_str);
let th = types.iter().find(|t| id_of(t) == tid).map_or(0.3, type_thickness);
let (a, b) = (p(w, "start"), p(w, "end"));
WallIn { start: [a.0, a.1], end: [b.0, b.1], thickness: th }
// Wandmitte gegenüber der Achse (Referenzlinie links/rechts bzw. -versatz, wie `dim_assoc`).
let half = th / 2.0;
let shift = match (field(w, "referenceOffset").and_then(Value::as_f64), field(w, "referenceLine").and_then(Value::as_str)) {
(Some(v), _) => v.clamp(-half, half),
(None, Some("left")) => half,
(None, Some("right")) => -half,
_ => 0.0,
};
WallIn { start: [a.0, a.1], end: [b.0, b.1], thickness: th, shift }
})
.collect();
let mut oin = Vec::new();
@@ -1154,6 +1283,11 @@ pub fn ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) ->
),
"pointmarker" => add_drawing(v, ctx, ids, obj(vec![("shape", s("pointmarker")), ("at", pt_val(v, "at"))])),
"block" => block_ops(v, ctx, ids),
"grid" => match grid_geom(v) {
Some(g) => add_drawing(v, ctx, ids, g),
None => Vec::new(),
},
"dimround" => dimround_ops(root, v, ctx, ids),
"dimension" => dimension_ops(root, v, ctx, ids),
"autodim" => autodim_ops(root, ctx),
_ => return None,
@@ -1227,6 +1361,8 @@ pub fn preview(root: &Map<String, Value>, v: &Value, ctx: &Ctx, pts: &[V], p: &m
}
}
"dimension" => dimension_preview(v, pts, p),
"grid" => grid_preview(v, pts, p),
"dimround" => dimround_preview(root, v, ctx, pts, p),
"autodim" => p.ok = !auto_dims(root, ctx, "autodim", 100.0).is_empty(),
_ => return false,
}
@@ -1282,6 +1418,52 @@ mod tests {
assert!((at.1 - (0.0 - 0.0035)).abs() < 1e-12);
}
/// [112] Befehl „Achsraster": Feldweiten als Text → Achsen 1, 2, 3 / A, B …; unlesbar → nichts.
#[test]
fn achsraster_befehl() {
let v = json!({"cmd": "grid", "at": {"x": 1, "y": 2}, "xs": "5 3x6", "ys": "4,5 4", "angle": 0, "bubbles": "end", "levels": ["L"]});
let o = ops(&Map::new(), &v, &ctx(), &mut IdGen::new("s")).unwrap();
let g = &o[0].to_json()["items"][0]["geom"];
assert_eq!(g["shape"], "grid");
assert_eq!(g["a"].as_array().unwrap().len(), 5);
assert_eq!(g["a"][4]["pos"], 23);
assert_eq!(g["b"][2]["label"], "C");
assert_eq!(g["b"][2]["pos"], 8.5);
assert_eq!(g["bubbles"], "end");
assert_eq!(g["origin"]["x"], 1);
assert!(serde_json::from_value::<crate::model::Drawing2DGeom>(g.clone()).is_ok());
// Ohne `angle` (Befehl aus der Hülle) gilt 0; leere Querachsen sind erlaubt.
let bare = json!({"cmd": "grid", "at": [0, 0], "xs": "5", "ys": ""});
let o2 = ops(&Map::new(), &bare, &ctx(), &mut IdGen::new("s")).unwrap();
assert_eq!(o2[0].to_json()["items"][0]["geom"]["angle"], 0);
let bad = json!({"cmd": "grid", "at": {"x": 0, "y": 0}, "xs": "x", "ys": ""});
assert!(ops(&Map::new(), &bad, &ctx(), &mut IdGen::new("s")).unwrap().is_empty());
// Vorschau am Cursor.
let mut p = Preview { shapes: Shapes::default(), ok: false, info: vec![] };
grid_preview(&v, &[(0.0, 0.0)], &mut p);
assert!(p.ok && !p.shapes.buf.is_empty());
}
/// [38] Befehl Radius/Bogenmass: trifft den Kreis, hängt Mittelpunkt und Rand an.
#[test]
fn rundmass_befehl() {
let root = json!({"drawings2d": [{"id": "K", "levelId": "L", "categoryCode": "20", "geom": {"shape": "circle", "center": {"x": 1, "y": 1}, "r": 2}}]});
let root = root.as_object().unwrap().clone();
let v = json!({"cmd": "dimround", "kind": "diameter", "pts": [[3.01, 1.0]]});
let o = ops(&root, &v, &ctx(), &mut IdGen::new("s")).unwrap();
let g = &o[0].to_json()["items"][0]["geom"];
assert_eq!(g["kind"], "diameter");
assert_eq!(g["refs"][0]["feature"], "center");
assert_eq!(g["refs"][1]["feature"], "rim");
let v = json!({"cmd": "dimround", "kind": "arc", "pts": [[3.0, 1.0], [1.0, 3.0]], "side": [1.0, 4.0]});
let g = &ops(&root, &v, &ctx(), &mut IdGen::new("s")).unwrap()[0].to_json()["items"][0]["geom"];
assert_eq!(g["pts"].as_array().unwrap().len(), 3);
assert!((g["offset"].as_f64().unwrap() - 1.0).abs() < 1e-9);
// Kein Kreis in der Nähe → nichts.
let far = json!({"cmd": "dimround", "kind": "radius", "pts": [[50.0, 50.0]]});
assert!(ops(&root, &far, &ctx(), &mut IdGen::new("s")).unwrap().is_empty());
}
#[test]
fn revisionswolke_beulen() {
assert!(revision_cloud(&[(0.0, 0.0)], false, 0.3).is_none());
+1
View File
@@ -733,6 +733,7 @@ fn map_points(g: &Value, f: &dyn Fn(P) -> P) -> Value {
"rect" | "image" => with_all(g, vec![("min", m("min")), ("max", m("max"))]),
"circle" | "arc" | "ellipse" => with(g, "center", m("center")),
"text" | "kote" | "detailref" | "scalebar" | "pointmarker" | "block" => with(g, "at", m("at")),
"grid" => with(g, "origin", m("origin")),
_ => g.clone(),
}
}
+27
View File
@@ -166,6 +166,21 @@ pub fn mv_geom(g: &Value, xf: &Xf) -> Option<Value> {
"circle" | "arc" | "ellipse" => with(g, "center", p("center")),
"bezier" | "spline" | "dimension" => with(g, "pts", ps("pts")),
"kote" | "detailref" | "scalebar" | "pointmarker" => with(g, "at", p("at")),
"grid" => {
// Ursprung und Richtung über einen mit abgebildeten Richtungspunkt; eine Spiegelung kehrt die
// Querachsen um (rechtwinklig: Y-Lagen, radial: Strahlwinkel).
let (ox, oy) = xy(field(g, "origin").unwrap_or(&Value::Null));
let ang = num_of(field(g, "angle"));
let no = xf.apply(ox, oy);
let nt = xf.apply(ox + jsnum::cos(ang), oy + jsnum::sin(ang));
let mut f = vec![("origin", pt(no.0, no.1)), ("angle", js_num(jsnum::atan2(nt.1 - no.1, nt.0 - no.0)))];
if xf.reverses() {
let key = if field(g, "radial").and_then(Value::as_bool) == Some(true) { "a" } else { "b" };
let neg = Value::Array(arr(field(g, key)).iter().map(|x| with(x, "pos", js_num(-num_of(field(x, "pos"))))).collect());
f.push((key, neg));
}
with_all(g, f)
}
"text" => {
// Hinweis-Ziel, Knicke und Pfadpunkte wandern mit.
let mut f = vec![("at", Some(p("at")))];
@@ -205,6 +220,18 @@ pub fn scale_geom(g: &Value, xf: &Xf, k: f64) -> Option<Value> {
"circle" | "arc" => with(&g, "r", times("r")),
"ellipse" => with_all(&g, vec![("rx", times("rx")), ("ry", times("ry"))]),
"dimension" => with(&g, "offset", times("offset")),
"grid" => {
let scaled = |key: &str| Value::Array(arr(field(&g, key)).iter().map(|x| with(x, "pos", js_num(num_of(field(x, "pos")) * k))).collect());
let radial = field(&g, "radial").and_then(Value::as_bool) == Some(true);
let mut f = vec![("b", scaled("b"))];
if !radial {
f.push(("a", scaled("a")));
}
if field(&g, "extend").is_some() {
f.push(("extend", times("extend")));
}
with_all(&g, f)
}
"text" => {
let mut f = vec![("height", times("height"))];
if field(&g, "width").is_some() {
+402 -34
View File
@@ -4,8 +4,12 @@
//! - **Anhängen** ([`attach`]): ein gefangener Punkt wird über Deckungsgleichheit (Toleranz [`TOL`])
//! einem Merkmal zugeordnet — Öffnungs-Leibung/-Mitte, Wandende, Wandecke (Schnitt zweier
//! Wandlinien), Punkt auf Wandachse/Schichtgrenze, Stütze (Mitte, Ecken, Kanten), Decken-/Dach-/
//! Raum-Umriss (Ecken, Kanten), 2D-Zeichnung (Eckpunkte, Mittelpunkte, Kanten). Bogenwände
//! werden nicht angehängt. Freie Klicks decken sich praktisch nie und bleiben frei.
//! Raum-Umriss (Ecken, Kanten), 2D-Zeichnung (Eckpunkte, Mittelpunkte, Kanten), Treppe (Umriss
//! und Podest: Ecken, Kanten), Bogenwand (Enden, Punkt auf Achse/Fläche, Mittelpunkt), Rasterachse
//! und Achsschnittpunkt ([112]). Freie Klicks decken sich praktisch nie und bleiben frei.
//! - **Radius/Durchmesser/Bogenlänge** ([`refs_for_round`]): Mittelpunkt und Punkte auf dem Rand
//! (`DimFeature::Rim`, Winkel) von 2D-Kreis, -Bogen oder Bogenwand; sie werden einzeln (ohne
//! Kettenprojektion) nachgeführt.
//! - **Nachführen** ([`sync_ops`]): nach jeder Benutzer-Änderung (`Document::commit`) löst der Kern
//! die Bezüge auf und schreibt die Lage in `pts` zurück (dieselbe Undo-Stufe). Damit lesen alle
//! Ableitungen (Plan, DXF, Griffe, Auswahl-Info) einfach `pts`, und `pts` ist immer die zuletzt
@@ -78,6 +82,7 @@ struct WallGeo {
offs: Vec<f64>,
total: f64,
arc: bool,
warc: Option<crate::wall_arc::WallArc>,
}
fn wall_geo(lk: &Lookup, w: &Value) -> Option<WallGeo> {
@@ -106,16 +111,40 @@ fn wall_geo(lk: &Lookup, w: &Value) -> Option<WallGeo> {
}
}
let arc = crate::wall_arc::is_arc_bulge(num(w.get("bulge")));
Some(WallGeo { a, b, offs, total, arc })
let warc = if arc { crate::wall_arc::WallArc::of(kernel2d::Vec2 { x: a.0, y: a.1 }, kernel2d::Vec2 { x: b.0, y: b.1 }, num(w.get("bulge"))) } else { None };
Some(WallGeo { a, b, offs, total, arc, warc })
}
impl WallGeo {
/// Linie `index` (fehlt = Achse): Anfang und Ende.
fn offset(&self, index: Option<u32>) -> Option<f64> {
match index {
None => Some(0.0),
Some(k) => self.offs.get(k as usize).copied(),
}
}
/// Punkt auf Linie `index` beim Anteil `t` (Bogenwand: entlang der Bogenlänge auf dem Versatzbogen).
fn point(&self, index: Option<u32>, t: f64) -> Option<P> {
let o = self.offset(index)?;
match &self.warc {
Some(w) => {
let q = w.point(t * w.length(), o);
Some((q.x, q.y))
}
None => {
let (a, b) = self.line(index)?;
Some(lerp(a, b, t))
}
}
}
/// Linie `index` (fehlt = Achse): Anfang und Ende (Bogenwand: Sehne zwischen den Bogenenden).
fn line(&self, index: Option<u32>) -> Option<(P, P)> {
let o = match index {
None => 0.0,
Some(k) => *self.offs.get(k as usize)?,
};
let o = self.offset(index)?;
if let Some(w) = &self.warc {
let (p0, p1) = (w.point(0.0, o), w.point(w.length(), o));
return Some(((p0.x, p0.y), (p1.x, p1.y)));
}
let n = left(unit(self.a, self.b)?);
Some((add(self.a, n, o), add(self.b, n, o)))
}
@@ -149,6 +178,32 @@ struct Shape {
pts: Vec<P>,
closed: bool,
center: Option<P>,
/// Weitere geschlossene Umrisse (Treppenpodest): Ecken/Kanten zählen nach denen von `pts` weiter.
more: Vec<Vec<P>>,
}
impl Shape {
fn new(pts: Vec<P>, closed: bool, center: Option<P>) -> Shape {
Shape { pts, closed, center, more: Vec::new() }
}
fn vertex(&self, mut i: usize) -> Option<P> {
if i < self.pts.len() {
return Some(self.pts[i]);
}
i -= self.pts.len();
for m in &self.more {
if i < m.len() {
return Some(m[i]);
}
i -= m.len();
}
None
}
fn vertex_count(&self) -> usize {
self.pts.len() + self.more.iter().map(Vec::len).sum::<usize>()
}
}
fn pts_list(v: Option<&Value>) -> Vec<P> {
@@ -163,35 +218,55 @@ fn column_shape(c: &Value) -> Option<Shape> {
let rot = num(c.get("rotation")).unwrap_or(0.0);
let (co, si) = (crate::jsnum::cos(rot), crate::jsnum::sin(rot));
let pts = [(-hw, -hd), (hw, -hd), (hw, hd), (-hw, hd)].iter().map(|&(x, y)| (at.0 + x * co - y * si, at.1 + x * si + y * co)).collect();
return Some(Shape { pts, closed: true, center: Some(at) });
return Some(Shape::new(pts, true, Some(at)));
}
Some(Shape { pts: Vec::new(), closed: false, center: Some(at) })
Some(Shape::new(Vec::new(), false, Some(at)))
}
fn drawing_shape(d: &Value) -> Option<Shape> {
let g = d.get("geom")?;
let p = |k: &str| pt(g.get(k));
Some(match str_of(g, "shape")? {
"line" => Shape { pts: vec![p("a")?, p("b")?], closed: false, center: None },
"polyline" => Shape { pts: pts_list(g.get("pts")), closed: g.get("closed").and_then(Value::as_bool).unwrap_or(false), center: None },
"line" => Shape::new(vec![p("a")?, p("b")?], false, None),
"polyline" => Shape::new(pts_list(g.get("pts")), g.get("closed").and_then(Value::as_bool).unwrap_or(false), None),
"rect" => {
let (lo, hi) = (p("min")?, p("max")?);
Shape { pts: vec![lo, (hi.0, lo.1), hi, (lo.0, hi.1)], closed: true, center: None }
Shape::new(vec![lo, (hi.0, lo.1), hi, (lo.0, hi.1)], true, None)
}
"circle" | "arc" | "ellipse" => Shape { pts: Vec::new(), closed: false, center: Some(p("center")?) },
"circle" | "arc" | "ellipse" => Shape::new(Vec::new(), false, Some(p("center")?)),
_ => return None,
})
}
/// Listen, in denen Ecke/Kante/Mitte ihr Element suchen (in dieser Reihenfolge).
const SHAPE_LISTS: [&str; 5] = ["columns", "ceilings", "roofs", "rooms", "drawings2d"];
const SHAPE_LISTS: [&str; 6] = ["columns", "ceilings", "roofs", "rooms", "drawings2d", "stairs"];
/// Treppe: Umriss (gerade/L: Aussenlinie; Wendel: die vier Ecken der Schliesslinien), Podest als
/// weiterer Umriss, Mittelpunkt nur bei der Wendel.
fn stair_shape(e: &Value) -> Option<Shape> {
let s: crate::model::Stair = serde_json::from_value(e.clone()).ok()?;
let sp = crate::stair::decode_params(&s.encode())?;
let o = kernel2d::stair_outline(&sp);
let t = |q: &kernel2d::Vec2| (q.x, q.y);
if let Some(poly) = o.polygon {
let mut sh = Shape::new(poly.iter().map(t).collect(), true, None);
if let Some(l) = kernel2d::stair_geometry(&sp, 3.0).landing {
sh.more.push(l.iter().map(t).collect());
}
return Some(sh);
}
let sp2 = o.spiral?;
let [(i0, o0), (i1, o1)] = sp2.lines;
Some(Shape::new(vec![t(&i0), t(&o0), t(&o1), t(&i1)], true, Some((sp2.arcs[0].0.x, sp2.arcs[0].0.y))))
}
fn shape_of(coll: &str, e: &Value) -> Option<Shape> {
match coll {
"columns" => column_shape(e),
"ceilings" | "roofs" => Some(Shape { pts: pts_list(e.get("outline")), closed: true, center: None }),
"rooms" => Some(Shape { pts: pts_list(e.get("boundary")), closed: true, center: None }),
"ceilings" | "roofs" => Some(Shape::new(pts_list(e.get("outline")), true, None)),
"rooms" => Some(Shape::new(pts_list(e.get("boundary")), true, None)),
"drawings2d" => drawing_shape(e),
"stairs" => stair_shape(e),
_ => None,
}
}
@@ -200,17 +275,66 @@ fn find_shape(lk: &Lookup, id: &str) -> Option<Shape> {
SHAPE_LISTS.iter().find_map(|c| lk.find(c, id).map(|e| (*c, e))).and_then(|(c, e)| shape_of(c, e))
}
fn edge(s: &Shape, i: usize) -> Option<(P, P)> {
let n = s.pts.len();
fn ring_edge(pts: &[P], closed: bool, i: usize) -> Option<(P, P)> {
let n = pts.len();
if i + 1 < n {
Some((s.pts[i], s.pts[i + 1]))
} else if s.closed && n > 2 && i + 1 == n {
Some((s.pts[i], s.pts[0]))
Some((pts[i], pts[i + 1]))
} else if closed && n > 2 && i + 1 == n {
Some((pts[i], pts[0]))
} else {
None
}
}
fn ring_edges(pts: &[P], closed: bool) -> usize {
if closed && pts.len() > 2 {
pts.len()
} else {
pts.len().saturating_sub(1)
}
}
fn edge(s: &Shape, mut i: usize) -> Option<(P, P)> {
let n = ring_edges(&s.pts, s.closed);
if i < n {
return ring_edge(&s.pts, s.closed, i);
}
i -= n;
for m in &s.more {
let k = ring_edges(m, true);
if i < k {
return ring_edge(m, true, i);
}
i -= k;
}
None
}
fn edge_count(s: &Shape) -> usize {
ring_edges(&s.pts, s.closed) + s.more.iter().map(|m| ring_edges(m, true)).sum::<usize>()
}
/// Rasterachse `index` des Rasters `id` und das Raster selbst.
fn with_grid<T>(lk: &Lookup, id: &str, f: impl FnOnce(&crate::grid::Spec) -> Option<T>) -> Option<T> {
let d = lk.find("drawings2d", id)?;
let g: crate::model::Drawing2DGeom = serde_json::from_value(d.get("geom")?.clone()).ok()?;
f(&crate::grid::Spec::of(&g)?)
}
/// Kreis/Bogen (2D-Zeichnung) oder Bogenwand-Schicht: Mittelpunkt, Radius.
fn round_of(lk: &Lookup, id: &str, index: Option<u32>) -> Option<(P, f64)> {
if let Some(d) = lk.find("drawings2d", id) {
let g = d.get("geom")?;
if matches!(str_of(g, "shape"), Some("circle" | "arc")) {
return Some((pt(g.get("center"))?, num(g.get("r"))?));
}
return None;
}
let g = wall_geo(lk, lk.find("walls", id)?)?;
let w = g.warc?;
Some(((w.center.x, w.center.y), w.radius_at(g.offset(index)?)))
}
/// Schnitt zweier unendlicher Geraden (parallel → `None`).
fn intersect(a: (P, P), b: (P, P)) -> Option<P> {
let r = sub(a.1, a.0);
@@ -229,17 +353,27 @@ fn intersect(a: (P, P), b: (P, P)) -> Option<P> {
pub fn resolve(lk: &Lookup, r: &DimRef) -> Option<P> {
let wall_line = |id: &str, idx: Option<u32>| -> Option<(P, P)> { wall_geo(lk, lk.find("walls", id)?)?.line(idx) };
let p = match r.feature {
DimFeature::Wall => {
let (a, b) = wall_line(&r.id, r.index)?;
lerp(a, b, r.t?)
}
DimFeature::Wall => wall_geo(lk, lk.find("walls", &r.id)?)?.point(r.index, r.t?)?,
DimFeature::Opening => opening_point(lk, lk.find("openings", &r.id)?, r.index?, r.index2)?,
DimFeature::Vertex => *find_shape(lk, &r.id)?.pts.get(r.index? as usize)?,
DimFeature::Vertex => find_shape(lk, &r.id)?.vertex(r.index? as usize)?,
DimFeature::Edge => {
let (a, b) = edge(&find_shape(lk, &r.id)?, r.index? as usize)?;
lerp(a, b, r.t?)
}
DimFeature::Center => find_shape(lk, &r.id)?.center?,
DimFeature::Center => match find_shape(lk, &r.id) {
Some(sh) => sh.center?,
None => {
let w = wall_geo(lk, lk.find("walls", &r.id)?)?.warc?;
(w.center.x, w.center.y)
}
},
DimFeature::Axis => with_grid(lk, &r.id, |g| g.point_at(r.index?, r.t?))?,
DimFeature::AxisCross => with_grid(lk, &r.id, |g| g.cross(r.index?, r.index2?))?,
DimFeature::Rim => {
let (c, rad) = round_of(lk, &r.id, r.index)?;
let a = r.t?;
(c.0 + rad * a.cos(), c.1 + rad * a.sin())
}
DimFeature::Intersection => intersect(wall_line(&r.id, r.index)?, wall_line(r.id2.as_deref()?, r.index2)?)?,
};
finite(p).then_some(p)
@@ -276,7 +410,6 @@ pub fn attach(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<DimRef> {
.iter()
.filter(|w| on_level(w, "floorId", level))
.filter_map(|w| Some((str_of(w, "id")?, wall_geo(lk, w)?)))
.filter(|(_, g)| !g.arc)
.collect();
// 1) Öffnungen: Leibungen und Mitte auf jeder Linie der Wirtswand.
for o in list(lk, "openings") {
@@ -300,9 +433,24 @@ pub fn attach(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<DimRef> {
}
}
}
// 2b) Bogenwände: Mittelpunkt, Punkt auf Achse/Schichtgrenze (Anteil der Bogenlänge).
for (id, g) in walls.iter().filter(|(_, g)| g.warc.is_some()) {
let Some(w) = &g.warc else { continue };
if dist((w.center.x, w.center.y), s) <= tol {
return Some(rf(id, DimFeature::Center));
}
let (ls, ln) = w.local(kernel2d::Vec2 { x: s.0, y: s.1 });
let len = w.length();
for (k, _, _) in g.lines() {
let Some(o) = g.offset(k) else { continue };
if (ln - o).abs() <= tol && ls >= -tol && ls <= len + tol {
return Some(DimRef { index: k, t: Some((ls / len).clamp(0.0, 1.0)), ..rf(id, DimFeature::Wall) });
}
}
}
// 3) Wandecken: auf den Linien zweier Wände (Verlängerung bis zur Wanddicke über das Ende).
let mut hits: Vec<(&str, Option<u32>, P, P, f64)> = Vec::new();
for (id, g) in &walls {
for (id, g) in walls.iter().filter(|(_, g)| !g.arc) {
let len = dist(g.a, g.b);
let m = (g.total.max(0.3) + tol) / len;
for (k, a, b) in g.lines() {
@@ -324,7 +472,7 @@ pub fn attach(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<DimRef> {
if let Some(h) = hits.iter().find(|h| (0.0..=1.0).contains(&h.4)) {
return Some(DimRef { index: h.1, t: Some(h.4), ..rf(h.0, DimFeature::Wall) });
}
// 5) Stützen, Decken, Dächer, Räume, 2D-Zeichnungen: Mitte, Ecken, Kanten.
// 5) Stützen, Decken, Dächer, Räume, 2D-Zeichnungen, Treppen: Mitte, Ecken, Kanten.
for coll in SHAPE_LISTS {
let key = if coll == "drawings2d" { "levelId" } else { "floorId" };
for e in list(lk, coll).iter().filter(|e| on_level(e, key, level)) {
@@ -332,10 +480,10 @@ pub fn attach(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<DimRef> {
if sh.center.is_some_and(|c| dist(c, s) <= tol) {
return Some(rf(id, DimFeature::Center));
}
if let Some(i) = sh.pts.iter().position(|p| dist(*p, s) <= tol) {
if let Some(i) = (0..sh.vertex_count()).find(|&i| sh.vertex(i).is_some_and(|p| dist(p, s) <= tol)) {
return Some(DimRef { index: Some(i as u32), ..rf(id, DimFeature::Vertex) });
}
for i in 0..sh.pts.len() {
for i in 0..edge_count(&sh) {
let Some((a, b)) = edge(&sh, i) else { continue };
if let Some((t, d)) = param(a, b, s) {
if d <= tol && (0.0..=1.0).contains(&t) {
@@ -345,9 +493,93 @@ pub fn attach(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<DimRef> {
}
}
}
// 6) Achsraster ([112]): Achsschnittpunkt, sonst Punkt auf einer Achse.
for d in list(lk, "drawings2d") {
let Some(id) = str_of(d, "id") else { continue };
let Some(g) = d.get("geom").filter(|g| str_of(g, "shape") == Some("grid")) else { continue };
let Ok(geom) = serde_json::from_value::<crate::model::Drawing2DGeom>(g.clone()) else { continue };
let Some(spec) = crate::grid::Spec::of(&geom) else { continue };
let visible = serde_json::from_value::<crate::model::Drawing2D>(d.clone()).map(|dd| crate::grid::visible_on(&dd, level)).unwrap_or(false);
if !visible {
continue;
}
let n = (spec.a.len() + spec.b.len()) as u32;
for i in 0..spec.a.len() as u32 {
for j in spec.a.len() as u32..n {
if spec.cross(i, j).is_some_and(|p| dist(p, s) <= tol) {
return Some(DimRef { index: Some(i), index2: Some(j), ..rf(id, DimFeature::AxisCross) });
}
}
}
for i in 0..n {
if let Some((t, d)) = spec.project(i, s) {
if d <= tol && (-1e-9..=1.0 + 1e-9).contains(&t) {
return Some(DimRef { index: Some(i), t: Some(t.clamp(0.0, 1.0)), ..rf(id, DimFeature::Axis) });
}
}
}
}
None
}
/// Rand-Bezug (Winkel `a`) auf dem Kreis/Bogen `id` ([38]).
fn rim(id: &str, index: Option<u32>, a: f64) -> DimRef {
DimRef { index, t: Some(a), ..rf(id, DimFeature::Rim) }
}
/// Kreis/Bogen (2D-Zeichnung des Geschosses) oder Bogenwand-Schicht, auf deren Rand `s` liegt
/// (Toleranz `tol`): Kennung, Schichtgrenze, Mittelpunkt, Radius.
pub fn find_round(lk: &Lookup, level: &str, s: P, tol: f64) -> Option<(String, Option<u32>, P, f64)> {
// Nächster Rand innerhalb der Toleranz (bei konzentrischen Kreisen/Schichten der genaueste).
let mut best: Option<(f64, (String, Option<u32>, P, f64))> = None;
let mut offer = |err: f64, hit: (String, Option<u32>, P, f64)| {
if err <= tol && best.as_ref().is_none_or(|(e, _)| err < *e) {
best = Some((err, hit));
}
};
for d in list(lk, "drawings2d").iter().filter(|d| on_level(d, "levelId", level)) {
let (Some(id), Some(g)) = (str_of(d, "id"), d.get("geom")) else { continue };
if !matches!(str_of(g, "shape"), Some("circle" | "arc")) {
continue;
}
let (Some(c), Some(r)) = (pt(g.get("center")), num(g.get("r"))) else { continue };
offer((dist(c, s) - r).abs(), (id.to_owned(), None, c, r));
}
for w in list(lk, "walls").iter().filter(|w| on_level(w, "floorId", level)) {
let (Some(id), Some(g)) = (str_of(w, "id"), wall_geo(lk, w)) else { continue };
let Some(arc) = g.warc else { continue };
let c = (arc.center.x, arc.center.y);
let mut ks: Vec<Option<u32>> = vec![None];
ks.extend((0..g.offs.len() as u32).map(Some));
for k in ks {
let Some(o) = g.offset(k) else { continue };
let r = arc.radius_at(o);
offer((dist(c, s) - r).abs(), (id.to_owned(), k, c, r));
}
}
best.map(|(_, h)| h)
}
/// Radius-/Durchmesser-/Bogenlängen-Bemassung ([38]): aus den Klickpunkten `clicks` (ein Punkt auf
/// dem Rand; bei der Bogenlänge Anfang und Ende) die Punkte `pts` (Mittelpunkt, Randpunkt[e]) und
/// ihre Bezüge. `None`, wenn kein Kreis/Bogen/Bogenwand getroffen wird.
pub fn round_dimension(lk: &Lookup, level: &str, kind: crate::model::DimKind, clicks: &[P], tol: f64) -> Option<(Vec<P>, Vec<Option<DimRef>>)> {
use crate::model::DimKind;
let first = *clicks.first()?;
let (id, idx, c, r) = find_round(lk, level, first, tol)?;
let ang = |p: P| (p.1 - c.1).atan2(p.0 - c.0);
let on_rim = |a: f64| (c.0 + r * a.cos(), c.1 + r * a.sin());
let a0 = ang(first);
let mut pts = vec![c, on_rim(a0)];
let mut refs = vec![Some(rf(&id, DimFeature::Center)), Some(rim(&id, idx, a0))];
if kind == DimKind::Arc {
let a1 = ang(*clicks.get(1)?);
pts.push(on_rim(a1));
refs.push(Some(rim(&id, idx, a1)));
}
Some((pts, refs))
}
/// Bezüge einer neuen Kette `pts`: je Punkt der erste Fangpunkt aus `snaps`, der auf ihn projiziert
/// (Kette = Gerade pts[0]→pts[1]) und an einem Merkmal hängt; `d` = Normalabstand Fangpunkt → Punkt.
/// `keep(i)` liefert einen schon bekannten Bezug (Ergänzen einer Kette). Kein Bezug → `None`.
@@ -411,6 +643,13 @@ pub fn resolve_chain(lk: &Lookup, pts: &[P], refs: &[Option<DimRef>]) -> (Vec<P>
(out, lost)
}
/// Punkte ohne Kettenprojektion (Radius-/Bogenmass): jeder hängende Punkt an seiner Lage.
fn resolve_each(lk: &Lookup, pts: &[P], refs: &[Option<DimRef>]) -> (Vec<P>, Vec<bool>) {
let q: Vec<Option<P>> = (0..pts.len()).map(|i| refs.get(i).and_then(Option::as_ref).and_then(|r| resolve(lk, r))).collect();
let lost = (0..refs.len()).map(|i| refs[i].is_some() && q.get(i).copied().flatten().is_none()).collect();
(pts.iter().zip(&q).map(|(p, n)| n.unwrap_or(*p)).collect(), lost)
}
fn refs_of(g: &Value) -> Option<Vec<Option<DimRef>>> {
let r = g.get("refs")?;
let refs: Vec<Option<DimRef>> = serde_json::from_value(r.clone()).ok()?;
@@ -441,7 +680,8 @@ pub fn sync_ops(lk: &Lookup) -> Vec<Op> {
if pts.len() != g.get("pts").and_then(Value::as_array).map_or(0, Vec::len) {
continue;
}
let (np, lost) = resolve_chain(lk, &pts, &refs);
let round = str_of(g, "kind").is_some();
let (np, lost) = if round { resolve_each(lk, &pts, &refs) } else { resolve_chain(lk, &pts, &refs) };
let moved = np.iter().zip(&pts).any(|(a, b)| dist(*a, *b) > MOVE_EPS);
let flags_changed = refs.iter().zip(&lost).any(|(r, l)| r.as_ref().is_some_and(|r| r.lost.unwrap_or(false) != *l));
if !moved && !flags_changed {
@@ -690,6 +930,134 @@ mod tests {
assert!(d.last_extra().is_empty());
}
fn grid_project() -> Map<String, Value> {
root(json!({
"drawings2d": [
{"id": "G", "type": "drawing2d", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0,
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 6}], "b": [{"label": "A", "pos": 0}, {"label": "B", "pos": 4}], "extend": 1}}
]
}))
}
/// [112] Rasterachsen: Punkt auf Achse, Achsschnittpunkt; die Bemassung folgt der verschobenen Achse.
#[test]
fn rasterachsen_bezuege_folgen_der_achse() {
let mut r = grid_project();
let lk = Lookup::plain(&r);
// Achsschnittpunkt 2/B (index 1 × index 3), Punkt auf Achse 1.
let cross = attach(&lk, "eg", (6.0, 4.0), TOL).unwrap();
assert_eq!((cross.feature, cross.index, cross.index2), (DimFeature::AxisCross, Some(1), Some(3)));
let on1 = attach(&lk, "eg", (0.0, 2.5), TOL).unwrap();
assert_eq!((on1.feature, on1.index), (DimFeature::Axis, Some(0)));
close(resolve(&lk, &on1).unwrap(), (0.0, 2.5));
// Bemassung zwischen Achse 1 und Achse 2 (Kette bei y = 1): Länge 6; Achse 2 nach x = 7.5 → 7.5.
let pts = [(0.0, 1.0), (6.0, 1.0)];
let refs = vec![attach(&lk, "eg", (0.0, 1.0), TOL), attach(&lk, "eg", (6.0, 1.0), TOL)];
assert!(refs.iter().all(|x| x.as_ref().is_some_and(|x| x.feature == DimFeature::Axis)));
set(&mut r, "drawings2d", "G", "geom", json!({"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0,
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 7.5}], "b": [{"label": "A", "pos": 0}, {"label": "B", "pos": 4}], "extend": 1}));
let (np, lost) = resolve_chain(&Lookup::plain(&r), &pts, &refs);
assert_eq!(lost, vec![false, false]);
close(np[0], (0.0, 1.0));
close(np[1], (7.5, 1.0));
// Raster gelöscht → ungültig.
r.insert("drawings2d".into(), json!([]));
assert!(resolve(&Lookup::plain(&r), refs[1].as_ref().unwrap()).is_none());
}
fn arc_project() -> Map<String, Value> {
root(json!({
"wallTypes": [{"id": "T", "layers": [{"thickness": 0.1}, {"thickness": 0.2}]}],
// Halbkreis: Mittelpunkt (5, 0), Achsradius 5, Scheitel (5, 5).
"walls": [{"id": "A", "floorId": "eg", "wallTypeId": "T", "start": {"x": 0, "y": 0}, "end": {"x": 10, "y": 0}, "bulge": 1}],
"drawings2d": [{"id": "K", "levelId": "eg", "geom": {"shape": "circle", "center": {"x": 30, "y": 0}, "r": 2}}]
}))
}
/// [38] Bogenwand: Enden, Punkt auf Achse/Fläche (Anteil der Bogenlänge), Mittelpunkt, Rand-Bezug.
#[test]
fn bogenwand_bezuege() {
let mut r = arc_project();
let lk = Lookup::plain(&r);
let apex = attach(&lk, "eg", (5.0, 5.0), TOL).unwrap();
assert_eq!((apex.feature, apex.index), (DimFeature::Wall, None));
assert!((apex.t.unwrap() - 0.5).abs() < 1e-9);
let face = attach(&lk, "eg", (5.0, 5.15), TOL).unwrap();
assert_eq!((face.feature, face.index), (DimFeature::Wall, Some(2)));
let end = attach(&lk, "eg", (10.0, 0.0), TOL).unwrap();
assert_eq!((end.feature, end.t), (DimFeature::Wall, Some(1.0)));
let centre = attach(&lk, "eg", (5.0, 0.0), TOL).unwrap();
assert_eq!(centre.feature, DimFeature::Center);
close(resolve(&lk, &centre).unwrap(), (5.0, 0.0));
close(resolve(&lk, &face).unwrap(), (5.0, 5.15));
// Rand-Bezug (Winkel 90°) auf der Fläche 2: Radius 5.15; Mittelpunkt und Winkel bleiben beim Strecken.
let rim_ref = DimRef { index: Some(2), t: Some(std::f64::consts::FRAC_PI_2), ..rf("A", DimFeature::Rim) };
close(resolve(&lk, &rim_ref).unwrap(), (5.0, 5.15));
// Wand verlängern (Ende x = 12 → Mittelpunkt (6, 0), Radius 6): Scheitel folgt.
set(&mut r, "walls", "A", "end", json!({"x": 12, "y": 0}));
let lk = Lookup::plain(&r);
close(resolve(&lk, &apex).unwrap(), (6.0, 6.0));
close(resolve(&lk, &centre).unwrap(), (6.0, 0.0));
}
/// [38] Radius-, Durchmesser- und Bogenlängen-Bemassung hängen an Kreis und Bogenwand.
#[test]
fn radius_und_bogenmass_assoziativ() {
use crate::model::DimKind;
let mut r = arc_project();
let lk = Lookup::plain(&r);
let (pts, refs) = round_dimension(&lk, "eg", DimKind::Radius, &[(30.0, 2.0)], 0.1).unwrap();
close(pts[0], (30.0, 0.0));
close(pts[1], (30.0, 2.0));
assert_eq!(refs[0].as_ref().unwrap().feature, DimFeature::Center);
// Kreis verschieben und vergrössern → Mittelpunkt und Randpunkt folgen (ohne Kettenprojektion).
set(&mut r, "drawings2d", "K", "geom", json!({"shape": "circle", "center": {"x": 40, "y": 5}, "r": 3}));
let (np, lost) = resolve_each(&Lookup::plain(&r), &pts, &refs);
assert_eq!(lost, vec![false, false]);
close(np[0], (40.0, 5.0));
close(np[1], (40.0, 8.0));
// Bogenlänge auf der Aussenfläche der Bogenwand (Radius 5.15): Viertelkreis von 90° bis 0°.
let lk = Lookup::plain(&r);
let (pts, refs) = round_dimension(&lk, "eg", DimKind::Arc, &[(5.0, 5.15), (5.15, 0.0)], 0.04).unwrap();
assert_eq!(pts.len(), 3);
close(pts[0], (5.0, 0.0));
assert_eq!(refs[1].as_ref().unwrap().index, Some(2));
// Nichts getroffen.
assert!(round_dimension(&lk, "eg", DimKind::Radius, &[(100.0, 100.0)], 0.1).is_none());
}
/// [38] Treppe: Umriss-Ecken/-Kanten und Podest-Kanten der L-Treppe sind anhängbar.
#[test]
fn treppe_bezuege() {
let stair = |shape: &str| json!({"id": "S", "type": "stair", "floorId": "eg", "categoryCode": "20", "shape": shape,
"start": {"x": 0, "y": 0}, "dir": {"x": 1, "y": 0}, "runLength": 3, "run2Length": 2, "turn": 1, "width": 1, "stepCount": 16});
let r = root(json!({"stairs": [stair("straight")]}));
let lk = Lookup::plain(&r);
let sh = find_shape(&lk, "S").unwrap();
assert_eq!(sh.pts.len(), 4);
// Eck 0 und Mitte der Kante 1 (Auftrittsende) hängen an und lösen auf.
let v0 = sh.pts[0];
let rv = attach(&lk, "eg", v0, TOL).unwrap();
assert_eq!((rv.feature, rv.id.as_str(), rv.index), (DimFeature::Vertex, "S", Some(0)));
let (a, b) = edge(&sh, 1).unwrap();
let mid = lerp(a, b, 0.5);
let re = attach(&lk, "eg", mid, TOL).unwrap();
assert_eq!((re.feature, re.index), (DimFeature::Edge, Some(1)));
close(resolve(&lk, &re).unwrap(), mid);
// L-Treppe: zusätzlich Podest-Ecken und -Kanten (Indizes nach dem Umriss).
let r = root(json!({"stairs": [stair("L")]}));
let lk = Lookup::plain(&r);
let sh = find_shape(&lk, "S").unwrap();
assert_eq!(sh.pts.len(), 6);
assert_eq!(sh.more.len(), 1);
let n = sh.pts.len();
let landing_corner = sh.vertex(n).unwrap();
let rl = attach(&lk, "eg", landing_corner, TOL).unwrap();
assert_eq!(rl.feature, DimFeature::Vertex);
close(resolve(&lk, &rl).unwrap(), landing_corner);
assert!(edge_count(&sh) > n);
}
#[test]
fn befehl_bemassung_haengt_gefangene_punkte_an() {
let r = project();
+1 -1
View File
@@ -30,7 +30,7 @@ fn shift_geom(g: &mut Drawing2DGeom, dx: f64, dy: f64) {
*max = shift(*max, dx, dy);
}
Circle { center, .. } | Arc { center, .. } | Ellipse { center, .. } => *center = shift(*center, dx, dy),
Kote { at, .. } | Detailref { at, .. } | Scalebar { at, .. } | Pointmarker { at } | Block { at, .. } => *at = shift(*at, dx, dy),
Grid { origin: at, .. } | Kote { at, .. } | Detailref { at, .. } | Scalebar { at, .. } | Pointmarker { at } | Block { at, .. } => *at = shift(*at, dx, dy),
Text { at, leader_target, leader_bend_points, path_pts, .. } => {
*at = shift(*at, dx, dy);
if let Some(t) = leader_target {
+1
View File
@@ -63,6 +63,7 @@ fn shift_geom(g: &Value, dx: f64, dy: f64) -> Value {
"rect" | "image" => shift_pts_fields(&mut m, &["min", "max"], dx, dy, &[]),
"circle" | "arc" | "ellipse" => shift_pts_fields(&mut m, &["center"], dx, dy, &[]),
"kote" | "detailref" | "scalebar" | "pointmarker" | "block" => shift_pts_fields(&mut m, &["at"], dx, dy, &[]),
"grid" => shift_pts_fields(&mut m, &["origin"], dx, dy, &[]),
"text" => {
shift_pts_fields(&mut m, &["at"], dx, dy, &[]);
if truthy(g.get("leaderTarget")) {
+466
View File
@@ -0,0 +1,466 @@
//! Achsraster ([112]): Geometrie der Rasterachsen, Achsblasen, Fangpunkte und Schnitt-/Ansichtslinien.
//!
//! Das Raster ist eine 2D-Zeichnung (`Drawing2DGeom::Grid`, Auswahl/Verschieben/Kopieren/Ebenen wie
//! jede Zeichnung). Rechtwinklig: `a` = Achsen parallel zur lokalen Y-Achse (X = `pos`), `b` = Achsen
//! parallel zur lokalen X-Achse (Y = `pos`). Radial: `a` = Strahlen (`pos` = Grad gegen `angle`),
//! `b` = Ringe (`pos` = Radius). Die Achsen tragen fortlaufende Indizes: erst `a`, dann `b`.
use crate::model::{Drawing2D, Drawing2DGeom, GridAxis, GridBubbles};
pub type P = (f64, f64);
/// Überstand der Achsen über die äusserste Querachse (Meter).
pub const DEFAULT_EXTEND: f64 = 1.5;
/// Blasen-Durchmesser (Papier-mm).
pub const DEFAULT_BUBBLE_MM: f64 = 8.0;
/// Verlauf einer Achse: Strecke oder Kreisbogen (gegen den Uhrzeigersinn von `a0` nach `a1`).
#[derive(Clone, Debug, PartialEq)]
pub enum Shape {
Line { a: P, b: P },
Arc { c: P, r: f64, a0: f64, a1: f64 },
}
/// Eine Rasterachse.
#[derive(Clone, Debug, PartialEq)]
pub struct Axis {
pub index: u32,
pub label: String,
pub shape: Shape,
/// Blasen an Anfang/Ende: Endpunkt der Achse und Richtung nach aussen.
pub bubbles: [Option<(P, P)>; 2],
}
/// Parameter eines Rasters.
pub struct Spec<'a> {
pub origin: P,
pub angle: f64,
pub radial: bool,
pub a: &'a [GridAxis],
pub b: &'a [GridAxis],
pub extend: f64,
pub bubbles: GridBubbles,
}
impl<'a> Spec<'a> {
/// Raster einer Zeichnung (`None`, wenn sie keines ist).
pub fn of(g: &'a Drawing2DGeom) -> Option<Spec<'a>> {
let Drawing2DGeom::Grid { origin, angle, radial, a, b, extend, bubbles, .. } = g else { return None };
Some(Spec {
origin: (origin.x, origin.y),
angle: *angle,
radial: *radial == Some(true),
a,
b,
extend: extend.filter(|e| e.is_finite() && *e >= 0.0).unwrap_or(DEFAULT_EXTEND),
bubbles: bubbles.unwrap_or(GridBubbles::Both),
})
}
fn world(&self, x: f64, y: f64) -> P {
let (s, c) = self.angle.sin_cos();
(self.origin.0 + x * c - y * s, self.origin.1 + x * s + y * c)
}
fn dir(&self, x: f64, y: f64) -> P {
let (s, c) = self.angle.sin_cos();
(x * c - y * s, x * s + y * c)
}
fn span(list: &[GridAxis]) -> (f64, f64) {
let it = list.iter().map(|g| g.pos).filter(|p| p.is_finite());
let lo = it.clone().fold(f64::INFINITY, f64::min);
let hi = it.fold(f64::NEG_INFINITY, f64::max);
if lo > hi {
(0.0, 0.0)
} else {
(lo, hi)
}
}
fn ray_angle(&self, pos: f64) -> f64 {
self.angle + pos.to_radians()
}
/// Alle Achsen (Index: `a` zuerst, dann `b`).
pub fn axes(&self) -> Vec<Axis> {
let want = |start: bool| match self.bubbles {
GridBubbles::Both => true,
GridBubbles::Start => start,
GridBubbles::End => !start,
};
let mut out = Vec::with_capacity(self.a.len() + self.b.len());
let ext = self.extend;
if !self.radial {
let (y0, y1) = Self::span(self.b);
let (x0, x1) = Self::span(self.a);
for (i, g) in self.a.iter().enumerate() {
let (p0, p1) = (self.world(g.pos, y0 - ext), self.world(g.pos, y1 + ext));
let (d0, d1) = (self.dir(0.0, -1.0), self.dir(0.0, 1.0));
out.push(Axis {
index: i as u32,
label: g.label.clone(),
shape: Shape::Line { a: p0, b: p1 },
bubbles: [want(true).then_some((p0, d0)), want(false).then_some((p1, d1))],
});
}
for (j, g) in self.b.iter().enumerate() {
let (p0, p1) = (self.world(x0 - ext, g.pos), self.world(x1 + ext, g.pos));
let (d0, d1) = (self.dir(-1.0, 0.0), self.dir(1.0, 0.0));
out.push(Axis {
index: (self.a.len() + j) as u32,
label: g.label.clone(),
shape: Shape::Line { a: p0, b: p1 },
bubbles: [want(true).then_some((p0, d0)), want(false).then_some((p1, d1))],
});
}
return out;
}
// Radial: Strahlen vom Mittelpunkt bis zum grössten Ring + Überstand, Ringe zwischen den Strahlen.
let (_, rmax) = Self::span(self.b);
for (i, g) in self.a.iter().enumerate() {
let th = self.ray_angle(g.pos);
let u = (th.cos(), th.sin());
let end = (self.origin.0 + u.0 * (rmax + ext), self.origin.1 + u.1 * (rmax + ext));
out.push(Axis {
index: i as u32,
label: g.label.clone(),
shape: Shape::Line { a: self.origin, b: end },
bubbles: [None, (self.bubbles != GridBubbles::Start).then_some((end, u))],
});
}
let (t0, t1) = Self::span(self.a);
let (t0, t1) = (self.ray_angle(t0), self.ray_angle(t1));
for (j, g) in self.b.iter().enumerate() {
let r = g.pos;
let full = self.a.len() < 2 || t1 - t0 >= std::f64::consts::TAU - 1e-9 || r <= 1e-9;
let (a0, a1) = if full {
(self.angle, self.angle + std::f64::consts::TAU)
} else {
let da = (ext / r).min((std::f64::consts::TAU - (t1 - t0)) / 2.0);
(t0 - da, t1 + da)
};
let at = |t: f64| (self.origin.0 + r * t.cos(), self.origin.1 + r * t.sin());
let tan = |t: f64, s: f64| (-t.sin() * s, t.cos() * s);
out.push(Axis {
index: (self.a.len() + j) as u32,
label: g.label.clone(),
shape: Shape::Arc { c: self.origin, r, a0, a1 },
bubbles: [
(!full && want(true)).then(|| (at(a0), tan(a0, -1.0))),
(if full { self.bubbles != GridBubbles::Start } else { want(false) }).then(|| (at(a1), tan(a1, 1.0))),
],
});
}
out
}
/// Schnittpunkte der Achsen: rechtwinklig `a` × `b`, radial Strahl × Ring.
pub fn crossings(&self) -> Vec<P> {
let mut out = Vec::new();
for i in 0..self.a.len() {
for j in 0..self.b.len() {
if let Some(p) = self.cross(i as u32, (self.a.len() + j) as u32) {
out.push(p);
}
}
}
out
}
/// Schnittpunkt zweier Achsen (Reihenfolge egal); gleiche Familie → `None`.
pub fn cross(&self, i: u32, j: u32) -> Option<P> {
let na = self.a.len() as u32;
let (i, j) = if i < na && j >= na { (i, j) } else if j < na && i >= na { (j, i) } else { return None };
let (ga, gb) = (self.a.get(i as usize)?, self.b.get((j - na) as usize)?);
let p = if self.radial {
let th = self.ray_angle(ga.pos);
(self.origin.0 + gb.pos * th.cos(), self.origin.1 + gb.pos * th.sin())
} else {
self.world(ga.pos, gb.pos)
};
(p.0.is_finite() && p.1.is_finite()).then_some(p)
}
/// Punkt auf Achse `index` beim Anteil `t` (0 = Anfang, 1 = Ende).
pub fn point_at(&self, index: u32, t: f64) -> Option<P> {
let ax = self.axes().into_iter().find(|a| a.index == index)?;
let p = match ax.shape {
Shape::Line { a, b } => (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t),
Shape::Arc { c, r, a0, a1 } => {
let th = a0 + (a1 - a0) * t;
(c.0 + r * th.cos(), c.1 + r * th.sin())
}
};
(p.0.is_finite() && p.1.is_finite()).then_some(p)
}
/// Anteil `t` des Punkts `s` auf der Achse und sein Abstand zu ihr (nächster Punkt der Achse).
pub fn project(&self, index: u32, s: P) -> Option<(f64, f64)> {
let ax = self.axes().into_iter().find(|a| a.index == index)?;
match ax.shape {
Shape::Line { a, b } => {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let l2 = dx * dx + dy * dy;
(l2 > 1e-18).then(|| {
let t = ((s.0 - a.0) * dx + (s.1 - a.1) * dy) / l2;
let q = (a.0 + dx * t, a.1 + dy * t);
(t, (s.0 - q.0).hypot(s.1 - q.1))
})
}
Shape::Arc { c, r, a0, a1 } => {
let th = (s.1 - c.1).atan2(s.0 - c.0);
let sweep = a1 - a0;
let mut rel = (th - a0).rem_euclid(std::f64::consts::TAU);
if rel > sweep.abs() + 1e-9 {
// ausserhalb des Bogens: zum näheren Ende
rel = if rel - sweep.abs() < std::f64::consts::TAU - rel { sweep.abs() } else { 0.0 };
}
(sweep.abs() > 1e-12).then(|| (rel / sweep.abs(), ((s.0 - c.0).hypot(s.1 - c.1) - r).abs()))
}
}
}
}
/// Feldweiten aus Text: Zahlen, getrennt durch Leerzeichen/`;` (Komma als Dezimalzeichen), `N*W` oder
/// `NxW` = N Felder zu W. Nur endliche Werte > 0, höchstens 200 Felder.
pub fn parse_bays(text: &str) -> Option<Vec<f64>> {
let mut out = Vec::new();
for tok in text.split(|c: char| c.is_whitespace() || c == ';').filter(|t| !t.is_empty()) {
let tok = tok.replace(',', ".");
let (n, w) = match tok.split_once(['x', 'X', '*']) {
Some((n, w)) => (n.parse::<usize>().ok()?, w.parse::<f64>().ok()?),
None => (1, tok.parse::<f64>().ok()?),
};
if !(w.is_finite() && w > 0.0) || n == 0 || out.len() + n > 200 {
return None;
}
out.extend(std::iter::repeat(w).take(n));
}
(!out.is_empty()).then_some(out)
}
/// Beschriftung `i` (0-basiert) als Buchstaben A … Z, AA, AB … (ohne I und O wie im Hochbau üblich).
pub fn letter_label(mut i: usize) -> String {
const L: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ";
let mut s = Vec::new();
loop {
s.push(L[i % L.len()]);
if i < L.len() {
break;
}
i = i / L.len() - 1;
}
s.reverse();
String::from_utf8(s).unwrap_or_default()
}
/// Achsen aus Feldweiten: rechtwinklig a = 1, 2, 3 … bei 0, Σ…; b = A, B, C … ebenso. Radial: a =
/// Strahlen (Winkel in Grad ab 0), b = Ringe (Radien = laufende Summe, der erste Ring beim ersten Mass).
pub fn axes_from_bays(radial: bool, xs: &[f64], ys: &[f64]) -> (Vec<GridAxis>, Vec<GridAxis>) {
let cum = |w: &[f64], zero: bool| {
let mut acc = 0.0;
let mut out = Vec::new();
if zero {
out.push(0.0);
}
for v in w {
acc += v;
out.push(acc);
}
out
};
let a = cum(xs, true).iter().enumerate().map(|(i, p)| GridAxis { label: (i + 1).to_string(), pos: *p }).collect();
let b = cum(ys, !radial).iter().enumerate().map(|(i, p)| GridAxis { label: letter_label(i), pos: *p }).collect();
(a, b)
}
/// Achsen als Punktfolgen für die 3D-Spur (Bögen in 7.5°-Schritten).
pub fn polylines_3d(spec: &Spec) -> Vec<Vec<P>> {
spec.axes()
.into_iter()
.map(|ax| match ax.shape {
Shape::Line { a, b } => vec![a, b],
Shape::Arc { c, r, a0, a1 } => {
let n = (((a1 - a0).abs() / (std::f64::consts::PI / 24.0)).ceil() as usize).clamp(2, 400);
(0..=n).map(|i| a0 + (a1 - a0) * i as f64 / n as f64).map(|t| (c.0 + r * t.cos(), c.1 + r * t.sin())).collect()
}
})
.collect()
}
/// Wird das Raster `d` im Geschoss `level` gezeigt? (`levels` fehlt/leer = in allen Geschossen.)
pub fn visible_on(d: &Drawing2D, level: &str) -> bool {
match &d.geom {
Drawing2DGeom::Grid { levels: Some(l), .. } if !l.is_empty() => l.iter().any(|x| x == level),
Drawing2DGeom::Grid { .. } => true,
_ => d.level_id == level,
}
}
/// Bildmass der Blase (Durchmesser, Modell-Meter) aus Papier-mm und Massstab.
pub fn bubble_diameter(mm: Option<f64>, scale: f64) -> f64 {
mm.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(DEFAULT_BUBBLE_MM) * scale / 1000.0
}
/// Senkrechte Achsen eines Schnitts/einer Ansicht: Raster-Achsen (nur Strecken) als (Beschriftung,
/// Lage entlang der Schnittlinien-Achse u). `origin`/`dir` = Schnittlinie (Einheitsvektor `dir`).
/// Schnitt (`projected` false): die Achse muss die Schnittebene innerhalb ihrer Länge schneiden.
/// Ansicht (`projected` true): Achsen, die (bis 5°) senkrecht auf der Ansichtsebene stehen, erscheinen
/// unabhängig von ihrer Länge an der Stelle, an der ihre Verlängerung die Ebene trifft.
pub fn section_axes(spec: &Spec, origin: P, dir: P, projected: bool) -> Vec<(String, f64)> {
let mut out = Vec::new();
for ax in spec.axes() {
let Shape::Line { a, b } = ax.shape else { continue };
let (rx, ry) = (b.0 - a.0, b.1 - a.1);
let den = dir.0 * ry - dir.1 * rx;
let slope = if projected { 0.996 } else { 1e-9 };
if den.abs() < slope * rx.hypot(ry).max(1e-12) {
continue;
}
// Schnitt Gerade origin+u*dir mit der Achsstrecke a+t*r.
let (qx, qy) = (a.0 - origin.0, a.1 - origin.1);
let t = (qx * dir.1 - qy * dir.0) / den;
if !projected && !(-1e-9..=1.0 + 1e-9).contains(&t) {
continue;
}
let u = (qx * ry - qy * rx) / den;
out.push((ax.label.clone(), u));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::Vec2;
fn ax(l: &str, p: f64) -> GridAxis {
GridAxis { label: l.into(), pos: p }
}
fn ortho() -> Drawing2DGeom {
Drawing2DGeom::Grid {
origin: Vec2 { x: 10.0, y: 20.0 },
angle: 0.0,
radial: None,
a: vec![ax("1", 0.0), ax("2", 4.0), ax("3", 10.0)],
b: vec![ax("A", 0.0), ax("B", 5.0)],
extend: Some(2.0),
bubbles: None,
bubble_mm: None,
levels: None,
show_3d: None,
}
}
#[test]
fn unregelmaessiger_raster_achsen_und_ueberstand() {
let g = ortho();
let s = Spec::of(&g).unwrap();
let axes = s.axes();
assert_eq!(axes.len(), 5);
// Achse "2": senkrecht bei x = 14, von y = 18 bis 27.
assert_eq!(axes[1].shape, Shape::Line { a: (14.0, 18.0), b: (14.0, 27.0) });
// Achse "B": waagrecht bei y = 25, von x = 8 bis 22.
assert_eq!(axes[4].shape, Shape::Line { a: (8.0, 25.0), b: (22.0, 25.0) });
// Blasen an beiden Enden, Richtung nach aussen.
assert_eq!(axes[1].bubbles[0], Some(((14.0, 18.0), (0.0, -1.0))));
assert_eq!(axes[1].bubbles[1], Some(((14.0, 27.0), (0.0, 1.0))));
assert_eq!(s.crossings().len(), 6);
assert_eq!(s.cross(4, 1), Some((14.0, 25.0)));
assert_eq!(s.cross(0, 1), None);
}
#[test]
fn gedrehtes_raster_und_blasenseite() {
let mut g = ortho();
if let Drawing2DGeom::Grid { angle, bubbles, .. } = &mut g {
*angle = std::f64::consts::FRAC_PI_2;
*bubbles = Some(GridBubbles::End);
}
let s = Spec::of(&g).unwrap();
let p = s.cross(1, 4).unwrap(); // Achse 2 x B: lokal (4, 5) -> (10 - 5, 20 + 4)
assert!((p.0 - 5.0).abs() < 1e-12 && (p.1 - 24.0).abs() < 1e-12);
let a = &s.axes()[0];
assert!(a.bubbles[0].is_none() && a.bubbles[1].is_some());
}
#[test]
fn radial_strahlen_ringe() {
let g = Drawing2DGeom::Grid {
origin: Vec2 { x: 0.0, y: 0.0 },
angle: 0.0,
radial: Some(true),
a: vec![ax("1", 0.0), ax("2", 90.0)],
b: vec![ax("A", 3.0), ax("B", 6.0)],
extend: Some(1.0),
bubbles: None,
bubble_mm: None,
levels: None,
show_3d: None,
};
let s = Spec::of(&g).unwrap();
let axes = s.axes();
assert_eq!(axes.len(), 4);
match axes[0].shape {
Shape::Line { b, .. } => assert!((b.0 - 7.0).abs() < 1e-12 && b.1.abs() < 1e-12),
_ => panic!(),
}
let p = s.cross(1, 3).unwrap();
assert!(p.0.abs() < 1e-12 && (p.1 - 6.0).abs() < 1e-12);
match axes[2].shape {
Shape::Arc { a0, a1, r, .. } => {
assert_eq!(r, 3.0);
assert!(a0 < 0.0 && a1 > std::f64::consts::FRAC_PI_2);
}
_ => panic!(),
}
// Projektion auf den Ring.
let (t, d) = s.project(2, (0.0, 3.5)).unwrap();
assert!((d - 0.5).abs() < 1e-9 && t > 0.0 && t < 1.0);
}
#[test]
fn feldweiten_und_beschriftung() {
assert_eq!(parse_bays("5 4,5 3x6"), Some(vec![5.0, 4.5, 6.0, 6.0, 6.0]));
assert_eq!(parse_bays("2*3.2; 4"), Some(vec![3.2, 3.2, 4.0]));
assert_eq!(parse_bays(""), None);
assert_eq!(parse_bays("5 -1"), None);
assert_eq!(parse_bays("abc"), None);
assert_eq!(parse_bays("0x5"), None);
assert_eq!((letter_label(0), letter_label(7), letter_label(8), letter_label(23), letter_label(24)), ("A".into(), "H".into(), "J".into(), "Z".into(), "AA".into()));
let (a, b) = axes_from_bays(false, &[5.0, 3.0], &[4.0]);
assert_eq!(a.iter().map(|x| (x.label.as_str(), x.pos)).collect::<Vec<_>>(), [("1", 0.0), ("2", 5.0), ("3", 8.0)]);
assert_eq!(b.iter().map(|x| (x.label.as_str(), x.pos)).collect::<Vec<_>>(), [("A", 0.0), ("B", 4.0)]);
// Radial: Ringe ohne Radius 0.
let (_, rings) = axes_from_bays(true, &[45.0], &[2.0, 3.0]);
assert_eq!(rings.iter().map(|x| x.pos).collect::<Vec<_>>(), [2.0, 5.0]);
}
#[test]
fn sichtbarkeit_je_geschoss() {
let mut d = Drawing2D { level_id: "eg".into(), geom: ortho(), ..Default::default() };
assert!(visible_on(&d, "og") && visible_on(&d, "eg"));
if let Drawing2DGeom::Grid { levels, .. } = &mut d.geom {
*levels = Some(vec!["eg".into()]);
}
assert!(visible_on(&d, "eg") && !visible_on(&d, "og"));
}
#[test]
fn schnittachsen_quer_zur_schnittlinie() {
let g = ortho();
let s = Spec::of(&g).unwrap();
// Schnitt entlang +x bei y = 22: schneidet die senkrechten Achsen 1, 2, 3 bei u = 0, 4, 10 (ab x = 10).
let r = section_axes(&s, (10.0, 22.0), (1.0, 0.0), false);
let us: Vec<f64> = r.iter().map(|x| x.1).collect();
assert_eq!(r.len(), 3);
assert!((us[0]).abs() < 1e-9 && (us[1] - 4.0).abs() < 1e-9 && (us[2] - 10.0).abs() < 1e-9);
// Ausserhalb der Achslänge: nichts.
assert!(section_axes(&s, (10.0, 40.0), (1.0, 0.0), false).is_empty());
// Ansicht von aussen (Ebene bei y = 40): die senkrechten Achsen erscheinen trotzdem, die waagrechten nicht.
let v = section_axes(&s, (10.0, 40.0), (1.0, 0.0), true);
assert_eq!(v.iter().map(|x| x.0.as_str()).collect::<Vec<_>>(), ["1", "2", "3"]);
}
}
+45
View File
@@ -613,6 +613,11 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option<Val
let ng = with(g, "pts", replace_at(pts, index, &p));
return Some(with_geom(d, crate::dim_assoc::without_ref(&ng, index_in(index, n))));
}
if index == n as f64 && field(g, "kind").and_then(Value::as_str) == Some("arc") && n >= 2 {
// Bogenlängen-Mass: Abstand der Masslinie vom Bogen (radial).
let (c, p0) = (xy(&pts[0]), xy(&pts[1]));
return set("offset", js_num(hypot2(x - c.0, y - c.1) - hypot2(p0.0 - c.0, p0.1 - c.1)));
}
if index == n as f64 {
// Griff auf der Masslinie: nur `offset` (Normalabstand zur Punktreihe).
let (a, b) = (xy(pts.first()?), xy(pts.last()?));
@@ -698,6 +703,33 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64) -> Option<Val
set("at", p)
}
"kote" | "detailref" | "scalebar" | "pointmarker" | "block" => set("at", p),
"grid" => {
// Griff 0 = Ursprung, danach je Achse (a, dann b) das Achsende: zieht die Achse auf die neue Lage.
if index == 0.0 {
return set("origin", p);
}
let (na, nb) = (arr(field(g, "a")).len(), arr(field(g, "b")).len());
let k = index_in(index - 1.0, na + nb)?;
let (ox, oy) = xy(field(g, "origin").unwrap_or(&Value::Null));
let ang = num_of(field(g, "angle"));
let (dx, dy) = (x - ox, y - oy);
let radial = field(g, "radial").and_then(Value::as_bool) == Some(true);
let (key, i) = if k < na { ("a", k) } else { ("b", k - na) };
let pos = match (radial, key) {
(false, "a") => dx * jsnum::cos(ang) + dy * jsnum::sin(ang),
(false, _) => -dx * jsnum::sin(ang) + dy * jsnum::cos(ang),
(true, "a") => {
let d = (jsnum::atan2(dy, dx) - ang).to_degrees();
let old = num_of(field(&arr(field(g, "a"))[i], "pos"));
// auf den Winkel nächst dem alten legen (kein Sprung um 360°)
old + (d - old + 180.0).rem_euclid(360.0) - 180.0
}
(true, _) => hypot2(dx, dy),
};
let list = arr(field(g, key));
let nl = Value::Array(list.iter().enumerate().map(|(j, e)| if j == i { with(e, "pos", js_num(pos)) } else { e.clone() }).collect());
set(key, nl)
}
"circle" => {
let (cx, cy) = xy(field(g, "center").unwrap_or(&Value::Null));
let r = pass(field(g, "r"));
@@ -758,6 +790,7 @@ fn drawing_moved(d: &Value, dx: f64, dy: f64) -> Option<Value> {
"rect" | "image" => with_all(g, vec![("min", mv("min")), ("max", mv("max"))]),
"circle" | "arc" | "ellipse" => with(g, "center", mv("center")),
"kote" | "detailref" | "scalebar" | "pointmarker" | "text" => with(g, "at", mv("at")),
"grid" => with(g, "origin", mv("origin")),
_ => return None,
};
Some(with_geom(d, ng))
@@ -1229,6 +1262,18 @@ pub fn drawing_vertices(g: &Value, scale: f64) -> Option<Vec<(f64, f64)>> {
out
}
"kote" | "detailref" | "scalebar" | "pointmarker" | "block" => vec![p("at")],
"grid" => {
let geom: crate::model::Drawing2DGeom = serde_json::from_value(g.clone()).ok()?;
let spec = crate::grid::Spec::of(&geom)?;
let mut out = vec![p("origin")];
for ax in spec.axes() {
out.push(match ax.shape {
crate::grid::Shape::Line { b, .. } => b,
crate::grid::Shape::Arc { c, r, a1, .. } => (c.0 + r * jsnum::cos(a1), c.1 + r * jsnum::sin(a1)),
});
}
out
}
"text" => {
if truthy(field(g, "pathPts")) {
pts("pathPts")
+1
View File
@@ -30,6 +30,7 @@ pub mod stair;
pub mod joins;
pub mod wall_bands;
pub mod wall_arc;
pub mod grid;
pub mod room_area;
pub mod room_boundary;
pub mod polygon_holes;
+77
View File
@@ -125,6 +125,26 @@ pub enum DimFeature {
/// Schnittpunkt der Wandlinie (`id`, `index`) mit der Wandlinie (`id2`, `index2`) — Ecken.
#[serde(rename = "intersection")]
Intersection,
/// Punkt auf Rasterachse `index` des Achsrasters `id` beim Anteil `t` entlang der Achse ([112]).
#[serde(rename = "axis")]
Axis,
/// Schnittpunkt der Rasterachsen `index` und `index2` des Achsrasters `id` ([112]).
#[serde(rename = "axiscross")]
AxisCross,
/// Punkt auf dem Kreis/Bogen (2D-Kreis, -Bogen, Bogenwand) `id` beim Winkel `t` (Bogenmass);
/// bei Bogenwänden `index` = Schichtgrenze (fehlt = Achse). Für Radius-, Durchmesser- und
/// Bogenlängen-Bemassung ([38]).
#[serde(rename = "rim")]
Rim,
}
/// Art einer Bemassung ([38]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "lowercase")]
pub enum DimKind {
Radius,
Diameter,
Arc,
}
/// Bezug eines Bemassungspunkts auf ein Element ([38]).
@@ -180,6 +200,23 @@ pub enum SplineMode {
Control,
}
/// Eine Achse des Achsrasters: Beschriftung und Lage (Abstand bzw. Winkel/Radius, s. `Grid`).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
#[serde(default)]
pub struct GridAxis {
pub label: String,
pub pos: f64,
}
/// Welche Achsenden eine Blase tragen.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "lowercase")]
pub enum GridBubbles {
Start,
End,
Both,
}
/// Geometrie eines 2D-Zeichenelements (Tag `shape`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(tag = "shape")]
@@ -332,6 +369,11 @@ pub enum Drawing2DGeom {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
refs: Option<Vec<Option<DimRef>>>,
/// Art der Bemassung (fehlt = linear): Radius/Durchmesser (`pts` = Mittelpunkt, Punkt auf dem
/// Kreis) und Bogenlänge (`pts` = Mittelpunkt, Bogenanfang, Bogenende).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional, inline)]
kind: Option<DimKind>,
},
/// Höhenkote (SIA 400 B.5.4, Figur 18): Dreieck-Symbol + Höhenwert (Meter,
/// ±0.00-Referenz frei wählbar, s. Norm) an einem Punkt. `kind` bestimmt
@@ -404,6 +446,41 @@ pub enum Drawing2DGeom {
/// gleichbleibende Lesbarkeit im Plan.
#[serde(rename = "pointmarker")]
Pointmarker { at: Vec2 },
/// Achsraster ([112], `grid.rs`): rechtwinklig (`a` = Achsen parallel zur lokalen Y-Achse bei
/// X = `pos`, Beschriftung 1, 2, 3 …; `b` = Achsen parallel zur lokalen X-Achse bei Y = `pos`,
/// A, B, C …) oder radial (`radial`: `a` = Strahlen unter `pos` Grad, `b` = Ringe mit Radius
/// `pos`). `origin`/`angle` (Bogenmass) legen das lokale System fest.
#[serde(rename = "grid")]
Grid {
origin: Vec2,
#[serde(default)]
angle: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
radial: Option<bool>,
a: Vec<GridAxis>,
b: Vec<GridAxis>,
/// Überstand der Achsen über die äusserste Querachse (Meter, Standard 1.5).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
extend: Option<f64>,
/// Enden mit Achsblase (Standard Anfang und Ende).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional, inline)]
bubbles: Option<GridBubbles>,
/// Blasen-Durchmesser in Papier-mm (Standard 8).
#[serde(rename = "bubbleMm", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
bubble_mm: Option<f64>,
/// Geschosse, in denen das Raster gezeigt wird; fehlt oder leer = in allen.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
levels: Option<Vec<String>>,
/// Im 3D-Modell als dünne Linien zeigen.
#[serde(rename = "show3d", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
show_3d: Option<bool>,
},
#[serde(rename = "text")]
Text {
at: Vec2,
+36 -13
View File
@@ -1888,24 +1888,28 @@ fn for_each_drawing_chunk(p: &Project, with_color: bool, mut f: impl FnMut(&[f64
buf.truncate(1);
};
for d in &p.drawings2d {
let (kind, pts): (f64, Vec<Vec2>) = match &d.geom {
Drawing2DGeom::Line { a, b } => (1.0, vec![*a, *b]),
Drawing2DGeom::Rect { min, max } => (3.0, vec![*min, *max]),
Drawing2DGeom::Polyline { pts, .. } => (2.0, pts.clone()),
// Teile einer Zeichnung: (Art, Punkte); ein Achsraster mit `show3d` liefert je Achse eines.
let parts: Vec<(f64, Vec<Vec2>)> = match &d.geom {
Drawing2DGeom::Line { a, b } => vec![(1.0, vec![*a, *b])],
Drawing2DGeom::Rect { min, max } => vec![(3.0, vec![*min, *max])],
Drawing2DGeom::Polyline { pts, .. } => vec![(2.0, pts.clone())],
Drawing2DGeom::Grid { show_3d: Some(true), .. } => crate::grid::Spec::of(&d.geom).map(|s| crate::grid::polylines_3d(&s)).unwrap_or_default().into_iter().map(|q| (2.0, q.into_iter().map(|(x, y)| Vec2 { x, y }).collect())).collect(),
_ => continue,
};
let need = 7 + 2 * pts.len();
if buf.len() + need > CHUNK_DOUBLES {
flush(&mut buf, &mut ids, &mut f);
}
let closed = matches!(&d.geom, Drawing2DGeom::Polyline { closed: true, .. });
let elev = *elevations.entry(d.level_id.as_str()).or_insert_with(|| p.floor(&d.level_id).map_or(0.0, |l| l.base_elevation.unwrap_or(0.0)) + DRAWING_LINE_ELEVATION_EPS);
let rgb = if with_color { drawing_color(d, &by_category, &by_line_style) } else { [0.0; 3] };
let closed = matches!(&d.geom, Drawing2DGeom::Polyline { closed: true, .. });
buf.extend([kind, elev, rgb[0], rgb[1], rgb[2], if closed { 1.0 } else { 0.0 }, pts.len() as f64]);
for q in &pts {
buf.extend([q.x, q.y]);
for (kind, pts) in parts {
let need = 7 + 2 * pts.len();
if buf.len() + need > CHUNK_DOUBLES {
flush(&mut buf, &mut ids, &mut f);
}
buf.extend([kind, elev, rgb[0], rgb[1], rgb[2], if closed { 1.0 } else { 0.0 }, pts.len() as f64]);
for q in &pts {
buf.extend([q.x, q.y]);
}
ids.push(d);
}
ids.push(d);
}
flush(&mut buf, &mut ids, &mut f);
}
@@ -2097,6 +2101,25 @@ pub fn pick_geometry(p: &Project) -> Result<PickGeometry, String> {
mod tests {
use super::*;
/// [112] Achsraster mit `show3d` erscheint als Boden-Spur (eine Strecke je Achse), ohne Flag nicht.
#[test]
fn achsraster_im_3d_nur_mit_flag() {
let mk = |show: serde_json::Value| -> Project {
serde_json::from_value(serde_json::json!({
"id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "layers": [], "openings": [], "walls": [],
"drawingLevels": [{"id": "F", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3.0, "baseElevation": 1.0}],
"drawings2d": [{"id": "G", "type": "drawing2d", "levelId": "F", "categoryCode": "20", "geom": {"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0,
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 4}], "b": [{"label": "A", "pos": 0}], "show3d": show}}]
}))
.unwrap()
};
assert!(drawing_line_verts(&mk(serde_json::json!(false))).is_empty());
let v = drawing_line_verts(&mk(serde_json::json!(true)));
// 3 Achsen × 1 Segment × 2 Endpunkte × 6 Zahlen.
assert_eq!(v.len(), 3 * 2 * 6);
assert!((v[1] - 1.01).abs() < 1e-4, "Höhe = Geschoss-UK + 0.01: {}", v[1]);
}
/// Walmdach 12×7 m: zwei Trapeze + zwei Walm-Dreiecke, First (3,3)-(8,3).
fn walm_planes() -> Vec<Vec<V3>> {
vec![
+233 -3
View File
@@ -54,6 +54,9 @@ pub fn symbol_factor(p: &Project, level: &str) -> f64 {
}
}
/// Rand um die Achsen im Ausmass, damit die Blasen ins Bild passen (Meter).
const GRID_BUBBLE_MARGIN_M: f64 = 1.0;
// Massstabsbalken, Papier-mm.
const SCALEBAR_HEIGHT_MM: f64 = 1.5;
const SCALEBAR_TICK_MM: f64 = 1.0;
@@ -211,6 +214,7 @@ pub fn shape_name(g: &Drawing2DGeom) -> &'static str {
Drawing2DGeom::Detailref { .. } => "detailref",
Drawing2DGeom::Scalebar { .. } => "scalebar",
Drawing2DGeom::Pointmarker { .. } => "pointmarker",
Drawing2DGeom::Grid { .. } => "grid",
Drawing2DGeom::Text { .. } => "text",
Drawing2DGeom::Block { .. } => "block",
Drawing2DGeom::Image { .. } => "image",
@@ -738,9 +742,22 @@ fn emit_inner(c: &Ctx, d: &Drawing2D, attrs: Attrs, geom: &Drawing2DGeom, greyed
em.seg(q[q.len() - 1], q[0]);
}
}
Drawing2DGeom::Dimension { pts, offset, gap_mm, overshoot_mm, tick_len_mm, text_height_mm, line_weight_mm, ext_weight_mm, tick_weight_mm, text_offsets_mm, refs } => {
Drawing2DGeom::Dimension { pts, offset, gap_mm, overshoot_mm, tick_len_mm, text_height_mm, line_weight_mm, ext_weight_mm, tick_weight_mm, text_offsets_mm, refs, kind } => {
let mm = |x: f64| mm_to_model(x, scale);
for i in 0..pts.len().saturating_sub(1) {
if let Some(k) = kind {
let st = DimStyle {
gap: mm(gap_mm.unwrap_or(DIM_GAP_MM)),
overshoot: mm(overshoot_mm.unwrap_or(DIM_OVERSHOOT_MM)),
tick_len: mm(tick_len_mm.unwrap_or(DIM_TICK_LEN_MM)),
text_height: mm(text_height_mm.unwrap_or(DIM_TEXT_HEIGHT_MM)),
line_weight: line_weight_mm.unwrap_or(em.weight),
ext_weight: ext_weight_mm.unwrap_or(em.weight),
tick_weight: tick_weight_mm.unwrap_or(em.weight * 2.0),
text_offset: (0.0, 0.0),
};
dimension_round(&mut em, pts, *offset, *k, &st);
}
for i in 0..(if kind.is_some() { 0 } else { pts.len().saturating_sub(1) }) {
let st = DimStyle {
gap: mm(gap_mm.unwrap_or(DIM_GAP_MM)),
overshoot: mm(overshoot_mm.unwrap_or(DIM_OVERSHOOT_MM)),
@@ -817,6 +834,11 @@ fn emit_inner(c: &Ctx, d: &Drawing2D, attrs: Attrs, geom: &Drawing2DGeom, greyed
em.seg(v(at.x - cross, at.y), v(at.x + cross, at.y));
em.seg(v(at.x, at.y - cross), v(at.x, at.y + cross));
}
Drawing2DGeom::Grid { bubble_mm, .. } => {
if let Some(spec) = crate::grid::Spec::of(geom) {
emit_grid(&mut em, &spec, crate::grid::bubble_diameter(*bubble_mm, scale), scale);
}
}
Drawing2DGeom::Text { at, text: s, height, angle, width, marks, doc, leader_target, leader_bend_points, path_pts } => {
let color = marks.as_ref().and_then(|m| m.color.clone()).unwrap_or_else(|| em.color.to_string());
if let Some(path) = path_pts.as_ref().filter(|q| q.len() >= 2) {
@@ -941,6 +963,110 @@ fn dimension_segment(em: &mut Em, a: Vec2, b: Vec2, offset: f64, st: &DimStyle)
em.sink.push(p, 0);
}
/// Achsraster ([112]): Achsen strichpunktiert, an den Enden Blasen mit der Beschriftung.
fn emit_grid(em: &mut Em, spec: &crate::grid::Spec, diameter: f64, scale: f64) {
use crate::grid::Shape;
let mm = |x: f64| mm_to_model(x, scale);
let dash = [mm(12.0), mm(2.5), mm(1.5), mm(2.5)];
let dash_ref = em.sink.fresh_ref();
let w = jsnum::min(em.weight, XLINE_WEIGHT_MM.max(0.18));
let r = diameter / 2.0;
let text_h = diameter * 0.5;
for ax in spec.axes() {
match ax.shape {
Shape::Line { a, b } => em.line(v(a.0, a.1), v(b.0, b.1), w, Some(&dash), dash_ref),
Shape::Arc { c, r: rad, a0, a1 } => {
let dash_v = Some(dash.to_vec());
if a1 - a0 >= std::f64::consts::TAU - 1e-9 {
em.sink.push(
Primitive::DrawingCircle { center: v(c.0, c.1), r: rad, fill: "none".into(), stroke: em.color.into(), weight_mm: w, dash: Some(dash_v), drawing_id: Some(em.id.into()), greyed: Some(em.greyed), opacity: None },
dash_ref,
);
} else {
em.sink.push(
Primitive::DrawingArc { center: v(c.0, c.1), r: rad, a0, a1, stroke: em.color.into(), weight_mm: w, dash: Some(dash_v), drawing_id: Some(em.id.into()), greyed: Some(em.greyed), opacity: None },
dash_ref,
);
}
}
}
for (end, dir) in ax.bubbles.iter().flatten() {
let c = v(end.0 + dir.0 * r, end.1 + dir.1 * r);
em.circle(c, r, "none", Some(None));
let n = ax.label.chars().count() as f64;
em.text(v(c.x - text_h * 0.3 * n, c.y - text_h * 0.35), ax.label.clone(), text_h);
}
}
}
/// Radius-, Durchmesser- und Bogenlängen-Mass ([38]): `pts` = Mittelpunkt, Punkt auf dem Kreis
/// (bzw. Bogenanfang, Bogenende); Mass auf dem Rand mit Massstrichen und Masszahl.
fn dimension_round(em: &mut Em, pts: &[Vec2], offset: f64, kind: DimKind, st: &DimStyle) {
let (Some(&c), Some(&p)) = (pts.first(), pts.get(1)) else { return };
let r = hypot2(p.x - c.x, p.y - c.y);
if !(r > 1e-6) {
return;
}
let (ux, uy) = ((p.x - c.x) / r, (p.y - c.y) / r);
let tick = |em: &mut Em, q: Vec2, tx: f64, ty: f64| {
let (nx, ny) = (-ty, tx);
let (dx, dy) = ((tx + nx) / std::f64::consts::SQRT_2, (ty + ny) / std::f64::consts::SQRT_2);
let h = st.tick_len / 2.0;
em.line(v(q.x - dx * h, q.y - dy * h), v(q.x + dx * h, q.y + dy * h), st.tick_weight, None, 0);
};
let label = |em: &mut Em, at: Vec2, ang: f64, s: String| {
let mut a = ang;
if jsnum::cos(a) < 0.0 {
a += std::f64::consts::PI;
}
let up = v(-jsnum::sin(a), jsnum::cos(a));
let q = v(at.x + up.x * st.text_height * 0.6, at.y + up.y * st.text_height * 0.6);
let pr = text(q, s, st.text_height, a, em.color, em.greyed, Some(em.id));
em.sink.push(pr, 0);
};
let (dash, dref) = (em.dash.clone(), em.dash_ref);
let dash = dash.as_deref();
match kind {
DimKind::Radius => {
em.line(c, p, st.line_weight, dash, dref);
tick(em, p, ux, uy);
tick(em, c, ux, uy);
let mid = v((c.x + p.x) / 2.0, (c.y + p.y) / 2.0);
label(em, mid, jsnum::atan2(uy, ux), format!("R {}", to_fixed(r, 2)));
}
DimKind::Diameter => {
let q = v(c.x - ux * r, c.y - uy * r);
em.line(q, p, st.line_weight, dash, dref);
tick(em, p, ux, uy);
tick(em, q, ux, uy);
label(em, c, jsnum::atan2(uy, ux), format!("\u{d8} {}", to_fixed(2.0 * r, 2)));
}
DimKind::Arc => {
let Some(&p1) = pts.get(2) else { return };
let a0 = jsnum::atan2(p.y - c.y, p.x - c.x);
let a1 = jsnum::atan2(p1.y - c.y, p1.x - c.x);
let sweep = (a1 - a0).rem_euclid(std::f64::consts::TAU);
let rr = r + offset;
if !(rr > 1e-6) || !(sweep > 1e-9) {
return;
}
let sign = if offset >= 0.0 { 1.0 } else { -1.0 };
for (a, pt) in [(a0, p), (a1, p1)] {
let (cx, cy) = (jsnum::cos(a), jsnum::sin(a));
em.line(v(pt.x + cx * st.gap * sign, pt.y + cy * st.gap * sign), v(c.x + cx * (rr + st.overshoot * sign), c.y + cy * (rr + st.overshoot * sign)), st.ext_weight, dash, dref);
tick(em, v(c.x + cx * rr, c.y + cy * rr), -cy, cx);
}
em.sink.push(
Primitive::DrawingArc { center: c, r: rr, a0, a1: a0 + sweep, stroke: em.color.into(), weight_mm: st.line_weight, dash: Some(dash.map(|x| x.to_vec())), drawing_id: Some(em.id.into()), greyed: Some(em.greyed), opacity: None },
if dash.is_some() { dref } else { 0 },
);
let am = a0 + sweep / 2.0;
let at = v(c.x + jsnum::cos(am) * rr, c.y + jsnum::sin(am) * rr);
label(em, at, am + std::f64::consts::FRAC_PI_2, format!("L {}", to_fixed(r * sweep, 2)));
}
}
}
/// Dreht die Umlauf-Orientierung um (Spiegelung)? Flächenvorzeichen eines Test-Dreiecks.
fn reverses_orientation(f: &dyn Fn(Vec2) -> Vec2) -> bool {
let (p0, p1, p2) = (f(v(0.0, 0.0)), f(v(1.0, 0.0)), f(v(0.0, 1.0)));
@@ -986,6 +1112,19 @@ pub fn mv_geom(g: &Drawing2DGeom, f: &dyn Fn(Vec2) -> Vec2) -> Drawing2DGeom {
G::Detailref { at, label, sheet_layout_id, sheet_label } => G::Detailref { at: f(*at), label: label.clone(), sheet_layout_id: sheet_layout_id.clone(), sheet_label: sheet_label.clone() },
G::Scalebar { at, segment_length, segments } => G::Scalebar { at: f(*at), segment_length: *segment_length, segments: *segments },
G::Pointmarker { at } => G::Pointmarker { at: f(*at) },
G::Grid { origin, angle, radial, a, b, extend, bubbles, bubble_mm, levels, show_3d } => {
let o = f(*origin);
let ex = f(v(origin.x + angle.cos(), origin.y + angle.sin()));
let flip = reverses_orientation(f);
let neg = |l: &Vec<GridAxis>| l.iter().map(|x| GridAxis { label: x.label.clone(), pos: -x.pos }).collect::<Vec<_>>();
let ang = (ex.y - o.y).atan2(ex.x - o.x);
let (a2, b2) = match (flip, radial == &Some(true)) {
(false, _) => (a.clone(), b.clone()),
(true, false) => (a.clone(), neg(b)),
(true, true) => (neg(a), b.clone()),
};
G::Grid { origin: o, angle: ang, radial: *radial, a: a2, b: b2, extend: *extend, bubbles: *bubbles, bubble_mm: *bubble_mm, levels: levels.clone(), show_3d: *show_3d }
}
G::Text { at, text, height, angle, width, marks, doc, leader_target, leader_bend_points, path_pts } => G::Text {
at: f(*at),
text: text.clone(),
@@ -1024,6 +1163,15 @@ pub fn scale_geom(g: &Drawing2DGeom, f: &dyn Fn(Vec2) -> Vec2, k: f64) -> Drawin
*ry *= k;
}
G::Dimension { offset, .. } => *offset *= k,
G::Grid { a, b, extend, radial, .. } => {
if *radial != Some(true) {
a.iter_mut().for_each(|x| x.pos *= k);
}
b.iter_mut().for_each(|x| x.pos *= k);
if let Some(e) = extend {
*e *= k;
}
}
G::Text { height, width, .. } => {
*height *= k;
if let Some(w) = width {
@@ -1097,6 +1245,25 @@ fn acc_bounds(g: &Drawing2DGeom, b: &mut Bounds) {
}
}
G::Kote { at, .. } | G::Detailref { at, .. } | G::Pointmarker { at } | G::Text { at, .. } => acc(at),
G::Grid { .. } => {
if let Some(spec) = crate::grid::Spec::of(g) {
for ax in spec.axes() {
match ax.shape {
// Rand für die Blasen an den Enden (Durchmesser bis ≈ 1 m bei 1:100).
crate::grid::Shape::Line { a, b: e } => {
acc(&v(a.0 - GRID_BUBBLE_MARGIN_M, a.1 - GRID_BUBBLE_MARGIN_M));
acc(&v(e.0 + GRID_BUBBLE_MARGIN_M, e.1 + GRID_BUBBLE_MARGIN_M));
acc(&v(a.0 + GRID_BUBBLE_MARGIN_M, a.1 + GRID_BUBBLE_MARGIN_M));
acc(&v(e.0 - GRID_BUBBLE_MARGIN_M, e.1 - GRID_BUBBLE_MARGIN_M));
}
crate::grid::Shape::Arc { c, r, .. } => {
acc(&v(c.0 - r - GRID_BUBBLE_MARGIN_M, c.1 - r - GRID_BUBBLE_MARGIN_M));
acc(&v(c.0 + r + GRID_BUBBLE_MARGIN_M, c.1 + r + GRID_BUBBLE_MARGIN_M));
}
}
}
}
}
G::Scalebar { at, segment_length, segments } => {
acc(at);
acc(&v(at.x + segment_length * segments, at.y));
@@ -1107,7 +1274,7 @@ fn acc_bounds(g: &Drawing2DGeom, b: &mut Bounds) {
/// Liegt die Zeichnung auf dem Geschoss (und ist sie im Druck nicht ausgenommen, `noPrint`)?
fn on_floor(c: &Ctx, d: &Drawing2D) -> bool {
d.level_id == c.a.floor && !(c.a.for_print && d.no_print == Some(true))
crate::grid::visible_on(d, &c.a.floor) && !(c.a.for_print && d.no_print == Some(true))
}
/// Domäne „2D-Zeichnungen" von `planDomains`: alle gezeichneten Zeichnungen des Geschosses in
@@ -1475,6 +1642,69 @@ mod tests {
}
}
/// [112] Achsraster: strichpunktierte Achsen, Blasen (Kreis + Beschriftung) an beiden Enden,
/// Ringe als Bögen, Blasengrösse folgt dem Massstab; auf anderen Geschossen sichtbar (`levels` leer).
#[test]
fn achsraster_achsen_und_blasen() {
let p = project(serde_json::json!({}));
let grid = |radial: bool| {
drawing(serde_json::json!({"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0, "radial": radial,
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": if radial { 90.0 } else { 5.0 }}], "b": [{"label": "A", "pos": 0}, {"label": "B", "pos": 4}], "extend": 1}))
};
let prims = render(&p, grid(false), 100.0);
let lines = prims.iter().filter(|q| matches!(q, Primitive::Line { dash: Some(Some(_)), .. })).count();
let circles: Vec<f64> = prims.iter().filter_map(|q| if let Primitive::DrawingCircle { r, .. } = q { Some(*r) } else { None }).collect();
let texts: Vec<String> = prims.iter().filter_map(|q| if let Primitive::DrawingText { text, .. } = q { Some(text.clone()) } else { None }).collect();
assert_eq!(lines, 4);
assert_eq!(circles.len(), 8);
// 8 mm Durchmesser bei 1:100 = 0.8 m → Radius 0.4.
assert!(circles.iter().all(|r| (r - 0.4).abs() < 1e-9), "{circles:?}");
assert_eq!(texts.len(), 8);
assert!(["1", "2", "A", "B"].iter().all(|t| texts.iter().any(|x| x == t)));
// Halber Massstab → halbe Blase.
let half: Vec<f64> = render(&p, grid(false), 50.0).iter().filter_map(|q| if let Primitive::DrawingCircle { r, .. } = q { Some(*r) } else { None }).collect();
assert!((half[0] - 0.2).abs() < 1e-9);
// Radial: 2 Strahlen (Linien) und 2 Ringe (Bögen, Ring A mit Radius 0 entfällt als Vollkreis-Punkt).
let prims = render(&p, grid(true), 100.0);
assert_eq!(prims.iter().filter(|q| matches!(q, Primitive::Line { .. })).count(), 2);
assert!(prims.iter().any(|q| matches!(q, Primitive::DrawingArc { r, .. } if (*r - 4.0).abs() < 1e-9)));
}
/// [112] Raster erscheint in jedem Geschoss, bei `levels` nur in den genannten.
#[test]
fn achsraster_je_geschoss() {
let g = |levels: Option<Vec<&str>>| {
let mut d: Drawing2D = serde_json::from_value(drawing(serde_json::json!({"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0, "a": [], "b": []}))).unwrap();
if let Drawing2DGeom::Grid { levels: l, .. } = &mut d.geom {
*l = levels.map(|v| v.into_iter().map(String::from).collect());
}
d
};
let p = project(serde_json::json!({}));
let a = args(100.0);
let c = Ctx::new(&p, &a);
let mut d = g(None);
d.level_id = "og".into();
assert!(on_floor(&c, &d), "ohne levels: in allen Geschossen (Plan zeigt eg)");
assert!(!on_floor(&c, &g(Some(vec!["og"]))));
assert!(on_floor(&c, &g(Some(vec!["og", "eg"]))));
}
/// [38] Radius-, Durchmesser- und Bogenlängen-Mass: Linien, Masszahl mit R / Ø / L.
#[test]
fn rund_bemassung_zeichnet_zahl() {
let p = project(serde_json::json!({}));
let dim = |kind: &str, pts: serde_json::Value| drawing(serde_json::json!({"shape": "dimension", "pts": pts, "offset": 0.5, "kind": kind}));
let texts = |prims: &[Primitive]| -> Vec<String> { prims.iter().filter_map(|q| if let Primitive::DrawingText { text, .. } = q { Some(text.clone()) } else { None }).collect() };
let r = render(&p, dim("radius", serde_json::json!([{"x": 0, "y": 0}, {"x": 3, "y": 0}])), 100.0);
assert_eq!(texts(&r), ["R 3.00"]);
let r = render(&p, dim("diameter", serde_json::json!([{"x": 0, "y": 0}, {"x": 3, "y": 0}])), 100.0);
assert_eq!(texts(&r), ["\u{d8} 6.00"]);
let r = render(&p, dim("arc", serde_json::json!([{"x": 0, "y": 0}, {"x": 2, "y": 0}, {"x": 0, "y": 2}])), 100.0);
assert_eq!(texts(&r), ["L 3.14"]);
assert!(r.iter().any(|q| matches!(q, Primitive::DrawingArc { r, .. } if (*r - 2.5).abs() < 1e-9)));
}
#[test]
fn rechteck_flaeche_und_vier_linien_in_ebenenfarbe() {
let p = project(serde_json::json!({}));
+6 -1
View File
@@ -1562,7 +1562,12 @@ pub fn elevation_plan_buf(p: &Project, args: &[f64], text: &str) -> Result<Vec<u
let mut w = crate::plan_buf::Writer::new(true);
if let Some((prims, bounds)) = elevation_primitives(p, &level, shadows, mono, &vis, scale)? {
w.group(&prims);
w.bounds = Some(bounds);
// Achsraster ([112]): Achsen quer zur Blickebene.
let grid = super::grid_view::grid_prims(p, &level, bounds, scale);
if !grid.is_empty() {
w.group(&grid);
}
w.bounds = Some(super::grid_view::union_bounds(bounds, &grid));
}
Ok(w.finish())
}
+159
View File
@@ -0,0 +1,159 @@
//! Achsraster in Schnitt und Ansicht ([112]): Rasterachsen quer zur Blickebene als senkrechte
//! strichpunktierte Linien (x = Lage entlang der Schnittlinie, y = Höhe) mit Blase und Beschriftung
//! oben (bzw. unten bei „nur Anfang"). Hängt als eigene Gruppe hinter dem Schnitt/der Ansicht.
use super::prim::Primitive;
use super::section::{LevelSpec, Plane};
use crate::grid::{bubble_diameter, section_axes, Spec};
use crate::model::{Drawing2DGeom, GridBubbles, Project, Vec2};
const INK: &str = "#5a5f66";
const AXIS_MM: f64 = 0.18;
/// Überstand der Achse über die Gebäudehöhe und unter die Bodenlinie (Meter).
const OVER_TOP: f64 = 0.8;
const OVER_BOTTOM: f64 = 0.3;
fn v2(x: f64, y: f64) -> Vec2 {
Vec2 { x, y }
}
/// Achslinien und Blasen für eine Ebene; `bounds` = Ausmass des Schnitts/der Ansicht (x0, y0, x1, y1),
/// `scale` = Massstabsnenner. Leer ohne Raster oder ohne Ebene.
pub fn grid_prims(p: &Project, level: &LevelSpec, bounds: [f64; 4], scale: f64) -> Vec<Primitive> {
let Some(plane) = level.plane() else { return Vec::new() };
let mut out = Vec::new();
for d in &p.drawings2d {
let Drawing2DGeom::Grid { bubble_mm, bubbles, .. } = &d.geom else { continue };
let Some(spec) = Spec::of(&d.geom) else { continue };
out.extend(one(&spec, &plane, level, bounds, scale, bubble_diameter(*bubble_mm, scale), bubbles.unwrap_or(GridBubbles::Both)));
}
out
}
/// Ausmass der Achsen (für die Bounds des Aufrufers).
pub fn extent(prims: &[Primitive]) -> Option<[f64; 4]> {
let mut b: Option<[f64; 4]> = None;
let mut acc = |x: f64, y: f64| {
let r = b.get_or_insert([x, y, x, y]);
r[0] = r[0].min(x);
r[1] = r[1].min(y);
r[2] = r[2].max(x);
r[3] = r[3].max(y);
};
for q in prims {
match q {
Primitive::Line { a, b, .. } => {
acc(a.x, a.y);
acc(b.x, b.y);
}
Primitive::DrawingCircle { center, r, .. } => {
acc(center.x - r, center.y - r);
acc(center.x + r, center.y + r);
}
_ => {}
}
}
b
}
/// Vereinigt das Ausmass `bounds` mit dem der Achsen.
pub fn union_bounds(bounds: [f64; 4], grid: &[Primitive]) -> [f64; 4] {
extent(grid).map_or(bounds, |g| [bounds[0].min(g[0]), bounds[1].min(g[1]), bounds[2].max(g[2]), bounds[3].max(g[3])])
}
fn one(spec: &Spec, plane: &Plane, level: &LevelSpec, bounds: [f64; 4], scale: f64, diameter: f64, bubbles: GridBubbles) -> Vec<Primitive> {
let (bx, by) = plane.base();
let (ux, uy) = plane.u_model();
let l = ux.hypot(uy);
if !(l > 1e-12) || !bounds.iter().all(|x| x.is_finite()) {
return Vec::new();
}
let u = (ux / l, uy / l);
// Länge der Schnittlinie in u: die Achsen ausserhalb dieser Spanne gehören nicht zum Bild.
let [p0, p1] = level.line.unwrap_or([v2(bx, by), v2(bx, by)]);
let e = (p1.x - p0.x) * u.0 + (p1.y - p0.y) * u.1;
let (lo, hi) = (e.min(0.0), e.max(0.0));
let mm = |x: f64| x * scale / 1000.0;
let dash = vec![mm(12.0), mm(2.5), mm(1.5), mm(2.5)];
let (y0, y1) = (bounds[1] - OVER_BOTTOM, bounds[3] + OVER_TOP);
let (r, text_h) = (diameter / 2.0, diameter * 0.5);
let mut out = Vec::new();
for (label, x) in section_axes(spec, (bx, by), u, level.kind == "elevation") {
if x < lo - 1e-9 || x > hi + 1e-9 {
continue;
}
out.push(Primitive::Line {
a: v2(x, y0),
b: v2(x, y1),
cls: "draw2d".into(),
weight_mm: AXIS_MM,
dash: Some(Some(dash.clone())),
zigzag: None,
motif: None,
color: Some(INK.into()),
drawing_id: None,
opening_id: None,
stair_id: None,
greyed: None,
opacity: None,
});
let (y, dir) = if bubbles == GridBubbles::Start { (y0, -1.0) } else { (y1, 1.0) };
let c = v2(x, y + dir * r);
out.push(Primitive::DrawingCircle { center: c, r, fill: "none".into(), stroke: INK.into(), weight_mm: 0.25, dash: None, drawing_id: None, greyed: None, opacity: None });
let n = label.chars().count() as f64;
out.push(Primitive::DrawingText {
at: v2(c.x - text_h * 0.3 * n, c.y - text_h * 0.35),
text: label.clone(),
height_m: text_h,
angle: 0.0,
color: INK.into(),
marks: None,
wrap_width: None,
doc: None,
drawing_id: None,
greyed: None,
opacity: None,
});
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn project(grid: serde_json::Value) -> Project {
serde_json::from_value(serde_json::json!({
"id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "layers": [], "openings": [], "walls": [],
"drawingLevels": [{"id": "F", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3.0, "baseElevation": 0}],
"drawings2d": [{"id": "G", "type": "drawing2d", "levelId": "F", "categoryCode": "20", "geom": grid}]
}))
.unwrap()
}
fn texts(prims: &[Primitive]) -> Vec<String> {
prims.iter().filter_map(|q| if let Primitive::DrawingText { text, .. } = q { Some(text.clone()) } else { None }).collect()
}
#[test]
fn senkrechte_achsen_mit_blase() {
let p = project(serde_json::json!({"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0,
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 4}], "b": [{"label": "A", "pos": 0}, {"label": "B", "pos": 6}]}));
// Schnitt entlang +x bei y = 3 von x = -1 bis 8: schneidet die Achsen 1 und 2 (u = 1 und 5).
let level = LevelSpec { kind: "section".into(), line: Some([v2(-1.0, 3.0), v2(8.0, 3.0)]), ..Default::default() };
let prims = grid_prims(&p, &level, [0.0, 0.0, 9.0, 6.0], 100.0);
let lines: Vec<(f64, f64, f64)> = prims.iter().filter_map(|q| if let Primitive::Line { a, b, .. } = q { Some((a.x, a.y, b.y)) } else { None }).collect();
assert_eq!(lines.len(), 2, "{prims:?}");
assert!((lines[0].0 - 1.0).abs() < 1e-9 && (lines[1].0 - 5.0).abs() < 1e-9);
assert!(lines[0].1 < 0.0 && lines[0].2 > 6.0);
assert_eq!(texts(&prims), ["1", "2"]);
// Schnitt längs der Achsen 1/2: nur die waagrechten Achsen A, B queren.
let level = LevelSpec { kind: "section".into(), line: Some([v2(2.0, -1.0), v2(2.0, 9.0)]), ..Default::default() };
let prims = grid_prims(&p, &level, [0.0, 0.0, 9.0, 6.0], 100.0);
assert_eq!(texts(&prims), ["A", "B"]);
assert!(union_bounds([0.0, 0.0, 9.0, 6.0], &prims)[3] > 6.0);
// Ansicht von Süden (y = -3): Achsen 1, 2 stehen senkrecht zur Ebene und erscheinen an ihrer Lage.
let level = LevelSpec { kind: "elevation".into(), line: Some([v2(-1.0, -3.0), v2(8.0, -3.0)]), ..Default::default() };
assert_eq!(texts(&grid_prims(&p, &level, [0.0, 0.0, 9.0, 6.0], 100.0)), ["1", "2"]);
}
}
+1
View File
@@ -11,6 +11,7 @@ pub mod context;
pub mod drawings;
pub mod section;
pub mod elevation;
pub mod grid_view;
pub mod cache;
pub mod extras;
pub mod underlay;
+6 -1
View File
@@ -2349,7 +2349,12 @@ pub fn section_plan_buf(p: &Project, args: &[f64], text: &str) -> Result<Vec<u8>
w.group(&prims);
let ops = if openings { section_opening_primitives(p, &level, &vis)? } else { Vec::new() };
w.group(&ops);
w.bounds = Some(bounds);
// Achsraster ([112]): Achsen quer zur Schnittebene.
let grid = super::grid_view::grid_prims(p, &level, bounds, v.get("scale").and_then(|s| s.as_f64()).filter(|s| *s > 0.0).unwrap_or(100.0));
if !grid.is_empty() {
w.group(&grid);
}
w.bounds = Some(super::grid_view::union_bounds(bounds, &grid));
Ok(w.finish())
}
+2 -1
View File
@@ -1231,7 +1231,8 @@ fn emit_entries(cx: &mut Ctx, main: &mut Buf, entries: &[Entry], layer_by_code:
let mut block_by_id: HashMap<&str, &Drawing2D> = HashMap::new();
for d in &project.drawings2d {
match d.geom {
Drawing2DGeom::Dimension { .. } => {
// Radius-/Durchmesser-/Bogenmass (`kind`) geht als Linien, Bögen und Text hinaus.
Drawing2DGeom::Dimension { kind: None, .. } => {
dim_by_id.insert(d.id.as_str(), d);
}
Drawing2DGeom::Block { .. } => {
+10
View File
@@ -1135,6 +1135,16 @@ pub fn geom_bbox(g: &Value) -> [f64; 4] {
}
}
Some("kote" | "text" | "block" | "detailref" | "pointmarker") => pts.push(p("at")),
Some("grid") => {
if let Some(spec) = serde_json::from_value::<crate::model::Drawing2DGeom>(g.clone()).ok().as_ref().and_then(crate::grid::Spec::of) {
for ax in spec.axes() {
match ax.shape {
crate::grid::Shape::Line { a, b } => pts.extend([a, b]),
crate::grid::Shape::Arc { c, r, .. } => pts.extend([(c.0 - r, c.1 - r), (c.0 + r, c.1 + r)]),
}
}
}
}
Some("scalebar") => {
let at = p("at");
pts.extend([at, (at.0 + num_of(field(g, "segmentLength")) * num_of(field(g, "segments")), at.1)]);
+38 -2
View File
@@ -265,18 +265,31 @@ pub fn collect_drawings(p: &Project, level: &str, codes: &HashSet<String>) -> Sn
let mut segs: Vec<Seg> = Vec::new();
let mut circles = Vec::new();
let mut ellipses = Vec::new();
let mut anchors = Vec::new();
for d in &p.drawings2d {
if d.level_id != level || !codes.contains(&d.category_code) {
if !crate::grid::visible_on(d, level) || !codes.contains(&d.category_code) {
continue;
}
match &d.geom {
// Achsraster ([112]): Achsen als Strecken/Bögen, Achsschnittpunkte als Endpunkte.
g @ Drawing2DGeom::Grid { .. } => {
if let Some(spec) = crate::grid::Spec::of(g) {
for ax in spec.axes() {
match ax.shape {
crate::grid::Shape::Line { a, b } => segs.push([a.0, a.1, b.0, b.1]),
crate::grid::Shape::Arc { c, r, a0, a1 } => circles.push(Circle { cx: c.0, cy: c.1, r, arc: (a1 - a0 < std::f64::consts::TAU - 1e-9).then_some((a0, a1)) }),
}
}
anchors.extend(spec.crossings());
}
}
Drawing2DGeom::Circle { center, r } => circles.push(Circle { cx: center.x, cy: center.y, r: *r, arc: None }),
Drawing2DGeom::Arc { center, r, a0, a1 } => circles.push(Circle { cx: center.x, cy: center.y, r: *r, arc: Some((*a0, *a1)) }),
Drawing2DGeom::Ellipse { center, .. } => ellipses.push((center.x, center.y)),
g => drawing_segs(g, &mut segs),
}
}
SnapPart { segs: SnapSet::new(segs), circles, anchors: Vec::new(), ellipses }
SnapPart { segs: SnapSet::new(segs), circles, anchors, ellipses }
}
/// Die Kandidaten eines Geschosses: Modell, Zeichnungen, Nahmodus.
@@ -656,6 +669,29 @@ mod tests {
assert!(o.dwell.is_none() && o.a.is_none() && o.b.is_none());
}
/// [112] Achsraster: Achsen als Strecken, Ringe als Kreise, Achsschnittpunkte als Endpunkte; in allen Geschossen.
#[test]
fn achsraster_fang() {
let mut v = base();
v["drawings2d"] = json!([{"id": "G", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "grid", "origin": {"x": 1, "y": 2}, "angle": 0,
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 4}], "b": [{"label": "A", "pos": 0}, {"label": "B", "pos": 3}], "extend": 1}}]);
let p: Project = serde_json::from_value(v).unwrap();
let codes: HashSet<String> = ["20".to_string()].into_iter().collect();
for level in ["eg", "og"] {
let part = collect_drawings(&p, level, &codes);
assert_eq!(part.anchors.len(), 4, "{level}");
assert!(part.anchors.contains(&(5.0, 5.0)));
}
let mut v = base();
v["drawings2d"] = json!([{"id": "G", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0, "radial": true,
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 90}], "b": [{"label": "A", "pos": 3}], "extend": 1}}]);
let p: Project = serde_json::from_value(v).unwrap();
let part = collect_drawings(&p, "eg", &codes);
assert_eq!(part.circles.len(), 1);
assert_eq!(part.circles[0].r, 3.0);
assert_eq!(part.anchors.len(), 2);
}
#[test]
fn gleiche_nummer_solange_nichts_relevantes_aendert_teile_einzeln_neu() {
let mut v = base();
+1
View File
@@ -292,6 +292,7 @@ const TOOL_COMMAND: Partial<Record<ToolId, string>> = {
scalebar: "scalebar",
revcloud: "revcloud",
pointmarker: "pointmarker",
grid: "grid",
wipeout: "wipeout",
text: "text",
leader: "leader",
+1 -1
View File
@@ -603,7 +603,7 @@ async function execute(project: Project, file: string, command: string, rest: st
const o = await computeSection(project, lvl);
if (!o) fail("keine gültige Schnittlinie");
// Wie die App: verdeckte Kanten nach der Ebene, geschnittene Fenster/Türen.
plan = generateSectionPlan(o, false, { visibleCodes: allCodes, hiddenLines: lvl.hiddenLines, openings: true });
plan = generateSectionPlan(o, false, { visibleCodes: allCodes, hiddenLines: lvl.hiddenLines, openings: true, scaleDenominator: scale });
} else {
plan = generateElevationPlan(project, lvl, { scaleDenominator: scale });
if (!plan) fail("keine gültige Ansichtslinie");
+60
View File
@@ -0,0 +1,60 @@
// Radius-, Durchmesser- und Bogenlängen-Bemassung ([38]): Klick auf den Rand eines Kreises, Bogens oder
// einer Bogenwand (Fläche oder Achse). Der Kern (`cmd_draw.rs`, `dim_assoc::round_dimension`) findet den
// Kreis, setzt Mittelpunkt und Randpunkte und hängt sie daran (Bezug `center`/`rim`): Verschieben oder
// Vergrössern des Kreises, Strecken der Bogenwand führt das Mass nach. Radius und Durchmesser: ein Klick;
// Bogenlänge: Anfang, Ende (gegen den Uhrzeigersinn), dann Lage der Masslinie.
import type { Command, CommandContext, CommandResult, CommandState, ToolDraft, Vec2 } from "../types";
import { createMutation, createPreview, xy } from "../createCore";
export type RoundKind = "radius" | "diameter" | "arc";
interface RoundState extends CommandState {
phase: "first" | "second" | "offset";
pts: Vec2[];
}
const fresh = (): RoundState => ({ phase: "first", lastPoint: null, pts: [] });
const idle = (): [CommandState, CommandResult] => [fresh(), { draft: null, done: true }];
/** Fangtoleranz auf dem Rand (Modell-Meter). */
const TOL = 0.2;
function draft(ctx: CommandContext, kind: RoundKind, pts: Vec2[], cursor: Vec2 | null): ToolDraft | null {
const all = cursor ? [...pts, cursor] : pts;
if (all.length === 0) return null;
const pv = createPreview(ctx, { cmd: "dimround", kind, tol: TOL }, all);
return { preview: pv.shapes, vertices: pts };
}
function make(kind: RoundKind, name: string): Command {
const keyOf = (s: RoundState) => (s.phase === "first" ? `cmd.${name}.first` : s.phase === "second" ? `cmd.${name}.second` : `cmd.${name}.offset`);
return {
name,
labelKey: `cmd.${name}.label` as never,
prompt: (s) => keyOf(s as RoundState) as never,
accepts: () => ["point"],
options: () => [],
init: fresh,
onInput: (state, input, ctx): [CommandState, CommandResult] => {
const s = state as RoundState;
if (input.kind !== "point") return [s, { draft: null }];
const pts = [...s.pts, input.point];
if (kind !== "arc" || s.phase === "offset") {
const commit = createMutation(ctx, { cmd: "dimround", kind, tol: TOL, pts: pts.slice(0, kind === "arc" ? 2 : 1).map(xy), side: kind === "arc" ? xy(input.point) : null });
return [fresh(), { draft: null, done: true, commit }];
}
const ns: RoundState = { phase: pts.length >= 2 ? "offset" : "second", pts, lastPoint: input.point };
return [ns, { draft: draft(ctx, kind, pts, null) }];
},
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => [state, { draft: draft(ctx, kind, (state as RoundState).pts, point) }],
onConfirm: () => idle(),
onCancel: () => idle(),
};
}
export const radiusDimCommand = make("radius", "dimradius");
export const diameterDimCommand = make("diameter", "dimdiameter");
export const arcDimCommand = make("arc", "dimarc");
+110
View File
@@ -0,0 +1,110 @@
/**
* `gridCommand` ([112]) und die Rundmass-Befehle ([38]): Eingabe → Zeichnung im Kern. Die Nachführung der
* Bezüge im Store prüft `src/state/gridAssoc.test.ts`.
*/
import { describe, it, expect } from "vitest";
import { gridCommand } from "./grid";
import { arcDimCommand, diameterDimCommand, radiusDimCommand } from "./dimround";
import type { CommandContext, Project } from "../types";
import type { Drawing2D } from "../../model/types";
function project(extra: Drawing2D[] = []): Project {
return {
id: "t",
name: "T",
lineStyles: [],
hatches: [],
components: [],
wallTypes: [],
drawingLevels: [{ id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }],
layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }],
walls: [],
openings: [],
ceilings: [],
stairs: [],
rooms: [],
drawings2d: extra,
context: [],
};
}
function ctxOf(p: Project): CommandContext {
return { project: p, level: p.drawingLevels[0], defaultCategoryCode: "20", activeLineStyleId: "solid", activeWallTypeId: "aw", lastPoint: null, selection: { wallIds: [], drawingId: null } };
}
describe("gridCommand", () => {
it("Ursprung + Feldweiten → Achsraster mit Beschriftung 1, 2, 3 / A, B", () => {
const p = project();
const ctx = ctxOf(p);
let [s] = gridCommand.onInput(gridCommand.init(), { kind: "point", point: { x: 2, y: 1 } }, ctx);
[s] = gridCommand.onInput(s, { kind: "text", text: "6 4.5 3x5" }, ctx);
const [, r] = gridCommand.onInput(s, { kind: "text", text: "5 5" }, ctx);
expect(r.done).toBe(true);
const g = r.commit!(p).drawings2d[0].geom;
expect(g.shape).toBe("grid");
if (g.shape !== "grid") return;
expect(g.origin).toEqual({ x: 2, y: 1 });
expect(g.a.map((x) => [x.label, x.pos])).toEqual([["1", 0], ["2", 6], ["3", 10.5], ["4", 15.5], ["5", 20.5], ["6", 25.5]]);
expect(g.b.map((x) => [x.label, x.pos])).toEqual([["A", 0], ["B", 5], ["C", 10]]);
});
it("radial: Option umschalten, Strahlen und Ringe; Enter übernimmt die Vorgaben", () => {
const p = project();
const ctx = ctxOf(p);
let [s] = gridCommand.onInput(gridCommand.init(), { kind: "option", id: "radial" }, ctx);
[s] = gridCommand.onInput(s, { kind: "point", point: { x: 0, y: 0 } }, ctx);
[s] = gridCommand.onInput(s, { kind: "text", text: "2x45" }, ctx);
const [, r] = gridCommand.onInput(s, { kind: "text", text: "3 3" }, ctx);
const g = r.commit!(p).drawings2d[0].geom;
expect(g.shape === "grid" && g.radial).toBe(true);
if (g.shape === "grid") {
expect(g.a.map((x) => x.pos)).toEqual([0, 45, 90]);
expect(g.b.map((x) => x.pos)).toEqual([3, 6]);
}
// Vorgaben (Enter, Enter) im rechtwinkligen Raster: 6 6 6 / 6 6.
let [t] = gridCommand.onInput(gridCommand.init(), { kind: "point", point: { x: 0, y: 0 } }, ctx);
[t] = gridCommand.onConfirm(t, ctx);
const [, e] = gridCommand.onConfirm(t, ctx);
const d = e.commit!(p).drawings2d[0].geom;
expect(d.shape === "grid" && [d.a.length, d.b.length]).toEqual([4, 3]);
});
it("unlesbare Feldweiten legen nichts an; Vorschau am Cursor liefert Achsen", () => {
const p = project();
const ctx = ctxOf(p);
let [s] = gridCommand.onInput(gridCommand.init(), { kind: "point", point: { x: 0, y: 0 } }, ctx);
[s] = gridCommand.onInput(s, { kind: "text", text: "abc" }, ctx);
const [, r] = gridCommand.onInput(s, { kind: "text", text: "5" }, ctx);
expect(r.commit!(p).drawings2d.length).toBe(0);
const [, mv] = gridCommand.onMove(gridCommand.init(), { x: 1, y: 1 }, null, ctx);
expect(mv.draft?.preview.length).toBeGreaterThan(0);
});
});
describe("Rundmass-Befehle", () => {
const circle = { id: "K", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "circle", center: { x: 5, y: 5 }, r: 2 } } as Drawing2D;
it("Radius/Durchmesser: ein Klick auf den Rand → Mass mit Bezug", () => {
for (const [cmd, kind] of [[radiusDimCommand, "radius"], [diameterDimCommand, "diameter"]] as const) {
const p = project([circle]);
const [, r] = cmd.onInput(cmd.init(), { kind: "point", point: { x: 7, y: 5.02 } }, ctxOf(p));
const g = r.commit!(p).drawings2d[1].geom;
expect(g.shape === "dimension" && g.kind).toBe(kind);
expect(g.shape === "dimension" && g.refs?.map((x) => x?.feature)).toEqual(["center", "rim"]);
}
});
it("Bogenlänge: Anfang, Ende, Lage → drei Punkte; Klick ins Leere legt nichts an", () => {
const p = project([circle]);
const ctx = ctxOf(p);
let [s] = arcDimCommand.onInput(arcDimCommand.init(), { kind: "point", point: { x: 7, y: 5 } }, ctx);
[s] = arcDimCommand.onInput(s, { kind: "point", point: { x: 5, y: 7 } }, ctx);
const [, r] = arcDimCommand.onInput(s, { kind: "point", point: { x: 5, y: 8 } }, ctx);
const dim = r.commit!(p).drawings2d[1];
expect(dim.geom.shape === "dimension" && dim.geom.pts.length).toBe(3);
expect(dim.geom.shape === "dimension" && dim.geom.offset).toBeCloseTo(1, 6);
const [, none] = radiusDimCommand.onInput(radiusDimCommand.init(), { kind: "point", point: { x: 50, y: 50 } }, ctx);
expect(none.commit!(p).drawings2d.length).toBe(1);
});
});
+95
View File
@@ -0,0 +1,95 @@
// Achsraster ([112]): Ursprung klicken, dann die Feldweiten als Text (`6 4.5 3x5`: Zahlen, `N x W` =
// N Felder zu W). Rechtwinklig: erst die Richtung 1, 2, 3 …, dann A, B, C …; radial: Strahlwinkel in
// Grad und Ringabstände. Das Raster ist eine 2D-Zeichnung (Kern, `grid.rs`): Achsen mit Blasen in
// allen Plänen, Schnitten und Ansichten, Fang auf Achsen und Schnittpunkte, Griffe je Achse.
import type { Command, CommandContext, CommandResult, CommandState, CmdOption, ToolDraft, Vec2 } from "../types";
import { createMutation, createPreview, xy } from "../createCore";
type Phase = "origin" | "xs" | "ys";
interface GridState extends CommandState {
phase: Phase;
origin: Vec2 | null;
radial: boolean;
xs: string;
ys: string;
}
const DEFAULTS = {
ortho: { xs: "6 6 6", ys: "6 6" },
radial: { xs: "4x45", ys: "3 3 3" },
};
const RADIAL: CmdOption = { id: "radial", labelKey: "cmd.grid.radial" };
const start = (radial = false): GridState => ({
phase: "origin",
lastPoint: null,
origin: null,
radial,
xs: radial ? DEFAULTS.radial.xs : DEFAULTS.ortho.xs,
ys: radial ? DEFAULTS.radial.ys : DEFAULTS.ortho.ys,
});
const idle = (): [CommandState, CommandResult] => [start(), { draft: null, done: true }];
/** Vorschau (Kern): die Achsen des Rasters am Cursor. */
function draft(ctx: CommandContext, s: GridState, at: Vec2): ToolDraft {
const pv = createPreview(ctx, { cmd: "grid", xs: s.xs, ys: s.ys, radial: s.radial, angle: 0 }, [at]);
return { preview: pv.shapes, vertices: [at] };
}
const commit = (ctx: CommandContext, s: GridState, ys: string) =>
createMutation(ctx, { cmd: "grid", at: xy(s.origin as Vec2), xs: s.xs, ys, radial: s.radial, angle: 0 });
export const gridCommand: Command = {
name: "grid",
labelKey: "cmd.grid.label",
prompt: (state) => {
const s = state as GridState;
if (s.phase === "origin") return "cmd.grid.origin";
if (s.phase === "xs") return s.radial ? "cmd.grid.xsRadial" : "cmd.grid.xs";
return s.radial ? "cmd.grid.ysRadial" : "cmd.grid.ys";
},
accepts: (state) => ((state as GridState).phase === "origin" ? ["point", "option"] : ["text"]),
options: (state): CmdOption[] => ((state as GridState).phase === "origin" ? [{ ...RADIAL, value: (state as GridState).radial ? "ja" : "nein" }] : []),
floorOnly: false,
init: () => start(),
onInput: (state, input, ctx): [CommandState, CommandResult] => {
const s = state as GridState;
if (s.phase === "origin") {
if (input.kind === "option" && input.id === "radial") return [start(!s.radial), { draft: null }];
if (input.kind !== "point") return [s, { draft: null }];
const ns: GridState = { ...s, phase: "xs", origin: input.point, lastPoint: input.point };
return [ns, { draft: draft(ctx, ns, input.point) }];
}
if (input.kind !== "text") return [s, { draft: null }];
const text = input.text.trim();
if (s.phase === "xs") {
const ns: GridState = { ...s, phase: "ys", xs: text === "" ? s.xs : text };
return [ns, { draft: s.origin ? draft(ctx, ns, s.origin) : null }];
}
const ys = text === "" && !s.radial ? s.ys : text;
return [start(), { draft: null, done: true, commit: commit(ctx, s, ys) }];
},
onMove: (state, point, _snap, ctx): [CommandState, CommandResult] => {
const s = state as GridState;
if (s.phase !== "origin") return [s, { draft: s.origin ? draft(ctx, s, s.origin) : null }];
return [s, { draft: draft(ctx, s, point) }];
},
// Enter: Vorgabe-Feldweiten übernehmen.
onConfirm: (state, ctx): [CommandState, CommandResult] => {
const s = state as GridState;
if (s.phase === "origin") return idle();
if (s.phase === "xs") {
const ns: GridState = { ...s, phase: "ys" };
return [ns, { draft: s.origin ? draft(ctx, ns, s.origin) : null }];
}
return [start(), { draft: null, done: true, commit: commit(ctx, s, s.ys) }];
},
onCancel: () => idle(),
};
+15
View File
@@ -47,6 +47,8 @@ import { scaleCommand } from "./cmds/scale";
import { explodeCommand } from "./cmds/explode";
import { dimdetachCommand } from "./cmds/dimdetach";
import { autodimCommand } from "./cmds/autodim";
import { gridCommand } from "./cmds/grid";
import { arcDimCommand, diameterDimCommand, radiusDimCommand } from "./cmds/dimround";
import { alignCommand } from "./cmds/align";
import { joinCommand } from "./cmds/join";
import { copyCommand } from "./cmds/copy";
@@ -115,6 +117,10 @@ export const COMMANDS: Record<string, Command> = {
explode: explodeCommand,
dimdetach: dimdetachCommand,
autodim: autodimCommand,
grid: gridCommand,
dimradius: radiusDimCommand,
dimdiameter: diameterDimCommand,
dimarc: arcDimCommand,
align: alignCommand,
join: joinCommand,
copy: copyCommand,
@@ -236,6 +242,15 @@ export const ALIASES: Record<string, string> = {
bml: "dimdetach",
bemassungloesen: "dimdetach",
ab: "autodim",
axes: "grid",
achsraster: "grid",
achsen: "grid",
rad: "dimradius",
radiusmass: "dimradius",
dm: "dimdiameter",
durchmessermass: "dimdiameter",
bogenl: "dimarc",
bogenlaenge: "dimarc",
aussenbemassung: "autodim",
al: "align",
ausrichten: "align",
+30
View File
@@ -208,6 +208,8 @@ export const de = {
"tool.revcloud.hint": "Revisionswolke: Punkte wie Polylinie klicken, Enter beendet offen, Klick nahe Start oder \"Schliessen\" schliesst",
"tool.pointmarker": "Punktmarker",
"tool.pointmarker.hint": "Punktmarker: Punkt setzen — Kreuz-in-Kreis-Symbol markiert einen Referenzpunkt",
"tool.grid": "Achsraster",
"tool.grid.hint": "Achsraster: Ursprung setzen, dann Feldweiten eingeben — Achsen mit Blasen in allen Plänen, Schnitten und Ansichten",
"tool.wipeout": "Maskenregion",
"tool.wipeout.hint": "Maskenregion: Punkte wie Polylinie klicken, Klick nahe Start oder Enter (ab 3 Punkten) schliesst und deckt darunterliegende Zeichnung ab",
"tool.text": "Text",
@@ -384,6 +386,17 @@ export const de = {
"attr.ends.tick": "Schrägstrich",
"attr.ends.square": "Quadrat",
"attr.dim.section": "Bemassung",
"attr.grid.section": "Achsraster",
"attr.grid.bubbles": "Achsblasen",
"attr.grid.bubbles.both": "Beide Enden",
"attr.grid.bubbles.start": "Nur Anfang",
"attr.grid.bubbles.end": "Nur Ende",
"attr.grid.extend": "Überstand (m)",
"attr.grid.bubbleMm": "Blase Ø (mm)",
"attr.grid.levels": "Sichtbar in",
"attr.grid.show3d": "Im 3D-Modell zeigen",
"attr.grid.levels.all": "Allen Geschossen",
"attr.grid.levels.here": "Nur diesem Geschoss",
"attr.dim.gap": "Abstand Hilfslinie (mm)",
"attr.dim.overshoot": "Überstand (mm)",
"attr.dim.tick": "Massstrich-Länge (mm)",
@@ -1766,6 +1779,23 @@ export const de = {
"cmd.revcloud.arcSize": "Beulengrösse",
"cmd.pointmarker.label": "Punktmarker",
"cmd.pointmarker.point": "Punkt:",
"cmd.grid.label": "Achsraster",
"cmd.grid.origin": "Ursprung des Achsrasters ( Radial ):",
"cmd.grid.radial": "Radial",
"cmd.grid.xs": "Feldweiten Achsen 1, 2, 3 … (z. B. 6 4.5 3x5, Enter = 6 6 6):",
"cmd.grid.ys": "Feldweiten Achsen A, B, C … (z. B. 5 5, Enter = 6 6):",
"cmd.grid.xsRadial": "Strahlwinkel in Grad (z. B. 8x45, Enter = 4x45):",
"cmd.grid.ysRadial": "Ringabstände ab der Mitte (z. B. 3 3 4):",
"cmd.dimradius.label": "Radiusmass",
"cmd.dimradius.first": "Kreis, Bogen oder Bogenwand anklicken:",
"cmd.dimdiameter.label": "Durchmessermass",
"cmd.dimdiameter.first": "Kreis, Bogen oder Bogenwand anklicken:",
"cmd.dimarc.label": "Bogenlänge",
"cmd.dimarc.first": "Bogenanfang auf Kreis, Bogen oder Bogenwand:",
"cmd.dimarc.second": "Bogenende:",
"cmd.dimarc.offset": "Lage der Masslinie:",
"history.cmd.grid": "Achsraster",
"history.cmd.dimround": "Radius-/Bogenmass",
"cmd.wipeout.label": "Maskenregion",
"cmd.wipeout.start": "Startpunkt:",
"cmd.wipeout.next": "Nächster Punkt:",
+30
View File
@@ -206,6 +206,8 @@ export const en: Record<TranslationKey, string> = {
"tool.revcloud.hint": "Revision cloud: click points like a polyline, Enter finishes open, clicking near start or \"Close\" closes it",
"tool.pointmarker": "Point marker",
"tool.pointmarker.hint": "Point marker: set a point — a cross-in-circle symbol marks a reference point",
"tool.grid": "Structural grid",
"tool.grid.hint": "Structural grid: set the origin, then enter bay widths — axes with bubbles in all plans, sections and elevations",
"tool.wipeout": "Mask region",
"tool.wipeout.hint": "Mask region: click points like a polyline, clicking near start or Enter (3+ points) closes and covers the drawing underneath",
"tool.text": "Text",
@@ -382,6 +384,17 @@ export const en: Record<TranslationKey, string> = {
"attr.ends.tick": "Tick",
"attr.ends.square": "Square",
"attr.dim.section": "Dimension",
"attr.grid.section": "Structural grid",
"attr.grid.bubbles": "Axis bubbles",
"attr.grid.bubbles.both": "Both ends",
"attr.grid.bubbles.start": "Start only",
"attr.grid.bubbles.end": "End only",
"attr.grid.extend": "Extension (m)",
"attr.grid.bubbleMm": "Bubble Ø (mm)",
"attr.grid.levels": "Visible on",
"attr.grid.show3d": "Show in 3D model",
"attr.grid.levels.all": "All levels",
"attr.grid.levels.here": "This level only",
"attr.dim.gap": "Extension gap (mm)",
"attr.dim.overshoot": "Overshoot (mm)",
"attr.dim.tick": "Tick length (mm)",
@@ -1755,6 +1768,23 @@ export const en: Record<TranslationKey, string> = {
"cmd.revcloud.arcSize": "Arc size",
"cmd.pointmarker.label": "Point marker",
"cmd.pointmarker.point": "Point:",
"cmd.grid.label": "Structural grid",
"cmd.grid.origin": "Grid origin ( Radial ):",
"cmd.grid.radial": "Radial",
"cmd.grid.xs": "Bay widths for axes 1, 2, 3 … (e.g. 6 4.5 3x5, Enter = 6 6 6):",
"cmd.grid.ys": "Bay widths for axes A, B, C … (e.g. 5 5, Enter = 6 6):",
"cmd.grid.xsRadial": "Ray angles in degrees (e.g. 8x45, Enter = 4x45):",
"cmd.grid.ysRadial": "Ring spacings from the centre (e.g. 3 3 4):",
"cmd.dimradius.label": "Radius dimension",
"cmd.dimradius.first": "Pick a circle, arc or arc wall:",
"cmd.dimdiameter.label": "Diameter dimension",
"cmd.dimdiameter.first": "Pick a circle, arc or arc wall:",
"cmd.dimarc.label": "Arc length",
"cmd.dimarc.first": "Arc start on a circle, arc or arc wall:",
"cmd.dimarc.second": "Arc end:",
"cmd.dimarc.offset": "Position of the dimension line:",
"history.cmd.grid": "Structural grid",
"history.cmd.dimround": "Radius/arc dimension",
"cmd.wipeout.label": "Mask region",
"cmd.wipeout.start": "Start point:",
"cmd.wipeout.next": "Next point:",
+36 -1
View File
@@ -521,7 +521,16 @@ export type CustomPalette = {
export type DetailLevel = "grob" | "mittel" | "fein";
/** Merkmal, an dem ein Bemassungspunkt hängt ([38], `dim_assoc.rs`). */
export type DimFeature = "wall" | "opening" | "vertex" | "edge" | "center" | "intersection";
export type DimFeature =
| "wall"
| "opening"
| "vertex"
| "edge"
| "center"
| "intersection"
| "axis"
| "axiscross"
| "rim";
/** Bezug eines Bemassungspunkts auf ein Element ([38]). */
export type DimRef = {
@@ -887,6 +896,11 @@ export type Drawing2DGeom =
* wenn ein Bezug ungültig wird. Fehlt das Feld, ist die Bemassung frei wie bisher.
*/
refs?: Array<DimRef | null>;
/**
* Art der Bemassung (fehlt = linear): Radius/Durchmesser (`pts` = Mittelpunkt, Punkt auf dem
* Kreis) und Bogenlänge (`pts` = Mittelpunkt, Bogenanfang, Bogenende).
*/
kind?: "radius" | "diameter" | "arc";
}
| {
shape: "kote";
@@ -921,6 +935,24 @@ export type Drawing2DGeom =
segments: number;
}
| { shape: "pointmarker"; at: Vec2 }
| {
shape: "grid";
origin: Vec2;
angle: number;
radial?: boolean;
a: Array<GridAxis>;
b: Array<GridAxis>;
/** Überstand der Achsen über die äusserste Querachse (Meter, Standard 1.5). */
extend?: number;
/** Enden mit Achsblase (Standard Anfang und Ende). */
bubbles?: "start" | "end" | "both";
/** Blasen-Durchmesser in Papier-mm (Standard 8). */
bubbleMm?: number;
/** Geschosse, in denen das Raster gezeigt wird; fehlt oder leer = in allen. */
levels?: Array<string>;
/** Im 3D-Modell als dünne Linien zeigen. */
show3d?: boolean;
}
| {
shape: "text";
at: Vec2;
@@ -1240,6 +1272,9 @@ export type FrameDetail = {
rebates?: OpeningSides;
};
/** Eine Achse des Achsrasters: Beschriftung und Lage (Abstand bzw. Winkel/Radius, s. `Grid`). */
export type GridAxis = { label: string; pos: number };
/**
* Raster-Regel: generiert Wände entlang gleichmäßiger X-/Y-Achsen.
* Typischer Anwendungsfall: Tragwerks-Achsraster (z. B. 3 m Abstand).
+39
View File
@@ -501,6 +501,45 @@ export function AttributesPanel() {
(Modellmass, s. `model/dimension.ts`); leer/0 fällt auf den
Standard zurück. Die Masszahl selbst wird direkt im Plan am
eigenen Griff verschoben (rastet nahe der Standardlage ein). */}
{drawing?.geom.shape === "grid" && (() => {
const geom = drawing.geom as Extract<typeof drawing.geom, { shape: "grid" }>;
const here = geom.levels?.includes(drawing.levelId) && geom.levels.length === 1;
return (
<>
<div className="attr-section-label">{t("attr.grid.section")}</div>
<span className="attr-key">{t("attr.grid.bubbles")}</span>
<span className="attr-val">
<select value={geom.bubbles ?? "both"} onChange={(e) => host.onSetGridProps(drawing.id, { bubbles: e.target.value as "start" | "end" | "both" })}>
<option value="both">{t("attr.grid.bubbles.both")}</option>
<option value="start">{t("attr.grid.bubbles.start")}</option>
<option value="end">{t("attr.grid.bubbles.end")}</option>
</select>
</span>
<span className="attr-key">{t("attr.grid.extend")}</span>
<span className="attr-val">
<input className="attr-num" style={{ width: 72 }} type="number" step={0.1} min={0} value={geom.extend ?? 1.5}
onChange={(e) => { const v = Number(e.target.value); if (Number.isFinite(v) && v >= 0) host.onSetGridProps(drawing.id, { extend: v }); }} />
</span>
<span className="attr-key">{t("attr.grid.bubbleMm")}</span>
<span className="attr-val">
<input className="attr-num" style={{ width: 72 }} type="number" step={0.5} min={2} value={geom.bubbleMm ?? 8}
onChange={(e) => { const v = Number(e.target.value); if (Number.isFinite(v) && v >= 2) host.onSetGridProps(drawing.id, { bubbleMm: v }); }} />
</span>
<span className="attr-key">{t("attr.grid.show3d")}</span>
<span className="attr-val">
<input type="checkbox" checked={geom.show3d === true} onChange={(e) => host.onSetGridProps(drawing.id, { show3d: e.target.checked })} />
</span>
<span className="attr-key">{t("attr.grid.levels")}</span>
<span className="attr-val">
<select value={here ? "here" : "all"} onChange={(e) => host.onSetGridProps(drawing.id, { levels: e.target.value === "here" ? [drawing.levelId] : undefined })}>
<option value="all">{t("attr.grid.levels.all")}</option>
<option value="here">{t("attr.grid.levels.here")}</option>
</select>
</span>
</>
);
})()}
{drawing?.geom.shape === "dimension" && (
<>
<div className="attr-section-label">{t("attr.dim.section")}</div>
+12
View File
@@ -253,6 +253,17 @@ export function ToolIcon({ id }: { id: ToolId }) {
/>
</svg>
);
case "grid":
// Achsraster: zwei Achsen mit Blasen.
return (
<svg {...common}>
<line x1="5" y1="5" x2="5" y2="15" strokeDasharray="2 1" />
<line x1="11" y1="5" x2="11" y2="15" strokeDasharray="2 1" />
<line x1="1" y1="10" x2="15" y2="10" strokeDasharray="2 1" />
<circle cx="5" cy="3" r="2" fill="none" />
<circle cx="11" cy="3" r="2" fill="none" />
</svg>
);
case "pointmarker":
// Kreuz-in-Kreis (Punkt-/Knotenmarker).
return (
@@ -347,6 +358,7 @@ const TOOLS_2D: ToolId[] = [
"scalebar",
"revcloud",
"pointmarker",
"grid",
"wipeout",
"text",
"leader",
+5
View File
@@ -297,6 +297,11 @@ export interface PanelHostValue {
drawingId: string,
patch: { start?: EndMark; end?: EndMark; sizeMm?: number },
) => void;
/** Achsraster ([112]): Blasenseite, Überstand (m), Blasen-Ø (Papier-mm), Geschosse (leer = alle). */
onSetGridProps: (
drawingId: string,
patch: { bubbles?: "start" | "end" | "both"; extend?: number; bubbleMm?: number; levels?: string[] | undefined; show3d?: boolean },
) => void;
onSetDimensionStyle: (
drawingId: string,
patch: {
+3 -1
View File
@@ -118,12 +118,14 @@ export function levelArg(level: DrawingLevel) {
export function generateSectionPlan(
output: SectionOutput,
mono = false,
opts: { hiddenLines?: boolean; visibleCodes?: Set<string>; categoryDisplay?: CategoryDisplayResolver; openings?: boolean } = {},
opts: { hiddenLines?: boolean; visibleCodes?: Set<string>; categoryDisplay?: CategoryDisplayResolver; openings?: boolean; scaleDenominator?: number } = {},
): Plan {
const { project, level } = output;
const text = JSON.stringify({
level: levelArg(level),
hiddenLines: !!opts.hiddenLines,
// Massstabsnenner für die Achsblasen des Rasters ([112]); Default 100.
scale: opts.scaleDenominator ?? 100,
...visibilityArgs(project, opts.visibleCodes, opts.categoryDisplay),
});
const args = output.bodies.slice();
+57
View File
@@ -0,0 +1,57 @@
// [112]/[38] Achsraster und Bemassung im Store: eine Bemassung zwischen zwei Achsen folgt der verschobenen
// Achse (Kern führt `pts` im selben Undo-Schritt nach); Rundmass folgt dem Kreis; Achsfang im Kern.
import { describe, it, expect, beforeEach } from "vitest";
import { getState, setState } from "./appStore";
import { emptyProject } from "../model/sampleProject";
import { addItems, cmdMutation, patchItem } from "../core";
import type { Drawing2D } from "../model/types";
const dims = (): Drawing2D[] => getState().project.drawings2d.filter((d) => d.geom.shape === "dimension");
const xs = (d: Drawing2D): number[] => (d.geom.shape === "dimension" ? d.geom.pts.map((q) => q.x) : []);
beforeEach(() => {
setState({ project: emptyProject, undoDepth: 0, redoDepth: 0, canUndo: false, canRedo: false });
getState().clearHistory();
getState().setProject(cmdMutation({ cmd: "grid", at: [2, 1], xs: "6 6", ys: "5", ctx: { level: "eg", cat: "20" }, stamp: "g" }));
});
describe("Achsraster im Store", () => {
it("Bemassung zwischen zwei Achsen: Achse verschieben → Mass folgt, ein Undo-Schritt", () => {
const grid = getState().project.drawings2d.find((d) => d.geom.shape === "grid")!;
expect(grid).toBeDefined();
// Achse 1 bei x = 2, Achse 2 bei x = 8, Kette auf y = 3 zwischen den gefangenen Achspunkten.
getState().setProject(cmdMutation({ cmd: "dimension", pts: [[2, 3], [8, 3]], snaps: [[2, 3], [8, 3]], offset: 1, ctx: { level: "eg" }, stamp: "t" }));
const d0 = dims()[0];
expect(d0.geom.shape === "dimension" && d0.geom.refs?.map((r) => r?.feature)).toEqual(["axis", "axis"]);
expect(xs(d0)).toEqual([2, 8]);
getState().applyChange((p) =>
patchItem(p, "drawings2d", grid.id, (d) => (d.geom.shape === "grid" ? { ...d, geom: { ...d.geom, a: d.geom.a.map((x) => (x.label === "2" ? { ...x, pos: 7.5 } : x)) } } : d)),
);
expect(xs(dims()[0])).toEqual([2, 9.5]);
getState().undo();
expect(xs(dims()[0])).toEqual([2, 8]);
getState().redo();
expect(xs(dims()[0])).toEqual([2, 9.5]);
});
it("Raster verschieben mit der Bemassung bleibt verbunden; Achsschnittpunkt hängt als axiscross an", () => {
getState().setProject(cmdMutation({ cmd: "dimension", pts: [[2, 1], [8, 1]], snaps: [[2, 1], [8, 1]], offset: 1, ctx: { level: "eg" }, stamp: "t" }));
const d = dims()[0];
expect(d.geom.shape === "dimension" && d.geom.refs?.map((r) => r?.feature)).toEqual(["axiscross", "axiscross"]);
// Ursprung des Rasters um (1, 0) verschieben → Punkte folgen.
const grid = getState().project.drawings2d.find((x) => x.geom.shape === "grid")!;
getState().applyChange((p) => patchItem(p, "drawings2d", grid.id, (x) => (x.geom.shape === "grid" ? { ...x, geom: { ...x.geom, origin: { x: 3, y: 1 } } } : x)));
expect(xs(dims()[0])).toEqual([3, 9]);
});
it("Radiusmass folgt dem Kreis", () => {
getState().applyChange(
addItems("drawings2d", [{ id: "K", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "circle", center: { x: 20, y: 20 }, r: 2 } } as Drawing2D]),
);
getState().setProject(cmdMutation({ cmd: "dimround", kind: "radius", pts: [[22, 20]], ctx: { level: "eg" }, stamp: "r" }));
getState().applyChange((p) => patchItem(p, "drawings2d", "K", (x) => (x.geom.shape === "circle" ? { ...x, geom: { ...x.geom, center: { x: 30, y: 20 }, r: 3 } } : x)));
const d = dims()[0];
expect(d.geom.shape === "dimension" && d.geom.pts).toEqual([{ x: 30, y: 20 }, { x: 33, y: 20 }]);
});
});
+11
View File
@@ -602,6 +602,17 @@ export function usePanelHostBase(opts: {
patchItem(p, "drawings2d", drawingId, (d) => ({ ...d, endMarks: { ...d.endMarks, ...patch } })),
),
),
onSetGridProps: (drawingId, patch) =>
setProject(
opsMutation((p) =>
patchItem(p, "drawings2d", drawingId, (d) => {
if (d.geom.shape !== "grid") return d;
const geom = { ...d.geom, ...patch };
if (patch.levels === undefined && "levels" in patch) delete geom.levels;
return { ...d, geom };
}),
),
),
onSetDimensionStyle: (drawingId, patch) =>
setProject(
opsMutation((p) =>
+13
View File
@@ -346,6 +346,18 @@ const pointmarkerTool: Tool = {
onCancel: (s) => [s, { draft: null, done: true }],
};
// Achsraster ([112]): Platzhalter-Werkzeug, gekoppelt an den `grid`-Befehl (Ursprung + Feldweiten).
const gridTool: Tool = {
id: "grid",
labelKey: "tool.grid",
hintKey: () => "tool.grid.hint",
init: () => ({ phase: "idle" }),
onClick: (s) => [s, { draft: null }],
onMove: (s) => [s, { draft: null }],
onCommitGesture: (s) => [s, { draft: null, done: true }],
onCancel: (s) => [s, { draft: null, done: true }],
};
// Wipeout/Maskenregion: Platzhalter-Werkzeug, gekoppelt an den
// `wipeout`-Befehl (Punktfolge, schliesst automatisch → weisse Maskenfläche).
// Freies 2D-Element (nicht floorOnly).
@@ -456,6 +468,7 @@ const TOOLS: Record<ToolId, Tool> = {
scalebar: scalebarTool,
revcloud: revcloudTool,
pointmarker: pointmarkerTool,
grid: gridTool,
wipeout: wipeoutTool,
text: textTool,
leader: leaderTool,
+1
View File
@@ -35,6 +35,7 @@ export type ToolId =
| "scalebar"
| "revcloud"
| "pointmarker"
| "grid"
| "wipeout"
| "text"
| "leader"
+1
View File
@@ -47,5 +47,6 @@ export function drawingMoveAnchor(d: Drawing2D, verts: Vec2[]): Vec2 | null {
const g = d.geom;
if (g.shape === "circle" || g.shape === "arc" || g.shape === "ellipse") return g.center;
if (g.shape === "text" || g.shape === "kote" || g.shape === "detailref" || g.shape === "scalebar" || g.shape === "pointmarker") return g.at;
if (g.shape === "grid") return g.origin;
return null;
}
+3 -2
View File
@@ -669,7 +669,7 @@ function useCrossKindOverlay(
} else if (l.kind === "section") {
const sOut = sectionOutputs[l.id];
prims = sOut
? generateSectionPlan(sOut, mono, { hiddenLines: l.hiddenLines, visibleCodes, categoryDisplay })
? generateSectionPlan(sOut, mono, { hiddenLines: l.hiddenLines, visibleCodes, categoryDisplay, scaleDenominator })
.primitives
: [];
} else {
@@ -1155,9 +1155,10 @@ function SectionPlanView({
visibleCodes,
categoryDisplay,
openings: true,
scaleDenominator,
})
: null,
[isElevation, output, mono, level.hiddenLines, visibleCodes, categoryDisplay, inputs],
[isElevation, output, mono, level.hiddenLines, visibleCodes, categoryDisplay, inputs, scaleDenominator],
);
const rawPlan = isElevation ? elevationPlan : sectionPlan;
// Grundriss-Unterlage (Nutzer-Wunsch: "in der Ansicht auch mal einen