Merge branch 'worktree-agent-ac143182c4c59003b' into claude/practical-noether-1hb2s1
This commit is contained in:
33 files changed
+798
-157
No files matched your search
+1
-1
@@ -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` |
|
||||
|
||||
@@ -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<Op> {
|
||||
});
|
||||
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<Op> {
|
||||
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!({
|
||||
|
||||
@@ -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<String, Value>, 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<String, Value>, 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"))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<String, Value>, 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<String, Value>, 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");
|
||||
|
||||
@@ -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<Flat, String>
|
||||
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<String>| {
|
||||
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();
|
||||
|
||||
@@ -50,6 +50,8 @@ struct Info {
|
||||
type_name: Option<String>,
|
||||
layers: Vec<MatLayer>,
|
||||
classified: bool,
|
||||
/// [201] IFC-GlobalId des Quell-Bauteils (22 Zeichen); bleibt am Element, der Export schreibt sie zurück.
|
||||
global_id: Option<String>,
|
||||
/// Eigenschaften aus `Pset_*Common` (Text).
|
||||
common: Map<String, Value>,
|
||||
}
|
||||
@@ -190,6 +192,11 @@ struct Elements {
|
||||
kept_reasons: Map<String, Value>,
|
||||
}
|
||||
|
||||
/// 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<String> {
|
||||
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<String, Value>, 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<String, Value>, 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<String, Value>, 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<String, Value>, 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<String, Value>, 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<String, Value>, 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<Value> = Vec::new();
|
||||
@@ -952,6 +979,7 @@ fn elements_ops(root: &Map<String, Value>, 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<String, Value>, 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");
|
||||
|
||||
@@ -125,6 +125,12 @@ pub fn with_opt(v: &Value, fields: Vec<(&str, Option<Value>)>) -> 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(&[])
|
||||
}
|
||||
|
||||
@@ -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<String>,
|
||||
/// 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<String>,
|
||||
/// 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<String>,
|
||||
/// 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<String>,
|
||||
/// 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<String>,
|
||||
/// 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<String>,
|
||||
/// 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<String>,
|
||||
/// 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<String>,
|
||||
/// Objekt-Sperre, analog `Wall.locked`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
|
||||
Generated
+14
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
@@ -34,6 +34,8 @@ pub(super) struct Builder {
|
||||
pub(super) column_materials: Vec<(String, String, Vec<usize>)>,
|
||||
/// Bauteil-Schlüssel (wie für die GlobalId, z. B. `wall/<id>`) → Entität; Ziel von Klassifikation/Zone/Attach.
|
||||
pub(super) elements: HashMap<String, usize>,
|
||||
/// [201] Übernommene GlobalIds (Schlüssel wie für `gid`), Vorrang vor der abgeleiteten.
|
||||
pub(super) guid_override: HashMap<String, String>,
|
||||
/// IFC2x3: Türen/Fenster je (Tür?, Ausführung) → Bauteile; am Ende je ein IfcDoorStyle/IfcWindowStyle.
|
||||
pub(super) fill_styles: Vec<(bool, String, Vec<usize>)>,
|
||||
}
|
||||
@@ -53,6 +55,9 @@ impl Builder {
|
||||
|
||||
/// Dauerhafte GlobalId (als STEP-String) aus `<Art>/<id>[/<Zusatz>]`, 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)))
|
||||
}
|
||||
|
||||
|
||||
@@ -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 `<Projekt-id>/<Art>/<id>[/<Zusatz>]`.
|
||||
|
||||
@@ -100,6 +100,10 @@
|
||||
// IfcZone mit IfcRelAssignsToGroup der Räume (`space/<id>`-Entitäten; unbekannte ids werden
|
||||
// übersprungen, ohne Raum keine Zone). GlobalId aus `zone/<key>`; 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/<id>`, `slab/<id>`, `roof/<id>`,
|
||||
// `column/<id>`, `stair/<id>`, `space/<id>`, `extrusion/<id>`, `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/<id>`.
|
||||
@@ -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<String, String> {
|
||||
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<String, String> {
|
||||
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<String> = 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()?;
|
||||
|
||||
@@ -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<String> {
|
||||
let mut out: Vec<String> = 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<usize> {
|
||||
let mut used: Vec<usize> = 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<[usize; 3]>> = 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<u8>) {
|
||||
// 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<f32>, Vec<u32>)> = Vec::new();
|
||||
let mut merged: Vec<(i64, Vec<f32>, Vec<f32>, Vec<u32>)> = 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<u8>) {
|
||||
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<u8>) {
|
||||
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<u8>) {
|
||||
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<u8>) {
|
||||
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<u8>) {
|
||||
};
|
||||
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<u8>) {
|
||||
// ── Öffentliche Schreiber ───────────────────────────────────────────────────
|
||||
|
||||
/// OBJ-Text aus der flachen Szene.
|
||||
pub fn export_obj(flat: &[f64], strings: &str) -> Result<String, String> {
|
||||
Ok(write_obj(&parse(flat, strings)?))
|
||||
pub fn export_obj(flat: &[f64], strings: &str, mtl_name: &str) -> Result<String, String> {
|
||||
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<String, String> {
|
||||
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<Vec<u8>, 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::<f32>() - 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]
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -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<Option<[[f32; 3]; 3]>> {
|
||||
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<Option<([usize; 3], [f32; 3], [f32; 3])>> = 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<usize>> = 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()
|
||||
}
|
||||
@@ -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<Option<[[f32; 3]; 3]>> {
|
||||
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<Option<([usize; 3], [f32; 3], [f32; 3])>> = 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<usize>> = 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;
|
||||
|
||||
Reference in new issue
Block a user