[K2] 3D-Ableitungen Decken, Stützen, Treppen und 2D-Zeichnungen nach Rust

ceilings3d.rs (Aussparungen über Brücken-Trick, Schicht-Spannen), columns3d.rs
(Prisma-Meshes), stairs3d.rs (Tritt-Slabs je Tragart, Nase, Setzstufen, Podest,
Soffit-Scheiben, Betonlaufplatte, Handlauf/Pfosten; Geometrie direkt aus kernel2d),
drawing2d_3d.rs (Boden-Spuren und Pick-Strecken in Chargen), mesh3d.rs, jsmath.rs
(V8-Math.hypot für bitgleiche Ergebnisse). toWalls3d/{ceilings,columns,stairs,drawing2d}.ts
sammeln nur noch aus dem Project und färben ein; TS-Rechenlogik gelöscht.
extrusions.ts und voids3d.ts bleiben TS (truck-Pfad).

Ergebnis bitgleich zur alten TS-Fassung (460 Projekte inkl. Zufallsfälle).
This commit is contained in:
Claude committed 2026-10-27 22:17:39 +00:00
1 parent d6c1817801
commit cc7c42f9cd
20 files changed
+1570 -594

No files matched your search

+71 -62
View File
@@ -1,13 +1,18 @@
// Decken-Domäne der 3D-Ableitung: extrudiert `project.ceilings` zu geschichteten
// Deckenplatten (eine RSlab je Materiallage, oben→unten gestapelt) — das 3D-
// Pendant zu `generatePlan/ceilings.ts::addCeilingPoche`.
//
// Die Rechnung (Aussparungen über den Brücken-Trick in EINEN einfachen Umriss, derselbe Ring für
// ALLE Schichten; z-Spanne proportional auf die Schichten verteilt) steht in Rust
// (`src-tauri/core/src/ceilings3d.rs`). Hier nur: aus dem `Project` sammeln und je Schicht
// Farbe, Schraffur und Schnitt-Metadaten zuordnen.
import type { Layer, Project } from "../../model/types";
import type { Ceiling, Layer, Project } from "../../model/types";
import { getCeilingType, getComponent } from "../../model/types";
import { ceilingVerticalExtent } from "../../model/wall";
import { mergeHoles } from "../../geometry/polygonHoles";
import { core } from "../../engine/coreWasm";
import { FlatWriter } from "../../geometry/coreFlat";
import {
EPS,
SLAB_RGB,
hexToRgb,
resolveComponentHatch,
@@ -20,77 +25,81 @@ import {
/** Emittiert die Deckenplatten eines Projekts (falls vorhanden). */
export function emitSlabs(project: Project): RSlab[] {
const out: RSlab[] = [];
const ceilings: Ceiling[] = [];
const layersOf: (Layer[] | undefined)[] = [];
const w = new FlatWriter();
const count = w.slot();
for (const c of project.ceilings ?? []) {
if (!c.outline || c.outline.length < 3) continue;
// zBottom/zTop (und damit die Deckendicke) berechnet ceilingVerticalExtent
// bereits über ceilingThickness (respektiert Typ-Dicke + Übersteuerung).
const { zBottom, zTop } = ceilingVerticalExtent(project, c);
if (zTop - zBottom <= EPS) continue;
// Aussparungen (Treppenauge/Schacht) über den Brücken-Trick in EINEN
// einfachen Umriss-Ring einfügen — derselbe Ring für ALLE Schichten dieser
// Decke. Kein `openings` ⇒ unverändertes `c.outline` (exakt heutiges
// Verhalten). Der Ring ist paritätskorrekt fürs Ear-Clipping (render3d)
// UND fürs Pick (pickGeometry nutzt denselben emitSlabs-Pfad): ein Klick
// ins Loch trifft die Decke NICHT — das ist gewollt.
const openings = c.openings ?? [];
const mergedOutline = openings.length ? mergeHoles(c.outline, openings).ring : c.outline;
const outline = mergedOutline.map((p) => [p.x, p.y] as RVec2);
// Geschichteter Bodenaufbau: je Schicht des Deckentyps EIN eigener Slab,
// von oben (OK, erste Lage) nach unten (UK, letzte Lage) gestapelt und
// proportional auf die tatsächliche z-Spanne [zBottom, zTop] verteilt (wie
// die Lagen-Summe bei den Wänden). Jede Lage trägt ihre Bauteil-Schraffur +
// -Farbe — so zeigt der 3D-Schnitt den Bodenaufbau GESCHICHTET (Estrich/
// Dämmung/Beton …), identisch zum 2D-Schnitt, statt eines Einkörpers in der
// dominanten Schicht. Kein auflösbarer Deckentyp / keine Lagen ⇒ EIN
// Vollkörper-Slab in SLAB_RGB (bisheriges Fallback-Verhalten).
// Kein auflösbarer Deckentyp ⇒ keine Lagen ⇒ EIN Vollkörper-Slab in SLAB_RGB.
let layers: Layer[] | undefined;
try {
layers = getCeilingType(project, c).layers;
} catch {
layers = undefined;
}
const total = layers?.reduce((s, l) => s + l.thickness, 0) ?? 0;
if (layers && layers.length > 0 && total > EPS) {
const span = zTop - zBottom;
let prefixTop = 0; // von OK (zTop) nach unten aufsummiert (Meter)
for (const l of layers) {
const t = (l.thickness / total) * span;
const layerTop = zTop - prefixTop;
const layerBottom = layerTop - t;
prefixTop += t;
let color: RRgb = SLAB_RGB;
let cut: RCutMeta | undefined;
try {
const comp = getComponent(project, l.componentId);
color = hexToRgb(comp.color);
// Schnitt-Metadaten der Schicht: joinPriority + Identität (für die
// Boolean-Dominanz/MERGE) + Schnittkanten-Stil aus jointLineStyleId.
const lineStyle = resolveCutLineStyle(project, l.jointLineStyleId);
cut = {
joinPriority: comp.joinPriority,
componentId: comp.id,
...(lineStyle?.color ? { lineColor: lineStyle.color } : {}),
...(lineStyle?.weight != null ? { lineWeight: lineStyle.weight } : {}),
};
} catch {
color = SLAB_RGB;
cut = undefined;
}
const hatch = resolveComponentHatch(project, l.componentId);
out.push({
outline,
zBottom: layerBottom,
zTop: layerTop,
color,
ceilingId: c.id,
...(hatch ? { hatch } : {}),
...(cut ? { cut } : {}),
});
w.ring(c.outline);
const openings = c.openings ?? [];
w.num(openings.length);
for (const o of openings) w.ring(o);
w.num(zBottom, zTop, layers?.length ?? 0);
for (const l of layers ?? []) w.num(l.thickness);
ceilings.push(c);
layersOf.push(layers);
}
if (ceilings.length === 0) return [];
w.set(count, ceilings.length);
const f = core().ceilings3d_flat(w.done());
const out: RSlab[] = [];
let i = 1;
for (let n = f.length ? f[0] : 0; n > 0; n--) {
const ci = f[i++];
const c = ceilings[ci];
const layers = layersOf[ci];
const nPts = f[i++];
const outline: RVec2[] = new Array(nPts);
for (let k = 0; k < nPts; k++, i += 2) outline[k] = [f[i], f[i + 1]];
for (let s = f[i++]; s > 0; s--, i += 3) {
const layerIdx = f[i];
const zBottom = f[i + 1];
const zTop = f[i + 2];
if (layerIdx < 0 || !layers) {
out.push({ outline, zBottom, zTop, color: SLAB_RGB, ceilingId: c.id });
continue;
}
} else {
out.push({ outline, zBottom, zTop, color: SLAB_RGB, ceilingId: c.id });
const l = layers[layerIdx];
let color: RRgb = SLAB_RGB;
let cut: RCutMeta | undefined;
try {
const comp = getComponent(project, l.componentId);
color = hexToRgb(comp.color);
// Schnitt-Metadaten der Schicht: joinPriority + Identität (für die
// Boolean-Dominanz/MERGE) + Schnittkanten-Stil aus jointLineStyleId.
const lineStyle = resolveCutLineStyle(project, l.jointLineStyleId);
cut = {
joinPriority: comp.joinPriority,
componentId: comp.id,
...(lineStyle?.color ? { lineColor: lineStyle.color } : {}),
...(lineStyle?.weight != null ? { lineWeight: lineStyle.weight } : {}),
};
} catch {
color = SLAB_RGB;
cut = undefined;
}
const hatch = resolveComponentHatch(project, l.componentId);
out.push({
outline,
zBottom,
zTop,
color,
ceilingId: c.id,
...(hatch ? { hatch } : {}),
...(cut ? { cut } : {}),
});
}
}
return out;
+48 -36
View File
@@ -1,11 +1,15 @@
// Stützen-Domäne der 3D-Ableitung (Tragwerk): extrudiert `project.columns` zu
// parametrischen Prisma-Meshes (Rechteck-Box bzw. tesselliertes Kreis-Prisma).
//
// Das Prisma (Mantel-Quads, Deckel als Dreiecksfächer) rechnet Rust
// (`src-tauri/core/src/columns3d.rs`); hier nur Querschnitt und Höhen sammeln und einfärben.
import type { Column, Project, Vec2 } from "../../model/types";
import { getComponent } from "../../model/types";
import { columnFootprint } from "../../geometry/column";
import { columnVerticalExtent } from "../../model/wall";
import { EPS, hexToRgb, type RMesh, type RRgb } from "./shared";
import { core } from "../../engine/coreWasm";
import { hexToRgb, type RMesh, type RRgb } from "./shared";
/** Neutraler Beton-/Tragwerks-Grauton für Stützen (Fallback ohne Bauteil-Farbe). */
const COLUMN_RGB: RRgb = [0.7, 0.7, 0.72];
@@ -28,51 +32,59 @@ function columnColor3d(project: Project, col: Column): RRgb {
return COLUMN_RGB;
}
/**
* Baut ein geschlossenes Prisma-Mesh aus einem konvexen Grundriss-Polygon
* `foot` (≥3 Punkte, CCW) zwischen `zBottom` und `zTop`. `positions` in MODELL-
* Metern (x, y, z=Höhe); render3d rendert Kontext-Meshes doppelseitig, daher
* ist die Winding-Reihenfolge unerheblich. Die Deckel werden als Dreiecks-
* Fächer ab dem ersten Vertex tesselliert (konvex → korrekt).
*/
function prismMesh(foot: Vec2[], zBottom: number, zTop: number, color: RRgb): RMesh {
const n = foot.length;
const positions: number[] = [];
const indices: number[] = [];
// 0..n-1 = untere Ring-Vertices, n..2n-1 = obere Ring-Vertices.
for (const p of foot) positions.push(p.x, p.y, zBottom);
for (const p of foot) positions.push(p.x, p.y, zTop);
// Mantelflächen: je Kante ein Quad (2 Dreiecke).
for (let i = 0; i < n; i++) {
const j = (i + 1) % n;
const b0 = i, b1 = j, t0 = i + n, t1 = j + n;
indices.push(b0, b1, t1, b0, t1, t0);
}
// Deckel (Fächer ab Vertex 0): unten + oben.
for (let i = 1; i < n - 1; i++) {
indices.push(0, i, i + 1); // unten
indices.push(n, n + i, n + i + 1); // oben
}
return { positions, indices, kind: "extrusion", color };
}
/**
* Extrudiert `project.columns` (Tragwerk) zu parametrischen Prisma-Meshes —
* Rechteck-Box bzw. tesselliertes Kreis-Prisma, je Profil. SYNCHRON (anders als
* die truck-Extrusion der `ExtrudedSolid`s, s. `../extrusions.ts`): die
* Kontur kommt aus `columnFootprint`, die vertikale Lage aus
* `columnVerticalExtent` (UK/OK-Anker bzw. Geschoss-UK + Höhe). Rust/render3d
* bleibt unverändert (Kontext-Mesh-Pfad).
* `columnVerticalExtent` (UK/OK-Anker bzw. Geschoss-UK + Höhe). `positions` in MODELL-Metern
* (x, y, z=Höhe); render3d rendert Kontext-Meshes doppelseitig, die Winding-Reihenfolge ist
* unerheblich. Rust/render3d bleibt unverändert (Kontext-Mesh-Pfad).
*/
export function emitColumns(project: Project): RMesh[] {
const out: RMesh[] = [];
const cols: Column[] = [];
const feet: Vec2[][] = [];
const zs: number[] = [];
let doubles = 1;
for (const col of project.columns ?? []) {
if (col.height <= 0) continue;
const foot = columnFootprint(col);
if (foot.length < 3) continue;
const { zBottom, zTop } = columnVerticalExtent(project, col);
if (zTop - zBottom <= EPS) continue;
out.push(prismMesh(foot, zBottom, zTop, columnColor3d(project, col)));
const foot = columnFootprint(col);
cols.push(col);
feet.push(foot);
zs.push(zBottom, zTop);
doubles += 3 + 2 * foot.length;
}
if (cols.length === 0) return [];
const buf = new Float64Array(doubles);
buf[0] = cols.length;
let w = 1;
for (let k = 0; k < cols.length; k++) {
const foot = feet[k];
buf[w++] = zs[2 * k];
buf[w++] = zs[2 * k + 1];
buf[w++] = foot.length;
for (const p of foot) {
buf[w++] = p.x;
buf[w++] = p.y;
}
}
const f = core().columns3d_flat(buf);
const out: RMesh[] = [];
let i = 1;
for (let n = f.length ? f[0] : 0; n > 0; n--) {
const col = cols[f[i]];
const nPos = f[i + 1];
const nIdx = f[i + 2];
i += 3;
const positions: number[] = [];
for (let k = 0; k < nPos; k++) positions.push(f[i + k]);
i += nPos;
const indices: number[] = [];
for (let k = 0; k < nIdx; k++) indices.push(f[i + k]);
i += nIdx;
out.push({ positions, indices, kind: "extrusion", color: columnColor3d(project, col) });
}
return out;
}
+34 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { Project } from "../../model/types";
import { sampleProject } from "../../model/sampleProject";
import { emitDrawingLineVerts } from "./drawing2d";
import { emitDrawingLineVerts, pickDrawingSegs } from "./drawing2d";
// `emitDrawingLineVerts` liefert die 2D-Boden-Spuren als LineList-Vertices für
// render3ds `set_drawing_lines` (binärer Float32Array-Kanal) — interleaved
@@ -176,3 +176,36 @@ describe("emitDrawingLineVerts — WORLD-Abbildung und Puffergrösse", () => {
expect(v[FLOATS_PER_VERTEX + 3]).toBeCloseTo(1, 5);
});
});
describe("Chargen an den Rust-Kern (Kataster-Grössenordnung)", () => {
const line = (i: number) => ({
id: `D${i}`,
type: "drawing2d",
levelId: "eg",
categoryCode: "2d-line",
geom: { shape: "line", a: { x: i, y: 0 }, b: { x: i, y: 1 } },
});
it("viele Zeichnungen über mehrere Chargen: nichts geht verloren, Reihenfolge bleibt", () => {
const n = 60000; // 60000 × 11 Zahlen > eine Charge
const p = projectWith(Array.from({ length: n }, (_, i) => line(i)) as unknown as Project["drawings2d"]);
const v = emitDrawingLineVerts(p);
expect(v.length).toBe(n * 2 * FLOATS_PER_VERTEX);
expect(v[0]).toBe(0);
expect(v[FLOATS_PER_VERTEX * 2 * 33333]).toBe(33333);
expect(v[v.length - FLOATS_PER_VERTEX]).toBe(n - 1);
const picks = pickDrawingSegs(p);
expect(picks.length).toBe(n);
expect(picks[n - 1].drawingId).toBe(`D${n - 1}`);
expect(picks[40000].start).toEqual([40000, 0]);
});
it("eine einzelne Polylinie grösser als eine Charge", () => {
const pts = Array.from({ length: 200000 }, (_, i) => ({ x: i, y: i % 2 }));
const p = projectWith([
{ id: "P", type: "drawing2d", levelId: "eg", categoryCode: "2d-line", geom: { shape: "polyline", pts, closed: true } },
] as unknown as Project["drawings2d"]);
expect(emitDrawingLineVerts(p).length).toBe(200000 * 2 * FLOATS_PER_VERTEX);
expect(pickDrawingSegs(p).length).toBe(200000);
});
});
+107 -93
View File
@@ -9,35 +9,15 @@
// Segmente liefern — als Ribbon-Meshes im JSON-Modell sprengt das sowohl die
// JS-String-Längengrenze als auch den Vertexspeicher (s. Funktionsdoc unten).
import type { Drawing2D, Project, Vec2 } from "../../model/types";
import type { Drawing2D, Project } from "../../model/types";
import { flattenCategories, getFloor } from "../../model/types";
import { core } from "../../engine/coreWasm";
import { DRAWING_LINE_FALLBACK_RGB, hexToRgb, type RRgb } from "./shared";
import { DRAWING_PICK_TOLERANCE, type PickDrawingSeg } from "../pickTypes";
/** Höhen-Offset über der Geschossebene gegen Z-Fighting (wie addDrawing2DLines in Viewport3D.tsx). */
const DRAWING_LINE_ELEVATION_EPS = 0.01;
/**
* Strecken eines 2D-Zeichenelements für die Boden-Spur im 3D — exakt dieselbe
* Teilmenge wie `drawing2DSegments` im drei.js-Fallback (`Viewport3D.tsx`):
* line/polyline/rect. Kreis/Bogen/Text bleiben aussen vor (keine neue
* Fähigkeit gegenüber dem Fallback, nur Parität).
*/
export function drawingSegments3d(d: Drawing2D): [Vec2, Vec2][] {
const g = d.geom;
const out: [Vec2, Vec2][] = [];
if (g.shape === "line") out.push([g.a, g.b]);
else if (g.shape === "polyline") {
for (let i = 0; i < g.pts.length - 1; i++) out.push([g.pts[i], g.pts[i + 1]]);
if (g.closed && g.pts.length > 2) out.push([g.pts[g.pts.length - 1], g.pts[0]]);
} else if (g.shape === "rect") {
const c1 = g.min, c3 = g.max;
const c2 = { x: g.max.x, y: g.min.y }, c4 = { x: g.min.x, y: g.max.y };
out.push([c1, c2], [c2, c3], [c3, c4], [c4, c1]);
}
return out;
}
/**
* Farb-Nachschlagetabellen für {@link drawingColor3d} — EINMAL je Emitter-Lauf
* gebaut statt je Element. Vorher rief `drawingColor3d` pro Zeichnung
@@ -73,23 +53,6 @@ function drawingColor3d(maps: DrawingColorMaps, d: Drawing2D): RRgb {
return cat ? hexToRgb(cat, DRAWING_LINE_FALLBACK_RGB) : DRAWING_LINE_FALLBACK_RGB;
}
/**
* Segmentzahl einer 2D-Zeichnung OHNE die Segmente zu materialisieren —
* damit {@link emitDrawingLineVerts} den Zielpuffer exakt vorab dimensionieren
* kann. Muss mit {@link drawingSegments3d} synchron bleiben (gleiche Formen,
* gleiche Zählung); der Test deckt das ab.
*/
function countSegments3d(d: Drawing2D): number {
const g = d.geom;
if (g.shape === "line") return 1;
if (g.shape === "polyline") {
const open = Math.max(0, g.pts.length - 1);
return g.closed && g.pts.length > 2 ? open + 1 : open;
}
if (g.shape === "rect") return 4;
return 0;
}
/** Boden-Spur-Höhe (world-Y) einer 2D-Zeichnung: Geschoss-UK + Epsilon gegen
* Z-Fighting, oder 0 als Fallback (Geschoss nicht mehr auflösbar). Gemeinsam
* für `emitDrawingLineVerts` (Sichtbarkeit) UND `pickDrawingSegs` (Klickbarkeit) —
@@ -104,9 +67,75 @@ function drawingElevation(project: Project, d: Drawing2D): number {
return baseZ + DRAWING_LINE_ELEVATION_EPS;
}
/** Floats je LineList-Vertex: `[px, py, pz, r, g, b]` — Format der render3d-
* Linien-Pipeline (Gitter/Kanten/Highlight teilen es, s. `GRID_FLOATS_PER_VERTEX`). */
const LINE_FLOATS_PER_VERTEX = 6;
/** Doppelte je Charge an den Rust-Kern (Eingabe: `drawing2d_3d.rs`) — begrenzt den Speicher. */
const CHUNK_DOUBLES = 1 << 18;
let scratch: Float64Array | null = null;
/** Art-Kennzahl der Zeichnung im Rust-Puffer; Kreis/Bogen/Text zeigt das 3D nicht. */
const SHAPE_KIND = { line: 1, polyline: 2, rect: 3 } as const;
/**
* Packt die darstellbaren Zeichnungen (line/polyline/rect — Parität mit `drawing2DSegments`
* im drei.js-Fallback `Viewport3D.tsx`) in Chargen und ruft `fn(puffer, zeichnungen)` je Charge
* auf. `color` liefert die Linienfarbe (`null`: ohne, für den Pick).
*/
function forEachChunk(
project: Project,
color: ((d: Drawing2D) => RRgb) | null,
fn: (buf: Float64Array, drawings: Drawing2D[]) => void,
): void {
if (project.drawings2d.length === 0) return;
// Der Zwischenpuffer lebt zwischen den Aufrufen weiter (Neuanlage von 2 MB kostet mehr als die
// Rechnung bei kleinen Projekten); der Kern kopiert den Inhalt je Aufruf.
scratch ??= new Float64Array(CHUNK_DOUBLES);
let buf = scratch;
let ids: Drawing2D[] = [];
let w = 1; // [0] = Anzahl
const flush = () => {
if (ids.length === 0) return;
buf[0] = ids.length;
fn(buf.subarray(0, w), ids);
ids = [];
w = 1;
};
// Geschoss-UK je Ebene nur einmal auflösen (bei Kataster-Importen hängen Tausende Zeichnungen an einer).
const elevations = new Map<string, number>();
for (const d of project.drawings2d) {
const g = d.geom;
if (g.shape !== "line" && g.shape !== "rect" && g.shape !== "polyline") continue;
const kind = SHAPE_KIND[g.shape];
const nPts = g.shape === "polyline" ? g.pts.length : 2;
const need = 7 + 2 * nPts;
if (w + need > buf.length) {
flush();
if (1 + need > buf.length) buf = new Float64Array(1 + need);
}
let elev = elevations.get(d.levelId);
if (elev === undefined) {
elev = drawingElevation(project, d);
elevations.set(d.levelId, elev);
}
const [r, gr, b] = color ? color(d) : [0, 0, 0];
buf[w++] = kind;
buf[w++] = elev;
buf[w++] = r;
buf[w++] = gr;
buf[w++] = b;
buf[w++] = g.shape === "polyline" && g.closed ? 1 : 0;
buf[w++] = nPts;
if (g.shape === "line") {
buf[w++] = g.a.x; buf[w++] = g.a.y; buf[w++] = g.b.x; buf[w++] = g.b.y;
} else if (g.shape === "rect") {
buf[w++] = g.min.x; buf[w++] = g.min.y; buf[w++] = g.max.x; buf[w++] = g.max.y;
} else {
for (const p of g.pts) {
buf[w++] = p.x;
buf[w++] = p.y;
}
}
ids.push(d);
}
flush();
}
/**
* Boden-Spuren aller 2D-Zeichnungen als LineList-Vertices für render3d —
@@ -115,74 +144,59 @@ const LINE_FLOATS_PER_VERTEX = 6;
*
* Liefert interleaved `[px, py, pz, r, g, b, ...]` in WORLD-Metern, je zwei
* Vertices ein Segment — direkt für `WebModelRenderer::set_drawing_lines`
* (Binärtransfer als `Float32Array`, kein JSON).
* (Binärtransfer als `Float32Array`, kein JSON). Entartete Segmente entfallen.
*
* WARUM LINIEN STATT MESHES (Nutzer-Report 2026-10-08, Kataster-DXF „Amtliche
* Vermessung Luzern", 439 MB → 3,6 Mio. Segmente): vorher wurde je Zeichnung
* ein Ribbon-MESH erzeugt und über `RModel3d.meshes` als EIN JSON-String an
* `set_model` gereicht. Das scheiterte an zwei harten Wänden — (1)
* `JSON.stringify` sprengte die JS-String-Längengrenze komplett
* (`RangeError: Invalid string length`; auch mit zu EINEM Mesh gebündelten
* Daten, gemessen), und (2) `append_context_mesh` de-indiziert fürs
* Flat-Shading und emittiert jedes Dreieck doppelt → ~1,55 GB Vertexdaten für
* dieselbe Geometrie. Als LineList sind es 2 Vertices je Segment (~173 MB)
* ohne jede Textkodierung.
* Vermessung Luzern", 439 MB → 3,6 Mio. Segmente): als Ribbon-MESH im JSON-Modell sprengte das
* die JS-String-Längengrenze, und `append_context_mesh` hätte ~1,55 GB Vertexdaten erzeugt.
* Als LineList sind es 2 Vertices je Segment (~173 MB) ohne jede Textkodierung.
*
* WORLD-TRANSFORM: hier selbst angewandt, weil die Vertices NICHT mehr durch
* `append_context_mesh` laufen. Modell `(x, y, z=Höhe)` → world `(x, Höhe, y)`
* — exakt die `MeshKind::Extrusion`-Konvention (KEINE Nord-Negation; die gilt
* nur für `Terrain`/`Imported`, s. `mesh.rs` und die Mirror-Bug-Herleitung in
* PENDENZEN.md 2026-09-27).
* WORLD-TRANSFORM: Modell `(x, y, z=Höhe)` → world `(x, Höhe, y)` — exakt die
* `MeshKind::Extrusion`-Konvention (KEINE Nord-Negation; die gilt nur für `Terrain`/`Imported`,
* s. `mesh.rs`). Die Segmente erzeugt der Rust-Kern (`drawing2d_3d.rs`) in Chargen; die
* Teilergebnisse werden am Ende in EINEN Puffer kopiert.
*/
export function emitDrawingLineVerts(project: Project): Float32Array {
let segTotal = 0;
for (const d of project.drawings2d) segTotal += countSegments3d(d);
if (segTotal === 0) return new Float32Array(0);
// Exakt vorab dimensionieren statt wachsendem `number[]`: bei Millionen
// Segmenten spart das die doppelte Spitzenlast (JS-Array mit Float64-
// Einträgen + anschliessende Kopie in den Float32Array).
const out = new Float32Array(segTotal * 2 * LINE_FLOATS_PER_VERTEX);
if (project.drawings2d.length === 0) return new Float32Array(0);
const maps = buildDrawingColorMaps(project);
let w = 0;
for (const d of project.drawings2d) {
const segs = drawingSegments3d(d);
if (segs.length === 0) continue;
const elev = drawingElevation(project, d);
const [r, g, b] = drawingColor3d(maps, d);
for (const [p0, p1] of segs) {
// Entartete Segmente überspringen (wie bisher); der Puffer wird am Ende
// auf die tatsächlich geschriebene Länge zugeschnitten.
if (Math.hypot(p1.x - p0.x, p1.y - p0.y) < 1e-9) continue;
out[w++] = p0.x; out[w++] = elev; out[w++] = p0.y;
out[w++] = r; out[w++] = g; out[w++] = b;
out[w++] = p1.x; out[w++] = elev; out[w++] = p1.y;
out[w++] = r; out[w++] = g; out[w++] = b;
const parts: Float32Array[] = [];
let total = 0;
forEachChunk(project, (d) => drawingColor3d(maps, d), (buf) => {
const v = core().drawing3d_line_verts(buf);
if (v.length) {
parts.push(v);
total += v.length;
}
});
if (parts.length === 0) return new Float32Array(0);
if (parts.length === 1) return parts[0];
const out = new Float32Array(total);
let w = 0;
for (const p of parts) {
out.set(p, w);
w += p.length;
}
return w === out.length ? out : out.subarray(0, w);
return out;
}
/**
* Pick-Kandidaten (Raycast-Boxen, s. `viewport/raycast3d.ts::PickDrawingSeg`)
* für alle 2D-Zeichnungen — dieselben Segmente/Höhen wie `emitDrawingLineVerts`
* (Klick trifft, was sichtbar ist), nur mit grosszügiger Toleranz statt der
* sichtbaren 0.008m Linienbreite. Bislang gab es GAR KEINE Pick-Unterstützung
* für freie 2D-Geometrie im WASM-Viewport (Nutzer-Report: „2D-Elemente können
* nicht angewählt werden" — Wände/Decken/Öffnungen/Treppen/Dächer waren schon
* pickbar, 2D-Zeichnungen nie).
* sichtbaren 0.008m Linienbreite.
*/
export function pickDrawingSegs(project: Project): PickDrawingSeg[] {
const out: PickDrawingSeg[] = [];
for (const d of project.drawings2d) {
const segs = drawingSegments3d(d);
if (segs.length === 0) continue;
const elev = drawingElevation(project, d);
const baseElevation = elev - DRAWING_PICK_TOLERANCE / 2;
for (const [a, b] of segs) {
out.push({ start: [a.x, a.y], end: [b.x, b.y], baseElevation, drawingId: d.id });
forEachChunk(project, null, (buf, drawings) => {
const f = core().drawing3d_pick_segs(buf, DRAWING_PICK_TOLERANCE);
for (let i = 0; i + 5 < f.length; i += 6) {
out.push({
start: [f[i], f[i + 1]],
end: [f[i + 2], f[i + 3]],
baseElevation: f[i + 4],
drawingId: drawings[f[i + 5]].id,
});
}
}
});
return out;
}
+100 -399
View File
@@ -1,114 +1,83 @@
// Treppen-Domäne der 3D-Ableitung: emittiert Treppen als extrudierte RSlabs
// (Tritte + Podest, tragart-abhängige Untersicht) — der WASM/wgpu-Renderer
// kennt sonst KEINE Treppen (nur Wände/Decken/Meshes). Für Ortbeton-Läufe
// zusätzlich ein glattes Dreiecks-Mesh der schrägen Laufplatten-Untersicht.
// zusätzlich ein glattes Dreiecks-Mesh der schrägen Laufplatten-Untersicht, und für gerade
// Läufe Handlauf + Pfosten (`StairType.railing`).
//
// Die ganze Rechnung (Tritt-Prismen je Tragart, Nasen-Verlängerung `StairType.nosing`, dünne
// Setzstufen-Platten `closedRisers`, Podest, Soffit-Scheiben im Schnitt, Laufplatten-Mesh,
// Handlauf/Pfosten-Quader) steht in Rust (`src-tauri/core/src/stairs3d.rs`, Treppengeometrie aus
// `kernel2d`). Hier nur: aus dem `Project` sammeln und die Ergebnisse einfärben.
// `ceilingId` trägt bei den Slabs die Treppen-Id (nur TS-seitiges Tagging; render3d ignoriert
// das Feld, und der Pick läuft separat über `pickGeometry`).
import type { Project, Vec2 } from "../../model/types";
import type { Project, Stair, StairType } from "../../model/types";
import { getStairType } from "../../model/types";
import { stairVerticalExtent } from "../../model/wall";
import { stairGeometry } from "../../geometry/stair";
import { leftNormal, normalize } from "../../model/geometry";
import { EPS, SLAB_RGB, hexToRgb, type RMesh, type RRgb, type RSlab, type RVec2 } from "./shared";
import { encodeStair } from "../../geometry/stair";
import { core } from "../../engine/coreWasm";
import { SLAB_RGB, hexToRgb, type RMesh, type RRgb, type RSlab, type RVec2 } from "./shared";
/** Neutraler Beton-Grauton für Treppen (wie der Three.js-Pfad `addStairMeshes`). */
const STAIR_RGB: RRgb = hexToRgb("#9aa0a6", SLAB_RGB);
/** Neutrales Metallgrau für Handlauf + Pfosten. */
const RAIL_RGB: RRgb = hexToRgb("#74797f", SLAB_RGB);
/** Laufplattendicke einer Ortbetontreppe (Meter). */
const CONCRETE_WAIST = 0.18;
/** Schwerpunkt eines Tritt-Polygons (Grundriss). */
function centroidOf(pts: Vec2[]): Vec2 {
let x = 0, y = 0;
for (const p of pts) { x += p.x; y += p.y; }
return { x: x / pts.length, y: y / pts.length };
}
const STRUCTURE = { massiv: 0, beton: 1, wange: 2, aufgesattelt: 2, spindel: 2 } as const;
const RAILING = { keine: 0, links: 1, rechts: 2, beide: 3 } as const;
/**
* Bestimmt die "vordere" Kante eines Tritt-Vielecks (die Kante in Richtung
* des nächsten Tritts) — für die Nasen-Verlängerung ({@link StairType.nosing}).
* `target` ist der Schwerpunkt eines Nachbartritts; `preferNear` wählt die dem
* Ziel NÄCHSTE Kante (Nachbar = nächster Tritt), sonst die FERNSTE (Nachbar =
* vorheriger Tritt, Vorderkante liegt entgegengesetzt). Liefert die Indizes
* der beiden Eckpunkte der Vorderkante + deren Richtung (Trittschwerpunkt →
* Kantenmitte, normiert). Wortgetreu portiert vom Three.js-Pfad
* (`viewport/viewport3d/meshBuilders.ts::frontEdgeOf`), wo dieselbe Logik
* bereits für `nosing` verwendet wird.
* Flache Rust-Eingabe der Treppen (Aufbau: `stairs3d.rs`); `null` ohne Treppen. `wanted` wählt
* nur vor, welche Treppen sich lohnen (spart den WASM-Aufruf); die Regeln selbst prüft Rust.
*/
function frontEdgeOf(
pts: Vec2[],
target: Vec2,
preferNear: boolean,
): { a: number; b: number; dir: Vec2 } {
const c = centroidOf(pts);
let best = 0;
let bestDist = preferNear ? Infinity : -Infinity;
for (let e = 0; e < pts.length; e++) {
const p0 = pts[e];
const p1 = pts[(e + 1) % pts.length];
const mid = { x: (p0.x + p1.x) / 2, y: (p0.y + p1.y) / 2 };
const d = Math.hypot(mid.x - target.x, mid.y - target.y);
if (preferNear ? d < bestDist : d > bestDist) {
bestDist = d;
best = e;
}
function stairInput(
project: Project,
wanted: (stair: Stair, st: StairType | undefined) => boolean = () => true,
): { stairs: Stair[]; buf: Float64Array } | null {
const stairs: Stair[] = [];
const types: (StairType | undefined)[] = [];
for (const stair of project.stairs ?? []) {
const st = getStairType(project, stair);
if (!wanted(stair, st)) continue;
stairs.push(stair);
types.push(st);
}
const p0 = pts[best];
const p1 = pts[(best + 1) % pts.length];
const mid = { x: (p0.x + p1.x) / 2, y: (p0.y + p1.y) / 2 };
const dx = mid.x - c.x;
const dy = mid.y - c.y;
const len = Math.hypot(dx, dy) || 1e-9;
return { a: best, b: (best + 1) % pts.length, dir: { x: dx / len, y: dy / len } };
if (stairs.length === 0) return null;
const buf = new Float64Array(1 + 23 * stairs.length);
buf[0] = stairs.length;
stairs.forEach((stair, k) => {
const { zBottom, zTop } = stairVerticalExtent(project, stair);
const st = types[k];
const o = 1 + 23 * k;
buf.set(encodeStair(stair), o);
buf[o + 16] = zBottom;
buf[o + 17] = zTop;
buf[o + 18] = STRUCTURE[st?.structure ?? "massiv"] ?? 2;
buf[o + 19] = st?.treadThickness ?? 0.04;
buf[o + 20] = st?.nosing ?? 0;
buf[o + 21] = st?.closedRisers ? 1 : 0;
buf[o + 22] = RAILING[st?.railing ?? "keine"] ?? 0;
});
return { stairs, buf };
}
/**
* Verlängert die Vorderkante eines Tritts um `nosing` Meter (Trittkanten-
* Überstand/Nase, {@link StairType.nosing}) — nur bei OFFENEN Tragarten
* sinnvoll (dünne Tritt-Platte mit sichtbarem Vorstand vor der Setzstufe
* darunter), daher nur aus dem `structure !== "massiv"`-Zweig aufgerufen.
*/
function withNosing(pts: Vec2[], neighbors: Vec2[][], k: number, nosing: number): Vec2[] {
if (nosing <= 1e-6) return pts;
const hasNext = k + 1 < neighbors.length;
const hasPrev = k > 0;
const ref = hasNext ? neighbors[k + 1] : hasPrev ? neighbors[k - 1] : null;
if (!ref) return pts;
const { a, b, dir } = frontEdgeOf(pts, centroidOf(ref), hasNext);
const nosed = pts.slice();
nosed[a] = { x: pts[a].x + dir.x * nosing, y: pts[a].y + dir.y * nosing };
nosed[b] = { x: pts[b].x + dir.x * nosing, y: pts[b].y + dir.y * nosing };
return nosed;
}
/**
* Grundriss einer geschlossenen Setzstufen-Platte ({@link StairType.closedRisers}):
* eine DÜNNE Fläche an der RÜCKKante des Tritts `k` (= Vorderkante des
* Vorgängers, Gegenkante zur eigenen Vorderkante), leicht in Vorderkanten-
* Richtung aufgeweitet, damit ein extrudierbares Vieleck entsteht (statt einer
* entarteten Linie). `null`, wenn kein Nachbartritt zur Vorderkanten-
* Bestimmung existiert (Einzeltritt). Wortgetreu portiert vom Three.js-Pfad
* (`meshBuilders.ts::addStairMeshes`), inkl. der Verwendung der ROHEN
* (nicht genasten) Trittpunkte — die Nase betrifft nur die Trittplatte selbst.
*/
function closedRiserOutline(
trPts: Vec2[],
neighbors: Vec2[][],
k: number,
treadThickness: number,
): Vec2[] | null {
const hasNext = k + 1 < neighbors.length;
const ref = hasNext ? neighbors[k + 1] : k > 0 ? neighbors[k - 1] : null;
if (!ref) return null;
const front = frontEdgeOf(trPts, centroidOf(ref), hasNext);
const n = trPts.length;
const backA = (front.a + Math.floor(n / 2)) % n;
const backB = (front.b + Math.floor(n / 2)) % n;
const riserA = trPts[backA];
const riserB = trPts[backB];
const thin = Math.min(treadThickness, 0.02) || 0.01;
const offA = { x: riserA.x - front.dir.x * thin, y: riserA.y - front.dir.y * thin };
const offB = { x: riserB.x - front.dir.x * thin, y: riserB.y - front.dir.y * thin };
return [riserA, riserB, offB, offA];
/** Rust-Meshes `[n, (treppe, nPos, nIdx, positionen…, indizes…)…]` → `RMesh[]`. */
function meshesOf(f: Float64Array, color: RRgb): RMesh[] {
const out: RMesh[] = [];
let i = 1;
for (let n = f.length ? f[0] : 0; n > 0; n--) {
const nPos = f[i + 1];
const nIdx = f[i + 2];
i += 3;
const positions: number[] = [];
for (let k = 0; k < nPos; k++) positions.push(f[i + k]);
i += nPos;
const indices: number[] = [];
for (let k = 0; k < nIdx; k++) indices.push(f[i + k]);
i += nIdx;
out.push({ positions, indices, kind: "extrusion", color });
}
return out;
}
/**
@@ -125,26 +94,11 @@ function closedRiserOutline(
* • "wange"/"aufgesattelt"/"spindel" — nur eine dünne Tritt-Platte der Dicke
* `treadThickness` an der Tritt-OK, darunter offen.
* Podest (L/Wendel) als Vollblock bis zur halben Steighöhe. Bei OFFENEN
* Tragarten (nicht "massiv") wird die Vorderkante jedes Tritts zusätzlich um
* `StairType.nosing` (Trittkanten-Überstand) verlängert und — bei
* `StairType.closedRisers` — eine dünne Setzstufen-Platte an der Rückkante
* ergänzt (sonst bleibt die Treppe dort offen) — wortgetreu wie im Three.js-
* Pfad, hier ans WASM/wgpu-Default-3D nachgezogen (beide Felder waren dort
* unwirksam: existierten im Modell + der ResourceManager-UI, aber der
* Standard-Renderer las sie nie, s. PENDENZEN.md). Handlauf/Geländer
* (`StairType.railing`) sind separat in {@link emitStairRailings} (nur
* gerade Läufe, s. dort).
* `ceilingId` trägt hier die Treppen-Id (nur TS-seitiges Tagging; render3d ignoriert
* das Feld, und der Pick läuft separat über `pickGeometry`).
* Tragarten wird die Vorderkante jedes Tritts zusätzlich um `StairType.nosing`
* (Trittkanten-Überstand) verlängert und — bei `StairType.closedRisers` — eine dünne
* Setzstufen-Platte an der Rückkante ergänzt. Massiv/Beton bilden EIN Körper
* (`monolith`, s. render3d `SlabInput::monolith`).
*/
/** Max. Stufenhöhe (Meter) der Soffit-Treppung im Schnitt: darunter wirkt die Untersicht glatt. */
const SOFFIT_SLICE_STEP = 0.015;
/** Laufplattendicke (vertikal) der glatten Betontreppe — gemeinsam für Mesh und Schnitt. */
function concreteWaist(riserHeight: number): number {
return Math.min(0.24, Math.max(0.14, riserHeight * 1.2));
}
export function emitStairs(
project: Project,
/**
@@ -154,112 +108,28 @@ export function emitStairs(
*/
opts: { forSection?: boolean } = {},
): RSlab[] {
const input = stairInput(project);
if (!input) return [];
const f = core().stairs3d_slabs_flat(input.buf, !!opts.forSection);
const out: RSlab[] = [];
for (const stair of project.stairs ?? []) {
const { zBottom, zTop } = stairVerticalExtent(project, stair);
const totalRise = zTop - zBottom;
if (totalRise <= EPS) continue;
const geo = stairGeometry(stair, totalRise);
const st = getStairType(project, stair);
const structure = st?.structure ?? "massiv";
// Gerade Betontreppe: die GLATTE Laufplatte kommt als echtes Mesh
// (emitStairMeshes) — hier keine Slab-Näherung emittieren (sonst doppelt).
if (structure === "beton" && stair.shape === "straight" && !opts.forSection) continue;
const treadThickness = st?.treadThickness ?? 0.04;
const riser = geo.riserHeight;
const open = structure !== "massiv";
// Massiv/Beton = EIN Körper: die Tritt-Prismen verschmelzen im Schnitt
// (keine Nähte zwischen den Tritten, s. render3d `SlabInput::monolith`).
const monolith = structure === "massiv" || structure === "beton" ? stair.id : undefined;
const nosing = open ? st?.nosing ?? 0 : 0;
const neighborPts = geo.treads.map((t) => t.pts);
// Gerade Betontreppe im Schnitt: schräge Soffit-Untersicht (wie das 3D-Mesh) als
// feine Scheiben — jede Tritt-Fläche längs des Laufs in dünne Prismen zerlegt, deren
// Unterkante der Soffit-Geraden folgt (Stufen < SOFFIT_SLICE_STEP statt Sägezahn).
if (structure === "beton" && stair.shape === "straight" && opts.forSection && stair.runLength > EPS) {
const u = normalize(stair.dir);
const w = leftNormal(u);
const waistV = concreteWaist(riser);
const runOf = (p: Vec2) => (p.x - stair.start.x) * u.x + (p.y - stair.start.y) * u.y;
const sideOf = (p: Vec2) => (p.x - stair.start.x) * w.x + (p.y - stair.start.y) * w.y;
const soffit = (runS: number) => {
const t = Math.min(Math.max(runS, 0), stair.runLength);
return Math.max(zBottom, zBottom + (t / stair.runLength) * totalRise - waistV);
};
const n = Math.max(1, Math.ceil(riser / SOFFIT_SLICE_STEP));
for (const tr of geo.treads) {
if (tr.pts.length < 4) continue;
const byRun = [...tr.pts].sort((a, b) => runOf(a) - runOf(b));
const a = [byRun[0], byRun[1]].sort((p, q) => sideOf(p) - sideOf(q));
const b = [byRun[2], byRun[3]].sort((p, q) => sideOf(p) - sideOf(q));
const top = zBottom + tr.topRise;
const lerp = (p: Vec2, q: Vec2, t: number): Vec2 => ({ x: p.x + (q.x - p.x) * t, y: p.y + (q.y - p.y) * t });
for (let j = 0; j < n; j++) {
const t0 = j / n;
const t1 = (j + 1) / n;
// Die tiefere (Anfangs-)Seite der Scheibe bestimmt die Unterkante: keine Lücke zum Soffit.
const bottom = soffit(runOf(lerp(a[0], b[0], t0)));
if (top - bottom <= EPS) continue;
const quad = [lerp(a[0], b[0], t0), lerp(a[0], b[0], t1), lerp(a[1], b[1], t1), lerp(a[1], b[1], t0)];
out.push({
outline: quad.map((p) => [p.x, p.y] as RVec2),
zBottom: bottom,
zTop: top,
color: STAIR_RGB,
ceilingId: stair.id,
monolith,
});
}
}
continue;
}
for (let k = 0; k < geo.treads.length; k++) {
const tr = geo.treads[k];
if (tr.pts.length < 3) continue;
const pts = withNosing(tr.pts, neighborPts, k, nosing);
const top = zBottom + tr.topRise;
const bottom =
structure === "massiv"
? zBottom // Vollblock bis zur Treppen-UK
: structure === "beton"
? Math.max(zBottom, top - riser - CONCRETE_WAIST) // schräge Laufplatte
: top - treadThickness; // offene Tritte (Wange/aufgesattelt/Spindel)
if (top - bottom > EPS) {
out.push({
outline: pts.map((p) => [p.x, p.y] as RVec2),
zBottom: bottom,
zTop: top,
color: STAIR_RGB,
ceilingId: stair.id,
monolith,
});
}
if (open && st?.closedRisers) {
const riserOutline = closedRiserOutline(tr.pts, neighborPts, k, treadThickness);
if (riserOutline) {
out.push({
outline: riserOutline.map((p) => [p.x, p.y] as RVec2),
zBottom: zBottom + tr.baseRise,
zTop: zBottom + tr.topRise,
color: STAIR_RGB,
ceilingId: stair.id,
});
}
}
}
if (geo.landing && geo.landing.length >= 3) {
const landingTop = zBottom + totalRise * 0.5;
out.push({
outline: geo.landing.map((p) => [p.x, p.y] as RVec2),
// Betontreppe: Podest als Platte (wie die Laufplatte), kein Vollblock
// bis zum Boden; massiv bleibt Vollkörper.
zBottom: structure === "beton" ? Math.max(zBottom, landingTop - riser - CONCRETE_WAIST) : zBottom,
zTop: landingTop,
color: STAIR_RGB,
ceilingId: stair.id,
monolith,
});
}
let i = 1;
for (let n = f.length ? f[0] : 0; n > 0; n--) {
const stair = input.stairs[f[i]];
const monolith = f[i + 1] !== 0;
const zBottom = f[i + 2];
const zTop = f[i + 3];
const nPts = f[i + 4];
i += 5;
const outline: RVec2[] = new Array(nPts);
for (let k = 0; k < nPts; k++, i += 2) outline[k] = [f[i], f[i + 1]];
out.push({
outline,
zBottom,
zTop,
color: STAIR_RGB,
ceilingId: stair.id,
...(monolith ? { monolith: stair.id } : {}),
});
}
return out;
}
@@ -269,191 +139,22 @@ export function emitStairs(
* GERADE Läufe. Anders als die stufige Slab-Näherung ({@link emitStairs}) entsteht
* eine SPIEGELGLATTE schräge Untersicht: je Tritt ein konvexes Prisma mit
* HORIZONTALER Oberkante (= Trittfläche) und SCHRÄGER Unterkante auf EINER
* gemeinsamen Soffit-Geraden. Weil alle Prismen-Unterkanten exakt auf dieser
* Geraden liegen, bildet die Vereinigung eine durchgehende glatte Schräge; die
* Höhensprünge der Oberkanten bleiben als sichtbare Setzstufen. Prismen sind
* konvex → triviale, robuste Triangulierung (kein Ear-Clipping). Positions in
* MODELL-Metern (x, y, z=Höhe); render3d bildet nach world (x, z, y) ab.
* gemeinsamen Soffit-Geraden. Positions in MODELL-Metern (x, y, z=Höhe); render3d bildet
* nach world (x, z, y) ab.
*/
export function emitStairMeshes(project: Project): RMesh[] {
const out: RMesh[] = [];
for (const stair of project.stairs ?? []) {
const st = getStairType(project, stair);
if (!st || st.structure !== "beton") continue;
if (stair.shape !== "straight") continue; // glattes Mesh nur für gerade Läufe
if (stair.runLength <= EPS) continue;
const { zBottom, zTop } = stairVerticalExtent(project, stair);
const totalRise = zTop - zBottom;
if (totalRise <= EPS) continue;
const geo = stairGeometry(stair, totalRise);
const u = normalize(stair.dir); // Laufrichtung (Grundriss)
const w = leftNormal(u); // Querrichtung (Breite)
const runTotal = stair.runLength;
// Laufplattendicke (vertikal): an die Steigung gekoppelt, geklemmt.
const waistV = concreteWaist(geo.riserHeight);
// Soffit-Höhe entlang des Laufs: eine Gerade PARALLEL zur Trittkantenlinie
// (Steigung totalRise/runTotal), um `waistV` nach unten versetzt → KONSTANTE
// Plattendicke über den ganzen Lauf (sonst würde die Platte nach oben dicker).
// An der Treppen-UK gekappt, damit die unterste Stufe auf dem Boden aufsitzt
// statt darunter zu schweben.
const soffitH = (runS: number) => {
const s = Math.min(Math.max(runS, 0), runTotal);
return Math.max(zBottom, zBottom + (s / runTotal) * totalRise - waistV);
};
const runOf = (p: Vec2) => (p.x - stair.start.x) * u.x + (p.y - stair.start.y) * u.y;
const sideOf = (p: Vec2) => (p.x - stair.start.x) * w.x + (p.y - stair.start.y) * w.y;
const positions: number[] = [];
const indices: number[] = [];
for (const tr of geo.treads) {
if (tr.pts.length < 4) continue;
// Vier Eckpunkte nach Lauf-Parameter trennen (2 kleinste = Startkante, 2
// grösste = Endkante), je Kante nach Quer-Parameter sortieren (0 = links).
const byRun = [...tr.pts].sort((a, b) => runOf(a) - runOf(b));
const startEdge = [byRun[0], byRun[1]].sort((a, b) => sideOf(a) - sideOf(b));
const endEdge = [byRun[2], byRun[3]].sort((a, b) => sideOf(a) - sideOf(b));
const runS = Math.min(runOf(byRun[0]), runOf(byRun[1]));
const runE = Math.max(runOf(byRun[2]), runOf(byRun[3]));
const topH = zBottom + tr.topRise;
const bS = soffitH(runS);
const bE = soffitH(runE);
if (topH - Math.max(bS, bE) <= EPS) continue;
const base = positions.length / 3;
const push = (p: Vec2, z: number) => positions.push(p.x, p.y, z);
// 0/1 Startkante unten (soffit), 2/3 Endkante unten, 4/5 Start oben, 6/7 End oben.
push(startEdge[0], bS); push(startEdge[1], bS);
push(endEdge[0], bE); push(endEdge[1], bE);
push(startEdge[0], topH); push(startEdge[1], topH);
push(endEdge[0], topH); push(endEdge[1], topH);
const quad = (a: number, b: number, c: number, d: number) =>
indices.push(base + a, base + b, base + c, base + a, base + c, base + d);
quad(0, 1, 3, 2); // Untersicht (schräge Soffit-Fläche)
quad(4, 6, 7, 5); // Oberseite (Trittfläche)
quad(0, 4, 5, 1); // Startkante (Setzstufen-Front der Vorstufe sichtbar)
quad(2, 3, 7, 6); // Endkante
quad(0, 2, 6, 4); // linke Wange
quad(1, 5, 7, 3); // rechte Wange
}
if (indices.length === 0) continue;
out.push({ positions, indices, kind: "extrusion", color: STAIR_RGB });
}
return out;
}
/** Neutrales Metallgrau für Handlauf + Pfosten. */
const RAIL_RGB: RRgb = hexToRgb("#74797f", SLAB_RGB);
/** Handlaufhöhe über der Trittvorderkante (SIA-üblich), Meter. */
const RAIL_HEIGHT = 0.9;
/** Handlauf-/Pfosten-Querschnitt (Kantenlänge), Meter. */
const RAIL_THICK = 0.04;
type Vec3 = { x: number; y: number; z: number };
/**
* Schlanker Quader zwischen zwei beliebigen 3D-Punkten (Modell-Meter, NICHT
* an eine Wandachse gebunden — anders als die übrigen Quader-Helfer in
* `openings.ts`, die alle wand-lokale Achsen voraussetzen). Querschnitt-Achsen
* werden aus einem festen Welt-„oben" (0,0,1) abgeleitet (fällt bei fast
* senkrechten Segmenten — Pfosten — auf die X-Achse zurück, damit das
* Kreuzprodukt nicht entartet). `null` bei entartetem (zu kurzem) Segment.
*/
function strutBox(a: Vec3, b: Vec3, half: number, color: RRgb): RMesh | null {
const dx = b.x - a.x, dy = b.y - a.y, dz = b.z - a.z;
const len = Math.hypot(dx, dy, dz);
if (len < EPS) return null;
const d = { x: dx / len, y: dy / len, z: dz / len };
const upRef: Vec3 = Math.abs(d.z) > 0.98 ? { x: 1, y: 0, z: 0 } : { x: 0, y: 0, z: 1 };
let rx = d.y * upRef.z - d.z * upRef.y;
let ry = d.z * upRef.x - d.x * upRef.z;
let rz = d.x * upRef.y - d.y * upRef.x;
const rl = Math.hypot(rx, ry, rz) || 1;
rx /= rl; ry /= rl; rz /= rl;
const ux = ry * d.z - rz * d.y;
const uy = rz * d.x - rx * d.z;
const uz = rx * d.y - ry * d.x;
const corners: Vec3[] = [];
for (const p of [a, b]) {
for (const [sr, su] of [[-1, -1], [1, -1], [1, 1], [-1, 1]] as const) {
corners.push({
x: p.x + rx * sr * half + ux * su * half,
y: p.y + ry * sr * half + uy * su * half,
z: p.z + rz * sr * half + uz * su * half,
});
}
}
const positions: number[] = [];
for (const c of corners) positions.push(c.x, c.y, c.z);
const indices: number[] = [];
const quad = (a0: number, b0: number, c0: number, d0: number) =>
indices.push(a0, b0, c0, a0, c0, d0);
quad(0, 1, 2, 3); // Stirnfläche bei a
quad(7, 6, 5, 4); // Stirnfläche bei b
quad(0, 4, 5, 1);
quad(1, 5, 6, 2);
quad(2, 6, 7, 3);
quad(3, 7, 4, 0);
return { positions, indices, kind: "extrusion", color };
// Nur gerade Betontreppen haben eine glatte Laufplatte.
const input = stairInput(project, (s, st) => st?.structure === "beton" && s.shape === "straight");
return input ? meshesOf(core().stairs3d_meshes_flat(input.buf), STAIR_RGB) : [];
}
/**
* Handlauf + Pfosten (`StairType.railing`: "keine"|"links"|"rechts"|"beide")
* — bislang ein „totes" Feld: im Modell, im ResourceManager (`StairStylesTab`)
* und in den i18n-Labels längst vorhanden, aber von KEINEM Renderer je
* gelesen (weder dem alten Three.js-Pfad — dort selbst als TODO markiert —
* noch diesem WASM/wgpu-Default-3D). Nur für GERADE Läufe umgesetzt: bei
* einer geraden Treppe liegt die Vorderkante jedes Tritts (das Eckpunktpaar
* mit dem GRÖSSEREN Lauf-Parameter, s. `treadRect`/`stairGeometry`) exakt auf
* der linearen Rampen-Geraden (Steigung totalRise/runLength ist über den
* ganzen Lauf konstant) — Handlauf und Pfosten lassen sich daher als EIN
* gerades, schräges Segment je Seite + ein Pfosten je Trittvorderkante bauen,
* ohne die Stufen einzeln nachzubilden. L-Läufe/Wendeltreppen (Richtungs-
* wechsel bzw. keine lineare Rampe) bleiben bewusst aussen vor — eigener,
* grösserer Folgeschritt (Rampen-Polyline müsste knickweise bzw. als Spirale
* gebaut werden), kein Blocker für die Sichtbarkeit bei geraden Treppen, dem
* mit Abstand häufigsten Fall.
* Handlauf + Pfosten (`StairType.railing`: "keine"|"links"|"rechts"|"beide"). Nur für GERADE
* Läufe: dort liegt die Vorderkante jedes Tritts exakt auf der linearen Rampen-Geraden, ein
* gerades, schräges Segment je Seite + ein Pfosten je Trittvorderkante genügen. L-Läufe und
* Wendeltreppen bleiben bewusst aussen vor (eigener Folgeschritt).
*/
export function emitStairRailings(project: Project): RMesh[] {
const out: RMesh[] = [];
for (const stair of project.stairs ?? []) {
if (stair.shape !== "straight") continue;
const st = getStairType(project, stair);
const railing = st?.railing ?? "keine";
if (railing === "keine") continue;
const { zBottom, zTop } = stairVerticalExtent(project, stair);
const totalRise = zTop - zBottom;
if (totalRise <= EPS) continue;
const geo = stairGeometry(stair, totalRise);
if (geo.treads.length === 0) continue;
const sides: ("left" | "right")[] =
railing === "beide" ? ["left", "right"] : railing === "links" ? ["left"] : ["right"];
for (const side of sides) {
// Tritt-Eckpunkte (s. treadRect): 0/1 = linke Kante (Start/Ende),
// 3/2 = rechte Kante (Start/Ende). Die „Ende"-Ecke jedes Tritts ist
// dessen Vorderkante (liegt auf der Rampen-Geraden, s. Funktionsdoc).
const iStart = side === "left" ? 0 : 3;
const iEnd = side === "left" ? 1 : 2;
const first = geo.treads[0];
const startPt = first.pts[iStart];
const last = geo.treads[geo.treads.length - 1];
const endPt = last.pts[iEnd];
const rail = strutBox(
{ x: startPt.x, y: startPt.y, z: zBottom + RAIL_HEIGHT },
{ x: endPt.x, y: endPt.y, z: zTop + RAIL_HEIGHT },
RAIL_THICK / 2,
RAIL_RGB,
);
if (rail) out.push(rail);
const postAt = (p: Vec2, topZ: number) => {
const post = strutBox(
{ x: p.x, y: p.y, z: topZ },
{ x: p.x, y: p.y, z: topZ + RAIL_HEIGHT },
RAIL_THICK / 2,
RAIL_RGB,
);
if (post) out.push(post);
};
postAt(startPt, zBottom); // Fusspfosten am Bodenanschluss.
for (const tr of geo.treads) postAt(tr.pts[iEnd], zBottom + tr.topRise);
}
}
return out;
const input = stairInput(project, (s, st) => s.shape === "straight" && (st?.railing ?? "keine") !== "keine");
return input ? meshesOf(core().stairs3d_railings_flat(input.buf), RAIL_RGB) : [];
}