Desktop app for designing parametric 3D models in CadQuery together with the coding agent of your choice
TypeScript 3d-modeling3d-printing3d-printing-toolsagentagentic-aiai-cadcadcadqueryclaude-codecodexelectronfemllmmacdmakeropencodeparametric-designpythonsteptext-to-cad
App: Messen im Viewer (E9, E22)
Kai-Jungsthoefele11253879e47
diff --git a/app/package.json b/app/package.jsonindex 5db5118..7c11339 100644--- a/app/package.json+++ b/app/package.json@@ -11,8 +11,9 @@"test:smoke": "npm run build && node test/smoke.mjs","test:versions": "npm run build && node test/versions.mjs","test:editor": "npm run build && node test/editor.mjs",+ "test:measure": "npm run build && node test/measure.mjs","test:unit": "node test/unit.mjs",- "test": "npm run build && node test/unit.mjs && node test/smoke.mjs && node test/versions.mjs && node test/editor.mjs"+ "test": "npm run build && node test/unit.mjs && node test/smoke.mjs && node test/versions.mjs && node test/editor.mjs && node test/measure.mjs"},"dependencies": {"@codemirror/autocomplete": "^6.20.3",diff --git a/app/resources/template/.gitignore b/app/resources/template/.gitignoreindex c504aec..8117328 100644--- a/app/resources/template/.gitignore+++ b/app/resources/template/.gitignore@@ -11,3 +11,4 @@ __pycache__/.cadide/build.json.cadide/zip-info.json.cadide/feedback/+.cadide/geometry/diff --git a/app/src/main/git.ts b/app/src/main/git.tsindex ed4c3ef..57f0a35 100644--- a/app/src/main/git.ts+++ b/app/src/main/git.ts@@ -16,8 +16,12 @@ const APP_SUBJECT = /^(Neues Modell angelegt|Automatischer Snapshot beim Speiche/** Gilt für jeden Aufruf: UTF-8-Pfade lesbar, keine Zeilenenden-Umwandlung (ZIPs wandern zwischen Systemen). */const COMMON = ['-c', 'core.quotepath=false', '-c', 'core.autocrlf=false'];-/** `output/` zählt nicht als Änderung: STEP-Dateien sind nicht byte-stabil (Zeitstempel, teils Reihenfolge). */-const NOT_OUTPUT = ['--', '.', ':(exclude)output'];+/**+ * `output/` zählt nicht als Änderung: STEP-Dateien sind nicht byte-stabil (Zeitstempel, teils Reihenfolge).+ * `.cadide/geometry/` (Geometrie für das Messen) ist ein Zwischenergebnis. Ältere Projekte haben es noch nicht in der+ * .gitignore, deshalb klammert die App es selbst aus, beim Status und beim Hinzufügen (siehe addAll).+ */+const NOT_OUTPUT = ['--', '.', ':(exclude)output', ':(exclude).cadide/geometry'];const HASH = /^[0-9a-f]{7,40}$/;const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));@@ -47,6 +51,15 @@ export class GitRepo {}}+ /**+ * Alles vormerken außer `.cadide/geometry/`. Ein Ausschluss im Pfad (`:(exclude)…`) ginge nicht: Steht der Ordner in+ * der .gitignore (neue Projekte), bricht `git add` dann mit Fehler ab. Deshalb danach aus dem Index nehmen, was dort liegt.+ */+ private async addAll(): Promise<void> {+ await this.mustRun(['add', '-A'], true);+ await this.mustRun(['rm', '-r', '--cached', '--ignore-unmatch', '-q', '--', '.cadide/geometry'], true);+ }+private async mustRun(args: string[], write = false): Promise<string> {const r = await this.run(args, write);if (!r.ok) throw new Error(`git ${args[0]} fehlgeschlagen: ${(r.err || r.out).trim().slice(0, 400)}`);@@ -74,7 +87,7 @@ export class GitRepo {const email = await this.run(['config', 'user.email']);if (!name.out.trim()) await this.mustRun(['config', '--local', 'user.name', 'CAD-IDE'], true);if (!email.out.trim()) await this.mustRun(['config', '--local', 'user.email', 'cadide@localhost'], true);- await this.mustRun(['add', '-A'], true);+ await this.addAll();await this.mustRun(['commit', '--allow-empty', '--no-verify', '-m', message, ...APP_TRAILER], true);return (await this.mustRun(['rev-parse', 'HEAD'])).trim();});@@ -95,7 +108,7 @@ export class GitRepo {async snapshot(message: string): Promise<string | null> {return this.serial(async () => {if (!(await this.status()).dirty) return null;- await this.mustRun(['add', '-A'], true);+ await this.addAll();await this.mustRun(['commit', '--no-verify', '-m', message, ...APP_TRAILER], true);return (await this.mustRun(['rev-parse', 'HEAD'])).trim();});@@ -144,7 +157,7 @@ export class GitRepo {let safety: string | null = null;if ((await this.status()).dirty) {- await this.mustRun(['add', '-A'], true);+ await this.addAll();await this.mustRun(['commit', '--no-verify', '-m', 'Sicherung vor Wiederherstellung', ...APP_TRAILER], true);safety = (await this.mustRun(['rev-parse', 'HEAD'])).trim();}@@ -154,7 +167,7 @@ export class GitRepo {if (!target.has(f)) fs.rmSync(resolveInside(this.dir, f), { force: true });}await this.mustRun(['restore', `--source=${hash}`, '--staged', '--worktree', '--', '.'], true);- await this.mustRun(['add', '-A'], true);+ await this.addAll();const diff = await this.run(['diff', '--cached', '--quiet']);if (diff.ok) return { commit: null, safety }; // Stand war schon identischawait this.mustRun(['commit', '--no-verify', '-m', `Stand wiederhergestellt: ${subject} (${short})`, ...APP_TRAILER], true);diff --git a/app/src/main/main.ts b/app/src/main/main.tsindex 2dafaa6..0db5d29 100644--- a/app/src/main/main.ts+++ b/app/src/main/main.ts@@ -76,6 +76,7 @@ function registerIpc(ctl: ProjectController): void {ipcMain.on('term:kill', (_e, id: number) => ctl.session?.terminals.kill(id));ipcMain.handle('agents:detect', () => detectAgents(terminalEnv(dir())));+ ipcMain.handle('measure:query', (_e, source: unknown, req: unknown) => ctl.measure(source, req));// Rückfragen aus dem Renderer (etwa ungespeicherte Eingaben im Editor) laufen über dieselben Dialoge wie im HauptprozessipcMain.handle('dialog:choose', (_e, o: { title?: unknown; message?: unknown; detail?: unknown; buttons?: unknown }) => {const buttons = Array.isArray(o?.buttons) ? o.buttons.slice(0, 4).map(String) : [];diff --git a/app/src/main/measure.ts b/app/src/main/measure.tsnew file mode 100644index 0000000..4e7aa27--- /dev/null+++ b/app/src/main/measure.ts@@ -0,0 +1,90 @@+import { spawn, type ChildProcess } from 'node:child_process';+import type { MeasureRequest, MeasureResponse } from '../shared/types';+import { pythonExe } from './paths';++const START_TIMEOUT_MS = 60_000; // cadquery zu laden dauert beim ersten Mal einige Sekunden+const REQUEST_TIMEOUT_MS = 30_000;++interface Pending { resolve: (r: MeasureResponse) => void; timer: NodeJS.Timeout }++/**+ * Langlebiger Python-Dienst pro Projekt für exakte Messungen (E24): `python -m cadide serve`, JSON-Zeilen über+ * stdin/stdout. Er startet erst bei der ersten Messung (cadquery zu laden kostet Sekunden) und bleibt dann offen.+ * Stürzt er ab, gilt die laufende Anfrage als fehlgeschlagen, die nächste startet ihn neu. Fehler sind Ergebnisse,+ * keine Ausnahmen: Die Oberfläche zeigt sie an.+ */+export class MeasureService {+ private proc: ChildProcess | null = null;+ private ready: Promise<void> | null = null;+ private pending = new Map<number, Pending>();+ private seq = 0;+ private buf = '';+ private disposed = false;++ constructor(private readonly cwd: string) {}++ async request(folder: string, req: MeasureRequest): Promise<MeasureResponse> {+ if (this.disposed) return { ok: false, error: 'Das Modell ist geschlossen.' };+ try { await this.start(); } catch (e) { return { ok: false, error: `Der Messdienst ließ sich nicht starten: ${e instanceof Error ? e.message : String(e)}` }; }+ const proc = this.proc;+ if (!proc?.stdin) return { ok: false, error: 'Der Messdienst läuft nicht.' };+ const id = ++this.seq;+ return new Promise((resolve) => {+ const timer = setTimeout(() => { this.pending.delete(id); resolve({ ok: false, error: 'Der Messdienst antwortet nicht (Zeitlimit).' }); }, REQUEST_TIMEOUT_MS);+ this.pending.set(id, { resolve, timer });+ proc.stdin!.write(JSON.stringify({ ...req, id, folder }) + '\n');+ });+ }++ stop(): void {+ this.disposed = true;+ this.proc?.kill();+ this.fail('Das Modell ist geschlossen.');+ }++ private start(): Promise<void> {+ if (this.proc && this.ready) return this.ready;+ this.buf = '';+ const child = spawn(pythonExe(), ['-m', 'cadide', 'serve'], {+ cwd: this.cwd, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'],+ env: { ...process.env, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8', PYTHONUNBUFFERED: '1' },+ });+ this.proc = child;+ let err = '';+ this.ready = new Promise<void>((resolve, reject) => {+ const timer = setTimeout(() => { reject(new Error('Zeitlimit beim Start')); child.kill(); }, START_TIMEOUT_MS);+ child.stdout!.setEncoding('utf8');+ child.stdout!.on('data', (d: string) => {+ this.buf += d;+ let nl: number;+ while ((nl = this.buf.indexOf('\n')) >= 0) {+ const line = this.buf.slice(0, nl).trim();+ this.buf = this.buf.slice(nl + 1);+ if (!line) continue;+ let msg: { ready?: boolean; id?: number } & MeasureResponse;+ try { msg = JSON.parse(line); } catch { continue; } // fremde Ausgaben (Warnungen von Bibliotheken) überspringen+ if (msg.ready) { clearTimeout(timer); resolve(); continue; }+ const p = msg.id != null ? this.pending.get(msg.id) : undefined;+ if (!p) continue;+ this.pending.delete(msg.id!);+ clearTimeout(p.timer);+ p.resolve({ ok: !!msg.ok, result: msg.result, error: msg.error, stale: msg.stale });+ }+ });+ child.stderr!.on('data', (d: Buffer) => { err = (err + d.toString('utf8')).slice(-2000); });+ child.on('error', (e) => { clearTimeout(timer); reject(e); });+ child.on('exit', (code) => {+ clearTimeout(timer);+ if (this.proc === child) { this.proc = null; this.ready = null; }+ reject(new Error(`beendet mit Code ${code}. ${err.trim().split('\n').pop() ?? ''}`));+ this.fail(`Der Messdienst wurde beendet (Code ${code}). Die nächste Messung startet ihn neu.`);+ });+ });+ this.ready.catch(() => { /* wird bei der Anfrage gemeldet */ });+ return this.ready;+ }++ private fail(error: string): void {+ for (const [id, p] of this.pending) { clearTimeout(p.timer); p.resolve({ ok: false, error }); this.pending.delete(id); }+ }+}diff --git a/app/src/main/projects.ts b/app/src/main/projects.tsindex 249f52c..82af6d7 100644--- a/app/src/main/projects.ts+++ b/app/src/main/projects.ts@@ -1,10 +1,11 @@import { shell, type BrowserWindow, type WebContents } from 'electron';import fs from 'node:fs';import path from 'node:path';-import type { ExportResult, GitLog, ModelMap, OpenResult, PreviewResult, ProjectInfo, RestoreResult, SaveResult, SaveState } from '../shared/types';+import type { ExportResult, GitLog, MeasureEntity, MeasureRequest, MeasureResponse, ModelMap, OpenResult, PreviewResult, ProjectInfo, RestoreResult, SaveResult, SaveState } from '../shared/types';import { BuildManager, buildIsStale, newestSourceMtime, runCadide } from './build';import { choose, choosePath } from './dialogs';import { GitRepo } from './git';+import { MeasureService } from './measure';import { previewsDir } from './paths';import { TerminalManager } from './terminals';import { watchProject } from './watcher';@@ -21,6 +22,7 @@ interface Session {builds: BuildManager;terminals: TerminalManager;git: GitRepo;+ measure: MeasureService;stopWatch: () => void;poll: NodeJS.Timeout;signature: string;@@ -58,6 +60,7 @@ export class ProjectController {s.stopWatch();s.builds.dispose();s.terminals.killAll();+ s.measure.stop();this.session = null;}@@ -69,7 +72,7 @@ export class ProjectController {const git = new GitRepo(dir);builds.on('status', (st) => this.send('build:status', st));const stopWatch = watchProject(dir, (rel) => builds.sourceChanged(rel ? path.join(dir, rel) : null), () => this.send('fs:changed'));- const session: Session = { id, dir, builds, terminals, git, stopWatch, signature: '', poll: setInterval(() => void this.pollGit(), POLL_MS) };+ const session: Session = { id, dir, builds, terminals, git, measure: new MeasureService(dir), stopWatch, signature: '', poll: setInterval(() => void this.pollGit(), POLL_MS) };this.session = session;setLastProject(id);// Erster Build direkt beim Öffnen, damit der Viewer nicht leer ist (der Nutzer kann Auto-Build danach abschalten).@@ -261,7 +264,8 @@ export class ProjectController {const commit = (await s.git.log()).find((c) => c.hash === hash) ?? null;const dir = path.join(previewsDir(), s.id, hash);try {- if (!fs.existsSync(path.join(dir, 'model.glb'))) {+ // Ältere Vorschauen haben noch keine Geometrie zum Messen: dann neu erzeugen+ if (!fs.existsSync(path.join(dir, 'model.glb')) || !fs.existsSync(path.join(dir, 'geometry'))) {const step = path.join(dir, 'model.step');await s.git.exportFile(hash, 'output/model.step', step);const r = await runCadide(['glb', step, '--out', dir], s.dir);@@ -278,6 +282,30 @@ export class ProjectController {}}+ /**+ * Exakte Messung (E9). Der Renderer nennt nur die Quelle (aktueller Stand oder Vorschau), den Ordner bestimmt der+ * Hauptprozess. Die Anfrage wird auf die erwartete Form gebracht, bevor sie an den Python-Dienst geht.+ */+ async measure(source: unknown, req: unknown): Promise<MeasureResponse> {+ const s = this.need();+ let folder: string;+ const hash = (source as { preview?: unknown } | null)?.preview;+ if (source === 'live') folder = path.join(s.dir, '.cadide');+ else if (typeof hash === 'string' && /^[0-9a-f]{7,40}$/.test(hash)) folder = path.join(previewsDir(), s.id, hash);+ else return { ok: false, error: 'Unbekannte Quelle für die Messung.' };+ const r = req as { build?: unknown; a?: unknown; b?: unknown } | null;+ const ent = (v: unknown): MeasureEntity | null => {+ const e = v as { part?: unknown; kind?: unknown; id?: unknown; point?: unknown; check?: unknown } | null;+ if (!e || typeof e.part !== 'string' || (e.kind !== 'face' && e.kind !== 'edge' && e.kind !== 'vertex') || !Number.isInteger(e.id)) return null;+ const pt = Array.isArray(e.point) && e.point.length === 3 && e.point.every((x) => Number.isFinite(x)) ? (e.point as number[]) : null;+ return { part: e.part, kind: e.kind, id: e.id as number, point: pt, check: Number.isFinite(e.check) ? (e.check as number) : undefined };+ };+ const a = ent(r?.a), b = r?.b == null ? undefined : ent(r.b);+ if (!a || b === null || typeof r?.build !== 'string') return { ok: false, error: 'Ungültige Messanfrage.' };+ const clean: MeasureRequest = { build: r.build, a, ...(b ? { b } : {}) };+ return s.measure.request(folder, clean);+ }+async restore(hash: string): Promise<RestoreResult> {const s = this.need();const commit = (await s.git.log()).find((c) => c.hash === hash);diff --git a/app/src/main/zip.ts b/app/src/main/zip.tsindex 6a763c3..6a35df3 100644--- a/app/src/main/zip.ts+++ b/app/src/main/zip.ts@@ -11,6 +11,8 @@ export const ZIP_INFO_PATH = '.cadide/zip-info.json';/** Wird nie gepackt: Umgebungen und Caches (Umgebung wird aus requirements.txt neu gebaut, Cache neu erzeugt). */const SKIP_DIRS = new Set(['.venv', 'venv', 'env', '__pycache__', 'node_modules']);const SKIP_FILES = new Set(['.cadide/model.glb', '.cadide/model.map.json', '.cadide/build.json']);+/** Ganze Ordner, die nie gepackt werden (Pfad relativ zum Projekt): die Geometrie für das Messen entsteht beim Bauen neu. */+const SKIP_PATHS = new Set(['.cadide/geometry']);const MAX_UNPACKED = 2 * 1024 ** 3;function collect(root: string): string[] {@@ -19,7 +21,7 @@ function collect(root: string): string[] {for (const e of fs.readdirSync(dir, { withFileTypes: true })) {const r = rel ? `${rel}/${e.name}` : e.name;if (e.isSymbolicLink()) continue;- if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name)) walk(path.join(dir, e.name), r); continue; }+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name) && !SKIP_PATHS.has(r)) walk(path.join(dir, e.name), r); continue; }if (SKIP_FILES.has(r) || (r.startsWith('.git/') && r.endsWith('.lock'))) continue;out.push(r);}diff --git a/app/src/preload/preload.ts b/app/src/preload/preload.tsindex 462932a..83dd414 100644--- a/app/src/preload/preload.ts+++ b/app/src/preload/preload.ts@@ -55,6 +55,7 @@ const api: CadideApi = {onExit: (cb) => { ipcRenderer.on('term:exit', (_e, id, code) => cb(id, code)); },},agents: { detect: () => ipcRenderer.invoke('agents:detect') },+ measure: { query: (source, req) => ipcRenderer.invoke('measure:query', source, req) },dialog: { choose: (o) => ipcRenderer.invoke('dialog:choose', o) },// Nur im Testmodus: vorbereitete Antworten für native Dialogetest: process.env.CADIDE_TEST === '1'diff --git a/app/src/renderer/index.html b/app/src/renderer/index.htmlindex 409dc2d..12b5910 100644--- a/app/src/renderer/index.html+++ b/app/src/renderer/index.html@@ -78,7 +78,7 @@<div id="dock" class="float dock"><button id="btn-display" aria-haspopup="menu" aria-expanded="false" title="Darstellung"><i data-icon="layers"></i><span class="lbl">Darstellung</span><span class="c2"><i data-icon="down" data-size="13" data-stroke="2"></i></span></button><span class="vsep"></span>- <button disabled title="Messen kommt in einem späteren Schritt"><i data-icon="ruler"></i><span class="lbl">Messen</span></button>+ <button id="btn-measure" aria-pressed="false" title="Messen: Fläche oder Kante anklicken, ein zweiter Klick misst Abstand und Winkel (exakte Werte)"><i data-icon="ruler"></i><span class="lbl">Messen</span></button><button disabled title="Die Schnittansicht kommt in einem späteren Schritt"><i data-icon="section"></i><span class="lbl">Schnitt</span></button><span class="vsep"></span><button id="btn-mark" class="hot" title="Viewer-Bild markieren und an den Agenten geben"><i data-icon="camera"></i><span class="lbl">Markieren</span></button>@@ -107,6 +107,16 @@</div></div>+ <div id="measure-card" class="float mcard" hidden>+ <div class="mc-hd"><span class="mc-ico"><i data-icon="ruler" data-size="16"></i></span><b>Messen</b><span class="grow"></span>+ <button id="btn-measure-close" class="ibtn s" aria-label="Messen beenden" title="Messen beenden (Escape)"><i data-icon="x" data-size="14" data-stroke="2"></i></button></div>+ <div id="measure-body" class="mc-body"></div>+ <div class="sc-actions">+ <button id="btn-measure-again" class="btn sm" disabled>Neu messen</button>+ <button id="btn-measure-agent" class="btn sm acc" disabled title="Die Messung in die Eingabe des Agenten einfügen"><i data-icon="send" data-size="14" data-stroke="1.9"></i>An Agent geben</button>+ </div>+ </div>+<div id="errcard" class="float errcard" hidden><div class="ec-hd"><span class="err-ico"><i data-icon="alert" data-size="18"></i></span><div class="ec-title"><b>Build fehlgeschlagen</b><span id="err-where" class="c2"></span></div><span class="grow"></span>diff --git a/app/src/renderer/main.ts b/app/src/renderer/main.tsindex 2407165..06c3b71 100644--- a/app/src/renderer/main.ts+++ b/app/src/renderer/main.ts@@ -4,6 +4,7 @@ import { CodePanel, codeRows, type Mark } from './code';import { FileTree, TEXT_EXT } from './filetree';import { hydrateIcons, icon } from './icons';import { Markup } from './markup';+import { MeasureTool } from './measuretool';import { PartsCard } from './parts';import { TerminalTabs } from './terminals';import { $, el, fmtWhen, menuItem, menus, toast } from './ui';@@ -205,6 +206,19 @@ function insertToAgent(text: string | null, done?: string): void {else toast(`${pre}Das Terminal ist beendet. Öffne über + ein neues.`, 'error');}+// ---- Messen (E9) ------------------------------------------------------------------------------------------------++const measureTool = new MeasureTool({+ card: $('measure-card'), body: $('measure-body'), button: $<HTMLButtonElement>('btn-measure'), close: $<HTMLButtonElement>('btn-measure-close'),+ again: $<HTMLButtonElement>('btn-measure-again'), agent: $<HTMLButtonElement>('btn-measure-agent'), viewerEl: $('viewer'),+}, {+ viewer,+ source: () => (versions.previewed ? { preview: versions.previewed.hash } : 'live'),+ build: () => map?.build ?? null,+ part: (id) => partEntry(id),+ insert: (t) => insertToAgent(t),+});+// ---- Markierung (E16) -------------------------------------------------------------------------------------------const markup = new Markup({@@ -340,6 +354,7 @@ async function loadModel(): Promise<void> {map = JSON.parse(mapText) as ModelMap;textCache.clear();await viewer.load(glb);+ measureTool.reset(); // neuer Build: die Nummern der Flächen und Kanten gelten nicht mehrmsg.className = ''; msg.textContent = '';refreshPartsCard();// Flächen-IDs gelten nur für einen Build: nach dem Neuladen bleibt das Bauteil gewählt, die Fläche nicht@@ -373,6 +388,7 @@ const versions = new VersionsBar({map = res.map;textCache.clear();await viewer.load(res.glb);+ measureTool.reset();refreshPartsCard();selectPart(null, null);void renderErrorCard();@@ -391,6 +407,7 @@ async function onProject(p: ProjectInfo): Promise<void> {lastOkAt = null;textCache.clear();markup.close();+ if (measureTool.isActive) measureTool.setActive(false);viewer.clear();versions.reset();terminals.closeAll();@@ -778,6 +795,7 @@ if (api.testMode) {versionsUi: () => ({ restoreHidden: $('btn-restore').hidden, problem: $('vproblem').hidden ? '' : $('vproblem').textContent }),selectionText, errorText,markup: () => markup.state(),+ measure: () => measureTool.state(),markPixel: (x: number, y: number) => markup.pixel(x, y),markHandles: () => markup.handles(),insert: (text: string) => insertToAgent(text),diff --git a/app/src/renderer/measuretool.ts b/app/src/renderer/measuretool.tsnew file mode 100644index 0000000..dfcf64a--- /dev/null+++ b/app/src/renderer/measuretool.ts@@ -0,0 +1,283 @@+import type { MeasureInfo, MeasureResponse, MeasureResult, MeasureSource, MeasureSpan, PartMap } from '../shared/types';+import { el } from './ui';+import type { MeasureMarks, ProbeHit, Viewer } from './viewer';++interface Ui {+ card: HTMLElement; body: HTMLElement;+ /** Knopf „Messen“ im Viewer (schaltet den Modus), Schließen, Neu messen, An Agent geben. */+ button: HTMLButtonElement; close: HTMLButtonElement; again: HTMLButtonElement; agent: HTMLButtonElement;+ /** Bekommt die Klasse `measuring`, solange gemessen wird (die Auswahlkarte tritt dann zurück). */+ viewerEl: HTMLElement;+}+interface Deps {+ viewer: Viewer;+ /** Aktueller Stand oder Vorschau eines alten Stands. */+ source(): MeasureSource;+ /** Kennung des angezeigten Builds (aus model.map.json). */+ build(): string | null;+ part(id: string): PartMap | undefined;+ insert(text: string): void;+}++const TYPE: Record<string, string> = {+ PLANE: 'eben', CYLINDER: 'Zylinder', CONE: 'Kegel', SPHERE: 'Kugel', TORUS: 'Torus', BSPLINE: 'Freiform', BEZIER: 'Freiform',+ REVOLUTION: 'Drehfläche', EXTRUSION: 'Extrusionsfläche', OFFSET: 'Versatzfläche', OTHER: 'sonstige',+ LINE: 'Gerade', CIRCLE: 'Kreis', ELLIPSE: 'Ellipse', HYPERBOLA: 'Hyperbel', PARABOLA: 'Parabel', VERTEX: 'Punkt',+};+const KIND: Record<string, string> = { face: 'Fläche', edge: 'Kante', vertex: 'Punkt' };+/** „Fläche · eben“, „Kante · Kreis“, beim Eckpunkt nur „Punkt“. */+const what = (i: { kind: string; type: string }, sep = ' · ') => (i.kind === 'vertex' ? 'Punkt' : `${KIND[i.kind]}${sep}${typeName(i.type)}`);+/** Lage eines Punkts: „X 20,00 · Y −15,00 · Z 5,00“. */+const coords = (p: number[]) => p.map((v, k) => `${'XYZ'[k]} ${minus((Math.abs(v) < 5e-4 ? 0 : v).toLocaleString('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 }))}`).join(' · ');+const typeName = (t: string) => TYPE[t] ?? t.toLowerCase();+const mm = (v: number) => `${v.toLocaleString('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} mm`;+const mm2 = (v: number) => `${v.toLocaleString('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} mm²`;+const deg = (v: number) => `${v.toLocaleString('de-DE', { maximumFractionDigits: 1 })}°`;+const minus = (s: string) => s.replace(/^-/, '−');+/** Für den Agenten: Punkt als Dezimalzeichen, drei Stellen, kein „-0“. */+const f3 = (v: number) => (Math.abs(v) < 5e-4 ? 0 : v).toFixed(3);+const vec = (d: number[]) => `(${d.map((x) => +(Math.abs(x) < 5e-7 ? 0 : x).toFixed(4)).join(', ')})`;++/** Richtung in Worten: entlang einer Achse „+Z“, sonst die Komponenten. */+function dirText(d: number[]): string {+ const len = Math.hypot(d[0], d[1], d[2]) || 1;+ for (let i = 0; i < 3; i++) if (Math.abs(Math.abs(d[i]) / len - 1) < 1e-6) return `${d[i] > 0 ? '+' : '−'}${'XYZ'[i]}`;+ return `(${d.map((x) => minus((x / len).toLocaleString('de-DE', { maximumFractionDigits: 3 }))).join(' · ')})`;+}+const mid = (a: number[], b: number[]) => [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2];+const same = (a: number[], b: number[]) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]) < 1e-3;++/**+ * Messen (E9, E22): Im Messmodus wählt ein Klick einen Eckpunkt, eine Kante oder eine Fläche. Der erste Klick zeigt die+ * exakten Werte (Lage, Durchmesser, Länge, Fläche, Normale), der zweite Abstand und Winkel zum ersten, der dritte beginnt von vorn.+ * Gerechnet wird im Python-Dienst an der exakten Geometrie, der Viewer liefert nur, was angeklickt wurde.+ */+export class MeasureTool {+ private active = false;+ private a: ProbeHit | null = null;+ private b: ProbeHit | null = null;+ private result: MeasureResult | null = null;+ private error = '';+ private busy = false;+ private seq = 0;+ private warm = false;++ constructor(private ui: Ui, private deps: Deps) {+ ui.button.addEventListener('click', () => this.setActive(!this.active));+ ui.close.addEventListener('click', () => this.setActive(false));+ ui.again.addEventListener('click', () => this.reset());+ ui.agent.addEventListener('click', () => { const t = this.agentText(); if (t) deps.insert(t); });+ deps.viewer.onMeasurePick = (h) => void this.pick(h);+ window.addEventListener('keydown', (e) => {+ if (!this.active || e.key !== 'Escape') return;+ const t = e.target as HTMLElement | null;+ if (t?.closest?.('#terminals, #code-view, input, textarea, .menu')) return;+ e.preventDefault();+ // Erst die Messung verwerfen, beim zweiten Mal den Modus verlassen+ if (this.a) this.reset(); else this.setActive(false);+ });+ this.render();+ }++ get isActive(): boolean { return this.active; }++ setActive(on: boolean): void {+ this.active = on;+ this.ui.button.setAttribute('aria-pressed', String(on));+ this.ui.viewerEl.classList.toggle('measuring', on);+ this.deps.viewer.setMode(on ? 'measure' : 'select');+ this.clear();+ this.render();+ }++ /** Neuer Build oder anderer Stand: Die IDs der Flächen und Kanten gelten nicht mehr. */+ reset(): void { this.clear(); this.render(); }++ private clear(): void {+ this.a = this.b = null;+ this.result = null;+ this.error = '';+ this.busy = false;+ this.seq++;+ this.deps.viewer.setMeasureMarks(null);+ }++ private async pick(h: ProbeHit | null): Promise<void> {+ if (!h) { if (this.a) this.reset(); return; } // daneben geklickt: von vorn+ const sameAsA = this.a && !this.b && this.a.partId === h.partId && this.a.kind === h.kind && this.a.id === h.id;+ if (!this.a || this.b || sameAsA) { this.a = h; this.b = null; } else this.b = h;+ this.result = null;+ this.error = '';+ this.deps.viewer.setMeasureMarks({ entities: this.entities(), points: [], lines: [] });+ await this.query();+ }++ private entities(): MeasureMarks['entities'] {+ return [this.a, this.b].filter((x): x is ProbeHit => !!x).map((x) => ({ partId: x.partId, kind: x.kind, id: x.id }));+ }++ private async query(): Promise<void> {+ const build = this.deps.build();+ if (!build) { this.error = 'Zu diesem Stand gibt es keine Geometrie zum Messen. Einmal neu bauen hilft.'; this.render(); return; }+ const seq = ++this.seq;+ this.busy = true;+ this.render();+ const ent = (x: ProbeHit) => ({ part: x.partId, kind: x.kind, id: x.id, point: x.point, check: x.size ?? undefined });+ let r: MeasureResponse;+ try { r = await window.cadide.measure.query(this.deps.source(), { build, a: ent(this.a!), ...(this.b ? { b: ent(this.b) } : {}) }); }+ catch (e) { r = { ok: false, error: e instanceof Error ? e.message : String(e) }; }+ if (seq !== this.seq) return; // inzwischen neu geklickt oder abgebrochen+ this.busy = false;+ this.warm = true;+ if (r.ok && r.result) { this.result = r.result; this.drawMarks(); }+ else {+ this.error = r.error ?? 'Die Messung ist fehlgeschlagen.';+ if (r.stale) { this.a = this.b = null; this.deps.viewer.setMeasureMarks(null); }+ }+ this.render();+ }++ /**+ * Die wichtigste Angabe eines Paars: Abstand paralleler Ebenen oder Achsen, mit einem Punkt dessen Abstand zur Ebene,+ * Achse oder Geraden, bei zwei Punkten ihr Abstand, sonst der kürzeste Abstand.+ */+ private primary(r: MeasureResult): { label: string; span: MeasureSpan } | null {+ const p = r.pair;+ if (!p) return null;+ if (p.planes) return { label: 'Abstand der Ebenen', span: p.planes };+ const circles = r.a.type === 'CIRCLE' && r.b?.type === 'CIRCLE';+ if (p.axes) return { label: circles ? 'Abstand der Mittelpunkte' : 'Abstand der Achsen', span: p.axes };+ if (p.toPlane) return { label: 'Abstand zur Ebene', span: p.toPlane };+ if (p.toAxis) return { label: 'Abstand zur Achse', span: p.toAxis };+ if (p.toLine) return { label: 'Abstand zur Geraden', span: p.toLine };+ if (r.a.kind === 'vertex' && r.b?.kind === 'vertex' && p.points) return { label: 'Abstand der Punkte', span: p.points };+ return { label: 'Kürzester Abstand', span: p.min };+ }++ /** Wert, der im Viewer an einem einzelnen Element steht. */+ private headline(i: MeasureInfo): string | null {+ if (i.kind === 'vertex') return i.point ? coords(i.point) : null;+ if (i.radius != null && (i.type === 'CYLINDER' || i.type === 'CIRCLE' || i.type === 'SPHERE')) return `Ø ${mm(2 * i.radius)}`;+ if (i.kind === 'edge' && i.length != null) return mm(i.length);+ if (i.area != null) return mm2(i.area);+ return null;+ }++ private drawMarks(): void {+ const r = this.result!;+ const points = [r.a.point, r.b?.point].filter((p): p is number[] => !!p);+ const lines: MeasureMarks['lines'] = [];+ let label: MeasureMarks['label'];+ const main = this.primary(r);+ if (main) {+ lines.push({ a: main.span.p1, b: main.span.p2, primary: true });+ label = { at: mid(main.span.p1, main.span.p2), text: mm(main.span.value) };+ const pts = r.pair?.points;+ if (pts && !(same(pts.p1, main.span.p1) && same(pts.p2, main.span.p2))) lines.push({ a: pts.p1, b: pts.p2 });+ } else {+ const text = this.headline(r.a);+ const at = r.a.type === 'CIRCLE' && r.a.center ? r.a.center : r.a.point ?? this.a?.point;+ if (text && at) label = { at, text };+ }+ this.deps.viewer.setMeasureMarks({ entities: this.entities(), points, lines, label });+ }++ // ---- Karte ----------------------------------------------------------------------------------------------------++ private render(): void {+ const { card, body, again, agent } = this.ui;+ card.hidden = !this.active;+ if (!this.active) return;+ const rows: HTMLElement[] = [];+ const hint = (t: string) => el('div', { className: 'mc-hint', textContent: t });+ if (!this.a) rows.push(hint('Klick auf einen Punkt, eine Kante oder eine Fläche. Ein zweiter Klick misst Abstand und Winkel zum ersten.'));+ else if (this.busy) rows.push(hint(this.warm ? 'Messe …' : 'Messe … Beim ersten Mal startet der Messdienst, das dauert einige Sekunden.'));+ else if (this.error) rows.push(el('div', { className: 'mc-err', textContent: this.error }));+ else if (this.result && !this.result.b) {+ rows.push(...this.entityRows(this.result.a, true));+ rows.push(hint('Zweites Element anklicken für Abstand und Winkel.'));+ } else if (this.result?.b && this.result.pair) {+ const r = this.result, p = this.result.pair;+ const main = this.primary(r)!;+ rows.push(el('div', { className: 'mc-main' }, el('span', { textContent: main.label }), el('b', { textContent: mm(main.span.value) })));+ if (main.span !== p.min && Math.abs(main.span.value - p.min.value) > 5e-4) rows.push(this.row('Kürzester Abstand', mm(p.min.value)));+ if (p.points) {+ // Bei zwei Punkten ist der Abstand schon die Hauptangabe, die Anteile je Achse gehören trotzdem dazu+ if (main.span !== p.points) rows.push(this.row('Punkt zu Punkt', mm(p.points.value)));+ const d = p.points.delta ?? [0, 0, 0];+ rows.push(el('div', { className: 'mc-sub', textContent: d.map((v, k) => `Δ${'XYZ'[k]} ${minus(v.toLocaleString('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 }))}`).join(' · ') }));+ }+ if (p.angle != null) rows.push(this.row('Winkel', p.angle < 1e-6 ? '0° (parallel)' : deg(p.angle)));+ rows.push(el('div', { className: 'mc-sep' }));+ rows.push(this.entityLine('A', r.a), this.entityLine('B', r.b!));+ }+ body.replaceChildren(...rows);+ again.disabled = !this.a;+ agent.disabled = !this.result;+ }++ private row(label: string, value: string): HTMLElement {+ return el('div', { className: 'mc-row' }, el('span', { textContent: label }), el('span', { className: 'v', textContent: value }));+ }++ private entityLine(tag: string, i: MeasureInfo): HTMLElement {+ const value = this.headline(i);+ return el('div', { className: 'mc-ent' }, el('b', { textContent: tag }), el('span', { textContent: `${what(i, ' ')} · ${i.name ?? i.part}${value ? ` · ${value}` : ''}` }));+ }++ private entityRows(i: MeasureInfo, withPart: boolean): HTMLElement[] {+ const rows: HTMLElement[] = [+ el('div', { className: 'mc-title' }, el('b', { textContent: what(i) }), el('span', { className: 'c2', textContent: i.name ?? i.part })),+ ];+ if (i.kind === 'vertex' && i.point) i.point.forEach((v, k) => rows.push(this.row('XYZ'[k], mm(Math.abs(v) < 5e-4 ? 0 : v).replace(/^-/, '−'))));+ if (i.radius != null) { rows.push(this.row('Durchmesser', `Ø ${mm(2 * i.radius)}`), this.row('Radius', mm(i.radius))); }+ if (i.majorRadius != null && i.minorRadius != null) rows.push(this.row('Radien', `${mm(i.majorRadius)} · ${mm(i.minorRadius)}`));+ if (i.semiAngle != null) rows.push(this.row('Halber Öffnungswinkel', deg(Math.abs(i.semiAngle))));+ if (i.axis) rows.push(this.row('Achse', dirText(i.axis.dir)));+ if (i.normal) rows.push(this.row('Normale', dirText(i.normal)));+ if (i.dir) rows.push(this.row('Richtung', dirText(i.dir)));+ if (i.kind === 'edge' && i.length != null) rows.push(this.row(i.type === 'CIRCLE' && i.closed === false ? 'Bogenlänge' : 'Länge', mm(i.length)));+ if (i.area != null) rows.push(this.row('Fläche', mm2(i.area)));+ const bb = withPart ? this.deps.part(i.part)?.bbox : undefined;+ if (bb) {+ const d = [0, 1, 2].map((k) => bb[1][k] - bb[0][k]);+ rows.push(el('div', { className: 'mc-sep' }), this.row('Bauteil (X × Y × Z)', d.map((v) => v.toLocaleString('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 })).join(' × ') + ' mm'));+ }+ return rows;+ }++ // ---- Für den Agenten ------------------------------------------------------------------------------------------++ /** Text für die Eingabe des Agenten. Zahlen mit Punkt und drei Stellen, damit sie eindeutig bleiben. */+ agentText(): string | null {+ const r = this.result;+ if (!r) return null;+ const desc = (i: MeasureInfo) => `Bauteil "${i.name ?? i.part}" ${what(i, ' ')}`;+ const facts = (i: MeasureInfo) => {+ const out: string[] = [];+ if (i.kind === 'vertex' && i.point) return [`Lage ${vec(i.point.map((v) => +v.toFixed(3)))}`];+ if (i.radius != null) out.push(`Durchmesser ${f3(2 * i.radius)} mm`);+ if (i.axis) out.push(`Achse ${vec(i.axis.dir)} durch ${vec(i.axis.point)}`);+ if (i.normal) out.push(`Normale ${vec(i.normal)}`);+ if (i.dir) out.push(`Richtung ${vec(i.dir)}`);+ if (i.kind === 'edge' && i.length != null) out.push(`Länge ${f3(i.length)} mm`);+ if (i.area != null) out.push(`Fläche ${f3(i.area)} mm²`);+ if (i.point) out.push(`angeklickt bei ${vec(i.point.map((v) => +v.toFixed(3)))}`);+ return out;+ };+ if (!r.b || !r.pair) return `[Messung: ${desc(r.a)}, ${facts(r.a).join(', ')}] `;+ const p = r.pair, main = this.primary(r)!;+ const out = [`${main.label} ${f3(main.span.value)} mm`];+ if (main.span !== p.min && Math.abs(main.span.value - p.min.value) > 5e-4) out.push(`kürzester Abstand ${f3(p.min.value)} mm`);+ if (p.points && main.span === p.points) out.push(`dX ${f3(p.points.delta?.[0] ?? 0)}, dY ${f3(p.points.delta?.[1] ?? 0)}, dZ ${f3(p.points.delta?.[2] ?? 0)}`);+ else if (p.points) out.push(`Punkt zu Punkt ${f3(p.points.value)} mm (dX ${f3(p.points.delta?.[0] ?? 0)}, dY ${f3(p.points.delta?.[1] ?? 0)}, dZ ${f3(p.points.delta?.[2] ?? 0)})`);+ if (p.angle != null) out.push(`Winkel ${p.angle.toFixed(1)}°`);+ return `[Messung: ${desc(r.a)} und ${desc(r.b)}: ${out.join(', ')}] `;+ }++ // ---- Prüfhilfe (nur Tests) ------------------------------------------------------------------------------------++ state() {+ return { active: this.active, a: this.a, b: this.b, busy: this.busy, error: this.error, result: this.result, text: this.ui.body.textContent, agentText: this.agentText() };+ }+}diff --git a/app/src/renderer/style.css b/app/src/renderer/style.cssindex 566bd36..5504f31 100644--- a/app/src/renderer/style.css+++ b/app/src/renderer/style.css@@ -232,6 +232,33 @@ code { font-family:var(--mono); font-size:.95em; }.vbtns button:hover { background:var(--s3); }.selcard { left:12px; bottom:12px; width:356px; overflow:hidden; }+.dock button[aria-pressed=true] { background:var(--acc-tint); color:var(--acc-tx); font-weight:500; }++/* Messen (E9): Karte unten links statt der Auswahlkarte, Punkte und Beschriftung als HTML über dem Bild */+#viewer.measuring #selcard { display:none; }+.mcard { left:12px; bottom:12px; width:356px; overflow:hidden; }+.mc-hd { display:flex; align-items:center; gap:8px; padding:10px 8px 6px 14px; }+.mc-hd b { font-size:14px; }+.mc-ico { color:var(--acc-tx); display:flex; }+.mc-body { padding:0 0 4px; }+.mc-hint { padding:2px 14px 6px; font-size:12px; color:var(--tx3); }+.mc-err { margin:2px 12px 6px; padding:8px 10px; border-radius:6px; background:var(--err-tint); color:#ffc4c0; font-size:12px; }+.mc-title { display:flex; align-items:baseline; gap:8px; padding:2px 14px 6px; min-width:0; }+.mc-title b { font-size:13px; white-space:nowrap; }+.mc-title span { font-size:12px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }+.mc-row { display:flex; justify-content:space-between; gap:12px; padding:3px 14px; font-size:12.5px; color:var(--tx2); }+.mc-row .v { font-family:var(--mono); font-size:12px; color:var(--tx); white-space:nowrap; }+.mc-main { display:flex; align-items:baseline; justify-content:space-between; gap:12px; padding:2px 14px 8px; color:var(--tx2); font-size:12.5px; }+.mc-main b { font:600 20px var(--mono); color:var(--acc-tx); white-space:nowrap; }+.mc-sub { padding:0 14px 4px; font:11.5px var(--mono); color:var(--tx3); text-align:right; }+.mc-sep { height:1px; background:var(--line); margin:6px 12px; }+.mc-ent { display:flex; gap:8px; padding:2px 14px; font-size:12px; color:var(--tx2); min-width:0; }+.mc-ent b { color:var(--acc-tx); }+.mc-ent span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }+.v-overlay { position:absolute; inset:0; pointer-events:none; z-index:1; overflow:hidden; }+.v-pt { position:absolute; left:-5px; top:-5px; width:10px; height:10px; border-radius:50%; background:var(--acc); box-shadow:0 0 0 2px var(--bg); }+.v-label { position:absolute; left:0; top:0; margin:-32px 0 0 10px; padding:3px 8px; border-radius:6px; background:rgba(24,27,31,.95);+ border:1px solid var(--acc-line); color:var(--acc-tx); font:600 12.5px var(--mono); white-space:nowrap; }.sc-hd { display:flex; align-items:center; gap:8px; padding:10px 8px 0 14px; }.sc-hd b { font-size:14px; font-weight:600; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }.sc-info { font-size:12px; padding:2px 14px 8px; }diff --git a/app/src/renderer/viewer.ts b/app/src/renderer/viewer.tsindex b571563..7228c63 100644--- a/app/src/renderer/viewer.ts+++ b/app/src/renderer/viewer.ts@@ -1,12 +1,17 @@import * as THREE from 'three';import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';+import { LineMaterial } from 'three/examples/jsm/lines/LineMaterial.js';+import { LineSegments2 } from 'three/examples/jsm/lines/LineSegments2.js';+import { LineSegmentsGeometry } from 'three/examples/jsm/lines/LineSegmentsGeometry.js';// CAD-Konvention: Z ist oben, Einheit mm. Muss vor dem Anlegen von Kamera und Objekten gesetzt sein.THREE.Object3D.DEFAULT_UP.set(0, 0, 1);interface FaceEntry { id: number; surface: string; area?: number; center?: number[]; triStart: number; triCount: number }-interface PartMeta { partId: string; name: string; role: string; faces: FaceEntry[] }+interface EdgeEntry { id: number; curve: string; length?: number; segStart: number; segCount: number }+interface VertexEntry { id: number; p: number[] }+interface PartMeta { partId: string; name: string; role: string; faces: FaceEntry[]; edges?: EdgeEntry[]; vertices?: VertexEntry[] }interface PartEntry { group: THREE.Object3D; meta: PartMeta; meshes: THREE.Mesh[]; lines: THREE.LineSegments[] }export interface PickResult {@@ -17,6 +22,29 @@ export interface PickResult {export type ViewName = 'iso' | 'front' | 'top' | 'right' | 'fit';+/** Treffer beim Messen: Fläche, Kante oder Eckpunkt eines Bauteils, mit Punkt auf dem Netz (beim Eckpunkt seine Lage). */+export interface ProbeHit {+ partId: string; name: string; kind: 'face' | 'edge' | 'vertex'; id: number;+ /** Flächenart bzw. Kurvenart laut Mesher (PLANE, CYLINDER, LINE, CIRCLE …), bei Eckpunkten VERTEX. */+ type: string;+ /** Flächeninhalt bzw. Länge laut Mesher, zum Abgleich mit der exakten Geometrie. */+ size: number | null;+ point: number[];+}++/** Was die Messung im Viewer zeigt: hervorgehobene Elemente, Punkte, Strecken und eine Beschriftung. */+export interface MeasureMarks {+ entities: { partId: string; kind: 'face' | 'edge' | 'vertex'; id: number }[];+ points: number[][];+ lines: { a: number[]; b: number[]; primary?: boolean }[];+ label?: { at: number[]; text: string };+}++/** Fangradius für Kanten und Eckpunkte in Bildschirmpixeln. Punkte etwas größer, sonst gewönne stets die Kante. */+const EDGE_PX = 7;+const VERTEX_PX = 9;+const ORANGE = 0xf29a38;+export class Viewer {private renderer: THREE.WebGLRenderer;private scene = new THREE.Scene();@@ -33,7 +61,18 @@ export class Viewer {private wire = false;private ghost = false;private selectedId: string | null = null;+ private mode: 'select' | 'measure' = 'select';+ /** Hervorhebung unter dem Zeiger (Messen) und Markierungen der Messung. */+ private hover = new THREE.Group();+ private marks = new THREE.Group();+ private hoverKey = '';+ private lineMats = new Set<LineMaterial>();+ /** HTML-Ebene über dem Bild: Messpunkte und Beschriftung, bei jedem Zeichnen neu positioniert. */+ private overlay: HTMLElement;+ private overlayItems: { el: HTMLElement; at: THREE.Vector3 }[] = [];onPick: (r: PickResult | null) => void = () => {};+ /** Klick im Messmodus. null: daneben geklickt. */+ onMeasurePick: (h: ProbeHit | null) => void = () => {};constructor(private container: HTMLElement) {// Durchsichtiger Hintergrund: den Verlauf dahinter zeichnet CSS, so passt er zur übrigen Oberfläche@@ -45,7 +84,10 @@ export class Viewer {this.scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.6));const sun = new THREE.DirectionalLight(0xffffff, 2.2);sun.position.set(80, -120, 200);- this.scene.add(sun, this.highlight);+ this.scene.add(sun, this.highlight, this.hover, this.marks);+ this.overlay = document.createElement('div');+ this.overlay.className = 'v-overlay';+ container.appendChild(this.overlay);this.controls = new OrbitControls(this.camera, this.renderer.domElement);this.controls.enableDamping = false; // gerendert wird nur bei Änderungenthis.controls.addEventListener('change', () => this.requestRender());@@ -89,6 +131,8 @@ export class Viewer {this.applyVisibility();this.applyDisplay();this.highlight.clear();+ this.clearGroup(this.hover);+ this.hoverKey = '';if (this.selectedId && !this.parts.has(this.selectedId)) this.selectedId = null;this.applySelection();if (!this.hasFitted && this.parts.size) { this.setView('iso'); this.hasFitted = true; }@@ -101,6 +145,8 @@ export class Viewer {this.hidden.clear();this.hasFitted = false;this.highlight.clear();+ this.clearGroup(this.hover);+ this.setMeasureMarks(null);this.requestRender();}@@ -250,9 +296,258 @@ export class Viewer {el.addEventListener('pointerdown', (e) => { down = [e.clientX, e.clientY]; });el.addEventListener('pointerup', (e) => {if (!down || Math.hypot(e.clientX - down[0], e.clientY - down[1]) > 4) return; // Ziehen ist kein Klick+ if (this.mode === 'measure') { this.onMeasurePick(this.probe(e.clientX, e.clientY)); return; }const r = el.getBoundingClientRect();this.onPick(this.pickAt(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1));});+ // Messen: Element unter dem Zeiger hervorheben (höchstens einmal pro Bild berechnet)+ let queued: [number, number] | null = null;+ el.addEventListener('pointermove', (e) => {+ if (this.mode !== 'measure' || e.buttons) return;+ if (!queued) requestAnimationFrame(() => { const q = queued; queued = null; if (q && this.mode === 'measure') this.showHover(this.probe(q[0], q[1])); });+ queued = [e.clientX, e.clientY];+ });+ el.addEventListener('pointerleave', () => this.showHover(null));+ }++ // ---- Messen ---------------------------------------------------------------------------------------------------++ /** Umschalten zwischen Auswählen (Klick wählt ein Bauteil) und Messen (Klick wählt Fläche oder Kante). */+ setMode(m: 'select' | 'measure'): void {+ this.mode = m;+ this.renderer.domElement.style.cursor = m === 'measure' ? 'crosshair' : '';+ if (m !== 'measure') this.showHover(null);+ }++ /**+ * Eckpunkt, Kante oder Fläche unter einem Bildschirmpunkt, in dieser Reihenfolge: Punkte gewinnen im Umkreis von VERTEX_PX,+ * Kanten im Umkreis von EDGE_PX, sonst gilt die Fläche (sonst ließen sich Punkte und Kanten kaum treffen). Verdeckte Punkte+ * und Kanten zählen nicht, ebenso wenig ausgeblendete Bauteile. Ohne sichtbare Kanten gibt es auch keine Punkte.+ */+ probe(clientX: number, clientY: number): ProbeHit | null {+ const el = this.renderer.domElement;+ const r = el.getBoundingClientRect();+ if (!r.width || !r.height) return null;+ const px = clientX - r.left, py = clientY - r.top;+ this.camera.updateMatrixWorld();+ this.raycaster.setFromCamera(new THREE.Vector2((px / r.width) * 2 - 1, -(py / r.height) * 2 + 1), this.camera);+ const targets: THREE.Mesh[] = [];+ for (const p of this.parts.values()) if (p.group.visible) targets.push(...p.meshes);+ const hit = this.raycaster.intersectObjects(targets, false)[0];+ const vertex = this.nearestVertex(px, py, r.width, r.height, targets);+ if (vertex) return vertex;+ const edge = this.nearestEdge(px, py, r.width, r.height, targets);+ if (edge) return edge;+ if (!hit) return null;+ const part = [...this.parts.values()].find((p) => p.meshes.includes(hit.object as THREE.Mesh))!;+ const face = hit.faceIndex != null ? Viewer.faceOfTriangle(part.meta.faces, hit.faceIndex) : null;+ if (!face) return null;+ return { partId: part.meta.partId, name: part.meta.name, kind: 'face', id: face.id, type: face.surface, size: face.area ?? null, point: hit.point.toArray() };+ }++ /** Liegt der Weltpunkt hinter einer Fläche? Toleranz für die Vernetzung, sonst verdeckte die eigene Fläche ihre Kanten. */+ private occluded(p: THREE.Vector3, occluders: THREE.Mesh[]): boolean {+ const eye = this.camera.position;+ const dist = eye.distanceTo(p);+ this.raycaster.set(eye, p.clone().sub(eye).normalize());+ const first = this.raycaster.intersectObjects(occluders, false)[0];+ return !!first && first.distance < dist - Math.max(0.5, dist * 0.002);+ }++ private nearestVertex(px: number, py: number, w: number, h: number, occluders: THREE.Mesh[]): ProbeHit | null {+ const v = new THREE.Vector3(), s = new THREE.Vector3();+ const cands: { part: PartEntry; vx: VertexEntry; d: number; point: THREE.Vector3 }[] = [];+ for (const p of this.parts.values()) {+ if (!p.group.visible || !p.meta.vertices?.length || !p.lines.some((l) => l.visible)) continue;+ p.group.updateMatrixWorld();+ for (const vx of p.meta.vertices) {+ v.set(vx.p[0], vx.p[1], vx.p[2]).applyMatrix4(p.group.matrixWorld);+ s.copy(v).project(this.camera);+ if (s.z > 1) continue;+ const d = Math.hypot((s.x + 1) / 2 * w - px, (1 - s.y) / 2 * h - py);+ if (d <= VERTEX_PX) cands.push({ part: p, vx, d, point: v.clone() });+ }+ }+ cands.sort((a, b) => a.d - b.d);+ for (const c of cands.slice(0, 8)) {+ if (this.occluded(c.point, occluders)) continue;+ return { partId: c.part.meta.partId, name: c.part.meta.name, kind: 'vertex', id: c.vx.id, type: 'VERTEX', size: null, point: c.point.toArray() };+ }+ return null;+ }++ private nearestEdge(px: number, py: number, w: number, h: number, occluders: THREE.Mesh[]): ProbeHit | null {+ const a = new THREE.Vector3(), b = new THREE.Vector3(), sa = new THREE.Vector3(), sb = new THREE.Vector3();+ const cands: { part: PartEntry; seg: number; d: number; point: THREE.Vector3 }[] = [];+ for (const p of this.parts.values()) {+ if (!p.group.visible || !p.meta.edges?.length) continue;+ for (const l of p.lines) {+ if (!l.visible) continue;+ const pos = l.geometry.getAttribute('position');+ l.updateMatrixWorld();+ for (let i = 0; i + 1 < pos.count; i += 2) {+ a.fromBufferAttribute(pos, i).applyMatrix4(l.matrixWorld);+ b.fromBufferAttribute(pos, i + 1).applyMatrix4(l.matrixWorld);+ sa.copy(a).project(this.camera);+ sb.copy(b).project(this.camera);+ if (sa.z > 1 || sb.z > 1) continue; // hinter der Kamera+ const ax = (sa.x + 1) / 2 * w, ay = (1 - sa.y) / 2 * h, bx = (sb.x + 1) / 2 * w, by = (1 - sb.y) / 2 * h;+ const dx = bx - ax, dy = by - ay, len = dx * dx + dy * dy;+ const t = len ? Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / len)) : 0;+ const d = Math.hypot(px - ax - t * dx, py - ay - t * dy);+ if (d <= EDGE_PX) cands.push({ part: p, seg: i / 2, d, point: a.clone().lerp(b, t) });+ }+ }+ }+ cands.sort((x, y) => x.d - y.d);+ for (const c of cands.slice(0, 8)) {+ if (this.occluded(c.point, occluders)) continue;+ const edge = Viewer.edgeOfSegment(c.part.meta.edges!, c.seg);+ if (!edge) continue;+ return { partId: c.part.meta.partId, name: c.part.meta.name, kind: 'edge', id: edge.id, type: edge.curve, size: edge.length ?? null, point: c.point.toArray() };+ }+ return null;+ }++ private static edgeOfSegment(edges: EdgeEntry[], seg: number): EdgeEntry | null {+ let lo = 0, hi = edges.length - 1, ans = -1;+ while (lo <= hi) {+ const mid = (lo + hi) >> 1;+ if (edges[mid].segStart <= seg) { ans = mid; lo = mid + 1; } else hi = mid - 1;+ }+ return ans >= 0 && seg < edges[ans].segStart + edges[ans].segCount ? edges[ans] : null;+ }++ private showHover(h: ProbeHit | null): void {+ const key = h ? `${h.partId}|${h.kind}|${h.id}` : '';+ if (key === this.hoverKey) return;+ this.hoverKey = key;+ this.clearGroup(this.hover);+ if (h) this.addEntity(this.hover, h.partId, h.kind, h.id, 0xffffff, 0.22, 2);+ this.requestRender();+ }++ /** Messung zeichnen (oder mit null entfernen). Die Elemente stehen in Orange (Auswahl), die Strecken darüber. */+ setMeasureMarks(m: MeasureMarks | null): void {+ this.clearGroup(this.marks);+ for (const it of this.overlayItems) it.el.remove();+ this.overlayItems = [];+ if (m) {+ for (const e of m.entities) this.addEntity(this.marks, e.partId, e.kind, e.id, ORANGE, 0.5, 3);+ for (const l of m.lines) {+ this.marks.add(this.fatLines([...l.a, ...l.b], l.primary ? ORANGE : 0xe6e8eb, l.primary ? 2.5 : 1.5, !l.primary));+ }+ for (const p of m.points) this.addOverlay('v-pt', '', p);+ if (m.label) this.addOverlay('v-label', m.label.text, m.label.at);+ }+ this.requestRender();+ }++ private addOverlay(cls: string, text: string, at: number[]): void {+ const el = document.createElement('div');+ el.className = cls;+ el.textContent = text; // Werte, kein Text aus dem Projekt, trotzdem nie innerHTML+ this.overlay.appendChild(el);+ this.overlayItems.push({ el, at: new THREE.Vector3(...(at as [number, number, number])) });+ }++ private addEntity(group: THREE.Group, partId: string, kind: 'face' | 'edge' | 'vertex', id: number, color: number, opacity: number, width: number): void {+ const p = this.parts.get(partId);+ if (!p) return;+ if (kind === 'vertex') {+ const vx = p.meta.vertices?.find((x) => x.id === id);+ if (!vx) return;+ // Ein runder Punkt fester Bildgröße, immer sichtbar (Hervorhebung: größer, Auswahl in Orange)+ const g = new THREE.BufferGeometry();+ g.setAttribute('position', new THREE.Float32BufferAttribute(new THREE.Vector3(...(vx.p as [number, number, number])).applyMatrix4(p.group.matrixWorld).toArray(), 3));+ const m = new THREE.PointsMaterial({ color, size: 6 + width * 3, sizeAttenuation: false, map: Viewer.dot(), transparent: true, alphaTest: 0.2, depthTest: false });+ const o = new THREE.Points(g, m);+ o.renderOrder = 11;+ group.add(o);+ return;+ }+ if (kind === 'face') {+ const face = p.meta.faces.find((f) => f.id === id);+ const src = p.meshes.find((m) => m.geometry.index);+ if (!face || !face.triCount || !src) return;+ // Eigene, kompakte Dreiecke: So lässt sich die Hervorhebung freigeben, ohne die Daten des Bauteils anzufassen+ const pos = src.geometry.getAttribute('position'), idx = src.geometry.index!;+ const tri = new Float32Array(face.triCount * 9);+ for (let k = 0; k < face.triCount * 3; k++) {+ const vi = idx.getX(face.triStart * 3 + k);+ tri[k * 3] = pos.getX(vi); tri[k * 3 + 1] = pos.getY(vi); tri[k * 3 + 2] = pos.getZ(vi);+ }+ const g = new THREE.BufferGeometry();+ g.setAttribute('position', new THREE.BufferAttribute(tri, 3));+ const o = new THREE.Mesh(g, new THREE.MeshBasicMaterial({ color, transparent: true, opacity, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2, side: THREE.DoubleSide }));+ o.renderOrder = 3;+ group.add(o);+ return;+ }+ const edge = p.meta.edges?.find((e) => e.id === id);+ const l = p.lines[0];+ if (!edge || !l) return;+ const pos = l.geometry.getAttribute('position');+ const v = new THREE.Vector3();+ const flat: number[] = [];+ for (let s = edge.segStart; s < edge.segStart + edge.segCount; s++) {+ for (const k of [s * 2, s * 2 + 1]) { v.fromBufferAttribute(pos, k).applyMatrix4(l.matrixWorld); flat.push(v.x, v.y, v.z); }+ }+ group.add(this.fatLines(flat, color, width, false));+ }++ private static dotTexture: THREE.Texture | null = null;+ /** Runde Punktform mit dunklem Rand, einmal gezeichnet und für alle Punkte geteilt. */+ private static dot(): THREE.Texture {+ if (!Viewer.dotTexture) {+ const c = document.createElement('canvas');+ c.width = c.height = 64;+ const g = c.getContext('2d')!;+ g.beginPath();+ g.arc(32, 32, 26, 0, Math.PI * 2);+ g.fillStyle = '#ffffff';+ g.fill();+ g.lineWidth = 8;+ g.strokeStyle = 'rgba(0,0,0,0.65)';+ g.stroke();+ Viewer.dotTexture = new THREE.CanvasTexture(c);+ }+ return Viewer.dotTexture;+ }++ /** Linien mit fester Breite in Pixeln (WebGL-Linien sind sonst immer 1 px). Immer sichtbar, auch hinter Flächen. */+ private fatLines(flat: number[], color: number, width: number, dashed: boolean): LineSegments2 {+ const g = new LineSegmentsGeometry();+ g.setPositions(flat);+ const m = new LineMaterial({ color, linewidth: width, depthTest: false, transparent: true, dashed, dashSize: 1.2, gapSize: 0.9 });+ m.resolution.set(this.container.clientWidth || 1, this.container.clientHeight || 1);+ this.lineMats.add(m);+ const l = new LineSegments2(g, m);+ if (dashed) l.computeLineDistances();+ l.renderOrder = 10;+ return l;+ }++ private clearGroup(g: THREE.Group): void {+ for (const o of [...g.children]) {+ g.remove(o);+ const m = o as THREE.Mesh;+ m.geometry?.dispose();+ const mat = m.material as THREE.Material | undefined;+ if (mat) { if (mat instanceof LineMaterial) this.lineMats.delete(mat); mat.dispose(); }+ }+ }++ private placeOverlay(): void {+ if (!this.overlayItems.length) return;+ const w = this.container.clientWidth, h = this.container.clientHeight;+ const v = new THREE.Vector3();+ for (const it of this.overlayItems) {+ v.copy(it.at).project(this.camera);+ const off = v.z > 1 || v.x < -1.2 || v.x > 1.2 || v.y < -1.2 || v.y > 1.2;+ it.el.hidden = off;+ if (!off) it.el.style.transform = `translate(${((v.x + 1) / 2) * w}px, ${((1 - v.y) / 2) * h}px)`;+ }}select(id: string | null): void { this.selectedId = id; this.highlight.clear(); this.applySelection(); this.requestRender(); }@@ -271,6 +566,7 @@ export class Viewer {const w = this.container.clientWidth, h = this.container.clientHeight;if (!w || !h) return;this.renderer.setSize(w, h, false);+ for (const m of this.lineMats) m.resolution.set(w, h);this.camera.aspect = w / h;this.camera.updateProjectionMatrix();this.requestRender();@@ -279,7 +575,7 @@ export class Viewer {requestRender(): void {if (this.renderQueued) return;this.renderQueued = true;- requestAnimationFrame(() => { this.renderQueued = false; this.renderer.render(this.scene, this.camera); });+ requestAnimationFrame(() => { this.renderQueued = false; this.renderer.render(this.scene, this.camera); this.placeOverlay(); });}/**@@ -292,12 +588,16 @@ export class Viewer {this.selectedId = null;this.applySelection();this.highlight.visible = false;+ this.hover.visible = false; // Messlinien ohne ihre Beschriftung wären im Bild nur verwirrend+ this.marks.visible = false;this.renderer.render(this.scene, this.camera);const c = document.createElement('canvas');try { this.paintSnapshot(c); } finally {this.selectedId = sel;this.applySelection();this.highlight.visible = true;+ this.hover.visible = true;+ this.marks.visible = true;this.requestRender();}return c;@@ -349,6 +649,36 @@ export class Viewer {facesOf(partId: string): FaceEntry[] { return this.parts.get(partId)?.meta.faces ?? []; }+ /** Kanten eines Bauteils mit Mittelpunkt (Mitte des mittleren Segments) und dessen Bildschirmposition. */+ edgesOf(partId: string): { id: number; curve: string; length?: number; mid: number[]; screen: { x: number; y: number } }[] {+ const p = this.parts.get(partId);+ const l = p?.lines[0];+ if (!p || !l) return [];+ const pos = l.geometry.getAttribute('position');+ const r = this.renderer.domElement.getBoundingClientRect();+ this.camera.updateMatrixWorld();+ return (p.meta.edges ?? []).map((e) => {+ const s = e.segStart + Math.floor(e.segCount / 2);+ const a = new THREE.Vector3().fromBufferAttribute(pos, s * 2), b = new THREE.Vector3().fromBufferAttribute(pos, s * 2 + 1);+ const m = a.clone().lerp(b, 0.5);+ const v = m.clone().project(this.camera);+ return { id: e.id, curve: e.curve, length: e.length, mid: m.toArray(), screen: { x: r.left + ((v.x + 1) / 2) * r.width, y: r.top + ((1 - v.y) / 2) * r.height } };+ });+ }++ /** Eckpunkte eines Bauteils mit Bildschirmposition. */+ verticesOf(partId: string): { id: number; p: number[]; screen: { x: number; y: number } }[] {+ return (this.parts.get(partId)?.meta.vertices ?? []).map((v) => ({ id: v.id, p: v.p, screen: this.screenAt(v.p) }));+ }++ /** Bildschirmposition (Pixel im Fenster) eines Weltpunkts. */+ screenAt(p: number[]): { x: number; y: number } {+ this.camera.updateMatrixWorld();+ const v = new THREE.Vector3(...(p as [number, number, number])).project(this.camera);+ const r = this.renderer.domElement.getBoundingClientRect();+ return { x: r.left + ((v.x + 1) / 2) * r.width, y: r.top + ((1 - v.y) / 2) * r.height };+ }+/** Ausdehnung (x, y, z in mm) eines Bauteils. */partSize(partId: string): number[] | null {const p = this.parts.get(partId);diff --git a/app/src/shared/types.ts b/app/src/shared/types.tsindex f2525f6..7578359 100644--- a/app/src/shared/types.ts+++ b/app/src/shared/types.ts@@ -47,8 +47,42 @@ export interface AgentInfo { id: string; label: string; command: string; found:export interface PartMap {id: string; name: string; step_name: string; role: string;file?: string; line?: number; end_line?: number; volume?: number;+ /** Achsparallele Hülle [[xmin, ymin, zmin], [xmax, ymax, zmax]] in mm. */+ bbox?: number[][];}-export interface ModelMap { version: number; parts: PartMap[] }+/** `build`: Kennung des Builds. Sie verbindet GLB, Mapping und die exakte Geometrie für das Messen. */+export interface ModelMap { version: number; build?: string; parts: PartMap[] }++/** Art eines Elements beim Messen: Fläche, Kante oder Eckpunkt. */+export type MeasureKind = 'face' | 'edge' | 'vertex';+/**+ * Angeklicktes Element (E9). `point`: Klickpunkt auf dem Netz, bei Eckpunkten ihre Lage (zum Abgleich).+ * `check`: Flächeninhalt bzw. Länge laut Viewer, zum Abgleich.+ */+export interface MeasureEntity { part: string; kind: MeasureKind; id: number; point: number[] | null; check?: number }+export interface MeasureRequest { build: string; a: MeasureEntity; b?: MeasureEntity }+/** Exakte Angaben zu einem Element, Längen in mm, Winkel in Grad. `point`: Klickpunkt, exakt auf das Element gelegt. */+export interface MeasureInfo {+ kind: MeasureKind; part: string; name?: string; type: string; point: number[] | null;+ area?: number; length?: number; radius?: number; normal?: number[]; origin?: number[];+ axis?: { point: number[]; dir: number[] }; center?: number[]; start?: number[]; end?: number[]; dir?: number[];+ semiAngle?: number; refRadius?: number; majorRadius?: number; minorRadius?: number; closed?: boolean;+}+/** Eine Strecke: Wert und die beiden Endpunkte (zum Zeichnen). */+export interface MeasureSpan { value: number; p1: number[]; p2: number[]; delta?: number[] }+/**+ * `planes`: Abstand paralleler Ebenen, `axes`: Abstand paralleler Achsen, `min`: kürzester Abstand, `points`: Klickpunkt zu+ * Klickpunkt. Mit einem Eckpunkt: `toPlane`, `toAxis`, `toLine` (Lot auf die unbegrenzte Ebene, Achse bzw. Gerade).+ */+export interface MeasurePair {+ min: MeasureSpan; points?: MeasureSpan; planes?: MeasureSpan; axes?: MeasureSpan;+ toPlane?: MeasureSpan; toAxis?: MeasureSpan; toLine?: MeasureSpan; angle?: number;+}+export interface MeasureResult { build: string; a: MeasureInfo; b?: MeasureInfo; pair?: MeasurePair }+/** `stale`: Die Anfrage gehört zu einem älteren Build, die Auswahl ist neu zu treffen. */+export interface MeasureResponse { ok: boolean; result?: MeasureResult; error?: string; stale?: boolean }+/** Was vermessen wird: der aktuelle Stand oder die Vorschau eines alten Stands. */+export type MeasureSource = 'live' | { preview: string };/** Stand der Speicherung: was ist gesichert, was nicht (E21). */export interface SaveState {@@ -134,6 +168,8 @@ export interface CadideApi {onExit(cb: (id: number, code: number) => void): void;};agents: { detect(): Promise<AgentInfo[]> };+ /** Exakte Messung über den Python-Dienst (E9, E24). */+ measure: { query(source: MeasureSource, req: MeasureRequest): Promise<MeasureResponse> };/** Nativer Dialog mit Knöpfen, liefert den Index. Der letzte Knopf gilt als Abbrechen. Im Test über `test.answers` beantwortbar. */dialog: { choose(o: { title: string; message: string; detail?: string; buttons: string[] }): Promise<number> };}diff --git a/app/test/measure.mjs b/app/test/measure.mjsnew file mode 100644index 0000000..da8006c--- /dev/null+++ b/app/test/measure.mjs@@ -0,0 +1,184 @@+// Test des Messens (E9): Messmodus, Fläche und Kante anklicken, exakte Werte aus dem Python-Dienst, Abstand paralleler+// Ebenen, Abstand zweier Bohrungen, verdeckte Kanten, Text für den Agenten, neuer Build, Vorschau eines alten Stands.+// Aufruf: npm run test:measure (baut vorher). SMOKE_VISIBLE=offscreen SMOKE_SHOTS=1 legt Bilder in test/shots/ ab.+import fs from 'node:fs';+import path from 'node:path';+import { APP, checker, cleanup, sleep, startApp } from './harness.mjs';++const t = checker();+const { check } = t;+let app;++// Bekannte Maße: Platte 40 × 30 × 5 mit zwei Bohrungen Ø 6 bei x = ±10, Block 20 × 20 × 5 auf z = 15..20+const MODEL = `import cadquery as cq+from cadide import add_part++plate = (cq.Workplane("XY").box(40, 30, 5, centered=(True, True, False))+ .faces(">Z").workplane().pushPoints([(-10, 0), (10, 0)]).hole(6))+block = cq.Workplane("XY").box(20, 20, 5, centered=(True, True, False)).translate((45, 0, 15))++add_part("Platte", plate)+add_part("Block", block, color=(0.85, 0.55, 0.25))+`;++try {+ app = await startApp({ name: 'measure' });+ const { ev, waitFor, domClick, page } = app;+ const shot = async (name) => {+ if (!process.env.SMOKE_SHOTS) return;+ fs.mkdirSync(path.join(APP, 'test', 'shots'), { recursive: true });+ await sleep(900);+ await app.screenshot(path.join(APP, 'test', 'shots', `${name}.png`)).catch((e) => console.log('Screenshot:', e.message));+ };+ await waitFor('Projekt und Build', () => !!window.__t && !!window.__t.project() && window.__t.status().state === 'ok' && window.__t.partCount() === 2);+ const proj = await ev(() => window.__t.project());+ fs.writeFileSync(path.join(proj.dir, 'model.py'), MODEL);+ await waitFor('Testmodell gebaut', () => window.__t.status().state === 'ok' && JSON.stringify(window.__t.treeNames()) === '["Platte","Block"]', 60000);+ await ev(() => window.__t.viewer.setView('iso'));+ await sleep(300);+ const ids = await ev(() => Object.fromEntries(window.__t.parts().map((p) => [p.name, p.id])));+ const ms = () => ev(() => window.__t.measure());+ const clickAt = (p) => page.click(p.x, p.y);+ const topFace = (name, z) => ev(([pid, z]) => {+ const f = window.__t.viewer.facesOf(pid).find((x) => x.surface === 'PLANE' && Math.abs(x.center[2] - z) < 1e-6);+ return f ? { id: f.id, area: f.area, screen: window.__t.viewer.screenOf(pid, f.id) } : null;+ }, [ids[name], z]);+ const result = (pred) => waitFor('Messergebnis', pred, 60000).catch(() => null);++ // 1) Messmodus+ await domClick('btn-measure');+ let s = await ms();+ check('„Messen": Modus an, Karte mit Hinweis, Auswahlkarte tritt zurück', s.active && s.text.includes('Klick auf einen Punkt, eine Kante oder eine Fläche')+ && await ev(() => document.getElementById('btn-measure').getAttribute('aria-pressed') === 'true' && getComputedStyle(document.getElementById('selcard')).display === 'none'));++ // 2) Eine Fläche: exakte Werte, Maße des Bauteils. Der erste Aufruf startet den Messdienst.+ const plateTop = await topFace('Platte', 5);+ await clickAt(plateTop.screen);+ await result(() => !!window.__t.measure().result);+ s = await ms();+ const expArea = 40 * 30 - 2 * Math.PI * 9;+ check('Klick auf die Oberseite der Platte: Fläche eben, exakter Flächeninhalt, Normale +Z', s.result?.a.type === 'PLANE' && Math.abs(s.result.a.area - expArea) < 1e-6+ && s.text.includes('Fläche · eben') && s.text.includes('+Z'), s.error || `${s.result?.a.area}`);+ check('Karte nennt die Maße des Bauteils: 40,00 × 30,00 × 5,00 mm', s.text.includes('40,00 × 30,00 × 5,00 mm'), s.text.replace(/\s+/g, ' ').slice(0, 90));+ await shot('11-messen-flaeche');++ // 3) Zweite Fläche: Abstand der parallelen Ebenen, Beschriftung im Viewer+ const blockTop = await topFace('Block', 20);+ await clickAt(blockTop.screen);+ await result(() => !!window.__t.measure().result?.pair);+ s = await ms();+ check('Zweiter Klick auf die Oberseite des Blocks: Abstand der Ebenen 15,00 mm, parallel', Math.abs((s.result?.pair?.planes?.value ?? 0) - 15) < 1e-9+ && s.text.includes('Abstand der Ebenen') && s.text.includes('15,00 mm') && s.text.includes('0° (parallel)'), s.error || s.text.replace(/\s+/g, ' ').slice(0, 90));+ check('Im Viewer: Beschriftung „15,00 mm" und zwei Messpunkte', await ev(() => document.querySelector('.v-label')?.textContent === '15,00 mm' && document.querySelectorAll('.v-pt').length === 2));+ await shot('12-messen-abstand');++ // 4) Kanten: obere Ränder der beiden Bohrungen (Kreise). Dritter Klick beginnt von vorn.+ const rims = await ev((pid) => window.__t.viewer.edgesOf(pid).filter((e) => e.curve === 'CIRCLE' && Math.abs(e.mid[2] - 5) < 1e-3).sort((a, b) => a.mid[0] - b.mid[0]), ids.Platte);+ const left = rims[0], right = rims[rims.length - 1];+ await clickAt(left.screen);+ await result(() => !!window.__t.measure().result && !window.__t.measure().b && window.__t.measure().a?.kind === 'edge');+ s = await ms();+ check('Klick auf den Rand der linken Bohrung: Kante Kreis, Ø 6,00 mm', s.result?.a.type === 'CIRCLE' && Math.abs(s.result.a.radius - 3) < 1e-9 && s.text.includes('Ø 6,00 mm'),+ s.error || `${s.a?.kind} ${s.result?.a.type}`);+ await clickAt(right.screen);+ await result(() => !!window.__t.measure().result?.pair);+ s = await ms();+ check('Rand der rechten Bohrung dazu: Abstand der Mittelpunkte 20,00 mm', Math.abs((s.result?.pair?.axes?.value ?? 0) - 20) < 1e-9 && s.text.includes('Abstand der Mittelpunkte'),+ s.error || s.text.replace(/\s+/g, ' ').slice(0, 90));+ await shot('13-messen-bohrungen');++ // 5) An den Agenten+ const tid = await ev(() => window.__t.terminals.activeId);+ await domClick('btn-measure-agent');+ await waitFor('Messung im Terminal', (id) => window.__t.termText(id).includes('[Messung:'), 10000, tid).catch(() => {});+ const txt = await ev((id) => window.__t.termText(id), tid);+ // Den genauen Text prüft das Werkzeug selbst: Im Terminal kann beim Zeilenumbruch der Darstellung ein Zeichen fehlen+ const agentText = (await ms()).agentText ?? '';+ check('„An Agent geben": Text mit Bauteil, Elementen und Wert (Punkt als Dezimalzeichen), steht im Terminal',+ agentText.startsWith('[Messung: Bauteil "Platte" Kante Kreis und Bauteil "Platte" Kante Kreis: Abstand der Mittelpunkte 20.000 mm') && txt.includes('[Messung: Bauteil'),+ agentText.slice(0, 90));+ await ev((id) => window.cadide.term.write(id, '\x03'), tid);++ // 6) Verdeckte Kante: Die untere hintere Kante der Platte liegt hinter der Oberseite und darf nicht getroffen werden+ const hidden = await ev((pid) => window.__t.viewer.edgesOf(pid).find((e) => e.curve === 'LINE' && Math.abs(e.mid[2]) < 1e-3 && Math.abs(e.mid[1] - 15) < 1e-3), ids.Platte);+ const probe = await ev((p) => window.__t.viewer.probe(p.x, p.y), hidden.screen);+ check('Verdeckte Kante wird nicht getroffen, dort liegt die Oberseite', !!probe && !(probe.kind === 'edge' && probe.id === hidden.id), probe ? `${probe.kind} ${probe.type}` : 'nichts');++ // 6b) Punkte fassen: Ecken der Platte. Ein Klick in der Nähe fasst den Punkt, auch wo Kanten zusammenlaufen.+ const verts = await ev((pid) => window.__t.viewer.verticesOf(pid), ids.Platte);+ const vAt = (x, y, z) => verts.find((v) => Math.abs(v.p[0] - x) < 1e-6 && Math.abs(v.p[1] - y) < 1e-6 && Math.abs(v.p[2] - z) < 1e-6);+ const cornerR = vAt(20, -15, 5), cornerL = vAt(-20, -15, 5), cornerHidden = vAt(-20, 15, 0);+ await page.click(cornerR.screen.x + 4, cornerR.screen.y + 3); // knapp daneben: Der Punkt wird trotzdem gefasst+ await result(() => window.__t.measure().a?.kind === 'vertex' && !!window.__t.measure().result && !window.__t.measure().b);+ s = await ms();+ check('Klick nahe einer Ecke fasst den Punkt (vor den Kanten dort): X 20,00 · Y −15,00 · Z 5,00', s.a?.kind === 'vertex' && s.result?.a.type === 'VERTEX'+ && s.text.includes('Punkt') && s.text.includes('−15,00 mm') && await ev(() => document.querySelector('.v-label')?.textContent === 'X 20,00 · Y −15,00 · Z 5,00'),+ s.error || `${s.a?.kind} ${s.text.replace(/\s+/g, ' ').slice(0, 60)}`);+ await clickAt(cornerL.screen);+ await result(() => !!window.__t.measure().result?.pair);+ s = await ms();+ check('Zweiter Punkt: Abstand der Punkte 40,00 mm (ΔX −40,00)', Math.abs((s.result?.pair?.points?.value ?? 0) - 40) < 1e-9 && s.text.includes('Abstand der Punkte') && s.text.includes('40,00 mm') && s.text.includes('ΔX −40,00'),+ s.error || s.text.replace(/\s+/g, ' ').slice(0, 80));+ await shot('14-messen-punkte');+ await clickAt(cornerR.screen);+ await result(() => window.__t.measure().a?.kind === 'vertex' && !window.__t.measure().b && !!window.__t.measure().result);+ await clickAt(blockTop.screen);+ await result(() => !!window.__t.measure().result?.pair);+ s = await ms();+ check('Punkt und Fläche: Abstand zur Ebene 15,00 mm', Math.abs((s.result?.pair?.toPlane?.value ?? 0) - 15) < 1e-9 && s.text.includes('Abstand zur Ebene'), s.error || s.text.replace(/\s+/g, ' ').slice(0, 80));+ check('Text für den Agenten nennt den Punkt mit Lage', (s.agentText ?? '').startsWith('[Messung: Bauteil "Platte" Punkt und Bauteil "Block" Fläche eben: Abstand zur Ebene 15.000 mm'), (s.agentText ?? '').slice(0, 90));+ const probeV = await ev((q) => window.__t.viewer.probe(q.x, q.y), cornerHidden.screen);+ check('Verdeckte Ecke lässt sich nicht fassen', !!probeV && !(probeV.kind === 'vertex' && probeV.id === cornerHidden.id), probeV ? `${probeV.kind} ${probeV.type}` : 'nichts');++ // 7) Escape: erst die Messung verwerfen, dann den Modus verlassen. Danach wählt ein Klick wieder das Bauteil.+ await ev(() => document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));+ s = await ms();+ check('Escape verwirft die Messung, der Modus bleibt', s.active && !s.a && !s.result && await ev(() => !document.querySelector('.v-label')));+ await ev(() => document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));+ await clickAt(plateTop.screen);+ await sleep(300);+ check('Zweites Escape beendet das Messen, ein Klick wählt wieder das Bauteil', !(await ms()).active && await ev(() => document.getElementById('measure-card').hidden)+ && (await ev(() => window.__t.info())).startsWith('Platte'));++ // 8) Neuer Build während einer Messung: Die Nummern gelten nicht mehr, die Messung beginnt von vorn+ await domClick('btn-measure');+ await clickAt(plateTop.screen);+ await result(() => !!window.__t.measure().result);+ fs.writeFileSync(path.join(proj.dir, 'model.py'), MODEL.replace('translate((45, 0, 15))', 'translate((45, 0, 18))'));+ await waitFor('neu gebaut', () => window.__t.status().state === 'ok' && !window.__t.measure().a, 60000).catch(() => {});+ s = await ms();+ check('Neuer Build: Messung zurückgesetzt, Modus bleibt an', s.active && !s.a && !s.result && s.text.includes('Klick auf einen Punkt'));+ const blockTop2 = await topFace('Block', 23);+ await clickAt(plateTop.screen);+ await result(() => !!window.__t.measure().result);+ await clickAt(blockTop2.screen);+ await result(() => !!window.__t.measure().result?.pair);+ s = await ms();+ check('Nach dem Build misst der Dienst den neuen Stand (Abstand jetzt 18,00 mm)', Math.abs((s.result?.pair?.planes?.value ?? 0) - 18) < 1e-9, s.error || s.text.replace(/\s+/g, ' ').slice(0, 80));++ // 9) Vorschau eines alten Stands (Startcommit, Vorlagenmodell) lässt sich ebenfalls vermessen+ await ev(() => document.querySelectorAll('#vdots .vdot')[0].click());+ await waitFor('Vorschau', () => !!window.__t.versions().previewing && JSON.stringify(window.__t.treeNames()) === '["Body","Lid"]', 60000).catch(() => {});+ s = await ms();+ check('Vorschau: Messung zurückgesetzt', s.active && !s.a);+ await ev(() => window.__t.viewer.setView('iso'));+ await sleep(300);+ const lidTop = await ev((pid) => {+ const f = window.__t.viewer.facesOf(pid).filter((x) => x.surface === 'PLANE').sort((a, b) => b.center[2] - a.center[2])[0];+ return { id: f.id, screen: window.__t.viewer.screenOf(pid, f.id) };+ }, await ev(() => window.__t.parts().find((p) => p.name === 'Lid').id));+ await clickAt(lidTop.screen);+ await result(() => !!window.__t.measure().result || !!window.__t.measure().error);+ s = await ms();+ check('In der Vorschau: Oberseite des Deckels vermessen (Deckel 60 × 40, Radius 3 in den Ecken)', s.result?.a.type === 'PLANE' && Math.abs(s.result.a.area - (60 * 40 - (4 - Math.PI) * 9)) < 1e-6,+ s.error || `${s.result?.a.area}`);++ const relevant = page.errors.filter((e) => !/favicon/i.test(e));+ check('Keine Konsolenfehler im Renderer', relevant.length === 0, relevant.slice(0, 2).join(' | ').slice(0, 100));+} catch (e) {+ console.log('ABBRUCH:', e.message);+ t.fail();+}+if (app) { await app.stop(); cleanup(app.ud); }+console.log(t.fails ? `\n${t.fails} Prüfung(en) fehlgeschlagen` : '\nALLE PRÜFUNGEN BESTANDEN');+process.exit(t.fails ? 1 : 0);