Merge [272] Varianten (mit Umbau-Panel zusammengeführt, Import selectionRenovationIds aus state/renovationHook)

This commit is contained in:
Claude committed 2026-11-17 13:02:33 +00:00
commit 5f0ae6a523
73 files changed
+2979 -100

No files matched your search

+1 -1
View File
@@ -688,7 +688,7 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC.
Grünfläche nur per Eingabe, Grenzabstand als Verstossfläche statt kleinster Abstand, Fassadenhöhe nur über ±0.00, Mac/Tauri nicht geprüft. · S
UI-Review 14.11.: Flächenbilanz-Panel: Tabellen brechen Text/Köpfe um (Nachweis- und Grundlagen-Tabelle jetzt in 340 px ganz sichtbar, de/en); die breite Flächentabelle (11 Spalten) scrollt nicht mehr: in der schmalen Dock-Spalte (Container ≤ 460 px) wird jede Zeile zur Karte (Geschoss oben, Kennwerte 5 je Zeile mit Kopf über der Zahl; `.area-table.wide`, de/en bei 340 px vollständig lesbar, CSV/PDF unverändert); Fenster-/Türliste (15–20 Spalten) und Raumbuch (12–16) nutzen dasselbe Muster als gemeinsame Komponente `src/panels/CardTable.tsx` (Köpfe per Effekt als `data-label`, lange Textzellen belegen 2–3 Rasterspalten, leere Zellen entfallen; Container-Query ≤ 460 px, sonst normale Tabelle; 14.11. spät, Chromium de/en, 303 px Dock, kein waagrechtes Scrollen mehr; Kosten- und Bauteil-Tabelle (≤ 6 Spalten) scrollten nicht und blieben). Icon-Schrift „settings“ als Text: Schrift ist lokal gebündelt (npm `material-symbols`, `main.tsx`, NOTICE [117]) — Ursache war nur der verlinkte `node_modules` im Worktree (Vite `/@fs` 403), kein App-Fehler. Blatt-Tabelle Baurecht (14.11. spät, als Primitive in Chromium angesehen, nicht in der Blatt-Ansicht der App): Kopf „Reserve (+) / Überschr. (−)“ und „Zulässig“/„Erfüllt“ wurden mit „…“ gekürzt → kurzer Blatt-Kopf „Reserve“, Spaltenbreiten neu (Köpfe passen ab 100 mm Rahmenbreite, Test `baurecht_tabelle_koepfe_passen`); lange Zeilentexte kürzen bei < 150 mm weiterhin mit „…“ (kein Umbruch im Blatt-Tabellenkern).
- ○ **[272]** Varianten wie Archicad „Design Options“ (17.11., Wunsch Maintainer, für 1.0). Variantensätze (z. B. „Dachform“, „Fassade“, „Grundriss OG“) mit Varianten (A, B, C …); jedes Element gehört zum Hauptmodell oder zu genau einer Variante eines Satzes; je Reiter/Ausschnitt/Layout-Viewport eine Variantenkombination (Vorgabe: Hauptvariante je Satz); Kennzahlen/Kosten/Baurecht je Kombination und als Vergleichstabelle nebeneinander; Blatt mit mehreren Viewports derselben Ansicht in verschiedenen Kombinationen; Element in Variante kopieren/verschieben, Variante übernehmen (ins Hauptmodell, andere löschen). Gleiche Filter-Infrastruktur wie der Umbaufilter [271] (ein Kern-Ort „Element sichtbar in Ansicht“), Start nach [271]. Exporte (IFC/DXF) mit der Kombination der Ansicht. Ersetzt den Ausschluss „Varianten nebeneinander“ in den Release-Notes. · M–L
- ◐ **[272]** Varianten wie Archicad „Design Options“ (17.11., Wunsch Maintainer, für 1.0). **Stand 17.11.:** Modell (Rust, gen:types, KNOWN_KEYS): `Project.designOptionSets` (Sätze, Varianten, Hauptvariante), `designOption: {set, option}` an Wand, Öffnung, Decke, Dach, Treppe, Stütze, Körper, Raum, 2D-Element (samt Bibliotheksobjekt), Kombination `designOptions` an Ebene/Vorlage/Ausschnitt/Layout-Viewport. Sichtbarkeit im EINEN Kern-Ort `renovation::View` (Kombination neben dem Umbaufilter, `doc/ARCHITEKTUR.md` 3.9): Grundriss, Schnitt, Ansicht, Vektor-Axo, 3D-Fenster (Kombination der aktiven Ebene), Kennzahlen, Kosten, Baurecht, Raumbuch, DXF (über den Plan), IFC/Netz-Exporte (Hauptvarianten bzw. JSON-Text), PDF/Blatt (Viewport-Kombination + Titelzusatz). Kern `design_options.rs`: Übernehmen, Satz/Variante löschen, Zuweisen, In Variante kopieren (je ein Undo-Schritt), Zeichen-Variante neuer Elemente, Vergleich (Kreuzprodukt ≤ 24). Oberfläche: Panel „Varianten“ (Kombination, neue Elemente zeichnen in …, Zuweisen/Kopieren, Sätze verwalten, Übernehmen, Vergleich), Chip „Variante: …“ in der Statusleiste (öffnet das Panel, Überlauf „⋯“), Objekt-Info „Variante“, Ressourcen-Tab „Varianten“, Befehle `variante`/`variantekopieren`, Varianten-Vergleich + CSV in der Flächenbilanz, Viewport-Wahl je Satz im Blatt; Vorlage „Beispiel Varianten“ (CLI `:varianten`); CLI `--options`, `designoptions`. Tests: Kern `design_options_tests.rs` (13), Robustheit, vitest `model/designOptions.test.ts`, `commands/cmds/designOption.test.ts`, e2e `designOptions272.spec.ts` (2× grün, Port 5195); Bilder `doc/review-272/`. **Offen:** Blatt-Tabelle (`sheet_table.rs`) für den Vergleich fehlt (nur Panel + CSV); App-IFC-Export und Cycles-Szene nehmen die Hauptvarianten, nicht die Kombination der Ansicht; Variantensatz-Wahl in Ansichtsvorlagen/Ausschnitten nur im Modell (keine Oberfläche ausser Ebene und Viewport); nicht geprüft, ob Wandanschlüsse im Grundriss Wände anderer Varianten noch berücksichtigen (gleicher Weg wie die Regel „Ausblenden“); 3D-Bild und Tauri/Mac nicht geprüft (Prüfschritt `doc/RELEASE-1.0.md` 13.38). · M–L
### Phase 4 (4.–12.12.): Härten und veröffentlichen
- Nur noch Fehler aus dem Referenz-Ablauf; Leistung mit grossen Kontext-Importen; keine neuen Funktionen.
- Release 1.0.0: Tag, signierte Pakete, Release-Notes (ehrlich: was nicht geht), Download-Seite.
+19
View File
@@ -476,6 +476,25 @@ Vektor-Axo (`axo_plan_buf`), 3D (`model3dParts` mit `text.renovation`, ohne Teil
(`text` = Filter-Id), DXF (`dxf.rs::renovation_layers`) und IFC (`ifc_data.rs::renovation_props`). Neue Bauteile der Zeichenbefehle
bekommen den Zeichen-Status über `commands::stamp_renovation` (Anfrage-Feld `renovation`, gesetzt in `projectSlice.applyCmd`).
### 3.9 Varianten ([272])
Wie Archicads „Design Options“: `Project.designOptionSets` (Sätze mit Varianten, `primary` = Hauptvariante), an Wand, Öffnung, Decke,
Dach, Treppe, Stütze, Körper, Raum und 2D-Element `designOption: {set, option}` (fehlt = Hauptmodell), Kombination `designOptions`
(Satz-Id → Varianten-Id) an `DrawingLevel`, `ViewTemplate`, `ViewSnapshot` und `LayoutViewport`. **Keine zweite Sichtbarkeitslogik:**
die Kombination ist Teil der `renovation::View` (3.8) — `View::with`/`for_level` lösen sie auf (Hauptvarianten, darüber die gespeicherte
Wahl der Ebene/des Ausschnitts, darüber die Anfrage `designOptions` als Text „Dachform=B,…“ oder Objekt), `View::resolve` legt
Elemente anderer Varianten (Öffnungen ausgeblendeter Wände mit) in `hidden`; eine `View` gibt es darum auch ohne Umbaufilter, sobald
das Projekt Elemente in Varianten hat (`design_options::active`, sonst alles wie vorher). So wirkt sie ohne eigene Anbindung überall,
wo der Umbaufilter wirkt: Grundriss (`Ctx.hidden`, 2D-Elemente über `drawings::on_floor`), Schnitt/Ansicht (`LevelSpec.design_options`),
Axo, 3D (`model3dParts` mit Text; das 3D-Fenster nimmt die Kombination der aktiven Ebene, ohne Teil-Cache), Kennzahlen/Kosten/Baurecht/
Raumbuch/IFC/Netz-Exporte (`queries.rs::options_state`: Kombination des JSON-Texts, sonst Hauptvarianten). Blatt-Viewports:
`sheet_viewports::viewport_snapshot`/`snapshot_project` (Rust) bzw. `viewportPlan.ts::viewportDesignOptions` (TS), Titelzusatz
`posterTemplates.ts::viewportVariantSuffix`. Bearbeiten: `design_options.rs` (Wurzel-Abfragen `designOptionAcceptOps`, `…DeleteOps`,
`…AssignOps`, `…CopyOps`; neue Elemente der Zeichenbefehle über `stamp_ops`, Anfrage-Feld `designOption` aus `projectSlice.applyCmd`),
Vergleich `designOptionCompare` (Kreuzprodukt, höchstens 24 Kombinationen). Oberfläche: Panel „Varianten“ (`panels/DesignOptionsPanel.tsx`),
Chip in der Statusleiste, Objekt-Info `DesignOptionField`, Ressourcen-Tab, Befehle `variante`/`variantekopieren`; CLI `--options`.
---
## 4. Schnitt
+24
View File
@@ -374,6 +374,30 @@ Fenster zugemauert, neues Fenster in der Westwand, Anbau in der zweiten Etappe).
`Pset_WallCommon` (NEW, EXISTING, DEMOLISH) und die Etappe in `Dossier_Umbau`. Kommandozeile: `--renovation umbauplan`
(und `--phase`) bei plan, section, elevation, axo, model3d und kennzahlen.
## 13. Varianten
Für Wettbewerb und Vorprojekt lassen sich Teile des Entwurfs in Varianten zeichnen und nebeneinander vergleichen (wie die
Design Options in Archicad). Ein Variantensatz (z. B. Dachform) hat Varianten (A, B, …); jedes Element gehört zum
„Hauptmodell“ oder zu genau einer Variante. Zum Ausprobieren: *Datei → Neu aus Vorlage: Beispiel Varianten* (Sätze Dachform:
Flachdach/Satteldach und Fassade: Lochfenster/Bandfenster).
- **Panel:** ein Klick auf den Knopf Variante rechts in der Statusleiste (nur mit Variantensätzen; bei wenig Platz unter ⋯)
öffnet das Panel „Varianten“. Dort: „Kombination dieser Ansicht“ (je Satz eine Variante, Vorgabe die „Hauptvariante“), „Neue
Elemente zeichnen in“ (neue Bauteile und 2D-Elemente gehören dieser Variante), die Auswahl einer Variante „Zuweisen“ oder
„Kopieren in“ eine Variante, die Sätze verwalten („Satz hinzufügen“, umbenennen, löschen) und „Übernehmen“.
- **Kombination:** gehört zur Ebene wie der Umbaufilter, also je Reiter (Geschoss, Schnitt, Ansicht) eigen und mit Undo; der
Grundriss, der Schnitt, die Ansicht, die Axonometrie und das 3D zeigen nur die gewählten Varianten. Ausschnitte merken die
Kombination; ein Viewport auf dem Blatt kann dieselbe Ansicht in einer anderen Kombination zeigen (je Satz eine Wahl im
Viewport, Vorgabe „wie Ausschnitt“) und trägt dann den Variantennamen unter dem Plan.
- **Zuweisen:** Elemente wählen, in der **Objekt-Info** (auch Taste T) das Feld „Variante“; bei Mehrfachauswahl in einem Schritt.
Oder die Befehle `variante` und `variantekopieren` (Ziel z. B. Dachform=B, Variantenname oder Nummer; H = Hauptmodell).
- **Übernehmen:** „Übernehmen“ bei einer Variante legt ihre Elemente ins Hauptmodell und löscht die übrigen Varianten des Satzes
samt Elementen (ein Undo-Schritt). Der Papierkorb löscht eine Variante bzw. einen Satz samt Elementen.
- **Vergleich:** Panel Flächenbilanz (oder „Vergleich öffnen“ im Panel „Varianten“): der „Varianten-Vergleich“ zeigt GF, HNF,
GV, Fussabdruck, AZ, ÜZ und Kosten je Kombination nebeneinander, mit „Vergleich als CSV“.
- **Exporte:** DXF, IFC, PDF und Kennzahlen nehmen die Kombination der Ansicht bzw. die Hauptvarianten. Kommandozeile:
--options "Dachform=B,Fassade=A" bei allen Ausgaben, dossier-cli … designoptions für den Vergleich (--format csv).
---
## Noch offen
+1
View File
@@ -179,6 +179,7 @@ und Befunde in `TODO.md` eintragen.
| 13.35 | **Version und Build ([261]):** `npm run tauri:build`, App im Finder wählen → Informationen; Dossier → Über dossier; Statusleiste rechts unten | Finder: Version 1.0.0-beta.1 (Build 261115.N in der Bundle-Version); Über-Dialog „1.0.0-beta.1 (Build …)“ gleiche Nummer; Statusleiste „Build …“ |
| 13.36 | **Blickrichtungen seitenrichtig ([270]):** Musterhaus komplex (Erker im Osten = Plan rechts); 3D-Fenster (Metal) nacheinander Oben, Vorne, Rechts, Isometrie Südost, Südwest, Nordost, Nordwest; dann Ausschnitt „Axonometrie Südost“ auf einem Blatt und `rendering` mit Kamera „Südost“; im 3D Maus nach rechts ziehen (Orbit), rechte Maustaste ziehen (Pan), Begehen mit D, Umschauen; Gelände/Kataster-Kontext (swisstopo) und eine Punktwolke laden; Luftbild drapieren | Oben = Grundriss (Norden oben, Erker rechts, nicht kopfüber); Vorne = Südfassade mit Erker rechts; Rechts = Ostfassade; Isometrie Südost zeigt Süd- und Ostfassade, Erker rechts — gleich wie Axonometrie Südost, Cycles „Südost“ und die Ansicht Süd; Orbit dreht das Modell mit der Maus, Pan folgt der Maus, D läuft nach rechts; Gelände, Baugrube, Verbau, Punktwolke und Luftbild liegen deckungsgleich unter dem Haus (nicht an y = 0 gespiegelt), Strassen/Gebäude des Kontexts seitenrichtig; Schatten fallen auf die richtige Seite (Nachmittag: nach Osten) |
| 13.37 | **Umbau ([271]):** *Datei → Neu aus Vorlage: Beispiel Umbau*; Statusleiste „Umbau“ → Umbaufilter nacheinander Bestand, Abbruch, Neubau, Umbauplan, Endzustand (Erdgeschoss, dann Schnitt A); Wand W9 wählen, Objekt-Info „Umbau“ auf Neu, ⌘Z; Zeichen-Status Neu, eine Wand zeichnen; Flächenbilanz „Zustand“ Bestand/Endzustand; PDF und DXF des Umbauplans | Bestand ohne Anbau und neues Fenster (Westwand zu); Abbruch: Zwischenwand gelb gestrichelt, gelbes Stück im neuen Fenster; Neubau: Anbau und neue Tür rot, Nordfenster rot zugemauert; Umbauplan alle drei Farben; Endzustand ohne Farben; Schnitt gleich; neue Wand rot im Umbauplan; ⌘Z nimmt die Status-Änderung in einem Schritt zurück; GF im Endzustand grösser; DXF mit Layern „…_Abbruch“/„…_Neu“; am Bildschirm (Metal) wie im PDF |
| 13.38 | **Varianten ([272]):** *Datei → Neu aus Vorlage: Beispiel Varianten*; Knopf „Variante“ in der Statusleiste → Panel „Varianten“; Kombination Fassade B, dann Dachform B (Erdgeschoss, Schnitt A, Ansicht Süd, 3D); Wand W1 wählen, „Zuweisen“ zu Fassade: B, ⌘Z; Satz hinzufügen; „Vergleich öffnen“ und „Vergleich als CSV“; Blatt mit zwei Viewports desselben Ausschnitts, einer mit Dachform B; „Übernehmen“ bei Dachform B, ⌘Z; PDF/DXF/IFC in Kombination B | Fassade B: Bandfenster statt Nordfenster; Dachform B: Satteldach statt Flachdach in Schnitt, Ansicht und 3D; ⌘Z nimmt Zuweisen bzw. Übernehmen in einem Schritt zurück; Vergleich mit 4 Zeilen, GV und Kosten bei Satteldach höher; zweiter Viewport mit Titelzusatz „Dachform B Satteldach“; Exporte zeigen nur die gewählte Variante |
## 14. Datensicherheit auf dem Mac ([116], Audit 14.11.)
+9 -1
View File
@@ -90,6 +90,14 @@ in `doc/KURZANLEITUNG.md`):
Etappe; neue Öffnungen in Bestandswänden zeigen das abgebrochene Mauerwerk, zugemauerte Öffnungen die Ausfachung. Gilt in Grundriss,
Schnitt, Ansicht, Vektor-Axonometrie, Kennzahlen (Bestand/Endzustand) und Exporten (DXF-Layer je Status, IFC `Status` im
`Pset_*Common`). Beispiel: *Datei → Neu aus Vorlage: Beispiel Umbau*. Das 3D-Fenster folgt dem Filter der aktiven Ebene (noch ohne Bildprüfung); Cycles/Blender noch ohne Filter.
14. **Varianten (17.11., [272]).** Wie Archicads „Design Options“: Variantensätze (z. B. Dachform, Fassade) mit Varianten A, B, …; jedes
Element (Bauteile, Öffnungen, Räume, Körper, 2D-Elemente samt Bibliotheksobjekten) gehört zum Hauptmodell oder zu genau einer Variante.
Je Ansicht, Ausschnitt, Vorlage und Blatt-Viewport eine Kombination (Vorgabe die Hauptvarianten); Grundriss, Schnitt, Ansicht,
Vektor-Axonometrie, 3D, Kennzahlen, Kosten, Baurecht, DXF, IFC und PDF folgen ihr. Panel „Varianten“ (Sätze verwalten, Kombination,
neue Elemente zeichnen in …, Zuweisen, Kopieren in …, Übernehmen), Objekt-Info „Variante“, Befehle `variante`/`variantekopieren`,
Varianten-Vergleich (GF, HNF, GV, AZ, ÜZ, Kosten je Kombination, CSV) in der Flächenbilanz; ein Viewport kann dieselbe Ansicht in
anderer Kombination zeigen (Titelzusatz mit Variantenname). CLI `--options "Dachform=B"`, Vergleich `designoptions`. Beispiel:
*Datei → Neu aus Vorlage: Beispiel Varianten*.
**Erker und Wiederanlauf (15.11.).** Fenster in Bogenwänden (Erker) sitzen in Schnitt und Ansicht wie im 3D und im Grundriss auf der Sehne; die Sehnen-Zonen
gelten über alle Geschosse, der Deckenrand folgt der Sehne ([216]). Raumstempel rücken in Lücken zwischen den Linien, bevor sie schrumpfen; die Baulinie setzt vor
@@ -204,7 +212,7 @@ Ehrlich vorweg: **Der Durchlauf des ganzen Referenz-Ablaufs auf dem Mac ist noch
Fenster in der Ansicht mit Rahmen und Glas, ausweichende und rauschfest lesbare Masszahlen sind behoben. **Bewusst vereinfacht:** mit der Vorlage
«Wettbewerb 1:200» zeigen Grundriss und Schnitt die Fenster als Linien (nur die Ansicht zeigt Rahmen/Glas). Nur im Linux-Container (CLI-SVG in Chromium,
PDF mit Poppler `pdftotext`/`pdftoppm`) angesehen, nicht auf dem Mac.
- Kostenschätzung: Kennwerte sind Beispielwerte; keine Varianten nebeneinander, keine Kennwerte aus Büro- oder CRB-Quelle ([209]).
- Kostenschätzung: Kennwerte sind Beispielwerte; Varianten nebeneinander über den Varianten-Vergleich ([272]), keine Kennwerte aus Büro- oder CRB-Quelle ([209]).
- Volumen → Bauteile: nur gerade Prismen und Quader/Zylinder; verjüngte Körper, Kugel/Kegel/Torus u. a. werden mit Meldung abgelehnt; keine
Bodenplatte, keine Innenwände ([222]).
- **Baurecht-Nachweis** ([255]): Fassadenhöhe nur über ±0.00 (Näherung); Grünfläche und aGSF nur per Eingabe; die Blatt-Tabelle übernimmt nur
Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 251 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

