From 27f7df80980494d14faa39fbc8057d00760a2990 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 09:41:52 +0000 Subject: [PATCH] =?UTF-8?q?[222]=20Volumenstudie=20=E2=86=92=20Bauteile:?= =?UTF-8?q?=20K=C3=B6rper=20in=20Aussenw=C3=A4nde=20je=20Geschoss,=20Decke?= =?UTF-8?q?n=20und=20Flachdach=20umwandeln?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Neuer Befehl solidtoparts (koerperinbauteile): gewählter Körper oder Klick; ein Undo-Schritt. Kern cmd_massing.rs: bestehende Geschosse nutzen, fehlende obenauf anlegen; Wände mit Aussenfläche auf der Körperkante (Referenz left), Decken/Dach wie beim Zeichnen (ceiling_item/roof_item aus cmd_create.rs), Körper entfällt. Nicht abgedeckte Körper (verjüngt, Kugel/Kegel, verrundet, Abzugskörper, selbstschneidend, UK zwischen Geschossen) werden mit Meldung abgelehnt. Tests: Rust, vitest, e2e [222] statt fixme. --- TODO.md | 16 +- doc/RELEASE-1.0.md | 2 +- e2e/release10.spec.ts | 32 +- src-tauri/core/src/README.md | 1 + src-tauri/core/src/cmd_create.rs | 53 ++- src-tauri/core/src/cmd_massing.rs | 522 +++++++++++++++++++++++++ src-tauri/core/src/lib.rs | 1 + src/commands/README.md | 2 +- src/commands/cmds/solidToParts.test.ts | 108 +++++ src/commands/cmds/solidToParts.ts | 67 ++++ src/commands/registry.ts | 4 + src/i18n/de.ts | 13 + src/i18n/en.ts | 13 + src/panels/ToolsPanel.tsx | 2 +- src/ui/ribbon/CommandIcon.tsx | 8 + 15 files changed, 817 insertions(+), 27 deletions(-) create mode 100644 src-tauri/core/src/cmd_massing.rs create mode 100644 src/commands/cmds/solidToParts.test.ts create mode 100644 src/commands/cmds/solidToParts.ts diff --git a/TODO.md b/TODO.md index ac683074..c5d9d291 100644 --- a/TODO.md +++ b/TODO.md @@ -59,7 +59,7 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC. oben ein Test; was fehlt, wird hier als Aufgabe eingetragen. · M Umgesetzt (12.11.): `e2e/release10.spec.ts` spielt leeres Projekt → Kataster-DXF (LV95) → Baurecht → Wände/Decke/Dach → Raum + Raumprogramm → SIA 416/Kennzahlen (CSV/PDF) → 1:200 → Schnitt → Axonometrie/Schatten → Präsentationsplan A1 → Publikation PDF → DXF/IFC - → Speichern in 13 Schritten durch; fehlende Schritte als `test.fixme` ([207] [208] [211] [222]; [223] [224] seit 13.11. aktiv; [209], [221] und [225] seit 12.11. aktiv). Behoben: GV in der + → Speichern in 13 Schritten durch; fehlende Schritte als `test.fixme` ([207] [208] [211]; [222] [223] [224] seit 13.11. aktiv; [209], [221] und [225] seit 12.11. aktiv). Behoben: GV in der Kennzahlenleiste war ohne freie Körper 0 m³, neue Decken bekamen den Aussenwand-Aufbau statt eines Deckentyps. Offen: Durchlauf der Checkliste auf dem Mac (Maintainer); 3D-Bild headless nicht prüfbar (kein WebGPU). @@ -188,8 +188,18 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC. lavapipe gemessen (komplex ~150–570 ms Software), Culling/LOD/Instancing erst nach Messung auf echter GPU (Mac); (5) Draw-Calls der Geisterschicht je Klumpen (gross 275 → 465), ggf. bündeln. · M -- ○ **[222]** Volumenstudie → Bauteile (12.11., aus [206]): gewählten Körper (Massenmodell) in Aussenwände je Geschoss, Decken und Flachdach - umwandeln, Geschosse aus der Körperhöhe; heute nur Zeichnen von Wand/Decke/Dach oder GV aus Körpern. Ort: neuer Befehl, Kern `cmd_create.rs`. · M +- ✓ **[222]** Volumenstudie → Bauteile (12.11., aus [206]; umgesetzt 13.11.): Befehl `solidtoparts` (`koerperinbauteile`, Werkzeuge 3D + neben „Körper verschneiden“) wandelt den gewählten Körper (sonst Klick in den Körper) in einem Undo-Schritt um: je Geschoss eine + Aussenwand je Umrisskante (aktiver Wandtyp, Referenz „left“ = Aussenfläche auf der Körperkante, wächst nach innen, `isExternal`), + Decken zwischen den Geschossen (Deckentyp wie beim Zeichnen), Flachdach ohne Vorsprung bündig mit der Körper-OK; der Körper entfällt + (GV sonst doppelt). Geschosse: Körper-UK muss auf einem Geschoss oder der Stapel-OK stehen; bestehende Geschosse werden genutzt, fehlende + obenauf angelegt (Höhe des obersten, gleichmässig auf den Rest verteilt), Reste < 0.5 m verlängern das oberste. Prismen auch nicht- + rechteckig/konkav, dazu Quader/Zylinder des Befehls „Körper“. Abgelehnt mit Meldung: verjüngt, Kugel/Kegel/Torus/Rotation/Verschneidung, + verrundete/gefaste Ecken, Abzugskörper, selbstschneidender Grundriss, UK zwischen Geschossen, < 0.5 m. Kern `cmd_massing.rs` (Decke/Dach + über `ceiling_item`/`roof_item` aus `cmd_create.rs`), Befehl `commands/cmds/solidToParts.ts`. Tests: Rust `cmd_massing::tests` (5), + vitest `solidToParts.test.ts`, e2e `release10.spec.ts` [222] (aus fixme). Angesehen: CLI-Plan/Schnitt eines L-Körpers mit schräger Kante, + Browser-App (Linux). Offen: Mac/Tauri nicht geprüft; keine Bodenplatte unter dem untersten Geschoss; keine Innenwände/Öffnungen; + Körper mit Löchern (gibt es im Modell nicht) und Bogenkanten (Zylinder wird zum 48-Eck aus Einzelwänden). · M - ✓ **[229]** Cycles-Rendering: Streifen/Dreiecke auf der Hauptdachfläche (12.11., Maintainer, Musterhaus komplex Iso). Ursache: Das GLB hat keine UVs; der Normal-Map-Knoten (Tangentenraum) bekam je Dreieck einen anderen Tangentenrahmen und zeichnete die Gauben-Fan-Triangulierung als helle/dunkle Diagonalen. Nicht im Netz: GLB geprüft (Normalen der Dachdreiecke an der Oberseite max. 0.0002 rad neben der Flächennormalen, diff --git a/doc/RELEASE-1.0.md b/doc/RELEASE-1.0.md index 14834c4a..a25aea46 100644 --- a/doc/RELEASE-1.0.md +++ b/doc/RELEASE-1.0.md @@ -56,7 +56,7 @@ E 2'600'048 / N 1'200'046 und E 2'600'060 / N 1'200'056. Raumprogramm als CSV (` | 3.2 | Befehl `wand` (Kürzel `w`), Punkte tippen `2600048,1200046` … zurück zum Start, Enter | 4 Aussenwände, Ecken verbunden (getippte Landeskoordinaten landen lokal bei 48/46) | ✅ (Spec 3) | | 3.3 | Befehl `decke` (`d`), 4 Ecken, Enter | eine Decke mit Deckentyp „Geschossdecke mehrschichtig“ | ✅ (Spec 3; vorher Aussenwand-Aufbau, in [206] behoben) | | 3.4 | Befehl `dach` (`rf`), zwei Ecken | Satteldach 30°, Vorsprung 0.4 m | ✅ (Spec 3) | -| 3.5 | Volumen als Körper (`koerper`) und daraus Wände/Decken/Dach | Bauteile je Geschoss aus dem Körper | ❌ **[222]** (Körper geht, Umwandlung fehlt) | +| 3.5 | Volumen als Körper (`koerper`, Form Quader), dann `koerperinbauteile` und in den Körper klicken (oder Körper wählen, dann Befehl) | Aussenwände je Geschoss (aussen bündig mit dem Körper), Decken, Flachdach auf Körper-OK, fehlende Geschosse obenauf; Meldung mit Anzahl; ⌘Z nimmt alles zurück | ✅ (Spec [222]; geneigte/Kugel-/Kegelkörper werden mit Meldung abgelehnt) | | 3.6 | Obergeschoss: Wände kopieren (⌘5/⌘6 Geschoss wechseln) | OG mit Wänden, GF steigt | ◐ nicht in der Spec | ## 4. Raumprogramm gegen Modell diff --git a/e2e/release10.spec.ts b/e2e/release10.spec.ts index 6a87214b..75f887a3 100644 --- a/e2e/release10.spec.ts +++ b/e2e/release10.spec.ts @@ -345,7 +345,37 @@ test("Referenz-Ablauf WBW/Vorprojekt: leeres Projekt bis Abgabe", async ({ page // ── Was für 1.0 noch fehlt (je ein Test, bis der Schritt geht; Reproduktion in TODO.md) ────────────────────── -test.fixme("[222] Volumenstudie: Wände/Decken/Dach aus einem Volumen (Körper) erzeugen", async () => {}); +// [222] Quader-Körper (Befehl „Körper“) 12 × 10 × 8 m im EG, dann „Körper in Bauteile umwandeln“ per Klick (getippter +// Punkt): Aussenwände je Geschoss, Decken, Flachdach, fehlende Geschosse obenauf; Strg+Z nimmt alles in einem Schritt zurück. +test("[222] Volumenstudie: Wände/Decken/Dach aus einem Volumen (Körper) erzeugen", async ({ page }) => { + await startNewProject(page); + await openTab(page, "Zeichnungsebenen"); + await page.getByText("Erdgeschoss", { exact: true }).first().click(); + const floors = page.getByText(/^Geschoss \d+$/); + const floorsBefore = await floors.count(); + await typeCommand(page, "koerper"); + await typeCommand(page, "cuboid"); + await expect(page.locator(".cmdline-prompt")).toHaveText("Mittelpunkt bzw. erste Ecke:"); + await typeCommand(page, "0,0"); + await typeCommand(page, "12,10"); + await typeCommand(page, "8"); + await expect(page.locator(".cmdline-prompt")).toHaveText("Befehl:"); + await typeCommand(page, "koerperinbauteile"); + await expect(page.locator(".cmdline-prompt")).toHaveText("Körper wählen (Massenmodell):"); + await typeCommand(page, "6,5"); + const done = page.locator(".toast-message").filter({ hasText: /Geschosse \(\d+ neu\): \d+ Aussenwände, \d+ Decken und Flachdach erzeugt/ }); + await expect(done).toBeVisible(); + const [, stories, fresh, walls, ceilings] = (await done.first().innerText()).match(/(\d+) Geschosse \((\d+) neu\): (\d+) Aussenwände, (\d+) Decken/)!.map(Number); + expect(stories).toBeGreaterThanOrEqual(2); + expect(walls).toBe(4 * stories); + expect(ceilings).toBe(stories - 1); + await expect(floors).toHaveCount(floorsBefore + fresh); + await shot(page, "222-bauteile"); + // Ein Undo-Schritt: neue Geschosse wieder weg. + await blurFocus(page); + await page.keyboard.press("ControlOrMeta+z"); + await expect(floors).toHaveCount(floorsBefore); +}); test.fixme("[207] Situation 1:500 / Schwarzplan als Ansichtsvorlage „Situation WBW“", async () => {}); diff --git a/src-tauri/core/src/README.md b/src-tauri/core/src/README.md index d3cbaa79..3f1a1ca8 100644 --- a/src-tauri/core/src/README.md +++ b/src-tauri/core/src/README.md @@ -71,6 +71,7 @@ Neues Modul: `.rs` und `mod` in `lib.rs`, Bindungen in `web/.rs` u |---|---| | `commands.rs` | Einstieg der Befehle: `ops()` verteilt eine Anfrage `{cmd, …}` | | `cmd_create.rs` | Zeichenbefehle für Bauteile: neue Elemente, Vorschau, Treffer | +| `cmd_massing.rs` | [222] Volumenstudie → Bauteile: Körper zu Aussenwänden je Geschoss, Decken, Flachdach (fehlende Geschosse obenauf) | | `cmd_draw.rs`, `cmd_edit.rs`, `cmd_split.rs`, `cmd_paste.rs` | 2D zeichnen und bemassen, bearbeiten, teilen, einfügen | | `cmd_transform.rs`, `cmd_wall_edit.rs`, `cmd_solid.rs` | Transformieren; Wände bearbeiten; Körper, Gelände, Sonderbefehle | | `cmd_context.rs` | [193] Höhenversatz und Höhe je Höhenlinie von Gelände-/Umgebungs-Elementen (`contextOffset`, `contourZ`) | diff --git a/src-tauri/core/src/cmd_create.rs b/src-tauri/core/src/cmd_create.rs index 09a10908..9d8e6493 100644 --- a/src-tauri/core/src/cmd_create.rs +++ b/src-tauri/core/src/cmd_create.rs @@ -273,7 +273,7 @@ fn active_wall_type<'a>(root: &'a Map, ctx: &Ctx) -> Option<&'a V } /// id des aktiven Wandtyps (Fallback: erster Typ, sonst die id aus dem Kontext). -fn active_wall_type_id(p: &Project, ctx: &Ctx) -> Value { +pub(crate) fn active_wall_type_id(p: &Project, ctx: &Ctx) -> Value { let t = p.wall_types.iter().find(|t| t.id == ctx.wall_type).or(p.wall_types.first()); s(t.map_or(ctx.wall_type, |t| t.id.as_str())) } @@ -448,19 +448,24 @@ fn ceiling_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { if abs_area(&outline) < 1e-4 { return Vec::new(); } + add_op("ceilings", vec![ceiling_item(p, ctx.level, &outline, ctx, ids)]) +} + +/// Neue Decke auf Geschoss `floor` mit dem Umriss `outline` (Aufbau wie beim Zeichnen; auch [222]). +pub(crate) fn ceiling_item(p: &Project, floor: &str, outline: &[V], ctx: &Ctx, ids: &mut IdGen) -> Value { let mut fields = vec![ ("id", s(&ids.next("C"))), ("type", s("ceiling")), - ("floorId", s(ctx.level)), + ("floorId", s(floor)), ("categoryCode", category_or(p, "30", ctx)), - ("outline", pvs(&outline)), + ("outline", pvs(outline)), ("wallTypeId", active_wall_type_id(p, ctx)), ]; // Eigener Deckentyp (erster des Projekts); `wallTypeId` bleibt als Pflichtfeld/Rückfall ([206]). if let Some(ct) = p.ceiling_types.as_deref().and_then(|l| l.first()) { fields.push(("ceilingTypeId", s(&ct.id))); } - add_op("ceilings", vec![obj(fields)]) + obj(fields) } /// Wände des Geschosses als `[n, (ax, ay, bx, by, dicke)…]` für die Raumerkennung. @@ -911,22 +916,27 @@ fn roof_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { if w < 0.1 || d < 0.1 { return Vec::new(); } - let shape = s_of(v, "shape"); - add_op( - "roofs", - vec![obj(vec![ - ("id", s(&ids.next("RF"))), - ("type", s("roof")), - ("floorId", s(ctx.level)), - ("categoryCode", category_or(p, "31", ctx)), - ("outline", pvs(&rect_corners(a, b))), - ("shape", s(shape)), - ("pitchDeg", js_num(if shape == "flach" { 0.0 } else { 30.0 })), - ("overhang", js_num(0.4)), - ("ridgeAxis", s(if w >= d { "x" } else { "y" })), - ("thickness", js_num(0.2)), - ])], - ) + add_op("roofs", vec![roof_item(p, ctx.level, &rect_corners(a, b), s_of(v, "shape"), 0.4, ctx, ids)]) +} + +/// Neues Dach auf Geschoss `floor` über `outline` (Vorgaben wie beim Zeichnen: 30° bzw. flach, 20 cm; auch [222]). +pub(crate) fn roof_item(p: &Project, floor: &str, outline: &[V], shape: &str, overhang: f64, ctx: &Ctx, ids: &mut IdGen) -> Value { + let (mut x0, mut x1, mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY); + for q in outline { + (x0, x1, y0, y1) = (x0.min(q.0), x1.max(q.0), y0.min(q.1), y1.max(q.1)); + } + obj(vec![ + ("id", s(&ids.next("RF"))), + ("type", s("roof")), + ("floorId", s(floor)), + ("categoryCode", category_or(p, "31", ctx)), + ("outline", pvs(outline)), + ("shape", s(shape)), + ("pitchDeg", js_num(if shape == "flach" { 0.0 } else { 30.0 })), + ("overhang", js_num(overhang)), + ("ridgeAxis", s(if x1 - x0 >= y1 - y0 { "x" } else { "y" })), + ("thickness", js_num(0.2)), + ]) } /// Stützen-Profil: rund (Durchmesser `size`) oder quadratisch (Kante `size`). @@ -1144,6 +1154,8 @@ pub fn ops(root: &Map, p: &Project, v: &Value) -> Option> "tree" => tree_ops(p, v, &ctx, ids), "circlesToTrees" => circles_to_trees_ops(root, p, v, &ctx, ids), "extrude" => extrude_ops(root, v, &ctx, ids), + // [222] Volumenstudie → Bauteile. + "solidToParts" => crate::cmd_massing::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)), }) } @@ -1263,6 +1275,7 @@ pub fn query(root: &Map, p: &Project, v: &Value) -> Option json!({ "hit": null }), }, "recognize" => crate::drawing_recognize::report(p, v), + "solidToParts" => crate::cmd_massing::check(p, v), "pickProfile" => 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, p, v).or_else(|| crate::cmd_solid::query(root, p, v)).map(Ok), diff --git a/src-tauri/core/src/cmd_massing.rs b/src-tauri/core/src/cmd_massing.rs new file mode 100644 index 00000000..d5f4b71e --- /dev/null +++ b/src-tauri/core/src/cmd_massing.rs @@ -0,0 +1,522 @@ +//! [222] Volumenstudie → Bauteile: ein prismatischer Körper (`ExtrudedSolid`, Grundriss-Polygon × Höhe) wird zu +//! Aussenwänden je Geschoss, Decken zwischen den Geschossen und einem Flachdach. Ein Undo-Schritt (Befehl +//! `solidtoparts` in `commands/cmds/solidToParts.ts`, Anfrage `{cmd: "solidToParts", id, floorName}`). +//! +//! Geschosse: der Körper muss auf einem Geschoss (OK fertig Boden) oder auf der Oberkante des Geschoss-Stapels +//! stehen. Ab dort nimmt der Befehl die bestehenden Geschosse; reicht der Stapel nicht bis zur Körper-OK, legt er +//! neue Geschosse obenauf an (Höhe des obersten Geschosses, gleichmässig auf die Resthöhe verteilt). Ein Rest unter +//! [`MIN_STORY`] verlängert die Wände des obersten Geschosses. Das Flachdach schliesst bündig mit der Körper-OK ab +//! (seine Schichten hängen nach unten wie bei einer Decke), die Hülle der Bauteile deckt sich mit dem Körper. +//! +//! Wände: je Umrisskante eine Wand des aktiven Wandtyps (wie beim Zeichnen), Referenzlinie „left“ = Aussenfläche +//! auf der Körperkante, Achse im Uhrzeigersinn, damit die Wand nach innen wächst. Decken und Dach mit den Vorgaben +//! des Zeichnens (`ceiling_item`, `roof_item`). Der Körper selbst entfällt (sonst zählte das GV doppelt). +//! +//! Abgelehnt (Code in [`check`], Meldung in der Hülle): geneigte/verjüngte Körper, B-Rep-Körper ausser Quader, +//! Zylinder und Extrusion (die sind Prismen über dem Grundriss `points`), verrundete oder +//! gefaste Ecken, Abzugskörper, selbstschneidende oder flächenlose Grundrisse, zu niedrige Körper, Körper-UK +//! zwischen zwei Geschossen. Löcher kennt `ExtrudedSolid` nicht. + +use crate::cmd_create::{active_wall_type_id, category_or, ceiling_item, obj, pv, remove_op, roof_item, s, s_of, Ctx, V}; +use crate::cmd_transform::IdGen; +use crate::json_util::js_num; +use crate::model::{DrawingLevelKind, ExtrudedSolid, Project}; +use crate::ops::Op; +use serde_json::{json, Value}; + +/// Toleranz für „steht auf dem Geschoss“ (Meter). +const TOL: f64 = 0.02; +/// Kleinste Geschosshöhe, die ein neues Geschoss wert ist; kleinere Reste verlängern das oberste. +pub const MIN_STORY: f64 = 0.5; +/// Vorgabe-Geschosshöhe ohne bestehende Geschosse. +const DEF_STORY: f64 = 3.0; +/// Obergrenze der Geschosse (Unsinn wie 1 km hohe Körper ablehnen statt tausende Wände zu bauen). +const MAX_STORIES: usize = 200; + +/// Ein Geschoss des Ergebnisses: bestehend (`new` = None) oder neu (Index in `Plan::new_floors`). +#[derive(Debug, Clone, PartialEq)] +pub struct Story { + pub floor: String, + /// Unterkante (OKFF) und Oberkante der Wände in diesem Geschoss. + pub base: f64, + pub top: f64, + /// Oberkante des Geschosses (`baseElevation + floorHeight`): dort liegt die Decke ohne Bindung. + pub floor_top: f64, +} + +/// Neues Geschoss (obenauf). +#[derive(Debug, Clone, PartialEq)] +pub struct NewFloor { + pub id: String, + pub name: String, + pub base: f64, + pub height: f64, +} + +#[derive(Debug)] +pub struct Plan { + /// Grundriss im Gegenuhrzeigersinn (Decken, Dach); die Wände laufen umgekehrt. + pub outline: Vec, + pub stories: Vec, + pub new_floors: Vec, +} + +/// Auf Mikrometer gerundet: Höhen aus Differenzen ohne Gleitkomma-Rest (2.5999999999999996 → 2.6). +fn um(x: f64) -> f64 { + (x * 1e6).round() / 1e6 +} + +fn cross(o: V, a: V, b: V) -> f64 { + (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0) +} + +/// Grundriss bereinigen: doppelte Punkte, Schlusspunkt und kollineare Zwischenpunkte weg, CCW. `None`, wenn er +/// entartet oder selbstschneidend ist. +pub fn clean_outline(pts: &[V]) -> Option> { + if pts.iter().any(|q| !q.0.is_finite() || !q.1.is_finite()) { + return None; + } + let near = |a: V, b: V| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6; + let mut r: Vec = Vec::new(); + for q in pts { + if r.last().is_none_or(|l| !near(*l, *q)) { + r.push(*q); + } + } + while r.len() > 1 && near(r[0], r[r.len() - 1]) { + r.pop(); + } + // Kollineare Punkte (auch Spitzen, die zurücklaufen) entfernen, bis nichts mehr wegfällt. + loop { + let n = r.len(); + if n < 3 { + return None; + } + let drop = (0..n).find(|&i| { + let (a, b, c) = (r[(i + n - 1) % n], r[i], r[(i + 1) % n]); + let len = crate::jsmath::hypot2(c.0 - a.0, c.1 - a.1).max(1e-9); + cross(a, b, c).abs() / len < 1e-6 + }); + match drop { + Some(i) => { + r.remove(i); + } + None => break, + } + } + let ring: Vec<[f64; 2]> = r.iter().map(|q| [q.0, q.1]).collect(); + if !crate::roof_skeleton::is_simple_ring(&ring) { + return None; + } + if crate::roof_skeleton::signed_area(&ring) < 0.0 { + r.reverse(); + } + Some(r) +} + +/// Grund, warum der Körper nicht prismatisch-einfach ist (Code für die Meldung), sonst `None`. +fn shape_problem(sd: &ExtrudedSolid) -> Option<&'static str> { + if sd.operation.as_deref() == Some("subtract") { + return Some("subtract"); + } + if let Some(b) = &sd.brep { + if !prismatic_brep(&b.spec, sd.height) { + return Some("brep"); + } + } + if sd.taper.is_some_and(|t| t.abs() > 1e-9) { + return Some("tapered"); + } + if sd.corner_radius.is_some_and(|r| r > 1e-9) || sd.chamfer.is_some_and(|c| c > 1e-9) { + return Some("rounded"); + } + if !(sd.height.is_finite() && sd.height >= MIN_STORY) { + return Some("height"); + } + None +} + +/// B-Rep-Körper, die doch ein senkrechtes Prisma über `points` sind: Quader (Befehl „Körper“, Form Quader), +/// Zylinder und Extrusion, je ab der Körper-UK und so hoch wie der Körper. Kugel, Kegel, Torus, Rotation, +/// Loft und Verschneidungen nicht. +fn prismatic_brep(spec: &std::collections::BTreeMap, height: f64) -> bool { + let num = |k: &str| spec.get(k).and_then(Value::as_f64); + let z = |k: &str, i: usize| spec.get(k).and_then(|v| v.get(i)).and_then(Value::as_f64); + let near = |a: Option, b: f64| a.is_some_and(|a| (a - b).abs() < 1e-6); + let z0_ok = num("z0").is_none_or(|z0| z0.abs() < 1e-6); + match spec.get("kind").and_then(Value::as_str) { + Some("cuboid") => near(z("min", 2), 0.0) && near(z("max", 2), height), + Some("cylinder") => z0_ok && near(num("height"), height), + Some("extrude") => z0_ok && near(num("height"), height) && !num("cornerRadius").is_some_and(|r| r > 0.0) && !num("chamfer").is_some_and(|c| c > 0.0), + _ => false, + } +} + +/// Geschosse (OKFF, Höhe, id) nach Höhe sortiert; Geschosse ohne Höhe zählen nicht. +fn floor_stack(p: &Project) -> Vec<(f64, f64, &str)> { + let mut f: Vec<(f64, f64, &str)> = p + .drawing_levels + .iter() + .filter(|l| l.kind == DrawingLevelKind::Floor) + .map(|l| (l.base_elevation.filter(|b| b.is_finite()).unwrap_or(0.0), l.floor_height.filter(|h| h.is_finite()).unwrap_or(0.0), l.id.as_str())) + .filter(|f| f.1 > 1e-6) + .collect(); + f.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)); + f +} + +/// Plan der Umwandlung oder der Ablehnungs-Code. +pub fn plan(p: &Project, id: &str, floor_name: &str, ids: &mut IdGen) -> Result { + let sd = p.extruded_solids.as_deref().unwrap_or(&[]).iter().find(|x| x.id == id).ok_or("none")?; + if let Some(code) = shape_problem(sd) { + return Err(code); + } + let outline = clean_outline(&sd.points.iter().map(|q| (q.x, q.y)).collect::>()).ok_or("outline")?; + let level_base = p.floor(&sd.level_id).and_then(|l| l.base_elevation).filter(|b| b.is_finite()).unwrap_or(0.0); + let z0 = level_base + sd.base_offset.filter(|o| o.is_finite()).unwrap_or(0.0); + let z1 = z0 + sd.height; + let stack = floor_stack(p); + let stack_top = stack.iter().map(|f| f.0 + f.1).fold(f64::NEG_INFINITY, f64::max); + let stack_top = if stack_top.is_finite() { stack_top } else { 0.0 }; + + // Bestehende Geschosse ab der Körper-UK, lückenlos aufeinander. + let mut stories: Vec = Vec::new(); + let mut cur = z0; + for &(base, h, fid) in &stack { + if cur >= z1 - TOL { + break; + } + if (base - cur).abs() < TOL { + stories.push(Story { floor: fid.into(), base: cur, top: (base + h).min(z1), floor_top: base + h }); + cur = base + h; + } + } + if stories.is_empty() && (z0 - stack_top).abs() >= TOL { + return Err("base"); + } + let mut new_floors = Vec::new(); + let rest = z1 - cur; + if rest >= TOL { + if rest < MIN_STORY && !stories.is_empty() { + stories.last_mut().unwrap().top = z1; + } else if (cur - stack_top).abs() >= TOL { + // Lücke im Stapel (Geschosse überlappen oder fehlen): nichts raten. + return Err("floors"); + } else { + let h_def = stack.iter().rev().find(|f| (f.0 + f.1 - stack_top).abs() < TOL).map(|f| f.1).filter(|h| *h >= MIN_STORY).unwrap_or(DEF_STORY); + let n = (rest / h_def).round().max(1.0); + if n > MAX_STORIES as f64 { + return Err("height"); + } + let n = n as usize; + let h = um(rest / n as f64); + let count = p.drawing_levels.iter().filter(|l| l.kind == DrawingLevelKind::Floor).count(); + for k in 0..n { + let base = um(cur + h * k as f64); + let fid = ids.next("floor"); + let name = floor_name.replace("{n}", &(count + k + 1).to_string()); + // Das oberste neue Geschoss nimmt den Rundungsrest: der Stapel endet genau auf der Körper-OK. + let height = if k + 1 == n { um(z1 - base) } else { h }; + stories.push(Story { floor: fid.clone(), base, top: if k + 1 == n { z1 } else { base + h }, floor_top: base + height }); + new_floors.push(NewFloor { id: fid, name, base, height }); + } + } + } + if stories.len() > MAX_STORIES { + return Err("height"); + } + Ok(Plan { outline, stories, new_floors }) +} + +fn level_value(f: &NewFloor) -> Value { + obj(vec![ + ("id", s(&f.id)), + ("name", s(&f.name)), + ("kind", s("floor")), + ("visible", Value::Bool(true)), + ("locked", Value::Bool(false)), + ("floorHeight", js_num(f.height)), + ("cutHeight", js_num(1.0)), + ("baseElevation", js_num(f.base)), + ]) +} + +fn floor_name_of(v: &Value) -> &str { + match s_of(v, "floorName") { + "" => "Geschoss {n}", + n => n, + } +} + +/// Ops der Umwandlung: neue Geschosse, Wände, Decken, Dach, Körper weg. Leer bei Ablehnung. +pub fn ops(root: &serde_json::Map, p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let id = s_of(v, "id"); + let Ok(plan) = plan(p, id, floor_name_of(v), ids) else { return Vec::new() }; + let wall_type = active_wall_type_id(p, ctx); + let wall_cat = category_or(p, "20", ctx); + // Wände im Uhrzeigersinn: die linke Seite (+n, Referenz „left“) ist aussen. + let cw: Vec = plan.outline.iter().rev().copied().collect(); + let (mut walls, mut ceilings) = (Vec::new(), Vec::new()); + let last = plan.stories.len() - 1; + for (i, st) in plan.stories.iter().enumerate() { + for k in 0..cw.len() { + let (a, b) = (cw[k], cw[(k + 1) % cw.len()]); + walls.push(obj(vec![ + ("id", s(&ids.next("W"))), + ("type", s("wall")), + ("floorId", s(&st.floor)), + ("categoryCode", wall_cat.clone()), + ("isExternal", Value::Bool(true)), + ("start", pv(a)), + ("end", pv(b)), + ("wallTypeId", wall_type.clone()), + ("height", js_num(um(st.top - st.base))), + ("referenceLine", s("left")), + ])); + } + if i < last { + let mut c = ceiling_item(p, &st.floor, &plan.outline, ctx, ids); + if (st.top - st.floor_top).abs() > 1e-3 { + c["top"] = json!({ "mode": "custom", "z": js_num(st.top) }); + } + ceilings.push(c); + } + } + let top = &plan.stories[last]; + let mut roof = roof_item(p, &top.floor, &plan.outline, "flach", 0.0, ctx, ids); + if (top.top - top.floor_top).abs() > 1e-3 { + roof["baseElevation"] = js_num(top.top); + } + let mut out = crate::cmd_create::add_op("drawingLevels", plan.new_floors.iter().map(level_value).collect()); + out.extend(crate::cmd_create::add_op("walls", walls)); + out.extend(crate::cmd_create::add_op("ceilings", ceilings)); + out.extend(crate::cmd_create::add_op("roofs", vec![roof])); + out.extend(remove_op(root, "extrudedSolids", &[id])); + out +} + +/// Prüfung vor dem Commit (Abfrage `{q: "solidToParts", id}`): `ok`, Ablehnungs-Code `reason` und die Zähler für +/// die Meldung. +pub fn check(p: &Project, v: &Value) -> Value { + let mut ids = IdGen::new("check"); + match plan(p, s_of(v, "id"), floor_name_of(v), &mut ids) { + Ok(pl) => json!({ + "ok": true, + "reason": null, + "stories": pl.stories.len(), + "newFloors": pl.new_floors.len(), + "walls": pl.stories.len() * pl.outline.len(), + "ceilings": pl.stories.len() - 1, + }), + Err(code) => json!({ "ok": false, "reason": code }), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::Map; + + const CTX: &str = r#"{"level":"eg","floorHeight":3,"cat":"90","wallType":"aw"}"#; + + fn root(extra: Value) -> Map { + let mut r = json!({ + "id": "t", "name": "T", + "layers": [{"code": "20", "name": "Wände", "color": "#000"}, {"code": "30", "name": "Decken", "color": "#000"}, {"code": "31", "name": "Dach", "color": "#000"}], + "wallTypes": [{"id": "aw", "name": "Aussenwand", "layers": [{"componentId": "c", "thickness": 0.3}]}], + "ceilingTypes": [{"id": "ct", "name": "Decke", "layers": [{"componentId": "c", "thickness": 0.25}]}], + "drawingLevels": [ + {"id": "eg", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3, "cutHeight": 1, "baseElevation": 0}, + {"id": "og", "name": "OG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3, "cutHeight": 1, "baseElevation": 3} + ], + "walls": [], "ceilings": [], "roofs": [], "extrudedSolids": [] + }); + for (k, v) in extra.as_object().unwrap() { + r[k] = v.clone(); + } + r.as_object().unwrap().clone() + } + + fn solid(pts: Value, h: f64) -> Value { + json!({"id": "K", "type": "extrudedSolid", "levelId": "eg", "categoryCode": "90", "points": pts, "height": h}) + } + + /// Ops anwenden (nur add/remove, wie der Befehl sie liefert). + fn apply(r: &mut Map, ops: &[Op]) { + for op in ops { + match op { + Op::Add { collection, items, .. } => { + let list = r.entry(collection.clone()).or_insert_with(|| json!([])); + list.as_array_mut().unwrap().extend(items.iter().cloned()); + } + Op::Remove { collection, ids } => { + let list = r.get_mut(collection).unwrap().as_array_mut().unwrap(); + list.retain(|e| !ids.iter().any(|i| e["id"] == json!(i))); + } + _ => panic!("unerwartete Op"), + } + } + } + + fn run(r: &Map) -> Vec { + let p = crate::model::lenient::typed_for_test(r); + let req = json!({"cmd": "solidToParts", "id": "K", "floorName": "Geschoss {n}", "ctx": serde_json::from_str::(CTX).unwrap(), "stamp": "s"}); + crate::cmd_create::ops(r, &p, &req).unwrap() + } + + fn check_of(r: &Map) -> Value { + let p = crate::model::lenient::typed_for_test(r); + crate::cmd_create::query(r, &p, &json!({"q": "solidToParts", "id": "K"})).unwrap().unwrap() + } + + /// Rechteck 12 × 10, 9 m hoch auf EG/OG (je 3 m): ein drittes Geschoss entsteht, 3 × 4 Wände, 2 Decken, Flachdach + /// bündig mit der Körper-OK; Wände aussen bündig mit dem Körper, Innenseite nach innen; der Körper entfällt. + #[test] + fn rechteck_drei_geschosse() { + let mut r = root(json!({"extrudedSolids": [solid(json!([{"x": 0, "y": 0}, {"x": 12, "y": 0}, {"x": 12, "y": 10}, {"x": 0, "y": 10}]), 9.0)]})); + let c = check_of(&r); + assert_eq!(c, json!({"ok": true, "reason": null, "stories": 3, "newFloors": 1, "walls": 12, "ceilings": 2})); + let o = run(&r); + apply(&mut r, &o); + let p = crate::model::lenient::typed_for_test(&r); + assert!(p.extruded_solids.as_deref().unwrap_or(&[]).is_empty(), "Körper entfällt"); + let new = p.drawing_levels.iter().find(|l| l.id.starts_with("floor-")).unwrap(); + assert_eq!((new.name.as_str(), new.base_elevation, new.floor_height), ("Geschoss 3", Some(6.0), Some(3.0))); + assert_eq!(p.walls.len(), 12); + for w in &p.walls { + assert_eq!(w.wall_type_id, "aw"); + assert_eq!(w.category_code, "20"); + assert_eq!(w.is_external, Some(true)); + assert_eq!(p.wall_vertical_extent(w).1 - p.wall_vertical_extent(w).0, 3.0); + // Aussenfläche auf der Körperkante: Achse auf dem Umriss, linke Normale zeigt nach aussen. + let (dx, dy) = (w.end.x - w.start.x, w.end.y - w.start.y); + let m = ((w.start.x + w.end.x) / 2.0 - dy * 0.01, (w.start.y + w.end.y) / 2.0 + dx * 0.01); + assert!(m.0 < 0.0 || m.0 > 12.0 || m.1 < 0.0 || m.1 > 10.0, "links = aussen: {w:?}"); + } + let floors: Vec<&str> = p.walls.iter().map(|w| w.floor_id.as_str()).collect(); + assert_eq!(floors.iter().filter(|f| **f == "eg").count(), 4); + assert_eq!(floors.iter().filter(|f| **f == "og").count(), 4); + // Decken: EG und OG (OK = Geschoss-OK), mit Deckentyp; das oberste Geschoss bekommt das Dach. + assert_eq!(p.ceilings.as_deref().unwrap().len(), 2); + let ce: Vec<(f64, f64)> = p.ceilings.as_deref().unwrap().iter().map(|c| p.ceiling_vertical_extent(c)).collect(); + assert_eq!(ce, vec![(2.75, 3.0), (5.75, 6.0)]); + assert_eq!(p.ceilings.as_deref().unwrap()[0].ceiling_type_id.as_deref(), Some("ct")); + let roofs = p.roofs.as_deref().unwrap(); + assert_eq!(roofs.len(), 1); + assert_eq!(roofs[0].floor_id, new.id); + assert_eq!(p.roof_base_elevation(&roofs[0]), 9.0); + assert_eq!(roofs[0].shape, crate::model::RoofShape::Flach); + assert_eq!(roofs[0].overhang, 0.0); + assert!(crate::ops::validate_project(&r).is_empty()); + } + + /// L-förmig (konkav, 6 Ecken, Punkte im Uhrzeigersinn und mit kollinearem Zwischenpunkt): 6 Wände je Geschoss. + #[test] + fn l_form_konkav() { + let pts = json!([{"x": 0, "y": 0}, {"x": 0, "y": 8}, {"x": 4, "y": 8}, {"x": 4, "y": 4}, {"x": 10, "y": 4}, {"x": 10, "y": 0}, {"x": 5, "y": 0}]); + let mut r = root(json!({"extrudedSolids": [solid(pts, 6.0)]})); + let o = run(&r); + apply(&mut r, &o); + let p = crate::model::lenient::typed_for_test(&r); + assert_eq!(p.walls.len(), 12, "zwei Geschosse × 6 Kanten, kein neues Geschoss"); + assert_eq!(p.drawing_levels.len(), 2); + // Jede Wand: linke Seite aussen (Punkt knapp links der Mitte liegt nicht im L). + let inside = |x: f64, y: f64| (0.0..=10.0).contains(&x) && (0.0..=4.0).contains(&y) || (0.0..=4.0).contains(&x) && (0.0..=8.0).contains(&y); + for w in &p.walls { + let (dx, dy) = (w.end.x - w.start.x, w.end.y - w.start.y); + let l = (dx * dx + dy * dy).sqrt(); + let (mx, my) = ((w.start.x + w.end.x) / 2.0, (w.start.y + w.end.y) / 2.0); + assert!(!inside(mx - dy / l * 0.05, my + dx / l * 0.05), "links aussen: {w:?}"); + assert!(inside(mx + dy / l * 0.05, my - dx / l * 0.05), "rechts innen: {w:?}"); + } + assert_eq!(p.ceilings.as_deref().unwrap().len(), 1); + assert_eq!(p.roof_base_elevation(&p.roofs.as_deref().unwrap()[0]), 6.0); + } + + /// Körper niedriger als die Geschosse und kleine Reste: Wände bis zur Körper-OK, Dach mit eigener Traufhöhe; + /// ein Rest unter 0.5 m verlängert das oberste Geschoss statt eines neuen. + #[test] + fn hoehen_die_nicht_aufgehen() { + let rect = json!([{"x": 0, "y": 0}, {"x": 5, "y": 0}, {"x": 5, "y": 5}, {"x": 0, "y": 5}]); + let mut r = root(json!({"extrudedSolids": [solid(rect.clone(), 4.5)]})); + let o = run(&r); + apply(&mut r, &o); + let p = crate::model::lenient::typed_for_test(&r); + let og: Vec<_> = p.walls.iter().filter(|w| w.floor_id == "og").collect(); + assert_eq!(og[0].height, 1.5); + assert_eq!(p.roof_base_elevation(&p.roofs.as_deref().unwrap()[0]), 4.5); + let mut r = root(json!({"extrudedSolids": [solid(rect.clone(), 6.3)]})); + let o = run(&r); + apply(&mut r, &o); + let p = crate::model::lenient::typed_for_test(&r); + assert_eq!(p.drawing_levels.len(), 2, "Rest 0.3 m: kein neues Geschoss"); + assert!((p.walls.iter().find(|w| w.floor_id == "og").unwrap().height - 3.3).abs() < 1e-9); + // 10 m auf 6 m Stapel: Rest 4 m → ein neues Geschoss à 4 m (round(4/3) = 1). + let r = root(json!({"extrudedSolids": [solid(rect.clone(), 10.0)]})); + assert_eq!(check_of(&r)["newFloors"], 1); + // Geschosse à 2.6 m, Körper 7.8 m: das neue Geschoss hat genau 2.6 m (kein Gleitkomma-Rest 2.5999…). + let mut r = root(json!({"extrudedSolids": [solid(rect, 7.8)]})); + r["drawingLevels"][0]["floorHeight"] = json!(2.6); + r["drawingLevels"][1]["floorHeight"] = json!(2.6); + r["drawingLevels"][1]["baseElevation"] = json!(2.6); + let o = run(&r); + apply(&mut r, &o); + assert_eq!(r["drawingLevels"][2]["floorHeight"], json!(2.6)); + assert_eq!(r["drawingLevels"][2]["baseElevation"], json!(5.2)); + } + + /// Ohne Geschosse: der Stapel beginnt bei ±0, die Höhe wird gleichmässig auf Geschosse à ~3 m verteilt. + #[test] + fn ohne_geschosse() { + let rect = json!([{"x": 0, "y": 0}, {"x": 5, "y": 0}, {"x": 5, "y": 5}, {"x": 0, "y": 5}]); + let mut r = root(json!({"drawingLevels": [{"id": "z", "name": "Zeichnung", "kind": "drawing", "visible": true, "locked": false}], "extrudedSolids": [solid(rect, 10.0)]})); + r["extrudedSolids"][0]["levelId"] = json!("z"); + let o = run(&r); + apply(&mut r, &o); + let p = crate::model::lenient::typed_for_test(&r); + let f: Vec<(f64, f64)> = p.drawing_levels.iter().filter(|l| l.kind == DrawingLevelKind::Floor).map(|l| (l.base_elevation.unwrap(), l.floor_height.unwrap())).collect(); + assert_eq!(f.len(), 3); + assert!((f[2].0 + f[2].1 - 10.0).abs() < 1e-9); + assert_eq!(p.drawing_levels[1].name, "Geschoss 1"); + } + + /// Abgelehnt: geneigt, B-Rep, verrundet, Abzugskörper, selbstschneidend, UK zwischen Geschossen, zu niedrig, + /// unbekannte id. Keine Ops. + #[test] + fn ablehnen() { + let rect = json!([{"x": 0, "y": 0}, {"x": 5, "y": 0}, {"x": 5, "y": 5}, {"x": 0, "y": 5}]); + let cases: Vec<(&str, Value, &str)> = vec![ + ("taper", json!(0.5), "tapered"), + ("brep", json!({"spec": {"kind": "sphere"}, "origin": {"x": 0, "y": 0}}), "brep"), + ("cornerRadius", json!(0.5), "rounded"), + ("operation", json!("subtract"), "subtract"), + ("baseOffset", json!(1.2), "base"), + ("height", json!(0.2), "height"), + ("height", json!(5000.0), "height"), + ("points", json!([{"x": 0, "y": 0}, {"x": 5, "y": 5}, {"x": 5, "y": 0}, {"x": 0, "y": 5}]), "outline"), + ("points", json!([{"x": 0, "y": 0}, {"x": 5, "y": 0}, {"x": 10, "y": 0}]), "outline"), + ("id", json!("anders"), "none"), + ]; + for (k, v, code) in cases { + let mut sd = solid(rect.clone(), 6.0); + sd[k] = v; + let r = root(json!({"extrudedSolids": [sd]})); + assert_eq!(check_of(&r), json!({"ok": false, "reason": code}), "{k}"); + assert!(run(&r).is_empty(), "{k}"); + } + // Quader und Zylinder aus dem Befehl „Körper“ sind Prismen und gelten; Kegel nicht. + let mut sd = solid(rect.clone(), 6.0); + sd["brep"] = json!({"spec": {"kind": "cuboid", "min": [0, 0, 0], "max": [5, 5, 6]}, "origin": {"x": 0, "y": 0}, "label": "Quader"}); + assert_eq!(check_of(&root(json!({"extrudedSolids": [sd.clone()]})))["ok"], true); + sd["brep"]["spec"] = json!({"kind": "cylinder", "cx": 2.5, "cy": 2.5, "z0": 0, "r": 2.5, "height": 6}); + assert_eq!(check_of(&root(json!({"extrudedSolids": [sd.clone()]})))["ok"], true); + sd["brep"]["spec"]["kind"] = json!("cone"); + assert_eq!(check_of(&root(json!({"extrudedSolids": [sd]})))["reason"], "brep"); + // Körper auf dem OG (UK 3 m) und auf der Stapel-OK (6 m, versetzt): gültig. + for off in [3.0, 6.0] { + let mut sd = solid(rect.clone(), 3.0); + sd["baseOffset"] = json!(off); + assert_eq!(check_of(&root(json!({"extrudedSolids": [sd]})))["ok"], true, "{off}"); + } + } +} diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index ec2cf390..f46f86ee 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -118,6 +118,7 @@ pub mod commands; pub mod cmd_transform; pub mod cmd_edit; pub mod cmd_create; +pub mod cmd_massing; pub mod cmd_draw; #[cfg(test)] mod cmd_autodim_tests; diff --git a/src/commands/README.md b/src/commands/README.md index 02d1a6e3..d689b9d2 100644 --- a/src/commands/README.md +++ b/src/commands/README.md @@ -29,7 +29,7 @@ Ribbon-Befehle sie erreichen: `src/state/useToolInput.ts`. | Gruppe | Module | |---|---| | Bauteile | `wall.ts`, `opening.ts`, `ceiling.ts`, `ceilingOpening.ts`, `roof.ts`, `roofHole.ts`, `roofWindow.ts`, `dormer.ts`, `stair.ts`, `column.ts`, `room.ts`, `grid.ts`, `tree.ts`, `terrain.ts`, `excavation.ts` | -| Körper | `solid.ts`, `solidbool.ts`, `voidbox.ts`, `extrude.ts`, `revolve.ts`, `loft.ts` | +| Körper | `solid.ts`, `solidbool.ts`, `solidToParts.ts` (Körper → Bauteile, [222]), `voidbox.ts`, `extrude.ts`, `revolve.ts`, `loft.ts` | | 2D zeichnen | `line.ts`, `xline.ts`, `ray.ts`, `polyline.ts`, `polygon.ts`, `rect.ts`, `circle.ts`, `arc.ts`, `ellipse.ts`, `bezier.ts`, `spline.ts`, `multiline.ts`, `revcloud.ts`, `wipeout.ts`, `block.ts`, `defblock.ts` | | Beschriften | `text.ts`, `textbox.ts`, `textpath.ts`, `leader.ts`, `dimension.ts`, `dimround.ts`, `dimdetach.ts`, `autodim.ts`, `kote.ts`, `detailref.ts`, `pointmarker.ts`, `scalebar.ts`, `sectionline.ts` | | Bearbeiten | `transform.ts` (Bewegen, Drehen, Spiegeln), `copy.ts`, `scale.ts`, `array.ts`, `align.ts`, `offset.ts`, `trim.ts`, `extend.ts`, `fillet.ts`, `chamfer.ts`, `cornerHit.ts`, `break.ts`, `split.ts`, `join.ts`, `explode.ts` | diff --git a/src/commands/cmds/solidToParts.test.ts b/src/commands/cmds/solidToParts.test.ts new file mode 100644 index 00000000..1a02663d --- /dev/null +++ b/src/commands/cmds/solidToParts.test.ts @@ -0,0 +1,108 @@ +/** + * [222] „Körper in Bauteile umwandeln": gewählter Körper → Aussenwände je Geschoss, Decken, Flachdach (ein Commit), + * fehlende Geschosse obenauf; Unsinn (verjüngt, UK zwischen Geschossen) mit Meldung abgelehnt; ohne Auswahl Klick. + */ + +import { describe, it, expect } from "vitest"; +import { solidToPartsCommand } from "./solidToParts"; +import { resolveCommand } from "../registry"; +import type { CommandContext, Project } from "../types"; +import type { ExtrudedSolid } from "../../model/types"; + +/** L-förmiger Körper (konkav) 10 × 8 m, Höhe `h`, auf dem EG. */ +const solid = (h: number, extra: Partial = {}): ExtrudedSolid => ({ + id: "K", + type: "extrudedSolid", + levelId: "eg", + categoryCode: "90", + points: [{ x: 0, y: 0 }, { x: 10, y: 0 }, { x: 10, y: 4 }, { x: 4, y: 4 }, { x: 4, y: 8 }, { x: 0, y: 8 }], + height: h, + ...extra, +}); + +function project(s: ExtrudedSolid): Project { + return { + id: "t", + name: "T", + lineStyles: [], + hatches: [], + components: [{ id: "c", name: "Beton", color: "#999999" }] as Project["components"], + wallTypes: [{ id: "aw", name: "Aussenwand", layers: [{ componentId: "c", thickness: 0.3 }] }], + ceilingTypes: [{ id: "ct", name: "Decke", layers: [{ componentId: "c", thickness: 0.25 }] }], + drawingLevels: [{ id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 3, cutHeight: 1.0, baseElevation: 0 }], + layers: [ + { code: "20", name: "Wände", color: "#000000", lw: 0.5, visible: true, locked: false }, + { code: "90", name: "Körper", color: "#000000", lw: 0.25, visible: true, locked: false }, + ], + walls: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + extrudedSolids: [s], + } as Project; +} + +const ctxOf = (p: Project, solidId: string | null): CommandContext => + ({ + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "90", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null, drawingIds: [], extrudedSolidId: solidId }, + }) as CommandContext; + +describe("solidToPartsCommand", () => { + it("Name und Kürzel", () => { + expect(resolveCommand("solidtoparts")?.name).toBe("solidtoparts"); + expect(resolveCommand("koerperinbauteile")?.name).toBe("solidtoparts"); + }); + + it("gewählter Körper 9 m: drei Geschosse (zwei neu), 6 Wände je Geschoss, 2 Decken, Flachdach, Körper weg", () => { + const p = project(solid(9)); + const r = solidToPartsCommand.autoRun!(ctxOf(p, "K")); + expect(r.done).toBe(true); + expect(r.notice).toMatchObject({ key: "cmd.solidtoparts.done", params: { stories: 3, newFloors: 2, walls: 18, ceilings: 2 } }); + const next = r.commit!(p); + expect(next.extrudedSolids ?? []).toHaveLength(0); + const floors = next.drawingLevels.filter((l) => l.kind === "floor"); + expect(floors.map((f) => [f.name, f.baseElevation, f.floorHeight])).toEqual([ + ["EG", 0, 3], + ["Geschoss 2", 3, 3], + ["Geschoss 3", 6, 3], + ]); + expect(next.walls).toHaveLength(18); + expect(next.walls.every((w) => w.wallTypeId === "aw" && w.height === 3 && w.referenceLine === "left" && w.isExternal)).toBe(true); + expect(next.walls.filter((w) => w.floorId === "eg")).toHaveLength(6); + expect((next.ceilings ?? []).map((c) => c.ceilingTypeId)).toEqual(["ct", "ct"]); + expect(next.roofs).toHaveLength(1); + expect(next.roofs![0]).toMatchObject({ shape: "flach", overhang: 0, floorId: floors[2].id }); + }); + + it("lehnt verjüngte Körper und Körper zwischen Geschossen mit Meldung ab (kein Commit)", () => { + const tapered = solidToPartsCommand.autoRun!(ctxOf(project(solid(6, { taper: 0.4 })), "K")); + expect(tapered).toMatchObject({ done: true, notice: { key: "cmd.solidtoparts.reject.tapered", kind: "warning" } }); + expect(tapered.commit).toBeUndefined(); + const floating = solidToPartsCommand.autoRun!(ctxOf(project(solid(6, { baseOffset: 1.3 })), "K")); + expect(floating.notice?.key).toBe("cmd.solidtoparts.reject.base"); + expect(floating.commit).toBeUndefined(); + }); + + it("ohne Auswahl: Klick in den Körper wandelt um, Klick daneben meldet", () => { + const p = project(solid(3)); + const ctx = ctxOf(p, null); + expect(solidToPartsCommand.autoRun!(ctx).done).toBeFalsy(); + const [, miss] = solidToPartsCommand.onInput(solidToPartsCommand.init(), { kind: "point", point: { x: 8, y: 7 } }, ctx); + expect(miss.commit).toBeUndefined(); + expect(miss.notice?.key).toBe("cmd.solidtoparts.noSolid"); + const [, hit] = solidToPartsCommand.onInput(solidToPartsCommand.init(), { kind: "point", point: { x: 1, y: 1 } }, ctx); + const next = hit.commit!(p); + expect(next.walls).toHaveLength(6); + expect(next.ceilings).toHaveLength(0); + expect(next.roofs).toHaveLength(1); + }); +}); diff --git a/src/commands/cmds/solidToParts.ts b/src/commands/cmds/solidToParts.ts new file mode 100644 index 00000000..c54c9edf --- /dev/null +++ b/src/commands/cmds/solidToParts.ts @@ -0,0 +1,67 @@ +// [222] Volumenstudie → Bauteile: ein gewählter Körper (Massenmodell) wird zu Aussenwänden je Geschoss, Decken +// und Flachdach; fehlende Geschosse legt der Kern obenauf an, der Körper entfällt. Ein Undo-Schritt. +// Ist ein Körper gewählt, läuft der Befehl sofort; sonst „Körper wählen“ (Klick in seine Grundfläche). +// Rechnung und Prüfung im Kern (`cmd_massing.rs`); was er nicht abdeckt (geneigt, Kugel/Kegel/Torus, verrundet, Abzugskörper, +// selbstschneidend, UK zwischen Geschossen), lehnt der Befehl mit einer Meldung ab. + +import type { Command, CommandContext, CommandResult, CommandState } from "../types"; +import { createMutation, createQuery, xy } from "../createCore"; +import { t, type TranslationKey } from "../../i18n"; + +/** Ergebnis der Prüfung im Kern (`cmd_massing::check`). */ +export interface SolidToPartsCheck { + ok: boolean; + reason: string | null; + stories?: number; + newFloors?: number; + walls?: number; + ceilings?: number; +} + +/** Namensmuster neuer Geschosse („Geschoss {n}“, der Kern setzt die Nummer ein). */ +const floorName = (): string => t("default.floorName"); + +export function checkSolidToParts(ctx: CommandContext, id: string): SolidToPartsCheck { + return createQuery(ctx.project, { q: "solidToParts", id, floorName: floorName() }); +} + +/** Umwandeln (Commit + Meldung) oder ablehnen (nur Meldung). */ +function convert(ctx: CommandContext, id: string): CommandResult { + const c = checkSolidToParts(ctx, id); + if (!c.ok) { + return { draft: null, done: true, notice: { key: `cmd.solidtoparts.reject.${c.reason ?? "none"}` as TranslationKey, kind: "warning" } }; + } + return { + draft: null, + done: true, + commit: createMutation(ctx, { cmd: "solidToParts", id, floorName: floorName() }), + notice: { key: "cmd.solidtoparts.done", params: { stories: c.stories ?? 0, newFloors: c.newFloors ?? 0, walls: c.walls ?? 0, ceilings: c.ceilings ?? 0 }, kind: "info" }, + }; +} + +const idle = (): CommandState => ({ phase: "pick", lastPoint: null }); + +export const solidToPartsCommand: Command = { + name: "solidtoparts", + labelKey: "cmd.solidtoparts.label", + floorOnly: true, + prompt: () => "cmd.solidtoparts.pick", + accepts: () => ["point"], + options: () => [], + init: idle, + + autoRun: (ctx): CommandResult => { + const id = ctx.selection.extrudedSolidId; + return id ? convert(ctx, id) : { draft: null }; + }, + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + if (input.kind !== "point") return [state, { draft: null }]; + const hit = createQuery<{ hit: string | null }>(ctx.project, { q: "pickSolid", level: ctx.level.id, pt: xy(input.point) }).hit; + if (!hit) return [state, { draft: null, notice: { key: "cmd.solidtoparts.noSolid", kind: "info" } }]; + return [idle(), convert(ctx, hit)]; + }, + onMove: (state): [CommandState, CommandResult] => [state, { draft: null }], + onConfirm: (): [CommandState, CommandResult] => [idle(), { draft: null, done: true }], + onCancel: (): [CommandState, CommandResult] => [idle(), { draft: null, done: true }], +}; diff --git a/src/commands/registry.ts b/src/commands/registry.ts index 3d8113ff..f7a46b91 100644 --- a/src/commands/registry.ts +++ b/src/commands/registry.ts @@ -17,6 +17,7 @@ import { circlesToTreesCommand, treeCommand } from "./cmds/tree"; import { roofCommand } from "./cmds/roof"; import { solidCommand } from "./cmds/solid"; import { solidBoolCommand } from "./cmds/solidbool"; +import { solidToPartsCommand } from "./cmds/solidToParts"; import { voidBoxCommand } from "./cmds/voidbox"; import { ceilingOpeningCommand } from "./cmds/ceilingOpening"; import { roofWindowCommand } from "./cmds/roofWindow"; @@ -93,6 +94,7 @@ export const COMMANDS: Record = { roof: roofCommand, solid: solidCommand, solidbool: solidBoolCommand, + solidtoparts: solidToPartsCommand, voidbox: voidBoxCommand, ceilingopening: ceilingOpeningCommand, roofwindow: roofWindowCommand, @@ -186,6 +188,8 @@ export const ALIASES: Record = { stütze: "column", baum: "tree", kreiseinbaeume: "circlestotrees", + koerperinbauteile: "solidtoparts", + volumenzubauteilen: "solidtoparts", dach: "roof", koerper: "solid", durchbruch: "voidbox", diff --git a/src/i18n/de.ts b/src/i18n/de.ts index f623cff1..b7af6320 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1974,6 +1974,19 @@ export const de = { "cmd.solidbool.op.union": "Vereinigung", "cmd.solidbool.op.difference": "Differenz", "cmd.solidbool.op.intersection": "Durchschnitt", + "cmd.solidtoparts.label": "Körper in Bauteile umwandeln", + "cmd.solidtoparts.pick": "Körper wählen (Massenmodell):", + "cmd.solidtoparts.noSolid": "Hier liegt kein Körper.", + "cmd.solidtoparts.done": "{stories} Geschosse ({newFloors} neu): {walls} Aussenwände, {ceilings} Decken und Flachdach erzeugt.", + "cmd.solidtoparts.reject.none": "Kein Körper gewählt.", + "cmd.solidtoparts.reject.tapered": "Nur senkrechte Körper: verjüngte oder geneigte Körper lassen sich nicht umwandeln.", + "cmd.solidtoparts.reject.brep": "Nur Körper aus Grundriss × Höhe (auch Quader, Zylinder): Kugel, Kegel, Torus, Rotations- und verschnittene Körper lassen sich nicht umwandeln.", + "cmd.solidtoparts.reject.rounded": "Körper mit verrundeten oder gefasten Ecken lassen sich nicht umwandeln.", + "cmd.solidtoparts.reject.subtract": "Abzugskörper lassen sich nicht in Bauteile umwandeln.", + "cmd.solidtoparts.reject.outline": "Der Grundriss des Körpers ist selbstschneidend oder flächenlos.", + "cmd.solidtoparts.reject.height": "Der Körper ist zu niedrig (unter 0.5 m) oder zu hoch für Geschosse.", + "cmd.solidtoparts.reject.base": "Die Unterkante des Körpers liegt nicht auf einem Geschoss (OK fertig Boden).", + "cmd.solidtoparts.reject.floors": "Die Geschosse über dem Körper sind nicht lückenlos gestapelt.", "cmd.void.label": "Durchbruch", "cmd.void.corner": "Erste Ecke des Durchbruchs:", "cmd.void.corner2": "Gegenecke:", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 2ef414fc..cba53589 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1963,6 +1963,19 @@ export const en: Record = { "cmd.solidbool.op.union": "Union", "cmd.solidbool.op.difference": "Difference", "cmd.solidbool.op.intersection": "Intersection", + "cmd.solidtoparts.label": "Convert solid to building parts", + "cmd.solidtoparts.pick": "Select solid (massing model):", + "cmd.solidtoparts.noSolid": "No solid here.", + "cmd.solidtoparts.done": "{stories} floors ({newFloors} new): created {walls} exterior walls, {ceilings} slabs and a flat roof.", + "cmd.solidtoparts.reject.none": "No solid selected.", + "cmd.solidtoparts.reject.tapered": "Vertical solids only: tapered or sloped solids cannot be converted.", + "cmd.solidtoparts.reject.brep": "Only footprint × height solids (including boxes and cylinders): spheres, cones, tori, revolved and boolean solids cannot be converted.", + "cmd.solidtoparts.reject.rounded": "Solids with rounded or chamfered corners cannot be converted.", + "cmd.solidtoparts.reject.subtract": "Subtraction solids cannot be converted to building parts.", + "cmd.solidtoparts.reject.outline": "The solid's footprint is self-intersecting or has no area.", + "cmd.solidtoparts.reject.height": "The solid is too low (under 0.5 m) or too tall for floors.", + "cmd.solidtoparts.reject.base": "The bottom of the solid does not sit on a floor (finished floor level).", + "cmd.solidtoparts.reject.floors": "The floors above the solid are not stacked without gaps.", "cmd.void.label": "Penetration", "cmd.void.corner": "First corner of the penetration:", "cmd.void.corner2": "Opposite corner:", diff --git a/src/panels/ToolsPanel.tsx b/src/panels/ToolsPanel.tsx index 38372caa..81ad2576 100644 --- a/src/panels/ToolsPanel.tsx +++ b/src/panels/ToolsPanel.tsx @@ -379,7 +379,7 @@ const TOOLS_2D: ToolId[] = [ "image", ]; const TOOLS_3D: ToolId[] = ["wall", "ceiling", "window", "door", "stair", "room"]; -const COMMANDS_3D = ["column", "tree", "circlestotrees", "ceilingopening", "roof", "roofhole", "roofwindow", "dormer", "extrude", "revolve", "loft", "solid", "solidbool", "sectionline", "viewline", "autodim", "excavation"]; +const COMMANDS_3D = ["column", "tree", "circlestotrees", "ceilingopening", "roof", "roofhole", "roofwindow", "dormer", "extrude", "revolve", "loft", "solid", "solidbool", "solidtoparts", "sectionline", "viewline", "autodim", "excavation"]; const COMMANDS_EDIT = ["move", "copy", "array", "rotate", "mirror", "offset", "multiline", "trim", "break", "split", "extend", "fillet", "chamfer", "join", "defblock", "measure", "erkennen"]; type ToolsView = "list" | "icons"; diff --git a/src/ui/ribbon/CommandIcon.tsx b/src/ui/ribbon/CommandIcon.tsx index e8f9afd1..14beaa44 100644 --- a/src/ui/ribbon/CommandIcon.tsx +++ b/src/ui/ribbon/CommandIcon.tsx @@ -308,6 +308,14 @@ export const CommandIcon = memo(function CommandIcon({ name }: { name: string }) ); + case "solidtoparts": + // [222] Körper → Bauteile: Quader mit Geschosslinien und Dachplatte. + return ( + + + + + ); case "solid": // Körper: Kugel mit Äquator (B-Rep-Grundkörper). return (