From ded5aa13323c276f65737fc99bf7d71ae0b44c09 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 08:06:44 +0000 Subject: [PATCH] =?UTF-8?q?[T7]=20Rotationsk=C3=B6rper=20und=20Loft=20als?= =?UTF-8?q?=20Befehle=20(Profil,=20Achse,=20Winkel=20/=20mehrere=20Profile?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.md | 2 +- src-tauri/core/src/cmd_create.rs | 2 +- src-tauri/core/src/cmd_solid.rs | 179 ++++++++++++++++++++++++++ src-tauri/trucksolid/src/brep.rs | 26 ++++ src/commands/cmds/extrude.ts | 8 +- src/commands/cmds/loft.ts | 71 ++++++++++ src/commands/cmds/revolve.ts | 98 ++++++++++++++ src/commands/cmds/revolveLoft.test.ts | 102 +++++++++++++++ src/commands/registry.ts | 7 + src/i18n/de.ts | 11 ++ src/i18n/en.ts | 11 ++ src/panels/ToolsPanel.tsx | 2 +- src/ui/ribbon/CommandIcon.tsx | 18 +++ 13 files changed, 530 insertions(+), 7 deletions(-) create mode 100644 src/commands/cmds/loft.ts create mode 100644 src/commands/cmds/revolve.ts create mode 100644 src/commands/cmds/revolveLoft.test.ts diff --git a/TODO.md b/TODO.md index ee414d73..e423e492 100644 --- a/TODO.md +++ b/TODO.md @@ -1357,7 +1357,7 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). - ○ **[T4] Import-Meshes glätten oder kantig** (`add_smooth_normals`). · S - ○ **[T5] Import reparieren** (`put_together_same_attrs`, Healing). · S - ○ **[T6] Glattes Gelände aus Höhenlinien** + Gelände-Prisma für Aushub (= [68]). · L -- ○ **[T7] Rotationskörper/Loft im UI** (API besteht). · S–M +- ✅ **[T7] Rotationskörper/Loft im UI** (API besteht). · S–M — 30.10.: Befehle `revolve` (Profil + Achse aus 2 Plan-Punkten + Winkel; Achse waagrecht auf Höhe r_max, Profil auf einer Seite) und `loft` (≥ 2 Profile der Reihe nach, gleichmässig über die Höhe; Punktzahl durch Kantenteilung angeglichen) in `cmd_solid.rs`/`cmds/{revolve,loft}.ts`, Körper als `ExtrudedSolid.brep` (Objekt-Info, STEP, Kennwerte wie die Grundkörper); Kürzel `rev`/`lf`, Werkzeugpalette 3D. Tests Rust (Spezifikation, Ops, truck-Volumen/STEP), vitest (Befehlsablauf). Nicht in der Tauri-App getestet. Offen: Achse senkrecht/beliebig im Raum, Loft mit Führungskurve, Profil-Startpunkt-Ausrichtung beim Loft. - ○ **[T8] Kollisionsprüfung im 3D zeigen** (heute nur Marker im Grundriss). · S --- diff --git a/src-tauri/core/src/cmd_create.rs b/src-tauri/core/src/cmd_create.rs index f0225a3a..a4c38a94 100644 --- a/src-tauri/core/src/cmd_create.rs +++ b/src-tauri/core/src/cmd_create.rs @@ -881,7 +881,7 @@ const PROFILE_HIT_TOL: f64 = 0.25; /// Extrudierbares Profil einer Zeichnung: geschlossene Polylinie (≥ 3 Punkte), Rechteck, Kreis. /// Punkte als JSON-Werte (Polylinie: die gespeicherten), dazu `circle` beim Kreis. -fn profile_of(d: &Value) -> Option<(Vec, Option)> { +pub(crate) fn profile_of(d: &Value) -> Option<(Vec, Option)> { let g = field(d, "geom")?; match field(g, "shape").and_then(Value::as_str)? { "polyline" => { diff --git a/src-tauri/core/src/cmd_solid.rs b/src-tauri/core/src/cmd_solid.rs index 2a17b1d1..c3aad013 100644 --- a/src-tauri/core/src/cmd_solid.rs +++ b/src-tauri/core/src/cmd_solid.rs @@ -150,6 +150,130 @@ pub fn solid_from_inputs(shape: &str, p0: V, p1: Option, nums: &[f64]) -> Opt } } +// ═════════════════════════════════════════════════════════════════════════════ +// Rotationskörper und Loft aus Plan-Profilen ([T7]) +// ═════════════════════════════════════════════════════════════════════════════ + +/// Rotationskörper: das Plan-Profil (geschlossen, in der Zeichenebene) dreht sich um die Achse +/// `a → b` (liegt waagrecht im Plan, auf Höhe des grössten Profilabstands, damit ein voller Körper auf +/// der Geschoss-UK steht). Das Profil muss ganz auf einer Seite der Achse liegen; es wird als +/// (r = Abstand, z = Lage entlang der Achse) an `revolve` von truck gegeben und per `transform` ins +/// Modell gesetzt (lokal x → Querrichtung, y → oben, z → Achse). `angle_deg` in (0, 360]; positive +/// Drehung hebt das Profil nach oben. Ergebnis: Grundriss-Rechteck, Höhe, B-Rep-Beschreibung, Label. +pub fn revolve_from_profile(profile: &[V], a: V, b: V, angle_deg: f64) -> Option<(Vec, f64, Value, String)> { + let len = hypot2(b.0 - a.0, b.1 - a.1); + if profile.len() < 3 || !(len > 1e-6) || !angle_deg.is_finite() || !(angle_deg > 0.0) { + return None; + } + let mut d = ((b.0 - a.0) / len, (b.1 - a.1) / len); + let side = |d: V, p: V| (p.0 - a.0) * -d.1 + (p.1 - a.1) * d.0; + let (lo, hi) = profile.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(side(d, *p)), hi.max(side(d, *p)))); + if !(lo.is_finite() && hi.is_finite()) { + return None; + } + if lo < -1e-6 { + if hi > 1e-6 { + return None; // Profil überquert die Achse + } + d = (-d.0, -d.1); // Profil liegt rechts: Achse umdrehen, damit r >= 0 + } + let n = (-d.1, d.0); + let ring: Vec<(f64, f64)> = profile.iter().map(|p| (side(d, *p).max(0.0), (p.0 - a.0) * d.0 + (p.1 - a.1) * d.1)).collect(); + let r_max = ring.iter().fold(0.0_f64, |m, q| m.max(q.0)); + if !(r_max > 1e-6) { + return None; + } + let (z_min, z_max) = ring.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), q| (lo.min(q.1), hi.max(q.1))); + if !(z_max - z_min > 1e-6) { + return None; + } + let angle = angle_deg.min(360.0); + let flat: Vec = ring.iter().flat_map(|q| [js_num(q.0), js_num(q.1)]).collect(); + let inner = obj(vec![("kind", s("revolve")), ("profile", Value::Array(flat)), ("angleDeg", js_num(angle))]); + let m = [n.0, 0.0, d.0, a.0, n.1, 0.0, d.1, a.1, 0.0, 1.0, 0.0, r_max]; + let spec = obj(vec![("kind", s("transform")), ("m", Value::Array(m.iter().map(|x| js_num(*x)).collect())), ("solid", inner)]); + let at = |along: f64, perp: f64| (a.0 + d.0 * along + n.0 * perp, a.1 + d.1 * along + n.1 * perp); + let pts = vec![at(z_min, -r_max), at(z_max, -r_max), at(z_max, r_max), at(z_min, r_max)]; + Some((pts, 2.0 * r_max, spec, format!("Rotationskörper {}°", fixed2(angle)))) +} + +fn ring_area(r: &[V]) -> f64 { + let n = r.len(); + (0..n).map(|i| r[i].0 * r[(i + 1) % n].1 - r[(i + 1) % n].0 * r[i].1).sum::() / 2.0 +} + +/// Gleiche Punktzahl für alle Ringe: kürzere Ringe teilen ihre längste Kante, bis sie so viele Punkte +/// haben wie der längste (Ecken bleiben erhalten); alle gegen den Uhrzeigersinn. +fn match_rings(rings: &[Vec]) -> Vec> { + let target = rings.iter().map(Vec::len).max().unwrap_or(0); + rings + .iter() + .map(|r| { + let mut r = r.clone(); + if ring_area(&r) < 0.0 { + r.reverse(); + } + while r.len() < target { + let n = r.len(); + let len = |k: usize| hypot2(r[(k + 1) % n].0 - r[k].0, r[(k + 1) % n].1 - r[k].1); + let Some(i) = (0..n).max_by(|&i, &j| len(i).partial_cmp(&len(j)).unwrap_or(std::cmp::Ordering::Equal)) else { break }; + let (p, q) = (r[i], r[(i + 1) % n]); + r.insert(i + 1, ((p.0 + q.0) / 2.0, (p.1 + q.1) / 2.0)); + } + r + }) + .collect() +} + +/// Loft durch >= 2 Plan-Profile, gleichmässig über `height` verteilt (erstes Profil unten). +pub fn loft_from_rings(rings: &[Vec], height: f64) -> Option<(Vec, f64, Value, String)> { + if rings.len() < 2 || !(height > 1e-6) || rings.iter().any(|r| r.len() < 3 || r.iter().any(|p| !(p.0.is_finite() && p.1.is_finite()))) { + return None; + } + let rings = match_rings(rings); + let last = (rings.len() - 1) as f64; + let sections: Vec = rings + .iter() + .enumerate() + .map(|(i, r)| obj(vec![("z", js_num(height * i as f64 / last)), ("points", Value::Array(r.iter().flat_map(|p| [js_num(p.0), js_num(p.1)]).collect()))])) + .collect(); + let spec = obj(vec![("kind", s("loft")), ("sections", Value::Array(sections))]); + Some((rings[0].clone(), height, spec, format!("Loft {} Profile h={}", rings.len(), fixed2(height)))) +} + +fn profile_ring(root: &Map, id: &str) -> Option> { + let (pts, _) = find(root, "drawings2d", id).and_then(crate::cmd_create::profile_of)?; + Some(pts.iter().map(xy).collect()) +} + +fn brep_solid_ops(root: &Map, ctx: &Ctx, ids: &mut IdGen, sources: &[&str], made: Option<(Vec, f64, Value, String)>) -> Vec { + let Some((pts, height, spec, label)) = made else { return Vec::new() }; + let solid = obj(vec![ + ("id", s(&ids.next("body"))), + ("type", s("extrudedSolid")), + ("levelId", s(ctx.level)), + ("points", pvs(&pts)), + ("height", js_num(height)), + ("brep", obj(vec![("spec", spec), ("origin", pv(pts[0])), ("label", s(&label))])), + ]); + let mut ops = crate::cmd_create::remove_op(root, "drawings2d", sources); + ops.extend(add_op("extrudedSolids", vec![solid])); + ops +} + +fn revolve_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let src = s_of(v, "source"); + let made = profile_ring(root, src).and_then(|ring| revolve_from_profile(&ring, p_of(v, "a"), p_of(v, "b"), num_or(field(v, "angle"), 360.0))); + brep_solid_ops(root, ctx, ids, &[src], made) +} + +fn loft_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let sources: Vec<&str> = arr(v.get("sources")).iter().filter_map(Value::as_str).collect(); + let rings: Option>> = sources.iter().map(|id| profile_ring(root, id)).collect(); + let made = rings.and_then(|r| loft_from_rings(&r, n_of(v, "height"))); + brep_solid_ops(root, ctx, ids, &sources, made) +} + fn solid_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { let nums: Vec = arr(v.get("nums")).iter().map(|x| num_of(Some(x))).collect(); let Some((pts, height, spec, label)) = solid_from_inputs(s_of(v, "shape"), p_of(v, "p0"), opt_p(v, "p1"), &nums) else { @@ -621,6 +745,8 @@ fn direction_arrow(a: V, b: V, sign: f64, out: &mut Shapes) { pub fn ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Option> { Some(match s_of(v, "cmd") { "solid" => solid_ops(v, ctx, ids), + "revolve" => revolve_ops(root, v, ctx, ids), + "loft" => loft_ops(root, v, ctx, ids), "solidbool" => solidbool_ops(root, v, ids), "voidbox" => voidbox_ops(v, ctx, ids), "terrain" => terrain_ops(root, ids), @@ -748,4 +874,57 @@ mod tests { assert_eq!(t["indices"].as_array().unwrap().len(), 6); assert_eq!(t["positions"][2], 1); } + + /// [T7] Rotationskörper: Achse waagrecht im Plan, Profil auf einer Seite, Matrix bildet lokal x → Quer, z → Achse ab. + #[test] + fn rotationskoerper_aus_profil() { + let prof = [(0.0, 0.0), (2.0, 0.0), (2.0, 1.0), (0.0, 1.0)]; + let (pts, h, spec, label) = revolve_from_profile(&prof, (0.0, 0.0), (5.0, 0.0), 360.0).unwrap(); + assert_eq!(h, 2.0); + assert_eq!(label, "Rotationskörper 360.00°"); + assert_eq!(spec["kind"], "transform"); + assert_eq!(spec["solid"]["profile"], json!([0, 0, 0, 2, 1, 2, 1, 0])); + let m: Vec = spec["m"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect(); + let w = |l: [f64; 3]| [m[0] * l[0] + m[1] * l[1] + m[2] * l[2] + m[3], m[4] * l[0] + m[5] * l[1] + m[6] * l[2] + m[7], m[8] * l[0] + m[9] * l[1] + m[10] * l[2] + m[11]]; + assert_eq!(w([1.0, 0.0, 2.0]), [2.0, 1.0, 1.0]); + assert_eq!(w([0.0, 1.0, 0.0]), [0.0, 0.0, 2.0]); + assert_eq!(pts.len(), 4); + let rechts = [(0.0, 0.0), (2.0, 0.0), (2.0, -1.0), (0.0, -1.0)]; + let (_, _, spec2, _) = revolve_from_profile(&rechts, (0.0, 0.0), (5.0, 0.0), 90.0).unwrap(); + assert_eq!(spec2["solid"]["angleDeg"], 90.0); + assert!(revolve_from_profile(&[(0.0, -1.0), (2.0, -1.0), (2.0, 1.0), (0.0, 1.0)], (0.0, 0.0), (5.0, 0.0), 360.0).is_none()); + assert!(revolve_from_profile(&prof, (0.0, 0.0), (0.0, 0.0), 360.0).is_none()); + assert!(revolve_from_profile(&prof, (0.0, 0.0), (5.0, 0.0), f64::NAN).is_none()); + } + + /// [T7] Loft: gleiche Punktzahl (Kante teilen), Höhen gleichmässig, Ringe gegen den Uhrzeigersinn. + #[test] + fn loft_aus_profilen() { + let quad = vec![(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]; + let tri_cw = vec![(0.5, 0.5), (0.5, 1.5), (1.5, 0.5)]; + let (pts, h, spec, label) = loft_from_rings(&[quad.clone(), tri_cw, quad.clone()], 3.0).unwrap(); + assert_eq!((pts.len(), h), (4, 3.0)); + assert_eq!(label, "Loft 3 Profile h=3.00"); + let secs = spec["sections"].as_array().unwrap(); + assert_eq!(secs.len(), 3); + assert_eq!(secs[1]["z"], 1.5); + assert!(secs.iter().all(|s| s["points"].as_array().unwrap().len() == 8)); + assert!(loft_from_rings(&[quad.clone()], 3.0).is_none()); + assert!(loft_from_rings(&[quad.clone(), quad], 0.0).is_none()); + } + + #[test] + fn rotation_und_loft_befehle_legen_koerper_an_und_entfernen_quellen() { + let d = |id: &str, pts: Value| json!({"id": id, "type": "drawing2d", "levelId": "eg", "geom": {"shape": "polyline", "closed": true, "pts": pts}}); + let sq = |x: f64, s: f64| json!([{"x": x, "y": 0}, {"x": x + s, "y": 0}, {"x": x + s, "y": s}, {"x": x, "y": s}]); + let root = json!({"drawings2d": [d("A", sq(0.0, 2.0)), d("B", sq(10.0, 1.0))]}); + let root = root.as_object().unwrap(); + let ctx = Ctx { level: "eg", floor_height: None, cat: "", wall_type: "", text_height: 0.25, symbol: 1.0 }; + let mut ids = IdGen::new("t"); + let ops = loft_ops(root, &json!({"sources": ["A", "B"], "height": 2.0}), &ctx, &mut ids); + assert_eq!(ops.len(), 2); + let ops = revolve_ops(root, &json!({"source": "A", "a": {"x": -1, "y": -1}, "b": {"x": 5, "y": -1}, "angle": 180}), &ctx, &mut ids); + assert_eq!(ops.len(), 2); + assert!(revolve_ops(root, &json!({"source": "ZZ", "a": {"x": 0, "y": 0}, "b": {"x": 1, "y": 0}}), &ctx, &mut ids).is_empty()); + } } diff --git a/src-tauri/trucksolid/src/brep.rs b/src-tauri/trucksolid/src/brep.rs index 4c1c54f7..21d14910 100644 --- a/src-tauri/trucksolid/src/brep.rs +++ b/src-tauri/trucksolid/src/brep.rs @@ -1127,6 +1127,32 @@ mod dbg_step { assert!((vol(&mir) - 6.0).abs() < 1e-6, "mir {}", vol(&mir)); } + /// [T7] Rotationskörper um eine waagrechte Planachse (Befehl `revolve`, `cmd_solid.rs`): Zylinder r=1, l=2 + /// auf dem Boden; Halbdrehung = halbes Volumen; STEP-Export klappt. + #[test] + fn revolve_um_waagrechte_achse_steht_auf_dem_boden() { + let spec = |angle: f64| SolidSpec::Transform { + m: [-1.0, 0.0, 0.0, 3.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0], + solid: Box::new(SolidSpec::Revolve { profile: vec![0.0, 0.0, 0.0, 2.0, 1.0, 2.0, 1.0, 0.0], cx: 0.0, cy: 0.0, angle_deg: angle }), + }; + let vol_zmin = |sp: &SolidSpec| { + let m = solid_mesh_core(sp, 0.005).unwrap(); + let p: Vec<[f64; 3]> = m.positions.chunks(3).map(|c| [c[0] as f64, c[1] as f64, c[2] as f64]).collect(); + let v: f64 = m.indices.chunks(3).map(|t| { + let (a, b, c) = (p[t[0] as usize], p[t[1] as usize], p[t[2] as usize]); + (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0 + }).sum(); + (v, p.iter().map(|q| q[2]).fold(f64::INFINITY, f64::min), p.iter().map(|q| q[2]).fold(f64::NEG_INFINITY, f64::max)) + }; + let (v, z0, z1) = vol_zmin(&spec(360.0)); + assert!((v - 2.0 * std::f64::consts::PI).abs() < 0.02, "Volumen {v}"); + assert!(z0.abs() < 1e-3 && (z1 - 2.0).abs() < 1e-3, "z {z0}..{z1}"); + let (vh, h0, _) = vol_zmin(&spec(180.0)); + assert!((vh - std::f64::consts::PI).abs() < 0.02, "halb {vh}"); + assert!(h0 > 0.99, "Halbdrehung steigt nach oben: {h0}"); + assert!(export_step_core(&[spec(360.0)], &StepHeader::default()).is_ok()); + } + #[test] fn bool_result_step_dump() { let dir = std::env::var("STEP_DUMP_DIR").unwrap_or_default(); diff --git a/src/commands/cmds/extrude.ts b/src/commands/cmds/extrude.ts index 9d21af23..30399e6f 100644 --- a/src/commands/cmds/extrude.ts +++ b/src/commands/cmds/extrude.ts @@ -32,25 +32,25 @@ let lastTaper = 0; // ── Profil (Kern, `cmd_create.rs`): geschlossene polyline/rect/circle → Punktliste ─ /** Profil eines extrudierbaren 2D-Elements (Kreis: 48-Eck + Mittelpunkt/Radius). */ -interface Profile { +export interface Profile { pts: Vec2[]; circle?: { center: Vec2; r: number }; } -type ProfileHit = { id: string } & Profile; +export type ProfileHit = { id: string } & Profile; function profileQuery(project: Project, req: { q: string } & Record): ProfileHit | null { return createQuery<{ hit: (ProfileHit & { circle: Profile["circle"] | null }) | null }>(project, req).hit ?? null; } /** Genau EIN geeignetes Profil vorgewählt (sonst null). */ -function singleSelectedProfile(project: Project, sel: CommandSelection): ProfileHit | null { +export function singleSelectedProfile(project: Project, sel: CommandSelection): ProfileHit | null { if (!sel.drawingId || sel.wallIds.length > 0) return null; return profileQuery(project, { q: "profile", id: sel.drawingId }); } /** Nächstes Profil der Ebene am Klickpunkt (Kanten-Abstand < 0.25 m). */ -const pickProfileAt = (project: Project, levelId: string, pt: Vec2): ProfileHit | null => +export const pickProfileAt = (project: Project, levelId: string, pt: Vec2): ProfileHit | null => profileQuery(project, { q: "pickProfile", level: levelId, pt: xy(pt) }); /** Commit (Kern): Quelle entfernen, Körper (Punkte + Höhe + Verjüngung) anlegen. */ diff --git a/src/commands/cmds/loft.ts b/src/commands/cmds/loft.ts new file mode 100644 index 00000000..c0215bd1 --- /dev/null +++ b/src/commands/cmds/loft.ts @@ -0,0 +1,71 @@ +// Loft ([T7]): ≥ 2 geschlossene Plan-Profile nacheinander anklicken (erstes = unten), Enter, dann die +// Gesamthöhe. Die Profile werden gleichmässig über die Höhe verteilt (Kern `cmd_solid.rs`: gleiche +// Punktzahl durch Kantenteilung, Drehsinn angeglichen) und zu einem truck-`loft`-B-Rep-Körper +// (`ExtrudedSolid.brep`) verbunden; die Quellprofile entfallen wie beim Extrudieren. + +import type { Command, CommandContext, CommandResult, CommandState, Vec2 } from "../types"; +import { createMutation } from "../createCore"; +import { pickProfileAt, type ProfileHit } from "./extrude"; + +let lastHeight = 3; + +interface LoftState extends CommandState { + phase: "pick" | "height" | "done"; + picks: ProfileHit[]; +} + +const draft = (s: LoftState, cursor: Vec2 | null): CommandResult["draft"] => ({ + preview: s.picks.map((p) => ({ kind: "poly" as const, pts: p.pts, closed: true })), + vertices: [], + hud: cursor ? { at: cursor, text: s.phase === "height" ? `${lastHeight.toFixed(2)} m` : `${s.picks.length}` } : undefined, +}); + +const finished = (): LoftState => ({ phase: "done", picks: [], lastPoint: null }); +const done = (): [CommandState, CommandResult] => [finished(), { draft: null, done: true }]; + +function commit(s: LoftState, height: number, ctx: CommandContext): [CommandState, CommandResult] { + lastHeight = height; + return [ + finished(), + { draft: null, done: true, commit: createMutation(ctx, { cmd: "loft", sources: s.picks.map((p) => p.id), height }) }, + ]; +} + +export const loftCommand: Command = { + name: "loft", + labelKey: "cmd.loft.label", + prompt: (st) => ((st as LoftState).phase === "height" ? "cmd.loft.height" : (st as LoftState).picks.length < 2 ? "cmd.loft.pick" : "cmd.loft.pickMore"), + accepts: (st) => ((st as LoftState).phase === "height" ? ["number"] : ["point"]), + options: () => [], + floorOnly: true, + + init: (): LoftState => ({ phase: "pick", picks: [], lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + const s = state as LoftState; + if (s.phase === "done") return done(); + if (s.phase === "pick") { + if (input.kind !== "point") return [s, { draft: draft(s, null) }]; + const hit = pickProfileAt(ctx.project, ctx.level.id, input.point); + if (!hit || s.picks.some((p) => p.id === hit.id)) return [s, { draft: draft(s, null) }]; + const ns: LoftState = { ...s, picks: [...s.picks, hit] }; + return [ns, { draft: draft(ns, input.point) }]; + } + if (input.kind !== "number" || !(input.value > 0)) return [s, { draft: draft(s, null) }]; + return commit(s, input.value, ctx); + }, + + onMove: (state, point): [CommandState, CommandResult] => [state, { draft: draft(state as LoftState, point) }], + + // Enter: mit ≥ 2 Profilen zur Höhe; bei der Höhe die zuletzt benutzte übernehmen. + onConfirm: (state, ctx): [CommandState, CommandResult] => { + const s = state as LoftState; + if (s.phase === "pick") { + if (s.picks.length < 2) return [s, { draft: draft(s, null) }]; + const ns: LoftState = { ...s, phase: "height" }; + return [ns, { draft: draft(ns, null) }]; + } + return s.phase === "height" ? commit(s, lastHeight, ctx) : done(); + }, + onCancel: () => done(), +}; diff --git a/src/commands/cmds/revolve.ts b/src/commands/cmds/revolve.ts new file mode 100644 index 00000000..9b72148f --- /dev/null +++ b/src/commands/cmds/revolve.ts @@ -0,0 +1,98 @@ +// Rotationskörper ([T7]): geschlossenes Plan-Profil + Drehachse (2 Punkte im Plan) + Winkel → truck- +// `revolve` als B-Rep-Körper (`ExtrudedSolid.brep`, Kern `cmd_solid.rs`). Das Profil muss ganz auf einer +// Seite der Achse liegen; die Achse liegt waagrecht auf Höhe des grössten Profilabstands, ein voller +// Körper steht also auf der Geschoss-UK. Die Quelle (Profil) wird ersetzt wie beim Extrudieren. +// +// Schritte: Profil wählen (oder vorselektiert) → Achse Anfang → Achse Ende → Winkel (Zahl oder Enter = zuletzt, 360). + +import type { Command, CommandContext, CommandResult, CommandState, Vec2 } from "../types"; +import { createMutation } from "../createCore"; +import { pickProfileAt, singleSelectedProfile, type Profile } from "./extrude"; + +let lastAngle = 360; + +interface RevState extends CommandState { + phase: "pick" | "axisA" | "axisB" | "angle" | "done"; + profile: Profile | null; + sourceId: string | null; + a: Vec2 | null; + b: Vec2 | null; + cursor: Vec2 | null; +} + +const draft = (s: RevState, cursor: Vec2 | null): CommandResult["draft"] => { + const preview: NonNullable["preview"] = []; + if (s.profile) preview.push({ kind: "poly", pts: s.profile.pts, closed: true }); + const end = s.b ?? cursor; + if (s.a && end) preview.push({ kind: "line", a: s.a, b: end }); + return { preview, vertices: s.a ? [s.a] : [], hud: cursor && s.phase === "angle" ? { at: cursor, text: `${lastAngle}°` } : undefined }; +}; + +const finished = (): RevState => ({ phase: "done", profile: null, sourceId: null, a: null, b: null, cursor: null, lastPoint: null }); + +const done = (): [CommandState, CommandResult] => [finished(), { draft: null, done: true }]; + +function commit(s: RevState, angle: number, ctx: CommandContext): [CommandState, CommandResult] { + lastAngle = angle; + return [ + finished(), + { draft: null, done: true, commit: createMutation(ctx, { cmd: "revolve", source: s.sourceId, a: s.a, b: s.b, angle }) }, + ]; +} + +export const revolveCommand: Command = { + name: "revolve", + labelKey: "cmd.revolve.label", + prompt: (st) => { + const p = (st as RevState).phase; + return p === "axisA" ? "cmd.revolve.axisA" : p === "axisB" ? "cmd.revolve.axisB" : p === "angle" ? "cmd.revolve.angle" : "cmd.revolve.pick"; + }, + accepts: (st) => ((st as RevState).phase === "angle" ? ["number"] : ["point"]), + options: () => [], + floorOnly: true, + + init: (): RevState => ({ phase: "pick", profile: null, sourceId: null, a: null, b: null, cursor: null, lastPoint: null }), + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + let s = state as RevState; + if (s.phase === "done") return done(); + if (s.phase === "pick") { + if (input.kind !== "point") return [s, { draft: null }]; + // Vorselektiertes Profil: der erste Punkt ist gleich der Achsenanfang. + const pre = singleSelectedProfile(ctx.project, ctx.selection); + if (pre) { + s = { ...s, phase: "axisA", profile: pre, sourceId: pre.id }; + } else { + const hit = pickProfileAt(ctx.project, ctx.level.id, input.point); + if (!hit) return [s, { draft: null }]; + const ns: RevState = { ...s, phase: "axisA", profile: hit, sourceId: hit.id }; + return [ns, { draft: draft(ns, null) }]; + } + } + if (s.phase === "axisA") { + if (input.kind !== "point") return [s, { draft: draft(s, s.cursor) }]; + const ns: RevState = { ...s, phase: "axisB", a: input.point, lastPoint: input.point }; + return [ns, { draft: draft(ns, input.point) }]; + } + if (s.phase === "axisB") { + if (input.kind !== "point" || !s.a || Math.hypot(input.point.x - s.a.x, input.point.y - s.a.y) < 1e-6) return [s, { draft: draft(s, s.cursor) }]; + const ns: RevState = { ...s, phase: "angle", b: input.point, lastPoint: input.point }; + return [ns, { draft: draft(ns, input.point) }]; + } + // angle + if (input.kind !== "number" || !(input.value > 0)) return [s, { draft: draft(s, s.cursor) }]; + return commit(s, Math.min(360, input.value), ctx); + }, + + onMove: (state, point): [CommandState, CommandResult] => { + const s = { ...(state as RevState), cursor: point }; + return [s, { draft: draft(s, point) }]; + }, + + // Enter beim Winkel: zuletzt benutzten Winkel übernehmen. + onConfirm: (state, ctx): [CommandState, CommandResult] => { + const s = state as RevState; + return s.phase === "angle" ? commit(s, lastAngle, ctx) : done(); + }, + onCancel: () => done(), +}; diff --git a/src/commands/cmds/revolveLoft.test.ts b/src/commands/cmds/revolveLoft.test.ts new file mode 100644 index 00000000..7e304588 --- /dev/null +++ b/src/commands/cmds/revolveLoft.test.ts @@ -0,0 +1,102 @@ +/** + * [T7] `revolveCommand` (Profil + Achse + Winkel) und `loftCommand` (≥ 2 Profile + Höhe): beide legen + * einen B-Rep-Körper (`ExtrudedSolid.brep`) an und entfernen die Quellprofile. + */ + +import { describe, it, expect } from "vitest"; +import { revolveCommand } from "./revolve"; +import { loftCommand } from "./loft"; +import type { CommandContext, CmdInput, Project } from "../types"; + +const rect = (id: string, x: number, y: number, w: number, h: number) => ({ + id, + type: "drawing2d" as const, + levelId: "eg", + categoryCode: "20", + geom: { shape: "rect" as const, min: { x, y }, max: { x: x + w, y: y + h } }, +}); + +function project(): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [], + wallTypes: [], + drawingLevels: [{ id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 }], + layers: [{ code: "20", name: "Zeichnung", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }], + walls: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [rect("A", 0, 1, 2, 1), rect("B", 10, 0, 1, 1)], + extrudedSolids: [], + context: [], + } as unknown as Project; +} + +function makeCtx(p: Project, drawingId: string | null = null): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId }, + } as CommandContext; +} + +/** Spielt Eingaben ab; liefert das Projekt nach dem Commit (oder null). */ +function run(cmd: typeof revolveCommand, p: Project, inputs: Array, selected: string | null = null) { + const ctx = makeCtx(p, selected); + let state = cmd.init(); + let commit: ((p: Project) => Project) | undefined; + for (const i of inputs) { + const [ns, res] = i === "confirm" ? cmd.onConfirm(state, ctx) : cmd.onInput(state, i, ctx); + state = ns; + if (res.commit) commit = res.commit as typeof commit; + } + return commit ? commit(p) : null; +} + +const pt = (x: number, y: number): CmdInput => ({ kind: "point", point: { x, y } }); + +describe("revolveCommand", () => { + it("Profil wählen, Achse (2 Punkte), Winkel → Rotationskörper, Quelle entfernt", () => { + const next = run(revolveCommand, project(), [pt(1, 1), pt(-1, 0), pt(5, 0), { kind: "number", value: 180 }])!; + expect(next.drawings2d.map((d) => d.id)).toEqual(["B"]); + const s = next.extrudedSolids![0]; + expect(s.brep!.spec).toMatchObject({ kind: "transform", solid: { kind: "revolve", angleDeg: 180 } }); + expect(s.height).toBeCloseTo(4, 9); // Profil 1 … 2 m neben der Achse y=0 → r_max = 2 + }); + + it("Enter beim Winkel übernimmt den zuletzt benutzten; vorgewähltes Profil überspringt die Wahl", () => { + run(revolveCommand, project(), [pt(1, 1), pt(-1, 0), pt(5, 0), { kind: "number", value: 90 }]); + const next = run(revolveCommand, project(), [pt(-1, 0), pt(5, 0), "confirm"], "A")!; + expect(next.extrudedSolids![0].brep!.spec).toMatchObject({ solid: { angleDeg: 90 } }); + }); + + it("Profil, das die Achse überquert, ergibt keinen Körper", () => { + const next = run(revolveCommand, project(), [pt(1, 1), pt(-1, 1.5), pt(5, 1.5), "confirm"]); + expect(next?.extrudedSolids ?? []).toHaveLength(0); + }); +}); + +describe("loftCommand", () => { + it("zwei Profile wählen, Enter, Höhe → Loft-Körper, Quellen entfernt", () => { + const next = run(loftCommand, project(), [pt(1, 1), pt(10.5, 0), "confirm", { kind: "number", value: 3 }])!; + expect(next.drawings2d).toHaveLength(0); + const s = next.extrudedSolids![0]; + expect(s.height).toBe(3); + expect(s.brep!.spec).toMatchObject({ kind: "loft" }); + expect((s.brep!.spec as { sections: unknown[] }).sections).toHaveLength(2); + }); + + it("mit nur einem Profil bleibt Enter wirkungslos", () => { + const next = run(loftCommand, project(), [pt(1, 1), "confirm", { kind: "number", value: 3 }]); + expect(next?.extrudedSolids ?? []).toHaveLength(0); + }); +}); diff --git a/src/commands/registry.ts b/src/commands/registry.ts index 0991b3c4..522c869a 100644 --- a/src/commands/registry.ts +++ b/src/commands/registry.ts @@ -53,6 +53,8 @@ import { copyCommand } from "./cmds/copy"; import { arrayCommand } from "./cmds/array"; import { offsetCommand } from "./cmds/offset"; import { extrudeCommand } from "./cmds/extrude"; +import { revolveCommand } from "./cmds/revolve"; +import { loftCommand } from "./cmds/loft"; import { trimCommand } from "./cmds/trim"; import { breakCommand } from "./cmds/break"; import { extendCommand } from "./cmds/extend"; @@ -120,6 +122,8 @@ export const COMMANDS: Record = { array: arrayCommand, offset: offsetCommand, extrude: extrudeCommand, + revolve: revolveCommand, + loft: loftCommand, trim: trimCommand, break: breakCommand, extend: extendCommand, @@ -244,6 +248,9 @@ export const ALIASES: Record = { feld: "array", o: "offset", ex: "extrude", + rev: "revolve", + rotation: "revolve", + lf: "loft", tr: "trim", br: "break", unterbrechen: "break", diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 722c4946..afdd14e4 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1839,6 +1839,17 @@ export const de = { "cmd.offset.label": "Versatz", "cmd.offset.pick": "Kurve wählen:", "cmd.offset.side": "Seite oder Distanz:", + "cmd.revolve.label": "Rotationskörper", + "cmd.revolve.pick": "Geschlossenes Profil wählen:", + "cmd.revolve.axisA": "Drehachse: Anfangspunkt:", + "cmd.revolve.axisB": "Drehachse: Endpunkt:", + "cmd.revolve.angle": "Drehwinkel (°, Enter = zuletzt):", + "cmd.loft.label": "Loft", + "cmd.loft.pick": "Profile der Reihe nach wählen (unten zuerst):", + "cmd.loft.pickMore": "Weiteres Profil wählen oder Enter:", + "cmd.loft.height": "Gesamthöhe:", + "history.cmd.revolve": "Rotationskörper", + "history.cmd.loft": "Loft", "cmd.extrude.label": "Extrudieren", "cmd.extrude.pick": "Geschlossenes Profil wählen:", "cmd.extrude.height": "Höhe:", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 4c9dfc37..c8902b82 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1827,6 +1827,17 @@ export const en: Record = { "cmd.offset.label": "Offset", "cmd.offset.pick": "Select curve:", "cmd.offset.side": "Side or distance:", + "cmd.revolve.label": "Revolve", + "cmd.revolve.pick": "Select closed profile:", + "cmd.revolve.axisA": "Revolve axis: start point:", + "cmd.revolve.axisB": "Revolve axis: end point:", + "cmd.revolve.angle": "Revolve angle (°, Enter = last):", + "cmd.loft.label": "Loft", + "cmd.loft.pick": "Select profiles in order (bottom first):", + "cmd.loft.pickMore": "Select another profile or Enter:", + "cmd.loft.height": "Total height:", + "history.cmd.revolve": "Revolve", + "history.cmd.loft": "Loft", "cmd.extrude.label": "Extrude", "cmd.extrude.pick": "Select closed profile:", "cmd.extrude.height": "Height:", diff --git a/src/panels/ToolsPanel.tsx b/src/panels/ToolsPanel.tsx index 4fc8c5c6..8caaf8ec 100644 --- a/src/panels/ToolsPanel.tsx +++ b/src/panels/ToolsPanel.tsx @@ -355,7 +355,7 @@ const TOOLS_2D: ToolId[] = [ "image", ]; const TOOLS_3D: ToolId[] = ["wall", "ceiling", "window", "door", "stair", "room"]; -const COMMANDS_3D = ["column", "ceilingopening", "roof", "roofhole", "roofwindow", "dormer", "extrude", "solid", "solidbool", "sectionline", "viewline", "autodim"]; +const COMMANDS_3D = ["column", "ceilingopening", "roof", "roofhole", "roofwindow", "dormer", "extrude", "revolve", "loft", "solid", "solidbool", "sectionline", "viewline", "autodim"]; const COMMANDS_EDIT = ["move", "copy", "array", "rotate", "mirror", "offset", "multiline", "trim", "break", "extend", "fillet", "chamfer", "join", "defblock", "measure"]; type ToolsView = "list" | "icons"; diff --git a/src/ui/ribbon/CommandIcon.tsx b/src/ui/ribbon/CommandIcon.tsx index 84e16c37..abfb3966 100644 --- a/src/ui/ribbon/CommandIcon.tsx +++ b/src/ui/ribbon/CommandIcon.tsx @@ -225,6 +225,24 @@ export function CommandIcon({ name }: { name: string }) { ); + case "revolve": + // Rotationskörper: Profil neben einer Achse, Drehbogen. + return ( + + + + + + ); + case "loft": + // Loft: grosses Profil unten, kleines oben, verbunden. + return ( + + + + + + ); case "voidbox": // Durchbruch: Wand mit gestricheltem, durchkreuztem Ausschnitt. return (