From 9b67e8e491a0b2bd085a3599e4b158decb9805f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 02:07:16 +0000 Subject: [PATCH] [253] Objektbibliothek 2D: parametrische Standard-Symbole mit Palette MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Statt starrer BlockDefs eine neue Drawing2DGeom-Form `libobj` (libId + offene Parameter-Map + seed + Lage). Gründe: Masse, Stuhl-/Modulzahl und Detailgrad (grob/mittel/fein, wie Türen/Fenster über c.a.detail) lassen sich in fester Geometrie nicht speichern; als 2D-Form gelten Klasse, Auswahl, Griffe, Verschieben/Drehen/Spiegeln und Belag-Aussparen ([156]) ohne Sonderweg. - Kern `furniture_lib.rs`: Definition (Id, Gruppe, Klasse, Einfügepunkt, Parameterliste) getrennt von der Erzeugung (Trait LibObject, Register), nur allgemeine Primitive; Platz für spätere eigene Objekte [254] und 3D. 48 Objekte (Sanitär, Küche 55er-Raster, Tische, Sitzen, Betten, Schränke, Auto/Parkfeld/Velo/Wendekreis). Tische: Unordnung per Seed, deterministisch, Stühle schneiden den Tisch nie. Unbekannte Id = Platzhalter-Rahmen. - Klassen Möbel 22, Sanitär 23, Fahrzeuge & Freiflächen 24 (Standards laden; Setzen legt sie im selben Undo-Schritt an). - Palette (Dock-Panel „Objekte“), Befehl libobj (R drehen, M spiegeln), Objekt-Info baut Felder generisch aus der Parameterliste. - Tests: Rust (Katalog, Masse = Bounding-Box, Detailgrad, Seed, Spiegeln, Plan-Ausgabe), vitest (Befehl, Klasse, Plan, Platzhalter). - doc/ARCHITEKTUR.md 3.7, READMEs, TODO.md nachgeführt. --- TODO.md | 13 +- doc/ARCHITEKTUR.md | 20 + src-tauri/core/src/README.md | 1 + src-tauri/core/src/cmd_draw.rs | 25 + src-tauri/core/src/cmd_transform.rs | 24 +- src-tauri/core/src/furniture_lib.rs | 1143 ++++++++++++++++++++ src-tauri/core/src/geo_rebase.rs | 2 +- src-tauri/core/src/geo_translate.rs | 2 +- src-tauri/core/src/grips.rs | 4 +- src-tauri/core/src/lib.rs | 1 + src-tauri/core/src/model/manual.rs | 19 + src-tauri/core/src/plan/drawings.rs | 74 +- src-tauri/core/src/selection_info.rs | 2 +- src-tauri/core/src/standards.rs | 12 +- src-tauri/core/src/web/furniture_lib.rs | 20 + src-tauri/core/src/web/mod.rs | 1 + src/commands/README.md | 2 +- src/commands/cmds/libobj.test.ts | 152 +++ src/commands/cmds/libobj.ts | 98 ++ src/commands/registry.ts | 2 + src/i18n/de.ts | 79 ++ src/i18n/en.ts | 79 ++ src/model/furnitureLib.ts | 145 +++ src/model/types.generated.ts | 12 + src/panels/ObjectInfoPanel.tsx | 4 + src/panels/ObjectLibraryPanel.tsx | 111 ++ src/panels/README.md | 1 + src/panels/builtinPanels.tsx | 11 + src/panels/layout.ts | 5 +- src/panels/objectInfo/LibObjectSection.tsx | 95 ++ 30 files changed, 2142 insertions(+), 17 deletions(-) create mode 100644 src-tauri/core/src/furniture_lib.rs create mode 100644 src-tauri/core/src/web/furniture_lib.rs create mode 100644 src/commands/cmds/libobj.test.ts create mode 100644 src/commands/cmds/libobj.ts create mode 100644 src/model/furnitureLib.ts create mode 100644 src/panels/ObjectLibraryPanel.tsx create mode 100644 src/panels/objectInfo/LibObjectSection.tsx diff --git a/TODO.md b/TODO.md index 1775e729..11f561b1 100644 --- a/TODO.md +++ b/TODO.md @@ -55,7 +55,18 @@ Raumprogramm gegen Modell → Grundrisse/Schnitte/Ansichten 1:200 (Vorprojekt 1: Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC. #- ○ **[252]** Entscheide Maintainer 14.11.: (1) „Geschoss“ heisst im Englischen durchgehend **floor** (en.ts vereinheitlichen, „storey“ ersetzen; Fachbegriffe wie „storey height“ → „floor height“). (2) **Tab bleibt immer für die Befehlszeile** (kein Tab-Durchlauf durch Dock-Knöpfe); **Ctrl+Tab / Ctrl+Umschalt+Tab** springt durch die Reiter (Grundriss/3D/Schnitt …). · S -- ○ **[253]** Standard-Objektbibliothek 2D (14.11., Wunsch Maintainer): Sanitär (WC, Lavabo, Dusche, Wanne, Urinal, WM/Tumbler), Küche (Schweizer Küchennorm 55er-Raster, T 60: Unterbau, Spüle, Kochfeld, GS, Kühlschrank, Hochschrank, Zeile/L/Insel), Tische, Stühle, Sofa, Betten 90–180×200, Schränke T 60/35, Auto+Parkfeld, Velo, Rollstuhl-Wendekreis Ø 150; als `BlockDef`s aus dem Kern erzeugt (abstrakter Strich, 1:100/1:200), Klassen „Möbel“/„Sanitär“, Palette zum Einsetzen. Vorgaben ohne Antwort des Maintainers: abstrakt, nur 55er-Raster, nur 2D (3D nach 1.0). · M +- ◐ **[253]** Standard-Objektbibliothek 2D (14.11., Wunsch Maintainer). Stand 14.11.: parametrische Objekte statt starrer `BlockDef`s — + `Drawing2DGeom::Libobj { libId, at, rotation, params, seed }`; der Kern (`furniture_lib.rs`) erzeugt die Linien zur Plan-Zeit nach Detailgrad + (grob/mittel/fein wie bei Türen/Fenstern), Definition (Parameterliste, Einfügepunkt, Klasse) getrennt von der Erzeugung, Register für + spätere eigene Objekte [254] (`doc/ARCHITEKTUR.md` 3.7). 48 Objekte: Sanitär (WC wand/Kasten, Lavabo, Handwasch, Doppel, Dusche, Wanne, + Urinal, WM/Tumbler), Küche im 55er-Raster (Unterbau, Spüle, Kochfeld, GS, Kühlschrank, Hochschrank, Zeile mit n Modulen, Insel), Tische + (mit/ohne Stühle, Anzahl und „Unordnung“ per Seed, gleicher Seed = gleiche Stühle), Stuhl, Sofa, Sessel, Salontisch, Betten, Nachttisch, Schränke, + Garderobe, Regal, Auto+Parkfeld, Velo, Wendekreis Ø 150 (gestrichelt). Klassen Möbel „22“, Sanitär „23“, Fahrzeuge & Freiflächen „24“ + (Standards laden ergänzt sie, Setzen legt sie im selben Undo-Schritt an); Möbel/Sanitär sparen den Belag aus ([156]). Palette: Dock-Panel + „Objekte“ (Tab neben den Werkzeugen), Befehl `libobj` (R drehen, M spiegeln, Vorschau am Cursor); Objekt-Info baut die Felder generisch aus + der Parameterliste („Neu würfeln“). Unbekannte Id = Platzhalter-Rahmen. Offen: auf dem Mac nicht geprüft; Ziehen aus der Palette (nur Klick); + 3D nach 1.0 (Trait hat Platz für `geometry3d`); Symbole nur im CLI-SVG/Chromium angesehen, nicht in der Tauri-App; DXF gibt die erzeugten Linien lose aus + (kein BLOCK/INSERT). Vorgaben ohne Antwort des Maintainers: abstrakt, nur 55er-Raster, nur 2D. · M ## Phase 1 (13.–19.11.): Stabil und baubar - ◐ **[206]** Referenz-Ablauf als e2e-Spec (Browser) und als Checkliste für die Mac-Abnahme (`doc/RELEASE-1.0.md`): jeder Schritt diff --git a/doc/ARCHITEKTUR.md b/doc/ARCHITEKTUR.md index 9d7b22de..9a1d5daf 100644 --- a/doc/ARCHITEKTUR.md +++ b/doc/ARCHITEKTUR.md @@ -443,6 +443,26 @@ nach dem 3D-Cache: `layers` ist dort keine globale Änderung, Teil-Updates halte Offen: Bauzonen sind kein eigener Planinhalt (nur Baurecht-Einstellungen); „grau" im 3D als Geisterschicht (Klassen und Geschosse, `set_ghost_model`/`set_ghost_lines`, `src/viewport/ghostSync.ts`); Datei-Exporte (OBJ/glTF/IFC/STEP) bleiben vollständig. +### 3.7 Objektbibliothek 2D ([253]) + +Standard-Symbole (Sanitär, Küche im 55er-Raster, Tische mit Stühlen, Sofa, Betten, Schränke, Auto/Velo/Wendekreis) sind +**keine `BlockDef`s**, sondern parametrische Instanzen. Der Grund: Masse, Stuhlzahl, Küchenmodule und der Detailgrad +(grob/mittel/fein, derselbe Mechanismus wie bei Türen und Fenstern: `c.a.detail`, „mittel" ab 1:200 wie „grob") lassen +sich mit starrer Geometrie nicht speichern. Aufbau in `src-tauri/core/src/furniture_lib.rs`: + +| Teil | Inhalt | +|---|---| +| **Definition** `ObjectDef` | Id (`lib:wc-wand`), Gruppe, Klasse (`Cat`: Möbel „22", Sanitär „23", Fahrzeuge & Freiflächen „24"), Einfügepunkt (`Wall` = Wandseite Mitte, `Center`), Parameterliste `ParamDef` (Schlüssel, Art `Length`/`Count`/`Flag`/`Fraction`/`Choice`, Vorgabe, Min, Max, Schritt). Nur Daten. | +| **Erzeugung** `LibObject::geometry` | `(Params, Detail, seed) → Vec`: nur allgemeine Primitive (Linie, Rechteck, Polylinie, Kreis, Bogen, Ellipse), nie objektspezifische Typen. Für eine spätere 3D-Erzeugung hat der Trait Platz für eine zweite Methode (`geometry3d`), heute nicht umgesetzt. | +| **Register** `all()`, `find(id)` | die eingebauten Objekte (`Builtin`) sind die ersten Einträge; eine Benutzerdefinition oder ein Knoten-Graph [254] wäre ein weiterer `LibObject`-Implementierer, ohne Änderung an Modell, Plan oder Objekt-Info. | +| **Instanz im Modell** | `Drawing2DGeom::Libobj { libId, at, rotation, params, seed }` — `params` ist eine offene Map (Name → Zahl/Bool/Text, `mirror` = Spiegeln), keine objektspezifischen Felder. Klasse, Auswahl, Griffe, Verschieben/Drehen/Spiegeln, Belag-Aussparen ([156]) laufen wie bei jeder 2D-Zeichnung. | +| **Plan** | `plan/drawings.rs::emit_inner` (Fall `Libobj`): `furniture_lib::geometry_for(id, params, detail, seed)`, drehen/verschieben, dann wie ein Block rekursiv ausgeben (Klasse, Strichstärke, Overrides, DXF als lose Linien). Unbekannte Id ⇒ `placeholder` (Rahmen mit Diagonalen), nie ein Fehler. | +| **Zufall** | Die Unordnung der Stühle (`mess`, 0–1) nutzt nur `seed` (ganzzahliges SplitMix, plattformgleich); der Seed wird beim Setzen aus der Element-Id gebildet, „Neu würfeln" setzt ihn neu. Nie Zufall zur Plan-Zeit ⇒ Goldens und Export stabil. Stühle werden immer so weit hinausgeschoben, dass sie den Tisch nicht schneiden. | +| **Oberfläche** | Katalog als JSON (`furniture_lib_catalog_json`, Vorschau-Linien `furniture_lib_geometry_json`) → `src/model/furnitureLib.ts`; Dock-Panel „Objekte" (`panels/ObjectLibraryPanel.tsx`), Befehl `libobj` (`commands/cmds/libobj.ts`, R = drehen, M = spiegeln; Kern `cmd_draw.rs::libobj_ops` legt die Klasse im selben Undo-Schritt an, falls sie fehlt), Objekt-Info (`panels/objectInfo/LibObjectSection.tsx`) baut ihre Felder generisch aus der Parameterliste. Namen: i18n `lib.o.`, `lib.g.`, `lib.p.`. | + +Neues eingebautes Objekt: Eintrag in `furniture_lib.rs::build()` (Definition + Zeichenfunktion), Namen in `de.ts`/`en.ts`. +Standards laden ergänzt die Klassen „Möbel", „Sanitär" und „Fahrzeuge & Freiflächen" (`standards.rs::merge_plan`). + --- ## 4. Schnitt diff --git a/src-tauri/core/src/README.md b/src-tauri/core/src/README.md index 935578b7..49389c81 100644 --- a/src-tauri/core/src/README.md +++ b/src-tauri/core/src/README.md @@ -33,6 +33,7 @@ Neues Modul: `.rs` und `mod` in `lib.rs`, Bindungen in `web/.rs` u | `gpu_compile.rs` | GPU-Kompilierung von Plan-Puffern (nativer macOS-Weg) | | `style.rs` | Farben, Schraffur und Schnitt-Linienstil aus dem Modell | | `standards.rs` | Standard-Bibliothek: Baustoffe mit SIA-400-Schraffur und Kennwerten, Linientypen, Standard-Aufbauten | +| `furniture_lib.rs` | Objektbibliothek 2D ([253]): Katalog der Standard-Symbole mit Parametern (Definition) und Zeichenfunktionen nach Detailgrad (Erzeugung), Register, Platzhalter für unbekannte Ids; s. `doc/ARCHITEKTUR.md` 3.7 | | `text_layout.rs`, `rich_text.rs` | Text-Layout (Zeilen, Umbruch) und Bearbeiten von Rich-Text | ## 3D diff --git a/src-tauri/core/src/cmd_draw.rs b/src-tauri/core/src/cmd_draw.rs index 17ac86eb..c4dd56f2 100644 --- a/src-tauri/core/src/cmd_draw.rs +++ b/src-tauri/core/src/cmd_draw.rs @@ -880,6 +880,30 @@ fn block_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { ) } +/// [253] Objekt der Bibliothek setzen: Instanz `{shape: "libobj", libId, at, rotation, params, seed}` auf der Klasse +/// des Objekts (Möbel, Sanitär, Fahrzeuge & Freiflächen); fehlt die Klasse im Projekt, kommt sie im selben Schritt dazu +/// (ein Undo-Schritt). Der Seed folgt aus der Element-Id (gleiche Id = gleiche Stühle). +fn libobj_ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec { + let lib = s_of(v, "lib"); + let Some(def) = crate::furniture_lib::find(lib).map(|o| o.def()) else { return Vec::new() }; + let id = id_or_new(v, ids); + let seed = id.bytes().fold(2166136261u32, |h, b| (h ^ b as u32).wrapping_mul(16777619)); + let mut f = vec![("shape", s("libobj")), ("libId", s(lib)), ("at", pt_val(v, "at")), ("rotation", js_num(n_of(v, "rotation"))), ("seed", js_num(seed as f64))]; + if let Some(m) = v.get("params").filter(|m| m.as_object().is_some_and(|o| !o.is_empty())) { + f.push(("params", m.clone())); + } + let c = Ctx { level: ctx.level, floor_height: ctx.floor_height, cat: def.cat.code(), wall_type: ctx.wall_type, text_height: ctx.text_height, symbol: ctx.symbol }; + let mut ops = add_op("drawings2d", vec![drawing(id, &c, obj(f))]); + let layers = arr(root.get("layers")); + if !crate::standards::has_category(layers, def.cat.code(), &def.cat.name().to_lowercase()) { + let (_, code, name, color, lw) = crate::furniture_lib::CATEGORIES.iter().find(|c| c.0 == def.cat).copied().unwrap_or(crate::furniture_lib::CATEGORIES[0]); + let mut all = layers.to_vec(); + all.push(json!({"code": code, "name": name, "color": color, "lw": lw, "visible": true, "locked": false})); + ops.push(Op::SetField { key: "layers".into(), value: Some(Value::Array(all)), at: None }); + } + ops +} + // ═════════════════════════════════════════════════════════════════════════════ // Bemassung // ═════════════════════════════════════════════════════════════════════════════ @@ -1350,6 +1374,7 @@ pub fn ops(root: &Map, p: &Project, v: &Value, ctx: &Ctx, ids: &m ), "pointmarker" => add_drawing(v, ctx, ids, obj(vec![("shape", s("pointmarker")), ("at", pt_val(v, "at"))])), "block" => block_ops(v, ctx, ids), + "libobj" => libobj_ops(root, v, ctx, ids), "grid" => match grid_geom(v) { Some(g) => add_drawing(v, ctx, ids, g), None => Vec::new(), diff --git a/src-tauri/core/src/cmd_transform.rs b/src-tauri/core/src/cmd_transform.rs index b63b0436..4262bf25 100644 --- a/src-tauri/core/src/cmd_transform.rs +++ b/src-tauri/core/src/cmd_transform.rs @@ -202,13 +202,21 @@ pub fn mv_geom(g: &Value, xf: &Xf) -> Option { } with_opt(g, f) } - "block" => { + "block" | "libobj" => { // Winkel aus einem mit abgebildeten Richtungspunkt: Drehen/Spiegeln nehmen die Ausrichtung mit. let (ax, ay) = xy(field(g, "at").unwrap_or(&Value::Null)); let rot = num_of(field(g, "rotation")); let nb = xf.apply(ax, ay); let nt = xf.apply(ax + jsnum::cos(rot), ay + jsnum::sin(rot)); - with_all(g, vec![("at", pt(nb.0, nb.1)), ("rotation", js_num(jsnum::atan2(nt.1 - nb.1, nt.0 - nb.0)))]) + let mut f = vec![("at", pt(nb.0, nb.1)), ("rotation", js_num(jsnum::atan2(nt.1 - nb.1, nt.0 - nb.0)))]; + // [253] Eine Spiegelung kehrt das Objekt um (Parameter `mirror`). + if shape(g) == "libobj" && xf.reverses() { + let mut params = field(g, "params").and_then(Value::as_object).cloned().unwrap_or_default(); + let on = params.get("mirror").is_some_and(|v| v.as_bool() == Some(true)); + params.insert("mirror".into(), Value::Bool(!on)); + f.push(("params", Value::Object(params))); + } + with_all(g, f) } "image" => { // Nur die Lage folgt (die Box bleibt achsparallel und unverzerrt). @@ -252,6 +260,18 @@ pub fn scale_geom(g: &Value, xf: &Xf, k: f64) -> Option { } "scalebar" => with(&g, "segmentLength", times("segmentLength")), "block" => with(&g, "scale", js_num(num_or(field(&g, "scale"), 1.0) * k)), + "libobj" => { + // [253] Längen-Parameter (Breite, Tiefe) wachsen mit. + let mut params = field(&g, "params").and_then(Value::as_object).cloned().unwrap_or_default(); + let def = field(&g, "libId").and_then(Value::as_str).and_then(crate::furniture_lib::find).map(|o| o.def()); + for key in ["w", "d"] { + let dflt = def.and_then(|d| d.params.iter().find(|q| q.key == key)).map(|q| q.default); + if let Some(x) = params.get(key).and_then(Value::as_f64).or(dflt) { + params.insert(key.into(), js_num(x * k)); + } + } + with(&g, "params", Value::Object(params)) + } _ => g, }) } diff --git a/src-tauri/core/src/furniture_lib.rs b/src-tauri/core/src/furniture_lib.rs new file mode 100644 index 00000000..80cf6bc9 --- /dev/null +++ b/src-tauri/core/src/furniture_lib.rs @@ -0,0 +1,1143 @@ +//! Objektbibliothek 2D ([253]): Standard-Symbole (Sanitär, Küche, Tische, Sitzen, Schlafen, Schränke, Aussenraum), +//! die der Kern zur Plan-Zeit aus Massen erzeugt — nach Detailgrad (grob/mittel/fein) und mit Parametern. +//! +//! Aufbau (so, dass später eigene parametrische Objekte [254] ohne Umbau dazukommen): +//! - **Definition** ([`ObjectDef`]): Id (`lib:wc-wand`), Gruppe, Klasse, Einfügepunkt, Parameterliste ([`ParamDef`]: +//! Schlüssel, Art, Vorgabe, Min, Max, Schritt) — nur Daten, daraus baut die Objekt-Info ihre Felder. +//! - **Erzeugung** ([`LibObject::geometry`]): `(Parameter, Detailgrad, Seed) → Vec`; ausgegeben werden nur +//! allgemeine Primitive (Linie, Rechteck, Polylinie, Kreis, Bogen, Ellipse), nie objektspezifische Typen. Platz für eine +//! spätere 3D-Erzeugung: weitere Methode am Trait (`geometry3d`), heute nicht umgesetzt. +//! - **Register** ([`find`], [`all`]): die eingebauten Objekte sind die ersten Einträge; eine Benutzerdefinition +//! käme als weiterer `LibObject`-Implementierer. +//! - **Instanz im Modell**: `Drawing2DGeom::Libobj { libId, at, rotation, params, seed }` — Parameter als offene Map +//! (Zahl/Bool/Text), keine objektspezifischen Felder. Unbekannte Id ⇒ Platzhalter-Rahmen ([`placeholder`]), kein Fehler. +//! +//! Lokale Geometrie in Metern, +y = Blickrichtung des Objekts (Rückseite/Wand bei y = 0 bei Einfügepunkt „Wandseite +//! Mitte“, sonst Mittelpunkt). Spiegeln (Parameter `mirror`) spiegelt an der y-Achse. + +use crate::model::{Drawing2DGeom as G, Vec2}; +use crate::plan::style::Detail; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::f64::consts::{FRAC_PI_2, PI, TAU}; +use std::sync::OnceLock; + +use crate::jsnum::{atan2, cos, sin}; + +/// Küchenraster (Schweizer Küchennorm): Modulbreite in m. +pub const KITCHEN_MODULE: f64 = 0.55; + +// ── Definition ─────────────────────────────────────────────────────────────── + +/// Art eines Parameters (allgemein gehalten: Zahl mit Einheit, Ganzzahl, Bool, Auswahl). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum ParamKind { + /// Länge in Metern. + Length, + /// Ganzzahl. + Count, + /// Ja/Nein (0/1). + Flag, + /// Zahl 0..1 ohne Einheit. + Fraction, + /// Auswahl aus ganzzahligen Werten `min..=max` (Beschriftung je Wert übersetzt die Oberfläche). + Choice, +} + +impl ParamKind { + pub fn name(self) -> &'static str { + match self { + ParamKind::Length => "length", + ParamKind::Count => "count", + ParamKind::Flag => "flag", + ParamKind::Fraction => "fraction", + ParamKind::Choice => "choice", + } + } +} + +/// Ein Parameter eines Objekts. +#[derive(Clone, Debug)] +pub struct ParamDef { + pub key: &'static str, + pub kind: ParamKind, + pub default: f64, + pub min: f64, + pub max: f64, + pub step: f64, +} + +/// Einfügepunkt (lokaler Ursprung). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Anchor { + /// Wandseite, Mitte (Sanitär, Küche, Schränke, Betten, Sofa): an die Wand setzen. + Wall, + /// Mittelpunkt (Tische, Stühle, Fahrzeuge). + Center, +} + +/// Klasse (Grafik-Kategorie) eines Objekts: Möbel, Sanitär, Fahrzeuge & Freiflächen. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Cat { + Furniture, + Sanitary, + Outdoor, +} + +/// Klassen der Bibliothek: Schlüssel, Code, Name, Farbe, Strichstärke (Papier-mm; fein). +pub const CATEGORIES: [(Cat, &str, &str, &str, f64); 3] = [ + (Cat::Furniture, "22", "Möbel", "#4a4a4a", 0.13), + (Cat::Sanitary, "23", "Sanitär", "#4a4a4a", 0.13), + (Cat::Outdoor, "24", "Fahrzeuge & Freiflächen", "#4a4a4a", 0.13), +]; + +impl Cat { + pub fn code(self) -> &'static str { + CATEGORIES.iter().find(|c| c.0 == self).map(|c| c.1).unwrap_or("22") + } + pub fn name(self) -> &'static str { + CATEGORIES.iter().find(|c| c.0 == self).map(|c| c.2).unwrap_or("Möbel") + } + pub fn key(self) -> &'static str { + match self { + Cat::Furniture => "furniture", + Cat::Sanitary => "sanitary", + Cat::Outdoor => "outdoor", + } + } +} + +/// Definition eines Objekts (nur Daten). +#[derive(Clone, Debug)] +pub struct ObjectDef { + pub id: &'static str, + pub group: &'static str, + pub cat: Cat, + pub anchor: Anchor, + pub params: Vec, + /// Das Objekt nutzt den Seed (Unordnung der Stühle). + pub seeded: bool, + /// Rund: Tiefe = Breite (Durchmesser). + pub round: bool, + /// Breite = `n` × Küchenmodul (55 cm). + pub modular: bool, +} + +/// Parameter eines Objekts, aufgelöst (Vorgabe, Grenzen), dazu die abgeleiteten Masse `w`/`d`. +#[derive(Clone, Debug)] +pub struct Params { + vals: BTreeMap, + pub w: f64, + pub d: f64, +} + +impl Params { + /// Wert von `key` (0 für unbekannte Schlüssel). + pub fn get(&self, key: &str) -> f64 { + self.vals.get(key).copied().unwrap_or(0.0) + } + pub fn flag(&self, key: &str) -> bool { + self.get(key) >= 0.5 + } + pub fn count(&self, key: &str) -> usize { + jsround(self.get(key)).max(0.0) as usize + } +} + +fn jsround(x: f64) -> f64 { + (x + 0.5).floor() +} + +/// Ein Objekt der Bibliothek: Definition + Erzeugung. Eigene Objekte [254] implementieren dasselbe. +pub trait LibObject: Send + Sync { + fn def(&self) -> &ObjectDef; + /// 2D-Geometrie in lokalen Koordinaten (Einfügepunkt = Ursprung), ohne Spiegelung. + fn geometry(&self, p: &Params, detail: Detail, seed: u32) -> Vec; + // Später (3D nach 1.0): `fn geometry3d(&self, p: &Params) -> Option`. +} + +struct Builtin { + def: ObjectDef, + gen: fn(&Params, Detail, u32, &mut Sh), +} + +impl LibObject for Builtin { + fn def(&self) -> &ObjectDef { + &self.def + } + fn geometry(&self, p: &Params, detail: Detail, seed: u32) -> Vec { + let (ox, oy) = match self.def.anchor { + Anchor::Wall => (-p.w / 2.0, 0.0), + Anchor::Center => (-p.w / 2.0, -p.d / 2.0), + }; + let mut sh = Sh { out: Vec::new(), ox, oy }; + (self.gen)(p, detail, seed, &mut sh); + sh.out + } +} + +impl ObjectDef { + /// Parameter auflösen: fehlende/ungültige Werte (NaN, falscher Typ) ⇒ Vorgabe, sonst in die Grenzen geklemmt. + pub fn resolve(&self, given: &BTreeMap) -> Params { + let mut vals = BTreeMap::new(); + for pd in &self.params { + let raw = match given.get(pd.key) { + Some(Value::Number(n)) => n.as_f64(), + Some(Value::Bool(b)) => Some(if *b { 1.0 } else { 0.0 }), + _ => None, + }; + let mut v = raw.filter(|x| x.is_finite()).unwrap_or(pd.default).clamp(pd.min, pd.max); + if matches!(pd.kind, ParamKind::Count | ParamKind::Choice | ParamKind::Flag) { + v = jsround(v).clamp(pd.min, pd.max); + } + vals.insert(pd.key.to_string(), v); + } + let mut p = Params { vals, w: 0.0, d: 0.0 }; + p.w = if self.modular { p.get("n") * KITCHEN_MODULE } else { p.get("w") }; + p.d = if self.round { p.w } else { p.get("d") }; + p + } +} + +// ── Register ───────────────────────────────────────────────────────────────── + +/// Alle Objekte der Bibliothek, in Palettenreihenfolge. +pub fn all() -> &'static [Box] { + static REG: OnceLock>> = OnceLock::new(); + REG.get_or_init(|| build().into_iter().map(|b| Box::new(b) as Box).collect()) +} + +pub fn find(id: &str) -> Option<&'static dyn LibObject> { + all().iter().find(|o| o.def().id == id).map(|b| b.as_ref()) +} + +/// Parameter, die jedes Objekt zusätzlich kennt: Spiegeln. +const MIRROR: &str = "mirror"; + +/// Platzhalter für eine unbekannte Objekt-Id: Rahmen mit Diagonalen (Breite/Tiefe aus `w`/`d`, sonst 0.5 m). +pub fn placeholder(params: &BTreeMap) -> Vec { + let num = |k: &str| params.get(k).and_then(Value::as_f64).filter(|x| x.is_finite() && *x > 0.0).unwrap_or(0.5).min(50.0); + let (w, d) = (num("w"), num("d")); + let mut sh = Sh { out: Vec::new(), ox: -w / 2.0, oy: -d / 2.0 }; + sh.rect(0.0, 0.0, w, d); + sh.line(0.0, 0.0, w, d); + sh.line(0.0, d, w, 0.0); + sh.out +} + +/// Geometrie einer Instanz: Objekt nach Id (sonst Platzhalter), Parameter, Detailgrad, Spiegeln. Nie ein Fehler. +pub fn geometry_for(lib_id: &str, params: &BTreeMap, detail: Detail, seed: u32) -> Vec { + let Some(o) = find(lib_id) else { return placeholder(params) }; + let p = o.def().resolve(params); + let mut g = o.geometry(&p, detail, seed); + if params.get(MIRROR).is_some_and(|v| v.as_bool() == Some(true) || v.as_f64().is_some_and(|x| x >= 0.5)) { + g = g.iter().map(mirror_x).collect(); + } + g +} + +/// Spiegelung an der y-Achse (x → −x). +fn mirror_x(g: &G) -> G { + let m = |q: &Vec2| Vec2 { x: -q.x, y: q.y }; + match g { + G::Line { a, b } => G::Line { a: m(a), b: m(b) }, + G::Rect { min, max } => G::Rect { min: Vec2 { x: -max.x, y: min.y }, max: Vec2 { x: -min.x, y: max.y } }, + G::Polyline { pts, closed, bulge, holes } => G::Polyline { + pts: pts.iter().map(m).collect(), + closed: *closed, + bulge: bulge.as_ref().map(|b| b.iter().map(|x| -x).collect()), + holes: holes.clone(), + }, + G::Circle { center, r } => G::Circle { center: m(center), r: *r }, + G::Arc { center, r, a0, a1 } => G::Arc { center: m(center), r: *r, a0: PI - a1, a1: PI - a0 }, + G::Ellipse { center, rx, ry, rotation } => G::Ellipse { center: m(center), rx: *rx, ry: *ry, rotation: -rotation }, + other => other.clone(), + } +} + +/// Katalog als JSON (für die Palette und die Objekt-Info): Objekte mit Parameterliste. Namen und Beschriftungen +/// übersetzt die Oberfläche über `lib.o.`, `lib.g.`, `lib.p.`. +pub fn catalog_json() -> Value { + let objs: Vec = all() + .iter() + .map(|o| { + let d = o.def(); + let mut params: Vec = d + .params + .iter() + .map(|p| json!({"key": p.key, "kind": p.kind.name(), "default": p.default, "min": p.min, "max": p.max, "step": p.step})) + .collect(); + params.push(json!({"key": MIRROR, "kind": "flag", "default": 0, "min": 0, "max": 1, "step": 1})); + json!({ + "id": d.id, "group": d.group, "category": d.cat.key(), "categoryCode": d.cat.code(), "categoryName": d.cat.name(), + "anchor": if d.anchor == Anchor::Wall { "wall" } else { "center" }, "seeded": d.seeded, "params": params, + }) + }) + .collect(); + let cats: Vec = CATEGORIES.iter().map(|c| json!({"key": c.0.key(), "code": c.1, "name": c.2, "color": c.3, "lw": c.4})).collect(); + json!({"objects": objs, "categories": cats}) +} + +// ── Zeichenhelfer ──────────────────────────────────────────────────────────── + +/// Sammler: Koordinaten im Kasten (x 0..w, y 0..d), verschoben um den Einfügepunkt. +struct Sh { + out: Vec, + ox: f64, + oy: f64, +} + +impl Sh { + fn p(&self, x: f64, y: f64) -> Vec2 { + Vec2 { x: x + self.ox, y: y + self.oy } + } + fn line(&mut self, x0: f64, y0: f64, x1: f64, y1: f64) { + let (a, b) = (self.p(x0, y0), self.p(x1, y1)); + self.out.push(G::Line { a, b }); + } + fn rect(&mut self, x0: f64, y0: f64, x1: f64, y1: f64) { + let (min, max) = (self.p(x0.min(x1), y0.min(y1)), self.p(x0.max(x1), y0.max(y1))); + self.out.push(G::Rect { min, max }); + } + fn poly(&mut self, pts: &[(f64, f64)], closed: bool) { + let pts = pts.iter().map(|q| self.p(q.0, q.1)).collect(); + self.out.push(G::Polyline { pts, closed, bulge: None, holes: None }); + } + fn circle(&mut self, x: f64, y: f64, r: f64) { + let center = self.p(x, y); + self.out.push(G::Circle { center, r }); + } + fn ellipse(&mut self, x: f64, y: f64, rx: f64, ry: f64) { + let center = self.p(x, y); + self.out.push(G::Ellipse { center, rx, ry, rotation: 0.0 }); + } + /// Rechteck mit gerundeten Ecken (Radius `r`, je 4 Segmente). + fn rrect(&mut self, x0: f64, y0: f64, x1: f64, y1: f64, r: f64) { + let r = r.min((x1 - x0) / 2.0).min((y1 - y0) / 2.0).max(0.0); + if r < 1e-4 { + return self.rect(x0, y0, x1, y1); + } + let mut pts = Vec::new(); + for (cx, cy, a0) in [(x1 - r, y1 - r, 0.0), (x0 + r, y1 - r, FRAC_PI_2), (x0 + r, y0 + r, PI), (x1 - r, y0 + r, PI + FRAC_PI_2)] { + for i in 0..=4 { + let a = a0 + FRAC_PI_2 * i as f64 / 4.0; + pts.push((cx + r * cos(a), cy + r * sin(a))); + } + } + self.poly(&pts, true); + } + /// Gestrichelter Kreis aus Bögen (`n` Striche, halb Strich, halb Lücke). + fn dashed_circle(&mut self, x: f64, y: f64, r: f64, n: usize) { + let center = self.p(x, y); + for i in 0..n { + let a0 = TAU * i as f64 / n as f64; + self.out.push(G::Arc { center, r, a0, a1: a0 + TAU / n as f64 * 0.55 }); + } + } + /// Verdrehtes Rechteck um (cx, cy) um `rot`, Kasten −hw..hw × −hd..hd. + fn rot_rect(&mut self, cx: f64, cy: f64, hw: f64, hd: f64, rot: f64) { + let (c, s) = (cos(rot), sin(rot)); + let pts: Vec<(f64, f64)> = [(-hw, -hd), (hw, -hd), (hw, hd), (-hw, hd)].iter().map(|(x, y)| (cx + x * c - y * s, cy + x * s + y * c)).collect(); + self.poly(&pts, true); + } + fn rot_line(&mut self, cx: f64, cy: f64, rot: f64, a: (f64, f64), b: (f64, f64)) { + let (c, s) = (cos(rot), sin(rot)); + let t = |q: (f64, f64)| (cx + q.0 * c - q.1 * s, cy + q.0 * s + q.1 * c); + let (pa, pb) = (t(a), t(b)); + self.line(pa.0, pa.1, pb.0, pb.1); + } +} + +fn ell_pts(cx: f64, cy: f64, rx: f64, ry: f64, a0: f64, a1: f64, n: usize) -> Vec<(f64, f64)> { + (0..=n).map(|i| { + let a = a0 + (a1 - a0) * i as f64 / n as f64; + (cx + rx * cos(a), cy + ry * sin(a)) + }).collect() +} + +// ── Erzeuger ───────────────────────────────────────────────────────────────── + +fn mid(d: Detail) -> bool { + d != Detail::Grob +} +fn fine(d: Detail) -> bool { + d == Detail::Fein +} + +/// WC: Schüssel mit halbrundem Bug; `cistern` = Tiefe des aufgesetzten Spülkastens (0 = wandhängend). +fn wc(p: &Params, dt: Detail, cistern: f64, sh: &mut Sh) { + let (w, d) = (p.w, p.d); + let top = cistern; + if cistern > 0.0 { + sh.rect(0.0, 0.0, w, cistern); + if fine(dt) { + sh.rect(w / 2.0 - 0.04, 0.03, w / 2.0 + 0.04, 0.07); + } + } + let ry = (d - top) * 0.45; + let mut pts = vec![(0.0, top), (w, top), (w, d - ry)]; + pts.extend(ell_pts(w / 2.0, d - ry, w / 2.0, ry, 0.0, PI, 12)); + sh.poly(&pts, true); + if mid(dt) { + sh.ellipse(w / 2.0, d - ry, w / 2.0 - 0.05, ry - 0.05); + } + if fine(dt) { + sh.line(w * 0.15, top + 0.06, w * 0.85, top + 0.06); + } +} + +/// Becken (Lavabo, Handwaschbecken, Spüle): Umriss + Innenkontur (+ Ablauf, Armatur). +fn basin(sh: &mut Sh, dt: Detail, x0: f64, x1: f64, d: f64, round_in: bool) { + sh.rrect(x0, 0.0, x1, d, 0.06); + if mid(dt) { + let (cx, cy) = ((x0 + x1) / 2.0, d * 0.55); + let (rx, ry) = ((x1 - x0) / 2.0 - 0.05, d * 0.5 - 0.04); + if round_in { + sh.ellipse(cx, cy, rx, ry); + } else { + sh.rrect(cx - rx, cy - ry, cx + rx, cy + ry, 0.05); + } + } + if fine(dt) { + let cx = (x0 + x1) / 2.0; + sh.circle(cx, d * 0.55, 0.02); + sh.circle(cx, 0.045, 0.012); + } +} + +fn lavabo(p: &Params, dt: Detail, sh: &mut Sh) { + basin(sh, dt, 0.0, p.w, p.d, true); +} + +fn double_basin(p: &Params, dt: Detail, sh: &mut Sh) { + sh.rrect(0.0, 0.0, p.w, p.d, 0.05); + for (a, b) in [(0.0, p.w / 2.0), (p.w / 2.0, p.w)] { + if mid(dt) { + sh.ellipse((a + b) / 2.0, p.d * 0.55, (b - a) / 2.0 - 0.07, p.d * 0.5 - 0.05); + } + if fine(dt) { + sh.circle((a + b) / 2.0, p.d * 0.55, 0.02); + } + } +} + +fn shower(p: &Params, dt: Detail, sh: &mut Sh) { + let (w, d) = (p.w, p.d); + sh.rect(0.0, 0.0, w, d); + sh.line(0.0, d, w, 0.0); + if mid(dt) { + sh.circle(w / 2.0, d / 2.0, 0.04); + sh.line(0.0, d - 0.02, w, d - 0.02); + } + if fine(dt) { + sh.rect(0.03, 0.03, w - 0.03, d - 0.03); + } +} + +fn bathtub(p: &Params, dt: Detail, sh: &mut Sh) { + let (w, d) = (p.w, p.d); + sh.rrect(0.0, 0.0, w, d, 0.06); + let m = 0.05; + sh.rrect(m, m, w - m, d - m, (d - 2.0 * m) * 0.45); + if mid(dt) { + sh.circle(0.17, d / 2.0, 0.025); + sh.line(0.09, d / 2.0 - 0.05, 0.09, d / 2.0 + 0.05); + } + if fine(dt) { + sh.circle(w - 0.35, d / 2.0, 0.02); + sh.line(w - 0.25, m + 0.04, w - 0.25, d - m - 0.04); + } +} + +fn urinal(p: &Params, dt: Detail, sh: &mut Sh) { + let (w, d) = (p.w, p.d); + let ry = d * 0.45; + let mut pts = vec![(0.0, 0.0), (w, 0.0), (w, d - ry)]; + pts.extend(ell_pts(w / 2.0, d - ry, w / 2.0, ry, 0.0, PI, 10)); + sh.poly(&pts, true); + if mid(dt) { + sh.ellipse(w / 2.0, d - ry, w / 2.0 - 0.05, ry - 0.05); + } + if fine(dt) { + sh.circle(w / 2.0, d - ry, 0.02); + } +} + +fn washer(p: &Params, dt: Detail, sh: &mut Sh) { + let (w, d) = (p.w, p.d); + sh.rect(0.0, 0.0, w, d); + let r = (w.min(d) * 0.36).max(0.05); + sh.circle(w / 2.0, d / 2.0 + 0.02, r); + if mid(dt) { + sh.circle(w / 2.0, d / 2.0 + 0.02, r * 0.75); + } + if fine(dt) { + sh.line(0.0, d - 0.05, w, d - 0.05); + } +} + +// Küche ---------------------------------------------------------------------- + +#[derive(Clone, Copy, PartialEq)] +enum Mod { + Base, + Sink, + Hob, + Dish, + Fridge, + Tall, +} + +fn kitchen_module(sh: &mut Sh, dt: Detail, m: Mod, x0: f64, x1: f64, d: f64, outline: bool) { + if outline { + sh.rect(x0, 0.0, x1, d); + } + let (cx, w) = ((x0 + x1) / 2.0, x1 - x0); + match m { + Mod::Base => { + if mid(dt) { + sh.line(x0, d - 0.02, x1, d - 0.02); + } + } + Mod::Sink => { + sh.rect(x0 + 0.06, 0.07, x0 + w * 0.65, d - 0.1); + if mid(dt) { + sh.line(x0 + w * 0.65, 0.07, x0 + w * 0.65, d - 0.1); + } + if fine(dt) { + sh.circle(x0 + w * 0.33, (d + 0.07 - 0.1) / 2.0, 0.025); + sh.line(x0 + w * 0.7, 0.2, x0 + w - 0.04, 0.2); + sh.line(x0 + w * 0.7, 0.28, x0 + w - 0.04, 0.28); + } + } + Mod::Hob => { + let r = (w * 0.16).min(0.09); + for (dx, dy) in [(-0.25, 0.3), (0.25, 0.3), (-0.25, 0.72), (0.25, 0.72)] { + sh.circle(cx + dx * w, d * dy, r * if dy > 0.5 { 0.85 } else { 1.0 }); + } + if fine(dt) { + sh.rect(x0 + 0.04, 0.04, x1 - 0.04, d - 0.04); + } + } + Mod::Dish => { + sh.line(x0, 0.0, x1, d); + if mid(dt) { + sh.line(x0, d - 0.04, x1, d - 0.04); + } + } + Mod::Fridge => { + sh.line(x0, 0.0, x1, d); + sh.line(x0, d, x1, 0.0); + if fine(dt) { + sh.line(x0, d * 0.7, x1, d * 0.7); + } + } + Mod::Tall => { + sh.line(x0, 0.0, x1, d); + if mid(dt) { + sh.line(x0, d - 0.02, x1, d - 0.02); + } + } + } +} + +fn kitchen_single(m: Mod) -> impl Fn(&Params, Detail, u32, &mut Sh) { + move |p, dt, _, sh| kitchen_module(sh, dt, m, 0.0, p.w, p.d, true) +} + +fn kitchen_row(p: &Params, dt: Detail, sh: &mut Sh) { + let n = p.count("n").max(1); + sh.rect(0.0, 0.0, p.w, p.d); + let seq = [Mod::Base, Mod::Sink, Mod::Dish, Mod::Base, Mod::Hob]; + for i in 0..n { + let m = seq.get(i).copied().unwrap_or(Mod::Base); + let (x0, x1) = (i as f64 * KITCHEN_MODULE, (i + 1) as f64 * KITCHEN_MODULE); + if i > 0 && mid(dt) { + sh.line(x0, 0.0, x0, p.d); + } + kitchen_module(sh, dt, m, x0, x1, p.d, false); + } +} + +fn kitchen_island(p: &Params, dt: Detail, sh: &mut Sh) { + let (w, d) = (p.w, p.d); + sh.rect(0.0, 0.0, w, d); + sh.line(0.0, d - 0.3, w, d - 0.3); + if mid(dt) { + let r = 0.09; + for (cx, cy) in [(0.3, 0.15), (0.5, 0.15), (0.3, 0.33), (0.5, 0.33)] { + sh.circle(cx, cy, r * 0.8); + } + sh.rect(w - 0.7, 0.1, w - 0.15, d - 0.4); + } + if fine(dt) { + sh.circle(w - 0.42, (d - 0.3) / 2.0 + 0.1, 0.025); + } +} + +// Tische und Stühle ---------------------------------------------------------- + +const CHAIR_W: f64 = 0.45; +const CHAIR_D: f64 = 0.50; +const CHAIR_GAP: f64 = 0.03; + +/// Stuhl, lokal: Rückenlehne bei y = −d/2, Blick +y. +fn chair_at(sh: &mut Sh, dt: Detail, cx: f64, cy: f64, rot: f64) { + let (hw, hd) = (CHAIR_W / 2.0, CHAIR_D / 2.0); + sh.rot_rect(cx, cy, hw, hd, rot); + if mid(dt) { + sh.rot_line(cx, cy, rot, (-hw, -hd + 0.07), (hw, -hd + 0.07)); + } + if fine(dt) { + sh.rot_line(cx, cy, rot, (-hw + 0.03, -hd + 0.07), (-hw + 0.03, hd - 0.04)); + sh.rot_line(cx, cy, rot, (hw - 0.03, -hd + 0.07), (hw - 0.03, hd - 0.04)); + } +} + +fn chair(p: &Params, dt: Detail, sh: &mut Sh) { + sh.rect(0.0, 0.0, p.w, p.d); + if mid(dt) { + sh.line(0.0, 0.07, p.w, 0.07); + } + if fine(dt) { + sh.line(0.03, 0.07, 0.03, p.d - 0.04); + sh.line(p.w - 0.03, 0.07, p.w - 0.03, p.d - 0.04); + } +} + +/// Zufall 0..1 aus Seed und Zähler (SplitMix32-artig, ganzzahlig ⇒ auf allen Plattformen gleich). +fn rnd(seed: u32, i: u32) -> f64 { + let mut z = seed.wrapping_add(i.wrapping_mul(0x9E37_79B9)).wrapping_add(0x7F4A_7C15); + z = (z ^ (z >> 16)).wrapping_mul(0x85EB_CA6B); + z = (z ^ (z >> 13)).wrapping_mul(0xC2B2_AE35); + z ^= z >> 16; + z as f64 / 4_294_967_296.0 +} + +/// Stuhl an einer Tischkante: Mitte der Kante `edge` (Punkt), Aussennormale `nx, ny`, `lat` entlang der Kante, +/// Unordnung `m` (0–1) mit Seed. Rückt so weit hinaus, dass der Stuhl den Tisch nie schneidet. +fn chair_for_edge(sh: &mut Sh, dt: Detail, edge: (f64, f64), n: (f64, f64), tang: (f64, f64), lat: f64, m: f64, seed: u32, idx: u32) { + let (phi, out, side) = if m > 0.0 { + ((rnd(seed, idx * 3) * 2.0 - 1.0) * 12.0_f64.to_radians() * m, rnd(seed, idx * 3 + 1) * 0.08 * m, (rnd(seed, idx * 3 + 2) * 2.0 - 1.0) * 0.02 * m) + } else { + (0.0, 0.0, 0.0) + }; + let rot = atan2(n.0, -n.1) + phi; + // Ausdehnung des verdrehten Stuhls entlang der Normalen. + let ext = CHAIR_D / 2.0 * cos(phi).abs() + CHAIR_W / 2.0 * sin(phi).abs(); + let dist = CHAIR_GAP + ext + out; + let (cx, cy) = (edge.0 + n.0 * dist + tang.0 * (lat + side), edge.1 + n.1 * dist + tang.1 * (lat + side)); + chair_at(sh, dt, cx, cy, rot); +} + +fn rect_table(p: &Params, dt: Detail, seed: u32, sh: &mut Sh) { + let (w, d) = (p.w, p.d); + sh.rect(0.0, 0.0, w, d); + if fine(dt) { + sh.rect(0.04, 0.04, w - 0.04, d - 0.04); + } + let n = p.count("n"); + if n == 0 { + return; + } + let m = p.get("mess"); + let ends = if n >= 6 { 2 } else { 0 }; + let sides = n - ends; + let (bottom, top) = (sides.div_ceil(2), sides / 2); + let mut idx = 0u32; + for (k, y, ny) in [(bottom, 0.0, -1.0), (top, d, 1.0)] { + for i in 0..k { + let x = w * (i as f64 + 0.5) / k as f64; + chair_for_edge(sh, dt, (x, y), (0.0, ny), (1.0, 0.0), 0.0, m, seed, idx); + idx += 1; + } + } + if ends == 2 { + chair_for_edge(sh, dt, (0.0, d / 2.0), (-1.0, 0.0), (0.0, 1.0), 0.0, m, seed, idx); + chair_for_edge(sh, dt, (w, d / 2.0), (1.0, 0.0), (0.0, 1.0), 0.0, m, seed, idx + 1); + } +} + +fn round_table(p: &Params, dt: Detail, seed: u32, sh: &mut Sh) { + let r = p.w / 2.0; + sh.circle(r, r, r); + if fine(dt) { + sh.circle(r, r, r - 0.04); + } + let n = p.count("n"); + let m = p.get("mess"); + for i in 0..n { + let a = FRAC_PI_2 + TAU * i as f64 / n as f64; + let nrm = (cos(a), sin(a)); + chair_for_edge(sh, dt, (r + nrm.0 * r, r + nrm.1 * r), nrm, (-nrm.1, nrm.0), 0.0, m, seed, i as u32); + } +} + +fn office_table(p: &Params, dt: Detail, seed: u32, sh: &mut Sh) { + rect_table(p, dt, seed, sh); + if mid(dt) { + // Kabelkanal-/Plattenlinie + sh.line(0.0, p.d - 0.04, p.w, p.d - 0.04); + } +} + +fn coffee_table(p: &Params, dt: Detail, sh: &mut Sh) { + sh.rrect(0.0, 0.0, p.w, p.d, 0.04); + if fine(dt) { + sh.rrect(0.04, 0.04, p.w - 0.04, p.d - 0.04, 0.02); + } +} + +// Sitzen ---------------------------------------------------------------------- + +fn sofa(p: &Params, dt: Detail, sh: &mut Sh) { + let (w, d) = (p.w, p.d); + sh.rrect(0.0, 0.0, w, d, 0.05); + sh.line(0.0, 0.22, w, 0.22); + if mid(dt) { + sh.line(0.2, 0.22, 0.2, d); + sh.line(w - 0.2, 0.22, w - 0.2, d); + } + if fine(dt) { + let seats = if w > 1.9 { 3 } else { 2 }; + for i in 1..seats { + let x = 0.2 + (w - 0.4) * i as f64 / seats as f64; + sh.line(x, 0.22, x, d - 0.02); + } + } +} + +fn armchair(p: &Params, dt: Detail, sh: &mut Sh) { + let (w, d) = (p.w, p.d); + sh.rrect(0.0, 0.0, w, d, 0.05); + sh.line(0.0, 0.2, w, 0.2); + if mid(dt) { + sh.line(0.17, 0.2, 0.17, d); + sh.line(w - 0.17, 0.2, w - 0.17, d); + } +} + +// Schlafen --------------------------------------------------------------------- + +fn bed(p: &Params, dt: Detail, sh: &mut Sh) { + let (w, d) = (p.w, p.d); + sh.rect(0.0, 0.0, w, d); + // Deckenkante + sh.line(0.0, d * 0.28, w, d * 0.28); + if mid(dt) { + let double = w >= 1.3; + let pw = if double { (w - 0.15) / 2.0 - 0.04 } else { w - 0.2 }; + let xs: Vec = if double { vec![0.075 + 0.02, w / 2.0 + 0.02] } else { vec![0.1] }; + for x in xs { + sh.rect(x, 0.07, x + pw, d.min(0.45) * 0.8); + } + } + if fine(dt) { + sh.line(0.0, 0.04, w, 0.04); + } +} + +fn nightstand(p: &Params, dt: Detail, sh: &mut Sh) { + sh.rect(0.0, 0.0, p.w, p.d); + if mid(dt) { + sh.line(0.0, p.d - 0.02, p.w, p.d - 0.02); + } + if fine(dt) { + sh.circle(p.w / 2.0, p.d / 2.0, 0.03); + } +} + +// Schränke --------------------------------------------------------------------- + +fn cupboard(p: &Params, dt: Detail, sh: &mut Sh) { + sh.rect(0.0, 0.0, p.w, p.d); + sh.line(0.0, 0.0, p.w, p.d); + if mid(dt) { + sh.line(0.0, p.d - 0.02, p.w, p.d - 0.02); + } + if fine(dt) { + let doors = (p.w / 0.5).round().max(1.0) as usize; + for i in 1..doors { + let x = p.w * i as f64 / doors as f64; + sh.line(x, p.d - 0.02, x, p.d); + } + } +} + +fn wardrobe(p: &Params, dt: Detail, sh: &mut Sh) { + sh.rect(0.0, 0.0, p.w, p.d); + sh.line(0.04, p.d / 2.0, p.w - 0.04, p.d / 2.0); + if mid(dt) { + sh.line(0.0, p.d - 0.02, p.w, p.d - 0.02); + } + if fine(dt) { + for i in 1..5 { + let x = 0.04 + (p.w - 0.08) * i as f64 / 5.0; + sh.line(x, p.d / 2.0 - 0.03, x, p.d / 2.0 + 0.03); + } + } +} + +fn shelf(p: &Params, dt: Detail, sh: &mut Sh) { + sh.rect(0.0, 0.0, p.w, p.d); + sh.line(0.0, 0.0, p.w, p.d); + sh.line(0.0, p.d, p.w, 0.0); + if fine(dt) { + sh.line(0.0, p.d - 0.02, p.w, p.d - 0.02); + } +} + +// Aussenraum ------------------------------------------------------------------- + +fn car(p: &Params, dt: Detail, sh: &mut Sh) { + let (w, d) = (p.w, p.d); + // Parkfeld (Mitte, Auto darin zentriert), nur wenn `field` gesetzt. + let (fw, fh) = (2.5_f64.max(w), 5.0_f64.max(d)); + if p.flag("field") { + sh.rect((w - fw) / 2.0, (d - fh) / 2.0, (w + fw) / 2.0, (d + fh) / 2.0); + } + sh.rrect(0.0, 0.0, w, d, 0.25); + // Kabine (Dach) und Frontscheibe als Kennlinien + sh.line(0.06, d * 0.30, w - 0.06, d * 0.30); + sh.line(0.06, d * 0.72, w - 0.06, d * 0.72); + if mid(dt) { + sh.rrect(0.12, d * 0.30, w - 0.12, d * 0.72, 0.1); + } + if fine(dt) { + for (x, y) in [(0.0, 0.7), (w, 0.7), (0.0, d - 1.1), (w, d - 1.1)] { + sh.rect(x - 0.03, y, x + 0.03, y + 0.2); + } + sh.rect(-0.08, d * 0.62, 0.0, d * 0.62 + 0.12); + sh.rect(w, d * 0.62, w + 0.08, d * 0.62 + 0.12); + } +} + +fn parking(p: &Params, _dt: Detail, sh: &mut Sh) { + sh.rect(0.0, 0.0, p.w, p.d); +} + +fn bike(p: &Params, dt: Detail, sh: &mut Sh) { + let (w, d) = (p.w, p.d); + sh.line(w / 2.0, 0.0, w / 2.0, d); + sh.rrect(w / 2.0 - 0.03, 0.0, w / 2.0 + 0.03, 0.65, 0.03); + sh.rrect(w / 2.0 - 0.03, d - 0.65, w / 2.0 + 0.03, d, 0.03); + sh.line(0.0, d - 0.55, w, d - 0.55); + if mid(dt) { + sh.rect(w / 2.0 - 0.05, 0.62, w / 2.0 + 0.05, 0.9); + } + if fine(dt) { + sh.line(w / 2.0 - 0.08, 0.5, w / 2.0 + 0.08, 0.5); + } +} + +fn wheelchair_circle(p: &Params, dt: Detail, sh: &mut Sh) { + let r = p.w / 2.0; + sh.dashed_circle(r, r, r, 24); + if mid(dt) { + sh.line(r - 0.1, r, r + 0.1, r); + sh.line(r, r - 0.1, r, r + 0.1); + } +} + +// ── Katalog ────────────────────────────────────────────────────────────────── + +fn len(key: &'static str, default: f64, min: f64, max: f64) -> ParamDef { + ParamDef { key, kind: ParamKind::Length, default, min, max, step: 0.05 } +} +fn count(key: &'static str, default: f64, min: f64, max: f64) -> ParamDef { + ParamDef { key, kind: ParamKind::Count, default, min, max, step: 1.0 } +} +fn flag(key: &'static str, default: f64) -> ParamDef { + ParamDef { key, kind: ParamKind::Flag, default, min: 0.0, max: 1.0, step: 1.0 } +} +fn frac(key: &'static str, default: f64) -> ParamDef { + ParamDef { key, kind: ParamKind::Fraction, default, min: 0.0, max: 1.0, step: 0.05 } +} + +fn wd(w: f64, d: f64) -> Vec { + vec![len("w", w, 0.1, 6.0), len("d", d, 0.1, 6.0)] +} + +fn ent(id: &'static str, group: &'static str, cat: Cat, anchor: Anchor, params: Vec, gen: fn(&Params, Detail, u32, &mut Sh)) -> Builtin { + Builtin { def: ObjectDef { id, group, cat, anchor, params, seeded: false, round: false, modular: false }, gen } +} + +fn build() -> Vec { + use Anchor::{Center, Wall}; + use Cat::{Furniture as F, Outdoor as O, Sanitary as S}; + let mut v: Vec = Vec::new(); + let tbl = |id: &'static str, w: f64, d: f64, n: f64, gen: fn(&Params, Detail, u32, &mut Sh), round: bool| { + let mut params = if round { vec![len("w", w, 0.4, 3.0)] } else { wd(w, d) }; + params.push(count("n", n, 0.0, 12.0)); + params.push(frac("mess", 0.0)); + let mut b = ent(id, "tables", F, Center, params, gen); + b.def.seeded = true; + b.def.round = round; + b + }; + let tables = vec![ + tbl("lib:tisch-80x140", 1.4, 0.8, 6.0, rect_table, false), + tbl("lib:tisch-80x140-leer", 1.4, 0.8, 0.0, rect_table, false), + tbl("lib:tisch-90x180", 1.8, 0.9, 8.0, rect_table, false), + tbl("lib:tisch-90x180-leer", 1.8, 0.9, 0.0, rect_table, false), + tbl("lib:tisch-rund-100", 1.0, 1.0, 4.0, round_table, true), + tbl("lib:tisch-rund-100-leer", 1.0, 1.0, 0.0, round_table, true), + tbl("lib:tisch-rund-120", 1.2, 1.2, 5.0, round_table, true), + tbl("lib:tisch-rund-120-leer", 1.2, 1.2, 0.0, round_table, true), + tbl("lib:tisch-buero", 1.6, 0.8, 1.0, office_table, false), + ]; + + // Sanitär + v.push(ent("lib:wc-wand", "sanitary", S, Wall, wd(0.38, 0.55), |p, dt, _, sh| wc(p, dt, 0.0, sh))); + v.push(ent("lib:wc-kasten", "sanitary", S, Wall, wd(0.40, 0.70), |p, dt, _, sh| wc(p, dt, 0.2, sh))); + v.push(ent("lib:lavabo", "sanitary", S, Wall, wd(0.60, 0.45), |p, dt, _, sh| lavabo(p, dt, sh))); + v.push(ent("lib:handwaschbecken", "sanitary", S, Wall, wd(0.45, 0.32), |p, dt, _, sh| lavabo(p, dt, sh))); + v.push(ent("lib:doppellavabo", "sanitary", S, Wall, wd(1.20, 0.50), |p, dt, _, sh| double_basin(p, dt, sh))); + v.push(ent("lib:dusche-90", "sanitary", S, Wall, wd(0.90, 0.90), |p, dt, _, sh| shower(p, dt, sh))); + v.push(ent("lib:dusche-80x120", "sanitary", S, Wall, wd(1.20, 0.80), |p, dt, _, sh| shower(p, dt, sh))); + v.push(ent("lib:wanne-170", "sanitary", S, Wall, wd(1.70, 0.75), |p, dt, _, sh| bathtub(p, dt, sh))); + v.push(ent("lib:wanne-180", "sanitary", S, Wall, wd(1.80, 0.80), |p, dt, _, sh| bathtub(p, dt, sh))); + v.push(ent("lib:urinal", "sanitary", S, Wall, wd(0.35, 0.35), |p, dt, _, sh| urinal(p, dt, sh))); + v.push(ent("lib:waschmaschine", "sanitary", S, Wall, wd(0.60, 0.60), |p, dt, _, sh| washer(p, dt, sh))); + + // Küche (55er-Raster, Tiefe 60) + v.push(ent("lib:kueche-unterbau", "kitchen", F, Wall, wd(0.55, 0.60), |p, dt, s, sh| kitchen_single(Mod::Base)(p, dt, s, sh))); + v.push(ent("lib:kueche-spuele", "kitchen", F, Wall, wd(0.55, 0.60), |p, dt, s, sh| kitchen_single(Mod::Sink)(p, dt, s, sh))); + v.push(ent("lib:kueche-kochfeld", "kitchen", F, Wall, wd(0.55, 0.60), |p, dt, s, sh| kitchen_single(Mod::Hob)(p, dt, s, sh))); + v.push(ent("lib:kueche-geschirrspueler", "kitchen", F, Wall, wd(0.55, 0.60), |p, dt, s, sh| kitchen_single(Mod::Dish)(p, dt, s, sh))); + v.push(ent("lib:kueche-kuehlschrank", "kitchen", F, Wall, wd(0.55, 0.60), |p, dt, s, sh| kitchen_single(Mod::Fridge)(p, dt, s, sh))); + v.push(ent("lib:kueche-hochschrank", "kitchen", F, Wall, wd(0.55, 0.60), |p, dt, s, sh| kitchen_single(Mod::Tall)(p, dt, s, sh))); + let mut row = ent("lib:kueche-zeile", "kitchen", F, Wall, vec![count("n", 5.0, 1.0, 12.0), len("d", 0.60, 0.3, 1.2)], |p, dt, _, sh| kitchen_row(p, dt, sh)); + row.def.modular = true; + v.push(row); + v.push(ent("lib:kueche-insel", "kitchen", F, Center, wd(1.65, 0.90), |p, dt, _, sh| kitchen_island(p, dt, sh))); + + // Tische + v.extend(tables); + + // Sitzen + v.push(ent("lib:stuhl", "seating", F, Center, wd(0.45, 0.50), |p, dt, _, sh| chair(p, dt, sh))); + v.push(ent("lib:sofa-2", "seating", F, Wall, wd(1.60, 0.90), |p, dt, _, sh| sofa(p, dt, sh))); + v.push(ent("lib:sofa-3", "seating", F, Wall, wd(2.10, 0.90), |p, dt, _, sh| sofa(p, dt, sh))); + v.push(ent("lib:sessel", "seating", F, Wall, wd(0.80, 0.80), |p, dt, _, sh| armchair(p, dt, sh))); + v.push(ent("lib:salontisch", "seating", F, Center, wd(1.00, 0.60), |p, dt, _, sh| coffee_table(p, dt, sh))); + + // Schlafen + for (id, w, d) in [("lib:bett-90", 0.9, 2.0), ("lib:bett-140", 1.4, 2.0), ("lib:bett-160", 1.6, 2.0), ("lib:bett-180", 1.8, 2.0), ("lib:kinderbett", 0.7, 1.4)] { + v.push(ent(id, "sleeping", F, Wall, wd(w, d), |p, dt, _, sh| bed(p, dt, sh))); + } + v.push(ent("lib:nachttisch", "sleeping", F, Wall, wd(0.40, 0.40), |p, dt, _, sh| nightstand(p, dt, sh))); + + // Schränke + for (id, w) in [("lib:schrank-50", 0.5), ("lib:schrank-60", 0.6), ("lib:schrank-100", 1.0)] { + v.push(ent(id, "cupboards", F, Wall, wd(w, 0.60), |p, dt, _, sh| cupboard(p, dt, sh))); + } + v.push(ent("lib:garderobe", "cupboards", F, Wall, wd(1.00, 0.35), |p, dt, _, sh| wardrobe(p, dt, sh))); + v.push(ent("lib:regal", "cupboards", F, Wall, wd(1.00, 0.35), |p, dt, _, sh| shelf(p, dt, sh))); + + // Aussenraum + let mut car_params = wd(1.80, 4.70); + car_params.push(flag("field", 1.0)); + v.push(ent("lib:auto", "outdoor", O, Center, car_params, |p, dt, _, sh| car(p, dt, sh))); + v.push(ent("lib:parkfeld", "outdoor", O, Center, wd(2.50, 5.00), |p, dt, _, sh| parking(p, dt, sh))); + v.push(ent("lib:velo", "outdoor", O, Center, wd(0.60, 1.80), |p, dt, _, sh| bike(p, dt, sh))); + let mut wc_circle = ent("lib:wendekreis", "outdoor", O, Center, vec![len("w", 1.5, 0.5, 3.0)], |p, dt, _, sh| wheelchair_circle(p, dt, sh)); + wc_circle.def.round = true; + v.push(wc_circle); + v +} + +// ── Tests ──────────────────────────────────────────────────────────────────── + +#[cfg(test)] +mod tests { + use super::*; + + fn bbox(g: &[G]) -> (f64, f64, f64, f64) { + let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + let mut acc = |q: &Vec2| { + x0 = x0.min(q.x); + y0 = y0.min(q.y); + x1 = x1.max(q.x); + y1 = y1.max(q.y); + }; + for s in g { + match s { + G::Line { a, b } => { + acc(a); + acc(b); + } + G::Rect { min, max } => { + acc(min); + acc(max); + } + G::Polyline { pts, .. } => pts.iter().for_each(&mut acc), + G::Circle { center, r } => { + acc(&Vec2 { x: center.x - r, y: center.y - r }); + acc(&Vec2 { x: center.x + r, y: center.y + r }); + } + G::Arc { center, r, .. } => { + acc(&Vec2 { x: center.x - r, y: center.y - r }); + acc(&Vec2 { x: center.x + r, y: center.y + r }); + } + G::Ellipse { center, rx, ry, .. } => { + acc(&Vec2 { x: center.x - rx, y: center.y - ry }); + acc(&Vec2 { x: center.x + rx, y: center.y + ry }); + } + _ => panic!("unerwartete Form"), + } + } + (x0, y0, x1, y1) + } + + fn finite(g: &[G]) -> bool { + bbox(g).0.is_finite() && bbox(g).3.is_finite() + } + + const DETAILS: [Detail; 3] = [Detail::Grob, Detail::Mittel, Detail::Fein]; + + #[test] + fn every_object_has_geometry_at_every_detail() { + assert!(all().len() >= 48, "{}", all().len()); + let mut ids = std::collections::HashSet::new(); + for o in all() { + let d = o.def(); + assert!(d.id.starts_with("lib:") && ids.insert(d.id), "{}", d.id); + for dt in DETAILS { + let g = geometry_for(d.id, &BTreeMap::new(), dt, 1); + assert!(!g.is_empty() && finite(&g), "{} {dt:?}", d.id); + } + } + } + + #[test] + fn detail_adds_lines_never_removes() { + for o in all() { + let c = |dt| geometry_for(o.def().id, &BTreeMap::new(), dt, 1).len(); + assert!(c(Detail::Grob) <= c(Detail::Mittel) && c(Detail::Mittel) <= c(Detail::Fein), "{}", o.def().id); + } + } + + #[test] + fn dimensions_match_bounding_box() { + for o in all() { + let d = o.def(); + // Objekte ohne Zusatzgeometrie über das Mass hinaus (Stühle, Parkfeld, Spiegel, Scheinwerfer). + if d.id.contains("tisch-") && !d.id.ends_with("-leer") && d.id != "lib:tisch-buero" || d.id == "lib:tisch-buero" { + continue; + } + let g = geometry_for(d.id, &BTreeMap::new(), Detail::Mittel, 1); + let p = d.resolve(&BTreeMap::new()); + let (x0, y0, x1, y1) = bbox(&g); + let (ox, oy) = if d.anchor == Anchor::Wall { (-p.w / 2.0, 0.0) } else { (-p.w / 2.0, -p.d / 2.0) }; + let eps = 1e-9; + // Auto: das Parkfeld 2.50 × 5.00 umschliesst das Fahrzeug 1.80 × 4.70. + if d.id == "lib:auto" { + assert!((x1 - x0 - 2.5).abs() < eps && (y1 - y0 - 5.0).abs() < eps); + continue; + } + assert!((x0 - ox).abs() < eps && (x1 - (ox + p.w)).abs() < eps, "{} x {x0} {x1}", d.id); + assert!((y0 - oy).abs() < eps && (y1 - (oy + p.d)).abs() < eps, "{} y {y0} {y1}", d.id); + } + } + + #[test] + fn catalog_sizes_from_the_brief() { + let size = |id: &str| { + let p = find(id).unwrap().def().resolve(&BTreeMap::new()); + (p.w, p.d) + }; + assert_eq!(size("lib:wc-wand"), (0.38, 0.55)); + assert_eq!(size("lib:kueche-zeile"), (2.75, 0.60)); + assert_eq!(size("lib:kueche-insel"), (1.65, 0.90)); + assert_eq!(size("lib:wendekreis"), (1.5, 1.5)); + assert_eq!(size("lib:tisch-rund-120"), (1.2, 1.2)); + assert_eq!(size("lib:auto"), (1.8, 4.7)); + } + + #[test] + fn params_clamp_and_ignore_garbage() { + let o = find("lib:lavabo").unwrap(); + let mut m = BTreeMap::new(); + m.insert("w".to_string(), json!(99.0)); + m.insert("d".to_string(), json!("x")); + let p = o.def().resolve(&m); + assert_eq!((p.w, p.d), (6.0, 0.45)); + m.insert("w".to_string(), json!(f64::NAN)); + assert_eq!(o.def().resolve(&m).w, 0.6); + } + + #[test] + fn unknown_id_draws_placeholder() { + let g = geometry_for("lib:gibt-es-nicht", &BTreeMap::new(), Detail::Mittel, 0); + assert_eq!(g.len(), 3); + assert!(finite(&g)); + } + + #[test] + fn mirror_flips_x() { + let mut m = BTreeMap::new(); + let a = bbox(&geometry_for("lib:sofa-2", &m, Detail::Grob, 0)); + m.insert("mirror".to_string(), json!(true)); + let b = bbox(&geometry_for("lib:sofa-2", &m, Detail::Grob, 0)); + assert!((a.0 + b.2).abs() < 1e-9 && (a.2 + b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9); + } + + fn table_params(id: &str, mess: f64) -> BTreeMap { + let _ = id; + let mut m = BTreeMap::new(); + m.insert("mess".to_string(), json!(mess)); + m + } + + #[test] + fn mess_zero_is_regular_and_seed_is_deterministic() { + for id in ["lib:tisch-80x140", "lib:tisch-rund-100"] { + let a = geometry_for(id, &table_params(id, 0.0), Detail::Mittel, 1); + let b = geometry_for(id, &table_params(id, 0.0), Detail::Mittel, 99); + assert_eq!(a, b, "{id}: Unordnung 0 hängt nicht vom Seed ab"); + let c = geometry_for(id, &table_params(id, 1.0), Detail::Mittel, 7); + assert_eq!(c, geometry_for(id, &table_params(id, 1.0), Detail::Mittel, 7)); + assert_ne!(c, geometry_for(id, &table_params(id, 1.0), Detail::Mittel, 8)); + assert_ne!(a, c); + } + } + + #[test] + fn regular_chairs_are_symmetric_about_the_table() { + let g = geometry_for("lib:tisch-80x140", &table_params("", 0.0), Detail::Grob, 0); + let (x0, y0, x1, y1) = bbox(&g); + assert!((x0 + x1).abs() < 1e-9 && (y0 + y1).abs() < 1e-9); + } + + /// Stühle schneiden den Tisch nie: der Abstand jedes Stuhl-Eckpunkts zum Tisch bleibt > 0. + #[test] + fn messy_chairs_never_cut_the_table() { + for seed in 0..60u32 { + let g = geometry_for("lib:tisch-80x140", &table_params("", 1.0), Detail::Grob, seed); + for s in &g { + if let G::Polyline { pts, .. } = s { + for q in pts { + let inside = q.x > -0.7 && q.x < 0.7 && q.y > -0.4 && q.y < 0.4; + assert!(!inside, "seed {seed}: {q:?}"); + } + } + } + let g = geometry_for("lib:tisch-rund-120", &table_params("", 1.0), Detail::Grob, seed); + for s in &g { + if let G::Polyline { pts, .. } = s { + for q in pts { + assert!((q.x * q.x + q.y * q.y).sqrt() > 0.6, "seed {seed}: {q:?}"); + } + } + } + } + } + + #[test] + fn catalog_json_lists_all() { + let c = catalog_json(); + assert_eq!(c["objects"].as_array().unwrap().len(), all().len()); + assert_eq!(c["categories"].as_array().unwrap().len(), 3); + } +} diff --git a/src-tauri/core/src/geo_rebase.rs b/src-tauri/core/src/geo_rebase.rs index bd814a26..c9ae09bf 100644 --- a/src-tauri/core/src/geo_rebase.rs +++ b/src-tauri/core/src/geo_rebase.rs @@ -36,7 +36,7 @@ fn shift_geom(g: &mut Drawing2DGeom, dx: f64, dy: f64) { *max = shift(*max, dx, dy); } Circle { center, .. } | Arc { center, .. } | Ellipse { center, .. } => *center = shift(*center, dx, dy), - Grid { origin: at, .. } | Kote { at, .. } | Detailref { at, .. } | Scalebar { at, .. } | Pointmarker { at } | Block { at, .. } => *at = shift(*at, dx, dy), + Grid { origin: at, .. } | Kote { at, .. } | Detailref { at, .. } | Scalebar { at, .. } | Pointmarker { at } | Block { at, .. } | Libobj { at, .. } => *at = shift(*at, dx, dy), Text { at, leader_target, leader_bend_points, path_pts, .. } => { *at = shift(*at, dx, dy); if let Some(t) = leader_target { diff --git a/src-tauri/core/src/geo_translate.rs b/src-tauri/core/src/geo_translate.rs index a35a10a8..8f60f1d3 100644 --- a/src-tauri/core/src/geo_translate.rs +++ b/src-tauri/core/src/geo_translate.rs @@ -68,7 +68,7 @@ fn shift_geom(g: &Value, dx: f64, dy: f64) -> Value { } "rect" | "image" => shift_pts_fields(&mut m, &["min", "max"], dx, dy, &[]), "circle" | "arc" | "ellipse" => shift_pts_fields(&mut m, &["center"], dx, dy, &[]), - "kote" | "detailref" | "scalebar" | "pointmarker" | "block" => shift_pts_fields(&mut m, &["at"], dx, dy, &[]), + "kote" | "detailref" | "scalebar" | "pointmarker" | "block" | "libobj" => shift_pts_fields(&mut m, &["at"], dx, dy, &[]), "grid" => shift_pts_fields(&mut m, &["origin"], dx, dy, &[]), "text" => { shift_pts_fields(&mut m, &["at"], dx, dy, &[]); diff --git a/src-tauri/core/src/grips.rs b/src-tauri/core/src/grips.rs index 4637eb7e..53ae8f87 100644 --- a/src-tauri/core/src/grips.rs +++ b/src-tauri/core/src/grips.rs @@ -969,7 +969,7 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64, free: bool) - } set("at", p) } - "kote" | "detailref" | "scalebar" | "pointmarker" | "block" => set("at", p), + "kote" | "detailref" | "scalebar" | "pointmarker" | "block" | "libobj" => set("at", p), "grid" => { // Griff 0 = Ursprung, danach je Achse (a, dann b) das Achsende: zieht die Achse auf die neue Lage. if index == 0.0 { @@ -1928,7 +1928,7 @@ pub fn drawing_vertices(g: &Value, scale: f64) -> Option> { } out } - "kote" | "detailref" | "scalebar" | "pointmarker" | "block" => vec![p("at")], + "kote" | "detailref" | "scalebar" | "pointmarker" | "block" | "libobj" => vec![p("at")], "grid" => { let geom: crate::model::Drawing2DGeom = serde_json::from_value(g.clone()).ok()?; let spec = crate::grid::Spec::of(&geom)?; diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 81211a59..38713c28 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -141,6 +141,7 @@ pub mod opening_presets; pub mod surface_pattern; pub mod surface_pattern3d; pub mod standards; +pub mod furniture_lib; pub mod dim_assoc; pub mod opening_slide; diff --git a/src-tauri/core/src/model/manual.rs b/src-tauri/core/src/model/manual.rs index de077c9c..ed83e8ce 100644 --- a/src-tauri/core/src/model/manual.rs +++ b/src-tauri/core/src/model/manual.rs @@ -599,6 +599,25 @@ pub enum Drawing2DGeom { #[ts(optional)] scale: Option, }, + /// Objekt der Bibliothek ([253], `furniture_lib.rs`): Katalog-Id + offene Parameter-Map; der Kern erzeugt die + /// Linien zur Plan-Zeit nach Detailgrad. Keine objektspezifischen Felder (spätere eigene Objekte [254]); + /// unbekannte `libId` zeichnet einen Platzhalter-Rahmen. `at` = Einfügepunkt (je Objekt Wandseite Mitte oder + /// Mittelpunkt), `rotation` in Radiant (CCW). + #[serde(rename = "libobj")] + Libobj { + #[serde(rename = "libId")] + lib_id: String, + at: Vec2, + rotation: f64, + /// Parameter (Name → Zahl/Bool/Text), z. B. `w`, `d`, `n`, `mirror`, `mess`; fehlend = Vorgabe des Objekts. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional, type = "Record")] + params: Option>, + /// Seed für zufällige Anteile (Unordnung der Stühle): gleicher Seed = gleiche Geometrie. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + seed: Option, + }, #[serde(rename = "image")] Image { /// Obere-linke Ecke der Bild-Box (Modell-Meter). diff --git a/src-tauri/core/src/plan/drawings.rs b/src-tauri/core/src/plan/drawings.rs index 193c747a..83187055 100644 --- a/src-tauri/core/src/plan/drawings.rs +++ b/src-tauri/core/src/plan/drawings.rs @@ -228,6 +228,7 @@ pub fn shape_name(g: &Drawing2DGeom) -> &'static str { Drawing2DGeom::Grid { .. } => "grid", Drawing2DGeom::Text { .. } => "text", Drawing2DGeom::Block { .. } => "block", + Drawing2DGeom::Libobj { .. } => "libobj", Drawing2DGeom::Image { .. } => "image", } } @@ -951,6 +952,21 @@ fn emit_inner(c: &Ctx, d: &Drawing2D, attrs: Attrs, geom: &Drawing2DGeom, greyed emit(c, d, attrs, &g2, greyed, scale, em.sink, depth + 1)?; } } + Drawing2DGeom::Libobj { lib_id, at, rotation, params, seed } => { + // [253] Objekt der Bibliothek: Linien nach Detailgrad erzeugen, drehen, verschieben, wie ein Block ausgeben. + if depth >= MAX_BLOCK_DEPTH { + return Ok(()); + } + let none = std::collections::BTreeMap::new(); + let local = crate::furniture_lib::geometry_for(lib_id, params.as_ref().unwrap_or(&none), c.a.detail, seed.unwrap_or(0)); + let (cs, sn) = (jsnum::cos(*rotation), jsnum::sin(*rotation)); + let at = *at; + let xf = move |q: Vec2| v(at.x + q.x * cs - q.y * sn, at.y + q.x * sn + q.y * cs); + for sub in &local { + let g2 = scale_geom(sub, &xf, 1.0); + emit(c, d, attrs, &g2, greyed, scale, em.sink, depth + 1)?; + } + } Drawing2DGeom::Image { min, max, src, opacity } => { em.sink.push(Primitive::DrawingImage { min: *min, max: *max, src: src.clone(), opacity: opacity.unwrap_or(1.0), drawing_id: Some(d.id.clone()), greyed: Some(greyed) }, 0); } @@ -1510,6 +1526,12 @@ pub fn mv_geom(g: &Drawing2DGeom, f: &dyn Fn(Vec2) -> Vec2) -> Drawing2DGeom { let nt = f(tip); G::Block { block_def_id: block_def_id.clone(), at: nb, rotation: jsnum::atan2(nt.y - nb.y, nt.x - nb.x), scale: *scale } } + G::Libobj { lib_id, at, rotation, params, seed } => { + let tip = v(at.x + jsnum::cos(*rotation), at.y + jsnum::sin(*rotation)); + let nb = f(*at); + let nt = f(tip); + G::Libobj { lib_id: lib_id.clone(), at: nb, rotation: jsnum::atan2(nt.y - nb.y, nt.x - nb.x), params: params.clone(), seed: *seed } + } G::Image { min, max, src, opacity } => { let old = v((min.x + max.x) / 2.0, (min.y + max.y) / 2.0); let new = f(old); @@ -1547,6 +1569,18 @@ pub fn scale_geom(g: &Drawing2DGeom, f: &dyn Fn(Vec2) -> Vec2, k: f64) -> Drawin } G::Scalebar { segment_length, .. } => *segment_length *= k, G::Block { scale, .. } => *scale = Some(scale.unwrap_or(1.0) * k), + G::Libobj { params, .. } => { + // Masse (Längen) wachsen mit; Anzahl, Flags, Unordnung bleiben. + if let Some(m) = params { + for key in ["w", "d"] { + if let Some(x) = m.get_mut(key) { + if let Some(n) = x.as_f64() { + *x = serde_json::json!(n * k); + } + } + } + } + } _ => {} } out @@ -1635,7 +1669,7 @@ fn acc_bounds(g: &Drawing2DGeom, b: &mut Bounds) { acc(at); acc(&v(at.x + segment_length * segments, at.y)); } - G::Xline { .. } | G::Ray { .. } | G::Block { .. } => {} + G::Xline { .. } | G::Ray { .. } | G::Block { .. } | G::Libobj { .. } => {} } } @@ -1969,7 +2003,7 @@ pub fn closed_rings_by_class_ids(c: &Ctx, pred: impl Fn(&str) -> bool) -> Vec<(S /// [140] Zeichnungsarten, denen Raumstempel ausweichen (Bemassung, Koten, Texte, Symbole/Möbel als Blöcke, /// Detailverweise, Punktmarken). Linien, Flächen, Raster und Bilder nicht: sie laufen oft durch ganze Räume. pub fn is_stamp_obstacle(g: &Drawing2DGeom) -> bool { - matches!(g, Drawing2DGeom::Dimension { .. } | Drawing2DGeom::Kote { .. } | Drawing2DGeom::Text { .. } | Drawing2DGeom::Block { .. } | Drawing2DGeom::Detailref { .. } | Drawing2DGeom::Pointmarker { .. }) + matches!(g, Drawing2DGeom::Dimension { .. } | Drawing2DGeom::Kote { .. } | Drawing2DGeom::Text { .. } | Drawing2DGeom::Block { .. } | Drawing2DGeom::Libobj { .. } | Drawing2DGeom::Detailref { .. } | Drawing2DGeom::Pointmarker { .. }) } /// [140] Primitive der gezeichneten Zeichnungen des Geschosses, denen Raumstempel ausweichen @@ -2029,7 +2063,15 @@ fn prims_where(c: &Ctx, pred: impl Fn(&Drawing2DGeom) -> bool) -> Vec pub fn block_footprints(c: &Ctx) -> Vec> { let mut memo = Memo::default(); let mut res = Vec::new(); - for d in c.p.drawings2d.iter().filter(|d| matches!(d.geom, Drawing2DGeom::Block { .. }) && on_floor(c, d)) { + for d in c.p.drawings2d.iter().filter(|d| { + // [253] Objekte der Bibliothek ausser Aussenraum (Auto, Parkfeld, Wendekreis) sparen den Belag aus. + let drawn = match &d.geom { + Drawing2DGeom::Block { .. } => true, + Drawing2DGeom::Libobj { lib_id, .. } => crate::furniture_lib::find(lib_id).is_none_or(|o| o.def().cat != crate::furniture_lib::Cat::Outdoor), + _ => false, + }; + drawn && on_floor(c, d) + }) { let m = memo.get(c, d); if !m.shown { continue; @@ -2710,6 +2752,32 @@ mod tests { assert!(matches!(out[0], Primitive::Polygon { .. })); } + /// [253] Objekt der Bibliothek: Detailgrad (grob < mittel < fein) wie bei Fenstern/Türen, Lage und Drehung, + /// unbekannte Id = Platzhalter, ein Objekt mit Parametern ändert das Mass. + #[test] + fn libobj_nach_detailgrad_lage_und_platzhalter() { + let p = project(serde_json::json!({})); + let lines_at = |detail: f64, geom: serde_json::Value| -> Vec { + let d: Drawing2D = serde_json::from_value(drawing(geom)).unwrap(); + let a = PlanArgs::parse(detail, r#"{"floor":"eg","show":["20"],"scale":100}"#).unwrap(); + let c = Ctx::new(&p, &a); + let mut out = Out::default(); + emit(&c, &d, Attrs::of(&c, &d), &d.geom, false, 100.0, &mut Sink::new(Target::Vec(&mut out), Keep::All), 0).unwrap(); + out.prims.into_iter().filter(|q| matches!(q, Primitive::Line { .. })).collect() + }; + let wc = |detail: f64| lines_at(detail, serde_json::json!({"shape": "libobj", "libId": "lib:wc-wand", "at": {"x": 5, "y": 5}, "rotation": 0})); + let (g, m, f) = (wc(0.0).len(), wc(1.0).len(), wc(2.0).len()); + assert!(g > 0 && g <= m && m < f, "{g} {m} {f}"); + // Gedreht um 90°: die Tiefe 0.55 liegt nun in x (Wandseite bei x = 5, Bug nach links). + let rot = lines_at(1.0, serde_json::json!({"shape": "libobj", "libId": "lib:wc-wand", "at": {"x": 5, "y": 5}, "rotation": std::f64::consts::FRAC_PI_2})); + let xs: Vec = rot.iter().filter_map(|q| if let Primitive::Line { a, b, .. } = q { Some([a.x, b.x]) } else { None }).flatten().collect(); + let (lo, hi) = xs.iter().fold((f64::MAX, f64::MIN), |(l, h), x| (l.min(*x), h.max(*x))); + assert!((hi - 5.0).abs() < 1e-6 && (lo - 4.45).abs() < 1e-3, "{lo} {hi}"); + // Unbekannte Id: Rahmen mit Diagonalen statt Fehler. + let ghost = lines_at(1.0, serde_json::json!({"shape": "libobj", "libId": "lib:zukunft", "at": {"x": 0, "y": 0}, "rotation": 0})); + assert_eq!(ghost.len(), 6); + } + #[test] fn block_mit_selbstbezug_endet() { let p = project(serde_json::json!({ "blockDefs": [{ "id": "b", "name": "B", "geom2d": [ diff --git a/src-tauri/core/src/selection_info.rs b/src-tauri/core/src/selection_info.rs index 79dc85b7..439a4dac 100644 --- a/src-tauri/core/src/selection_info.rs +++ b/src-tauri/core/src/selection_info.rs @@ -1250,7 +1250,7 @@ pub fn geom_bbox(g: &Value) -> [f64; 4] { pts.extend(chain.iter().map(|q| (q.0 + nx, q.1 + ny))); } } - Some("kote" | "text" | "block" | "detailref" | "pointmarker") => pts.push(p("at")), + Some("kote" | "text" | "block" | "libobj" | "detailref" | "pointmarker") => pts.push(p("at")), Some("grid") => { if let Some(spec) = serde_json::from_value::(g.clone()).ok().as_ref().and_then(crate::grid::Spec::of) { for ax in spec.axes() { diff --git a/src-tauri/core/src/standards.rs b/src-tauri/core/src/standards.rs index 00b47bc5..098b10d0 100644 --- a/src-tauri/core/src/standards.rs +++ b/src-tauri/core/src/standards.rs @@ -409,7 +409,7 @@ pub fn derived_visible(p: &crate::model::Project, code: &str, shown: impl Fn(&st } /// Gibt es im Kategorie-Baum schon den Code oder den Namen `name` (klein)? -fn has_category(layers: &[Value], code: &str, name: &str) -> bool { +pub(crate) fn has_category(layers: &[Value], code: &str, name: &str) -> bool { layers.iter().any(|l| l["code"].as_str() == Some(code) || name_key(l).as_deref() == Some(name) || l["children"].as_array().is_some_and(|c| has_category(c, code, name))) } @@ -500,6 +500,12 @@ fn merge_plan(root: &Map) -> (Vec, HashMap all.push(d); } } + // [253] Klassen der Objektbibliothek: Möbel, Sanitär, Fahrzeuge & Freiflächen. + for (_, code, name, color, lw) in crate::furniture_lib::CATEGORIES { + if !has_category(&layers, code, &name.to_lowercase()) { + all.push(json!({"code": code, "name": name, "color": color, "lw": lw, "visible": true, "locked": false})); + } + } if all.len() != layers.len() { ops.push(json!({"kind": "setField", "key": "layers", "value": all})); } @@ -867,7 +873,7 @@ mod tests { // Andere Kategorien bleiben, die neue kommt ans Ende. own.insert("layers".into(), json!([{"code": "20", "name": "Wände", "color": "#000", "lw": 0.35, "visible": true, "locked": false}])); let op = merge_ops(&own).into_iter().find(|o| o["key"] == "layers").unwrap(); - assert_eq!(op["value"].as_array().unwrap().iter().map(|l| l["code"].as_str().unwrap()).collect::>(), ["20", "65", "08", "81", "82", "91", "92", "83", "84"]); + assert_eq!(op["value"].as_array().unwrap().iter().map(|l| l["code"].as_str().unwrap()).collect::>(), ["20", "65", "08", "81", "82", "91", "92", "83", "84", "22", "23", "24"]); } /// [180] Klassen der abgeleiteten Darstellung: „Standards laden" legt sie an, einmal; vorhandene (Code oder Name) bleiben. @@ -883,7 +889,7 @@ mod tests { own.insert("layers".into(), json!([{"code": "77", "name": "schatten", "color": "#000", "lw": 0.13, "visible": true, "locked": false}])); let op = merge_ops(&own).into_iter().find(|o| o["key"] == "layers").unwrap(); let codes: Vec<&str> = op["value"].as_array().unwrap().iter().map(|l| l["code"].as_str().unwrap()).collect(); - assert_eq!(codes, ["77", "65", "81", "82", "91", "92", "83", "84"]); + assert_eq!(codes, ["77", "65", "81", "82", "91", "92", "83", "84", "22", "23", "24"]); // Sichtbar, solange die Klasse fehlt; sonst nach der Klassen-Sichtbarkeit. assert!(derived_visible(&p, SHADOW_CATEGORY, |c| c == SHADOW_CATEGORY)); assert!(!derived_visible(&p, SHADOW_CATEGORY, |_| false)); diff --git a/src-tauri/core/src/web/furniture_lib.rs b/src-tauri/core/src/web/furniture_lib.rs new file mode 100644 index 00000000..bd0b3c40 --- /dev/null +++ b/src-tauri/core/src/web/furniture_lib.rs @@ -0,0 +1,20 @@ +//! Bindung der Objektbibliothek (`crate::furniture_lib`, [253]): Katalog und Vorschau-Geometrie als JSON. +//! Unsinn (kaputtes JSON, unbekannte Id) ergibt Platzhalter bzw. leere Listen — nie einen Panic. + +use crate::plan::style::Detail; +use std::collections::BTreeMap; +use wasm_bindgen::prelude::wasm_bindgen; + +/// Katalog `{ objects: [{id, group, category, categoryCode, categoryName, anchor, seeded, params}], categories }`. +#[wasm_bindgen] +pub fn furniture_lib_catalog_json() -> String { + crate::furniture_lib::catalog_json().to_string() +} + +/// Lokale Geometrie (Array von `Drawing2DGeom`) eines Objekts: `params_json` = Parameter-Map, `detail` = grob|mittel|fein. +#[wasm_bindgen] +pub fn furniture_lib_geometry_json(lib_id: &str, params_json: &str, detail: &str, seed: u32) -> String { + let params: BTreeMap = serde_json::from_str(params_json).unwrap_or_default(); + let g = crate::furniture_lib::geometry_for(lib_id, ¶ms, Detail::parse(detail), seed); + serde_json::to_string(&g).unwrap_or_else(|_| "[]".into()) +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 88ffaf8d..5cfb2e9c 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -47,6 +47,7 @@ mod area_report; mod rich_text; mod geo_mesh; mod opening_presets; +mod furniture_lib; mod solid_bool; mod line_pattern; diff --git a/src/commands/README.md b/src/commands/README.md index d689b9d2..35b07b05 100644 --- a/src/commands/README.md +++ b/src/commands/README.md @@ -30,7 +30,7 @@ Ribbon-Befehle sie erreichen: `src/state/useToolInput.ts`. |---|---| | 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`, `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` | +| 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`, `libobj.ts` (Objekt aus der Bibliothek setzen, [253]) | | 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` | | Sonstiges | `measure.ts`, `wand.ts` (Zauberstab), `recognize.ts` (Bauteile aus Zeichnung), `georef.ts`, `import.ts`, `presentation.ts` | diff --git a/src/commands/cmds/libobj.test.ts b/src/commands/cmds/libobj.test.ts new file mode 100644 index 00000000..876ae6bc --- /dev/null +++ b/src/commands/cmds/libobj.test.ts @@ -0,0 +1,152 @@ +/** + * Objektbibliothek 2D ([253]): Katalog aus dem Kern, Platzieren (Befehl `libobj`: Klasse wird im selben Schritt + * angelegt, Drehen/Spiegeln), Plan-Ausgabe nach Detailgrad, unbekannte Objekt-Id, Möbel sparen den Belag aus. + */ + +import { describe, it, expect, beforeEach } from "vitest"; +import { libobjCommand, setActiveLibObject, resetLibObjectPlacement } from "./libobj"; +import { libCatalog, libDefaultParams, libGeometry, libGroups, libObjectDef } from "../../model/furnitureLib"; +import { drawingPrimitives } from "../../plan/generatePlan"; +import type { CommandContext, Project } from "../types"; +import type { Drawing2D } from "../../model/types"; + +function project(layers: Project["layers"] = []): 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, + walls: [], + openings: [], + ceilings: [], + stairs: [], + rooms: [], + drawings2d: [], + context: [], + }; +} + +function makeCtx(p: Project): CommandContext { + return { + project: p, + level: p.drawingLevels[0], + defaultCategoryCode: "20", + activeLineStyleId: "solid", + activeWallTypeId: "aw", + lastPoint: null, + selection: { wallIds: [], drawingId: null }, + }; +} + +const LAYER_MOEBEL = { code: "22", name: "Möbel", color: "#4a4a4a", lw: 0.13, visible: true, locked: false }; + +function place(p: Project, libId: string, at = { x: 3, y: 4 }) { + setActiveLibObject(libId, libDefaultParams(libObjectDef(libId)!)); + const [, r] = libobjCommand.onInput(libobjCommand.init(), { kind: "point", point: at }, makeCtx(p)); + expect(r.commit).toBeDefined(); + return r.commit!(p); +} + +beforeEach(() => resetLibObjectPlacement()); + +describe("Katalog", () => { + it("enthält alle Gruppen und Objekte aus dem Kern", () => { + const c = libCatalog(); + expect(c.objects.length).toBeGreaterThanOrEqual(48); + expect(libGroups()).toEqual(["sanitary", "kitchen", "tables", "seating", "sleeping", "cupboards", "outdoor"]); + for (const o of c.objects) expect(libGeometry(o.id, libDefaultParams(o), "mittel").length).toBeGreaterThan(0); + }); + + it("Parameter sind allgemein beschrieben (Art, Vorgabe, Grenzen)", () => { + const wc = libObjectDef("lib:wc-wand")!; + expect(wc.params.find((p) => p.key === "w")).toMatchObject({ kind: "length", default: 0.38 }); + expect(libObjectDef("lib:tisch-80x140")!.seeded).toBe(true); + }); +}); + +describe("Befehl libobj", () => { + it("setzt ein WC auf Sanitär und legt die Klasse im selben Schritt an", () => { + const p = project([LAYER_MOEBEL]); + const next = place(p, "lib:wc-wand"); + expect(next.drawings2d).toHaveLength(1); + const d = next.drawings2d[0]; + expect(d.categoryCode).toBe("23"); + expect(next.layers.some((l) => l.code === "23" && l.name === "Sanitär")).toBe(true); + expect(d.geom.shape).toBe("libobj"); + if (d.geom.shape === "libobj") { + expect(d.geom.libId).toBe("lib:wc-wand"); + expect(d.geom.at).toEqual({ x: 3, y: 4 }); + expect(d.geom.rotation).toBe(0); + } + }); + + it("Möbel landen auf „Möbel“; eine vorhandene Klasse wird nicht doppelt angelegt", () => { + const p = project([LAYER_MOEBEL]); + const next = place(p, "lib:bett-140"); + expect(next.drawings2d[0].categoryCode).toBe("22"); + expect(next.layers.filter((l) => l.code === "22")).toHaveLength(1); + }); + + it("Drehen (R) und Spiegeln (M) gelten für das nächste Objekt", () => { + const p = project([LAYER_MOEBEL]); + setActiveLibObject("lib:sofa-2", libDefaultParams(libObjectDef("lib:sofa-2")!)); + let [s] = libobjCommand.onInput(libobjCommand.init(), { kind: "option", id: "rotate" }, makeCtx(p)); + [s] = libobjCommand.onInput(s, { kind: "option", id: "mirror" }, makeCtx(p)); + const [, r] = libobjCommand.onInput(s, { kind: "point", point: { x: 1, y: 1 } }, makeCtx(p)); + const g = r.commit!(p).drawings2d[0].geom; + expect(g.shape).toBe("libobj"); + if (g.shape === "libobj") { + expect(g.rotation).toBeCloseTo(Math.PI / 2, 9); + expect(g.params?.mirror).toBe(true); + } + }); + + it("Vorschau hängt am Cursor", () => { + setActiveLibObject("lib:stuhl", {}); + const [, r] = libobjCommand.onMove!(libobjCommand.init(), { x: 2, y: 2 }, null, makeCtx(project())); + expect(r.draft?.preview.length).toBeGreaterThan(0); + }); +}); + +function libDrawing(geom: Extract): Drawing2D { + return { id: "o1", type: "drawing2d", levelId: "eg", categoryCode: "23", geom }; +} + +describe("Plan-Ausgabe", () => { + const proj = () => project([LAYER_MOEBEL, { code: "23", name: "Sanitär", color: "#4a4a4a", lw: 0.13, visible: true, locked: false }]); + + it("ein gesetztes WC erscheint als Linien an der Lage, gedreht", () => { + const d = libDrawing({ shape: "libobj", libId: "lib:wc-wand", at: { x: 10, y: 10 }, rotation: 0 }); + const lines = drawingPrimitives(proj(), d).filter((p) => p.kind === "line"); + expect(lines.length).toBeGreaterThan(4); + const ys = lines.flatMap((l) => [l.a.y, l.b.y]); + // Wandseite bei y = 10, Bug 55 cm davor. + expect(Math.min(...ys)).toBeCloseTo(10, 6); + expect(Math.max(...ys)).toBeCloseTo(10.55, 2); + const xs = lines.flatMap((l) => [l.a.x, l.b.x]); + expect(Math.max(...xs) - Math.min(...xs)).toBeCloseTo(0.38, 2); + }); + + it("Detailgrad: mehr Linien bei höherem Grad — Parameter ändern das Mass", () => { + const d = libDrawing({ shape: "libobj", libId: "lib:lavabo", at: { x: 0, y: 0 }, rotation: 0, params: { w: 0.8 } }); + const xs = drawingPrimitives(proj(), d).filter((p) => p.kind === "line").flatMap((l) => [l.a.x, l.b.x]); + expect(Math.max(...xs) - Math.min(...xs)).toBeCloseTo(0.8, 2); + }); + + it("unbekannte Objekt-Id zeichnet einen Platzhalter-Rahmen statt zu scheitern", () => { + const d = libDrawing({ shape: "libobj", libId: "lib:gibt-es-nicht", at: { x: 0, y: 0 }, rotation: 0 }); + expect(drawingPrimitives(proj(), d).filter((p) => p.kind === "line").length).toBeGreaterThanOrEqual(3); + }); + + it("gleicher Seed = gleiche Stühle; Unordnung 0 = regelmässig", () => { + const mk = (mess: number, seed: number) => + drawingPrimitives(proj(), libDrawing({ shape: "libobj", libId: "lib:tisch-80x140", at: { x: 0, y: 0 }, rotation: 0, params: { mess }, seed })); + expect(JSON.stringify(mk(1, 5))).toEqual(JSON.stringify(mk(1, 5))); + expect(JSON.stringify(mk(1, 5))).not.toEqual(JSON.stringify(mk(1, 6))); + expect(JSON.stringify(mk(0, 5))).toEqual(JSON.stringify(mk(0, 6))); + }); +}); diff --git a/src/commands/cmds/libobj.ts b/src/commands/cmds/libobj.ts new file mode 100644 index 00000000..e54a6953 --- /dev/null +++ b/src/commands/cmds/libobj.ts @@ -0,0 +1,98 @@ +// Objekt der Bibliothek setzen ([253]) — platziert ein Objekt der Standard-Bibliothek (Palette „Objekte") als +// parametrische Instanz (`{shape:"libobj"}`: Katalog-Id + Parameter + Lage); der Kern erzeugt die Linien zur +// Plan-Zeit nach Detailgrad. Welches Objekt aktiv ist, setzt die Palette über `setActiveLibObject`. +// „Einfügepunkt:" → Punkt (Klick setzt ein). Optionen: Drehen (R, +90°), Spiegeln (M). Drehung und Spiegelung +// bleiben für die nächsten Objekte erhalten. Die Vorschau hängt am Cursor. +// Klasse (Möbel, Sanitär, Fahrzeuge & Freiflächen) bestimmt der Kern; fehlt sie im Projekt, legt der Befehl sie +// im selben Undo-Schritt an. + +import { createMutation, xy } from "../createCore"; +import { libGeometry, libGeometryToPolys, type LibParams } from "../../model/furnitureLib"; +import type { CmdOption, Command, CommandResult, CommandState, Vec2 } from "../types"; + +interface ActiveLib { + libId: string; + params: LibParams; +} + +let active: ActiveLib | null = null; +/** Drehung (Radiant) und Spiegelung der Objekte, die als Nächstes gesetzt werden. */ +let rotation = 0; +let mirror = false; + +/** Die Palette wählt das Objekt (und seine Parameter) für den Befehl `libobj`. */ +export function setActiveLibObject(libId: string, params: LibParams = {}): void { + active = { libId, params: { ...params } }; +} + +export function activeLibObject(): ActiveLib | null { + return active; +} + +/** Nur für Tests: Drehung/Spiegelung zurücksetzen. */ +export function resetLibObjectPlacement(): void { + rotation = 0; + mirror = false; +} + +interface LibState extends CommandState { + phase: "point"; +} + +const OPTIONS: CmdOption[] = [ + { id: "rotate", labelKey: "cmd.libobj.rotate", key: "R" }, + { id: "mirror", labelKey: "cmd.libobj.mirror", key: "M" }, +]; + +function instanceParams(): LibParams { + const p: LibParams = { ...(active?.params ?? {}) }; + if (mirror) p.mirror = true; + else delete p.mirror; + return p; +} + +function previewAt(at: Vec2): CommandResult { + if (!active) return { draft: null }; + const c = Math.cos(rotation); + const s = Math.sin(rotation); + const geoms = libGeometry(active.libId, instanceParams(), "mittel", 0); + const polys = libGeometryToPolys(geoms, (p) => ({ x: at.x + p.x * c - p.y * s, y: at.y + p.x * s + p.y * c })); + return { + draft: { + preview: polys.map((pl) => ({ kind: "poly" as const, pts: pl.pts, closed: pl.closed })), + vertices: [at], + }, + }; +} + +const state0 = (): LibState => ({ phase: "point", lastPoint: null }); + +export const libobjCommand: Command = { + name: "libobj", + labelKey: "cmd.libobj.label", + prompt: () => "cmd.libobj.point", + accepts: () => ["point", "option"], + options: () => OPTIONS.map((o) => (o.id === "mirror" ? { ...o, value: mirror ? "ja" : "nein" } : { ...o, value: `${Math.round((rotation * 180) / Math.PI) % 360}°` })), + init: state0, + + onInput: (state, input, ctx): [CommandState, CommandResult] => { + if (input.kind === "option") { + if (input.id === "rotate") rotation = (rotation + Math.PI / 2) % (2 * Math.PI); + else if (input.id === "mirror") mirror = !mirror; + return [state, { draft: null }]; + } + if (input.kind !== "point" || !active) return [state, { draft: null }]; + const commit = createMutation(ctx, { + cmd: "libobj", + lib: active.libId, + at: xy(input.point), + rotation, + params: instanceParams(), + }); + return [state0(), { draft: null, done: true, commit }]; + }, + + onMove: (state, point): [CommandState, CommandResult] => [state, previewAt(point)], + onConfirm: (): [CommandState, CommandResult] => [state0(), { draft: null, done: true }], + onCancel: (): [CommandState, CommandResult] => [state0(), { draft: null, done: true }], +}; diff --git a/src/commands/registry.ts b/src/commands/registry.ts index f7a46b91..0df46ede 100644 --- a/src/commands/registry.ts +++ b/src/commands/registry.ts @@ -75,6 +75,7 @@ import { sectionLineCommand, viewLineCommand } from "./cmds/sectionline"; import { georefCommand } from "./cmds/georef"; import { blockCommand } from "./cmds/block"; import { defblockCommand } from "./cmds/defblock"; +import { libobjCommand } from "./cmds/libobj"; import { presentationCommand } from "./cmds/presentation"; import { traceMoveCommand, traceRotateCommand } from "./cmds/tracemove"; import { renderingCommand } from "./cmds/rendering"; @@ -164,6 +165,7 @@ export const COMMANDS: Record = { georef: georefCommand, block: blockCommand, defblock: defblockCommand, + libobj: libobjCommand, tracemove: traceMoveCommand, tracerotate: traceRotateCommand, }; diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 38f3ee3a..ae84b601 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -4248,6 +4248,85 @@ export const de = { "help.shortcuts.commandsHint": "In die Befehlszeile tippen, dann Enter. Ändern: Einstellungen → Tastenkürzel.", "file.newFromWettbewerbSample": "Neu aus Vorlage: Wettbewerb", "menu.native.newFromWettbewerbSample": "Wettbewerb", + "lib.o.wc-wand": "WC wandhängend", + "lib.o.wc-kasten": "WC mit Spülkasten", + "lib.o.lavabo": "Lavabo", + "lib.o.handwaschbecken": "Handwaschbecken", + "lib.o.doppellavabo": "Doppellavabo", + "lib.o.dusche-90": "Dusche 90×90", + "lib.o.dusche-80x120": "Dusche 80×120", + "lib.o.wanne-170": "Badewanne 170×75", + "lib.o.wanne-180": "Badewanne 180×80", + "lib.o.urinal": "Urinal", + "lib.o.waschmaschine": "Waschmaschine / Tumbler", + "lib.o.kueche-unterbau": "Unterbau 55", + "lib.o.kueche-spuele": "Spüle 55", + "lib.o.kueche-kochfeld": "Kochfeld 55", + "lib.o.kueche-geschirrspueler": "Geschirrspüler 55", + "lib.o.kueche-kuehlschrank": "Kühlschrank 55", + "lib.o.kueche-hochschrank": "Hochschrank 55", + "lib.o.kueche-zeile": "Küchenzeile (55er-Module)", + "lib.o.kueche-insel": "Küchen-Insel", + "lib.o.tisch-80x140": "Tisch 80×140 mit Stühlen", + "lib.o.tisch-80x140-leer": "Tisch 80×140", + "lib.o.tisch-90x180": "Tisch 90×180 mit Stühlen", + "lib.o.tisch-90x180-leer": "Tisch 90×180", + "lib.o.tisch-rund-100": "Tisch rund Ø 100 mit Stühlen", + "lib.o.tisch-rund-100-leer": "Tisch rund Ø 100", + "lib.o.tisch-rund-120": "Tisch rund Ø 120 mit Stühlen", + "lib.o.tisch-rund-120-leer": "Tisch rund Ø 120", + "lib.o.tisch-buero": "Bürotisch 80×160", + "lib.o.stuhl": "Stuhl", + "lib.o.sofa-2": "Sofa 2er", + "lib.o.sofa-3": "Sofa 3er", + "lib.o.sessel": "Sessel", + "lib.o.salontisch": "Salontisch", + "lib.o.bett-90": "Bett 90×200", + "lib.o.bett-140": "Bett 140×200", + "lib.o.bett-160": "Bett 160×200", + "lib.o.bett-180": "Bett 180×200", + "lib.o.kinderbett": "Kinderbett 70×140", + "lib.o.nachttisch": "Nachttisch", + "lib.o.schrank-50": "Einbauschrank 50", + "lib.o.schrank-60": "Einbauschrank 60", + "lib.o.schrank-100": "Einbauschrank 100", + "lib.o.garderobe": "Garderobe T 35", + "lib.o.regal": "Regal T 35", + "lib.o.auto": "Auto mit Parkfeld", + "lib.o.parkfeld": "Parkfeld 2.50×5.00", + "lib.o.velo": "Velo", + "lib.o.wendekreis": "Rollstuhl-Wendekreis Ø 150", + "lib.g.sanitary": "Sanitär", + "lib.g.kitchen": "Küche", + "lib.g.tables": "Tische", + "lib.g.seating": "Sitzen", + "lib.g.sleeping": "Schlafen", + "lib.g.cupboards": "Schränke", + "lib.g.outdoor": "Aussenraum", + "lib.p.w": "Breite", + "lib.p.d": "Tiefe", + "lib.p.n": "Anzahl", + "lib.p.mess": "Unordnung", + "lib.p.field": "Parkfeld", + "lib.p.mirror": "Spiegeln", + "lib.title": "Objekte", + "lib.hint": "Objekt wählen, dann im Plan den Einfügepunkt klicken (R = drehen, M = spiegeln).", + "lib.empty": "Keine Objekte verfügbar.", + "lib.params": "Vorgaben", + "lib.reroll": "Neu würfeln", + "lib.section": "Objekt aus Bibliothek", + "lib.unknown": "Unbekanntes Objekt", + "cmd.libobj.label": "Objekt setzen", + "cmd.libobj.point": "Einfügepunkt:", + "cmd.libobj.rotate": "Drehen", + "cmd.libobj.mirror": "Spiegeln", + "history.cmd.libobj": "Objekt setzen", + "history.libobj.param": "Objekt-Parameter ändern", + "history.libobj.reroll": "Stühle neu würfeln", + "nav.objects": "Objekte", + "lib.p.diameter": "Durchmesser", + "lib.p.n.kitchen": "Module (55 cm)", + "lib.p.n.tables": "Stühle", } as const; export type TranslationKey = keyof typeof de; diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 63822c06..0c361a4b 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -4234,4 +4234,83 @@ export const en: Record = { "help.shortcuts.commandsHint": "Type into the command line, then press Enter. To change: Settings → Keyboard shortcuts.", "file.newFromWettbewerbSample": "New From Template: Competition", "menu.native.newFromWettbewerbSample": "Competition", + "lib.o.wc-wand": "Wall-hung toilet", + "lib.o.wc-kasten": "Toilet with cistern", + "lib.o.lavabo": "Washbasin", + "lib.o.handwaschbecken": "Hand basin", + "lib.o.doppellavabo": "Double washbasin", + "lib.o.dusche-90": "Shower 90×90", + "lib.o.dusche-80x120": "Shower 80×120", + "lib.o.wanne-170": "Bathtub 170×75", + "lib.o.wanne-180": "Bathtub 180×80", + "lib.o.urinal": "Urinal", + "lib.o.waschmaschine": "Washer / dryer", + "lib.o.kueche-unterbau": "Base unit 55", + "lib.o.kueche-spuele": "Sink unit 55", + "lib.o.kueche-kochfeld": "Hob 55", + "lib.o.kueche-geschirrspueler": "Dishwasher 55", + "lib.o.kueche-kuehlschrank": "Fridge 55", + "lib.o.kueche-hochschrank": "Tall unit 55", + "lib.o.kueche-zeile": "Kitchen run (55 cm modules)", + "lib.o.kueche-insel": "Kitchen island", + "lib.o.tisch-80x140": "Table 80×140 with chairs", + "lib.o.tisch-80x140-leer": "Table 80×140", + "lib.o.tisch-90x180": "Table 90×180 with chairs", + "lib.o.tisch-90x180-leer": "Table 90×180", + "lib.o.tisch-rund-100": "Round table Ø 100 with chairs", + "lib.o.tisch-rund-100-leer": "Round table Ø 100", + "lib.o.tisch-rund-120": "Round table Ø 120 with chairs", + "lib.o.tisch-rund-120-leer": "Round table Ø 120", + "lib.o.tisch-buero": "Office desk 80×160", + "lib.o.stuhl": "Chair", + "lib.o.sofa-2": "Sofa 2-seater", + "lib.o.sofa-3": "Sofa 3-seater", + "lib.o.sessel": "Armchair", + "lib.o.salontisch": "Coffee table", + "lib.o.bett-90": "Bed 90×200", + "lib.o.bett-140": "Bed 140×200", + "lib.o.bett-160": "Bed 160×200", + "lib.o.bett-180": "Bed 180×200", + "lib.o.kinderbett": "Child bed 70×140", + "lib.o.nachttisch": "Bedside table", + "lib.o.schrank-50": "Built-in cupboard 50", + "lib.o.schrank-60": "Built-in cupboard 60", + "lib.o.schrank-100": "Built-in cupboard 100", + "lib.o.garderobe": "Wardrobe D 35", + "lib.o.regal": "Shelf D 35", + "lib.o.auto": "Car with parking bay", + "lib.o.parkfeld": "Parking bay 2.50×5.00", + "lib.o.velo": "Bicycle", + "lib.o.wendekreis": "Wheelchair turning circle Ø 150", + "lib.g.sanitary": "Sanitary", + "lib.g.kitchen": "Kitchen", + "lib.g.tables": "Tables", + "lib.g.seating": "Seating", + "lib.g.sleeping": "Sleeping", + "lib.g.cupboards": "Cupboards", + "lib.g.outdoor": "Outdoor", + "lib.p.w": "Width", + "lib.p.d": "Depth", + "lib.p.n": "Count", + "lib.p.mess": "Disorder", + "lib.p.field": "Parking bay", + "lib.p.mirror": "Mirror", + "lib.title": "Objects", + "lib.hint": "Pick an object, then click the insertion point in the plan (R = rotate, M = mirror).", + "lib.empty": "No objects available.", + "lib.params": "Defaults", + "lib.reroll": "Re-roll", + "lib.section": "Library object", + "lib.unknown": "Unknown object", + "cmd.libobj.label": "Place object", + "cmd.libobj.point": "Insertion point:", + "cmd.libobj.rotate": "Rotate", + "cmd.libobj.mirror": "Mirror", + "history.cmd.libobj": "Place object", + "history.libobj.param": "Change object parameter", + "history.libobj.reroll": "Re-roll chairs", + "nav.objects": "Objects", + "lib.p.diameter": "Diameter", + "lib.p.n.kitchen": "Modules (55 cm)", + "lib.p.n.tables": "Chairs", }; diff --git a/src/model/furnitureLib.ts b/src/model/furnitureLib.ts new file mode 100644 index 00000000..4e686a91 --- /dev/null +++ b/src/model/furnitureLib.ts @@ -0,0 +1,145 @@ +// Objektbibliothek 2D ([253]) — dünne Fassade über den Katalog des Rust-Kerns +// (`src-tauri/core/src/furniture_lib.rs`). Der Katalog beschreibt Objekte mit Gruppe, Klasse, Einfügepunkt und +// einer allgemeinen Parameterliste; die Linien erzeugt der Kern (zur Plan-Zeit nach Detailgrad, hier nur für +// die Vorschau der Palette und des Platzier-Werkzeugs). + +import { core } from "../engine/coreWasm"; +import type { Drawing2DGeom } from "./types"; + +export type LibParamKind = "length" | "count" | "flag" | "fraction" | "choice"; + +export interface LibParamDef { + key: string; + kind: LibParamKind; + default: number; + min: number; + max: number; + step: number; +} + +export interface LibObjectDef { + id: string; + /** Gruppe (`lib.g.`). */ + group: string; + /** Klasse: Schlüssel, Code und Name der Grafik-Kategorie. */ + category: string; + categoryCode: string; + categoryName: string; + /** Einfügepunkt: Wandseite Mitte oder Mittelpunkt. */ + anchor: "wall" | "center"; + /** Nutzt den Seed (Unordnung der Stühle). */ + seeded: boolean; + params: LibParamDef[]; +} + +export interface LibCatalog { + objects: LibObjectDef[]; + categories: { key: string; code: string; name: string; color: string; lw: number }[]; +} + +/** Parameter einer Instanz (Name → Zahl/Bool/Text), wie im Modell. */ +export type LibParams = Record; + +export type LibDetail = "grob" | "mittel" | "fein"; + +let cache: LibCatalog | null = null; + +/** Der Katalog (einmal aus dem Kern gelesen). */ +export function libCatalog(): LibCatalog { + if (!cache) { + try { + const c = JSON.parse(core().furniture_lib_catalog_json()) as Partial; + cache = { objects: c.objects ?? [], categories: c.categories ?? [] }; + } catch { + cache = { objects: [], categories: [] }; + } + } + return cache; +} + +export function libObjectDef(id: string): LibObjectDef | undefined { + return libCatalog().objects.find((o) => o.id === id); +} + +/** Gruppen in Palettenreihenfolge. */ +export function libGroups(): string[] { + const seen: string[] = []; + for (const o of libCatalog().objects) if (!seen.includes(o.group)) seen.push(o.group); + return seen; +} + +/** Vorgabe-Parameter eines Objekts (alle Schlüssel mit Vorgabewert). */ +export function libDefaultParams(def: LibObjectDef): LibParams { + const out: LibParams = {}; + for (const p of def.params) out[p.key] = p.kind === "flag" ? p.default >= 0.5 : p.default; + return out; +} + +/** Lokale Geometrie (Einfügepunkt = Ursprung, ohne Drehung) für Vorschau; der Kern erzeugt sie. */ +export function libGeometry(libId: string, params: LibParams, detail: LibDetail, seed = 0): Drawing2DGeom[] { + try { + return JSON.parse(core().furniture_lib_geometry_json(libId, JSON.stringify(params), detail, seed >>> 0)) as Drawing2DGeom[]; + } catch { + return []; + } +} + +type P = { x: number; y: number }; + +/** Geometrie als Linienzüge (Vorschau): Kreise, Bögen und Ellipsen abgetastet; `tf` bildet jeden Punkt ab. */ +export function libGeometryToPolys(geoms: Drawing2DGeom[], tf: (p: P) => P = (p) => p): { pts: P[]; closed: boolean }[] { + const out: { pts: P[]; closed: boolean }[] = []; + const arc = (c: P, rx: number, ry: number, a0: number, a1: number, closed: boolean) => { + const n = Math.max(8, Math.ceil((Math.abs(a1 - a0) / (2 * Math.PI)) * 32)); + const pts: P[] = []; + for (let i = 0; i <= n; i++) { + const a = a0 + ((a1 - a0) * i) / n; + pts.push(tf({ x: c.x + rx * Math.cos(a), y: c.y + ry * Math.sin(a) })); + } + out.push({ pts: closed ? pts.slice(0, -1) : pts, closed }); + }; + for (const g of geoms) { + switch (g.shape) { + case "line": + out.push({ pts: [tf(g.a), tf(g.b)], closed: false }); + break; + case "rect": + out.push({ + pts: [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }].map(tf), + closed: true, + }); + break; + case "polyline": + out.push({ pts: g.pts.map(tf), closed: g.closed }); + break; + case "circle": + arc(g.center, g.r, g.r, 0, 2 * Math.PI, true); + break; + case "ellipse": + arc(g.center, g.rx, g.ry, 0, 2 * Math.PI, true); + break; + case "arc": + arc(g.center, g.r, g.r, g.a0, g.a1 > g.a0 ? g.a1 : g.a1 + 2 * Math.PI, false); + break; + default: + break; + } + } + return out; +} + +/** Grenzen der Linienzüge (für den Massstab der Vorschau). */ +export function polysBounds(polys: { pts: P[] }[]): { minX: number; minY: number; maxX: number; maxY: number } | null { + let b: { minX: number; minY: number; maxX: number; maxY: number } | null = null; + for (const pl of polys) + for (const p of pl.pts) { + if (!b) b = { minX: p.x, minY: p.y, maxX: p.x, maxY: p.y }; + else { + b.minX = Math.min(b.minX, p.x); + b.minY = Math.min(b.minY, p.y); + b.maxX = Math.max(b.maxX, p.x); + b.maxY = Math.max(b.maxY, p.y); + } + } + return b; +} diff --git a/src/model/types.generated.ts b/src/model/types.generated.ts index 6240a45d..7c37a5bd 100644 --- a/src/model/types.generated.ts +++ b/src/model/types.generated.ts @@ -1193,6 +1193,18 @@ export type Drawing2DGeom = */ scale?: number; } + | { + shape: "libobj"; + libId: string; + at: Vec2; + rotation: number; + /** + * Parameter (Name → Zahl/Bool/Text), z. B. `w`, `d`, `n`, `mirror`, `mess`; fehlend = Vorgabe des Objekts. + */ + params?: Record; + /** Seed für zufällige Anteile (Unordnung der Stühle): gleicher Seed = gleiche Geometrie. */ + seed?: number; + } | { shape: "image"; /** Obere-linke Ecke der Bild-Box (Modell-Meter). */ diff --git a/src/panels/ObjectInfoPanel.tsx b/src/panels/ObjectInfoPanel.tsx index 71f3e32d..51f7edb1 100644 --- a/src/panels/ObjectInfoPanel.tsx +++ b/src/panels/ObjectInfoPanel.tsx @@ -34,6 +34,7 @@ import { TreeSection } from "./objectInfo/TreeSection"; import { CameraSection } from "./objectInfo/CameraSection"; import { ViewShadowsInfo, MeasurementSection } from "./objectInfo/InfoBlocks"; import { DimensionField, RotateField } from "./objectInfo/fields"; +import { LibObjectSection } from "./objectInfo/LibObjectSection"; import { elementDimensions } from "./objectInfo/elementDims"; import { InfoGroups, hasInfoGroups } from "./objectInfo/InfoGroups"; import { infoGroupFrame, useInfoGroupState } from "./objectInfo/InfoGroup"; @@ -262,6 +263,9 @@ export function ObjectInfoPanel({ showPlacement = true }: { showPlacement?: bool {len(d.value).toFixed(u.digits)} {u.suffix} )) + ) : rawDrawing?.geom.shape === "libobj" ? ( + // [253] Bibliotheks-Objekt: Masse und Parameter generisch aus dem Katalog. + ) : ( <> libGeometryToPolys(libGeometry(def.id, libDefaultParams(def), "grob", 1), (p) => ({ x: p.x, y: -p.y })), + [def], + ); + const b = polysBounds(polys); + if (!b) return ; + const w = Math.max(b.maxX - b.minX, 1e-3); + const h = Math.max(b.maxY - b.minY, 1e-3); + const pad = 3; + const k = (SIZE - 2 * pad) / Math.max(w, h); + const tx = (x: number) => pad + (x - b.minX) * k + ((SIZE - 2 * pad) - w * k) / 2; + const ty = (y: number) => pad + (y - b.minY) * k + ((SIZE - 2 * pad) - h * k) / 2; + return ( + + ); +} + +export function ObjectLibraryPanel() { + const onRunCommand = usePanelHostAction("onRunCommand"); + const catalog = useMemo(() => libCatalog(), []); + const groups = useMemo(() => libGroups(), []); + + const place = (def: LibObjectDef) => { + setActiveLibObject(def.id, libDefaultParams(def)); + onRunCommand("libobj"); + }; + + if (catalog.objects.length === 0) { + return
{t("lib.empty")}
; + } + return ( +
+
{t("lib.hint")}
+ {groups.map((g) => ( +
+ {t(`lib.g.${g}` as TranslationKey)} +
+ {catalog.objects + .filter((o) => o.group === g) + .map((o) => { + const name = t(`lib.o.${o.id.replace(/^lib:/, "")}` as TranslationKey); + return ( + + ); + })} +
+
+ ))} +
+ ); +} + +/** Tab-Symbol: Stuhl in der Draufsicht. */ +export function ObjectLibraryTabIcon() { + return ( + + ); +} diff --git a/src/panels/README.md b/src/panels/README.md index 1df3ea24..ebfc9386 100644 --- a/src/panels/README.md +++ b/src/panels/README.md @@ -28,6 +28,7 @@ Kern; hier stehen Eingabe und Darstellung. Zustand über den Store (`src/state`) | `SitePanel.tsx` | Aktionen zu Gelände und Lage (Import, Gelände erzeugen, Baugrube; keine Import-Liste, [181]), mit `SiteRulesSection.tsx` (Baurecht), `SunStudySection.tsx` (Schatten) und `PointCloudSection.tsx` | | `BcfPanel.tsx`, `ClashPanel.tsx` | BCF-Themen und Kollisionsliste; Sitzungszustand in `bcfSession.ts` und `clashSession.ts` | | `HistoryPanel.tsx` | Undo-Verlauf mit Sprung auf einen Schritt | +| `ObjectLibraryPanel.tsx` | Palette „Objekte" ([253]): Standard-Symbole 2D nach Gruppen, Klick startet den Befehl `libobj`; Parameter später in `objectInfo/LibObjectSection.tsx` | ## Reine Helfer diff --git a/src/panels/builtinPanels.tsx b/src/panels/builtinPanels.tsx index 30340b6f..8b507dec 100644 --- a/src/panels/builtinPanels.tsx +++ b/src/panels/builtinPanels.tsx @@ -24,6 +24,7 @@ import { SitePanel } from "./SitePanel"; import { RoomBalancePanel } from "./RoomBalancePanel"; import { ElementTreePanel, ElementsTabIcon } from "./ElementTreePanel"; import { ViewSnapshotsPanel, ViewSnapshotsTabIcon } from "./ViewSnapshotsPanel"; +import { ObjectLibraryPanel, ObjectLibraryTabIcon } from "./ObjectLibraryPanel"; import { LayoutsPanel, LayoutsTabIcon } from "./LayoutsPanel"; import { BcfPanel } from "./BcfPanel"; import { ClashPanel } from "./ClashPanel"; @@ -57,6 +58,7 @@ export const BUILTIN_PANEL_IDS = { clash: "clash", history: "history", objectSettings: "object-settings", + objectLibrary: "object-library", } as const; // Werkzeug-Palette (Symbol + Name je Werkzeug, ArchiCAD/Vectorworks-Stil). @@ -68,6 +70,15 @@ registerPanel({ render: () => , }); +// Objekt-Bibliothek 2D ([253]): Palette der Standard-Symbole (Sanitär, Küche, Möbel …) zum Einsetzen. +registerPanel({ + id: BUILTIN_PANEL_IDS.objectLibrary, + title: "nav.objects", + icon: , + hasDisplayMode: false, + render: () => , +}); + // Attribute-Palette (Stift/Füllung/Strichstärke der Auswahl, Vectorworks-Stil). registerPanel({ id: BUILTIN_PANEL_IDS.attributes, diff --git a/src/panels/layout.ts b/src/panels/layout.ts index cc52c031..e33e57a1 100644 --- a/src/panels/layout.ts +++ b/src/panels/layout.ts @@ -45,7 +45,8 @@ import type { // Attribute darunter (Vectorworks-Bild aus v6, vor dem Ribbon-UI-Phase-3-Bump). // v13 ([238]): rechts oben (Objekt-Info/Flächenbilanz) bekommt mehr Höhe: Gewichte 1,6 : 1 statt 1 : 1,5 (die // Flächenbilanz mit Raumprogramm war nur ~300 px hoch). Die Höhe merkt sich der Gruppen-Splitter (`resizeGroups`). -export const LAYOUT_VERSION = 13; +// v14 ([253]): Objekt-Bibliothek ("object-library") als Tab neben den Werkzeugen links oben. +export const LAYOUT_VERSION = 14; /** localStorage-Schlüssel des zuletzt benutzten Layouts. */ const CURRENT_KEY = "cad.layout"; @@ -73,7 +74,7 @@ const NAMED_PREFIX = "cad.layouts."; // der Attribute-Palette darunter (Vectorworks-Bild). Das Ribbon-Band bleibt als // Reiter erreichbar, ist aber nicht mehr der primäre Weg zu den Werkzeugen. const DEFAULT_LEFT_GROUPS: DockGroup[] = [ - { tabs: ["tools"], activeTab: "tools", weight: 1 }, + { tabs: ["tools", "object-library"], activeTab: "tools", weight: 1 }, { tabs: ["attributes"], activeTab: "attributes", weight: 1 }, ]; const DEFAULT_RIGHT_GROUPS: DockGroup[] = [ diff --git a/src/panels/objectInfo/LibObjectSection.tsx b/src/panels/objectInfo/LibObjectSection.tsx new file mode 100644 index 00000000..692136b7 --- /dev/null +++ b/src/panels/objectInfo/LibObjectSection.tsx @@ -0,0 +1,95 @@ +// Objekt-Info eines Bibliotheks-Objekts ([253], `Drawing2DGeom.shape === "libobj"`): die Felder entstehen generisch +// aus der Parameterliste des Katalogs (Länge, Anzahl, Ja/Nein, Anteil) — kein Formular je Objekt, damit eigene +// Objekte [254] ohne Änderung hier dazukommen. Änderungen laufen als Ops über `updateDrawing2D` (ein Undo-Schritt je +// Eingabe). Unbekannte Objekt-Id: nur ein Hinweis (die Plandarstellung zeigt einen Platzhalter-Rahmen). + +import { t } from "../../i18n"; +import type { TranslationKey } from "../../i18n"; +import { useStore } from "../../state/appStore"; +import type { Drawing2D } from "../../model/types"; +import { libDefaultParams, libObjectDef, type LibObjectDef, type LibParamDef, type LibParams } from "../../model/furnitureLib"; +import { DimensionField } from "./fields"; + +type LibGeom = Extract; + +/** Beschriftung eines Parameters; je Gruppe/Form spezifischer (Stühle, Module, Durchmesser). */ +function paramLabel(def: LibObjectDef, p: LibParamDef): TranslationKey { + if (p.key === "n" && def.group === "kitchen") return "lib.p.n.kitchen"; + if (p.key === "n" && def.group === "tables") return "lib.p.n.tables"; + if (p.key === "w" && !def.params.some((q) => q.key === "d")) return "lib.p.diameter"; + return `lib.p.${p.key}` as TranslationKey; +} + +export function LibObjectSection({ drawing, geom }: { drawing: Drawing2D; geom: LibGeom }) { + const update = useStore((s) => s.updateDrawing2D); + const def = libObjectDef(geom.libId); + if (!def) { + return ( +
+ + {t("lib.unknown")}: {geom.libId} + +
+ ); + } + const values: LibParams = { ...libDefaultParams(def), ...(geom.params ?? {}) }; + const set = (key: string, v: number | boolean) => update(drawing.id, { geom: { ...geom, params: { ...(geom.params ?? {}), [key]: v } } }); + const name = t(`lib.o.${def.id.replace(/^lib:/, "")}` as TranslationKey); + + return ( +
+
+ {t("lib.section")} + {name} +
+ {def.params.map((p) => { + const label = t(paramLabel(def, p)); + const v = values[p.key]; + if (p.kind === "length") { + return set(p.key, Math.min(p.max, Math.max(p.min, x)))} />; + } + if (p.kind === "flag") { + return ( + + ); + } + if (p.kind === "fraction") { + return ( + + ); + } + return ( + + ); + })} + {def.seeded && ( +
+ +
+ )} +
+ ); +}