diff --git a/TODO.md b/TODO.md index f0714d1a..124fa15e 100644 --- a/TODO.md +++ b/TODO.md @@ -10,7 +10,7 @@ Wer zu einer ID mehr wissen will (Entscheide, Tests, Bilder), sucht dort nach `* stehen im Archiv („Bewusst nicht übernommen“). - **Grösse** (eine Person mit Agenten): S ≤ 1 Tag · M ≤ 1 Woche · L ≤ 1 Monat · XL > 1 Monat. Steht keine Grösse im Archiv, ist sie hier geschätzt. -- **IDs sind stabil.** Neue ID = nächste freie Zahl nach der höchsten im Archiv und hier (aktuell 179); +- **IDs sind stabil.** Neue ID = nächste freie Zahl nach der höchsten im Archiv und hier (aktuell 201); nie eine ID wiederverwenden oder umnummerieren. Präfix-IDs (`[K]`, `[G]`, `[T]`, `[B]`, `[C]`) bleiben. - **Pro Punkt:** was fehlt · wo im Code · Grösse. Höchstens ein bis drei Sätze je Punkt; Messwerte und Befunde gehören in den Commit. @@ -658,7 +658,14 @@ Wer zu einer ID mehr wissen will (Entscheide, Tests, Bilder), sucht dort nach `* - ◐ **[BCF]** BCF (`fileio/src/bcf.rs`). Kamera im nativen Metal-Fenster; Schnittebene aus dem Live-Schnitt übernehmen; Kamera-Roll; schräge Schnittebenen nur angezeigt; `extensions.xml`, Farbgruppen/Linien, BimSnippet, Dokument- Referenzen und verwandte Themen gehen beim Speichern verloren. · M -- ◐ **[C11]** glTF/GLB-Export (`fileio/src/mesh_export.rs`). Keine Normalen/Texturen/Instanzen; Gelände ohne Vertex-Farben; +- ◐ **[201]** IFC-GlobalId-Rundreise, Normalen in glTF/OBJ (12.11.). Erledigt: `ifcGlobalId` an Wand, Öffnung (IfcDoor/IfcWindow), Decke, Stütze, + Dach, Treppe, Raum, Extrusionskörper — der IFC-Import setzt sie (`import_ifc.rs`), der Export schreibt sie zurück (Datensatz `GUIDS`, + `ifc_export/`), doppelte/ungültige fallen auf die abgeleitete GUID zurück; Kopieren/Einfügen/Reihe/Spiegeln/Wand teilen setzen sie + NICHT mit (`json_util::as_copy`); BCF-Zuordnung (`bcfMatch.ts`) nimmt sie. glTF/GLB mit `NORMAL` (geteilt bis 30° Knickwinkel, Funktion + `hatchgen/src/mesh_normals.rs` wie die 3D-Anzeige), OBJ mit `vn`, `usemtl` und `.mtl` (zweiter Speichern-Dialog; CLI schreibt beide + Dateien). Offen: GlobalId von Bäumen und IfcOpeningElement/-Beziehungen (bleiben abgeleitet); OBJ-Normalen/MTL im Tauri-Dialog + (zweiter Dialog) und IFC nicht in Revit/ArchiCAD geprüft; keine UVs/Texturen. · S +- ◐ **[C11]** glTF/GLB-Export (`fileio/src/mesh_export.rs`). Keine Texturen/Instanzen; Gelände ohne Vertex-Farben; Abzugskörper-Booleans und truck-Extrusionen nicht wie im 3D. · M - ◐ **[C12]** Allgemeiner Mesh-Import. Keine Texturen/UVs/Normalen/Vertex-Farben, keine `EXT_mesh_gpu_instancing`, Sparse-Accessors, Draco/Meshopt. · M diff --git a/doc/DATEIFORMATE.md b/doc/DATEIFORMATE.md index ee981eab..14619c88 100644 --- a/doc/DATEIFORMATE.md +++ b/doc/DATEIFORMATE.md @@ -61,7 +61,7 @@ Schreiber `fileio/src/ifc_export/mod.rs`, Aufruf `src/export/exportIfc.ts`. | Stützen, Bäume, Achsraster, Extrusionskörper | `IfcColumn`, `IfcGeographicElement` (IFC2x3: Proxy), `IfcGrid`, `IfcBuildingElementProxy` | Baum: zwei Netze Stamm + Krone | `ifc_data.rs` | | Psets / Mengen | `Pset_*Common` und `Qto_*BaseQuantities` nur mit **Modellwerten**; `CH_Qto_SIA416`, `Dossier_*` | keine frei definierbaren Eigenschaften | Kopf `ifc_data.rs`, Pset-Namen dort und in `ifc_quantities.rs` | | Georeferenz | ganze Geometrie in LV95, wenn `geoAnchor` gesetzt | – | `geo_rebase`, Kopf `ifc_data.rs` | -| GUIDs | deterministisch aus der Modell-id | – | `ifc_export::ifc_guid` | +| GUIDs | `ifcGlobalId` des Bauteils, wenn gesetzt (Import, [201]; Wand, Decke, Dach, Stütze, Treppe, Raum, Extrusion, Tür/Fenster); sonst deterministisch aus der Modell-id. Doppelte oder ungültige GlobalIds fallen auf die abgeleitete zurück | Bäume, `IfcOpeningElement` und Beziehungen bleiben abgeleitet | `ifc_data.rs` (Datensatz `GUIDS`), `ifc_export::ifc_guid` | | **Nicht exportiert** | 2D-Zeichnungen (ausser Raster), Texte, Bemassungen, Schraffuren, Layouts/Blätter, Ebenen als Sichtbarkeit, Stifte, Gruppen, Gelände, Netzkörper, Möbel/Blöcke, Ansichtsausschnitte | Im Sammler wird nur über Bauteile iteriert, `context` und `drawings2d` (ausser `Grid`) kommen nicht vor | `ifc_data.rs` (`grep context` leer) | Geprüft mit IfcOpenShell nur, wenn `ifcopenshell` installiert ist (`src/export/exportIfc.validate.test.ts`); ob @@ -80,7 +80,7 @@ Revit/ArchiCAD alles wie gewünscht lesen: ungeprüft. | Geschosse | Geschosse (Höhe ±5 mm wiederverwendet) | – | `import_ifc.rs::LEVEL_TOL` | | Psets | nur `IsExternal`, `LoadBearing`, `ThermalTransmittance`, Brand-/Schall-/Einbruchschutz, Raumbuch-Felder; **übrige Psets gehen verloren** | frei definierte Eigenschaften, Mengen (`Qto_*`) werden neu gerechnet | `import_ifc.rs` (`info.flag/text`), Tests „[98] Pset_*Common", „[158] Raumbuch" | | Klassifikation | nur **gezählt** im Bericht, nicht im Modell gespeichert | eBKP-H/Uniclass-Codes gehen verloren | `import_ifc.rs` (`classified`) | -| GlobalId | nur am Netzkörper (`ImportedMesh.ifcGlobalId`); Wände, Decken usw. **verlieren** sie | Export vergibt neue, aus der Dossier-id abgeleitete GUIDs; Rundreise über GUID nicht möglich | `model/generated.rs`, Test „Kontext-Mesh: Farbe und GlobalId" | +| GlobalId | an jedem erkannten Bauteil `ifcGlobalId` (Wand, Öffnung, Decke, Stütze, Dach, Treppe, Raum, Träger/Extrusion) und am Netzkörper | Kopien (Einfügen, Kopieren, Reihe, Spiegeln, Wand teilen) bekommen keine; der Export schreibt sie zurück, Rundreise über GUID möglich | `import_ifc.rs` (`set_gid`), Tests `ifcGlobalIdRoundtrip.test.ts`, „Kontext-Mesh: Farbe und GlobalId" | | Rest (Möbel, Haustechnik, Freiformen, Gelände) | Netzkörper `importedMesh` bzw. Gelände `terrainMesh` mit Klasse nach Herkunft | Nur Dreiecke und Farbe; Booleans und Öffnungen via BSP (`csg.rs`), bei Budget-Überschreitung fällt der Import auf den ersten Operanden zurück | `ARCHITEKTUR.md` §8, `CLAUDE.md` („3D-Booleans, wer wo") | | Klasse (`categoryCode`) | feste Codes je Bauteilart (Wand 20, Öffnung 21, Decke 30, Dach/Träger 35, Treppe 40, Stütze 50, Raum 60) | Eigene Ebenen der Quelle werden nicht übernommen | Konstanten in `import_ifc.rs` | @@ -145,8 +145,8 @@ Rundreise Dossier → DXF → Dossier: Linien/Bögen/Texte kommen wieder, Wände | Richtung | Inhalt | Verlust | Beleg | |---|---|---|---| -| Export OBJ/STL | Dreiecke; ein Objekt je Bauteil; Y-up rechtshändig, Meter | **OBJ ohne MTL, ohne Farben, Normalen und UVs**; STL ohne Farbe | `fileio/src/mesh_export.rs::write_obj` (keine `usemtl`/`mtllib`) | -| Export glTF/GLB | Knoten je Bauteil (`extras`: Typ, id), Material je Primitive (Farbe, Transparenz), optional nach Geschoss gegliedert | Keine Normalen, Texturen, UVs; im UI nur **GLB** wählbar (`.gltf` per Funktion) | Kopf `mesh_export.rs`, `ExportSaveDialog.tsx` | +| Export OBJ/STL | Dreiecke; ein Objekt je Bauteil; Y-up rechtshändig, Meter. OBJ mit `vn` (je Ecke geteilt bis 30° Knickwinkel wie die 3D-Anzeige, scharfe Kanten bleiben kantig), `usemtl` je Material und `.mtl` mit Farbe (`Kd`) und Deckkraft (`d`) | **OBJ ohne UVs/Texturen**; STL ohne Farbe. Die MTL ist eine zweite Datei: im Speichern-Dialog der App folgt ein zweiter Dialog (Browser: zweiter Download), CLI `obj --out haus.obj` schreibt `haus.mtl` mit, `--no-mtl` oder `--out -` nur das OBJ (Farben dann als Kommentar im Kopf, ohne `mtllib`) | `fileio/src/mesh_export.rs::write_obj`/`write_mtl`, `saveTextWithCompanion` | +| Export glTF/GLB | Knoten je Bauteil (`extras`: Typ, id), Material je Primitive (Farbe, Transparenz), optional nach Geschoss gegliedert | `NORMAL` je Ecke (wie OBJ geteilt bis 30°; Eckpunkte an scharfen Kanten getrennt). Keine Texturen, UVs; im UI nur **GLB** wählbar (`.gltf` per Funktion) | Kopf `mesh_export.rs`, `ExportSaveDialog.tsx` | | Quelle der Dreiecke | wie das 3D; Extrusionen mit Verjüngung als **Prisma-Näherung** | Dächer, Treppen, Stützen, Bäume (Stamm + Krone), Gelände und Netzkörper sind enthalten (Optionen `context`, `openingParts`) | Kopf `core/src/mesh_data.rs` | | Import OBJ(+MTL), STL, PLY (mit Flächen), glTF/GLB | Netzkörper je Objekt mit Name, Gruppe und Farbe; Achse und Einheit wählbar bzw. erkannt | **Texturen, Skinning, Morphing, Draco/Meshopt** nicht unterstützt; Dreiecksbudget 6 Mio. (Rest abgeschnitten) | Kopf `mesh_import.rs`, `mesh_import_gltf.rs` | @@ -201,8 +201,8 @@ Nur Import, alle Abrufe über `netFetch` (`src/net`). ## BCF `.bcfzip` 2.1/3.0 lesen und schreiben (Text, Kamera, Komponenten-GUIDs, Snapshots), `src/io/bcf.ts` und `fileio/src/bcf.rs`. -Die Zuordnung GUID zu Bauteil läuft über `bcfMatch.ts`; da importierte Bauteile ihre GlobalId verlieren (s. IFC-Import), -trifft sie nur Dossier-eigene, deterministische GUIDs. Themen leben in einer eigenen Datei, nicht im Projekt. +Die Zuordnung GUID zu Bauteil läuft über `bcfMatch.ts`: übernommene `ifcGlobalId` (IFC-Import, [201]) zuerst, sonst die +Dossier-eigene, deterministische GUID. Themen leben in einer eigenen Datei, nicht im Projekt. ## Querschnitt: was nirgends mitreist diff --git a/src-tauri/README.md b/src-tauri/README.md index e2afd2cd..35b9ceae 100644 --- a/src-tauri/README.md +++ b/src-tauri/README.md @@ -9,7 +9,7 @@ Zusammenspiel: `doc/ARCHITEKTUR.md`. |---|---|---|---| | `core/` | `dossier-core` | der Kern: Dokument, Ops, Verlauf, Projektformat, Plan, Schnitt, Ansicht, 3D, Export-Sammler, Befehle; siehe `core/src/README.md` | `npm run build:core` → `src/engine/pkgCore` | | `kernel2d/` | `kernel2d` | 2D-Geometrie: Offset, Trim, Extend, Fillet, Fase, Split, Join, Schnittpunkte, Treppen, Raum-Erkennung (je ein Modul unter `src/`, `lib.rs` re-exportiert), Bögen (`src/bulge.rs`) | im Kern eingebunden | -| `hatchgen/` | `dossier-hatch` | Schraffur- und Linienmuster (`hatch.rs`), Schnitt-Dominanz (`section_dominance.rs`), JS-Zahlsemantik (`jsnum.rs`, `jsmath.rs`) | im Kern und in render3d eingebunden | +| `hatchgen/` | `dossier-hatch` | Schraffur- und Linienmuster (`hatch.rs`), Schnitt-Dominanz (`section_dominance.rs`), geteilte Ecken-Normalen (`mesh_normals.rs`, 3D-Anzeige und glTF/OBJ-Export), JS-Zahlsemantik (`jsnum.rs`, `jsmath.rs`) | im Kern, in render3d und fileio eingebunden | | `render2d/` | `render2d` | Plan-Renderer: Szene lesen (`scene_bin.rs`), Tessellierung (`tessellate.rs`), wgpu (`gpu.rs`, Feature `render`), GPU-Chunks des nativen Wegs (`chunks.rs`), Browser-Bindung (`web.rs`) | `npm run build:engine` → `src/engine/pkg` | | `render3d/` | `render3d` | 3D-Renderer: Szene aus Teilen (`scene.rs`), Netze (`mesh.rs`), Kanten (`edges.rs`), Schatten (`shadow.rs`), Live-Schnitt (`section_fill.rs`, `section_boolean.rs`), Punktwolken, wgpu (`gpu.rs`), Browser-Bindung (`web.rs`); analytischer Prismen-Schnitt (`section.rs`, auch vom Kern genutzt); Headless-Bilder `src/bin/render_png.rs` | `npm run build:engine3d` → `src/engine/pkg3d` | | `fileio/` | `dossier-fileio` | Dateiformate: DXF/DWG lesen und schreiben (acadrust: `import.rs`, `export.rs`), IFC lesen (`ifc_import.rs`, `ifc_semantic.rs`) und schreiben (`ifc_export/`), Vektor-PDF (`pdf_*.rs`), Meshes, Punktwolken, Tabellen, BCF | `npm run build:fileio` → `src/engine/pkgFileIo` | diff --git a/src-tauri/core/src/cmd_paste.rs b/src-tauri/core/src/cmd_paste.rs index f6923acc..18fb6896 100644 --- a/src-tauri/core/src/cmd_paste.rs +++ b/src-tauri/core/src/cmd_paste.rs @@ -13,7 +13,7 @@ //! fehlende kommen ans Ende, unbekannte Felder bleiben). use crate::cmd_transform::IdGen; -use crate::json_util::{arr, field, with_all}; +use crate::json_util::{arr, as_copy, field, with_all}; use crate::ops::{id_of, Op}; use serde_json::Value; use std::collections::HashMap; @@ -51,7 +51,7 @@ pub fn paste_ops(clip: &Value, level_id: &str, stamp: &str) -> Vec { }); let Some((key, host)) = host else { continue }; let host = Value::String(host.clone()); - items.push(with_all(e, vec![("id", Value::String(ids.next(prefix))), (key, host)])); + items.push(with_all(&as_copy(e), vec![("id", Value::String(ids.next(prefix))), (key, host)])); continue; } let id = ids.next(prefix); @@ -60,7 +60,7 @@ pub fn paste_ops(clip: &Value, level_id: &str, stamp: &str) -> Vec { host_ids.insert(old.to_owned(), id.clone()); } } - items.push(with_all(e, vec![("id", Value::String(id)), (level_field, level.clone())])); + items.push(with_all(&as_copy(e), vec![("id", Value::String(id)), (level_field, level.clone())])); } if !items.is_empty() { ops.push(Op::Add { collection: collection.into(), items, at: None }); @@ -74,6 +74,21 @@ mod tests { use super::*; use serde_json::json; + /// [201] Eine Kopie bekommt eine neue id und NICHT die IFC-GlobalId des Originals. + #[test] + fn kopie_traegt_keine_ifc_global_id() { + let clip = json!({ + "walls": [{"id": "w1", "floorId": "eg", "ifcGlobalId": "0AbcDEFghijKLMNOPQRSt1"}], + "openings": [{"id": "o1", "hostWallId": "w1", "ifcGlobalId": "1AbcDEFghijKLMNOPQRSt2"}], + "columns": [{"id": "c1", "floorId": "eg", "ifcGlobalId": "2AbcDEFghijKLMNOPQRSt3"}] + }); + for op in paste_ops(&clip, "og", "s") { + for item in op.to_json()["items"].as_array().unwrap() { + assert!(item.get("ifcGlobalId").is_none(), "{item}"); + } + } + } + #[test] fn klone_mit_neuen_ids_auf_dem_aktiven_geschoss_oeffnung_umgehaengt() { let clip = json!({ diff --git a/src-tauri/core/src/cmd_transform.rs b/src-tauri/core/src/cmd_transform.rs index 0f24fc59..143a426d 100644 --- a/src-tauri/core/src/cmd_transform.rs +++ b/src-tauri/core/src/cmd_transform.rs @@ -12,7 +12,7 @@ //! Rechnung auf der rohen Projekt-Wurzel (verlustfrei, Schlüsselreihenfolge wie das Objekt-Spreizen in //! TS); Zahlen wie in JS (`jsnum`, `jsmath`), nicht endliche Ergebnisse als Marken (`json_util::js_num`). -use crate::json_util::{arr, field, js_num, num_of, num_or, pt, truthy, with, with_all, with_opt, xy, N}; +use crate::json_util::{arr, as_copy, field, js_num, num_of, num_or, pt, truthy, with, with_all, with_opt, xy, N}; use crate::jsmath::hypot2; use crate::jsnum; use crate::model::Project; @@ -959,7 +959,7 @@ pub fn transform_result(root: &Map, p: &Project, req: &TransformR for o in list(root, "openings") { let (Some(oid), Some(nh)) = (id_of(o), wall_host(o).and_then(|h| copied.get(h)).cloned()) else { continue }; let nid = ids.next("O"); - new_openings.push(with_all(&mv_wall_opening(o, &xf), vec![("id", Value::String(nid.clone())), ("hostWallId", Value::String(nh))])); + new_openings.push(with_all(&as_copy(&mv_wall_opening(o, &xf)), vec![("id", Value::String(nid.clone())), ("hostWallId", Value::String(nh))])); copied.insert(oid, nid); } let to_copy = |id: &str| copied.get(id).cloned(); @@ -976,23 +976,23 @@ pub fn transform_result(root: &Map, p: &Project, req: &TransformR Kind::Tree => (8, mv_tree(e, &xf)), Kind::Context => (9, mv_context(e, &xf)), }; - new[slot].push(with(&v, "id", Value::String(new_id.clone()))); + new[slot].push(with(&as_copy(&v), "id", Value::String(new_id.clone()))); } // Öffnungen kopierter Dächer/Decken ([103]) mit neuem Wirt mitkopieren. for o in list(root, "openings") { let Some((key, nh)) = surface_host(o).and_then(|(k, h)| Some((k, to_copy(h)?))) else { continue }; - let v = with(&mv_surface_opening(o, &xf), key, Value::String(nh)); + let v = with(&as_copy(&mv_surface_opening(o, &xf)), key, Value::String(nh)); new_openings.push(with(&v, "id", Value::String(ids.next("O")))); } // Kopien frei gewählter Wandöffnungen ([144]) in der Wand versetzt. for o in &free { if let Some(v) = slide(o, move_delta(&pts, t), true) { - new_openings.push(with(&v, "id", Value::String(ids.next("O")))); + new_openings.push(with(&as_copy(&v), "id", Value::String(ids.next("O")))); } } for o in &free_surf { if let Some(v) = slide_surface_opening(root, o, move_delta(&pts, t)) { - new_openings.push(with(&v, "id", Value::String(ids.next("O")))); + new_openings.push(with(&as_copy(&v), "id", Value::String(ids.next("O")))); } } } diff --git a/src-tauri/core/src/cmd_wall_edit.rs b/src-tauri/core/src/cmd_wall_edit.rs index 240881c5..e1686174 100644 --- a/src-tauri/core/src/cmd_wall_edit.rs +++ b/src-tauri/core/src/cmd_wall_edit.rs @@ -23,7 +23,7 @@ //! Geschosses, 2D-Linien/-Polylinien (mit Bögen)/-Rechtecke/-Kreise/-Bögen und Achsraster der Ebene. use crate::cmd_transform::{IdGen, Shapes}; -use crate::json_util::{arr, field, js_num, pt, with, with_all}; +use crate::json_util::{arr, as_copy, field, js_num, pt, with, with_all}; use crate::joins::Line; use crate::model::{DimFeature, DimRef, Drawing2D, Drawing2DGeom, Project, Vec2, Wall, WallReferenceLine}; use crate::ops::{id_of, Op}; @@ -592,7 +592,7 @@ pub fn commit(root: &Map, pr: &Project, e: &Edit, ids: &mut IdGen ops.push(Op::Replace { collection: "walls".into(), entity: with_all(src, f) }); } else { f.push(("id", Value::String(id.clone()))); - added.push(with_all(src, f)); + added.push(with_all(&as_copy(src), f)); } targets.push(Target { id, s0: *s0, s1: *s1 }); } @@ -605,7 +605,7 @@ pub fn commit(root: &Map, pr: &Project, e: &Edit, ids: &mut IdGen let Some(src) = raw(root, "walls", &n.src.id) else { continue }; let mut f = geom_fields(n.a, n.b, n.bulge); f.push(("id", Value::String(ids.next("wall")))); - let w = with_all(src, f); + let w = with_all(&as_copy(src), f); // Gerade Kopie einer Bogenwand: kein Bulge. let w = if n.bulge.is_none() { without(&w, "bulge") } else { w }; added.push(w); @@ -1291,11 +1291,15 @@ mod tests { fn trim_mittelstueck_teilt_und_haengt_oeffnungen_um() { let mut r = t_case(); r.get_mut("walls").unwrap().as_array_mut().unwrap().push(wall("c", (3.0, -3.0), (3.0, 3.0), None)); + r.get_mut("walls").unwrap().as_array_mut().unwrap()[0]["ifcGlobalId"] = "0AbcDEFghijKLMNOPQRSt1".into(); let pr = typed(&r); let e = trim(&pr, find_wall(&pr, "a").unwrap(), P::new(4.5, 0.0), false); let n = commit_edit(&r, &pr, e); assert!(close(xy_of(&w_of(&n, "a")["end"]), (3.0, 0.0))); let new = arr(n.get("walls")).iter().find(|w| w["id"] == "wall-s-1").unwrap(); + // [201] Das abgetrennte Stück ist eine neue Wand: GlobalId bleibt nur beim Original. + assert_eq!(w_of(&n, "a")["ifcGlobalId"], "0AbcDEFghijKLMNOPQRSt1"); + assert!(new.get("ifcGlobalId").is_none()); assert!(close(xy_of(&new["start"]), (6.0, 0.0))); let o2 = arr(n.get("openings")).iter().find(|o| o["id"] == "o2").unwrap(); assert_eq!(o2["hostWallId"], "wall-s-1"); diff --git a/src-tauri/core/src/ifc_data.rs b/src-tauri/core/src/ifc_data.rs index b049c5f0..5461a361 100644 --- a/src-tauri/core/src/ifc_data.rs +++ b/src-tauri/core/src/ifc_data.rs @@ -54,6 +54,7 @@ const REC_TREE: f64 = 19.0; const REC_COLUMN_PIECES: f64 = 20.0; const REC_CEILING_ARC: f64 = 21.0; const REC_SPACE_ARC: f64 = 22.0; +const REC_GUIDS: f64 = 23.0; /// Toleranz des Kerns (`wall_bands.rs::EPS`) für „Öffnung trifft Band". const BAND_EPS: f64 = 1e-4; @@ -899,6 +900,34 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result f.nums(&[a, b, storey_base[i]]); } + // [201] Übernommene GlobalIds (IFC-Import) vor allen Bauteilen; jede GlobalId höchstens einmal + // (Kopien tragen sie nicht, doppelt importierte Dateien würden sonst kollidieren). + { + let mut guids: Vec<(String, String)> = Vec::new(); + let mut push = |key: String, g: &Option| { + if let Some(g) = g.as_deref().filter(|g| !g.is_empty()) { + guids.push((key, g.to_string())); + } + }; + p.walls.iter().for_each(|x| push(format!("wall/{}", x.id), &x.ifc_global_id)); + p.ceilings.iter().flatten().for_each(|x| push(format!("slab/{}", x.id), &x.ifc_global_id)); + p.roofs.iter().flatten().for_each(|x| push(format!("roof/{}", x.id), &x.ifc_global_id)); + p.columns.iter().flatten().for_each(|x| push(format!("column/{}", x.id), &x.ifc_global_id)); + p.stairs.iter().flatten().for_each(|x| push(format!("stair/{}", x.id), &x.ifc_global_id)); + p.rooms.iter().flatten().for_each(|x| push(format!("space/{}", x.id), &x.ifc_global_id)); + p.extruded_solids.iter().flatten().for_each(|x| push(format!("extrusion/{}", x.id), &x.ifc_global_id)); + p.openings.iter().flatten().for_each(|x| push(format!("fill/{}", x.id), &x.ifc_global_id)); + let mut seen = std::collections::HashSet::new(); + guids.retain(|(_, g)| seen.insert(g.clone())); + if !guids.is_empty() { + f.nums(&[REC_GUIDS, guids.len() as f64]); + for (k, g) in guids { + let (a, b) = (f.str(&k), f.str(&g)); + f.nums(&[a, b]); + } + } + } + // Klassifikation: je geschriebenem Bauteil Schlüssel (wie für die GUID), Art und Ebene; `fileio` // überspringt Schlüssel ohne geschriebenes Bauteil. let mut classified: Vec<(String, Kind, String)> = Vec::new(); diff --git a/src-tauri/core/src/import_ifc.rs b/src-tauri/core/src/import_ifc.rs index 04be86fa..8dc0a83f 100644 --- a/src-tauri/core/src/import_ifc.rs +++ b/src-tauri/core/src/import_ifc.rs @@ -50,6 +50,8 @@ struct Info { type_name: Option, layers: Vec, classified: bool, + /// [201] IFC-GlobalId des Quell-Bauteils (22 Zeichen); bleibt am Element, der Export schreibt sie zurück. + global_id: Option, /// Eigenschaften aus `Pset_*Common` (Text). common: Map, } @@ -190,6 +192,11 @@ struct Elements { kept_reasons: Map, } +/// Gültige IFC-GlobalId: 22 Zeichen aus dem 64er-Alphabet, erstes Zeichen 0–3 (128 Bit). +fn is_ifc_guid(g: &str) -> bool { + g.len() == 22 && g.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'$') && matches!(g.as_bytes()[0], b'0'..=b'3') +} + fn s_of(v: Option<&Value>) -> Option { v.and_then(Value::as_str).map(str::to_string) } @@ -214,6 +221,7 @@ fn info_of(e: &Value) -> Info { type_name: s_of(e.get("typeName")), layers, classified: e.get("classifications").and_then(Value::as_array).is_some_and(|a| !a.is_empty()), + global_id: s_of(e.get("globalId")).filter(|g| is_ifc_guid(g)), common: e.get("common").and_then(Value::as_object).cloned().unwrap_or_default(), } } @@ -417,6 +425,13 @@ fn id_of(v: &Value) -> &str { v.get("id").and_then(Value::as_str).unwrap_or("") } +/// [201] GlobalId der Quelle ans neue Element (`ifcGlobalId`). +fn set_gid(v: &mut Value, info: &Info) { + if let Some(g) = &info.global_id { + v["ifcGlobalId"] = g.clone().into(); + } +} + fn pt(p: [f64; 2]) -> Value { json!({"x": js_num(p[0]), "y": js_num(p[1])}) } @@ -694,6 +709,7 @@ fn elements_ops(root: &Map, meta: &Value, products: &[IfcProduct] if let Some(b) = w.info.flag("LoadBearing") { o["loadBearing"] = b.into(); } + set_gid(&mut o, &w.info); walls.push(o); } let mut door_types: Vec<(Value, bool)> = list_of(root, "doorTypes"); @@ -740,6 +756,9 @@ fn elements_ops(root: &Map, meta: &Value, products: &[IfcProduct] let mut v = Map::new(); v.insert("id".into(), ctx.new_id("opening").into()); v.insert("type".into(), "opening".into()); + if let Some(g) = &o.info.global_id { + v.insert("ifcGlobalId".into(), g.clone().into()); + } v.insert("hostWallId".into(), host["id"].clone()); v.insert("categoryCode".into(), OPENING_CATEGORY.into()); v.insert("kind".into(), kind.into()); @@ -795,6 +814,9 @@ fn elements_ops(root: &Map, meta: &Value, products: &[IfcProduct] let mut v = Map::new(); v.insert("id".into(), ctx.new_id("ceiling").into()); v.insert("type".into(), "ceiling".into()); + if let Some(g) = &s.info.global_id { + v.insert("ifcGlobalId".into(), g.clone().into()); + } v.insert("floorId".into(), fid.clone().into()); v.insert("categoryCode".into(), CEILING_CATEGORY.into()); v.insert("outline".into(), s.outline.iter().map(|&p| mv(p)).collect()); @@ -824,6 +846,9 @@ fn elements_ops(root: &Map, meta: &Value, products: &[IfcProduct] let mut v = Map::new(); v.insert("id".into(), ctx.new_id("column").into()); v.insert("type".into(), "column".into()); + if let Some(g) = &c.info.global_id { + v.insert("ifcGlobalId".into(), g.clone().into()); + } v.insert("floorId".into(), fid.clone().into()); v.insert("categoryCode".into(), COLUMN_CATEGORY.into()); v.insert("position".into(), mv(c.center)); @@ -880,6 +905,7 @@ fn elements_ops(root: &Map, meta: &Value, products: &[IfcProduct] if let Some(t) = s.info.text("FloorBuildUp") { room["floorBuildUp"] = t.into(); } + set_gid(&mut room, &s.info); rooms.push(room); } @@ -902,6 +928,7 @@ fn elements_ops(root: &Map, meta: &Value, products: &[IfcProduct] if r.info.layers.iter().any(|l| !l.material.trim().is_empty()) { v["roofTypeId"] = type_for(&mut ctx, &mut roof_types, &r.info, r.thickness, "rooftype", "roofTypes").into(); } + set_gid(&mut v, &r.info); roofs.push(v); } let mut stairs: Vec = Vec::new(); @@ -952,6 +979,7 @@ fn elements_ops(root: &Map, meta: &Value, products: &[IfcProduct] } _ => {} } + set_gid(&mut v, &s.info); stairs.push(v); } // Träger als Extrusionskörper (Grundriss + Höhe über der Geschoss-UK). @@ -966,6 +994,7 @@ fn elements_ops(root: &Map, meta: &Value, products: &[IfcProduct] if off.abs() > 1e-9 { v["baseOffset"] = js_num(off); } + set_gid(&mut v, &b.info); solids.push(v); } @@ -1220,6 +1249,25 @@ mod tests { assert!(added(&r.ops, "rooms")[0].get("usage").is_none()); } + /// [201] Die GlobalId der Quelle landet an jedem erkannten Bauteil; ungültige fallen weg. + #[test] + fn global_id_goes_to_every_element() { + let (mut m, data) = meta("Haustür Eiche"); + let ids = ["0AbcDEFghijKLMNOPQRSt1", "1AbcDEFghijKLMNOPQRSt2", "2AbcDEFghijKLMNOPQRSt3", "3AbcDEFghijKLMNOPQRSt4", "kurz", "0AbcDEFghijKLMNOPQRSt6"]; + for (i, g) in ids.iter().enumerate() { + m["elements"]["elements"][i]["globalId"] = (*g).into(); + } + let opts = IfcOptions { file_name: "a.ifc".into(), group: None, elements: true }; + let r = ifc_import(&root(), &m.to_string(), &[], &[], &data, &opts, 0.0).unwrap(); + let gid = |v: &Value| v["ifcGlobalId"].as_str().map(str::to_string); + let walls = added(&r.ops, "walls"); + assert_eq!((gid(walls[0]), gid(walls[1])), (Some(ids[0].into()), Some(ids[2].into()))); + let openings = added(&r.ops, "openings"); + assert_eq!((gid(openings[0]), gid(openings[1])), (Some(ids[1].into()), Some(ids[3].into()))); + assert_eq!(gid(added(&r.ops, "roofs")[0]), None, "ungültige GlobalId wird nicht übernommen"); + assert_eq!(gid(added(&r.ops, "stairs")[0]), Some(ids[5].into())); + } + #[test] fn roof_stair_arc_wall_round_opening_type_by_name_and_map_shift() { let (m, data) = meta("Haustür Eiche"); diff --git a/src-tauri/core/src/json_util.rs b/src-tauri/core/src/json_util.rs index 726f4128..b3892cba 100644 --- a/src-tauri/core/src/json_util.rs +++ b/src-tauri/core/src/json_util.rs @@ -125,6 +125,12 @@ pub fn with_opt(v: &Value, fields: Vec<(&str, Option)>) -> Value { Value::Object(m) } +/// [201] Eine Kopie mit neuer id trägt die IFC-GlobalId des Originals nicht mit (sonst zwei Bauteile mit +/// derselben GlobalId im Export). +pub fn as_copy(v: &Value) -> Value { + with_opt(v, vec![("ifcGlobalId", None)]) +} + pub fn arr(v: Option<&Value>) -> &[Value] { v.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]) } diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs index 2668a363..3b9096eb 100644 --- a/src-tauri/core/src/model/generated.rs +++ b/src-tauri/core/src/model/generated.rs @@ -2838,6 +2838,11 @@ pub struct Wall { /// Grafik-Kategorie (Ebene), z. B. "20" für Wände. #[serde(rename = "categoryCode")] pub category_code: String, + /// [201] IFC-GlobalId des Quell-Bauteils (IFC-Import); der IFC-Export schreibt sie zurück, damit + /// die Rundreise dieselben GUIDs behält. Kopien (Einfügen, Kopieren, Reihe, Wand teilen) tragen sie NICHT. + #[serde(rename = "ifcGlobalId", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub ifc_global_id: Option, /// Vorsprung im Baurecht ([63]: Wand eines Erkers): darf mit `SiteRules.projectionDepth`/ /// `projectionShare` in den Grenzabstand ragen. Fehlt ⇒ normales Bauteil. #[serde(rename = "siteProjection", default, skip_serializing_if = "Option::is_none")] @@ -3018,6 +3023,11 @@ pub struct Ceiling { /// Grafik-Kategorie (Ebene), z. B. "30" für Decken. #[serde(rename = "categoryCode")] pub category_code: String, + /// [201] IFC-GlobalId des Quell-Bauteils (IFC-Import); der IFC-Export schreibt sie zurück, damit + /// die Rundreise dieselben GUIDs behält. Kopien (Einfügen, Kopieren, Reihe, Wand teilen) tragen sie NICHT. + #[serde(rename = "ifcGlobalId", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub ifc_global_id: Option, /// Vorsprung im Baurecht ([63]: Balkon, Erker): darf mit `SiteRules.projectionDepth`/ /// `projectionShare` in den Grenzabstand ragen. Fehlt ⇒ normales Bauteil. #[serde(rename = "siteProjection", default, skip_serializing_if = "Option::is_none")] @@ -3219,6 +3229,11 @@ pub struct Roof { /// Grafik-Kategorie (Ebene), z. B. "35" für Dächer. #[serde(rename = "categoryCode")] pub category_code: String, + /// [201] IFC-GlobalId des Quell-Bauteils (IFC-Import); der IFC-Export schreibt sie zurück, damit + /// die Rundreise dieselben GUIDs behält. Kopien (Einfügen, Kopieren, Reihe, Wand teilen) tragen sie NICHT. + #[serde(rename = "ifcGlobalId", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub ifc_global_id: Option, /// Objekt-Sperre, analog `Wall.locked`. #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] @@ -3601,6 +3616,11 @@ pub struct Opening { /// Grafik-Kategorie (Ebene), z. B. "21" für Türen/Fenster. #[serde(rename = "categoryCode")] pub category_code: String, + /// [201] IFC-GlobalId des Quell-Bauteils (IFC-Import); der IFC-Export schreibt sie zurück, damit + /// die Rundreise dieselben GUIDs behält. Kopien (Einfügen, Kopieren, Reihe, Wand teilen) tragen sie NICHT. + #[serde(rename = "ifcGlobalId", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub ifc_global_id: Option, /// Objekt-Sperre, analog `Wall.locked`. #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] @@ -3914,6 +3934,11 @@ pub struct Stair { /// Grafik-Kategorie (Ebene), z. B. "40" für Treppen. #[serde(rename = "categoryCode")] pub category_code: String, + /// [201] IFC-GlobalId des Quell-Bauteils (IFC-Import); der IFC-Export schreibt sie zurück, damit + /// die Rundreise dieselben GUIDs behält. Kopien (Einfügen, Kopieren, Reihe, Wand teilen) tragen sie NICHT. + #[serde(rename = "ifcGlobalId", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub ifc_global_id: Option, /// Objekt-Sperre, analog `Wall.locked`. #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] @@ -4216,6 +4241,11 @@ pub struct Room { /// Grafik-Kategorie (Ebene), z. B. "45" für Räume. #[serde(rename = "categoryCode")] pub category_code: String, + /// [201] IFC-GlobalId des Quell-Bauteils (IFC-Import); der IFC-Export schreibt sie zurück, damit + /// die Rundreise dieselben GUIDs behält. Kopien (Einfügen, Kopieren, Reihe, Wand teilen) tragen sie NICHT. + #[serde(rename = "ifcGlobalId", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub ifc_global_id: Option, /// Objekt-Sperre, analog `Wall.locked`. #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] @@ -4565,6 +4595,11 @@ pub struct ExtrudedSolid { /// [180] Klasse (Ebene/Kategorie) wie bei jedem Bauteil: Sichtbarkeit in Grundriss, Schnitt und Ansicht. #[serde(rename = "categoryCode")] pub category_code: String, + /// [201] IFC-GlobalId des Quell-Bauteils (IFC-Import); der IFC-Export schreibt sie zurück, damit + /// die Rundreise dieselben GUIDs behält. Kopien (Einfügen, Kopieren, Reihe, Wand teilen) tragen sie NICHT. + #[serde(rename = "ifcGlobalId", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub ifc_global_id: Option, /// Geschlossenes Profil in der XY-Ebene (Grundriss), ≥3 Punkte. Bei einem /// Kreis-Profil (`circle` gesetzt) eine Tessellierung des Kreises (48-Eck) — /// für 2D-Footprint/Auswahl/bbox/Verschieben; die 3D-Extrusion nutzt in dem @@ -4643,6 +4678,11 @@ pub struct Column { /// Grafik-Kategorie (Ebene), z. B. "50" für Tragwerk. #[serde(rename = "categoryCode")] pub category_code: String, + /// [201] IFC-GlobalId des Quell-Bauteils (IFC-Import); der IFC-Export schreibt sie zurück, damit + /// die Rundreise dieselben GUIDs behält. Kopien (Einfügen, Kopieren, Reihe, Wand teilen) tragen sie NICHT. + #[serde(rename = "ifcGlobalId", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub ifc_global_id: Option, /// Objekt-Sperre, analog `Wall.locked`. #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] diff --git a/src-tauri/fileio/Cargo.lock b/src-tauri/fileio/Cargo.lock index 34e5e3cb..4506350e 100644 --- a/src-tauri/fileio/Cargo.lock +++ b/src-tauri/fileio/Cargo.lock @@ -144,6 +144,7 @@ version = "0.1.0" dependencies = [ "acadrust", "console_error_panic_hook", + "dossier-hatch", "e57", "earcutr", "flate2", @@ -157,6 +158,13 @@ dependencies = [ "zip", ] +[[package]] +name = "dossier-hatch" +version = "0.1.0" +dependencies = [ + "libm", +] + [[package]] name = "e57" version = "0.11.13" @@ -320,6 +328,12 @@ version = "0.2.186" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "log" version = "0.4.34" diff --git a/src-tauri/fileio/Cargo.toml b/src-tauri/fileio/Cargo.toml index 6981784d..e5ff50ed 100644 --- a/src-tauri/fileio/Cargo.toml +++ b/src-tauri/fileio/Cargo.toml @@ -56,5 +56,8 @@ quick-xml = "0.39" # Vektor-PDF ([76]): FlateDecode-Streams (MIT OR Apache-2.0, reines Rust über miniz_oxide; schon über zip im Baum). flate2 = { version = "1", default-features = false, features = ["rust_backend"] } +# Geteilte Ecken-Normalen (glTF/OBJ-Export), dieselbe Funktion wie die 3D-Anzeige in render3d. +dossier-hatch = { path = "../hatchgen" } + [dev-dependencies] serde_json = "1" diff --git a/src-tauri/fileio/src/ifc_export/builder.rs b/src-tauri/fileio/src/ifc_export/builder.rs index a4fda816..0846d87e 100644 --- a/src-tauri/fileio/src/ifc_export/builder.rs +++ b/src-tauri/fileio/src/ifc_export/builder.rs @@ -34,6 +34,8 @@ pub(super) struct Builder { pub(super) column_materials: Vec<(String, String, Vec)>, /// Bauteil-Schlüssel (wie für die GlobalId, z. B. `wall/`) → Entität; Ziel von Klassifikation/Zone/Attach. pub(super) elements: HashMap, + /// [201] Übernommene GlobalIds (Schlüssel wie für `gid`), Vorrang vor der abgeleiteten. + pub(super) guid_override: HashMap, /// IFC2x3: Türen/Fenster je (Tür?, Ausführung) → Bauteile; am Ende je ein IfcDoorStyle/IfcWindowStyle. pub(super) fill_styles: Vec<(bool, String, Vec)>, } @@ -53,6 +55,9 @@ impl Builder { /// Dauerhafte GlobalId (als STEP-String) aus `/[/]`, im Namensraum des Projekts. pub(super) fn gid(&self, key: &str) -> String { + if let Some(g) = self.guid_override.get(key) { + return ifc_string(g); + } ifc_string(&ifc_guid(&format!("{}/{key}", self.project_id))) } diff --git a/src-tauri/fileio/src/ifc_export/format.rs b/src-tauri/fileio/src/ifc_export/format.rs index c87a5372..625b5253 100644 --- a/src-tauri/fileio/src/ifc_export/format.rs +++ b/src-tauri/fileio/src/ifc_export/format.rs @@ -48,6 +48,11 @@ pub(super) fn fnv1a64(bytes: &[u8], seed: u64, reverse: bool) -> u64 { hash } +/// Gültige IFC-GlobalId: 22 Zeichen des 64er-Alphabets, erstes Zeichen 0–3 (128 Bit). +pub fn valid_guid(g: &str) -> bool { + g.len() == 22 && g.bytes().all(|b| IFC_GUID_CHARS.contains(&b)) && matches!(g.as_bytes()[0], b'0'..=b'3') +} + /// Deterministische 22-stellige IFC-GUID aus einem Namen: zwei unabhängige 64-Bit-Läufe (FNV-1a vorwärts/ /// rückwärts mit verschiedenen Startwerten, je fmix64-nachgemischt), gekennzeichnet als RFC-9562-UUID /// Version 8 mit Variante 10. Im Export lautet der Name `//[/]`. diff --git a/src-tauri/fileio/src/ifc_export/mod.rs b/src-tauri/fileio/src/ifc_export/mod.rs index cf4e167f..60f17f5a 100644 --- a/src-tauri/fileio/src/ifc_export/mod.rs +++ b/src-tauri/fileio/src/ifc_export/mod.rs @@ -100,6 +100,10 @@ // IfcZone mit IfcRelAssignsToGroup der Räume (`space/`-Entitäten; unbekannte ids werden // übersprungen, ohne Raum keine Zone). GlobalId aus `zone/`; Psets/Mengen wie bei Bauteilen. // ATTACH = 14, key, PSETS (Psets/Mengen an ein schon geschriebenes Bauteil/Geschoss, Schlüssel wie oben) +// GUIDS = 23 ([201] GlobalId-Rundreise), n, (key, guid) × n: übernommene GlobalIds importierter Bauteile. +// key = Bauteil-Schlüssel wie für die abgeleitete GlobalId (`wall/`, `slab/`, `roof/`, +// `column/`, `stair/`, `space/`, `extrusion/`, `fill/<Öffnungs-id>`); guid = 22 Zeichen. +// Gehört VOR alle Bauteile. Doppelte oder ungültige GlobalIds werden verworfen (dann abgeleitet). // TREE = 19 ([149] Baum), structure, id, name, PSETS, MESH (Stamm + Krone, Welt rel. Geschoss-UK) // IFC4: IfcGeographicElement (ObjectType „Baum", PredefinedType USERDEFINED); IFC2x3 (kennt die // Klasse nicht): IfcBuildingElementProxy mit ObjectType „Baum". GlobalId aus `tree/`. @@ -153,6 +157,7 @@ pub const REC_OPENING_SOLID: f64 = 15.0; pub const REC_WALL_ARC: f64 = 16.0; pub const REC_WALL_ARC_SOLID: f64 = 17.0; pub const REC_GRID: f64 = 18.0; +pub const REC_GUIDS: f64 = 23.0; pub const REC_TREE: f64 = 19.0; pub const REC_COLUMN_PIECES: f64 = 20.0; pub const REC_CEILING_ARC: f64 = 21.0; @@ -186,6 +191,7 @@ fn rec_name(code: f64) -> &'static str { c if c == REC_ZONE => "ZONE", c if c == REC_ATTACH => "ATTACH", c if c == REC_GRID => "GRID", + c if c == REC_GUIDS => "GUIDS", c if c == REC_TREE => "TREE", c if c == REC_COLUMN_PIECES => "COLUMN_PIECES", _ => "?", @@ -257,6 +263,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { types: Vec::new(), type_index: HashMap::new(), walls: HashMap::new(), + guid_override: HashMap::new(), axis_context: 0, styles: [0; 3], spaces: Vec::new(), @@ -1131,6 +1138,18 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { w.add_to_containment(structure, entity); w.elements.insert(format!("grid/{id}"), entity); } + c if c == REC_GUIDS => { + let n = r.idx()?; + let mut used: std::collections::HashSet = w.guid_override.values().cloned().collect(); + for _ in 0..n { + let key = r.string()?; + let guid = r.string()?; + // Nur gültige, bisher unbenutzte GlobalIds; sonst bleibt es bei der abgeleiteten. + if valid_guid(&guid) && used.insert(guid.clone()) { + w.guid_override.insert(key, guid); + } + } + } c if c == REC_ATTACH => { let key = r.string()?; let psets = r.psets()?; diff --git a/src-tauri/fileio/src/mesh_export.rs b/src-tauri/fileio/src/mesh_export.rs index 76f2bd3a..3c7525e5 100644 --- a/src-tauri/fileio/src/mesh_export.rs +++ b/src-tauri/fileio/src/mesh_export.rs @@ -21,11 +21,19 @@ // // glTF: ein Knoten je Bauteil (Name = Gruppenname, `extras` = Typ und id), je Material eine Primitive, // PBR (`baseColorFactor` linear, aus sRGB umgerechnet), transparente Materialien mit `alphaMode: BLEND`, -// Positionen als FLOAT mit `min`/`max`, Indizes als UNSIGNED_INT, keine Normalen (glTF schreibt dann -// Flat-Shading vor). GLB = JSON-Chunk + BIN-Chunk; `.gltf` bettet den Puffer als Base64-Data-URI ein. +// Positionen als FLOAT mit `min`/`max`, Indizes als UNSIGNED_INT, NORMAL als FLOAT VEC3 ([201]): geteilte +// Ecken-Normalen nach Knickwinkel (`CREASE_DEG`), dieselbe Funktion wie die 3D-Anzeige +// (`dossier_hatch::mesh_normals::smooth_corner_normals`); Ecken mit verschiedener Normale werden getrennte Eckpunkte, +// scharfe Kanten (über dem Knickwinkel) bleiben also kantig. OBJ: `vn` je Fläche/Ecke, `usemtl` je Teil-Netz und +// optional `mtllib` auf eine MTL mit den Farben (`export_mtl`). GLB = JSON-Chunk + BIN-Chunk; `.gltf` bettet den Puffer als Base64-Data-URI ein. // Keine Abhängigkeit: JSON und Base64 sind hier von Hand geschrieben. use crate::ifc_export::fmt_real; +use dossier_hatch::mesh_normals::smooth_corner_normals; +use std::collections::HashMap; + +/// Knickwinkel, bis zu dem Ecken-Normalen geteilt werden (wie `DEFAULT_CREASE_DEG` der 3D-Anzeige für glatte Netze). +const CREASE_DEG: f32 = 30.0; const FLAT_VERSION: f64 = 1.0; @@ -171,16 +179,105 @@ fn to_file(x: f64, y: f64, z: f64) -> [f64; 3] { [x, y, 0.0 - z] } -// ── OBJ ───────────────────────────────────────────────────────────────────── +// ── Normalen ──────────────────────────────────────────────────────────────── -fn write_obj(s: &Scene) -> String { +/// Ecken-Normalen je Dreieck eines Teil-Netzes in DATEI-Achsen ((x, y, −z), passend zu `to_file`); entartete Dreiecke +/// bekommen +Y. Rechnung in Szene-Achsen (Wicklung nach aussen), dann gespiegelt: Spiegelung + vertauschte Wicklung +/// lassen die Normale nach aussen zeigen. +fn corner_normals_file(p: &Prim) -> Vec<[[f32; 3]; 3]> { + let nv = p.positions.len() / 3; + let world = |i: usize| -> [f32; 3] { [p.positions[i * 3] as f32, p.positions[i * 3 + 1] as f32, p.positions[i * 3 + 2] as f32] }; + smooth_corner_normals(&p.indices, nv, &world, CREASE_DEG) + .into_iter() + .map(|t| match t { + Some(n) => n.map(|v| [v[0], v[1], 0.0 - v[2]]), + None => [[0.0, 1.0, 0.0]; 3], + }) + .collect() +} + +fn normal_key(n: [f32; 3]) -> [i32; 3] { + [(n[0] * 1e5).round() as i32, (n[1] * 1e5).round() as i32, (n[2] * 1e5).round() as i32] +} + +// ── OBJ / MTL ─────────────────────────────────────────────────────────────── + +/// Materialnamen für `usemtl`/`newmtl`: ohne Leerraum, eindeutig; Index `materials.len()` = „Standard“ (Teile ohne Material). +fn material_names(s: &Scene) -> Vec { + let mut out: Vec = Vec::new(); + for (i, m) in s.materials.iter().enumerate() { + let base: String = m.name.chars().map(|c| if c.is_whitespace() || c.is_control() { '_' } else { c }).collect(); + let base = if base.is_empty() { "Material".to_string() } else { base }; + let name = if out.contains(&base) { format!("{base}_{i}") } else { base }; + out.push(name); + } + out.push(if out.iter().any(|n| n == "Standard") { "Standard_0".to_string() } else { "Standard".to_string() }); + out +} + +fn mat_index(s: &Scene, m: i64) -> usize { + if m >= 0 { + m as usize + } else { + s.materials.len() + } +} + +/// Verwendete Materialien (Index in `material_names`) in der Reihenfolge des ersten Auftretens. +fn used_materials(s: &Scene) -> Vec { + let mut used: Vec = Vec::new(); + for g in s.groups.iter().filter(|g| tri_count(g) > 0) { + for p in g.prims.iter().filter(|p| !p.indices.is_empty()) { + let k = mat_index(s, p.material); + if !used.contains(&k) { + used.push(k); + } + } + } + used +} + +/// Farbe eines (verwendeten) Materials: aus der Szene, „Standard“ grau. +fn rgba_of(s: &Scene, k: usize) -> [f64; 4] { + s.materials.get(k).map_or([0.8, 0.8, 0.8, 1.0], |m| m.rgba) +} + +/// MTL-Datei mit den Farben der verwendeten Materialien (Kd = sRGB-Farbe, d = Deckkraft). +fn write_mtl(s: &Scene) -> String { + let names = material_names(s); + let mut out = String::from("# DOSSIER MTL - Materialien des OBJ-Exports (Kd = sRGB-Farbe 0..1, d = Deckkraft)\n"); + for k in used_materials(s) { + let c = rgba_of(s, k); + out.push_str(&format!("\nnewmtl {}\nKa 0 0 0\n", names[k])); + out.push_str(&format!("Kd {} {} {}\n", fmt_real(c[0].clamp(0.0, 1.0)), fmt_real(c[1].clamp(0.0, 1.0)), fmt_real(c[2].clamp(0.0, 1.0)))); + out.push_str(&format!("Ks 0 0 0\nd {}\nillum 2\n", fmt_real(c[3].clamp(0.0, 1.0)))); + } + out +} + +/// OBJ mit `vn` und `usemtl`. `mtl_name` = Dateiname der MTL (`mtllib`); leer ⇒ keine MTL daneben, die Farben stehen dann +/// als Kommentar im Kopf (jedes Material bleibt eine eigene `usemtl`-Gruppe). +fn write_obj(s: &Scene, mtl_name: &str) -> String { + let names = material_names(s); let mut out = String::new(); out.push_str("# DOSSIER OBJ-Export - Dreiecks-Mesh des 3D-Gebaeudemodells\n"); out.push_str("# Achsen: rechtshaendig, Y-up (Y = Hoehe ueber OKFF), Modell (x,y,z) -> (x,z,-y), Norden = -Z.\n"); out.push_str("# Waende: Schicht-Baender mit oeffnungsgenau ausgeschnittenen Loechern (inkl. Laibungen).\n"); out.push_str("# Decken/Extrusionen: Umriss-Prisma (Ear-Clipping-Triangulierung).\n"); out.push_str("# Daecher, Treppen, Stuetzen, Fenster/Tueren (je Oeffnung ein Objekt), Gelaende und Kontext-Meshes wie im 3D.\n"); + out.push_str(&format!("# Normalen: je Ecke geteilt bis {CREASE_DEG} Grad Knickwinkel (wie die 3D-Anzeige), scharfe Kanten bleiben kantig.\n")); + let mtl_name = mtl_name.trim(); + if mtl_name.is_empty() { + out.push_str("# Farben (ohne MTL-Datei; Gruppen je Material mit usemtl):\n"); + for k in used_materials(s) { + let c = rgba_of(s, k); + out.push_str(&format!("# {}: Kd {} {} {} d {}\n", names[k], fmt_real(c[0]), fmt_real(c[1]), fmt_real(c[2]), fmt_real(c[3]))); + } + } else { + out.push_str(&format!("mtllib {mtl_name}\n")); + } let mut offset = 0usize; + let mut n_off = 0usize; for g in s.groups.iter().filter(|g| tri_count(g) > 0) { out.push_str("o "); out.push_str(&g.name); @@ -192,15 +289,41 @@ fn write_obj(s: &Scene) -> String { out.push_str(&format!("v {} {} {}\n", fmt_real(f[0]), fmt_real(f[1]), fmt_real(f[2]))); } } + // Normalen des Objekts (je verschiedene Richtung einmal), Flächen verweisen darauf. + let mut normals: HashMap<[i32; 3], usize> = HashMap::new(); + let mut per_prim: Vec> = Vec::new(); + let mut vn = String::new(); for p in &g.prims { - for t in p.indices.chunks_exact(3) { - let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize); + let mut tris = Vec::new(); + for t in corner_normals_file(p) { + let mut ids = [0usize; 3]; + for (c, n) in t.iter().enumerate() { + let next = normals.len(); + ids[c] = *normals.entry(normal_key(*n)).or_insert_with(|| { + vn.push_str(&format!("vn {} {} {}\n", fmt_real(f64::from(n[0])), fmt_real(f64::from(n[1])), fmt_real(f64::from(n[2])))); + next + }); + } + tris.push(ids); + } + per_prim.push(tris); + } + out.push_str(&vn); + for (p, tris) in g.prims.iter().zip(&per_prim) { + if p.indices.is_empty() { + continue; + } + out.push_str(&format!("usemtl {}\n", names[mat_index(s, p.material)])); + for (t, nrm) in p.indices.chunks_exact(3).zip(tris) { + let (a, b, c) = (t[0] as usize + 1 + offset + local, t[2] as usize + 1 + offset + local, t[1] as usize + 1 + offset + local); // Z gespiegelt ⇒ Wicklung vertauschen (Normalen zeigen weiter nach aussen). - out.push_str(&format!("f {} {} {}\n", a + 1 + offset + local, c + 1 + offset + local, b + 1 + offset + local)); + let (na, nb, nc) = (nrm[0] + 1 + n_off, nrm[2] + 1 + n_off, nrm[1] + 1 + n_off); + out.push_str(&format!("f {a}//{na} {b}//{nb} {c}//{nc}\n")); } local += p.positions.len() / 3; } offset += local; + n_off += normals.len(); } out } @@ -338,7 +461,7 @@ fn build_gltf(s: &Scene, uri_for_buffer: bool) -> (String, Vec) { // Gruppen mit Dreiecken → Knoten 0..n_mesh (Knoten i = Mesh i). for g in s.groups.iter().filter(|g| tri_count(g) > 0) { // Je Material eine Primitive (gleiches Material zusammenfassen, Reihenfolge des ersten Auftretens). - let mut merged: Vec<(i64, Vec, Vec)> = Vec::new(); + let mut merged: Vec<(i64, Vec, Vec, Vec)> = Vec::new(); for p in &g.prims { if p.indices.is_empty() { continue; @@ -346,18 +469,27 @@ fn build_gltf(s: &Scene, uri_for_buffer: bool) -> (String, Vec) { let at = match merged.iter().position(|m| m.0 == p.material) { Some(i) => i, None => { - merged.push((p.material, Vec::new(), Vec::new())); + merged.push((p.material, Vec::new(), Vec::new(), Vec::new())); merged.len() - 1 } }; let m = &mut merged[at]; - let base = (m.1.len() / 3) as u32; - // Z spiegeln (Modell-Welt → rechtshändiges glTF) und Wicklung vertauschen. - for v in p.positions.chunks_exact(3) { - m.1.extend_from_slice(&[v[0] as f32, v[1] as f32, 0.0 - v[2] as f32]); - } - for t in p.indices.chunks_exact(3) { - m.2.extend_from_slice(&[base + t[0], base + t[2], base + t[1]]); + // Eckpunkte je (Index, Normale): Ecken mit gleicher Normale teilen sich einen Punkt, scharfe Kanten + // bekommen getrennte. Z spiegeln (Modell-Welt → rechtshändiges glTF) und Wicklung vertauschen. + let normals = corner_normals_file(p); + let mut local: HashMap<(u32, [i32; 3]), u32> = HashMap::new(); + for (t, nrm) in p.indices.chunks_exact(3).zip(&normals) { + for c in [0usize, 2, 1] { + let key = (t[c], normal_key(nrm[c])); + let next = (m.1.len() / 3) as u32; + let id = *local.entry(key).or_insert_with(|| { + let v = &p.positions[t[c] as usize * 3..t[c] as usize * 3 + 3]; + m.1.extend_from_slice(&[v[0] as f32, v[1] as f32, 0.0 - v[2] as f32]); + m.2.extend_from_slice(&nrm[c]); + next + }); + m.3.push(id); + } } } push_sep(&mut meshes, n_mesh); @@ -365,7 +497,7 @@ fn build_gltf(s: &Scene, uri_for_buffer: bool) -> (String, Vec) { meshes.push_str("{\"name\":"); json_str(&g.name, &mut meshes); meshes.push_str(",\"primitives\":["); - for (k, (mat, pos, idx)) in merged.iter().enumerate() { + for (k, (mat, pos, nrm, idx)) in merged.iter().enumerate() { let (mut lo, mut hi) = ([f32::MAX; 3], [f32::MIN; 3]); for v in pos.chunks_exact(3) { for a in 0..3 { @@ -381,9 +513,14 @@ fn build_gltf(s: &Scene, uri_for_buffer: bool) -> (String, Vec) { for i in idx { bin.extend_from_slice(&i.to_le_bytes()); } + let nrm_off = bin.len(); + for f in nrm { + bin.extend_from_slice(&f.to_le_bytes()); + } push_sep(&mut views, n_views); views.push_str(&format!("{{\"buffer\":0,\"byteOffset\":{pos_off},\"byteLength\":{},\"target\":34962}}", pos.len() * 4)); views.push_str(&format!(",{{\"buffer\":0,\"byteOffset\":{idx_off},\"byteLength\":{},\"target\":34963}}", idx.len() * 4)); + views.push_str(&format!(",{{\"buffer\":0,\"byteOffset\":{nrm_off},\"byteLength\":{},\"target\":34962}}", nrm.len() * 4)); push_sep(&mut accessors, n_acc); // min/max als exakter Wert des f32 (der Prüfer vergleicht mit den Daten). accessors.push_str(&format!( @@ -401,6 +538,7 @@ fn build_gltf(s: &Scene, uri_for_buffer: bool) -> (String, Vec) { n_views + 1, idx.len() )); + accessors.push_str(&format!(",{{\"bufferView\":{},\"componentType\":5126,\"count\":{},\"type\":\"VEC3\"}}", n_views + 2, nrm.len() / 3)); let material = if *mat >= 0 { *mat as usize } else { @@ -409,11 +547,12 @@ fn build_gltf(s: &Scene, uri_for_buffer: bool) -> (String, Vec) { }; push_sep(&mut meshes, k); meshes.push_str(&format!( - "{{\"attributes\":{{\"POSITION\":{n_acc}}},\"indices\":{},\"material\":{material},\"mode\":4}}", + "{{\"attributes\":{{\"POSITION\":{n_acc},\"NORMAL\":{}}},\"indices\":{},\"material\":{material},\"mode\":4}}", + n_acc + 2, n_acc + 1 )); - n_views += 2; - n_acc += 2; + n_views += 3; + n_acc += 3; } meshes.push_str("]}"); nodes.push_str("{\"name\":"); @@ -505,8 +644,13 @@ fn build_gltf(s: &Scene, uri_for_buffer: bool) -> (String, Vec) { // ── Öffentliche Schreiber ─────────────────────────────────────────────────── /// OBJ-Text aus der flachen Szene. -pub fn export_obj(flat: &[f64], strings: &str) -> Result { - Ok(write_obj(&parse(flat, strings)?)) +pub fn export_obj(flat: &[f64], strings: &str, mtl_name: &str) -> Result { + Ok(write_obj(&parse(flat, strings)?, mtl_name)) +} + +/// MTL-Datei (Farben) zum OBJ aus derselben Szene. +pub fn export_mtl(flat: &[f64], strings: &str) -> Result { + Ok(write_mtl(&parse(flat, strings)?)) } /// ASCII-STL aus der flachen Szene. @@ -558,10 +702,16 @@ pub fn export_glb(flat: &[f64], strings: &str) -> Result, String> { mod wasm { use wasm_bindgen::prelude::*; - /// Flache Szene → OBJ-Text; leer bei kaputtem Puffer. + /// Flache Szene → OBJ-Text; leer bei kaputtem Puffer. `mtl_name` = Dateiname der MTL (`mtllib`), leer = keine. #[wasm_bindgen] - pub fn export_mesh_obj_flat(flat: &[f64], strings: &str) -> String { - super::export_obj(flat, strings).unwrap_or_default() + pub fn export_mesh_obj_flat(flat: &[f64], strings: &str, mtl_name: &str) -> String { + super::export_obj(flat, strings, mtl_name).unwrap_or_default() + } + + /// Flache Szene → MTL-Text (Farben zum OBJ); leer bei kaputtem Puffer. + #[wasm_bindgen] + pub fn export_mesh_mtl_flat(flat: &[f64], strings: &str) -> String { + super::export_mtl(flat, strings).unwrap_or_default() } /// Flache Szene → ASCII-STL; leer bei kaputtem Puffer. @@ -649,12 +799,64 @@ mod tests { #[test] fn obj_aufbau() { let (n, s) = scene(true); - let obj = export_obj(&n, &s).unwrap(); + let obj = export_obj(&n, &s, "").unwrap(); assert!(obj.starts_with("# DOSSIER OBJ-Export")); assert!(obj.contains("o Wand_W1\nv 0.0 0.0 0.0\nv 1.0 0.0 0.0\n")); // Zweite Gruppe: Indizes global (8 Vertices davor, 1-basiert). Rechtshändig: Z gespiegelt, Wicklung vertauscht. - assert!(obj.contains("o Decke_D\"1\nv 0.0 2.5 0.0\nv 1.0 2.5 0.0\nv 0.0 2.5 -1.0\nf 9 11 10\n"), "{obj}"); + // Normale der Decke (Dreiecks-Normale in Szene-Achsen (0,-1,0), Spiegelung von z ändert sie nicht); davor 6 Würfel-Normalen (flach, 90° > Knickwinkel), daher Index 7. + assert!(obj.contains("o Decke_D\"1\nv 0.0 2.5 0.0\nv 1.0 2.5 0.0\nv 0.0 2.5 -1.0\nvn 0.0 -1.0 0.0\nusemtl Standard\nf 9//7 11//7 10//7\n"), "{obj}"); assert_eq!(obj.matches("\nf ").count(), 13); + // Ohne MTL-Datei: Farben als Kommentar, Gruppen je Material. + assert!(obj.contains("# Beton: Kd 0.8 0.8 0.8 d 1.0\n") && obj.contains("usemtl Beton\n") && !obj.contains("mtllib"), "{obj}"); + // Jede Fläche trägt Normale; Würfel: genau 6 verschiedene `vn`. + assert_eq!(obj.split("o Decke").next().unwrap().matches("\nvn ").count(), 6); + } + + #[test] + fn obj_mit_mtl() { + let (n, s) = scene(true); + let obj = export_obj(&n, &s, "haus.mtl").unwrap(); + assert!(obj.contains("\nmtllib haus.mtl\n") && !obj.contains("# Beton: Kd"), "{obj}"); + let mtl = export_mtl(&n, &s).unwrap(); + assert!(mtl.contains("\nnewmtl Beton\nKa 0 0 0\nKd 0.8 0.8 0.8\nKs 0 0 0\nd 1.0\nillum 2\n"), "{mtl}"); + assert!(mtl.contains("\nnewmtl Standard\n"), "{mtl}"); + } + + #[test] + fn normalen_im_gltf_flach_und_geteilt() { + // Würfel: scharfe Kanten (90°) ⇒ 24 Eckpunkte, Normalen = Einheitsachsen, passend zur geschriebenen Wicklung. + let (n, s) = scene(false); + let (json, bin) = build_gltf(&parse(&n, &s).unwrap(), false); + assert!(json.contains(r#""NORMAL":2"#), "{json}"); + let f = |o: usize| f32::from_le_bytes(bin[o..o + 4].try_into().unwrap()); + let idx = |o: usize| u32::from_le_bytes(bin[o..o + 4].try_into().unwrap()) as usize; + // Gruppe 1: 24 Positionen (288 B), 36 Indizes (144 B), dann 24 Normalen. + let (pos0, idx0, nrm0) = (0, 24 * 12, 24 * 12 + 36 * 4); + let at = |base: usize, v: usize| [f(base + v * 12), f(base + v * 12 + 4), f(base + v * 12 + 8)]; + for v in 0..24 { + let n = at(nrm0, v); + assert!((n.iter().map(|x| x * x).sum::() - 1.0).abs() < 1e-5 && n.iter().filter(|x| x.abs() > 0.99).count() == 1, "{n:?}"); + } + for t in 0..12 { + let (a, b, c) = (idx(idx0 + t * 12), idx(idx0 + t * 12 + 4), idx(idx0 + t * 12 + 8)); + let (pa, pb, pc) = (at(pos0, a), at(pos0, b), at(pos0, c)); + let (u, w) = ([pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]], [pc[0] - pa[0], pc[1] - pa[1], pc[2] - pa[2]]); + let cross = [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]]; + for v in [a, b, c] { + let n = at(nrm0, v); + assert!(cross[0] * n[0] + cross[1] * n[1] + cross[2] * n[2] > 0.0, "Dreieck {t}: Normale gegen die Wicklung"); + } + } + // Leicht geknickte Fläche (zwei Dreiecke, ~6° Knick < Knickwinkel) ⇒ geteilte Normalen: 4 statt 6 Eckpunkte. + let mut f2 = Flat::default(); + let (g, k, i) = (f2.s("Wand_X"), f2.s("wall"), f2.s("X")); + f2.nums = vec![FLAT_VERSION, 0.0, 0.0, 0.0, 1.0, g, k, i, -1.0, 1.0, -1.0, 4.0]; + f2.nums.extend([0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.1]); + f2.nums.extend([2.0, 0.0, 1.0, 2.0, 1.0, 3.0, 2.0]); + let (n2, s2) = f2.args(); + let (json2, _) = build_gltf(&parse(&n2, &s2).unwrap(), false); + assert!(json2.contains(r#""count":4,"type":"VEC3","min""#), "{json2}"); + assert!(json2.contains(r#""count":4,"type":"VEC3"}"#), "{json2}"); } #[test] @@ -696,8 +898,8 @@ mod tests { let (n, s) = scene(true); let glb = export_glb(&n, &s).unwrap(); let (json, bl) = json_of_glb(&glb); - // Puffer: (8 + 3) Vertices je 12 B + (36 + 3) Indizes je 4 B. - assert_eq!(bl, (8 + 3) * 12 + (36 + 3) * 4); + // Puffer: Würfel mit scharfen Kanten = 24 Eckpunkte + 3 des Dreiecks, je Position + Normale 24 B; (36 + 3) Indizes je 4 B. + assert_eq!(bl, (24 + 3) * 24 + (36 + 3) * 4); assert!(json.contains(&format!("\"byteLength\":{bl}"))); // Knoten 0/1 = Bauteile, Knoten 2 = Geschoss mit Kind 0; Decke (ohne Geschoss) bleibt an der Wurzel. assert!(json.contains("\"scenes\":[{\"nodes\":[2,1]}]"), "{json}"); @@ -728,7 +930,7 @@ mod tests { let (json, bl) = json_of_glb(&glb); assert_eq!(bl, 0); assert!(json.trim_end().ends_with("\"scene\":0,\"scenes\":[{}]}"), "{json}"); - assert_eq!(export_obj(&n, "").unwrap().lines().count(), 5); + assert_eq!(export_obj(&n, "", "").unwrap().lines().count(), 7); assert_eq!(export_stl(&n, "").unwrap(), "solid dossier\nendsolid dossier\n"); } @@ -756,14 +958,14 @@ mod tests { for bad in [f64::NAN, f64::INFINITY, -1.0, 1e12, 0.5] { let mut m = n.clone(); m[pos] = bad; - let _ = export_obj(&m, &s); + let _ = export_obj(&m, &s, ""); let _ = export_stl(&m, &s); let _ = export_glb(&m, &s); let _ = export_gltf(&m, &s); } } - assert!(export_obj(&n, "").is_err()); - assert!(export_obj(&[], "").is_err()); + assert!(export_obj(&n, "", "").is_err()); + assert!(export_obj(&[], "", "").is_err()); } #[test] diff --git a/src-tauri/fileio/src/mesh_import_tests.rs b/src-tauri/fileio/src/mesh_import_tests.rs index be695450..c6b09d24 100644 --- a/src-tauri/fileio/src/mesh_import_tests.rs +++ b/src-tauri/fileio/src/mesh_import_tests.rs @@ -150,7 +150,7 @@ fn rundreise_gltf_data_uri() { #[test] fn rundreise_obj_y_up_aus_kopf() { let (f, s) = flat(&two_boxes()); - let obj = export_obj(&f, &s).expect("obj"); + let obj = export_obj(&f, &s, "").expect("obj"); let m = import_mesh(obj.as_bytes(), "x.obj", &opts()).expect("import"); assert_eq!(m.format, Format::Obj); assert_eq!(m.up_used, Up::Y); @@ -177,7 +177,7 @@ fn rundreise_stl_achse_aus_ausdehnung() { #[test] fn einheit_skaliert_ausser_gltf() { let (f, s) = flat(&two_boxes()); - let obj = export_obj(&f, &s).expect("obj"); + let obj = export_obj(&f, &s, "").expect("obj"); let m = import_mesh(obj.as_bytes(), "x.obj", &Options { unit_scale: 0.001, ..opts() }).expect("import"); let v: f64 = m.objects.iter().map(volume).sum(); assert!((v - 61.0e-9).abs() < 1e-12, "{v}"); @@ -496,7 +496,7 @@ fn gltf_draco_abgelehnt() { fn dreiecksbudget() { let (p, t) = cuboid(0.0, 0.0, 0.0, 1.0, 1.0, 1.0); let (f, s) = flat(&[G { name: "K", rgba: None, pos: p, tris: t }]); - let obj = export_obj(&f, &s).expect("obj"); + let obj = export_obj(&f, &s, "").expect("obj"); let m = import_mesh(obj.as_bytes(), "x.obj", &Options { max_triangles: 5, ..opts() }).expect("import"); assert!(m.truncated); assert_eq!(m.triangles, 5); @@ -531,7 +531,7 @@ fn kaputte_dateien_ohne_panic() { } let (p, t) = cuboid(0.0, 0.0, 0.0, 1.0, 1.0, 1.0); let (f, s) = flat(&[G { name: "K", rgba: Some([0.5; 4]), pos: p, tris: t }]); - let obj = export_obj(&f, &s).expect("obj"); + let obj = export_obj(&f, &s, "").expect("obj"); for n in 0..obj.len() { let _ = import_mesh(&obj.as_bytes()[..n], "x.obj", &opts()); } diff --git a/src-tauri/hatchgen/src/lib.rs b/src-tauri/hatchgen/src/lib.rs index 1825c9fd..0448d6d3 100644 --- a/src-tauri/hatchgen/src/lib.rs +++ b/src-tauri/hatchgen/src/lib.rs @@ -1,9 +1,11 @@ //! Schraffur-Generator ([109]): `hatch` (Linien-, Schicht-, Streumuster), `jsnum`/`jsmath` (JS-Zahlsemantik); -//! `section_dominance` (Schnitt-Dominanz der Schnittbänder, [125]) und `ugrid` (Bereichs-Vorauswahl). +//! `section_dominance` (Schnitt-Dominanz der Schnittbänder, [125]), `ugrid` (Bereichs-Vorauswahl) und `mesh_normals` +//! (geteilte Ecken-Normalen, [T4]/[201]: 3D-Anzeige und glTF/OBJ-Export in `fileio`). //! Gemeinsam genutzt von `dossier-core` (Re-Export unter `crate::hatch` usw.) und `render3d` (Live-Schnitt). pub mod hatch; pub mod jsmath; pub mod jsnum; +pub mod mesh_normals; pub mod section_dominance; pub mod ugrid; diff --git a/src-tauri/hatchgen/src/mesh_normals.rs b/src-tauri/hatchgen/src/mesh_normals.rs new file mode 100644 index 00000000..c0a7ab03 --- /dev/null +++ b/src-tauri/hatchgen/src/mesh_normals.rs @@ -0,0 +1,64 @@ +//! Geteilte Ecken-Normalen eines Dreiecksnetzes ([T4], verschoben aus `render3d/src/mesh.rs` [201]): EINE Funktion für die +//! 3D-Anzeige (`render3d`, glatt schattierte Netzkörper) und die Mesh-Exporte (`fileio/mesh_export.rs`, glTF/OBJ-Normalen). + +/// [T4] Geteilte Normalen ("split normals") je Dreiecks-Ecke: Summe der flaechengewichteten Normalen +/// aller Dreiecke an derselben Lage (verschweisst ueber die Lage, 0.01 mm Raster), deren Normale um +/// hoechstens `crease_deg` von der des Dreiecks abweicht. Entartete Dreiecke/kaputte Indizes: `None`. +pub fn smooth_corner_normals(indices: &[u32], vcount: usize, vworld: &dyn Fn(usize) -> [f32; 3], crease_deg: f32) -> Vec> { + use std::collections::HashMap; + let key = |p: [f32; 3]| [(p[0] as f64 * 1e5).round() as i64, (p[1] as f64 * 1e5).round() as i64, (p[2] as f64 * 1e5).round() as i64]; + let mut weld: HashMap<[i64; 3], usize> = HashMap::new(); + let mut id = vec![usize::MAX; vcount]; + for (i, slot) in id.iter_mut().enumerate() { + let n = weld.len(); + *slot = *weld.entry(key(vworld(i))).or_insert(n); + } + let tris: Vec> = indices + .chunks_exact(3) + .map(|t| { + let v = [t[0] as usize, t[1] as usize, t[2] as usize]; + if v.iter().any(|&i| i >= vcount) { + return None; + } + let (a, b, c) = (vworld(v[0]), vworld(v[1]), vworld(v[2])); + let ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + let ac = [c[0] - a[0], c[1] - a[1], c[2] - a[2]]; + let g = [ab[1] * ac[2] - ab[2] * ac[1], ab[2] * ac[0] - ab[0] * ac[2], ab[0] * ac[1] - ab[1] * ac[0]]; + let l = (g[0] * g[0] + g[1] * g[1] + g[2] * g[2]).sqrt(); + (l >= 1e-12 && l.is_finite()).then(|| ([id[v[0]], id[v[1]], id[v[2]]], g, [g[0] / l, g[1] / l, g[2] / l])) + }) + .collect(); + let mut around: Vec> = vec![Vec::new(); weld.len()]; + for (k, t) in tris.iter().enumerate() { + if let Some((w, _, _)) = t { + for &v in w { + if around[v].last() != Some(&k) { + around[v].push(k); + } + } + } + } + let cos = crease_deg.min(180.0).to_radians().cos() - 1e-6; + tris.iter() + .map(|t| { + let (w, _, nt) = t.as_ref()?; + let corner = |v: usize| { + let mut s = [0.0f32; 3]; + for &f in &around[v] { + if let Some((_, g, nf)) = &tris[f] { + if nf[0] * nt[0] + nf[1] * nt[1] + nf[2] * nt[2] >= cos { + s = [s[0] + g[0], s[1] + g[1], s[2] + g[2]]; + } + } + } + let l = (s[0] * s[0] + s[1] * s[1] + s[2] * s[2]).sqrt(); + if l > 1e-20 && l.is_finite() { + [s[0] / l, s[1] / l, s[2] / l] + } else { + *nt + } + }; + Some([corner(w[0]), corner(w[1]), corner(w[2])]) + }) + .collect() +} diff --git a/src-tauri/render3d/src/mesh.rs b/src-tauri/render3d/src/mesh.rs index 1eab079e..da1c6fac 100644 --- a/src-tauri/render3d/src/mesh.rs +++ b/src-tauri/render3d/src/mesh.rs @@ -1472,7 +1472,7 @@ pub fn append_context_mesh(mesh: &mut Mesh, input: &MeshInput) { } }; // [T4] Glatt: Ecken-Normalen je Dreieck (sonst kantig mit der Flaechennormale). - let smooth = input.crease_angle.filter(|a| a.is_finite() && *a > 0.0).map(|a| smooth_corner_normals(&input.indices, vcount, &vworld, a)); + let smooth = input.crease_angle.filter(|a| a.is_finite() && *a > 0.0).map(|a| dossier_hatch::mesh_normals::smooth_corner_normals(&input.indices, vcount, &vworld, a)); for (k, t) in input.indices.chunks_exact(3).enumerate() { let (ia, ib, ic) = (t[0] as usize, t[1] as usize, t[2] as usize); // Fehlerhafte Indizes robust ueberspringen (kein Panic bei kaputter Eingabe). @@ -1508,68 +1508,6 @@ pub fn append_context_mesh(mesh: &mut Mesh, input: &MeshInput) { } } -/// [T4] Geteilte Normalen ("split normals") je Dreiecks-Ecke: Summe der flaechengewichteten Normalen -/// aller Dreiecke an derselben Lage (verschweisst ueber die Lage, 0.01 mm Raster), deren Normale um -/// hoechstens `crease_deg` von der des Dreiecks abweicht. Entartete Dreiecke/kaputte Indizes: `None`. -fn smooth_corner_normals(indices: &[u32], vcount: usize, vworld: &dyn Fn(usize) -> [f32; 3], crease_deg: f32) -> Vec> { - use std::collections::HashMap; - let key = |p: [f32; 3]| [(p[0] as f64 * 1e5).round() as i64, (p[1] as f64 * 1e5).round() as i64, (p[2] as f64 * 1e5).round() as i64]; - let mut weld: HashMap<[i64; 3], usize> = HashMap::new(); - let mut id = vec![usize::MAX; vcount]; - for (i, slot) in id.iter_mut().enumerate() { - let n = weld.len(); - *slot = *weld.entry(key(vworld(i))).or_insert(n); - } - let tris: Vec> = indices - .chunks_exact(3) - .map(|t| { - let v = [t[0] as usize, t[1] as usize, t[2] as usize]; - if v.iter().any(|&i| i >= vcount) { - return None; - } - let (a, b, c) = (vworld(v[0]), vworld(v[1]), vworld(v[2])); - let ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; - let ac = [c[0] - a[0], c[1] - a[1], c[2] - a[2]]; - let g = [ab[1] * ac[2] - ab[2] * ac[1], ab[2] * ac[0] - ab[0] * ac[2], ab[0] * ac[1] - ab[1] * ac[0]]; - let l = (g[0] * g[0] + g[1] * g[1] + g[2] * g[2]).sqrt(); - (l >= 1e-12 && l.is_finite()).then(|| ([id[v[0]], id[v[1]], id[v[2]]], g, [g[0] / l, g[1] / l, g[2] / l])) - }) - .collect(); - let mut around: Vec> = vec![Vec::new(); weld.len()]; - for (k, t) in tris.iter().enumerate() { - if let Some((w, _, _)) = t { - for &v in w { - if around[v].last() != Some(&k) { - around[v].push(k); - } - } - } - } - let cos = crease_deg.min(180.0).to_radians().cos() - 1e-6; - tris.iter() - .map(|t| { - let (w, _, nt) = t.as_ref()?; - let corner = |v: usize| { - let mut s = [0.0f32; 3]; - for &f in &around[v] { - if let Some((_, g, nf)) = &tris[f] { - if nf[0] * nt[0] + nf[1] * nt[1] + nf[2] * nt[2] >= cos { - s = [s[0] + g[0], s[1] + g[1], s[2] + g[2]]; - } - } - } - let l = (s[0] * s[0] + s[1] * s[1] + s[2] * s[2]).sqrt(); - if l > 1e-20 && l.is_finite() { - [s[0] / l, s[1] / l, s[2] / l] - } else { - *nt - } - }; - Some([corner(w[0]), corner(w[1]), corner(w[2])]) - }) - .collect() -} - /// Wie [`push_ctx_tri`], mit einer Normale je Ecke ([T4] glatt). fn push_ctx_tri_n(mesh: &mut Mesh, p: [[f32; 3]; 3], n: [[f32; 3]; 3], colors: [Rgb; 3]) { let base = (mesh.verts.len() / FLOATS_PER_VERTEX) as u32; diff --git a/src/cli/main.ts b/src/cli/main.ts index e7436302..eb152a45 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -20,7 +20,7 @@ // --hide blendet Klassen aus (z. B. --hide "Schatten,Auto-Bemassung") [180] // dossier-cli ifc [--ebkph] [--ebenen] (IFC mit eBKP-H-Hauptgruppen bzw. Modell-Ebenen als Klassifikation) // --schema 4|2x3: IFC4 (Standard) oder IFC2x3 (Coordination View 2.0) -// dossier-cli dxf [--binary] [--scale 100] [--dim-unit cm] [--layout]|dwg|ifc|step|obj|stl|glb|gltf|schedule [--openings|--elements|--rooms] [--format json|csv|svg|pdf]|kennzahlen [--sia416] [--ivhb] [--format json|csv|svg|pdf] [--agsf m2] [--gruenflaeche m2] [--agf-basis gf|ngf|nf] [--untergeschosse]|raumprogramm [--import tabelle] [--sheet name|nr] [--mode replace|append] [--tolerance %] [--generate] [--format json|csv|svg|pdf] [--save projekt.obp]|sun [--level EG] [--out datei] +// dossier-cli dxf [--binary] [--scale 100] [--dim-unit cm] [--layout]|dwg|ifc|step|obj [--no-mtl]|stl|glb|gltf|schedule [--openings|--elements|--rooms] [--format json|csv|svg|pdf]|kennzahlen [--sia416] [--ivhb] [--format json|csv|svg|pdf] [--agsf m2] [--gruenflaeche m2] [--agf-basis gf|ngf|nf] [--untergeschosse]|raumprogramm [--import tabelle] [--sheet name|nr] [--mode replace|append] [--tolerance %] [--generate] [--format json|csv|svg|pdf] [--save projekt.obp]|sun [--level EG] [--out datei] // glb/gltf = glTF 2.0 (Y-up, Meter, Geschoss als Eltern; --flat ohne Geschoss-Knoten) // dossier-cli convert [--cmd "befehl"]… Format nach Endung: dxf/dwg/ifc/obp → obp-Import, // obp → dxf/dwg/ifc/obj/stl/glb/gltf/step; --cmd: weitere Befehle @@ -50,7 +50,7 @@ // WASM-Pakete (src/engine/pkg*) werden aus DOSSIER_WASM_DIR bzw. `/src/engine` gelesen. import { readFileSync, writeFileSync } from "node:fs"; -import { dirname, join, resolve } from "node:path"; +import { basename, dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { buildPlanDxf, @@ -70,6 +70,7 @@ import { computeSection, exportIfcSpf, exportObj, + exportMtl, exportProjectStep, exportScheduleCsv, computeKennzahlen, @@ -441,7 +442,7 @@ export async function run(argv: string[]): Promise { if (file === "mcp" && args.flags.has("app")) return runAppBridge(args); if (!file || (!command && args.cmds.length === 0)) { process.stderr.write( - "Aufruf: dossier-cli [Optionen]\n" + + "Aufruf: dossier-cli [Optionen]\n" + " dossier-cli convert [--cmd \"befehl …\"]…\n" + " dossier-cli --cmd \"befehl …\" [--cmd …] ({last} = zuletzt geschriebene Datei)\n" + " dossier-cli pointcloud-info [--voxel 0.05] [--max 2000000]\n" + @@ -786,7 +787,19 @@ async function execute(project: Project, file: string, command: string, rest: st return 0; case "obj": await loadFileio(); - out(args, exportObj(project), `${project.name || "projekt"}.obj`); + // [201] Mit MTL (Farben) daneben: `--out haus.obj` schreibt auch `haus.mtl`; `--out -` oder `--no-mtl`: nur das OBJ + // (Farben dann als Kommentar im Kopf). + { + const target = args.flags.get("out") ?? `${project.name || "projekt"}.obj`; + if (target === "-" || args.flags.has("no-mtl")) { + out(args, exportObj(project), `${project.name || "projekt"}.obj`); + } else { + const mtlPath = target.replace(/\.obj$/i, "") + ".mtl"; + out(args, exportObj(project, {}, basename(mtlPath)), target); + writeFileSync(mtlPath, exportMtl(project)); + process.stderr.write(`geschrieben: ${mtlPath}\n`); + } + } return 0; case "stl": await loadFileio(); diff --git a/src/core/extra.ts b/src/core/extra.ts index 51968334..3175de05 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -13,7 +13,7 @@ export { projectGeoOrigin } from "../model/geoRebase"; export { ensureContextCategories } from "../model/contextCategories"; export { projectToWorldCoords } from "../model/geoRebase"; export { exportScheduleCsv } from "../export/exportSchedule"; -export { exportObj, exportStl, exportGlb, exportGltf } from "../export/exportMesh"; +export { exportObj, exportMtl, exportStl, exportGlb, exportGltf } from "../export/exportMesh"; export { exportProjectStep } from "../export/exportStep"; export { planToSvgString } from "../export/planToSvgString"; export { setWasmBytesProvider } from "../engine/wasmSource"; diff --git a/src/export/exportGltf.test.ts b/src/export/exportGltf.test.ts index a93ec5e3..3bc9045f 100644 --- a/src/export/exportGltf.test.ts +++ b/src/export/exportGltf.test.ts @@ -3,7 +3,7 @@ import { describe, it, expect } from "vitest"; import "../engine/fileioWasm.setup"; import validator from "gltf-validator"; -import { exportGlb, exportGltf, exportObj } from "./exportMesh"; +import { exportGlb, exportGltf, exportMtl, exportObj } from "./exportMesh"; import { sampleProject } from "../model/sampleProject"; interface Gltf { @@ -83,3 +83,39 @@ describe("glTF-Export", () => { expect(g.materials.some((m) => names.includes(m.name))).toBe(true); }); }); + +describe("[201] Normalen und MTL", () => { + it("jede Primitive trägt NORMAL (gleiche Anzahl wie POSITION); Validator ohne Meldung zu Normalen", async () => { + const glb = exportGlb(sampleProject); + const g = glbJson(glb) as Gltf & { meshes: { primitives: { attributes: { POSITION: number; NORMAL?: number } }[] }[] }; + for (const m of g.meshes) { + for (const p of m.primitives) { + expect(p.attributes.NORMAL).toBeDefined(); + expect(g.accessors[p.attributes.NORMAL!].count).toBe(g.accessors[p.attributes.POSITION].count); + expect(g.accessors[p.attributes.NORMAL!].type).toBe("VEC3"); + } + } + const report = await validator.validateBytes(glb, { maxIssues: 200 }); + const normalIssues = report.issues.messages.filter((m) => /NORMAL|normal/.test(m.code + m.message)); + expect(normalIssues).toEqual([]); + }); + + it("OBJ: vn zu jeder Fläche, usemtl je Material, mtllib nur mit MTL; MTL nennt jedes verwendete Material", () => { + const withMtl = exportObj(sampleProject, {}, "haus.mtl"); + const lines = withMtl.split("\n"); + expect(lines).toContain("mtllib haus.mtl"); + const faces = lines.filter((l) => l.startsWith("f ")); + expect(lines.filter((l) => l.startsWith("vn ")).length).toBeGreaterThan(0); + for (const f of faces) expect(f).toMatch(/^f \d+\/\/\d+ \d+\/\/\d+ \d+\/\/\d+$/); + const used = new Set(lines.filter((l) => l.startsWith("usemtl ")).map((l) => l.slice(7))); + expect(used.size).toBeGreaterThan(1); + const mtl = exportMtl(sampleProject); + const defined = new Set(mtl.split("\n").filter((l) => l.startsWith("newmtl ")).map((l) => l.slice(7))); + for (const u of used) expect(defined.has(u), u).toBe(true); + expect(mtl).toMatch(/\nKd [\d.]+ [\d.]+ [\d.]+\n/); + // Ohne MTL: keine mtllib, Farben im Kopf als Kommentar. + const plain = exportObj(sampleProject); + expect(plain).not.toContain("mtllib"); + expect(plain).toMatch(/\n# \S+: Kd /); + }); +}); diff --git a/src/export/exportIfc.validate.test.ts b/src/export/exportIfc.validate.test.ts index 38d5e206..9d9226cc 100644 --- a/src/export/exportIfc.validate.test.ts +++ b/src/export/exportIfc.validate.test.ts @@ -10,7 +10,7 @@ import { join } from "node:path"; import "../engine/fileioWasm.setup"; import { exportIfcSpf, ifcGuid } from "./exportIfc"; import { wallMeshVolumes } from "./meshScene.testutil"; -import { sampleProject } from "../model/sampleProject"; +import { emptyProject, sampleProject } from "../model/sampleProject"; import { buildComplexSampleProject } from "../model/sampleProjectComplex"; import type { Project } from "../model/types"; @@ -164,6 +164,15 @@ describe.skipIf(!hasIfcOpenShell)("IFC-Export gegen ifcopenshell", { timeout: 60 expect(r.out).toContain("0 Befunde"); expect(r.status).toBe(0); }); + it("[201] Import → Export mit übernommenen GlobalIds: gültig (22 Zeichen, keine doppelten)", async () => { + const { importIfcInto } = await import("../io/importView.testutil"); + const first = (await importIfcInto(emptyProject, new TextEncoder().encode(exportIfcSpf(sampleProject)), { elements: true })).project; + const ifc = exportIfcSpf(first); + expect(ifc).toContain(`'${first.walls[0].ifcGlobalId}'`); + const r = validate("globalid-rundreise", ifc); + expect(r.out).toContain("0 Befunde"); + expect(r.status).toBe(0); + }, 240_000); it("[191] Decken/Räume mit Bogenkanten: IfcCompositeCurve mit IfcTrimmedCurve, gültig", () => { const ifc = exportIfcSpf(buildComplexSampleProject()); expect(ifc).toContain("IFCCOMPOSITECURVE("); diff --git a/src/export/exportMesh.complete.test.ts b/src/export/exportMesh.complete.test.ts index 4d460fdb..7b8ca5d8 100644 --- a/src/export/exportMesh.complete.test.ts +++ b/src/export/exportMesh.complete.test.ts @@ -86,7 +86,7 @@ function objVolumes(obj: string): Map { cur = l.slice(2).trim(); out.set(cur, 0); } else if (l.startsWith("f ")) { - const [a, b, c] = l.slice(2).trim().split(/\s+/).map((i) => verts[Number(i) - 1]); + const [a, b, c] = l.slice(2).trim().split(/\s+/).map((i) => verts[Number(i.split("/")[0]) - 1]); // [201]: `v//vn` const v = a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0]); out.set(cur, (out.get(cur) ?? 0) + v / 6); diff --git a/src/export/exportMesh.test.ts b/src/export/exportMesh.test.ts index 2486b9a2..2c12b3e9 100644 --- a/src/export/exportMesh.test.ts +++ b/src/export/exportMesh.test.ts @@ -164,7 +164,7 @@ function parseObjFaces(obj: string): number[][] { return obj .split("\n") .filter((l) => l.startsWith("f ")) - .map((l) => l.slice(2).trim().split(/\s+/).map(Number)); + .map((l) => l.slice(2).trim().split(/\s+/).map((t) => Number(t.split("/")[0]))); // [201]: `v//vn` } describe("exportObj — Wavefront-OBJ-Export", () => { diff --git a/src/export/exportMesh.ts b/src/export/exportMesh.ts index 86d600a8..14edaa31 100644 --- a/src/export/exportMesh.ts +++ b/src/export/exportMesh.ts @@ -38,10 +38,17 @@ function write(project: Project, opts: MeshOption * Baut einen vollständigen Wavefront-OBJ-String des 3D-Gebäudemodells (Meter, Y-up rechtshändig: * Modell (x, y, z-hoch) → (x, z, −y)). Ein `o`-Objekt je Bauteil-Vorkommen (Wand, Decke, Extrusion, Dach, * Treppe, Stütze, Fenster/Tür, Kontext-Mesh). Leeres Projekt ⇒ gültige Datei nur mit Kopf-Kommentaren. - * Verlangt das geladene Format-Modul (`await loadFileio()`). + * Mit Normalen (`vn`, geteilt bis 30° Knickwinkel wie die 3D-Anzeige) und `usemtl` je Material ([201]). `mtlName` = + * Dateiname der MTL daneben (`mtllib`, Datei von {@link exportMtl}); leer ⇒ ohne MTL, die Farben stehen dann als + * Kommentar im Kopf. Verlangt das geladene Format-Modul (`await loadFileio()`). */ -export function exportObj(project: Project, opts: MeshOptions = {}): string { - return write(project, opts, false, (m, b, s) => m.export_mesh_obj_flat(b, s)); +export function exportObj(project: Project, opts: MeshOptions = {}, mtlName = ""): string { + return write(project, opts, false, (m, b, s) => m.export_mesh_obj_flat(b, s, mtlName)); +} + +/** MTL-Datei mit den Farben (`Kd`, Deckkraft `d`) der OBJ-Materialien aus {@link exportObj} ([201]). */ +export function exportMtl(project: Project, opts: MeshOptions = {}): string { + return write(project, opts, false, (m, b, s) => m.export_mesh_mtl_flat(b, s)); } /** @@ -63,7 +70,8 @@ export interface GltfOptions extends MeshOptions { * glTF 2.0 binär (GLB) für Blender, Twinmotion, Enscape, Web-Viewer. Ein Knoten je Bauteil (Name * `Wand_`, `Decke_`, `Dach_`, `Treppe_`, `Stuetze_`, `Fenster_`, `Tuer_`, * `Extrusion_`, `Kontext_`, `Gelaende_`; `extras` = Typ + id), PBR-Materialien mit der - * Farbe der Bauteilschicht, Verglasung transparent (`BLEND`), Geschosse als Eltern-Knoten. Meter; + * Farbe der Bauteilschicht, Verglasung transparent (`BLEND`), `NORMAL` je Ecke (geteilt bis 30° Knickwinkel wie die + * 3D-Anzeige, scharfe Kanten bleiben kantig), Geschosse als Eltern-Knoten. Meter; * rechtshändig, Y-up: Modell (x, y, z-hoch) → (x, z, −y), Norden = −Z. Verlangt das geladene * Format-Modul (`await loadFileio()`). */ diff --git a/src/io/bcf.test.ts b/src/io/bcf.test.ts index 6f6080ba..76fccb9e 100644 --- a/src/io/bcf.test.ts +++ b/src/io/bcf.test.ts @@ -121,6 +121,17 @@ describe("BCF-GlobalId-Zuordnung", () => { expect(resolveGuids(sampleProject, [g]).selection.wallIds).toEqual([w.id]); }); + it("[201] Bauteil mit übernommener ifcGlobalId: sie gilt statt der abgeleiteten (beide Richtungen)", () => { + const own = "2O2Fr$t4X7Zf8NOew3FLOH"; + const p = { ...sampleProject, walls: sampleProject.walls.map((w, i) => (i === 0 ? { ...w, ifcGlobalId: own } : w)) } as Project; + const w = p.walls[0]; + expect(resolveGuids(p, [own]).selection.wallIds).toEqual([w.id]); + expect(resolveGuids(p, [ifcGuid(`${p.id}/wall/${w.id}`)]).missing).toHaveLength(1); + const sel = emptyBcfSelection(); + sel.wallIds = [w.id]; + expect(selectionToGuids(p, sel)).toEqual([own]); + }); + it("unbekannte GUIDs werden gemeldet", () => { const r = resolveGuids(sampleProject, ["0000000000000000000000", ifcGuid(`${sampleProject.id}/wall/${sampleProject.walls[0].id}`)]); expect(r.missing).toEqual(["0000000000000000000000"]); diff --git a/src/io/bcfMatch.ts b/src/io/bcfMatch.ts index e9cb5d65..f0ba1712 100644 --- a/src/io/bcfMatch.ts +++ b/src/io/bcfMatch.ts @@ -2,7 +2,8 @@ // // Dieselbe Ableitung wie der IFC-Export (`exportIfc.ts`/`ifc_export/mod.rs`: `ifcGuid("//")`), // damit die Rundreise Dossier → IFC → Solibri → BCF → Dossier trifft. Importierte Meshes tragen die -// GlobalId ihres Quell-Bauteils (`ImportedMesh.ifcGlobalId`). Bauteile, die im Export nicht vorkommen +// GlobalId ihres Quell-Bauteils (`ImportedMesh.ifcGlobalId`); erkannte Bauteile des IFC-Imports ebenso (`ifcGlobalId`, +// [201]: der Export schreibt sie zurück, sie gilt statt der abgeleiteten). Bauteile, die im Export nicht vorkommen // (2D-Zeichnungen, Gruppen), haben keine GlobalId. import type { BcfViewpoint } from "./bcf"; @@ -49,17 +50,21 @@ interface Target { export function buildGuidIndex(project: Project): Map { const index = new Map(); const pid = project.id; - const add = (key: string, channel: BcfChannel, id: string) => index.set(ifcGuid(`${pid}/${key}/${id}`), { channel, id }); - for (const w of project.walls ?? []) add("wall", "wallIds", w.id); - for (const c of project.ceilings ?? []) add("slab", "ceilingIds", c.id); - for (const r of project.roofs ?? []) add("roof", "roofIds", r.id); - for (const c of project.columns ?? []) add("column", "columnIds", c.id); - for (const s of project.stairs ?? []) add("stair", "stairIds", s.id); - for (const e of project.extrudedSolids ?? []) add("extrusion", "extrudedSolidIds", e.id); - for (const r of project.rooms ?? []) add("space", "roomIds", r.id); + // Übernommene GlobalId (Import) vor der abgeleiteten; bei doppelter GlobalId gilt der erste (wie im Export). + const add = (key: string, channel: BcfChannel, id: string, own?: string) => { + const g = own || ifcGuid(`${pid}/${key}/${id}`); + if (!index.has(g)) index.set(g, { channel, id }); + }; + for (const w of project.walls ?? []) add("wall", "wallIds", w.id, w.ifcGlobalId); + for (const c of project.ceilings ?? []) add("slab", "ceilingIds", c.id, c.ifcGlobalId); + for (const r of project.roofs ?? []) add("roof", "roofIds", r.id, r.ifcGlobalId); + for (const c of project.columns ?? []) add("column", "columnIds", c.id, c.ifcGlobalId); + for (const s of project.stairs ?? []) add("stair", "stairIds", s.id, s.ifcGlobalId); + for (const e of project.extrudedSolids ?? []) add("extrusion", "extrudedSolidIds", e.id, e.ifcGlobalId); + for (const r of project.rooms ?? []) add("space", "roomIds", r.id, r.ifcGlobalId); for (const o of project.openings ?? []) { // Tür/Fenster (IfcDoor/IfcWindow) und Öffnung (IfcOpeningElement) gehören zur selben Dossier-Öffnung. - add("fill", "openingIds", o.id); + add("fill", "openingIds", o.id, o.ifcGlobalId); add("opening", "openingIds", o.id); } for (const o of project.context ?? []) { @@ -96,15 +101,16 @@ export function viewpointGuids(vp: BcfViewpoint): string[] { export function selectionToGuids(project: Project, sel: BcfSelection): string[] { const pid = project.id; const guids: string[] = []; - const g = (key: string, ids: string[]) => ids.forEach((id) => guids.push(ifcGuid(`${pid}/${key}/${id}`))); - g("wall", sel.wallIds); - g("slab", sel.ceilingIds); - g("roof", sel.roofIds); - g("column", sel.columnIds); - g("stair", sel.stairIds); - g("extrusion", sel.extrudedSolidIds); - g("space", sel.roomIds); - g("fill", sel.openingIds); + const g = (key: string, ids: string[], items: { id: string; ifcGlobalId?: string }[] | undefined) => + ids.forEach((id) => guids.push(items?.find((e) => e.id === id)?.ifcGlobalId || ifcGuid(`${pid}/${key}/${id}`))); + g("wall", sel.wallIds, project.walls); + g("slab", sel.ceilingIds, project.ceilings); + g("roof", sel.roofIds, project.roofs); + g("column", sel.columnIds, project.columns); + g("stair", sel.stairIds, project.stairs); + g("extrusion", sel.extrudedSolidIds, project.extrudedSolids); + g("space", sel.roomIds, project.rooms); + g("fill", sel.openingIds, project.openings); for (const id of sel.contextObjectIds) { const o = (project.context ?? []).find((c) => c.id === id); if (o?.type === "importedMesh" && o.ifcGlobalId) guids.push(o.ifcGlobalId); diff --git a/src/io/ifcGlobalIdRoundtrip.test.ts b/src/io/ifcGlobalIdRoundtrip.test.ts new file mode 100644 index 00000000..3a3a18fe --- /dev/null +++ b/src/io/ifcGlobalIdRoundtrip.test.ts @@ -0,0 +1,66 @@ +// [201] IFC-GlobalId-Rundreise: der Import setzt `ifcGlobalId` an jedem erkannten Bauteil (Wand, Öffnung, Decke, Stütze, Dach, +// Treppe, Raum, Extrusion), der Export schreibt sie zurück; ohne sie bleibt es bei der abgeleiteten GUID. Doppelte +// GlobalIds (Datei zweimal importiert) landen nie doppelt in der Ausgabe. + +import "../engine/fileioWasm.setup"; +import { describe, expect, it } from "vitest"; +import { exportIfcSpf } from "../export/exportIfc"; +import { emptyProject, sampleProject } from "../model/sampleProject"; +import type { Project } from "../model/types"; +import { importIfcInto } from "./importView.testutil"; + +const bytesOf = (s: string) => new TextEncoder().encode(s); + +/** GlobalIds je IFC-Klasse (nur die 22-stelligen Kennungen am Anfang einer Entität). */ +function guidsByClass(spf: string): Map { + const out = new Map(); + for (const m of spf.matchAll(/#\d+=(IFC[A-Z0-9]+)\('([0-9A-Za-z_$]{22})'/g)) { + out.set(m[1], [...(out.get(m[1]) ?? []), m[2]]); + } + for (const v of out.values()) v.sort(); + return out; +} + +async function imported(base: Project, src: Project): Promise { + return (await importIfcInto(base, bytesOf(exportIfcSpf(src)), { elements: true })).project; +} + +const BIM = ["IFCWALL", "IFCSLAB", "IFCDOOR", "IFCWINDOW", "IFCROOF", "IFCSTAIR", "IFCSPACE"]; + +describe("[201] IFC-GlobalId-Rundreise", () => { + it("Import setzt ifcGlobalId an jedem erkannten Bauteil", async () => { + const p = await imported(emptyProject, sampleProject); + const all = [...p.walls, ...(p.openings ?? []), ...(p.ceilings ?? []), ...(p.roofs ?? []), ...(p.stairs ?? []), ...(p.rooms ?? [])]; + expect(all.length).toBeGreaterThan(10); + for (const e of all) expect(e.ifcGlobalId, `${e.type} ${e.id}`).toMatch(/^[0-3][0-9A-Za-z_$]{21}$/); + }); + + it("Import → Export: gleiche GlobalIds je Klasse wie die Quelldatei", async () => { + const a = guidsByClass(exportIfcSpf(sampleProject)); + const p = await imported(emptyProject, sampleProject); + const b = guidsByClass(exportIfcSpf(p)); + for (const cls of BIM) { + expect(a.get(cls)?.length ?? 0, `${cls} in der Quelle`).toBeGreaterThan(0); + expect(b.get(cls), cls).toEqual(a.get(cls)); + } + }); + + it("ohne ifcGlobalId bleibt die abgeleitete GUID (deterministisch wie bisher)", () => { + const x = guidsByClass(exportIfcSpf(sampleProject)); + const y = guidsByClass(exportIfcSpf(sampleProject)); + expect(x.get("IFCWALL")).toEqual(y.get("IFCWALL")); + }); + + it("dieselbe Datei zweimal importiert: keine GlobalId doppelt in der Ausgabe", async () => { + const once = await imported(emptyProject, sampleProject); + const twice = await imported(once, sampleProject); + expect(twice.walls.length).toBe(once.walls.length * 2); + const spf = exportIfcSpf(twice); + const all = [...spf.matchAll(/#\d+=IFC[A-Z0-9]+\('([0-9A-Za-z_$]{22})'/g)].map((m) => m[1]); + expect(new Set(all).size).toBe(all.length); + // Die erste Kopie behält die ursprünglichen GlobalIds. + const src = guidsByClass(exportIfcSpf(sampleProject)).get("IFCWALL")!; + const out = new Set(guidsByClass(spf).get("IFCWALL")!); + for (const g of src) expect(out.has(g)).toBe(true); + }); +}); diff --git a/src/model/types.generated.ts b/src/model/types.generated.ts index ec79acc1..edddd884 100644 --- a/src/model/types.generated.ts +++ b/src/model/types.generated.ts @@ -70,6 +70,11 @@ export type Ceiling = { floorId: string; /** Grafik-Kategorie (Ebene), z. B. "30" für Decken. */ categoryCode: string; + /** + * [201] IFC-GlobalId des Quell-Bauteils (IFC-Import); der IFC-Export schreibt sie zurück, damit + * die Rundreise dieselben GUIDs behält. Kopien (Einfügen, Kopieren, Reihe, Wand teilen) tragen sie NICHT. + */ + ifcGlobalId?: string; /** * Vorsprung im Baurecht ([63]: Balkon, Erker): darf mit `SiteRules.projectionDepth`/ * `projectionShare` in den Grenzabstand ragen. Fehlt ⇒ normales Bauteil. @@ -208,6 +213,11 @@ export type Column = { floorId: string; /** Grafik-Kategorie (Ebene), z. B. "50" für Tragwerk. */ categoryCode: string; + /** + * [201] IFC-GlobalId des Quell-Bauteils (IFC-Import); der IFC-Export schreibt sie zurück, damit + * die Rundreise dieselben GUIDs behält. Kopien (Einfügen, Kopieren, Reihe, Wand teilen) tragen sie NICHT. + */ + ifcGlobalId?: string; /** Objekt-Sperre, analog `Wall.locked`. */ locked?: boolean; /** Einfügepunkt (Profil-Mitte) im Grundriss (Meter). */ @@ -1315,6 +1325,11 @@ export type ExtrudedSolid = { * [180] Klasse (Ebene/Kategorie) wie bei jedem Bauteil: Sichtbarkeit in Grundriss, Schnitt und Ansicht. */ categoryCode: string; + /** + * [201] IFC-GlobalId des Quell-Bauteils (IFC-Import); der IFC-Export schreibt sie zurück, damit + * die Rundreise dieselben GUIDs behält. Kopien (Einfügen, Kopieren, Reihe, Wand teilen) tragen sie NICHT. + */ + ifcGlobalId?: string; /** * Geschlossenes Profil in der XY-Ebene (Grundriss), ≥3 Punkte. Bei einem * Kreis-Profil (`circle` gesetzt) eine Tessellierung des Kreises (48-Eck) — @@ -2331,6 +2346,11 @@ export type Opening = { hostWallId: string; /** Grafik-Kategorie (Ebene), z. B. "21" für Türen/Fenster. */ categoryCode: string; + /** + * [201] IFC-GlobalId des Quell-Bauteils (IFC-Import); der IFC-Export schreibt sie zurück, damit + * die Rundreise dieselben GUIDs behält. Kopien (Einfügen, Kopieren, Reihe, Wand teilen) tragen sie NICHT. + */ + ifcGlobalId?: string; /** Objekt-Sperre, analog `Wall.locked`. */ locked?: boolean; /** Bauteilnummer (Fenster-/Türliste); leer = automatisch je Geschoss nummeriert. */ @@ -3027,6 +3047,11 @@ export type Roof = { floorId: string; /** Grafik-Kategorie (Ebene), z. B. "35" für Dächer. */ categoryCode: string; + /** + * [201] IFC-GlobalId des Quell-Bauteils (IFC-Import); der IFC-Export schreibt sie zurück, damit + * die Rundreise dieselben GUIDs behält. Kopien (Einfügen, Kopieren, Reihe, Wand teilen) tragen sie NICHT. + */ + ifcGlobalId?: string; /** Objekt-Sperre, analog `Wall.locked`. */ locked?: boolean; /** @@ -3176,6 +3201,11 @@ export type Room = { floorId: string; /** Grafik-Kategorie (Ebene), z. B. "45" für Räume. */ categoryCode: string; + /** + * [201] IFC-GlobalId des Quell-Bauteils (IFC-Import); der IFC-Export schreibt sie zurück, damit + * die Rundreise dieselben GUIDs behält. Kopien (Einfügen, Kopieren, Reihe, Wand teilen) tragen sie NICHT. + */ + ifcGlobalId?: string; /** Objekt-Sperre, analog `Wall.locked`. */ locked?: boolean; /** SIA-416-Blatt-Kategorie (HNF/NNF/VF/FF/KGF). */ @@ -3456,6 +3486,11 @@ export type Stair = { floorId: string; /** Grafik-Kategorie (Ebene), z. B. "40" für Treppen. */ categoryCode: string; + /** + * [201] IFC-GlobalId des Quell-Bauteils (IFC-Import); der IFC-Export schreibt sie zurück, damit + * die Rundreise dieselben GUIDs behält. Kopien (Einfügen, Kopieren, Reihe, Wand teilen) tragen sie NICHT. + */ + ifcGlobalId?: string; /** Objekt-Sperre, analog `Wall.locked`. */ locked?: boolean; /** Grundform (gerade / L / Wendel). */ @@ -3989,6 +4024,11 @@ export type Wall = { floorId: string; /** Grafik-Kategorie (Ebene), z. B. "20" für Wände. */ categoryCode: string; + /** + * [201] IFC-GlobalId des Quell-Bauteils (IFC-Import); der IFC-Export schreibt sie zurück, damit + * die Rundreise dieselben GUIDs behält. Kopien (Einfügen, Kopieren, Reihe, Wand teilen) tragen sie NICHT. + */ + ifcGlobalId?: string; /** * Vorsprung im Baurecht ([63]: Wand eines Erkers): darf mit `SiteRules.projectionDepth`/ * `projectionShare` in den Grenzabstand ragen. Fehlt ⇒ normales Bauteil. diff --git a/src/native/saveFile.ts b/src/native/saveFile.ts index 302b569c..59299230 100644 --- a/src/native/saveFile.ts +++ b/src/native/saveFile.ts @@ -146,3 +146,52 @@ function browserDownloadBlob(blob: Blob, defaultName: string): boolean { }, 4000); return true; } + +/** Hauptdatei samt Begleitdatei, die auf sie verweist ([201], OBJ + MTL). */ +export interface TextWithCompanion { + main: string; + companion: string; +} + +/** + * Speichert eine Textdatei und eine Begleitdatei mit gleichem Namen, aber anderer Endung (OBJ + MTL). + * `build` bekommt den Dateinamen der Begleitdatei (für den Verweis in der Hauptdatei, z. B. `mtllib`). + * - Unter Tauri: Speichern-Dialog für die Hauptdatei, danach ein zweiter für die Begleitdatei (Vorschlag: gleicher Ordner und + * Stamm) — der Dialog gibt den Pfad frei; ein stilles Schreiben neben die Hauptdatei dürfte am Dateizugriff scheitern. + * Bricht man den zweiten ab, bleibt die Hauptdatei mit totem Verweis (nur die Farben fehlen dann). + * - Im Browser: zwei Downloads nacheinander. + * + * @returns `true` wenn die Hauptdatei geschrieben wurde, `false` bei Abbruch. + */ +export async function saveTextWithCompanion( + build: (companionName: string) => TextWithCompanion, + defaultName: string, + companionExt: string, + filters?: FileDialogFilter[], + companionFilters?: FileDialogFilter[], +): Promise { + const stemOf = (name: string) => name.replace(/^.*[\\/]/, "").replace(/\.[^.]*$/, ""); + if (isTauri()) { + try { + const { save } = await import("@tauri-apps/plugin-dialog"); + const { writeTextFile } = await import("@tauri-apps/plugin-fs"); + const path = await save({ defaultPath: defaultName, filters }); + if (!path) return false; + const companionName = `${stemOf(path)}.${companionExt}`; + const files = build(companionName); + await writeTextFile(path, files.main); + const companionPath = await save({ defaultPath: path.replace(/[^\\/]*$/, companionName), filters: companionFilters }); + if (companionPath) await writeTextFile(companionPath, files.companion); + return true; + } catch (err) { + if (!warnedFallback) { + warnedFallback = true; + console.warn("Nativer Speichern-Dialog fehlgeschlagen, nutze Browser-Download.", err); + } + } + } + const companionName = `${stemOf(defaultName)}.${companionExt}`; + const files = build(companionName); + browserDownload(files.main, defaultName, "application/octet-stream"); + return browserDownload(files.companion, companionName, "application/octet-stream"); +} diff --git a/src/state/useProjectFileActions.ts b/src/state/useProjectFileActions.ts index ab9c79e1..1cac8efb 100644 --- a/src/state/useProjectFileActions.ts +++ b/src/state/useProjectFileActions.ts @@ -26,9 +26,9 @@ import { exportScheduleCsv } from "../export/exportSchedule"; import { exportIfcSpf, type IfcExportOptions } from "../export/exportIfc"; import { loadFileio } from "../engine/fileioWasm"; import { exportProjectStep } from "../export/exportStep"; -import { exportGlb, exportObj, exportStl } from "../export/exportMesh"; +import { exportGlb, exportMtl, exportObj, exportStl } from "../export/exportMesh"; import type { ExportSaveFormat } from "../ui/ExportSaveDialog"; -import { saveBinaryFile, saveTextFile } from "../native/saveFile"; +import { saveBinaryFile, saveTextFile, saveTextWithCompanion } from "../native/saveFile"; import { saveProjectFile, openProjectFileNative, @@ -583,7 +583,9 @@ export function useProjectFileActions( void loadFileio() .then(() => { if (format === "glb") void saveBinaryFile(exportGlb(project), filename, "model/gltf-binary"); - else downloadTextFile(format === "obj" ? exportObj(project) : exportStl(project), filename); + // [201] OBJ mit MTL (Farben) als zweite Datei gleichen Namens; STL kennt keine Farben. + else if (format === "obj") void saveTextWithCompanion((mtlName) => ({ main: exportObj(project, {}, mtlName), companion: exportMtl(project) }), filename, "mtl"); + else downloadTextFile(exportStl(project), filename); }) .catch((e) => notify(`${t("mesh.export.failed")}: ${e instanceof Error ? e.message : String(e)}`, "error")); break;