diff --git a/TODO.md b/TODO.md index f0d07e68..d69cdec4 100644 --- a/TODO.md +++ b/TODO.md @@ -131,6 +131,9 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern treffende Schneider, Verschmelzen ohne Neustart über alle Paare, Monolith-Umriss per Bereichs-Malen; Öffnungen je Wand einmal indiziert; Zahlen-Nachbildung mit Schnellweg. Messung (Node/WASM, Min., Kacheln des Beispielhauses mit Treppen): Schnitt 6×6 10,2 s → 0,10 s, 8×8 33 s → 0,19 s, 16×16 0,8 s (alt nicht messbar, > 1 min); Ansicht 8×8 107 → 29 ms. + Der Kern merkt sich die zuletzt vorbereiteten Schnitte (Schlüssel je `computeSection`): Schwarz-Weiss/Sichtbarkeit + umschalten 8×8 ~1 ms statt Neurechnen. Offen: Szene mit vielen verdeckten (gestrichelten) Kanten bleibt teuer + (16×16 mit verdeckten Kanten ~2,5 s, Strichmuster-Zerlegung in `plan_scene`). Rest in TS (28.10.): Stil-Auflösung (Bauteil, Schraffur, Farbe, Linienstil, Pick-IDs, Painter-Reihenfolge) in `generatePlan*.ts`, `toSection.ts` (Besitzer-Zuordnung, Schichtbänder), `toElevation.ts` (Orchestrierung), `sectionOpenings.ts`, `planUnderlay.ts`, `drawing2d.ts`. Das ist kein Rechenanteil mehr, sondern liest das Modell; es zieht mit [K4] um. diff --git a/src-tauri/core/src/plan/section.rs b/src-tauri/core/src/plan/section.rs index 90f40ac3..64cc7242 100644 --- a/src-tauri/core/src/plan/section.rs +++ b/src-tauri/core/src/plan/section.rs @@ -1571,7 +1571,43 @@ pub fn section_opening_primitives(p: &Project, level: &LevelSpec, vis: &Visibili // ── Abfrage ─────────────────────────────────────────────────────────────────── -/// Abfrage `sectionPlan`: `args` = `[mono, openings, bodies…]` (Körper s. [`read_bodies`]), +/// Zuletzt berechnete Schnitte je Schlüssel (> 0), wenige, älteste fallen weg. +const CACHE_SLOTS: usize = 6; + +thread_local! { + static CACHE: std::cell::RefCell)>> = const { std::cell::RefCell::new(Vec::new()) }; +} + +fn cache_get(key: f64) -> Option> { + if !(key > 0.0) { + return None; + } + CACHE.with(|c| { + let mut c = c.borrow_mut(); + let i = c.iter().position(|e| e.0 == key)?; + let e = c.remove(i); + let o = e.1.clone(); + c.push(e); + Some(o) + }) +} + +fn cache_put(key: f64, o: std::rc::Rc) { + if !(key > 0.0) { + return; + } + CACHE.with(|c| { + let mut c = c.borrow_mut(); + c.retain(|e| e.0 != key); + if c.len() >= CACHE_SLOTS { + c.remove(0); + } + c.push((key, o)); + }); +} + +/// Abfrage `sectionPlan`: `args` = `[mono, openings, key, bodies…]` (Körper s. [`read_bodies`]; `key` > 0 +/// = Schlüssel des vorbereiteten Schnitts, s. Cache unten, 0 = immer rechnen), /// `text` = `{"level": {...}, "hiddenLines", "hasVis", "invisible", "hasDisplay", "norender", "grey"}`. /// Puffer: Gruppe 0 Schnitt, Gruppe 1 geschnittene Öffnungen; Ausmass ohne die Öffnungen. /// Ohne gültige Schnittlinie: leerer Puffer ohne Gruppen. @@ -1581,9 +1617,21 @@ pub fn section_plan_buf(p: &Project, args: &[f64], text: &str) -> Result let vis = Visibility::from_json(&v); let mono = args.first().is_some_and(|&x| x != 0.0); let openings = args.get(1).is_some_and(|&x| x != 0.0); - let bodies = read_bodies(args.get(2..).unwrap_or(&[])).ok_or("Schnitt: Körper-Netze unlesbar")?; + let key = args.get(2).copied().unwrap_or(0.0); let mut w = crate::plan_buf::Writer::new(true); - let Some(out) = compute_section(p, &level, &bodies)? else { return Ok(w.finish()) }; + // Der Schnitt selbst hängt nur am Projektstand, an der Ebene und den Körpern (= ein Aufruf von + // `computeSection` in TS, Schlüssel `key`); Schwarz-Weiss, Sichtbarkeit und verdeckte Kanten nur an + // der Darstellung. Darum die zuletzt berechneten Schnitte merken (Umschalten ohne Neurechnen). + let out = match cache_get(key) { + Some(o) => o, + None => { + let bodies = read_bodies(args.get(3..).unwrap_or(&[])).ok_or("Schnitt: Körper-Netze unlesbar")?; + let Some(o) = compute_section(p, &level, &bodies)? else { return Ok(w.finish()) }; + let o = std::rc::Rc::new(o); + cache_put(key, o.clone()); + o + } + }; let hidden = v.get("hiddenLines").and_then(|b| b.as_bool()).unwrap_or(false); let (prims, bounds) = section_primitives(&out, mono, hidden, &vis); w.group(&prims); @@ -1658,7 +1706,7 @@ mod tests { fn puffer_hat_zwei_gruppen() { let p = sample(); let text = serde_json::json!({ "level": serde_json::to_value(p.drawing_levels.iter().find(|l| l.id == "schnitt-a").unwrap()).unwrap() }).to_string(); - let buf = section_plan_buf(&p, &[0.0, 1.0, 0.0], &text).unwrap(); + let buf = section_plan_buf(&p, &[0.0, 1.0, 0.0, 0.0], &text).unwrap(); let (prims, groups, bounds) = crate::plan_buf::decode(&buf).unwrap(); assert_eq!(groups.len(), 2); assert!(bounds.is_some() && !prims.is_empty()); @@ -1701,7 +1749,7 @@ mod bench { let t_cut = t.elapsed(); let t = Instant::now(); let buf = if l.kind == DrawingLevelKind::Section { - section_plan_buf(&p, &[0.0, 1.0, 0.0], &serde_json::json!({ "level": serde_json::to_value(l).unwrap() }).to_string()).unwrap() + section_plan_buf(&p, &[0.0, 1.0, 0.0, 0.0], &serde_json::json!({ "level": serde_json::to_value(l).unwrap() }).to_string()).unwrap() } else { crate::plan::elevation::elevation_plan_buf(&p, &[0.0, 0.0], &serde_json::json!({ "level": serde_json::to_value(l).unwrap() }).to_string()).unwrap() }; diff --git a/src/plan/sectionBench.test.ts b/src/plan/sectionBench.test.ts index 1c2308e4..f212697c 100644 --- a/src/plan/sectionBench.test.ts +++ b/src/plan/sectionBench.test.ts @@ -51,7 +51,11 @@ it.skipIf(!process.env.BENCH)("Messung Schnitt/Ansicht alt gegen neu", async () const b = await time(newP, runs); const c = skipOld ? ([NaN, NaN] as [number, number]) : await time(async () => planToRenderScene(await oldP(), 100), runs); const d = await time(async () => planToRenderScene(await newP(), 100), runs); - rows.push(`${name} | ${l.id} Schnitt | ${fmt(a)} | ${fmt(b)} | ${fmt(c)} | ${fmt(d)}`); + // Umschalten (Schwarz-Weiss) auf einem vorbereiteten Schnitt: der Kern rechnet nicht neu. + const prepared = (await newCompute(p, l))!; + let flip = false; + const e = await time(() => newGen(prepared, (flip = !flip), { hiddenLines: l.hiddenLines, visibleCodes: codes, openings: true }), runs); + rows.push(`${name} | ${l.id} Schnitt | ${fmt(a)} | ${fmt(b)} | ${fmt(c)} | ${fmt(d)} | Umschalten ${fmt(e)}`); process.stderr.write(rows[rows.length - 1] + "\n"); } else { const skipOld = !!process.env.BENCH_NEW_ONLY; diff --git a/src/plan/sectionCore.ts b/src/plan/sectionCore.ts index 335c541a..e934f676 100644 --- a/src/plan/sectionCore.ts +++ b/src/plan/sectionCore.ts @@ -16,11 +16,15 @@ import type { CategoryDisplayResolver, Plan } from "./generatePlan"; export interface SectionOutput { project: Project; level: DrawingLevel; - /** `[mono, openings, n, (index, nPos, pos…, nIdx, idx…) × n]`: Platz für die zwei Schalter, dann die - * geschnittenen freien Körper. */ + /** `[mono, openings, key, n, (index, nPos, pos…, nIdx, idx…) × n]`: Platz für die zwei Schalter, der + * Schlüssel dieses Schnitts (der Kern merkt sich die zuletzt berechneten, Umschalten von Darstellung + * oder Sichtbarkeit rechnet nicht neu), dann die geschnittenen freien Körper. */ bodies: Float64Array; } +/** Schlüssel der vorbereiteten Schnitte (s. `SectionOutput.bodies`). */ +let sectionKey = 0; + /** Ob die Ebene eine gültige Schnittlinie trägt (wie `sectionPlaneFromLevel`). */ function hasLine(level: DrawingLevel): boolean { const line = level.linePoints; @@ -39,7 +43,7 @@ function isVoid(s: NonNullable[number]): boolean { */ export async function computeSection(project: Project, level: DrawingLevel): Promise { if (!hasLine(level)) return null; - const bodies: number[] = [0, 0, 0]; + const bodies: number[] = [0, 0, ++sectionKey, 0]; const solids = project.extrudedSolids ?? []; for (let index = 0; index < solids.length; index++) { const solid = solids[index]; @@ -62,7 +66,7 @@ export async function computeSection(project: Project, level: DrawingLevel): Pro for (let i = 0; i < mesh.positions.length; i++) bodies.push(mesh.positions[i]); bodies.push(mesh.indices.length); for (let i = 0; i < mesh.indices.length; i++) bodies.push(mesh.indices[i]); - bodies[2]++; + bodies[3]++; } return { project, level, bodies: Float64Array.from(bodies) }; } diff --git a/src/plan/sectionPort.parity.test.ts b/src/plan/sectionPort.parity.test.ts index 92ceae56..5fc960fc 100644 --- a/src/plan/sectionPort.parity.test.ts +++ b/src/plan/sectionPort.parity.test.ts @@ -82,12 +82,19 @@ async function oldPlan(project: Project, level: DrawingLevel, o: Opts): Promise< } async function newPlan(project: Project, level: DrawingLevel, o: Opts): Promise<{ prims: Primitive[]; bounds: Plan["bounds"]; plan: Plan } | null> { - const out = await newCompute(project, level); + // Ein vorbereiteter Schnitt je Ebene für alle Optionssätze: prüft auch den Kern-Cache (Umschalten). + let out = prepared.get(level); + if (out === undefined || out?.project !== project) { + out = await newCompute(project, level); + prepared.set(level, out); + } if (!out) return null; const plan = newGen(out, o.mono, o); return { prims: plan.primitives, bounds: plan.bounds, plan }; } +const prepared = new WeakMap>>(); + /** Szene (render2d) und SVG wie die Verbraucher: alt als gewöhnlicher Plan, neu aus dem Puffer. */ function outputsDiffer(a: { prims: Primitive[]; raw: Primitive[]; bounds: Plan["bounds"] }, b: Plan): string | null { const sa = JSON.stringify(planToRenderScene({ primitives: a.prims, bounds: a.bounds }, 100));