Stütze: Mitte verschiebt, Eck-Griffe setzen Breite/Tiefe symmetrisch um die Mitte (auch gedreht), Rundprofil Radius-Griff, Dreh-Griff (Kern grips.rs columnGrip). Freier Körper: Profil-Ecken + Verschiebe-Griff, Kreis/B-Rep nur verschieben (solidGrip). Bibliotheks-Objekt: Dreh-Griff neben dem Einfügepunkt. Rust-Tests + e2e grips333.
2808 lines
148 KiB
Rust
2808 lines
148 KiB
Rust
//! Griff-, Kanten- und Grössen-Geometrie der Bauteile ([K4] S3, vorher `state/projectSlice.ts` und
|
||
//! `state/edgeGrips.ts`): Eckpunkt-Griff ziehen (`moveGrip`), Element verschieben (`moveElementBy`),
|
||
//! Kante parallel verschieben (`moveEdge`, winkeltreu an den Nachbarkanten), Grösse um einen Anker
|
||
//! (`resizeElement`), Decken-/Dach-/Treppen-/Raum-Griffe, Raumstempel, Polylinien-Punkt einfügen/
|
||
//! löschen und die Dicke einschichtiger Wände/Decken. Dazu die Griff-Listen (`drawingVertices`) und
|
||
//! die Kanten-Griffe (`ringEdges`/`openEdges`) für die Anzeige.
|
||
//!
|
||
//! Rechnung auf der rohen Projekt-Wurzel (`serde_json`, verlustfrei): ein geändertes Element behält
|
||
//! unbekannte Felder und die Schlüsselreihenfolge, genau wie das Objekt-Spreizen (`{...d, geom}`) in TS.
|
||
//! Ergebnis sind Ops (`replace`/`add`); keine Op, wo die TS-Fassung dasselbe Objekt zurückgab.
|
||
//! Zahlen wie in JS (`jsnum`, `jsmath`); nicht endliche Ergebnisse reisen als Marken (`"\u{1}NaN"`,
|
||
//! s. `ops.rs`), damit die Prüfung des Dokuments sie wie bisher zurückweist.
|
||
//!
|
||
//! Abweichung (gewollt): Ein Griff-Index, unter dem kein Punkt liegt (negativ, gebrochen, zu gross), ist
|
||
//! keine Änderung — TS warf dort beim Lesen von `undefined` einen Fehler.
|
||
|
||
pub use crate::document::Lookup;
|
||
use crate::jsmath::hypot2;
|
||
use crate::jsnum;
|
||
use crate::json_util::{arr, field, js_num, num_of, num_or, pt, truthy, with, with_all, with_opt, xy, N};
|
||
use crate::ops::{id_of, Op};
|
||
use serde_json::{Map, Value};
|
||
|
||
fn nullish(v: Option<&Value>) -> bool {
|
||
matches!(v, None | Some(Value::Null))
|
||
}
|
||
|
||
/// Zahl, die TS teils unverändert durchreicht (`ry: g.ry`): Wert für die Rechnung und JSON-Wert
|
||
/// (`None` = fehlend/`undefined`; ein `null` bleibt `null`).
|
||
#[derive(Clone)]
|
||
struct Pass {
|
||
f: f64,
|
||
v: Option<Value>,
|
||
}
|
||
|
||
/// Unverändert durchgereichtes Feld.
|
||
fn pass(v: Option<&Value>) -> Pass {
|
||
Pass { f: num_of(v), v: v.cloned() }
|
||
}
|
||
|
||
/// Neu gerechnete Zahl.
|
||
fn calc(f: f64) -> Pass {
|
||
Pass { f, v: Some(js_num(f)) }
|
||
}
|
||
|
||
/// Ganzzahliger Index in `0..len` (JS: `list[i]` trifft nur dann ein Element).
|
||
fn index_in(i: f64, len: usize) -> Option<usize> {
|
||
(i.fract() == 0.0 && i >= 0.0 && i < len as f64).then_some(i as usize)
|
||
}
|
||
|
||
fn eq_index(i: usize, index: f64) -> bool {
|
||
i as f64 == index
|
||
}
|
||
|
||
/// `pts.map((p, i) => i === index ? new : p)`.
|
||
fn replace_at(list: &[Value], index: f64, new: &Value) -> Value {
|
||
Value::Array(list.iter().enumerate().map(|(i, p)| if eq_index(i, index) { new.clone() } else { p.clone() }).collect())
|
||
}
|
||
|
||
fn moved(p: &Value, dx: f64, dy: f64) -> Value {
|
||
let (x, y) = xy(p);
|
||
pt(x + dx, y + dy)
|
||
}
|
||
|
||
fn moved_all(list: &[Value], dx: f64, dy: f64) -> Value {
|
||
Value::Array(list.iter().map(|p| moved(p, dx, dy)).collect())
|
||
}
|
||
|
||
fn find<'a>(root: &'a Map<String, Value>, collection: &str, id: &str) -> Option<&'a Value> {
|
||
arr(root.get(collection)).iter().find(|e| id_of(e) == Some(id))
|
||
}
|
||
|
||
/// Mittelwert der Ecken eines Umrisses (Griff-Lage der Sohlenhöhe einer Baugruben).
|
||
pub fn ring_centroid(ring: &[Value]) -> (f64, f64) {
|
||
let n = ring.len().max(1) as f64;
|
||
let (sx, sy) = ring.iter().map(xy).fold((0.0, 0.0), |a, p| (a.0 + p.0, a.1 + p.1));
|
||
(sx / n, sy / n)
|
||
}
|
||
|
||
fn replace(collection: &str, entity: Value) -> Op {
|
||
Op::Replace { collection: collection.into(), entity }
|
||
}
|
||
|
||
fn with_geom(d: &Value, g: Value) -> Value {
|
||
with(d, "geom", g)
|
||
}
|
||
|
||
/// [333] Abstand des Dreh-Griffs eines Bibliotheks-Objekts vom Einfügepunkt (m).
|
||
const LIBOBJ_ROT_ARM: f64 = 0.6;
|
||
|
||
/// Kleinste Stützenkante/-radius beim Ziehen (m).
|
||
const COLUMN_MIN: f64 = 0.05;
|
||
|
||
/// [333] Stützen-Griff `index` nach (x, y) ziehen (s. `columnGrip`); `None` = nichts ändern.
|
||
fn column_grip(e: &Value, index: f64, x: f64, y: f64) -> Option<Value> {
|
||
if truthy(field(e, "locked")) || !(x.is_finite() && y.is_finite()) {
|
||
return None;
|
||
}
|
||
let (px, py) = xy(field(e, "position")?);
|
||
if index == 0.0 {
|
||
return Some(with(e, "position", pt(x, y)));
|
||
}
|
||
let prof = field(e, "profile")?;
|
||
let (dx, dy) = (x - px, y - py);
|
||
match prof.get("kind").and_then(Value::as_str)? {
|
||
"round" if index == 1.0 => {
|
||
let rad = jsnum::max(COLUMN_MIN / 2.0, hypot2(dx, dy));
|
||
Some(with(e, "profile", with(prof, "radius", js_num(rad))))
|
||
}
|
||
"rect" if (1.0..=4.0).contains(&index) => {
|
||
let rot = num_of(field(e, "rotation"));
|
||
let (c, s) = (jsnum::cos(rot), jsnum::sin(rot));
|
||
let (lx, ly) = (dx * c + dy * s, -dx * s + dy * c);
|
||
let w = jsnum::max(COLUMN_MIN, 2.0 * lx.abs());
|
||
let d = jsnum::max(COLUMN_MIN, 2.0 * ly.abs());
|
||
Some(with(e, "profile", with_all(prof, vec![("width", js_num(w)), ("depth", js_num(d))])))
|
||
}
|
||
"rect" if index == 5.0 => {
|
||
if hypot2(dx, dy) < 1e-9 {
|
||
return None;
|
||
}
|
||
Some(with(e, "rotation", js_num(jsnum::atan2(dy, dx))))
|
||
}
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
/// [333] Griff eines freien Körpers (s. `solidGrip`).
|
||
fn solid_grip(e: &Value, index: f64, x: f64, y: f64) -> Option<Value> {
|
||
if truthy(field(e, "locked")) || !(x.is_finite() && y.is_finite()) {
|
||
return None;
|
||
}
|
||
let ring = field(e, "points")?.as_array()?;
|
||
let derived = field(e, "circle").is_some_and(|c| !c.is_null()) || field(e, "brep").is_some_and(|c| !c.is_null());
|
||
if let Some(i) = index_in(index, ring.len()) {
|
||
if derived {
|
||
return None;
|
||
}
|
||
return Some(with(e, "points", replace_at(ring, i as f64, &pt(x, y))));
|
||
}
|
||
if index != ring.len() as f64 {
|
||
return None;
|
||
}
|
||
let c = ring_centroid(ring);
|
||
let (dx, dy) = (x - c.0, y - c.1);
|
||
let moved_e = with(e, "points", moved_all(ring, dx, dy));
|
||
match field(e, "circle") {
|
||
Some(circ) if !circ.is_null() => {
|
||
let (cx, cy) = xy(field(circ, "center")?);
|
||
Some(with(&moved_e, "circle", with(circ, "center", pt(cx + dx, cy + dy))))
|
||
}
|
||
_ => Some(moved_e),
|
||
}
|
||
}
|
||
|
||
// ── Anfrage ──────────────────────────────────────────────────────────────────
|
||
|
||
/// Eine Änderung aus den Griff-Aktionen des Stores (`GripRequest` in `geometry/grips.ts`); Zahlen dürfen
|
||
/// Nicht-endlich-Marken sein. Typisiert gelesen (je Mausschritt billiger als ein JSON-Baum).
|
||
#[derive(serde::Deserialize, Default, Debug)]
|
||
#[serde(default, rename_all = "camelCase")]
|
||
pub struct Request {
|
||
pub op: String,
|
||
drawing_id: Option<String>,
|
||
wall_id: Option<String>,
|
||
id: Option<String>,
|
||
kind: Option<String>,
|
||
new_id: Option<String>,
|
||
new_name: Value,
|
||
index: N,
|
||
a: N,
|
||
b: N,
|
||
seg: N,
|
||
scale: N,
|
||
w: N,
|
||
h: N,
|
||
fx: N,
|
||
fy: N,
|
||
/// [T2] Getippte Bogenlänge (Tab) beim Endpunkt-Griff einer Bogenwand; fehlt = NaN = Cursor.
|
||
arc_length: N,
|
||
/// [176] Aufräum-Abstand (m) für `sectionLineTidy` (Zeiger-Genauigkeit der Ansicht); fehlt = NaN = 5 mm.
|
||
tol: N,
|
||
thickness: N,
|
||
pt: [N; 2],
|
||
delta: [N; 2],
|
||
/// Punkttyp der Polylinie (`vertexType`: "corner" | "arc" | "spline").
|
||
vertex_type: Option<String>,
|
||
/// Modifikator gehalten: Masszahl-Griff frei ohne Einrasten ([172], Alt), Scheitel-Griff einer Bogenwand mit
|
||
/// festem Mittelpunkt statt festen Endpunkten ([T2], Shift) — die Hülle setzt es je nach Griff.
|
||
free: bool,
|
||
}
|
||
|
||
impl Request {
|
||
fn n(&self, k: &str) -> f64 {
|
||
match k {
|
||
"index" => self.index.0,
|
||
"a" => self.a.0,
|
||
"b" => self.b.0,
|
||
"seg" => self.seg.0,
|
||
"scale" => self.scale.0,
|
||
"w" => self.w.0,
|
||
"h" => self.h.0,
|
||
"fx" => self.fx.0,
|
||
"fy" => self.fy.0,
|
||
"arcLength" => self.arc_length.0,
|
||
"tol" => self.tol.0,
|
||
_ => self.thickness.0,
|
||
}
|
||
}
|
||
/// Text-Feld; leer = fehlend (JS-Wahrheitswert der ids).
|
||
fn s(&self, k: &str) -> Option<&str> {
|
||
let v = match k {
|
||
"drawingId" => &self.drawing_id,
|
||
"wallId" => &self.wall_id,
|
||
"kind" => &self.kind,
|
||
"newId" => &self.new_id,
|
||
_ => &self.id,
|
||
};
|
||
v.as_deref().filter(|s| !s.is_empty())
|
||
}
|
||
/// Punkt als `[x, y]`.
|
||
fn p(&self, k: &str) -> (f64, f64) {
|
||
let [x, y] = if k == "pt" { self.pt } else { self.delta };
|
||
(x.0, y.0)
|
||
}
|
||
}
|
||
|
||
/// Ergebnis: Ops und ggf. ein Hinweis-Schlüssel für die Hülle (i18n, z. B. zu wenige Punkte).
|
||
#[derive(Default)]
|
||
pub struct GripResult {
|
||
pub ops: Vec<Op>,
|
||
pub notice: Option<&'static str>,
|
||
/// Zahlen/Texte für den Hinweis ([190]); die Antwort trägt sie als `Schlüssel|arg|arg` im Feld `notice`.
|
||
pub notice_args: Vec<String>,
|
||
}
|
||
|
||
impl From<Vec<Op>> for GripResult {
|
||
fn from(ops: Vec<Op>) -> Self {
|
||
GripResult { ops, notice: None, notice_args: vec![] }
|
||
}
|
||
}
|
||
|
||
/// Antwort-JSON `{"ops": […], "notice": …}` (Ops wie `CoreOp` in TS; `replace` ohne Kopie des Elements).
|
||
pub fn result_json(r: &GripResult) -> String {
|
||
// Direkt in einen Puffer (`to_writer`; `to_string` ginge über `fmt::Display` und wäre langsamer).
|
||
let mut out: Vec<u8> = b"{\"ops\":[".to_vec();
|
||
for (i, op) in r.ops.iter().enumerate() {
|
||
if i > 0 {
|
||
out.push(b',');
|
||
}
|
||
let _ = match op {
|
||
Op::Replace { collection, entity } => {
|
||
out.extend_from_slice(b"{\"kind\":\"replace\",\"collection\":");
|
||
let _ = serde_json::to_writer(&mut out, collection);
|
||
out.extend_from_slice(b",\"entity\":");
|
||
let w = serde_json::to_writer(&mut out, entity);
|
||
out.push(b'}');
|
||
w
|
||
}
|
||
op => serde_json::to_writer(&mut out, &op.to_json()),
|
||
};
|
||
}
|
||
out.push(b']');
|
||
if let Some(n) = r.notice {
|
||
out.extend_from_slice(b",\"notice\":");
|
||
let _ = if r.notice_args.is_empty() { serde_json::to_writer(&mut out, n) } else { serde_json::to_writer(&mut out, &format!("{n}|{}", r.notice_args.join("|"))) };
|
||
}
|
||
out.push(b'}');
|
||
String::from_utf8(out).unwrap_or_default()
|
||
}
|
||
|
||
/// Wie [`run`] auf dem Dokument. [202] Treppe als Ganzes ziehen (`stairBy`): das Deckenloch, in dem sie
|
||
/// ankommt, wandert um denselben Vektor mit (`stair_guard::carried_holes`, braucht die typisierte Sicht);
|
||
/// beides in einem Op-Satz, also ein Undo-Schritt.
|
||
pub fn run_doc(d: &mut crate::document::Document, req: &Request) -> Result<GripResult, String> {
|
||
if req.op != "stairBy" {
|
||
return run(&d.lookup(), req);
|
||
}
|
||
let (p, lk) = d.project_lookup()?;
|
||
let mut res = run(&lk, req)?;
|
||
if let (false, Some(id)) = (res.ops.is_empty(), req.s("id")) {
|
||
let (dx, dy) = req.p("delta");
|
||
let holes = crate::stair_guard::carried_holes(p, &|s| s == id, &|_| false, &|_| false);
|
||
res.ops.extend(crate::cmd_transform::carry_hole_ops(lk.root, p, &holes, &crate::cmd_transform::Xf::translate(dx, dy)));
|
||
}
|
||
Ok(res)
|
||
}
|
||
|
||
/// Führt eine Griff-Änderung aus (`req.op` wählt die Art, s. `src/state/gripOps.ts`). Das Element
|
||
/// sucht `lk` (im Dokument über den Positions-Index, je Mausschritt keine lineare Suche).
|
||
pub fn run(lk: &Lookup, req: &Request) -> Result<GripResult, String> {
|
||
let root = lk.root;
|
||
let r = req;
|
||
let op = req.op.as_str();
|
||
let patch = |coll: &str, id: Option<&str>, f: &dyn Fn(&Value) -> Option<Value>| -> Vec<Op> {
|
||
id.and_then(|id| lk.find(coll, id)).and_then(f).map(|e| vec![replace(coll, e)]).unwrap_or_default()
|
||
};
|
||
Ok(match op {
|
||
"moveGrip" | "moveBy" | "moveEdge" => {
|
||
let (did, wid) = (r.s("drawingId"), r.s("wallId"));
|
||
// Jedes Element nur einmal suchen.
|
||
let d = did.and_then(|i| lk.find("drawings2d", i));
|
||
let w = wid.and_then(|i| lk.find("walls", i));
|
||
// Objekt-Sperre: gesperrte Elemente lassen sich anwählen, aber nicht ziehen.
|
||
if d.is_some_and(|d| truthy(field(d, "locked"))) || w.is_some_and(|w| truthy(field(w, "locked"))) {
|
||
return Ok(GripResult::default());
|
||
}
|
||
let f: Box<dyn Fn(&Value, bool) -> Option<Value>> = match op {
|
||
"moveGrip" => {
|
||
let (index, (x, y), scale, free, arc_length) = (r.n("index"), r.p("pt"), r.n("scale"), r.free, r.n("arcLength"));
|
||
Box::new(move |e, wall| if wall { Some(wall_grip(e, index, x, y, free, arc_length)) } else { drawing_grip(e, index, x, y, scale, free) })
|
||
}
|
||
"moveBy" => {
|
||
let (dx, dy) = r.p("delta");
|
||
Box::new(move |e, wall| if wall { Some(wall_moved(e, dx, dy)) } else { drawing_moved(e, dx, dy) })
|
||
}
|
||
_ => {
|
||
let (a, b, (dx, dy)) = (r.n("a"), r.n("b"), r.p("delta"));
|
||
Box::new(move |e, wall| if wall { Some(wall_moved(e, dx, dy)) } else { drawing_edge(e, a, b, dx, dy) })
|
||
}
|
||
};
|
||
// Mit Zeichnung wird nur sie geändert (die Wand zählt dann nur für die Sperre).
|
||
let (coll, e, wall) = if did.is_some() { ("drawings2d", d, false) } else { ("walls", w, true) };
|
||
let Some((old, new)) = e.and_then(|e| f(e, wall).map(|n| (e, n))) else { return Ok(GripResult::default()) };
|
||
let mut ops = Vec::new();
|
||
// [188] Wand kürzen/verlängern: Öffnungen bleiben an ihrer Stelle im Plan (ihre Position zählt ab
|
||
// Wandanfang — ohne Ausgleich wanderten sie beim Ziehen des Anfangspunkts mit).
|
||
if wall && op == "moveGrip" {
|
||
ops.extend(openings_keep_place(root, old, &new));
|
||
}
|
||
ops.insert(0, replace(coll, new));
|
||
ops.into()
|
||
}
|
||
"resize" => {
|
||
let (w, h, fx, fy) = (r.n("w"), r.n("h"), r.n("fx"), r.n("fy"));
|
||
if r.s("kind") == Some("drawing2d") {
|
||
patch("drawings2d", r.s("id"), &|d| resize_geom(field(d, "geom")?, w, h, fx, fy).map(|g| with_geom(d, g))).into()
|
||
} else {
|
||
patch("walls", r.s("id"), &|wall| {
|
||
let s = xy(field(wall, "start").unwrap_or(&Value::Null));
|
||
let e = xy(field(wall, "end").unwrap_or(&Value::Null));
|
||
let (ax, ay, sx, sy) = scale_around(bbox(&[s, e]), w, h, fx, fy);
|
||
let f = |p: (f64, f64)| pt(ax + (p.0 - ax) * sx, ay + (p.1 - ay) * sy);
|
||
// Bogenwand: negativer Massstab (Spiegelung) kehrt den Bogen um.
|
||
match field(wall, "bulge").and_then(Value::as_f64) {
|
||
Some(b) if sx * sy < 0.0 => Some(with_all(wall, vec![("start", f(s)), ("end", f(e)), ("bulge", js_num(-b))])),
|
||
_ => Some(with_all(wall, vec![("start", f(s)), ("end", f(e))])),
|
||
}
|
||
})
|
||
.into()
|
||
}
|
||
}
|
||
// [333] Stütze im Grundriss: Griff 0 = Mitte (verschiebt), Rechteck: 1..4 = Ecken (Querschnitt symmetrisch um die Mitte,
|
||
// im gedrehten Profil-Rahmen: Breite = 2·|lx|, Tiefe = 2·|ly|), 5 = Dreh-Griff auf der lokalen +x-Achse;
|
||
// Rundprofil: 1 = Radius-Griff.
|
||
"columnGrip" => {
|
||
let (index, (x, y)) = (r.n("index"), r.p("pt"));
|
||
patch("columns", r.s("id"), &|e| column_grip(e, index, x, y)).into()
|
||
}
|
||
// [333] Freier Körper im Grundriss: Index < Eckenzahl = Profil-Ecke; Index = Eckenzahl = Verschiebe-Griff (Ziel = neue
|
||
// Lage des Profil-Mittelpunkts). Kreis- und B-Rep-Körper nur verschieben (ihr Profil ist abgeleitet).
|
||
"solidGrip" => {
|
||
let (index, (x, y)) = (r.n("index"), r.p("pt"));
|
||
patch("extrudedSolids", r.s("id"), &|e| solid_grip(e, index, x, y)).into()
|
||
}
|
||
// [213] Kamera: Griff 0 Standpunkt, 1 Ziel, 2 Bildwinkel/Sichtbreite; `cameraBy` verschiebt Standpunkt und Ziel.
|
||
"cameraGrip" | "cameraBy" => {
|
||
let (index, (x, y), (dx, dy)) = (r.n("index"), r.p("pt"), r.p("delta"));
|
||
patch("cameras", r.s("id"), &|e| {
|
||
if truthy(field(e, "locked")) {
|
||
return None;
|
||
}
|
||
let cam: crate::model::Camera = serde_json::from_value(e.clone()).ok()?;
|
||
let next = if op == "cameraGrip" { crate::camera::grip_edit(&cam, index, x, y)? } else { crate::camera::moved(&cam, dx, dy)? };
|
||
serde_json::to_value(next).ok()
|
||
})
|
||
.into()
|
||
}
|
||
// [280] Träger: Griff 0 = Anfang, 1 = Ende der Achse, 2 = Mitte (verschiebt den ganzen Träger).
|
||
"beamGrip" => {
|
||
let (index, (x, y)) = (r.n("index"), r.p("pt"));
|
||
patch("beams", r.s("id"), &|e| {
|
||
if truthy(field(e, "locked")) {
|
||
return None;
|
||
}
|
||
let (s, t) = (xy(field(e, "start")?), xy(field(e, "end")?));
|
||
if index == 0.0 {
|
||
Some(with(e, "start", pt(x, y)))
|
||
} else if index == 1.0 {
|
||
Some(with(e, "end", pt(x, y)))
|
||
} else if index == 2.0 {
|
||
let (dx, dy) = (x - (s.0 + t.0) / 2.0, y - (s.1 + t.1) / 2.0);
|
||
Some(with_all(e, vec![("start", pt(s.0 + dx, s.1 + dy)), ("end", pt(t.0 + dx, t.1 + dy))]))
|
||
} else {
|
||
None
|
||
}
|
||
})
|
||
.into()
|
||
}
|
||
// [281] Gefällelinie einer geneigten Decke: Griff 0 = Bezugspunkt `slope.from`, 1 = `slope.to`. Das Gefälle in %
|
||
// (rise / Länge) bleibt, der Höhenunterschied passt sich der neuen Länge an (wie die Objekt-Info).
|
||
"ceilingSlopeGrip" => {
|
||
let (index, (x, y)) = (r.n("index"), r.p("pt"));
|
||
patch("ceilings", r.s("id"), &|e| {
|
||
if truthy(field(e, "locked")) || !(index == 0.0 || index == 1.0) {
|
||
return None;
|
||
}
|
||
let sl = field(e, "slope")?;
|
||
let (a, b) = (xy(field(sl, "from")?), xy(field(sl, "to")?));
|
||
let rise = num_of(field(sl, "rise"));
|
||
let len = hypot2(b.0 - a.0, b.1 - a.1);
|
||
let (na, nb) = if index == 0.0 { ((x, y), b) } else { (a, (x, y)) };
|
||
let nlen = hypot2(nb.0 - na.0, nb.1 - na.1);
|
||
if !(len > 1e-9 && nlen > 1e-9 && nlen.is_finite()) {
|
||
return None;
|
||
}
|
||
let nsl = with_all(sl, vec![("from", pt(na.0, na.1)), ("to", pt(nb.0, nb.1)), ("rise", js_num(rise / len * nlen))]);
|
||
Some(with(e, "slope", nsl))
|
||
})
|
||
.into()
|
||
}
|
||
"ceilingGrip" | "roomGrip" => {
|
||
let (coll, field) = if op == "ceilingGrip" { ("ceilings", "outline") } else { ("rooms", "boundary") };
|
||
let (index, (x, y)) = (r.n("index"), r.p("pt"));
|
||
patch(coll, r.s("id"), &|e| Some(with(e, field, replace_at(e.get(field)?.as_array()?, index, &pt(x, y))))).into()
|
||
}
|
||
// [68] Baugrube: Umriss-Ecke ziehen; der Index hinter der letzten Ecke ist der Sohlen-Griff
|
||
// (Lage = Schwerpunkt, y um die Sohlenhöhe versetzt: Ziehen setzt `bottom` = y − Schwerpunkt-y).
|
||
// [176] Schnittlinie: Griff 0 = Anfang, letzter = Ende, dazwischen die Knickpunkte (`bendPoints`).
|
||
"sectionLineGrip" => {
|
||
let (index, (x, y)) = (r.n("index"), r.p("pt"));
|
||
patch("drawingLevels", r.s("id"), &|e| section_line_grip(e, index, x, y)).into()
|
||
}
|
||
// [176] Knick einfügen (Mittel-Griff von Segment `seg` gezogen), löschen (Kontextmenü am Knick-Griff,
|
||
// `index` wie bei `sectionLineGrip`) bzw. aufräumen (nach dem Ziehen: Knicke auf einem Nachbarpunkt
|
||
// oder auf der Geraden zwischen den Nachbarn entfallen).
|
||
"sectionBendInsert" => {
|
||
let (seg, (x, y)) = (r.n("seg"), r.p("pt"));
|
||
patch("drawingLevels", r.s("id"), &|e| section_bend_edit(e, SectionBendEdit::Insert(seg, x, y))).into()
|
||
}
|
||
"sectionBendDelete" => {
|
||
let index = r.n("index");
|
||
patch("drawingLevels", r.s("id"), &|e| section_bend_edit(e, SectionBendEdit::Delete(index))).into()
|
||
}
|
||
"sectionLineTidy" => {
|
||
let tol = r.n("tol");
|
||
let tol = if tol.is_finite() { tol.clamp(BEND_TIDY_M, 1.0) } else { BEND_TIDY_M };
|
||
patch("drawingLevels", r.s("id"), &|e| section_bend_edit(e, SectionBendEdit::Tidy(tol))).into()
|
||
}
|
||
"excavationGrip" => {
|
||
let (index, (x, y)) = (r.n("index"), r.p("pt"));
|
||
patch("context", r.s("id"), &|e| {
|
||
let ring = field(e, "outline")?.as_array()?;
|
||
if index_in(index, ring.len()).is_some() {
|
||
return Some(with(e, "outline", replace_at(ring, index, &pt(x, y))));
|
||
}
|
||
if index == ring.len() as f64 && y.is_finite() {
|
||
let c = ring_centroid(ring);
|
||
return Some(with(e, "bottom", js_num(((y - c.1) * 100.0).round() / 100.0)));
|
||
}
|
||
None
|
||
})
|
||
.into()
|
||
}
|
||
// [193] Höhenlinien-Punkt ziehen bzw. einfügen: flacher Index über alle Linien des Satzes (Punkt-Index bzw. Segment-Index).
|
||
"contourGrip" => {
|
||
let (index, (x, y)) = (r.n("index"), r.p("pt"));
|
||
patch("context", r.s("id"), &|e| contour_edit(e, index, Some((x, y)), false)).into()
|
||
}
|
||
"contourInsert" => {
|
||
let (seg, (x, y)) = (r.n("seg"), r.p("pt"));
|
||
patch("context", r.s("id"), &|e| contour_edit(e, seg, Some((x, y)), true)).into()
|
||
}
|
||
// [193] Gelände-Netz: Netzpunkt `index` (Vertex-Nummer) im Grundriss verschieben, die Höhe bleibt (Höhe: Befehl `meshPointZ`).
|
||
"meshGrip" => {
|
||
let (index, (x, y)) = (r.n("index"), r.p("pt"));
|
||
patch("context", r.s("id"), &|e| mesh_grip(e, index, x, y)).into()
|
||
}
|
||
"excavationEdge" => {
|
||
let (a, b, (dx, dy)) = (r.n("a"), r.n("b"), r.p("delta"));
|
||
patch("context", r.s("id"), &|e| Some(with(e, "outline", move_polygon_edge(field(e, "outline")?.as_array()?, a, b, dx, dy, true)?))).into()
|
||
}
|
||
"ceilingBy" | "roofBy" => {
|
||
let coll = if op == "ceilingBy" { "ceilings" } else { "roofs" };
|
||
let (dx, dy) = r.p("delta");
|
||
patch(coll, r.s("id"), &|e| Some(with(e, "outline", moved_all(field(e, "outline")?.as_array()?, dx, dy)))).into()
|
||
}
|
||
"ceilingEdge" | "roomEdge" => {
|
||
let (coll, field) = if op == "ceilingEdge" { ("ceilings", "outline") } else { ("rooms", "boundary") };
|
||
let (a, b, (dx, dy)) = (r.n("a"), r.n("b"), r.p("delta"));
|
||
patch(coll, r.s("id"), &|e| Some(with(e, field, move_polygon_edge(e.get(field)?.as_array()?, a, b, dx, dy, true)?))).into()
|
||
}
|
||
"roofGrip" => {
|
||
let (index, (x, y)) = (r.n("index"), r.p("pt"));
|
||
patch("roofs", r.s("id"), &|e| roof_grip(e, index, x, y)).into()
|
||
}
|
||
// [26] Dach über beliebigem Grundriss: Eckpunkt bzw. Kante des Umrisses oder eines Hofs. Flacher Index:
|
||
// erst die Ecken von `outline`, danach die der `holes` Ring für Ring (wie die Kanten-Nummerierung
|
||
// von `edgePitchDeg`); eine Kante liegt immer in EINEM Ring.
|
||
"roofVertex" => {
|
||
let (index, (x, y)) = (r.n("index"), r.p("pt"));
|
||
patch("roofs", r.s("id"), &|e| {
|
||
if !(x.is_finite() && y.is_finite()) {
|
||
return None;
|
||
}
|
||
roof_ring_edit(e, index, None, &|ring, i| Some(replace_at(ring, i as f64, &pt(x, y))))
|
||
})
|
||
.into()
|
||
}
|
||
"roofEdge" => {
|
||
let (a, b, (dx, dy)) = (r.n("a"), r.n("b"), r.p("delta"));
|
||
patch("roofs", r.s("id"), &|e| {
|
||
if !(dx.is_finite() && dy.is_finite()) {
|
||
return None;
|
||
}
|
||
roof_ring_edit(e, a, Some(b), &|ring, i| move_polygon_edge(ring, i as f64, b - (a - i as f64), dx, dy, true))
|
||
})
|
||
.into()
|
||
}
|
||
// [26] Ecke einfügen/löschen/aufräumen an Umriss-Ringen (Dach samt Höfen, Decke, Raum, Baugrube, geschlossene
|
||
// Polylinie), ein Kern für alle: `kind` = "roof" | "ceiling" | "room" | "excavation" | "polyline", `seg`/`index`
|
||
// wie bei den Eck-Griffen (Dach: flacher Index über Umriss + Höfe). Kanten-Eigenschaften laufen mit.
|
||
"ringInsert" | "ringDelete" | "ringTidy" => {
|
||
let (index, (x, y)) = (if op == "ringInsert" { r.n("seg") } else { r.n("index") }, r.p("pt"));
|
||
let edit = match op {
|
||
"ringInsert" => RingEdit::Insert(x, y),
|
||
"ringDelete" => RingEdit::Delete,
|
||
_ => {
|
||
let tol = r.n("tol");
|
||
RingEdit::Tidy(if tol.is_finite() { tol.clamp(BEND_TIDY_M, 1.0) } else { BEND_TIDY_M })
|
||
}
|
||
};
|
||
let coll = match r.s("kind") {
|
||
Some("roof") => "roofs",
|
||
Some("ceiling") => "ceilings",
|
||
Some("room") => "rooms",
|
||
Some("excavation") | Some("contours") => "context",
|
||
Some("polyline") => "drawings2d",
|
||
_ => return Ok(GripResult::default()),
|
||
};
|
||
let kind = r.s("kind").unwrap_or("");
|
||
patch(coll, r.s("id"), &|e| ring_edit(e, kind, index, &edit)).into()
|
||
}
|
||
// [191] Bogen-Scheitel einer Umriss-Kante (Decke, Raum, Dach samt Höfen, Baugrube; `seg` wie bei `ringInsert`): der
|
||
// Griff liegt im Scheitel, Ziehen setzt den Bulge über die Pfeilhöhe (senkrecht zur Sehne; auf der Sehne =
|
||
// gerade Kante).
|
||
"ringArc" => {
|
||
let (seg, (x, y)) = (r.n("seg"), r.p("pt"));
|
||
let coll = match r.s("kind") {
|
||
Some("roof") => "roofs",
|
||
Some("ceiling") => "ceilings",
|
||
Some("room") => "rooms",
|
||
Some("excavation") => "context",
|
||
_ => return Ok(GripResult::default()),
|
||
};
|
||
let kind = r.s("kind").unwrap_or("");
|
||
patch(coll, r.s("id"), &|e| ring_arc_edit(e, kind, seg, x, y)).into()
|
||
}
|
||
"stairBy" => {
|
||
let (dx, dy) = r.p("delta");
|
||
patch("stairs", r.s("id"), &|s| {
|
||
let mut out = with(s, "start", moved(field(s, "start").unwrap_or(&Value::Null), dx, dy));
|
||
if truthy(field(s, "center")) {
|
||
out = with(&out, "center", moved(&s["center"], dx, dy));
|
||
}
|
||
Some(out)
|
||
})
|
||
.into()
|
||
}
|
||
// [151] Parameter-Griff einer Podesttreppe (Lauflängen, Podesttiefe, Auge/Drehsinn).
|
||
"stairParam" => {
|
||
let (index, (x, y)) = (r.n("index"), r.p("pt"));
|
||
patch("stairs", r.s("id"), &|s| {
|
||
let st: crate::model::Stair = serde_json::from_value(s.clone()).ok()?;
|
||
let i = index_in(index, 4)?;
|
||
let changes = crate::grip_drag::stair_param_drag(&st.encode(), i, (x, y));
|
||
if changes.is_empty() {
|
||
return None;
|
||
}
|
||
let mut out = s.clone();
|
||
for (k, v) in changes {
|
||
out = with(&out, k, js_num(v));
|
||
}
|
||
Some(out)
|
||
})
|
||
.into()
|
||
}
|
||
"roomBy" => {
|
||
let (dx, dy) = r.p("delta");
|
||
patch("rooms", r.s("id"), &|rm| {
|
||
let mut out = with(rm, "boundary", moved_all(field(rm, "boundary")?.as_array()?, dx, dy));
|
||
if truthy(field(rm, "stampAnchor")) {
|
||
out = with(&out, "stampAnchor", moved(&rm["stampAnchor"], dx, dy));
|
||
}
|
||
Some(out)
|
||
})
|
||
.into()
|
||
}
|
||
// Stempel verschieben: ab dem eigenen Anker, sonst ab der gezeichneten Lage `pt` ([140]: ohne Anker rückt
|
||
// der Plan den Stempel vom Pol weg — L-Raum, Hindernisse), fehlt sie, ab dem Pol.
|
||
"roomStamp" => {
|
||
let (dx, dy) = r.p("delta");
|
||
let drawn = Some(r.p("pt")).filter(|q| q.0.is_finite() && q.1.is_finite());
|
||
patch("rooms", r.s("id"), &|rm| {
|
||
let base = match field(rm, "stampAnchor") {
|
||
Some(a) if !a.is_null() => xy(a),
|
||
_ if drawn.is_some() => drawn.unwrap_or_default(),
|
||
_ => {
|
||
let ring: Vec<[f64; 2]> = arr(field(rm, "boundary")).iter().map(|p| xy(p).into()).collect();
|
||
let c = crate::room_area::label_point(&ring);
|
||
(c[0], c[1])
|
||
}
|
||
};
|
||
Some(with(rm, "stampAnchor", pt(base.0 + dx, base.1 + dy)))
|
||
})
|
||
.into()
|
||
}
|
||
"insertPoint" => {
|
||
let (seg, (x, y)) = (r.n("seg"), r.p("pt"));
|
||
patch("drawings2d", r.s("id"), &|d| insert_point(d, seg, x, y)).into()
|
||
}
|
||
"vertexType" => {
|
||
let Some(t) = req.vertex_type.as_deref().and_then(crate::polyline_vertex::VertexType::parse) else {
|
||
return Ok(GripResult::default());
|
||
};
|
||
let index = r.n("index");
|
||
patch("drawings2d", r.s("id"), &|d| vertex_type(d, index, t)).into()
|
||
}
|
||
"deletePoint" => {
|
||
let index = r.n("index");
|
||
let Some(d) = r.s("id").and_then(|i| lk.find("drawings2d", i)) else { return Ok(GripResult::default()) };
|
||
let g = field(d, "geom").unwrap_or(&Value::Null);
|
||
if field(g, "shape").and_then(Value::as_str) != Some("polyline") {
|
||
return Ok(GripResult::default());
|
||
}
|
||
let pts = arr(field(g, "pts"));
|
||
let min = if truthy(field(g, "closed")) { 4 } else { 3 };
|
||
if pts.len() < min {
|
||
return Ok(GripResult { ops: vec![], notice: Some("alert.polylineMinPoints"), ..Default::default() });
|
||
}
|
||
let Some(k) = index_in(index, pts.len()) else { return Ok(GripResult::default()) };
|
||
// Zwei Segmente werden eins: der Bogen des entfernten Segments fällt weg, das verbleibende behält
|
||
// seinen (die genaue Bogenform lässt sich ohne den Stützpunkt nicht erhalten).
|
||
let drop = |l: &[Value]| Value::Array(l.iter().enumerate().filter(|(i, _)| *i != k).map(|(_, v)| v.clone()).collect());
|
||
let mut fields = vec![("pts", drop(pts))];
|
||
if truthy(field(g, "bulge")) {
|
||
fields.push(("bulge", drop(arr(field(g, "bulge")))));
|
||
}
|
||
vec![replace("drawings2d", with_geom(d, with_all(g, fields)))].into()
|
||
}
|
||
// [187] Höhen-Griff im Schnitt/in der Ansicht: `kind` = wallTop | wallBottom | openingTop | openingBottom |
|
||
// ceilingTop | ceilingBottom | roofEave | roofTop | parapetTop | stairTop | contextTop | contourLine, `a` = Blatt-Höhe (absolutes Z), `free` ohne 1-cm-Raster (`sheet_height.rs`).
|
||
"sheetHeight" => crate::sheet_height::ops(lk, r.s("kind").unwrap_or(""), r.s("id").unwrap_or(""), r.n("a"), r.free, r.s("newId").unwrap_or(""), &req.new_name, r.n("b"), r.n("index")).into(),
|
||
// [333] Waagrechte End-Griffe im Schnitt: `kind` = ceilingEdge | wallEnd, `index` = Ende (0 links, 1 rechts), `a` = Zug in u (m),
|
||
// `pt` = Punkt der Schnittlinie (u = 0), `delta` = u-Achse im Grundriss (`sheet_height::end_ops`).
|
||
"sheetEnd" => {
|
||
let (base, ua) = (r.p("pt"), r.p("delta"));
|
||
crate::sheet_height::end_ops(lk, r.s("kind").unwrap_or(""), r.s("id").unwrap_or(""), u8::from(r.n("index") == 1.0), r.n("a"), [base.0, base.1], [ua.0, ua.1]).into()
|
||
}
|
||
"wallThickness" => wall_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.new_name.clone()).into(),
|
||
"ceilingThickness" => ceiling_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.new_name.clone()).into(),
|
||
// [144] Wandöffnung gleiten lassen: Griff-Zug nach `pt` bzw. Objekt-Info-Position `a` (ab
|
||
// Wandanfang; Bogenwand: Bogenlänge). Geklemmt auf die Wand und vor der Nachbaröffnung.
|
||
"openingSlide" | "openingPosition" => {
|
||
let Some(o) = r.s("id").and_then(|id| lk.find("openings", id)).filter(|o| !crate::json_util::truthy(field(o, "locked"))) else {
|
||
return Ok(GripResult::default());
|
||
};
|
||
let want = if op == "openingSlide" { crate::opening_slide::grip_want(root, o, r.p("pt")) } else { Some(r.n("a")).filter(|v| v.is_finite()) };
|
||
let Some(placed) = want.and_then(|w| crate::opening_slide::slide_to(root, o, w)) else { return Ok(GripResult::default()) };
|
||
let v = with(o, "position", js_num(placed.position));
|
||
let ops = if v == *o { vec![] } else { vec![replace("openings", v)] };
|
||
GripResult { ops, notice: placed.clamped.then_some(crate::opening_slide::NOTICE_OVERLAP), ..Default::default() }
|
||
}
|
||
other => return Err(format!("Unbekannte Griff-Änderung: {other}")),
|
||
})
|
||
}
|
||
|
||
// ── Wand ─────────────────────────────────────────────────────────────────────
|
||
|
||
/// [188] Öffnungen einer geraden Wand, deren Anfang/Ende verschoben wurde, so nachführen, dass sie im Plan stehen
|
||
/// bleiben: neue Position = Projektion des alten Weltpunkts (Anfang + Richtung·Position) auf die neue Achse.
|
||
/// Bogenwände (Position = Bogenlänge) bleiben wie bisher.
|
||
fn openings_keep_place(root: &Map<String, Value>, old: &Value, new: &Value) -> Vec<Op> {
|
||
let is_arc = |w: &Value| crate::wall_arc::is_arc_bulge(field(w, "bulge").and_then(Value::as_f64));
|
||
if is_arc(old) || is_arc(new) {
|
||
return vec![];
|
||
}
|
||
let p = |w: &Value, k: &str| xy(field(w, k).unwrap_or(&Value::Null));
|
||
let (s0, e0, s1, e1) = (p(old, "start"), p(old, "end"), p(new, "start"), p(new, "end"));
|
||
let unit = |a: (f64, f64), b: (f64, f64)| {
|
||
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
|
||
let l = crate::jsmath::hypot2(dx, dy);
|
||
(l > 1e-12).then(|| (dx / l, dy / l))
|
||
};
|
||
let (Some(d0), Some(d1)) = (unit(s0, e0), unit(s1, e1)) else { return vec![] };
|
||
let Some(wid) = field(old, "id").and_then(Value::as_str) else { return vec![] };
|
||
crate::json_util::arr(root.get("openings"))
|
||
.iter()
|
||
.filter(|o| field(o, "hostWallId").and_then(Value::as_str) == Some(wid))
|
||
.filter_map(|o| {
|
||
let pos = field(o, "position").and_then(Value::as_f64)?;
|
||
let (wx, wy) = (s0.0 + d0.0 * pos, s0.1 + d0.1 * pos);
|
||
let np = (wx - s1.0) * d1.0 + (wy - s1.1) * d1.1;
|
||
((np - pos).abs() > 1e-9).then(|| replace("openings", with(o, "position", js_num(np))))
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
fn wall_grip(w: &Value, index: f64, x: f64, y: f64, fixed_center: bool, arc_length: f64) -> Value {
|
||
// Bogenwand ([T2]): Griff 2 = Bogenscheitel; der Bogen geht durch den gezogenen Punkt.
|
||
if index == 2.0 {
|
||
let (s, e) = (xy(field(w, "start").unwrap_or(&Value::Null)), xy(field(w, "end").unwrap_or(&Value::Null)));
|
||
// Mit festem Mittelpunkt (Shift): Radius = Abstand zum Mittelpunkt, Öffnungswinkel bleibt, die Enden wandern radial.
|
||
if fixed_center {
|
||
if let Some(b) = field(w, "bulge").and_then(Value::as_f64).filter(|b| crate::wall_arc::is_arc_bulge(Some(*b))) {
|
||
return match crate::grip_drag::arc_wall_radius_fixed_center(s, e, b, (x, y)) {
|
||
Some((ns, ne)) => with_all(w, vec![("start", pt(ns.0, ns.1)), ("end", pt(ne.0, ne.1))]),
|
||
None => w.clone(),
|
||
};
|
||
}
|
||
}
|
||
let b = crate::bulge::from_sagitta_point(s.0, s.1, e.0, e.1, x, y);
|
||
return with_opt(w, vec![("bulge", (b.is_finite() && b.abs() > 1e-9).then(|| js_num(b)))]);
|
||
}
|
||
// Endpunkt einer Bogenwand ([T2]): der Punkt folgt dem Kreis (Mittelpunkt und Radius bleiben, das
|
||
// andere Ende steht), der Bulge passt sich an.
|
||
if index == 0.0 || index == 1.0 {
|
||
let (s, e) = (xy(field(w, "start").unwrap_or(&Value::Null)), xy(field(w, "end").unwrap_or(&Value::Null)));
|
||
if let Some(b) = field(w, "bulge").and_then(Value::as_f64).filter(|b| crate::wall_arc::is_arc_bulge(Some(*b))) {
|
||
return match crate::grip_drag::arc_wall_resize(s, e, b, index as usize, Some(arc_length).filter(|l| l.is_finite()), (x, y)) {
|
||
Some((ns, ne, nb)) => with_all(w, vec![("start", pt(ns.0, ns.1)), ("end", pt(ne.0, ne.1)), ("bulge", js_num(nb))]),
|
||
None => w.clone(),
|
||
};
|
||
}
|
||
}
|
||
with(w, if index == 0.0 { "start" } else { "end" }, pt(x, y))
|
||
}
|
||
|
||
/// [176] Griff einer Schnitt-/Ansichtslinie ziehen: Index 0 = `linePoints[0]`, 1…n = `bendPoints`,
|
||
/// n + 1 = `linePoints[1]` (Reihenfolge entlang der Linie).
|
||
fn section_line_grip(e: &Value, index: f64, x: f64, y: f64) -> Option<Value> {
|
||
let line = field(e, "linePoints")?.as_array()?;
|
||
if line.len() < 2 {
|
||
return None;
|
||
}
|
||
let bends: &[Value] = field(e, "bendPoints").and_then(Value::as_array).map_or(&[], Vec::as_slice);
|
||
let n = bends.len();
|
||
let i = index_in(index, n + 2)?;
|
||
if i == 0 || i == n + 1 {
|
||
let k = if i == 0 { 0.0 } else { 1.0 };
|
||
return Some(with(e, "linePoints", replace_at(line, k, &pt(x, y))));
|
||
}
|
||
Some(with(e, "bendPoints", replace_at(bends, (i - 1) as f64, &pt(x, y))))
|
||
}
|
||
|
||
enum SectionBendEdit {
|
||
Insert(f64, f64, f64),
|
||
Delete(f64),
|
||
Tidy(f64),
|
||
}
|
||
|
||
/// Mindest-Abstand (m), unter dem ein Knick als auf dem Nachbarpunkt bzw. der Geraden zwischen den Nachbarn gilt
|
||
/// (die Hülle gibt beim Ziehen die Zeiger-Genauigkeit der Ansicht mit, `tol`).
|
||
const BEND_TIDY_M: f64 = 0.005;
|
||
|
||
/// [176] Knickpunkte einer Schnittlinie ändern; `None`, wenn nichts zu tun ist.
|
||
fn section_bend_edit(e: &Value, edit: SectionBendEdit) -> Option<Value> {
|
||
let line = field(e, "linePoints")?.as_array()?;
|
||
if line.len() < 2 {
|
||
return None;
|
||
}
|
||
let mut bends: Vec<Value> = field(e, "bendPoints").and_then(Value::as_array).cloned().unwrap_or_default();
|
||
match edit {
|
||
SectionBendEdit::Insert(seg, x, y) => {
|
||
let j = index_in(seg, bends.len() + 1)?;
|
||
if !(x.is_finite() && y.is_finite()) {
|
||
return None;
|
||
}
|
||
bends.insert(j, pt(x, y));
|
||
}
|
||
SectionBendEdit::Delete(index) => {
|
||
let i = index_in(index, bends.len() + 2)?;
|
||
if i == 0 || i == bends.len() + 1 {
|
||
return None;
|
||
}
|
||
bends.remove(i - 1);
|
||
}
|
||
SectionBendEdit::Tidy(tol) => {
|
||
let before = bends.len();
|
||
loop {
|
||
let mut pts: Vec<(f64, f64)> = vec![xy(&line[0])];
|
||
pts.extend(bends.iter().map(xy));
|
||
pts.push(xy(&line[1]));
|
||
// Knick i (Punkt i+1) mit den Nachbarn i und i+2.
|
||
let bad = (0..bends.len()).find(|&i| {
|
||
let (a, b, c) = (pts[i], pts[i + 1], pts[i + 2]);
|
||
let (dx, dy) = (c.0 - a.0, c.1 - a.1);
|
||
let len2 = dx * dx + dy * dy;
|
||
let t = if len2 > 0.0 { ((b.0 - a.0) * dx + (b.1 - a.1) * dy) / len2 } else { 0.0 };
|
||
let (qx, qy) = (a.0 + t.clamp(0.0, 1.0) * dx, a.1 + t.clamp(0.0, 1.0) * dy);
|
||
(b.0 - qx).hypot(b.1 - qy) < tol
|
||
});
|
||
match bad {
|
||
Some(i) => {
|
||
bends.remove(i);
|
||
}
|
||
None => break,
|
||
}
|
||
}
|
||
if bends.len() == before {
|
||
return None;
|
||
}
|
||
}
|
||
}
|
||
if bends.is_empty() {
|
||
// Ohne Knicke fällt das Feld weg (altes 2-Punkt-Format).
|
||
return Some(with_opt(e, vec![("bendPoints", None)]));
|
||
}
|
||
Some(with(e, "bendPoints", Value::Array(bends)))
|
||
}
|
||
|
||
fn wall_moved(w: &Value, dx: f64, dy: f64) -> Value {
|
||
let s = moved(field(w, "start").unwrap_or(&Value::Null), dx, dy);
|
||
let e = moved(field(w, "end").unwrap_or(&Value::Null), dx, dy);
|
||
with_all(w, vec![("start", s), ("end", e)])
|
||
}
|
||
|
||
// ── 2D-Zeichnungen ───────────────────────────────────────────────────────────
|
||
|
||
fn shape(g: &Value) -> &str {
|
||
field(g, "shape").and_then(Value::as_str).unwrap_or("")
|
||
}
|
||
|
||
/// Kreis, solange rx≈ry (relative Toleranz 0.5 %) — sonst Ellipse (rotation 0). Neues Objekt (weitere
|
||
/// Felder der alten Form entfallen, wie in TS).
|
||
fn ellipse_or_circle(center: Option<&Value>, rx: Pass, ry: Pass) -> Value {
|
||
let mut m = Map::new();
|
||
let mut put = |k: &str, v: Option<Value>| {
|
||
if let Some(v) = v {
|
||
m.insert(k.into(), v);
|
||
}
|
||
};
|
||
if (rx.f - ry.f).abs() <= 0.005 * jsnum::max(rx.f, ry.f) {
|
||
put("shape", Some("circle".into()));
|
||
put("center", center.cloned());
|
||
put("r", Some(js_num((rx.f + ry.f) / 2.0)));
|
||
} else {
|
||
put("shape", Some("ellipse".into()));
|
||
put("center", center.cloned());
|
||
put("rx", rx.v);
|
||
put("ry", ry.v);
|
||
put("rotation", Some(Value::from(0u64)));
|
||
}
|
||
Value::Object(m)
|
||
}
|
||
|
||
/// `mmToModel`: Papier-mm → Modell-Meter beim Massstab 1:N.
|
||
fn mm_to_model(mm: f64, scale: f64) -> f64 {
|
||
(mm / 1000.0) * scale
|
||
}
|
||
|
||
fn model_to_mm(m: f64, scale: f64) -> f64 {
|
||
(m * 1000.0) / scale
|
||
}
|
||
|
||
/// Standard-Schrifthöhe der Masszahl (Papier-mm, `DIM_DEFAULTS_MM.textHeight`).
|
||
const DIM_TEXT_HEIGHT_MM: f64 = 2.5;
|
||
|
||
/// `dimTextFrame` der TS-Fassade: bei nicht endlichen Eingaben alles NaN.
|
||
fn dim_frame(a: (f64, f64), b: (f64, f64), offset: f64, h: f64) -> ((f64, f64), (f64, f64), (f64, f64)) {
|
||
if ![a.0, a.1, b.0, b.1, offset, h].iter().all(|v| v.is_finite()) {
|
||
let n = (f64::NAN, f64::NAN);
|
||
return (n, n, n);
|
||
}
|
||
let v = |p: (f64, f64)| crate::model::Vec2 { x: p.0, y: p.1 };
|
||
let (base, read, up, _) = crate::plan::drawings::dim_text_frame(v(a), v(b), offset, h);
|
||
((base.x, base.y), (read.x, read.y), (up.x, up.y))
|
||
}
|
||
|
||
/// `dimTextPos`: Lage der Masszahl inkl. Versatz (Modell-Meter).
|
||
fn dim_text_pos(a: (f64, f64), b: (f64, f64), offset: f64, h: f64, along: f64, perp: f64) -> (f64, f64) {
|
||
let (base, read, up) = dim_frame(a, b, offset, h);
|
||
(base.0 + read.0 * along + up.0 * perp, base.1 + read.1 * along + up.1 * perp)
|
||
}
|
||
|
||
/// Schrifthöhe der Masszahl in Modell-Metern.
|
||
fn dim_height(g: &Value, scale: f64) -> f64 {
|
||
mm_to_model(num_or(field(g, "textHeightMm"), DIM_TEXT_HEIGHT_MM), scale)
|
||
}
|
||
|
||
/// [172] Masszahl eines Radius-/Durchmesser-/Bogenlängenmasses: (Art, Rahmen). Mitte der Zahl bei Versatz 0 =
|
||
/// Anker + Querachse · 0.6 h; Leserichtung/Querachse wie im Plan (`plan::drawings::round_label`).
|
||
fn round_dim_label(g: &Value) -> Option<(crate::plan::drawings::RoundLabel, (f64, f64), (f64, f64))> {
|
||
use crate::model::DimKind;
|
||
let kind = match field(g, "kind").and_then(Value::as_str)? {
|
||
"radius" => DimKind::Radius,
|
||
"diameter" => DimKind::Diameter,
|
||
"arc" => DimKind::Arc,
|
||
_ => return None,
|
||
};
|
||
let pts: Vec<crate::model::Vec2> = arr(field(g, "pts")).iter().map(|q| xy(q)).map(|q| crate::model::Vec2 { x: q.0, y: q.1 }).collect();
|
||
let l = crate::plan::drawings::round_label(kind, &pts, num_of(field(g, "offset")))?;
|
||
let (read, up) = ((jsnum::cos(l.angle), jsnum::sin(l.angle)), (-jsnum::sin(l.angle), jsnum::cos(l.angle)));
|
||
Some((l, read, up))
|
||
}
|
||
|
||
/// [172] Lage des Masszahl-Griffs eines Rundmasses (Modell-Meter), samt gespeichertem Versatz.
|
||
fn round_dim_text_grip(g: &Value, scale: f64) -> Option<(f64, f64)> {
|
||
let (l, read, up) = round_dim_label(g)?;
|
||
let h = dim_height(g, scale);
|
||
let o = arr(field(g, "textOffsetsMm")).first().cloned().unwrap_or(Value::Null);
|
||
let (along, perp) = (mm_to_model(num_or(field(&o, "along"), 0.0), scale), mm_to_model(num_or(field(&o, "perp"), 0.0), scale));
|
||
let q = (l.at.x + up.0 * (0.6 * h + perp) + read.0 * along, l.at.y + up.1 * (0.6 * h + perp) + read.1 * along);
|
||
(q.0.is_finite() && q.1.is_finite()).then_some(q)
|
||
}
|
||
|
||
/// [172] Einrast-Stellen der Masszahl eines Segments der Länge `len` (Modell-Meter, Schrifthöhe `h`) als (entlang,
|
||
/// quer) ab der Mitte über dem Massstrich: Mitte (Vorgabe), innen links/rechts (Zahl bündig an der Hilfslinie),
|
||
/// aussen links/rechts, eine Zeile über bzw. unter der Linie. Nächste Stelle zu (`along`, `perp`); passt die Zahl
|
||
/// nicht zwischen die Hilfslinien, entfallen Mitte und innen. Mitte = (0, 0) = Vorgabe (läuft über `dim_auto_offsets`).
|
||
fn dim_text_slot(len: f64, h: f64, along: f64, perp: f64) -> (f64, f64) {
|
||
dim_text_slot_w(len, crate::plan::drawings::dim_text_width(len, h), h, along, perp)
|
||
}
|
||
|
||
/// Wie [`dim_text_slot`] mit gegebener Breite `w` der Zahl (Rundmasse tragen ein Präfix: „R 2.00“).
|
||
fn dim_text_slot_w(len: f64, w: f64, h: f64, along: f64, perp: f64) -> (f64, f64) {
|
||
use crate::plan::drawings::{dim_text_below, dim_text_pad, dim_text_row};
|
||
let (pad, row) = (dim_text_pad(h), dim_text_row(h));
|
||
let fits = w + 2.0 * pad <= len;
|
||
let (inner, outer) = (len / 2.0 - w / 2.0 - pad, len / 2.0 + w / 2.0 + pad);
|
||
let mut slots = vec![(-outer, 0.0), (outer, 0.0), (0.0, row), (0.0, dim_text_below(h))];
|
||
if fits {
|
||
slots.extend([(0.0, 0.0), (-inner, 0.0), (inner, 0.0)]);
|
||
}
|
||
let d2 = |s: &(f64, f64)| (s.0 - along) * (s.0 - along) + (s.1 - perp) * (s.1 - perp);
|
||
// `min_by` mit NaN: erste Stelle (links aussen) bleibt dann stehen.
|
||
slots.into_iter().min_by(|p, q| d2(p).partial_cmp(&d2(q)).unwrap_or(std::cmp::Ordering::Equal)).unwrap_or((0.0, 0.0))
|
||
}
|
||
|
||
/// Griff `index` einer 2D-Zeichnung auf (x, y) (`moveGrip`); `None` = keine Änderung.
|
||
fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64, free: bool) -> Option<Value> {
|
||
let g = field(d, "geom")?;
|
||
let p = pt(x, y);
|
||
let set = |k: &str, v: Value| Some(with_geom(d, with(g, k, v)));
|
||
match shape(g) {
|
||
"line" | "xline" | "ray" => set(if index == 0.0 { "a" } else { "b" }, p),
|
||
"polyline" => {
|
||
let pts = arr(field(g, "pts"));
|
||
let n = pts.len();
|
||
if index < n as f64 {
|
||
return set("pts", replace_at(pts, index, &p));
|
||
}
|
||
// Loch-Ecken (Index ≥ 2n, geschlossen): nach den Bogen-Griffen, Löcher der Reihe nach.
|
||
if truthy(field(g, "closed")) && n > 2 && index >= (2 * n) as f64 && field(g, "holes").is_some() {
|
||
let mut rest = index as usize - 2 * n;
|
||
let mut holes: Vec<Value> = arr(field(g, "holes")).to_vec();
|
||
for h in holes.iter_mut() {
|
||
let ring = arr(Some(&*h));
|
||
if rest < ring.len() {
|
||
*h = replace_at(ring, rest as f64, &p);
|
||
return set("holes", Value::Array(holes));
|
||
}
|
||
rest -= ring.len();
|
||
}
|
||
return None;
|
||
}
|
||
// Bulge-Griff (Index ≥ n): Segment-Mitte senkrecht zur Sehne → Bogen dieses Segments.
|
||
let seg = index - n as f64;
|
||
let k = index_in(seg, n)?;
|
||
let a = xy(&pts[k]);
|
||
let b = xy(if k == n - 1 { &pts[0] } else { &pts[k + 1] });
|
||
let val = crate::bulge::from_sagitta_point(a.0, a.1, b.0, b.1, x, y);
|
||
let mut bulge: Vec<Value> = arr(field(g, "bulge")).to_vec();
|
||
while bulge.len() <= k {
|
||
bulge.push(Value::from(0u64));
|
||
}
|
||
bulge[k] = js_num(val);
|
||
set("bulge", Value::Array(bulge))
|
||
}
|
||
"bezier" | "spline" => set("pts", replace_at(arr(field(g, "pts")), index, &p)),
|
||
"dimension" => {
|
||
let pts = arr(field(g, "pts"));
|
||
let n = pts.len();
|
||
// Radius-/Durchmesser-/Bogenlängen-Mass ([T2]): Randpunkte bleiben auf dem Kreis um den Mittelpunkt
|
||
// (Radius = bisheriger Abstand des ersten Randpunkts), nur die Lage auf dem Kreis ändert sich.
|
||
let round = matches!(field(g, "kind").and_then(Value::as_str), Some("radius" | "diameter" | "arc")) && n >= 2;
|
||
if round && index >= 1.0 && index < n as f64 {
|
||
let (c, rim) = (xy(&pts[0]), xy(&pts[1]));
|
||
let r = hypot2(rim.0 - c.0, rim.1 - c.1);
|
||
let l = hypot2(x - c.0, y - c.1);
|
||
if !(l > 1e-9 && r.is_finite()) {
|
||
return None;
|
||
}
|
||
let q = pt(c.0 + (x - c.0) * r / l, c.1 + (y - c.1) * r / l);
|
||
let ng = with(g, "pts", replace_at(pts, index, &q));
|
||
return Some(with_geom(d, crate::dim_assoc::without_ref(&ng, index_in(index, n))));
|
||
}
|
||
// Masszahl-Griff eines Rundmasses ([172]): rastet wie bei linearen Massen ein (Alt = frei).
|
||
if matches!(field(g, "kind").and_then(Value::as_str), Some("radius" | "diameter" | "arc")) && index == n as f64 + 1.0 {
|
||
let (l, read, up) = round_dim_label(g)?;
|
||
let h = dim_height(g, scale);
|
||
let (vx, vy) = (x - l.at.x, y - l.at.y);
|
||
let (along, perp) = (vx * read.0 + vy * read.1, vx * up.0 + vy * up.1 - 0.6 * h);
|
||
let w = crate::text_layout::text_width_em(&l.text, false) * h;
|
||
let (along, perp) = if free { (along, perp) } else { dim_text_slot_w(l.len, w, h, along, perp) };
|
||
let next = serde_json::json!({"along": js_num(model_to_mm(along, scale)), "perp": js_num(model_to_mm(perp, scale))});
|
||
return set("textOffsetsMm", Value::Array(vec![next]));
|
||
}
|
||
if index < n as f64 {
|
||
// Von Hand gezogener Punkt ist frei ([38]).
|
||
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()?));
|
||
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
|
||
let len = or1(hypot2(dx, dy));
|
||
let (nx, ny) = (-dy / len, dx / len);
|
||
return set("offset", js_num((x - a.0) * nx + (y - a.1) * ny));
|
||
}
|
||
// Masszahl-Griff ([172]): nur die Zahl des Segments; rastet an festen Stellen ein (Mitte, innen links/
|
||
// rechts, aussen links/rechts, über/unter der Linie), frei nur mit gehaltener Alt-Taste.
|
||
let seg = index - n as f64 - 1.0;
|
||
if seg < 0.0 || seg >= n as f64 - 1.0 {
|
||
return None;
|
||
}
|
||
let k = index_in(seg, n)?;
|
||
let h = dim_height(g, scale);
|
||
let (a, b) = (xy(&pts[k]), xy(&pts[k + 1]));
|
||
let (base, read, up) = dim_frame(a, b, num_of(field(g, "offset")), h);
|
||
let (vx, vy) = (x - base.0, y - base.1);
|
||
let (along, perp) = (vx * read.0 + vy * read.1, vx * up.0 + vy * up.1);
|
||
let (along, perp) = if free { (along, perp) } else { dim_text_slot(hypot2(b.0 - a.0, b.1 - a.1), h, along, perp) };
|
||
let mut next = Map::new();
|
||
next.insert("along".into(), js_num(model_to_mm(along, scale)));
|
||
next.insert("perp".into(), js_num(model_to_mm(perp, scale)));
|
||
let old = arr(field(g, "textOffsetsMm"));
|
||
let offs: Vec<Value> = (0..n - 1)
|
||
.map(|i| {
|
||
if i == k {
|
||
Value::Object(next.clone())
|
||
} else {
|
||
match old.get(i) {
|
||
Some(v) if !v.is_null() => v.clone(),
|
||
_ => serde_json::json!({"along": 0, "perp": 0}),
|
||
}
|
||
}
|
||
})
|
||
.collect();
|
||
set("textOffsetsMm", Value::Array(offs))
|
||
}
|
||
"rect" | "image" => {
|
||
let corners = rect_corners(g);
|
||
let r = (index + 2.0) % 4.0;
|
||
let opp = corners[index_in(r, 4)?];
|
||
let min = pt(jsnum::min(x, opp.0), jsnum::min(y, opp.1));
|
||
let max = pt(jsnum::max(x, opp.0), jsnum::max(y, opp.1));
|
||
Some(with_geom(d, with_all(g, vec![("min", min), ("max", max)])))
|
||
}
|
||
"text" => {
|
||
if truthy(field(g, "pathPts")) {
|
||
return set("pathPts", replace_at(arr(field(g, "pathPts")), index, &p));
|
||
}
|
||
if truthy(field(g, "leaderTarget")) {
|
||
let bends = arr(field(g, "leaderBendPoints"));
|
||
let tip = bends.len() as f64 + 1.0;
|
||
if index == 0.0 {
|
||
return set("at", p);
|
||
}
|
||
if index == tip {
|
||
return set("leaderTarget", p);
|
||
}
|
||
if index > 0.0 && index < tip {
|
||
let v = Value::Array(bends.iter().enumerate().map(|(i, bp)| if i as f64 == index - 1.0 { p.clone() } else { bp.clone() }).collect());
|
||
return set("leaderBendPoints", v);
|
||
}
|
||
return None;
|
||
}
|
||
let width = num_of(field(g, "width"));
|
||
if truthy(field(g, "width")) && width > 0.0 && index >= 0.0 && index < 4.0 {
|
||
// Nur die Spaltenbreite ändert sich (InDesign-Textrahmen); Zug auf die lokale x-Achse.
|
||
let angle = num_of(field(g, "angle"));
|
||
let (cos, sin) = (jsnum::cos(angle), jsnum::sin(angle));
|
||
let (ax, ay) = xy(field(g, "at").unwrap_or(&Value::Null));
|
||
let local_x = (x - ax) * cos + (y - ay) * sin;
|
||
const MIN_WIDTH: f64 = 0.1;
|
||
if index == 0.0 || index == 3.0 {
|
||
let w = jsnum::max(MIN_WIDTH, width - local_x);
|
||
let at = pt(ax + local_x * cos, ay + local_x * sin);
|
||
return Some(with_geom(d, with_all(g, vec![("at", at), ("width", js_num(w))])));
|
||
}
|
||
return set("width", js_num(jsnum::max(MIN_WIDTH, local_x)));
|
||
}
|
||
set("at", p)
|
||
}
|
||
// [333] Bibliotheks-Objekt: Griff 0 = Einfügepunkt (verschiebt), 1 = Dreh-Griff (Richtung Mitte → Griff = Drehung).
|
||
"libobj" if index == 1.0 => {
|
||
let (ax, ay) = xy(field(g, "at").unwrap_or(&Value::Null));
|
||
if hypot2(x - ax, y - ay) < 1e-9 {
|
||
return None;
|
||
}
|
||
set("rotation", js_num(jsnum::atan2(y - ay, x - ax)))
|
||
}
|
||
"kote" | "detailref" | "scalebar" | "pointmarker" | "block" | "libobj" => 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"));
|
||
let (rx, ry) = if index == 0.0 { (calc(jsnum::max(1e-3, (x - cx).abs())), r) } else { (r, calc(jsnum::max(1e-3, (y - cy).abs()))) };
|
||
Some(with_geom(d, ellipse_or_circle(field(g, "center"), rx, ry)))
|
||
}
|
||
"arc" => {
|
||
let (cx, cy) = xy(field(g, "center").unwrap_or(&Value::Null));
|
||
if index == 2.0 {
|
||
return set("r", js_num(jsnum::max(1e-3, hypot2(x - cx, y - cy))));
|
||
}
|
||
set(if index == 0.0 { "a0" } else { "a1" }, js_num(jsnum::atan2(y - cy, x - cx)))
|
||
}
|
||
"ellipse" => {
|
||
let rot = num_of(field(g, "rotation"));
|
||
let (c, s) = (jsnum::cos(rot), jsnum::sin(rot));
|
||
let (cx, cy) = xy(field(g, "center").unwrap_or(&Value::Null));
|
||
let (dx, dy) = (x - cx, y - cy);
|
||
let lx = dx * c + dy * s;
|
||
let ly = -dx * s + dy * c;
|
||
let rx = if index == 0.0 { calc(jsnum::max(1e-3, lx.abs())) } else { pass(field(g, "rx")) };
|
||
let ry = if index == 0.0 { pass(field(g, "ry")) } else { calc(jsnum::max(1e-3, ly.abs())) };
|
||
// Nur ungedreht (`rotation === 0`) kann eine (fast) gleichseitige Ellipse wieder zum Kreis werden.
|
||
if field(g, "rotation").and_then(Value::as_f64) == Some(0.0) {
|
||
return Some(with_geom(d, ellipse_or_circle(field(g, "center"), rx, ry)));
|
||
}
|
||
Some(with_geom(d, with_opt(g, vec![("rx", rx.v), ("ry", ry.v)])))
|
||
}
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
/// `x || 1` für eine Länge (0 und NaN → 1).
|
||
fn or1(l: f64) -> f64 {
|
||
if l == 0.0 || l.is_nan() {
|
||
1.0
|
||
} else {
|
||
l
|
||
}
|
||
}
|
||
|
||
/// Ecken eines Rechtecks/Bilds in Griff-Reihenfolge: min, (max.x, min.y), max, (min.x, max.y).
|
||
fn rect_corners(g: &Value) -> [(f64, f64); 4] {
|
||
let mn = xy(field(g, "min").unwrap_or(&Value::Null));
|
||
let mx = xy(field(g, "max").unwrap_or(&Value::Null));
|
||
[mn, (mx.0, mn.1), mx, (mn.0, mx.1)]
|
||
}
|
||
|
||
/// Ganze 2D-Zeichnung verschieben (`moveElementBy`); `None` = Form ohne Verschiebung.
|
||
fn drawing_moved(d: &Value, dx: f64, dy: f64) -> Option<Value> {
|
||
let g = field(d, "geom")?;
|
||
let mv = |k: &str| moved(g.get(k).unwrap_or(&Value::Null), dx, dy);
|
||
let ng = match shape(g) {
|
||
"line" => with_all(g, vec![("a", mv("a")), ("b", mv("b"))]),
|
||
"polyline" if truthy(field(g, "holes")) => {
|
||
let holes = Value::Array(arr(field(g, "holes")).iter().map(|h| moved_all(arr(Some(h)), dx, dy)).collect());
|
||
with_all(g, vec![("pts", moved_all(arr(field(g, "pts")), dx, dy)), ("holes", holes)])
|
||
}
|
||
"polyline" | "bezier" | "spline" => with(g, "pts", moved_all(arr(field(g, "pts")), dx, dy)),
|
||
// Allein verschobene Bemassung löst ihre Bezüge ([38]).
|
||
"dimension" => crate::dim_assoc::without_ref(&with(g, "pts", moved_all(arr(field(g, "pts")), dx, dy)), None),
|
||
"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))
|
||
}
|
||
|
||
/// Kante (a, b) einer 2D-Zeichnung verschieben (`moveEdge`); `None` = keine Änderung.
|
||
fn drawing_edge(d: &Value, a: f64, b: f64, dx: f64, dy: f64) -> Option<Value> {
|
||
let g = field(d, "geom")?;
|
||
let ng = match shape(g) {
|
||
"line" => with_all(g, vec![("a", moved(field(g, "a").unwrap_or(&Value::Null), dx, dy)), ("b", moved(field(g, "b").unwrap_or(&Value::Null), dx, dy))]),
|
||
"polyline" | "spline" => with(g, "pts", move_polygon_edge(arr(field(g, "pts")), a, b, dx, dy, truthy(field(g, "closed")))?),
|
||
"rect" | "image" => {
|
||
// Die zwei Kanten-Ecken verschieben, dann die bbox neu bilden (achsparallel).
|
||
let corners = rect_corners(g);
|
||
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
|
||
for (i, c) in corners.iter().enumerate() {
|
||
let c = if eq_index(i, a) || eq_index(i, b) { (c.0 + dx, c.1 + dy) } else { *c };
|
||
x0 = jsnum::min(x0, c.0);
|
||
y0 = jsnum::min(y0, c.1);
|
||
x1 = jsnum::max(x1, c.0);
|
||
y1 = jsnum::max(y1, c.1);
|
||
}
|
||
with_all(g, vec![("min", pt(x0, y0)), ("max", pt(x1, y1))])
|
||
}
|
||
_ => return None,
|
||
};
|
||
Some(with_geom(d, ng))
|
||
}
|
||
|
||
/// Schnittpunkt der Geraden a + t·da mit b + s·db (`lineIntersect`); `None` bei (fast) parallelen.
|
||
fn line_intersect(a: (f64, f64), da: (f64, f64), b: (f64, f64), db: (f64, f64)) -> Option<(f64, f64)> {
|
||
let cross = |p: (f64, f64), q: (f64, f64)| p.0 * q.1 - p.1 * q.0;
|
||
let denom = cross(da, db);
|
||
if denom.abs() < 1e-9 {
|
||
return None;
|
||
}
|
||
let t = cross((b.0 - a.0, b.1 - a.1), db) / denom;
|
||
Some((a.0 + da.0 * t, a.1 + da.1 * t))
|
||
}
|
||
|
||
/// Neue Lage eines Eckpunkts, dessen eine Kante parallel verschoben wird: er wandert entlang seiner
|
||
/// anderen (unverschobenen) Nachbarkante (`edgeMoveVertex`); ohne Nachbarn oder bei paralleler
|
||
/// Nachbarkante einfach um das Delta.
|
||
fn edge_move_vertex(v: (f64, f64), neighbor: Option<(f64, f64)>, shifted: (f64, f64), edge_dir: (f64, f64), dx: f64, dy: f64) -> (f64, f64) {
|
||
let fallback = (v.0 + dx, v.1 + dy);
|
||
let Some(nb) = neighbor else { return fallback };
|
||
let nd = (v.0 - nb.0, v.1 - nb.1);
|
||
if hypot2(nd.0, nd.1) < 1e-9 {
|
||
return fallback;
|
||
}
|
||
line_intersect(nb, nd, shifted, edge_dir).unwrap_or(fallback)
|
||
}
|
||
|
||
/// Nachbar-Index von `i` in Richtung `dir` (`ringNeighbor`): `None` am offenen Ende oder wenn er auf
|
||
/// die andere Kanten-Ecke fiele.
|
||
fn ring_neighbor(i: usize, n: usize, closed: bool, dir: i64, excluding: usize) -> Option<usize> {
|
||
let j = i as i64 + dir;
|
||
let k = if j >= 0 && j < n as i64 {
|
||
Some(j as usize)
|
||
} else if closed {
|
||
Some(j.rem_euclid(n as i64) as usize)
|
||
} else {
|
||
None
|
||
};
|
||
k.filter(|&k| k != excluding)
|
||
}
|
||
|
||
/// Kante (a, b) eines Rings/einer Kette um das Delta verschieben, winkeltreu an den Nachbar-Ecken
|
||
/// (`movePolygonEdge`); `None`, wenn a oder b kein Punkt ist.
|
||
pub fn move_polygon_edge(pts: &[Value], a: f64, b: f64, dx: f64, dy: f64, closed: bool) -> Option<Value> {
|
||
let n = pts.len();
|
||
let (ai, bi) = (index_in(a, n)?, index_in(b, n)?);
|
||
let (pa, pb) = (xy(&pts[ai]), xy(&pts[bi]));
|
||
let shifted = (pa.0 + dx, pa.1 + dy);
|
||
let edge_dir = (pb.0 - pa.0, pb.1 - pa.1);
|
||
let prev = ring_neighbor(ai, n, closed, -1, bi).map(|k| xy(&pts[k]));
|
||
let next = ring_neighbor(bi, n, closed, 1, ai).map(|k| xy(&pts[k]));
|
||
Some(Value::Array(
|
||
pts.iter()
|
||
.enumerate()
|
||
.map(|(i, p)| {
|
||
if i == ai {
|
||
let q = edge_move_vertex(pa, prev, shifted, edge_dir, dx, dy);
|
||
pt(q.0, q.1)
|
||
} else if i == bi {
|
||
let q = edge_move_vertex(pb, next, shifted, edge_dir, dx, dy);
|
||
pt(q.0, q.1)
|
||
} else {
|
||
p.clone()
|
||
}
|
||
})
|
||
.collect(),
|
||
))
|
||
}
|
||
|
||
// ── Grösse um einen Anker ────────────────────────────────────────────────────
|
||
|
||
type BBox = (f64, f64, f64, f64);
|
||
|
||
/// bbox einer Punktliste (`bbox2`; nicht endlich → Null-Box).
|
||
fn bbox(pts: &[(f64, f64)]) -> BBox {
|
||
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
|
||
for p in pts {
|
||
x0 = jsnum::min(x0, p.0);
|
||
y0 = jsnum::min(y0, p.1);
|
||
x1 = jsnum::max(x1, p.0);
|
||
y1 = jsnum::max(y1, p.1);
|
||
}
|
||
if !x0.is_finite() {
|
||
return (0.0, 0.0, 0.0, 0.0);
|
||
}
|
||
(x0, y0, x1, y1)
|
||
}
|
||
|
||
/// Anker und Faktoren, um eine bbox auf w × h zu bringen (`scaleAround`; Null-Ausdehnung → Faktor 1).
|
||
fn scale_around(b: BBox, w: f64, h: f64, fx: f64, fy: f64) -> (f64, f64, f64, f64) {
|
||
let bw = b.2 - b.0;
|
||
let bh = b.3 - b.1;
|
||
let ax = b.0 + fx * bw;
|
||
let ay = b.1 + fy * bh;
|
||
let sx = if bw > 1e-9 { w / bw } else { 1.0 };
|
||
let sy = if bh > 1e-9 { h / bh } else { 1.0 };
|
||
(ax, ay, sx, sy)
|
||
}
|
||
|
||
/// 2D-Form auf w × h um den Anker skalieren (`resizeGeom`); `None` = Form bleibt (Kote, Bemassung …).
|
||
fn resize_geom(g: &Value, w: f64, h: f64, fx: f64, fy: f64) -> Option<Value> {
|
||
let p = |k: &str| xy(g.get(k).unwrap_or(&Value::Null));
|
||
let pts_of = |k: &str| arr(g.get(k)).iter().map(xy).collect::<Vec<_>>();
|
||
let scaled = |(ax, ay, sx, sy): (f64, f64, f64, f64), q: (f64, f64)| (ax + (q.0 - ax) * sx, ay + (q.1 - ay) * sy);
|
||
let ptv = |q: (f64, f64)| pt(q.0, q.1);
|
||
Some(match shape(g) {
|
||
"line" | "xline" | "ray" => {
|
||
let (a, b) = (p("a"), p("b"));
|
||
let s = scale_around(bbox(&[a, b]), w, h, fx, fy);
|
||
with_all(g, vec![("a", ptv(scaled(s, a))), ("b", ptv(scaled(s, b)))])
|
||
}
|
||
"polyline" | "bezier" | "spline" => {
|
||
let pts = pts_of("pts");
|
||
let s = scale_around(bbox(&pts), w, h, fx, fy);
|
||
with(g, "pts", Value::Array(pts.iter().map(|q| ptv(scaled(s, *q))).collect()))
|
||
}
|
||
"rect" | "image" => {
|
||
let (mn, mx) = (p("min"), p("max"));
|
||
let s = scale_around(bbox(&[mn, mx]), w, h, fx, fy);
|
||
let (a, b) = (scaled(s, mn), scaled(s, mx));
|
||
with_all(g, vec![("min", pt(jsnum::min(a.0, b.0), jsnum::min(a.1, b.1))), ("max", pt(jsnum::max(a.0, b.0), jsnum::max(a.1, b.1)))])
|
||
}
|
||
"circle" | "arc" => {
|
||
// bbox eines Kreises ist 2r × 2r; Radius = grössere Zielhälfte, Mitte nicht-uniform um den Anker.
|
||
let c = p("center");
|
||
let r = num_of(field(g, "r"));
|
||
let ax = (c.0 - r) + fx * (2.0 * r);
|
||
let ay = (c.1 - r) + fy * (2.0 * r);
|
||
let half = jsnum::max(w, h) / 2.0;
|
||
let nr = if half > 0.0 { Some(js_num(half)) } else { field(g, "r").cloned() };
|
||
let sx = if r > 1e-9 { (w / 2.0) / r } else { 1.0 };
|
||
let sy = if r > 1e-9 { (h / 2.0) / r } else { 1.0 };
|
||
with_opt(g, vec![("center", Some(pt(ax + (c.0 - ax) * sx, ay + (c.1 - ay) * sy))), ("r", nr)])
|
||
}
|
||
"ellipse" => {
|
||
let c = p("center");
|
||
let (rx, ry) = (num_of(field(g, "rx")), num_of(field(g, "ry")));
|
||
let (ax, ay, sx, sy) = scale_around((c.0 - rx, c.1 - ry, c.0 + rx, c.1 + ry), w, h, fx, fy);
|
||
with_all(g, vec![("center", pt(ax + (c.0 - ax) * sx, ay + (c.1 - ay) * sy)), ("rx", js_num(jsnum::max(1e-3, rx * sx))), ("ry", js_num(jsnum::max(1e-3, ry * sy)))])
|
||
}
|
||
"text" | "block" => {
|
||
// Nur die Einfügeposition wandert (Schrifthöhe bzw. Symbol bleiben).
|
||
let at = p("at");
|
||
let s = scale_around((at.0, at.1, at.0, at.1), w, h, fx, fy);
|
||
with(g, "at", ptv(scaled(s, at)))
|
||
}
|
||
_ => return None,
|
||
})
|
||
}
|
||
|
||
// ── Dach, Polylinien-Punkte, Dicken ──────────────────────────────────────────
|
||
|
||
/// Gauben-Griffe ([G5]) im Dach-Griff: Index = Basis + 10 × Gaube + k; k = 0/1 Breite (links/rechts,
|
||
/// symmetrisch um die Stirnmitte), k = 2 Tiefe (Schleppgaube; die Neigung folgt daraus).
|
||
pub const DORMER_GRIP_BASE: f64 = 1000.0;
|
||
|
||
fn dormer_grip(r: &Value, local: f64, x: f64, y: f64) -> Option<Value> {
|
||
if !(local.is_finite() && local >= 0.0 && x.is_finite() && y.is_finite()) {
|
||
return None;
|
||
}
|
||
let (di, k) = ((local / 10.0).floor() as usize, local as i64 % 10);
|
||
let dormers = field(r, "dormers")?.as_array()?;
|
||
let d = dormers.get(di)?;
|
||
let roof: crate::model::Roof = serde_json::from_value(r.clone()).ok()?;
|
||
let (px, py) = xy(field(d, "position")?);
|
||
let g = crate::roof::roof_geometry(&roof.params(), 0.0);
|
||
let pl = g.planes.iter().find(|pl| pl.len() >= 3 && crate::dormer::point_in_xy(px, py, pl))?;
|
||
let n = crate::model3d::plane_normal_up(pl);
|
||
let hl = hypot2(n[0], n[1]);
|
||
if !(hl > 0.05) {
|
||
return None;
|
||
}
|
||
let h = (n[0] / hl, n[1] / hl);
|
||
let (dx, dy) = (x - px, y - py);
|
||
let nd = match k {
|
||
0 | 1 => {
|
||
let w = 2.0 * (dx * -h.1 + dy * h.0).abs();
|
||
with(d, "width", js_num(jsnum::max(0.8, w)))
|
||
}
|
||
2 => {
|
||
let depth = -(dx * h.0 + dy * h.1);
|
||
let mut nd = with(d, "depth", js_num(jsnum::max(0.3, depth)));
|
||
if let Some(o) = nd.as_object_mut() {
|
||
o.remove("pitchDeg");
|
||
}
|
||
nd
|
||
}
|
||
_ => return None,
|
||
};
|
||
let mut list = dormers.clone();
|
||
list[di] = nd;
|
||
Some(with(r, "dormers", Value::Array(list)))
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod dormer_grip_tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn breite_und_tiefe() {
|
||
let r = serde_json::json!({
|
||
"id": "R", "type": "roof", "floorId": "F", "categoryCode": "35",
|
||
"outline": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 8}, {"x": 0, "y": 8}],
|
||
"shape": "sattel", "pitchDeg": 45, "overhang": 0.3, "ridgeAxis": "x", "thickness": 0.3,
|
||
"dormers": [{"id": "D", "kind": "schlepp", "position": {"x": 4, "y": 1}, "width": 2, "frontHeight": 1.5, "pitchDeg": 15}]
|
||
});
|
||
// Breite: Punkt 1.5 rechts der Mitte (Südseite: ew = +x) ⇒ 3.0
|
||
let w = roof_grip(&r, DORMER_GRIP_BASE + 1.0, 5.5, 1.0).unwrap();
|
||
assert_eq!(w["dormers"][0]["width"], 3.0);
|
||
// Tiefe: 2 m das Gefälle hinauf (+y) ⇒ depth 2, Neigung entfällt
|
||
let d = roof_grip(&r, DORMER_GRIP_BASE + 2.0, 4.0, 3.0).unwrap();
|
||
assert_eq!(d["dormers"][0]["depth"], 2.0);
|
||
assert!(d["dormers"][0].get("pitchDeg").is_none());
|
||
assert!(roof_grip(&r, DORMER_GRIP_BASE + 10.0, 4.0, 3.0).is_none(), "keine zweite Gaube");
|
||
assert!(roof_grip(&r, DORMER_GRIP_BASE + 2.0, f64::NAN, 3.0).is_none());
|
||
}
|
||
}
|
||
|
||
/// [26] Ring (Umriss oder Hof) des Dachs, in dem der flache Index `a` (und ggf. `b`) liegt, durch `f` ersetzen.
|
||
/// `f` bekommt den Ring und den Index von `a` darin. Gesperrt, Index ausserhalb, `b` in anderem Ring → None.
|
||
fn roof_ring_edit(r: &Value, a: f64, b: Option<f64>, f: &dyn Fn(&[Value], usize) -> Option<Value>) -> Option<Value> {
|
||
if truthy(field(r, "locked")) {
|
||
return None;
|
||
}
|
||
let outline = field(r, "outline")?.as_array()?;
|
||
let holes: Vec<&Vec<Value>> = arr(field(r, "holes")).iter().filter_map(|h| h.as_array()).collect();
|
||
let mut off = 0usize;
|
||
for ring_no in 0..=holes.len() {
|
||
let ring: &[Value] = if ring_no == 0 { outline } else { holes[ring_no - 1] };
|
||
let in_ring = |i: f64| index_in(i - off as f64, ring.len());
|
||
if let Some(i) = in_ring(a) {
|
||
if let Some(b) = b {
|
||
in_ring(b)?;
|
||
}
|
||
let new = f(ring, i)?;
|
||
return Some(if ring_no == 0 {
|
||
with(r, "outline", new)
|
||
} else {
|
||
let mut hs: Vec<Value> = arr(field(r, "holes")).to_vec();
|
||
hs[ring_no - 1] = new;
|
||
with(r, "holes", Value::Array(hs))
|
||
});
|
||
}
|
||
off += ring.len();
|
||
}
|
||
None
|
||
}
|
||
|
||
enum RingEdit {
|
||
/// Ecke hinter Ecke `i` einfügen (Mittel-Griff der Kante i → i+1).
|
||
Insert(f64, f64),
|
||
Delete,
|
||
/// Ecke `i` entfernen, wenn sie (fast) auf dem Nachbarpunkt oder der Geraden zwischen den Nachbarn liegt.
|
||
Tidy(f64),
|
||
}
|
||
|
||
/// Was mit den Kanten-Einträgen (Neigung, Böschung …) geschieht: Eintrag `i` verdoppeln bzw. streichen.
|
||
enum EdgeShift {
|
||
Dup(usize),
|
||
Drop(usize),
|
||
}
|
||
|
||
fn v2(v: &Value) -> crate::model::Vec2 {
|
||
let (x, y) = xy(v);
|
||
crate::model::Vec2 { x, y }
|
||
}
|
||
|
||
/// [191] Bögen eines Rings (`bulge`, je Kante; kürzer = gerade) auf `n` Einträge gebracht.
|
||
fn ring_bulges(bulge: &[Value], n: usize) -> Vec<f64> {
|
||
(0..n).map(|i| bulge.get(i).and_then(Value::as_f64).filter(|b| b.is_finite()).unwrap_or(0.0)).collect()
|
||
}
|
||
|
||
/// Liegen die Bögen a→b (`b1`) und b→c (`b2`) auf demselben Kreis? Dann der Bulge des Gesamtbogens a→c.
|
||
fn merged_arc(a: crate::model::Vec2, b: crate::model::Vec2, c: crate::model::Vec2, b1: f64, b2: f64) -> Option<f64> {
|
||
use crate::ring_arc::arc_of;
|
||
let (k1, k2) = (arc_of(a, b, b1)?, arc_of(b, c, b2)?);
|
||
let tol = 1e-6 * k1.1.max(1.0);
|
||
let same = hypot2(k1.0.x - k2.0.x, k1.0.y - k2.0.y) < tol && (k1.1 - k2.1).abs() < tol && k1.3 * k2.3 > 0.0;
|
||
let q = b1.atan() + b2.atan();
|
||
(same && q.abs() < std::f64::consts::PI * 0.999).then(|| q.tan())
|
||
}
|
||
|
||
/// Neuer Ring nach `edit` an Ecke/Kante `i`; mindestens 3 Ecken bleiben. [191] `bulge` (je Kante, auf die
|
||
/// Eckenzahl gebracht) läuft mit: Einfügen auf einem Bogen teilt ihn (beide Teile auf demselben Kreis),
|
||
/// Löschen verbindet die Nachbarn gerade, ausser beide Bögen liegen auf einem Kreis (dann ein Bogen).
|
||
/// Aufräumen nur, wo beide Kanten gerade sind oder auf einem Kreis liegen.
|
||
fn ring_apply(ring: &[Value], bulge: &[f64], i: usize, edit: &RingEdit) -> Option<(Vec<Value>, Vec<f64>, EdgeShift)> {
|
||
let n = ring.len();
|
||
let mut v = ring.to_vec();
|
||
let mut bl = bulge.to_vec();
|
||
let merge = |bl: &mut Vec<f64>| {
|
||
let prev = (i + n - 1) % n;
|
||
let (a, b, c) = (v2(&ring[prev]), v2(&ring[i]), v2(&ring[(i + 1) % n]));
|
||
let m = if bl[prev] == 0.0 && bl[i] == 0.0 { Some(0.0) } else { merged_arc(a, b, c, bl[prev], bl[i]) };
|
||
bl[prev] = m.unwrap_or(0.0);
|
||
bl.remove(i);
|
||
m.is_some()
|
||
};
|
||
match *edit {
|
||
RingEdit::Insert(x, y) => {
|
||
if !(x.is_finite() && y.is_finite()) {
|
||
return None;
|
||
}
|
||
let (a, b) = (v2(&ring[i]), v2(&ring[(i + 1) % n]));
|
||
let f = crate::ring_arc::arc_fraction(a, b, bl[i], crate::model::Vec2 { x, y });
|
||
let (b1, b2) = crate::ring_arc::split_bulge(bl[i], f);
|
||
bl[i] = b1;
|
||
bl.insert(i + 1, b2);
|
||
v.insert(i + 1, pt(x, y));
|
||
Some((v, bl, EdgeShift::Dup(i)))
|
||
}
|
||
RingEdit::Delete => {
|
||
if n <= 3 {
|
||
return None;
|
||
}
|
||
merge(&mut bl);
|
||
v.remove(i);
|
||
Some((v, bl, EdgeShift::Drop(i)))
|
||
}
|
||
RingEdit::Tidy(tol) => {
|
||
if n <= 3 {
|
||
return None;
|
||
}
|
||
let prev = (i + n - 1) % n;
|
||
let straight = bl[prev] == 0.0 && bl[i] == 0.0;
|
||
if straight && !point_near_neighbors(ring, i, tol) {
|
||
return None;
|
||
}
|
||
if !merge(&mut bl) {
|
||
return None;
|
||
}
|
||
v.remove(i);
|
||
Some((v, bl, EdgeShift::Drop(i)))
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Bogen-Liste `key` nach einer Ring-Änderung schreiben: fehlte sie und ist alles gerade, bleibt sie weg.
|
||
fn put_bulges(e: Value, key: &str, bl: &[f64]) -> Value {
|
||
if field(&e, key).is_none() && bl.iter().all(|b| *b == 0.0) {
|
||
return e;
|
||
}
|
||
with(&e, key, Value::Array(bl.iter().map(|b| js_num(*b)).collect()))
|
||
}
|
||
|
||
/// Wie [`put_bulges`] für die Bögen eines Lochs/Hofs (`key` = Liste je Ring, Ring `k` von `n_rings`).
|
||
fn put_hole_bulges(e: Value, key: &str, k: usize, n_rings: usize, bl: &[f64]) -> Value {
|
||
if field(&e, key).is_none() && bl.iter().all(|b| *b == 0.0) {
|
||
return e;
|
||
}
|
||
let mut all: Vec<Value> = arr(field(&e, key)).to_vec();
|
||
while all.len() < n_rings {
|
||
all.push(Value::Array(vec![]));
|
||
}
|
||
all[k] = Value::Array(bl.iter().map(|b| js_num(*b)).collect());
|
||
with(&e, key, Value::Array(all))
|
||
}
|
||
|
||
/// Liegt Ecke `i` des Rings näher als `tol` an der Strecke zwischen ihren Nachbarn (Nachbarpunkt eingeschlossen)?
|
||
fn point_near_neighbors(ring: &[Value], i: usize, tol: f64) -> bool {
|
||
let n = ring.len();
|
||
let (a, b, c) = (xy(&ring[(i + n - 1) % n]), xy(&ring[i]), xy(&ring[(i + 1) % n]));
|
||
let (dx, dy) = (c.0 - a.0, c.1 - a.1);
|
||
let len2 = dx * dx + dy * dy;
|
||
let t = if len2 > 0.0 { ((b.0 - a.0) * dx + (b.1 - a.1) * dy) / len2 } else { 0.0 };
|
||
let (qx, qy) = (a.0 + t.clamp(0.0, 1.0) * dx, a.1 + t.clamp(0.0, 1.0) * dy);
|
||
(b.0 - qx).hypot(b.1 - qy) < tol
|
||
}
|
||
|
||
/// Kanten-Einträge `field` (ab Kante `off`) nachführen: die neue Kante erbt die geteilte, beim Löschen bleibt die
|
||
/// vorherige Kante (Nachbar → Nachbar). Fehlende Einträge (kürzere Liste) bleiben fehlend = Standard.
|
||
fn shift_edge_list(e: Value, field_name: &str, off: usize, shift: &EdgeShift) -> Value {
|
||
let Some(list) = field(&e, field_name).and_then(Value::as_array) else { return e };
|
||
let mut v = list.clone();
|
||
match *shift {
|
||
EdgeShift::Dup(i) => {
|
||
if v.len() > off + i {
|
||
let c = v[off + i].clone();
|
||
v.insert(off + i + 1, c);
|
||
}
|
||
}
|
||
EdgeShift::Drop(i) => {
|
||
if v.len() > off + i {
|
||
v.remove(off + i);
|
||
}
|
||
}
|
||
}
|
||
with(&e, field_name, Value::Array(v))
|
||
}
|
||
|
||
/// [193] Punkt `flat` (flach über alle Linien eines Höhenlinien-Satzes) auf `at` setzen bzw. (`insert`) hinter dem
|
||
/// Punkt `flat` einen Punkt einfügen (Segment von `flat` zum Nachfolger; geschlossen: der letzte schliesst zum Anfang,
|
||
/// offen: der letzte hat kein Segment). Eine wahre Kurve (`curve`) fällt weg.
|
||
fn contour_edit(e: &Value, flat: f64, at: Option<(f64, f64)>, insert: bool) -> Option<Value> {
|
||
let (x, y) = at.filter(|(x, y)| x.is_finite() && y.is_finite())?;
|
||
if field(e, "type").and_then(Value::as_str) != Some("contourSet") {
|
||
return None;
|
||
}
|
||
let cs = arr(field(e, "contours"));
|
||
let mut off = 0usize;
|
||
for (ci, c) in cs.iter().enumerate() {
|
||
let pts = arr(field(c, "pts"));
|
||
let closed = truthy(field(c, "closed"));
|
||
let count = pts.len();
|
||
let has_seg = |i: usize| count >= 2 && (closed || i + 1 < count);
|
||
if let Some(i) = index_in(flat - off as f64, count).filter(|i| !insert || has_seg(*i)) {
|
||
let new_pts = if insert {
|
||
let mut v = pts.to_vec();
|
||
v.insert(i + 1, pt(x, y));
|
||
Value::Array(v)
|
||
} else {
|
||
replace_at(pts, i as f64, &pt(x, y))
|
||
};
|
||
let nc = with_opt(&with(c, "pts", new_pts), vec![("curve", None)]);
|
||
let mut out = cs.to_vec();
|
||
out[ci] = nc;
|
||
return Some(with(e, "contours", Value::Array(out)));
|
||
}
|
||
off += count;
|
||
}
|
||
None
|
||
}
|
||
|
||
/// [193] Netzpunkt `index` eines `terrainMesh`/`importedMesh` auf `(x, y)` setzen (z unverändert).
|
||
fn mesh_grip(e: &Value, index: f64, x: f64, y: f64) -> Option<Value> {
|
||
if !(x.is_finite() && y.is_finite()) || !matches!(field(e, "type").and_then(Value::as_str), Some("terrainMesh" | "importedMesh")) {
|
||
return None;
|
||
}
|
||
let pos = arr(field(e, "positions"));
|
||
let i = index_in(index, pos.len() / 3)?;
|
||
let mut v = pos.to_vec();
|
||
v[3 * i] = js_num(x);
|
||
v[3 * i + 1] = js_num(y);
|
||
Some(with(e, "positions", Value::Array(v)))
|
||
}
|
||
|
||
/// [193] Höhenlinien-Punkt löschen bzw. aufräumen (flacher Index über alle Linien des Satzes). Mindestens 2 Punkte
|
||
/// (offen) bzw. 3 (geschlossen) bleiben. Aufräumen entfernt den Punkt nur, wenn er auf dem Nachbarpunkt oder (innen) auf
|
||
/// der Geraden zwischen den Nachbarn liegt. Eine wahre Kurve (`curve`) fällt weg. Einfügen läuft über `contourInsert`.
|
||
fn contour_ring_edit(e: &Value, flat: f64, edit: &RingEdit) -> Option<Value> {
|
||
if field(e, "type").and_then(Value::as_str) != Some("contourSet") || matches!(edit, RingEdit::Insert(..)) {
|
||
return None;
|
||
}
|
||
let cs = arr(field(e, "contours"));
|
||
let mut off = 0usize;
|
||
for (ci, c) in cs.iter().enumerate() {
|
||
let pts = arr(field(c, "pts"));
|
||
let (closed, n) = (truthy(field(c, "closed")), pts.len());
|
||
if let Some(i) = index_in(flat - off as f64, n) {
|
||
if n <= if closed { 3 } else { 2 } {
|
||
return None;
|
||
}
|
||
if let RingEdit::Tidy(tol) = *edit {
|
||
let near = |a: usize, b: usize| {
|
||
let (p, q) = (xy(&pts[a]), xy(&pts[b]));
|
||
hypot2(p.0 - q.0, p.1 - q.1) < tol
|
||
};
|
||
let end = !closed && (i == 0 || i == n - 1);
|
||
let hit = if end { near(i, if i == 0 { 1 } else { n - 2 }) } else { near(i, (i + n - 1) % n) || near(i, (i + 1) % n) || point_near_neighbors(pts, i, tol) };
|
||
if !hit {
|
||
return None;
|
||
}
|
||
}
|
||
let mut v = pts.to_vec();
|
||
v.remove(i);
|
||
let nc = with_opt(&with(c, "pts", Value::Array(v)), vec![("curve", None)]);
|
||
let mut out = cs.to_vec();
|
||
out[ci] = nc;
|
||
return Some(with(e, "contours", Value::Array(out)));
|
||
}
|
||
off += n;
|
||
}
|
||
None
|
||
}
|
||
|
||
/// [26] Ecke einfügen/löschen/aufräumen an einem Umriss-Element (s. `ringInsert`).
|
||
fn ring_edit(e: &Value, kind: &str, flat: f64, edit: &RingEdit) -> Option<Value> {
|
||
if truthy(field(e, "locked")) {
|
||
return None;
|
||
}
|
||
let simple = |name: &str, bulge_key: &str| -> Option<Value> {
|
||
let ring = field(e, name)?.as_array()?;
|
||
let bl = ring_bulges(arr(field(e, bulge_key)), ring.len());
|
||
let (v, bl, shift) = ring_apply(ring, &bl, index_in(flat, ring.len())?, edit)?;
|
||
let out = put_bulges(with(e, name, Value::Array(v)), bulge_key, &bl);
|
||
Some(if kind == "excavation" {
|
||
shift_edge_list(shift_edge_list(out, "edgeSlopes", 0, &shift), "edgeShoring", 0, &shift)
|
||
} else {
|
||
out
|
||
})
|
||
};
|
||
match kind {
|
||
"ceiling" => simple("outline", "outlineBulge"),
|
||
"excavation" => simple("outline", "outlineBulge"),
|
||
"room" => simple("boundary", "boundaryBulge"),
|
||
"polyline" => polyline_ring_edit(e, flat, edit),
|
||
"contours" => contour_ring_edit(e, flat, edit),
|
||
"roof" => {
|
||
let outline = field(e, "outline")?.as_array()?;
|
||
let holes: Vec<&Vec<Value>> = arr(field(e, "holes")).iter().filter_map(|h| h.as_array()).collect();
|
||
let mut off = 0usize;
|
||
for ring_no in 0..=holes.len() {
|
||
let ring: &[Value] = if ring_no == 0 { outline } else { holes[ring_no - 1] };
|
||
if let Some(i) = index_in(flat - off as f64, ring.len()) {
|
||
let bl = if ring_no == 0 { ring_bulges(arr(field(e, "outlineBulge")), ring.len()) } else { ring_bulges(arr(arr(field(e, "holesBulge")).get(ring_no - 1)), ring.len()) };
|
||
let (v, bl, shift) = ring_apply(ring, &bl, i, edit)?;
|
||
let out = if ring_no == 0 {
|
||
put_bulges(with(e, "outline", Value::Array(v)), "outlineBulge", &bl)
|
||
} else {
|
||
let mut hs: Vec<Value> = arr(field(e, "holes")).to_vec();
|
||
hs[ring_no - 1] = Value::Array(v);
|
||
put_hole_bulges(with(e, "holes", Value::Array(hs)), "holesBulge", ring_no - 1, holes.len(), &bl)
|
||
};
|
||
return Some(shift_edge_list(out, "edgePitchDeg", off, &shift));
|
||
}
|
||
off += ring.len();
|
||
}
|
||
None
|
||
}
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
/// [191] Bulge der Kante `flat` (Dach: flacher Index über Umriss + Höfe) aus dem gezogenen Scheitel `(x, y)`.
|
||
fn ring_arc_edit(e: &Value, kind: &str, flat: f64, x: f64, y: f64) -> Option<Value> {
|
||
if truthy(field(e, "locked")) || !(x.is_finite() && y.is_finite()) {
|
||
return None;
|
||
}
|
||
let bulge_of = |ring: &[Value], i: usize| -> f64 {
|
||
let (a, b) = (xy(&ring[i]), xy(&ring[(i + 1) % ring.len()]));
|
||
let v = crate::bulge::from_sagitta_point(a.0, a.1, b.0, b.1, x, y);
|
||
// Fast gerade (Pfeilhöhe < 1 mm) = gerade Kante.
|
||
let chord = hypot2(b.0 - a.0, b.1 - a.1);
|
||
if (v * chord / 2.0).abs() < 1e-3 { 0.0 } else { v.clamp(-1e3, 1e3) }
|
||
};
|
||
let simple = |name: &str, bulge_key: &str| -> Option<Value> {
|
||
let ring = field(e, name)?.as_array()?;
|
||
let i = index_in(flat, ring.len())?;
|
||
if ring.len() < 3 {
|
||
return None;
|
||
}
|
||
let mut bl = ring_bulges(arr(field(e, bulge_key)), ring.len());
|
||
bl[i] = bulge_of(ring, i);
|
||
Some(put_bulges(e.clone(), bulge_key, &bl))
|
||
};
|
||
match kind {
|
||
"ceiling" | "excavation" => simple("outline", "outlineBulge"),
|
||
"room" => simple("boundary", "boundaryBulge"),
|
||
"roof" => {
|
||
let outline = field(e, "outline")?.as_array()?;
|
||
let holes: Vec<&Vec<Value>> = arr(field(e, "holes")).iter().filter_map(|h| h.as_array()).collect();
|
||
let mut off = 0usize;
|
||
for ring_no in 0..=holes.len() {
|
||
let ring: &[Value] = if ring_no == 0 { outline } else { holes[ring_no - 1] };
|
||
if let Some(i) = index_in(flat - off as f64, ring.len()) {
|
||
if ring.len() < 3 {
|
||
return None;
|
||
}
|
||
let src = if ring_no == 0 { arr(field(e, "outlineBulge")) } else { arr(arr(field(e, "holesBulge")).get(ring_no - 1)) };
|
||
let mut bl = ring_bulges(src, ring.len());
|
||
bl[i] = bulge_of(ring, i);
|
||
return Some(if ring_no == 0 { put_bulges(e.clone(), "outlineBulge", &bl) } else { put_hole_bulges(e.clone(), "holesBulge", ring_no - 1, holes.len(), &bl) });
|
||
}
|
||
off += ring.len();
|
||
}
|
||
None
|
||
}
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
/// Geschlossene Polylinie: nur Aufräumen (Einfügen/Löschen laufen über `insertPoint`/`deletePoint`, die Bögen
|
||
/// kennen). Ecke entfällt, wenn beide anliegenden Segmente gerade sind und sie auf der Nachbargeraden liegt.
|
||
fn polyline_ring_edit(d: &Value, index: f64, edit: &RingEdit) -> Option<Value> {
|
||
let RingEdit::Tidy(tol) = *edit else { return None };
|
||
let g = field(d, "geom")?;
|
||
if shape(g) != "polyline" || !truthy(field(g, "closed")) {
|
||
return None;
|
||
}
|
||
let pts = arr(field(g, "pts"));
|
||
let n = pts.len();
|
||
let k = index_in(index, n)?;
|
||
if n <= 3 || !point_near_neighbors(pts, k, tol) {
|
||
return None;
|
||
}
|
||
let bulge = arr(field(g, "bulge"));
|
||
let straight = |i: usize| num_or(bulge.get(i), 0.0).abs() < 1e-9;
|
||
if !(straight(k) && straight((k + n - 1) % n)) {
|
||
return None;
|
||
}
|
||
let drop = |l: &[Value]| Value::Array(l.iter().enumerate().filter(|(i, _)| *i != k).map(|(_, v)| v.clone()).collect());
|
||
let mut fields = vec![("pts", drop(pts))];
|
||
if truthy(field(g, "bulge")) {
|
||
fields.push(("bulge", drop(bulge)));
|
||
}
|
||
Some(with_geom(d, with_all(g, fields)))
|
||
}
|
||
|
||
/// Dach-Eckgriff: die gegenüberliegende Ecke bleibt fix, der Umriss bleibt ein achsparalleles Rechteck.
|
||
fn roof_grip(r: &Value, index: f64, x: f64, y: f64) -> Option<Value> {
|
||
if index >= DORMER_GRIP_BASE {
|
||
return dormer_grip(r, index - DORMER_GRIP_BASE, x, y);
|
||
}
|
||
let outline = field(r, "outline")?.as_array()?;
|
||
let n = outline.len();
|
||
if n < 4 {
|
||
return None;
|
||
}
|
||
let k = index_in((index + 2.0) % n as f64, n)?;
|
||
let opp = xy(&outline[k]);
|
||
let (x0, x1) = (jsnum::min(x, opp.0), jsnum::max(x, opp.0));
|
||
let (y0, y1) = (jsnum::min(y, opp.1), jsnum::max(y, opp.1));
|
||
Some(with(r, "outline", Value::Array(vec![pt(x0, y0), pt(x1, y0), pt(x1, y1), pt(x0, y1)])))
|
||
}
|
||
|
||
/// Punkt in Segment `seg` einer Polylinie einfügen. Ein Bogen wird exakt über die Kreisgeometrie in der
|
||
/// Winkel-Mitte geteilt (wie `kernel2d` Bogen-Segmente zuschneidet); eine Näherung über tessellierte
|
||
/// Punkte wäre zu ungenau. Die Bulge-Liste wird nur mitgeführt, wenn es eine gab.
|
||
/// Punkttyp `t` am Punkt `index` einer Polylinie (`setPolylineVertexType`, `polyline_vertex.rs`): die
|
||
/// Bulges der beiden anliegenden Segmente; `bulge` steht danach am Ende der Geometrie und fällt weg,
|
||
/// wenn alle Segmente gerade sind. Gesperrt, keine Polylinie, Index ohne Punkt oder keine Änderung →
|
||
/// None (kein leerer Undo-Schritt).
|
||
fn vertex_type(d: &Value, index: f64, t: crate::polyline_vertex::VertexType) -> Option<Value> {
|
||
use crate::polyline_vertex::{index_of, with_type, Poly};
|
||
if truthy(field(d, "locked")) {
|
||
return None;
|
||
}
|
||
let g = field(d, "geom")?;
|
||
if shape(g) != "polyline" {
|
||
return None;
|
||
}
|
||
let pts: Vec<(f64, f64)> = arr(field(g, "pts")).iter().map(xy).collect();
|
||
let i = index_of(index, pts.len())?;
|
||
// `g.bulge?.[k] ?? 0`
|
||
let bulge: Vec<f64> = arr(field(g, "bulge")).iter().map(|b| if b.is_null() { 0.0 } else { num_of(Some(b)) }).collect();
|
||
let nb = with_type(&Poly { pts: &pts, closed: truthy(field(g, "closed")), bulge: &bulge }, i, t);
|
||
let new_bulge = nb.iter().any(|b| *b != 0.0).then(|| Value::Array(nb.into_iter().map(js_num).collect()));
|
||
// Unverändert (ohne die grosse Geometrie zu vergleichen): gleiche Bögen, `bulge` steht schon am Ende.
|
||
let last_key = g.as_object().and_then(|m| m.keys().last()).map(String::as_str);
|
||
let same = match (field(g, "bulge"), &new_bulge) {
|
||
(None, None) => true,
|
||
(Some(old), Some(new)) => old == new && last_key == Some("bulge"),
|
||
_ => false,
|
||
};
|
||
if same {
|
||
return None;
|
||
}
|
||
let mut geom = with_opt(g, vec![("bulge", None)]);
|
||
if let (Value::Object(m), Some(b)) = (&mut geom, new_bulge) {
|
||
m.insert("bulge".into(), b);
|
||
}
|
||
Some(with_geom(d, geom))
|
||
}
|
||
|
||
fn insert_point(d: &Value, seg: f64, x: f64, y: f64) -> Option<Value> {
|
||
let g = field(d, "geom")?;
|
||
if shape(g) != "polyline" {
|
||
return None;
|
||
}
|
||
let pts = arr(field(g, "pts"));
|
||
let n = pts.len();
|
||
let k = index_in(seg, n)?;
|
||
let last = k == n - 1;
|
||
if last && !truthy(field(g, "closed")) {
|
||
return None;
|
||
}
|
||
let a = xy(&pts[k]);
|
||
let b = xy(if last { &pts[0] } else { &pts[k + 1] });
|
||
let bulge = num_or(arr(field(g, "bulge")).get(k), 0.0);
|
||
// `bulgeArc` der Fassade: gerade (|bulge| < 1e-9 oder NaN) ohne Bogen.
|
||
let arc = if bulge.abs() >= 1e-9 { crate::bulge::arc(a.0, a.1, b.0, b.1, bulge) } else { vec![] };
|
||
let (insert, b1, b2) = if arc.len() >= 6 {
|
||
let (cx, cy, r, a0, a1, sweep) = (arc[0], arc[1], arc[2], arc[3], arc[4], arc[5]);
|
||
let mid = a0 + sweep / 2.0;
|
||
let sign = if sweep < 0.0 { -1.0 } else { 1.0 };
|
||
(
|
||
pt(cx + r * jsnum::cos(mid), cy + r * jsnum::sin(mid)),
|
||
crate::bulge::between_angles(cx, cy, r, a0, mid, sign),
|
||
crate::bulge::between_angles(cx, cy, r, mid, a1, sign),
|
||
)
|
||
} else {
|
||
(pt(x, y), 0.0, 0.0)
|
||
};
|
||
let mut np: Vec<Value> = pts[..=k].to_vec();
|
||
np.push(insert);
|
||
np.extend_from_slice(&pts[k + 1..]);
|
||
let mut fields = vec![("pts", Value::Array(np))];
|
||
if truthy(field(g, "bulge")) {
|
||
let old = arr(field(g, "bulge"));
|
||
let mut nb: Vec<Value> = old.iter().take(k).cloned().collect();
|
||
nb.push(js_num(b1));
|
||
nb.push(js_num(b2));
|
||
nb.extend(old.iter().skip(k + 1).cloned());
|
||
fields.push(("bulge", Value::Array(nb)));
|
||
}
|
||
Some(with_geom(d, with_all(g, fields)))
|
||
}
|
||
|
||
/// `{...layers[0], thickness}` als einzige Schicht.
|
||
fn single_layer(layers: &[Value], thickness: f64) -> Value {
|
||
Value::Array(vec![with(&layers[0], "thickness", js_num(thickness))])
|
||
}
|
||
|
||
/// Neuer einschichtiger Typ `{id, name, layers}`.
|
||
fn new_type(id: &str, name: Value, layers: &[Value], thickness: f64) -> Value {
|
||
let mut m = Map::new();
|
||
m.insert("id".into(), id.into());
|
||
m.insert("name".into(), name);
|
||
m.insert("layers".into(), single_layer(layers, thickness));
|
||
Value::Object(m)
|
||
}
|
||
|
||
fn add(collection: &str, item: Value) -> Op {
|
||
Op::Add { collection: collection.into(), items: vec![item], at: None }
|
||
}
|
||
|
||
/// Dicke einer einschichtigen Wand (`setWallThickness`): exklusiven einschichtigen Wandtyp direkt
|
||
/// ändern, sonst einen eigenen Typ `new_id`/`new_name` anlegen und der Wand zuweisen.
|
||
fn wall_thickness(root: &Map<String, Value>, wall_id: &str, thickness: f64, new_id: &str, new_name: Value) -> Vec<Op> {
|
||
if !thickness.is_finite() || thickness <= 0.0 {
|
||
return vec![];
|
||
}
|
||
let Some(wall) = find(root, "walls", wall_id) else { return vec![] };
|
||
let wt_id = field(wall, "wallTypeId");
|
||
let Some(wt) = arr(root.get("wallTypes")).iter().find(|t| field(t, "id") == wt_id) else { return vec![] };
|
||
let layers = arr(field(wt, "layers"));
|
||
if layers.is_empty() {
|
||
return vec![];
|
||
}
|
||
let wt_idv = field(wt, "id");
|
||
let used_by_others = arr(root.get("walls")).iter().any(|w| id_of(w) != Some(wall_id) && field(w, "wallTypeId") == wt_idv);
|
||
if layers.len() == 1 && !used_by_others {
|
||
let tid = id_of(wt).unwrap_or("");
|
||
return find(root, "wallTypes", tid).map(|t| vec![replace("wallTypes", with(t, "layers", single_layer(arr(field(t, "layers")), thickness)))]).unwrap_or_default();
|
||
}
|
||
vec![add("wallTypes", new_type(new_id, new_name, layers, thickness)), replace("walls", with(wall, "wallTypeId", new_id.into()))]
|
||
}
|
||
|
||
/// Dicke einer einschichtigen Decke (`setCeilingThickness`), analog zur Wand; der geteilte
|
||
/// Alt-Wandtyp (`Ceiling.wallTypeId`) wird nie verändert.
|
||
pub(crate) fn ceiling_thickness(root: &Map<String, Value>, ceiling_id: &str, thickness: f64, new_id: &str, new_name: Value) -> Vec<Op> {
|
||
if !thickness.is_finite() || thickness <= 0.0 {
|
||
return vec![];
|
||
}
|
||
let Some(c) = find(root, "ceilings", ceiling_id) else { return vec![] };
|
||
let active = |c: &Value| -> Option<Value> {
|
||
let v = field(c, "ceilingTypeId");
|
||
if nullish(v) { field(c, "wallTypeId").cloned() } else { v.cloned() }
|
||
};
|
||
let active_id = active(c);
|
||
let by_id = |coll: &str, id: Option<&Value>| arr(root.get(coll)).iter().find(|t| field(t, "id") == id).cloned();
|
||
let Some(ct) = by_id("ceilingTypes", field(c, "ceilingTypeId")).or_else(|| by_id("wallTypes", field(c, "wallTypeId"))) else { return vec![] };
|
||
let layers = arr(field(&ct, "layers"));
|
||
if layers.is_empty() {
|
||
return vec![];
|
||
}
|
||
let used_by_others = arr(root.get("ceilings")).iter().any(|o| id_of(o) != Some(ceiling_id) && active(o) == active_id);
|
||
if layers.len() == 1 && !used_by_others && truthy(field(c, "ceilingTypeId")) {
|
||
let tid = id_of(&ct).unwrap_or("");
|
||
return find(root, "ceilingTypes", tid).map(|t| vec![replace("ceilingTypes", with(t, "layers", single_layer(arr(field(t, "layers")), thickness)))]).unwrap_or_default();
|
||
}
|
||
let mut nc = with(c, "ceilingTypeId", new_id.into());
|
||
if let Value::Object(m) = &mut nc {
|
||
m.shift_remove("thickness");
|
||
}
|
||
vec![add("ceilingTypes", new_type(new_id, new_name, layers, thickness)), replace("ceilings", nc)]
|
||
}
|
||
|
||
// ── Griff-Listen für die Anzeige ─────────────────────────────────────────────
|
||
|
||
/// Editier-Griffe einer 2D-Zeichnung in Modell-Metern (`drawingVertices`, gleiche Reihenfolge wie
|
||
/// [`drawing_grip`]): Ecken; Polylinie zusätzlich je Segment ein Bogen-Mitten-Griff; Kreis Ost/Nord;
|
||
/// Bogen Start/Ende/Mitte; Ellipse je Halbachse; Bemassung Kettenpunkte · Masslinie · je Segment die
|
||
/// Masszahl; Text Anker · Knicke · Spitze bzw. Pfadpunkte. `None` für die Textspalte (Rahmen-Ecken
|
||
/// brauchen die Schrift-Metrik der Hülle, `text/textFrame.ts`).
|
||
pub fn drawing_vertices(g: &Value, scale: f64) -> Option<Vec<(f64, f64)>> {
|
||
let p = |k: &str| xy(g.get(k).unwrap_or(&Value::Null));
|
||
let pts = |k: &str| arr(g.get(k)).iter().map(xy).collect::<Vec<_>>();
|
||
Some(match shape(g) {
|
||
"line" | "xline" | "ray" => vec![p("a"), p("b")],
|
||
"polyline" => {
|
||
let bulge = arr(field(g, "bulge"));
|
||
let closed = truthy(field(g, "closed"));
|
||
let mut out = polyline_vertices(pts("pts"), closed, |i| num_or(bulge.get(i), 0.0));
|
||
// Loch-Ecken hinter den Bogen-Griffen (Index ≥ 2n); nur geschlossene Polylinien tragen Löcher.
|
||
if closed && out.len() >= 6 {
|
||
for h in arr(field(g, "holes")) {
|
||
out.extend(arr(Some(h)).iter().map(xy));
|
||
}
|
||
}
|
||
out
|
||
}
|
||
"rect" | "image" => rect_corners(g).to_vec(),
|
||
"circle" => {
|
||
let (c, r) = (p("center"), num_of(field(g, "r")));
|
||
vec![(c.0 + r, c.1), (c.0, c.1 + r)]
|
||
}
|
||
"arc" => {
|
||
let (c, r) = (p("center"), num_of(field(g, "r")));
|
||
let (a0, a1) = (num_of(field(g, "a0")), num_of(field(g, "a1")));
|
||
let mid = (a0 + a1) / 2.0;
|
||
[a0, a1, mid].iter().map(|a| (c.0 + r * jsnum::cos(*a), c.1 + r * jsnum::sin(*a))).collect()
|
||
}
|
||
"ellipse" => {
|
||
let rot = num_of(field(g, "rotation"));
|
||
let (c, s) = (jsnum::cos(rot), jsnum::sin(rot));
|
||
let ctr = p("center");
|
||
let (rx, ry) = (num_of(field(g, "rx")), num_of(field(g, "ry")));
|
||
vec![(ctr.0 + rx * c, ctr.1 + rx * s), (ctr.0 - ry * s, ctr.1 + ry * c)]
|
||
}
|
||
"bezier" | "spline" => pts("pts"),
|
||
"dimension" => {
|
||
let mut out = pts("pts");
|
||
let n = out.len();
|
||
let nan = (f64::NAN, f64::NAN);
|
||
let (a, b) = (out.first().copied().unwrap_or(nan), out.last().copied().unwrap_or(nan));
|
||
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
|
||
let len = or1(hypot2(dx, dy));
|
||
let offset = num_of(field(g, "offset"));
|
||
let (nx, ny) = ((-dy / len) * offset, (dx / len) * offset);
|
||
out.push(((a.0 + b.0) / 2.0 + nx, (a.1 + b.1) / 2.0 + ny));
|
||
// Rundmass ([172]): ein Masszahl-Griff an der Zahl selbst.
|
||
if let Some(q) = round_dim_text_grip(g, scale) {
|
||
out.push(q);
|
||
return Some(out);
|
||
}
|
||
let h = dim_height(g, scale);
|
||
let offs = arr(field(g, "textOffsetsMm"));
|
||
// [172] Ohne gespeicherte Abweichung steht der Griff dort, wo der Plan die Zahl zeichnet.
|
||
let auto = crate::plan::drawings::dim_auto_offsets(&out[..n].iter().map(|q| crate::model::Vec2 { x: q.0, y: q.1 }).collect::<Vec<_>>(), h, offset);
|
||
for i in 0..n.saturating_sub(1) {
|
||
let stored = match offs.get(i) {
|
||
Some(o) if truthy(Some(o)) => (num_of(field(o, "along")), num_of(field(o, "perp"))),
|
||
_ => (0.0, 0.0),
|
||
};
|
||
let (along, perp) = if stored.0 != 0.0 || stored.1 != 0.0 { (mm_to_model(stored.0, scale), mm_to_model(stored.1, scale)) } else { auto.get(i).copied().unwrap_or((0.0, 0.0)) };
|
||
out.push(dim_text_pos(out[i], out[i + 1], offset, h, along, perp));
|
||
}
|
||
out
|
||
}
|
||
"libobj" => {
|
||
let a = p("at");
|
||
let rot = num_of(field(g, "rotation"));
|
||
vec![a, (a.0 + LIBOBJ_ROT_ARM * jsnum::cos(rot), a.1 + LIBOBJ_ROT_ARM * jsnum::sin(rot))]
|
||
}
|
||
"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")
|
||
} else if truthy(field(g, "leaderTarget")) {
|
||
let mut out = vec![p("at")];
|
||
out.extend(pts("leaderBendPoints"));
|
||
out.push(p("leaderTarget"));
|
||
out
|
||
} else if truthy(field(g, "width")) && num_of(field(g, "width")) > 0.0 {
|
||
return None;
|
||
} else {
|
||
vec![p("at")]
|
||
}
|
||
}
|
||
_ => vec![],
|
||
})
|
||
}
|
||
|
||
/// Griffe einer Polylinie: die Eckpunkte, dahinter je Segment ein Bogen-Mitten-Griff (Scheitel des
|
||
/// Bogens bzw. Sehnen-Mitte); `bulge(i)` = Bogen von Segment `i` (fehlend 0).
|
||
pub fn polyline_vertices(mut out: Vec<(f64, f64)>, closed: bool, bulge: impl Fn(usize) -> f64) -> Vec<(f64, f64)> {
|
||
let n = out.len();
|
||
let close = closed && n > 2;
|
||
let seg_count = n.saturating_sub(1) + usize::from(close);
|
||
for i in 0..seg_count {
|
||
let a = out[i];
|
||
let b = if i == n - 1 { out[0] } else { out[i + 1] };
|
||
let q = crate::bulge::point_at(a.0, a.1, b.0, b.1, bulge(i), 0.5);
|
||
out.push((q[0], q[1]));
|
||
}
|
||
out
|
||
}
|
||
|
||
/// Kanten-Griffe (`ringEdges`/`openEdges`): je Kante `(a, b, Mitte, Normale)`. Ring: Normale nach
|
||
/// aussen (vom Eckpunkt-Mittel weg), auch die Schlusskante; Kette: linke Normale, ohne Schlusskante.
|
||
/// `bulge` (Polylinie): Kanten an Bogen-Segmenten fallen weg (die haben ihren Bogen-Mitten-Griff).
|
||
pub fn edge_grips(verts: &[(f64, f64)], closed: bool, bulge: Option<&[f64]>) -> Vec<(usize, usize, (f64, f64), (f64, f64))> {
|
||
let n = verts.len();
|
||
if (closed && n < 3) || n < 2 {
|
||
return vec![];
|
||
}
|
||
let (mut cx, mut cy) = (0.0, 0.0);
|
||
for v in verts {
|
||
cx += v.0;
|
||
cy += v.1;
|
||
}
|
||
let ctr = (cx / n as f64, cy / n as f64);
|
||
let count = if closed { n } else { n - 1 };
|
||
let mut out = Vec::with_capacity(count);
|
||
for i in 0..count {
|
||
let j = (i + 1) % n;
|
||
if bulge.is_some_and(|b| !(b.get(i).copied().unwrap_or(0.0).abs() <= 1e-9)) {
|
||
continue;
|
||
}
|
||
let (a, b) = (verts[i], verts[j]);
|
||
let mid = ((a.0 + b.0) / 2.0, (a.1 + b.1) / 2.0);
|
||
let (lx, ly) = (-(b.1 - a.1), b.0 - a.0);
|
||
let l = or1(hypot2(lx, ly));
|
||
let mut nrm = (lx / l, ly / l);
|
||
if closed {
|
||
let out_dir = (mid.0 - ctr.0, mid.1 - ctr.1);
|
||
if nrm.0 * out_dir.0 + nrm.1 * out_dir.1 < 0.0 {
|
||
nrm = (nrm.0 * -1.0, nrm.1 * -1.0);
|
||
}
|
||
}
|
||
out.push((i, j, mid, nrm));
|
||
}
|
||
out
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use serde_json::json;
|
||
|
||
fn root(v: Value) -> Map<String, Value> {
|
||
v.as_object().unwrap().clone()
|
||
}
|
||
|
||
fn rq(v: Value) -> Request {
|
||
serde_json::from_value(v).unwrap()
|
||
}
|
||
|
||
fn entity(r: &GripResult) -> &Value {
|
||
match &r.ops[0] {
|
||
Op::Replace { entity, .. } => entity,
|
||
_ => panic!("replace erwartet"),
|
||
}
|
||
}
|
||
|
||
/// [333] Stützen-Griffe: Mitte verschiebt, Ecke setzt Querschnitt symmetrisch (auch gedreht), Rund = Radius, Dreh-Griff.
|
||
#[test]
|
||
fn stuetzen_griffe() {
|
||
let r = root(json!({"columns": [
|
||
{"id": "c", "position": {"x": 1, "y": 2}, "rotation": 0, "profile": {"kind": "rect", "width": 0.3, "depth": 0.3}, "height": 3},
|
||
{"id": "k", "position": {"x": 0, "y": 0}, "rotation": 0, "profile": {"kind": "round", "radius": 0.2}, "height": 3},
|
||
{"id": "g", "position": {"x": 0, "y": 0}, "rotation": 1.5707963267948966, "profile": {"kind": "rect", "width": 0.3, "depth": 0.3}, "height": 3},
|
||
{"id": "l", "locked": true, "position": {"x": 0, "y": 0}, "rotation": 0, "profile": {"kind": "round", "radius": 0.2}, "height": 3}
|
||
]}));
|
||
let ent = |req: Value| run(&Lookup::plain(&r), &rq(req)).unwrap();
|
||
let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
|
||
let e = ent(json!({"op": "columnGrip", "id": "c", "index": 0, "pt": [3, 3]}));
|
||
assert_eq!(entity(&e)["position"]["x"].as_f64(), Some(3.0));
|
||
// Ecke nach (+0.25, +0.2) vom Mittelpunkt: 0.5 × 0.4, Mitte bleibt.
|
||
let e = ent(json!({"op": "columnGrip", "id": "c", "index": 3, "pt": [1.25, 2.2]}));
|
||
let pr = &entity(&e)["profile"];
|
||
assert!(near(pr["width"].as_f64().unwrap(), 0.5) && near(pr["depth"].as_f64().unwrap(), 0.4));
|
||
assert_eq!(entity(&e)["position"]["x"].as_f64(), Some(1.0));
|
||
// Rund: Radius = Abstand zur Mitte.
|
||
let e = ent(json!({"op": "columnGrip", "id": "k", "index": 1, "pt": [0.3, 0.4]}));
|
||
assert!(near(entity(&e)["profile"]["radius"].as_f64().unwrap(), 0.5));
|
||
// Gedrehtes Profil (90°): lokale x = globale y.
|
||
let e = ent(json!({"op": "columnGrip", "id": "g", "index": 1, "pt": [0.1, 0.5]}));
|
||
let pr = &entity(&e)["profile"];
|
||
assert!(near(pr["width"].as_f64().unwrap(), 1.0) && near(pr["depth"].as_f64().unwrap(), 0.2));
|
||
// Drehen: Ziel auf +y → 90°.
|
||
let e = ent(json!({"op": "columnGrip", "id": "c", "index": 5, "pt": [1, 5]}));
|
||
assert!(near(entity(&e)["rotation"].as_f64().unwrap(), std::f64::consts::FRAC_PI_2));
|
||
// Nicht vorhandene Griffe, gesperrt, unbekannt.
|
||
assert!(ent(json!({"op": "columnGrip", "id": "k", "index": 5, "pt": [1, 1]})).ops.is_empty());
|
||
assert!(ent(json!({"op": "columnGrip", "id": "l", "index": 0, "pt": [1, 1]})).ops.is_empty());
|
||
assert!(ent(json!({"op": "columnGrip", "id": "x", "index": 0, "pt": [1, 1]})).ops.is_empty());
|
||
}
|
||
|
||
/// [333] Körper-Griffe: Ecke ziehen, Verschiebe-Griff (Schwerpunkt), Kreis nur verschieben.
|
||
#[test]
|
||
fn koerper_griffe() {
|
||
let r = root(json!({"extrudedSolids": [
|
||
{"id": "s", "points": [{"x": 0, "y": 0}, {"x": 2, "y": 0}, {"x": 2, "y": 2}, {"x": 0, "y": 2}], "height": 1},
|
||
{"id": "c", "points": [{"x": 0, "y": 0}, {"x": 2, "y": 0}, {"x": 2, "y": 2}, {"x": 0, "y": 2}], "circle": {"center": {"x": 1, "y": 1}, "r": 1}, "height": 1}
|
||
]}));
|
||
let ent = |req: Value| run(&Lookup::plain(&r), &rq(req)).unwrap();
|
||
let e = ent(json!({"op": "solidGrip", "id": "s", "index": 2, "pt": [3, 3]}));
|
||
assert_eq!(entity(&e)["points"][2]["x"].as_f64(), Some(3.0));
|
||
assert_eq!(entity(&e)["points"][0]["x"].as_f64(), Some(0.0));
|
||
let e = ent(json!({"op": "solidGrip", "id": "s", "index": 4, "pt": [11, 11]}));
|
||
assert_eq!(entity(&e)["points"][0]["x"].as_f64(), Some(10.0));
|
||
assert_eq!(entity(&e)["points"][2]["y"].as_f64(), Some(12.0));
|
||
assert!(ent(json!({"op": "solidGrip", "id": "s", "index": 5, "pt": [1, 1]})).ops.is_empty());
|
||
assert!(ent(json!({"op": "solidGrip", "id": "c", "index": 1, "pt": [1, 1]})).ops.is_empty());
|
||
let e = ent(json!({"op": "solidGrip", "id": "c", "index": 4, "pt": [6, 1]}));
|
||
assert_eq!(entity(&e)["circle"]["center"]["x"].as_f64(), Some(6.0));
|
||
assert_eq!(entity(&e)["points"][1]["x"].as_f64(), Some(7.0));
|
||
}
|
||
|
||
/// [280] Träger: Griff 0 Anfang, 1 Ende, 2 Mitte verschiebt; gesperrt/unbekannt/Index daneben ändern nichts.
|
||
#[test]
|
||
fn traeger_griffe() {
|
||
let r = root(json!({"beams": [{"id": "b", "start": {"x": 0, "y": 0}, "end": {"x": 4, "y": 0}, "width": 0.2, "height": 0.4}]}));
|
||
let ent = |req: Value| run(&Lookup::plain(&r), &rq(req)).unwrap();
|
||
let p = |v: &Value| (v["x"].as_f64().unwrap(), v["y"].as_f64().unwrap());
|
||
let e = ent(json!({"op": "beamGrip", "id": "b", "index": 0, "pt": [1, 1]}));
|
||
assert_eq!((p(&entity(&e)["start"]), p(&entity(&e)["end"])), ((1.0, 1.0), (4.0, 0.0)));
|
||
let e = ent(json!({"op": "beamGrip", "id": "b", "index": 1, "pt": [5, 2]}));
|
||
assert_eq!(p(&entity(&e)["end"]), (5.0, 2.0));
|
||
let e = ent(json!({"op": "beamGrip", "id": "b", "index": 2, "pt": [3, 1]}));
|
||
assert_eq!((p(&entity(&e)["start"]), p(&entity(&e)["end"])), ((1.0, 1.0), (5.0, 1.0)));
|
||
assert!(ent(json!({"op": "beamGrip", "id": "b", "index": 3, "pt": [3, 1]})).ops.is_empty());
|
||
assert!(ent(json!({"op": "beamGrip", "id": "x", "index": 0, "pt": [3, 1]})).ops.is_empty());
|
||
let locked = root(json!({"beams": [{"id": "b", "locked": true, "start": {"x": 0, "y": 0}, "end": {"x": 4, "y": 0}}]}));
|
||
assert!(run(&Lookup::plain(&locked), &rq(json!({"op": "beamGrip", "id": "b", "index": 0, "pt": [1, 1]}))).unwrap().ops.is_empty());
|
||
}
|
||
|
||
/// [281] Gefällelinie: Griff 0/1 verschiebt from/to, das Gefälle in % bleibt (rise skaliert mit der Länge).
|
||
#[test]
|
||
fn decke_gefaelle_griffe() {
|
||
let r = root(json!({"ceilings": [{"id": "c", "slope": {"from": {"x": 0, "y": 0}, "to": {"x": 5, "y": 0}, "rise": -0.3, "ramp": true}}, {"id": "f"}]}));
|
||
let ent = |req: Value| run(&Lookup::plain(&r), &rq(req)).unwrap();
|
||
let g = |e: &Value, k: &str| (e["slope"][k]["x"].as_f64().unwrap(), e["slope"][k]["y"].as_f64().unwrap());
|
||
let e = ent(json!({"op": "ceilingSlopeGrip", "id": "c", "index": 1, "pt": [10, 0]}));
|
||
let c = entity(&e);
|
||
assert_eq!((g(c, "from"), g(c, "to")), ((0.0, 0.0), (10.0, 0.0)));
|
||
assert!((c["slope"]["rise"].as_f64().unwrap() + 0.6).abs() < 1e-12 && c["slope"]["ramp"] == true);
|
||
let e = ent(json!({"op": "ceilingSlopeGrip", "id": "c", "index": 0, "pt": [1, 0]}));
|
||
let c = entity(&e);
|
||
assert_eq!(g(c, "from"), (1.0, 0.0));
|
||
assert!((c["slope"]["rise"].as_f64().unwrap() + 0.24).abs() < 1e-12);
|
||
assert!(ent(json!({"op": "ceilingSlopeGrip", "id": "c", "index": 2, "pt": [1, 0]})).ops.is_empty());
|
||
assert!(ent(json!({"op": "ceilingSlopeGrip", "id": "c", "index": 1, "pt": [0, 0]})).ops.is_empty());
|
||
assert!(ent(json!({"op": "ceilingSlopeGrip", "id": "f", "index": 0, "pt": [1, 0]})).ops.is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn js_zahlen() {
|
||
assert_eq!(js_num(5.0).to_string(), "5");
|
||
assert_eq!(js_num(-0.0).to_string(), "0");
|
||
assert_eq!(js_num(-3.0).to_string(), "-3");
|
||
assert_eq!(js_num(0.5).to_string(), "0.5");
|
||
assert_eq!(js_num(f64::NAN), json!("\u{1}NaN"));
|
||
assert_eq!(js_num(f64::NEG_INFINITY), json!("\u{1}-Infinity"));
|
||
assert_eq!(num_of(Some(&json!("\u{1}Infinity"))), f64::INFINITY);
|
||
assert_eq!(num_of(Some(&Value::Null)), 0.0);
|
||
assert!(num_of(None).is_nan());
|
||
}
|
||
|
||
/// [188] Wand am Anfang kürzen: das Fenster bleibt an seiner Stelle im Plan (Position ab Wandanfang wird
|
||
/// nachgeführt); am Ende kürzen ändert die Position nicht.
|
||
#[test]
|
||
fn wand_kuerzen_fenster_bleibt_stehen() {
|
||
let r = root(json!({
|
||
"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 10, "y": 0}}],
|
||
"openings": [{"id": "o", "hostWallId": "w", "position": 4.0, "width": 1.2}, {"id": "x", "hostWallId": "andere", "position": 4.0}]
|
||
}));
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "wallId": "w", "index": 0, "pt": [3, 0]}))).unwrap();
|
||
let ops: Vec<Value> = res.ops.iter().map(|o| o.to_json()).collect();
|
||
assert_eq!(ops.len(), 2, "Wand + eine Öffnung");
|
||
assert_eq!(ops[0]["entity"]["start"]["x"].as_f64(), Some(3.0));
|
||
assert_eq!(ops[1]["entity"]["id"], "o");
|
||
assert!((ops[1]["entity"]["position"].as_f64().unwrap() - 1.0).abs() < 1e-9, "4 m ab altem Anfang = 1 m ab neuem");
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [7, 0]}))).unwrap();
|
||
assert_eq!(res.ops.len(), 1, "Ende kürzen: Öffnung unverändert");
|
||
}
|
||
|
||
/// [140] Stempel-Griff: ohne eigenen Anker ab der gezeichneten Lage `pt` (sonst ab dem Pol), mit Anker ab ihm.
|
||
#[test]
|
||
fn raumstempel_ab_gezeichneter_lage() {
|
||
let room = json!({"id": "r", "boundary": [{"x": 0, "y": 0}, {"x": 4, "y": 0}, {"x": 4, "y": 4}, {"x": 0, "y": 4}]});
|
||
let r = root(json!({"rooms": [room.clone()]}));
|
||
let anchor = |q: Value| {
|
||
let e = run(&Lookup::plain(&r), &rq(q)).unwrap().ops[0].to_json()["entity"]["stampAnchor"].clone();
|
||
(e["x"].as_f64().unwrap(), e["y"].as_f64().unwrap())
|
||
};
|
||
assert_eq!(anchor(json!({"op": "roomStamp", "id": "r", "delta": [1, 0]})), (3.0, 2.0), "ab dem Pol");
|
||
assert_eq!(anchor(json!({"op": "roomStamp", "id": "r", "delta": [1, 0], "pt": [0.5, 3]})), (1.5, 3.0), "ab der gezeichneten Lage");
|
||
let mut fixed = room;
|
||
fixed["stampAnchor"] = json!({"x": 1, "y": 1});
|
||
let r2 = root(json!({"rooms": [fixed]}));
|
||
let e = run(&Lookup::plain(&r2), &rq(json!({"op": "roomStamp", "id": "r", "delta": [1, 0], "pt": [0.5, 3]}))).unwrap().ops[0].to_json()["entity"]["stampAnchor"].clone();
|
||
assert_eq!((e["x"].as_f64(), e["y"].as_f64()), (Some(2.0), Some(1.0)), "eigener Anker gewinnt");
|
||
}
|
||
|
||
/// [T2] Bogenwand: Griff 2 setzt den Scheitel (Bulge), Endpunkt-Griffe behalten ihn; gerade
|
||
/// gezogen fällt der Bulge weg.
|
||
#[test]
|
||
fn bogenwand_scheitel_griff() {
|
||
let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 4, "y": 0}, "bulge": 0.5}]}));
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "wallId": "w", "index": 2, "pt": [2, 2]}))).unwrap();
|
||
let e = res.ops[0].to_json()["entity"].clone();
|
||
assert!((e["bulge"].as_f64().unwrap() - 1.0).abs() < 1e-12, "{e}");
|
||
// Endpunkt-Griff: entlang des Kreises (Mittelpunkt/Radius bleiben), nicht frei.
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [5, 0]}))).unwrap();
|
||
let e = res.ops[0].to_json()["entity"].clone();
|
||
let (s, en) = (xy(&e["start"]), xy(&e["end"]));
|
||
let a = crate::wall_arc::WallArc::of(kernel2d::Vec2::new(s.0, s.1), kernel2d::Vec2::new(en.0, en.1), e["bulge"].as_f64()).unwrap();
|
||
let a0 = crate::wall_arc::WallArc::of(kernel2d::Vec2::new(0.0, 0.0), kernel2d::Vec2::new(4.0, 0.0), Some(0.5)).unwrap();
|
||
assert!(s == (0.0, 0.0) && (a.center.x - a0.center.x).abs() < 1e-9 && (a.center.y - a0.center.y).abs() < 1e-9 && (a.r - a0.r).abs() < 1e-9, "{e}");
|
||
assert!((en.0 - a0.center.x).hypot(en.1 - a0.center.y) - a0.r < 1e-9);
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "wallId": "w", "index": 2, "pt": [2, 0]}))).unwrap();
|
||
assert!(res.ops[0].to_json()["entity"].get("bulge").is_none());
|
||
}
|
||
|
||
/// [T2] Scheitel-Griff mit gehaltenem Modifikator (`free`): fester Mittelpunkt, Enden wandern radial.
|
||
#[test]
|
||
fn bogenwand_scheitel_fester_mittelpunkt() {
|
||
let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 4, "y": 0}, "bulge": 1.0}]}));
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "wallId": "w", "index": 2, "pt": [2, 3], "free": true}))).unwrap();
|
||
let e = res.ops[0].to_json()["entity"].clone();
|
||
let (s, en) = (xy(&e["start"]), xy(&e["end"]));
|
||
assert!((s.0 + 1.0).abs() < 1e-9 && s.1.abs() < 1e-9 && (en.0 - 5.0).abs() < 1e-9 && e["bulge"].as_f64() == Some(1.0), "{e}");
|
||
// Ohne Modifikator bleiben die Endpunkte fest.
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "wallId": "w", "index": 2, "pt": [2, 3]}))).unwrap();
|
||
let e = res.ops[0].to_json()["entity"].clone();
|
||
assert_eq!(xy(&e["start"]), (0.0, 0.0));
|
||
}
|
||
|
||
/// [T2] Endpunkt-Griff mit getippter Bogenlänge über dem Halbkreis: Öffnungswinkel l / r, Seite vom Cursor.
|
||
#[test]
|
||
fn bogenwand_endpunkt_bogenlaenge_ueber_halbkreis() {
|
||
let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 4, "y": 0}, "bulge": 1.0}]}));
|
||
let l = 3.0 * std::f64::consts::PI; // 270° bei r = 2
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, -2], "arcLength": l}))).unwrap();
|
||
let e = res.ops[0].to_json()["entity"].clone();
|
||
let (s, en) = (xy(&e["start"]), xy(&e["end"]));
|
||
let a = crate::wall_arc::WallArc::of(kernel2d::Vec2::new(s.0, s.1), kernel2d::Vec2::new(en.0, en.1), e["bulge"].as_f64()).unwrap();
|
||
assert!((a.length() - l).abs() < 1e-9 && a.sweep.abs() > std::f64::consts::PI, "{} {e}", a.length());
|
||
}
|
||
|
||
/// [172] Masszahl-Griff eines Radius-/Durchmesser-/Bogenmasses: Lage an der Zahl, rastet ein, Alt = frei.
|
||
#[test]
|
||
fn rundmass_masszahl_griff_rastet_ein() {
|
||
let h = 0.25;
|
||
let mk = |kind: &str, pts: Value| json!({"id": "d", "level": "L", "geom": {"shape": "dimension", "kind": kind, "pts": pts, "offset": 0.0}});
|
||
// Radius 2: Zahl mittig über der Strecke, Griff genau dort (Index = n + 1).
|
||
let d = mk("radius", json!([{"x": 0, "y": 0}, {"x": 2, "y": 0}]));
|
||
let v = drawing_vertices(d.get("geom").unwrap(), 100.0).unwrap();
|
||
assert_eq!(v.len(), 4, "{v:?}");
|
||
assert!((v[3].0 - 1.0).abs() < 1e-9 && (v[3].1 - 0.6 * h).abs() < 1e-9, "{:?}", v[3]);
|
||
let r = root(json!({"drawings2d": [d]}));
|
||
let run_at = |x: f64, y: f64, free: bool| {
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "drawingId": "d", "index": 3, "pt": [x, y], "scale": 100, "free": free}))).unwrap();
|
||
let o = entity(&res)["geom"]["textOffsetsMm"][0].clone();
|
||
(o["along"].as_f64().unwrap(), o["perp"].as_f64().unwrap())
|
||
};
|
||
// Nahe der Mitte: Vorgabe (0, 0).
|
||
assert_eq!(run_at(1.05, 0.17, false), (0.0, 0.0));
|
||
// Deutlich darüber: eine Zeile höher (1.35 h = 3.375 mm Papier bei 1:100 und h = 2.5 mm).
|
||
let (al, pe) = run_at(1.0, 0.15 + 0.4, false);
|
||
assert!(al.abs() < 1e-9 && (pe - 3.375).abs() < 1e-6, "{al} {pe}");
|
||
// Weit rechts: aussen rechts, bündig neben dem Strecken-Ende.
|
||
let (al, pe) = run_at(4.0, 0.15, false);
|
||
assert!(al > 0.0 && pe == 0.0, "{al} {pe}");
|
||
// Alt: frei, ohne Einrasten.
|
||
let (al, pe) = run_at(1.3, 0.35, true);
|
||
assert!((al - 3.0).abs() < 1e-6 && (pe - 2.0).abs() < 1e-6, "{al} {pe}");
|
||
// Griff steht danach an der verschobenen Zahl.
|
||
let moved = json!({"id": "d", "level": "L", "geom": {"shape": "dimension", "kind": "radius", "pts": [{"x": 0, "y": 0}, {"x": 2, "y": 0}], "offset": 0.0, "textOffsetsMm": [{"along": 3, "perp": 2}]}});
|
||
let v = drawing_vertices(moved.get("geom").unwrap(), 100.0).unwrap();
|
||
assert!((v[3].0 - 1.3).abs() < 1e-9 && (v[3].1 - 0.35).abs() < 1e-9, "{:?}", v[3]);
|
||
// Durchmesser: Anker im Mittelpunkt; Bogenlänge: genau ein Text-Griff (Index 4).
|
||
let dm = mk("diameter", json!([{"x": 0, "y": 0}, {"x": 2, "y": 0}]));
|
||
let v = drawing_vertices(dm.get("geom").unwrap(), 100.0).unwrap();
|
||
assert!(v[3].0.abs() < 1e-9, "{v:?}");
|
||
let ar = mk("arc", json!([{"x": 0, "y": 0}, {"x": 2, "y": 0}, {"x": 0, "y": 2}]));
|
||
let v = drawing_vertices(ar.get("geom").unwrap(), 100.0).unwrap();
|
||
assert_eq!(v.len(), 5, "{v:?}");
|
||
let r = root(json!({"drawings2d": [ar]}));
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "drawingId": "d", "index": 4, "pt": [1.4, 1.4], "scale": 100}))).unwrap();
|
||
assert!(entity(&res)["geom"]["textOffsetsMm"][0].is_object());
|
||
}
|
||
|
||
/// [333] Bibliotheks-Objekt: Griff 0 verschiebt, Griff 1 (0.6 m in Blickrichtung) dreht.
|
||
#[test]
|
||
fn libobj_griffe() {
|
||
let d = json!({"id": "d", "level": "L", "geom": {"shape": "libobj", "libId": "lib:x", "at": {"x": 1, "y": 1}, "rotation": 0}});
|
||
let v = drawing_vertices(d.get("geom").unwrap(), 100.0).unwrap();
|
||
assert_eq!(v.len(), 2);
|
||
assert!((v[1].0 - 1.6).abs() < 1e-9 && (v[1].1 - 1.0).abs() < 1e-9, "{v:?}");
|
||
let r = root(json!({"drawings2d": [d]}));
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "drawingId": "d", "index": 1, "pt": [1, 5], "scale": 100}))).unwrap();
|
||
assert!((res.ops[0].to_json()["entity"]["geom"]["rotation"].as_f64().unwrap() - std::f64::consts::FRAC_PI_2).abs() < 1e-9);
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "drawingId": "d", "index": 0, "pt": [3, 4], "scale": 100}))).unwrap();
|
||
assert_eq!(res.ops[0].to_json()["entity"]["geom"]["at"]["x"].as_f64(), Some(3.0));
|
||
}
|
||
|
||
/// [T2] Bogenlängen-/Radiusmass: Randpunkte-Griffe bleiben auf dem Kreis um den Mittelpunkt.
|
||
#[test]
|
||
fn bogenmass_griff_auf_dem_kreis() {
|
||
let d = json!({"id": "d", "level": "L", "geom": {"shape": "dimension", "kind": "arc", "pts": [{"x": 0, "y": 0}, {"x": 2, "y": 0}, {"x": 0, "y": 2}], "offset": 0.5}});
|
||
let r = root(json!({"drawings2d": [d]}));
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "drawingId": "d", "index": 2, "pt": [-6, 0], "scale": 100}))).unwrap();
|
||
let p = &res.ops[0].to_json()["entity"]["geom"]["pts"][2];
|
||
assert!((p["x"].as_f64().unwrap() + 2.0).abs() < 1e-9 && p["y"].as_f64().unwrap().abs() < 1e-9, "{p}");
|
||
// Mittelpunkt bleibt frei.
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "drawingId": "d", "index": 0, "pt": [1, 1], "scale": 100}))).unwrap();
|
||
let p = &res.ops[0].to_json()["entity"]["geom"]["pts"][0];
|
||
assert_eq!((p["x"].as_f64(), p["y"].as_f64()), (Some(1.0), Some(1.0)));
|
||
}
|
||
|
||
/// [68] Baugrube: Ecke, Kante und Sohlen-Griff (Index hinter der letzten Ecke).
|
||
#[test]
|
||
fn baugrube_griffe() {
|
||
let r = root(json!({"context": [{"id": "bg", "type": "excavation", "bottom": -2, "outline": [{"x": 0, "y": 0}, {"x": 4, "y": 0}, {"x": 4, "y": 4}, {"x": 0, "y": 4}]}]}));
|
||
let ent = |v: Value| run(&Lookup::plain(&r), &rq(v)).unwrap().ops[0].to_json()["entity"].clone();
|
||
let e = ent(json!({"op": "excavationGrip", "id": "bg", "index": 2, "pt": [5, 6]}));
|
||
assert_eq!(e["outline"][2], json!({"x": 5, "y": 6}));
|
||
// Kante 0–1 um 1 nach unten: beide Ecken wandern.
|
||
let e = ent(json!({"op": "excavationEdge", "id": "bg", "a": 0, "b": 1, "delta": [0, -1]}));
|
||
assert_eq!((e["outline"][0]["y"].as_f64(), e["outline"][1]["y"].as_f64()), (Some(-1.0), Some(-1.0)));
|
||
// Sohlen-Griff: Schwerpunkt-y = 2, Ziel-y = −1 → Sohle −3.
|
||
let e = ent(json!({"op": "excavationGrip", "id": "bg", "index": 4, "pt": [2, -1]}));
|
||
assert_eq!(e["bottom"], json!(-3));
|
||
assert_eq!(e["outline"][2], json!({"x": 4, "y": 4}));
|
||
}
|
||
|
||
/// [193] Höhenlinien-Satz: Punkt ziehen (flacher Index über alle Linien) und Punkt hinter einem Segment einfügen.
|
||
#[test]
|
||
fn hoehenlinien_griffe() {
|
||
let r = root(json!({"context": [{"id": "hl", "type": "contourSet", "contours": [
|
||
{"z": 1, "closed": false, "pts": [{"x": 0, "y": 0}, {"x": 2, "y": 0}, {"x": 4, "y": 0}]},
|
||
{"z": 2, "closed": true, "curve": {"cx": 0, "cy": 0}, "pts": [{"x": 0, "y": 1}, {"x": 2, "y": 1}, {"x": 2, "y": 3}]}]}]}));
|
||
let ent = |v: Value| run(&Lookup::plain(&r), &rq(v)).unwrap().ops.first().map(|o| o.to_json()["entity"].clone());
|
||
let e = ent(json!({"op": "contourGrip", "id": "hl", "index": 4, "pt": [9, 9]})).unwrap();
|
||
assert_eq!(e["contours"][1]["pts"][1], json!({"x": 9, "y": 9}));
|
||
assert!(e["contours"][1].get("curve").is_none());
|
||
assert_eq!(e["contours"][0]["pts"][1], json!({"x": 2, "y": 0}));
|
||
assert!(ent(json!({"op": "contourGrip", "id": "hl", "index": 6, "pt": [9, 9]})).is_none());
|
||
// Offene Linie: Segmente ab Punkt 0 und 1 (Punkt 2 hat keins); geschlossene: ab 3, 4, 5 (5 schliesst zum Anfang).
|
||
assert!(ent(json!({"op": "contourInsert", "id": "hl", "seg": 2, "pt": [3, 1]})).is_none());
|
||
let e = ent(json!({"op": "contourInsert", "id": "hl", "seg": 1, "pt": [3, 1]})).unwrap();
|
||
assert_eq!(e["contours"][0]["pts"].as_array().unwrap().len(), 4);
|
||
assert_eq!(e["contours"][0]["pts"][2], json!({"x": 3, "y": 1}));
|
||
let e = ent(json!({"op": "contourInsert", "id": "hl", "seg": 5, "pt": [1, 2]})).unwrap();
|
||
assert_eq!(e["contours"][1]["pts"][3], json!({"x": 1, "y": 2}));
|
||
assert!(ent(json!({"op": "contourInsert", "id": "hl", "seg": 6, "pt": [1, 2]})).is_none());
|
||
}
|
||
|
||
/// [193] Netzpunkt im Grundriss verschieben (z bleibt).
|
||
#[test]
|
||
fn netzpunkt_griff() {
|
||
let r = root(json!({"context": [{"id": "tm", "type": "terrainMesh", "positions": [0, 0, 5, 1, 0, 6, 0, 1, 7], "indices": [0, 1, 2]}]}));
|
||
let ent = |v: Value| run(&Lookup::plain(&r), &rq(v)).unwrap().ops.first().map(|o| o.to_json()["entity"].clone());
|
||
let e = ent(json!({"op": "meshGrip", "id": "tm", "index": 1, "pt": [3, 4]})).unwrap();
|
||
assert_eq!(e["positions"], json!([0, 0, 5, 3, 4, 6, 0, 1, 7]));
|
||
assert!(ent(json!({"op": "meshGrip", "id": "tm", "index": 3, "pt": [3, 4]})).is_none());
|
||
}
|
||
|
||
/// [193] Höhenlinien-Punkt löschen / aufräumen (Mindestpunktzahl offen 2, geschlossen 3).
|
||
#[test]
|
||
fn hoehenlinien_punkt_loeschen() {
|
||
let r = root(json!({"context": [{"id": "hl", "type": "contourSet", "contours": [
|
||
{"z": 1, "closed": false, "pts": [{"x": 0, "y": 0}, {"x": 2, "y": 0}, {"x": 4, "y": 0}]},
|
||
{"z": 2, "closed": true, "curve": {"cx": 0, "cy": 0}, "pts": [{"x": 0, "y": 1}, {"x": 2, "y": 1}, {"x": 2, "y": 3}]},
|
||
{"z": 3, "closed": false, "pts": [{"x": 0, "y": 5}, {"x": 5, "y": 5}]}]}]}));
|
||
let ent = |v: Value| run(&Lookup::plain(&r), &rq(v)).unwrap().ops.first().map(|o| o.to_json()["entity"].clone());
|
||
let e = ent(json!({"op": "ringDelete", "kind": "contours", "id": "hl", "index": 1})).unwrap();
|
||
assert_eq!(e["contours"][0]["pts"].as_array().unwrap().len(), 2);
|
||
assert_eq!(e["contours"][0]["pts"][1], json!({"x": 4, "y": 0}));
|
||
// geschlossen mit 3 Punkten und offen mit 2: nicht löschbar
|
||
assert!(ent(json!({"op": "ringDelete", "kind": "contours", "id": "hl", "index": 4})).is_none());
|
||
assert!(ent(json!({"op": "ringDelete", "kind": "contours", "id": "hl", "index": 6})).is_none());
|
||
assert!(ent(json!({"op": "ringDelete", "kind": "contours", "id": "hl", "index": 9})).is_none());
|
||
// Aufräumen: Punkt 1 liegt auf der Geraden -> weg; ein Punkt abseits bliebe.
|
||
let e = ent(json!({"op": "ringTidy", "kind": "contours", "id": "hl", "index": 1, "tol": 0.01})).unwrap();
|
||
assert_eq!(e["contours"][0]["pts"].as_array().unwrap().len(), 2);
|
||
assert!(ent(json!({"op": "ringTidy", "kind": "contours", "id": "hl", "index": 4, "tol": 0.01})).is_none());
|
||
}
|
||
|
||
/// [26] Dach: Ecken und Kanten von Umriss und Hof über den flachen Index; schiefer Umriss bleibt schief.
|
||
#[test]
|
||
fn dach_griffe_umriss_und_hof() {
|
||
let roof = json!({"id": "R", "type": "roof", "floorId": "F", "categoryCode": "35", "shape": "walm",
|
||
"outline": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 12, "y": 8}, {"x": 0, "y": 8}],
|
||
"holes": [[{"x": 3, "y": 2}, {"x": 5, "y": 2}, {"x": 5, "y": 4}, {"x": 3, "y": 4}]]});
|
||
let r = root(json!({"roofs": [roof]}));
|
||
let ent = |v: Value| run(&Lookup::plain(&r), &rq(v)).unwrap().ops.first().map(|o| o.to_json()["entity"].clone());
|
||
// Umriss-Ecke 2 ziehen: übrige Ecken (kein Rechteck erzwungen) und Höfe bleiben.
|
||
let e = ent(json!({"op": "roofVertex", "id": "R", "index": 2, "pt": [13, 9]})).unwrap();
|
||
assert_eq!(e["outline"][2], json!({"x": 13, "y": 9}));
|
||
assert_eq!(e["outline"][1], json!({"x": 10, "y": 0}));
|
||
assert_eq!(e["holes"][0][0], json!({"x": 3, "y": 2}));
|
||
// Hof-Ecke: flacher Index 4 + 2 = Ecke 2 des Hofs.
|
||
let e = ent(json!({"op": "roofVertex", "id": "R", "index": 6, "pt": [6, 5]})).unwrap();
|
||
assert_eq!(e["holes"][0][2], json!({"x": 6, "y": 5}));
|
||
assert_eq!(e["outline"].as_array().unwrap().len(), 4);
|
||
// Hof-Kante 4–5 (Hof-Ecken 0–1) um 1 nach oben.
|
||
let e = ent(json!({"op": "roofEdge", "id": "R", "a": 4, "b": 5, "delta": [0, 1]})).unwrap();
|
||
assert_eq!((e["holes"][0][0]["y"].as_f64(), e["holes"][0][1]["y"].as_f64()), (Some(3.0), Some(3.0)));
|
||
// Umriss-Kante 3–0 (Schlusskante, Westwand) um 1 nach aussen.
|
||
let e = ent(json!({"op": "roofEdge", "id": "R", "a": 3, "b": 0, "delta": [-1, 0]})).unwrap();
|
||
assert_eq!((e["outline"][3]["x"].as_f64(), e["outline"][0]["x"].as_f64()), (Some(-1.0), Some(-1.0)));
|
||
// Kante über zwei Ringe, Index ausserhalb, NaN: kein Op.
|
||
assert!(ent(json!({"op": "roofEdge", "id": "R", "a": 3, "b": 4, "delta": [0, 1]})).is_none());
|
||
assert!(ent(json!({"op": "roofVertex", "id": "R", "index": 8, "pt": [0, 0]})).is_none());
|
||
assert!(ent(json!({"op": "roofVertex", "id": "R", "index": -1, "pt": [0, 0]})).is_none());
|
||
}
|
||
|
||
/// [26] Ecke einfügen/löschen/aufräumen an Umriss-Ringen; Kanten-Neigung des Dachs läuft mit.
|
||
/// [191] Bögen in Umriss-Ringen: Scheitel-Griff setzt den Bulge, Einfügen teilt den Bogen auf demselben
|
||
/// Kreis, Löschen/Aufräumen fügt ihn wieder zusammen; ohne Bögen kein neues Feld.
|
||
#[test]
|
||
fn ring_boegen_scheitel_teilen_zusammenfuegen() {
|
||
let sq = json!([{"x": 0, "y": 0}, {"x": 4, "y": 0}, {"x": 4, "y": 4}, {"x": 0, "y": 4}]);
|
||
let r = root(json!({"ceilings": [{"id": "C", "outline": sq}], "rooms": [{"id": "Rm", "boundary": sq}],
|
||
"roofs": [{"id": "R", "outline": sq, "holes": [[{"x": 1, "y": 1}, {"x": 2, "y": 1}, {"x": 2, "y": 2}]]}]}));
|
||
let ent = |r: &Map<String, Value>, v: Value| run(&Lookup::plain(r), &rq(v)).unwrap().ops.first().map(|o| o.to_json()["entity"].clone());
|
||
// Kante 1 (x = 4) nach aussen zum Halbkreis: Scheitel bei (6, 2), Bulge −1 (Scheitel rechts der Kante).
|
||
let e = ent(&r, json!({"op": "ringArc", "kind": "ceiling", "id": "C", "seg": 1, "pt": [6, 2]})).unwrap();
|
||
assert_eq!(e["outlineBulge"], json!([0, -1, 0, 0]));
|
||
// Baugrube ebenso (Kontextobjekt); Böschung/Verbau je Kante bleiben.
|
||
let rx = root(json!({"context": [{"id": "bg", "type": "excavation", "bottom": -3, "outline": sq, "edgeSlopes": [45, 60, 45, 45]}]}));
|
||
let ex = ent(&rx, json!({"op": "ringArc", "kind": "excavation", "id": "bg", "seg": 1, "pt": [6, 2]})).unwrap();
|
||
assert_eq!((ex["outlineBulge"].clone(), ex["edgeSlopes"].clone()), (json!([0, -1, 0, 0]), json!([45, 60, 45, 45])));
|
||
let rx2 = root(json!({"context": [ex]}));
|
||
let back = ent(&rx2, json!({"op": "ringArc", "kind": "excavation", "id": "bg", "seg": 1, "pt": [4, 2]})).unwrap();
|
||
assert_eq!(back["outlineBulge"], json!([0, 0, 0, 0]), "auf die Sehne gezogen = gerade");
|
||
let e2 = ent(&r, json!({"op": "ringArc", "kind": "room", "id": "Rm", "seg": 3, "pt": [0.0005, 2]}));
|
||
assert!(e2.is_none() || e2.unwrap().get("boundaryBulge").is_none(), "fast gerade bleibt gerade, ohne Feld");
|
||
// Dach: Hof-Kante (flacher Index 4 + 1 = 5).
|
||
let e3 = ent(&r, json!({"op": "ringArc", "kind": "roof", "id": "R", "seg": 5, "pt": [1.8, 1.8]})).unwrap();
|
||
assert_eq!(e3["holesBulge"][0].as_array().unwrap().len(), 3);
|
||
assert!(e3["holesBulge"][0][1].as_f64().unwrap() != 0.0 && e3.get("outlineBulge").is_none());
|
||
// Ecke auf dem Bogen einfügen: zwei Viertelbögen desselben Kreises.
|
||
let r2 = root(json!({"ceilings": [e.clone()]}));
|
||
let ins = ent(&r2, json!({"op": "ringInsert", "kind": "ceiling", "id": "C", "seg": 1, "pt": [6, 2]})).unwrap();
|
||
let q = (std::f64::consts::PI / 8.0).tan();
|
||
let b = ins["outlineBulge"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::<Vec<_>>();
|
||
assert_eq!(b.len(), 5);
|
||
assert!((b[1] + q).abs() < 1e-9 && (b[2] + q).abs() < 1e-9, "{b:?}");
|
||
// Fläche bleibt (Halbkreis r = 2).
|
||
let area = |e: &Value, k: &str| {
|
||
let c: crate::model::Ceiling = serde_json::from_value(e.clone()).unwrap();
|
||
let _ = k;
|
||
c.outline_area()
|
||
};
|
||
assert!((area(&ins, "") - (16.0 + 2.0 * std::f64::consts::PI)).abs() < 1e-9);
|
||
// Aufräumen der eingefügten Ecke auf dem Kreis: wieder ein Halbkreis.
|
||
let r3 = root(json!({"ceilings": [ins.clone()]}));
|
||
let tidy = ent(&r3, json!({"op": "ringTidy", "kind": "ceiling", "id": "C", "index": 2})).unwrap();
|
||
let b = tidy["outlineBulge"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::<Vec<_>>();
|
||
assert_eq!(tidy["outline"].as_array().unwrap().len(), 4);
|
||
assert!((b[1] + 1.0).abs() < 1e-9 && b[0] == 0.0 && b[2] == 0.0, "{b:?}");
|
||
// Löschen einer Ecke zwischen Gerade und Bogen: gerade Verbindung.
|
||
let del = ent(&r2, json!({"op": "ringDelete", "kind": "ceiling", "id": "C", "index": 2})).unwrap();
|
||
assert_eq!(del["outlineBulge"], json!([0, 0, 0]));
|
||
// Ohne Bögen bleibt das Feld weg.
|
||
let plain = ent(&r, json!({"op": "ringInsert", "kind": "ceiling", "id": "C", "seg": 0, "pt": [2, -1]})).unwrap();
|
||
assert!(plain.get("outlineBulge").is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn ring_ecken_einfuegen_loeschen() {
|
||
let roof = json!({"id": "R", "type": "roof", "shape": "walm",
|
||
"outline": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 8}, {"x": 0, "y": 8}],
|
||
"holes": [[{"x": 3, "y": 2}, {"x": 5, "y": 2}, {"x": 5, "y": 4}]],
|
||
"edgePitchDeg": [30, null, 40, 50, 20, 21, 22]});
|
||
let r = root(json!({"roofs": [roof],
|
||
"ceilings": [{"id": "C", "outline": [{"x": 0, "y": 0}, {"x": 4, "y": 0}, {"x": 4, "y": 4}]}],
|
||
"rooms": [{"id": "Rm", "boundary": [{"x": 0, "y": 0}, {"x": 4, "y": 0}, {"x": 4, "y": 4}, {"x": 0, "y": 4}]}],
|
||
"context": [{"id": "bg", "type": "excavation", "outline": [{"x": 0, "y": 0}, {"x": 4, "y": 0}, {"x": 4, "y": 4}, {"x": 0, "y": 4}],
|
||
"edgeSlopes": [1, 2, 3, 4], "edgeShoring": [true, false, false, true]}],
|
||
"drawings2d": [{"id": "pl", "geom": {"shape": "polyline", "closed": true, "bulge": [0, 0, 0, 0.5],
|
||
"pts": [{"x": 0, "y": 0}, {"x": 4, "y": 0}, {"x": 4, "y": 4}, {"x": 0, "y": 4}]}}]}));
|
||
let ent = |v: Value| run(&Lookup::plain(&r), &rq(v)).unwrap().ops.first().map(|o| o.to_json()["entity"].clone());
|
||
// Dach: Kante 1 (Umriss) teilen -> neue Ecke 2, beide Hälften erben `null` (Giebel); Hof-Einträge rücken nach.
|
||
let e = ent(json!({"op": "ringInsert", "kind": "roof", "id": "R", "seg": 1, "pt": [11, 4]})).unwrap();
|
||
assert_eq!(e["outline"].as_array().unwrap().len(), 5);
|
||
assert_eq!(e["outline"][2], json!({"x": 11, "y": 4}));
|
||
assert_eq!(e["edgePitchDeg"], json!([30, null, null, 40, 50, 20, 21, 22]));
|
||
// Hof-Kante (flacher Index 5) teilen: Eintrag 21 verdoppelt, Umriss unberührt.
|
||
let e = ent(json!({"op": "ringInsert", "kind": "roof", "id": "R", "seg": 5, "pt": [5, 3]})).unwrap();
|
||
assert_eq!(e["holes"][0].as_array().unwrap().len(), 4);
|
||
assert_eq!(e["edgePitchDeg"], json!([30, null, 40, 50, 20, 21, 21, 22]));
|
||
// Löschen: Umriss-Ecke 2 -> Kante 1 (Nachbar -> Nachbar) bleibt, Eintrag 2 entfällt.
|
||
let e = ent(json!({"op": "ringDelete", "kind": "roof", "id": "R", "index": 2})).unwrap();
|
||
assert_eq!(e["outline"].as_array().unwrap().len(), 3);
|
||
assert_eq!(e["edgePitchDeg"], json!([30, null, 50, 20, 21, 22]));
|
||
// Ecke 0: die Schlusskante bleibt, Eintrag 0 entfällt.
|
||
let e = ent(json!({"op": "ringDelete", "kind": "roof", "id": "R", "index": 0})).unwrap();
|
||
assert_eq!(e["edgePitchDeg"], json!([null, 40, 50, 20, 21, 22]));
|
||
// Hof hat nur 3 Ecken, Index ausserhalb, falsche Art: nichts.
|
||
assert!(ent(json!({"op": "ringDelete", "kind": "roof", "id": "R", "index": 5})).is_none());
|
||
assert!(ent(json!({"op": "ringDelete", "kind": "roof", "id": "R", "index": 9})).is_none());
|
||
assert!(ent(json!({"op": "ringDelete", "kind": "ceiling", "id": "C", "index": 0})).is_none());
|
||
assert!(ent(json!({"op": "ringInsert", "kind": "wand", "id": "C", "seg": 0, "pt": [1, 1]})).is_none());
|
||
// Decke, Raum.
|
||
let e = ent(json!({"op": "ringInsert", "kind": "ceiling", "id": "C", "seg": 2, "pt": [1, 3]})).unwrap();
|
||
assert_eq!(e["outline"].as_array().unwrap().len(), 4);
|
||
assert_eq!(e["outline"][3], json!({"x": 1, "y": 3}));
|
||
let e = ent(json!({"op": "ringDelete", "kind": "room", "id": "Rm", "index": 1})).unwrap();
|
||
assert_eq!(e["boundary"].as_array().unwrap().len(), 3);
|
||
// Baugrube: Böschung/Verbau laufen mit.
|
||
let e = ent(json!({"op": "ringInsert", "kind": "excavation", "id": "bg", "seg": 3, "pt": [-1, 2]})).unwrap();
|
||
assert_eq!((e["edgeSlopes"].clone(), e["edgeShoring"].clone()), (json!([1, 2, 3, 4, 4]), json!([true, false, false, true, true])));
|
||
let e = ent(json!({"op": "ringDelete", "kind": "excavation", "id": "bg", "index": 1})).unwrap();
|
||
assert_eq!((e["edgeSlopes"].clone(), e["edgeShoring"].clone()), (json!([1, 3, 4]), json!([true, false, true])));
|
||
// Aufräumen: Ecke 1 auf der Geraden bzw. auf dem Nachbarn entfällt, eine echte Ecke bleibt.
|
||
let tidy = |kind: &str, id: &str, ring: Value, index: u32| {
|
||
let key = if kind == "ceiling" { "ceilings" } else { "rooms" };
|
||
let field = if kind == "ceiling" { "outline" } else { "boundary" };
|
||
let r2 = root(json!({ key: [{"id": id, field: ring}] }));
|
||
run(&Lookup::plain(&r2), &rq(json!({"op": "ringTidy", "kind": kind, "id": id, "index": index}))).unwrap().ops.first().map(|o| o.to_json()["entity"].clone())
|
||
};
|
||
let p = |x: f64, y: f64| json!({"x": x, "y": y});
|
||
assert_eq!(tidy("ceiling", "c", json!([p(0.0, 0.0), p(2.0, 0.001), p(4.0, 0.0), p(4.0, 4.0)]), 1).unwrap()["outline"].as_array().unwrap().len(), 3);
|
||
assert_eq!(tidy("room", "c", json!([p(0.0, 0.0), p(0.0, 0.0), p(4.0, 0.0), p(4.0, 4.0)]), 1).unwrap()["boundary"].as_array().unwrap().len(), 3);
|
||
assert!(tidy("room", "c", json!([p(0.0, 0.0), p(2.0, 1.0), p(4.0, 0.0), p(4.0, 4.0)]), 1).is_none());
|
||
assert!(tidy("room", "c", json!([p(0.0, 0.0), p(2.0, 0.001), p(4.0, 0.0)]), 1).is_none());
|
||
// Polylinie: Aufräumen entfernt die Ecke samt Bulge-Eintrag, aber nicht an einem Bogen-Segment.
|
||
let r3 = root(json!({"drawings2d": [
|
||
{"id": "a", "geom": {"shape": "polyline", "closed": true, "bulge": [0, 0.5, 0, 0], "pts": [p(0.0, 0.0), p(2.0, 0.0), p(4.0, 0.0), p(4.0, 4.0)]}},
|
||
{"id": "b", "geom": {"shape": "polyline", "closed": true, "bulge": [0, 0, 0, 0.5], "pts": [p(0.0, 0.0), p(2.0, 0.0), p(4.0, 0.0), p(4.0, 4.0)]}}]}));
|
||
let t3 = |id: &str| run(&Lookup::plain(&r3), &rq(json!({"op": "ringTidy", "kind": "polyline", "id": id, "index": 1}))).unwrap().ops.first().map(|o| o.to_json()["entity"].clone());
|
||
assert!(t3("a").is_none());
|
||
let g = &t3("b").unwrap()["geom"];
|
||
assert_eq!((g["pts"].as_array().unwrap().len(), g["bulge"].clone()), (3, json!([0, 0, 0.5])));
|
||
}
|
||
|
||
/// [176] Schnittlinie: Endpunkte und Knickpunkte als Griffe.
|
||
#[test]
|
||
fn schnittlinie_griffe() {
|
||
let lv = json!({"id": "s", "kind": "section", "linePoints": [{"x": 0, "y": 0}, {"x": 6, "y": 10}], "bendPoints": [{"x": 6, "y": 0}], "directionSign": 1});
|
||
let r = root(json!({"drawingLevels": [lv]}));
|
||
let ent = |v: Value| run(&Lookup::plain(&r), &rq(v)).unwrap().ops.first().map(|o| o.to_json()["entity"].clone());
|
||
let e = ent(json!({"op": "sectionLineGrip", "id": "s", "index": 1, "pt": [7, -1]})).unwrap();
|
||
assert_eq!(e["bendPoints"], json!([{"x": 7, "y": -1}]));
|
||
assert_eq!(e["linePoints"][1], json!({"x": 6, "y": 10}));
|
||
let e = ent(json!({"op": "sectionLineGrip", "id": "s", "index": 2, "pt": [5, 9]})).unwrap();
|
||
assert_eq!(e["linePoints"][1], json!({"x": 5, "y": 9}));
|
||
let e = ent(json!({"op": "sectionLineGrip", "id": "s", "index": 0, "pt": [1, 1]})).unwrap();
|
||
assert_eq!(e["linePoints"][0], json!({"x": 1, "y": 1}));
|
||
assert!(ent(json!({"op": "sectionLineGrip", "id": "s", "index": 3, "pt": [1, 1]})).is_none());
|
||
// Gerade Linie (ohne Knicke): Index 1 = Ende.
|
||
let r2 = root(json!({"drawingLevels": [{"id": "g", "kind": "section", "linePoints": [{"x": 0, "y": 0}, {"x": 5, "y": 0}]}]}));
|
||
let res = run(&Lookup::plain(&r2), &rq(json!({"op": "sectionLineGrip", "id": "g", "index": 1, "pt": [4, 2]}))).unwrap();
|
||
assert_eq!(entity(&res)["linePoints"][1], json!({"x": 4, "y": 2}));
|
||
assert!(entity(&res).get("bendPoints").is_none());
|
||
}
|
||
|
||
/// [176] Knick einfügen / löschen / aufräumen am bestehenden Schnitt.
|
||
#[test]
|
||
fn schnittlinie_knick_einfuegen_loeschen_aufraeumen() {
|
||
let lv = json!({"id": "s", "kind": "section", "linePoints": [{"x": 0, "y": 0}, {"x": 6, "y": 10}], "bendPoints": [{"x": 6, "y": 0}]});
|
||
let gerade = json!({"id": "g", "kind": "section", "linePoints": [{"x": 0, "y": 0}, {"x": 10, "y": 0}]});
|
||
let r = root(json!({"drawingLevels": [lv, gerade]}));
|
||
let ent = |v: Value| run(&Lookup::plain(&r), &rq(v)).unwrap().ops.first().map(|o| o.to_json()["entity"].clone());
|
||
// Gerade Linie: Segment 0 → erster Knick.
|
||
let e = ent(json!({"op": "sectionBendInsert", "id": "g", "seg": 0, "pt": [5, 3]})).unwrap();
|
||
assert_eq!(e["bendPoints"], json!([{"x": 5, "y": 3}]));
|
||
// Mit Knick: Segment 1 (zwischen Knick und Ende) → Knick an Stelle 1, Reihenfolge bleibt.
|
||
let e = ent(json!({"op": "sectionBendInsert", "id": "s", "seg": 1, "pt": [7, 4]})).unwrap();
|
||
assert_eq!(e["bendPoints"], json!([{"x": 6, "y": 0}, {"x": 7, "y": 4}]));
|
||
let e = ent(json!({"op": "sectionBendInsert", "id": "s", "seg": 0, "pt": [3, -1]})).unwrap();
|
||
assert_eq!(e["bendPoints"], json!([{"x": 3, "y": -1}, {"x": 6, "y": 0}]));
|
||
assert!(ent(json!({"op": "sectionBendInsert", "id": "s", "seg": 2, "pt": [1, 1]})).is_none());
|
||
// Löschen: Knick-Griff 1; Anfang/Ende lassen sich nicht löschen; ohne Knicke fällt das Feld weg.
|
||
let e = ent(json!({"op": "sectionBendDelete", "id": "s", "index": 1})).unwrap();
|
||
assert!(e.get("bendPoints").is_none());
|
||
assert!(ent(json!({"op": "sectionBendDelete", "id": "s", "index": 0})).is_none());
|
||
assert!(ent(json!({"op": "sectionBendDelete", "id": "s", "index": 2})).is_none());
|
||
// Aufräumen: Knick auf der Geraden bzw. auf dem Nachbarpunkt entfällt, ein echter Knick bleibt.
|
||
let r2 = root(json!({"drawingLevels": [
|
||
{"id": "a", "kind": "section", "linePoints": [{"x": 0, "y": 0}, {"x": 10, "y": 0}], "bendPoints": [{"x": 5, "y": 0.001}]},
|
||
{"id": "b", "kind": "section", "linePoints": [{"x": 0, "y": 0}, {"x": 10, "y": 0}], "bendPoints": [{"x": 0, "y": 0}, {"x": 5, "y": 3}]},
|
||
{"id": "c", "kind": "section", "linePoints": [{"x": 0, "y": 0}, {"x": 10, "y": 0}], "bendPoints": [{"x": 5, "y": 3}]},
|
||
{"id": "d", "kind": "section", "linePoints": [{"x": 0, "y": 0}, {"x": 10, "y": 0}], "bendPoints": [{"x": 5, "y": 0.02}]}
|
||
]}));
|
||
let tidy = |id: &str| run(&Lookup::plain(&r2), &rq(json!({"op": "sectionLineTidy", "id": id}))).unwrap().ops.first().map(|o| o.to_json()["entity"].clone());
|
||
// Mit Ansichts-Toleranz (3 cm) entfällt auch ein Knick, der nur 2 cm neben der Geraden liegt (ohne: bleibt).
|
||
assert!(tidy("d").is_none());
|
||
let grob = run(&Lookup::plain(&r2), &rq(json!({"op": "sectionLineTidy", "id": "d", "tol": 0.03}))).unwrap().ops.first().map(|o| o.to_json()["entity"].clone());
|
||
assert!(grob.unwrap().get("bendPoints").is_none());
|
||
assert!(tidy("a").unwrap().get("bendPoints").is_none());
|
||
assert_eq!(tidy("b").unwrap()["bendPoints"], json!([{"x": 5, "y": 3}]));
|
||
assert!(tidy("c").is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn wand_griff_und_sperre() {
|
||
let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}, "extra": 1}]}));
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]}))).unwrap();
|
||
assert_eq!(entity(&res).to_string(), r#"{"id":"w","start":{"x":0,"y":0},"end":{"x":2,"y":3},"extra":1}"#);
|
||
let locked = root(json!({"walls": [{"id": "w", "locked": true, "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}}]}));
|
||
assert!(run(&Lookup::plain(&locked), &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]}))).unwrap().ops.is_empty());
|
||
// Fehlendes Element: keine Op.
|
||
assert!(run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "wallId": "x", "index": 1, "pt": [2, 3]}))).unwrap().ops.is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn kreis_wird_ellipse() {
|
||
let r = root(json!({"drawings2d": [{"id": "d", "geom": {"shape": "circle", "center": {"x": 0, "y": 0}, "r": 1}}]}));
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "drawingId": "d", "index": 0, "pt": [2, 0]}))).unwrap();
|
||
assert_eq!(entity(&res)["geom"].to_string(), r#"{"shape":"ellipse","center":{"x":0,"y":0},"rx":2,"ry":1,"rotation":0}"#);
|
||
}
|
||
|
||
#[test]
|
||
fn kante_winkeltreu() {
|
||
// Trapez: die obere Kante nach oben ziehen, die Ecken wandern entlang der Schrägen.
|
||
let pts: Vec<Value> = [(0.0, 0.0), (4.0, 0.0), (3.0, 1.0), (1.0, 1.0)].iter().map(|p| pt(p.0, p.1)).collect();
|
||
let out = move_polygon_edge(&pts, 2.0, 3.0, 0.0, 1.0, true).unwrap();
|
||
assert_eq!(out.to_string(), r#"[{"x":0,"y":0},{"x":4,"y":0},{"x":2,"y":2},{"x":2,"y":2}]"#);
|
||
assert!(move_polygon_edge(&pts, 4.0, 0.0, 0.0, 1.0, true).is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn nan_als_marke() {
|
||
let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}}]}));
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveBy", "wallId": "w", "delta": ["\u{1}NaN", 0]}))).unwrap();
|
||
assert_eq!(entity(&res)["start"]["x"], json!("\u{1}NaN"));
|
||
}
|
||
|
||
#[test]
|
||
fn punkt_loeschen_mindestzahl() {
|
||
let r = root(json!({"drawings2d": [{"id": "d", "geom": {"shape": "polyline", "closed": false, "pts": [{"x": 0, "y": 0}, {"x": 1, "y": 0}]}}]}));
|
||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "deletePoint", "id": "d", "index": 0}))).unwrap();
|
||
assert_eq!(res.notice, Some("alert.polylineMinPoints"));
|
||
assert!(res.ops.is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn deckendicke_neuer_typ() {
|
||
let r = root(json!({
|
||
"wallTypes": [{"id": "wt", "name": "W", "layers": [{"componentId": "c", "thickness": 0.2}]}],
|
||
"ceilings": [{"id": "c1", "wallTypeId": "wt", "thickness": 0.3}, {"id": "c2", "wallTypeId": "wt"}],
|
||
}));
|
||
let ops = run(&Lookup::plain(&r), &rq(json!({"op": "ceilingThickness", "id": "c1", "thickness": 0.25, "newId": "ct-1", "newName": "Decke"}))).unwrap().ops;
|
||
assert_eq!(crate::ops::ops_to_json(&ops), r#"[{"kind":"add","collection":"ceilingTypes","items":[{"id":"ct-1","name":"Decke","layers":[{"componentId":"c","thickness":0.25}]}]},{"kind":"replace","collection":"ceilings","entity":{"id":"c1","wallTypeId":"wt","ceilingTypeId":"ct-1"}}]"#);
|
||
}
|
||
|
||
#[test]
|
||
fn loch_ecken_haben_griffe() {
|
||
let pl = |o: bool| json!({"id": "d", "geom": {"shape": "polyline", "closed": o, "pts": [{"x": 0, "y": 0}, {"x": 4, "y": 0}, {"x": 4, "y": 4}, {"x": 0, "y": 4}],
|
||
"holes": [[{"x": 1, "y": 1}, {"x": 2, "y": 1}, {"x": 2, "y": 2}]]}});
|
||
let v = drawing_vertices(&pl(true)["geom"], 100.0).unwrap();
|
||
assert_eq!(v.len(), 4 + 4 + 3);
|
||
assert_eq!(v[9], (2.0, 1.0));
|
||
let r = drawing_grip(&pl(true), 9.0, 3.0, 1.5, 100.0, false).unwrap();
|
||
assert_eq!((r["geom"]["holes"][0][1]["x"].as_f64(), r["geom"]["holes"][0][1]["y"].as_f64()), (Some(3.0), Some(1.5)));
|
||
assert_eq!(r["geom"]["pts"].as_array().unwrap().len(), 4);
|
||
assert!(drawing_grip(&pl(true), 11.0, 0.0, 0.0, 100.0, false).is_none());
|
||
// Bestehende Indizes bleiben: Bogen-Griff 4..8.
|
||
assert!(drawing_grip(&pl(true), 5.0, 2.0, -1.0, 100.0, false).unwrap()["geom"]["bulge"].is_array());
|
||
}
|
||
|
||
#[test]
|
||
fn griffe_und_kanten() {
|
||
let g = json!({"shape": "polyline", "closed": true, "pts": [{"x": 0, "y": 0}, {"x": 2, "y": 0}, {"x": 2, "y": 2}], "bulge": [0, 0.5, 0]});
|
||
let v = drawing_vertices(&g, 100.0).unwrap();
|
||
assert_eq!(v.len(), 6);
|
||
assert_eq!(v[3], (1.0, 0.0));
|
||
let e = edge_grips(&v[..3], true, Some(&[0.0, 0.5, 0.0]));
|
||
assert_eq!(e.iter().map(|x| (x.0, x.1)).collect::<Vec<_>>(), vec![(0, 1), (2, 0)]);
|
||
assert_eq!(e[0].3, (0.0, -1.0));
|
||
let text = json!({"shape": "text", "at": {"x": 0, "y": 0}, "width": 2});
|
||
assert!(drawing_vertices(&text, 100.0).is_none());
|
||
}
|
||
|
||
/// [172] Masszahl-Griff: rastet an festen Stellen ein, Mitte nur wenn die Zahl zwischen die Hilfslinien passt.
|
||
#[test]
|
||
fn masszahl_rastet_ein() {
|
||
let h = 0.25;
|
||
let w = crate::plan::drawings::dim_text_width(4.0, h);
|
||
let pad = crate::plan::drawings::dim_text_pad(h);
|
||
assert_eq!(dim_text_slot(4.0, h, 0.05, 0.02), (0.0, 0.0));
|
||
assert_eq!(dim_text_slot(4.0, h, 1.7, 0.0), (2.0 - w / 2.0 - pad, 0.0));
|
||
assert_eq!(dim_text_slot(4.0, h, 5.0, 0.1), (2.0 + w / 2.0 + pad, 0.0));
|
||
assert_eq!(dim_text_slot(4.0, h, -5.0, 0.0), (-(2.0 + w / 2.0 + pad), 0.0));
|
||
assert_eq!(dim_text_slot(4.0, h, 0.0, -1.0), (0.0, -1.95 * h));
|
||
// 0.3 m: Mitte entfällt (wäre die Vorgabe „aussen").
|
||
assert_ne!(dim_text_slot(0.3, h, 0.0, 0.0), (0.0, 0.0));
|
||
}
|
||
}
|