diff --git a/src-tauri/core/src/model3d.rs b/src-tauri/core/src/model3d.rs index 051a7a04..7207b9b3 100644 --- a/src-tauri/core/src/model3d.rs +++ b/src-tauri/core/src/model3d.rs @@ -1124,6 +1124,233 @@ pub fn parts(p: &Project, layered: bool, detail: f64, for_section: bool) -> Resu }) } +// ── 2D-Zeichnungen im 3D (Boden-Spuren) ───────────────────────────────────── + +/// Doppelte je Charge an `drawing2d_3d` — begrenzt den Speicher bei Kataster-Importen. +const CHUNK_DOUBLES: usize = 1 << 18; +const DRAWING_LINE_ELEVATION_EPS: f64 = 0.01; +const DRAWING_PICK_TOLERANCE: f64 = 0.12; + +/// Linienfarbe einer Zeichnung: color → Linienstil → Kategorie (`drawingColor3d`). +fn drawing_color( + d: &Drawing2D, + by_category: &HashMap<&str, &str>, + by_line_style: &HashMap<&str, &str>, +) -> Rgb { + let fb = style::DRAWING_LINE_FALLBACK_RGB; + if let Some(c) = d.color.as_deref().filter(|c| !c.is_empty()) { + return hex_to_rgb(c, fb); + } + if let Some(c) = d.line_style_id.as_deref().and_then(|id| by_line_style.get(id)) { + return hex_to_rgb(c, fb); + } + by_category.get(d.category_code.as_str()).map_or(fb, |c| hex_to_rgb(c, fb)) +} + +/// Packt die darstellbaren Zeichnungen (Linie, Polylinie, Rechteck) in Chargen für `drawing2d_3d`. +fn for_each_drawing_chunk(p: &Project, with_color: bool, mut f: impl FnMut(&[f64], &[&Drawing2D])) { + if p.drawings2d.is_empty() { + return; + } + let cats = p.flat_categories(); + let by_category: HashMap<&str, &str> = cats.iter().filter(|c| !c.color.is_empty()).map(|c| (c.code.as_str(), c.color.as_str())).collect(); + let by_line_style: HashMap<&str, &str> = p.line_styles.iter().filter(|l| !l.color.is_empty()).map(|l| (l.id.as_str(), l.color.as_str())).collect(); + let mut elevations: HashMap<&str, f64> = HashMap::new(); + let mut buf: Vec = vec![0.0]; + let mut ids: Vec<&Drawing2D> = Vec::new(); + let flush = |buf: &mut Vec, ids: &mut Vec<&Drawing2D>, f: &mut dyn FnMut(&[f64], &[&Drawing2D])| { + if ids.is_empty() { + return; + } + buf[0] = ids.len() as f64; + f(buf, ids); + ids.clear(); + buf.truncate(1); + }; + for d in &p.drawings2d { + let (kind, pts): (f64, Vec) = match &d.geom { + Drawing2DGeom::Line { a, b } => (1.0, vec![*a, *b]), + Drawing2DGeom::Rect { min, max } => (3.0, vec![*min, *max]), + Drawing2DGeom::Polyline { pts, .. } => (2.0, pts.clone()), + _ => continue, + }; + let need = 7 + 2 * pts.len(); + if buf.len() + need > CHUNK_DOUBLES { + flush(&mut buf, &mut ids, &mut f); + } + let elev = *elevations.entry(d.level_id.as_str()).or_insert_with(|| p.floor(&d.level_id).map_or(0.0, |l| l.base_elevation.unwrap_or(0.0)) + DRAWING_LINE_ELEVATION_EPS); + let rgb = if with_color { drawing_color(d, &by_category, &by_line_style) } else { [0.0; 3] }; + let closed = matches!(&d.geom, Drawing2DGeom::Polyline { closed: true, .. }); + buf.extend([kind, elev, rgb[0], rgb[1], rgb[2], if closed { 1.0 } else { 0.0 }, pts.len() as f64]); + for q in &pts { + buf.extend([q.x, q.y]); + } + ids.push(d); + } + flush(&mut buf, &mut ids, &mut f); +} + +/// Boden-Spuren aller Zeichnungen als LineList-Vertices `[px, py, pz, r, g, b]` (`emitDrawingLineVerts`). +pub fn drawing_line_verts(p: &Project) -> Vec { + let mut out = Vec::new(); + for_each_drawing_chunk(p, true, |buf, _| out.extend(crate::drawing2d_3d::line_verts(buf))); + out +} + +/// Pick-Strecke einer Zeichnung (`PickDrawingSeg`). +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PickDrawingSeg { + pub start: [f64; 2], + pub end: [f64; 2], + pub base_elevation: f64, + pub drawing_id: String, +} + +fn pick_drawing_segs(p: &Project) -> Vec { + let mut out = Vec::new(); + for_each_drawing_chunk(p, false, |buf, drawings| { + let f = crate::drawing2d_3d::pick_segs(buf, DRAWING_PICK_TOLERANCE); + for c in f.chunks_exact(6) { + out.push(PickDrawingSeg { start: [c[0], c[1]], end: [c[2], c[3]], base_elevation: c[4], drawing_id: drawings[c[5] as usize].id.clone() }); + } + }); + out +} + +// ── Pick-Geometrie ────────────────────────────────────────────────────────── + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PickBox { + pub start: [f64; 2], + pub end: [f64; 2], + pub thickness: f64, + pub height: f64, + pub base_elevation: f64, + pub opening_id: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PickStair { + pub outline: [[f64; 2]; 4], + pub z_bottom: f64, + pub z_top: f64, + pub stair_id: String, +} + +type Tri = [V3; 3]; + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PickRoof { + pub tris: Vec, + pub roof_id: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PickContextMesh { + pub tris: Vec, + pub context_object_id: String, +} + +#[derive(Debug, Serialize)] +pub struct PickGeometry { + pub walls: Vec, + pub slabs: Vec, + pub openings: Vec, + pub stairs: Vec, + pub roofs: Vec, + #[serde(rename = "contextMeshes")] + pub context_meshes: Vec, + pub drawings: Vec, +} + +/// Geometrie für den 3D-Raycast (`pickGeometry`). +pub fn pick_geometry(p: &Project) -> Result { + // Dächer: Flächen + Giebel als Welt-Dreiecke (Fächer ab Punkt 0), Modell [x, y, h] → Welt [x, h, y]. + let mut roofs = Vec::new(); + for roof in p.roofs.as_deref().unwrap_or(&[]) { + let g = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof)); + let to_world = |q: &V3| -> V3 { [q[0], q[2], q[1]] }; + let mut tris: Vec = Vec::new(); + for poly in g.planes.iter().chain(g.gables.iter()) { + for i in 1..poly.len().saturating_sub(1) { + tris.push([to_world(&poly[0]), to_world(&poly[i]), to_world(&poly[i + 1])]); + } + } + if !tris.is_empty() { + roofs.push(PickRoof { tris, roof_id: roof.id.clone() }); + } + } + let mut openings = Vec::new(); + for o in p.openings.as_deref().unwrap_or(&[]) { + let Some(wall) = p.walls.iter().find(|w| w.id == o.host_wall_id) else { continue }; + let wr = wall_ref(p, wall); + let Some((jamb_start, jamb_end)) = opening_geom::opening_jambs(&wr, o.position, o.width) else { continue }; + let thickness = p.wall_type(wall).map(|t| Project::type_thickness(&t.layers)).ok_or_else(|| format!("Unbekannter Wandtyp: {}", wall.wall_type_id))?; + let (zb, zt) = p.wall_vertical_extent(wall); + let o_bottom = zb + o.sill_height.max(0.0); + let o_top = zt.min(o_bottom + o.height); + if o_top - o_bottom <= 0.0 { + continue; + } + openings.push(PickBox { + start: [jamb_start.x, jamb_start.y], + end: [jamb_end.x, jamb_end.y], + thickness, + height: o_top - o_bottom, + base_elevation: o_bottom, + opening_id: o.id.clone(), + }); + } + let mut stairs = Vec::new(); + for st in p.stairs.as_deref().unwrap_or(&[]) { + let (z_bottom, z_top) = p.stair_vertical_extent(st); + let total_rise = z_top - z_bottom; + if total_rise <= 0.0 { + continue; + } + let geo = crate::stair::geometry(&st.encode(), total_rise); + let b = crate::stair::bbox(&geo); + let (min_x, min_y, max_x, max_y) = if b.len() >= 4 { (b[0], b[1], b[2], b[3]) } else { (0.0, 0.0, 0.0, 0.0) }; + stairs.push(PickStair { outline: [[min_x, min_y], [max_x, min_y], [max_x, max_y], [min_x, max_y]], z_bottom, z_top, stair_id: st.id.clone() }); + } + // Kontext-Meshes: rohe Welt-Dreiecke, Modell (x, y, z) → Welt (x, z, −y). + let mut context_meshes = Vec::new(); + for obj in p.context.as_deref().unwrap_or(&[]) { + let (pos, idx, id) = match obj { + ContextObject::TerrainMesh(m) => (&m.positions, &m.indices, &m.id), + ContextObject::ImportedMesh(m) => (&m.positions, &m.indices, &m.id), + _ => continue, + }; + let vcount = pos.len() / 3; + let at = |i: usize| -> V3 { [pos[i * 3], pos[i * 3 + 2], -pos[i * 3 + 1]] }; + let mut tris: Vec = Vec::new(); + for t in idx.chunks_exact(3) { + let ok = |v: f64| v >= 0.0 && v.fract() == 0.0 && (v as usize) < vcount; + if !(ok(t[0]) && ok(t[1]) && ok(t[2])) { + continue; + } + tris.push([at(t[0] as usize), at(t[1] as usize), at(t[2] as usize)]); + } + if !tris.is_empty() { + context_meshes.push(PickContextMesh { tris, context_object_id: id.clone() }); + } + } + Ok(PickGeometry { + walls: emit_walls(p, true)?, + slabs: emit_slabs(p), + openings, + stairs, + roofs, + context_meshes, + drawings: pick_drawing_segs(p), + }) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs index 0f26f366..4c2890f8 100644 --- a/src-tauri/core/src/queries.rs +++ b/src-tauri/core/src/queries.rs @@ -26,6 +26,7 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result json(&model3d::emit_stair_railings(p)), ("roofMeshes", _) => json(&model3d::emit_roofs(p, if text.is_empty() { None } else { Some(text) })?), ("roofCutLayers", _) => json(&model3d::emit_roof_cut_layers(p)?), + ("pickGeometry", _) => json(&model3d::pick_geometry(p)?), ("model3dParts", 3) => json(&model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?), _ => Err(format!("Unbekannte Abfrage: {name}")), } diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index 6dcd4355..ad13f78a 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -83,3 +83,10 @@ pub fn doc_query_args(h: u32, name: &str, args: &[f64], text: &str) -> String { Err(e) => format!("\u{1}{e}"), } } + +/// Boden-Spuren aller 2D-Zeichnungen als LineList-Vertices `[px, py, pz, r, g, b]` (Float32); +/// leer bei Fehler oder ohne Zeichnungen. +#[wasm_bindgen] +pub fn doc_drawing_line_verts(h: u32) -> Vec { + with_doc(h, |d| d.project().ok().map(|p| crate::model3d::drawing_line_verts(&p))).flatten().unwrap_or_default() +} diff --git a/src/core/document.ts b/src/core/document.ts index 5c7ad2b0..21828f48 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -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) : ""; diff --git a/src/plan/toWalls3d.ts b/src/plan/toWalls3d.ts index a99dad7d..b90b7636 100644 --- a/src/plan/toWalls3d.ts +++ b/src/plan/toWalls3d.ts @@ -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("slabs"), - openings, - stairs, - roofs, - contextMeshes, - drawings, - }; + return documentFor(project).query("pickGeometry"); } /** diff --git a/src/plan/toWalls3d/drawing2d.test.ts b/src/plan/toWalls3d/drawing2d.test.ts index 11179a40..4dbe2456 100644 --- a/src/plan/toWalls3d/drawing2d.test.ts +++ b/src/plan/toWalls3d/drawing2d.test.ts @@ -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 diff --git a/src/plan/toWalls3d/drawing2d.ts b/src/plan/toWalls3d/drawing2d.ts deleted file mode 100644 index 95c4c610..00000000 --- a/src/plan/toWalls3d/drawing2d.ts +++ /dev/null @@ -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; - byLineStyle: Map; -} - -function buildDrawingColorMaps(project: Project): DrawingColorMaps { - const byCategory = new Map(); - for (const c of flattenCategories(project.layers)) { - if (c.color) byCategory.set(c.code, c.color); - } - const byLineStyle = new Map(); - 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(); - 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; -}