diff --git a/src/core/document.ts b/src/core/document.ts index ea7eb468..7abe7186 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -69,7 +69,17 @@ interface Model3dDeltaCache { } /** Setzt die Teile aus Antwort und gehaltenen Einträgen zusammen; `null`, wenn ein Eintrag fehlt. */ -function assembleModel3dDelta(r: Model3dDelta, cache: Model3dDeltaCache | undefined): { parts: Record; cache: Model3dDeltaCache } | null { +/** Einträge des 3D-Modells mit Laufnummer (Wandkörper bzw. 5 Listen Einbauteile) und Öffnungs-Rest. */ +export interface Model3dKeyed { + wallEntries: (readonly [number, unknown[]])[]; + openingEntries: (readonly [number, unknown[][]])[]; + openingTail: unknown[]; +} + +function assembleModel3dDelta( + r: Model3dDelta, + cache: Model3dDeltaCache | undefined, +): { parts: Record; keyed: Model3dKeyed; cache: Model3dDeltaCache } | null { const wallNew = new Map(r.wallNew); const walls: unknown[] = []; const wallMap = new Map(); @@ -91,8 +101,14 @@ function assembleModel3dDelta(r: Model3dDelta, cache: Model3dDeltaCache | undefi const openingMeshes: unknown[] = []; for (let l = 0; l < 5; l++) for (const e of entries) for (const x of e[l]) openingMeshes.push(x); for (const x of r.openingTail) openingMeshes.push(x); - const { mark, wallKeys: _wk, wallNew: _wn, openingKeys: _ok, openingNew: _on, openingTail: _ot, ...rest } = r; - return { parts: { ...rest, walls, openingMeshes }, cache: { mark, walls: wallMap, openings: openMap } }; + const { mark, wallKeys: _wk, wallNew: _wn, openingKeys: _ok, openingNew: _on, openingTail, ...rest } = r; + // Einträge mit Laufnummer zusätzlich, für den 3D-Viewer (Teil-Updates, `toWalls3d.projectToModel3dParts`). + const keyed: Model3dKeyed = { + wallEntries: r.wallKeys.map((k) => [k, wallMap.get(k)!] as const), + openingEntries: r.openingKeys.map((k) => [k, openMap.get(k)!] as const), + openingTail, + }; + return { parts: { ...rest, walls, openingMeshes }, keyed, cache: { mark, walls: wallMap, openings: openMap } }; } /** Ergebnis des Ladens einer Projektdatei ({@link ProjectDocument.loadFile}). */ @@ -217,6 +233,11 @@ export class ProjectDocument { * Ergebnissen geteilt — nicht verändern. */ model3dParts(args: number[]): T { + return this.model3dPartsKeyed(args).parts; + } + + /** Wie {@link model3dParts}, dazu die Einträge mit Laufnummer (3D-Viewer, Teil-Updates [58]). */ + model3dPartsKeyed(args: number[]): { parts: T; keyed: Model3dKeyed } { const a = [0, 0, 0, 0, 0].map((d, i) => args[i] ?? d); const key = a.join(","); let cache = this.m3d.get(key); @@ -227,7 +248,7 @@ export class ProjectDocument { this.m3d.delete(key); this.m3d.set(key, out.cache); if (this.m3d.size > 4) this.m3d.delete(this.m3d.keys().next().value!); - return out.parts as T; + return { parts: out.parts as T, keyed: out.keyed }; } // Ein Eintrag fehlt (sollte nicht vorkommen): einmal alles neu anfordern. cache = undefined; diff --git a/src/core/index.ts b/src/core/index.ts index e58566a9..dd9c02ec 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -249,8 +249,10 @@ export { explodeFloorOffsets, pickGeometry, projectToModel3d, + projectToModel3dParts, selectionHighlightLines, wallMaterialColorMaps, } from "../plan/toWalls3d"; +export type { Model3dPart } from "../plan/toWalls3d"; export * from "./extra"; diff --git a/src/plan/toWalls3d.ts b/src/plan/toWalls3d.ts index a6f1ae44..ca859ae3 100644 --- a/src/plan/toWalls3d.ts +++ b/src/plan/toWalls3d.ts @@ -43,6 +43,7 @@ import type { Project, Vec2 } from "../model/types"; import type { DetailLevel } from "../model/viewTypes"; import { documentFor } from "../core/document"; +import { coreEpoch } from "../engine/coreWasm"; import type { PickOpening, PickRoof, PickStair, PickContextMesh, PickDrawingSeg } from "./pickTypes"; import { type RMesh, @@ -194,6 +195,93 @@ export function projectToModel3d(project: Project, opts: Model3dOptions = {}): R return model; } +/** + * Ein Teil des 3D-Modells für Teil-Updates im Viewer ([58], render3d `set_parts`). `fixed`: der Inhalt + * zur `id` ändert sich nie (Wand-/Öffnungs-Eintrag des Kern-Caches, Laufnummer in der id) — der Viewer + * schickt ihn nur einmal; sonst entscheidet der Inhalt (Rest-Gruppen: Decken, Dächer, Kontext …). + */ +export interface Model3dPart { + id: string; + fixed: boolean; + walls?: RWall[]; + slabs?: RSlab[]; + meshes?: RMesh[]; + roofLayers?: RModel3d["roofLayers"]; +} + +/** Stabile Nummer je Objekt (truck-Ergebnis der Abzugskörper) für die Teil-id. */ +const objectIds = new WeakMap(); +let nextObjectId = 1; +function objectId(o: object): number { + let id = objectIds.get(o); + if (id === undefined) objectIds.set(o, (id = nextObjectId++)); + return id; +} + +/** + * Das 3D-Modell wie {@link projectToModel3d} (gleiche Wände, Decken, Meshes — nur anders gruppiert), aber + * in Teilen ([58]): je Wand-Eintrag des Kern-Caches (`w…`) und je Öffnungs-Eintrag (`o…`) ein + * unveränderlicher Teil, dazu Rest-Gruppen. `null` mit Explosion (dort kein Cache): dann das ganze Modell. + */ +export function projectToModel3dParts(project: Project, opts: Model3dOptions = {}): Model3dPart[] | null { + const layered = opts.layeredWalls ?? true; + const detail = opts.detail ?? "fein"; + if (explodeGap(opts.explode) > 0) return null; + const voids = !!opts.voids && typeof window !== "undefined"; + const args = [layered ? 1 : 0, DETAIL_CODE[detail] ?? 3, opts.forSection ? 1 : 0, voids ? 1 : 0, 0]; + const { parts, keyed } = documentFor(project).model3dPartsKeyed(args); + const wallEntries = keyed.wallEntries as (readonly [number, RWall[]])[]; + const openingEntries = keyed.openingEntries as (readonly [number, RMesh[][]])[]; + // Abzugskörper wie im vollen Modell (gleiche Reihenfolge, gleicher truck-Cache); danach zuordnen, + // welche Wand/Decke durch welches Netz ersetzt wurde (Netze in Index-Reihenfolge der Schnitte). + const vm: RModel3d = { walls: parts.walls, slabs: parts.slabs, meshes: [], roofLayers: [] }; + const wallMesh = new Map(); + const slabMeshes: RMesh[] = []; + if (parts.voidCuts) { + applyVoids3d(vm, parts.voidCuts); + const keptW = new Set(vm.walls); + const keptS = new Set(vm.slabs); + let mi = 0; + for (const i of parts.voidCuts.walls.map(([i]) => i).sort((a, b) => a - b)) { + if (!keptW.has(parts.walls[i])) wallMesh.set(i, vm.meshes[mi++]); + } + for (const i of parts.voidCuts.slabs.map(([i]) => i).sort((a, b) => a - b)) { + if (!keptS.has(parts.slabs[i])) slabMeshes.push(vm.meshes[mi++]); + } + } + const ns = `${coreEpoch()}.`; + const out: Model3dPart[] = []; + let at = 0; + for (const [k, ws] of wallEntries) { + const start = at; + at += ws.length; + let cut = ""; + const walls: RWall[] = []; + const meshes: RMesh[] = []; + for (let i = start; i < at; i++) { + const m = wallMesh.get(i); + if (m) { + meshes.push(m); + cut += `.${i - start}m${objectId(m)}`; + } else walls.push(parts.walls[i]); + } + out.push(cut ? { id: `w${ns}${k}${cut}`, fixed: true, walls, meshes } : { id: `w${ns}${k}`, fixed: true, walls }); + } + for (const [k, lists] of openingEntries) { + const meshes = lists.flat(); + if (meshes.length) out.push({ id: `o${ns}${k}`, fixed: true, meshes }); + } + const rest = (id: string, p: Omit) => out.push({ id, fixed: false, ...p }); + rest("slabs", { slabs: vm.slabs, meshes: slabMeshes }); + rest("context", { meshes: parts.contextMeshes }); + rest("extrusions", { meshes: emitExtrudedSolids(project, parts.floorOffsets) }); + rest("columns", { meshes: parts.columnMeshes }); + rest("openingTail", { meshes: keyed.openingTail as RMesh[] }); + rest("stairs", { meshes: [...parts.stairMeshes, ...parts.stairRailings] }); + rest("roofs", { meshes: parts.roofMeshes, roofLayers: parts.roofLayers }); + return out; +} + /** Teile des 3D-Modells aus dem Kern (`model3d::Parts`). */ interface Model3dParts { walls: RWall[]; diff --git a/src/viewport/model3dPartsSync.test.ts b/src/viewport/model3dPartsSync.test.ts new file mode 100644 index 00000000..8e60c776 --- /dev/null +++ b/src/viewport/model3dPartsSync.test.ts @@ -0,0 +1,72 @@ +/** + * [58] Teil-Updates des 3D-Viewers: `projectToModel3dParts` enthält dasselbe wie `projectToModel3d`, und + * `Model3dPartsSync` schickt nach einer Wand-Änderung nur deren Teile (plus die Entfernung der alten). + */ +import { describe, it, expect } from "vitest"; +import { sampleProject } from "../model/sampleProject"; +import type { Project } from "../model/types"; +import { withDocument } from "../core/document"; +import { patchItem } from "../core/opsBuild"; +import { projectToModel3d, projectToModel3dParts, type Model3dPart } from "../core"; +import { Model3dPartsSync } from "./model3dPartsSync"; + +/** Inhalt als sortierte JSON-Liste je Feld (Reihenfolge der Teile egal). */ +function bag(m: { walls?: unknown[]; slabs?: unknown[]; meshes?: unknown[]; roofLayers?: unknown[] }[]) { + const out: Record = { walls: [], slabs: [], meshes: [], roofLayers: [] }; + for (const p of m) for (const k of Object.keys(out)) for (const x of (p as Record)[k] ?? []) out[k].push(JSON.stringify(x)); + for (const k of Object.keys(out)) out[k].sort(); + return out; +} + +describe("3D-Viewer Teil-Updates", () => { + it("Teile = ganzes Modell; nach 1 Wand-Änderung reist nur diese", () => { + let cur: Project = structuredClone(sampleProject); + withDocument(cur, (doc) => { + const parts = projectToModel3dParts(cur)!; + expect(parts).not.toBeNull(); + expect(bag(parts)).toEqual(bag([projectToModel3d(cur)])); + expect(new Set(parts.map((p) => p.id)).size).toBe(parts.length); + + const sync = new Model3dPartsSync(); + const first = sync.diff(parts)!; + expect(first.reset).toBe(true); + expect(first.upserted).toBe(parts.length); + const msg = JSON.parse(first.json) as { upsert: { id: string }[] }; + expect(msg.upsert.map((u) => u.id)).toEqual(parts.map((p) => p.id)); + expect(sync.diff(projectToModel3dParts(cur)!)).toBeNull(); + + const w = cur.walls[3]; + const r = doc.commit(cur, patchItem(cur, "walls", w.id, { height: (w.height ?? 2.6) + 0.2 }), undefined, Date.now()); + if (!("project" in r)) throw new Error(r.problems.join("; ")); + cur = r.project; + const after = projectToModel3dParts(cur)!; + expect(bag(after)).toEqual(bag([projectToModel3d(cur)])); + const d = sync.diff(after)!; + expect(d.reset).toBe(false); + // Die Wand (ggf. mit Nachbarn über Verschneidung) und ihre Öffnungs-Einbauteile; keine Rest-Gruppe. + expect(d.upserted).toBeGreaterThan(0); + expect(d.upserted).toBeLessThanOrEqual(6); + expect(d.removed).toBe(d.upserted); + const ids = (JSON.parse(d.json) as { upsert: { id: string }[] }).upsert.map((u) => u.id); + expect(ids.every((id) => /^[wo]/.test(id))).toBe(true); + }); + }); + + it("Rest-Gruppen nach Inhalt, unveränderliche Teile nach id; Entfernen; Reset", () => { + const sync = new Model3dPartsSync(); + const wall = { start: [0, 0], end: [1, 0], thickness: 0.2, height: 3 } as unknown as NonNullable[number]; + const a: Model3dPart[] = [ + { id: "w1", fixed: true, walls: [wall] }, + { id: "slabs", fixed: false, slabs: [] }, + ]; + expect(sync.diff(a)!.upserted).toBe(2); + // Gleiche id eines unveränderlichen Teils: nicht nochmals, auch mit anderem Objekt. + expect(sync.diff([{ ...a[0], walls: [{ ...wall }] }, a[1]])).toBeNull(); + const d = sync.diff([a[0], { id: "slabs", fixed: false, meshes: [] }])!; + expect(JSON.parse(d.json)).toEqual({ reset: false, remove: [], upsert: [{ id: "slabs", meshes: [] }] }); + const e = sync.diff([{ id: "w2", fixed: true, walls: [wall] }])!; + expect(JSON.parse(e.json)).toEqual({ reset: false, remove: ["w1", "slabs"], upsert: [{ id: "w2", walls: [wall] }] }); + sync.reset(); + expect(JSON.parse(sync.diff([{ id: "w2", fixed: true }])!.json)).toEqual({ reset: true, remove: [], upsert: [{ id: "w2" }] }); + }); +}); diff --git a/src/viewport/model3dPartsSync.ts b/src/viewport/model3dPartsSync.ts new file mode 100644 index 00000000..da73c1d4 --- /dev/null +++ b/src/viewport/model3dPartsSync.ts @@ -0,0 +1,57 @@ +/** + * Teil-Updates des 3D-Modells für render3d ([58], `web::set_parts`): merkt, welche Teile der Viewer schon + * hat, und schreibt nur neue, geänderte und entfernte Teile als JSON. Unveränderliche Teile (`fixed`, + * Wand-/Öffnungs-Einträge des Kern-Caches mit Laufnummer in der id) reisen genau einmal; Rest-Gruppen + * (Decken, Dächer, Kontext …) werden über ihren JSON-Text verglichen. + */ + +import type { Model3dPart } from "../core"; + +/** Ergebnis von {@link Model3dPartsSync.diff}: JSON für `set_parts` und Zahlen für Messung/Tests. */ +export interface PartsDiff { + json: string; + upserted: number; + removed: number; + reset: boolean; +} + +export class Model3dPartsSync { + /** id → JSON-Text des Inhalts (Rest-Gruppen) bzw. `true` (unveränderlich). */ + private sent: Map | null = null; + + /** Vergessen, was der Viewer hat (neuer Renderer, Vollaufbau über `set_model`): nächstes Mal `reset`. */ + reset(): void { + this.sent = null; + } + + /** Änderung gegenüber dem zuletzt Geschickten; `null`, wenn sich nichts geändert hat. */ + diff(parts: Model3dPart[]): PartsDiff | null { + const reset = this.sent === null; + const prev = this.sent ?? new Map(); + const next = new Map(); + const upserts: string[] = []; + for (const p of parts) { + if (next.has(p.id)) continue; + const { id, fixed, ...content } = p; + if (fixed) { + next.set(id, true); + if (prev.get(id) !== true) upserts.push(withId(id, JSON.stringify(content))); + } else { + const body = JSON.stringify(content); + next.set(id, body); + if (prev.get(id) !== body) upserts.push(withId(id, body)); + } + } + const removed: string[] = []; + if (!reset) for (const id of prev.keys()) if (!next.has(id)) removed.push(id); + this.sent = next; + if (!reset && upserts.length === 0 && removed.length === 0) return null; + const json = `{"reset":${reset},"remove":${JSON.stringify(removed)},"upsert":[${upserts.join(",")}]}`; + return { json, upserted: upserts.length, removed: removed.length, reset }; + } +} + +/** `{"id":…, …Inhalt}` aus dem JSON-Text des Inhalts (ein Objekt). */ +function withId(id: string, body: string): string { + return body === "{}" ? `{"id":${JSON.stringify(id)}}` : `{"id":${JSON.stringify(id)},${body.slice(1)}`; +} diff --git a/src/viewport/useWasm3dRenderer.ts b/src/viewport/useWasm3dRenderer.ts index cf8469b1..c70acafa 100644 --- a/src/viewport/useWasm3dRenderer.ts +++ b/src/viewport/useWasm3dRenderer.ts @@ -7,9 +7,10 @@ * in Rust (src-tauri/render3d, Feature `web`) — dieselbe Extrusion/Pipeline * wie das native wgpu-Fenster. * - * Modell-Sync: `updateModel(project)` flacht das Projekt über - * {@link projectToModel3d} (Wände mit Öffnungs-Teilquadern + Deckenplatten) - * und schiebt es als JSON an `set_model` — exakt dasselbe Format wie der + * Modell-Sync: `updateModel(project)` holt das Modell in Teilen + * ({@link projectToModel3dParts}, je Wand-/Öffnungs-Eintrag des Kern-Caches plus Rest-Gruppen) und + * schickt nur Geändertes an `set_parts` ([58]); mit Explosion das ganze Modell + * ({@link projectToModel3d}) als JSON an `set_model` — dasselbe Format wie der * native Tauri-Push (nativeSync.ts). * * Fällt bei fehlendem WebGPU oder Init-Fehler auf `ready:false` + `failed:true` @@ -18,7 +19,8 @@ import { useCallback, useEffect, useRef, useState } from "react"; import type { ContextImage, Project } from "../model/types"; -import { emitDrawingLineVerts, emitSurfacePatternLines, projectToModel3d, siteEnvelope3d } from "../core"; +import { emitDrawingLineVerts, emitSurfacePatternLines, projectToModel3d, projectToModel3dParts, siteEnvelope3d } from "../core"; +import { Model3dPartsSync } from "./model3dPartsSync"; import type { DetailLevel } from "../model/viewTypes"; import { loadEngine3d } from "../engine/engine3d"; import { decodeMaterialTextures } from "./materialTextures"; @@ -42,6 +44,9 @@ export interface Camera3d { /** Minimal-Typ des WASM-Exports (das echte .d.ts entsteht erst mit `build:engine3d`). */ interface WebModelRendererLike { set_model(json: string): void; + /** Teil-Update ([58], `web::set_parts`): `{ reset?, remove?, upsert? }`, s. `model3dPartsSync.ts`. + * Optional — ältere WASM-Builds. */ + set_parts?(json: string): number; /** Darstellungsart setzen — `style` ∈ "shaded"|"white"|"wireframe"|"hidden"| * "textured" (deckt die volle `RenderMode`-Union der Oberleiste ab; * "textured" faellt engine-seitig vorerst auf "shaded" zurueck). */ @@ -183,6 +188,35 @@ function getRenderer(canvas: HTMLCanvasElement): Promise { return p; } +/** Was jeder Renderer schon an Modell-Teilen hat ([58]). */ +const partsSyncs = new WeakMap(); + +/** + * Modell an den Renderer: ohne Explosion als Teil-Update (nur geänderte Wände/Öffnungen/Gruppen reisen + * und werden in render3d neu vernetzt und hochgeladen), sonst bzw. bei älteren WASM-Builds und nach + * einem Fehler das ganze Modell über `set_model`. + */ +function syncModel3d(r: WebModelRendererLike, project: Project, detail: DetailLevel | undefined, explode: number): void { + let sync = partsSyncs.get(r); + if (!sync) partsSyncs.set(r, (sync = new Model3dPartsSync())); + try { + const parts = typeof r.set_parts === "function" ? projectToModel3dParts(project, { detail, voids: true, explode }) : null; + if (parts) { + const d = sync.diff(parts); + if (d) r.set_parts!(d.json); + return; + } + } catch (e) { + console.warn("render3d set_parts fehlgeschlagen, ganzes Modell:", e); + } + sync.reset(); + try { + r.set_model(JSON.stringify(projectToModel3d(project, { detail, voids: true, explode }))); + } catch (e) { + console.warn("render3d set_model fehlgeschlagen:", e); + } +} + export function useWasm3dRenderer( canvasRef: React.RefObject, enabled: boolean, @@ -236,11 +270,7 @@ export function useWasm3dRenderer( const updateModel = useCallback((project: Project, detail?: DetailLevel, explode = 0) => { const r = rendererRef.current; if (!r || !project) return; - try { - r.set_model(JSON.stringify(projectToModel3d(project, { detail, voids: true, explode }))); - } catch (e) { - console.warn("render3d set_model fehlgeschlagen:", e); - } + syncModel3d(r, project, detail, explode); // 2D-Boden-Spuren als eigener BINÄRER LineList-Kanal — bewusst NICHT Teil // des JSON-Modells oben: ein Kataster-DXF (Mio. Segmente) sprengt als // Ribbon-Meshes im JSON die String-Längengrenze komplett (Nutzer-Report