+65
View File
@@ -0,0 +1,65 @@
// [272] Varianten: Beispiel Varianten öffnen, Panel „Varianten“ über den Chip der Statusleiste, Satz anlegen, Auswahl einer
// Variante zuweisen (Undo), Kombination der Ansicht umschalten (Grundriss zeigt das Bandfenster statt des Lochfensters),
// Vergleichstabelle, Variante übernehmen und Undo. Geprüft über die UI und den Plan (Test-Nähte), nicht über Pixel.
import { blurFocus, discardIfAsked, expect, fileMenu, test } from "./app";
test("Varianten: Satz, Zuweisen, Kombination, Vergleich, Übernehmen, Undo ([272])", async ({ page }) => {
await page.goto("/?dossierTest");
await page.getByRole("button", { name: /Neues Projekt/ }).first().click();
await expect(page.getByRole("group", { name: "Befehlszeile" })).toBeVisible();
await fileMenu(page, /^Neu aus Vorlage: Beispiel Varianten$/);
await discardIfAsked(page);
await expect(page.locator(".project-name")).toHaveText("Beispiel Varianten");
const dopt = () => page.evaluate(() => window.__dossierTest!.designOptions());
const openings = () => page.evaluate(() => window.__dossierTest!.planOpeningIds());
// Hauptvarianten: Lochfenster O2, kein Bandfenster.
await expect.poll(openings).toContain("O2");
expect(await openings()).not.toContain("O-band");
// Chip der Statusleiste öffnet das Panel.
const chip = page.getByTestId("design-option-toggle");
await expect(chip).toContainText("Hauptvarianten");
await chip.click();
const panel = page.getByTestId("design-options-panel");
await expect(panel).toBeVisible();
// Neuer Satz.
await panel.getByTestId("rm-design-option-set-name").fill("Grundriss OG");
await panel.getByTestId("rm-design-option-set-add").click();
await expect.poll(async () => (await dopt()).sets).toEqual(["dachform", "fassade", "satz-3"]);
// Wand W1 der Variante „Fassade: B Bandfenster“ zuweisen; Undo in einem Schritt.
await page.evaluate(() => window.__dossierTest!.select({ walls: ["W1"] }));
await panel.getByTestId("design-option-target").selectOption("fassade/b");
await panel.getByTestId("design-option-assign").click();
await expect.poll(async () => (await dopt()).elements.W1).toBe("fassade/b");
await blurFocus(page);
await page.keyboard.press("ControlOrMeta+z");
await expect.poll(async () => (await dopt()).elements.W1).toBe("");
// Kombination der Ansicht: Fassade B → Bandfenster statt Lochfenster; der Chip nennt die Abweichung.
await panel.getByTestId("design-option-combo-fassade").selectOption("b");
await expect.poll(async () => (await dopt()).level).toEqual({ fassade: "b" });
await expect.poll(openings).toContain("O-band");
expect(await openings()).not.toContain("O2");
await expect(chip).toContainText("Fassade B Bandfenster");
// Vergleich: vier Kombinationen, Hauptkombination zuerst.
await panel.getByTestId("design-option-compare-open").click();
const rows = panel.getByTestId("design-option-compare-row");
await expect(rows).toHaveCount(4);
await expect(rows.first()).toContainText("Dachform A Flachdach, Fassade A Lochfenster");
await page.screenshot({ path: "test-results/designOptions272-panel.png" });
await rows.last().scrollIntoViewIfNeeded();
await panel.screenshot({ path: "test-results/designOptions272-compare.png" });
// Variante übernehmen (Dachform B): Satz weg; Undo bringt ihn zurück.
const dach = panel.getByTestId("rm-design-option-set").first();
await dach.getByTestId("rm-design-option-accept").nth(1).click();
await expect.poll(async () => (await dopt()).sets).toEqual(["fassade", "satz-3"]);
expect((await dopt()).elements.RF1).toBe("");
await blurFocus(page);
await page.keyboard.press("ControlOrMeta+z");
await expect.poll(async () => (await dopt()).sets).toEqual(["dachform", "fassade", "satz-3"]);
expect((await dopt()).elements.RF1).toBe("dachform/b");
});
+1
View File
@@ -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 |
| `renovation.rs` | [271] Umbau: Status je Bauteil, Etappen, Umbaufilter (`View`, `Resolved`), SIA-Farben; ein Ort für „sichtbar/wie gezeichnet im Filter“ (s. `doc/ARCHITEKTUR.md` 3.8) |
| `design_options.rs` | [272] Varianten: Kombination (je Satz eine Variante), Anfragen „Satz=Variante“, Ops (Übernehmen, Löschen, Zuweisen, Kopieren, Zeichen-Variante), Vergleich der Kennzahlen/Kosten; die Sichtbarkeit selbst entscheidet `renovation.rs` (`doc/ARCHITEKTUR.md` 3.9) |
| `standards.rs` | Standard-Bibliothek: Baustoffe mit SIA-400-Schraffur und Kennwerten, Linientypen, Standard-Aufbauten |
| `standards_names.rs` | [264] Englische Namen der Standards nach Kennung (`Lang`, `name_in`); neue Projekte in englischer UI bekommen sie über `standardsMergeOps(lang)` |
| `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 |
+2 -1
View File
@@ -34,7 +34,8 @@ pub fn ops(root: &Map<String, Value>, p: &Project, text: &str) -> Result<Vec<Op>
}
if let Some(ops) = crate::cmd_create::ops(root, p, &v) {
// [271] Aktueller Zeichen-Status (`renovation` der Anfrage): neue Bauteile tragen ihn (Bestand = ohne Feld).
return Ok(stamp_renovation(ops, v.get("renovation")));
// [272] Aktuelle Zeichen-Variante (`designOption` der Anfrage): neue Elemente gehören ihr.
return Ok(crate::design_options::stamp_ops(stamp_renovation(ops, v.get("renovation")), v.get("designOption")));
}
if let Some(ops) = crate::cmd_context::ops(root, p, &v) {
return Ok(ops);
+597
View File
@@ -0,0 +1,597 @@
//! [272] Varianten wie Archicads „Design Options“: Variantensätze (z. B. „Dachform“) mit Varianten (A, B, C …),
//! jedes Element gehört zum Hauptmodell (ohne `designOption`) oder zu genau einer Variante eines Satzes.
//!
//! Hier liegen nur das Modell der **Kombination** (je Satz eine Variante, Vorgabe die Hauptvariante), das Lesen der
//! Anfragen (`"Dachform=B,Fassade=A"` oder `{"Dachform": "B"}`), die Ops zum Bearbeiten (Übernehmen, Löschen,
//! Zuweisen, Kopieren) und der Vergleich der Kennzahlen. **Ob ein Element in einer Darstellung erscheint**, entscheidet
//! weiterhin der eine Ort `renovation.rs` ([`crate::renovation::View`]): er nimmt die Kombination mit auf und blendet
//! Elemente anderer Varianten aus wie die Regel „Ausblenden“ — Grundriss, Schnitt, Ansicht, Axo, 3D, Kennzahlen und
//! Exporte fragen dort.
use crate::model::*;
use serde_json::{json, Map, Value};
use std::collections::{BTreeMap, HashSet};
/// Listen, deren Elemente eine Variante tragen können (Wurzel-Schlüssel).
pub const COLLECTIONS: [&str; 9] = ["walls", "openings", "ceilings", "roofs", "stairs", "columns", "extrudedSolids", "rooms", "drawings2d"];
/// Höchstens so viele Kombinationen im Vergleich (Kreuzprodukt der Sätze).
pub const MAX_COMPARE: usize = 24;
/// Variantensätze des Projekts.
pub fn sets(p: &Project) -> &[DesignOptionSet] {
p.design_option_sets.as_deref().unwrap_or(&[])
}
/// Id der Hauptvariante eines Satzes (`primary`, sonst die erste); `None` ohne Varianten.
pub fn primary_of(s: &DesignOptionSet) -> Option<&str> {
s.primary.as_deref().filter(|id| s.options.iter().any(|o| o.id == *id)).or_else(|| s.options.first().map(|o| o.id.as_str()))
}
/// Satz nach Id, sonst nach Name (ohne Gross-/Kleinschreibung).
pub fn find_set<'a>(p: &'a Project, key: &str) -> Option<&'a DesignOptionSet> {
let key = key.trim();
let low = key.to_lowercase();
sets(p).iter().find(|s| s.id == key).or_else(|| sets(p).iter().find(|s| s.name.trim().to_lowercase() == low))
}
/// Variante eines Satzes nach Id, sonst nach Name (ohne Gross-/Kleinschreibung).
pub fn find_option<'a>(s: &'a DesignOptionSet, key: &str) -> Option<&'a DesignOption> {
let key = key.trim();
let low = key.to_lowercase();
s.options.iter().find(|o| o.id == key).or_else(|| s.options.iter().find(|o| o.name.trim().to_lowercase() == low))
}
/// Trägt irgendein Element eine Variante eines bekannten Satzes? Sonst ist jede Kombination wirkungslos.
pub fn active(p: &Project) -> bool {
if sets(p).is_empty() {
return false;
}
let known = |r: Option<&DesignOptionRef>| r.is_some_and(|r| sets(p).iter().any(|s| s.id == r.set));
p.walls.iter().any(|x| known(x.design_option.as_ref()))
|| p.openings.iter().flatten().any(|x| known(x.design_option.as_ref()))
|| p.ceilings.iter().flatten().any(|x| known(x.design_option.as_ref()))
|| p.roofs.iter().flatten().any(|x| known(x.design_option.as_ref()))
|| p.stairs.iter().flatten().any(|x| known(x.design_option.as_ref()))
|| p.columns.iter().flatten().any(|x| known(x.design_option.as_ref()))
|| p.extruded_solids.iter().flatten().any(|x| known(x.design_option.as_ref()))
|| p.rooms.iter().flatten().any(|x| known(x.design_option.as_ref()))
|| p.drawings2d.iter().any(|x| known(x.design_option.as_ref()))
}
/// Eine Variantenkombination: je Satz (Id) die gezeigte Variante (Id). Sätze ohne Varianten fehlen.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Combination {
pub choice: BTreeMap<String, String>,
}
/// Anfrage einer Kombination: Paare (Satz, Variante) als Id oder Name.
pub type Request = Vec<(String, String)>;
/// Liest eine Anfrage: Text `"Dachform=B,Fassade=A"` (auch `;`) oder Objekt `{"Dachform": "B"}`; Unsinn ⇒ leer.
pub fn parse_request(v: Option<&Value>) -> Request {
match v {
Some(Value::String(s)) => parse_text(s),
Some(Value::Object(m)) => m.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))).filter(|(k, v)| !k.trim().is_empty() && !v.trim().is_empty()).collect(),
_ => Vec::new(),
}
}
/// Wie [`parse_request`] für einen Text (CLI `--options`).
pub fn parse_text(s: &str) -> Request {
s.split([',', ';'])
.filter_map(|part| {
let (k, v) = part.split_once('=')?;
let (k, v) = (k.trim(), v.trim());
(!k.is_empty() && !v.is_empty()).then(|| (k.to_string(), v.to_string()))
})
.collect()
}
impl Combination {
/// Hauptvariante je Satz.
pub fn primary(p: &Project) -> Combination {
let mut choice = BTreeMap::new();
for s in sets(p) {
if let Some(o) = primary_of(s) {
choice.insert(s.id.clone(), o.to_string());
}
}
Combination { choice }
}
/// Kombination einer Darstellung: Hauptvarianten, darüber die gespeicherte Wahl (`level`: Ebene, Vorlage,
/// Ausschnitt, Viewport — nur gültige Ids), darüber die ausdrückliche Anfrage (Ids oder Namen). Unbekanntes
/// wird übergangen.
pub fn resolve(p: &Project, stored: &[&BTreeMap<String, String>], request: &[(String, String)]) -> Combination {
let mut c = Combination::primary(p);
for m in stored {
for (k, v) in m.iter() {
c.set(p, k, v);
}
}
for (k, v) in request {
c.set(p, k, v);
}
c
}
/// Variante `option` (Id/Name) im Satz `set` (Id/Name) wählen; unbekannt ⇒ unverändert.
pub fn set(&mut self, p: &Project, set: &str, option: &str) {
if let Some(s) = find_set(p, set) {
if let Some(o) = find_option(s, option) {
self.choice.insert(s.id.clone(), o.id.clone());
}
}
}
/// Erscheint ein Element mit dieser Zugehörigkeit? Ohne Feld oder bei unbekanntem Satz: ja (Hauptmodell).
pub fn shows(&self, r: Option<&DesignOptionRef>) -> bool {
match r {
None => true,
Some(r) => self.choice.get(&r.set).is_none_or(|o| *o == r.option),
}
}
/// Schlüssel für Caches.
pub fn key(&self) -> String {
self.choice.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join(",")
}
/// Sind alle Sätze auf der Hauptvariante?
pub fn is_primary(&self, p: &Project) -> bool {
*self == Combination::primary(p)
}
/// Lesbarer Name „Dachform B, Fassade A“ (Namen der Sätze und Varianten, Projekt-Reihenfolge).
pub fn label(&self, p: &Project) -> String {
let mut parts = Vec::new();
for s in sets(p) {
let Some(oid) = self.choice.get(&s.id) else { continue };
let Some(o) = s.options.iter().find(|o| o.id == *oid) else { continue };
parts.push(format!("{} {}", s.name.trim(), o.name.trim()).trim().to_string());
}
parts.join(", ")
}
/// Ausgeblendete Elemente (ids) aller Listen mit Varianten: Elemente anderer Varianten; Öffnungen in
/// ausgeblendeten Wänden mit.
pub fn hidden(&self, p: &Project) -> HashSet<String> {
let mut out = HashSet::new();
if self.choice.is_empty() {
return out;
}
for w in &p.walls {
if !self.shows(w.design_option.as_ref()) {
out.insert(w.id.clone());
}
}
for o in p.openings.iter().flatten() {
if out.contains(&o.host_wall_id) || !self.shows(o.design_option.as_ref()) {
out.insert(o.id.clone());
}
}
macro_rules! each {
($($f:ident),*) => {$(
for x in p.$f.iter().flatten() {
if !self.shows(x.design_option.as_ref()) {
out.insert(x.id.clone());
}
}
)*};
}
each!(ceilings, roofs, stairs, columns, extruded_solids, rooms);
for d in &p.drawings2d {
if !self.shows(d.design_option.as_ref()) {
out.insert(d.id.clone());
}
}
out
}
/// Alle Kombinationen (Kreuzprodukt der Sätze, Hauptkombination zuerst), höchstens [`MAX_COMPARE`].
pub fn all(p: &Project) -> Vec<Combination> {
let mut out = vec![Combination::default()];
for s in sets(p).iter().filter(|s| !s.options.is_empty()) {
let prim = primary_of(s).unwrap_or_default().to_string();
let mut order: Vec<&str> = vec![prim.as_str()];
order.extend(s.options.iter().map(|o| o.id.as_str()).filter(|id| *id != prim));
let mut next = Vec::new();
for c in &out {
for o in &order {
let mut c = c.clone();
c.choice.insert(s.id.clone(), o.to_string());
next.push(c);
if next.len() >= MAX_COMPARE {
break;
}
}
if next.len() >= MAX_COMPARE {
break;
}
}
out = next;
}
out
}
}
/// Gespeicherte Kombination einer Ebene (über die verknüpfte Vorlage hat sie schon `level_with_template`).
pub fn level_choice<'a>(p: &'a Project, level_id: &str) -> Option<&'a BTreeMap<String, String>> {
p.floor(level_id).and_then(|l| l.design_options.as_ref())
}
/// Das Projekt in einer Kombination (Elemente anderer Varianten fehlen; ohne Wirkung geliehen).
pub fn project_in<'a>(p: &'a Project, c: &Combination) -> std::borrow::Cow<'a, Project> {
let hidden = c.hidden(p);
if hidden.is_empty() {
std::borrow::Cow::Borrowed(p)
} else {
std::borrow::Cow::Owned(crate::renovation::without_hidden(p, &hidden))
}
}
// ── Vergleich ────────────────────────────────────────────────────────────────
/// Eine Zeile der Vergleichstabelle: Kennzahlen und Kosten einer Kombination.
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CompareRow {
/// Satz-Id → Varianten-Id.
pub choice: BTreeMap<String, String>,
pub label: String,
pub primary: bool,
pub gf: f64,
pub hnf: f64,
pub gv: f64,
pub footprint: f64,
pub az: Option<f64>,
pub uez: Option<f64>,
/// Kosten inkl. MwSt. (Grobschätzung [209]).
pub cost: f64,
}
/// [272] Kennzahlen und Kosten je Kombination (Hauptkombination zuerst); `filter`/`phase`: Umbau-Zustand.
pub fn compare(p: &Project, filter: Option<&str>, phase: Option<&str>) -> Vec<CompareRow> {
if sets(p).is_empty() {
return Vec::new();
}
let prim = Combination::primary(p);
Combination::all(p)
.into_iter()
.map(|c| {
let q = crate::renovation::project_in_view(p, filter, phase, &c);
let k = crate::kennzahlen::compute(&q);
let cost = crate::kosten::estimate(&q);
let num = |x: f64| if x.is_finite() { x } else { 0.0 };
CompareRow { label: c.label(p), primary: c == prim, gf: num(k.gf), hnf: num(k.hnf), gv: num(k.gv), footprint: num(k.footprint), az: k.az.filter(|x| x.is_finite()), uez: k.uez.filter(|x| x.is_finite()), cost: num(cost.gross), choice: c.choice }
})
.collect()
}
/// Vergleich als CSV (Semikolon, Spaltenköpfe aus `head`, de/en von der Oberfläche).
pub fn compare_csv(rows: &[CompareRow], head: &[String]) -> String {
let f = |x: f64, d: usize| format!("{x:.d$}");
let o = |x: Option<f64>| x.map_or(String::new(), |x| f(x, 2));
let mut out = head.iter().map(|h| csv_cell(h)).collect::<Vec<_>>().join(";");
out.push('\n');
for r in rows {
let cells = [csv_cell(&r.label), f(r.gf, 1), f(r.hnf, 1), f(r.gv, 0), f(r.footprint, 1), o(r.az), o(r.uez), f(r.cost, 0)];
out.push_str(&cells.join(";"));
out.push('\n');
}
out
}
fn csv_cell(s: &str) -> String {
if s.contains([';', '"', '\n']) {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s.to_string()
}
}
// ── Ops (auf der rohen Wurzel, verlustfrei) ─────────────────────────────────
fn arr<'a>(root: &'a Map<String, Value>, key: &str) -> &'a [Value] {
root.get(key).and_then(Value::as_array).map_or(&[], Vec::as_slice)
}
fn ref_of(v: &Value) -> Option<(&str, &str)> {
let r = v.get("designOption")?;
Some((r.get("set")?.as_str()?, r.get("option")?.as_str()?))
}
fn id_of(v: &Value) -> Option<&str> {
v.get("id").and_then(Value::as_str)
}
/// Element ohne/mit Feld `designOption` (als `replace`-Op).
fn with_ref(v: &Value, r: Option<(&str, &str)>) -> Value {
let mut m = v.as_object().cloned().unwrap_or_default();
match r {
Some((s, o)) => {
m.insert("designOption".into(), json!({"set": s, "option": o}));
}
None => {
m.shift_remove("designOption");
}
}
Value::Object(m)
}
fn set_list(root: &Map<String, Value>) -> Vec<Value> {
arr(root, "designOptionSets").to_vec()
}
/// Gespeicherte Kombinationen (Ebenen, Vorlagen, Ausschnitte, Layout-Viewports) ohne den Satz `set` bzw. ohne die
/// Variante `option` des Satzes (`None` = alle seine Varianten).
fn clear_choices(root: &Map<String, Value>, set: &str, option: Option<&str>, ops: &mut Vec<Value>) {
let fix = |v: &Value| -> Option<Value> {
let m = v.get("designOptions")?.as_object()?;
let cur = m.get(set)?.as_str();
if option.is_some_and(|o| cur != Some(o)) {
return None;
}
let mut obj = v.as_object()?.clone();
let mut next = m.clone();
next.shift_remove(set);
if next.is_empty() {
obj.shift_remove("designOptions");
} else {
obj.insert("designOptions".into(), Value::Object(next));
}
Some(Value::Object(obj))
};
for key in ["drawingLevels", "viewTemplates", "viewSnapshots"] {
for v in arr(root, key) {
if let Some(n) = fix(v) {
ops.push(json!({"kind": "replace", "collection": key, "entity": n}));
}
}
}
// Viewports liegen in den Layouts.
for l in arr(root, "layouts") {
let Some(vps) = l.get("viewports").and_then(Value::as_array) else { continue };
let next: Vec<Value> = vps.iter().map(|vp| fix(vp).unwrap_or_else(|| vp.clone())).collect();
if next != *vps {
let mut obj = l.as_object().cloned().unwrap_or_default();
obj.insert("viewports".into(), Value::Array(next));
ops.push(json!({"kind": "replace", "collection": "layouts", "entity": Value::Object(obj)}));
}
}
}
/// Elemente des Satzes `set` je Liste: (Liste, Element) für jede Variante, die `keep(option)` nicht behält.
fn elements_where<'a>(root: &'a Map<String, Value>, pred: impl Fn(&str, &str) -> bool) -> Vec<(&'static str, &'a Value)> {
let mut out = Vec::new();
for c in COLLECTIONS {
for v in arr(root, c) {
if ref_of(v).is_some_and(|(s, o)| pred(s, o)) {
out.push((c, v));
}
}
}
out
}
/// Ops zum Entfernen der Elemente (je Liste ein `remove`), Öffnungen entfernter Wände mit.
fn remove_ops(root: &Map<String, Value>, doomed: &[(&'static str, &Value)], ops: &mut Vec<Value>) {
let mut by: BTreeMap<&str, Vec<String>> = BTreeMap::new();
for (c, v) in doomed {
if let Some(id) = id_of(v) {
by.entry(c).or_default().push(id.to_string());
}
}
let walls: HashSet<&str> = by.get("walls").map(|v| v.iter().map(String::as_str).collect()).unwrap_or_default();
let mut extra = Vec::new();
for o in arr(root, "openings") {
let host = o.get("hostWallId").and_then(Value::as_str).unwrap_or("");
if walls.contains(host) {
if let Some(id) = id_of(o) {
if !by.get("openings").is_some_and(|v| v.iter().any(|x| x == id)) {
extra.push(id.to_string());
}
}
}
}
if !extra.is_empty() {
by.entry("openings").or_default().extend(extra);
}
for (c, ids) in by {
ops.push(json!({"kind": "remove", "collection": c, "ids": ids}));
}
}
/// [272] „Variante übernehmen“: die Elemente der Variante `option` gehen ins Hauptmodell, die der übrigen Varianten
/// des Satzes werden gelöscht, der Satz verschwindet (auch aus gespeicherten Kombinationen). Ein Undo-Schritt.
pub fn accept_ops(root: &Map<String, Value>, set: &str, option: &str) -> Vec<Value> {
let mut ops = Vec::new();
let sets = set_list(root);
let Some(s) = sets.iter().find(|s| id_of(s) == Some(set)) else { return ops };
if !s.get("options").and_then(Value::as_array).is_some_and(|a| a.iter().any(|o| id_of(o) == Some(option))) {
return ops;
}
for c in COLLECTIONS {
for v in arr(root, c) {
if ref_of(v) == Some((set, option)) {
ops.push(json!({"kind": "replace", "collection": c, "entity": with_ref(v, None)}));
}
}
}
let doomed = elements_where(root, |s, o| s == set && o != option);
remove_ops(root, &doomed, &mut ops);
clear_choices(root, set, None, &mut ops);
ops.push(json!({"kind": "remove", "collection": "designOptionSets", "ids": [set]}));
ops
}
/// [272] Satz löschen: alle Elemente seiner Varianten werden gelöscht, der Satz verschwindet.
pub fn delete_set_ops(root: &Map<String, Value>, set: &str) -> Vec<Value> {
let mut ops = Vec::new();
if !set_list(root).iter().any(|s| id_of(s) == Some(set)) {
return ops;
}
let doomed = elements_where(root, |s, _| s == set);
remove_ops(root, &doomed, &mut ops);
clear_choices(root, set, None, &mut ops);
ops.push(json!({"kind": "remove", "collection": "designOptionSets", "ids": [set]}));
ops
}
/// [272] Variante löschen: ihre Elemente werden gelöscht; war sie die Hauptvariante, wird die erste übrige es.
/// Die letzte Variante löscht den Satz.
pub fn delete_option_ops(root: &Map<String, Value>, set: &str, option: &str) -> Vec<Value> {
let mut ops = Vec::new();
let sets = set_list(root);
let Some(s) = sets.iter().find(|s| id_of(s) == Some(set)) else { return ops };
let opts: Vec<Value> = s.get("options").and_then(Value::as_array).cloned().unwrap_or_default();
if !opts.iter().any(|o| id_of(o) == Some(option)) {
return ops;
}
let rest: Vec<Value> = opts.iter().filter(|o| id_of(o) != Some(option)).cloned().collect();
if rest.is_empty() {
return delete_set_ops(root, set);
}
let doomed = elements_where(root, |s, o| s == set && o == option);
remove_ops(root, &doomed, &mut ops);
clear_choices(root, set, Some(option), &mut ops);
let mut obj = s.as_object().cloned().unwrap_or_default();
obj.insert("options".into(), Value::Array(rest.clone()));
if obj.get("primary").and_then(Value::as_str) == Some(option) || !obj.contains_key("primary") {
if let Some(first) = rest.first().and_then(id_of) {
obj.insert("primary".into(), json!(first));
}
}
ops.push(json!({"kind": "replace", "collection": "designOptionSets", "entity": Value::Object(obj)}));
ops
}
/// Ids je Liste (Auswahl der Oberfläche, `{walls: [...], ...}`); Listen ohne Varianten werden übergangen.
pub type Selection = BTreeMap<String, Vec<String>>;
fn selected<'a>(root: &'a Map<String, Value>, sel: &Selection) -> Vec<(&'static str, &'a Value)> {
let mut out = Vec::new();
for c in COLLECTIONS {
let Some(ids) = sel.get(c) else { continue };
let ids: HashSet<&str> = ids.iter().map(String::as_str).collect();
for v in arr(root, c) {
if id_of(v).is_some_and(|id| ids.contains(id)) {
out.push((c, v));
}
}
}
out
}
/// Ist (`set`, `option`) eine bekannte Variante?
fn known(root: &Map<String, Value>, set: &str, option: &str) -> bool {
set_list(root).iter().any(|s| id_of(s) == Some(set) && s.get("options").and_then(Value::as_array).is_some_and(|a| a.iter().any(|o| id_of(o) == Some(option))))
}
/// [272] Variante zuweisen (`None` = Hauptmodell) für die Auswahl: ein `replace` je geändertes Element.
/// Unbekannte Variante ⇒ keine Ops.
pub fn assign_ops(root: &Map<String, Value>, sel: &Selection, target: Option<(&str, &str)>) -> Vec<Value> {
if target.is_some_and(|(s, o)| !known(root, s, o)) {
return Vec::new();
}
let mut ops = Vec::new();
for (c, v) in selected(root, sel) {
if ref_of(v) != target {
ops.push(json!({"kind": "replace", "collection": c, "entity": with_ref(v, target)}));
}
}
ops
}
/// [272] „In Variante kopieren“: Kopien der Auswahl mit neuen Ids (`stamp` + laufende Nummer) in der Variante
/// (`None` = Hauptmodell); Öffnungen gewählter Wände wandern mit und zeigen auf die kopierte Wand.
pub fn copy_ops(root: &Map<String, Value>, sel: &Selection, target: Option<(&str, &str)>, stamp: &str) -> Vec<Value> {
if target.is_some_and(|(s, o)| !known(root, s, o)) {
return Vec::new();
}
let mut picked = selected(root, sel);
// Öffnungen der gewählten Wände kommen mit, sofern nicht selbst gewählt.
let wall_ids: HashSet<&str> = picked.iter().filter(|(c, _)| *c == "walls").filter_map(|(_, v)| id_of(v)).collect();
let chosen: HashSet<&str> = picked.iter().filter(|(c, _)| *c == "openings").filter_map(|(_, v)| id_of(v)).collect();
for o in arr(root, "openings") {
let host = o.get("hostWallId").and_then(Value::as_str).unwrap_or("");
if wall_ids.contains(host) && id_of(o).is_some_and(|id| !chosen.contains(id)) {
picked.push(("openings", o));
}
}
let mut n = 0usize;
let mut new_id: BTreeMap<String, String> = BTreeMap::new();
for (_, v) in &picked {
if let Some(id) = id_of(v) {
n += 1;
new_id.insert(id.to_string(), format!("{stamp}-{n}"));
}
}
let mut by: BTreeMap<&str, Vec<Value>> = BTreeMap::new();
for (c, v) in &picked {
let Some(id) = id_of(v) else { continue };
let mut x = with_ref(v, target);
if let Some(m) = x.as_object_mut() {
m.insert("id".into(), json!(new_id[id]));
if *c == "openings" {
if let Some(h) = m.get("hostWallId").and_then(Value::as_str).and_then(|h| new_id.get(h)) {
m.insert("hostWallId".into(), json!(h));
}
}
}
by.entry(c).or_default().push(x);
}
by.into_iter().map(|(c, items)| json!({"kind": "add", "collection": c, "items": items})).collect()
}
/// [272] Neue Elemente der Ops (`add` in [`COLLECTIONS`]) erhalten die Zeichen-Variante (`{set, option}`), sofern sie
/// keine tragen; ohne gültige Angabe unverändert.
pub fn stamp_ops(mut ops: Vec<crate::ops::Op>, v: Option<&Value>) -> Vec<crate::ops::Op> {
let Some(r) = v.and_then(|r| Some(json!({"set": r.get("set")?.as_str().filter(|s| !s.is_empty())?, "option": r.get("option")?.as_str().filter(|s| !s.is_empty())?}))) else { return ops };
for op in ops.iter_mut() {
if let crate::ops::Op::Add { collection, items, .. } = op {
if !COLLECTIONS.contains(&collection.as_str()) {
continue;
}
for it in items.iter_mut() {
if let Some(o) = it.as_object_mut() {
o.entry("designOption").or_insert_with(|| r.clone());
}
}
}
}
ops
}
/// Antwort der Abfrage `designOptionInfo`: Sätze mit Varianten und Hauptvariante, Zahl der Elemente je Variante.
pub fn info(p: &Project) -> Value {
let mut count: BTreeMap<(String, String), usize> = BTreeMap::new();
let mut add = |r: Option<&DesignOptionRef>| {
if let Some(r) = r {
*count.entry((r.set.clone(), r.option.clone())).or_default() += 1;
}
};
p.walls.iter().for_each(|x| add(x.design_option.as_ref()));
p.openings.iter().flatten().for_each(|x| add(x.design_option.as_ref()));
p.ceilings.iter().flatten().for_each(|x| add(x.design_option.as_ref()));
p.roofs.iter().flatten().for_each(|x| add(x.design_option.as_ref()));
p.stairs.iter().flatten().for_each(|x| add(x.design_option.as_ref()));
p.columns.iter().flatten().for_each(|x| add(x.design_option.as_ref()));
p.extruded_solids.iter().flatten().for_each(|x| add(x.design_option.as_ref()));
p.rooms.iter().flatten().for_each(|x| add(x.design_option.as_ref()));
p.drawings2d.iter().for_each(|x| add(x.design_option.as_ref()));
Value::Array(
sets(p)
.iter()
.map(|s| {
let opts: Vec<Value> = s.options.iter().map(|o| json!({"id": o.id, "name": o.name, "count": count.get(&(s.id.clone(), o.id.clone())).copied().unwrap_or(0)})).collect();
json!({"id": s.id, "name": s.name, "primary": primary_of(s), "options": opts})
})
.collect(),
)
}
#[cfg(test)]
#[path = "design_options_tests.rs"]
mod tests;
+438
View File
@@ -0,0 +1,438 @@
//! [272] Tests der Varianten: Sichtbarkeit je Kombination (auch mit Umbaufilter), Kennzahlen-Vergleich, Übernehmen,
//! Löschen, Zuweisen/Kopieren, Robustheit.
use super::*;
use crate::plan::domains::{plan_domains, PlanArgs};
use crate::plan::prim::Primitive;
use serde_json::{json, Value};
/// Musterhaus mit Satz „Dachform“ (A Flachdach = Haupt, B Satteldach): W2 und Raum R1 in A; W9, Dach RF1, Öffnung O2 und
/// eine Linie im EG in B. Dazu die Umbau-Angaben der [271]-Fixture (W2 Abbruch, W9 Neu Etappe 2).
fn fixture() -> Value {
let mut v = crate::renovation::tests::umbau_fixture();
v["designOptionSets"] = json!([{"id": "dach", "name": "Dachform", "options": [{"id": "a", "name": "A"}, {"id": "b", "name": "B"}], "primary": "a"}]);
let tag = |v: &mut Value, coll: &str, id: &str, opt: &str| {
for x in v[coll].as_array_mut().unwrap() {
if x["id"] == id {
x["designOption"] = json!({"set": "dach", "option": opt});
}
}
};
tag(&mut v, "walls", "W2", "a");
tag(&mut v, "rooms", "R1", "a");
tag(&mut v, "walls", "W9", "b");
tag(&mut v, "roofs", "RF1", "b");
tag(&mut v, "openings", "O2", "b");
v["drawings2d"].as_array_mut().unwrap().push(json!({"id": "L-b", "type": "line", "levelId": "eg", "categoryCode": "00", "geom": {"shape": "line", "a": {"x": 0, "y": 0}, "b": {"x": 3, "y": 3}}, "designOption": {"set": "dach", "option": "b"}}));
v
}
fn project(v: &Value) -> Project {
serde_json::from_value(v.clone()).unwrap()
}
fn plan_with(p: &Project, extra: Value) -> Vec<Primitive> {
let codes: Vec<String> = (0..100).map(|k| format!("{k:02}")).collect();
let mut t = json!({"floor": "eg", "show": codes, "scale": 100});
for (k, x) in extra.as_object().unwrap() {
t[k] = x.clone();
}
let d = plan_domains(p, &PlanArgs::parse_in(p, 1.0, &t.to_string()).unwrap()).unwrap();
[d.walls, d.ceilings, d.roofs, d.stairs, d.columns, d.solids, d.rooms, d.drawings.prims].concat()
}
fn has_wall(prims: &[Primitive], id: &str) -> bool {
prims.iter().any(|q| matches!(q, Primitive::Polygon { wall_id: Some(w), .. } if w == id))
}
fn has_opening(prims: &[Primitive], id: &str) -> bool {
prims.iter().any(|q| match q {
Primitive::Polygon { opening_id: Some(o), .. } | Primitive::Line { opening_id: Some(o), .. } | Primitive::Arc { opening_id: Some(o), .. } => o == id,
_ => false,
})
}
fn has_drawing(prims: &[Primitive], id: &str) -> bool {
prims.iter().any(|q| match q {
Primitive::Line { drawing_id: Some(d), .. } | Primitive::Polygon { drawing_id: Some(d), .. } => d == id,
_ => false,
})
}
#[test]
fn kombination_lesen_und_aufloesen() {
let p = project(&fixture());
assert!(active(&p));
let prim = Combination::primary(&p);
assert_eq!(prim.choice.get("dach").map(String::as_str), Some("a"));
assert!(prim.shows(None));
assert!(prim.shows(Some(&DesignOptionRef { set: "dach".into(), option: "a".into(), ..Default::default() })));
assert!(!prim.shows(Some(&DesignOptionRef { set: "dach".into(), option: "b".into(), ..Default::default() })));
// Unbekannter Satz: Hauptmodell (sichtbar).
assert!(prim.shows(Some(&DesignOptionRef { set: "weg".into(), option: "x".into(), ..Default::default() })));
// Anfrage nach Namen (Gross-/Kleinschreibung egal), Text oder Objekt.
assert_eq!(parse_text("Dachform=B, Fassade = A"), vec![("Dachform".to_string(), "B".to_string()), ("Fassade".to_string(), "A".to_string())]);
let c = Combination::resolve(&p, &[], &parse_text("dachform=b"));
assert_eq!(c.choice["dach"], "b");
assert_eq!(c.label(&p), "Dachform B");
assert!(!c.is_primary(&p));
let c2 = Combination::resolve(&p, &[], &parse_request(Some(&json!({"Dachform": "B"}))));
assert_eq!(c, c2);
// Gespeicherte Wahl unter der Anfrage.
let stored: BTreeMap<String, String> = [("dach".to_string(), "b".to_string())].into();
assert_eq!(Combination::resolve(&p, &[&stored], &[]).choice["dach"], "b");
assert_eq!(Combination::resolve(&p, &[&stored], &parse_text("Dachform=A")).choice["dach"], "a");
// Unbekanntes wird übergangen.
assert_eq!(Combination::resolve(&p, &[], &parse_text("Dachform=Z,Fassade=A,=,kaputt")).choice["dach"], "a");
// Ausgeblendet: W2/R1 in B, W9/RF1/O2/L-b in A.
let h = prim.hidden(&p);
for id in ["W9", "RF1", "O2", "L-b"] {
assert!(h.contains(id), "{id}");
}
assert!(!h.contains("W2") && !h.contains("O1"));
let hb = c.hidden(&p);
assert!(hb.contains("W2") && hb.contains("R1") && !hb.contains("W9"));
// Alle Kombinationen: Hauptkombination zuerst.
let all = Combination::all(&p);
assert_eq!(all.len(), 2);
assert_eq!(all[0], prim);
}
#[test]
fn grundriss_je_kombination() {
let p = project(&fixture());
let a = plan_with(&p, json!({}));
assert!(has_wall(&a, "W2") && !has_wall(&a, "W9"));
assert!(!has_opening(&a, "O2") && has_opening(&a, "O1"));
assert!(!has_drawing(&a, "L-b"));
let b = plan_with(&p, json!({"designOptions": "Dachform=B"}));
assert!(!has_wall(&b, "W2") && has_wall(&b, "W9"));
assert!(has_opening(&b, "O2"));
assert!(has_drawing(&b, "L-b"));
// Kombination der Ebene.
let mut v = fixture();
for l in v["drawingLevels"].as_array_mut().unwrap() {
if l["id"] == "eg" {
l["designOptions"] = json!({"dach": "b"});
}
}
let q = project(&v);
let b2 = plan_with(&q, json!({}));
assert!(has_wall(&b2, "W9") && !has_wall(&b2, "W2"));
// Die Anfrage geht vor.
let a2 = plan_with(&q, json!({"designOptions": {"dach": "a"}}));
assert!(has_wall(&a2, "W2") && !has_wall(&a2, "W9"));
}
#[test]
fn ohne_varianten_unveraendert() {
// Projekt ohne Sätze: keine View, der Plan ist derselbe wie vorher.
let v = crate::renovation::tests::umbau_fixture();
let p = project(&v);
assert!(!active(&p));
assert!(crate::renovation::View::new(&p, None, None).is_none());
// Sätze ohne Elemente: wirkungslos.
let mut v2 = v.clone();
v2["designOptionSets"] = json!([{"id": "s", "name": "S", "options": [{"id": "x", "name": "X"}]}]);
let p2 = project(&v2);
assert!(!active(&p2));
assert_eq!(format!("{:?}", plan_with(&p, json!({}))), format!("{:?}", plan_with(&p2, json!({"designOptions": "S=X"}))));
}
#[test]
fn umbaufilter_und_kombination() {
let p = project(&fixture());
// Neubau: Abbruch (W2) weg, W9 neu (Etappe 2) — aber W9 nur in B.
let a = plan_with(&p, json!({"renovation": "neubau"}));
assert!(!has_wall(&a, "W2") && !has_wall(&a, "W9"));
let b = plan_with(&p, json!({"renovation": "neubau", "designOptions": "Dachform=B"}));
assert!(has_wall(&b, "W9") && !has_wall(&b, "W2"));
// Bestand in B: W9 (neu) fehlt, W2 ist in A — beides fehlt.
let bb = plan_with(&p, json!({"renovation": "bestand", "designOptions": "Dachform=B"}));
assert!(!has_wall(&bb, "W9") && !has_wall(&bb, "W2") && has_wall(&bb, "W1"));
// Bestand in A: W2 steht noch.
let ba = plan_with(&p, json!({"renovation": "bestand"}));
assert!(has_wall(&ba, "W2"));
// View: Schlüssel unterscheidet die Kombinationen.
let k = |r: &[(String, String)]| crate::renovation::View::with(&p, Some("umbauplan"), None, &[], r).unwrap().key();
assert_ne!(k(&[]), k(&parse_text("Dachform=B")));
}
fn section_prims(p: &Project, extra: Value) -> Vec<Primitive> {
let level = p.drawing_levels.iter().find(|l| l.id == "schnitt-a").unwrap();
let mut v = json!({"level": level, "scale": 50, "detail": "mittel"});
for (k, x) in extra.as_object().unwrap() {
v[k] = x.clone();
}
let buf = crate::queries::run_bin(p, "sectionPlan", &[0.0, 1.0, 0.0], &v.to_string()).unwrap();
crate::plan::buf::View::parse(&buf).and_then(|v| v.prims()).unwrap_or_default()
}
fn elevation_prims(p: &Project, extra: Value) -> Vec<Primitive> {
let level = p.drawing_levels.iter().find(|l| l.id == "ansicht-sued").unwrap();
let mut v = json!({"level": level});
for (k, x) in extra.as_object().unwrap() {
v[k] = x.clone();
}
let buf = crate::queries::run_bin(p, "elevationPlan", &[0.0, 0.0, 100.0], &v.to_string()).unwrap();
crate::plan::buf::View::parse(&buf).and_then(|v| v.prims()).unwrap_or_default()
}
fn ids_in(prims: &[Primitive]) -> HashSet<String> {
prims.iter().filter_map(|q| crate::renovation::prim_element(q).map(String::from)).collect()
}
#[test]
fn schnitt_und_ansicht_je_kombination() {
let p = project(&fixture());
let a = ids_in(&section_prims(&p, json!({})));
let b = ids_in(&section_prims(&p, json!({"designOptions": "Dachform=B"})));
assert!(!a.contains("RF1") && b.contains("RF1"), "{a:?} / {b:?}");
// Kombination der Ebene (Schnitt-Ebene).
let mut v = fixture();
for l in v["drawingLevels"].as_array_mut().unwrap() {
if l["id"] == "schnitt-a" || l["id"] == "ansicht-sued" {
l["designOptions"] = json!({"dach": "b"});
}
}
let q = project(&v);
assert!(ids_in(&section_prims(&q, json!({}))).contains("RF1"));
// Ansicht: das Dach erscheint nur in B (andere Bilder).
let ea = elevation_prims(&p, json!({}));
let eb = elevation_prims(&p, json!({"designOptions": "Dachform=B"}));
assert_ne!(format!("{ea:?}"), format!("{eb:?}"));
assert_eq!(format!("{eb:?}"), format!("{:?}", elevation_prims(&q, json!({}))));
}
#[test]
fn drei_d_axo_und_exporte_je_kombination() {
let p = project(&fixture());
let parts = |t: &str| -> Value { serde_json::from_str(&crate::queries::run(&p, "model3dParts", &[1.0, 1.0, 0.0], t).unwrap()).unwrap() };
let ids = |v: &Value| v["walls"].as_array().unwrap().iter().map(|w| w["wallId"].as_str().unwrap().to_string()).collect::<Vec<_>>();
let a = parts("");
let b = parts(r#"{"designOptions": "Dachform=B"}"#);
assert!(ids(&a).contains(&"W2".to_string()) && !ids(&a).contains(&"W9".to_string()));
assert!(ids(&b).contains(&"W9".to_string()) && !ids(&b).contains(&"W2".to_string()));
// Mit Umbaufilter und Kombination zusammen.
let nb = parts(r#"{"renovation": "neubau", "designOptions": "Dachform=B"}"#);
assert!(ids(&nb).contains(&"W9".to_string()));
// Picken trifft keine Elemente anderer Varianten.
let pick = crate::queries::run(&p, "pickGeometry", &[], "").unwrap();
assert!(!pick.contains("\"W9\"") && pick.contains("\"W2\""));
// Dokument (Cache-Weg) wie ohne Cache.
let mut d = crate::document::Document::from_json(&fixture().to_string()).unwrap();
let doc = crate::queries::run_doc(&mut d, "model3dParts", &[1.0, 1.0, 0.0, 0.0], "").unwrap();
assert!(!doc.contains("\"W9\"") && doc.contains("\"W2\""));
// IFC: Hauptkombination bzw. die angefragte.
let ifc = |t: &str| crate::queries::run_bin(&p, "ifcExportData", &[0.0, 0.0, 0.0, 0.0], t).unwrap();
let names = |b: &[u8]| String::from_utf8_lossy(b).to_string();
let ia = names(&ifc("2026-11-17T00:00:00Z"));
let ib = names(&ifc(r#"{"iso": "2026-11-17T00:00:00Z", "designOptions": "Dachform=B"}"#));
assert!(ia.contains("W2") && !ia.contains("W9"), "IFC A");
assert!(ib.contains("W9") && !ib.contains("W2"), "IFC B");
// Axo (3D-Dokument): andere Bilder je Kombination.
let axo = |t: Value| crate::queries::run_bin(&p, "axoPlan", &[0.0, 100.0], &t.to_string()).unwrap();
assert_ne!(axo(json!({})), axo(json!({"designOptions": "Dachform=B"})));
}
#[test]
fn kennzahlen_und_kosten_je_variante() {
let p = project(&fixture());
let ka = crate::queries::run(&p, "kennzahlen", &[], "").unwrap();
let kb = crate::queries::run(&p, "kennzahlen", &[], r#"{"designOptions": "Dachform=B"}"#).unwrap();
assert_ne!(ka, kb, "R1 zählt nur in A");
let rows = compare(&p, None, None);
assert_eq!(rows.len(), 2);
assert!(rows[0].primary && !rows[1].primary);
assert_eq!(rows[0].label, "Dachform A");
assert!(rows[0].hnf > rows[1].hnf, "{} / {}", rows[0].hnf, rows[1].hnf);
assert!(rows.iter().all(|r| r.gf.is_finite() && r.cost.is_finite()));
// Mit Umbaufilter.
let rb = compare(&p, Some("bestand"), None);
assert_eq!(rb.len(), 2);
// Abfrage und CSV.
let q: Value = serde_json::from_str(&crate::queries::run(&p, "designOptionCompare", &[], "").unwrap()).unwrap();
assert_eq!(q.as_array().unwrap().len(), 2);
let csv: String = serde_json::from_str(&crate::queries::run(&p, "designOptionCompare", &[], r#"{"head": ["Variante","GF","HNF","GV","Fussabdruck","AZ","ÜZ","Kosten"]}"#).unwrap()).unwrap();
assert!(csv.starts_with("Variante;GF;"));
assert_eq!(csv.lines().count(), 3);
// Info: Zahl der Elemente je Variante.
let info: Value = serde_json::from_str(&crate::queries::run(&p, "designOptionInfo", &[], "").unwrap()).unwrap();
assert_eq!(info[0]["options"][1]["count"], 4);
assert_eq!(info[0]["primary"], "a");
}
fn doc() -> crate::document::Document {
crate::document::Document::from_json(&fixture().to_string()).unwrap()
}
fn apply(d: &mut crate::document::Document, ops: &[Value]) {
let ops: Vec<crate::ops::Op> = ops.iter().map(|o| crate::ops::Op::from_json(o).unwrap()).collect();
d.commit(ops, None, 0.0, false).unwrap();
}
fn root_ops(d: &crate::document::Document, name: &str, text: Value) -> Vec<Value> {
serde_json::from_str(&crate::queries::run_root(&d.lookup(), name, &text.to_string()).unwrap()).unwrap()
}
#[test]
fn variante_uebernehmen_und_rueckgaengig() {
let mut d = doc();
// Gespeicherte Wahl an einer Ebene wird mit aufgeräumt.
apply(&mut d, &[json!({"kind": "replace", "collection": "drawingLevels", "entity": {"id": "eg", "name": "EG", "kind": "floor", "designOptions": {"dach": "b"}}})]);
let before = d.to_json();
let ops = root_ops(&d, "designOptionAcceptOps", json!({"set": "dach", "option": "b"}));
apply(&mut d, &ops);
let p = d.project().unwrap().clone();
assert!(p.design_option_sets.as_deref().unwrap_or(&[]).is_empty());
let w9 = p.walls.iter().find(|w| w.id == "W9").unwrap();
assert!(w9.design_option.is_none());
assert!(p.walls.iter().all(|w| w.id != "W2"), "Variante A gelöscht");
assert!(p.rooms.iter().flatten().all(|r| r.id != "R1"));
assert!(p.openings.iter().flatten().any(|o| o.id == "O2" && o.design_option.is_none()));
assert!(p.drawing_levels.iter().all(|l| l.design_options.is_none()));
// Öffnungen der gelöschten Wand W2 (keine) — die übrigen bleiben.
assert!(p.openings.iter().flatten().any(|o| o.id == "O1"));
// Ein Undo-Schritt stellt alles wieder her.
d.undo().unwrap();
assert_eq!(d.to_json(), before);
// Unbekannt: keine Ops.
assert!(root_ops(&d, "designOptionAcceptOps", json!({"set": "dach", "option": "z"})).is_empty());
assert!(root_ops(&d, "designOptionAcceptOps", json!({"set": "weg", "option": "a"})).is_empty());
}
#[test]
fn satz_und_variante_loeschen() {
let mut d = doc();
let ops = root_ops(&d, "designOptionDeleteOps", json!({"set": "dach"}));
apply(&mut d, &ops);
let p = d.project().unwrap().clone();
assert!(p.design_option_sets.as_deref().unwrap_or(&[]).is_empty());
for id in ["W2", "W9"] {
assert!(p.walls.iter().all(|w| w.id != id), "{id}");
}
assert!(p.roofs.iter().flatten().all(|r| r.id != "RF1"));
assert!(p.drawings2d.iter().all(|x| x.id != "L-b"));
// Variante löschen: Hauptvariante A weg ⇒ B wird Haupt.
let mut d = doc();
let ops = root_ops(&d, "designOptionDeleteOps", json!({"set": "dach", "option": "a"}));
apply(&mut d, &ops);
let p = d.project().unwrap().clone();
let s = &p.design_option_sets.as_ref().unwrap()[0];
assert_eq!(s.options.len(), 1);
assert_eq!(s.primary.as_deref(), Some("b"));
assert!(p.walls.iter().all(|w| w.id != "W2") && p.walls.iter().any(|w| w.id == "W9"));
// Jetzt zeigt die Hauptkombination B.
assert!(!Combination::primary(&p).hidden(&p).contains("W9"));
}
#[test]
fn zuweisen_und_kopieren() {
let mut d = doc();
let sel = json!({"walls": ["W1", "W9"], "rooms": ["R1"]});
let ops = root_ops(&d, "designOptionAssignOps", json!({"set": "dach", "option": "b", "sel": sel}));
// W9 ist schon in B: nur W1 und R1.
assert_eq!(ops.len(), 2);
apply(&mut d, &ops);
let p = d.project().unwrap().clone();
assert_eq!(p.walls.iter().find(|w| w.id == "W1").unwrap().design_option.as_ref().unwrap().option, "b");
// Zurück ins Hauptmodell.
let ops = root_ops(&d, "designOptionAssignOps", json!({"sel": {"walls": ["W1"]}}));
apply(&mut d, &ops);
assert!(d.project().unwrap().walls.iter().find(|w| w.id == "W1").unwrap().design_option.is_none());
// Unbekannte Variante: nichts.
assert!(root_ops(&d, "designOptionAssignOps", json!({"set": "dach", "option": "q", "sel": {"walls": ["W1"]}})).is_empty());
// Kopieren: W1 samt Öffnungen D1/O1 in Variante A, neue Ids, Öffnungen auf der Kopie.
let ops = root_ops(&d, "designOptionCopyOps", json!({"set": "dach", "option": "a", "sel": {"walls": ["W1"]}, "stamp": "k"}));
apply(&mut d, &ops);
let p = d.project().unwrap().clone();
let copy = p.walls.iter().find(|w| w.id.starts_with("k-")).unwrap();
assert_eq!(copy.design_option.as_ref().unwrap().option, "a");
let kids: Vec<_> = p.openings.iter().flatten().filter(|o| o.host_wall_id == copy.id).collect();
assert_eq!(kids.len(), 2);
assert!(kids.iter().all(|o| o.design_option.as_ref().is_some_and(|r| r.option == "a")));
}
#[test]
fn neue_elemente_tragen_die_zeichen_variante() {
use crate::ops::Op;
let add = |c: &str| Op::Add { collection: c.into(), items: vec![json!({"id": "x"}), json!({"id": "y", "designOption": {"set": "s", "option": "o"}})], at: None };
let out = stamp_ops(vec![add("walls"), add("drawings2d"), add("layers")], Some(&json!({"set": "dach", "option": "b"})));
match &out[0] {
Op::Add { items, .. } => {
assert_eq!(items[0]["designOption"], json!({"set": "dach", "option": "b"}));
assert_eq!(items[1]["designOption"]["set"], "s");
}
_ => panic!(),
}
assert!(matches!(&out[1], Op::Add { items, .. } if items[0]["designOption"]["option"] == "b"));
assert!(matches!(&out[2], Op::Add { items, .. } if items[0].get("designOption").is_none()));
for r in [json!({"set": "", "option": "b"}), json!({"set": 3}), json!(42), json!(null)] {
let o = stamp_ops(vec![add("walls")], Some(&r));
assert!(matches!(&o[0], Op::Add { items, .. } if items[0].get("designOption").is_none()), "{r}");
}
// Über den Befehl: `designOption` der Anfrage.
let p = project(&fixture());
let root = serde_json::to_value(&p).unwrap();
let cmd = json!({"cmd": "wall", "levelId": "eg", "points": [{"x": 0, "y": 10}, {"x": 4, "y": 10}], "designOption": {"set": "dach", "option": "b"}});
if let Ok(ops) = crate::commands::ops(root.as_object().unwrap(), &p, &cmd.to_string()) {
for op in ops {
if let Op::Add { collection, items, .. } = op {
if collection == "walls" {
assert!(items.iter().all(|i| i["designOption"]["option"] == "b"));
}
}
}
}
}
#[test]
fn blatt_viewport_mit_eigener_kombination() {
let p = project(&fixture());
let snap: ViewSnapshot = serde_json::from_value(json!({"id": "s", "name": "EG", "activeLevelId": "eg", "viewType": "grundriss", "scaleDenominator": 100, "detail": "mittel", "layerVisibility": {}, "drawingVisibility": {}})).unwrap_or_default();
let mut vp = LayoutViewport::default();
vp.design_options = Some([("dach".to_string(), "b".to_string())].into());
let s2 = crate::sheet_viewports::viewport_snapshot(&snap, &vp);
assert_eq!(s2.design_options.as_ref().unwrap()["dach"], "b");
let q = crate::sheet_viewports::snapshot_project(&p, &s2);
let l = q.drawing_levels.iter().find(|l| l.id == "eg").unwrap();
assert_eq!(l.design_options.as_ref().unwrap()["dach"], "b");
// Ohne eigene Wahl unverändert (geliehen).
assert!(matches!(crate::sheet_viewports::viewport_snapshot(&snap, &LayoutViewport::default()), std::borrow::Cow::Borrowed(_)));
}
#[test]
fn robust_bei_unsinn() {
// Fehlende Felder, leere Sätze, Sätze ohne Varianten, unbekannte Ids, Unsinn in Anfragen.
let mut v = fixture();
v["designOptionSets"].as_array_mut().unwrap().push(json!({"id": "leer", "name": "", "options": []}));
v["designOptionSets"].as_array_mut().unwrap().push(json!({}));
v["walls"][0]["designOption"] = json!({});
v["walls"][1]["designOption"] = json!({"set": "dach"});
let p = project(&v);
let c = Combination::primary(&p);
assert!(!c.choice.contains_key("leer"));
assert!(c.shows(p.walls[0].design_option.as_ref()), "leere Angabe = Hauptmodell");
for t in ["", "{", "{}", "nan", r#"{"designOptions": 42}"#, r#"{"designOptions": [1, 2]}"#, r#"{"designOptions": {"dach": null}}"#, r#"{"renovation": 5}"#] {
assert!(crate::queries::run(&p, "kennzahlen", &[], t).is_ok(), "{t}");
assert!(crate::queries::run(&p, "designOptionCompare", &[], t).is_ok(), "{t}");
assert!(crate::queries::run(&p, "model3dParts", &[1.0, f64::NAN, 0.0], t).is_ok(), "{t}");
}
let _ = plan_with(&p, json!({"designOptions": 42}));
let _ = plan_with(&p, json!({"designOptions": {"dach": [1]}}));
// Ops-Abfragen mit Unsinn: keine Ops bzw. Fehler, nie Panic.
let d = crate::document::Document::from_json(&v.to_string()).unwrap();
for t in ["{}", r#"{"set": 1}"#, r#"{"sel": 5}"#, r#"{"set": "dach", "option": "b", "sel": {"walls": [1]}}"#] {
for n in ["designOptionAcceptOps", "designOptionDeleteOps", "designOptionAssignOps", "designOptionCopyOps"] {
let _ = crate::queries::run_root(&d.lookup(), n, t);
}
}
assert!(crate::queries::run_root(&d.lookup(), "designOptionAcceptOps", "kaputt").is_err());
// Vergleich über viele Sätze bleibt beschränkt.
let mut many = fixture();
let sets: Vec<Value> = (0..8).map(|i| json!({"id": format!("s{i}"), "name": format!("S{i}"), "options": [{"id": "a", "name": "A"}, {"id": "b", "name": "B"}, {"id": "c", "name": "C"}]})).collect();
many["designOptionSets"] = Value::Array(sets);
many["walls"][0]["designOption"] = json!({"set": "s0", "option": "b"});
let pm = project(&many);
assert!(Combination::all(&pm).len() <= MAX_COMPARE);
}
+1
View File
@@ -60,6 +60,7 @@ pub use dossier_hatch::hatch;
pub mod hatch_flat;
pub mod plan;
pub mod renovation;
pub mod design_options;
pub mod project_format;
pub mod queries;
pub mod gpu_compile;
+98
View File
@@ -1963,6 +1963,10 @@ pub struct DrawingLevel {
#[serde(rename = "renovationPhase", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub renovation_phase: Option<String>,
/// [272] Variantenkombination: Satz-Id → Varianten-Id (fehlende Sätze ⇒ Hauptvariante).
#[serde(rename = "designOptions", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_options: Option<std::collections::BTreeMap<String, String>>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -2058,6 +2062,10 @@ pub struct ViewTemplate {
#[serde(rename = "renovationPhase", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub renovation_phase: Option<String>,
/// [272] Variantenkombination: Satz-Id → Varianten-Id (fehlende Sätze ⇒ Hauptvariante).
#[serde(rename = "designOptions", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_options: Option<std::collections::BTreeMap<String, String>>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -3043,6 +3051,47 @@ pub struct RenovationFilter {
pub extra: Extra,
}
/// [272] Zugehörigkeit eines Elements zu einer Variante (Archicad „Design Options“).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
#[serde(default)]
pub struct DesignOptionRef {
/// Id des Variantensatzes (`DesignOptionSet.id`).
pub set: String,
/// Id der Variante im Satz (`DesignOption.id`).
pub option: String,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
}
/// [272] Eine Variante eines Satzes (z. B. „A Flachdach“).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
#[serde(default)]
pub struct DesignOption {
pub id: String,
pub name: String,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
}
/// [272] Ein Variantensatz (z. B. „Dachform“) mit seinen Varianten; je Darstellung ist genau eine Variante des
/// Satzes sichtbar (Vorgabe: die Hauptvariante).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
#[serde(default)]
pub struct DesignOptionSet {
pub id: String,
pub name: String,
pub options: Vec<DesignOption>,
/// Id der Hauptvariante. Fehlt/unbekannt ⇒ die erste Variante.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub primary: Option<String>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
}
/// [271] Umbau-Einstellungen des Projekts.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
#[serde(default)]
@@ -3236,6 +3285,10 @@ pub struct Wall {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub renovation: Option<Renovation>,
/// [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
#[serde(rename = "designOption", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_option: Option<DesignOptionRef>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -3398,6 +3451,10 @@ pub struct Ceiling {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub renovation: Option<Renovation>,
/// [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
#[serde(rename = "designOption", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_option: Option<DesignOptionRef>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -3605,6 +3662,10 @@ pub struct Roof {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub renovation: Option<Renovation>,
/// [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
#[serde(rename = "designOption", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_option: Option<DesignOptionRef>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -4101,6 +4162,10 @@ pub struct Opening {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub renovation: Option<Renovation>,
/// [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
#[serde(rename = "designOption", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_option: Option<DesignOptionRef>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -4366,6 +4431,10 @@ pub struct Stair {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub renovation: Option<Renovation>,
/// [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
#[serde(rename = "designOption", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_option: Option<DesignOptionRef>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -4646,6 +4715,10 @@ pub struct Room {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub renovation: Option<Renovation>,
/// [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
#[serde(rename = "designOption", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_option: Option<DesignOptionRef>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -4884,6 +4957,10 @@ pub struct Drawing2D {
#[serde(rename = "hatchSource", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub hatch_source: Option<AttributeSource>,
/// [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
#[serde(rename = "designOption", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_option: Option<DesignOptionRef>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -4998,6 +5075,10 @@ pub struct ExtrudedSolid {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub renovation: Option<Renovation>,
/// [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
#[serde(rename = "designOption", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_option: Option<DesignOptionRef>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -5109,6 +5190,10 @@ pub struct Column {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub renovation: Option<Renovation>,
/// [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
#[serde(rename = "designOption", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_option: Option<DesignOptionRef>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -5670,6 +5755,10 @@ pub struct ViewSnapshot {
#[serde(rename = "renovationPhase", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub renovation_phase: Option<String>,
/// [272] Variantenkombination: Satz-Id → Varianten-Id (fehlende Sätze ⇒ Hauptvariante).
#[serde(rename = "designOptions", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_options: Option<std::collections::BTreeMap<String, String>>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -5869,6 +5958,10 @@ pub struct LayoutViewport {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub center: Option<Vec2>,
/// [272] Variantenkombination des Viewports (über der des Ausschnitts): Satz-Id → Varianten-Id (fehlende Sätze ⇒ Hauptvariante).
#[serde(rename = "designOptions", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_options: Option<std::collections::BTreeMap<String, String>>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -6764,6 +6857,11 @@ pub struct Project {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub renovation: Option<RenovationSettings>,
/// [272] Variantensätze (Archicad „Design Options“): Elemente mit `designOption` erscheinen nur in der
/// Kombination ihrer Variante.
#[serde(rename = "designOptionSets", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_option_sets: Option<Vec<DesignOptionSet>>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
+7 -1
View File
@@ -636,6 +636,10 @@ pub fn snapshot_text(snap: &ViewSnapshot, invisible: &[String]) -> String {
}
o.insert("hasVis".into(), serde_json::Value::Bool(true));
o.insert("invisible".into(), serde_json::to_value(invisible).unwrap_or_default());
// [272] Variantenkombination des Ausschnitts.
if let Some(m) = snap.design_options.as_ref().filter(|m| !m.is_empty()) {
o.insert("designOptions".into(), serde_json::to_value(m).unwrap_or_default());
}
}
v.to_string()
}
@@ -706,7 +710,9 @@ pub fn axo_plan_buf(p: &Project, args: &[f64], text: &str) -> Result<Vec<u8>, St
let scale = args.get(1).copied().filter(|s| s.is_finite() && *s > 0.0).unwrap_or(100.0);
let mut w = crate::plan::buf::Writer::new(true);
// [271] Umbaufilter (`renovation`, `renovationPhase`): Ausgeblendetes fehlt, Flächen in der Umbau-Farbe.
let ren = crate::renovation::View::new(p, v.get("renovation").and_then(|x| x.as_str()), v.get("renovationPhase").and_then(|x| x.as_str())).map(|r| r.resolve(p));
// [272] Variantenkombination (`designOptions`, sonst die Hauptvarianten): andere Varianten fehlen.
let opts = crate::design_options::parse_request(v.get("designOptions"));
let ren = crate::renovation::View::with(p, v.get("renovation").and_then(|x| x.as_str()), v.get("renovationPhase").and_then(|x| x.as_str()), &[], &opts).map(|r| r.resolve(p));
let filtered = ren.as_ref().filter(|r| !r.hidden.is_empty()).map(|r| crate::renovation::without_hidden(p, &r.hidden));
let p = filtered.as_ref().unwrap_or(p);
let Some(a) = AxoArgs::parse(p, &v) else { return Ok(w.finish()) };
+1
View File
@@ -149,6 +149,7 @@ pub fn ctx_key(a: &PlanArgs) -> String {
format!("{}\u{1}{:?}\u{1}{}\u{1}{}\u{1}{}\u{1}{}\u{1}{}\u{1}{}\u{1}{}\u{1}{}", a.floor, a.detail, a.reference_lines, a.global, a.scale.to_bits(), a.for_print, a.compact, a.mono, a.auto_coarse, rules) + &a.model_view.as_deref().map_or(String::new(), |m| format!("\u{1}mv:{m}"))
+ &a.trace_of.as_deref().map_or(String::new(), |t| format!("\u{1}trace:{t}"))
+ &a.renovation.as_deref().map_or(String::new(), |t| format!("\u{1}ren:{t}:{}", a.renovation_phase.as_deref().unwrap_or("")))
+ &a.design_options.iter().map(|(k, v)| format!("\u{1}opt:{k}={v}")).collect::<String>()
}
/// Sichtbarkeit und Dimmen als vergleichbarer Text (Mengen sortiert).
+1
View File
@@ -57,6 +57,7 @@ fn floor_args(a: &PlanArgs, floor: &str) -> PlanArgs {
trace_of: None,
renovation: a.renovation.clone(),
renovation_phase: a.renovation_phase.clone(),
design_options: a.design_options.clone(),
}
}
+6 -2
View File
@@ -68,6 +68,9 @@ pub struct PlanArgs {
/// `None` = der der Ebene (`DrawingLevel.renovationFilter`), sonst kein Filter (`renovation.rs`).
pub renovation: Option<String>,
pub renovation_phase: Option<String>,
/// [272] Ausdrücklich angefragte Variantenkombination (Blatt-Viewport, CLI `--options`), über der der Ebene
/// (`DrawingLevel.designOptions`) und den Hauptvarianten (`design_options.rs`).
pub design_options: crate::design_options::Request,
}
/// [140] Ab diesem Massstab (1:N) zeichnet der Detailgrad „mittel" wie „grob".
@@ -116,6 +119,7 @@ impl PlanArgs {
trace_of: v.get("traceOf").and_then(|m| m.as_str()).filter(|m| !m.is_empty()).map(String::from),
renovation: v.get("renovation").and_then(|m| m.as_str()).filter(|m| !m.is_empty()).map(String::from),
renovation_phase: v.get("renovationPhase").and_then(|m| m.as_str()).filter(|m| !m.is_empty()).map(String::from),
design_options: crate::design_options::parse_request(v.get("designOptions")),
})
}
@@ -174,7 +178,7 @@ impl<'a> Ctx<'a> {
}
let mut hidden = overrides::hidden_elements(p, overrides::RuleView::at(a.scale, a.rules.as_ref()).view("plan"));
// [271] Umbaufilter: ausgeblendete Bauteile wie bei der Regel „Ausblenden“ (eine Öffnung schliesst ihre Wand).
let ren = crate::renovation::View::for_level(p, &a.floor, a.renovation.as_deref(), a.renovation_phase.as_deref()).map(|v| v.resolve(p)).filter(|r| !r.is_empty());
let ren = crate::renovation::View::for_level(p, &a.floor, a.renovation.as_deref(), a.renovation_phase.as_deref(), &a.design_options).map(|v| v.resolve(p)).filter(|r| !r.is_empty());
if let Some(r) = &ren {
hidden.extend(r.hidden.iter().cloned());
}
@@ -1668,7 +1672,7 @@ pub fn room_stamp_spots(p: &Project, floor: &str, show: &HashSet<String>, scale:
return out;
}
let (detail, auto_coarse) = effective_detail(Detail::Mittel, scale);
let a = PlanArgs { floor: floor.to_string(), detail, show: show.clone(), grey: HashSet::new(), reference_lines: false, global: true, scale, for_print: false, compact: false, mono: false, sun_when: None, auto_coarse, rules: None, model_view: None, trace_of: None, renovation: None, renovation_phase: None };
let a = PlanArgs { floor: floor.to_string(), detail, show: show.clone(), grey: HashSet::new(), reference_lines: false, global: true, scale, for_print: false, compact: false, mono: false, sun_when: None, auto_coarse, rules: None, model_view: None, trace_of: None, renovation: None, renovation_phase: None, design_options: Vec::new() };
let Ok(d) = plan_domains(p, &a) else { return out };
for q in d.rooms.iter().chain(&d.sections) {
if let Primitive::Text { at, room_id: Some(id), .. } = q {
+2
View File
@@ -2077,6 +2077,8 @@ fn on_floor(c: &Ctx, d: &Drawing2D) -> bool {
&& !(matches!(d.geom, Drawing2DGeom::Grid { .. }) && c.a.trace_of.as_deref().is_some_and(|t| crate::grid::visible_on(d, t)))
&& !(c.a.for_print && d.no_print == Some(true))
&& c.mv().dims.shows(d)
// [272] Zeichnungen anderer Varianten (und künftig von Regeln ausgeblendete) fehlen.
&& !c.rule_hidden(&d.id)
}
/// Domäne „2D-Zeichnungen" von `planDomains`: alle gezeichneten Zeichnungen des Geschosses in
+1
View File
@@ -1783,6 +1783,7 @@ fn sheets(cx: &mut Ctx, main: &mut Buf, layer_by_code: &HashMap<&str, String>) {
trace_of: None,
renovation: None,
renovation_phase: None,
design_options: Vec::new(),
};
if let Some(entries) = plan_domains_buf(p, &args).ok().and_then(|buf| {
let view = View::parse(&buf)?;
+1 -1
View File
@@ -786,7 +786,7 @@ pub fn post_for(p: &Project, a: &super::domains::PlanArgs) -> Option<Post> {
let sketch = if sheet { 0.0 } else { sketch_k(level.and_then(|l| l.sketch), a.scale) };
// [271] Umbau-Farben bleiben auch in Schwarz-Weiss (Tusche): ohne sie sagt ein Umbauplan nichts.
let keep = if a.mono {
crate::renovation::View::for_level(p, &a.floor, a.renovation.as_deref(), a.renovation_phase.as_deref()).map_or_else(KeepColors::default, |v| KeepColors::of(v.colors().iter().map(String::as_str)))
crate::renovation::View::for_level(p, &a.floor, a.renovation.as_deref(), a.renovation_phase.as_deref(), &a.design_options).map_or_else(KeepColors::default, |v| KeepColors::of(v.colors().iter().map(String::as_str)))
} else {
KeepColors::default()
};
+3
View File
@@ -134,6 +134,8 @@ pub struct LevelSpec {
/// [271] Umbaufilter und Etappe der Ebene (`renovationFilter`, `renovationPhase`).
pub renovation: Option<String>,
pub renovation_phase: Option<String>,
/// [272] Variantenkombination der Ebene (`designOptions`: Satz-Id → Varianten-Id).
pub design_options: Option<std::collections::BTreeMap<String, String>>,
}
impl LevelSpec {
@@ -154,6 +156,7 @@ impl LevelSpec {
model_view: v.get("modelViewOptionId").and_then(|m| m.as_str()).filter(|m| !m.is_empty()).map(String::from),
renovation: v.get("renovationFilter").and_then(|m| m.as_str()).filter(|m| !m.is_empty()).map(String::from),
renovation_phase: v.get("renovationPhase").and_then(|m| m.as_str()).filter(|m| !m.is_empty()).map(String::from),
design_options: v.get("designOptions").and_then(|m| m.as_object()).map(|m| m.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))).collect()),
}
}
+4 -2
View File
@@ -41,14 +41,16 @@ fn cache_put(key: (f64, u64), o: std::rc::Rc<Output>) {
}
/// [271] Umbaufilter eines Schnitts/einer Ansicht: `renovation`/`renovationPhase` im Aufruf (CLI, Blatt-Ausschnitt), sonst
/// die Felder der Ebene (`renovationFilter`, `renovationPhase`).
/// die Felder der Ebene (`renovationFilter`, `renovationPhase`). [272] Dazu die Variantenkombination: die der Ebene
/// (`designOptions`), darüber die angefragte (`designOptions` im Aufruf: Blatt-Viewport, CLI `--options`).
pub fn renovation_view(p: &Project, v: &serde_json::Value, level: &LevelSpec) -> Option<crate::renovation::View> {
let req = v.get("renovation").and_then(|m| m.as_str()).filter(|m| !m.is_empty());
let (f, ph) = match req {
Some(f) => (Some(f), v.get("renovationPhase").and_then(|m| m.as_str())),
None => (level.renovation.as_deref(), level.renovation_phase.as_deref()),
};
crate::renovation::View::new(p, f, ph)
let stored: Vec<&std::collections::BTreeMap<String, String>> = level.design_options.iter().collect();
crate::renovation::View::with(p, f, ph, &stored, &crate::design_options::parse_request(v.get("designOptions")))
}
/// Abfrage `sectionPlan`: `args` = `[mono, openings, key]` (`key` > 0
+1 -1
View File
@@ -168,7 +168,7 @@ fn tiefe_blendet_ferne_bauteile_aus() {
let mut p = Project::default();
// quer: von der Ebene geschnitten und weit nach hinten; nah: 3 m, fern: 10 m hinter der Ebene (höher).
p.walls = vec![wall("quer", (0.0, -1.0), (0.0, 12.0), 2.5), wall("nah", (2.0, 3.0), (6.0, 3.0), 2.5), wall("fern", (2.0, 10.0), (6.0, 10.0), 4.0)];
let lv = |depth: Option<f64>| LevelSpec { model_view: None, renovation: None, renovation_phase: None, bends: Vec::new(), sketch: false, cut_hatch: false, kind: "section".into(), line: Some([Vec2 { x: -1.0, y: 0.0 }, Vec2 { x: 8.0, y: 0.0 }]), direction_sign: Some(1.0), depth, shadows: false, hidden_lines: false };
let lv = |depth: Option<f64>| LevelSpec { model_view: None, renovation: None, renovation_phase: None, design_options: None, bends: Vec::new(), sketch: false, cut_hatch: false, kind: "section".into(), line: Some([Vec2 { x: -1.0, y: 0.0 }, Vec2 { x: 8.0, y: 0.0 }]), direction_sign: Some(1.0), depth, shadows: false, hidden_lines: false };
let top = |o: &Output| o.visible.iter().map(|e| e.a[1].max(e.b[1])).fold(f64::NEG_INFINITY, f64::max);
let all = compute_section(&p, &lv(None), &[]).unwrap().unwrap();
assert!(top(&all) > 3.9, "ohne Tiefe ist die ferne Wand sichtbar: {}", top(&all));
+2 -1
View File
@@ -15,7 +15,7 @@ const REQUIRED_ARRAYS: [&str; 3] = ["walls", "layers", "drawingLevels"];
const DEFAULT_ARRAYS: [&str; 5] = ["lineStyles", "hatches", "components", "wallTypes", "drawings2d"];
/// Bekannte Felder von `Project` (für die Meldung unbekannter Felder).
const KNOWN_KEYS: [&str; 60] = [
const KNOWN_KEYS: [&str; 61] = [
"formatVersion", "id", "name", "lineStyles", "textStyles", "hatches", "components", "wallTypes",
"ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens",
"penSets", "activePenSetId", "customPalettes", "builtinPaletteBanks", "drawingLevels", "layers",
@@ -27,6 +27,7 @@ const KNOWN_KEYS: [&str; 60] = [
"modelViewOptions", "cameras",
"costEstimate",
"renovation",
"designOptionSets",
];
/// Ergebnis des Einlesens.
+67 -30
View File
@@ -16,7 +16,10 @@ pub fn run_doc(d: &mut crate::document::Document, name: &str, args: &[f64], text
// des Aufrufers (0 = alles), Antwort als Änderung (`model3d_cache::write_delta`).
let delta = (name == "model3dPartsDelta").then(|| args.get(5).copied().filter(|m| m.is_finite() && *m >= 0.0).unwrap_or(0.0) as u64);
// [173] Mit Modelldarstellung (`text`) ohne den Cache (eigene Teile, s. `model3d_mv`).
if (name == "model3dParts" || delta.is_some()) && args.len() >= 3 && !explode && model3d_mv_id(text).is_none() && !text.contains("\"renovation\"") {
// [272] Mit Varianten ohne den Cache (die Teile hängen an der Kombination).
// Die Änderungs-Abfrage bleibt beim Cache (die Hülle fragt bei Varianten `model3dParts`, `toWalls3d.ts`).
let options = name == "model3dParts" && d.project().is_ok_and(crate::design_options::active);
if (name == "model3dParts" || delta.is_some()) && args.len() >= 3 && !explode && model3d_mv_id(text).is_none() && !text.contains("\"renovation\"") && !options {
let voids = args.get(3).is_some_and(|v| *v != 0.0);
// [214] Ohne Abzugskörper braucht es die Wände/Decken nicht als Werte (spart das Kopieren): leere `voidMeshes`.
if voids && crate::plan::extras::void_prisms(d.project()?).is_empty() {
@@ -68,19 +71,16 @@ fn model3d_mv(p: &Project, text: &str, detail: f64) -> (f64, bool) {
(base, o.stair.handrail.is_some())
}
/// [271] Projekt im Umbau-Zustand des Texts (`renovation::view_from_text`), sonst unverändert.
/// [271] Projekt im Umbau-Zustand des Texts (`renovation::view_from_text`), [272] in der Variantenkombination des
/// Texts (`designOptions`, sonst die Hauptvarianten), sonst unverändert.
fn renovation_state<'a>(p: &'a Project, text: &str) -> std::borrow::Cow<'a, Project> {
match crate::renovation::view_from_text(p, text) {
Some(v) => {
let r = v.resolve(p);
if r.hidden.is_empty() {
std::borrow::Cow::Borrowed(p)
} else {
std::borrow::Cow::Owned(crate::renovation::without_hidden(p, &r.hidden))
}
}
None => std::borrow::Cow::Borrowed(p),
}
crate::renovation::project_for_text(p, text)
}
/// [272] Projekt in der Kombination eines JSON-Texts (`designOptions`, Umbaufilter), sonst in den Hauptvarianten;
/// für Abfragen, deren Text keine Darstellung ist (dann zählt nur ein JSON-Objekt).
fn options_state<'a>(p: &'a Project, text: &str) -> std::borrow::Cow<'a, Project> {
crate::renovation::project_for_text(p, if text.trim_start().starts_with('{') { text } else { "" })
}
/// Führt die Abfrage `name` aus. `args`: Zahlen, `text`: ein Text (z. B. eine id).
@@ -92,34 +92,46 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
// [271] Umbaufilter (eingebaute und eigene) für die Oberfläche.
("renovationFilters", _) => json(&crate::renovation::filter_list(p)),
// [209] Kostenschätzung grob; `costDefaults` mit Text „gf“/„gv“ = Beispielwerte der Methode.
("costEstimate", _) => json(&crate::kosten::estimate(p)),
("costEstimate", _) => json(&crate::kosten::estimate(&renovation_state(p, text))),
// [272] Varianten: Sätze mit Varianten und Zahl der Elemente; Vergleich der Kennzahlen/Kosten je Kombination
// (`text` = `{"renovation", "renovationPhase"}` oder leer); CSV mit Spaltenköpfen (`text` = `{"head": [...]}`).
("designOptionInfo", _) => Ok(crate::design_options::info(p).to_string()),
("designOptionCompare", _) => {
let v: serde_json::Value = serde_json::from_str(text).unwrap_or_default();
let s = |k: &str| v.get(k).and_then(|x| x.as_str()).filter(|x| !x.is_empty());
let rows = crate::design_options::compare(p, s("renovation"), s("renovationPhase"));
match v.get("head").and_then(|h| h.as_array()) {
Some(h) => json(&crate::design_options::compare_csv(&rows, &h.iter().filter_map(|x| x.as_str().map(String::from)).collect::<Vec<_>>())),
None => json(&rows),
}
}
("costDefaults", _) => json(&crate::kosten::default_estimate(if text.trim() == "gf" { crate::model::CostMethod::Gf } else { crate::model::CostMethod::Gv })),
("ivhb", _) => {
let opt: flaechen::IvhbOptions = if text.trim().is_empty() { Default::default() } else { serde_json::from_str(text).map_err(|e| format!("ivhb: {e}"))? };
json(&flaechen::ivhb(p, &opt))
json(&flaechen::ivhb(&options_state(p, text), &opt))
}
// [255] Baurecht-Nachweis (Vorgaben der Parzelle gegen Kennzahlen); Text = `IvhbOptions` als JSON.
("siteProof", _) => {
let opt: flaechen::IvhbOptions = if text.trim().is_empty() { Default::default() } else { serde_json::from_str(text).map_err(|e| format!("siteProof: {e}"))? };
json(&crate::site_proof::site_proof(p, &opt))
json(&crate::site_proof::site_proof(&options_state(p, text), &opt))
}
("programCompare", _) => json(&room_program::compare(p)),
("programCompare", _) => json(&room_program::compare(&options_state(p, text))),
("programLayout", _) => {
let opt: room_program::LayoutOptions = if text.trim().is_empty() { Default::default() } else { serde_json::from_str(text).map_err(|e| format!("programLayout: {e}"))? };
json(&room_program::layout(p, &opt))
}
("siteCheck", _) => json(&site_rules::check_project(p)),
("siteCheck", _) => json(&site_rules::check_project(&options_state(p, text))),
// [215] Cycles-Szene (XML + Bilddateien) aus dem Projekt; Text = `CyclesOptions` als JSON (camelCase).
("cyclesScene", _) => {
let o: crate::cycles_scene::CyclesOptions = if text.trim().is_empty() { Default::default() } else { serde_json::from_str(text).map_err(|e| format!("cyclesScene: {e}"))? };
json(&crate::cycles_scene::cycles_scene(p, &o)?)
json(&crate::cycles_scene::cycles_scene(&options_state(p, text), &o)?)
}
("dormerStatus", _) => json(&crate::dormer::status(p)),
("excavationQuantities", _) => json(&crate::excavation::quantities(p)),
("buildingFootprint", _) => json(&site_rules::building_footprint(p)),
("modelTop", _) => json(&site_rules::model_top(p)),
("buildingFootprint", _) => json(&site_rules::building_footprint(&options_state(p, text))),
("modelTop", _) => json(&site_rules::model_top(&options_state(p, text))),
// [142] Drittes Argument: Schnitthöhe des Grundrisses (Decken/Dächer darunter fangen den Schatten).
("shadows", 2 | 3) => json(&site_rules::area_out(&sun::shadow_polygons_project(p, sun::SunPosition { azimuth: args[0], elevation: args[1] }, args.get(2).copied().filter(|c| c.is_finite())))),
("shadows", 2 | 3) => json(&site_rules::area_out(&sun::shadow_polygons_project(&options_state(p, text), sun::SunPosition { azimuth: args[0], elevation: args[1] }, args.get(2).copied().filter(|c| c.is_finite())))),
("materialMaps", _) => json(&model3d::wall_material_color_maps(p)),
("slabs", _) => json(&model3d::emit_slabs(p)),
("columnMeshes", _) => json(&model3d::emit_columns(p)),
@@ -130,10 +142,10 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
("stairRailings", _) => json(&model3d::emit_stair_railings(p)),
("roofMeshes", _) => json(&model3d::emit_roofs(p, if text.is_empty() { None } else { Some(text) })?),
("roofCutLayers", _) => json(&model3d::emit_roof_cut_layers(p)?),
("scheduleRows", _) => json(&export_schedule::schedule_rows(p)),
("openingSchedule", _) => json(&crate::opening_schedule::opening_schedule(p)),
("elementSchedule", _) => json(&crate::u_value::element_schedule(p)),
("roomBook", _) => json(&crate::room_book::room_book(p)),
("scheduleRows", _) => json(&export_schedule::schedule_rows(&options_state(p, text))),
("openingSchedule", _) => json(&crate::opening_schedule::opening_schedule(&options_state(p, text))),
("elementSchedule", _) => json(&crate::u_value::element_schedule(&options_state(p, text))),
("roomBook", _) => json(&crate::room_book::room_book(&options_state(p, text))),
("sheetTables", _) => Ok(crate::sheet_table::query(p, text).to_string()),
("sheetTableCatalog", _) => Ok(crate::sheet_table::catalog_json().to_string()),
("presentationSheet", _) => Ok(crate::presentation_sheet::query(p, text)?.to_string()),
@@ -148,6 +160,9 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
("explodeOffsets", _) => json(&crate::explode3d::floor_offsets(p, args.first().copied().unwrap_or(0.0))),
// [180] Ohne die Elemente ausgeblendeter Klassen (`text` = `{"hide": [codes]}`, s. `model3d::ClassFilter`).
("pickGeometry", _) => {
// [272] Elemente anderer Varianten nicht picken.
let q = options_state(p, text);
let p = q.as_ref();
let mut g = crate::explode3d::pick_geometry(p, args.first().copied().unwrap_or(0.0))?;
model3d::ClassFilter::from_text(p, text).retain_pick(&mut g);
json(&g)
@@ -160,9 +175,12 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
// `args[4]`: Explosionsabstand ([65], `explode3d.rs`; Körper und Abzugskörper wandern mit dem Geschoss).
// [180] Ohne die Teile ausgeblendeter Klassen (`text` = `{"hide": [codes], "modelView": …}`).
("model3dParts", n) if n >= 3 => {
// [272] Explosion in der Kombination des Texts (sonst Hauptvarianten); ohne Explosion unten mit Umbaufilter.
let opt_p = options_state(p, text);
let explode = args.get(4).copied().filter(|g| g.is_finite() && *g > 0.0);
let filter = model3d::ClassFilter::from_text(p, text);
if let Some(gap) = explode {
let p = opt_p.as_ref();
let parts = crate::explode3d::parts_filtered(p, args[0] != 0.0, args[1], args[2] != 0.0, gap, &filter)?;
let mut v = serde_json::to_value(&parts).map_err(|e| e.to_string())?;
if args.get(3).is_some_and(|v| *v != 0.0) {
@@ -190,7 +208,7 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
json(&parts)
}
// STEP-Export: alle Bauteile als truck-Spezifikationen (`solid_specs::project_solid_specs`).
("projectSolidSpecs", _) => json(&crate::solid_specs::project_solid_specs(p)?),
("projectSolidSpecs", _) => json(&crate::solid_specs::project_solid_specs(&options_state(p, text))?),
// [33] Von einer Regel „Ausblenden“ ausgeblendete Elemente (ids, sortiert): `args[0]` = Massstab 1:N
// (fehlt/NaN = ohne Massstab-Kriterium), `text` = Darstellung ("plan", "section", "elevation").
("hiddenElements", _) => {
@@ -247,6 +265,21 @@ pub fn run_root(lk: &crate::document::Lookup, name: &str, text: &str) -> Result<
match name {
// Stiftsätze ([K4] S3, `pens.rs`): Ops statt Projekt-Kopien.
"penRebakeOps" => json(&crate::pens::rebake_ops(root)),
// [272] Varianten (`design_options.rs`): `text` = JSON `{set, option?, sel?, stamp?}`; Antwort Ops (ein Undo-Schritt).
"designOptionAcceptOps" | "designOptionDeleteOps" | "designOptionAssignOps" | "designOptionCopyOps" => {
let a: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("{name}: {e}"))?;
let s = |k: &str| a.get(k).and_then(|x| x.as_str()).unwrap_or("").to_string();
let (set, option) = (s("set"), s("option"));
let target = (!set.is_empty() && !option.is_empty()).then_some((set.as_str(), option.as_str()));
let sel: crate::design_options::Selection = a.get("sel").and_then(|x| serde_json::from_value(x.clone()).ok()).unwrap_or_default();
json(&match name {
"designOptionAcceptOps" => crate::design_options::accept_ops(root, &set, &option),
"designOptionDeleteOps" if option.is_empty() => crate::design_options::delete_set_ops(root, &set),
"designOptionDeleteOps" => crate::design_options::delete_option_ops(root, &set, &option),
"designOptionAssignOps" => crate::design_options::assign_ops(root, &sel, target),
_ => crate::design_options::copy_ops(root, &sel, target, &s("stamp")),
})
}
"penDeleteOps" => json(&crate::pens::delete_pen_ops(root, text)),
// Standard-Bibliothek ([100]–[102], `standards.rs`): fehlende Standard-Ressourcen als Ops.
"standardsMergeOps" => json(&crate::standards::merge_ops_in(root, crate::standards::Lang::parse(text))),
@@ -333,13 +366,17 @@ pub fn run_bin(p: &Project, name: &str, args: &[f64], text: &str) -> Result<Vec<
// Export-Sammler ([K4], [B5], [C11]): flacher Puffer für `fileio` (Byte-Hülle `export_flat.rs`).
("ifcExportData", 4 | 5) => {
// 5. Argument [259]: Kontext (Gelände, Nachbarn) mitgeben.
let opt = crate::ifc_data::IfcOptions { now: args[0], ifc2x3: args[1] != 0.0, ebkph: args[2] != 0.0, layer_codes: args[3] != 0.0, context: args.get(4).is_some_and(|v| *v != 0.0), iso: text.to_string() };
crate::ifc_data::ifc_export_data(p, &opt).map(|f| f.to_bytes())
// [272] `text` = Zeitstempel (ISO) oder `{"iso", "designOptions", "renovation"}`: Kombination der Ansicht.
let json_text = text.trim_start().starts_with('{');
let iso = if json_text { serde_json::from_str::<serde_json::Value>(text).ok().and_then(|v| v.get("iso").and_then(|x| x.as_str()).map(String::from)).unwrap_or_default() } else { text.to_string() };
let q = options_state(p, text);
let opt = crate::ifc_data::IfcOptions { now: args[0], ifc2x3: args[1] != 0.0, ebkph: args[2] != 0.0, layer_codes: args[3] != 0.0, context: args.get(4).is_some_and(|v| *v != 0.0), iso };
crate::ifc_data::ifc_export_data(&q, &opt).map(|f| f.to_bytes())
}
("meshExportData", 3 | 4) => {
// 4. Argument [227]: Baugruben weglassen (hinterfüllt).
let opt = crate::mesh_data::MeshOptions { opening_parts: args[0] != 0.0, context: args[1] != 0.0, by_level: args[2] != 0.0, backfilled: args.get(3).is_some_and(|v| *v != 0.0) };
crate::mesh_data::mesh_export_data(p, &opt).map(|f| f.to_bytes())
crate::mesh_data::mesh_export_data(&options_state(p, text), &opt).map(|f| f.to_bytes())
}
// Gruppen der kompakten Linien-Unterlage (gleiche Argumente wie `planDomains`), als f64.
("drawingUnderlay", 1) => {
+88 -21
View File
@@ -17,6 +17,10 @@
//! bricht dort Mauerwerk ab — der Wandteil in der Öffnung ist ein Abbruch-Stück ([`Patch`], gelb). Eine Öffnung
//! „Abbruch“ wird zugemauert — die Ausfachung ist ein Neu-Stück (rot). Ist die Öffnung ausgeblendet (Bestand:
//! die neue Öffnung gibt es noch nicht; Neubau/Endzustand: die alte ist zu), ist die Wand dort geschlossen.
//! - **Varianten** ([272], `design_options.rs`): Die Variantenkombination der Darstellung (je Satz eine Variante,
//! Vorgabe die Hauptvariante) gehört mit in die [`View`]: Elemente anderer Varianten sind ausgeblendet wie
//! Ausgeblendetes des Umbaufilters (auch 2D-Zeichnungen). Darum gibt es eine `View` auch ohne Umbaufilter, sobald
//! das Projekt Elemente in Varianten hat.
use crate::model::*;
use crate::plan::prim::Primitive;
@@ -146,7 +150,10 @@ pub enum Treat {
/// Ein aufgelöster Umbaufilter einer Darstellung.
#[derive(Clone, Debug)]
pub struct View {
pub filter: RenovationFilter,
/// Umbaufilter; `None` = keiner (nur die Variantenkombination wirkt).
pub filter: Option<RenovationFilter>,
/// [272] Variantenkombination; `None` = das Projekt hat keine Elemente in Varianten.
pub options: Option<crate::design_options::Combination>,
/// Etappe, bis zu der der Filter gilt (Index), `None` = alle.
pub upto: Option<usize>,
phases: HashMap<String, usize>,
@@ -155,21 +162,41 @@ pub struct View {
impl View {
/// Filter `filter` (Id oder Name) bis Etappe `phase` (Id oder Name); `None` ohne (gültigen) Filter.
/// [272] Mit der Hauptkombination der Varianten (sofern das Projekt Elemente in Varianten hat).
pub fn new(p: &Project, filter: Option<&str>, phase: Option<&str>) -> Option<View> {
let filter = find_filter(p, filter?)?;
let upto = phase.filter(|s| !s.trim().is_empty()).and_then(|s| phase_index(p, s));
Self::with(p, filter, phase, &[], &[])
}
/// Filter und Etappe wie [`Self::new`], dazu die Variantenkombination aus gespeicherten Wahlen (`stored`:
/// Ebene, Vorlage, Ausschnitt, Viewport — spätere gehen vor) und der ausdrücklichen Anfrage (`request`, Ids
/// oder Namen; CLI `--options`). `None` ohne Filter und ohne Elemente in Varianten.
pub fn with(p: &Project, filter: Option<&str>, phase: Option<&str>, stored: &[&std::collections::BTreeMap<String, String>], request: &[(String, String)]) -> Option<View> {
let options = crate::design_options::active(p).then(|| crate::design_options::Combination::resolve(p, stored, request));
Self::with_combination(p, filter, phase, options)
}
/// Wie [`Self::with`] mit fertiger Kombination (`None` = ohne Varianten).
pub fn with_combination(p: &Project, filter: Option<&str>, phase: Option<&str>, options: Option<crate::design_options::Combination>) -> Option<View> {
let filter = filter.and_then(|f| find_filter(p, f));
let options = options.filter(|c| !c.choice.is_empty() && crate::design_options::active(p));
if filter.is_none() && options.is_none() {
return None;
}
let upto = if filter.is_some() { phase.filter(|s| !s.trim().is_empty()).and_then(|s| phase_index(p, s)) } else { None };
let phases = phases(p).iter().enumerate().map(|(i, x)| (x.id.clone(), i)).collect();
let styles = [style(p, RenovationStatus::Existing), style(p, RenovationStatus::Demolish), style(p, RenovationStatus::New)];
Some(View { filter, upto, phases, styles })
Some(View { filter, options, upto, phases, styles })
}
/// Filter einer Darstellung: ausdrücklich angefragt (CLI, Blatt-Ausschnitt), sonst der der Ebene `level_id`
/// (`DrawingLevel.renovationFilter`/`renovationPhase`, wie die Modelldarstellung [173]).
pub fn for_level(p: &Project, level_id: &str, filter: Option<&str>, phase: Option<&str>) -> Option<View> {
/// (`DrawingLevel.renovationFilter`/`renovationPhase`, wie die Modelldarstellung [173]). [272] Dazu die
/// Variantenkombination der Ebene (`designOptions`), darüber `options` (Anfrage).
pub fn for_level(p: &Project, level_id: &str, filter: Option<&str>, phase: Option<&str>, options: &[(String, String)]) -> Option<View> {
let l = p.floor(level_id);
let f = filter.filter(|s| !s.is_empty()).or_else(|| l.and_then(|l| l.renovation_filter.as_deref()));
let ph = if filter.is_some_and(|s| !s.is_empty()) { phase } else { phase.or_else(|| l.and_then(|l| l.renovation_phase.as_deref())) };
Self::new(p, f, ph)
let stored: Vec<&std::collections::BTreeMap<String, String>> = l.and_then(|l| l.design_options.as_ref()).into_iter().collect();
Self::with(p, f, ph, &stored, options)
}
/// Zustand des Elements in der Etappe des Filters; `None` = es steht dort (noch/schon) nicht.
@@ -188,10 +215,11 @@ impl View {
/// Darstellung eines Zustands im Filter.
pub fn treat_state(&self, s: Option<RenovationStatus>) -> Treat {
let Some(s) = s else { return Treat::Hide };
let Some(filter) = &self.filter else { return Treat::Show };
let (show, k) = match s {
RenovationStatus::Demolish => (self.filter.demolish, 1),
RenovationStatus::New => (self.filter.new, 2),
_ => (self.filter.existing, 0),
RenovationStatus::Demolish => (filter.demolish, 1),
RenovationStatus::New => (filter.new, 2),
_ => (filter.existing, 0),
};
match show {
RenovationShow::Hide => Treat::Hide,
@@ -213,6 +241,13 @@ impl View {
/// Ausgeblendete Elemente, Umbau-Farben und Ersatzstücke der Öffnungen für das ganze Projekt.
pub fn resolve(&self, p: &Project) -> Resolved {
let mut out = Resolved::default();
// [272] Elemente anderer Varianten: ausgeblendet (Öffnungen ausgeblendeter Wände mit).
if let Some(c) = &self.options {
out.hidden = c.hidden(p);
}
if self.filter.is_none() {
return out;
}
let mut put = |id: &str, t: Treat, out: &mut Resolved| match t {
Treat::Hide => {
out.hidden.insert(id.to_string());
@@ -276,7 +311,8 @@ impl View {
/// Füll- und Linienfarben der Status, die der Filter farbig zeigt (bleiben in Schwarz-Weiss erhalten).
pub fn colors(&self) -> Vec<String> {
let mut out = Vec::new();
for (show, st) in [(self.filter.existing, &self.styles[0]), (self.filter.demolish, &self.styles[1]), (self.filter.new, &self.styles[2])] {
let Some(f) = &self.filter else { return out };
for (show, st) in [(f.existing, &self.styles[0]), (f.demolish, &self.styles[1]), (f.new, &self.styles[2])] {
if show == RenovationShow::Override {
out.push(st.fill.clone());
out.extend(st.line.clone());
@@ -287,7 +323,11 @@ impl View {
/// Schlüssel für Caches (Filter samt Darstellungen, Etappe, Farben).
pub fn key(&self) -> String {
format!("{}:{:?}{:?}{:?}:{:?}:{:?}", self.filter.id, self.filter.existing, self.filter.demolish, self.filter.new, self.upto, self.styles)
let opts = self.options.as_ref().map_or(String::new(), |c| c.key());
match &self.filter {
Some(f) => format!("{}:{:?}{:?}{:?}:{:?}:{:?}|{opts}", f.id, f.existing, f.demolish, f.new, self.upto, self.styles),
None => format!("-|{opts}"),
}
}
}
@@ -326,9 +366,37 @@ pub fn without_hidden(p: &Project, hidden: &HashSet<String>) -> Project {
if let Some(v) = &mut q.extruded_solids {
v.retain(|x| !hidden.contains(&x.id));
}
// [272] 2D-Zeichnungen anderer Varianten.
q.drawings2d.retain(|x| !hidden.contains(&x.id));
q
}
/// [272] Das Projekt in Umbau-Zustand und Variantenkombination `c` (Vergleichstabelle); ohne Wirkung geliehen.
pub fn project_in_view<'a>(p: &'a Project, filter: Option<&str>, phase: Option<&str>, c: &crate::design_options::Combination) -> std::borrow::Cow<'a, Project> {
filtered(p, View::with_combination(p, filter, phase, Some(c.clone())))
}
/// [271]/[272] Projekt im Zustand eines Anfrage-Texts ([`view_from_text`]: Umbaufilter, Etappe, Variantenkombination;
/// leer = Hauptkombination), sonst unverändert.
pub fn project_for_text<'a>(p: &'a Project, text: &str) -> std::borrow::Cow<'a, Project> {
filtered(p, view_from_text(p, text))
}
/// Das Projekt ohne das in `v` Ausgeblendete (ohne Wirkung geliehen).
pub fn filtered(p: &Project, v: Option<View>) -> std::borrow::Cow<'_, Project> {
match v {
Some(v) => {
let r = v.resolve(p);
if r.hidden.is_empty() {
std::borrow::Cow::Borrowed(p)
} else {
std::borrow::Cow::Owned(without_hidden(p, &r.hidden))
}
}
None => std::borrow::Cow::Borrowed(p),
}
}
/// Das Projekt im Zustand eines Filters (`filter`: Id/Name, `phase`: Etappe); ohne gültigen Filter unverändert.
pub fn project_in_state<'a>(p: &'a Project, filter: Option<&str>, phase: Option<&str>) -> std::borrow::Cow<'a, Project> {
match View::new(p, filter, phase) {
@@ -504,18 +572,17 @@ pub fn patch_prims(ring: Vec<Vec2>, st: &Style, weight_mm: f64, opening_id: &str
}
/// Umbaufilter aus einem JSON-Text (`{"renovation": Id/Name, "renovationPhase": Etappe}`, 3D und Kennzahlen);
/// ein Text ohne `{` ist selbst die Filter-Id. `None` ohne Filter.
/// ein Text ohne `{` ist selbst die Filter-Id. [272] `designOptions`: Variantenkombination (Text „Satz=Variante,…“
/// oder Objekt), ohne Angabe die Hauptkombination. `None` ohne Filter und ohne Elemente in Varianten.
pub fn view_from_text(p: &Project, text: &str) -> Option<View> {
let t = text.trim();
if t.is_empty() {
return None;
}
if !t.starts_with('{') {
return View::new(p, Some(t), None);
return View::new(p, Some(t).filter(|t| !t.is_empty()), None);
}
let v: serde_json::Value = serde_json::from_str(t).ok()?;
let f = v.get("renovation").and_then(|x| x.as_str())?;
View::new(p, Some(f), v.get("renovationPhase").and_then(|x| x.as_str()))
let Ok(v) = serde_json::from_str::<serde_json::Value>(t) else { return View::new(p, None, None) };
let f = v.get("renovation").and_then(|x| x.as_str()).filter(|x| !x.is_empty());
let req = crate::design_options::parse_request(v.get("designOptions"));
View::with(p, f, v.get("renovationPhase").and_then(|x| x.as_str()), &[], &req)
}
/// 3D: Teile in der Umbau-Farbe (Füllfarbe des Status) — Wände, Decken, Dächer, Stützen, Treppen, Körper.
@@ -591,4 +658,4 @@ pub fn renovation_of<'a>(p: &'a Project, id: &str) -> Option<&'a Renovation> {
#[cfg(test)]
#[path = "renovation_tests.rs"]
mod tests;
pub(crate) mod tests;
+1 -1
View File
@@ -67,7 +67,7 @@ fn kein_filter_ohne_gueltige_id() {
assert!(View::new(&p, Some(""), None).is_none());
assert!(View::new(&p, Some("gibts-nicht"), None).is_none());
// Name ohne Gross-/Kleinschreibung (CLI).
assert_eq!(View::new(&p, Some("Umbauplan"), None).unwrap().filter.id, "umbauplan");
assert_eq!(View::new(&p, Some("Umbauplan"), None).unwrap().filter.unwrap().id, "umbauplan");
}
#[test]
+35 -4
View File
@@ -102,24 +102,51 @@ pub fn level_with_template(l: &DrawingLevel, t: &ViewTemplate) -> DrawingLevel {
macro_rules! take {
($($f:ident),*) => { $(if t.$f.is_some() { l.$f = t.$f.clone(); })* };
}
take!(cut_height, view_top, view_bottom, view_depth, shadows, hidden_lines, sketch, cut_hatch, floor_finish, show_terrain, model_view_option_id, renovation_filter, renovation_phase);
take!(cut_height, view_top, view_bottom, view_depth, shadows, hidden_lines, sketch, cut_hatch, floor_finish, show_terrain, model_view_option_id, renovation_filter, renovation_phase, design_options);
l
}
/// [34] Das Projekt, wie es die verknüpfte Vorlage des Ausschnitts für dessen Ebene sieht: Ebenen-Felder
/// der Vorlage und ihre Strichstärken-Skalierung. Ohne verknüpfte Vorlage unverändert (geliehen).
pub fn snapshot_project<'a>(p: &'a Project, snap: &ViewSnapshot) -> Cow<'a, Project> {
let Some(t) = snapshot_template(p, snap) else { return Cow::Borrowed(p) };
let t = snapshot_template(p, snap);
// [272] Variantenkombination des Ausschnitts (über der der Ebene und der Vorlage).
let opts = snap.design_options.as_ref().filter(|m| !m.is_empty());
if t.is_none() && opts.is_none() {
return Cow::Borrowed(p);
}
let mut q = p.clone();
for l in q.drawing_levels.iter_mut().filter(|l| l.id == snap.active_level_id) {
*l = level_with_template(l, t);
if let Some(t) = t {
*l = level_with_template(l, t);
}
if let Some(o) = opts {
let mut m = l.design_options.clone().unwrap_or_default();
m.extend(o.iter().map(|(k, v)| (k.clone(), v.clone())));
l.design_options = Some(m);
}
}
if t.scale_line_weights.is_some() {
if let Some(t) = t.filter(|t| t.scale_line_weights.is_some()) {
q.scale_line_weights = t.scale_line_weights;
}
Cow::Owned(q)
}
/// [272] Der Ausschnitt eines Viewports mit dessen eigener Variantenkombination (über der des Ausschnitts); ohne
/// eigene Wahl unverändert.
pub fn viewport_snapshot<'a>(snap: &'a ViewSnapshot, vp: &LayoutViewport) -> Cow<'a, ViewSnapshot> {
match vp.design_options.as_ref().filter(|m| !m.is_empty()) {
Some(o) => {
let mut s = snap.clone();
let mut m = s.design_options.clone().unwrap_or_default();
m.extend(o.iter().map(|(k, v)| (k.clone(), v.clone())));
s.design_options = Some(m);
Cow::Owned(s)
}
None => Cow::Borrowed(snap),
}
}
/// Plan-Argumente eines Viewports (wie `ViewportPlanSvg`: projektglobal, nicht für den Druck).
pub fn viewport_args(p: &Project, snap: &ViewSnapshot, scale: f64, mono: bool) -> PlanArgs {
let (detail, auto_coarse) = crate::plan::domains::effective_detail(detail_of(snap.detail), scale);
@@ -143,6 +170,8 @@ pub fn viewport_args(p: &Project, snap: &ViewSnapshot, scale: f64, mono: bool) -
// [271] Umbaufilter des Ausschnitts (sonst der der Ebene).
renovation: snap.renovation_filter.clone().filter(|s| !s.is_empty()),
renovation_phase: snap.renovation_phase.clone().filter(|s| !s.is_empty()),
// [272] Variantenkombination des Ausschnitts (über der der Ebene).
design_options: snap.design_options.iter().flatten().map(|(k, v)| (k.clone(), v.clone())).collect(),
};
a.apply_model_view(p);
a
@@ -164,6 +193,8 @@ pub fn viewport_maps(p: &Project, layout: &Layout) -> Vec<VpMap> {
let mut out = Vec::new();
for vp in &layout.viewports {
let Some(snap) = snaps.iter().find(|s| s.id == vp.snapshot_id) else { continue };
let snap = viewport_snapshot(snap, vp);
let snap = snap.as_ref();
if !(vp.width_mm > 0.0 && vp.height_mm > 0.0 && vp.x_mm.is_finite() && vp.y_mm.is_finite()) {
continue;
}
+8 -2
View File
@@ -240,7 +240,7 @@ fn derive_all(d: &mut Document, tag: &str, depth: Depth, fails: &mut Fails) {
}
}
// [271] Umbaufilter (eingebaut, mit Etappe, Unsinn).
for ren in [json!({"renovation": "umbauplan"}), json!({"renovation": "neubau", "renovationPhase": "x"}), json!({"renovation": "?"})] {
for ren in [json!({"renovation": "umbauplan"}), json!({"renovation": "neubau", "renovationPhase": "x"}), json!({"renovation": "?"}), json!({"designOptions": "Dachform=B,?=?"}), json!({"designOptions": {"x": 5}}), json!({"designOptions": 42, "renovation": "bestand"})] {
let t = plan_text(&p, fl, 100.0, ren.clone());
fails.run(|| format!("{tag} Grundriss {fl} Umbau {ren}"), || dossier_core::queries::run_bin_doc(d, "planDomains", &[1.0], &t));
}
@@ -279,7 +279,7 @@ fn derive_all(d: &mut Document, tag: &str, depth: Depth, fails: &mut Fails) {
}
}
// [271] Umbaufilter im Schnitt/in der Ansicht.
let t = if section { json!({"level": level, "scale": 100.0, "detail": "mittel", "renovation": "umbauplan"}) } else { json!({"level": level, "renovation": "abbruch"}) }.to_string();
let t = if section { json!({"level": level, "scale": 100.0, "detail": "mittel", "renovation": "umbauplan"}) } else { json!({"level": level, "renovation": "abbruch", "designOptions": "x=y"}) }.to_string();
let args = if section { vec![0.0, 1.0, 0.0] } else { vec![0.0, 0.0, 100.0] };
fails.run(|| format!("{tag} {kind} {} Umbau", lv.id), || dossier_core::queries::run_bin_doc(d, if section { "sectionPlan" } else { "elevationPlan" }, &args, &t));
}
@@ -332,6 +332,12 @@ fn derive_all(d: &mut Document, tag: &str, depth: Depth, fails: &mut Fails) {
("kennzahlen", vec![], "endzustand"),
("areaTable", vec![], "{\"renovation\": \"bestand\", \"renovationPhase\": 7}"),
("renovationFilters", vec![], ""),
// [272] Varianten: Info, Vergleich (mit Unsinn), Kombination in Kennzahlen/3D/IFC.
("designOptionInfo", vec![], ""),
("designOptionCompare", vec![], "{\"renovation\": 3, \"head\": [1]}"),
("kennzahlen", vec![], "{\"designOptions\": \"a=b\"}"),
("model3dParts", vec![0.0, f64::NAN, 0.0, 1.0], "{\"designOptions\": {\"s\": null}}"),
("costEstimate", vec![], "{\"designOptions\": []}"),
("model3dParts", vec![0.0, 1.0, 0.0, 1.0], "{\"renovation\": \"umbauplan\"}"),
];
if heavy {
+13 -1
View File
@@ -244,6 +244,15 @@ export default function App() {
// localStorage + reconcile). Bei jeder Änderung zurückspeichern.
const layout = useStore((s) => s.layout);
const setLayout = useStore((s) => s.setLayout);
// [272] Panel öffnen auf Wunsch eines Bausteins ohne Zugriff aufs Layout (Chip „Variante: …“ der Statusleiste).
useEffect(() => {
const on = (e: Event) => {
const id = (e as CustomEvent<string>).detail;
if (typeof id === "string" && id) setLayout((l) => revealPanel(l, id, { x: 96, y: 96, w: 520, h: 680 }));
};
window.addEventListener("dossier:reveal-panel", on);
return () => window.removeEventListener("dossier:reveal-panel", on);
}, [setLayout]);
const modeFor = useStore((s) => s.modeFor);
const setModeFor = useStore((s) => s.setModeFor);
useEffect(() => {
@@ -406,7 +415,7 @@ export default function App() {
);
const {
projectFileInputRef, projectTemplateFileInputRef, openImportForFile, onSaveProject, onSaveProjectAs, onRestoreBackup,
onNewProject, onNewProjectFromSample, onNewProjectFromComplexSample, onNewProjectFromWettbewerbSample, onNewProjectFromUmbauSample, onNewProjectFromTemplate,
onNewProject, onNewProjectFromSample, onNewProjectFromComplexSample, onNewProjectFromWettbewerbSample, onNewProjectFromUmbauSample, onNewProjectFromVariantenSample, onNewProjectFromTemplate,
onProjectTemplateFileChosen, onExportIfc, onExportObj, onExportStl, onOpenProject, onProjectFileChosen,
} = files;
@@ -716,6 +725,7 @@ export default function App() {
onNewProjectFromComplexSample,
onNewProjectFromWettbewerbSample,
onNewProjectFromUmbauSample,
onNewProjectFromVariantenSample,
onNewProjectFromTemplate,
onOpenProject,
onSaveProject,
@@ -734,6 +744,8 @@ export default function App() {
onOpenSettings: () => openSettings(),
onOpenBcf: () => setLayout((l) => revealPanel(l, "bcf")),
onOpenHistory: () => setLayout((l) => revealPanel(l, "history")),
// [272] Panel „Varianten“ (auch vom Chip der Statusleiste über `dossier:reveal-panel`).
onOpenDesignOptions: () => setLayout((l) => revealPanel(l, "design-options", { x: 96, y: 96, w: 520, h: 680 })),
applyScale,
fitPlan,
fitSelection,
+32 -2
View File
@@ -21,6 +21,9 @@
// --model-view <Name> wählt eine Modelldarstellung (eigene Stufe oder grob/mittel/fein) [173]
// --renovation <Filter> Umbaufilter (bestand, abbruch, neubau, umbauplan, endzustand oder eigener)
// mit --phase <Etappe> (Name oder id); auch für axo, model3d und kennzahlen [271]
// --options "Dachform=B,Fassade=A" Variantenkombination (Satz=Variante, Namen oder ids;
// fehlende Sätze: Hauptvariante); für alle Ausgaben (plan, section, elevation, axo,
// model3d, kennzahlen, dxf, ifc, obj …); `designoptions` vergleicht alle Kombinationen [272]
// --hide <Code|Name,…> blendet Klassen aus (z. B. --hide "Schatten,Auto-Bemassung") [180]
// --snapshot <Name|id> übernimmt Geschoss, Massstab, Vorlage und Sichtbarkeit eines Ausschnitts [207]
// dossier-cli <projekt.obp> axo [--view southeast|southwest|northeast|northwest|iso|…] [--projection iso|military|military30]
@@ -145,6 +148,12 @@ import {
viewportLevelPlan,
generateAxoPlan,
renovationFilterList,
parseCombination,
designOptionSets,
projectWithCombination,
compareDesignOptions,
compareDesignOptionsCsv,
buildVariantenSampleProject,
buildUmbauSampleProject,
type AxoOptions,
planToRenderScene,
@@ -258,6 +267,7 @@ function loadProject(path: string, args: Args): Project {
if (path === ":musterhaus-komplex") return buildComplexSampleProject();
if (path === ":wettbewerb") return buildWettbewerbSampleProject();
if (path === ":umbau") return buildUmbauSampleProject();
if (path === ":varianten") return buildVariantenSampleProject();
if (path === ":gross") return buildBigSampleProject({ floors: Number(args.flags.get("floors") ?? 8), apartments: Number(args.flags.get("apartments") ?? 15) });
let text: string;
try {
@@ -631,7 +641,7 @@ function importParsedDrawing(base: Project, parsed: ReturnType<typeof parseDxf>,
/** Liest Eingabe nach Endung in ein Projekt: obp direkt, dxf/dwg als 2D-Zeichnung + Meshes, ifc als Kontext-Meshes (`--elements`: Bauteile). */
async function importAny(path: string, args: Args): Promise<Project> {
const ext = extOf(path);
if (ext === "obp" || ext === "json" || path === ":beispiel" || path === ":musterhaus-komplex" || path === ":wettbewerb" || path === ":umbau") return loadProject(path, args);
if (ext === "obp" || ext === "json" || path === ":beispiel" || path === ":musterhaus-komplex" || path === ":wettbewerb" || path === ":umbau" || path === ":varianten") return loadProject(path, args);
let bytes: Uint8Array;
try {
bytes = new Uint8Array(readFileSync(path));
@@ -1049,7 +1059,7 @@ async function importSyntheticContext(base: Project, args: Args, rows: Array<[st
}
/** Befehle, die eine Ausgabe-Datei erzeugen (für die Anonymitäts-Prüfung einer Wettbewerbs-Abgabe, [208]). */
const EXPORT_COMMANDS = new Set(["plan", "section", "elevation", "axo", "dxf", "dwg", "ifc", "obj", "stl", "glb", "gltf", "step", "stp", "schedule", "kennzahlen", "raumprogramm", "render", "blend", "model3d"]);
const EXPORT_COMMANDS = new Set(["plan", "section", "elevation", "axo", "dxf", "dwg", "ifc", "obj", "stl", "glb", "gltf", "step", "stp", "schedule", "kennzahlen", "designoptions", "raumprogramm", "render", "blend", "model3d"]);
/**
* [208] Anonyme Abgabe: vor einem Export den Freitext prüfen. Treffer stehen auf stderr; ohne `--ignore-anonymity`
@@ -1078,6 +1088,17 @@ async function execute(project: Project, file: string, command: string, rest: st
const scale = Number(args.flags.get("scale") ?? 100);
const blocked = anonymityGate(project, file, command, args);
if (blocked !== 0) return blocked;
// [272] `--options "Dachform=B,Fassade=A"`: diese Variantenkombination gilt für alle Ausgaben (wird zur Hauptkombination).
const optSpec = args.flags.get("options");
if (optSpec && optSpec !== "true") {
const combo = parseCombination(project, optSpec);
const asked = optSpec.split(/[,;]/).filter((s) => s.trim()).length;
if (Object.keys(combo).length !== asked) {
const known = designOptionSets(project).map((s) => `${s.name}=${s.options.map((o) => o.name).join("|")}`).join(", ");
fail(`Variante nicht gefunden: ${optSpec} (vorhanden: ${known || "keine Variantensätze"})`);
}
project = projectWithCombination(project, combo);
}
// [257] `bench --context`: vorher synthetische Kontext-Importe (Kataster, Höhenlinien, Gebäudenetze) ins Projekt laden.
const contextRows: Array<[string, number]> = [];
if (command === "bench" && args.flags.has("context")) {
@@ -1341,6 +1362,15 @@ async function execute(project: Project, file: string, command: string, rest: st
out(args, JSON.stringify({ kennzahlen: k, raumprogramm: prog, baurecht, erdarbeiten }, null, 2), `${exportProjectName(project) || "projekt"}-kennzahlen.json`);
return 0;
}
case "designoptions": {
// [272] Varianten-Vergleich: Kennzahlen und Kosten je Kombination; --format json|csv, --renovation wie kennzahlen.
const ren = renovationFlags(project, args)?.renovation ?? "";
const stem = `${exportProjectName(project) || "projekt"}-varianten`;
if ((args.flags.get("format") ?? "json") === "csv") {
out(args, compareDesignOptionsCsv(project, ["Kombination", "GF m2", "HNF m2", "GV m3", "Fussabdruck m2", "AZ", "UEZ", "Kosten CHF"], ren), `${stem}.csv`);
} else out(args, JSON.stringify(compareDesignOptions(project, ren), null, 2), `${stem}.json`);
return 0;
}
case "raumprogramm": {
// Raumprogramm: [--import tabelle.xlsx|ods|csv [--sheet Name|Nr] [--mode replace|append]] [--tolerance 5]
// [--generate] [--format json|csv|svg|pdf] [--out datei] [--save projekt.obp]
+59
View File
@@ -0,0 +1,59 @@
// [272] Befehle „Variante zuweisen …“ und „In Variante kopieren …“: Ziel als Satz=Variante, Name, Nummer oder H, ein Schritt.
import { describe, expect, it } from "vitest";
import { designOptionCommand, designOptionCopyCommand, designOptionSelectionIds, parseDesignOptionTarget } from "./designOption";
import type { CommandContext } from "../types";
import { sampleProject } from "../../model/sampleProject";
import { buildVariantenSampleProject } from "../../model/sampleProjectVarianten";
import { applyOps } from "../../core/ops";
import { withDocument } from "../../core/document";
import type { Project } from "../../model/types";
function ctx(project: Project, sel: Partial<CommandContext["selection"]>): CommandContext {
return {
project,
level: project.drawingLevels[0],
defaultCategoryCode: "20",
activeLineStyleId: "solid",
activeWallTypeId: "aw",
lastPoint: null,
selection: { wallIds: [], drawingId: null, ...sel },
};
}
describe("[272] variante", () => {
it("ohne Satz oder ohne Auswahl: Hinweis statt Start", () => {
expect(designOptionCommand.precondition?.(ctx(sampleProject, { wallIds: ["W1"] }))).toBe("cmd.designOption.needsSet");
const p = buildVariantenSampleProject();
expect(designOptionCommand.precondition?.(ctx(p, {}))).toBe("cmd.designOption.needsSelection");
expect(designOptionCommand.precondition?.(ctx(p, { wallIds: ["W1"] }))).toBeNull();
});
it("Ziel lesen: Satz=Variante, Name, Nummer, H; Unbekanntes/Mehrdeutiges = undefined", () => {
const p = buildVariantenSampleProject();
expect(parseDesignOptionTarget(p, "Dachform=B Satteldach")).toEqual({ set: "dachform", option: "b" });
expect(parseDesignOptionTarget(p, "b bandfenster")).toEqual({ set: "fassade", option: "b" });
expect(parseDesignOptionTarget(p, "2")).toEqual({ set: "dachform", option: "b" });
expect(parseDesignOptionTarget(p, "H")).toBeNull();
expect(parseDesignOptionTarget(p, "a")).toBeUndefined();
expect(parseDesignOptionTarget(p, "99")).toBeUndefined();
expect(parseDesignOptionTarget(p, "")).toBeUndefined();
});
it("weist alle gewählten Elemente samt 2D in einem Schritt zu; kopiert in eine Variante", () => {
const p = buildVariantenSampleProject();
const c = ctx(p, { wallIds: ["W1"], openingIds: ["O1"], drawingIds: [] });
expect(designOptionSelectionIds(c.selection)).toEqual(["W1", "O1"]);
const [, res] = designOptionCommand.onInput(designOptionCommand.init(), { kind: "text", text: "Fassade=B Bandfenster" }, c);
expect(res.done).toBe(true);
const q = withDocument(p, () => applyOps(p, res.commit!.toOps(p)));
expect(q.walls.find((w) => w.id === "W1")?.designOption).toEqual({ set: "fassade", option: "b" });
expect(q.openings?.find((o) => o.id === "O1")?.designOption).toEqual({ set: "fassade", option: "b" });
// Unbekanntes Ziel: bleibt im Befehl.
const [, r2] = designOptionCommand.onInput(designOptionCommand.init(), { kind: "text", text: "quatsch" }, c);
expect(r2.done).toBeFalsy();
const [, r3] = designOptionCopyCommand.onInput(designOptionCopyCommand.init(), { kind: "option", id: "main" }, c);
expect(r3.done).toBe(true);
expect(r3.commit).toBeDefined();
});
});
+76
View File
@@ -0,0 +1,76 @@
// [272] Befehle „Variante zuweisen …“ (`designOption`, Kürzel `variante`) und „In Variante kopieren …“
// (`designOptionCopy`, Kürzel `variantekopieren`): die gewählten Elemente gehören danach der Variante (bzw. Kopien davon) —
// in einem Undo-Schritt. Ziel getippt als „Dachform=B“, als Variantenname („B Satteldach“, eindeutig über alle Sätze) oder
// als Nummer der Liste „Satz: Variante“ (1, 2, …); Option H = Hauptmodell. Ohne Auswahl oder ohne Variantensatz kein Start.
import { assignDesignOptionOps, copyToDesignOptionOps, designOptionSets, designOptionTargets, opsMutation, parseCombination } from "../../core";
import type { Project } from "../../model/types";
import type { Command, CommandContext, CommandResult, CommandSelection, CommandState } from "../types";
import { renovationSelectionIds } from "./renovation";
/** Gewählte Elemente, die einer Variante angehören können (Bauteile, Räume, 2D-Zeichnungen samt Bibliotheksobjekten). */
export function designOptionSelectionIds(sel: CommandSelection): string[] {
const drawings = sel.drawingIds ?? (sel.drawingId ? [sel.drawingId] : []);
return [...renovationSelectionIds(sel), ...drawings];
}
/** Ziel aus getipptem Text: `null` = Hauptmodell, `undefined` = unbekannt. */
export function parseDesignOptionTarget(project: Project, text: string): { set: string; option: string } | null | undefined {
const q = text.trim().toLowerCase();
if (!q) return undefined;
if (q === "h" || q === "haupt" || q === "hauptmodell" || q === "main") return null;
const targets = designOptionTargets(project);
const n = Number(q);
if (Number.isInteger(n) && n >= 1 && n <= targets.length) {
const [set, option] = targets[n - 1].key.split("/");
return { set, option };
}
if (q.includes("=")) {
const c = parseCombination(project, q);
const [set, option] = Object.entries(c)[0] ?? [];
return set ? { set, option } : undefined;
}
// Variantenname oder „Satz: Variante“, eindeutig über alle Sätze.
const hits: { set: string; option: string }[] = [];
for (const s of designOptionSets(project)) {
for (const o of s.options) {
const name = o.name.trim().toLowerCase();
if (name === q || o.id.toLowerCase() === q || `${s.name}: ${o.name}`.toLowerCase() === q) hits.push({ set: s.id, option: o.id });
}
}
return hits.length === 1 ? hits[0] : undefined;
}
const idle = (): CommandState => ({ phase: "pick", lastPoint: null });
const done = (commit?: CommandResult["commit"]): [CommandState, CommandResult] => [idle(), { draft: null, done: true, ...(commit ? { commit } : {}) }];
function makeCommand(copy: boolean): Command {
const key = copy ? "designOptionCopy" : "designOption";
return {
name: key,
labelKey: copy ? "cmd.designOptionCopy.label" : "cmd.designOption.label",
prompt: () => (copy ? "cmd.designOptionCopy.prompt" : "cmd.designOption.prompt"),
accepts: () => ["option", "text"],
options: () => [{ id: "main", labelKey: "designOption.main", key: "H" }],
precondition: (ctx: CommandContext) => {
if (!designOptionSets(ctx.project).length) return "cmd.designOption.needsSet";
return designOptionSelectionIds(ctx.selection).length === 0 ? "cmd.designOption.needsSelection" : null;
},
init: idle,
onInput: (state, input, ctx): [CommandState, CommandResult] => {
const text = input.kind === "option" ? (input.id === "main" ? "h" : input.id) : input.kind === "text" ? input.text : "";
const target = parseDesignOptionTarget(ctx.project, text);
if (target === undefined) return [state, { draft: null }];
const ids = designOptionSelectionIds(ctx.selection);
if (ids.length === 0) return done();
return done(opsMutation((p) => (copy ? copyToDesignOptionOps(p, ids, target) : assignDesignOptionOps(p, ids, target))));
},
onMove: (state): [CommandState, CommandResult] => [state, { draft: null }],
onConfirm: (): [CommandState, CommandResult] => done(),
onCancel: (): [CommandState, CommandResult] => done(),
};
}
export const designOptionCommand: Command = makeCommand(false);
export const designOptionCopyCommand: Command = makeCommand(true);
+5
View File
@@ -48,6 +48,7 @@ import { mirrorCommand, moveCommand, rotateCommand } from "./cmds/transform";
import { scaleCommand } from "./cmds/scale";
import { explodeCommand } from "./cmds/explode";
import { renovationCommand } from "./cmds/renovation";
import { designOptionCommand, designOptionCopyCommand } from "./cmds/designOption";
import { dimdetachCommand } from "./cmds/dimdetach";
import { autodimCommand } from "./cmds/autodim";
import { gridCommand } from "./cmds/grid";
@@ -134,6 +135,8 @@ export const COMMANDS: Record<string, Command> = {
scale: scaleCommand,
explode: explodeCommand,
renovation: renovationCommand,
designOption: designOptionCommand,
designOptionCopy: designOptionCopyCommand,
dimdetach: dimdetachCommand,
autodim: autodimCommand,
grid: gridCommand,
@@ -286,6 +289,8 @@ export const ALIASES: Record<string, string> = {
x: "explode",
aufloesen: "explode",
umbau: "renovation",
variante: "designOption",
variantekopieren: "designOptionCopy",
bml: "dimdetach",
bemassungloesen: "dimdetach",
ab: "autodim",
+5 -1
View File
@@ -172,7 +172,9 @@ export type LoadFileResult =
| { ok: false; error: string };
/** Wurzel-Abfragen des Kerns (`queries.rs::run_root`). */
export type RootQueryName = "penRebakeOps" | "penDeleteOps" | "penSeedOps" | "standardsMergeOps" | "standardsUpdatePlan" | "standardsUpdateOps" | "folderPdfPages" | "layoutTitleBlock" | "translatePatch" | "translateOps" | "selectionFilterPatch";
export type RootQueryName = "penRebakeOps" | "penDeleteOps" | "penSeedOps" | "standardsMergeOps" | "standardsUpdatePlan" | "standardsUpdateOps" | "folderPdfPages" | "layoutTitleBlock" | "translatePatch" | "translateOps" | "selectionFilterPatch"
// [272] Varianten (`design_options.rs`)
| "designOptionAcceptOps" | "designOptionDeleteOps" | "designOptionAssignOps" | "designOptionCopyOps";
/** Abfragen des Kerns (`queries.rs`). */
export type QueryName =
@@ -182,6 +184,8 @@ export type QueryName =
| "kennzahlen"
| "areaTable"
| "renovationFilters"
| "designOptionInfo"
| "designOptionCompare"
| "costEstimate"
| "costDefaults"
| "programCompare"
+9
View File
@@ -128,3 +128,12 @@ export {
} from "../model/renovation";
export type { RenovationFilterEntry, RenovationCollection } from "../model/renovation";
export { buildUmbauSampleProject } from "../model/sampleProjectUmbau";
// [272] Varianten: Sätze, Kombinationen, Zuweisen/Kopieren/Übernehmen (Regeln im Kern `design_options.rs`, Sichtbarkeit `renovation.rs`)
export {
DESIGN_OPTION_COLLECTIONS, designOptionSets, primaryOption, resolveCombination, levelCombination, combinationLabel, combinationSuffix, combinationSpec,
parseCombination, showsInCombination, designOptionLabel, designOptionSelection, designOptionIds, commonDesignOption, parseTarget, designOptionTargets,
assignDesignOptionOps, copyToDesignOptionOps, acceptDesignOptionOps, deleteDesignOptionOps, nextOptionName, addDesignOptionSetOps, addDesignOptionOps,
renameDesignOptionSetOps, renameDesignOptionOps, setPrimaryOptionOps, setLevelCombinationOps, compareDesignOptions, compareDesignOptionsCsv, projectWithCombination,
} from "../model/designOptions";
export type { Combination, DesignOptionCompareRow, DesignOptionCollection } from "../model/designOptions";
export { buildVariantenSampleProject } from "../model/sampleProjectVarianten";
+10 -5
View File
@@ -17,14 +17,14 @@ import { t } from "../i18n/translate";
import { legendPlan, legendPrintSvg } from "./legendSvg";
import { categoryLayerGroups, enablePdfLayers, type PdfLayers } from "./pdfLayers";
import { generatePlan, type Plan } from "../plan/generatePlan";
import { snapshotMono, snapshotOverrideRuleIds, snapshotTemplate, viewportLevelPlan, viewportSnapshotPlan } from "../plan/viewportPlan";
import { snapshotMono, snapshotOverrideRuleIds, snapshotTemplate, viewportDesignOptions, viewportLevelPlan, viewportSnapshotPlan } from "../plan/viewportPlan";
import { isDoc3dSnapshot } from "../plan/toAxo";
import { planToPrintSvg } from "./planToPrintSvg";
import { drawTablesPdf, PDF_TABLE_FONT, sheetTables } from "./sheetTable";
import { applyPdfInfo, finishPdfBytes } from "./pdfInfo";
import { ensurePdfFonts, PDF_DEFAULT_FONT, prepareSvgFonts, setPdfFont } from "./pdfFonts";
import { imageGeometry } from "../model/layoutImages";
import { posterHeaderItems, viewportScaleLabel } from "../model/posterTemplates";
import { posterHeaderItems, viewportScaleLabel, viewportVariantLabel } from "../model/posterTemplates";
import { collectVisibleCodes } from "../model/types";
import {
effectiveSheetSizeMm,
@@ -181,11 +181,12 @@ function drawImagesPdf(doc: jsPDF, layout: Layout): void {
}
/** Massstabsangabe unter jedem Viewport ([208], Master `viewportScaleLabels`). */
function drawScaleLabelsPdf(doc: jsPDF, project: Project, layout: Layout, sheet: { w: number; h: number }, scaleOverride?: number): void {
function drawScaleLabelsPdf(doc: jsPDF, project: Project, layout: Layout, sheet: { w: number; h: number }, scaleOverride?: number, withScale = true): void {
doc.setTextColor(17, 17, 17);
setPdfFont(doc, PDF_DEFAULT_FONT);
for (const vp of layout.viewports) {
const l = viewportScaleLabel(project, vp, sheet, scaleOverride);
// [272] Ohne Massstabsangaben nur der Titelzusatz der Varianten.
const l = withScale ? viewportScaleLabel(project, vp, sheet, scaleOverride) : viewportVariantLabel(project, vp, sheet);
if (!l) continue;
doc.setFontSize(l.sizeMm * MM_TO_PT);
doc.text(l.text, l.x, l.y);
@@ -232,7 +233,9 @@ async function renderPage(
const ruleIds = snapshotOverrideRuleIds(project, snap);
const template = snapshotTemplate(project, snap);
// [266] 3D-Ausschnitt: 3D-Dokument aus dem Kern (`viewportSnapshotPlan`).
const planOf = (visible: Set<string>) => (isDoc3dSnapshot(snap) ? viewportSnapshotPlan(project, snap, visible, scaleN, true) : viewportLevelPlan(project, snap.activeLevelId, visible, snap.detail, scaleN, true, snapshotMono(project, snap), ruleIds, template, snap.modelViewOptionId));
// [272] Variantenkombination des Ausschnitts/Viewports.
const dopts = viewportDesignOptions(snap, vp);
const planOf = (visible: Set<string>) => (isDoc3dSnapshot(snap) ? viewportSnapshotPlan(project, snap, visible, scaleN, true, vp) : viewportLevelPlan(project, snap.activeLevelId, visible, snap.detail, scaleN, true, snapshotMono(project, snap), ruleIds, template, snap.modelViewOptionId, dopts));
// [208] Eigene Bildmitte (Plakat): Ausschnitt um die Mitte; was darüber hinausgeht, schneidet der Rahmen ab.
const centered = viewportCenterBounds(vp, scaleN);
const draw = async (plan: Plan, transparent: boolean, bounds?: Plan["bounds"]) => {
@@ -278,6 +281,8 @@ async function renderPage(
// Massstab je Viewport ([208]).
if (master?.viewportScaleLabels) {
await inLayer(ctx, t("pdfLayers.frame"), () => drawScaleLabelsPdf(doc, project, layout, { w: widthMm, h: heightMm }, ctx.scaleOverride));
} else if (project.designOptionSets?.length) {
await inLayer(ctx, t("pdfLayers.frame"), () => drawScaleLabelsPdf(doc, project, layout, { w: widthMm, h: heightMm }, ctx.scaleOverride, false));
}
// Legenden ([82]): live aus den Viewports (oder Handauswahl), Muster vom Kern-Schraffurgenerator.
+45
View File
@@ -4746,6 +4746,51 @@ export const de = {
"cmd.renovation.label": "Umbau-Status setzen …",
"cmd.renovation.prompt": "Umbau-Status der Auswahl",
"cmd.renovation.needsSelection": "Zuerst Bauteile wählen, dann den Umbau-Status setzen.",
// [272] Varianten (Archicad „Design Options“)
"file.newFromVariantenSample": "Neu aus Vorlage: Beispiel Varianten",
"menu.native.newFromVariantenSample": "Beispiel Varianten",
"designOption.label": "Variante",
"designOption.title": "Varianten",
"designOption.main": "Hauptmodell",
"designOption.fromSnapshot": "wie Ausschnitt",
"designOption.short": "Variante: {combination}",
"designOption.hint": "Kombination dieser Ansicht: {combination} · Neue Elemente: {draw}",
"designOption.primaryCombination": "Hauptvarianten",
"designOption.viewCombination": "Kombination dieser Ansicht",
"designOption.drawIn": "Neue Elemente zeichnen in",
"designOption.set": "Variantensatz",
"designOption.option": "Variante",
"designOption.primary": "Hauptvariante",
"designOption.count": "Elemente in dieser Variante",
"designOption.sets.title": "Variantensätze",
"designOption.sets.hint": "Ein Satz (z. B. „Dachform“) hat Varianten (A, B, …); jedes Element gehört zum Hauptmodell oder zu genau einer Variante. Jede Ansicht, jeder Ausschnitt und jeder Viewport zeigt je Satz eine Variante (Vorgabe: die Hauptvariante).",
"designOption.sets.empty": "Keine Variantensätze: alle Elemente gehören zum Hauptmodell.",
"designOption.set.add": "Satz hinzufügen",
"designOption.set.new": "Name des neuen Satzes",
"designOption.set.placeholder": "z. B. Dachform",
"designOption.set.defaultName": "Satz {n}",
"designOption.set.delete": "Satz samt seinen Elementen löschen",
"designOption.option.add": "Variante hinzufügen",
"designOption.option.delete": "Variante samt ihren Elementen löschen",
"designOption.accept": "Übernehmen",
"designOption.accept.hint": "Variante übernehmen: ihre Elemente gehen ins Hauptmodell, die übrigen Varianten des Satzes werden gelöscht (ein Undo-Schritt).",
"designOption.compare.title": "Varianten-Vergleich",
"designOption.compare.combination": "Kombination",
"designOption.compare.footprint": "Fussabdruck m²",
"designOption.compare.cost": "Kosten CHF",
"designOption.compare.csv": "Vergleich als CSV",
"designOption.selection": "Auswahl ({n} Elemente)",
"designOption.assign": "Zuweisen",
"designOption.copy": "Kopieren in …",
"designOption.compare.show": "Vergleich öffnen",
"designOption.compare.hide": "Vergleich schliessen",
"resources.tab.designOptions": "Varianten",
"cmd.designOption.label": "Variante zuweisen …",
"cmd.designOption.prompt": "Ziel-Variante (z. B. Dachform=B, Variantenname oder Nummer; H = Hauptmodell)",
"cmd.designOptionCopy.label": "In Variante kopieren …",
"cmd.designOptionCopy.prompt": "Kopieren in Variante (z. B. Dachform=B, Variantenname oder Nummer; H = Hauptmodell)",
"cmd.designOption.needsSelection": "Zuerst Elemente wählen, dann die Variante wählen.",
"cmd.designOption.needsSet": "Das Projekt hat noch keinen Variantensatz (Ressourcen › Varianten).",
} as const;
export type TranslationKey = keyof typeof de;
+45
View File
@@ -4732,4 +4732,49 @@ export const en: Record<TranslationKey, string> = {
"cmd.renovation.label": "Set renovation status …",
"cmd.renovation.prompt": "Renovation status of the selection",
"cmd.renovation.needsSelection": "Select elements first, then set the renovation status.",
// [272] Design options
"file.newFromVariantenSample": "New from template: design options example",
"menu.native.newFromVariantenSample": "Design options example",
"designOption.label": "Design option",
"designOption.title": "Design options",
"designOption.main": "Main model",
"designOption.fromSnapshot": "as view",
"designOption.short": "Option: {combination}",
"designOption.hint": "Combination of this view: {combination} · New elements: {draw}",
"designOption.primaryCombination": "primary options",
"designOption.viewCombination": "Combination of this view",
"designOption.drawIn": "Draw new elements in",
"designOption.set": "Option set",
"designOption.option": "Option",
"designOption.primary": "Primary option",
"designOption.count": "Elements in this option",
"designOption.sets.title": "Option sets",
"designOption.sets.hint": "A set (e.g. “Roof shape”) has options (A, B, …); every element belongs to the main model or to exactly one option. Every view, saved view and viewport shows one option per set (default: the primary option).",
"designOption.sets.empty": "No option sets: all elements belong to the main model.",
"designOption.set.add": "Add set",
"designOption.set.new": "Name of the new set",
"designOption.set.placeholder": "e.g. Roof shape",
"designOption.set.defaultName": "Set {n}",
"designOption.set.delete": "Delete set with its elements",
"designOption.option.add": "Add option",
"designOption.option.delete": "Delete option with its elements",
"designOption.accept": "Accept",
"designOption.accept.hint": "Accept option: its elements move to the main model, the other options of the set are deleted (one undo step).",
"designOption.compare.title": "Option comparison",
"designOption.compare.combination": "Combination",
"designOption.compare.footprint": "Footprint m²",
"designOption.compare.cost": "Cost CHF",
"designOption.compare.csv": "Comparison as CSV",
"designOption.selection": "Selection ({n} elements)",
"designOption.assign": "Assign",
"designOption.copy": "Copy to …",
"designOption.compare.show": "Open comparison",
"designOption.compare.hide": "Close comparison",
"resources.tab.designOptions": "Design options",
"cmd.designOption.label": "Assign design option …",
"cmd.designOption.prompt": "Target option (e.g. Roof=B, option name or number; H = main model)",
"cmd.designOptionCopy.label": "Copy to design option …",
"cmd.designOptionCopy.prompt": "Copy into option (e.g. Roof=B, option name or number; H = main model)",
"cmd.designOption.needsSelection": "Select elements first, then choose the option.",
"cmd.designOption.needsSet": "The project has no option set yet (Resources › Design options).",
};
+137
View File
@@ -0,0 +1,137 @@
// [272] Varianten: Kombinationen lesen, Sätze/Varianten anlegen, Zuweisen/Kopieren/Übernehmen/Löschen über den Kern,
// Grundriss/Schnitt/3D/Kennzahlen je Kombination am Varianten-Beispiel, Vergleich und CSV, CLI-Kombination.
import { describe, expect, it } from "vitest";
import { applyOps } from "../core/ops";
import {
acceptDesignOptionOps, addDesignOptionOps, addDesignOptionSetOps, assignDesignOptionOps, combinationLabel, combinationSpec, combinationSuffix, commonDesignOption,
compareDesignOptions, compareDesignOptionsCsv, copyToDesignOptionOps, deleteDesignOptionOps, levelCombination, nextOptionName, parseCombination, projectWithCombination,
resolveCombination, setLevelCombinationOps, setPrimaryOptionOps, showsInCombination,
} from "./designOptions";
import { buildVariantenSampleProject } from "./sampleProjectVarianten";
import { sampleProject } from "./sampleProject";
import { generatePlan } from "../plan/generatePlan";
import { computeKennzahlen } from "../analysis/kennzahlen";
import { projectToModel3d, projectToModel3dParts } from "../plan/toWalls3d";
import { withDocument } from "../core/document";
import type { Project } from "./types";
const ALL = new Set(["20", "21", "30", "31", "40", "60"]);
/** Ids der Öffnungen/Dächer im Grundriss des OG bzw. EG einer Projekt-Fassung. */
function planIds(p: Project, level: string): Set<string> {
return withDocument(p, () => {
const out = new Set<string>();
for (const x of generatePlan(p, level, ALL).primitives) {
const r = x as { openingId?: string; roofId?: string };
if (r.openingId) out.add(r.openingId);
if (r.roofId) out.add(r.roofId);
}
return out;
});
}
describe("[272] Varianten", () => {
it("Kombination: Hauptvarianten, gespeicherte Wahl, Namen, Text", () => {
const p = buildVariantenSampleProject();
expect(resolveCombination(p)).toEqual({ dachform: "a", fassade: "a" });
expect(resolveCombination(p, { dachform: "b", weg: "x" }, { fassade: "z" })).toEqual({ dachform: "b", fassade: "a" });
expect(combinationLabel(p, { dachform: "b", fassade: "a" })).toBe("Dachform B Satteldach, Fassade A Lochfenster");
expect(combinationSuffix(p, { dachform: "b", fassade: "a" })).toBe("Dachform B Satteldach");
expect(combinationSuffix(p, {})).toBe("");
expect(parseCombination(p, "dachform=b satteldach; Fassade = B Bandfenster, Unsinn")).toEqual({ dachform: "b", fassade: "b" });
expect(combinationSpec(p, { dachform: "b" })).toBe("Dachform=B Satteldach");
expect(showsInCombination({ dachform: "a" }, { set: "dachform", option: "b" })).toBe(false);
expect(showsInCombination({ dachform: "a" }, undefined)).toBe(true);
expect(showsInCombination({ dachform: "a" }, { set: "weg", option: "b" })).toBe(true);
});
it("Sätze und Varianten anlegen, Hauptvariante, Kombination der Ebene (ohne Hauptvariante gespeichert)", () => {
const { ops, id } = addDesignOptionSetOps(sampleProject, "Dachform");
let p = applyOps(sampleProject, ops);
expect(p.designOptionSets?.[0]).toMatchObject({ id, name: "Dachform", primary: "a" });
p = applyOps(p, addDesignOptionOps(p, id));
expect(p.designOptionSets?.[0].options.map((o) => o.name)).toEqual(["A", "B", "C"]);
expect(nextOptionName(p.designOptionSets?.[0])).toBe("D");
p = applyOps(p, setLevelCombinationOps(p, "eg", id, "b"));
expect(p.drawingLevels.find((l) => l.id === "eg")?.designOptions).toEqual({ [id]: "b" });
expect(levelCombination(p, p.drawingLevels.find((l) => l.id === "eg"))[id]).toBe("b");
p = applyOps(p, setLevelCombinationOps(p, "eg", id, "a"));
expect(p.drawingLevels.find((l) => l.id === "eg")).not.toHaveProperty("designOptions");
p = applyOps(p, setPrimaryOptionOps(p, id, "b"));
expect(p.designOptionSets?.[0].primary).toBe("b");
expect(setPrimaryOptionOps(p, id, "zz")).toHaveLength(0);
});
it("Grundriss je Kombination: Dächer und Fenster der anderen Variante fehlen", () => {
const p = buildVariantenSampleProject();
const a = planIds(p, "eg");
expect(a.has("O2")).toBe(true);
expect(a.has("O-band")).toBe(false);
const q = applyOps(p, setLevelCombinationOps(p, "eg", "fassade", "b"));
const b = planIds(q, "eg");
expect(b.has("O2")).toBe(false);
expect(b.has("O-band")).toBe(true);
});
it("3D und Kennzahlen je Kombination; Teil-Cache aus bei Varianten", () => {
const p = buildVariantenSampleProject();
withDocument(p, () => {
expect(projectToModel3dParts(p)).toBeNull();
const roofs = (opts?: Record<string, string>) => JSON.stringify(projectToModel3d(p, opts ? { hide: { designOptions: opts } } : {}));
expect(roofs()).not.toEqual(roofs({ dachform: "b" }));
});
const ka = withDocument(p, () => computeKennzahlen(p));
const pb = projectWithCombination(p, { dachform: "b" });
const kb = withDocument(pb, () => computeKennzahlen(pb));
expect(ka.gv).not.toBeCloseTo(kb.gv, 3);
});
it("Vergleich: alle Kombinationen, Hauptkombination zuerst, CSV mit Kopf", () => {
const p = buildVariantenSampleProject();
const rows = withDocument(p, () => compareDesignOptions(p));
expect(rows).toHaveLength(4);
expect(rows[0].primary).toBe(true);
expect(rows[0].label).toBe("Dachform A Flachdach, Fassade A Lochfenster");
expect(new Set(rows.map((r) => r.gv)).size).toBeGreaterThan(1);
expect(rows.every((r) => Number.isFinite(r.cost) && r.cost > 0)).toBe(true);
const csv = withDocument(p, () => compareDesignOptionsCsv(p, ["Kombination", "GF", "HNF", "GV", "Fussabdruck", "AZ", "ÜZ", "Kosten"]));
expect(csv.split("\n")[0]).toBe("Kombination;GF;HNF;GV;Fussabdruck;AZ;ÜZ;Kosten");
expect(csv.trim().split("\n")).toHaveLength(5);
expect(compareDesignOptions(sampleProject)).toEqual([]);
});
it("Zuweisen (Mehrfachauswahl, ein Schritt), gemeinsamer Wert, Kopieren, Übernehmen, Löschen", () => {
const p = buildVariantenSampleProject();
withDocument(p, () => {
const ops = assignDesignOptionOps(p, ["W1", "W2", "nix"], { set: "fassade", option: "b" });
expect(ops).toHaveLength(2);
const q = applyOps(p, ops);
expect(commonDesignOption(q, ["W1", "W2"])).toBe("fassade/b");
expect(commonDesignOption(q, ["W1", "W3"])).toBe("mixed");
expect(commonDesignOption(q, ["W3"])).toBe("");
const copy = copyToDesignOptionOps(p, ["W3"], { set: "fassade", option: "b" }, "k");
const c = applyOps(p, copy);
const w = c.walls.find((x) => x.id.startsWith("k-"));
expect(w?.designOption).toEqual({ set: "fassade", option: "b" });
expect((c.openings ?? []).filter((o) => o.hostWallId === w?.id).length).toBeGreaterThan(0);
});
// Übernehmen: B Satteldach bleibt (ohne Variante), Flachdach weg, Satz weg.
const acc = withDocument(p, () => applyOps(p, acceptDesignOptionOps(p, "dachform", "b")));
expect(acc.roofs?.map((r) => r.id)).toEqual(["RF1"]);
expect(acc.roofs?.[0]).not.toHaveProperty("designOption");
expect(acc.designOptionSets?.map((s) => s.id)).toEqual(["fassade"]);
// Satz löschen: alle Fenster beider Fassaden-Varianten weg.
const del = withDocument(p, () => applyOps(p, deleteDesignOptionOps(p, "fassade")));
expect((del.openings ?? []).some((o) => o.id === "O2" || o.id === "O-band")).toBe(false);
});
it("CLI-Kombination: gewählte Varianten werden Hauptvarianten, gespeicherte Wahlen entfallen", () => {
const p0 = buildVariantenSampleProject();
const p = { ...p0, drawingLevels: p0.drawingLevels.map((l) => (l.id === "eg" ? { ...l, designOptions: { dachform: "a", fassade: "b" } } : l)) };
const q = projectWithCombination(p, { dachform: "b" });
expect(q.designOptionSets?.find((s) => s.id === "dachform")?.primary).toBe("b");
expect(q.drawingLevels.find((l) => l.id === "eg")?.designOptions).toEqual({ fassade: "b" });
expect(projectWithCombination(p, {})).toBe(p);
});
});
+301
View File
@@ -0,0 +1,301 @@
// [272] Varianten (Archicad „Design Options“): Variantensätze mit Varianten, Elemente im Hauptmodell oder in genau einer
// Variante, je Ebene/Ausschnitt/Viewport eine Kombination. Was sichtbar ist, entscheidet der Kern (`renovation.rs`, ein Ort
// mit dem Umbaufilter; Modell und Ops in `design_options.rs`); hier nur, was die Oberfläche zum Lesen und Setzen braucht.
import type { CoreOp } from "../core/ops";
import { documentFor } from "../core/document";
import { patchItem, setField } from "../core/opsBuild";
import type { DesignOption, DesignOptionRef, DesignOptionSet, DrawingLevel, Project } from "./types";
/** Listen, deren Elemente einer Variante angehören können (gleich wie `design_options::COLLECTIONS`). */
export const DESIGN_OPTION_COLLECTIONS = ["walls", "openings", "ceilings", "roofs", "stairs", "columns", "extrudedSolids", "rooms", "drawings2d"] as const;
export type DesignOptionCollection = (typeof DESIGN_OPTION_COLLECTIONS)[number];
/** Kombination: Satz-Id → Varianten-Id. */
export type Combination = Record<string, string>;
/** Variantensätze des Projekts. */
export function designOptionSets(project: Project): readonly DesignOptionSet[] {
return project.designOptionSets ?? [];
}
/** Hauptvariante eines Satzes (`primary`, sonst die erste). */
export function primaryOption(s: DesignOptionSet): string | undefined {
return s.primary && s.options.some((o) => o.id === s.primary) ? s.primary : s.options[0]?.id;
}
/** Wirksame Kombination: Hauptvarianten, darüber die gespeicherten Wahlen (spätere gehen vor; unbekannte übergangen). */
export function resolveCombination(project: Project, ...stored: (Combination | undefined | null)[]): Combination {
const out: Combination = {};
for (const s of designOptionSets(project)) {
const p = primaryOption(s);
if (p) out[s.id] = p;
}
for (const m of stored) {
for (const [k, v] of Object.entries(m ?? {})) {
const s = designOptionSets(project).find((x) => x.id === k);
if (s?.options.some((o) => o.id === v)) out[k] = v;
}
}
return out;
}
/** Kombination einer Ebene (`DrawingLevel.designOptions` über den Hauptvarianten). */
export function levelCombination(project: Project, level: DrawingLevel | undefined): Combination {
return resolveCombination(project, level?.designOptions);
}
/** Lesbarer Name „Dachform B, Fassade A“ (nur Sätze mit Varianten). */
export function combinationLabel(project: Project, c: Combination): string {
const parts: string[] = [];
for (const s of designOptionSets(project)) {
const o = s.options.find((x) => x.id === c[s.id]);
if (o) parts.push(`${s.name} ${o.name}`.trim());
}
return parts.join(", ");
}
/** Kurzname nur der Varianten, die von der Hauptvariante abweichen (Titelzusatz im Blatt); leer = Hauptkombination. */
export function combinationSuffix(project: Project, c: Combination | undefined | null): string {
if (!c) return "";
const full = resolveCombination(project, c);
const prim = resolveCombination(project);
const diff: Combination = {};
for (const [k, v] of Object.entries(full)) if (prim[k] !== v) diff[k] = v;
return combinationLabel(project, diff);
}
/** Text „Satz=Variante,…“ (Namen) einer Kombination — Format der CLI `--options`. */
export function combinationSpec(project: Project, c: Combination): string {
const parts: string[] = [];
for (const s of designOptionSets(project)) {
const o = s.options.find((x) => x.id === c[s.id]);
if (o) parts.push(`${s.name}=${o.name}`);
}
return parts.join(",");
}
/** Liest „Dachform=B,Fassade=A“ (Ids oder Namen, ohne Gross-/Kleinschreibung); Unbekanntes übergangen. */
export function parseCombination(project: Project, spec: string): Combination {
const out: Combination = {};
for (const part of spec.split(/[,;]/)) {
const i = part.indexOf("=");
if (i <= 0) continue;
const k = part.slice(0, i).trim().toLowerCase();
const v = part.slice(i + 1).trim().toLowerCase();
const s = designOptionSets(project).find((x) => x.id.toLowerCase() === k || x.name.trim().toLowerCase() === k);
const o = s?.options.find((x) => x.id.toLowerCase() === v || x.name.trim().toLowerCase() === v);
if (s && o) out[s.id] = o.id;
}
return out;
}
/** Erscheint ein Element mit dieser Zugehörigkeit in der Kombination? (Gleiche Regel wie `Combination::shows` im Kern.) */
export function showsInCombination(c: Combination, r: DesignOptionRef | undefined | null): boolean {
if (!r) return true;
const chosen = c[r.set];
return chosen === undefined || chosen === r.option;
}
/** Name „Dachform: B“ einer Zugehörigkeit; leer = Hauptmodell. */
export function designOptionLabel(project: Project, r: DesignOptionRef | undefined | null): string {
if (!r) return "";
const s = designOptionSets(project).find((x) => x.id === r.set);
const o = s?.options.find((x) => x.id === r.option);
return s && o ? `${s.name}: ${o.name}` : "";
}
/** Auswahl je Liste (ids), wie der Kern sie für Zuweisen/Kopieren nimmt. */
export function designOptionSelection(project: Project, ids: Iterable<string>): Record<string, string[]> {
const set = new Set(ids);
const out: Record<string, string[]> = {};
for (const c of DESIGN_OPTION_COLLECTIONS) {
const hit = ((project[c] ?? []) as { id: string }[]).filter((e) => set.has(e.id)).map((e) => e.id);
if (hit.length) out[c] = hit;
}
return out;
}
/** Ids der Auswahl, die einer Variante angehören können. */
export function designOptionIds(project: Project, ids: Iterable<string>): string[] {
return Object.values(designOptionSelection(project, ids)).flat();
}
/** Gemeinsame Zugehörigkeit der Elemente `ids` als `"set/option"` (`""` = Hauptmodell, `"mixed"`, `null` ohne Elemente). */
export function commonDesignOption(project: Project, ids: Iterable<string>): string | "mixed" | null {
const set = new Set(ids);
let out: string | null = null;
for (const c of DESIGN_OPTION_COLLECTIONS) {
for (const e of (project[c] ?? []) as { id: string; designOption?: DesignOptionRef }[]) {
if (!set.has(e.id)) continue;
const k = e.designOption ? `${e.designOption.set}/${e.designOption.option}` : "";
if (out === null) out = k;
else if (out !== k) return "mixed";
}
}
return out;
}
/** Ziel aus `"set/option"` (`""` = Hauptmodell). */
export function parseTarget(key: string): { set: string; option: string } | null {
const i = key.indexOf("/");
return i > 0 ? { set: key.slice(0, i), option: key.slice(i + 1) } : null;
}
/** Alle Ziele „Satz: Variante“ für Auswahllisten (`key` = `"set/option"`). */
export function designOptionTargets(project: Project): { key: string; label: string }[] {
const out: { key: string; label: string }[] = [];
for (const s of designOptionSets(project)) for (const o of s.options) out.push({ key: `${s.id}/${o.id}`, label: `${s.name}: ${o.name}` });
return out;
}
// ── Ops ─────────────────────────────────────────────────────────────────────
/** Ops: Variante zuweisen (`null` = Hauptmodell) für die Auswahl (Kern `design_options::assign_ops`; ein Undo-Schritt). */
export function assignDesignOptionOps(project: Project, ids: Iterable<string>, target: { set: string; option: string } | null): CoreOp[] {
const sel = designOptionSelection(project, ids);
if (!Object.keys(sel).length) return [];
return documentFor(project).queryRoot<CoreOp[]>("designOptionAssignOps", JSON.stringify({ ...(target ?? {}), sel }));
}
/** Ops: Kopien der Auswahl in die Variante (`null` = Hauptmodell); Öffnungen gewählter Wände wandern mit. */
export function copyToDesignOptionOps(project: Project, ids: Iterable<string>, target: { set: string; option: string } | null, stamp = `v${Date.now().toString(36)}`): CoreOp[] {
const sel = designOptionSelection(project, ids);
if (!Object.keys(sel).length) return [];
return documentFor(project).queryRoot<CoreOp[]>("designOptionCopyOps", JSON.stringify({ ...(target ?? {}), sel, stamp }));
}
/** Ops: „Variante übernehmen“ — ihre Elemente ins Hauptmodell, die übrigen Varianten des Satzes gelöscht, Satz weg. */
export function acceptDesignOptionOps(project: Project, set: string, option: string): CoreOp[] {
return documentFor(project).queryRoot<CoreOp[]>("designOptionAcceptOps", JSON.stringify({ set, option }));
}
/** Ops: Satz (ohne `option`) bzw. Variante löschen samt ihren Elementen. */
export function deleteDesignOptionOps(project: Project, set: string, option?: string): CoreOp[] {
return documentFor(project).queryRoot<CoreOp[]>("designOptionDeleteOps", JSON.stringify(option ? { set, option } : { set }));
}
/** Nächste freie Id mit Präfix. */
function freeId(used: Iterable<string>, prefix: string): string {
const u = new Set(used);
let i = u.size + 1;
while (u.has(`${prefix}${i}`)) i++;
return `${prefix}${i}`;
}
/** Variantenname „A“, „B“, … (nächster freier Buchstabe). */
export function nextOptionName(s: DesignOptionSet | undefined): string {
const used = new Set((s?.options ?? []).map((o) => o.name.trim().toUpperCase()));
for (let i = 0; i < 26; i++) {
const n = String.fromCharCode(65 + i);
if (!used.has(n)) return n;
}
return String((s?.options.length ?? 0) + 1);
}
/** Ops: neuer Satz `name` mit den Varianten A und B (A = Hauptvariante). Gibt auch die neue Satz-Id zurück. */
export function addDesignOptionSetOps(project: Project, name: string): { ops: CoreOp[]; id: string } {
const sets = designOptionSets(project);
const id = freeId(sets.map((s) => s.id), "satz-");
const options: DesignOption[] = [
{ id: "a", name: "A" },
{ id: "b", name: "B" },
];
return { ops: [setField("designOptionSets", [...sets, { id, name: name.trim() || id, options, primary: "a" }])], id };
}
/** Ops: weitere Variante im Satz (nächster Buchstabe). */
export function addDesignOptionOps(project: Project, setId: string): CoreOp[] {
const sets = designOptionSets(project);
const s = sets.find((x) => x.id === setId);
if (!s) return [];
const name = nextOptionName(s);
const id = freeId(s.options.map((o) => o.id), "v");
return [setField("designOptionSets", sets.map((x) => (x.id === setId ? { ...x, options: [...x.options, { id, name }] } : x)))];
}
/** Ops: Satz bzw. Variante umbenennen, Hauptvariante setzen. */
export function renameDesignOptionSetOps(project: Project, setId: string, name: string): CoreOp[] {
const sets = designOptionSets(project);
if (!sets.some((s) => s.id === setId)) return [];
return [setField("designOptionSets", sets.map((s) => (s.id === setId ? { ...s, name } : s)))];
}
export function renameDesignOptionOps(project: Project, setId: string, optionId: string, name: string): CoreOp[] {
const sets = designOptionSets(project);
if (!sets.some((s) => s.id === setId && s.options.some((o) => o.id === optionId))) return [];
return [setField("designOptionSets", sets.map((s) => (s.id === setId ? { ...s, options: s.options.map((o) => (o.id === optionId ? { ...o, name } : o)) } : s)))];
}
export function setPrimaryOptionOps(project: Project, setId: string, optionId: string): CoreOp[] {
const sets = designOptionSets(project);
if (!sets.some((s) => s.id === setId && s.options.some((o) => o.id === optionId))) return [];
return [setField("designOptionSets", sets.map((s) => (s.id === setId ? { ...s, primary: optionId } : s)))];
}
/** Ops: Kombination der Ebene setzen (eine Variante je Satz; die Hauptvariante wird nicht gespeichert). */
export function setLevelCombinationOps(project: Project, levelId: string, setId: string, optionId: string): CoreOp[] {
const s = designOptionSets(project).find((x) => x.id === setId);
if (!s || !s.options.some((o) => o.id === optionId)) return [];
return patchItem(project, "drawingLevels", levelId, (l) => {
const m: Combination = { ...(l.designOptions ?? {}) };
if (primaryOption(s) === optionId) delete m[setId];
else m[setId] = optionId;
const next = { ...l, designOptions: m };
if (!Object.keys(m).length) delete (next as { designOptions?: Combination }).designOptions;
return next;
});
}
// ── Vergleich ───────────────────────────────────────────────────────────────
/** Zeile der Vergleichstabelle (Kern `design_options::CompareRow`). */
export interface DesignOptionCompareRow {
choice: Combination;
label: string;
primary: boolean;
gf: number;
hnf: number;
gv: number;
footprint: number;
az?: number | null;
uez?: number | null;
cost: number;
}
/** Kennzahlen und Kosten je Kombination (Hauptkombination zuerst); `renovation`: Umbau-Zustand (Filter-Id). */
export function compareDesignOptions(project: Project, renovation = ""): DesignOptionCompareRow[] {
if (!designOptionSets(project).length) return [];
return documentFor(project).query<DesignOptionCompareRow[]>("designOptionCompare", [], renovation ? JSON.stringify({ renovation }) : "");
}
/** Vergleich als CSV (Semikolon) mit den Spaltenköpfen `head` (übersetzt). */
export function compareDesignOptionsCsv(project: Project, head: readonly string[], renovation = ""): string {
if (!designOptionSets(project).length) return "";
return documentFor(project).query<string>("designOptionCompare", [], JSON.stringify(renovation ? { renovation, head } : { head }));
}
/**
* Das Projekt so, dass die Kombination `c` überall gilt (CLI `--options`): die gewählten Varianten werden Hauptvarianten,
* gespeicherte Wahlen dieser Sätze an Ebenen, Vorlagen, Ausschnitten und Viewports entfallen. Kein Op (Kopie für Exporte).
*/
export function projectWithCombination(project: Project, c: Combination): Project {
const keys = Object.keys(c);
if (!keys.length) return project;
const strip = <T extends { designOptions?: Combination | null }>(x: T): T => {
if (!x.designOptions || !keys.some((k) => k in x.designOptions!)) return x;
const m = { ...x.designOptions };
for (const k of keys) delete m[k];
const next = { ...x, designOptions: m };
if (!Object.keys(m).length) delete (next as { designOptions?: Combination | null }).designOptions;
return next;
};
return {
...project,
designOptionSets: designOptionSets(project).map((s) => (c[s.id] && s.options.some((o) => o.id === c[s.id]) ? { ...s, primary: c[s.id] } : s)),
drawingLevels: project.drawingLevels.map(strip),
...(project.viewTemplates ? { viewTemplates: project.viewTemplates.map(strip) } : {}),
...(project.viewSnapshots ? { viewSnapshots: project.viewSnapshots.map(strip) } : {}),
...(project.layouts ? { layouts: project.layouts.map((l) => ({ ...l, viewports: l.viewports.map(strip) })) } : {}),
};
}
+19 -1
View File
@@ -9,6 +9,7 @@ import type { Layout, LayoutOrientation, LayoutPaperFormat, MasterLayout, Projec
import { core } from "../engine/coreWasm";
import { t } from "../i18n/translate";
import { findSnapshot, resolveTitleBlock, resolveViewportScale, sheetSizeMm } from "./layoutModel";
import { combinationSuffix } from "./designOptions";
export interface PosterTemplate {
/** Schlüssel in `MasterLayout.template`. */
@@ -113,5 +114,22 @@ export function viewportScaleLabel(
if (!snap) return null;
const n = scaleOverride ?? resolveViewportScale(vp, snap);
const { sizeMm, dyMm } = scaleLabelMetrics(sheet);
return { text: `1:${n}`, x: vp.xMm, y: vp.yMm + vp.heightMm + dyMm, sizeMm };
// [272] Titelzusatz: Varianten, die von der Hauptkombination abweichen (Ausschnitt bzw. Viewport).
const suffix = viewportVariantSuffix(project, vp);
return { text: suffix ? `1:${n} · ${suffix}` : `1:${n}`, x: vp.xMm, y: vp.yMm + vp.heightMm + dyMm, sizeMm };
}
/** [272] Varianten eines Viewports, die von der Hauptkombination abweichen („Dachform B Satteldach“); leer sonst. */
export function viewportVariantSuffix(project: Project, vp: Layout["viewports"][number]): string {
if (!project.designOptionSets?.length) return "";
const snap = findSnapshot(project, vp.snapshotId);
return combinationSuffix(project, { ...(snap?.designOptions ?? {}), ...(vp.designOptions ?? {}) });
}
/** [272] Titelzusatz unter einem Viewport ohne Massstabsangaben des Masters: nur die Varianten; `null` ohne Abweichung. */
export function viewportVariantLabel(project: Project, vp: Layout["viewports"][number], sheet: { w: number; h: number }): { text: string; x: number; y: number; sizeMm: number } | null {
const suffix = viewportVariantSuffix(project, vp);
if (!suffix) return null;
const { sizeMm, dyMm } = scaleLabelMetrics(sheet);
return { text: suffix, x: vp.xMm, y: vp.yMm + vp.heightMm + dyMm, sizeMm };
}
+35
View File
@@ -0,0 +1,35 @@
// [272] „Beispiel Varianten": das Demo-Haus (sampleProject) mit zwei Variantensätzen — Vorlage für Tests, die Kurzanleitung
// (Abschnitt Varianten) und die Prüfbilder (`doc/review-272`).
//
// Satz „Dachform": A Flachdach (Hauptvariante, neues Dach RF2), B Satteldach (das Dach RF1 des Demo-Hauses).
// Satz „Fassade": A Lochfenster (Nordfenster O2 des Demo-Hauses, Hauptvariante), B Bandfenster (O-band, 3.6 m breit).
// Alles Übrige gehört zum Hauptmodell. Ein eigenes Beispiel, damit die bestehenden Goldens unverändert bleiben.
import type { DesignOptionSet, Opening, Project, Roof } from "./types";
import { sampleProject } from "./sampleProject";
export const VARIANTEN_SETS: DesignOptionSet[] = [
{ id: "dachform", name: "Dachform", options: [{ id: "a", name: "A Flachdach" }, { id: "b", name: "B Satteldach" }], primary: "a" },
{ id: "fassade", name: "Fassade", options: [{ id: "a", name: "A Lochfenster" }, { id: "b", name: "B Bandfenster" }], primary: "a" },
];
/** Das Varianten-Beispiel (frische Kopie bei jedem Aufruf). */
export function buildVariantenSampleProject(): Project {
const base = structuredClone(sampleProject);
const rf1 = (base.roofs ?? [])[0];
const roofs: Roof[] = [
{ ...rf1, designOption: { set: "dachform", option: "b" } },
{ ...rf1, id: "RF2", shape: "flach", pitchDeg: 0, overhang: 0.15, thickness: 0.3, designOption: { set: "dachform", option: "a" } },
];
const openings: Opening[] = (base.openings ?? []).map((o) => (o.id === "O2" ? { ...o, designOption: { set: "fassade", option: "a" } } : o));
const o2 = (base.openings ?? []).find((o) => o.id === "O2")!;
openings.push({ ...o2, id: "O-band", position: 0.7, width: 3.6, height: 1.0, sillHeight: 1.1, designOption: { set: "fassade", option: "b" } });
return {
...base,
id: "beispiel-varianten",
name: "Beispiel Varianten",
roofs,
openings,
designOptionSets: structuredClone(VARIANTEN_SETS),
};
}
+74
View File
@@ -224,6 +224,10 @@ export type Ceiling = {
bottom?: VerticalAnchor;
/** [271] Umbau: Status (Bestand, Abbruch, Neu) und Etappe. Fehlt ⇒ Bestand. */
renovation?: Renovation;
/**
* [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
*/
designOption?: DesignOptionRef;
};
/**
@@ -331,6 +335,10 @@ export type Column = {
hatchSource?: AttributeSource;
/** [271] Umbau: Status (Bestand, Abbruch, Neu) und Etappe. Fehlt ⇒ Bestand. */
renovation?: Renovation;
/**
* [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
*/
designOption?: DesignOptionRef;
};
/**
@@ -667,6 +675,29 @@ export type CustomPalette = {
visible?: boolean;
};
/** [272] Eine Variante eines Satzes (z. B. „A Flachdach“). */
export type DesignOption = { id: string; name: string };
/** [272] Zugehörigkeit eines Elements zu einer Variante (Archicad „Design Options“). */
export type DesignOptionRef = {
/** Id des Variantensatzes (`DesignOptionSet.id`). */
set: string;
/** Id der Variante im Satz (`DesignOption.id`). */
option: string;
};
/**
* [272] Ein Variantensatz (z. B. „Dachform“) mit seinen Varianten; je Darstellung ist genau eine Variante des
* Satzes sichtbar (Vorgabe: die Hauptvariante).
*/
export type DesignOptionSet = {
id: string;
name: string;
options: Array<DesignOption>;
/** Id der Hauptvariante. Fehlt/unbekannt ⇒ die erste Variante. */
primary?: string;
};
/**
* Detailgrad der Darstellung (≙ DOSSIER Einfach/Standard/Detail). Wirkt im
* Grundriss auf Tür-/Fenstersymbole + Schraffuren/Linienfeinheit (siehe
@@ -1010,6 +1041,10 @@ export type Drawing2D = {
* Verhalten (ohne `hatchId` keine Schraffur).
*/
hatchSource?: AttributeSource;
/**
* [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
*/
designOption?: DesignOptionRef;
};
/** Geometrie eines 2D-Zeichenelements (Tag `shape`). */
@@ -1407,6 +1442,8 @@ export type DrawingLevel = {
* noch, Abbruch späterer Etappen steht noch als Bestand. Fehlt ⇒ alle Etappen.
*/
renovationPhase?: string;
/** [272] Variantenkombination: Satz-Id → Varianten-Id (fehlende Sätze ⇒ Hauptvariante). */
designOptions?: { [key in string]: string };
};
/**
@@ -1557,6 +1594,10 @@ export type ExtrudedSolid = {
componentId?: string;
/** [271] Umbau: Status (Bestand, Abbruch, Neu) und Etappe. Fehlt ⇒ Bestand. */
renovation?: Renovation;
/**
* [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
*/
designOption?: DesignOptionRef;
};
/**
@@ -2161,6 +2202,10 @@ export type LayoutViewport = {
* gleicher ±0.00 stehen und Kontext ausserhalb des Rahmens beschnitten wird.
*/
center?: Vec2;
/**
* [272] Variantenkombination des Viewports (über der des Ausschnitts): Satz-Id → Varianten-Id (fehlende Sätze ⇒ Hauptvariante).
*/
designOptions?: { [key in string]: string };
};
/** Linienenden aller Striche im Plan/Schnitt/Ansicht und in den Exporten ([146]); fehlt = flach. */
@@ -2799,6 +2844,10 @@ export type Opening = {
* [271] Umbau: Status (Bestand, Abbruch, Neu) und Etappe. Fehlt ⇒ Bestand wie die Wand (eine neue Öffnung in einer Bestandswand bricht die Wand dort ab, eine Öffnung „Abbruch“ wird zugemauert).
*/
renovation?: Renovation;
/**
* [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
*/
designOption?: DesignOptionRef;
};
/**
@@ -3255,6 +3304,11 @@ export type Project = {
};
/** [271] Umbau: Etappen, Farben je Status (SIA 400) und eigene Umbaufilter. */
renovation?: RenovationSettings;
/**
* [272] Variantensätze (Archicad „Design Options“): Elemente mit `designOption` erscheinen nur in der
* Kombination ihrer Variante.
*/
designOptionSets?: Array<DesignOptionSet>;
};
/** Protokolleintrag einer Publikation ([79]): Datum, Blätter mit Revision, erzeugte Dateien. */
@@ -3505,6 +3559,10 @@ export type Roof = {
parapetComponentId?: string;
/** [271] Umbau: Status (Bestand, Abbruch, Neu) und Etappe. Fehlt ⇒ Bestand. */
renovation?: Renovation;
/**
* [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
*/
designOption?: DesignOptionRef;
};
/**
@@ -3609,6 +3667,10 @@ export type Room = {
* [271] Umbau: Status (Bestand, Abbruch, Neu) und Etappe. Fehlt ⇒ Bestand (nur Sichtbarkeit und Flächen je Zustand, keine Umbau-Farbe: ein Raum ist kein Bauteil).
*/
renovation?: Renovation;
/**
* [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
*/
designOption?: DesignOptionRef;
};
/**
@@ -4019,6 +4081,10 @@ export type Stair = {
postDepth?: number;
/** [271] Umbau: Status (Bestand, Abbruch, Neu) und Etappe. Fehlt ⇒ Bestand. */
renovation?: Renovation;
/**
* [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
*/
designOption?: DesignOptionRef;
};
/**
@@ -4395,6 +4461,8 @@ export type ViewSnapshot = {
* noch, Abbruch späterer Etappen steht noch als Bestand. Fehlt ⇒ alle Etappen.
*/
renovationPhase?: string;
/** [272] Variantenkombination: Satz-Id → Varianten-Id (fehlende Sätze ⇒ Hauptvariante). */
designOptions?: { [key in string]: string };
};
/**
@@ -4466,6 +4534,8 @@ export type ViewTemplate = {
* noch, Abbruch späterer Etappen steht noch als Bestand. Fehlt ⇒ alle Etappen.
*/
renovationPhase?: string;
/** [272] Variantenkombination: Satz-Id → Varianten-Id (fehlende Sätze ⇒ Hauptvariante). */
designOptions?: { [key in string]: string };
};
/** Ansichtstyp eines Geschosses (wie in App). */
@@ -4624,6 +4694,10 @@ export type Wall = {
surfacePatternOffset?: Vec2;
/** [271] Umbau: Status (Bestand, Abbruch, Neu) und Etappe. Fehlt ⇒ Bestand. */
renovation?: Renovation;
/**
* [272] Variante, zu der das Element gehört (`Project.designOptionSets`). Fehlt ⇒ Hauptmodell (immer sichtbar).
*/
designOption?: DesignOptionRef;
};
/**
+5
View File
@@ -36,6 +36,7 @@ export interface NativeAppMenuHandlers {
onNewProjectFromComplexSample: () => void;
onNewProjectFromWettbewerbSample: () => void;
onNewProjectFromUmbauSample: () => void;
onNewProjectFromVariantenSample: () => void;
onNewProjectFromTemplate: () => void;
onOpenProject: () => void;
onSaveProject: () => void;
@@ -194,6 +195,10 @@ export function useNativeAppMenu(
text: t("menu.native.newFromUmbauSample"),
action: () => handlersRef.current.onNewProjectFromUmbauSample(),
}),
await MenuItem.new({
text: t("menu.native.newFromVariantenSample"),
action: () => handlersRef.current.onNewProjectFromVariantenSample(),
}),
await MenuItem.new({
text: t("menu.native.newFromTemplateFile"),
action: () => handlersRef.current.onNewProjectFromTemplate(),
+60
View File
@@ -0,0 +1,60 @@
// [272] Varianten-Vergleich im Flächenbilanz-Panel: Kennzahlen (GF, HNF, GV, Fussabdruck, AZ, ÜZ) und Kosten (Grobschätzung
// inkl. MwSt.) je Kombination der Variantensätze nebeneinander, Hauptkombination zuerst (Kern `design_options::compare`);
// mit CSV-Export. Nur mit Variantensätzen im Projekt; `renovation`: Umbau-Zustand wie die Kennzahlenleiste.
import { t } from "../i18n";
import { compareDesignOptions, compareDesignOptionsCsv, designOptionSets, exportProjectName, formatChf } from "../core";
import type { Project } from "../model/types";
import { downloadCsv } from "./downloadFile";
import { runWithAnonymityGate } from "../state/anonymityGate";
const fmt = (n: number, d = 1) => n.toLocaleString("de-CH", { minimumFractionDigits: d, maximumFractionDigits: d });
/** Spaltenköpfe (übersetzt) für Tabelle und CSV. */
export function designOptionCompareHead(): string[] {
return [t("designOption.compare.combination"), "GF m²", "HNF m²", "GV m³", t("designOption.compare.footprint"), "AZ", "ÜZ", t("designOption.compare.cost")];
}
export function DesignOptionCompareSection({ project, renovation = "" }: { project: Project; renovation?: string }) {
if (!designOptionSets(project).length) return null;
const rows = compareDesignOptions(project, renovation);
if (!rows.length) return null;
const head = designOptionCompareHead();
const stem = `${exportProjectName(project) || "projekt"}-varianten`;
const exportCsv = () => runWithAnonymityGate(project, [`${stem}.csv`], () => downloadCsv(`${stem}.csv`, compareDesignOptionsCsv(project, head, renovation)));
const base = rows[0];
const delta = (v: number, b: number, d: number) => (v === b ? "" : ` (${v > b ? "+" : "−"}${fmt(Math.abs(v - b), d)})`);
return (
<div className="kz-variants" data-testid="design-option-compare">
<div className="balance-section-label">{t("designOption.compare.title")}</div>
<div className="kz-variants-scroll">
<table className="kz-variants-table">
<thead>
<tr>
{head.map((h) => (
<th key={h}>{h}</th>
))}
</tr>
</thead>
<tbody>
{rows.map((r) => (
<tr key={r.label} className={r.primary ? "kz-variants-primary" : undefined} data-testid="design-option-compare-row">
<td title={r.label}>{r.label}</td>
<td className="num">{fmt(r.gf) + delta(r.gf, base.gf, 1)}</td>
<td className="num">{fmt(r.hnf) + delta(r.hnf, base.hnf, 1)}</td>
<td className="num">{fmt(r.gv, 0) + delta(r.gv, base.gv, 0)}</td>
<td className="num">{fmt(r.footprint)}</td>
<td className="num">{r.az == null ? "–" : fmt(r.az, 2)}</td>
<td className="num">{r.uez == null ? "–" : fmt(r.uez, 2)}</td>
<td className="num">{formatChf(r.cost)}</td>
</tr>
))}
</tbody>
</table>
</div>
<button type="button" className="balance-export" data-testid="design-option-compare-csv" onClick={exportCsv}>
{t("designOption.compare.csv")}
</button>
</div>
);
}
+107
View File
@@ -0,0 +1,107 @@
// [272] Dock-Panel „Varianten“ (wie Archicads Design-Options-Verwaltung): Kombination der aktiven Ansicht (je Satz eine
// Variante; ein Feld der Ebene wie der Umbaufilter, darum je Reiter eigen und mit Undo), „neue Elemente zeichnen in …“
// (Zustand der Sitzung), Auswahl einer Variante zuweisen oder in eine Variante kopieren (ein Undo-Schritt), Sätze und
// Varianten verwalten samt „Übernehmen“ (Ressourcen-Tab, dieselben Bausteine) und der Vergleich der Kennzahlen/Kosten.
import { useMemo, useState } from "react";
import { t } from "../i18n";
import { useStore } from "../state/appStore";
import {
acceptDesignOptionOps, addDesignOptionOps, addDesignOptionSetOps, assignDesignOptionOps, copyToDesignOptionOps, deleteDesignOptionOps, designOptionIds,
designOptionSets, designOptionTargets, levelCombination, parseTarget, renameDesignOptionOps, renameDesignOptionSetOps, setLevelCombinationOps, setPrimaryOptionOps,
} from "../core";
import { DesignOptionsTab, type DesignOptionHandlers } from "../ui/resourceManager/DesignOptionsTab";
import { DesignOptionCompareSection } from "./DesignOptionCompareSection";
import { selectionDesignOptionIds } from "./objectInfo/DesignOptionField";
export function DesignOptionsPanel() {
const project = useStore((s) => s.project);
const activeLevelId = useStore((s) => s.activeLevelId);
const selection = useStore((s) => s.selection);
const draw = useStore((s) => s.drawDesignOption);
const setDraw = useStore((s) => s.setDrawDesignOption);
const applyChange = useStore((s) => s.applyChange);
const [target, setTarget] = useState("");
const [showCompare, setShowCompare] = useState(false);
const sets = designOptionSets(project);
const level = project.drawingLevels.find((l) => l.id === activeLevelId);
const combo = levelCombination(project, level);
const levelEditable = !!level && (level.kind === "floor" || level.kind === "section" || level.kind === "elevation" || level.kind === "ceiling");
const targets = designOptionTargets(project);
const selIds = useMemo(() => designOptionIds(project, selectionDesignOptionIds(selection)), [project, selection]);
const handlers: DesignOptionHandlers = {
onAddDesignOptionSet: (name) => applyChange((p) => addDesignOptionSetOps(p, name).ops),
onRenameDesignOptionSet: (setId, name) => applyChange((p) => renameDesignOptionSetOps(p, setId, name), `dopt-set-${setId}`),
onAddDesignOption: (setId) => applyChange((p) => addDesignOptionOps(p, setId)),
onRenameDesignOption: (setId, optionId, name) => applyChange((p) => renameDesignOptionOps(p, setId, optionId, name), `dopt-${setId}-${optionId}`),
onSetPrimaryDesignOption: (setId, optionId) => applyChange((p) => setPrimaryOptionOps(p, setId, optionId)),
onAcceptDesignOption: (setId, optionId) => applyChange((p) => acceptDesignOptionOps(p, setId, optionId)),
onDeleteDesignOption: (setId, optionId) => applyChange((p) => deleteDesignOptionOps(p, setId, optionId)),
};
const drawKey = draw ? `${draw.set}/${draw.option}` : "";
return (
<div className="design-options-panel" data-testid="design-options-panel">
{sets.length > 0 && (
<>
<div className="balance-section-label">{t("designOption.viewCombination")}</div>
{sets.map((s) => (
<label key={s.id} className="kz-parcel">
<span>{s.name}</span>
<select
className="kz-input"
value={combo[s.id] ?? ""}
disabled={!levelEditable}
aria-label={s.name}
data-testid={`design-option-combo-${s.id}`}
onChange={(e) => level && applyChange((p) => setLevelCombinationOps(p, level.id, s.id, e.target.value))}
>
{s.options.map((o) => (
<option key={o.id} value={o.id}>
{o.name}
</option>
))}
</select>
</label>
))}
<label className="kz-parcel">
<span>{t("designOption.drawIn")}</span>
<select className="kz-input" value={drawKey} aria-label={t("designOption.drawIn")} data-testid="design-option-draw" onChange={(e) => setDraw(parseTarget(e.target.value))}>
<option value="">{t("designOption.main")}</option>
{targets.map((x) => (
<option key={x.key} value={x.key}>
{x.label}
</option>
))}
</select>
</label>
<div className="balance-section-label">{t("designOption.selection", { n: selIds.length })}</div>
<div className="kz-parcel">
<select className="kz-input" value={target} aria-label={t("designOption.label")} data-testid="design-option-target" onChange={(e) => setTarget(e.target.value)}>
<option value="">{t("designOption.main")}</option>
{targets.map((x) => (
<option key={x.key} value={x.key}>
{x.label}
</option>
))}
</select>
<button type="button" className="kz-add" disabled={!selIds.length} data-testid="design-option-assign" onClick={() => applyChange((p) => assignDesignOptionOps(p, selIds, parseTarget(target)))}>
{t("designOption.assign")}
</button>
<button type="button" className="kz-add" disabled={!selIds.length} data-testid="design-option-copy" onClick={() => applyChange((p) => copyToDesignOptionOps(p, selIds, parseTarget(target)))}>
{t("designOption.copy")}
</button>
</div>
</>
)}
<DesignOptionsTab project={project} handlers={handlers} />
{sets.length > 0 && (
<>
<button type="button" className="balance-export" data-testid="design-option-compare-open" onClick={() => setShowCompare((v) => !v)}>
{showCompare ? t("designOption.compare.hide") : t("designOption.compare.show")}
</button>
{showCompare && <DesignOptionCompareSection project={project} />}
</>
)}
</div>
);
}
+4
View File
@@ -15,6 +15,7 @@ import type { Project, RoomProgramRow } from "../model/types";
import { setField, setFieldIfChanged } from "../core";
import { RoomProgramImportButton } from "../ui/RoomProgramImportDialog";
import { ProgramCompareSection } from "./ProgramCompareSection";
import { DesignOptionCompareSection } from "./DesignOptionCompareSection";
type ProgramStatus = ReturnType<typeof checkRoomProgram>["rows"][number]["status"];
@@ -101,6 +102,9 @@ export function KennzahlenSection() {
))}
</div>
{/* [272] Varianten: Kennzahlen und Kosten je Kombination nebeneinander (Leiste oben: Hauptvarianten). */}
<DesignOptionCompareSection project={project} renovation={renState} />
<label className="kz-parcel">
<span>{t("kennzahlen.parcelArea")}</span>
<input
+3
View File
@@ -39,6 +39,7 @@ import { elementDimensions } from "./objectInfo/elementDims";
import { InfoGroups, hasInfoGroups } from "./objectInfo/InfoGroups";
import { infoGroupFrame, useInfoGroupState } from "./objectInfo/InfoGroup";
import { RenovationField } from "./objectInfo/RenovationField";
import { DesignOptionField } from "./objectInfo/DesignOptionField";
// ── Bezugspunkt-Raster ───────────────────────────────────────────────────────
// Neun Anker als 3×3-Raster. Zeile 0 = oben (fy=0), Spalte 0 = links (fx=0).
@@ -198,6 +199,8 @@ export function ObjectInfoPanel({ showPlacement = true }: { showPlacement?: bool
{/* [271] Umbau: Status und Etappe der Auswahl (Mehrfachauswahl in einem Undo-Schritt). */}
<RenovationField />
{/* [272] Variante der Auswahl (Hauptmodell oder Satz: Variante; ein Undo-Schritt). */}
<DesignOptionField />
{showPlacement && (
<>
+13
View File
@@ -98,6 +98,19 @@ export function RoomBalanceTabIcon() {
);
}
/** [272] Varianten — Verzweigung in zwei Äste (A/B). */
export function DesignOptionsTabIcon() {
return (
<svg {...common}>
<path d="M8 14V8" />
<path d="M8 8L3.5 3.5" />
<path d="M8 8l4.5-4.5" />
<circle cx="3.5" cy="3" r="1.2" />
<circle cx="12.5" cy="3" r="1.2" />
</svg>
);
}
/** Verlauf — Uhr mit Rückwärtspfeil. */
export function HistoryTabIcon() {
return (
+13
View File
@@ -30,6 +30,7 @@ import { BcfPanel } from "./BcfPanel";
import { ClashPanel } from "./ClashPanel";
import { HistoryPanel } from "./HistoryPanel";
import { RenovationPanel, RenovationTabIcon } from "./RenovationPanel";
import { DesignOptionsPanel } from "./DesignOptionsPanel";
import { ObjectSettingsPanel } from "./objectSettings/ObjectSettingsPanel";
import {
ToolsTabIcon,
@@ -41,6 +42,7 @@ import {
RoomBalanceTabIcon,
BcfTabIcon,
HistoryTabIcon,
DesignOptionsTabIcon,
} from "./PanelIcons";
/** IDs der eingebauten Dock-Panels (auch für defaultLayout/Filter nutzbar). */
@@ -58,6 +60,7 @@ export const BUILTIN_PANEL_IDS = {
bcf: "bcf",
clash: "clash",
history: "history",
designOptions: "design-options",
objectSettings: "object-settings",
objectLibrary: "object-library",
renovation: "renovation",
@@ -202,6 +205,16 @@ registerPanel({
render: () => <HistoryPanel />,
});
// [272] Varianten (Archicad „Design Options“): Sätze/Varianten, Kombination der Ansicht, Zeichen-Variante, Zuweisen,
// Übernehmen, Vergleich. Nicht im Standard-Layout; über „Fenster > Panels“ bzw. den Chip „Variante: …“ der Statusleiste.
registerPanel({
id: BUILTIN_PANEL_IDS.designOptions,
title: "designOption.title",
icon: <DesignOptionsTabIcon />,
hasDisplayMode: false,
render: () => <DesignOptionsPanel />,
});
// Objekteinstellungen ([195]) — Taste T: schwebendes Fenster, folgt der Auswahl; Bereiche „Objekt" (Objekt-Info)
// und „Darstellung" (Attribute). Nicht im Standard-Layout; öffnet sich mit T bzw. „Bearbeiten > Objekteinstellungen…".
registerPanel({
@@ -0,0 +1,48 @@
// [272] Objekt-Info und Objekteinstellungen: „Variante“ — Hauptmodell oder eine Variante eines Satzes für die Auswahl.
// Mehrfachauswahl: alle gewählten Elemente in einem Undo-Schritt; verschiedene Werte zeigen „gemischt“. Nur mit
// Variantensätzen im Projekt.
import { useMemo } from "react";
import { t } from "../../i18n";
import { assignDesignOptionOps, commonDesignOption, designOptionIds, designOptionSets, designOptionTargets, parseTarget } from "../../core";
import { useStore } from "../../state/appStore";
import type { Selection } from "../../state/selection";
import { Dropdown } from "../../ui/Dropdown";
import { selectionRenovationIds } from "../../state/renovationHook";
const MIXED = "__mixed";
/** Ids der Auswahl, die einer Variante angehören können (Bauteile, Räume, 2D-Zeichnungen). */
export function selectionDesignOptionIds(sel: Selection): string[] {
return [...selectionRenovationIds(sel), ...sel.drawings];
}
export function DesignOptionField() {
const project = useStore((s) => s.project);
const selection = useStore((s) => s.selection);
const applyChange = useStore((s) => s.applyChange);
const ids = useMemo(() => designOptionIds(project, selectionDesignOptionIds(selection)), [project, selection]);
const common = useMemo(() => commonDesignOption(project, ids), [project, ids]);
if (ids.length === 0 || designOptionSets(project).length === 0) return null;
const value = common === "mixed" || common === null ? MIXED : common;
const options = [
...(value === MIXED ? [{ value: MIXED, label: t("renovation.mixed") }] : []),
{ value: "", label: t("designOption.main") },
...designOptionTargets(project).map((x) => ({ value: x.key, label: x.label })),
];
return (
<div className="objinfo-field" data-testid="objinfo-design-option">
<span className="objinfo-flabel">{t("designOption.label")}</span>
<Dropdown
value={value}
onChange={(v) => {
if (v === MIXED) return;
applyChange((p) => assignDesignOptionOps(p, ids, parseTarget(v)));
}}
options={options}
title={t("designOption.label")}
width={150}
/>
</div>
);
}
+6 -2
View File
@@ -24,6 +24,8 @@ export interface AxoOptions extends Doc3d {
/** [271] Umbaufilter (Id oder Name) und Etappe. */
renovation?: string;
renovationPhase?: string;
/** [272] Variantenkombination (Satz-Id → Varianten-Id); fehlt = Hauptvarianten. */
designOptions?: Record<string, string>;
}
/** Kern-Abfrage `axoPlan`. */
@@ -51,6 +53,8 @@ export function isDoc3dSnapshot(snap: Pick<ViewSnapshot, "viewType">): boolean {
}
/** 3D-Dokument eines Ausschnitts (Kern: `sheet_viewports::doc3d_buf`): `doc3d`, sonst sein Blickwinkel `view3d`. */
export function snapshotAxoPlan(project: Project, snap: ViewSnapshot, visibleCodes: Set<string>, scaleDenominator: number, mono = true): Plan | null {
return generateAxoPlan(project, { view: snap.view3d, ...(snap.doc3d ?? {}), visibleCodes, scaleDenominator, mono });
export function snapshotAxoPlan(project: Project, snap: ViewSnapshot, visibleCodes: Set<string>, scaleDenominator: number, mono = true, designOptions?: Record<string, string> | null): Plan | null {
// [272] Variantenkombination des Ausschnitts bzw. Viewports.
const opts = designOptions ?? snap.designOptions;
return generateAxoPlan(project, { view: snap.view3d, ...(snap.doc3d ?? {}), visibleCodes, scaleDenominator, mono, ...(opts && Object.keys(opts).length ? { designOptions: opts } : {}) });
}
+2
View File
@@ -87,6 +87,8 @@ export function levelArg(level: DrawingLevel) {
// [271] Umbaufilter und Etappe der Ebene (Kern `renovation.rs`).
renovationFilter: level.renovationFilter,
renovationPhase: level.renovationPhase,
// [272] Variantenkombination der Ebene (Kern `design_options.rs`, Sichtbarkeit `renovation.rs`).
designOptions: level.designOptions,
};
}
+8 -2
View File
@@ -101,6 +101,8 @@ export function classFilterText(hide?: Hide3d, extra?: Record<string, unknown>):
h.renovation = f.renovation;
if (f.renovationPhase) h.renovationPhase = f.renovationPhase;
}
// [272] Variantenkombination der Ansicht (fehlt = Hauptvarianten; Kern `renovation.rs`).
if (f.designOptions && Object.keys(f.designOptions).length) h.designOptions = f.designOptions;
return Object.keys(h).length || extra ? JSON.stringify({ ...extra, ...h }) : "";
}
@@ -125,6 +127,8 @@ export interface Filter3d {
/** [271] Umbaufilter der Ansicht (Id) und Etappe: Ausgeblendetes fehlt, Bauteile in der Umbau-Farbe (ohne Teil-Cache). */
renovation?: string;
renovationPhase?: string;
/** [272] Variantenkombination der Ansicht (Satz-Id → Varianten-Id); fehlt = Hauptvarianten. */
designOptions?: Record<string, string>;
}
/**
@@ -335,7 +339,8 @@ export function projectToModel3d(project: Project, opts: Model3dOptions = {}): R
if (opts.renovationPhase) extra.renovationPhase = opts.renovationPhase;
}
const text = classFilterText(opts.hide, Object.keys(extra).length ? extra : undefined);
const parts = opts.modelView || opts.renovation || filter3d(opts.hide).renovation || explode > 0 ? doc.query<Model3dParts>("model3dParts", args, text) : doc.model3dParts<Model3dParts>(args, text);
// [272] Mit Variantensätzen ohne Änderungs-Antworten (die Teile hängen an der Kombination).
const parts = opts.modelView || opts.renovation || filter3d(opts.hide).renovation || project.designOptionSets?.length || explode > 0 ? doc.query<Model3dParts>("model3dParts", args, text) : doc.model3dParts<Model3dParts>(args, text);
// [115] Freie Körper als Kern-Netze (`model3d/solids.rs`) zwischen Kontext-Meshes und Stützen.
const meshes: RMesh[] = [...parts.contextMeshes];
for (const m of parts.solidMeshes) meshes.push(m);
@@ -389,7 +394,8 @@ export function projectToModel3dParts(project: Project, opts: Model3dOptions = {
const layered = opts.layeredWalls ?? true;
const detail = opts.detail ?? "fein";
// [271] Mit Umbaufilter ohne Teil-Cache: das ganze Modell (`projectToModel3d`).
if (explodeGap(opts.explode) > 0 || opts.renovation || filter3d(opts.hide).renovation) return null;
// [272] Mit Variantensätzen ebenso (die Teile hängen an der Kombination; der Kern rechnet dann ohne Cache).
if (explodeGap(opts.explode) > 0 || opts.renovation || filter3d(opts.hide).renovation || project.designOptionSets?.length) return null;
const voids = !!opts.voids;
const args = [layered ? 1 : 0, DETAIL_CODE[detail] ?? 3, opts.forSection ? 1 : 0, voids ? 1 : 0, 0];
const { parts, keyed } = documentFor(project).model3dPartsKeyed<Model3dParts>(args, classFilterText(opts.hide));
+25 -3
View File
@@ -67,10 +67,14 @@ export async function viewportLevelPlan(
/** [173] Modelldarstellung des Ausschnitts (`ViewSnapshot.modelViewOptionId`): geht der Ebene und der
* Vorlage vor (Kern: `sheet_viewports::viewport_args`, Schnitt/Ansicht über `modelView`). */
modelViewOptionId?: string | null,
/** [272] Variantenkombination des Ausschnitts/Viewports (über der der Ebene; Kern: `sheet_viewports::snapshot_project`). */
designOptions?: Record<string, string> | null,
): Promise<Plan> {
if (!template && !modelViewOptionId) return levelPlan(project, levelId, visibleCodes, detail, scaleDenominator, forPrint, mono, overrideRuleIds);
const opts = designOptions && Object.keys(designOptions).length ? designOptions : null;
if (!template && !modelViewOptionId && !opts) return levelPlan(project, levelId, visibleCodes, detail, scaleDenominator, forPrint, mono, overrideRuleIds);
let tp = template ? projectWithTemplate(project, levelId, template) : project;
if (modelViewOptionId) tp = projectWithModelView(tp, levelId, modelViewOptionId);
if (opts) tp = projectWithDesignOptions(tp, levelId, opts);
return withDocument(tp, () => levelPlan(tp, levelId, visibleCodes, template?.detail ?? detail, scaleDenominator, forPrint, mono, overrideRuleIds));
}
@@ -78,8 +82,15 @@ export async function viewportLevelPlan(
* Inhalt eines Ausschnitts auf dem Blatt bzw. im PDF: [266] 3D-Ausschnitte (Ansichtstyp „perspektive“) als 3D-Dokument aus dem
* Kern (Vektor-Axonometrie/-Perspektive mit verdeckten Kanten, Kern: `sheet_viewports::doc3d_buf`), sonst {@link viewportLevelPlan}.
*/
export async function viewportSnapshotPlan(project: Project, snap: ViewSnapshot, visibleCodes: Set<string>, scaleDenominator: number, forPrint = false): Promise<Plan> {
if (isDoc3dSnapshot(snap)) return snapshotAxoPlan(project, snap, visibleCodes, scaleDenominator, snapshotMono(project, snap)) ?? EMPTY;
export async function viewportSnapshotPlan(project: Project, snap: ViewSnapshot, visibleCodes: Set<string>, scaleDenominator: number, forPrint = false, viewport?: { designOptions?: Record<string, string> | null } | null): Promise<Plan> {
// [272] Variantenkombination: Ausschnitt, darüber die des Viewports (dieselbe Ansicht in anderer Kombination).
const opts = viewportDesignOptions(snap, viewport);
if (isDoc3dSnapshot(snap)) return snapshotAxoPlan(project, snap, visibleCodes, scaleDenominator, snapshotMono(project, snap), opts) ?? EMPTY;
if (opts) {
const dp = projectWithDesignOptions(project, snap.activeLevelId, opts);
const fp = snap.renovationFilter ? projectWithRenovation(dp, snap.activeLevelId, snap.renovationFilter, snap.renovationPhase) : dp;
return withDocument(fp, () => viewportLevelPlan(fp, snap.activeLevelId, visibleCodes, snap.detail, scaleDenominator, forPrint, snapshotMono(fp, snap), snapshotOverrideRuleIds(fp, snap), snapshotTemplate(fp, snap), snap.modelViewOptionId));
}
// [271] Umbaufilter des Ausschnitts: geht dem der Ebene vor (wie im Kern `sheet_viewports::viewport_args`).
if (snap.renovationFilter) {
const rp = projectWithRenovation(project, snap.activeLevelId, snap.renovationFilter, snap.renovationPhase);
@@ -88,6 +99,17 @@ export async function viewportSnapshotPlan(project: Project, snap: ViewSnapshot,
return viewportLevelPlan(project, snap.activeLevelId, visibleCodes, snap.detail, scaleDenominator, forPrint, snapshotMono(project, snap), snapshotOverrideRuleIds(project, snap), snapshotTemplate(project, snap), snap.modelViewOptionId);
}
/** [272] Kombination eines Ausschnitts samt Viewport (Viewport geht vor); `null` ohne eigene Wahl. */
export function viewportDesignOptions(snap: { designOptions?: Record<string, string> | null }, viewport?: { designOptions?: Record<string, string> | null } | null): Record<string, string> | null {
const m = { ...(snap.designOptions ?? {}), ...(viewport?.designOptions ?? {}) };
return Object.keys(m).length ? m : null;
}
/** [272] Das Projekt mit der Variantenkombination `opts` an der Ebene `levelId` (über deren eigener Wahl). */
export function projectWithDesignOptions(project: Project, levelId: string, opts: Record<string, string>): Project {
return { ...project, drawingLevels: project.drawingLevels.map((l) => (l.id === levelId ? { ...l, designOptions: { ...(l.designOptions ?? {}), ...opts } } : l)) };
}
/** [271] Das Projekt mit Umbaufilter `filter` (und Etappe) an der Ebene `levelId`. */
export function projectWithRenovation(project: Project, levelId: string, filter: string, phase?: string): Project {
return { ...project, drawingLevels: project.drawingLevels.map((l) => (l.id === levelId ? { ...l, renovationFilter: filter, ...(phase ? { renovationPhase: phase } : {}) } : l)) };
+5 -1
View File
@@ -579,7 +579,11 @@ export function createProjectSlice(
const applyCmd = (req0: object, coalesceKey?: string) => {
// [271] Aktueller Zeichen-Status: der Kern gibt ihn neuen Bauteilen der Zeichenbefehle (`commands::stamp_renovation`).
const dr = (get() as unknown as { drawRenovation?: { status: string; phase?: string } }).drawRenovation;
const req = dr && (dr.status !== "existing" || dr.phase) ? { ...req0, renovation: dr } : req0;
const req1 = dr && (dr.status !== "existing" || dr.phase) ? { ...req0, renovation: dr } : req0;
// [272] Aktuelle Zeichen-Variante: neue Elemente der Zeichenbefehle gehören ihr (`design_options::stamp_ops`).
const dopt = (get() as unknown as { drawDesignOption?: { set: string; option: string } | null }).drawDesignOption;
const known = dopt && get().project.designOptionSets?.some((s) => s.id === dopt.set && s.options.some((o) => o.id === dopt.option));
const req = known ? { ...req1, designOption: dopt } : req1;
if (forwarded(() => storeDocument(get().project).cmdOps(req), coalesceKey)) return;
let notice: string | undefined;
set((s) => {
+30
View File
@@ -62,8 +62,12 @@ declare global {
context: () => { id: string; type: string; first?: { x: number; y: number } }[];
/** [271] Füllfarben der Element-Flächen im Grundriss der aktiven Ebene (Farbe → Anzahl, alle Klassen, 1:100). */
planFillColors: () => Record<string, number>;
/** [272] Öffnungs-Ids im Grundriss der aktiven Ebene (alle Klassen, 1:100). */
planOpeningIds: () => string[];
/** [271] Umbau: Filter und Etappe der aktiven Ebene, Zeichen-Status, Status je Wand. */
renovation: () => { filter: string | null; phase: string | null; draw: string; walls: Record<string, string> };
/** [272] Varianten: Kombination der aktiven Ebene, Zeichen-Variante, Variante je Element (`set/option`, leer = Hauptmodell), Sätze. */
designOptions: () => { level: Record<string, string>; draw: string | null; elements: Record<string, string>; sets: string[] };
/** [193] Gefüllte Flächen (Füllfarbe gesetzt) im Grundriss der aktiven Ebene (alle Kategorien, 1:100); bei 0 ist nichts Gefülltes mehr zu sehen. */
planFills: () => number;
/** [193] Höhe (z) des ersten Gelände-Netz-Punkts. */
@@ -157,6 +161,23 @@ export function installTestHooks(): void {
walk(s.project.layers);
return generatePlan(s.project, s.activeLevelId, codes, undefined, s.detail, false, false, true, 50).primitives.filter((q) => q.kind === "line" && q.cls === cls).length;
},
planOpeningIds: () => {
const s = getState();
const codes = new Set<string>();
const walk = (cs: { code: string; children?: unknown[] }[]): void => {
for (const c of cs) {
codes.add(c.code);
walk((c.children ?? []) as { code: string; children?: unknown[] }[]);
}
};
walk(s.project.layers);
const ids = new Set<string>();
for (const q of generatePlan(s.project, s.activeLevelId, codes, undefined, s.detail, false, false, true, 100).primitives) {
const o = (q as { openingId?: string }).openingId;
if (o) ids.add(o);
}
return [...ids].sort();
},
planFillColors: () => {
const s = getState();
const codes = new Set<string>();
@@ -174,6 +195,15 @@ export function installTestHooks(): void {
}
return out;
},
designOptions: () => {
const s = getState();
const l = s.project.drawingLevels.find((x) => x.id === s.activeLevelId);
const elements: Record<string, string> = {};
for (const list of [s.project.walls, s.project.openings, s.project.roofs, s.project.ceilings, s.project.rooms]) {
for (const e of (list ?? []) as { id: string; designOption?: { set: string; option: string } }[]) elements[e.id] = e.designOption ? `${e.designOption.set}/${e.designOption.option}` : "";
}
return { level: l?.designOptions ?? {}, draw: s.drawDesignOption ? `${s.drawDesignOption.set}/${s.drawDesignOption.option}` : null, elements, sets: (s.project.designOptionSets ?? []).map((x) => x.id) };
},
renovation: () => {
const s = getState();
const l = s.project.drawingLevels.find((x) => x.id === s.activeLevelId);
+2
View File
@@ -90,6 +90,7 @@ export function useNativeMenu(opts: {
onNewProjectFromComplexSample,
onNewProjectFromWettbewerbSample,
onNewProjectFromUmbauSample,
onNewProjectFromVariantenSample,
onNewProjectFromTemplate,
onOpenProject,
onSaveProject,
@@ -121,6 +122,7 @@ export function useNativeMenu(opts: {
onNewProjectFromComplexSample,
onNewProjectFromWettbewerbSample,
onNewProjectFromUmbauSample,
onNewProjectFromVariantenSample,
onNewProjectFromTemplate,
onOpenProject,
onSaveProject,
+9
View File
@@ -51,6 +51,7 @@ import { withNewProjectNames } from "../model/newProjectNames";
import { buildComplexSampleProject } from "../model/sampleProjectComplex";
import { buildWettbewerbSampleProject } from "../model/sampleProjectWettbewerb";
import { buildUmbauSampleProject } from "../model/sampleProjectUmbau";
import { buildVariantenSampleProject } from "../model/sampleProjectVarianten";
import { withStandards } from "../model/standards";
import type { Project } from "../model/types";
import type { PlanViewHandle } from "../views/plan/PlanView";
@@ -578,6 +579,13 @@ export function useProjectFileActions(
getState().loadProject(next);
lastSavedProjectRef.current = next;
});
// [272] „Neu aus Vorlage: Beispiel Varianten" — Demo-Haus mit den Sätzen Dachform (Flach-/Satteldach) und Fassade.
const onNewProjectFromVariantenSample = () => guardDiscard(() => {
releaseCurrentProjectLock();
const next = buildVariantenSampleProject();
getState().loadProject(next);
lastSavedProjectRef.current = next;
});
// „Neu aus Vorlage: Datei wählen…" — native `.obpt`-Dialog unter Tauri, sonst
// das versteckte `<input type=file>` (projectTemplateFileInputRef).
const onNewProjectFromTemplate = () => {
@@ -923,6 +931,7 @@ export function useProjectFileActions(
onNewProjectFromComplexSample,
onNewProjectFromWettbewerbSample,
onNewProjectFromUmbauSample,
onNewProjectFromVariantenSample,
onNewProjectFromTemplate,
onProjectTemplateFileChosen,
releaseCurrentProjectLock,
+9 -1
View File
@@ -18,7 +18,7 @@ import type { useProjectActions } from "./useProjectActions";
import type { useTopBarState } from "./useTopBarState";
import { useViewTemplateHandlers } from "./useViewTemplateHandlers";
import { modelViewHandlers } from "./useModelViewHandlers";
import { setField, setPhasesOps } from "../core";
import { setField, setPhasesOps, addDesignOptionSetOps, renameDesignOptionSetOps, addDesignOptionOps, renameDesignOptionOps, setPrimaryOptionOps, acceptDesignOptionOps, deleteDesignOptionOps } from "../core";
type TopBar = ReturnType<typeof useTopBarState>;
type Dialogs = ReturnType<typeof useDialogState>;
@@ -145,6 +145,14 @@ export function useResourceHandlers(opts: {
else delete next.styles;
return [setField("renovation", Object.keys(next).length ? next : undefined)];
}),
// [272] Varianten (Ressourcen-Tab „Varianten“): Sätze/Varianten, Hauptvariante, Übernehmen, Löschen (je ein Undo-Schritt).
onAddDesignOptionSet: (name) => applyChange((p) => addDesignOptionSetOps(p, name).ops),
onRenameDesignOptionSet: (setId, name) => applyChange((p) => renameDesignOptionSetOps(p, setId, name), `dopt-set-${setId}`),
onAddDesignOption: (setId) => applyChange((p) => addDesignOptionOps(p, setId)),
onRenameDesignOption: (setId, optionId, name) => applyChange((p) => renameDesignOptionOps(p, setId, optionId, name), `dopt-${setId}-${optionId}`),
onSetPrimaryDesignOption: (setId, optionId) => applyChange((p) => setPrimaryOptionOps(p, setId, optionId)),
onAcceptDesignOption: (setId, optionId) => applyChange((p) => acceptDesignOptionOps(p, setId, optionId)),
onDeleteDesignOption: (setId, optionId) => applyChange((p) => deleteDesignOptionOps(p, setId, optionId)),
onPatchComponent: patchComponent,
onPatchWallType: patchWallType,
onAddWallType: addWallType,
+8
View File
@@ -27,6 +27,12 @@ export interface ViewSlice {
*/
drawRenovation: { status: RenovationStatus; phase?: string };
setDrawRenovation: (status: RenovationStatus, phase?: string) => void;
/**
* [272] Aktuelle Zeichen-Variante: neue Elemente der Zeichenbefehle gehören ihr (`null` = Hauptmodell). Zustand der
* Sitzung, kein Undo-Schritt.
*/
drawDesignOption: { set: string; option: string } | null;
setDrawDesignOption: (target: { set: string; option: string } | null) => void;
// Ansichtstyp (Grundriss / Perspektive).
viewType: ViewType;
// Zuletzt gewählter Ansichtstyp je Zeichnungsebene — jeder Tab merkt sich
@@ -100,6 +106,8 @@ export function createViewSlice(api: StoreApi<ViewSlice>): ViewSlice {
activeLevelId: sampleProject.drawingLevels[0].id,
drawRenovation: { status: "existing" },
setDrawRenovation: (status, phase) => set({ drawRenovation: phase ? { status, phase } : { status } }),
drawDesignOption: null,
setDrawDesignOption: (target) => set({ drawDesignOption: target }),
viewType: "grundriss",
viewTypeByLevel: {},
detail: "mittel",
+73 -1
View File
@@ -9404,7 +9404,7 @@ body {
}
.rpi-table th,
.rpi-table td {
padding: 2px 6px;
padding: 2px 4px;
border-bottom: 1px solid var(--border);
text-align: left;
white-space: nowrap;
@@ -9897,4 +9897,76 @@ body {
border: 1px solid var(--border);
border-radius: 999px;
cursor: pointer;
/* [272] Varianten: Vergleichstabelle (Flächenbilanz) und Ressourcen-Tab. */
.kz-variants-scroll {
overflow-x: auto;
}
.kz-variants-table {
border-collapse: collapse;
font-size: 11px;
width: 100%;
}
.kz-variants-table th,
.kz-variants-table td {
padding: 2px 4px;
border-bottom: 1px solid rgba(127, 127, 127, 0.25);
text-align: left;
white-space: nowrap;
}
.kz-variants-table td:first-child {
white-space: normal;
min-width: 110px;
}
.kz-variants-table th {
white-space: normal;
}
.kz-variants-table td.num {
text-align: right;
font-variant-numeric: tabular-nums;
}
.kz-variants-primary td {
font-weight: 600;
}
.rm-design-option-set {
margin-bottom: 8px;
}
.rm-design-option {
padding-left: 16px;
}
.rm-design-option-count {
min-width: 2em;
text-align: right;
opacity: 0.7;
font-variant-numeric: tabular-nums;
}
.rm-design-options .rm-row {
display: flex;
align-items: center;
gap: 4px;
margin: 2px 0;
}
.rm-design-options .rm-row input[type="text"] {
flex: 1 1 auto;
min-width: 0;
}
.rm-design-options .rm-icon-btn {
padding: 0 2px;
line-height: 1;
}
.rm-design-options .rm-icon-btn .material-symbols-outlined {
font-size: 16px;
}
.rm-design-options .rm-add-btn {
white-space: nowrap;
font-size: 11px;
}
.rm-design-options .rm-hint {
font-size: 11px;
opacity: 0.75;
}
.design-options-panel {
padding: 4px 8px 8px;
}
.design-options-panel .kz-parcel select {
max-width: 170px;
}
+7
View File
@@ -26,6 +26,7 @@ export interface AppMenuBarProps {
onNewProjectFromComplexSample: () => void;
onNewProjectFromWettbewerbSample: () => void;
onNewProjectFromUmbauSample?: () => void;
onNewProjectFromVariantenSample?: () => void;
onNewProjectFromTemplate: () => void;
onOpenProject: () => void;
onSaveProject: () => void;
@@ -68,6 +69,8 @@ export interface AppMenuBarProps {
onOpenBcf?: () => void;
/** Verlauf-Panel öffnen ([84]). */
onOpenHistory?: () => void;
/** [272] Panel „Varianten“ öffnen. */
onOpenDesignOptions?: () => void;
}
/** Menüleiste (Bearbeiten/Ansicht/Fenster) — sitzt in der TopBar neben der Wortmarke. */
@@ -77,6 +80,7 @@ export const AppMenuBar = memo(function AppMenuBar({
onNewProjectFromComplexSample,
onNewProjectFromWettbewerbSample,
onNewProjectFromUmbauSample,
onNewProjectFromVariantenSample,
onNewProjectFromTemplate,
onOpenProject,
onSaveProject,
@@ -107,6 +111,7 @@ export const AppMenuBar = memo(function AppMenuBar({
onOpenSettings,
onOpenBcf,
onOpenHistory,
onOpenDesignOptions,
}: AppMenuBarProps) {
const fileItems: DropdownItem[] = [
{ label: t("file.new"), onSelect: onNewProject },
@@ -114,6 +119,7 @@ export const AppMenuBar = memo(function AppMenuBar({
{ label: t("file.newFromComplexSample"), onSelect: onNewProjectFromComplexSample },
{ label: t("file.newFromWettbewerbSample"), onSelect: onNewProjectFromWettbewerbSample },
...(onNewProjectFromUmbauSample ? [{ label: t("file.newFromUmbauSample"), onSelect: onNewProjectFromUmbauSample }] : []),
...(onNewProjectFromVariantenSample ? [{ label: t("file.newFromVariantenSample"), onSelect: onNewProjectFromVariantenSample }] : []),
{ label: t("file.newFromTemplateFile"), onSelect: onNewProjectFromTemplate },
{ divider: true },
{ label: t("file.open"), onSelect: onOpenProject },
@@ -136,6 +142,7 @@ export const AppMenuBar = memo(function AppMenuBar({
{ label: t("menu.edit.undo"), onSelect: onUndo, disabled: !canUndo },
{ label: t("menu.edit.redo"), onSelect: onRedo, disabled: !canRedo },
...(onOpenHistory ? [{ label: t("nav.history"), onSelect: onOpenHistory }] : []),
...(onOpenDesignOptions ? [{ label: t("designOption.title"), onSelect: onOpenDesignOptions }] : []),
{ divider: true },
{
label: t("menu.edit.delete"),
+30
View File
@@ -0,0 +1,30 @@
// [272] Chip „Variante: …“ in der Statusleiste (neben „Umbau“): zeigt die Variantenkombination der aktiven Ansicht (nur die
// Abweichungen von den Hauptvarianten) und öffnet per Klick das Panel „Varianten“, in dem man sie einstellt. Nur sichtbar,
// wenn das Projekt Variantensätze hat; bei wenig Platz wandert es mit Pausfolie und „Umbau“ in „⋯“ ([263]).
import { t } from "../i18n";
import { useStore } from "../state/appStore";
import { combinationSuffix, designOptionTargets } from "../core";
export function DesignOptionControl() {
const project = useStore((s) => s.project);
const activeLevelId = useStore((s) => s.activeLevelId);
const draw = useStore((s) => s.drawDesignOption);
if (!project.designOptionSets?.length) return null;
const level = project.drawingLevels.find((l) => l.id === activeLevelId);
const suffix = combinationSuffix(project, level?.designOptions);
const drawKey = draw ? `${draw.set}/${draw.option}` : "";
const drawLabel = designOptionTargets(project).find((x) => x.key === drawKey)?.label ?? t("designOption.main");
const shown = suffix || t("designOption.primaryCombination");
return (
<button
type="button"
className={`sb-toggle${suffix || draw ? " sb-renovation-on" : ""}`}
data-testid="design-option-toggle"
title={t("designOption.hint", { combination: shown, draw: drawLabel })}
onClick={() => window.dispatchEvent(new CustomEvent("dossier:reveal-panel", { detail: "design-options" }))}
>
{t("designOption.short", { combination: shown })}
</button>
);
}
+31 -6
View File
@@ -44,7 +44,7 @@ import {
type GuideHit,
} from "./sheetSnap";
import { createLayoutImage, imageAspect, imageGeometry } from "../model/layoutImages";
import { posterHeaderItems, viewportScaleLabel } from "../model/posterTemplates";
import { posterHeaderItems, viewportScaleLabel, viewportVariantLabel } from "../model/posterTemplates";
import { planToPrintSvg } from "../export/planToPrintSvg";
import { legendPlan, legendPrintSvg } from "../export/legendSvg";
import { legendBox, legendEntries, legendKeysOfViewports, type LegendKind } from "../analysis/legend";
@@ -111,7 +111,8 @@ export function ViewportPlanSvg({
// Massstab ZUERST: er geht in die Plan-Erzeugung ein (Bemassung in Papier-mm, s. model/dimension.ts).
const scaleN = resolveViewportScale(viewport, snap);
// Geschoss/Zeichnung wie bisher; Schnitt/Ansicht über die abgeleitete Projektion ([115], Schnitt asynchron).
void viewportSnapshotPlan(project, snap, codes, scaleN)
// [272] Eigene Variantenkombination des Viewports (dieselbe Ansicht in anderer Kombination).
void viewportSnapshotPlan(project, snap, codes, scaleN, false, viewport)
.then((plan) => {
if (disposed) return;
const print = planToPrintSvg(plan, {
@@ -130,7 +131,7 @@ export function ViewportPlanSvg({
return () => {
disposed = true;
};
}, [project, viewport.snapshotId, viewport.widthMm, viewport.heightMm, viewport.scaleDenominator, viewport.center?.x, viewport.center?.y]);
}, [project, viewport.snapshotId, viewport.widthMm, viewport.heightMm, viewport.scaleDenominator, viewport.center?.x, viewport.center?.y, viewport.designOptions]);
// Lage/Grösse über die Attribute des inneren SVG (folgt auch dem Ghost beim Ziehen).
useEffect(() => {
if (ref.current) placeInner(ref.current, rect);
@@ -803,9 +804,9 @@ export function LayoutSheetPane({
);
})}
{/* Massstab unter jedem Viewport (Master „Massstabsangaben"). */}
{master?.viewportScaleLabels &&
layout.viewports.map((vp) => {
const l = viewportScaleLabel(project, vp, sheet);
{layout.viewports.map((vp) => {
// [272] Ohne Massstabsangaben des Masters nur der Titelzusatz der Varianten (falls abweichend).
const l = master?.viewportScaleLabels ? viewportScaleLabel(project, vp, sheet) : viewportVariantLabel(project, vp, sheet);
return l ? (
<text key={`sl-${vp.id}`} x={l.x} y={l.y} fontSize={l.sizeMm} fontFamily="Helvetica, Arial, sans-serif" fill="#111111" pointerEvents="none" data-scale-label>
{l.text}
@@ -1217,6 +1218,30 @@ export function LayoutSheetPane({
/>
</span>
</label>
{/* [272] Eigene Variantenkombination des Viewports: dieselbe Ansicht in anderer Kombination (Titelzusatz). */}
{(project.designOptionSets ?? []).map((s) => (
<label key={s.id} className="layout-sheet-hud-row">
<span>{s.name}</span>
<select
className="res-input"
data-testid={`vp-design-option-${s.id}`}
value={selectedVp.designOptions?.[s.id] ?? ""}
onChange={(e) => {
const next = { ...(selectedVp.designOptions ?? {}) };
if (e.target.value) next[s.id] = e.target.value;
else delete next[s.id];
handlers.onPatchViewport(selectedVp.id, { designOptions: Object.keys(next).length ? next : undefined });
}}
>
<option value="">{t("designOption.fromSnapshot")}</option>
{s.options.map((o) => (
<option key={o.id} value={o.id}>
{o.name}
</option>
))}
</select>
</label>
))}
<div className="layout-sheet-hud-size">
{Math.round(selectedVp.widthMm)} × {Math.round(selectedVp.heightMm)} mm
</div>
+6 -1
View File
@@ -48,6 +48,8 @@ import { ModelViewsTab } from "./resourceManager/ModelViewsTab";
import type { ModelViewHandlers } from "./resourceManager/ModelViewsTab";
import { RenovationTab } from "./resourceManager/RenovationTab";
import type { RenovationHandlers } from "./resourceManager/RenovationTab";
import { DesignOptionsTab } from "./resourceManager/DesignOptionsTab";
import type { DesignOptionHandlers } from "./resourceManager/DesignOptionsTab";
import { PenSetsTab } from "./resourceManager/PenSetsTab";
import { PalettesTab } from "./resourceManager/PalettesTab";
import { TextStylesTab } from "./resourceManager/TextStylesTab";
@@ -72,6 +74,7 @@ export type TabId =
| "viewTemplates"
| "modelViews"
| "renovation"
| "designOptions"
| "pens"
| "palettes";
@@ -93,10 +96,11 @@ const TABS: { id: TabId; labelKey: string }[] = [
{ id: "viewTemplates", labelKey: "resources.tab.viewTemplates" },
{ id: "modelViews", labelKey: "resources.tab.modelViews" },
{ id: "renovation", labelKey: "resources.tab.renovation" },
{ id: "designOptions", labelKey: "resources.tab.designOptions" },
];
/** Bündel der immutablen Mutationen (von App über setProject bereitgestellt). */
export interface ResourceManagerHandlers extends ViewTemplateHandlers, ModelViewHandlers, RenovationHandlers {
export interface ResourceManagerHandlers extends ViewTemplateHandlers, ModelViewHandlers, RenovationHandlers, DesignOptionHandlers {
onPatchComponent: (id: string, patch: Partial<Component>) => void;
onAddComponent: () => void;
onDeleteComponent: (id: string) => void;
@@ -496,6 +500,7 @@ export function ResourceManager({
{tab === "viewTemplates" && <ViewTemplatesTab project={project} handlers={handlers} />}
{tab === "modelViews" && <ModelViewsTab project={project} handlers={handlers} />}
{tab === "renovation" && <RenovationTab project={project} handlers={handlers} />}
{tab === "designOptions" && <DesignOptionsTab project={project} handlers={handlers} />}
{tab === "overrides" && (
<OverridesTab
project={project}
+12 -1
View File
@@ -16,6 +16,8 @@ import type { SnapSettings } from "../tools/types";
import { t } from "../i18n";
import { TraceControl } from "./TraceControl";
import { RenovationControl } from "./RenovationControl";
import { DesignOptionControl } from "./DesignOptionControl";
import { useStore } from "../state/appStore";
import { BUILD_INFO, formatBuildShort } from "../update/buildInfo";
export interface StatusBarProps {
@@ -488,6 +490,9 @@ export const StatusBar = memo(function StatusBar({
);
const traceEl = <TraceControl enabled={!!traceEnabled} onRunCommand={onRunCommand} />;
const renovationEl = <RenovationControl />;
// [272] Varianten (nur mit Variantensätzen im Projekt; sonst leer).
const hasDesignOptions = useStore((s) => !!s.project.designOptionSets?.length);
const designOptionEl = <DesignOptionControl />;
const snapEl = <SnapControl snap={snap} onSnapChange={onSnapChange} />;
const refEl = (
<button
@@ -504,7 +509,7 @@ export const StatusBar = memo(function StatusBar({
// Was in „⋯“ wandert (Reihenfolge = Wegfall-Priorität von oben nach unten).
const inMore: React.ReactNode[] = [];
if (level >= 3) inMore.push(<span key="lm">{lineModeEl}</span>);
if (level >= 4) inMore.push(<span key="tr">{traceEl}</span>, <span key="ren">{renovationEl}</span>);
if (level >= 4) inMore.push(<span key="tr">{traceEl}</span>, <span key="ren">{renovationEl}</span>, <span key="dopt">{designOptionEl}</span>);
if (level >= 5) {
inMore.push(<span key="sn">{snapEl}</span>, <span key="rf">{refEl}</span>);
}
@@ -535,6 +540,12 @@ export const StatusBar = memo(function StatusBar({
<Sep />
{renovationEl}
<Sep />
{hasDesignOptions && (
<>
{designOptionEl}
<Sep />
</>
)}
</>
)}
{level < 5 && (
+103
View File
@@ -0,0 +1,103 @@
// [272] Ressourcen-Tab „Varianten“: Variantensätze (z. B. „Dachform“) mit ihren Varianten anlegen, umbenennen, löschen;
// Hauptvariante wählen; „Variante übernehmen“ (ihre Elemente ins Hauptmodell, die übrigen Varianten des Satzes werden
// gelöscht — ein Undo-Schritt). Reine Darstellung über Handler mit Werten (auch im macOS-Nebenfenster).
import { useState } from "react";
import { t } from "../../i18n";
import type { Project } from "../../model/types";
import { designOptionSets, primaryOption } from "../../core";
export interface DesignOptionHandlers {
onAddDesignOptionSet?: (name: string) => void;
onRenameDesignOptionSet?: (setId: string, name: string) => void;
onAddDesignOption?: (setId: string) => void;
onRenameDesignOption?: (setId: string, optionId: string, name: string) => void;
onSetPrimaryDesignOption?: (setId: string, optionId: string) => void;
/** Variante übernehmen: Elemente ins Hauptmodell, übrige Varianten des Satzes gelöscht, Satz weg. */
onAcceptDesignOption?: (setId: string, optionId: string) => void;
/** Satz (ohne `optionId`) bzw. Variante samt ihren Elementen löschen. */
onDeleteDesignOption?: (setId: string, optionId?: string) => void;
}
/** Zahl der Elemente je Variante (Satz-Id → Varianten-Id → Anzahl). */
function counts(project: Project): Map<string, number> {
const out = new Map<string, number>();
const lists = [project.walls, project.openings, project.ceilings, project.roofs, project.stairs, project.columns, project.extrudedSolids, project.rooms, project.drawings2d];
for (const list of lists) {
for (const e of (list ?? []) as { designOption?: { set: string; option: string } }[]) {
if (!e.designOption) continue;
const k = `${e.designOption.set}/${e.designOption.option}`;
out.set(k, (out.get(k) ?? 0) + 1);
}
}
return out;
}
export function DesignOptionsTab({ project, handlers }: { project: Project; handlers: DesignOptionHandlers }) {
const sets = designOptionSets(project);
const [newName, setNewName] = useState("");
const n = counts(project);
const add = () => {
if (!handlers.onAddDesignOptionSet) return;
handlers.onAddDesignOptionSet(newName.trim() || t("designOption.set.defaultName", { n: sets.length + 1 }));
setNewName("");
};
return (
<div className="rm-design-options" data-testid="rm-design-options">
<h4 className="rm-subhead">{t("designOption.sets.title")}</h4>
<p className="rm-hint">{t("designOption.sets.hint")}</p>
{sets.length === 0 && <div className="rm-empty">{t("designOption.sets.empty")}</div>}
{sets.map((s) => {
const prim = primaryOption(s);
return (
<div key={s.id} className="rm-design-option-set" data-testid="rm-design-option-set">
<div className="rm-row">
<input
type="text"
value={s.name}
aria-label={t("designOption.set")}
disabled={!handlers.onRenameDesignOptionSet}
onChange={(e) => handlers.onRenameDesignOptionSet?.(s.id, e.target.value)}
/>
<button type="button" className="rm-icon-btn" title={t("designOption.option.add")} aria-label={t("designOption.option.add")} disabled={!handlers.onAddDesignOption} onClick={() => handlers.onAddDesignOption?.(s.id)} data-testid="rm-design-option-add">
<span className="material-symbols-outlined" aria-hidden="true">add</span>
</button>
<button type="button" className="rm-icon-btn" title={t("designOption.set.delete")} aria-label={t("designOption.set.delete")} disabled={!handlers.onDeleteDesignOption} onClick={() => handlers.onDeleteDesignOption?.(s.id)}>
<span className="material-symbols-outlined" aria-hidden="true">delete</span>
</button>
</div>
{s.options.map((o) => (
<div className="rm-row rm-design-option" key={o.id} data-testid="rm-design-option">
<label className="rm-design-option-primary" title={t("designOption.primary")}>
<input type="radio" name={`primary-${s.id}`} checked={prim === o.id} disabled={!handlers.onSetPrimaryDesignOption} onChange={() => handlers.onSetPrimaryDesignOption?.(s.id, o.id)} aria-label={t("designOption.primary")} />
</label>
<input
type="text"
value={o.name}
aria-label={t("designOption.option")}
disabled={!handlers.onRenameDesignOption}
onChange={(e) => handlers.onRenameDesignOption?.(s.id, o.id, e.target.value)}
/>
<span className="rm-design-option-count" title={t("designOption.count")}>
{n.get(`${s.id}/${o.id}`) ?? 0}
</span>
<button type="button" className="rm-add-btn" disabled={!handlers.onAcceptDesignOption} onClick={() => handlers.onAcceptDesignOption?.(s.id, o.id)} title={t("designOption.accept.hint")} data-testid="rm-design-option-accept">
{t("designOption.accept")}
</button>
<button type="button" className="rm-icon-btn" title={t("designOption.option.delete")} aria-label={t("designOption.option.delete")} disabled={!handlers.onDeleteDesignOption} onClick={() => handlers.onDeleteDesignOption?.(s.id, o.id)}>
<span className="material-symbols-outlined" aria-hidden="true">delete</span>
</button>
</div>
))}
</div>
);
})}
<div className="rm-row">
<input type="text" value={newName} placeholder={t("designOption.set.placeholder")} aria-label={t("designOption.set.new")} onChange={(e) => setNewName(e.target.value)} onKeyDown={(e) => e.key === "Enter" && add()} data-testid="rm-design-option-set-name" />
<button type="button" className="rm-add-btn" disabled={!handlers.onAddDesignOptionSet} onClick={add} data-testid="rm-design-option-set-add">
{t("designOption.set.add")}
</button>
</div>
</div>
);
}
+2
View File
@@ -31,6 +31,7 @@ export type TopBarEvents = Required<
| "onNewProjectFromComplexSample"
| "onNewProjectFromWettbewerbSample"
| "onNewProjectFromUmbauSample"
| "onNewProjectFromVariantenSample"
| "onNewProjectFromTemplate"
| "onOpenProject"
| "onSaveProject"
@@ -135,6 +136,7 @@ export function useTopBarElements(opts: {
onNewProjectFromComplexSample={ev.onNewProjectFromComplexSample}
onNewProjectFromWettbewerbSample={ev.onNewProjectFromWettbewerbSample}
onNewProjectFromUmbauSample={ev.onNewProjectFromUmbauSample}
onNewProjectFromVariantenSample={ev.onNewProjectFromVariantenSample}
onNewProjectFromTemplate={ev.onNewProjectFromTemplate}
onOpenProject={ev.onOpenProject}
onSaveProject={ev.onSaveProject}
+9 -3
View File
@@ -626,6 +626,11 @@ export function Wasm3DViewport({
const l = s.project.drawingLevels.find((x) => x.id === s.activeLevelId);
return l?.renovationFilter ? `${l.renovationFilter}\u0001${l.renovationPhase ?? ""}` : "";
});
// [272] Variantenkombination der aktiven Ebene (wie im Grundriss); ohne Wahl die Hauptvarianten (Kern).
const optKey = useStore((s) => {
const l = s.project.drawingLevels.find((x) => x.id === s.activeLevelId);
return l?.designOptions ? JSON.stringify(l.designOptions) : "";
});
const hide = useMemo<Hide3d>(() => {
const split = (k: string) => (k ? k.split("\u0001") : []);
const codes = split(hiddenKey);
@@ -633,10 +638,11 @@ export function Wasm3DViewport({
const dim = { grey: split(greyKey), lock: split(lockKey), greyFloors: split(greyFloorsKey) };
const [renovation, renovationPhase] = split(renKey);
const ren = renovation ? { renovation, ...(renovationPhase ? { renovationPhase } : {}) } : {};
return onlyIds || hiddenIds.length || floors.length || dim.grey.length || dim.lock.length || dim.greyFloors.length || renovation
? { ...toFilter3d({ only: onlyIds, hidden: hiddenIds }, codes, floors, dim), ...ren }
const opts = optKey ? { designOptions: JSON.parse(optKey) as Record<string, string> } : {};
return onlyIds || hiddenIds.length || floors.length || dim.grey.length || dim.lock.length || dim.greyFloors.length || renovation || optKey
? { ...toFilter3d({ only: onlyIds, hidden: hiddenIds }, codes, floors, dim), ...ren, ...opts }
: codes;
}, [hiddenKey, floorsKey, greyKey, greyFloorsKey, lockKey, onlyIds, hiddenIds, renKey]);
}, [hiddenKey, floorsKey, greyKey, greyFloorsKey, lockKey, onlyIds, hiddenIds, renKey, optKey]);
const hideRef = useRef(hide);
hideRef.current = hide;
// Versatz je Geschoss ([65]) für Griffe und gezogene Höhen (Modell bleibt unversetzt).