[K4] S4 Import: Umwandlung DXF/DWG/PDF, IFC und Meshes im Kern, Paritätstests neben der TS-Fassung
Kern-Module import_drawing/import_ifc/import_context, Bindungen web/import.rs (doc_import_drawing, doc_import_ifc, doc_import_mesh, Zusammenfassung, Leseansicht, pdf_page_info), ProjectDocument.importDrawing/ importIfc/importMesh. Vorübergehend: io/importParity.test.ts, io/importBench.test.ts.
This commit is contained in:
13 files changed
+3193
No files matched your search
@@ -804,6 +804,11 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
wie vorher bis auf erzeugte ids. Messung (vitest/Node, `--no-opt`-WASM, Container unter Last, bigSample(20),
|
||||
2,6 MB, 3600 Wände): Öffnen 106–115 ms (alter Weg ohne den Kern-Parse ≈ 210–260 ms: JSON zurück, Differenz,
|
||||
Commit), Speichern im Kern 32 ms (vorher Kopie des Baums ≈ 80 ms; `JSON.stringify` in JS 17–19 ms).
|
||||
◐ **Import-Umwandlung im Kern (29.10.):** Format-Modul liest, der Kern wandelt und wendet als EIN Undo-Schritt an
|
||||
(`core/src/import_drawing.rs`, `import_ifc.rs`, `import_context.rs`, Bindungen `web/import.rs`, TS
|
||||
`ProjectDocument.importDrawing/importIfc/importMesh`). Schritt 1: Kern-Fassung + vorübergehende Paritätstests
|
||||
(`io/importParity.test.ts`, Fixtures über `DOSSIER_PARITY_FX`) neben der alten TS-Fassung; offen: Aufrufer umstellen,
|
||||
TS-Umwandlung löschen.
|
||||
Offene Entscheide/Risiken: Kosten der JSON-Übergabe bei grossen Projekten (Teil-Updates statt Neuaufbau), Struktur-Sharing im
|
||||
React-Store (TS-Spiegel bleibt bis S3), Befehls-Zustandsautomaten sind viel Code (`src/commands/cmds/*`).
|
||||
- **Fertig wenn** (je Etappe): TS-Fassung gelöscht, `npm run check` grün, App/CLI/IFC unverändert.
|
||||
|
||||
@@ -0,0 +1,479 @@
|
||||
//! Kontext-Meshes aus Importen ([K4] S4, vorher `io/ifcImport.ts::ifcToImportedMeshes`,
|
||||
//! `io/meshImport.ts::meshObjectsToImportedMeshes`, `model/contextCategories.ts::ensureContextCategories`
|
||||
//! und die Op-Bauer im CLI/`siteSlice`): IFC-Bauteile ([B3]) und Objekte aus OBJ/STL/glTF/PLY ([C11]) werden
|
||||
//! zu `ImportedMesh` der Kontext-Schicht, fehlende Kontext-Kategorien werden im Ebenen-Baum ergänzt.
|
||||
//!
|
||||
//! Eingaben sind die flachen Puffer des Format-Moduls (`fileio/src/ifc_import.rs`: Bericht als JSON +
|
||||
//! Positionen/Indizes; `fileio/src/mesh_import.rs`: Zahlenpuffer + Strings). Zahlen wie in der TS-Fassung
|
||||
//! (`Math.hypot`, `Math.round`), ids aus Zeit (Basis 36) + Zähler.
|
||||
|
||||
use crate::grips::js_num;
|
||||
use crate::import_drawing::{next_seq, GENERIC_IMPORT_CODE};
|
||||
use crate::jsmath;
|
||||
use crate::jsnum;
|
||||
use crate::ops::Op;
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
// ── Kontext-Kategorien ───────────────────────────────────────────────────────
|
||||
|
||||
struct Def {
|
||||
code: &'static str,
|
||||
name: &'static str,
|
||||
color: &'static str,
|
||||
lw: f64,
|
||||
}
|
||||
|
||||
/// „05 Kontext" — Elternkategorie der Kontext-Kategorien.
|
||||
const CONTEXT_PARENT: Def = Def { code: "05", name: "Kontext", color: "#707078", lw: 0.13 };
|
||||
/// „31 Dächer" bleibt oberste Ebene.
|
||||
const IMPORTED_ROOF: Def = Def { code: "31", name: "Dächer", color: "#7a4a3a", lw: 0.35 };
|
||||
/// Kinder von „05 Kontext", in dieser Reihenfolge (`NESTED_CONTEXT_CATEGORIES`).
|
||||
const NESTED: [Def; 10] = [
|
||||
Def { code: "02", name: "Gelände", color: "#8a9478", lw: 0.13 },
|
||||
Def { code: "03", name: "Luftbild", color: "#707078", lw: 0.13 },
|
||||
Def { code: "10", name: "Situation", color: "#909090", lw: 0.18 },
|
||||
Def { code: "12", name: "Gebäude", color: "#888888", lw: 0.25 },
|
||||
Def { code: "11", name: "Strasse", color: "#a89070", lw: 0.18 },
|
||||
Def { code: "04", name: "Wald", color: "#3a7a3a", lw: 0.13 },
|
||||
Def { code: "15", name: "Parkplätze", color: "#a0a0a0", lw: 0.13 },
|
||||
Def { code: "16", name: "Bahn", color: "#606060", lw: 0.18 },
|
||||
Def { code: "17", name: "Gewässer", color: "#5a90b0", lw: 0.13 },
|
||||
Def { code: "18", name: "Grünflächen", color: "#70b070", lw: 0.13 },
|
||||
];
|
||||
|
||||
fn category(d: &Def) -> Value {
|
||||
json!({"code": d.code, "name": d.name, "color": d.color, "lw": d.lw, "visible": true, "locked": false})
|
||||
}
|
||||
|
||||
/// Ergänzt `layers` um jede fehlende Kontext-Kategorie aus `codes` (vorhandene Codes, auch umbenannte, bleiben).
|
||||
/// Fehlende Kinder landen unter „05 Kontext" (bei Bedarf angelegt), „31 Dächer" oben. `true` = geändert.
|
||||
pub fn ensure_context_categories<'a>(layers: &mut Vec<Value>, codes: impl IntoIterator<Item = &'a str>) -> bool {
|
||||
let existing: HashSet<String> =
|
||||
crate::layers::flatten(layers).into_iter().filter_map(|c| c.get("code").and_then(Value::as_str).map(str::to_string)).collect();
|
||||
let missing: HashSet<&str> = codes.into_iter().filter(|c| !existing.contains(*c)).collect();
|
||||
if missing.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let nested: Vec<Value> = NESTED.iter().filter(|d| missing.contains(d.code)).map(category).collect();
|
||||
if !nested.is_empty() {
|
||||
match layers.iter().position(|l| l.get("code").and_then(Value::as_str) == Some(CONTEXT_PARENT.code)) {
|
||||
Some(i) => {
|
||||
let mut l = layers[i].as_object().cloned().unwrap_or_default();
|
||||
let mut kids = l.get("children").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
kids.extend(nested);
|
||||
l.insert("children".into(), Value::Array(kids));
|
||||
layers[i] = Value::Object(l);
|
||||
}
|
||||
None => {
|
||||
let mut p = category(&CONTEXT_PARENT);
|
||||
p.as_object_mut().unwrap().insert("children".into(), Value::Array(nested));
|
||||
layers.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
if missing.contains(IMPORTED_ROOF.code) {
|
||||
layers.push(category(&IMPORTED_ROOF));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Ops: Kontext-Objekte anhängen (fehlt die Liste, wird sie gesetzt) und fehlende Kontext-Kategorien ergänzen.
|
||||
pub fn context_ops(root: &Map<String, Value>, meshes: Vec<Value>) -> Vec<Op> {
|
||||
let codes: Vec<String> = meshes.iter().filter_map(|m| m.get("categoryCode").and_then(Value::as_str).filter(|c| !c.is_empty()).map(str::to_string)).collect();
|
||||
let mut ops = Vec::new();
|
||||
if root.get("context").is_some_and(|c| !c.is_null()) {
|
||||
if !meshes.is_empty() {
|
||||
ops.push(Op::Add { collection: "context".into(), items: meshes, at: None });
|
||||
}
|
||||
} else {
|
||||
ops.push(Op::SetField { key: "context".into(), value: Some(Value::Array(meshes)), at: None });
|
||||
}
|
||||
let mut layers = root.get("layers").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
if ensure_context_categories(&mut layers, codes.iter().map(String::as_str)) {
|
||||
ops.push(Op::SetField { key: "layers".into(), value: Some(Value::Array(layers)), at: None });
|
||||
}
|
||||
ops
|
||||
}
|
||||
|
||||
// ── Gemeinsames ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// `Date.now().toString(36)`.
|
||||
pub fn stamp36(now: f64) -> String {
|
||||
let mut n = if now.is_finite() && now > 0.0 { now.trunc() as u64 } else { 0 };
|
||||
if n == 0 {
|
||||
return "0".into();
|
||||
}
|
||||
let mut d = Vec::new();
|
||||
while n > 0 {
|
||||
d.push(std::char::from_digit((n % 36) as u32, 36).unwrap());
|
||||
n /= 36;
|
||||
}
|
||||
d.iter().rev().collect()
|
||||
}
|
||||
|
||||
/// Dateiname ohne letzte Endung (`name.replace(/\.[^.]+$/, "")`), leer → `fallback`.
|
||||
pub fn base_name(file: &str, fallback: &str) -> String {
|
||||
let b = match file.rfind('.') {
|
||||
Some(i) if i + 1 < file.len() => &file[..i],
|
||||
_ => file,
|
||||
};
|
||||
if b.is_empty() { fallback.to_string() } else { b.to_string() }
|
||||
}
|
||||
|
||||
/// RGBA 0..1 → `#rrggbb` (`rgbToHex`, Alpha entfällt); `None` ohne gültige Farbe.
|
||||
pub fn color_hex(c: Option<&[f64]>) -> Option<String> {
|
||||
let c = c?;
|
||||
if c.len() < 3 || !c[..3].iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let h = |v: f64| jsnum::max(0.0, jsnum::min(255.0, jsnum::round(v * 255.0))) as u32;
|
||||
Some(format!("#{:02x}{:02x}{:02x}", h(c[0]), h(c[1]), h(c[2])))
|
||||
}
|
||||
|
||||
/// Farbe eines JSON-Werts (`[r, g, b, a]` oder `null`).
|
||||
pub fn color_of(v: Option<&Value>) -> Option<Vec<f64>> {
|
||||
v?.as_array().map(|a| a.iter().map(|x| x.as_f64().unwrap_or(f64::NAN)).collect())
|
||||
}
|
||||
|
||||
fn mesh_value(id: String, name: String, layer: &str, color: Option<String>, extra: Option<(&str, &str)>, positions: Vec<Value>, indices: Vec<Value>) -> Value {
|
||||
let mut o = Map::new();
|
||||
o.insert("id".into(), id.into());
|
||||
o.insert("type".into(), "importedMesh".into());
|
||||
o.insert("name".into(), name.into());
|
||||
o.insert("layer".into(), layer.into());
|
||||
o.insert("categoryCode".into(), GENERIC_IMPORT_CODE.into());
|
||||
if let Some(c) = color {
|
||||
o.insert("color".into(), c.into());
|
||||
}
|
||||
if let Some((k, v)) = extra {
|
||||
o.insert(k.into(), v.into());
|
||||
}
|
||||
o.insert("positions".into(), Value::Array(positions));
|
||||
o.insert("indices".into(), Value::Array(indices));
|
||||
Value::Object(o)
|
||||
}
|
||||
|
||||
/// Positionen (verschoben) und Indizes mehrerer Teile hintereinander.
|
||||
fn arrays<'a>(parts: impl Iterator<Item = (&'a [f64], &'a [f64])>, d: [f64; 3]) -> (Vec<Value>, Vec<Value>) {
|
||||
let mut pos = Vec::new();
|
||||
let mut idx = Vec::new();
|
||||
for (p, ix) in parts {
|
||||
let off = (pos.len() / 3) as f64;
|
||||
let mut i = 0;
|
||||
while i + 2 < p.len() {
|
||||
pos.push(js_num(p[i] + d[0]));
|
||||
pos.push(js_num(p[i + 1] + d[1]));
|
||||
pos.push(js_num(p[i + 2] + d[2]));
|
||||
i += 3;
|
||||
}
|
||||
for &k in ix {
|
||||
idx.push(js_num(k + off));
|
||||
}
|
||||
}
|
||||
(pos, idx)
|
||||
}
|
||||
|
||||
/// Gruppen in Reihenfolge des ersten Auftretens.
|
||||
fn group_by<T>(items: &[T], key: impl Fn(&T) -> String) -> Vec<Vec<usize>> {
|
||||
let mut at: HashMap<String, usize> = HashMap::new();
|
||||
let mut groups: Vec<Vec<usize>> = Vec::new();
|
||||
for (i, it) in items.iter().enumerate() {
|
||||
let k = key(it);
|
||||
match at.get(&k) {
|
||||
Some(&g) => groups[g].push(i),
|
||||
None => {
|
||||
at.insert(k, groups.len());
|
||||
groups.push(vec![i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// LV95-Ursprung des Projekts (`projectGeoOrigin`: `geoAnchor.lv95 − geoAnchor.model`), ohne Bezug `None`.
|
||||
pub fn project_geo_origin(root: &Map<String, Value>) -> Option<[f64; 2]> {
|
||||
let a = root.get("geoAnchor").filter(|a| crate::grips::truthy(Some(a)))?;
|
||||
let n = |p: &str, k: &str| a.get(p).and_then(|o| o.get(k)).and_then(Value::as_f64).unwrap_or(f64::NAN);
|
||||
Some([n("lv95", "e") - n("model", "x"), n("lv95", "n") - n("model", "y")])
|
||||
}
|
||||
|
||||
// ── IFC ([B3]) ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// Ab so vielen Bauteilen bzw. Objekten wird zusammengelegt.
|
||||
pub const MAX_SINGLE: usize = 2000;
|
||||
|
||||
/// Ein gelesenes IFC-Bauteil (Ansichten in die flachen Puffer).
|
||||
pub struct IfcProduct<'a> {
|
||||
pub global_id: String,
|
||||
pub ifc_class: String,
|
||||
pub name: Option<String>,
|
||||
pub storey: Option<String>,
|
||||
pub color: Option<Vec<f64>>,
|
||||
pub classifications: Vec<Value>,
|
||||
pub positions: &'a [f64],
|
||||
pub indices: &'a [f64],
|
||||
}
|
||||
|
||||
fn opt_str(v: Option<&Value>) -> Option<String> {
|
||||
v.and_then(Value::as_str).map(str::to_string)
|
||||
}
|
||||
|
||||
/// Bauteile aus dem Bericht (`meta.products`) und den Puffern (vorher `decodeIfc`).
|
||||
pub fn decode_ifc_products<'a>(meta: &Value, positions: &'a [f64], indices: &'a [f64]) -> Result<Vec<IfcProduct<'a>>, String> {
|
||||
let list = meta.get("products").and_then(Value::as_array).ok_or("IFC-Bericht ohne Bauteile")?;
|
||||
let (mut po, mut io) = (0usize, 0usize);
|
||||
let mut out = Vec::with_capacity(list.len());
|
||||
for p in list {
|
||||
let pc = p.get("positionCount").and_then(Value::as_u64).unwrap_or(0) as usize;
|
||||
let ic = p.get("indexCount").and_then(Value::as_u64).unwrap_or(0) as usize;
|
||||
let pe = (po + pc).min(positions.len());
|
||||
let ie = (io + ic).min(indices.len());
|
||||
out.push(IfcProduct {
|
||||
global_id: opt_str(p.get("globalId")).unwrap_or_default(),
|
||||
ifc_class: opt_str(p.get("ifcClass")).unwrap_or_default(),
|
||||
name: opt_str(p.get("name")),
|
||||
storey: opt_str(p.get("storey")),
|
||||
color: color_of(p.get("color")),
|
||||
classifications: p.get("classifications").and_then(Value::as_array).cloned().unwrap_or_default(),
|
||||
positions: &positions[po.min(pe)..pe],
|
||||
indices: &indices[io.min(ie)..ie],
|
||||
});
|
||||
po += pc;
|
||||
io += ic;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Verschiebung, falls die Datei in Landeskoordinaten liegt und das Projekt einen Bezug hat (`geoShift`);
|
||||
/// `extra` = weitere Punkte (x, y flach).
|
||||
pub fn geo_shift(products: &[IfcProduct], origin: Option<[f64; 2]>, extra: &[f64]) -> [f64; 2] {
|
||||
let Some(o) = origin else { return [0.0, 0.0] };
|
||||
let (mut sx, mut sy, mut n) = (0.0, 0.0, 0.0);
|
||||
for p in products {
|
||||
let mut i = 0;
|
||||
while i + 2 < p.positions.len() {
|
||||
sx += p.positions[i];
|
||||
sy += p.positions[i + 1];
|
||||
n += 1.0;
|
||||
i += 3 * 64;
|
||||
}
|
||||
}
|
||||
let mut i = 0;
|
||||
while i + 1 < extra.len() {
|
||||
sx += extra[i];
|
||||
sy += extra[i + 1];
|
||||
n += 1.0;
|
||||
i += 2;
|
||||
}
|
||||
if n == 0.0 {
|
||||
return [0.0, 0.0];
|
||||
}
|
||||
let (cx, cy) = (sx / n, sy / n);
|
||||
if jsmath::hypot2(cx - o[0], cy - o[1]) < jsmath::hypot2(cx, cy) {
|
||||
[-o[0], -o[1]]
|
||||
} else {
|
||||
[0.0, 0.0]
|
||||
}
|
||||
}
|
||||
|
||||
/// Klassifikation als Namenszusatz (` [eBKP-H C]`), nur die erste; ohne leer.
|
||||
pub fn classification_suffix(list: &[Value]) -> String {
|
||||
let Some(c) = list.first() else { return String::new() };
|
||||
let parts: Vec<&str> = [c.get("system"), c.get("code")].iter().filter_map(|v| v.and_then(Value::as_str)).filter(|s| !s.is_empty()).collect();
|
||||
format!(" [{}]", parts.join(" "))
|
||||
}
|
||||
|
||||
/// Gruppierung: `"product"`, `"class"` oder `"auto"` (nach [`MAX_SINGLE`]).
|
||||
pub fn ifc_meshes(products: &[IfcProduct], file_name: &str, group: &str, shift: [f64; 2], now: f64) -> Vec<Value> {
|
||||
let base = base_name(file_name, "IFC");
|
||||
let stamp = stamp36(now);
|
||||
let d = [shift[0], shift[1], 0.0];
|
||||
let per_product = group == "product" || (group != "class" && products.len() <= MAX_SINGLE);
|
||||
if per_product {
|
||||
return products
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let label = [p.storey.as_deref(), Some(p.name.as_deref().filter(|n| !n.is_empty()).unwrap_or(&p.ifc_class))]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join(": ");
|
||||
let (pos, idx) = arrays(std::iter::once((p.positions, p.indices)), d);
|
||||
let gid = (!p.global_id.is_empty()).then_some(("ifcGlobalId", p.global_id.as_str()));
|
||||
mesh_value(
|
||||
format!("imported-ifc-{stamp}-{}", next_seq()),
|
||||
label + &classification_suffix(&p.classifications),
|
||||
&p.ifc_class,
|
||||
color_hex(p.color.as_deref()),
|
||||
gid,
|
||||
pos,
|
||||
idx,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
group_by(products, |p| format!("{}\u{0}{}", p.ifc_class, p.storey.as_deref().unwrap_or("")))
|
||||
.into_iter()
|
||||
.map(|g| {
|
||||
let first = &products[g[0]];
|
||||
let colors: HashSet<String> = g.iter().map(|&i| color_hex(products[i].color.as_deref()).unwrap_or_default()).collect();
|
||||
let color = if colors.len() == 1 { colors.into_iter().next().filter(|c| !c.is_empty()) } else { None };
|
||||
let label = [first.storey.as_deref(), Some(first.ifc_class.as_str())].into_iter().flatten().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" ");
|
||||
let (pos, idx) = arrays(g.iter().map(|&i| (products[i].positions, products[i].indices)), d);
|
||||
mesh_value(format!("imported-ifc-{stamp}-{}", next_seq()), format!("{base}: {label} ({})", g.len()), &first.ifc_class, color, None, pos, idx)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Bericht des IFC-Imports: Bericht des Lesers mit `products` = Anzahl, dazu Bauteile je Klasse und Dreiecke.
|
||||
pub fn ifc_report(meta: &Value, products: &[IfcProduct]) -> Value {
|
||||
let mut r = meta.as_object().cloned().unwrap_or_default();
|
||||
r.insert("products".into(), products.len().into());
|
||||
let mut by_class = Map::new();
|
||||
for p in products {
|
||||
let n = by_class.get(&p.ifc_class).and_then(Value::as_f64).unwrap_or(0.0) + 1.0;
|
||||
by_class.insert(p.ifc_class.clone(), js_num(n));
|
||||
}
|
||||
let tris: f64 = products.iter().map(|p| p.indices.len() as f64 / 3.0).sum();
|
||||
r.insert("byClass".into(), Value::Object(by_class));
|
||||
r.insert("triangles".into(), js_num(tris));
|
||||
Value::Object(r)
|
||||
}
|
||||
|
||||
// ── Allgemeine Meshes ([C11]) ────────────────────────────────────────────────
|
||||
|
||||
pub struct MeshObject {
|
||||
pub name: String,
|
||||
pub group: String,
|
||||
pub color: Option<Vec<f64>>,
|
||||
pub positions: Vec<f64>,
|
||||
pub indices: Vec<f64>,
|
||||
}
|
||||
|
||||
const MESH_FORMATS: [&str; 4] = ["obj", "stl", "gltf", "ply"];
|
||||
|
||||
/// Flache Puffer → Objekte + Bericht (vorher `decodeMesh`, Aufbau: Kopf von `mesh_import.rs`).
|
||||
pub fn decode_mesh(f: &[f64], strings: &[String]) -> Result<(Vec<MeshObject>, Value), String> {
|
||||
const HEAD: usize = 12;
|
||||
if f.len() < HEAD || f[0] != 1.0 {
|
||||
return Err("Mesh-Import: unbekannte Kodierung".into());
|
||||
}
|
||||
let s = |k: f64| if k >= 0.0 && k.fract() == 0.0 { strings.get(k as usize).cloned().unwrap_or_default() } else { String::new() };
|
||||
let n_warn = f[10];
|
||||
let n_obj = f[11];
|
||||
let mut at = HEAD;
|
||||
let mut warnings = Vec::new();
|
||||
let mut k = 0.0;
|
||||
while k < n_warn {
|
||||
warnings.push(Value::String(s(*f.get(at).ok_or("Mesh-Import: Puffer beschädigt")?)));
|
||||
at += 1;
|
||||
k += 1.0;
|
||||
}
|
||||
let mut objects = Vec::new();
|
||||
let mut k = 0.0;
|
||||
while k < n_obj {
|
||||
let h = f.get(at..at + 9).ok_or("Mesh-Import: Puffer beschädigt")?;
|
||||
let name = s(h[0]);
|
||||
let group = if h[1] >= 0.0 { s(h[1]) } else { String::new() };
|
||||
let color = (h[2] == 1.0).then(|| vec![h[3], h[4], h[5], h[6]]);
|
||||
let (np, ni) = (h[7], h[8]);
|
||||
at += 9;
|
||||
if !(np.fract() == 0.0 && ni.fract() == 0.0 && np >= 0.0 && ni >= 0.0) || at + np as usize + ni as usize > f.len() {
|
||||
return Err("Mesh-Import: Puffer beschädigt".into());
|
||||
}
|
||||
let positions = f[at..at + np as usize].to_vec();
|
||||
at += np as usize;
|
||||
// Wie `Uint32Array`: ganzzahlig modulo 2³².
|
||||
let indices = f[at..at + ni as usize].iter().map(|&x| (jsnum::to_int32(x) as u32) as f64).collect();
|
||||
at += ni as usize;
|
||||
objects.push(MeshObject { name, group, color, positions, indices });
|
||||
k += 1.0;
|
||||
}
|
||||
let report = json!({
|
||||
"format": MESH_FORMATS.get(f[1] as usize).copied().filter(|_| f[1] >= 0.0 && f[1].fract() == 0.0).unwrap_or("obj"),
|
||||
"up": if f[2] == 1.0 { "y" } else { "z" },
|
||||
"upAuto": f[3] == 1.0,
|
||||
"upCertain": f[4] == 1.0,
|
||||
"unitScale": js_num(f[5]),
|
||||
"triangles": js_num(f[6]),
|
||||
"degenerate": js_num(f[7]),
|
||||
"badFaces": js_num(f[8]),
|
||||
"truncated": f[9] == 1.0,
|
||||
"warnings": warnings,
|
||||
"objects": objects.len(),
|
||||
});
|
||||
Ok((objects, report))
|
||||
}
|
||||
|
||||
/// Verschiebung (x, y, z) je nach Platzierung (`meshShift`): `"center"` = Grundriss-Mitte auf den
|
||||
/// Nullpunkt, Unterkante auf 0; `"original"` = Datei-Koordinaten, Landeskoordinaten auf den Modell-Nullpunkt.
|
||||
pub fn mesh_shift(objects: &[MeshObject], placement: &str, origin: Option<[f64; 2]>) -> [f64; 3] {
|
||||
let (mut min_x, mut max_x, mut min_y, mut max_y, mut min_z) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY);
|
||||
for o in objects {
|
||||
let p = &o.positions;
|
||||
let mut i = 0;
|
||||
while i + 2 < p.len() {
|
||||
if p[i] < min_x {
|
||||
min_x = p[i];
|
||||
}
|
||||
if p[i] > max_x {
|
||||
max_x = p[i];
|
||||
}
|
||||
if p[i + 1] < min_y {
|
||||
min_y = p[i + 1];
|
||||
}
|
||||
if p[i + 1] > max_y {
|
||||
max_y = p[i + 1];
|
||||
}
|
||||
if p[i + 2] < min_z {
|
||||
min_z = p[i + 2];
|
||||
}
|
||||
i += 3;
|
||||
}
|
||||
}
|
||||
if !min_x.is_finite() {
|
||||
return [0.0, 0.0, 0.0];
|
||||
}
|
||||
let cx = (min_x + max_x) / 2.0;
|
||||
let cy = (min_y + max_y) / 2.0;
|
||||
if placement != "original" {
|
||||
return [-cx, -cy, -min_z];
|
||||
}
|
||||
match origin {
|
||||
Some(o) if jsmath::hypot2(cx - o[0], cy - o[1]) < jsmath::hypot2(cx, cy) => [-o[0], -o[1], 0.0],
|
||||
_ => [0.0, 0.0, 0.0],
|
||||
}
|
||||
}
|
||||
|
||||
/// Objekte → Kontext-Meshes (`layer` = Gruppe, sonst Dateiname); `group`: `"object"`, `"merge"`, `"auto"`.
|
||||
pub fn mesh_objects_to_meshes(objects: &[MeshObject], file_name: &str, placement: &str, origin: Option<[f64; 2]>, group: &str, now: f64) -> Vec<Value> {
|
||||
let base = base_name(file_name, "Mesh");
|
||||
let d = mesh_shift(objects, placement, origin);
|
||||
let stamp = stamp36(now);
|
||||
let merge = group == "merge" || (group != "object" && objects.len() > MAX_SINGLE);
|
||||
if !merge {
|
||||
return objects
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, o)| {
|
||||
let (pos, idx) = arrays(std::iter::once((o.positions.as_slice(), o.indices.as_slice())), d);
|
||||
let name = if o.name.is_empty() { format!("{base} {}", i + 1) } else { o.name.clone() };
|
||||
let layer = if o.group.is_empty() { base.as_str() } else { o.group.as_str() };
|
||||
mesh_value(format!("imported-mesh-{stamp}-{}", next_seq()), name, layer, color_hex(o.color.as_deref()), None, pos, idx)
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
group_by(objects, |o| format!("{}\u{0}{}", o.group, color_hex(o.color.as_deref()).unwrap_or_default()))
|
||||
.into_iter()
|
||||
.map(|g| {
|
||||
let first = &objects[g[0]];
|
||||
let (pos, idx) = arrays(g.iter().map(|&i| (objects[i].positions.as_slice(), objects[i].indices.as_slice())), d);
|
||||
let gname = &first.group;
|
||||
let name = format!("{base}{} ({})", if gname.is_empty() { String::new() } else { format!(": {gname}") }, g.len());
|
||||
let layer = if gname.is_empty() { base.as_str() } else { gname.as_str() };
|
||||
mesh_value(format!("imported-mesh-{stamp}-{}", next_seq()), name, layer, color_hex(first.color.as_deref()), None, pos, idx)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,937 @@
|
||||
//! Zeichnungs-Import ([K4] S4, vorher `io/dxfParser.ts::decodeImport`, `io/dxfToDrawings.ts`,
|
||||
//! `io/pdfVector.ts::pdfPageToImport`, `io/pdfLineStyles.ts`, `ui/ImportDialog.tsx::buildDrawings` und
|
||||
//! `state/useProjectFileActions.ts::runImport`): das Format-Modul (`src-tauri/fileio`, eigenes WASM) liest
|
||||
//! DXF/DWG bzw. eine PDF-Seite in einen flachen Puffer + String-Tabelle; hier wird daraus die Import-Form
|
||||
//! ([`DrawingImport`]: Konturen, Texte, Meshes, Ebenenfarben …), die Zusammenfassung für den Dialog
|
||||
//! ([`summary_json`]) und die Ops, die alles ins Projekt bringen ([`import_ops`]): neue Zeichnungsebene,
|
||||
//! Kategorien je DXF-Layer, Linienstile der PDF-Strichmuster, 2D-Zeichnungen, Kontext-Meshes — als EINE
|
||||
//! Op-Folge (ein Undo-Schritt).
|
||||
//!
|
||||
//! Aufbau des Puffers: `fileio/src/import.rs::encode` (Version 3) bzw. `fileio/src/pdf_vector.rs::encode`
|
||||
//! (Version 2). Grosse ASCII-DXF liest die App in mehreren Stücken parallel; jedes Stück ist ein eigener
|
||||
//! Puffer (`chunks`), die Teilergebnisse werden wie früher in TS zusammengeführt.
|
||||
//!
|
||||
//! Zahlen und Texte wie in der TS-Fassung (`Math.round`, `toFixed`, `String(n)`, ids aus Zeit + Zähler),
|
||||
//! Schlüsselreihenfolge der erzeugten Objekte wie die früheren Objekt-Literale.
|
||||
|
||||
use crate::grips::js_num;
|
||||
use crate::js_fmt::{js_number, to_fixed};
|
||||
use crate::jsnum;
|
||||
use crate::ops::Op;
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::cell::Cell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Kategorie generischer Importe (`GENERIC_IMPORT_CATEGORY`, „10 Situation").
|
||||
pub const GENERIC_IMPORT_CODE: &str = "10";
|
||||
/// Füllfarbe aus HATCH importierter Flächen (`DXF_HATCH_FILL`).
|
||||
const DXF_HATCH_FILL: &str = "#c8c8c8";
|
||||
/// Papier-Millimeter je PDF-Punkt.
|
||||
pub const PT_TO_MM: f64 = 25.4 / 72.0;
|
||||
|
||||
thread_local! {
|
||||
/// Laufnummer der erzeugten ids (wie die Modul-Zähler der TS-Fassung).
|
||||
static SEQ: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Nächste Laufnummer für ids.
|
||||
pub fn next_seq() -> u64 {
|
||||
SEQ.with(|s| {
|
||||
let v = s.get();
|
||||
s.set(v + 1);
|
||||
v
|
||||
})
|
||||
}
|
||||
|
||||
/// Zeitstempel als Text wie `${Date.now()}` (ganze ms).
|
||||
pub fn now_text(now: f64) -> String {
|
||||
js_number(if now.is_finite() { now.trunc() } else { 0.0 })
|
||||
}
|
||||
|
||||
/// `#rrggbb` aus einer Zahl (`(c & 0xffffff).toString(16).padStart(6, "0")`).
|
||||
pub fn hex_color(c: f64) -> String {
|
||||
format!("#{:06x}", jsnum::to_int32(c) & 0xffffff)
|
||||
}
|
||||
|
||||
// ── Import-Form ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// Echte Kurve einer Kontur (CIRCLE/ARC bzw. aus Bézier-Folgen erkannt).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Curve {
|
||||
pub circle: bool,
|
||||
pub cx: f64,
|
||||
pub cy: f64,
|
||||
pub r: f64,
|
||||
pub a0: f64,
|
||||
pub a1: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Contour {
|
||||
pub layer: String,
|
||||
/// Höhe (in 2D-Zeichnungen ohne Bedeutung).
|
||||
pub z: f64,
|
||||
pub closed: bool,
|
||||
pub filled: bool,
|
||||
pub curve: Option<Curve>,
|
||||
pub pts: Vec<[f64; 2]>,
|
||||
/// Polylinie mit Bögen: Stützpunkte + DXF-Bulge je Stützpunkt.
|
||||
pub bulge: Option<(Vec<[f64; 2]>, Vec<f64>)>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Text {
|
||||
pub layer: String,
|
||||
pub text: String,
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub height: f64,
|
||||
pub angle: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Mesh {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub layer: String,
|
||||
pub positions: Vec<f64>,
|
||||
pub indices: Vec<f64>,
|
||||
}
|
||||
|
||||
/// Ergebnis eines Zeichnungs-Imports (vorher `DxfImportResult`).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DrawingImport {
|
||||
pub contours: Vec<Contour>,
|
||||
pub texts: Vec<Text>,
|
||||
pub meshes: Vec<Mesh>,
|
||||
/// Farbe je Layer (Reihenfolge wie ein JS-Objekt mit Zuweisung).
|
||||
pub layer_colors: Map<String, Value>,
|
||||
pub layer_line_weights: Map<String, Value>,
|
||||
pub layer_fill_colors: Map<String, Value>,
|
||||
pub layer_dashes: Vec<(String, Vec<f64>)>,
|
||||
pub entity_counts: Map<String, Value>,
|
||||
pub total: f64,
|
||||
pub ins_units: Option<f64>,
|
||||
pub unit_scale: Option<f64>,
|
||||
pub layouts: Option<Vec<(String, f64)>>,
|
||||
pub layout: Option<String>,
|
||||
pub recovered: bool,
|
||||
}
|
||||
|
||||
struct Rd<'a> {
|
||||
g: &'a [f64],
|
||||
s: &'a [String],
|
||||
i: usize,
|
||||
}
|
||||
|
||||
impl Rd<'_> {
|
||||
fn num(&mut self) -> Result<f64, String> {
|
||||
let v = *self.g.get(self.i).ok_or("Importpuffer zu kurz")?;
|
||||
self.i += 1;
|
||||
Ok(v)
|
||||
}
|
||||
fn count(&mut self) -> Result<usize, String> {
|
||||
let v = self.num()?;
|
||||
if v.is_finite() && v >= 0.0 && v.fract() == 0.0 && (v as usize) <= self.g.len() {
|
||||
Ok(v as usize)
|
||||
} else if v.is_finite() && v <= 0.0 {
|
||||
Ok(0)
|
||||
} else {
|
||||
Err("Importpuffer beschädigt".into())
|
||||
}
|
||||
}
|
||||
fn str(&mut self) -> Result<String, String> {
|
||||
let k = self.num()?;
|
||||
Ok(if k >= 0.0 && k.fract() == 0.0 { self.s.get(k as usize).cloned().unwrap_or_default() } else { String::new() })
|
||||
}
|
||||
fn take(&mut self, n: usize) -> Result<&[f64], String> {
|
||||
let end = self.i.checked_add(n).filter(|&e| e <= self.g.len()).ok_or("Importpuffer zu kurz")?;
|
||||
let out = &self.g[self.i..end];
|
||||
self.i = end;
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Dekodiert einen DXF/DWG-Puffer (`import.rs::encode`, Version 3). `id_prefix` macht Mesh-ids
|
||||
/// eindeutig, wenn mehrere Stücke parallel gelesen wurden (`c0-` …).
|
||||
pub fn decode_drawing(geom: &[f64], strings: &[String], id_prefix: &str, now: f64) -> Result<DrawingImport, String> {
|
||||
let mut r = Rd { g: geom, s: strings, i: 0 };
|
||||
if r.num()? != 3.0 {
|
||||
return Err("Unbekanntes Importformat (Version).".into());
|
||||
}
|
||||
let fmt = if r.num()? == 1.0 { "DWG" } else { "DXF" };
|
||||
let ins_units = r.num()?;
|
||||
let unit_scale = r.num()?;
|
||||
let total = r.num()?;
|
||||
let mut out = DrawingImport { total, ins_units: Some(ins_units), unit_scale: Some(unit_scale), ..Default::default() };
|
||||
for _ in 0..r.count()? {
|
||||
let name = r.str()?;
|
||||
let c = r.num()?;
|
||||
out.layer_colors.insert(name, Value::String(hex_color(c)));
|
||||
}
|
||||
for _ in 0..r.count()? {
|
||||
let name = r.str()?;
|
||||
let n = r.num()?;
|
||||
out.entity_counts.insert(name, js_num(n));
|
||||
}
|
||||
let n_contours = r.count()?;
|
||||
out.contours.reserve(n_contours);
|
||||
for _ in 0..n_contours {
|
||||
let layer = r.str()?;
|
||||
let flags = jsnum::to_int32(r.num()?);
|
||||
let z = r.num()?;
|
||||
let mut c = Contour { layer, z, closed: flags & 1 != 0, filled: flags & 2 != 0, curve: None, pts: Vec::new(), bulge: None };
|
||||
if flags & 4 != 0 {
|
||||
let circle = r.num()? == 1.0;
|
||||
let v = r.take(5)?;
|
||||
c.curve = Some(Curve { circle, cx: v[0], cy: v[1], r: v[2], a0: v[3], a1: v[4] });
|
||||
}
|
||||
let np = r.count()?;
|
||||
let v = r.take(2 * np)?;
|
||||
c.pts = v.chunks_exact(2).map(|p| [p[0], p[1]]).collect();
|
||||
if flags & 8 != 0 {
|
||||
let nv = r.count()?;
|
||||
let v = r.take(3 * nv)?;
|
||||
let pts = v.chunks_exact(3).map(|p| [p[0], p[1]]).collect();
|
||||
let bulge = v.chunks_exact(3).map(|p| p[2]).collect();
|
||||
c.bulge = Some((pts, bulge));
|
||||
}
|
||||
out.contours.push(c);
|
||||
}
|
||||
for _ in 0..r.count()? {
|
||||
let layer = r.str()?;
|
||||
let text = r.str()?;
|
||||
let v = r.take(4)?;
|
||||
out.texts.push(Text { layer, text, x: v[0], y: v[1], height: v[2], angle: v[3] });
|
||||
}
|
||||
let n_meshes = r.count()?;
|
||||
let stamp = now_text(now);
|
||||
for _ in 0..n_meshes {
|
||||
let layer = r.str()?;
|
||||
let n_pos = r.count()?;
|
||||
let n_idx = r.count()?;
|
||||
let positions = r.take(n_pos * 3)?.to_vec();
|
||||
let indices = r.take(n_idx)?.to_vec();
|
||||
let name = if n_meshes > 1 { format!("{fmt}-Mesh ({layer})") } else { format!("{fmt}-Mesh") };
|
||||
out.meshes.push(Mesh { id: format!("{id_prefix}imported-{stamp}-{}", next_seq()), name, layer, positions, indices });
|
||||
}
|
||||
let mut layouts = Vec::new();
|
||||
for _ in 0..r.count()? {
|
||||
let name = r.str()?;
|
||||
layouts.push((name, r.num()?));
|
||||
}
|
||||
out.layouts = Some(layouts);
|
||||
out.recovered = r.num()? == 1.0;
|
||||
let layout_idx = r.num()?;
|
||||
out.layout = (layout_idx >= 0.0).then(|| strings.get(layout_idx as usize).cloned()).flatten();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Führt die Teilergebnisse mehrerer Stücke zusammen (vorher `dxfParserAsync.ts::mergeResults`).
|
||||
pub fn merge(parts: Vec<DrawingImport>) -> DrawingImport {
|
||||
let mut out = DrawingImport::default();
|
||||
let mut first = true;
|
||||
for p in parts {
|
||||
if first {
|
||||
out.ins_units = p.ins_units;
|
||||
out.unit_scale = p.unit_scale;
|
||||
out.layouts = p.layouts.clone();
|
||||
first = false;
|
||||
}
|
||||
out.meshes.extend(p.meshes);
|
||||
out.contours.extend(p.contours);
|
||||
out.texts.extend(p.texts);
|
||||
for (k, v) in p.layer_colors {
|
||||
out.layer_colors.insert(k, v);
|
||||
}
|
||||
for (k, v) in p.entity_counts {
|
||||
let n = out.entity_counts.get(&k).and_then(Value::as_f64).unwrap_or(0.0) + v.as_f64().unwrap_or(0.0);
|
||||
out.entity_counts.insert(k, js_num(n));
|
||||
}
|
||||
out.total += p.total;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ── Vektor-PDF ([76]) ────────────────────────────────────────────────────────
|
||||
|
||||
/// Pfad einer PDF-Seite (pt, angezeigte Seite).
|
||||
pub struct PdfPath {
|
||||
pub pts: Vec<[f64; 2]>,
|
||||
pub closed: bool,
|
||||
pub stroke: Option<String>,
|
||||
pub fill: Option<String>,
|
||||
pub line_width: f64,
|
||||
pub dash: Vec<f64>,
|
||||
pub curve: Option<Curve>,
|
||||
}
|
||||
|
||||
pub struct PdfText {
|
||||
pub text: String,
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub size: f64,
|
||||
pub angle: f64,
|
||||
pub color: String,
|
||||
}
|
||||
|
||||
pub struct PdfPage {
|
||||
pub page_count: f64,
|
||||
pub page_index: f64,
|
||||
pub width: f64,
|
||||
pub height: f64,
|
||||
pub rotate: f64,
|
||||
pub truncated: bool,
|
||||
pub images: f64,
|
||||
pub paths: Vec<PdfPath>,
|
||||
pub texts: Vec<PdfText>,
|
||||
}
|
||||
|
||||
/// Dekodiert den Puffer aus `pdf_vector.rs::encode` (Version 2).
|
||||
pub fn decode_pdf(geom: &[f64], strings: &[String]) -> Result<PdfPage, String> {
|
||||
let mut r = Rd { g: geom, s: strings, i: 0 };
|
||||
if r.num()? != 2.0 {
|
||||
return Err("Unbekanntes PDF-Importformat (Version).".into());
|
||||
}
|
||||
let page_count = r.num()?;
|
||||
let page_index = r.num()?;
|
||||
let width = r.num()?;
|
||||
let height = r.num()?;
|
||||
r.take(8)?; // MediaBox, CropBox
|
||||
let rotate = r.num()?;
|
||||
let truncated = r.num()? == 1.0;
|
||||
let images = r.num()?;
|
||||
let mut paths = Vec::new();
|
||||
for _ in 0..r.count()? {
|
||||
let flags = jsnum::to_int32(r.num()?);
|
||||
let s = r.num()?;
|
||||
let f = r.num()?;
|
||||
let line_width = r.num()?;
|
||||
let nd = r.count()?;
|
||||
let dash = r.take(nd)?.to_vec();
|
||||
let np = r.count()?;
|
||||
let pts = r.take(2 * np)?.chunks_exact(2).map(|p| [p[0], p[1]]).collect();
|
||||
let curve = if flags & 16 != 0 {
|
||||
let v = r.take(5)?;
|
||||
Some(Curve { circle: flags & 32 != 0, cx: v[0], cy: v[1], r: v[2], a0: v[3], a1: v[4] })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
paths.push(PdfPath {
|
||||
pts,
|
||||
closed: flags & 1 != 0,
|
||||
stroke: (flags & 2 != 0).then(|| hex_color(s)),
|
||||
fill: (flags & 4 != 0).then(|| hex_color(f)),
|
||||
line_width,
|
||||
dash,
|
||||
curve,
|
||||
});
|
||||
}
|
||||
let mut texts = Vec::new();
|
||||
for _ in 0..r.count()? {
|
||||
let text = r.str()?;
|
||||
let _font = r.str()?;
|
||||
let v = r.take(5)?;
|
||||
texts.push(PdfText { text, x: v[0], y: v[1], size: v[2], angle: v[3], color: hex_color(v[4]) });
|
||||
}
|
||||
Ok(PdfPage { page_count, page_index, width, height, rotate, truncated, images, paths, texts })
|
||||
}
|
||||
|
||||
/// Modell-Meter je PDF-Punkt bei Massstab 1:`scale`.
|
||||
pub fn pdf_meters_per_pt(scale: f64) -> f64 {
|
||||
(PT_TO_MM / 1000.0) * scale
|
||||
}
|
||||
|
||||
/// Strichstärke in Papier-mm, auf 0.01 mm gerundet.
|
||||
pub fn pdf_line_weight_mm(lw: f64) -> f64 {
|
||||
jsnum::round(lw * PT_TO_MM * 100.0) / 100.0
|
||||
}
|
||||
|
||||
/// Strichmuster in Papier-mm, auf 0.05 mm gerundet.
|
||||
pub fn pdf_dash_mm(dash: &[f64]) -> Vec<f64> {
|
||||
dash.iter().map(|d| jsnum::round((d * PT_TO_MM) / 0.05) * 0.05).map(|d| jsnum::round(d * 100.0) / 100.0).collect()
|
||||
}
|
||||
|
||||
/// Kurzschrift eines Strichmusters: „0.9/0.6".
|
||||
pub fn pdf_dash_label(dash_mm: &[f64]) -> String {
|
||||
dash_mm.iter().map(|d| js_number(jsnum::round(d * 100.0) / 100.0)).collect::<Vec<_>>().join("/")
|
||||
}
|
||||
|
||||
/// Ebenenname einer gestrichenen Linie.
|
||||
pub fn pdf_stroke_layer(p: &PdfPath) -> String {
|
||||
let lw = to_fixed(pdf_line_weight_mm(p.line_width), 2);
|
||||
let dash = if p.dash.is_empty() { String::new() } else { format!(" (Strich {})", pdf_dash_label(&pdf_dash_mm(&p.dash))) };
|
||||
format!("PDF {lw} {}{dash}", p.stroke.as_deref().unwrap_or("#000000"))
|
||||
}
|
||||
|
||||
fn polygon_area(pts: &[[f64; 2]]) -> f64 {
|
||||
let n = pts.len();
|
||||
let mut a = 0.0;
|
||||
let mut j = n.wrapping_sub(1);
|
||||
for i in 0..n {
|
||||
a += (pts[j][0] + pts[i][0]) * (pts[j][1] - pts[i][1]);
|
||||
j = i;
|
||||
}
|
||||
(a / 2.0).abs()
|
||||
}
|
||||
|
||||
/// Seite → Import-Form bei Massstab 1:`scale` (vorher `pdfPageToImport`).
|
||||
pub fn pdf_to_import(page: &PdfPage, scale: f64, with_texts: bool) -> DrawingImport {
|
||||
let k = pdf_meters_per_pt(scale);
|
||||
let mut out = DrawingImport::default();
|
||||
let page_area = page.width * page.height;
|
||||
let (mut n_fill, mut n_stroke) = (0.0, 0.0);
|
||||
let to_m = |pts: &[[f64; 2]]| pts.iter().map(|p| [p[0] * k, p[1] * k]).collect::<Vec<_>>();
|
||||
for p in &page.paths {
|
||||
if let Some(fill) = &p.fill {
|
||||
if p.closed && !(fill == "#ffffff" && p.stroke.is_none() && polygon_area(&p.pts) > 0.5 * page_area) {
|
||||
let layer = format!("PDF Fläche {fill}");
|
||||
out.layer_colors.insert(layer.clone(), Value::String(fill.clone()));
|
||||
out.layer_fill_colors.insert(layer.clone(), Value::String(fill.clone()));
|
||||
if !out.layer_line_weights.get(&layer).is_some_and(|v| !v.is_null()) {
|
||||
out.layer_line_weights.insert(layer.clone(), json!(0.05));
|
||||
}
|
||||
out.contours.push(Contour { layer, z: 0.0, closed: true, filled: true, curve: None, pts: to_m(&p.pts), bulge: None });
|
||||
n_fill += 1.0;
|
||||
}
|
||||
}
|
||||
if let Some(stroke) = &p.stroke {
|
||||
let layer = pdf_stroke_layer(p);
|
||||
out.layer_colors.insert(layer.clone(), Value::String(stroke.clone()));
|
||||
out.layer_line_weights.insert(layer.clone(), js_num(jsnum::max(0.05, pdf_line_weight_mm(p.line_width))));
|
||||
if !p.dash.is_empty() && !out.layer_dashes.iter().any(|(l, _)| *l == layer) {
|
||||
out.layer_dashes.push((layer.clone(), pdf_dash_mm(&p.dash)));
|
||||
}
|
||||
let curve = p.curve.as_ref().map(|c| Curve { circle: c.circle, cx: c.cx * k, cy: c.cy * k, r: c.r * k, a0: c.a0, a1: c.a1 });
|
||||
out.contours.push(Contour { layer, z: 0.0, closed: p.closed, filled: false, curve, pts: to_m(&p.pts), bulge: None });
|
||||
n_stroke += 1.0;
|
||||
}
|
||||
}
|
||||
if with_texts {
|
||||
for t in &page.texts {
|
||||
let layer = format!("PDF Text {}", t.color);
|
||||
out.layer_colors.insert(layer.clone(), Value::String(t.color.clone()));
|
||||
out.texts.push(Text { layer, text: t.text.clone(), x: t.x * k, y: t.y * k, height: t.size * k, angle: t.angle });
|
||||
}
|
||||
}
|
||||
for (key, n) in [("PATH", n_stroke), ("FILL", n_fill), ("TEXT", out.texts.len() as f64), ("IMAGE", page.images)] {
|
||||
out.entity_counts.insert(key.into(), js_num(n));
|
||||
}
|
||||
out.total = (page.paths.len() + page.texts.len()) as f64;
|
||||
out.unit_scale = Some(k);
|
||||
out.recovered = page.truncated;
|
||||
out
|
||||
}
|
||||
|
||||
/// Kurzbericht einer Seite (CLI `pdf-info`, vorher `pdfPageInfo`): Zahlen und Umriss in pt und Papier-mm.
|
||||
pub fn pdf_page_info(page: &PdfPage) -> Value {
|
||||
let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
|
||||
let mut grow = |x: f64, y: f64| {
|
||||
if x < min_x {
|
||||
min_x = x;
|
||||
}
|
||||
if y < min_y {
|
||||
min_y = y;
|
||||
}
|
||||
if x > max_x {
|
||||
max_x = x;
|
||||
}
|
||||
if y > max_y {
|
||||
max_y = y;
|
||||
}
|
||||
};
|
||||
let mut points = 0usize;
|
||||
for p in &page.paths {
|
||||
points += p.pts.len();
|
||||
for q in &p.pts {
|
||||
grow(q[0], q[1]);
|
||||
}
|
||||
}
|
||||
for t in &page.texts {
|
||||
grow(t.x, t.y);
|
||||
}
|
||||
let mut layers = Map::new();
|
||||
let mut bump = |l: String| {
|
||||
let n = layers.get(&l).and_then(Value::as_f64).unwrap_or(0.0) + 1.0;
|
||||
layers.insert(l, js_num(n));
|
||||
};
|
||||
for p in &page.paths {
|
||||
if p.stroke.is_some() {
|
||||
bump(pdf_stroke_layer(p));
|
||||
}
|
||||
if let Some(f) = &p.fill {
|
||||
bump(format!("PDF Fläche {f}"));
|
||||
}
|
||||
}
|
||||
let r = |v: f64| js_num(jsnum::round(v * 100.0) / 100.0);
|
||||
json!({
|
||||
"pages": js_num(page.page_count),
|
||||
"page": js_num(page.page_index + 1.0),
|
||||
"sizePt": [r(page.width), r(page.height)],
|
||||
"sizeMm": [r(page.width * PT_TO_MM), r(page.height * PT_TO_MM)],
|
||||
"rotate": js_num(page.rotate),
|
||||
"paths": page.paths.len(),
|
||||
"points": points,
|
||||
"texts": page.texts.len(),
|
||||
"images": js_num(page.images),
|
||||
"truncated": page.truncated,
|
||||
"bboxPt": if min_x.is_finite() { json!([r(min_x), r(min_y), r(max_x), r(max_y)]) } else { Value::Null },
|
||||
"layers": layers,
|
||||
})
|
||||
}
|
||||
|
||||
// ── Quelle (Bindung) ─────────────────────────────────────────────────────────
|
||||
|
||||
/// Woher die Import-Form kommt: `{"kind":"drawing"}` (Stücke eines DXF/DWG) oder
|
||||
/// `{"kind":"pdf","scale":100,"texts":true}`.
|
||||
#[derive(serde::Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub struct Source {
|
||||
pub kind: String,
|
||||
pub scale: Option<f64>,
|
||||
pub texts: Option<bool>,
|
||||
}
|
||||
|
||||
/// Stücke aus dem Übergabepuffer: `[n, len_0 … len_{n−1}, daten_0 …]`, String-Tabellen als JSON-Liste von Listen.
|
||||
pub fn split_chunks<'a>(geom: &'a [f64], strings: &'a [Vec<String>]) -> Result<Vec<(&'a [f64], &'a [String])>, String> {
|
||||
let n = *geom.first().ok_or("Importpuffer leer")?;
|
||||
if !(n.is_finite() && n >= 0.0 && n.fract() == 0.0 && (n as usize) < geom.len() && (n as usize) == strings.len()) {
|
||||
return Err("Importpuffer beschädigt".into());
|
||||
}
|
||||
let n = n as usize;
|
||||
let mut at = 1 + n;
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for k in 0..n {
|
||||
let len = geom[1 + k];
|
||||
if !(len.is_finite() && len >= 0.0 && len.fract() == 0.0) {
|
||||
return Err("Importpuffer beschädigt".into());
|
||||
}
|
||||
let end = at.checked_add(len as usize).filter(|&e| e <= geom.len()).ok_or("Importpuffer zu kurz")?;
|
||||
out.push((&geom[at..end], strings[k].as_slice()));
|
||||
at = end;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Import-Form aus dem Übergabepuffer (`source` sagt, wie er zu lesen ist).
|
||||
pub fn read_source(geom: &[f64], strings_json: &str, source: &Source, now: f64) -> Result<DrawingImport, String> {
|
||||
let strings: Vec<Vec<String>> = serde_json::from_str(strings_json).map_err(|e| format!("Import-Texte: {e}"))?;
|
||||
let chunks = split_chunks(geom, &strings)?;
|
||||
if source.kind == "pdf" {
|
||||
let (g, s) = chunks.first().ok_or("PDF-Seite fehlt")?;
|
||||
let page = decode_pdf(g, s)?;
|
||||
let scale = source.scale.unwrap_or(100.0);
|
||||
return Ok(pdf_to_import(&page, scale, source.texts != Some(false)));
|
||||
}
|
||||
if chunks.len() == 1 {
|
||||
return decode_drawing(chunks[0].0, chunks[0].1, "", now);
|
||||
}
|
||||
let parts = chunks.iter().enumerate().map(|(i, (g, s))| decode_drawing(g, s, &format!("c{i}-"), now)).collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(merge(parts))
|
||||
}
|
||||
|
||||
// ── Zusammenfassung für den Dialog ───────────────────────────────────────────
|
||||
|
||||
/// Unterschiedliche Layer-Namen der Konturen (`distinctLayers`).
|
||||
pub fn contour_layers(d: &DrawingImport) -> Vec<String> {
|
||||
let mut seen = HashSet::new();
|
||||
d.contours.iter().filter(|c| !c.layer.is_empty() && seen.insert(c.layer.as_str())).map(|c| c.layer.clone()).collect()
|
||||
}
|
||||
|
||||
/// Wie [`contour_layers`], über Konturen UND Texte (`distinctImportLayers`).
|
||||
pub fn import_layers(d: &DrawingImport) -> Vec<String> {
|
||||
let mut seen: HashSet<&str> = HashSet::new();
|
||||
let mut out = Vec::new();
|
||||
for l in d.contours.iter().map(|c| c.layer.as_str()).chain(d.texts.iter().map(|t| t.layer.as_str())) {
|
||||
if !l.is_empty() && seen.insert(l) {
|
||||
out.push(l.to_string());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Was der Import-Dialog zeigt: Zahlen, Layer, Diagnose, Layouts, Einheit.
|
||||
pub fn summary_json(d: &DrawingImport) -> Value {
|
||||
let mut m = Map::new();
|
||||
m.insert("contours".into(), d.contours.len().into());
|
||||
m.insert("texts".into(), d.texts.len().into());
|
||||
m.insert("meshes".into(), d.meshes.len().into());
|
||||
m.insert("layers".into(), contour_layers(d).into());
|
||||
m.insert("diagnostics".into(), json!({"entityCounts": d.entity_counts, "total": js_num(d.total)}));
|
||||
if let Some(u) = d.ins_units {
|
||||
m.insert("insUnits".into(), js_num(u));
|
||||
}
|
||||
if let Some(u) = d.unit_scale {
|
||||
m.insert("unitScale".into(), js_num(u));
|
||||
}
|
||||
if let Some(l) = &d.layouts {
|
||||
m.insert("layouts".into(), l.iter().map(|(name, n)| json!({"name": name, "entities": js_num(*n)})).collect());
|
||||
}
|
||||
if let Some(l) = &d.layout {
|
||||
m.insert("layout".into(), l.clone().into());
|
||||
}
|
||||
m.insert("recovered".into(), d.recovered.into());
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
/// Meshes als Kontext-Objekte (`ImportedMesh`, Kategorie „10 Situation"; Layer „0" ohne `layer`).
|
||||
pub fn mesh_values(d: &DrawingImport) -> Vec<Value> {
|
||||
d.meshes
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let mut o = Map::new();
|
||||
o.insert("id".into(), m.id.clone().into());
|
||||
o.insert("type".into(), "importedMesh".into());
|
||||
o.insert("name".into(), m.name.clone().into());
|
||||
o.insert("categoryCode".into(), GENERIC_IMPORT_CODE.into());
|
||||
if m.layer != "0" {
|
||||
o.insert("layer".into(), m.layer.clone().into());
|
||||
}
|
||||
o.insert("positions".into(), Value::Array(m.positions.iter().map(|&x| js_num(x)).collect()));
|
||||
o.insert("indices".into(), Value::Array(m.indices.iter().map(|&x| js_num(x)).collect()));
|
||||
Value::Object(o)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Die ganze Import-Form als JSON (Leseansicht für Tests und Diagnose; Form wie das frühere
|
||||
/// `DxfImportResult`: ein Konturen-Satz, Texte, Meshes, Ebenenfarben …).
|
||||
pub fn view_json(d: &DrawingImport) -> Value {
|
||||
let p = |q: &[f64; 2]| json!({"x": js_num(q[0]), "y": js_num(q[1])});
|
||||
let contours: Vec<Value> = d
|
||||
.contours
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let mut o = Map::new();
|
||||
o.insert("z".into(), js_num(c.z));
|
||||
o.insert("pts".into(), c.pts.iter().map(p).collect());
|
||||
o.insert("closed".into(), c.closed.into());
|
||||
o.insert("layer".into(), c.layer.clone().into());
|
||||
if c.filled {
|
||||
o.insert("filled".into(), true.into());
|
||||
}
|
||||
if let Some(k) = &c.curve {
|
||||
o.insert(
|
||||
"curve".into(),
|
||||
json!({"kind": if k.circle { "circle" } else { "arc" }, "cx": js_num(k.cx), "cy": js_num(k.cy), "r": js_num(k.r), "a0": js_num(k.a0), "a1": js_num(k.a1)}),
|
||||
);
|
||||
}
|
||||
if let Some((pts, b)) = &c.bulge {
|
||||
o.insert("bulgePolyline".into(), json!({"pts": pts.iter().map(p).collect::<Vec<_>>(), "bulge": b.iter().map(|&x| js_num(x)).collect::<Vec<_>>()}));
|
||||
}
|
||||
Value::Object(o)
|
||||
})
|
||||
.collect();
|
||||
let mut m = Map::new();
|
||||
m.insert("meshes".into(), mesh_values(d).into());
|
||||
let sets = if contours.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![json!({"type": "contourSet", "categoryCode": GENERIC_IMPORT_CODE, "contours": contours})]
|
||||
};
|
||||
m.insert("contours".into(), sets.into());
|
||||
m.insert(
|
||||
"texts".into(),
|
||||
d.texts.iter().map(|t| json!({"at": {"x": js_num(t.x), "y": js_num(t.y)}, "text": t.text, "height": js_num(t.height), "angle": js_num(t.angle), "layer": t.layer})).collect(),
|
||||
);
|
||||
m.insert("layerColors".into(), Value::Object(d.layer_colors.clone()));
|
||||
m.insert("layerLineWeights".into(), Value::Object(d.layer_line_weights.clone()));
|
||||
m.insert("layerFillColors".into(), Value::Object(d.layer_fill_colors.clone()));
|
||||
m.insert("layerDashes".into(), d.layer_dashes.iter().map(|(l, v)| (l.clone(), json!(v.iter().map(|&x| js_num(x)).collect::<Vec<_>>()))).collect::<Map<_, _>>().into());
|
||||
if let Value::Object(s) = summary_json(d) {
|
||||
for k in ["diagnostics", "insUnits", "unitScale", "layouts", "layout", "recovered"] {
|
||||
if let Some(v) = s.get(k) {
|
||||
m.insert(k.into(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
// ── Ops ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Ziel-Ebene des Imports.
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum Target {
|
||||
Existing {
|
||||
#[serde(rename = "levelId")]
|
||||
level_id: String,
|
||||
},
|
||||
New {
|
||||
name: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Entscheidung des Import-Dialogs (bzw. des CLI). Übersetzte Texte bringt die Hülle mit (der Kern kennt
|
||||
/// kein i18n): `levelNameTemplate` (Name einer neuen Zeichnung ohne Eingabe, `{n}` = Nummer),
|
||||
/// `parentName` (Elternkategorie der neuen Layer-Kategorien), `dashStyleTemplate` (Linienstil, `{pattern}`).
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Decision {
|
||||
pub target: Target,
|
||||
/// `"byLayer"` | `"active"`.
|
||||
pub category_mode: String,
|
||||
pub active_category_code: String,
|
||||
#[serde(default)]
|
||||
pub import_meshes: bool,
|
||||
/// Mitte des Ausschnitts für `placement: "viewCenter"`; fehlt = an den Datei-Koordinaten.
|
||||
#[serde(default)]
|
||||
pub view_center: Option<[f64; 2]>,
|
||||
#[serde(default)]
|
||||
pub level_name_template: String,
|
||||
#[serde(default)]
|
||||
pub parent_name: String,
|
||||
#[serde(default)]
|
||||
pub dash_style_template: String,
|
||||
}
|
||||
|
||||
/// Ergebnis von [`import_ops`].
|
||||
pub struct ImportResult {
|
||||
pub ops: Vec<Op>,
|
||||
/// Ziel-Ebene (neu angelegt oder gewählt).
|
||||
pub level_id: String,
|
||||
pub drawings: usize,
|
||||
pub meshes: usize,
|
||||
}
|
||||
|
||||
fn layer_list(root: &Map<String, Value>) -> Vec<Value> {
|
||||
root.get("layers").and_then(Value::as_array).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Gleiches Strichmuster (Toleranz 15 % bzw. 0.06 mm je Glied, `sameDash`).
|
||||
fn same_dash(a: &[f64], b: &[f64]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(v, w)| (v - w).abs() <= jsnum::max(0.06, 0.15 * jsnum::max(*v, *w)))
|
||||
}
|
||||
|
||||
/// Linienstile der PDF-Strichmuster (`planDashLineStyles`): vorhandene mit gleichem Muster oder neue.
|
||||
fn plan_dash_styles(dashes: &[(String, Vec<f64>)], existing: &[Value], name_template: &str) -> (Vec<Value>, HashMap<String, String>) {
|
||||
let mut created: Vec<Value> = Vec::new();
|
||||
let mut by_layer = HashMap::new();
|
||||
let mut used: HashSet<String> = existing.iter().filter_map(|l| l.get("id").and_then(Value::as_str).map(str::to_string)).collect();
|
||||
let dash_of = |l: &Value| -> Option<Vec<f64>> {
|
||||
let kind = l.get("kind").and_then(Value::as_str).unwrap_or("dash");
|
||||
if kind != "dash" {
|
||||
return None;
|
||||
}
|
||||
l.get("dash")?.as_array().map(|a| a.iter().map(|x| x.as_f64().unwrap_or(f64::NAN)).collect())
|
||||
};
|
||||
for (layer, dash) in dashes {
|
||||
if dash.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let known = existing.iter().chain(created.iter()).find(|l| dash_of(l).is_some_and(|d| same_dash(&d, dash)));
|
||||
if let Some(k) = known {
|
||||
by_layer.insert(layer.clone(), k.get("id").and_then(Value::as_str).unwrap_or("").to_string());
|
||||
continue;
|
||||
}
|
||||
let label = pdf_dash_label(dash);
|
||||
let mut base = String::from("pdf-dash-");
|
||||
let mut in_run = false;
|
||||
for ch in label.chars() {
|
||||
if ch.is_ascii_alphanumeric() {
|
||||
base.push(ch);
|
||||
in_run = false;
|
||||
} else if !in_run {
|
||||
base.push('_');
|
||||
in_run = true;
|
||||
}
|
||||
}
|
||||
let mut id = base.clone();
|
||||
let mut n = 2;
|
||||
while used.contains(&id) {
|
||||
id = format!("{base}-{n}");
|
||||
n += 1;
|
||||
}
|
||||
used.insert(id.clone());
|
||||
let name = name_template.replace("{pattern}", &label);
|
||||
created.push(json!({"id": id, "name": name, "weight": 0.02, "color": "#1a1a1a", "dash": dash.iter().map(|&d| js_num(d)).collect::<Vec<_>>()}));
|
||||
by_layer.insert(layer.clone(), id);
|
||||
}
|
||||
(created, by_layer)
|
||||
}
|
||||
|
||||
fn pt(p: [f64; 2], dx: f64, dy: f64) -> Value {
|
||||
json!({"x": js_num(p[0] + dx), "y": js_num(p[1] + dy)})
|
||||
}
|
||||
|
||||
/// Eine Kontur → 2D-Geometrie (`contourGeom`); `None` = zu wenig Punkte.
|
||||
fn contour_geom(c: &Contour, dx: f64, dy: f64) -> Option<Value> {
|
||||
if let Some(k) = &c.curve {
|
||||
let center = pt([k.cx, k.cy], dx, dy);
|
||||
return Some(if k.circle {
|
||||
json!({"shape": "circle", "center": center, "r": js_num(k.r)})
|
||||
} else {
|
||||
json!({"shape": "arc", "center": center, "r": js_num(k.r), "a0": js_num(k.a0), "a1": js_num(k.a1)})
|
||||
});
|
||||
}
|
||||
// VORZEICHEN: DXF-Bulge > 0 = Bogen im Gegenuhrzeigersinn (Scheitel rechts der Sehne), im Modell liegt
|
||||
// der Scheitel bei Bulge > 0 LINKS der Sehne (`kernel2d/src/bulge.rs`) — also umgekehrt.
|
||||
if let Some((pts, bulge)) = &c.bulge {
|
||||
if pts.len() >= 2 && bulge.len() == pts.len() {
|
||||
return Some(json!({
|
||||
"shape": "polyline",
|
||||
"pts": pts.iter().map(|&p| pt(p, dx, dy)).collect::<Vec<_>>(),
|
||||
"closed": c.closed,
|
||||
"bulge": bulge.iter().map(|&b| js_num(if b == 0.0 { 0.0 } else { -b })).collect::<Vec<_>>(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
if c.pts.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
if c.pts.len() == 2 && !c.closed {
|
||||
return Some(json!({"shape": "line", "a": pt(c.pts[0], dx, dy), "b": pt(c.pts[1], dx, dy)}));
|
||||
}
|
||||
Some(json!({"shape": "polyline", "pts": c.pts.iter().map(|&p| pt(p, dx, dy)).collect::<Vec<_>>(), "closed": c.closed}))
|
||||
}
|
||||
|
||||
/// Umriss aller entstehenden Zeichnungen (`drawingsBBox` über Linie, Polylinie, Kreis/Bogen, Text).
|
||||
fn bbox(d: &DrawingImport) -> Option<[f64; 4]> {
|
||||
let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
|
||||
let mut acc = |x: f64, y: f64| {
|
||||
min_x = jsnum::min(min_x, x);
|
||||
min_y = jsnum::min(min_y, y);
|
||||
max_x = jsnum::max(max_x, x);
|
||||
max_y = jsnum::max(max_y, y);
|
||||
};
|
||||
for c in &d.contours {
|
||||
if let Some(k) = &c.curve {
|
||||
acc(k.cx - k.r, k.cy - k.r);
|
||||
acc(k.cx + k.r, k.cy + k.r);
|
||||
continue;
|
||||
}
|
||||
let pts = match &c.bulge {
|
||||
Some((p, b)) if p.len() >= 2 && b.len() == p.len() => p,
|
||||
_ if c.pts.len() < 2 => continue,
|
||||
_ => &c.pts,
|
||||
};
|
||||
for p in pts {
|
||||
acc(p[0], p[1]);
|
||||
}
|
||||
}
|
||||
for t in &d.texts {
|
||||
acc(t.x, t.y);
|
||||
}
|
||||
min_x.is_finite().then_some([min_x, min_y, max_x, max_y])
|
||||
}
|
||||
|
||||
fn ensure_layers_with_parent(layers: &mut Vec<Value>, parent: Option<Value>) {
|
||||
if let Some(p) = parent {
|
||||
layers.push(p);
|
||||
}
|
||||
}
|
||||
|
||||
/// Die Ops eines bestätigten Imports auf dem Projekt `root` (vorher `runImport` + `buildDrawings`).
|
||||
pub fn import_ops(root: &Map<String, Value>, d: &DrawingImport, dec: &Decision, now: f64) -> ImportResult {
|
||||
let mut ops = Vec::new();
|
||||
let stamp = now_text(now);
|
||||
// Ziel-Ebene.
|
||||
let level_id = match &dec.target {
|
||||
Target::Existing { level_id } => level_id.clone(),
|
||||
Target::New { name } => {
|
||||
let id = format!("drawing-{stamp}");
|
||||
let n = root
|
||||
.get("drawingLevels")
|
||||
.and_then(Value::as_array)
|
||||
.map_or(0, |l| l.iter().filter(|z| z.get("kind").and_then(Value::as_str) == Some("drawing")).count())
|
||||
+ 1;
|
||||
let name = if name.trim().is_empty() { dec.level_name_template.replace("{n}", &n.to_string()) } else { name.trim().to_string() };
|
||||
ops.push(Op::Add {
|
||||
collection: "drawingLevels".into(),
|
||||
items: vec![json!({"id": id, "name": name, "kind": "drawing", "visible": true, "locked": false})],
|
||||
at: None,
|
||||
});
|
||||
id
|
||||
}
|
||||
};
|
||||
// Layer als Kategorien: fehlende als Unterkategorien einer neuen Elternkategorie.
|
||||
let mut layers = layer_list(root);
|
||||
let mut layers_changed = false;
|
||||
let by_layer = dec.category_mode == "byLayer";
|
||||
let mut code_by_layer: HashMap<String, String> = HashMap::new();
|
||||
if by_layer {
|
||||
let names = import_layers(d);
|
||||
let plan = crate::layers::plan_import(&names, &layers, &d.layer_colors, &d.layer_line_weights);
|
||||
code_by_layer = plan.code_by_layer.into_iter().collect();
|
||||
if !plan.children.is_empty() {
|
||||
let parent = json!({"code": plan.parent_code, "name": dec.parent_name, "color": "#707078", "lw": 0.18, "visible": true, "locked": false, "children": plan.children});
|
||||
ensure_layers_with_parent(&mut layers, Some(parent));
|
||||
layers_changed = true;
|
||||
}
|
||||
}
|
||||
// PDF-Strichmuster → Linienstile.
|
||||
let existing_styles = root.get("lineStyles").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
let (created, style_by_layer) = plan_dash_styles(&d.layer_dashes, &existing_styles, &dec.dash_style_template);
|
||||
if !created.is_empty() {
|
||||
ops.push(Op::Add { collection: "lineStyles".into(), items: created, at: None });
|
||||
}
|
||||
// Layer-Name → Kategorie: Plan, sonst gleichnamige Kategorie (Stand vor dem Import), sonst die aktive.
|
||||
let mut by_name: HashMap<String, String> = HashMap::new();
|
||||
for c in crate::layers::flatten(&layer_list(root)) {
|
||||
if let (Some(code), Some(name)) = (c.get("code").and_then(Value::as_str), c.get("name").and_then(Value::as_str)) {
|
||||
by_name.insert(name.to_lowercase(), code.to_string());
|
||||
}
|
||||
}
|
||||
let active = dec.active_category_code.as_str();
|
||||
let code_for = |layer: &str| -> String {
|
||||
if !(by_layer && !layer.is_empty()) {
|
||||
return active.to_string();
|
||||
}
|
||||
code_by_layer.get(layer).or_else(|| by_name.get(&layer.to_lowercase())).cloned().unwrap_or_else(|| active.to_string())
|
||||
};
|
||||
// Platzierung „viewCenter": Mitte des Umrisses auf die Mitte des Ausschnitts.
|
||||
let (dx, dy) = match (dec.view_center, bbox(d)) {
|
||||
(Some(c), Some(b)) => (c[0] - (b[0] + b[2]) / 2.0, c[1] - (b[1] + b[3]) / 2.0),
|
||||
_ => (0.0, 0.0),
|
||||
};
|
||||
let mut drawings = Vec::with_capacity(d.contours.len() + d.texts.len());
|
||||
for c in &d.contours {
|
||||
let Some(geom) = contour_geom(c, dx, dy) else { continue };
|
||||
let is_polyline = geom.get("shape").and_then(Value::as_str) == Some("polyline");
|
||||
let mut o = Map::new();
|
||||
o.insert("id".into(), format!("dxf2d-{stamp}-{}", next_seq()).into());
|
||||
o.insert("type".into(), "drawing2d".into());
|
||||
o.insert("levelId".into(), level_id.clone().into());
|
||||
o.insert("categoryCode".into(), code_for(&c.layer).into());
|
||||
o.insert("geom".into(), geom);
|
||||
if let Some(s) = style_by_layer.get(&c.layer).filter(|s| !s.is_empty()) {
|
||||
o.insert("lineStyleId".into(), s.clone().into());
|
||||
}
|
||||
if c.filled && is_polyline {
|
||||
let fill = d.layer_fill_colors.get(&c.layer).and_then(Value::as_str).unwrap_or(DXF_HATCH_FILL);
|
||||
o.insert("fillColor".into(), fill.into());
|
||||
}
|
||||
drawings.push(Value::Object(o));
|
||||
}
|
||||
for t in &d.texts {
|
||||
drawings.push(json!({
|
||||
"id": format!("dxf2d-{stamp}-{}", next_seq()),
|
||||
"type": "drawing2d",
|
||||
"levelId": level_id,
|
||||
"categoryCode": code_for(&t.layer),
|
||||
"geom": {"shape": "text", "at": pt([t.x, t.y], dx, dy), "text": t.text, "height": js_num(t.height), "angle": js_num(t.angle)},
|
||||
}));
|
||||
}
|
||||
let n_drawings = drawings.len();
|
||||
if !drawings.is_empty() {
|
||||
ops.push(Op::Add { collection: "drawings2d".into(), items: drawings, at: None });
|
||||
}
|
||||
let mut n_meshes = 0;
|
||||
if dec.import_meshes && !d.meshes.is_empty() {
|
||||
let meshes = mesh_values(d);
|
||||
n_meshes = meshes.len();
|
||||
ops.push(Op::Add { collection: "context".into(), items: meshes, at: None });
|
||||
if crate::import_context::ensure_context_categories(&mut layers, [GENERIC_IMPORT_CODE]) {
|
||||
layers_changed = true;
|
||||
}
|
||||
}
|
||||
if layers_changed {
|
||||
ops.push(Op::SetField { key: "layers".into(), value: Some(Value::Array(layers)), at: None });
|
||||
}
|
||||
ImportResult { ops, level_id, drawings: n_drawings, meshes: n_meshes }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "import_drawing_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,199 @@
|
||||
use super::*;
|
||||
use crate::import_context::{ensure_context_categories, mesh_objects_to_meshes, stamp36, MeshObject};
|
||||
|
||||
/// DXF-Puffer (Version 3) wie `fileio/src/import.rs::encode`: Layer „A" (rot) und „B", eine Linie,
|
||||
/// eine Polylinie mit Bogen, ein Kreis, eine Schraffur, ein Text, ein Mesh auf „0".
|
||||
fn sample() -> (Vec<f64>, Vec<String>) {
|
||||
let s: Vec<String> = ["A", "B", "LINE", "Wohnen", "0"].iter().map(|x| x.to_string()).collect();
|
||||
let mut g = vec![3.0, 0.0, 6.0, 1.0, 5.0];
|
||||
g.extend([2.0, 0.0, 16711680.0, 1.0, 255.0]); // Ebenenfarben
|
||||
g.extend([1.0, 2.0, 5.0]); // Entity-Zähler
|
||||
g.push(4.0); // Konturen
|
||||
g.extend([0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 4.0, 0.0]); // Linie
|
||||
g.extend([1.0, 8.0, 0.0, 3.0, 0.0, 0.0, 1.0, 0.5, 2.0, 0.0]); // Polylinie (tesselliert) …
|
||||
g.extend([2.0, 0.0, 0.0, 0.5, 2.0, 0.0, 0.0]); // … + Stützpunkte mit Bulge
|
||||
g.extend([0.0, 4.0, 0.0, 1.0, 10.0, 10.0, 2.0, 0.0, 6.283, 0.0]); // Kreis ohne Punkte
|
||||
g.extend([1.0, 3.0, 0.0, 3.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0]); // Schraffur, geschlossen
|
||||
g.extend([1.0, 1.0, 3.0, 5.0, 6.0, 0.25, 0.0]); // Text
|
||||
g.extend([1.0, 4.0, 3.0, 3.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 2.0]); // Mesh
|
||||
g.extend([0.0, 0.0, -1.0]); // Layouts, recovered, layout
|
||||
(g, s)
|
||||
}
|
||||
|
||||
fn chunked(g: &[f64]) -> Vec<f64> {
|
||||
let mut out = vec![1.0, g.len() as f64];
|
||||
out.extend_from_slice(g);
|
||||
out
|
||||
}
|
||||
|
||||
fn project() -> Map<String, Value> {
|
||||
json!({
|
||||
"drawingLevels": [{"id": "eg", "name": "EG", "kind": "floor", "visible": true, "locked": false}],
|
||||
"layers": [{"code": "20", "name": "Wände", "color": "#000", "lw": 0.5, "visible": true, "locked": false},
|
||||
{"code": "30", "name": "b", "color": "#000", "lw": 0.5, "visible": true, "locked": false}],
|
||||
"lineStyles": [], "drawings2d": [], "context": [],
|
||||
})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone()
|
||||
}
|
||||
|
||||
fn decision(v: Value) -> Decision {
|
||||
serde_json::from_value(v).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dekodiert_den_puffer() {
|
||||
let (g, s) = sample();
|
||||
let d = decode_drawing(&g, &s, "", 1000.0).unwrap();
|
||||
assert_eq!(d.contours.len(), 4);
|
||||
assert_eq!(d.texts.len(), 1);
|
||||
assert_eq!(d.meshes.len(), 1);
|
||||
assert_eq!(d.meshes[0].name, "DXF-Mesh");
|
||||
assert_eq!(d.layer_colors["A"], json!("#ff0000"));
|
||||
assert_eq!(d.layer_colors["B"], json!("#0000ff"));
|
||||
let sum = summary_json(&d);
|
||||
assert_eq!(sum["contours"], json!(4));
|
||||
assert_eq!(sum["layers"], json!(["A", "B"]));
|
||||
assert_eq!(sum["diagnostics"], json!({"entityCounts": {"LINE": 5}, "total": 5}));
|
||||
assert_eq!(sum["unitScale"], json!(1));
|
||||
assert_eq!(sum["recovered"], json!(false));
|
||||
// Kaputte Puffer: Fehler statt Panic.
|
||||
for n in 0..g.len() {
|
||||
let _ = decode_drawing(&g[..n], &s, "", 0.0);
|
||||
}
|
||||
assert!(decode_drawing(&[2.0], &s, "", 0.0).is_err());
|
||||
assert!(read_source(&[5.0, 1.0], "[[]]", &Source::default(), 0.0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ops_neue_zeichnung_mit_layer_kategorien() {
|
||||
let (g, s) = sample();
|
||||
let d = read_source(&chunked(&g), &serde_json::to_string(&vec![s]).unwrap(), &Source::default(), 0.0).unwrap();
|
||||
let dec = decision(json!({"target": {"kind": "new", "name": " "}, "categoryMode": "byLayer", "activeCategoryCode": "20",
|
||||
"importMeshes": true, "levelNameTemplate": "Zeichnung {n}", "parentName": "Import x"}));
|
||||
let r = import_ops(&project(), &d, &dec, 1234.0);
|
||||
assert_eq!(r.level_id, "drawing-1234");
|
||||
assert_eq!(r.drawings, 5);
|
||||
assert_eq!(r.meshes, 1);
|
||||
let ops: Vec<Value> = r.ops.iter().map(Op::to_json).collect();
|
||||
assert_eq!(ops[0]["items"][0], json!({"id": "drawing-1234", "name": "Zeichnung 1", "kind": "drawing", "visible": true, "locked": false}));
|
||||
let drawings = &ops[1]["items"];
|
||||
assert_eq!(drawings[0]["geom"], json!({"shape": "line", "a": {"x": 0, "y": 0}, "b": {"x": 4, "y": 0}}));
|
||||
assert_eq!(drawings[0]["categoryCode"], json!("31"));
|
||||
// Bulge: Modell = − DXF.
|
||||
assert_eq!(drawings[1]["geom"]["bulge"], json!([-0.5, 0]));
|
||||
// „B" passt (ohne Gross-/Kleinschreibung) auf die vorhandene Kategorie „b".
|
||||
assert_eq!(drawings[1]["categoryCode"], json!("30"));
|
||||
assert_eq!(drawings[2]["geom"], json!({"shape": "circle", "center": {"x": 10, "y": 10}, "r": 2}));
|
||||
assert_eq!(drawings[3]["fillColor"], json!("#c8c8c8"));
|
||||
assert_eq!(drawings[4]["geom"], json!({"shape": "text", "at": {"x": 5, "y": 6}, "text": "Wohnen", "height": 0.25, "angle": 0}));
|
||||
assert_eq!(ops[2]["collection"], json!("context"));
|
||||
assert!(ops[2]["items"][0].get("layer").is_none());
|
||||
// Kategorien: „Import x" mit A, B; dazu „05 Kontext" mit „10 Situation".
|
||||
let layers = &ops[3]["value"];
|
||||
assert_eq!(layers[2]["name"], json!("Import x"));
|
||||
assert_eq!(layers[2]["code"], json!("32"));
|
||||
assert_eq!(layers[2]["children"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(layers[2]["children"][0], json!({"code": "31", "name": "A", "color": "#ff0000", "lw": 0.18, "visible": true, "locked": false}));
|
||||
assert_eq!(layers[3]["code"], json!("05"));
|
||||
assert_eq!(layers[3]["children"][0]["code"], json!("10"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ops_aktive_kategorie_und_ausschnittsmitte() {
|
||||
let (g, s) = sample();
|
||||
let d = decode_drawing(&g, &s, "", 0.0).unwrap();
|
||||
let dec = decision(json!({"target": {"kind": "existing", "levelId": "eg"}, "categoryMode": "active", "activeCategoryCode": "20", "viewCenter": [100.0, 50.0]}));
|
||||
let r = import_ops(&project(), &d, &dec, 0.0);
|
||||
assert_eq!(r.ops.len(), 1);
|
||||
let ops = r.ops[0].to_json();
|
||||
// Umriss x 0…12, y 0…12 → Mitte (6, 6).
|
||||
assert_eq!(ops["items"][0]["geom"]["a"], json!({"x": 94, "y": 44}));
|
||||
assert!(ops["items"].as_array().unwrap().iter().all(|d| d["categoryCode"] == json!("20") && d["levelId"] == json!("eg")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_mit_strichmuster() {
|
||||
let page = PdfPage {
|
||||
page_count: 1.0,
|
||||
page_index: 0.0,
|
||||
width: 595.0,
|
||||
height: 842.0,
|
||||
rotate: 0.0,
|
||||
truncated: false,
|
||||
images: 0.0,
|
||||
paths: vec![
|
||||
PdfPath { pts: vec![[72.0, 100.0], [172.0, 100.0]], closed: false, stroke: Some("#ff0000".into()), fill: None, line_width: 0.5, dash: vec![3.0, 2.0], curve: None },
|
||||
PdfPath { pts: vec![[0.0, 0.0], [595.0, 0.0], [595.0, 842.0], [0.0, 842.0]], closed: true, stroke: None, fill: Some("#ffffff".into()), line_width: 0.0, dash: vec![], curve: None },
|
||||
],
|
||||
texts: vec![],
|
||||
};
|
||||
let d = pdf_to_import(&page, 100.0, true);
|
||||
assert_eq!(d.contours.len(), 1);
|
||||
assert_eq!(d.contours[0].layer, "PDF 0.18 #ff0000 (Strich 1.05/0.7)");
|
||||
assert_eq!(d.layer_dashes, vec![("PDF 0.18 #ff0000 (Strich 1.05/0.7)".to_string(), vec![1.05, 0.7])]);
|
||||
let dec = decision(json!({"target": {"kind": "existing", "levelId": "eg"}, "categoryMode": "byLayer", "activeCategoryCode": "20", "dashStyleTemplate": "PDF-Strich {pattern}"}));
|
||||
let r = import_ops(&project(), &d, &dec, 0.0);
|
||||
let ops: Vec<Value> = r.ops.iter().map(Op::to_json).collect();
|
||||
assert_eq!(ops[0]["items"][0], json!({"id": "pdf-dash-1_05_0_7", "name": "PDF-Strich 1.05/0.7", "weight": 0.02, "color": "#1a1a1a", "dash": [1.05, 0.7]}));
|
||||
assert_eq!(ops[1]["items"][0]["lineStyleId"], json!("pdf-dash-1_05_0_7"));
|
||||
let info = pdf_page_info(&page);
|
||||
assert_eq!(info["layers"], json!({"PDF 0.18 #ff0000 (Strich 1.05/0.7)": 1, "PDF Fläche #ffffff": 1}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kontext_kategorien() {
|
||||
let mut l = vec![json!({"code": "20"})];
|
||||
assert!(ensure_context_categories(&mut l, ["10", "31", "20"]));
|
||||
assert_eq!(l[1]["code"], json!("05"));
|
||||
assert_eq!(l[1]["children"][0]["name"], json!("Situation"));
|
||||
assert_eq!(l[2]["code"], json!("31"));
|
||||
assert!(!ensure_context_categories(&mut l, ["10"]));
|
||||
assert!(ensure_context_categories(&mut l, ["02"]));
|
||||
assert_eq!(l[1]["children"][1]["code"], json!("02"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn meshes_mitte_und_gruppen() {
|
||||
assert_eq!(stamp36(1_700_000_000_000.0), "loyw3v28");
|
||||
let obj = |g: &str, x: f64| MeshObject { name: String::new(), group: g.into(), color: Some(vec![1.0, 0.5, 0.0, 1.0]), positions: vec![x, 0.0, 1.0, x + 2.0, 2.0, 3.0], indices: vec![0.0, 1.0, 0.0] };
|
||||
let m = mesh_objects_to_meshes(&[obj("", 0.0), obj("g", 10.0)], "haus.obj", "center", None, "auto", 0.0);
|
||||
assert_eq!(m[0]["name"], json!("haus 1"));
|
||||
assert_eq!(m[0]["layer"], json!("haus"));
|
||||
assert_eq!(m[0]["color"], json!("#ff8000"));
|
||||
assert_eq!(m[0]["positions"], json!([-6, -1, 0, -4, 1, 2]));
|
||||
let m = mesh_objects_to_meshes(&[obj("g", 0.0), obj("g", 10.0)], "haus.obj", "original", None, "merge", 0.0);
|
||||
assert_eq!(m.len(), 1);
|
||||
assert_eq!(m[0]["name"], json!("haus: g (2)"));
|
||||
assert_eq!(m[0]["indices"], json!([0, 1, 0, 2, 3, 2]));
|
||||
}
|
||||
|
||||
/// Zeitmessung (nativ, von Hand): `IMPORT_BENCH=<geom-Datei>` mit `<geom>.strings.json` daneben.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn zeitmessung_kataster() {
|
||||
let Ok(path) = std::env::var("IMPORT_BENCH") else { return };
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
let geom: Vec<f64> = bytes.chunks_exact(8).map(|c| f64::from_le_bytes(c.try_into().unwrap())).collect();
|
||||
let strings: Vec<String> = serde_json::from_str(&std::fs::read_to_string(path.replace(".geom", ".strings.json")).unwrap()).unwrap();
|
||||
let t = std::time::Instant::now();
|
||||
let d = decode_drawing(&geom, &strings, "", 0.0).unwrap();
|
||||
eprintln!("dekodieren {:?}", t.elapsed());
|
||||
let mut root = project();
|
||||
root.insert("drawingLevels".into(), json!([]));
|
||||
let dec = decision(json!({"target": {"kind": "new", "name": "K"}, "categoryMode": "byLayer", "activeCategoryCode": "20", "parentName": "I"}));
|
||||
let t = std::time::Instant::now();
|
||||
let r = import_ops(&root, &d, &dec, 0.0);
|
||||
eprintln!("ops {:?}", t.elapsed());
|
||||
let t = std::time::Instant::now();
|
||||
let mut out = Vec::new();
|
||||
for op in &r.ops {
|
||||
serde_json::to_writer(&mut out, &op.to_json()).unwrap();
|
||||
}
|
||||
eprintln!("json {:?} ({} MB)", t.elapsed(), out.len() / 1_000_000);
|
||||
let mut doc = crate::document::Document::from_json(&Value::Object(root).to_string()).unwrap();
|
||||
let t = std::time::Instant::now();
|
||||
doc.commit(r.ops, None, 0.0, false).unwrap();
|
||||
eprintln!("commit {:?}", t.elapsed());
|
||||
}
|
||||
@@ -0,0 +1,719 @@
|
||||
//! IFC-Import zu echten Bauteilen ([B4], [K4] S4; vorher `io/ifcElements.ts`): baut aus dem, was das
|
||||
//! Format-Modul erkannt hat (`fileio/src/ifc_semantic.rs`: Achse, Dicke, Höhe, Umriss … in Metern),
|
||||
//! Dossier-Objekte — Geschosse, Wände (Wandtyp aus den Materialschichten, wiederverwendet oder neu),
|
||||
//! Türen/Fenster/Wanddurchbrüche, Decken (Deckentyp), Stützen, Räume; der Rest kommt als Kontext-Mesh
|
||||
//! (`import_context`). Ergebnis sind Ops auf dem Projekt (ein Undo-Schritt) und eine Zusammenfassung.
|
||||
//!
|
||||
//! Zuordnung wie in der TS-Fassung: Geschoss nach Höhe (±5 mm) wiederverwenden oder anlegen, Wand- und
|
||||
//! Deckentypen nach Schichten (Material + Dicke, ±0.5 mm), Materialien nach Namen; Zahlen auf 1e-9 m bzw.
|
||||
//! 1e-6 gerundet (`Math.round(x / step) * step`).
|
||||
|
||||
use crate::grips::js_num;
|
||||
use crate::import_context::{color_hex, color_of, context_ops, geo_shift, ifc_meshes, project_geo_origin, stamp36, IfcProduct};
|
||||
use crate::import_drawing::next_seq;
|
||||
use crate::js_fmt::js_number;
|
||||
use crate::jsnum;
|
||||
use crate::ops::Op;
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
const WALL_CATEGORY: &str = "20";
|
||||
const OPENING_CATEGORY: &str = "21";
|
||||
const CEILING_CATEGORY: &str = "30";
|
||||
const COLUMN_CATEGORY: &str = "50";
|
||||
const ROOM_CATEGORY: &str = "60";
|
||||
const ROOM_COLOR: &str = "#6b7280";
|
||||
const SIA: [&str; 6] = ["HNF", "NNF", "VF", "FF", "KGF", "AGF"];
|
||||
const LEVEL_TOL: f64 = 0.005;
|
||||
const LAYER_TOL: f64 = 0.0005;
|
||||
|
||||
fn round(x: f64, step: f64) -> f64 {
|
||||
jsnum::round(x / step) * step
|
||||
}
|
||||
|
||||
// ── Erkannte Bauteile ────────────────────────────────────────────────────────
|
||||
|
||||
struct MatLayer {
|
||||
material: String,
|
||||
thickness: f64,
|
||||
color: Option<Vec<f64>>,
|
||||
}
|
||||
|
||||
struct Info {
|
||||
storey: Option<usize>,
|
||||
color: Option<Vec<f64>>,
|
||||
type_name: Option<String>,
|
||||
layers: Vec<MatLayer>,
|
||||
classified: bool,
|
||||
}
|
||||
|
||||
struct WallData {
|
||||
info: Info,
|
||||
start: [f64; 2],
|
||||
end: [f64; 2],
|
||||
z0: f64,
|
||||
z1: f64,
|
||||
thickness: f64,
|
||||
}
|
||||
|
||||
struct OpeningData {
|
||||
info: Info,
|
||||
host: usize,
|
||||
kind: String,
|
||||
position: f64,
|
||||
width: f64,
|
||||
sill: f64,
|
||||
height: f64,
|
||||
operation: Option<String>,
|
||||
swing: f64,
|
||||
hinge: f64,
|
||||
}
|
||||
|
||||
struct SlabData {
|
||||
info: Info,
|
||||
outline: Vec<[f64; 2]>,
|
||||
holes: Vec<Vec<[f64; 2]>>,
|
||||
z0: f64,
|
||||
z1: f64,
|
||||
}
|
||||
|
||||
struct ColumnData {
|
||||
info: Info,
|
||||
center: [f64; 2],
|
||||
rotation: f64,
|
||||
round: bool,
|
||||
a: f64,
|
||||
b: f64,
|
||||
z0: f64,
|
||||
z1: f64,
|
||||
}
|
||||
|
||||
struct SpaceData {
|
||||
info: Info,
|
||||
name: Option<String>,
|
||||
long_name: Option<String>,
|
||||
sia: Option<String>,
|
||||
boundary: Vec<[f64; 2]>,
|
||||
z0: f64,
|
||||
}
|
||||
|
||||
struct Storey {
|
||||
name: String,
|
||||
elevation: f64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Elements {
|
||||
storeys: Vec<Storey>,
|
||||
walls: Vec<WallData>,
|
||||
openings: Vec<OpeningData>,
|
||||
slabs: Vec<SlabData>,
|
||||
columns: Vec<ColumnData>,
|
||||
spaces: Vec<SpaceData>,
|
||||
kept: Map<String, Value>,
|
||||
}
|
||||
|
||||
fn s_of(v: Option<&Value>) -> Option<String> {
|
||||
v.and_then(Value::as_str).map(str::to_string)
|
||||
}
|
||||
|
||||
fn info_of(e: &Value) -> Info {
|
||||
let layers = e
|
||||
.get("layers")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.map(|l| MatLayer {
|
||||
material: s_of(l.get("material")).unwrap_or_default(),
|
||||
thickness: l.get("thickness").and_then(Value::as_f64).unwrap_or(f64::NAN),
|
||||
color: color_of(l.get("color")),
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
Info {
|
||||
storey: e.get("storey").and_then(Value::as_f64).filter(|s| *s >= 0.0 && s.fract() == 0.0).map(|s| s as usize),
|
||||
color: color_of(e.get("color")),
|
||||
type_name: s_of(e.get("typeName")),
|
||||
layers,
|
||||
classified: e.get("classifications").and_then(Value::as_array).is_some_and(|a| !a.is_empty()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ringe ab `start` (je Anzahl + Punkte); `None` bei kaputten Daten.
|
||||
fn rings(v: &[f64], start: usize, count: f64) -> Option<Vec<Vec<[f64; 2]>>> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = start;
|
||||
let mut r = 0.0;
|
||||
while r < count {
|
||||
let n = *v.get(i)?;
|
||||
i += 1;
|
||||
if !(n >= 3.0) || i as f64 + 2.0 * n > v.len() as f64 {
|
||||
return None;
|
||||
}
|
||||
let n = n as usize;
|
||||
out.push((0..n).map(|k| [v[i + 2 * k], v[i + 2 * k + 1]]).collect());
|
||||
i += 2 * n;
|
||||
r += 1.0;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Erkannte Bauteile aus dem Bericht (`meta.elements`) und den Zahlen (vorher `decodeIfcElements`).
|
||||
fn decode_elements(meta: &Value, data: &[f64]) -> Elements {
|
||||
let mut out = Elements::default();
|
||||
let Some(raw) = meta.get("elements") else { return out };
|
||||
out.storeys = raw
|
||||
.get("storeys")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.map(|s| Storey { name: s_of(s.get("name")).unwrap_or_default(), elevation: s.get("elevation").and_then(Value::as_f64).unwrap_or(f64::NAN) })
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
out.kept = raw.get("kept").and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
let mut wall_index: HashMap<i64, usize> = HashMap::new();
|
||||
let mut rust_wall: i64 = 0;
|
||||
for e in raw.get("elements").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]) {
|
||||
let kind = e.get("kind").and_then(Value::as_str).unwrap_or("");
|
||||
let at = e.get("at").and_then(Value::as_f64).unwrap_or(-1.0);
|
||||
let n = e.get("n").and_then(Value::as_f64).unwrap_or(-1.0);
|
||||
let ok = at >= 0.0 && n >= 0.0 && at.fract() == 0.0 && n.fract() == 0.0 && (at + n) as usize <= data.len();
|
||||
let v: &[f64] = if ok { &data[at as usize..(at + n) as usize] } else { &[] };
|
||||
if !ok || !v.iter().all(|x| x.is_finite()) {
|
||||
if kind == "wall" {
|
||||
rust_wall += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let info = info_of(e);
|
||||
match kind {
|
||||
"wall" => {
|
||||
if v.len() == 7 {
|
||||
wall_index.insert(rust_wall, out.walls.len());
|
||||
out.walls.push(WallData { info, start: [v[0], v[1]], end: [v[2], v[3]], z0: v[4], z1: v[5], thickness: v[6] });
|
||||
}
|
||||
rust_wall += 1;
|
||||
}
|
||||
"opening" => {
|
||||
let host = e.get("host").and_then(Value::as_f64).unwrap_or(-1.0);
|
||||
let host = if host.fract() == 0.0 { wall_index.get(&(host as i64)).copied() } else { None };
|
||||
if let (Some(host), 6) = (host, v.len()) {
|
||||
out.openings.push(OpeningData {
|
||||
info,
|
||||
host,
|
||||
kind: s_of(e.get("openingKind")).unwrap_or_else(|| "hole".into()),
|
||||
position: v[0],
|
||||
width: v[1],
|
||||
sill: v[2],
|
||||
height: v[3],
|
||||
operation: s_of(e.get("operation")),
|
||||
swing: v[4].signum() * (v[4] != 0.0) as u8 as f64,
|
||||
hinge: v[5].signum() * (v[5] != 0.0) as u8 as f64,
|
||||
});
|
||||
}
|
||||
}
|
||||
"slab" => {
|
||||
if let Some(r) = v.get(2).and_then(|&c| rings(v, 3, c)) {
|
||||
if let Some((outline, holes)) = r.split_first() {
|
||||
out.slabs.push(SlabData { info, z0: v[0], z1: v[1], outline: outline.clone(), holes: holes.to_vec() });
|
||||
}
|
||||
}
|
||||
}
|
||||
"column" => {
|
||||
if v.len() == 7 {
|
||||
let round = e.get("profile").and_then(Value::as_str) == Some("round");
|
||||
out.columns.push(ColumnData { info, center: [v[0], v[1]], rotation: v[2], z0: v[3], z1: v[4], round, a: v[5], b: v[6] });
|
||||
}
|
||||
}
|
||||
"space" => {
|
||||
if let Some(mut r) = rings(v, 2, 1.0) {
|
||||
out.spaces.push(SpaceData {
|
||||
info,
|
||||
name: s_of(e.get("name")),
|
||||
long_name: s_of(e.get("longName")),
|
||||
sia: s_of(e.get("sia")),
|
||||
z0: v[0],
|
||||
boundary: r.remove(0),
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ── Aufbau ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Optionen: Dateiname (Namen der Kontext-Meshes), Gruppierung der Meshes.
|
||||
#[derive(serde::Deserialize, Default)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct IfcOptions {
|
||||
pub file_name: String,
|
||||
pub group: Option<String>,
|
||||
/// Bauteile erkennen ([B4]); sonst nur Kontext-Meshes ([B3]).
|
||||
pub elements: bool,
|
||||
}
|
||||
|
||||
pub struct IfcResult {
|
||||
pub ops: Vec<Op>,
|
||||
/// Zusammenfassung (nur mit `elements`).
|
||||
pub summary: Option<Value>,
|
||||
/// Bericht des Lesers (ohne Bauteil-Liste), Bauteile je Klasse, Dreiecke.
|
||||
pub report: Value,
|
||||
pub kept: Map<String, Value>,
|
||||
pub context_objects: usize,
|
||||
}
|
||||
|
||||
fn floor_base(l: &Value) -> f64 {
|
||||
l.get("baseElevation").and_then(Value::as_f64).unwrap_or(0.0)
|
||||
}
|
||||
|
||||
fn is_floor(l: &Value) -> bool {
|
||||
l.get("kind").and_then(Value::as_str) == Some("floor")
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> &str {
|
||||
v.get("id").and_then(Value::as_str).unwrap_or("")
|
||||
}
|
||||
|
||||
fn pt(p: [f64; 2]) -> Value {
|
||||
json!({"x": js_num(p[0]), "y": js_num(p[1])})
|
||||
}
|
||||
|
||||
/// Ops für eine Liste, an die nur neue Elemente (`is_new`) angefügt bzw. eingeschoben wurden (`fieldOps`).
|
||||
fn grown_list_ops(key: &str, old: Option<&Value>, list: Vec<(Value, bool)>) -> Vec<Op> {
|
||||
let unique_ids = |a: &[Value]| {
|
||||
let mut seen = HashSet::new();
|
||||
a.iter().all(|e| e.get("id").and_then(Value::as_str).is_some_and(|id| seen.insert(id.to_string())))
|
||||
};
|
||||
match old.and_then(Value::as_array) {
|
||||
Some(a) if unique_ids(a) => {
|
||||
let mut ops = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < list.len() {
|
||||
if !list[i].1 {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let at = i;
|
||||
let mut run = Vec::new();
|
||||
while i < list.len() && list[i].1 {
|
||||
run.push(list[i].0.clone());
|
||||
i += 1;
|
||||
}
|
||||
ops.push(Op::Add { collection: key.into(), items: run, at: Some(at) });
|
||||
}
|
||||
ops
|
||||
}
|
||||
_ => {
|
||||
if old.is_some_and(|o| o.as_array().is_some()) && !list.iter().any(|x| x.1) {
|
||||
return Vec::new();
|
||||
}
|
||||
vec![Op::SetField { key: key.into(), value: Some(Value::Array(list.into_iter().map(|x| x.0).collect())), at: None }]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Ctx<'a> {
|
||||
stamp: String,
|
||||
summary: Map<String, Value>,
|
||||
levels: Vec<(Value, bool)>,
|
||||
components: Vec<(Value, bool)>,
|
||||
hatch_id: String,
|
||||
root: &'a Map<String, Value>,
|
||||
}
|
||||
|
||||
impl Ctx<'_> {
|
||||
fn new_id(&self, kind: &str) -> String {
|
||||
format!("ifc-{kind}-{}-{}", self.stamp, next_seq())
|
||||
}
|
||||
fn bump(&mut self, k: &str) {
|
||||
let n = self.summary.get(k).and_then(Value::as_f64).unwrap_or(0.0) + 1.0;
|
||||
self.summary.insert(k.into(), js_num(n));
|
||||
}
|
||||
/// Geschosse aufsteigend nach Höhe (Index in `levels`), stabil.
|
||||
fn floors_sorted(&self) -> Vec<usize> {
|
||||
let mut f: Vec<usize> = (0..self.levels.len()).filter(|&i| is_floor(&self.levels[i].0)).collect();
|
||||
f.sort_by(|&a, &b| floor_base(&self.levels[a].0).partial_cmp(&floor_base(&self.levels[b].0)).unwrap_or(std::cmp::Ordering::Equal));
|
||||
f
|
||||
}
|
||||
fn component_for(&mut self, name: &str, color: Option<String>) -> String {
|
||||
let key = name.trim().to_lowercase();
|
||||
if let Some((c, _)) = self.components.iter().find(|(c, _)| c.get("name").and_then(Value::as_str).unwrap_or("").trim().to_lowercase() == key) {
|
||||
return id_of(c).to_string();
|
||||
}
|
||||
let id = self.new_id("component");
|
||||
let n = if name.trim().is_empty() { "IFC".to_string() } else { name.trim().to_string() };
|
||||
self.components.push((json!({"id": id, "name": n, "color": color.unwrap_or_else(|| "#b0b0b0".into()), "hatchId": self.hatch_id, "joinPriority": 50}), true));
|
||||
self.bump("components");
|
||||
id
|
||||
}
|
||||
fn component_name(&self, id: &str) -> String {
|
||||
self.components.iter().find(|(c, _)| id_of(c) == id).and_then(|(c, _)| c.get("name").and_then(Value::as_str)).unwrap_or("").trim().to_lowercase()
|
||||
}
|
||||
}
|
||||
|
||||
struct Spec {
|
||||
material: String,
|
||||
thickness: f64,
|
||||
color: Option<String>,
|
||||
}
|
||||
|
||||
fn layer_spec(e: &Info, t: f64) -> Vec<Spec> {
|
||||
let ls = &e.layers;
|
||||
let sum = ls.iter().fold(0.0, |s, l| s + l.thickness);
|
||||
if !ls.is_empty() && ls.iter().all(|l| l.thickness > 0.0) && (sum - t).abs() <= 0.005 {
|
||||
return ls.iter().map(|l| Spec { material: l.material.clone(), thickness: round(l.thickness, 1e-6), color: color_hex(l.color.as_deref()) }).collect();
|
||||
}
|
||||
let first = if ls.len() == 1 { Some(&ls[0]) } else { None };
|
||||
let color = first.and_then(|f| f.color.as_deref()).or(e.color.as_deref());
|
||||
vec![Spec { material: first.map(|f| f.material.clone()).unwrap_or_default(), thickness: round(t, 1e-6), color: color_hex(color) }]
|
||||
}
|
||||
|
||||
fn type_name(e: &Info, t: f64) -> String {
|
||||
match e.type_name.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
|
||||
Some(n) => n.to_string(),
|
||||
None => format!("IFC {} cm", js_number(round(t * 100.0, 0.1))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wand- bzw. Deckentyp mit diesen Schichten (vorhanden oder neu); `kind` = `walltype`/`ceilingtype`.
|
||||
fn type_for(ctx: &mut Ctx, types: &mut Vec<(Value, bool)>, e: &Info, t: f64, kind: &str, counter: &str) -> String {
|
||||
let spec = layer_spec(e, t);
|
||||
let name = type_name(e, t);
|
||||
let any_material = spec.iter().any(|l| !l.material.is_empty());
|
||||
let found = types.iter().find(|(ty, _)| {
|
||||
let have = ty.get("layers").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]);
|
||||
let same = have.len() == spec.len()
|
||||
&& have.iter().zip(&spec).all(|(l, w)| {
|
||||
let th = l.get("thickness").and_then(Value::as_f64).unwrap_or(f64::NAN);
|
||||
if (th - w.thickness).abs() > LAYER_TOL {
|
||||
return false;
|
||||
}
|
||||
let cname = ctx.component_name(l.get("componentId").and_then(Value::as_str).unwrap_or(""));
|
||||
w.material.is_empty() || cname == w.material.trim().to_lowercase()
|
||||
});
|
||||
same && (any_material || ty.get("name").and_then(Value::as_str) == Some(name.as_str()))
|
||||
});
|
||||
if let Some((ty, _)) = found {
|
||||
return id_of(ty).to_string();
|
||||
}
|
||||
let id = ctx.new_id(kind);
|
||||
let layers: Vec<Value> = spec.into_iter().map(|l| json!({"componentId": ctx.component_for(&l.material, l.color), "thickness": js_num(l.thickness)})).collect();
|
||||
types.push((json!({"id": id, "name": name, "layers": layers}), true));
|
||||
ctx.bump(counter);
|
||||
id
|
||||
}
|
||||
|
||||
fn list_of(root: &Map<String, Value>, key: &str) -> Vec<(Value, bool)> {
|
||||
root.get(key).and_then(Value::as_array).map(|a| a.iter().map(|v| (v.clone(), false)).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Bauteile + übrige Kontext-Meshes ins Projekt `root` (vorher `ifcElementsToProject`).
|
||||
fn elements_ops(root: &Map<String, Value>, products: &[IfcProduct], el: &Elements, opts: &IfcOptions, now: f64) -> (Vec<Op>, Value, usize) {
|
||||
let kept: f64 = el.kept.values().map(|v| v.as_f64().unwrap_or(f64::NAN)).sum();
|
||||
let mut summary = Map::new();
|
||||
for k in ["walls", "openings", "ceilings", "columns", "rooms", "floors", "wallTypes", "ceilingTypes", "components", "meshes", "classified"] {
|
||||
summary.insert(k.into(), 0.into());
|
||||
}
|
||||
summary.insert("kept".into(), js_num(kept));
|
||||
let hatches = root.get("hatches").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
let hatch_id = hatches.iter().find(|h| id_of(h) == "none").or(hatches.first()).and_then(|h| h.get("id").and_then(Value::as_str)).unwrap_or("none").to_string();
|
||||
let mut ctx = Ctx { stamp: stamp36(now), summary, levels: list_of(root, "drawingLevels"), components: list_of(root, "components"), hatch_id, root };
|
||||
|
||||
// Verschiebung bei Landeskoordinaten: gemeinsam für Bauteile und Meshes.
|
||||
let mut extra = Vec::new();
|
||||
for w in &el.walls {
|
||||
extra.extend([w.start[0], w.start[1], w.end[0], w.end[1]]);
|
||||
}
|
||||
for s in &el.slabs {
|
||||
s.outline.iter().for_each(|p| extra.extend(p));
|
||||
}
|
||||
for c in &el.columns {
|
||||
extra.extend(c.center);
|
||||
}
|
||||
for s in &el.spaces {
|
||||
s.boundary.iter().for_each(|p| extra.extend(p));
|
||||
}
|
||||
let [dx, dy] = geo_shift(products, project_geo_origin(root), &extra);
|
||||
let mv = |p: [f64; 2]| pt([round(p[0] + dx, 1e-9), round(p[1] + dy, 1e-9)]);
|
||||
|
||||
// ── Geschosse ──
|
||||
let mut top_of: HashMap<usize, f64> = HashMap::new();
|
||||
for (s, z) in el.walls.iter().map(|w| (w.info.storey, w.z1)).chain(el.columns.iter().map(|c| (c.info.storey, c.z1))) {
|
||||
if let Some(s) = s {
|
||||
let t = top_of.get(&s).copied().unwrap_or(f64::NEG_INFINITY);
|
||||
top_of.insert(s, jsnum::max(t, z));
|
||||
}
|
||||
}
|
||||
let mut storey_floor: Vec<String> = Vec::new();
|
||||
for (i, s) in el.storeys.iter().enumerate() {
|
||||
if let Some((l, _)) = ctx.levels.iter().find(|(l, _)| is_floor(l) && (floor_base(l) - s.elevation).abs() <= LEVEL_TOL) {
|
||||
storey_floor.push(id_of(l).to_string());
|
||||
continue;
|
||||
}
|
||||
let height = match (el.storeys.get(i + 1), top_of.get(&i)) {
|
||||
(Some(next), _) => next.elevation - s.elevation,
|
||||
(None, Some(&top)) if top > s.elevation + 0.5 => top - s.elevation,
|
||||
_ => 2.6,
|
||||
};
|
||||
let id = ctx.new_id("floor");
|
||||
let name = if s.name.is_empty() { format!("IFC {}", js_number(round(s.elevation, 0.001))) } else { s.name.clone() };
|
||||
let level = json!({
|
||||
"id": id, "name": name, "kind": "floor", "visible": true, "locked": false,
|
||||
"floorHeight": js_num(round(height, 1e-6)), "cutHeight": 1, "baseElevation": js_num(round(s.elevation, 1e-6)),
|
||||
});
|
||||
let floors = ctx.floors_sorted();
|
||||
let higher = floors.iter().find(|&&f| floor_base(&ctx.levels[f].0) > s.elevation).copied();
|
||||
let at = match (higher, floors.last()) {
|
||||
(Some(h), _) => h,
|
||||
(None, Some(&last)) => last + 1,
|
||||
(None, None) => 0,
|
||||
};
|
||||
ctx.levels.insert(at, (level, true));
|
||||
ctx.bump("floors");
|
||||
storey_floor.push(id);
|
||||
}
|
||||
// Geschoss eines Bauteils: aus der Datei, sonst das höchste mit OK FB ≤ Unterkante. Ergebnis: (id, Basis, Höhe).
|
||||
let floor_of = |ctx: &mut Ctx, storey: Option<usize>, z0: f64| -> (String, f64, f64) {
|
||||
let fields = |l: &Value| (id_of(l).to_string(), floor_base(l), l.get("floorHeight").and_then(Value::as_f64).unwrap_or(0.0));
|
||||
if let Some(id) = storey.and_then(|s| storey_floor.get(s)) {
|
||||
if let Some((l, _)) = ctx.levels.iter().find(|(l, _)| id_of(l) == id) {
|
||||
return fields(l);
|
||||
}
|
||||
}
|
||||
let floors = ctx.floors_sorted();
|
||||
let below: Vec<usize> = floors.iter().copied().filter(|&f| floor_base(&ctx.levels[f].0) <= z0 + LEVEL_TOL).collect();
|
||||
if let Some(&f) = below.last().or(floors.first()) {
|
||||
return fields(&ctx.levels[f].0);
|
||||
}
|
||||
let id = ctx.new_id("floor");
|
||||
let level = json!({"id": id, "name": "IFC", "kind": "floor", "visible": true, "locked": false, "floorHeight": 2.6, "cutHeight": 1, "baseElevation": 0});
|
||||
let out = fields(&level);
|
||||
ctx.levels.push((level, true));
|
||||
ctx.bump("floors");
|
||||
out
|
||||
};
|
||||
let anchor_offset = |z: f64, base: f64| round(z - base, 1e-6);
|
||||
|
||||
// ── Typen ──
|
||||
let mut wall_types = list_of(root, "wallTypes");
|
||||
let mut ceiling_types = list_of(root, "ceilingTypes");
|
||||
|
||||
// ── Wände und Öffnungen ──
|
||||
let mut walls: Vec<Value> = Vec::new();
|
||||
for w in &el.walls {
|
||||
let (fid, base, _) = floor_of(&mut ctx, w.info.storey, w.z0);
|
||||
let height = round(w.z1 - w.z0, 1e-6);
|
||||
let bottom = anchor_offset(w.z0, base);
|
||||
let id = ctx.new_id("wall");
|
||||
let wt = type_for(&mut ctx, &mut wall_types, &w.info, w.thickness, "walltype", "wallTypes");
|
||||
let mut o = json!({"id": id, "type": "wall", "floorId": fid, "categoryCode": WALL_CATEGORY, "start": mv(w.start), "end": mv(w.end), "wallTypeId": wt, "height": js_num(height)});
|
||||
if bottom.abs() > LEVEL_TOL {
|
||||
o["bottom"] = json!({"mode": "floor", "floorId": fid, "offset": js_num(bottom)});
|
||||
}
|
||||
walls.push(o);
|
||||
}
|
||||
let door_types = root.get("doorTypes").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
let window_types = root.get("windowTypes").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
let mut openings: Vec<Value> = Vec::new();
|
||||
for o in &el.openings {
|
||||
let Some(host) = walls.get(o.host) else { continue };
|
||||
let kind = if o.kind == "window" { "window" } else { "door" };
|
||||
let op = o.operation.as_deref().unwrap_or("");
|
||||
let sliding = op.contains("SLIDING");
|
||||
let leaves = if op.starts_with("DOUBLE_DOOR") { 2.0 } else { 1.0 };
|
||||
let door_type = (!op.is_empty())
|
||||
.then(|| {
|
||||
door_types.iter().find(|t| {
|
||||
t.get("kind").and_then(Value::as_str) == Some(if sliding { "schiebe" } else { "dreh" }) && t.get("leafCount").and_then(Value::as_f64) == Some(leaves)
|
||||
})
|
||||
})
|
||||
.flatten()
|
||||
.or(door_types.first());
|
||||
let wings: Option<f64> = match op {
|
||||
"SINGLE_PANEL" => Some(1.0),
|
||||
"DOUBLE_PANEL_VERTICAL" => Some(2.0),
|
||||
"TRIPLE_PANEL_VERTICAL" => Some(3.0),
|
||||
_ => None,
|
||||
};
|
||||
let window_type = wings.and_then(|w| window_types.iter().find(|t| t.get("wingCount").and_then(Value::as_f64) == Some(w))).or(window_types.first());
|
||||
let type_id = match o.kind.as_str() {
|
||||
"door" => door_type.and_then(|t| t.get("id")).and_then(Value::as_str),
|
||||
"window" => window_type.and_then(|t| t.get("id")).and_then(Value::as_str),
|
||||
_ => None,
|
||||
};
|
||||
let mut v = Map::new();
|
||||
v.insert("id".into(), ctx.new_id("opening").into());
|
||||
v.insert("type".into(), "opening".into());
|
||||
v.insert("hostWallId".into(), host["id"].clone());
|
||||
v.insert("categoryCode".into(), OPENING_CATEGORY.into());
|
||||
v.insert("kind".into(), kind.into());
|
||||
v.insert("position".into(), js_num(round(o.position, 1e-6)));
|
||||
v.insert("width".into(), js_num(round(o.width, 1e-6)));
|
||||
v.insert("height".into(), js_num(round(o.height, 1e-6)));
|
||||
v.insert("sillHeight".into(), js_num(round(o.sill, 1e-6)));
|
||||
if o.kind == "hole" {
|
||||
v.insert("doorType".into(), "wandoeffnung".into());
|
||||
}
|
||||
if let Some(t) = type_id.filter(|t| !t.is_empty()) {
|
||||
v.insert("typeId".into(), t.into());
|
||||
}
|
||||
if o.kind == "door" {
|
||||
if o.hinge != 0.0 {
|
||||
v.insert("hinge".into(), if o.hinge > 0.0 { "start" } else { "end" }.into());
|
||||
}
|
||||
if o.swing != 0.0 {
|
||||
v.insert("swing".into(), if o.swing > 0.0 { "left" } else { "right" }.into());
|
||||
}
|
||||
}
|
||||
if let (true, Some(w)) = (o.kind == "window", wings) {
|
||||
if window_type.and_then(|t| t.get("wingCount")).and_then(Value::as_f64).unwrap_or(1.0) != w {
|
||||
v.insert("wingCount".into(), js_num(w));
|
||||
}
|
||||
}
|
||||
openings.push(Value::Object(v));
|
||||
}
|
||||
|
||||
// ── Decken, Stützen, Räume ──
|
||||
let mut ceilings: Vec<Value> = Vec::new();
|
||||
let first_wall_type = root.get("wallTypes").and_then(Value::as_array).and_then(|a| a.first()).and_then(|t| t.get("id")).and_then(Value::as_str).map(str::to_string);
|
||||
for s in &el.slabs {
|
||||
let (fid, base, fh) = floor_of(&mut ctx, s.info.storey, s.z0);
|
||||
let t = s.z1 - s.z0;
|
||||
let floor_top = base + fh;
|
||||
let mut v = Map::new();
|
||||
v.insert("id".into(), ctx.new_id("ceiling").into());
|
||||
v.insert("type".into(), "ceiling".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());
|
||||
if !s.holes.is_empty() {
|
||||
v.insert("openings".into(), s.holes.iter().map(|h| h.iter().map(|&p| mv(p)).collect::<Value>()).collect());
|
||||
}
|
||||
let wt = first_wall_type.clone().or_else(|| wall_types.first().map(|(t, _)| id_of(t).to_string())).unwrap_or_default();
|
||||
v.insert("wallTypeId".into(), wt.into());
|
||||
let ct = type_for(&mut ctx, &mut ceiling_types, &s.info, t, "ceilingtype", "ceilingTypes");
|
||||
v.insert("ceilingTypeId".into(), ct.into());
|
||||
if (s.z1 - floor_top).abs() > LEVEL_TOL {
|
||||
v.insert("top".into(), json!({"mode": "floor", "floorId": fid, "offset": js_num(anchor_offset(s.z1, base))}));
|
||||
}
|
||||
ceilings.push(Value::Object(v));
|
||||
}
|
||||
let mut columns: Vec<Value> = Vec::new();
|
||||
for c in &el.columns {
|
||||
let (fid, base, _) = floor_of(&mut ctx, c.info.storey, c.z0);
|
||||
let bottom = anchor_offset(c.z0, base);
|
||||
let material = c.info.layers.first().map(|l| l.material.clone()).filter(|m| !m.is_empty());
|
||||
let mut v = Map::new();
|
||||
v.insert("id".into(), ctx.new_id("column").into());
|
||||
v.insert("type".into(), "column".into());
|
||||
v.insert("floorId".into(), fid.clone().into());
|
||||
v.insert("categoryCode".into(), COLUMN_CATEGORY.into());
|
||||
v.insert("position".into(), mv(c.center));
|
||||
v.insert(
|
||||
"profile".into(),
|
||||
if c.round {
|
||||
json!({"kind": "round", "radius": js_num(round(c.a, 1e-6))})
|
||||
} else {
|
||||
json!({"kind": "rect", "width": js_num(round(c.a, 1e-6)), "depth": js_num(round(c.b, 1e-6))})
|
||||
},
|
||||
);
|
||||
v.insert("rotation".into(), js_num(c.rotation));
|
||||
v.insert("height".into(), js_num(round(c.z1 - c.z0, 1e-6)));
|
||||
if let Some(m) = material {
|
||||
let l0 = &c.info.layers[0];
|
||||
let color = color_hex(l0.color.as_deref().or(c.info.color.as_deref()));
|
||||
v.insert("componentId".into(), ctx.component_for(&m, color).into());
|
||||
}
|
||||
if bottom.abs() > LEVEL_TOL {
|
||||
v.insert("bottom".into(), json!({"mode": "floor", "floorId": fid, "offset": js_num(bottom)}));
|
||||
}
|
||||
columns.push(Value::Object(v));
|
||||
}
|
||||
let room_color = crate::layers::flatten(root.get("layers").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]))
|
||||
.into_iter()
|
||||
.find(|c| c.get("code").and_then(Value::as_str) == Some(ROOM_CATEGORY))
|
||||
.and_then(|c| c.get("color"))
|
||||
.filter(|c| !c.is_null())
|
||||
.cloned()
|
||||
.unwrap_or_else(|| ROOM_COLOR.into());
|
||||
let rooms_before = root.get("rooms").and_then(Value::as_array).map_or(0, Vec::len);
|
||||
let mut rooms: Vec<Value> = Vec::new();
|
||||
for s in &el.spaces {
|
||||
let (fid, _, _) = floor_of(&mut ctx, s.info.storey, s.z0);
|
||||
let boundary: Vec<Value> = s.boundary.iter().map(|&p| mv(p)).collect();
|
||||
let sia_key = s.sia.as_deref().map(|x| x.trim().to_uppercase());
|
||||
let sia = SIA.iter().find(|c| Some(**c) == sia_key.as_deref()).copied().unwrap_or("HNF");
|
||||
let n = boundary.len() as f64;
|
||||
let (sx, sy) = boundary.iter().fold((0.0, 0.0), |(a, b), p| (a + p["x"].as_f64().unwrap_or(f64::NAN), b + p["y"].as_f64().unwrap_or(f64::NAN)));
|
||||
let name = [s.long_name.as_deref(), s.name.as_deref()].into_iter().flatten().find(|x| !x.is_empty()).map(str::to_string).unwrap_or_else(|| format!("Raum {}", rooms_before + rooms.len() + 1));
|
||||
rooms.push(json!({
|
||||
"id": ctx.new_id("room"), "type": "room", "floorId": fid, "categoryCode": ROOM_CATEGORY, "siaCategory": sia,
|
||||
"name": name, "boundary": boundary, "color": room_color, "stampAnchor": {"x": js_num(sx / n), "y": js_num(sy / n)},
|
||||
}));
|
||||
}
|
||||
|
||||
// ── Übrige Bauteile als Kontext-Mesh ──
|
||||
let meshes = ifc_meshes(products, &opts.file_name, opts.group.as_deref().unwrap_or("auto"), [dx, dy], now);
|
||||
let n_meshes = meshes.len();
|
||||
let classified = el.walls.iter().filter(|w| w.info.classified).count()
|
||||
+ el.openings.iter().filter(|o| o.kind != "hole" && o.info.classified).count()
|
||||
+ el.slabs.iter().filter(|s| s.info.classified).count()
|
||||
+ el.columns.iter().filter(|c| c.info.classified).count()
|
||||
+ el.spaces.iter().filter(|s| s.info.classified).count()
|
||||
+ products.iter().filter(|p| !p.classifications.is_empty()).count();
|
||||
for (k, n) in [("walls", walls.len()), ("openings", openings.len()), ("ceilings", ceilings.len()), ("columns", columns.len()), ("rooms", rooms.len()), ("meshes", n_meshes), ("classified", classified)] {
|
||||
ctx.summary.insert(k.into(), n.into());
|
||||
}
|
||||
|
||||
let mut ops = Vec::new();
|
||||
ops.extend(grown_list_ops("drawingLevels", root.get("drawingLevels"), std::mem::take(&mut ctx.levels)));
|
||||
ops.extend(grown_list_ops("components", root.get("components"), std::mem::take(&mut ctx.components)));
|
||||
ops.extend(grown_list_ops("wallTypes", root.get("wallTypes"), wall_types));
|
||||
if !ceiling_types.is_empty() || root.get("ceilingTypes").is_some_and(|v| crate::grips::truthy(Some(v))) {
|
||||
ops.extend(grown_list_ops("ceilingTypes", root.get("ceilingTypes"), ceiling_types));
|
||||
}
|
||||
if !walls.is_empty() {
|
||||
ops.push(Op::Add { collection: "walls".into(), items: walls, at: None });
|
||||
}
|
||||
for (key, items) in [("openings", openings), ("ceilings", ceilings), ("columns", columns), ("rooms", rooms)] {
|
||||
if root.get(key).is_some_and(|v| crate::grips::truthy(Some(v))) {
|
||||
if !items.is_empty() {
|
||||
ops.push(Op::Add { collection: key.into(), items, at: None });
|
||||
}
|
||||
} else {
|
||||
ops.push(Op::SetField { key: key.into(), value: Some(Value::Array(items)), at: None });
|
||||
}
|
||||
}
|
||||
if n_meshes > 0 {
|
||||
ops.extend(context_ops(root, meshes));
|
||||
}
|
||||
let _ = ctx.root;
|
||||
(ops, Value::Object(ctx.summary), n_meshes)
|
||||
}
|
||||
|
||||
/// IFC ins Projekt `root`: als Kontext-Meshes oder (mit `opts.elements`) als Bauteile.
|
||||
pub fn ifc_import(root: &Map<String, Value>, meta_json: &str, positions: &[f64], indices: &[f64], element_data: &[f64], opts: &IfcOptions, now: f64) -> Result<IfcResult, String> {
|
||||
let meta: Value = serde_json::from_str(meta_json).map_err(|e| format!("IFC-Bericht: {e}"))?;
|
||||
let products = crate::import_context::decode_ifc_products(&meta, positions, indices)?;
|
||||
let report = crate::import_context::ifc_report(&meta, &products);
|
||||
if opts.elements {
|
||||
let el = decode_elements(&meta, element_data);
|
||||
let kept = el.kept.clone();
|
||||
let (ops, summary, n) = elements_ops(root, &products, &el, opts, now);
|
||||
// Statt der Roh-Bauteile die Zusammenfassung (an derselben Stelle des Berichts).
|
||||
let mut report = report;
|
||||
if let Some(r) = report.as_object_mut() {
|
||||
r.insert("elements".into(), summary.clone());
|
||||
}
|
||||
return Ok(IfcResult { ops, summary: Some(summary), report, kept, context_objects: n });
|
||||
}
|
||||
let shift = geo_shift(&products, project_geo_origin(root), &[]);
|
||||
let meshes = ifc_meshes(&products, &opts.file_name, opts.group.as_deref().unwrap_or("auto"), shift, now);
|
||||
let n = meshes.len();
|
||||
Ok(IfcResult { ops: context_ops(root, meshes), summary: None, report, kept: Map::new(), context_objects: n })
|
||||
}
|
||||
@@ -92,6 +92,9 @@ pub mod commands;
|
||||
pub mod cmd_transform;
|
||||
pub mod cmd_edit;
|
||||
pub mod polyline_vertex;
|
||||
pub mod import_drawing;
|
||||
pub mod import_context;
|
||||
pub mod import_ifc;
|
||||
|
||||
#[cfg(feature = "web")]
|
||||
mod web;
|
||||
@@ -0,0 +1,210 @@
|
||||
//! Bindungen der Import-Umwandlung ([K4] S4, `crate::import_drawing`, `crate::import_ifc`,
|
||||
//! `crate::import_context`): das Format-Modul (eigenes WASM `pkgFileIo`) liest die Datei in flache Puffer,
|
||||
//! der Kern macht daraus Ops und wendet sie als EINEN Undo-Schritt auf das Dokument an.
|
||||
//!
|
||||
//! Antworten als JSON; Fehler (kaputter Puffer, Dokument nicht offen) als Text mit `\u{1}` vorn, von der
|
||||
//! Prüfung zurückgewiesene Änderungen als `{"problems":[…]}` (Dokument unverändert).
|
||||
|
||||
use super::document::with_doc;
|
||||
use crate::document::Document;
|
||||
use crate::import_drawing::{self as imp, Decision, Source};
|
||||
use crate::ops::Op;
|
||||
use serde_json::{json, Value};
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
fn err(e: impl std::fmt::Display) -> String {
|
||||
format!("\u{1}{e}")
|
||||
}
|
||||
|
||||
fn now_of(now_ms: f64) -> f64 {
|
||||
if now_ms.is_finite() { now_ms } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Ops als JSON-Liste, ohne die Elemente zu kopieren (grosse Importe: 10⁵ Zeichnungen).
|
||||
pub(crate) fn write_ops(out: &mut Vec<u8>, ops: &[Op]) {
|
||||
out.push(b'[');
|
||||
for (i, op) in ops.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push(b',');
|
||||
}
|
||||
match op {
|
||||
Op::Add { collection, items, at } => {
|
||||
out.extend_from_slice(b"{\"kind\":\"add\",\"collection\":");
|
||||
let _ = serde_json::to_writer(&mut *out, collection);
|
||||
out.extend_from_slice(b",\"items\":[");
|
||||
for (k, it) in items.iter().enumerate() {
|
||||
if k > 0 {
|
||||
out.push(b',');
|
||||
}
|
||||
let _ = serde_json::to_writer(&mut *out, it);
|
||||
}
|
||||
out.push(b']');
|
||||
if let Some(a) = at {
|
||||
out.extend_from_slice(format!(",\"at\":{a}").as_bytes());
|
||||
}
|
||||
out.push(b'}');
|
||||
}
|
||||
op => {
|
||||
let _ = serde_json::to_writer(&mut *out, &op.to_json());
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(b']');
|
||||
}
|
||||
|
||||
/// Ops als Benutzer-Änderung anwenden; Antwort `{"ops":[…], …extra}` bzw. `{"problems":[…]}`.
|
||||
fn commit(d: &mut Document, ops: Vec<Op>, extra: &[(&str, Value)], key: &str, now: f64) -> String {
|
||||
let mut out: Vec<u8> = b"{\"ops\":".to_vec();
|
||||
write_ops(&mut out, &ops);
|
||||
for (k, v) in extra {
|
||||
out.push(b',');
|
||||
let _ = serde_json::to_writer(&mut out, k);
|
||||
out.push(b':');
|
||||
let _ = serde_json::to_writer(&mut out, v);
|
||||
}
|
||||
out.push(b'}');
|
||||
let text = String::from_utf8(out).unwrap_or_default();
|
||||
if ops.is_empty() {
|
||||
return text;
|
||||
}
|
||||
let marks = text.contains("\\u0001");
|
||||
let key = (!key.is_empty()).then_some(key);
|
||||
match d.commit(ops, key, now, marks) {
|
||||
Ok(()) => text,
|
||||
Err(problems) => json!({ "problems": problems }).to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn source_of(json: &str) -> Source {
|
||||
serde_json::from_str(json).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Zusammenfassung eines gelesenen Zeichnungs-Imports für den Dialog (Zahlen, Layer, Diagnose, Layouts).
|
||||
/// `geom` = Stücke (`[n, len_0 …, daten …]`), `strings_json` = String-Tabellen je Stück, `source_json` s. [`Source`].
|
||||
#[wasm_bindgen]
|
||||
pub fn import_drawing_summary(geom: &[f64], strings_json: &str, source_json: &str) -> String {
|
||||
match imp::read_source(geom, strings_json, &source_of(source_json), 0.0) {
|
||||
Ok(d) => imp::summary_json(&d).to_string(),
|
||||
Err(e) => err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Die ganze Import-Form als JSON (Leseansicht für Tests/Diagnose, s. `import_drawing::view_json`).
|
||||
#[wasm_bindgen]
|
||||
pub fn import_drawing_view(geom: &[f64], strings_json: &str, source_json: &str, now_ms: f64) -> String {
|
||||
match imp::read_source(geom, strings_json, &source_of(source_json), now_of(now_ms)) {
|
||||
Ok(d) => imp::view_json(&d).to_string(),
|
||||
Err(e) => err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Nur die Meshes eines Zeichnungs-Imports als Kontext-Objekte (JSON-Liste), z. B. swissBUILDINGS3D-Kacheln.
|
||||
#[wasm_bindgen]
|
||||
pub fn import_drawing_meshes(geom: &[f64], strings_json: &str, source_json: &str, now_ms: f64) -> String {
|
||||
match imp::read_source(geom, strings_json, &source_of(source_json), now_of(now_ms)) {
|
||||
Ok(d) => Value::Array(imp::mesh_values(&d)).to_string(),
|
||||
Err(e) => err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bestätigten Zeichnungs-Import (DXF/DWG/PDF) als EINEN Undo-Schritt ins Dokument `h` übernehmen.
|
||||
/// `decision_json` s. [`Decision`]. Antwort: `{"ops":[…],"levelId":"…","drawings":n,"meshes":n}`.
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_import_drawing(h: u32, geom: &[f64], strings_json: &str, source_json: &str, decision_json: &str, key: &str, now_ms: f64) -> String {
|
||||
let now = now_of(now_ms);
|
||||
let dec: Decision = match serde_json::from_str(decision_json) {
|
||||
Ok(d) => d,
|
||||
Err(e) => return err(format!("Import-Entscheidung: {e}")),
|
||||
};
|
||||
let d = match imp::read_source(geom, strings_json, &source_of(source_json), now) {
|
||||
Ok(d) => d,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
with_doc(h, |doc| {
|
||||
let r = imp::import_ops(doc.root(), &d, &dec, now);
|
||||
let extra = [("levelId", Value::from(r.level_id)), ("drawings", r.drawings.into()), ("meshes", r.meshes.into())];
|
||||
commit(doc, r.ops, &extra, key, now)
|
||||
})
|
||||
.unwrap_or_else(|| err("Dokument nicht offen"))
|
||||
}
|
||||
|
||||
/// IFC ins Dokument `h` übernehmen (Kontext-Meshes, mit `opts.elements` Bauteile), ein Undo-Schritt.
|
||||
/// `meta` = Bericht des Lesers (JSON), dazu Positionen, Indizes und (Bauteile) die Zahlen der Erkennung.
|
||||
/// Antwort: `{"ops":[…],"report":{…},"summary":{…}|null,"kept":{…},"contextObjects":n}`.
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_import_ifc(h: u32, meta: &str, positions: &[f64], indices: &[u32], element_data: &[f64], opts_json: &str, key: &str, now_ms: f64) -> String {
|
||||
let now = now_of(now_ms);
|
||||
let opts: crate::import_ifc::IfcOptions = serde_json::from_str(opts_json).unwrap_or_default();
|
||||
let idx: Vec<f64> = indices.iter().map(|&i| i as f64).collect();
|
||||
with_doc(h, |doc| match crate::import_ifc::ifc_import(doc.root(), meta, positions, &idx, element_data, &opts, now) {
|
||||
Ok(r) => {
|
||||
let extra = [
|
||||
("report", r.report),
|
||||
("summary", r.summary.unwrap_or(Value::Null)),
|
||||
("kept", Value::Object(r.kept)),
|
||||
("contextObjects", r.context_objects.into()),
|
||||
];
|
||||
commit(doc, r.ops, &extra, key, now)
|
||||
}
|
||||
Err(e) => err(e),
|
||||
})
|
||||
.unwrap_or_else(|| err("Dokument nicht offen"))
|
||||
}
|
||||
|
||||
fn strings_of(json: &str) -> Result<Vec<String>, String> {
|
||||
serde_json::from_str(json).map_err(|e| format!("Import-Texte: {e}"))
|
||||
}
|
||||
|
||||
/// Bericht eines gelesenen Mesh-Imports (Format, Achse, Einheit, Dreiecke, Hinweise) für den Dialog.
|
||||
#[wasm_bindgen]
|
||||
pub fn mesh_import_report(flat: &[f64], strings_json: &str) -> String {
|
||||
match strings_of(strings_json).and_then(|s| crate::import_context::decode_mesh(flat, &s)) {
|
||||
Ok((_, report)) => report.to_string(),
|
||||
Err(e) => err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Optionen des Mesh-Imports: Dateiname, Platzierung (`center`|`original`), Gruppierung (`object`|`merge`|`auto`).
|
||||
#[derive(serde::Deserialize, Default)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
struct MeshOptions {
|
||||
file_name: String,
|
||||
placement: Option<String>,
|
||||
group: Option<String>,
|
||||
}
|
||||
|
||||
/// Gelesenes 3D-Modell (OBJ/STL/glTF/PLY) als Kontext-Meshes ins Dokument `h`, ein Undo-Schritt.
|
||||
/// Antwort: `{"ops":[…],"report":{…},"contextObjects":n}`.
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_import_mesh(h: u32, flat: &[f64], strings_json: &str, opts_json: &str, key: &str, now_ms: f64) -> String {
|
||||
let now = now_of(now_ms);
|
||||
let opts: MeshOptions = serde_json::from_str(opts_json).unwrap_or_default();
|
||||
let (objects, report) = match strings_of(strings_json).and_then(|s| crate::import_context::decode_mesh(flat, &s)) {
|
||||
Ok(r) => r,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
with_doc(h, |doc| {
|
||||
let origin = crate::import_context::project_geo_origin(doc.root());
|
||||
let meshes = crate::import_context::mesh_objects_to_meshes(
|
||||
&objects,
|
||||
&opts.file_name,
|
||||
opts.placement.as_deref().unwrap_or("center"),
|
||||
origin,
|
||||
opts.group.as_deref().unwrap_or("auto"),
|
||||
now,
|
||||
);
|
||||
let n = meshes.len();
|
||||
let ops = crate::import_context::context_ops(doc.root(), meshes);
|
||||
commit(doc, ops, &[("report", report), ("contextObjects", n.into())], key, now)
|
||||
})
|
||||
.unwrap_or_else(|| err("Dokument nicht offen"))
|
||||
}
|
||||
|
||||
/// Kurzbericht einer gelesenen PDF-Seite (CLI `pdf-info`): Zahlen, Ebenen, Umriss.
|
||||
#[wasm_bindgen]
|
||||
pub fn pdf_page_info(geom: &[f64], strings_json: &str) -> String {
|
||||
match strings_of(strings_json).and_then(|s| imp::decode_pdf(geom, &s)) {
|
||||
Ok(p) => imp::pdf_page_info(&p).to_string(),
|
||||
Err(e) => err(e),
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,12 @@ pub fn layers_call(name: &str, layers_json: &str, arg_json: &str, now_ms: f64) -
|
||||
let plan = layers::plan_import(&strings(&arg["names"]), &cats, &obj(&arg["colors"]), &obj(&arg["weights"]));
|
||||
json!({"children": plan.children, "parentCode": plan.parent_code, "codeByLayer": plan.code_by_layer})
|
||||
}
|
||||
// Fehlende Kontext-Kategorien ergänzen (`ensureContextCategories`); `null` = nichts fehlt.
|
||||
"ensureContext" => {
|
||||
let mut cats = cats;
|
||||
let codes = strings(&arg);
|
||||
if crate::import_context::ensure_context_categories(&mut cats, codes.iter().map(String::as_str)) { Value::Array(cats) } else { Value::Null }
|
||||
}
|
||||
_ => return String::new(),
|
||||
};
|
||||
out.to_string()
|
||||
|
||||
@@ -40,6 +40,7 @@ mod text_layout;
|
||||
mod grips;
|
||||
mod project_refs;
|
||||
mod commands;
|
||||
mod import;
|
||||
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
|
||||
@@ -13,6 +13,41 @@ import { fieldOps } from "./opsBuild";
|
||||
import { opsMutation } from "./opsBuild";
|
||||
import type { ProjectMutation } from "./opsBuild";
|
||||
|
||||
/**
|
||||
* Gelesene Zeichnungs-Datei für den Kern ([K4] S4): Puffer des Format-Moduls, je Stück (paralleles Lesen
|
||||
* grosser DXF) hintereinander als `[n, len_0 … len_{n−1}, daten …]`, die String-Tabellen je Stück, und wie
|
||||
* der Puffer zu lesen ist (DXF/DWG bzw. PDF-Seite mit Massstab).
|
||||
*/
|
||||
export interface ImportSource {
|
||||
geom: Float64Array;
|
||||
strings: string[][];
|
||||
source: { kind: "drawing" } | { kind: "pdf"; scale: number; texts?: boolean };
|
||||
}
|
||||
|
||||
/** Entscheidung des Import-Dialogs (bzw. CLI) für {@link ProjectDocument.importDrawing}; Texte schon übersetzt. */
|
||||
export interface DrawingImportDecision {
|
||||
target: { kind: "existing"; levelId: string } | { kind: "new"; name: string };
|
||||
categoryMode: "byLayer" | "active";
|
||||
activeCategoryCode: string;
|
||||
importMeshes: boolean;
|
||||
/** Mitte des Ausschnitts (Platzierung „viewCenter"); fehlt = an den Datei-Koordinaten. */
|
||||
viewCenter?: [number, number];
|
||||
/** Name einer neuen Zeichnung ohne Eingabe, `{n}` = Nummer. */
|
||||
levelNameTemplate?: string;
|
||||
/** Elternkategorie der neuen Layer-Kategorien. */
|
||||
parentName?: string;
|
||||
/** Name neuer Linienstile aus PDF-Strichmustern, `{pattern}` = Muster. */
|
||||
dashStyleTemplate?: string;
|
||||
}
|
||||
|
||||
/** Rohergebnis des IFC-Lesers (`fileio`): Bericht (JSON), Positionen, Indizes, Zahlen der Bauteil-Erkennung. */
|
||||
export interface IfcFlatInput {
|
||||
meta: string;
|
||||
positions: Float64Array;
|
||||
indices: Uint32Array;
|
||||
elementData?: Float64Array;
|
||||
}
|
||||
|
||||
/** Ergebnis des Ladens einer Projektdatei ({@link ProjectDocument.loadFile}). */
|
||||
export type LoadFileResult =
|
||||
| { ok: true; project: Project; warnings: string[]; migratedFrom: number | null }
|
||||
@@ -308,6 +343,48 @@ export class ProjectDocument {
|
||||
return { project, ops: r.ops };
|
||||
}
|
||||
|
||||
/**
|
||||
* Kern-Aufruf, der Ops rechnet und gleich als Benutzer-Änderung anwendet (Importe, [K4] S4): `call`
|
||||
* bekommt das Handle und liefert `{ops, …}`, `{problems}` oder einen Fehlertext mit `\u0001` vorn (wirft).
|
||||
* Die Leseansicht wird mit den angewendeten Ops nachgeführt; die übrigen Felder kommen unverändert zurück.
|
||||
*/
|
||||
private commitCore<R extends object>(base: Project, call: (h: number) => string): ({ project: Project; ops: CoreOp[] } & R) | { problems: string[] } {
|
||||
this.ensure(base);
|
||||
if (!this.handle) return { problems: ["Projekt-Dokument im Kern nicht offen."] };
|
||||
const out = call(this.handle);
|
||||
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
|
||||
const r = fromMarkedJson<({ ops: CoreOp[] } & R) | { problems: string[] }>(out);
|
||||
if ("problems" in r) return r;
|
||||
const project = r.ops.length ? applyOps(base, r.ops) : base;
|
||||
this.mirror = project;
|
||||
return { ...r, project };
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeichnungs-Import (DXF/DWG/PDF, [K4] S4): der Kern wandelt die gelesene Datei (`src`, Puffer des
|
||||
* Format-Moduls) nach der Entscheidung des Dialogs in Ops (Zeichnungsebene, Kategorien je Layer,
|
||||
* Linienstile, 2D-Zeichnungen, Kontext-Meshes) und wendet sie als EINEN Undo-Schritt an.
|
||||
*/
|
||||
importDrawing(base: Project, src: ImportSource, decision: DrawingImportDecision, now: number) {
|
||||
return this.commitCore<{ levelId: string; drawings: number; meshes: number }>(base, (h) =>
|
||||
core().doc_import_drawing(h, src.geom, JSON.stringify(src.strings), JSON.stringify(src.source), JSON.stringify(decision), "", now),
|
||||
);
|
||||
}
|
||||
|
||||
/** IFC-Import ([B3]/[B4], [K4] S4): Kontext-Meshes bzw. (`opts.elements`) Bauteile, ein Undo-Schritt. */
|
||||
importIfc(base: Project, flat: IfcFlatInput, opts: { fileName: string; group?: string; elements?: boolean }, now: number) {
|
||||
return this.commitCore<{ report: Record<string, unknown>; summary: Record<string, number> | null; kept: Record<string, number>; contextObjects: number }>(base, (h) =>
|
||||
core().doc_import_ifc(h, flat.meta, flat.positions, flat.indices, flat.elementData ?? new Float64Array(0), JSON.stringify(opts), "", now),
|
||||
);
|
||||
}
|
||||
|
||||
/** Mesh-Import (OBJ/STL/glTF/PLY, [C11], [K4] S4): Kontext-Meshes, ein Undo-Schritt. */
|
||||
importMesh(base: Project, flat: { flat: Float64Array; strings: string[] }, opts: { fileName: string; placement?: string; group?: string }, now: number) {
|
||||
return this.commitCore<{ report: Record<string, unknown>; contextObjects: number }>(base, (h) =>
|
||||
core().doc_import_mesh(h, flat.flat, JSON.stringify(flat.strings), JSON.stringify(opts), "", now),
|
||||
);
|
||||
}
|
||||
|
||||
/** Abfrage eines Befehls zwischen den Schritten (`doc_cmd_query`: Treffer, Vorschau-Formen), JSON-Antwort. */
|
||||
cmdQuery<T>(req: object): T {
|
||||
if (!this.handle) throw new Error("Kern-Abfrage „cmdQuery“: Dokument nicht offen");
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
// VORÜBERGEHEND ([K4] S4): Zeitmessung Kataster-Import alt (TS-Umwandlung + Commit) ↔ neu (Kern).
|
||||
import "../engine/fileioWasm.setup";
|
||||
import { describe, it } from "vitest";
|
||||
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { applyOps } from "../core/ops";
|
||||
import type { CoreOp } from "../core/ops";
|
||||
import { addItems, fieldOps } from "../core/opsBuild";
|
||||
import { ProjectDocument } from "../core/document";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { flattenCategories } from "../model/types";
|
||||
import { decodeImport, importDrawingFlat } from "./dxfParser";
|
||||
import { countContours, distinctImportLayers, distinctLayers, planImportCategories } from "./dxfToDrawings";
|
||||
import { buildDrawings } from "../ui/ImportDialog";
|
||||
import { planDashLineStyles } from "./pdfLineStyles";
|
||||
import { packChunks, importSummary } from "./importSource";
|
||||
import { core } from "../engine/coreWasm";
|
||||
|
||||
const FX = process.env.DOSSIER_PARITY_FX ?? "";
|
||||
const file = join(FX, "kataster150k.dxf");
|
||||
|
||||
describe.skipIf(!existsSync(file))("Zeitmessung Kataster 150k", { timeout: 600_000 }, () => {
|
||||
it("alt ↔ neu", () => {
|
||||
const bytes = new Uint8Array(readFileSync(file));
|
||||
const runs = Number(process.env.BENCH_RUNS ?? 3);
|
||||
for (let run = 0; run < runs; run++) {
|
||||
let t0 = performance.now();
|
||||
const flat = importDrawingFlat(bytes);
|
||||
const tParse = performance.now() - t0;
|
||||
if (process.env.BENCH_DUMP) {
|
||||
writeFileSync(join(FX, "k150.geom"), new Uint8Array(flat.geom.buffer, flat.geom.byteOffset, flat.geom.byteLength));
|
||||
writeFileSync(join(FX, "k150.strings.json"), JSON.stringify(flat.strings));
|
||||
}
|
||||
// alt
|
||||
t0 = performance.now();
|
||||
const parsed = decodeImport(flat.geom, flat.strings);
|
||||
void [countContours(parsed.contours), distinctLayers(parsed.contours)];
|
||||
const tOldDecode = performance.now() - t0;
|
||||
t0 = performance.now();
|
||||
const base = sampleProject;
|
||||
const levelId = "drawing-1";
|
||||
const ops: CoreOp[] = addItems("drawingLevels", [{ id: levelId, name: "K", kind: "drawing", visible: true, locked: false }]);
|
||||
let p = applyOps(base, ops);
|
||||
const plan = planImportCategories(distinctImportLayers(parsed.contours, parsed.texts ?? []), flattenCategories(base.layers), "Import", parsed.layerColors, parsed.layerLineWeights);
|
||||
const lops = fieldOps(p, "layers", [...p.layers, plan.parent!]);
|
||||
p = applyOps(p, lops);
|
||||
const dash = planDashLineStyles(parsed.layerDashes, base.lineStyles);
|
||||
const drawings = buildDrawings({ target: { kind: "existing", levelId }, categoryMode: "byLayer", importMeshes: false, placement: "origin", parsed }, levelId, base, "20", plan.codeByLayer, dash.styleByLayer);
|
||||
const all = [...ops, ...lops, ...addItems("drawings2d", drawings)];
|
||||
const tOldConvert = performance.now() - t0;
|
||||
const docOld = new ProjectDocument(base);
|
||||
t0 = performance.now();
|
||||
const rOld = docOld.commit(base, all, undefined, Date.now());
|
||||
const tOldCommit = performance.now() - t0;
|
||||
if ("problems" in rOld) throw new Error(rOld.problems[0]);
|
||||
docOld.close();
|
||||
// neu
|
||||
t0 = performance.now();
|
||||
const src = packChunks([flat]);
|
||||
const summary = importSummary(src);
|
||||
const tNewSummary = performance.now() - t0;
|
||||
const docNew = new ProjectDocument(base);
|
||||
t0 = performance.now();
|
||||
const r = docNew.importDrawing(base, src, { target: { kind: "new", name: "K" }, categoryMode: "byLayer", activeCategoryCode: "20", importMeshes: false, parentName: "Import" }, Date.now());
|
||||
const tNewImport = performance.now() - t0;
|
||||
if ("problems" in r) throw new Error(r.problems[0]);
|
||||
// Aufteilung: Kern-Aufruf, JSON.parse, applyOps.
|
||||
const docX = new ProjectDocument(base);
|
||||
void docX.json();
|
||||
t0 = performance.now();
|
||||
const out = core().doc_import_drawing(docX.id, src.geom, JSON.stringify(src.strings), JSON.stringify(src.source), JSON.stringify({ target: { kind: "new", name: "K" }, categoryMode: "byLayer", activeCategoryCode: "20", importMeshes: false, parentName: "Import" }), "", Date.now());
|
||||
const tCore = performance.now() - t0;
|
||||
t0 = performance.now();
|
||||
const parsedOut = JSON.parse(out) as { ops: CoreOp[] };
|
||||
const tParseOut = performance.now() - t0;
|
||||
t0 = performance.now();
|
||||
applyOps(base, parsedOut.ops);
|
||||
const tApply = performance.now() - t0;
|
||||
console.log(` Kern ${tCore.toFixed(0)} ms (${(out.length / 1e6).toFixed(1)} MB JSON), JSON.parse ${tParseOut.toFixed(0)} ms, applyOps ${tApply.toFixed(0)} ms`);
|
||||
docX.close();
|
||||
docNew.close();
|
||||
const f = (x: number) => x.toFixed(0).padStart(5);
|
||||
console.log(
|
||||
`Lauf ${run}: ${summary.contours + summary.texts} Elemente | Lesen ${f(tParse)} ms | alt: Dekodieren ${f(tOldDecode)} + Umwandeln ${f(tOldConvert)} + Commit ${f(tOldCommit)} = ${f(tOldDecode + tOldConvert + tOldCommit)} ms | neu: Zusammenfassung ${f(tNewSummary)} + Import ${f(tNewImport)} = ${f(tNewSummary + tNewImport)} ms`,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,379 @@
|
||||
// VORÜBERGEHEND ([K4] S4): Gleichheit alte TS-Umwandlung ↔ Kern-Import (`ProjectDocument.importDrawing/
|
||||
// importIfc/importMesh`). Gleiches Projekt (bis auf erzeugte ids), gleiche Zusammenfassung/Berichte. Wird mit
|
||||
// der TS-Fassung gelöscht. Fixtures: `DOSSIER_PARITY_FX` (Verzeichnis), sonst übersprungen.
|
||||
|
||||
import "../engine/fileioWasm.setup";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { applyOps } from "../core/ops";
|
||||
import type { CoreOp } from "../core/ops";
|
||||
import { addItems, fieldOps } from "../core/opsBuild";
|
||||
import { ProjectDocument } from "../core/document";
|
||||
import type { DrawingImportDecision } from "../core/document";
|
||||
import { emptyProject, sampleProject } from "../model/sampleProject";
|
||||
import type { ContextObject, ContourSet, Drawing2D, ImportedMesh, ImportedText, Project, Vec2 } from "../model/types";
|
||||
import { flattenCategories } from "../model/types";
|
||||
import { ensureContextCategories } from "../model/contextCategories";
|
||||
import { projectGeoOrigin } from "../model/geoRebase";
|
||||
import { decodeImport, importDrawingFlat, parseDxf, type DxfImportResult } from "./dxfParser";
|
||||
import { countContours, distinctImportLayers, distinctLayers, planImportCategories } from "./dxfToDrawings";
|
||||
import { buildDrawings } from "../ui/ImportDialog";
|
||||
import { planDashLineStyles } from "./pdfLineStyles";
|
||||
import { pdfPageInfo, pdfPageToImport, readPdfVectorPage } from "./pdfVector";
|
||||
import { packChunks, importSummary } from "./importSource";
|
||||
import { fileioLoaded } from "../engine/fileioWasm";
|
||||
import { t } from "../i18n";
|
||||
import { ifcElementsToProject, readIfcElements } from "./ifcElements";
|
||||
import { ifcToImportedMeshes, importIfcFlat, readIfc } from "./ifcImport";
|
||||
import { decodeMesh, importMeshFlat, meshObjectsToImportedMeshes, type MeshUnit, type MeshUp } from "./meshImport";
|
||||
import { core } from "../engine/coreWasm";
|
||||
|
||||
const FX = process.env.DOSSIER_PARITY_FX ?? "";
|
||||
const have = FX !== "" && existsSync(FX);
|
||||
const fx = (n: string) => new Uint8Array(readFileSync(join(FX, n)));
|
||||
|
||||
/** Erzeugte ids (Zeit + Zähler) durch Platzhalter in Reihenfolge des ersten Auftretens ersetzen. */
|
||||
function normalize(v: unknown): string {
|
||||
const text = JSON.stringify(v);
|
||||
const map = new Map<string, string>();
|
||||
return text.replace(
|
||||
/"((?:c\d+-)?imported-\d+-\d+|dxf2d-\d+-\d+|drawing-\d+|ifc-[a-z]+-[0-9a-z]+-\d+|imported-ifc-[0-9a-z]+-\d+|imported-mesh-[0-9a-z]+-\d+)"/g,
|
||||
(_, id: string) => {
|
||||
if (!map.has(id)) map.set(id, `#${map.size}`);
|
||||
return `"${map.get(id)}"`;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** Schlüssel sortiert (Leseansicht ↔ Dokument: Felder mit `undefined` behalten in TS ihre Stelle). */
|
||||
function canon(v: unknown): unknown {
|
||||
if (Array.isArray(v)) return v.map(canon);
|
||||
if (v && typeof v === "object") return Object.fromEntries(Object.keys(v).sort().filter((k) => (v as Record<string, unknown>)[k] !== undefined).map((k) => [k, canon((v as Record<string, unknown>)[k])]));
|
||||
return v;
|
||||
}
|
||||
|
||||
// ── Alte App-Fassung (`useProjectFileActions.runImportSteps`, Kopie der privaten Helfer) ─────────
|
||||
|
||||
function drawingsBBox(drawings: Drawing2D[]) {
|
||||
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
|
||||
const acc = (x: number, y: number) => {
|
||||
minX = Math.min(minX, x); minY = Math.min(minY, y);
|
||||
maxX = Math.max(maxX, x); maxY = Math.max(maxY, y);
|
||||
};
|
||||
for (const d of drawings) {
|
||||
const g = d.geom;
|
||||
if (g.shape === "line") { acc(g.a.x, g.a.y); acc(g.b.x, g.b.y); }
|
||||
else if (g.shape === "polyline") for (const p of g.pts) acc(p.x, p.y);
|
||||
else if (g.shape === "circle" || g.shape === "arc") { acc(g.center.x - g.r, g.center.y - g.r); acc(g.center.x + g.r, g.center.y + g.r); }
|
||||
else if (g.shape === "text") acc(g.at.x, g.at.y);
|
||||
}
|
||||
return Number.isFinite(minX) ? { minX, minY, maxX, maxY } : null;
|
||||
}
|
||||
|
||||
function translateDrawing(d: Drawing2D, dx: number, dy: number): Drawing2D {
|
||||
const mv = (p: Vec2): Vec2 => ({ x: p.x + dx, y: p.y + dy });
|
||||
const g = d.geom;
|
||||
switch (g.shape) {
|
||||
case "line": return { ...d, geom: { ...g, a: mv(g.a), b: mv(g.b) } };
|
||||
case "polyline": return { ...d, geom: { ...g, pts: g.pts.map(mv) } };
|
||||
case "circle": return { ...d, geom: { ...g, center: mv(g.center) } };
|
||||
case "arc": return { ...d, geom: { ...g, center: mv(g.center) } };
|
||||
case "text": return { ...d, geom: { ...g, at: mv(g.at) } };
|
||||
default: return d;
|
||||
}
|
||||
}
|
||||
|
||||
interface Case {
|
||||
target: DrawingImportDecision["target"];
|
||||
categoryMode: "byLayer" | "active";
|
||||
importMeshes: boolean;
|
||||
viewCenter?: [number, number];
|
||||
}
|
||||
|
||||
function oldApp(project: Project, parsed: DxfImportResult, c: Case, active: string, parentName: string): Project {
|
||||
let p = project;
|
||||
const apply = (ops: CoreOp[]) => {
|
||||
p = applyOps(p, ops);
|
||||
};
|
||||
let levelId: string;
|
||||
if (c.target.kind === "new") {
|
||||
const id = `drawing-${Date.now()}`;
|
||||
const n = p.drawingLevels.filter((z) => z.kind === "drawing").length + 1;
|
||||
apply(addItems("drawingLevels", [{ id, name: c.target.name.trim() || t("default.drawingName", { n }), kind: "drawing", visible: true, locked: false }]));
|
||||
levelId = id;
|
||||
} else levelId = c.target.levelId;
|
||||
let codeByLayer: Map<string, string> | undefined;
|
||||
if (c.categoryMode === "byLayer") {
|
||||
const plan = planImportCategories(distinctImportLayers(parsed.contours, parsed.texts ?? []), flattenCategories(project.layers), parentName, parsed.layerColors, parsed.layerLineWeights);
|
||||
codeByLayer = plan.codeByLayer;
|
||||
if (plan.parent) apply(fieldOps(p, "layers", [...p.layers, plan.parent]));
|
||||
}
|
||||
const dashPlan = planDashLineStyles(parsed.layerDashes, project.lineStyles);
|
||||
if (dashPlan.created.length) apply(addItems("lineStyles", dashPlan.created.filter((x) => !p.lineStyles.some((l) => l.id === x.id))));
|
||||
let drawings = buildDrawings(
|
||||
{ target: c.target, categoryMode: c.categoryMode, importMeshes: c.importMeshes, placement: c.viewCenter ? "viewCenter" : "origin", parsed },
|
||||
levelId,
|
||||
project,
|
||||
active,
|
||||
codeByLayer,
|
||||
dashPlan.styleByLayer,
|
||||
);
|
||||
if (c.viewCenter && drawings.length) {
|
||||
const bb = drawingsBBox(drawings);
|
||||
if (bb) {
|
||||
const dx = c.viewCenter[0] - (bb.minX + bb.maxX) / 2;
|
||||
const dy = c.viewCenter[1] - (bb.minY + bb.maxY) / 2;
|
||||
drawings = drawings.map((d) => translateDrawing(d, dx, dy));
|
||||
}
|
||||
}
|
||||
if (drawings.length) apply(addItems("drawings2d", drawings));
|
||||
if (c.importMeshes && parsed.meshes.length) {
|
||||
const added = parsed.meshes as ContextObject[];
|
||||
const codes = added.map((o) => o.categoryCode).filter((x): x is string => !!x);
|
||||
apply([...addItems("context", added), ...fieldOps(p, "layers", ensureContextCategories(p.layers, codes))]);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
function oldSummary(parsed: DxfImportResult) {
|
||||
const texts = parsed.texts ?? [];
|
||||
return {
|
||||
contours: countContours(parsed.contours),
|
||||
texts: texts.length,
|
||||
meshes: parsed.meshes.length,
|
||||
layers: distinctLayers(parsed.contours),
|
||||
diagnostics: parsed.diagnostics,
|
||||
...(parsed.insUnits !== undefined ? { insUnits: parsed.insUnits } : {}),
|
||||
...(parsed.unitScale !== undefined ? { unitScale: parsed.unitScale } : {}),
|
||||
...(parsed.layouts !== undefined ? { layouts: parsed.layouts } : {}),
|
||||
...(parsed.layout !== undefined ? { layout: parsed.layout } : {}),
|
||||
recovered: parsed.recovered ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
const LEVEL_TEMPLATE = t("default.drawingName", { n: "{n}" });
|
||||
const DASH_TEMPLATE = t("import.pdf.dashStyleName", { pattern: "{pattern}" });
|
||||
|
||||
function compareDrawing(project: Project, parsed: DxfImportResult, src: ReturnType<typeof packChunks>, c: Case, label: string) {
|
||||
const active = project.layers[0].code;
|
||||
const parentName = `Import ${label}`;
|
||||
const old = oldApp(project, parsed, c, active, parentName);
|
||||
const doc = new ProjectDocument(project);
|
||||
const r = doc.importDrawing(project, src, { ...c, activeCategoryCode: active, levelNameTemplate: LEVEL_TEMPLATE, parentName, dashStyleTemplate: DASH_TEMPLATE }, Date.now());
|
||||
if ("problems" in r) throw new Error(`${label}: ${r.problems.join("; ")}`);
|
||||
expect(normalize(r.project), label).toBe(normalize(old));
|
||||
// Kern-Dokument = Leseansicht.
|
||||
expect(normalize(canon(JSON.parse(doc.json()))), `${label} (Dokument)`).toBe(normalize(canon(r.project)));
|
||||
doc.close();
|
||||
}
|
||||
|
||||
const CASES: Case[] = [
|
||||
{ target: { kind: "new", name: "" }, categoryMode: "byLayer", importMeshes: true },
|
||||
{ target: { kind: "new", name: " Plan " }, categoryMode: "active", importMeshes: false, viewCenter: [12.5, -3.25] },
|
||||
{ target: { kind: "existing", levelId: "eg" }, categoryMode: "byLayer", importMeshes: false, viewCenter: [0, 0] },
|
||||
];
|
||||
|
||||
const BASES: [string, Project][] = [
|
||||
["leer", emptyProject],
|
||||
["beispiel", sampleProject],
|
||||
];
|
||||
|
||||
function dxfFiles(): string[] {
|
||||
return readdirSync(FX).filter((n) => /\.(dxf|dwg)$/i.test(n) && !n.startsWith("kataster150k"));
|
||||
}
|
||||
|
||||
describe.skipIf(!have)("Parität Zeichnungs-Import (DXF/DWG/PDF)", { timeout: 600_000 }, () => {
|
||||
it("DXF/DWG: Projekt und Zusammenfassung gleich", () => {
|
||||
let n = 0;
|
||||
for (const name of dxfFiles()) {
|
||||
const bytes = fx(name);
|
||||
const flat = importDrawingFlat(bytes);
|
||||
const parsed = decodeImport(flat.geom, flat.strings);
|
||||
const src = packChunks([flat]);
|
||||
expect(importSummary(src), name).toEqual(JSON.parse(JSON.stringify(oldSummary(parsed))));
|
||||
for (const [bn, base] of BASES) {
|
||||
const levelId = base.drawingLevels[0].id;
|
||||
for (const c of CASES) {
|
||||
const cc = c.target.kind === "existing" ? { ...c, target: { kind: "existing" as const, levelId } } : c;
|
||||
compareDrawing(base, parsed, src, cc, `${name}/${bn}/${JSON.stringify(cc)}`);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(n).toBeGreaterThan(20);
|
||||
});
|
||||
|
||||
it("Layouts (Papierbereich)", () => {
|
||||
const bytes = fx("layouts.dxf");
|
||||
const layouts = parseDxf(bytes).layouts ?? [];
|
||||
expect(layouts.length).toBeGreaterThan(0);
|
||||
for (const l of layouts) {
|
||||
const flat = importDrawingFlat(bytes, l.name);
|
||||
const parsed = decodeImport(flat.geom, flat.strings);
|
||||
const src = packChunks([flat]);
|
||||
expect(importSummary(src)).toEqual(JSON.parse(JSON.stringify(oldSummary(parsed))));
|
||||
compareDrawing(sampleProject, parsed, src, CASES[0], `layout ${l.name}`);
|
||||
}
|
||||
});
|
||||
|
||||
it("parallel gelesene Stücke (grosse DXF)", () => {
|
||||
for (const name of ["kataster150k.dxf"]) {
|
||||
const bytes = fx(name);
|
||||
const offsets = Array.from(fileioLoaded()!.dxf_split_offsets(bytes, 4));
|
||||
expect(offsets.length, name).toBeGreaterThanOrEqual(3);
|
||||
const closer = new TextEncoder().encode("0\nENDSEC\n0\nEOF\n");
|
||||
const pre = bytes.subarray(0, offsets[0]);
|
||||
const chunks: Uint8Array[] = [];
|
||||
for (let i = 0; i + 1 < offsets.length; i++) {
|
||||
const body = bytes.subarray(offsets[i], offsets[i + 1]);
|
||||
const c = new Uint8Array(pre.length + body.length + closer.length);
|
||||
c.set(pre, 0);
|
||||
c.set(body, pre.length);
|
||||
c.set(closer, pre.length + body.length);
|
||||
chunks.push(c);
|
||||
}
|
||||
const flats = chunks.map((c) => importDrawingFlat(c));
|
||||
const parts = flats.map((f, i) => decodeImport(f.geom, f.strings, `c${i}-`));
|
||||
const merged = mergeResults(parts);
|
||||
const src = packChunks(flats);
|
||||
expect(importSummary(src), name).toEqual(JSON.parse(JSON.stringify(oldSummary(merged))));
|
||||
compareDrawing(sampleProject, merged, src, CASES[0], `${name} Stücke`);
|
||||
compareDrawing(emptyProject, merged, src, CASES[1], `${name} Stücke aktiv`);
|
||||
}
|
||||
});
|
||||
|
||||
it("Vektor-PDF: Seiten, Massstäbe, Texte, Strichmuster", () => {
|
||||
for (const name of ["plan.pdf", "plan-rot.pdf"]) {
|
||||
const bytes = fx(name);
|
||||
const res = fileioLoaded()!.pdf_read_page(bytes, 0);
|
||||
const flat = { geom: res.geom(), strings: res.strings() };
|
||||
res.free();
|
||||
const page = readPdfVectorPage(bytes, 0);
|
||||
// pdf-info
|
||||
expect(JSON.parse(core().pdf_page_info(flat.geom, JSON.stringify(flat.strings)))).toEqual(JSON.parse(JSON.stringify(pdfPageInfo(page))));
|
||||
for (const scale of [100, 50, 1, 333.3]) {
|
||||
for (const texts of [true, false]) {
|
||||
const parsed = pdfPageToImport(page, scale, { texts });
|
||||
const src = packChunks([flat], { kind: "pdf", scale, texts });
|
||||
expect(importSummary(src)).toEqual(JSON.parse(JSON.stringify(oldSummary(parsed))));
|
||||
for (const [bn, base] of BASES) {
|
||||
for (const c of CASES) {
|
||||
const cc = c.target.kind === "existing" ? { ...c, target: { kind: "existing" as const, levelId: base.drawingLevels[0].id } } : c;
|
||||
compareDrawing(base, parsed, src, cc, `${name}/${scale}/${texts}/${bn}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Projekt mit schon passendem Linienstil: wird wiederverwendet.
|
||||
const withStyle: Project = { ...sampleProject, lineStyles: [...sampleProject.lineStyles, { id: "x", name: "x", weight: 0.1, color: "#000", dash: [1.05, 0.7] }] };
|
||||
compareDrawing(withStyle, pdfPageToImport(page, 100), packChunks([flat], { kind: "pdf", scale: 100 }), CASES[0], `${name} Stil`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function mergeResults(results: DxfImportResult[]): DxfImportResult {
|
||||
const meshes: ImportedMesh[] = [];
|
||||
const contours: ContourSet[] = [];
|
||||
const texts: ImportedText[] = [];
|
||||
const layerColors: Record<string, string> = {};
|
||||
const diagnostics = { entityCounts: {} as Record<string, number>, total: 0 };
|
||||
for (const r of results) {
|
||||
for (const m of r.meshes) meshes.push(m);
|
||||
for (const c of r.contours) contours.push(c);
|
||||
for (const tt of r.texts ?? []) texts.push(tt);
|
||||
Object.assign(layerColors, r.layerColors);
|
||||
for (const [k, n] of Object.entries(r.diagnostics?.entityCounts ?? {})) diagnostics.entityCounts[k] = (diagnostics.entityCounts[k] ?? 0) + n;
|
||||
diagnostics.total += r.diagnostics?.total ?? 0;
|
||||
}
|
||||
return { meshes, contours, texts, layerColors, diagnostics, insUnits: results[0]?.insUnits, unitScale: results[0]?.unitScale, layouts: results[0]?.layouts };
|
||||
}
|
||||
|
||||
// ── IFC ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
function contextOps(project: Project, meshes: NonNullable<Project["context"]>): CoreOp[] {
|
||||
return [
|
||||
...(project.context ? addItems("context", meshes) : fieldOps(project, "context", meshes)),
|
||||
...fieldOps(project, "layers", ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : [])))),
|
||||
];
|
||||
}
|
||||
|
||||
const geoProject: Project = { ...sampleProject, geoAnchor: { lv95: { e: 2600000, n: 1200000 }, model: { x: 0, y: 0 } } } as Project;
|
||||
const IFC_BASES: [string, Project][] = [["leer", emptyProject], ["beispiel", sampleProject], ["geo", geoProject], ["ohneListen", { ...emptyProject, context: undefined, rooms: undefined, columns: undefined, ceilingTypes: undefined } as unknown as Project]];
|
||||
|
||||
describe.skipIf(!have)("Parität IFC-Import", { timeout: 600_000 }, () => {
|
||||
it("Bauteile und Kontext-Meshes: Projekt, Zusammenfassung, Bericht gleich", async () => {
|
||||
const files = readdirSync(FX).filter((n) => n.endsWith(".ifc"));
|
||||
expect(files.length).toBeGreaterThanOrEqual(5);
|
||||
for (const name of files) {
|
||||
const bytes = fx(name);
|
||||
const flat = await importIfcFlat(bytes, true);
|
||||
const { products, report, elements } = await readIfcElements(bytes);
|
||||
for (const [bn, base] of IFC_BASES) {
|
||||
for (const group of ["auto", "product", "class"] as const) {
|
||||
const label = `${name}/${bn}/${group}`;
|
||||
const old = ifcElementsToProject(base, products, elements, { fileName: name, geoOrigin: projectGeoOrigin(base), group });
|
||||
const doc = new ProjectDocument(base);
|
||||
const r = doc.importIfc(base, flat, { fileName: name, group, elements: true }, Date.now());
|
||||
if ("problems" in r) throw new Error(`${label}: ${r.problems.join("; ")}`);
|
||||
expect(normalize(r.project), label).toBe(normalize(old.project));
|
||||
expect(r.summary, label).toEqual(old.summary);
|
||||
expect(r.kept, label).toEqual(elements.kept);
|
||||
// CLI `import-ifc --elements`: Bericht wie früher `{ ...report, products: undefined, elements: summary, kept }`.
|
||||
expect(JSON.stringify({ ...r.report, products: undefined, byClass: undefined, triangles: undefined, kept: r.kept })).toBe(
|
||||
JSON.stringify({ ...report, products: undefined, elements: old.summary, kept: elements.kept }),
|
||||
);
|
||||
expect(normalize(canon(JSON.parse(doc.json()))), `${label} (Dokument)`).toBe(normalize(canon(r.project)));
|
||||
doc.close();
|
||||
// Nur Kontext-Meshes ([B3]).
|
||||
const m = await readIfc(bytes);
|
||||
const meshes = ifcToImportedMeshes(m.products, name, { geoOrigin: projectGeoOrigin(base), group });
|
||||
const oldMesh = applyOps(base, contextOps(base, meshes));
|
||||
const flat2 = await importIfcFlat(bytes, false);
|
||||
const doc2 = new ProjectDocument(base);
|
||||
const r2 = doc2.importIfc(base, flat2, { fileName: name, group }, Date.now());
|
||||
if ("problems" in r2) throw new Error(r2.problems.join("; "));
|
||||
expect(normalize(r2.project), `${label} Meshes`).toBe(normalize(oldMesh));
|
||||
const byClass: Record<string, number> = {};
|
||||
for (const p of m.products) byClass[p.ifcClass] = (byClass[p.ifcClass] ?? 0) + 1;
|
||||
const triangles = m.products.reduce((s, p) => s + p.indices.length / 3, 0);
|
||||
expect(r2.report).toEqual(JSON.parse(JSON.stringify({ ...m.report, byClass, triangles })));
|
||||
expect(r2.contextObjects).toBe(meshes.length);
|
||||
doc2.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ── Meshes ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe.skipIf(!have)("Parität Mesh-Import", { timeout: 600_000 }, () => {
|
||||
it("OBJ/STL/glTF/GLB/PLY: Projekt und Bericht gleich", async () => {
|
||||
const files = readdirSync(FX).filter((n) => /\.(obj|stl|glb|gltf|ply)$/i.test(n));
|
||||
expect(files.length).toBeGreaterThanOrEqual(6);
|
||||
const sidecars = (n: string) => (n === "gruppen.obj" ? [{ name: "farben.mtl", bytes: fx("farben.mtl") }] : []);
|
||||
for (const name of files) {
|
||||
for (const [unit, up] of [["m", "auto"], ["mm", "y"], ["cm", "z"]] as [MeshUnit, MeshUp][]) {
|
||||
const flat = await importMeshFlat(fx(name), name, { unit, up, maxTriangles: 0, files: sidecars(name) });
|
||||
const { objects, report } = decodeMesh(flat);
|
||||
expect(JSON.parse(core().mesh_import_report(flat.flat, JSON.stringify(flat.strings)))).toEqual(JSON.parse(JSON.stringify(report)));
|
||||
for (const [bn, base] of [["beispiel", sampleProject], ["geo", geoProject], ["leer", { ...emptyProject, context: undefined } as unknown as Project]] as [string, Project][]) {
|
||||
for (const placement of ["center", "original"] as const) {
|
||||
for (const group of ["auto", "object", "merge"] as const) {
|
||||
const label = `${name}/${unit}/${bn}/${placement}/${group}`;
|
||||
const meshes = meshObjectsToImportedMeshes(objects, name, { placement, geoOrigin: projectGeoOrigin(base), group });
|
||||
const old = applyOps(base, contextOps(base, meshes));
|
||||
const doc = new ProjectDocument(base);
|
||||
const r = doc.importMesh(base, flat, { fileName: name, placement, group }, Date.now());
|
||||
if ("problems" in r) throw new Error(`${label}: ${r.problems.join("; ")}`);
|
||||
expect(normalize(r.project), label).toBe(normalize(old));
|
||||
expect(r.contextObjects).toBe(meshes.length);
|
||||
doc.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
// Gelesene Import-Datei (DXF/DWG/PDF) als Eingabe für den Kern ([K4] S4): das Format-Modul (`pkgFileIo`,
|
||||
// `src-tauri/fileio`) liest die Datei in flache Puffer, der Kern (`core/src/import_drawing.rs`) macht daraus
|
||||
// die Zusammenfassung für den Dialog und beim Bestätigen die Ops (`ProjectDocument.importDrawing`). TS hält
|
||||
// nur die Puffer (keine Umwandlung in Konturen/Zeichnungen mehr).
|
||||
|
||||
import type { ImportedMesh } from "../model/types";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import type { ImportSource } from "../core/document";
|
||||
|
||||
export type { ImportSource };
|
||||
|
||||
/** Diagnose: gelesene Entity-Typen (Typ → Anzahl) und Gesamtzahl. */
|
||||
export interface ImportDiagnostics {
|
||||
entityCounts: Record<string, number>;
|
||||
total: number;
|
||||
}
|
||||
|
||||
/** Was der Import-Dialog von der gelesenen Datei zeigt (`import_drawing::summary_json`). */
|
||||
export interface ImportSummary {
|
||||
contours: number;
|
||||
texts: number;
|
||||
meshes: number;
|
||||
/** Layer der Konturen (in Fundreihenfolge). */
|
||||
layers: string[];
|
||||
diagnostics: ImportDiagnostics;
|
||||
/** `$INSUNITS` der Datei (0 = ohne Einheit, 4 = mm …). */
|
||||
insUnits?: number;
|
||||
/** Meter je Zeicheneinheit (schon umgerechnet; PDF: Meter je Punkt beim gewählten Massstab). */
|
||||
unitScale?: number;
|
||||
/** Papierbereich-Layouts der Datei (ohne „Model"); `entities` = Zeichnungs-Entities. */
|
||||
layouts?: { name: string; entities: number }[];
|
||||
/** Name des gelesenen Layouts; fehlt beim Modellraum. */
|
||||
layout?: string;
|
||||
/** Die Datei war beschädigt/abgeschnitten und wurde nur teilweise gelesen. */
|
||||
recovered: boolean;
|
||||
}
|
||||
|
||||
/** Gelesene Datei + Zusammenfassung (Zustand des Import-Dialogs). */
|
||||
export interface ParsedImport {
|
||||
src: ImportSource;
|
||||
summary: ImportSummary;
|
||||
}
|
||||
|
||||
/** Ein gelesenes Stück (flacher Puffer + String-Tabelle des Format-Moduls). */
|
||||
export interface ImportChunk {
|
||||
geom: Float64Array;
|
||||
strings: string[];
|
||||
}
|
||||
|
||||
/** Stücke zu einer Kern-Eingabe zusammenpacken: `[n, len_0 … len_{n−1}, daten …]`. */
|
||||
export function packChunks(chunks: readonly ImportChunk[], source: ImportSource["source"] = { kind: "drawing" }): ImportSource {
|
||||
const n = chunks.length;
|
||||
const total = chunks.reduce((s, c) => s + c.geom.length, 0);
|
||||
const geom = new Float64Array(1 + n + total);
|
||||
geom[0] = n;
|
||||
let at = 1 + n;
|
||||
chunks.forEach((c, i) => {
|
||||
geom[1 + i] = c.geom.length;
|
||||
geom.set(c.geom, at);
|
||||
at += c.geom.length;
|
||||
});
|
||||
return { geom, strings: chunks.map((c) => c.strings), source };
|
||||
}
|
||||
|
||||
function call<T>(out: string): T {
|
||||
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
|
||||
return JSON.parse(out) as T;
|
||||
}
|
||||
|
||||
/** Zusammenfassung für den Dialog (Kern). Wirft bei kaputtem Puffer. */
|
||||
export function importSummary(src: ImportSource): ImportSummary {
|
||||
return call(core().import_drawing_summary(src.geom, JSON.stringify(src.strings), JSON.stringify(src.source)));
|
||||
}
|
||||
|
||||
/** Gelesene Stücke → Dialog-Zustand. */
|
||||
export function parsedImport(chunks: readonly ImportChunk[], source?: ImportSource["source"]): ParsedImport {
|
||||
const src = packChunks(chunks, source);
|
||||
return { src, summary: importSummary(src) };
|
||||
}
|
||||
|
||||
/** Leerer Import (Fehlerfall im Dialog). */
|
||||
export function emptyImport(): ParsedImport {
|
||||
const src = packChunks([]);
|
||||
return { src, summary: { contours: 0, texts: 0, meshes: 0, layers: [], diagnostics: { entityCounts: {}, total: 0 }, recovered: false } };
|
||||
}
|
||||
|
||||
/** Nur die Meshes als Kontext-Objekte (z. B. swissBUILDINGS3D-Kacheln, je Ebene ein Mesh). */
|
||||
export function importMeshes(src: ImportSource, now = Date.now()): ImportedMesh[] {
|
||||
return call(core().import_drawing_meshes(src.geom, JSON.stringify(src.strings), JSON.stringify(src.source), now));
|
||||
}
|
||||
Reference in new issue
Block a user