[58] 3D-Ableitung inkrementell: Cache je Wand (Körper, Öffnungs-Einbauteile, JSON) und Verschneidung je Geschoss im Dokument
This commit is contained in:
7 files changed
+612
-88
No files matched your search
@@ -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) -> 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)
|
||||
}
|
||||
|
||||
/// 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,399 @@
|
||||
//! 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"];
|
||||
|
||||
#[derive(Debug)]
|
||||
struct WallEntry {
|
||||
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 {
|
||||
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.
|
||||
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) -> 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 { 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 opening_json = String::new();
|
||||
let mut opening_structs: Vec<RMesh> = Vec::new();
|
||||
if arcs {
|
||||
self.openings[slot].1.clear();
|
||||
let m = model3d::emit_opening_meshes(p, detail);
|
||||
opening_json = inner_json(&m);
|
||||
if structs {
|
||||
opening_structs = m;
|
||||
}
|
||||
} 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 { openings: os, meshes, json }
|
||||
}
|
||||
};
|
||||
open_fresh.insert(stamp, e);
|
||||
}
|
||||
let surface = model3d::surface_window_meshes(p);
|
||||
let order = || wall_stamps.iter().map(|s| &open_fresh[s]);
|
||||
let surface_json = inner_json(&surface);
|
||||
let lists: Vec<String> = (0..5)
|
||||
.map(|k| {
|
||||
let mut s = String::new();
|
||||
join_json(&mut s, order().map(|e| e.json[k].as_str()));
|
||||
s
|
||||
})
|
||||
.collect();
|
||||
join_json(&mut opening_json, lists.iter().map(String::as_str).chain([surface_json.as_str()]));
|
||||
if structs {
|
||||
opening_structs = model3d::assemble_opening_meshes(order().map(|e| e.meshes.clone()).collect());
|
||||
opening_structs.extend(surface);
|
||||
}
|
||||
self.openings[slot].1 = open_fresh;
|
||||
}
|
||||
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: opening_structs,
|
||||
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)?,
|
||||
};
|
||||
let mut json = String::with_capacity(fresh.values().map(|e| e.json.len() + 1).sum::<usize>() + opening_json.len() + 4096);
|
||||
json.push_str("{\"walls\":[");
|
||||
join_json(&mut json, wall_stamps.iter().map(|s| fresh[s].json.as_str()));
|
||||
json.push_str("],\"slabs\":");
|
||||
json.push_str(&js(&parts.slabs)?);
|
||||
json.push_str(",\"contextMeshes\":");
|
||||
json.push_str(&js(&parts.context_meshes)?);
|
||||
json.push_str(",\"columnMeshes\":");
|
||||
json.push_str(&js(&parts.column_meshes)?);
|
||||
json.push_str(",\"openingMeshes\":[");
|
||||
json.push_str(&opening_json);
|
||||
json.push_str("],\"stairMeshes\":");
|
||||
json.push_str(&js(&parts.stair_meshes)?);
|
||||
json.push_str(",\"stairRailings\":");
|
||||
json.push_str(&js(&parts.stair_railings)?);
|
||||
json.push_str(",\"roofMeshes\":");
|
||||
json.push_str(&js(&parts.roof_meshes)?);
|
||||
json.push_str(",\"roofLayers\":");
|
||||
json.push_str(&js(&parts.roof_layers)?);
|
||||
json.push('}');
|
||||
if structs {
|
||||
parts.walls = wall_stamps.iter().flat_map(|s| fresh[s].pieces.iter().cloned()).collect();
|
||||
}
|
||||
self.walls[layered as usize] = fresh;
|
||||
Ok(CachedParts { parts, json })
|
||||
}
|
||||
}
|
||||
|
||||
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, step: &str) {
|
||||
let p = d.project().unwrap().clone();
|
||||
for a in ARGS {
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
check(&mut d, "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, &format!("Schritt {step} (undo)"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
9 => {
|
||||
if d.redo().is_some() {
|
||||
kinds[kind] += 1;
|
||||
check(&mut d, &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, &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).unwrap();
|
||||
assert_eq!(d.model3d_rebuilt(), (n, n));
|
||||
d.model3d_parts(true, 2.0, false, false).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).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).unwrap();
|
||||
assert_eq!(d.model3d_rebuilt(), (1, 1));
|
||||
d.undo();
|
||||
d.model3d_parts(true, 2.0, false, false).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,35 @@ 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);
|
||||
if name == "model3dParts" && 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)?;
|
||||
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 +98,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,
|
||||
|
||||
Reference in new issue
Block a user