[K4] S2: Pick-Geometrie und 2D-Boden-Spuren im 3D rechnen auf dem Dokument; drawing2d.ts (3D) geloescht

This commit is contained in:
karim committed 2026-10-28 02:09:29 +01:00
1 parent 8995ea161d
commit 8d61363724
7 files changed
+254 -303

No files matched your search

+6
View File
@@ -25,6 +25,7 @@ export type QueryName =
| "stairRailings"
| "roofMeshes"
| "roofCutLayers"
| "pickGeometry"
| "model3dParts";
export class ProjectDocument {
@@ -81,6 +82,11 @@ export class ProjectDocument {
return out;
}
/** Boden-Spuren der 2D-Zeichnungen als LineList-Vertices `[px, py, pz, r, g, b]`. */
drawingLineVerts(): Float32Array {
return this.handle ? core().doc_drawing_line_verts(this.handle) : new Float32Array(0);
}
/** Das Dokument als JSON-Text (Test, Export). */
json(): string {
return this.handle ? core().doc_json(this.handle) : "";
+10 -100
View File
@@ -41,13 +41,8 @@
// `toWalls3d/` — siehe dort für die konkrete Emissions-Logik je Bauteil.
import type { Project, Vec2 } from "../model/types";
import { getWallType, wallTypeThickness } from "../model/types";
import { stairVerticalExtent } from "../model/wall";
import { openingJambs, openingVerticalExtent } from "../geometry/opening";
import type { DetailLevel } from "../model/viewTypes";
import { stairBBox, stairGeometry } from "../geometry/stair";
import { roofBaseElevation, roofGeometry } from "../geometry/roof";
import type { Vec3 as RoofVec3 } from "../geometry/roof";
import { documentFor } from "../core/document";
import type { PickOpening, PickRoof, PickStair, PickContextMesh, PickDrawingSeg } from "./pickTypes";
import {
@@ -61,20 +56,22 @@ import {
} from "./toWalls3d/shared";
import { emitExtrudedSolids, TRUCK_MESH_READY_EVENT } from "./toWalls3d/extrusions";
import { applyVoids3d } from "./toWalls3d/voids3d";
import { emitDrawingLineVerts, pickDrawingSegs } from "./toWalls3d/drawing2d";
// Re-Export des gemeinsamen Vokabulars — externe Konsumenten (viewport/,
// export/, toSection.ts, nativeSync.ts, …) importieren weiterhin
// ausschliesslich von hier, unverändert zur Zeit vor dem Domänen-Split.
export { TRUCK_MESH_READY_EVENT };
// 2D-Boden-Spuren gehen NICHT über `RModel3d`, sondern als LineList über den
// binären `set_drawing_lines`-Kanal (s. dortige Funktionsdoc) — der Viewport
// holt sie direkt hier ab.
export { emitDrawingLineVerts };
export type { RVec2, RRgb, RWall, RSlab, RModel3d };
/** World-Punkt [x, Höhe, y] für den Dach-Pick (Vec3-Konvention von raycast3d). */
type RoofPickVec3 = [number, number, number];
/**
* Boden-Spuren aller 2D-Zeichnungen (Linie, Polylinie, Rechteck) als LineList-Vertices
* `[px, py, pz, r, g, b]` in Welt-Metern für render3d (`set_drawing_lines`, Binärkanal — ein
* Kataster-DXF kann Millionen Segmente liefern, als JSON-Mesh sprengte das Speicher und
* String-Länge). Rechnet der Kern (`model3d.rs`, Chargen).
*/
export function emitDrawingLineVerts(project: Project): Float32Array {
return documentFor(project).drawingLineVerts();
}
/** Weltpunkt (x, elevation, y) — nur intern für Highlight-Kantengeometrie. */
type RVec3 = [number, number, number];
@@ -209,94 +206,7 @@ export function pickGeometry(
contextMeshes: PickContextMesh[];
drawings: PickDrawingSeg[];
} {
// Dächer: Dachflächen + Giebel als WORLD-Dreiecke (fan-trianguliert wie
// emitRoofs; model [x,y,z=Höhe] → world [x, z, y]) — präzise geneigte
// Flächen für den Ray-Dreieck-Pick (raycast3d.rayRoofTris).
const roofs: PickRoof[] = [];
for (const roof of project.roofs ?? []) {
const eavesZ = roofBaseElevation(project, roof);
const g = roofGeometry(roof, eavesZ);
const tris: [RoofPickVec3, RoofPickVec3, RoofPickVec3][] = [];
const toWorld = (p: RoofVec3): RoofPickVec3 => [p[0], p[2], p[1]];
for (const poly of [...g.planes.map((pl) => pl.pts), ...g.gables]) {
for (let i = 1; i + 1 < poly.length; i++) {
tris.push([toWorld(poly[0]), toWorld(poly[i]), toWorld(poly[i + 1])]);
}
}
if (tris.length > 0) roofs.push({ tris, roofId: roof.id });
}
const openings: PickOpening[] = [];
for (const o of project.openings ?? []) {
const wall = project.walls.find((w) => w.id === o.hostWallId);
if (!wall) continue;
const jambs = openingJambs(wall, o);
if (!jambs) continue;
const thickness = wallTypeThickness(getWallType(project, wall));
const { zBottom, zTop } = openingVerticalExtent(project, wall, o);
if (zTop - zBottom <= 0) continue;
openings.push({
start: [jambs.jambStart.x, jambs.jambStart.y],
end: [jambs.jambEnd.x, jambs.jambEnd.y],
thickness,
height: zTop - zBottom,
baseElevation: zBottom,
openingId: o.id,
});
}
const stairs: PickStair[] = [];
for (const st of project.stairs ?? []) {
const { zBottom, zTop } = stairVerticalExtent(project, st);
const totalRise = zTop - zBottom;
if (totalRise <= 0) continue;
const bbox = stairBBox(stairGeometry(st, totalRise));
stairs.push({
outline: [
[bbox.minX, bbox.minY],
[bbox.maxX, bbox.minY],
[bbox.maxX, bbox.maxY],
[bbox.minX, bbox.maxY],
],
zBottom,
zTop,
stairId: st.id,
});
}
// Kontext-Meshes (importierte Gebäude/Terrain, s. ContextObject): rohe
// WORLD-Dreiecke, direkt aus dem Indexpuffer (kein Fan nötig — ImportedMesh/
// TerrainMesh liefern bereits ein echtes Dreiecksnetz). Kaputte Indizes
// robust überspringen statt abzustürzen (importierte Daten).
// Modell (x,y,z) → world (x, z, −y) — Nord-Achse NEGIERT, damit der Pick
// dieselbe (gespiegelte→korrigierte) Lage trifft wie die sichtbare Geometrie
// in `viewport3d/meshBuilders.ts::buildContextMesh` (dort ausführlich
// begründet: reines Achsen-Vertauschen ohne Vorzeichenwechsel ist für einen
// allgemeinen xyz-Punktsatz eine Spiegelung, anders als bei Wand/Dach, die
// über eine orientierungserhaltende Rotation/Fächer-Triangulation entstehen).
const contextMeshes: PickContextMesh[] = [];
for (const obj of project.context ?? []) {
if (obj.type === "contourSet" || obj.type === "image") continue;
const pos = obj.positions;
const vcount = pos.length / 3;
const tris: [RoofPickVec3, RoofPickVec3, RoofPickVec3][] = [];
for (let i = 0; i + 2 < obj.indices.length; i += 3) {
const ia = obj.indices[i];
const ib = obj.indices[i + 1];
const ic = obj.indices[i + 2];
if (ia >= vcount || ib >= vcount || ic >= vcount) continue;
const at = (idx: number): RoofPickVec3 => [pos[idx * 3], pos[idx * 3 + 2], -pos[idx * 3 + 1]];
tris.push([at(ia), at(ib), at(ic)]);
}
if (tris.length > 0) contextMeshes.push({ tris, contextObjectId: obj.id });
}
const drawings = pickDrawingSegs(project);
return {
walls: projectToWalls3d(project),
slabs: documentFor(project).query<RSlab[]>("slabs"),
openings,
stairs,
roofs,
contextMeshes,
drawings,
};
return documentFor(project).query("pickGeometry");
}
/**
+3 -1
View File
@@ -1,7 +1,9 @@
import { describe, expect, it } from "vitest";
import type { Project } from "../../model/types";
import { sampleProject } from "../../model/sampleProject";
import { emitDrawingLineVerts, pickDrawingSegs } from "./drawing2d";
import { emitDrawingLineVerts, pickGeometry } from "../toWalls3d";
const pickDrawingSegs = (p: Project) => pickGeometry(p).drawings;
// `emitDrawingLineVerts` liefert die 2D-Boden-Spuren als LineList-Vertices für
// render3ds `set_drawing_lines` (binärer Float32Array-Kanal) — interleaved
-202
View File
@@ -1,202 +0,0 @@
// Freie-2D-Geometrie-Domäne der 3D-Ableitung: zeigt jede 2D-Zeichnung
// (line/polyline/rect) als Boden-Spur knapp über ihrer Geschossebene — die
// "2D-Referenz im 3D", die der drei.js-Fallback (`addDrawing2DLines` in
// Viewport3D.tsx) zeigt.
//
// Die Spuren gehen als LineList-Vertices (`emitDrawingLineVerts`) über einen
// eigenen BINÄREN Kanal an render3d (`set_drawing_lines`), NICHT als Meshes
// über `RModel3d.meshes`/`set_model`. Grund: ein Kataster-DXF kann Millionen
// 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 } 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;
/**
* Farb-Nachschlagetabellen für {@link drawingColor3d} — EINMAL je Emitter-Lauf
* gebaut statt je Element. Vorher rief `drawingColor3d` pro Zeichnung
* `flattenCategories(project.layers).find(...)` auf und baute damit den
* GESAMTEN Kategorie-Baum je Element neu als Array auf (O(n·L) plus
* entsprechender GC-Druck). Bei einem Kataster-Import mit >100'000 Elementen
* war das zweistellige Millionen Allokationen pro Renderdurchlauf. Muster wie
* `generatePlan.ts::categoryColorMap`.
*/
interface DrawingColorMaps {
byCategory: Map<string, string>;
byLineStyle: Map<string, string>;
}
function buildDrawingColorMaps(project: Project): DrawingColorMaps {
const byCategory = new Map<string, string>();
for (const c of flattenCategories(project.layers)) {
if (c.color) byCategory.set(c.code, c.color);
}
const byLineStyle = new Map<string, string>();
for (const l of project.lineStyles) {
if (l.color) byLineStyle.set(l.id, l.color);
}
return { byCategory, byLineStyle };
}
/** Modellfarbe einer 2D-Zeichnung (color → LineStyle → Kategorie), analog `drawing2DColor`. */
function drawingColor3d(maps: DrawingColorMaps, d: Drawing2D): RRgb {
if (d.color) return hexToRgb(d.color, DRAWING_LINE_FALLBACK_RGB);
const ls = d.lineStyleId ? maps.byLineStyle.get(d.lineStyleId) : undefined;
if (ls) return hexToRgb(ls, DRAWING_LINE_FALLBACK_RGB);
const cat = maps.byCategory.get(d.categoryCode);
return cat ? hexToRgb(cat, DRAWING_LINE_FALLBACK_RGB) : DRAWING_LINE_FALLBACK_RGB;
}
/** 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) —
* beide MÜSSEN dieselbe Höhe verwenden, sonst klickt man daneben. */
function drawingElevation(project: Project, d: Drawing2D): number {
let baseZ = 0;
try {
baseZ = getFloor(project, d.levelId).baseElevation ?? 0;
} catch {
// Geschoss nicht (mehr) auflösbar: bei UK 0 zeichnen (Fallback).
}
return baseZ + DRAWING_LINE_ELEVATION_EPS;
}
/** 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 —
* die "2D-Referenz im 3D" (z. B. ein Kataster-Plan oder Boden-Raster), die
* auch der drei.js-Fallback (`addDrawing2DLines`) zeigt.
*
* 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). Entartete Segmente entfallen.
*
* WARUM LINIEN STATT MESHES (Nutzer-Report 2026-10-08, Kataster-DXF „Amtliche
* 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: 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 {
if (project.drawings2d.length === 0) return new Float32Array(0);
const maps = buildDrawingColorMaps(project);
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 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.
*/
export function pickDrawingSegs(project: Project): PickDrawingSeg[] {
const out: PickDrawingSeg[] = [];
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;
}