From caa616a1c9c73703550e25233aefca896530de77 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 20:22:47 +0000 Subject: [PATCH] [63] Baurecht: Parzelle, Grenzabstaende je Kante, Baulinien, Gesamthoehe; zulaessige Flaeche, Pruefung und Darstellung im Grundriss - analysis/siteRules.ts: zulaessige Flaeche = Parzelle minus Abstandsstreifen je Kante (auch konkav), begrenzt durch Baulinien (Seite des Parzellen-Schwerpunkts); Pruefung von Grundflaeche (Waende aller Geschosse, freie Koerper) und Gesamthoehe - Grundriss (Geschoss naechst +-0.00): Parzellengrenze strichpunktiert, zulaessige Flaeche gestrichelt, Verstoesse rot ueber dem Gebaeude; Planbegrenzung umfasst die Parzelle - Lage-Panel: Parzelle und Baulinien aus der Auswahl, Grenzabstand pauschal und je Kante, Gesamthoehe, Ergebnis - Kennzahlen: Parzellenflaeche aus der Grenze, wenn keine Zahl gesetzt ist; CLI kennzahlen liefert baurecht - Tests Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- src/analysis/kennzahlen.ts | 6 +- src/analysis/siteRules.test.ts | 67 ++++++++ src/analysis/siteRules.ts | 174 ++++++++++++++++++++ src/cli/main.ts | 4 +- src/core/extra.ts | 2 + src/i18n/de.ts | 20 +++ src/i18n/en.ts | 20 +++ src/io/projectFormat.ts | 2 +- src/model/types.ts | 21 +++ src/panels/KennzahlenSection.tsx | 7 +- src/panels/SitePanel.tsx | 4 + src/panels/SiteRulesSection.tsx | 203 ++++++++++++++++++++++++ src/panels/siteRulesInput.test.ts | 20 +++ src/panels/siteRulesInput.ts | 29 ++++ src/plan/generatePlan.siteRules.test.ts | 44 +++++ src/plan/generatePlan.ts | 17 +- src/plan/generatePlan/siteRules.ts | 48 ++++++ src/styles.css | 51 ++++++ 18 files changed, 728 insertions(+), 11 deletions(-) create mode 100644 src/analysis/siteRules.test.ts create mode 100644 src/analysis/siteRules.ts create mode 100644 src/panels/SiteRulesSection.tsx create mode 100644 src/panels/siteRulesInput.test.ts create mode 100644 src/panels/siteRulesInput.ts create mode 100644 src/plan/generatePlan.siteRules.test.ts create mode 100644 src/plan/generatePlan/siteRules.ts diff --git a/src/analysis/kennzahlen.ts b/src/analysis/kennzahlen.ts index 4c3f13aa..adb07eb3 100644 --- a/src/analysis/kennzahlen.ts +++ b/src/analysis/kennzahlen.ts @@ -3,7 +3,7 @@ // • Flächen je Geschoss aus den Räumen (SIA 416: GF, NGF/aGF), Summe über das Gebäude. // • Gebäudevolumen (GV) aus den freien Körpern (Massenmodell); Abzugskörper zählen nicht mit, // ihr Volumen wird abgezogen. -// • Ausnützungs-/Überbauungsziffer nur mit `project.parcelArea`. +// • Ausnützungs-/Überbauungsziffer nur mit `project.parcelArea` oder der Parzellengrenze (`siteRules`). // • Raumprogramm (`project.roomProgram`, Soll) gegen die gezeichneten Räume. // Alles rein und ohne Wasm — exakt für Prismen/Kegelstümpfe/Kreise, Näherung sonst (Fasen/Rundungen). @@ -64,7 +64,9 @@ export function computeKennzahlen(project: Project): Kennzahlen { gv += s.operation === "subtract" ? -v : v; } const footprint = levels.find((l) => l.gf > 0)?.gf ?? 0; - const parcel = project.parcelArea && project.parcelArea > 0 ? project.parcelArea : null; + // Parzellenfläche: eingegebene Zahl, sonst aus der Parzellengrenze des Baurechts. + const fromRules = project.siteRules?.parcel && project.siteRules.parcel.length >= 3 ? finite(polygonArea(project.siteRules.parcel)) : 0; + const parcel = project.parcelArea && project.parcelArea > 0 ? project.parcelArea : fromRules > 0 ? fromRules : null; return { levels, gf, diff --git a/src/analysis/siteRules.test.ts b/src/analysis/siteRules.test.ts new file mode 100644 index 00000000..c3a64f62 --- /dev/null +++ b/src/analysis/siteRules.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from "vitest"; +import { allowedArea, checkSiteRules, multiPolygonArea } from "./siteRules"; +import { computeKennzahlen } from "./kennzahlen"; +import type { ExtrudedSolid, Project, SiteRules, Vec2 } from "../model/types"; + +const rect = (x0: number, y0: number, x1: number, y1: number): Vec2[] => [ + { x: x0, y: y0 }, { x: x1, y: y0 }, { x: x1, y: y1 }, { x: x0, y: y1 }, +]; +// Parzelle 30 × 20 m; Kante 0 = Süd (y = 0), 1 = Ost, 2 = Nord, 3 = West. +const parcel = rect(0, 0, 30, 20); +const base: SiteRules = { parcel, defaultSetback: 4 }; + +function project(site: SiteRules, solids: ExtrudedSolid[] = []): Project { + return { + id: "t", name: "T", lineStyles: [], hatches: [], components: [], wallTypes: [], + drawingLevels: [ + { id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 3, cutHeight: 1, baseElevation: 0 }, + ], + layers: [], walls: [], openings: [], ceilings: [], stairs: [], rooms: [], drawings2d: [], context: [], + extrudedSolids: solids, siteRules: site, + } as unknown as Project; +} +const solid = (pts: Vec2[], height: number): ExtrudedSolid => + ({ id: "k" + pts[0].x, type: "extrudedSolid", levelId: "eg", points: pts, height }) as ExtrudedSolid; + +describe("zulässige Grundfläche", () => { + it("gleicher Grenzabstand rundum → inneres Rechteck", () => { + expect(multiPolygonArea(allowedArea(base))).toBeCloseTo(22 * 12, 6); + }); + it("Grenzabstand je Kante (Süden 8 m)", () => { + expect(multiPolygonArea(allowedArea({ ...base, setbacks: [8] }))).toBeCloseTo(22 * 8, 6); + }); + it("Baulinie begrenzt auf der Seite der Parzelle", () => { + // Baulinie bei y = 14, Richtung egal: zulässig ist die Seite mit dem Parzellen-Schwerpunkt. + const site = { ...base, setbacks: [8], buildingLines: [{ a: { x: 30, y: 14 }, b: { x: 0, y: 14 } }] }; + expect(multiPolygonArea(allowedArea(site))).toBeCloseTo(22 * 6, 6); + }); + it("Uhrzeigersinn der Parzelle spielt keine Rolle", () => { + expect(multiPolygonArea(allowedArea({ ...base, parcel: parcel.slice().reverse() }))).toBeCloseTo(22 * 12, 6); + }); + it("ungültige Parzelle → keine Fläche, kein Absturz", () => { + expect(allowedArea({ parcel: rect(0, 0, 1, 1).slice(0, 2), defaultSetback: 1 })).toEqual([]); + expect(multiPolygonArea(allowedArea({ parcel, defaultSetback: Number.NaN }))).toBeCloseTo(600, 6); + }); +}); + +describe("Prüfung gegen das Modell", () => { + it("Körper über dem Grenzabstand → Verstoss mit Fläche", () => { + const r = checkSiteRules(project(base, [solid(rect(1, 1, 6, 6), 6)]))!; + expect(r.violationArea).toBeCloseTo(25 - 4, 6); + expect(r.heightExceeded).toBe(false); + }); + it("Höhe über der Gesamthöhe", () => { + const r = checkSiteRules(project({ ...base, maxHeight: 10 }, [solid(rect(10, 6, 16, 12), 12)]))!; + expect(r.violationArea).toBeCloseTo(0, 6); + expect(r.maxTop).toBeCloseTo(12, 6); + expect(r.heightExceeded).toBe(true); + }); + it("ohne Baurecht → null", () => { + expect(checkSiteRules({ ...project(base), siteRules: undefined })).toBeNull(); + }); + it("Parzellenfläche aus der Grenze, wenn keine Zahl gesetzt ist", () => { + const p = project(base, [solid(rect(10, 6, 16, 12), 6)]); + expect(computeKennzahlen(p).az).not.toBeNull(); + expect(computeKennzahlen({ ...p, parcelArea: 1000 }).az).toBeCloseTo(computeKennzahlen(p).agf / 1000, 9); + }); +}); diff --git a/src/analysis/siteRules.ts b/src/analysis/siteRules.ts new file mode 100644 index 00000000..b323e3cf --- /dev/null +++ b/src/analysis/siteRules.ts @@ -0,0 +1,174 @@ +// Baurecht der Parzelle ([63]): zulässige Grundfläche aus Grenzabständen und Baulinien, Prüfung +// des Modells (Grundfläche ausserhalb, Gesamthöhe). +// +// • Grenzabstand: gesperrt ist alles, was näher als d_i an Kante i liegt (Streifen um die Kante +// mit gerundeten Enden) — so stimmen auch konkave Parzellen und einspringende Ecken. +// • Baulinie: Halbebene auf der Seite des Parzellen-Schwerpunkts. +// • Gebäude-Grundfläche: Wände aller Geschosse und freie Körper (ohne Abzugskörper). Vorsprünge +// (Dachüberstand, Balkone) und ihre Sonderregeln zählen nicht. + +import polygonClipping from "polygon-clipping"; +import type { MultiPolygon, Pair, Polygon as PcPolygon } from "polygon-clipping"; +import type { Project, SiteRules, Vec2 } from "../model/types"; +import { getFloor, getWallType, wallTypeThickness } from "../model/types"; +import { wallVerticalExtent } from "../model/wall"; +import { wallCorners } from "../model/geometry"; +import { roofBaseElevation, roofGeometry } from "../geometry/roof"; +import { polygonArea } from "../geometry/roomArea"; + +/** Polygone mit Ringen: `[polygon][ring]`, Ring 0 aussen, weitere Löcher; Ringe offen. */ +export type Area = Vec2[][][]; + +const ring = (pts: Vec2[]): Pair[] => [...pts.map((p): Pair => [p.x, p.y]), [pts[0].x, pts[0].y]]; +const fromPc = (mp: MultiPolygon): Area => mp.map((poly) => poly.map((r) => r.slice(0, -1).map(([x, y]) => ({ x, y })))); +const toPc = (a: Area): MultiPolygon => a.map((poly) => poly.map(ring)); + +/** Fläche einer Mehrfach-Fläche (Löcher abgezogen). */ +export function multiPolygonArea(a: Area): number { + let s = 0; + for (const poly of a) poly.forEach((r, i) => (s += (i === 0 ? 1 : -1) * polygonArea(r))); + return s; +} + +/** Streifen um die Strecke a–b mit Halbbreite d und Halbkreis-Enden (Polygon-Näherung). */ +function capsule(a: Vec2, b: Vec2, d: number, segs = 12): Vec2[] { + const ang = Math.atan2(b.y - a.y, b.x - a.x); + const pts: Vec2[] = []; + // Halbkreis um b (von rechts nach links der Richtung), dann um a; Polygon-Ecken AUSSERHALB + // des Kreises (Radius / cos), damit der gesperrte Streifen nie zu schmal gerät. + const r = d / Math.cos(Math.PI / (2 * segs)); + for (let i = 0; i <= segs; i++) { + const t = ang - Math.PI / 2 + (Math.PI * i) / segs; + const rr = i === 0 || i === segs ? d : r; + pts.push({ x: b.x + rr * Math.cos(t), y: b.y + rr * Math.sin(t) }); + } + for (let i = 0; i <= segs; i++) { + const t = ang + Math.PI / 2 + (Math.PI * i) / segs; + const rr = i === 0 || i === segs ? d : r; + pts.push({ x: a.x + rr * Math.cos(t), y: a.y + rr * Math.sin(t) }); + } + return pts; +} + +function centroid(pts: Vec2[]): Vec2 { + let a = 0, cx = 0, cy = 0; + for (let i = 0; i < pts.length; i++) { + const p = pts[i], q = pts[(i + 1) % pts.length]; + const c = p.x * q.y - q.x * p.y; + a += c; cx += (p.x + q.x) * c; cy += (p.y + q.y) * c; + } + if (Math.abs(a) < 1e-12) return pts[0]; + return { x: cx / (3 * a), y: cy / (3 * a) }; +} + +/** Grosses Rechteck = Halbebene der Baulinie a–b auf der Seite von `inside`. */ +function halfPlane(a: Vec2, b: Vec2, inside: Vec2, size: number): PcPolygon | null { + const dx = b.x - a.x, dy = b.y - a.y; + const len = Math.hypot(dx, dy); + if (!(len > 1e-9)) return null; + const ux = dx / len, uy = dy / len; + // Normale zur Innenseite. + let nx = -uy, ny = ux; + if ((inside.x - a.x) * nx + (inside.y - a.y) * ny < 0) { nx = -nx; ny = -ny; } + const p0 = { x: a.x - ux * size, y: a.y - uy * size }; + const p1 = { x: a.x + ux * size, y: a.y + uy * size }; + return [ring([p0, p1, { x: p1.x + nx * size, y: p1.y + ny * size }, { x: p0.x + nx * size, y: p0.y + ny * size }])]; +} + +const validParcel = (r: SiteRules) => + Array.isArray(r.parcel) && r.parcel.length >= 3 && r.parcel.every((p) => Number.isFinite(p.x) && Number.isFinite(p.y)) && polygonArea(r.parcel) > 1e-9; + +/** Grenzabstand der Kante i (ungültig/negativ → 0). */ +export function setbackOf(r: SiteRules, i: number): number { + const v = r.setbacks?.[i] ?? r.defaultSetback; + return Number.isFinite(v) && v > 0 ? v : 0; +} + +/** Zulässige Grundfläche (leer bei ungültiger Parzelle). */ +export function allowedArea(r: SiteRules): Area { + if (!validParcel(r)) return []; + const n = r.parcel.length; + let mp: MultiPolygon = [[ring(r.parcel)]]; + const strips: PcPolygon[] = []; + for (let i = 0; i < n; i++) { + const d = setbackOf(r, i); + if (d > 0) strips.push([ring(capsule(r.parcel[i], r.parcel[(i + 1) % n], d))]); + } + if (strips.length > 0) mp = polygonClipping.difference(mp, ...strips); + const c = centroid(r.parcel); + const xs = r.parcel.map((p) => p.x), ys = r.parcel.map((p) => p.y); + const size = 10 * (Math.max(...xs) - Math.min(...xs) + Math.max(...ys) - Math.min(...ys) + 1); + for (const line of r.buildingLines ?? []) { + const h = halfPlane(line.a, line.b, c, size); + if (h && mp.length > 0) mp = polygonClipping.intersection(mp, h); + } + return fromPc(mp); +} + +/** Grundfläche des Gebäudes (Wände aller Geschosse, freie Körper ohne Abzugskörper). */ +export function buildingFootprint(project: Project): Area { + const parts: PcPolygon[] = []; + for (const w of project.walls) { + if (Math.hypot(w.end.x - w.start.x, w.end.y - w.start.y) < 1e-9) continue; + parts.push([ring(wallCorners(w.start, w.end, wallTypeThickness(getWallType(project, w))))]); + } + for (const s of project.extrudedSolids ?? []) { + if (s.operation === "subtract" || s.points.length < 3) continue; + parts.push([ring(s.points)]); + } + if (parts.length === 0) return []; + return fromPc(polygonClipping.union(parts[0], ...parts.slice(1))); +} + +/** Höchster Punkt des Modells über ±0.00 (Wände, freie Körper, Dächer); `null` ohne Bauteile. */ +export function modelTop(project: Project): number | null { + let top = -Infinity; + for (const w of project.walls) top = Math.max(top, wallVerticalExtent(project, w).zTop); + for (const s of project.extrudedSolids ?? []) { + if (s.operation === "subtract") continue; + let base = 0; + try { + base = getFloor(project, s.levelId).baseElevation ?? 0; + } catch { + /* Geschoss fehlt → 0 */ + } + top = Math.max(top, base + (s.baseOffset ?? 0) + s.height); + } + for (const r of project.roofs ?? []) { + const eavesZ = roofBaseElevation(project, r); + top = Math.max(top, eavesZ + roofGeometry(r, eavesZ).ridgeHeight); + } + return Number.isFinite(top) ? top : null; +} + +export interface SiteCheck { + parcelArea: number; + allowed: Area; + allowedArea: number; + /** Gebäude-Grundfläche ausserhalb der zulässigen Fläche. */ + violations: Area; + violationArea: number; + maxTop: number | null; + heightExceeded: boolean; +} + +/** Prüft das Modell gegen `project.siteRules`; `null` ohne (gültiges) Baurecht. */ +export function checkSiteRules(project: Project): SiteCheck | null { + const r = project.siteRules; + if (!r || !validParcel(r)) return null; + const allowed = allowedArea(r); + const fp = buildingFootprint(project); + const violations = fp.length === 0 ? [] : allowed.length === 0 ? fp : fromPc(polygonClipping.difference(toPc(fp), toPc(allowed))); + // Kleinste Splitter (Rundung an gemeinsamen Kanten) nicht als Verstoss melden. + const real = violations.filter((poly) => polygonArea(poly[0]) > 1e-4); + const maxTop = modelTop(project); + return { + parcelArea: polygonArea(r.parcel), + allowed, + allowedArea: multiPolygonArea(allowed), + violations: real, + violationArea: multiPolygonArea(real), + maxTop, + heightExceeded: r.maxHeight !== undefined && maxTop !== null && maxTop > r.maxHeight + 1e-6, + }; +} diff --git a/src/cli/main.ts b/src/cli/main.ts index 503ce7d9..115ddd05 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -30,6 +30,7 @@ import { shadowPolygons, projectLatLon, checkRoomProgram, + checkSiteRules, exportStl, generateElevationPlan, diffToOps, @@ -207,7 +208,8 @@ export async function run(argv: string[]): Promise { case "kennzahlen": { const k = computeKennzahlen(project); const prog = checkRoomProgram(project); - out(args, JSON.stringify({ kennzahlen: k, raumprogramm: prog }, null, 2), `${project.name || "projekt"}-kennzahlen.json`); + const baurecht = checkSiteRules(project); + out(args, JSON.stringify({ kennzahlen: k, raumprogramm: prog, baurecht }, null, 2), `${project.name || "projekt"}-kennzahlen.json`); return 0; } case "sun": { diff --git a/src/core/extra.ts b/src/core/extra.ts index c7a0f7be..399d2802 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -16,3 +16,5 @@ export { computeKennzahlen, checkRoomProgram, solidVolume } from "../analysis/ke export type { Kennzahlen, ProgramCheck } from "../analysis/kennzahlen"; export { sunPosition, shadowPolygons, shadowOfPrism, projectLatLon } from "../analysis/sun"; export type { SunPosition } from "../analysis/sun"; +export { checkSiteRules, allowedArea, multiPolygonArea, buildingFootprint, modelTop } from "../analysis/siteRules"; +export type { SiteCheck } from "../analysis/siteRules"; diff --git a/src/i18n/de.ts b/src/i18n/de.ts index dca3dcbf..dd6ef6f8 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1778,6 +1778,7 @@ export const de = { "kennzahlen.az": "Ausnützungsziffer aGF / Parzelle", "kennzahlen.uez": "Überbauungsziffer bebaute Fläche / Parzelle", "kennzahlen.parcelArea": "Parzellenfläche", + "kennzahlen.parcelArea.hint": "Leer lassen, um die Fläche der Parzellengrenze (Lage-Panel) zu verwenden.", "program.title": "Raumprogramm", "program.name": "Name", "program.namePlaceholder": "Raumname", @@ -1803,6 +1804,25 @@ export const de = { "sun.belowHorizon": "Sonne unter dem Horizont", "sun.noAnchor": "Standort Zürich angenommen", "sun.noAnchor.hint": "Ohne Georeferenz rechnet die Studie mit Zürich. Standort über «Standort importieren» oder «Neuer Bezugspunkt» festlegen.", + "siteRules.title": "Baurecht der Parzelle", + "siteRules.show": "im Grundriss", + "siteRules.fromSelection": "Parzelle aus Auswahl", + "siteRules.fromSelection.hint": "Eine geschlossene Polylinie oder ein Rechteck wählen (z. B. die Parzellengrenze aus dem Kataster).", + "siteRules.replaceParcel": "Grenze ersetzen", + "siteRules.remove": "Baurecht entfernen", + "siteRules.areas": "Parzelle {parcel} m² · zulässig {allowed} m²", + "siteRules.violation": "Gebäude {area} m² ausserhalb der zulässigen Fläche", + "siteRules.inside": "Gebäude innerhalb der zulässigen Fläche", + "siteRules.heightOk": "Höhe {top} m ≤ {max} m", + "siteRules.heightOver": "Höhe {top} m über {max} m", + "siteRules.defaultSetback": "Grenzabstand", + "siteRules.maxHeight": "Gesamthöhe max.", + "siteRules.edges": "Grenzabstand je Kante ({n})", + "siteRules.edge": "Kante {i} ({len} m)", + "siteRules.lines": "Baulinien: {n}", + "siteRules.addLine": "Baulinie aus Auswahl", + "siteRules.addLine.hint": "Eine Linie wählen; das Gebäude bleibt auf der Seite der Parzelle.", + "siteRules.clearLines": "Alle Baulinien entfernen", "clash.none": "Keine Kollisionen gefunden.", "clash.found": "Kollisionen gefunden", "clash.failed": "Kollisionsprüfung fehlgeschlagen", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index d74b99b9..5d64cc7d 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1739,6 +1739,7 @@ export const en: Record = { "kennzahlen.az": "Floor area ratio (usable area / site)", "kennzahlen.uez": "Site coverage (built area / site)", "kennzahlen.parcelArea": "Site area", + "kennzahlen.parcelArea.hint": "Leave empty to use the area of the parcel boundary (Site panel).", "program.title": "Room programme", "program.name": "Name", "program.namePlaceholder": "Room name", @@ -1764,6 +1765,25 @@ export const en: Record = { "sun.belowHorizon": "Sun below the horizon", "sun.noAnchor": "Location assumed: Zurich", "sun.noAnchor.hint": "Without georeference the study uses Zurich. Set the location via “Import location” or “New reference point”.", + "siteRules.title": "Zoning of the parcel", + "siteRules.show": "in plan", + "siteRules.fromSelection": "Parcel from selection", + "siteRules.fromSelection.hint": "Select a closed polyline or a rectangle (e.g. the parcel boundary from the cadastre).", + "siteRules.replaceParcel": "Replace boundary", + "siteRules.remove": "Remove zoning", + "siteRules.areas": "Parcel {parcel} m² · buildable {allowed} m²", + "siteRules.violation": "Building {area} m² outside the buildable area", + "siteRules.inside": "Building inside the buildable area", + "siteRules.heightOk": "Height {top} m ≤ {max} m", + "siteRules.heightOver": "Height {top} m exceeds {max} m", + "siteRules.defaultSetback": "Boundary distance", + "siteRules.maxHeight": "Max. total height", + "siteRules.edges": "Distance per edge ({n})", + "siteRules.edge": "Edge {i} ({len} m)", + "siteRules.lines": "Building lines: {n}", + "siteRules.addLine": "Building line from selection", + "siteRules.addLine.hint": "Select a line; the building stays on the parcel side.", + "siteRules.clearLines": "Remove all building lines", "clash.none": "No clashes found.", "clash.found": "Clashes found", "clash.failed": "Clash detection failed", diff --git a/src/io/projectFormat.ts b/src/io/projectFormat.ts index 78406a36..298f28b1 100644 --- a/src/io/projectFormat.ts +++ b/src/io/projectFormat.ts @@ -69,7 +69,7 @@ const KNOWN_KEYS = new Set([ "walls", "ceilings", "roofs", "openings", "stairs", "rooms", "drawings2d", "context", "extrudedSolids", "columns", "groups", "parametricWalls", "overrideRules", "viewSnapshots", "viewSnapshotFolders", "layouts", "masterLayouts", "layoutFolders", "referenceElevationMasl", - "geoAnchor", "roomProgram", "parcelArea", "sunStudy", + "geoAnchor", "roomProgram", "parcelArea", "sunStudy", "siteRules", ]); export type ParseProjectResult = diff --git a/src/model/types.ts b/src/model/types.ts index 8d261d40..f23a916a 100644 --- a/src/model/types.ts +++ b/src/model/types.ts @@ -946,6 +946,25 @@ export interface RoomProgramRow { * Geschoss nutzt floorHeight/cutHeight/baseElevation; Schnitt/Ansicht nutzen * linePoints/directionSign; "drawing" nutzt keines dieser Felder. */ +/** + * Baurecht einer Parzelle ([63]). Die zulässige Grundfläche ist die Parzelle ohne die Streifen + * „näher als der Grenzabstand an Kante i", begrenzt durch die Baulinien. + */ +export interface SiteRules { + /** Parzellengrenze als geschlossener Ring (Modell-Meter, Umlaufsinn beliebig). */ + parcel: Vec2[]; + /** Grenzabstand (m) je Kante i = parcel[i] → parcel[i+1]; fehlende Einträge → `defaultSetback`. */ + setbacks?: number[]; + /** Grenzabstand (m) für alle Kanten ohne eigenen Wert. */ + defaultSetback: number; + /** Baulinien: das Gebäude bleibt auf der Seite der Linie, auf der der Parzellen-Schwerpunkt liegt. */ + buildingLines?: { a: Vec2; b: Vec2 }[]; + /** Zulässige Gesamthöhe über ±0.00 (m). */ + maxHeight?: number; + /** Parzelle, zulässige Fläche und Verstösse im Grundriss zeigen (Default: ja). */ + show?: boolean; +} + /** Schattenstudie (`analysis/sun.ts`): der Schatten liegt auf dem Geschoss nächst ±0.00. */ export interface SunStudy { /** Zeitpunkt als ISO-8601-Text in UTC, z. B. "2026-12-21T11:00:00Z". */ @@ -2916,6 +2935,8 @@ export interface Project { parcelArea?: number; /** Schattenstudie: Zeitpunkt (ISO 8601, UTC) und ob der Boden-Schatten im Grundriss erscheint. */ sunStudy?: SunStudy; + /** Baurecht der Parzelle: Grenze, Grenzabstände, Baulinien, Gesamthöhe (`analysis/siteRules.ts`). */ + siteRules?: SiteRules; /** Grafik-Kategorie-Baum (geschossübergreifend). */ layers: LayerCategory[]; walls: Wall[]; diff --git a/src/panels/KennzahlenSection.tsx b/src/panels/KennzahlenSection.tsx index 07a185ef..efe7b169 100644 --- a/src/panels/KennzahlenSection.tsx +++ b/src/panels/KennzahlenSection.tsx @@ -1,7 +1,7 @@ // Kennzahlenleiste [62] und Raumprogramm-Editor [61] im Flächenbilanz-Panel. // // • Leiste: GF, aGF, GV, AZ, ÜZ (live aus `computeKennzahlen`), darunter je Geschoss GF/aGF. -// • Parzellenfläche: Eingabefeld → `Project.parcelArea` (leer/0 = nicht gesetzt). +// • Parzellenfläche: Eingabefeld → `Project.parcelArea` (leer/0 = aus der Parzellengrenze, sonst nicht gesetzt). // • Raumprogramm: Soll-Zeilen (Name, Fläche je Raum, Anzahl) bearbeiten; der Status je Zeile // kommt aus `checkRoomProgram`. // Änderungen laufen über `setProject` mit coalesceKey, damit Tippen einen Undo-Schritt ergibt. @@ -10,7 +10,7 @@ import { t } from "../i18n"; import type { TranslationKey } from "../i18n"; import { usePanelHost } from "./host"; import { useStore } from "../state/appStore"; -import { checkRoomProgram, computeKennzahlen } from "../core"; +import { checkRoomProgram, computeKennzahlen, polygonArea } from "../core"; import type { Project, RoomProgramRow } from "../model/types"; type ProgramStatus = ReturnType["rows"][number]["status"]; @@ -92,7 +92,8 @@ export function KennzahlenSection() { step={1} className="kz-input kz-num" value={project.parcelArea !== undefined ? String(project.parcelArea) : ""} - placeholder="–" + placeholder={project.siteRules?.parcel && project.siteRules.parcel.length >= 3 ? fmt(polygonArea(project.siteRules.parcel)) : "–"} + title={t("kennzahlen.parcelArea.hint")} onChange={(e) => setParcel(e.target.value)} /> m² diff --git a/src/panels/SitePanel.tsx b/src/panels/SitePanel.tsx index 455d3ae1..e70d66f4 100644 --- a/src/panels/SitePanel.tsx +++ b/src/panels/SitePanel.tsx @@ -7,6 +7,7 @@ // Dialog) + „Gelände erzeugen" (aus dem gewählten Kontur-Satz). // • Liste der Kontext-Objekte: Name + Typ-Badge + „Entfernen". // • Schattenstudie (SunStudySection): Schalter, Datum, Zeitregler. +// • Baurecht (SiteRulesSection): Parzelle, Grenzabstände, Baulinien, Gesamthöhe. // • DWG-Hinweis am Fuß. // // Bezeichner englisch, UI-Text/Kommentare deutsch (CONVENTIONS.md). Alle sichtbaren @@ -23,6 +24,7 @@ import { useStore } from "../state/appStore"; import { isTauriRuntime } from "../native/projectFile"; import { openContextImportWindowNative } from "../native/contextImportWindow"; import { SunStudySection } from "./SunStudySection"; +import { SiteRulesSection } from "./SiteRulesSection"; /** Typ-spezifisches Badge-Label (i18n-Key) je Kontext-Objekt-Art. */ function typeBadgeKey(obj: ContextObject): TranslationKey { @@ -159,6 +161,8 @@ export function SitePanel() {
+ +
{/* Kontext-Objekte nach Ebene (`layer`) gruppiert: importierte Gebäude liegen als EINZELNE, getrennt lösch-/anwählbare Elemente unter ihrer diff --git a/src/panels/SiteRulesSection.tsx b/src/panels/SiteRulesSection.tsx new file mode 100644 index 00000000..6dae8103 --- /dev/null +++ b/src/panels/SiteRulesSection.tsx @@ -0,0 +1,203 @@ +// Baurecht im Lage-Panel ([63]): Parzelle und Baulinien aus der Auswahl übernehmen, +// Grenzabstände (pauschal und je Kante), Gesamthöhe; Ergebnis der Prüfung. Die Darstellung im +// Grundriss entsteht aus `Project.siteRules` (`plan/generatePlan/siteRules.ts`). + +import { t } from "../i18n"; +import { usePanelHost } from "./host"; +import { useStore } from "../state/appStore"; +import { checkSiteRules } from "../core"; +import type { Project, SiteRules } from "../model/types"; +import { lineFromDrawing, parcelFromDrawing } from "./siteRulesInput"; + +const fmt = (n: number, d = 1) => n.toLocaleString("de-CH", { minimumFractionDigits: d, maximumFractionDigits: d }); + +/** Zahl aus einer Eingabe; leer → undefined, ungültig/negativ → null (verwerfen). */ +function parseLen(text: string): number | undefined | null { + if (text.trim() === "") return undefined; + const v = Number(text.trim().replace(",", ".")); + return Number.isFinite(v) && v >= 0 ? v : null; +} + +export function SiteRulesSection() { + const host = usePanelHost(); + const setProject = useStore((s) => s.setProject); + const rules = host.project.siteRules; + const sel = host.selection; + const selDrawing = sel?.kind === "drawing2d" ? host.project.drawings2d.find((d) => d.id === sel.id) : undefined; + const selParcel = parcelFromDrawing(selDrawing); + const selLine = lineFromDrawing(selDrawing); + + const write = (fn: (r: SiteRules) => SiteRules | undefined, key?: string) => + setProject((p: Project) => { + const { siteRules: old, ...rest } = p; + if (!old) return p; + const next = fn(old); + return next ? { ...rest, siteRules: next } : rest; + }, key); + + const takeParcel = () => { + if (!selParcel) return; + setProject((p: Project) => { + // Neue Grenze: Grenzabstände je Kante passen nicht mehr → zurücksetzen. + const { setbacks: _old, ...prev } = p.siteRules ?? { parcel: [], defaultSetback: 4 }; + return { ...p, siteRules: { ...prev, parcel: selParcel } }; + }); + }; + + if (!rules) { + return ( +
+
{t("siteRules.title")}
+ + {!selParcel &&
{t("siteRules.fromSelection.hint")}
} +
+ ); + } + + const check = checkSiteRules(host.project); + const n = rules.parcel.length; + const ok = check !== null && check.violationArea < 0.01 && !check.heightExceeded; + + return ( +
+
+ {t("siteRules.title")} + +
+ + {check && ( +
+
{t("siteRules.areas", { parcel: fmt(check.parcelArea), allowed: fmt(check.allowedArea) })}
+
+ {check.violationArea >= 0.01 + ? t("siteRules.violation", { area: fmt(check.violationArea, 2) }) + : t("siteRules.inside")} +
+ {rules.maxHeight !== undefined && check.maxTop !== null && ( +
+ {t(check.heightExceeded ? "siteRules.heightOver" : "siteRules.heightOk", { + top: fmt(check.maxTop, 2), + max: fmt(rules.maxHeight, 2), + })} +
+ )} +
+ )} + + + + +
+ {t("siteRules.edges", { n })} + {rules.parcel.map((p, i) => { + const q = rules.parcel[(i + 1) % n]; + const own = rules.setbacks?.[i]; + return ( + + ); + })} +
+ +
+ {t("siteRules.lines", { n: rules.buildingLines?.length ?? 0 })} + + {(rules.buildingLines?.length ?? 0) > 0 && ( + + )} +
+ +
+ + +
+
+ ); +} diff --git a/src/panels/siteRulesInput.test.ts b/src/panels/siteRulesInput.test.ts new file mode 100644 index 00000000..03a463ee --- /dev/null +++ b/src/panels/siteRulesInput.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from "vitest"; +import { lineFromDrawing, parcelFromDrawing } from "./siteRulesInput"; +import type { Drawing2D, Drawing2DGeom } from "../model/types"; + +const d = (geom: Drawing2DGeom): Drawing2D => ({ id: "d", type: "drawing2d", levelId: "eg", categoryCode: "20", geom }) as Drawing2D; + +describe("Parzelle und Baulinie aus der Auswahl", () => { + it("Rechteck und geschlossene Polylinie (doppelter Schlusspunkt entfällt)", () => { + expect(parcelFromDrawing(d({ shape: "rect", min: { x: 0, y: 0 }, max: { x: 2, y: 1 } }))).toHaveLength(4); + const pts = [{ x: 0, y: 0 }, { x: 3, y: 0 }, { x: 3, y: 2 }, { x: 0, y: 2 }, { x: 0, y: 0 }]; + expect(parcelFromDrawing(d({ shape: "polyline", pts, closed: true }))).toHaveLength(4); + }); + it("offene Polylinie ist keine Parzelle, aber zweipunktig eine Baulinie", () => { + const pts = [{ x: 0, y: 0 }, { x: 3, y: 0 }]; + expect(parcelFromDrawing(d({ shape: "polyline", pts, closed: false }))).toBeNull(); + expect(lineFromDrawing(d({ shape: "polyline", pts, closed: false }))).toEqual({ a: pts[0], b: pts[1] }); + expect(lineFromDrawing(d({ shape: "line", a: pts[0], b: pts[1] }))).toEqual({ a: pts[0], b: pts[1] }); + expect(lineFromDrawing(undefined)).toBeNull(); + }); +}); diff --git a/src/panels/siteRulesInput.ts b/src/panels/siteRulesInput.ts new file mode 100644 index 00000000..4d54a0d4 --- /dev/null +++ b/src/panels/siteRulesInput.ts @@ -0,0 +1,29 @@ +// Übernahme von Parzellengrenze und Baulinien aus gezeichneter 2D-Geometrie (Lage-Panel, [63]). + +import type { Drawing2D, Vec2 } from "../model/types"; + +/** Geschlossene Polylinie oder Rechteck → Parzellenring; sonst `null`. */ +export function parcelFromDrawing(d: Drawing2D | undefined): Vec2[] | null { + const g = d?.geom; + if (!g) return null; + if (g.shape === "rect") { + return [g.min, { x: g.max.x, y: g.min.y }, g.max, { x: g.min.x, y: g.max.y }]; + } + if (g.shape === "polyline" && g.closed && g.pts.length >= 3) { + // Doppelter Schlusspunkt (manche Importe) weglassen. + const pts = g.pts.slice(); + const f = pts[0], l = pts[pts.length - 1]; + if (pts.length > 3 && Math.hypot(f.x - l.x, f.y - l.y) < 1e-9) pts.pop(); + return pts.map((p) => ({ x: p.x, y: p.y })); + } + return null; +} + +/** Linie, Hilfslinie, Strahl oder zweipunktige Polylinie → Baulinie; sonst `null`. */ +export function lineFromDrawing(d: Drawing2D | undefined): { a: Vec2; b: Vec2 } | null { + const g = d?.geom; + if (!g) return null; + if (g.shape === "line" || g.shape === "xline" || g.shape === "ray") return { a: { ...g.a }, b: { ...g.b } }; + if (g.shape === "polyline" && !g.closed && g.pts.length === 2) return { a: { ...g.pts[0] }, b: { ...g.pts[1] } }; + return null; +} diff --git a/src/plan/generatePlan.siteRules.test.ts b/src/plan/generatePlan.siteRules.test.ts new file mode 100644 index 00000000..f380b02f --- /dev/null +++ b/src/plan/generatePlan.siteRules.test.ts @@ -0,0 +1,44 @@ +/** + * `generatePlan` — Baurecht (`Project.siteRules`): Parzellengrenze, zulässige Fläche und + * Verstösse im Geschoss nächst ±0.00. + */ + +import { describe, it, expect } from "vitest"; +import { generatePlan } from "./generatePlan"; +import { SITE_CLS } from "./generatePlan/siteRules"; +import { sampleProject } from "../model/sampleProject"; +import { flattenCategories } from "../model/types"; +import type { Project, SiteRules } from "../model/types"; + +const ALL = new Set(flattenCategories(sampleProject.layers).map((c) => c.code)); +const site: SiteRules = { + parcel: [{ x: -10, y: -10 }, { x: 20, y: -10 }, { x: 20, y: 20 }, { x: -10, y: 20 }], + defaultSetback: 4, +}; +const withSite = (s: SiteRules | undefined): Project => ({ ...sampleProject, siteRules: s }); +const prims = (p: Project, floorId: string) => generatePlan(p, floorId, ALL).primitives; + +describe("Baurecht im Grundriss", () => { + it("Parzellengrenze und zulässige Fläche als Linien im EG", () => { + const ps = prims(withSite(site), "eg"); + expect(ps.filter((q) => q.kind === "line" && q.cls === SITE_CLS.parcel).length).toBe(4); + expect(ps.filter((q) => q.kind === "line" && q.cls === SITE_CLS.allowed).length).toBe(4); + expect(ps.some((q) => q.kind === "polygon" && q.fill === SITE_CLS.violationFill)).toBe(false); + }); + it("Gebäude über dem Grenzabstand → rote Fläche, zuoberst gezeichnet", () => { + const ps = prims(withSite({ ...site, defaultSetback: 12 }), "eg"); + const last = ps[ps.length - 1]; + expect(last.kind === "polygon" && last.fill === SITE_CLS.violationFill).toBe(true); + }); + it("nicht im OG, nicht ausgeblendet, nicht ohne Baurecht", () => { + const has = (ps: ReturnType) => ps.some((q) => q.kind === "line" && q.cls === SITE_CLS.parcel); + expect(has(prims(withSite(site), "og"))).toBe(false); + expect(has(prims(withSite({ ...site, show: false }), "eg"))).toBe(false); + expect(has(prims(withSite(undefined), "eg"))).toBe(false); + }); + it("Planbegrenzung umfasst die Parzelle", () => { + const b = generatePlan(withSite(site), "eg", ALL).bounds; + expect(b.minX).toBeLessThanOrEqual(-10); + expect(b.maxY).toBeGreaterThanOrEqual(20); + }); +}); diff --git a/src/plan/generatePlan.ts b/src/plan/generatePlan.ts index 1090e0e2..93ca1950 100644 --- a/src/plan/generatePlan.ts +++ b/src/plan/generatePlan.ts @@ -73,6 +73,7 @@ import { addCeilingPoche } from "./generatePlan/ceilings"; import { subtractVoidsInPlan } from "./voids"; import { addContextContours } from "./generatePlan/context"; import { addSunShadow } from "./generatePlan/sunShadow"; +import { addSiteRules, addSiteViolations } from "./generatePlan/siteRules"; import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension"; import { addDrawing2D, @@ -352,7 +353,9 @@ export function generatePlan( const primitives: Primitive[] = []; // Schattenstudie zuunterst (projektglobal, nur im Geschoss nächst ±0.00). if (includeGlobal) addSunShadow(primitives, project, floorId); - const shadowCount = primitives.length; + // Baurecht (Parzelle, zulässige Fläche, Verstösse), ebenfalls zuunterst. + if (includeGlobal) addSiteRules(primitives, project, floorId); + const underlayCount = primitives.length; // Aktives Geschoss (für die Grundriss-Schnitthöhe der Treppen). const floor = project.drawingLevels.find((z) => z.id === floorId); // Code → Kategorie-Strichstärke (mm), damit die Wand-Umrisslinie aus dem @@ -659,6 +662,9 @@ export function generatePlan( // Abzugskörper (Aussparungen/Durchbrüche): von Wand-/Stützen-/Decken-Poché abziehen. subtractVoidsInPlan(primitives, project, (floor?.baseElevation ?? 0) + (floor?.cutHeight ?? 1.0)); + // Baurechts-Verstösse über allem (Signal, soll nicht unter der Wand-Poché verschwinden). + if (includeGlobal) addSiteViolations(primitives, project, floorId); + if (mono) toMono(primitives); // Georeferenzierte Luftbilder als Hintergrund-Ebenen (nur interaktive Ansicht, @@ -679,7 +685,7 @@ export function generatePlan( return { primitives, - bounds: computeBounds(project, walls, drawings, ceilings, stairs, rooms, roofs, primitives.slice(0, shadowCount)), + bounds: computeBounds(project, walls, drawings, ceilings, stairs, rooms, roofs, primitives.slice(0, underlayCount)), backgroundImages, ...(underlay.length ? { underlay } : {}), }; @@ -1060,7 +1066,7 @@ function computeBounds( stairs: Stair[] = [], rooms: Room[] = [], roofs: Roof[] = [], - /** Zusätzlich einzurahmende Flächen (Schattenstudie), damit Druck/Einpassen den ganzen Schatten zeigen. */ + /** Zusätzlich einzurahmende Primitive (Schatten, Parzelle), damit Druck/Einpassen sie ganz zeigen. */ extra: Primitive[] = [], ) { let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; @@ -1074,7 +1080,10 @@ function computeBounds( } for (const c of ceilings) for (const p of c.outline) acc(p); for (const r of rooms) for (const p of r.boundary) acc(p); - for (const e of extra) if (e.kind === "polygon") e.pts.forEach(acc); + for (const e of extra) { + if (e.kind === "polygon") e.pts.forEach(acc); + else if (e.kind === "line") { acc(e.a); acc(e.b); } + } // Traufe (inkl. Überstand) statt reinem Umriss, damit ein weit auskragendes // Dach das „Einpassen" korrekt mit einrahmt. for (const roof of roofs) for (const p of roofGeometry(roof, 0).eaves) acc(p); diff --git a/src/plan/generatePlan/siteRules.ts b/src/plan/generatePlan/siteRules.ts new file mode 100644 index 00000000..1e81a051 --- /dev/null +++ b/src/plan/generatePlan/siteRules.ts @@ -0,0 +1,48 @@ +// Baurecht im Grundriss ([63]): Parzellengrenze (strichpunktiert), zulässige Grundfläche +// (gestrichelt), beides zuunterst, und Gebäude-Grundfläche ausserhalb davon (rot, halbtransparent, +// zuoberst). Nur im Geschoss +// nächst ±0.00, wie die Schattenstudie. Rechnung in `analysis/siteRules.ts`. + +import type { Project, Vec2 } from "../../model/types"; +import { checkSiteRules } from "../../analysis/siteRules"; +import { withoutHoles } from "../../analysis/sun"; +import { NO_HATCH, type Primitive } from "./shared"; +import { groundFloorId } from "./sunShadow"; + +/** Erkennungsmerkmale (Linien-Klassen, Füllfarbe) — auch für Tests. */ +export const SITE_CLS = { + parcel: "site-parcel", + allowed: "site-allowed", + violationFill: "#d0342c", +} as const; + +const PARCEL_COLOR = "#1f6f3f"; +const ALLOWED_COLOR = "#2b5fae"; + +function ringLines(out: Primitive[], pts: Vec2[], cls: string, color: string, weightMm: number, dash: number[]): void { + for (let i = 0; i < pts.length; i++) { + out.push({ kind: "line", a: pts[i], b: pts[(i + 1) % pts.length], cls, weightMm, dash, color }); + } +} + +/** Parzellengrenze und zulässige Fläche (zuunterst gezeichnet). */ +export function addSiteRules(out: Primitive[], project: Project, floorId: string): void { + const rules = project.siteRules; + if (!rules || rules.show === false || groundFloorId(project) !== floorId) return; + const check = checkSiteRules(project); + if (!check) return; + // Parzellengrenze: Strich-Punkt; zulässige Fläche: gestrichelt (Papier-mm). + ringLines(out, rules.parcel, SITE_CLS.parcel, PARCEL_COLOR, 0.35, [6, 1.5, 0.5, 1.5]); + for (const poly of check.allowed) for (const r of poly) ringLines(out, r, SITE_CLS.allowed, ALLOWED_COLOR, 0.25, [2, 1]); +} + +/** Gebäude-Grundfläche ausserhalb der zulässigen Fläche (zuoberst, damit sie über der Wand liegt). */ +export function addSiteViolations(out: Primitive[], project: Project, floorId: string): void { + const rules = project.siteRules; + if (!rules || rules.show === false || groundFloorId(project) !== floorId) return; + for (const poly of checkSiteRules(project)?.violations ?? []) { + for (const pts of withoutHoles(poly)) { + out.push({ kind: "polygon", pts, fill: SITE_CLS.violationFill, stroke: "none", strokeWidthMm: 0, hatch: NO_HATCH, opacity: 0.45 }); + } + } +} diff --git a/src/styles.css b/src/styles.css index 498724df..47a29872 100644 --- a/src/styles.css +++ b/src/styles.css @@ -8184,3 +8184,54 @@ body { color: var(--ink-2); font-size: 11px; } + +/* Baurecht (Lage-Panel, SiteRulesSection). */ +.site-rules { + display: flex; + flex-direction: column; + gap: 6px; +} +.site-rules-head { + display: flex; + align-items: center; + justify-content: space-between; + font-weight: 600; +} +.site-rules-head .sun-row { + font-weight: normal; +} +.site-rules-result { + padding: 4px 6px; + border-radius: 6px; + border: 1px solid var(--line); + font-size: 11px; + line-height: 1.5; +} +.site-rules-result.ok { + border-color: var(--ok, #2f8f4e); +} +.site-rules-result.bad { + border-color: var(--danger); + color: var(--danger-light, var(--danger)); +} +.site-rules-edges summary { + cursor: pointer; + color: var(--ink-2); + margin-bottom: 4px; +} +.site-rules-edges .kz-parcel { + margin: 2px 0 2px 10px; +} +.site-rules-lines { + display: flex; + align-items: center; + gap: 6px; +} +.site-rules-lines > span { + flex: 1 1 auto; + color: var(--ink-2); +} +.site-panel .site-btn:disabled { + opacity: 0.5; + cursor: default; +}