Skip to content

armgit / SOMA

Public Imported from GitHub
0

Desktop app for designing parametric 3D models in CadQuery together with the coding agent of your choice

App: Bauteilbaum mit Gruppen, Transparenz je Teil und Gruppe (E42)

Kai-Jungsthoefela1a06fc1970f
diff --git a/app/package.json b/app/package.json
index 7c11339..12595e0 100644
--- a/app/package.json
+++ b/app/package.json
@@ -12,8 +12,9 @@
"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:groups": "npm run build && node test/groups.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 && node test/measure.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 && node test/groups.mjs"
},
"dependencies": {
"@codemirror/autocomplete": "^6.20.3",
diff --git a/app/resources/template/AGENTS.md b/app/resources/template/AGENTS.md
index 196f203..b809c7d 100644
--- a/app/resources/template/AGENTS.md
+++ b/app/resources/template/AGENTS.md
@@ -17,13 +17,14 @@ The app shows the result in a 3D viewer next to this terminal. Notes and wishes
## Rules for model.py
-1. `from cadide import add_part, import_step`
+1. `from cadide import add_part, import_step, import_assembly`
2. **Register every part**: `add_part("Name", workplane_or_shape)`. Unregistered geometry is invisible in the viewer and missing from exports.
3. Names are unique. Umlauts are fine, they are shown as written.
-4. Mark a part the user brought (for example a circuit board) with `role="reference"`: it is shown semi-transparent and skipped by `cadide export --all`. Cut clearances around it, but do not export it.
-5. Units are millimetres, Z is up. Put dimensions in named constants at the top so the user can ask for changes ("make the wall 3 mm").
-6. Load user files with `import_step("inputs/board.step")`. STEP files often have their origin in a corner: check the bounding box and move the part deliberately.
-7. Prefer simple, readable CadQuery. Check that operations produced solids. Do not use `show_object` or `cq_editor`.
+4. Group related parts with `group`: `add_part("Screw front", screw, group="Housing/Screws")` (nested with `/`). Groups show up in the part tree of the app and as sub-assemblies in `output/model.step`.
+5. Mark a part the user brought (for example a circuit board) with `role="reference"`: it is shown semi-transparent and skipped by `cadide export --all`. Cut clearances around it, but do not export it.
+6. Units are millimetres, Z is up. Put dimensions in named constants at the top so the user can ask for changes ("make the wall 3 mm").
+7. Load user files with `import_step("inputs/board.step")`: this merges the whole file into one shape. If the file has several parts or sub-assemblies, keep them with `asm = import_assembly("inputs/board.step")` and `add_part("Board", asm, role="reference")`: every body becomes its own part with its name and color, the sub-assemblies become groups under "Board". Move an assembly with `asm.loc = cq.Location((x, y, z))`. STEP files often have their origin in a corner: check the bounding box and move the part deliberately.
+8. Prefer simple, readable CadQuery. Check that operations produced solids. Do not use `show_object` or `cq_editor`.
## Commands
diff --git a/app/src/renderer/icons.ts b/app/src/renderer/icons.ts
index 59c16c1..931692d 100644
--- a/app/src/renderer/icons.ts
+++ b/app/src/renderer/icons.ts
@@ -35,6 +35,7 @@ const PATHS: Record<string, string> = {
play: '<path d="M7 5v14l11-7z"/>',
// Werkzeuge der Markierung
pointer: '<path d="M6 3v16l4.2-4.1 2.9 6.2 2.6-1.2-2.9-6.1H18.5z"/>',
+ ghost: '<circle cx="12" cy="12" r="8"/><path d="M12 4a8 8 0 0 1 0 16z" fill="currentColor" fill-opacity=".45"/>',
trash: '<path d="M4 7h16M10 11v6M14 11v6"/><path d="M6 7l1 13h10l1-13M9 7V4h6v3"/>',
pen: '<path d="M4 20h4L19 9l-4-4L4 16z"/>', arrow: '<path d="M5 19 19 5M9 5h10v10"/>',
square: '<rect x="4" y="4" width="16" height="16" rx="1.5"/>', circle: '<circle cx="12" cy="12" r="8"/>',
diff --git a/app/src/renderer/main.ts b/app/src/renderer/main.ts
index 8243c85..1f96d00 100644
--- a/app/src/renderer/main.ts
+++ b/app/src/renderer/main.ts
@@ -125,9 +125,12 @@ const partsCard = new PartsCard({
search: $<HTMLButtonElement>('btn-parts-search'), filter: $<HTMLInputElement>('parts-filter'),
}, {
select: (id) => selectPart(id, null, true),
- setVisible: (id, on) => viewer.setVisible(id, on),
+ setVisible: (ids, on) => viewer.setVisible(ids, on),
isVisible: (id) => viewer.isVisible(id),
+ setGhost: (ids, on) => viewer.setGhosted(ids, on),
+ isGhost: (id) => viewer.isGhosted(id),
context: (id, x, y) => openPartMenu(id, x, y),
+ groupContext: (ids, name, x, y) => openGroupMenu(ids, name, x, y),
});
const refreshPartsCard = () => partsCard.set(viewer.partList(), viewer.selection);
@@ -154,6 +157,7 @@ async function renderSelection(): Promise<void> {
const e = partEntry(partId);
const name = e?.name ?? p?.name ?? partId;
$('sel-name').textContent = name + (p?.role === 'reference' ? ' (Referenz)' : '');
+ $('sel-name').title = p?.group ? `Gruppe ${p.group}` : '';
$('sel-swatch').style.background = p?.color ?? '';
const bits = pick?.faceId != null
? ['Fläche', surfaceName(pick.surface), ...(pick.area != null ? [`${num(pick.area)} mm²`] : [])]
@@ -180,7 +184,8 @@ async function renderSelection(): Promise<void> {
function selectionText(): string | null {
if (!selection) return null;
const e = partEntry(selection.partId);
- const bits = [`Bauteil "${e?.name ?? partInfo(selection.partId)?.name ?? selection.partId}"`];
+ const group = partInfo(selection.partId)?.group;
+ const bits = [`Bauteil "${e?.name ?? partInfo(selection.partId)?.name ?? selection.partId}"${group ? ` in Gruppe "${group}"` : ''}`];
if (e?.file && e.line) { const { from, to } = lineRange(e); bits.push(`${e.file} Zeile ${from}${to !== from ? '-' + to : ''}`); }
const pk = selection.pick;
if (pk?.faceId != null) {
@@ -262,12 +267,14 @@ $('btn-mark-send').addEventListener('click', () => void sendMarkup());
function openPartMenu(id: string, x: number, y: number): void {
const e = partEntry(id);
const visible = viewer.isVisible(id);
+ const ghost = viewer.isGhosted(id);
const m = $('menu-ctx');
const items: (HTMLElement | null)[] = [
el('div', { className: 'mh', textContent: e?.name ?? partInfo(id)?.name ?? id }),
menuItem('Isolieren', { icon: 'target', onClick: () => { viewer.isolate(id); refreshPartsCard(); } }),
viewer.hiddenCount ? menuItem('Alle einblenden', { icon: 'eye', onClick: () => { viewer.showAll(); refreshPartsCard(); } }) : null,
menuItem(visible ? 'Ausblenden' : 'Einblenden', { icon: visible ? 'eyeoff' : 'eye', onClick: () => { viewer.setVisible(id, !visible); refreshPartsCard(); } }),
+ menuItem(ghost ? 'Nicht mehr transparent' : 'Transparent', { icon: 'ghost', onClick: () => { viewer.setGhosted(id, !ghost); refreshPartsCard(); } }),
menuItem('Kamera auf Bauteil', { icon: 'fit', onClick: () => viewer.focusPart(id) }),
el('div', { className: 'msep' }),
menuItem('Code zeigen', { icon: 'code', disabled: !e?.file, onClick: () => { selectPart(id, null); if (e?.file && e.line) void openCode(e.file, { ...lineRange(e), label: e.name, color: partInfo(id)?.color }); } }),
@@ -278,6 +285,23 @@ function openPartMenu(id: string, x: number, y: number): void {
menus.at(m, x, y);
}
+/** Rechtsklick auf eine Gruppe: dasselbe für alle ihre Teile. */
+function openGroupMenu(ids: string[], name: string, x: number, y: number): void {
+ const anyVisible = ids.some((id) => viewer.isVisible(id));
+ const allGhost = ids.every((id) => viewer.isGhosted(id));
+ const m = $('menu-ctx');
+ const items: (HTMLElement | null)[] = [
+ el('div', { className: 'mh', textContent: `${name} · ${ids.length} Teil${ids.length === 1 ? '' : 'e'}` }),
+ menuItem('Isolieren', { icon: 'target', onClick: () => { viewer.isolate(ids); refreshPartsCard(); } }),
+ viewer.hiddenCount ? menuItem('Alle einblenden', { icon: 'eye', onClick: () => { viewer.showAll(); refreshPartsCard(); } }) : null,
+ menuItem(anyVisible ? 'Ausblenden' : 'Einblenden', { icon: anyVisible ? 'eyeoff' : 'eye', onClick: () => { viewer.setVisible(ids, !anyVisible); refreshPartsCard(); } }),
+ menuItem(allGhost ? 'Nicht mehr transparent' : 'Transparent', { icon: 'ghost', onClick: () => { viewer.setGhosted(ids, !allGhost); refreshPartsCard(); } }),
+ menuItem('Kamera auf Gruppe', { icon: 'fit', onClick: () => viewer.setView('fit', ids) }),
+ ];
+ m.replaceChildren(...items.filter((x): x is HTMLElement => !!x));
+ menus.at(m, x, y);
+}
+
// ---- Build und Modell -------------------------------------------------------------------------------------------
function renderBuild(s: BuildStatus): void {
diff --git a/app/src/renderer/parts.ts b/app/src/renderer/parts.ts
index 8fb491e..ae95153 100644
--- a/app/src/renderer/parts.ts
+++ b/app/src/renderer/parts.ts
@@ -1,24 +1,33 @@
import { icon } from './icons';
import { el } from './ui';
-export interface PartRow { id: string; name: string; role: string; color: string }
+/** `group`: Pfad der Gruppe mit „/“, z. B. „Gehäuse/Schrauben“, oder null. */
+export interface PartRow { id: string; name: string; role: string; color: string; group: string | null }
interface Hooks {
select(id: string): void;
- setVisible(id: string, on: boolean): void;
+ setVisible(ids: string[], on: boolean): void;
isVisible(id: string): boolean;
+ setGhost(ids: string[], on: boolean): void;
+ isGhost(id: string): boolean;
context(id: string, x: number, y: number): void;
+ groupContext(ids: string[], name: string, x: number, y: number): void;
}
+/** Gruppe im Baum. `items` in der Reihenfolge, in der sie im Modell zuerst vorkommen (Gruppen und Teile gemischt). */
+interface GroupNode { key: string; name: string; items: ({ group: GroupNode } | { part: PartRow })[] }
+
/**
* Schwebende Bauteilkarte oben links im Viewer. Nur so hoch wie ihr Inhalt, einklappbar, ab ein paar Teilen mit Suche.
- * Referenzen stehen in einem eigenen Abschnitt (E34).
+ * Gruppen (aus add_part(group=…) oder aus der Struktur importierter STEP-Dateien) stehen als aufklappbarer Baum.
+ * Jedes Teil und jede Gruppe lässt sich aus- und einblenden sowie transparent schalten. Referenzen stehen für sich (E34).
*/
export class PartsCard {
private parts: PartRow[] = [];
private selected: string | null = null;
private filter = '';
private placeholder = '';
+ private collapsed = new Set<string>();
constructor(private ui: { card: HTMLElement; list: HTMLElement; count: HTMLElement; toggle: HTMLButtonElement; search: HTMLButtonElement; filter: HTMLInputElement }, private hooks: Hooks) {
ui.toggle.addEventListener('click', () => this.setCollapsed(!ui.card.classList.contains('collapsed')));
@@ -45,27 +54,92 @@ export class PartsCard {
const { list, count } = this.ui;
count.textContent = this.parts.length ? String(this.parts.length) : '';
if (!this.parts.length) { list.replaceChildren(el('div', { className: 'hint', textContent: this.placeholder || 'Noch keine Bauteile.' })); return; }
- const match = (p: PartRow) => !this.filter || p.name.toLowerCase().includes(this.filter);
- const own = this.parts.filter((p) => p.role !== 'reference' && match(p));
- const refs = this.parts.filter((p) => p.role === 'reference' && match(p));
- const rows: HTMLElement[] = own.map((p) => this.row(p));
- if (refs.length) rows.push(el('div', { className: 'grp', textContent: 'REFERENZEN' }), ...refs.map((p) => this.row(p)));
+ const match = (p: PartRow) => !this.filter || p.name.toLowerCase().includes(this.filter) || (p.group ?? '').toLowerCase().includes(this.filter);
+ const own = this.tree('own', this.parts.filter((p) => p.role !== 'reference' && match(p)));
+ const refs = this.tree('ref', this.parts.filter((p) => p.role === 'reference' && match(p)));
+ const rows: HTMLElement[] = this.rows(own, 0);
+ if (refs.items.length) rows.push(el('div', { className: 'grp', textContent: 'REFERENZEN' }), ...this.rows(refs, 0));
if (!rows.length) rows.push(el('div', { className: 'hint', textContent: 'Kein Bauteil passt zur Suche.' }));
list.replaceChildren(...rows);
}
- private row(p: PartRow): HTMLElement {
+ private tree(section: string, parts: PartRow[]): GroupNode {
+ const root: GroupNode = { key: section, name: '', items: [] };
+ for (const p of parts) {
+ let node = root;
+ for (const seg of (p.group ?? '').split('/').filter(Boolean)) {
+ let next = node.items.find((x): x is { group: GroupNode } => 'group' in x && x.group.name === seg)?.group;
+ if (!next) { next = { key: `${node.key}/${seg}`, name: seg, items: [] }; node.items.push({ group: next }); }
+ node = next;
+ }
+ node.items.push({ part: p });
+ }
+ return root;
+ }
+
+ private static ids(node: GroupNode): string[] {
+ return node.items.flatMap((x) => ('part' in x ? [x.part.id] : PartsCard.ids(x.group)));
+ }
+
+ private rows(node: GroupNode, depth: number): HTMLElement[] {
+ const out: HTMLElement[] = [];
+ for (const it of node.items) {
+ if ('part' in it) { out.push(this.row(it.part, depth)); continue; }
+ const g = it.group;
+ // Beim Suchen immer aufgeklappt, sonst sähe man die Treffer nicht
+ const open = !!this.filter || !this.collapsed.has(g.key);
+ out.push(this.groupRow(g, depth, open));
+ if (open) out.push(...this.rows(g, depth + 1));
+ }
+ return out;
+ }
+
+ private groupRow(g: GroupNode, depth: number, open: boolean): HTMLElement {
+ const ids = PartsCard.ids(g);
+ const anyVisible = ids.some((id) => this.hooks.isVisible(id));
+ const ghosts = ids.filter((id) => this.hooks.isGhost(id)).length;
+ const toggle = () => { if (open) this.collapsed.add(g.key); else this.collapsed.delete(g.key); this.render(); };
+ const name = el('button', { className: 'nm', title: open ? 'Gruppe zuklappen' : 'Gruppe aufklappen' },
+ el('span', { className: 'chev' + (open ? '' : ' shut') }, icon('down', 13, 2)), el('span', { className: 'gname', textContent: g.name }), el('span', { className: 'gcount', textContent: String(ids.length) }));
+ name.setAttribute('aria-expanded', String(open));
+ name.addEventListener('click', toggle);
+ const row = el('div', { className: 'row gr' + (anyVisible ? '' : ' off') }, name,
+ this.ghostButton(`Gruppe ${g.name}`, ghosts === ids.length, ghosts > 0 && ghosts < ids.length, () => this.hooks.setGhost(ids, ghosts !== ids.length)),
+ this.eyeButton(`Gruppe ${g.name}`, anyVisible, () => this.hooks.setVisible(ids, !anyVisible)));
+ row.style.paddingLeft = `${4 + depth * 14}px`;
+ row.addEventListener('contextmenu', (e) => { e.preventDefault(); this.hooks.groupContext(ids, g.name, e.clientX, e.clientY); });
+ return row;
+ }
+
+ private row(p: PartRow, depth: number): HTMLElement {
const visible = this.hooks.isVisible(p.id);
+ const ghost = this.hooks.isGhost(p.id);
const sw = el('span', { className: 'sw' + (p.role === 'reference' ? ' ref' : '') });
sw.style.background = p.color;
const name = el('button', { className: 'nm', title: 'Auswählen und Codestelle zeigen' }, sw, el('span', { className: 'pname', textContent: p.name }));
name.addEventListener('click', () => this.hooks.select(p.id));
- const eye = el('button', { className: 'eye', title: visible ? 'Ausblenden' : 'Einblenden' }, icon(visible ? 'eye' : 'eyeoff', 15));
- eye.setAttribute('aria-label', `${p.name} ${visible ? 'ausblenden' : 'einblenden'}`);
- eye.addEventListener('click', () => { this.hooks.setVisible(p.id, !visible); this.render(); });
- const row = el('div', { className: 'row' + (this.selected === p.id ? ' sel' : '') + (visible ? '' : ' off') }, name, eye);
+ const row = el('div', { className: 'row' + (this.selected === p.id ? ' sel' : '') + (visible ? '' : ' off') }, name,
+ this.ghostButton(p.name, ghost, false, () => this.hooks.setGhost([p.id], !ghost)),
+ this.eyeButton(p.name, visible, () => this.hooks.setVisible([p.id], !visible)));
+ row.style.paddingLeft = `${4 + depth * 14}px`;
row.dataset.id = p.id;
row.addEventListener('contextmenu', (e) => { e.preventDefault(); this.hooks.context(p.id, e.clientX, e.clientY); });
return row;
}
+
+ private eyeButton(what: string, visible: boolean, act: () => void): HTMLButtonElement {
+ const b = el('button', { className: 'eye', title: visible ? 'Ausblenden' : 'Einblenden' }, icon(visible ? 'eye' : 'eyeoff', 15));
+ b.setAttribute('aria-label', `${what} ${visible ? 'ausblenden' : 'einblenden'}`);
+ b.addEventListener('click', () => { act(); this.render(); });
+ return b;
+ }
+
+ /** Transparent schalten. `partly`: nur ein Teil der Gruppe ist transparent. */
+ private ghostButton(what: string, on: boolean, partly: boolean, act: () => void): HTMLButtonElement {
+ const b = el('button', { className: 'eye gh' + (on ? ' on' : partly ? ' partly' : ''), title: on ? 'Nicht mehr transparent' : 'Transparent schalten' }, icon('ghost', 15));
+ b.setAttribute('aria-label', `${what} ${on ? 'nicht mehr transparent' : 'transparent schalten'}`);
+ b.setAttribute('aria-pressed', String(on));
+ b.addEventListener('click', () => { act(); this.render(); });
+ return b;
+ }
}
diff --git a/app/src/renderer/style.css b/app/src/renderer/style.css
index c8e161d..c8d7e6a 100644
--- a/app/src/renderer/style.css
+++ b/app/src/renderer/style.css
@@ -206,6 +206,13 @@ code { font-family:var(--mono); font-size:.95em; }
.row.off .nm { color:var(--tx3); }
.row .eye { width:26px; height:26px; display:flex; align-items:center; justify-content:center; border-radius:6px; color:var(--tx3); }
.row .eye:hover { background:var(--s3); color:var(--tx); }
+.row .eye.gh.on { color:var(--acc-tx); }
+.row .eye.gh.partly { color:var(--acc-tx); opacity:.45; } /* nur ein Teil der Gruppe ist transparent */
+.row.gr .nm { gap:5px; padding-left:4px; }
+.row.gr .chev { display:flex; color:var(--tx3); transition:transform .12s; }
+.row.gr .chev.shut { transform:rotate(-90deg); }
+.row.gr .gname { font-weight:500; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
+.row.gr .gcount { font-size:11px; color:var(--tx3); margin-left:2px; }
.sw { width:10px; height:10px; border-radius:3px; flex-shrink:0; display:inline-block; box-shadow:inset 0 0 0 1px rgba(255,255,255,.18); }
.sw.ref { background:transparent !important; border:1px dashed var(--tx3); box-shadow:none; }
.grp { padding:10px 12px 4px; font-size:11px; letter-spacing:.06em; color:var(--tx3); }
diff --git a/app/src/renderer/versions.ts b/app/src/renderer/versions.ts
index ead925f..b47fb1f 100644
--- a/app/src/renderer/versions.ts
+++ b/app/src/renderer/versions.ts
@@ -35,6 +35,7 @@ export class VersionsBar {
private previewHash: string | null = null;
private savedHead: string | null = null;
private seq = 0;
+ private logSeq = 0;
constructor(private ui: Ui, private hooks: Hooks) {
ui.live.addEventListener('click', () => void this.select(this.log.commits.length));
@@ -62,7 +63,13 @@ export class VersionsBar {
}
async refresh(): Promise<void> {
- try { this.log = await window.cadide.versions.log(); } catch { return; }
+ // Abfragen können sich überholen (etwa wenn .git gerade verschwindet). Nur die neueste zählt, sonst bliebe ein
+ // veralteter Stand stehen, und weil sich danach nichts mehr ändert, käme auch keine neue Abfrage.
+ const seq = ++this.logSeq;
+ let log: GitLog;
+ try { log = await window.cadide.versions.log(); } catch { return; }
+ if (seq !== this.logSeq) return;
+ this.log = log;
// Existiert der angezeigte Stand nicht mehr (Verlauf umgebaut), zurück zum Arbeitsstand
if (this.previewHash && !this.log.commits.some((c) => c.hash === this.previewHash)) await this.select(this.log.commits.length);
else this.render();
diff --git a/app/src/renderer/viewer.ts b/app/src/renderer/viewer.ts
index a589417..1d5cd07 100644
--- a/app/src/renderer/viewer.ts
+++ b/app/src/renderer/viewer.ts
@@ -12,7 +12,7 @@ THREE.Object3D.DEFAULT_UP.set(0, 0, 1);
interface FaceEntry { id: number; surface: string; area?: number; center?: number[]; triStart: number; triCount: number }
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 PartMeta { partId: string; name: string; role: string; group?: string | null; faces: FaceEntry[]; edges?: EdgeEntry[]; vertices?: VertexEntry[] }
interface PartEntry { group: THREE.Object3D; meta: PartMeta; meshes: THREE.Mesh[]; lines: THREE.LineSegments[] }
export interface PickResult {
@@ -55,6 +55,8 @@ export class Viewer {
private parts = new Map<string, PartEntry>();
private highlight = new THREE.Group();
private hidden = new Set<string>();
+ /** Einzeln transparent geschaltete Bauteile (anders als „Transparent“ im Menü, das für alle gilt). */
+ private ghosted = new Set<string>();
private raycaster = new THREE.Raycaster();
private renderQueued = false;
private hasFitted = false;
@@ -131,6 +133,8 @@ export class Viewer {
if ((c as THREE.Mesh).isMesh) meshes.push(c as THREE.Mesh);
if ((c as THREE.LineSegments).isLineSegments) lines.push(c as THREE.LineSegments);
});
+ // Auch die Kanten brauchen ihr eigenes Material, sonst würden sie mit einem transparenten Teil überall blass
+ for (const l of lines) l.material = (l.material as THREE.LineBasicMaterial).clone();
for (const m of meshes) {
// Eigenes Material je Netz: die Auswahl färbt ein Bauteil ein, gleichfarbige Teile dürfen nicht mitleuchten
const mat = (m.material as THREE.MeshStandardMaterial).clone();
@@ -148,6 +152,7 @@ export class Viewer {
this.parts = fresh;
this.scene.add(gltf.scene);
for (const id of [...this.hidden]) if (!this.parts.has(id)) this.hidden.delete(id);
+ for (const id of [...this.ghosted]) if (!this.parts.has(id)) this.ghosted.delete(id);
this.applyVisibility();
this.applyDisplay();
this.highlight.clear();
@@ -166,6 +171,7 @@ export class Viewer {
this.disposeModel();
this.parts.clear();
this.hidden.clear();
+ this.ghosted.clear();
this.hasFitted = false;
this.highlight.clear();
this.clearGroup(this.hover);
@@ -187,28 +193,38 @@ export class Viewer {
// ---- Sichtbarkeit und Darstellung -----------------------------------------------------------------------------
- partList(): { id: string; name: string; role: string; color: string }[] {
+ partList(): { id: string; name: string; role: string; color: string; group: string | null }[] {
return [...this.parts.values()].map((p) => ({
- id: p.meta.partId, name: p.meta.name, role: p.meta.role,
+ id: p.meta.partId, name: p.meta.name, role: p.meta.role, group: p.meta.group ?? null,
color: p.meshes[0] ? '#' + (p.meshes[0].material as THREE.MeshStandardMaterial).color.getHexString() : '#888',
}));
}
isVisible(id: string): boolean { return !this.hidden.has(id); }
- setVisible(id: string, on: boolean): void {
- if (on) this.hidden.delete(id); else this.hidden.add(id);
+ setVisible(ids: string | string[], on: boolean): void {
+ for (const id of typeof ids === 'string' ? [ids] : ids) { if (on) this.hidden.delete(id); else this.hidden.add(id); }
this.applyVisibility();
this.requestRender();
}
- /** Nur dieses Bauteil zeigen. */
- isolate(id: string): void {
- for (const k of this.parts.keys()) if (k !== id) this.hidden.add(k); else this.hidden.delete(k);
+ /** Nur dieses Bauteil (oder diese Gruppe) zeigen. */
+ isolate(ids: string | string[]): void {
+ const keep = new Set(typeof ids === 'string' ? [ids] : ids);
+ for (const k of this.parts.keys()) if (!keep.has(k)) this.hidden.add(k); else this.hidden.delete(k);
this.applyVisibility();
this.requestRender();
}
+ isGhosted(id: string): boolean { return this.ghosted.has(id); }
+
+ /** Einzelne Bauteile transparent schalten. Sie lassen dann Klicks durch zu dem, was dahinter liegt. */
+ setGhosted(ids: string | string[], on: boolean): void {
+ for (const id of typeof ids === 'string' ? [ids] : ids) { if (on) this.ghosted.add(id); else this.ghosted.delete(id); }
+ this.applyDisplay();
+ this.requestRender();
+ }
+
showAll(): void { this.hidden.clear(); this.applyVisibility(); this.requestRender(); }
get hiddenCount(): number { return this.hidden.size; }
@@ -222,19 +238,41 @@ export class Viewer {
setGhost(on: boolean): void { this.ghost = on; this.applyDisplay(); this.requestRender(); }
private applyDisplay(): void {
- for (const p of this.parts.values()) {
- for (const l of p.lines) l.visible = this.edges;
+ for (const [id, p] of this.parts) {
+ const own = this.ghosted.has(id);
+ for (const l of p.lines) {
+ l.visible = this.edges;
+ const lm = l.material as THREE.LineBasicMaterial;
+ lm.transparent = own;
+ lm.opacity = own ? 0.3 : 1;
+ }
for (const m of p.meshes) {
const mat = m.material as THREE.MeshStandardMaterial;
mat.wireframe = this.wire;
const base = (mat.userData.baseOpacity as number) ?? 1;
- mat.opacity = this.ghost ? Math.min(base, 0.35) : base;
- mat.transparent = this.ghost || (mat.userData.baseTransparent as boolean);
+ // Einzeln transparent: deutlich durchsichtiger und ohne Tiefe, damit man sieht, was dahinter liegt
+ mat.opacity = own ? Math.min(base, 0.18) : this.ghost ? Math.min(base, 0.35) : base;
+ mat.transparent = own || this.ghost || (mat.userData.baseTransparent as boolean);
+ mat.depthWrite = !own && p.meta.role !== 'reference';
+ m.renderOrder = own ? 2 : p.meta.role === 'reference' ? 1 : 0;
mat.needsUpdate = true;
}
}
}
+ /** Sichtbare Bauteile, getrennt nach deckend und einzeln transparent. Treffer gehen zuerst an die deckenden. */
+ private pickSets(): [PartEntry[], PartEntry[]] {
+ const vis = [...this.parts.values()].filter((p) => p.group.visible);
+ return [vis.filter((p) => !this.ghosted.has(p.meta.partId)), vis.filter((p) => this.ghosted.has(p.meta.partId))];
+ }
+
+ /** Erste Fläche unter dem Strahl, transparente Teile nur, wenn dahinter nichts Deckendes liegt. */
+ private firstHit(): THREE.Intersection | undefined {
+ const [solid, ghost] = this.pickSets();
+ return this.raycaster.intersectObjects(solid.flatMap((p) => p.meshes), false)[0]
+ ?? this.raycaster.intersectObjects(ghost.flatMap((p) => p.meshes), false)[0];
+ }
+
// ---- Kamera ---------------------------------------------------------------------------------------------------
private bounds(ids?: string[]): THREE.Box3 {
@@ -382,9 +420,7 @@ export class Viewer {
pickAt(ndcX: number, ndcY: number): PickResult | null {
this.raycaster.setFromCamera(new THREE.Vector2(ndcX, ndcY), 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 hit = this.firstHit();
this.highlight.clear();
if (!hit) { this.selectedId = null; this.applySelection(); this.requestRender(); return null; }
const part = [...this.parts.values()].find((p) => p.meshes.includes(hit.object as THREE.Mesh))!;
@@ -434,9 +470,7 @@ export class Viewer {
el.addEventListener('dblclick', (e) => {
const r = el.getBoundingClientRect();
this.raycaster.setFromCamera(new THREE.Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / 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 hit = this.firstHit();
if (hit) this.setPivot(hit.point.clone());
});
}
@@ -461,13 +495,19 @@ export class Viewer {
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);
+ // Erst die deckenden Teile, transparent geschaltete nur, wenn dort nichts anderes liegt: So misst man durch sie hindurch
+ const [solid, ghost] = this.pickSets();
+ return this.probeIn(px, py, r.width, r.height, solid) ?? this.probeIn(px, py, r.width, r.height, ghost);
+ }
+
+ private probeIn(px: number, py: number, w: number, h: number, parts: PartEntry[]): ProbeHit | null {
+ if (!parts.length) return null;
+ const targets = parts.flatMap((p) => p.meshes);
+ this.raycaster.setFromCamera(new THREE.Vector2((px / w) * 2 - 1, -(py / h) * 2 + 1), this.camera);
const hit = this.raycaster.intersectObjects(targets, false)[0];
- const vertex = this.nearestVertex(px, py, r.width, r.height, targets);
+ const vertex = this.nearestVertex(px, py, w, h, parts, targets);
if (vertex) return vertex;
- const edge = this.nearestEdge(px, py, r.width, r.height, targets);
+ const edge = this.nearestEdge(px, py, w, h, parts, targets);
if (edge) return edge;
if (!hit) return null;
const part = [...this.parts.values()].find((p) => p.meshes.includes(hit.object as THREE.Mesh))!;
@@ -485,11 +525,11 @@ export class Viewer {
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 {
+ private nearestVertex(px: number, py: number, w: number, h: number, parts: PartEntry[], 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;
+ for (const p of parts) {
+ if (!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);
@@ -507,11 +547,11 @@ export class Viewer {
return null;
}
- private nearestEdge(px: number, py: number, w: number, h: number, occluders: THREE.Mesh[]): ProbeHit | null {
+ private nearestEdge(px: number, py: number, w: number, h: number, parts: PartEntry[], 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 p of parts) {
+ if (!p.meta.edges?.length) continue;
for (const l of p.lines) {
if (!l.visible) continue;
const pos = l.geometry.getAttribute('position');
@@ -811,6 +851,12 @@ export class Viewer {
return (this.parts.get(partId)?.meta.vertices ?? []).map((v) => ({ id: v.id, p: v.p, screen: this.screenAt(v.p) }));
}
+ /** Deckkraft und Tiefenschreiben eines Bauteils, für Tests. */
+ partLook(id: string): { opacity: number; depthWrite: boolean } | null {
+ const m = this.parts.get(id)?.meshes[0]?.material as THREE.MeshStandardMaterial | undefined;
+ return m ? { opacity: m.opacity, depthWrite: m.depthWrite } : null;
+ }
+
/** Kamera, Drehpunkt und Schnittebenen, für Tests. */
viewState() {
const d = this.camera.position.clone().sub(this.controls.target);
diff --git a/app/src/shared/types.ts b/app/src/shared/types.ts
index 7578359..50e6679 100644
--- a/app/src/shared/types.ts
+++ b/app/src/shared/types.ts
@@ -47,6 +47,8 @@ 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;
+ /** Gruppe mit „/“ verschachtelt, z. B. „Gehäuse/Schrauben“ (aus add_part(group=…) oder einer importierten Baugruppe). */
+ group?: string | null;
/** Achsparallele Hülle [[xmin, ymin, zmin], [xmax, ymax, zmax]] in mm. */
bbox?: number[][];
}
diff --git a/app/test/groups.mjs b/app/test/groups.mjs
new file mode 100644
index 0000000..a64cf46
--- /dev/null
+++ b/app/test/groups.mjs
@@ -0,0 +1,149 @@
+// Test für Gruppen und Transparenz: Gruppen aus add_part(group=…) und aus einer importierten STEP-Baugruppe, Baum in der
+// Bauteilkarte, Aus-/Einblenden und Transparenz je Teil und Gruppe, Klick durch ein transparentes Teil, Gruppen in der
+// Ausgabe-STEP. Aufruf: npm run test:groups (baut vorher). SMOKE_VISIBLE=offscreen SMOKE_SHOTS=1 legt Bilder ab.
+import { spawnSync } from 'node:child_process';
+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;
+
+// Dasselbe Python wie die App (paths.ts): CADIDE_PYTHON oder die Entwicklungsumgebung aus Phase 0
+const PY = process.env.CADIDE_PYTHON || path.join(process.env.LOCALAPPDATA ?? '', 'cadide-phase0', 'venv-full', 'Scripts', 'python.exe');
+const py = (code) => spawnSync(PY, ['-c', code], { encoding: 'utf8' });
+
+// Fremde Baugruppe wie von einem Hersteller: Platine mit Unterbaugruppe „Stecker“
+const MAKE_STEP = (file) => `
+import cadquery as cq
+sub = cq.Assembly(name="Stecker")
+sub.add(cq.Workplane().box(8, 6, 3).translate((20, 0, 2.3)), name="USB_C", color=cq.Color(0.7, 0.7, 0.7))
+sub.add(cq.Workplane().box(2.5, 10, 2.5).translate((-20, 0, 2)), name="Pinleiste", color=cq.Color(0.1, 0.1, 0.1))
+asm = cq.Assembly(name="Platine")
+asm.add(cq.Workplane().box(50, 30, 1.6), name="Leiterplatte", color=cq.Color(0.1, 0.5, 0.2))
+asm.add(sub, name="Stecker")
+asm.export(${JSON.stringify(file)})
+`;
+const MODEL = `import cadquery as cq
+from cadide import add_part, import_assembly
+
+add_part("Boden", cq.Workplane().box(60, 40, 3), group="Gehäuse")
+add_part("Deckel", cq.Workplane().box(60, 40, 2).translate((0, 0, 20)), group="Gehäuse")
+add_part("Schraube", cq.Workplane().cylinder(10, 1.5).translate((25, 15, 10)), group="Gehäuse/Schrauben")
+
+platine = import_assembly("inputs/platine.step")
+platine.loc = cq.Location((0, 0, 8))
+add_part("Platine", platine, role="reference")
+`;
+
+try {
+ app = await startApp({ name: 'groups' });
+ const { ev, waitFor, 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.mkdirSync(path.join(proj.dir, 'inputs'), { recursive: true });
+ const made = py(MAKE_STEP(path.join(proj.dir, 'inputs', 'platine.step')));
+ check('Test-STEP mit Unterbaugruppe angelegt', made.status === 0 && fs.existsSync(path.join(proj.dir, 'inputs', 'platine.step')), made.stderr.slice(-200));
+ fs.writeFileSync(path.join(proj.dir, 'model.py'), MODEL);
+ await waitFor('Modell mit Gruppen gebaut', () => window.__t.status().state === 'ok' && window.__t.partCount() === 6, 90000).catch(() => {});
+ const status = await ev(() => window.__t.status());
+ check('Build mit Gruppen und importierter Baugruppe: 6 Bauteile', (await ev(() => window.__t.partCount())) === 6, `${status.text} ${status.detail} ${status.viewerMsg ?? ''}`.slice(0, 90));
+
+ // 1) Baum in der Bauteilkarte
+ const rows = () => ev(() => [...document.querySelectorAll('#tab-model .row, #tab-model .grp')].map((r) => ({
+ kind: r.classList.contains('grp') ? 'section' : r.classList.contains('gr') ? 'group' : 'part',
+ name: (r.querySelector('.gname') ?? r.querySelector('.pname'))?.textContent ?? r.textContent, pad: parseInt(r.style.paddingLeft || '0', 10),
+ })));
+ let r = await rows();
+ const outline = r.map((x) => `${x.kind === 'group' ? '+' : x.kind === 'section' ? '#' : '-'}${x.name}@${x.pad}`).join(' ');
+ check('Baum: Gehäuse › Boden, Deckel, Schrauben › Schraube, dann Referenzen › Platine › Leiterplatte, Stecker › USB_C, Pinleiste',
+ outline === '+Gehäuse@4 -Boden@18 -Deckel@18 +Schrauben@18 -Schraube@32 #REFERENZEN@0 +Platine@4 -Leiterplatte@18 +Stecker@18 -USB_C@32 -Pinleiste@32', outline);
+ const parts = await ev(() => Object.fromEntries(window.__t.parts().map((p) => [p.name, p])));
+ const green = parts.Leiterplatte?.color ?? '#000';
+ const [cr, cg, cb] = [1, 3, 5].map((i) => parseInt(green.slice(i, i + 2), 16));
+ check('Namen und Farben kommen aus der STEP-Datei (Leiterplatte grün, Stecker in Gruppe „Platine/Stecker")', cg > cr && cg > cb && parts.USB_C?.group === 'Platine/Stecker', `${green} ${parts.USB_C?.group}`);
+ await shot('15-gruppen');
+
+ const groupRow = (name) => `[...document.querySelectorAll('#tab-model .row.gr')].find((r) => r.querySelector('.gname').textContent === ${JSON.stringify(name)})`;
+ const partRow = (name) => `[...document.querySelectorAll('#tab-model .row:not(.gr)')].find((r) => r.querySelector('.pname')?.textContent === ${JSON.stringify(name)})`;
+ const clickIn = (rowExpr, sel) => ev(`(${rowExpr}).querySelector(${JSON.stringify(sel)}).click()`);
+ const ids = (names) => names.map((n) => parts[n].id);
+ const visible = (names) => ev((l) => l.map((id) => window.__t.viewer.isVisible(id)), ids(names));
+ const ghosted = (names) => ev((l) => l.map((id) => window.__t.viewer.isGhosted(id)), ids(names));
+
+ // 2) Gruppe aus- und einblenden
+ await clickIn(groupRow('Gehäuse'), '.eye:not(.gh)');
+ check('Auge der Gruppe „Gehäuse" blendet alle drei Teile aus, auch in der Untergruppe', (await visible(['Boden', 'Deckel', 'Schraube'])).every((v) => !v) && (await visible(['Leiterplatte']))[0]);
+ await clickIn(groupRow('Gehäuse'), '.eye:not(.gh)');
+ check('Noch einmal: alle wieder da', (await visible(['Boden', 'Deckel', 'Schraube'])).every(Boolean));
+
+ // 3) Zuklappen
+ await clickIn(groupRow('Gehäuse'), '.nm');
+ r = await rows();
+ check('Gruppe zuklappen: ihre Teile verschwinden aus der Liste, sichtbar bleiben sie im Modell', !r.some((x) => ['Boden', 'Deckel', 'Schraube', 'Schrauben'].includes(x.name)) && (await visible(['Boden']))[0]);
+ await clickIn(groupRow('Gehäuse'), '.nm');
+
+ // 4) Transparenz: Von oben liegt der Deckel über der Platine. Deckend trifft der Klick den Deckel, transparent die Platine.
+ await ev(() => window.__t.viewer.setView('top'));
+ await sleep(200);
+ const center = await ev(() => window.__t.viewer.screenAt([0, 0, 8.8]));
+ await page.click(center.x, center.y);
+ await waitFor('Auswahl', () => window.__t.info() !== '', 5000).catch(() => {});
+ check('Deckend: Klick von oben trifft den Deckel', (await ev(() => window.__t.info())).startsWith('Deckel'), (await ev(() => window.__t.info())).slice(0, 30));
+ await clickIn(partRow('Deckel'), '.gh');
+ const look = await ev((id) => window.__t.viewer.partLook(id), parts.Deckel.id);
+ check('Deckel transparent schalten: durchsichtig, verdeckt nichts mehr', (await ghosted(['Deckel']))[0] && look.opacity < 0.3 && !look.depthWrite
+ && await ev(`(${partRow('Deckel')}).querySelector('.gh').getAttribute('aria-pressed') === 'true'`), JSON.stringify(look));
+ await page.click(center.x, center.y);
+ await waitFor('Auswahl Platine', () => window.__t.info().startsWith('Leiterplatte'), 5000).catch(() => {});
+ check('Transparent: derselbe Klick geht durch den Deckel und trifft die Leiterplatte', (await ev(() => window.__t.info())).startsWith('Leiterplatte'), (await ev(() => window.__t.info())).slice(0, 30));
+ check('Auswahltext für den Agenten nennt die Gruppe', /Bauteil "Leiterplatte" in Gruppe "Platine"/.test(await ev(() => window.__t.selectionText())), (await ev(() => window.__t.selectionText())).slice(0, 70));
+ await clickIn(groupRow('Stecker'), '.gh');
+ check('Transparenz der Gruppe „Stecker": beide Teile, die Gruppe darüber zeigt „teilweise"', (await ghosted(['USB_C', 'Pinleiste'])).every(Boolean) && !(await ghosted(['Leiterplatte']))[0]
+ && await ev(`(${groupRow('Platine')}).querySelector('.gh').classList.contains('partly')`));
+ await shot('16-gruppen-transparent');
+ await clickIn(partRow('Deckel'), '.gh');
+ check('Transparenz wieder aus: Deckel deckend', !(await ghosted(['Deckel']))[0] && (await ev((id) => window.__t.viewer.partLook(id), parts.Deckel.id)).depthWrite);
+
+ // 5) Rechtsklick auf eine Gruppe: Isolieren
+ await ev(`(${groupRow('Gehäuse')}).dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 60, clientY: 90 }))`);
+ const menu = await ev(() => [...document.querySelectorAll('#menu-ctx .mi span:nth-child(2)')].map((x) => x.textContent));
+ await ev(() => [...document.querySelectorAll('#menu-ctx .mi')].find((b) => b.textContent.includes('Isolieren')).click());
+ check('Rechtsklick auf eine Gruppe: Isolieren zeigt nur ihre Teile', menu.includes('Isolieren') && menu.includes('Transparent')
+ && (await visible(['Boden', 'Deckel', 'Schraube'])).every(Boolean) && (await visible(['Leiterplatte', 'USB_C'])).every((v) => !v), menu.join(', '));
+ await ev(() => window.__t.viewer.showAll());
+
+ // 6) Suche findet Teile samt ihren Gruppen
+ await ev(() => { document.getElementById('btn-parts-search').click(); const f = document.getElementById('parts-filter'); f.value = 'usb'; f.dispatchEvent(new Event('input')); });
+ r = await rows();
+ check('Suche „usb": USB_C mit seinen Gruppen Platine und Stecker', r.filter((x) => x.kind !== 'section').map((x) => x.name).join(',') === 'Platine,Stecker,USB_C', r.map((x) => x.name).join(','));
+ await ev(() => document.getElementById('btn-parts-search').click());
+
+ // 7) Ausgabe-STEP: Gruppen als Unterbaugruppen, Referenzen unter „Referenz"
+ const tree = py(`
+import cadquery as cq
+a = cq.Assembly.importStep(${JSON.stringify(path.join(proj.dir, 'output', 'model.step'))})
+def walk(x, d=0):
+ print(" " * d + x.name)
+ for c in x.children: walk(c, d + 1)
+walk(a)`);
+ const lines = tree.stdout.split(/\r?\n/).filter(Boolean).slice(1).map((l) => l.replace(/\s+$/, ''));
+ check('output/model.step: Gehaeuse › Schrauben › Schraube und Referenz › Platine › Stecker › USB_C', lines.includes(' Gehaeuse') && lines.includes(' Schrauben') && lines.includes(' Schraube')
+ && lines.includes(' Referenz') && lines.includes(' Platine') && lines.includes(' Stecker') && lines.includes(' USB_C'), lines.join(' | ').slice(0, 120));
+
+ 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);