[253] Objektbibliothek 2D: parametrische Standard-Symbole mit Palette
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.
This commit is contained in:
30 files changed
+2142
-17
No files matched your search
@@ -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
|
||||
|
||||
@@ -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<Drawing2DGeom>`: 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.<id>`, `lib.g.<gruppe>`, `lib.p.<parameter>`. |
|
||||
|
||||
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
|
||||
|
||||
@@ -33,6 +33,7 @@ Neues Modul: `<modul>.rs` und `mod` in `lib.rs`, Bindungen in `web/<modul>.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
|
||||
|
||||
@@ -880,6 +880,30 @@ fn block_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
)
|
||||
}
|
||||
|
||||
/// [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<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
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<String, Value>, 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(),
|
||||
|
||||
@@ -202,13 +202,21 @@ pub fn mv_geom(g: &Value, xf: &Xf) -> Option<Value> {
|
||||
}
|
||||
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<Value> {
|
||||
}
|
||||
"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,
|
||||
})
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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 {
|
||||
|
||||
@@ -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, &[]);
|
||||
|
||||
@@ -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<Vec<(f64, f64)>> {
|
||||
}
|
||||
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)?;
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -599,6 +599,25 @@ pub enum Drawing2DGeom {
|
||||
#[ts(optional)]
|
||||
scale: Option<f64>,
|
||||
},
|
||||
/// 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<string, number | boolean | string>")]
|
||||
params: Option<std::collections::BTreeMap<String, serde_json::Value>>,
|
||||
/// 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<u32>,
|
||||
},
|
||||
#[serde(rename = "image")]
|
||||
Image {
|
||||
/// Obere-linke Ecke der Bild-Box (Modell-Meter).
|
||||
|
||||
@@ -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<Primitive>
|
||||
pub fn block_footprints(c: &Ctx) -> Vec<Vec<[f64; 2]>> {
|
||||
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<Primitive> {
|
||||
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<f64> = 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": [
|
||||
|
||||
@@ -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::<crate::model::Drawing2DGeom>(g.clone()).ok().as_ref().and_then(crate::grid::Spec::of) {
|
||||
for ax in spec.axes() {
|
||||
|
||||
@@ -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<String, Value>) -> (Vec<Value>, HashMap<String, String>
|
||||
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::<Vec<_>>(), ["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::<Vec<_>>(), ["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));
|
||||
|
||||
@@ -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<String, serde_json::Value> = 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())
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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` |
|
||||
|
||||
@@ -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["geom"], { shape: "libobj" }>): 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)));
|
||||
});
|
||||
});
|
||||
@@ -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 }],
|
||||
};
|
||||
@@ -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<string, Command> = {
|
||||
georef: georefCommand,
|
||||
block: blockCommand,
|
||||
defblock: defblockCommand,
|
||||
libobj: libobjCommand,
|
||||
tracemove: traceMoveCommand,
|
||||
tracerotate: traceRotateCommand,
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
@@ -4234,4 +4234,83 @@ export const en: Record<TranslationKey, string> = {
|
||||
"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",
|
||||
};
|
||||
@@ -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>`). */
|
||||
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<string, number | boolean | string>;
|
||||
|
||||
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<LibCatalog>;
|
||||
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;
|
||||
}
|
||||
@@ -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<string, number | boolean | string>;
|
||||
/** 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). */
|
||||
|
||||
@@ -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
|
||||
<span className="objinfo-fval">{len(d.value).toFixed(u.digits)} {u.suffix}</span>
|
||||
</div>
|
||||
))
|
||||
) : rawDrawing?.geom.shape === "libobj" ? (
|
||||
// [253] Bibliotheks-Objekt: Masse und Parameter generisch aus dem Katalog.
|
||||
<LibObjectSection drawing={rawDrawing} geom={rawDrawing.geom} />
|
||||
) : (
|
||||
<>
|
||||
<DimensionField
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
// Dock-Panel „Objekte" ([253]) — Palette der Standard-Objektbibliothek 2D: Gruppen (Sanitär, Küche, Tische, …)
|
||||
// mit Vorschau-Symbol je Objekt. Klick wählt das Objekt und startet den Befehl `libobj` (Einfügepunkt klicken,
|
||||
// R = drehen, M = spiegeln). Der Katalog kommt aus dem Rust-Kern; die Vorschau zeichnet der Kern (grob).
|
||||
|
||||
import { useMemo } from "react";
|
||||
import { t } from "../i18n";
|
||||
import type { TranslationKey } from "../i18n";
|
||||
import { usePanelHostAction } from "./host";
|
||||
import { setActiveLibObject } from "../commands/cmds/libobj";
|
||||
import {
|
||||
libCatalog,
|
||||
libDefaultParams,
|
||||
libGeometry,
|
||||
libGeometryToPolys,
|
||||
libGroups,
|
||||
polysBounds,
|
||||
type LibObjectDef,
|
||||
} from "../model/furnitureLib";
|
||||
|
||||
const SIZE = 44;
|
||||
|
||||
/** Vorschau: Linien des Objekts (grob) als kleines SVG, Plan-y nach oben. */
|
||||
function Preview({ def }: { def: LibObjectDef }) {
|
||||
const polys = useMemo(
|
||||
() => libGeometryToPolys(libGeometry(def.id, libDefaultParams(def), "grob", 1), (p) => ({ x: p.x, y: -p.y })),
|
||||
[def],
|
||||
);
|
||||
const b = polysBounds(polys);
|
||||
if (!b) return <svg width={SIZE} height={SIZE} aria-hidden="true" />;
|
||||
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 (
|
||||
<svg width={SIZE} height={SIZE} viewBox={`0 0 ${SIZE} ${SIZE}`} fill="none" stroke="currentColor" strokeWidth={1} strokeLinejoin="round" aria-hidden="true" focusable="false">
|
||||
{polys.map((pl, i) => {
|
||||
const d = pl.pts.map((p, j) => `${j ? "L" : "M"}${tx(p.x).toFixed(2)} ${ty(p.y).toFixed(2)}`).join(" ") + (pl.closed ? "Z" : "");
|
||||
return <path key={i} d={d} />;
|
||||
})}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
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 <div style={{ padding: 10, fontSize: 12, color: "var(--muted)" }}>{t("lib.empty")}</div>;
|
||||
}
|
||||
return (
|
||||
<div className="objlib-panel" style={{ overflowY: "auto", padding: "6px 8px" }}>
|
||||
<div style={{ fontSize: 11, color: "var(--muted)", marginBottom: 6 }}>{t("lib.hint")}</div>
|
||||
{groups.map((g) => (
|
||||
<details key={g} open={g === groups[0]} style={{ marginBottom: 4 }}>
|
||||
<summary style={{ cursor: "pointer", fontSize: 12, fontWeight: 600, padding: "3px 0" }}>{t(`lib.g.${g}` as TranslationKey)}</summary>
|
||||
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(72px, 1fr))", gap: 4, padding: "4px 0" }}>
|
||||
{catalog.objects
|
||||
.filter((o) => o.group === g)
|
||||
.map((o) => {
|
||||
const name = t(`lib.o.${o.id.replace(/^lib:/, "")}` as TranslationKey);
|
||||
return (
|
||||
<button
|
||||
key={o.id}
|
||||
type="button"
|
||||
title={name}
|
||||
aria-label={name}
|
||||
onClick={() => place(o)}
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
gap: 2,
|
||||
padding: "4px 2px",
|
||||
border: "1px solid var(--border)",
|
||||
borderRadius: 4,
|
||||
background: "var(--field-bg)",
|
||||
color: "var(--ink)",
|
||||
cursor: "pointer",
|
||||
font: "inherit",
|
||||
}}
|
||||
>
|
||||
<Preview def={o} />
|
||||
<span style={{ fontSize: 10, lineHeight: 1.15, textAlign: "center", overflowWrap: "anywhere" }}>{name}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</details>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Tab-Symbol: Stuhl in der Draufsicht. */
|
||||
export function ObjectLibraryTabIcon() {
|
||||
return (
|
||||
<svg width={16} height={16} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={1.4} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" focusable="false">
|
||||
<rect x="3" y="3" width="10" height="10" rx="1" />
|
||||
<path d="M3 6h10" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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: () => <ToolsPanel />,
|
||||
});
|
||||
|
||||
// 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: <ObjectLibraryTabIcon />,
|
||||
hasDisplayMode: false,
|
||||
render: () => <ObjectLibraryPanel />,
|
||||
});
|
||||
|
||||
// Attribute-Palette (Stift/Füllung/Strichstärke der Auswahl, Vectorworks-Stil).
|
||||
registerPanel({
|
||||
id: BUILTIN_PANEL_IDS.attributes,
|
||||
|
||||
@@ -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[] = [
|
||||
|
||||
@@ -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<Drawing2D["geom"], { shape: "libobj" }>;
|
||||
|
||||
/** 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 (
|
||||
<div className="objinfo-field">
|
||||
<span className="objinfo-fval objinfo-muted">
|
||||
{t("lib.unknown")}: {geom.libId}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
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 (
|
||||
<div data-testid="libobj-section">
|
||||
<div className="objinfo-field">
|
||||
<span className="objinfo-flabel">{t("lib.section")}</span>
|
||||
<span className="objinfo-fval">{name}</span>
|
||||
</div>
|
||||
{def.params.map((p) => {
|
||||
const label = t(paramLabel(def, p));
|
||||
const v = values[p.key];
|
||||
if (p.kind === "length") {
|
||||
return <DimensionField key={p.key} label={label} value={Number(v)} min={p.min} step={p.step} digits={3} onCommit={(x) => set(p.key, Math.min(p.max, Math.max(p.min, x)))} />;
|
||||
}
|
||||
if (p.kind === "flag") {
|
||||
return (
|
||||
<label className="objinfo-field" key={p.key}>
|
||||
<span className="objinfo-flabel">{label}</span>
|
||||
<input type="checkbox" checked={v === true || Number(v) >= 0.5} onChange={(e) => set(p.key, e.target.checked)} />
|
||||
</label>
|
||||
);
|
||||
}
|
||||
if (p.kind === "fraction") {
|
||||
return (
|
||||
<label className="objinfo-field" key={p.key}>
|
||||
<span className="objinfo-flabel">{label}</span>
|
||||
<input type="range" min={p.min} max={p.max} step={p.step} value={Number(v)} onChange={(e) => set(p.key, Number(e.target.value))} />
|
||||
<span className="objinfo-unit">{Math.round(Number(v) * 100)} %</span>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<label className="objinfo-field" key={p.key}>
|
||||
<span className="objinfo-flabel">{label}</span>
|
||||
<input
|
||||
className="objinfo-input"
|
||||
type="number"
|
||||
min={p.min}
|
||||
max={p.max}
|
||||
step={p.step}
|
||||
value={Number(v)}
|
||||
onChange={(e) => {
|
||||
const x = Math.round(Number(e.target.value));
|
||||
if (Number.isFinite(x)) set(p.key, Math.min(p.max, Math.max(p.min, x)));
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
{def.seeded && (
|
||||
<div className="objinfo-field">
|
||||
<button type="button" className="objinfo-btn" onClick={() => update(drawing.id, { geom: { ...geom, seed: (Math.random() * 0xffffffff) >>> 0 } })}>
|
||||
{t("lib.reroll")}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user