diff --git a/TODO.md b/TODO.md index 249961ae..adefa778 100644 --- a/TODO.md +++ b/TODO.md @@ -1130,6 +1130,16 @@ Prüfung des ganzen Programms (Rust-Kern, TS-Hülle, Build/Sicherheit), nur Code `cmd_edit`, `cmd_transform`, `cmd_wall_edit`, `cmd_split`, `cmd_paste`, Rest `cmd_solid`/`cmd_create` (Wand, Picks, Extrusion), `grips`, `selection_info`, `dim_assoc`, `pens`, `layers`, `geo_translate`, Importe; Einfügen einer Kopie eines Alt-Fehler-Elements (`add`) wird jetzt abgelehnt. Nicht in der Tauri-App geprüft. + 4.11. Stufe 2 (mechanisch, Verhalten gleich): `cmd_wall_edit` liest Wände, Wandtypen, Öffnungen, Bemassungen und + 2D-Grenzen typisiert (`&Project`/`&Wall`/`&Drawing2D`; `Axis::of(&Wall)`, `Plan.src: &Wall`); die rohen Elemente + holen nur noch `commit`/`join_ops`/`opening_ops`/`dim_ops` per id, um sie verlustfrei zurückzuschreiben. + `cmd_edit::ops/query` und die Wand-Anfragen (`pickWall`, Trim/Extend/Bruch/Offset/Verrunden) nehmen `&Project`; + `cmd_draw`: `auto_dims` (Aussenbemassung) und `pick_tangent` typisiert, `ops/preview/query` mit `&Project` + (`cmd_create::query` ebenso, `web/*` über `project_lookup`). **Offen** (Rest rohes JSON, Zahl der Zeilen mit + `field/num_of/truthy/js_num/arr`): `selection_info` ~200, `grips` ~145, `cmd_solid` ~90, `cmd_transform` ~80, + `cmd_create` ~60, `cmd_edit` (Kurven/Ecken/Aufloesen auf 2D-Zeichnungen) ~45, `cmd_draw` (Bemassung/Polylinie) ~40, + `cmd_split` ~25, `geo_translate`, `pens`, `layers`, Importe. `selection_info`/`grips` bewusst nicht angefasst: + sie geben fehlende/`null`-Felder unverändert ins Ergebnis-JSON weiter (undefined ≠ null), das braucht eigene Tests. - ✅ **[125] Doppelte Schnitt-Dominanz** (`render3d/section_boolean.rs` ↔ `core/plan_section.rs`) auf eine Fassung. · S 3.11.: eine Fassung `dossier_hatch::section_dominance` (f64, JS-`min/max`, Schneider-Vorauswahl `ugrid` — mit `ugrid` aus dem Kern nach `hatchgen` verschoben); `core/plan/section.rs` und `render3d/section_boolean.rs` sind diff --git a/src-tauri/core/src/cmd_create.rs b/src-tauri/core/src/cmd_create.rs index fde2889a..220c357f 100644 --- a/src-tauri/core/src/cmd_create.rs +++ b/src-tauri/core/src/cmd_create.rs @@ -982,7 +982,7 @@ pub fn ops(root: &Map, p: &Project, v: &Value) -> Option> "roof" => roof_ops(p, v, &ctx, ids), "column" => column_ops(v, &ctx, ids), "extrude" => extrude_ops(root, v, &ctx, ids), - _ => return crate::cmd_draw::ops(root, v, &ctx, ids).or_else(|| crate::cmd_solid::ops(root, p, v, &ctx, ids)), + _ => return crate::cmd_draw::ops(root, p, v, &ctx, ids).or_else(|| crate::cmd_solid::ops(root, p, v, &ctx, ids)), }) } @@ -1062,7 +1062,7 @@ pub fn preview_req(root: &Map, project: &Project, req: &Req, pts: } } _ => { - if !crate::cmd_draw::preview(root, v, &ctx, &pts, &mut p) && !crate::cmd_solid::preview(root, v, &pts, &mut p) { + if !crate::cmd_draw::preview(root, project, v, &ctx, &pts, &mut p) && !crate::cmd_solid::preview(root, v, &pts, &mut p) { p.ok = false; } } @@ -1071,7 +1071,7 @@ pub fn preview_req(root: &Map, project: &Project, req: &Req, pts: } /// Treffer-Abfragen der Zeichenbefehle (`None` = keine Abfrage dieses Moduls). -pub fn query(root: &Map, v: &Value) -> Option> { +pub fn query(root: &Map, p: &Project, v: &Value) -> Option> { let at = p_of(v, "pt"); let level = s_of(v, "level"); Some(Ok(match s_of(v, "q") { @@ -1087,7 +1087,7 @@ pub fn query(root: &Map, v: &Value) -> Option json!({ "hit": pick_profile(root, level, at).map_or(Value::Null, profile_json) }), "profile" => json!({ "hit": find(root, "drawings2d", s_of(v, "id")).map_or(Value::Null, profile_json) }), - _ => return crate::cmd_draw::query(root, v).or_else(|| crate::cmd_solid::query(root, v)).map(Ok), + _ => return crate::cmd_draw::query(root, p, v).or_else(|| crate::cmd_solid::query(root, v)).map(Ok), })) } @@ -1239,7 +1239,8 @@ mod tests { fn oeffnung_in_bogenwand() { // Halbkreis (0,0)→(4,0), Scheitel oben (2,2): Bogenlänge 2π. let r = root(json!({"walls": [{"id": "w", "floorId": "F1", "start": {"x": 0, "y": 0}, "end": {"x": 4, "y": 0}, "bulge": 1}], "windowTypes": [{"id": "FT"}]})); - let q = query(&r, &json!({"q": "pickWall", "level": "F1", "pt": [2, 2.2]})).unwrap().unwrap(); + let p = crate::document::Document::from_json(&Value::Object(r.clone()).to_string()).unwrap().project().unwrap().clone(); + let q = query(&r, &p, &json!({"q": "pickWall", "level": "F1", "pt": [2, 2.2]})).unwrap().unwrap(); assert_eq!(q["hit"]["id"], "w"); assert!((q["hit"]["t"].as_f64().unwrap() - std::f64::consts::PI).abs() < 1e-9); assert_eq!(q["hit"]["bulge"], 1); @@ -1251,7 +1252,8 @@ mod tests { #[test] fn oeffnung_pick_und_vorschau() { let r = root(json!({"walls": [{"id": "w", "floorId": "F1", "start": {"x": 0, "y": 0}, "end": {"x": 6, "y": 0}}], "windowTypes": [{"id": "FT"}]})); - let q = query(&r, &json!({"q": "pickWall", "level": "F1", "pt": [2, 0.3]})).unwrap().unwrap(); + let p = crate::document::Document::from_json(&Value::Object(r.clone()).to_string()).unwrap().project().unwrap().clone(); + let q = query(&r, &p, &json!({"q": "pickWall", "level": "F1", "pt": [2, 0.3]})).unwrap().unwrap(); assert_eq!(q["hit"]["id"], "w"); assert_eq!(q["hit"]["t"], 2); let o = ops(&r, &crate::model::lenient::typed_for_test(&r), &req(json!({"cmd": "opening", "wall": "w", "start": [0, 0], "end": [6, 0], "kind": "window", "pos": 5.5, "width": 1.2, "height": 1.2, "sill": 0.9}))).unwrap(); diff --git a/src-tauri/core/src/cmd_draw.rs b/src-tauri/core/src/cmd_draw.rs index 7f4e4859..2089d1a9 100644 --- a/src-tauri/core/src/cmd_draw.rs +++ b/src-tauri/core/src/cmd_draw.rs @@ -5,13 +5,14 @@ //! und die Treffer der Befehle (Tangenten-Objekt, Massketten). Einstieg über `cmd_create`. use crate::cmd_create::{ - add_op, b_of, circle_pts, find, level_of, n_of, normalize, obj, opt_n, opt_p, p_of, pair, point_segment_distance, polyline_edges, - pts_of, pv, pvs, s, s_of, seg_len, to_p, type_thickness, wall_types, Ctx, Preview, V, EPS, + add_op, b_of, circle_pts, find, n_of, normalize, obj, opt_n, opt_p, p_of, pair, point_segment_distance, polyline_edges, + pts_of, pv, pvs, s, s_of, seg_len, to_p, Ctx, Preview, V, EPS, }; use crate::cmd_transform::{IdGen, Shapes}; -use crate::json_util::{arr, field, js_num, num_of, num_or, with, xy}; +use crate::json_util::{arr, field, js_num, num_of, with, xy}; use crate::jsmath::hypot2; use crate::jsnum; +use crate::model::{Drawing2D, Drawing2DGeom, Project, Vec2, Wall, WallReferenceLine}; use crate::ops::{id_of, Op}; use kernel2d::{self as k, TangentTarget, Vec2 as P}; use serde_json::{json, Map, Value}; @@ -362,21 +363,17 @@ fn in_arc_span(a0: f64, a1: f64, ang: f64) -> bool { } /// Gerade Kanten einer Form für die Tangenten-Wahl (Bogen-Segmente ausgenommen). -fn straight_edges(g: &Value) -> Vec<(V, V)> { - let p = |k: &str| xy(field(g, k).unwrap_or(&Value::Null)); - match field(g, "shape").and_then(Value::as_str) { - Some("line") => vec![(p("a"), p("b"))], - Some("rect") => { - let (mn, mx) = (p("min"), p("max")); - polyline_edges(&corners_of(mn, mx), true) - } - Some("polyline") => { - let pts: Vec = arr(field(g, "pts")).iter().map(xy).collect(); - let bulge = arr(field(g, "bulge")); - polyline_edges(&pts, crate::json_util::truthy(field(g, "closed"))) +fn straight_edges(g: &Drawing2DGeom) -> Vec<(V, V)> { + let v = |p: &Vec2| (p.x, p.y); + match g { + Drawing2DGeom::Line { a, b } => vec![(v(a), v(b))], + Drawing2DGeom::Rect { min, max } => polyline_edges(&corners_of(v(min), v(max)), true), + Drawing2DGeom::Polyline { pts, closed, bulge } => { + let pts: Vec = pts.iter().map(v).collect(); + polyline_edges(&pts, *closed) .into_iter() .enumerate() - .filter(|(i, _)| num_or(bulge.get(*i), 0.0).abs() <= EPS) + .filter(|(i, _)| bulge.as_ref().and_then(|b| b.get(*i)).copied().unwrap_or(0.0).abs() <= EPS) .map(|(_, e)| e) .collect() } @@ -401,30 +398,37 @@ fn target_of(v: &Value) -> Option { } /// Nächstes tangentenfähiges Element (Gerade oder Kreis/Bogen) zum Klickpunkt. -fn pick_tangent<'a>(root: &'a Map, level: &str, at: V) -> Option<(TangentTarget, &'a Value)> { - let mut best: Option<(TangentTarget, &Value)> = None; +fn pick_tangent<'a>(p: &'a Project, level: &str, at: V) -> Option<(TangentTarget, &'a Drawing2D)> { + let mut best: Option<(TangentTarget, &Drawing2D)> = None; let mut best_d = TTR_HIT_TOL; - for d in arr(root.get("drawings2d")) { - if level_of(d) != Some(level) { + for d in &p.drawings2d { + if d.level_id != level { continue; } - let Some(g) = field(d, "geom") else { continue }; - let shape = field(g, "shape").and_then(Value::as_str); - if shape == Some("circle") || shape == Some("arc") { - let c = xy(field(g, "center").unwrap_or(&Value::Null)); - let r = num_of(field(g, "r")); - let dd = (dist(at, c) - r).abs(); - let span = shape == Some("circle") || in_arc_span(num_of(field(g, "a0")), num_of(field(g, "a1")), angle(c, at)); - if dd < best_d && span { - best_d = dd; - best = Some((TangentTarget::Circle { center: to_p(c), r }, d)); - } - } else { - for (a, b) in straight_edges(g) { - let dd = point_segment_distance(at, a, b); - if dd < best_d { + match &d.geom { + g @ (Drawing2DGeom::Circle { .. } | Drawing2DGeom::Arc { .. }) => { + let (center, r) = match g { + Drawing2DGeom::Circle { center, r } | Drawing2DGeom::Arc { center, r, .. } => (center, *r), + _ => continue, + }; + let c = (center.x, center.y); + let dd = (dist(at, c) - r).abs(); + let span = match g { + Drawing2DGeom::Arc { a0, a1, .. } => in_arc_span(*a0, *a1, angle(c, at)), + _ => true, + }; + if dd < best_d && span { best_d = dd; - best = Some((TangentTarget::Line { a: to_p(a), b: to_p(b) }, d)); + best = Some((TangentTarget::Circle { center: to_p(c), r }, d)); + } + } + g => { + for (a, b) in straight_edges(g) { + let dd = point_segment_distance(at, a, b); + if dd < best_d { + best_d = dd; + best = Some((TangentTarget::Line { a: to_p(a), b: to_p(b) }, d)); + } } } } @@ -1130,40 +1134,37 @@ fn dimension_preview(v: &Value, pts: &[V], p: &mut Preview) { // ── Aussenbemassung ────────────────────────────────────────────────────────── /// Aussenbemassung des Geschosses `level` (Ketten aus `auto_dimensions`), ids `prefix-Geschoss-Seite-Kette`. -fn auto_dims(root: &Map, ctx: &Ctx, prefix: &str, scale: f64) -> Vec { +fn auto_dims(root: &Map, pr: &Project, ctx: &Ctx, prefix: &str, scale: f64) -> Vec { use crate::auto_dimensions::{auto_exterior_dimensions, OpeningIn, WallIn}; - let types = wall_types(root); - let walls: Vec<&Value> = arr(root.get("walls")).iter().filter(|w| crate::cmd_create::floor_of(w) == Some(ctx.level)).collect(); + let walls: Vec<&Wall> = pr.walls.iter().filter(|w| w.floor_id == ctx.level).collect(); if walls.is_empty() { return Vec::new(); } - let p = |w: &Value, k: &str| xy(field(w, k).unwrap_or(&Value::Null)); + let p = |v: &Vec2| (v.x, v.y); let win: Vec = walls .iter() .map(|w| { - let tid = field(w, "wallTypeId").and_then(Value::as_str); - let th = types.iter().find(|t| id_of(t) == tid).map_or(0.3, type_thickness); - let (a, b) = (p(w, "start"), p(w, "end")); + let th = pr.wall_types.iter().find(|t| t.id == w.wall_type_id).map_or(0.3, |t| t.layers.iter().fold(0.0, |sum, l| sum + l.thickness)); + let (a, b) = (p(&w.start), p(&w.end)); // Wandmitte gegenüber der Achse (Referenzlinie links/rechts bzw. -versatz, wie `dim_assoc`). let half = th / 2.0; - let shift = match (field(w, "referenceOffset").and_then(Value::as_f64), field(w, "referenceLine").and_then(Value::as_str)) { + let shift = match (w.reference_offset, w.reference_line) { (Some(v), _) => v.clamp(-half, half), - (None, Some("left")) => half, - (None, Some("right")) => -half, + (None, Some(WallReferenceLine::Left)) => half, + (None, Some(WallReferenceLine::Right)) => -half, _ => 0.0, }; - WallIn { start: [a.0, a.1], end: [b.0, b.1], thickness: th, shift, bulge: field(w, "bulge").and_then(Value::as_f64).unwrap_or(0.0) } + WallIn { start: [a.0, a.1], end: [b.0, b.1], thickness: th, shift, bulge: w.bulge.unwrap_or(0.0) } }) .collect(); let mut oin = Vec::new(); - for o in arr(root.get("openings")) { - let host = field(o, "hostWallId").and_then(Value::as_str); - let Some(i) = walls.iter().position(|w| id_of(w) == host) else { continue }; - let (a, b) = (p(walls[i], "start"), p(walls[i], "end")); + for o in pr.openings.iter().flatten() { + let Some(i) = walls.iter().position(|w| w.id == o.host_wall_id) else { continue }; + let (a, b) = (p(&walls[i].start), p(&walls[i].end)); // Bogenwand ([T2]): Lage = Bogenlänge, Leibungen auf dem Achsbogen. let arc = win[i].arc(); let axis = arc.map_or_else(|| dist(a, b), |x| x.length()); - let (pos, width) = (num_of(field(o, "position")), num_of(field(o, "width"))); + let (pos, width) = (o.position, o.width); let from = jsnum::max(0.0, jsnum::min(pos, axis)); let to = jsnum::max(from, jsnum::min(pos + width, axis)); if to - from < 1e-4 { @@ -1186,7 +1187,7 @@ fn auto_dims(root: &Map, ctx: &Ctx, prefix: &str, scale: f64) -> .into_iter() .map(|c| { let id = match c.arc { - Some((_, wi)) => format!("{prefix}-{}-arc-{}", ctx.level, id_of(walls[wi]).unwrap_or("")), + Some((_, wi)) => format!("{prefix}-{}-arc-{}", ctx.level, walls[wi].id), None => format!("{prefix}-{}-{}-{}", ctx.level, SIDES[c.side as usize], CHAINS[c.chain as usize]), }; let pts = Value::Array(c.pts.iter().map(|q| crate::json_util::pt(q[0], q[1])).collect()); @@ -1211,8 +1212,8 @@ fn autodim_scale(v: &Value) -> f64 { v.get("scale").and_then(Value::as_f64).filter(|s| s.is_finite() && *s > 0.0).unwrap_or(100.0) } -fn autodim_ops(root: &Map, v: &Value, ctx: &Ctx) -> Vec { - let dims = auto_dims(root, ctx, "autodim", autodim_scale(v)); +fn autodim_ops(root: &Map, p: &Project, v: &Value, ctx: &Ctx) -> Vec { + let dims = auto_dims(root, p, ctx, "autodim", autodim_scale(v)); if dims.is_empty() { return Vec::new(); } @@ -1228,7 +1229,7 @@ fn autodim_ops(root: &Map, v: &Value, ctx: &Ctx) -> Vec { // ═════════════════════════════════════════════════════════════════════════════ /// Ops eines 2D-Zeichenbefehls (`None` = keiner dieses Moduls). -pub fn ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Option> { +pub fn ops(root: &Map, p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Option> { let geom2 = |shape: &str| obj(vec![("shape", s(shape)), ("a", pt_val(v, "a")), ("b", pt_val(v, "b"))]); Some(match s_of(v, "cmd") { "line" | "xline" | "ray" => add_drawing(v, ctx, ids, geom2(s_of(v, "cmd"))), @@ -1316,13 +1317,13 @@ pub fn ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> }, "dimround" => dimround_ops(root, v, ctx, ids), "dimension" => dimension_ops(root, v, ctx, ids), - "autodim" => autodim_ops(root, v, ctx), + "autodim" => autodim_ops(root, p, v, ctx), _ => return None, }) } /// Vorschau eines 2D-Zeichenbefehls (`false` = keiner dieses Moduls). -pub fn preview(root: &Map, v: &Value, ctx: &Ctx, pts: &[V], p: &mut Preview) -> bool { +pub fn preview(root: &Map, project: &Project, v: &Value, ctx: &Ctx, pts: &[V], p: &mut Preview) -> bool { match s_of(v, "cmd") { "xline" | "ray" => { if let [a, c] = pts { @@ -1390,18 +1391,18 @@ pub fn preview(root: &Map, v: &Value, ctx: &Ctx, pts: &[V], p: &m "dimension" => dimension_preview(v, pts, p), "grid" => grid_preview(v, pts, p), "dimround" => dimround_preview(root, v, ctx, pts, p), - "autodim" => p.ok = !auto_dims(root, ctx, "autodim", autodim_scale(v)).is_empty(), + "autodim" => p.ok = !auto_dims(root, project, ctx, "autodim", autodim_scale(v)).is_empty(), _ => return false, } true } /// Treffer-Abfragen der 2D-Befehle (`None` = keine dieses Moduls). -pub fn query(root: &Map, v: &Value) -> Option { +pub fn query(root: &Map, p: &Project, v: &Value) -> Option { let at = p_of(v, "pt"); Some(match s_of(v, "q") { - "pickTangent" => match pick_tangent(root, s_of(v, "level"), at) { - Some((t, d)) => json!({ "hit": { "target": target_json(&t), "id": id_of(d) } }), + "pickTangent" => match pick_tangent(p, s_of(v, "level"), at) { + Some((t, d)) => json!({ "hit": { "target": target_json(&t), "id": d.id } }), None => json!({ "hit": null }), }, "dimChain" => { @@ -1435,12 +1436,12 @@ mod tests { let v = json!({"cmd": "text", "at": {"x": 0.1, "y": -0.1}, "ctx": {"level": "blatt", "cat": "20", "textHeight": 0.0035}}); let c = crate::cmd_create::ctx_of(&v); assert_eq!(c.text_height, 0.0035); - let o = ops(&Map::new(), &v, &c, &mut IdGen::new("s")).unwrap(); + let o = ops(&Map::new(), &Project::default(), &v, &c, &mut IdGen::new("s")).unwrap(); assert_eq!(o[0].to_json()["items"][0]["geom"]["height"], 0.0035); // [37] Im Grundriss in Papiergrösse (2.5 mm), auf dem Blatt (`sheet`) nicht. assert_eq!(o[0].to_json()["items"][0]["geom"]["paperHeight"], 2.5); let sheet = json!({"cmd": "text", "at": {"x": 0.1, "y": -0.1}, "ctx": {"level": "blatt", "cat": "20", "textHeight": 0.0035, "sheet": true}}); - let o = ops(&Map::new(), &sheet, &crate::cmd_create::ctx_of(&sheet), &mut IdGen::new("s")).unwrap(); + let o = ops(&Map::new(), &Project::default(), &sheet, &crate::cmd_create::ctx_of(&sheet), &mut IdGen::new("s")).unwrap(); assert!(o[0].to_json()["items"][0]["geom"].get("paperHeight").is_none()); let plain = json!({"ctx": {"level": "eg", "textHeight": -1}}); assert_eq!(crate::cmd_create::ctx_of(&plain).text_height, crate::cmd_create::DEFAULT_TEXT_HEIGHT); @@ -1454,7 +1455,7 @@ mod tests { #[test] fn achsraster_befehl() { let v = json!({"cmd": "grid", "at": {"x": 1, "y": 2}, "xs": "5 3x6", "ys": "4,5 4", "angle": 0, "bubbles": "end", "levels": ["L"]}); - let o = ops(&Map::new(), &v, &ctx(), &mut IdGen::new("s")).unwrap(); + let o = ops(&Map::new(), &Project::default(), &v, &ctx(), &mut IdGen::new("s")).unwrap(); let g = &o[0].to_json()["items"][0]["geom"]; assert_eq!(g["shape"], "grid"); assert_eq!(g["a"].as_array().unwrap().len(), 5); @@ -1466,10 +1467,10 @@ mod tests { assert!(serde_json::from_value::(g.clone()).is_ok()); // Ohne `angle` (Befehl aus der Hülle) gilt 0; leere Querachsen sind erlaubt. let bare = json!({"cmd": "grid", "at": [0, 0], "xs": "5", "ys": ""}); - let o2 = ops(&Map::new(), &bare, &ctx(), &mut IdGen::new("s")).unwrap(); + let o2 = ops(&Map::new(), &Project::default(), &bare, &ctx(), &mut IdGen::new("s")).unwrap(); assert_eq!(o2[0].to_json()["items"][0]["geom"]["angle"], 0); let bad = json!({"cmd": "grid", "at": {"x": 0, "y": 0}, "xs": "x", "ys": ""}); - assert!(ops(&Map::new(), &bad, &ctx(), &mut IdGen::new("s")).unwrap().is_empty()); + assert!(ops(&Map::new(), &Project::default(), &bad, &ctx(), &mut IdGen::new("s")).unwrap().is_empty()); // Vorschau am Cursor. let mut p = Preview { shapes: Shapes::default(), ok: false, info: vec![] }; grid_preview(&v, &[(0.0, 0.0)], &mut p); @@ -1482,18 +1483,18 @@ mod tests { let root = json!({"drawings2d": [{"id": "K", "levelId": "L", "categoryCode": "20", "geom": {"shape": "circle", "center": {"x": 1, "y": 1}, "r": 2}}]}); let root = root.as_object().unwrap().clone(); let v = json!({"cmd": "dimround", "kind": "diameter", "pts": [[3.01, 1.0]]}); - let o = ops(&root, &v, &ctx(), &mut IdGen::new("s")).unwrap(); + let o = ops(&root, &Project::default(), &v, &ctx(), &mut IdGen::new("s")).unwrap(); let g = &o[0].to_json()["items"][0]["geom"]; assert_eq!(g["kind"], "diameter"); assert_eq!(g["refs"][0]["feature"], "center"); assert_eq!(g["refs"][1]["feature"], "rim"); let v = json!({"cmd": "dimround", "kind": "arc", "pts": [[3.0, 1.0], [1.0, 3.0]], "side": [1.0, 4.0]}); - let g = &ops(&root, &v, &ctx(), &mut IdGen::new("s")).unwrap()[0].to_json()["items"][0]["geom"]; + let g = &ops(&root, &Project::default(), &v, &ctx(), &mut IdGen::new("s")).unwrap()[0].to_json()["items"][0]["geom"]; assert_eq!(g["pts"].as_array().unwrap().len(), 3); assert!((g["offset"].as_f64().unwrap() - 1.0).abs() < 1e-9); // Kein Kreis in der Nähe → nichts. let far = json!({"cmd": "dimround", "kind": "radius", "pts": [[50.0, 50.0]]}); - assert!(ops(&root, &far, &ctx(), &mut IdGen::new("s")).unwrap().is_empty()); + assert!(ops(&root, &Project::default(), &far, &ctx(), &mut IdGen::new("s")).unwrap().is_empty()); } #[test] @@ -1509,7 +1510,7 @@ mod tests { #[test] fn polylinie_tangential_und_schluss() { let v = json!({"cmd": "polyline", "pts": [[0, 0], [2, 0], [2, 2]], "segs": [0, 1], "closed": true, "closing": 0}); - let o = ops(&Map::new(), &v, &ctx(), &mut IdGen::new("s")).unwrap(); + let o = ops(&Map::new(), &Project::default(), &v, &ctx(), &mut IdGen::new("s")).unwrap(); let g = &o[0].to_json()["items"][0]["geom"]; assert_eq!(g["bulge"].as_array().unwrap().len(), 3); assert!(g["bulge"][1].as_f64().unwrap().abs() > 0.1); @@ -1519,10 +1520,10 @@ mod tests { #[test] fn rechteck_gerundet_und_kreis_durch_drei_punkte() { let v = json!({"cmd": "rect", "method": "corner", "a": [0, 0], "b": [2, 1], "radius": 0.1}); - let o = ops(&Map::new(), &v, &ctx(), &mut IdGen::new("s")).unwrap(); + let o = ops(&Map::new(), &Project::default(), &v, &ctx(), &mut IdGen::new("s")).unwrap(); assert_eq!(o[0].to_json()["items"][0]["geom"]["pts"].as_array().unwrap().len(), 8); let v = json!({"cmd": "circle", "method": "threePoint", "pts": [[1, 0], [0, 1], [-1, 0]]}); - let o = ops(&Map::new(), &v, &ctx(), &mut IdGen::new("s")).unwrap(); + let o = ops(&Map::new(), &Project::default(), &v, &ctx(), &mut IdGen::new("s")).unwrap(); assert_eq!(o[0].to_json()["items"][0]["geom"]["r"], 1); } @@ -1533,7 +1534,7 @@ mod tests { assert_eq!(out[1], json!({"x": 2, "y": 0})); let root = json!({"drawings2d": [{"id": "d", "levelId": "L", "geom": {"shape": "dimension", "pts": [], "offset": 0}}]}); let v = json!({"cmd": "dimension", "pts": [[0, 0], [4, 0]], "side": [1, 1], "editId": "d"}); - let o = ops(root.as_object().unwrap(), &v, &ctx(), &mut IdGen::new("s")).unwrap(); + let o = ops(root.as_object().unwrap(), &Project::default(), &v, &ctx(), &mut IdGen::new("s")).unwrap(); assert_eq!(o[0].to_json()["entity"]["geom"]["offset"], 1); } } diff --git a/src-tauri/core/src/cmd_edit.rs b/src-tauri/core/src/cmd_edit.rs index a38dc770..9b6e7868 100644 --- a/src-tauri/core/src/cmd_edit.rs +++ b/src-tauri/core/src/cmd_edit.rs @@ -16,6 +16,7 @@ use crate::cmd_wall_edit as wall_edit; use crate::json_util::{arr, field, js_num, num_of, num_or, pt, truthy, with, with_all, xy}; use crate::jsmath::hypot2; use crate::jsnum; +use crate::model::{Project, Wall}; use crate::ops::{id_of, Op}; use kernel2d::{self as k, Vec2 as P}; use serde_json::{Map, Value}; @@ -184,7 +185,7 @@ fn tuples(pts: &[P]) -> Vec<(f64, f64)> { } /// Nächste Kurve der Ebene zum Punkt (innerhalb `HIT_TOL`). -fn pick_curve<'a>(root: &'a Map, level: &str, at: P, take: Take) -> Option<&'a Value> { +fn pick_curve<'a>(root: &'a Map, p: &Project, level: &str, at: P, take: Take) -> Option<&'a Value> { let mut best = None; let mut best_d = HIT_TOL; for d in drawings(root) { @@ -201,9 +202,9 @@ fn pick_curve<'a>(root: &'a Map, level: &str, at: P, take: Take) } } if take != Take::Corner { - if let Some((w, dd)) = wall_edit::pick_wall(root, level, at) { + if let Some((w, dd)) = wall_edit::pick_wall(p, level, at) { if dd < best_d { - best = Some(w); + best = arr(root.get("walls")).iter().find(|r| id_of(r) == Some(w.id.as_str())).or(best); } } } @@ -214,6 +215,15 @@ fn is_wall(v: &Value) -> bool { field(v, "type").and_then(Value::as_str) == Some("wall") } +/// Die typisierte Wand zu einem getroffenen Element (`None` = keine Wand). +fn wall_of<'a>(p: &'a Project, d: &Value) -> Option<&'a Wall> { + if is_wall(d) { + wall_edit::find_wall(p, id_of(d)?) + } else { + None + } +} + /// Kette → Zeichengeometrie (`chainToGeom`/`fromPolyForm`): zwei Punkte offen ohne Bogen = Linie. fn chain_geom(pts: Vec, closed: Value, bulge: Option>) -> Value { let b = bulge.as_deref().map(nums).unwrap_or_default(); @@ -302,11 +312,11 @@ pub fn trim_ops(root: &Map, id: &str, at: P, ids: &mut IdGen) -> } /// Vorschau des Trims am Punkt: die verbleibenden Ketten der getroffenen Kurve. -pub fn trim_preview(root: &Map, level: &str, at: P, face: bool, out: &mut Shapes) -> bool { - let Some(target) = pick_curve(root, level, at, Take::Curve) else { return false }; +pub fn trim_preview(root: &Map, p: &Project, level: &str, at: P, face: bool, out: &mut Shapes) -> bool { + let Some(target) = pick_curve(root, p, level, at, Take::Curve) else { return false }; if is_wall(target) { - if let Some(e) = wall_edit::trim(root, target, at, face) { - wall_edit::preview(root, &e, out); + if let Some(e) = wall_of(p, target).and_then(|w| wall_edit::trim(p, w, at, face)) { + wall_edit::preview(p, &e, out); } return true; } @@ -407,11 +417,11 @@ pub fn extend_ops(root: &Map, id: &str, at: P) -> Vec { } /// Vorschau der Verlängerung (Bögen tesselliert). -pub fn extend_preview(root: &Map, level: &str, at: P, face: bool, out: &mut Shapes) -> bool { - let Some(target) = pick_curve(root, level, at, Take::Open) else { return false }; +pub fn extend_preview(root: &Map, p: &Project, level: &str, at: P, face: bool, out: &mut Shapes) -> bool { + let Some(target) = pick_curve(root, p, level, at, Take::Open) else { return false }; if is_wall(target) { - if let Some(e) = wall_edit::extend(root, target, at, face) { - wall_edit::preview(root, &e, out); + if let Some(e) = wall_of(p, target).and_then(|w| wall_edit::extend(p, w, at, face)) { + wall_edit::preview(p, &e, out); } return true; } @@ -576,8 +586,8 @@ fn corner_preview(h: &Corner, fillet: bool, r: f64, out: &mut Shapes) { // ── Bruch ──────────────────────────────────────────────────────────────────── /// Offene, bogenfreie Kurve unter dem Punkt (die nächste Kurve muss es sein). -pub fn pick_breakable<'a>(root: &'a Map, level: &str, at: P) -> Option<&'a Value> { - let d = pick_curve(root, level, at, Take::Curve)?; +pub fn pick_breakable<'a>(root: &'a Map, p: &Project, level: &str, at: P) -> Option<&'a Value> { + let d = pick_curve(root, p, level, at, Take::Curve)?; if is_wall(d) { return Some(d); } @@ -602,10 +612,10 @@ pub fn break_ops(root: &Map, id: &str, p1: P, p2: P, ids: &mut Id ops } -fn break_preview(root: &Map, id: &str, p1: P, p2: P, out: &mut Shapes) { - if let Some(w) = wall_edit::find_wall(root, id) { +fn break_preview(root: &Map, p: &Project, id: &str, p1: P, p2: P, out: &mut Shapes) { + if let Some(w) = wall_edit::find_wall(p, id) { if let Some(e) = wall_edit::break_at(w, p1, p2) { - wall_edit::preview(root, &e, out); + wall_edit::preview(p, &e, out); } return; } @@ -893,13 +903,13 @@ fn s_arg<'a>(v: &'a Value, k: &str) -> &'a str { } /// Ops eines Editier-Befehls (`None` = kein Editier-Befehl). -pub fn ops(root: &Map, v: &Value) -> Option> { +pub fn ops(root: &Map, p: &Project, v: &Value) -> Option> { let cmd = s_arg(v, "cmd"); let mut ids = IdGen::new(s_arg(v, "stamp")); let list = |k: &str| -> Vec { v.get(k).and_then(|x| serde_json::from_value(x.clone()).ok()).unwrap_or_default() }; - if let Some(w) = wall_edit::find_wall(root, s_arg(v, "id")) { - if let Some(e) = wall_edit_of(root, w, v) { - return Some(e.map(|e| wall_edit::commit(root, &e, &mut ids)).unwrap_or_default()); + if let Some(w) = wall_edit::find_wall(p, s_arg(v, "id")) { + if let Some(e) = wall_edit_of(p, w, v) { + return Some(e.map(|e| wall_edit::commit(root, p, &e, &mut ids)).unwrap_or_default()); } } Some(match cmd { @@ -911,7 +921,7 @@ pub fn ops(root: &Map, v: &Value) -> Option> { "offset" => offset_ops(root, s_arg(v, "id"), n_arg(v, "d"), &mut ids), "join" => { let mut ops = join_ops(root, &list("ids"), &mut ids); - ops.extend(wall_edit::join_ops(root, &list("ids"))); + ops.extend(wall_edit::join_ops(root, p, &list("ids"))); ops } "splitAt" => break_ops(root, s_arg(v, "id"), p_arg(v, "pt"), p_arg(v, "pt"), &mut ids), @@ -924,23 +934,23 @@ pub fn ops(root: &Map, v: &Value) -> Option> { /// Wand-Änderung einer Anfrage an die Wand `w` (`None` = kein Wand-Befehl; `Some(None)` = Befehl ohne /// Ergebnis, z. B. keine Grenze getroffen). -fn wall_edit_of<'a>(root: &'a Map, w: &'a Value, v: &Value) -> Option>> { +fn wall_edit_of<'a>(p: &'a Project, w: &'a Wall, v: &Value) -> Option>> { let face = truthy(v.get("face")); Some(match s_arg(v, "cmd") { - "trim" => wall_edit::trim(root, w, p_arg(v, "pt"), face), - "extend" => wall_edit::extend(root, w, p_arg(v, "pt"), face), + "trim" => wall_edit::trim(p, w, p_arg(v, "pt"), face), + "extend" => wall_edit::extend(p, w, p_arg(v, "pt"), face), "break" => wall_edit::break_at(w, p_arg(v, "p1"), p_arg(v, "p2")), "splitAt" => wall_edit::break_at(w, p_arg(v, "pt"), p_arg(v, "pt")), - "splitInter" => wall_edit::split_at_intersections(root, w), + "splitInter" => wall_edit::split_at_intersections(p, w), "offset" => wall_edit::offset(w, n_arg(v, "d")), - "filletWalls" => wall_edit::find_wall(root, s_arg(v, "id2")).and_then(|w2| wall_edit::fillet(w, p_arg(v, "p1"), w2, p_arg(v, "p2"), n_arg(v, "r"))), + "filletWalls" => wall_edit::find_wall(p, s_arg(v, "id2")).and_then(|w2| wall_edit::fillet(w, p_arg(v, "p1"), w2, p_arg(v, "p2"), n_arg(v, "r"))), _ => return None, }) } /// Abfragen der Befehle zwischen den Schritten (Treffer, Vorschau): Antwort-JSON. Formen flach wie /// `doc_cmd_preview` (`shapes`), Treffer als `hit` (`null` = keiner). -pub fn query(root: &Map, v: &Value) -> Result { +pub fn query(root: &Map, p: &Project, v: &Value) -> Result { use serde_json::json; let q = s_arg(v, "q"); let at = p_arg(v, "pt"); @@ -949,9 +959,9 @@ pub fn query(root: &Map, v: &Value) -> Result { let shapes = |s: Shapes| Value::Array(s.buf.iter().map(|x| js_num(*x)).collect()); let hit_id = |d: Option<&Value>| d.and_then(id_of).map_or(Value::Null, |i| Value::String(i.into())); Ok(match q { - "pickCurve" => json!({ "hit": hit_id(pick_curve(root, level, at, Take::Curve)) }), - "pickOpen" => json!({ "hit": hit_id(pick_curve(root, level, at, Take::Open)) }), - "pickBreakable" => json!({ "hit": hit_id(pick_breakable(root, level, at)) }), + "pickCurve" => json!({ "hit": hit_id(pick_curve(root, p, level, at, Take::Curve)) }), + "pickOpen" => json!({ "hit": hit_id(pick_curve(root, p, level, at, Take::Open)) }), + "pickBreakable" => json!({ "hit": hit_id(pick_breakable(root, p, level, at)) }), "pickCorner" => { let fillet = s_arg(v, "kind") == "fillet"; match pick_corner(root, level, at) { @@ -973,43 +983,43 @@ pub fn query(root: &Map, v: &Value) -> Result { } "trim" | "extend" => { let face = truthy(v.get("face")); - let hit = if q == "trim" { trim_preview(root, level, at, face, &mut s) } else { extend_preview(root, level, at, face, &mut s) }; + let hit = if q == "trim" { trim_preview(root, p, level, at, face, &mut s) } else { extend_preview(root, p, level, at, face, &mut s) }; json!({ "hit": hit, "shapes": shapes(s) }) } "break" => { - break_preview(root, s_arg(v, "id"), p_arg(v, "p1"), at, &mut s); + break_preview(root, p, s_arg(v, "id"), p_arg(v, "p1"), at, &mut s); json!({ "shapes": shapes(s) }) } - "offset" if wall_edit::find_wall(root, s_arg(v, "id")).is_some() => { - let w = wall_edit::find_wall(root, s_arg(v, "id")).unwrap_or(&Value::Null); + "offset" if wall_edit::find_wall(p, s_arg(v, "id")).is_some() => { + let Some(w) = wall_edit::find_wall(p, s_arg(v, "id")) else { return Ok(Value::Null) }; let sign = wall_edit::side(w, at).unwrap_or(n_arg(v, "lastSign")); let dist = n_arg(v, "dist"); if let Some(e) = wall_edit::offset(w, sign * dist) { - wall_edit::preview(root, &e, &mut s); + wall_edit::preview(p, &e, &mut s); } json!({ "hit": true, "sign": sign, "shapes": shapes(s) }) } - "pickWall" => json!({ "hit": hit_id(wall_edit::pick_wall(root, level, at).map(|w| w.0)) }), + "pickWall" => json!({ "hit": json!(wall_edit::pick_wall(p, level, at).map(|w| w.0.id.as_str())) }), "filletWalls" => { - let e = match (wall_edit::find_wall(root, s_arg(v, "id")), wall_edit::pick_wall(root, level, at)) { + let e = match (wall_edit::find_wall(p, s_arg(v, "id")), wall_edit::pick_wall(p, level, at)) { (Some(w1), Some((w2, _))) => wall_edit::fillet(w1, p_arg(v, "p1"), w2, at, n_arg(v, "r")), _ => None, }; if let Some(e) = &e { - wall_edit::preview(root, e, &mut s); + wall_edit::preview(p, e, &mut s); } json!({ "hit": e.is_some(), "shapes": shapes(s) }) } "split" => { let inter = truthy(v.get("inter")); - let target = if inter { pick_curve(root, level, at, Take::Curve) } else { pick_breakable(root, level, at) }; + let target = if inter { pick_curve(root, p, level, at, Take::Curve) } else { pick_breakable(root, p, level, at) }; let mut hit = Value::Null; if let Some(t) = target { hit = hit_id(Some(t)); if is_wall(t) { - let e = if inter { wall_edit::split_at_intersections(root, t) } else { wall_edit::break_at(t, at, at) }; + let e = wall_of(p, t).and_then(|w| if inter { wall_edit::split_at_intersections(p, w) } else { wall_edit::break_at(w, at, at) }); if let Some(e) = e { - wall_edit::preview(root, &e, &mut s); + wall_edit::preview(p, &e, &mut s); } } else if !inter { // Teilstelle der Zeichnung: kleines Kreuz. @@ -1046,6 +1056,9 @@ mod tests { fn root(v: Value) -> Map { v.as_object().unwrap().clone() } + fn typed(r: &Map) -> crate::model::Project { + crate::document::Document::from_json(&Value::Object(r.clone()).to_string()).unwrap().project().unwrap().clone() + } fn line(id: &str, a: (f64, f64), b: (f64, f64)) -> Value { json!({"id": id, "type": "drawing2d", "levelId": "L", "categoryCode": "20", "geom": {"shape": "line", "a": {"x": a.0, "y": a.1}, "b": {"x": b.0, "y": b.1}}}) } @@ -1094,20 +1107,21 @@ mod tests { let w = |id: &str, a: (f64, f64), b: (f64, f64)| json!({"id": id, "type": "wall", "floorId": "L", "start": {"x": a.0, "y": a.1}, "end": {"x": b.0, "y": b.1}, "wallTypeId": "t", "height": 2.5}); let r = root(json!({"wallTypes": [{"id": "t", "layers": [{"thickness": 0.2}]}], "walls": [w("a", (0.0, 0.0), (10.0, 0.0)), w("b", (6.0, -3.0), (6.0, 3.0))], "drawings2d": [], "openings": []})); // Treffer: Klick in den Wandkörper trifft die Wand (auch für Bruch/Teilen). - assert_eq!(query(&r, &json!({"q": "pickCurve", "level": "L", "pt": [8.0, 0.05]})).unwrap()["hit"], "a"); - assert_eq!(query(&r, &json!({"q": "pickBreakable", "level": "L", "pt": [8.0, 0.05]})).unwrap()["hit"], "a"); - let pv = query(&r, &json!({"q": "trim", "level": "L", "pt": [8.0, 0.0]})).unwrap(); + let p = typed(&r); + assert_eq!(query(&r, &p, &json!({"q": "pickCurve", "level": "L", "pt": [8.0, 0.05]})).unwrap()["hit"], "a"); + assert_eq!(query(&r, &p, &json!({"q": "pickBreakable", "level": "L", "pt": [8.0, 0.05]})).unwrap()["hit"], "a"); + let pv = query(&r, &p, &json!({"q": "trim", "level": "L", "pt": [8.0, 0.0]})).unwrap(); assert_eq!(pv["hit"], true); assert!(!pv["shapes"].as_array().unwrap().is_empty()); - let o = super::ops(&r, &json!({"cmd": "trim", "id": "a", "pt": [8.0, 0.0], "stamp": "s"})).unwrap(); + let o = super::ops(&r, &p, &json!({"cmd": "trim", "id": "a", "pt": [8.0, 0.0], "stamp": "s"})).unwrap(); assert_eq!(o[0].to_json()["entity"]["end"], json!({"x": 6, "y": 0})); - let o = super::ops(&r, &json!({"cmd": "splitAt", "id": "a", "pt": [2.0, 0.0], "stamp": "s"})).unwrap(); + let o = super::ops(&r, &p, &json!({"cmd": "splitAt", "id": "a", "pt": [2.0, 0.0], "stamp": "s"})).unwrap(); assert_eq!(o.len(), 2); - let o = super::ops(&r, &json!({"cmd": "splitInter", "id": "a", "stamp": "s"})).unwrap(); + let o = super::ops(&r, &p, &json!({"cmd": "splitInter", "id": "a", "stamp": "s"})).unwrap(); assert_eq!(o[1].to_json()["items"][0]["start"], json!({"x": 6, "y": 0})); - let o = super::ops(&r, &json!({"cmd": "offset", "id": "a", "d": -1.0, "stamp": "s"})).unwrap(); + let o = super::ops(&r, &p, &json!({"cmd": "offset", "id": "a", "d": -1.0, "stamp": "s"})).unwrap(); assert_eq!(o[0].to_json()["items"][0]["start"], json!({"x": 0, "y": -1})); - let pv = query(&r, &json!({"q": "filletWalls", "level": "L", "id": "a", "p1": [2.0, 0.0], "pt": [6.0, 2.0], "r": 0.5})).unwrap(); + let pv = query(&r, &p, &json!({"q": "filletWalls", "level": "L", "id": "a", "p1": [2.0, 0.0], "pt": [6.0, 2.0], "r": 0.5})).unwrap(); assert_eq!(pv["hit"], true); } } diff --git a/src-tauri/core/src/cmd_wall_edit.rs b/src-tauri/core/src/cmd_wall_edit.rs index bd8119c9..cbb66f77 100644 --- a/src-tauri/core/src/cmd_wall_edit.rs +++ b/src-tauri/core/src/cmd_wall_edit.rs @@ -21,9 +21,9 @@ //! Geschosses, 2D-Linien/-Polylinien (mit Bögen)/-Rechtecke/-Kreise/-Bögen und Achsraster der Ebene. use crate::cmd_transform::{IdGen, Shapes}; -use crate::json_util::{arr, field, js_num, num_of, pt, truthy, with, with_all, xy}; +use crate::json_util::{arr, field, js_num, pt, with, with_all}; use crate::joins::Line; -use crate::model::{DimFeature, DimRef}; +use crate::model::{DimFeature, DimRef, Drawing2D, Drawing2DGeom, Project, Vec2, Wall, WallReferenceLine}; use crate::ops::{id_of, Op}; use crate::wall_arc::{circle_circle, circle_line, WallArc}; use kernel2d::Vec2 as P; @@ -39,9 +39,8 @@ const EPS_GEO: f64 = 1e-5; /// Pick-Toleranz neben dem Wandkörper (Meter, wie `cmd_edit::HIT_TOL`). const HIT_TOL: f64 = 0.25; -fn p_of(v: Option<&Value>) -> P { - let (x, y) = xy(v.unwrap_or(&Value::Null)); - P::new(x, y) +fn p_of(v: &Vec2) -> P { + P::new(v.x, v.y) } fn ptv(p: P) -> Value { pt(p.x, p.y) @@ -55,20 +54,21 @@ fn dist(a: P, b: P) -> f64 { fn cross(a: P, b: P) -> f64 { a.x * b.y - a.y * b.x } -fn str_of<'a>(v: &'a Value, k: &str) -> Option<&'a str> { - field(v, k).and_then(Value::as_str) +pub fn walls(p: &Project) -> &[Wall] { + &p.walls } -pub fn walls(root: &Map) -> &[Value] { - arr(root.get("walls")) +pub fn find_wall<'a>(p: &'a Project, id: &str) -> Option<&'a Wall> { + p.walls.iter().find(|w| w.id == id) } -pub fn find_wall<'a>(root: &'a Map, id: &str) -> Option<&'a Value> { - walls(root).iter().find(|w| id_of(w) == Some(id)) +/// Das rohe Element (verlustfreier Baum) zu einer id: Ops schreiben es mit geänderten Feldern zurück. +fn raw<'a>(root: &'a Map, collection: &str, id: &str) -> Option<&'a Value> { + arr(root.get(collection)).iter().find(|e| id_of(e) == Some(id)) } -fn editable(w: &Value) -> bool { - !truthy(field(w, "locked")) +fn editable(w: &Wall) -> bool { + !w.locked.unwrap_or(false) } // ── Achse ─────────────────────────────────────────────────────────────────── @@ -100,8 +100,8 @@ impl Axis { Some(Axis { a, b, arc, len, u, sign: bulge.unwrap_or(0.0).signum() }) } - pub fn of(w: &Value) -> Option { - Axis::new(p_of(field(w, "start")), p_of(field(w, "end")), field(w, "bulge").and_then(Value::as_f64)) + pub fn of(w: &Wall) -> Option { + Axis::new(p_of(&w.start), p_of(&w.end), w.bulge) } /// Weltpunkt bei (s, n), `n` links der Laufrichtung. @@ -199,17 +199,13 @@ fn on_arc(c: P, a0: f64, sweep: f64, x: P) -> bool { } /// Linien der Wand quer zur Achse: (erste Fläche, zweite Fläche) wie `dim_assoc::wall_geo`. -pub fn faces(root: &Map, w: &Value) -> (f64, f64) { - let layers: Vec = str_of(w, "wallTypeId") - .and_then(|id| arr(root.get("wallTypes")).iter().find(|t| id_of(t) == Some(id))) - .map(|t| arr(field(t, "layers")).iter().map(|l| field(l, "thickness").and_then(Value::as_f64).filter(|x| x.is_finite()).unwrap_or(0.0)).collect()) - .unwrap_or_default(); - let total: f64 = layers.iter().sum(); +pub fn faces(p: &Project, w: &Wall) -> (f64, f64) { + let total: f64 = p.wall_types.iter().find(|t| t.id == w.wall_type_id).map_or(0.0, |t| t.layers.iter().map(|l| Some(l.thickness).filter(|x| x.is_finite()).unwrap_or(0.0)).sum()); let half = total / 2.0; - let r = match (field(w, "referenceOffset").and_then(Value::as_f64), str_of(w, "referenceLine")) { + let r = match (w.reference_offset, w.reference_line) { (Some(v), _) if v.is_finite() => crate::joins::Reference::Offset(v), - (_, Some("left")) => crate::joins::Reference::Left, - (_, Some("right")) => crate::joins::Reference::Right, + (_, Some(WallReferenceLine::Left)) => crate::joins::Reference::Left, + (_, Some(WallReferenceLine::Right)) => crate::joins::Reference::Right, _ => crate::joins::Reference::Center, }; let off = crate::joins::reference_offset(r, total); @@ -238,50 +234,45 @@ fn wall_bound(ax: &Axis, n: f64, ext: f64) -> Bound { } /// Grenzen einer 2D-Zeichnung (Linie, Polylinie mit Bögen, Rechteck, Kreis, Bogen, Achsraster). -fn drawing_bounds(d: &Value, level: &str, out: &mut Vec) { - let g = field(d, "geom").unwrap_or(&Value::Null); - match str_of(g, "shape").unwrap_or("") { - "line" => out.push(Bound::Seg(p_of(field(g, "a")), p_of(field(g, "b")))), - "rect" => { - let (a, b) = (p_of(field(g, "min")), p_of(field(g, "max"))); +fn drawing_bounds(d: &Drawing2D, out: &mut Vec) { + match &d.geom { + Drawing2DGeom::Line { a, b } => out.push(Bound::Seg(p_of(a), p_of(b))), + Drawing2DGeom::Rect { min, max } => { + let (a, b) = (p_of(min), p_of(max)); let c = [a, P::new(b.x, a.y), b, P::new(a.x, b.y)]; for i in 0..4 { out.push(Bound::Seg(c[i], c[(i + 1) % 4])); } } - "polyline" => { - let pts: Vec

= arr(field(g, "pts")).iter().map(|v| p_of(Some(v))).collect(); + Drawing2DGeom::Polyline { pts, closed, bulge } => { + let pts: Vec

= pts.iter().map(p_of).collect(); let n = pts.len(); - let segs = if truthy(field(g, "closed")) && n > 2 { n } else { n.saturating_sub(1) }; - let bulge = arr(field(g, "bulge")); + let segs = if *closed && n > 2 { n } else { n.saturating_sub(1) }; for i in 0..segs { let (a, b) = (pts[i], pts[(i + 1) % n]); - let bv = num_of(bulge.get(i)); + let bv = bulge.as_ref().and_then(|b| b.get(i)).copied().unwrap_or(f64::NAN); match kernel2d::bulge_arc(a, b, bv).filter(|_| bv.abs() > 1e-9) { Some(arc) => out.push(Bound::Arc { c: arc.center, r: arc.r, a0: arc.a0, sweep: arc.sweep }), None => out.push(Bound::Seg(a, b)), } } } - "circle" => out.push(Bound::Arc { c: p_of(field(g, "center")), r: num_of(field(g, "r")), a0: 0.0, sweep: TAU }), - "arc" => { - let (a0, a1) = (num_of(field(g, "a0")), num_of(field(g, "a1"))); + Drawing2DGeom::Circle { center, r } => out.push(Bound::Arc { c: p_of(center), r: *r, a0: 0.0, sweep: TAU }), + Drawing2DGeom::Arc { center, r, a0, a1 } => { let mut sweep = (a1 - a0).rem_euclid(TAU); if sweep < 1e-12 { sweep = TAU; } - out.push(Bound::Arc { c: p_of(field(g, "center")), r: num_of(field(g, "r")), a0, sweep }); + out.push(Bound::Arc { c: p_of(center), r: *r, a0: *a0, sweep }); } - "grid" => { - let Ok(geom) = serde_json::from_value::(g.clone()) else { return }; - let Some(spec) = crate::grid::Spec::of(&geom) else { return }; + g @ Drawing2DGeom::Grid { .. } => { + let Some(spec) = crate::grid::Spec::of(g) else { return }; for ax in spec.axes() { match ax.shape { crate::grid::Shape::Line { a, b } => out.push(Bound::Seg(P::new(a.0, a.1), P::new(b.0, b.1))), crate::grid::Shape::Arc { c, r, a0, a1 } => out.push(Bound::Arc { c: P::new(c.0, c.1), r, a0, sweep: a1 - a0 }), } } - let _ = level; } _ => {} } @@ -289,16 +280,15 @@ fn drawing_bounds(d: &Value, level: &str, out: &mut Vec) { /// Alle Grenzen für die Wand `target`: übrige Wände des Geschosses (Achse oder, `face`, beide Flächen, /// je um die halbe Dicke über die Enden verlängert, damit Ecken greifen), 2D-Zeichnungen und Achsraster. -pub fn bounds(root: &Map, target: &Value, face: bool) -> Vec { - let level = str_of(target, "floorId").unwrap_or(""); - let tid = id_of(target); +pub fn bounds(p: &Project, target: &Wall, face: bool) -> Vec { + let level = target.floor_id.as_str(); let mut out = Vec::new(); - for w in walls(root) { - if id_of(w) == tid || str_of(w, "floorId") != Some(level) { + for w in walls(p) { + if w.id == target.id || w.floor_id != level { continue; } let Some(ax) = Axis::of(w) else { continue }; - let (lo, hi) = faces(root, w); + let (lo, hi) = faces(p, w); let ext = (hi - lo) / 2.0; if face && hi - lo > 1e-9 { out.push(wall_bound(&ax, lo, ext)); @@ -307,12 +297,9 @@ pub fn bounds(root: &Map, target: &Value, face: bool) -> Vec(d.clone()).is_ok_and(|dd| crate::grid::visible_on(&dd, level))); - if on { - drawing_bounds(d, level, &mut out); + for d in &p.drawings2d { + if d.level_id == level || (matches!(d.geom, Drawing2DGeom::Grid { .. }) && crate::grid::visible_on(d, level)) { + drawing_bounds(d, &mut out); } } out @@ -329,26 +316,26 @@ fn cuts(ax: &Axis, bs: &[Bound]) -> Vec { // ── Treffer ───────────────────────────────────────────────────────────────── /// Abstand des Punkts zum Wandkörper (0 innen), `None` ausserhalb der Länge. -pub fn wall_distance(root: &Map, w: &Value, at: P) -> Option { +pub fn wall_distance(p: &Project, w: &Wall, at: P) -> Option { let ax = Axis::of(w)?; let (s, n) = ax.local(at); if !(s >= -HIT_TOL && s <= ax.len + HIT_TOL) { return None; } - let (lo, hi) = faces(root, w); + let (lo, hi) = faces(p, w); let d = if n < lo { lo - n } else if n > hi { n - hi } else { 0.0 }; let along = if s < 0.0 { -s } else if s > ax.len { s - ax.len } else { 0.0 }; Some(d.hypot(along)) } /// Nächste bearbeitbare Wand des Geschosses unter dem Punkt (Abstand < `HIT_TOL`), mit Abstand. -pub fn pick_wall<'a>(root: &'a Map, level: &str, at: P) -> Option<(&'a Value, f64)> { - let mut best: Option<(&Value, f64)> = None; - for w in walls(root) { - if str_of(w, "floorId") != Some(level) || !editable(w) { +pub fn pick_wall<'a>(p: &'a Project, level: &str, at: P) -> Option<(&'a Wall, f64)> { + let mut best: Option<(&Wall, f64)> = None; + for w in walls(p) { + if w.floor_id != level || !editable(w) { continue; } - if let Some(d) = wall_distance(root, w, at) { + if let Some(d) = wall_distance(p, w, at) { if d < HIT_TOL && best.map_or(true, |b| d < b.1) { best = Some((w, d)); } @@ -361,7 +348,7 @@ pub fn pick_wall<'a>(root: &'a Map, level: &str, at: P) -> Option /// Teilstücke einer Wand: `(id, s0, s1)` im Parameter der alten Achse (`None` = alte id). pub struct Plan<'a> { - pub src: &'a Value, + pub src: &'a Wall, pub ax: Axis, pub pieces: Vec<(f64, f64)>, /// Wandende-Bezüge folgen dem ersten/letzten Stück (Trim, Extend, Verrunden). @@ -370,7 +357,7 @@ pub struct Plan<'a> { /// Neue Wand als Kopie von `src` (Fillet-Bogen, Offset). pub struct NewWall<'a> { - pub src: &'a Value, + pub src: &'a Wall, pub a: P, pub b: P, pub bulge: Option, @@ -429,26 +416,25 @@ impl Remap { } /// Öffnungen der umgebauten Wände umhängen/umrechnen/löschen. -fn opening_ops(root: &Map, maps: &[Remap]) -> Vec { +fn opening_ops(root: &Map, p: &Project, maps: &[Remap]) -> Vec { let mut ops = Vec::new(); let mut gone = Vec::new(); - for o in arr(root.get("openings")) { - let Some(m) = str_of(o, "hostWallId").and_then(|h| maps.iter().find(|m| m.old == h)) else { continue }; - let (pos, width) = (num_of(field(o, "position")), num_of(field(o, "width"))); + for o in p.openings.iter().flatten() { + let Some(m) = maps.iter().find(|m| m.old == o.host_wall_id) else { continue }; + let (pos, width) = (o.position, o.width); let c = pos + width / 2.0; let t = m.containing(c); let Some(t) = t.filter(|t| width <= t.s1 - t.s0 + EPS_S) else { - if let Some(id) = id_of(o) { - gone.push(id.to_string()); - } + gone.push(o.id.clone()); continue; }; let np = (pos - t.s0).min(t.s1 - t.s0 - width).max(0.0); - let same_host = str_of(o, "hostWallId") == Some(t.id.as_str()); + let same_host = o.host_wall_id == t.id; if same_host && (np - pos).abs() < 1e-12 { continue; } - ops.push(Op::Replace { collection: "openings".into(), entity: with_all(o, vec![("hostWallId", Value::String(t.id.clone())), ("position", js_num(np))]) }); + let Some(ro) = raw(root, "openings", &o.id) else { continue }; + ops.push(Op::Replace { collection: "openings".into(), entity: with_all(ro, vec![("hostWallId", Value::String(t.id.clone())), ("position", js_num(np))]) }); } if !gone.is_empty() { ops.push(Op::Remove { collection: "openings".into(), ids: gone }); @@ -457,13 +443,12 @@ fn opening_ops(root: &Map, maps: &[Remap]) -> Vec { } /// Bezüge der Bemassung auf umgebaute Wände umschreiben ([38]). -fn dim_ops(root: &Map, maps: &[Remap]) -> Vec { +fn dim_ops(root: &Map, p: &Project, maps: &[Remap]) -> Vec { let mut ops = Vec::new(); - for d in arr(root.get("drawings2d")) { - let Some(g) = field(d, "geom").filter(|g| str_of(g, "shape") == Some("dimension")) else { continue }; - let Some(rv) = field(g, "refs") else { continue }; - let Ok(mut refs) = serde_json::from_value::>>(rv.clone()) else { continue }; - let pts: Vec

= arr(field(g, "pts")).iter().map(|v| p_of(Some(v))).collect(); + for d in &p.drawings2d { + let Drawing2DGeom::Dimension { pts, refs: Some(refs), .. } = &d.geom else { continue }; + let mut refs: Vec> = refs.clone(); + let pts: Vec

= pts.iter().map(p_of).collect(); let mut changed = false; for (i, r) in refs.iter_mut().enumerate() { let Some(r) = r.as_mut() else { continue }; @@ -511,15 +496,16 @@ fn dim_ops(root: &Map, maps: &[Remap]) -> Vec { } } if changed { - let ng = with(g, "refs", serde_json::to_value(&refs).unwrap_or(Value::Null)); - ops.push(Op::Replace { collection: "drawings2d".into(), entity: with(d, "geom", ng) }); + let Some(rd) = raw(root, "drawings2d", &d.id) else { continue }; + let ng = with(field(rd, "geom").unwrap_or(&Value::Null), "refs", serde_json::to_value(&refs).unwrap_or(Value::Null)); + ops.push(Op::Replace { collection: "drawings2d".into(), entity: with(rd, "geom", ng) }); } } ops } /// Ops einer Änderung (eine Undo-Stufe). -pub fn commit(root: &Map, e: &Edit, ids: &mut IdGen) -> Vec { +pub fn commit(root: &Map, pr: &Project, e: &Edit, ids: &mut IdGen) -> Vec { if !e.changes() { return vec![]; } @@ -527,17 +513,18 @@ pub fn commit(root: &Map, e: &Edit, ids: &mut IdGen) -> Vec { let mut added = Vec::new(); let mut maps = Vec::new(); for p in &e.plans { - let Some(old) = id_of(p.src) else { continue }; + let old = p.src.id.as_str(); + let Some(src) = raw(root, "walls", old) else { continue }; let mut targets = Vec::new(); for (k, (s0, s1)) in p.pieces.iter().enumerate() { let Some((a, b, bulge)) = p.ax.piece(*s0, *s1) else { continue }; let id = if k == 0 { old.to_string() } else { ids.next("wall") }; let mut f = geom_fields(a, b, bulge); if k == 0 { - ops.push(Op::Replace { collection: "walls".into(), entity: with_all(p.src, f) }); + ops.push(Op::Replace { collection: "walls".into(), entity: with_all(src, f) }); } else { f.push(("id", Value::String(id.clone()))); - added.push(with_all(p.src, f)); + added.push(with_all(src, f)); } targets.push(Target { id, s0: *s0, s1: *s1 }); } @@ -547,9 +534,10 @@ pub fn commit(root: &Map, e: &Edit, ids: &mut IdGen) -> Vec { maps.push(Remap { old: old.to_string(), len: p.ax.len, ax: p.ax.clone(), targets, follow_ends: p.follow_ends }); } for n in &e.extra { + let Some(src) = raw(root, "walls", &n.src.id) else { continue }; let mut f = geom_fields(n.a, n.b, n.bulge); f.push(("id", Value::String(ids.next("wall")))); - let w = with_all(n.src, f); + let w = with_all(src, f); // Gerade Kopie einer Bogenwand: kein Bulge. let w = if n.bulge.is_none() { without(&w, "bulge") } else { w }; added.push(w); @@ -557,8 +545,8 @@ pub fn commit(root: &Map, e: &Edit, ids: &mut IdGen) -> Vec { if !added.is_empty() { ops.push(Op::Add { collection: "walls".into(), items: added, at: None }); } - ops.extend(opening_ops(root, &maps)); - ops.extend(dim_ops(root, &maps)); + ops.extend(opening_ops(root, pr, &maps)); + ops.extend(dim_ops(root, pr, &maps)); ops } @@ -569,9 +557,9 @@ fn without(v: &Value, k: &str) -> Value { } /// Vorschau: Umriss jedes Ergebnis-Stücks. -pub fn preview(root: &Map, e: &Edit, out: &mut Shapes) { +pub fn preview(pr: &Project, e: &Edit, out: &mut Shapes) { for p in &e.plans { - let (lo, hi) = faces(root, p.src); + let (lo, hi) = faces(pr, p.src); for (s0, s1) in &p.pieces { if p.ax.piece(*s0, *s1).is_some() { out.poly(&p.ax.outline(*s0, *s1, lo, hi)); @@ -579,7 +567,7 @@ pub fn preview(root: &Map, e: &Edit, out: &mut Shapes) { } } for n in &e.extra { - let (lo, hi) = faces(root, n.src); + let (lo, hi) = faces(pr, n.src); if let Some(ax) = Axis::new(n.a, n.b, n.bulge) { out.poly(&ax.outline(0.0, ax.len, lo, hi)); } @@ -588,13 +576,13 @@ pub fn preview(root: &Map, e: &Edit, out: &mut Shapes) { // ── Befehle ───────────────────────────────────────────────────────────────── -fn plan(w: &Value, follow_ends: bool) -> Option> { +fn plan(w: &Wall, follow_ends: bool) -> Option> { editable(w).then_some(())?; Some(Plan { src: w, ax: Axis::of(w)?, pieces: vec![], follow_ends }) } /// Trim: das angeklickte Stück zwischen den nächsten Schnitten (bzw. bis zum Ende) entfällt. -pub fn trim<'a>(root: &'a Map, w: &'a Value, at: P, face: bool) -> Option> { +pub fn trim<'a>(root: &'a Project, w: &'a Wall, at: P, face: bool) -> Option> { let mut p = plan(w, true)?; let s = p.ax.local(at).0; let c: Vec = cuts(&p.ax, &bounds(root, w, face)).into_iter().filter(|x| *x > EPS_S && *x < p.ax.len - EPS_S).collect(); @@ -614,7 +602,7 @@ pub fn trim<'a>(root: &'a Map, w: &'a Value, at: P, face: bool) - } /// Extend: das dem Punkt nähere Ende bis zur nächsten Grenze dahinter verlängern. -pub fn extend<'a>(root: &'a Map, w: &'a Value, at: P, face: bool) -> Option> { +pub fn extend<'a>(root: &'a Project, w: &'a Wall, at: P, face: bool) -> Option> { let mut p = plan(w, true)?; let start = dist(at, p.ax.a) <= dist(at, p.ax.b); let c = cuts(&p.ax, &bounds(root, w, face)); @@ -626,7 +614,7 @@ pub fn extend<'a>(root: &'a Map, w: &'a Value, at: P, face: bool) } /// Bruch zwischen zwei Punkten (gleicher Punkt = Teilen an dieser Stelle). -pub fn break_at<'a>(w: &'a Value, p1: P, p2: P) -> Option> { +pub fn break_at<'a>(w: &'a Wall, p1: P, p2: P) -> Option> { let mut p = plan(w, false)?; let len = p.ax.len; let (s1, s2) = (p.ax.local(p1).0.clamp(0.0, len), p.ax.local(p2).0.clamp(0.0, len)); @@ -644,7 +632,7 @@ pub fn break_at<'a>(w: &'a Value, p1: P, p2: P) -> Option> { } /// Teilen an allen Schnittpunkten mit den Grenzen (Achsen der übrigen Wände, 2D, Achsraster). -pub fn split_at_intersections<'a>(root: &'a Map, w: &'a Value) -> Option> { +pub fn split_at_intersections<'a>(root: &'a Project, w: &'a Wall) -> Option> { let mut p = plan(w, false)?; let len = p.ax.len; let mut last = 0.0; @@ -662,7 +650,7 @@ pub fn split_at_intersections<'a>(root: &'a Map, w: &'a Value) -> } /// Offset: parallele (bei Bogenwänden konzentrische) Kopie im Achsabstand `d` (links positiv). -pub fn offset(w: &Value, d: f64) -> Option> { +pub fn offset(w: &Wall, d: f64) -> Option> { let ax = Axis::of(w)?; if !d.is_finite() || d.abs() < 1e-9 { return None; @@ -673,12 +661,12 @@ pub fn offset(w: &Value, d: f64) -> Option> { } } let (a, b) = (ax.point(0.0, d), ax.point(ax.len, d)); - let bulge = ax.arc.map(|_| num_of(field(w, "bulge"))); + let bulge = ax.arc.map(|_| w.bulge.unwrap_or(f64::NAN)); Some(Edit { plans: vec![], extra: vec![NewWall { src: w, a, b, bulge }] }) } /// Seite des Punkts zur Wand (+1 links, −1 rechts). -pub fn side(w: &Value, at: P) -> Option { +pub fn side(w: &Wall, at: P) -> Option { let (_, n) = Axis::of(w)?.local(at); Some(if n >= 0.0 { 1.0 } else { -1.0 }) } @@ -702,8 +690,8 @@ fn keep(ax: &Axis, s_x: f64, s_c: f64) -> Option<(f64, f64)> { /// Verrunden zweier Wände: beide bis zum Achsschnittpunkt (nächst den Klicks) stutzen bzw. verlängern /// (L-Ecke); mit Radius `r > 0` (nur gerade Wände) enden sie an den Tangentenpunkten und eine /// Bogenwand (Kopie der ersten Wand) schliesst tangential an. -pub fn fillet<'a>(w1: &'a Value, p1: P, w2: &'a Value, p2: P, r: f64) -> Option> { - if id_of(w1) == id_of(w2) { +pub fn fillet<'a>(w1: &'a Wall, p1: P, w2: &'a Wall, p2: P, r: f64) -> Option> { + if w1.id == w2.id { return None; } let (mut a, mut b) = (plan(w1, true)?, plan(w2, true)?); @@ -748,16 +736,16 @@ pub fn fillet<'a>(w1: &'a Value, p1: P, w2: &'a Value, p2: P, r: f64) -> Option< /// Verketten: gewählte Wände desselben Geschosses und Wandtyps, die mit der ersten kollinear (gleiche /// Laufrichtung) bzw. auf demselben Kreis (gleicher Drehsinn) liegen, werden eine Wand über die /// Gesamtspanne (Lücken werden geschlossen). Die erste behält id und Attribute. -pub fn join_ops(root: &Map, ids_sel: &[String]) -> Vec { - let sel: Vec<&Value> = walls(root).iter().filter(|w| editable(w) && id_of(w).is_some_and(|i| ids_sel.iter().any(|x| x == i))).collect(); +pub fn join_ops(root: &Map, pr: &Project, ids_sel: &[String]) -> Vec { + let sel: Vec<&Wall> = walls(pr).iter().filter(|w| editable(w) && ids_sel.iter().any(|x| *x == w.id)).collect(); let Some((first, rest)) = sel.split_first() else { return vec![] }; let Some(ax) = Axis::of(first) else { return vec![] }; - let same = |w: &Value, k: &str| field(w, k) == field(first, k); + let Some(first_raw) = raw(root, "walls", &first.id) else { return vec![] }; // Lage jeder Partnerwand auf der ersten Achse: Versatz ihres Starts. - let mut members: Vec<(&Value, Axis, f64)> = Vec::new(); + let mut members: Vec<(&Wall, Axis, f64)> = Vec::new(); for w in rest { let Some(bx) = Axis::of(w) else { continue }; - if !same(w, "floorId") || !same(w, "wallTypeId") { + if w.floor_id != first.floor_id || w.wall_type_id != first.wall_type_id { continue; } let ok = match (&ax.arc, &bx.arc) { @@ -779,15 +767,15 @@ pub fn join_ops(root: &Map, ids_sel: &[String]) -> Vec { let lo = members.iter().map(|m| m.2).fold(0.0_f64, f64::min); let hi = members.iter().map(|m| m.2 + m.1.len).fold(ax.len, f64::max); let Some((a, b, bulge)) = ax.piece(lo, hi) else { return vec![] }; - let new_id = id_of(first).unwrap_or("").to_string(); - let mut ops = vec![Op::Replace { collection: "walls".into(), entity: with_all(first, geom_fields(a, b, bulge)) }]; - ops.push(Op::Remove { collection: "walls".into(), ids: members.iter().filter_map(|m| id_of(m.0)).map(str::to_owned).collect() }); + let new_id = first.id.clone(); + let mut ops = vec![Op::Replace { collection: "walls".into(), entity: with_all(first_raw, geom_fields(a, b, bulge)) }]; + ops.push(Op::Remove { collection: "walls".into(), ids: members.iter().map(|m| m.0.id.clone()).collect() }); let mut maps = vec![Remap { old: new_id.clone(), len: ax.len, ax: ax.clone(), targets: vec![Target { id: new_id.clone(), s0: lo, s1: hi }], follow_ends: false }]; for (w, bx, off) in &members { - maps.push(Remap { old: id_of(w).unwrap_or("").to_string(), len: bx.len, ax: bx.clone(), targets: vec![Target { id: new_id.clone(), s0: lo - off, s1: hi - off }], follow_ends: false }); + maps.push(Remap { old: w.id.clone(), len: bx.len, ax: bx.clone(), targets: vec![Target { id: new_id.clone(), s0: lo - off, s1: hi - off }], follow_ends: false }); } - ops.extend(opening_ops(root, &maps)); - ops.extend(dim_ops(root, &maps)); + ops.extend(opening_ops(root, pr, &maps)); + ops.extend(dim_ops(root, pr, &maps)); ops } @@ -829,7 +817,10 @@ mod tests { d.root().clone() } fn w_of<'a>(r: &'a Map, id: &str) -> &'a Value { - find_wall(r, id).unwrap() + raw(r, "walls", id).unwrap() + } + fn typed(r: &Map) -> Project { + Document::from_json(&Value::Object(r.clone()).to_string()).unwrap().project().unwrap().clone() } fn xy_of(v: &Value) -> (f64, f64) { (v["x"].as_f64().unwrap(), v["y"].as_f64().unwrap()) @@ -837,8 +828,8 @@ mod tests { fn close(a: (f64, f64), b: (f64, f64)) -> bool { (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6 } - fn commit_edit(r: &Map, e: Option) -> Map { - let ops = commit(r, &e.expect("Änderung"), &mut IdGen::new("s")); + fn commit_edit(r: &Map, p: &Project, e: Option) -> Map { + let ops = commit(r, p, &e.expect("Änderung"), &mut IdGen::new("s")); assert!(!ops.is_empty()); apply(r, ops) } @@ -856,8 +847,9 @@ mod tests { #[test] fn trim_gerade_wand_an_querwand() { let r = t_case(); - let e = trim(&r, w_of(&r, "a"), P::new(8.0, 0.0), false); - let n = commit_edit(&r, e); + let pr = typed(&r); + let e = trim(&pr, find_wall(&pr, "a").unwrap(), P::new(8.0, 0.0), false); + let n = commit_edit(&r, &pr, e); let a = w_of(&n, "a"); assert!(close(xy_of(&a["end"]), (6.0, 0.0))); // o2 lag im weggeschnittenen Teil → weg; o1 bleibt. @@ -874,8 +866,9 @@ mod tests { fn trim_mittelstueck_teilt_und_haengt_oeffnungen_um() { let mut r = t_case(); r.get_mut("walls").unwrap().as_array_mut().unwrap().push(wall("c", (3.0, -3.0), (3.0, 3.0), None)); - let e = trim(&r, w_of(&r, "a"), P::new(4.5, 0.0), false); - let n = commit_edit(&r, e); + let pr = typed(&r); + let e = trim(&pr, find_wall(&pr, "a").unwrap(), P::new(4.5, 0.0), false); + let n = commit_edit(&r, &pr, e); assert!(close(xy_of(&w_of(&n, "a")["end"]), (3.0, 0.0))); let new = arr(n.get("walls")).iter().find(|w| w["id"] == "wall-s-1").unwrap(); assert!(close(xy_of(&new["start"]), (6.0, 0.0))); @@ -892,13 +885,15 @@ mod tests { #[test] fn extend_bis_zur_achse_und_flaeche() { let r = project(vec![wall("a", (0.0, 0.0), (4.0, 0.0), None), wall("b", (6.0, -3.0), (6.0, 3.0), None)], vec![], vec![]); - let n = commit_edit(&r, extend(&r, w_of(&r, "a"), P::new(3.9, 0.0), false)); + let pr = typed(&r); + let n = commit_edit(&r, &pr, extend(&pr, find_wall(&pr, "a").unwrap(), P::new(3.9, 0.0), false)); assert!(close(xy_of(&w_of(&n, "a")["end"]), (6.0, 0.0))); - let n = commit_edit(&r, extend(&r, w_of(&r, "a"), P::new(3.9, 0.0), true)); + let n = commit_edit(&r, &pr, extend(&pr, find_wall(&pr, "a").unwrap(), P::new(3.9, 0.0), true)); assert!(close(xy_of(&w_of(&n, "a")["end"]), (5.9, 0.0))); // Start verlängern: Öffnungen behalten ihre Weltlage. let r = project(vec![wall("a", (2.0, 0.0), (8.0, 0.0), None), wall("b", (0.0, -3.0), (0.0, 3.0), None)], vec![opening("o", "a", 1.0, 1.0)], vec![]); - let n = commit_edit(&r, extend(&r, w_of(&r, "a"), P::new(2.1, 0.0), false)); + let pr = typed(&r); + let n = commit_edit(&r, &pr, extend(&pr, find_wall(&pr, "a").unwrap(), P::new(2.1, 0.0), false)); assert!(close(xy_of(&w_of(&n, "a")["start"]), (0.0, 0.0))); assert!((arr(n.get("openings"))[0]["position"].as_f64().unwrap() - 3.0).abs() < 1e-9); } @@ -908,13 +903,14 @@ mod tests { // Halbkreis (−5,0)→(5,0) um (0,0), Scheitel unten oder oben je nach Bulge; Gerade x = 0 schneidet. let arc = wall("a", (-5.0, 0.0), (5.0, 0.0), Some(1.0)); let r = project(vec![arc, wall("b", (0.0, -8.0), (0.0, 8.0), None)], vec![opening("o", "a", 6.0, 1.0)], vec![]); - let ax = Axis::of(w_of(&r, "a")).unwrap(); + let pr = typed(&r); + let ax = Axis::of(find_wall(&typed(&r), "a").unwrap()).unwrap(); let len = ax.len; assert!((len - 5.0 * PI).abs() < 1e-9); let mid = ax.point(len / 2.0, 0.0); assert!(mid.x.abs() < 1e-9); // Split an den Schnittpunkten: zwei Viertelbögen, die Öffnung (Mitte 6.5 < len/2 ≈ 7.85) bleibt auf dem ersten. - let n = commit_edit(&r, split_at_intersections(&r, w_of(&r, "a"))); + let n = commit_edit(&r, &pr, split_at_intersections(&pr, find_wall(&pr, "a").unwrap())); let a = w_of(&n, "a"); assert!(close(xy_of(&a["end"]), (mid.x, mid.y))); assert!((a["bulge"].as_f64().unwrap() - (PI / 8.0).tan()).abs() < 1e-9); @@ -923,14 +919,15 @@ mod tests { assert_eq!(arr(n.get("openings"))[0]["hostWallId"], "a"); // Trim des zweiten Viertels: die Öffnung mit Mitte 6.5 < 7.85 bleibt. let p = ax.point(len * 0.75, 0.0); - let n = commit_edit(&r, trim(&r, w_of(&r, "a"), p, false)); + let n = commit_edit(&r, &pr, trim(&pr, find_wall(&pr, "a").unwrap(), p, false)); let a = w_of(&n, "a"); assert!(close(xy_of(&a["end"]), (mid.x, mid.y))); assert_eq!(arr(n.get("openings")).len(), 1); // Extend: Viertelbogen auf demselben Kreis bis zur Geraden x = 4 (Treffer (4, 3)). let q = wall("q", (-5.0, 0.0), (mid.x, mid.y), Some((PI / 8.0).tan())); let r = project(vec![q, wall("g", (4.0, -8.0), (4.0, 8.0), None)], vec![], vec![]); - let n = commit_edit(&r, extend(&r, w_of(&r, "q"), P::new(mid.x, mid.y), false)); + let pr = typed(&r); + let n = commit_edit(&r, &pr, extend(&pr, find_wall(&pr, "q").unwrap(), P::new(mid.x, mid.y), false)); let q = w_of(&n, "q"); assert!(close(xy_of(&q["end"]), (4.0, 3.0))); let sweep = PI - 3.0_f64.atan2(4.0); @@ -940,7 +937,8 @@ mod tests { #[test] fn teilen_am_punkt_und_bruch() { let r = t_case(); - let n = commit_edit(&r, break_at(w_of(&r, "a"), P::new(4.0, 0.1), P::new(4.0, 0.1))); + let pr = typed(&r); + let n = commit_edit(&r, &pr, break_at(find_wall(&pr, "a").unwrap(), P::new(4.0, 0.1), P::new(4.0, 0.1))); assert!(close(xy_of(&w_of(&n, "a")["end"]), (4.0, 0.0))); let o2 = arr(n.get("openings")).iter().find(|o| o["id"] == "o2").unwrap(); assert_eq!(o2["hostWallId"], "wall-s-1"); @@ -950,7 +948,7 @@ mod tests { assert_eq!(g["refs"][2]["id"], "wall-s-1"); assert_eq!(g["refs"][2]["t"], json!(1.0)); // Bruch 2..3 entfernt das Stück dazwischen; o1 (1..2) bleibt am ersten Stück. - let n = commit_edit(&r, break_at(w_of(&r, "a"), P::new(2.5, 0.0), P::new(3.5, 0.0))); + let n = commit_edit(&r, &pr, break_at(find_wall(&pr, "a").unwrap(), P::new(2.5, 0.0), P::new(3.5, 0.0))); assert!(close(xy_of(&w_of(&n, "a")["end"]), (2.5, 0.0))); assert_eq!(arr(n.get("openings")).len(), 2); } @@ -962,7 +960,7 @@ mod tests { vec![opening("o", "b", 1.0, 1.0)], vec![dim("d", json!([{"id": "a", "feature": "wall", "t": 0.0}, {"id": "b", "feature": "wall", "t": 1.0}]), json!([{"x": 0, "y": 0}, {"x": 10, "y": 0}]))], ); - let n = apply(&r, join_ops(&r, &["a".into(), "b".into()])); + let n = apply(&r, join_ops(&r, &typed(&r), &["a".into(), "b".into()])); assert_eq!(arr(n.get("walls")).len(), 1); assert!(close(xy_of(&w_of(&n, "a")["end"]), (10.0, 0.0))); let o = &arr(n.get("openings"))[0]; @@ -973,13 +971,13 @@ mod tests { assert!(close(xy_of(&g["pts"][1]), (10.0, 0.0))); // Gegenläufig: nicht verketten. let r2 = project(vec![wall("a", (0.0, 0.0), (4.0, 0.0), None), wall("b", (10.0, 0.0), (4.0, 0.0), None)], vec![], vec![]); - assert!(join_ops(&r2, &["a".into(), "b".into()]).is_empty()); + assert!(join_ops(&r2, &typed(&r2), &["a".into(), "b".into()]).is_empty()); // Zwei Viertelbögen desselben Kreises (um (0,0), unten herum) → Halbkreis. let t = (PI / 8.0).tan(); let r3 = project(vec![wall("a", (-5.0, 0.0), (0.0, -5.0), Some(-t)), wall("b", (0.0, -5.0), (5.0, 0.0), Some(-t))], vec![], vec![]); - let c = Axis::of(w_of(&r3, "a")).unwrap().arc.unwrap().center; + let c = Axis::of(find_wall(&typed(&r3), "a").unwrap()).unwrap().arc.unwrap().center; assert!(close((c.x, c.y), (0.0, 0.0))); - let n = apply(&r3, join_ops(&r3, &["a".into(), "b".into()])); + let n = apply(&r3, join_ops(&r3, &typed(&r3), &["a".into(), "b".into()])); let a = w_of(&n, "a"); assert!(close(xy_of(&a["end"]), (5.0, 0.0))); assert!((a["bulge"].as_f64().unwrap() + 1.0).abs() < 1e-9); @@ -989,19 +987,20 @@ mod tests { fn verrunden_l_ecke_und_radius() { // a läuft nach rechts bis x = 4 (zu kurz), b senkrecht bei x = 6 über y = 0 hinaus. let r = project(vec![wall("a", (0.0, 0.0), (4.0, 0.0), None), wall("b", (6.0, 5.0), (6.0, -2.0), None)], vec![opening("o", "b", 1.0, 1.0)], vec![]); - let (a, b) = (w_of(&r, "a"), w_of(&r, "b")); - let n = commit_edit(&r, fillet(a, P::new(2.0, 0.0), b, P::new(6.0, 3.0), 0.0)); + let pr = typed(&r); + let (a, b) = (find_wall(&pr, "a").unwrap(), find_wall(&pr, "b").unwrap()); + let n = commit_edit(&r, &pr, fillet(a, P::new(2.0, 0.0), b, P::new(6.0, 3.0), 0.0)); assert!(close(xy_of(&w_of(&n, "a")["end"]), (6.0, 0.0))); assert!(close(xy_of(&w_of(&n, "b")["end"]), (6.0, 0.0))); assert!(close(xy_of(&w_of(&n, "b")["start"]), (6.0, 5.0))); // Radius 1: Tangentenpunkte (5,0) und (6,1), Bogenwand dazwischen. - let n = commit_edit(&r, fillet(a, P::new(2.0, 0.0), b, P::new(6.0, 3.0), 1.0)); + let n = commit_edit(&r, &pr, fillet(a, P::new(2.0, 0.0), b, P::new(6.0, 3.0), 1.0)); assert!(close(xy_of(&w_of(&n, "a")["end"]), (5.0, 0.0))); assert!(close(xy_of(&w_of(&n, "b")["end"]), (6.0, 1.0))); let arcw = arr(n.get("walls")).iter().find(|w| w["id"] == "wall-s-1").unwrap(); assert!(close(xy_of(&arcw["start"]), (5.0, 0.0))); assert!(close(xy_of(&arcw["end"]), (6.0, 1.0))); - let ax = Axis::of(arcw).unwrap(); + let ax = Axis::of(find_wall(&typed(&n), "wall-s-1").unwrap()).unwrap(); let m = ax.point(ax.len / 2.0, 0.0); let c = (5.0, 1.0); assert!(((m.x - c.0).hypot(m.y - c.1) - 1.0).abs() < 1e-9); @@ -1013,14 +1012,15 @@ mod tests { #[test] fn offset_gerade_und_bogen() { let r = project(vec![wall("a", (0.0, 0.0), (4.0, 0.0), None), wall("c", (-5.0, 0.0), (5.0, 0.0), Some(1.0))], vec![], vec![]); - let n = commit_edit(&r, offset(w_of(&r, "a"), 1.5)); + let pr = typed(&r); + let n = commit_edit(&r, &pr, offset(find_wall(&pr, "a").unwrap(), 1.5)); let w = arr(n.get("walls")).iter().find(|w| w["id"] == "wall-s-1").unwrap(); assert!(close(xy_of(&w["start"]), (0.0, 1.5))); assert!(close(xy_of(&w["end"]), (4.0, 1.5))); - let n = commit_edit(&r, offset(w_of(&r, "c"), 1.0)); + let n = commit_edit(&r, &pr, offset(find_wall(&pr, "c").unwrap(), 1.0)); let w = arr(n.get("walls")).iter().find(|w| w["id"] == "wall-s-1").unwrap(); - let ax = Axis::of(w).unwrap(); - let c = Axis::of(w_of(&r, "c")).unwrap().arc.unwrap(); + let ax = Axis::of(find_wall(&typed(&n), "wall-s-1").unwrap()).unwrap(); + let c = Axis::of(find_wall(&typed(&r), "c").unwrap()).unwrap().arc.unwrap(); assert!((ax.arc.unwrap().r - c.radius_at(1.0)).abs() < 1e-9); assert_eq!(w["bulge"].as_f64(), Some(1.0)); } @@ -1028,16 +1028,19 @@ mod tests { #[test] fn treffer_und_gesperrt() { let mut r = t_case(); - assert_eq!(pick_wall(&r, "eg", P::new(8.0, 0.05)).map(|w| id_of(w.0)), Some(Some("a"))); + let pr = typed(&r); + assert_eq!(pick_wall(&pr, "eg", P::new(8.0, 0.05)).map(|w| w.0.id.as_str()), Some("a")); r.get_mut("walls").unwrap().as_array_mut().unwrap()[0]["locked"] = json!(true); - assert!(trim(&r, w_of(&r, "a"), P::new(8.0, 0.0), false).is_none()); - assert_ne!(pick_wall(&r, "eg", P::new(8.0, 0.05)).map(|w| id_of(w.0)), Some(Some("a"))); + let pr = typed(&r); + assert!(trim(&pr, find_wall(&pr, "a").unwrap(), P::new(8.0, 0.0), false).is_none()); + assert_ne!(pick_wall(&pr, "eg", P::new(8.0, 0.05)).map(|w| w.0.id.as_str()), Some("a")); } #[test] fn trim_an_2d_linie_und_achsraster() { let r = project(vec![wall("a", (0.0, 0.0), (10.0, 0.0), None)], vec![], vec![json!({"id": "l", "type": "drawing2d", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "line", "a": {"x": 3, "y": -1}, "b": {"x": 3, "y": 1}}})]); - let n = commit_edit(&r, trim(&r, w_of(&r, "a"), P::new(1.0, 0.0), false)); + let pr = typed(&r); + let n = commit_edit(&r, &pr, trim(&pr, find_wall(&pr, "a").unwrap(), P::new(1.0, 0.0), false)); assert!(close(xy_of(&w_of(&n, "a")["start"]), (3.0, 0.0))); } } diff --git a/src-tauri/core/src/commands.rs b/src-tauri/core/src/commands.rs index a6f70d9e..200065ff 100644 --- a/src-tauri/core/src/commands.rs +++ b/src-tauri/core/src/commands.rs @@ -29,7 +29,7 @@ pub fn ops(root: &Map, p: &Project, text: &str) -> Result let cmd = v.get("cmd").and_then(Value::as_str).unwrap_or(""); let ids = |k: &str| -> Vec { v.get(k).and_then(|x| serde_json::from_value(x.clone()).ok()).unwrap_or_default() }; let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_string(); - if let Some(ops) = crate::cmd_edit::ops(root, &v) { + if let Some(ops) = crate::cmd_edit::ops(root, p, &v) { return Ok(ops); } if let Some(ops) = crate::cmd_create::ops(root, p, &v) { diff --git a/src-tauri/core/src/web/cmd_create.rs b/src-tauri/core/src/web/cmd_create.rs index ee11c0bc..911d3cae 100644 --- a/src-tauri/core/src/web/cmd_create.rs +++ b/src-tauri/core/src/web/cmd_create.rs @@ -51,7 +51,10 @@ pub fn doc_create_query(h: u32, req_json: &str) -> String { Ok(v) => v, Err(e) => return format!("\u{1}Zeichen-Abfrage: {e}"), }; - match with_doc(h, |d| crate::cmd_create::query(d.root(), &v)) { + match with_doc(h, |d| match d.project_lookup() { + Ok((p, lk)) => crate::cmd_create::query(lk.root, p, &v), + Err(e) => Some(Err(e)), + }) { Some(Some(Ok(v))) => v.to_string(), Some(Some(Err(e))) => format!("\u{1}{e}"), Some(None) => "\u{1}Unbekannte Zeichen-Abfrage".to_string(), diff --git a/src-tauri/core/src/web/commands.rs b/src-tauri/core/src/web/commands.rs index 20bcd350..c4358179 100644 --- a/src-tauri/core/src/web/commands.rs +++ b/src-tauri/core/src/web/commands.rs @@ -57,7 +57,7 @@ pub fn doc_cmd_query(h: u32, req_json: &str) -> String { Ok(v) => v, Err(e) => return format!("\u{1}Befehls-Abfrage: {e}"), }; - match with_doc(h, |d| crate::cmd_edit::query(d.root(), &v)) { + match with_doc(h, |d| d.project_lookup().and_then(|(p, lk)| crate::cmd_edit::query(lk.root, p, &v))) { Some(Ok(v)) => v.to_string(), Some(Err(e)) => format!("\u{1}{e}"), None => "\u{1}Dokument nicht offen".to_string(),