Merge [213] Kameras und Begehen im 3D
This commit is contained in:
64 files changed
+2032
-59
No files matched your search
@@ -70,16 +70,8 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC.
|
||||
- [61] Raumprogramm gegen Modell und Flächennachweis SIA 416 als Tabelle/Layout-Element ([70]); Kennzahlen (GF, GV, HNF/GF, Fassadenanteil).
|
||||
- 3D-Bilder für die Abgabe: hochaufgelöster PNG-Export (Perspektive, Axonometrie, Schatten), Sonnenstand; [205] Pausfolie.
|
||||
- [199]/[204] Plan- und App-Review-Reste im Darstellungsbereich 1:500/1:200 schliessen.
|
||||
- ○ **[211]** Rendern mit Blender/Cycles (Entscheid Maintainer 12.11.: zuerst Brücke, danach eigener Renderer [212]): Knopf/Befehl
|
||||
„Rendering…“ übergibt Modell (glTF mit Normalen/UV), Materialien (Farben, ambientCG-Texturen, Glas), Kamera der 3D-Ansicht und
|
||||
Sonnenstand/Himmel an ein installiertes Blender (`blender -b --python`, eigener Prozess, GPL bleibt getrennt), rechnet im Hintergrund
|
||||
mit Cycles (Metal auf dem Mac), zeigt Fortschritt und lädt das PNG zurück (als Bild ins Layout einsetzbar). Ohne Blender: klarer Hinweis
|
||||
mit Download-Link. · M
|
||||
- ○ **[213]** Kameras und WASD (12.11., Wunsch Maintainer): Kameras als Modell-Elemente (Name, Standpunkt, Ziel, Augenhöhe,
|
||||
Brennweite/Bildwinkel, Perspektive/Axo, Uhrzeit für Sonne), im Grundriss als Kamerasymbol mit Griffen (Standpunkt, Ziel,
|
||||
Öffnungswinkel; Klasse „Kameras“ nach [180]), Liste im Navigator; „Aus aktueller Ansicht anlegen“, „Kamera öffnen“, Rendering [211]
|
||||
wählt eine Kamera. 3D-Navigation: WASD/Pfeile laufen, Q/E hoch/runter, Maus schauen, Shift schneller (Begehen-Modus wie Archicad/Spiele),
|
||||
Augenhöhe halten; auch im nativen Mac-3D. · M
|
||||
- [211] Rendering mit Blender/Cycles (◐, Eintrag unter „Import und Export“): Belichtung/Materialien abstimmen, Kamera [213] im Dialog wählbar, Mac-Gegenprobe.
|
||||
- [213] Kameras und Begehen/WASD (◐, Eintrag unter „Grundriss“): Kopieren/Gruppen/IFC, Mac-Gegenprobe.
|
||||
- ○ **[214]** 3D-Engine optimieren (12.11., Wunsch Maintainer: „render3d hat sich sehr früh entwickelt, Leistung könnte besser sein“).
|
||||
Zuerst messen (Bildzeit, Draw-Calls, Upload-Zeit, Neu-Vernetzen je Änderung, Speicher; Musterhaus komplex + Grossgebäude
|
||||
`buildBigSampleProject` + grosser Kontext-Import), dann der Reihe nach: nur geänderte Elemente neu vernetzen/hochladen (statt ganzes
|
||||
@@ -117,6 +109,18 @@ Punktwolken/BCF-Ausbau, Windows-Paket, [C5]/[C7]/[15] Kern-Umbauten — ausser s
|
||||
|
||||
## Grundriss
|
||||
|
||||
- ◐ **[213]** Kameras und Begehen im 3D (12.11., Wunsch Maintainer; ersetzt den offenen Eintrag in „Release 1.0“). Umgesetzt: Modell `Project.cameras`
|
||||
(Rust `Camera`: Name, Geschoss, Standpunkt + Augenhöhe über Geschoss, Ziel + Zielhöhe, Bildwinkel/Brennweite, Perspektive/Axonometrie/Parallel,
|
||||
Sichthöhe, Sonnenstand als ISO-Zeit; Klasse „Kameras“ Code 92, `standards::CAMERA_CATEGORY`); Ops über die gewöhnlichen Helfer. Grundriss-Symbol im Kern
|
||||
(`plan/cameras.rs`: Gehäuse mit Objektiv, Sichtkegel bzw. Streifen, Ziel mit Blicklinie, Name; Pick-Bänder `@camera:<id>`, nur Gehäuse/Kanten/Ziel,
|
||||
nicht der ganze Kegel); Griffe im Kern (`camera.rs`/`grips.rs`: Standpunkt, Ziel, Bildwinkel bzw. Sichtbreite, `cameraGrip`/`cameraBy`);
|
||||
Objekt-Info-Abschnitt `CameraSection` (Werte, Brennweite ↔ Bildwinkel, Sonne, „Kamera öffnen“, „Aus aktueller Ansicht“, „Isometrisch“); Liste mit Anlegen/Öffnen/Löschen im
|
||||
Panel „Ausschnitte“ (`CamerasGroup`); 3D: Knopf „Kamera+“ legt aus der aktuellen Ansicht an, Doppelklick auf das Symbol im Grundriss bzw. „Kamera öffnen“ setzt die 3D-Ansicht
|
||||
exakt (Reiterwechsel, Sonnenstudie übernimmt `sunWhen`); `viewport/cameraView.ts::cameraToView(project, camera)` liefert dieselbe `ViewCamera` wie `getCamera()`
|
||||
(Anschluss für das Rendering [211]: `cameraToView` statt der Live-Ansicht). Begehen: Umschalt+F bzw. Knopf „Begehen“, darin W/A/S/D und Pfeile gehen (horizontal, Augenhöhe bleibt),
|
||||
Q/E runter/hoch, Umschalt ×4, Alt ×0.25, Maus (links oder rechts) schaut um den Augpunkt, Esc beendet; die Tasten gelten nur im Modus (sonst kollidieren sie mit S/D/Q, [190]), pro Frame mit
|
||||
gekapptem Zeitschritt (`viewport/walk.ts`). Beispiel: Kamera „Südost“ im Musterhaus komplex. Offen: nicht in der Tauri-App geprüft (3D headless leer, Kamera-Brücke nur per Zustand); nativer Mac-3D ohne
|
||||
Begehen/Kameras (`native.rs` ist Linux/winit); Kameras fehlen in Verschieben/Kopieren/Gruppen/IFC/Zwischenablage; Stil „Sonne am Tag“ (Datum/Uhrzeit-Dialog) und Animation entlang mehrerer Kameras. · M
|
||||
- ◐ **[205]** Pausfolie/Referenz wie Archicad „Trace & Reference“ (12.11., Wunsch Maintainer). Umgesetzt (12.11.): **Entscheid:** die Pausfolie ist UI-Zustand je Reiter (`state.trace`, Typ `TraceReference` aus dem Rust-Modell; mit dem Reiter in `uiState.viewTabs` und im Ausschnitt `ViewSnapshot.trace` gespeichert, kein Op, kein Undo, nie im Druck/Export). Die Quelle rechnen die bestehenden Abfragen (`planDomains`, `sectionPlan` + eigene 2D-Elemente, `elevationPlan`), die TS-Fassade `plan/trace.ts` schickt sie als Teil-Abfragen an die neue Kern-Abfrage `tracePlan` (`plan/trace.rs`): Ausrichtung nach Koordinatenraum (Schnitt/Ansicht hinter Grundriss an der Schnittlinie aufgeklappt, u längs der Linie, jenseits des Grundrisses; Grundriss hinter Schnitt wie bisher die Unterlage `underlay.rs`; gleicher Raum deckungsgleich, Schnitt hinter Schnitt höhengleich), dann Verschieben/Drehen (Starrkörper), Auswahl-Ids weg, Farbe nach Deckkraft zur Papierfarbe aufgehellt in den Primitiven selbst — alle drei Zeichenwege (WebGPU, Metal, SVG) ohne eigene Logik; `withTrace` legt sie unter/über den Plan. **Vereinheitlicht:** die [203]-Überlagerung anderer Geschosse über den Modus „Andere grau“ entfällt im Grundriss (Modus wirkt nur noch im 3D), die Grundriss-Unterlage `DrawingLevel.planUnderlayId` (Objekt-Info Schnittlinie, Abfrage `planUnderlay`) entfällt, Schnitt/Ansicht hinter freien Zeichnungen über das Auge entfällt — alles nur noch als Pausfolie; Auge/Modus komponiert weiter Geschoss ↔ freie Zeichnung. **Bedienung:** Navigator-Kontextmenü „Als Pausfolie zeigen“, Statusleiste „Pausfolie“ (Ein/Aus, ▴: Quelle, Farbe, Deckkraft, über/unter, Versatz, Drehung, Verschieben/Drehen per Klick, Zurücksetzen), Kürzel Cmd/Ctrl+Shift+T (rebindbar, Menü Ansicht), Befehle `tracemove`/`tracerotate`. Tests: Rust `plan::trace` (9), vitest `plan/trace.test.ts`, `state/traceRef.test.ts`, `levelTrace203` angepasst, e2e `trace205`. Offen: Fang auf der Pause nur im Schnitt/in der Ansicht (im Grundriss nicht); Blatt/Layout als Quelle und Pause im Layout; nicht in der Tauri-App/auf dem Mac (Metal) geprüft. Opus. · L
|
||||
- ◐ **[182]** Tabs/Ansichten wie Archicad (11.11., Wunsch Maintainer). Umgesetzt: Reiter-Arten Grundriss · 3D · Schnitt · Ansicht ·
|
||||
2D-Zeichnung/Layout werden nie gemischt (`navigateToLevel`/`switchViewKind` in `state/viewTabs.ts`, Anwendung in
|
||||
|
||||
+1
-1
@@ -834,7 +834,7 @@ Reines Verschieben, ohne Verhaltensänderung (gleiche Abhängigkeitslisten, glei
|
||||
|---|---|
|
||||
| `src/views/plan/PlanView.tsx` (3902 Zeilen) | rund 1400 Zeilen: Props, Zustand, Hook-Aufrufe, SVG-Ebene. Typen und Konstanten in `planView/types.ts`, `planView/constants.ts`; Hooks `usePlanEngine`, `usePlanCoords`, `usePlanPicking`, `usePlanPointer`, `usePlanPickCycle`, `usePlanZoomInput`, `usePlanHighlights` in `planView/` (je 130 bis 680 Zeilen) |
|
||||
| `src-tauri/core/src/plan/elevation.rs` (3226 Zeilen) | Ordner `plan/elevation/`: `mod.rs` (Konstanten, Orchestrierung, Abfrage), `face`, `cull`, `collect`, `mesh_cull`, `openings`, `silhouette`, `patterns`, `tests`; `fascia_quads()` und `corner_shifts()` bleiben über `plan::elevation::` erreichbar |
|
||||
| `src/panels/ObjectInfoPanel.tsx` (2847 Zeilen) | rund 370 Zeilen; Abschnitte je Element-Art in `src/panels/objectInfo/` (`WallSection`, `CeilingSection`, `RoofSections`, `OpeningSections`, `StairSection`, `RoomSection`, `SolidSections`, `SectionLineSection`, `RefSections`, `TreeSection`, `fields`, `InfoBlocks`) |
|
||||
| `src/panels/ObjectInfoPanel.tsx` (2847 Zeilen) | rund 370 Zeilen; Abschnitte je Element-Art in `src/panels/objectInfo/` (`WallSection`, `CeilingSection`, `RoofSections`, `OpeningSections`, `StairSection`, `RoomSection`, `SolidSections`, `SectionLineSection`, `RefSections`, `TreeSection`, `CameraSection`, `fields`, `InfoBlocks`) |
|
||||
|
||||
Zwei Stellen in `PlanView` wurden dafür umgestellt, weil ein Hook nur zusammenhängende Anweisungen aufnimmt: der Aufräum-Effekt für den
|
||||
ausstehenden Pan steht jetzt bei `panRaf` (in `usePlanPointer`), die Hover-Teilpunkte (Zustand, Funktionen, zwei Effekte) bei den
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
// [213] Kameras: im Musterhaus komplex liegt die Kamera „Südost" — ihr Symbol (Gehäuse, Sichtkegel, Ziel) steht im
|
||||
// EG-Grundriss, die Kamera lässt sich in der Liste wählen (Objekt-Info), „Kamera öffnen" wechselt in den 3D-Reiter.
|
||||
// (Dass die Klasse „Kameras" das Symbol ausblendet, prüft der Kern-Test `plan::cameras`.) Aus der 3D-Ansicht lässt sich eine neue Kamera anlegen.
|
||||
// WebGPU ist headless oft leer: ist der 3D-Viewport nicht bereit, wird auf Reiter und Hinweis geprüft statt auf die Kamera.
|
||||
// Eigener Port: E2E_PORT=5191 npx playwright test e2e/camera.spec.ts
|
||||
import type { Page } from "@playwright/test";
|
||||
import type {} from "../src/state/testHooks"; // Typ von window.__dossierTest
|
||||
import { discardIfAsked, drawingTab, expect, fileMenu, openTab, showSnapshot, test } from "./app";
|
||||
|
||||
async function openKomplex(page: Page): Promise<void> {
|
||||
await page.goto("/?dossierTest");
|
||||
await page.getByRole("button", { name: /Neues Projekt/ }).first().click();
|
||||
await expect(page.getByRole("group", { name: "Befehlszeile" })).toBeVisible();
|
||||
await fileMenu(page, /Musterhaus \(komplex\)/);
|
||||
await discardIfAsked(page);
|
||||
await expect(page.locator(".project-name")).toHaveText("Musterhaus komplex", { timeout: 30_000 });
|
||||
await showSnapshot(page, "EG 1:100");
|
||||
await expect(page.locator("svg.plan-svg").first()).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
test("Kamera im Grundriss sehen, wählen, öffnen", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await openKomplex(page);
|
||||
|
||||
// Symbol im EG-Grundriss (Sichtkegel-Linien der Klasse „camera-cone").
|
||||
await expect.poll(() => page.evaluate(() => window.__dossierTest?.planLines("camera-cone") ?? 0), { timeout: 20_000 }).toBeGreaterThan(0);
|
||||
|
||||
// Kameraliste im Panel „Ausschnitte"; Klick wählt, die Objekt-Info zeigt die Werte.
|
||||
await openTab(page, "Ausschnitte");
|
||||
const row = page.getByTestId("camera-row-kamera-suedost");
|
||||
await expect(row).toContainText("Südost");
|
||||
await row.click();
|
||||
await openTab(page, "Objekt-Info");
|
||||
const section = page.getByTestId("camera-section");
|
||||
await expect(section).toBeVisible();
|
||||
await expect(section.getByTestId("camera-name")).toHaveValue("Südost");
|
||||
|
||||
// Name ändern und rückgängig machen.
|
||||
await section.getByTestId("camera-name").fill("Abendblick");
|
||||
await section.getByTestId("camera-name").press("Enter");
|
||||
await expect(section.getByTestId("camera-name")).toHaveValue("Abendblick");
|
||||
await page.locator("body").click({ position: { x: 5, y: 5 } });
|
||||
await page.keyboard.press("ControlOrMeta+z");
|
||||
await expect(section.getByTestId("camera-name")).toHaveValue("Südost");
|
||||
|
||||
// Kamera öffnen → 3D-Reiter.
|
||||
await section.getByTestId("camera-open").click();
|
||||
await expect(drawingTab(page, "3D · Erdgeschoss")).toHaveAttribute("aria-selected", "true", { timeout: 20_000 });
|
||||
const live = await page
|
||||
.waitForFunction(() => (window as unknown as { __dossierCamera?: unknown }).__dossierCamera !== undefined, undefined, { timeout: 8_000 })
|
||||
.then(() => true, () => false);
|
||||
if (live) {
|
||||
// Der Viewport ist bereit: die Ansicht sitzt exakt auf der Kamera (Standpunkt 17 / −3, Augenhöhe 1.6 über OK EG).
|
||||
await expect
|
||||
.poll(
|
||||
async () =>
|
||||
page.evaluate(() => {
|
||||
const c = (window as unknown as { __dossierCamera: { getCamera: () => { position: number[]; kind: string } | null } }).__dossierCamera.getCamera();
|
||||
return c ? [...c.position.map((v) => Math.round(v * 100) / 100), c.kind] : null;
|
||||
}),
|
||||
{ timeout: 10_000 },
|
||||
)
|
||||
.toEqual([17, -3, expect.any(Number), "perspective"]);
|
||||
}
|
||||
});
|
||||
|
||||
test("Kamera aus der 3D-Ansicht anlegen", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await openKomplex(page);
|
||||
// In den 3D-Reiter und dort „Kamera aus aktueller Ansicht anlegen" (Knopf oben rechts).
|
||||
await showSnapshot(page, "Axonometrie Südost");
|
||||
const create = page.getByTestId("camera-create-3d");
|
||||
await expect(create).toBeVisible({ timeout: 30_000 });
|
||||
await create.click();
|
||||
const ready = await page
|
||||
.waitForFunction(() => (window as unknown as { __dossierCamera?: unknown }).__dossierCamera !== undefined, undefined, { timeout: 5_000 })
|
||||
.then(() => true, () => false);
|
||||
await openTab(page, "Ausschnitte");
|
||||
if (ready) {
|
||||
await expect(page.locator("[data-testid^=camera-row-]")).toHaveCount(2);
|
||||
} else {
|
||||
// Ohne WebGPU gibt es keine Kamera zum Lesen: der Hinweis sagt es, es entsteht nichts.
|
||||
await expect(page.locator("[data-testid^=camera-row-]")).toHaveCount(1);
|
||||
}
|
||||
|
||||
// Zurück in den Grundriss: das Symbol ist da.
|
||||
await showSnapshot(page, "EG 1:100");
|
||||
await expect.poll(() => page.evaluate(() => window.__dossierTest?.planLines("camera-cone") ?? 0), { timeout: 20_000 }).toBeGreaterThan(0);
|
||||
});
|
||||
@@ -63,7 +63,7 @@ Neues Modul: `<modul>.rs` und `mod` in `lib.rs`, Bindungen in `web/<modul>.rs` u
|
||||
| `mesh_section.rs`, `mesh_view.rs`, `mesh_repair.rs` | Ebenenschnitt beliebiger Netze; importierte Netze; Netz-Reparatur |
|
||||
| `voids.rs` | Abzugskörper in Grundriss und Schnitt |
|
||||
| `surface_pattern.rs` | Ansichtsschraffur (Lattung, Verband, Schindeln …) |
|
||||
| `grid.rs`, `tree.rs`, `auto_dimensions.rs` | Achsraster, Bäume, automatische Aussenbemassung |
|
||||
| `grid.rs`, `tree.rs`, `camera.rs`, `auto_dimensions.rs` | Achsraster, Bäume, Kameras (Auflösung, Griffe, Brennweite), automatische Aussenbemassung |
|
||||
|
||||
## Befehle, Griffe, Auswahl, Verwaltung
|
||||
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
//! [213] Kameras (`Project.cameras`): Auflösung zu Augpunkt, Ziel und Blickrichtung in Modell-Koordinaten
|
||||
//! (z oben, Meter), Brennweite ↔ Bildwinkel. Das Planzeichen entsteht in `plan/cameras.rs`; die TS-Seite
|
||||
//! (`src/model/cameraView.ts`) liefert daraus die Ansicht der 3D-Kamera (`cameraToView`).
|
||||
|
||||
use crate::jsnum;
|
||||
use crate::model::*;
|
||||
|
||||
/// Präfix der Pick-Id im Feld `contextObjectId` der Plan-Primitive (`@` = keine Kontext-Element-Id).
|
||||
pub const CAMERA_PICK_PREFIX: &str = "@camera:";
|
||||
/// Vorgabe der Augenhöhe über dem Geschoss (m) und des vertikalen Bildwinkels (Grad; wie `FOV_Y` des 3D).
|
||||
pub const DEFAULT_EYE_HEIGHT: f64 = 1.6;
|
||||
pub const DEFAULT_FOV_DEG: f64 = 50.0;
|
||||
/// Sichthöhe bei Axonometrie/Parallel ohne Angabe (m).
|
||||
pub const DEFAULT_ORTHO_HEIGHT: f64 = 10.0;
|
||||
/// Bildverhältnis für den Sichtkegel im Grundriss (Breite/Höhe).
|
||||
pub const ASPECT: f64 = 16.0 / 9.0;
|
||||
/// Sensorhöhe für die Kleinbild-Brennweite (mm).
|
||||
pub const SENSOR_HEIGHT_MM: f64 = 24.0;
|
||||
/// Bildwinkel-Grenzen (Grad), wie `camera3dFromViewCamera`.
|
||||
pub const MIN_FOV_DEG: f64 = 5.0;
|
||||
pub const MAX_FOV_DEG: f64 = 120.0;
|
||||
|
||||
/// Aufgelöste Kamera in Modell-Koordinaten.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct CameraGeom {
|
||||
pub eye: [f64; 3],
|
||||
pub target: [f64; 3],
|
||||
/// Grundriss-Richtung (Bogenmass, 0 = +x), aus Standpunkt → Ziel.
|
||||
pub yaw: f64,
|
||||
/// Abstand Standpunkt → Ziel im Grundriss (m, ≥ 0).
|
||||
pub plan_dist: f64,
|
||||
pub fov_deg: f64,
|
||||
pub perspective: bool,
|
||||
pub ortho_height: f64,
|
||||
}
|
||||
|
||||
/// Brennweite (mm, Kleinbild, 24 mm Sensorhöhe) zum vertikalen Bildwinkel.
|
||||
pub fn focal_mm(fov_deg: f64) -> f64 {
|
||||
SENSOR_HEIGHT_MM / 2.0 / jsnum::tan(fov_deg.to_radians() / 2.0)
|
||||
}
|
||||
|
||||
/// Vertikaler Bildwinkel (Grad) zur Brennweite (mm).
|
||||
pub fn fov_deg_from_focal(mm: f64) -> f64 {
|
||||
2.0 * jsnum::atan(SENSOR_HEIGHT_MM / 2.0 / mm).to_degrees()
|
||||
}
|
||||
|
||||
/// Bildwinkel in den zulässigen Bereich (Vorgabe bei NaN/≤ 0).
|
||||
pub fn clamp_fov(fov_deg: f64) -> f64 {
|
||||
if fov_deg.is_finite() && fov_deg > 0.0 {
|
||||
fov_deg.clamp(MIN_FOV_DEG, MAX_FOV_DEG)
|
||||
} else {
|
||||
DEFAULT_FOV_DEG
|
||||
}
|
||||
}
|
||||
|
||||
impl CameraGeom {
|
||||
/// Auflösung gegen das Projekt; `None` bei unbrauchbarer Lage (NaN).
|
||||
pub fn of(p: &Project, c: &Camera) -> Option<CameraGeom> {
|
||||
let floor_z = p.floor(&c.floor_id).and_then(|l| l.base_elevation).filter(|z| z.is_finite()).unwrap_or(0.0);
|
||||
Self::at(c, floor_z)
|
||||
}
|
||||
|
||||
/// Wie [`CameraGeom::of`] mit gegebener Höhe der Geschoss-OK.
|
||||
pub fn at(c: &Camera, floor_z: f64) -> Option<CameraGeom> {
|
||||
let eye_h = if c.eye_height.is_finite() { c.eye_height } else { DEFAULT_EYE_HEIGHT };
|
||||
let (px, py, tx, ty, tz) = (c.position.x, c.position.y, c.target.x, c.target.y, c.target_height);
|
||||
if ![px, py, tx, ty, tz].iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let (dx, dy) = (tx - px, ty - py);
|
||||
let plan_dist = dx.hypot(dy);
|
||||
let eye_z = floor_z + eye_h;
|
||||
Some(CameraGeom {
|
||||
eye: [px, py, eye_z],
|
||||
target: [tx, ty, tz],
|
||||
yaw: if plan_dist > 1e-9 { jsnum::atan2(dy, dx) } else { 0.0 },
|
||||
plan_dist,
|
||||
fov_deg: clamp_fov(c.fov_deg),
|
||||
perspective: c.projection == CameraProjection::Perspective || c.projection == CameraProjection::Unknown,
|
||||
ortho_height: c.ortho_height.filter(|h| h.is_finite() && *h > 0.0).unwrap_or(DEFAULT_ORTHO_HEIGHT),
|
||||
})
|
||||
}
|
||||
|
||||
/// Blickrichtung (normiert); `None`, wenn Standpunkt und Ziel zusammenfallen.
|
||||
pub fn direction(&self) -> Option<[f64; 3]> {
|
||||
let d = [self.target[0] - self.eye[0], self.target[1] - self.eye[1], self.target[2] - self.eye[2]];
|
||||
let l = d[0].hypot(d[1]).hypot(d[2]);
|
||||
(l > 1e-9).then(|| [d[0] / l, d[1] / l, d[2] / l])
|
||||
}
|
||||
}
|
||||
|
||||
/// Griffe im Grundriss (Modell-Meter) beim Massstab 1:`scale`: 0 Standpunkt, 1 Ziel, 2 rechter Rand der fernen
|
||||
/// Sichtlinie (Perspektive: Bildwinkel, Axonometrie/Parallel: Sichtbreite).
|
||||
pub fn grip_points(c: &Camera, scale: f64) -> Vec<(f64, f64)> {
|
||||
let Some(g) = CameraGeom::at(c, 0.0) else { return vec![] };
|
||||
let a = crate::plan::cameras::view_area(&g, if scale.is_finite() && scale > 0.0 { scale / 1000.0 } else { 0.1 });
|
||||
vec![(g.eye[0], g.eye[1]), (g.target[0], g.target[1]), (a[2].x, a[2].y)]
|
||||
}
|
||||
|
||||
/// Kamera nach dem Ziehen des Griffs `index` an `(x, y)`; `None` bei unbekanntem Griff oder NaN.
|
||||
/// 0 setzt den Standpunkt (Ziel bleibt), 1 das Ziel, 2 den Bildwinkel (Perspektive: aus dem Winkel zur Blickachse,
|
||||
/// 5° bis 120° vertikal) bzw. die Sichtbreite (Axonometrie/Parallel: aus dem Abstand zur Blickachse).
|
||||
pub fn grip_edit(c: &Camera, index: f64, x: f64, y: f64) -> Option<Camera> {
|
||||
if !(x.is_finite() && y.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let g = CameraGeom::at(c, 0.0)?;
|
||||
let mut n = c.clone();
|
||||
match index {
|
||||
i if i == 0.0 => n.position = Vec2 { x, y },
|
||||
i if i == 1.0 => n.target = Vec2 { x, y },
|
||||
i if i == 2.0 => {
|
||||
let (dx, dy) = (x - g.eye[0], y - g.eye[1]);
|
||||
if g.perspective {
|
||||
if dx.hypot(dy) < 1e-9 {
|
||||
return None;
|
||||
}
|
||||
let mut a = jsnum::atan2(dy, dx) - g.yaw;
|
||||
a = jsnum::atan2(jsnum::sin(a), jsnum::cos(a)).abs();
|
||||
let h = a.clamp(0.5_f64.to_radians(), 75.0_f64.to_radians());
|
||||
n.fov_deg = clamp_fov((2.0 * jsnum::atan(jsnum::tan(h) / ASPECT)).to_degrees());
|
||||
} else {
|
||||
let side = (-jsnum::sin(g.yaw)) * dx + jsnum::cos(g.yaw) * dy;
|
||||
n.ortho_height = Some((2.0 * side.abs() / ASPECT).max(0.1));
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
/// Kamera um `(dx, dy)` verschoben (Standpunkt und Ziel).
|
||||
pub fn moved(c: &Camera, dx: f64, dy: f64) -> Option<Camera> {
|
||||
if !(dx.is_finite() && dy.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let mut n = c.clone();
|
||||
n.position = Vec2 { x: c.position.x + dx, y: c.position.y + dy };
|
||||
n.target = Vec2 { x: c.target.x + dx, y: c.target.y + dy };
|
||||
Some(n)
|
||||
}
|
||||
|
||||
/// Bezeichnung (Objekt-Info, Beschriftung): Name, sonst „Kamera".
|
||||
pub fn label(c: &Camera) -> String {
|
||||
let n = c.name.trim();
|
||||
if n.is_empty() { "Kamera".to_string() } else { n.to_string() }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn camera(json: serde_json::Value) -> Camera {
|
||||
let mut base = serde_json::json!({
|
||||
"id": "k1", "type": "camera", "name": "Süd", "floorId": "eg", "categoryCode": "92", "position": {"x": 1, "y": 2},
|
||||
"eyeHeight": 1.6, "target": {"x": 1, "y": 12}, "targetHeight": 1.6, "fovDeg": 50, "projection": "perspective"
|
||||
});
|
||||
for (k, v) in json.as_object().unwrap() {
|
||||
base[k] = v.clone();
|
||||
}
|
||||
serde_json::from_value(base).unwrap()
|
||||
}
|
||||
|
||||
fn project() -> Project {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "p", "name": "p", "walls": [], "layers": [],
|
||||
"drawingLevels": [{"id": "eg", "name": "EG", "kind": "floor", "visible": true, "locked": false, "baseElevation": 3.0}]
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn augenhoehe_ueber_geschoss_und_richtung() {
|
||||
let g = CameraGeom::of(&project(), &camera(serde_json::json!({}))).unwrap();
|
||||
assert_eq!(g.eye, [1.0, 2.0, 4.6]);
|
||||
assert!((g.yaw - std::f64::consts::FRAC_PI_2).abs() < 1e-12);
|
||||
assert!((g.plan_dist - 10.0).abs() < 1e-12);
|
||||
assert!(g.perspective);
|
||||
let d = g.direction().unwrap();
|
||||
assert!(d[1] > 0.9 && d[2] < 0.0, "Ziel liegt tiefer als das Auge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ohne_geschoss_null_und_nan_verworfen() {
|
||||
let g = CameraGeom::of(&Project::default(), &camera(serde_json::json!({"projection": "parallel", "orthoHeight": 6}))).unwrap();
|
||||
assert_eq!(g.eye[2], 1.6);
|
||||
assert!(!g.perspective);
|
||||
assert_eq!(g.ortho_height, 6.0);
|
||||
let mut c = camera(serde_json::json!({}));
|
||||
c.position.x = f64::NAN;
|
||||
assert!(CameraGeom::of(&project(), &c).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brennweite_und_bildwinkel_umkehrbar() {
|
||||
assert!((focal_mm(fov_deg_from_focal(35.0)) - 35.0).abs() < 1e-9);
|
||||
// 24 mm Sensorhöhe, 35 mm Brennweite: rund 37.8°.
|
||||
assert!((fov_deg_from_focal(35.0) - 37.85).abs() < 0.05);
|
||||
assert_eq!(clamp_fov(f64::NAN), DEFAULT_FOV_DEG);
|
||||
assert_eq!(clamp_fov(500.0), MAX_FOV_DEG);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn griffe_standpunkt_ziel_winkel() {
|
||||
let c = camera(serde_json::json!({}));
|
||||
let pts = grip_points(&c, 100.0);
|
||||
assert_eq!(pts.len(), 3);
|
||||
assert_eq!(pts[0], (1.0, 2.0));
|
||||
assert_eq!(pts[1], (1.0, 12.0));
|
||||
// Ziehen des Winkel-Griffs auf den heutigen Punkt ändert den Bildwinkel nicht.
|
||||
let same = grip_edit(&c, 2.0, pts[2].0, pts[2].1).unwrap();
|
||||
assert!((same.fov_deg - 50.0).abs() < 1e-9, "{}", same.fov_deg);
|
||||
// Weiter öffnen: 45° zur Blickachse ergibt einen grösseren Bildwinkel.
|
||||
let wide = grip_edit(&c, 2.0, 1.0 + 10.0, 2.0 + 10.0).unwrap();
|
||||
assert!(wide.fov_deg > 50.0);
|
||||
assert_eq!(grip_edit(&c, 0.0, 5.0, 6.0).unwrap().position, Vec2 { x: 5.0, y: 6.0 });
|
||||
assert_eq!(grip_edit(&c, 1.0, 5.0, 6.0).unwrap().target, Vec2 { x: 5.0, y: 6.0 });
|
||||
assert!(grip_edit(&c, 7.0, 0.0, 0.0).is_none());
|
||||
assert!(grip_edit(&c, 0.0, f64::NAN, 0.0).is_none());
|
||||
// Parallelprojektion: Sichtbreite aus dem Abstand zur Achse.
|
||||
let par = camera(serde_json::json!({"projection": "parallel", "orthoHeight": 4}));
|
||||
let w = grip_points(&par, 100.0)[2];
|
||||
let edit = grip_edit(&par, 2.0, w.0 - 1.0, w.1).unwrap();
|
||||
assert!((edit.ortho_height.unwrap() - 2.0 * (4.0 * ASPECT / 2.0 + 1.0) / ASPECT).abs() < 1e-9);
|
||||
let m = moved(&c, 1.0, -1.0).unwrap();
|
||||
assert_eq!((m.position, m.target), (Vec2 { x: 2.0, y: 1.0 }, Vec2 { x: 2.0, y: 11.0 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modell_aus_json_verlustfrei() {
|
||||
let c = camera(serde_json::json!({"sunWhen": "2026-06-21T08:00:00Z", "orthoHeight": 8}));
|
||||
let back: Camera = serde_json::from_value(serde_json::to_value(&c).unwrap()).unwrap();
|
||||
assert_eq!(back, c);
|
||||
assert_eq!(label(&Camera::default()), "Kamera");
|
||||
}
|
||||
}
|
||||
@@ -118,6 +118,10 @@ pub fn translate_project(p: &Project, dx: f64, dy: f64) -> Project {
|
||||
for t in out.trees.iter_mut().flatten() {
|
||||
t.position = shift(t.position, dx, dy);
|
||||
}
|
||||
for c in out.cameras.iter_mut().flatten() {
|
||||
c.position = shift(c.position, dx, dy);
|
||||
c.target = shift(c.target, dx, dy);
|
||||
}
|
||||
if let Some(r) = &mut out.site_rules {
|
||||
shift_all(&mut r.parcel, dx, dy);
|
||||
for l in r.building_lines.iter_mut().flatten() {
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
/// Projekt-Listen, die verschoben werden (jedes Element hat eine `id`), in Op-Reihenfolge.
|
||||
pub const TRANSLATED_LISTS: [&str; 11] = ["walls", "ceilings", "roofs", "stairs", "rooms", "columns", "extrudedSolids", "drawings2d", "context", "drawingLevels", "trees"];
|
||||
pub const TRANSLATED_LISTS: [&str; 12] = ["walls", "ceilings", "roofs", "stairs", "rooms", "columns", "extrudedSolids", "drawings2d", "context", "drawingLevels", "trees", "cameras"];
|
||||
|
||||
fn shift(p: &Value, dx: f64, dy: f64) -> Value {
|
||||
let c = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(f64::NAN);
|
||||
@@ -164,6 +164,7 @@ fn shift_element(key: &str, e: &Value, dx: f64, dy: f64) -> (Value, bool) {
|
||||
}
|
||||
"columns" => shift_pts_fields(&mut m, &["position"], dx, dy, &[]),
|
||||
"trees" => shift_pts_fields(&mut m, &["position"], dx, dy, &[]),
|
||||
"cameras" => shift_pts_fields(&mut m, &["position", "target"], dx, dy, &[]),
|
||||
"extrudedSolids" => {
|
||||
shift_pts_fields(&mut m, &[], dx, dy, &["points"]);
|
||||
let c = if truthy(e.get("circle")) {
|
||||
|
||||
@@ -282,6 +282,19 @@ pub fn run(lk: &Lookup, req: &Request) -> Result<GripResult, String> {
|
||||
.into()
|
||||
}
|
||||
}
|
||||
// [213] Kamera: Griff 0 Standpunkt, 1 Ziel, 2 Bildwinkel/Sichtbreite; `cameraBy` verschiebt Standpunkt und Ziel.
|
||||
"cameraGrip" | "cameraBy" => {
|
||||
let (index, (x, y), (dx, dy)) = (r.n("index"), r.p("pt"), r.p("delta"));
|
||||
patch("cameras", r.s("id"), &|e| {
|
||||
if truthy(field(e, "locked")) {
|
||||
return None;
|
||||
}
|
||||
let cam: crate::model::Camera = serde_json::from_value(e.clone()).ok()?;
|
||||
let next = if op == "cameraGrip" { crate::camera::grip_edit(&cam, index, x, y)? } else { crate::camera::moved(&cam, dx, dy)? };
|
||||
serde_json::to_value(next).ok()
|
||||
})
|
||||
.into()
|
||||
}
|
||||
"ceilingGrip" | "roomGrip" => {
|
||||
let (coll, field) = if op == "ceilingGrip" { ("ceilings", "outline") } else { ("rooms", "boundary") };
|
||||
let (index, (x, y)) = (r.n("index"), r.p("pt"));
|
||||
|
||||
@@ -20,6 +20,7 @@ pub mod roof_parapet;
|
||||
pub mod flat_read;
|
||||
pub mod sun;
|
||||
pub mod tree;
|
||||
pub mod camera;
|
||||
pub mod site_rules;
|
||||
pub mod auto_dimensions;
|
||||
pub mod kennzahlen;
|
||||
|
||||
@@ -4878,6 +4878,71 @@ pub struct Tree {
|
||||
pub extra: Extra,
|
||||
}
|
||||
|
||||
/// Projektion einer Kamera ([213]): Perspektive, Axonometrie (Parallelprojektion mit schrägem Blick, z. B.
|
||||
/// Isometrie) oder Parallelprojektion (frei ausgerichtet). Axonometrie und Parallel zeichnen im 3D orthografisch.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, TS)]
|
||||
pub enum CameraProjection {
|
||||
#[default]
|
||||
#[serde(rename = "perspective")]
|
||||
Perspective,
|
||||
#[serde(rename = "axonometric")]
|
||||
Axonometric,
|
||||
#[serde(rename = "parallel")]
|
||||
Parallel,
|
||||
#[serde(other)]
|
||||
#[ts(skip)]
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Eine Kamera ([213]) — gespeicherter Standpunkt für die 3D-Ansicht (und das Rendering): Standpunkt im
|
||||
/// Grundriss mit Augenhöhe über dem Geschoss, Ziel (Grundriss und absolute Höhe), Bildwinkel, Projektion
|
||||
/// und optional Datum/Uhrzeit für den Sonnenstand. Im Grundriss als Symbol mit Sichtkegel auf der Klasse
|
||||
/// „Kameras" (Vorgabe "92"); „Kamera öffnen" setzt die 3D-Ansicht exakt.
|
||||
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
|
||||
#[serde(default)]
|
||||
pub struct Camera {
|
||||
pub id: String,
|
||||
#[ts(type = "\"camera\"")]
|
||||
pub r#type: String,
|
||||
pub name: String,
|
||||
/// Geschoss, auf dem das Symbol im Grundriss steht und auf das sich die Augenhöhe bezieht.
|
||||
#[serde(rename = "floorId")]
|
||||
pub floor_id: String,
|
||||
/// Klasse (Ebene), Vorgabe "92" (Kameras).
|
||||
#[serde(rename = "categoryCode")]
|
||||
pub category_code: String,
|
||||
/// Objekt-Sperre, analog `Wall.locked`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub locked: Option<bool>,
|
||||
/// Standpunkt im Grundriss (Meter).
|
||||
pub position: Vec2,
|
||||
/// Augenhöhe über OK Fertigboden des Geschosses (m).
|
||||
#[serde(rename = "eyeHeight")]
|
||||
pub eye_height: f64,
|
||||
/// Ziel im Grundriss (Meter); der Abstand Standpunkt–Ziel ist die Länge des Sichtkegels.
|
||||
pub target: Vec2,
|
||||
/// Höhe des Ziels (m, absolut, z des Modells).
|
||||
#[serde(rename = "targetHeight")]
|
||||
pub target_height: f64,
|
||||
/// Vertikaler Bildwinkel (Grad, perspektivisch). Die Kleinbild-Brennweite folgt daraus (24-mm-Sensorhöhe).
|
||||
#[serde(rename = "fovDeg")]
|
||||
pub fov_deg: f64,
|
||||
pub projection: CameraProjection,
|
||||
/// Sichthöhe in Metern (volle Bildhöhe) bei Axonometrie/Parallel; fehlt = 10 m.
|
||||
#[serde(rename = "orthoHeight", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub ortho_height: Option<f64>,
|
||||
/// Zeitpunkt für den Sonnenstand (ISO-8601 in UTC wie `SunStudy.when`); „Kamera öffnen" setzt ihn in der
|
||||
/// Sonnenstudie. Fehlt er, bleibt die Sonne der Studie.
|
||||
#[serde(rename = "sunWhen", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub sun_when: Option<String>,
|
||||
#[serde(flatten)]
|
||||
#[ts(skip)]
|
||||
pub extra: Extra,
|
||||
}
|
||||
|
||||
/// Gruppe (Vectorworks-artig) — reine Mitgliedschaft je Elementart, siehe
|
||||
/// {@link Project.groups}. Alle ID-Listen sind additiv; ein Element gehört
|
||||
/// NIE zu mehr als einer Gruppe auf derselben Ebene (das Werkzeug/der Befehl
|
||||
@@ -5943,6 +6008,11 @@ pub struct Project {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub trees: Option<Vec<Tree>>,
|
||||
/// Kameras ([213]) — gespeicherte Standpunkte für 3D-Ansicht und Rendering, siehe {@link Camera}. Optional
|
||||
/// (Default: leer behandeln).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub cameras: Option<Vec<Camera>>,
|
||||
/// Gruppen (Vectorworks-artig: Cmd+G fasst die Auswahl zu einer Einheit
|
||||
/// zusammen; Doppelklick betritt die Gruppe zum Bearbeiten, alles andere
|
||||
/// wird dabei gedimmt/gesperrt — s. `state/useGroupState.ts`). Eine Gruppe
|
||||
|
||||
@@ -37,6 +37,7 @@ impl Project {
|
||||
"extrudedSolids" => put_opt(&mut self.extruded_solids, i, v),
|
||||
"columns" => put_opt(&mut self.columns, i, v),
|
||||
"trees" => put_opt(&mut self.trees, i, v),
|
||||
"cameras" => put_opt(&mut self.cameras, i, v),
|
||||
"groups" => put_opt(&mut self.groups, i, v),
|
||||
"layouts" => put_opt(&mut self.layouts, i, v),
|
||||
_ => Ok(false),
|
||||
|
||||
@@ -26,6 +26,7 @@ Herkunft, kein Wegweiser.
|
||||
| `floor_finish.rs` | Bodenbelag-Muster nach Massstab |
|
||||
| `model_view.rs` | Modelldarstellung ([173]): Optionen je Bauteilart über dem Detailgrad, Rangfolge Element > Typ > Stufe > Basis |
|
||||
| `trees.rs` | Bäume in Grundriss, Schnitt und Ansicht |
|
||||
| `cameras.rs` | [213] Kameras im Grundriss: Gehäuse, Sichtkegel, Ziel, Name, Pick-Bänder (Klasse „Kameras“) |
|
||||
| `stamp_place.rs` | Hindernisse für die Lage der Raumstempel |
|
||||
| `view_range.rs` | Ansichtsbereich: Schnitthöhe, Ober- und Unterkante der Sicht |
|
||||
| `extras.rs` | Zutaten: Schatten und Baurecht, Abzugskörper, Strichstärken nach Massstab, Schwarz-Weiss, Ausmass |
|
||||
|
||||
@@ -30,6 +30,7 @@ pub const NOT_FOR_DRAWINGS: &[&str] = &[
|
||||
"rooms",
|
||||
"columns",
|
||||
"trees",
|
||||
"cameras",
|
||||
"extrudedSolids",
|
||||
// [157] `context` lesen die Zeichnungen: die Aussenbemassung rückt hinter die sichtbare Baugrube.
|
||||
"groups",
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
//! [213] Kameras im Grundriss: Kamerakörper (Gehäuse mit Objektiv) am Standpunkt, Sichtkegel mit dem
|
||||
//! horizontalen Öffnungswinkel (Perspektive) bzw. parallele Sichtgrenzen (Axonometrie/Parallel), Ziel als
|
||||
//! Kreuz mit gestrichelter Blicklinie, Name als Beschriftung. Grösse in fester Papiergrösse (unabhängig vom
|
||||
//! Massstab). Alles liegt auf der Klasse der Kamera (Vorgabe „92", `standards::CAMERA_CATEGORY`); fehlt die
|
||||
//! Klasse im Projekt, bleibt das Symbol sichtbar (wie die übrige abgeleitete Darstellung, [180]).
|
||||
//! Pick: unsichtbare Fläche (Körper + Kegel) mit `contextObjectId = "@camera:<id>"`.
|
||||
|
||||
use super::domains::Ctx;
|
||||
use super::prim::Primitive;
|
||||
use super::style::MONO_INK;
|
||||
use super::trees::{line, poly};
|
||||
use crate::camera::{CameraGeom, CAMERA_PICK_PREFIX};
|
||||
use crate::jsnum;
|
||||
use crate::model::*;
|
||||
|
||||
const BODY_MM: f64 = 0.25;
|
||||
const CONE_MM: f64 = 0.18;
|
||||
const AIM_MM: f64 = 0.13;
|
||||
const AIM_DASH: [f64; 2] = [1.5, 1.0];
|
||||
/// Gehäuse: Länge entlang der Blickrichtung und Breite (Papier-mm), Objektiv davor.
|
||||
const BODY_LEN: f64 = 4.0;
|
||||
const BODY_WID: f64 = 3.2;
|
||||
const LENS_LEN: f64 = 1.6;
|
||||
const LENS_WID: f64 = 2.0;
|
||||
/// Zielkreuz (Halbarm, Papier-mm).
|
||||
const CROSS: f64 = 1.6;
|
||||
/// Grösster Winkel zur Achse für den Kegel (Grad), damit sehr grosse Bildwinkel keine endlosen Kanten geben.
|
||||
/// Halbe Breite der Pick-Bänder entlang der Linien (Papier-mm).
|
||||
const PICK_BAND: f64 = 1.2;
|
||||
const MAX_HALF_DEG: f64 = 75.0;
|
||||
|
||||
fn v(x: f64, y: f64) -> Vec2 {
|
||||
Vec2 { x, y }
|
||||
}
|
||||
|
||||
/// Pick-Id einer Kamera (Feld `contextObjectId`).
|
||||
pub fn pick_id(id: &str) -> String {
|
||||
format!("{CAMERA_PICK_PREFIX}{id}")
|
||||
}
|
||||
|
||||
/// Halber horizontaler Öffnungswinkel (Radiant) aus dem vertikalen Bildwinkel und dem Bildverhältnis.
|
||||
pub fn half_h_angle(fov_deg: f64) -> f64 {
|
||||
let h = jsnum::atan(jsnum::tan(fov_deg.to_radians() / 2.0) * crate::camera::ASPECT);
|
||||
h.min(MAX_HALF_DEG.to_radians())
|
||||
}
|
||||
|
||||
/// Ecken des Sichtkegels (Standpunkt, linke Ecke, rechte Ecke) bzw. des Streifens bei Parallelprojektion.
|
||||
pub fn view_area(g: &CameraGeom, mm: f64) -> Vec<Vec2> {
|
||||
let (px, py) = (g.eye[0], g.eye[1]);
|
||||
// Mindestlänge: damit auch ein Ziel unmittelbar am Standpunkt ein sichtbares Symbol gibt.
|
||||
let len = g.plan_dist.max(8.0 * mm);
|
||||
let (u, n) = ((jsnum::cos(g.yaw), jsnum::sin(g.yaw)), (-jsnum::sin(g.yaw), jsnum::cos(g.yaw)));
|
||||
if g.perspective {
|
||||
let h = half_h_angle(g.fov_deg);
|
||||
let edge = len / jsnum::cos(h);
|
||||
let at = |s: f64| v(px + edge * jsnum::cos(g.yaw + s * h), py + edge * jsnum::sin(g.yaw + s * h));
|
||||
vec![v(px, py), at(-1.0), at(1.0)]
|
||||
} else {
|
||||
// Breite = Sichthöhe × Bildverhältnis.
|
||||
let w = g.ortho_height * crate::camera::ASPECT / 2.0;
|
||||
let q = |a: f64, b: f64| v(px + u.0 * a + n.0 * b, py + u.1 * a + n.1 * b);
|
||||
vec![q(0.0, -w), q(len, -w), q(len, w), q(0.0, w)]
|
||||
}
|
||||
}
|
||||
|
||||
/// Planzeichen einer Kamera: Pick-Fläche, Sichtgrenzen, Gehäuse mit Objektiv, Blicklinie und Zielkreuz.
|
||||
pub fn camera_symbol(cam: &Camera, g: &CameraGeom, scale: f64, cat: Option<&LayerCategory>, greyed: Option<bool>) -> Vec<Primitive> {
|
||||
let mm = scale / 1000.0;
|
||||
let color = cat.map(|k| k.color.as_str()).filter(|c| !c.is_empty()).unwrap_or(MONO_INK).to_string();
|
||||
let (px, py) = (g.eye[0], g.eye[1]);
|
||||
let (cs, sn) = (jsnum::cos(g.yaw), jsnum::sin(g.yaw));
|
||||
let at = |a: f64, b: f64| v(px + (cs * a - sn * b) * mm, py + (sn * a + cs * b) * mm);
|
||||
// Gehäuse hinter dem Standpunkt, Objektiv davor: der Standpunkt liegt an der Vorderkante des Objektivs.
|
||||
let (bw, lw) = (BODY_WID / 2.0, LENS_WID / 2.0);
|
||||
let body = vec![at(-BODY_LEN - LENS_LEN, -bw), at(-LENS_LEN, -bw), at(-LENS_LEN, bw), at(-BODY_LEN - LENS_LEN, bw)];
|
||||
let lens = vec![at(-LENS_LEN, -lw), at(0.0, -lw * 1.5), at(0.0, lw * 1.5), at(-LENS_LEN, lw)];
|
||||
let area = view_area(g, mm);
|
||||
// Pick-Flächen (unsichtbar): Gehäuse mit Objektiv, Zielkreuz und schmale Bänder entlang der Sichtgrenzen und der
|
||||
// Blicklinie — nicht der ganze Kegel, sonst finge er jeden Klick auf Räume und Wände darin ab.
|
||||
let id = pick_id(&cam.id);
|
||||
let mut out = Vec::new();
|
||||
let mut pick = |pts: Vec<Vec2>| out.push(poly(pts, "none", "none", 0.0, Some(id.clone()), greyed));
|
||||
pick(vec![at(-BODY_LEN - LENS_LEN, -bw), at(0.0, -lw * 1.5), at(0.0, lw * 1.5), at(-BODY_LEN - LENS_LEN, bw)]);
|
||||
let band = |a: Vec2, b: Vec2| -> Option<Vec<Vec2>> {
|
||||
let (dx, dy) = (b.x - a.x, b.y - a.y);
|
||||
let l = dx.hypot(dy);
|
||||
if !(l > 1e-9) {
|
||||
return None;
|
||||
}
|
||||
let (nx, ny) = (-dy / l * PICK_BAND * mm, dx / l * PICK_BAND * mm);
|
||||
Some(vec![v(a.x + nx, a.y + ny), v(b.x + nx, b.y + ny), v(b.x - nx, b.y - ny), v(a.x - nx, a.y - ny)])
|
||||
};
|
||||
let m = area.len();
|
||||
for k in 0..m {
|
||||
// Perspektive: Kanten 0–1, 0–2 und 1–2; Streifen: Umriss.
|
||||
let (a, b) = if g.perspective { [(0, 1), (0, 2), (1, 2)][k.min(2)] } else { (k, (k + 1) % m) };
|
||||
if g.perspective && k > 2 {
|
||||
break;
|
||||
}
|
||||
if let Some(b) = band(area[a], area[b]) {
|
||||
pick(b);
|
||||
}
|
||||
}
|
||||
if g.plan_dist > 1e-6 {
|
||||
if let Some(b) = band(v(px, py), v(g.target[0], g.target[1])) {
|
||||
pick(b);
|
||||
}
|
||||
}
|
||||
let kk = CROSS * mm;
|
||||
pick(vec![v(g.target[0] - kk, g.target[1] - kk), v(g.target[0] + kk, g.target[1] - kk), v(g.target[0] + kk, g.target[1] + kk), v(g.target[0] - kk, g.target[1] + kk)]);
|
||||
// Sichtgrenzen: Kegel (zwei Kanten und die ferne Linie) bzw. Streifen (Umriss).
|
||||
if g.perspective {
|
||||
out.push(line(area[0], area[1], "camera-cone", CONE_MM, &color, None, greyed));
|
||||
out.push(line(area[0], area[2], "camera-cone", CONE_MM, &color, None, greyed));
|
||||
out.push(line(area[1], area[2], "camera-cone", CONE_MM, &color, Some(&AIM_DASH), greyed));
|
||||
} else {
|
||||
for k in 0..m {
|
||||
let dash = (k == 0).then_some(&AIM_DASH[..]);
|
||||
out.push(line(area[k], area[(k + 1) % m], "camera-cone", CONE_MM, &color, dash, greyed));
|
||||
}
|
||||
}
|
||||
out.push(poly(body, "#ffffff", &color, BODY_MM, None, greyed));
|
||||
out.push(poly(lens, &color, &color, BODY_MM, None, greyed));
|
||||
// Blicklinie zum Ziel und Zielkreuz.
|
||||
let (tx, ty) = (g.target[0], g.target[1]);
|
||||
if g.plan_dist > 1e-6 {
|
||||
out.push(line(v(px, py), v(tx, ty), "camera-aim", AIM_MM, &color, Some(&AIM_DASH), greyed));
|
||||
}
|
||||
let k = CROSS * mm;
|
||||
out.push(line(v(tx - k, ty), v(tx + k, ty), "camera-aim", CONE_MM, &color, None, greyed));
|
||||
out.push(line(v(tx, ty - k), v(tx, ty + k), "camera-aim", CONE_MM, &color, None, greyed));
|
||||
// Name hinter dem Gehäuse (Schrift bleibt waagrecht, der Block rückt so weit ab, dass er das Gehäuse nicht berührt).
|
||||
let name = cam.name.trim();
|
||||
if !name.is_empty() && scale.is_finite() && scale > 0.0 {
|
||||
let doc = super::domains::doc_from_text(name);
|
||||
let pt = super::trees::label_pt(scale);
|
||||
let (w, h) = crate::text_layout::stamp_block_size(&doc, &[], pt, crate::text_layout::PT_TO_MM * mm);
|
||||
let back = (BODY_LEN + LENS_LEN + 1.0) * mm;
|
||||
let reach = cs.abs() * w / 2.0 + sn.abs() * h / 2.0 + 0.5 * mm;
|
||||
let c = v(px - cs * (back + reach), py - sn * (back + reach));
|
||||
out.push(Primitive::Text { at: c, doc, extra_lines: vec![], base_pt: pt, color: color.clone(), room_id: None, greyed, opacity: None });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Kamera-Symbole des Grundrisses (Kameras dieses Geschosses mit sichtbarer Klasse).
|
||||
pub(super) fn plan_cameras(c: &Ctx, out: &mut Vec<Primitive>) {
|
||||
let Some(cams) = c.p.cameras.as_deref() else { return };
|
||||
let scale = if c.a.scale.is_finite() && c.a.scale > 0.0 { c.a.scale } else { 100.0 };
|
||||
for cam in cams {
|
||||
if cam.floor_id != c.a.floor || !c.derived_shown(&cam.category_code) || c.rule_hidden(&cam.id) {
|
||||
continue;
|
||||
}
|
||||
let Some(g) = CameraGeom::of(c.p, cam) else { continue };
|
||||
let greyed = Some(c.greyed(&cam.category_code));
|
||||
out.extend(camera_symbol(cam, &g, scale, c.cat(&cam.category_code), greyed));
|
||||
}
|
||||
}
|
||||
|
||||
/// Ist `q` ein Planzeichen einer Kamera?
|
||||
pub(super) fn is_symbol_part(q: &Primitive) -> bool {
|
||||
match q {
|
||||
Primitive::Line { cls, .. } => cls == "camera-cone" || cls == "camera-aim",
|
||||
Primitive::Polygon { context_object_id: Some(id), .. } => id.starts_with(CAMERA_PICK_PREFIX),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::plan::domains::{plan_domains_buf, PlanArgs};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn project(extra: Value) -> Project {
|
||||
let mut v: Value = serde_json::from_str(include_str!("../../tests/fixtures/sample_project.json")).unwrap();
|
||||
v["layers"].as_array_mut().unwrap().push(json!({"code": "92", "name": "Kameras", "color": "#123456", "lw": 0.18, "visible": true, "locked": false}));
|
||||
v["cameras"] = json!([{"id": "k1", "type": "camera", "name": "Süd", "floorId": "eg", "categoryCode": "92", "position": {"x": 2, "y": -3},
|
||||
"eyeHeight": 1.6, "target": {"x": 2, "y": 3}, "targetHeight": 1.6, "fovDeg": 50, "projection": "perspective"}]);
|
||||
if let Some(o) = extra.as_object() {
|
||||
for (k, val) in o {
|
||||
v["cameras"][0][k] = val.clone();
|
||||
}
|
||||
}
|
||||
serde_json::from_value(v).unwrap()
|
||||
}
|
||||
|
||||
fn plan(p: &Project, floor: &str, show: &[String]) -> Vec<Primitive> {
|
||||
let a = PlanArgs::parse(1.0, &json!({"floor": floor, "show": show, "global": true, "scale": 100}).to_string()).unwrap();
|
||||
let buf = plan_domains_buf(p, &a).unwrap();
|
||||
crate::plan::buf::View::parse(&buf).unwrap().prims().unwrap()
|
||||
}
|
||||
|
||||
fn all_codes(p: &Project) -> Vec<String> {
|
||||
let mut c: Vec<String> = p.flat_categories().iter().map(|c| c.code.clone()).collect();
|
||||
c.extend(p.walls.iter().map(|w| w.category_code.clone()));
|
||||
c
|
||||
}
|
||||
|
||||
fn camera_prims(prims: &[Primitive]) -> Vec<&Primitive> {
|
||||
prims.iter().filter(|q| is_symbol_part(q)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_auf_der_klasse_der_kamera() {
|
||||
let p = project(json!({}));
|
||||
let all = all_codes(&p);
|
||||
let prims = plan(&p, "eg", &all);
|
||||
let mine = camera_prims(&prims);
|
||||
assert!(mine.iter().any(|q| matches!(q, Primitive::Polygon { context_object_id: Some(id), .. } if id == "@camera:k1")), "Pick-Fläche");
|
||||
assert!(mine.iter().any(|q| matches!(q, Primitive::Line { cls, .. } if cls == "camera-cone")), "Sichtkegel");
|
||||
assert!(prims.iter().any(|q| matches!(q, Primitive::Text { color, .. } if color == "#123456")), "Name in der Klassenfarbe");
|
||||
// Klasse aus: nichts mehr.
|
||||
let without: Vec<String> = all.iter().filter(|c| *c != "92").cloned().collect();
|
||||
let prims = plan(&p, "eg", &without);
|
||||
assert!(camera_prims(&prims).is_empty(), "Klasse 92 aus");
|
||||
assert!(!prims.iter().any(|q| matches!(q, Primitive::Text { color, .. } if color == "#123456")), "Name mit der Klasse aus");
|
||||
// Anderes Geschoss: nichts.
|
||||
if let Some(o) = p.drawing_levels.iter().find(|l| l.id != "eg" && l.kind == DrawingLevelKind::Floor) {
|
||||
assert!(camera_prims(&plan(&p, &o.id, &all)).is_empty(), "anderes Geschoss");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kegel_oeffnet_sich_um_den_bildwinkel() {
|
||||
let p = project(json!({"fovDeg": 40}));
|
||||
let g = CameraGeom::of(&p, &p.cameras.as_ref().unwrap()[0]).unwrap();
|
||||
let a = view_area(&g, 0.1);
|
||||
// Blick nach +y: die Ecken liegen links/rechts davon, symmetrisch.
|
||||
assert!((a[1].x - 2.0 + (a[2].x - 2.0)).abs() < 1e-9);
|
||||
let half = ((a[2].x - 2.0) / (a[2].y + 3.0)).atan().abs();
|
||||
assert!((half - half_h_angle(40.0)).abs() < 1e-9);
|
||||
// Die ferne Kante geht durch das Ziel (Abstand 6 m).
|
||||
assert!((a[1].y - 3.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parallelprojektion_zeichnet_streifen() {
|
||||
let p = project(json!({"projection": "axonometric", "orthoHeight": 4}));
|
||||
let g = CameraGeom::of(&p, &p.cameras.as_ref().unwrap()[0]).unwrap();
|
||||
let a = view_area(&g, 0.1);
|
||||
assert_eq!(a.len(), 4);
|
||||
// Breite = 4 m × 16/9.
|
||||
assert!(((a[3].x - a[0].x).abs() - 4.0 * crate::camera::ASPECT).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
@@ -1790,6 +1790,16 @@ fn domains_after(c: &Ctx, out: &mut DomainPrims, bounds: &mut Bounds, marks: &mu
|
||||
}
|
||||
// Räume vor dem Kontext: Stempel ausserhalb ihres Raums (eigener Anker im Gelände) sind Hindernisse der
|
||||
// Höhenlinien-Beschriftungen; Stempel im Raum liegen im Fussabdruck, wo keine Beschriftung steht.
|
||||
// [213] Kameras: Planzeichen mit Sichtkegel obenauf (Gruppe der Schnittführungen).
|
||||
let first_camera = out.sections.len();
|
||||
super::cameras::plan_cameras(c, &mut out.sections);
|
||||
// Das Symbol (Kegel, Ziel) gehört zum Ausmass, damit es beim Einpassen nicht abgeschnitten wird.
|
||||
for q in &out.sections[first_camera..] {
|
||||
if let Primitive::Line { a, b, .. } = q {
|
||||
bounds.acc(a.x, a.y);
|
||||
bounds.acc(b.x, b.y);
|
||||
}
|
||||
}
|
||||
let obstacles = stamp_obstacles_with(out, drawn.clone());
|
||||
let mut top = Vec::new();
|
||||
rooms(c, &mut out.rooms, &mut top, bounds, &obstacles);
|
||||
|
||||
@@ -39,6 +39,7 @@ pub mod stamp_place;
|
||||
pub mod floor_finish;
|
||||
pub mod model_view;
|
||||
pub mod trees;
|
||||
pub mod cameras;
|
||||
pub mod mesh_plan;
|
||||
pub mod arc_fit;
|
||||
pub(crate) mod seams;
|
||||
|
||||
@@ -43,7 +43,7 @@ pub fn pick_id(id: &str) -> String {
|
||||
format!("{TREE_PICK_PREFIX}{id}")
|
||||
}
|
||||
|
||||
fn poly(pts: Vec<Vec2>, fill: &str, stroke: &str, w: f64, pick: Option<String>, greyed: Option<bool>) -> Primitive {
|
||||
pub(super) fn poly(pts: Vec<Vec2>, fill: &str, stroke: &str, w: f64, pick: Option<String>, greyed: Option<bool>) -> Primitive {
|
||||
Primitive::Polygon {
|
||||
pts,
|
||||
fill: fill.into(),
|
||||
@@ -67,7 +67,7 @@ fn poly(pts: Vec<Vec2>, fill: &str, stroke: &str, w: f64, pick: Option<String>,
|
||||
}
|
||||
}
|
||||
|
||||
fn line(a: Vec2, b: Vec2, cls: &str, w: f64, color: &str, dash: Option<&[f64]>, greyed: Option<bool>) -> Primitive {
|
||||
pub(super) fn line(a: Vec2, b: Vec2, cls: &str, w: f64, color: &str, dash: Option<&[f64]>, greyed: Option<bool>) -> Primitive {
|
||||
Primitive::Line {
|
||||
a,
|
||||
b,
|
||||
|
||||
@@ -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; 56] = [
|
||||
const KNOWN_KEYS: [&str; 57] = [
|
||||
"formatVersion", "id", "name", "lineStyles", "textStyles", "hatches", "components", "wallTypes",
|
||||
"ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens",
|
||||
"penSets", "activePenSetId", "customPalettes", "builtinPaletteBanks", "drawingLevels", "layers",
|
||||
@@ -24,7 +24,7 @@ const KNOWN_KEYS: [&str; 56] = [
|
||||
"viewSnapshotFolders", "viewTemplates", "layouts", "masterLayouts", "layoutFolders", "publishSets", "publishLog", "projectNumber", "referenceElevationMasl",
|
||||
"geoAnchor", "roomProgram", "roomProgramTolerance", "parcelArea", "sunStudy", "siteRules", "scaleLineWeights",
|
||||
"lineCap", "lineJoin", "trees", "uiState",
|
||||
"modelViewOptions",
|
||||
"modelViewOptions", "cameras",
|
||||
];
|
||||
|
||||
/// Ergebnis des Einlesens.
|
||||
|
||||
@@ -99,6 +99,9 @@ pub fn dangling_refs(p: &Project) -> Vec<String> {
|
||||
for r in p.rooms.as_deref().unwrap_or(&[]) {
|
||||
miss(&mut out, "Raum", &r.id, "Geschoss", &r.floor_id, &levels);
|
||||
}
|
||||
for c in p.cameras.as_deref().unwrap_or(&[]) {
|
||||
miss(&mut out, "Kamera", &c.id, "Geschoss", &c.floor_id, &levels);
|
||||
}
|
||||
for d in &p.drawings2d {
|
||||
miss(&mut out, "Zeichnung", &d.id, "Ebene", &d.level_id, &levels);
|
||||
miss(&mut out, "Zeichnung", &d.id, "Linienstil", d.line_style_id.as_deref().unwrap_or(""), &line_styles);
|
||||
|
||||
@@ -363,13 +363,16 @@ pub const AUTO_DIM_CATEGORY: &str = "81";
|
||||
pub const LEVEL_MARK_CATEGORY: &str = "82";
|
||||
/// Schnitt- und Ansichtsmarken im Grundriss (Schnittführung mit Pfeilen und Beschriftung).
|
||||
pub const SECTION_MARK_CATEGORY: &str = "91";
|
||||
/// Kameras ([213]): Symbol mit Sichtkegel im Grundriss (Element `Project.cameras`, Klasse je Element änderbar).
|
||||
pub const CAMERA_CATEGORY: &str = "92";
|
||||
|
||||
/// Die Klassen der abgeleiteten Darstellung (Code, Name, Farbe, Strichstärke).
|
||||
pub const DERIVED_CATEGORIES: [(&str, &str, &str, f64); 4] = [
|
||||
pub const DERIVED_CATEGORIES: [(&str, &str, &str, f64); 5] = [
|
||||
(SHADOW_CATEGORY, "Schatten", "#707078", 0.13),
|
||||
(AUTO_DIM_CATEGORY, "Auto-Bemassung", "#303038", 0.13),
|
||||
(LEVEL_MARK_CATEGORY, "Höhenkoten", "#1a1a1a", 0.13),
|
||||
(SECTION_MARK_CATEGORY, "Schnittmarken", "#1a1a1a", 0.18),
|
||||
(CAMERA_CATEGORY, "Kameras", "#1a1a1a", 0.18),
|
||||
];
|
||||
|
||||
pub fn derived_categories() -> Vec<Value> {
|
||||
@@ -841,7 +844,7 @@ mod tests {
|
||||
// Andere Kategorien bleiben, die neue kommt ans Ende.
|
||||
own.insert("layers".into(), json!([{"code": "20", "name": "Wände", "color": "#000", "lw": 0.35, "visible": true, "locked": false}]));
|
||||
let op = merge_ops(&own).into_iter().find(|o| o["key"] == "layers").unwrap();
|
||||
assert_eq!(op["value"].as_array().unwrap().iter().map(|l| l["code"].as_str().unwrap()).collect::<Vec<_>>(), ["20", "65", "08", "81", "82", "91"]);
|
||||
assert_eq!(op["value"].as_array().unwrap().iter().map(|l| l["code"].as_str().unwrap()).collect::<Vec<_>>(), ["20", "65", "08", "81", "82", "91", "92"]);
|
||||
}
|
||||
|
||||
/// [180] Klassen der abgeleiteten Darstellung: „Standards laden" legt sie an, einmal; vorhandene (Code oder Name) bleiben.
|
||||
@@ -857,7 +860,7 @@ mod tests {
|
||||
own.insert("layers".into(), json!([{"code": "77", "name": "schatten", "color": "#000", "lw": 0.13, "visible": true, "locked": false}]));
|
||||
let op = merge_ops(&own).into_iter().find(|o| o["key"] == "layers").unwrap();
|
||||
let codes: Vec<&str> = op["value"].as_array().unwrap().iter().map(|l| l["code"].as_str().unwrap()).collect();
|
||||
assert_eq!(codes, ["77", "65", "81", "82", "91"]);
|
||||
assert_eq!(codes, ["77", "65", "81", "82", "91", "92"]);
|
||||
// Sichtbar, solange die Klasse fehlt; sonst nach der Klassen-Sichtbarkeit.
|
||||
assert!(derived_visible(&p, SHADOW_CATEGORY, |c| c == SHADOW_CATEGORY));
|
||||
assert!(!derived_visible(&p, SHADOW_CATEGORY, |_| false));
|
||||
|
||||
@@ -58,6 +58,14 @@ pub fn grip_vertices(drawing_json: &str, scale: f64) -> Vec<f64> {
|
||||
}
|
||||
}
|
||||
|
||||
/// [213] Griffe einer Kamera (JSON) beim Massstab 1:`scale`: `[x0, y0, x1, y1, x2, y2]` (Standpunkt, Ziel,
|
||||
/// Bildwinkel/Sichtbreite), `[]` bei kaputtem JSON.
|
||||
#[wasm_bindgen]
|
||||
pub fn camera_grip_points(camera_json: &str, scale: f64) -> Vec<f64> {
|
||||
let Ok(c) = serde_json::from_str::<crate::model::Camera>(camera_json) else { return vec![] };
|
||||
crate::camera::grip_points(&c, scale).into_iter().flat_map(|p| [p.0, p.1]).collect()
|
||||
}
|
||||
|
||||
/// Editier-Griffe einer Polylinie aus flachen Puffern (grosse Kataster-Umrisse ohne JSON): `pts = [x0, y0, …]`,
|
||||
/// `bulge` je Segment (fehlend/NaN = gerade) → `[x0, y0, …]` (Eckpunkte, dann je Segment die Bogen-Mitte).
|
||||
#[wasm_bindgen]
|
||||
|
||||
@@ -72,6 +72,7 @@ export { EMPTY_MEMBERSHIP, containingGroupId, expandToGroups, isInsideActiveGrou
|
||||
export type { GroupMembership, MemberKind } from "../model/groups";
|
||||
export { arcApex, drawingVertices, gripPt, openEdges, polylineEdgeGrips, ringEdges } from "../geometry/grips";
|
||||
export { verticalExtents } from "../geometry/grips";
|
||||
export { cameraGripPoints } from "../geometry/grips";
|
||||
export type { VerticalExtent } from "../geometry/grips";
|
||||
export type { GripRequest, RingKind } from "../geometry/grips";
|
||||
export { edgeArcToggle, type ArcRingKind } from "../geometry/grips";
|
||||
|
||||
+12
-1
@@ -7,7 +7,7 @@
|
||||
// Bewusst TS: die Rahmen-Ecken einer Textspalte (`textFrameCorners` braucht die Schrift-Metrik der
|
||||
// Hülle) — der Kern meldet dafür nur „Textspalte".
|
||||
|
||||
import type { Ceiling, Drawing2D, Drawing2DGeom, EdgeGrip, Project, Vec2, Wall } from "../model/types";
|
||||
import type { Camera, Ceiling, Drawing2D, Drawing2DGeom, EdgeGrip, Project, Vec2, Wall } from "../model/types";
|
||||
import { documentFor } from "../core/document";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import { toMarkedJson } from "../core/ops";
|
||||
@@ -46,6 +46,9 @@ export type GripRequest =
|
||||
// [176] Schnittlinie: 0 = Anfang, dann `bendPoints`, zuletzt das Ende.
|
||||
| { op: "sectionLineGrip"; id: string; index: number; pt: P }
|
||||
| { op: "sectionBendInsert"; id: string; seg: number; pt: P }
|
||||
// [213] Kamera: 0 = Standpunkt, 1 = Ziel, 2 = Bildwinkel bzw. Sichtbreite (Kern `camera::grip_edit`); `cameraBy` verschiebt Standpunkt und Ziel.
|
||||
| { op: "cameraGrip"; id: string; index: number; pt: P }
|
||||
| { op: "cameraBy"; id: string; delta: P }
|
||||
| { op: "sectionBendDelete"; id: string; index: number }
|
||||
| { op: "sectionLineTidy"; id: string; tol?: number }
|
||||
// [26] Ecke an Umriss-Ringen einfügen (hinter Kante `seg`), löschen, aufräumen (Kern `ring_edit`); Dach: flacher Index.
|
||||
@@ -100,6 +103,14 @@ export function drawingVertices(d: Drawing2D, scaleDenominator: number = DEFAULT
|
||||
return out;
|
||||
}
|
||||
|
||||
/** [213] Griffe einer Kamera im Grundriss beim Massstab 1:`scaleDenominator`: Standpunkt, Ziel, Bildwinkel/Sichtbreite (Kern `camera::grip_points`). */
|
||||
export function cameraGripPoints(c: Camera, scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR): Vec2[] {
|
||||
const f = core().camera_grip_points(JSON.stringify(c), scaleDenominator);
|
||||
const out: Vec2[] = [];
|
||||
for (let i = 0; i + 1 < f.length; i += 2) out.push({ x: f[i], y: f[i + 1] });
|
||||
return out;
|
||||
}
|
||||
|
||||
type Owner = { drawingId?: string; wallId?: string };
|
||||
|
||||
function flat(verts: readonly Vec2[]): Float64Array {
|
||||
|
||||
@@ -1049,6 +1049,7 @@ export const de = {
|
||||
"nav.categoryDerived.81": "Abgeleitete Darstellung: automatische Aussenbemassung (je Kette änderbar)",
|
||||
"nav.categoryDerived.82": "Abgeleitete Darstellung: automatische Höhenkoten in Schnitt und Ansicht",
|
||||
"nav.categoryDerived.91": "Abgeleitete Darstellung: Schnitt- und Ansichtsmarken im Grundriss",
|
||||
"nav.categoryDerived.92": "Kameras: Symbol mit Sichtkegel im Grundriss (Element Kamera, je Kamera änderbar)",
|
||||
"nav.categorySettings": "Ebeneneinstellungen für {name}",
|
||||
"nav.drawingLevelsWindow": "Zeichnungsebenen als eigenes Fenster öffnen",
|
||||
|
||||
@@ -2055,6 +2056,44 @@ export const de = {
|
||||
"cmd.circlestotrees.label": "Kreise in Bäume umwandeln",
|
||||
"objinfo.kind.tree": "Baum",
|
||||
"objinfo.tree.many": "{n} Bäume",
|
||||
"camera.title": "Kameras",
|
||||
"camera.defaultName": "Kamera",
|
||||
"camera.empty": "Keine Kameras. Mit „+“ aus der aktuellen 3D-Ansicht anlegen.",
|
||||
"camera.createFromView": "Kamera aus aktueller Ansicht anlegen",
|
||||
"camera.created": "Kamera „{name}“ angelegt",
|
||||
"camera.open": "Kamera öffnen",
|
||||
"camera.rowHint": "Klick wählt die Kamera, Doppelklick öffnet sie im 3D",
|
||||
"camera.delete": "Kamera löschen",
|
||||
"camera.update": "Aus aktueller Ansicht",
|
||||
"camera.updateHint": "Standpunkt, Ziel, Bildwinkel und Projektion mit der aktuellen 3D-Ansicht überschreiben",
|
||||
"camera.updated": "Kamera „{name}“ aus der aktuellen Ansicht aktualisiert",
|
||||
"camera.iso": "Isometrisch",
|
||||
"camera.isoHint": "Standpunkt so legen, dass die Kamera das Ziel isometrisch (45°, 35,3° Neigung) ansieht",
|
||||
"camera.noViewport": "Die 3D-Ansicht ist nicht geöffnet.",
|
||||
"camera.invalid": "Kamera „{name}“ hat keinen gültigen Blick (Standpunkt gleich Ziel?).",
|
||||
"objinfo.kind.camera": "Kamera",
|
||||
"objinfo.camera.many": "{n} Kameras",
|
||||
"objinfo.camera.section": "Kamera",
|
||||
"objinfo.camera.name": "Name",
|
||||
"objinfo.camera.projection": "Projektion",
|
||||
"objinfo.camera.projection.perspective": "Perspektive",
|
||||
"objinfo.camera.projection.axonometric": "Axonometrie",
|
||||
"objinfo.camera.projection.parallel": "Parallelprojektion",
|
||||
"objinfo.camera.stand": "Standpunkt",
|
||||
"objinfo.camera.eyeHeight": "Augenhöhe über Geschoss",
|
||||
"objinfo.camera.target": "Ziel",
|
||||
"objinfo.camera.targetHeight": "Höhe Ziel",
|
||||
"objinfo.camera.fov": "Bildwinkel (vertikal)",
|
||||
"objinfo.camera.focal": "Brennweite (Kleinbild)",
|
||||
"objinfo.camera.orthoHeight": "Sichthöhe",
|
||||
"objinfo.camera.sun": "Sonnenstand",
|
||||
"objinfo.camera.sunHint": "Datum und Uhrzeit (UTC); „Kamera öffnen“ stellt die Sonnenstudie darauf. Leer = Sonne bleibt.",
|
||||
"objinfo.camera.locked": "Gesperrt: Die Kamera lässt sich nicht ändern.",
|
||||
"pick.kind.camera": "Kamera",
|
||||
"shortcut.walkMode": "Begehen im 3D ein/aus",
|
||||
"walk.toggle": "Begehen",
|
||||
"walk.hint": "Begehen (Umschalt+F): W/A/S/D oder Pfeile gehen, Q/E runter und hoch, Umschalt schneller, Alt langsamer, mit gedrückter Maustaste umschauen",
|
||||
"viewport3d.camera.create": "Kamera aus aktueller Ansicht anlegen",
|
||||
"objinfo.tree.section": "Baum",
|
||||
"objinfo.tree.species": "Art",
|
||||
"objinfo.tree.speciesHint": "z. B. Quercus robur",
|
||||
|
||||
@@ -1044,6 +1044,7 @@ export const en: Record<TranslationKey, string> = {
|
||||
"nav.categoryDerived.81": "Derived display: automatic exterior dimensions (each chain can be reassigned)",
|
||||
"nav.categoryDerived.82": "Derived display: automatic level marks in sections and elevations",
|
||||
"nav.categoryDerived.91": "Derived display: section and elevation marks in plans",
|
||||
"nav.categoryDerived.92": "Cameras: symbol with view cone in plans (camera element, each camera can be reassigned)",
|
||||
"nav.categorySettings": "Layer settings for {name}",
|
||||
"nav.drawingLevelsWindow": "Open drawing levels as its own window",
|
||||
|
||||
@@ -2044,6 +2045,44 @@ export const en: Record<TranslationKey, string> = {
|
||||
"cmd.circlestotrees.label": "Convert circles to trees",
|
||||
"objinfo.kind.tree": "Tree",
|
||||
"objinfo.tree.many": "{n} trees",
|
||||
"camera.title": "Cameras",
|
||||
"camera.defaultName": "Camera",
|
||||
"camera.empty": "No cameras. Use “+” to create one from the current 3D view.",
|
||||
"camera.createFromView": "Create camera from current view",
|
||||
"camera.created": "Camera “{name}” created",
|
||||
"camera.open": "Open camera",
|
||||
"camera.rowHint": "Click selects the camera, double-click opens it in 3D",
|
||||
"camera.delete": "Delete camera",
|
||||
"camera.update": "From current view",
|
||||
"camera.updateHint": "Overwrite position, target, field of view and projection with the current 3D view",
|
||||
"camera.updated": "Camera “{name}” updated from the current view",
|
||||
"camera.iso": "Isometric",
|
||||
"camera.isoHint": "Move the camera so it looks at the target isometrically (45°, 35.3° pitch)",
|
||||
"camera.noViewport": "The 3D view is not open.",
|
||||
"camera.invalid": "Camera “{name}” has no valid view (position equals target?).",
|
||||
"objinfo.kind.camera": "Camera",
|
||||
"objinfo.camera.many": "{n} cameras",
|
||||
"objinfo.camera.section": "Camera",
|
||||
"objinfo.camera.name": "Name",
|
||||
"objinfo.camera.projection": "Projection",
|
||||
"objinfo.camera.projection.perspective": "Perspective",
|
||||
"objinfo.camera.projection.axonometric": "Axonometric",
|
||||
"objinfo.camera.projection.parallel": "Parallel projection",
|
||||
"objinfo.camera.stand": "Position",
|
||||
"objinfo.camera.eyeHeight": "Eye height above floor",
|
||||
"objinfo.camera.target": "Target",
|
||||
"objinfo.camera.targetHeight": "Target height",
|
||||
"objinfo.camera.fov": "Field of view (vertical)",
|
||||
"objinfo.camera.focal": "Focal length (35 mm)",
|
||||
"objinfo.camera.orthoHeight": "View height",
|
||||
"objinfo.camera.sun": "Sun position",
|
||||
"objinfo.camera.sunHint": "Date and time (UTC); “Open camera” sets the sun study to it. Empty = sun stays.",
|
||||
"objinfo.camera.locked": "Locked: the camera cannot be changed.",
|
||||
"pick.kind.camera": "Camera",
|
||||
"shortcut.walkMode": "Walk through 3D on/off",
|
||||
"walk.toggle": "Walk",
|
||||
"walk.hint": "Walk (Shift+F): W/A/S/D or arrow keys move, Q/E down and up, Shift faster, Alt slower, hold a mouse button to look around",
|
||||
"viewport3d.camera.create": "Create camera from current view",
|
||||
"objinfo.tree.section": "Tree",
|
||||
"objinfo.tree.species": "Species",
|
||||
"objinfo.tree.speciesHint": "e.g. Quercus robur",
|
||||
|
||||
@@ -15,8 +15,10 @@ export const AUTO_DIM_CATEGORY = "81";
|
||||
export const LEVEL_MARK_CATEGORY = "82";
|
||||
/** Schnitt- und Ansichtsmarken im Grundriss. */
|
||||
export const SECTION_MARK_CATEGORY = "91";
|
||||
/** Kameras ([213]): Symbol mit Sichtkegel im Grundriss. */
|
||||
export const CAMERA_CATEGORY = "92";
|
||||
|
||||
export const DERIVED_CATEGORY_CODES: readonly string[] = [SHADOW_CATEGORY, AUTO_DIM_CATEGORY, LEVEL_MARK_CATEGORY, SECTION_MARK_CATEGORY];
|
||||
export const DERIVED_CATEGORY_CODES: readonly string[] = [SHADOW_CATEGORY, AUTO_DIM_CATEGORY, LEVEL_MARK_CATEGORY, SECTION_MARK_CATEGORY, CAMERA_CATEGORY];
|
||||
|
||||
/** Abgeleitete Darstellung der Klasse `code` sichtbar: Klasse eingeblendet (`shown`) oder im Projekt nicht vorhanden. */
|
||||
export function derivedVisible(layers: LayerCategory[], code: string, shown: (code: string) => boolean): boolean {
|
||||
|
||||
@@ -416,6 +416,7 @@ export const sampleProject: Project = {
|
||||
{ code: "82", name: "Höhenkoten", color: "#1a1a1a", lw: 0.13, visible: true, locked: false },
|
||||
{ code: "90", name: "Referenzen", color: "#1a1a1a", lw: 0.13, visible: true, locked: false },
|
||||
{ code: "91", name: "Schnittmarken", color: "#1a1a1a", lw: 0.18, visible: true, locked: false },
|
||||
{ code: "92", name: "Kameras", color: "#1a1a1a", lw: 0.18, visible: true, locked: false },
|
||||
{ code: "99", name: "Konstruktion", color: "#404040", lw: 0.13, visible: true, locked: false },
|
||||
],
|
||||
// [140] Strichstärken folgen dem Massstab (neue Projekte; bestehende behalten ihre Einstellung).
|
||||
|
||||
@@ -857,6 +857,14 @@ export function buildComplexSampleProject(): Project {
|
||||
roomProgramTolerance: 0.1,
|
||||
parcelArea: 1540,
|
||||
sunStudy: { when: "2026-06-21T10:00:00Z", show: true },
|
||||
// [213] Kamera aus Südost auf das Haus (Standpunkt 1.6 m über OK EG, Sonne am Abend).
|
||||
cameras: [
|
||||
{
|
||||
id: "kamera-suedost", type: "camera", name: "Südost", floorId: "eg", categoryCode: "92",
|
||||
position: P(17, -3), eyeHeight: 1.6, target: P(7.5, 5), targetHeight: 4, fovDeg: 50, projection: "perspective",
|
||||
sunWhen: "2026-06-21T16:00:00Z",
|
||||
},
|
||||
],
|
||||
siteRules: {
|
||||
parcel: PARCEL,
|
||||
// Grenzabstände je Parzellenkante (Süd, Ost, Nord, West); Baulinie entlang der Strasse.
|
||||
|
||||
@@ -46,6 +46,50 @@ export type BlockDef = { id: string; name: string; geom2d: Array<Drawing2DGeom>
|
||||
*/
|
||||
export type BuiltinPaletteBanks = { simple?: boolean; tango?: boolean; material?: boolean; ral?: boolean };
|
||||
|
||||
/**
|
||||
* Eine Kamera ([213]) — gespeicherter Standpunkt für die 3D-Ansicht (und das Rendering): Standpunkt im
|
||||
* Grundriss mit Augenhöhe über dem Geschoss, Ziel (Grundriss und absolute Höhe), Bildwinkel, Projektion
|
||||
* und optional Datum/Uhrzeit für den Sonnenstand. Im Grundriss als Symbol mit Sichtkegel auf der Klasse
|
||||
* „Kameras" (Vorgabe "92"); „Kamera öffnen" setzt die 3D-Ansicht exakt.
|
||||
*/
|
||||
export type Camera = {
|
||||
id: string;
|
||||
type: "camera";
|
||||
name: string;
|
||||
/** Geschoss, auf dem das Symbol im Grundriss steht und auf das sich die Augenhöhe bezieht. */
|
||||
floorId: string;
|
||||
/** Klasse (Ebene), Vorgabe "92" (Kameras). */
|
||||
categoryCode: string;
|
||||
/** Objekt-Sperre, analog `Wall.locked`. */
|
||||
locked?: boolean;
|
||||
/** Standpunkt im Grundriss (Meter). */
|
||||
position: Vec2;
|
||||
/** Augenhöhe über OK Fertigboden des Geschosses (m). */
|
||||
eyeHeight: number;
|
||||
/** Ziel im Grundriss (Meter); der Abstand Standpunkt–Ziel ist die Länge des Sichtkegels. */
|
||||
target: Vec2;
|
||||
/** Höhe des Ziels (m, absolut, z des Modells). */
|
||||
targetHeight: number;
|
||||
/**
|
||||
* Vertikaler Bildwinkel (Grad, perspektivisch). Die Kleinbild-Brennweite folgt daraus (24-mm-Sensorhöhe).
|
||||
*/
|
||||
fovDeg: number;
|
||||
projection: CameraProjection;
|
||||
/** Sichthöhe in Metern (volle Bildhöhe) bei Axonometrie/Parallel; fehlt = 10 m. */
|
||||
orthoHeight?: number;
|
||||
/**
|
||||
* Zeitpunkt für den Sonnenstand (ISO-8601 in UTC wie `SunStudy.when`); „Kamera öffnen" setzt ihn in der
|
||||
* Sonnenstudie. Fehlt er, bleibt die Sonne der Studie.
|
||||
*/
|
||||
sunWhen?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Projektion einer Kamera ([213]): Perspektive, Axonometrie (Parallelprojektion mit schrägem Blick, z. B.
|
||||
* Isometrie) oder Parallelprojektion (frei ausgerichtet). Axonometrie und Parallel zeichnen im 3D orthografisch.
|
||||
*/
|
||||
export type CameraProjection = "perspective" | "axonometric" | "parallel";
|
||||
|
||||
/** Bekleidung einer Tür ([105]): auf der Aufschlagseite, der Gegenseite, beidseitig oder keine. */
|
||||
export type CasingSides = "beide" | "aufschlag" | "gegen" | "keine";
|
||||
|
||||
@@ -2844,6 +2888,11 @@ export type Project = {
|
||||
* bestehende Projekte ohne `trees` gültig bleiben (Default: leer behandeln).
|
||||
*/
|
||||
trees?: Array<Tree>;
|
||||
/**
|
||||
* Kameras ([213]) — gespeicherte Standpunkte für 3D-Ansicht und Rendering, siehe {@link Camera}. Optional
|
||||
* (Default: leer behandeln).
|
||||
*/
|
||||
cameras?: Array<Camera>;
|
||||
/**
|
||||
* Gruppen (Vectorworks-artig: Cmd+G fasst die Auswahl zu einer Einheit
|
||||
* zusammen; Doppelklick betritt die Gruppe zum Bearbeiten, alles andere
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// Gruppe „Kameras" im Ausschnitte-Panel ([213]): die gespeicherten Kameras des Projekts als Liste. Klick wählt die
|
||||
// Kamera (Objekt-Info, Symbol im Grundriss), Doppelklick bzw. „↗" setzt die 3D-Ansicht exakt, „+" legt aus der
|
||||
// aktuellen 3D-Ansicht eine neue an, „✕" löscht. Die Kameras selbst sind Modell-Elemente (`Project.cameras`).
|
||||
|
||||
import { removeItems } from "../core";
|
||||
import { t } from "../i18n";
|
||||
import { createCameraFromView, openCamera } from "../state/cameraActions";
|
||||
import { getState, useStore } from "../state/appStore";
|
||||
import { fromIds } from "../state/selection";
|
||||
|
||||
export function CamerasGroup() {
|
||||
const cameras = useStore((s) => s.project.cameras);
|
||||
const levels = useStore((s) => s.project.drawingLevels);
|
||||
const selected = useStore((s) => s.selection.cameras);
|
||||
const list = cameras ?? [];
|
||||
return (
|
||||
<section className="nav-group" data-testid="cameras-group">
|
||||
<header className="nav-group-head">
|
||||
<span className="nav-group-title">{t("camera.title")}</span>
|
||||
<span className="nav-group-actions">
|
||||
<button className="nav-add" style={{ display: "inline-flex", padding: "1px 5px" }} title={t("camera.createFromView")} data-testid="camera-create" onClick={() => createCameraFromView()}>
|
||||
+
|
||||
</button>
|
||||
</span>
|
||||
</header>
|
||||
{list.length === 0 ? (
|
||||
<div style={{ padding: "10px 10px", fontSize: 12, color: "var(--muted)" }}>{t("camera.empty")}</div>
|
||||
) : (
|
||||
<div className="nav-list">
|
||||
{list.map((c) => (
|
||||
<div
|
||||
key={c.id}
|
||||
className={`nav-row${selected.includes(c.id) ? " active" : ""}`}
|
||||
data-testid={`camera-row-${c.id}`}
|
||||
title={t("camera.rowHint")}
|
||||
onClick={() => getState().setSelection(fromIds("cameras", [c.id]))}
|
||||
onDoubleClick={() => void openCamera(c.id)}
|
||||
style={{ display: "flex", alignItems: "center", gap: 4, paddingLeft: 10 }}
|
||||
>
|
||||
<span className="nav-label" style={{ flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
|
||||
{c.name}
|
||||
<span style={{ color: "var(--muted)", marginLeft: 6 }}>{levels.find((l) => l.id === c.floorId)?.name ?? ""}</span>
|
||||
</span>
|
||||
<button
|
||||
className="nav-add"
|
||||
style={{ padding: "1px 5px" }}
|
||||
title={t("camera.open")}
|
||||
data-testid={`camera-open-${c.id}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
void openCamera(c.id);
|
||||
}}
|
||||
>
|
||||
↗
|
||||
</button>
|
||||
<button
|
||||
className="nav-add"
|
||||
style={{ padding: "1px 5px" }}
|
||||
title={t("camera.delete")}
|
||||
disabled={!!c.locked}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
getState().applyChange((p) => removeItems(p, "cameras", [c.id]));
|
||||
getState().setSelection(fromIds("cameras", []));
|
||||
}}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -31,6 +31,7 @@ import { ContextObjectProps } from "./ContextObjectProps";
|
||||
import { SunStudySection } from "./SunStudySection";
|
||||
import { SiteRulesSection } from "./SiteRulesSection";
|
||||
import { TreeSection } from "./objectInfo/TreeSection";
|
||||
import { CameraSection } from "./objectInfo/CameraSection";
|
||||
import { ViewShadowsInfo, MeasurementSection } from "./objectInfo/InfoBlocks";
|
||||
import { DimensionField, RotateField } from "./objectInfo/fields";
|
||||
import { elementDimensions } from "./objectInfo/elementDims";
|
||||
@@ -74,6 +75,7 @@ export function ObjectInfoPanel() {
|
||||
// [137] Lage-Darstellung angeklickt (Schattenfläche / Baurechtslinie): Einstellungen der Quelle.
|
||||
const site = useStore((s) => s.selection.site);
|
||||
const treeSel = useStore((s) => s.selection.trees);
|
||||
const cameraSel = useStore((s) => s.selection.cameras);
|
||||
const ctxObj = sel?.kind === "contextObject" ? (storeProject.context ?? []).find((o) => o.id === sel.id) : undefined;
|
||||
const quantities = useMemo(
|
||||
() => (ctxObj?.type === "excavation" ? excavationQuantities(storeProject) : []),
|
||||
@@ -83,6 +85,8 @@ export function ObjectInfoPanel() {
|
||||
// ── Leerzustand ───────────────────────────────────────────────────────────
|
||||
// [149] Baum gewählt: eigene Felder (Lage, Masse, Form, Bestand).
|
||||
if (sel === null && treeSel.length > 0) return <TreeSection ids={treeSel} />;
|
||||
// [213] Kamera gewählt: Standpunkt, Ziel, Bildwinkel, Projektion, Sonne und „Kamera öffnen".
|
||||
if (sel === null && cameraSel.length > 0) return <CameraSection ids={cameraSel} />;
|
||||
if (sel === null && site[0] === "viewShadows") return <ViewShadowsInfo />;
|
||||
if (sel === null && site.length > 0) {
|
||||
const sun = site[0] === "sunStudy";
|
||||
|
||||
@@ -39,6 +39,7 @@ import { applyToSnapshotOps } from "../state/viewTemplates";
|
||||
import { getState } from "../state/appStore";
|
||||
import { patchItem } from "../core";
|
||||
import { t } from "../i18n";
|
||||
import { CamerasGroup } from "./CamerasGroup";
|
||||
|
||||
// ── Baum-Icons (inline-SVG im Panel-Stil: 14px, stroke currentColor 1.4) ──────
|
||||
|
||||
@@ -518,6 +519,7 @@ export function ViewSnapshotsPanel() {
|
||||
tree.rootFolders.length === 0 && tree.rootSnapshots.length === 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<section className="nav-group">
|
||||
<header className="nav-group-head">
|
||||
<span className="nav-group-title">{t("viewsnap.title")}</span>
|
||||
@@ -687,6 +689,9 @@ export function ViewSnapshotsPanel() {
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
{/* [213] Kameras des Projekts (öffnen, anlegen, löschen). */}
|
||||
<CamerasGroup />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
// Abschnitt „Kamera" der Objekt-Info ([213]): Standpunkt und Augenhöhe, Ziel, Bildwinkel/Brennweite, Projektion,
|
||||
// Sonnenstand und die Aktionen „Kamera öffnen" / „Aus aktueller Ansicht" / „Isometrisch". Jede Änderung ein Undo-Schritt
|
||||
// (der Kern prüft die Op); bei mehreren gewählten Kameras wirken die Auswahlfelder auf alle.
|
||||
|
||||
import type { Camera, CameraProjection } from "../../model/types";
|
||||
import { useStore } from "../../state/appStore";
|
||||
import { openCamera, updateCameraFromView } from "../../state/cameraActions";
|
||||
import { t } from "../../i18n";
|
||||
import type { TranslationKey } from "../../i18n";
|
||||
import { patchItem } from "../../core";
|
||||
import { Dropdown } from "../../ui/Dropdown";
|
||||
import { clampFov, focalFromFov, fovFromFocal, isometricAim } from "../../viewport/cameraView";
|
||||
import { DimensionField } from "./fields";
|
||||
|
||||
const PROJECTIONS: CameraProjection[] = ["perspective", "axonometric", "parallel"];
|
||||
|
||||
/** ISO-UTC-Text → Wert für `<input type="datetime-local">` (UTC-Anzeige, ohne Zeitzonen-Überraschung). */
|
||||
function toLocalInput(iso: string | undefined): string {
|
||||
if (!iso) return "";
|
||||
const d = new Date(iso);
|
||||
return Number.isFinite(d.getTime()) ? d.toISOString().slice(0, 16) : "";
|
||||
}
|
||||
|
||||
export function CameraSection({ ids }: { ids: readonly string[] }) {
|
||||
const project = useStore((st) => st.project);
|
||||
const applyChange = useStore((s) => s.applyChange);
|
||||
const cams = (project.cameras ?? []).filter((x) => ids.includes(x.id));
|
||||
const cam = cams[0];
|
||||
if (!cam) return <div className="objinfo-panel"><div className="objinfo-empty">{t("objinfo.empty")}</div></div>;
|
||||
const locked = !!cam.locked;
|
||||
const set = (patch: Partial<Camera>, all = false) =>
|
||||
applyChange((p) => (all ? cams : [cam]).filter((x) => !x.locked).flatMap((x) => patchItem(p, "cameras", x.id, patch)));
|
||||
const level = project.drawingLevels.find((l) => l.id === cam.floorId);
|
||||
const parallel = cam.projection !== "perspective";
|
||||
return (
|
||||
<div className="objinfo-panel objinfo-camera" data-testid="camera-section">
|
||||
<div className="objinfo-head">
|
||||
<span className="objinfo-kind">{cams.length > 1 ? t("objinfo.camera.many", { n: cams.length }) : t("objinfo.kind.camera")}</span>
|
||||
</div>
|
||||
<div className="objinfo-section-label">{t("objinfo.camera.section")}</div>
|
||||
<label className="objinfo-field">
|
||||
<span className="objinfo-flabel">{t("objinfo.camera.name")}</span>
|
||||
<input
|
||||
className="objinfo-text"
|
||||
type="text"
|
||||
defaultValue={cam.name}
|
||||
key={`nm-${cam.id}-${cam.name}`}
|
||||
disabled={locked}
|
||||
data-testid="camera-name"
|
||||
onBlur={(e) => {
|
||||
const v = e.target.value.trim();
|
||||
if (v && v !== cam.name) set({ name: v });
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") (e.target as HTMLInputElement).blur();
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<div className="objinfo-field">
|
||||
<span className="objinfo-flabel">{t("objinfo.camera.projection")}</span>
|
||||
<Dropdown
|
||||
value={cam.projection}
|
||||
onChange={(v) => set({ projection: v as CameraProjection }, true)}
|
||||
options={PROJECTIONS.map((v) => ({ value: v, label: t(`objinfo.camera.projection.${v}` as TranslationKey) }))}
|
||||
title={t("objinfo.camera.projection")}
|
||||
width={150}
|
||||
/>
|
||||
</div>
|
||||
<div className="objinfo-section-label">{t("objinfo.camera.stand")}</div>
|
||||
<DimensionField label="X" value={cam.position.x} min={-Infinity} onCommit={(v) => set({ position: { x: v, y: cam.position.y } })} />
|
||||
<DimensionField label="Y" value={cam.position.y} min={-Infinity} onCommit={(v) => set({ position: { x: cam.position.x, y: v } })} />
|
||||
<DimensionField label={t("objinfo.camera.eyeHeight")} value={cam.eyeHeight} min={0} onCommit={(v) => set({ eyeHeight: v })} />
|
||||
<div className="objinfo-section-label">{t("objinfo.camera.target")}</div>
|
||||
<DimensionField label="X" value={cam.target.x} min={-Infinity} onCommit={(v) => set({ target: { x: v, y: cam.target.y } })} />
|
||||
<DimensionField label="Y" value={cam.target.y} min={-Infinity} onCommit={(v) => set({ target: { x: cam.target.x, y: v } })} />
|
||||
<DimensionField label={t("objinfo.camera.targetHeight")} value={cam.targetHeight} min={-Infinity} onCommit={(v) => set({ targetHeight: v })} />
|
||||
{parallel ? (
|
||||
<DimensionField label={t("objinfo.camera.orthoHeight")} value={cam.orthoHeight ?? 10} min={0.1} onCommit={(v) => set({ orthoHeight: v })} />
|
||||
) : (
|
||||
<>
|
||||
<DimensionField label={t("objinfo.camera.fov")} value={cam.fovDeg} min={5} unit="°" step={1} digits={1} onCommit={(v) => set({ fovDeg: clampFov(v) })} />
|
||||
<DimensionField
|
||||
label={t("objinfo.camera.focal")}
|
||||
value={focalFromFov(cam.fovDeg)}
|
||||
min={5}
|
||||
unit="mm"
|
||||
step={1}
|
||||
digits={1}
|
||||
onCommit={(v) => set({ fovDeg: clampFov(fovFromFocal(v)) })}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<label className="objinfo-field">
|
||||
<span className="objinfo-flabel">{t("objinfo.camera.sun")}</span>
|
||||
<input
|
||||
className="objinfo-text"
|
||||
type="datetime-local"
|
||||
value={toLocalInput(cam.sunWhen)}
|
||||
disabled={locked}
|
||||
title={t("objinfo.camera.sunHint")}
|
||||
data-testid="camera-sun"
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
if (!v) {
|
||||
set({ sunWhen: undefined });
|
||||
return;
|
||||
}
|
||||
const d = new Date(`${v}:00Z`);
|
||||
if (Number.isFinite(d.getTime())) set({ sunWhen: d.toISOString().replace(".000Z", "Z") });
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<div className="objinfo-field">
|
||||
<span className="objinfo-flabel">{t("objinfo.column.floor")}</span>
|
||||
<span className="objinfo-fval">{level?.name ?? cam.floorId}</span>
|
||||
</div>
|
||||
<div className="objinfo-actions">
|
||||
<button type="button" className="btn" data-testid="camera-open" onClick={() => void openCamera(cam.id)}>
|
||||
{t("camera.open")}
|
||||
</button>
|
||||
<button type="button" className="btn" disabled={locked} data-testid="camera-update" onClick={() => updateCameraFromView(cam.id)} title={t("camera.updateHint")}>
|
||||
{t("camera.update")}
|
||||
</button>
|
||||
{parallel && (
|
||||
<button type="button" className="btn" disabled={locked} data-testid="camera-iso" onClick={() => set(isometricAim(project, cam))} title={t("camera.isoHint")}>
|
||||
{t("camera.iso")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{locked && <div className="objinfo-muted">{t("objinfo.camera.locked")}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -18,7 +18,7 @@ const AREA_TITLE = { object: "objsettings.area.object", appearance: "objsettings
|
||||
export function ObjectSettingsPanel() {
|
||||
const host = usePanelHost();
|
||||
const sel = useSelectionInfo();
|
||||
const otherSelected = useStore((s) => s.selection.trees.length + s.selection.site.length > 0);
|
||||
const otherSelected = useStore((s) => s.selection.trees.length + s.selection.cameras.length + s.selection.site.length > 0);
|
||||
const isGrid = useStore((s) => (sel?.kind === "drawing2d" ? s.project.drawings2d.find((d) => d.id === sel.id)?.geom.shape === "grid" : false));
|
||||
const wanted = useSyncExternalStore(subscribeSettingsArea, getSettingsArea, getSettingsArea);
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
viewBox -41.5 0 95 63.6
|
||||
bytes 66746
|
||||
bytes 68392
|
||||
circle 16
|
||||
g 1
|
||||
line 137
|
||||
line 141
|
||||
path 36
|
||||
polygon 93
|
||||
polyline 92
|
||||
polygon 101
|
||||
polyline 93
|
||||
rect 1
|
||||
svg 1
|
||||
text 115
|
||||
tspan 24
|
||||
hash 4a93fe9c7cb11710
|
||||
text 116
|
||||
tspan 25
|
||||
hash f73dd9a2827e46a8
|
||||
@@ -1,13 +1,13 @@
|
||||
viewBox -41.5 0 95 63.6
|
||||
bytes 107258
|
||||
bytes 108914
|
||||
circle 16
|
||||
g 1
|
||||
line 361
|
||||
line 365
|
||||
path 67
|
||||
polygon 216
|
||||
polyline 101
|
||||
polygon 224
|
||||
polyline 102
|
||||
rect 1
|
||||
svg 1
|
||||
text 115
|
||||
tspan 24
|
||||
hash c3b14e3bb9cdc26c
|
||||
text 116
|
||||
tspan 25
|
||||
hash 4e369fc245359944
|
||||
@@ -8,7 +8,7 @@ import { flattenCategories } from "../model/types";
|
||||
/** Art eines auswählbaren Objekts an einer Klickstelle (Reihenfolge = Standard-Priorität). */
|
||||
export type PickKind =
|
||||
| "section" | "opening" | "wall" | "column" | "drawing" | "solid"
|
||||
| "tree" | "ceiling" | "stair" | "room" | "roof" | "site" | "context";
|
||||
| "tree" | "camera" | "ceiling" | "stair" | "room" | "roof" | "site" | "context";
|
||||
|
||||
type WithCategory = { id: string; categoryCode?: string };
|
||||
|
||||
@@ -26,6 +26,7 @@ function collection(project: Project, kind: PickKind): readonly WithCategory[] {
|
||||
case "context": return p.context ?? [];
|
||||
case "solid": return p.extrudedSolids ?? [];
|
||||
case "tree": return p.trees ?? [];
|
||||
case "camera": return p.cameras ?? [];
|
||||
case "section":
|
||||
case "site": return [];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// [213] Aktionen zu Kamera-Elementen (`Project.cameras`): aus der aktuellen 3D-Ansicht anlegen, eine Kamera im 3D
|
||||
// öffnen (Ansicht exakt setzen, Sonne übernehmen), die Kamera mit der aktuellen Ansicht überschreiben. Die Umrechnung
|
||||
// Kamera ↔ Ansicht steht rein in `viewport/cameraView.ts`; hier hängt sie am Store, an den Reitern und am Viewport.
|
||||
|
||||
import { addItems, patchItem, setField } from "../core";
|
||||
import { t } from "../i18n";
|
||||
import type { Camera } from "../model/types";
|
||||
import { getCamera, getCameraTargetDistance, setCamera, viewportAvailable } from "../viewport/cameraBridge";
|
||||
import { cameraFromView, cameraToView, nextCameraName } from "../viewport/cameraView";
|
||||
import { getState } from "./appStore";
|
||||
import { fromIds } from "./selection";
|
||||
import { switchViewType } from "./tabNavigation";
|
||||
|
||||
function newCameraId(): string {
|
||||
const r = typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID().slice(0, 8) : Math.random().toString(36).slice(2, 10);
|
||||
return `cam-${r}`;
|
||||
}
|
||||
|
||||
/** Kamera aus der aktuellen 3D-Ansicht anlegen und wählen. Gibt die id zurück, `null` ohne 3D-Ansicht. */
|
||||
export function createCameraFromView(): string | null {
|
||||
const st = getState();
|
||||
const view = viewportAvailable() ? getCamera() : null;
|
||||
if (!view) {
|
||||
st.notify(t("camera.noViewport"), "warning");
|
||||
return null;
|
||||
}
|
||||
const cam = cameraFromView(st.project, view, {
|
||||
id: newCameraId(),
|
||||
name: nextCameraName(st.project, t("camera.defaultName")),
|
||||
fallbackFloorId: st.activeLevelId,
|
||||
distance: getCameraTargetDistance() ?? undefined,
|
||||
});
|
||||
st.applyChange(addItems("cameras", [cam]));
|
||||
st.setSelection(fromIds("cameras", [cam.id]));
|
||||
st.notify(t("camera.created", { name: cam.name }), "info");
|
||||
return cam.id;
|
||||
}
|
||||
|
||||
/** Wartet (höchstens `timeoutMs`), bis der 3D-Viewport Kamera-Zugriff meldet — nach dem Wechsel in den 3D-Reiter. */
|
||||
function whenViewportReady(timeoutMs = 3000): Promise<boolean> {
|
||||
if (viewportAvailable()) return Promise.resolve(true);
|
||||
return new Promise((resolve) => {
|
||||
const t0 = performance.now();
|
||||
const poll = () => {
|
||||
if (viewportAvailable()) resolve(true);
|
||||
else if (performance.now() - t0 > timeoutMs) resolve(false);
|
||||
else requestAnimationFrame(poll);
|
||||
};
|
||||
requestAnimationFrame(poll);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Kamera im 3D öffnen: in den 3D-Reiter wechseln, die Ansicht exakt setzen (Standpunkt, Blickrichtung, Bildwinkel,
|
||||
* Projektion) und — hat die Kamera einen Sonnenstand — die Sonnenstudie darauf stellen (Schatten im 3D an).
|
||||
*/
|
||||
export async function openCamera(id: string): Promise<boolean> {
|
||||
const st = getState();
|
||||
const cam = (st.project.cameras ?? []).find((c) => c.id === id);
|
||||
if (!cam) return false;
|
||||
const view = cameraToView(st.project, cam);
|
||||
if (!view) {
|
||||
st.notify(t("camera.invalid", { name: cam.name }), "warning");
|
||||
return false;
|
||||
}
|
||||
if (!viewportAvailable()) switchViewType("perspektive");
|
||||
if (!(await whenViewportReady())) {
|
||||
st.notify(t("camera.noViewport"), "warning");
|
||||
return false;
|
||||
}
|
||||
// Seitenverhältnis des Viewports behalten (die Brücke füllt es aus der Live-Kamera).
|
||||
const live = getCamera();
|
||||
const placed = setCamera({ ...view, aspect: live?.aspect ?? view.aspect }, { animate: true });
|
||||
if (!placed) {
|
||||
st.notify(t("camera.invalid", { name: cam.name }), "warning");
|
||||
return false;
|
||||
}
|
||||
if (cam.sunWhen && Number.isFinite(new Date(cam.sunWhen).getTime())) {
|
||||
const study = getState().project.sunStudy;
|
||||
if (study?.when !== cam.sunWhen || study.shadows3d !== true) {
|
||||
getState().applyChange([setField("sunStudy", { ...(study ?? { show: false }), when: cam.sunWhen, shadows3d: true } as NonNullable<typeof study>)]);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Kamera mit der aktuellen 3D-Ansicht überschreiben (Standpunkt, Ziel, Bildwinkel, Projektion; Name und Klasse bleiben). */
|
||||
export function updateCameraFromView(id: string): boolean {
|
||||
const st = getState();
|
||||
const old = (st.project.cameras ?? []).find((c) => c.id === id);
|
||||
const view = viewportAvailable() ? getCamera() : null;
|
||||
if (!old || !view) {
|
||||
st.notify(t("camera.noViewport"), "warning");
|
||||
return false;
|
||||
}
|
||||
const fresh = cameraFromView(st.project, view, {
|
||||
id: old.id,
|
||||
name: old.name,
|
||||
fallbackFloorId: old.floorId,
|
||||
distance: getCameraTargetDistance() ?? undefined,
|
||||
categoryCode: old.categoryCode,
|
||||
});
|
||||
const next: Camera = { ...old, ...fresh, locked: old.locked, sunWhen: old.sunWhen };
|
||||
if (fresh.projection === "perspective") delete next.orthoHeight;
|
||||
st.applyChange((p) => patchItem(p, "cameras", id, () => next));
|
||||
st.notify(t("camera.updated", { name: old.name }), "info");
|
||||
return true;
|
||||
}
|
||||
@@ -61,7 +61,8 @@ export type ShortcutId =
|
||||
| "fitAll"
|
||||
| "fitSelection"
|
||||
| "isolateLayer"
|
||||
| "toggleTrace";
|
||||
| "toggleTrace"
|
||||
| "walkMode";
|
||||
|
||||
export type ShortcutCategory =
|
||||
| "general"
|
||||
@@ -236,6 +237,9 @@ export const SHORTCUT_DEFS: ShortcutDef[] = [
|
||||
{ id: "isolateLayer", category: "navigation", labelKey: "shortcut.isolateLayer", defaultCombo: "mod+shift+l" },
|
||||
// [205] Pausfolie ein/aus (Archicad „Referenz ein/aus"); T wie Trace, frei neben den übrigen Cmd+Shift-Kürzeln.
|
||||
{ id: "toggleTrace", category: "navigation", labelKey: "shortcut.toggleTrace", defaultCombo: "mod+shift+t" },
|
||||
// [213] Begehen im 3D (WASD): Umschalt+F schaltet den Begehen-Modus; die Bewegungstasten selbst (W/A/S/D, Q/E, Pfeile) gelten nur
|
||||
// darin, damit sie nicht mit „s" (Spiegeln), „d" (Drehen) und „q" (Messen) kollidieren (`viewport/walk.ts`).
|
||||
{ id: "walkMode", category: "navigation", labelKey: "shortcut.walkMode", defaultCombo: "shift+f" },
|
||||
];
|
||||
|
||||
const DEFS_BY_ID = new Map<ShortcutId, ShortcutDef>(SHORTCUT_DEFS.map((d) => [d.id, d]));
|
||||
|
||||
@@ -34,7 +34,7 @@ export interface SelectionAppearance {
|
||||
|
||||
/** Zahl der gewählten Elemente (ohne Gruppen, Schnittlinien, Lage-Darstellung, Bäume). */
|
||||
export function selectedCount(sel: Selection): number {
|
||||
return ELEMENT_KINDS.filter((k) => k !== "sectionLines" && k !== "site" && k !== "trees").reduce((n, k) => n + sel[k].length, 0);
|
||||
return ELEMENT_KINDS.filter((k) => k !== "sectionLines" && k !== "site" && k !== "trees" && k !== "cameras").reduce((n, k) => n + sel[k].length, 0);
|
||||
}
|
||||
|
||||
/** Effektive Strichstärke und Farbe über die gewählten Wände/Decken/2D-Elemente. */
|
||||
|
||||
@@ -23,7 +23,7 @@ export function openObjectSettings(deps: ObjectSettingsDeps): boolean {
|
||||
const sel = selectionInfoFor(project, selection);
|
||||
let target = objectSettingsTarget(sel, deps.activeTool, isGridDrawing(sel?.kind === "drawing2d" ? sel.id : undefined));
|
||||
// Baum, Lage-Darstellung und Schnittlinie sind keine `SelectionInfo`, haben aber ihre Felder in der Objekt-Info.
|
||||
if (!target && (selection.trees.length > 0 || selection.site.length > 0 || selection.sectionLines.length > 0)) {
|
||||
if (!target && (selection.trees.length > 0 || selection.cameras.length > 0 || selection.site.length > 0 || selection.sectionLines.length > 0)) {
|
||||
target = { group: selection.sectionLines.length > 0 ? "sectionLine" : null };
|
||||
}
|
||||
if (!target) return false;
|
||||
|
||||
@@ -390,6 +390,8 @@ export interface ProjectSlice {
|
||||
moveExcavationGrip: (id: string, index: number, pt: Vec2) => void;
|
||||
/** [176] Griff einer Schnittlinie: 0 = Anfang, dann die Knickpunkte, zuletzt das Ende. */
|
||||
moveSectionLineGrip: (id: string, index: number, pt: Vec2, coalesceKey?: string) => void;
|
||||
/** [213] Griff einer Kamera: 0 = Standpunkt, 1 = Ziel, 2 = Bildwinkel/Sichtbreite. */
|
||||
moveCameraGrip: (id: string, index: number, pt: Vec2) => void;
|
||||
/** [176] Knick in Segment `seg` (Mittel-Griff) einfügen; `coalesceKey` fasst den anschliessenden Zug zusammen. */
|
||||
insertSectionBend: (id: string, seg: number, pt: Vec2, coalesceKey?: string) => void;
|
||||
/** [176] Knick löschen (`index` wie bei {@link moveSectionLineGrip}; Anfang/Ende lassen sich nicht löschen). */
|
||||
@@ -1298,6 +1300,7 @@ export function createProjectSlice(
|
||||
moveExcavationGrip: (id, index, pt) => applyGrip({ op: "excavationGrip", id, index, pt: gripPt(pt) }, `moveExcavationGrip:${id}:${index}`),
|
||||
moveSectionLineGrip: (id, index, pt, coalesceKey) =>
|
||||
applyGrip({ op: "sectionLineGrip", id, index, pt: gripPt(pt) }, coalesceKey ?? `moveSectionLineGrip:${id}:${index}`),
|
||||
moveCameraGrip: (id, index, pt) => applyGrip({ op: "cameraGrip", id, index, pt: gripPt(pt) }, `moveCameraGrip:${id}:${index}`),
|
||||
insertSectionBend: (id, seg, pt, coalesceKey) => applyGrip({ op: "sectionBendInsert", id, seg, pt: gripPt(pt) }, coalesceKey),
|
||||
deleteSectionBend: (id, index) => applyGrip({ op: "sectionBendDelete", id, index }),
|
||||
moveRingVertex: (kind, id, index, pt, coalesceKey) => {
|
||||
|
||||
@@ -39,6 +39,8 @@ export interface Selection {
|
||||
site: string[];
|
||||
/** [149] Bäume (`Project.trees`). */
|
||||
trees: string[];
|
||||
/** [213] Kameras (`Project.cameras`). */
|
||||
cameras: string[];
|
||||
/**
|
||||
* Gewählte Gruppen — rein informativ (Bounding-Box, Doppelklick-Ziel); die
|
||||
* Mitglieder stehen zusätzlich in den übrigen Arten (s. `groupActions.ts`).
|
||||
@@ -63,6 +65,7 @@ export const SELECTION_KINDS: readonly SelectionKind[] = [
|
||||
"sectionLines",
|
||||
"site",
|
||||
"trees",
|
||||
"cameras",
|
||||
"groups",
|
||||
];
|
||||
|
||||
@@ -184,6 +187,8 @@ export interface SelectionIdLists {
|
||||
groupIds: string[];
|
||||
/** [149] Bäume (nicht gruppierbar; Zwischenablage, Nachauswahl). */
|
||||
treeIds?: string[];
|
||||
/** [213] Kameras (nicht gruppierbar). */
|
||||
cameraIds?: string[];
|
||||
}
|
||||
|
||||
const ID_LIST_KEYS: [SelectionKind, keyof SelectionIdLists][] = [
|
||||
@@ -200,6 +205,7 @@ const ID_LIST_KEYS: [SelectionKind, keyof SelectionIdLists][] = [
|
||||
["sectionLines", "sectionLineIds"],
|
||||
["groups", "groupIds"],
|
||||
["trees", "treeIds"],
|
||||
["cameras", "cameraIds"],
|
||||
];
|
||||
|
||||
/** Auswahl → `…Ids`-Listen (passt strukturell auf `GroupMembership` und `BcfSelection`). */
|
||||
|
||||
@@ -63,5 +63,5 @@ export function hideSelectionIn3d(): void {
|
||||
const ids = selectionIds3d(st.selection);
|
||||
if (!ids.length) return;
|
||||
setView3dFilter(hideSelection3d(getView3dFilter(), ids));
|
||||
st.setSelection(clearKinds("walls", "ceilings", "openings", "stairs", "solids", "columns", "roofs", "contextObjects", "trees", "drawings", "groups"));
|
||||
st.setSelection(clearKinds("walls", "ceilings", "openings", "stairs", "solids", "columns", "roofs", "contextObjects", "trees", "cameras", "drawings", "groups"));
|
||||
}
|
||||
@@ -51,6 +51,7 @@ import { getPlanViewport, subscribePlanViewport } from "./planViewport";
|
||||
import { growRect, meshGripIndices } from "../core";
|
||||
import { patchItem, verticalExtents } from "../core";
|
||||
import { treeGripPatch, treeGripPoints } from "./treeGrips";
|
||||
import { cameraGripPoints } from "../core";
|
||||
import type { Selection } from "./selection";
|
||||
|
||||
export interface GripEditFieldsState {
|
||||
@@ -209,6 +210,9 @@ export function useGripEditing(opts: {
|
||||
const meshViewport = useSyncExternalStore(subscribePlanViewport, () => (selectedMesh && selectedMesh.positions.length / 3 > 600 ? getPlanViewport() : null));
|
||||
const selectedTreeId = single(selection, "trees");
|
||||
const selectedTree = selectedTreeId ? (project.trees ?? []).find((x) => x.id === selectedTreeId) : undefined;
|
||||
// [213] Kamera: Griffe an Standpunkt, Ziel und Sichtkegel-Rand (Bildwinkel); nur auf dem Geschoss der Kamera.
|
||||
const selectedCameraId = single(selection, "cameras");
|
||||
const selectedCamera = selectedCameraId ? (project.cameras ?? []).find((x) => x.id === selectedCameraId && x.floorId === levelId) : undefined;
|
||||
// [176] Schnitt-/Ansichtslinie im Grundriss: Griffe an Anfang, Knickpunkten (`bendPoints`) und Ende.
|
||||
const selectedSectionLineId = single(selection, "sectionLines");
|
||||
const selectedSectionLine = modelEditable && selectedSectionLineId
|
||||
@@ -510,6 +514,11 @@ export function useGripEditing(opts: {
|
||||
pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); });
|
||||
return pts;
|
||||
}
|
||||
if (selectedCamera && modelEditable && !selectedCamera.locked) {
|
||||
const pts = cameraGripPoints(selectedCamera, scaleDenominator);
|
||||
pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); });
|
||||
return pts;
|
||||
}
|
||||
if (selectedTree && modelEditable && !selectedTree.locked) {
|
||||
const pts = treeGrips(selectedTree);
|
||||
pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); });
|
||||
@@ -1238,6 +1247,11 @@ export function useGripEditing(opts: {
|
||||
else if (st) moveStairBy(st.id, sub(pt, stairMoveHandle(st)));
|
||||
return;
|
||||
}
|
||||
// [213] Kamera: Standpunkt, Ziel bzw. Sichtkegel-Rand live (Kern `camera::grip_edit`), ein Undo-Schritt je Zug.
|
||||
if (selectedCamera) {
|
||||
if (!selectedCamera.locked) storeState().moveCameraGrip(selectedCamera.id, index, pt);
|
||||
return;
|
||||
}
|
||||
// [149] Baum: Stammmitte, Kronenrand bzw. Beschriftung live, ein Undo-Schritt je Zug (gleicher coalesceKey).
|
||||
if (selectedTree) {
|
||||
const tr = selectedTree;
|
||||
|
||||
@@ -215,6 +215,7 @@ export function useMouseSelectionHandlers(opts: {
|
||||
context: "contextObjects",
|
||||
site: "site",
|
||||
tree: "trees",
|
||||
camera: "cameras",
|
||||
} as const satisfies Record<string, SelectionKind>;
|
||||
type Kind = keyof typeof channels;
|
||||
const target: { kind: Kind; id: string } | null = sel.sectionLineId
|
||||
@@ -235,6 +236,8 @@ export function useMouseSelectionHandlers(opts: {
|
||||
? { kind: "solid", id: sel.extrudedSolidId }
|
||||
: sel.treeId
|
||||
? { kind: "tree", id: sel.treeId }
|
||||
: sel.cameraId
|
||||
? { kind: "camera", id: sel.cameraId }
|
||||
: sel.columnId
|
||||
? { kind: "column", id: sel.columnId }
|
||||
: sel.roofId
|
||||
@@ -301,7 +304,9 @@ export function useMouseSelectionHandlers(opts: {
|
||||
? ["site", sel.siteId]
|
||||
: sel.treeId
|
||||
? ["trees", sel.treeId]
|
||||
: null;
|
||||
: sel.cameraId
|
||||
? ["cameras", sel.cameraId]
|
||||
: null;
|
||||
setSelection({ ...clearKinds(), groups: [], ...(one ? { [one[0]]: [one[1]] } : {}) });
|
||||
};
|
||||
// Links-Drag (Marquee) im Grundriss: die getroffene Wand-MENGE übernehmen
|
||||
@@ -353,6 +358,7 @@ export function useMouseSelectionHandlers(opts: {
|
||||
stairs: expanded.stairIds,
|
||||
rooms: expanded.roomIds,
|
||||
trees: expanded.treeIds,
|
||||
cameras: sel.cameraIds ?? [],
|
||||
groups: groupIds,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -151,6 +151,8 @@ export function useSelectionCommands(opts: {
|
||||
const ctxids = new Set(selection.contextObjects);
|
||||
// [149] Bäume (gesperrte bleiben).
|
||||
const treeids = new Set(selection.trees.filter((id) => !(project.trees ?? []).find((t) => t.id === id)?.locked));
|
||||
// [213] Kameras (gesperrte bleiben).
|
||||
const camids = new Set(selection.cameras.filter((id) => !(project.cameras ?? []).find((c) => c.id === id)?.locked));
|
||||
// [193] Abgeleitete Lage-Darstellung (Schatten, Baurecht) ist kein Element: Entf blendet sie aus
|
||||
// (`show: false`; über die Lage-Panels wieder einschaltbar).
|
||||
const siteHide: ReturnType<typeof fieldOps> = [];
|
||||
@@ -175,6 +177,7 @@ export function useSelectionCommands(opts: {
|
||||
...removeItems(p, "openings", (o) => oids.has(o.id) || wids.has(o.hostWallId) || (!!o.hostRoofId && rfids.has(o.hostRoofId)) || (!!o.hostCeilingId && cids.has(o.hostCeilingId))),
|
||||
...removeItems(p, "context", ctxids),
|
||||
...removeItems(p, "trees", treeids),
|
||||
...removeItems(p, "cameras", camids),
|
||||
]),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -2089,6 +2089,36 @@ body {
|
||||
height: 100% !important;
|
||||
}
|
||||
|
||||
/* [213] Begehen und Kamera anlegen: kleine Knöpfe oben rechts im 3D-Viewport. */
|
||||
.viewport3d-tools {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 8px;
|
||||
z-index: 6;
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
.viewport3d-tool {
|
||||
padding: 3px 9px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
background: var(--panel);
|
||||
color: var(--label);
|
||||
font-size: 11px;
|
||||
cursor: pointer;
|
||||
opacity: 0.85;
|
||||
}
|
||||
.viewport3d-tool:hover {
|
||||
background: var(--panel-2);
|
||||
opacity: 1;
|
||||
}
|
||||
.viewport3d-tool.is-on {
|
||||
background: var(--active-dim);
|
||||
border-color: var(--active-light);
|
||||
color: var(--active-light);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.viewport-fallback {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
|
||||
@@ -11,6 +11,8 @@ kommt als Teile aus dem Kern (`src/plan/toWalls3d.ts`). Weg eines Modells in den
|
||||
| `Wasm3DViewport.tsx` | die 3D-Ansicht: Canvas, Maus und Tastatur, Auswahl, Griffe, Cursor-HUD, Live-Schnitt |
|
||||
| `Viewport3D.tsx` | Zugang zur Ansicht (`Viewport3D = Wasm3DViewport`) und die geteilten Typen (`RenderDisplay`, `DisplayResolver`) |
|
||||
| `useWasm3dRenderer.ts` | Hook: lädt render3d, hält Modell, Kamera und Punktwolken, zeichnet; Typ `Camera3d` |
|
||||
| `cameraView.ts` | [213] Kamera-Element (`Project.cameras`) ↔ Sicht des Viewports: `cameraToView`, `cameraFromView`, Brennweite, Geschoss zur Höhe |
|
||||
| `walk.ts` | [213] Begehen (WASD): Bewegung und Umschauen als reine Funktionen auf dem Orbit-Zustand |
|
||||
| `cameraBridge.ts` | Kamera von aussen lesen und setzen, Bild-Schnappschuss, Live-Schnittebene (für BCF-Viewpoints) |
|
||||
|
||||
## Abgleich mit render3d
|
||||
|
||||
@@ -81,6 +81,9 @@ import {
|
||||
type OrbitState,
|
||||
type V3 as CamV3,
|
||||
} from "./cameraBridge";
|
||||
import { NO_KEYS, WALK_SPEED, anyKey, lookAround, speedFactor, stepWalk, walkKeyAllowed, walkKeyOf, type WalkKeys } from "./walk";
|
||||
import { loadShortcutOverrides, matchesShortcut } from "../state/keyboardShortcuts";
|
||||
import { createCameraFromView } from "../state/cameraActions";
|
||||
|
||||
/** Ein per 3D-Klick getroffenes Bauteil, oder null (Leerraum). */
|
||||
export type Pick3dHit =
|
||||
@@ -594,6 +597,10 @@ export function Wasm3DViewport({
|
||||
// stabile Pointer-Listener-Effekt stets den aktuellen Befehlszustand liest.
|
||||
const commandActiveRef = useRef(commandActive);
|
||||
commandActiveRef.current = commandActive;
|
||||
// [213] Begehen-Modus (Umschalt+F / Knopf): WASD, Q/E und Pfeile bewegen die Kamera, Maus ziehen schaut um.
|
||||
const [walkMode, setWalkMode] = useState(false);
|
||||
const walkModeRef = useRef(false);
|
||||
walkModeRef.current = walkMode;
|
||||
const onWorkplanePointRef = useRef(onWorkplanePoint);
|
||||
onWorkplanePointRef.current = onWorkplanePoint;
|
||||
const onWorkplaneConfirmRef = useRef(onWorkplaneConfirm);
|
||||
@@ -1381,6 +1388,89 @@ export function Wasm3DViewport({
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, []);
|
||||
|
||||
// [213] Begehen (WASD): Umschalt+F schaltet den Modus, darin bewegen W/A/S/D und die Pfeiltasten die Kamera
|
||||
// (vor/zurück/seitlich in der Horizontalen, Augenhöhe bleibt), Q/E senken und heben, Umschalt = schneller, Alt =
|
||||
// langsamer. Die Tasten gelten NUR im Modus — sonst kollidieren sie mit „s" (Spiegeln), „d" (Drehen), „q" (Messen).
|
||||
// Pro Frame (rAF) mit gekapptem Zeitschritt; Textfelder und Befehls-Modifikatoren (Strg/Cmd) sperren. Rechnung rein
|
||||
// in `walk.ts`. Die Handler laufen in der Capture-Phase und verbrauchen die Bewegungstasten, damit globale Kürzel
|
||||
// nicht zusätzlich feuern.
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
const keys: WalkKeys = { ...NO_KEYS };
|
||||
const mods = { shift: false, alt: false };
|
||||
let raf = 0;
|
||||
let last = 0;
|
||||
const redrawOrbit = () => {
|
||||
redrawRef.current = () => {
|
||||
if (orbitRef.current) render(orbitCamera(orbitRef.current));
|
||||
};
|
||||
redrawRef.current();
|
||||
};
|
||||
const tick = (now: number) => {
|
||||
raf = 0;
|
||||
if (!walkModeRef.current || !anyKey(keys)) return;
|
||||
const o = orbitRef.current;
|
||||
if (o) {
|
||||
const dt = last ? (now - last) / 1000 : 0;
|
||||
orbitRef.current = stepWalk(o, keys, dt, WALK_SPEED * speedFactor(mods.shift, mods.alt));
|
||||
redrawOrbit();
|
||||
}
|
||||
last = now;
|
||||
raf = requestAnimationFrame(tick);
|
||||
};
|
||||
const start = () => {
|
||||
if (raf === 0) {
|
||||
last = 0;
|
||||
raf = requestAnimationFrame(tick);
|
||||
}
|
||||
};
|
||||
const release = () => {
|
||||
Object.assign(keys, NO_KEYS);
|
||||
};
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
mods.shift = e.shiftKey;
|
||||
mods.alt = e.altKey;
|
||||
if (!walkKeyAllowed(e, document.activeElement)) return;
|
||||
if (!e.repeat && matchesShortcut(e, "walkMode", loadShortcutOverrides())) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setWalkMode((w) => !w);
|
||||
release();
|
||||
return;
|
||||
}
|
||||
if (!walkModeRef.current || commandActiveRef.current || gripDragRef.current) return;
|
||||
if (e.key === "Escape") {
|
||||
setWalkMode(false);
|
||||
release();
|
||||
return;
|
||||
}
|
||||
const k = walkKeyOf(e.code);
|
||||
if (!k) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
keys[k] = true;
|
||||
start();
|
||||
};
|
||||
const onKeyUp = (e: KeyboardEvent) => {
|
||||
mods.shift = e.shiftKey;
|
||||
mods.alt = e.altKey;
|
||||
const k = walkKeyOf(e.code);
|
||||
if (k && keys[k]) {
|
||||
keys[k] = false;
|
||||
e.stopPropagation();
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown, true);
|
||||
window.addEventListener("keyup", onKeyUp, true);
|
||||
window.addEventListener("blur", release);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKeyDown, true);
|
||||
window.removeEventListener("keyup", onKeyUp, true);
|
||||
window.removeEventListener("blur", release);
|
||||
cancelAnimationFrame(raf);
|
||||
};
|
||||
}, [ready, render]);
|
||||
|
||||
// Maus-Navigation (LINKS = Orbit, MITTE/RECHTS = Pan, RAD = Zoom, s.
|
||||
// Datei-Kommentar MAUS-SCHEMA). Verlässt damit IMMER die Praeset-Kamera und
|
||||
// wechselt auf die freie perspektivische Orbit-Kamera (Kontinuität über den
|
||||
@@ -1398,7 +1488,7 @@ export function Wasm3DViewport({
|
||||
};
|
||||
|
||||
let drag: {
|
||||
mode: "orbit" | "pan";
|
||||
mode: "orbit" | "pan" | "look";
|
||||
button: number;
|
||||
x: number;
|
||||
y: number;
|
||||
@@ -1469,7 +1559,8 @@ export function Wasm3DViewport({
|
||||
};
|
||||
|
||||
const onPointerDown = (e: PointerEvent) => {
|
||||
const mode = e.button === 0 ? "orbit" : e.button === 1 || e.button === 2 ? "pan" : null;
|
||||
// [213] Im Begehen-Modus schaut auch die rechte Taste um (statt zu schwenken); die mittlere schwenkt weiter.
|
||||
const mode = e.button === 0 ? "orbit" : e.button === 2 && walkModeRef.current ? "look" : e.button === 1 || e.button === 2 ? "pan" : null;
|
||||
if (!mode) return;
|
||||
e.preventDefault();
|
||||
drag = {
|
||||
@@ -1525,7 +1616,10 @@ export function Wasm3DViewport({
|
||||
return;
|
||||
}
|
||||
const h = canvas.clientHeight || 1;
|
||||
if (drag.mode === "orbit") {
|
||||
if (drag.mode === "look" || (drag.mode === "orbit" && walkModeRef.current)) {
|
||||
// [213] Umschauen um den Augpunkt (Orbit-Zustand bleibt die Wahrheit, das Ziel wandert mit).
|
||||
orbitRef.current = lookAround(o, dx, dy);
|
||||
} else if (drag.mode === "orbit") {
|
||||
// Winkel je Pixel wie OrbitControls: voller Umlauf über die Viewport-Höhe.
|
||||
o.yaw += (2 * Math.PI * dx) / h;
|
||||
o.pitch = Math.max(
|
||||
@@ -1716,6 +1810,30 @@ export function Wasm3DViewport({
|
||||
Darstellungsart kommen von der Oberleiste (TopBar); das Grid-Overlay
|
||||
unten ist der einzige eigene Umschalter hier. */}
|
||||
<canvas ref={canvasRef} data-engine="render3d" />
|
||||
{/* [213] Begehen (WASD) und Kamera aus der aktuellen Ansicht anlegen. */}
|
||||
<div className="viewport3d-tools" data-testid="viewport3d-tools">
|
||||
<button
|
||||
type="button"
|
||||
className={`viewport3d-tool${walkMode ? " is-on" : ""}`}
|
||||
aria-pressed={walkMode}
|
||||
title={t("walk.hint")}
|
||||
data-testid="walk-toggle"
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
onClick={() => setWalkMode((w) => !w)}
|
||||
>
|
||||
{t("walk.toggle")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="viewport3d-tool"
|
||||
title={t("viewport3d.camera.create")}
|
||||
data-testid="camera-create-3d"
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
onClick={() => createCameraFromView()}
|
||||
>
|
||||
{t("camera.defaultName")}+
|
||||
</button>
|
||||
</div>
|
||||
{/* Achsen-Lock-Führungslinie (Pfeiltasten während eines Endpunkt-/
|
||||
Verschiebe-Griff-Drags, s. `axisLockRef`-Dateikommentar) — SketchUp-
|
||||
Vorbild: eine durchgezogene farbige Linie durch den Anker markiert
|
||||
|
||||
@@ -242,6 +242,14 @@ export function getCamera(): ViewCamera | null {
|
||||
return r ? viewCameraFromCamera3d(r.camera, r.aspect) : null;
|
||||
}
|
||||
|
||||
/** [213] Abstand zwischen Augpunkt und Blickziel der Live-Kamera (Meter), oder null ohne Viewport. */
|
||||
export function getCameraTargetDistance(): number | null {
|
||||
const r = api?.read();
|
||||
if (!r) return null;
|
||||
const d = len(sub(r.camera.target, r.camera.eye));
|
||||
return Number.isFinite(d) && d > 0 ? d : null;
|
||||
}
|
||||
|
||||
/** Kamera setzen. `false` ohne Viewport oder bei unbrauchbarer Kamera (NaN, Nullvektor). */
|
||||
/** [C10] Systemeinstellung „Bewegung reduzieren": Kamerafahrten springen dann direkt ans Ziel. */
|
||||
export function prefersReducedMotion(): boolean {
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Camera, Project } from "../model/types";
|
||||
import { emptyProject } from "../model/sampleProject";
|
||||
import {
|
||||
cameraEye,
|
||||
cameraFromView,
|
||||
cameraToView,
|
||||
clampFov,
|
||||
floorForHeight,
|
||||
focalFromFov,
|
||||
fovFromFocal,
|
||||
isometricAim,
|
||||
nextCameraName,
|
||||
} from "./cameraView";
|
||||
import { camera3dFromViewCamera, viewCameraFromCamera3d } from "./cameraBridge";
|
||||
|
||||
const level = (id: string, baseElevation: number, kind: "floor" | "section" = "floor") =>
|
||||
({ id, name: id, kind, visible: true, locked: false, baseElevation, floorHeight: 2.8 }) as Project["drawingLevels"][number];
|
||||
|
||||
const project = (): Project => ({
|
||||
...emptyProject,
|
||||
drawingLevels: [level("eg", 0), level("og", 3), level("schnitt", 0, "section")],
|
||||
});
|
||||
|
||||
const cam = (over: Partial<Camera> = {}): Camera => ({
|
||||
id: "k1",
|
||||
type: "camera",
|
||||
name: "Süd",
|
||||
floorId: "og",
|
||||
categoryCode: "92",
|
||||
position: { x: 2, y: -3 },
|
||||
eyeHeight: 1.6,
|
||||
target: { x: 2, y: 7 },
|
||||
targetHeight: 4.6,
|
||||
fovDeg: 50,
|
||||
projection: "perspective",
|
||||
...over,
|
||||
});
|
||||
|
||||
describe("[213] Kamera → Ansicht", () => {
|
||||
it("Augenhöhe liegt über der Geschoss-OK; Blickrichtung zeigt zum Ziel", () => {
|
||||
const p = project();
|
||||
expect(cameraEye(p, cam())).toEqual([2, -3, 4.6]);
|
||||
const v = cameraToView(p, cam())!;
|
||||
expect(v.kind).toBe("perspective");
|
||||
expect(v.position).toEqual([2, -3, 4.6]);
|
||||
expect(v.direction[0]).toBeCloseTo(0, 12);
|
||||
expect(v.direction[1]).toBeCloseTo(1, 12);
|
||||
expect(v.direction[2]).toBeCloseTo(0, 12);
|
||||
expect(v.fovDeg).toBe(50);
|
||||
// Up steht senkrecht zur Blickrichtung und zeigt nach oben.
|
||||
expect(v.up[2]).toBeCloseTo(1, 12);
|
||||
expect(v.up[0] * v.direction[0] + v.up[1] * v.direction[1] + v.up[2] * v.direction[2]).toBeCloseTo(0, 12);
|
||||
});
|
||||
|
||||
it("geneigter Blick: Up bleibt senkrecht und normiert", () => {
|
||||
const v = cameraToView(project(), cam({ targetHeight: 0 }))!;
|
||||
expect(v.direction[2]).toBeLessThan(0);
|
||||
expect(Math.hypot(...v.up)).toBeCloseTo(1, 12);
|
||||
expect(v.up[0] * v.direction[0] + v.up[1] * v.direction[1] + v.up[2] * v.direction[2]).toBeCloseTo(0, 12);
|
||||
expect(v.up[2]).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("senkrechter Blick nach unten: Up ist Norden (Grundriss-Lage)", () => {
|
||||
const v = cameraToView(project(), cam({ target: { x: 2, y: -3 }, targetHeight: 0 }))!;
|
||||
expect(v.direction[2]).toBeCloseTo(-1, 12);
|
||||
expect(v.up[1]).toBeCloseTo(1, 9);
|
||||
});
|
||||
|
||||
it("Axonometrie und Parallel sind orthogonal mit Sichthöhe; Bildwinkel wird geklemmt", () => {
|
||||
const a = cameraToView(project(), cam({ projection: "axonometric", orthoHeight: 8 }))!;
|
||||
expect(a.kind).toBe("orthogonal");
|
||||
expect(a.orthoHeight).toBe(8);
|
||||
expect(cameraToView(project(), cam({ projection: "parallel" }))!.orthoHeight).toBe(10);
|
||||
expect(cameraToView(project(), cam({ fovDeg: 500 }))!.fovDeg).toBe(120);
|
||||
expect(clampFov(NaN)).toBe(50);
|
||||
});
|
||||
|
||||
it("Standpunkt gleich Ziel oder NaN: keine Ansicht", () => {
|
||||
expect(cameraToView(project(), cam({ target: { x: 2, y: -3 }, targetHeight: 4.6 }))).toBeNull();
|
||||
expect(cameraToView(project(), cam({ position: { x: NaN, y: 0 } }))).toBeNull();
|
||||
});
|
||||
|
||||
it("liefert dieselbe Struktur wie die aktive 3D-Ansicht: Umweg über die Viewport-Kamera ist verlustfrei", () => {
|
||||
const v = cameraToView(project(), cam({ targetHeight: 2 }), 1.5)!;
|
||||
const c3 = camera3dFromViewCamera(v, 10)!;
|
||||
const back = viewCameraFromCamera3d(c3, 1.5)!;
|
||||
expect(back.kind).toBe(v.kind);
|
||||
back.position.forEach((x, i) => expect(x).toBeCloseTo(v.position[i], 9));
|
||||
back.direction.forEach((x, i) => expect(x).toBeCloseTo(v.direction[i], 9));
|
||||
back.up.forEach((x, i) => expect(x).toBeCloseTo(v.up[i], 9));
|
||||
expect(back.fovDeg).toBeCloseTo(v.fovDeg, 9);
|
||||
expect(back.aspect).toBe(1.5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("[213] Ansicht → Kamera", () => {
|
||||
it("Standpunkt bestimmt Geschoss und Augenhöhe; Ziel liegt auf der Blickachse", () => {
|
||||
const p = project();
|
||||
const view = cameraToView(p, cam({ targetHeight: 3.6 }))!;
|
||||
const made = cameraFromView(p, view, { id: "k2", name: "Neu", fallbackFloorId: "eg", distance: Math.hypot(10, 1) });
|
||||
expect(made.floorId).toBe("og");
|
||||
expect(made.eyeHeight).toBeCloseTo(1.6, 9);
|
||||
expect(made.position).toEqual({ x: 2, y: -3 });
|
||||
expect(made.target.x).toBeCloseTo(2, 9);
|
||||
expect(made.target.y).toBeCloseTo(7, 9);
|
||||
expect(made.targetHeight).toBeCloseTo(3.6, 9);
|
||||
expect(made.projection).toBe("perspective");
|
||||
expect(made.categoryCode).toBe("92");
|
||||
expect(made.type).toBe("camera");
|
||||
// Wieder in die Ansicht: dieselbe Kamera.
|
||||
const again = cameraToView(p, made)!;
|
||||
again.position.forEach((x, i) => expect(x).toBeCloseTo(view.position[i], 9));
|
||||
again.direction.forEach((x, i) => expect(x).toBeCloseTo(view.direction[i], 9));
|
||||
});
|
||||
|
||||
it("orthografische Ansicht wird zur Parallelprojektion mit Sichthöhe", () => {
|
||||
const p = project();
|
||||
const view = cameraToView(p, cam({ projection: "axonometric", orthoHeight: 12 }))!;
|
||||
const made = cameraFromView(p, view, { id: "k3", name: "Ortho", fallbackFloorId: "eg" });
|
||||
expect(made.projection).toBe("parallel");
|
||||
expect(made.orthoHeight).toBe(12);
|
||||
});
|
||||
|
||||
it("Geschoss zu einer Höhe: höchstes mit OK ≤ z, sonst das unterste, Schnitte zählen nicht", () => {
|
||||
const p = project();
|
||||
expect(floorForHeight(p, 4.6, "x")).toBe("og");
|
||||
expect(floorForHeight(p, 2.99, "x")).toBe("eg");
|
||||
expect(floorForHeight(p, -5, "x")).toBe("eg");
|
||||
expect(floorForHeight(p, NaN, "x")).toBe("x");
|
||||
expect(floorForHeight({ ...p, drawingLevels: [] }, 1, "fallback")).toBe("fallback");
|
||||
});
|
||||
|
||||
it("Namen zählen hoch", () => {
|
||||
const p = { ...project(), cameras: [cam({ name: "Kamera 1" }), cam({ id: "k2", name: "Kamera 2" })] };
|
||||
expect(nextCameraName(p, "Kamera")).toBe("Kamera 3");
|
||||
expect(nextCameraName(project(), "Kamera")).toBe("Kamera 1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("[213] Brennweite und Axonometrie", () => {
|
||||
it("Brennweite ↔ Bildwinkel (24 mm Sensorhöhe)", () => {
|
||||
expect(fovFromFocal(focalFromFov(50))).toBeCloseTo(50, 9);
|
||||
expect(fovFromFocal(35)).toBeCloseTo(37.85, 1);
|
||||
});
|
||||
|
||||
it("Isometrie-Ausrichtung behält das Ziel im Blick und neigt 35.264°", () => {
|
||||
const p = project();
|
||||
const c = cam({ projection: "axonometric" });
|
||||
const aim = isometricAim(p, c);
|
||||
const next = { ...c, ...aim };
|
||||
const v = cameraToView(p, next)!;
|
||||
// Blick nach oben-rechts hinten: 45° im Grundriss, 35.264° nach unten.
|
||||
expect(v.direction[0]).toBeCloseTo(Math.SQRT1_2 * Math.cos(Math.atan(1 / Math.SQRT2)), 6);
|
||||
expect(v.direction[1]).toBeCloseTo(Math.SQRT1_2 * Math.cos(Math.atan(1 / Math.SQRT2)), 6);
|
||||
expect(v.direction[2]).toBeCloseTo(-Math.sin(Math.atan(1 / Math.SQRT2)), 6);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
// [213] Kamera-Element (`Project.cameras`) ↔ Sicht des 3D-Viewports. Reine Funktionen, ohne React und Engine.
|
||||
//
|
||||
// `cameraToView` liefert dieselbe Struktur wie die aktive 3D-Ansicht (`getCamera()` der `cameraBridge`: Modell-
|
||||
// Koordinaten, z oben) — damit setzt „Kamera öffnen" den Viewport exakt, und das Rendering ([211]) kann eine
|
||||
// gespeicherte Kamera wie die Live-Ansicht verwenden. `cameraFromView` legt umgekehrt aus der Live-Ansicht ein
|
||||
// Kamera-Element an (Standpunkt → Geschoss + Augenhöhe).
|
||||
|
||||
import type { Camera, DrawingLevel, Project, Vec2 } from "../model/types";
|
||||
import { CAMERA_CATEGORY } from "../model/derivedCategories";
|
||||
import type { V3, ViewCamera } from "./cameraBridge";
|
||||
|
||||
/** Vorgaben wie im Kern (`camera.rs`). */
|
||||
export const DEFAULT_EYE_HEIGHT = 1.6;
|
||||
export const DEFAULT_FOV_DEG = 50;
|
||||
export const DEFAULT_ORTHO_HEIGHT = 10;
|
||||
export const MIN_FOV_DEG = 5;
|
||||
export const MAX_FOV_DEG = 120;
|
||||
/** Sensorhöhe für die Kleinbild-Brennweite (mm), wie im Kern. */
|
||||
export const SENSOR_HEIGHT_MM = 24;
|
||||
/** Blickweite beim Anlegen aus einer Ansicht, wenn der Viewport keinen Zielabstand meldet (m). */
|
||||
export const DEFAULT_AIM_DISTANCE = 10;
|
||||
|
||||
/** Kleinbild-Brennweite (mm) zum vertikalen Bildwinkel (Grad). */
|
||||
export function focalFromFov(fovDeg: number): number {
|
||||
return SENSOR_HEIGHT_MM / 2 / Math.tan((fovDeg * Math.PI) / 360);
|
||||
}
|
||||
|
||||
/** Vertikaler Bildwinkel (Grad) zur Kleinbild-Brennweite (mm). */
|
||||
export function fovFromFocal(mm: number): number {
|
||||
return (2 * Math.atan(SENSOR_HEIGHT_MM / 2 / mm) * 180) / Math.PI;
|
||||
}
|
||||
|
||||
export function clampFov(fovDeg: number): number {
|
||||
return Number.isFinite(fovDeg) && fovDeg > 0 ? Math.min(MAX_FOV_DEG, Math.max(MIN_FOV_DEG, fovDeg)) : DEFAULT_FOV_DEG;
|
||||
}
|
||||
|
||||
const finite = (...v: number[]): boolean => v.every(Number.isFinite);
|
||||
|
||||
/** Höhe der Geschoss-OK (m), 0 ohne Angabe. */
|
||||
export function floorBase(project: Project, floorId: string): number {
|
||||
const z = project.drawingLevels.find((l) => l.id === floorId)?.baseElevation;
|
||||
return typeof z === "number" && Number.isFinite(z) ? z : 0;
|
||||
}
|
||||
|
||||
/** Augpunkt der Kamera in Modell-Koordinaten (Meter, z oben). */
|
||||
export function cameraEye(project: Project, cam: Camera): V3 {
|
||||
return [cam.position.x, cam.position.y, floorBase(project, cam.floorId) + (Number.isFinite(cam.eyeHeight) ? cam.eyeHeight : DEFAULT_EYE_HEIGHT)];
|
||||
}
|
||||
|
||||
/** Ziel der Kamera in Modell-Koordinaten. */
|
||||
export function cameraTarget(cam: Camera): V3 {
|
||||
return [cam.target.x, cam.target.y, cam.targetHeight];
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Sicht der Kamera: Standpunkt, normierte Blickrichtung und Up-Vektor (senkrecht zur Blickrichtung, aus der
|
||||
* Modell-Senkrechten; bei exakt senkrechtem Blick gilt die Grundriss-Richtung „oben = Norden"). Perspektive →
|
||||
* `perspective`, Axonometrie und Parallel → `orthogonal`. Null bei Standpunkt = Ziel oder nicht endlichen Zahlen.
|
||||
*/
|
||||
export function cameraToView(project: Project, cam: Camera, aspect = 16 / 9): ViewCamera | null {
|
||||
const eye = cameraEye(project, cam);
|
||||
const tgt = cameraTarget(cam);
|
||||
if (!finite(...eye, ...tgt)) return null;
|
||||
const d: V3 = [tgt[0] - eye[0], tgt[1] - eye[1], tgt[2] - eye[2]];
|
||||
const len = Math.hypot(d[0], d[1], d[2]);
|
||||
if (!(len > 1e-9)) return null;
|
||||
const dir: V3 = [d[0] / len, d[1] / len, d[2] / len];
|
||||
// Up aus der Modell-Senkrechten; ist der Blick (fast) senkrecht, aus der Nordrichtung.
|
||||
const ref: V3 = Math.abs(dir[2]) > 0.9999 ? [0, 1, 0] : [0, 0, 1];
|
||||
const k = ref[0] * dir[0] + ref[1] * dir[1] + ref[2] * dir[2];
|
||||
const upRaw: V3 = [ref[0] - dir[0] * k, ref[1] - dir[1] * k, ref[2] - dir[2] * k];
|
||||
const ul = Math.hypot(upRaw[0], upRaw[1], upRaw[2]);
|
||||
const up: V3 = [upRaw[0] / ul, upRaw[1] / ul, upRaw[2] / ul];
|
||||
const ortho = cam.projection !== "perspective";
|
||||
return {
|
||||
kind: ortho ? "orthogonal" : "perspective",
|
||||
position: eye,
|
||||
direction: dir,
|
||||
up,
|
||||
fovDeg: clampFov(cam.fovDeg),
|
||||
orthoHeight: cam.orthoHeight && cam.orthoHeight > 0 ? cam.orthoHeight : DEFAULT_ORTHO_HEIGHT,
|
||||
aspect: Number.isFinite(aspect) && aspect > 0 ? aspect : 16 / 9,
|
||||
};
|
||||
}
|
||||
|
||||
/** Geschoss, auf dem ein Standpunkt der Höhe `z` steht: das höchste Geschoss mit OK ≤ z (sonst das unterste, sonst `fallback`). */
|
||||
export function floorForHeight(project: Project, z: number, fallback: string): string {
|
||||
const floors = project.drawingLevels.filter((l: DrawingLevel) => l.kind === "floor");
|
||||
if (!floors.length || !Number.isFinite(z)) return fallback;
|
||||
const base = (l: DrawingLevel) => (typeof l.baseElevation === "number" && Number.isFinite(l.baseElevation) ? l.baseElevation : 0);
|
||||
const sorted = [...floors].sort((a, b) => base(a) - base(b));
|
||||
let hit = sorted[0];
|
||||
for (const l of sorted) if (base(l) <= z + 1e-6) hit = l;
|
||||
return hit.id;
|
||||
}
|
||||
|
||||
/** Nächster freier Name „Kamera 1", „Kamera 2" … (`label` = Namensstamm). */
|
||||
export function nextCameraName(project: Project, label: string): string {
|
||||
const used = new Set((project.cameras ?? []).map((c) => c.name));
|
||||
for (let n = 1; ; n++) if (!used.has(`${label} ${n}`)) return `${label} ${n}`;
|
||||
}
|
||||
|
||||
export interface CameraFromViewOptions {
|
||||
id: string;
|
||||
name: string;
|
||||
/** Geschoss des Symbols; fehlt = das Geschoss, auf dem der Standpunkt steht. */
|
||||
floorId?: string;
|
||||
/** Rückfall-Geschoss, wenn das Projekt kein Geschoss kennt (aktive Ebene). */
|
||||
fallbackFloorId: string;
|
||||
/** Abstand des Ziels vom Standpunkt (m); fehlt = 10 m (orthografisch: die Sichthöhe). */
|
||||
distance?: number;
|
||||
categoryCode?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kamera-Element aus der Sicht des Viewports (Modell-Koordinaten): Standpunkt → Geschoss + Augenhöhe, Ziel auf
|
||||
* der Blickachse im Abstand `distance`. Orthografische Sichten werden zu „parallel" (das Preset-Verhalten der
|
||||
* Axonometrie ist eine Ausrichtung, kein eigener Zustand der Sicht).
|
||||
*/
|
||||
export function cameraFromView(project: Project, view: ViewCamera, o: CameraFromViewOptions): Camera {
|
||||
const [px, py, pz] = view.position;
|
||||
const floorId = o.floorId ?? floorForHeight(project, pz, o.fallbackFloorId);
|
||||
const ortho = view.kind === "orthogonal";
|
||||
const dist = o.distance !== undefined && Number.isFinite(o.distance) && o.distance > 0 ? o.distance : ortho ? Math.max(view.orthoHeight, 1) : DEFAULT_AIM_DISTANCE;
|
||||
const target: Vec2 = { x: px + view.direction[0] * dist, y: py + view.direction[1] * dist };
|
||||
const cam: Camera = {
|
||||
id: o.id,
|
||||
type: "camera",
|
||||
name: o.name,
|
||||
floorId,
|
||||
categoryCode: o.categoryCode ?? CAMERA_CATEGORY,
|
||||
position: { x: px, y: py },
|
||||
eyeHeight: pz - floorBase(project, floorId),
|
||||
target,
|
||||
targetHeight: pz + view.direction[2] * dist,
|
||||
fovDeg: clampFov(view.fovDeg),
|
||||
projection: ortho ? "parallel" : "perspective",
|
||||
};
|
||||
if (ortho) cam.orthoHeight = view.orthoHeight;
|
||||
return cam;
|
||||
}
|
||||
|
||||
/** Axonometrie-Ausrichtung („Isometrie"): Blick aus Südwest von oben (45° Azimut, 35.264° Neigung) auf dasselbe Ziel. */
|
||||
export function isometricAim(project: Project, cam: Camera): Pick<Camera, "position" | "eyeHeight"> {
|
||||
const eye = cameraEye(project, cam);
|
||||
const tgt = cameraTarget(cam);
|
||||
const dist = Math.max(Math.hypot(tgt[0] - eye[0], tgt[1] - eye[1], tgt[2] - eye[2]), 5);
|
||||
const pitch = Math.atan(1 / Math.SQRT2);
|
||||
const horiz = dist * Math.cos(pitch);
|
||||
const from: V3 = [tgt[0] - horiz * Math.SQRT1_2, tgt[1] - horiz * Math.SQRT1_2, tgt[2] + dist * Math.sin(pitch)];
|
||||
return { position: { x: from[0], y: from[1] }, eyeHeight: from[2] - floorBase(project, cam.floorId) };
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { orbitCamera } from "./cameraBridge";
|
||||
import type { OrbitState } from "./cameraBridge";
|
||||
import { NO_KEYS, lookAround, orbitEye, speedFactor, stepWalk, walkKeyAllowed, walkKeyOf, walkVelocity } from "./walk";
|
||||
|
||||
const orbit = (over: Partial<OrbitState> = {}): OrbitState => ({
|
||||
yaw: 0,
|
||||
pitch: 0.4,
|
||||
dist: 10,
|
||||
target: [0, 1.6, 0],
|
||||
ortho: false,
|
||||
orthoHalfHeight: 5,
|
||||
...over,
|
||||
});
|
||||
|
||||
const near = (a: readonly number[], b: readonly number[], eps = 1e-9) => a.forEach((x, i) => expect(x).toBeCloseTo(b[i], -Math.log10(eps)));
|
||||
|
||||
describe("[213] Begehen: Tasten", () => {
|
||||
it("W/A/S/D, Pfeile und Q/E; alles andere ist keine Bewegung", () => {
|
||||
expect(walkKeyOf("KeyW")).toBe("forward");
|
||||
expect(walkKeyOf("ArrowUp")).toBe("forward");
|
||||
expect(walkKeyOf("KeyS")).toBe("back");
|
||||
expect(walkKeyOf("ArrowLeft")).toBe("left");
|
||||
expect(walkKeyOf("KeyD")).toBe("right");
|
||||
expect(walkKeyOf("KeyQ")).toBe("down");
|
||||
expect(walkKeyOf("KeyE")).toBe("up");
|
||||
expect(walkKeyOf("KeyT")).toBeNull();
|
||||
expect(walkKeyOf("Digit3")).toBeNull();
|
||||
});
|
||||
|
||||
it("Shift schneller, Alt langsamer, beide gleichen sich teils aus", () => {
|
||||
expect(speedFactor(false, false)).toBe(1);
|
||||
expect(speedFactor(true, false)).toBe(4);
|
||||
expect(speedFactor(false, true)).toBe(0.25);
|
||||
expect(speedFactor(true, true)).toBe(1);
|
||||
});
|
||||
|
||||
it("Befehls-Modifikator oder Textfeld sperren das Begehen", () => {
|
||||
expect(walkKeyAllowed({ ctrlKey: false, metaKey: false }, null)).toBe(true);
|
||||
expect(walkKeyAllowed({ ctrlKey: true, metaKey: false }, null)).toBe(false);
|
||||
expect(walkKeyAllowed({ ctrlKey: false, metaKey: true }, null)).toBe(false);
|
||||
const el = (tagName: string, isContentEditable = false) => ({ tagName, isContentEditable }) as unknown as Element;
|
||||
expect(walkKeyAllowed({ ctrlKey: false, metaKey: false }, el("INPUT"))).toBe(false);
|
||||
expect(walkKeyAllowed({ ctrlKey: false, metaKey: false }, el("TEXTAREA"))).toBe(false);
|
||||
expect(walkKeyAllowed({ ctrlKey: false, metaKey: false }, el("DIV", true))).toBe(false);
|
||||
expect(walkKeyAllowed({ ctrlKey: false, metaKey: false }, el("DIV"))).toBe(true);
|
||||
expect(walkKeyAllowed({ ctrlKey: false, metaKey: false }, el("CANVAS"))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("[213] Begehen: Bewegung", () => {
|
||||
it("vorwärts läuft in der Blickrichtung, waagrecht (Augenhöhe bleibt trotz Neigung)", () => {
|
||||
// yaw 0: Augpunkt liegt bei +x vom Ziel, Blick geht nach −x.
|
||||
const v = walkVelocity({ ...NO_KEYS, forward: true }, 0, 3);
|
||||
near(v, [-3, 0, 0]);
|
||||
const o = orbit({ pitch: 0.9 });
|
||||
const eye0 = orbitEye(o);
|
||||
const n = stepWalk(o, { ...NO_KEYS, forward: true }, 1 / 60);
|
||||
const eye1 = orbitEye(n);
|
||||
expect(eye1[1]).toBeCloseTo(eye0[1], 12);
|
||||
expect(eye1[0]).toBeLessThan(eye0[0]);
|
||||
// Abstand, Winkel und Projektion bleiben.
|
||||
expect(n.dist).toBe(o.dist);
|
||||
expect(n.pitch).toBe(o.pitch);
|
||||
expect(n.yaw).toBe(o.yaw);
|
||||
});
|
||||
|
||||
it("seitwärts steht senkrecht auf der Blickrichtung; rechts ist rechts", () => {
|
||||
// Blick nach −x (yaw 0), Weltoben +y: rechts ist −z.
|
||||
near(walkVelocity({ ...NO_KEYS, right: true }, 0, 2), [0, 0, -2]);
|
||||
near(walkVelocity({ ...NO_KEYS, left: true }, 0, 2), [0, 0, 2]);
|
||||
// Gedreht um 90°: Blick nach −z, rechts ist +x.
|
||||
near(walkVelocity({ ...NO_KEYS, forward: true }, Math.PI / 2, 2), [0, 0, -2]);
|
||||
near(walkVelocity({ ...NO_KEYS, right: true }, Math.PI / 2, 2), [2, 0, 0]);
|
||||
});
|
||||
|
||||
it("diagonal ist nicht schneller; Gegentasten heben sich auf; Q/E senkrecht", () => {
|
||||
const d = walkVelocity({ ...NO_KEYS, forward: true, right: true }, 0.3, 3);
|
||||
expect(Math.hypot(d[0], d[2])).toBeCloseTo(3, 12);
|
||||
near(walkVelocity({ ...NO_KEYS, forward: true, back: true }, 0.3, 3), [0, 0, 0]);
|
||||
near(walkVelocity({ ...NO_KEYS, up: true }, 0.3, 3), [0, 3, 0]);
|
||||
near(walkVelocity({ ...NO_KEYS, down: true }, 0.3, 3), [0, -3, 0]);
|
||||
});
|
||||
|
||||
it("Weg = Tempo × Zeit; langer Zeitschritt wird gekappt; ohne Taste oder dt bleibt der Zustand", () => {
|
||||
const o = orbit();
|
||||
const n = stepWalk(o, { ...NO_KEYS, forward: true }, 0.05, 4);
|
||||
expect(n.target[0]).toBeCloseTo(-0.2, 12);
|
||||
const slow = stepWalk(o, { ...NO_KEYS, forward: true }, 5, 4);
|
||||
expect(slow.target[0]).toBeCloseTo(-0.4, 12); // höchstens 0.1 s
|
||||
expect(stepWalk(o, NO_KEYS, 1)).toBe(o);
|
||||
expect(stepWalk(o, { ...NO_KEYS, forward: true }, 0)).toBe(o);
|
||||
expect(stepWalk(o, { ...NO_KEYS, forward: true }, NaN)).toBe(o);
|
||||
expect(stepWalk(o, { ...NO_KEYS, forward: true }, 1, 0)).toBe(o);
|
||||
});
|
||||
|
||||
it("die Kamera zeigt nach dem Gehen weiter in dieselbe Richtung", () => {
|
||||
const o = orbit({ yaw: 1.2, pitch: 0.3 });
|
||||
const c0 = orbitCamera(o);
|
||||
const c1 = orbitCamera(stepWalk(o, { ...NO_KEYS, forward: true, right: true }, 0.08));
|
||||
const dir = (c: { eye: number[]; target: number[] }) => {
|
||||
const d = [c.target[0] - c.eye[0], c.target[1] - c.eye[1], c.target[2] - c.eye[2]];
|
||||
const l = Math.hypot(d[0], d[1], d[2]);
|
||||
return d.map((x) => x / l);
|
||||
};
|
||||
near(dir(c1), dir(c0), 1e-9);
|
||||
});
|
||||
});
|
||||
|
||||
describe("[213] Begehen: Umschauen", () => {
|
||||
it("der Augpunkt bleibt stehen, die Blickrichtung dreht", () => {
|
||||
const o = orbit({ yaw: 0.7, pitch: 0.2 });
|
||||
const eye = orbitEye(o);
|
||||
const n = lookAround(o, 120, -40);
|
||||
near(orbitEye(n), eye, 1e-9);
|
||||
expect(n.yaw).toBeGreaterThan(o.yaw); // Maus nach rechts → Blick nach rechts
|
||||
expect(n.pitch).toBeLessThan(o.pitch); // Maus nach oben → Blick hebt sich
|
||||
expect(n.dist).toBe(o.dist);
|
||||
});
|
||||
|
||||
it("Neigung ist geklemmt; ohne Bewegung bleibt der Zustand", () => {
|
||||
const o = orbit();
|
||||
const steep = lookAround(o, 0, 1e6);
|
||||
expect(steep.pitch).toBeLessThan(Math.PI / 2);
|
||||
expect(steep.pitch).toBeGreaterThan(1.5);
|
||||
expect(lookAround(o, 0, 0)).toBe(o);
|
||||
expect(lookAround(o, NaN, 3)).toBe(o);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
// [213] Begehen im 3D (WASD): reine Bewegungsrechnung auf dem Orbit-Zustand des Viewports, ohne React und Engine.
|
||||
//
|
||||
// Der Orbit-Zustand (`OrbitState`, world Y-oben) beschreibt die Kamera als Blickziel + Abstand + Winkel. Den Augpunkt
|
||||
// verschieben heisst, das Blickziel um denselben Vektor verschieben — Abstand und Winkel bleiben. Vorwärts und
|
||||
// seitwärts laufen in der Horizontalen (Augenhöhe bleibt, auch bei geneigtem Blick); Q/E bewegen senkrecht.
|
||||
// Umschauen dreht die Blickrichtung um den Augpunkt (nicht um das Ziel wie der Orbit).
|
||||
|
||||
import { PITCH_LIMIT } from "./cameraBridge";
|
||||
import type { OrbitState, V3 } from "./cameraBridge";
|
||||
|
||||
/** Gedrückte Bewegungstasten. */
|
||||
export interface WalkKeys {
|
||||
forward: boolean;
|
||||
back: boolean;
|
||||
left: boolean;
|
||||
right: boolean;
|
||||
up: boolean;
|
||||
down: boolean;
|
||||
}
|
||||
|
||||
export const NO_KEYS: WalkKeys = { forward: false, back: false, left: false, right: false, up: false, down: false };
|
||||
|
||||
/** Grundgeschwindigkeit (m/s), Shift ×4, Alt ×0.25. */
|
||||
export const WALK_SPEED = 3;
|
||||
export const FAST_FACTOR = 4;
|
||||
export const SLOW_FACTOR = 0.25;
|
||||
/** Längster Zeitschritt (s): nach einem Hänger (Tab im Hintergrund) kein Sprung durchs Haus. */
|
||||
export const MAX_DT = 0.1;
|
||||
/** Mausempfindlichkeit beim Umschauen (Radiant je Pixel). */
|
||||
export const LOOK_RAD_PER_PX = 0.0035;
|
||||
|
||||
/** Taste (`KeyboardEvent.code`) → Bewegung; `null` für alle anderen. W/S/A/D und Pfeile vor/zurück/seitlich, Q/E runter/hoch. */
|
||||
export function walkKeyOf(code: string): keyof WalkKeys | null {
|
||||
switch (code) {
|
||||
case "KeyW":
|
||||
case "ArrowUp":
|
||||
return "forward";
|
||||
case "KeyS":
|
||||
case "ArrowDown":
|
||||
return "back";
|
||||
case "KeyA":
|
||||
case "ArrowLeft":
|
||||
return "left";
|
||||
case "KeyD":
|
||||
case "ArrowRight":
|
||||
return "right";
|
||||
case "KeyQ":
|
||||
return "down";
|
||||
case "KeyE":
|
||||
return "up";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Ist irgendeine Bewegungstaste gedrückt? */
|
||||
export const anyKey = (k: WalkKeys): boolean => k.forward || k.back || k.left || k.right || k.up || k.down;
|
||||
|
||||
/** Tempo-Faktor aus Shift (schneller) und Alt (langsamer); beide = Grundtempo. */
|
||||
export function speedFactor(shift: boolean, alt: boolean): number {
|
||||
return (shift ? FAST_FACTOR : 1) * (alt ? SLOW_FACTOR : 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Geschwindigkeit (world, m/s) aus den gedrückten Tasten. Vorwärts = horizontale Blickrichtung (die Höhe bleibt),
|
||||
* seitwärts = rechts, hoch/runter = world Y. Gegensätzliche Tasten heben sich auf; diagonale Bewegung ist nicht
|
||||
* schneller als geradeaus (die waagrechte Richtung wird normiert).
|
||||
*/
|
||||
export function walkVelocity(keys: WalkKeys, yaw: number, speed: number): V3 {
|
||||
const fwd = (keys.forward ? 1 : 0) - (keys.back ? 1 : 0);
|
||||
const side = (keys.right ? 1 : 0) - (keys.left ? 1 : 0);
|
||||
const vert = (keys.up ? 1 : 0) - (keys.down ? 1 : 0);
|
||||
// Horizontale Blickrichtung f = (−cos yaw, 0, −sin yaw), rechts s = (sin yaw, 0, −cos yaw) (wie im Pan des Viewports).
|
||||
const hx = -Math.cos(yaw) * fwd + Math.sin(yaw) * side;
|
||||
const hz = -Math.sin(yaw) * fwd - Math.cos(yaw) * side;
|
||||
const hl = Math.hypot(hx, hz);
|
||||
const k = hl > 1e-12 ? speed / hl : 0;
|
||||
return [hx * k, vert * speed, hz * k];
|
||||
}
|
||||
|
||||
/** Orbit-Zustand nach `dt` Sekunden Gehen; derselbe Zustand ohne Taste oder bei unbrauchbarem `dt`. */
|
||||
export function stepWalk(o: OrbitState, keys: WalkKeys, dt: number, speed: number = WALK_SPEED): OrbitState {
|
||||
if (!anyKey(keys) || !(dt > 0) || !Number.isFinite(dt) || !(speed > 0)) return o;
|
||||
const v = walkVelocity(keys, o.yaw, speed);
|
||||
const s = Math.min(dt, MAX_DT);
|
||||
return { ...o, target: [o.target[0] + v[0] * s, o.target[1] + v[1] * s, o.target[2] + v[2] * s] };
|
||||
}
|
||||
|
||||
/** Augpunkt (world) des Orbit-Zustands. */
|
||||
export function orbitEye(o: OrbitState): V3 {
|
||||
const pitch = Math.max(-PITCH_LIMIT, Math.min(PITCH_LIMIT, o.pitch));
|
||||
const r = o.dist * Math.cos(pitch);
|
||||
return [o.target[0] + r * Math.cos(o.yaw), o.target[1] + o.dist * Math.sin(pitch), o.target[2] + r * Math.sin(o.yaw)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Umschauen um den Augpunkt: Maus nach rechts (`dx` > 0) dreht den Blick nach rechts, Maus nach unten (`dy` > 0)
|
||||
* senkt ihn. Der Augpunkt bleibt exakt stehen (das Blickziel wandert auf der neuen Blickachse mit); der Neigungswinkel
|
||||
* ist wie beim Orbit geklemmt.
|
||||
*/
|
||||
export function lookAround(o: OrbitState, dx: number, dy: number, radPerPx: number = LOOK_RAD_PER_PX): OrbitState {
|
||||
if (!Number.isFinite(dx) || !Number.isFinite(dy) || (dx === 0 && dy === 0)) return o;
|
||||
const eye = orbitEye(o);
|
||||
const yaw = o.yaw + dx * radPerPx;
|
||||
const pitch = Math.max(-PITCH_LIMIT, Math.min(PITCH_LIMIT, o.pitch + dy * radPerPx));
|
||||
const r = o.dist * Math.cos(pitch);
|
||||
return { ...o, yaw, pitch, target: [eye[0] - r * Math.cos(yaw), eye[1] - o.dist * Math.sin(pitch), eye[2] - r * Math.sin(yaw)] };
|
||||
}
|
||||
|
||||
/** Darf die Taste das Begehen starten (kein Textfeld im Fokus, kein Befehls-Modifikator)? */
|
||||
export function walkKeyAllowed(e: { ctrlKey: boolean; metaKey: boolean }, active: Element | null): boolean {
|
||||
if (e.ctrlKey || e.metaKey) return false;
|
||||
if (!active) return true;
|
||||
const tag = active.tagName;
|
||||
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return false;
|
||||
return !(active as HTMLElement).isContentEditable;
|
||||
}
|
||||
@@ -153,6 +153,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
drawings: selectedDrawingIds,
|
||||
site: selectedSite,
|
||||
trees: selectedTreeIds,
|
||||
cameras: selectedCameraIds,
|
||||
} = selection;
|
||||
const selectedDrawingId = single(selection, "drawings");
|
||||
// Linke Maustaste liegt beim Werkzeug/der Transformation, wenn App das meldet
|
||||
@@ -312,6 +313,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
pickSectionLine,
|
||||
pickSiteAt,
|
||||
pickTree,
|
||||
pickCamera,
|
||||
pickContextObject,
|
||||
pickExtrudedSolid,
|
||||
pickColumn,
|
||||
@@ -414,6 +416,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
pickColumn,
|
||||
pickExtrudedSolid,
|
||||
pickTree,
|
||||
pickCamera,
|
||||
pickStair,
|
||||
pickRoof,
|
||||
pickSiteAt,
|
||||
@@ -450,6 +453,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
pickRoom,
|
||||
pickRoof,
|
||||
pickTree,
|
||||
pickCamera,
|
||||
pickSiteAt,
|
||||
pickContextObject,
|
||||
pickSectionLine,
|
||||
@@ -505,6 +509,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
pickRoom,
|
||||
onOpenSectionLevel,
|
||||
pickSectionLine,
|
||||
pickCamera,
|
||||
onContextMenu,
|
||||
view,
|
||||
viewToModel,
|
||||
@@ -546,6 +551,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
|
||||
selectedContextObjectIds,
|
||||
selectedSite,
|
||||
selectedTreeIds,
|
||||
selectedCameraIds,
|
||||
selectedSectionLineIds,
|
||||
selectedExtrudedSolidIds,
|
||||
selectedColumnIds,
|
||||
|
||||
@@ -35,6 +35,7 @@ const KIND_FIELD: Record<PickKind, SelectionKind> = {
|
||||
drawing: "drawings",
|
||||
solid: "solids",
|
||||
tree: "trees",
|
||||
camera: "cameras",
|
||||
ceiling: "ceilings",
|
||||
stair: "stairs",
|
||||
room: "rooms",
|
||||
|
||||
@@ -71,7 +71,7 @@ export const GRIP_HIT_PX = 9;
|
||||
export const LINE_PICK_PX = 6;
|
||||
|
||||
export const PICK_ORDER: readonly PickKind[] = [
|
||||
"section", "opening", "wall", "column", "drawing", "solid", "tree",
|
||||
"section", "opening", "wall", "column", "drawing", "solid", "tree", "camera",
|
||||
"ceiling", "stair", "room", "roof", "site", "context",
|
||||
];
|
||||
|
||||
@@ -90,11 +90,14 @@ export const EMPTY_PICK: PickIds = {
|
||||
contextObjectId: null,
|
||||
siteId: null,
|
||||
treeId: null,
|
||||
cameraId: null,
|
||||
};
|
||||
|
||||
/** Mac: Cmd+Klick; sonst Strg+Klick (Alt+Klick ist die Schere, Ctrl+Klick unter macOS das Kontextmenü). */
|
||||
/** [149] Präfix der Baum-Pick-Id im Feld `contextObjectId` (Kern `tree::TREE_PICK_PREFIX`). */
|
||||
export const TREE_PICK = "@tree:";
|
||||
/** [213] Präfix der Kamera-Pick-Id im Feld `contextObjectId` (Kern `camera::CAMERA_PICK_PREFIX`). */
|
||||
export const CAMERA_PICK = "@camera:";
|
||||
|
||||
export const IS_MAC = typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform);
|
||||
export const cycleModifier = (e: { metaKey: boolean; ctrlKey: boolean }): boolean => (IS_MAC ? e.metaKey : e.ctrlKey);
|
||||
@@ -156,6 +156,8 @@ export interface PlanSelection {
|
||||
* Öffnung/Wand/Stütze/2D-Element/Körper getroffen wurde; Vorrang vor Decke, Raum, Dach und Gelände.
|
||||
*/
|
||||
treeId?: string | null;
|
||||
/** [213] Getroffene Kamera (Sichtkegel/Gehäuse, Pick-Id `@camera:<id>` im Feld `contextObjectId`); Vorrang vor allem ausser Öffnung/Wand/Stütze/2D-Element/Körper/Baum. */
|
||||
cameraId?: string | null;
|
||||
/**
|
||||
* War beim Klick Shift gedrückt? Dann ERWEITERT der Aufrufer (App) die
|
||||
* Auswahl um das getroffene Element (bzw. schaltet es ab/zu), statt sie zu
|
||||
@@ -185,6 +187,8 @@ export interface MarqueeSelection {
|
||||
stairIds: string[];
|
||||
/** [149] Getroffene Bäume (Kronenfläche, gleiche Konvention). */
|
||||
treeIds?: string[];
|
||||
/** [213] Getroffene Kameras (Pick-Flächen von Gehäuse und Sichtgrenzen, gleiche Konvention). */
|
||||
cameraIds?: string[];
|
||||
/**
|
||||
* Zieh-Richtung: `false` = links→rechts (positiv Δx) → nur VOLLSTÄNDIG
|
||||
* eingeschlossene Wände; `true` = rechts→links (negativ Δx) → auch berührte/
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { Primitive, OwnerField, PickKind } from "../../../core";
|
||||
import { useMemo, useEffect } from "react";
|
||||
import { planPrimAt } from "../../../core";
|
||||
import { textFrameCorners } from "../../../text/textFrame";
|
||||
import { TREE_PICK } from "./constants";
|
||||
import { CAMERA_PICK, TREE_PICK } from "./constants";
|
||||
import { PlanPickIndex } from "../../../core";
|
||||
import type { Plan } from "../../../core";
|
||||
import type { UnderlayGroup } from "../../../core";
|
||||
@@ -36,6 +36,7 @@ export interface UsePlanHighlightsArgs {
|
||||
selectedContextObjectIds: string[];
|
||||
selectedSite: string[];
|
||||
selectedTreeIds: string[];
|
||||
selectedCameraIds?: string[];
|
||||
selectedSectionLineIds: string[];
|
||||
selectedExtrudedSolidIds: string[];
|
||||
selectedColumnIds: string[];
|
||||
@@ -64,6 +65,7 @@ export function usePlanHighlights(inp: UsePlanHighlightsArgs) {
|
||||
selectedContextObjectIds,
|
||||
selectedSite,
|
||||
selectedTreeIds,
|
||||
selectedCameraIds,
|
||||
selectedSectionLineIds,
|
||||
selectedExtrudedSolidIds,
|
||||
selectedColumnIds,
|
||||
@@ -238,10 +240,11 @@ export function usePlanHighlights(inp: UsePlanHighlightsArgs) {
|
||||
...(selectedContextObjectIds ?? []),
|
||||
...(selectedSite ?? []).map((s) => "@" + s),
|
||||
...(selectedTreeIds ?? []).map((s) => TREE_PICK + s),
|
||||
...(selectedCameraIds ?? []).map((s) => CAMERA_PICK + s),
|
||||
];
|
||||
if (!ids.length) return [];
|
||||
return primsOwnedBy("contextObjectId", ids, (p): p is Extract<Primitive, { kind: "polygon" }> => p.kind === "polygon");
|
||||
}, [plan, selectedContextObjectIds, selectedSite, selectedTreeIds]);
|
||||
}, [plan, selectedContextObjectIds, selectedSite, selectedTreeIds, selectedCameraIds]);
|
||||
|
||||
// Hervorhebung der selektierten Schnitt-/Ansichtslinie: das (unsichtbare)
|
||||
// Pick-Band (Polygon mit sectionLineId) mit Akzentkontur überzeichnen.
|
||||
@@ -280,7 +283,8 @@ export function usePlanHighlights(inp: UsePlanHighlightsArgs) {
|
||||
if (!hoverPick) return [];
|
||||
if (hoverPick.kind === "site") return primsOwnedBy("contextObjectId", ["@" + hoverPick.id], (_p): _p is Primitive => true);
|
||||
if (hoverPick.kind === "tree") return primsOwnedBy("contextObjectId", [TREE_PICK + hoverPick.id], (_p): _p is Primitive => true);
|
||||
const field: Record<Exclude<PickKind, "site" | "tree">, OwnerField> = {
|
||||
if (hoverPick.kind === "camera") return primsOwnedBy("contextObjectId", [CAMERA_PICK + hoverPick.id], (_p): _p is Primitive => true);
|
||||
const field: Record<Exclude<PickKind, "site" | "tree" | "camera">, OwnerField> = {
|
||||
wall: "wallId", drawing: "drawingId", ceiling: "ceilingId", opening: "openingId",
|
||||
stair: "stairId", room: "roomId", roof: "roofId", context: "contextObjectId",
|
||||
section: "sectionLineId", solid: "extrudedSolidId", column: "columnId",
|
||||
|
||||
@@ -10,7 +10,7 @@ import type { Vec2 } from "../../../model/types";
|
||||
import type { PlainCycle } from "../pickCycle";
|
||||
import { selectionHas, plainCycleNext, cycleHint } from "../pickCycle";
|
||||
import { t } from "../../../i18n";
|
||||
import { LINE_PICK_PX, TREE_PICK, PICK_ORDER, EMPTY_PICK, MARQUEE_THRESHOLD_PX, cycleModifier } from "./constants";
|
||||
import { CAMERA_PICK, LINE_PICK_PX, TREE_PICK, PICK_ORDER, EMPTY_PICK, MARQUEE_THRESHOLD_PX, cycleModifier } from "./constants";
|
||||
import { planPrimAt, drawingsWithinDistance } from "../../../core";
|
||||
import type { ViewBox__plan_planView_geometry as ViewBox } from "../../../core";
|
||||
import { PlanPickIndex } from "../../../core";
|
||||
@@ -47,6 +47,7 @@ export interface UsePlanPickCycleArgs {
|
||||
pickRoom: (clientX: number, clientY: number) => string | null;
|
||||
pickRoof: (clientX: number, clientY: number) => string | null;
|
||||
pickTree: (clientX: number, clientY: number) => string | null;
|
||||
pickCamera: (clientX: number, clientY: number) => string | null;
|
||||
pickSiteAt: (clientX: number, clientY: number) => string | null;
|
||||
pickContextObject: (clientX: number, clientY: number) => string | null;
|
||||
pickSectionLine: (clientX: number, clientY: number) => string | null;
|
||||
@@ -99,6 +100,7 @@ export function usePlanPickCycle(inp: UsePlanPickCycleArgs) {
|
||||
pickRoom,
|
||||
pickRoof,
|
||||
pickTree,
|
||||
pickCamera,
|
||||
pickSiteAt,
|
||||
pickContextObject,
|
||||
pickSectionLine,
|
||||
@@ -256,6 +258,7 @@ export function usePlanPickCycle(inp: UsePlanPickCycleArgs) {
|
||||
add("drawing", dp.drawingId, dp.hitIndex);
|
||||
add("solid", dp.extrudedSolidId, dp.hitIndex);
|
||||
add("tree", dp.treeId, dp.hitIndex);
|
||||
add("camera", dp.cameraId, dp.hitIndex);
|
||||
add("ceiling", dp.ceilingId, dp.hitIndex);
|
||||
add("stair", dp.stairId, dp.hitIndex);
|
||||
add("room", dp.roomId, dp.hitIndex);
|
||||
@@ -283,6 +286,7 @@ export function usePlanPickCycle(inp: UsePlanPickCycleArgs) {
|
||||
addRest("room", p.roomId, idx);
|
||||
addRest("roof", p.roofId, idx);
|
||||
if (p.contextObjectId?.startsWith(TREE_PICK)) addRest("tree", p.contextObjectId.slice(TREE_PICK.length), idx);
|
||||
else if (p.contextObjectId?.startsWith(CAMERA_PICK)) addRest("camera", p.contextObjectId.slice(CAMERA_PICK.length), idx);
|
||||
else if (p.contextObjectId?.startsWith("@")) addRest("site", p.contextObjectId.slice(1), idx);
|
||||
else addRest("context", p.contextObjectId, idx);
|
||||
addRest("section", p.sectionLineId, idx);
|
||||
@@ -295,6 +299,7 @@ export function usePlanPickCycle(inp: UsePlanPickCycleArgs) {
|
||||
addRest("room", pickRoom(clientX, clientY), null);
|
||||
addRest("roof", pickRoof(clientX, clientY), null);
|
||||
addRest("tree", pickTree(clientX, clientY), null);
|
||||
addRest("camera", pickCamera(clientX, clientY), null);
|
||||
addRest("site", pickSiteAt(clientX, clientY), null);
|
||||
addRest("context", pickContextObject(clientX, clientY), null);
|
||||
addRest("section", pickSectionLine(clientX, clientY), null);
|
||||
@@ -333,6 +338,7 @@ export function usePlanPickCycle(inp: UsePlanPickCycleArgs) {
|
||||
contextObjectId: c.kind === "context" ? c.id : null,
|
||||
siteId: c.kind === "site" ? c.id : null,
|
||||
treeId: c.kind === "tree" ? c.id : null,
|
||||
cameraId: c.kind === "camera" ? c.id : null,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -532,6 +538,15 @@ export function usePlanPickCycle(inp: UsePlanPickCycleArgs) {
|
||||
.marquee("contextObjectId", rect, crossing)
|
||||
.filter((id) => id.startsWith(TREE_PICK))
|
||||
.map((id) => id.slice(TREE_PICK.length)),
|
||||
// [213] Kameras: Pick-Flächen (`contextObjectId = "@camera:<id>"`).
|
||||
cameraIds: [
|
||||
...new Set(
|
||||
getPick()
|
||||
.marquee("contextObjectId", rect, crossing)
|
||||
.filter((id) => id.startsWith(CAMERA_PICK))
|
||||
.map((id) => id.slice(CAMERA_PICK.length)),
|
||||
),
|
||||
],
|
||||
crossing,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import type { GroupableHit, BodyTarget } from "./types";
|
||||
import { planPrimAt, nearestInDrawings, marqueeHitUnderlay } from "../../../core";
|
||||
import { LINE_PICK_PX, TREE_PICK } from "./constants";
|
||||
import { CAMERA_PICK, LINE_PICK_PX, TREE_PICK } from "./constants";
|
||||
import type { Primitive, ModelRect } from "../../../core";
|
||||
import type { Vec2 } from "../../../model/types";
|
||||
import { useState, useRef, useEffect } from "react";
|
||||
@@ -257,7 +257,7 @@ export function usePlanPicking(inp: UsePlanPickingArgs) {
|
||||
|
||||
// [137] Getroffene Lage-Darstellung: Quelle `"sunStudy"`/`"siteRules"` (Baurechtslinie vor Schatten) oder null.
|
||||
const pickSiteAt = (clientX: number, clientY: number): string | null => {
|
||||
const all = contextIdsAt(clientX, clientY).filter((id) => !id.startsWith(TREE_PICK));
|
||||
const all = contextIdsAt(clientX, clientY).filter((id) => !id.startsWith(TREE_PICK) && !id.startsWith(CAMERA_PICK));
|
||||
// [193] Liegt ein Kontext-Element (Baugrube, Netz) über der Schattenfläche, gehört der Klick ihm — sonst wäre
|
||||
// die Baugrube unter dem Schatten des Hauses nicht anzuwählen. Die Baurechtslinie (unsichtbares Band) gewinnt immer.
|
||||
if (all.includes("@siteRules")) return "siteRules";
|
||||
@@ -271,6 +271,12 @@ export function usePlanPicking(inp: UsePlanPickingArgs) {
|
||||
return id ? id.slice(TREE_PICK.length) : null;
|
||||
};
|
||||
|
||||
// [213] Getroffene Kamera (oberste Pickfläche aus Gehäuse und Sichtkegel) oder null.
|
||||
const pickCamera = (clientX: number, clientY: number): string | null => {
|
||||
const id = contextIdsAt(clientX, clientY).find((x) => x.startsWith(CAMERA_PICK));
|
||||
return id ? id.slice(CAMERA_PICK.length) : null;
|
||||
};
|
||||
|
||||
const pickContextObject = (clientX: number, clientY: number): string | null =>
|
||||
contextIdsAt(clientX, clientY).find((id) => !id.startsWith("@")) ?? null;
|
||||
|
||||
@@ -407,6 +413,7 @@ export function usePlanPicking(inp: UsePlanPickingArgs) {
|
||||
pickSectionLine,
|
||||
pickSiteAt,
|
||||
pickTree,
|
||||
pickCamera,
|
||||
pickContextObject,
|
||||
pickExtrudedSolid,
|
||||
pickColumn,
|
||||
|
||||
@@ -76,6 +76,7 @@ export interface UsePlanPointerArgs {
|
||||
pickColumn: (clientX: number, clientY: number) => string | null;
|
||||
pickExtrudedSolid: (clientX: number, clientY: number) => string | null;
|
||||
pickTree: (clientX: number, clientY: number) => string | null;
|
||||
pickCamera: (clientX: number, clientY: number) => string | null;
|
||||
pickStair: (clientX: number, clientY: number) => string | null;
|
||||
pickRoof: (clientX: number, clientY: number) => string | null;
|
||||
pickSiteAt: (clientX: number, clientY: number) => string | null;
|
||||
@@ -141,6 +142,7 @@ export function usePlanPointer(inp: UsePlanPointerArgs) {
|
||||
pickColumn,
|
||||
pickExtrudedSolid,
|
||||
pickTree,
|
||||
pickCamera,
|
||||
pickStair,
|
||||
pickRoof,
|
||||
pickSiteAt,
|
||||
@@ -616,27 +618,30 @@ export function usePlanPointer(inp: UsePlanPointerArgs) {
|
||||
// [149] Baum (Kronenfläche) vor Decke, Raum, Dach und Gelände.
|
||||
const treeId =
|
||||
openingId || wallId || columnId || drawingId || extrudedSolidId ? null : pickTree(clientX, clientY);
|
||||
// [213] Kamera (schmale Pickflächen von Gehäuse, Sichtgrenzen und Ziel) wie der Baum vor Decke, Raum, Dach.
|
||||
const cameraId =
|
||||
openingId || wallId || columnId || drawingId || extrudedSolidId || treeId ? null : pickCamera(clientX, clientY);
|
||||
// Decke nur, wenn weder Öffnung/Wand noch 2D-Element getroffen wurde. Da die
|
||||
// Decken-Polygone UNTER der Wand-Poché liegen, trifft ein direkter Klick
|
||||
// auf die Wand zuerst die Wand; freie Deckenfläche trifft die Decke.
|
||||
const hitCeilingId =
|
||||
hit && hit.kind === "polygon" ? hit.ceilingId ?? null : null;
|
||||
const ceilingId =
|
||||
openingId || wallId || columnId || drawingId || extrudedSolidId || treeId ? null : hitCeilingId;
|
||||
openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || cameraId ? null : hitCeilingId;
|
||||
// Treppe nur, wenn nichts anderes getroffen wurde (Tritte liegen frei).
|
||||
const stairId =
|
||||
openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || ceilingId
|
||||
openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || cameraId || ceilingId
|
||||
? null
|
||||
: pickStair(clientX, clientY);
|
||||
// Raum als vorletzte Priorität: die Raum-Fläche liegt UNTER allem anderen.
|
||||
const roomId =
|
||||
openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || ceilingId || stairId
|
||||
openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || cameraId || ceilingId || stairId
|
||||
? null
|
||||
: pickRoom(clientX, clientY);
|
||||
// Dach als LETZTE Priorität: die Traufe-Fläche deckt den ganzen Grundriss
|
||||
// ab, daher erst wählen, wenn wirklich nichts anderes getroffen wurde.
|
||||
const roofId =
|
||||
openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || ceilingId || stairId || roomId
|
||||
openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || cameraId || ceilingId || stairId || roomId
|
||||
? null
|
||||
: pickRoof(clientX, clientY);
|
||||
// Kontext-Objekt (Gebäude/Terrain) als ALLERLETZTE Priorität — seine
|
||||
@@ -644,11 +649,11 @@ export function usePlanPointer(inp: UsePlanPointerArgs) {
|
||||
// nichts anderes getroffen wurde.
|
||||
// [137] Schatten/Baurechtslinien (Lage-Darstellung) über dem Gelände, unter allen Bauteilen.
|
||||
const siteId =
|
||||
openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || ceilingId || stairId || roomId || roofId
|
||||
openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || cameraId || ceilingId || stairId || roomId || roofId
|
||||
? null
|
||||
: pickSiteAt(clientX, clientY);
|
||||
const contextObjectId =
|
||||
openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || ceilingId || stairId || roomId || roofId || siteId
|
||||
openingId || wallId || columnId || drawingId || extrudedSolidId || treeId || cameraId || ceilingId || stairId || roomId || roofId || siteId
|
||||
? null
|
||||
: pickContextObject(clientX, clientY);
|
||||
return {
|
||||
@@ -666,6 +671,7 @@ export function usePlanPointer(inp: UsePlanPointerArgs) {
|
||||
contextObjectId,
|
||||
siteId,
|
||||
treeId,
|
||||
cameraId,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Rad-Zoom, Doppelklick und Kontextmenü der Plan-Ansicht ([165] aus `PlanView.tsx`). Im GPU-Pfad zoomt
|
||||
// das Rad imperativ und schreibt den Ausschnitt nach kurzer Ruhe fest. Aufgerufen einmal von `PlanView`.
|
||||
|
||||
import { openCamera } from "../../../state/cameraActions";
|
||||
import type { ViewBox__plan_planView_geometry as ViewBox } from "../../../core";
|
||||
import type { Vec2 } from "../../../model/types";
|
||||
import { clamp } from "../../../core";
|
||||
@@ -32,6 +33,7 @@ export interface UsePlanZoomInputArgs {
|
||||
pickRoom: (clientX: number, clientY: number) => string | null;
|
||||
onOpenSectionLevel: ((levelId: string) => void) | undefined;
|
||||
pickSectionLine: (clientX: number, clientY: number) => string | null;
|
||||
pickCamera: (clientX: number, clientY: number) => string | null;
|
||||
onContextMenu: ((info: { clientX: number; clientY: number; model: Vec2; }) => void) | undefined;
|
||||
view: ViewBox;
|
||||
viewToModel: (vbX: number, vbY: number) => Vec2;
|
||||
@@ -60,6 +62,7 @@ export function usePlanZoomInput(inp: UsePlanZoomInputArgs) {
|
||||
pickRoom,
|
||||
onOpenSectionLevel,
|
||||
pickSectionLine,
|
||||
pickCamera,
|
||||
onContextMenu,
|
||||
view,
|
||||
viewToModel,
|
||||
@@ -163,6 +166,12 @@ export function usePlanZoomInput(inp: UsePlanZoomInputArgs) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// [213] Doppelklick auf das Symbol einer Kamera → die Kamera im 3D öffnen (Reiter wechseln, Ansicht exakt setzen).
|
||||
const cid = pickCamera(e.clientX, e.clientY);
|
||||
if (cid) {
|
||||
void openCamera(cid);
|
||||
return;
|
||||
}
|
||||
// Doppelklick auf eine Schnittlinie → in deren 2D-Schnittansicht springen.
|
||||
if (onOpenSectionLevel) {
|
||||
const sid = pickSectionLine(e.clientX, e.clientY);
|
||||
|
||||
Reference in new issue
Block a user