[58] Merge: 3D-Modell inkrementell (Cache je Wand, Delta-Abfrage)
This commit is contained in:
13 files changed
+1140
-95
No files matched your search
@@ -1277,7 +1277,18 @@ Entscheid CLA vs. Verzicht auf Dual Licensing.
|
||||
3D-Pfade. Mit `native2d` zusammen planen; [K3] liefert die Primitive direkt aus Rust. · L
|
||||
- ✅ **[4] Kern headless als `dossier-cli`.** info/validate/migrate/plan/section/elevation/dxf/ifc/step/
|
||||
obj/stl/schedule/kennzahlen/sun/model3d/mcp/bench. · S–M
|
||||
- ○ **[58] Inkrementelle Ableitung.** Teilweise über Caches. · L
|
||||
- ◐ **[58] Inkrementelle Ableitung.** Teilweise über Caches. · L
|
||||
5.11.: 3D-Modell inkrementell. Kern `model3d_cache.rs` (im Dokument): Wandkörper und Öffnungs-Einbauteile je Wand
|
||||
(Schlüssel Element-Stand der Wand aus `Revs::items`, gültig bei gleichen Ständen der gehosteten Öffnungen und gleichen
|
||||
Schnittlinien), Verschneidung je Geschoss (neu nur bei geänderter Eingabe), fertiges JSON je Eintrag; jedes andere
|
||||
Feld (Typen, Geschosse, Decken, Dächer …) oder eine andere Material-Liste verwirft alles; Bogenwände: Einbauteile
|
||||
ohne Cache. `model3dPartsDelta`: nur Einträge, die TS noch nicht hat (Laufnummern), TS setzt zusammen
|
||||
(`ProjectDocument.model3dParts`). Tests: Kern `model3d_cache::tests` (gemischte Änderungen samt Undo/Redo, Byte-gleich
|
||||
mit voller Ableitung, Änderungs-Antwort = voll; 1 Wand → 1 Wand neu), `toWalls3d.incremental.test.ts`.
|
||||
Grossgebäude (Linux, WASM): projectToModel3d nach 1 Wand-Änderung 316 → 12 ms, nach 1 Öffnungs-Änderung 302 → 12 ms.
|
||||
Offen: 3D-Viewer serialisiert das Modell weiter ganz (`JSON.stringify` → render3d `set_model`, eigener Schritt mit
|
||||
Teil-Updates in render3d); Explosion (`explode > 0`) ohne Cache; Schnitt/Ansicht (je ~100 ms) und Plan-Szene
|
||||
(`planToRenderScene` ~30 ms) noch voll.
|
||||
|
||||
### Befehle, Undo, Validierung
|
||||
|
||||
@@ -1327,7 +1338,8 @@ Entscheid CLA vs. Verzicht auf Dual Licensing.
|
||||
zusätzlich DXF (1 Geschoss), IFC und Doc-commit/undo/redo (200 Wände = 1 Schritt). Frame-Zeiten: `e2e/bigBuilding.spec.ts`
|
||||
(`npm run e2e:perf`, nur mit `E2E_PERF=1`; rAF-Abstände bei Rad-Zoom und Schwenken, p50/p95, grosse Obergrenze).
|
||||
Messung 5.11., **Linux-Container (nicht macOS), Mittel über 5 Läufe, Software-Rendering, Plan über SVG-Rückfall**:
|
||||
generatePlan 3,1 ms (Cache) · planToRenderScene 34,7 · planToSvgString 36,2 · projectToModel3d 327 · Schnitt 110 ·
|
||||
generatePlan 3,1 ms (Cache) · planToRenderScene 34,7 · planToSvgString 36,2 · projectToModel3d 327 (5.11. nach [58]:
|
||||
kalt ~530 einmalig, unverändert 18–24, nach 1 Wand-/Öffnungs-Änderung 12) · Schnitt 110 ·
|
||||
Ansicht 124 · DXF 73 · IFC 548 ms; Doc-commit 200 Wände 2,7 ms, undo 2,0, redo 0,8; commit 1 Wand 0,10 ms.
|
||||
Frames im Plan (Chromium headless, SVG): Zoom p50 16,7 / p95 450 / max 650 ms; Schwenken p50 150 / p95 550 / max 617 ms —
|
||||
Plan-Ansicht mit ~4000 Elementen im SVG-Rückfall ruckelt deutlich (ein Rad-Schritt ≈ 1 s Wartezeit). Offen: Messung auf macOS
|
||||
|
||||
@@ -40,6 +40,8 @@ pub struct Document {
|
||||
revs: Revs,
|
||||
/// Caches der Plan-Erzeugung (`plan::cache`), gültig über [`Revs`].
|
||||
plan_cache: crate::plan::cache::PlanCache,
|
||||
/// Cache der 3D-Ableitung ([58], `model3d_cache`), gültig über [`Revs`].
|
||||
model3d_cache: crate::model3d_cache::Model3dCache,
|
||||
/// id → Position je Liste über die Aufrufe hinweg (s. [`PosCache`]); in einer `RefCell`, damit auch
|
||||
/// lesende Abfragen ([`Lookup`]) den Index bauen und nutzen.
|
||||
pos: RefCell<PosCache>,
|
||||
@@ -790,6 +792,22 @@ impl Document {
|
||||
&self.revs
|
||||
}
|
||||
|
||||
/// 3D-Modell in Teilen ([58]) wie `model3d::parts`, Wände und Öffnungs-Einbauteile je Wand aus dem
|
||||
/// Cache (`model3d_cache`); `structs` wie dort.
|
||||
pub fn model3d_parts(&mut self, layered: bool, detail: f64, for_section: bool, structs: bool, delta: Option<u64>) -> Result<crate::model3d_cache::CachedParts, String> {
|
||||
self.project()?;
|
||||
let p = self.typed.as_ref().expect("gerade gelesen");
|
||||
let n_open = p.openings.as_ref().map_or(0, Vec::len);
|
||||
let walls = self.revs.items("walls", p.walls.len()).to_vec();
|
||||
let openings = self.revs.items("openings", n_open).to_vec();
|
||||
self.model3d_cache.parts(p, &self.revs, &walls, &openings, layered, detail, for_section, structs, delta)
|
||||
}
|
||||
|
||||
/// Letzte Statistik des 3D-Caches (Tests): neu gerechnete Wände / Öffnungs-Wände.
|
||||
pub fn model3d_rebuilt(&self) -> (usize, usize) {
|
||||
self.model3d_cache.last_rebuilt
|
||||
}
|
||||
|
||||
/// Typisierte Sicht samt Änderungsständen (Element-Stände der 2D-Zeichnungen vergeben) und
|
||||
/// Plan-Cache — getrennte Ausleihen für die gecachte Plan-Erzeugung (`plan::cache`).
|
||||
pub fn project_cached(&mut self) -> Result<(&Project, &Revs, &mut crate::plan::cache::PlanCache), String> {
|
||||
|
||||
@@ -62,6 +62,7 @@ pub mod ops;
|
||||
pub mod mesh_section;
|
||||
pub mod model;
|
||||
pub mod model3d;
|
||||
pub mod model3d_cache;
|
||||
pub mod explode3d;
|
||||
pub mod style;
|
||||
pub mod hlr;
|
||||
|
||||
+135
-74
@@ -481,62 +481,71 @@ fn wall_reveals(p: &Project, w: &Wall, openings: &[&Opening], n_bands: usize) ->
|
||||
|
||||
/// Verschneidung je Geschoss (`computeJoinsByFloor`); Fehler = unbekannter Wandtyp/Bauteil.
|
||||
fn compute_joins_by_floor(p: &Project) -> Result<HashMap<String, WallCuts>, String> {
|
||||
let mut groups: Vec<(String, Vec<&Wall>)> = Vec::new();
|
||||
for w in &p.walls {
|
||||
match groups.iter_mut().find(|g| g.0 == w.floor_id) {
|
||||
Some(g) => g.1.push(w),
|
||||
None => groups.push((w.floor_id.clone(), vec![w])),
|
||||
}
|
||||
}
|
||||
let mut merged = HashMap::new();
|
||||
for (_, walls) in &groups {
|
||||
let mut comp_index: HashMap<&str, u32> = HashMap::new();
|
||||
let mut jw: Vec<JoinWall> = Vec::with_capacity(walls.len());
|
||||
let mut finite = true;
|
||||
for w in walls {
|
||||
// Hängende Wandtypen/Bauteile (Datei/Import) verschneiden mit den Rückfall-Werten.
|
||||
let layers = Some(
|
||||
p.wall_type_or_fallback(w)
|
||||
.layers
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let comp = p.component_or_fallback(&l.component_id);
|
||||
let n = comp_index.len() as u32;
|
||||
let idx = *comp_index.entry(comp.id.as_str()).or_insert(n);
|
||||
JoinLayer { thickness: l.thickness, component: Some(idx), priority: comp.join_priority }
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
let reference = wall_reference(w);
|
||||
finite &= [w.start.x, w.start.y, w.end.x, w.end.y].iter().all(|v| v.is_finite())
|
||||
&& !matches!(reference, Reference::Offset(v) if !v.is_finite())
|
||||
&& layers.as_ref().is_none_or(|l| l.iter().all(|x| x.thickness.is_finite()));
|
||||
jw.push(JoinWall { start: kv(w.start), end: kv(w.end), reference, layers, bulge: w.bulge });
|
||||
}
|
||||
if !finite {
|
||||
for w in walls {
|
||||
merged.insert(w.id.clone(), WallCuts::default());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match joins::compute_joins(&jw) {
|
||||
Ok(cuts) => {
|
||||
for (w, c) in walls.iter().zip(cuts) {
|
||||
merged.insert(w.id.clone(), c);
|
||||
}
|
||||
}
|
||||
// Mit den Rückfällen oben nicht mehr erwartet: dann eben ohne Verschneidung.
|
||||
Err(_) => {
|
||||
for w in walls {
|
||||
merged.insert(w.id.clone(), WallCuts::default());
|
||||
}
|
||||
}
|
||||
for (_, idx) in floor_groups(p) {
|
||||
let (jw, finite) = floor_join_input(p, &idx);
|
||||
for (&i, c) in idx.iter().zip(floor_join_cuts(&jw, finite)) {
|
||||
merged.insert(p.walls[i].id.clone(), c);
|
||||
}
|
||||
}
|
||||
Ok(merged)
|
||||
}
|
||||
|
||||
fn floor_context(p: &Project, floor_id: &str, with_ceilings: bool) -> FloorContext {
|
||||
/// Wände je Geschoss (Positionen in `p.walls`), Geschosse in der Reihenfolge ihres ersten Auftretens.
|
||||
pub(crate) fn floor_groups(p: &Project) -> Vec<(&str, Vec<usize>)> {
|
||||
let mut groups: Vec<(&str, Vec<usize>)> = Vec::new();
|
||||
let mut at: HashMap<&str, usize> = HashMap::new();
|
||||
for (i, w) in p.walls.iter().enumerate() {
|
||||
match at.get(w.floor_id.as_str()) {
|
||||
Some(&g) => groups[g].1.push(i),
|
||||
None => {
|
||||
at.insert(w.floor_id.as_str(), groups.len());
|
||||
groups.push((w.floor_id.as_str(), vec![i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// Eingabe der Verschneidung eines Geschosses (Wände `idx`) und ob sie endlich ist.
|
||||
pub(crate) fn floor_join_input(p: &Project, idx: &[usize]) -> (Vec<JoinWall>, bool) {
|
||||
let mut comp_index: HashMap<&str, u32> = HashMap::new();
|
||||
let mut jw: Vec<JoinWall> = Vec::with_capacity(idx.len());
|
||||
let mut finite = true;
|
||||
for &i in idx {
|
||||
let w = &p.walls[i];
|
||||
// Hängende Wandtypen/Bauteile (Datei/Import) verschneiden mit den Rückfall-Werten.
|
||||
let layers = Some(
|
||||
p.wall_type_or_fallback(w)
|
||||
.layers
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let comp = p.component_or_fallback(&l.component_id);
|
||||
let n = comp_index.len() as u32;
|
||||
let idx = *comp_index.entry(comp.id.as_str()).or_insert(n);
|
||||
JoinLayer { thickness: l.thickness, component: Some(idx), priority: comp.join_priority }
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
let reference = wall_reference(w);
|
||||
finite &= [w.start.x, w.start.y, w.end.x, w.end.y].iter().all(|v| v.is_finite())
|
||||
&& !matches!(reference, Reference::Offset(v) if !v.is_finite())
|
||||
&& layers.as_ref().is_none_or(|l| l.iter().all(|x| x.thickness.is_finite()));
|
||||
jw.push(JoinWall { start: kv(w.start), end: kv(w.end), reference, layers, bulge: w.bulge });
|
||||
}
|
||||
(jw, finite)
|
||||
}
|
||||
|
||||
/// Schnittlinien je Wand eines Geschosses (gleich lang wie `jw`); nicht endlich oder Fehler = ohne.
|
||||
pub(crate) fn floor_join_cuts(jw: &[JoinWall], finite: bool) -> Vec<WallCuts> {
|
||||
if !finite {
|
||||
return vec![WallCuts::default(); jw.len()];
|
||||
}
|
||||
// Mit den Rückfällen oben nicht mehr erwartet: dann eben ohne Verschneidung.
|
||||
joins::compute_joins(jw).unwrap_or_else(|_| vec![WallCuts::default(); jw.len()])
|
||||
}
|
||||
|
||||
pub(crate) fn floor_context(p: &Project, floor_id: &str, with_ceilings: bool) -> FloorContext {
|
||||
let ceilings: Vec<CeilingIn> = p
|
||||
.ceilings
|
||||
.as_deref()
|
||||
@@ -598,10 +607,24 @@ pub fn emit_walls_with(p: &Project, layered: bool, pockets: bool) -> Result<Vec<
|
||||
let mut out = Vec::new();
|
||||
let by_wall = p.openings_by_wall();
|
||||
for wall in &p.walls {
|
||||
let (bands, stacked) = resolve_wall_bands(p, &maps, wall, layered);
|
||||
let (z_bottom, z_top) = p.wall_vertical_extent(wall);
|
||||
// Schnitt-Eingabe: nur die Dächer ([G2]); Decken rechnet der Schnitt selbst (Dominanz).
|
||||
let ctx = contexts.entry(wall.floor_id.as_str()).or_insert_with(|| floor_context(p, &wall.floor_id, layered));
|
||||
let openings = by_wall.get(wall.id.as_str()).map_or(&[][..], |v| v.as_slice());
|
||||
let cuts = if layered { joins.as_ref().and_then(|j| j.get(&wall.id)).cloned().unwrap_or_default() } else { WallCuts::default() };
|
||||
wall_pieces(p, &maps, wall, ctx, openings, cuts, layered, pockets, &mut out);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Die Körper EINER Wand (Schleifenrumpf von [`emit_walls_with`], hinten an `out` angehängt): hängt nur
|
||||
/// von der Wand, ihren Öffnungen, ihren Schnittlinien `cuts` (Verschneidung mit den Nachbarn), dem
|
||||
/// Geschoss-Kontext und den Typen/Materialien/Geschossen ab — der 3D-Cache ([58], `model3d_cache.rs`)
|
||||
/// behält das Ergebnis je Wand.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn wall_pieces(p: &Project, maps: &[String], wall: &Wall, ctx: &FloorContext, openings: &[&Opening], cuts: WallCuts, layered: bool, pockets: bool, out: &mut Vec<RWall>) {
|
||||
{
|
||||
let (bands, stacked) = resolve_wall_bands(p, maps, wall, layered);
|
||||
let (z_bottom, z_top) = p.wall_vertical_extent(wall);
|
||||
let win = wall_bands::WallIn {
|
||||
start: kv(wall.start),
|
||||
end: kv(wall.end),
|
||||
@@ -617,10 +640,10 @@ pub fn emit_walls_with(p: &Project, layered: bool, pockets: bool) -> Result<Vec<
|
||||
_ => Termination::Both,
|
||||
},
|
||||
bands: bands.iter().map(|b| BandIn { thickness: b.thickness, priority: b.priority }).collect(),
|
||||
openings: wall_openings(p, wall, by_wall.get(wall.id.as_str()).map_or(&[][..], |v| v.as_slice()), true),
|
||||
cuts: if layered { joins.as_ref().and_then(|j| j.get(&wall.id)).cloned().unwrap_or_default() } else { WallCuts::default() },
|
||||
openings: wall_openings(p, wall, openings, true),
|
||||
cuts,
|
||||
roof_attach: wall.roof_attach,
|
||||
reveals: if layered && stacked { wall_reveals(p, wall, by_wall.get(wall.id.as_str()).map_or(&[][..], |v| v.as_slice()), bands.len()) } else { Vec::new() },
|
||||
reveals: if layered && stacked { wall_reveals(p, wall, openings, bands.len()) } else { Vec::new() },
|
||||
};
|
||||
// Bogenwand ([T2]): Sehnen-Teilwände mit radialen Gehrungen.
|
||||
let arc = crate::wall_arc::WallArc::of_wall(wall);
|
||||
@@ -635,7 +658,7 @@ pub fn emit_walls_with(p: &Project, layered: bool, pockets: bool) -> Result<Vec<
|
||||
};
|
||||
let first_piece = out.len();
|
||||
// [95] Taschen (Achsmass; bei Bogenwänden = Bogenlänge, je Sehnen-Teilwand abgebildet).
|
||||
let pocket_cuts = if pockets { wall_pocket_cuts(p, wall, by_wall.get(wall.id.as_str()).map_or(&[][..], |v| v.as_slice())) } else { Vec::new() };
|
||||
let pocket_cuts = if pockets { wall_pocket_cuts(p, wall, openings) } else { Vec::new() };
|
||||
for win in &wins {
|
||||
let win_first = out.len();
|
||||
let (dx, dy) = (win.end.x - win.start.x, win.end.y - win.start.y);
|
||||
@@ -676,16 +699,14 @@ pub fn emit_walls_with(p: &Project, layered: bool, pockets: bool) -> Result<Vec<
|
||||
if (sb - sa).abs() > 1e-9 {
|
||||
let m = |u: f64| (u - sa) / (sb - sa) * chord;
|
||||
let cuts: Vec<[f64; 6]> = pocket_cuts.iter().map(|c| [m(c[0]), m(c[1]), c[2], c[3], c[4], c[5]]).collect();
|
||||
cut_wall_pockets([win.start.x, win.start.y], [dx, dy], &cuts, &mut out, win_first);
|
||||
cut_wall_pockets([win.start.x, win.start.y], [dx, dy], &cuts, out, win_first);
|
||||
}
|
||||
}
|
||||
}
|
||||
if arc.is_none() && !pocket_cuts.is_empty() {
|
||||
cut_wall_pockets([wall.start.x, wall.start.y], [wall.end.x - wall.start.x, wall.end.y - wall.start.y], &pocket_cuts, &mut out, first_piece);
|
||||
cut_wall_pockets([wall.start.x, wall.start.y], [wall.end.x - wall.start.x, wall.end.y - wall.start.y], &pocket_cuts, out, first_piece);
|
||||
}
|
||||
}
|
||||
let _ = hypot2;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// [95] Taschen der Taschen-Schiebetüren einer Wand: je Tasche `[u0, u1, n0, n1, z0, z1]` im Wandrahmen
|
||||
@@ -1106,21 +1127,66 @@ pub fn emit_opening_meshes(p: &Project, detail: f64) -> Vec<RMesh> {
|
||||
}
|
||||
|
||||
fn emit_opening_meshes_plain(p: &Project, detail: f64) -> Vec<RMesh> {
|
||||
let by_wall = p.openings_by_wall();
|
||||
let per: Vec<WallOpeningMeshes> = p.walls.iter().map(|wall| wall_opening_meshes(p, wall, by_wall.get(wall.id.as_str()).map_or(&[][..], |v| v.as_slice()), detail)).collect();
|
||||
let mut out = assemble_opening_meshes(per);
|
||||
out.extend(surface_window_meshes(p));
|
||||
out
|
||||
}
|
||||
|
||||
/// Öffnungs-Einbauteile EINER Wand ([58]: der 3D-Cache behält sie je Wand): die Quader je Durchgang
|
||||
/// (`openings3d::wall_mesh_passes`), Türzargen und Formöffnungen.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct WallOpeningMeshes {
|
||||
pub passes: [Vec<RMesh>; 3],
|
||||
pub zargen: Vec<RMesh>,
|
||||
pub shaped: Vec<RMesh>,
|
||||
}
|
||||
|
||||
/// Reihenfolge des ganzen Modells: alle Wände je Durchgang, dann alle Zargen, dann alle Formöffnungen
|
||||
/// (ohne die Dach-/Deckenfenster, s. [`surface_window_meshes`]).
|
||||
pub(crate) fn assemble_opening_meshes(per: Vec<WallOpeningMeshes>) -> Vec<RMesh> {
|
||||
let mut lists: [Vec<RMesh>; 5] = Default::default();
|
||||
for m in per {
|
||||
let [a, b, c] = m.passes;
|
||||
for (k, v) in [a, b, c, m.zargen, m.shaped].into_iter().enumerate() {
|
||||
lists[k].extend(v);
|
||||
}
|
||||
}
|
||||
lists.into_iter().flatten().collect()
|
||||
}
|
||||
|
||||
/// Dach-/Deckenfenster ([103]).
|
||||
pub(crate) fn surface_window_meshes(p: &Project) -> Vec<RMesh> {
|
||||
let mut out = Vec::new();
|
||||
for op in p.openings.as_deref().unwrap_or(&[]) {
|
||||
if let Some(f) = crate::opening_shape::host_frame(p, op) {
|
||||
for (part, positions) in crate::opening_shape::surface_window_boxes(p, op, &f) {
|
||||
out.push(box_mesh(positions, PART_RGB[part as usize]));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Einbauteile der Öffnungen `openings` (in Projekt-Reihenfolge) der Wand `wall`.
|
||||
pub(crate) fn wall_opening_meshes(p: &Project, wall: &Wall, openings: &[&Opening], detail: f64) -> WallOpeningMeshes {
|
||||
let mut shaped: Vec<RMesh> = Vec::new();
|
||||
let mut w = FlatWriter::new();
|
||||
w.num(detail).num(p.walls.len() as f64);
|
||||
w.num(detail).num(1.0);
|
||||
// [105] Anhang: Rahmen-Detail je (Wand, Öffnung); Türzargen als eigene Quader.
|
||||
let mut details: Vec<f64> = Vec::new();
|
||||
let mut n_details = 0.0;
|
||||
let mut zargen: Vec<RMesh> = Vec::new();
|
||||
for (wi, wall) in p.walls.iter().enumerate() {
|
||||
let wi = 0usize;
|
||||
{
|
||||
w.nums(&[wall.start.x, wall.start.y, wall.end.x, wall.end.y]);
|
||||
let slot = w.slot();
|
||||
let mut count = 0.0;
|
||||
let wr = wall_ref(p, wall);
|
||||
let (zb, zt) = p.wall_vertical_extent(wall);
|
||||
let mut thickness: Option<f64> = None;
|
||||
for op in p.openings_of_wall(&wall.id) {
|
||||
for &op in openings {
|
||||
let Some((from, to)) = opening_geom::opening_interval(&wr, op.position, op.width) else { continue };
|
||||
let o_bottom = zb + op.sill_height.max(0.0);
|
||||
let o_top = zt.min(o_bottom + op.height);
|
||||
@@ -1152,7 +1218,12 @@ fn emit_opening_meshes_plain(p: &Project, detail: f64) -> Vec<RMesh> {
|
||||
}
|
||||
w.num(n_details);
|
||||
w.nums(&details);
|
||||
let buf = crate::openings3d::opening_meshes_flat(&w.done());
|
||||
let passes = crate::openings3d::opening_mesh_passes_flat(&w.done()).map(|buf| box_meshes_of_flat(&buf));
|
||||
WallOpeningMeshes { passes, zargen, shaped }
|
||||
}
|
||||
|
||||
/// Quader aus dem flachen Puffer von `openings3d` (`[n, je Quader: Bauteil, 24 Koordinaten]`).
|
||||
fn box_meshes_of_flat(buf: &[f64]) -> Vec<RMesh> {
|
||||
let n = buf.first().copied().unwrap_or(0.0).max(0.0) as usize;
|
||||
let mut out = Vec::new();
|
||||
let mut i = 1;
|
||||
@@ -1172,16 +1243,6 @@ fn emit_opening_meshes_plain(p: &Project, detail: f64) -> Vec<RMesh> {
|
||||
});
|
||||
i += 25;
|
||||
}
|
||||
out.extend(zargen);
|
||||
out.extend(shaped);
|
||||
// Dach-/Deckenfenster ([103]).
|
||||
for op in p.openings.as_deref().unwrap_or(&[]) {
|
||||
if let Some(f) = crate::opening_shape::host_frame(p, op) {
|
||||
for (part, positions) in crate::opening_shape::surface_window_boxes(p, op, &f) {
|
||||
out.push(box_mesh(positions, PART_RGB[part as usize]));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,611 @@
|
||||
//! Inkrementelle 3D-Ableitung ([58]): Cache der Wandkörper und der Öffnungs-Einbauteile je Wand, damit
|
||||
//! eine Änderung an EINER Wand oder Öffnung nicht das ganze Modell neu rechnet und neu schreibt.
|
||||
//!
|
||||
//! Gültigkeit (im Zweifel verwerfen):
|
||||
//! - Alles verworfen, wenn sich ein anderes Feld als Wände/Öffnungen ändert (Typen, Materialien,
|
||||
//! Geschosse, Decken, Dächer …: `Revs::max_except`), bei neuer Epoche (Laden) oder wenn die
|
||||
//! Material-Liste der Wände (`wall_material_color_maps`, Index je Schicht) anders ausfällt.
|
||||
//! - Verschneidung je Geschoss: neu, wenn sich ihre Eingabe (Lage, Referenz, Schichten der Wände des
|
||||
//! Geschosses) dem Wert nach ändert.
|
||||
//! - Je Wand (Schlüssel: Element-Stand der Wand, `Revs::items`): gültig bei gleichen Element-Ständen der
|
||||
//! gehosteten Öffnungen und — für die Körper — gleichen Schnittlinien aus der Verschneidung.
|
||||
//!
|
||||
//! Ergebnis inhaltlich und als JSON Byte für Byte gleich wie [`model3d::parts`] (Test unten).
|
||||
|
||||
use crate::joins::{JoinWall, WallCuts};
|
||||
use crate::model::{Opening, Project};
|
||||
use crate::model3d::{self, Parts, RMesh, RWall, WallOpeningMeshes};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Felder, die das 3D-Modell nicht lesen oder die der Cache selbst je Element verfolgt.
|
||||
const NOT_GLOBAL: &[&str] = &["walls", "openings", "drawings2d", "viewSnapshots", "viewSnapshotFolders", "viewTemplates"];
|
||||
|
||||
/// Laufnummern der Einträge, über alle Dokumente eindeutig: TS hält die gelieferten Einträge unter
|
||||
/// dieser Nummer ([`Model3dCache::parts`] mit `delta`).
|
||||
static SERIALS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
fn next_serial() -> u64 {
|
||||
SERIALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1
|
||||
}
|
||||
|
||||
fn current_serial() -> u64 {
|
||||
SERIALS.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct WallEntry {
|
||||
serial: u64,
|
||||
openings: Vec<u64>,
|
||||
cuts: WallCuts,
|
||||
pieces: Vec<RWall>,
|
||||
/// `pieces` als JSON ohne die äusseren Klammern (leer bei keinem Körper).
|
||||
json: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct OpenEntry {
|
||||
serial: u64,
|
||||
openings: Vec<u64>,
|
||||
meshes: WallOpeningMeshes,
|
||||
/// Je Liste (3 Durchgänge, Zargen, Formöffnungen) JSON ohne Klammern.
|
||||
json: [String; 5],
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct JoinEntry {
|
||||
input: Vec<JoinWall>,
|
||||
finite: bool,
|
||||
cuts: Vec<WallCuts>,
|
||||
}
|
||||
|
||||
/// Cache eines Dokuments (`Document::model3d_parts`).
|
||||
/// Kopie eines Dokuments (`Clone`) beginnt mit leerem Cache.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Model3dCache {
|
||||
sig: Option<(u64, u64)>,
|
||||
maps: Vec<String>,
|
||||
joins: HashMap<String, JoinEntry>,
|
||||
/// Je `layered` (0/1): Wand-Stand → Körper.
|
||||
walls: [HashMap<u64, WallEntry>; 2],
|
||||
/// Je Detailgrad (Bits): Wand-Stand → Einbauteile.
|
||||
openings: Vec<(u64, HashMap<u64, OpenEntry>)>,
|
||||
/// Statistik (Tests): Wände/Öffnungs-Wände, die im letzten Aufruf neu gerechnet wurden.
|
||||
pub last_rebuilt: (usize, usize),
|
||||
}
|
||||
|
||||
/// Ergebnis: die Teile (Wände/Öffnungen nur mit `structs`) und das JSON wie `serde_json::to_string(&parts)`.
|
||||
pub struct CachedParts {
|
||||
pub parts: Parts,
|
||||
pub json: String,
|
||||
}
|
||||
|
||||
fn inner_json<T: serde::Serialize>(v: &[T]) -> String {
|
||||
let s = serde_json::to_string(v).unwrap_or_else(|_| "[]".into());
|
||||
s[1..s.len() - 1].to_owned()
|
||||
}
|
||||
|
||||
fn join_json<'a>(out: &mut String, parts: impl Iterator<Item = &'a str>) {
|
||||
let mut first = true;
|
||||
for s in parts.filter(|s| !s.is_empty()) {
|
||||
if !first {
|
||||
out.push(',');
|
||||
}
|
||||
out.push_str(s);
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
|
||||
impl Model3dCache {
|
||||
fn validate(&mut self, p: &Project, revs: &crate::document::Revs) {
|
||||
let sig = (revs.epoch(), revs.max_except(NOT_GLOBAL));
|
||||
let maps = model3d::wall_material_color_maps(p);
|
||||
if self.sig != Some(sig) || self.maps != maps {
|
||||
*self = Model3dCache {
|
||||
sig: Some(sig),
|
||||
maps,
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Schnittlinien je Wand (wie `compute_joins_by_floor`), Geschosse mit unveränderter Eingabe aus dem Cache.
|
||||
fn joins(&mut self, p: &Project) -> HashMap<String, WallCuts> {
|
||||
let mut merged = HashMap::new();
|
||||
let mut keep: HashMap<String, JoinEntry> = HashMap::new();
|
||||
for (floor, idx) in model3d::floor_groups(p) {
|
||||
let (input, finite) = model3d::floor_join_input(p, &idx);
|
||||
let e = match self.joins.remove(floor) {
|
||||
Some(e) if e.finite == finite && e.input == input => e,
|
||||
_ => {
|
||||
let cuts = model3d::floor_join_cuts(&input, finite);
|
||||
JoinEntry { input, finite, cuts }
|
||||
}
|
||||
};
|
||||
for (&i, c) in idx.iter().zip(&e.cuts) {
|
||||
merged.insert(p.walls[i].id.clone(), c.clone());
|
||||
}
|
||||
keep.insert(floor.to_owned(), e);
|
||||
}
|
||||
self.joins = keep;
|
||||
merged
|
||||
}
|
||||
|
||||
/// Wie [`model3d::parts`] (ohne Explosion), Wände und Öffnungs-Einbauteile je Wand aus dem Cache.
|
||||
/// `structs`: auch die Wände/Öffnungs-Meshes als Werte liefern (Abzugskörper); sonst leer, nur im JSON.
|
||||
/// `delta = Some(mark)`: JSON als Änderung gegenüber einem Aufrufer, der die Einträge bis zur Laufnummer
|
||||
/// `mark` aus seiner letzten Antwort (gleiche Argumente) noch hat, s. [`write_delta`].
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn parts(
|
||||
&mut self,
|
||||
p: &Project,
|
||||
revs: &crate::document::Revs,
|
||||
wall_stamps: &[u64],
|
||||
opening_stamps: &[u64],
|
||||
layered: bool,
|
||||
detail: f64,
|
||||
for_section: bool,
|
||||
structs: bool,
|
||||
delta: Option<u64>,
|
||||
) -> Result<CachedParts, String> {
|
||||
self.validate(p, revs);
|
||||
let openings = p.openings.as_deref().unwrap_or(&[]);
|
||||
if wall_stamps.len() != p.walls.len() || opening_stamps.len() != openings.len() {
|
||||
return Err("Element-Stände passen nicht zum Projekt".into());
|
||||
}
|
||||
// Gehostete Öffnungen je Wand-id in Projekt-Reihenfolge (wie `openings_by_wall`), mit Stand.
|
||||
let mut by_wall: HashMap<&str, Vec<usize>> = HashMap::new();
|
||||
for (i, o) in openings.iter().enumerate() {
|
||||
by_wall.entry(o.host_wall_id.as_str()).or_default().push(i);
|
||||
}
|
||||
let hosted = |id: &str| by_wall.get(id).map_or(&[][..], |v| v.as_slice());
|
||||
|
||||
// Wandkörper.
|
||||
let joins = if layered { Some(self.joins(p)) } else { None };
|
||||
let mut contexts: HashMap<&str, crate::wall_bands::FloorContext> = HashMap::new();
|
||||
let mut old = std::mem::take(&mut self.walls[layered as usize]);
|
||||
let mut fresh: HashMap<u64, WallEntry> = HashMap::with_capacity(p.walls.len());
|
||||
let mut rebuilt = (0, 0);
|
||||
for (wi, wall) in p.walls.iter().enumerate() {
|
||||
let stamp = wall_stamps[wi];
|
||||
let os: Vec<u64> = hosted(&wall.id).iter().map(|&i| opening_stamps[i]).collect();
|
||||
let cuts = if layered {
|
||||
joins.as_ref().and_then(|j| j.get(&wall.id)).cloned().unwrap_or_default()
|
||||
} else {
|
||||
WallCuts::default()
|
||||
};
|
||||
let e = match old.remove(&stamp) {
|
||||
Some(e) if e.openings == os && e.cuts == cuts => e,
|
||||
_ => {
|
||||
rebuilt.0 += 1;
|
||||
let ctx = contexts.entry(wall.floor_id.as_str()).or_insert_with(|| model3d::floor_context(p, &wall.floor_id, layered));
|
||||
let refs: Vec<&Opening> = hosted(&wall.id).iter().map(|&i| &openings[i]).collect();
|
||||
let mut pieces = Vec::new();
|
||||
model3d::wall_pieces(p, &self.maps, wall, ctx, &refs, cuts.clone(), layered, true, &mut pieces);
|
||||
let json = inner_json(&pieces);
|
||||
WallEntry {
|
||||
serial: next_serial(),
|
||||
openings: os,
|
||||
cuts,
|
||||
pieces,
|
||||
json,
|
||||
}
|
||||
}
|
||||
};
|
||||
fresh.insert(stamp, e);
|
||||
}
|
||||
// Öffnungs-Einbauteile (Bogenwände: ganz ohne Cache, s. `emit_opening_meshes`).
|
||||
let arcs = p.walls.iter().any(|w| crate::wall_arc::WallArc::of_wall(w).is_some());
|
||||
let dkey = detail.to_bits();
|
||||
let slot = match self.openings.iter().position(|(k, _)| *k == dkey) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
if self.openings.len() >= 3 {
|
||||
self.openings.remove(0);
|
||||
}
|
||||
self.openings.push((dkey, HashMap::new()));
|
||||
self.openings.len() - 1
|
||||
}
|
||||
};
|
||||
let mut open_fresh: HashMap<u64, OpenEntry> = HashMap::new();
|
||||
let mut arc_meshes: Option<Vec<RMesh>> = None;
|
||||
if arcs {
|
||||
self.openings[slot].1.clear();
|
||||
arc_meshes = Some(model3d::emit_opening_meshes(p, detail));
|
||||
} else {
|
||||
let mut old_open = std::mem::take(&mut self.openings[slot].1);
|
||||
for (wi, wall) in p.walls.iter().enumerate() {
|
||||
let stamp = wall_stamps[wi];
|
||||
let os: Vec<u64> = hosted(&wall.id).iter().map(|&i| opening_stamps[i]).collect();
|
||||
let e = match old_open.remove(&stamp) {
|
||||
Some(e) if e.openings == os => e,
|
||||
_ => {
|
||||
rebuilt.1 += 1;
|
||||
let refs: Vec<&Opening> = hosted(&wall.id).iter().map(|&i| &openings[i]).collect();
|
||||
let meshes = model3d::wall_opening_meshes(p, wall, &refs, detail);
|
||||
let json = [&meshes.passes[0], &meshes.passes[1], &meshes.passes[2], &meshes.zargen, &meshes.shaped].map(|v| inner_json(v));
|
||||
OpenEntry {
|
||||
serial: next_serial(),
|
||||
openings: os,
|
||||
meshes,
|
||||
json,
|
||||
}
|
||||
}
|
||||
};
|
||||
open_fresh.insert(stamp, e);
|
||||
}
|
||||
}
|
||||
self.last_rebuilt = rebuilt;
|
||||
|
||||
let mut slabs = model3d::emit_slabs(p);
|
||||
slabs.extend(model3d::emit_stairs(p, for_section));
|
||||
let mut parts = Parts {
|
||||
walls: Vec::new(),
|
||||
slabs,
|
||||
context_meshes: model3d::emit_context_meshes(p),
|
||||
column_meshes: model3d::emit_columns(p),
|
||||
opening_meshes: Vec::new(),
|
||||
stair_meshes: model3d::emit_stair_meshes(p),
|
||||
stair_railings: model3d::emit_stair_railings(p),
|
||||
roof_meshes: model3d::emit_roofs(p, None)?,
|
||||
roof_layers: model3d::emit_roof_cut_layers(p)?,
|
||||
};
|
||||
// JSON in einem Zug (wie `serde_json::to_string(&parts)`): Bruchstücke sammeln, dann einmal kopieren.
|
||||
let wall_entries: Vec<&WallEntry> = wall_stamps.iter().map(|s| &fresh[s]).collect();
|
||||
let open_entries: Vec<&OpenEntry> = if arcs { Vec::new() } else { wall_stamps.iter().map(|s| &open_fresh[s]).collect() };
|
||||
let surface = if arcs { Vec::new() } else { model3d::surface_window_meshes(p) };
|
||||
let opening_tail = match &arc_meshes {
|
||||
Some(m) => inner_json(m),
|
||||
None => inner_json(&surface),
|
||||
};
|
||||
let rest = [
|
||||
js(&parts.slabs)?,
|
||||
js(&parts.context_meshes)?,
|
||||
js(&parts.column_meshes)?,
|
||||
js(&parts.stair_meshes)?,
|
||||
js(&parts.stair_railings)?,
|
||||
js(&parts.roof_meshes)?,
|
||||
js(&parts.roof_layers)?,
|
||||
];
|
||||
let mut json = String::new();
|
||||
if let Some(mark) = delta {
|
||||
json = write_delta(mark, &wall_entries, &open_entries, &opening_tail, &rest);
|
||||
} else {
|
||||
let walls_frag = wall_entries.iter().map(|e| e.json.as_str());
|
||||
let opening_frags = (0..5).flat_map(|k| open_entries.iter().map(move |e| e.json[k].as_str())).chain([opening_tail.as_str()]);
|
||||
let cap = walls_frag.clone().chain(opening_frags.clone()).map(|s| s.len() + 1).sum::<usize>() + rest.iter().map(String::len).sum::<usize>() + 256;
|
||||
json.reserve(cap);
|
||||
json.push_str("{\"walls\":[");
|
||||
join_json(&mut json, walls_frag);
|
||||
json.push_str("],\"slabs\":");
|
||||
json.push_str(&rest[0]);
|
||||
json.push_str(",\"contextMeshes\":");
|
||||
json.push_str(&rest[1]);
|
||||
json.push_str(",\"columnMeshes\":");
|
||||
json.push_str(&rest[2]);
|
||||
json.push_str(",\"openingMeshes\":[");
|
||||
join_json(&mut json, opening_frags);
|
||||
json.push_str("],\"stairMeshes\":");
|
||||
json.push_str(&rest[3]);
|
||||
json.push_str(",\"stairRailings\":");
|
||||
json.push_str(&rest[4]);
|
||||
json.push_str(",\"roofMeshes\":");
|
||||
json.push_str(&rest[5]);
|
||||
json.push_str(",\"roofLayers\":");
|
||||
json.push_str(&rest[6]);
|
||||
json.push('}');
|
||||
}
|
||||
if structs {
|
||||
parts.walls = wall_entries.iter().flat_map(|e| e.pieces.iter().cloned()).collect();
|
||||
parts.opening_meshes = match arc_meshes {
|
||||
Some(m) => m,
|
||||
None => {
|
||||
let mut v = model3d::assemble_opening_meshes(open_entries.iter().map(|e| e.meshes.clone()).collect());
|
||||
v.extend(surface);
|
||||
v
|
||||
}
|
||||
};
|
||||
}
|
||||
drop((wall_entries, open_entries));
|
||||
self.walls[layered as usize] = fresh;
|
||||
if !arcs {
|
||||
self.openings[slot].1 = open_fresh;
|
||||
}
|
||||
Ok(CachedParts { parts, json })
|
||||
}
|
||||
}
|
||||
|
||||
/// Änderungs-JSON ([58], TS `ProjectDocument.model3dParts`): statt `walls`/`openingMeshes` die Laufnummern
|
||||
/// je Wand (`wallKeys`, `openingKeys`, Modell-Reihenfolge) und nur die Einträge mit Laufnummer > `mark`
|
||||
/// ausgeschrieben (`wallNew`: `[nr, [Körper…]]`, `openingNew`: `[nr, 3 Durchgänge, Zargen, Formöffnungen]`);
|
||||
/// `openingTail` = Dach-/Deckenfenster (bzw. alles bei Bogenwänden), `mark` = Stand für die nächste Frage.
|
||||
/// Gültig nur, wenn der Aufrufer die Einträge ≤ `mark` aus seiner letzten Antwort hat (sonst `mark` 0).
|
||||
fn write_delta(mark: u64, walls: &[&WallEntry], openings: &[&OpenEntry], opening_tail: &str, rest: &[String; 7]) -> String {
|
||||
use std::fmt::Write;
|
||||
let fresh = |serial: u64| mark == 0 || serial > mark || mark > current_serial();
|
||||
let cap = walls.iter().filter(|e| fresh(e.serial)).map(|e| e.json.len() + 32).sum::<usize>()
|
||||
+ openings
|
||||
.iter()
|
||||
.filter(|e| fresh(e.serial))
|
||||
.map(|e| e.json.iter().map(|j| j.len() + 4).sum::<usize>() + 32)
|
||||
.sum::<usize>()
|
||||
+ (walls.len() + openings.len()) * 12
|
||||
+ opening_tail.len()
|
||||
+ rest.iter().map(String::len).sum::<usize>()
|
||||
+ 512;
|
||||
let mut out = String::with_capacity(cap);
|
||||
let _ = write!(out, "{{\"mark\":{},\"wallKeys\":[", current_serial());
|
||||
for (i, e) in walls.iter().enumerate() {
|
||||
let _ = write!(out, "{}{}", if i > 0 { "," } else { "" }, e.serial);
|
||||
}
|
||||
out.push_str("],\"wallNew\":[");
|
||||
let mut first = true;
|
||||
for e in walls.iter().filter(|e| fresh(e.serial)) {
|
||||
let _ = write!(out, "{}[{},[{}]]", if first { "" } else { "," }, e.serial, e.json);
|
||||
first = false;
|
||||
}
|
||||
out.push_str("],\"openingKeys\":[");
|
||||
for (i, e) in openings.iter().enumerate() {
|
||||
let _ = write!(out, "{}{}", if i > 0 { "," } else { "" }, e.serial);
|
||||
}
|
||||
out.push_str("],\"openingNew\":[");
|
||||
let mut first = true;
|
||||
for e in openings.iter().filter(|e| fresh(e.serial)) {
|
||||
let _ = write!(out, "{}[{}", if first { "" } else { "," }, e.serial);
|
||||
for j in &e.json {
|
||||
let _ = write!(out, ",[{j}]");
|
||||
}
|
||||
out.push(']');
|
||||
first = false;
|
||||
}
|
||||
let _ = write!(
|
||||
out,
|
||||
"],\"openingTail\":[{opening_tail}],\"slabs\":{},\"contextMeshes\":{},\"columnMeshes\":{},\"stairMeshes\":{},\"stairRailings\":{},\"roofMeshes\":{},\"roofLayers\":{}}}",
|
||||
rest[0], rest[1], rest[2], rest[3], rest[4], rest[5], rest[6]
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
fn js<T: serde::Serialize>(v: &T) -> Result<String, String> {
|
||||
serde_json::to_string(v).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
impl Clone for Model3dCache {
|
||||
fn clone(&self) -> Self {
|
||||
Model3dCache::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::document::Document;
|
||||
use crate::ops::Op;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const ARGS: [[f64; 5]; 4] = [[1.0, 2.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 1.0, 0.0], [0.0, 1.0, 1.0, 0.0, 0.0], [1.0, 2.0, 0.0, 1.0, 0.0]];
|
||||
|
||||
/// Inkrementell (Cache des Dokuments) = voll (`queries::run` auf einer Kopie), Byte für Byte.
|
||||
fn check(d: &mut Document, clients: &mut [Client; 4], step: &str) {
|
||||
let p = d.project().unwrap().clone();
|
||||
for (a, c) in ARGS.iter().zip(clients.iter_mut()) {
|
||||
let inc = crate::queries::run_doc(d, "model3dParts", a, "").unwrap();
|
||||
let full = crate::queries::run(&p, "model3dParts", a, "").unwrap();
|
||||
assert!(inc == full, "{step}: model3dParts {a:?} weicht ab ({} / {} Zeichen)", inc.len(), full.len());
|
||||
// Änderungs-Antwort wie in TS (`ProjectDocument.model3dParts`) zusammengesetzt = voll.
|
||||
let mut da = a.to_vec();
|
||||
da.push(c.mark as f64);
|
||||
let delta = crate::queries::run_doc(d, "model3dPartsDelta", &da, "").unwrap();
|
||||
let got = c.apply(&delta);
|
||||
let want: Value = serde_json::from_str(&full).unwrap();
|
||||
assert!(got == want, "{step}: model3dPartsDelta {a:?} weicht ab");
|
||||
}
|
||||
}
|
||||
|
||||
/// Gegenstelle der Änderungs-Antworten (wie TS): hält die Einträge der letzten Antwort.
|
||||
#[derive(Default)]
|
||||
struct Client {
|
||||
mark: u64,
|
||||
walls: std::collections::HashMap<u64, Vec<Value>>,
|
||||
openings: std::collections::HashMap<u64, Vec<Vec<Value>>>,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
fn apply(&mut self, json: &str) -> Value {
|
||||
let r: Value = serde_json::from_str(json).unwrap();
|
||||
let key = |v: &Value| v.as_u64().unwrap();
|
||||
let arr = |v: &Value| v.as_array().unwrap().clone();
|
||||
let mut wn: std::collections::HashMap<u64, Vec<Value>> = r["wallNew"].as_array().unwrap().iter().map(|e| (key(&e[0]), arr(&e[1]))).collect();
|
||||
let mut on: std::collections::HashMap<u64, Vec<Vec<Value>>> = r["openingNew"].as_array().unwrap().iter().map(|e| (key(&e[0]), (1..6).map(|k| arr(&e[k])).collect())).collect();
|
||||
let (mut walls, mut nw) = (Vec::new(), std::collections::HashMap::new());
|
||||
for k in r["wallKeys"].as_array().unwrap().iter().map(key) {
|
||||
let e = wn.remove(&k).or_else(|| self.walls.remove(&k)).expect("Wand-Eintrag fehlt");
|
||||
walls.extend(e.iter().cloned());
|
||||
nw.insert(k, e);
|
||||
}
|
||||
let mut no = std::collections::HashMap::new();
|
||||
let keys: Vec<u64> = r["openingKeys"].as_array().unwrap().iter().map(key).collect();
|
||||
for &k in &keys {
|
||||
let e = on.remove(&k).or_else(|| self.openings.remove(&k)).expect("Öffnungs-Eintrag fehlt");
|
||||
no.insert(k, e);
|
||||
}
|
||||
let mut meshes = Vec::new();
|
||||
for l in 0..5 {
|
||||
for k in &keys {
|
||||
meshes.extend(no[k][l].iter().cloned());
|
||||
}
|
||||
}
|
||||
meshes.extend(arr(&r["openingTail"]));
|
||||
(self.mark, self.walls, self.openings) = (key(&r["mark"]), nw, no);
|
||||
let mut out = serde_json::Map::new();
|
||||
out.insert("walls".into(), Value::Array(walls));
|
||||
for k in ["slabs", "contextMeshes", "columnMeshes"] {
|
||||
out.insert(k.into(), r[k].clone());
|
||||
}
|
||||
out.insert("openingMeshes".into(), Value::Array(meshes));
|
||||
for k in ["stairMeshes", "stairRailings", "roofMeshes", "roofLayers", "voidCuts"] {
|
||||
if let Some(v) = r.get(k) {
|
||||
out.insert(k.into(), v.clone());
|
||||
}
|
||||
}
|
||||
Value::Object(out)
|
||||
}
|
||||
}
|
||||
|
||||
fn list(d: &Document, key: &str) -> Vec<Value> {
|
||||
d.root().get(key).and_then(Value::as_array).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
fn sample() -> Document {
|
||||
Document::from_json(include_str!("../tests/fixtures/sample_project.json")).unwrap()
|
||||
}
|
||||
|
||||
/// Eine Folge gemischter Änderungen (Wände, Öffnungen, Typen, Struktur, Undo/Redo): nach jedem Schritt gleich.
|
||||
#[test]
|
||||
fn incremental_equals_full_after_edits() {
|
||||
let mut d = sample();
|
||||
let mut clients: [Client; 4] = Default::default();
|
||||
check(&mut d, &mut clients, "start");
|
||||
let mut seed: u64 = 0x5eed;
|
||||
let mut rnd = |n: usize| {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
((seed >> 33) as usize) % n.max(1)
|
||||
};
|
||||
let mut kinds = [0usize; 11];
|
||||
for step in 0..80 {
|
||||
let walls = list(&d, "walls");
|
||||
let openings = list(&d, "openings");
|
||||
let kind = rnd(11);
|
||||
let ops: Vec<Op> = match kind {
|
||||
0 | 1 => {
|
||||
let mut w = walls[rnd(walls.len())].clone();
|
||||
let h = w["height"].as_f64().unwrap_or(2.6);
|
||||
w["height"] = json!(h + 0.1);
|
||||
vec![Op::Replace {
|
||||
collection: "walls".into(),
|
||||
entity: w,
|
||||
}]
|
||||
}
|
||||
2 => {
|
||||
// Endpunkt verschieben: ändert die Verschneidung der Nachbarn.
|
||||
let mut w = walls[rnd(walls.len())].clone();
|
||||
let x = w["end"]["x"].as_f64().unwrap_or(0.0);
|
||||
w["end"]["x"] = json!(x + 0.05);
|
||||
vec![Op::Replace {
|
||||
collection: "walls".into(),
|
||||
entity: w,
|
||||
}]
|
||||
}
|
||||
3 if !openings.is_empty() => {
|
||||
let mut o = openings[rnd(openings.len())].clone();
|
||||
let wd = o["width"].as_f64().unwrap_or(1.0);
|
||||
o["width"] = json!(wd * 0.9);
|
||||
vec![Op::Replace {
|
||||
collection: "openings".into(),
|
||||
entity: o,
|
||||
}]
|
||||
}
|
||||
4 if !openings.is_empty() => {
|
||||
// Öffnung in eine andere Wand umhängen.
|
||||
let mut o = openings[rnd(openings.len())].clone();
|
||||
o["hostWallId"] = walls[rnd(walls.len())]["id"].clone();
|
||||
vec![Op::Replace {
|
||||
collection: "openings".into(),
|
||||
entity: o,
|
||||
}]
|
||||
}
|
||||
5 => {
|
||||
let mut w = walls[rnd(walls.len())].clone();
|
||||
w["id"] = json!(format!("neu{step}"));
|
||||
w["start"]["y"] = json!(w["start"]["y"].as_f64().unwrap_or(0.0) + 0.3);
|
||||
vec![Op::Add {
|
||||
collection: "walls".into(),
|
||||
items: vec![w],
|
||||
at: Some(rnd(walls.len())),
|
||||
}]
|
||||
}
|
||||
6 if walls.len() > 3 => vec![Op::Remove {
|
||||
collection: "walls".into(),
|
||||
ids: vec![walls[rnd(walls.len())]["id"].as_str().unwrap().to_owned()],
|
||||
}],
|
||||
7 => {
|
||||
// Wandtyp ändern (globales Feld): alles neu.
|
||||
let mut ts = list(&d, "wallTypes");
|
||||
let t = rnd(ts.len());
|
||||
if let Some(l) = ts[t]["layers"].get_mut(0) {
|
||||
let th = l["thickness"].as_f64().unwrap_or(0.1);
|
||||
l["thickness"] = json!(th + 0.01);
|
||||
}
|
||||
vec![Op::Replace {
|
||||
collection: "wallTypes".into(),
|
||||
entity: ts.swap_remove(t),
|
||||
}]
|
||||
}
|
||||
8 => {
|
||||
if d.undo().is_some() {
|
||||
kinds[kind] += 1;
|
||||
check(&mut d, &mut clients, &format!("Schritt {step} (undo)"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
9 => {
|
||||
if d.redo().is_some() {
|
||||
kinds[kind] += 1;
|
||||
check(&mut d, &mut clients, &format!("Schritt {step} (redo)"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ => {
|
||||
let ids: Vec<String> = walls.iter().rev().map(|w| w["id"].as_str().unwrap().to_owned()).collect();
|
||||
vec![Op::Reorder { collection: "walls".into(), ids }]
|
||||
}
|
||||
};
|
||||
kinds[kind] += 1;
|
||||
d.commit(ops, None, step as f64, false).unwrap_or_else(|e| panic!("Schritt {step}: {e:?}"));
|
||||
check(&mut d, &mut clients, &format!("Schritt {step} (Art {kind})"));
|
||||
}
|
||||
// Jede Art kam vor (sonst prüft die Folge weniger als gedacht).
|
||||
assert!(kinds.iter().all(|&k| k > 0), "{kinds:?}");
|
||||
}
|
||||
|
||||
/// Eine Wandhöhe ändern: nur diese Wand (Körper und Einbauteile) wird neu gerechnet.
|
||||
#[test]
|
||||
fn one_wall_edit_rebuilds_one_wall() {
|
||||
let mut d = sample();
|
||||
let n = d.project().unwrap().walls.len();
|
||||
d.model3d_parts(true, 2.0, false, false, None).unwrap();
|
||||
assert_eq!(d.model3d_rebuilt(), (n, n));
|
||||
d.model3d_parts(true, 2.0, false, false, None).unwrap();
|
||||
assert_eq!(d.model3d_rebuilt(), (0, 0));
|
||||
let mut w = list(&d, "walls")[2].clone();
|
||||
w["height"] = json!(w["height"].as_f64().unwrap_or(2.6) + 0.2);
|
||||
d.commit(
|
||||
vec![Op::Replace {
|
||||
collection: "walls".into(),
|
||||
entity: w,
|
||||
}],
|
||||
None,
|
||||
0.0,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
d.model3d_parts(true, 2.0, false, false, None).unwrap();
|
||||
assert_eq!(d.model3d_rebuilt(), (1, 1));
|
||||
// Öffnung ändern: nur ihre Wirtswand.
|
||||
let mut o = list(&d, "openings")[0].clone();
|
||||
o["width"] = json!(o["width"].as_f64().unwrap_or(1.0) - 0.1);
|
||||
d.commit(
|
||||
vec![Op::Replace {
|
||||
collection: "openings".into(),
|
||||
entity: o,
|
||||
}],
|
||||
None,
|
||||
1.0,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
d.model3d_parts(true, 2.0, false, false, None).unwrap();
|
||||
assert_eq!(d.model3d_rebuilt(), (1, 1));
|
||||
d.undo();
|
||||
d.model3d_parts(true, 2.0, false, false, None).unwrap();
|
||||
assert_eq!(d.model3d_rebuilt(), (1, 1));
|
||||
}
|
||||
}
|
||||
@@ -1030,9 +1030,17 @@ fn kassette(em: &mut Emitter, leaf_from: f64, leaf_to: f64, leaf_bottom: f64, le
|
||||
/// aller Wände (`emitOpeningGlass`), dann Rahmen (`emitOpeningFrames`, nicht bei grob), dann
|
||||
/// Rollladenkästen (`emitOpeningShading`, nicht bei grob).
|
||||
pub fn opening_meshes(walls: &[WallIn], detail: Detail) -> Vec<BoxMesh> {
|
||||
let per: Vec<[Vec<BoxMesh>; 3]> = walls.iter().map(|w| wall_mesh_passes(w, detail)).collect();
|
||||
(0..3).flat_map(|k| per.iter().flat_map(move |p| p[k].iter().cloned())).collect()
|
||||
}
|
||||
|
||||
/// Die Quader EINER Wand in den drei Durchgängen von [`opening_meshes`] (Scheiben/Blätter/Anschläge,
|
||||
/// Rahmen, Sonnenschutz): das ganze Modell reiht erst alle Wände des ersten Durchgangs, dann des zweiten
|
||||
/// usw. — so kann der 3D-Cache ([58], `model3d_cache.rs`) die Teile je Wand behalten.
|
||||
pub fn wall_mesh_passes(w: &WallIn, detail: Detail) -> [Vec<BoxMesh>; 3] {
|
||||
let mut out = Vec::new();
|
||||
let open = |o: &OpeningIn| !(o.z_top - o.z_bottom <= EPS);
|
||||
for w in walls {
|
||||
{
|
||||
let mut em = Emitter { axis: Axis::of(w.start, w.end), out: &mut out };
|
||||
for o in w.openings.iter().filter(|o| open(o)) {
|
||||
let params = resolve_frame(o);
|
||||
@@ -1052,9 +1060,10 @@ pub fn opening_meshes(walls: &[WallIn], detail: Detail) -> Vec<BoxMesh> {
|
||||
}
|
||||
}
|
||||
if detail == Detail::Coarse {
|
||||
return out;
|
||||
return [out, Vec::new(), Vec::new()];
|
||||
}
|
||||
for w in walls {
|
||||
let first = std::mem::take(&mut out);
|
||||
{
|
||||
let mut em = Emitter { axis: Axis::of(w.start, w.end), out: &mut out };
|
||||
for o in w.openings.iter().filter(|o| open(o)) {
|
||||
if let Some(p) = resolve_frame(o) {
|
||||
@@ -1062,7 +1071,8 @@ pub fn opening_meshes(walls: &[WallIn], detail: Detail) -> Vec<BoxMesh> {
|
||||
}
|
||||
}
|
||||
}
|
||||
for w in walls {
|
||||
let second = std::mem::take(&mut out);
|
||||
{
|
||||
let mut em = Emitter { axis: Axis::of(w.start, w.end), out: &mut out };
|
||||
for o in w.openings.iter().filter(|o| open(o)) {
|
||||
let Some(TypeIn { kind: KindIn::Window(wt), .. }) = &o.ty else { continue };
|
||||
@@ -1093,7 +1103,7 @@ pub fn opening_meshes(walls: &[WallIn], detail: Detail) -> Vec<BoxMesh> {
|
||||
em.axis_box(from, to, o.z_top, o.z_top + h, n_outer, n_outer + d, Part::Shading);
|
||||
}
|
||||
}
|
||||
out
|
||||
[first, second, out]
|
||||
}
|
||||
|
||||
// ── Flache Kodierung ─────────────────────────────────────────────────────────
|
||||
@@ -1270,10 +1280,21 @@ fn decode(buf: &[f64]) -> Option<(Vec<WallIn>, Detail)> {
|
||||
/// Flache Bindung (Kodierung s. oben); nie ein Panic.
|
||||
pub fn opening_meshes_flat(buf: &[f64]) -> Vec<f64> {
|
||||
let Some((walls, detail)) = decode(buf) else { return vec![0.0] };
|
||||
let meshes = opening_meshes(&walls, detail);
|
||||
flat_out(&opening_meshes(&walls, detail))
|
||||
}
|
||||
|
||||
/// Wie [`opening_meshes_flat`], aber je Durchgang ([`wall_mesh_passes`]) ein eigener Puffer, über
|
||||
/// alle Wände der Eingabe gereiht ([58]: die Eingabe ist dort eine einzelne Wand).
|
||||
pub fn opening_mesh_passes_flat(buf: &[f64]) -> [Vec<f64>; 3] {
|
||||
let Some((walls, detail)) = decode(buf) else { return [vec![0.0], vec![0.0], vec![0.0]] };
|
||||
let per: Vec<[Vec<BoxMesh>; 3]> = walls.iter().map(|w| wall_mesh_passes(w, detail)).collect();
|
||||
[0, 1, 2].map(|k| flat_out(&per.iter().flat_map(|p| p[k].iter().cloned()).collect::<Vec<_>>()))
|
||||
}
|
||||
|
||||
fn flat_out(meshes: &[BoxMesh]) -> Vec<f64> {
|
||||
let mut out = Vec::with_capacity(1 + meshes.len() * 25);
|
||||
out.push(meshes.len() as f64);
|
||||
for m in &meshes {
|
||||
for m in meshes {
|
||||
out.push(m.part as i32 as f64);
|
||||
out.extend_from_slice(&m.positions);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,38 @@ fn json<T: serde::Serialize>(v: &T) -> Result<String, String> {
|
||||
serde_json::to_string(v).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Wie [`run`] auf dem Dokument: das 3D-Modell (`model3dParts` ohne Explosion) über den Cache des
|
||||
/// Dokuments ([58], `model3d_cache`) — gleiches JSON wie [`run`].
|
||||
pub fn run_doc(d: &mut crate::document::Document, name: &str, args: &[f64], text: &str) -> Result<String, String> {
|
||||
let explode = args.get(4).copied().is_some_and(|g| g.is_finite() && g > 0.0);
|
||||
// `model3dPartsDelta`: wie `model3dParts` (ohne Explosion), `args[5]` = Laufnummer der letzten Antwort
|
||||
// des Aufrufers (0 = alles), Antwort als Änderung (`model3d_cache::write_delta`).
|
||||
let delta = (name == "model3dPartsDelta").then(|| args.get(5).copied().filter(|m| m.is_finite() && *m >= 0.0).unwrap_or(0.0) as u64);
|
||||
if (name == "model3dParts" || delta.is_some()) && args.len() >= 3 && !explode {
|
||||
let voids = args.get(3).is_some_and(|v| *v != 0.0);
|
||||
let out = d.model3d_parts(args[0] != 0.0, args[1], args[2] != 0.0, voids, delta)?;
|
||||
if voids {
|
||||
let p = d.project()?;
|
||||
let cuts = crate::solid_specs::void_cuts(p, &out.parts.walls, &out.parts.slabs);
|
||||
return with_void_cuts(out.json, &cuts);
|
||||
}
|
||||
return Ok(out.json);
|
||||
}
|
||||
let p = d.project().map_err(|e| format!("Projekt passt nicht zum Kern-Modell: {e}"))?;
|
||||
run(p, name, args, text)
|
||||
}
|
||||
|
||||
/// Das JSON-Objekt der Teile um `voidCuts` ergänzen (hinten angefügt statt über `serde_json::Value`).
|
||||
fn with_void_cuts(mut parts: String, cuts: &crate::solid_specs::VoidCuts) -> Result<String, String> {
|
||||
if parts.pop() != Some('}') {
|
||||
return Err("model3dParts: kein JSON-Objekt".into());
|
||||
}
|
||||
parts.push_str(",\"voidCuts\":");
|
||||
parts.push_str(&json(cuts)?);
|
||||
parts.push('}');
|
||||
Ok(parts)
|
||||
}
|
||||
|
||||
/// Führt die Abfrage `name` aus. `args`: Zahlen, `text`: ein Text (z. B. eine id).
|
||||
pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String, String> {
|
||||
match (name, args.len()) {
|
||||
@@ -69,9 +101,7 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
|
||||
let parts = model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?;
|
||||
if args.get(3).is_some_and(|v| *v != 0.0) {
|
||||
let cuts = crate::solid_specs::void_cuts(p, &parts.walls, &parts.slabs);
|
||||
let mut v = serde_json::to_value(&parts).map_err(|e| e.to_string())?;
|
||||
v["voidCuts"] = serde_json::to_value(&cuts).map_err(|e| e.to_string())?;
|
||||
return Ok(v.to_string());
|
||||
return with_void_cuts(json(&parts)?, &cuts);
|
||||
}
|
||||
json(&parts)
|
||||
}
|
||||
|
||||
@@ -240,10 +240,7 @@ pub fn doc_json(h: u32) -> String {
|
||||
/// `\u{1}`. Abfragen s. `crate::queries`.
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_query_args(h: u32, name: &str, args: &[f64], text: &str) -> String {
|
||||
let result = with_doc(h, |d| {
|
||||
let p = d.project().map_err(|e| format!("Projekt passt nicht zum Kern-Modell: {e}"))?;
|
||||
crate::queries::run(&p, name, args, text)
|
||||
})
|
||||
let result = with_doc(h, |d| crate::queries::run_doc(d, name, args, text))
|
||||
.unwrap_or_else(|| Err("Dokument nicht offen".to_string()));
|
||||
match result {
|
||||
Ok(json) => json,
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
// Zeitprofil projectToModel3d am Grossgebäude ([58]); `BIG_OBP=… cargo test --release --test bench58 -- --nocapture --ignored`.
|
||||
use dossier_core::model3d as m;
|
||||
use std::time::Instant;
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn profile_model3d() {
|
||||
let path = std::env::var("BIG_OBP").expect("BIG_OBP");
|
||||
let text = std::fs::read_to_string(path).unwrap();
|
||||
let mut d = dossier_core::document::Document::from_json(&text).unwrap();
|
||||
let p = d.project().unwrap().clone();
|
||||
let t = |name: &str, f: &dyn Fn()| {
|
||||
f();
|
||||
let t0 = Instant::now();
|
||||
for _ in 0..3 {
|
||||
f();
|
||||
}
|
||||
println!("{name:30} {:8.2} ms", t0.elapsed().as_secs_f64() * 1000.0 / 3.0);
|
||||
};
|
||||
t("parts", &|| {
|
||||
m::parts(&p, true, 2.0, false).unwrap();
|
||||
});
|
||||
t("json(parts)", &|| {
|
||||
let x = m::parts(&p, true, 2.0, false).unwrap();
|
||||
serde_json::to_string(&x).unwrap();
|
||||
});
|
||||
t("emit_slabs", &|| {
|
||||
m::emit_slabs(&p);
|
||||
});
|
||||
t("emit_stairs", &|| {
|
||||
m::emit_stairs(&p, false);
|
||||
});
|
||||
t("emit_walls", &|| {
|
||||
m::emit_walls(&p, true).unwrap();
|
||||
});
|
||||
t("emit_context_meshes", &|| {
|
||||
m::emit_context_meshes(&p);
|
||||
});
|
||||
t("emit_columns", &|| {
|
||||
m::emit_columns(&p);
|
||||
});
|
||||
t("emit_opening_meshes", &|| {
|
||||
m::emit_opening_meshes(&p, 2.0);
|
||||
});
|
||||
t("emit_stair_meshes", &|| {
|
||||
m::emit_stair_meshes(&p);
|
||||
});
|
||||
t("emit_stair_railings", &|| {
|
||||
m::emit_stair_railings(&p);
|
||||
});
|
||||
t("emit_roofs", &|| {
|
||||
m::emit_roofs(&p, None).unwrap();
|
||||
});
|
||||
t("emit_roof_cut_layers", &|| {
|
||||
m::emit_roof_cut_layers(&p).unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
/// Inkrementell über das Dokument: erste Abfrage, ohne Änderung, nach 1 Wand-Änderung; gleich wie voll.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn incremental_model3d() {
|
||||
for f in std::env::var("DUMP_FILES").expect("DUMP_FILES").split(',') {
|
||||
for args in [[1.0, 2.0, 0.0, 0.0, 0.0], [1.0, 2.0, 0.0, 1.0, 0.0]] {
|
||||
let text = std::fs::read_to_string(f).unwrap();
|
||||
let mut d = dossier_core::document::Document::from_json(&text).unwrap();
|
||||
let t0 = Instant::now();
|
||||
dossier_core::queries::run_doc(&mut d, "model3dParts", &args, "").unwrap();
|
||||
let first = t0.elapsed().as_secs_f64() * 1000.0;
|
||||
let t0 = Instant::now();
|
||||
dossier_core::queries::run_doc(&mut d, "model3dParts", &args, "").unwrap();
|
||||
let same = t0.elapsed().as_secs_f64() * 1000.0;
|
||||
let mut w = d.root()["walls"][3].clone();
|
||||
w["height"] = serde_json::json!(w["height"].as_f64().unwrap_or(2.6) + 0.1);
|
||||
d.commit(
|
||||
vec![dossier_core::ops::Op::Replace {
|
||||
collection: "walls".into(),
|
||||
entity: w,
|
||||
}],
|
||||
None,
|
||||
0.0,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
let t0 = Instant::now();
|
||||
let inc = dossier_core::queries::run_doc(&mut d, "model3dParts", &args, "").unwrap();
|
||||
let edit = t0.elapsed().as_secs_f64() * 1000.0;
|
||||
let p = d.project().unwrap().clone();
|
||||
let t0 = Instant::now();
|
||||
let full = dossier_core::queries::run(&p, "model3dParts", &args, "").unwrap();
|
||||
let full_ms = t0.elapsed().as_secs_f64() * 1000.0;
|
||||
assert!(inc == full, "{f}: inkrementell ≠ voll");
|
||||
println!(
|
||||
"{args:?} {f}: erste {first:.1} ms, gleich {same:.1} ms, nach 1 Wand {edit:.1} ms (neu {:?}), voll {full_ms:.1} ms",
|
||||
d.model3d_rebuilt()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn dump_parts() {
|
||||
let out = std::env::var("DUMP_OUT").expect("DUMP_OUT");
|
||||
for f in std::env::var("DUMP_FILES").expect("DUMP_FILES").split(',') {
|
||||
let text = std::fs::read_to_string(f).unwrap();
|
||||
let mut d = dossier_core::document::Document::from_json(&text).unwrap();
|
||||
let p = d.project().unwrap().clone();
|
||||
let name = std::path::Path::new(f).file_stem().unwrap().to_string_lossy().to_string();
|
||||
for (layered, detail) in [(true, 2.0), (true, 0.0), (false, 1.0)] {
|
||||
let x = m::parts(&p, layered, detail, false).unwrap();
|
||||
std::fs::write(format!("{out}/{name}.{layered}.{detail}.json"), serde_json::to_string(&x).unwrap()).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
+31
-1
@@ -858,7 +858,16 @@ async function execute(project: Project, file: string, command: string, rest: st
|
||||
await time("planToRenderScene", () => planToRenderScene(plan));
|
||||
await time("planToSvgString", () => planToSvgString(plan, { scaleDenominator: scale }));
|
||||
}
|
||||
await time("projectToModel3d", () => projectToModel3d(project));
|
||||
{
|
||||
// Erstes Mal auf einem frischen Dokument (ohne Cache, [58]); die Zeile darunter misst die Wiederholung.
|
||||
const cold = structuredClone(project);
|
||||
withDocument(cold, () => {
|
||||
const t0 = performance.now();
|
||||
projectToModel3d(cold);
|
||||
rows.push(["projectToModel3d (kalt)", performance.now() - t0]);
|
||||
});
|
||||
}
|
||||
await time("projectToModel3d (unverändert)", () => projectToModel3d(project));
|
||||
if (sec) await time("Schnitt (Kern)", async () => generateSectionPlan((await computeSection(project, sec))!, false, { visibleCodes: allCodes }), Math.max(3, runs / 2));
|
||||
if (elev) await time("generateElevationPlan", () => generateElevationPlan(project, elev), Math.max(3, runs / 2));
|
||||
if (project.walls.length) {
|
||||
@@ -896,6 +905,27 @@ async function execute(project: Project, file: string, command: string, rest: st
|
||||
const r = doc.commit(cur, opsFor({ ...cur, walls: cur.walls.slice(0, 1) } as Project, 0.01 * ++k).slice(0, 1), undefined, Date.now());
|
||||
if ("project" in r) cur = r.project;
|
||||
}, runs * 5);
|
||||
// [58] Inkrementelle 3D-Ableitung (Cache im Dokument, Änderungs-Antworten): eine Änderung, dann das ganze
|
||||
// 3D-Modell neu abfragen; zum Vergleich die volle Abfrage ohne Cache-Weg in TS.
|
||||
lap("projectToModel3d (Dokument)", () => projectToModel3d(cur));
|
||||
lap(" model3dParts voll: Kern (JSON)", () => doc.queryJson("model3dParts", [1, 2, 0, 0, 0]));
|
||||
const partsJson = doc.queryJson("model3dParts", [1, 2, 0, 0, 0]);
|
||||
lap(" model3dParts voll: JSON.parse", () => JSON.parse(partsJson));
|
||||
lap("projectToModel3d nach 1 Wand-Änderung", () => {
|
||||
const w = cur.walls[++k % cur.walls.length];
|
||||
const r = doc.commit(cur, patchItem(cur, "walls", w.id, { height: (w.height ?? 2.6) + (k % 2 ? 0.01 : -0.01) }), undefined, Date.now());
|
||||
if ("project" in r) cur = r.project;
|
||||
projectToModel3d(cur);
|
||||
});
|
||||
const ops = cur.openings ?? [];
|
||||
if (ops.length) {
|
||||
lap("projectToModel3d nach 1 Öffnungs-Änderung", () => {
|
||||
const o = (cur.openings ?? [])[++k % ops.length];
|
||||
const r = doc.commit(cur, patchItem(cur, "openings", o.id, { width: o.width + (k % 2 ? 0.01 : -0.01) }), undefined, Date.now());
|
||||
if ("project" in r) cur = r.project;
|
||||
projectToModel3d(cur);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
for (const [n, ms] of rows) process.stdout.write(`${n.padEnd(28)} ${ms.toFixed(2).padStart(9)} ms\n`);
|
||||
|
||||
@@ -50,6 +50,51 @@ export interface IfcFlatInput {
|
||||
elementData?: Float64Array;
|
||||
}
|
||||
|
||||
/** Änderungs-Antwort des 3D-Modells (Kern `model3d_cache::write_delta`). */
|
||||
interface Model3dDelta {
|
||||
mark: number;
|
||||
wallKeys: number[];
|
||||
wallNew: [number, unknown[]][];
|
||||
openingKeys: number[];
|
||||
openingNew: [number, unknown[], unknown[], unknown[], unknown[], unknown[]][];
|
||||
openingTail: unknown[];
|
||||
[rest: string]: unknown;
|
||||
}
|
||||
|
||||
/** Gelesene Einträge der letzten Antwort (Laufnummer → Wandkörper bzw. 5 Listen Einbauteile). */
|
||||
interface Model3dDeltaCache {
|
||||
mark: number;
|
||||
walls: Map<number, unknown[]>;
|
||||
openings: Map<number, unknown[][]>;
|
||||
}
|
||||
|
||||
/** Setzt die Teile aus Antwort und gehaltenen Einträgen zusammen; `null`, wenn ein Eintrag fehlt. */
|
||||
function assembleModel3dDelta(r: Model3dDelta, cache: Model3dDeltaCache | undefined): { parts: Record<string, unknown>; cache: Model3dDeltaCache } | null {
|
||||
const wallNew = new Map(r.wallNew);
|
||||
const walls: unknown[] = [];
|
||||
const wallMap = new Map<number, unknown[]>();
|
||||
for (const k of r.wallKeys) {
|
||||
const e = wallNew.get(k) ?? cache?.walls.get(k);
|
||||
if (!e) return null;
|
||||
for (const x of e) walls.push(x);
|
||||
wallMap.set(k, e);
|
||||
}
|
||||
const openNew = new Map(r.openingNew.map(([k, ...lists]) => [k, lists] as const));
|
||||
const openMap = new Map<number, unknown[][]>();
|
||||
const entries: unknown[][][] = [];
|
||||
for (const k of r.openingKeys) {
|
||||
const e = openNew.get(k) ?? cache?.openings.get(k);
|
||||
if (!e) return null;
|
||||
entries.push(e);
|
||||
openMap.set(k, e);
|
||||
}
|
||||
const openingMeshes: unknown[] = [];
|
||||
for (let l = 0; l < 5; l++) for (const e of entries) for (const x of e[l]) openingMeshes.push(x);
|
||||
for (const x of r.openingTail) openingMeshes.push(x);
|
||||
const { mark, wallKeys: _wk, wallNew: _wn, openingKeys: _ok, openingNew: _on, openingTail: _ot, ...rest } = r;
|
||||
return { parts: { ...rest, walls, openingMeshes }, cache: { mark, walls: wallMap, openings: openMap } };
|
||||
}
|
||||
|
||||
/** Ergebnis des Ladens einer Projektdatei ({@link ProjectDocument.loadFile}). */
|
||||
export type LoadFileResult =
|
||||
| { ok: true; project: Project; warnings: string[]; migratedFrom: number | null }
|
||||
@@ -93,6 +138,7 @@ export type QueryName =
|
||||
| "pickGeometry"
|
||||
| "explodeOffsets"
|
||||
| "model3dParts"
|
||||
| "model3dPartsDelta"
|
||||
| "projectSolidSpecs"
|
||||
| "planDomains"
|
||||
| "ifcExportData"
|
||||
@@ -118,6 +164,8 @@ export class ProjectDocument {
|
||||
private limits: [number, number] | null = null;
|
||||
/** Stände grosser Verlaufsschritte (Undo/Redo ohne Ops-Rückgabe, s. `stepStates.ts`). */
|
||||
private steps = new StepStates();
|
||||
/** Gelieferte Einträge des 3D-Modells je Argument-Satz ([58], {@link model3dParts}). */
|
||||
private m3d = new Map<string, Model3dDeltaCache>();
|
||||
|
||||
constructor(project: Project) {
|
||||
this.mirror = project;
|
||||
@@ -137,6 +185,7 @@ export class ProjectDocument {
|
||||
* Änderung, deren Aufruf den Panic auslöste, war noch nicht übernommen). Der Verlauf beginnt leer.
|
||||
*/
|
||||
restoreAfterRestart(): void {
|
||||
this.m3d.clear();
|
||||
const wasOpen = this.handle !== 0;
|
||||
this.handle = 0;
|
||||
this.steps.clear();
|
||||
@@ -144,6 +193,7 @@ export class ProjectDocument {
|
||||
}
|
||||
|
||||
private reopen(project: Project): void {
|
||||
this.m3d.clear();
|
||||
if (this.handle) core().doc_close(this.handle);
|
||||
this.handle = core().doc_open(JSON.stringify(project));
|
||||
if (!this.handle) console.warn("Projekt-Dokument im Kern konnte nicht geöffnet werden.");
|
||||
@@ -159,6 +209,32 @@ export class ProjectDocument {
|
||||
return JSON.parse(this.queryJson(name, args, text)) as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* Teile des 3D-Modells (`model3dParts` ohne Explosion, `args` = deren 5 Zahlen) über Änderungs-Antworten
|
||||
* ([58], Kern `model3d_cache.rs`): der Kern schreibt nur die Wände/Öffnungs-Einbauteile aus, die seit der
|
||||
* letzten Antwort für dieselben Argumente neu sind; die übrigen kommen aus den hier gehaltenen, schon
|
||||
* gelesenen Einträgen. Ergebnis wie `query("model3dParts", args)`. Die Einträge werden zwischen den
|
||||
* Ergebnissen geteilt — nicht verändern.
|
||||
*/
|
||||
model3dParts<T>(args: number[]): T {
|
||||
const a = [0, 0, 0, 0, 0].map((d, i) => args[i] ?? d);
|
||||
const key = a.join(",");
|
||||
let cache = this.m3d.get(key);
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
const r = JSON.parse(this.queryJson("model3dPartsDelta", [...a, cache?.mark ?? 0])) as Model3dDelta;
|
||||
const out = assembleModel3dDelta(r, cache);
|
||||
if (out) {
|
||||
this.m3d.delete(key);
|
||||
this.m3d.set(key, out.cache);
|
||||
if (this.m3d.size > 4) this.m3d.delete(this.m3d.keys().next().value!);
|
||||
return out.parts as T;
|
||||
}
|
||||
// Ein Eintrag fehlt (sollte nicht vorkommen): einmal alles neu anfordern.
|
||||
cache = undefined;
|
||||
}
|
||||
throw new Error("Kern-Abfrage „model3dPartsDelta“: Einträge fehlen");
|
||||
}
|
||||
|
||||
/** Wie {@link query}, aber das JSON als Text (spart das Parsen, wenn es nur weitergereicht wird). */
|
||||
queryJson(name: QueryName, args: number[] = [], text = ""): string {
|
||||
if (!this.handle) throw new Error(`Kern-Abfrage „${name}": Dokument nicht offen`);
|
||||
@@ -194,6 +270,7 @@ export class ProjectDocument {
|
||||
load(project: Project): void {
|
||||
this.mirror = project;
|
||||
this.steps.clear();
|
||||
this.m3d.clear();
|
||||
if (!this.handle || !core().doc_load_json(this.handle, JSON.stringify(project))) this.reopen(project);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* [58] Inkrementelle 3D-Ableitung: `ProjectDocument.model3dParts` (Änderungs-Antworten, nur neue Einträge
|
||||
* je Wand) ergibt nach Änderungen, Undo und Redo dasselbe wie die volle Abfrage `model3dParts`.
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Project } from "../model/types";
|
||||
import { withDocument } from "../core/document";
|
||||
import { addItems, patchItem, removeItems } from "../core/opsBuild";
|
||||
import { projectToModel3d } from "./toWalls3d";
|
||||
|
||||
const ARGS = [
|
||||
[1, 2, 0, 0, 0],
|
||||
[1, 0, 0, 0, 0],
|
||||
[0, 1, 1, 0, 0],
|
||||
];
|
||||
|
||||
describe("3D-Modell inkrementell", () => {
|
||||
it("gleich wie voll nach Änderungen, Undo und Redo", () => {
|
||||
withDocument(sampleProject, (doc) => {
|
||||
let cur: Project = sampleProject;
|
||||
const check = (step: string) => {
|
||||
for (const a of ARGS) {
|
||||
expect(doc.model3dParts(a), `${step} ${a}`).toEqual(JSON.parse(doc.queryJson("model3dParts", a)));
|
||||
}
|
||||
};
|
||||
const commit = (ops: ReturnType<typeof patchItem>) => {
|
||||
const r = doc.commit(cur, ops, undefined, Date.now());
|
||||
if ("project" in r) cur = r.project;
|
||||
else throw new Error(r.problems.join("; "));
|
||||
};
|
||||
check("Start");
|
||||
const openings = cur.openings ?? [];
|
||||
expect(openings.length).toBeGreaterThan(0);
|
||||
for (let i = 0; i < 12; i++) {
|
||||
const w = cur.walls[(i * 5) % cur.walls.length];
|
||||
switch (i % 6) {
|
||||
case 0:
|
||||
commit(patchItem(cur, "walls", w.id, { height: (w.height ?? 2.6) + 0.1 }));
|
||||
break;
|
||||
case 1:
|
||||
commit(patchItem(cur, "walls", w.id, { end: { x: w.end.x + 0.05, y: w.end.y } }));
|
||||
break;
|
||||
case 2: {
|
||||
const o = (cur.openings ?? [])[i % openings.length];
|
||||
commit(patchItem(cur, "openings", o.id, { width: o.width * 0.9 }));
|
||||
break;
|
||||
}
|
||||
case 3:
|
||||
commit(addItems("walls", [{ ...w, id: `neu${i}`, start: { x: w.start.x, y: w.start.y + 0.4 } }]));
|
||||
break;
|
||||
case 4:
|
||||
commit(removeItems(cur, "walls", [w.id]));
|
||||
break;
|
||||
default: {
|
||||
const u = doc.undo(cur);
|
||||
if (u) cur = u;
|
||||
check(`Undo ${i}`);
|
||||
const r = doc.redo(cur);
|
||||
if (r) cur = r;
|
||||
}
|
||||
}
|
||||
check(`Schritt ${i}`);
|
||||
}
|
||||
// Die Fassade liefert dasselbe Modell wie ein frisch geöffnetes Dokument.
|
||||
const inc = JSON.stringify(projectToModel3d(cur));
|
||||
const copy = structuredClone(cur);
|
||||
const fresh = withDocument(copy, () => JSON.stringify(projectToModel3d(copy)));
|
||||
expect(inc).toBe(fresh);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -169,10 +169,10 @@ export function projectToModel3d(project: Project, opts: Model3dOptions = {}): R
|
||||
// Mit `voids` liefert der Kern zusätzlich die getroffenen Wände/Decken als truck-Spezifikationen.
|
||||
const explode = explodeGap(opts.explode);
|
||||
const voids = !!opts.voids && typeof window !== "undefined";
|
||||
const parts = documentFor(project).query<Model3dParts>(
|
||||
"model3dParts",
|
||||
[layered ? 1 : 0, DETAIL_CODE[detail] ?? 3, opts.forSection ? 1 : 0, voids ? 1 : 0, explode],
|
||||
);
|
||||
const args = [layered ? 1 : 0, DETAIL_CODE[detail] ?? 3, opts.forSection ? 1 : 0, voids ? 1 : 0, explode];
|
||||
// Ohne Explosion inkrementell ([58]): nur geänderte Wände reisen aus dem Kern und werden gelesen.
|
||||
const doc = documentFor(project);
|
||||
const parts = explode > 0 ? doc.query<Model3dParts>("model3dParts", args) : doc.model3dParts<Model3dParts>(args);
|
||||
// Die truck-Körper (asynchron, mit Cache) kommen zwischen Kontext-Meshes und Stützen.
|
||||
const meshes: RMesh[] = [...parts.contextMeshes];
|
||||
for (const m of emitExtrudedSolids(project, parts.floorOffsets)) meshes.push(m);
|
||||
|
||||
Reference in new issue
Block a user