Merge [K3d][K4] Plan-Puffer v2: planDomains binaer statt JSON, GPU kompiliert direkt aus dem Puffer, Chunk-Cache mit Inhalts-Hash (grosser Grundriss 386 -> 171 ms)
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
20 files changed
+2964
-743
No files matched your search
@@ -142,9 +142,37 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
aber die Antwort ist ~14 MB JSON (Wände 9,3 MB, Treppen 3,7 MB): Abfrage inkl. Serialisierung ~160–210 ms, `JSON.parse` ~145–225 ms.
|
||||
Die JSON-Form ist damit der Engpass → Plan-Puffer v2.
|
||||
Offen: `drawing2d.ts` (Verteiler), Schatten/Baurecht (dünner Stil-Glue um `analysis/`, Datum/Sonnenstand in TS), Abzugskörper
|
||||
(`voids.ts`), Mono, Strichstärken-Massstab und `generateVisibleLevelsPlan` bleiben TS; die Override-Engine in TS bedient nur noch 2D-Zeichnungen. Plan-Puffer v2 (Primitive binär mit Pick-IDs und vollem
|
||||
Umfang statt JSON, gemeinsame Tabellen für Schraffuren/Farben, damit nicht jedes Polygon seine `HatchRender` wiederholt) ist nicht
|
||||
begonnen; erst sinnvoll, wenn die Verbraucher (SVG/PDF/DXF, Auswahl, Overlay) den Puffer lesen statt `Primitive[]`.
|
||||
(`voids.ts`), Mono, Strichstärken-Massstab und `generateVisibleLevelsPlan` bleiben TS; die Override-Engine in TS bedient nur noch 2D-Zeichnungen. Plan-Puffer v2
|
||||
s. nächster Punkt (28.10. erledigt).
|
||||
✅ (28.10.) **Plan-Puffer v2**: `planDomains` antwortet binär statt mit ~15 MB JSON (`doc_query_bin` → `queries.rs::run_bin` →
|
||||
`plan/domains.rs::plan_domains_buf`). Format im Kopf von `plan_buf.rs` (Gegenstück `src/plan/planBuf.ts`): Bytes mit f64-Teil
|
||||
+ UTF-16-Texten; Kopf mit Magie "PLB2"/Version 2, Ausmass und Flags; gemeinsame Tabellen für Strings (Farben, Klassen, Ids,
|
||||
Text-JSON) und Schraffuren (je Eintrag einmal als JSON für TS + numerischer Hatch-Datensatz für die GPU); Gruppen (die neun
|
||||
Domänen); Offset-Tabelle (wahlfreier Zugriff); Inhalts-Hash je Primitiv; Einträge `[tag, flags, Pick-Art, Pick-Id, …]` mit
|
||||
Punkt-/Listen-Pool; voller `Primitive`-Umfang (Polygon mit Löchern/noStrokeEdges, Linie mit Strichmuster null/Liste, Zickzack,
|
||||
Motiv, Bogen, Kreis/Bogen der 2D-Zeichnung; Raumstempel, Texte, Textpfad, Bild als JSON „wie heute“). v1 und die TS-`parseColor`
|
||||
sind gelöscht (Farben parst jetzt `plan_buf::parse_color`, bitgleich); `prim.rs` kennt auch `drawingTextPath/Image/Circle/Arc`.
|
||||
TS liest den Puffer zu `Primitive[]` (gleiche Felder und Reihenfolge wie das alte JSON, Schraffur-Objekte geteilt);
|
||||
die GPU-Kompilierung liest Bereiche direkt aus dem Kern-Puffer (`compilePlanBufRange`: Puffer einmal im Kern gehalten,
|
||||
`plan_buf_hold`/`gpu_compile_held`, höchstens 8 Puffer/96 MB), gemischte Listen kodiert TS schlank (`lean`).
|
||||
GPU-Chunk-Cache: `Plan.bufRuns` merkt sich die Kern-Abschnitte (auch über Abzugskörper, Geschoss-Überlagerung, kompakte
|
||||
Unterlage hinweg; Mono/Strichstärken-Massstab lassen sie weg); dort zählt der Inhalts-Hash statt der Objekt-Identität, Chunk-
|
||||
Grenzen auch an Bauteil-Ids. Neu erzeugter Plan mit gleichem Inhalt → 0 Chunks neu (vorher alle), eine Wand verschoben → 1 von 69.
|
||||
Gleichheit (temporärer Paritätstest gegen den alten Kern, danach entfernt): planDomains-JSON nach Dekodierung Zeichen für Zeichen
|
||||
gleich (ohne Sortieren) über Beispiel + 120 Zufallsprojekte (Zickzack/Motiv-Fugen, Random-Schraffur, Override-Regeln,
|
||||
Zusatzwände/-öffnungen/-stützen/-treppen, kaputte Schraffuren/Deckentypen → gleiche Fehlermeldungen) × 2 Geschosse × 3 Detailgrade
|
||||
mit zufälliger Sichtbarkeit/Graustufe/Referenzlinien/global (726 Abfragen) und das grosse Projekt; GPU-Vertex-/Index-/Batch-Puffer
|
||||
byte-gleich zur v1-Kompilierung (2988 Puffer: Kern-Puffer direkt, ganzer Plan schlank kodiert, gepackt/ungepackt, LOD);
|
||||
CLI-SVG Beispiel-EG/OG und grosses Projekt byte-gleich; `npm run e2e` grün.
|
||||
Messung (Node, Linux-Container unter Last, Min/Median): `generatePlan` Beispiel-EG 0,63/0,76 → 0,32/0,51 ms; grosses Projekt
|
||||
(Beispielhaus 20×20, `plan/bigSampleProject.testing.ts`: 3600 Wände, 56 824 Primitive) 386/442 → 171/210 ms. Davon Abfrage
|
||||
122–130 ms (Rechnung ~130 ms nativ, Puffer schreiben 21 ms statt JSON 38 ms), Lesen in TS 39 ms (vorher `JSON.parse` 148 ms);
|
||||
Puffer 9,2 MB statt 15,5 MB JSON. GPU-Kompilierung des ganzen grossen Plans unverändert ~0,5 s (Rechnung, nicht Übergabe).
|
||||
Noch über `Primitive[]` (dekodiert): SVG/PDF/DXF-Export, Auswahl/Picken (`ownerIndex`, `segmentIndex`), Overlay/Texte
|
||||
(`nativeText`, PlanView), Culling, Fang, `toRenderScene` → render2d (`scene_bin.rs`, Browser-Ansicht und `push_native_scene`,
|
||||
unverändert). Offen: diese Verbraucher auf den Puffer umstellen (Picken über Pick-Art/Id je Eintrag; render2d-Szene direkt aus
|
||||
dem Puffer), TS-Anteile (2D-Zeichnungen, Schatten/Baurecht) in den Puffer schreiben. Nicht in der Tauri-App angesehen (der
|
||||
direkte GPU-Weg läuft nur im nativen macOS-Renderer; geprüft über die hochgeladenen Puffer in Vitest).
|
||||
Nachteile (bewusst): Übergang mit doppelter Datenhaltung, Format muss TS/Rust gleich bleiben
|
||||
(Versionsnummer + Hin-und-zurück-Tests), Text-Layout bleibt bis [K4] in TS.
|
||||
- ◐ **[K4] Modell und Ops in Rust** [2]; TS bekommt die Typen generiert (z. B. `ts-rs`). · XL
|
||||
@@ -176,6 +204,8 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
kommen über `planDomains` aus dem Dokument ([K3d]); übrig in `generatePlan`: 2D-Zeichnungen, Schatten/Baurecht, Abzugskörper.
|
||||
Ziel: Plan/Schnitt/Ansicht, 3D, Export rechnen mit `doc`-Handle statt flach gesammelter Arrays; TS-Sammler/-Adapter werden gelöscht
|
||||
([K3d] hängt hier dran: Plan-Puffer v2 mit Pick-IDs und vollem Primitive-Umfang).
|
||||
Stand 28.10.: Plan-Puffer v2 steht ([K3d]) — `planDomains` liefert binär, GPU liest ihn direkt; Export/Auswahl/Overlay lesen
|
||||
noch die dekodierten `Primitive[]`.
|
||||
- ◐ **S3 Änderungen kommen aus Rust**: Befehle (Zustandsautomaten, Werkzeuge) erzeugen Ops im Kern; Undo/Redo, Validierung
|
||||
(`validateOps`) und Gruppen/Ebenen-Logik wandern nach Rust; `diffToOps` entfällt, TS hält nur noch eine Leseansicht.
|
||||
**Erste Etappe (28.10.): Ops, Prüfung, Undo/Redo im Kern.** `core/src/ops.rs` (Op, Prüfung bitgleich zur TS-Fassung — gleiche
|
||||
|
||||
@@ -779,9 +779,10 @@ fn draw_circle_like(
|
||||
c.stroke_polyline(&pts, fill.is_some(), stroke_col, stroke_mm, false);
|
||||
}
|
||||
|
||||
/// Flache Ausgabe (s. Modulkopf); leer bei unlesbarem Plan-Puffer.
|
||||
pub fn compile_flat(buf: &[f64], px_per_meter: f64, packed: bool) -> Vec<u32> {
|
||||
let Some(plan) = plan_buf::decode(buf) else { return Vec::new() };
|
||||
/// Flache Ausgabe (s. Modulkopf) für die Primitive `[from, to)` eines Plan-Puffers (v2); leer bei
|
||||
/// unlesbarem Puffer oder ungültigem Bereich.
|
||||
pub fn compile_flat(bytes: &[u8], from: usize, to: usize, px_per_meter: f64, packed: bool) -> Vec<u32> {
|
||||
let Some(plan) = plan_buf::View::parse(bytes).and_then(|v| v.gpu(from, to)) else { return Vec::new() };
|
||||
let o = compile(&plan, px_per_meter, packed);
|
||||
let mut meta: Vec<f64> = vec![
|
||||
o.origin.0,
|
||||
@@ -843,7 +844,6 @@ mod tests {
|
||||
weight_mm: 0.18,
|
||||
a: v2(ax, 0.0),
|
||||
b: v2(bx, 0.0),
|
||||
dash: vec![],
|
||||
chain,
|
||||
zigzag: None,
|
||||
motif: None,
|
||||
@@ -926,8 +926,8 @@ mod tests {
|
||||
#[test]
|
||||
fn kreis_und_bogen() {
|
||||
let p = plan(vec![
|
||||
Prim::Circle { style: st(), fill: 1, stroke: 0, weight_mm: 0.0, center: v2(1.0, 1.0), r: 1.0, dash: vec![] },
|
||||
Prim::DrawingArc { style: st(), stroke: 0, weight_mm: 0.5, center: v2(0.0, 0.0), r: 1.0, a0: 0.0, a1: 0.0, dash: vec![] },
|
||||
Prim::Circle { style: st(), fill: 1, stroke: 0, weight_mm: 0.0, center: v2(1.0, 1.0), r: 1.0 },
|
||||
Prim::DrawingArc { style: st(), stroke: 0, weight_mm: 0.5, center: v2(0.0, 0.0), r: 1.0, a0: 0.0, a1: 0.0 },
|
||||
Prim::Placeholder,
|
||||
]);
|
||||
let o = compile(&p, 0.0, false);
|
||||
@@ -938,9 +938,26 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn kaputter_puffer_leer() {
|
||||
assert!(compile_flat(&[1.0, 2.0, 3.0], 90.0, true).is_empty());
|
||||
let enc = plan_buf::encode(&plan(vec![line(0.0, f64::NAN, false)]));
|
||||
let out = compile_flat(&enc, 90.0, true);
|
||||
assert!(!out.is_empty());
|
||||
assert!(compile_flat(&[1, 2, 3], 0, 0, 90.0, true).is_empty());
|
||||
let mut w = plan_buf::Writer::new(false);
|
||||
w.push(&crate::plan::prim::Primitive::Line {
|
||||
a: crate::model::Vec2 { x: 0.0, y: 0.0 },
|
||||
b: crate::model::Vec2 { x: f64::NAN, y: 0.0 },
|
||||
cls: "c".into(),
|
||||
weight_mm: 0.18,
|
||||
dash: None,
|
||||
zigzag: None,
|
||||
motif: None,
|
||||
color: None,
|
||||
drawing_id: None,
|
||||
opening_id: None,
|
||||
stair_id: None,
|
||||
greyed: None,
|
||||
opacity: None,
|
||||
});
|
||||
let enc = w.finish();
|
||||
assert!(!compile_flat(&enc, 0, 1, 90.0, true).is_empty());
|
||||
assert!(compile_flat(&enc, 0, 2, 90.0, true).is_empty(), "Bereich ausserhalb");
|
||||
assert!(!compile_flat(&enc, 1, 1, 90.0, true).is_empty(), "leerer Bereich = leere Geometrie");
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,6 @@ use crate::js_fmt::{js_number, to_fixed};
|
||||
use crate::jsnum::{max, min, round};
|
||||
use crate::model::*;
|
||||
use crate::plan_walls::{ceiling_outline_lines, wall_footprint, WallFootprint};
|
||||
use serde::Serialize;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Footprint-Farbe der Extrusionen (wie das 3D-Orange).
|
||||
@@ -96,9 +95,10 @@ impl<'a> Ctx<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Ergebnis der Abfrage `planDomains`: Primitive je Domäne (TS setzt sie an ihre Stelle in der
|
||||
/// Zeichenreihenfolge) und das Ausmass der Decken, Räume und Dach-Traufen.
|
||||
#[derive(Serialize, Default)]
|
||||
/// Ergebnis der Plan-Erzeugung: Primitive je Domäne (TS setzt sie an ihre Stelle in der
|
||||
/// Zeichenreihenfolge) und das Ausmass der Decken, Räume und Dach-Traufen. Über die Grenze geht es
|
||||
/// als Plan-Puffer v2 ([`plan_domains_buf`]).
|
||||
#[derive(Default)]
|
||||
pub struct DomainPrims {
|
||||
pub ceilings: Vec<Primitive>,
|
||||
/// Wände (Poché, Referenzlinie) mit ihren Öffnungs-Symbolen, je Wand nacheinander.
|
||||
@@ -517,6 +517,21 @@ pub fn plan_domains(p: &Project, a: &PlanArgs) -> Result<DomainPrims, String> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Reihenfolge der Gruppen im Plan-Puffer der Abfrage `planDomains`.
|
||||
pub const GROUPS: [&str; 9] = ["ceilings", "roofs", "rooms", "walls", "stairs", "columns", "solids", "context", "sections"];
|
||||
|
||||
/// Abfrage `planDomains` als Plan-Puffer v2 (s. `plan_buf.rs`): eine Gruppe je Domäne in der
|
||||
/// Reihenfolge [`GROUPS`], Ausmass im Kopf, Inhalts-Hashes für den GPU-Chunk-Cache.
|
||||
pub fn plan_domains_buf(p: &Project, a: &PlanArgs) -> Result<Vec<u8>, String> {
|
||||
let d = plan_domains(p, a)?;
|
||||
let mut w = crate::plan_buf::Writer::new(true);
|
||||
for g in [&d.ceilings, &d.roofs, &d.rooms, &d.walls, &d.stairs, &d.columns, &d.solids, &d.context, &d.sections] {
|
||||
w.group(g);
|
||||
}
|
||||
w.bounds = d.bounds;
|
||||
Ok(w.finish())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -545,6 +560,22 @@ mod tests {
|
||||
assert!(r.bounds.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn puffer_gruppen_wie_domaenen() {
|
||||
let p = sample();
|
||||
let a = args("eg", 1.0, &["20", "21", "30", "40", "60"]);
|
||||
let d = plan_domains(&p, &a).unwrap();
|
||||
let buf = plan_domains_buf(&p, &a).unwrap();
|
||||
let (prims, groups, bounds) = crate::plan_buf::decode(&buf).unwrap();
|
||||
assert_eq!(groups.len(), GROUPS.len());
|
||||
let lists = [&d.ceilings, &d.roofs, &d.rooms, &d.walls, &d.stairs, &d.columns, &d.solids, &d.context, &d.sections];
|
||||
for ((a, b), l) in groups.iter().zip(lists) {
|
||||
assert_eq!(serde_json::to_string(&prims[*a..*b]).unwrap(), serde_json::to_string(l).unwrap());
|
||||
}
|
||||
assert!(!d.walls.is_empty() && !d.rooms.is_empty());
|
||||
assert_eq!(bounds, d.bounds);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsichtbare_codes_fehlen() {
|
||||
let p = sample();
|
||||
@@ -605,4 +636,38 @@ mod tests {
|
||||
let col = Column { profile: ColumnProfile::Round { radius: 0.125 }, ..Default::default() };
|
||||
assert_eq!(column_label(&col), "Stütze Ø25");
|
||||
}
|
||||
|
||||
/// Messung (von Hand): `PLAN_BIG=projekt.obp cargo test --release --lib messung_plan_puffer -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn messung_plan_puffer() {
|
||||
let Ok(path) = std::env::var("PLAN_BIG") else { return };
|
||||
let mut doc = crate::document::Document::from_json(&std::fs::read_to_string(path).unwrap()).unwrap();
|
||||
let p = doc.project().unwrap().clone();
|
||||
let codes: Vec<String> = p.flat_categories().iter().map(|c| c.code.clone()).collect();
|
||||
let t = serde_json::json!({ "floor": "eg", "show": codes, "grey": [], "global": true }).to_string();
|
||||
let a = PlanArgs::parse(1.0, &t).unwrap();
|
||||
let time = |name: &str, f: &mut dyn FnMut()| {
|
||||
f();
|
||||
let t0 = std::time::Instant::now();
|
||||
for _ in 0..5 {
|
||||
f();
|
||||
}
|
||||
println!("{name}: {:.1} ms", t0.elapsed().as_secs_f64() * 1000.0 / 5.0);
|
||||
};
|
||||
time("plan_domains", &mut || {
|
||||
plan_domains(&p, &a).unwrap();
|
||||
});
|
||||
let d = plan_domains(&p, &a).unwrap();
|
||||
time("Puffer schreiben", &mut || {
|
||||
let mut w = crate::plan_buf::Writer::new(true);
|
||||
for g in [&d.ceilings, &d.roofs, &d.rooms, &d.walls, &d.stairs, &d.columns, &d.solids, &d.context, &d.sections] {
|
||||
w.group(g);
|
||||
}
|
||||
w.finish();
|
||||
});
|
||||
time("JSON (früher)", &mut || {
|
||||
serde_json::to_string(&(&d.ceilings, &d.roofs, &d.rooms, &d.walls, &d.stairs, &d.columns, &d.solids, &d.context, &d.sections)).unwrap();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,10 @@
|
||||
//! Zeichen für Zeichen die der TS-Objekte (camelCase, fehlende Felder fehlen).
|
||||
|
||||
use crate::model::*;
|
||||
use serde::Serialize;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
|
||||
/// Aufgelöste Schraffur eines Polygons (`HatchRender`).
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HatchRender {
|
||||
pub pattern: HatchPattern,
|
||||
@@ -38,7 +38,7 @@ pub struct HatchRender {
|
||||
}
|
||||
|
||||
/// Zeile unter dem Raum-Stempel.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct StampLine {
|
||||
pub text: String,
|
||||
pub align: Align,
|
||||
@@ -47,7 +47,12 @@ pub struct StampLine {
|
||||
/// `dash?: number[] | null`: fehlt (`None`), `null` (`Some(None)`) oder Muster.
|
||||
pub type Dash = Option<Option<Vec<f64>>>;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
/// Liest `dash` so, dass `null` (`Some(None)`) und fehlend (`None`, über `default`) verschieden bleiben.
|
||||
fn de_dash<'de, D: Deserializer<'de>>(d: D) -> Result<Dash, D::Error> {
|
||||
Option::<Vec<f64>>::deserialize(d).map(Some)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind")]
|
||||
pub enum Primitive {
|
||||
#[serde(rename = "polygon", rename_all = "camelCase")]
|
||||
@@ -92,7 +97,7 @@ pub enum Primitive {
|
||||
b: Vec2,
|
||||
cls: String,
|
||||
weight_mm: f64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_dash")]
|
||||
dash: Dash,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
zigzag: Option<LineStyleZigzag>,
|
||||
@@ -119,7 +124,7 @@ pub enum Primitive {
|
||||
r: f64,
|
||||
cls: String,
|
||||
weight_mm: f64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_dash")]
|
||||
dash: Dash,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
opening_id: Option<String>,
|
||||
@@ -164,13 +169,82 @@ pub enum Primitive {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
opacity: Option<f64>,
|
||||
},
|
||||
/// Text entlang eines Pfads (2D-Zeichnung); erzeugt heute nur TS, s. Plan-Puffer v2.
|
||||
#[serde(rename = "drawingTextPath", rename_all = "camelCase")]
|
||||
DrawingTextPath {
|
||||
path_pts: Vec<Vec2>,
|
||||
text: String,
|
||||
height_m: f64,
|
||||
color: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
drawing_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
greyed: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
opacity: Option<f64>,
|
||||
},
|
||||
/// Eingebettetes Rasterbild (2D-Zeichnung).
|
||||
#[serde(rename = "drawingImage", rename_all = "camelCase")]
|
||||
DrawingImage {
|
||||
min: Vec2,
|
||||
max: Vec2,
|
||||
src: String,
|
||||
opacity: f64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
drawing_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
greyed: Option<bool>,
|
||||
},
|
||||
/// Glatter Kreis (2D-Zeichnung).
|
||||
#[serde(rename = "drawingCircle", rename_all = "camelCase")]
|
||||
DrawingCircle {
|
||||
center: Vec2,
|
||||
r: f64,
|
||||
fill: String,
|
||||
stroke: String,
|
||||
weight_mm: f64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_dash")]
|
||||
dash: Dash,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
drawing_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
greyed: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
opacity: Option<f64>,
|
||||
},
|
||||
/// Glatter Bogen (2D-Zeichnung), Winkel im Bogenmass (CCW).
|
||||
#[serde(rename = "drawingArc", rename_all = "camelCase")]
|
||||
DrawingArc {
|
||||
center: Vec2,
|
||||
r: f64,
|
||||
a0: f64,
|
||||
a1: f64,
|
||||
stroke: String,
|
||||
weight_mm: f64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_dash")]
|
||||
dash: Dash,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
drawing_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
greyed: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
opacity: Option<f64>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Primitive {
|
||||
/// Setzt `greyed` (für Gruppen, deren Darstellungsmodus gedimmt ist).
|
||||
pub fn with_greyed(mut self, g: bool) -> Self {
|
||||
match &mut self {
|
||||
Primitive::Polygon { greyed, .. } | Primitive::Line { greyed, .. } | Primitive::Arc { greyed, .. } | Primitive::Text { greyed, .. } | Primitive::DrawingText { greyed, .. } => *greyed = Some(g),
|
||||
Primitive::Polygon { greyed, .. }
|
||||
| Primitive::Line { greyed, .. }
|
||||
| Primitive::Arc { greyed, .. }
|
||||
| Primitive::Text { greyed, .. }
|
||||
| Primitive::DrawingText { greyed, .. }
|
||||
| Primitive::DrawingTextPath { greyed, .. }
|
||||
| Primitive::DrawingImage { greyed, .. }
|
||||
| Primitive::DrawingCircle { greyed, .. }
|
||||
| Primitive::DrawingArc { greyed, .. } => *greyed = Some(g),
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
+1590
-411
File diff suppressed because it is too large.
Load diff
@@ -39,8 +39,15 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
|
||||
("scheduleRows", _) => json(&export_schedule::schedule_rows(p)),
|
||||
("scheduleCsv", 1) => Ok(export_schedule::export_schedule_csv(p, text, args[0] != 0.0)),
|
||||
("pickGeometry", _) => json(&model3d::pick_geometry(p)?),
|
||||
("planDomains", 1) => json(&crate::plan::domains::plan_domains(p, &crate::plan::domains::PlanArgs::parse(args[0], text)?)?),
|
||||
("model3dParts", 3) => json(&model3d::parts(p, args[0] != 0.0, args[1], args[2] != 0.0)?),
|
||||
_ => Err(format!("Unbekannte Abfrage: {name}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Abfragen mit binärer Antwort (Plan-Puffer v2, s. `plan_buf.rs`).
|
||||
pub fn run_bin(p: &Project, name: &str, args: &[f64], text: &str) -> Result<Vec<u8>, String> {
|
||||
match (name, args.len()) {
|
||||
("planDomains", 1) => crate::plan::domains::plan_domains_buf(p, &crate::plan::domains::PlanArgs::parse(args[0], text)?),
|
||||
_ => Err(format!("Unbekannte Abfrage: {name}")),
|
||||
}
|
||||
}
|
||||
@@ -177,3 +177,15 @@ pub fn doc_drawing_line_verts(h: u32) -> Vec<f32> {
|
||||
pub fn doc_serialize(h: u32) -> String {
|
||||
with_doc(h, |d| d.serialize()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Abfrage mit binärer Antwort (`crate::queries::run_bin`, z. B. `planDomains` als Plan-Puffer v2).
|
||||
/// Fehler kommen als Fehlerpuffer (`plan_buf::encode_error`).
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_query_bin(h: u32, name: &str, args: &[f64], text: &str) -> Vec<u8> {
|
||||
let result = with_doc(h, |d| {
|
||||
let p = d.project().map_err(|e| format!("Projekt passt nicht zum Kern-Modell: {e}"))?;
|
||||
crate::queries::run_bin(&p, name, args, text)
|
||||
})
|
||||
.unwrap_or_else(|| Err("Dokument nicht offen".to_string()));
|
||||
result.unwrap_or_else(|e| crate::plan_buf::encode_error(&e))
|
||||
}
|
||||
@@ -2,11 +2,18 @@
|
||||
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
/// Plan-Puffer (ein Chunk) → Vertex-/Index-/Batch-Daten als ein `u32`-Puffer; leer bei
|
||||
/// unlesbarem Puffer.
|
||||
/// Primitive `[from, to)` eines Plan-Puffers (v2) → Vertex-/Index-/Batch-Daten als ein
|
||||
/// `u32`-Puffer; leer bei unlesbarem Puffer oder ungültigem Bereich.
|
||||
#[wasm_bindgen]
|
||||
pub fn gpu_compile_flat(buf: &[f64], px_per_meter: f64, packed_lines: bool) -> Vec<u32> {
|
||||
crate::gpu_compile::compile_flat(buf, px_per_meter, packed_lines)
|
||||
pub fn gpu_compile_flat(buf: &[u8], from: u32, to: u32, px_per_meter: f64, packed_lines: bool) -> Vec<u32> {
|
||||
crate::gpu_compile::compile_flat(buf, from as usize, to as usize, px_per_meter, packed_lines)
|
||||
}
|
||||
|
||||
/// Wie [`gpu_compile_flat`] auf einem gehaltenen Puffer (`plan_buf_hold`); leer, wenn er nicht
|
||||
/// mehr gehalten wird.
|
||||
#[wasm_bindgen]
|
||||
pub fn gpu_compile_held(id: u32, from: u32, to: u32, px_per_meter: f64, packed_lines: bool) -> Vec<u32> {
|
||||
super::plan_buf::with_held(id, |b| crate::gpu_compile::compile_flat(b, from as usize, to as usize, px_per_meter, packed_lines)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Ear-Clipping eines Rings `[x, y, …]` → Dreiecks-Indizes.
|
||||
|
||||
@@ -1,10 +1,53 @@
|
||||
//! Bindungen des Plan-Puffers (`crate::plan_buf`). Format s. dort.
|
||||
//!
|
||||
//! Gehaltene Puffer: TS übergibt einen Plan-Puffer einmal (`plan_buf_hold`) und kompiliert danach
|
||||
//! beliebig viele GPU-Chunks daraus (`gpu_compile_held`), ohne ihn je Chunk erneut zu kopieren.
|
||||
//! Höchstens `MAX_HELD` Puffer bzw. `MAX_HELD_BYTES` bleiben liegen (ältester fällt weg);
|
||||
//! ein verdrängter Puffer liefert leere Ergebnisse, TS übergibt ihn dann neu.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
const MAX_HELD: usize = 8;
|
||||
const MAX_HELD_BYTES: usize = 96 << 20;
|
||||
|
||||
thread_local! {
|
||||
static HELD: RefCell<(u32, Vec<(u32, Vec<u8>)>)> = const { RefCell::new((0, Vec::new())) };
|
||||
}
|
||||
|
||||
/// Plan-Puffer lesen und neu schreiben (Hin-und-zurück-Prüfung der TS-Kodierung); leer bei
|
||||
/// fremder Version oder kaputtem Puffer.
|
||||
#[wasm_bindgen]
|
||||
pub fn plan_buf_recode(buf: &[f64]) -> Vec<f64> {
|
||||
pub fn plan_buf_recode(buf: &[u8]) -> Vec<u8> {
|
||||
crate::plan_buf::recode(buf)
|
||||
}
|
||||
|
||||
/// Puffer im Kern halten; Ergebnis ist die Nummer (≥ 1), 0 bei unlesbarem Puffer.
|
||||
#[wasm_bindgen]
|
||||
pub fn plan_buf_hold(buf: &[u8]) -> u32 {
|
||||
if crate::plan_buf::View::parse(buf).is_none() {
|
||||
return 0;
|
||||
}
|
||||
HELD.with(|h| {
|
||||
let mut h = h.borrow_mut();
|
||||
h.0 = h.0.wrapping_add(1).max(1);
|
||||
let id = h.0;
|
||||
h.1.push((id, buf.to_vec()));
|
||||
let mut bytes: usize = h.1.iter().map(|e| e.1.len()).sum();
|
||||
while h.1.len() > MAX_HELD || (bytes > MAX_HELD_BYTES && h.1.len() > 1) {
|
||||
bytes -= h.1.remove(0).1.len();
|
||||
}
|
||||
id
|
||||
})
|
||||
}
|
||||
|
||||
/// Gehaltenen Puffer freigeben (unbekannte Nummer: nichts).
|
||||
#[wasm_bindgen]
|
||||
pub fn plan_buf_release(id: u32) {
|
||||
HELD.with(|h| h.borrow_mut().1.retain(|e| e.0 != id));
|
||||
}
|
||||
|
||||
/// Mit dem gehaltenen Puffer `id` rechnen; `None`, wenn er nicht (mehr) da ist.
|
||||
pub(crate) fn with_held<R>(id: u32, f: impl FnOnce(&[u8]) -> R) -> Option<R> {
|
||||
HELD.with(|h| h.borrow().1.iter().find(|e| e.0 == id).map(|e| f(&e.1)))
|
||||
}
|
||||
@@ -94,6 +94,15 @@ export class ProjectDocument {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Abfrage mit binärer Antwort (`queries.rs::run_bin`, z. B. `planDomains` als Plan-Puffer v2,
|
||||
* s. `plan/planBuf.ts`). Fehler kommen als Fehlerpuffer (`decodePlanBuf` wirft die Meldung).
|
||||
*/
|
||||
queryBin(name: QueryName, args: number[] = [], text = ""): Uint8Array {
|
||||
if (!this.handle) throw new Error(`Kern-Abfrage „${name}": Dokument nicht offen`);
|
||||
return core().doc_query_bin(this.handle, name, Float64Array.from(args), text);
|
||||
}
|
||||
|
||||
/** Datei-Text des Projekts (Formatversion vorn, Einrückung 2). */
|
||||
serialize(): string {
|
||||
return this.handle ? core().doc_serialize(this.handle) : "";
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
// Testhilfe ([K3d]): grosses Projekt für Messungen — das Beispielhaus n × n Mal gekachelt
|
||||
// (n = 20: 3600 Wände, 1200 Öffnungen, 400 Decken/Räume/Treppen/Dächer, 1600 Stützen).
|
||||
// Ids bekommen ein Kachel-Suffix, Verweise (Öffnung → Wand) werden mitgeführt.
|
||||
|
||||
import type { Column, Project, Vec2 } from "../model/types";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
|
||||
const shift = (p: Vec2, dx: number, dy: number): Vec2 => ({ x: p.x + dx, y: p.y + dy });
|
||||
|
||||
export function bigSampleProject(n = 20, pitch = 8): Project {
|
||||
const s = sampleProject;
|
||||
const out: Project = {
|
||||
...s,
|
||||
walls: [],
|
||||
openings: [],
|
||||
ceilings: [],
|
||||
roofs: [],
|
||||
stairs: [],
|
||||
rooms: [],
|
||||
columns: [],
|
||||
};
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = 0; j < n; j++) {
|
||||
const dx = i * pitch;
|
||||
const dy = j * pitch;
|
||||
const sfx = `_${i}_${j}`;
|
||||
for (const w of s.walls) out.walls.push({ ...w, id: w.id + sfx, start: shift(w.start, dx, dy), end: shift(w.end, dx, dy) });
|
||||
for (const o of s.openings ?? []) out.openings!.push({ ...o, id: o.id + sfx, hostWallId: o.hostWallId + sfx });
|
||||
for (const c of s.ceilings ?? []) out.ceilings!.push({ ...c, id: c.id + sfx, outline: c.outline.map((p) => shift(p, dx, dy)) });
|
||||
for (const r of s.roofs ?? []) out.roofs!.push({ ...r, id: r.id + sfx, outline: r.outline.map((p) => shift(p, dx, dy)) });
|
||||
for (const st of s.stairs ?? []) out.stairs!.push({ ...st, id: st.id + sfx, start: shift(st.start, dx, dy) });
|
||||
for (const r of s.rooms ?? []) {
|
||||
out.rooms!.push({
|
||||
...r,
|
||||
id: r.id + sfx,
|
||||
boundary: r.boundary.map((p) => shift(p, dx, dy)),
|
||||
...(r.stampAnchor ? { stampAnchor: shift(r.stampAnchor, dx, dy) } : {}),
|
||||
});
|
||||
}
|
||||
for (let k = 0; k < 4; k++) {
|
||||
const col: Column = {
|
||||
id: `COL${k}${sfx}`,
|
||||
type: "column",
|
||||
floorId: "eg",
|
||||
categoryCode: "50",
|
||||
position: { x: dx + 1 + k, y: dy + 2 },
|
||||
profile: k % 2 ? { kind: "round", radius: 0.12 } : { kind: "rect", width: 0.25, depth: 0.25 },
|
||||
rotation: k * 0.3,
|
||||
height: 2.6,
|
||||
};
|
||||
out.columns!.push(col);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// Kern-Abschnitte im Plan ([K3d], Plan-Puffer v2): `Plan.bufRuns` zeigt auf unveränderte Primitive
|
||||
// aus dem Puffer des Kerns — auch nach Abzugskörpern, beim Überlagern mehrerer Geschosse und mit
|
||||
// der kompakten Unterlage; Mono und Strichstärken-Massstab lassen sie weg.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { generatePlan, generateVisibleLevelsPlan, materializeUnderlay } from "./generatePlan";
|
||||
import type { Plan } from "./generatePlan";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { flattenCategories } from "../model/types";
|
||||
import type { ExtrudedSolid, Project } from "../model/types";
|
||||
|
||||
const codes = (p: Project) => new Set(flattenCategories(p.layers).map((c) => c.code));
|
||||
|
||||
/** Jede Stelle eines Abschnitts trägt genau das Objekt aus dem Puffer. */
|
||||
function checkRuns(plan: Plan): number {
|
||||
let n = 0;
|
||||
for (const r of plan.bufRuns ?? []) {
|
||||
expect(r.to).toBeGreaterThan(r.from);
|
||||
for (let k = 0; k < r.to - r.from; k++) expect(plan.primitives[r.at + k]).toBe(r.buf.prims[r.from + k]);
|
||||
n += r.to - r.from;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
describe("Plan.bufRuns", () => {
|
||||
it("Beispiel-EG: zwei Abschnitte, alle Kern-Primitive abgedeckt", () => {
|
||||
const plan = generatePlan(sampleProject, "eg", codes(sampleProject));
|
||||
expect(plan.bufRuns?.length).toBe(2);
|
||||
const covered = checkRuns(plan);
|
||||
expect(covered).toBe(plan.bufRuns![0].buf.prims.length);
|
||||
});
|
||||
|
||||
it("Abzugskörper zerlegen Polygone: Abschnitte werden neu ausgerichtet", () => {
|
||||
const solid: ExtrudedSolid = {
|
||||
id: "void1",
|
||||
type: "extrudedSolid",
|
||||
levelId: "eg",
|
||||
operation: "subtract",
|
||||
height: 3,
|
||||
points: [
|
||||
{ x: 1, y: -0.5 },
|
||||
{ x: 1.4, y: -0.5 },
|
||||
{ x: 1.4, y: 0.5 },
|
||||
{ x: 1, y: 0.5 },
|
||||
],
|
||||
} as ExtrudedSolid;
|
||||
const p: Project = { ...sampleProject, extrudedSolids: [solid] };
|
||||
const plan = generatePlan(p, "eg", codes(p));
|
||||
const total = plan.bufRuns![0].buf.prims.length;
|
||||
const covered = checkRuns(plan);
|
||||
expect(covered).toBeGreaterThan(total / 2);
|
||||
expect(covered).toBeLessThan(total);
|
||||
});
|
||||
|
||||
it("Überlagerung mehrerer Geschosse und kompakte Unterlage verschieben die Abschnitte mit", () => {
|
||||
const plan = generateVisibleLevelsPlan(sampleProject, "og", codes(sampleProject), undefined, "mittel", false, false, undefined, 100, true);
|
||||
expect((plan.bufRuns ?? []).length).toBeGreaterThanOrEqual(3);
|
||||
checkRuns(plan);
|
||||
checkRuns(materializeUnderlay(plan));
|
||||
});
|
||||
|
||||
it("Mono und Strichstärken-Massstab: keine Abschnitte", () => {
|
||||
expect(generatePlan(sampleProject, "eg", codes(sampleProject), undefined, "mittel", false, true).bufRuns).toBeUndefined();
|
||||
const scaled: Project = { ...sampleProject, scaleLineWeights: true };
|
||||
expect(generatePlan(scaled, "eg", codes(scaled), undefined, "mittel", false, false, true, 50).bufRuns).toBeUndefined();
|
||||
expect(generatePlan(scaled, "eg", codes(scaled), undefined, "mittel", false, false, true, 100).bufRuns?.length).toBe(2);
|
||||
});
|
||||
});
|
||||
+94
-35
@@ -36,6 +36,7 @@ import {
|
||||
getWallType,
|
||||
} from "../model/types";
|
||||
import { documentFor } from "../core/document";
|
||||
import { decodePlanBuf, type DecodedPlanBuf } from "./planBuf";
|
||||
import { effectiveOverrides, hasOverrides } from "../overrides/engine";
|
||||
import type { SectionOutput } from "./toSection";
|
||||
import {
|
||||
@@ -193,6 +194,26 @@ export interface Plan {
|
||||
* {@link materializeUnderlay}.
|
||||
*/
|
||||
underlay?: UnderlayGroup[];
|
||||
/**
|
||||
* Abschnitte, die unverändert aus einem Plan-Puffer des Kerns stammen ([K3d]): der GPU-Pfad
|
||||
* kompiliert sie direkt aus dem Puffer und erkennt Unverändertes am Inhalts-Hash
|
||||
* (`glPlanChunks.ts`). Wer Primitive ersetzt oder verschiebt, muss nichts nachführen — der
|
||||
* Verbraucher prüft die Objekt-Identität und fällt sonst auf die Objekte zurück.
|
||||
*/
|
||||
bufRuns?: PlanBufRun[];
|
||||
}
|
||||
|
||||
/** `primitives[at + k]` ist (solange nicht ersetzt) `buf.prims[from + k]`, `k < to − from`. */
|
||||
export interface PlanBufRun {
|
||||
at: number;
|
||||
buf: DecodedPlanBuf;
|
||||
from: number;
|
||||
to: number;
|
||||
}
|
||||
|
||||
/** Kern-Abschnitte um `shift` verschieben (beim Zusammensetzen mehrerer Pläne). */
|
||||
function shiftRuns(runs: readonly PlanBufRun[] | undefined, shift: number, into: PlanBufRun[]): void {
|
||||
for (const r of runs ?? []) into.push({ ...r, at: r.at + shift });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -244,11 +265,14 @@ export function materializeUnderlay(plan: Plan): Plan {
|
||||
...shifted,
|
||||
...aboveGreyed.map(([a, b]): [number, number] => [a + aboveShift, b + aboveShift]),
|
||||
];
|
||||
const bufRuns: PlanBufRun[] = [];
|
||||
shiftRuns(plan.bufRuns, below.length, bufRuns);
|
||||
return {
|
||||
...plan,
|
||||
primitives,
|
||||
underlay: undefined,
|
||||
greyedRanges: ranges.length ? ranges : undefined,
|
||||
bufRuns: bufRuns.length ? bufRuns : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -385,20 +409,23 @@ export function generatePlan(
|
||||
// Kern auf dem Dokument ([K3d], `plan/{domains,walls,stairs}.rs`): Filter, Override-Regeln,
|
||||
// Verschneidung, Stil und Raumstempel-Daten. Decken, Dächer und Räume liegen unter der Wand-Poché; Stützen folgen
|
||||
// nach den Treppen, Extrusionen nach den 2D-Zeichnungen.
|
||||
// Der Kern liefert alles in EINEM Plan-Puffer (Gruppen in dieser Reihenfolge); die Abschnitte
|
||||
// merkt sich der Plan (`bufRuns`), damit die GPU sie direkt aus dem Puffer kompiliert.
|
||||
const dom = planDomains(project, floorId, visibleCodes, categoryDisplay, detail, showReferenceLines, includeGlobal);
|
||||
for (const pr of dom.ceilings) primitives.push(pr);
|
||||
for (const pr of dom.roofs) primitives.push(pr);
|
||||
for (const pr of dom.rooms) primitives.push(pr);
|
||||
|
||||
// Wände (Poché, Referenzlinie) mit ihren Öffnungs-Symbolen, je Wand nacheinander.
|
||||
for (const pr of dom.walls) primitives.push(pr);
|
||||
|
||||
// Treppen: Tritte + Lauflinie + Auf-/Abpfeil mit dem Grundriss-Schnitt (unter der Schnitthöhe
|
||||
// durchgezogen, darüber gestrichelt + SIA-Bruchlinie), über der Wand-Poché.
|
||||
for (const pr of dom.stairs) primitives.push(pr);
|
||||
|
||||
// Stützen (Tragwerk): Querschnitt-Poché, über der Wand-Poché.
|
||||
for (const pr of dom.columns) primitives.push(pr);
|
||||
const runs: PlanBufRun[] = [];
|
||||
const pushGroups = (first: number, last: number): void => {
|
||||
if (!dom.buf) return;
|
||||
const from = dom.buf.groups[first][0];
|
||||
const to = dom.buf.groups[last][1];
|
||||
const at = primitives.length;
|
||||
const src = dom.buf.prims;
|
||||
for (let i = from; i < to; i++) primitives.push(src[i]);
|
||||
if (to > from) runs.push({ at, buf: dom.buf, from, to });
|
||||
};
|
||||
// Decken, Dächer, Räume; Wände (Poché, Referenzlinie) mit ihren Öffnungs-Symbolen, je Wand
|
||||
// nacheinander; Treppen (Tritte + Lauflinie + Auf-/Abpfeil mit dem Grundriss-Schnitt, über der
|
||||
// Wand-Poché); Stützen (Querschnitt-Poché).
|
||||
pushGroups(G_CEILINGS, G_COLUMNS);
|
||||
|
||||
// 2D-Zeichengeometrie zuletzt (über der Poché).
|
||||
const compact = compactUnderlay && !mono && !forPrint;
|
||||
@@ -439,22 +466,21 @@ export function generatePlan(
|
||||
for (const grp of underGroups.values()) underlay.push(mkGroup(grp.ds, grp.greyed));
|
||||
|
||||
// Extrudierte Körper: Footprint-Umriss (Quell-Profil wurde beim Extrudieren entfernt).
|
||||
for (const pr of dom.solids) primitives.push(pr);
|
||||
|
||||
// Kontext-Konturen (Höhenlinien) als dezente Linien zeichnen — UNTER der
|
||||
// Wand-Poché wäre ideal, aber da sie eine eigene gedämpfte Farbe tragen, ist
|
||||
// die Reihenfolge unkritisch; wir hängen sie als Referenz an. Projektglobal
|
||||
// (nicht je Geschoss) → nur beim aktiven Aufruf einer Mehrfach-Überlagerung.
|
||||
for (const pr of dom.context) primitives.push(pr);
|
||||
// Schnittführungs-Symbole aller Schnitt-/Ansichtsebenen mit Linie — ebenfalls projektglobal,
|
||||
// Sichtbarkeit über die Kategorie "90" (Referenzen).
|
||||
for (const pr of dom.sections) primitives.push(pr);
|
||||
pushGroups(G_SOLIDS, G_SECTIONS);
|
||||
|
||||
// Schwarz-Weiss (mono): nachträglich alle Farben auf reine Tinte zwingen.
|
||||
// Element-/Kategorie-/Hatch-Farben werden ignoriert, Füllungen werden weiss,
|
||||
// Musterlinien/Striche schwarz — so entsteht ein reiner S/W-Plan.
|
||||
// Abzugskörper (Aussparungen/Durchbrüche): von Wand-/Stützen-/Decken-Poché abziehen.
|
||||
subtractVoidsInPlan(primitives, project, (floor?.baseElevation ?? 0) + (floor?.cutHeight ?? 1.0));
|
||||
// Ersetzte Primitive erkennt der GPU-Pfad selbst (Identität); verschiebt das Zerlegen die
|
||||
// Indizes, werden die Kern-Abschnitte neu ausgerichtet.
|
||||
if (subtractVoidsInPlan(primitives, project, (floor?.baseElevation ?? 0) + (floor?.cutHeight ?? 1.0))) realignRuns(primitives, runs);
|
||||
|
||||
// Baurechts-Verstösse über allem (Signal, soll nicht unter der Wand-Poché verschwinden).
|
||||
if (includeGlobal) addSiteViolations(primitives, project, floorId);
|
||||
@@ -488,14 +514,40 @@ export function generatePlan(
|
||||
ctx: [...g.ctx, lwf],
|
||||
build: (ds: Drawing2D[]) => g.build(ds).map((p) => scalePrimitiveWeights(p, lwf)),
|
||||
}));
|
||||
// Mono färbt die Objekte um, der Massstab ersetzt sie: dann gilt der Puffer nicht mehr.
|
||||
const keepRuns = !mono && lwf === 1 && runs.length > 0;
|
||||
return {
|
||||
primitives: lwf === 1 ? primitives : primitives.map((p) => scalePrimitiveWeights(p, lwf)),
|
||||
bounds: computeBounds(project, drawings, dom.bounds, primitives.slice(0, underlayCount)),
|
||||
bounds: computeBounds(project, drawings, dom.buf?.bounds, primitives.slice(0, underlayCount)),
|
||||
backgroundImages,
|
||||
...(scaledUnderlay.length ? { underlay: scaledUnderlay } : {}),
|
||||
...(keepRuns ? { bufRuns: runs } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Kern-Abschnitte nach einem Umbau der Liste (Abzugskörper zerlegen Polygone) neu ausrichten:
|
||||
* jede noch vorhandene Folge unveränderter Puffer-Objekte wird ein eigener Abschnitt.
|
||||
*/
|
||||
function realignRuns(primitives: readonly Primitive[], runs: PlanBufRun[]): void {
|
||||
if (runs.length === 0) return;
|
||||
const where = new Map<Primitive, [PlanBufRun, number]>();
|
||||
for (const r of runs) for (let i = r.from; i < r.to; i++) where.set(r.buf.prims[i], [r, i]);
|
||||
const out: PlanBufRun[] = [];
|
||||
let cur: PlanBufRun | null = null;
|
||||
for (let i = 0; i < primitives.length; i++) {
|
||||
const w = where.get(primitives[i]);
|
||||
if (w && cur && w[0].buf === cur.buf && w[1] === cur.to && i === cur.at + (cur.to - cur.from)) {
|
||||
cur.to++;
|
||||
continue;
|
||||
}
|
||||
cur = w ? { at: i, buf: w[0].buf, from: w[1], to: w[1] + 1 } : null;
|
||||
if (cur) out.push(cur);
|
||||
}
|
||||
runs.length = 0;
|
||||
for (const r of out) runs.push(r);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wie `generatePlan`, überlagert aber ZUSÄTZLICH alle sichtbaren Geschoss-
|
||||
* oder Zeichnungs-Ebenen DERSELBEN Art wie `activeLevelId` in EINEM Plan —
|
||||
@@ -544,6 +596,7 @@ export function generateVisibleLevelsPlan(
|
||||
const primitives: Primitive[] = [];
|
||||
const greyedRanges: Array<[number, number]> = [];
|
||||
const underlay: UnderlayGroup[] = [];
|
||||
const bufRuns: PlanBufRun[] = [];
|
||||
const bounds = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
|
||||
const extend = (b: Plan["bounds"]) => {
|
||||
bounds.minX = Math.min(bounds.minX, b.minX);
|
||||
@@ -579,6 +632,7 @@ export function generateVisibleLevelsPlan(
|
||||
// `dwgParser.ts`. Reine `for`-Schleife ist unbegrenzt sicher.
|
||||
const from = primitives.length;
|
||||
for (const pr of p.primitives) primitives.push(pr);
|
||||
shiftRuns(p.bufRuns, from, bufRuns);
|
||||
if (d.greyed && primitives.length > from) greyedRanges.push([from, primitives.length]);
|
||||
// Leere Ebenen melden als Platzhalter (0,0)–(1,1) — NICHT mitzählen: sonst zog
|
||||
// jede leere Nachbar-Ebene den Ausschnitt bis zum Ursprung (bei Landes-
|
||||
@@ -599,6 +653,7 @@ export function generateVisibleLevelsPlan(
|
||||
false,
|
||||
compactUnderlay,
|
||||
);
|
||||
shiftRuns(activePlan.bufRuns, primitives.length, bufRuns);
|
||||
for (const pr of activePlan.primitives) primitives.push(pr);
|
||||
for (const g of activePlan.underlay ?? []) underlay.push(g);
|
||||
// Aktive Ebene leer UND keine Nachbar-Ebene mit Inhalt → Platzhalter-Ausmass.
|
||||
@@ -610,6 +665,7 @@ export function generateVisibleLevelsPlan(
|
||||
backgroundImages: activePlan.backgroundImages,
|
||||
...(greyedRanges.length ? { greyedRanges } : {}),
|
||||
...(underlay.length ? { underlay } : {}),
|
||||
...(bufRuns.length ? { bufRuns } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -863,21 +919,20 @@ function categoryMap(layers: LayerCategory[]): Map<string, LayerCategory> {
|
||||
return map;
|
||||
}
|
||||
|
||||
/** Primitive der Kern-Domänen (`planDomains` in `queries.rs`). */
|
||||
/** Primitive der Kern-Domänen (`planDomains` in `queries.rs`) als gelesener Plan-Puffer v2. */
|
||||
interface DomainPrims {
|
||||
ceilings: Primitive[];
|
||||
walls: Primitive[];
|
||||
stairs: Primitive[];
|
||||
context: Primitive[];
|
||||
sections: Primitive[];
|
||||
roofs: Primitive[];
|
||||
rooms: Primitive[];
|
||||
columns: Primitive[];
|
||||
solids: Primitive[];
|
||||
bounds?: [number, number, number, number];
|
||||
/** Fehlt, wenn das Geschoss nichts für den Kern enthält. */
|
||||
buf?: DecodedPlanBuf;
|
||||
}
|
||||
|
||||
const NO_DOMAINS: DomainPrims = { ceilings: [], walls: [], stairs: [], context: [], sections: [], roofs: [], rooms: [], columns: [], solids: [] };
|
||||
/** Gruppen des Puffers (`plan/domains.rs::GROUPS`). */
|
||||
const G_CEILINGS = 0;
|
||||
const G_COLUMNS = 5;
|
||||
const G_SOLIDS = 6;
|
||||
const G_SECTIONS = 8;
|
||||
const N_GROUPS = 9;
|
||||
|
||||
const NO_DOMAINS: DomainPrims = {};
|
||||
const DETAIL_CODE: Record<DetailLevel, number> = { grob: 0, mittel: 1, fein: 2 };
|
||||
|
||||
/**
|
||||
@@ -932,11 +987,15 @@ function planDomains(
|
||||
show.push(c);
|
||||
if (d.greyed) grey.push(c);
|
||||
}
|
||||
return documentFor(project).query<DomainPrims>(
|
||||
"planDomains",
|
||||
[DETAIL_CODE[detail] ?? 1],
|
||||
JSON.stringify({ floor: floorId, show, grey, referenceLines, global }),
|
||||
const buf = decodePlanBuf(
|
||||
documentFor(project).queryBin(
|
||||
"planDomains",
|
||||
[DETAIL_CODE[detail] ?? 1],
|
||||
JSON.stringify({ floor: floorId, show, grey, referenceLines, global }),
|
||||
),
|
||||
);
|
||||
if (buf.groups.length !== N_GROUPS) throw new Error("planDomains: unerwartete Gruppen im Plan-Puffer");
|
||||
return { buf };
|
||||
}
|
||||
|
||||
function computeBounds(
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import type { Primitive, UnderlayGroup } from '../generatePlan';
|
||||
import type { Drawing2D } from '../../model/types';
|
||||
import { generatePlan } from '../generatePlan';
|
||||
import type { Drawing2D, Project } from '../../model/types';
|
||||
import { flattenCategories } from '../../model/types';
|
||||
import { bigSampleProject } from '../bigSampleProject.testing';
|
||||
import { GpuChunkCache, splitIntoChunks } from './glPlanChunks';
|
||||
import { compilePlanBufRange, compilePrimitivesToGpu } from './glPlanCompile';
|
||||
|
||||
const line = (x: number, drawingId: string): Primitive => ({
|
||||
kind: 'line',
|
||||
@@ -213,3 +217,83 @@ describe('GpuChunkCache: kompakte Unterlage', () => {
|
||||
expect(g.length).toBe(3); // 1 unten + 1 Primitiv-Chunk + 1 oben
|
||||
});
|
||||
});
|
||||
|
||||
describe('GpuChunkCache: Kern-Abschnitte (Plan-Puffer v2, Inhalts-Hash)', () => {
|
||||
const codes = (p: Project) => new Set(flattenCategories(p.layers).map((c) => c.code));
|
||||
/** GL, das die hochgeladenen Daten mitschreibt. */
|
||||
function recordingGl() {
|
||||
const uploads: number[][] = [];
|
||||
const gl = {
|
||||
createBuffer: () => ({}),
|
||||
bindBuffer: () => {},
|
||||
bufferData: (_t: number, d: ArrayBufferView) => uploads.push(Array.from(new Uint8Array(d.buffer, d.byteOffset, d.byteLength))),
|
||||
deleteBuffer: () => {},
|
||||
ARRAY_BUFFER: 1,
|
||||
ELEMENT_ARRAY_BUFFER: 2,
|
||||
STATIC_DRAW: 3,
|
||||
} as unknown as WebGL2RenderingContext;
|
||||
return { gl, uploads };
|
||||
}
|
||||
|
||||
it('neu erzeugter Plan (neue Objekte, gleicher Inhalt) kompiliert nichts neu', () => {
|
||||
const p = bigSampleProject(4);
|
||||
const { gl } = makeGl();
|
||||
const cache = new GpuChunkCache(gl);
|
||||
const a = generatePlan(p, 'eg', codes(p));
|
||||
expect(a.bufRuns?.length).toBe(2);
|
||||
cache.update(a.primitives, 90, 6, a.greyedRanges, a.underlay, a.bufRuns);
|
||||
expect(cache.lastStats.recompiled).toBe(cache.lastStats.chunks);
|
||||
const b = generatePlan(p, 'eg', codes(p));
|
||||
expect(b.primitives[0]).not.toBe(a.primitives[0]);
|
||||
cache.update(b.primitives, 90, 6, b.greyedRanges, b.underlay, b.bufRuns);
|
||||
expect(cache.lastStats.recompiled).toBe(0);
|
||||
// Ohne Abschnitte (Objekt-Identität) wäre alles neu.
|
||||
const c = generatePlan(p, 'eg', codes(p));
|
||||
cache.update(c.primitives, 90, 6, c.greyedRanges, c.underlay);
|
||||
expect(cache.lastStats.recompiled).toBe(cache.lastStats.chunks);
|
||||
});
|
||||
|
||||
it('eine verschobene Wand kompiliert nur wenige Chunks neu', () => {
|
||||
const p = bigSampleProject(8);
|
||||
const { gl } = makeGl();
|
||||
const cache = new GpuChunkCache(gl);
|
||||
const a = generatePlan(p, 'eg', codes(p));
|
||||
cache.update(a.primitives, 90, 6, a.greyedRanges, a.underlay, a.bufRuns);
|
||||
const total = cache.lastStats.chunks;
|
||||
expect(total).toBeGreaterThan(8);
|
||||
const walls = p.walls.slice();
|
||||
walls[200] = { ...walls[200], end: { x: walls[200].end.x + 0.05, y: walls[200].end.y } };
|
||||
const b = generatePlan({ ...p, walls }, 'eg', codes(p));
|
||||
cache.update(b.primitives, 90, 6, b.greyedRanges, b.underlay, b.bufRuns);
|
||||
expect(cache.lastStats.recompiled).toBeGreaterThan(0);
|
||||
expect(cache.lastStats.recompiled).toBeLessThanOrEqual(3);
|
||||
});
|
||||
|
||||
it('ersetzte Primitive (gedimmt geklont) fallen auf den Objekt-Weg zurück', () => {
|
||||
const p = bigSampleProject(2);
|
||||
const { gl } = makeGl();
|
||||
const cache = new GpuChunkCache(gl);
|
||||
const a = generatePlan(p, 'eg', codes(p));
|
||||
const prims = a.primitives.slice();
|
||||
prims[10] = { ...prims[10], greyed: true } as Primitive;
|
||||
cache.update(prims, 90, 6, a.greyedRanges, a.underlay, a.bufRuns);
|
||||
const n = cache.lastStats.chunks;
|
||||
cache.update(prims, 90, 6, a.greyedRanges, a.underlay, a.bufRuns);
|
||||
expect(cache.lastStats.recompiled).toBe(0);
|
||||
expect(cache.lastStats.chunks).toBe(n);
|
||||
});
|
||||
|
||||
it('direkt aus dem Puffer = über die Objekte (gleiche hochgeladene Daten)', () => {
|
||||
const p = bigSampleProject(2);
|
||||
const plan = generatePlan(p, 'eg', codes(p));
|
||||
const run = plan.bufRuns![0];
|
||||
for (const [from, to] of [[run.from, run.to], [run.from + 3, run.to - 5]]) {
|
||||
const x = recordingGl();
|
||||
const y = recordingGl();
|
||||
compilePlanBufRange(x.gl, run.buf, from, to, 120);
|
||||
compilePrimitivesToGpu(y.gl, run.buf.prims.slice(from, to), 120);
|
||||
expect(x.uploads.length).toBeGreaterThan(2);
|
||||
expect(x.uploads).toEqual(y.uploads);
|
||||
}
|
||||
});
|
||||
});
|
||||
+133
-15
@@ -10,21 +10,28 @@
|
||||
* Füllungen ebenfalls vor Linien kamen und innerhalb beider die Primitiv-
|
||||
* Reihenfolge galt.
|
||||
*
|
||||
* Chunk-Grenzen sind INHALTSBASIERT (Hash der `drawingId`), nicht
|
||||
* positionsbasiert: wird vorn ein Element eingefügt, verschieben sich alle
|
||||
* Indizes dahinter, die Grenzen bleiben aber an denselben Elementen — nur der
|
||||
* betroffene Chunk ändert sich.
|
||||
* Chunk-Grenzen sind INHALTSBASIERT (Hash der Element-Id: `drawingId`, sonst
|
||||
* die Pick-Id wie `wallId`), nicht positionsbasiert: wird vorn ein Element
|
||||
* eingefügt, verschieben sich alle Indizes dahinter, die Grenzen bleiben aber
|
||||
* an denselben Elementen — nur der betroffene Chunk ändert sich.
|
||||
*
|
||||
* Wiederverwendung: ein Chunk gilt als unverändert, wenn jede seiner
|
||||
* Primitive dasselbe OBJEKT ist wie beim letzten Lauf (Referenzvergleich) und,
|
||||
* falls er zoomabhängige Primitive (Bögen/Kreise) enthält, der LOD-Bucket
|
||||
* gleich ist. Beim blossen Zoomen werden dadurch nur die (wenigen) Chunks mit
|
||||
* Bögen neu tesselliert.
|
||||
*
|
||||
* Kern-Primitive ([K3d]): Abschnitte, die unverändert aus einem Plan-Puffer des
|
||||
* Kerns stammen (`Plan.bufRuns`), sind bei jeder Plan-Erzeugung neue Objekte —
|
||||
* dort gilt statt der Objekt-Identität der INHALTS-HASH je Primitiv (vom Kern
|
||||
* mitgeliefert), und kompiliert wird direkt aus dem Puffer
|
||||
* (`compilePlanBufRange`), ohne die Objekte erneut zu kodieren.
|
||||
*/
|
||||
|
||||
import type { Primitive, UnderlayGroup } from '../generatePlan';
|
||||
import type { PlanBufRun, Primitive, UnderlayGroup } from '../generatePlan';
|
||||
import type { Drawing2D } from '../../model/types';
|
||||
import { compilePrimitivesToGpu } from './glPlanCompile';
|
||||
import type { DecodedPlanBuf } from '../planBuf';
|
||||
import { compilePlanBufRange, compilePrimitivesToGpu } from './glPlanCompile';
|
||||
import type { BufferGl, GpuGeometry } from './glPlanTypes';
|
||||
|
||||
/** Ziel: im Mittel so viele Elemente (drawingIds) je Chunk = 2^BITS. */
|
||||
@@ -45,10 +52,42 @@ function hashId(id: string): number {
|
||||
return h >>> 0;
|
||||
}
|
||||
|
||||
type Ids = {
|
||||
drawingId?: string;
|
||||
wallId?: string;
|
||||
openingId?: string;
|
||||
stairId?: string;
|
||||
ceilingId?: string;
|
||||
roomId?: string;
|
||||
columnId?: string;
|
||||
roofId?: string;
|
||||
extrudedSolidId?: string;
|
||||
contextObjectId?: string;
|
||||
sectionLineId?: string;
|
||||
};
|
||||
|
||||
/** Element eines Primitivs für die Chunk-Grenzen: `drawingId`, sonst die Pick-Id des Bauteils. */
|
||||
function elemId(p: Primitive): string | undefined {
|
||||
const q = p as Ids;
|
||||
return (
|
||||
q.drawingId ??
|
||||
q.wallId ??
|
||||
q.openingId ??
|
||||
q.stairId ??
|
||||
q.ceilingId ??
|
||||
q.roomId ??
|
||||
q.columnId ??
|
||||
q.roofId ??
|
||||
q.extrudedSolidId ??
|
||||
q.contextObjectId ??
|
||||
q.sectionLineId
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Index-Bereiche [start, end) der Chunks. `cuts` sind Indizes, an denen IMMER
|
||||
* geschnitten wird (Grenzen gedimmter Bereiche, damit ein Chunk entweder ganz
|
||||
* gedimmt ist oder gar nicht).
|
||||
* gedimmt ist oder gar nicht; Grenzen der Kern-Abschnitte).
|
||||
*/
|
||||
export function splitIntoChunks(
|
||||
prims: readonly Primitive[],
|
||||
@@ -57,9 +96,9 @@ export function splitIntoChunks(
|
||||
const out: Array<[number, number]> = [];
|
||||
const mask = (1 << BOUNDARY_BITS) - 1;
|
||||
let start = 0;
|
||||
let prevId: string | undefined = prims.length ? (prims[0] as { drawingId?: string }).drawingId : undefined;
|
||||
let prevId: string | undefined = prims.length ? elemId(prims[0]) : undefined;
|
||||
for (let i = 1; i < prims.length; i++) {
|
||||
const id = (prims[i] as { drawingId?: string }).drawingId;
|
||||
const id = elemId(prims[i]);
|
||||
if (cuts.has(i)) {
|
||||
out.push([start, i]);
|
||||
start = i;
|
||||
@@ -79,12 +118,48 @@ export function splitIntoChunks(
|
||||
}
|
||||
|
||||
interface Chunk {
|
||||
/** Primitive (Referenzvergleich) — leer bei Kern-Chunks, die `keys` tragen. */
|
||||
prims: Primitive[];
|
||||
/** Inhalts-Hashes der Primitive eines Kern-Chunks (sonst null). */
|
||||
keys: Float64Array | null;
|
||||
dynamic: boolean;
|
||||
bucket: number;
|
||||
geometry: GpuGeometry;
|
||||
}
|
||||
|
||||
/** Ein geprüfter Kern-Abschnitt: `primitives[start..end)` = `buf.prims[from..]`. */
|
||||
interface Segment {
|
||||
start: number;
|
||||
end: number;
|
||||
buf: DecodedPlanBuf;
|
||||
from: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kern-Abschnitte auf Objekt-Identität prüfen: nur Stellen, an denen noch genau das dekodierte
|
||||
* Objekt steht (nicht ersetzt durch Abzugskörper, Dimmen, Strichstärken-Massstab), gelten.
|
||||
*/
|
||||
function verifiedSegments(primitives: readonly Primitive[], runs: readonly PlanBufRun[] | undefined): Segment[] {
|
||||
const out: Segment[] = [];
|
||||
for (const r of runs ?? []) {
|
||||
if (!r.buf.hashes) continue;
|
||||
const n = Math.min(r.to - r.from, primitives.length - r.at);
|
||||
let k = 0;
|
||||
while (k < n) {
|
||||
while (k < n && primitives[r.at + k] !== r.buf.prims[r.from + k]) k++;
|
||||
const k0 = k;
|
||||
while (k < n && primitives[r.at + k] === r.buf.prims[r.from + k]) k++;
|
||||
if (k > k0) out.push({ start: r.at + k0, end: r.at + k, buf: r.buf, from: r.from + k0 });
|
||||
}
|
||||
}
|
||||
return out.sort((a, b) => a.start - b.start);
|
||||
}
|
||||
|
||||
function sameKeys(a: Float64Array, b: Float64Array, offset: number): boolean {
|
||||
for (let i = 0; i < a.length; i++) if (a[i] !== b[offset + i]) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function disposeGeometry(gl: BufferGl, g: GpuGeometry): void {
|
||||
gl.deleteBuffer(g.fill.positionBuffer);
|
||||
gl.deleteBuffer(g.fill.indexBuffer);
|
||||
@@ -229,35 +304,77 @@ export class GpuChunkCache {
|
||||
lodBucket: number,
|
||||
greyedRanges?: ReadonlyArray<[number, number]>,
|
||||
underlay?: readonly UnderlayGroup[],
|
||||
/** Abschnitte aus Kern-Puffern (`Plan.bufRuns`): Inhalts-Hash statt Objekt-Identität. */
|
||||
runs?: readonly PlanBufRun[],
|
||||
): void {
|
||||
const cuts = new Set<number>();
|
||||
for (const [a, b] of greyedRanges ?? []) {
|
||||
cuts.add(a);
|
||||
cuts.add(b);
|
||||
}
|
||||
// Aktuelle + vorherige Generation nach erstem Primitiv indizieren (Referenz-Identität).
|
||||
const segs = verifiedSegments(primitives, runs);
|
||||
for (const g of segs) {
|
||||
cuts.add(g.start);
|
||||
cuts.add(g.end);
|
||||
}
|
||||
// Aktuelle + vorherige Generation nach erstem Primitiv (Referenz) bzw. erstem Hash indizieren.
|
||||
const pool = [...this.chunks, ...this.previous];
|
||||
const old = new Map<Primitive, Chunk[]>();
|
||||
const old = new Map<unknown, Chunk[]>();
|
||||
for (const c of pool) {
|
||||
if (!c.prims.length) continue;
|
||||
const list = old.get(c.prims[0]);
|
||||
const first = c.keys ? (c.keys.length ? c.keys[0] : undefined) : c.prims[0];
|
||||
if (first === undefined) continue;
|
||||
const list = old.get(first);
|
||||
if (list) list.push(c);
|
||||
else old.set(c.prims[0], [c]);
|
||||
else old.set(first, [c]);
|
||||
}
|
||||
|
||||
const next: Chunk[] = [];
|
||||
const chunkStarts: number[] = [];
|
||||
const reused = new Set<Chunk>();
|
||||
let recompiled = 0;
|
||||
let si = 0;
|
||||
for (const [start, end] of splitIntoChunks(primitives, cuts)) {
|
||||
chunkStarts.push(start);
|
||||
while (si < segs.length && segs[si].end <= start) si++;
|
||||
const seg = si < segs.length && segs[si].start <= start && end <= segs[si].end ? segs[si] : null;
|
||||
if (seg) {
|
||||
// Kern-Chunk: Inhalts-Hashes vergleichen, direkt aus dem Puffer kompilieren.
|
||||
const hashes = seg.buf.hashes!;
|
||||
const from = seg.from + (start - seg.start);
|
||||
const n = end - start;
|
||||
const hit = old.get(hashes[from])?.find(
|
||||
(c) =>
|
||||
!reused.has(c) &&
|
||||
c.keys !== null &&
|
||||
c.keys.length === n &&
|
||||
(!c.dynamic || c.bucket === lodBucket) &&
|
||||
sameKeys(c.keys, hashes, from),
|
||||
);
|
||||
if (hit) {
|
||||
reused.add(hit);
|
||||
next.push(hit);
|
||||
continue;
|
||||
}
|
||||
let dynamic = false;
|
||||
for (let i = start; i < end && !dynamic; i++) dynamic = isLodDependent(primitives[i]);
|
||||
next.push({
|
||||
prims: [],
|
||||
keys: hashes.slice(from, from + n),
|
||||
dynamic,
|
||||
bucket: lodBucket,
|
||||
geometry: compilePlanBufRange(this.gl, seg.buf, from, from + n, pxPerMeter),
|
||||
});
|
||||
recompiled++;
|
||||
continue;
|
||||
}
|
||||
const hit = old.get(primitives[start])?.find(
|
||||
(c) =>
|
||||
!reused.has(c) &&
|
||||
c.keys === null &&
|
||||
c.prims.length === end - start &&
|
||||
(!c.dynamic || c.bucket === lodBucket) &&
|
||||
sameRefs(c.prims, primitives, start),
|
||||
);
|
||||
chunkStarts.push(start);
|
||||
if (hit) {
|
||||
reused.add(hit);
|
||||
next.push(hit);
|
||||
@@ -266,6 +383,7 @@ export class GpuChunkCache {
|
||||
const slice = primitives.slice(start, end);
|
||||
next.push({
|
||||
prims: slice,
|
||||
keys: null,
|
||||
dynamic: slice.some(isLodDependent),
|
||||
bucket: lodBucket,
|
||||
geometry: compilePrimitivesToGpu(this.gl, slice, pxPerMeter),
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/**
|
||||
* Tessellierung: wandelt Plan-`Primitive` in GPU-fertige Puffer — Fassade über den Rust-Kern
|
||||
* ([K3b], `src-tauri/core/src/gpu_compile.rs`). TS kodiert die Primitive eines Chunks in den
|
||||
* Plan-Puffer (`../planBuf.ts`), Rust tesselliert (Ear-Clipping, Striche mit runden Kappen/Ecken,
|
||||
* Schraffur, Zickzack, Motive, Bögen, Kreise) und liefert Vertex-/Index-/Batch-Daten flach zurück;
|
||||
* hier werden sie nur noch hochgeladen.
|
||||
* ([K3b], `src-tauri/core/src/gpu_compile.rs`). Rust tesselliert (Ear-Clipping, Striche mit runden
|
||||
* Kappen/Ecken, Schraffur, Zickzack, Motive, Bögen, Kreise) und liefert Vertex-/Index-/Batch-Daten
|
||||
* flach zurück; hier werden sie nur noch hochgeladen. Eingabe ist der Plan-Puffer v2
|
||||
* (`../planBuf.ts`): Bereiche eines Kern-Puffers (`planDomains`) gehen direkt in die Kompilierung
|
||||
* ({@link compilePlanBufRange}, [K3d]), gemischte Listen kodiert TS schlank ({@link compilePrimitivesToGpu}).
|
||||
*
|
||||
* Koordinaten: alles in BILDSCHIRM-Raum (wie `toScreen`): sx = mx·PX_PER_M, sy = -my·PX_PER_M,
|
||||
* relativ zum lokalen Ursprung (`origin`, erster abgelegter Punkt).
|
||||
@@ -12,7 +13,7 @@
|
||||
import type { Primitive } from '../generatePlan';
|
||||
import type { Vec2 } from '../../model/types';
|
||||
import type { BufferGl, GpuGeometry, Rgba } from './glPlanTypes';
|
||||
import { encodePlanBuf } from '../planBuf';
|
||||
import { encodePlanBuf, type DecodedPlanBuf } from '../planBuf';
|
||||
import { core } from '../../engine/coreWasm';
|
||||
|
||||
/**
|
||||
@@ -41,7 +42,23 @@ export function compilePrimitivesToGpu(
|
||||
pxPerMeter = 0,
|
||||
): GpuGeometry {
|
||||
const packed = gl.packedLineVertices === true;
|
||||
const out = core().gpu_compile_flat(encodePlanBuf(primitives), pxPerMeter, packed);
|
||||
const out = core().gpu_compile_flat(encodePlanBuf(primitives, { lean: true }), 0, primitives.length, pxPerMeter, packed);
|
||||
return uploadCompiled(gl, out);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wie {@link compilePrimitivesToGpu} für die Primitive `[from, to)` eines Kern-Puffers — ohne
|
||||
* Umweg über Objekte: der Puffer wird einmal im Kern abgelegt (`plan_buf_hold`) und für alle
|
||||
* Chunks wiederverwendet. Ist er dort verdrängt, wird er neu abgelegt.
|
||||
*/
|
||||
export function compilePlanBufRange(gl: BufferGl, src: DecodedPlanBuf, from: number, to: number, pxPerMeter = 0): GpuGeometry {
|
||||
const packed = gl.packedLineVertices === true;
|
||||
const c = core();
|
||||
let out = src.hold ? c.gpu_compile_held(src.hold, from, to, pxPerMeter, packed) : new Uint32Array(0);
|
||||
if (out.length === 0) {
|
||||
src.hold = c.plan_buf_hold(src.bytes);
|
||||
out = src.hold ? c.gpu_compile_held(src.hold, from, to, pxPerMeter, packed) : c.gpu_compile_flat(src.bytes, from, to, pxPerMeter, packed);
|
||||
}
|
||||
return uploadCompiled(gl, out);
|
||||
}
|
||||
|
||||
|
||||
+126
-53
@@ -1,8 +1,10 @@
|
||||
// Plan-Puffer [K3b]: TS kodiert, Rust liest und schreibt neu — Hin und zurück muss jede Zahl
|
||||
// erhalten (je Primitiv-Typ), fremde Versionen werden sauber abgelehnt.
|
||||
// Plan-Puffer v2 [K3d]: TS kodiert und liest, Rust liest und schreibt neu — hin und zurück bleibt
|
||||
// jedes Primitiv gleich (je Typ, gemischt, über den Kern), fremde Versionen werden sauber abgelehnt.
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { encodePlanBuf, encodeHatch, parseColor, PLAN_BUF_MAGIC, PLAN_BUF_VERSION } from "./planBuf";
|
||||
import { decodePlanBuf, encodeHatch, encodePlanBuf, PLAN_BUF_MAGIC, PLAN_BUF_VERSION } from "./planBuf";
|
||||
import { documentFor } from "../core/document";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import type { HatchRender, Primitive } from "./generatePlan";
|
||||
|
||||
@@ -51,88 +53,159 @@ const PRIMS: Record<string, Primitive> = {
|
||||
arc: { kind: "arc", center: { x: 0, y: 0 }, from: { x: 1, y: 0 }, to: { x: 0, y: 1 }, r: 1, cls: "c", weightMm: 0.18, opacity: 0.5 },
|
||||
drawingCircle: { kind: "drawingCircle", center: { x: 5, y: 5 }, r: 2, fill: "none", stroke: "#123", weightMm: 0.18, dash: [2] },
|
||||
drawingArc: { kind: "drawingArc", center: { x: 5, y: 5 }, r: 2, a0: 0, a1: 3, stroke: "#123", weightMm: 0.5, greyed: true },
|
||||
text: { kind: "drawingText", at: { x: 0, y: 0 }, text: "x", heightM: 1, angle: 0, color: "#000" },
|
||||
image: { kind: "drawingImage", min: { x: 0, y: 0 }, max: { x: 1, y: 1 }, src: "", opacity: 1 },
|
||||
text: { kind: "drawingText", at: { x: 0, y: 0 }, text: "x 𝄞 ü", heightM: 1, angle: 0, color: "#000", drawingId: "t" },
|
||||
textPath: { kind: "drawingTextPath", pathPts: [{ x: 0, y: 0 }, { x: 1, y: 2 }], text: "Pfad", heightM: 0.2, color: "#f00", greyed: false },
|
||||
image: { kind: "drawingImage", min: { x: 0, y: 0 }, max: { x: 1, y: 1 }, src: "data:image/png;base64,AA", opacity: 1 },
|
||||
stamp: {
|
||||
kind: "text",
|
||||
at: { x: 1, y: 1 },
|
||||
doc: { version: 1, paragraphs: [{ align: "center", runs: [{ text: "Bad", marks: { bold: true } }] }] },
|
||||
extraLines: [{ text: "4.20 m²", align: "center" }],
|
||||
basePt: 10,
|
||||
color: "#333",
|
||||
roomId: "R1",
|
||||
} as unknown as Primitive,
|
||||
dashNull: { kind: "arc", center: { x: 0, y: 0 }, from: { x: 1, y: 0 }, to: { x: 0, y: 1 }, r: 1, cls: "c", weightMm: 0.18, dash: null, openingId: "o", stairId: "s", greyed: false },
|
||||
manyIds: {
|
||||
kind: "polygon",
|
||||
pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }],
|
||||
fill: "none",
|
||||
stroke: "#000",
|
||||
strokeWidthMm: 0.1,
|
||||
hatch,
|
||||
sectionLineId: "sl",
|
||||
wallId: "w",
|
||||
stairId: "st",
|
||||
},
|
||||
};
|
||||
|
||||
/** Gleichheit Zahl für Zahl (NaN = NaN, −0 ≠ +0). */
|
||||
function sameBits(a: Float64Array, b: Float64Array): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) if (!Object.is(a[i], b[i])) return false;
|
||||
return true;
|
||||
/**
|
||||
* JSON mit sortierten Schlüsseln. Fehlende Zahlen (TS `undefined`) reisen als NaN — beide fallen
|
||||
* hier weg; Kern-Ausgaben vergleichen die Paritätstests mit dem früheren JSON (NaN → null).
|
||||
*/
|
||||
function canon(v: unknown): string {
|
||||
return JSON.stringify(v, (_k, x) =>
|
||||
typeof x === "number" && Number.isNaN(x)
|
||||
? undefined
|
||||
: x && typeof x === "object" && !Array.isArray(x)
|
||||
? Object.fromEntries(Object.keys(x).sort().map((k) => [k, (x as Record<string, unknown>)[k]]))
|
||||
: x,
|
||||
);
|
||||
}
|
||||
|
||||
describe("Plan-Puffer", () => {
|
||||
/** Flags der Einträge (Kopf und Offsets gelesen wie im Format beschrieben). */
|
||||
function recFlags(bytes: Uint8Array): number[] {
|
||||
const f = new Float64Array(bytes.buffer, bytes.byteOffset, bytes.byteLength >> 3);
|
||||
const [nStrings, , nHatchWords, nGroups, nPrims] = [f[3], f[4], f[5], f[6], f[7]];
|
||||
const offAt = 16 + 2 * nStrings + nHatchWords + 2 * nGroups;
|
||||
const recAt = offAt + nPrims * (f[2] & 1 ? 2 : 1);
|
||||
return Array.from({ length: nPrims }, (_, i) => f[recAt + f[offAt + i] + 1]);
|
||||
}
|
||||
|
||||
describe("Plan-Puffer v2", () => {
|
||||
for (const [name, prim] of Object.entries(PRIMS)) {
|
||||
it(`Hin und zurück: ${name}`, () => {
|
||||
const buf = encodePlanBuf([prim]);
|
||||
expect(buf[0]).toBe(PLAN_BUF_MAGIC);
|
||||
expect(buf[1]).toBe(PLAN_BUF_VERSION);
|
||||
expect(buf[4]).toBe(1);
|
||||
expect(sameBits(core().plan_buf_recode(buf), buf)).toBe(true);
|
||||
const head = new Float64Array(buf.buffer, 0, 8);
|
||||
expect(head[0]).toBe(PLAN_BUF_MAGIC);
|
||||
expect(head[1]).toBe(PLAN_BUF_VERSION);
|
||||
expect(head[7]).toBe(1);
|
||||
expect(canon(decodePlanBuf(buf).prims)).toBe(canon([prim]));
|
||||
// Über den Kern (lesen + neu schreiben) bleibt der Inhalt gleich.
|
||||
expect(canon(decodePlanBuf(core().plan_buf_recode(buf)).prims)).toBe(canon([prim]));
|
||||
});
|
||||
}
|
||||
|
||||
it("Hin und zurück: alle Typen gemischt, ein Eintrag je Primitiv", () => {
|
||||
it("Hin und zurück: alle Typen gemischt, mit Gruppen und Ausmass", () => {
|
||||
const prims = Object.values(PRIMS);
|
||||
const buf = encodePlanBuf(prims);
|
||||
expect(buf[4]).toBe(prims.length);
|
||||
expect(sameBits(core().plan_buf_recode(buf), buf)).toBe(true);
|
||||
const buf = encodePlanBuf(prims, { groups: [[0, 2], [2, prims.length]], bounds: [-1, -2, 3, 4] });
|
||||
const d = decodePlanBuf(buf);
|
||||
expect(canon(d.prims)).toBe(canon(prims));
|
||||
expect(d.groups).toEqual([[0, 2], [2, prims.length]]);
|
||||
expect(d.bounds).toEqual([-1, -2, 3, 4]);
|
||||
expect(d.hashes).toBeNull();
|
||||
const back = decodePlanBuf(core().plan_buf_recode(buf));
|
||||
expect(canon(back.prims)).toBe(canon(prims));
|
||||
expect(back.groups).toEqual(d.groups);
|
||||
// Schraffuren werden einmal gelesen und geteilt.
|
||||
expect((d.prims[0] as { hatch: unknown }).hatch).toBe((d.prims[prims.length - 1] as { hatch: unknown }).hatch);
|
||||
});
|
||||
|
||||
it("Texte und Bilder sind Platzhalter (nur der Typ-Eintrag 0)", () => {
|
||||
expect(Array.from(encodePlanBuf([PRIMS.text, PRIMS.image]))).toEqual([PLAN_BUF_MAGIC, PLAN_BUF_VERSION, 0, 0, 2, 0, 0]);
|
||||
it("Texte mit einzelnen Surrogaten bleiben in TS exakt", () => {
|
||||
const t = { ...PRIMS.text, text: "a\ud800b\udfff" } as Primitive;
|
||||
expect(decodePlanBuf(encodePlanBuf([t])).prims[0]).toEqual(t);
|
||||
});
|
||||
|
||||
it("Farben werden einmal geparst und geteilt, ungültige ergeben −1", () => {
|
||||
const a = { ...PRIMS.line, color: "#ff0000" } as Primitive;
|
||||
const b = { ...PRIMS.line, color: "nonsense" } as Primitive;
|
||||
const buf = encodePlanBuf([a, a, b]);
|
||||
expect(buf[2]).toBe(1);
|
||||
expect(Array.from(buf.subarray(5, 9))).toEqual(parseColor("#ff0000"));
|
||||
it("schlank (nur GPU): Texte/Bilder als Platzhalter, ohne Ids und Klassen", () => {
|
||||
const prims = Object.values(PRIMS);
|
||||
const lean = encodePlanBuf(prims, { lean: true });
|
||||
expect(lean.byteLength).toBeLessThan(encodePlanBuf(prims).byteLength);
|
||||
expect(() => decodePlanBuf(lean)).toThrow();
|
||||
// Die GPU-Kompilierung liest beide gleich.
|
||||
const a = core().gpu_compile_flat(lean, 0, prims.length, 90, true);
|
||||
const b = core().gpu_compile_flat(encodePlanBuf(prims), 0, prims.length, 90, true);
|
||||
expect(a.length).toBeGreaterThan(30);
|
||||
expect(Array.from(a)).toEqual(Array.from(b));
|
||||
});
|
||||
|
||||
it("Linienzug-Flag: nur gleiches Element, gleicher Stil und lückenlos", () => {
|
||||
const seg = (ax: number, bx: number, extra: object = {}): Primitive =>
|
||||
({ kind: "line", a: { x: ax, y: 0 }, b: { x: bx, y: 0 }, cls: "c", weightMm: 0.18, color: "#000", drawingId: "d", ...extra }) as Primitive;
|
||||
const flagsOf = (prims: Primitive[]) => {
|
||||
const buf = encodePlanBuf(prims);
|
||||
const out: number[] = [];
|
||||
let i = 5 + buf[2] * 4;
|
||||
for (let k = 0; k < prims.length; k++) {
|
||||
out.push(buf[i + 1] & 4);
|
||||
i += 9 + 1 + buf[i + 9];
|
||||
}
|
||||
return out;
|
||||
};
|
||||
expect(flagsOf([seg(0, 1), seg(1, 2), seg(2, 3)])).toEqual([0, 4, 4]);
|
||||
expect(flagsOf([seg(0, 1), seg(1.5, 2)])).toEqual([0, 0]);
|
||||
expect(flagsOf([seg(0, 1), seg(1, 2, { drawingId: "e" })])).toEqual([0, 0]);
|
||||
expect(flagsOf([seg(0, 1), seg(1, 2, { weightMm: 0.5 })])).toEqual([0, 0]);
|
||||
expect(flagsOf([seg(0, 1), seg(1, 2, { greyed: false })])).toEqual([0, 0]);
|
||||
expect(flagsOf([seg(0, 1, { dash: [1] }), seg(1, 2, { dash: [1] })])).toEqual([0, 0]);
|
||||
const chain = (prims: Primitive[]) => recFlags(encodePlanBuf(prims)).map((fl) => fl & 8);
|
||||
expect(chain([seg(0, 1), seg(1, 2), seg(2, 3)])).toEqual([0, 8, 8]);
|
||||
expect(chain([seg(0, 1), seg(1.5, 2)])).toEqual([0, 0]);
|
||||
expect(chain([seg(0, 1), seg(1, 2, { drawingId: "e" })])).toEqual([0, 0]);
|
||||
expect(chain([seg(0, 1), seg(1, 2, { weightMm: 0.5 })])).toEqual([0, 0]);
|
||||
expect(chain([seg(0, 1), seg(1, 2, { greyed: false })])).toEqual([0, 0]);
|
||||
// Strichmuster: dieselbe Referenz verbindet, gleiche Werte in neuen Listen nicht.
|
||||
expect(chain([seg(0, 1, { dash: [1] }), seg(1, 2, { dash: [1] })])).toEqual([0, 0]);
|
||||
const d = [1];
|
||||
expect(chain([seg(0, 1, { dash: d }), seg(1, 2, { dash: d })])).toEqual([0, 8]);
|
||||
expect(chain([seg(0, 1, { dash: null }), seg(1, 2, { dash: null })])).toEqual([0, 8]);
|
||||
});
|
||||
|
||||
it("fremde Version oder kaputter Puffer → leeres Ergebnis, kein Absturz", () => {
|
||||
const buf = encodePlanBuf(Object.values(PRIMS));
|
||||
it("fremde Version oder kaputter Puffer → leeres Ergebnis bzw. Fehler, kein Absturz", () => {
|
||||
const prims = Object.values(PRIMS);
|
||||
const buf = encodePlanBuf(prims);
|
||||
const wrong = buf.slice();
|
||||
wrong[1] = PLAN_BUF_VERSION + 1;
|
||||
new Float64Array(wrong.buffer, 0, 2)[1] = PLAN_BUF_VERSION + 1;
|
||||
expect(core().plan_buf_recode(wrong).length).toBe(0);
|
||||
expect(core().gpu_compile_flat(wrong, 90, true).length).toBe(0);
|
||||
expect(core().gpu_compile_flat(wrong, 0, 1, 90, true).length).toBe(0);
|
||||
expect(() => decodePlanBuf(wrong)).toThrow(/Version/);
|
||||
expect(core().plan_buf_recode(buf.subarray(0, buf.length - 3)).length).toBe(0);
|
||||
expect(core().gpu_compile_flat(new Float64Array([1, 2, 3]), 90, false).length).toBe(0);
|
||||
expect(() => decodePlanBuf(buf.subarray(0, buf.length - 2))).toThrow();
|
||||
expect(core().gpu_compile_flat(new Uint8Array([1, 2, 3]), 0, 0, 90, false).length).toBe(0);
|
||||
expect(core().gpu_compile_flat(buf, 0, prims.length + 1, 90, false).length).toBe(0);
|
||||
expect(core().gpu_compile_held(424242, 0, 1, 90, false).length).toBe(0);
|
||||
expect(core().plan_buf_hold(wrong)).toBe(0);
|
||||
// Danach arbeitet der Kern normal weiter.
|
||||
expect(sameBits(core().plan_buf_recode(buf), buf)).toBe(true);
|
||||
expect(canon(decodePlanBuf(core().plan_buf_recode(buf)).prims)).toBe(canon(prims));
|
||||
});
|
||||
|
||||
it("gehaltener Puffer kompiliert wie der übergebene", () => {
|
||||
const prims = Object.values(PRIMS);
|
||||
const buf = encodePlanBuf(prims);
|
||||
const id = core().plan_buf_hold(buf);
|
||||
expect(id).toBeGreaterThan(0);
|
||||
expect(Array.from(core().gpu_compile_held(id, 1, 5, 90, true))).toEqual(Array.from(core().gpu_compile_flat(buf, 1, 5, 90, true)));
|
||||
core().plan_buf_release(id);
|
||||
expect(core().gpu_compile_held(id, 1, 5, 90, true).length).toBe(0);
|
||||
});
|
||||
|
||||
it("Fehler einer Kern-Abfrage kommen als Meldung", () => {
|
||||
const doc = documentFor(sampleProject);
|
||||
expect(() => decodePlanBuf(doc.queryBin("planDomains", [1], "kein json"))).toThrow(/Plan-Argumente/);
|
||||
});
|
||||
|
||||
it("Einzel-Schraffur hat dasselbe Format wie ein Hatch-Eintrag", () => {
|
||||
const h = encodeHatch(hatch);
|
||||
const buf = encodePlanBuf([PRIMS.polygon]);
|
||||
const colors = buf[2];
|
||||
// Im Plan-Puffer steht der Farbindex statt −1.
|
||||
const inPlan = buf.slice(5 + colors * 4, 5 + colors * 4 + h.length);
|
||||
const f = new Float64Array(buf.buffer, 0, buf.byteLength >> 3);
|
||||
const at = 16 + 2 * f[3] + 1; // nach dem JSON-String-Index des ersten Eintrags
|
||||
const inPlan = f.slice(at, at + h.length);
|
||||
// Im Plan-Puffer steht der Farb-String statt −1.
|
||||
expect(inPlan[5]).toBeGreaterThanOrEqual(0);
|
||||
inPlan[5] = -1;
|
||||
expect(sameBits(inPlan, h)).toBe(true);
|
||||
expect(Array.from(inPlan)).toEqual(Array.from(h));
|
||||
});
|
||||
});
|
||||
+489
-189
@@ -1,91 +1,73 @@
|
||||
/**
|
||||
* Plan-Puffer ([K3b]): kompakte Binärkodierung der zeichnungsrelevanten Plan-Primitive als
|
||||
* flacher `Float64Array`. TS schreibt ihn vorerst aus `Plan.primitives`, der Rust-Kern liest ihn
|
||||
* (`src-tauri/core/src/plan_buf.rs`, dort dieselbe Formatbeschreibung) — heute für die GPU-
|
||||
* Kompilierung (`glPlan/glPlanCompile.ts`), ab [K3a] erzeugt Rust ihn direkt.
|
||||
* Plan-Puffer v2 ([K3d]): binäre Übergabe der Plan-Primitive zwischen Rust-Kern und TS — Format
|
||||
* und Bedeutung aller Felder stehen im Kopf von `src-tauri/core/src/plan_buf.rs` (hier gekürzt).
|
||||
* Der Kern schreibt ihn direkt aus der Plan-Erzeugung (Abfrage `planDomains`); TS liest ihn zu
|
||||
* `Primitive[]` ({@link decodePlanBuf}: Auswahl, Overlay, SVG/PDF/DXF) und schreibt ihn für
|
||||
* GPU-Chunks aus gemischten Listen ({@link encodePlanBuf}, `glPlanCompile.ts`). Die GPU-Kompilierung
|
||||
* liest Bereiche eines Kern-Puffers direkt (`compilePlanBufRange`), ohne Umweg über Objekte.
|
||||
*
|
||||
* ```text
|
||||
* Kopf [MAGIC, VERSION, nColors, nHatches, nPrims]
|
||||
* MAGIC = 0x504C4231 ("PLB1"), VERSION = 1 — Rust lehnt fremde Werte ab (leeres Ergebnis)
|
||||
* Farben nColors × [r, g, b, a] (0..1, hier aus dem Farbtext geparst)
|
||||
* Schraffuren nHatches × Hatch
|
||||
* Primitive nPrims × Prim (genau ein Eintrag je Primitiv → Indizes bleiben gleich)
|
||||
*
|
||||
* Hatch [pattern, kind, flags, scale, angle, colorIdx, lineWeight, originX, originY,
|
||||
* seed, density, lengthMin, lengthMax, nDash, dash…, (Motiv: length, nPts, x,y…)]
|
||||
* pattern 0 none · 1 solid · 2 diagonal (auch unbekannt) · 3 crosshatch · 4 insulation · 5 custom
|
||||
* kind 0 vector · 1 image · 2 gradient (Bild/Verlauf: GPU fällt auf die Füllung zurück)
|
||||
* flags 1 random · 2 origin · 4 seed · 8 density · 16 lengthMin · 32 lengthMax · 64 Motiv
|
||||
* (Felder ohne Flag stehen auf 0 und gelten als „nicht gesetzt")
|
||||
*
|
||||
* Prim [tag, flags, …] flags 1 greyed · 2 opacity gesetzt · 4 setzt den Linienzug der
|
||||
* vorigen Linie fort · 8 Zickzack · 16 Motiv
|
||||
* 0 Platzhalter [0] (Text, Bild … — zeichnet die GPU nicht)
|
||||
* 1 polygon [1, flags, fillIdx, strokeIdx, strokeWidthMm, hatchIdx, opacity,
|
||||
* nPts, x,y…, nNoStroke, kante…]
|
||||
* 2 line [2, flags, colorIdx, weightMm, opacity, ax, ay, bx, by, nDash, dash…,
|
||||
* (Zickzack: amplitude, wavelength), (Motiv: length, nPts, x,y…)]
|
||||
* 3 arc [3, flags, colorIdx, weightMm, opacity, cx, cy, fromX, fromY, toX, toY, r,
|
||||
* nDash, dash…]
|
||||
* 4 drawingCircle [4, flags, fillIdx, strokeIdx, weightMm, opacity, cx, cy, r, nDash, dash…]
|
||||
* 5 drawingArc [5, flags, strokeIdx, weightMm, opacity, cx, cy, r, a0, a1, nDash, dash…]
|
||||
* Bytes: f64-Teil, dann UTF-16-Einheiten aller Texte
|
||||
* Kopf (16) [MAGIC "PLB2", VERSION 2, flags (1 Hashes, 2 Ausmass), nStrings, nHatches, nHatchWords,
|
||||
* nGroups, nPrims, nRecWords, nPool, nUnits, 0, minX, minY, maxX, maxY]
|
||||
* Strings nStrings × [unitOff, unitLen]
|
||||
* Schraffur nHatches × [jsonStr, Hatch] (Hatch wie encodeHatch, Farbe = String-Index)
|
||||
* Gruppen nGroups × [start, end)
|
||||
* Offsets nPrims × Wortindex des Eintrags
|
||||
* Hashes nPrims × Inhalts-Hash (nur Kern)
|
||||
* Primitive [tag, flags, pickKind, pickStr, …] 1 polygon · 2 line · 3 arc · 4 drawingCircle ·
|
||||
* 5 drawingArc · 6 text · 7 drawingText · 8 drawingTextPath · 9 drawingImage (JSON) ·
|
||||
* 0 Platzhalter (nur `lean`)
|
||||
* Pool Punkte, Strichmuster, Kantenlisten, Motive, weitere Ids
|
||||
* ```
|
||||
* Farb-/Schraffur-Index −1 = keine (Farbtext ungültig, "none", fehlende Schraffur). Längen in
|
||||
* Metern, Strichstärken/Strichmuster/Zickzack/Motiv in Papier-mm, Winkel von drawingArc in
|
||||
* Bogenmass, Schraffur-Winkel in Grad (SVG-Drehsinn). Ohne opacity-Flag steht 1 im Feld; fehlende
|
||||
* Zahlen (`undefined`) werden NaN, der Verbraucher nimmt dann wie bisher seinen Standard.
|
||||
* Flag 4 (Linienzug): gleiches Element (`drawingId`), gleiche Farbe/Stärke/greyed/opacity/
|
||||
* Strichmuster (Referenz) und Anfang = Ende der vorigen Linie — dann zeichnet die GPU die
|
||||
* Einzelsegmente als EINEN Zug (zwei echte Kappen statt 2N). Pick-IDs stehen NICHT im Puffer
|
||||
* (Picken bleibt vorerst TS).
|
||||
* Flags: 1 greyed gesetzt · 2 greyed · 4 opacity · 8 Linienzug · 16 Zickzack · 32 Motiv ·
|
||||
* 64 dash null · 128 dash Liste · 256 noStrokeEdges · 512 Farbe (line/arc) · 1024 weitere Ids.
|
||||
*/
|
||||
|
||||
import type { HatchRender, Primitive } from "./generatePlan";
|
||||
import type { Vec2 } from "../model/types";
|
||||
|
||||
export const PLAN_BUF_MAGIC = 0x504c4231;
|
||||
export const PLAN_BUF_VERSION = 1;
|
||||
export const PLAN_BUF_MAGIC = 0x504c4232;
|
||||
export const PLAN_BUF_VERSION = 2;
|
||||
/** Fehlerpuffer einer Kern-Abfrage ("PLBe"): `[ERR_MAGIC, nUnits]` + Meldung (UTF-16). */
|
||||
export const PLAN_BUF_ERR_MAGIC = 0x504c4265;
|
||||
const HEAD = 16;
|
||||
|
||||
/** RGBA-Farbe, Komponenten in [0,1]. */
|
||||
export type PlanRgba = [number, number, number, number];
|
||||
const F_GREYED_SET = 1;
|
||||
const F_GREYED = 2;
|
||||
const F_OPACITY = 4;
|
||||
const F_CHAIN = 8;
|
||||
const F_ZIGZAG = 16;
|
||||
const F_MOTIF = 32;
|
||||
const F_DASH_NULL = 64;
|
||||
const F_DASH_LIST = 128;
|
||||
const F_NSE = 256;
|
||||
const F_COLOR = 512;
|
||||
const F_IDS = 1024;
|
||||
|
||||
const FLAG_GREYED = 1;
|
||||
const FLAG_OPACITY = 2;
|
||||
const FLAG_CHAIN = 4;
|
||||
const FLAG_ZIGZAG = 8;
|
||||
const FLAG_MOTIF = 16;
|
||||
|
||||
/**
|
||||
* Farbe → RGBA[0..1]; ungültig/"none"/"transparent" → null.
|
||||
* Unterstützt "#rgb", "#rrggbb", "#rrggbbaa" und "rgb()/rgba()".
|
||||
*/
|
||||
export function parseColor(hex: string | undefined): PlanRgba | null {
|
||||
if (!hex) return null;
|
||||
const s = hex.trim().toLowerCase();
|
||||
if (s === "none" || s === "transparent") return null;
|
||||
|
||||
if (s.startsWith("rgb")) {
|
||||
const m = s.match(/[\d.]+/g);
|
||||
if (!m || m.length < 3) return null;
|
||||
const a = m.length >= 4 ? parseFloat(m[3]) : 1;
|
||||
return [+m[0] / 255, +m[1] / 255, +m[2] / 255, a > 1 ? a / 255 : a];
|
||||
}
|
||||
|
||||
let h = s[0] === "#" ? s.slice(1) : s;
|
||||
if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2];
|
||||
if (h.length !== 6 && h.length !== 8) return null;
|
||||
const r = parseInt(h.slice(0, 2), 16);
|
||||
const g = parseInt(h.slice(2, 4), 16);
|
||||
const b = parseInt(h.slice(4, 6), 16);
|
||||
const a = h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1;
|
||||
if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
|
||||
return [r / 255, g / 255, b / 255, a];
|
||||
}
|
||||
/** Pick-Arten (Index + 1) = Feldname am Primitiv. */
|
||||
const PICK_KEYS = [
|
||||
"wallId",
|
||||
"drawingId",
|
||||
"ceilingId",
|
||||
"openingId",
|
||||
"stairId",
|
||||
"roomId",
|
||||
"extrudedSolidId",
|
||||
"contextObjectId",
|
||||
"columnId",
|
||||
"roofId",
|
||||
"sectionLineId",
|
||||
] as const;
|
||||
type PickKey = (typeof PICK_KEYS)[number];
|
||||
|
||||
/** Wachsender `Float64Array`-Schreiber. */
|
||||
class F64Writer {
|
||||
buf = new Float64Array(1024);
|
||||
buf: Float64Array;
|
||||
length = 0;
|
||||
constructor(cap = 256) {
|
||||
this.buf = new Float64Array(cap);
|
||||
}
|
||||
private grow(need: number): void {
|
||||
let cap = this.buf.length * 2;
|
||||
while (cap < need) cap *= 2;
|
||||
@@ -131,7 +113,7 @@ const PATTERN_CODE: Record<string, number> = {
|
||||
custom: 5,
|
||||
};
|
||||
|
||||
/** Eine Schraffur im Hatch-Format (auch Eingabe der Einzel-Bindungen in `glPlanHatch.ts`). */
|
||||
/** Ein Hatch-Datensatz (auch Eingabe der Einzel-Bindungen in `glPlanHatch.ts`). */
|
||||
function writeHatch(w: F64Writer, h: HatchRender, colorIdx: number): void {
|
||||
let flags = 0;
|
||||
if (h.lines === "random") flags |= 1;
|
||||
@@ -165,14 +147,11 @@ function writeHatch(w: F64Writer, h: HatchRender, colorIdx: number): void {
|
||||
|
||||
/** Einzelne Schraffur kodieren (Farbe −1) — Eingabe der Schraffur-Bindungen des Kerns. */
|
||||
export function encodeHatch(h: HatchRender): Float64Array {
|
||||
const w = new F64Writer();
|
||||
const w = new F64Writer(32);
|
||||
writeHatch(w, h, -1);
|
||||
return w.buf.subarray(0, w.length);
|
||||
}
|
||||
|
||||
/** Zwischenspeicher Farbtext → Farbindex-Eintrag (geparste Farbe oder null). */
|
||||
const colorCache = new Map<string, PlanRgba | null>();
|
||||
|
||||
type LinePrim = Extract<Primitive, { kind: "line" }>;
|
||||
|
||||
const isPlainLine = (p: Primitive | undefined): p is LinePrim =>
|
||||
@@ -193,164 +172,485 @@ function chainsPrev(prev: Primitive | undefined, p: LinePrim): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/** Primitive → Plan-Puffer (Format s. Dateikopf). */
|
||||
export function encodePlanBuf(prims: readonly Primitive[]): Float64Array {
|
||||
const colors: PlanRgba[] = [];
|
||||
const colorIdx = new Map<string, number>();
|
||||
let lastColor: string | undefined;
|
||||
let lastColorIdx = -1;
|
||||
const color = (s: string | undefined): number => {
|
||||
if (!s) return -1;
|
||||
if (s === lastColor) return lastColorIdx;
|
||||
let i = colorIdx.get(s);
|
||||
if (i !== undefined) {
|
||||
lastColor = s;
|
||||
lastColorIdx = i;
|
||||
return i;
|
||||
export interface EncodeOptions {
|
||||
/**
|
||||
* Nur für die GPU: ohne Pick-Ids, Linienklassen und Schraffur-JSON, Texte/Bilder als Platzhalter
|
||||
* (tag 0). Schneller; {@link decodePlanBuf} kann so einen Puffer nicht vollständig lesen.
|
||||
*/
|
||||
lean?: boolean;
|
||||
/** Gruppen `[start, end)` in den Kopf schreiben. */
|
||||
groups?: ReadonlyArray<readonly [number, number]>;
|
||||
bounds?: readonly [number, number, number, number];
|
||||
}
|
||||
|
||||
/** Primitive → Plan-Puffer v2 (Format s. Dateikopf). */
|
||||
export function encodePlanBuf(prims: readonly Primitive[], opts: EncodeOptions = {}): Uint8Array {
|
||||
const lean = opts.lean === true;
|
||||
const strParts: string[] = [];
|
||||
const strTab = new F64Writer(64);
|
||||
const strIdx = new Map<string, number>();
|
||||
let units = 0;
|
||||
const str = (s: string | undefined): number => {
|
||||
if (s === undefined) return -1;
|
||||
let i = strIdx.get(s);
|
||||
if (i === undefined) {
|
||||
i = strTab.length >> 1;
|
||||
strTab.push(units);
|
||||
strTab.push(s.length);
|
||||
units += s.length;
|
||||
strParts.push(s);
|
||||
strIdx.set(s, i);
|
||||
}
|
||||
let c = colorCache.get(s);
|
||||
if (c === undefined) {
|
||||
c = parseColor(s);
|
||||
if (colorCache.size > 4096) colorCache.clear();
|
||||
colorCache.set(s, c);
|
||||
}
|
||||
i = c ? colors.push(c) - 1 : -1;
|
||||
colorIdx.set(s, i);
|
||||
return i;
|
||||
};
|
||||
const hatchW = new F64Writer();
|
||||
const hatchW = new F64Writer(64);
|
||||
const hatchIdx = new Map<HatchRender, number>();
|
||||
const hatch = (h: HatchRender | undefined): number => {
|
||||
if (!h) return -1;
|
||||
let i = hatchIdx.get(h);
|
||||
if (i === undefined) {
|
||||
i = hatchIdx.size;
|
||||
writeHatch(hatchW, h, color(h.color));
|
||||
hatchW.push(lean ? -1 : str(JSON.stringify(h)));
|
||||
writeHatch(hatchW, h, str(h.color));
|
||||
hatchIdx.set(h, i);
|
||||
}
|
||||
return i;
|
||||
};
|
||||
const style = (greyed: boolean | undefined, opacity: number | undefined): number =>
|
||||
(greyed ? FLAG_GREYED : 0) | (opacity !== undefined ? FLAG_OPACITY : 0);
|
||||
const offsets = new Float64Array(prims.length);
|
||||
const w = new F64Writer(Math.max(256, prims.length * 14));
|
||||
const pool = new F64Writer(Math.max(256, prims.length * 4));
|
||||
const poolList = (l: readonly number[]): void => {
|
||||
w.push(pool.length);
|
||||
w.push(l.length);
|
||||
const o = pool.reserve(l.length);
|
||||
for (let i = 0; i < l.length; i++) pool.buf[o + i] = l[i];
|
||||
};
|
||||
const poolPts = (p: readonly Vec2[]): void => {
|
||||
w.push(pool.length);
|
||||
w.push(p.length);
|
||||
const o = pool.reserve(2 * p.length);
|
||||
const b = pool.buf;
|
||||
for (let i = 0; i < p.length; i++) {
|
||||
b[o + 2 * i] = p[i].x;
|
||||
b[o + 2 * i + 1] = p[i].y;
|
||||
}
|
||||
};
|
||||
const styleFlags = (greyed: boolean | undefined, opacity: number | undefined): number =>
|
||||
(greyed === undefined ? 0 : greyed ? F_GREYED_SET | F_GREYED : F_GREYED_SET) | (opacity !== undefined ? F_OPACITY : 0);
|
||||
const dashFlags = (d: number[] | null | undefined): number => (d === null ? F_DASH_NULL : d ? F_DASH_LIST : 0);
|
||||
const op = (opacity: number | undefined): number => (opacity !== undefined ? opacity : 1);
|
||||
/** Kopf [tag, flags, pickKind, pickStr]; liefert die weiteren Ids. */
|
||||
const head = (tag: number, flags: number, p: Primitive): number[] | null => {
|
||||
let pk = 0;
|
||||
let ps = -1;
|
||||
let more: number[] | null = null;
|
||||
if (!lean) {
|
||||
const r = p as Partial<Record<PickKey, string>>;
|
||||
for (let k = 0; k < PICK_KEYS.length; k++) {
|
||||
const id = r[PICK_KEYS[k]];
|
||||
if (id === undefined) continue;
|
||||
if (pk === 0) {
|
||||
pk = k + 1;
|
||||
ps = str(id);
|
||||
} else (more ??= []).push(k + 1, str(id));
|
||||
}
|
||||
}
|
||||
const o = w.reserve(4);
|
||||
const b = w.buf;
|
||||
b[o] = tag;
|
||||
b[o + 1] = flags | (more ? F_IDS : 0);
|
||||
b[o + 2] = pk;
|
||||
b[o + 3] = ps;
|
||||
return more;
|
||||
};
|
||||
const tail = (more: number[] | null): void => {
|
||||
if (!more) return;
|
||||
w.push(pool.length);
|
||||
w.push(more.length / 2);
|
||||
for (const v of more) pool.push(v);
|
||||
};
|
||||
|
||||
const w = new F64Writer();
|
||||
for (let i = 0; i < prims.length; i++) {
|
||||
const p = prims[i];
|
||||
offsets[i] = w.length;
|
||||
switch (p.kind) {
|
||||
case "polygon": {
|
||||
const fill = color(p.fill);
|
||||
const stroke = color(p.stroke);
|
||||
const more = head(1, styleFlags(p.greyed, p.opacity) | (p.noStrokeEdges ? F_NSE : 0), p);
|
||||
const fill = str(p.fill);
|
||||
const stroke = str(p.stroke);
|
||||
const h = hatch(p.hatch);
|
||||
const o = w.reserve(7);
|
||||
const o = w.reserve(5);
|
||||
const b = w.buf;
|
||||
b[o] = 1;
|
||||
b[o + 1] = style(p.greyed, p.opacity);
|
||||
b[o + 2] = fill;
|
||||
b[o + 3] = stroke;
|
||||
b[o + 4] = p.strokeWidthMm;
|
||||
b[o + 5] = h;
|
||||
b[o + 6] = op(p.opacity);
|
||||
w.pts(p.pts);
|
||||
w.list(p.noStrokeEdges);
|
||||
b[o] = fill;
|
||||
b[o + 1] = stroke;
|
||||
b[o + 2] = p.strokeWidthMm;
|
||||
b[o + 3] = h;
|
||||
b[o + 4] = op(p.opacity);
|
||||
poolPts(p.pts);
|
||||
if (p.noStrokeEdges) poolList(p.noStrokeEdges);
|
||||
tail(more);
|
||||
break;
|
||||
}
|
||||
case "line": {
|
||||
let flags = style(p.greyed, p.opacity);
|
||||
if (isPlainLine(p) && chainsPrev(prims[i - 1], p)) flags |= FLAG_CHAIN;
|
||||
if (p.zigzag) flags |= FLAG_ZIGZAG;
|
||||
if (p.motif) flags |= FLAG_MOTIF;
|
||||
const c = color(p.color);
|
||||
const o = w.reserve(9);
|
||||
let flags = styleFlags(p.greyed, p.opacity) | dashFlags(p.dash);
|
||||
if (isPlainLine(p) && chainsPrev(prims[i - 1], p)) flags |= F_CHAIN;
|
||||
if (p.zigzag) flags |= F_ZIGZAG;
|
||||
if (p.motif) flags |= F_MOTIF;
|
||||
if (p.color !== undefined) flags |= F_COLOR;
|
||||
const more = head(2, flags, p);
|
||||
const cls = lean ? -1 : str(p.cls);
|
||||
const c = str(p.color);
|
||||
const o = w.reserve(8);
|
||||
const b = w.buf;
|
||||
b[o] = 2;
|
||||
b[o + 1] = flags;
|
||||
b[o + 2] = c;
|
||||
b[o + 3] = p.weightMm;
|
||||
b[o + 4] = op(p.opacity);
|
||||
b[o + 5] = p.a.x;
|
||||
b[o + 6] = p.a.y;
|
||||
b[o + 7] = p.b.x;
|
||||
b[o + 8] = p.b.y;
|
||||
w.list(p.dash);
|
||||
b[o] = cls;
|
||||
b[o + 1] = c;
|
||||
b[o + 2] = p.weightMm;
|
||||
b[o + 3] = op(p.opacity);
|
||||
b[o + 4] = p.a.x;
|
||||
b[o + 5] = p.a.y;
|
||||
b[o + 6] = p.b.x;
|
||||
b[o + 7] = p.b.y;
|
||||
if (p.dash) poolList(p.dash);
|
||||
if (p.zigzag) {
|
||||
w.push(p.zigzag.amplitude);
|
||||
w.push(p.zigzag.wavelength);
|
||||
}
|
||||
if (p.motif) {
|
||||
w.push(p.motif.length);
|
||||
w.pts(p.motif.points);
|
||||
poolPts(p.motif.points);
|
||||
}
|
||||
tail(more);
|
||||
break;
|
||||
}
|
||||
case "arc": {
|
||||
const c = color((p as { color?: string }).color);
|
||||
const o = w.reserve(12);
|
||||
const color = (p as { color?: string }).color;
|
||||
const more = head(3, styleFlags(p.greyed, p.opacity) | dashFlags(p.dash) | (color !== undefined ? F_COLOR : 0), p);
|
||||
const cls = lean ? -1 : str(p.cls);
|
||||
const c = str(color);
|
||||
const o = w.reserve(11);
|
||||
const b = w.buf;
|
||||
b[o] = 3;
|
||||
b[o + 1] = style(p.greyed, p.opacity);
|
||||
b[o + 2] = c;
|
||||
b[o + 3] = p.weightMm;
|
||||
b[o + 4] = op(p.opacity);
|
||||
b[o + 5] = p.center.x;
|
||||
b[o + 6] = p.center.y;
|
||||
b[o + 7] = p.from.x;
|
||||
b[o + 8] = p.from.y;
|
||||
b[o + 9] = p.to.x;
|
||||
b[o + 10] = p.to.y;
|
||||
b[o + 11] = p.r;
|
||||
w.list(p.dash);
|
||||
b[o] = cls;
|
||||
b[o + 1] = c;
|
||||
b[o + 2] = p.weightMm;
|
||||
b[o + 3] = op(p.opacity);
|
||||
b[o + 4] = p.center.x;
|
||||
b[o + 5] = p.center.y;
|
||||
b[o + 6] = p.from.x;
|
||||
b[o + 7] = p.from.y;
|
||||
b[o + 8] = p.to.x;
|
||||
b[o + 9] = p.to.y;
|
||||
b[o + 10] = p.r;
|
||||
if (p.dash) poolList(p.dash);
|
||||
tail(more);
|
||||
break;
|
||||
}
|
||||
case "drawingCircle": {
|
||||
const fill = color(p.fill);
|
||||
const stroke = color(p.stroke);
|
||||
const o = w.reserve(9);
|
||||
const more = head(4, styleFlags(p.greyed, p.opacity) | dashFlags(p.dash), p);
|
||||
const fill = str(p.fill);
|
||||
const stroke = str(p.stroke);
|
||||
const o = w.reserve(7);
|
||||
const b = w.buf;
|
||||
b[o] = 4;
|
||||
b[o + 1] = style(p.greyed, p.opacity);
|
||||
b[o + 2] = fill;
|
||||
b[o + 3] = stroke;
|
||||
b[o + 4] = p.weightMm;
|
||||
b[o + 5] = op(p.opacity);
|
||||
b[o + 6] = p.center.x;
|
||||
b[o + 7] = p.center.y;
|
||||
b[o + 8] = p.r;
|
||||
w.list(p.dash);
|
||||
b[o] = fill;
|
||||
b[o + 1] = stroke;
|
||||
b[o + 2] = p.weightMm;
|
||||
b[o + 3] = op(p.opacity);
|
||||
b[o + 4] = p.center.x;
|
||||
b[o + 5] = p.center.y;
|
||||
b[o + 6] = p.r;
|
||||
if (p.dash) poolList(p.dash);
|
||||
tail(more);
|
||||
break;
|
||||
}
|
||||
case "drawingArc": {
|
||||
const stroke = color(p.stroke);
|
||||
const o = w.reserve(10);
|
||||
const more = head(5, styleFlags(p.greyed, p.opacity) | dashFlags(p.dash), p);
|
||||
const stroke = str(p.stroke);
|
||||
const o = w.reserve(8);
|
||||
const b = w.buf;
|
||||
b[o] = 5;
|
||||
b[o + 1] = style(p.greyed, p.opacity);
|
||||
b[o + 2] = stroke;
|
||||
b[o + 3] = p.weightMm;
|
||||
b[o + 4] = op(p.opacity);
|
||||
b[o + 5] = p.center.x;
|
||||
b[o + 6] = p.center.y;
|
||||
b[o + 7] = p.r;
|
||||
b[o + 8] = p.a0;
|
||||
b[o + 9] = p.a1;
|
||||
w.list(p.dash);
|
||||
b[o] = stroke;
|
||||
b[o + 1] = p.weightMm;
|
||||
b[o + 2] = op(p.opacity);
|
||||
b[o + 3] = p.center.x;
|
||||
b[o + 4] = p.center.y;
|
||||
b[o + 5] = p.r;
|
||||
b[o + 6] = p.a0;
|
||||
b[o + 7] = p.a1;
|
||||
if (p.dash) poolList(p.dash);
|
||||
tail(more);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
// Text, Bild …: Platzhalter, damit Indizes/Bereiche gleich bleiben.
|
||||
w.push(0);
|
||||
default: {
|
||||
if (lean) {
|
||||
head(0, 0, p);
|
||||
break;
|
||||
}
|
||||
const tag = p.kind === "text" ? 6 : p.kind === "drawingText" ? 7 : p.kind === "drawingTextPath" ? 8 : 9;
|
||||
head(tag, 0, p);
|
||||
w.push(str(JSON.stringify(p)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const head = 5 + colors.length * 4;
|
||||
const out = new Float64Array(head + hatchW.length + w.length);
|
||||
out[0] = PLAN_BUF_MAGIC;
|
||||
out[1] = PLAN_BUF_VERSION;
|
||||
out[2] = colors.length;
|
||||
out[3] = hatchIdx.size;
|
||||
out[4] = prims.length;
|
||||
for (let i = 0; i < colors.length; i++) out.set(colors[i], 5 + i * 4);
|
||||
out.set(hatchW.buf.subarray(0, hatchW.length), head);
|
||||
out.set(w.buf.subarray(0, w.length), head + hatchW.length);
|
||||
return out;
|
||||
const groups = opts.groups ?? [];
|
||||
const nStrings = strTab.length >> 1;
|
||||
const nF64 = HEAD + strTab.length + hatchW.length + 2 * groups.length + prims.length + w.length + pool.length;
|
||||
const out = new ArrayBuffer(nF64 * 8 + units * 2);
|
||||
const f = new Float64Array(out, 0, nF64);
|
||||
const bounds = opts.bounds;
|
||||
f.set([
|
||||
PLAN_BUF_MAGIC,
|
||||
PLAN_BUF_VERSION,
|
||||
bounds ? 2 : 0,
|
||||
nStrings,
|
||||
hatchIdx.size,
|
||||
hatchW.length,
|
||||
groups.length,
|
||||
prims.length,
|
||||
w.length,
|
||||
pool.length,
|
||||
units,
|
||||
0,
|
||||
bounds ? bounds[0] : 0,
|
||||
bounds ? bounds[1] : 0,
|
||||
bounds ? bounds[2] : 0,
|
||||
bounds ? bounds[3] : 0,
|
||||
]);
|
||||
let k = HEAD;
|
||||
f.set(strTab.buf.subarray(0, strTab.length), k);
|
||||
k += strTab.length;
|
||||
f.set(hatchW.buf.subarray(0, hatchW.length), k);
|
||||
k += hatchW.length;
|
||||
for (const [a, b] of groups) {
|
||||
f[k++] = a;
|
||||
f[k++] = b;
|
||||
}
|
||||
f.set(offsets, k);
|
||||
k += prims.length;
|
||||
f.set(w.buf.subarray(0, w.length), k);
|
||||
k += w.length;
|
||||
f.set(pool.buf.subarray(0, pool.length), k);
|
||||
if (units > 0) {
|
||||
const u = new Uint16Array(out, nF64 * 8, units);
|
||||
let j = 0;
|
||||
for (const s of strParts) for (let c = 0; c < s.length; c++) u[j++] = s.charCodeAt(c);
|
||||
}
|
||||
return new Uint8Array(out);
|
||||
}
|
||||
|
||||
/** Gelesener Plan-Puffer (Kern-Ergebnis); `bytes` bleibt für die GPU-Kompilierung erhalten. */
|
||||
export interface DecodedPlanBuf {
|
||||
bytes: Uint8Array;
|
||||
prims: Primitive[];
|
||||
groups: Array<[number, number]>;
|
||||
bounds?: [number, number, number, number];
|
||||
/** Inhalts-Hash je Primitiv (vom Kern; Schlüssel des GPU-Chunk-Caches) oder null. */
|
||||
hashes: Float64Array | null;
|
||||
/** Nummer des im Kern gehaltenen Puffers (0 = keiner), s. `compilePlanBufRange`. */
|
||||
hold: number;
|
||||
}
|
||||
|
||||
/** UTF-16-Einheiten → ein String (exakt, auch einzelne Surrogate). */
|
||||
function unitsToString(u: Uint16Array): string {
|
||||
let s = "";
|
||||
for (let i = 0; i < u.length; i += 8192) {
|
||||
s += String.fromCharCode.apply(null, u.subarray(i, Math.min(u.length, i + 8192)) as unknown as number[]);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function bad(why: string): never {
|
||||
throw new Error(`Plan-Puffer unlesbar: ${why}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan-Puffer → Primitive (in der JSON-Form, die der Kern früher lieferte: gleiche Felder, gleiche
|
||||
* Reihenfolge). Wirft bei einem Fehlerpuffer des Kerns (mit dessen Meldung) oder kaputtem Puffer.
|
||||
*/
|
||||
export function decodePlanBuf(input: Uint8Array): DecodedPlanBuf {
|
||||
const bytes = input.byteOffset % 8 === 0 ? input : input.slice();
|
||||
if (bytes.byteLength >= 16) {
|
||||
const h = new Float64Array(bytes.buffer, bytes.byteOffset, 2);
|
||||
if (h[0] === PLAN_BUF_ERR_MAGIC) {
|
||||
const n = h[1];
|
||||
throw new Error(unitsToString(new Uint16Array(bytes.buffer, bytes.byteOffset + 16, Math.min(n, (bytes.byteLength - 16) >> 1))));
|
||||
}
|
||||
}
|
||||
if (bytes.byteLength < HEAD * 8) bad("zu kurz");
|
||||
const hd = new Float64Array(bytes.buffer, bytes.byteOffset, HEAD);
|
||||
if (hd[0] !== PLAN_BUF_MAGIC || hd[1] !== PLAN_BUF_VERSION) bad("fremde Version");
|
||||
const [, , flags, nStrings, nHatches, nHatchWords, nGroups, nPrims, nRec, nPool, nUnits] = hd;
|
||||
const hashes = (flags & 1) !== 0;
|
||||
const strAt = HEAD;
|
||||
const hatchAt = strAt + 2 * nStrings;
|
||||
const groupAt = hatchAt + nHatchWords;
|
||||
const offAt = groupAt + 2 * nGroups;
|
||||
const hashAt = offAt + nPrims;
|
||||
const recAt = hashAt + (hashes ? nPrims : 0);
|
||||
const poolAt = recAt + nRec;
|
||||
const nF64 = poolAt + nPool;
|
||||
if (!Number.isInteger(nF64) || bytes.byteLength !== nF64 * 8 + nUnits * 2) bad("Länge");
|
||||
const f = new Float64Array(bytes.buffer, bytes.byteOffset, nF64);
|
||||
const all = unitsToString(new Uint16Array(bytes.buffer, bytes.byteOffset + nF64 * 8, nUnits));
|
||||
const strs: Array<string | undefined> = new Array(nStrings);
|
||||
const S = (i: number): string => {
|
||||
let s = strs[i];
|
||||
if (s === undefined) {
|
||||
const o = f[strAt + 2 * i];
|
||||
s = all.slice(o, o + f[strAt + 2 * i + 1]);
|
||||
strs[i] = s;
|
||||
}
|
||||
return s;
|
||||
};
|
||||
// Schraffuren: einmal je Eintrag aus dem JSON (geteilt von allen Polygonen).
|
||||
const hatchList: HatchRender[] = [];
|
||||
let k = hatchAt;
|
||||
for (let i = 0; i < nHatches; i++) {
|
||||
// [jsonStr, pattern, kind, flags, scale, angle, color, lineWeight, ox, oy, seed, density,
|
||||
// lengthMin, lengthMax, nDash, dash…, (Motiv: length, nPts, x,y…)]
|
||||
const js = f[k];
|
||||
hatchList.push(js >= 0 ? (JSON.parse(S(js)) as HatchRender) : (undefined as unknown as HatchRender));
|
||||
const hf = f[k + 3];
|
||||
k += 15 + f[k + 14];
|
||||
if (hf & 64) k += 2 + 2 * f[k + 1];
|
||||
if (!(k <= groupAt)) bad("Schraffuren");
|
||||
}
|
||||
if (k !== groupAt) bad("Schraffuren");
|
||||
const groups: Array<[number, number]> = [];
|
||||
for (let g = 0; g < nGroups; g++) groups.push([f[groupAt + 2 * g], f[groupAt + 2 * g + 1]]);
|
||||
const pts = (o: number, n: number): Vec2[] => {
|
||||
const out: Vec2[] = new Array(n);
|
||||
const b = poolAt + o;
|
||||
for (let i = 0; i < n; i++) out[i] = { x: f[b + 2 * i], y: f[b + 2 * i + 1] };
|
||||
return out;
|
||||
};
|
||||
const list = (o: number, n: number): number[] => {
|
||||
const out: number[] = new Array(n);
|
||||
const b = poolAt + o;
|
||||
for (let i = 0; i < n; i++) out[i] = f[b + i];
|
||||
return out;
|
||||
};
|
||||
/** Pick-Ids in Art-Reihenfolge (= Feldreihenfolge der Kern-JSON-Form). */
|
||||
const setIds = (o: Record<string, unknown>, pk: number, ps: number, fl: number, tailAt: number): void => {
|
||||
if (!(fl & F_IDS)) {
|
||||
o[PICK_KEYS[pk - 1]] = S(ps);
|
||||
return;
|
||||
}
|
||||
const found: Array<[number, string]> = [[pk, S(ps)]];
|
||||
const po = poolAt + f[tailAt];
|
||||
const n = f[tailAt + 1];
|
||||
for (let j = 0; j < n; j++) found.push([f[po + 2 * j], S(f[po + 2 * j + 1])]);
|
||||
found.sort((a, b) => a[0] - b[0]);
|
||||
for (const [kk, id] of found) o[PICK_KEYS[kk - 1]] = id;
|
||||
};
|
||||
const prims: Primitive[] = new Array(nPrims);
|
||||
for (let i = 0; i < nPrims; i++) {
|
||||
let r = recAt + f[offAt + i];
|
||||
const tag = f[r];
|
||||
const fl = f[r + 1];
|
||||
const pk = f[r + 2];
|
||||
const ps = f[r + 3];
|
||||
r += 4;
|
||||
let o: Record<string, unknown>;
|
||||
switch (tag) {
|
||||
case 1: {
|
||||
o = { kind: "polygon", pts: pts(f[r + 5], f[r + 6]), fill: S(f[r]), stroke: S(f[r + 1]), strokeWidthMm: f[r + 2] };
|
||||
if (f[r + 3] >= 0) o.hatch = hatchList[f[r + 3]];
|
||||
if (fl & F_GREYED_SET) o.greyed = (fl & F_GREYED) !== 0;
|
||||
if (fl & F_OPACITY) o.opacity = f[r + 4];
|
||||
let t = r + 7;
|
||||
if (fl & F_NSE) {
|
||||
o.noStrokeEdges = list(f[t], f[t + 1]);
|
||||
t += 2;
|
||||
}
|
||||
if (pk > 0 || fl & F_IDS) setIds(o, pk, ps, fl, t);
|
||||
break;
|
||||
}
|
||||
case 2: {
|
||||
o = { kind: "line", a: { x: f[r + 4], y: f[r + 5] }, b: { x: f[r + 6], y: f[r + 7] }, cls: S(f[r]), weightMm: f[r + 2] };
|
||||
let t = r + 8;
|
||||
if (fl & F_DASH_NULL) o.dash = null;
|
||||
else if (fl & F_DASH_LIST) {
|
||||
o.dash = list(f[t], f[t + 1]);
|
||||
t += 2;
|
||||
}
|
||||
if (fl & F_ZIGZAG) {
|
||||
o.zigzag = { amplitude: f[t], wavelength: f[t + 1] };
|
||||
t += 2;
|
||||
}
|
||||
if (fl & F_MOTIF) {
|
||||
o.motif = { points: pts(f[t + 1], f[t + 2]), length: f[t] };
|
||||
t += 3;
|
||||
}
|
||||
if (fl & F_COLOR) o.color = S(f[r + 1]);
|
||||
if (pk > 0 || fl & F_IDS) setIds(o, pk, ps, fl, t);
|
||||
if (fl & F_GREYED_SET) o.greyed = (fl & F_GREYED) !== 0;
|
||||
if (fl & F_OPACITY) o.opacity = f[r + 3];
|
||||
break;
|
||||
}
|
||||
case 3: {
|
||||
o = {
|
||||
kind: "arc",
|
||||
center: { x: f[r + 4], y: f[r + 5] },
|
||||
from: { x: f[r + 6], y: f[r + 7] },
|
||||
to: { x: f[r + 8], y: f[r + 9] },
|
||||
r: f[r + 10],
|
||||
cls: S(f[r]),
|
||||
weightMm: f[r + 2],
|
||||
};
|
||||
let t = r + 11;
|
||||
if (fl & F_DASH_NULL) o.dash = null;
|
||||
else if (fl & F_DASH_LIST) {
|
||||
o.dash = list(f[t], f[t + 1]);
|
||||
t += 2;
|
||||
}
|
||||
if (fl & F_COLOR) o.color = S(f[r + 1]);
|
||||
if (pk > 0 || fl & F_IDS) setIds(o, pk, ps, fl, t);
|
||||
if (fl & F_GREYED_SET) o.greyed = (fl & F_GREYED) !== 0;
|
||||
if (fl & F_OPACITY) o.opacity = f[r + 3];
|
||||
break;
|
||||
}
|
||||
case 4: {
|
||||
o = { kind: "drawingCircle", center: { x: f[r + 4], y: f[r + 5] }, r: f[r + 6], fill: S(f[r]), stroke: S(f[r + 1]), weightMm: f[r + 2] };
|
||||
let t = r + 7;
|
||||
if (fl & F_DASH_NULL) o.dash = null;
|
||||
else if (fl & F_DASH_LIST) {
|
||||
o.dash = list(f[t], f[t + 1]);
|
||||
t += 2;
|
||||
}
|
||||
if (pk > 0 || fl & F_IDS) setIds(o, pk, ps, fl, t);
|
||||
if (fl & F_GREYED_SET) o.greyed = (fl & F_GREYED) !== 0;
|
||||
if (fl & F_OPACITY) o.opacity = f[r + 3];
|
||||
break;
|
||||
}
|
||||
case 5: {
|
||||
o = { kind: "drawingArc", center: { x: f[r + 3], y: f[r + 4] }, r: f[r + 5], a0: f[r + 6], a1: f[r + 7], stroke: S(f[r]), weightMm: f[r + 1] };
|
||||
let t = r + 8;
|
||||
if (fl & F_DASH_NULL) o.dash = null;
|
||||
else if (fl & F_DASH_LIST) {
|
||||
o.dash = list(f[t], f[t + 1]);
|
||||
t += 2;
|
||||
}
|
||||
if (pk > 0 || fl & F_IDS) setIds(o, pk, ps, fl, t);
|
||||
if (fl & F_GREYED_SET) o.greyed = (fl & F_GREYED) !== 0;
|
||||
if (fl & F_OPACITY) o.opacity = f[r + 2];
|
||||
break;
|
||||
}
|
||||
case 6:
|
||||
case 7:
|
||||
case 8:
|
||||
case 9:
|
||||
o = JSON.parse(S(f[r])) as Record<string, unknown>;
|
||||
break;
|
||||
default:
|
||||
bad(`Primitiv-Typ ${tag}`);
|
||||
}
|
||||
prims[i] = o as unknown as Primitive;
|
||||
}
|
||||
return {
|
||||
bytes,
|
||||
prims,
|
||||
groups,
|
||||
bounds: flags & 2 ? [hd[12], hd[13], hd[14], hd[15]] : undefined,
|
||||
hashes: hashes ? new Float64Array(bytes.buffer, bytes.byteOffset + hashAt * 8, nPrims) : null,
|
||||
hold: 0,
|
||||
};
|
||||
}
|
||||
+5
-3
@@ -137,11 +137,12 @@ const WALL_LINE_CLS = new Set(["wall-outline", "layer-joint", "layer-joint-l"]);
|
||||
/**
|
||||
* Zieht die Abzugskörper von den Bauteil-Polygonen eines Grundrisses ab (in place).
|
||||
* Wände: wenn der Körper die Schnitthöhe `cutZ` durchdringt. Stützen: ebenso, über ihren
|
||||
* Höhenbereich. Decken: wenn der Körper die Platte durchdringt (Deckendurchbruch).
|
||||
* Höhenbereich. Decken: wenn der Körper die Platte durchdringt (Deckendurchbruch). Liefert, ob
|
||||
* Abzugskörper da waren (dann kann sich die Liste verändert haben).
|
||||
*/
|
||||
export function subtractVoidsInPlan(prims: Primitive[], project: Project, cutZ: number): void {
|
||||
export function subtractVoidsInPlan(prims: Primitive[], project: Project, cutZ: number): boolean {
|
||||
const voids = voidPrisms(project);
|
||||
if (voids.length === 0) return;
|
||||
if (voids.length === 0) return false;
|
||||
const ceilings = new Map((project.ceilings ?? []).map((c) => [c.id, c]));
|
||||
const columns = new Map((project.columns ?? []).map((c) => [c.id, c]));
|
||||
const cuttersFor = (z0: number, z1: number): Pair[][] =>
|
||||
@@ -198,6 +199,7 @@ export function subtractVoidsInPlan(prims: Primitive[], project: Project, cutZ:
|
||||
}
|
||||
prims.length = 0;
|
||||
for (const p of out) prims.push(p);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Schnitt ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -275,6 +275,7 @@ export function useNativePlanRenderer(
|
||||
pxPerMeter > 0 ? Math.round(Math.log2(pxPerMeter)) : -Infinity,
|
||||
plan.greyedRanges,
|
||||
plan.underlay,
|
||||
plan.bufRuns,
|
||||
);
|
||||
} catch (e) {
|
||||
console.warn('Tessellierung fehlgeschlagen:', e);
|
||||
|
||||
Reference in new issue
Block a user