diff --git a/src/parametric/README.md b/src/parametric/README.md index d3ba2e52c0..6a24f30b3a 100644 --- a/src/parametric/README.md +++ b/src/parametric/README.md @@ -34,6 +34,30 @@ It runs entirely in the browser. The geometry kernel is OpenCascade compiled to - Open SolidWorks parts (.sldprt, SolidWorks 2003 and later) without SolidWorks: the exact solid is read from the file and becomes an imported body you can keep modeling on. The SolidWorks feature tree is not carried over. - References to faces and edges are stored by name, so fillets and sketches on faces survive dimension changes. +**Surfaces** +- A Surfaces tab: extruded, revolved, swept and lofted surfaces from open or closed sketch curves, planar surfaces from a closed sketch or a loop of edges, offset surfaces (a distance of 0 copies faces) and filled patches. +- Trim surfaces with a plane, a sketch or another surface (keep a side, or click the pieces to keep), extend them past an edge, and knit them together, into a solid when they close a volume. +- Thicken a surface into the part or cut with it (Thickened Cut), cut the part with a surface, or delete faces of the solid to work on it as a surface (or delete and patch them). +- Surface bodies are shown in a warm tint beside the solid, can be hidden from the design tree, are picked and referenced like the solid's faces and edges (sketch on a planar surface face), go into STEP files as shells and are left out of the solid's mass properties. + +**Sheet metal** +- Sheet Metal tab: Base Flange from a closed profile (a flat plate) or an open line and arc chain (bent at each corner), with the part's thickness, bend radius, K-factor (or bend allowance or deduction) and relief type kept on it and editable from the Sheet-Metal row of the design tree. A later Base Flange is a Tab on a face of the sheet. +- Edge Flange on one or more edges: length from the outer or inner virtual sharp or the bend, any angle, material inside or outside or bend outside, offsets with rectangular or obround bend reliefs. Sketched Bend along a line on a flat face, and closed or open Hems. +- Flatten shows the flat pattern (bend allowance π/180 · angle · (R + K·T)) with dashed bend lines, bend notes and the overall size; holes and cuts through flat regions are included. Export the flat pattern to DXF with outline, cuts and bend lines on their own layers. + +**Weldments** +- Structural Member (Weldments tab): sweep standard profiles along sketch lines and arcs from one or more sketches, in groups. ISO (EN 10219 tubes and pipe, EN 10056 angles, UPE channels, IPE and HE A beams, flat and round bar) and ANSI (HSS, standard pipe, angles, C channels, W shapes, bar) sizes are generated from their standard dimensions, with corner radii. +- Corner treatments within a group (end miter, end butt 1 and 2, with a gap), and trimming and extending between groups. Profile rotation, mirror and pierce point. +- Trim/Extend members to a planar face or to other members (planar or coped), End Cap on tube and pipe ends, Gusset plates between two faces, and solid Fillet Bead welds along inside corners. +- Cut list in the design tree: identical members grouped with quantity, description, length, end angles and mass, exported as CSV. + +**Assemblies** +- File > New Assembly. Insert Components places parts from your cloud, this browser or your device (a part file or a STEP model); insert a part several times for several instances (bracket<1>, bracket<2>). The first component is fixed; the others float. +- Mates: coincident, parallel, perpendicular, distance, angle, concentric, tangent and lock, between faces, edges and the assembly planes, with aligned or anti-aligned alignment and values that take equations. The Mates folder in the design tree edits, flips, suppresses and deletes them. The status bar shows whether the assembly is under, fully or over defined; conflicting mates are marked. +- Drag a component (Alt+drag, or Rotate Component, turns it): it moves only as its mates allow, so a lid on a hinge pin turns about the pin. Fixed components do not move. +- Exploded view steps, interference detection with the overlapping volumes, a bill of materials (item, part, quantity, material; copy or download as CSV), mass properties with each part's material, measure, section view, and STEP (components as named solids) and STL export of the whole assembly. +- An assembly references its part files and keeps a copy of each, so it opens even when a part file is moved, shared or downloaded. Open Part edits a component's part; save it and go back, and the assembly takes the change (Update Parts reads the part files again). + **Assistant** - An AI design assistant in the right sidebar (Ctrl+J, or the sparkle button). Describe a part or a change ("a 100 × 60 × 8 mm plate with four M5 holes and rounded corners", "make the wall 3 mm", "fillet the top edges") and it builds it with the same features you use: sketches with exact geometry, relations and dimensions, extrudes, revolves, holes, fillets, chamfers, shells, patterns, mirrors, planes, lofts, sweeps and drafts, global variables and equations. - It reads the part precisely (feature parameters, sketch entities, faces and edges by name, measurements, mass properties), checks every change by rebuilding, undoes steps that would break a feature, and looks at the model to verify its work. @@ -41,9 +65,14 @@ It runs entirely in the browser. The geometry kernel is OpenCascade compiled to - Everything it changes in one message is a single undo step. It runs on Puter AI (Claude Opus 5.5). **Drawings** -- A 2D drawing sheet for each part (Drawing tab in the status bar): front, top, right, left, back, bottom and isometric views projected from the solid, with hidden lines and overall dimensions. -- Sheet sizes A4 to A1, Letter and Tabloid, standard scales, drag to arrange views, title block. -- Export to PDF or SVG. +- A 2D drawing sheet for each part: **Make Drawing** on the Drafting ribbon tab or the File menu (or the Drawing tab in the status bar). Front, top, right, left, back, bottom and isometric views projected from the solid, with hidden lines and overall dimensions. +- Projected views that stay aligned with their parent, section views (horizontal, vertical or aligned cutting line, the cut face hatched, labelled A-A with arrows), detail views (a magnified circle with its letter and scale) and auxiliary views. Per-view scale, caption, hidden and tangent edges; deleting a view takes the views made from it along, after a warning. +- Annotations: Smart Dimension on the sheet (horizontal, vertical, aligned, radius, diameter and angle) measured from the model's named edges, so dimensions follow the model when it changes and are marked when their geometry is gone; center marks and hole centerlines (automatic or by hand), centerlines, notes with leaders and hole callouts. +- Sheet sizes A4 to A1, Letter, Tabloid, ANSI C and D, standard scales, third or first angle projection, title block with material, scale, date, revision, sheet number and the projection symbol. +- Export to PDF, SVG or DXF. +- Assembly drawings: Make Drawing (or the Drawing tab in the status bar) in an assembly lays out its views on an A3 sheet with the bill of materials (item number, part number, material, quantity) on the title block; the table follows the assembly as components are added or removed. Views show the components where the mates put them, or exploded (a checkbox on the view); section views cut every component and hatch each its own way. Balloons label components with their item number: Auto Balloon numbers every component a view shows, Balloon numbers the one whose edge you click. +- Sheet metal drawings: a Flat Pattern view (Drafting tab, or Add view) shows the flat outline and cuts, the bend lines (dashed up, chain lines down) with their notes ("UP 90° R 1") and the overall size; it can be dimensioned and detailed like any view. +- Weldment drawings: a Cut List table (Annotation tab) with item, quantity, description, length and end angles, which follows the part, and balloons on members numbered from it. **Working with parts** - Design tree with rollback bar, suppress, rename, hide/show, edit and delete with dependency warnings. @@ -80,6 +109,7 @@ npm run build # type check, license check, production build in dist/ | Area | Where | Notes | |---|---|---| | Document model | `src/model` | Plain JSON parts: features, sketches, variables. Undo/redo by snapshots. Parameters may be expressions. | +| Assemblies | `src/model/assembly.ts`, `src/assembly`, `src/app/assembly`, `src/kernel/assembly.ts` | Assembly documents embed their parts as blobs. Rigid-body mate solver: damped least squares over mate residuals, six degrees of freedom per floating component, rank analysis for the definition, conflicts found by adding mates one at a time. Components' meshes are placed on the main thread (dragging needs no kernel call); the worker keeps the placed solids for measure, interference, mass, projection and export. | | Sketch solver | `src/sketch/solver.ts` | Minimum-norm damped Gauss-Newton per independent cluster, with a rank analysis for degrees of freedom and redundant or conflicting constraints. | | Profiles | `src/sketch/profiles.ts` | Planar face finding on the sketch graph; nested loops alternate material and holes. | | Geometry kernel | `src/kernel` | OpenCascade (WebAssembly) in a Web Worker. Each feature is cached under a hash of everything before it, so edits rebuild only what changed. Faces are named after the feature and sketch entity that created them. | diff --git a/src/parametric/src/app/actions.ts b/src/parametric/src/app/actions.ts index 1d6228a657..0a14468a43 100644 --- a/src/parametric/src/app/actions.ts +++ b/src/parametric/src/app/actions.ts @@ -14,6 +14,10 @@ import { REPO_URL, type RibbonTab } from './shell'; import type { App, AppHooks } from './app'; import type { Command } from './commands'; import { panelFor, startFeature } from './panels'; +import { isSurfaceFeature } from '../model/surfaces'; +import { surfaceCommands, surfacePanelFor } from './surface-panels'; +import { hideable, surfaceHideItem } from './surface-display'; +import { WELDMENTS_TAB, weldmentCommands, weldmentPanelFor } from './weldment-panels'; import { SketchPanel } from './sketch/panel'; import { MeasurePanel, OffsetPanel, SectionPanel, aboutDialog, convertEntities, equationsDialog, massPropertiesDialog, materialDialog, @@ -32,6 +36,8 @@ import type { PlaneRef } from '../model/types'; import { facePlaneRef } from './selection'; import { RELATION_LABELS } from '../sketch/ops'; import { CONSTRAINTS, CONSTRAINT_HINTS, runConstraint } from './sketch/constrain'; +import { SHEET_METAL_TAB, sheetMetalCommands } from './sheetmetal-panels'; +import { drawingCommands } from './drawing-commands'; const SKETCH_TOOLS: Record SkTool }> = { line: { label: 'Line', shortcut: 'L', desc: 'Sketch straight lines.', make: (ed) => lineTool(ed) }, @@ -252,6 +258,8 @@ export function registerCommands(app: App, files: FileOps) { feature('circularPattern', 'Circular Pattern', 'circularPattern', 'Repeat features around an axis.', { needsBody: true, keywords: 'polar array' }), feature('mirror', 'Mirror', 'mirror', 'Mirror features or the body about a plane.', { needsBody: true, keywords: 'symmetry' }), feature('plane', 'Plane', 'plane', 'Create a reference plane offset from a plane or face.', { keywords: 'reference geometry datum' }), + // ---- sheet metal ---- + ...sheetMetalCommands(app), // ---- evaluate ---- { id: 'measure', label: 'Measure', icon: 'measure', keywords: 'distance length angle area', description: 'Measure distances, lengths, angles and areas.', enabled: () => hasBody() && in3d(), run: () => { void app.openPanel(new MeasurePanel(app)); } }, { id: 'massProperties', label: 'Mass Properties', icon: 'massProperties', keywords: 'volume weight inertia center of mass', description: 'Volume, mass, centre of mass and inertia.', enabled: hasBody, run: () => massPropertiesDialog(app) }, @@ -267,14 +275,32 @@ export function registerCommands(app: App, files: FileOps) { // ---- view ---- { id: 'zoomFit', label: 'Zoom to Fit', icon: 'zoomFit', shortcut: 'F', run: () => (app.inDrawing ? app.drawing.fit() : app.viewport.zoomToFit()) }, // ---- drawing ---- - { id: 'openDrawing', label: 'Make Drawing', icon: 'file', keywords: 'drawing sheet 2d views print pdf', description: 'Open the 2D drawing of this part with standard views.', enabled: () => hasBody() || !!app.store.doc.drawing, run: () => app.openDrawing() }, + { id: 'openDrawing', label: 'Make Drawing', icon: 'makeDrawing', keywords: 'drawing sheet 2d views print pdf drafting engineering drawing orthographic', description: 'Open the 2D drawing of this part: standard views, sections, details and dimensions, exported to PDF, SVG or DXF.', enabled: () => hasBody() || !!app.store.doc.drawing, run: () => app.openDrawing() }, { id: 'backToModel', label: 'Back to Model', icon: 'part', enabled: () => app.inDrawing, run: () => app.closeDrawing() }, - { id: 'drawing:arrange', label: 'Standard Views', icon: 'viewOrientation', description: 'Arrange front, top, right and isometric views at a fitting scale.', enabled: () => app.inDrawing && hasBody(), run: () => app.drawing.relayout() }, + { id: 'drawing:arrange', label: 'Standard Views', icon: 'viewOrientation', description: 'Arrange front, top, right and isometric views at a fitting scale.', enabled: () => app.inDrawing && hasBody(), run: () => void app.drawing.arrange() }, ...(['front', 'top', 'right', 'left', 'back', 'bottom', 'isometric'] as const).map((k): Command => ({ id: `drawing:add:${k}`, label: `${k[0].toUpperCase()}${k.slice(1)} View`, icon: k === 'isometric' ? 'viewIso' : `view${k[0].toUpperCase()}${k.slice(1)}`, enabled: () => app.inDrawing && hasBody(), run: () => app.drawing.addView(k), })), { id: 'drawing:pdf', label: 'Export PDF', icon: 'download', keywords: 'print drawing', enabled: () => !!app.store.doc.drawing && app.inDrawing, run: () => app.drawing.exportPdf() }, { id: 'drawing:svg', label: 'Export SVG', icon: 'download', enabled: () => !!app.store.doc.drawing && app.inDrawing, run: () => app.drawing.exportSvg() }, + { id: 'drawing:dxf', label: 'Export DXF', icon: 'download', keywords: 'drawing autocad cad 2d', description: 'Save the drawing sheet as a DXF file for 2D CAD programs.', enabled: () => !!app.store.doc.drawing && app.inDrawing, run: () => app.drawing.exportDxf() }, + ...([ + ['projected', 'drawingProjected', 'Projected View', 'Add a view projected from a view of the drawing, aligned with it.', 'orthographic drawing'], + ['section', 'drawingSection', 'Section View', 'Cut a view of the drawing along a line and show the cut face hatched.', 'drawing cut hatch cutting plane'], + ['detail', 'drawingDetail', 'Detail View', 'Show a circle of a view of the drawing magnified.', 'drawing zoom magnify enlarge'], + ['auxiliary', 'drawingAuxiliary', 'Auxiliary View', 'Add a view looking square to an inclined edge of a view.', 'drawing inclined'], + ['dimension', 'smartDimension', 'Smart Dimension', 'Dimension edges, circles and points of the drawing views: distances, radii, diameters and angles.', 'drawing dimension measure annotate'], + ['centerMark', 'drawingCenterMark', 'Center Mark', 'Mark the centre of a circle or arc in a drawing view.', 'drawing annotate centre'], + ['centerline', 'centerline', 'Centerline', 'Draw a centerline between two parallel edges in a drawing view.', 'drawing annotate axis'], + ['note', 'text', 'Note', 'Add text to the drawing sheet, with an optional leader arrow.', 'drawing annotate text label leader'], + ['holeCallout', 'drawingHoleCallout', 'Hole Callout', 'Label a hole with its size, depth and counterbore or countersink.', 'drawing annotate hole diameter thread'], + ] as const).map(([k, ic, label, description, keywords]): Command => ({ + id: `drawing:${k}`, label, icon: ic, description, keywords, + enabled: () => app.inDrawing && hasBody() && !!app.store.doc.drawing?.views.length, + checked: () => app.inDrawing && app.drawing.tool?.kind === k, + run: () => app.drawing.startTool(k), + })), + ...drawingCommands(app), { id: 'zoomIn', label: 'Zoom In', icon: 'zoomIn', shortcut: 'Shift+Z', run: () => (app.inDrawing ? app.drawing.zoomBy(1.25) : app.viewport.zoomBy(0.8)) }, { id: 'zoomOut', label: 'Zoom Out', icon: 'zoomOut', shortcut: 'Z', run: () => (app.inDrawing ? app.drawing.zoomBy(0.8) : app.viewport.zoomBy(1.25)) }, // No shortcut: Ctrl+Shift+Z is Redo. @@ -326,6 +352,10 @@ export function registerCommands(app: App, files: FileOps) { { id: 'shortcutsF1', label: 'Keyboard Shortcuts', hidden: true, shortcut: 'F1', run: () => shortcutsDialog(app) }, { id: 'github', label: 'Source Code on GitHub', icon: 'github', run: () => { window.open(REPO_URL, '_blank', 'noopener'); } }, { id: 'about', label: 'About Parametric', icon: 'info', run: () => aboutDialog() }, + // ---- surfaces ---- + ...surfaceCommands(app), + // ---- weldments ---- + ...weldmentCommands(app), ); void noModes; void VIEWS; @@ -393,13 +423,37 @@ export const RIBBON: RibbonTab[] = [ id: 'evaluate', label: 'Evaluate', groups: [[{ cmd: 'measure' }, { cmd: 'massProperties' }, { cmd: 'sectionView' }], [{ cmd: 'equations' }, { cmd: 'material' }]], }, + SHEET_METAL_TAB, + { + id: 'surfaces', label: 'Surfaces', + groups: [ + [{ cmd: 'surfaceExtrude' }, { cmd: 'surfaceRevolve' }, { stack: [{ cmd: 'surfaceSweep' }, { cmd: 'surfaceLoft' }, { cmd: 'surfacePlanar' }] }], + [{ stack: [{ cmd: 'surfaceOffset' }, { cmd: 'surfaceFill' }, { cmd: 'surfaceKnit' }] }, { stack: [{ cmd: 'surfaceTrim' }, { cmd: 'surfaceExtend' }, { cmd: 'deleteFace' }] }], + [{ cmd: 'thicken' }, { stack: [{ cmd: 'thickenCut' }, { cmd: 'surfaceCut' }] }], + ], + }, + WELDMENTS_TAB, { - id: 'drawing', label: 'Drawing', + // Shown in the model too (with Make Drawing first), so the drawing is found from the ribbon. + id: 'drawing', label: 'Drafting', groups: [ - [{ cmd: 'drawing:arrange' }, { stack: [{ cmd: 'drawing:add:front' }, { cmd: 'drawing:add:top' }, { cmd: 'drawing:add:right' }] }, { stack: [{ cmd: 'drawing:add:isometric' }, { cmd: 'drawing:add:left' }, { cmd: 'drawing:add:back' }] }], - [{ cmd: 'drawing:pdf' }, { cmd: 'drawing:svg' }], + [{ cmd: 'openDrawing' }, { cmd: 'drawing:arrange' }], + [{ stack: [{ cmd: 'drawing:add:front' }, { cmd: 'drawing:add:top' }, { cmd: 'drawing:add:right' }] }, { stack: [{ cmd: 'drawing:add:isometric' }, { cmd: 'drawing:add:left' }, { cmd: 'drawing:add:back' }] }], + [{ cmd: 'drawing:projected' }, { cmd: 'drawing:section' }, { stack: [{ cmd: 'drawing:detail' }, { cmd: 'drawing:auxiliary' }, { cmd: 'drawing:flat' }] }], + [{ cmd: 'drawing:pdf' }, { stack: [{ cmd: 'drawing:svg' }, { cmd: 'drawing:dxf' }] }], [{ cmd: 'zoomFit' }, { cmd: 'backToModel' }], ], + labels: ['Drawing', 'Model Views', 'Views', 'Export', ''], + }, + { + // Only in the drawing. + id: 'annotation', label: 'Annotation', + groups: [ + [{ cmd: 'drawing:dimension' }], + [{ stack: [{ cmd: 'drawing:centerMark' }, { cmd: 'drawing:centerline' }] }, { stack: [{ cmd: 'drawing:note' }, { cmd: 'drawing:holeCallout' }] }], + [{ stack: [{ cmd: 'drawing:balloon' }, { cmd: 'drawing:autoBalloon' }] }, { stack: [{ cmd: 'drawing:bom' }, { cmd: 'drawing:cutList' }] }], + [{ cmd: 'drawing:pdf' }, { cmd: 'backToModel' }], + ], }, { id: 'view', label: 'View', @@ -421,8 +475,8 @@ export function buildMenus(app: App): { label: string; items: () => MenuItem[] } return [ { label: 'File', items: () => [ - m('new'), m('open'), m('openDevice'), { label: 'Recent', icon: 'files', submenu: () => app.recentMenu() }, sep, - m('save'), m('saveAs'), m('downloadPart'), sep, m('importStep'), m('exportStep'), m('exportStl'), sep, m('openDrawing'), m('drawing:pdf'), sep, m('share'), m('rename'), m('properties'), + m('new'), ...(c.get('newAssembly') ? [m('newAssembly')] : []), m('open'), m('openDevice'), { label: 'Recent', icon: 'files', submenu: () => app.recentMenu() }, sep, + m('save'), m('saveAs'), m('downloadPart'), sep, m('importStep'), m('exportStep'), m('exportStl'), sep, m('openDrawing'), m('drawing:pdf'), m('drawing:dxf'), sep, m('share'), m('rename'), m('properties'), ], }, { @@ -450,7 +504,10 @@ export function buildMenus(app: App): { label: string; items: () => MenuItem[] } { label: 'Features', icon: 'fillet', submenu: () => [m('fillet'), m('chamfer'), m('hole'), m('shell'), m('draft')] }, { label: 'Pattern/Mirror', icon: 'linearPattern', submenu: () => [m('linearPattern'), m('circularPattern'), m('mirror')] }, { label: 'Reference Geometry', icon: 'plane', submenu: () => [m('plane')] }, + { label: 'Surface', icon: 'surfaceExtrude', submenu: () => ['surfaceExtrude', 'surfaceRevolve', 'surfaceSweep', 'surfaceLoft', 'surfacePlanar', 'surfaceOffset', 'surfaceFill', 'surfaceTrim', 'surfaceExtend', 'surfaceKnit', 'thicken', 'thickenCut', 'surfaceCut', 'deleteFace'].map((id) => m(id)) }, + { label: 'Weldments', icon: 'structuralMember', submenu: () => [m('structuralMember'), m('trimExtend'), m('endCap'), m('gusset'), m('weldBead'), m('cutList')] }, sep, m('importStep'), + ...(c.get('insertComponent') ? [sep, m('insertComponent'), m('mate')] : []), ], }, { @@ -511,13 +568,13 @@ export function contextItems(app: App, target: 'viewport' | 'feature' | 'referen const used = sketchesOf(app, f); // A sketch a feature absorbed is hidden though it was never hidden by hand: the menu says Show. const shown = app.isShown(f); - const showable = ids.filter((x) => ['sketch', 'plane'].includes(app.store.feature(x)?.type ?? '')); + const showable = ids.filter((x) => hideable(app.store.feature(x))); return [ f.type === 'sketch' ? { label: 'Edit Sketch', icon: 'sketch', run: () => app.editSketch(id) } : { label: 'Edit Feature', icon: 'edit', run: () => app.editFeature(id) }, ...used.map((sk): MenuItem => ({ label: used.length === 1 ? 'Edit Sketch' : `Edit ${sk.name}`, icon: 'sketch', run: () => app.editSketch(sk.id) })), { label: 'Rename', icon: 'text', shortcut: 'F2', run: () => app.startRename(id) }, sep, - ...(f.type === 'sketch' || f.type === 'plane' ? [{ label: shown ? 'Hide' : 'Show', icon: shown ? 'eyeOff' : 'eye', run: () => app.toggleHidden(showable, shown) } as MenuItem] : []), + ...(hideable(f) ? [surfaceHideItem(app, f) ?? { label: shown ? 'Hide' : 'Show', icon: shown ? 'eyeOff' : 'eye', run: () => app.toggleHidden(showable, shown) } as MenuItem] : []), { label: f.suppressed ? 'Unsuppress' : 'Suppress', icon: f.suppressed ? 'eye' : 'eyeOff', run: () => app.toggleSuppress(ids, !f.suppressed) }, { label: 'Roll Back to Here', icon: 'upToLine', run: () => app.setRollback(idx) }, { label: 'Roll to End', icon: 'downToLine', disabled: app.store.doc.rollback == null, run: () => app.setRollback(null) }, @@ -611,7 +668,7 @@ export function makeHooks(app: App): AppHooks { ribbonTabs: RIBBON, menus: buildMenus(app), sketchPanel: () => new SketchPanel(app), - editFeaturePanel: (f) => panelFor(app, f, true), + editFeaturePanel: (f) => (isSurfaceFeature(f) ? surfacePanelFor(app, f, true) : panelFor(app, f, true) ?? weldmentPanelFor(app, f, true)), planePickPanel: (done) => new PlanePickPanel(app, done), contextItems: (t, id) => contextItems(app, t, id), quickActions: () => quickActions(app), diff --git a/src/parametric/src/app/app.ts b/src/parametric/src/app/app.ts index 8cc48053cc..1d0e8cb0cc 100644 --- a/src/parametric/src/app/app.ts +++ b/src/parametric/src/app/app.ts @@ -32,8 +32,18 @@ import { Viewport, type VPEvent } from './viewport'; import { type Location } from '../platform/files'; import { setWindowTitle } from '../platform/puter'; import { DEFAULT_SETTINGS, normalizeSettings, type Settings } from './settings'; +import { applySurfaceColors, hiddenSurfaceFeatures } from './surface-display'; +import type { AssemblyMode } from './assembly/mode'; export { DEFAULT_SETTINGS, type Settings } from './settings'; +/** What the left pane shows as the design tree: a part's feature tree or an assembly's tree. */ +export interface DesignTree { + el: HTMLElement; + render(): void; + startRename(id: Id): void; + targets(id: Id): Id[]; +} + export interface Colors { sketchUnder: number[]; sketchFull: number[]; @@ -90,7 +100,7 @@ export class App { shell!: Shell; renderer!: Renderer; viewport!: Viewport; - tree!: FeatureTree; + tree!: DesignTree; hooks!: AppHooks; panel: PropertyPanel | null = null; sketchEditor: SketchEditor | null = null; @@ -106,6 +116,8 @@ export class App { frames: Record = {}; /** Sketches with projected model geometry, as the last rebuild placed it. */ linkedSketches: NonNullable = {}; + /** Structural members of the last build, for the weldment cut list. */ + weldments: NonNullable = []; bbox: { min: Vec3; max: Vec3 } | null = null; colors!: Colors; kernelReady = false; @@ -125,6 +137,13 @@ export class App { onDocumentChanged: (reason: string) => void = () => {}; /** Renames the part and its saved file, as Rename Part does (set by the file operations). */ renamePart: ((name: string) => Promise) | null = null; + /** The open assembly's interface and geometry; null while a part is open (set up by the assembly module). */ + assembly: AssemblyMode | null = null; + /** Called when a document is loaded, to switch between part and assembly mode (set by the assembly module). */ + syncDocumentKind: () => void = () => {}; + /** Ribbon tabs shown while an assembly is open, and those only an assembly has. */ + assemblyTabs = new Set(); + assemblyOnlyTabs = new Set(); constructor() { this.kernel = new KernelClient(); @@ -246,6 +265,7 @@ export class App { const c = this.store.doc.color; this.shownColor = c; this.renderer.modelColor = c ? parseColor(c) : null; + applySurfaceColors(this); this.renderer.requestRender(); } @@ -362,7 +382,7 @@ export class App { b.addEventListener('click', () => this.setRibbonTab(t.id)); this.shell.cmTabs.append(b); } - // The arrow keys skip the hidden tabs (the Drawing tab in the model, and the reverse). + // The arrow keys skip the hidden tabs (the Annotation tab in the model, and the model tabs in the drawing). tabKeys(this.shell.cmTabs); this.setRibbonTab(this.ribbonTab); } @@ -371,10 +391,22 @@ export class App { this.ribbonTab = id; for (const b of this.shell.cmTabs.querySelectorAll('[role="tab"]')) { b.setAttribute('aria-selected', String(b.dataset.tab === id)); - // The drawing has its own tab; model tabs are hidden while it is open. - b.hidden = (b.dataset.tab === 'drawing') !== (id === 'drawing'); + // The Drafting tab shows everywhere (Make Drawing is on it); Annotation only in the drawing, + // and the model tabs only in the model. + const tab = b.dataset.tab!; + b.hidden = tab === 'drawing' ? false : (tab === 'annotation') !== this.inDrawing; + // An assembly shows the tabs it uses; a part none of the assembly's own. + if (!b.hidden) b.hidden = this.assembly ? !this.assemblyTabs.has(tab) : this.assemblyOnlyTabs.has(tab); } syncTabStops(this.shell.cmTabs); + // A tab past the edge of a narrow strip (a phone) scrolls into view when chosen. + const strip = this.shell.cmTabs; + const sel = strip.querySelector('[role="tab"][aria-selected="true"]'); + if (sel && strip.scrollWidth > strip.clientWidth) { + const l = sel.getBoundingClientRect().left - strip.getBoundingClientRect().left + strip.scrollLeft, r = l + sel.offsetWidth; + if (l < strip.scrollLeft) strip.scrollLeft = l - 8; + else if (r > strip.scrollLeft + strip.clientWidth) strip.scrollLeft = r - strip.clientWidth + 8; + } const tab = this.hooks.ribbonTabs.find((t) => t.id === id)!; renderRibbon(this.shell.cmTools, tab, this.commands); } @@ -442,7 +474,7 @@ export class App { return [t('showPlanes'), t('showOrigin'), t('showSketches'), t('showRelations'), t('showDimensions')]; } - flyout!: FeatureTree; + flyout!: DesignTree; private flyoutEl!: HTMLElement; private flyoutOpen = false; @@ -810,6 +842,7 @@ export class App { previous.abort(); // A section belongs to the replaced part, not to the next document's geometry. this.renderer.section = null; + this.syncDocumentKind(); this.applyModelColor(); this.refreshAll(); } @@ -888,6 +921,7 @@ export class App { private async rebuild() { if (!this.kernelReady) return; + if (this.assembly) { await this.assembly.rebuild(); return; } const resolved = this.store.resolve(); this.resolveErrors = resolved.errors; const upTo = this.buildLimit(); @@ -946,6 +980,8 @@ export class App { buildVersion = 0; /** Incremented after a rebuild that changed the body (drawings re-project when it changes). */ geometryVersion = 0; + /** Features whose surface bodies were hidden at the last rebuild. */ + private hiddenSurfaces = ''; drawing!: DrawingWorkspace; get inDrawing(): boolean { @@ -960,7 +996,7 @@ export class App { this.syncSheetTabs(); this.setRibbonTab('drawing'); this.showDrawingPanel(); - this.setStatus('Drawing. Drag views to arrange them; export to PDF or SVG from the Drawing tab.'); + this.setStatus('Drawing. Drag views to arrange them; add views and annotations, and export to PDF, SVG or DXF, from the Drafting and Annotation tabs.'); this.commands.changed(); } @@ -968,7 +1004,7 @@ export class App { if (!this.drawing.active) return; this.drawing.close(); this.syncSheetTabs(); - this.setRibbonTab('features'); + this.setRibbonTab(this.assembly ? 'assembly' : 'features'); this.showLeft('tree'); this.setStatus('Ready'); this.commands.changed(); @@ -1002,8 +1038,11 @@ export class App { private applyBuild(res: BuildResult, ms: number) { this.buildVersion++; - // The same body (a rename, a suppressed sketch, a colour) needs no new drawing projections. - if (!res.meshUnchanged) this.geometryVersion++; + // The same body (a rename, a suppressed sketch, a colour) needs no new drawing projections; + // a surface body hidden or shown does (drawings leave hidden ones out). + const hiddenSurfaces = hiddenSurfaceFeatures(this).join(','); + if (!res.meshUnchanged || hiddenSurfaces !== this.hiddenSurfaces) this.geometryVersion++; + this.hiddenSurfaces = hiddenSurfaces; this.statuses = new Map(res.status.map((s) => [s.id, s])); for (const [id, err] of this.resolveErrors) { // A suppressed feature is not built, so its values are not used either. @@ -1013,6 +1052,7 @@ export class App { this.edges = res.edges; this.frames = res.frames; this.linkedSketches = res.sketches ?? {}; + this.weldments = res.weldments ?? []; this.bbox = res.bbox; // An unchanged mesh is the one the worker last sent, which is not the one // shown when its result was dropped (a part opened again while its first @@ -1022,6 +1062,7 @@ export class App { this.shownMesh = mesh; this.vertices = mesh?.vertices ?? new Float32Array(0); this.renderer.setModel(mesh, res.faces.length, res.edges.length); + applySurfaceColors(this); } const r = res.bbox ? Math.hypot(res.bbox.max[0] - res.bbox.min[0], res.bbox.max[1] - res.bbox.min[1], res.bbox.max[2] - res.bbox.min[2]) : 100; this.renderer.camera.sceneRadius = Math.max(r, 100); @@ -1060,6 +1101,31 @@ export class App { if (this.inDrawing) void this.drawing.refresh(); } + /** Shows the part's body again after a mode showed another mesh in its place (the flat pattern). */ + showModelMesh() { + this.renderer.setModel(this.shownMesh, this.faces.length, this.edges.length); + if (this.lastBuildResult) this.bbox = this.lastBuildResult.bbox; + this.viewport.refreshStates(); + this.renderer.requestRender(); + } + + /** + * Shows geometry built outside the part rebuild (an assembly's placed + * components) as the model: picking, selection and the view work on it. + */ + setModelGeometry(mesh: MeshData | null, faces: FaceInfo[], edges: EdgeInfo[], bbox: { min: Vec3; max: Vec3 } | null) { + this.faces = faces; + this.edges = edges; + this.frames = {}; + this.linkedSketches = {}; + this.bbox = bbox; + this.shownMesh = mesh; + this.vertices = mesh?.vertices ?? new Float32Array(0); + this.renderer.setModel(mesh, faces.length, edges.length); + const r = bbox ? Math.hypot(bbox.max[0] - bbox.min[0], bbox.max[1] - bbox.min[1], bbox.max[2] - bbox.min[2]) : 100; + this.renderer.camera.sceneRadius = Math.max(r, 100); + } + featureStatus(id: Id): FeatureStatus | null { return this.statuses.get(id) ?? null; } @@ -1136,7 +1202,10 @@ export class App { if (this.panel) for (const b of this.panel.boxes) for (const it of b.items) { const r = it.item?.kind === 'face' || it.item?.kind === 'edge' ? remapItem(it.item, this.faces, this.edges) : it.item; if (r) out.push(r); + if (it.highlights) out.push(...it.highlights()); } + // The faces a selected mate references. + if (this.assembly) out.push(...this.assembly.highlights()); return out; } @@ -1159,6 +1228,8 @@ export class App { } describe(it: SelItem): string { + const asm = this.assembly?.describe(it); + if (asm) return asm; const u = UNIT_SYSTEMS[this.store.doc.units], dec = this.store.doc.decimals; // Small values keep significant digits (a 5 mm edge in metres is 0.00500 m, not 0.01 m). const len = (v: number) => `${formatGroup([v / u.scale], dec)[0]} ${u.length}`; @@ -1178,6 +1249,11 @@ export class App { case 'plane': return it.ref.kind === 'base' ? BASE_PLANE_NAMES[it.ref.plane] : this.store.feature(it.ref.id)?.name ?? 'Plane'; case 'origin': return 'Origin'; case 'feature': return this.store.feature(it.id)?.name ?? ''; + case 'skseg': { + const sk = this.store.feature(it.sketch); + const e = sk?.type === 'sketch' ? sk.entities.find((x) => x.id === it.entity) : undefined; + return `${e?.t === 'arc' ? 'Arc' : 'Line'} of ${sk?.name ?? 'a sketch'}`; + } default: return ''; } } @@ -1592,6 +1668,7 @@ export class App { } async deleteFeatures(ids: Id[]) { + if (this.assembly) return this.assembly.deleteItems(ids); const signal = this.documentSignal; const doc = this.store.doc; const del = new Set(ids); diff --git a/src/parametric/src/app/assembly/index.ts b/src/parametric/src/app/assembly/index.ts new file mode 100644 index 0000000000..0c9a4d3895 --- /dev/null +++ b/src/parametric/src/app/assembly/index.ts @@ -0,0 +1,331 @@ +// Sets up assemblies in the app: the New Assembly command, the Assembly +// ribbon tab and commands, switching the interface between part and +// assembly documents, and the context menus of components and mates. + +import { Boxes, Expand, ListOrdered, Magnet, Move3d, PackagePlus, RefreshCw, SquaresIntersect, SquareArrowOutUpRight } from 'lucide'; +import { type AssemblyDocument, MATE_LABELS, asAssembly, mateComps } from '../../model/assembly'; +import type { Id } from '../../model/types'; +import { type Location, sameLocation } from '../../platform/files'; +import { addIcons, type IconNode } from '../../ui/icons'; +import type { MenuItem } from '../../ui/menu'; +import { toast } from '../../ui/overlay'; +import type { App, AppHooks } from '../app'; +import type { Command } from '../commands'; +import type { FileOps } from '../fileops'; +import type { RibbonTab } from '../shell'; +import { AssemblyMode } from './mode'; +import { ASSEMBLY_SOURCE, EXPLODED_SOURCE, assemblySource } from '../drawing-sources'; +import { ExplodePanel, InterferencePanel, MatePanel, MovePanel, assemblyMassDialog, bomDialog, insertComponent, pickPart, updateParts } from './panels'; + +addIcons({ + assembly: Boxes as unknown as IconNode, + insertComponent: PackagePlus as unknown as IconNode, + mate: Magnet as unknown as IconNode, + moveComponent: Move3d as unknown as IconNode, + rotateComponent: 'rotate', + explode: Expand as unknown as IconNode, + interference: SquaresIntersect as unknown as IconNode, + bom: ListOrdered as unknown as IconNode, + updateParts: RefreshCw as unknown as IconNode, + openPart: SquareArrowOutUpRight as unknown as IconNode, + angle: [['path', { d: 'M4 20h16M4 20L15 5' }], ['path', { d: 'M11 20a7 7 0 0 0-2.4-5.3' }]], + 'mate:coincident': [['rect', { x: 6, y: 4, width: 12, height: 8, rx: 0.5, class: 'a' }], ['rect', { x: 4, y: 12, width: 16, height: 8, rx: 0.5 }]], + 'mate:parallel': [['path', { d: 'M4 17L14 7M10 21L20 11' }]], + 'mate:perpendicular': [['path', { d: 'M4 20h16M12 20V4' }], ['path', { d: 'M12 16h4v4' }]], + 'mate:tangent': [['circle', { cx: 12, cy: 10, r: 6, class: 'a' }], ['path', { d: 'M3 16h18' }]], + 'mate:concentric': [['circle', { cx: 12, cy: 12, r: 8 }], ['circle', { cx: 12, cy: 12, r: 3.5, class: 'a' }]], + 'mate:distance': 'smartDimension', + 'mate:angle': [['path', { d: 'M4 20h16M4 20L15 5' }], ['path', { d: 'M11 20a7 7 0 0 0-2.4-5.3' }]], + 'mate:lock': 'lock', +}); + +/** The tabs an assembly shows; part tabs (sketch, features...) are hidden. */ +const ASSEMBLY_TABS = ['assembly', 'evaluate', 'view', 'drawing', 'annotation']; + +export const ASSEMBLY_TAB: RibbonTab = { + id: 'assembly', label: 'Assembly', + groups: [ + [{ cmd: 'insertComponent' }, { cmd: 'mate' }], + [{ stack: [{ cmd: 'moveComponent' }, { cmd: 'rotateComponent' }] }, { stack: [{ cmd: 'explodedView' }, { cmd: 'toggleExplode' }] }], + [{ cmd: 'interference' }, { cmd: 'billOfMaterials' }], + [{ stack: [{ cmd: 'updateParts' }, { cmd: 'openPart' }] }], + ], +}; + +/** + * Commands of parts that also work in an assembly (files, history, the view, + * measuring...). Every other command is disabled while an assembly is open. + */ +const SHARED = new Set([ + 'new', 'newAssembly', 'open', 'openDevice', 'save', 'saveAs', 'downloadPart', 'exportStep', 'exportStl', 'rename', 'share', 'properties', 'assistant', + 'undo', 'redo', 'redo2', 'rebuild', 'forceRebuild', 'repeat', 'delete', 'equations', 'options', 'measure', 'massProperties', 'sectionView', + 'zoomFit', 'zoomIn', 'zoomOut', 'previousView', 'normalTo', 'viewOrientation', 'displayStyle', 'toggleVisibility', 'perspective', 'showPlanes', 'showOrigin', + 'toggleTree', 'shortcutBar', 'shortcuts', 'shortcutsF1', 'github', 'about', 'openDrawing', 'backToModel', +]); +const sharedCommand = (id: string) => SHARED.has(id) || /^(view[A-Z]|style:|theme:|asm:|drawing:)/.test(id); + +export function installAssembly(app: App, files: FileOps, hooks: AppHooks) { + const c = app.commands; + const mode = () => app.assembly; + const asm = () => !!app.assembly; + const doc = (): AssemblyDocument | null => (app.assembly ? asAssembly(app.store.doc) : null); + /** Components the selection names: rows in the tree, or faces and edges in the graphics area. */ + const selectedComps = (): Id[] => { + const m = mode(); + if (!m) return []; + const out = new Set(); + for (const it of app.selection.items) { + if (it.kind === 'feature' && m.component(it.id)) out.add(it.id); + if (it.kind === 'face') { const x = m.faceComponent(it.index); if (x) out.add(x.id); } + if (it.kind === 'edge') { const x = m.edgeComponent(it.index); if (x) out.add(x.id); } + } + return [...out]; + }; + const hasComps = () => !!doc()?.components.length; + const openPanelWhenBuilt = (make: () => import('../pm').PropertyPanel | null) => { + void app.whenBuilt().then(() => { const p = mode() ? make() : null; if (p) void app.openPanel(p); }); + }; + + // Part commands are disabled in an assembly, with the reason in the status bar when one is tried. + for (const cmd of c.all()) { + if (sharedCommand(cmd.id)) continue; + const enabled = cmd.enabled; + cmd.enabled = () => !app.assembly && (enabled ? enabled() : true); + } + // Mass properties of an assembly weigh each component with its own material. + const mass = c.get('massProperties'); + if (mass) { + const run = mass.run; + mass.run = () => (app.assembly ? assemblyMassDialog(app.assembly) : run()); + } + + const commands: Command[] = [ + { id: 'newAssembly', label: 'New Assembly', icon: 'assembly', keywords: 'assembly components mates new', description: 'Start a new assembly of parts.', run: () => files.newAssembly() }, + { + id: 'insertComponent', label: 'Insert Components', icon: 'insertComponent', keywords: 'assembly add part component place instance', description: 'Place a part (or another instance of one) in the assembly.', + enabled: asm, + run: async () => { + const m = mode(); + if (!m) return; + const picked = await pickPart(app); + if (picked && app.assembly === m) insertComponent(m, picked); + }, + }, + { + id: 'mate', label: 'Mate', icon: 'mate', keywords: 'constraint coincident concentric distance angle parallel assembly', description: 'Position components relative to each other with mates.', + enabled: () => asm() && hasComps(), + run: () => openPanelWhenBuilt(() => new MatePanel(mode()!)), + }, + { id: 'moveComponent', label: 'Move Component', icon: 'moveComponent', keywords: 'drag translate', description: 'Drag components to move them within their mates.', enabled: () => asm() && hasComps(), run: () => openPanelWhenBuilt(() => new MovePanel(mode()!, false)) }, + { id: 'rotateComponent', label: 'Rotate Component', icon: 'rotateComponent', keywords: 'drag turn', description: 'Drag components to turn them within their mates.', enabled: () => asm() && hasComps(), run: () => openPanelWhenBuilt(() => new MovePanel(mode()!, true)) }, + { id: 'explodedView', label: 'Exploded View', icon: 'explode', keywords: 'explode step', description: 'Add a step that moves components apart to show how they fit.', enabled: () => asm() && hasComps(), run: () => openPanelWhenBuilt(() => new ExplodePanel(mode()!)) }, + { + id: 'toggleExplode', label: 'Explode/Collapse', icon: 'explode', keywords: 'exploded view collapse', description: 'Switch between the exploded and the assembled view.', + enabled: () => !!doc()?.explode.length, checked: () => !!doc()?.exploded, + run: () => { const m = mode(); if (m) m.commit(m.doc.exploded ? 'Collapse' : 'Explode', (d) => { d.exploded = !d.exploded; }, false); }, + }, + { id: 'interference', label: 'Interference Detection', icon: 'interference', keywords: 'clash overlap collision check', description: 'Find components that overlap, and by how much.', enabled: () => asm() && hasComps(), run: () => openPanelWhenBuilt(() => new InterferencePanel(mode()!)) }, + { id: 'billOfMaterials', label: 'Bill of Materials', icon: 'bom', keywords: 'bom parts list quantity', description: 'The parts of the assembly with their quantities and materials.', enabled: asm, run: () => { const m = mode(); if (m) void bomDialog(m); } }, + { + id: 'updateParts', label: 'Update Parts', icon: 'updateParts', keywords: 'reload refresh rebuild references', description: 'Read the part files again and take their latest saved versions.', + enabled: () => asm() && !!doc()?.parts.some((p) => p.source), + run: async () => { + const m = mode(); + if (!m) return; + const r = await updateParts(m); + const parts = (n: string[]) => n.join(', '); + if (r.updated.length) toast({ kind: 'success', message: `Updated ${parts(r.updated)}.` }); + else if (!r.missing.length) toast({ message: 'All parts are up to date.' }); + if (r.missing.length) toast({ kind: 'warning', message: `The part files of ${parts(r.missing)} could not be read: the copies kept in the assembly are used.`, timeout: 9000 }); + }, + }, + { + id: 'openPart', label: 'Open Part', icon: 'openPart', keywords: 'edit part component', description: 'Open the part of the selected component to edit it. Save it, then come back: the assembly takes the change.', + enabled: () => asm() && selectedComps().length === 1, + run: () => void openPart(selectedComps()[0]), + }, + { + id: 'fixComponent', label: 'Fix', icon: 'lock', keywords: 'ground anchor', description: 'Fix the selected components where they are.', + enabled: () => selectedComps().some((id) => !mode()!.component(id)?.fixed), + run: () => { const ids = selectedComps(); mode()?.commit('Fix', (d) => { for (const x of d.components) if (ids.includes(x.id)) x.fixed = true; }); }, + }, + { + id: 'floatComponent', label: 'Float', icon: 'unlock', keywords: 'unfix free', description: 'Let the selected components move.', + enabled: () => selectedComps().some((id) => mode()!.component(id)?.fixed), + run: () => { const ids = selectedComps(); mode()?.commit('Float', (d) => { for (const x of d.components) if (ids.includes(x.id)) x.fixed = false; }); }, + }, + ]; + c.register(...commands); + + // ---------- Open Part ---------- + + /** The assembly the user came from, while one of its parts is open. */ + let returnTo: { location: Location; name: string } | null = null; + async function openPart(compId: Id) { + const m = mode(); + const comp = m?.component(compId); + const part = comp && m!.doc.parts.find((p) => p.id === comp.part); + if (!m || !part) return; + const from = app.location ? { location: app.location, name: m.doc.name } : null; + // No part file (an inserted STEP model), or its file was not found: the copy kept in the assembly opens. + if (!part.source || m.missingParts.has(part.id)) { + const pd = m.partDoc(part.id); + if (!pd) return; + if (!(await files.confirmDiscard('open the part'))) return; + app.loadDocument(structuredClone(pd), null); + app.store.dirty = true; + const why = part.source ? `The part file of ${part.name} was not found (moved or deleted?): the copy kept in the assembly opened.` : `${part.name} has no part file of its own: it opened as a copy.`; + toast({ message: `${why} Save it, then insert the saved part in the assembly to use your changes.`, timeout: 10000 }); + return; + } + if (!(await files.confirmDiscard('open the part'))) return; + await files.openLocation(part.source as Location, part.name); + if (asAssembly(app.store.doc) || !from) return; + returnTo = from; + toast({ + message: `Editing ${part.name} from ${from.name}. Save the part, then go back: the assembly takes the change.`, timeout: 0, + actions: [{ label: `Back to ${from.name}`, primary: true, run: () => { const r = returnTo; returnTo = null; if (r) void files.openLocation(r.location, r.name); } }], + }); + } + + // ---------- switching between part and assembly mode ---------- + + let partTree = app.tree, partFlyout = app.flyout; + app.assemblyTabs = new Set(ASSEMBLY_TABS); + app.assemblyOnlyTabs = new Set(['assembly']); + hooks.ribbonTabs.unshift(ASSEMBLY_TAB); + + /** Part Properties is named for the open document. */ + const properties = c.get('properties'); + const partPropertiesLabel = properties?.label ?? ''; + const enter = () => { + if (properties) properties.label = 'Assembly Properties...'; + const m = new AssemblyMode(app); + m.onEdit = (id) => { + const mt = m.doc.mates.find((x) => x.id === id); + if (mt) { openPanelWhenBuilt(() => new MatePanel(m, mt)); return; } + const st = m.doc.explode.find((x) => x.id === id); + if (st) openPanelWhenBuilt(() => new ExplodePanel(m, st)); + }; + if (!app.assembly) { partTree = app.tree; partFlyout = app.flyout; } + app.assembly = m; + app.tree = m.tree; + if (app.flyout !== m.flyout) { app.flyout.el.replaceWith(m.flyout.el); app.flyout = m.flyout; } + app.viewport.tool = m.dragTool; + // Drawings of the assembly show its components collapsed, or exploded (see drawing-sources.ts). + app.drawing.sources.set(ASSEMBLY_SOURCE, assemblySource(app, m, false)); + app.drawing.sources.set(EXPLODED_SOURCE, assemblySource(app, m, true)); + m.onShow = () => { if (app.inDrawing) void app.drawing.refresh(); }; + app.setRibbonTab('assembly'); + void checkPartsOnOpen(m); + }; + const exit = () => { + const m = app.assembly; + if (!m) return; + if (properties) properties.label = partPropertiesLabel; + m.dispose(); + app.assembly = null; + app.drawing.sources.delete(ASSEMBLY_SOURCE); + app.drawing.sources.delete(EXPLODED_SOURCE); + if (app.viewport.tool === m.dragTool) app.viewport.tool = null; + app.tree = partTree; + if (app.flyout === m.flyout) { m.flyout.el.replaceWith(partFlyout.el); app.flyout = partFlyout; } + for (const el of app.shell.root.querySelectorAll('.sheet-tabs')) el.hidden = false; + app.shell.statusSketch.hidden = true; + app.setRibbonTab('features'); + void app.kernel.assembly({ op: 'drop', keep: [] }).catch(() => undefined); + }; + app.syncDocumentKind = () => { + if (asAssembly(app.store.doc)) { + if (app.assembly) exit(); + enter(); + // Back in the assembly a part was opened from: nothing more to go back to. + if (returnTo && sameLocation(returnTo.location, app.location)) returnTo = null; + } else exit(); + }; + + /** On open, parts whose files were saved since the assembly took its copy are taken again. */ + async function checkPartsOnOpen(m: AssemblyMode) { + if (!m.doc.parts.some((p) => p.source)) return; + const wasDirty = app.store.dirty; + const r = await updateParts(m).catch(() => null); + if (!r || app.assembly !== m) return; + if (r.updated.length) { + toast({ kind: 'info', message: `${r.updated.join(', ')} changed since the assembly was saved: the assembly now uses the latest version. Save it to keep this.`, timeout: 9000 }); + // The update is a change to save, unless nothing else changed and the user undoes it. + void wasDirty; + } + if (r.missing.length) toast({ kind: 'warning', message: `The part files of ${r.missing.join(', ')} were not found (moved or deleted?): the copies kept in the assembly are used.`, timeout: 9000 }); + } + + // ---------- context menus ---------- + + const contextItems = hooks.contextItems; + hooks.contextItems = (target, id) => (app.assembly ? assemblyContext(target, id) : contextItems(target, id)); + const quickActions = hooks.quickActions; + hooks.quickActions = () => (app.assembly ? (selectedComps().length ? [{ cmd: 'mate' }, { cmd: 'openPart' }, { cmd: 'measure' }] : []) : quickActions()); + + function assemblyContext(target: 'viewport' | 'feature' | 'reference', id?: Id): MenuItem[] { + const m = mode()!; + const d = m.doc; + const sep: MenuItem = { separator: true }; + const cmd = (cid: string, extra: Partial = {}): MenuItem => { + const x = c.get(cid)!; + return { label: x.label, icon: x.icon, shortcut: x.shortcut, disabled: !c.isEnabled(cid), run: () => c.run(cid), ...extra }; + }; + const view: MenuItem[] = [cmd('zoomFit'), { label: 'View Orientation', icon: 'viewOrientation', submenu: () => app.viewMenuItems() }, { label: 'Display Style', icon: 'shadedEdges', submenu: () => app.displayMenuItems() }]; + const mate = id ? d.mates.find((x) => x.id === id) : undefined; + if (mate) { + const ids = app.tree.targets(mate.id).filter((x) => d.mates.some((y) => y.id === x)); + return [ + { label: 'Edit Mate', icon: 'edit', run: () => m.edit(mate.id) }, + { label: 'Rename', icon: 'text', shortcut: 'F2', run: () => app.startRename(mate.id) }, + ...(mate.type !== 'perpendicular' && mate.type !== 'lock' && mate.type !== 'tangent' ? [{ label: 'Flip Mate Alignment', icon: 'reset', run: () => m.commit('Flip alignment', (x) => { for (const y of x.mates) if (y.id === mate.id) y.aligned = !y.aligned; }) } as MenuItem] : []), + { label: mate.suppressed ? 'Unsuppress' : 'Suppress', icon: mate.suppressed ? 'eye' : 'eyeOff', run: () => m.commit(mate.suppressed ? 'Unsuppress' : 'Suppress', (x) => { for (const y of x.mates) if (ids.includes(y.id)) y.suppressed = mate.suppressed ? undefined : true; }) }, + sep, + { label: 'Delete', icon: 'trash', shortcut: 'Delete', run: () => void m.deleteItems(ids) }, + ]; + } + const step = id ? d.explode.find((x) => x.id === id) : undefined; + if (step) { + return [ + { label: 'Edit Step', icon: 'edit', run: () => m.edit(step.id) }, + { label: 'Rename', icon: 'text', shortcut: 'F2', run: () => app.startRename(step.id) }, + cmd('toggleExplode'), sep, + { label: 'Delete', icon: 'trash', shortcut: 'Delete', run: () => void m.deleteItems([step.id]) }, + ]; + } + const comps = id && m.component(id) ? app.tree.targets(id).filter((x) => m.component(x)) : selectedComps(); + if (comps.length) { + const first = m.component(comps[0])!; + const set = (label: string, f: (x: AssemblyDocument['components'][number]) => void, solve = true) => () => m.commit(label, (x) => { for (const y of x.components) if (comps.includes(y.id)) f(y); }, solve); + const mates = d.mates.filter((x) => mateComps(x).includes(first.id)); + return [ + ...(target === 'viewport' ? [cmd('mate'), sep] : []), + cmd('openPart', { label: `Open ${d.parts.find((p) => p.id === first.part)?.name ?? 'Part'}`, disabled: comps.length !== 1 }), + { label: 'Rename', icon: 'text', shortcut: 'F2', disabled: comps.length !== 1, run: () => app.startRename(first.id) }, + sep, + first.hidden ? { label: 'Show', icon: 'eye', run: set('Show', (y) => { delete y.hidden; }, false) } : { label: 'Hide', icon: 'eyeOff', run: set('Hide', (y) => { y.hidden = true; }, false) }, + first.suppressed ? { label: 'Unsuppress', icon: 'eye', run: set('Unsuppress', (y) => { delete y.suppressed; }) } : { label: 'Suppress', icon: 'eyeOff', run: set('Suppress', (y) => { y.suppressed = true; }) }, + first.fixed ? { label: 'Float', icon: 'unlock', run: set('Float', (y) => { y.fixed = false; }) } : { label: 'Fix', icon: 'lock', run: set('Fix', (y) => { y.fixed = true; }) }, + { label: 'Insert Another Instance', icon: 'insertComponent', disabled: comps.length !== 1, run: () => insertAnother(first.id) }, + ...(mates.length ? [{ label: 'Mates', icon: 'mate', submenu: () => mates.map((x) => ({ label: `${x.name} (${MATE_LABELS[x.type]})`, icon: `mate:${x.type}`, run: () => m.edit(x.id) })) } as MenuItem] : []), + sep, + { label: 'Delete', icon: 'trash', shortcut: 'Delete', run: () => void m.deleteItems(comps) }, + ...(target === 'viewport' ? [sep, ...view] : []), + ]; + } + const items: MenuItem[] = [cmd('insertComponent'), cmd('mate'), sep, ...view]; + if (target === 'reference') items.unshift({ label: 'Show/Hide Planes', icon: 'plane', run: () => c.run('showPlanes') }, sep); + return items; + } + + function insertAnother(compId: Id) { + const m = mode(); + const comp = m?.component(compId); + const pd = comp && m!.partDoc(comp.part); + const part = comp && m!.doc.parts.find((p) => p.id === comp.part); + if (!m || !pd || !part) return; + insertComponent(m, { doc: pd, source: part.source, version: part.version, partId: part.id }); + } +} diff --git a/src/parametric/src/app/assembly/mode.ts b/src/parametric/src/app/assembly/mode.ts new file mode 100644 index 0000000000..26b16a9e5f --- /dev/null +++ b/src/parametric/src/app/assembly/mode.ts @@ -0,0 +1,686 @@ +// Assembly mode: what the app does while an assembly document is open. +// Builds the parts its components use (in the geometry worker, each once), +// solves the mates, shows the placed components as one model through the +// part renderer, and lets components be dragged within what their mates +// allow. The design tree, ribbon and panels of assemblies are set up here. + +import type { FaceInfo, FeatureStatus } from '../../kernel/protocol'; +import type { AsmPartBuild, AsmPartResult } from '../../kernel/assembly'; +import { KernelRestartError } from '../../kernel/client'; +import { type Quat, type Vec3, add, cross, dot, normalize, qAxisAngle, qMul, scale, sub } from '../../math/vec'; +import { DocStore, parseDocument } from '../../model/document'; +import { BASE_FRAMES, BASE_PLANE_NAMES } from '../../model/planes'; +import type { Id, PartDocument } from '../../model/types'; +import { UNIT_SYSTEMS } from '../../model/units'; +import { + type AsmComponent, type AsmPart, type AssemblyDocument, type ExplodeStep, type Mate, type MateRef, type Placement, MATE_LABELS, PartCache, asAssembly, mateComps, +} from '../../model/assembly'; +import { type ComposedModel, type PartGeometry, combinedName, composeModel, edgeGeo, faceGeo, findEdge, findFace, placementMatrix } from '../../assembly/compose'; +import { type AnalysisResult, type DragGoal, type Geo, MateSolver, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, matesMoving } from '../../assembly/solver'; +import { parseColor } from '../../platform/theme'; +import { confirmDialog, toast } from '../../ui/overlay'; +import type { App } from '../app'; +import { formatGroup } from '../dialogs'; +import type { SelItem } from '../selection'; +import type { ViewportTool, VPEvent } from '../viewport'; +import { AssemblyTree } from './tree'; + +type Geom = PartGeometry & { status: FeatureStatus[] }; + +export class AssemblyMode { + readonly parts = new PartCache(parseDocument); + private geoms = new Map(); + private generation = -1; + model: ComposedModel | null = null; + /** The components in the worker's scene, in order (hidden ones too: see AsmSceneItem). */ + sceneComps: Id[] = []; + /** Where the mates put each component (exploded view aside). */ + solved = new Map(); + analysis: AnalysisResult | null = null; + /** Parts that could not be read or built, with why. */ + partErrors = new Map(); + readonly tree: AssemblyTree; + readonly flyout: AssemblyTree; + readonly dragTool: ViewportTool; + /** Drags turn components instead of moving them (Rotate Component). */ + rotateMode = false; + /** Frame the assembly once its first rebuild shows it. */ + fitPending = true; + /** The document (but its drawing) the components were last shown for. */ + private shownKey = ''; + private building: Promise | null = null; + private again = false; + private restartRetried = false; + /** Set while a drag shows placements that are not in the document yet. */ + private preview: Map | null = null; + /** An explode step being edited: shown before it is in the document. */ + private explodePreview: { step: ExplodeStep | null; replace: Id | null } | null = null; + /** Parts whose file could not be found when the assembly was opened (their copies are used). */ + missingParts = new Set(); + /** Opens the panel that edits a mate or explode step (set by the commands). */ + onEdit: (id: Id) => void = () => {}; + onShow: () => void = () => {}; + + constructor(readonly app: App) { + this.tree = new AssemblyTree(app, this); + this.flyout = new AssemblyTree(app, this, true); + this.dragTool = new DragTool(this); + } + + get doc(): AssemblyDocument { + return asAssembly(this.app.store.doc)!; + } + + /** What the worker builds a part by (its embedded copy at the current quality). */ + key(p: AsmPart): string { + return `${p.blob}|${this.app.settings.quality}`; + } + + /** What the worker built for a part (null until it is built, or when it failed). */ + geometryOf(partId: Id): Geom | null { + const p = this.doc.parts.find((x) => x.id === partId); + return p ? this.geoms.get(this.key(p)) ?? null : null; + } + + partDoc(partId: Id): PartDocument | null { + return this.parts.get(this.doc, partId).doc; + } + + component(id: Id): AsmComponent | undefined { + return this.doc.components.find((c) => c.id === id); + } + + // ---------- rebuild ---------- + + /** Builds what is missing, solves the mates and shows the result (one at a time). */ + rebuild(): Promise { + if (this.building) { this.again = true; return this.building; } + this.building = (async () => { + do { + this.again = false; + await this.rebuildOnce(); + } while (this.again && this.app.assembly === this); + })().finally(() => { this.building = null; }); + return this.building; + } + + private async rebuildOnce() { + const app = this.app; + const doc = this.doc; + const signal = app.documentSignal; + if (app.kernel.generation !== this.generation) { this.geoms.clear(); this.generation = app.kernel.generation; } + const used = doc.parts.filter((p) => doc.components.some((c) => c.part === p.id && !c.suppressed)); + // Only the drawing changed (a view dragged on the sheet): the components are shown as they are. + const shownKey = JSON.stringify([app.kernel.generation, app.settings.quality, { ...doc, drawing: undefined, modified: undefined, blobs: undefined }]); + if (this.model && shownKey === this.shownKey && used.every((p) => this.geoms.has(this.key(p)))) return; + this.shownKey = ''; + const builds: AsmPartBuild[] = []; + this.partErrors.clear(); + for (const p of used) { + const k = this.key(p); + if (this.geoms.has(k)) continue; + const { doc: pd, error } = this.parts.get(doc, p.id); + if (!pd) { this.partErrors.set(p.id, error ?? 'The part could not be read'); continue; } + const st = new DocStore(pd); + const res = st.resolve(); + const invalid = Object.fromEntries([...res.errors].filter(([id]) => st.feature(id)?.type !== 'sketch')); + builds.push({ key: k, features: res.features, blobs: pd.blobs, quality: app.settings.quality, invalid }); + } + const t0 = performance.now(); + if (builds.length) { + app.setStatus(`Building ${builds.length === 1 ? 'a part' : `${builds.length} parts`} of the assembly...`); + let results: AsmPartResult[]; + try { + results = await app.kernel.assembly({ op: 'build', parts: builds }); + } catch (e) { + if (signal.aborted || app.assembly !== this) return; + if (e instanceof KernelRestartError && !this.restartRetried) { this.restartRetried = true; this.again = true; return; } + toast({ kind: 'error', title: 'Rebuild failed', message: (e as Error).message }); + app.clearStatus(); + return; + } + if (signal.aborted || app.assembly !== this) return; + this.restartRetried = false; + for (const r of results) this.geoms.set(r.key, { mesh: r.mesh, faces: r.faces, edges: r.edges, bbox: r.bbox, cones: r.cones, status: r.status }); + app.clearStatus(); + } + for (const p of used) { + const g = this.geoms.get(this.key(p)); + const bad = g?.status.find((s) => !s.ok); + if (bad && !this.partErrors.has(p.id)) { + const f = this.partDoc(p.id)?.features.find((x) => x.id === bad.id); + this.partErrors.set(p.id, `${p.name} has rebuild errors (${f?.name ?? 'a feature'}: ${bad.error ?? 'failed'}). Open the part to fix it.`); + } else if (g && !g.mesh && !this.partErrors.has(p.id)) this.partErrors.set(p.id, `${p.name} has no solid body`); + } + // The worker forgets parts no longer used (all their components deleted or suppressed, or + // built at another quality); this side too, so using them again builds them again. + const keep = used.map((p) => this.key(p)); + for (const k of [...this.geoms.keys()]) if (!keep.includes(k)) this.geoms.delete(k); + void app.kernel.assembly({ op: 'drop', keep }).catch(() => undefined); + this.parts.prune(doc); + this.analyze(); + this.show(); + this.shownKey = shownKey; + app.shell.statusRebuild.textContent = `${Math.round(performance.now() - t0)} ms`; + app.renderTrees(); + app.commands.changed(); + } + + // ---------- mates ---------- + + /** The size the solver measures lengths against: the assembly's extent. */ + private scale(): number { + let r = 0; + for (const c of this.doc.components) { + const g = this.geometryOf(c.part); + if (!g?.bbox) continue; + const pl = this.solved.get(c.id) ?? c.placement; + for (const p of [g.bbox.min, g.bbox.max]) r = Math.max(r, Math.hypot(...applyPlacement(pl, p))); + } + return Math.max(10, r); + } + + /** A mate reference as solver geometry, or why it cannot be used. */ + entity(ref: MateRef, doc = this.doc): SolverEntity | string { + if ('plane' in ref) { + const f = BASE_FRAMES[ref.plane]; + return { body: null, geo: { kind: 'plane', o: f.o, n: f.n } }; + } + const c = doc.components.find((x) => x.id === ref.comp); + if (!c) return 'Its component was deleted'; + if ('face' in ref || 'edge' in ref) { + const g = this.geometryOf(c.part); + if (!g) return `${c.name} is not built`; + let geo: Geo | null = null; + if ('face' in ref) { + const i = findFace(g.faces, ref.face); + if (i < 0) return `The face it references on ${c.name} no longer exists`; + geo = faceGeo(g, i); + } else { + const i = findEdge(g.edges, ref.edge); + if (i < 0) return `The edge it references on ${c.name} no longer exists`; + geo = edgeGeo(g, i); + } + return geo ? { body: c.id, geo } : `The ${'face' in ref ? 'face' : 'edge'} it references on ${c.name} cannot be mated`; + } + return { body: c.id, geo: { kind: 'body' } }; + } + + /** Mate value in mm or degrees. */ + mateValue(m: Mate): number { + if (m.value === undefined) return 0; + return this.app.store.evalParam(m.value, m.type === 'angle' ? 'angle' : 'length'); + } + + /** + * Solver mates of a document: active mates between components that are + * not suppressed. Mates that cannot be formed are returned with why. + */ + solverInput(doc = this.doc): { bodies: SolverBody[]; mates: SolverMate[]; problems: Map; inactive: Set } { + const live = doc.components.filter((c) => !c.suppressed); + const bodies: SolverBody[] = live.map((c) => { + const b = this.geometryOf(c.part)?.bbox; + return { id: c.id, fixed: c.fixed, placement: c.placement, center: b ? scale(add(b.min, b.max), 0.5) : [0, 0, 0] }; + }); + const mates: SolverMate[] = []; + const problems = new Map(); + const inactive = new Set(); + for (const m of doc.mates) { + if (m.suppressed || mateComps(m).some((id) => doc.components.find((c) => c.id === id)?.suppressed)) { inactive.add(m.id); continue; } + const a = this.entity(m.a, doc), b = this.entity(m.b, doc); + if (typeof a === 'string' || typeof b === 'string') { problems.set(m.id, typeof a === 'string' ? a : b as string); continue; } + let value = 0; + try { + value = this.mateValue(m); + } catch (e) { + problems.set(m.id, `${m.type === 'angle' ? 'Angle' : 'Distance'}: ${(e as Error).message}`); + continue; + } + mates.push({ id: m.id, type: m.type, a, b, aligned: m.aligned, value, flip: !!m.flip, rel: m.rel }); + } + return { bodies, mates, problems, inactive }; + } + + /** Components linked to a fixed one (or the assembly planes) by mates: they move last. */ + private grounded(mates: SolverMate[], bodies: SolverBody[]): Set { + const out = new Set(bodies.filter((b) => b.fixed).map((b) => b.id)); + let grew = true; + let ground = mates.some((m) => !m.a.body || !m.b.body); + while (grew) { + grew = false; + for (const m of mates) { + const ids = [m.a.body, m.b.body]; + const touches = ids.some((id) => (id ? out.has(id) : ground)); + if (!touches) continue; + for (const id of ids) if (id && !out.has(id)) { out.add(id); grew = true; } + } + ground = false; + } + return out; + } + + /** Solves a document's mates; the analysis carries the placements. */ + solveDoc(doc = this.doc): AnalysisResult { + const { bodies, mates, problems } = this.solverInput(doc); + const solver = new MateSolver(bodies, mates); + const grounded = this.grounded(mates, bodies); + const r = solver.analyze({ scale: this.scale(), weight: (id) => (grounded.has(id) ? 100 : 1) }); + for (const [id, why] of problems) r.invalid.set(id, why); + // A mate that cannot be formed (a face gone) is an error, not a conflict. + if (problems.size && r.status !== 'over') r.status = 'error'; + return r; + } + + /** The analysis a commit just made, reused by the rebuild that follows it when nothing it used changed. */ + private solveCache: { key: string; result: AnalysisResult } | null = null; + + /** What an analysis of a document depends on. */ + private solveKey(doc: AssemblyDocument): string { + return JSON.stringify([this.app.kernel.generation, this.app.settings.quality, [...this.geoms.keys()], doc.components, doc.mates, doc.variables, doc.units, doc.parts.map((p) => p.blob)]); + } + + private analyze() { + // A commit solved this very document already (an over-defined assembly takes long to analyse). + const hit = this.solveCache?.key === this.solveKey(this.doc) ? this.solveCache.result : null; + this.solveCache = null; + this.analysis = hit ?? this.solveDoc(); + this.solved = new Map(this.analysis.placements); + } + + isDefined(id: Id): boolean { + return !!this.analysis?.defined.has(id); + } + + mateError(id: Id): string | null { + const a = this.analysis; + if (!a) return null; + if (a.invalid.has(id)) return a.invalid.get(id)!; + if (a.conflicts.has(id)) return 'Over defined: this mate cannot hold together with the mates before it'; + return null; + } + + componentError(id: Id): { kind: 'error' | 'warning'; text: string } | null { + const c = this.component(id); + if (!c || c.suppressed) return null; + const err = this.partErrors.get(c.part); + if (err) return { kind: 'error', text: err }; + const p = this.doc.parts.find((x) => x.id === c.part); + if (p && !p.source) return { kind: 'warning', text: `${p.name} exists only inside this assembly (it has no part file).` }; + if (p && this.missingParts.has(p.id)) return { kind: 'warning', text: `The part file of ${p.name} was not found (moved or deleted?): the copy kept in the assembly is used.` }; + return null; + } + + /** "bracket<1>, pin<1>" for a mate's row. */ + mateLabel(m: Mate): string { + return [m.a, m.b].map((r) => ('plane' in r ? BASE_PLANE_NAMES[r.plane] : this.component(r.comp)?.name ?? '?')).join(', '); + } + + // ---------- display ---------- + + /** Where a component is shown: where the mates put it, moved by the exploded view. */ + shownPlacement(id: Id, base = this.preview ?? this.solved): Placement | null { + const c = this.component(id); + if (!c) return null; + const pl = base.get(id) ?? c.placement; + const doc = this.doc; + const ex = this.explodePreview; + if (!doc.exploded && !ex) return pl; + let steps = doc.explode; + if (ex) { + steps = steps.flatMap((s) => (s.id === ex.replace ? (ex.step ? [ex.step] : []) : [s])); + if (ex.step && !ex.replace) steps = [...steps, ex.step]; + } + let off: Vec3 = [0, 0, 0]; + for (const s of steps) { + if (!s.comps.includes(id)) continue; + let d = 0; + try { d = this.app.store.evalParam(s.distance, 'length'); } catch { d = 0; } + off = add(off, scale(normalize(s.dir), d)); + } + return { p: add(pl.p, off), q: pl.q }; + } + + /** Shows the components where they are now (or where a drag puts them). */ + show() { + const app = this.app; + const doc = this.doc; + const all = []; + for (const c of doc.components) { + if (c.suppressed) continue; + const geom = this.geometryOf(c.part); + const pl = this.shownPlacement(c.id); + if (!geom || !pl) continue; + const part = doc.parts.find((p) => p.id === c.part)!; + all.push({ comp: c, placement: pl, geom, color: parseColor(part.color) as [number, number, number] }); + } + const items = all.filter((it) => !it.comp.hidden); + const model = composeModel(items); + this.model = model; + app.setModelGeometry(model.mesh, model.faces, model.edges, model.bbox); + app.renderer.setFaceColors(model.faceColors); + app.buildVersion++; + app.geometryVersion++; + app.selection.revalidate(model.faces, model.edges); + app.viewport.refreshStates(); + // The worker places the same components, in the same order, for measure, export and + // interference, and the hidden ones too for mass properties (they are still in the assembly). + this.sceneComps = all.map((it) => it.comp.id); + void app.kernel.assembly({ + op: 'scene', items: all.map((it) => { + const part = doc.parts.find((p) => p.id === it.comp.part)!; + return { part: this.key(part), m: placementMatrix(it.placement), name: it.comp.name, color: part.color, ...(it.comp.hidden ? { hidden: true } : {}) }; + }), + }).catch(() => undefined); + if (this.fitPending && model.bbox) { + this.fitPending = false; + app.viewport.zoomToFit(false, false); + } + app.panel?.onBuild({ mesh: null, faces: model.faces, edges: model.edges, status: [], frames: {}, bbox: model.bbox, ms: 0, preview: null }); + this.updateStatus(); + this.onShow(); + } + + updateStatus() { + const btn = this.app.shell.statusSketch; + const a = this.analysis; + if (!a || !this.doc.components.length) { btn.hidden = true; return; } + btn.hidden = false; + btn.className = `cell status-${a.status === 'error' ? 'over' : a.status}`; + btn.textContent = a.status === 'over' ? 'Over Defined' : a.status === 'error' ? 'Mate Errors' : a.status === 'full' ? 'Fully Defined' : `Under Defined (${a.dof} DOF)`; + } + + /** The combined face index of a component's part face, or -1. */ + combinedFace(comp: Id, local: number): number { + const m = this.model; + if (!m) return -1; + const ci = m.comps.indexOf(comp); + for (let i = 0; i < m.faceComp.length; i++) if (m.faceComp[i] === ci && m.faceLocal[i] === local) return i; + return -1; + } + + /** The component a combined face belongs to. */ + faceComponent(index: number): AsmComponent | undefined { + const m = this.model; + if (!m || index < 0 || index >= m.faceComp.length) return undefined; + return this.component(m.comps[m.faceComp[index]]); + } + + edgeComponent(index: number): AsmComponent | undefined { + const m = this.model; + if (!m || index < 0 || index >= m.edgeComp.length) return undefined; + return this.component(m.comps[m.edgeComp[index]]); + } + + /** A picked face or edge as a mate reference (by its name in the part). */ + refOf(it: SelItem): MateRef | null { + if (it.kind === 'plane' && it.ref.kind === 'base') return { plane: it.ref.plane }; + if (it.kind === 'feature' && this.component(it.id)) return { comp: it.id }; + const m = this.model; + if (!m) return null; + if (it.kind === 'face') { + const c = this.faceComponent(it.index); + const g = c && this.geometryOf(c.part); + const f = g?.faces[m.faceLocal[it.index]]; + return c && f ? { comp: c.id, face: { name: f.name, sig: { type: f.type, c: f.center, n: f.normal, area: f.area } } } : null; + } + if (it.kind === 'edge') { + const c = this.edgeComponent(it.index); + const g = c && this.geometryOf(c.part); + const e = g?.edges[m.edgeLocal[it.index]]; + return c && e ? { comp: c.id, edge: { name: e.name, sig: { type: e.type, m: e.mid, len: e.length } } } : null; + } + return null; + } + + /** The item a mate reference shows as (to highlight it). */ + itemOf(ref: MateRef): SelItem | null { + if ('plane' in ref) return { kind: 'plane', ref: { kind: 'base', plane: ref.plane } }; + const c = this.component(ref.comp); + const g = c && this.geometryOf(c.part); + if (!c || !g) return null; + if ('face' in ref) { + const i = this.combinedFace(c.id, findFace(g.faces, ref.face)); + return i >= 0 ? { kind: 'face', index: i, name: combinedName(c.id, ref.face.name) } : null; + } + if ('edge' in ref) { + const m = this.model; + const local = findEdge(g.edges, ref.edge); + if (!m || local < 0) return null; + const ci = m.comps.indexOf(c.id); + for (let i = 0; i < m.edgeComp.length; i++) if (m.edgeComp[i] === ci && m.edgeLocal[i] === local) return { kind: 'edge', index: i, name: combinedName(c.id, ref.edge.name) }; + return null; + } + return { kind: 'feature', id: c.id }; + } + + /** Faces and components highlighted because a mate or explode step is selected. */ + highlights(): SelItem[] { + const out: SelItem[] = []; + for (const it of this.app.selection.ofKind('feature')) { + const m = this.doc.mates.find((x) => x.id === it.id); + if (m) for (const r of [m.a, m.b]) { const x = this.itemOf(r); if (x) out.push(x); } + const s = this.doc.explode.find((x) => x.id === it.id); + if (s) for (const id of s.comps) out.push({ kind: 'feature', id }); + } + return out; + } + + describe(it: SelItem): string | null { + const doc = this.app.store.doc; + const u = UNIT_SYSTEMS[doc.units], dec = doc.decimals; + if (it.kind === 'face') { + const f = this.app.faces[it.index]; + const c = this.faceComponent(it.index); + if (!f || !c) return null; + return `Face (${f.type}) of ${c.name} Area ${formatGroup([f.area / u.scale ** 2], dec)[0]} ${u.length}²`; + } + if (it.kind === 'edge') { + const e = this.app.edges[it.index]; + const c = this.edgeComponent(it.index); + if (!e || !c) return null; + return `Edge (${e.type}) of ${c.name} Length ${formatGroup([e.length / u.scale], dec)[0]} ${u.length}`; + } + if (it.kind === 'feature') { + const c = this.component(it.id); + if (c) return `${c.name}${c.fixed ? ' (fixed)' : this.isDefined(c.id) ? ' (fully defined)' : ' (under defined)'}`; + const m = this.doc.mates.find((x) => x.id === it.id); + if (m) return `${MATE_LABELS[m.type]} mate: ${this.mateLabel(m)}`; + const s = this.doc.explode.find((x) => x.id === it.id); + if (s) return s.name; + } + return null; + } + + // ---------- editing ---------- + + /** + * Changes the document as one undo step; the mates are solved again and + * the floating components put where they hold. + */ + commit(label: string, fn: (d: AssemblyDocument) => void, solve = true) { + this.app.store.change(label, (raw) => { + const d = asAssembly(raw)!; + fn(d); + if (!solve) return; + const r = this.solveDoc(d); + for (const c of d.components) { + const pl = r.placements.get(c.id); + if (pl && !c.fixed && !c.suppressed) c.placement = pl; + } + this.solveCache = { key: this.solveKey(d), result: r }; + }); + } + + itemName(id: Id): string | null { + const d = this.doc; + return d.components.find((x) => x.id === id)?.name ?? d.mates.find((x) => x.id === id)?.name ?? d.explode.find((x) => x.id === id)?.name ?? null; + } + + nameRefusal(id: Id, name: string): string | null { + const low = name.toLowerCase(); + const d = this.doc; + const other = [...d.components, ...d.mates, ...d.explode].find((x) => x.id !== id && x.name.toLowerCase() === low); + return other ? `"${name}" is already the name of another item. Choose another name.` : null; + } + + rename(id: Id, name: string) { + this.commit('Rename', (d) => { + for (const x of [...d.components, ...d.mates, ...d.explode]) if (x.id === id) x.name = name; + }, false); + } + + /** Double click or Enter on a tree row. */ + edit(id: Id) { + if (this.component(id)) this.app.selection.set([{ kind: 'feature', id }]); + else this.onEdit(id); + } + + async deleteItems(ids: Id[]) { + const doc = this.doc; + const signal = this.app.documentSignal; + const comps = doc.components.filter((c) => ids.includes(c.id)); + const mates = doc.mates.filter((m) => ids.includes(m.id) || mateComps(m).some((c) => comps.some((x) => x.id === c))); + const steps = doc.explode.filter((s) => ids.includes(s.id)); + const names = [...comps, ...doc.mates.filter((m) => ids.includes(m.id)), ...steps].map((x) => x.name); + if (!names.length) return; + const dependent = mates.filter((m) => !ids.includes(m.id)); + const msg = dependent.length ? `Delete ${names.join(', ')}? These mates reference ${comps.length === 1 ? 'it' : 'them'} and are deleted too: ${dependent.map((m) => m.name).join(', ')}.` : `Delete ${names.join(', ')}?`; + if (!(await confirmDialog('Delete', msg, 'Delete', true, signal)) || signal.aborted) return; + if (this.app.panel) await this.app.closePanel(false); + const gone = new Set([...comps.map((c) => c.id), ...mates.map((m) => m.id), ...steps.map((s) => s.id)]); + this.commit('Delete', (d) => { + d.components = d.components.filter((c) => !gone.has(c.id)); + d.mates = d.mates.filter((m) => !gone.has(m.id)); + d.explode = d.explode.filter((s) => !gone.has(s.id)).map((s) => ({ ...s, comps: s.comps.filter((c) => !gone.has(c)) })).filter((s) => s.comps.length); + if (!d.explode.length) d.exploded = false; + d.parts = d.parts.filter((p) => d.components.some((c) => c.part === p.id)); + // The first component left is fixed when none is, so the assembly keeps its ground. + if (d.components.length && !d.components.some((c) => c.fixed)) d.components[0].fixed = true; + }); + this.app.selection.clear(); + } + + // ---------- dragging ---------- + + /** Shows an explode step being added (or replacing `replace`) before it is in the document. */ + previewExplode(step: ExplodeStep | null, replace: Id | null) { + this.explodePreview = step || replace ? { step, replace } : null; + this.show(); + } + + /** Shows a drag's placements without changing the document. */ + previewPlacements(pl: Map | null) { + this.preview = pl; + this.show(); + } + + /** Solves with a drag goal from where the components are shown. */ + dragSolve(goal: DragGoal, from: Map): Map { + const { bodies, mates } = this.solverInput(); + const start = new Map(bodies.map((b) => [b.id, from.get(b.id) ?? b.placement])); + const active = mates.filter((m) => !this.analysis?.conflicts.has(m.id)); + const solver = new MateSolver(bodies.map((b) => ({ ...b, placement: start.get(b.id)! })), matesMoving(goal.body, bodies, active)); + return solver.solve({ scale: this.scale(), drag: goal, maxIter: 25 }).placements; + } + + commitPlacements(label: string, pl: Map) { + this.preview = null; + this.commit(label, (d) => { + for (const c of d.components) { + const p = pl.get(c.id); + if (p && !c.fixed) c.placement = p; + } + }); + } + + dispose() { + this.preview = null; + this.explodePreview = null; + } +} + +/** + * Dragging components in the graphics area: the grabbed point follows the + * cursor (Alt, or Rotate Component: the component turns), within what the + * mates allow. Fixed components do not move; the view turns instead. + */ +class DragTool implements ViewportTool { + private drag: { + comp: Id; local: Vec3; plane: { o: Vec3; n: Vec3 }; rotate: boolean; x: number; y: number; + q0: Quat; from: Map; last: Map | null; + } | null = null; + + constructor(private mode: AssemblyMode) {} + + pointerDown(e: VPEvent): boolean { + const mode = this.mode; + const app = mode.app; + if (e.button !== 0 || (e.pointerType === 'touch' && !app.panel?.title.endsWith('Component'))) return false; + if (app.sketchEditor) return false; + const hit = app.renderer.pick(e.x, e.y, { face: true }, 0); + if (!hit || hit.kind !== 'face' || !hit.point) return false; + const c = mode.faceComponent(hit.index); + if (!c) return false; + if (c.fixed) { app.setStatus(`${c.name} is fixed. Float it to move it.`, true); return false; } + // Its mates leave it no freedom: the view turns, as for a fixed one (a drag would only add an empty undo step). + if (mode.isDefined(c.id)) { app.setStatus(`${c.name} is fully defined by its mates. Suppress or edit a mate to move it.`, true); return false; } + if (mode.doc.exploded) { app.setStatus('Collapse the exploded view to move components.', true); return false; } + const pl = mode.solved.get(c.id) ?? c.placement; + const inv = { q: [-pl.q[0], -pl.q[1], -pl.q[2], pl.q[3]] as Quat }; + const local = rotateBy(inv.q, sub(hit.point, pl.p)); + this.drag = { comp: c.id, local, plane: { o: hit.point, n: app.renderer.camera.back }, rotate: e.alt || mode.rotateMode, x: e.x, y: e.y, q0: pl.q, from: new Map(mode.solved), last: null }; + return true; + } + + pointerMove(e: VPEvent, dragging: boolean) { + const d = this.drag; + if (!d || !dragging) return; + const mode = this.mode; + let goal: DragGoal; + if (d.rotate) { + const cam = mode.app.renderer.camera; + const k = 0.01; + const q = qMul(qAxisAngle(cam.up, (e.x - d.x) * k), qMul(qAxisAngle(cam.right, (e.y - d.y) * k), d.q0)); + goal = { kind: 'rotate', body: d.comp, q }; + } else { + const t = rayPlane(e.ray.o, e.ray.d, d.plane.o, d.plane.n); + if (!t) return; + goal = { kind: 'move', body: d.comp, local: d.local, target: t }; + } + d.last = mode.dragSolve(goal, d.last ?? d.from); + mode.previewPlacements(d.last); + } + + pointerUp() { + const d = this.drag; + this.drag = null; + if (!d) return; + if (d.last) this.mode.commitPlacements(d.rotate ? 'Rotate component' : 'Move component', d.last); + else this.mode.previewPlacements(null); + } + + click(): boolean { + this.drag = null; + return false; + } +} + +function rotateBy(q: Quat, v: Vec3): Vec3 { + // q v q*, written out to avoid importing another helper. + const [x, y, z, w] = q; + const uv = cross([x, y, z], v); + const uuv = cross([x, y, z], uv); + return add(v, add(scale(uv, 2 * w), scale(uuv, 2))); +} + +function rayPlane(o: Vec3, d: Vec3, p: Vec3, n: Vec3): Vec3 | null { + const den = dot(d, n); + if (Math.abs(den) < 1e-9) return null; + const t = dot(sub(p, o), n) / den; + return add(o, scale(d, t)); +} + +/** Faces of a model's face list that belong to a component (tests and panels). */ +export function facesOf(faces: FaceInfo[], comp: Id): number[] { + return faces.map((f, i) => (f.feature === comp ? i : -1)).filter((i) => i >= 0); +} diff --git a/src/parametric/src/app/assembly/panels.ts b/src/parametric/src/app/assembly/panels.ts new file mode 100644 index 0000000000..58e2702b5c --- /dev/null +++ b/src/parametric/src/app/assembly/panels.ts @@ -0,0 +1,816 @@ +// PropertyManager panels and dialogs of assemblies: Insert Components, Mate, +// Move and Rotate Component, Explode Step, Interference Detection, Bill of +// Materials and the assembly's Mass Properties. + +import type { MeshData } from '../../kernel/protocol'; +import type { AsmMassResult, InterferencePair } from '../../kernel/assembly'; +import { type Vec3, add, normalize, qAxisAngle, qMul, scale } from '../../math/vec'; +import { allocateId, newDocument, parseDocument, serializeDocument } from '../../model/document'; +import { defaultName } from '../../model/features'; +import { BASE_PLANE_NAMES } from '../../model/planes'; +import type { Id, Param, PartDocument } from '../../model/types'; +import { UNIT_SYSTEMS } from '../../model/units'; +import { + type AssemblyDocument, type ExplodeStep, type Mate, type MateRef, type MateType, type PartSource, MATE_LABELS, assemblyBom, bomCsv, instanceName, + isAssembly, newPartBlobId, nextAsmId, nextPartColor, parseAnyDocument, +} from '../../model/assembly'; +import { type Geo, fittingMates, initialMateSettings, mateProblem, placeGeo, relativePlacement } from '../../assembly/solver'; +import { + EXT, acceptList, cloudVersion, download, isSolidWorksFile, isStepFile, listParts, loadPart, locationLabel, pickCloudFile, pickDeviceFile, readIndexEntry, safeName, sameLocation, versionChanged, + type FileEntry, type FileVersion, type Location, +} from '../../platform/files'; +import { cloudAvailable, puter, storageError } from '../../platform/puter'; +import { h } from '../../ui/dom'; +import { icon } from '../../ui/icons'; +import { showDialog, toast } from '../../ui/overlay'; +import type { App } from '../app'; +import { formatGroup } from '../dialogs'; +import { type SelBoxItem, PropertyPanel, SelectionBox, checkbox, numberField, section, segmented, selectField } from '../pm'; +import type { SelItem } from '../selection'; +import type { AssemblyMode } from './mode'; + +// ---------- Insert Components ---------- + +interface PickedPart { + doc: PartDocument; + source: PartSource | null; + version: FileVersion | null; + /** Another instance of a part the assembly already has. */ + partId?: Id; +} + +/** Version of a part file to compare with later (cloud: its time and size; this browser: its listing). */ +export function localVersion(loc: Location): FileVersion | null { + if (loc.type !== 'local') return null; + const e = readIndexEntry(loc.id); + return e ? { modified: e.modified, size: e.size } : null; +} + +/** Reads a part file's text as a part (an assembly or another file is refused with why). */ +function partFrom(text: string, name: string): PartDocument | null { + let doc; + try { + doc = parseAnyDocument(text); + } catch (e) { + toast({ kind: 'error', title: 'Could not insert the part', message: (e as Error).message }); + return null; + } + if (isAssembly(doc)) { + toast({ kind: 'error', title: 'Could not insert the part', message: `${name} is an assembly. Insert its parts instead: assemblies inside assemblies are not supported yet.` }); + return null; + } + return doc; +} + +/** + * Asks which part to insert: parts in the cloud or this browser (as the Open + * dialog lists them), a file from the device (a part, or a STEP model, which + * becomes a part kept inside the assembly) or one picked in Puter. + */ +export async function pickPart(app: App): Promise { + const signal = app.documentSignal; + let cloudError = ''; + const entries = (await listParts((e) => { cloudError = storageError(e); })).filter((e) => !sameLocation(e.location, app.location)); + if (signal.aborted) return null; + const list = h('div', { class: 'file-list', role: 'list' }); + let chosen: FileEntry | null = null; + let close: ((v: string | null) => void) | null = null; + if (!entries.length) list.replaceChildren(h('p', {}, 'No saved parts yet. Save a part first, or insert a part or STEP file from this device.')); + for (const e of entries) { + const b = h('button', { class: 'file-item', type: 'button' }, + h('span', { 'aria-hidden': 'true', style: { color: e.location.type === 'cloud' ? 'var(--accent)' : 'var(--text-3)' } }, icon(e.location.type === 'cloud' ? 'cloud' : 'device', 18)), + h('span', { class: 'txt' }, h('span', { class: 'n' }, e.name), h('span', { class: 'meta' }, `${locationLabel(e.location)} ${e.modified ? new Date(e.modified).toLocaleString() : ''}`))); + b.addEventListener('click', () => { chosen = e; close?.('pick'); }); + list.append(h('div', { class: 'file-row', role: 'listitem' }, b)); + } + const body = h('div', {}, h('p', { class: 'field-label' }, 'Choose a part to place in the assembly. The assembly keeps a copy, and picks up changes to the part file when it is opened.'), + cloudError ? h('p', { role: 'alert' }, `Your cloud parts could not be listed: ${cloudError}`) : null, list); + const buttons: { label: string; value: string; left?: boolean }[] = [{ label: 'From device...', value: 'device', left: true }]; + if (cloudAvailable() && puter()?.ui?.showOpenFilePicker) buttons.push({ label: 'Browse Puter...', value: 'browse', left: true }); + buttons.push({ label: 'Cancel', value: 'cancel' }); + const v = await showDialog({ title: 'Insert Components', signal, body, buttons, wide: true, onReady: (c) => { close = c; } }); + if (signal.aborted) return null; + if (v === 'pick' && chosen) { + const e = chosen as FileEntry; + try { + const read = await loadPart(e.location); + const doc = partFrom(read.text, e.name); + if (!doc || signal.aborted) return null; + if (e.location.type === 'cloud') doc.name = e.name; + return { doc, source: e.location, version: read.version ?? localVersion(e.location) ?? (e.modified ? { modified: e.modified, size: e.size ?? null } : null) }; + } catch (err) { + toast({ kind: 'error', title: 'Could not insert the part', message: storageError(err) }); + return null; + } + } + if (v === 'browse') { + const r = await pickCloudFile().catch((err) => { toast({ kind: 'error', message: storageError(err) }); return null; }); + if (!r || signal.aborted) return null; + return fromFile(app, r.blob, r.fileName, r.location, r.version); + } + if (v === 'device') { + const file = await pickDeviceFile(acceptList([EXT, '.json', '.step', '.stp', '.sldprt'])); + if (!file || signal.aborted) return null; + return fromFile(app, file, file.name, null, null); + } + return null; +} + +async function fromFile(app: App, blob: Blob, fileName: string, loc: Location | null, version: FileVersion | null): Promise { + const base = safeName(fileName.replace(/\.[^.]+$/, '')); + if (isStepFile(fileName) || isSolidWorksFile(fileName)) { + if (/\.(sldasm|slddrw)$/i.test(fileName)) { toast({ kind: 'error', message: `${fileName} is not a SolidWorks part. Insert parts (.sldprt) one by one.` }); return null; } + let step: string; + try { + step = isStepFile(fileName) ? await blob.text() : (await app.kernel.convertSolidWorks(new Uint8Array(await blob.arrayBuffer()), fileName)).step; + } catch (e) { + toast({ kind: 'error', title: 'Could not insert the file', message: (e as Error).message }); + return null; + } + const err = step.trim() ? await app.kernel.checkImport(step).catch((e) => (e as Error).message) : `${fileName} is empty.`; + if (err) { toast({ kind: 'error', title: 'Could not insert the file', message: err }); return null; } + // A model file becomes a part kept inside the assembly, its solid as an imported body. + const doc = newDocument(base || 'Part', app.settings.defaultUnits); + const blobId = `b${Math.random().toString(36).slice(2, 10)}`; + doc.blobs[blobId] = step; + doc.features.push({ id: allocateId(doc), name: defaultName(doc, 'import'), type: 'import', format: 'step', blob: blobId, fileName }); + return { doc, source: null, version: null }; + } + const doc = partFrom(await blob.text(), fileName); + if (!doc) return null; + if (loc) doc.name = base; + return { doc, source: loc, version }; +} + +/** Embeds the part (once) and places a new component of it. */ +export function insertComponent(mode: AssemblyMode, picked: PickedPart) { + const app = mode.app; + const doc = mode.doc; + let part = picked.partId ? doc.parts.find((p) => p.id === picked.partId) + : picked.source ? doc.parts.find((p) => p.source && sameLocation(p.source as Location, picked.source as Location)) : undefined; + const text = picked.partId ? '' : serializeDocument(picked.doc); + let blob: Id | null = null; + if (!part || (!picked.partId && doc.blobs[part.blob] !== text)) { + blob = newPartBlobId(doc); + // Copies are kept out of undo history (like imported files): set before the change that uses it. + doc.blobs[blob] = text; + } + const b = app.bbox; + const gap = b ? Math.max(20, 0.25 * Math.hypot(b.max[0] - b.min[0], b.max[1] - b.min[1], b.max[2] - b.min[2])) : 0; + let compId = ''; + mode.commit('Insert component', (d) => { + if (!part) { + part = { id: nextAsmId(d, 'p'), name: picked.doc.name, source: picked.source, version: picked.version, blob: blob!, color: nextPartColor(d) }; + d.parts.push(part); + } else if (blob) { + const p = d.parts.find((x) => x.id === part!.id)!; + p.blob = blob; + p.version = picked.version; + } + compId = nextAsmId(d, 'c'); + const first = !d.components.length; + d.components.push({ + id: compId, name: instanceName(d, part.name), part: part.id, + placement: { p: first || !b ? [0, 0, 0] : [b.max[0] + gap, 0, 0], q: [0, 0, 0, 1] }, + fixed: first, + }); + }, false); + app.selection.set([{ kind: 'feature', id: compId }]); + // The new component is placed beside the others: show them all. + mode.fitPending = true; + const c = mode.component(compId); + app.setStatus(c?.fixed ? `${c.name} is fixed at the origin. Insert more components and mate them to it.` : `Inserted ${c?.name}. Drag it into place, or add mates (Mate).`, true); +} + +// ---------- Mate ---------- + +const MATE_TYPES: MateType[] = ['coincident', 'parallel', 'perpendicular', 'distance', 'angle', 'concentric', 'tangent', 'lock']; + +export class MatePanel extends PropertyPanel { + title = 'Mate'; + icon = 'mate'; + private box!: SelectionBox; + private refs: MateRef[] = []; + private type: MateType | null = null; + private aligned = true; + private flip = false; + private value: Param = 10; + private auto = true; + private result = h('div', { class: 'pm-msg', role: 'status' }); + + constructor(private mode: AssemblyMode, private existing: Mate | null = null) { + super(); + this.helpText = 'Select two faces, edges or planes of different components (or of a component and the assembly). Mates keep them together as you move things.'; + if (existing) { + this.editingId = existing.id; + this.refs = [existing.a, existing.b]; + this.type = existing.type; + this.aligned = existing.aligned; + this.flip = !!existing.flip; + this.value = existing.value ?? (existing.type === 'angle' ? 90 : 10); + this.auto = false; + this.title = `Mate: ${existing.name}`; + } else { + const pre = mode.app.selection.items.map((it) => mode.refOf(it)).filter((r): r is MateRef => !!r).slice(0, 2); + if (pre.length) { this.refs = pre; this.pickDefaults(); } + } + } + + private geo(r: MateRef): Geo | null { + const e = this.mode.entity(r); + if (typeof e === 'string') return null; + const comp = e.body ? this.mode.solved.get(e.body) ?? null : null; + return placeGeo(e.geo, comp); + } + + private label(r: MateRef): string { + if ('plane' in r) return BASE_PLANE_NAMES[r.plane]; + const c = this.mode.component(r.comp)?.name ?? '?'; + if ('face' in r) return `Face (${r.face.sig.type}) of ${c}`; + if ('edge' in r) return `Edge (${r.edge.sig.type}) of ${c}`; + return c; + } + + /** The type, alignment, side and value that fit the two entities where they are. */ + private pickDefaults() { + if (this.refs.length < 2) return; + const [a, b] = this.refs.map((r) => this.geo(r)); + if (!a || !b) return; + const fits = fittingMates(a, b); + if (this.auto || !this.type || !fits.includes(this.type)) this.type = fits[0] ?? 'coincident'; + const st = initialMateSettings(this.type, a, b); + this.aligned = st.aligned; + this.flip = st.flip; + if (this.type === 'distance') this.value = Math.round(st.value * 1000) / 1000; + if (this.type === 'angle') this.value = Math.round(st.value * 100) / 100; + } + + render(): HTMLElement[] { + const app = this.mode.app; + const ctx = app.unitContext(); + this.box = new SelectionBox(this, 'Entities to mate', { face: true, edge: true, plane: true, feature: true }, (it) => this.convert(it), (items) => { + if (items.length > 2) { this.box.setItems(items.slice(-2)); return; } + this.refs = items.map((x) => x.data as MateRef); + if (!this.existing) this.pickDefaults(); + this.mode.app.refreshPanel(); + this.update(); + }, { placeholder: 'Select two faces, edges or planes', icon: 'mate' }); + this.box.setItems(this.refs.map((r) => ({ item: this.mode.itemOf(r), data: r, label: this.label(r) }))); + const geos = this.refs.length === 2 ? this.refs.map((r) => this.geo(r)) : null; + const fits = geos && geos[0] && geos[1] ? MATE_TYPES.filter((t) => t === 'lock' || !mateProblem(t, geos[0]!, geos[1]!)) : MATE_TYPES; + const type = this.type ?? 'coincident'; + const typeSel = selectField('Mate type', type, fits.map((t) => ({ value: t, label: MATE_LABELS[t] })), (v) => { + this.type = v; + this.auto = false; + this.pickDefaults(); + this.mode.app.refreshPanel(); + this.update(); + }, `mate:${type}`); + const out: HTMLElement[] = [section('Mate Selections', [this.box.el]), section('Standard Mates', [typeSel])]; + const extra: HTMLElement[] = []; + if (type === 'distance' || type === 'angle') { + extra.push(numberField({ + label: type === 'distance' ? 'Distance' : 'Angle', icon: type === 'distance' ? 'smartDimension' : 'angle', value: this.value, kind: type === 'distance' ? 'length' : 'angle', ctx, min: type === 'distance' ? 0 : 0, max: type === 'angle' ? 180 : undefined, + onChange: (v) => { this.value = v; this.update(); }, + })); + } + if (type === 'distance' || type === 'tangent') extra.push(checkbox('Flip dimension (other side)', this.flip, (v) => { this.flip = v; this.update(); })); + if (type !== 'perpendicular' && type !== 'lock' && type !== 'tangent') { + extra.push(h('div', { class: 'field-label' }, 'Mate alignment'), segmented('Mate alignment', this.aligned ? 'aligned' : 'anti', [ + { value: 'aligned', label: 'Aligned' }, { value: 'anti', label: 'Anti-Aligned' }, + ], (v) => { this.aligned = v === 'aligned'; this.update(); })); + } + if (extra.length) out.push(section('Options', extra)); + out.push(h('section', { class: 'pm-section' }, this.result)); + queueMicrotask(() => this.update()); + return out; + } + + private convert(it: SelItem): SelBoxItem | null { + const r = this.mode.refOf(it); + if (!r) return null; + if ('comp' in r && !('face' in r) && !('edge' in r) && this.type !== 'lock') { + // A component picked in the tree only takes a lock mate. + this.type = 'lock'; + this.auto = false; + } + return { item: it, data: r, label: this.label(r) }; + } + + /** The mate as it would be added. */ + private mate(): Mate | null { + if (this.refs.length !== 2 || !this.type) return null; + const doc = this.mode.doc; + let [a, b] = this.refs; + if (this.type === 'lock') { + a = 'comp' in a ? { comp: a.comp } : a; + b = 'comp' in b ? { comp: b.comp } : b; + } + const m: Mate = { + id: this.existing?.id ?? '', name: this.existing?.name ?? '', type: this.type, a, b, aligned: this.aligned, + ...(this.type === 'distance' || this.type === 'angle' ? { value: this.value } : {}), + ...(this.flip && (this.type === 'distance' || this.type === 'tangent') ? { flip: true } : {}), + ...(this.existing?.suppressed ? { suppressed: true } : {}), + }; + if (this.type === 'lock') { + const pa = 'comp' in a ? this.mode.solved.get(a.comp) ?? doc.components.find((c) => c.id === (a as { comp: Id }).comp)?.placement : { p: [0, 0, 0] as Vec3, q: [0, 0, 0, 1] as [number, number, number, number] }; + const pb = 'comp' in b ? this.mode.solved.get(b.comp) ?? doc.components.find((c) => c.id === (b as { comp: Id }).comp)?.placement : { p: [0, 0, 0] as Vec3, q: [0, 0, 0, 1] as [number, number, number, number] }; + if (pa && pb) m.rel = relativePlacement(pa, pb); + } + return m; + } + + private withMate(d: AssemblyDocument, m: Mate) { + if (this.existing) d.mates = d.mates.map((x) => (x.id === m.id ? m : x)); + else { + m.id = nextAsmId(d, 'm'); + const n = d.mates.filter((x) => x.type === m.type).length + 1; + let name = `${MATE_LABELS[m.type]}${n}`; + for (let k = n + 1; d.mates.some((x) => x.name === name); k++) name = `${MATE_LABELS[m.type]}${k}`; + m.name = name; + d.mates.push(m); + } + } + + /** Shows where the components go with the mate, and whether it holds. */ + private update() { + const m = this.mate(); + const mode = this.mode; + if (!m) { this.result.textContent = this.refs.length < 2 ? 'Select two entities to mate.' : ''; this.result.className = 'pm-msg'; mode.previewPlacements(null); return; } + const d = structuredClone({ ...mode.doc, blobs: {} }) as AssemblyDocument; + this.withMate(d, m); + const r = mode.solveDoc(d); + const id = this.existing?.id ?? d.mates[d.mates.length - 1].id; + const problem = r.invalid.get(id) ?? (r.conflicts.has(id) ? 'This mate cannot hold with the existing mates (over defined). Change it, or delete or suppress a mate it conflicts with.' : null); + if (problem) { + this.result.className = 'pm-msg error'; + this.result.textContent = problem; + } else { + this.result.className = 'pm-msg info'; + this.result.textContent = r.status === 'full' ? 'The assembly is fully defined.' : `The mate holds. ${r.dof} degrees of freedom are left.`; + } + mode.previewPlacements(r.placements); + } + + ok(): boolean { + const m = this.mate(); + if (!m) { this.setMessage('error', 'Select two entities to mate.'); return false; } + const d = structuredClone({ ...this.mode.doc, blobs: {} }) as AssemblyDocument; + this.withMate(d, m); + const r = this.mode.solveDoc(d); + const id = this.existing?.id ?? d.mates[d.mates.length - 1].id; + const problem = r.invalid.get(id); + if (problem) { this.setMessage('error', problem); return false; } + this.mode.previewPlacements(null); + this.mode.commit(this.existing ? `Edit ${m.name}` : 'Add mate', (doc) => this.withMate(doc, m)); + return true; + } + + cancel() { + this.mode.previewPlacements(null); + } + + get edited(): boolean { + return this.refs.length === 2 && !this.existing; + } +} + +// ---------- Move / Rotate Component ---------- + +export class MovePanel extends PropertyPanel { + icon: string; + title: string; + confirm = false; + private axis: 'x' | 'y' | 'z' = 'y'; + private delta: Vec3 = [0, 0, 0]; + private angle = 90; + + constructor(private mode: AssemblyMode, private rotate: boolean) { + super(); + this.title = rotate ? 'Rotate Component' : 'Move Component'; + this.icon = rotate ? 'rotateComponent' : 'moveComponent'; + mode.rotateMode = rotate; + this.helpText = rotate + ? 'Drag a component to turn it; mates are kept (a component on a hinge turns about it). Fixed components do not move. Outside this command, Alt+drag turns a component too.' + : 'Drag a component to move it; mates are kept, so a mated component slides or turns only as its mates allow. Fixed components do not move. Alt+drag turns a component.'; + } + + render(): HTMLElement[] { + const app = this.mode.app; + const ctx = app.unitContext(); + const sel = this.target(); + const apply = h('button', { class: 'btn small', type: 'button', disabled: !sel }, this.rotate ? 'Rotate' : 'Move'); + apply.addEventListener('click', () => this.apply()); + const fields = this.rotate + ? [selectField('About axis', this.axis, [{ value: 'x', label: 'Assembly X' }, { value: 'y', label: 'Assembly Y' }, { value: 'z', label: 'Assembly Z' }], (v) => { this.axis = v; }), + numberField({ label: 'Angle', icon: 'angle', value: this.angle, kind: 'angle', ctx, allowExpr: false, onChange: (v) => { this.angle = Number(v); } })] + : (['X', 'Y', 'Z'] as const).map((k, i) => numberField({ label: `Delta ${k}`, value: this.delta[i], kind: 'length', ctx, allowExpr: false, onChange: (v) => { this.delta[i] = Number(v); } })); + return [ + section(this.rotate ? 'Rotate by' : 'Move by', [ + h('p', { class: 'field-label' }, sel ? `Selected: ${sel.name}` : 'Select a floating component (a face of it, or its row in the tree) to move it by exact amounts.'), + ...fields, apply, + ]), + ]; + } + + private target() { + const it = this.mode.app.selection.items[0]; + const c = it?.kind === 'feature' ? this.mode.component(it.id) : it?.kind === 'face' ? this.mode.faceComponent(it.index) : it?.kind === 'edge' ? this.mode.edgeComponent(it.index) : undefined; + return c && !c.fixed && !c.suppressed ? c : null; + } + + private apply() { + const c = this.target(); + if (!c) return; + const mode = this.mode; + const pl = mode.solved.get(c.id) ?? c.placement; + const g = mode.geometryOf(c.part)?.bbox; + const center: Vec3 = g ? scale(add(g.min, g.max), 0.5) : [0, 0, 0]; + let result; + if (this.rotate) { + const axis: Vec3 = this.axis === 'x' ? [1, 0, 0] : this.axis === 'y' ? [0, 1, 0] : [0, 0, 1]; + result = mode.dragSolve({ kind: 'rotate', body: c.id, q: qMul(qAxisAngle(axis, (this.angle * Math.PI) / 180), pl.q) }, mode.solved); + } else { + const target = add(add(pl.p, rotateLocal(pl.q, center)), this.delta); + result = mode.dragSolve({ kind: 'move', body: c.id, local: center, target }, mode.solved); + } + mode.commitPlacements(this.rotate ? 'Rotate component' : 'Move component', result); + } + + onPick(item: SelItem): boolean { + this.mode.app.selection.set([item]); + this.mode.app.refreshPanel(); + return true; + } + + filter() { + return { face: true, edge: true }; + } + + ok() { return true; } + + dispose() { + this.mode.rotateMode = false; + } +} + +function rotateLocal(q: [number, number, number, number], v: Vec3): Vec3 { + const [x, y, z, w] = q; + const ix = w * v[0] + y * v[2] - z * v[1], iy = w * v[1] + z * v[0] - x * v[2], iz = w * v[2] + x * v[1] - y * v[0], iw = -x * v[0] - y * v[1] - z * v[2]; + return [ix * w + iw * -x + iy * -z - iz * -y, iy * w + iw * -y + iz * -x - ix * -z, iz * w + iw * -z + ix * -y - iy * -x]; +} + +// ---------- Exploded view ---------- + +export class ExplodePanel extends PropertyPanel { + title = 'Explode Step'; + icon = 'explode'; + private comps: Id[] = []; + private dirKind: 'x' | 'y' | 'z' | 'pick' = 'y'; + private picked: Vec3 | null = null; + private pickedLabel = ''; + private distance: Param = 50; + private reverse = false; + + constructor(private mode: AssemblyMode, private existing: ExplodeStep | null = null) { + super(); + this.helpText = 'Select the components to move, a direction (an assembly axis, or a face or straight edge) and how far. Explode/Collapse switches between the exploded and assembled views.'; + if (existing) { + this.editingId = existing.id; + this.title = `Explode Step: ${existing.name}`; + this.comps = [...existing.comps]; + this.distance = existing.distance; + const d = existing.dir; + const axis = (['x', 'y', 'z'] as const).find((_, i) => Math.abs(Math.abs(d[i]) - 1) < 1e-9); + if (axis) { this.dirKind = axis; this.reverse = d[['x', 'y', 'z'].indexOf(axis)] < 0; } else { this.dirKind = 'pick'; this.picked = d; this.pickedLabel = 'Direction of the step'; } + } else { + const sel = mode.app.selection.items.map((it) => this.compOf(it)).filter((x): x is Id => !!x); + this.comps = [...new Set(sel)]; + } + } + + private compOf(it: SelItem): Id | null { + if (it.kind === 'feature' && this.mode.component(it.id)) return it.id; + if (it.kind === 'face') return this.mode.faceComponent(it.index)?.id ?? null; + if (it.kind === 'edge') return this.mode.edgeComponent(it.index)?.id ?? null; + return null; + } + + render(): HTMLElement[] { + const ctx = this.mode.app.unitContext(); + const box = new SelectionBox(this, 'Components to explode', { face: true, feature: true }, (it) => { + const id = this.compOf(it); + return id ? { item: { kind: 'feature', id }, data: id, label: this.mode.component(id)!.name } : null; + }, (items) => { this.comps = items.map((x) => x.data as Id); this.showStep(); }, { placeholder: 'Select components', icon: 'part' }); + box.setItems(this.comps.map((id) => ({ item: { kind: 'feature', id }, data: id, label: this.mode.component(id)?.name ?? id }))); + const dirBox = new SelectionBox(this, 'Direction from a face or edge', { face: true, edge: true }, (it) => { + const f = it.kind === 'face' ? this.mode.app.faces[it.index] : null; + const e = it.kind === 'edge' ? this.mode.app.edges[it.index] : null; + const d = f?.normal ?? f?.axis?.d ?? e?.dir ?? e?.axis; + if (!d) return null; + return { item: it, data: d, label: f ? `Face (${f.type})` : `Edge (${e!.type})` }; + }, (items) => { + const it = items[0]; + this.picked = it ? it.data as Vec3 : null; + this.pickedLabel = it?.label ?? ''; + if (it) this.dirKind = 'pick'; + this.showStep(); + this.mode.app.refreshPanel(); + }, { single: true, placeholder: 'Optional: select a face or edge', icon: 'axis' }); + if (this.picked && this.dirKind === 'pick') dirBox.setItems([{ item: null, data: this.picked, label: this.pickedLabel }]); + queueMicrotask(() => this.showStep()); + return [ + section('Components', [box.el]), + section('Direction', [ + selectField('Explode direction', this.dirKind, [ + { value: 'x', label: 'Along X' }, { value: 'y', label: 'Along Y' }, { value: 'z', label: 'Along Z' }, { value: 'pick', label: 'Along the selected face or edge' }, + ], (v) => { this.dirKind = v; this.showStep(); }, 'axis'), + dirBox.el, + checkbox('Reverse direction', this.reverse, (v) => { this.reverse = v; this.showStep(); }), + numberField({ label: 'Distance', icon: 'smartDimension', value: this.distance, kind: 'length', ctx, onChange: (v) => { this.distance = v; this.showStep(); } }), + ]), + ]; + } + + private dir(): Vec3 | null { + const base: Vec3 | null = this.dirKind === 'x' ? [1, 0, 0] : this.dirKind === 'y' ? [0, 1, 0] : this.dirKind === 'z' ? [0, 0, 1] : this.picked; + return base ? scale(normalize(base), this.reverse ? -1 : 1) : null; + } + + private step(): ExplodeStep | null { + const dir = this.dir(); + if (!dir || !this.comps.length) return null; + return { id: this.existing?.id ?? '', name: this.existing?.name ?? '', comps: [...this.comps], dir, distance: this.distance }; + } + + private showStep() { + this.mode.previewExplode(this.step(), this.existing?.id ?? null); + } + + ok(): boolean { + const s = this.step(); + if (!s) { this.setMessage('error', this.comps.length ? 'Choose a direction: select a face or edge, or an axis.' : 'Select the components to explode.'); return false; } + this.mode.previewExplode(null, null); + this.mode.commit(this.existing ? `Edit ${s.name}` : 'Add explode step', (d) => { + if (this.existing) d.explode = d.explode.map((x) => (x.id === s.id ? s : x)); + else { + s.id = nextAsmId(d, 'x'); + // The next number no step has (a step deleted before it leaves a gap). + let k = d.explode.length + 1; + while (d.explode.some((x) => x.name.toLowerCase() === `explode step${k}`)) k++; + s.name = `Explode Step${k}`; + d.explode.push(s); + } + d.exploded = true; + }, false); + return true; + } + + cancel() { + this.mode.previewExplode(null, null); + } +} + +// ---------- Interference ---------- + +export class InterferencePanel extends PropertyPanel { + title = 'Interference Detection'; + icon = 'interference'; + confirm = false; + private out = h('div', { class: 'sec-body' }); + private seq = 0; + + constructor(private mode: AssemblyMode) { + super(); + this.helpText = 'Overlapping volumes are shown in red. Click a result to select its components.'; + } + + render(): HTMLElement[] { + const again = h('button', { class: 'btn small', type: 'button' }, icon('rebuild', 14), 'Calculate again'); + again.addEventListener('click', () => void this.run()); + queueMicrotask(() => void this.run()); + return [section('Results', [this.out, again])]; + } + + async run() { + const app = this.mode.app; + const seq = ++this.seq; + this.out.replaceChildren(h('div', { class: 'field-label', role: 'status' }, 'Calculating...')); + await app.whenBuilt(); + if (seq !== this.seq) return; + this.checked = this.key(); + let pairs: InterferencePair[]; + try { + pairs = await app.kernel.assembly({ op: 'interference' }); + } catch (e) { + if (seq !== this.seq) return; + this.out.replaceChildren(h('div', { class: 'pm-msg error', role: 'alert' }, (e as Error).message)); + return; + } + if (seq !== this.seq || app.panel !== this) return; + // The pairs are numbered as the worker's scene is. + const comps = this.mode.sceneComps; + const name = (i: number) => this.mode.component(comps[i])?.name ?? '?'; + const u = UNIT_SYSTEMS[app.store.doc.units]; + const vol = (v: number) => `${formatGroup([v / u.scale ** 3], Math.max(2, app.store.doc.decimals))[0]} ${u.length}³`; + app.renderer.setPreview(mergeMeshes(pairs.map((p) => p.mesh)), 'tool', true); + // Checked where the components are shown: exploded, they are apart. + const exploded = this.mode.doc.exploded ? h('div', { class: 'pm-msg warn' }, 'The exploded view is shown: collapse it (Explode/Collapse) to check the assembled position.') : null; + // Pairs whose overlap could not be computed are not called clear. + const failed = pairs.filter((p) => p.failed); + const found = pairs.filter((p) => !p.failed); + const unchecked = failed.length + ? h('div', { class: 'pm-msg error', role: 'alert' }, `Could not check ${failed.map((p) => `${name(p.a)} / ${name(p.b)}`).join(', ')}: the overlap could not be computed.`) + : null; + // Only solids are checked: say so when a part has surface bodies, so they are not taken as clear. + const parts = new Set((this.mode.model?.comps ?? []).map((id) => this.mode.component(id)?.part)); + const surfaced = [...parts].some((p) => !!p && !!this.mode.geometryOf(p)?.faces.some((f) => f.body)); + const surfaces = surfaced ? h('div', { class: 'pm-msg info' }, 'Surface bodies are not checked: interference is found between solids only.') : null; + const notes = [...(unchecked ? [unchecked] : []), ...(surfaces ? [surfaces] : []), ...(exploded ? [exploded] : [])]; + if (!found.length) { + this.out.replaceChildren(...(failed.length ? [] : [h('div', { class: 'pm-msg info', role: 'status' }, 'No interference: no two components overlap.')]), ...notes); + return; + } + const list = h('div', { class: 'file-list', role: 'list', 'aria-label': 'Interferences' }); + for (const p of found) { + const b = h('button', { class: 'file-item', type: 'button' }, h('span', { 'aria-hidden': 'true', style: { color: 'var(--danger)' } }, icon('interference', 16)), + h('span', { class: 'txt' }, h('span', { class: 'n' }, `${name(p.a)} and ${name(p.b)}`), h('span', { class: 'meta' }, `Interference volume ${vol(p.volume)}`))); + b.addEventListener('click', () => app.selection.set([{ kind: 'feature', id: comps[p.a] }, { kind: 'feature', id: comps[p.b] }])); + list.append(h('div', { class: 'file-row', role: 'listitem' }, b)); + } + this.out.replaceChildren(h('div', { class: 'pm-msg warn', role: 'status' }, `${found.length} ${found.length === 1 ? 'interference' : 'interferences'} found.`), list, ...notes); + } + + private timer = 0; + private checked = ''; + + /** The assembly changed under the panel: check it again (once it stops changing, a drag say). */ + private key(): string { + return JSON.stringify([...this.mode.model?.comps ?? []].map((id) => [id, this.mode.shownPlacement(id)])); + } + + onBuild() { + if (this.key() === this.checked) return; + clearTimeout(this.timer); + this.timer = window.setTimeout(() => void this.run(), 400); + } + + ok() { return true; } + + dispose() { + clearTimeout(this.timer); + this.seq++; + this.mode.app.renderer.setPreview(null); + } +} + +function mergeMeshes(list: (MeshData | null)[]): MeshData | null { + const ms = list.filter((m): m is MeshData => !!m && m.indices.length > 0); + if (!ms.length) return null; + const nv = ms.reduce((s, m) => s + m.positions.length, 0), ni = ms.reduce((s, m) => s + m.indices.length, 0); + const positions = new Float32Array(nv), normals = new Float32Array(nv), indices = new Uint32Array(ni); + let ov = 0, oi = 0; + for (const m of ms) { + positions.set(m.positions, ov); + normals.set(m.normals, ov); + for (let k = 0; k < m.indices.length; k++) indices[oi + k] = m.indices[k] + ov / 3; + ov += m.positions.length; + oi += m.indices.length; + } + return { positions, normals, indices, vertexFace: new Float32Array(nv / 3), edgePositions: new Float32Array(0), edgeIds: new Float32Array(0), vertices: new Float32Array(0) }; +} + +// ---------- Bill of materials ---------- + +export async function bomDialog(mode: AssemblyMode) { + const doc = mode.doc; + const rows = assemblyBom(doc, (id) => mode.partDoc(id)); + const csv = bomCsv(rows); + const table = rows.length + ? h('table', { class: 'table' }, + h('thead', {}, h('tr', {}, ['Item No.', 'Part Name', 'Quantity', 'Material'].map((t) => h('th', { scope: 'col' }, t)))), + h('tbody', {}, rows.map((r) => h('tr', {}, h('td', { class: 'num' }, String(r.item)), h('td', {}, r.name), h('td', { class: 'num' }, String(r.quantity)), h('td', {}, r.material || '—'))))) + : h('p', {}, 'The assembly has no components yet.'); + const v = await showDialog({ + title: 'Bill of Materials', wide: true, signal: mode.app.documentSignal, + body: [h('p', { class: 'field-label' }, `${doc.name}: ${rows.reduce((s, r) => s + r.quantity, 0)} components of ${rows.length} ${rows.length === 1 ? 'part' : 'parts'} (suppressed components are not counted).`), table], + buttons: [{ label: 'Copy', value: 'copy', left: true, disabled: !rows.length }, { label: 'Download CSV', value: 'csv', left: true, disabled: !rows.length }, { label: 'Close', value: 'close', primary: true }], + onAction: async (value) => { + if (value === 'copy') { + try { + // Tab-separated, as spreadsheets paste it (a comma in a part name stays in its cell). + await navigator.clipboard.writeText(bomCsv(rows, '\t')); + toast({ message: 'Copied to the clipboard', timeout: 1800 }); + } catch { + toast({ kind: 'error', message: 'Could not copy to the clipboard.' }); + } + return false; + } + return true; + }, + }); + if (v === 'csv') download(csv, `${safeName(doc.name)} BOM.csv`, 'text/csv'); +} + +// ---------- Mass properties ---------- + +export async function assemblyMassDialog(mode: AssemblyMode) { + const app = mode.app; + await app.whenBuilt(); + // Hidden components weigh as much as shown ones (suppressed ones are left out). + const comps = mode.sceneComps; + if (!comps.length) { toast({ kind: 'warning', message: 'There is no solid body yet.' }); return; } + const densities = comps.map((id) => mode.partDoc(mode.component(id)!.part)?.material?.density ?? 1000); + let r: AsmMassResult | null; + try { + r = await app.kernel.assembly({ op: 'mass', densities }); + } catch (e) { + toast({ kind: 'error', message: (e as Error).message }); + return; + } + if (!r) { toast({ kind: 'warning', message: 'There is no solid body yet.' }); return; } + const doc = app.store.doc; + const u = UNIT_SYSTEMS[doc.units]; + const dec = Math.max(2, doc.decimals); + const s = u.scale; + const fmt = (v: number) => formatGroup([v], dec)[0]; + const unspecified = comps.filter((id) => !mode.partDoc(mode.component(id)!.part)?.material).map((id) => mode.component(id)!.name); + // kg·mm² to mass units·length². + const k = 1 / u.massScale / (s * s); + const tensor = formatGroup(r.inertia.map((x) => x * k), 3); + const rows: [string, string][] = [ + ['Mass', `${fmt(r.mass / u.massScale)} ${u.mass}`], + ['Volume', `${fmt(r.volume / s ** 3)} ${u.length}³`], + ['Surface area', `${fmt(r.area / s ** 2)} ${u.length}²`], + ['Center of mass', `${formatGroup(r.center.map((c) => c / s), dec).join(', ')} ${u.length}`], + ['Principal moments', formatGroup(r.principal.moments.map((x) => x * k), 3).join(', ')], + ]; + await showDialog({ + title: 'Mass Properties', wide: true, signal: app.documentSignal, + body: [ + ...(unspecified.length ? [h('p', { class: 'pm-msg warn' }, `No material on ${unspecified.join(', ')}: 1000 kg/m³ is used for ${unspecified.length === 1 ? 'it' : 'them'}.`)] : []), + ...(r.open.length ? [h('p', { class: 'pm-msg warn' }, `${r.open.join(', ')} ${r.open.length === 1 ? 'has' : 'have'} no closed solid and ${r.open.length === 1 ? 'is' : 'are'} left out.`)] : []), + h('p', { class: 'field-label' }, `Mass properties of ${doc.name}, every component with its part's material (hidden components count; suppressed ones do not).`), + h('table', { class: 'table' }, h('tbody', {}, rows.map(([a, b]) => h('tr', {}, h('th', {}, a), h('td', { class: 'num' }, b))))), + h('div', { class: 'field-label' }, `Moments of inertia about the center of mass, assembly axes (${u.mass}·${u.length}²)`), + h('table', { class: 'table' }, h('tbody', {}, [0, 1, 2].map((row) => h('tr', {}, [0, 1, 2].map((c) => h('td', { class: 'num' }, `I${'xyz'[row]}${'xyz'[c]} = ${tensor[row * 3 + c]}`)))))), + ], + buttons: [{ label: 'Close', value: 'ok', primary: true }], + }); +} + +// ---------- updating embedded parts ---------- + +/** + * Reads the part files of the assembly again and takes the copies of those + * saved since the assembly took its copy (`force`: every one that can be read). + * Returns the names of the updated parts. + */ +export async function updateParts(mode: AssemblyMode, force = false): Promise<{ updated: string[]; missing: string[] }> { + const app = mode.app; + const signal = app.documentSignal; + const doc = mode.doc; + const updates: { id: Id; blob: Id; text: string; version: FileVersion | null; name: string }[] = []; + const missing: string[] = []; + const missingIds = new Set(); + for (const p of doc.parts) { + const src = p.source as Location | null; + if (!src) continue; + let newer = force; + if (!force) { + if (src.type === 'cloud') { + const now = await cloudVersion(src.path); + if (now === null) { missing.push(p.name); missingIds.add(p.id); continue; } + newer = !!now && (!p.version || versionChanged(now, p.version)); + } else { + const e = readIndexEntry(src.id); + if (!e) { missing.push(p.name); missingIds.add(p.id); continue; } + newer = !p.version || e.modified > p.version.modified; + } + } + if (!newer) continue; + try { + const read = await loadPart(src); + if (signal.aborted) return { updated: [], missing }; + const pd = parseDocument(read.text); + const text = serializeDocument(pd); + if (text === doc.blobs[p.blob]) continue; + updates.push({ id: p.id, blob: newPartBlobId(doc), text, version: read.version ?? localVersion(src), name: src.type === 'cloud' ? (src.path.split('/').pop() ?? p.name).replace(/\.(parametric|json)$/i, '') : pd.name }); + } catch { + missing.push(p.name); + missingIds.add(p.id); + } + } + if (signal.aborted || app.assembly !== mode) return { updated: [], missing }; + mode.missingParts = missingIds; + if (updates.length) { + for (const u of updates) mode.doc.blobs[u.blob] = u.text; + mode.commit('Update parts', (d) => { + for (const u of updates) { + const p = d.parts.find((x) => x.id === u.id); + if (p) { p.blob = u.blob; p.version = u.version; p.name = u.name || p.name; } + } + }); + } else app.renderTrees(); + return { updated: updates.map((u) => u.name), missing }; +} diff --git a/src/parametric/src/app/assembly/tree.ts b/src/parametric/src/app/assembly/tree.ts new file mode 100644 index 0000000000..51ca59fc59 --- /dev/null +++ b/src/parametric/src/app/assembly/tree.ts @@ -0,0 +1,323 @@ +// The design tree of an assembly: the assembly, its planes and origin, the +// components (with (f) for fixed and (-) for under-defined ones, as in other +// CAD systems), the Mates folder and the exploded view steps. Same rows, +// keys and menus as the part tree. + +import type { Id } from '../../model/types'; +import { BASE_PLANE_NAMES } from '../../model/planes'; +import type { BasePlane } from '../../model/types'; +import { type AssemblyDocument, mateComps } from '../../model/assembly'; +import { h, titleWhenClipped } from '../../ui/dom'; +import { icon } from '../../ui/icons'; +import type { App } from '../app'; +import type { SelItem } from '../selection'; +import type { AssemblyMode } from './mode'; + +interface Row { + key: string; + item: SelItem | null; + label: string; + icon: string; + depth: number; + kind: 'root' | 'plane' | 'origin' | 'component' | 'folder' | 'mate' | 'step'; + children?: boolean; + expanded?: boolean; + muted?: string; + suppressed?: boolean; + error?: string; + warning?: string; + /** Renamable item id. */ + id?: Id; +} + +export class AssemblyTree { + el: HTMLElement; + private list: HTMLElement; + private filter = ''; + private collapsed = new Set(); + private focusKey: string | null = null; + private renaming: Id | null = null; + private renameEl: HTMLInputElement | null = null; + private rendering = false; + private shown: Row[] = []; + private anchor: string | null = null; + + constructor(private app: App, private mode: AssemblyMode, flyout = false) { + const filterInput = h('input', { type: 'search', placeholder: 'Filter', 'aria-label': 'Filter the design tree' }) as HTMLInputElement; + filterInput.addEventListener('input', () => { this.filter = filterInput.value.trim().toLowerCase(); this.render(); }); + this.list = h('div', { class: 'tree', role: 'tree', 'aria-label': flyout ? 'Assembly design tree (flyout)' : 'Assembly design tree', 'aria-multiselectable': 'true' }); + this.list.addEventListener('keydown', (e) => this.onKey(e)); + this.el = flyout ? h('div', {}, this.list) : h('div', {}, h('div', { class: 'tree-filter' }, icon('search', 14), filterInput), this.list); + } + + private get doc(): AssemblyDocument { + return this.mode.doc; + } + + private rows(): Row[] { + const doc = this.doc; + const mode = this.mode; + const rows: Row[] = [{ key: 'part', item: null, label: doc.name, icon: 'assembly', depth: 0, kind: 'root' }]; + for (const k of ['front', 'top', 'right'] as BasePlane[]) rows.push({ key: `plane:${k}`, item: { kind: 'plane', ref: { kind: 'base', plane: k } }, label: BASE_PLANE_NAMES[k], icon: 'plane', depth: 1, kind: 'plane' }); + rows.push({ key: 'origin', item: { kind: 'origin' }, label: 'Origin', icon: 'origin', depth: 1, kind: 'origin' }); + for (const c of doc.components) { + const prefix = c.suppressed ? '' : c.fixed ? '(f) ' : mode.isDefined(c.id) ? '' : '(-) '; + const err = mode.componentError(c.id); + rows.push({ + key: c.id, id: c.id, item: { kind: 'feature', id: c.id }, label: `${prefix}${c.name}`, icon: 'part', depth: 1, kind: 'component', + suppressed: c.suppressed, muted: c.hidden ? ' (hidden)' : '', error: err?.kind === 'error' ? err.text : undefined, warning: err?.kind === 'warning' ? err.text : undefined, + }); + } + const matesOpen = !this.collapsed.has('mates'); + rows.push({ key: 'mates', item: null, label: 'Mates', icon: 'mate', depth: 1, kind: 'folder', children: doc.mates.length > 0, expanded: matesOpen, muted: doc.mates.length ? '' : ' (none)' }); + if (matesOpen || this.filter) for (const m of doc.mates) { + const err = mode.mateError(m.id); + const names = mode.mateLabel(m); + // A mate of a suppressed component does not act either: it shows suppressed. + const off = !!m.suppressed || mateComps(m).some((id) => mode.component(id)?.suppressed); + rows.push({ key: m.id, id: m.id, item: { kind: 'feature', id: m.id }, label: m.name, muted: names ? ` (${names})` : '', icon: `mate:${m.type}`, depth: 2, kind: 'mate', suppressed: off, error: err ?? undefined }); + } + if (doc.explode.length) { + const open = !this.collapsed.has('explode'); + rows.push({ key: 'explode', item: null, label: 'Exploded View', icon: 'explode', depth: 1, kind: 'folder', children: true, expanded: open, muted: doc.exploded ? ' (exploded)' : ' (collapsed)' }); + if (open || this.filter) for (const s of doc.explode) rows.push({ key: s.id, id: s.id, item: { kind: 'feature', id: s.id }, label: s.name, icon: 'explode', depth: 2, kind: 'step', muted: ` (${s.comps.length} ${s.comps.length === 1 ? 'component' : 'components'})` }); + } + if (!this.filter) return rows; + return rows.filter((r) => r.depth === 0 || r.label.toLowerCase().includes(this.filter)); + } + + render() { + if (!this.app.assembly) return; + const app = this.app; + const rows = this.rows(); + this.shown = rows; + const sel = app.selection; + const active = document.activeElement; + const hadFocus = !!active && this.list.contains(active); + const tabKey = this.focusKey && rows.some((r) => r.key === this.focusKey) ? this.focusKey : 'part'; + this.rendering = true; + this.list.textContent = ''; + this.rendering = false; + for (const r of rows) { + const selected = r.item ? sel.has(r.item) : false; + const el = h('div', { + class: `ti${r.suppressed ? ' suppressed' : ''}${r.error ? ' error' : ''}${app.panel?.editingId && app.panel.editingId === r.id ? ' editing' : ''}`, + role: 'treeitem', + tabindex: r.key === tabKey ? '0' : '-1', + 'aria-selected': r.item ? String(selected) : null, + 'aria-level': String(r.depth + 1), + 'aria-expanded': r.children ? String(!!r.expanded) : null, + 'data-key': r.key, + style: { paddingLeft: `${4 + r.depth * 14}px` }, + }); + const twisty = h('span', { class: r.children ? 'twisty' : 'twisty empty', 'aria-hidden': 'true' }, r.children ? icon(r.expanded ? 'chevronDown' : 'chevronRight', 12) : null); + twisty.addEventListener('click', (e) => { e.stopPropagation(); this.toggle(r.key); }); + el.append(twisty, icon(r.icon, 16)); + if (this.renaming && this.renaming === r.id) el.append(this.renameInput(r)); + else { + const label = h('span', { class: 'label' }, r.label, r.muted ? h('span', { class: 'muted' }, r.muted) : null); + titleWhenClipped(label); + el.append(label); + } + const states: string[] = []; + if (r.suppressed) states.push('Suppressed'); + if (r.kind === 'component' && r.label.startsWith('(f)')) states.push('Fixed'); + if (r.kind === 'component' && r.label.startsWith('(-)')) states.push('Under defined'); + if (r.error) { + el.append(h('span', { class: 'badge', title: r.error }, icon('error', 14))); + states.push(`Error: ${r.error}`); + } else if (r.warning) { + el.append(h('span', { class: 'badge warn', title: r.warning }, icon('warning', 14))); + states.push(`Warning: ${r.warning}`); + } + if (states.length) el.setAttribute('aria-description', states.join('. ')); + el.addEventListener('click', (e) => this.onClick(r, e)); + el.addEventListener('dblclick', () => this.onDouble(r)); + el.addEventListener('contextmenu', (e) => { + e.preventDefault(); + if (r.item && !sel.has(r.item)) sel.set([r.item]); + if (r.id) app.openFeatureMenu(r.id, e.clientX, e.clientY); + else if (r.item) app.openReferenceMenu(r.item, e.clientX, e.clientY); + else if (r.key === 'part') app.openCommandMenu(['properties', 'rename', 'equations', 'insertComponent', 'billOfMaterials'], e.clientX, e.clientY, 'Assembly menu'); + else if (r.key === 'mates') app.openCommandMenu(['mate'], e.clientX, e.clientY, 'Mates menu'); + else if (r.key === 'explode') app.openCommandMenu(['explodedView', 'toggleExplode'], e.clientX, e.clientY, 'Exploded view menu'); + }); + el.addEventListener('pointerenter', () => { if (r.item) sel.setHover(r.item); }); + el.addEventListener('pointerleave', () => { if (r.item) sel.setHover(null); }); + el.addEventListener('focus', () => { this.focusKey = r.key; }); + this.list.append(el); + } + if (hadFocus) { + const target = this.renaming && this.renameEl?.isConnected ? this.renameEl : this.list.querySelector(`[data-key="${CSS.escape(tabKey)}"]`); + target?.focus({ preventScroll: true }); + } + } + + private renameInput(r: Row): HTMLInputElement { + const id = r.id!; + if (this.renameEl?.dataset.id === id) return this.renameEl; + const current = this.mode.itemName(id) ?? ''; + const input = h('input', { class: 'rename', value: current, 'aria-label': 'Name', 'data-id': id }) as HTMLInputElement; + this.renameEl = input; + const refusal = (name: string) => this.mode.nameRefusal(id, name); + const finish = (save: boolean) => { + if (this.renaming !== id) return; + this.renaming = null; + this.renameEl = null; + const name = input.value.trim(); + const msg = save && name ? refusal(name) : null; + if (msg) this.app.setStatus(msg, true); + if (save && name && name !== current && !msg) this.mode.rename(id, name); + else this.render(); + this.focus(id); + }; + input.addEventListener('input', () => { input.removeAttribute('aria-invalid'); input.removeAttribute('title'); }); + input.addEventListener('keydown', (e) => { + if (e.isComposing || e.keyCode === 229) return; + e.stopPropagation(); + if (e.key === 'Enter') { + const msg = refusal(input.value.trim()); + if (msg) { + input.setAttribute('aria-invalid', 'true'); + input.title = msg; + this.app.setStatus(msg, true); + input.select(); + return; + } + finish(true); + } + if (e.key === 'Escape') finish(false); + }); + input.addEventListener('blur', () => { if (!this.rendering && input.isConnected) finish(true); }); + input.addEventListener('click', (e) => e.stopPropagation()); + requestAnimationFrame(() => { if (document.activeElement !== input) { input.focus(); input.select(); } }); + return input; + } + + startRename(id: Id) { + if (!this.mode.itemName(id)) return; + this.renaming = id; + this.renameEl = null; + this.render(); + const input = this.renameEl as HTMLInputElement | null; + if (input?.isConnected) { input.focus(); input.select(); } + } + + targets(id: Id): Id[] { + const sel = this.app.selection.ofKind('feature').map((x) => x.id); + return sel.includes(id) ? sel : [id]; + } + + private toggle(key: string) { + if (this.collapsed.has(key)) this.collapsed.delete(key); + else this.collapsed.add(key); + this.render(); + } + + private onClick(r: Row, e: MouseEvent) { + this.focusKey = r.key; + if (!r.item) { if (r.children) this.toggle(r.key); return; } + const app = this.app; + if (app.panel && app.panel.onPick(r.item, true)) { this.render(); return; } + if (e.shiftKey && this.selectRange(r.key)) return; + this.anchor = r.key; + if (e.ctrlKey || e.metaKey) app.selection.toggle(r.item); + else app.selection.set([r.item]); + } + + private selectRange(key: string): boolean { + const rows = this.shown; + const a = rows.findIndex((r) => r.key === this.anchor && r.item); + const b = rows.findIndex((r) => r.key === key); + if (a < 0 || b < 0) return false; + this.app.selection.set(rows.slice(Math.min(a, b), Math.max(a, b) + 1).flatMap((r) => (r.item ? [r.item] : []))); + return true; + } + + private onDouble(r: Row) { + if (r.id) this.mode.edit(r.id); + else if (r.key === 'part') this.app.commands.run('properties'); + } + + focus(key: string) { + this.focusKey = key; + const row = () => this.list.querySelector(`[data-key="${CSS.escape(key)}"]`); + row()?.focus(); + requestAnimationFrame(() => { + if (this.renameEl?.isConnected) return; + const now = document.activeElement; + if (now && now !== document.body && now.isConnected && this.list.contains(now)) return; + if (!now || now === document.body) row()?.focus(); + }); + } + + private onKey(e: KeyboardEvent) { + const items = [...this.list.querySelectorAll('.ti')]; + const cur = items.findIndex((x) => x === document.activeElement); + if (cur < 0) return; + const key = items[cur].dataset.key ?? ''; + const row = this.shown.find((r) => r.key === key); + const go = (i: number) => { + const t = items[Math.max(0, Math.min(items.length - 1, i))]; + this.focusKey = t.dataset.key!; + items.forEach((x) => x.setAttribute('tabindex', x === t ? '0' : '-1')); + t.focus(); + }; + switch (e.key) { + case 'ArrowDown': e.preventDefault(); go(cur + 1); break; + case 'ArrowUp': e.preventDefault(); go(cur - 1); break; + case 'Home': e.preventDefault(); go(0); break; + case 'End': e.preventDefault(); go(items.length - 1); break; + case 'ArrowRight': { + const expanded = items[cur].getAttribute('aria-expanded'); + if (expanded === 'false') { e.preventDefault(); this.toggle(key); this.focus(key); } + else if (expanded === 'true') { e.preventDefault(); go(cur + 1); } + break; + } + case 'ArrowLeft': { + if (items[cur].getAttribute('aria-expanded') === 'true') { e.preventDefault(); this.toggle(key); this.focus(key); break; } + const level = Number(items[cur].getAttribute('aria-level')); + const parent = items.slice(0, cur).findLastIndex((x) => Number(x.getAttribute('aria-level')) < level); + if (parent >= 0) { e.preventDefault(); go(parent); } + break; + } + case 'Enter': + e.preventDefault(); + e.stopPropagation(); + if (row?.id) this.mode.edit(row.id); + else if (key === 'part') this.app.commands.run('properties'); + else if (row?.children) { this.toggle(key); this.focus(key); } + break; + case ' ': + e.preventDefault(); + e.stopPropagation(); + items[cur].dispatchEvent(new MouseEvent('click', { bubbles: true, ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey })); + break; + case 'F10': + if (e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) { + e.preventDefault(); + e.stopPropagation(); + const r = items[cur].getBoundingClientRect(); + items[cur].dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: r.left + 24, clientY: r.bottom })); + } + break; + case 'F2': + if (row?.id) { e.preventDefault(); e.stopPropagation(); this.startRename(row.id); } + break; + case 'Delete': + case 'Backspace': + if (row?.id) { + e.preventDefault(); + e.stopPropagation(); + const keys = items.map((x) => x.dataset.key); + const order = [...keys.slice(cur + 1), ...keys.slice(0, cur).reverse()]; + void this.mode.deleteItems(this.targets(row.id)).then(() => { + if (this.mode.itemName(key) || !this.list.contains(document.activeElement)) return; + const next = order.find((k) => k && this.list.querySelector(`[data-key="${CSS.escape(k)}"]`)); + if (next) this.focus(next); + }); + } + break; + } + } +} diff --git a/src/parametric/src/app/dialogs.ts b/src/parametric/src/app/dialogs.ts index e1ad650f1e..1462210c12 100644 --- a/src/parametric/src/app/dialogs.ts +++ b/src/parametric/src/app/dialogs.ts @@ -277,7 +277,7 @@ export async function propertiesDialog(app: App, rename?: (name: string) => Prom return bad; }; const v = await showDialog({ - title: 'Part Properties', signal, + title: app.assembly ? 'Assembly Properties' : 'Part Properties', signal, body: [h('div', { class: 'grid-form' }, fieldLabel('Name', name), name, fieldLabel('Unit system', units), units, fieldLabel('Decimal places', decimals), decimals), error, h('p', { class: 'field-label' }, 'Changing units only changes how values are shown. The geometry keeps its size.')], buttons: [{ label: 'Cancel', value: 'cancel' }, { label: 'OK', value: 'ok', primary: true }], @@ -436,6 +436,8 @@ export async function massPropertiesDialog(app: App) { ['Mass', mp.solid ? `${fmt(mass)} ${u.mass}` : none], ['Volume', mp.solid ? `${fmt(mp.volume / s ** 3)} ${L}³` : none], ['Surface area', `${fmt(mp.area / s ** 2)} ${L}²`], + // Surface bodies have area only: stated apart, they are in none of the other values. + ...(mp.surfaceArea != null ? [['Surface bodies area', `${fmt(mp.surfaceArea / s ** 2)} ${L}² (not included above)`] as [string, string]] : []), ['Center of mass', mp.solid ? group(mp.center.map((c) => c / s)).join(', ') + ` ${L}` : none], ]; const tensorText = group(tensor, 3); diff --git a/src/parametric/src/app/drawing-commands.ts b/src/parametric/src/app/drawing-commands.ts new file mode 100644 index 0000000000..4b06d57c2a --- /dev/null +++ b/src/parametric/src/app/drawing-commands.ts @@ -0,0 +1,48 @@ +// Drawing commands for assemblies, sheet metal and weldments: balloons, the bill of materials +// and cut list tables, and the flat pattern view. + +import { addIcons } from '../ui/icons'; +import type { App } from './app'; +import type { Command } from './commands'; + +addIcons({ + balloon: [['circle', { cx: 9, cy: 9, r: 6, class: 'a' }], ['path', { d: 'M8 7l1.5-1v6' }], ['path', { d: 'M13.3 13.3L19.5 19.5' }], ['circle', { cx: 19.5, cy: 19.5, r: 1.2, class: 'f' }]], + autoBalloon: [['circle', { cx: 6, cy: 6, r: 3.5, class: 'a' }], ['circle', { cx: 18, cy: 6, r: 3.5, class: 'a' }], ['circle', { cx: 6, cy: 18, r: 3.5, class: 'a' }], ['path', { d: 'M8.5 8.5L12 12M15.5 8.5L12 12M8.5 15.5L12 12' }], ['rect', { x: 13, y: 13, width: 8, height: 8, rx: 0.5 }]], + drawingBom: [['path', { d: 'M3 5h18v14H3z', class: 's' }], ['path', { d: 'M3 9.5h18M3 14h18M7.5 5v14M17 5v14' }]], + drawingFlat: 'flatPattern', +}); + +export function drawingCommands(app: App): Command[] { + const views = () => app.inDrawing && !!app.store.doc.drawing?.views.length; + const members = () => !app.assembly && app.weldments.length > 0; + const sheetMetal = () => !app.assembly && !!app.bbox && app.store.doc.features.some((f) => f.type === 'baseFlange'); + return [ + { + id: 'drawing:balloon', label: 'Balloon', icon: 'balloon', keywords: 'drawing item number bill of materials bom cut list annotate', + description: 'Label a component (or a structural member) with its item number from the bill of materials (or the cut list).', + enabled: () => views() && (!!app.assembly || members()), checked: () => app.inDrawing && app.drawing.tool?.kind === 'balloon', + run: () => app.drawing.startTool('balloon'), + }, + { + id: 'drawing:autoBalloon', label: 'Auto Balloon', icon: 'autoBalloon', keywords: 'drawing balloons item numbers bill of materials bom', + description: 'Add a balloon to every component a view shows, numbered from the bill of materials.', + enabled: () => views() && !!app.assembly, checked: () => app.inDrawing && app.drawing.tool?.kind === 'autoBalloon', + run: () => app.drawing.startTool('autoBalloon'), + }, + { + id: 'drawing:bom', label: 'Bill of Materials', icon: 'drawingBom', keywords: 'drawing bom parts list table quantity', + description: 'Put the assembly’s bill of materials on the sheet: item number, part, material and quantity. It follows the assembly.', + enabled: () => app.inDrawing && !!app.assembly, run: () => app.drawing.addTable('bom'), + }, + { + id: 'drawing:cutList', label: 'Cut List', icon: 'cutList', keywords: 'drawing weldment table lengths angles members', + description: 'Put the weldment’s cut list on the sheet: item, quantity, description, length and end angles. It follows the part.', + enabled: () => app.inDrawing && members(), run: () => app.drawing.addTable('cutList'), + }, + { + id: 'drawing:flat', label: 'Flat Pattern', icon: 'drawingFlat', keywords: 'drawing sheet metal flat pattern unfold bend lines', + description: 'Add a view of the sheet metal part’s flat pattern, with bend lines, bend notes and its overall size.', + enabled: () => app.inDrawing && sheetMetal(), run: () => void app.drawing.addFlatView(), + }, + ]; +} diff --git a/src/parametric/src/app/drawing-sources.ts b/src/parametric/src/app/drawing-sources.ts new file mode 100644 index 0000000000..6436f7ebae --- /dev/null +++ b/src/parametric/src/app/drawing-sources.ts @@ -0,0 +1,132 @@ +// Drawing sources beyond the open part's body (see src/drawing/source.ts): an assembly's +// placed components, collapsed or exploded, with their bill of materials, and a sheet metal +// part's flat pattern. + +import { combinedName } from '../assembly/compose'; +import { flatEdges, flatProjection } from '../drawing/flat'; +import type { BomRow, DrawingSource } from '../drawing/source'; +import type { EdgeInfo, ProjectionResult } from '../kernel/protocol'; +import { type Vec3, add, normalize, qRotate, scale } from '../math/vec'; +import { type AsmComponent, type AsmPart, type Placement, assemblyBom } from '../model/assembly'; +import type { FlatPattern } from '../model/flat-pattern'; +import { placementMatrix } from '../assembly/compose'; +import { applyPlacement } from '../assembly/solver'; +import type { App } from './app'; +import type { AssemblyMode } from './assembly/mode'; + +export const ASSEMBLY_SOURCE = 'assembly'; +export const EXPLODED_SOURCE = 'assembly:exploded'; + +interface Placed { comp: AsmComponent; part: AsmPart; pl: Placement } + +/** + * Versions of assembly sources, counted across all of them: a drawing's projections are kept + * by version, so another assembly opened later must not find the same numbers. + */ +let versions = 0; + +/** + * The components of an open assembly as a drawing shows them: every component that is not + * suppressed (hidden ones too: hiding is for the graphics area), where the mates put it, or + * moved by the exploded view's steps. Edges are named as the assembly's graphics area names + * them (component id, '#', the part's edge name). + */ +export function assemblySource(app: App, m: AssemblyMode, exploded: boolean): DrawingSource { + let memo: { build: number; doc: unknown; quality: number } | null = null; + let state: { key: string; items: Placed[]; edges: EdgeInfo[]; bbox: { min: Vec3; max: Vec3 } | null } | null = null; + let version = 0; + const current = () => { + const doc = m.doc; + if (memo && memo.build === app.buildVersion && memo.doc === app.store.doc && memo.quality === app.settings.quality && state) return state; + memo = { build: app.buildVersion, doc: app.store.doc, quality: app.settings.quality }; + const items: Placed[] = []; + for (const c of doc.components) { + const part = doc.parts.find((p) => p.id === c.part); + if (c.suppressed || !part || !m.geometryOf(c.part)?.mesh) continue; + let pl = m.solved.get(c.id) ?? c.placement; + if (exploded) { + let off: Vec3 = [0, 0, 0]; + for (const s of doc.explode) { + if (!s.comps.includes(c.id)) continue; + let d = 0; + try { d = app.store.evalParam(s.distance, 'length'); } catch { d = 0; } + off = add(off, scale(normalize(s.dir), d)); + } + pl = { p: add(pl.p, off), q: pl.q }; + } + items.push({ comp: c, part, pl }); + } + const key = JSON.stringify(items.map((it) => [it.comp.id, m.key(it.part), placementMatrix(it.pl).map((v) => +v.toFixed(9))])); + if (state?.key === key) return state; + version = ++versions; + const edges: EdgeInfo[] = []; + const min: Vec3 = [Infinity, Infinity, Infinity], max: Vec3 = [-Infinity, -Infinity, -Infinity]; + for (const { comp, part, pl } of items) { + const g = m.geometryOf(part.id)!; + const P = (p: Vec3) => applyPlacement(pl, p); + const D = (d: Vec3) => qRotate(pl.q, d); + for (const e of g.edges) { + const out: EdgeInfo = { ...e, name: combinedName(comp.id, e.name), a: P(e.a), b: P(e.b), mid: P(e.mid) }; + if (e.dir) out.dir = D(e.dir); + if (e.center) out.center = P(e.center); + if (e.axis) out.axis = D(e.axis); + edges.push(out); + } + const pos = g.mesh!.positions; + for (let k = 0; k + 2 < pos.length; k += 3) { + const q = P([pos[k], pos[k + 1], pos[k + 2]]); + for (let i = 0; i < 3; i++) { if (q[i] < min[i]) min[i] = q[i]; if (q[i] > max[i]) max[i] = q[i]; } + } + } + state = { key, items, edges, bbox: min[0] <= max[0] ? { min, max } : null }; + return state; + }; + return { + version: () => (current(), version), + bbox: () => current().bbox, + edges: () => current().edges, + project: (views) => { + const s = current(); + const items = s.items.map((it) => ({ part: m.key(it.part), m: placementMatrix(it.pl), name: it.comp.name, color: it.part.color })); + return app.kernel.assembly({ op: 'project', items, views }); + }, + bom: () => assemblyBomRows(m), + }; +} + +/** The assembly's bill of materials as drawing rows (each with the edge prefixes of its components). */ +export function assemblyBomRows(m: AssemblyMode): BomRow[] { + const doc = m.doc; + return assemblyBom(doc, (id) => m.partDoc(id)).map((r) => ({ + item: r.item, name: r.name, material: r.material, qty: r.quantity, + prefixes: doc.components.filter((c) => c.part === r.part && !c.suppressed).map((c) => combinedName(c.id, '')), + })); +} + +/** A sheet metal part's flat pattern (computed by the geometry worker once per change of the body). */ +export function flatSource(app: App): DrawingSource { + interface Got { version: number; pattern: FlatPattern | null; error?: string; edges: EdgeInfo[] } + let got: Got | null = null; + let loading: { version: number; p: Promise } | null = null; + const load = (): Promise => { + const v = app.geometryVersion; + if (got?.version === v) return Promise.resolve(got); + if (loading?.version === v) return loading.p; + const p = app.kernel.flatPattern(0).then((r) => { + const g: Got = { version: v, pattern: r.pattern, error: r.error, edges: flatEdges(r.pattern) }; + got = g; + return g; + }); + loading = { version: v, p }; + return p; + }; + return { + version: () => app.geometryVersion, + bbox: () => app.bbox, + edges: () => (got?.version === app.geometryVersion ? got.edges : []), + project: async (views) => { + const g = await load(); + return views.map((v) => flatProjection(v.id, g.pattern, g.error)); + }, + }; +} diff --git a/src/parametric/src/app/drawing.ts b/src/parametric/src/app/drawing.ts index f6da3351ca..34408a3786 100644 --- a/src/parametric/src/app/drawing.ts +++ b/src/parametric/src/app/drawing.ts @@ -1,17 +1,34 @@ // Drawing workspace: a paper sheet with projected views of the part (hidden -// lines dashed), overall dimensions and a title block. Views can be dragged, -// added and removed; the sheet exports to PDF and SVG. +// lines dashed), section, detail and auxiliary views, dimensions measured from +// the model, centre marks, notes and a title block. Views and annotations can be +// dragged, added and removed; the sheet exports to PDF, SVG and DXF. -import type { ProjectionResult } from '../kernel/protocol'; -import type { DrawingDoc, DrawingView, DrawingViewKind, SheetSize } from '../model/types'; +import type { EdgeInfo, ProjectionResult } from '../kernel/protocol'; +import type { DrawingAnnotation, DrawingBom, DrawingCutList, DrawingDimension, DrawingDoc, DrawingRef, DrawingView, DrawingViewKind, HoleFeature, Id, SheetSize } from '../model/types'; +import type { Vec3 } from '../math/vec'; +import { flatSize } from '../model/flat-pattern'; +import { type CutList, cutListRows, memberOfFace, weldmentCutList } from '../model/weldments'; +import { type TableSpec, autoBalloons, balloonTip, bomTable, cutListTable, drawBalloon, itemOfEdge, splitTable, tableSize } from '../drawing/tables'; +import { ASSEMBLY_SOURCE, EXPLODED_SOURCE, flatSource } from './drawing-sources'; import { UNIT_SYSTEMS, formatNumber } from '../model/units'; -import { DIM_BELOW, DIM_LEFT, MARGIN, SHEET_LABELS, STANDARD_SCALES, VIEW_DIRS, VIEW_LABELS, buildSheet, placeView, projectedSize, scaleLabel, sheetDims, standardLayout, toPdf, toSvg, type ViewFrame } from '../drawing/sheet'; +import { + DIM_BELOW, DIM_LEFT, MARGIN, SHEETS, TITLE_H, SHEET_LABELS, STANDARD_SCALES, VIEW_LABELS, buildSheet, freeSpot, placeView, projectedSize, scaleLabel, sheetDims, + standardLayout, switchProjection, toPdf, toSvg, viewCaption, type Item, type ViewFrame, type ViewPlacement, +} from '../drawing/sheet'; +import { type AnnoFormat, type Geo, type HoleSpec, drawDimension, guessKind, holeCount, holeInstance, holeSpecOf, measure, resolveRef } from '../drawing/annotate'; +import { toDxf } from '../drawing/dxf'; +import type { DrawingSource } from '../drawing/source'; +import { type P2, type Prim, type ResolvedView, FLAT_SOURCE, SIDE_VECTORS, besideOrient, dependents, lineNormal, projectionRequest, resolveViews, standardKindOf } from '../drawing/views'; import { download, safeName } from '../platform/files'; import { h } from '../ui/dom'; import { icon } from '../ui/icons'; -import { toast } from '../ui/overlay'; +import { confirmDialog, toast } from '../ui/overlay'; import type { App } from './app'; -import { PropertyPanel, checkbox, section, selectField } from './pm'; +import { PropertyPanel, checkbox, section, segmented, selectField } from './pm'; +import { hiddenSurfaceFeatures } from './surface-display'; + +/** A sheet metal part (a flat pattern view can be added to its drawing). */ +const isSheetMetal = (app: App) => !app.assembly && app.store.doc.features.some((f) => f.type === 'baseFlange'); /** YYYY-MM-DD in the user's time zone (toISOString gives the UTC day, a day off in the evening or morning). */ function localDate(ms: number): string { @@ -19,17 +36,76 @@ function localDate(ms: number): string { return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; } +/** Commands that work on the sheet with the mouse. */ +export type DrawingToolKind = 'projected' | 'section' | 'detail' | 'auxiliary' | 'dimension' | 'note' | 'centerMark' | 'centerline' | 'holeCallout' | 'balloon' | 'autoBalloon'; + +export const TOOL_LABELS: Record = { + projected: 'Projected View', section: 'Section View', detail: 'Detail View', auxiliary: 'Auxiliary View', dimension: 'Smart Dimension', + note: 'Note', centerMark: 'Center Mark', centerline: 'Centerline', holeCallout: 'Hole Callout', balloon: 'Balloon', autoBalloon: 'Auto Balloon', +}; + +/** Commands that start by picking the view they work on. */ +const fromView = (k: DrawingToolKind) => k === 'projected' || k === 'section' || k === 'detail' || k === 'auxiliary' || k === 'autoBalloon'; + +/** Something picked on the sheet: a model edge or point seen in a view (`t`: where on a straight edge a balloon's leader is attached, a fraction of it from its start). */ +interface Pick { view: Id; ref: DrawingRef; geo: Geo; q: P2; t?: number } +type ToolOptions = { orient?: ToolState['orient']; leader?: boolean }; + +interface ToolState { + kind: DrawingToolKind; + parent?: Id; + /** Points clicked so far, in the parent's view coordinates. */ + pts: P2[]; + picks: Pick[]; + /** Section cutting line direction. */ + orient: 'horizontal' | 'vertical' | 'aligned'; + /** Notes: start with the leader's arrow. */ + leader: boolean; + hover: Pick | null; + cursor: P2 | null; +} + +/** Order of the sheet sizes in the list. */ +const SHEET_ORDER: SheetSize[] = ['A4', 'A3', 'A2', 'A1', 'Letter', 'Tabloid', 'ANSI C', 'ANSI D']; + +/** The name of a view in lists and messages. */ +export function viewName(d: DrawingDoc, v: DrawingView): string { + const t = v.type ?? 'model'; + if (t === 'model') return v.label ? `${VIEW_LABELS[v.kind]} (${v.label})` : VIEW_LABELS[v.kind]; + const r = resolveViews(d).get(v.id); + if (!r) return 'View'; + const cap = viewCaption(d, r).replace(/\s+SCALE .*$/, ''); + return cap.charAt(0) + cap.slice(1).toLowerCase().replace(/ ([a-z])-([a-z])$/, (_, a: string, b: string) => ` ${a.toUpperCase()}-${b.toUpperCase()}`).replace(/ ([a-z])$/, (_, a: string) => ` ${a.toUpperCase()}`); +} + +/** The next unused view letter (I, O and Q are skipped: they read as numbers). */ +export function nextLetter(d: DrawingDoc): string { + const used = new Set(d.views.filter((v) => v.type && v.type !== 'model' && v.type !== 'projected').map((v) => (v.label ?? '').toUpperCase())); + const letters = 'ABCDEFGHJKLMNPRSTUVWXYZ'; + for (let k = 1; k < 4; k++) { + for (const c of letters) { const s = c.repeat(k); if (!used.has(s)) return s; } + } + return 'X'; +} + export class DrawingWorkspace { readonly el: HTMLElement; private host: HTMLElement; private paper: HTMLElement; private selBox: HTMLElement; + private overlay: HTMLElement; active = false; selected: string | null = null; + /** The selected annotation. */ + selectedAnno: string | null = null; + tool: ToolState | null = null; private zoom = 1; private pan = { x: 0, y: 0 }; - private cache = new Map(); + /** Projections by the key of what they show (views that look the same way share one). */ + private cache = new Map(); private frames: ViewFrame[] = []; + private placements = new Map(); + private annoBoxes: { id: string; box: [number, number, number, number] }[] = []; private pending = false; /** A refresh was asked for while views were being projected. */ private refreshAgain = false; @@ -38,28 +114,40 @@ export class DrawingWorkspace { private panelChanging = false; private layoutPending = false; private sheetW = 297; + /** The sheet's warnings as last said (a toast says new ones). */ + private warned = ''; /** Says the views are being projected, when that takes a moment (a large part takes seconds). */ private busy = h('div', { class: 'drawing-busy', role: 'status' }); private sheetH = 210; + /** Where views get their geometry (see src/drawing/source.ts). */ + readonly sources = new Map(); constructor(private app: App) { this.paper = h('div', { class: 'paper', role: 'img', 'aria-label': 'Drawing sheet' }); this.selBox = h('div', { class: 'view-sel', hidden: true }); - this.host = h('div', { class: 'sheet-host' }, this.paper, this.selBox); + this.overlay = h('div', { class: 'drw-overlay', 'aria-hidden': 'true' }); + this.host = h('div', { class: 'sheet-host' }, this.paper, this.selBox, this.overlay); // An application: screen readers pass it the arrow keys instead of reading on with them // (and a label on a plain div is not read at all). this.el = h('div', { class: 'drawing-ws', hidden: true, tabindex: '0', role: 'application', - 'aria-label': 'Drawing. Drag views to move them, or select one in the Views list of the Drawing panel and move it with the arrow keys; Escape deselects it and Delete removes it. With no view selected the arrow keys move the sheet; plus and minus zoom.', + 'aria-label': 'Drawing. Drag views to move them, or select one in the Views list (or an annotation in the Annotations list) of the Drawing panel and move it with the arrow keys; Escape deselects it and Delete removes it. With nothing selected the arrow keys move the sheet; plus and minus zoom.', }, this.host, h('div', { class: 'drawing-empty', hidden: true }, 'There is no solid to draw yet. Build the part in the Model tab first.'), this.busy); app.shell.viewport.append(this.el); + this.sources.set('part', { + version: () => app.geometryVersion, + bbox: () => app.bbox, + project: (q) => { const hide = hiddenSurfaceFeatures(app); return app.kernel.project(hide.length ? q.map((v) => ({ ...v, hideSurfaces: hide })) : q); }, + edges: () => app.edges, + }); + this.sources.set(FLAT_SOURCE, flatSource(app)); this.bind(); // A drawing made before the part had a solid is laid out when the solid exists, even // if the drawing was left meanwhile; not once another document replaced that part. app.store.on((reason) => { - if (reason === 'load') { this.layoutPending = false; this.untouched = ''; } + if (reason === 'load') { this.layoutPending = false; this.untouched = ''; this.selectedAnno = null; this.tool = null; } // Undoing an edit made before the drawing was first shown takes the drawing out of the // part with it. A drawing nobody changed was never an edit: on screen, it stays. else if ((reason === 'undo' || reason === 'redo') && this.active && !app.store.doc.drawing && this.untouched) { @@ -72,6 +160,67 @@ export class DrawingWorkspace { return this.app.store.doc.drawing ?? null; } + /** + * A source by name; in an assembly, views that name none show the assembly. A name not known + * here (an assembly's view in a part file, or a damaged one) shows what the document has. + */ + source(name: string): DrawingSource | undefined { + const known = this.sources.has(name) ? name : 'part'; + return this.sources.get(known === 'part' && this.app.assembly ? ASSEMBLY_SOURCE : known); + } + + /** The bounding box of what a view of a source shows (absent: the part's, or the assembly's). */ + bbox(source = 'part'): { min: Vec3; max: Vec3 } | null { + return this.source(source)?.bbox() ?? null; + } + + /** The rows a bill of materials or cut list table shows (null: there is nothing to list). */ + tableOf(a: DrawingBom | DrawingCutList): TableSpec | null { + const app = this.app; + const doc = app.store.doc; + if (a.type === 'bom') { + const d = this.doc; + const first = d?.views.length ? resolveViews(d).get(d.views[0].id)?.source : undefined; + const rows = this.source(a.source ?? first ?? 'part')?.bom?.(); + return rows ? bomTable(rows) : null; + } + if (app.assembly || !app.weldments.length) return null; + const r = cutListRows(this.cutList(), doc.units, doc.decimals); + return cutListTable(r.rows, UNIT_SYSTEMS[doc.units].length); + } + + private cutListMemo: { build: number; doc: unknown; list: CutList } | null = null; + /** The weldment's cut list as last built. */ + private cutList(): CutList { + const app = this.app; + const m = this.cutListMemo; + if (m && m.build === app.buildVersion && m.doc === app.store.doc) return m.list; + const list = weldmentCutList(app.store.doc, app.weldments); + this.cutListMemo = { build: app.buildVersion, doc: app.store.doc, list }; + return list; + } + + /** + * The item number of what an edge of a source belongs to: its component's bill of materials + * row in an assembly, its structural member's cut list item in a weldment. + */ + itemOf(source: string, edge: string): number | null { + const src = this.source(source); + const rows = src?.bom?.(); + if (rows) return itemOfEdge(edge, rows); + const app = this.app; + if (app.assembly || source !== 'part' || !app.weldments.length) return null; + const e = app.edges.find((x) => x.name === edge); + if (!e) return null; + const items = this.cutList().items; + for (const fi of e.faces) { + const m = memberOfFace(app.faces[fi]?.name ?? ''); + const it = m && items.find((x) => x.members.some((y) => y.feature === m.feature && y.member === m.member)); + if (it) return it.item; + } + return null; + } + // ---------- lifecycle ---------- open() { @@ -84,23 +233,36 @@ export class DrawingWorkspace { close() { this.refreshAgain = false; + this.warned = ''; this.panelKey = ''; this.active = false; + this.tool = null; + this.el.classList.remove('drw-tool'); this.el.hidden = true; } - /** Creates a drawing with the standard views laid out on an A4 (or, for inch parts, Letter) sheet. */ + /** + * Creates a drawing with the standard views laid out on an A4 (or, for inch parts, Letter) + * sheet. An assembly's goes on an A3 (or Tabloid) sheet, with its bill of materials on the + * title block. + */ create() { - const b = this.app.bbox; - const size: SheetSize = this.app.store.doc.units === 'IPS' ? 'Letter' : 'A4'; - const layout = b ? standardLayout(sheetDims({ sheet: size, landscape: true }), b.min, b.max) : { scale: 1, views: [] }; + const b = this.bbox(); + const asm = !!this.app.assembly; + const ips = this.app.store.doc.units === 'IPS'; + const size: SheetSize = asm ? (ips ? 'Tabloid' : 'A3') : ips ? 'Letter' : 'A4'; + const sheet = sheetDims({ sheet: size, landscape: true }); + const annotations: DrawingAnnotation[] | undefined = asm ? [{ id: 'a1', type: 'bom', at: [sheet.w - MARGIN, sheet.h - MARGIN - TITLE_H], anchor: 'bottomRight' }] : undefined; + const layout = b ? standardLayout(sheet, b.min, b.max, this.layoutBottom(annotations, sheet)) : { scale: 1, views: [] }; // Opened before the first rebuild finished: lay out once the solid exists. this.layoutPending = !b; // Only looking at the drawing does not edit the part: it is neither marked edited nor // given an undo step until the drawing is changed (and is saved with the part from then). const drawing: DrawingDoc = { sheet: size, landscape: true, scale: layout.scale, - views: layout.views.map((v, i) => ({ ...v, id: `v${i + 1}` })), title: '', drawnBy: '', notes: '', + views: layout.views.map((v, i) => ({ ...v, id: `v${i + 1}`, centerMarks: true, ...(asm ? { source: ASSEMBLY_SOURCE } : {}) })), title: '', drawnBy: '', notes: '', + titleBlock: 'full', revision: '', + ...(annotations ? { annotations } : {}), }; this.app.store.doc.drawing = drawing; this.untouched = JSON.stringify(drawing); @@ -109,20 +271,75 @@ export class DrawingWorkspace { /** The drawing as created, until it is changed. */ private untouched = ''; + /** + * The height the standard views leave free along the bottom of the sheet: the title block's, + * and a table's standing on it. + */ + private layoutBottom(annotations: DrawingAnnotation[] | undefined, sheet: { w: number; h: number }): number { + let bottom = TITLE_H; + for (const a of annotations ?? []) { + if ((a.type !== 'bom' && a.type !== 'cutList') || a.anchor !== 'bottomRight') continue; + const t = this.tableOf(a); + // As tall as its tallest column, when it is split to stay on the sheet. + const box = t && splitTable(t, a.at, a.anchor, { top: MARGIN, bottom: sheet.h - MARGIN, left: MARGIN, right: sheet.w - MARGIN }).box; + if (box) bottom = Math.max(bottom, TITLE_H + (box[3] - box[1]) + 6); + } + return bottom; + } + + /** + * Arrange standard views from a button or command: first asks when it would delete views + * made since (sections, details...) or annotations on views. Resolves whether it arranged. + */ + async arrange(): Promise { + const d = this.doc; + if (!d) return false; + const views = d.views.filter((v) => (v.type ?? 'model') !== 'model').length; + const annos = (d.annotations ?? []).filter((a) => a.view).length; + if (views || annos) { + const n = (k: number, one: string, many: string) => `${k} ${k === 1 ? one : many}`; + const lost = [views && n(views, 'section, detail or other added view', 'section, detail and other added views'), annos && n(annos, 'annotation on a view', 'annotations on views')].filter(Boolean).join(' and '); + const ok = await confirmDialog('Arrange standard views', `This replaces the views on the sheet with the standard ones, so the ${lost} will be deleted.`, 'Arrange', true); + if (!ok || !this.doc) return false; + } + this.relayout(); + return true; + } + /** Re-lays out the standard views (keeps sheet settings). */ relayout() { - const b = this.app.bbox; + const b = this.bbox(); const d = this.doc; if (!b || !d) return; - const layout = standardLayout(sheetDims(d), b.min, b.max); + const layout = standardLayout(sheetDims(d), b.min, b.max, this.layoutBottom(d.annotations, sheetDims(d))); + const source = this.app.assembly ? { source: ASSEMBLY_SOURCE } : {}; + const first = d.projection === 'first'; const arrange = (x: DrawingDoc) => { x.scale = layout.scale; - x.views = layout.views.map((v, i) => ({ ...v, id: `v${i + 1}` })); + const centerMarks = x.titleBlock === 'full' ? true : undefined; + // First angle: the top view goes below the front view, and the view right of it is the left view. + x.views = layout.views.map((v, i) => { + const nv: DrawingView = { ...v, id: `v${i + 1}`, ...source }; + if (centerMarks) nv.centerMarks = true; + if (first && v.kind === 'top') nv.y = layout.views[0].y + (layout.views[0].y - v.y); + if (first && v.kind === 'right') nv.kind = 'left'; + if (first && v.kind === 'isometric') nv.y = layout.views[0].y + (layout.views[0].y - v.y); + return nv; + }); + if (first) { + // Mirrored about the front view's row: keep the whole layout on the sheet. + const { h: sh } = sheetDims(x); + const dy = Math.max(0, Math.max(...x.views.map((v) => v.y)) - (sh - MARGIN - 40)); + for (const v of x.views) v.y -= dy; + } + x.annotations = (x.annotations ?? []).filter((a) => !a.view); }; // A drawing nobody changed yet is still not an edit of the part. if (JSON.stringify(d) === this.untouched) { arrange(d); this.untouched = JSON.stringify(d); + // Not a document change, which would re-enable the commands that need views. + this.app.commands.changed(); void this.refresh(); } else this.app.store.change('Arrange views', (doc) => arrange(doc.drawing!)); } @@ -147,7 +364,12 @@ export class DrawingWorkspace { /** Rebuilds the PropertyManager if what it shows changed (not when a view only moved). */ private syncPanel() { const d = this.doc; - const key = d ? JSON.stringify([this.selected, this.app.store.doc.name, d.sheet, d.landscape, d.scale, d.title, d.drawnBy, d.notes, d.views.map((v) => [v.id, v.kind, v.hidden, v.dims])]) : ''; + const key = d ? JSON.stringify([ + this.selected, this.selectedAnno, this.tool && [this.tool.kind, this.tool.parent, this.tool.orient, this.tool.leader, this.tool.pts.length, this.tool.picks.length], + this.app.store.doc.name, d.sheet, d.landscape, d.scale, d.title, d.drawnBy, d.notes, d.revision, d.projection, d.titleBlock, + d.views.map((v) => [v.id, v.kind, v.hidden, v.dims, v.type, v.label, v.scale, v.tangent, v.centerMarks, v.source]), + (d.annotations ?? []).map((a) => [a.id, a.type, a.type === 'note' ? a.text : '', a.type === 'note' ? a.size : '', a.type === 'dimension' ? [a.decimals, a.prefix, this.dangling(a)] : '']), + ]) : ''; if (key === this.panelKey) return; this.panelKey = key; if (this.panelChanging) return; @@ -160,12 +382,27 @@ export class DrawingWorkspace { this.app.refreshPanel(); if (!was || was.isConnected) return; const rows = body.querySelectorAll('.relations-list > *'); - const controls = [...body.querySelectorAll('button, input, select')]; + const controls = [...body.querySelectorAll('button, input, select, textarea')]; const same = controls.find((el) => name(el) === name(was)); const near = row >= 0 ? rows[Math.min(row, rows.length - 1)]?.querySelector('button[aria-label^="Delete"]') ?? controls.find((el) => name(el) === 'Add view') : null; (same ?? near ?? body.querySelector('.pm-head .title'))?.focus(); } + /** The source a view's geometry comes from (projected, section and detail views: their parent's). */ + viewSource(id: Id): string | undefined { + const d = this.doc; + return d ? resolveViews(d).get(id)?.source : undefined; + } + + /** A dimension whose model geometry is gone. */ + dangling(a: DrawingAnnotation): boolean { + if (a.type !== 'dimension' && a.type !== 'centerMark' && a.type !== 'centerline' && a.type !== 'holeCallout' && a.type !== 'balloon') return false; + const p = this.placements.get(a.view); + if (!p) return false; + const refs = a.type === 'dimension' || a.type === 'centerline' ? a.refs : [a.ref]; + return refs.some((r) => !p.prims.some((q) => q.edge === r.edge)); + } + // ---------- projections and rendering ---------- /** Projects missing or outdated views, then renders. */ @@ -174,26 +411,43 @@ export class DrawingWorkspace { if (this.pending) { this.refreshAgain = true; return; } const d = this.doc; if (!d) return; - if (this.layoutPending && this.app.bbox) { + if (this.layoutPending && this.bbox()) { this.layoutPending = false; if (!d.views.length) { this.relayout(); return; } } - const version = this.app.geometryVersion; - const need = d.views.filter((v) => { - const c = this.cache.get(v.id); + const resolved = resolveViews(d); + // One request per projection key, with hidden lines if any view sharing it shows them. + const want = new Map(); + for (const v of d.views) { + const r = resolved.get(v.id); + if (!r) continue; + const w = want.get(r.key); + want.set(r.key, { r, hidden: (w?.hidden ?? false) || v.hidden }); + } + const bySource = new Map(); + for (const [key, w] of want) { + const src = this.source(w.r.source); + if (!src || !src.bbox()) continue; + const c = this.cache.get(key); // A view whose hidden lines are turned on needs them projected; turned off, they are just not drawn. - return !c || c.kind !== v.kind || c.version !== version || (v.hidden && !c.hidden); - }); - if (need.length && this.app.bbox) { + if (c && c.version === src.version() && (!w.hidden || c.hidden)) continue; + const list = bySource.get(w.r.source) ?? []; + list.push({ key, ...w }); + bySource.set(w.r.source, list); + } + if (bySource.size) { this.pending = true; + const versions = new Map([...bySource.keys()].map((s) => [s, this.source(s)!.version()])); // A sheet opened for the first time shows its border and title block meanwhile, not nothing. if (!this.paper.firstChild) this.render(); const slow = setTimeout(() => { this.busy.textContent = 'Projecting the views…'; }, 300); try { - const res = await this.app.kernel.project(need.map((v) => ({ id: v.id, ...VIEW_DIRS[v.kind], hidden: v.hidden }))); - for (const r of res) { - const v = need.find((x) => x.id === r.id)!; - this.cache.set(r.id, { kind: v.kind, version, hidden: v.hidden, result: r }); + for (const [name, list] of bySource) { + const res = await this.source(name)!.project(list.map((x) => projectionRequest(x.r, x.hidden))); + for (const r of res) { + const x = list.find((q) => q.key === r.id); + if (x) this.cache.set(x.key, { version: versions.get(name)!, hidden: x.hidden, result: r }); + } } } catch (e) { toast({ kind: 'error', title: 'Could not project the views', message: (e as Error).message }); @@ -203,29 +457,62 @@ export class DrawingWorkspace { this.busy.textContent = ''; } // The model or the views may have changed while projecting. - if (version !== this.app.geometryVersion || this.refreshAgain) { this.refreshAgain = false; void this.refresh(); return; } + const changed = [...versions].some(([s, ver]) => this.source(s)?.version() !== ver); + if (changed || this.refreshAgain) { this.refreshAgain = false; void this.refresh(); return; } } this.render(); } + private fmt(): AnnoFormat { + const doc = this.app.store.doc; + const u = UNIT_SYSTEMS[doc.units]; + return { + length: (mm, dec) => formatNumber(mm / u.scale, dec ?? doc.decimals), + angle: (deg, dec) => `${formatNumber(deg, dec ?? Math.min(doc.decimals, 2))}°`, + }; + } + private info() { const doc = this.app.store.doc; const u = UNIT_SYSTEMS[doc.units]; return { partName: doc.name, - material: doc.material?.name ?? 'Not specified', + material: this.app.assembly ? 'See bill of materials' : doc.material?.name ?? 'Not specified', units: u.length, date: localDate(doc.modified || Date.now()), formatLength: (mm: number) => formatNumber(mm / u.scale, doc.decimals), + edges: (src: string): EdgeInfo[] => this.source(src)?.edges() ?? [], + format: this.fmt(), + holeOf: (edge: string) => this.holeOf(edge), + table: (a: DrawingBom | DrawingCutList) => this.tableOf(a), + itemOf: (source: string, edge: string) => this.itemOf(source, edge), }; } + /** + * The hole feature a circular edge was made by, with its sizes and how many holes it made + * (pattern and mirror copies of it too: their faces' names trace back to it). + */ + private holeOf(edge: string): HoleSpec | null { + const app = this.app; + const e = app.edges.find((x) => x.name === edge); + if (!e || e.type !== 'circle' || !e.radius) return null; + const fid = e.faces.map((i) => holeInstance(app.faces[i]?.name ?? '')?.feature).find((id) => app.store.feature(id ?? '')?.type === 'hole'); + if (!fid) return null; + const f = app.store.resolve().features.find((x) => x.id === fid) as HoleFeature | undefined; + if (!f) return null; + return holeSpecOf(f, holeCount(app.faces.map((x) => x.name), fid)); + } + private sheet() { const d = this.doc!; const projections = new Map(); + const resolved = resolveViews(d); for (const v of d.views) { - const c = this.cache.get(v.id); - if (this.app.bbox && c?.version === this.app.geometryVersion && c.kind === v.kind) projections.set(v.id, c.result); + const r = resolved.get(v.id); + const src = r && this.source(r.source); + const c = r && this.cache.get(r.key); + if (src?.bbox() && c?.version === src.version()) projections.set(v.id, c.result); } return buildSheet(d, projections, this.info()); } @@ -235,6 +522,14 @@ export class DrawingWorkspace { if (!d || !this.active) return; const s = this.sheet(); this.frames = s.frames; + this.placements = s.placements; + this.annoBoxes = s.annos; + // What does not fit on the sheet is said once (and stays in red on the sheet). + const warn = s.warnings.join('\n'); + if (warn && warn !== this.warned) toast({ kind: 'warning', title: 'Drawing', message: warn }); + this.warned = warn; + if (this.selectedAnno && !(d.annotations ?? []).some((a) => a.id === this.selectedAnno)) this.selectedAnno = null; + if (this.selected && !d.views.some((v) => v.id === this.selected)) this.selected = null; // A new sheet size or orientation is refitted, or only part of it shows. const resized = s.w !== this.sheetW || s.h !== this.sheetH; this.sheetW = s.w; @@ -247,10 +542,11 @@ export class DrawingWorkspace { } this.paper.style.width = `${s.w}px`; this.paper.style.height = `${s.h}px`; - (this.el.querySelector('.drawing-empty') as HTMLElement).hidden = !!this.app.bbox; + (this.el.querySelector('.drawing-empty') as HTMLElement).hidden = !!this.bbox(); if (resized) this.fit(); else this.applyTransform(); this.drawSelection(); + this.drawOverlay(); this.syncPanel(); } @@ -260,10 +556,12 @@ export class DrawingWorkspace { private drawSelection() { const f = this.frames.find((x) => x.id === this.selected); - this.selBox.hidden = !f; - if (!f) return; - const pad = 3; - Object.assign(this.selBox.style, { left: `${f.x0 - pad}px`, top: `${f.y0 - pad}px`, width: `${f.x1 - f.x0 + 2 * pad}px`, height: `${f.y1 - f.y0 + 2 * pad}px` }); + const a = this.annoBoxes.find((x) => x.id === this.selectedAnno); + const b = f ? [f.x0, f.y0, f.x1, f.y1] : a ? a.box : null; + this.selBox.hidden = !b; + if (!b) return; + const pad = f ? 3 : 0.8; + Object.assign(this.selBox.style, { left: `${b[0] - pad}px`, top: `${b[1] - pad}px`, width: `${b[2] - b[0] + 2 * pad}px`, height: `${b[3] - b[1] + 2 * pad}px` }); } /** Zooms the sheet by f about the middle of the view. */ @@ -288,6 +586,504 @@ export class DrawingWorkspace { this.applyTransform(); } + // ---------- tools ---------- + + /** Starts a sheet command; a view selected beforehand is the one it works from. */ + startTool(kind: DrawingToolKind) { + if (!this.doc) return; + const needsParent = fromView(kind); + let parent = needsParent && this.selected && this.placements.has(this.selected) ? this.selected : undefined; + if (parent && !this.parentAllowed(kind, parent)) parent = undefined; + if (kind === 'autoBalloon' && parent) { this.autoBalloon(parent); return; } + this.tool = { kind, parent, pts: [], picks: [], orient: 'horizontal', leader: false, hover: null, cursor: null }; + this.el.classList.add('drw-tool'); + this.selectedAnno = null; + this.drawSelection(); + this.drawOverlay(); + this.syncPanel(); + this.app.setStatus(this.toolPrompt()); + this.app.commands.changed(); + this.el.focus({ preventScroll: true }); + } + + /** Only a detail view can be made from a flat pattern view (it has no direction to project from). */ + private parentAllowed(kind: DrawingToolKind, id: Id): boolean { + const v = this.doc?.views.find((q) => q.id === id); + return !(v?.type === 'flat' && kind !== 'detail' && kind !== 'autoBalloon'); + } + + cancelTool(): boolean { + if (!this.tool) return false; + this.tool = null; + this.el.classList.remove('drw-tool'); + this.drawOverlay(); + this.syncPanel(); + this.app.setStatus('Drawing. Drag views to arrange them; export to PDF, SVG or DXF from the Drafting tab.'); + // The command's ribbon button shows it is no longer on. + this.app.commands.changed(); + return true; + } + + setToolOption(o: ToolOptions) { + if (!this.tool) return; + Object.assign(this.tool, o); + this.tool.pts = []; + this.drawOverlay(); + this.syncPanel(); + this.app.setStatus(this.toolPrompt()); + } + + /** What the active command asks for next. */ + toolPrompt(): string { + const t = this.tool; + if (!t) return ''; + if (t.kind === 'autoBalloon') return 'Click the view to add balloons to.'; + if (fromView(t.kind) && !t.parent) return 'Click the view to make it from.'; + switch (t.kind) { + case 'projected': return 'Move the pointer to the side of the view to project to, and click to place the view.'; + case 'section': + if (t.orient === 'aligned') return t.pts.length === 0 ? 'Click the first end of the cutting line.' : t.pts.length === 1 ? 'Click the other end of the cutting line.' : 'Click on the side to look from to place the section view.'; + return t.pts.length === 0 ? `Click where the ${t.orient} cutting line goes (it snaps to centres and corners).` : 'Click on the side to look from to place the section view.'; + case 'detail': return t.pts.length === 0 ? 'Click the centre of the detail circle.' : t.pts.length === 1 ? 'Click to set the size of the circle.' : 'Click where the detail view goes.'; + case 'auxiliary': return t.pts.length === 0 ? 'Click a straight edge to look square to.' : 'Click on a side of the edge to place the auxiliary view.'; + case 'dimension': return t.picks.length === 0 ? 'Click an edge, circle or point of a view to dimension.' : t.picks.length === 1 ? 'Click a second edge or point, or click where the dimension goes.' : 'Click where the dimension goes.'; + case 'note': return t.leader && t.pts.length === 0 ? 'Click where the leader arrow points.' : 'Click where the note goes.'; + case 'centerMark': return 'Click a circle or arc of a view.'; + case 'centerline': return t.picks.length === 0 ? 'Click the first of two parallel edges.' : 'Click the second edge.'; + case 'holeCallout': return t.picks.length === 0 ? 'Click a hole (a circle seen end on).' : 'Click where the callout goes.'; + case 'balloon': return t.picks.length === 0 ? 'Click an edge of a component (or member) in a view.' : 'Click where the balloon goes.'; + } + } + + /** View coordinates of a sheet point in a placed view. */ + private toView(p: ViewPlacement, x: number, y: number): P2 { + return [(x - p.tx) / p.s, (y - p.ty) / p.s]; + } + + /** The model edge or point of a view under a sheet point, within a few pixels. */ + private pick(x: number, y: number, want: 'any' | 'point' | 'line' | 'circle', only?: Id): Pick | null { + const order = only ? [only] : [...this.frames].reverse().map((f) => f.id); + for (const id of order) { + const p = this.placements.get(id); + if (!p) continue; + const f = p.frame; + if (!only && !(x >= f.x0 - 3 && x <= f.x1 + 3 && y >= f.y0 - 3 && y <= f.y1 + 3)) continue; + const q = this.toView(p, x, y); + const tol = 7 / this.zoom / p.s; + let best: Pick | null = null, bd = tol; + const consider = (d: number, mk: () => Pick) => { if (d < bd) { bd = d; best = mk(); } }; + const dist = (a: P2) => Math.hypot(a[0] - q[0], a[1] - q[1]); + if (want === 'any' || want === 'point') { + for (const pr of p.prims) { + if (pr.kind === 'arc') { + consider(dist(pr.c), () => ({ view: id, ref: { edge: pr.edge, at: 'center' }, geo: { kind: 'point', p: pr.c }, q: pr.c })); + if (pr.full) continue; + } + consider(dist(pr.a), () => ({ view: id, ref: { edge: pr.edge, at: 'start' }, geo: { kind: 'point', p: pr.a }, q: pr.a })); + consider(dist(pr.b), () => ({ view: id, ref: { edge: pr.edge, at: 'end' }, geo: { kind: 'point', p: pr.b }, q: pr.b })); + } + if (best || want === 'point') return best; + } + for (const pr of p.prims) { + if (pr.kind === 'line' && (want === 'any' || want === 'line')) { + const dx = pr.b[0] - pr.a[0], dy = pr.b[1] - pr.a[1], L = dx * dx + dy * dy; + const t = L > 0 ? Math.max(0, Math.min(1, ((q[0] - pr.a[0]) * dx + (q[1] - pr.a[1]) * dy) / L)) : 0; + consider(Math.hypot(pr.a[0] + dx * t - q[0], pr.a[1] + dy * t - q[1]), () => ({ view: id, ref: { edge: pr.edge, at: 'edge' }, geo: { kind: 'line', a: pr.a, b: pr.b }, q })); + } + if (pr.kind === 'arc' && (want === 'any' || want === 'circle')) { + consider(Math.abs(dist(pr.c) - pr.r), () => ({ view: id, ref: { edge: pr.edge, at: 'edge' }, geo: { kind: 'circle', c: pr.c, r: pr.r, full: pr.full, a: pr.a, b: pr.b, m: pr.m }, q })); + } + } + if (best) return best; + if (!only) return null; + } + return null; + } + + /** Snaps a sheet point in a view to a nearby corner or centre (else keeps it), in view coordinates. */ + private snap(p: ViewPlacement, x: number, y: number): P2 { + const hit = this.pick(x, y, 'point', p.r.v.id); + return hit ? hit.q : this.toView(p, x, y); + } + + private newViewId(d: DrawingDoc): string { + let n = d.views.length + 1; + while (d.views.some((v) => v.id === `v${n}`)) n++; + return `v${n}`; + } + + private newAnnoId(d: DrawingDoc): string { + const list = d.annotations ?? []; + let n = list.length + 1; + while (list.some((a) => a.id === `a${n}`)) n++; + return `a${n}`; + } + + /** A section or auxiliary view's line through the parent, oriented so the view is on the side of `to`. */ + private orientLine(l: [number, number, number, number], to: P2): [number, number, number, number] { + const n = lineNormal(l); + const side = (to[0] - l[0]) * n[0] + (to[1] - l[1]) * n[1]; + return side >= 0 ? l : [l[2], l[3], l[0], l[1]]; + } + + /** The cutting line of the section tool so far (parent view coordinates). */ + private sectionLine(t: ToolState, p: ViewPlacement, cursorView: P2 | null): [number, number, number, number] | null { + const pr = this.projectionOf(p.r.v.id); + const b = pr?.bounds; + if (!b) return null; + const m = Math.max(b[2] - b[0], b[3] - b[1]) * 0.08 + 3 / p.s; + if (t.orient === 'horizontal' && t.pts[0]) return [b[0] - m, t.pts[0][1], b[2] + m, t.pts[0][1]]; + if (t.orient === 'vertical' && t.pts[0]) return [t.pts[0][0], b[3] + m, t.pts[0][0], b[1] - m]; + if (t.orient === 'aligned' && t.pts[0]) { + const e = t.pts[1] ?? cursorView; + if (!e || Math.hypot(e[0] - t.pts[0][0], e[1] - t.pts[0][1]) < 1e-6) return null; + return [t.pts[0][0], t.pts[0][1], e[0], e[1]]; + } + return null; + } + + private projectionOf(id: Id): ProjectionResult | undefined { + const d = this.doc; + if (!d) return undefined; + const r = resolveViews(d).get(id); + return r ? this.cache.get(r.key)?.result : undefined; + } + + /** A sheet click with a command active. */ + private toolClick(x: number, y: number) { + const t = this.tool!; + const d = this.doc!; + const needsParent = fromView(t.kind); + if (needsParent && !t.parent) { + const id = this.viewAt(x, y); + if (id && this.placements.has(id) && !this.parentAllowed(t.kind, id)) { toast({ kind: 'info', message: 'A flat pattern view can only have detail views made from it.' }); return; } + if (id && this.placements.has(id) && t.kind === 'autoBalloon') { this.cancelTool(); this.autoBalloon(id); return; } + if (id && this.placements.has(id)) { t.parent = id; this.selected = id; this.drawSelection(); this.syncPanel(); } + this.app.setStatus(this.toolPrompt()); + this.drawOverlay(); + return; + } + const p = t.parent ? this.placements.get(t.parent) : undefined; + if (needsParent && !p) { this.cancelTool(); return; } + const finish = (label: string, fn: (dd: DrawingDoc) => void, keep = false) => { + this.update(fn, label); + if (keep) { t.pts = []; t.picks = []; this.drawOverlay(); this.syncPanel(); this.app.setStatus(this.toolPrompt()); } + else this.cancelTool(); + }; + switch (t.kind) { + case 'projected': { + const side = this.sideOf(p!, x, y); + const id = this.newViewId(d); + const o = besideOrient(p!.r.o, SIDE_VECTORS[side], d.projection === 'first'); + const kind = (standardKindOf(o) ?? p!.r.v.kind) as DrawingViewKind; + const cx = (p!.frame.x0 + p!.frame.x1) / 2, cy = (p!.frame.y0 + p!.frame.y1) / 2; + const [nx, ny] = side === 'left' || side === 'right' ? [x, cy] : [cx, y]; + this.selected = id; + finish('Projected view', (dd) => { dd.views.push({ id, kind, type: 'projected', parent: t.parent, side, x: nx, y: ny, hidden: kind !== 'isometric', dims: false, centerMarks: true }); this.placeOnSheet(dd, id); }); + return; + } + case 'section': { + const q = this.toView(p!, x, y); + const need = t.orient === 'aligned' ? 2 : 1; + if (t.pts.length < need) { + t.pts.push(this.snap(p!, x, y)); + if (t.orient === 'aligned' && t.pts.length === 2 && Math.hypot(t.pts[1][0] - t.pts[0][0], t.pts[1][1] - t.pts[0][1]) < 1e-6) t.pts.pop(); + this.app.setStatus(this.toolPrompt()); + this.drawOverlay(); + return; + } + const raw = this.sectionLine(t, p!, null); + if (!raw) return; + const line = this.orientLine(raw, q); + const id = this.newViewId(d); + const label = nextLetter(d); + const n = lineNormal(line); + const aligned = Math.abs(n[0]) < 1e-9 || Math.abs(n[1]) < 1e-9; + const cx = (p!.frame.x0 + p!.frame.x1) / 2, cy = (p!.frame.y0 + p!.frame.y1) / 2; + const [nx, ny] = !aligned ? [x, y] : Math.abs(n[0]) < 1e-9 ? [cx, y] : [x, cy]; + this.selected = id; + finish('Section view', (dd) => { dd.views.push({ id, kind: p!.r.v.kind, type: 'section', parent: t.parent, line: line.map((v) => +v.toFixed(6)) as [number, number, number, number], label, x: nx, y: ny, hidden: false, dims: false, centerMarks: true }); this.placeOnSheet(dd, id); }); + return; + } + case 'detail': { + if (t.pts.length === 0) { t.pts.push(this.snap(p!, x, y)); this.app.setStatus(this.toolPrompt()); this.drawOverlay(); return; } + if (t.pts.length === 1) { + const q = this.toView(p!, x, y); + const r = Math.hypot(q[0] - t.pts[0][0], q[1] - t.pts[0][1]); + if (r * p!.s < 1) return; + t.pts.push([r, 0]); + this.app.setStatus(this.toolPrompt()); + this.drawOverlay(); + return; + } + const id = this.newViewId(d); + const label = nextLetter(d); + const c = t.pts[0], r = t.pts[1][0]; + const scale = detailScale(p!.s); + this.selected = id; + finish('Detail view', (dd) => { dd.views.push({ id, kind: p!.r.v.kind, type: 'detail', parent: t.parent, circle: [+c[0].toFixed(6), +c[1].toFixed(6), +r.toFixed(6)], scale, label, x, y, hidden: false, dims: false, centerMarks: true }); this.placeOnSheet(dd, id); }); + return; + } + case 'auxiliary': { + if (t.pts.length === 0) { + const hit = this.pick(x, y, 'line', t.parent); + if (hit?.geo.kind !== 'line') return; + t.pts.push(hit.geo.a, hit.geo.b); + this.app.setStatus(this.toolPrompt()); + this.drawOverlay(); + return; + } + const q = this.toView(p!, x, y); + const line = this.orientLine([t.pts[0][0], t.pts[0][1], t.pts[1][0], t.pts[1][1]], q); + const id = this.newViewId(d); + const label = nextLetter(d); + this.selected = id; + finish('Auxiliary view', (dd) => { dd.views.push({ id, kind: p!.r.v.kind, type: 'auxiliary', parent: t.parent, line: line.map((v) => +v.toFixed(6)) as [number, number, number, number], label, x, y, hidden: false, dims: false, centerMarks: true }); this.placeOnSheet(dd, id); }); + return; + } + case 'dimension': { + const first = t.picks[0]; + const hit = t.picks.length < 2 ? this.pick(x, y, 'any', first?.view) : null; + if (hit && (!first || !(hit.ref.edge === first.ref.edge && hit.ref.at === first.ref.at))) { + t.picks.push(hit); + this.app.setStatus(this.toolPrompt()); + this.drawOverlay(); + return; + } + // A single point measures nothing: it waits for a second one. + if (!first || (t.picks.length === 1 && first.geo.kind === 'point')) return; + const pv = this.placements.get(first.view); + if (!pv) return; + const at = this.toView(pv, x, y); + const gs = t.picks.map((k) => k.geo); + const kind = guessKind(gs, at); + if (!measure(kind, gs)) { toast({ kind: 'info', message: 'These cannot be dimensioned together. Pick other edges or points.' }); t.picks = []; this.drawOverlay(); return; } + const id = this.newAnnoId(d); + const refs = t.picks.map((k) => k.ref); + finish('Dimension', (dd) => { (dd.annotations ??= []).push({ id, type: 'dimension', view: first.view, kind, refs, at: [+at[0].toFixed(4), +at[1].toFixed(4)] }); }, true); + return; + } + case 'note': { + const vid = this.viewAt(x, y); + const pv = vid ? this.placements.get(vid) : undefined; + if (t.leader && t.pts.length === 0) { + const hit = this.pick(x, y, 'any'); + const vp = hit ? this.placements.get(hit.view) : pv; + t.parent = vp?.r.v.id; + t.pts.push(vp ? (hit ? hit.q : this.toView(vp, x, y)) : [x, y]); + this.app.setStatus(this.toolPrompt()); + this.drawOverlay(); + return; + } + const owner = t.leader ? (t.parent ? this.placements.get(t.parent) : undefined) : pv; + const at: P2 = owner ? this.toView(owner, x, y) : [x, y]; + const id = this.newAnnoId(d); + this.selectedAnno = id; + const leader = t.leader ? t.pts[0] : undefined; + finish('Note', (dd) => { + const n: DrawingAnnotation = { id, type: 'note', text: 'NOTE', at: [+at[0].toFixed(4), +at[1].toFixed(4)] }; + if (owner) n.view = owner.r.v.id; + if (leader) n.leader = [+leader[0].toFixed(4), +leader[1].toFixed(4)]; + (dd.annotations ??= []).push(n); + }); + requestAnimationFrame(() => (this.app.shell.lpBody.querySelector('textarea[aria-label="Note text"]') as HTMLTextAreaElement | null)?.select()); + return; + } + case 'centerMark': { + const hit = this.pick(x, y, 'circle'); + if (hit?.geo.kind !== 'circle') return; + const id = this.newAnnoId(d); + finish('Center mark', (dd) => { (dd.annotations ??= []).push({ id, type: 'centerMark', view: hit.view, ref: hit.ref }); }, true); + return; + } + case 'centerline': { + const hit = this.pick(x, y, 'line', t.picks[0]?.view); + if (hit?.geo.kind !== 'line') return; + if (!t.picks.length) { t.picks.push(hit); this.app.setStatus(this.toolPrompt()); this.drawOverlay(); return; } + const a = t.picks[0]; + const g1 = a.geo as Extract, g2 = hit.geo; + const u1 = [g1.b[0] - g1.a[0], g1.b[1] - g1.a[1]], u2 = [g2.b[0] - g2.a[0], g2.b[1] - g2.a[1]]; + if (Math.abs(u1[0] * u2[1] - u1[1] * u2[0]) > 1e-6 * Math.hypot(...u1) * Math.hypot(...u2) || hit.ref.edge === a.ref.edge) { + toast({ kind: 'info', message: 'A centerline goes between two parallel edges.' }); + return; + } + const id = this.newAnnoId(d); + finish('Centerline', (dd) => { (dd.annotations ??= []).push({ id, type: 'centerline', view: a.view, refs: [a.ref, hit.ref] }); }, true); + return; + } + case 'holeCallout': { + if (!t.picks.length) { + const hit = this.pick(x, y, 'circle'); + if (hit?.geo.kind !== 'circle') return; + t.picks.push(hit); + this.app.setStatus(this.toolPrompt()); + this.drawOverlay(); + return; + } + const a = t.picks[0]; + const pv = this.placements.get(a.view); + if (!pv) return; + const at = this.toView(pv, x, y); + const id = this.newAnnoId(d); + finish('Hole callout', (dd) => { (dd.annotations ??= []).push({ id, type: 'holeCallout', view: a.view, ref: a.ref, at: [+at[0].toFixed(4), +at[1].toFixed(4)] }); }, true); + return; + } + case 'balloon': { + if (!t.picks.length) { + const hit = this.pick(x, y, 'any'); + if (!hit) return; + const pv = this.placements.get(hit.view); + if (!pv || this.itemOf(pv.r.source, hit.ref.edge) === null) { + toast({ kind: 'info', message: this.app.assembly ? 'Click an edge of a component listed in the bill of materials.' : 'Click an edge of a structural member listed in the cut list.' }); + return; + } + // The leader ends where the edge was clicked (a vertex: that end of it). + const ref: DrawingRef = { edge: hit.ref.edge, at: 'edge' }; + const geo = resolveRef(pv.prims, ref) ?? hit.geo; + let along: number | undefined; + if (geo.kind === 'line') { + const dx = geo.b[0] - geo.a[0], dy = geo.b[1] - geo.a[1], L = dx * dx + dy * dy; + along = L > 0 ? +Math.max(0, Math.min(1, ((hit.q[0] - geo.a[0]) * dx + (hit.q[1] - geo.a[1]) * dy) / L)).toFixed(4) : undefined; + } + t.picks.push({ ...hit, ref, geo, ...(along !== undefined ? { t: along } : {}) }); + this.app.setStatus(this.toolPrompt()); + this.drawOverlay(); + return; + } + const a = t.picks[0]; + const pv = this.placements.get(a.view); + if (!pv) return; + const at = this.toView(pv, x, y); + const id = this.newAnnoId(d); + finish('Balloon', (dd) => { (dd.annotations ??= []).push({ id, type: 'balloon', view: a.view, ref: a.ref, at: [+at[0].toFixed(4), +at[1].toFixed(4)], ...(a.t !== undefined ? { t: a.t } : {}) }); }, true); + return; + } + case 'autoBalloon': return; + } + } + + /** A view just added where it was clicked: kept on the sheet (a click beside the paper would put it out of sight). */ + private placeOnSheet(d: DrawingDoc, id: Id) { + const v = d.views.find((q) => q.id === id); + if (v) [v.x, v.y] = this.onSheet(id, v.x, v.y, d); + } + + /** On which side of a view a sheet point is. */ + private sideOf(p: ViewPlacement, x: number, y: number): 'left' | 'right' | 'above' | 'below' { + const f = p.frame; + const cx = (f.x0 + f.x1) / 2, cy = (f.y0 + f.y1) / 2; + const dx = (x - cx) / Math.max(f.x1 - f.x0, 1), dy = (y - cy) / Math.max(f.y1 - f.y0, 1); + if (Math.abs(dx) >= Math.abs(dy)) return dx >= 0 ? 'right' : 'left'; + return dy >= 0 ? 'below' : 'above'; + } + + /** Previews of the active command and highlights of what it would pick. */ + private drawOverlay() { + const t = this.tool; + if (!t || !this.active) { this.overlay.innerHTML = ''; return; } + const items: Item[] = []; + const accent = '#1e88e5'; + const p = t.parent ? this.placements.get(t.parent) : undefined; + const T = (pl: ViewPlacement, q: P2): P2 => [pl.tx + q[0] * pl.s, pl.ty + q[1] * pl.s]; + const mark = (k: Pick) => { + const pl = this.placements.get(k.view); + if (!pl) return; + const g = k.geo; + if (g.kind === 'point') { const c = T(pl, g.p); items.push({ t: 'circle', cx: c[0], cy: c[1], r: 1, w: 0.4 }); } + else if (g.kind === 'line') { const a = T(pl, g.a), b = T(pl, g.b); items.push({ t: 'line', x1: a[0], y1: a[1], x2: b[0], y2: b[1], w: 0.6 }); } + else { const c = T(pl, g.c); items.push({ t: 'circle', cx: c[0], cy: c[1], r: g.r * pl.s, w: 0.6 }); } + }; + if (p) { const f = p.frame; items.push({ t: 'rect', x: f.x0 - 2, y: f.y0 - 2, w: f.x1 - f.x0 + 4, h: f.y1 - f.y0 + 4, sw: 0.3 }); } + for (const k of t.picks) mark(k); + if (t.hover) mark(t.hover); + const cur = t.cursor; + if (p && cur) { + const qv = this.toView(p, cur[0], cur[1]); + if (t.kind === 'projected') { + const side = this.sideOf(p, cur[0], cur[1]); + const f = p.frame, w = f.x1 - f.x0, hh = f.y1 - f.y0; + const o = besideOrient(p.r.o, SIDE_VECTORS[side], this.doc?.projection === 'first'); + const bb = this.source(p.r.source)?.bbox(); + const size = bb && p.r.type !== 'flat' ? sizeIn(o, bb.min, bb.max).map((v) => v * p.s) : [w, hh]; + const [cx, cy] = side === 'left' || side === 'right' ? [cur[0], (f.y0 + f.y1) / 2] : [(f.x0 + f.x1) / 2, cur[1]]; + items.push({ t: 'rect', x: cx - size[0] / 2, y: cy - size[1] / 2, w: size[0], h: size[1], sw: 0.3 }); + } else if (t.kind === 'section') { + const pts = t.pts.length ? t : { ...t, pts: [this.snap(p, cur[0], cur[1])] }; + const l = this.sectionLine(pts, p, qv); + if (l) { + const a = T(p, [l[0], l[1]]), b = T(p, [l[2], l[3]]); + items.push({ t: 'line', x1: a[0], y1: a[1], x2: b[0], y2: b[1], w: 0.5, dash: [4, 1, 1, 1] }); + const ready = t.orient === 'aligned' ? t.pts.length >= 2 : t.pts.length >= 1; + if (ready) { + const n = lineNormal(this.orientLine(l, qv)); + const first = this.doc?.projection === 'first'; + const w: P2 = first ? n : [-n[0], -n[1]]; + for (const e of [a, b]) { + const tip: P2 = [e[0] + w[0] * 7, e[1] + w[1] * 7]; + items.push({ t: 'line', x1: e[0], y1: e[1], x2: tip[0], y2: tip[1], w: 0.4 }); + } + } + } + } else if (t.kind === 'detail') { + const c = t.pts[0] ?? this.snap(p, cur[0], cur[1]); + const r = t.pts[1] ? t.pts[1][0] : t.pts[0] ? Math.hypot(qv[0] - c[0], qv[1] - c[1]) : 0; + const sc = T(p, c); + if (r > 0) items.push({ t: 'circle', cx: sc[0], cy: sc[1], r: r * p.s, w: 0.4 }); + else items.push({ t: 'circle', cx: sc[0], cy: sc[1], r: 1, w: 0.4 }); + if (t.pts[1]) items.push({ t: 'circle', cx: cur[0], cy: cur[1], r: r * detailScale(p.s), w: 0.3, dash: [2, 1] }); + } else if (t.kind === 'auxiliary' && t.pts.length === 2) { + const a = T(p, t.pts[0]), b = T(p, t.pts[1]); + items.push({ t: 'line', x1: a[0], y1: a[1], x2: b[0], y2: b[1], w: 0.6 }); + items.push({ t: 'circle', cx: cur[0], cy: cur[1], r: 2, w: 0.3 }); + } + } + if (cur && t.kind === 'dimension' && t.picks.length) { + const pl = this.placements.get(t.picks[0].view); + if (pl) { + const at = this.toView(pl, cur[0], cur[1]); + const gs = t.picks.map((k) => k.geo); + const kind = guessKind(gs, at); + const dim: DrawingDimension = { id: 'preview', type: 'dimension', view: pl.r.v.id, kind, refs: t.picks.map((k) => k.ref), at }; + drawDimension(items, dim, measure(kind, gs), { T: (q) => T(pl, q), s: pl.s }, this.fmt()); + } + } + if (cur && t.kind === 'holeCallout' && t.picks.length) items.push({ t: 'circle', cx: cur[0], cy: cur[1], r: 1, w: 0.3 }); + if (cur && t.kind === 'balloon' && t.picks.length) { + const k = t.picks[0], pl = this.placements.get(k.view); + if (pl) { + const n = this.itemOf(pl.r.source, k.ref.edge); + drawBalloon(items, n === null ? '?' : String(n), cur, T(pl, balloonTip(k.geo, this.toView(pl, cur[0], cur[1]), k.t))); + } + } + if (cur && t.kind === 'note' && t.leader && t.pts.length) { + const pl = t.parent ? this.placements.get(t.parent) : undefined; + const tip = pl ? T(pl, t.pts[0]) : t.pts[0]; + items.push({ t: 'line', x1: tip[0], y1: tip[1], x2: cur[0], y2: cur[1], w: 0.3 }); + } + const svg = toSvg(items, this.sheetW, this.sheetH, { background: 'none', ink: accent }); + this.overlay.innerHTML = svg; + const el = this.overlay.firstElementChild as SVGSVGElement | null; + if (el) { el.setAttribute('width', `${this.sheetW}`); el.setAttribute('height', `${this.sheetH}`); } + } + + /** Pointer moved with a command active: what it would pick, and its preview. */ + private toolMove(x: number, y: number) { + const t = this.tool!; + t.cursor = [x, y]; + t.hover = null; + switch (t.kind) { + case 'dimension': if (t.picks.length < 2) t.hover = this.pick(x, y, 'any', t.picks[0]?.view); break; + case 'centerMark': t.hover = this.pick(x, y, 'circle'); break; + case 'holeCallout': if (!t.picks.length) t.hover = this.pick(x, y, 'circle'); break; + case 'balloon': if (!t.picks.length) t.hover = this.pick(x, y, 'any'); break; + case 'centerline': t.hover = this.pick(x, y, 'line', t.picks[0]?.view); break; + case 'auxiliary': if (t.parent && !t.pts.length) t.hover = this.pick(x, y, 'line', t.parent); break; + case 'section': case 'detail': if (t.parent) t.hover = this.pick(x, y, 'point', t.parent); break; + case 'note': if (t.leader && !t.pts.length) t.hover = this.pick(x, y, 'any'); break; + } + this.drawOverlay(); + } + // ---------- interaction ---------- private toSheet(clientX: number, clientY: number): [number, number] { @@ -300,8 +1096,28 @@ export class DrawingWorkspace { return null; } + private annoAt(x: number, y: number): string | null { + for (const a of [...this.annoBoxes].reverse()) if (x >= a.box[0] - 1 && x <= a.box[2] + 1 && y >= a.box[1] - 1 && y <= a.box[3] + 1) return a.id; + return null; + } + + /** Views that move with a view: those aligned to it, and theirs. */ + private followers(d: DrawingDoc, id: Id): Id[] { + const rs = resolveViews(d); + const out: Id[] = []; + const walk = (p: Id) => { + for (const v of d.views) { + const r = rs.get(v.id); + if (v.parent === p && r?.align && !out.includes(v.id)) { out.push(v.id); walk(v.id); } + } + }; + walk(id); + return out; + } + private bind() { - let drag: { kind: 'pan' | 'view'; sx: number; sy: number; ox: number; oy: number; id?: string; moved: boolean } | null = null; + type Drag = { kind: 'pan' | 'view' | 'anno'; sx: number; sy: number; ox: number; oy: number; id?: string; moved: boolean; follow?: { id: Id; x: number; y: number }[]; align?: 'x' | 'y'; s?: number }; + let drag: Drag | null = null; // Two fingers pinch to zoom and pan (touch screens have no wheel). const pointers = new Map(); let pinch: { d: number; sx: number; sy: number; zoom: number } | null = null; @@ -314,7 +1130,7 @@ export class DrawingWorkspace { if (e.pointerType === 'touch') pointers.set(e.pointerId, { x: e.clientX, y: e.clientY }); if (pointers.size >= 2) { // A second finger ends any drag (closing its undo step) and starts a pinch. - if (drag?.kind === 'view' && drag.moved) this.app.store.endBatch(); + if ((drag?.kind === 'view' || drag?.kind === 'anno') && drag.moved) this.app.store.endBatch(); drag = null; if (pointers.size === 2) { const p = pinchState(); @@ -325,16 +1141,33 @@ export class DrawingWorkspace { } this.el.focus({ preventScroll: true }); const [x, y] = this.toSheet(e.clientX, e.clientY); - const id = e.button === 0 ? this.viewAt(x, y) : null; + if (this.tool && e.button === 0) { + this.toolClick(x, y); + return; + } + const anno = e.button === 0 ? this.annoAt(x, y) : null; + const id = e.button === 0 && !anno ? this.viewAt(x, y) : null; this.el.setPointerCapture(e.pointerId); - if (id) { - const v = this.doc!.views.find((q) => q.id === id)!; + if (anno) { + const a = this.doc!.annotations!.find((q) => q.id === anno)!; + this.selectedAnno = anno; + this.selected = null; + this.drawSelection(); + this.syncPanel(); + const at = 'at' in a ? a.at : [0, 0]; + const p = a.view ? this.placements.get(a.view) : undefined; + drag = { kind: 'anno', sx: e.clientX, sy: e.clientY, ox: at[0], oy: at[1], id: anno, moved: false, s: p?.s ?? 1 }; + } else if (id) { + const d = this.doc!; + const v = d.views.find((q) => q.id === id)!; this.selected = id; + this.selectedAnno = null; this.drawSelection(); this.syncPanel(); - drag = { kind: 'view', sx: e.clientX, sy: e.clientY, ox: v.x, oy: v.y, id, moved: false }; + const follow = this.followers(d, id).map((f) => { const q = d.views.find((w) => w.id === f)!; return { id: f, x: q.x, y: q.y }; }); + drag = { kind: 'view', sx: e.clientX, sy: e.clientY, ox: v.x, oy: v.y, id, moved: false, follow, align: this.placements.get(id)?.r.align }; } else { - if (e.button === 0 && this.selected) { this.selected = null; this.drawSelection(); this.syncPanel(); } + if (e.button === 0 && (this.selected || this.selectedAnno)) { this.selected = null; this.selectedAnno = null; this.drawSelection(); this.syncPanel(); } drag = { kind: 'pan', sx: e.clientX, sy: e.clientY, ox: this.pan.x, oy: this.pan.y, moved: false }; } }); @@ -349,25 +1182,40 @@ export class DrawingWorkspace { this.applyTransform(); return; } - if (!drag) return; + if (!drag) { + if (this.tool) { const [x, y] = this.toSheet(e.clientX, e.clientY); this.toolMove(x, y); } + return; + } const dx = e.clientX - drag.sx, dy = e.clientY - drag.sy; if (!drag.moved && Math.hypot(dx, dy) < 3) return; - if (!drag.moved && drag.kind === 'view') this.app.store.beginBatch('Move view', () => { drag = null; }); + if (!drag.moved && drag.kind !== 'pan') this.app.store.beginBatch(drag.kind === 'view' ? 'Move view' : 'Move annotation', () => { drag = null; }); drag.moved = true; if (drag.kind === 'pan') { this.pan = { x: drag.ox + dx, y: drag.oy + dy }; this.applyTransform(); + } else if (drag.kind === 'anno') { + const id = drag.id!, k = (drag.s ?? 1) * this.zoom; + const nx = drag.ox + dx / k, ny = drag.oy + dy / k; + this.update((d) => { const a = d.annotations?.find((q) => q.id === id); if (a && 'at' in a) a.at = [+nx.toFixed(4), +ny.toFixed(4)]; }, 'Move annotation'); } else { const id = drag.id!; - const [nx, ny] = this.onSheet(id, drag.ox + dx / this.zoom, drag.oy + dy / this.zoom); + // A view aligned with its parent moves only along the axis they do not share. + const mx = drag.align === 'x' ? 0 : dx, my = drag.align === 'y' ? 0 : dy; + const follow = drag.follow ?? []; + const [ddx, ddy] = this.groupMove(id, drag.ox, drag.oy, drag.ox + mx / this.zoom, drag.oy + my / this.zoom, follow); + const nx = drag.ox + ddx, ny = drag.oy + ddy; // The change re-renders the sheet (App refreshes the drawing on every document change). - this.update((d) => { const v = d.views.find((q) => q.id === id); if (v) { v.x = nx; v.y = ny; } }, 'Move view'); + this.update((d) => { + const v = d.views.find((q) => q.id === id); + if (v) { v.x = nx; v.y = ny; } + for (const f of follow) { const q = d.views.find((w) => w.id === f.id); if (q) { q.x = f.x + ddx; q.y = f.y + ddy; } } + }, 'Move view'); } }); const end = (e: PointerEvent) => { pointers.delete(e.pointerId); if (pinch) { if (pointers.size < 2) pinch = null; return; } - if (drag?.kind === 'view' && drag.moved) this.app.store.endBatch(); + if ((drag?.kind === 'view' || drag?.kind === 'anno') && drag.moved) this.app.store.endBatch(); drag = null; }; this.el.addEventListener('pointerup', end); @@ -386,25 +1234,52 @@ export class DrawingWorkspace { this.pan = { x: mx - ((mx - this.pan.x) * nz) / this.zoom, y: my - ((my - this.pan.y) * nz) / this.zoom }; this.zoom = nz; this.applyTransform(); + if (this.tool) this.drawOverlay(); }, { passive: false }); // A held arrow key is one undo step: its auto-repeats join the step of the first press // (one step each filled the bounded history within seconds and dropped older steps). let nudge: { id: string; mark: number; last: number } | null = null; this.el.addEventListener('keydown', (e) => { const step = e.shiftKey ? 10 : 1; + // The selected annotation that has a place of its own (a dimension's value, a note...). + const anno = !this.selected && this.selectedAnno ? this.doc?.annotations?.find((q) => q.id === this.selectedAnno && 'at' in q) : undefined; + const moveAnno = (dx: number, dy: number) => { + if (!anno || !('at' in anno)) return; + e.preventDefault(); + const id = anno.id; + const store = this.app.store; + const join = e.repeat && nudge?.id === id && nudge.last === store.undoMark ? nudge : null; + const mark = join ? join.mark : store.undoMark; + // A step is a millimetre on the sheet (an annotation of a view has its place in the view's coordinates). + const s = (anno.view && this.placements.get(anno.view)?.s) || 1; + const at: [number, number] = [+(anno.at[0] + dx / s).toFixed(4), +(anno.at[1] + dy / s).toFixed(4)]; + this.update((d) => { const q = d.annotations?.find((x) => x.id === id); if (q && 'at' in q) q.at = at; }, 'Move annotation'); + if (join) store.squash(mark, 'Move annotation'); + nudge = { id, mark, last: store.undoMark }; + }; const move = (dx: number, dy: number) => { const id = this.selected; - if (!id) return; + if (!id) { moveAnno(dx, dy); return; } e.preventDefault(); const store = this.app.store; const join = e.repeat && nudge?.id === id && nudge.last === store.undoMark ? nudge : null; const mark = join ? join.mark : store.undoMark; - const v = this.doc?.views.find((q) => q.id === id); - if (!v) return; + const d0 = this.doc; + const v = d0?.views.find((q) => q.id === id); + if (!d0 || !v) return; + const align = this.placements.get(id)?.r.align; + if (align === 'x') dx = 0; + if (align === 'y') dy = 0; // Held against the edge of the sheet: nothing to move (and no empty undo step). - const [nx, ny] = this.onSheet(id, v.x + dx, v.y + dy); - if (nx === v.x && ny === v.y) return; - this.update((d) => { const q = d.views.find((x) => x.id === id); if (q) { q.x = nx; q.y = ny; } }, 'Move view'); + const follow = this.followers(d0, id); + const [ddx, ddy] = this.groupMove(id, v.x, v.y, v.x + dx, v.y + dy, follow.map((f) => { const q = d0.views.find((w) => w.id === f)!; return { id: f, x: q.x, y: q.y }; })); + if (!ddx && !ddy) return; + const nx = v.x + ddx, ny = v.y + ddy; + this.update((d) => { + const q = d.views.find((x) => x.id === id); + if (q) { q.x = nx; q.y = ny; } + for (const f of follow) { const w = d.views.find((x) => x.id === f); if (w) { w.x += ddx; w.y += ddy; } } + }, 'Move view'); if (join) store.squash(mark, 'Move view'); nudge = { id, mark, last: store.undoMark }; }; @@ -413,8 +1288,8 @@ export class DrawingWorkspace { this.pan = { x: this.pan.x + dx, y: this.pan.y + dy }; this.applyTransform(); }; - // Arrow keys move the selected view, else the sheet; + and - zoom it (as the wheel does). - const d = this.selected ? null : 40 * (e.shiftKey ? 4 : 1); + // Arrow keys move the selected view or annotation, else the sheet; + and - zoom it (as the wheel does). + const d = this.selected || anno ? null : 40 * (e.shiftKey ? 4 : 1); const plain = !e.ctrlKey && !e.metaKey && !e.altKey; if (e.key === 'ArrowLeft') d ? pan(d, 0) : move(-step, 0); else if (e.key === 'ArrowRight') d ? pan(-d, 0) : move(step, 0); @@ -437,14 +1312,30 @@ export class DrawingWorkspace { if (!d || !v) return [x, y]; const { w, h } = sheetDims(d); // The view's reach from its centre, at k times the scale drawn. - const f = this.frameOf(v, d.scale / k); + const f = this.frameOf(v, d.scale / k, d); const [l, r, t, b] = f ? [v.x - f.x0, f.x1 - v.x, v.y - f.y0, f.y1 - v.y].map((q) => q * k) : [0, 0, 0, 0]; // Its dimensions, left of and below it, stay on the sheet too. - const [dl, db] = v.dims && v.kind !== 'isometric' ? [DIM_LEFT, DIM_BELOW] : [0, 0]; + const [dl, db] = v.dims && v.kind !== 'isometric' && v.type !== 'detail' ? [DIM_LEFT, DIM_BELOW] : [0, 0]; const fit = (c: number, lo: number, hi: number) => Math.min(Math.max(c, Math.min(lo, hi)), Math.max(lo, hi)); return [fit(x, MARGIN + l + dl, w - MARGIN - r), fit(y, MARGIN + t, h - MARGIN - b - db)]; } + /** + * How far a view at (ox, oy) moved toward (x, y) goes, with the views that follow it (at + * their positions then): as far as keeps it and every one of them on the sheet. + */ + private groupMove(id: string, ox: number, oy: number, x: number, y: number, follow: { id: Id; x: number; y: number }[]): [number, number] { + const [nx, ny] = this.onSheet(id, x, y); + let dx = nx - ox, dy = ny - oy; + // Each limit holds where the move started, so narrowing the move for one keeps it within the others'. + for (const f of follow) { + const [fx, fy] = this.onSheet(f.id, f.x + dx, f.y + dy); + dx = fx - f.x; + dy = fy - f.y; + } + return [dx, dy]; + } + /** * After the scale changed from `old` to d.scale: views stay on the sheet. Growing, the * layout grows from its top left corner, so the views move apart as they grow instead @@ -453,7 +1344,7 @@ export class DrawingWorkspace { rescaleViews(d: DrawingDoc, old: number) { const k = d.scale / old; if (!(k > 0) || k === 1) return; - const fs = d.views.map((v) => this.frameOf(v, old)).filter((f) => !!f); + const fs = d.views.map((v) => this.frameOf(v, old, d)).filter((f) => !!f); const ax = Math.min(...fs.map((f) => f.x0)), ay = Math.min(...fs.map((f) => f.y0)); const moved = d.views.map((v) => { const [x, y] = k > 1 && fs.length ? [ax + (v.x - ax) * k, ay + (v.y - ay) * k] : [v.x, v.y]; @@ -463,62 +1354,216 @@ export class DrawingWorkspace { } /** - * A view's frame as last drawn or, while it is still being projected (a drawing just opened), - * the projection of the part's bounding box drawn at `scale`. + * A view's frame as last drawn, centred on where the view is now (an aligned view's frame + * is not centred on its position) or, while it is still being projected (a drawing just + * opened), the projection of the part's bounding box drawn at `scale`. */ - private frameOf(v: DrawingView, scale: number): ViewFrame | undefined { + private frameOf(v: DrawingView, scale: number, d = this.doc): ViewFrame | undefined { const f = this.frames.find((q) => q.id === v.id); - const b = this.app.bbox; - if (f || !b) return f; - const [vw, vh] = projectedSize(v.kind, b.min, b.max).map((q) => (q * scale) / 2); + const b = this.bbox(v.source); + if (f) { + const p = this.placements.get(v.id); + if (!p?.r.align) return f; + const cx = (f.x0 + f.x1) / 2, cy = (f.y0 + f.y1) / 2; + return { id: f.id, x0: f.x0 - cx + v.x, x1: f.x1 - cx + v.x, y0: f.y0 - cy + v.y, y1: f.y1 - cy + v.y }; + } + if (!b) return f; + const r = d ? resolveViews(d).get(v.id) : undefined; + const vs = r && r.type !== 'model' ? r.scale * (scale / (d?.scale || scale)) : scale; + // A detail view shows its circle. + if (r?.clip) { const R = r.clip.r * vs; return { id: v.id, x0: v.x - R, y0: v.y - R, x1: v.x + R, y1: v.y + R }; } + const [vw, vh] = (r && r.type !== 'model' ? sizeIn(r.o, b.min, b.max) : projectedSize(v.kind, b.min, b.max)).map((q) => (q * vs) / 2); return { id: v.id, x0: v.x - vw, y0: v.y - vh, x1: v.x + vw, y1: v.y + vh }; } + /** A new projection angle: the views keep what they show and move to their side for it (see switchProjection). */ + setProjection(d: DrawingDoc, to: 'first' | 'third') { + switchProjection(d, to, (v) => this.frameOf(v, d.scale, d)); + } + /** After the sheet got smaller or turned: views that would hang off it move back on. */ - keepOnSheet(d: DrawingDoc) { + keepOnSheet(d: DrawingDoc, was?: { w: number; h: number }) { for (const v of d.views) [v.x, v.y] = this.onSheet(v.id, v.x, v.y, d); + // A table that stood on the title block stays on it; any other stays on the sheet. + const { w, h } = sheetDims(d); + for (const a of d.annotations ?? []) { + if (a.type !== 'bom' && a.type !== 'cutList') continue; + if (a.anchor === 'bottomRight' && was && Math.abs(a.at[0] - (was.w - MARGIN)) < 1e-6 && Math.abs(a.at[1] - (was.h - MARGIN - TITLE_H)) < 1e-6) { + a.at = [w - MARGIN, h - MARGIN - TITLE_H]; + continue; + } + const t = this.tableOf(a); + const size = t ? tableSize(t) : { w: 0, h: 0 }; + const [ox, oy] = a.anchor === 'bottomRight' ? [size.w, size.h] : [0, 0]; + const fit = (c: number, lo: number, hi: number) => Math.min(Math.max(c, Math.min(lo, hi)), Math.max(lo, hi)); + a.at = [fit(a.at[0], MARGIN + ox, w - MARGIN - size.w + ox), fit(a.at[1], MARGIN + oy, h - MARGIN - size.h + oy)]; + } } /** Selects a view from the keyboard (the Views list) and focuses the sheet so arrow keys move it. */ select(id: string) { this.selected = id; + this.selectedAnno = null; this.drawSelection(); this.syncPanel(); this.el.focus({ preventScroll: true }); } - /** Esc: the arrow keys go back to moving the sheet. */ + /** Selects an annotation (from the Annotations list too) and focuses the sheet so arrow keys move it. */ + selectAnno(id: string) { + this.selectedAnno = id; + this.selected = null; + this.drawSelection(); + this.syncPanel(); + this.el.focus({ preventScroll: true }); + } + + /** Esc: ends the command, else the arrow keys go back to moving the sheet. */ deselect(): boolean { - if (!this.selected) return false; + if (this.cancelTool()) return true; + if (!this.selected && !this.selectedAnno) return false; this.selected = null; + this.selectedAnno = null; this.drawSelection(); this.syncPanel(); return true; } deleteSelected(): boolean { + const anno = this.selectedAnno; + if (anno) { this.deleteAnno(anno); return true; } const id = this.selected; if (!id) return false; - this.selected = null; - this.update((d) => { d.views = d.views.filter((v) => v.id !== id); }, 'Delete view'); + this.deleteView(id); return true; } + deleteAnno(anno: Id) { + if (this.selectedAnno === anno) this.selectedAnno = null; + this.update((d) => { d.annotations = (d.annotations ?? []).filter((a) => a.id !== anno); }, 'Delete annotation'); + } + + /** Deletes a view with its annotations; the views made from it go too, after a warning. */ + deleteView(id: Id) { + const d = this.doc; + const deps = d ? dependents(d, id) : []; + const remove = () => { + const gone = [id, ...deps]; + if (this.selected && gone.includes(this.selected)) this.selected = null; + this.update((x) => { + x.views = x.views.filter((v) => !gone.includes(v.id)); + if (x.annotations) x.annotations = x.annotations.filter((a) => !a.view || !gone.includes(a.view)); + }, 'Delete view'); + }; + if (!deps.length || !d) { if (this.selected === id) this.selected = null; remove(); return; } + const names = deps.map((q) => viewName(d, d.views.find((v) => v.id === q)!)).join(', '); + const v = d.views.find((q) => q.id === id)!; + void confirmDialog('Delete view', `Deleting the ${viewName(d, v)} view also deletes the views made from it: ${names}.`, 'Delete', true).then((ok) => { if (ok) remove(); }); + } + addView(kind: DrawingViewKind) { const d = this.doc; - const b = this.app.bbox; + const b = this.bbox(); if (!d || !b) return; const [w, hh] = projectedSize(kind, b.min, b.max); const dims = kind !== 'isometric'; // In free room on the sheet, not on top of the other views or their dimensions // (a view still being projected takes the room of its bounding box's projection). - const others = d.views.map((v) => ({ frame: this.frameOf(v, d.scale)!, dims: v.dims && v.kind !== 'isometric' })); + const others = d.views.map((v) => ({ frame: this.frameOf(v, d.scale)!, dims: v.dims && v.kind !== 'isometric' && v.type !== 'detail' })); const [x, y] = placeView(sheetDims(d), w * d.scale, hh * d.scale, dims, others); - let n = d.views.length + 1; - while (d.views.some((v) => v.id === `v${n}`)) n++; - const id = `v${n}`; + const id = this.newViewId(d); this.selected = id; - this.update((dd) => { dd.views.push({ id, kind, x, y, hidden: dims, dims }); }, 'Add view'); + const full = d.titleBlock === 'full'; + const source = this.app.assembly ? { source: ASSEMBLY_SOURCE } : {}; + this.update((dd) => { dd.views.push({ id, kind, x, y, hidden: dims, dims, ...(full ? { centerMarks: true } : {}), ...source }); }, 'Add view'); + } + + /** + * Adds the flat pattern of the sheet metal part as a view, with its bend lines and notes + * and its overall size, where there is room (at a smaller scale when it does not fit). + */ + async addFlatView() { + const d0 = this.doc; + if (!d0) return; + let res; + try { + res = await this.app.kernel.flatPattern(0); + } catch (e) { + toast({ kind: 'error', title: 'Flat pattern view', message: (e as Error).message }); + return; + } + const d = this.doc; + if (!d || d !== d0 || !this.active) return; + if (!res.pattern) { toast({ kind: 'error', title: 'Flat pattern view', message: res.error ?? 'The part cannot be flattened.' }); return; } + const [fw, fh] = flatSize(res.pattern); + const sheet = sheetDims(d); + const fit = Math.min((sheet.w - 2 * MARGIN - 2 * DIM_LEFT) / Math.max(fw, 1e-6), (sheet.h - 2 * MARGIN - TITLE_H - 2 * DIM_BELOW) / Math.max(fh, 1e-6)); + let own = d.scale <= fit ? undefined : STANDARD_SCALES.find((q) => q <= fit) ?? STANDARD_SCALES[STANDARD_SCALES.length - 1]; + const others = d.views.map((v) => ({ frame: this.frameOf(v, d.scale)!, dims: v.dims && v.kind !== 'isometric' && v.type !== 'detail' })).filter((o) => !!o.frame); + // In free room on the sheet, down to a quarter of the scale it would have; else at that scale in the middle. + const first = own ?? d.scale; + let spot = freeSpot(sheet, fw * first, fh * first, true, others); + for (const q of STANDARD_SCALES) { + if (spot || q < first / 4 - 1e-9) break; + if (q >= first - 1e-9) continue; + spot = freeSpot(sheet, fw * q, fh * q, true, others); + if (spot) own = q; + } + const [x, y] = spot ?? placeView(sheet, fw * first, fh * first, true, others); + if (!spot) own = first === d.scale ? undefined : first; + const id = this.newViewId(d); + this.selected = id; + this.update((dd) => { dd.views.push({ id, kind: 'front', type: 'flat', x, y, hidden: false, dims: true, ...(own ? { scale: own } : {}) }); }, 'Flat pattern view'); + } + + /** Puts the bill of materials (an assembly) or the cut list (a weldment) on the title block, or selects the one there. */ + addTable(type: 'bom' | 'cutList') { + const d = this.doc; + if (!d) return; + const there = d.annotations?.find((a) => a.type === type); + if (there) { this.selectAnno(there.id); toast({ message: `The ${type === 'bom' ? 'bill of materials' : 'cut list'} is already on the sheet (selected).` }); return; } + const { w, h: sh } = sheetDims(d); + const id = this.newAnnoId(d); + this.selectedAnno = id; + this.update((dd) => { (dd.annotations ??= []).push({ id, type, at: [w - MARGIN, sh - MARGIN - TITLE_H], anchor: 'bottomRight' }); }, type === 'bom' ? 'Bill of materials' : 'Cut list'); + } + + /** Balloons on every component of the bill of materials a view shows that has none there yet. */ + autoBalloon(viewId: Id) { + const d = this.doc; + const p = this.placements.get(viewId); + const pr = this.projectionOf(viewId); + if (!d) return; + if (!p || !pr?.bounds) { + // Still being projected (a drawing just opened, or the assembly still building), or empty. + const busy = this.pending || !pr; + toast({ kind: 'info', message: busy ? 'Wait for the view to finish updating, then use Auto Balloon again.' : 'This view shows no components to balloon.' }); + return; + } + const rows = this.source(p.r.source)?.bom?.(); + if (!rows) { toast({ kind: 'info', message: 'Auto Balloon numbers the components of an assembly drawing.' }); return; } + const skip = new Set(); + for (const a of d.annotations ?? []) { + if (a.type !== 'balloon' || a.view !== viewId) continue; + const n = a.item ?? this.itemOf(p.r.source, a.ref.edge); + if (n !== null) skip.add(n); + } + let prims = p.prims, bounds = pr.bounds; + if (p.r.clip) { + const { c, r } = p.r.clip; + const inside = (q: P2) => Math.hypot(q[0] - c[0], q[1] - c[1]) <= r; + prims = prims.filter((q) => inside(q.a) || inside(q.b)); + bounds = [c[0] - r, c[1] - r, c[0] + r, c[1] + r]; + } + // Past the view's dimensions (left and below) and its label (below). + const v = p.r.v; + const dims = v.dims && v.kind !== 'isometric' && v.type !== 'detail'; + const plan = autoBalloons(prims, rows, bounds, p.s, skip, dims ? [DIM_LEFT + 4, 6, 6, DIM_BELOW + 10] : [6, 6, 6, 12]); + if (!plan.length) { toast({ message: skip.size ? 'Every component this view shows has a balloon already.' : 'This view shows no components to balloon.' }); return; } + this.update((dd) => { + for (const b of plan) (dd.annotations ??= []).push({ id: this.newAnnoId(dd), type: 'balloon', view: viewId, ref: b.ref, at: b.at }); + }, 'Auto balloon'); + this.app.setStatus(`Added ${plan.length} balloon${plan.length === 1 ? '' : 's'}. Drag them to arrange them.`); } // ---------- export ---------- @@ -560,9 +1605,33 @@ export class DrawingWorkspace { const s = this.sheet(); download(toSvg(s.items, s.w, s.h, { title: this.exportTitle() }), `${safeName(this.app.store.doc.name)}.svg`, 'image/svg+xml'); } + + async exportDxf() { + if (!(await this.projected())) return; + const s = this.sheet(); + download(toDxf(s.items, s.w, s.h), `${safeName(this.app.store.doc.name)}.dxf`, 'application/dxf'); + } +} + +/** Size (paper width, height) of a box seen from a direction. */ +function sizeIn(o: { dir: [number, number, number]; x: [number, number, number]; up: [number, number, number] }, min: [number, number, number], max: [number, number, number]): [number, number] { + let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity; + for (let i = 0; i < 8; i++) { + const p = [i & 1 ? max[0] : min[0], i & 2 ? max[1] : min[1], i & 4 ? max[2] : min[2]]; + const u = p[0] * o.x[0] + p[1] * o.x[1] + p[2] * o.x[2], v = p[0] * o.up[0] + p[1] * o.up[1] + p[2] * o.up[2]; + x0 = Math.min(x0, u); x1 = Math.max(x1, u); y0 = Math.min(y0, v); y1 = Math.max(y1, v); + } + return [x1 - x0, y1 - y0]; +} + +/** A detail view's scale: the standard scale at least twice its parent's. */ +export function detailScale(parent: number): number { + const want = parent * 2; + const up = [...STANDARD_SCALES].reverse().find((s) => s >= want - 1e-9); + return up ?? want; } -/** PropertyManager for the drawing: sheet, scale, views and title block. */ +/** PropertyManager for the drawing: sheet, scale, views, annotations and title block. */ export class DrawingPanel extends PropertyPanel { title = 'Drawing'; icon = 'file'; @@ -582,62 +1651,177 @@ export class DrawingPanel extends PropertyPanel { const ws = this.ws; const d = ws.doc; if (!d) return []; - const sheet = selectField('Sheet size', d.sheet, (Object.keys(SHEET_LABELS) as SheetSize[]).map((k) => ({ value: k, label: SHEET_LABELS[k] })), (v) => ws.updateFromPanel((x) => { x.sheet = v; ws.keepOnSheet(x); }, 'Sheet size')); + const sheet = selectField('Sheet size', d.sheet, SHEET_ORDER.filter((k) => k in SHEETS).map((k) => ({ value: k, label: SHEET_LABELS[k] })), (v) => ws.updateFromPanel((x) => { const was = sheetDims(x); x.sheet = v; ws.keepOnSheet(x, was); }, 'Sheet size')); const scales = STANDARD_SCALES.map((s) => ({ value: String(s), label: scaleLabel(s) })); if (!scales.some((s) => Number(s.value) === d.scale)) scales.push({ value: String(d.scale), label: scaleLabel(d.scale) }); const scale = selectField('Scale', String(d.scale), scales, (v) => ws.updateFromPanel((x) => { const old = x.scale; x.scale = Number(v); ws.rescaleViews(x, old); }, 'Sheet scale')); const views = h('div', { class: 'relations-list' }); - for (const v of d.views) views.append(this.viewRow(v)); + for (const v of d.views) views.append(this.viewRow(d, v)); const addSel = h('select', { class: 'input', 'aria-label': 'View to add' }) as HTMLSelectElement; for (const k of Object.keys(VIEW_LABELS) as DrawingViewKind[]) addSel.append(h('option', { value: k }, VIEW_LABELS[k])); + if (isSheetMetal(this.app)) addSel.append(h('option', { value: 'flat' }, 'Flat pattern')); const add = h('button', { class: 'btn small', type: 'button' }, icon('plus', 14), 'Add view'); - add.addEventListener('click', () => ws.addView(addSel.value as DrawingViewKind)); + add.addEventListener('click', () => (addSel.value === 'flat' ? void ws.addFlatView() : ws.addView(addSel.value as DrawingViewKind))); const field = (label: string, value: string, set: (v: string) => void) => { const input = h('input', { class: 'input', value, 'aria-label': label }) as HTMLInputElement; input.addEventListener('change', () => set(input.value)); return h('div', {}, h('div', { class: 'field-label' }, label), input); }; - return [ + const toolButton = (kind: DrawingToolKind, ic: string) => + h('button', { class: 'btn small', type: 'button', 'aria-pressed': String(ws.tool?.kind === kind), onclick: () => ws.startTool(kind) }, icon(ic, 14), TOOL_LABELS[kind]); + const out: HTMLElement[] = []; + const tool = this.toolSection(); + if (tool) out.push(tool); + out.push( section('Sheet', [ sheet, - checkbox('Landscape', d.landscape, (v) => ws.updateFromPanel((x) => { x.landscape = v; ws.keepOnSheet(x); }, 'Sheet orientation')), + checkbox('Landscape', d.landscape, (v) => ws.updateFromPanel((x) => { const was = sheetDims(x); x.landscape = v; ws.keepOnSheet(x, was); }, 'Sheet orientation')), scale, - h('button', { class: 'btn small', type: 'button', onclick: () => ws.relayout() }, icon('reset', 14), 'Arrange standard views'), + selectField('Projection angle', d.projection ?? 'third', [{ value: 'third', label: 'Third angle (ASME)' }, { value: 'first', label: 'First angle (ISO)' }], (v) => ws.updateFromPanel((x) => ws.setProjection(x, v), 'Projection angle')), + h('button', { class: 'btn small', type: 'button', onclick: () => void ws.arrange() }, icon('reset', 14), 'Arrange standard views'), ]), - section('Views', [views, h('div', { class: 'row' }, h('div', { class: 'grow' }, addSel), add)]), + section('Views', [ + views, h('div', { class: 'row' }, h('div', { class: 'grow' }, addSel), add), + h('div', { class: 'row wrap drw-tools' }, toolButton('projected', 'drawingProjected'), toolButton('section', 'drawingSection'), toolButton('detail', 'drawingDetail'), toolButton('auxiliary', 'drawingAuxiliary')), + ]), + ); + const sel = ws.selected ? d.views.find((v) => v.id === ws.selected) : undefined; + if (sel) out.push(this.viewSection(d, sel)); + out.push(this.annotationsSection(d)); + const anno = ws.selectedAnno ? d.annotations?.find((a) => a.id === ws.selectedAnno) : undefined; + if (anno) out.push(this.annotationSection(anno)); + out.push( section('Title Block', [ field('Title', d.title || this.app.store.doc.name, (v) => ws.updateFromPanel((x) => { x.title = v; }, 'Title')), field('Drawn by', d.drawnBy, (v) => ws.updateFromPanel((x) => { x.drawnBy = v; }, 'Drawn by')), field('Notes', d.notes, (v) => ws.updateFromPanel((x) => { x.notes = v; }, 'Notes')), + field('Revision', d.revision ?? '', (v) => ws.updateFromPanel((x) => { x.revision = v; }, 'Revision')), + checkbox('Full title block (projection symbol, revision, sheet number)', d.titleBlock === 'full', (v) => ws.updateFromPanel((x) => { x.titleBlock = v ? 'full' : 'basic'; }, 'Title block')), ]), section('Export', [ h('div', { class: 'row' }, h('button', { class: 'btn small', type: 'button', onclick: () => void ws.exportPdf() }, icon('download', 14), 'PDF'), - h('button', { class: 'btn small', type: 'button', onclick: () => void ws.exportSvg() }, icon('download', 14), 'SVG')), + h('button', { class: 'btn small', type: 'button', onclick: () => void ws.exportSvg() }, icon('download', 14), 'SVG'), + h('button', { class: 'btn small', type: 'button', onclick: () => void ws.exportDxf() }, icon('download', 14), 'DXF')), ]), - ]; + ); + return out; + } + + /** The active sheet command: what it asks for, its options, and Cancel. */ + private toolSection(): HTMLElement | null { + const ws = this.ws; + const t = ws.tool; + if (!t) return null; + const parts: HTMLElement[] = [h('div', { class: 'pm-msg info', role: 'status' }, ws.toolPrompt())]; + if (t.kind === 'section') parts.push(segmented('Cutting line', t.orient, [{ value: 'horizontal', label: 'Horizontal' }, { value: 'vertical', label: 'Vertical' }, { value: 'aligned', label: 'Aligned' }], (v) => ws.setToolOption({ orient: v }))); + if (t.kind === 'note') parts.push(checkbox('With a leader arrow', t.leader, (v) => ws.setToolOption({ leader: v }))); + parts.push(h('button', { class: 'btn small', type: 'button', onclick: () => ws.cancelTool() }, icon('close', 14), 'Cancel command')); + return section(TOOL_LABELS[t.kind], parts); } - private viewRow(v: DrawingView): HTMLElement { + private viewSection(d: DrawingDoc, v: DrawingView): HTMLElement { const ws = this.ws; - const del = h('button', { class: 'icon-btn', type: 'button', 'aria-label': `Delete ${VIEW_LABELS[v.kind]} view` }, icon('trash', 14)); - del.addEventListener('click', () => { ws.selected = v.id; ws.deleteSelected(); }); - const hidden = h('input', { type: 'checkbox', 'aria-label': `Hidden lines in ${VIEW_LABELS[v.kind]} view` }) as HTMLInputElement; - hidden.checked = v.hidden; - hidden.addEventListener('change', () => ws.updateFromPanel((d) => { const x = d.views.find((q) => q.id === v.id); if (x) x.hidden = hidden.checked; }, 'Hidden lines')); - const dims = h('input', { type: 'checkbox', 'aria-label': `Dimensions in ${VIEW_LABELS[v.kind]} view` }) as HTMLInputElement; + const set = (label: string, fn: (x: DrawingView) => void) => ws.updateFromPanel((dd) => { const x = dd.views.find((q) => q.id === v.id); if (x) fn(x); }, label); + const type = v.type ?? 'model'; + const parts: HTMLElement[] = []; + const label = h('input', { class: 'input', value: v.label ?? '', 'aria-label': type === 'section' || type === 'detail' || type === 'auxiliary' ? 'View letter' : 'View caption' }) as HTMLInputElement; + label.addEventListener('change', () => set('View label', (x) => { const s = label.value.trim(); if (s) x.label = s; else if (type === 'model' || type === 'projected') delete x.label; })); + parts.push(h('div', {}, h('div', { class: 'field-label' }, type === 'model' || type === 'projected' ? 'Caption (empty: the view’s name)' : 'Letter'), label)); + if (type === 'model' && v.source && (v.source === ASSEMBLY_SOURCE || v.source === EXPLODED_SOURCE) && this.app.assembly?.doc.explode.length) { + parts.push(checkbox('Exploded (the assembly’s exploded view steps)', v.source === EXPLODED_SOURCE, (val) => set('Exploded view', (x) => { x.source = val ? EXPLODED_SOURCE : ASSEMBLY_SOURCE; }))); + } + if (type === 'model' || type === 'detail' || type === 'flat') { + const own = v.scale; + const opts = [{ value: '', label: type === 'detail' ? 'Twice the parent’s' : `Sheet scale (${scaleLabel(d.scale)})` }, ...STANDARD_SCALES.map((s) => ({ value: String(s), label: scaleLabel(s) }))]; + if (own !== undefined && !STANDARD_SCALES.includes(own)) opts.push({ value: String(own), label: scaleLabel(own) }); + parts.push(selectField('View scale', own === undefined ? '' : String(own), opts, (val) => set('View scale', (x) => { if (val) x.scale = Number(val); else delete x.scale; }))); + } + // A flat pattern has neither hidden lines nor tangent edges. + if (type !== 'flat') { + parts.push( + checkbox('Show hidden lines', v.hidden, (val) => set('Hidden lines', (x) => { x.hidden = val; })), + checkbox('Show tangent edges', v.tangent !== false, (val) => set('Tangent edges', (x) => { if (val) delete x.tangent; else x.tangent = false; })), + ); + } + parts.push(checkbox('Center marks and hole centerlines', !!v.centerMarks, (val) => set('Center marks', (x) => { x.centerMarks = val; }))); + if (type !== 'detail') parts.push(checkbox('Overall dimensions', v.dims, (val) => set('Dimensions', (x) => { x.dims = val; }))); + const deps = dependents(d, v.id); + parts.push(h('button', { class: 'btn small', type: 'button', onclick: () => ws.deleteView(v.id) }, icon('trash', 14), deps.length ? `Delete view and ${deps.length} made from it` : 'Delete view')); + return section(`View: ${viewName(d, v)}`, parts); + } + + private annotationsSection(d: DrawingDoc): HTMLElement { + const ws = this.ws; + const list = h('div', { class: 'drw-anno-list' }); + const names: Record = { dimension: 'Dimension', note: 'Note', centerMark: 'Center mark', centerline: 'Centerline', holeCallout: 'Hole callout', balloon: 'Balloon', bom: 'Bill of materials', cutList: 'Cut list' }; + for (const a of d.annotations ?? []) { + const dangling = ws.dangling(a); + const item = a.type === 'balloon' ? a.item ?? (a.view && ws.viewSource(a.view) ? ws.itemOf(ws.viewSource(a.view)!, a.ref.edge) : null) : null; + const text = a.type === 'balloon' ? `Balloon ${item ?? '?'}` : a.type === 'note' ? `Note: ${a.text.split('\n')[0]}` : a.type === 'dimension' ? `${{ horizontal: 'Horizontal', vertical: 'Vertical', aligned: 'Aligned', radius: 'Radius', diameter: 'Diameter', angle: 'Angle' }[a.kind]} dimension` : names[a.type]; + const name = h('button', { class: 'grow', type: 'button', 'aria-pressed': String(ws.selectedAnno === a.id), style: { background: 'none', border: '0', padding: '0', textAlign: 'left' } }, text, dangling ? h('span', { class: 'drw-missing' }, ' (geometry missing)') : null); + name.addEventListener('click', () => ws.selectAnno(a.id)); + const del = h('button', { class: 'icon-btn', type: 'button', 'aria-label': `Delete ${text}` }, icon('trash', 14)); + del.addEventListener('click', () => ws.deleteAnno(a.id)); + list.append(h('div', { class: `rel-btn${ws.selectedAnno === a.id ? ' on' : ''}`, style: { cursor: 'default' } }, name, del)); + } + const tool = (kind: DrawingToolKind, ic: string) => h('button', { class: 'btn small', type: 'button', 'aria-pressed': String(ws.tool?.kind === kind), onclick: () => ws.startTool(kind) }, icon(ic, 14), TOOL_LABELS[kind]); + return section('Annotations', [ + (d.annotations ?? []).length ? list : h('div', { class: 'field-label' }, 'No annotations yet.'), + h('div', { class: 'row wrap drw-tools' }, tool('dimension', 'smartDimension'), tool('centerMark', 'drawingCenterMark'), tool('centerline', 'centerline'), tool('note', 'text'), tool('holeCallout', 'drawingHoleCallout'), + ...(this.app.assembly || this.app.weldments.length ? [tool('balloon', 'balloon')] : []), + ...(this.app.assembly ? [tool('autoBalloon', 'autoBalloon'), h('button', { class: 'btn small', type: 'button', onclick: () => ws.addTable('bom') }, icon('bom', 14), 'Bill of Materials')] : []), + ...(!this.app.assembly && this.app.weldments.length ? [h('button', { class: 'btn small', type: 'button', onclick: () => ws.addTable('cutList') }, icon('cutList', 14), 'Cut List')] : [])), + ]); + } + + private annotationSection(a: DrawingAnnotation): HTMLElement { + const ws = this.ws; + const set = (label: string, fn: (x: DrawingAnnotation) => void) => ws.updateFromPanel((dd) => { const x = dd.annotations?.find((q) => q.id === a.id); if (x) fn(x); }, label); + const parts: HTMLElement[] = []; + if (a.type === 'note') { + const ta = h('textarea', { class: 'input', rows: '3', 'aria-label': 'Note text' }) as HTMLTextAreaElement; + ta.value = a.text; + ta.addEventListener('change', () => set('Note text', (x) => { if (x.type === 'note') x.text = ta.value; })); + parts.push(h('div', {}, h('div', { class: 'field-label' }, 'Text'), ta)); + parts.push(selectField('Text height', String(a.size ?? 3.5), ['2.5', '3.5', '5', '7'].map((s) => ({ value: s, label: `${s} mm` })), (v) => set('Note size', (x) => { if (x.type === 'note') x.size = Number(v); }))); + } + if (a.type === 'dimension') { + const doc = this.app.store.doc; + parts.push(selectField('Decimals', a.decimals === undefined ? '' : String(a.decimals), [{ value: '', label: `Document (${doc.decimals})` }, ...[0, 1, 2, 3, 4].map((n) => ({ value: String(n), label: String(n) }))], (v) => set('Decimals', (x) => { if (x.type === 'dimension') { if (v === '') delete x.decimals; else x.decimals = Number(v); } }))); + const pre = h('input', { class: 'input', value: a.prefix ?? '', 'aria-label': 'Text before the value' }) as HTMLInputElement; + pre.addEventListener('change', () => set('Dimension prefix', (x) => { if (x.type === 'dimension') { if (pre.value) x.prefix = pre.value; else delete x.prefix; } })); + parts.push(h('div', {}, h('div', { class: 'field-label' }, 'Text before the value (e.g. 2X)'), pre)); + if (ws.dangling(a)) parts.push(h('div', { class: 'pm-msg warn', role: 'status' }, 'The model edge this dimension measured is gone. Delete it and dimension the new geometry.')); + } + parts.push(h('button', { class: 'btn small', type: 'button', onclick: () => ws.deleteAnno(a.id) }, icon('trash', 14), 'Delete annotation')); + return section('Selected annotation', parts); + } + + private viewRow(d: DrawingDoc, v: DrawingView): HTMLElement { + const ws = this.ws; + const vn = viewName(d, v); + const del = h('button', { class: 'icon-btn', type: 'button', 'aria-label': `Delete ${vn} view` }, icon('trash', 14)); + del.addEventListener('click', () => ws.deleteView(v.id)); + const flat = v.type === 'flat'; + const hidden = h('input', { type: 'checkbox', 'aria-label': `Hidden lines in ${vn} view`, ...(flat ? { disabled: true } : {}) }) as HTMLInputElement; + hidden.checked = v.hidden && !flat; + hidden.addEventListener('change', () => ws.updateFromPanel((dd) => { const x = dd.views.find((q) => q.id === v.id); if (x) x.hidden = hidden.checked; }, 'Hidden lines')); + const dims = h('input', { type: 'checkbox', 'aria-label': `Dimensions in ${vn} view` }) as HTMLInputElement; dims.checked = v.dims; - dims.addEventListener('change', () => ws.updateFromPanel((d) => { const x = d.views.find((q) => q.id === v.id); if (x) x.dims = dims.checked; }, 'Dimensions')); + dims.addEventListener('change', () => ws.updateFromPanel((dd) => { const x = dd.views.find((q) => q.id === v.id); if (x) x.dims = dims.checked; }, 'Dimensions')); const name = h('button', { class: 'grow', type: 'button', 'aria-pressed': String(ws.selected === v.id), title: 'Select the view; arrow keys then move it', style: { background: 'none', border: '0', padding: '0', textAlign: 'left' }, - }, VIEW_LABELS[v.kind]); + }, vn); name.addEventListener('click', () => ws.select(v.id)); const row = h('div', { class: `rel-btn${ws.selected === v.id ? ' on' : ''}`, style: { cursor: 'default' } }, name, - h('label', { class: 'check', title: 'Hidden lines' }, hidden, h('span', { class: 'field-label' }, 'Hidden')), + h('label', { class: 'check', title: flat ? 'A flat pattern has no hidden lines' : 'Hidden lines' }, hidden, h('span', { class: 'field-label' }, 'Hidden')), h('label', { class: 'check', title: 'Overall dimensions' }, dims, h('span', { class: 'field-label' }, 'Dims')), del); return row; } } + +export type { Prim }; diff --git a/src/parametric/src/app/fileops.ts b/src/parametric/src/app/fileops.ts index 88e8161212..9c0b8fdd3a 100644 --- a/src/parametric/src/app/fileops.ts +++ b/src/parametric/src/app/fileops.ts @@ -2,8 +2,9 @@ // plus crash recovery of unsaved work in browser storage. import { defaultName } from '../model/features'; -import { allocateId, newDocument, parseDocument, serializeDocument, withUsedBlobs } from '../model/document'; +import { allocateId, newDocument, serializeDocument, withUsedBlobs } from '../model/document'; import type { ImportFeature, PartDocument } from '../model/types'; +import { newAssembly, parseAnyDocument } from '../model/assembly'; import { type Location, EXT, IMPORT_EXTS, clearRecovery, download, isSolidWorksFile, isStepFile, listParts, loadText, locationLabel, newLocation, pickCloudFile, pickCloudSave, pickDeviceFile, claimRecovery, orphanRecoveries, removeRecovery, safeName, writeRecovery, writeRecoveryOnUnload, type FileEntry, deletePart, forgetRecent, rememberRecent, @@ -265,6 +266,13 @@ export class FileOps { await this.clearRecoveryCopies(); } + /** Starts a new, empty assembly (an assembly is saved in a part file of its own kind). */ + async newAssembly() { + if (!(await this.confirmDiscard('start a new assembly'))) return; + this.app.loadDocument(newAssembly(nextUntitled(this.app.store.doc.name, 'Assembly'), this.app.settings.defaultUnits) as unknown as PartDocument, null); + await this.clearRecoveryCopies(); + } + /** Save to the current location, or ask where for a new document. */ async save(): Promise { const app = this.app; @@ -722,6 +730,8 @@ export class FileOps { const blob = new Blob([data as BlobPart], { type: format === 'step' ? 'model/step' : 'model/stl' }); download(blob, `${name}.${format === 'step' ? 'step' : 'stl'}`); + // Surface bodies (listed after the solid's faces) are not in an STL file. + if (format === 'stl' && app.faces.at(-1)?.body) toast({ kind: 'warning', message: 'The surface bodies are not in the STL file: STL holds solids only. Export STEP to keep them.', timeout: 9000 }); // The file has what the model shows: say so when the rollback bar leaves features out. const left = app.store.doc.features.length - app.store.builtCount; if (left > 0) toast({ kind: 'warning', message: `The part is rolled back, so the ${left === 1 ? 'feature' : `${left} features`} below the rollback bar ${left === 1 ? 'is' : 'are'} not in the exported file. Move the rollback bar to the end to export the whole part.`, timeout: 9000 }); @@ -867,7 +877,7 @@ export class FileOps { if (v === 'restore') { let doc: PartDocument; try { - doc = parseDocument(JSON.stringify(data.doc)); + doc = parseAnyDocument(JSON.stringify(data.doc)) as PartDocument; } catch (e) { toast({ kind: 'error', message: (e as Error).message }); await removeRecovery(file); @@ -989,23 +999,24 @@ const isDriveFolder = (it: PuterFSItem) => { /** The part in a file's text, or null after reporting why it is not one. */ function parsePart(text: string): PartDocument | null { try { - return parseDocument(text); + // An assembly opens as well: the app switches to assembly mode for it. + return parseAnyDocument(text) as PartDocument; } catch (e) { toast({ kind: 'error', title: 'Could not open the part', message: (e as Error).message }); return null; } } -let untitled = 1; +const untitledCounts: Record = { Part: 1, Assembly: 0 }; /** - * The next PartN of this session that no part open, recently opened or kept - * in this browser has, so a new part does not take the name of one it would - * be confused with (or, saved, get "Part2 (2)"). + * The next PartN (or AssemblyN) of this session that no part open, recently + * opened or kept in this browser has, so a new part does not take the name of + * one it would be confused with (or, saved, get "Part2 (2)"). */ -function nextUntitled(current: string): string { +function nextUntitled(current: string, prefix: 'Part' | 'Assembly' = 'Part'): string { const taken = new Set([current, ...recentParts().map((r) => r.name), ...localPartNames()].map((n) => n.toLowerCase())); let name: string; - do name = `Part${++untitled}`; while (taken.has(name.toLowerCase())); + do name = `${prefix}${++untitledCounts[prefix]}`; while (taken.has(name.toLowerCase())); return name; } diff --git a/src/parametric/src/app/panels.ts b/src/parametric/src/app/panels.ts index b9ab67cc56..004fe6a039 100644 --- a/src/parametric/src/app/panels.ts +++ b/src/parametric/src/app/panels.ts @@ -4,7 +4,7 @@ import type { Vec3 } from '../math/vec'; import { dot, sub, toLocal } from '../math/vec'; import { defaultName, newChamfer, newCircularPattern, newDraft, newExtrude, newFillet, newHole, newLinearPattern, newLoft, - newMirror, newPlane, newRevolve, newShell, newSketch, newSweep, FEATURE_LABELS, featureIcon, + newMirror, newPlane, newRevolve, newShell, newSketch, newSweep, FEATURE_LABELS, consumedSketches, featureIcon, } from '../model/features'; import { BASE_PLANE_NAMES } from '../model/planes'; import { changeFeatureUnits } from '../model/document'; @@ -104,7 +104,7 @@ function axisLabel(app: App, ref: AxisRef | null): string { if (!ref) return ''; switch (ref.kind) { case 'base': return `${ref.axis.toUpperCase()} axis`; - case 'edge': return `Edge (${ref.edge.sig.type})`; + case 'edge': return ref.edge.sig.type ? `Edge (${ref.edge.sig.type})` : 'Edge'; case 'face': return `Face of ${app.store.feature(app.faces.find((f) => f.name === ref.face.name)?.feature ?? '')?.name ?? 'part'}`; case 'sketchLine': return `${app.store.feature(ref.sketch)?.name ?? 'Sketch'} line`; } @@ -134,7 +134,7 @@ function axisItem(app: App, r: AxisRef): SelItem | null { // ---------- base ---------- -abstract class FeaturePanel extends PropertyPanel { +export abstract class FeaturePanel extends PropertyPanel { f: T; private units: UnitSystem; private variables: Variable[]; @@ -315,7 +315,7 @@ function edgeFaceBox(panel: PropertyPanel, app: App, label: string, f: { edges: onChange(); }, { placeholder: 'Select edges or faces', icon: 'fillet' }); box.setItems([ - ...f.edges.map((e) => ({ item: edgeItem(app, e), data: e, label: `Edge (${e.sig.type})` })), + ...f.edges.map((e) => ({ item: edgeItem(app, e), data: e, label: e.sig.type ? `Edge (${e.sig.type})` : 'Edge' })), ...f.faces.map((r) => ({ item: faceItem(app, r), data: r, label: 'Face' })), ]); return box; @@ -680,6 +680,9 @@ export class SweepPanel extends FeaturePanel { // ---------- factory ---------- +/** Panels of feature types defined in other modules (sheet metal), which register them here. */ +export const featurePanelFactories: ((app: App, f: Feature, editing: boolean) => PropertyPanel | null)[] = []; + export function panelFor(app: App, f: Feature, editing: boolean): PropertyPanel | null { switch (f.type) { case 'extrude': return new ExtrudePanel(app, f, editing); @@ -695,7 +698,9 @@ export function panelFor(app: App, f: Feature, editing: boolean): PropertyPanel case 'loft': return new LoftPanel(app, f, editing); case 'sweep': return new SweepPanel(app, f, editing); case 'draft': return new DraftPanel(app, f, editing); - default: return null; + default: + for (const make of featurePanelFactories) { const p = make(app, f, editing); if (p) return p; } + return null; } } @@ -710,7 +715,8 @@ export function startFeature(app: App, type: Feature['type'], opts: { cut?: bool const selSketch = (() => { for (const it of sel) if (it.kind === 'feature' && app.store.feature(it.id)?.type === 'sketch') return it.id; // Default to the most recent unconsumed sketch. - const used = new Set(doc.features.flatMap((f) => (f.type === 'extrude' || f.type === 'revolve' || f.type === 'hole' ? [f.sketch] : f.type === 'loft' ? f.profiles : f.type === 'sweep' ? [f.profile, f.path] : []))); + // (Surface features, base flanges and sketched bends consume their sketches too.) + const used = new Set(doc.features.flatMap((f) => consumedSketches(f))); const built = doc.features.slice(0, app.store.builtCount); for (let i = built.length - 1; i >= 0; i--) if (built[i].type === 'sketch' && !used.has(built[i].id)) return built[i].id; return null; @@ -779,3 +785,6 @@ function cutFlip(app: App, sketchId: Id | null): boolean { // Cuts go against the normal by default; flip when the material is in front. return dot(sub(c, fr.o), fr.n) > 1e-6; } + +// For the surface feature panels (surface-panels.ts). +export { axisItem, axisLabel, edgeItem, faceItem, isSketch, planeItem, planeLabel }; diff --git a/src/parametric/src/app/pm.ts b/src/parametric/src/app/pm.ts index adb38168ac..f6f48dbe89 100644 --- a/src/parametric/src/app/pm.ts +++ b/src/parametric/src/app/pm.ts @@ -25,6 +25,8 @@ export interface PickFilter { sketchLine?: boolean; sketchPoint?: boolean; axis?: boolean; + /** Lines and arcs of the sketches shown in the 3D view (weldment member paths). */ + sketchSegment?: boolean; } export interface UnitContext { @@ -411,6 +413,8 @@ export function flipButton(label: string, pressed: boolean, onChange: (v: boolea export interface SelBoxItem { item: SelItem | null; + /** More to highlight in the graphics area (all faces of a structural member), found again at each redraw. */ + highlights?: () => SelItem[]; /** Arbitrary payload stored by the panel (e.g. a FaceRef). */ data: unknown; label: string; diff --git a/src/parametric/src/app/selection.ts b/src/parametric/src/app/selection.ts index 68c9b28333..7a92b7ed0d 100644 --- a/src/parametric/src/app/selection.ts +++ b/src/parametric/src/app/selection.ts @@ -16,7 +16,9 @@ export type SelItem = | { kind: 'feature'; id: Id } | { kind: 'sk'; id: Id } | { kind: 'skdim'; id: Id } - | { kind: 'skrel'; id: Id }; + | { kind: 'skrel'; id: Id } + /** A line or arc of a sketch picked in the 3D view (weldment member paths). */ + | { kind: 'skseg'; sketch: Id; entity: Id }; export function sameItem(a: SelItem, b: SelItem): boolean { if (a.kind !== b.kind) return false; @@ -36,6 +38,8 @@ export function sameItem(a: SelItem, b: SelItem): boolean { return true; case 'axis': return a.axis === (b as typeof a).axis; + case 'skseg': + return a.sketch === (b as typeof a).sketch && a.entity === (b as typeof a).entity; default: return (a as { id: Id }).id === (b as { id: Id }).id; } diff --git a/src/parametric/src/app/sheetmetal-panels.ts b/src/parametric/src/app/sheetmetal-panels.ts new file mode 100644 index 0000000000..0b103b6c4d --- /dev/null +++ b/src/parametric/src/app/sheetmetal-panels.ts @@ -0,0 +1,508 @@ +// Sheet metal in the interface: the Sheet Metal tab of the CommandManager, +// PropertyManager panels for its features, the flat pattern view (with DXF +// export) and the Sheet-Metal and Flat-Pattern rows of the design tree. + +import type { Vec3 } from '../math/vec'; +import { add, scale } from '../math/vec'; +import { Camera } from '../render/camera'; +import type { EdgeRef, Feature, Id, SketchFeature } from '../model/types'; +import { + type BaseFlangeFeature, type BendAllowanceType, type EdgeFlangeFeature, type FlangeLengthRef, type FlangePosition, type HemFeature, type ReliefType, + type SketchedBendFeature, type SketchedBendPosition, newBaseFlange, newEdgeFlange, newHem, newSketchedBend, +} from '../model/sheetmetal'; +import { type FlatPattern, bendNote, flatPatternDxf, flatSize } from '../model/flat-pattern'; +import { defaultName, nextName } from '../model/features'; +import { buildProfiles } from '../sketch/profiles'; +import type { FlatPatternResult } from '../kernel/protocol'; +import { download, safeName } from '../platform/files'; +import { h, nextDomId } from '../ui/dom'; +import { toast } from '../ui/overlay'; +import type { App } from './app'; +import type { Command } from './commands'; +import type { RibbonTab } from './shell'; +import { FeaturePanel, featurePanelFactories, toEdge } from './panels'; +import { PropertyPanel, SelectionBox, type SelBoxItem, checkbox, flipButton, fmt, numberField, section, selectField } from './pm'; +import { edgeRef } from './selection'; + +// ---------- helpers ---------- + +/** + * The Base Flange holding the part's sheet metal parameters: as in the + * rebuild, the first one that is not suppressed and builds (else the first + * one not suppressed, which is the one to fix). A later one is a Tab. + */ +export function sheetOwner(app: App): BaseFlangeFeature | null { + const flanges = app.store.doc.features.filter((f): f is BaseFlangeFeature => f.type === 'baseFlange'); + const active = flanges.filter((f) => !f.suppressed && !app.featureStatus(f.id)?.suppressed); + return active.find((f) => app.featureStatus(f.id)?.ok !== false) ?? active[0] ?? flanges[0] ?? null; +} + +const hasSheetMetal = (app: App) => !!sheetOwner(app); + +/** + * A default length in millimetres that shows as a plain number in the part's + * units (an inch value converted from millimetres showed as 0.060000000000000005). + */ +function plainLength(app: App, mm: number): number { + const unit = app.store.unitScale; + return Number((mm / unit).toPrecision(10)) * unit; +} + +/** The sheet thickness in millimetres (1 mm, or 0.06 in, without a sheet metal part). */ +function sheetThickness(app: App): number { + const o = sheetOwner(app); + if (!o) return app.store.doc.units === 'IPS' ? plainLength(app, 1.524) : 1; + try { return app.store.evalParam(o.sm.thickness, 'length'); } catch { return 1; } +} + +/** A plain decimal input (K-factor, ratios). */ +function ratioField(label: string, value: number, opts: { min: number; max?: number }, onChange: (v: number) => void): HTMLElement { + const id = nextDomId('ratio'); + const input = h('input', { class: 'input', id, inputmode: 'decimal', autocomplete: 'off', spellcheck: 'false', 'aria-label': label, value: String(value) }) as HTMLInputElement; + input.addEventListener('change', () => { + const v = Number(input.value.trim()); + const bad = !Number.isFinite(v) || input.value.trim() === '' ? 'Enter a number' : v < opts.min ? `Must be at least ${opts.min}` : opts.max !== undefined && v > opts.max ? `Must be at most ${opts.max}` : ''; + input.classList.toggle('invalid', !!bad); + if (bad) { input.setAttribute('aria-invalid', 'true'); input.title = bad; return; } + input.removeAttribute('aria-invalid'); + input.title = ''; + onChange(v); + }); + return h('div', {}, h('label', { class: 'field-label', for: id }, label), h('div', { class: 'row' }, h('div', { class: 'spin grow' }, input))); +} + +function sketchOf(app: App, id: Id): SketchFeature | null { + const f = id ? app.store.feature(id) : undefined; + return f?.type === 'sketch' ? f : null; +} + +/** The sketch a new feature uses: the selected one, else the latest one no feature uses yet. */ +function pickSketch(app: App): Id | null { + for (const it of app.selection.items) if (it.kind === 'feature' && app.store.feature(it.id)?.type === 'sketch') return it.id; + const doc = app.store.doc; + const used = new Set(doc.features.flatMap((f) => (f.type === 'extrude' || f.type === 'revolve' || f.type === 'hole' || f.type === 'baseFlange' || f.type === 'sketchedBend' ? [f.sketch] : f.type === 'loft' ? f.profiles : f.type === 'sweep' ? [f.profile, f.path] : []))); + const built = doc.features.slice(0, app.store.builtCount); + for (let i = built.length - 1; i >= 0; i--) if (built[i].type === 'sketch' && !used.has(built[i].id) && (built[i] as SketchFeature).entities.length) return built[i].id; + return null; +} + +/** Straight edges only. */ +const toStraightEdge = (app: App) => (it: import('./selection').SelItem): SelBoxItem | null => { + const r = toEdge(app)(it); + return r && app.edges[(it as { index: number }).index]?.type === 'line' ? r : null; +}; + +function edgeBox(panel: PropertyPanel, app: App, f: { edges: EdgeRef[] }, onChange: () => void): SelectionBox { + const box = new SelectionBox(panel, 'Edges', { edge: true }, toStraightEdge(app), (items) => { f.edges = items.map((i) => i.data as EdgeRef); onChange(); }, { placeholder: 'Select edges of the sheet', icon: 'edgeFlange' }); + box.setItems(f.edges.map((e) => ({ item: { kind: 'edge', index: app.edges.findIndex((x) => x.name === e.name), name: e.name }, data: e, label: e.sig?.type ? `Edge (${e.sig.type})` : 'Edge' }))); + return box; +} + +// ---------- Base Flange / Tab ---------- + +export class BaseFlangePanel extends FeaturePanel { + /** + * Whether this feature holds the part's sheet metal parameters: it is the + * active Base Flange, or one before it (failed or suppressed) that would be. + */ + private get owner(): boolean { + const o = sheetOwner(this.app); + if (!o || o.id === this.f.id) return true; + const features = this.app.store.doc.features; + const at = features.findIndex((f) => f.id === this.f.id); + return at >= 0 && at < features.findIndex((f) => f.id === o.id); + } + + get title() { + return this.editingId ? this.f.name : this.owner ? 'Base Flange' : 'Tab'; + } + + private open(): boolean { + const sk = sketchOf(this.app, this.f.sketch); + return !!sk && sk.entities.some((e) => e.t !== 'point' && !e.construction) && !buildProfiles(sk.entities).regions.length; + } + + render(): HTMLElement[] { + const f = this.f; + const ctx = this.ctx(); + const sketch = this.sketchBox('Profile sketch', () => f.sketch, (id) => { f.sketch = id ?? ''; this.app.refreshPanel(); }); + const out: HTMLElement[] = [section('Profile', [sketch.el])]; + if (!this.owner) { + out.push(section('Tab', [h('p', { class: 'field-label' }, 'Sketch a closed profile on a flat face of the sheet. The tab adds it in the sheet\'s thickness.')])); + return out; + } + const open = this.open(); + if (open) { + const depth = numberField({ label: 'Depth', icon: 'ruler', value: f.depth, kind: 'length', ctx, min: 1e-6, onChange: (v) => { f.depth = v; this.changed(); } }); + out.push(section('Direction 1', [ + h('div', { class: 'row' }, flipButton('Reverse direction', f.depthFlip, (v) => { f.depthFlip = v; this.changed(); }), h('div', { class: 'grow' }, + selectField('End condition', f.depthEnd, [{ value: 'blind' as const, label: 'Blind' }, { value: 'midPlane' as const, label: 'Mid Plane' }], (v) => { f.depthEnd = v; this.changed(); }))), + depth, + ])); + } + const sm = f.sm; + const allowance = numberField({ label: sm.allowance === 'bendDeduction' ? 'Bend deduction' : 'Bend allowance', icon: 'ruler', value: sm.allowanceValue, kind: 'length', ctx, onChange: (v) => { sm.allowanceValue = v; this.changed(); } }); + allowance.hidden = sm.allowance === 'kFactor'; + const deductionNote = h('p', { class: 'field-label' }, 'Bends over 90° use the K-factor this deduction gives a 90° bend.'); + deductionNote.hidden = sm.allowance !== 'bendDeduction'; + const k = ratioField('K-factor', sm.kFactor, { min: 0, max: 1 }, (v) => { sm.kFactor = v; this.changed(); }); + k.hidden = sm.allowance !== 'kFactor'; + const ratio = ratioField('Relief ratio', sm.reliefRatio, { min: 0.05, max: 10 }, (v) => { sm.reliefRatio = v; this.changed(); }); + ratio.hidden = sm.relief === 'none'; + out.push( + section('Sheet Metal Parameters', [ + h('div', { class: 'row' }, flipButton('Reverse thickness direction', f.flip, (v) => { f.flip = v; this.changed(); }), h('div', { class: 'grow' }, + numberField({ label: 'Thickness', icon: 'sheetThickness', value: sm.thickness, kind: 'length', ctx, min: 1e-6, onChange: (v) => { sm.thickness = v; this.changed(); } }))), + checkbox('Mid-plane thickness', f.mid, (v) => { f.mid = v; this.changed(); }), + numberField({ label: 'Bend radius', icon: 'bendRadius', value: sm.radius, kind: 'length', ctx, min: 0, onChange: (v) => { sm.radius = v; this.changed(); } }), + ], { icon: 'sheetMetal' }), + section('Bend Allowance', [ + selectField('Bend allowance type', sm.allowance, [ + { value: 'kFactor', label: 'K-Factor' }, { value: 'bendAllowance', label: 'Bend Allowance' }, { value: 'bendDeduction', label: 'Bend Deduction' }, + ], (v) => { sm.allowance = v; this.changed(); this.app.refreshPanel(); }), + k, allowance, deductionNote, + ]), + section('Auto Relief', [ + selectField('Relief type', sm.relief, [{ value: 'rectangular', label: 'Rectangular' }, { value: 'obround', label: 'Obround' }, { value: 'none', label: 'None' }], (v) => { + sm.relief = v; ratio.hidden = v === 'none'; this.changed(); + }), + ratio, + ]), + ); + return out; + } + + protected validate() { + return this.f.sketch ? null : 'Select a sketch for the base flange'; + } +} + +// ---------- Edge Flange ---------- + +const POSITIONS: { value: FlangePosition; label: string }[] = [ + { value: 'materialInside', label: 'Material Inside' }, { value: 'materialOutside', label: 'Material Outside' }, { value: 'bendOutside', label: 'Bend Outside' }, +]; + +export class EdgeFlangePanel extends FeaturePanel { + render(): HTMLElement[] { + const f = this.f; + const ctx = this.ctx(); + const box = edgeBox(this, this.app, f, () => this.changed()); + return [ + section('Flange Parameters', [box.el, h('div', { class: 'row' }, flipButton('Reverse direction', f.flip, (v) => { f.flip = v; this.changed(); }), h('span', { class: 'field-label' }, 'Reverse direction'))]), + section('Angle', [numberField({ label: 'Flange angle', icon: 'angle', value: f.angle, kind: 'angle', ctx, min: 1e-6, max: 179.999, onChange: (v) => { f.angle = v; this.changed(); } })]), + section('Flange Length', [ + numberField({ label: 'Length', icon: 'ruler', value: f.length, kind: 'length', ctx, min: 1e-6, onChange: (v) => { f.length = v; this.changed(); } }), + selectField('Measured from', f.lengthRef, [ + { value: 'outer', label: 'Outer Virtual Sharp' }, { value: 'inner', label: 'Inner Virtual Sharp' }, { value: 'tangent', label: 'Tangent Bend' }, + ], (v) => { f.lengthRef = v; this.changed(); }), + ]), + section('Flange Position', [selectField('Flange position', f.position, POSITIONS, (v) => { f.position = v; this.changed(); })]), + section('Offsets', [ + h('p', { class: 'field-label' }, 'Stop the flange short of the ends of the edge; reliefs are cut beside its bend.'), + numberField({ label: 'Offset 1', icon: 'ruler', value: f.offset1, kind: 'length', ctx, min: 0, onChange: (v) => { f.offset1 = v; this.changed(); } }), + numberField({ label: 'Offset 2', icon: 'ruler', value: f.offset2, kind: 'length', ctx, min: 0, onChange: (v) => { f.offset2 = v; this.changed(); } }), + ], { collapsed: !Number(f.offset1) && !Number(f.offset2) }), + ]; + } + + preview() { + return this.f.edges.length ? this.f : null; + } + + protected validate() { + return this.f.edges.length ? null : 'Select one or more edges of the sheet'; + } +} + +// ---------- Sketched Bend ---------- + +export class SketchedBendPanel extends FeaturePanel { + render(): HTMLElement[] { + const f = this.f; + const ctx = this.ctx(); + const sketch = this.sketchBox('Bend line sketch', () => f.sketch, (id) => { f.sketch = id ?? ''; }); + return [ + section('Bend Parameters', [ + sketch.el, + h('div', { class: 'row' }, flipButton('Reverse fixed side', f.flipFixed, (v) => { f.flipFixed = v; this.changed(); }), h('span', { class: 'field-label' }, 'Fixed side: reverse')), + selectField('Bend position', f.position, [{ value: 'centerline', label: 'Bend Centerline' }, ...POSITIONS], (v) => { f.position = v; this.changed(); }), + h('div', { class: 'row' }, flipButton('Reverse direction', f.flip, (v) => { f.flip = v; this.changed(); }), h('div', { class: 'grow' }, + numberField({ label: 'Bend angle', icon: 'angle', value: f.angle, kind: 'angle', ctx, min: 1e-6, max: 179.999, onChange: (v) => { f.angle = v; this.changed(); } }))), + ]), + ]; + } + + protected validate() { + return this.f.sketch ? null : 'Select a sketch with the bend line'; + } +} + +// ---------- Hem ---------- + +export class HemPanel extends FeaturePanel { + render(): HTMLElement[] { + const f = this.f; + const ctx = this.ctx(); + const box = edgeBox(this, this.app, f, () => this.changed()); + const gap = numberField({ label: 'Gap distance', icon: 'ruler', value: f.gap, kind: 'length', ctx, min: 1e-6, onChange: (v) => { f.gap = v; this.changed(); } }); + gap.hidden = f.kind === 'closed'; + return [ + section('Edges', [box.el, h('div', { class: 'row' }, flipButton('Reverse direction', f.flip, (v) => { f.flip = v; this.changed(); }), h('span', { class: 'field-label' }, 'Reverse direction')), + selectField('Position', f.position, [{ value: 'materialInside', label: 'Material Inside' }, { value: 'bendOutside', label: 'Bend Outside' }], (v) => { f.position = v; this.changed(); })]), + section('Type and Size', [ + selectField('Hem type', f.kind, [{ value: 'closed', label: 'Closed' }, { value: 'open', label: 'Open' }], (v) => { f.kind = v; gap.hidden = v === 'closed'; this.changed(); }), + numberField({ label: 'Length', icon: 'ruler', value: f.length, kind: 'length', ctx, min: 1e-6, onChange: (v) => { f.length = v; this.changed(); } }), + gap, + ]), + ]; + } + + preview() { + return this.f.edges.length ? this.f : null; + } + + protected validate() { + return this.f.edges.length ? null : 'Select one or more edges of the sheet'; + } +} + +export function sheetMetalPanelFor(app: App, f: Feature, editing: boolean): PropertyPanel | null { + switch (f.type) { + case 'baseFlange': return new BaseFlangePanel(app, f, editing); + case 'edgeFlange': return new EdgeFlangePanel(app, f, editing); + case 'sketchedBend': return new SketchedBendPanel(app, f, editing); + case 'hem': return new HemPanel(app, f, editing); + default: return null; + } +} + +featurePanelFactories.push(sheetMetalPanelFor); + +// ---------- flat pattern ---------- + +/** Shows the part flattened in place of the folded body while it is open. */ +export class FlatPatternPanel extends PropertyPanel { + title = 'Flat Pattern'; + icon = 'flatPattern'; + confirm = false; + closeLabel = 'Exit Flat Pattern'; + helpText = 'The part unfolded, with bend lines (dashed) and the bend notes.'; + private result: FlatPatternResult | null = null; + private error: string | null = null; + private seq = 0; + private disposed = false; + private framed = false; + + constructor(private app: App) { + super(); + app.selection.clear(); + } + + filter() { + return {}; + } + + mount(): HTMLElement { + const el = super.mount(); + if (!this.result && !this.error) void this.load(); + return el; + } + + onBuild() { + void this.load(); + } + + private async load() { + const seq = ++this.seq; + let res: FlatPatternResult; + try { + res = await this.app.kernel.flatPattern(this.app.settings.quality); + } catch (e) { + res = { pattern: null, mesh: null, error: (e as Error).message }; + } + if (this.disposed || seq !== this.seq) return; + this.result = res; + this.error = res.error ?? null; + this.show(); + this.app.refreshPanel(); + } + + private show() { + const app = this.app; + const r = this.result; + if (!r?.pattern || !r.mesh) { app.showModelMesh(); app.renderer.setLines('flatBends', null); return; } + const p = r.pattern; + app.renderer.setModel(r.mesh, Math.max(1, app.faces.length), Math.max(1, app.edges.length)); + const pos = r.mesh.positions; + const min: Vec3 = [Infinity, Infinity, Infinity], max: Vec3 = [-Infinity, -Infinity, -Infinity]; + for (let i = 0; i < pos.length; i += 3) for (let k = 0; k < 3; k++) { min[k] = Math.min(min[k], pos[i + k]); max[k] = Math.max(max[k], pos[i + k]); } + app.bbox = { min, max }; + // Bend centre lines on the top face of the flat pattern, dashed: green up, blue down. + const xf = p.placement; + const at = (q: [number, number]): Vec3 => add(add(add(xf.o, scale(xf.x, q[0])), scale(xf.y, q[1])), scale(xf.n, p.thickness * 1.001)); + const lines: number[] = []; + const colors: number[] = []; + for (const b of p.bends) { + lines.push(...at(b.a), ...at(b.b)); + colors.push(...(b.up ? [40, 150, 60, 255] : [40, 90, 200, 255])); + } + app.renderer.setLines('flatBends', lines.length ? { positions: new Float32Array(lines), colors: new Uint8Array(colors), width: 1.6, depth: 'always', dash: 6, order: 6 } : null); + if (!this.framed) { + this.framed = true; + const cam = app.renderer.camera; + const center = scale(add(min, max), 0.5); + const radius = Math.max(1, Math.hypot(max[0] - min[0], max[1] - min[1], max[2] - min[2]) / 2); + cam.animateTo(cam.fitState(center, radius, Camera.normalTo(xf.n, xf.x))); + } + app.renderer.requestRender(); + } + + render(): HTMLElement[] { + const app = this.app; + const ctx = app.unitContext(); + const r = this.result; + if (!r) return [section('Flat Pattern', [h('p', { class: 'field-label' }, 'Flattening the part...')])]; + if (!r.pattern) return [section('Flat Pattern', [h('p', { class: 'pm-msg error', role: 'alert' }, r.error ?? 'The part cannot be flattened')])]; + const p = r.pattern; + const [w, ht] = flatSize(p); + const len = (v: number) => `${fmt(v, 'length', ctx)}`; + const notes = p.notes.length ? p.notes : ['Holes and cuts through flat regions are shown.']; + return [ + section('Flat Pattern', [ + h('table', { class: 'table flat-size' }, h('tbody', {}, + h('tr', {}, h('th', {}, 'Overall size'), h('td', { class: 'num' }, `${len(w)} × ${len(ht)}`)), + h('tr', {}, h('th', {}, 'Thickness'), h('td', { class: 'num' }, len(p.thickness))), + h('tr', {}, h('th', {}, 'Bends'), h('td', { class: 'num' }, String(p.bends.length))))), + h('button', { class: 'btn small', type: 'button', onclick: () => exportDxf(app, p) }, 'Export DXF...'), + ], { icon: 'flatPattern' }), + ...(p.bends.length ? [section('Bend Notes', [ + h('table', { class: 'table flat-bends' }, + h('thead', {}, h('tr', {}, h('th', {}, 'Bend'), h('th', {}, 'Note'), h('th', {}, 'Allowance'))), + h('tbody', {}, p.bends.map((b, i) => h('tr', {}, h('td', {}, `${app.store.feature(b.feature)?.name ?? 'Bend'} (${i + 1})`), h('td', {}, bendNote(b, (v) => fmt(v, 'length', ctx))), h('td', { class: 'num' }, len(b.allowance)))))), + ])] : []), + section('Notes', notes.map((n) => h('p', { class: p.notes.length ? 'pm-msg warn' : 'field-label', role: 'note' }, n))), + ]; + } + + ok() { return true; } + + dispose() { + this.disposed = true; + this.app.renderer.setLines('flatBends', null); + this.app.showModelMesh(); + } +} + +function exportDxf(app: App, p: FlatPattern) { + download(flatPatternDxf(p), `${safeName(app.store.doc.name)}-flat.dxf`, 'application/dxf'); + toast({ kind: 'success', message: 'Flat pattern exported as DXF' }); +} + +async function exportFlatDxf(app: App) { + try { + const res = await app.kernel.flatPattern(0); + if (!res.pattern) { toast({ kind: 'error', title: 'Export DXF', message: res.error ?? 'The part cannot be flattened' }); return; } + exportDxf(app, res.pattern); + } catch (e) { + toast({ kind: 'error', title: 'Export DXF', message: (e as Error).message }); + } +} + +// ---------- commands ---------- + +function startFeature(app: App, type: 'baseFlange' | 'edgeFlange' | 'sketchedBend' | 'hem') { + const doc = app.store.doc; + const id = app.store.nextId('f'); + const T = sheetThickness(app); + const edges = app.selection.ofKind('edge').map((s) => app.edges[s.index]).filter((e) => e?.type === 'line').map(edgeRef); + let f: Feature; + switch (type) { + case 'baseFlange': { + const tab = hasSheetMetal(app); + f = newBaseFlange(id, tab ? nextName(doc, 'Tab') : defaultName(doc, 'baseFlange'), pickSketch(app) ?? '', T, Math.max(app.typicalSize(), doc.units === 'IPS' ? 12.7 : 10)); + break; + } + case 'edgeFlange': f = { ...newEdgeFlange(id, defaultName(doc, 'edgeFlange'), plainLength(app, Math.max(10 * T, app.typicalSize() / 4))), edges }; break; + case 'sketchedBend': f = newSketchedBend(id, defaultName(doc, 'sketchedBend'), pickSketch(app) ?? ''); break; + case 'hem': f = { ...newHem(id, defaultName(doc, 'hem'), plainLength(app, 5 * T), plainLength(app, T / 2)), edges }; break; + } + const p = sheetMetalPanelFor(app, f, false); + if (p) void app.openPanel(p); +} + +/** The sheet metal commands (ids are the feature types, as other features' are). */ +export function sheetMetalCommands(app: App): Command[] { + const needsSheet = () => hasSheetMetal(app) && !!app.bbox; + const sketchFirst = (type: 'baseFlange' | 'sketchedBend') => () => { + if (app.sketchEditor) { + const id = app.sketchEditor.sketchId; + app.exitSketch(true); + app.selection.set([{ kind: 'feature', id }]); + } + if (!pickSketch(app)) { + // No sketch yet: draw one, then carry on with this command. + app.pendingAfterSketch = type; + void app.commands.run('sketch'); + return; + } + startFeature(app, type); + }; + return [ + { + id: 'baseFlange', label: 'Base Flange/Tab', icon: 'baseFlange', keywords: 'sheet metal plate tab thickness bend', + description: 'Make a sheet metal part from a sketch: a closed profile gives a flat plate, an open one a bent profile. In a sheet metal part, adds a tab on a face.', + run: sketchFirst('baseFlange'), + }, + { + id: 'edgeFlange', label: 'Edge Flange', icon: 'edgeFlange', keywords: 'sheet metal flange bend wall', enabled: needsSheet, + description: 'Add a bent wall along edges of the sheet.', run: () => startFeature(app, 'edgeFlange'), + }, + { + id: 'sketchedBend', label: 'Sketched Bend', icon: 'sketchedBend', keywords: 'sheet metal bend line fold', enabled: needsSheet, + description: 'Bend the sheet along a line sketched on a flat face.', run: sketchFirst('sketchedBend'), + }, + { + id: 'hem', label: 'Hem', icon: 'hem', keywords: 'sheet metal fold back edge', enabled: needsSheet, + description: 'Fold an edge of the sheet back over itself.', run: () => startFeature(app, 'hem'), + }, + { + id: 'flatten', label: 'Flatten', icon: 'flatPattern', keywords: 'sheet metal flat pattern unfold blank', enabled: needsSheet, + description: 'Show the sheet metal part unfolded, with bend lines and notes.', + checked: () => app.panel instanceof FlatPatternPanel, + run: () => { + if (app.panel instanceof FlatPatternPanel) { void app.closePanel(false); return; } + app.exitModes(); + void app.openPanel(new FlatPatternPanel(app)); + }, + }, + { + id: 'exportFlatDxf', label: 'Export DXF', icon: 'export', keywords: 'sheet metal flat pattern dxf laser cut', enabled: needsSheet, + description: 'Export the flat pattern as a DXF file for cutting.', run: () => { void exportFlatDxf(app); }, + }, + { + id: 'sheetMetalParameters', label: 'Sheet Metal Parameters', icon: 'sheetMetal', keywords: 'thickness bend radius k-factor', enabled: () => hasSheetMetal(app), + description: 'Thickness, bend radius, bend allowance and reliefs of the part.', run: () => { const o = sheetOwner(app); if (o) app.editFeature(o.id); }, + }, + ]; +} + +export const SHEET_METAL_TAB: RibbonTab = { + id: 'sheetMetal', label: 'Sheet Metal', + groups: [ + [{ cmd: 'baseFlange' }, { cmd: 'edgeFlange' }, { stack: [{ cmd: 'sketchedBend' }, { cmd: 'hem' }] }], + [{ cmd: 'flatten' }, { cmd: 'exportFlatDxf' }], + [{ cmd: 'extrudeCut' }, { cmd: 'sheetMetalParameters' }], + ], +}; + +/** Design tree rows of a sheet metal part: its parameters and the flat pattern. */ +export function sheetMetalTreeRows(app: App): { key: string; item: null; label: string; icon: string; depth: number; action: () => void }[] { + const o = sheetOwner(app); + if (!o) return []; + return [ + { key: 'sheetMetal', item: null, label: 'Sheet-Metal', icon: 'sheetMetal', depth: 1, action: () => app.editFeature(o.id) }, + { key: 'flatPattern', item: null, label: 'Flat-Pattern', icon: 'flatPattern', depth: 1, action: () => app.commands.run('flatten') }, + ]; +} + diff --git a/src/parametric/src/app/shell.ts b/src/parametric/src/app/shell.ts index e7b88c022f..8d978a4d56 100644 --- a/src/parametric/src/app/shell.ts +++ b/src/parametric/src/app/shell.ts @@ -196,7 +196,17 @@ export function buildShell(cmds: CommandRegistry, menus: { label: string; items: cmTools.scrollLeft += e.deltaMode === 1 ? e.deltaY * 16 : e.deltaY; }, { passive: false }); const cmTabs = h('div', { class: 'cm-tabs', role: 'tablist', 'aria-label': 'Command groups' }); - const cm = h('section', { class: 'cm', 'aria-label': 'CommandManager' }, ribbonScroller(cmTools), cmTabs); + // On a phone not every tab fits: fade the edge that has more tabs past it. + const tabEdges = () => { + const max = cmTabs.scrollWidth - cmTabs.clientWidth; + cmTabs.classList.toggle('more-start', max > 1 && cmTabs.scrollLeft > 1); + cmTabs.classList.toggle('more-end', max > 1 && cmTabs.scrollLeft < max - 1); + }; + cmTabs.addEventListener('scroll', tabEdges, { passive: true }); + if (typeof ResizeObserver !== 'undefined') new ResizeObserver(tabEdges).observe(cmTabs); + // Tabs shown or hidden (the drawing's, an assembly's) change what is past the edge too. + if (typeof MutationObserver !== 'undefined') new MutationObserver(tabEdges).observe(cmTabs, { subtree: true, childList: true, attributeFilter: ['hidden'] }); + const cm =h('section', { class: 'cm', 'aria-label': 'CommandManager' }, ribbonScroller(cmTools), cmTabs); const lpTabs = h('div', { class: 'lp-tabs' }); const lpBody = h('div', { class: 'lp-body', id: 'left-panel', role: 'tabpanel' }); @@ -284,6 +294,7 @@ function ribbonScroller(tools: HTMLElement): HTMLElement { /** Renders one CommandManager tab's tools. */ export function renderRibbon(target: HTMLElement, tab: RibbonTab, cmds: CommandRegistry) { target.textContent = ''; + target.dataset.tab = tab.id; tab.groups.forEach((group, i) => { const name = tab.labels?.[i]; const g = h('div', { class: 'cm-group', role: 'group', ...(name ? { 'aria-label': name, 'data-group': name.toLowerCase() } : {}) }); diff --git a/src/parametric/src/app/surface-display.ts b/src/parametric/src/app/surface-display.ts new file mode 100644 index 0000000000..56829e1986 --- /dev/null +++ b/src/parametric/src/app/surface-display.ts @@ -0,0 +1,73 @@ +// How surface bodies are shown: tinted apart from the solid, and hidden with +// the feature that made them. Their faces and edges come after the solid's in +// the build result, so a part without surfaces is checked in constant time. + +import { bodyFeatureOf, makesSurfaceBody } from '../model/surfaces'; +import type { Feature, Id } from '../model/types'; +import { STATE_HIDDEN } from '../render/renderer'; +import type { MenuItem } from '../ui/menu'; +import type { App } from './app'; + +/** Colour of surface bodies: the part's colour shifted towards a warm tan, so sheets read apart from the solid. */ +function surfaceTint(app: App): [number, number, number] { + const base = app.renderer.modelColor ?? app.renderer.theme.model; + const warm = [0.96, 0.74, 0.36]; + return base.map((c, i) => c * 0.55 + warm[i] * 0.45) as [number, number, number]; +} + +/** Colours the faces of surface bodies (they come after the solid's in the face list). */ +export function applySurfaceColors(app: App) { + const faces = app.faces; + if (!faces.length || !faces[faces.length - 1].body) return; + const rgba = new Uint8Array(faces.length * 4); + const c = surfaceTint(app).map((v) => Math.round(Math.max(0, Math.min(1, v)) * 255)); + faces.forEach((f, i) => { if (f.body) rgba.set([c[0], c[1], c[2], 255], i * 4); }); + app.renderer.setFaceColors(rgba); +} + +/** Features whose surface bodies are hidden (none for a part without surfaces, checked in constant time). */ +export function hiddenSurfaceFeatures(app: App): Id[] { + const fl = app.faces; + if (!fl.length || !fl[fl.length - 1].body) return []; + return app.store.doc.features.filter((f) => f.hidden && makesSurfaceBody(f)).map((f) => f.id); +} + +/** Hides the faces and edges of surface bodies whose feature is hidden. */ +export function markHiddenSurfaces(app: App, faces: Uint8Array, edges: Uint8Array) { + const fl = app.faces, el = app.edges; + if (!fl.length || !fl[fl.length - 1].body) return; + const hidden = new Set(); + for (const f of app.store.doc.features) if (f.hidden && makesSurfaceBody(f)) hidden.add(f.id); + if (!hidden.size) return; + fl.forEach((f, i) => { if (f.body && hidden.has(bodyFeatureOf(f.body)) && i < faces.length) faces[i] |= STATE_HIDDEN; }); + el.forEach((e, i) => { if (e.body && hidden.has(bodyFeatureOf(e.body)) && i < edges.length) edges[i] |= STATE_HIDDEN; }); +} + +/** Whether a feature can be hidden and shown from the design tree (a sketch, plane or surface). */ +export function hideable(f: Feature | undefined): boolean { + return !!f && (f.type === 'sketch' || f.type === 'plane' || makesSurfaceBody(f)); +} + + +/** + * The Hide item of a surface feature whose body a later feature replaced + * (a Trim, Extend or Knit made it into its own body): hiding the feature + * itself showed no change. It hides the feature the body is now, or says + * that no body shows the surface (thickened, or knit into the solid). + * Null when the plain Hide item does what it says. + */ +export function surfaceHideItem(app: App, f: Feature): MenuItem | null { + if (!makesSurfaceBody(f) || f.hidden) return null; + // Not built yet (below the rollback bar): hiding it takes effect when it is. + if (app.store.indexOf(f.id) >= app.buildLimit()) return null; + const owners = new Set(); + for (const x of app.faces) { + if (!x.body) continue; + const owner = bodyFeatureOf(x.body); + if (owner === f.id) return null; + if (x.feature === f.id) owners.add(owner); + } + const later = [...owners].map((id) => app.store.feature(id)).filter((x): x is Feature => !!x && makesSurfaceBody(x)); + if (later.length === 1) return { label: `Hide ${later[0].name}`, icon: 'eyeOff', run: () => app.toggleHidden([later[0].id], true) }; + return { label: 'Hide (a later feature used this surface)', icon: 'eyeOff', disabled: true }; +} diff --git a/src/parametric/src/app/surface-panels.ts b/src/parametric/src/app/surface-panels.ts new file mode 100644 index 0000000000..3e64c6dd19 --- /dev/null +++ b/src/parametric/src/app/surface-panels.ts @@ -0,0 +1,534 @@ +// Surface modeling in the interface: the commands of the Surfaces tab, their +// PropertyManager panels, and how surface bodies are shown (tinted, hidden +// with their feature). + +import type { Vec3 } from '../math/vec'; +import { consumedSketches, defaultName, nextName } from '../model/features'; +import { + SURFACE_LABELS, bodyFeatureOf, newSurfaceFeature, type SurfaceFeature, type SurfaceFeatureType, +} from '../model/surfaces'; +import type { + AxisRef, DeleteFaceFeature, EdgeRef, FaceRef, Id, PlaneRef, SurfaceCutFeature, SurfaceExtendFeature, + SurfaceExtrudeFeature, SurfaceFillFeature, SurfaceKnitFeature, SurfaceLoftFeature, SurfaceOffsetFeature, SurfacePlanarFeature, + SurfaceRevolveFeature, SurfaceSweepFeature, SurfaceTrimFeature, ThickenFeature, TrimTool, +} from '../model/types'; +import { formatLength } from '../model/units'; +import { h } from '../ui/dom'; +import type { App } from './app'; +import type { Command } from './commands'; +import { + FeaturePanel, axisItem, axisLabel, edgeItem, faceItem, isSketch, planeItem, planeLabel, toAxis, toEdge, toFace, toFeature, toPlane, +} from './panels'; +import { PropertyPanel, SelectionBox, type SelBoxItem, checkbox, flipButton, numberField, section, segmented, selectField } from './pm'; +import { type SelItem, edgeRef, faceRef } from './selection'; + +// ---------- picks ---------- + +/** The feature name of a surface body ("Surface-Loft1"). */ +function bodyName(app: App, body: Id): string { + return app.store.feature(bodyFeatureOf(body))?.name ?? 'surface'; +} + +/** A face of a surface body as a pick naming the body. */ +const toSurfaceFace = (app: App) => (it: SelItem): SelBoxItem | null => { + if (it.kind !== 'face') return null; + const f = app.faces[it.index]; + if (!f?.body) return null; + return { item: it, data: faceRef(f), label: bodyName(app, f.body) }; +}; + +/** A face of the solid. */ +const toSolidFace = (app: App) => (it: SelItem): SelBoxItem | null => { + if (it.kind !== 'face') return null; + const f = app.faces[it.index]; + if (!f || f.body) return null; + return toFace(app)(it); +}; + +/** An edge on the boundary of a surface body. */ +const toSurfaceEdge = (app: App) => (it: SelItem): SelBoxItem | null => { + if (it.kind !== 'edge') return null; + const e = app.edges[it.index]; + if (!e?.body || e.faces.length !== 1) return null; + return { item: it, data: edgeRef(e), label: `Edge <${it.index + 1}> of ${bodyName(app, e.body)}` }; +}; + +/** One pick per surface body: a second face of a body already listed toggles it off. */ +function bodyBox(panel: PropertyPanel, app: App, label: string, refs: FaceRef[], onChange: (refs: FaceRef[]) => void, opts: { single?: boolean; placeholder?: string; icon?: string } = {}): SelectionBox { + const bodyOf = (r: FaceRef) => app.faces.find((f) => f.name === r.name)?.body ?? null; + let box: SelectionBox; + const convert = (it: SelItem): SelBoxItem | null => { + const x = toSurfaceFace(app)(it); + if (!x) return null; + // Another face of a body that is listed stands for the same body. + const body = app.faces[(it as { index: number }).index]?.body; + const listed = box.items.find((i) => bodyOf(i.data as FaceRef) === body); + return listed ?? x; + }; + box = new SelectionBox(panel, label, { face: true }, convert, (items) => onChange(items.map((i) => i.data as FaceRef)), { placeholder: 'Select a surface in the graphics area', ...opts }); + box.setItems(refs.map((r) => ({ item: faceItem(app, r), data: r, label: bodyName(app, bodyOf(r) ?? r.name.split(':')[0]) }))); + return box; +} + +const surfaceFaceLabel = (app: App, r: FaceRef) => { + const f = app.faces.find((x) => x.name === r.name); + return f?.body ? bodyName(app, f.body) : 'Face'; +}; + +// ---------- panels ---------- + +abstract class SurfacePanel extends FeaturePanel {} + +export class SurfaceExtrudePanel extends SurfacePanel { + render(): HTMLElement[] { + const f = this.f; + const ctx = this.ctx(); + const sketch = this.sketchBox('Profile sketch', () => f.sketch || null, (id) => { f.sketch = id ?? ''; }); + const dir2 = f.dir2 ?? { depth: f.depth }; + const dir2sec = section('Direction 2', [ + numberField({ label: 'Depth', icon: 'ruler', value: dir2.depth, kind: 'length', ctx, min: 1e-6, onChange: (v) => { dir2.depth = v; if (f.dir2) this.changed(); } }), + ], { collapsed: !f.dir2, checkbox: { checked: !!f.dir2, onChange: (v) => { f.dir2 = v ? dir2 : null; this.changed(); } } }); + dir2sec.hidden = f.end === 'midPlane'; + return [ + section('Profile', [sketch.el, h('p', { class: 'field-label' }, 'Open or closed curves; each becomes a face.')]), + section('Direction 1', [ + h('div', { class: 'row' }, flipButton('Reverse direction', f.flip, (v) => { f.flip = v; this.changed(); }), h('div', { class: 'grow' }, + selectField('End condition', f.end, [{ value: 'blind' as const, label: 'Blind' }, { value: 'midPlane' as const, label: 'Mid Plane' }], (v) => { + f.end = v; + dir2sec.hidden = v === 'midPlane'; + this.changed(); + }))), + numberField({ label: 'Depth', icon: 'ruler', value: f.depth, kind: 'length', ctx, min: 1e-6, onChange: (v) => { f.depth = v; this.changed(); } }), + ]), + dir2sec, + ]; + } + + protected validate() { + return this.f.sketch ? null : 'Select a sketch to extrude'; + } + + preview() { + return this.f.sketch ? this.f : null; + } +} + +export class SurfaceRevolvePanel extends SurfacePanel { + render(): HTMLElement[] { + const f = this.f; + const sketch = this.sketchBox('Profile sketch', () => f.sketch || null, (id) => { f.sketch = id ?? ''; }); + const axis = new SelectionBox(this, 'Axis of revolution', { edge: true, face: true }, toAxis(this.app), (items) => { f.axis = (items[0]?.data as AxisRef) ?? null; this.changed(); }, { single: true, placeholder: 'Uses the sketch centerline (or pick an edge)', icon: 'axis' }); + if (f.axis) axis.setItems([{ item: axisItem(this.app, f.axis), data: f.axis, label: axisLabel(this.app, f.axis) }]); + return [ + section('Profile', [sketch.el]), + section('Axis', [axis.el]), + section('Direction 1', [ + h('div', { class: 'row' }, flipButton('Reverse direction', f.flip, (v) => { f.flip = v; this.changed(); }), h('div', { class: 'grow' }, + selectField('Type', f.end, [{ value: 'blind' as const, label: 'Blind' }, { value: 'midPlane' as const, label: 'Mid Plane' }], (v) => { f.end = v; this.changed(); }))), + numberField({ label: 'Angle', icon: 'revolve', value: f.angle, kind: 'angle', ctx: this.ctx(), min: 1e-6, max: 360, onChange: (v) => { f.angle = v; this.changed(); } }), + ]), + ]; + } + + protected validate() { + return this.f.sketch ? null : 'Select a sketch to revolve'; + } + + preview() { + return this.f.sketch ? this.f : null; + } +} + +export class SurfaceSweepPanel extends SurfacePanel { + render(): HTMLElement[] { + const f = this.f; + const profile = this.sketchBox('Profile', () => f.profile, (id) => { f.profile = id; }); + const path = new SelectionBox(this, 'Path', { feature: true }, toFeature(this.app, isSketch), (items) => { f.path = (items[0]?.data as Id) ?? null; this.changed(); }, { single: true, placeholder: 'Select the path sketch', icon: 'sweep' }); + if (f.path) path.setItems([{ item: { kind: 'feature', id: f.path }, data: f.path, label: this.app.store.feature(f.path)?.name ?? '' }]); + return [section('Profile and Path', [profile.el, path.el, h('p', { class: 'field-label' }, 'The profile may be an open curve.')])]; + } + + protected validate() { + return this.f.profile && this.f.path ? null : 'Select a profile and a path'; + } + + preview() { + return this.f.profile && this.f.path ? this.f : null; + } +} + +export class SurfaceLoftPanel extends SurfacePanel { + render(): HTMLElement[] { + const f = this.f; + const box = new SelectionBox(this, 'Profiles', { feature: true }, toFeature(this.app, isSketch), (items) => { f.profiles = items.map((i) => i.data as Id); this.changed(); }, { placeholder: 'Select two or more sketches in order', icon: 'surfaceLoft' }); + box.setItems(f.profiles.map((id) => ({ item: { kind: 'feature', id }, data: id, label: this.app.store.feature(id)?.name ?? id }))); + return [section('Profiles', [box.el, h('p', { class: 'field-label' }, 'Open or closed curves, one chain per sketch.'), checkbox('Ruled (straight) sections', f.ruled, (v) => { f.ruled = v; this.changed(); })])]; + } + + protected validate() { + return this.f.profiles.length >= 2 ? null : 'Select at least two profile sketches'; + } + + preview() { + return this.f.profiles.length >= 2 ? this.f : null; + } +} + +export class SurfacePlanarPanel extends SurfacePanel { + render(): HTMLElement[] { + const f = this.f; + const app = this.app; + // A sketch, or edges (of the solid or of surfaces) closing a loop: either kind replaces the other. + const convert = (it: SelItem): SelBoxItem | null => toFeature(app, isSketch)(it.kind === 'face' ? { kind: 'feature', id: '' } : it) ?? toEdge(app)(it); + const box = new SelectionBox(this, 'Bounding entities', { feature: true, edge: true }, convert, (items) => { + const sk = items.filter((i) => typeof i.data === 'string'); + const last = items[items.length - 1]; + if (sk.length && last && typeof last.data === 'string') { + f.sketch = last.data as Id; + f.edges = []; + if (items.length > 1) box.setItems([last]); + } else { + f.sketch = null; + f.edges = items.filter((i) => typeof i.data !== 'string').map((i) => i.data as EdgeRef); + if (sk.length) box.setItems(items.filter((i) => typeof i.data !== 'string')); + } + this.changed(); + }, { placeholder: 'Select a sketch, or edges forming a closed loop', icon: 'surfacePlanar' }); + if (f.sketch) box.setItems([{ item: { kind: 'feature', id: f.sketch }, data: f.sketch, label: app.store.feature(f.sketch)?.name ?? f.sketch }]); + else box.setItems(f.edges.map((e) => ({ item: edgeItem(app, e), data: e, label: e.sig.type ? `Edge (${e.sig.type})` : 'Edge' }))); + return [section('Bounding Entities', [box.el])]; + } + + protected validate() { + return this.f.sketch || this.f.edges.length ? null : 'Select a sketch or a closed loop of edges'; + } + + preview() { + return this.f.sketch || this.f.edges.length ? this.f : null; + } +} + +export class SurfaceOffsetPanel extends SurfacePanel { + render(): HTMLElement[] { + const f = this.f; + const app = this.app; + const box = new SelectionBox(this, 'Faces to offset', { face: true }, (it) => toSurfaceFace(app)(it) ?? toFace(app)(it), (items) => { f.faces = items.map((i) => i.data as FaceRef); this.changed(); }, { placeholder: 'Select faces of the part or of surfaces', icon: 'surfaceOffset' }); + box.setItems(f.faces.map((r) => ({ item: faceItem(app, r), data: r, label: surfaceFaceLabel(app, r) }))); + return [section('Offset Parameters', [ + box.el, + h('div', { class: 'row' }, flipButton('Flip offset direction', f.flip, (v) => { f.flip = v; this.changed(); }), h('div', { class: 'grow' }, + numberField({ label: 'Offset distance', icon: 'ruler', value: f.distance, kind: 'length', ctx: this.ctx(), min: 0, onChange: (v) => { f.distance = v; this.changed(); } }))), + h('p', { class: 'field-label' }, 'A distance of 0 copies the faces.'), + ])]; + } + + protected validate() { + return this.f.faces.length ? null : 'Select faces to offset'; + } + + preview() { + return this.f.faces.length ? this.f : null; + } +} + +export class SurfaceFillPanel extends SurfacePanel { + render(): HTMLElement[] { + const f = this.f; + const box = new SelectionBox(this, 'Patch boundary', { edge: true }, toEdge(this.app), (items) => { f.edges = items.map((i) => i.data as EdgeRef); this.changed(); }, { placeholder: 'Select the edges around the opening', icon: 'surfaceFill' }); + box.setItems(f.edges.map((e) => ({ item: edgeItem(this.app, e), data: e, label: e.sig.type ? `Edge (${e.sig.type})` : 'Edge' }))); + return [section('Patch Boundary', [box.el])]; + } + + protected validate() { + return this.f.edges.length ? null : 'Select the edges around the opening'; + } + + preview() { + return this.f.edges.length ? this.f : null; + } +} + +export class SurfaceTrimPanel extends SurfacePanel { + render(): HTMLElement[] { + const f = this.f; + const app = this.app; + const toTool = (it: SelItem): SelBoxItem | null => { + const s = toSurfaceFace(app)(it); + if (s) return { ...s, data: { kind: 'surface', face: s.data as FaceRef } as TrimTool }; + const sk = toFeature(app, isSketch)(it); + if (sk) return { ...sk, data: { kind: 'sketch', sketch: sk.data as Id } as TrimTool }; + const p = toPlane(app)(it); + if (p) return { ...p, data: { kind: 'plane', plane: p.data as PlaneRef } as TrimTool }; + return null; + }; + const tool = new SelectionBox(this, 'Trim tool', { face: true, plane: true, feature: true, sketch: true }, toTool, (items) => { f.tool = (items[0]?.data as TrimTool) ?? null; this.changed(); }, { single: true, placeholder: 'Select a plane, a sketch or a surface', icon: 'surfaceTrim' }); + if (f.tool) tool.setItems([{ item: f.tool.kind === 'surface' ? faceItem(app, f.tool.face) : f.tool.kind === 'plane' ? planeItem(app, f.tool.plane) : { kind: 'feature', id: f.tool.sketch }, data: f.tool, label: this.toolLabel(f.tool) }]); + const targets = bodyBox(this, app, 'Surfaces to trim', f.faces, (refs) => { f.faces = refs; this.changed(); }, { icon: 'surfaceExtrude' }); + const flip = checkbox('Keep the other side', f.flip, (v) => { f.flip = v; this.changed(); }); + flip.hidden = f.keep.length > 0; + const keep = new SelectionBox(this, 'Pieces to keep', { face: true }, (it) => { + const s = toSurfaceFace(app)(it); + if (!s) return null; + const p: Vec3 = app.lastPickPoint ?? app.faces[(it as { index: number }).index].center; + return { item: null, data: p, label: `Piece of ${s.label} at ${this.at(p)}` }; + }, (items) => { f.keep = items.map((i) => i.data as Vec3); flip.hidden = f.keep.length > 0; this.changed(); }, { placeholder: 'Optional: click the pieces to keep', icon: 'select' }); + keep.setItems(f.keep.map((p) => ({ item: null, data: p, label: `Piece at ${this.at(p)}` }))); + return [ + section('Trim Tool', [tool.el]), + section('Surfaces', [targets.el]), + section('Keep', [keep.el, flip, h('p', { class: 'field-label' }, 'Without picked pieces, the side the tool’s normal points to is kept.')]), + ]; + } + + /** A picked point in the part's units ("1.25, 0.5, 0 in"). */ + private at(p: Vec3): string { + const doc = this.app.store.doc; + return p.map((x, i) => formatLength(x, doc.units, doc.decimals, i === 2)).join(', '); + } + + private toolLabel(t: TrimTool): string { + if (t.kind === 'sketch') return this.app.store.feature(t.sketch)?.name ?? 'Sketch'; + if (t.kind === 'plane') return planeLabel(this.app, t.plane); + return surfaceFaceLabel(this.app, t.face); + } + + protected validate() { + if (!this.f.tool) return 'Select a trim tool'; + return this.f.faces.length ? null : 'Select the surfaces to trim'; + } + + preview() { + return this.f.tool && this.f.faces.length ? this.f : null; + } +} + +export class SurfaceExtendPanel extends SurfacePanel { + render(): HTMLElement[] { + const f = this.f; + const box = new SelectionBox(this, 'Edges to extend', { edge: true }, toSurfaceEdge(this.app), (items) => { f.edges = items.map((i) => i.data as EdgeRef); this.changed(); }, { placeholder: 'Select boundary edges of a surface', icon: 'surfaceExtend' }); + box.setItems(f.edges.map((e) => ({ item: edgeItem(this.app, e), data: e, label: e.sig.type ? `Edge (${e.sig.type})` : 'Edge' }))); + return [ + section('Edges to Extend', [box.el]), + section('End Condition', [ + numberField({ label: 'Distance', icon: 'ruler', value: f.distance, kind: 'length', ctx: this.ctx(), min: 1e-6, onChange: (v) => { f.distance = v; this.changed(); } }), + ]), + section('Extension Type', [segmented('Extension type', f.mode, [{ value: 'same' as const, label: 'Same surface' }, { value: 'linear' as const, label: 'Linear' }], (v) => { f.mode = v; this.changed(); })]), + ]; + } + + protected validate() { + return this.f.edges.length ? null : 'Select edges to extend'; + } + + preview() { + return this.f.edges.length ? this.f : null; + } +} + +export class SurfaceKnitPanel extends SurfacePanel { + render(): HTMLElement[] { + const f = this.f; + const box = bodyBox(this, this.app, 'Surfaces to knit', f.faces, (refs) => { f.faces = refs; this.changed(); }, { icon: 'surfaceKnit' }); + return [section('Selections', [ + box.el, + checkbox('Create solid', f.solid, (v) => { f.solid = v; this.changed(); }), + h('p', { class: 'field-label' }, 'A solid is made when the surfaces close a volume; it is added to the part.'), + numberField({ label: 'Knit tolerance', icon: 'ruler', value: f.tolerance, kind: 'length', ctx: this.ctx(), min: 1e-7, onChange: (v) => { f.tolerance = v; this.changed(); } }), + ])]; + } + + protected validate() { + return this.f.faces.length ? null : 'Select the surfaces to knit'; + } + + preview() { + return this.f.faces.length ? this.f : null; + } +} + +export class ThickenPanel extends SurfacePanel { + get title() { + return this.editingId ? this.f.name : this.f.cut ? 'Thickened Cut' : 'Thicken'; + } + + render(): HTMLElement[] { + const f = this.f; + const box = bodyBox(this, this.app, 'Surface to thicken', f.faces, (refs) => { f.faces = refs; this.changed(); }, { single: true, icon: 'thicken' }); + return [section('Thicken Parameters', [ + box.el, + segmented('Thicken side', f.side, [{ value: 'front' as const, label: 'Side 1' }, { value: 'back' as const, label: 'Side 2' }, { value: 'both' as const, label: 'Both' }], (v) => { f.side = v; this.changed(); }), + numberField({ label: 'Thickness', icon: 'ruler', value: f.thickness, kind: 'length', ctx: this.ctx(), min: 1e-6, onChange: (v) => { f.thickness = v; this.changed(); } }), + h('p', { class: 'field-label' }, f.cut ? 'The thickened surface is cut from the part.' : 'The thickened surface is added to the part.'), + ])]; + } + + protected validate() { + return this.f.faces.length ? null : 'Select a surface to thicken'; + } + + preview() { + return this.f.faces.length ? this.f : null; + } +} + +export class SurfaceCutPanel extends SurfacePanel { + render(): HTMLElement[] { + const f = this.f; + const box = bodyBox(this, this.app, 'Cutting surface', f.face ? [f.face] : [], (refs) => { f.face = refs[0] ?? null; this.changed(); }, { single: true, icon: 'surfaceCut' }); + return [section('Surface Cut Parameters', [ + box.el, + h('div', { class: 'row' }, flipButton('Flip side to cut', f.flip, (v) => { f.flip = v; this.changed(); }), h('span', { class: 'field-label' }, 'Flip side to cut')), + h('p', { class: 'field-label' }, 'Material on the side the surface’s normal points to is removed.'), + ])]; + } + + protected validate() { + return this.f.face ? null : 'Select the surface to cut with'; + } + + preview() { + return this.f.face ? this.f : null; + } +} + +export class DeleteFacePanel extends SurfacePanel { + render(): HTMLElement[] { + const f = this.f; + const box = new SelectionBox(this, 'Faces to delete', { face: true }, toSolidFace(this.app), (items) => { f.faces = items.map((i) => i.data as FaceRef); this.changed(); }, { placeholder: 'Select faces of the solid', icon: 'deleteFace' }); + box.setItems(f.faces.map((r) => ({ item: faceItem(this.app, r), data: r, label: 'Face' }))); + return [section('Selections', [ + box.el, + selectField('Options', f.mode, [{ value: 'delete' as const, label: 'Delete (the solid becomes a surface)' }, { value: 'patch' as const, label: 'Delete and Patch' }], (v) => { f.mode = v; this.changed(); }), + ])]; + } + + protected validate() { + return this.f.faces.length ? null : 'Select faces to delete'; + } + + preview() { + return this.f.faces.length ? this.f : null; + } +} + +export function surfacePanelFor(app: App, f: SurfaceFeature, editing: boolean): PropertyPanel { + switch (f.type) { + case 'surfaceExtrude': return new SurfaceExtrudePanel(app, f, editing); + case 'surfaceRevolve': return new SurfaceRevolvePanel(app, f, editing); + case 'surfaceSweep': return new SurfaceSweepPanel(app, f, editing); + case 'surfaceLoft': return new SurfaceLoftPanel(app, f, editing); + case 'surfacePlanar': return new SurfacePlanarPanel(app, f, editing); + case 'surfaceOffset': return new SurfaceOffsetPanel(app, f, editing); + case 'surfaceFill': return new SurfaceFillPanel(app, f, editing); + case 'surfaceTrim': return new SurfaceTrimPanel(app, f, editing); + case 'surfaceExtend': return new SurfaceExtendPanel(app, f, editing); + case 'surfaceKnit': return new SurfaceKnitPanel(app, f, editing); + case 'thicken': return new ThickenPanel(app, f, editing); + case 'surfaceCut': return new SurfaceCutPanel(app, f, editing); + case 'deleteFace': return new DeleteFacePanel(app, f, editing); + } +} + +// ---------- starting a feature ---------- + +/** The selected sketch, or the last sketch built that no feature uses yet. */ +function profileSketch(app: App): Id | null { + for (const it of app.selection.items) if (it.kind === 'feature' && app.store.feature(it.id)?.type === 'sketch') return it.id; + const doc = app.store.doc; + const used = new Set(doc.features.flatMap((f) => consumedSketches(f))); + const built = doc.features.slice(0, app.store.builtCount); + for (let i = built.length - 1; i >= 0; i--) if (built[i].type === 'sketch' && !used.has(built[i].id)) return built[i].id; + return null; +} + +/** A new surface feature, filled in from the selection, in its panel. */ +export function startSurfaceFeature(app: App, type: SurfaceFeatureType, opts: { cut?: boolean } = {}): PropertyPanel { + const doc = app.store.doc; + const id = app.store.nextId('f'); + const name = type === 'thicken' && opts.cut ? nextName(doc, 'Thicken-Cut') : defaultName(doc, type); + const f = newSurfaceFeature(type, id, name, app.typicalSize()); + const sel = app.selection.items; + const faces = sel.flatMap((it) => (it.kind === 'face' && app.faces[it.index] ? [app.faces[it.index]] : [])); + const surfaceFaces = faces.filter((x) => x.body); + const solidFaces = faces.filter((x) => !x.body); + const edges = app.selection.ofKind('edge').map((s) => app.edges[s.index]).filter(Boolean).map(edgeRef); + const sketches = sel.filter((it) => it.kind === 'feature' && app.store.feature(it.id)?.type === 'sketch').map((it) => (it as { id: Id }).id); + // One face per surface body. + const perBody = surfaceFaces.filter((x, i) => surfaceFaces.findIndex((y) => y.body === x.body) === i).map(faceRef); + switch (f.type) { + case 'surfaceExtrude': case 'surfaceRevolve': f.sketch = profileSketch(app) ?? ''; break; + case 'surfacePlanar': if (edges.length) f.edges = edges; else f.sketch = profileSketch(app); break; + case 'surfaceLoft': f.profiles = sketches; break; + case 'surfaceSweep': if (sketches.length) { f.profile = sketches[0]; f.path = sketches[1] ?? null; } break; + case 'surfaceOffset': f.faces = faces.map(faceRef); break; + case 'surfaceFill': f.edges = edges; break; + case 'surfaceExtend': f.edges = app.selection.ofKind('edge').map((s) => app.edges[s.index]).filter((e) => e?.body && e.faces.length === 1).map(edgeRef); break; + case 'surfaceTrim': f.faces = perBody; break; + case 'surfaceKnit': f.faces = perBody; break; + case 'thicken': f.faces = perBody.slice(0, 1); f.cut = !!opts.cut; break; + case 'surfaceCut': f.face = perBody[0] ?? null; break; + case 'deleteFace': f.faces = solidFaces.map(faceRef); break; + } + const flat = ['front', 'back', 'left', 'right', 'top', 'bottom']; + if (['surfaceExtrude', 'surfaceRevolve', 'surfaceLoft', 'surfaceSweep'].includes(type) && flat.includes(app.renderer.camera.viewName() ?? '')) app.viewport.setView('trimetric'); + return surfacePanelFor(app, f, false); +} + +// ---------- commands ---------- + +const DESCRIPTIONS: Record = { + surfaceExtrude: 'Extrude open or closed sketch curves into a surface.', + surfaceRevolve: 'Revolve sketch curves around an axis into a surface.', + surfaceSweep: 'Sweep an open or closed profile along a path into a surface.', + surfaceLoft: 'Blend a surface through two or more open or closed profiles.', + surfacePlanar: 'Fill a closed sketch profile or a closed loop of edges with a flat surface.', + surfaceOffset: 'Offset faces of the part or of surfaces into a new surface. A distance of 0 copies them.', + surfaceFill: 'Patch an opening bounded by a closed loop of edges.', + surfaceTrim: 'Trim surfaces with a plane, a sketch or another surface.', + surfaceExtend: 'Extend a surface past its boundary edges.', + surfaceKnit: 'Join surfaces along their edges into one, or into a solid when they close a volume.', + thicken: 'Give a surface thickness, adding it to the part.', + surfaceCut: 'Cut the part with a surface, removing the material on one side of it.', + deleteFace: 'Delete faces of the solid, leaving a surface body, or delete and patch them.', +}; + +const KEYWORDS: Partial> = { + surfaceExtrude: 'surface extrude sheet', + surfaceRevolve: 'surface revolve sheet', + surfaceSweep: 'surface sweep sheet', + surfaceLoft: 'surface loft blend boundary', + surfacePlanar: 'surface planar plane fill flat', + surfaceOffset: 'surface offset copy', + surfaceFill: 'surface fill patch boundary', + surfaceTrim: 'surface trim split cut', + surfaceExtend: 'surface extend', + surfaceKnit: 'surface knit sew stitch solid', + thicken: 'surface thicken solid', + surfaceCut: 'surface cut split body replace', + deleteFace: 'surface delete face remove patch', +}; + +/** The Surfaces tab's commands. */ +export function surfaceCommands(app: App): Command[] { + const start = (type: SurfaceFeatureType, cut = false) => () => { + if (app.sketchEditor) { + // Finish the sketch first; it becomes the profile. + const id = app.sketchEditor.sketchId; + app.exitSketch(true); + app.selection.set([{ kind: 'feature', id }]); + } + void app.openPanel(startSurfaceFeature(app, type, { cut })); + }; + const types = Object.keys(SURFACE_LABELS) as SurfaceFeatureType[]; + return [ + ...types.map((type): Command => ({ + id: type, label: SURFACE_LABELS[type], icon: type, description: DESCRIPTIONS[type], keywords: KEYWORDS[type], + enabled: () => !['surfaceCut', 'deleteFace'].includes(type) || !!app.bbox, + run: start(type), + })), + { + id: 'thickenCut', label: 'Thickened Cut', icon: 'thickenCut', description: 'Give a surface thickness and cut it from the part.', keywords: 'surface thicken cut remove', + enabled: () => !!app.bbox, run: start('thicken', true), + }, + ]; +} diff --git a/src/parametric/src/app/tree.ts b/src/parametric/src/app/tree.ts index 4023b5c065..ffcc11ef6a 100644 --- a/src/parametric/src/app/tree.ts +++ b/src/parametric/src/app/tree.ts @@ -10,6 +10,7 @@ import { h, titleWhenClipped } from '../ui/dom'; import { icon } from '../ui/icons'; import type { App } from './app'; import type { SelItem } from './selection'; +import { sheetMetalTreeRows } from './sheetmetal-panels'; interface Row { key: string; @@ -63,12 +64,17 @@ export class FeatureTree { const doc = app.store.doc; const rows: Row[] = []; rows.push({ key: 'part', item: null, label: doc.name, icon: 'part', depth: 0 }); + // Weldments: the cut list, with the number of members built. + if (doc.features.some((f) => f.type === 'structuralMember')) { + rows.push({ key: 'cutlist', item: null, label: `Cut list (${app.weldments.length})`, icon: 'cutList', depth: 1, action: () => app.commands.run('cutList') }); + } rows.push({ key: 'material', item: null, label: doc.material ? doc.material.name : 'Material', muted: doc.material ? '' : ' ', icon: 'material', depth: 1, action: () => app.commands.run('material'), }); for (const k of ['front', 'top', 'right'] as BasePlane[]) rows.push({ key: `plane:${k}`, item: { kind: 'plane', ref: { kind: 'base', plane: k } }, label: BASE_PLANE_NAMES[k], icon: 'plane', depth: 1 }); rows.push({ key: 'origin', item: { kind: 'origin' }, label: 'Origin', icon: 'origin', depth: 1 }); + rows.push(...sheetMetalTreeRows(app)); const consumedBy = new Map(); for (const f of doc.features) for (const s of consumedSketches(f)) if (!consumedBy.has(s)) consumedBy.set(s, f.id); for (const f of doc.features) { @@ -157,6 +163,8 @@ export class FeatureTree { // The part and Material rows have menus too (Shift+F10 on them did nothing). else if (r.key === 'part') app.openCommandMenu(['properties', 'rename', 'equations', 'appearance'], e.clientX, e.clientY, 'Part menu'); else if (r.key === 'material') app.openCommandMenu(['material'], e.clientX, e.clientY, 'Material menu'); + else if (r.key === 'cutlist') app.openCommandMenu(['cutList', 'cutListCsv'], e.clientX, e.clientY, 'Cut list menu'); + else if (r.key === 'sheetMetal' || r.key === 'flatPattern') app.openCommandMenu(['sheetMetalParameters', 'flatten', 'exportFlatDxf'], e.clientX, e.clientY, 'Sheet metal menu'); }); el.addEventListener('pointerenter', () => { if (r.item) sel.setHover(r.item); }); el.addEventListener('pointerleave', () => { if (r.item) sel.setHover(null); }); @@ -394,6 +402,9 @@ export class FeatureTree { if (this.app.store.feature(key)) this.app.editFeature(key); // As a click on Material or a double click on the part does. else if (key === 'material') this.app.commands.run('material'); + else if (key === 'cutlist') this.app.commands.run('cutList'); + else if (key === 'sheetMetal') this.app.commands.run('sheetMetalParameters'); + else if (key === 'flatPattern') this.app.commands.run('flatten'); else if (key === 'part') this.app.commands.run('properties'); break; case ' ': diff --git a/src/parametric/src/app/viewport.ts b/src/parametric/src/app/viewport.ts index 039af28e46..a21b3898ba 100644 --- a/src/parametric/src/app/viewport.ts +++ b/src/parametric/src/app/viewport.ts @@ -15,6 +15,7 @@ import { formatShortcut, h, isMac } from '../ui/dom'; import type { App } from './app'; import type { PickFilter } from './pm'; import type { SelItem } from './selection'; +import { markHiddenSurfaces } from './surface-display'; export interface VPEvent { x: number; @@ -557,6 +558,11 @@ export class Viewport { // A face that may not be picked still hides the planes behind it. const hitDist = hit?.point ? dot(sub(hit.point, ray.o), ray.d) : Infinity; if (hit && hit.kind === 'face' && f.planarOnly && this.app.faces[hit.index]?.type !== 'plane') hit = null; + // Sketch lines run inside the members built on them: they come first. + if (f.sketchSegment) { + const seg = this.pickSketchSegment(x, y); + if (seg) return seg; + } // Origin and axes first: tiny targets. if (f.plane && (this.showOrigin || this.app.inSketch)) { const o = this.camera.project([0, 0, 0]); @@ -607,6 +613,7 @@ export class Viewport { for (const it of app.selection.items) mark(it, STATE_SELECTED); mark(app.selection.hover, STATE_HOVER); for (const it of app.extraHighlights()) mark(it, STATE_SELECTED); + markHiddenSurfaces(app, faces, edges); this.renderer.setStates(faces, edges); this.drawVertices(); this.drawReferenceGeometry(hoverOnly); @@ -689,7 +696,7 @@ export class Viewport { /** The hovered feature, the only hover that changes how sketches are drawn. */ private sketchHoverKey(): Id | null { const h = this.app.selection.hover; - return h?.kind === 'feature' ? h.id : null; + return h?.kind === 'feature' ? h.id : h?.kind === 'skseg' ? `${h.sketch}/${h.entity}` : null; } private drawnSketchHover: Id | null = null; @@ -728,6 +735,45 @@ export class Viewport { } } + /** Sketches whose lines and arcs can be picked: the visible ones, and all of them while a panel picks segments. */ + private segmentSketches(): { f: SketchFeature; fr: Frame }[] { + const app = this.app; + const all = !!app.pickFilter().sketchSegment; + const consumed = new Set(); + for (const f of app.store.doc.features) consumedSketches(f).forEach((s) => consumed.add(s)); + const out: { f: SketchFeature; fr: Frame }[] = []; + for (const f of app.store.doc.features.slice(0, app.buildLimit())) { + if (f.type !== 'sketch' || f.suppressed || app.featureStatus(f.id)?.suppressed || app.sketchEditor?.sketchId === f.id) continue; + const shown = f.hidden === false || (f.hidden === undefined && !consumed.has(f.id)); + if (!all && !shown) continue; + const fr = app.frameOfSketch(f); + if (fr) out.push({ f, fr }); + } + return out; + } + + /** The sketch line or arc under the cursor (within a few pixels). */ + pickSketchSegment(x: number, y: number): SelItem | null { + const cam = this.camera; + const tol = Math.max(cam.pixelSize * 0.5, 1e-4); + let best: SelItem | null = null, bestD = 7; + for (const { f, fr } of this.segmentSketches()) { + const ix = new SketchIndex(this.app.builtEntities(f)); + for (const e of ix.entities) { + if (e.t !== 'line' && e.t !== 'arc') continue; + const pts = tessellate(ix, e, tol).map((p) => cam.project(toWorld(fr, p))); + for (let i = 0; i + 1 < pts.length; i++) { + const [ax, ay] = pts[i], [bx, by] = pts[i + 1]; + const dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy; + const t = l2 > 0 ? Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / l2)) : 0; + const d = Math.hypot(ax + t * dx - x, ay + t * dy - y); + if (d < bestD) { bestD = d; best = { kind: 'skseg', sketch: f.id, entity: e.id }; } + } + } + } + return best; + } + /** Visible sketches other than the one being edited. */ drawSketches() { const app = this.app; @@ -745,6 +791,24 @@ export class Viewport { const rgba = (c: number[]) => [...c.map((v) => Math.round(v * 255)), 255]; const inactive = rgba(cssColor('--sketch-inactive')); const highlight = rgba(this.renderer.theme.selection); + // Segments picked for a panel (weldment members) and the one under the cursor. + const segs = [...app.extraHighlights(), ...(sel.hover ? [sel.hover] : [])].filter((x): x is Extract => x.kind === 'skseg'); + const picking = !!app.pickFilter().sketchSegment; + if (segs.length || picking) { + for (const { f, fr } of this.segmentSketches()) { + const ix = new SketchIndex(app.builtEntities(f)); + const tol = Math.max(this.camera.pixelSize * 0.5, 1e-4); + for (const e of ix.entities) { + if (e.t !== 'line' && e.t !== 'arc') continue; + const on = segs.some((s) => s.sketch === f.id && s.entity === e.id); + // While picking, every sketch shows (hidden layout sketches too); picked segments in the selection colour. + if (!on && !picking) continue; + const c = on ? highlight : inactive; + const poly = tessellate(ix, e, tol); + for (let i = 0; i + 1 < poly.length; i++) { pos.push(...toWorld(fr, poly[i]), ...toWorld(fr, poly[i + 1])); col.push(c[0], c[1], c[2], 255); } + } + } + } if (this.showSketches) { for (const f of built) { if (f.type !== 'sketch' || f.suppressed || app.featureStatus(f.id)?.suppressed) continue; diff --git a/src/parametric/src/app/weldment-panels.ts b/src/parametric/src/app/weldment-panels.ts new file mode 100644 index 0000000000..97e541deff --- /dev/null +++ b/src/parametric/src/app/weldment-panels.ts @@ -0,0 +1,596 @@ +// Weldments: the Weldments tab's commands, the PropertyManager panels of +// Structural Member, Trim/Extend, End Cap and Gusset, and the cut list. + +import type { + CornerTreatment, EdgeRef, EndCapFeature, FaceRef, Feature, GussetFeature, MemberRef, SegmentRef, SketchFeature, StructuralMemberFeature, + TrimExtendFeature, WeldBeadFeature, +} from '../model/types'; +import { defaultName } from '../model/features'; +import { MATERIALS } from '../model/materials'; +import { PIERCE_POINTS, WELD_STANDARDS, WELD_TYPES, profileSizes, type WeldProfileType, type WeldStandard } from '../model/weldment-profiles'; +import { + type CutList, cutListCsv, cutListRows, memberKey, memberOfFace, newEndCap, newGusset, newStructuralMember, newTrimExtend, newWeldBead, + sameMember, weldmentCutList, +} from '../model/weldments'; +import { download, safeName } from '../platform/files'; +import { h } from '../ui/dom'; +import { icon } from '../ui/icons'; +import { showDialog, toast } from '../ui/overlay'; +import type { App } from './app'; +import type { Command } from './commands'; +import { FeaturePanel } from './panels'; +import { type PropertyPanel, SelectionBox, type SelBoxItem, checkbox, numberField, section, segmented, selectField } from './pm'; +import { type SelItem, edgeRef, faceRef } from './selection'; +import type { RibbonTab } from './shell'; + +// ---------- labels and picks ---------- + +/** "Line 3 of Sketch1": lines and arcs numbered in their sketch's drawing order. */ +function segmentLabel(app: App, s: SegmentRef): string { + const sk = app.store.feature(s.sketch); + if (sk?.type !== 'sketch') return 'Missing segment'; + const e = sk.entities.find((x) => x.id === s.entity); + if (!e || (e.t !== 'line' && e.t !== 'arc')) return `Missing segment of ${sk.name}`; + const n = sk.entities.filter((x) => x.t === e.t).indexOf(e) + 1; + return `${e.t === 'arc' ? 'Arc' : 'Line'} ${n} of ${sk.name}`; +} + +/** The lines and arcs of a sketch (member paths). */ +function sketchSegments(sk: SketchFeature): SegmentRef[] { + return sk.entities.filter((e) => e.t === 'line' || e.t === 'arc').map((e) => ({ sketch: sk.id, entity: e.id })); +} + +function memberLabel(app: App, r: MemberRef): string { + const f = app.store.feature(r.feature); + const [sketch, entity] = r.member.split('/'); + return `${f?.name ?? 'Member'}: ${segmentLabel(app, { sketch, entity })}`; +} + +/** A member in a selection box, its faces highlighted in the graphics area. */ +function memberItem(app: App, m: MemberRef): SelBoxItem { + return { + item: null, data: m, label: memberLabel(app, m), + highlights: () => app.faces.flatMap((f, index) => { + const r = memberOfFace(f.name); + return r && sameMember(r, m) ? [{ kind: 'face' as const, index, name: f.name }] : []; + }), + }; +} + +/** A face of a structural member, as the member. */ +const toMember = (app: App) => (it: SelItem): SelBoxItem | null => { + if (it.kind !== 'face') return null; + const f = app.faces[it.index]; + const m = f ? memberOfFace(f.name) : null; + return m ? memberItem(app, m) : null; +}; + +/** A planar face, labelled with the feature (and member) it belongs to. */ +const toPlanarFace = (app: App, membersOnly = false) => (it: SelItem): SelBoxItem | null => { + if (it.kind !== 'face') return null; + const f = app.faces[it.index]; + if (!f || f.type !== 'plane') return null; + const m = memberOfFace(f.name); + if (membersOnly && !m) return null; + const owner = app.store.feature(f.feature); + return { item: it, data: faceRef(f), label: m ? `Face of ${memberLabel(app, m)}` : `Face <${it.index + 1}>${owner ? ` of ${owner.name}` : ''}` }; +}; + +function faceItems(app: App, refs: FaceRef[]): SelBoxItem[] { + return refs.map((r) => { + const m = memberOfFace(r.name); + return { item: { kind: 'face', index: app.faces.findIndex((f) => f.name === r.name), name: r.name }, data: r, label: m ? `Face of ${memberLabel(app, m)}` : 'Face' }; + }); +} + +/** Default profile for the part's units: inch parts get ANSI sizes. */ +function defaultProfile(app: App): Pick { + return app.store.doc.units === 'IPS' ? { standard: 'ansi', profile: 'squareTube', size: '2x2x1/8' } : { standard: 'iso', profile: 'squareTube', size: '40x40x3' }; +} + +// ---------- structural member ---------- + +export class StructuralMemberPanel extends FeaturePanel { + private groupBoxes: SelectionBox[] = []; + private groupsEl: HTMLElement = h('div'); + + constructor(app: App, f: StructuralMemberFeature, editing: boolean) { + super(app, f, editing); + this.helpText = 'Select sketch lines and arcs for each group. Members of a group meet at the corner treatment; later groups are trimmed to earlier ones.'; + } + + render(): HTMLElement[] { + const f = this.f; + const ctx = this.ctx(); + if (!f.groups.length) f.groups.push({ segments: [] }); + // Standard, type and size: the size list follows the other two. + const sizeWrap = h('div'); + const fillSizes = () => { + const sizes = profileSizes(f.standard as WeldStandard, f.profile as WeldProfileType); + if (!sizes.some((s) => s.id === f.size)) f.size = sizes[Math.min(sizes.length - 1, Math.floor(sizes.length / 3))]?.id ?? ''; + sizeWrap.replaceChildren(selectField('Size', f.size, sizes.map((s) => ({ value: s.id, label: s.label })), (v) => { f.size = v; this.changed(); })); + }; + fillSizes(); + const profile = section('Selections', [ + selectField('Standard', f.standard as WeldStandard, WELD_STANDARDS, (v) => { f.standard = v; fillSizes(); this.changed(); }), + selectField('Type', f.profile as WeldProfileType, WELD_TYPES, (v) => { f.profile = v; fillSizes(); this.changed(); }), + sizeWrap, + ], { icon: 'structuralMember' }); + this.groupBoxes = []; + this.groupsEl = h('div', { class: 'weld-groups' }); + f.groups.forEach((_, i) => this.groupsEl.append(this.groupEl(i))); + const newGroup = h('button', { class: 'btn small', type: 'button' }, icon('plus', 14), 'New Group'); + newGroup.addEventListener('click', () => { + f.groups.push({ segments: [] }); + this.groupsEl.append(this.groupEl(f.groups.length - 1)); + this.activate(this.groupBoxes[this.groupBoxes.length - 1]); + this.changed(); + }); + const gap = numberField({ label: 'Gap', icon: 'ruler', value: f.gap, kind: 'length', ctx, min: 0, onChange: (v) => { f.gap = v; this.changed(); } }); + const gap2 = numberField({ label: 'Gap between groups', icon: 'ruler', value: f.gap2, kind: 'length', ctx, min: 0, onChange: (v) => { f.gap2 = v; this.changed(); } }); + gap2.hidden = !f.trimGroups; + const corners: { value: CornerTreatment; label: string }[] = [ + { value: 'miter', label: 'End miter' }, { value: 'butt1', label: 'End butt 1' }, { value: 'butt2', label: 'End butt 2' }, + ]; + return [ + profile, + section('Groups', [this.groupsEl, h('div', { class: 'row' }, newGroup)]), + section('Corner Treatment', [ + segmented('Corner treatment', f.corner, corners, (v) => { f.corner = v; this.changed(); }), + h('p', { class: 'field-label' }, 'At corners within a group. End butt 1: the arriving member runs through; End butt 2: the next one does.'), + gap, + checkbox('Trim and extend members between groups', f.trimGroups, (v) => { f.trimGroups = v; gap2.hidden = !v; this.changed(); }), + gap2, + ]), + section('Profile Placement', [ + numberField({ label: 'Rotation angle', icon: 'reset', value: f.rotation, kind: 'angle', ctx, onChange: (v) => { f.rotation = v; this.changed(); } }), + checkbox('Mirror profile', f.mirror, (v) => { f.mirror = v; this.changed(); }), + selectField('Pierce point', f.pierce as (typeof PIERCE_POINTS)[number]['value'], PIERCE_POINTS, (v) => { f.pierce = v; this.changed(); }), + ]), + ]; + } + + private groupEl(i: number): HTMLElement { + const f = this.f; + const box = new SelectionBox(this, `Group ${i + 1}`, { sketchSegment: true, feature: true, sketch: true }, (it) => this.toSegment(it), (items) => { + f.groups[this.groupBoxes.indexOf(box)].segments = items.map((x) => x.data as SegmentRef); + this.changed(); + }, { placeholder: 'Select sketch lines and arcs', icon: 'line' }); + box.setItems(f.groups[i].segments.map((s) => ({ item: { kind: 'skseg', sketch: s.sketch, entity: s.entity }, data: s, label: segmentLabel(this.app, s) }))); + this.groupBoxes.push(box); + const remove = h('button', { class: 'icon-btn weld-group-rm', type: 'button', 'aria-label': `Remove group ${i + 1}` }, icon('trash', 14)); + // In the group's heading, beside its name. + box.el.firstElementChild?.append(remove); + const wrap = h('div', { class: 'weld-group' }, box.el); + remove.addEventListener('click', () => { + const k = this.groupBoxes.indexOf(box); + if (f.groups.length === 1) { box.setItems([], true); return; } + f.groups.splice(k, 1); + this.groupBoxes.splice(k, 1); + this.boxes.splice(this.boxes.indexOf(box), 1); + wrap.remove(); + // The other groups are numbered again. + this.groupBoxes.forEach((b, j) => { + const label = b.el.querySelector('.field-label'); + if (label) label.textContent = `Group ${j + 1}`; + b.el.querySelector('.weld-group-rm')?.setAttribute('aria-label', `Remove group ${j + 1}`); + b.el.querySelector('.selbox')?.setAttribute('aria-label', `Group ${j + 1}`); + }); + if (this.activeBox === box) this.activate(this.groupBoxes[Math.max(0, k - 1)]); + this.changed(); + }); + return wrap; + } + + private toSegment(it: SelItem): SelBoxItem | null { + if (it.kind !== 'skseg') return null; + const s: SegmentRef = { sketch: it.sketch, entity: it.entity }; + // A segment belongs to one group: picked for another, it moves there. + this.takeFromOtherGroups([s]); + return { item: it, data: s, label: segmentLabel(this.app, s) }; + } + + private takeFromOtherGroups(segs: SegmentRef[], keep = this.activeBox) { + const keys = new Set(segs.map(memberKey)); + for (const b of this.groupBoxes) { + if (b === keep) continue; + const left = b.items.filter((x) => !keys.has(memberKey(x.data as SegmentRef))); + if (left.length !== b.items.length) b.setItems(left, true); + } + } + + onPick(item: SelItem, additive: boolean): boolean { + // A sketch picked in the tree adds all its lines and arcs to the active group. + if (item.kind === 'feature' && this.activeBox && this.groupBoxes.includes(this.activeBox)) { + const sk = this.app.store.feature(item.id); + if (sk?.type !== 'sketch') return false; + const box = this.activeBox; + const have = new Set(box.items.map((x) => memberKey(x.data as SegmentRef))); + const add = sketchSegments(sk).filter((s) => !have.has(memberKey(s))); + if (!add.length) return true; + this.takeFromOtherGroups(add, box); + box.setItems([...box.items, ...add.map((s) => ({ item: { kind: 'skseg', sketch: s.sketch, entity: s.entity } as SelItem, data: s, label: segmentLabel(this.app, s) }))], true); + return true; + } + return super.onPick(item, additive); + } + + protected validate() { + return this.f.groups.some((g) => g.segments.length) ? null : 'Select sketch lines or arcs for the members'; + } + + preview() { + return this.f.groups.some((g) => g.segments.length) ? this.f : null; + } + + ok(): boolean { + const doc = this.app.store.doc; + const steel = MATERIALS.find((m) => m.name === 'Plain Carbon Steel'); + // The first member of a part without a material makes it steel (one undo step with the member). + if (this.editingId || doc.material || !steel || doc.features.some((x) => x.type === 'structuralMember') || this.validate()) return super.ok(); + const f = this.f; + this.app.store.change(`Add ${f.name}`, (d) => { + const at = d.rollback == null ? d.features.length : d.rollback; + d.features.splice(at, 0, f); + if (d.rollback != null) d.rollback = at + 1; + d.material = { ...steel }; + }); + toast({ kind: 'info', message: `Material set to ${steel.name} for the weldment. Change it with Edit Material.`, timeout: 4000 }); + return true; + } +} + +// ---------- trim / extend ---------- + +export class TrimExtendPanel extends FeaturePanel { + render(): HTMLElement[] { + const f = this.f; + const ctx = this.ctx(); + const members = new SelectionBox(this, 'Bodies to be trimmed', { face: true }, toMember(this.app), (items) => { + f.members = dedupe(items.map((x) => x.data as MemberRef)); + this.changed(); + }, { placeholder: 'Select faces of the members to trim', icon: 'structuralMember' }); + members.setItems(f.members.map((m) => memberItem(this.app, m))); + const faces = new SelectionBox(this, 'Face/Plane', { face: true, planarOnly: true }, toPlanarFace(this.app), (items) => { f.faces = items.map((x) => x.data as FaceRef); this.changed(); }, { placeholder: 'Select a planar face to trim to', icon: 'plane' }); + faces.setItems(faceItems(this.app, f.faces)); + const bounds = new SelectionBox(this, 'Bodies', { face: true }, toMember(this.app), (items) => { + f.boundaryMembers = dedupe(items.map((x) => x.data as MemberRef)); + this.changed(); + }, { placeholder: 'Select faces of the members to trim to', icon: 'structuralMember' }); + bounds.setItems(f.boundaryMembers.map((m) => memberItem(this.app, m))); + const coped = checkbox('Coped cut (follow the boundary member)', f.coped, (v) => { f.coped = v; this.changed(); }); + const sync = () => { + faces.el.hidden = f.boundary !== 'faces'; + bounds.el.hidden = f.boundary !== 'members'; + coped.hidden = f.boundary !== 'members'; + }; + sync(); + return [ + section('Bodies to Be Trimmed', [members.el]), + section('Trimming Boundary', [ + segmented('Trimming boundary', f.boundary, [{ value: 'faces' as const, label: 'Face/Plane' }, { value: 'members' as const, label: 'Bodies' }], (v) => { + f.boundary = v; + sync(); + this.activate(v === 'faces' ? faces : bounds); + this.changed(); + }), + faces.el, bounds.el, + checkbox('Allow extension', f.allowExtension, (v) => { f.allowExtension = v; this.changed(); }), + coped, + numberField({ label: 'Gap', icon: 'ruler', value: f.gap, kind: 'length', ctx, min: 0, onChange: (v) => { f.gap = v; this.changed(); } }), + ]), + ]; + } + + protected validate() { + if (!this.f.members.length) return 'Select the members to trim or extend'; + return (this.f.boundary === 'faces' ? this.f.faces.length : this.f.boundaryMembers.length) ? null : 'Select the boundary to trim to'; + } + + preview() { + return this.validate() ? null : this.f; + } +} + +function dedupe(refs: MemberRef[]): MemberRef[] { + return refs.filter((r, i) => refs.findIndex((x) => sameMember(x, r)) === i); +} + +// ---------- end cap ---------- + +export class EndCapPanel extends FeaturePanel { + render(): HTMLElement[] { + const f = this.f; + const ctx = this.ctx(); + const faces = new SelectionBox(this, 'Faces', { face: true, planarOnly: true }, toPlanarFace(this.app, true), (items) => { f.faces = items.map((x) => x.data as FaceRef); this.changed(); }, { placeholder: 'Select end faces of tubes or pipes', icon: 'endCap' }); + faces.setItems(faceItems(this.app, f.faces)); + return [ + section('Parameters', [ + faces.el, + segmented('Thickness direction', f.inward ? 'inward' : 'outward', [{ value: 'outward' as const, label: 'Outward' }, { value: 'inward' as const, label: 'Inward' }], (v) => { f.inward = v === 'inward'; this.changed(); }), + numberField({ label: 'Thickness', icon: 'ruler', value: f.thickness, kind: 'length', ctx, min: 1e-6, onChange: (v) => { f.thickness = v; this.changed(); } }), + numberField({ label: 'Offset', icon: 'offset', value: f.offset, kind: 'length', ctx, min: 0, onChange: (v) => { f.offset = v; this.changed(); } }), + h('p', { class: 'field-label' }, 'Offset sets the cap\'s edge in from the edge of the tube (inward caps start inside the wall).'), + ]), + ]; + } + + protected validate() { + return this.f.faces.length ? null : 'Select end faces of tube or pipe members'; + } + + preview() { + return this.f.faces.length ? this.f : null; + } +} + +// ---------- gusset ---------- + +export class GussetPanel extends FeaturePanel { + render(): HTMLElement[] { + const f = this.f; + const ctx = this.ctx(); + const faces = new SelectionBox(this, 'Supporting faces', { face: true, planarOnly: true }, toPlanarFace(this.app), (items) => { + f.faces = items.map((x) => x.data as FaceRef).slice(-2); + if (items.length > 2) faces.setItems(items.slice(-2)); + this.changed(); + }, { placeholder: 'Select two planar faces at a corner', icon: 'gusset' }); + faces.setItems(faceItems(this.app, f.faces)); + const d3 = numberField({ label: 'Distance 3', icon: 'ruler', value: f.d3, kind: 'length', ctx, min: 1e-6, onChange: (v) => { f.d3 = v; this.changed(); } }); + d3.hidden = f.shape !== 'polygonal'; + return [ + section('Supporting Faces', [faces.el]), + section('Profile', [ + segmented('Profile', f.shape, [{ value: 'triangular' as const, label: 'Triangular' }, { value: 'polygonal' as const, label: 'Polygonal' }], (v) => { f.shape = v; d3.hidden = v !== 'polygonal'; this.changed(); }), + numberField({ label: 'Distance 1', icon: 'ruler', value: f.d1, kind: 'length', ctx, min: 1e-6, onChange: (v) => { f.d1 = v; this.changed(); } }), + numberField({ label: 'Distance 2', icon: 'ruler', value: f.d2, kind: 'length', ctx, min: 1e-6, onChange: (v) => { f.d2 = v; this.changed(); } }), + d3, + numberField({ label: 'Thickness', icon: 'ruler', value: f.thickness, kind: 'length', ctx, min: 1e-6, onChange: (v) => { f.thickness = v; this.changed(); } }), + selectField('Location', f.location, [{ value: 'center' as const, label: 'Centered' }, { value: 'side1' as const, label: 'Side 1' }, { value: 'side2' as const, label: 'Side 2' }], (v) => { f.location = v; this.changed(); }), + numberField({ label: 'Chamfer distance', icon: 'chamfer', value: f.chamfer, kind: 'length', ctx, min: 0, onChange: (v) => { f.chamfer = v; this.changed(); } }), + ]), + ]; + } + + protected validate() { + return this.f.faces.length === 2 ? null : 'Select two planar faces that meet at a corner'; + } + + preview() { + return this.f.faces.length === 2 ? this.f : null; + } +} + +// ---------- fillet bead ---------- + +export class WeldBeadPanel extends FeaturePanel { + render(): HTMLElement[] { + const f = this.f; + const edges = new SelectionBox(this, 'Edges', { edge: true }, (it) => { + if (it.kind !== 'edge') return null; + const e = this.app.edges[it.index]; + if (!e || e.type !== 'line') return null; + return { item: it, data: edgeRef(e), label: `Edge <${it.index + 1}>` }; + }, (items) => { f.edges = items.map((x) => x.data as EdgeRef); this.changed(); }, { placeholder: 'Select straight inside corner edges', icon: 'weldBead' }); + edges.setItems(f.edges.map((r) => ({ item: { kind: 'edge', index: this.app.edges.findIndex((e) => e.name === r.name), name: r.name }, data: r, label: 'Edge (line)' }))); + return [section('Settings', [ + edges.el, + numberField({ label: 'Bead size', icon: 'ruler', value: f.size, kind: 'length', ctx: this.ctx(), min: 1e-6, onChange: (v) => { f.size = v; this.changed(); } }), + h('p', { class: 'field-label' }, 'A solid fillet weld with equal legs along each edge, where two flat faces meet at an inside corner.'), + ])]; + } + + protected validate() { + return this.f.edges.length ? null : 'Select the inside corner edges to weld'; + } + + preview() { + return this.f.edges.length ? this.f : null; + } +} + +// ---------- factory ---------- + +export function weldmentPanelFor(app: App, f: Feature, editing: boolean): PropertyPanel | null { + switch (f.type) { + case 'structuralMember': return new StructuralMemberPanel(app, f, editing); + case 'trimExtend': return new TrimExtendPanel(app, f, editing); + case 'endCap': return new EndCapPanel(app, f, editing); + case 'gusset': return new GussetPanel(app, f, editing); + case 'weldBead': return new WeldBeadPanel(app, f, editing); + default: return null; + } +} + +/** A new weldment feature's panel, filled from the selection. */ +export function startWeldment(app: App, type: Feature['type']): PropertyPanel | null { + const doc = app.store.doc; + const id = app.store.nextId('f'); + const name = defaultName(doc, type); + const size = app.typicalSize(); + const sel = app.selection.items; + const planar = app.selectedFaceRefs().filter((r) => r.sig.type === 'plane'); + let f: Feature; + switch (type) { + case 'structuralMember': { + // Picked lines and arcs, or every line and arc of the picked sketches, make the first group. + const segs: SegmentRef[] = []; + for (const it of sel) { + if (it.kind === 'skseg') segs.push({ sketch: it.sketch, entity: it.entity }); + else if (it.kind === 'feature') { const sk = app.store.feature(it.id); if (sk?.type === 'sketch') segs.push(...sketchSegments(sk)); } + } + // A line picked as well as its sketch is one member. + const uniq = segs.filter((s, i) => segs.findIndex((x) => memberKey(x) === memberKey(s)) === i); + f = { ...newStructuralMember(id, name, uniq.length ? [uniq] : []), ...defaultProfile(app) }; + break; + } + case 'trimExtend': { + const x = newTrimExtend(id, name); + x.members = dedupe(sel.flatMap((it) => (it.kind === 'face' ? [memberOfFace(app.faces[it.index]?.name ?? '')] : [])).filter((m): m is MemberRef => !!m)); + f = x; + break; + } + case 'endCap': { + const x = newEndCap(id, name, Math.max(size / 50, 1)); + x.faces = planar.filter((r) => memberOfFace(r.name)); + f = x; + break; + } + case 'gusset': { + const x = newGusset(id, name, Math.max(size / 8, 5), Math.max(size / 50, 1)); + x.faces = planar.slice(0, 2); + f = x; + break; + } + case 'weldBead': { + const x = newWeldBead(id, name, Math.max(size / 50, 1)); + x.edges = app.selection.ofKind('edge').map((s) => app.edges[s.index]).filter((e) => e?.type === 'line').map(edgeRef); + f = x; + break; + } + default: return null; + } + return weldmentPanelFor(app, f, false); +} + +// ---------- cut list ---------- + +export function cutListOf(app: App): CutList { + return weldmentCutList(app.store.doc, app.weldments); +} + +/** + * The cut list after the latest rebuild, with each member's mass less what + * later cuts and holes took from it (asked of the kernel only here, when the + * list is opened or exported: never on a rebuild). + */ +export async function exactCutList(app: App): Promise { + await app.whenBuilt(); + let members = app.weldments; + let approximate = false; + try { + const v = await app.kernel.weldVolumes(); + approximate = v.approximate; + const vol = new Map(v.volumes.map((x) => [`${x.feature}|${x.member}`, x.volume])); + if (vol.size) members = members.map((m) => ({ ...m, volume: vol.get(`${m.feature}|${m.member}`) ?? m.volume })); + } catch { + // The kernel restarted: the masses as built, said to be so. + approximate = true; + } + const list = weldmentCutList(app.store.doc, members); + if (approximate) list.massApproximate = true; + return list; +} + +let cutListOpen = false; + +export async function cutListDialog(app: App) { + if (cutListOpen) return; + cutListOpen = true; + try { + const list = await exactCutList(app); + const doc = app.store.doc; + if (!list.items.length) { + // The tree's Cut list row stays while the members fail to build or are rolled back. + const message = doc.features.some((x) => x.type === 'structuralMember') + ? 'No structural members are built: check the Structural Member features for errors, suppression or the rollback position.' + : 'The part has no structural members yet. Add them with Structural Member in the Weldments tab.'; + toast({ kind: 'info', message }); + return; + } + const { header, rows, total } = cutListRows(list, doc.units, doc.decimals); + const numeric = (i: number) => i !== 2; + const table = h('table', { class: 'table weld-cutlist' }, + h('caption', { class: 'sr-only' }, 'Cut list'), + h('thead', {}, h('tr', {}, ...header.map((x, i) => h('th', { scope: 'col', class: numeric(i) ? 'num' : '' }, x)))), + h('tbody', {}, ...rows.map((r) => h('tr', {}, ...r.map((x, i) => h('td', { class: numeric(i) ? 'num' : '' }, x))))), + h('tfoot', {}, h('tr', {}, ...total.map((x, i) => h(i === 2 ? 'th' : 'td', { class: numeric(i) ? 'num' : '', ...(i === 2 ? { scope: 'row' } : {}) }, x)))), + ); + const limit = app.buildLimit(); + const rolledTo = limit < doc.features.length ? doc.features[limit] : null; + const note = (doc.material + ? `Mass from ${doc.material.name} (${doc.material.density} kg/m³), less later cuts and holes.` + : 'No material is set: mass uses 1000 kg/m³. Set one with Edit Material.') + + (list.massApproximate ? ' Later fillets, shells and other changes to the members are not in the mass.' : ''); + const v = await showDialog({ + title: 'Cut List', signal: app.documentSignal, wide: true, + body: [ + h('p', {}, `${list.count} ${list.count === 1 ? 'member' : 'members'} in ${list.items.length} ${list.items.length === 1 ? 'item' : 'items'}. Lengths are overall (long point to long point); angles are the end cuts from square. ${note}`), + ...(rolledTo ? [h('p', { class: 'field-label' }, `The part is rolled back to before ${rolledTo.name}: members from there on are not listed.`)] : []), + h('div', { class: 'weld-cutlist-wrap', tabindex: '0', role: 'region', 'aria-label': 'Cut list table' }, table), + ], + buttons: [{ label: 'Export CSV', value: 'csv', left: true }, { label: 'Close', value: 'close', primary: true }], + onAction: (a) => { + if (a === 'csv') { exportCutList(app, list); return false; } + }, + }); + void v; + } finally { + cutListOpen = false; + } +} + +function exportCutList(app: App, list: CutList) { + const doc = app.store.doc; + // A byte order mark lets spreadsheet programs read the degree signs. + download('' + cutListCsv(list, doc.units, doc.decimals), `${safeName(doc.name)} cut list.csv`, 'text/csv'); +} + +// ---------- commands and ribbon ---------- + +export function weldmentCommands(app: App): Command[] { + const hasMembers = () => app.weldments.length > 0; + const start = (type: Feature['type']) => () => { + if (app.sketchEditor) { + // Finish the sketch first: its lines become member paths. + const id = app.sketchEditor.sketchId; + app.exitSketch(true); + app.selection.set([{ kind: 'feature', id }]); + } + const p = startWeldment(app, type); + if (p) void app.openPanel(p); + }; + return [ + { + id: 'structuralMember', label: 'Structural Member', icon: 'structuralMember', keywords: 'weldment frame tube pipe beam channel angle profile steel', + description: 'Sweep a standard profile (tube, pipe, angle, channel, beam, bar) along sketch lines and arcs.', run: start('structuralMember'), + }, + { + id: 'trimExtend', label: 'Trim / Extend', icon: 'trimExtend', keywords: 'weldment trim extend cope member', + description: 'Trim or extend structural members to a face or to other members.', enabled: hasMembers, run: start('trimExtend'), + }, + { + id: 'endCap', label: 'End Cap', icon: 'endCap', keywords: 'weldment cap plug tube end', + description: 'Close the open end of a tube or pipe member with a plate.', enabled: hasMembers, run: start('endCap'), + }, + { + id: 'gusset', label: 'Gusset', icon: 'gusset', keywords: 'weldment gusset stiffener plate corner bracket', + description: 'Add a triangular or polygonal plate between two faces at a corner.', enabled: () => !!app.bbox, run: start('gusset'), + }, + { + id: 'weldBead', label: 'Fillet Bead', icon: 'weldBead', keywords: 'weldment weld bead fillet weld seam', + description: 'Add a solid fillet weld along inside corner edges.', enabled: () => !!app.bbox, run: start('weldBead'), + }, + { + id: 'cutList', label: 'Cut List', icon: 'cutList', keywords: 'weldment bill of materials bom lengths csv', + description: 'List the structural members by profile, length and end angles, and export it as CSV.', + // With members that fail to build too, so the tree's Cut list row says why it is empty. + enabled: () => hasMembers() || app.store.doc.features.some((x) => x.type === 'structuralMember'), run: () => cutListDialog(app), + }, + { + id: 'cutListCsv', label: 'Export Cut List (CSV)', icon: 'download', keywords: 'weldment csv', enabled: hasMembers, + // After the rebuild of the latest edit, as the dialog does. + run: async () => exportCutList(app, await exactCutList(app)), + }, + ]; +} + +export const WELDMENTS_TAB: RibbonTab = { + id: 'weldments', label: 'Weldments', + groups: [ + [{ cmd: 'structuralMember' }, { cmd: 'trimExtend' }], + [{ stack: [{ cmd: 'endCap' }, { cmd: 'gusset' }, { cmd: 'weldBead' }] }], + [{ cmd: 'cutList' }], + [{ cmd: 'sketch' }], + ], +}; diff --git a/src/parametric/src/assembly/compose.ts b/src/parametric/src/assembly/compose.ts new file mode 100644 index 0000000000..33b4ebb00e --- /dev/null +++ b/src/parametric/src/assembly/compose.ts @@ -0,0 +1,193 @@ +// Combines the meshes of an assembly's components into one model for the +// renderer: every component's part mesh is placed by its transform and its +// faces and edges are numbered after those of the components before it, so +// picking, selection states, display styles and section views work on an +// assembly as they do on a part. A combined face or edge remembers its +// component and its index in the part. + +import type { EdgeInfo, FaceInfo, MeshData } from '../kernel/protocol'; +import type { Frame, Vec3 } from '../math/vec'; +import { qRotate } from '../math/vec'; +import type { AsmComponent, Placement } from '../model/assembly'; +import type { EdgeRef, FaceRef, Id } from '../model/types'; +import { type Geo, applyPlacement } from './solver'; + +/** What the worker built for a part. */ +export interface PartGeometry { + mesh: MeshData | null; + faces: FaceInfo[]; + edges: EdgeInfo[]; + bbox: { min: Vec3; max: Vec3 } | null; + cones: Record; +} + +export interface ComposedModel { + mesh: MeshData | null; + faces: FaceInfo[]; + edges: EdgeInfo[]; + bbox: { min: Vec3; max: Vec3 } | null; + /** RGBA of every combined face (the component's part colour). */ + faceColors: Uint8Array; + /** For each combined face and edge: the component (index into `comps`) and the index in its part. */ + faceComp: Int32Array; + faceLocal: Int32Array; + edgeComp: Int32Array; + edgeLocal: Int32Array; + /** The components in the model, in order (what faceComp indexes). */ + comps: Id[]; +} + +/** Separates a component id from a face or edge name in the combined lists. */ +export const NAME_SEP = '#'; +export const combinedName = (comp: Id, name: string) => `${comp}${NAME_SEP}${name}`; +export function splitName(name: string): { comp: Id; name: string } | null { + const i = name.indexOf(NAME_SEP); + return i > 0 ? { comp: name.slice(0, i), name: name.slice(i + 1) } : null; +} + +/** A placement as a 3×4 row-major matrix (rotation | translation). */ +export function placementMatrix(pl: Placement): number[] { + const x = qRotate(pl.q, [1, 0, 0]), y = qRotate(pl.q, [0, 1, 0]), z = qRotate(pl.q, [0, 0, 1]); + return [x[0], y[0], z[0], pl.p[0], x[1], y[1], z[1], pl.p[1], x[2], y[2], z[2], pl.p[2]]; +} + +export function composeModel(items: { comp: AsmComponent; placement: Placement; geom: PartGeometry; color: [number, number, number] }[]): ComposedModel { + let nv = 0, ni = 0, ne = 0, nvert = 0; + for (const it of items) { + const m = it.geom.mesh; + if (!m) continue; + nv += m.positions.length; ni += m.indices.length; ne += m.edgePositions.length; nvert += m.vertices.length; + } + const faces: FaceInfo[] = []; + const edges: EdgeInfo[] = []; + const faceComp: number[] = [], faceLocal: number[] = [], edgeComp: number[] = [], edgeLocal: number[] = []; + const colors: number[] = []; + if (!nv) { + return { mesh: null, faces, edges, bbox: null, faceColors: new Uint8Array(0), faceComp: new Int32Array(0), faceLocal: new Int32Array(0), edgeComp: new Int32Array(0), edgeLocal: new Int32Array(0), comps: items.map((i) => i.comp.id) }; + } + const positions = new Float32Array(nv), normals = new Float32Array(nv), vertexFace = new Float32Array(nv / 3); + const indices = new Uint32Array(ni), edgePositions = new Float32Array(ne), edgeIds = new Float32Array(ne / 3), vertices = new Float32Array(nvert); + let ov = 0, oi = 0, oe = 0, overt = 0; + const min: Vec3 = [Infinity, Infinity, Infinity], max: Vec3 = [-Infinity, -Infinity, -Infinity]; + items.forEach((it, ci) => { + const { geom, placement: pl } = it; + const faceBase = faces.length, edgeBase = edges.length; + const m = geom.mesh; + const R = rotation(pl); + const t = pl.p; + if (m) { + const vBase = ov / 3; + for (let k = 0; k < m.positions.length; k += 3) { + const x = m.positions[k], y = m.positions[k + 1], z = m.positions[k + 2]; + const px = R[0] * x + R[1] * y + R[2] * z + t[0], py = R[3] * x + R[4] * y + R[5] * z + t[1], pz = R[6] * x + R[7] * y + R[8] * z + t[2]; + positions[ov + k] = px; positions[ov + k + 1] = py; positions[ov + k + 2] = pz; + if (px < min[0]) min[0] = px; if (py < min[1]) min[1] = py; if (pz < min[2]) min[2] = pz; + if (px > max[0]) max[0] = px; if (py > max[1]) max[1] = py; if (pz > max[2]) max[2] = pz; + const nx = m.normals[k], ny = m.normals[k + 1], nz = m.normals[k + 2]; + normals[ov + k] = R[0] * nx + R[1] * ny + R[2] * nz; + normals[ov + k + 1] = R[3] * nx + R[4] * ny + R[5] * nz; + normals[ov + k + 2] = R[6] * nx + R[7] * ny + R[8] * nz; + } + for (let k = 0; k < m.vertexFace.length; k++) vertexFace[ov / 3 + k] = m.vertexFace[k] + faceBase; + for (let k = 0; k < m.indices.length; k++) indices[oi + k] = m.indices[k] + vBase; + for (let k = 0; k < m.edgePositions.length; k += 3) { + const x = m.edgePositions[k], y = m.edgePositions[k + 1], z = m.edgePositions[k + 2]; + edgePositions[oe + k] = R[0] * x + R[1] * y + R[2] * z + t[0]; + edgePositions[oe + k + 1] = R[3] * x + R[4] * y + R[5] * z + t[1]; + edgePositions[oe + k + 2] = R[6] * x + R[7] * y + R[8] * z + t[2]; + } + for (let k = 0; k < m.edgeIds.length; k++) edgeIds[oe / 3 + k] = m.edgeIds[k] + edgeBase; + for (let k = 0; k < m.vertices.length; k += 3) { + const x = m.vertices[k], y = m.vertices[k + 1], z = m.vertices[k + 2]; + vertices[overt + k] = R[0] * x + R[1] * y + R[2] * z + t[0]; + vertices[overt + k + 1] = R[3] * x + R[4] * y + R[5] * z + t[1]; + vertices[overt + k + 2] = R[6] * x + R[7] * y + R[8] * z + t[2]; + } + ov += m.positions.length; oi += m.indices.length; oe += m.edgePositions.length; overt += m.vertices.length; + } + const P = (p: Vec3) => applyPlacement(pl, p); + const D = (d: Vec3) => qRotate(pl.q, d); + const id = it.comp.id; + geom.faces.forEach((f, i) => { + const out: FaceInfo = { ...f, name: combinedName(id, f.name), center: P(f.center), feature: id }; + if (f.normal) out.normal = D(f.normal); + if (f.frame) out.frame = placeFrame(f.frame, pl); + if (f.axis) out.axis = { p: P(f.axis.p), d: D(f.axis.d) }; + faces.push(out); + faceComp.push(ci); faceLocal.push(i); + colors.push(...it.color.map((c) => Math.round(c * 255)), 255); + }); + geom.edges.forEach((e, i) => { + const out: EdgeInfo = { ...e, name: combinedName(id, e.name), a: P(e.a), b: P(e.b), mid: P(e.mid), faces: e.faces.map((x) => x + faceBase) }; + if (e.dir) out.dir = D(e.dir); + if (e.center) out.center = P(e.center); + if (e.axis) out.axis = D(e.axis); + edges.push(out); + edgeComp.push(ci); edgeLocal.push(i); + }); + }); + return { + mesh: { positions, normals, indices, vertexFace, edgePositions, edgeIds, vertices }, + faces, edges, + bbox: min[0] <= max[0] ? { min, max } : null, + faceColors: new Uint8Array(colors), + faceComp: Int32Array.from(faceComp), faceLocal: Int32Array.from(faceLocal), edgeComp: Int32Array.from(edgeComp), edgeLocal: Int32Array.from(edgeLocal), + comps: items.map((i) => i.comp.id), + }; +} + +function rotation(pl: Placement): number[] { + const x = qRotate(pl.q, [1, 0, 0]), y = qRotate(pl.q, [0, 1, 0]), z = qRotate(pl.q, [0, 0, 1]); + return [x[0], y[0], z[0], x[1], y[1], z[1], x[2], y[2], z[2]]; +} + +function placeFrame(f: Frame, pl: Placement): Frame { + return { o: applyPlacement(pl, f.o), x: qRotate(pl.q, f.x), y: qRotate(pl.q, f.y), n: qRotate(pl.q, f.n) }; +} + +// ---------- mate geometry from a part's faces and edges ---------- + +/** The face a reference names in a part's face list (by name, then by signature among same-named pieces). */ +export function findFace(faces: FaceInfo[], ref: FaceRef): number { + const same = faces.map((f, i) => (f.name === ref.name ? i : -1)).filter((i) => i >= 0); + if (same.length <= 1) return same[0] ?? -1; + let best = same[0], bestD = Infinity; + for (const i of same) { + const c = faces[i].center; + const d = Math.hypot(c[0] - ref.sig.c[0], c[1] - ref.sig.c[1], c[2] - ref.sig.c[2]); + if (d < bestD) { bestD = d; best = i; } + } + return best; +} + +export function findEdge(edges: EdgeInfo[], ref: EdgeRef): number { + const same = edges.map((e, i) => (e.name === ref.name ? i : -1)).filter((i) => i >= 0); + if (same.length <= 1) return same[0] ?? -1; + let best = same[0], bestD = Infinity; + for (const i of same) { + const m = edges[i].mid; + const d = Math.hypot(m[0] - ref.sig.m[0], m[1] - ref.sig.m[1], m[2] - ref.sig.m[2]); + if (d < bestD) { bestD = d; best = i; } + } + return best; +} + +/** Mate geometry of a part face (in the part's coordinates), or null for faces mates cannot use. */ +export function faceGeo(geom: PartGeometry, index: number): Geo | null { + const f = geom.faces[index]; + if (!f) return null; + if (f.type === 'plane' && f.normal) return { kind: 'plane', o: f.center, n: f.normal }; + if (f.type === 'cylinder' && f.axis) return { kind: 'axis', p: f.axis.p, d: f.axis.d, r: f.radius ?? 0, surface: 'cylinder' }; + if (f.type === 'sphere' && f.axis) return { kind: 'sphere', c: f.axis.p, r: f.radius ?? 0 }; + const cone = geom.cones[index]; + if (f.type === 'cone' && cone) return { kind: 'axis', p: cone.p, d: cone.d, r: 0, surface: 'cone' }; + return null; +} + +export function edgeGeo(geom: PartGeometry, index: number): Geo | null { + const e = geom.edges[index]; + if (!e) return null; + if (e.type === 'line' && e.dir) return { kind: 'line', p: e.a, d: e.dir }; + if (e.type === 'circle' && e.center && e.axis) return { kind: 'axis', p: e.center, d: e.axis, r: e.radius ?? 0, surface: 'circle' }; + return null; +} diff --git a/src/parametric/src/assembly/solver.ts b/src/parametric/src/assembly/solver.ts new file mode 100644 index 0000000000..cc4e84990f --- /dev/null +++ b/src/parametric/src/assembly/solver.ts @@ -0,0 +1,749 @@ +// Rigid-body mate solver for assemblies. +// +// Every floating component has six degrees of freedom: a translation and a +// rotation about its own centre. Mates are equations between the faces, +// edges and axes of two components (or an assembly plane) placed in the +// assembly; each is a short vector of residuals that is zero when the mate +// holds. The solver runs damped least squares (Levenberg-Marquardt) with +// Tikhonov damping, so a component that the mates leave free stays where it +// is (minimum-norm steps), and reports which components are fully defined, +// the degrees of freedom left (from the rank of the Jacobian) and which mates +// conflict (cannot hold together with the mates before them). +// +// Dragging adds soft goals (the grabbed point follows the cursor, or the +// component turns toward an orientation) that the mates override: a lid on a +// hinge pin turns about the pin as its edge is dragged. + +import type { Quat, Vec3 } from '../math/vec'; +import { add, cross, dot, len, normalize, qMul, qNormalize, qRotate, scale, sub } from '../math/vec'; +import type { Id } from '../model/types'; +import type { MateType, Placement } from '../model/assembly'; + +/** Geometry of a mate entity, in the coordinates of its component (or the assembly for ground). */ +export type Geo = + | { kind: 'plane'; o: Vec3; n: Vec3 } + /** Cylinder, cone or circular edge: a point on the axis, its direction and (cylinder, circle) radius. */ + | { kind: 'axis'; p: Vec3; d: Vec3; r: number; surface: 'cylinder' | 'cone' | 'circle' } + | { kind: 'line'; p: Vec3; d: Vec3 } + | { kind: 'point'; p: Vec3 } + | { kind: 'sphere'; c: Vec3; r: number } + /** A whole component (lock mates). */ + | { kind: 'body' }; + +export interface SolverEntity { + /** The component the geometry belongs to; null for the assembly itself (its planes). */ + body: Id | null; + geo: Geo; +} + +export interface SolverMate { + id: Id; + type: MateType; + a: SolverEntity; + b: SolverEntity; + aligned: boolean; + /** Distance in mm, angle in degrees. */ + value: number; + flip: boolean; + /** Lock: b's placement in a's frame. */ + rel?: Placement; +} + +export interface SolverBody { + id: Id; + fixed: boolean; + placement: Placement; + /** The component's centre in its own coordinates: it turns about this point. */ + center?: Vec3; +} + +export type DragGoal = + | { kind: 'move'; body: Id; local: Vec3; target: Vec3 } + | { kind: 'rotate'; body: Id; q: Quat }; + +export interface SolveOptions { + /** Characteristic length (mm) the residuals are measured against: the assembly's size. */ + scale?: number; + maxIter?: number; + drag?: DragGoal | null; + /** Relative resistance of a body to moving (higher moves less). */ + weight?: (id: Id) => number; +} + +export interface SolveResult { + placements: Map; + /** All mates hold. */ + ok: boolean; + /** Largest residual of each mate (normalised), after solving. */ + residuals: Map; + iterations: number; +} + +/** 'error': a mate cannot be formed (its face is gone, or the entities do not fit its type); none conflict. */ +export type DefinitionStatus = 'under' | 'full' | 'over' | 'error'; + +export interface AnalysisResult { + status: DefinitionStatus; + /** Remaining degrees of freedom of the floating components. */ + dof: number; + /** Floating components every degree of freedom of which the mates fix. */ + defined: Set; + /** Mates that cannot hold together with the mates before them. */ + conflicts: Set; + /** Mates whose entities cannot be mated with that mate type. */ + invalid: Map; + placements: Map; +} + +const TOL = 1e-9; +/** How much more a drag resists turning a component than sliding it (see solve). */ +const DRAG_TURN_RESISTANCE = 10; +/** A mate whose residual stays above this (relative to the assembly size) does not hold. */ +export const CONFLICT_TOL = 1e-6; + +// ---------- placements ---------- + +export function applyPlacement(pl: Placement, p: Vec3): Vec3 { + return add(qRotate(pl.q, p), pl.p); +} + +export function rotVecQuat(w: Vec3): Quat { + const a = len(w); + if (a < 1e-12) return qNormalize([w[0] / 2, w[1] / 2, w[2] / 2, 1]); + const s = Math.sin(a / 2) / a; + return [w[0] * s, w[1] * s, w[2] * s, Math.cos(a / 2)]; +} + +const qConj = (q: Quat): Quat => [-q[0], -q[1], -q[2], q[3]]; + +/** Rotation vector (axis times angle) of a quaternion. */ +export function quatRotVec(q: Quat): Vec3 { + const s = q[3] < 0 ? -1 : 1; + const v: Vec3 = [q[0] * s, q[1] * s, q[2] * s]; + const sin = len(v); + if (sin < 1e-12) return scale(v, 2); + const angle = 2 * Math.atan2(sin, q[3] * s); + return scale(v, angle / sin); +} + +/** Placement of b in a's frame. */ +export function relativePlacement(a: Placement, b: Placement): Placement { + const qa = qConj(a.q); + return { p: qRotate(qa, sub(b.p, a.p)), q: qNormalize(qMul(qa, b.q)) }; +} + +export function composePlacement(a: Placement, rel: Placement): Placement { + return { p: add(qRotate(a.q, rel.p), a.p), q: qNormalize(qMul(a.q, rel.q)) }; +} + +/** The geometry placed in the assembly. */ +export function placeGeo(g: Geo, pl: Placement | null): Geo { + if (!pl) return g; + const pt = (p: Vec3) => applyPlacement(pl, p); + const dir = (d: Vec3) => qRotate(pl.q, d); + switch (g.kind) { + case 'plane': return { kind: 'plane', o: pt(g.o), n: dir(g.n) }; + case 'axis': return { ...g, p: pt(g.p), d: dir(g.d) }; + case 'line': return { kind: 'line', p: pt(g.p), d: dir(g.d) }; + case 'point': return { kind: 'point', p: pt(g.p) }; + case 'sphere': return { kind: 'sphere', c: pt(g.c), r: g.r }; + default: return g; + } +} + +// ---------- mate equations ---------- + +const dirOf = (g: Geo): Vec3 | null => (g.kind === 'plane' ? g.n : g.kind === 'axis' || g.kind === 'line' ? g.d : null); +const pointOf = (g: Geo): Vec3 | null => (g.kind === 'plane' ? g.o : g.kind === 'axis' || g.kind === 'line' ? g.p : g.kind === 'point' ? g.p : g.kind === 'sphere' ? g.c : null); +const isAxisLike = (g: Geo) => g.kind === 'axis' || g.kind === 'line'; +const isPointLike = (g: Geo) => g.kind === 'point' || g.kind === 'sphere' || (g.kind === 'axis' && g.surface === 'circle'); +const isCylinder = (g: Geo): g is Extract => g.kind === 'axis' && g.surface !== 'cone'; + +/** + * Why two entities cannot take a mate type, or null when they can. Also + * what the mate panel uses to offer only the types that fit. + */ +export function mateProblem(type: MateType, a: Geo, b: Geo): string | null { + return equations(type, a, b, { aligned: true, value: 1, flip: false, scale: 1 }, null, null) ? null : `${a.kind === 'body' || b.kind === 'body' ? 'Whole components' : `${describeGeo(a)} and ${describeGeo(b)}`} cannot take a ${type} mate`; +} + +export function describeGeo(g: Geo): string { + switch (g.kind) { + case 'plane': return 'a plane'; + case 'axis': return g.surface === 'circle' ? 'a circular edge' : g.surface === 'cone' ? 'a cone' : 'a cylinder'; + case 'line': return 'a straight edge'; + case 'point': return 'a point'; + case 'sphere': return 'a sphere'; + default: return 'a component'; + } +} + +/** The mate types two entities can take, most likely first. */ +export function fittingMates(a: Geo, b: Geo): MateType[] { + const all: MateType[] = ['coincident', 'concentric', 'distance', 'parallel', 'perpendicular', 'angle', 'tangent', 'lock']; + const fit = all.filter((t) => !mateProblem(t, a, b)); + // Two round entities are first of all concentric; a plane and a cylinder tangent. + const first = (isCylinder(a) || a.kind === 'sphere') && (isCylinder(b) || b.kind === 'sphere') ? 'concentric' + : (a.kind === 'plane' && (isCylinder(b) || b.kind === 'sphere')) || (b.kind === 'plane' && (isCylinder(a) || a.kind === 'sphere')) ? 'tangent' : null; + return first && fit.includes(first) ? [first, ...fit.filter((t) => t !== first)] : fit; +} + +interface EqOpts { aligned: boolean; value: number; flip: boolean; scale: number; rel?: Placement } + +/** + * Residuals of a mate between two placed entities (lengths divided by the + * assembly scale), or null when the entities cannot take that mate. + * `pa`, `pb`: the placements of the two components (for lock mates). + */ +function equations(type: MateType, a: Geo, b: Geo, o: EqOpts, pa: Placement | null, pb: Placement | null, swapped = false): number[] | null { + const L = o.scale; + const s = o.flip ? -1 : 1; + const match = (da: Vec3, db: Vec3) => (o.aligned ? sub(da, db) : add(da, db)); + // The same mate with the entities the other way round (once). + const sw = () => (swapped ? null : equations(type, b, a, o, pb, pa, true)); + const div = (v: Vec3): number[] => [v[0] / L, v[1] / L, v[2] / L]; + if (type === 'lock') { + if (a.kind !== 'body' || b.kind !== 'body' || !o.rel) return null; + const A = pa ?? { p: [0, 0, 0], q: [0, 0, 0, 1] }, B = pb ?? { p: [0, 0, 0], q: [0, 0, 0, 1] }; + const rel = relativePlacement(A, B); + const qe = qMul(qConj(o.rel.q), rel.q); + const w = quatRotVec(qe); + return [...div(sub(rel.p, o.rel.p)), w[0], w[1], w[2]]; + } + if (a.kind === 'body' || b.kind === 'body') return null; + switch (type) { + case 'coincident': { + if (a.kind === 'plane' && b.kind === 'plane') return [...match(a.n, b.n), dot(sub(b.o, a.o), a.n) / L]; + if (b.kind === 'plane') return sw(); + if (a.kind === 'plane') { + if (b.kind === 'axis' && b.surface === 'circle') return [...cross(a.n, b.d), dot(sub(b.p, a.o), a.n) / L]; + if (isAxisLike(b)) return [dot(dirOf(b)!, a.n), dot(sub(pointOf(b)!, a.o), a.n) / L]; + return [dot(sub(pointOf(b)!, a.o), a.n) / L]; + } + if (a.kind === 'axis' && a.surface === 'circle' && b.kind === 'axis' && b.surface === 'circle') return [...match(a.d, b.d), ...div(sub(a.p, b.p))]; + if (isAxisLike(a) && isAxisLike(b)) return [...match(dirOf(a)!, dirOf(b)!), ...div(cross(sub(pointOf(b)!, pointOf(a)!), dirOf(a)!))]; + if (isPointLike(a) && isPointLike(b)) return div(sub(pointOf(a)!, pointOf(b)!)); + if (isAxisLike(a)) return div(cross(sub(pointOf(b)!, pointOf(a)!), dirOf(a)!)); + if (isAxisLike(b)) return sw(); + return null; + } + case 'concentric': { + if (a.kind === 'axis' && b.kind === 'axis') return [...match(a.d, b.d), ...div(cross(sub(b.p, a.p), a.d))]; + if (a.kind === 'sphere' && b.kind === 'sphere') return div(sub(a.c, b.c)); + if (a.kind === 'axis' && (b.kind === 'sphere' || b.kind === 'point')) return div(cross(sub(pointOf(b)!, a.p), a.d)); + if (b.kind === 'axis' && (a.kind === 'sphere' || a.kind === 'point')) return sw(); + return null; + } + case 'parallel': { + const da = dirOf(a), db = dirOf(b); + if (!da || !db) return null; + if ((a.kind === 'plane') !== (b.kind === 'plane')) return [dot(da, db)]; + return match(da, db); + } + case 'perpendicular': { + const da = dirOf(a), db = dirOf(b); + if (!da || !db) return null; + if ((a.kind === 'plane') !== (b.kind === 'plane')) return cross(da, db); + return [dot(da, db)]; + } + case 'angle': { + const da = dirOf(a), db = dirOf(b); + if (!da || !db) return null; + const c = Math.cos((o.value * Math.PI) / 180); + const t = o.aligned ? c : -c; + // At 0° or 180° the angle is a parallel condition: written as one so its + // gradient does not vanish where it holds (the DOF count would be wrong). + if (Math.abs(Math.abs(t) - 1) < 1e-12) return t > 0 ? sub(da, db) : add(da, db); + return [dot(da, db) - t]; + } + case 'distance': { + const D = o.value; + if (a.kind === 'plane' && b.kind === 'plane') return [...match(a.n, b.n), (dot(sub(b.o, a.o), a.n) - s * D) / L]; + if (b.kind === 'plane') return sw(); + if (a.kind === 'plane') { + if (isAxisLike(b) && !(b.kind === 'axis' && b.surface === 'circle')) return [dot(dirOf(b)!, a.n), (dot(sub(pointOf(b)!, a.o), a.n) - s * D) / L]; + const p = pointOf(b); + return p ? [(dot(sub(p, a.o), a.n) - s * D) / L] : null; + } + // A zero distance is a coincidence: written as one, as a length's gradient vanishes at zero. + const zero = Math.abs(D) < 1e-12; + if (isPointLike(a) && isPointLike(b)) return zero ? div(sub(pointOf(a)!, pointOf(b)!)) : [(len(sub(pointOf(a)!, pointOf(b)!)) - D) / L]; + if (isAxisLike(a) && isAxisLike(b) && !isPointLike(a) && !isPointLike(b)) { + const off = cross(sub(pointOf(b)!, pointOf(a)!), dirOf(a)!); + return [...match(dirOf(a)!, dirOf(b)!), ...(zero ? div(off) : [(len(off) - D) / L])]; + } + if (isAxisLike(a) && isPointLike(b)) { + const off = cross(sub(pointOf(b)!, pointOf(a)!), dirOf(a)!); + return zero ? div(off) : [(len(off) - D) / L]; + } + if (isAxisLike(b) && isPointLike(a)) return sw(); + return null; + } + case 'tangent': { + if (a.kind === 'plane' && isCylinder(b) && b.surface === 'cylinder') return [dot(b.d, a.n), (dot(sub(b.p, a.o), a.n) - s * b.r) / L]; + if (a.kind === 'plane' && b.kind === 'sphere') return [(dot(sub(b.c, a.o), a.n) - s * b.r) / L]; + if (b.kind === 'plane') return sw(); + if (a.kind === 'axis' && a.surface === 'cylinder' && b.kind === 'axis' && b.surface === 'cylinder') return [...match(a.d, b.d), (len(cross(sub(b.p, a.p), a.d)) - (a.r + b.r)) / L]; + if (a.kind === 'sphere' && b.kind === 'sphere') return [(len(sub(a.c, b.c)) - (a.r + b.r)) / L]; + if (a.kind === 'axis' && a.surface === 'cylinder' && b.kind === 'sphere') return [(len(cross(sub(b.c, a.p), a.d)) - (a.r + b.r)) / L]; + if (b.kind === 'axis' && a.kind === 'sphere') return sw(); + return null; + } + } + return null; +} + +/** + * The alignment, side and value a new mate takes from where its entities + * are now (as other CAD systems do), so adding it moves things least. + */ +export function initialMateSettings(type: MateType, a: Geo, b: Geo): { aligned: boolean; flip: boolean; value: number } { + const da = dirOf(a), db = dirOf(b); + const aligned = da && db ? dot(da, db) >= 0 : true; + let flip = false, value = 0; + if (type === 'distance' || type === 'tangent') { + const plane = a.kind === 'plane' ? a : b.kind === 'plane' ? b : null; + const other = plane === a ? b : a; + const p = pointOf(other); + if (plane && p) { + const d = dot(sub(p, plane.o), plane.n); + flip = d < 0; + value = Math.abs(d); + } else { + const pa = pointOf(a), pb = pointOf(b); + if (pa && pb) value = da && isAxisLike(a) && isAxisLike(b) ? len(cross(sub(pb, pa), normalize(da))) : len(sub(pa, pb)); + } + } + if (type === 'angle' && da && db) { + const c = Math.max(-1, Math.min(1, dot(da, db))); + value = (Math.acos(Math.abs(c)) * 180) / Math.PI; + return { aligned: c >= 0, flip, value }; + } + return { aligned, flip, value }; +} + +// ---------- the solver ---------- + +interface System { + vars: Id[]; + index: Map; + bodies: Map; + centers: Map; +} + +function placementWith(base: Placement, center: Vec3, x: number[], o: number, L: number): Placement { + const w: Vec3 = [x[o + 3], x[o + 4], x[o + 5]]; + const dq = rotVecQuat(w); + // Turn about the component's centre (in the assembly), then move. + const c = applyPlacement(base, center); + const p = add(add(qRotate(dq, sub(base.p, c)), c), [x[o] * L, x[o + 1] * L, x[o + 2] * L]); + return { p, q: qNormalize(qMul(dq, base.q)) }; +} + +export class MateSolver { + constructor(readonly bodies: SolverBody[], readonly mates: SolverMate[]) {} + + /** Placements with all mates (and the drag goal) satisfied as far as possible. */ + solve(opts: SolveOptions = {}, mates = this.mates, start?: Map): SolveResult { + const L = opts.scale && opts.scale > 0 ? opts.scale : 100; + const bodies = new Map(this.bodies.map((b) => [b.id, { ...b, placement: start?.get(b.id) ?? b.placement }])); + const involved = new Set(); + for (const m of mates) for (const e of [m.a, m.b]) if (e.body) involved.add(e.body); + if (opts.drag) involved.add(opts.drag.body); + const vars = [...involved].filter((id) => bodies.has(id) && !bodies.get(id)!.fixed); + const sys: System = { vars, index: new Map(vars.map((id, i) => [id, i])), bodies, centers: new Map(vars.map((id) => [id, bodies.get(id)!.center ?? [0, 0, 0]])) }; + const placements = new Map([...bodies].map(([id, b]) => [id, b.placement])); + const weights = vars.map((id) => Math.sqrt(Math.max(1e-6, opts.weight?.(id) ?? 1))); + const n = vars.length * 6; + const residuals = new Map(); + const evalMates = (pl: Map) => { + residuals.clear(); + let worst = 0; + for (const m of mates) { + const r = this.mateResidual(m, pl, L); + const v = r ? Math.max(0, ...r.map(Math.abs)) : Infinity; + residuals.set(m.id, v); + worst = Math.max(worst, v); + } + return worst; + }; + // A component no mate holds is carried by a move drag without turning, as if picked up. + const drag = opts.drag; + if (drag?.kind === 'move' && sys.index.has(drag.body) && !mates.some((m) => m.a.body === drag.body || m.b.body === drag.body)) { + const pl = placements.get(drag.body)!; + const moved = new Map(placements).set(drag.body, { p: add(pl.p, sub(drag.target, applyPlacement(pl, drag.local))), q: pl.q }); + return this.solve({ ...opts, drag: null }, mates, moved); + } + if (!n) { + const worst = evalMates(placements); + return { placements, ok: worst < CONFLICT_TOL, residuals, iterations: 0 }; + } + // While a move drag pulls, turning costs more than sliding: a component + // its mates let slide follows the cursor without spinning, and one they + // only let turn (a lid on a hinge) still turns. + const varWeights = (withDrag: boolean) => vars.flatMap((_, i) => [0, 1, 2, 3, 4, 5].map((j) => weights[i] * (withDrag && drag?.kind === 'move' && j >= 3 ? DRAG_TURN_RESISTANCE : 1))); + let x = new Array(n).fill(0); + const at = (xv: number[]): Map => { + const out = new Map(placements); + vars.forEach((id, i) => out.set(id, placementWith(bodies.get(id)!.placement, sys.centers.get(id)!, xv, i * 6, L))); + return out; + }; + const dragWeight = 0.05; + const rows = (pl: Map, withDrag: boolean): number[] => { + const out: number[] = []; + for (const m of mates) out.push(...(this.mateResidual(m, pl, L) ?? [])); + if (withDrag && opts.drag) out.push(...dragResidual(opts.drag, pl, L).map((v) => v * dragWeight)); + return out; + }; + const maxIter = opts.maxIter ?? 60; + let iterations = 0; + const run = (withDrag: boolean, iters: number) => { + const vw = varWeights(withDrag); + let lambda = 1e-6; + let r = rows(at(x), withDrag); + let cost = sumSq(r); + let perturbations = 0; + for (let it = 0; it < iters; it++) { + iterations++; + const mateCost = withDrag ? sumSq(rows(at(x), false)) : cost; + if (!withDrag && Math.sqrt(mateCost) < TOL) break; + const J = this.jacobian(x, sys, placements, mates, withDrag ? opts.drag ?? null : null, dragWeight, r.length, n, vw, L); + const g = new Array(n).fill(0); + const A = Array.from({ length: n }, () => new Array(n).fill(0)); + for (let i = 0; i < r.length; i++) { + const Ji = J[i]; + for (let p = 0; p < n; p++) { + const v = Ji[p]; + if (!v) continue; + g[p] += v * r[i]; + const Ap = A[p]; + for (let q = p; q < n; q++) Ap[q] += v * Ji[q]; + } + } + for (let p = 0; p < n; p++) for (let q = 0; q < p; q++) A[p][q] = A[q][p]; + let improved = false; + let step: number[] = []; + for (let tries = 0; tries < 12; tries++) { + const M = A.map((row, p) => row.map((v, q) => (p === q ? v + lambda : v))); + const d = choleskySolve(M, g.map((v) => -v)); + if (!d) { lambda *= 10; continue; } + step = d.map((v, i) => v / vw[i]); + const xn = x.map((v, i) => v + step[i]); + const rn = rows(at(xn), withDrag); + const cn = sumSq(rn); + if (cn < cost) { + x = xn; r = rn; cost = cn; + lambda = Math.max(1e-12, lambda / 4); + improved = true; + break; + } + lambda *= 6; + } + const stepSize = Math.max(0, ...step.map(Math.abs)); + if (!improved || stepSize < 1e-13) { + // Stuck where the gradient vanishes (a face turned exactly the + // wrong way for its alignment): give the bodies a turn and go on. + if (!withDrag && Math.sqrt(cost) > CONFLICT_TOL && perturbations < 3) { + perturbations++; + x = x.map((v, i) => (i % 6 >= 3 ? v + [0.7, -0.5, 0.3][i % 3] * (perturbations % 2 ? 1 : -1) : v)); + r = rows(at(x), withDrag); + cost = sumSq(r); + lambda = 1e-3; + continue; + } + break; + } + if (withDrag && stepSize < 1e-9) break; + } + }; + if (opts.drag) { + run(true, Math.min(maxIter, 30)); + // Then exactly onto the mates, moving as little as possible. + run(false, maxIter); + } else run(false, maxIter); + const final = at(x); + const worst = evalMates(final); + return { placements: final, ok: worst < CONFLICT_TOL, residuals, iterations }; + } + + /** + * Jacobian of the residual rows (mates, then the drag goal) by central + * differences: each mate depends on the variables of its two components only. + * Columns are divided by the variables' weights (`vw`, one per variable). + */ + private jacobian(x: number[], sys: System, base: Map, mates: SolverMate[], drag: DragGoal | null, dragWeight: number, m: number, n: number, vw: number[], L: number): number[][] { + const J = Array.from({ length: m }, () => new Array(n).fill(0)); + const h = 1e-6; + const current = new Map(base); + sys.vars.forEach((id, i) => current.set(id, placementWith(sys.bodies.get(id)!.placement, sys.centers.get(id)!, x, i * 6, L))); + // One component moved at a time, in one map put back after each (a copy + // of every placement per evaluation made large assemblies drag slowly). + const work = new Map(current); + const perturbed = (id: Id, j: number, d: number): Map => { + const i = sys.index.get(id)!; + const xv = x.slice(i * 6, i * 6 + 6); + xv[j] += d; + work.set(id, placementWith(sys.bodies.get(id)!.placement, sys.centers.get(id)!, xv, 0, L)); + return work; + }; + const block = (row: number, bodies: (Id | null)[], f: (pl: Map) => number[]) => { + for (const id of new Set(bodies)) { + if (!id || !sys.index.has(id)) continue; + const k = sys.index.get(id)! * 6; + for (let j = 0; j < 6; j++) { + const rp = f(perturbed(id, j, h)), rm = f(perturbed(id, j, -h)); + for (let i = 0; i < rp.length; i++) J[row + i][k + j] = (rp[i] - rm[i]) / (2 * h) / vw[k + j]; + } + work.set(id, current.get(id)!); + } + }; + let row = 0; + for (const mt of mates) { + const f = (pl: Map) => this.mateResidual(mt, pl, L) ?? []; + const len0 = f(current).length; + block(row, [mt.a.body, mt.b.body], f); + row += len0; + } + if (drag) block(row, [drag.body], (pl) => dragResidual(drag, pl, L).map((v) => v * dragWeight)); + return J; + } + + /** A mate's residuals with the components where `pl` puts them; null when it cannot be formed. */ + mateResidual(m: SolverMate, pl: Map, L: number): number[] | null { + const pa = m.a.body ? pl.get(m.a.body) ?? null : null; + const pb = m.b.body ? pl.get(m.b.body) ?? null : null; + if ((m.a.body && !pa) || (m.b.body && !pb)) return null; + return equations(m.type, placeGeo(m.a.geo, pa), placeGeo(m.b.geo, pb), { aligned: m.aligned, value: m.value, flip: m.flip, scale: L, rel: m.rel }, pa, pb); + } + + /** + * Solves, then finds conflicting mates (each mate that cannot hold with + * the ones before it is left out) and the definition of every component. + */ + analyze(opts: SolveOptions = {}): AnalysisResult { + const L = opts.scale && opts.scale > 0 ? opts.scale : 100; + const invalid = new Map(); + const usable: SolverMate[] = []; + for (const m of this.mates) { + const problem = this.validity(m); + if (problem) invalid.set(m.id, problem); + else usable.push(m); + } + let res = this.solve(opts, usable); + const conflicts = new Set(); + if (!res.ok) { + // Add the mates one at a time; one that does not hold with those before it conflicts. + const kept: SolverMate[] = []; + let placements = new Map(this.bodies.map((b) => [b.id, b.placement])); + for (const m of usable) { + const r = this.solve(opts, [...kept, m], placements); + if (r.ok) { kept.push(m); placements = r.placements; } else conflicts.add(m.id); + } + res = this.solve(opts, kept, placements); + } + const active = usable.filter((m) => !conflicts.has(m.id)); + const floating = this.bodies.filter((b) => !b.fixed); + const pl = res.placements; + // The Jacobian of the mates at the solution (all components free to move) is + // block diagonal over groups of floating components linked by mates between + // them: each group is analysed on its own, and a component no mate holds + // simply keeps its six degrees of freedom (one large matrix took seconds and, + // with hundreds of components, gigabytes). + const parent = new Map(floating.map((b) => [b.id, b.id])); + const root = (id: Id): Id => { + let r = id; + while (parent.get(r) !== r) r = parent.get(r)!; + parent.set(id, r); + return r; + }; + for (const m of active) { + const a = m.a.body, b = m.b.body; + if (a && b && parent.has(a) && parent.has(b)) parent.set(root(a), root(b)); + } + const groups = new Map(); + for (const b of floating) { + const r = root(b.id); + if (!groups.has(r)) groups.set(r, { bodies: [], mates: [] }); + groups.get(r)!.bodies.push(b); + } + for (const m of active) { + const id = [m.a.body, m.b.body].find((x): x is Id => !!x && parent.has(x)); + if (id) groups.get(root(id))!.mates.push(m); + } + let dof = 0; + const defined = new Set(); + const work = new Map(pl); + for (const g of groups.values()) { + const n = g.bodies.length * 6; + if (!g.mates.length) { dof += n; continue; } + const index = new Map(g.bodies.map((b, i) => [b.id, i])); + const J: number[][] = []; + for (const m of g.mates) { + const base = this.mateResidual(m, pl, L); + if (!base) continue; + const block = base.map(() => new Array(n).fill(0)); + for (const id of new Set([m.a.body, m.b.body])) { + if (!id || !index.has(id)) continue; + const i = index.get(id)!; + const center = g.bodies[i].center ?? [0, 0, 0]; + for (let j = 0; j < 6; j++) { + const x = [0, 0, 0, 0, 0, 0]; + x[j] = 1e-6; + work.set(id, placementWith(pl.get(id)!, center, x, 0, L)); + const rp = this.mateResidual(m, work, L)!; + x[j] = -1e-6; + work.set(id, placementWith(pl.get(id)!, center, x, 0, L)); + const rm = this.mateResidual(m, work, L)!; + for (let r = 0; r < base.length; r++) block[r][i * 6 + j] = (rp[r] - rm[r]) / 2e-6; + } + work.set(id, pl.get(id)!); + } + J.push(...block); + } + // A component is fully defined when no motion the mates allow moves it: + // every vector of the Jacobian's null space is zero on its six variables. + const { rank, basis } = nullSpace(J, n); + dof += n - rank; + g.bodies.forEach((b, i) => { + const k = i * 6; + if (basis.every((v) => { + let all = 0, own = 0; + for (let j = 0; j < n; j++) all = Math.max(all, Math.abs(v[j])); + for (let j = k; j < k + 6; j++) own = Math.max(own, Math.abs(v[j])); + return own <= 1e-6 * all; + })) defined.add(b.id); + }); + } + const status: DefinitionStatus = conflicts.size ? 'over' : invalid.size ? 'error' : dof === 0 ? 'full' : 'under'; + return { status, dof, defined, conflicts, invalid, placements: res.placements }; + } + + private validity(m: SolverMate): string | null { + if (m.a.body && m.a.body === m.b.body) return 'Both entities are on the same component'; + if (!m.a.body && !m.b.body) return 'A mate needs at least one component'; + if (m.type === 'lock' && !m.rel) return 'The lock mate has no stored position'; + return m.type === 'lock' ? null : mateProblem(m.type, m.a.geo, m.b.geo); + } +} + +/** + * The mates that can move a component: those of the floating components + * linked to it through mates between floating components. Mates of other + * components hold already and do not change while it is dragged, so a drag + * solves only these (fast in a large assembly). + */ +export function matesMoving(body: Id, bodies: SolverBody[], mates: SolverMate[]): SolverMate[] { + const floating = new Set(bodies.filter((b) => !b.fixed).map((b) => b.id)); + const linked = new Set([body]); + for (let grew = true; grew;) { + grew = false; + for (const m of mates) { + const a = m.a.body, b = m.b.body; + if (a && b && floating.has(a) && floating.has(b) && linked.has(a) !== linked.has(b)) { linked.add(a); linked.add(b); grew = true; } + } + } + return mates.filter((m) => (m.a.body && linked.has(m.a.body)) || (m.b.body && linked.has(m.b.body))); +} + +function dragResidual(goal: DragGoal, pl: Map, L: number): number[] { + const p = pl.get(goal.body); + if (!p) return []; + if (goal.kind === 'move') { + const w = applyPlacement(p, goal.local); + return [(w[0] - goal.target[0]) / L, (w[1] - goal.target[1]) / L, (w[2] - goal.target[2]) / L]; + } + return quatRotVec(qMul(qConj(goal.q), p.q)); +} + +const sumSq = (r: number[]) => r.reduce((s, v) => s + v * v, 0); + +/** Solves the symmetric positive definite system A x = b (null when it is not positive definite). */ +function choleskySolve(A: number[][], b: number[]): number[] | null { + const n = b.length; + const Lm = Array.from({ length: n }, () => new Array(n).fill(0)); + for (let i = 0; i < n; i++) { + for (let j = 0; j <= i; j++) { + let s = A[i][j]; + for (let k = 0; k < j; k++) s -= Lm[i][k] * Lm[j][k]; + if (i === j) { + if (!(s > 0)) return null; + Lm[i][i] = Math.sqrt(s); + } else Lm[i][j] = s / Lm[j][j]; + } + } + const y = new Array(n).fill(0); + for (let i = 0; i < n; i++) { + let s = b[i]; + for (let k = 0; k < i; k++) s -= Lm[i][k] * y[k]; + y[i] = s / Lm[i][i]; + } + const x = new Array(n).fill(0); + for (let i = n - 1; i >= 0; i--) { + let s = y[i]; + for (let k = i + 1; k < n; k++) s -= Lm[k][i] * x[k]; + x[i] = s / Lm[i][i]; + } + return x; +} + +/** Numerical rank of an m×n matrix (Householder QR with column pivoting). */ +export function matrixRank(rowsIn: number[][], n: number, tol = 1e-7): number { + return pivotedQR(rowsIn, n, tol).rank; +} + +/** Rank and a basis of the null space of an m×n matrix (from its pivoted QR factorisation). */ +export function nullSpace(rowsIn: number[][], n: number, tol = 1e-7): { rank: number; basis: number[][] } { + const { A, cols, rank } = pivotedQR(rowsIn, n, tol); + const basis: number[][] = []; + // R = [R11 R12] in pivot order: each free column f gives z with z_f = 1 and R11 z_pivots = -R12_f. + for (let f = rank; f < n; f++) { + const z = new Array(n).fill(0); + z[cols[f]] = 1; + for (let i = rank - 1; i >= 0; i--) { + let s = A[i][cols[f]]; + for (let c = i + 1; c < rank; c++) s += A[i][cols[c]] * z[cols[c]]; + z[cols[i]] = -s / A[i][cols[i]]; + } + basis.push(z); + } + return { rank, basis }; +} + +function pivotedQR(rowsIn: number[][], n: number, tol: number): { A: number[][]; cols: number[]; rank: number } { + const m = rowsIn.length; + const cols = [...Array(n).keys()]; + if (!m || !n) return { A: [], cols, rank: 0 }; + const A = rowsIn.map((r) => r.slice()); + const norms = new Array(n).fill(0).map((_, j) => Math.sqrt(A.reduce((s, r) => s + r[j] * r[j], 0))); + const scaleRef = Math.max(1, ...norms); + let rank = 0; + for (let k = 0; k < Math.min(m, n); k++) { + // Pivot: the remaining column with the largest norm below row k. + let best = -1, bestNorm = 0; + for (let c = k; c < n; c++) { + let s = 0; + for (let i = k; i < m; i++) s += A[i][cols[c]] ** 2; + if (s > bestNorm) { bestNorm = s; best = c; } + } + if (best < 0 || Math.sqrt(bestNorm) <= tol * scaleRef) break; + [cols[k], cols[best]] = [cols[best], cols[k]]; + const j = cols[k]; + // Householder reflection zeroing column j below row k. + const alpha = -Math.sign(A[k][j] || 1) * Math.sqrt(bestNorm); + const v = new Array(m).fill(0); + for (let i = k; i < m; i++) v[i] = A[i][j]; + v[k] -= alpha; + const vn = v.reduce((s, x) => s + x * x, 0); + if (vn > 0) { + for (let c = k; c < n; c++) { + const jc = cols[c]; + let s = 0; + for (let i = k; i < m; i++) s += v[i] * A[i][jc]; + const f = (2 * s) / vn; + for (let i = k; i < m; i++) A[i][jc] -= f * v[i]; + } + } + rank++; + } + return { A, cols, rank }; +} diff --git a/src/parametric/src/assistant/features.ts b/src/parametric/src/assistant/features.ts index 30cb35bdc3..d86eeaf969 100644 --- a/src/parametric/src/assistant/features.ts +++ b/src/parametric/src/assistant/features.ts @@ -287,6 +287,10 @@ export class FeatureCodec { case 'sweep': return { profile: f.profile, path: f.path, cut: f.cut }; case 'draft': return { faces: f.faces.map((x) => x.name), neutral_plane: planeSpec(f.neutral), angle: A(f.angle), reverse: f.flip }; case 'import': return { format: f.format, file: f.fileName }; + // Sheet metal and weldment features are made in their ribbon tabs, not by the assistant. + default: return { read_only: true }; } + // Features the assistant cannot create (surfaces...) are listed without their arguments. + return {}; } } diff --git a/src/parametric/src/assistant/inspect.ts b/src/parametric/src/assistant/inspect.ts index e722c6ee15..11fcf0c9ed 100644 --- a/src/parametric/src/assistant/inspect.ts +++ b/src/parametric/src/assistant/inspect.ts @@ -93,7 +93,12 @@ export class Inspector { if (!b) return 'Body: none yet (nothing solid has been built).'; const u = this.u; const size = [0, 1, 2].map((i) => u.len(b.max[i] - b.min[i])); - return `Body: ${this.host.faces.length} faces, ${this.host.edges.length} edges; bounding box X ${u.len(b.min[0])}…${u.len(b.max[0])}, Y ${u.len(b.min[1])}…${u.len(b.max[1])}, Z ${u.len(b.min[2])}…${u.len(b.max[2])} (size ${size.join(' × ')} ${u.unit}).`; + // Faces and edges of surface bodies come after the solid's: counted apart, as they are not part of it. + const faces = this.host.faces.filter((f) => !f.body).length, edges = this.host.edges.filter((e) => !e.body).length; + const sheets = new Set(this.host.faces.flatMap((f) => (f.body ? [f.body] : []))); + const solid = faces ? `${faces} faces, ${edges} edges` : 'no solid'; + const surfaces = sheets.size ? `; ${sheets.size} surface bod${sheets.size === 1 ? 'y' : 'ies'} apart from the solid (${this.host.faces.length - faces} faces, ${this.host.edges.length - edges} edges)` : ''; + return `Body: ${solid}${surfaces}; bounding box X ${u.len(b.min[0])}…${u.len(b.max[0])}, Y ${u.len(b.min[1])}…${u.len(b.max[1])}, Z ${u.len(b.min[2])}…${u.len(b.max[2])} (size ${size.join(' × ')} ${u.unit}).`; } partHeader(): string { diff --git a/src/parametric/src/assistant/panel.ts b/src/parametric/src/assistant/panel.ts index 2efe04dde6..2decdf7d4d 100644 --- a/src/parametric/src/assistant/panel.ts +++ b/src/parametric/src/assistant/panel.ts @@ -243,8 +243,10 @@ export class AssistantPanel { this.log, h('div', { class: 'as-bottom' }, this.status, composer, this.limit, h('div', { class: 'as-note' }, 'Sends your messages and a description of the part to Puter AI. Check designs before relying on them.'))); + this.composer = composer; this.bindDrop(); this.renderEmpty(); + this.syncAvailable(); app.store.on((reason) => { if (reason !== 'load') { // The ideas offered before a message is sent follow the part: new parts, or changes to this one. @@ -260,9 +262,31 @@ export class AssistantPanel { // Another part was opened: the reply in progress was about the one that was closed. if (this.agent.busy) this.stop('Stopped: another part was opened.'); else if (!this.agent.messages.length) this.renderEmpty(); + this.syncAvailable(); }); } + private composer: HTMLElement; + private unavailable: HTMLElement | null = null; + + /** + * The assistant edits parts: while an assembly is open it says so and takes + * no messages (from the box or the ideas), wherever the pane was when it opened. + */ + private syncAvailable() { + const off = !!this.app.assembly; + this.composer.inert = off; + this.el.classList.toggle('unavailable', off); + if (off && !this.unavailable) { + this.unavailable = h('div', { class: 'pm-msg info', role: 'status' }, 'The assistant works on parts. Open a part (Open Part on a component) to use it.'); + this.composer.before(this.unavailable); + } else if (!off && this.unavailable) { + this.unavailable.remove(); + this.unavailable = null; + } + for (const b of this.log.querySelectorAll('.as-idea')) b.disabled = off; + } + focus() { requestAnimationFrame(() => this.focusInput()); } @@ -329,7 +353,7 @@ export class AssistantPanel { ? ['Explain how this part is built', 'Round all the outer edges with 1 mm fillets', 'Make the main sizes parametric with global variables', 'What does it weigh in aluminium?'] : ['A 100 × 60 × 8 mm mounting plate with four M5 holes and rounded corners', 'A flanged bushing: 40 mm flange, 20 mm shaft, 10 mm bore', 'An enclosure box 80 × 50 × 30 mm with 2 mm walls, open on top', 'A spur-gear-like disc: 60 mm across with 12 teeth and a 8 mm bore']; const chips = h('div', { class: 'as-ideas' }, ...ideas.map((t) => { - const b = h('button', { class: 'as-idea', type: 'button' }, t); + const b = h('button', { class: 'as-idea', type: 'button', disabled: !!this.app.assembly }, t); b.addEventListener('click', (e) => { this.input.value = t; this.grow(); this.keepFocus(e); void this.submit(); }); return b; })); @@ -406,7 +430,7 @@ export class AssistantPanel { async submit() { let text = this.input.value.trim(); - if ((!text && !this.pending.length) || this.agent.busy || this.sending) return; + if ((!text && !this.pending.length) || this.agent.busy || this.sending || this.app.assembly) return; if (!this.checkLength()) { this.input.focus(); return; } if (!(await this.ready()) || this.agent.busy) return; // What the box holds now goes: it may have been edited while signing in. diff --git a/src/parametric/src/assistant/tools.ts b/src/parametric/src/assistant/tools.ts index 9c018e25b5..b36ea8c493 100644 --- a/src/parametric/src/assistant/tools.ts +++ b/src/parametric/src/assistant/tools.ts @@ -347,7 +347,7 @@ const TOOLS: ToolDef[] = [ show: B('Show (true) or leave (false) the drawing sheet'), arrange: B('Lay out front, top, right and isometric views at a fitting scale'), add_views: ARR({ type: 'string', enum: ['front', 'back', 'left', 'right', 'top', 'bottom', 'isometric'] }, 'Views to add'), - sheet: S('Sheet size', { enum: ['A4', 'A3', 'A2', 'A1', 'Letter', 'Tabloid'] }), + sheet: S('Sheet size', { enum: ['A4', 'A3', 'A2', 'A1', 'Letter', 'Tabloid', 'ANSI C', 'ANSI D'] }), landscape: B('Landscape (true) or portrait'), scale: N('Model to paper scale, e.g. 0.5 for 1:2'), title: S('Title block title'), drawn_by: S('Drawn by'), notes: S('Notes'), @@ -573,7 +573,10 @@ class Toolkit { const mp = await this.host.massProperties(); if (!mp) return 'Mass properties are not available for this body.'; const u = this.u; - if (!mp.solid) return `The body has no closed solid (only surfaces), so it has no volume, mass or centre of mass. Surface area ${u.area(mp.area)}.\n${this.ins.bodyText()}`; + // Surface bodies have area only: they are in none of the solid's values. + const sheets = mp.surfaceArea != null ? `Surface bodies: area ${u.area(mp.surfaceArea)}, not included in the values above (surfaces have no volume or mass).` : ''; + if (!mp.solid && mp.surfaceArea != null && !mp.area) return `The part has no solid, only surface bodies (area ${u.area(mp.surfaceArea)}), so it has no volume, mass or centre of mass.\n${this.ins.bodyText()}`; + if (!mp.solid) return `The body has no closed solid (only surfaces), so it has no volume, mass or centre of mass. Surface area ${u.area(mp.area)}.${sheets ? `\n${sheets}` : ''}\n${this.ins.bodyText()}`; const us = UNIT_SYSTEMS[this.doc.units]; const lines = [`Volume ${u.volume(mp.volume)}; surface area ${u.area(mp.area)}; centre of mass ${u.pt(mp.center)}.`]; const m = this.doc.material; @@ -582,6 +585,7 @@ class Toolkit { lines.push(`Mass ${qty(kg / us.massScale, 4)} ${us.mass} (${m.name}, ${m.density} kg/m³).`); } else lines.push('Mass: set a material (set_part) to get the mass.'); lines.push(`Principal moments per unit density: ${mp.principal.moments.map((x) => qty(x / u.scale ** 5, 2)).join(', ')} ${u.unit}⁵ about axes ${mp.principal.axes.map((x) => u.dir(normalize(x))).join(', ')}.`); + if (sheets) lines.push(sheets); lines.push(this.ins.bodyText()); return lines.join('\n'); } @@ -982,7 +986,7 @@ class Toolkit { done.push(`added ${v} view`); } const patch: Obj = {}; - if (a.sheet != null) { if (!['A4', 'A3', 'A2', 'A1', 'Letter', 'Tabloid'].includes(str(a.sheet))) throw new ToolError('sheet: A4, A3, A2, A1, Letter or Tabloid'); patch.sheet = str(a.sheet); } + if (a.sheet != null) { if (!['A4', 'A3', 'A2', 'A1', 'Letter', 'Tabloid', 'ANSI C', 'ANSI D'].includes(str(a.sheet))) throw new ToolError('sheet: A4, A3, A2, A1, Letter, Tabloid, ANSI C or ANSI D'); patch.sheet = str(a.sheet); } if (typeof a.landscape === 'boolean') patch.landscape = a.landscape; if (a.scale != null) { const s = Number(a.scale); if (!(s > 0 && s <= 100)) throw new ToolError('scale: a positive ratio such as 0.5 for 1:2'); patch.scale = s; } if (a.title != null) patch.title = str(a.title); diff --git a/src/parametric/src/drawing/annotate.ts b/src/parametric/src/drawing/annotate.ts new file mode 100644 index 0000000000..80522c9c77 --- /dev/null +++ b/src/parametric/src/drawing/annotate.ts @@ -0,0 +1,434 @@ +// Drawing annotations: dimensions measured from the model edges a view shows (which follow +// the model as it changes), centre marks and centrelines, notes, hole callouts, and the +// marks a section or detail view leaves on its parent. Everything is drawn as display-list +// items in sheet millimetres. + +import type { DrawingAnnotation, DrawingDimKind, DrawingDimension, DrawingRef, HoleFeature } from '../model/types'; +import { textWidth } from './pdf'; +import type { Item } from './sheet'; +import { type P2, type Prim, arcOverHalf } from './views'; + +export const DANGER = '#d32f2f'; +const THIN = 0.18; +const ARROW = 2.4, AW = 0.8; +export const DIM_TEXT_SIZE = 3; + +/** What a reference points at, in view coordinates. */ +export type Geo = + | { kind: 'point'; p: P2 } + | { kind: 'line'; a: P2; b: P2 } + | { kind: 'circle'; c: P2; r: number; full: boolean; a: P2; b: P2; m: P2 }; + +export function resolveRef(prims: Prim[], ref: DrawingRef): Geo | null { + for (const p of prims) { + if (p.edge !== ref.edge) continue; + if (ref.at === 'start') return { kind: 'point', p: p.a }; + if (ref.at === 'end') return { kind: 'point', p: p.b }; + if (ref.at === 'center') { if (p.kind === 'arc') return { kind: 'point', p: p.c }; continue; } + if (p.kind === 'line') return { kind: 'line', a: p.a, b: p.b }; + if (p.kind === 'arc') return { kind: 'circle', c: p.c, r: p.r, full: p.full, a: p.a, b: p.b, m: p.m }; + } + return null; +} + +const sub2 = (a: P2, b: P2): P2 => [a[0] - b[0], a[1] - b[1]]; +const dot2 = (a: P2, b: P2) => a[0] * b[0] + a[1] * b[1]; +const len2 = (a: P2) => Math.hypot(a[0], a[1]); +const unit = (a: P2): P2 => { const l = len2(a) || 1; return [a[0] / l, a[1] / l]; }; +const perp = (a: P2): P2 => [-a[1], a[0]]; + +/** The measured geometry of a dimension, in view coordinates. */ +export type Measured = + | { kind: 'linear'; p1: P2; p2: P2; u: P2; value: number } + | { kind: 'radial'; c: P2; r: number; diameter: boolean; value: number } + | { kind: 'angle'; v: P2; d1: P2; d2: P2; value: number; e1: P2[]; e2: P2[] }; + +function pointOf(g: Geo): P2 { + return g.kind === 'point' ? g.p : g.kind === 'circle' ? g.c : [(g.a[0] + g.b[0]) / 2, (g.a[1] + g.b[1]) / 2]; +} + +/** Where the line through p in direction u meets the line through a, b (null when parallel). */ +function meet(p: P2, u: P2, a: P2, b: P2): P2 | null { + const d = sub2(b, a); + const den = u[0] * d[1] - u[1] * d[0]; + if (Math.abs(den) < 1e-12) return null; + const t = ((a[0] - p[0]) * d[1] - (a[1] - p[1]) * d[0]) / den; + return [p[0] + u[0] * t, p[1] + u[1] * t]; +} + +function foot(p: P2, a: P2, b: P2): P2 { + const d = unit(sub2(b, a)); + const t = dot2(sub2(p, a), d); + return [a[0] + d[0] * t, a[1] + d[1] * t]; +} + +/** + * The kind of dimension a selection gives, placed at `at`: a circle its diameter (an arc its + * radius), two lines that meet their angle, else a distance, horizontal or vertical when the + * value is placed beyond the ends of what it measures (or that is what the geometry is), else + * aligned with it. + */ +export function guessKind(gs: Geo[], at: P2): DrawingDimKind { + if (gs.length === 1 && gs[0].kind === 'circle') return gs[0].full || arcOverHalf(gs[0]) ? 'diameter' : 'radius'; + if (gs.length === 2 && gs[0].kind === 'line' && gs[1].kind === 'line') { + const d1 = unit(sub2(gs[0].b, gs[0].a)), d2 = unit(sub2(gs[1].b, gs[1].a)); + if (Math.abs(d1[0] * d2[1] - d1[1] * d2[0]) > 1e-6) return 'angle'; + // Parallel: the distance across them. + if (Math.abs(d1[1]) < 1e-9) return 'vertical'; + if (Math.abs(d1[0]) < 1e-9) return 'horizontal'; + return 'aligned'; + } + let p1: P2, p2: P2; + if (gs.length === 1 && gs[0].kind === 'line') { p1 = gs[0].a; p2 = gs[0].b; } + else if (gs.length === 2 && (gs[0].kind === 'line' || gs[1].kind === 'line')) { + const [l, o] = gs[0].kind === 'line' ? [gs[0], gs[1]] : [gs[1] as Extract, gs[0]]; + const d = unit(sub2(l.b, l.a)); + if (Math.abs(d[1]) < 1e-9) return 'vertical'; + if (Math.abs(d[0]) < 1e-9) return 'horizontal'; + p1 = pointOf(o); p2 = foot(p1, l.a, l.b); + } else if (gs.length === 2) { p1 = pointOf(gs[0]); p2 = pointOf(gs[1]); } + else return 'aligned'; + const dx = Math.abs(p2[0] - p1[0]), dy = Math.abs(p2[1] - p1[1]); + if (dy < 1e-9) return 'horizontal'; + if (dx < 1e-9) return 'vertical'; + const inX = at[0] > Math.min(p1[0], p2[0]) && at[0] < Math.max(p1[0], p2[0]); + const inY = at[1] > Math.min(p1[1], p2[1]) && at[1] < Math.max(p1[1], p2[1]); + if (inX && !inY) return 'horizontal'; + if (inY && !inX) return 'vertical'; + return 'aligned'; +} + +/** Measures a dimension of the given kind on the geometry (view coordinates, model millimetres). */ +export function measure(kind: DrawingDimKind, gs: Geo[]): Measured | null { + if (kind === 'radius' || kind === 'diameter') { + const c = gs.find((g) => g.kind === 'circle') as Extract | undefined; + if (!c) return null; + return { kind: 'radial', c: c.c, r: c.r, diameter: kind === 'diameter', value: kind === 'diameter' ? 2 * c.r : c.r }; + } + if (kind === 'angle') { + if (gs.length !== 2 || gs[0].kind !== 'line' || gs[1].kind !== 'line') return null; + const [l1, l2] = gs as Extract[]; + const d1 = unit(sub2(l1.b, l1.a)), d2 = unit(sub2(l2.b, l2.a)); + const v = meet(l1.a, d1, l2.a, l2.b); + if (!v) return null; + return { kind: 'angle', v, d1, d2, value: (Math.acos(Math.max(-1, Math.min(1, Math.abs(dot2(d1, d2))))) * 180) / Math.PI, e1: [l1.a, l1.b], e2: [l2.a, l2.b] }; + } + const u: P2 | null = kind === 'horizontal' ? [1, 0] : kind === 'vertical' ? [0, 1] : null; + let p1: P2, p2: P2; + if (gs.length === 1) { + const g = gs[0]; + if (g.kind === 'line') { p1 = g.a; p2 = g.b; } + else if (g.kind === 'circle') { + // A circle alone measured linearly: its width across. + const w: P2 = u ?? [1, 0]; + p1 = [g.c[0] - w[0] * g.r, g.c[1] - w[1] * g.r]; p2 = [g.c[0] + w[0] * g.r, g.c[1] + w[1] * g.r]; + } else return null; + } else if (gs.length === 2) { + const [g1, g2] = gs; + if (g1.kind === 'line' && g2.kind === 'line') { + // Parallel lines: from the middle of the first across to the second. + p1 = pointOf(g1); + const dir = u ?? perp(unit(sub2(g1.b, g1.a))); + p2 = meet(p1, dir, g2.a, g2.b) ?? foot(p1, g2.a, g2.b); + } else if (g1.kind === 'line' || g2.kind === 'line') { + const [l, o] = g1.kind === 'line' ? [g1, g2] : [g2 as Extract, g1]; + p1 = pointOf(o); + if (u) { + const q = meet(p1, u, l.a, l.b); + p2 = q ?? foot(p1, l.a, l.b); + } else p2 = foot(p1, l.a, l.b); + if (g1.kind === 'line') [p1, p2] = [p2, p1]; + } else { p1 = pointOf(g1); p2 = pointOf(g2); } + } else return null; + const dir = u ?? unit(sub2(p2, p1)); + const value = Math.abs(dot2(sub2(p2, p1), dir)); + return { kind: 'linear', p1, p2, u: dir, value }; +} + +export interface Placement { + /** View coordinates to sheet. */ + T: (p: P2) => P2; + s: number; +} + +export interface AnnoFormat { + length: (mm: number, decimals?: number) => string; + angle: (deg: number, decimals?: number) => string; +} + +type Box = [number, number, number, number]; +const textBox = (s: string, x: number, y: number, size: number, anchor: 'start' | 'middle' | 'end'): Box => { + const w = textWidth(s, size); + const x0 = anchor === 'middle' ? x - w / 2 : anchor === 'end' ? x - w : x; + return [x0 - 0.5, y - size * 0.8, x0 + w + 0.5, y + size * 0.25]; +}; + +function arrow(items: Item[], tip: P2, dir: P2, color?: string) { + const d = unit(dir), n = perp(d); + items.push({ t: 'tri', a: tip, b: [tip[0] - d[0] * ARROW + n[0] * AW, tip[1] - d[1] * ARROW + n[1] * AW], c: [tip[0] - d[0] * ARROW - n[0] * AW, tip[1] - d[1] * ARROW - n[1] * AW], color }); +} + +const line = (items: Item[], a: P2, b: P2, color?: string, w = THIN, dash?: number[]) => + items.push({ t: 'line', x1: a[0], y1: a[1], x2: b[0], y2: b[1], w, color, ...(dash ? { dash } : {}) }); + +/** Readable text rotation (degrees, SVG sense) for text along direction u: never upside down, verticals read upward. */ +function readable(u: P2): number { + let a = (Math.atan2(u[1], u[0]) * 180) / Math.PI; + if (a >= 90 - 1e-9) a -= 180; + if (a < -90 - 1e-9) a += 180; + return Math.abs(a) < 1e-9 ? 0 : a; +} + +/** Draws a dimension. Returns the box its value takes (for picking), or null when it cannot be measured. */ +export function drawDimension(items: Item[], dim: DrawingDimension, m: Measured | null, pl: Placement, fmt: AnnoFormat): Box { + const at = pl.T(dim.at); + const pre = dim.prefix ?? ''; + if (!m) { + // Its geometry is gone: the dimension stays where it was, plainly marked. + const s = `${pre}${dim.kind === 'diameter' ? 'Ø' : dim.kind === 'radius' ? 'R' : ''}? (missing)`; + items.push({ t: 'text', s, x: at[0], y: at[1], size: DIM_TEXT_SIZE, anchor: 'middle', color: DANGER }); + return textBox(s, at[0], at[1], DIM_TEXT_SIZE, 'middle'); + } + if (m.kind === 'radial') { + const s = `${pre}${m.diameter ? 'Ø' : 'R'}${fmt.length(m.value, dim.decimals)}`; + const c = pl.T(m.c), r = m.r * pl.s; + const d = unit(len2(sub2(at, c)) > 1e-9 ? sub2(at, c) : [1, -1]); + const rim: P2 = [c[0] + d[0] * r, c[1] + d[1] * r]; + const tw = textWidth(s, DIM_TEXT_SIZE); + if (len2(sub2(at, c)) > r) { + // Outside: a leader from the value to the circle, arrow pointing at the centre, a short shoulder under the value. + const right = at[0] >= c[0]; + const shoulder: P2 = [at[0] + (right ? -3 : 3), at[1]]; + line(items, rim, shoulder); + line(items, shoulder, at); + arrow(items, rim, sub2(rim, shoulder)); + if (m.diameter) { + // The other side of a diameter: arrow inward from outside too. + const far: P2 = [c[0] - d[0] * r, c[1] - d[1] * r]; + line(items, far, [far[0] - d[0] * 4, far[1] - d[1] * 4]); + arrow(items, far, d); + } + const x = right ? at[0] + 0.8 : at[0] - 0.8; + items.push({ t: 'text', s, x, y: at[1] - 0.8, size: DIM_TEXT_SIZE, anchor: right ? 'start' : 'end' }); + return textBox(s, x, at[1] - 0.8, DIM_TEXT_SIZE, right ? 'start' : 'end'); + } + // Inside: across the circle (diameter) or from the centre (radius), the value at the point placed. + const from: P2 = m.diameter ? [c[0] - d[0] * r, c[1] - d[1] * r] : c; + line(items, from, rim); + arrow(items, rim, d); + if (m.diameter) arrow(items, from, [-d[0], -d[1]]); + items.push({ t: 'text', s, x: at[0], y: at[1] - 0.8, size: DIM_TEXT_SIZE, anchor: 'middle' }); + void tw; + return textBox(s, at[0], at[1] - 0.8, DIM_TEXT_SIZE, 'middle'); + } + if (m.kind === 'angle') { + const s = `${pre}${fmt.angle(m.value, dim.decimals)}`; + const v = pl.T(m.v); + const rho = Math.max(len2(sub2(at, v)), 3); + // The two rays bounding the angle the value was placed in. + const ta = Math.atan2(at[1] - v[1], at[0] - v[0]); + const cands = [m.d1, [-m.d1[0], -m.d1[1]] as P2].flatMap((a) => [m.d2, [-m.d2[0], -m.d2[1]] as P2].map((b) => [a, b] as [P2, P2])); + let best: [number, number] = [0, 0]; + for (const [a, b] of cands) { + const aa = Math.atan2(a[1], a[0]); + let sw = Math.atan2(b[1], b[0]) - aa; + while (sw <= -Math.PI) sw += 2 * Math.PI; + while (sw > Math.PI) sw -= 2 * Math.PI; + let rel = ta - aa; + while (rel <= -Math.PI) rel += 2 * Math.PI; + while (rel > Math.PI) rel -= 2 * Math.PI; + if ((sw >= 0 && rel >= 0 && rel <= sw) || (sw < 0 && rel <= 0 && rel >= sw)) { best = [aa, sw]; break; } + } + const [a0, sw] = best; + const n = Math.max(8, Math.ceil(Math.abs(sw) / 0.08)); + const pts: P2[] = []; + for (let i = 0; i <= n; i++) { const t = a0 + (sw * i) / n; pts.push([v[0] + rho * Math.cos(t), v[1] + rho * Math.sin(t)]); } + for (let i = 0; i < n; i++) line(items, pts[i], pts[i + 1]); + const sg = Math.sign(sw) || 1; + arrow(items, pts[0], [Math.sin(a0) * sg, -Math.cos(a0) * sg]); + const a1 = a0 + sw; + arrow(items, pts[n], [-Math.sin(a1) * sg, Math.cos(a1) * sg]); + // Extension lines from the edges out to the arc. + for (const [ang, ends] of [[a0, m.e1], [a1, m.e2]] as [number, P2[]][]) { + const dir: P2 = [Math.cos(ang), Math.sin(ang)]; + const far = Math.max(...ends.map((e) => dot2(sub2(pl.T(e), v), dir))); + if (rho > far + 1) line(items, [v[0] + dir[0] * (far + 1), v[1] + dir[1] * (far + 1)], [v[0] + dir[0] * (rho + 1.5), v[1] + dir[1] * (rho + 1.5)]); + } + items.push({ t: 'text', s, x: at[0], y: at[1], size: DIM_TEXT_SIZE, anchor: 'middle' }); + return textBox(s, at[0], at[1], DIM_TEXT_SIZE, 'middle'); + } + // Linear: extension lines from the points to the dimension line through the value. + const s = `${pre}${fmt.length(m.value, dim.decimals)}`; + const p1 = pl.T(m.p1), p2 = pl.T(m.p2); + const u = m.u, n = perp(u); + const o1 = dot2(sub2(at, p1), n), o2 = dot2(sub2(at, p2), n); + const d1: P2 = [p1[0] + n[0] * o1, p1[1] + n[1] * o1], d2: P2 = [p2[0] + n[0] * o2, p2[1] + n[1] * o2]; + for (const [p, d, o] of [[p1, d1, o1], [p2, d2, o2]] as [P2, P2, number][]) { + if (Math.abs(o) < 1e-6) continue; + const sg = Math.sign(o); + line(items, [p[0] + n[0] * sg * 1, p[1] + n[1] * sg * 1], [d[0] + n[0] * sg * 2, d[1] + n[1] * sg * 2]); + } + // From d1 toward d2 along u (or against it). + const span = dot2(sub2(d2, d1), u); + const e: P2 = span >= 0 ? u : [-u[0], -u[1]]; + const L = Math.abs(span); + const tw = textWidth(s, DIM_TEXT_SIZE); + // The value's place along the line, from d1. + const ta = dot2(sub2(at, d1), e); + const outside = L < 2 * ARROW + 1; + let lo = Math.min(0, ta - tw / 2 - 0.5), hi = Math.max(L, ta + tw / 2 + 0.5); + if (outside) { lo = Math.min(lo, -ARROW - 2); hi = Math.max(hi, L + ARROW + 2); } + line(items, [d1[0] + e[0] * lo, d1[1] + e[1] * lo], [d1[0] + e[0] * hi, d1[1] + e[1] * hi]); + arrow(items, d1, outside ? e : [-e[0], -e[1]]); + arrow(items, d2, outside ? [-e[0], -e[1]] : e); + const rot = readable(u); + const ra = (rot * Math.PI) / 180; + const textUp: P2 = [Math.sin(ra), -Math.cos(ra)]; + const base: P2 = [d1[0] + e[0] * ta + textUp[0] * 1, d1[1] + e[1] * ta + textUp[1] * 1]; + items.push({ t: 'text', s, x: base[0], y: base[1], size: DIM_TEXT_SIZE, anchor: 'middle', ...(rot ? { rotate: rot } : {}) }); + const half = tw / 2 + 0.5, h = DIM_TEXT_SIZE; + const ux: P2 = [Math.cos(ra), Math.sin(ra)]; + const corners: P2[] = [-half, half].flatMap((a) => [-0.3, h].map((b) => [base[0] + ux[0] * a + textUp[0] * b, base[1] + ux[1] * a + textUp[1] * b] as P2)); + return [Math.min(...corners.map((c) => c[0])), Math.min(...corners.map((c) => c[1])), Math.max(...corners.map((c) => c[0])), Math.max(...corners.map((c) => c[1]))]; +} + +/** Centre mark: a small cross at the centre and lines out past the circle. */ +export function drawCenterMark(items: Item[], c: P2, r: number, color?: string) { + const g = 1.5, ext = 2.5; + for (const d of [[1, 0], [0, 1]] as P2[]) { + line(items, [c[0] - d[0] * g, c[1] - d[1] * g], [c[0] + d[0] * g, c[1] + d[1] * g], color); + if (r > g + 1) { + line(items, [c[0] + d[0] * (g + 1), c[1] + d[1] * (g + 1)], [c[0] + d[0] * (r + ext), c[1] + d[1] * (r + ext)], color); + line(items, [c[0] - d[0] * (g + 1), c[1] - d[1] * (g + 1)], [c[0] - d[0] * (r + ext), c[1] - d[1] * (r + ext)], color); + } + } +} + +export const CHAIN = [6, 1.2, 1, 1.2]; + +/** Centreline between two points (sheet), running a little past both. */ +export function drawCenterline(items: Item[], a: P2, b: P2, color?: string) { + const u = unit(sub2(b, a)), ext = 2.5; + line(items, [a[0] - u[0] * ext, a[1] - u[1] * ext], [b[0] + u[0] * ext, b[1] + u[1] * ext], color, THIN, CHAIN); +} + +export const NOTE_SIZE = 3.5; + +/** A note: lines of text from `at` (top line's baseline), with a leader arrow to `tip`. */ +export function drawNote(items: Item[], text: string, at: P2, size: number, tip?: P2, color?: string): Box { + const lines = text.split('\n'); + let w = 0; + lines.forEach((s, i) => { + items.push({ t: 'text', s, x: at[0], y: at[1] + i * size * 1.4, size, color }); + w = Math.max(w, textWidth(s, size)); + }); + const box: Box = [at[0] - 0.5, at[1] - size * 0.8, at[0] + w + 0.5, at[1] + (lines.length - 1) * size * 1.4 + size * 0.25]; + if (tip) { + // From the side of the text nearer the tip, at the first line's middle height. + const y = at[1] - size * 0.35; + const from: P2 = tip[0] < at[0] + w / 2 ? [at[0] - 1, y] : [at[0] + w + 1, y]; + line(items, tip, from, color); + arrow(items, tip, sub2(tip, from), color); + } + return box; +} + +/** The cutting line of a section view on its parent: thick ends, a chain line between, arrows and letters. */ +export function drawCuttingLine(items: Item[], a: P2, b: P2, sight: P2, letter: string) { + const u = unit(sub2(b, a)); + const end = Math.min(5, len2(sub2(b, a)) / 3); + line(items, a, [a[0] + u[0] * end, a[1] + u[1] * end], undefined, 0.6); + line(items, b, [b[0] - u[0] * end, b[1] - u[1] * end], undefined, 0.6); + line(items, [a[0] + u[0] * end, a[1] + u[1] * end], [b[0] - u[0] * end, b[1] - u[1] * end], undefined, THIN, [8, 1.5, 1.5, 1.5]); + const w = unit(sight); + for (const p of [a, b]) { + const tip: P2 = [p[0] + w[0] * 7, p[1] + w[1] * 7]; + line(items, p, tip, undefined, 0.35); + arrow(items, tip, w); + const q: P2 = [tip[0] + w[0] * 2.5, tip[1] + w[1] * 2.5 + 1.75]; + items.push({ t: 'text', s: letter, x: q[0], y: q[1], size: 3.5, bold: true, anchor: 'middle' }); + } +} + +/** + * The viewing arrow of an auxiliary view on its parent: square to the edge it looks at, on the + * side it is seen from, pointing at the edge's middle `m`, with the view's letter at its tail. + */ +export function drawViewArrow(items: Item[], m: P2, sight: P2, letter: string) { + const w = unit(sight); + const tip: P2 = [m[0] - w[0] * 2, m[1] - w[1] * 2], tail: P2 = [m[0] - w[0] * 12, m[1] - w[1] * 12]; + line(items, tail, tip, undefined, 0.35); + arrow(items, tip, w); + const q: P2 = [tail[0] - w[0] * 2.5, tail[1] - w[1] * 2.5 + 1.75]; + items.push({ t: 'text', s: letter, x: q[0], y: q[1], size: 3.5, bold: true, anchor: 'middle' }); +} + +/** The circle of a detail view on its parent, with its letter. */ +export function drawDetailCircle(items: Item[], c: P2, r: number, letter: string) { + items.push({ t: 'circle', cx: c[0], cy: c[1], r, w: 0.35, dash: [6, 1.2, 1, 1.2] }); + const k = Math.SQRT1_2; + items.push({ t: 'text', s: letter, x: c[0] + (r + 1.5) * k, y: c[1] - (r + 1.5) * k, size: 3.5, bold: true, anchor: 'start' }); +} + +export interface HoleSpec { + kind: 'simple' | 'counterbore' | 'countersink'; + diameter: number; + /** Absent: through all. */ + depth?: number; + cbDiameter?: number; + cbDepth?: number; + csDiameter?: number; + csAngle?: number; + /** Holes made by the same feature with this size. */ + count: number; +} + +/** + * The hole feature a face was made by and which hole of it the face belongs to, from the + * face's name: "f2:p1:1" is face 1 of the hole at sketch point p1, and "f2:p1:1@f5.3" the same + * face of copy 3 of a pattern or mirror f5 (see the kernel's naming). Null when the name does + * not have that form; the caller checks that the feature is a hole. + */ +export function holeInstance(name: string): { feature: string; key: string } | null { + const [base, ...copies] = name.replace(/#\d+$/, '').split('@'); + const parts = base.split(':'); + if (parts.length < 3 || !parts[0] || !parts[1]) return null; + return { feature: parts[0], key: [parts[1], ...copies].join('@') }; +} + +/** How many holes of a hole feature the part has: one per hole centre, and per pattern or mirror copy of it. */ +export function holeCount(faceNames: string[], feature: string): number { + const keys = new Set(); + for (const n of faceNames) { + const h = holeInstance(n); + if (h?.feature === feature) keys.add(h.key); + } + return keys.size; +} + +/** The sizes of a hole feature (its Params evaluated) for a callout of `count` holes. */ +export function holeSpecOf(f: HoleFeature, count: number): HoleSpec { + const num = (v: unknown) => (typeof v === 'number' ? v : Number(v) || 0); + return { + kind: f.kind === 'counterbore' ? 'counterbore' : f.kind === 'countersink' ? 'countersink' : 'simple', + diameter: num(f.diameter), + depth: f.end === 'blind' ? num(f.depth) : undefined, + cbDiameter: num(f.cbDiameter), cbDepth: num(f.cbDepth), csDiameter: num(f.csDiameter), csAngle: num(f.csAngle), + count: Math.max(1, count), + }; +} + +/** A hole callout's lines: count, diameter and depth, then the counterbore or countersink. */ +export function holeCalloutText(h: HoleSpec, fmt: AnnoFormat): string { + const lines: string[] = []; + const n = h.count > 1 ? `${h.count}X ` : ''; + lines.push(`${n}Ø${fmt.length(h.diameter)} ${h.depth === undefined ? 'THRU' : `DEEP ${fmt.length(h.depth)}`}`); + if (h.kind === 'counterbore' && h.cbDiameter !== undefined) lines.push(`CBORE Ø${fmt.length(h.cbDiameter)} DEEP ${fmt.length(h.cbDepth ?? 0)}`); + if (h.kind === 'countersink' && h.csDiameter !== undefined) lines.push(`CSK Ø${fmt.length(h.csDiameter)} X ${fmt.angle(h.csAngle ?? 90, 0)}`); + return lines.join('\n'); +} + +/** Annotations belonging to a view (deleted with it). */ +export const annotationsOf = (list: DrawingAnnotation[] | undefined, views: string[]) => (list ?? []).filter((a) => a.view && views.includes(a.view)); + +export { textBox }; diff --git a/src/parametric/src/drawing/dxf.ts b/src/parametric/src/drawing/dxf.ts new file mode 100644 index 0000000000..b2187fd54a --- /dev/null +++ b/src/parametric/src/drawing/dxf.ts @@ -0,0 +1,168 @@ +// DXF export of a drawing sheet (AutoCAD R12 ASCII, millimetres, y up): lines, true arcs +// and circles, text and filled arrowheads, on layers by line kind, so the sheet opens in +// any 2D CAD program. + +import { parseSvgPath } from './pdf'; +import type { Item } from './sheet'; +import { flattenPath } from './views'; + +type P2 = [number, number]; + +/** Layer of an item by its line weight and pattern. */ +function layerOf(it: Item): string { + if (it.t === 'text') return 'TEXT'; + if (it.t === 'rect') return 'BORDER'; + if (it.t === 'tri') return 'DIM'; + const dash = 'dash' in it ? it.dash : undefined; + const w = it.t === 'path' || it.t === 'line' || it.t === 'circle' ? it.w : 0.25; + if (dash && dash.length >= 4) return 'CENTER'; + if (dash) return 'HIDDEN'; + return w >= 0.3 ? 'VISIBLE' : 'THIN'; +} + +const LAYERS: [string, number, string][] = [ + ['VISIBLE', 7, 'CONTINUOUS'], ['HIDDEN', 8, 'DASHED'], ['CENTER', 4, 'CENTER'], ['THIN', 7, 'CONTINUOUS'], + ['DIM', 7, 'CONTINUOUS'], ['TEXT', 7, 'CONTINUOUS'], ['BORDER', 7, 'CONTINUOUS'], +]; + +/** Text in the DXF's code page: diameter, degree and plus-minus as their control codes, an ellipsis as three dots, else ASCII. */ +export function dxfText(s: string): string { + return s.replace(/Ø|⌀/g, '%%c').replace(/°/g, '%%d').replace(/±/g, '%%p').replace(/…/g, '...').replace(/[^\x20-\x7e]/g, '?'); +} + +const n = (v: number) => (Math.abs(v) < 1e-10 ? '0' : String(+v.toFixed(6))); + +export function toDxf(items: Item[], w: number, h: number): string { + const out: string[] = []; + const g = (code: number, value: string | number) => out.push(String(code), typeof value === 'number' ? n(value) : value); + const Y = (y: number) => h - y; + const head = (type: string, layer: string, color?: string) => { + g(0, type); g(8, layer); + if (color) g(62, '1'); + }; + const line = (a: P2, b: P2, layer: string, color?: string) => { + if (Math.hypot(a[0] - b[0], a[1] - b[1]) < 1e-9) return; + head('LINE', layer, color); + g(10, a[0]); g(20, Y(a[1])); g(30, 0); g(11, b[0]); g(21, Y(b[1])); g(31, 0); + }; + const poly = (pts: P2[], layer: string, color?: string) => { for (let i = 0; i + 1 < pts.length; i++) line(pts[i], pts[i + 1], layer, color); }; + /** A circular arc from the sheet (y down): centre, radius, start angle, signed sweep (radians, y down). */ + const arc = (c: P2, r: number, a0: number, sweep: number, layer: string, color?: string) => { + if (Math.abs(sweep) >= 2 * Math.PI - 1e-9) { + head('CIRCLE', layer, color); g(10, c[0]); g(20, Y(c[1])); g(30, 0); g(40, r); + return; + } + // y flips: angles change sign, and DXF arcs run counterclockwise. + const s = -(sweep > 0 ? a0 + sweep : a0), e = -(sweep > 0 ? a0 : a0 + sweep); + const deg = (x: number) => ((((x * 180) / Math.PI) % 360) + 360) % 360; + head('ARC', layer, color); g(10, c[0]); g(20, Y(c[1])); g(30, 0); g(40, r); g(50, deg(s)); g(51, deg(e)); + }; + + out.push('0', 'SECTION', '2', 'HEADER', '9', '$ACADVER', '1', 'AC1009', '9', '$INSBASE', '10', '0', '20', '0', '30', '0', + '9', '$EXTMIN', '10', '0', '20', '0', '30', '0', '9', '$EXTMAX', '10', n(w), '20', n(h), '30', '0', '9', '$MEASUREMENT', '70', '1', '0', 'ENDSEC'); + out.push('0', 'SECTION', '2', 'TABLES'); + out.push('0', 'TABLE', '2', 'LTYPE', '70', '3'); + const ltype = (name: string, desc: string, pattern: number[]) => { + out.push('0', 'LTYPE', '2', name, '70', '0', '3', desc, '72', '65', '73', String(pattern.length), '40', n(pattern.reduce((s, x) => s + Math.abs(x), 0))); + for (const p of pattern) out.push('49', n(p)); + }; + ltype('CONTINUOUS', 'Solid line', []); + ltype('DASHED', '__ __ __', [1.6, -0.8]); + ltype('CENTER', '____ _ ____', [6, -1.2, 1, -1.2]); + out.push('0', 'ENDTAB'); + out.push('0', 'TABLE', '2', 'LAYER', '70', String(LAYERS.length)); + for (const [name, color, lt] of LAYERS) out.push('0', 'LAYER', '2', name, '70', '0', '62', String(color), '6', lt); + out.push('0', 'ENDTAB', '0', 'ENDSEC'); + out.push('0', 'SECTION', '2', 'ENTITIES'); + + for (const it of items) { + const layer = layerOf(it); + const color = (it as { color?: string }).color; + switch (it.t) { + case 'line': line([it.x1, it.y1], [it.x2, it.y2], layer, color); break; + case 'rect': poly([[it.x, it.y], [it.x + it.w, it.y], [it.x + it.w, it.y + it.h], [it.x, it.y + it.h], [it.x, it.y]], layer); break; + case 'circle': arc([it.cx, it.cy], it.r, 0, 2 * Math.PI, layer, color); break; + case 'tri': + head('SOLID', layer, color); + g(10, it.a[0]); g(20, Y(it.a[1])); g(30, 0); g(11, it.b[0]); g(21, Y(it.b[1])); g(31, 0); + g(12, it.c[0]); g(22, Y(it.c[1])); g(32, 0); g(13, it.c[0]); g(23, Y(it.c[1])); g(33, 0); + break; + case 'text': { + const just = it.anchor === 'middle' ? 1 : it.anchor === 'end' ? 2 : 0; + head('TEXT', layer, color); + g(10, it.x); g(20, Y(it.y)); g(30, 0); g(40, it.size * 0.72); g(1, dxfText(it.s)); + if (it.rotate) g(50, -it.rotate); + if (it.bold) g(7, 'STANDARD'); + if (just) { g(72, String(just)); g(11, it.x); g(21, Y(it.y)); g(31, 0); } + break; + } + case 'path': pathEntities(it, layer, color, line, arc, poly); break; + } + } + out.push('0', 'ENDSEC', '0', 'EOF'); + return out.join('\n') + '\n'; +} + +/** A path's lines and circular arcs as DXF lines and arcs; curves and elliptical arcs as short lines. */ +function pathEntities( + it: Extract, + layer: string, + color: string | undefined, + line: (a: P2, b: P2, layer: string, color?: string) => void, + arc: (c: P2, r: number, a0: number, sweep: number, layer: string, color?: string) => void, + poly: (pts: P2[], layer: string, color?: string) => void, +) { + const { d, tx, ty, s } = it; + if (/[CcSsQqTt]/.test(d)) { + for (const pl of flattenPath(d, tx, ty, s, 0.01)) poly(pl, layer, color); + return; + } + const T = (p: P2): P2 => [p[0] * s + tx, p[1] * s + ty]; + const toks = d.match(/[a-zA-Z]|-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/g) ?? []; + let i = 0, cmd = ''; + let cur: P2 = [0, 0], start: P2 = [0, 0]; + const num = () => Number(toks[i++]); + while (i < toks.length) { + if (/^[a-zA-Z]$/.test(toks[i])) cmd = toks[i++]; + else if (!cmd) { i++; continue; } + const rel = cmd === cmd.toLowerCase(); + const C = cmd.toUpperCase(); + const o: P2 = rel ? cur : [0, 0]; + if (C === 'M') { cur = [o[0] + num(), o[1] + num()]; start = cur; cmd = rel ? 'l' : 'L'; } + else if (C === 'L') { const p: P2 = [o[0] + num(), o[1] + num()]; line(T(cur), T(p), layer, color); cur = p; } + else if (C === 'H') { const p: P2 = [(rel ? cur[0] : 0) + num(), cur[1]]; line(T(cur), T(p), layer, color); cur = p; } + else if (C === 'V') { const p: P2 = [cur[0], (rel ? cur[1] : 0) + num()]; line(T(cur), T(p), layer, color); cur = p; } + else if (C === 'Z') { line(T(cur), T(start), layer, color); cur = start; } + else if (C === 'A') { + const rx = num(), ry = num(), rot = num(), large = num(), sweep = num(); + const p: P2 = [o[0] + num(), o[1] + num()]; + const c = Math.abs(rx - ry) < 1e-9 * (1 + rx) ? circleArc(cur, p, rx, !!large, !!sweep) : null; + if (c) arc(T(c.c), c.r * s, c.a0, c.sweep, layer, color); + else { + // An ellipse: as lines along its curve. + const segs = parseSvgPath(`M${cur[0]} ${cur[1]}A${rx} ${ry} ${rot} ${large} ${sweep} ${p[0]} ${p[1]}`); + const sub = segs.map((q) => ('p' in q ? `${q.op}${'c1' in q ? `${q.c1[0]} ${q.c1[1]} ${q.c2[0]} ${q.c2[1]} ` : ''}${q.p[0]} ${q.p[1]}` : '')).join(''); + for (const pl of flattenPath(sub, tx, ty, s, 0.01)) poly(pl, layer, color); + } + cur = p; + } else i++; + } +} + +/** Centre, radius, start angle and signed sweep of an SVG circular arc (y down). */ +export function circleArc(a: P2, b: P2, r: number, large: boolean, sweep: boolean): { c: P2; r: number; a0: number; sweep: number } | null { + const dx = b[0] - a[0], dy = b[1] - a[1]; + const dd = Math.hypot(dx, dy); + if (dd < 1e-12 || r <= 0) return null; + r = Math.max(r, dd / 2); + const h = Math.sqrt(Math.max(0, r * r - (dd * dd) / 4)); + const mx = (a[0] + b[0]) / 2, my = (a[1] + b[1]) / 2; + // SVG: with the sweep flag the arc turns toward positive angles (clockwise on paper, y down). + const sgn = large === sweep ? -1 : 1; + const c: P2 = [mx - (sgn * h * dy) / dd, my + (sgn * h * dx) / dd]; + const a0 = Math.atan2(a[1] - c[1], a[0] - c[0]); + let a1 = Math.atan2(b[1] - c[1], b[0] - c[0]) - a0; + if (sweep && a1 < 0) a1 += 2 * Math.PI; + if (!sweep && a1 > 0) a1 -= 2 * Math.PI; + return { c, r, a0, sweep: a1 }; +} diff --git a/src/parametric/src/drawing/flat.ts b/src/parametric/src/drawing/flat.ts new file mode 100644 index 0000000000..8e5989186b --- /dev/null +++ b/src/parametric/src/drawing/flat.ts @@ -0,0 +1,85 @@ +// Flat pattern views of sheet metal parts: the flat pattern (src/model/flat-pattern.ts) as a +// drawing view's lines (outline and cuts), its edges for dimensions, and its bend lines with +// their notes. View coordinates are the flat pattern's x and y with y turned down. + +import type { EdgeInfo, ProjectionResult } from '../kernel/protocol'; +import type { FlatPattern, FlatSeg } from '../model/flat-pattern'; +import type { P2 } from './views'; + +/** A bend centre line in view coordinates. */ +export interface FlatBendLine { + a: P2; + b: P2; + up: boolean; + angle: number; + radius: number; +} + +/** What a flat pattern view draws: its lines, plus the bend lines, or why there is no flat pattern. */ +export interface FlatProjection extends ProjectionResult { + bends?: FlatBendLine[]; + error?: string; + /** What the flat pattern leaves out or cannot show exactly (said beside the view). */ + notes?: string[]; +} + +const r4 = (v: number) => +v.toFixed(4) || 0; +const V = (p: P2): P2 => [p[0], -p[1]]; +const pt = (p: P2) => `${r4(p[0])} ${r4(p[1])}`; + +function segPath(s: FlatSeg): string { + if (s.k === 'line') return `M${pt(V(s.a))}L${pt(V(s.b))}`; + if (s.k === 'circle') { + const a = V([s.c[0] + s.r, s.c[1]]), b = V([s.c[0] - s.r, s.c[1]]); + return `M${pt(a)}A${r4(s.r)} ${r4(s.r)} 0 1 0 ${pt(b)}A${r4(s.r)} ${r4(s.r)} 0 1 0 ${pt(a)}`; + } + // Counter-clockwise with y up is clockwise with y down: SVG's sweep flag 0. + let sweep = s.a1 - s.a0; + while (sweep <= 0) sweep += 2 * Math.PI; + while (sweep > 2 * Math.PI) sweep -= 2 * Math.PI; + const a = V([s.c[0] + s.r * Math.cos(s.a0), s.c[1] + s.r * Math.sin(s.a0)]); + const b = V([s.c[0] + s.r * Math.cos(s.a1), s.c[1] + s.r * Math.sin(s.a1)]); + return `M${pt(a)}A${r4(s.r)} ${r4(s.r)} 0 ${sweep > Math.PI ? 1 : 0} 0 ${pt(b)}`; +} + +/** The flat pattern as a view's projection (id: the view's key); without one, the reason. */ +export function flatProjection(id: string, f: FlatPattern | null, error?: string): FlatProjection { + if (!f) return { id, visible: [], hidden: [], bounds: null, bends: [], error: error ?? 'The part cannot be flattened' }; + return { + id, + visible: f.loops.flatMap((l) => l.segs.map(segPath)), + hidden: [], + bounds: [r4(f.min[0]), r4(-f.max[1]), r4(f.max[0]), r4(-f.min[1])], + bends: f.bends.map((b) => ({ a: V(b.a), b: V(b.b), up: b.up, angle: b.angle, radius: b.radius })), + ...(f.notes.length ? { notes: [...f.notes] } : {}), + }; +} + +/** + * The flat pattern's outline and cut edges as model edges of the view (in the plane z = 0, so + * the front view direction sees them as the flat pattern shows), named "flat::" + * for dimensions and centre marks. + */ +export function flatEdges(f: FlatPattern | null): EdgeInfo[] { + if (!f) return []; + const out: EdgeInfo[] = []; + const P = (p: P2): [number, number, number] => [p[0], p[1], 0]; + f.loops.forEach((l, i) => l.segs.forEach((s, j) => { + const name = `flat:${i}:${j}`; + // Two faces: a drawing leaves out edges with one face (seams). + if (s.k === 'line') { + const len = Math.hypot(s.b[0] - s.a[0], s.b[1] - s.a[1]); + if (len < 1e-9) return; + out.push({ name, type: 'line', a: P(s.a), b: P(s.b), mid: P([(s.a[0] + s.b[0]) / 2, (s.a[1] + s.b[1]) / 2]), length: len, faces: [0, 1], dir: [(s.b[0] - s.a[0]) / len, (s.b[1] - s.a[1]) / len, 0] }); + } else if (s.k === 'circle') { + const a = P([s.c[0] + s.r, s.c[1]]); + out.push({ name, type: 'circle', a, b: a, mid: P([s.c[0] - s.r, s.c[1]]), length: 2 * Math.PI * s.r, faces: [0, 1], center: P(s.c), axis: [0, 0, 1], radius: s.r }); + } else { + let sweep = s.a1 - s.a0; + while (sweep <= 0) sweep += 2 * Math.PI; + const at = (t: number): P2 => [s.c[0] + s.r * Math.cos(t), s.c[1] + s.r * Math.sin(t)]; + out.push({ name, type: 'circle', a: P(at(s.a0)), b: P(at(s.a0 + sweep)), mid: P(at(s.a0 + sweep / 2)), length: sweep * s.r, faces: [0, 1], center: P(s.c), axis: [0, 0, 1], radius: s.r }); + } + })); + return out; +} diff --git a/src/parametric/src/drawing/pdf.ts b/src/parametric/src/drawing/pdf.ts index 5fd5b8bcae..628f083d48 100644 --- a/src/parametric/src/drawing/pdf.ts +++ b/src/parametric/src/drawing/pdf.ts @@ -174,6 +174,8 @@ export interface StrokeStyle { width: number; dash?: number[]; gray?: number; + /** Colour (0-1 each), in place of gray. */ + rgb?: [number, number, number]; } /** A single-page vector PDF. */ @@ -186,7 +188,7 @@ export class PdfPage { private y(v: number) { return ((this.heightMm - v) * PT).toFixed(3); } private style(s: StrokeStyle) { - this.ops.push(`${(s.width * PT).toFixed(3)} w`, `[${(s.dash ?? []).map((d) => (d * PT).toFixed(2)).join(' ')}] 0 d`, `${(s.gray ?? 0).toFixed(3)} G`, '1 J 1 j'); + this.ops.push(`${(s.width * PT).toFixed(3)} w`, `[${(s.dash ?? []).map((d) => (d * PT).toFixed(2)).join(' ')}] 0 d`, s.rgb ? `${s.rgb.map((c) => c.toFixed(3)).join(' ')} RG` : `${(s.gray ?? 0).toFixed(3)} G`, '1 J 1 j'); } /** Strokes SVG path data transformed by sheet = (x * s + tx, y * s + ty). */ @@ -215,23 +217,24 @@ export class PdfPage { } /** Filled triangle (arrowheads). */ - triangle(a: [number, number], b: [number, number], c: [number, number]) { - this.ops.push('0 g', `${this.x(a[0])} ${this.y(a[1])} m ${this.x(b[0])} ${this.y(b[1])} l ${this.x(c[0])} ${this.y(c[1])} l h f`); + triangle(a: [number, number], b: [number, number], c: [number, number], rgb?: [number, number, number]) { + this.ops.push(rgb ? `${rgb.map((v) => v.toFixed(3)).join(' ')} rg` : '0 g', `${this.x(a[0])} ${this.y(a[1])} m ${this.x(b[0])} ${this.y(b[1])} l ${this.x(c[0])} ${this.y(c[1])} l h f`); } /** Text with its baseline at (x, y); anchor start, middle or end. */ - text(str: string, x: number, y: number, sizeMm: number, opts: { bold?: boolean; anchor?: 'start' | 'middle' | 'end'; rotate?: number } = {}) { + text(str: string, x: number, y: number, sizeMm: number, opts: { bold?: boolean; anchor?: 'start' | 'middle' | 'end'; rotate?: number; rgb?: [number, number, number] } = {}) { const size = sizeMm * PT; const w = textWidth(str, sizeMm, opts.bold); const dx = opts.anchor === 'middle' ? -w / 2 : opts.anchor === 'end' ? -w : 0; const esc = pdfString(str); const font = opts.bold ? '/F2' : '/F1'; + const fill = opts.rgb ? `${opts.rgb.map((v) => v.toFixed(3)).join(' ')} rg` : '0 g'; if (opts.rotate) { const r = (opts.rotate * Math.PI) / 180; const c = Math.cos(r), s = Math.sin(r); const px = x + dx * c, py = y - dx * s; - this.ops.push('0 g', 'BT', `${font} ${size.toFixed(2)} Tf`, `${c.toFixed(4)} ${s.toFixed(4)} ${(-s).toFixed(4)} ${c.toFixed(4)} ${this.x(px)} ${this.y(py)} Tm`, `(${esc}) Tj`, 'ET'); - } else this.ops.push('0 g', 'BT', `${font} ${size.toFixed(2)} Tf`, `${this.x(x + dx)} ${this.y(y)} Td`, `(${esc}) Tj`, 'ET'); + this.ops.push(fill, 'BT', `${font} ${size.toFixed(2)} Tf`, `${c.toFixed(4)} ${s.toFixed(4)} ${(-s).toFixed(4)} ${c.toFixed(4)} ${this.x(px)} ${this.y(py)} Tm`, `(${esc}) Tj`, 'ET'); + } else this.ops.push(fill, 'BT', `${font} ${size.toFixed(2)} Tf`, `${this.x(x + dx)} ${this.y(y)} Td`, `(${esc}) Tj`, 'ET'); } /** Serialises the document. */ diff --git a/src/parametric/src/drawing/sheet.ts b/src/parametric/src/drawing/sheet.ts index 5be79672dd..b52beff5be 100644 --- a/src/parametric/src/drawing/sheet.ts +++ b/src/parametric/src/drawing/sheet.ts @@ -2,10 +2,18 @@ // and a display list (lines, paths, text) that renders identically to SVG // (on screen and export) and PDF. -import type { ProjectionResult } from '../kernel/protocol'; +import type { EdgeInfo, ProjectionResult } from '../kernel/protocol'; import { type Vec3, cross, normalize } from '../math/vec'; -import type { DrawingDoc, DrawingView, DrawingViewKind, SheetSize } from '../model/types'; +import { bendNote } from '../model/flat-pattern'; +import type { DrawingBom, DrawingCutList, DrawingDoc, DrawingView, DrawingViewKind, SheetSize } from '../model/types'; +import { + type AnnoFormat, type Geo, type HoleSpec, type Placement, DANGER, DIM_TEXT_SIZE, NOTE_SIZE, drawCenterMark, drawCenterline, drawCuttingLine, + drawDetailCircle, drawDimension, drawNote, drawViewArrow, holeCalloutText, measure, resolveRef, +} from './annotate'; +import type { FlatProjection } from './flat'; import { PdfPage, textWidth } from './pdf'; +import { type TableSpec, balloonTip, drawBalloon, drawTable } from './tables'; +import { type Prim, type ResolvedView, centerMarks, clipToCircle, flattenPath, hatch, holeAxes, polyPath, resolveViews, standardKindOf, viewPrims } from './views'; /** Portrait sizes in millimetres. */ export const SHEETS: Record = { @@ -15,11 +23,14 @@ export const SHEETS: Record = { A1: [594, 841], Letter: [215.9, 279.4], Tabloid: [279.4, 431.8], + 'ANSI C': [431.8, 558.8], + 'ANSI D': [558.8, 863.6], }; export const SHEET_LABELS: Record = { A4: 'A4 (297 x 210 mm)', A3: 'A3 (420 x 297 mm)', A2: 'A2 (594 x 420 mm)', A1: 'A1 (841 x 594 mm)', Letter: 'Letter (11 x 8.5 in)', Tabloid: 'Tabloid (17 x 11 in)', + 'ANSI C': 'ANSI C (22 x 17 in)', 'ANSI D': 'ANSI D (34 x 22 in)', }; export function sheetDims(d: Pick): { w: number; h: number } { @@ -73,7 +84,11 @@ export const TITLE_H = 32; * Standard three views (third-angle: top above front, right to the right) * plus an isometric view, at the largest standard scale that fits. */ -export function standardLayout(sheet: { w: number; h: number }, min: Vec3, max: Vec3): { scale: number; views: Omit[] } { +/** + * `bottom` is the height kept free along the bottom of the sheet (the title block's, and with + * a bill of materials on it, the table's too). + */ +export function standardLayout(sheet: { w: number; h: number }, min: Vec3, max: Vec3, bottom = TITLE_H): { scale: number; views: Omit[] } { const f = projectedSize('front', min, max), t = projectedSize('top', min, max), r = projectedSize('right', min, max), i = projectedSize('isometric', min, max); const c1 = Math.max(f[0], t[0]), c2 = Math.max(r[0], i[0]); const r1 = Math.max(t[1], i[1]), r2 = Math.max(f[1], r[1]); @@ -83,7 +98,7 @@ export function standardLayout(sheet: { w: number; h: number }, min: Vec3, max: const gap = 15; const top = 5, below = (3 * gap - top) / 2; const availW = sheet.w - 2 * MARGIN - 3 * gap; - const availH = sheet.h - 2 * MARGIN - TITLE_H - 3 * gap; + const availH = sheet.h - 2 * MARGIN - bottom - 3 * gap; const fit = Math.min(availW / Math.max(c1 + c2, 1e-6), availH / Math.max(r1 + r2, 1e-6)); const scale = STANDARD_SCALES.find((s) => s <= fit) ?? STANDARD_SCALES[STANDARD_SCALES.length - 1]; const x1 = MARGIN + gap + (c1 * scale) / 2; @@ -115,6 +130,17 @@ export function placeView( dims: boolean, others: { frame: ViewFrame; dims: boolean }[], ): [number, number] { + return freeSpot(sheet, vw, vh, dims, others) ?? [sheet.w / 2, sheet.h / 2]; +} + +/** The spot placeView finds, null when there is none. */ +export function freeSpot( + sheet: { w: number; h: number }, + vw: number, + vh: number, + dims: boolean, + others: { frame: ViewFrame; dims: boolean }[], +): [number, number] | null { const room = (x0: number, y0: number, x1: number, y1: number, d: boolean): Box => [x0 - (d ? DIM_LEFT : 2), y0 - 2, x1 + 2, y1 + (d ? 18 : 9)]; const taken = others.map(({ frame: f, dims: d }) => room(f.x0, f.y0, f.x1, f.y1, d)); @@ -128,17 +154,100 @@ export function placeView( if (b[2] <= w - MARGIN && b[3] <= h - MARGIN && !overlaps(b)) return [x, y]; } } - return [w / 2, h / 2]; + return null; +} + +/** + * Changes the projection angle of a drawing so every view still shows what it showed: the + * standard views beside a front view (top and bottom above or below it, left and right beside + * it, and an isometric view in the row of a top or bottom view) and projected views move to + * the other side of their parent at the same distance; section and auxiliary views keep their + * place and look the same way (their line turns round, which first angle reads the other way). + * The views that moved, with the views aligned to them, then slide together to stay on the + * sheet and clear of the title block. `frameOf` gives a view's frame where it is now. + */ +export function switchProjection(d: DrawingDoc, to: 'first' | 'third', frameOf: (v: DrawingView) => ViewFrame | undefined) { + if ((d.projection ?? 'third') === to) return; + const frames = new Map(d.views.map((v) => [v.id, frameOf(v)])); + const old = new Map(d.views.map((v) => [v.id, [v.x, v.y] as [number, number]])); + d.projection = to; + const byId = new Map(d.views.map((v) => [v.id, v])); + const moved = new Set(); + const isModel = (v: DrawingView) => (v.type ?? 'model') === 'model'; + const near = (a: number, b: number) => Math.abs(a - b) < 0.5; + for (const f of d.views.filter((v) => isModel(v) && v.kind === 'front')) { + const rows = new Set(); + for (const v of d.views) { + if (!isModel(v) || moved.has(v.id) || v === f) continue; + if ((v.kind === 'top' || v.kind === 'bottom') && near(v.x, f.x)) { rows.add(v.y); v.y = 2 * f.y - v.y; moved.add(v.id); moved.add(f.id); } + else if ((v.kind === 'left' || v.kind === 'right') && near(v.y, f.y)) { v.x = 2 * f.x - v.x; moved.add(v.id); moved.add(f.id); } + } + for (const v of d.views) if (isModel(v) && v.kind === 'isometric' && !moved.has(v.id) && [...rows].some((y) => near(v.y, y))) { v.y = 2 * f.y - v.y; moved.add(v.id); } + } + // Projected views, each after its parent: the other side, at the same distance. + const flip: Record = { left: 'right', right: 'left', above: 'below', below: 'above' }; + const done = new Set(); + const visit = (v: DrawingView, depth: number) => { + if (done.has(v.id) || depth > 32) return; + done.add(v.id); + const p = v.parent ? byId.get(v.parent) : undefined; + if (p) visit(p, depth + 1); + if (v.type === 'section' || v.type === 'auxiliary') { + if (v.line) v.line = [v.line[2], v.line[3], v.line[0], v.line[1]]; + return; + } + if (v.type !== 'projected' || !p) return; + const [px, py] = old.get(p.id)!; + const side = v.side ?? 'right'; + v.side = flip[side]; + if (side === 'left' || side === 'right') { v.x = 2 * p.x - (v.x - px + p.x); v.y += p.y - py; } + else { v.y = 2 * p.y - (v.y - py + p.y); v.x += p.x - px; } + moved.add(v.id); + }; + for (const v of d.views) visit(v, 0); + if (!moved.size) return; + // With the views aligned to those that moved (they move together when dragged too). + const group = new Set(moved); + for (let grew = true; grew;) { + grew = false; + for (const v of d.views) { + if (group.has(v.id) || !v.parent || !group.has(v.parent)) continue; + const aligned = v.type === 'projected' || ((v.type === 'section' || v.type === 'auxiliary') && !!v.line && (v.line[0] === v.line[2] || v.line[1] === v.line[3])); + if (aligned) { group.add(v.id); grew = true; } + } + } + const { w, h } = sheetDims(d); + const boxes: Box[] = []; + for (const id of group) { + const v = byId.get(id)!, f = frames.get(id), o = old.get(id)!; + if (!f) continue; + const dx = v.x - o[0], dy = v.y - o[1]; + const dims = hasDims(v); + boxes.push([f.x0 + dx - (dims ? DIM_LEFT : 0), f.y0 + dy, f.x1 + dx, f.y1 + dy + (dims ? DIM_BELOW + 8 : 9)]); + } + if (!boxes.length) return; + const U: Box = [Math.min(...boxes.map((b) => b[0])), Math.min(...boxes.map((b) => b[1])), Math.max(...boxes.map((b) => b[2])), Math.max(...boxes.map((b) => b[3]))]; + const fit = (lo: number, hi: number, min: number, max: number) => (lo < min ? min - lo : hi > max ? Math.max(max - hi, min - lo) : 0); + const sx = fit(U[0], U[2], MARGIN, w - MARGIN); + let sy = fit(U[1], U[3], MARGIN, h - MARGIN); + // Up, clear of the title block, as far as the top border allows. + const tb = titleBlockSize(d); + const T: Box = [w - MARGIN - tb.w, h - MARGIN - tb.h, w - MARGIN, h - MARGIN]; + const over = Math.max(0, ...boxes.filter((b) => b[0] + sx < T[2] && b[2] + sx > T[0] && b[1] + sy < T[3] && b[3] + sy > T[1]).map((b) => b[3] + sy - T[1])); + sy -= Math.min(over, Math.max(0, U[1] + sy - MARGIN)); + if (!sx && !sy) return; + for (const id of group) { const v = byId.get(id)!; v.x += sx; v.y += sy; } } // ---------- display list ---------- export type Item = - | { t: 'path'; d: string; tx: number; ty: number; s: number; w: number; dash?: number[]; view?: string } - | { t: 'line'; x1: number; y1: number; x2: number; y2: number; w: number; dash?: number[] } + | { t: 'path'; d: string; tx: number; ty: number; s: number; w: number; dash?: number[]; view?: string; color?: string } + | { t: 'line'; x1: number; y1: number; x2: number; y2: number; w: number; dash?: number[]; color?: string } | { t: 'rect'; x: number; y: number; w: number; h: number; sw: number } - | { t: 'tri'; a: [number, number]; b: [number, number]; c: [number, number] } - | { t: 'text'; s: string; x: number; y: number; size: number; bold?: boolean; anchor?: 'start' | 'middle' | 'end'; rotate?: number }; + | { t: 'tri'; a: [number, number]; b: [number, number]; c: [number, number]; color?: string } + | { t: 'circle'; cx: number; cy: number; r: number; w: number; dash?: number[]; color?: string } + | { t: 'text'; s: string; x: number; y: number; size: number; bold?: boolean; anchor?: 'start' | 'middle' | 'end'; rotate?: number; color?: string }; export interface SheetInfo { partName: string; @@ -146,6 +255,16 @@ export interface SheetInfo { units: string; date: string; formatLength: (mm: number) => string; + /** Model edges of a view's source, for dimensions and centre marks (absent: none drawn). */ + edges?: (source: string) => EdgeInfo[]; + /** Lengths with a dimension's own decimals, and angles (absent: formatLength and 2 decimals). */ + format?: AnnoFormat; + /** The hole a circular edge belongs to, for hole callouts. */ + holeOf?: (edge: string) => HoleSpec | null; + /** What a bill of materials or cut list table lists (null: there is nothing it could list). */ + table?: (a: DrawingBom | DrawingCutList) => TableSpec | null; + /** The item number of the component or member an edge of a source belongs to (balloons). */ + itemOf?: (source: string, edge: string) => number | null; } export interface ViewFrame { @@ -156,33 +275,99 @@ export interface ViewFrame { y1: number; } +/** Where a view is drawn: sheet = view coordinates * s + (tx, ty). */ +export interface ViewPlacement { + r: ResolvedView; + tx: number; + ty: number; + s: number; + frame: ViewFrame; + /** The model edges it shows (when the sheet was given them). */ + prims: Prim[]; +} + const MIN_TEXT = 1.8; const VISIBLE_W = 0.35; const HIDDEN_W = 0.18; const THIN = 0.18; +export const HATCH_SPACING = 3; + +/** The label under a view. */ +export function viewCaption(d: DrawingDoc, r: ResolvedView): string { + const v = r.v; + const scale = Math.abs(r.scale - d.scale) > 1e-12 ? ` SCALE ${scaleLabel(r.scale)}` : ''; + const letter = (v.label ?? '').toUpperCase(); + switch (r.type) { + case 'section': return `SECTION ${letter || 'A'}-${letter || 'A'}${scale}`; + case 'detail': return `DETAIL ${letter || 'A'}${scale}`; + case 'auxiliary': return `${letter ? `VIEW ${letter}` : 'AUXILIARY VIEW'}${scale}`; + case 'flat': return `${letter || 'FLAT PATTERN'}${scale}`; + case 'projected': { + if (letter) return letter + scale; + const k = standardKindOf(r.o); + return `${k ? VIEW_LABELS[k as DrawingViewKind].toUpperCase() : 'PROJECTED VIEW'}${scale}`; + } + default: return `${letter || VIEW_LABELS[v.kind].toUpperCase()}${scale}`; + } +} /** Builds the sheet's display list. Also returns each view's frame on the sheet. */ -export function buildSheet(d: DrawingDoc, projections: Map, info: SheetInfo): { items: Item[]; frames: ViewFrame[]; w: number; h: number } { +export function buildSheet(d: DrawingDoc, projections: Map, info: SheetInfo): { + items: Item[]; frames: ViewFrame[]; w: number; h: number; + /** Where each projected view is drawn. */ + placements: Map; + /** Boxes of the annotations, for picking. */ + annos: { id: string; box: Box }[]; + /** What does not fit on the sheet (said in red on it too). */ + warnings: string[]; +} { const { w, h } = sheetDims(d); const items: Item[] = []; const frames: ViewFrame[] = []; items.push({ t: 'rect', x: MARGIN, y: MARGIN, w: w - 2 * MARGIN, h: h - 2 * MARGIN, sw: 0.5 }); - const s = d.scale; - const placed: { v: DrawingView; pr: ProjectionResult; tx: number; ty: number; f: ViewFrame }[] = []; - for (const v of d.views) { + const resolved = resolveViews(d); + const placed: { v: DrawingView; r: ResolvedView; pr: ProjectionResult; tx: number; ty: number; s: number; f: ViewFrame }[] = []; + const placements = new Map(); + const place = (v: DrawingView, depth = 0): ViewPlacement | undefined => { + const done = placements.get(v.id); + if (done || depth > 32) return done; + const r = resolved.get(v.id); const pr = projections.get(v.id); - if (!pr || !pr.bounds) continue; + if (!r || !pr || !pr.bounds) return undefined; + const s = r.scale; const [bx0, by0, bx1, by1] = pr.bounds; - const tx = v.x - (s * (bx0 + bx1)) / 2; - const ty = v.y - (s * (by0 + by1)) / 2; - const f = { id: v.id, x0: tx + bx0 * s, y0: ty + by0 * s, x1: tx + bx1 * s, y1: ty + by1 * s }; - frames.push(f); - placed.push({ v, pr, tx, ty, f }); + let tx: number, ty: number, f: ViewFrame; + if (r.type === 'detail' && r.clip) { + tx = v.x - s * r.clip.c[0]; + ty = v.y - s * r.clip.c[1]; + const R = r.clip.r * s; + f = { id: v.id, x0: v.x - R, y0: v.y - R, x1: v.x + R, y1: v.y + R }; + } else { + tx = v.x - (s * (bx0 + bx1)) / 2; + ty = v.y - (s * (by0 + by1)) / 2; + // Aligned with its parent: the axis they share lines up (the same scale, so the same offset). + const pv = r.align && r.parent ? d.views.find((q) => q.id === r.parent!.v.id) : undefined; + const pp = pv ? place(pv, depth + 1) : undefined; + if (pp && r.align === 'y') ty = pp.ty; + if (pp && r.align === 'x') tx = pp.tx; + f = { id: v.id, x0: tx + bx0 * s, y0: ty + by0 * s, x1: tx + bx1 * s, y1: ty + by1 * s }; + } + const edges = info.edges?.(r.source); + const p: ViewPlacement = { r, tx, ty, s, frame: f, prims: edges ? viewPrims(r, edges) : [] }; + placements.set(v.id, p); + return p; + }; + for (const v of d.views) { + const p = place(v); + if (!p) continue; + frames.push(p.frame); + placed.push({ v, r: p.r, pr: projections.get(v.id)!, tx: p.tx, ty: p.ty, s: p.s, f: p.frame }); } // What a view label must stay clear of: every view with its dimensions, // the labels already placed and the title block. const taken: Box[] = placed.map(({ v, f }) => (hasDims(v) ? [f.x0 - DIM_LEFT, f.y0, f.x1, f.y1 + DIM_BELOW] : [f.x0, f.y0, f.x1, f.y1])); - taken.push([w - MARGIN - TITLE_W, h - MARGIN - TITLE_H, w - MARGIN, h - MARGIN]); + const tb = titleBlockSize(d); + taken.push([w - MARGIN - tb.w, h - MARGIN - tb.h, w - MARGIN, h - MARGIN]); // Dimensions first: a value moved outside its lines is something labels must avoid too. const dims = placed.map(({ v, pr, f }) => { const out: Item[] = []; @@ -192,26 +377,261 @@ export function buildSheet(d: DrawingDoc, projections: Map j !== i), w, h); + for (const [i, { v, r, pr, tx, ty, s, f }] of placed.entries()) { + if (r.type === 'detail' && r.clip) { + // The parent's lines, magnified and cut off at the circle. + const c: [number, number] = [v.x, v.y], R = r.clip.r * s; + const clipped = (paths: string[]) => paths.flatMap((p) => flattenPath(p, tx, ty, s, 0.02)).flatMap((pl) => clipToCircle(pl, c, R)).map(polyPath); + if (v.hidden) for (const p of clipped(pr.hidden)) items.push({ t: 'path', d: p, tx: 0, ty: 0, s: 1, w: HIDDEN_W, dash: [1.6, 0.8], view: v.id }); + for (const p of clipped(pr.visible)) items.push({ t: 'path', d: p, tx: 0, ty: 0, s: 1, w: VISIBLE_W, view: v.id }); + if (pr.cut?.length) { + const segs = hatchGroups(pr).flatMap(([cut, angle]) => hatch(cut.map((pl) => pl.map((q, k) => (k % 2 ? q * s + ty : q * s + tx))), angle, HATCH_SPACING)) + .flatMap(([x1, y1, x2, y2]) => clipToCircle([[x1, y1], [x2, y2]], c, R)).map(polyPath); + if (segs.length) items.push({ t: 'path', d: segs.join(''), tx: 0, ty: 0, s: 1, w: THIN, view: v.id }); + } + // A detail of a flat pattern shows its bend lines too. + if (r.parent?.type === 'flat') { + for (const b of (pr as FlatProjection).bends ?? []) { + for (const seg of clipToCircle([[tx + b.a[0] * s, ty + b.a[1] * s], [tx + b.b[0] * s, ty + b.b[1] * s]], c, R)) { + items.push({ t: 'line', x1: seg[0][0], y1: seg[0][1], x2: seg[seg.length - 1][0], y2: seg[seg.length - 1][1], w: THIN, dash: b.up ? [4, 1.5] : [4, 1.2, 1, 1.2] }); + } + } + } + items.push({ t: 'circle', cx: c[0], cy: c[1], r: R, w: THIN }); + } else { + if (v.hidden) for (const p of pr.hidden) items.push({ t: 'path', d: p, tx, ty, s, w: HIDDEN_W, dash: [1.6, 0.8], view: v.id }); + for (const p of pr.visible) items.push({ t: 'path', d: p, tx, ty, s, w: VISIBLE_W, view: v.id }); + if (pr.cut?.length) { + for (const [cut, angle] of hatchGroups(pr)) { + const segs = hatch(cut.map((pl) => pl.map((q, k) => (k % 2 ? q * s + ty : q * s + tx))), angle, HATCH_SPACING); + if (segs.length) items.push({ t: 'path', d: segs.map(([x1, y1, x2, y2]) => `M${+x1.toFixed(4)} ${+y1.toFixed(4)}L${+x2.toFixed(4)} ${+y2.toFixed(4)}`).join(''), tx: 0, ty: 0, s: 1, w: THIN, view: v.id }); + } + } + if (r.type === 'flat') drawBendLines(items, (pr as FlatProjection).bends ?? [], tx, ty, s, info.formatLength); + } + const label = viewLabel(viewCaption(d, r), f, hasDims(v), taken.filter((_, j) => j !== i), w, h); items.push(label.item); taken.push(label.box); + const notes = r.type === 'flat' ? (pr as FlatProjection).notes : undefined; + if (notes?.length) taken.push(drawFlatNotes(items, notes, f, hasDims(v), label.box, w)); items.push(...dims[i]); } - titleBlock(items, w, h, d, info); - return { items, frames, w, h }; + // A flat pattern view of a part that cannot be flattened says why where it would be. + for (const v of d.views) { + const pr = projections.get(v.id) as FlatProjection | undefined; + if (v.type === 'flat' && pr?.error && !placements.has(v.id)) drawNote(items, `FLAT PATTERN: ${pr.error}`, [v.x - 30, v.y], 2.5, undefined, DANGER); + } + // A view with nothing to show (a section whose cutting line misses the part) says so where it + // is, and can still be selected, moved and deleted there. + for (const v of d.views) { + const r = resolved.get(v.id), pr = projections.get(v.id); + if (!r || !pr || pr.bounds || placements.has(v.id) || (pr as FlatProjection).error) continue; + const text = `${viewCaption(d, r).replace(/\s+SCALE .*$/, '')}: ${r.type === 'section' ? 'THE CUTTING LINE MISSES THE PART' : 'NOTHING TO SHOW'}`; + const box = drawNote(items, text, [v.x - textWidth(text, 2.5) / 2, v.y], 2.5, undefined, DANGER); + frames.push({ id: v.id, x0: box[0], y0: box[1], x1: box[2], y1: box[3] }); + } + const fmt: AnnoFormat = info.format ?? { length: (mm) => info.formatLength(mm), angle: (deg, dec) => `${deg.toFixed(dec ?? 2)}°` }; + // What sections and details leave on their parents (also while the view itself is empty or still projecting). + for (const v of d.views) { + const r = resolved.get(v.id); + const pp = r?.parent && placements.get(r.parent.v.id); + if (!r || !pp) continue; + const T = (q: [number, number]): [number, number] => [pp.tx + q[0] * pp.s, pp.ty + q[1] * pp.s]; + const letter = (v.label || 'A').toUpperCase(); + if (r.type === 'section' && v.line && r.toward) { + const first = d.projection === 'first'; + const sight: [number, number] = first ? r.toward : [-r.toward[0], -r.toward[1]]; + drawCuttingLine(items, T([v.line[0], v.line[1]]), T([v.line[2], v.line[3]]), sight, letter); + } else if (r.type === 'auxiliary' && v.line && r.toward) { + const first = d.projection === 'first'; + const sight: [number, number] = first ? r.toward : [-r.toward[0], -r.toward[1]]; + drawViewArrow(items, T([(v.line[0] + v.line[2]) / 2, (v.line[1] + v.line[3]) / 2]), sight, letter); + } else if (r.type === 'detail' && r.clip) drawDetailCircle(items, T(r.clip.c), r.clip.r * pp.s, letter); + } + // Centre marks and hole axes of the views that show them. + for (const { v, r } of placed) { + if (!v.centerMarks) continue; + const p = placements.get(v.id)!; + const T = (q: [number, number]): [number, number] => [p.tx + q[0] * p.s, p.ty + q[1] * p.s]; + const inside = (q: [number, number]) => !r.clip || Math.hypot(q[0] - v.x, q[1] - v.y) <= r.clip.r * p.s; + for (const m of centerMarks(p.prims)) if (inside(T(m.c))) drawCenterMark(items, T(m.c), m.r * p.s); + const edges = info.edges?.(r.source); + if (edges && !r.clip) for (const a of holeAxes(r, edges)) drawCenterline(items, T(a.a), T(a.b)); + } + const warnings: string[] = []; + const annos = drawAnnotations(items, d, placements, info, fmt, warnings); + if (d.titleBlock === 'full') titleBlockFull(items, w, h, d, info); + else titleBlock(items, w, h, d, info); + return { items, frames, w, h, placements, annos, warnings }; +} + +/** Draws the annotations; returns their boxes. */ +function drawAnnotations(items: Item[], d: DrawingDoc, placements: Map, info: SheetInfo, fmt: AnnoFormat, warnings: string[]): { id: string; box: Box }[] { + const out: { id: string; box: Box }[] = []; + for (const a of d.annotations ?? []) { + const p = a.view ? placements.get(a.view) : undefined; + // An annotation of a view not drawn (still being projected, or its part has no solid) waits for it. + if (a.view && !p) continue; + const pl: Placement = p ? { T: (q) => [p.tx + q[0] * p.s, p.ty + q[1] * p.s], s: p.s } : { T: (q) => q, s: 1 }; + const prims = p?.prims ?? []; + switch (a.type) { + case 'dimension': { + const gs = a.refs.map((ref) => resolveRef(prims, ref)); + const m = gs.every((g) => !!g) && gs.length ? measure(a.kind, gs as Geo[]) : null; + out.push({ id: a.id, box: drawDimension(items, a, m, pl, fmt) }); + break; + } + case 'note': { + const at = pl.T(a.at); + out.push({ id: a.id, box: drawNote(items, a.text, at, a.size ?? NOTE_SIZE, a.leader ? pl.T(a.leader) : undefined) }); + break; + } + case 'centerMark': { + const g = resolveRef(prims, { edge: a.ref.edge, at: 'edge' }); + if (g?.kind === 'circle') { + const c = pl.T(g.c); + drawCenterMark(items, c, g.r * pl.s); + out.push({ id: a.id, box: [c[0] - 2, c[1] - 2, c[0] + 2, c[1] + 2] }); + } else { + const at = p ? [p.frame.x0, p.frame.y0 - 2] as [number, number] : [0, 0] as [number, number]; + out.push({ id: a.id, box: drawNote(items, 'CENTER MARK? (missing)', at, 2.5, undefined, DANGER) }); + } + break; + } + case 'centerline': { + const g1 = resolveRef(prims, a.refs[0]), g2 = resolveRef(prims, a.refs[1]); + if (g1?.kind === 'line' && g2?.kind === 'line') { + // Midway between the two edges, over the length they share. + const u = (([dx, dy]) => { const l = Math.hypot(dx, dy) || 1; return [dx / l, dy / l] as [number, number]; })([g1.b[0] - g1.a[0], g1.b[1] - g1.a[1]]); + const t = (q: [number, number]) => q[0] * u[0] + q[1] * u[1]; + const n: [number, number] = [-u[1], u[0]]; + const o1 = g1.a[0] * n[0] + g1.a[1] * n[1], o2 = g2.a[0] * n[0] + g2.a[1] * n[1], om = (o1 + o2) / 2; + const ts = [t(g1.a), t(g1.b), t(g2.a), t(g2.b)]; + const lo = Math.max(Math.min(ts[0], ts[1]), Math.min(ts[2], ts[3])), hi = Math.min(Math.max(ts[0], ts[1]), Math.max(ts[2], ts[3])); + const [t0, t1] = hi > lo ? [lo, hi] : [Math.min(...ts), Math.max(...ts)]; + const at = (tt: number): [number, number] => [u[0] * tt + n[0] * om, u[1] * tt + n[1] * om]; + const A = pl.T(at(t0)), B = pl.T(at(t1)); + drawCenterline(items, A, B); + out.push({ id: a.id, box: [Math.min(A[0], B[0]) - 1, Math.min(A[1], B[1]) - 1, Math.max(A[0], B[0]) + 1, Math.max(A[1], B[1]) + 1] }); + } else { + const at = p ? [p.frame.x0, p.frame.y0 - 2] as [number, number] : [0, 0] as [number, number]; + out.push({ id: a.id, box: drawNote(items, 'CENTERLINE? (missing)', at, 2.5, undefined, DANGER) }); + } + break; + } + case 'holeCallout': { + const g = resolveRef(prims, { edge: a.ref.edge, at: 'edge' }); + const spec = info.holeOf?.(a.ref.edge) ?? null; + const at = pl.T(a.at); + if (g?.kind === 'circle') { + const c = pl.T(g.c), r = g.r * pl.s; + const text = spec ? holeCalloutText(spec, fmt) : `Ø${fmt.length(2 * g.r)}`; + const dx = at[0] - c[0], dy = at[1] - c[1], l = Math.hypot(dx, dy) || 1; + const tip: [number, number] = [c[0] + (dx / l) * r, c[1] + (dy / l) * r]; + out.push({ id: a.id, box: drawNote(items, text, at, DIM_TEXT_SIZE, tip) }); + } else out.push({ id: a.id, box: drawNote(items, 'HOLE? (missing)', at, DIM_TEXT_SIZE, undefined, DANGER) }); + break; + } + case 'balloon': { + const g = resolveRef(prims, a.ref); + const at = pl.T(a.at); + const n = a.item ?? (p ? info.itemOf?.(p.r.source, a.ref.edge) : null) ?? null; + const ok = !!g && n !== null; + out.push({ id: a.id, box: drawBalloon(items, n === null ? '?' : String(n), at, g ? pl.T(balloonTip(g, a.at, a.t)) : null, ok ? undefined : DANGER) }); + break; + } + case 'bom': + case 'cutList': { + const t = info.table?.(a); + if (t) { + // Split into columns to stay on the sheet; one that still does not fit says so. + const { w, h } = sheetDims(d); + const drawn = drawTable(items, t, a.at, a.anchor, { top: MARGIN, bottom: h - MARGIN, left: MARGIN, right: w - MARGIN }); + if (!drawn.fits) { + const what = a.type === 'bom' ? 'The bill of materials' : 'The cut list'; + warnings.push(`${what} does not fit on this sheet: use a larger sheet.`); + const text = `${what.slice(4).toUpperCase()} DOES NOT FIT ON THIS SHEET: USE A LARGER SHEET`; + const tw = textWidth(text, 2.5); + drawNote(items, text, [Math.max(MARGIN + 1, Math.min(drawn.box[2] - tw, w - MARGIN - 1 - tw)), Math.max(MARGIN + 4, Math.min(drawn.box[1] - 1.5, h - MARGIN - 1))], 2.5, undefined, DANGER); + } + out.push({ id: a.id, box: drawn.box }); + } else { + const text = a.type === 'bom' ? 'BILL OF MATERIALS? (no assembly)' : 'CUT LIST? (no structural members)'; + const at: [number, number] = a.anchor === 'bottomRight' ? [a.at[0] - textWidth(text, 2.5), a.at[1] - 1] : [a.at[0], a.at[1] + 3]; + out.push({ id: a.id, box: drawNote(items, text, at, 2.5, undefined, DANGER) }); + } + break; + } + } + } + return out; } type Box = [x0: number, y0: number, x1: number, y1: number]; +/** Hatch angles of an assembly section's components in turn (a part's cut is hatched at 45°). */ +const HATCH_ANGLES = [45, 135, 60, 120, 30, 150]; + +/** A section's cut outlines by component, each with its hatch angle. */ +function hatchGroups(pr: ProjectionResult): [number[][], number][] { + const cut = pr.cut ?? []; + const g = pr.cutGroups; + if (!g || g.length !== cut.length) return [[cut, 45]]; + const order = [...new Set(g)]; + return order.map((k, i) => [cut.filter((_, j) => g[j] === k), HATCH_ANGLES[i % HATCH_ANGLES.length]]); +} + +/** + * Bend centre lines of a flat pattern view (view coordinates placed by tx, ty, s): dashed for + * bends up, chain lines for bends down, each with its note ("UP 90° R 1") along its middle. + */ +function drawBendLines(items: Item[], bends: { a: [number, number]; b: [number, number]; up: boolean; angle: number; radius: number }[], tx: number, ty: number, s: number, fmt: (mm: number) => string) { + for (const b of bends) { + const A: [number, number] = [tx + b.a[0] * s, ty + b.a[1] * s], B: [number, number] = [tx + b.b[0] * s, ty + b.b[1] * s]; + items.push({ t: 'line', x1: A[0], y1: A[1], x2: B[0], y2: B[1], w: THIN, dash: b.up ? [4, 1.5] : [4, 1.2, 1, 1.2] }); + let ang = (Math.atan2(B[1] - A[1], B[0] - A[0]) * 180) / Math.PI; + // Never upside down; along a vertical line it reads upward. + if (ang >= 90 - 1e-9) ang -= 180; + if (ang < -90 - 1e-9) ang += 180; + const t = (ang * Math.PI) / 180; + // Above the line as it reads. + const m: [number, number] = [(A[0] + B[0]) / 2 + Math.sin(t) * 1.2, (A[1] + B[1]) / 2 - Math.cos(t) * 1.2]; + items.push({ t: 'text', s: bendNote({ up: b.up, angle: b.angle, radius: b.radius } as Parameters[0], fmt), x: m[0], y: m[1], size: 2.5, anchor: 'middle', rotate: ang || undefined }); + } +} + +/** + * What a flat pattern leaves out, in red above its view (below it, past its dimensions, when + * the view is at the top of the sheet), wrapped to the view's width (at least 90 mm) and kept + * on the sheet, so the drawing does not pass for the whole part. Returns its box. + */ +function drawFlatNotes(items: Item[], notes: string[], f: ViewFrame, dims: boolean, label: Box, sheetW: number): Box { + const size = 2; + const room = Math.min(Math.max(f.x1 - f.x0, 90), sheetW - 2 * MARGIN); + const lines: string[] = []; + for (const n of notes) { + let cur = ''; + for (const word of `NOTE: ${n}`.split(' ')) { + const next = cur ? `${cur} ${word}` : word; + if (cur && textWidth(next, size) > room) { lines.push(cur); cur = word; } else cur = next; + } + if (cur) lines.push(cur); + } + const width = Math.max(...lines.map((s) => textWidth(s, size))); + const x = Math.max(MARGIN + 1, Math.min(f.x0, sheetW - MARGIN - 1 - width)); + const above = f.y0 - 2 - (lines.length - 1) * size * 1.4; + // Above, clear of the label if it went there; else below the dimensions and the label. + const top = label[3] <= f.y0 ? Math.min(above, label[1] - 1 - (lines.length - 1) * size * 1.4) : above; + const y = top - size * 0.8 >= MARGIN + 1 ? top : Math.max(f.y1 + (dims ? DIM_BELOW : 0), label[1] >= f.y1 ? label[3] : -Infinity) + 1 + size; + return drawNote(items, lines.join('\n'), [x, y], size, undefined, DANGER); +} + const LABEL_SIZE = 2.6; /** How far a view's dimensions reach left of and below its outline. */ export const DIM_LEFT = 12; export const DIM_BELOW = 10.5; -const hasDims = (v: DrawingView) => v.dims && v.kind !== 'isometric'; +const hasDims = (v: DrawingView) => v.dims && v.kind !== 'isometric' && v.type !== 'detail'; /** * A view's label: centred below the view (past its width dimension) unless @@ -325,6 +745,87 @@ function titleBlock(items: Item[], w: number, h: number, d: DrawingDoc, info: Sh label('NOTES', c1, y + 2 * row); value(d.notes || '', c1, y + 2 * row, right - c1, 2.4); } +/** The title block's size on the sheet (the full one is as large as the basic one). */ +export function titleBlockSize(_d: DrawingDoc): { w: number; h: number } { + return { w: TITLE_W, h: TITLE_H }; +} + +/** Fits a value into a cell: long values shrink, down to a legible minimum, then are cut short. */ +function fitText(s: string, room: number, size: number, bold = false): { s: string; size: number } { + let fitted = s; + const w = textWidth(s, size, bold); + if (w > room) { + size = Math.max(MIN_TEXT, (size * room) / w); + if (textWidth(s, size, bold) > room + 1e-9) { + let n = s.length; + while (n > 0 && textWidth(`${s.slice(0, n).trimEnd()}…`, size, bold) > room) n--; + fitted = `${s.slice(0, n).trimEnd()}…`; + } + } + return { s: fitted, size }; +} + +/** + * The full title block: title, scale and sheet number; material, units, the projection + * symbol, date and revision; drawn by, sheet size and notes. + */ +function titleBlockFull(items: Item[], w: number, h: number, d: DrawingDoc, info: SheetInfo) { + const x = w - MARGIN - TITLE_W, y = h - MARGIN - TITLE_H; + const row = TITLE_H / 3; + const right = x + TITLE_W; + items.push({ t: 'rect', x, y, w: TITLE_W, h: TITLE_H, sw: 0.5 }); + const hl = (yy: number) => items.push({ t: 'line', x1: x, y1: yy, x2: right, y2: yy, w: 0.25 }); + const vl = (xx: number, y0: number, y1: number) => items.push({ t: 'line', x1: xx, y1: y0, x2: xx, y2: y1, w: 0.25 }); + hl(y + row); hl(y + 2 * row); + const c1 = x + 110, c2 = x + 56, c3 = x + 83, c4 = x + 140; + vl(c1, y, y + TITLE_H); + vl(c4, y, y + 2 * row); + vl(c2, y + row, y + TITLE_H); + vl(c3, y + row, y + 2 * row); + const label = (s: string, lx: number, ly: number) => items.push({ t: 'text', s, x: lx + 1.5, y: ly + 3, size: 1.8 }); + const value = (s: string, lx: number, ly: number, cellW: number, size = 3.2, bold = false) => { + const f = fitText(s, cellW - 3, size, bold); + items.push({ t: 'text', s: f.s, x: lx + 1.5, y: ly + row - 2, size: f.size, bold }); + }; + label('TITLE', x, y); value(d.title || info.partName, x, y, c1 - x, 4, true); + label('SCALE', c1, y); value(scaleLabel(d.scale), c1, y, c4 - c1); + label('SHEET', c4, y); value('1 OF 1', c4, y, right - c4, 2.8); + label('MATERIAL', x, y + row); value(info.material, x, y + row, c2 - x, 2.8); + label('UNITS', c2, y + row); value(info.units, c2, y + row, c3 - c2, 2.8); + label(d.projection === 'first' ? 'FIRST ANGLE' : 'THIRD ANGLE', c3, y + row); + projectionSymbol(items, (c3 + c1) / 2, y + row + row * 0.62, d.projection === 'first'); + label('DATE', c1, y + row); value(info.date, c1, y + row, c4 - c1, 2.8); + label('REV', c4, y + row); value(d.revision || '', c4, y + row, right - c4, 2.8); + label('DRAWN BY', x, y + 2 * row); value(d.drawnBy || '', x, y + 2 * row, c2 - x, 2.8); + label('SIZE', c2, y + 2 * row); value(`${d.sheet}${d.landscape ? '' : ' portrait'}`, c2, y + 2 * row, c1 - c2, 2.8); + label('NOTES', c1, y + 2 * row); value(d.notes || '', c1, y + 2 * row, right - c1, 2.4); +} + +/** + * The projection symbol, centred at (cx, cy): a truncated cone seen from the side and from + * its small end. Third angle: the side view left, its small end toward the end view on the + * right; first angle: the end view left, the side view right with its large end toward it. + */ +export function projectionSymbol(items: Item[], cx: number, cy: number, first: boolean) { + const D = 5, dd = 2.6, L = 5, gap = 3; + const total = L + gap + D; + const left = cx - total / 2; + const [tx, ex] = first ? [left + D + gap, left + D / 2] : [left, left + L + gap + D / 2]; + const w = 0.25; + // Side view: large end on the left, small end on the right. + const pts: [number, number][] = [[tx, cy - D / 2], [tx + L, cy - dd / 2], [tx + L, cy + dd / 2], [tx, cy + D / 2]]; + for (let i = 0; i < 4; i++) { + const a = pts[i], b = pts[(i + 1) % 4]; + items.push({ t: 'line', x1: a[0], y1: a[1], x2: b[0], y2: b[1], w }); + } + items.push({ t: 'circle', cx: ex, cy, r: D / 2, w }); + items.push({ t: 'circle', cx: ex, cy, r: dd / 2, w }); + // Centrelines. + items.push({ t: 'line', x1: tx - 1, y1: cy, x2: tx + L + 1, y2: cy, w: 0.13, dash: [2, 0.5, 0.5, 0.5] }); + items.push({ t: 'line', x1: ex - D / 2 - 1, y1: cy, x2: ex + D / 2 + 1, y2: cy, w: 0.13, dash: [2, 0.5, 0.5, 0.5] }); + items.push({ t: 'line', x1: ex, y1: cy - D / 2 - 1, x2: ex, y2: cy + D / 2 + 1, w: 0.13, dash: [2, 0.5, 0.5, 0.5] }); +} + // ---------- renderers ---------- /** @@ -352,23 +853,27 @@ export function toSvg(items: Item[], w: number, h: number, opts: { background?: if (v) parts.push(``); view = v; } + const col = (it as { color?: string }).color ?? ink; switch (it.t) { case 'path': - parts.push(``); + parts.push(``); break; case 'line': - parts.push(``); + parts.push(``); break; case 'rect': parts.push(``); break; + case 'circle': + parts.push(``); + break; case 'tri': - parts.push(``); + parts.push(``); break; case 'text': { const anchor = it.anchor === 'middle' ? 'middle' : it.anchor === 'end' ? 'end' : 'start'; const rot = it.rotate ? ` transform="rotate(${it.rotate} ${it.x} ${it.y})"` : ''; - parts.push(`${esc(it.s)}`); + parts.push(`${esc(it.s)}`); break; } } @@ -381,13 +886,24 @@ export function toSvg(items: Item[], w: number, h: number, opts: { background?: export function toPdf(items: Item[], w: number, h: number, title: string): Uint8Array { const pdf = new PdfPage(w, h); for (const it of items) { + const rgb = rgbOf((it as { color?: string }).color); switch (it.t) { - case 'path': pdf.path(it.d, it.tx, it.ty, it.s, { width: it.w, dash: it.dash }); break; - case 'line': pdf.line(it.x1, it.y1, it.x2, it.y2, { width: it.w, dash: it.dash }); break; + case 'path': pdf.path(it.d, it.tx, it.ty, it.s, { width: it.w, dash: it.dash, rgb }); break; + case 'line': pdf.line(it.x1, it.y1, it.x2, it.y2, { width: it.w, dash: it.dash, rgb }); break; case 'rect': pdf.rect(it.x, it.y, it.w, it.h, { width: it.sw }); break; - case 'tri': pdf.triangle(it.a, it.b, it.c); break; - case 'text': pdf.text(it.s, it.x, it.y, it.size, { bold: it.bold, anchor: it.anchor, rotate: it.rotate ? -it.rotate : undefined }); break; + case 'circle': pdf.path(circlePath(it.cx, it.cy, it.r), 0, 0, 1, { width: it.w, dash: it.dash, rgb }); break; + case 'tri': pdf.triangle(it.a, it.b, it.c, rgb); break; + case 'text': pdf.text(it.s, it.x, it.y, it.size, { bold: it.bold, anchor: it.anchor, rotate: it.rotate ? -it.rotate : undefined, rgb }); break; } } return pdf.build(title); } + +/** SVG path data of a whole circle (two half arcs). */ +export const circlePath = (cx: number, cy: number, r: number) => `M${cx + r} ${cy}A${r} ${r} 0 1 1 ${cx - r} ${cy}A${r} ${r} 0 1 1 ${cx + r} ${cy}`; + +/** A #rrggbb colour as PDF components. */ +function rgbOf(c: string | undefined): [number, number, number] | undefined { + const m = c ? /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(c) : null; + return m ? [parseInt(m[1], 16) / 255, parseInt(m[2], 16) / 255, parseInt(m[3], 16) / 255] : undefined; +} diff --git a/src/parametric/src/drawing/source.ts b/src/parametric/src/drawing/source.ts new file mode 100644 index 0000000000..e652eb5d6d --- /dev/null +++ b/src/parametric/src/drawing/source.ts @@ -0,0 +1,32 @@ +// Where a drawing view's geometry comes from. Every view names a source (absent: 'part', the +// open part's body). An open assembly registers 'assembly' and 'assembly:exploded': the +// combined placed solids to project, their named edges (component id + '#' + the part's edge +// name, as the assembly's graphics area names them, so dimensions and balloons can refer to +// them) and the bill of materials. A sheet metal part registers 'flat', its flat pattern. + +import type { EdgeInfo, ProjectionRequest, ProjectionResult } from '../kernel/protocol'; +import type { Vec3 } from '../math/vec'; + +export interface BomRow { + item: number; + /** Part number or name. */ + name: string; + description?: string; + material?: string; + qty: number; + /** Edge names of this row's components start with one of these (a balloon's reference finds its row by them). */ + prefixes: string[]; +} + +export interface DrawingSource { + /** Changes whenever the geometry changes (projections are cached until it does). */ + version(): number; + /** Bounding box of the geometry, null while there is none. */ + bbox(): { min: Vec3; max: Vec3 } | null; + /** Hidden-line projections (each request's id comes back on its result). */ + project(requests: ProjectionRequest[]): Promise; + /** Named model edges, in the same coordinates as the projections. */ + edges(): EdgeInfo[]; + /** Bill of materials rows (assemblies). */ + bom?(): BomRow[]; +} diff --git a/src/parametric/src/drawing/tables.ts b/src/parametric/src/drawing/tables.ts new file mode 100644 index 0000000000..23354c3f70 --- /dev/null +++ b/src/parametric/src/drawing/tables.ts @@ -0,0 +1,252 @@ +// Tables and balloons on drawing sheets: an assembly's bill of materials and a weldment's +// cut list as tables of fixed column widths (so a table keeps its place and size as its rows +// change), item balloons with their leaders, and where automatic balloons go around a view. + +import type { DrawingRef } from '../model/types'; +import type { Geo } from './annotate'; +import { textWidth } from './pdf'; +import type { Item } from './sheet'; +import type { BomRow } from './source'; +import type { P2, Prim } from './views'; + +type Box = [number, number, number, number]; +type Align = 'start' | 'middle' | 'end'; + +export interface TableSpec { + header: string[]; + /** Column widths in sheet millimetres. */ + widths: number[]; + rows: string[][]; + /** Alignment of each column's values (absent: start). */ + align?: Align[]; +} + +export const TABLE_ROW_H = 6; +export const TABLE_TEXT = 2.5; +const PAD = 1.2; +const MIN_TEXT = 1.6; + +export function tableSize(t: TableSpec): { w: number; h: number } { + return { w: t.widths.reduce((a, b) => a + b, 0), h: (t.rows.length + 1) * TABLE_ROW_H }; +} + +/** The top left corner of a table placed at `at` (its top left, or with 'bottomRight' its bottom right corner). */ +export function tableOrigin(t: TableSpec, at: P2, anchor?: 'bottomRight'): P2 { + if (anchor !== 'bottomRight') return at; + const { w, h } = tableSize(t); + return [at[0] - w, at[1] - h]; +} + +/** A value fitted to a cell: shrunk down to a legible size, then cut short. */ +export function fitCell(s: string, room: number, size: number, bold = false): { s: string; size: number } { + const w = textWidth(s, size, bold); + if (w <= room) return { s, size }; + size = Math.max(MIN_TEXT, (size * room) / w); + if (textWidth(s, size, bold) <= room + 1e-9) return { s, size }; + let n = s.length; + while (n > 0 && textWidth(`${s.slice(0, n).trimEnd()}…`, size, bold) > room) n--; + return { s: `${s.slice(0, n).trimEnd()}…`, size }; +} + +/** + * Where every cell of a table is: the column edges, the row edges (the header first) and each + * value's text position. Pure, for drawing and for tests. + */ +export function layoutTable(t: TableSpec, at: P2, anchor?: 'bottomRight') { + const [x0, y0] = tableOrigin(t, at, anchor); + const { w, h } = tableSize(t); + const cols = [x0]; + for (const cw of t.widths) cols.push(cols[cols.length - 1] + cw); + const rows: number[] = []; + for (let i = 0; i <= t.rows.length + 1; i++) rows.push(y0 + i * TABLE_ROW_H); + const cell = (r: number, c: number, s: string, bold: boolean, align: Align) => { + const room = t.widths[c] - 2 * PAD; + const f = fitCell(s, room, TABLE_TEXT, bold); + const x = align === 'middle' ? (cols[c] + cols[c + 1]) / 2 : align === 'end' ? cols[c + 1] - PAD : cols[c] + PAD; + return { s: f.s, size: f.size, x, y: rows[r] + TABLE_ROW_H / 2 + f.size * 0.36, bold, anchor: align }; + }; + const texts = [ + ...t.header.map((s, c) => cell(0, c, s, true, 'middle')), + ...t.rows.flatMap((row, r) => row.map((s, c) => cell(r + 1, c, s, false, t.align?.[c] ?? 'start'))), + ]; + return { box: [x0, y0, x0 + w, y0 + h] as Box, cols, rows, texts }; +} + +/** The gap between the columns of a table split to fit the sheet. */ +export const TABLE_SPLIT_GAP = 4; + +/** + * A table cut into columns that fit between `top` and `bottom` (the sheet's border): each with + * the header again, the first where the table is placed and the next ones beside it, to the + * left of a table placed by its bottom right corner (each standing on the same line), else to + * its right. `fits` is false when even so they reach past `left` or `right`, or a single row + * does not fit. + */ +export function splitTable(t: TableSpec, at: P2, anchor: 'bottomRight' | undefined, room: { top: number; bottom: number; left: number; right: number }): + { parts: { t: TableSpec; at: P2 }[]; box: Box; fits: boolean } { + const avail = anchor === 'bottomRight' ? at[1] - room.top : room.bottom - at[1]; + const per = Math.floor(avail / TABLE_ROW_H + 1e-9) - 1; + const whole = tableSize(t); + if (whole.h <= avail + 1e-9 || per < 1) { + const L = layoutTable(t, at, anchor); + const b = L.box; + return { parts: [{ t, at }], box: b, fits: whole.h <= avail + 1e-9 && b[0] >= room.left - 1e-9 && b[2] <= room.right + 1e-9 }; + } + const parts: { t: TableSpec; at: P2 }[] = []; + const step = whole.w + TABLE_SPLIT_GAP; + for (let i = 0, k = 0; i < t.rows.length; i += per, k++) { + const dx = anchor === 'bottomRight' ? -k * step : k * step; + parts.push({ t: { ...t, rows: t.rows.slice(i, i + per) }, at: [at[0] + dx, at[1]] }); + } + const boxes = parts.map((p) => layoutTable(p.t, p.at, anchor).box); + const box: Box = [Math.min(...boxes.map((b) => b[0])), Math.min(...boxes.map((b) => b[1])), Math.max(...boxes.map((b) => b[2])), Math.max(...boxes.map((b) => b[3]))]; + return { parts, box, fits: box[0] >= room.left - 1e-9 && box[2] <= room.right + 1e-9 }; +} + +/** Draws a table (split into columns to stay inside `room`, the sheet's border, when given); returns its box and whether it fits. */ +export function drawTable(items: Item[], t: TableSpec, at: P2, anchor?: 'bottomRight', room?: { top: number; bottom: number; left: number; right: number }): { box: Box; fits: boolean } { + const split = room ? splitTable(t, at, anchor, room) : { parts: [{ t, at }], box: layoutTable(t, at, anchor).box, fits: true }; + for (const part of split.parts) { + const L = layoutTable(part.t, part.at, anchor); + const [x0, y0, x1, y1] = L.box; + items.push({ t: 'rect', x: x0, y: y0, w: x1 - x0, h: y1 - y0, sw: 0.35 }); + L.rows.slice(1, -1).forEach((y, i) => items.push({ t: 'line', x1: x0, y1: y, x2: x1, y2: y, w: i === 0 ? 0.35 : 0.18 })); + for (const x of L.cols.slice(1, -1)) items.push({ t: 'line', x1: x, y1: y0, x2: x, y2: y1, w: 0.18 }); + for (const c of L.texts) if (c.s) items.push({ t: 'text', s: c.s, x: c.x, y: c.y, size: c.size, bold: c.bold || undefined, anchor: c.anchor }); + } + return { box: split.box, fits: split.fits }; +} + +/** The bill of materials table: item number, part, material and quantity. */ +export function bomTable(rows: BomRow[]): TableSpec { + return { + header: ['ITEM NO.', 'PART NUMBER', 'MATERIAL', 'QTY.'], + widths: [16, 52, 44, 14], + rows: rows.map((r) => [String(r.item), r.name, r.description || r.material || '', String(r.qty)]), + align: ['middle', 'start', 'start', 'middle'], + }; +} + +/** + * The cut list table from the cut list's rows as text (cutListRows in src/model/weldments.ts: + * item, quantity, description, length, angle 1, angle 2, ...). + */ +export function cutListTable(rows: string[][], lengthUnit: string): TableSpec { + return { + header: ['ITEM NO.', 'QTY.', 'DESCRIPTION', `LENGTH (${lengthUnit})`, 'ANGLE1', 'ANGLE2'], + widths: [14, 10, 50, 22, 15, 15], + rows: rows.map((r) => [r[0], r[1], r[2], r[3], `${r[4]}°`, `${r[5]}°`]), + align: ['middle', 'middle', 'start', 'end', 'end', 'end'], + }; +} + +// ---------- balloons ---------- + +export const BALLOON_R = 3.5; +const BALLOON_TEXT = 3.5; + +/** The bill of materials row (item number) an edge of a view belongs to. */ +export function itemOfEdge(edge: string, rows: BomRow[]): number | null { + return rows.find((r) => r.prefixes.some((p) => edge.startsWith(p)))?.item ?? null; +} + +/** + * Where a balloon's leader meets its edge: on a line where it was attached (`t`, a fraction of + * it from its start; absent: its middle), the point of a circle nearest the balloon, an arc's middle. + */ +export function balloonTip(g: Geo, at: P2, t?: number): P2 { + if (g.kind === 'point') return g.p; + if (g.kind === 'line') { + const k = t ?? 0.5; + return [g.a[0] + (g.b[0] - g.a[0]) * k, g.a[1] + (g.b[1] - g.a[1]) * k]; + } + if (!g.full) return g.m; + const dx = at[0] - g.c[0], dy = at[1] - g.c[1], l = Math.hypot(dx, dy) || 1; + return [g.c[0] + (dx / l) * g.r, g.c[1] + (dy / l) * g.r]; +} + +/** A balloon: the item number in a circle, with a leader ending in a dot on its edge. Returns its box. */ +export function drawBalloon(items: Item[], text: string, at: P2, tip: P2 | null, color?: string): Box { + const R = BALLOON_R; + items.push({ t: 'circle', cx: at[0], cy: at[1], r: R, w: 0.25, color }); + const w = textWidth(text, BALLOON_TEXT); + const size = w > 2 * R - 1.4 ? (BALLOON_TEXT * (2 * R - 1.4)) / w : BALLOON_TEXT; + items.push({ t: 'text', s: text, x: at[0], y: at[1] + size * 0.36, size, anchor: 'middle', color }); + if (tip) { + const dx = tip[0] - at[0], dy = tip[1] - at[1], l = Math.hypot(dx, dy); + if (l > R + 0.5) { + items.push({ t: 'line', x1: at[0] + (dx / l) * R, y1: at[1] + (dy / l) * R, x2: tip[0], y2: tip[1], w: 0.18, color }); + items.push({ t: 'circle', cx: tip[0], cy: tip[1], r: 0.3, w: 0.6, color }); + } + } + return [at[0] - R, at[1] - R, at[0] + R, at[1] + R]; +} + +/** + * Automatic balloons for a view: one per bill of materials row seen in it (and not in + * `skip`), on an edge of one of the row's components toward the outside of the view, placed + * on a ring around the view (`bounds`, view coordinates) and spread so they do not touch. + * `s` is the view's scale (sheet millimetres per view unit); `clear` how far the ring stays + * from the view on the sheet, left, top, right and bottom (past its dimensions and label). + * Positions are view coordinates. + */ +export function autoBalloons( + prims: Prim[], rows: BomRow[], bounds: [number, number, number, number], s: number, skip: Set = new Set(), clear: [number, number, number, number] = [10, 10, 10, 10], +): { item: number; ref: DrawingRef; at: P2 }[] { + const [bx0, by0, bx1, by1] = bounds; + const c: P2 = [(bx0 + bx1) / 2, (by0 + by1) / 2]; + const span = Math.max(bx1 - bx0, by1 - by0, 1e-9); + const picks: { item: number; edge: string; tip: P2 }[] = []; + for (const r of rows) { + if (skip.has(r.item)) continue; + const mine = prims.filter((p) => p.kind !== 'points' && r.prefixes.some((x) => p.edge.startsWith(x))); + if (!mine.length) continue; + // An edge toward the outside of the view (more likely seen than one in the middle), not a tiny one. + const size = (p: Prim) => (p.kind === 'line' ? Math.hypot(p.b[0] - p.a[0], p.b[1] - p.a[1]) : p.kind === 'arc' ? p.r : 0); + const longest = Math.max(...mine.map(size)); + let best: { edge: string; tip: P2 } | null = null, bestScore = -Infinity; + for (const p of mine) { + if (size(p) < longest * 0.2) continue; + const tip: P2 = p.kind === 'line' ? [(p.a[0] + p.b[0]) / 2, (p.a[1] + p.b[1]) / 2] : p.kind === 'arc' ? (p.full ? [p.c[0] + p.r, p.c[1]] : p.m) : p.a; + const score = Math.hypot(tip[0] - c[0], tip[1] - c[1]) / span + (0.25 * size(p)) / span; + if (score > bestScore) { bestScore = score; best = { edge: p.edge, tip }; } + } + if (best) picks.push({ item: r.item, ...best }); + } + if (!picks.length) return []; + // A ring around the view, clear of it on the sheet. + const m = clear.map((c) => (c + BALLOON_R) / s); + const X0 = bx0 - m[0], Y0 = by0 - m[1], X1 = bx1 + m[2], Y1 = by1 + m[3]; + const W = X1 - X0, H = Y1 - Y0, L = 2 * (W + H); + const at = (t: number): P2 => { + t = ((t % L) + L) % L; + if (t < W) return [X0 + t, Y0]; + if (t < W + H) return [X1, Y0 + (t - W)]; + if (t < 2 * W + H) return [X1 - (t - W - H), Y1]; + return [X0, Y1 - (t - 2 * W - H)]; + }; + // Where the ray from the view's centre through the tip leaves the ring, as a distance along it. + const param = (tip: P2): number => { + let dx = tip[0] - c[0], dy = tip[1] - c[1]; + if (Math.hypot(dx, dy) < 1e-9) { dx = 1; dy = -1; } + const k = Math.min(dx > 0 ? (X1 - c[0]) / dx : dx < 0 ? (X0 - c[0]) / dx : Infinity, dy > 0 ? (Y1 - c[1]) / dy : dy < 0 ? (Y0 - c[1]) / dy : Infinity); + const px = c[0] + dx * k, py = c[1] + dy * k; + const e = 1e-9 * (1 + W + H); + if (Math.abs(py - Y0) < e) return px - X0; + if (Math.abs(px - X1) < e) return W + (py - Y0); + if (Math.abs(py - Y1) < e) return W + H + (X1 - px); + return 2 * W + H + (Y1 - py); + }; + const order = picks.map((p) => ({ ...p, t: param(p.tip) })).sort((a, b) => a.t - b.t); + // Spread along the ring: at least two balloons and a gap apart (less when they do not fit). + const gap = Math.min((2 * BALLOON_R + 3) / s, L / order.length); + for (let pass = 0; pass < 3; pass++) { + for (let i = 1; i < order.length; i++) if (order[i].t - order[i - 1].t < gap) order[i].t = order[i - 1].t + gap; + const n = order.length; + if (n > 1 && order[0].t + L - order[n - 1].t < gap) { + const over = gap - (order[0].t + L - order[n - 1].t); + for (const o of order) o.t -= over / 2; + } + } + return order.map((o) => ({ item: o.item, ref: { edge: o.edge, at: 'edge' as const }, at: at(o.t).map((v) => +v.toFixed(4)) as P2 })); +} diff --git a/src/parametric/src/drawing/views.ts b/src/parametric/src/drawing/views.ts new file mode 100644 index 0000000000..7240eb7523 --- /dev/null +++ b/src/parametric/src/drawing/views.ts @@ -0,0 +1,373 @@ +// Drawing views beyond the standard ones: the direction each view looks from (projected, +// section and auxiliary views from their parent), the scale it is drawn at, which axis it +// shares with its parent, its projection request, and the model edges it shows (for +// dimensions and centre marks), plus the 2D geometry they need: hatching and clipping. + +import type { EdgeInfo, ProjectionRequest } from '../kernel/protocol'; +import { type Vec3, cross, dot, normalize, scale, sub } from '../math/vec'; +import type { DrawingDoc, DrawingSide, DrawingView, DrawingViewType, Id } from '../model/types'; +import { parseSvgPath } from './pdf'; + +export type P2 = [number, number]; + +/** Direction toward the viewer, paper x axis and paper up axis of a view, in the model. */ +export interface Orient { + dir: Vec3; + x: Vec3; + up: Vec3; +} + +const STD: Record = { + front: { dir: [0, 0, 1], x: [1, 0, 0] }, + back: { dir: [0, 0, -1], x: [-1, 0, 0] }, + top: { dir: [0, 1, 0], x: [1, 0, 0] }, + bottom: { dir: [0, -1, 0], x: [1, 0, 0] }, + right: { dir: [1, 0, 0], x: [0, 0, -1] }, + left: { dir: [-1, 0, 0], x: [0, 0, 1] }, + isometric: { dir: normalize([1, 1, 1]), x: normalize(cross([0, 1, 0], normalize([1, 1, 1]))) }, +}; + +/** The source of flat pattern views (the sheet metal part's flat pattern). */ +export const FLAT_SOURCE = 'flat'; + +export const SIDE_VECTORS: Record = { right: [1, 0], left: [-1, 0], above: [0, -1], below: [0, 1] }; + +export interface ResolvedView { + v: DrawingView; + type: DrawingViewType; + o: Orient; + /** Model millimetres to sheet millimetres. */ + scale: number; + parent?: ResolvedView; + /** The sheet axis it shares with its parent: 'x' (placed above or below) or 'y' (left or right). */ + align?: 'x' | 'y'; + /** Section views: the part kept is where (p - section.p) . section.n >= 0. */ + section?: { p: Vec3; n: Vec3 }; + /** Detail views: the circle shown, in the view's coordinates. */ + clip?: { c: P2; r: number }; + /** Paper direction from the parent's line toward this view (section and auxiliary views). */ + toward?: P2; + /** Views that share a key share their projection. */ + key: string; + source: string; +} + +const r6 = (v: number) => Math.round(v * 1e6) / 1e6; +const rv = (v: Vec3) => v.map((q) => r6(q) || 0); + +/** A view's coordinates (model millimetres, x right, y down) of a model point. */ +export const toView = (o: Orient, p: Vec3): P2 => [dot(p, o.x), -dot(p, o.up)]; +/** A model point (on the plane through the origin facing the viewer) at view coordinates q. */ +export const fromView = (o: Orient, q: P2): Vec3 => [o.x[0] * q[0] - o.up[0] * q[1], o.x[1] * q[0] - o.up[1] * q[1], o.x[2] * q[0] - o.up[2] * q[1]]; + +/** + * The view placed beside a parent, in the direction n2 on paper (y down), as the projection + * angle places it: in third angle a view sits on the side it is seen from, in first angle on + * the opposite side. Placed above or below, the parent's view direction is the view's up (or + * down); placed left or right, the parent's up stays up as nearly as the direction allows. + */ +export function besideOrient(p: Orient, n2: P2, first: boolean): Orient { + const [nx, ny] = n2; + const N = normalize([p.x[0] * nx - p.up[0] * ny, p.x[1] * nx - p.up[1] * ny, p.x[2] * nx - p.up[2] * ny]); + const dir = first ? scale(N, -1) : N; + let up: Vec3; + if (Math.abs(ny) >= Math.abs(nx)) up = scale(p.dir, (first ? 1 : -1) * Math.sign(-ny)); + else up = normalize(sub(p.up, scale(dir, dot(p.up, dir)))); + return { dir: z(dir), up: z(up), x: z(normalize(cross(up, dir))) }; +} + +/** Without negative zeros (so equal directions compare and key equal). */ +const z = (v: Vec3): Vec3 => [v[0] || 0, v[1] || 0, v[2] || 0]; + +export function standardOrient(kind: string): Orient { + const s = STD[kind] ?? STD.front; + return { dir: s.dir, x: s.x, up: cross(s.dir, s.x) }; +} + +/** Unit left normal of a line on paper (y down): the side its view lies on. */ +export function lineNormal(l: [number, number, number, number]): P2 { + const dx = l[2] - l[0], dy = l[3] - l[1]; + const n = Math.hypot(dx, dy) || 1; + return [-dy / n, dx / n]; +} + +const EPS_AXIS = 1e-9; + +/** + * Every view's direction, scale and relation to its parent. Views whose parent is missing + * (or that form a cycle) are left out. + */ +export function resolveViews(d: DrawingDoc): Map { + const out = new Map(); + const byId = new Map(d.views.map((v) => [v.id, v])); + const first = d.projection === 'first'; + const visit = (v: DrawingView, depth: number): ResolvedView | undefined => { + const done = out.get(v.id); + if (done) return done; + if (depth > 32) return undefined; + const type: DrawingViewType = v.type ?? 'model'; + const source = v.source ?? 'part'; + let r: ResolvedView | undefined; + if (type === 'flat') { + // The flat pattern, seen from its top face (its own x and y on paper). + r = { v, type, o: standardOrient('front'), scale: v.scale ?? d.scale, key: '', source: FLAT_SOURCE }; + } else if (type === 'model' || !v.parent) { + const o = standardOrient(v.kind); + r = { v, type: 'model', o, scale: v.scale ?? d.scale, key: '', source }; + } else { + const pv = byId.get(v.parent); + const parent = pv && pv.id !== v.id ? visit(pv, depth + 1) : undefined; + if (!parent) return undefined; + if (type === 'detail') { + const c = v.circle ?? [0, 0, 10]; + r = { v, type, o: parent.o, scale: v.scale ?? parent.scale * 2, parent, clip: { c: [c[0], c[1]], r: Math.abs(c[2]) }, section: parent.section, key: '', source: parent.source }; + } else if (type === 'projected') { + const side = v.side ?? 'right'; + r = { v, type, o: besideOrient(parent.o, SIDE_VECTORS[side], first), scale: parent.scale, parent, align: side === 'left' || side === 'right' ? 'y' : 'x', key: '', source: parent.source }; + } else { + // Section and auxiliary views: beside the parent's line, on its left normal's side. + const l = v.line ?? [0, 0, 1, 0]; + const n2 = lineNormal(l); + const o = besideOrient(parent.o, n2, first); + const align = Math.abs(n2[0]) < EPS_AXIS ? 'x' : Math.abs(n2[1]) < EPS_AXIS ? 'y' : undefined; + r = { v, type, o, scale: parent.scale, parent, align, toward: n2, key: '', source: parent.source }; + if (type === 'section') { + // The plane holds the line and the parent's direction; what lies between it and the viewer goes. + const p = fromView(parent.o, [l[0], l[1]]); + r.section = { p: rv(p) as Vec3, n: rv(scale(o.dir, -1)) as Vec3 }; + } + } + } + r.key = JSON.stringify([r.source, rv(r.o.dir), rv(r.o.x), r.section ?? null, v.tangent !== false]); + out.set(v.id, r); + return r; + }; + for (const v of d.views) visit(v, 0); + return out; +} + +/** The projection request of a view (id: its key). */ +export function projectionRequest(r: ResolvedView, hidden: boolean): ProjectionRequest { + const q: ProjectionRequest = { id: r.key, dir: r.o.dir, x: r.o.x, hidden }; + if (r.v.tangent === false) q.smooth = false; + if (r.section) q.section = r.section; + return q; +} + +/** The views that depend on a view (projected from it, its sections and details...), deepest last. */ +export function dependents(d: DrawingDoc, id: Id): Id[] { + const out: Id[] = []; + const walk = (p: Id) => { + for (const v of d.views) if (v.parent === p && !out.includes(v.id) && v.id !== id) { out.push(v.id); walk(v.id); } + }; + walk(id); + return out; +} + +/** The standard view a view's direction matches, if any. */ +export function standardKindOf(o: Orient): string | null { + for (const [k, s] of Object.entries(STD)) { + if (k === 'isometric') continue; + if (Math.abs(dot(s.dir, o.dir) - 1) < 1e-9 && Math.abs(dot(s.x, o.x) - 1) < 1e-9) return k; + } + return null; +} + +// ---------- model edges seen in a view ---------- + +/** A model edge as seen in a view (view coordinates). */ +export type Prim = + | { edge: string; kind: 'line'; a: P2; b: P2 } + | { edge: string; kind: 'arc'; c: P2; r: number; a: P2; b: P2; m: P2; full: boolean } + /** Seen end-on, or a curve: only its end points can be picked. */ + | { edge: string; kind: 'points'; a: P2; b: P2 }; + +const near = (a: number, b: number, tol = 1e-6) => Math.abs(a - b) <= tol; + +/** + * The named model edges as seen in a view: lines, circles and arcs facing the viewer, and + * circles seen edge on (as the line across them). A section view sees only what it keeps. + */ +export function viewPrims(r: ResolvedView, edges: EdgeInfo[]): Prim[] { + const o = r.o; + const out: Prim[] = []; + const keep = (p: Vec3) => !r.section || dot(sub(p, r.section.p), r.section.n) >= -1e-6 * (1 + Math.abs(dot(p, r.section.n))); + for (const e of edges) { + // Seams (where a closed face meets itself) are not edges on a drawing. + if (e.faces.length === 1) continue; + if (r.section && !(keep(e.a) && keep(e.b) && keep(e.mid))) continue; + const a = toView(o, e.a), b = toView(o, e.b); + if (e.type === 'line') { + if (Math.hypot(a[0] - b[0], a[1] - b[1]) < 1e-9) out.push({ edge: e.name, kind: 'points', a, b }); + else out.push({ edge: e.name, kind: 'line', a, b }); + continue; + } + if (e.type === 'circle' && e.center && e.axis && e.radius) { + const c = toView(o, e.center); + const ad = Math.abs(dot(normalize(e.axis), o.dir)); + const full = Math.hypot(a[0] - b[0], a[1] - b[1]) < 1e-7 * (1 + e.radius) && e.length > e.radius; + if (near(ad, 1, 1e-9)) { + out.push({ edge: e.name, kind: 'arc', c, r: e.radius, a, b, m: toView(o, e.mid), full }); + continue; + } + if (near(ad, 0, 1e-9) && full) { + // Edge on: the line across it. + const across = normalize(cross(e.axis, o.dir)); + const u = toView(o, across); + const k = e.radius; + // toView of a direction includes no translation (it is linear). + out.push({ edge: e.name, kind: 'line', a: [c[0] - u[0] * k, c[1] - u[1] * k], b: [c[0] + u[0] * k, c[1] + u[1] * k] }); + continue; + } + } + out.push({ edge: e.name, kind: 'points', a, b }); + } + return out; +} + +/** Holes and bosses seen end on: one circle per centre (the largest), and arcs of more than half a turn. */ +export function centerMarks(prims: Prim[]): { c: P2; r: number; edge: string }[] { + const out: { c: P2; r: number; edge: string }[] = []; + for (const p of prims) { + if (p.kind !== 'arc') continue; + if (!p.full && !arcOverHalf(p)) continue; + const same = out.find((q) => Math.hypot(q.c[0] - p.c[0], q.c[1] - p.c[1]) < 1e-6 * (1 + p.r)); + if (same) { if (p.r > same.r) { same.r = p.r; same.edge = p.edge; } continue; } + out.push({ c: p.c, r: p.r, edge: p.edge }); + } + return out; +} + +/** An arc of more than half a turn: its centre lies between its chord and its middle. */ +export function arcOverHalf(p: { a: P2; b: P2; m: P2; c: P2 }): boolean { + const mx = (p.a[0] + p.b[0]) / 2, my = (p.a[1] + p.b[1]) / 2; + return (p.m[0] - mx) * (p.c[0] - mx) + (p.m[1] - my) * (p.c[1] - my) > 0; +} + +/** + * Axes of holes and bosses seen from the side: the line between the centres of full circles of + * the same radius on one axis, which the view sees edge on. + */ +export function holeAxes(r: ResolvedView, edges: EdgeInfo[]): { a: P2; b: P2; r: number }[] { + const o = r.o; + const groups: { p: Vec3; d: Vec3; rad: number; ts: number[] }[] = []; + const keep = (p: Vec3) => !r.section || dot(sub(p, r.section.p), r.section.n) >= -1e-6 * (1 + Math.abs(dot(p, r.section.n))); + for (const e of edges) { + if (e.type !== 'circle' || !e.center || !e.axis || !e.radius) continue; + if (Math.hypot(e.a[0] - e.b[0], e.a[1] - e.b[1], e.a[2] - e.b[2]) > 1e-7 * (1 + e.radius)) continue; + const d = normalize(e.axis); + if (Math.abs(dot(d, o.dir)) > 1e-9) continue; + if (!keep(e.center)) continue; + const g = groups.find((q) => near(q.rad, e.radius!, 1e-6 * (1 + e.radius!)) && Math.abs(Math.abs(dot(q.d, d)) - 1) < 1e-9 + && Math.hypot(...cross(sub(e.center!, q.p), q.d)) < 1e-6 * (1 + e.radius!)); + if (g) g.ts.push(dot(sub(e.center, g.p), g.d)); + else groups.push({ p: e.center, d, rad: e.radius, ts: [0] }); + } + const out: { a: P2; b: P2; r: number }[] = []; + for (const g of groups) { + if (g.ts.length < 2) continue; + const t0 = Math.min(...g.ts), t1 = Math.max(...g.ts); + if (t1 - t0 < 1e-9) continue; + const at = (t: number): Vec3 => [g.p[0] + g.d[0] * t, g.p[1] + g.d[1] * t, g.p[2] + g.d[2] * t]; + out.push({ a: toView(o, at(t0)), b: toView(o, at(t1)), r: g.rad }); + } + return out; +} + +// ---------- 2D geometry ---------- + +/** + * Hatch lines inside the regions bounded by the segments (even-odd), at `angle` degrees and + * `spacing` apart, as segments [x1, y1, x2, y2]. The lines are spaced from the origin, so the + * hatching of neighbouring regions lines up. + */ +export function hatch(polylines: number[][], angle: number, spacing: number): [number, number, number, number][] { + const a = (angle * Math.PI) / 180, ca = Math.cos(a), sa = Math.sin(a); + // Rotate so the hatch lines run along x: v = -x sin + y cos is constant along a line. + const segs: [number, number, number, number][] = []; + let v0 = Infinity, v1 = -Infinity; + for (const pl of polylines) { + for (let i = 0; i + 3 < pl.length; i += 2) { + const x1 = pl[i], y1 = pl[i + 1], x2 = pl[i + 2], y2 = pl[i + 3]; + const u1 = x1 * ca + y1 * sa, w1 = -x1 * sa + y1 * ca, u2 = x2 * ca + y2 * sa, w2 = -x2 * sa + y2 * ca; + segs.push([u1, w1, u2, w2]); + v0 = Math.min(v0, w1, w2); v1 = Math.max(v1, w1, w2); + } + } + const out: [number, number, number, number][] = []; + if (!segs.length || !(spacing > 0)) return out; + if ((v1 - v0) / spacing > 20000) return out; + for (let k = Math.ceil(v0 / spacing); k * spacing <= v1; k++) { + const w = k * spacing; + const xs: number[] = []; + for (const [u1, w1, u2, w2] of segs) { + // Half-open in w, so a line through a vertex counts it once. + if ((w1 <= w && w2 > w) || (w2 <= w && w1 > w)) xs.push(u1 + ((w - w1) * (u2 - u1)) / (w2 - w1)); + } + xs.sort((p, q) => p - q); + for (let i = 0; i + 1 < xs.length; i += 2) { + if (xs[i + 1] - xs[i] < 1e-9) continue; + const [ua, ub] = [xs[i], xs[i + 1]]; + out.push([ua * ca - w * sa, ua * sa + w * ca, ub * ca - w * sa, ub * sa + w * ca]); + } + } + return out; +} + +/** SVG path data (lines, arcs, curves) as polylines, transformed by x * s + t. */ +export function flattenPath(d: string, tx: number, ty: number, s: number, tol = 0.05): P2[][] { + const out: P2[][] = []; + let cur: P2[] = []; + let start: P2 = [0, 0]; + const T = (p: [number, number]): P2 => [p[0] * s + tx, p[1] * s + ty]; + for (const g of parseSvgPath(d)) { + if (g.op === 'M') { + if (cur.length > 1) out.push(cur); + start = T(g.p); + cur = [start]; + } else if (g.op === 'L') cur.push(T(g.p)); + else if (g.op === 'C') { + const p0 = cur[cur.length - 1] ?? start, c1 = T(g.c1), c2 = T(g.c2), p3 = T(g.p); + const L = Math.hypot(c1[0] - p0[0], c1[1] - p0[1]) + Math.hypot(c2[0] - c1[0], c2[1] - c1[1]) + Math.hypot(p3[0] - c2[0], p3[1] - c2[1]); + const n = Math.max(2, Math.min(64, Math.ceil(Math.sqrt(L / Math.max(tol, 1e-6))))); + for (let i = 1; i <= n; i++) { + const t = i / n, m = 1 - t; + cur.push([ + m * m * m * p0[0] + 3 * m * m * t * c1[0] + 3 * m * t * t * c2[0] + t * t * t * p3[0], + m * m * m * p0[1] + 3 * m * m * t * c1[1] + 3 * m * t * t * c2[1] + t * t * t * p3[1], + ]); + } + } else if (g.op === 'Z') cur.push(start); + } + if (cur.length > 1) out.push(cur); + return out; +} + +/** The parts of a polyline inside a circle. */ +export function clipToCircle(pl: P2[], c: P2, r: number): P2[][] { + const out: P2[][] = []; + let cur: P2[] = []; + const inside = (p: P2) => (p[0] - c[0]) ** 2 + (p[1] - c[1]) ** 2 <= r * r; + for (let i = 0; i + 1 < pl.length; i++) { + const p = pl[i], q = pl[i + 1]; + const dx = q[0] - p[0], dy = q[1] - p[1]; + const fx = p[0] - c[0], fy = p[1] - c[1]; + const A = dx * dx + dy * dy, B = 2 * (fx * dx + fy * dy), C = fx * fx + fy * fy - r * r; + let t0 = 0, t1 = 1; + if (A < 1e-18) { if (!inside(p)) { if (cur.length > 1) out.push(cur); cur = []; } continue; } + const disc = B * B - 4 * A * C; + if (disc <= 0) { if (cur.length > 1) out.push(cur); cur = []; continue; } + const sq = Math.sqrt(disc); + t0 = Math.max(0, (-B - sq) / (2 * A)); + t1 = Math.min(1, (-B + sq) / (2 * A)); + if (t0 >= t1) { if (cur.length > 1) out.push(cur); cur = []; continue; } + const a: P2 = [p[0] + dx * t0, p[1] + dy * t0], b: P2 = [p[0] + dx * t1, p[1] + dy * t1]; + if (t0 > 0 || !cur.length) { if (cur.length > 1) out.push(cur); cur = [a]; } + cur.push(b); + if (t1 < 1) { out.push(cur); cur = []; } + } + if (cur.length > 1) out.push(cur); + return out; +} + +export const polyPath = (pl: P2[]) => `M${pl.map((p) => `${+p[0].toFixed(4)} ${+p[1].toFixed(4)}`).join('L')}`; diff --git a/src/parametric/src/kernel/assembly.ts b/src/parametric/src/kernel/assembly.ts new file mode 100644 index 0000000000..f5dd43208c --- /dev/null +++ b/src/parametric/src/kernel/assembly.ts @@ -0,0 +1,499 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +// Assemblies in the geometry worker. Every part an assembly uses is built by +// a ModelBuilder of its own (kept while the assembly uses it), and the +// components are placed copies of those bodies. The main thread places the +// meshes itself, so moving a component never needs the worker; the worker +// keeps the current placement of every component (the scene) for what needs +// the exact solids: measuring between components, interference, mass +// properties, drawing projections and STEP and STL export. + +import * as R from 'replicad'; +import type { Vec3 } from '../math/vec'; +import { add, dist, scale, sub } from '../math/vec'; +import type { Feature, Id } from '../model/types'; +import { ModelBuilder, eigenSym3 } from './build'; +import { cutOutlines, halfOf } from './drawing-section'; +import { type Sh, bbox, common, compound, getOc, gdir, meshShape, pnt, projectShape, subShapes, volumeOf, wrap, xyz } from './occ'; +import type { BuildResult, EdgeInfo, FaceInfo, FeatureStatus, MassProperties, MeasureResult, MeasureTarget, MeshData, ProjectionRequest, ProjectionResult } from './protocol'; + +export interface AsmPartBuild { + /** Identifies the part's content (the key of its embedded copy). */ + key: string; + features: Feature[]; + blobs: Record; + quality: number; + invalid?: Record; +} + +export interface AsmPartResult { + key: string; + quality: number; + mesh: MeshData | null; + faces: FaceInfo[]; + edges: EdgeInfo[]; + bbox: { min: Vec3; max: Vec3 } | null; + status: FeatureStatus[]; + /** Axes of conical faces (by face index), which the part's face list does not carry. */ + cones: Record; +} + +/** A component in the worker's scene: its part and its placement as a 3×4 row-major matrix. */ +export interface AsmSceneItem { + part: string; + m: number[]; + name: string; + color: string; + /** + * Hidden components are in the scene for mass properties (hiding only + * changes what is shown), but not in the graphics area's face and edge + * lists, measuring, interference, drawings or export. + */ + hidden?: boolean; +} + +export interface InterferencePair { + /** Scene indices of the two components. */ + a: number; + b: number; + volume: number; + mesh: MeshData | null; + /** The overlap of the two could not be computed: they were not checked (volume 0, no mesh). */ + failed?: boolean; +} + +export interface AsmMassResult { + /** Some component has no closed solid (its volume is left out). */ + open: string[]; + /** kg */ + mass: number; + /** mm³ */ + volume: number; + /** mm² */ + area: number; + center: Vec3; + /** About the centre of mass, assembly axes, kg·mm², row-major 3×3. */ + inertia: number[]; + principal: { moments: Vec3; axes: [Vec3, Vec3, Vec3] }; +} + +export type AsmRequest = + | { op: 'build'; parts: AsmPartBuild[] } + | { op: 'scene'; items: AsmSceneItem[] } + | { op: 'drop'; keep: string[] } + | { op: 'interference' } + /** densities: kg/m³ for each scene item. */ + | { op: 'mass'; densities: number[] } + /** Drawing projections of components placed as given (the scene is left as it is). */ + | { op: 'project'; items: AsmSceneItem[]; views: ProjectionRequest[] }; + +const IDENTITY_M = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]; + +export class AssemblyBuilder { + /** The open document is an assembly: drawings, measure and export use the scene. */ + active = false; + private builders = new Map(); + private scene: AsmSceneItem[] = []; + private placedCache = new Map(); + + reset() { + this.builders.clear(); + this.placedCache.clear(); + this.scene = []; + } + + async build(parts: AsmPartBuild[]): Promise { + this.active = true; + const out: AsmPartResult[] = []; + for (const p of parts) { + let b = this.builders.get(p.key); + if (!b) this.builders.set(p.key, (b = new ModelBuilder())); + const res: BuildResult = await b.build({ features: p.features, upTo: p.features.length, blobs: p.blobs, quality: p.quality, invalid: p.invalid }); + const shapes = b.currentShapes(); + const cones: AsmPartResult['cones'] = {}; + shapes.faces.forEach((f, i) => { if (f.desc.type === 'cone') { const ax = coneAxis(f.shape); if (ax) cones[i] = ax; } }); + out.push({ key: p.key, quality: p.quality, mesh: copyMesh(res.mesh), faces: res.faces, edges: res.edges, bbox: res.bbox, status: res.status, cones }); + } + this.placedCache.clear(); + return out; + } + + /** Forgets the parts the assembly no longer uses. */ + drop(keep: string[]) { + const k = new Set(keep); + for (const key of [...this.builders.keys()]) if (!k.has(key)) this.builders.delete(key); + } + + setScene(items: AsmSceneItem[]) { + this.active = true; + this.scene = items; + this.placedCache.clear(); + } + + private shapesOf(key: string) { + const b = this.builders.get(key); + if (!b) throw new Error('A part of the assembly is not built yet. Rebuild the assembly and try again.'); + return b.currentShapes(); + } + + /** A component's body where the scene places it (null when its part has no body). */ + private placedBody(i: number): Sh | null { + const it = this.scene[i]; + const cacheKey = `${i}|${it.part}|${it.m.join(',')}`; + const hit = this.placedCache.get(cacheKey); + if (hit) return hit; + const body = this.shapesOf(it.part).body; + if (!body) return null; + const placed = place(body, it.m); + this.placedCache.set(cacheKey, placed); + return placed; + } + + /** The placed bodies of the shown components (`hidden`: of the hidden ones too), with their scene indices. */ + private bodies(hidden = false): { i: number; shape: Sh }[] { + const out: { i: number; shape: Sh }[] = []; + this.scene.forEach((it, i) => { if (it.hidden && !hidden) return; const s = this.placedBody(i); if (s) out.push({ i, shape: s }); }); + return out; + } + + /** + * The shown components' solids with their surface bodies (shells), placed: + * what drawings and STEP export show, as a part's do. Mass and interference + * take the solids only (bodies). + */ + private shapes(): { i: number; shape: Sh }[] { + const out: { i: number; shape: Sh }[] = []; + this.scene.forEach((it, i) => { + if (it.hidden) return; + const s = this.shapesOf(it.part); + if (!s.surfaces.length) { const b = this.placedBody(i); if (b) out.push({ i, shape: b }); return; } + const all = [...(s.body ? [s.body] : []), ...s.surfaces]; + out.push({ i, shape: place(all.length === 1 ? all[0] : compound(all), it.m) }); + }); + return out; + } + + /** The face or edge with a combined index (components in scene order, as the main thread lists them). */ + private locate(kind: 'face' | 'edge', index: number): Sh { + let k = index; + for (const it of this.scene) { + if (it.hidden) continue; + const s = this.shapesOf(it.part); + // Numbered as the graphics area lists them: the solid's, then its surface bodies'. + const list = kind === 'face' ? [...s.faces.map((f) => f.shape), ...s.surfaceFaces] : [...s.edges, ...s.surfaceEdges]; + if (k < list.length) return place(list[k], it.m); + k -= list.length; + } + throw new Error(`${kind === 'face' ? 'Face' : 'Edge'} not found`); + } + + measure(a: MeasureTarget, b: MeasureTarget): MeasureResult { + const oc = getOc(); + const shapeOf = (t: MeasureTarget): Sh => { + if (t.kind === 'vertex') { + const gp = pnt(t.p); + const mv = new oc.BRepBuilderAPI_MakeVertex(gp); + const v = wrap(mv.Vertex()); + mv.delete(); + gp.delete(); + return v; + } + return this.locate(t.kind, t.index); + }; + const s1 = shapeOf(a), s2 = shapeOf(b); + const ext = new oc.BRepExtrema_DistShapeShape(); + const progress = new oc.Message_ProgressRange(); + try { + ext.LoadS1(s1.wrapped); + ext.LoadS2(s2.wrapped); + ext.Perform(progress); + if (!ext.IsDone() || ext.NbSolution() < 1) throw new Error('Distance could not be computed'); + const p1 = ext.PointOnShape1(1), p2 = ext.PointOnShape2(1); + const out = { distance: ext.Value(), p1: xyz(p1), p2: xyz(p2) }; + p1.delete(); p2.delete(); + return out; + } finally { + ext.delete(); + progress.delete(); + } + } + + /** + * The combined solid of the visible components where they are placed: + * what a drawing of the assembly projects (see project). + */ + combined(): Sh | null { + const list = this.bodies(); + return list.length ? compound(list.map((b) => b.shape)) : null; + } + + project(views: ProjectionRequest[]): ProjectionResult[] { + return projectBodies(this.shapes().map((b) => b.shape), views); + } + + /** + * Projections of the components placed as `items` say (a drawing of the assembly + * collapsed or exploded, whatever the graphics area shows). Hidden components are drawn. + */ + projectItems(items: AsmSceneItem[], views: ProjectionRequest[]): ProjectionResult[] { + const list: Sh[] = []; + for (const it of items) { + const s = this.shapesOf(it.part); + // Surface bodies are drawn too, as in a drawing of the part. + const all = [...(s.body ? [s.body] : []), ...s.surfaces]; + if (all.length) list.push(place(all.length === 1 ? all[0] : compound(all), it.m)); + } + return projectBodies(list, views); + } + + /** Volume properties per unit density of all components together (what the part's Mass Properties reports). */ + massProperties(): MassProperties | null { + const r = this.mass(this.scene.map(() => 1e9)); + if (!r) return null; + // At 1e9 kg/m³ a cubic millimetre weighs a kilogram: the values are per unit density in mm. + return { solid: !r.open.length, volume: r.volume, area: r.area, center: r.center, inertia: r.inertia, principal: r.principal }; + } + + /** Mass properties of the components (hidden ones too), each with its own density (kg/m³) by scene index. */ + mass(densities: number[]): AsmMassResult | null { + const oc = getOc(); + const items: { m: number; v: number; area: number; c: Vec3; I: number[] }[] = []; + const open: string[] = []; + for (const { i, shape } of this.bodies(true)) { + const props = new oc.GProp_GProps(); + const sprops = new oc.GProp_GProps(); + try { + oc.BRepGProp.VolumeProperties(shape.wrapped, props, true, false, false); + oc.BRepGProp.SurfaceProperties(shape.wrapped, sprops, true, false); + const v = props.Mass(); + const b = bbox(shape); + const area = sprops.Mass(); + if (!(v > (b ? dist(b.min, b.max) : 1) ** 3 * 1e-12)) { open.push(this.scene[i].name); items.push({ m: 0, v: 0, area, c: [0, 0, 0], I: new Array(9).fill(0) }); continue; } + const gc = props.CentreOfMass(); + const c = xyz(gc); + gc.delete(); + const moment = (d: Vec3) => { + const gp = pnt(c), gd = gdir(d); + const ax = new oc.gp_Ax1(gp, gd); + const val = props.MomentOfInertia(ax); + ax.delete(); gp.delete(); gd.delete(); + return val; + }; + const ixx = moment([1, 0, 0]), iyy = moment([0, 1, 0]), izz = moment([0, 0, 1]); + const s = Math.SQRT1_2; + const ixy = moment([s, s, 0]) - (ixx + iyy) / 2; + const iyz = moment([0, s, s]) - (iyy + izz) / 2; + const ixz = moment([s, 0, s]) - (ixx + izz) / 2; + const rho = (densities[i] ?? 1000) * 1e-9; // kg/mm³ + items.push({ m: v * rho, v, area, c, I: [ixx, ixy, ixz, ixy, iyy, iyz, ixz, iyz, izz].map((x) => x * rho) }); + } finally { + props.delete(); + sprops.delete(); + } + } + if (!items.length) return null; + const mass = items.reduce((s, x) => s + x.m, 0); + const volume = items.reduce((s, x) => s + x.v, 0); + const area = items.reduce((s, x) => s + x.area, 0); + const center: Vec3 = mass > 0 ? scale(items.reduce((s, x) => add(s, scale(x.c, x.m)), [0, 0, 0] as Vec3), 1 / mass) : [0, 0, 0]; + // Each component's inertia moved to the common centre (parallel axis theorem). + const I = new Array(9).fill(0); + for (const x of items) { + const d = sub(x.c, center); + const d2 = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; + for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) I[r * 3 + c] += x.I[r * 3 + c] + x.m * ((r === c ? d2 : 0) - d[r] * d[c]); + } + return { open, mass, volume, area, center, inertia: I, principal: eigenSym3(I) }; + } + + /** The solid two placed bodies share (a method so tests can make it fail). */ + protected sharedSolid(a: Sh, b: Sh): Sh { + return common(a, b); + } + + /** + * Pairs of components whose solids overlap, with the volume they share, and + * pairs whose overlap could not be computed (`failed`: never reported as clear). + */ + interference(): InterferencePair[] { + const list = this.bodies().map((b) => ({ ...b, box: bbox(b.shape) })); + const all = this.combined(); + const ab = all ? bbox(all) : null; + const diag = ab ? dist(ab.min, ab.max) : 1; + const minVolume = Math.max(1e-6, 1e-12 * diag ** 3); + const out: InterferencePair[] = []; + for (let x = 0; x < list.length; x++) { + for (let y = x + 1; y < list.length; y++) { + const A = list[x], B = list[y]; + if (!A.box || !B.box || !boxesOverlap(A.box, B.box)) continue; + let shared: Sh, v: number; + try { + shared = this.sharedSolid(A.shape, B.shape); + v = volumeOf(shared); + } catch { + out.push({ a: A.i, b: B.i, volume: 0, mesh: null, failed: true }); + continue; + } + if (!Number.isFinite(v)) { out.push({ a: A.i, b: B.i, volume: 0, mesh: null, failed: true }); continue; } + if (!(v > minVolume)) continue; + out.push({ a: A.i, b: B.i, volume: v, mesh: meshOf(shared, diag) }); + } + } + return out; + } + + /** A STEP file with every component as a named solid of its own. */ + async exportStep(): Promise { + // Surface bodies go in as shells beside each component's solid, as a part's export writes them. + const list = this.shapes(); + if (!list.length) throw new Error('There is no geometry to export'); + const oc = getOc(); + // replicad's writer changes global translation settings: they are put back + // afterwards so a part exported later is written exactly as before. + const ints = ['write.surfacecurve.mode', 'write.precision.mode', 'write.step.assembly', 'write.step.schema']; + const strs = ['write.step.unit', 'xstep.cascade.unit']; + const savedI = ints.map((k) => oc.Interface_Static.IVal(k)); + const savedC = strs.map((k) => oc.Interface_Static.CVal(k)); + const naming = oc.XCAFDoc_ShapeTool.AutoNaming(); + try { + const blob = (R as any).exportSTEP(list.map(({ i, shape }) => ({ shape, name: this.scene[i].name, color: this.scene[i].color })), { unit: 'MM' }) as Blob; + return new Uint8Array(await blob.arrayBuffer()); + } finally { + ints.forEach((k, j) => oc.Interface_Static.SetIVal(k, savedI[j])); + strs.forEach((k, j) => oc.Interface_Static.SetCVal(k, savedC[j])); + oc.XCAFDoc_ShapeTool.SetAutoNaming(naming); + } + } + + /** Binary STL of all components where they are placed. */ + exportStl(quality: number): Uint8Array { + const list = this.bodies(); + if (!list.length) throw new Error('There is no geometry to export'); + const all = this.combined()!; + const b = bbox(all); + const diag = b ? dist(b.min, b.max) : 1; + const q = Math.max(1, Math.min(2, quality)); + const meshes = list.map(({ shape }) => meshShape(shape, Math.max(diag * [0.002, 0.0006, 0.0002][q] * 0.5, 1e-4), [0.5, 0.25, 0.12][q] * 0.5)); + const tris = meshes.reduce((s, m) => s + m.indices.length / 3, 0); + const buf = new ArrayBuffer(84 + tris * 50); + const dv = new DataView(buf); + const header = 'Parametric binary STL (assembly)'; + for (let i = 0; i < header.length; i++) dv.setUint8(i, header.charCodeAt(i)); + dv.setUint32(80, tris, true); + let o = 84; + for (const m of meshes) { + const P = m.positions; + for (let t = 0; t < m.indices.length / 3; t++) { + const i0 = m.indices[t * 3] * 3, i1 = m.indices[t * 3 + 1] * 3, i2 = m.indices[t * 3 + 2] * 3; + const ux = P[i1] - P[i0], uy = P[i1 + 1] - P[i0 + 1], uz = P[i1 + 2] - P[i0 + 2]; + const vx = P[i2] - P[i0], vy = P[i2 + 1] - P[i0 + 1], vz = P[i2 + 2] - P[i0 + 2]; + let nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx; + const l = Math.hypot(nx, ny, nz) || 1; + nx /= l; ny /= l; nz /= l; + dv.setFloat32(o, nx, true); dv.setFloat32(o + 4, ny, true); dv.setFloat32(o + 8, nz, true); + o += 12; + for (const i of [i0, i1, i2]) { + dv.setFloat32(o, P[i], true); dv.setFloat32(o + 4, P[i + 1], true); dv.setFloat32(o + 8, P[i + 2], true); + o += 12; + } + dv.setUint16(o, 0, true); + o += 2; + } + } + return new Uint8Array(buf); + } + + /** The scene item count (tests). */ + get sceneSize(): number { + return this.scene.length; + } +} + +/** + * Hidden-line projections of placed components. A section view cuts each component on its + * own (a boolean on all of them at once loses those that touch), and tells which component + * each cut outline belongs to, so neighbours are hatched differently. + */ +function projectBodies(list: Sh[], views: ProjectionRequest[]): ProjectionResult[] { + const body = list.length ? compound(list) : null; + const b = body ? bbox(body) : null; + const tol = b ? Math.max(dist(b.min, b.max) * 1e-3, 1e-4) : 0.01; + return views.map((v) => { + if (!body || !b) return { id: v.id, visible: [], hidden: [], bounds: null }; + if (!v.section) return { id: v.id, ...projectShape(body, v.dir, v.x, tol, tol / 10, v.hidden !== false, v.smooth !== false) }; + const { p, n } = v.section; + const size = 2 * (dist(b.min, b.max) + Math.hypot(...p) + Math.hypot(...b.min) + 1); + const halves: Sh[] = [], cut: number[][] = [], cutGroups: number[] = []; + list.forEach((s, i) => { + const half = halfOf(s, p, n, size); + if (!subShapes(half, 'face').length) return; + halves.push(half); + for (const pl of cutOutlines(half, p, n, v.dir, v.x, tol)) { cut.push(pl); cutGroups.push(i); } + }); + if (!halves.length) return { id: v.id, visible: [], hidden: [], bounds: null, cut: [] }; + return { id: v.id, ...projectShape(compound(halves), v.dir, v.x, tol, tol / 10, v.hidden !== false, v.smooth !== false), cut, cutGroups }; + }); +} + +/** A shape moved by a rigid 3×4 row-major matrix (the geometry is shared, only its location changes). */ +export function place(shape: Sh, m: number[]): Sh { + if (m.every((v, i) => Math.abs(v - IDENTITY_M[i]) < 1e-15)) return shape; + const oc = getOc(); + const tr = new oc.gp_Trsf(); + try { + tr.SetValues(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11]); + const t = new oc.BRepBuilderAPI_Transform(shape.wrapped, tr, false); + try { return wrap(t.Shape()); } finally { t.delete(); } + } finally { + tr.delete(); + } +} + +function coneAxis(face: Sh): { p: Vec3; d: Vec3 } | null { + const oc = getOc(); + const ad = new oc.BRepAdaptor_Surface(face.wrapped, true); + try { + const cone = ad.Cone(); + const ax = cone.Axis(); + const loc = ax.Location(), dd = ax.Direction(); + const out = { p: xyz(loc), d: xyz(dd) }; + loc.delete(); dd.delete(); ax.delete(); cone.delete(); + return out; + } catch { + return null; + } finally { + ad.delete(); + } +} + +function boxesOverlap(a: { min: Vec3; max: Vec3 }, b: { min: Vec3; max: Vec3 }): boolean { + for (let k = 0; k < 3; k++) if (a.max[k] < b.min[k] - 1e-7 || b.max[k] < a.min[k] - 1e-7) return false; + return true; +} + +function meshOf(shape: Sh, diag: number): MeshData | null { + try { + const m = meshShape(shape, Math.max(diag * 0.001, 1e-4), 0.3); + if (!m.indices.length) return null; + return { positions: m.positions, normals: m.normals, indices: m.indices, vertexFace: new Float32Array(m.positions.length / 3), edgePositions: new Float32Array(0), edgeIds: new Float32Array(0), vertices: new Float32Array(0) }; + } catch { + return null; + } +} + +function copyMesh(m: MeshData | null): MeshData | null { + return m && { + positions: m.positions.slice(), normals: m.normals.slice(), indices: m.indices.slice(), vertexFace: m.vertexFace.slice(), + edgePositions: m.edgePositions.slice(), edgeIds: m.edgeIds.slice(), vertices: m.vertices.slice(), + }; +} + +/** Buffers of the meshes in results, to transfer rather than copy. */ +export function asmTransfers(result: unknown): Transferable[] { + const out: Transferable[] = []; + const add = (m: MeshData | null | undefined) => { + if (!m) return; + for (const a of [m.positions, m.normals, m.indices, m.vertexFace, m.edgePositions, m.edgeIds, m.vertices]) out.push(a.buffer as ArrayBuffer); + }; + if (Array.isArray(result)) for (const r of result) add((r as { mesh?: MeshData | null })?.mesh); + return out; +} diff --git a/src/parametric/src/kernel/build.ts b/src/parametric/src/kernel/build.ts index 3bde671441..7282147cd8 100644 --- a/src/parametric/src/kernel/build.ts +++ b/src/parametric/src/kernel/build.ts @@ -21,30 +21,37 @@ import type { } from '../model/types'; import { PARAM_FIELDS, dependencies, getPath, refFeatureIds } from '../model/features'; import { BASE_FRAMES } from '../model/planes'; +import { type SheetHost, type SheetModel, applySheetMetal, flatPattern } from './sheetmetal'; import { type Region, type Seg2, buildProfiles, hasOverlappingLines, holesMayTouch, inRegion, pointInPoly, reverseLoop, segPolyline, sketchPoints } from '../sketch/profiles'; import { SketchIndex, pointIdsOf, splineBeziers } from '../sketch/geom'; import { hasExternal, resolveExternal } from '../sketch/external'; import { solveSketch } from '../sketch/solver'; import { measureDimension } from '../sketch/ops'; import type { - BuildRequest, BuildResult, EdgeInfo, FaceInfo, FeatureStatus, MassProperties, MeasureResult, MeasureTarget, MeshData, - ProjectionRequest, ProjectionResult, + BuildRequest, BuildResult, EdgeInfo, FaceInfo, FeatureStatus, FlatPatternResult, MassProperties, MeasureResult, MeasureTarget, MeshData, + ProjectionRequest, ProjectionResult, WeldVolumes, } from './protocol'; +import { type WeldCtx, type WeldState, applyEndCap, applyGusset, applyStructuralMember, applyTrimExtend, applyWeldBead } from './weldments'; +import { projectSection } from './drawing-section'; import { type EdgeDesc, type Sh, type SurfDesc, ShapeIndex, bbox, compound, cut, describeEdge, describeFace, faceMidPoint, fuse, fuseAll, getOc, gdir, hashOf, isEmpty, isValid, meshEdgesOf, meshShape, mirrored, planarFaceFrame, plane, pnt, projectShape, rotated, sameSurface, sharesSurface, SurfaceCache, subShapes, translated, vertexPoint, volumeOf, wrap, xyz, } from './occ'; +import { SurfaceKit, bodyEdges, type SurfaceBody, type SurfState } from './surfaces'; +import { SURFACE_TYPES, type SurfaceFeature } from '../model/surfaces'; export { BASE_FRAMES }; export class FeatureError extends Error {} +// STL holds closed meshes for printing: surface bodies are left out of it. +const STL_SOLIDS_ONLY = 'STL files hold solids only, and this part has only surfaces. Thicken or knit the surfaces into a solid, or export STEP to keep them.'; // Thin (wall) extrudes and revolves are not built yet; failing beats // silently making a solid where a wall was asked for. const THIN_UNSUPPORTED = 'Thin features are not supported yet. Sketch the wall as two offset contours instead.'; -interface NamedFace { +export interface NamedFace { shape: Sh; name: string; desc: SurfDesc; @@ -66,7 +73,7 @@ interface Tool { parts?: Tool[]; } -interface State { +export interface State { body: Sh | null; faces: NamedFace[]; edges: NamedEdge[] | null; @@ -75,6 +82,12 @@ interface State { /** Projected sketch entities whose model edge or vertex is gone, by sketch. */ lostRefs: Map; tools: Map; + /** Surface bodies (see surfaces.ts); empty for parts without surface features. */ + surfaces: SurfaceBody[]; + /** Sheet metal model (sheetmetal.ts), from the first Base Flange on. */ + sheet?: SheetModel | null; + /** Structural members, end caps and gussets built so far (weldment parts only). */ + weld?: WeldState; } interface Step { @@ -83,7 +96,10 @@ interface Step { status: FeatureStatus; } -const emptyState = (): State => ({ body: null, faces: [], edges: null, frames: new Map(), sketches: new Map(), lostRefs: new Map(), tools: new Map() }); +const WELD_TOOL_TYPES = new Set(['structuralMember', 'endCap', 'gusset', 'weldBead']); +const WELD_TYPES = new Set([...WELD_TOOL_TYPES, 'trimExtend']); + +const emptyState = (): State => ({ body: null, faces: [], edges: null, frames: new Map(), sketches: new Map(), lostRefs: new Map(), tools: new Map(), surfaces: [] }); const cloneState = (s: State): State => ({ body: s.body, @@ -93,6 +109,9 @@ const cloneState = (s: State): State => ({ sketches: new Map(s.sketches), lostRefs: new Map(s.lostRefs), tools: new Map(s.tools), + surfaces: s.surfaces, + sheet: s.sheet, + weld: s.weld, }); /** A feature's numeric value at a path (dir1.count), named by its label when it is not a number. */ @@ -164,6 +183,8 @@ export function hashString(s: string, seed = 0): string { export class ModelBuilder { private steps: Step[] = []; private current: State = emptyState(); + /** Number of features the current state was built from. */ + private currentUpTo = 0; /** * What the cached mesh was made from. Keyed by the body and its faces, not * by the chain of steps: a sketch or plane leaves the body as it was, yet @@ -171,7 +192,7 @@ export class ModelBuilder { * meshed the whole part again and sent it to the GPU, 0.6 s on a plate of * 400 holes. */ - private meshKey: { body: Sh | null; faces: NamedFace[]; quality: number } | null = null; + private meshKey: { body: Sh | null; faces: NamedFace[]; quality: number; surfaces?: SurfaceBody[] } | null = null; private meshCache: { mesh: MeshData | null; faces: FaceInfo[]; edges: EdgeInfo[] } | null = null; reset() { @@ -271,6 +292,8 @@ export class ModelBuilder { next.body = state.body; next.faces = state.faces; next.edges = state.edges; + next.surfaces = state.surfaces; + next.sheet = state.sheet; } } this.steps[i] = { key, state: next, status: st }; @@ -280,6 +303,7 @@ export class ModelBuilder { } for (let i = upTo; i < req.features.length; i++) status.push({ id: req.features[i].id, ok: true }); this.current = state; + this.currentUpTo = upTo; // Imported shapes of parts no longer open (their file data is gone from // the request) would otherwise be kept for the life of the worker. for (const blob of [...this.importCache.keys()]) if (!(blob in req.blobs)) this.importCache.delete(blob); @@ -290,9 +314,11 @@ export class ModelBuilder { } const k = this.meshKey; - if (!k || k.body !== state.body || k.faces !== state.faces || k.quality !== req.quality || !this.meshCache) { + if (!k || k.body !== state.body || k.faces !== state.faces || k.quality !== req.quality || !this.meshCache || k.surfaces !== state.surfaces) { this.meshCache = this.meshState(state, req.quality); - this.meshKey = { body: state.body, faces: state.faces, quality: req.quality }; + // Surface bodies are drawn and picked with the solid, their faces and edges after its. + if (state.surfaces.length) this.meshCache = this.surf.mesh(this.meshCache, state, req.quality); + this.meshKey = { body: state.body, faces: state.faces, quality: req.quality, surfaces: state.surfaces }; } const frames: Record = {}; for (const [k, v] of state.frames) frames[k] = v; @@ -322,6 +348,11 @@ export class ModelBuilder { preview: null, sketches, }; + if (state.surfaces.length) { + result.bbox = this.surf.box(state); + result.surfaces = { face: state.faces.length, edge: this.edgesOf(state).length }; + } + if (state.weld) result.weldments = state.weld.members.map((m) => m.info); if (req.preview) { const p = cloneState(state); @@ -338,6 +369,10 @@ export class ModelBuilder { } else if (kind === 'body' && p.body) { result.preview = this.meshBody(p.body, req.quality); result.previewKind = 'body'; + } else if (kind === 'surface') { + const shape = this.surf.previewShape(p, req.preview.id); + if (shape) result.preview = this.meshBody(shape, req.quality); + result.previewKind = 'tool'; } if (req.preview.type === 'sketch' || req.preview.type === 'plane') { const fr = p.frames.get(req.preview.id); @@ -358,7 +393,7 @@ export class ModelBuilder { // ---- feature dispatch ---- /** Applies a feature to the state. Returns what a preview should show. */ - private async apply(f: Feature, st: State, req: BuildRequest): Promise<'tool' | 'body' | 'none'> { + private async apply(f: Feature, st: State, req: BuildRequest): Promise<'tool' | 'body' | 'none' | 'surface'> { switch (f.type) { case 'sketch': { const frame = this.resolvePlane(f.plane, st); @@ -380,7 +415,85 @@ export class ModelBuilder { case 'sweep': this.applySweep(f, st); return 'tool'; case 'draft': this.applyDraft(f, st); return 'body'; case 'import': await this.applyImport(f, st, req); return 'body'; + case 'baseFlange': + case 'edgeFlange': + case 'sketchedBend': + case 'hem': + applySheetMetal(this.sheetHost(), f, st); + // Its booleans leave a tool that is not the feature (a flange's cut or wall alone): it cannot be a pattern seed. + st.tools.delete(f.id); + return 'body'; + case 'structuralMember': applyStructuralMember(this.weldCtx(f.id, st), f); return 'tool'; + case 'trimExtend': applyTrimExtend(this.weldCtx(f.id, st), f); return 'body'; + case 'endCap': applyEndCap(this.weldCtx(f.id, st), f); return 'tool'; + case 'gusset': applyGusset(this.weldCtx(f.id, st), f); return 'tool'; + case 'weldBead': applyWeldBead(this.weldCtx(f.id, st), f); return 'tool'; } + if (SURFACE_TYPES.has(f.type)) return this.surf.apply(f as SurfaceFeature, st); + return 'none'; + } + + /** What the sheet metal features (sheetmetal.ts) use of the builder. */ + private sheetHost(): SheetHost { + return { + sketchRegions: (id, st) => this.sketchRegions(id, st as State), + regionFace: (r, fr) => this.regionFace(r, fr), + nearestSrc: (regions, p) => this.nearestSrc(regions, p), + applyTool: (featId, st, tool, faces, isCut, noGain) => this.applyTool(featId, st as State, tool, faces, isCut, noGain), + nameFaces: (featId, body, st, tool) => this.nameFaces(featId, body, st as State, tool), + edges: (st) => this.edgesOf(st as State), + resolveEdge: (ref, st) => this.resolveEdge(ref, st as State), + missing: (id, what) => this.missing(id, what), + error: (message) => new FeatureError(message), + warn: (message) => { this.warning = message; }, + }; + } + + /** The flat pattern of the sheet metal part as last built. */ + flatPattern(quality = 1): FlatPatternResult { + const r = flatPattern(this.current); + if ('error' in r) return { pattern: null, error: r.error, mesh: null }; + return { pattern: r.pattern, mesh: this.meshBody(r.solid, quality) }; + } + + /** What the weldment features (weldments.ts) use of the builder. */ + private weldCtx(featId: Id, st: State): WeldCtx { + return { + st, + featureId: featId, + sketch: (id) => { + const sk = st.sketches.get(id), frame = st.frames.get(id); + if (!sk || !frame) throw this.missing(id, 'layout sketch'); + return { entities: sk.entities, frame }; + }, + face: (ref) => { const f = st.faces[this.resolveFace(ref, st)]; return { name: f.name, desc: f.desc }; }, + edge: (ref) => { const e = this.edgesOf(st)[this.resolveEdge(ref, st)]; return { desc: e.desc, faces: e.faces.map((i) => ({ desc: st.faces[i].desc, shape: st.faces[i].shape })) }; }, + nameTool: (prefix, shape, classify) => this.nameTool(prefix, shape, (_d, k) => classify(k)), + applyTool: (tool, faces, noGain) => this.applyTool(featId, st, tool, faces as NamedFace[], false, noGain), + setBody: (body, faces) => { + st.faces = this.nameFaces(featId, body, st, faces as NamedFace[]); + st.body = body; + st.edges = null; + }, + bodyBefore: (id) => { + const i = this.order.get(id)?.index ?? -1; + return i > 0 ? this.steps[i - 1]?.state.body ?? null : null; + }, + toolsAfter: (id) => { + const from = this.order.get(id)?.index ?? Infinity; + const out = { adds: [] as Sh[], cuts: [] as Sh[] }; + for (const [fid, t] of st.tools) { + const o = this.order.get(fid); + // Members, caps, gussets and beads are in the weld state as they now stand (a trim may have changed them). + if (!o || o.index <= from || WELD_TOOL_TYPES.has(o.type)) continue; + for (const p of t.parts ?? [t]) (p.cut ? out.cuts : out.adds).push(p.shape); + } + return out; + }, + warn: (m) => { this.warning = m; }, + err: (m) => new FeatureError(m), + name: nameOf, + }; } /** @@ -392,6 +505,8 @@ export class ModelBuilder { if (!hasExternal(f)) return f; const sk = structuredClone(f); const find = (ref: EdgeRef) => { + const onSurface = st.surfaces.length ? this.surf.surfaceEdgeDesc(ref, st) : null; + if (onSurface) return onSurface; try { return this.edgesOf(st)[this.resolveEdge(ref, st)].desc; } catch (e) { @@ -425,6 +540,8 @@ export class ModelBuilder { if (!f) throw this.missing(ref.id, 'reference plane'); return f; } + const onSurface = st.surfaces.length ? this.surf.surfacePlane(ref.face, st, ref.x) : null; + if (onSurface) return onSurface; const i = this.resolveFace(ref.face, st); const d = st.faces[i].desc; if (d.type !== 'plane') throw new FeatureError('The selected face is not planar'); @@ -454,6 +571,8 @@ export class ModelBuilder { // face (references saved before a naming fix): then the signature decides. if (cands.length === 1 && fits(st.faces[cands[0]].desc)) return cands[0]; if (cands.length > 1) return near(cands); + // A face of a surface body is not one of the solid's: say so rather than "no longer exists". + if (!cands.length && st.surfaces.length && this.surf.findFace(ref, st)) throw new FeatureError(`A selected face${this.maker(ref.name)} is on a surface body, not the solid. Edit the feature and select a face of the solid.`); // Fallback: same type and orientation, nearest centre. const b = st.body ? boxOf(st.body) : null; const lim = b ? dist(b.min, b.max) * 0.05 : 1; @@ -485,6 +604,7 @@ export class ModelBuilder { const base = ref.name.replace(/#\d+$/, ''); const same = edges.flatMap((e, i) => (e.name.replace(/#\d+$/, '') === base ? [i] : [])); if (same.length) return split && base === ref.name ? same : [near(same)]; + if (st.surfaces.length && this.surf.findEdge(ref, st)) throw new FeatureError(`A selected edge${this.maker(ref.name)} is on a surface body, not the solid. Edit the feature and select an edge of the solid.`); const b = st.body ? boxOf(st.body) : null; const lim = b ? dist(b.min, b.max) * 0.02 : 1; const alt = edges.flatMap((e, i) => (e.desc.type === ref.sig.type && dist(e.desc.mid, ref.sig.m) < lim ? [i] : [])); @@ -498,6 +618,8 @@ export class ModelBuilder { /** Point and unit direction of an axis reference. */ resolveAxis(ref: AxisRef | null, st: State): { p: Vec3; d: Vec3 } { if (!ref) throw new FeatureError('Select a direction or axis'); + const onSurface = st.surfaces.length ? this.surf.surfaceAxis(ref, st) : null; + if (onSurface) return onSurface; switch (ref.kind) { case 'base': return { p: [0, 0, 0], d: ref.axis === 'x' ? [1, 0, 0] : ref.axis === 'y' ? [0, 1, 0] : [0, 0, 1] }; case 'edge': { @@ -1140,8 +1262,8 @@ export class ModelBuilder { this.applyTool(f.id, st, tool, named, true); } - private seedTools(featId: Id, seeds: Id[], st: State): Tool[] { - if (!seeds.length) throw new FeatureError('Select features to pattern'); + private seedTools(featId: Id, seeds: Id[], st: State, verb = 'pattern'): Tool[] { + if (!seeds.length) throw new FeatureError(`Select features to ${verb}`); return seeds.flatMap((id) => { const t = st.tools.get(id); if (t) return t.parts ?? [t]; @@ -1151,7 +1273,7 @@ export class ModelBuilder { if (at === undefined) throw new FeatureError('A seed feature no longer exists'); if (at.index > (this.order.get(featId)?.index ?? Infinity)) throw new FeatureError(`The seed feature ${nameOf(id)} comes after this feature in the tree`); if (SEED_TYPES.has(at.type)) throw new FeatureError(`The seed feature ${nameOf(id)} failed to build`); - throw new FeatureError(`${nameOf(id)} cannot be patterned (only extrudes, revolves, holes, lofts, sweeps and patterns)`); + throw new FeatureError(`${nameOf(id)} cannot be ${verb}ed (only extrudes, revolves, holes, lofts, sweeps and patterns)`); }); } @@ -1263,7 +1385,7 @@ export class ModelBuilder { this.applyTool(f.id, st, m, tf, false, 'The mirror adds no material: the part is already symmetric about the mirror plane.', true); return; } - this.applyInstances(f.id, st, this.seedTools(f.id, f.seeds, st), [(s) => mirrored(s, fr.o, fr.n)]); + this.applyInstances(f.id, st, this.seedTools(f.id, f.seeds, st, 'mirror'), [(s) => mirrored(s, fr.o, fr.n)]); } /** The first closed region of a profile sketch, as an outer wire and hole wires. */ @@ -1520,20 +1642,70 @@ export class ModelBuilder { /** Hidden-line removal projections of the current body. */ project(views: ProjectionRequest[]): ProjectionResult[] { - const body = this.current.body; + // Hidden surface bodies are not drawn (the views of one request share what is hidden). + const hidden = new Set(views[0]?.hideSurfaces ?? []); + const body = this.current.surfaces.length ? this.surf.allShapes(this.current, hidden) : this.current.body; const b = body ? boxOf(body) : null; // Curves other than lines and arcs are drawn within a thousandth of the part's size. const tol = b ? Math.max(dist(b.min, b.max) * 1e-3, 1e-4) : 0.01; return views.map((v) => { if (!body) return { id: v.id, visible: [], hidden: [], bounds: null }; - return { id: v.id, ...projectShape(body, v.dir, v.x, tol, tol / 10, v.hidden !== false) }; + if (v.section && b) return { id: v.id, ...projectSection(body, b, v, tol) }; + return { id: v.id, ...projectShape(body, v.dir, v.x, tol, tol / 10, v.hidden !== false, v.smooth !== false) }; }); } // ---- evaluation ---- + /** + * Volumes of the structural members as the part now stands, for the cut + * list: what a later cut or hole took from a member is left out (the member + * less those tools, a small boolean each, so this runs when the cut list is + * asked for, not on every rebuild). `approximate` when a later feature of + * another kind (a fillet, a shell) changed the body: those changes are not + * measured. Members not listed keep their volume as built. + */ + weldVolumes(): WeldVolumes { + const st = this.current; + const out: WeldVolumes = { volumes: [], approximate: false }; + if (!st.weld?.members.length || !st.body) return out; + const first = Math.min(...st.weld.members.map((m) => this.order.get(m.feature)?.index ?? Infinity)); + // The cut tools of the features after the first member, and whether any other feature changed the body there. + const after: { index: number; cut: Sh }[] = []; + const ids: Id[] = []; + for (const [id, o] of this.order) ids[o.index] = id; + for (let i = first + 1; i < this.currentUpTo; i++) { + const prev = this.steps[i - 1]?.state.body, cur = this.steps[i]?.state.body; + if (!cur || cur === prev) continue; + const o = this.order.get(ids[i]); + if (!o || WELD_TYPES.has(o.type)) continue; + const t = this.steps[i].state.tools.get(ids[i]); + if (!t) { out.approximate = true; continue; } + for (const p of t.parts ?? [t]) if (p.cut) after.push({ index: i, cut: p.shape }); + } + if (!after.length) return out; + const boxes = new Map>(); + const boxOf = (s: Sh) => { if (!boxes.has(s)) boxes.set(s, bbox(s)); return boxes.get(s)!; }; + const meets = (a: Sh, b: Sh) => { + const p = boxOf(a), q = boxOf(b); + return !!p && !!q && [0, 1, 2].every((k) => p.min[k] <= q.max[k] + 1e-6 && q.min[k] <= p.max[k] + 1e-6); + }; + for (const m of st.weld.members) { + const from = this.order.get(m.feature)?.index ?? Infinity; + const tools = after.filter((a) => a.index > from && meets(a.cut, m.solid)).map((a) => a.cut); + if (!tools.length) continue; + const left = cut(m.solid, tools.length === 1 ? tools[0] : compound(tools)); + out.volumes.push({ feature: m.feature, member: m.key, volume: isEmpty(left) ? 0 : volumeOf(left) }); + } + return out; + } + massProperties(): MassProperties | null { const body = this.current.body; + if (!body && this.current.surfaces.length) { + // Only surfaces: no volume or mass; their area is stated apart. + return { solid: false, volume: 0, area: 0, center: [0, 0, 0], inertia: [0, 0, 0, 0, 0, 0, 0, 0, 0], principal: eigenSym3([0, 0, 0, 0, 0, 0, 0, 0, 0]), surfaceArea: this.surf.area(this.current) }; + } if (!body) return null; const oc = getOc(); const props = new oc.GProp_GProps(); @@ -1560,7 +1732,9 @@ export class ModelBuilder { const volume = props.Mass(); const b = boxOf(body); const solid = volume > (b ? dist(b.min, b.max) : 1) ** 3 * 1e-12; - return { solid, volume, area: sprops.Mass(), center, inertia, principal: eigenSym3(inertia) }; + const out: MassProperties = { solid, volume, area: sprops.Mass(), center, inertia, principal: eigenSym3(inertia) }; + if (this.current.surfaces.length) out.surfaceArea = this.surf.area(this.current); + return out; } finally { props.delete(); sprops.delete(); @@ -1580,9 +1754,13 @@ export class ModelBuilder { } if (t.kind === 'face') { const f = this.current.faces[t.index]; + const s = !f && this.current.surfaces.length ? this.surf.shapeAt(this.current, 'face', t.index, this.current.faces.length) : null; + if (s) return s; if (!f) throw new FeatureError('Face not found'); return f.shape; } + const se = this.current.surfaces.length ? this.surf.shapeAt(this.current, 'edge', t.index, this.edgesOf(this.current).length) : null; + if (se) return se; const e = this.edgesOf(this.current)[t.index]; if (!e) throw new FeatureError('Edge not found'); return e.shape; @@ -1609,7 +1787,8 @@ export class ModelBuilder { /** A STEP file of the current body; its product (what other CAD systems list the body as) is named `name`. */ exportStep(name?: string): Uint8Array { - const body = this.current.body; + // Surface bodies go into the file as shells beside the solid. + const body = this.current.surfaces.length ? this.surf.allShapes(this.current) : this.current.body; if (!body) throw new FeatureError('There is no geometry to export'); const oc = getOc(); const writer = new oc.STEPControl_Writer(); @@ -1638,6 +1817,7 @@ export class ModelBuilder { /** Binary STL of the current body. */ exportStl(quality: number): Uint8Array { const body = this.current.body; + if (!body && this.current.surfaces.length) throw new FeatureError(STL_SOLIDS_ONLY); if (!body) throw new FeatureError('There is no geometry to export'); const { tol, ang } = this.meshParams(body, Math.max(1, quality)); const m = meshShape(body, tol * 0.5, ang * 0.5); @@ -1668,6 +1848,19 @@ export class ModelBuilder { return new Uint8Array(buf); } + /** The body built last with its faces and edges, in the order the build result lists them (assemblies place and combine these). */ + currentShapes(): { + body: Sh | null; faces: { shape: Sh; desc: SurfDesc }[]; edges: Sh[]; + /** Surface bodies (shells), and their faces and edges in the order the build result lists them after the solid's. */ + surfaces: Sh[]; surfaceFaces: Sh[]; surfaceEdges: Sh[]; + } { + const st = this.current; + return { + body: st.body, faces: st.faces.map((f) => ({ shape: f.shape, desc: f.desc })), edges: st.body ? this.edgesOf(st).map((e) => e.shape) : [], + surfaces: st.surfaces.map((b) => b.shape), surfaceFaces: st.surfaces.flatMap((b) => b.faces.map((f) => f.shape)), surfaceEdges: st.surfaces.flatMap((b) => bodyEdges(b).map((e) => e.shape)), + }; + } + /** Current body volume (used by tests). */ get hasBody(): boolean { return !!this.current.body; @@ -1689,6 +1882,35 @@ export class ModelBuilder { topologyHash(): number { return this.current.body ? hashOf(this.current.body.wrapped) : 0; } + + // ---- surfaces ---- + + /** Surface bodies of the current build (for tests). */ + surfaceBodies(): SurfaceBody[] { + return this.current.surfaces; + } + + private surfaceKit: SurfaceKit | null = null; + + /** Surface features (surfaces.ts), with the parts of the builder they use. */ + private get surf(): SurfaceKit { + const st = (s: SurfState) => s as State; + return (this.surfaceKit ??= new SurfaceKit({ + fail: (m) => new FeatureError(m), + missing: (id, what) => this.missing(id, what), + warn: (m) => { this.warning = m; }, + num: (f, path) => num(f, path), + sketchRegions: (id, s) => this.sketchRegions(id, st(s)), + regionFace: (r, fr) => this.regionFace(r, fr), + resolvePlane: (ref, s) => this.resolvePlane(ref, st(s)), + resolveAxis: (ref, s) => this.resolveAxis(ref, st(s)), + resolveFace: (ref, s) => this.resolveFace(ref, st(s)), + resolveEdge: (ref, s) => this.resolveEdge(ref, st(s)), + edgesOf: (s) => this.edgesOf(st(s)), + applyTool: (id, s, tool, faces, isCut, noGain) => this.applyTool(id, st(s), tool, faces, isCut, noGain), + nameFaces: (id, body, s, tool) => this.nameFaces(id, body, st(s), tool), + })); + } } /** diff --git a/src/parametric/src/kernel/client.ts b/src/parametric/src/kernel/client.ts index ab381781a3..5c25eea656 100644 --- a/src/parametric/src/kernel/client.ts +++ b/src/parametric/src/kernel/client.ts @@ -9,7 +9,8 @@ import type { SolidWorksImport } from '../formats/sldprt'; import type { Id } from '../model/types'; -import type { BuildRequest, BuildResult, MassProperties, MeasureResult, MeasureTarget, MeshData, ProjectionRequest, ProjectionResult, WorkerRequest, WorkerResponse } from './protocol'; +import type { AsmPartBuild, AsmRequest, AsmSceneItem } from './assembly'; +import type { BuildRequest, BuildResult, FlatPatternResult, MassProperties, MeasureResult, MeasureTarget, MeshData, ProjectionRequest, ProjectionResult, WeldVolumes, WorkerRequest, WorkerResponse } from './protocol'; type Pending = { resolve: (v: unknown) => void; reject: (e: Error) => void }; type Call = Pending & { at: number; type: WorkerRequest['type'] }; @@ -52,6 +53,8 @@ export class KernelClient { */ lastMesh: MeshData | null = null; private started = false; + /** Counts the workers started and resets: after either, the worker has none of the parts an assembly built. */ + generation = 0; private stalled = false; private watchdog: ReturnType | null = null; private readonly createWorker: () => Worker; @@ -63,6 +66,9 @@ export class KernelClient { /** Kernel memory after the current worker's first build: what the part needs. */ private baseHeap = 0; private recycleWanted = false; + /** The parts an open assembly had the worker build, and where it placed them: a replacing worker is given them again. */ + private asmParts = new Map(); + private asmScene: AsmSceneItem[] | null = null; readonly ready: Promise; /** Called after the worker was replaced; `building` tells whether a rebuild someone waits on was cut short. */ onRestart: (reason: string, building: boolean) => void = () => {}; @@ -83,6 +89,7 @@ export class KernelClient { private spawn() { const w = this.createWorker(); this.worker = w; + this.generation++; this.sentBlobs.clear(); this.lastMesh = null; this.baseHeap = 0; @@ -91,6 +98,7 @@ export class KernelClient { const p = this.pending.get(r.id); if (p) { this.pending.delete(r.id); + if (r.ok && r.heap) this.noteHeap(r.heap); if (r.ok) p.resolve(r.result); // An aborted kernel restarts the worker: the request was cut short like // any other one in flight then, and a rebuild is tried again (an @@ -199,10 +207,7 @@ export class KernelClient { this.call({ type: 'build', req: { ...req, blobs: fresh }, blobs: ids }) .then((res) => { if (!res.meshUnchanged) this.lastMesh = res.mesh; - if (res.heap) { - this.baseHeap ||= res.heap; - if (res.heap > Math.max(this.recycleBytes, 2 * this.baseHeap)) this.recycleWanted = true; - } + if (res.heap) this.noteHeap(res.heap); for (const w of waiters) w.resolve(res); }) .catch((e) => { for (const w of waiters) w.reject(e); }) @@ -215,6 +220,12 @@ export class KernelClient { }); } + /** Notes the kernel memory after a request: far past what the first request needed, the idle worker is replaced. */ + private noteHeap(heap: number) { + this.baseHeap ||= heap; + if (heap > Math.max(this.recycleBytes, 2 * this.baseHeap)) this.recycleWanted = true; + } + /** * Replaces a worker whose kernel memory has grown far past what the part * needs, while nothing waits on it. OpenCascade's booleans leak a little @@ -225,13 +236,20 @@ export class KernelClient { */ private recycle() { this.recycleWanted = false; - if (this.pending.size || !this.lastReq) return; + const asm = this.asmParts.size > 0; + if (this.pending.size || this.building || (!asm && !this.lastReq)) return; const old = this.worker; old.onmessage = old.onerror = old.onmessageerror = null; old.terminate(); this.spawn(); this.call({ type: 'init' }).catch(() => undefined); - this.run(this.lastReq, []); + if (!asm) { this.run(this.lastReq!, []); return; } + // An open assembly: the new worker builds its parts and places them again + // before anything else, so to the assembly it is the worker it had (a + // worker that dies doing so is restarted, and the assembly rebuilt). + this.generation--; + this.call({ type: 'asm', req: { op: 'build', parts: [...this.asmParts.values()] } }).catch(() => undefined); + if (this.asmScene) this.call({ type: 'asm', req: { op: 'scene', items: this.asmScene } }).catch(() => undefined); } get busy(): boolean { @@ -240,6 +258,8 @@ export class KernelClient { /** Drops all cached rebuild steps. */ reset(): Promise { + // The worker forgets the parts an assembly built, as a new worker would. + this.generation++; return this.call({ type: 'reset' }); } @@ -252,6 +272,16 @@ export class KernelClient { return this.call({ type: 'mass' }); } + /** Structural member volumes after later cuts, for the cut list (on demand: a boolean per member cut). */ + weldVolumes(): Promise { + return this.call({ type: 'weldVolumes' }); + } + + /** The flat pattern of the sheet metal part as last built. */ + flatPattern(quality = 1): Promise { + return this.call({ type: 'flatPattern', quality }); + } + measure(a: MeasureTarget, b: MeasureTarget): Promise { return this.call({ type: 'measure', a, b }); } @@ -275,6 +305,21 @@ export class KernelClient { return this.call({ type: 'checkImport', format: 'step', text }); } + /** Assembly requests: building parts, placing components, interference, mass (see kernel/assembly.ts). */ + assembly(req: AsmRequest): Promise { + if (req.op === 'build') for (const p of req.parts) this.asmParts.set(p.key, p); + else if (req.op === 'scene') this.asmScene = req.items; + else if (req.op === 'drop') { + const keep = new Set(req.keep); + for (const k of [...this.asmParts.keys()]) if (!keep.has(k)) this.asmParts.delete(k); + // Dropping every part closes the assembly. + if (!keep.size) this.asmScene = null; + } + // Assembly requests grow the kernel's memory too (interference, placed solids): once + // nothing else is waiting, a worker grown too big is replaced as after a part build. + return this.call({ type: 'asm', req }).finally(() => { if (this.recycleWanted && !this.building && !this.pending.size) this.recycle(); }); + } + /** Development builds: makes the worker fail on purpose (tests of recovery). */ debugFail(mode: 'hang' | 'abort' | 'crash'): Promise { return this.call({ type: 'debugFail', mode }); diff --git a/src/parametric/src/kernel/drawing-section.ts b/src/parametric/src/kernel/drawing-section.ts new file mode 100644 index 0000000000..527247e555 --- /dev/null +++ b/src/parametric/src/kernel/drawing-section.ts @@ -0,0 +1,94 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +// Section views of drawings: the body cut by a plane (the half between the viewer and +// the plane taken away) and the outline of the faces the cut makes, which the sheet hatches. + +import { type Vec3, cross, dot, normalize, perpendicular } from '../math/vec'; +import { type Sh, common, describeFace, getOc, projectShape, subShapes, transformShape, wrap, xyz } from './occ'; + +/** + * The part of `body` on the side of the plane through p that n points to ((x - p) . n >= 0). + * `size` is larger than the body (the half-space is a box of that half-width). + */ +export function halfOf(body: Sh, p: Vec3, n: Vec3, size: number): Sh { + const oc = getOc(); + const z = normalize(n), x = perpendicular(z), y = cross(z, x); + const a = new oc.gp_Pnt(-size, -size, 0), b = new oc.gp_Pnt(size, size, size); + const mk = new oc.BRepPrimAPI_MakeBox(a, b); + const tr = new oc.gp_Trsf(); + try { + const box = wrap(mk.Shape()); + // Columns: the box's x, y and z axes in the model, then its origin. + tr.SetValues(x[0], y[0], z[0], p[0], x[1], y[1], z[1], p[1], x[2], y[2], z[2], p[2]); + return common(body, transformShape(box, tr)); + } finally { + a.delete(); b.delete(); mk.delete(); tr.delete(); + } +} + +/** + * Outlines of the cut faces of `half` (made by halfOf with the same plane) as polylines in + * a view's coordinates (paper x along `xAxis`, y down along -(dir x xAxis), model millimetres), + * flat [x0, y0, x1, y1, ...]. Arcs and curves are drawn within `tol`. + */ +export function cutOutlines(half: Sh, p: Vec3, n: Vec3, dir: Vec3, xAxis: Vec3, tol: number): number[][] { + const oc = getOc(); + const up = cross(dir, xAxis); + const nn = normalize(n); + const out: number[][] = []; + const size = Math.max(tol * 1000, 1); + for (const f of subShapes(half, 'face')) { + const d = describeFace(f); + // A cut face lies in the plane and faces the half taken away. + if (d.type !== 'plane' || dot(d.d, nn) > -1 + 1e-7 || Math.abs(dot(d.center, nn) - dot(p, nn)) > 1e-6 * size) continue; + for (const e of subShapes(f, 'edge')) { + const ad = new oc.BRepAdaptor_Curve(e.wrapped); + const pts: number[] = []; + const push = (q: any) => { + const v = xyz(q); + pts.push(dot(v, xAxis), -dot(v, up)); + }; + try { + const u0 = ad.FirstParameter(), u1 = ad.LastParameter(); + if (!(u1 > u0)) continue; + if (ad.GetType() === oc.GeomAbs_CurveType.GeomAbs_Line) { + const a = ad.Value(u0), b = ad.Value(u1); + push(a); push(b); + a.delete(); b.delete(); + } else { + const td = new oc.GCPnts_TangentialDeflection(ad, u0, u1, 0.1, tol, 2, 1e-9, 1e-7); + try { + for (let i = 1; i <= td.NbPoints(); i++) { + const q = td.Value(i); + push(q); + q.delete(); + } + } finally { + td.delete(); + } + } + } finally { + ad.delete(); + } + if (pts.length >= 4) out.push(pts); + } + } + return out; +} + +/** A section view's projection: the half of the body behind the cutting plane, with the cut faces' outlines. */ +export function projectSection( + body: Sh, + box: { min: Vec3; max: Vec3 }, + v: { dir: Vec3; x: Vec3; hidden?: boolean; smooth?: boolean; section?: { p: Vec3; n: Vec3 } }, + tol: number, +): { visible: string[]; hidden: string[]; bounds: [number, number, number, number] | null; cut: number[][] } { + const { p, n } = v.section!; + // Larger than the body wherever on it the plane passes. + const size = 2 * (Math.hypot(box.max[0] - box.min[0], box.max[1] - box.min[1], box.max[2] - box.min[2]) + Math.hypot(...p) + Math.hypot(...box.min) + 1); + const half = halfOf(body, p, n, size); + if (!subShapes(half, 'face').length) return { visible: [], hidden: [], bounds: null, cut: [] }; + return { + ...projectShape(half, v.dir, v.x, tol, tol / 10, v.hidden !== false, v.smooth !== false), + cut: cutOutlines(half, p, n, v.dir, v.x, tol), + }; +} diff --git a/src/parametric/src/kernel/occ.ts b/src/parametric/src/kernel/occ.ts index a7aebb2cc4..5df1b45963 100644 --- a/src/parametric/src/kernel/occ.ts +++ b/src/parametric/src/kernel/occ.ts @@ -592,7 +592,7 @@ const add3 = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]] * Native objects are freed here, not left to the garbage collector: the projections of a whole * part take megabytes that the geometry worker would otherwise keep for as long as it runs. */ -export function projectShape(shape: Sh, dir: Vec3, xAxis: Vec3, tol: number, hair: number, withHidden = true): { visible: string[]; hidden: string[]; bounds: [number, number, number, number] | null } { +export function projectShape(shape: Sh, dir: Vec3, xAxis: Vec3, tol: number, hair: number, withHidden = true, smooth = true): { visible: string[]; hidden: string[]; bounds: [number, number, number, number] | null } { const origin = pnt([0, 0, 0]), n = gdir(dir), vx = gdir(xAxis); const ax = new oc.gp_Ax2(origin, n, vx); const projector = new oc.HLRAlgo_Projector(ax); @@ -617,10 +617,10 @@ export function projectShape(shape: Sh, dir: Vec3, xAxis: Vec3, tol: number, hai } }); // Sharp edges, smooth (tangent) edges and silhouettes. - const visible = lines(['VCompound', 'Rg1LineVCompound', 'OutLineVCompound'], box, shape.wrapped); + const visible = lines(smooth ? ['VCompound', 'Rg1LineVCompound', 'OutLineVCompound'] : ['VCompound', 'OutLineVCompound'], box, shape.wrapped); // A view drawn without hidden lines does not extract them: it takes time, and the // extraction of hidden sharp edges keeps some memory each time (inside OpenCascade). - const hidden = withHidden ? lines(['HCompound', 'Rg1LineHCompound', 'OutLineHCompound'], null, shape.wrapped) : []; + const hidden = withHidden ? lines(smooth ? ['HCompound', 'Rg1LineHCompound', 'OutLineHCompound'] : ['HCompound', 'OutLineHCompound'], null, shape.wrapped) : []; if (seams) { // The seams along the silhouette, drawn the hair outside it: their extent, less the hair, is the part's. const seamBox = [Infinity, Infinity, -Infinity, -Infinity]; diff --git a/src/parametric/src/kernel/protocol.ts b/src/parametric/src/kernel/protocol.ts index 8bd7fb6a83..077a4e4af3 100644 --- a/src/parametric/src/kernel/protocol.ts +++ b/src/parametric/src/kernel/protocol.ts @@ -3,6 +3,9 @@ import type { Frame, Vec3 } from '../math/vec'; import type { Feature, Id, SkEntity } from '../model/types'; +import type { FlatPattern } from '../model/flat-pattern'; +import type { WeldMemberInfo } from '../model/weldments'; +import type { AsmRequest } from './assembly'; /** Features with every Param already evaluated to a number. */ export type ResolvedFeature = Feature; @@ -37,6 +40,8 @@ export interface FaceInfo { radius?: number; /** Feature that last named this face. */ feature: Id; + /** The surface body the face is on (a surface feature's id); absent for faces of the solid. */ + body?: Id; } export interface EdgeInfo { @@ -52,6 +57,8 @@ export interface EdgeInfo { center?: Vec3; axis?: Vec3; radius?: number; + /** The surface body the edge is on; absent for edges of the solid. */ + body?: Id; } export interface MeshData { @@ -105,6 +112,17 @@ export interface BuildResult { previewWarning?: string; /** Bytes of WebAssembly memory the kernel holds after the build (it never shrinks). */ heap?: number; + /** Set when there are surface bodies: their faces and edges follow the solid's from these indices. */ + surfaces?: { face: number; edge: number }; + /** Structural members as built (weldment parts only), for the cut list. */ + weldments?: WeldMemberInfo[]; +} + +/** The flat pattern of a sheet metal part, and the solid showing it (placed on the part's base flange). */ +export interface FlatPatternResult { + pattern: FlatPattern | null; + error?: string; + mesh: MeshData | null; } export interface MassProperties { @@ -119,6 +137,8 @@ export interface MassProperties { /** Inertia tensor about the centre of mass (per unit density), row-major 3x3. */ inertia: number[]; principal: { moments: Vec3; axes: [Vec3, Vec3, Vec3] }; + /** Area of the surface bodies (not part of the solid's volume or area), when there are any. */ + surfaceArea?: number; } export type MeasureTarget = @@ -140,6 +160,15 @@ export interface ProjectionRequest { x: Vec3; /** Whether to find the hidden lines too (default true). */ hidden?: boolean; + /** Whether to draw smooth (tangent) edges (default true). */ + smooth?: boolean; + /** + * Section views: the body is cut by the plane through p with normal n, and only + * the part n points to ((x - p) . n >= 0) is projected. + */ + section?: { p: Vec3; n: Vec3 }; + /** Features whose surface bodies are hidden: left out of the view. */ + hideSurfaces?: Id[]; } export interface ProjectionResult { @@ -149,6 +178,10 @@ export interface ProjectionResult { hidden: string[]; /** [minX, minY, maxX, maxY] of the visible lines (y down). */ bounds: [number, number, number, number] | null; + /** Section views: outlines of the cut faces, polylines [x0, y0, x1, y1, ...] in the same coordinates. */ + cut?: number[][]; + /** Assembly section views: which component each cut outline belongs to (each is hatched its own way). */ + cutGroups?: number[]; } export type WorkerRequest = @@ -160,15 +193,28 @@ export type WorkerRequest = */ | { id: number; type: 'build'; req: BuildRequest; blobs: Id[] } | { id: number; type: 'mass' } + | { id: number; type: 'flatPattern'; quality: number } + /** Volumes of the structural members after later cuts, for the cut list. */ + | { id: number; type: 'weldVolumes' } | { id: number; type: 'project'; views: ProjectionRequest[] } | { id: number; type: 'measure'; a: MeasureTarget; b: MeasureTarget } | { id: number; type: 'export'; format: 'step' | 'stl' | 'brep'; quality: number; name?: string } | { id: number; type: 'checkImport'; format: 'step'; text: string } | { id: number; type: 'convertSolidWorks'; data: Uint8Array; name: string } + /** Assemblies: building their parts and the placed components (see assembly.ts). */ + | { id: number; type: 'asm'; req: AsmRequest } /** Development builds only: fail on purpose to test recovery. */ | { id: number; type: 'debugFail'; mode: 'hang' | 'abort' | 'crash' }; export type WorkerResponse = - | { id: number; ok: true; result: unknown } + /** heap: bytes of WebAssembly memory after the request (assembly requests; builds report it in their result). */ + | { id: number; ok: true; result: unknown; heap?: number } /** fatal: the OpenCascade module aborted and the worker must be replaced. */ | { id: number; ok: false; error: string; fatal?: boolean }; + +/** Structural member volumes after later cuts (see ModelBuilder.weldVolumes). */ +export interface WeldVolumes { + volumes: { feature: Id; member: string; volume: number }[]; + /** A later feature other than a cut changed the body: its change is not measured. */ + approximate: boolean; +} diff --git a/src/parametric/src/kernel/sheetmetal.ts b/src/parametric/src/kernel/sheetmetal.ts new file mode 100644 index 0000000000..45c5f79529 --- /dev/null +++ b/src/parametric/src/kernel/sheetmetal.ts @@ -0,0 +1,763 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +// Sheet metal features and the flat pattern. +// +// Alongside the body, a sheet metal part keeps a model of its sheet built +// from the feature definitions: flat regions (panels) and the bends joining +// them. Every panel is a planar face in one common flat-pattern plane (z = 0, +// the sheet spanning z = 0..T) with the rigid placement that takes it to the +// folded part. A bend is a strip of the flat pattern, as wide as its bend +// allowance, between the panel it starts from (fixed) and the panel it +// carries (moving); the moving panel's placement is the fixed one's followed +// by the bend's motion. Features change both the body (with booleans, so cuts, +// fillets and holes made in between are kept) and this model, from which the +// flat pattern is laid out: panels where they are, bends as strips, with the +// body's material in each panel (holes and cuts through the sheet) found by +// sectioning it at the panel's mid-plane. + +import * as R from 'replicad'; +import type { Frame, Vec2, Vec3 } from '../math/vec'; +import { add, cross, dot, normalize, scale, sub, toLocal } from '../math/vec'; +import type { Id } from '../model/types'; +import type { Region } from '../sketch/profiles'; +import { buildProfiles } from '../sketch/profiles'; +import { + type BendParams, type HemFeature, type ReliefType, CLOSED_HEM_GAP, bendAllowance, layoutOpenProfile, openChain, setback, sheetParamsError, + type BaseFlangeFeature, type EdgeFlangeFeature, type SheetMetalFeature, type SketchedBendFeature, +} from '../model/sheetmetal'; +import type { FlatBend, FlatLoop, FlatPattern, FlatSeg } from '../model/flat-pattern'; +import type { EdgeRef, SketchFeature } from '../model/types'; +import { + type Sh, type SurfDesc, common, cut, describeEdge, describeFace, faceProps, fuse, fuseAll, getOc, isEmpty, subShapes, transformShape, + translated, vertexPoint, volumeOf, wrap, xyz, +} from './occ'; + +// ---- the sheet model ---- + +export interface SmPanel { + id: string; + /** Planar face in the flat-pattern plane (z = 0). */ + face: Sh; + /** Flat-pattern coordinates to the folded part. */ + xf: Frame; +} + +export interface SmBend { + id: string; + feature: Id; + fixed: string; + moving: string; + /** Start of the bend line on the fixed panel, its direction u and the direction w across it toward the moving panel (flat). */ + s0: Vec2; + u: Vec2; + w: Vec2; + length: number; + /** Flat width (bend allowance). */ + width: number; + angle: number; + radius: number; + /** Bends toward +z of the flat pattern. */ + up: boolean; +} + +export interface SheetParams extends BendParams { + relief: ReliefType; + reliefRatio: number; +} + +export interface SheetModel { + /** The Base Flange holding the parameters. */ + owner: Id; + p: SheetParams; + panels: SmPanel[]; + bends: SmBend[]; +} + +/** Named face of a body (as in build.ts). */ +export interface SmNamedFace { + shape: Sh; + name: string; + desc: SurfDesc; + feature: Id; +} + +/** The builder's state, as far as sheet metal uses it. */ +export interface SmState { + body: Sh | null; + faces: SmNamedFace[]; + edges: unknown; + frames: Map; + sketches: Map; + sheet?: SheetModel | null; +} + +/** What sheet metal features use of the model builder. */ +export interface SheetHost { + sketchRegions(id: Id, st: SmState): { regions: Region[]; frame: Frame; sketch: SketchFeature }; + regionFace(r: Region, fr: Frame): any; + nearestSrc(regions: Region[], p: Vec2): string; + applyTool(featId: Id, st: SmState, tool: Sh, faces: SmNamedFace[], isCut: boolean, noGain?: string): void; + nameFaces(featId: Id, body: Sh, st: SmState, tool: SmNamedFace[]): SmNamedFace[]; + edges(st: SmState): { shape: Sh; name: string }[]; + resolveEdge(ref: EdgeRef, st: SmState): number; + missing(id: Id, what: string): Error; + error(message: string): Error; + warn(message: string): void; +} + +// ---- rigid placements (Frame: o + x*px + y*py + n*pz) ---- + +const EZ: Vec3 = [0, 0, 1]; + +export const xfApply = (f: Frame, p: Vec3): Vec3 => [ + f.o[0] + f.x[0] * p[0] + f.y[0] * p[1] + f.n[0] * p[2], + f.o[1] + f.x[1] * p[0] + f.y[1] * p[1] + f.n[1] * p[2], + f.o[2] + f.x[2] * p[0] + f.y[2] * p[1] + f.n[2] * p[2], +]; + +const xfDir = (f: Frame, d: Vec3): Vec3 => [ + f.x[0] * d[0] + f.y[0] * d[1] + f.n[0] * d[2], + f.x[1] * d[0] + f.y[1] * d[1] + f.n[1] * d[2], + f.x[2] * d[0] + f.y[2] * d[1] + f.n[2] * d[2], +]; + +export const xfLocal = (f: Frame, p: Vec3): Vec3 => { const d = sub(p, f.o); return [dot(d, f.x), dot(d, f.y), dot(d, f.n)]; }; + +export function xfInverse(f: Frame): Frame { + const x: Vec3 = [f.x[0], f.y[0], f.n[0]], y: Vec3 = [f.x[1], f.y[1], f.n[1]], n: Vec3 = [f.x[2], f.y[2], f.n[2]]; + return { o: [-dot(f.x, f.o), -dot(f.y, f.o), -dot(f.n, f.o)], x, y, n }; +} + +/** a after b. */ +export const xfCompose = (a: Frame, b: Frame): Frame => ({ o: xfApply(a, b.o), x: xfDir(a, b.x), y: xfDir(a, b.y), n: xfDir(a, b.n) }); + +export function placed(shape: Sh, f: Frame): Sh { + const oc = getOc(); + const tr = new oc.gp_Trsf(); + try { + tr.SetValues(f.x[0], f.y[0], f.n[0], f.o[0], f.x[1], f.y[1], f.n[1], f.o[1], f.x[2], f.y[2], f.n[2], f.o[2]); + return transformShape(shape, tr); + } finally { + tr.delete(); + } +} + +const rotate = (v: Vec3, d: Vec3, a: number): Vec3 => { + const c = Math.cos(a), s = Math.sin(a); + return add(add(scale(v, c), scale(cross(d, v), s)), scale(d, dot(d, v) * (1 - c))); +}; + +const w3 = (v: Vec2): Vec3 => [v[0], v[1], 0]; +const add2 = (a: Vec2, b: Vec2, k = 1): Vec2 => [a[0] + b[0] * k, a[1] + b[1] * k]; +const dot2 = (a: Vec2, b: Vec2) => a[0] * b[0] + a[1] * b[1]; + +/** Axis of a bend in the flat coordinates of its fixed panel. */ +function bendAxis(b: Pick, T: number): { c: Vec3; d: Vec3 } { + return { c: [b.s0[0], b.s0[1], b.up ? T + b.radius : -b.radius], d: b.up ? cross(w3(b.w), EZ) : cross(EZ, w3(b.w)) }; +} + +/** The bend's motion in flat coordinates: the moving side is moved back over the bend's width and turned about its axis. */ +export function bendMotion(b: Pick, T: number): Frame { + const { c, d } = bendAxis(b, T); + const a = (b.angle * Math.PI) / 180; + const shift = scale(w3(b.w), -b.width); + return { o: add(rotate(sub(shift, c), d, a), c), x: rotate([1, 0, 0], d, a), y: rotate([0, 1, 0], d, a), n: rotate(EZ, d, a) }; +} + +// ---- shapes ---- + +function polyFace(pts: Vec3[]): Sh { + return R.makeFace(R.assembleWire(pts.map((p, i) => R.makeLine(p, pts[(i + 1) % pts.length])))) as unknown as Sh; +} + +/** Rectangle in the flat plane from a corner along two directions. */ +const rectFace = (o: Vec2, u: Vec2, lu: number, w: Vec2, lw: number, z = 0): Sh => { + const p = (a: number, b: number): Vec3 => [o[0] + u[0] * a + w[0] * b, o[1] + u[1] * a + w[1] * b, z]; + return polyFace([p(0, 0), p(lu, 0), p(lu, lw), p(0, lw)]); +}; + +const extrudeZ = (face: Sh, from: number, to: number): Sh => { + const f = from !== 0 ? translated(face, [0, 0, from]) : face; + return R.basicFaceExtrusion(f as any, new R.Vector([0, 0, to - from])) as unknown as Sh; +}; + +/** The solid of a bend in its fixed panel's flat coordinates (z0, z1 widen it past the sheet). */ +function bendSolid(b: SmBend, T: number, z0 = 0, z1 = T): Sh { + const { c, d } = bendAxis(b, T); + const p = (t: number, z: number): Vec3 => [b.s0[0] + b.u[0] * t, b.s0[1] + b.u[1] * t, z]; + const face = polyFace([p(0, z0), p(b.length, z0), p(b.length, z1), p(0, z1)]); + return R.revolution(face as any, c, d, b.angle) as unknown as Sh; +} + +/** Faces of a fused flat region merged where they meet (the boolean leaves them apart). */ +function unified(shape: Sh): Sh { + const oc = getOc(); + const u = new oc.ShapeUpgrade_UnifySameDomain(shape.wrapped, true, true, false); + try { + u.Build(); + return wrap(u.Shape()); + } finally { + u.delete(); + } +} + +/** A flat face with its normal toward +z (faces of opposite sides are not merged). */ +const facingUp = (f: Sh): Sh => (describeFace(f).d[2] < 0 ? wrap(f.wrapped.Reversed()) : f); + +const area = (s: Sh) => subShapes(s, 'face').reduce((a, f) => a + faceProps(f.wrapped).area, 0); + +/** Points along an edge (lines: its ends). */ +function edgePoints(e: Sh, n = 24): Vec3[] { + const d = describeEdge(e); + if (d.type === 'line') return [d.a, d.b]; + const oc = getOc(); + const ad = new oc.BRepAdaptor_Curve(e.wrapped); + try { + const f = ad.FirstParameter(), l = ad.LastParameter(); + const out: Vec3[] = []; + for (let i = 0; i <= n; i++) { const p = ad.Value(f + ((l - f) * i) / n); out.push(xyz(p)); p.delete(); } + return out; + } finally { + ad.delete(); + } +} + +/** Whether a flat point lies inside a flat face (even-odd over its boundary). */ +function insideFlat(face: Sh, q: Vec2): boolean { + let inside = false; + for (const e of subShapes(face, 'edge')) { + const pts = edgePoints(e); + for (let i = 0; i + 1 < pts.length; i++) { + const a = pts[i], b = pts[i + 1]; + if ((a[1] > q[1]) !== (b[1] > q[1]) && q[0] < a[0] + ((q[1] - a[1]) * (b[0] - a[0])) / (b[1] - a[1])) inside = !inside; + } + } + return inside; +} + +interface Piece { solid: Sh; faces: SmNamedFace[] } + +/** A solid made in flat coordinates, placed, with each face named by classify (looking at it in flat coordinates). */ +function namedPiece(featId: Id, flat: Sh, xf: Frame, classify: (d: SurfDesc) => string): Piece { + const faces = subShapes(flat, 'face').map((f) => { + const name = `${featId}:${classify(describeFace(f))}`; + const shape = placed(f, xf); + return { shape, desc: describeFace(shape), name, feature: featId }; + }); + return { solid: placed(flat, xf), faces }; +} + +const near = (a: number, b: number, tol: number) => Math.abs(a - b) <= tol; + +// ---- dispatch ---- + +export function applySheetMetal(h: SheetHost, f: SheetMetalFeature, st: SmState) { + switch (f.type) { + case 'baseFlange': return st.sheet ? applyTab(h, f, st) : applyBaseFlange(h, f, st); + case 'edgeFlange': return applyEdgeFlange(h, f, st); + case 'hem': return applyHem(h, f, st); + case 'sketchedBend': return applySketchedBend(h, f, st); + } +} + +const num = (h: SheetHost, v: unknown, label: string): number => { + const x = typeof v === 'number' ? v : Number(v); + if (!Number.isFinite(x)) throw h.error(`${label} has an invalid value`); + return x; +}; + +function sheetOf(h: SheetHost, st: SmState, what: string): SheetModel { + if (!st.sheet || !st.body) throw h.error(`${what} needs a sheet metal part. Start with a Base Flange.`); + return st.sheet; +} + +// ---- base flange ---- + +function applyBaseFlange(h: SheetHost, f: BaseFlangeFeature, st: SmState) { + const p: SheetParams = { + thickness: num(h, f.sm.thickness, 'Thickness'), radius: num(h, f.sm.radius, 'Bend radius'), allowance: f.sm.allowance, + kFactor: num(h, f.sm.kFactor, 'K-factor'), allowanceValue: num(h, f.sm.allowanceValue, 'Bend allowance'), relief: f.sm.relief, + reliefRatio: num(h, f.sm.reliefRatio, 'Relief ratio'), + }; + const bad = sheetParamsError(p); + if (bad) throw h.error(bad); + if (p.relief !== 'none' && !(p.reliefRatio > 0)) throw h.error('The relief ratio must be greater than zero'); + const sketch = st.sketches.get(f.sketch); + const frame = st.frames.get(f.sketch); + if (!sketch || !frame) throw h.missing(f.sketch, 'profile sketch'); + const T = p.thickness; + if (buildProfiles(sketch.entities).regions.length) { + // Closed profile: a flat plate. + const { regions } = h.sketchRegions(f.sketch, st); + if (regions.length !== 1) throw h.error('A base flange needs one closed profile (it may have holes)'); + // Thickness along the sketch normal (or against it), its frame kept right-handed. + const at: Frame = f.flip ? { o: frame.o, x: frame.x, y: scale(frame.y, -1), n: scale(frame.n, -1) } : { ...frame }; + const xf: Frame = f.mid ? { ...at, o: sub(at.o, scale(at.n, T / 2)) } : at; + const flatFace = placed(h.regionFace(regions[0], frame) as Sh, xfInverse(at)); + const piece = namedPiece(f.id, extrudeZ(flatFace, 0, T), xf, (d) => { + if (d.type === 'plane' && Math.abs(d.d[2]) > 1 - 1e-6) return d.center[2] < T / 2 ? 'cap0' : 'cap1'; + return 'side:' + h.nearestSrc(regions, toLocal(frame, xfApply(at, [d.center[0], d.center[1], 0]))); + }); + h.applyTool(f.id, st, piece.solid, piece.faces, false); + st.sheet = { owner: f.id, p, panels: [{ id: `${f.id}:p0`, face: flatFace, xf }], bends: [] }; + return; + } + // Open profile: thickened along the chain and extruded, with bends at the corners. + const chain = openChain(sketch.entities); + if ('error' in chain) throw h.error(chain.error === 'The profile is closed' ? 'The sketch has no closed or open profile' : chain.error); + const zl = f.mid ? T / 2 : f.flip ? T : 0; + const lay = layoutOpenProfile(chain.segs, p, zl); + if ('error' in lay) throw h.error(lay.error); + const D = num(h, f.depth, 'Depth'); + if (!(D > 0)) throw h.error('Depth must be greater than zero'); + // Flat y runs against the sketch normal, so a blind depth along the normal is y in [-D, 0]. + const [y0, y1] = f.depthEnd === 'midPlane' ? [-D / 2, D / 2] : f.depthFlip ? [0, D] : [-D, 0]; + const r0 = lay.runs[0]; + const d0 = normalize(sub(toWorld3(frame, add2(r0.a, r0.d)), toWorld3(frame, r0.a))); + const nL = cross(frame.n, d0); + let xf: Frame = { o: sub(toWorld3(frame, r0.a), add(scale(nL, zl), scale(d0, r0.x0))), x: d0, y: scale(frame.n, -1), n: nL }; + const panels: SmPanel[] = []; + const bends: SmBend[] = []; + const pieces: Piece[] = []; + const last = lay.runs.length - 1; + const capName = (y: number) => (near(y, f.depthEnd === 'midPlane' ? y0 : 0, 1e-6 * D) ? 'cap0' : 'cap1'); + lay.runs.forEach((run, i) => { + const face = rectFace([run.x0, y0], [1, 0], run.x1 - run.x0, [0, 1], y1 - y0); + const id = `${f.id}:p${i}`; + panels.push({ id, face, xf }); + pieces.push(namedPiece(f.id, extrudeZ(face, 0, T), xf, (d) => { + if (Math.abs(d.d[2]) > 1 - 1e-6) return `${run.src}:${d.center[2] < T / 2 ? 'a' : 'b'}`; + if (Math.abs(d.d[1]) > 1 - 1e-6) return capName(d.center[1]); + if (i === 0 && near(d.center[0], run.x0, 1e-6 * D)) return 'end0'; + if (i === last && near(d.center[0], run.x1, 1e-6 * D)) return 'end1'; + return `${run.src}:joint`; + })); + if (i === last) return; + const lb = lay.bends[i]; + const b: SmBend = { + id: `${f.id}:b${i}`, feature: f.id, fixed: id, moving: `${f.id}:p${i + 1}`, s0: [lb.x, y0], u: [0, 1], w: [1, 0], length: y1 - y0, + width: lb.width, angle: lb.angle, radius: lb.radius, up: lb.up, + }; + bends.push(b); + pieces.push(namedPiece(f.id, bendSolid(b, T), xf, (d) => { + if (d.type === 'cylinder') return `bend:${lb.src}:${near(d.r, b.radius, 1e-6 * T + 1e-9) ? 'in' : 'out'}`; + if (d.type === 'plane' && Math.abs(d.d[1]) > 1 - 1e-6) return capName(d.center[1]); + return `bend:${lb.src}:joint`; + })); + xf = xfCompose(xf, bendMotion(b, T)); + }); + const tool = fuseAll(pieces.map((x) => x.solid)); + // The pieces only touch, unless the profile crosses itself or its sides come closer than the thickness. + const expected = (y1 - y0) * (lay.runs.reduce((s, r) => s + (r.x1 - r.x0) * T, 0) + + bends.reduce((s, b) => s + ((b.angle * Math.PI) / 180) * T * (b.radius + T / 2), 0)); + if (volumeOf(tool) < expected * (1 - 1e-6)) throw h.error('The profile crosses itself, or its sides come closer than the sheet thickness'); + h.applyTool(f.id, st, tool, pieces.flatMap((x) => x.faces), false); + st.sheet = { owner: f.id, p, panels, bends }; +} + +const toWorld3 = (f: Frame, p: Vec2): Vec3 => add(f.o, add(scale(f.x, p[0]), scale(f.y, p[1]))); + +/** The panel a sketch plane lies on (its plane level with the panel's top or bottom face), with the side. */ +function panelOfPlane(sheet: SheetModel, frame: Frame, at?: Vec3): { panel: SmPanel; top: boolean } | null { + const T = sheet.p.thickness; + const tol = Math.max(1e-6, T * 1e-5); + let best: { panel: SmPanel; top: boolean } | null = null; + for (const panel of sheet.panels) { + const c = dot(frame.n, panel.xf.n); + if (Math.abs(c) < 1 - 1e-7) continue; + const z = xfLocal(panel.xf, frame.o)[2]; + const top = near(z, T, tol) && c > 0; + if (!top && !(near(z, 0, tol) && c < 0)) continue; + if (at) { + const q = xfLocal(panel.xf, at); + if (!insideFlat(panel.face, [q[0], q[1]])) continue; + } + best = { panel, top }; + break; + } + return best; +} + +function replacePanels(sheet: SheetModel, panels: SmPanel[], bends: SmBend[] = sheet.bends): SheetModel { + return { ...sheet, panels, bends }; +} + +// ---- tab ---- + +function applyTab(h: SheetHost, f: BaseFlangeFeature, st: SmState) { + const sheet = sheetOf(h, st, 'A tab'); + const sketch = st.sketches.get(f.sketch); + const frame = st.frames.get(f.sketch); + if (!sketch || !frame) throw h.missing(f.sketch, 'profile sketch'); + if (!buildProfiles(sketch.entities).regions.length) throw h.error('This part already has a base flange: another one is a tab, which needs a closed profile on a flat face of the sheet'); + const { regions } = h.sketchRegions(f.sketch, st); + const T = sheet.p.thickness; + const on = panelOfPlane(sheet, frame); + if (!on) throw h.error('Sketch the tab on a flat face of the sheet metal part'); + const { panel } = on; + const toFlat = xfInverse(panel.xf); + const faces = regions.map((r) => { + const flat = placed(h.regionFace(r, frame) as Sh, toFlat); + return on.top ? translated(flat, [0, 0, -T]) : flat; + }); + const flatFace = faces.length === 1 ? faces[0] : fuseAll(faces); + const piece = namedPiece(f.id, extrudeZ(flatFace, 0, T), panel.xf, (d) => { + if (d.type === 'plane' && Math.abs(d.d[2]) > 1 - 1e-6) return d.center[2] < T / 2 ? 'cap0' : 'cap1'; + return 'side:' + h.nearestSrc(regions, toLocal(frame, xfApply(panel.xf, [d.center[0], d.center[1], on.top ? T : 0]))); + }); + const before = st.body ? subShapes(st.body, 'solid').length : 0; + h.applyTool(f.id, st, piece.solid, piece.faces, false, 'The tab adds no material: it lies on the sheet already.'); + if (st.body && subShapes(st.body, 'solid').length > before) throw h.error('The tab must touch the edge of the face it is sketched on'); + const merged = unified(fuse(panel.face, flatFace)); + const face = subShapes(merged, 'face'); + st.sheet = replacePanels(sheet, sheet.panels.map((x) => (x === panel ? { ...x, face: face.length === 1 ? face[0] : merged } : x))); +} + +// ---- edge flanges and hems ---- + +interface FlangeSpec { + angle: number; + radius: number; + /** How far the panel is cut back from the edge for the bend. */ + trim: number; + /** Length of the flat part of the flange. */ + straight: number; + flip: boolean; + offset1: number; + offset2: number; +} + +/** The panel and boundary of a selected sheet edge. */ +function sheetEdge(h: SheetHost, sheet: SheetModel, st: SmState, ref: EdgeRef) { + const T = sheet.p.thickness; + // A reference read from a file may lack its signature: then only its name finds the edge. + const at = ref.sig ? h.resolveEdge(ref, st) : h.edges(st).findIndex((e) => e.name === ref.name); + if (at < 0) throw h.error('A selected edge no longer exists. Edit the feature and select it again.'); + const edge = h.edges(st)[at]; + const d = describeEdge(edge.shape); + if (d.type !== 'line') throw h.error('Select straight edges of the sheet (an edge along a flat face)'); + const tol = Math.max(1e-6, T * 1e-4); + let across = false; + for (const panel of sheet.panels) { + const a = xfLocal(panel.xf, d.a), b = xfLocal(panel.xf, d.b); + const onFace = (z: number) => near(z, 0, tol) || near(z, T, tol); + if (!near(a[2], b[2], tol) || !onFace(a[2])) { + if (onFace(a[2]) && onFace(b[2]) && near(Math.hypot(a[0] - b[0], a[1] - b[1]), 0, tol)) across = true; + continue; + } + for (const e of subShapes(panel.face, 'edge')) { + const s = describeEdge(e); + if (s.type !== 'line') continue; + const p: Vec2 = [s.a[0], s.a[1]], q: Vec2 = [s.b[0], s.b[1]]; + const L = Math.hypot(q[0] - p[0], q[1] - p[1]); + const u: Vec2 = [(q[0] - p[0]) / L, (q[1] - p[1]) / L]; + const off = (pt: Vec3) => Math.abs((pt[0] - p[0]) * u[1] - (pt[1] - p[1]) * u[0]); + if (off(a) > tol || off(b) > tol) continue; + const ta = dot2([a[0] - p[0], a[1] - p[1]], u), tb = dot2([b[0] - p[0], b[1] - p[1]], u); + const t0 = Math.max(0, Math.min(ta, tb)), t1 = Math.min(L, Math.max(ta, tb)); + if (t1 - t0 < tol) continue; + // Across the edge, out of the panel. + let w: Vec2 = [u[1], -u[0]]; + const mid = add2(p, u, (t0 + t1) / 2); + if (insideFlat(panel.face, add2(mid, w, Math.min(T, L) * 1e-3))) w = [-w[0], -w[1]]; + return { panel, p, u, w, L, t0, t1, top: near(a[2], T, tol) }; + } + } + if (across) throw h.error('Select an edge along a face of the sheet, not one across its thickness'); + throw h.error('The selected edge is not an outside edge of a flat region of the sheet. Select an edge along the boundary of a flat face.'); +} + +function addFlange(h: SheetHost, st: SmState, featId: Id, k: number, ref: EdgeRef, spec: FlangeSpec, what: string) { + const sheet = st.sheet!; + const T = sheet.p.thickness; + const { panel, p, u, w, L, t0: e0, t1: e1, top } = sheetEdge(h, sheet, st, ref); + const t0 = e0 + spec.offset1, t1 = e1 - spec.offset2; + if (t1 - t0 < 1e-6) throw h.error(`The offsets leave no ${what}`); + if (!(spec.straight > 1e-6)) throw h.error(`The ${what} is too short for the bend radius and thickness`); + const up = top !== spec.flip; + const tag = `e${k}`; + // Cut the panel back where the bend goes (a strip along the edge), with reliefs where the flange stops short of the panel's edge. + const s0 = add2(add2(p, u, t0), w, -spec.trim); + let panelFace = panel.face; + if (spec.trim > 1e-9) { + const strip = rectFace(s0, u, t1 - t0, w, spec.trim); + if (area(common(panel.face, strip)) < (t1 - t0) * spec.trim * (1 - 1e-6)) throw h.error(`The face is too narrow for the ${what} with this position, or has a hole or cut where its bend goes. Use Bend Outside or move the hole.`); + const eps = Math.max(T * 0.01, 1e-4); + const tools: Sh[] = [extrudeZ(rectFace(s0, u, t1 - t0, w, spec.trim + eps), -eps, T + eps)]; + const rw = sheet.p.reliefRatio * T; + if (sheet.p.relief !== 'none') { + const ends: number[] = []; + if (t0 > 1e-6) ends.push(t0 - rw); + if (t1 < L - 1e-6) ends.push(t1); + for (const at of ends) { + const depth = spec.trim + rw; + const corner = add2(add2(p, u, at), w, -depth); + if (sheet.p.relief === 'rectangular') tools.push(extrudeZ(rectFace(corner, u, rw, w, depth + eps), -eps, T + eps)); + else { + tools.push(extrudeZ(rectFace(add2(corner, w, rw / 2), u, rw, w, depth - rw / 2 + eps), -eps, T + eps)); + const c = add2(add2(corner, w, rw / 2), u, rw / 2); + tools.push(R.makeCylinder(rw / 2, T + 2 * eps, [c[0], c[1], -eps], [0, 0, 1]) as unknown as Sh); + } + } + } + const cutter = namedPiece(featId, tools.length === 1 ? tools[0] : fuseAll(tools), panel.xf, (d) => (d.type === 'plane' && Math.abs(dot2([d.d[0], d.d[1]], w)) > 1 - 1e-6 ? `${tag}:trim` : `${tag}:relief`)); + h.applyTool(featId, st, cutter.solid, cutter.faces, true); + panelFace = cut(panel.face, strip); + } + const b: SmBend = { + id: `${featId}:${tag}`, feature: featId, fixed: panel.id, moving: `${featId}:${tag}`, s0, u, w, length: t1 - t0, + width: bendAllowance(spec.angle, spec.radius, sheet.p), angle: spec.angle, radius: spec.radius, up, + }; + if (!(b.width > 0)) throw h.error('The bend allowance must be greater than zero'); + const xf = xfCompose(panel.xf, bendMotion(b, T)); + const face = rectFace(add2(s0, w, b.width), u, b.length, w, spec.straight); + const side = (c: SurfDesc['center']) => (dot2([c[0] - s0[0], c[1] - s0[1]], u) < b.length / 2 ? `${tag}:side0` : `${tag}:side1`); + const bend = namedPiece(featId, bendSolid(b, T), panel.xf, (d) => { + if (d.type === 'cylinder') return `${tag}:bend:${near(d.r, b.radius, 1e-6 * T + 1e-9) ? 'in' : 'out'}`; + if (d.type === 'plane' && Math.abs(dot2([d.d[0], d.d[1]], u)) > 1 - 1e-6) return side(d.center); + return `${tag}:joint`; + }); + const flange = namedPiece(featId, extrudeZ(face, 0, T), xf, (d) => { + if (Math.abs(d.d[2]) > 1 - 1e-6) return `${tag}:flange:${(d.center[2] > T / 2) === up ? 'in' : 'out'}`; + if (Math.abs(dot2([d.d[0], d.d[1]], u)) > 1 - 1e-6) return side(d.center); + return dot2([d.center[0] - s0[0], d.center[1] - s0[1]], w) > b.width + spec.straight / 2 ? `${tag}:end` : `${tag}:joint`; + }); + const tool = fuse(bend.solid, flange.solid); + // The bend only touches its panel, so the body gains all of the new wall unless the wall runs into the part. + const before = volumeOf(st.body!), added = volumeOf(tool); + h.applyTool(featId, st, tool, [...bend.faces, ...flange.faces], false); + if (volumeOf(st.body!) < before + added * (1 - 1e-6)) throw h.error(what === 'flange' ? 'The flange runs into the part. Shorten it, change its angle or direction, or stop it short of other flanges with offsets.' : `The ${what} runs into the part. Shorten it or reverse its direction.`); + st.sheet = replacePanels(sheet, [...sheet.panels.map((x) => (x === panel ? { ...x, face: panelFace } : x)), { id: b.moving, face, xf }], [...sheet.bends, b]); +} + +function applyEdgeFlange(h: SheetHost, f: EdgeFlangeFeature, st: SmState) { + const sheet = sheetOf(h, st, 'An edge flange'); + if (!f.edges.length) throw h.error('Select one or more edges of the sheet'); + const T = sheet.p.thickness, R0 = sheet.p.radius; + const angle = num(h, f.angle, 'Angle'); + if (!(angle > 0 && angle < 180)) throw h.error('The flange angle must be more than 0 and less than 180 degrees'); + const length = num(h, f.length, 'Flange length'); + if (!(length > 0)) throw h.error('The flange length must be greater than zero'); + const trim = f.position === 'materialInside' ? setback(angle, R0 + T) : f.position === 'materialOutside' ? setback(angle, R0) : 0; + const straight = length - (f.lengthRef === 'outer' ? setback(angle, R0 + T) : f.lengthRef === 'inner' ? setback(angle, R0) : 0); + const offset1 = num(h, f.offset1, 'Offset 1'), offset2 = num(h, f.offset2, 'Offset 2'); + if (offset1 < 0 || offset2 < 0) throw h.error('Offsets cannot be negative'); + f.edges.forEach((ref, k) => addFlange(h, st, f.id, k, ref, { angle, radius: R0, trim, straight, flip: f.flip, offset1, offset2 }, 'flange')); +} + +function applyHem(h: SheetHost, f: HemFeature, st: SmState) { + const sheet = sheetOf(h, st, 'A hem'); + if (!f.edges.length) throw h.error('Select one or more edges of the sheet'); + const T = sheet.p.thickness; + const gap = f.kind === 'closed' ? CLOSED_HEM_GAP * T : num(h, f.gap, 'Gap'); + if (!(gap > 0)) throw h.error('The gap of an open hem must be greater than zero'); + const length = num(h, f.length, 'Length'); + if (!(length > 0)) throw h.error('The hem length must be greater than zero'); + const radius = gap / 2; + const straight = length - (radius + T); + const trim = f.position === 'materialInside' ? radius + T : 0; + f.edges.forEach((ref, k) => addFlange(h, st, f.id, k, ref, { angle: 180, radius, trim, straight, flip: f.flip, offset1: 0, offset2: 0 }, 'hem')); +} + +// ---- sketched bend ---- + +function applySketchedBend(h: SheetHost, f: SketchedBendFeature, st: SmState) { + const sheet = sheetOf(h, st, 'A sketched bend'); + const body = st.body!; + const sketch = st.sketches.get(f.sketch); + const frame = st.frames.get(f.sketch); + if (!sketch || !frame) throw h.missing(f.sketch, 'bend line sketch'); + const lines = sketch.entities.filter((e) => e.t === 'line' && !e.construction); + const others = sketch.entities.filter((e) => e.t !== 'point' && e.t !== 'line' && !e.construction); + if (lines.length !== 1 || others.length) throw h.error('Sketch a single line for the bend'); + const line = lines[0] as Extract; + const pt = (id: Id): Vec2 => { const e = sketch.entities.find((x) => x.id === id); return e && e.t === 'point' ? [e.x, e.y] : [NaN, NaN]; }; + const A = toWorld3(frame, pt(line.a)), B = toWorld3(frame, pt(line.b)); + const T = sheet.p.thickness, Rb = sheet.p.radius; + const angle = num(h, f.angle, 'Angle'); + if (!(angle > 0 && angle < 180)) throw h.error('The bend angle must be more than 0 and less than 180 degrees'); + // The face under the line (its middle, else another point of a line drawn past the face). + let on: ReturnType = null; + for (const t of [0.5, 0.25, 0.75, 0.1, 0.9, 0.4, 0.6, 0.02, 0.98]) if ((on = panelOfPlane(sheet, frame, add(A, scale(sub(B, A), t))))) break; + if (!on) throw h.error('Sketch the bend line on a flat face of the sheet metal part'); + const { panel } = on; + const la = xfLocal(panel.xf, A), lb = xfLocal(panel.xf, B); + let u: Vec2 = [lb[0] - la[0], lb[1] - la[1]]; + const ul = Math.hypot(u[0], u[1]); + if (ul < 1e-9) throw h.error('The bend line has no length'); + u = [u[0] / ul, u[1] / ul]; + // The same direction whichever end the line was drawn from; the fixed side is to its left. + if (u[0] < -1e-9 || (Math.abs(u[0]) <= 1e-9 && u[1] < 0)) u = [-u[0], -u[1]]; + let w: Vec2 = [u[1], -u[0]]; + if (f.flipFixed) w = [-w[0], -w[1]]; + const up = on.top !== f.flip; + const width = bendAllowance(angle, Rb, sheet.p); + if (!(width > 0)) throw h.error('The bend allowance must be greater than zero'); + const start = f.position === 'centerline' ? -width / 2 : f.position === 'materialInside' ? -setback(angle, Rb + T) : f.position === 'materialOutside' ? -setback(angle, Rb) : 0; + // Half-planes of the panel's flat face beside and across the bend strip. + const box = subShapes(panel.face, 'vertex').length ? flatExtent(panel.face) : 1000; + const big = box * 4 + width * 4; + const origin: Vec2 = add2([la[0], la[1]], w, start); + const half = (from: number, to: number) => rectFace(add2(add2(origin, u, -big), w, from), u, 2 * big, w, to - from); + const fixedFace = common(panel.face, half(-big, 0)); + const stripFace = common(panel.face, half(0, width)); + const movingFace = common(panel.face, half(width, big)); + if (isEmpty(fixedFace) || isEmpty(movingFace) || isEmpty(stripFace)) throw h.error('The bend line must divide the face in two, with room for the bend on both sides'); + // The bend strip must cross the face straight: a rectangle as wide as the bend allowance. + const ts = subShapes(stripFace, 'vertex').map((v) => { const q = vertexPoint(v); return dot2([q[0] - origin[0], q[1] - origin[1]], u); }); + const u0 = Math.min(...ts), u1 = Math.max(...ts); + if (Math.abs(area(stripFace) - width * (u1 - u0)) > 1e-6 * Math.max(1, width * (u1 - u0))) { + throw h.error('The bend must cross the face where its edges are square to the bend line, without holes or notches in the bend region'); + } + const b: SmBend = { + id: `${f.id}:b`, feature: f.id, fixed: panel.id, moving: `${f.id}:p`, s0: add2(origin, u, u0), u, w, length: u1 - u0, width, angle, radius: Rb, up, + }; + // Bends of the panel go with the side they start from. + const side = (q: Vec2) => dot2([q[0] - origin[0], q[1] - origin[1]], w); + const bends = sheet.bends.map((x) => { + if (x.fixed !== panel.id && x.moving !== panel.id) return x; + const m = x.fixed === panel.id ? add2(x.s0, x.u, x.length / 2) : add2(add2(x.s0, x.u, x.length / 2), x.w, x.width); + const s = side(m); + if (s > -1e-6 && s < width + 1e-6) throw h.error('The bend is too close to another bend'); + if (s < 0) return x; + return x.fixed === panel.id ? { ...x, fixed: b.moving } : { ...x, moving: b.moving }; + }); + // Everything joined to the moving side moves with it. + const moving = new Set([b.moving]); + for (let grew = true; grew;) { + grew = false; + for (const x of bends) { + for (const [p0, p1] of [[x.fixed, x.moving], [x.moving, x.fixed]]) if (moving.has(p0) && !moving.has(p1) && p1 !== panel.id) { moving.add(p1); grew = true; } + } + } + const motion = bendMotion(b, T); + const G = xfCompose(xfCompose(panel.xf, motion), xfInverse(panel.xf)); + const eps = Math.max(T * 0.01, 1e-4); + const prism = (face: Sh, xf: Frame) => placed(extrudeZ(face, -eps, T + eps), xf); + const region: Sh[] = [prism(movingFace, panel.xf)]; + for (const x of sheet.panels) if (x !== panel && moving.has(x.id)) region.push(prism(x.face, x.xf)); + for (const x of bends) { + if (!moving.has(x.fixed) || !moving.has(x.moving)) continue; + const xfFixed = x.fixed === b.moving ? panel.xf : sheet.panels.find((q) => q.id === x.fixed)!.xf; + const eIn = Math.min(eps, x.radius * 0.5); + region.push(placed(bendSolid(x, T, x.up ? -eps : -eIn, x.up ? T + eIn : T + eps), xfFixed)); + } + const movingRegion = fuseAll(region); + const strip = prism(stripFace, panel.xf); + const moved = common(body, movingRegion); + if (isEmpty(moved)) throw h.error('There is no material on the side of the bend that moves'); + const kept = cut(body, fuse(movingRegion, strip)); + const stripVolume = volumeOf(common(body, strip)); + if (stripVolume < area(stripFace) * T * (1 - 1e-6)) h.warn('Cuts in the bend region were filled in by the bend'); + const keptNames = new Set(h.nameFaces(f.id, kept, st, []).map((x) => x.name)); + const movedFaces = h.nameFaces(f.id, moved, st, []).map((x) => { + const shape = placed(x.shape, G); + return { shape, desc: describeFace(shape), name: keptNames.has(x.name) ? `${f.id}:m:${x.name}` : x.name, feature: x.feature }; + }); + const bendPiece = namedPiece(f.id, bendSolid(b, T), panel.xf, (d) => { + if (d.type === 'cylinder') return `bend:${near(d.r, b.radius, 1e-6 * T + 1e-9) ? 'in' : 'out'}`; + return 'bend:side'; + }); + const result = fuseAll([kept, placed(moved, G), bendPiece.solid]); + // The pieces only touch, unless the moved side lands in the kept one. + const pieces = volumeOf(kept) + volumeOf(moved) + volumeOf(bendPiece.solid); + if (volumeOf(result) < pieces * (1 - 1e-6)) throw h.error('The bend folds the sheet into itself. Use a smaller angle, reverse the direction or keep the other side fixed.'); + st.faces = h.nameFaces(f.id, result, st, [...movedFaces, ...bendPiece.faces]); + st.body = result; + st.edges = null; + const panels: SmPanel[] = []; + for (const x of sheet.panels) { + if (x === panel) panels.push({ ...x, face: fixedFace }, { id: b.moving, face: movingFace, xf: xfCompose(panel.xf, motion) }); + else panels.push(moving.has(x.id) ? { ...x, xf: xfCompose(G, x.xf) } : x); + } + st.sheet = replacePanels(sheet, panels, [...bends, b]); +} + +function flatExtent(face: Sh): number { + let m = 0; + for (const v of subShapes(face, 'vertex')) { + const p = vertexPoint(v); + m = Math.max(m, Math.abs(p[0]), Math.abs(p[1])); + } + return m; +} + +// ---- flat pattern ---- + +const NOT_SHOWN = 'Material the flat pattern cannot show is left out: features that change the bends (such as cuts across a bend) or add material off the sheet.'; + +/** The flat pattern of the sheet as built, with the solid to show it. */ +export function flatPattern(st: SmState): { pattern: FlatPattern; solid: Sh } | { error: string } { + const sheet = st.sheet; + if (!sheet) return { error: 'This part has no sheet metal features' }; + const body = st.body; + if (!body) return { error: 'The sheet metal part failed to build' }; + const T = sheet.p.thickness; + const notes: string[] = []; + const pieces: Sh[] = []; + let expected = 0; + for (const panel of sheet.panels) { + const mid = placed(translated(panel.face, [0, 0, T / 2]), panel.xf); + const sec = common(body, mid); + if (isEmpty(sec)) continue; + const flat = translated(placed(sec, xfInverse(panel.xf)), [0, 0, -T / 2]); + for (const face of subShapes(flat, 'face')) { pieces.push(facingUp(face)); expected += faceProps(face.wrapped).area * T; } + } + const bends: FlatBend[] = []; + for (const b of sheet.bends) { + pieces.push(facingUp(rectFace(b.s0, b.u, b.length, b.w, b.width))); + expected += ((b.angle * Math.PI) / 180) * T * (b.radius + T / 2) * b.length; + const a = add2(b.s0, b.w, b.width / 2); + bends.push({ a, b: add2(a, b.u, b.length), up: b.up, angle: b.angle, radius: b.radius, allowance: b.width, feature: b.feature }); + } + if (!pieces.length) return { error: 'The sheet has no material left' }; + const flat = pieces.length === 1 ? pieces[0] : unified(fuseAll(pieces)); + const faces = subShapes(flat, 'face'); + const pieceArea = pieces.reduce((s, x) => s + faceProps(x.wrapped).area, 0); + const flatArea = faces.reduce((s, x) => s + faceProps(x.wrapped).area, 0); + if (pieceArea - flatArea > 1e-6 * Math.max(1, flatArea)) notes.push('Some regions of the sheet overlap when it is flattened.'); + const v = volumeOf(body); + if (Math.abs(v - expected) > 1e-4 * Math.max(1, v)) notes.push(NOT_SHOWN); + const loops: FlatLoop[] = []; + const oc = getOc(); + let min: Vec2 = [Infinity, Infinity], max: Vec2 = [-Infinity, -Infinity]; + for (const face of faces) { + const outer = oc.BRepTools.OuterWire(face.wrapped); + for (const wire of subShapes(face, 'wire')) { + const segs: FlatSeg[] = []; + for (const e of subShapes(wire, 'edge')) { + const d = describeEdge(e); + const two = (p: Vec3): Vec2 => [p[0], p[1]]; + if (d.type === 'line') segs.push({ k: 'line', a: two(d.a), b: two(d.b) }); + else if (d.type === 'circle' && d.closed) segs.push({ k: 'circle', c: two(d.center!), r: d.radius! }); + else if (d.type === 'circle') { + const c = two(d.center!); + const ang = (p: Vec3) => Math.atan2(p[1] - c[1], p[0] - c[0]); + const ccw = d.axis![2] > 0; + segs.push({ k: 'arc', c, r: d.radius!, a0: ang(ccw ? d.a : d.b), a1: ang(ccw ? d.b : d.a) }); + } else { + const pts = edgePoints(e, 48); + for (let i = 0; i + 1 < pts.length; i++) segs.push({ k: 'line', a: two(pts[i]), b: two(pts[i + 1]) }); + } + } + for (const s of segs) { + const pts: Vec2[] = s.k === 'line' ? [s.a, s.b] : s.k === 'circle' ? [[s.c[0] - s.r, s.c[1] - s.r], [s.c[0] + s.r, s.c[1] + s.r]] : arcBox(s); + for (const p of pts) { min = [Math.min(min[0], p[0]), Math.min(min[1], p[1])]; max = [Math.max(max[0], p[0]), Math.max(max[1], p[1])]; } + } + loops.push({ outer: wire.wrapped.IsSame(outer), segs }); + } + outer.delete?.(); + } + const solid = fuseAll(faces.map((x) => extrudeZ(x, 0, T))); + const base = sheet.panels[0]; + return { pattern: { loops, bends, thickness: T, min, max, notes, placement: base.xf }, solid: placed(solid, base.xf) }; +} + +function arcBox(s: Extract): Vec2[] { + const out: Vec2[] = []; + let a1 = s.a1; + while (a1 <= s.a0) a1 += 2 * Math.PI; + const at = (a: number): Vec2 => [s.c[0] + s.r * Math.cos(a), s.c[1] + s.r * Math.sin(a)]; + out.push(at(s.a0), at(a1)); + for (let k = Math.ceil(s.a0 / (Math.PI / 2)); k * (Math.PI / 2) < a1; k++) out.push(at(k * (Math.PI / 2))); + return out; +} diff --git a/src/parametric/src/kernel/surfaces.ts b/src/parametric/src/kernel/surfaces.ts new file mode 100644 index 0000000000..bc7fe16eec --- /dev/null +++ b/src/parametric/src/kernel/surfaces.ts @@ -0,0 +1,1672 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +// Surface modeling: surface bodies kept apart from the solid body, and the +// features that make, change and use them (extruded, revolved, swept, +// lofted, planar, offset and filled surfaces; trim, extend and knit; +// thicken, cut with surface, delete face). +// +// A part without surface features never reaches this file: the solid path +// of ModelBuilder is unchanged. Surface bodies are listed in the build state +// by the feature that last made them; their faces are named like the +// solid's ("f7:side:l2", after the feature and sketch entity that made the +// surface) and their edges after the faces they bound, so later features +// and sketches reference them by name. + +import * as R from 'replicad'; +import type { Frame, Vec2, Vec3 } from '../math/vec'; +import { add, cross, dist, dot, len, normalize, scale, sub, toWorld } from '../math/vec'; +import { type SurfaceFeature, bodyFeatureOf } from '../model/surfaces'; +import type { + AxisRef, DeleteFaceFeature, EdgeRef, FaceRef, Feature, Id, PlaneRef, SketchFeature, SurfaceCutFeature, SurfaceExtendFeature, + SurfaceExtrudeFeature, SurfaceFillFeature, SurfaceKnitFeature, SurfaceLoftFeature, SurfaceOffsetFeature, SurfacePlanarFeature, + SurfaceRevolveFeature, SurfaceSweepFeature, SurfaceTrimFeature, ThickenFeature, +} from '../model/types'; +import { SketchIndex, pointIdsOf, splineBeziers } from '../sketch/geom'; +import type { Region } from '../sketch/profiles'; +import { + type EdgeDesc, type Sh, type SurfDesc, ShapeIndex, SurfaceCache, bbox, compound, describeEdge, describeFace, faceMidPoint, getOc, + cut, gvec, isEmpty, isValid, meshEdgesOf, meshShape, planarFaceFrame, pnt, rotated, sameSurface, sharesSurface, subShapes, translated, + vertexPoint, volumeOf, wrap, xyz, +} from './occ'; +import type { EdgeInfo, FaceInfo, MeshData } from './protocol'; + +export interface SurfFace { + shape: Sh; + name: string; + desc: SurfDesc; + feature: Id; +} + +export interface SurfEdge { + shape: Sh; + name: string; + desc: EdgeDesc; + faces: number[]; +} + +/** A surface body: an open (or closed, not yet solid) sheet of faces. */ +export interface SurfaceBody { + /** The feature that last made it ("f7"), or "f7.2" for the second body one feature made. */ + id: Id; + shape: Sh; + faces: SurfFace[]; +} + +/** The parts of the builder's state this file reads and writes. */ +export interface SurfState { + body: Sh | null; + faces: SurfFace[]; + edges: SurfEdge[] | null; + frames: Map; + sketches: Map; + surfaces: SurfaceBody[]; +} + +/** What the surface features use of ModelBuilder (its sketch, reference and boolean machinery). */ +export interface SurfaceHost { + fail(message: string): Error; + missing(id: Id | null | undefined, what: string): Error; + warn(message: string): void; + num(f: Feature, path: string): number; + sketchRegions(id: Id, st: SurfState): { regions: Region[]; frame: Frame; sketch: SketchFeature }; + regionFace(r: Region, fr: Frame): any; + resolvePlane(ref: PlaneRef | null, st: SurfState): Frame; + resolveAxis(ref: AxisRef, st: SurfState): { p: Vec3; d: Vec3 }; + resolveFace(ref: FaceRef, st: SurfState): number; + resolveEdge(ref: EdgeRef, st: SurfState): number; + edgesOf(st: SurfState): SurfEdge[]; + applyTool(featId: Id, st: SurfState, tool: Sh, faces: SurfFace[], cut: boolean, noGain?: string): void; + nameFaces(featId: Id, body: Sh, st: SurfState, tool: SurfFace[]): SurfFace[]; +} + +const bodyFeature = bodyFeatureOf; + +const SWEEP_FAILED = 'The swept surface could not be created. The profile should start at the path and be roughly perpendicular to it.'; +const MAX_KNIT_FACES = 5000; +const MAX_FILL_EDGES = 32; +const MAX_LOFT_PROFILES = 50; + +// ---------- small OpenCascade helpers ---------- + +function progress(fn: (p: any) => T): T { + const p = new (getOc().Message_ProgressRange)(); + try { return fn(p); } finally { p.delete(); } +} + +/** Sews shapes along edges closer than tol. */ +function sew(shapes: Sh[], tol: number): { shape: Sh; free: number } { + const oc = getOc(); + const s = new oc.BRepBuilderAPI_Sewing(tol, true, true, true, false); + try { + for (const x of shapes) s.Add(x.wrapped); + progress((p) => s.Perform(p)); + const out = s.SewedShape(); + if (out.IsNull()) throw new Error('sewing failed'); + return { shape: wrap(out), free: s.NbFreeEdges() }; + } finally { + s.delete(); + } +} + +/** A shell (or a single face) of faces that already share their edges. */ +function shellOf(faces: Sh[]): Sh { + if (faces.length === 1) return faces[0]; + const oc = getOc(); + const b = new oc.TopoDS_Builder(); + const sh = new oc.TopoDS_Shell(); + try { + b.MakeShell(sh); + for (const f of faces) b.Add(sh, f.wrapped); + return wrap(sh); + } finally { + b.delete(); + } +} + +function areaOf(s: Sh): number { + const oc = getOc(); + const p = new oc.GProp_GProps(); + try { oc.BRepGProp.SurfaceProperties(s.wrapped, p, 1e-7, true); return p.Mass(); } finally { p.delete(); } +} + +function sizeOf(s: Sh): number { + const b = bbox(s); + return b ? dist(b.min, b.max) : 1; +} + +function vertexAt(p: Vec3): Sh { + const oc = getOc(); + const g = pnt(p); + const mv = new oc.BRepBuilderAPI_MakeVertex(g); + try { return wrap(mv.Vertex()); } finally { mv.delete(); g.delete(); } +} + +/** + * One distance calculator, loaded again for each pair: every one made and + * deleted kept about 6 kB inside the geometry engine, and a trim asks for + * hundreds of distances (a part with a trim grew by 1.5 MB on each rebuild). + */ +let distCalc: { oc: unknown; ext: any } | null = null; + +/** Distance between two shapes and the nearest points. */ +function nearest(a: Sh, b: Sh): { d: number; p1: Vec3; p2: Vec3 } | null { + const oc = getOc(); + if (!distCalc || distCalc.oc !== oc) distCalc = { oc, ext: new oc.BRepExtrema_DistShapeShape() }; + const ext = distCalc.ext; + try { + ext.LoadS1(a.wrapped); + ext.LoadS2(b.wrapped); + progress((p) => ext.Perform(p)); + if (!ext.IsDone() || ext.NbSolution() < 1) return null; + const p1 = ext.PointOnShape1(1), p2 = ext.PointOnShape2(1); + const out = { d: ext.Value(), p1: xyz(p1), p2: xyz(p2) }; + p1.delete(); p2.delete(); + return out; + } catch { + // A failed calculation may leave it in any state: the next call makes a new one. + try { ext.delete(); } catch { /* already unusable */ } + distCalc = null; + return null; + } +} + +/** Unit normal of a face (as oriented in its shape) at the point of it nearest p. */ +function normalAt(face: Sh, p: Vec3): Vec3 | null { + const oc = getOc(); + let surf: any = null, proj: any = null, gf: any = null; + const g = pnt(p), q = new oc.gp_Pnt(), n = new oc.gp_Vec(); + try { + surf = oc.BRep_Tool.Surface(face.wrapped); + proj = new oc.GeomAPI_ProjectPointOnSurf(g, surf, oc.Extrema_ExtAlgo.Extrema_ExtAlgo_Grad); + if (!proj.NbPoints()) return null; + const uv = proj.LowerDistanceParameters(0, 0); + gf = new oc.BRepGProp_Face(face.wrapped, false); + gf.Normal(uv.U, uv.V, q, n); + const v = xyz(n); + return len(v) > 1e-12 ? normalize(v) : null; + } catch { + return null; + } finally { + proj?.delete(); gf?.delete(); surf?.delete?.(); g.delete(); q.delete(); n.delete(); + } +} + +/** A large planar face on a frame, reaching `reach` from its origin. */ +function bigPlane(fr: Frame, reach: number): Sh { + const oc = getOc(); + const o = pnt(fr.o), d = new oc.gp_Dir(fr.n[0], fr.n[1], fr.n[2]); + const pl = new oc.gp_Pln(o, d); + const mf = new oc.BRepBuilderAPI_MakeFace(pl, -reach, reach, -reach, reach); + try { return wrap(mf.Face()); } finally { mf.delete(); pl.delete(); o.delete(); d.delete(); } +} + +/** Faces of a shape with names: those on the surface of a source face take its name, the rest from fallback. */ +function inherit(shape: Sh, sources: SurfFace[], tol: number, fallback: (k: number, desc: SurfDesc) => { name: string; feature: Id }): SurfFace[] { + const cache = new SurfaceCache(); + let k = 0; + try { + return subShapes(shape, 'face').map((f) => { + const desc = describeFace(f); + let best: SurfFace | null = null, bd = Infinity; + for (const s of sources) { + if (s.desc.type !== desc.type) continue; + if (!sharesSurface(f, s.shape, cache) && !(EXACT.has(desc.type) && sameSurface(desc, s.desc, tol))) continue; + const d = dist(desc.center, s.desc.center); + if (d < bd) { bd = d; best = s; } + } + if (best) return { shape: f, desc, name: best.name, feature: best.feature }; + return { shape: f, desc, ...fallback(k++, desc) }; + }); + } finally { + cache.dispose(); + } +} + +const EXACT = new Set(['plane', 'cylinder', 'sphere']); + +function cmpVec(a: Vec3, b: Vec3): number { + for (let i = 0; i < 3; i++) { + const d = Math.round(a[i] * 1e6) - Math.round(b[i] * 1e6); + if (d) return d; + } + return 0; +} + +const bodyEdgeCache = new WeakMap(); + +/** Edges of a surface body, named by the faces they bound (a boundary edge by its one face). */ +export function bodyEdges(b: SurfaceBody): SurfEdge[] { + const cached = bodyEdgeCache.get(b); + if (cached) return cached; + const edges = subShapes(b.shape, 'edge'); + const index = new ShapeIndex(edges); + const adj: number[][] = edges.map(() => []); + b.faces.forEach((f, fi) => { + for (const e of subShapes(f.shape, 'edge')) { + const j = index.find(e.wrapped); + if (j >= 0 && !adj[j].includes(fi)) adj[j].push(fi); + } + }); + const named: SurfEdge[] = edges.map((shape, i) => { + const names = [...new Set(adj[i].map((fi) => b.faces[fi].name))].sort(); + return { shape, desc: describeEdge(shape), faces: adj[i], name: names.join('|') || `${b.id}:free` }; + }); + const groups = new Map(); + named.forEach((e, i) => { const g = groups.get(e.name); if (g) g.push(i); else groups.set(e.name, [i]); }); + for (const [, ids] of groups) { + if (ids.length < 2) continue; + ids.sort((x, y) => cmpVec(named[x].desc.mid, named[y].desc.mid)); + ids.forEach((id, k) => { named[id].name += `#${k}`; }); + } + bodyEdgeCache.set(b, named); + return named; +} + +// ---------- sketch curves ---------- + +interface Piece { edges: any[]; a?: Vec2; b?: Vec2; src: Id } + +/** The sketch's curves (not construction geometry) as 3D edges, with their end points. */ +function curvePieces(sk: SketchFeature, fr: Frame): Piece[] { + const ix = new SketchIndex(sk.entities); + const out: Piece[] = []; + for (const e of sk.entities) { + if (e.construction) continue; + const w = (id: string) => toWorld(fr, ix.pt(id)); + if (e.t === 'line') { + const a = ix.pt(e.a), b = ix.pt(e.b); + if (Math.hypot(a[0] - b[0], a[1] - b[1]) < 1e-9) continue; + out.push({ edges: [R.makeLine(w(e.a), w(e.b))], a, b, src: e.id }); + } else if (e.t === 'arc') { + const c = ix.pt(e.c), a = ix.pt(e.a), b = ix.pt(e.b); + const r = Math.hypot(a[0] - c[0], a[1] - c[1]); + const a0 = Math.atan2(a[1] - c[1], a[0] - c[0]); + let a1 = Math.atan2(b[1] - c[1], b[0] - c[0]); + if (a1 <= a0) a1 += 2 * Math.PI; + const am = (a0 + a1) / 2; + out.push({ edges: [R.makeThreePointArc(w(e.a), toWorld(fr, [c[0] + r * Math.cos(am), c[1] + r * Math.sin(am)]), w(e.b))], a, b, src: e.id }); + } else if (e.t === 'spline') { + const pts = e.pts.map((p) => ix.pt(p)); + if (pts.length < 2) continue; + out.push({ edges: splineBeziers(pts).map((bz) => R.makeBezierCurve(bz.map((p) => toWorld(fr, p)))), a: pts[0], b: pts[pts.length - 1], src: e.id }); + } else if (e.t === 'circle') { + if (e.r > 0) out.push({ edges: [R.makeCircle(e.r, toWorld(fr, ix.pt(e.c)), fr.n)], src: e.id }); + } + } + return out; +} + +/** Connected chains of pieces, each in order end to end (closed curves alone). */ +function chains(pieces: Piece[]): { pieces: Piece[]; closed: boolean }[] { + let size = 0; + for (const p of pieces) for (const q of [p.a, p.b]) if (q) size = Math.max(size, Math.abs(q[0]), Math.abs(q[1])); + const tol = 1e-6 * (1 + size); + const same = (p: Vec2, q: Vec2) => Math.hypot(p[0] - q[0], p[1] - q[1]) < tol; + const rest = [...pieces]; + const out: { pieces: Piece[]; closed: boolean }[] = []; + while (rest.length) { + const first = rest.shift()!; + if (!first.a || !first.b) { out.push({ pieces: [first], closed: true }); continue; } + const chain = [first]; + let head = first.a, tail = first.b; + for (;;) { + const i = rest.findIndex((p) => !!p.a && !!p.b && (same(p.a, tail) || same(p.b, tail) || same(p.a, head) || same(p.b, head))); + if (i < 0 || same(head, tail)) break; + const [p] = rest.splice(i, 1); + if (same(p.a!, tail)) { chain.push(p); tail = p.b!; } + else if (same(p.b!, tail)) { chain.push(p); tail = p.a!; } + else if (same(p.a!, head)) { chain.unshift(p); head = p.b!; } + else { chain.unshift(p); head = p.a!; } + } + out.push({ pieces: chain, closed: same(head, tail) }); + } + return out; +} + +// ---------- the surface features ---------- + +export class SurfaceKit { + constructor(private h: SurfaceHost) {} + + /** Builds a surface feature into the state. Returns what its preview shows. */ + apply(f: SurfaceFeature, st: SurfState): 'surface' | 'body' { + switch (f.type) { + case 'surfaceExtrude': this.extrude(f, st); return 'surface'; + case 'surfaceRevolve': this.revolve(f, st); return 'surface'; + case 'surfaceSweep': this.sweep(f, st); return 'surface'; + case 'surfaceLoft': this.loft(f, st); return 'surface'; + case 'surfacePlanar': this.planar(f, st); return 'surface'; + case 'surfaceOffset': this.offset(f, st); return 'surface'; + case 'surfaceFill': this.fill(f, st); return 'surface'; + case 'surfaceTrim': this.trim(f, st); return 'surface'; + case 'surfaceExtend': this.extend(f, st); return 'surface'; + case 'surfaceKnit': return this.knit(f, st); + case 'thicken': this.thicken(f, st); return 'body'; + case 'surfaceCut': this.cutWith(f, st); return 'body'; + case 'deleteFace': return this.deleteFace(f, st); + } + } + + /** The shape a surface feature's preview shows: the bodies it made. */ + previewShape(st: SurfState, id: Id): Sh | null { + const mine = st.surfaces.filter((b) => bodyFeature(b.id) === id); + if (!mine.length) return null; + return mine.length === 1 ? mine[0].shape : compound(mine.map((b) => b.shape)); + } + + // ---- references ---- + + /** A surface face of that name (nearest the reference's place when several have it). */ + findFace(ref: FaceRef, st: SurfState): { body: SurfaceBody; face: SurfFace } | null { + let best: { body: SurfaceBody; face: SurfFace } | null = null, bd = Infinity; + for (const body of st.surfaces) { + for (const face of body.faces) { + if (face.name !== ref.name) continue; + const d = dist(face.desc.center, ref.sig.c); + if (d < bd) { bd = d; best = { body, face }; } + } + } + return best; + } + + /** A surface edge of that name, or a piece of it (nearest the reference's place). */ + findEdge(ref: EdgeRef, st: SurfState): { body: SurfaceBody; edge: SurfEdge } | null { + const base = ref.name.replace(/#\d+$/, ''); + let best: { body: SurfaceBody; edge: SurfEdge } | null = null, bd = Infinity; + let exact = false; + for (const body of st.surfaces) { + for (const edge of bodyEdges(body)) { + const isExact = edge.name === ref.name; + if (!isExact && edge.name.replace(/#\d+$/, '') !== base) continue; + if (exact && !isExact) continue; + const d = dist(edge.desc.mid, ref.sig.m); + if ((isExact && !exact) || d < bd) { bd = d; best = { body, edge }; exact = exact || isExact; } + } + } + return best; + } + + /** A face of a surface body or of the solid. */ + anyFace(ref: FaceRef, st: SurfState): { shape: Sh; desc: SurfDesc; body: SurfaceBody | null } { + const s = this.findFace(ref, st); + if (s) return { shape: s.face.shape, desc: s.face.desc, body: s.body }; + if (!st.faces.some((f) => f.name === ref.name) && st.surfaces.length) { + // Gone by name (trimmed away, renamed): the nearest surface face of that kind nearby. + let best: { body: SurfaceBody; face: SurfFace } | null = null, bd = Infinity; + for (const body of st.surfaces) { + const lim = sizeOf(body.shape) * 0.05; + for (const face of body.faces) { + if (face.desc.type !== ref.sig.type) continue; + const d = dist(face.desc.center, ref.sig.c); + if (d < lim && d < bd) { bd = d; best = { body, face }; } + } + } + if (best) return { shape: best.face.shape, desc: best.face.desc, body: best.body }; + } + const f = st.faces[this.h.resolveFace(ref, st)]; + return { shape: f.shape, desc: f.desc, body: null }; + } + + /** An edge of a surface body or of the solid, with the faces it bounds. */ + anyEdge(ref: EdgeRef, st: SurfState): { shape: Sh; desc: EdgeDesc; faces: Sh[]; body: SurfaceBody | null } { + const s = this.findEdge(ref, st); + if (s) return { shape: s.edge.shape, desc: s.edge.desc, faces: s.edge.faces.map((i) => s.body.faces[i].shape), body: s.body }; + const e = this.h.edgesOf(st)[this.h.resolveEdge(ref, st)]; + return { shape: e.shape, desc: e.desc, faces: e.faces.map((i) => st.faces[i].shape), body: null }; + } + + /** The surface body a face reference is on. */ + private bodyOf(ref: FaceRef, st: SurfState, what: string): SurfaceBody { + const s = this.findFace(ref, st); + if (s) return s.body; + const any = st.surfaces.length ? this.anyFace(ref, st) : null; + if (any?.body) return any.body; + if (st.faces.some((f) => f.name === ref.name)) throw this.h.fail(`The selected face is a face of the solid. Select ${what}.`); + throw this.h.fail(`A selected surface no longer exists. Edit the feature and select ${what} again.`); + } + + /** Distinct surface bodies of the selected faces, in selection order. */ + private bodiesOf(refs: FaceRef[], st: SurfState, what: string): SurfaceBody[] { + const out: SurfaceBody[] = []; + for (const r of refs) { + const b = this.bodyOf(r, st, what); + if (!out.includes(b)) out.push(b); + } + return out; + } + + /** Plane frame of a planar surface face (sketches and planes on surfaces). */ + surfacePlane(ref: FaceRef, st: SurfState, x?: Vec3): Frame | null { + const s = this.findFace(ref, st); + if (!s) return null; + if (s.face.desc.type !== 'plane') throw this.h.fail('The selected face is not planar'); + return planarFaceFrame(s.face.desc, x); + } + + /** An axis from a surface edge or face, or null when the reference is not on a surface. */ + surfaceAxis(ref: AxisRef, st: SurfState): { p: Vec3; d: Vec3 } | null { + if (ref.kind === 'edge') { + const s = this.findEdge(ref.edge, st); + if (!s) return null; + const e = s.edge.desc; + if (e.type === 'line') return { p: e.a, d: e.dir! }; + if (e.type === 'circle') return { p: e.center!, d: normalize(e.axis!) }; + throw this.h.fail('The selected edge is not straight or circular'); + } + if (ref.kind === 'face') { + const s = this.findFace(ref.face, st); + if (!s) return null; + const f = s.face.desc; + if (f.type === 'plane') return { p: f.center, d: f.d }; + if (f.type === 'cylinder' || f.type === 'sphere') return { p: f.p, d: f.d }; + throw this.h.fail('Select a planar or cylindrical face'); + } + return null; + } + + /** A surface edge for a sketch's projected geometry, or null. */ + surfaceEdgeDesc(ref: EdgeRef, st: SurfState): EdgeDesc | null { + return this.findEdge(ref, st)?.edge.desc ?? null; + } + + // ---- adding and replacing bodies ---- + + private addBody(st: SurfState, id: Id, shape: Sh, faces: SurfFace[], replace: SurfaceBody[] = []) { + if (isEmpty(shape)) throw this.h.fail('The surface has no faces'); + st.surfaces = [...st.surfaces.filter((b) => !replace.includes(b)), { id, shape, faces }]; + } + + private named(featId: Id, shape: Sh, name: (k: number, desc: SurfDesc, face: Sh) => string): SurfFace[] { + return subShapes(shape, 'face').map((f, k) => { + const desc = describeFace(f); + return { shape: f, desc, name: `${featId}:${name(k, desc, f)}`, feature: featId }; + }); + } + + /** Faces sewn into one shell where they meet, keeping their names. */ + private sewNamed(featId: Id, faces: SurfFace[]): { shape: Sh; faces: SurfFace[] } { + if (faces.length === 1) return { shape: faces[0].shape, faces }; + const all = compound(faces.map((f) => f.shape)); + const tol = Math.max(1e-6, sizeOf(all) * 1e-7); + const { shape } = sew(faces.map((f) => f.shape), tol); + return { shape, faces: inherit(shape, faces, tol, (k) => ({ name: `${featId}:n${k}`, feature: featId })) }; + } + + // ---- extruded, revolved, swept, lofted, planar ---- + + private sketchOf(id: Id | null | undefined, st: SurfState, what: string): { sketch: SketchFeature; frame: Frame } { + const sketch = id ? st.sketches.get(id) : undefined; + const frame = id ? st.frames.get(id) : undefined; + if (!sketch || !frame) throw this.h.missing(id, what); + return { sketch, frame }; + } + + private extrude(f: SurfaceExtrudeFeature, st: SurfState) { + const { sketch, frame } = this.sketchOf(f.sketch, st, 'profile sketch'); + const pieces = curvePieces(sketch, frame); + if (!pieces.length) throw this.h.fail('The sketch has no curves to extrude'); + const d1 = this.h.num(f, 'depth'); + if (!(d1 > 0)) throw this.h.fail('Depth must be greater than zero'); + const dir = scale(frame.n, f.flip ? -1 : 1); + let start = 0, total = d1; + if (f.end === 'midPlane') start = -d1 / 2; + else if (f.dir2) { + const d2 = this.h.num(f, 'dir2.depth'); + if (!(d2 > 0)) throw this.h.fail('Direction 2 depth must be greater than zero'); + start = -d2; total = d1 + d2; + } + const oc = getOc(); + const faces: SurfFace[] = []; + for (const p of pieces) { + for (const e of p.edges) { + const v = gvec(scale(dir, total)); + const mk = new oc.BRepPrimAPI_MakePrism(e.wrapped, v, false, true); + let face: Sh; + try { face = wrap(mk.Shape()); } finally { mk.delete(); v.delete(); } + if (start) face = translated(face, scale(dir, start)); + for (const s of subShapes(face, 'face')) faces.push({ shape: s, desc: describeFace(s), name: `${f.id}:side:${p.src}`, feature: f.id }); + } + } + const { shape, faces: named } = this.sewNamed(f.id, faces); + this.addBody(st, f.id, shape, named); + } + + /** The axis of a revolve: the reference, or the sketch's free-standing centerline. */ + private revolveAxis(f: SurfaceRevolveFeature, sketch: SketchFeature, frame: Frame, st: SurfState): { p: Vec3; d: Vec3; line?: Id } { + if (f.axis) return this.h.resolveAxis(f.axis, st); + const ix = new SketchIndex(sketch.entities); + const lines = sketch.entities.filter((e) => e.t === 'line' && e.construction); + const onProfile = new Set(sketch.entities.flatMap((e) => (e.t !== 'point' && !e.construction ? pointIdsOf(e) : []))); + const cl = lines.find((l) => l.t === 'line' && !l.ext && !onProfile.has(l.a) && !onProfile.has(l.b)) ?? lines[0]; + if (!cl || cl.t !== 'line') throw this.h.fail('Select an axis of revolution (or add a centerline to the sketch)'); + const a = toWorld(frame, ix.pt(cl.a)), b = toWorld(frame, ix.pt(cl.b)); + return { p: a, d: normalize(sub(b, a)), line: cl.id }; + } + + private revolve(f: SurfaceRevolveFeature, st: SurfState) { + const { sketch, frame } = this.sketchOf(f.sketch, st, 'profile sketch'); + const axis = this.revolveAxis(f, sketch, frame, st); + const pieces = curvePieces(sketch, frame); + const angle = this.h.num(f, 'angle'); + if (!(angle > 0)) throw this.h.fail('Angle must be greater than zero'); + if (angle > 360 + 1e-9) throw this.h.fail('The angle cannot be more than 360 degrees'); + const d = scale(axis.d, f.flip ? -1 : 1); + const onAxis = (p: Vec3) => len(sub(sub(p, axis.p), scale(d, dot(sub(p, axis.p), d)))) < 1e-7 * (1 + len(p)); + const oc = getOc(); + const faces: SurfFace[] = []; + for (const p of pieces) { + for (const e of p.edges) { + const ed = describeEdge(e as Sh); + // A curve on the axis sweeps nothing. + if (onAxis(ed.a) && onAxis(ed.b) && onAxis(ed.mid)) continue; + const ap = pnt(axis.p), ad = new oc.gp_Dir(d[0], d[1], d[2]); + const ax = new oc.gp_Ax1(ap, ad); + ap.delete(); ad.delete(); + const mk = new oc.BRepPrimAPI_MakeRevol(e.wrapped, ax, (Math.min(angle, 360) * Math.PI) / 180, true); + let face: Sh; + try { face = wrap(mk.Shape()); } catch { + throw this.h.fail(crossesAxis(e as Sh, axis.p, d, frame.n) ? 'The profile crosses the axis of revolution. Keep the curves on one side of the axis.' : 'The revolved surface could not be created'); + } finally { mk.delete(); ax.delete(); } + if (f.end === 'midPlane' && angle < 360) face = rotated(face, axis.p, d, (-angle * Math.PI) / 360); + for (const s of subShapes(face, 'face')) faces.push({ shape: s, desc: describeFace(s), name: `${f.id}:side:${p.src}`, feature: f.id }); + } + } + if (!faces.length) throw this.h.fail('The sketch has no curves to revolve (other than the axis)'); + const { shape, faces: named } = this.sewNamed(f.id, faces); + this.addBody(st, f.id, shape, named); + } + + /** One wire through a sketch's curves; `extra` when it has more than one chain. */ + private sketchWire(id: Id | null, st: SurfState, what: string): { wire: any; closed: boolean; frame: Frame; extra: boolean } { + const { sketch, frame } = this.sketchOf(id, st, what); + const cs = chains(curvePieces(sketch, frame)); + if (!cs.length) throw this.h.fail(`The ${what} (${sketch.name}) has no curves`); + const c = cs[0]; + try { + return { wire: R.assembleWire(c.pieces.flatMap((p) => p.edges)), closed: c.closed, frame, extra: cs.length > 1 }; + } catch { + throw this.h.fail(`The curves of the ${what} (${sketch.name}) do not join into one chain`); + } + } + + private sweep(f: SurfaceSweepFeature, st: SurfState) { + if (!f.profile || !f.path) throw this.h.fail('Select a profile and a path'); + if (f.profile === f.path) throw this.h.fail('The profile and the path are the same sketch. Draw the path in a sketch of its own.'); + const prof = this.sketchWire(f.profile, st, 'profile sketch'); + const path = this.sketchWire(f.path, st, 'path sketch'); + if (prof.extra || path.extra) this.h.warn('Only the first chain of curves of each sketch was used; the others were ignored'); + let shape: Sh; + try { + shape = R.genericSweep(prof.wire, path.wire, { frenet: true }) as unknown as Sh; + } catch { + throw this.h.fail(SWEEP_FAILED); + } + if (isEmpty(shape) || !(areaOf(shape) > 0)) throw this.h.fail(SWEEP_FAILED); + this.addBody(st, f.id, shape, this.named(f.id, shape, (k) => `s${k}`)); + } + + private loft(f: SurfaceLoftFeature, st: SurfState) { + if (f.profiles.length < 2) throw this.h.fail('Select at least two profiles'); + // Hundreds of sections (a damaged file) kept the geometry engine busy for minutes. + if (f.profiles.length > MAX_LOFT_PROFILES) throw this.h.fail(`Select at most ${MAX_LOFT_PROFILES} profiles to loft`); + const profs = f.profiles.map((id) => this.sketchWire(id, st, 'profile sketch')); + if (profs.some((p) => p.closed) && profs.some((p) => !p.closed)) throw this.h.fail('The profiles must be all open or all closed'); + for (let i = 1; i < profs.length; i++) { + const a = profs[i - 1].frame, b = profs[i].frame; + const size = Math.max(1, len(a.o), len(b.o)); + if (Math.abs(dot(a.n, b.n)) > 1 - 1e-9 && Math.abs(dot(sub(b.o, a.o), a.n)) < 1e-9 * size) { + throw this.h.fail('Two of the profiles lie in the same plane. Sketch each profile on its own plane.'); + } + } + if (profs.some((p) => p.extra)) this.h.warn('Only the first chain of curves of each profile was used; the others were ignored'); + const oc = getOc(); + const ts = new oc.BRepOffsetAPI_ThruSections(false, f.ruled, 1e-6); + let shape: Sh; + try { + for (const p of profs) ts.AddWire(p.wire.wrapped); + progress((p) => ts.Build(p)); + if (!ts.IsDone()) throw new Error('loft'); + shape = wrap(ts.Shape()); + } catch { + throw this.h.fail('The lofted surface could not be created from these profiles'); + } finally { + ts.delete(); + } + if (isEmpty(shape) || !(areaOf(shape) > 0)) throw this.h.fail('The lofted surface could not be created from these profiles'); + this.addBody(st, f.id, shape, this.named(f.id, shape, (k) => `l${k}`)); + } + + private planar(f: SurfacePlanarFeature, st: SurfState) { + if (f.sketch) { + const { regions, frame } = this.h.sketchRegions(f.sketch, st); + const faces: SurfFace[] = []; + regions.forEach((r, k) => { + for (const s of subShapes(wrap(this.h.regionFace(r, frame).wrapped), 'face')) faces.push({ shape: s, desc: describeFace(s), name: `${f.id}:p${k}`, feature: f.id }); + }); + const { shape, faces: named } = this.sewNamed(f.id, faces); + this.addBody(st, f.id, shape, named); + return; + } + if (!f.edges.length) throw this.h.fail('Select a sketch with a closed profile, or a closed loop of edges'); + const edges = distinct(f.edges.map((r) => this.anyEdge(r, st).shape)); + if (!closesLoop(edges)) throw this.h.fail('The selected edges must form one closed loop lying in a plane'); + const oc = getOc(); + let face: Sh; + try { + const wire = R.assembleWire(edges as any); + const mf = new oc.BRepBuilderAPI_MakeFace(wire.wrapped, true); + try { + if (!mf.IsDone()) throw new Error('face'); + face = wrap(mf.Face()); + } finally { + mf.delete(); + } + } catch { + throw this.h.fail('The selected edges must form one closed loop lying in a plane'); + } + if (!(areaOf(face) > 0)) throw this.h.fail('The selected edges must form one closed loop lying in a plane'); + this.addBody(st, f.id, face, this.named(f.id, face, (k) => `p${k}`)); + } + + // ---- offset and fill ---- + + private offset(f: SurfaceOffsetFeature, st: SurfState) { + if (!f.faces.length) throw this.h.fail('Select faces to offset'); + const src = distinct(f.faces.map((r) => this.anyFace(r, st).shape)); + const d = this.h.num(f, 'distance') * (f.flip ? -1 : 1); + const oc = getOc(); + let shape: Sh; + if (Math.abs(d) < 1e-12) { + // A copy: new faces of the same geometry, sewn where they meet. + shape = src.length === 1 ? copyShape(src[0]) : sew(src.map(copyShape), Math.max(1e-6, sizeOf(compound(src)) * 1e-7)).shape; + } else { + const base = src.length === 1 ? src[0] : sew(src, Math.max(1e-6, sizeOf(compound(src)) * 1e-7)).shape; + const run = (simple: boolean): Sh | null => { + const mk = new oc.BRepOffsetAPI_MakeOffsetShape(); + try { + if (simple) mk.PerformBySimple(base.wrapped, d); + else progress((p) => mk.PerformByJoin(base.wrapped, d, 1e-4, oc.BRepOffset_Mode.BRepOffset_Skin, false, false, oc.GeomAbs_JoinType.GeomAbs_Intersection, false, p)); + if (!mk.IsDone()) return null; + const s = wrap(mk.Shape()); + return isEmpty(s) || !offsetHolds(s, base, Math.abs(d)) ? null : s; + } catch { + return null; + } finally { + mk.delete(); + } + }; + const out = run(false) ?? run(true); + if (!out) throw this.h.fail('The faces could not be offset by this distance. Try a smaller distance.'); + shape = out; + } + this.addBody(st, f.id, shape, this.named(f.id, shape, (k) => `o${k}`)); + } + + private fill(f: SurfaceFillFeature, st: SurfState) { + if (f.edges.length < 1) throw this.h.fail('Select the edges around the opening to fill'); + if (f.edges.length > MAX_FILL_EDGES) throw this.h.fail(`Select at most ${MAX_FILL_EDGES} edges to fill`); + const edges = distinct(f.edges.map((r) => this.anyEdge(r, st).shape)); + // The boundary must close: an open set of edges is filled with made-up edges. + if (!closesLoop(edges)) throw this.h.fail('The selected edges must form one closed boundary'); + const oc = getOc(); + const mk = new oc.BRepOffsetAPI_MakeFilling(3, 15, 2, false, 1e-5, 1e-4, 1e-2, 0.1, 8, 9); + let shape: Sh; + try { + for (const e of edges) mk.Add(e.wrapped, oc.GeomAbs_Shape.GeomAbs_C0, true); + progress((p) => mk.Build(p)); + if (!mk.IsDone()) throw new Error('fill'); + shape = wrap(mk.Shape()); + } catch { + throw this.h.fail('The opening could not be filled. Check that the edges form one closed boundary.'); + } finally { + mk.delete(); + } + if (isEmpty(shape) || !(areaOf(shape) > 0)) throw this.h.fail('The opening could not be filled'); + this.addBody(st, f.id, shape, this.named(f.id, shape, (k) => `fill${k}`)); + } + + // ---- trim and extend ---- + + /** The trim tool as a shape spanning the targets, and its normal at a point. */ + private trimTool(f: SurfaceTrimFeature, st: SurfState, targets: SurfaceBody[]): { shape: Sh; normal: (p: Vec3) => Vec3 | null } { + const t = f.tool; + if (!t) throw this.h.fail('Select a trim tool: a plane, a sketch or a surface'); + const box = bbox(compound(targets.map((b) => b.shape))); + const center: Vec3 = box ? scale(add(box.min, box.max), 0.5) : [0, 0, 0]; + const size = box ? dist(box.min, box.max) : 100; + if (t.kind === 'plane') { + const fr = this.h.resolvePlane(t.plane, st); + const shape = bigPlane(fr, 2 * size + dist(fr.o, center) + 1); + return { shape, normal: () => fr.n }; + } + if (t.kind === 'sketch') { + const { sketch, frame } = this.sketchOf(t.sketch, st, 'trim sketch'); + const pieces = curvePieces(sketch, frame); + if (!pieces.length) throw this.h.fail('The trim sketch has no curves'); + const reach = 2 * size + Math.abs(dot(sub(center, frame.o), frame.n)) + 1; + const oc = getOc(); + const faces: Sh[] = []; + for (const p of pieces) { + for (const e of p.edges) { + const v = gvec(scale(frame.n, 2 * reach)); + const mk = new oc.BRepPrimAPI_MakePrism(e.wrapped, v, false, true); + try { faces.push(translated(wrap(mk.Shape()), scale(frame.n, -reach))); } finally { mk.delete(); v.delete(); } + } + } + const shape = faces.length === 1 ? faces[0] : compound(faces); + return { shape, normal: (p) => { const face = nearestFace(shape, p); return face ? normalAt(face, p) : null; } }; + } + const tool = this.bodyOf(t.face, st, 'a surface as the trim tool'); + if (targets.includes(tool)) throw this.h.fail('The trim tool cannot be one of the surfaces to trim'); + return { shape: tool.shape, normal: (p) => { const face = nearestFace(tool.shape, p); return face ? normalAt(face, p) : null; } }; + } + + private trim(f: SurfaceTrimFeature, st: SurfState) { + if (!f.faces.length) throw this.h.fail('Select the surfaces to trim'); + const targets = this.bodiesOf(f.faces, st, 'a surface to trim'); + const tool = this.trimTool(f, st, targets); + const results: { shape: Sh; faces: SurfFace[]; from: SurfaceBody }[] = []; + let crossed = false; + for (const body of targets) { + const tol = Math.max(1e-6, sizeOf(body.shape) * 1e-6); + const split = splitShape(body.shape, [tool.shape]); + if (!split) throw this.h.fail('The surface could not be trimmed with this tool'); + const faces = subShapes(split, 'face'); + const comps = components(faces, tool.shape, tol); + if (comps.length > 1) crossed = true; + let keep: number[]; + if (f.keep.length) { + const pts = f.keep.map(vertexAt); + keep = [...new Set(pts.map((v) => { + let best = -1, bd = Infinity; + comps.forEach((c, ci) => { for (const fi of c) { const d = nearest(v, faces[fi])?.d ?? Infinity; if (d < bd) { bd = d; best = ci; } } }); + return best; + }).filter((i) => i >= 0))]; + } else { + keep = comps.flatMap((c, ci) => { + const p = interiorPoint(faces[c[0]], tool.shape, tol); + const q = nearest(vertexAt(p), tool.shape); + const n = q ? tool.normal(q.p2) : null; + if (!q || !n) return []; + const side = dot(sub(p, q.p2), n); + return (side > 0) !== f.flip ? [ci] : []; + }); + } + const kept = keep.flatMap((ci) => comps[ci].map((fi) => faces[fi])); + if (!kept.length) { + throw this.h.fail(comps.length > 1 + ? 'Nothing of the surface is left on that side. Flip the side to keep, or pick the pieces to keep.' + : 'The trim tool does not cross the surface. Select a tool that reaches across it.'); + } + const shape = kept.length === 1 ? kept[0] : sew(kept, tol).shape; + results.push({ shape, from: body, faces: inherit(shape, body.faces, tol, (k) => ({ name: `${f.id}:t${k}`, feature: f.id })) }); + } + if (!crossed) this.h.warn('The trim tool does not cross the surface, so nothing was trimmed'); + results.forEach((r, k) => this.addBody(st, k ? `${f.id}.${k + 1}` : f.id, r.shape, r.faces, [r.from])); + } + + private extend(f: SurfaceExtendFeature, st: SurfState) { + if (!f.edges.length) throw this.h.fail('Select boundary edges of a surface to extend'); + const d = this.h.num(f, 'distance'); + if (!(d > 0)) throw this.h.fail('Distance must be greater than zero'); + const picks = f.edges.map((r) => { + const s = this.findEdge(r, st); + if (!s) throw this.h.fail('Select boundary edges of a surface body (the solid cannot be extended)'); + if (s.edge.faces.length !== 1) throw this.h.fail('Select edges on the boundary of the surface'); + return { body: s.body, edge: s.edge, face: s.body.faces[s.edge.faces[0]] }; + }).filter((p, i, all) => all.findIndex((q) => q.edge === p.edge) === i); + const oc = getOc(); + for (const body of [...new Set(picks.map((p) => p.body))]) { + const mine = picks.filter((p) => p.body === body); + const tol = Math.max(1e-6, sizeOf(body.shape) * 1e-6); + const pieces: SurfFace[] = []; + const replaced = new Set(); + if (f.mode === 'same') { + // Each face grows on the sides of its parameter range the selected edges lie on. + for (const face of [...new Set(mine.map((p) => p.face))]) { + const sides = { umin: false, umax: false, vmin: false, vmax: false }; + const uv = oc.BRepTools.UVBounds(face.shape.wrapped, 0, 0, 0, 0); + const span = Math.max(uv.UMax - uv.UMin, uv.VMax - uv.VMin, 1e-12); + for (const p of mine.filter((q) => q.face === face)) { + // The edge's ends and middle all lie on one side of the face's + // parameter range: a circle bounding a flat disc touches all four + // at its points, and extending one side made a rectangle of it. + let side: keyof typeof sides | null = null; + for (const pt of [p.edge.desc.mid, p.edge.desc.a, p.edge.desc.b]) { + const at = surfaceParams(face.shape, pt); + if (!at) throw this.h.fail('The surface could not be extended at the selected edge'); + const dists: [keyof typeof sides, number][] = [['umin', Math.abs(at.u - uv.UMin)], ['umax', Math.abs(at.u - uv.UMax)], ['vmin', Math.abs(at.v - uv.VMin)], ['vmax', Math.abs(at.v - uv.VMax)]]; + const on = dists.filter((x) => x[1] <= span * 1e-3).map((x) => x[0]); + if (!on.length || (side && !on.includes(side))) side = null; + else if (!side) side = on[0]; + if (!side) throw this.h.fail('Same-surface extension works on edges along the sides of a surface. Use Linear for this edge.'); + } + sides[side!] = true; + } + const out = new oc.TopoDS_Face(); + try { + oc.BRepLib.ExtendFace(face.shape.wrapped, d, sides.umin, sides.umax, sides.vmin, sides.vmax, out); + } catch { + throw this.h.fail('The surface could not be extended by this distance'); + } + const ext = wrap(out); + if (isEmpty(ext) || !(areaOf(ext) > face.desc.area)) throw this.h.fail('The surface could not be extended by this distance'); + replaced.add(face); + pieces.push({ shape: ext, desc: describeFace(ext), name: face.name, feature: face.feature }); + } + } else { + // A strip along each edge, tangent to the surface and straight out from it. + for (const p of mine) { + const mid = p.edge.desc.mid; + const n = normalAt(p.face.shape, mid); + const t = edgeTangent(p.edge.shape, mid); + if (!n || !t) throw this.h.fail('The surface could not be extended at the selected edge'); + // Away from the face: a step that way from the edge is off it. (The + // middle of the face's range lay behind the edge, except for a hole's + // edge: its strip went over the face around the hole.) + const eps = sizeOf(p.face.shape) * 1e-3; + const sign = (nearest(vertexAt(add(mid, scale(normalize(cross(t, n)), eps))), p.face.shape)?.d ?? eps) < eps * 0.5 ? -1 : 1; + const out = scale(normalize(cross(t, n)), sign); + const strip = p.edge.desc.type === 'line' ? 'straight' : ruledStrip(p.edge.shape, p.face.shape, out, sign, d); + if (!strip) throw this.h.fail('The surface could not be extended at the selected edge'); + let shape: Sh; + if (strip !== 'straight') shape = strip; + else { + // Straight out along one direction (a straight edge, or the rim of an extruded surface). + const v = gvec(scale(out, d)); + const mk = new oc.BRepPrimAPI_MakePrism(p.edge.shape.wrapped, v, false, true); + try { shape = wrap(mk.Shape()); } catch { throw this.h.fail('The surface could not be extended at the selected edge'); } finally { mk.delete(); v.delete(); } + } + if (!(areaOf(shape) > d * p.edge.desc.length * 0.5)) throw this.h.fail('The surface could not be extended at the selected edge'); + for (const s of subShapes(shape, 'face')) pieces.push({ shape: s, desc: describeFace(s), name: `${f.id}:x:${p.face.name}`, feature: f.id }); + } + } + const rest = body.faces.filter((x) => !replaced.has(x)); + const all = [...rest, ...pieces]; + const shape = all.length === 1 ? all[0].shape : sew(all.map((x) => x.shape), tol).shape; + const n = st.surfaces.filter((b) => bodyFeature(b.id) === f.id).length; + this.addBody(st, n ? `${f.id}.${n + 1}` : f.id, shape, inherit(shape, all, tol, (k) => ({ name: `${f.id}:x${k}`, feature: f.id })), [body]); + } + } + + // ---- knit, thicken, cut, delete face ---- + + private knit(f: SurfaceKnitFeature, st: SurfState): 'surface' | 'body' { + if (!f.faces.length) throw this.h.fail('Select the surfaces to knit'); + const bodies = this.bodiesOf(f.faces, st, 'surfaces to knit'); + const tol = this.h.num(f, 'tolerance'); + if (!(tol > 0)) throw this.h.fail('The knit tolerance must be greater than zero'); + const faces = bodies.flatMap((b) => b.faces); + if (faces.length > MAX_KNIT_FACES) throw this.h.fail(`Too many faces to knit (more than ${MAX_KNIT_FACES})`); + if (bodies.length < 2 && !f.solid) this.h.warn('Only one surface is selected: there is nothing to knit it to'); + let res: { shape: Sh; free: number }; + try { + res = sew(bodies.map((b) => b.shape), tol); + } catch { + throw this.h.fail('The surfaces could not be knit'); + } + // A tolerance near the surfaces' size sews their edges together into nothing. + if (isEmpty(res.shape)) throw this.h.fail('The surfaces could not be knit with this tolerance. Use a smaller knit tolerance: about the size of the gaps to close.'); + let shells = subShapes(res.shape, 'shell'); + const named = inherit(res.shape, faces, Math.max(tol, 1e-6), (k) => ({ name: `${f.id}:k${k}`, feature: f.id })); + if (f.solid) { + // Sewing leaves a single closed face (a revolved sphere) as a face, not a shell. + if (!shells.length && res.free === 0) { + const all = subShapes(res.shape, 'face'); + if (all.length === 1) shells = [closedShell(all[0])]; + } + if (res.free > 0 || shells.length !== 1) { + throw this.h.fail(res.free > 0 + ? `The surfaces do not form a closed volume (${res.free} open ${res.free === 1 ? 'edge' : 'edges'}). Close the gaps or raise the knit tolerance, or knit without Create solid.` + : 'The surfaces do not form a closed volume. Close the gaps or raise the knit tolerance, or knit without Create solid.'); + } + const solid = solidFromShell(shells[0]); + if (!solid) throw this.h.fail('The surfaces do not form a closed volume'); + const tool = inherit(solid, named, Math.max(tol, 1e-6), (k) => ({ name: `${f.id}:k${k}`, feature: f.id })); + st.surfaces = st.surfaces.filter((b) => !bodies.includes(b)); + this.h.applyTool(f.id, st, solid, tool, false, 'The knit solid adds no material: it lies inside the part.'); + return 'body'; + } + if (shells.length > 1 || (bodies.length > 1 && res.free > 0 && shells.length + subShapes(res.shape, 'face', 'shell').length > 1)) { + this.h.warn('Some of the surfaces could not be knit: they do not meet within the knit tolerance'); + } + this.addBody(st, f.id, res.shape, named, bodies); + return 'surface'; + } + + private thicken(f: ThickenFeature, st: SurfState) { + if (!f.faces.length) throw this.h.fail('Select a surface to thicken'); + const body = this.bodyOf(f.faces[0], st, 'a surface to thicken'); + const t = this.h.num(f, 'thickness'); + if (!(t > 0)) throw this.h.fail('Thickness must be greater than zero'); + const area = areaOf(body.shape); + const solid = thickSolid(body.shape, f.side === 'back' ? -t : t, f.side === 'both', area); + if (!solid) throw this.h.fail('The surface could not be thickened. Try a smaller thickness, or thicken smooth surfaces one by one.'); + const tool = this.named(f.id, solid, (k) => `t${k}`); + st.surfaces = st.surfaces.filter((b) => b !== body); + this.h.applyTool(f.id, st, solid, tool, f.cut, 'The thickened surface adds no material: it lies inside the part.'); + } + + private cutWith(f: SurfaceCutFeature, st: SurfState) { + if (!f.face) throw this.h.fail('Select the surface to cut with'); + if (!st.body) throw this.h.fail('There is no solid body to cut'); + const tool = this.bodyOf(f.face, st, 'a surface to cut with'); + const body = st.body; + const split = splitShape(body, [tool.shape]); + if (!split) throw this.h.fail('The body could not be cut with this surface'); + const solids = subShapes(split, 'solid'); + const tol = Math.max(1e-6, sizeOf(body) * 1e-6); + const kept: Sh[] = []; + let removed = 0; + for (const s of solids) { + // A piece is removed when it lies on the side of the surface its normal + // points to: its faces on the surface face the other way from it. + let side = 0; + for (const face of subShapes(s, 'face')) { + const p = faceMidPoint(face); + const q = nearest(vertexAt(p), tool.shape); + if (!q || q.d > tol * 10) continue; + const nTool = nearestFace(tool.shape, q.p2); + const a = nTool ? normalAt(nTool, q.p2) : null; + const b = normalAt(face, p); + if (!a || !b) continue; + side = dot(a, b) < 0 ? 1 : -1; + break; + } + if ((side > 0) !== f.flip && side !== 0) removed++; + else kept.push(s); + } + if (!removed) throw this.h.fail('The surface does not cut the body. Make it reach across the body (extend it), or flip the side.'); + if (!kept.length) throw this.h.fail('The cut removes all material'); + const result = kept.length === 1 ? kept[0] : compound(kept); + const toolFaces = tool.faces.map((x, k) => ({ ...x, name: `${f.id}:c${k}`, feature: f.id })); + st.faces = this.h.nameFaces(f.id, result, st, toolFaces); + st.body = result; + st.edges = null; + } + + private deleteFace(f: DeleteFaceFeature, st: SurfState): 'surface' | 'body' { + if (!f.faces.length) throw this.h.fail('Select faces of the solid to delete'); + if (!st.body) throw this.h.fail('There is no solid body to delete faces from'); + const gone = new Set(f.faces.map((r) => { + if (this.findFace(r, st)) throw this.h.fail('Select faces of the solid. To remove part of a surface, trim it.'); + return this.h.resolveFace(r, st); + })); + const rest = st.faces.filter((_, i) => !gone.has(i)); + if (!rest.length) throw this.h.fail('Deleting every face leaves nothing'); + if (f.mode === 'patch') { + const tol = Math.max(1e-6, sizeOf(st.body) * 1e-7); + const holes = boundaryLoops(rest.map((x) => x.shape)); + const patches: SurfFace[] = []; + holes.forEach((loop, k) => { + const filled = fillLoop(loop); + if (!filled) throw this.h.fail('The hole left by the deleted faces could not be patched'); + for (const s of subShapes(filled, 'face')) patches.push({ shape: s, desc: describeFace(s), name: `${f.id}:patch${k}`, feature: f.id }); + }); + const all = [...rest, ...patches]; + const { shape, free } = sew(all.map((x) => x.shape), tol); + const shells = subShapes(shape, 'shell'); + const solid = free === 0 && shells.length === 1 ? solidFromShell(shells[0]) : null; + if (!solid) throw this.h.fail('The patched faces do not close the body'); + st.faces = inherit(solid, all, tol, (k) => ({ name: `${f.id}:n${k}`, feature: f.id })); + st.body = solid; + st.edges = null; + return 'body'; + } + // The remaining faces share their edges already: one shell of them. + const shape = shellOf(rest.map((x) => x.shape)); + const faces = rest.map((x) => ({ ...x })); + st.body = null; + st.faces = []; + st.edges = null; + this.addBody(st, f.id, shape, faces); + return 'surface'; + } + + // ---------- output ---------- + + /** The solid's mesh and lists with every surface body's faces and edges after them. */ + mesh(base: { mesh: MeshData | null; faces: FaceInfo[]; edges: EdgeInfo[] }, st: SurfState, quality: number): { mesh: MeshData | null; faces: FaceInfo[]; edges: EdgeInfo[] } { + const box = this.box(st); + const diag = box ? dist(box.min, box.max) : 1; + const q = Math.max(0, Math.min(2, quality)); + const tol = Math.max(diag * [0.002, 0.0006, 0.0002][q], 1e-4), ang = [0.5, 0.25, 0.12][q]; + const pos: Float32Array[] = [], nrm: Float32Array[] = [], idx: Uint32Array[] = [], vf: Float32Array[] = [], ep: Float32Array[] = [], eid: Float32Array[] = [], vtx: Float32Array[] = []; + const m0 = base.mesh; + if (m0) { pos.push(m0.positions); nrm.push(m0.normals); idx.push(m0.indices); vf.push(m0.vertexFace); ep.push(m0.edgePositions); eid.push(m0.edgeIds); vtx.push(m0.vertices); } + let vCount = m0 ? m0.positions.length / 3 : 0; + const faces = [...base.faces]; + const edges = [...base.edges]; + for (const body of st.surfaces) { + const f0 = faces.length, e0 = edges.length; + const m = bodyMesh(body, tol, ang); + const shifted = new Uint32Array(m.indices.length); + for (let i = 0; i < m.indices.length; i++) shifted[i] = m.indices[i] + vCount; + vCount += m.positions.length / 3; + const vface = new Float32Array(m.vface.length); + for (let i = 0; i < vface.length; i++) vface[i] = m.vface[i] + f0; + const ids = new Float32Array(m.ids.length); + for (let i = 0; i < ids.length; i++) ids[i] = m.ids[i] + e0; + pos.push(m.positions); nrm.push(m.normals); idx.push(shifted); vf.push(vface); + ep.push(m.lines); eid.push(ids); vtx.push(m.vertices); + const bes = bodyEdges(body); + for (const x of body.faces) { + const d = x.desc; + const info: FaceInfo = { name: x.name, type: d.type, center: d.center, area: d.area, feature: x.feature, body: body.id }; + if (d.type === 'plane') { info.normal = d.d; info.frame = planarFaceFrame(d); } + if (d.type === 'cylinder' || d.type === 'sphere') { info.axis = { p: d.p, d: d.d }; info.radius = d.r; } + faces.push(info); + } + for (const e of bes) { + edges.push({ + name: e.name, type: e.desc.type, a: e.desc.a, b: e.desc.b, mid: e.desc.mid, length: e.desc.length, faces: e.faces.map((i) => f0 + i), + dir: e.desc.dir, center: e.desc.center, axis: e.desc.axis, radius: e.desc.radius, body: body.id, + }); + } + } + const cat = (parts: T[], make: (n: number) => T): T => { + const out = make(parts.reduce((n, p) => n + p.length, 0)); + let o = 0; + for (const p of parts) { out.set(p as never, o); o += p.length; } + return out; + }; + const f32 = (n: number) => new Float32Array(n); + const mesh: MeshData = { + positions: cat(pos, f32), normals: cat(nrm, f32), indices: cat(idx, (n) => new Uint32Array(n)), vertexFace: cat(vf, f32), + edgePositions: cat(ep, f32), edgeIds: cat(eid, f32), vertices: cat(vtx, f32), + }; + return { mesh, faces, edges }; + } + + /** Bounding box of the solid and the surface bodies. */ + box(st: SurfState): { min: Vec3; max: Vec3 } | null { + // Each body's box is kept: a box of a curved surface takes milliseconds, and + // every rebuild (an edit of the solid) asked for the boxes of all of them again. + const boxes = [...(st.body ? [bbox(st.body)] : []), ...st.surfaces.map(bodyBox)].filter((b): b is { min: Vec3; max: Vec3 } => !!b); + if (!boxes.length) return null; + return { + min: [0, 1, 2].map((i) => Math.min(...boxes.map((b) => b.min[i]))) as Vec3, + max: [0, 1, 2].map((i) => Math.max(...boxes.map((b) => b.max[i]))) as Vec3, + }; + } + + /** The solid with the surface bodies (less those of hidden features), for export and drawings. */ + allShapes(st: SurfState, hidden?: ReadonlySet): Sh | null { + const shown = hidden?.size ? st.surfaces.filter((b) => !hidden.has(bodyFeature(b.id))) : st.surfaces; + const shapes = [...(st.body ? [st.body] : []), ...shown.map((b) => b.shape)]; + if (!shapes.length) return null; + return shapes.length === 1 ? shapes[0] : compound(shapes); + } + + /** Total area of the surface bodies. */ + area(st: SurfState): number { + return st.surfaces.reduce((a, b) => a + areaOf(b.shape), 0); + } + + /** A face or edge of a surface body by its index in the build result's lists (after the solid's). */ + shapeAt(st: SurfState, kind: 'face' | 'edge', index: number, solidCount: number): Sh | null { + let i = index - solidCount; + if (i < 0) return null; + for (const b of st.surfaces) { + const list = kind === 'face' ? b.faces : bodyEdges(b); + if (i < list.length) return list[i].shape; + i -= list.length; + } + return null; + } +} + +// ---------- meshes of surface bodies ---------- + +interface BodyMesh { + positions: Float32Array; + normals: Float32Array; + indices: Uint32Array; + /** Face of each vertex, by its index in the body's faces. */ + vface: Float32Array; + lines: Float32Array; + /** Edge of each line point, by its index in bodyEdges. */ + ids: Float32Array; + vertices: Float32Array; +} + +/** + * Meshes and boxes of surface bodies, kept with the body (bodies are not + * changed once made): an edit of the solid meshed every surface again, 30 ms + * on each rebuild for a surface of 200 faces. + */ +const bodyMeshCache = new WeakMap(); +const bodyBoxCache = new WeakMap(); + +function bodyBox(body: SurfaceBody): { min: Vec3; max: Vec3 } | null { + if (!bodyBoxCache.has(body)) bodyBoxCache.set(body, bbox(body.shape)); + return bodyBoxCache.get(body)!; +} + +function bodyMesh(body: SurfaceBody, tol: number, ang: number): BodyMesh { + const hit = bodyMeshCache.get(body); + if (hit && hit.tol === tol && hit.ang === ang) return hit.m; + const oc = getOc(); + const m = meshShape(body.shape, tol, ang); + const fIndex = new ShapeIndex(body.faces.map((x) => x.shape)); + const vface = new Float32Array(m.positions.length / 3); + const claimed = new Set(); + for (let g = 0; g + 2 < m.faceGroups.length; g += 3) { + const start = m.faceGroups[g], count = m.faceGroups[g + 1]; + const cands = fIndex.findHash(m.faceGroups[g + 2]); + const fi = cands.find((c) => !claimed.has(c)) ?? cands[0] ?? 0; + claimed.add(fi); + for (let t = start; t < start + count; t++) vface[m.indices[t]] = fi; + } + const bes = bodyEdges(body); + const eIndex = new ShapeIndex(bes.map((e) => e.shape)); + const em = meshEdgesOf(body.shape, tol, ang); + const lines: number[] = [], ids: number[] = []; + const claimedE = new Set(); + for (let g = 0; g + 2 < em.groups.length; g += 3) { + const start = em.groups[g], count = em.groups[g + 1]; + const cands = eIndex.findHash(em.groups[g + 2]); + const ei = cands.find((c) => !claimedE.has(c)) ?? cands[0] ?? 0; + claimedE.add(ei); + const e = bes[ei]; + // Seams (a closed face meeting itself) are not drawn. + if (e && e.faces.length === 1 && oc.BRep_Tool.IsClosed(e.shape.wrapped, body.faces[e.faces[0]].shape.wrapped)) continue; + for (let k = start; k < start + count; k++) { lines.push(em.lines[k * 3], em.lines[k * 3 + 1], em.lines[k * 3 + 2]); ids.push(ei); } + } + const vs = subShapes(body.shape, 'vertex').map(vertexPoint); + const vertices = new Float32Array(vs.length * 3); + vs.forEach((p, i) => vertices.set(p, i * 3)); + const out: BodyMesh = { positions: m.positions, normals: m.normals, indices: m.indices, vface, lines: new Float32Array(lines), ids: new Float32Array(ids), vertices }; + bodyMeshCache.set(body, { tol, ang, m: out }); + return out; +} + +// ---------- geometry helpers ---------- + +function copyShape(s: Sh): Sh { + // A transform by the identity copies the geometry (BRepBuilderAPI_Copy is not in the bindings). + const oc = getOc(); + const tr = new oc.gp_Trsf(); + const mk = new oc.BRepBuilderAPI_Transform(s.wrapped, tr, true, false); + try { return wrap(mk.Shape()); } finally { mk.delete(); tr.delete(); } +} + +/** + * Whether an offset of `base` by d is one: no face collapsed to nothing, and + * no part of it nearer the base than d. Offsetting a curved face inward by + * its radius or more turns it inside out: a cylinder of radius 5 offset by + * -6 came out as a cylinder of radius 1, on the wrong side of the axis. + */ +function offsetHolds(out: Sh, base: Sh, d: number): boolean { + const size = Math.max(sizeOf(base), d, 1); + if (subShapes(out, 'face').some((f) => !(areaOf(f) > size * size * 1e-9))) return false; + const q = nearest(out, base); + return !!q && q.d > d * (1 - 1e-3) - size * 1e-6; +} + +/** The shape split by the tools (null when the operation fails). */ +function splitShape(shape: Sh, tools: Sh[]): Sh | null { + const oc = getOc(); + const args = new oc.NCollection_List_TopoDS_Shape(), list = new oc.NCollection_List_TopoDS_Shape(); + const sp = new oc.BRepAlgoAPI_Splitter(); + try { + args.Append(shape.wrapped); + for (const t of tools) list.Append(t.wrapped); + sp.SetArguments(args); + sp.SetTools(list); + progress((p) => sp.Build(p)); + if (!sp.IsDone() || sp.HasErrors?.()) return null; + return wrap(sp.Shape()); + } catch { + return null; + } finally { + sp.delete(); + args.delete(); + list.delete(); + } +} + +/** Groups faces into pieces connected across edges that do not lie on the tool. */ +function components(faces: Sh[], tool: Sh, tol: number): number[][] { + const edgeFaces = new Map(); + const oc = getOc(); + faces.forEach((f, fi) => { + for (const e of subShapes(f, 'edge')) { + const h = oc.ReplicadShapeHasher.HashCode(e.wrapped, 2147483647); + let l = edgeFaces.get(h); + if (!l) edgeFaces.set(h, (l = [])); + const hit = l.find((x) => x.e.wrapped.IsSame(e.wrapped)); + if (hit) { if (!hit.f.includes(fi)) hit.f.push(fi); } else l.push({ e, f: [fi] }); + } + }); + const parent = faces.map((_, i) => i); + const find = (i: number): number => (parent[i] === i ? i : (parent[i] = find(parent[i]))); + for (const l of edgeFaces.values()) { + for (const { e, f } of l) { + if (f.length < 2) continue; + const mid = describeEdge(e).mid; + const q = nearest(vertexAt(mid), tool); + if (q && q.d < tol * 10) continue; + for (let k = 1; k < f.length; k++) parent[find(f[k])] = find(f[0]); + } + } + const groups = new Map(); + faces.forEach((_, i) => { const r = find(i); const g = groups.get(r); if (g) g.push(i); else groups.set(r, [i]); }); + return [...groups.values()]; +} + +/** + * A point on a face, as far from `avoid` as can be found: the middle of its + * parameter range lies outside a face with a hole (the square around a + * circle trimmed out of it), so a grid over that range is tried, keeping + * the points that are on the face. + */ +function interiorPoint(face: Sh, avoid: Sh, tol: number): Vec3 { + const oc = getOc(); + const ad = new oc.BRepAdaptor_Surface(face.wrapped, true); + const pts: Vec3[] = []; + try { + const u0 = ad.FirstUParameter(), u1 = ad.LastUParameter(), v0 = ad.FirstVParameter(), v1 = ad.LastVParameter(); + const at = (u: number, v: number) => { const q = ad.Value(u0 + (u1 - u0) * u, v0 + (v1 - v0) * v); const out = xyz(q); q.delete(); return out; }; + pts.push(at(0.5, 0.5)); + const n = 6; + for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) pts.push(at((i + 0.5) / n, (j + 0.5) / n)); + } finally { + ad.delete(); + } + let best = pts[0], bd = -1; + for (const p of pts) { + const v = vertexAt(p); + if ((nearest(v, face)?.d ?? Infinity) > tol) continue; + const d = nearest(v, avoid)?.d ?? 0; + if (d > bd) { bd = d; best = p; } + } + return best; +} + +/** + * Shapes less repeats: a file that names one edge or face twice made two + * overlapping strips or offsets of it (and thousands of them took minutes). + */ +function distinct(shapes: Sh[]): Sh[] { + const out: Sh[] = []; + for (const s of shapes) if (!out.some((o) => o === s || o.wrapped.IsSame(s.wrapped))) out.push(s); + return out; +} + +/** The face of a shape nearest a point. */ +function nearestFace(shape: Sh, p: Vec3): Sh | null { + const faces = subShapes(shape, 'face'); + if (faces.length === 1) return faces[0]; + const v = vertexAt(p); + let best: Sh | null = null, bd = Infinity; + for (const f of faces) { + const d = nearest(v, f)?.d ?? Infinity; + if (d < bd) { bd = d; best = f; } + } + return best; +} + +/** Parameters (u, v) of the point of a face's surface nearest p. */ +function surfaceParams(face: Sh, p: Vec3): { u: number; v: number } | null { + const oc = getOc(); + let surf: any = null, proj: any = null; + const g = pnt(p); + try { + surf = oc.BRep_Tool.Surface(face.wrapped); + proj = new oc.GeomAPI_ProjectPointOnSurf(g, surf, oc.Extrema_ExtAlgo.Extrema_ExtAlgo_Grad); + if (!proj.NbPoints()) return null; + const uv = proj.LowerDistanceParameters(0, 0); + return { u: uv.U, v: uv.V }; + } catch { + return null; + } finally { + proj?.delete(); surf?.delete?.(); g.delete(); + } +} + +/** + * A strip of width d straight out from a curved edge of a face, tangent to + * the face, where the outward direction turns along the edge (a circle + * bounding a flat disc): ruled between the edge and the curve d out from it. + * 'straight' when the direction does not turn, so a prism makes the strip + * exactly; null when the strip cannot be made. + */ +function ruledStrip(edge: Sh, face: Sh, outMid: Vec3, sign: number, d: number): Sh | 'straight' | null { + const oc = getOc(); + const ad = new oc.BRepAdaptor_Curve(edge.wrapped); + const far: Vec3[] = []; + let turns = false; + try { + const f = ad.FirstParameter(), l = ad.LastParameter(); + const N = 64; + for (let i = 0; i <= N; i++) { + const q = new oc.gp_Pnt(), v = new oc.gp_Vec(); + ad.D1(f + ((l - f) * i) / N, q, v); + const p = xyz(q), t = xyz(v); + q.delete(); v.delete(); + const n = normalAt(face, p); + if (!n || !(len(t) > 1e-12)) return null; + const out = scale(normalize(cross(normalize(t), n)), sign); + if (dot(out, outMid) < 1 - 1e-9) turns = true; + far.push(add(p, scale(out, d))); + } + } finally { + ad.delete(); + } + if (!turns) return 'straight'; + if (describeEdge(edge).closed) far[far.length - 1] = far[0]; + const ts = new oc.BRepOffsetAPI_ThruSections(false, true, 1e-6); + try { + const farEdge = R.makeBSplineApproximation(far, { tolerance: Math.max(1e-6, d * 1e-5) }); + ts.AddWire(R.assembleWire([edge as any]).wrapped); + ts.AddWire(R.assembleWire([farEdge]).wrapped); + progress((p) => ts.Build(p)); + if (!ts.IsDone()) return null; + const s = wrap(ts.Shape()); + return isEmpty(s) ? null : s; + } catch { + return null; + } finally { + ts.delete(); + } +} + +/** Whether an edge has points on both sides of an axis lying in its plane (normal n). */ +function crossesAxis(edge: Sh, p: Vec3, d: Vec3, n: Vec3): boolean { + const oc = getOc(); + const ad = new oc.BRepAdaptor_Curve(edge.wrapped); + try { + const f = ad.FirstParameter(), l = ad.LastParameter(); + const side = new Set(); + const size = Math.max(1, describeEdge(edge).length); + for (let i = 0; i <= 32; i++) { + const q = ad.Value(f + ((l - f) * i) / 32); + const s = dot(cross(d, sub(xyz(q), p)), n); + q.delete(); + if (Math.abs(s) > 1e-7 * size) side.add(Math.sign(s)); + } + return side.size > 1; + } catch { + return false; + } finally { + ad.delete(); + } +} + +/** Unit tangent of an edge at the point of it nearest p. */ +function edgeTangent(edge: Sh, p: Vec3): Vec3 | null { + const oc = getOc(); + const ad = new oc.BRepAdaptor_Curve(edge.wrapped); + try { + const f = ad.FirstParameter(), l = ad.LastParameter(); + let best = f, bd = Infinity; + for (let i = 0; i <= 32; i++) { + const t = f + ((l - f) * i) / 32; + const q = ad.Value(t); + const d = dist(xyz(q), p); + q.delete(); + if (d < bd) { bd = d; best = t; } + } + const q = new oc.gp_Pnt(), v = new oc.gp_Vec(); + ad.D1(best, q, v); + const out = xyz(v); + q.delete(); v.delete(); + return len(out) > 1e-12 ? normalize(out) : null; + } catch { + return null; + } finally { + ad.delete(); + } +} + +/** A shell of one face (shellOf leaves a single face as it is). */ +function closedShell(face: Sh): Sh { + const oc = getOc(); + const b = new oc.TopoDS_Builder(); + const sh = new oc.TopoDS_Shell(); + try { + b.MakeShell(sh); + b.Add(sh, face.wrapped); + return wrap(sh); + } finally { + b.delete(); + } +} + +/** A solid bounded by a closed shell, oriented so its volume is positive. */ +function solidFromShell(shell: Sh): Sh | null { + const oc = getOc(); + const fix = new oc.ShapeFix_Solid(); + try { + const raw = oc.TopoDS.Shell(shell.wrapped); + let s: Sh; + try { s = wrap(fix.SolidFromShell(raw)); } finally { raw.delete(); } + if (volumeOf(s) < 0) s = wrap(s.wrapped.Reversed()); + return volumeOf(s) > 0 ? s : null; + } catch { + return null; + } finally { + fix.delete(); + } +} + +/** + * A solid made by thickening a surface by t along its normal (negative: + * against it; both: half each way). A smooth surface is offset as a whole; + * across sharp edges between faces that offset leaves gaps, so each face is + * thickened alone and the slabs joined, with a wedge filling the corner + * outside each sharp (straight) edge, as the offset faces would meet there. + */ +function thickSolid(shape: Sh, t: number, both: boolean, area: number): Sh | null { + const oc = getOc(); + // A thickened surface takes at least a third of area × thickness (a sphere + // thickened inward to its centre; less means its offset turned inside out) + // and no more than its box grown by the thickness. Curvature alone takes it + // well outside area × thickness: a dome of radius 5 thickened 7 outward is + // three times that, and inward by 4 four tenths of it. + const box = bbox(shape); + const grown = box ? box.max.reduce((v, c, i) => v * (c - box.min[i] + 2 * Math.abs(t)), 1) : Infinity; + const plausible = (v: number) => v > (area * Math.abs(t) / 3) * (1 - 1e-6) && v < grown * (1 + 1e-6); + const simple = (base: Sh, off: number): Sh | null => { + const mk = new oc.BRepOffsetAPI_MakeThickSolid(); + try { + mk.MakeThickSolidBySimple(base.wrapped, off); + if (!mk.IsDone()) return null; + let s = wrap(mk.Shape()); + if (volumeOf(s) < 0) s = wrap(s.wrapped.Reversed()); + return s; + } catch { + return null; + } finally { + mk.delete(); + } + }; + const shift = (base: Sh, off: number): Sh | null => { + const mk = new oc.BRepOffsetAPI_MakeOffsetShape(); + try { + mk.PerformBySimple(base.wrapped, off); + return mk.IsDone() ? wrap(mk.Shape()) : null; + } catch { + return null; + } finally { + mk.delete(); + } + }; + const make = (base: Sh): Sh | null => { + const start = both ? shift(base, -t / 2) : base; + return start ? simple(start, t) : null; + }; + const sharp = sharpEdges(shape); + if (!sharp) return null; + if (!sharp.length) { + const whole = make(shape); + if (whole && !isEmpty(whole)) return plausible(volumeOf(whole)) && isValid(whole) ? whole : null; + // A closed surface (a sphere) has no edge to thicken from: the solid + // between it and its offset, the larger less the smaller. + const shells = subShapes(shape, 'shell'); + const faces = subShapes(shape, 'face'); + const shell = shells.length === 1 ? shells[0] : !shells.length && faces.length === 1 ? closedShell(faces[0]) : null; + if (!shell || sew([shell], 1e-6).free > 0) return null; + const [a, b] = both ? [-t / 2, t / 2] : [0, t]; + const solidAt = (off: number) => { + const s = off ? shift(shell, off) : shell; + // Offset inward past its centre, a sphere comes out inside out (see offsetHolds). + if (!s || (off && !offsetHolds(s, shell, Math.abs(off)))) return null; + const sh = subShapes(s, 'shell'); + return sh.length === 1 ? solidFromShell(sh[0]) : null; + }; + const sa = solidAt(a), sb = solidAt(b); + if (!sa || !sb) return null; + const [big, small] = volumeOf(sa) > volumeOf(sb) ? [sa, sb] : [sb, sa]; + try { + const out = cut(big, small); + return plausible(volumeOf(out)) && isValid(out) ? out : null; + } catch { + return null; + } + } + // Wedges are built for straight edges only. + if (sharp.some((e) => e.desc.type !== 'line')) return null; + const pieces: Sh[] = []; + for (const f of subShapes(shape, 'face')) { + const slab = make(f); + if (!slab || !(volumeOf(slab) > 0)) return null; + pieces.push(slab); + } + const sides = both ? [t / 2, -t / 2] : [t]; + for (const e of sharp) { + const k = 1 + dot(e.na, e.nb); + if (k < 1e-6) return null; + for (const s of sides) { + const P = e.desc.a; + const quad = [P, add(P, scale(e.na, s)), add(P, scale(add(e.na, e.nb), s / k)), add(P, scale(e.nb, s))]; + try { + const face = R.makeFace(R.assembleWire(quad.map((q, i) => R.makeLine(q, quad[(i + 1) % 4])))); + const v = gvec(sub(e.desc.b, e.desc.a)); + const mk = new oc.BRepPrimAPI_MakePrism(face.wrapped, v, false, true); + try { pieces.push(wrap(mk.Shape())); } finally { mk.delete(); v.delete(); } + } catch { + // Faces meeting flat (no corner to fill) make no quad. + } + } + } + const args = new oc.NCollection_List_TopoDS_Shape(), tools = new oc.NCollection_List_TopoDS_Shape(); + const builder = new oc.BRepAlgoAPI_Fuse(); + try { + args.Append(pieces[0].wrapped); + for (let i = 1; i < pieces.length; i++) tools.Append(pieces[i].wrapped); + builder.SetArguments(args); + builder.SetTools(tools); + progress((p) => builder.Build(p)); + if (!builder.IsDone()) return null; + let out = wrap(builder.Shape()); + const unify = new oc.ShapeUpgrade_UnifySameDomain(out.wrapped, true, true, false); + try { unify.Build(); out = wrap(unify.Shape()); } finally { unify.delete(); } + return plausible(volumeOf(out)) && isValid(out) ? out : null; + } catch { + return null; + } finally { + builder.delete(); args.delete(); tools.delete(); + } +} + +/** + * Edges between two faces of a shell whose normals differ there, with the + * normals at the edge's start (null when a normal cannot be found). + */ +function sharpEdges(shape: Sh): { desc: EdgeDesc; na: Vec3; nb: Vec3 }[] | null { + const faces = subShapes(shape, 'face'); + if (faces.length < 2) return []; + const edges = subShapes(shape, 'edge'); + const index = new ShapeIndex(edges); + const adj: number[][] = edges.map(() => []); + faces.forEach((f, fi) => { + for (const e of subShapes(f, 'edge')) { + const j = index.find(e.wrapped); + if (j >= 0 && !adj[j].includes(fi)) adj[j].push(fi); + } + }); + const out: { desc: EdgeDesc; na: Vec3; nb: Vec3 }[] = []; + for (let i = 0; i < edges.length; i++) { + if (adj[i].length !== 2) continue; + const desc = describeEdge(edges[i]); + const na = normalAt(faces[adj[i][0]], desc.mid), nb = normalAt(faces[adj[i][1]], desc.mid); + if (!na || !nb) return null; + if (dot(na, nb) < Math.cos(Math.PI / 180)) { + const a = normalAt(faces[adj[i][0]], desc.a), b = normalAt(faces[adj[i][1]], desc.a); + if (!a || !b) return null; + out.push({ desc, na: a, nb: b }); + } + } + return out; +} + +/** Whether edges join into one closed loop: every end point is shared by two of them. */ +function closesLoop(edges: Sh[]): boolean { + if (!edges.length) return false; + const ends: Vec3[] = []; + for (const e of edges) { + const d = describeEdge(e); + if (d.closed) { if (edges.length === 1) return true; return false; } + ends.push(d.a, d.b); + } + let size = 1; + for (const p of ends) size = Math.max(size, Math.abs(p[0]), Math.abs(p[1]), Math.abs(p[2])); + const tol = 1e-5 * size; + return ends.every((p) => ends.filter((q) => dist(p, q) < tol).length === 2); +} + +/** Closed loops of the edges bounding only one of the faces (the holes left in them). */ +function boundaryLoops(faces: Sh[]): Sh[][] { + const oc = getOc(); + const seen = new Map(); + for (const f of faces) { + for (const e of subShapes(f, 'edge')) { + const h = oc.ReplicadShapeHasher.HashCode(e.wrapped, 2147483647); + let l = seen.get(h); + if (!l) seen.set(h, (l = [])); + const hit = l.find((x) => x.e.wrapped.IsSame(e.wrapped)); + if (hit) hit.n++; else l.push({ e, n: 1 }); + } + } + const free = [...seen.values()].flat().filter((x) => x.n === 1).map((x) => x.e); + const ends = free.map((e) => subShapes(e, 'vertex').map(vertexPoint)); + const used = new Set(); + const loops: Sh[][] = []; + const tol = 1e-6; + for (let i = 0; i < free.length; i++) { + if (used.has(i)) continue; + used.add(i); + const loop = [free[i]]; + const start = ends[i][0]; + let tail = ends[i][ends[i].length - 1]; + for (let guard = 0; guard < free.length && dist(start, tail) > tol; guard++) { + const j = free.findIndex((_, k) => !used.has(k) && ends[k].some((p) => dist(p, tail) < tol)); + if (j < 0) break; + used.add(j); + loop.push(free[j]); + tail = dist(ends[j][0], tail) < tol ? ends[j][ends[j].length - 1] : ends[j][0]; + } + loops.push(loop); + } + return loops; +} + +/** A patch over a closed loop of edges. */ +function fillLoop(edges: Sh[]): Sh | null { + if (edges.length > MAX_FILL_EDGES) return null; + const oc = getOc(); + const mk = new oc.BRepOffsetAPI_MakeFilling(3, 15, 2, false, 1e-5, 1e-4, 1e-2, 0.1, 8, 9); + try { + for (const e of edges) mk.Add(e.wrapped, oc.GeomAbs_Shape.GeomAbs_C0, true); + progress((p) => mk.Build(p)); + if (!mk.IsDone()) return null; + const s = wrap(mk.Shape()); + return isEmpty(s) ? null : s; + } catch { + return null; + } finally { + mk.delete(); + } +} + diff --git a/src/parametric/src/kernel/weldments.ts b/src/parametric/src/kernel/weldments.ts new file mode 100644 index 0000000000..e48fa213dc --- /dev/null +++ b/src/parametric/src/kernel/weldments.ts @@ -0,0 +1,906 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +// Weldment features: structural members swept along sketch segments, with +// corner treatments, trimming and extending, end caps and gussets. +// +// Each member is built as a solid of its own (so members can be trimmed +// against each other and measured), then fused into the part's single body +// like any boss. What the cut list needs (profile, length, end angles, +// volume) is kept per member in the build state, so it does not need +// separate bodies. +// +// A member runs along a line or arc of a sketch. Its frame at a point of the +// path: D along the path, V the sketch plane normal, U = V × D. The placed +// profile (pierce point at the origin) is drawn in (U, V). Each end of a +// member is cut by one or more planes whose normals point out of the member. + +import * as R from 'replicad'; +import type { Frame, Vec3 } from '../math/vec'; +import { add, cross, dist, dot, len, normalize, perpendicular, scale, sub, toWorld } from '../math/vec'; +import type { + EdgeRef, EndCapFeature, FaceRef, GussetFeature, Id, MemberRef, SkEntity, StructuralMemberFeature, TrimExtendFeature, WeldBeadFeature, +} from '../model/types'; +import { + type PSeg, type Placement, type PiercePoint, type ProfileDims, type ProfileShape, PIERCE_POINTS, findProfile, isHollow, outlineMax, + outlinePoints, placeProfile, piercePointOf, placeWith, profileShape, sectionProps, +} from '../model/weldment-profiles'; +import { type WeldMemberInfo, memberKey, memberOfFace, sameMember } from '../model/weldments'; +import { SketchIndex } from '../sketch/geom'; +import { type EdgeDesc, type Sh, type SurfDesc, getOc, pnt, bbox, compound, cut, fuse, fuseAll, isEmpty, isValid, rotated, subShapes, volumeOf } from './occ'; + +export interface Plane { + p: Vec3; + /** Points out of the member. */ + n: Vec3; +} + +export interface MemberEnd { + planes: Plane[]; + /** Solids cut from the end (a coped end follows the member it meets). */ + copes: Sh[]; +} + +export type MemberPath = + | { kind: 'line'; a: Vec3; d: Vec3; len: number; v: Vec3 } + /** Arc from a, turning about axis (through c) by sweep radians. */ + | { kind: 'arc'; c: Vec3; axis: Vec3; r: number; a: Vec3; sweep: number; v: Vec3 }; + +export interface WeldMember { + feature: Id; + key: string; + group: number; + standard: string; + profile: string; + size: string; + desc: string; + dims: ProfileDims; + placement: Placement; + /** The profile as placed on the path (pierce point at the origin). */ + shape: ProfileShape; + area: number; + path: MemberPath; + ends: [MemberEnd, MemberEnd]; + solid: Sh; + info: WeldMemberInfo; +} + +export interface WeldState { + members: WeldMember[]; + /** End caps and gussets: kept so a trim can put back what it took from them. */ + extras: Sh[]; +} + +/** What the weldment features need from the model builder. */ +export interface WeldCtx { + st: { body: Sh | null; weld?: WeldState }; + featureId: Id; + /** A sketch as built (throws the builder's "missing" error). */ + sketch(id: Id): { entities: SkEntity[]; frame: Frame }; + face(ref: FaceRef): { name: string; desc: SurfDesc }; + /** An edge and the faces it separates. */ + edge(ref: EdgeRef): { desc: EdgeDesc; faces: { desc: SurfDesc; shape: Sh }[] }; + /** Names a tool's faces ":". */ + nameTool(prefix: Id, shape: Sh, classify: (k: number) => string): unknown[]; + applyTool(tool: Sh, faces: unknown[], noGain?: string): void; + /** Replaces the body, naming its faces after the previous body and the given faces. */ + setBody(body: Sh, faces: unknown[]): void; + /** The body before a feature was built. */ + bodyBefore(id: Id): Sh | null; + /** Tools of the features after a feature (bosses and cuts built since). */ + toolsAfter(id: Id): { adds: Sh[]; cuts: Sh[] }; + warn(msg: string): void; + err(msg: string): Error; + /** A feature's name in a message. */ + name(id: Id): string; +} + +/** + * Says so when the feature left the body an invalid solid (later features, + * export and mass properties would go wrong on it), instead of reporting OK. + */ +function checkValid(ctx: WeldCtx, message: string) { + const b = ctx.st.body; + if (b && !isValid(b)) ctx.warn(message); +} + +// ---------- small vector helpers ---------- + +function rotateAbout(v: Vec3, axis: Vec3, ang: number): Vec3 { + const c = Math.cos(ang), s = Math.sin(ang); + return add(add(scale(v, c), scale(cross(axis, v), s)), scale(axis, dot(axis, v) * (1 - c))); +} + +/** A finite number from a resolved parameter (a damaged file may hold text). */ +function value(ctx: WeldCtx, v: unknown, label: string): number { + const x = typeof v === 'number' ? v : Number(v); + if (!Number.isFinite(x)) throw ctx.err(`${label} has an invalid value`); + return x; +} + +// ---------- paths ---------- + +function pathEnd(p: MemberPath, e: 0 | 1): Vec3 { + if (p.kind === 'line') return e ? add(p.a, scale(p.d, p.len)) : p.a; + return e ? add(p.c, rotateAbout(sub(p.a, p.c), p.axis, p.sweep)) : p.a; +} + +/** Frame of the path at a parameter (length along a line, angle along an arc). */ +function frameAt(p: MemberPath, t: number): { o: Vec3; D: Vec3; U: Vec3; V: Vec3 } { + if (p.kind === 'line') { + const U = cross(p.v, p.d); + return { o: add(p.a, scale(p.d, t)), D: p.d, U, V: p.v }; + } + const o = add(p.c, rotateAbout(sub(p.a, p.c), p.axis, t)); + const D = normalize(cross(p.axis, sub(o, p.c))); + return { o, D, U: cross(p.v, D), V: p.v }; +} + +const pathLength = (p: MemberPath) => (p.kind === 'line' ? p.len : p.sweep); + +/** End point, outward direction and cross-section axes at an end. */ +function endFrame(p: MemberPath, e: 0 | 1): { P: Vec3; a: Vec3; U: Vec3; V: Vec3 } { + const f = frameAt(p, e ? pathLength(p) : 0); + return { P: f.o, a: e ? f.D : scale(f.D, -1), U: f.U, V: f.V }; +} + +function reversePath(p: MemberPath): MemberPath { + if (p.kind === 'line') return { ...p, a: pathEnd(p, 1), d: scale(p.d, -1) }; + return { ...p, a: pathEnd(p, 1), axis: scale(p.axis, -1) }; +} + +/** Closest point of the path to x: its parameter and distance. */ +function closestOnPath(p: MemberPath, x: Vec3): { t: number; d: number; q: Vec3 } { + if (p.kind === 'line') { + const t = Math.max(0, Math.min(p.len, dot(sub(x, p.a), p.d))); + const q = add(p.a, scale(p.d, t)); + return { t, d: dist(q, x), q }; + } + const rel = sub(x, p.c); + const inPlane = sub(rel, scale(p.axis, dot(rel, p.axis))); + const r0 = sub(p.a, p.c); + let ang = Math.atan2(dot(cross(r0, inPlane), p.axis), dot(r0, inPlane)); + if (ang < 0) ang += 2 * Math.PI; + // Past the end: the nearer end. + if (ang > p.sweep) ang = ang - p.sweep < 2 * Math.PI - ang ? p.sweep : 0; + const q = add(p.c, rotateAbout(r0, p.axis, ang)); + return { t: ang, d: dist(q, x), q }; +} + +/** Linear function of profile coordinates: k + g·(x, y). */ +interface Lin { k: number; g: [number, number] } + +const linMax = (outer: PSeg[], f: Lin) => f.k + outlineMax(outer, f.g); +const linMin = (outer: PSeg[], f: Lin) => f.k - outlineMax(outer, [-f.g[0], -f.g[1]]); + +/** + * Where profile point (x, y) of an end's cross-section meets a plane, as a + * distance along the outward direction from the end point. + */ +function reach(fr: { P: Vec3; a: Vec3; U: Vec3; V: Vec3 }, pl: Plane): Lin { + const an = dot(fr.a, pl.n); + return { k: dot(sub(pl.p, fr.P), pl.n) / an, g: [-dot(fr.U, pl.n) / an, -dot(fr.V, pl.n) / an] }; +} + +/** How far past an end point the member reaches (max over its outline; several planes cut in turn). */ +function endReach(m: { shape: ProfileShape; path: MemberPath }, e: 0 | 1, planes: Plane[]): number { + const fr = endFrame(m.path, e); + const lins = planes.map((pl) => reach(fr, pl)); + if (lins.length === 1) return linMax(m.shape.outer, lins[0]); + let best = -Infinity; + for (const q of outlinePoints(m.shape.outer, 2)) best = Math.max(best, Math.min(...lins.map((l) => l.k + l.g[0] * q[0] + l.g[1] * q[1]))); + return best; +} + +/** Degrees between an end's direction and its first cutting plane's normal (0: square). */ +function endAngle(path: MemberPath, e: 0 | 1, end: MemberEnd): number { + const pl = end.planes[0]; + if (!pl) return 0; + const c = Math.min(1, Math.abs(dot(endFrame(path, e).a, pl.n))); + const deg = (Math.acos(c) * 180) / Math.PI; + return deg < 1e-7 ? 0 : deg; +} + +// ---------- solids ---------- + +function p3(o: Vec3, U: Vec3, V: Vec3, q: [number, number]): Vec3 { + return add(o, add(scale(U, q[0]), scale(V, q[1]))); +} + +function segEdge(s: PSeg, o: Vec3, U: Vec3, V: Vec3, D: Vec3): any { + if (s.k === 'line') return R.makeLine(p3(o, U, V, s.a), p3(o, U, V, s.b)); + const at = (t: number): [number, number] => [s.c[0] + s.r * Math.cos(t), s.c[1] + s.r * Math.sin(t)]; + if (Math.abs(s.a1 - s.a0) >= 2 * Math.PI - 1e-9) return R.makeCircle(s.r, p3(o, U, V, s.c), s.a1 > s.a0 ? D : scale(D, -1)); + return R.makeThreePointArc(p3(o, U, V, at(s.a0)), p3(o, U, V, at((s.a0 + s.a1) / 2)), p3(o, U, V, at(s.a1))); +} + +/** The profile as a face in a cross-section plane (its outline only grown by `grow`, for a cope with a gap). */ +function profileFace(shape: ProfileShape, o: Vec3, U: Vec3, V: Vec3, D: Vec3, outerOnly = false, grow = 0): any { + const wire = (loop: PSeg[]) => R.assembleWire(loop.map((s) => segEdge(s, o, U, V, D))); + let face = R.makeFace(outerOnly && grow > 0 ? wire(shape.outer).offset2D(grow, 'arc') : wire(shape.outer)); + if (!outerOnly && shape.holes.length) face = R.addHolesInFace(face, shape.holes.map(wire)); + return face; +} + +/** A large box on the outer side of a plane, around a point of it. */ +function halfSpaceBox(pl: Plane, near: Vec3, size: number): Sh { + const c = sub(near, scale(pl.n, dot(sub(near, pl.p), pl.n))); + const e1 = perpendicular(pl.n); + const e2 = cross(pl.n, e1); + const corner = (i: number, j: number) => add(c, add(scale(e1, i * size), scale(e2, j * size))); + const pts = [corner(-1, -1), corner(1, -1), corner(1, 1), corner(-1, 1)]; + const face = R.makeFace(R.assembleWire(pts.map((p, i) => R.makeLine(p, pts[(i + 1) % 4])))); + return R.basicFaceExtrusion(face, new R.Vector(scale(pl.n, size * 2))) as unknown as Sh; +} + +/** Largest distance of the profile from its pierce point. */ +function profileRadius(shape: ProfileShape): number { + let r = 0; + for (const q of outlinePoints(shape.outer, 10)) r = Math.max(r, Math.hypot(q[0], q[1])); + return r; +} + +/** + * An end cut square by one plane: a straight member is swept exactly to it. + * An arc member's sweep ends on a plane through its end point only (past the + * end, a sweep's end face turns about the arc's axis). + */ +const isSquare = (fr: { P: Vec3; a: Vec3 }, end: MemberEnd, tol: number, line: boolean) => + end.planes.length === 1 && !end.copes.length && dot(fr.a, end.planes[0].n) > 1 - 1e-12 && (line || Math.abs(dot(sub(end.planes[0].p, fr.P), end.planes[0].n)) < tol); + +/** The member's solid: the profile swept along its path past both ends, cut by its end planes. */ +function memberSolid(ctx: WeldCtx, m: Pick, outerOnly = false, grow = 0): Sh { + const { path, shape } = m; + const size = profileRadius(shape); + const margin = 1 + size * 0.05; + const cuts: Plane[] = []; + let solid: Sh; + // Distance each end reaches past its end point; square ends are swept exactly. + const ext = ([0, 1] as const).map((e) => { + const fr = endFrame(path, e); + const end = m.ends[e]; + for (const pl of end.planes) { + if (dot(fr.a, pl.n) < 1e-6) throw ctx.err(`An end of a member is cut along its length. Check the trim faces and corner treatment.`); + } + if (isSquare(fr, end, 1e-9 * (1 + len(fr.P)), path.kind === 'line')) return dot(sub(end.planes[0].p, fr.P), fr.a); + cuts.push(...end.planes); + let far = -Infinity; + for (const pl of end.planes) far = Math.max(far, linMax(shape.outer, reach(fr, pl))); + if (end.copes.length) far = Math.max(far, size * 2); + return far + margin; + }); + if (path.kind === 'line') { + const t0 = -ext[0], t1 = path.len + ext[1]; + if (t1 - t0 < 1e-6) throw ctx.err(`A member has no length left after trimming`); + const f = frameAt(path, t0); + const face = profileFace(shape, f.o, f.U, f.V, f.D, outerOnly, grow); + solid = R.basicFaceExtrusion(face, new R.Vector(scale(path.d, t1 - t0))) as unknown as Sh; + } else { + // Radii of the profile about the arc's axis: it must stay clear of the axis. + const f0 = frameAt(path, 0); + const radial = normalize(sub(f0.o, path.c)); + const s = dot(f0.U, radial); + const inner = path.r - outlineMax(shape.outer, [-s, 0]); + if (inner <= 1e-6 * path.r) throw ctx.err(`The profile does not fit inside the arc: make the arc radius larger than the profile`); + const room = 2 * Math.PI - path.sweep; + let d0 = Math.max(0, ext[0]) / inner, d1 = Math.max(0, ext[1]) / inner; + if (ext[0] < 0) d0 = ext[0] / path.r; + if (ext[1] < 0) d1 = ext[1] / path.r; + if (d0 + d1 > room - 1e-3) { + const k = Math.max(0, room - 1e-3) / (d0 + d1); + if (d0 > 0) d0 *= k; + if (d1 > 0) d1 *= k; + } + const total = path.sweep + d0 + d1; + if (total <= 1e-6) throw ctx.err(`A member has no length left after trimming`); + const f = frameAt(path, -d0); + const face = profileFace(shape, f.o, f.U, f.V, f.D, outerOnly, grow); + solid = R.revolution(face, path.c, path.axis, (total * 180) / Math.PI) as unknown as Sh; + } + const mid = frameAt(path, pathLength(path) / 2).o; + const big = (size + Math.max(...ext.map(Math.abs)) + (path.kind === 'line' ? path.len : path.r * 2)) * 2 + 10; + for (const pl of cuts) solid = cut(solid, halfSpaceBox(pl, mid, big)); + for (const e of [0, 1] as const) for (const c of m.ends[e].copes) solid = cut(solid, c); + if (isEmpty(solid)) throw ctx.err(`A member has no length left after trimming`); + if (m.ends.some((e) => e.copes.length)) { + // A cope to an open section (a beam, channel or angle) leaves the piece + // that ran on past the flange, between the flanges: only the member's + // own piece is kept, the one at its other end (or nearest its middle + // when both ends are coped). + const parts = subShapes(solid, 'solid'); + if (parts.length > 1) { + const at = !m.ends[0].copes.length ? pathEnd(path, 0) : !m.ends[1].copes.length ? pathEnd(path, 1) : mid; + let best = parts[0], bd = Infinity; + for (const p of parts) { const d = pointDistance(p, at); if (d < bd) { bd = d; best = p; } } + solid = best; + } + } + return solid; +} + +/** Overall length of a member along its axis (long point to long point). */ +function memberLength(m: Pick): number { + const coped = m.ends.some((e) => e.copes.length); + if (m.path.kind === 'line') { + if (coped) { + // The cope's surface decides: measure the solid along the member. + const z: Vec3 = [0, 0, 1]; + const d = m.path.d; + const ax = cross(d, z); + const s = len(ax); + const turned = s < 1e-12 ? (dot(d, z) > 0 ? m.solid : rotated(m.solid, [0, 0, 0], [1, 0, 0], Math.PI)) : rotated(m.solid, [0, 0, 0], scale(ax, 1 / s), Math.atan2(s, dot(d, z))); + const b = bbox(turned); + return b ? b.max[2] - b.min[2] : 0; + } + return m.path.len + endReach(m, 0, m.ends[0].planes) + endReach(m, 1, m.ends[1].planes); + } + // An arc member: along the path of its centroid. + const path = m.path; + const c = sectionProps(m.shape).centroid; + const f0 = frameAt(path, 0); + const radial = normalize(sub(f0.o, path.c)); + const rc = Math.abs(path.r + c[0] * dot(f0.U, radial)); + let s = rc * path.sweep; + for (const e of [0, 1] as const) { + const fr = endFrame(path, e); + const pl = m.ends[e].planes; + if (pl.length) s += Math.min(...pl.map((p) => { const l = reach(fr, p); return l.k + l.g[0] * c[0] + l.g[1] * c[1]; })) * (rc / path.r); + } + return s; +} + +function memberInfo(m: Omit): WeldMemberInfo { + return { + feature: m.feature, member: m.key, group: m.group, standard: m.standard, profile: m.profile, size: m.size, desc: m.desc, + length: memberLength(m), angle1: endAngle(m.path, 0, m.ends[0]), angle2: endAngle(m.path, 1, m.ends[1]), + volume: volumeOf(m.solid), area: m.area, ...(m.path.kind === 'arc' ? { curved: true, radius: m.path.r } : {}), + }; +} + +function finishMember(ctx: WeldCtx, m: Omit): WeldMember { + const solid = memberSolid(ctx, m); + const full = { ...m, solid }; + return { ...full, info: memberInfo(full) }; +} + +// ---------- joints ---------- + +/** Cross-section frame of a member at the point of its path nearest x. */ +function sectionAt(m: { path: MemberPath }, x: Vec3) { + const c = closestOnPath(m.path, x); + const f = frameAt(m.path, c.t); + return { ...f, P: c.q, dist: c.d, t: c.t }; +} + +/** + * Members turning less than this (degrees) at a corner, or from a member of + * an earlier group, run in line: butted, the trimmed member would be cut along its length to the + * other's side face, and the one running through would reach far past the + * corner (a 40 mm tube turning 0.1 degrees reached 23 m). + */ +const IN_LINE_COS = Math.cos((5 * Math.PI) / 180); + +/** + * The plane a member ending at P (outward direction a) is trimmed to where it + * meets member S: the face of S toward it, set back by the gap. Null when + * the two run in line. + */ +function trimPlane(S: { shape: ProfileShape; path: MemberPath }, P: Vec3, a: Vec3, gap: number): Plane | null { + const s = sectionAt(S, P); + const perp = sub(a, scale(s.D, dot(a, s.D))); + if (len(perp) < 1e-6) return null; + const w = normalize(perp); + const near = linMin(S.shape.outer, { k: 0, g: [dot(s.U, w), dot(s.V, w)] }); + return { p: add(s.P, scale(w, near - gap)), n: w }; +} + +/** How far a member running through a joint must reach past P to cover the end of the member trimmed to it. */ +function throughReach(T: { shape: ProfileShape; path: MemberPath }, te: 0 | 1, tPlane: Plane, P: Vec3, b: Vec3): number { + const fr = endFrame(T.path, te); + const a = fr.a, w = tPlane.n; + const aw = dot(a, w); + if (Math.abs(aw) < 1e-9) return 0; + const k = dot(a, b) / aw; + const base = dot(sub(fr.P, P), b) + dot(sub(tPlane.p, fr.P), w) * k; + const g: [number, number] = [dot(fr.U, b) - dot(fr.U, w) * k, dot(fr.V, b) - dot(fr.V, w) * k]; + return base + outlineMax(T.shape.outer, g); +} + +// ---------- structural member ---------- + +interface Draft { + key: string; + group: number; + path: MemberPath; + ends: [MemberEnd, MemberEnd]; + /** Ends joined to another member (they are not cut square). */ + joined: [boolean, boolean]; + /** Free ends reaching past their end point to cover a member trimmed to them. */ + extend: [number, number]; +} + +/** The angle (radians) within which the kernel merges faces as one (its simplify tolerance). */ +const NEARLY_STRAIGHT = 1e-3; + +/** Moves an end of a line member's path to q. */ +function moveLineEnd(d: Draft, e: 0 | 1, q: Vec3) { + if (d.path.kind !== 'line') return; + const other = pathEnd(d.path, e ? 0 : 1); + const [a, b] = e ? [other, q] : [q, other]; + const l = dist(a, b); + d.path = { ...d.path, a, d: scale(sub(b, a), 1 / l), len: l }; +} + +const SEGMENT_KINDS: Record = { circle: 'circles', spline: 'splines', point: 'points' }; + +export function applyStructuralMember(ctx: WeldCtx, f: StructuralMemberFeature): void { + const prof = findProfile(f.standard, f.profile, f.size); + if (!prof) throw ctx.err('Select a profile standard, type and size from the library'); + const pierce: PiercePoint = PIERCE_POINTS.some((p) => p.value === f.pierce) ? (f.pierce as PiercePoint) : 'centroid'; + const placement: Placement = { pierce, rotation: value(ctx, f.rotation, 'Rotation angle'), mirror: !!f.mirror }; + const raw = profileShape(f.profile, prof.dims); + const shape = placeProfile(raw, placement); + const area = sectionProps(raw).area; + const gap = value(ctx, f.gap, 'Gap'); + const gap2 = f.trimGroups ? value(ctx, f.gap2, 'Gap between groups') : 0; + if (gap < 0 || gap2 < 0) throw ctx.err('The gap cannot be negative'); + const segs = f.groups.flatMap((g, gi) => g.segments.map((s) => ({ s, gi }))); + if (!segs.length) throw ctx.err('Select sketch lines or arcs for the members'); + + // Paths of the segments, in world coordinates. + const drafts: Draft[] = []; + const seen = new Set(); + const ixs = new Map(); + // "Line 3 of Sketch1", numbered as the panel lists them, for a message about one member. + const labels = new Map(); + let size = 1; + for (const { s, gi } of segs) { + const key = memberKey(s); + if (seen.has(key)) throw ctx.err('A sketch segment is selected twice. Each segment makes one member.'); + seen.add(key); + let sk = ixs.get(s.sketch); + if (!sk) { + const got = ctx.sketch(s.sketch); + sk = { ix: new SketchIndex(got.entities), frame: got.frame, entities: got.entities }; + ixs.set(s.sketch, sk); + } + const e = sk.ix.get(s.entity); + if (!e) throw ctx.err(`A selected segment is no longer in ${ctx.name(s.sketch)}. Edit the feature and select the segments again.`); + if (e.t !== 'line' && e.t !== 'arc') throw ctx.err(`Members run along lines and arcs; ${SEGMENT_KINDS[e.t] ?? 'these curves'} cannot be member paths`); + labels.set(key, `${e.t === 'arc' ? 'Arc' : 'Line'} ${sk.entities.filter((x) => x.t === e.t).indexOf(e) + 1} of ${ctx.name(s.sketch)}`); + const fr = sk.frame; + const w = (id: Id) => toWorld(fr, sk!.ix.pt(id)); + let path: MemberPath; + if (e.t === 'line') { + const a = w(e.a), b = w(e.b); + const l = dist(a, b); + if (l < 1e-9) throw ctx.err(`A selected line in ${ctx.name(s.sketch)} has no length`); + path = { kind: 'line', a, d: scale(sub(b, a), 1 / l), len: l, v: fr.n }; + } else { + const c2 = sk.ix.pt(e.c), a2 = sk.ix.pt(e.a), b2 = sk.ix.pt(e.b); + const r = Math.hypot(a2[0] - c2[0], a2[1] - c2[1]); + let sweep = Math.atan2(b2[1] - c2[1], b2[0] - c2[0]) - Math.atan2(a2[1] - c2[1], a2[0] - c2[0]); + while (sweep <= 1e-12) sweep += 2 * Math.PI; + if (r < 1e-9) throw ctx.err(`A selected arc in ${ctx.name(s.sketch)} has no radius`); + path = { kind: 'arc', c: w(e.c), axis: fr.n, r, a: w(e.a), sweep, v: fr.n }; + } + for (const q of [pathEnd(path, 0), pathEnd(path, 1)]) size = Math.max(size, ...q.map(Math.abs)); + const free = (): MemberEnd => ({ planes: [], copes: [] }); + drafts.push({ key, group: gi, path, ends: [free(), free()], joined: [false, false], extend: [0, 0] }); + } + const tol = 1e-6 * size * 10; + const same = (p: Vec3, q: Vec3) => dist(p, q) < tol; + const shaped = (d: Draft) => ({ shape, path: d.path }); + + // Two lines meeting at a point less than NEARLY_STRAIGHT radians off + // straight have side faces the kernel takes for one plane (it merges faces + // that close), which left an invalid body: their meeting point is moved + // onto the line between their far ends, so they run exactly in line. + for (const A of drafts) { + for (const ea of [0, 1] as const) { + if (A.path.kind !== 'line') continue; + const P = pathEnd(A.path, ea); + const at = drafts.flatMap((d) => ([0, 1] as const).flatMap((e) => (d !== A && same(pathEnd(d.path, e), P) ? [{ d, e }] : []))); + if (at.length !== 1 || at[0].d.path.kind !== 'line') continue; + const B = at[0].d, eb = at[0].e; + const FA = pathEnd(A.path, ea ? 0 : 1), FB = pathEnd(B.path, eb ? 0 : 1); + const c = dot(normalize(sub(P, FA)), normalize(sub(FB, P))); + if (c >= 1 - 1e-15 || c < Math.cos(NEARLY_STRAIGHT)) continue; + const ab = sub(FB, FA); + const q = add(FA, scale(ab, dot(sub(P, FA), ab) / dot(ab, ab))); + moveLineEnd(A, ea, q); + moveLineEnd(B, eb, q); + } + } + + // Orient each group's chains so members follow each other. + const groups = f.groups.map((_, gi) => drafts.filter((d) => d.group === gi)); + for (const g of groups) { + const done = new Set(); + for (const first of g) { + if (done.has(first)) continue; + done.add(first); + const queue = [first]; + while (queue.length) { + const cur = queue.shift()!; + const a = pathEnd(cur.path, 0), b = pathEnd(cur.path, 1); + for (const o of g) { + if (done.has(o)) continue; + const oa = pathEnd(o.path, 0), ob = pathEnd(o.path, 1); + let rev: boolean | null = null; + if (same(oa, b) || same(ob, a)) rev = false; + else if (same(ob, b) || same(oa, a)) rev = true; + if (rev === null) continue; + if (rev) o.path = reversePath(o.path); + done.add(o); + queue.push(o); + } + } + } + } + + // Corners within groups. + for (const g of groups) { + const ends = g.flatMap((d) => ([0, 1] as const).map((e) => ({ d, e, p: pathEnd(d.path, e) }))); + const used = new Set(); + for (let i = 0; i < ends.length; i++) { + if (used.has(i)) continue; + const at = ends.flatMap((x, j) => (j !== i && !used.has(j) && x.d !== ends[i].d && same(x.p, ends[i].p) ? [j] : [])); + if (!at.length) continue; + if (at.length > 1) throw ctx.err('Three or more members of a group meet at one point. Put the extra members in another group.'); + used.add(i); used.add(at[0]); + let A = ends[i], B = ends[at[0]]; + // A arrives at the corner (its end), B leaves it (its start). + if (A.e === 0 && B.e === 1) [A, B] = [B, A]; + const fa = endFrame(A.d.path, A.e), fb = endFrame(B.d.path, B.e); + const P = fa.P; + A.d.joined[A.e] = true; + B.d.joined[B.e] = true; + if (f.corner === 'miter') { + const mv = sub(fa.a, fb.a); + if (len(mv) < 1e-9) throw ctx.err('Two members of a group fold back on each other at a corner'); + const m = normalize(mv); + A.d.ends[A.e].planes.push({ p: sub(P, scale(m, gap / 2)), n: m }); + B.d.ends[B.e].planes.push({ p: add(P, scale(m, gap / 2)), n: scale(m, -1) }); + continue; + } + // End butt 1: the arriving member runs through and the next one is trimmed to it; butt 2 the other way. + const [S, se, T, te] = f.corner === 'butt1' ? [A, A.e, B, B.e] : [B, B.e, A, A.e]; + const fs = endFrame(S.d.path, se), ft = endFrame(T.d.path, te); + // The two ends point (nearly) opposite ways where the members run on in line. + const tp = dot(fa.a, fb.a) < -IN_LINE_COS ? null : trimPlane(shaped(S.d), P, ft.a, gap); + if (!tp) { + // Members (nearly) in line: they meet on the plane halfway between them (square when exactly in line). + const m = normalize(sub(fa.a, fb.a)); + A.d.ends[A.e].planes.push({ p: sub(P, scale(m, gap / 2)), n: m }); + B.d.ends[B.e].planes.push({ p: add(P, scale(m, gap / 2)), n: scale(m, -1) }); + continue; + } + T.d.ends[te].planes.push(tp); + const ext = throughReach(shaped(T.d), te, tp, P, fs.a); + S.d.ends[se].planes.push({ p: add(P, scale(fs.a, ext)), n: fs.a }); + } + } + + // Members of later groups trimmed or extended to members of earlier groups. + if (f.trimGroups) { + for (let gi = 1; gi < groups.length; gi++) { + for (const T of groups[gi]) { + for (const te of [0, 1] as const) { + if (T.joined[te]) continue; + const ft = endFrame(T.path, te); + for (const S of groups.slice(0, gi).flat()) { + const s = closestOnPath(S.path, ft.P); + if (s.d > tol) continue; + // Running on (nearly) in line from a free end of S: they meet on the plane halfway between them. + const se = ([0, 1] as const).find((e) => !S.joined[e] && same(pathEnd(S.path, e), ft.P) && dot(endFrame(S.path, e).a, ft.a) < -IN_LINE_COS); + if (se !== undefined) { + const m = normalize(sub(ft.a, endFrame(S.path, se).a)); + T.ends[te].planes.push({ p: sub(ft.P, scale(m, gap2 / 2)), n: m }); + S.ends[se].planes.push({ p: add(ft.P, scale(m, gap2 / 2)), n: scale(m, -1) }); + S.joined[se] = true; + continue; + } + const tp = trimPlane(shaped(S), ft.P, ft.a, gap2); + if (!tp) continue; + T.ends[te].planes.push(tp); + // A free end of S at the joint reaches out to cover T. + for (const se of [0, 1] as const) { + if (S.joined[se] || !same(pathEnd(S.path, se), ft.P)) continue; + const fs = endFrame(S.path, se); + S.extend[se] = Math.max(S.extend[se], throughReach(shaped(T), te, tp, fs.P, fs.a)); + } + } + if (T.ends[te].planes.length) T.joined[te] = true; + } + } + } + } + + // Free ends are cut square at their end points. + for (const d of drafts) { + for (const e of [0, 1] as const) { + if (d.ends[e].planes.length) continue; + const fr = endFrame(d.path, e); + d.ends[e].planes.push({ p: add(fr.P, scale(fr.a, d.extend[e])), n: fr.a }); + } + } + + const featureError = ctx.err('').constructor; + const members = drafts.map((d) => { + try { + return finishMember(ctx, { + feature: f.id, key: d.key, group: d.group, standard: f.standard, profile: f.profile, size: f.size, desc: prof.desc, + dims: prof.dims, placement, shape, area, path: d.path, ends: d.ends, + }); + } catch (e) { + // Which of many members it is. + if (e instanceof featureError && labels.has(d.key)) throw ctx.err(`${labels.get(d.key)}: ${(e as Error).message}`); + throw e; + } + }); + const named = members.flatMap((m) => ctx.nameTool(f.id, m.solid, (k) => `${m.key}:${k}`)); + const tool = members.length === 1 ? members[0].solid : fuseAll(members.map((m) => m.solid)); + ctx.applyTool(tool, named, 'The members add no material: they lie inside the part.'); + checkValid(ctx, 'The result is not a valid solid where the members meet. Try another corner treatment or a small gap.'); + const prev = ctx.st.weld; + ctx.st.weld = { members: [...(prev?.members ?? []), ...members], extras: prev?.extras ?? [] }; +} + +// ---------- trim / extend ---------- + +function findMember(ctx: WeldCtx, ref: MemberRef, what: string): WeldMember { + const m = ctx.st.weld?.members.find((x) => sameMember({ feature: x.feature, member: x.key }, ref)); + if (!m) throw ctx.err(`A ${what} no longer exists. Edit the feature and select it again.`); + return m; +} + +/** + * Puts a changed member into the body: what the old one alone added is + * removed, and what the new one reaches past the old one is fused. Features + * built since the member keep their effect: a boss there keeps its material, + * and a hole cut through the member stays open. + */ +function replaceMember(ctx: WeldCtx, old: WeldMember, next: WeldMember, others: Sh[]): Sh { + let body = ctx.st.body; + if (!body) throw ctx.err('There is no body'); + const since = ctx.toolsAfter(old.feature); + // The part of the old member the new one leaves out, less what other features own there. + let removed = cut(old.solid, next.solid); + if (!isEmpty(removed)) { + const keep = [ctx.bodyBefore(old.feature), ...others, ...since.adds].filter((s): s is Sh => !!s && !isEmpty(s)); + if (keep.length) removed = cut(removed, keep.length === 1 ? keep[0] : compound(keep)); + if (!isEmpty(removed) && volumeOf(removed) > 1e-9) body = cut(body, removed); + } + let added = cut(next.solid, old.solid); + if (!isEmpty(added) && since.cuts.length) added = cut(added, since.cuts.length === 1 ? since.cuts[0] : compound(since.cuts)); + return isEmpty(added) || volumeOf(added) <= 1e-9 ? body : fuse(body, added); +} + +export function applyTrimExtend(ctx: WeldCtx, f: TrimExtendFeature): void { + if (!ctx.st.weld?.members.length) throw ctx.err('There are no structural members to trim. Add a Structural Member first.'); + if (!f.members.length) throw ctx.err('Select the members to trim or extend'); + const targets = f.members.map((r) => findMember(ctx, r, 'member to trim')); + const gap = value(ctx, f.gap, 'Gap'); + if (gap < 0) throw ctx.err('The gap cannot be negative'); + const planes: Plane[] = []; + const bounds: WeldMember[] = []; + if (f.boundary === 'faces') { + if (!f.faces.length) throw ctx.err('Select the faces to trim to'); + for (const r of f.faces) { + const fc = ctx.face(r); + if (fc.desc.type !== 'plane') throw ctx.err('Members can be trimmed to planar faces only'); + planes.push({ p: fc.desc.p, n: fc.desc.d }); + } + } else { + if (!f.boundaryMembers.length) throw ctx.err('Select the members to trim to'); + for (const r of f.boundaryMembers) bounds.push(findMember(ctx, r, 'boundary member')); + } + let weld = ctx.st.weld; + const faces: unknown[] = []; + let short = 0; + for (const target of targets) { + const m = weld.members.find((x) => x.feature === target.feature && x.key === target.key)!; + if (bounds.includes(m) || bounds.some((b) => b.feature === m.feature && b.key === m.key)) throw ctx.err('A member cannot be trimmed to itself'); + // The end nearer the boundary is the one trimmed. + const dists = ([0, 1] as const).map((e) => { + const P = pathEnd(m.path, e); + const ds = [...planes.map((pl) => Math.abs(dot(sub(P, pl.p), pl.n))), ...bounds.map((b) => closestOnPath(b.path, P).d)]; + return Math.min(...ds); + }); + const e: 0 | 1 = dists[1] < dists[0] ? 1 : 0; + const fr = endFrame(m.path, e); + const mid = frameAt(m.path, pathLength(m.path) / 2).o; + const end: MemberEnd = { planes: [], copes: [] }; + if (planes.length) { + // The nearest face's plane, facing away from the member. + let best = planes[0], bd = Infinity; + for (const pl of planes) { const d = Math.abs(dot(sub(fr.P, pl.p), pl.n)); if (d < bd) { bd = d; best = pl; } } + const n = dot(sub(mid, best.p), best.n) > 0 ? scale(best.n, -1) : best.n; + if (Math.abs(dot(fr.a, n)) < 1e-3) throw ctx.err('A member runs along the face it is trimmed to'); + end.planes.push({ p: sub(best.p, scale(n, gap)), n }); + } else { + let best = bounds[0], bd = Infinity; + for (const b of bounds) { const d = closestOnPath(b.path, fr.P).d; if (d < bd) { bd = d; best = b; } } + const tp = trimPlane(best, fr.P, fr.a, gap); + if (!tp) throw ctx.err('A member runs along the member it is trimmed to'); + if (f.coped) { + // To the boundary's axis, then the boundary's outline (grown by the gap) is cut away. + const s = sectionAt(best, fr.P); + end.planes.push({ p: sub(s.P, scale(tp.n, gap)), n: tp.n }); + const env = memberSolid(ctx, best, true, gap); + end.copes.push(env); + } else end.planes.push(tp); + } + // Whether the new end lies past the old one (an extension), measured on the path. + const axis = (pl: Plane) => dot(sub(pl.p, fr.P), pl.n) / dot(fr.a, pl.n); + const was = Math.min(...m.ends[e].planes.map(axis)); + const now = Math.min(...end.planes.map(axis)); + if (now > was + 1e-6 * (1 + len(fr.P)) && !f.allowExtension) { short++; continue; } + const ends: [MemberEnd, MemberEnd] = e ? [m.ends[0], end] : [end, m.ends[1]]; + const next = finishMember(ctx, { ...m, ends }); + const others = [...weld.members.filter((x) => x !== m).map((x) => x.solid), ...weld.extras]; + ctx.st.body = replaceMember(ctx, m, next, others); + faces.push(...ctx.nameTool(m.feature, next.solid, (k) => `${m.key}:${k}`)); + weld = { ...weld, members: weld.members.map((x) => (x === m ? next : x)) }; + } + if (short) ctx.warn(short === 1 ? 'A member does not reach the boundary. Turn on Allow extension to extend it.' : `${short} members do not reach the boundary. Turn on Allow extension to extend them.`); + ctx.setBody(ctx.st.body!, faces); + // A flat end trimmed to a round member touches it along a line only. + const round = (b: WeldMember) => b.path.kind === 'arc' || b.profile === 'pipe' || b.profile === 'roundBar'; + checkValid(ctx, bounds.length && !f.coped && bounds.some(round) + ? 'The result is not a valid solid: the trimmed end touches the boundary member along a line. Turn on Coped cut.' + : 'The result is not a valid solid where the trimmed members meet the boundary. Try Coped cut or a small gap.'); + ctx.st.weld = weld; +} + +// ---------- end cap ---------- + +/** The member an end face belongs to and which end it is. */ +function memberEndOfFace(ctx: WeldCtx, ref: FaceRef): { m: WeldMember; e: 0 | 1; desc: SurfDesc } { + const fc = ctx.face(ref); + const id = memberOfFace(fc.name); + const m = id ? ctx.st.weld?.members.find((x) => x.feature === id.feature && x.key === id.member) : undefined; + if (!m || fc.desc.type !== 'plane') throw ctx.err('Select the flat end face of a structural member'); + const ds = ([0, 1] as const).map((e) => { + const fr = endFrame(m.path, e); + return Math.abs(Math.abs(dot(fc.desc.d, fr.a)) - 1) < 1e-6 ? Math.abs(dot(sub(fc.desc.center, fr.P), fr.a)) + dist(fc.desc.center, fr.P) * 1e-3 : Infinity; + }); + if (!Number.isFinite(Math.min(...ds))) throw ctx.err('End caps go on square-cut member ends. Select an end face square to the member.'); + return { m, e: ds[1] < ds[0] ? 1 : 0, desc: fc.desc }; +} + +export function applyEndCap(ctx: WeldCtx, f: EndCapFeature): void { + if (!f.faces.length) throw ctx.err('Select the end faces of tube or pipe members'); + const t = value(ctx, f.thickness, 'Thickness'); + const off = value(ctx, f.offset, 'Offset'); + if (!(t > 0)) throw ctx.err('Thickness must be greater than zero'); + if (off < 0) throw ctx.err('The offset cannot be negative'); + const solids: Sh[] = []; + const named: unknown[] = []; + f.faces.forEach((ref, i) => { + const { m, e } = memberEndOfFace(ctx, ref); + if (!isHollow(m.profile)) throw ctx.err('End caps go on tube and pipe members'); + const fr = endFrame(m.path, e); + if (m.ends[e].planes.length !== 1 || m.ends[e].copes.length || dot(fr.a, m.ends[e].planes[0].n) < 1 - 1e-9) { + throw ctx.err('End caps go on square-cut member ends. Select an end face square to the member.'); + } + const d = m.dims, wall = d.t ?? 0; + const inset = off + (f.inward ? wall : 0); + let cap: ProfileShape; + if (m.profile === 'pipe') { + const r = (d.D ?? 0) / 2 - inset; + if (r <= 1e-6) throw ctx.err('The offset is too large for this profile'); + cap = { outer: [{ k: 'arc', c: [0, 0], r, a0: 0, a1: 2 * Math.PI }], holes: [] }; + } else { + const B = (d.B ?? 0) - 2 * inset, H = (d.H ?? 0) - 2 * inset; + if (B <= 1e-6 || H <= 1e-6) throw ctx.err('The offset is too large for this profile'); + const rr = Math.max(0, (f.inward ? d.ri ?? 0 : d.ro ?? 0) - off); + cap = profileShape('squareTube', { B, H, t: Math.min(B, H) / 4, ro: rr, ri: 0 }); + cap = { outer: cap.outer, holes: [] }; + } + // Placed on the member like its profile (the same pierce point, turn and mirror). + const full = profileShape(m.profile, m.dims); + const placed = placeWith(cap, piercePointOf(full, m.placement.pierce), m.placement); + // The end face lies where the end plane crosses the path. + const pl = m.ends[e].planes[0]; + const o = add(fr.P, scale(fr.a, dot(sub(pl.p, fr.P), pl.n))); + const start = f.inward ? sub(o, scale(fr.a, t)) : o; + const face = profileFace(placed, start, fr.U, fr.V, fr.a); + const solid = R.basicFaceExtrusion(face, new R.Vector(scale(fr.a, t))) as unknown as Sh; + if (f.inward && memberLength(m) <= t) throw ctx.err('The member is shorter than the cap is thick'); + solids.push(solid); + named.push(...ctx.nameTool(f.id, solid, (k) => `cap${i}:${k}`)); + }); + const tool = solids.length === 1 ? solids[0] : fuseAll(solids); + ctx.applyTool(tool, named, f.inward ? 'The end caps add no material: the tube is already closed there.' : undefined); + checkValid(ctx, 'The result is not a valid solid where the end caps meet the part. Try another offset or thickness.'); + const prev = ctx.st.weld; + ctx.st.weld = { members: prev?.members ?? [], extras: [...(prev?.extras ?? []), ...solids] }; +} + +// ---------- gusset ---------- + +export function applyGusset(ctx: WeldCtx, f: GussetFeature): void { + if (f.faces.length !== 2) throw ctx.err('Select two planar faces that meet at a corner'); + const [f1, f2] = f.faces.map((r) => ctx.face(r)); + if (f1.desc.type !== 'plane' || f2.desc.type !== 'plane') throw ctx.err('Select two planar faces that meet at a corner'); + const n1 = f1.desc.d, n2 = f2.desc.d; + const L0 = cross(n1, n2); + if (len(L0) < 0.02) throw ctx.err('The faces are parallel. Select two faces that meet at a corner.'); + const L = normalize(L0); + const d1 = value(ctx, f.d1, 'Distance 1'), d2 = value(ctx, f.d2, 'Distance 2'), t = value(ctx, f.thickness, 'Thickness'); + const ch = value(ctx, f.chamfer, 'Chamfer distance'); + const d3 = f.shape === 'polygonal' ? value(ctx, f.d3, 'Distance 3') : 0; + if (!(d1 > 0) || !(d2 > 0)) throw ctx.err('The gusset distances must be greater than zero'); + if (!(t > 0)) throw ctx.err('Thickness must be greater than zero'); + if (ch < 0 || ch >= Math.min(d1, d2)) throw ctx.err('The chamfer must be shorter than the gusset sides'); + if (f.shape === 'polygonal' && (!(d3 > 0) || d3 >= d1 || d3 >= d2)) throw ctx.err('Distance 3 must be greater than zero and shorter than distances 1 and 2'); + // The corner: where the two face planes meet, midway between the faces along that line. + const k1 = dot(n1, f1.desc.p), k2 = dot(n2, f2.desc.p), k3 = dot(L, scale(add(f1.desc.center, f2.desc.center), 0.5)); + const det = dot(n1, cross(n2, L)); + const C = scale(add(add(scale(cross(n2, L), k1), scale(cross(L, n1), k2)), scale(cross(n1, n2), k3)), 1 / det); + // Legs along each face, toward the other face's side. + const e1 = normalize(sub(n2, scale(n1, dot(n1, n2)))); + const e2 = normalize(sub(n1, scale(n2, dot(n1, n2)))); + const at = (s1: number, s2: number) => add(C, add(scale(e1, s1), scale(e2, s2))); + const pts: Vec3[] = ch > 0 ? [at(ch, 0), at(d1, 0)] : [at(0, 0), at(d1, 0)]; + if (f.shape === 'polygonal') pts.push(at(d1, d3), at(d3, d2)); + pts.push(at(0, d2)); + if (ch > 0) pts.push(at(0, ch)); + const off = f.location === 'center' ? -t / 2 : f.location === 'side1' ? 0 : -t; + const moved = pts.map((p) => add(p, scale(L, off))); + const face = R.makeFace(R.assembleWire(moved.map((p, i) => R.makeLine(p, moved[(i + 1) % moved.length])))); + const solid = R.basicFaceExtrusion(face, new R.Vector(scale(L, t))) as unknown as Sh; + ctx.applyTool(solid, ctx.nameTool(f.id, solid, (k) => `g${k}`), 'The gusset adds no material: it lies inside the part.'); + checkValid(ctx, 'The result is not a valid solid where the gusset meets the part. Try other distances, a chamfer or another location.'); + const prev = ctx.st.weld; + ctx.st.weld = { members: prev?.members ?? [], extras: [...(prev?.extras ?? []), solid] }; +} + +// ---------- fillet weld bead ---------- + +/** Distance from a point to a shape. */ +function pointDistance(shape: Sh, p: Vec3): number { + const oc = getOc(); + const gp = pnt(p); + const mv = new oc.BRepBuilderAPI_MakeVertex(gp); + const ext = new oc.BRepExtrema_DistShapeShape(); + const progress = new oc.Message_ProgressRange(); + try { + ext.LoadS1(mv.Vertex()); + ext.LoadS2(shape.wrapped); + ext.Perform(progress); + return ext.IsDone() && ext.NbSolution() > 0 ? ext.Value() : Infinity; + } finally { + ext.delete(); progress.delete(); mv.delete(); gp.delete(); + } +} + +export function applyWeldBead(ctx: WeldCtx, f: WeldBeadFeature): void { + if (!f.edges.length) throw ctx.err('Select the inside corner edges to weld'); + const s = value(ctx, f.size, 'Bead size'); + if (!(s > 0)) throw ctx.err('The bead size must be greater than zero'); + const solids: Sh[] = []; + for (const ref of f.edges) { + const e = ctx.edge(ref); + if (e.desc.type !== 'line') throw ctx.err('Fillet beads follow straight edges'); + if (e.faces.length !== 2 || e.faces.some((x) => x.desc.type !== 'plane')) throw ctx.err('Fillet beads go along edges between two flat faces'); + const [f1, f2] = e.faces.map((x) => x.desc); + const n1 = f1.d, n2 = f2.d, c = dot(n1, n2); + if (Math.abs(c) > 0.999) throw ctx.err('The faces at the edge are in line: there is no corner to weld'); + // The legs run along each face, away from the edge. + const e1 = normalize(sub(n2, scale(n1, c))), e2 = normalize(sub(n1, scale(n2, c))); + const E = e.desc.a; + // At an inside corner each face goes on along its leg from the edge. + const eps = Math.min(s, e.desc.length) * 0.02; + const on = (k: 0 | 1, dir: Vec3) => pointDistance(e.faces[k].shape, add(e.desc.mid, scale(dir, eps))) < eps * 1e-3; + if (!on(0, e1) || !on(1, e2)) throw ctx.err('Fillet beads go along inside corners, where two faces meet at less than 180 degrees'); + const pts = [E, add(E, scale(e1, s)), add(E, scale(e2, s))]; + const face = R.makeFace(R.assembleWire(pts.map((p, i) => R.makeLine(p, pts[(i + 1) % 3])))); + solids.push(R.basicFaceExtrusion(face, new R.Vector(sub(e.desc.b, e.desc.a))) as unknown as Sh); + } + const tool = solids.length === 1 ? solids[0] : fuseAll(solids); + ctx.applyTool(tool, solids.flatMap((x, i) => ctx.nameTool(f.id, x, (k) => `w${i}:${k}`)), 'The bead adds no material: the corner is already filled.'); + checkValid(ctx, 'The result is not a valid solid where the bead meets the part. Try another bead size.'); + const prev = ctx.st.weld; + ctx.st.weld = { members: prev?.members ?? [], extras: [...(prev?.extras ?? []), ...solids] }; +} diff --git a/src/parametric/src/kernel/worker.ts b/src/parametric/src/kernel/worker.ts index 8842e1cda3..c8698f52c3 100644 --- a/src/parametric/src/kernel/worker.ts +++ b/src/parametric/src/kernel/worker.ts @@ -6,6 +6,7 @@ import init from 'replicad-opencascadejs'; import wasmUrl from 'replicad-opencascadejs/wasm?url'; import { solidWorksToStep } from '../formats/sldprt'; import { ModelBuilder, checkStep, errorText, isFatal } from './build'; +import { AssemblyBuilder, asmTransfers } from './assembly'; import { setOc } from './occ'; import type { BuildResult, MeshData, WorkerRequest, WorkerResponse } from './protocol'; @@ -15,6 +16,8 @@ let ready: Promise | null = null; /** The WebAssembly memory of the OpenCascade module, to report its size. */ let memory: { buffer: ArrayBuffer } | undefined; const builder = new ModelBuilder(); +/** The parts and components of an open assembly (active while one is open). */ +const assembly = new AssemblyBuilder(); /** Imported file data of the open part, by blob id. */ const blobs: Record = {}; /** The builder's cached mesh last sent to the main thread. */ @@ -39,7 +42,16 @@ function meshTransfers(m: MeshData | null, out: Transferable[]) { for (const a of [m.positions, m.normals, m.indices, m.vertexFace, m.edgePositions, m.edgeIds, m.vertices]) out.push(a.buffer); } -self.onmessage = async (ev: MessageEvent) => { +// One request at a time, in the order sent. Requests that arrive while the +// WebAssembly module loads all wait for it; run side by side, a request sent +// after a build (measure, an assembly's mass) ran in the middle of it, between +// two of its features, and found the part or the assembly's parts not built yet. +let queue: Promise = Promise.resolve(); +self.onmessage = (ev: MessageEvent) => { + queue = queue.then(() => handle(ev)).catch(() => undefined); +}; + +async function handle(ev: MessageEvent) { const msg = ev.data; // A result computed after the module aborted cannot be trusted either. const reply = (r: WorkerResponse, transfer: Transferable[] = []) => @@ -52,9 +64,12 @@ self.onmessage = async (ev: MessageEvent) => { return; case 'reset': builder.reset(); + assembly.reset(); reply({ id: msg.id, ok: true, result: true }); return; case 'build': { + // A part is open: drawings, measure and export work on it again. + assembly.active = false; // File data arrives once; later requests only list the ids in use. const keep = new Set(msg.blobs); for (const k of Object.keys(blobs)) if (!keep.has(k)) delete blobs[k]; @@ -80,20 +95,47 @@ self.onmessage = async (ev: MessageEvent) => { return; } case 'project': - reply({ id: msg.id, ok: true, result: builder.project(msg.views) }); + reply({ id: msg.id, ok: true, result: assembly.active ? assembly.project(msg.views) : builder.project(msg.views) }); return; case 'mass': - reply({ id: msg.id, ok: true, result: builder.massProperties() }); + reply({ id: msg.id, ok: true, result: assembly.active ? assembly.massProperties() : builder.massProperties() }); + return; + case 'weldVolumes': + reply({ id: msg.id, ok: true, result: builder.weldVolumes() }); + return; + case 'flatPattern': { + const res = builder.flatPattern(msg.quality); + const transfer: Transferable[] = []; + meshTransfers(res.mesh, transfer); + reply({ id: msg.id, ok: true, result: res }, transfer); return; + } case 'measure': - reply({ id: msg.id, ok: true, result: builder.measure(msg.a, msg.b) }); + reply({ id: msg.id, ok: true, result: assembly.active ? assembly.measure(msg.a, msg.b) : builder.measure(msg.a, msg.b) }); return; case 'export': { + if (assembly.active && msg.format !== 'brep') { + const data = msg.format === 'step' ? await assembly.exportStep() : assembly.exportStl(msg.quality); + reply({ id: msg.id, ok: true, result: data }, [data.buffer as ArrayBuffer]); + return; + } if (msg.format === 'brep') { reply({ id: msg.id, ok: true, result: builder.exportBrep() }); return; } const data = msg.format === 'step' ? builder.exportStep(msg.name) : builder.exportStl(msg.quality); reply({ id: msg.id, ok: true, result: data }, [data.buffer as ArrayBuffer]); return; } + case 'asm': { + const r = msg.req; + const result = r.op === 'build' ? await assembly.build(r.parts) + : r.op === 'scene' ? (assembly.setScene(r.items), true) + : r.op === 'drop' ? (assembly.drop(r.keep), true) + : r.op === 'project' ? assembly.projectItems(r.items, r.views) + : r.op === 'interference' ? assembly.interference() + : assembly.mass(r.densities); + // The heap lets the main thread replace a worker that grew too big, as after part builds. + reply({ id: msg.id, ok: true, result, heap: memory?.buffer.byteLength }, r.op === 'build' || r.op === 'interference' ? asmTransfers(result) : []); + return; + } case 'checkImport': reply({ id: msg.id, ok: true, result: await checkStep(msg.text) }); return; @@ -113,4 +155,4 @@ self.onmessage = async (ev: MessageEvent) => { if (isFatal(e)) aborted = true; reply({ id: msg.id, ok: false, error: errorText(e) }); } -}; +} diff --git a/src/parametric/src/main.ts b/src/parametric/src/main.ts index c70d46ec3c..c94155ee69 100644 --- a/src/parametric/src/main.ts +++ b/src/parametric/src/main.ts @@ -1,6 +1,7 @@ import './styles/app.css'; import { App } from './app/app'; import { makeHooks, registerCommands } from './app/actions'; +import { installAssembly } from './app/assembly'; import { FileOps } from './app/fileops'; import { StartScreen, bindAccountMenu, bindUserMenu, refreshAccount } from './app/start'; import { TaskPane, recentItems } from './app/taskpane'; @@ -30,6 +31,7 @@ async function boot() { app.renamePart = (name) => files.rename(name); registerCommands(app, files); const hooks = makeHooks(app); + installAssembly(app, files, hooks); let start: StartScreen | null = null; hooks.recent = () => recentItems(app, files); hooks.gettingStarted = () => app.openTaskPane('help'); diff --git a/src/parametric/src/model/assembly.ts b/src/parametric/src/model/assembly.ts new file mode 100644 index 0000000000..b13edd53d9 --- /dev/null +++ b/src/parametric/src/model/assembly.ts @@ -0,0 +1,416 @@ +// Assembly documents: components (placed instances of part files), mates +// between their faces and edges, and exploded view steps. An assembly is +// saved in a .parametric file like a part, told apart by its format. +// +// Every component references its part file by location AND the assembly +// embeds a copy of each part document it uses (once per part, however many +// instances), so it still opens when a part file is moved, deleted, shared +// or downloaded as one file. The copies live in `blobs` as part file text, +// keyed by an id that changes whenever a newer copy is taken: blobs are kept +// out of undo snapshots, and undo goes back to the copy it referenced. +// +// The document keeps the fields every part document has (name, units, +// variables, an always empty feature list...) so the document store, file +// operations, history and recovery treat both kinds alike. + +import type { Vec3, Quat } from '../math/vec'; +import { qNormalize } from '../math/vec'; +import type { BasePlane, EdgeRef, FaceRef, Id, Param, PartDocument, UnitSystem } from './types'; +import { UNIT_SYSTEMS } from './units'; +import { parseDocument } from './document'; +import { validDrawing } from './validate-drawing'; + +export const ASSEMBLY_FORMAT = 'parametric-assembly'; + +/** Where a part file lives (the same shape as platform/files Location). */ +export type PartSource = { type: 'cloud'; path: string } | { type: 'local'; id: string }; + +/** Rigid placement of a component: world = rotate(q, local) + p. */ +export interface Placement { + p: Vec3; + /** Unit quaternion (x, y, z, w). */ + q: Quat; +} + +export interface AsmPart { + id: Id; + /** The part's name (its file's name when it has one). */ + name: string; + /** The part file; null for parts that exist only inside the assembly (an uploaded STEP model). */ + source: PartSource | null; + /** Version of the source file the embedded copy was read from, to tell when the file is newer. */ + version: { modified: number; size: number | null } | null; + /** Key into the document's blobs of the embedded part document's file text. */ + blob: Id; + /** Appearance colour of this part's components (#rrggbb). */ + color: string; +} + +export interface AsmComponent { + id: Id; + /** Instance name, e.g. "bracket<1>". */ + name: string; + part: Id; + placement: Placement; + /** Fixed components never move; the first one inserted is fixed. */ + fixed: boolean; + hidden?: boolean; + suppressed?: boolean; +} + +export type MateType = 'coincident' | 'parallel' | 'perpendicular' | 'distance' | 'angle' | 'concentric' | 'tangent' | 'lock'; + +/** What a mate references: a face or edge of a component (by name, as features reference faces), an assembly plane, or a whole component (lock). */ +export type MateRef = + | { comp: Id; face: FaceRef } + | { comp: Id; edge: EdgeRef } + | { comp: Id } + | { plane: BasePlane }; + +export interface Mate { + id: Id; + name: string; + type: MateType; + a: MateRef; + b: MateRef; + /** Directions (normals, axes) point the same way (true) or opposite ways (false). */ + aligned: boolean; + /** Distance (mm) or angle (degrees); expressions allowed. */ + value?: Param; + /** Distance and tangent mates: the second entity lies on the other side of the first. */ + flip?: boolean; + suppressed?: boolean; + /** Lock mates: where b sits in a's frame. */ + rel?: Placement; +} + +export interface ExplodeStep { + id: Id; + name: string; + comps: Id[]; + /** Unit direction in assembly coordinates. */ + dir: Vec3; + distance: Param; +} + +export interface AssemblyDocument extends Omit { + format: typeof ASSEMBLY_FORMAT; + /** Always empty: an assembly has components, not features. */ + features: []; + parts: AsmPart[]; + components: AsmComponent[]; + mates: Mate[]; + explode: ExplodeStep[]; + /** Whether the exploded view is shown. */ + exploded: boolean; +} + +export const MATE_LABELS: Record = { + coincident: 'Coincident', parallel: 'Parallel', perpendicular: 'Perpendicular', distance: 'Distance', + angle: 'Angle', concentric: 'Concentric', tangent: 'Tangent', lock: 'Lock', +}; + +/** Distinct component colours, picked in turn for each new part. */ +export const PART_COLORS = ['#b8c4d2', '#e0a85a', '#7fb37c', '#c98bb9', '#6fa8dc', '#d9776a', '#a7a35a', '#8e8fd6', '#5fb3a8', '#c7a27c']; + +export const isAssembly = (doc: { format?: unknown } | null | undefined): doc is AssemblyDocument => doc?.format === ASSEMBLY_FORMAT; + +/** The open document as an assembly (the store is typed for parts; see the note at the top). */ +export const asAssembly = (doc: unknown): AssemblyDocument | null => (isAssembly(doc as { format?: unknown }) ? doc as AssemblyDocument : null); + +export function newAssembly(name = 'Assembly1', units: UnitSystem = 'MMGS'): AssemblyDocument { + const now = Date.now(); + return { + format: ASSEMBLY_FORMAT, + version: 1, + name, + units, + decimals: units === 'IPS' ? 3 : 2, + material: null, + color: '#b8c4d2', + variables: [], + features: [], + rollback: null, + blobs: {}, + parts: [], + components: [], + mates: [], + explode: [], + exploded: false, + nextId: 1, + created: now, + modified: now, + }; +} + +export const IDENTITY: Placement = { p: [0, 0, 0], q: [0, 0, 0, 1] }; + +// ---------- validation ---------- + +const isObj = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const isStr = (v: unknown): v is string => typeof v === 'string' && v.length > 0; +const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); +const isVec = (v: unknown): v is Vec3 => Array.isArray(v) && v.length === 3 && v.every(isNum); +const isParam = (v: unknown) => isNum(v) || typeof v === 'string'; +const BASE_PLANES = ['front', 'top', 'right']; +const MATE_TYPES = Object.keys(MATE_LABELS); +/** The most components (and parts), mates and explode steps an assembly file may have. */ +export const MAX_COMPONENTS = 2000, MAX_MATES = 10000, MAX_EXPLODE_STEPS = 1000; + +function validPlacement(v: unknown): v is Placement { + return isObj(v) && isVec(v.p) && Array.isArray(v.q) && v.q.length === 4 && v.q.every(isNum) && Math.hypot(...(v.q as number[])) > 1e-9; +} + +function validFaceRef(v: unknown): boolean { + return isObj(v) && typeof v.name === 'string' && isObj(v.sig) && typeof v.sig.type === 'string' && isVec(v.sig.c) && isNum(v.sig.area) && (v.sig.n === undefined || isVec(v.sig.n)); +} + +function validEdgeRef(v: unknown): boolean { + return isObj(v) && typeof v.name === 'string' && isObj(v.sig) && typeof v.sig.type === 'string' && isVec(v.sig.m) && isNum(v.sig.len); +} + +function validMateRef(v: unknown, comps: Set): boolean { + if (!isObj(v)) return false; + if ('plane' in v) return BASE_PLANES.includes(v.plane as string); + if (!isStr(v.comp) || !comps.has(v.comp)) return false; + if ('face' in v) return validFaceRef(v.face); + if ('edge' in v) return validEdgeRef(v.edge); + return true; +} + +function validSource(v: unknown): v is PartSource | null { + return v === null || (isObj(v) && ((v.type === 'cloud' && isStr(v.path)) || (v.type === 'local' && isStr(v.id)))); +} + +/** + * Validates and normalises an assembly read from a file (throws a readable + * error). Embedded parts are checked when they are used, so one damaged part + * shows as a failed component rather than refusing the whole assembly. + */ +export function parseAssembly(text: string): AssemblyDocument { + let raw: unknown; + try { + raw = JSON.parse(text); + } catch { + throw new Error('This file is not a valid assembly file.'); + } + return validateAssembly(raw); +} + +export function validateAssembly(raw: unknown): AssemblyDocument { + const d = raw as Partial & Record; + if (!isObj(d) || d.format !== ASSEMBLY_FORMAT) throw new Error('This file is not an assembly created with Parametric.'); + if (typeof d.version === 'number' && d.version > 1) throw new Error('This assembly was created with a newer version of Parametric.'); + if (d.version !== 1) throw new Error('The assembly file is damaged (unknown version).'); + const damaged = (what: string) => new Error(`The assembly file is damaged (${what}).`); + const blobs = isObj(d.blobs) ? d.blobs : {}; + if (!Object.values(blobs).every((b) => typeof b === 'string')) throw damaged('invalid part copy'); + if (!Array.isArray(d.parts) || !Array.isArray(d.components)) throw damaged('no component list'); + // Far beyond any assembly made here: a file this big was damaged or made by hand, and would not open in a browser tab. + const mates0 = Array.isArray(d.mates) ? d.mates : [], explode0 = Array.isArray(d.explode) ? d.explode : []; + for (const [list, max, what] of [[d.components, MAX_COMPONENTS, 'components'], [d.parts, MAX_COMPONENTS, 'parts'], [mates0, MAX_MATES, 'mates'], [explode0, MAX_EXPLODE_STEPS, 'explode steps']] as const) { + if (list.length > max) throw new Error(`This assembly has ${list.length} ${what}, more than Parametric can open (at most ${max}).`); + } + const partIds = new Set(); + for (const p of d.parts) { + if (!isObj(p) || !isStr(p.id) || partIds.has(p.id) || typeof p.name !== 'string' || !isStr(p.blob) || !Object.hasOwn(blobs, p.blob) || !validSource(p.source)) throw damaged('invalid part'); + partIds.add(p.id); + } + const compIds = new Set(); + for (const c of d.components) { + if (!isObj(c) || !isStr(c.id) || compIds.has(c.id) || partIds.has(c.id) || !isStr(c.part) || !partIds.has(c.part) || !validPlacement(c.placement)) throw damaged('invalid component'); + compIds.add(c.id); + } + const mates = Array.isArray(d.mates) ? d.mates : []; + const ids = new Set([...partIds, ...compIds]); + for (const m of mates) { + if (!isObj(m) || !isStr(m.id) || ids.has(m.id) || !MATE_TYPES.includes(m.type as string) || !validMateRef(m.a, compIds) || !validMateRef(m.b, compIds)) throw damaged('invalid mate'); + if (m.value !== undefined && !isParam(m.value)) throw damaged('invalid mate value'); + if (m.rel !== undefined && !validPlacement(m.rel)) throw damaged('invalid mate'); + ids.add(m.id); + } + const explode = Array.isArray(d.explode) ? d.explode : []; + for (const s of explode) { + if (!isObj(s) || !isStr(s.id) || ids.has(s.id) || !Array.isArray(s.comps) || !s.comps.every((c) => compIds.has(c as string)) || !isVec(s.dir) || !isParam(s.distance)) throw damaged('invalid explode step'); + ids.add(s.id); + } + if (d.drawing != null && !validDrawing(d.drawing)) throw damaged('invalid drawing'); + const units = typeof d.units === 'string' && Object.hasOwn(UNIT_SYSTEMS, d.units) ? d.units : 'MMGS'; + const base = newAssembly(typeof d.name === 'string' && d.name ? d.name : undefined, units); + const variables = (Array.isArray(d.variables) ? d.variables : []) + .filter((v) => isObj(v) && typeof v.name === 'string') + .map((v, i) => ({ id: isStr(v.id) ? v.id : `v${i + 1}x`, name: v.name, expr: typeof v.expr === 'string' ? v.expr : String(v.expr ?? '') })); + const doc: AssemblyDocument = { + ...base, + name: typeof d.name === 'string' && d.name ? d.name : base.name, + units, + decimals: Number.isInteger(d.decimals) && (d.decimals as number) >= 0 && (d.decimals as number) <= 8 ? d.decimals as number : base.decimals, + variables, + blobs: blobs as Record, + parts: d.parts.map((p) => ({ + id: p.id, name: p.name, source: p.source ?? null, blob: p.blob, + version: isObj(p.version) && isNum(p.version.modified) ? { modified: p.version.modified, size: isNum(p.version.size) ? p.version.size : null } : null, + color: typeof p.color === 'string' && /^#[0-9a-f]{6}$/i.test(p.color) ? p.color : PART_COLORS[0], + })), + components: d.components.map((c) => ({ + id: c.id, name: typeof c.name === 'string' && c.name ? c.name : c.id, part: c.part, + placement: { p: [...c.placement.p] as Vec3, q: qNormalize(c.placement.q as Quat) }, + fixed: c.fixed === true, + ...(c.hidden === true ? { hidden: true } : {}), + ...(c.suppressed === true ? { suppressed: true } : {}), + })), + mates: mates.map((m) => ({ + ...m, + name: typeof m.name === 'string' && m.name ? m.name : m.id, + aligned: m.aligned === true, + ...(m.flip === true ? { flip: true } : { flip: undefined }), + ...(m.suppressed === true ? { suppressed: true } : { suppressed: undefined }), + })).map((m) => JSON.parse(JSON.stringify(m)) as Mate), + explode: explode.map((s) => ({ id: s.id, name: typeof s.name === 'string' && s.name ? s.name : s.id, comps: [...new Set(s.comps as Id[])], dir: [...s.dir] as Vec3, distance: s.distance })), + exploded: d.exploded === true && explode.length > 0, + ...(d.drawing != null ? { drawing: d.drawing } : {}), + created: isNum(d.created) && Math.abs(d.created) < 8.64e15 ? d.created : base.created, + modified: isNum(d.modified) && Math.abs(d.modified) < 8.64e15 ? d.modified : base.modified, + nextId: 1, + }; + // New ids must not collide with existing ones, even when the counter is stale. + let max = 0; + for (const id of [...ids, ...variables.map((v) => v.id)]) { + const m = /^[a-z]+(\d+)$/i.exec(id); + if (m && Number.isSafeInteger(Number(m[1]))) max = Math.max(max, Number(m[1])); + } + doc.nextId = Math.max(isNum(d.nextId) && Number.isSafeInteger(d.nextId) && d.nextId > 0 ? d.nextId : 1, max + 1); + return doc; +} + +/** + * A part or an assembly from a .parametric file's text. Parts take exactly + * the path they always did; an assembly is told by its format. + */ +export function parseAnyDocument(text: string): PartDocument | AssemblyDocument { + if (/^\s*\{\s*"format"\s*:\s*"parametric-assembly"/.test(text.slice(0, 200))) return parseAssembly(text); + try { + return parseDocument(text); + } catch (e) { + // An assembly whose format is not written first (edited by hand, say). + if (text.length < 50_000_000 && text.includes(ASSEMBLY_FORMAT)) { + let raw: unknown = null; + try { raw = JSON.parse(text); } catch { /* not JSON: the part error says so */ } + if (isAssembly(raw as { format?: unknown })) return validateAssembly(raw); + } + throw e; + } +} + +/** Allocates a new id in an assembly (components, parts, mates, explode steps). */ +export function nextAsmId(doc: AssemblyDocument, prefix: string): Id { + const used = new Set([...doc.parts.map((p) => p.id), ...doc.components.map((c) => c.id), ...doc.mates.map((m) => m.id), ...doc.explode.map((s) => s.id)]); + let id: string; + do id = `${prefix}${doc.nextId++}`; while (used.has(id)); + return id; +} + +/** A new key for an embedded part copy (copies are immutable: an update gets a new key). */ +export function newPartBlobId(doc: { blobs: Record }): Id { + let id: string; + do id = `a${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`; while (Object.hasOwn(doc.blobs, id)); + return id; +} + +/** Instance name for a new component of a part: "name" with the first free n. */ +export function instanceName(doc: AssemblyDocument, partName: string): string { + const taken = new Set(doc.components.map((c) => c.name.toLowerCase())); + let n = 1; + while (taken.has(`${partName}<${n}>`.toLowerCase())) n++; + return `${partName}<${n}>`; +} + +/** The colour a newly embedded part gets: the first palette colour not used yet. */ +export function nextPartColor(doc: AssemblyDocument): string { + const used = new Set(doc.parts.map((p) => p.color.toLowerCase())); + return PART_COLORS.find((c) => !used.has(c)) ?? PART_COLORS[doc.parts.length % PART_COLORS.length]; +} + +/** The components a mate references. */ +export function mateComps(m: Mate): Id[] { + const out: Id[] = []; + for (const r of [m.a, m.b]) if ('comp' in r) out.push(r.comp); + return out; +} + +// ---------- embedded parts ---------- + +/** + * Parses embedded part documents. Kept by blob key: a key always holds the + * same text, so the parsed document can be reused until the key goes away. + */ +export class PartCache { + private cache = new Map(); + + constructor(private parse: (text: string) => PartDocument) {} + + get(doc: AssemblyDocument, partId: Id): { doc: PartDocument | null; error: string | null } { + const p = doc.parts.find((x) => x.id === partId); + if (!p) return { doc: null, error: 'The part is missing from the assembly' }; + const text = doc.blobs[p.blob]; + if (typeof text !== 'string') return { doc: null, error: 'The copy of the part kept in the assembly is missing' }; + const hit = this.cache.get(p.blob); + if (hit && hit.text === text) return hit; + let parsed: PartDocument | null = null, error: string | null = null; + try { + parsed = this.parse(text); + } catch (e) { + error = (e as Error).message; + } + const entry = { text, doc: parsed, error }; + this.cache.set(p.blob, entry); + return entry; + } + + /** Forgets copies no longer referenced by the document. */ + prune(doc: AssemblyDocument) { + const keep = new Set(doc.parts.map((p) => p.blob)); + for (const k of [...this.cache.keys()]) if (!keep.has(k)) this.cache.delete(k); + } +} + +// ---------- bill of materials ---------- + +export interface BomRow { + /** Item number, from 1, in the order parts first appear in the assembly. */ + item: number; + part: Id; + name: string; + quantity: number; + /** Material name, or '' when the part has none. */ + material: string; + /** Where the part file is, for reference. */ + source: PartSource | null; +} + +/** + * The assembly's bill of materials: one row per part, counting its + * components that are not suppressed (hidden ones count: they are still in + * the assembly). `partDoc` gives the embedded part document (for its material). + */ +export function assemblyBom(doc: AssemblyDocument, partDoc: (partId: Id) => PartDocument | null = () => null): BomRow[] { + const rows: BomRow[] = []; + for (const c of doc.components) { + if (c.suppressed) continue; + let row = rows.find((r) => r.part === c.part); + if (!row) { + const p = doc.parts.find((x) => x.id === c.part); + if (!p) continue; + row = { item: rows.length + 1, part: p.id, name: p.name, quantity: 0, material: partDoc(p.id)?.material?.name ?? '', source: p.source }; + rows.push(row); + } + row.quantity++; + } + return rows; +} + +/** The bill of materials as CSV text (for spreadsheets), or tab-separated (`sep` '\t', to paste into one). */ +export function bomCsv(rows: BomRow[], sep: ',' | '\t' = ','): string { + const cell = (v: string | number) => (/["\n\r]/.test(String(v)) || String(v).includes(sep) ? `"${String(v).replace(/"/g, '""')}"` : String(v)); + return [['Item No.', 'Part Name', 'Quantity', 'Material'], ...rows.map((r) => [r.item, r.name, r.quantity, r.material])].map((row) => row.map(cell).join(sep)).join('\n'); +} diff --git a/src/parametric/src/model/document.ts b/src/parametric/src/model/document.ts index 703a6c50d6..f27804e103 100644 --- a/src/parametric/src/model/document.ts +++ b/src/parametric/src/model/document.ts @@ -231,6 +231,8 @@ export function serializeDocument(doc: PartDocument): string { export function withUsedBlobs(doc: PartDocument): PartDocument { const used = new Set(doc.features.map((f) => (f.type === 'import' ? f.blob : null))); + // An assembly keeps the copies of its parts as blobs (see assembly.ts). + for (const p of (doc as { parts?: { blob?: string }[] }).parts ?? []) used.add(p.blob ?? null); const keys = Object.keys(doc.blobs ?? {}); if (keys.every((k) => used.has(k))) return doc; return { ...doc, blobs: Object.fromEntries(keys.filter((k) => used.has(k)).map((k) => [k, doc.blobs[k]])) }; diff --git a/src/parametric/src/model/features.ts b/src/parametric/src/model/features.ts index 92d20c5f36..2b92930a09 100644 --- a/src/parametric/src/model/features.ts +++ b/src/parametric/src/model/features.ts @@ -5,6 +5,7 @@ import type { Id, LinearPatternFeature, LoftFeature, MirrorFeature, PartDocument, PlaneFeature, PlaneRef, RevolveFeature, ShellFeature, SketchFeature, SweepFeature, } from './types'; +import { SURFACE_BASE_NAMES, SURFACE_LABELS, SURFACE_PARAM_FIELDS, isSurfaceFeature, surfaceIcon, surfaceRefs, surfaceSketches } from './surfaces'; export type ParamKind = 'length' | 'angle' | 'count'; @@ -43,6 +44,42 @@ export const PARAM_FIELDS: Partial = { sweep: 'Sweep', draft: 'Draft', import: 'Imported', + ...SURFACE_BASE_NAMES, + baseFlange: 'Base-Flange', + edgeFlange: 'Edge-Flange', + sketchedBend: 'Sketched Bend', + hem: 'Hem', + structuralMember: 'Structural Member', + trimExtend: 'Trim/Extend', + endCap: 'End Cap', + gusset: 'Gusset', + weldBead: 'Fillet Bead', }; export const FEATURE_LABELS: Record = { @@ -108,9 +163,20 @@ export const FEATURE_LABELS: Record = { sweep: 'Sweep', draft: 'Draft', import: 'Imported Body', + ...SURFACE_LABELS, + baseFlange: 'Base Flange/Tab', + edgeFlange: 'Edge Flange', + sketchedBend: 'Sketched Bend', + hem: 'Hem', + structuralMember: 'Structural Member', + trimExtend: 'Trim/Extend', + endCap: 'End Cap', + gusset: 'Gusset', + weldBead: 'Fillet Bead', }; export function featureIcon(f: Feature): string { + if (isSurfaceFeature(f)) return surfaceIcon(f); switch (f.type) { case 'sketch': return 'sketchFeature'; case 'extrude': return f.cut ? 'extrudeCut' : 'extrude'; @@ -178,10 +244,13 @@ export const newDraft = (id: Id, name: string): DraftFeature => ({ id, name, typ /** Features that consume a sketch (the sketch is shown nested under them). */ export function consumedSketches(f: Feature): Id[] { + if (isSurfaceFeature(f)) return surfaceSketches(f); switch (f.type) { case 'extrude': case 'revolve': case 'hole': + case 'baseFlange': + case 'sketchedBend': return [f.sketch]; case 'loft': return f.profiles; @@ -237,6 +306,16 @@ export function dependencies(f: Feature): Id[] { if (f.type === 'linearPattern') for (const d of [f.dir1, f.dir2]) visitAxis(d?.ref); if (f.type === 'fillet' || f.type === 'chamfer') { f.edges.forEach((r) => visitName(r.name)); f.faces.forEach((r) => visitName(r.name)); } if (f.type === 'shell') f.faces.forEach((r) => visitName(r.name)); + if (isSurfaceFeature(f)) surfaceRefs(f, { name: visitName, plane: visitPlane, axis: visitAxis }); + if (f.type === 'edgeFlange' || f.type === 'hem') f.edges.forEach((r) => visitName(r.name)); + // Weldments: the layout sketches of members, the members trimmed and the faces picked. + if (f.type === 'structuralMember') for (const g of f.groups) for (const s of g.segments) out.add(s.sketch); + if (f.type === 'trimExtend') { + for (const m of [...f.members, ...f.boundaryMembers]) if (m.feature !== f.id) out.add(m.feature); + f.faces.forEach((r) => visitName(r.name)); + } + if (f.type === 'endCap' || f.type === 'gusset') f.faces.forEach((r) => visitName(r.name)); + if (f.type === 'weldBead') f.edges.forEach((r) => visitName(r.name)); return [...out]; } diff --git a/src/parametric/src/model/flat-pattern.ts b/src/parametric/src/model/flat-pattern.ts new file mode 100644 index 0000000000..7af8bdbf6c --- /dev/null +++ b/src/parametric/src/model/flat-pattern.ts @@ -0,0 +1,146 @@ +// The flat pattern of a sheet metal part as 2D geometry (computed by the +// geometry worker from the sheet metal features), and its DXF export. +// Coordinates are millimetres in the flat pattern's own plane. + +import type { Frame, Vec2 } from '../math/vec'; +import type { Id } from './types'; + +export type FlatSeg = + | { k: 'line'; a: Vec2; b: Vec2 } + /** Counter-clockwise from a0 to a1 (radians). */ + | { k: 'arc'; c: Vec2; r: number; a0: number; a1: number } + | { k: 'circle'; c: Vec2; r: number }; + +export interface FlatLoop { + /** The outline of a region (else a hole or cut inside it). */ + outer: boolean; + segs: FlatSeg[]; +} + +export interface FlatBend { + /** Bend centre line, from a to b. */ + a: Vec2; + b: Vec2; + /** Bends toward the viewer of the flat pattern (its top face). */ + up: boolean; + angle: number; + /** Inner radius. */ + radius: number; + /** Flat length of the bend region (bend allowance). */ + allowance: number; + /** Feature that made the bend. */ + feature: Id; +} + +export interface FlatPattern { + loops: FlatLoop[]; + bends: FlatBend[]; + thickness: number; + /** Bounding box of the outline. */ + min: Vec2; + max: Vec2; + /** Things the flat pattern leaves out or cannot show exactly. */ + notes: string[]; + /** Where the flat pattern is shown in the model (flat x, y, thickness to world). */ + placement: Frame; +} + +/** A bend note as drawings and the PropertyManager show it, e.g. "UP 90° R 1". */ +export function bendNote(b: FlatBend, fmt: (mm: number) => string = (v) => trimNum(v)): string { + return `${b.up ? 'UP' : 'DOWN'} ${trimNum(b.angle)}° R ${fmt(b.radius)}`; +} + +export function trimNum(v: number, digits = 3): string { + const s = v.toFixed(digits); + return s.includes('.') ? s.replace(/\.?0+$/, '') : s; +} + +/** Overall size of the flat pattern (width along x, height along y). */ +export const flatSize = (f: FlatPattern): Vec2 => [f.max[0] - f.min[0], f.max[1] - f.min[1]]; + +// ---- DXF ---- + +const deg = (r: number) => (r * 180) / Math.PI; +const num = (v: number) => { + const s = (Math.abs(v) < 5e-10 ? 0 : v).toFixed(9); + return s.replace(/\.?0+$/, '') || '0'; +}; + +/** + * The flat pattern as an ASCII DXF (AutoCAD R12, which every cutting + * program reads): the outline on layer OUTLINE, holes and cuts on CUTS, bend + * centre lines on BEND_UP or BEND_DOWN (dashed) and the bend notes on + * BEND_NOTES. + */ +export function flatPatternDxf(f: FlatPattern, opts: { notes?: boolean } = {}): string { + const out: string[] = []; + const g = (code: number, v: string | number) => { out.push(String(code), typeof v === 'number' ? num(v) : v); }; + const layers: [string, number, string][] = [ + ['OUTLINE', 7, 'CONTINUOUS'], ['CUTS', 1, 'CONTINUOUS'], ['BEND_UP', 3, 'DASHED'], ['BEND_DOWN', 5, 'DASHED'], ['BEND_NOTES', 2, 'CONTINUOUS'], + ]; + g(0, 'SECTION'); g(2, 'HEADER'); + g(9, '$ACADVER'); g(1, 'AC1009'); + g(9, '$INSUNITS'); g(70, 4); + g(9, '$EXTMIN'); g(10, f.min[0]); g(20, f.min[1]); g(30, 0); + g(9, '$EXTMAX'); g(10, f.max[0]); g(20, f.max[1]); g(30, 0); + g(0, 'ENDSEC'); + g(0, 'SECTION'); g(2, 'TABLES'); + g(0, 'TABLE'); g(2, 'LTYPE'); g(70, 2); + g(0, 'LTYPE'); g(2, 'CONTINUOUS'); g(70, 0); g(3, 'Solid line'); g(72, 65); g(73, 0); g(40, 0); + g(0, 'LTYPE'); g(2, 'DASHED'); g(70, 0); g(3, '__ __ __'); g(72, 65); g(73, 2); g(40, 6); g(49, 4); g(49, -2); + g(0, 'ENDTAB'); + g(0, 'TABLE'); g(2, 'LAYER'); g(70, layers.length); + for (const [name, color, lt] of layers) { g(0, 'LAYER'); g(2, name); g(70, 0); g(62, color); g(6, lt); } + g(0, 'ENDTAB'); + g(0, 'ENDSEC'); + g(0, 'SECTION'); g(2, 'ENTITIES'); + for (const loop of f.loops) { + const layer = loop.outer ? 'OUTLINE' : 'CUTS'; + for (const s of loop.segs) { + if (s.k === 'line') { g(0, 'LINE'); g(8, layer); g(10, s.a[0]); g(20, s.a[1]); g(30, 0); g(11, s.b[0]); g(21, s.b[1]); g(31, 0); } + else if (s.k === 'circle') { g(0, 'CIRCLE'); g(8, layer); g(10, s.c[0]); g(20, s.c[1]); g(30, 0); g(40, s.r); } + else { g(0, 'ARC'); g(8, layer); g(10, s.c[0]); g(20, s.c[1]); g(30, 0); g(40, s.r); g(50, deg(s.a0)); g(51, deg(s.a1)); } + } + } + for (const b of f.bends) { + const layer = b.up ? 'BEND_UP' : 'BEND_DOWN'; + g(0, 'LINE'); g(8, layer); g(6, 'DASHED'); g(10, b.a[0]); g(20, b.a[1]); g(30, 0); g(11, b.b[0]); g(21, b.b[1]); g(31, 0); + if (opts.notes !== false) { + const h = Math.max(f.thickness, 1.5); + const ang = deg(Math.atan2(b.b[1] - b.a[1], b.b[0] - b.a[0])); + // Upright text along the line, beside its middle. + const upright = ang > 90 || ang <= -90 ? ang + 180 : ang; + const t = (upright * Math.PI) / 180; + const m: Vec2 = [(b.a[0] + b.b[0]) / 2 - Math.sin(t) * h * 0.4, (b.a[1] + b.b[1]) / 2 + Math.cos(t) * h * 0.4]; + g(0, 'TEXT'); g(8, 'BEND_NOTES'); g(10, m[0]); g(20, m[1]); g(30, 0); g(40, h); g(1, bendNote(b).replace('°', '%%d')); g(50, upright); g(72, 1); g(11, m[0]); g(21, m[1]); g(31, 0); + } + } + g(0, 'ENDSEC'); + g(0, 'EOF'); + return out.join('\n') + '\n'; +} + +/** Entities of a DXF file as code/value pairs per entity (for checks). */ +export function parseDxfEntities(text: string): { type: string; layer: string; values: Map }[] { + const lines = text.split(/\r?\n/); + const out: { type: string; layer: string; values: Map }[] = []; + let inEntities = false; + let cur: { type: string; layer: string; values: Map } | null = null; + for (let i = 0; i + 1 < lines.length; i += 2) { + const code = Number(lines[i].trim()), value = lines[i + 1].trim(); + if (!Number.isInteger(code)) throw new Error(`Bad group code at line ${i + 1}`); + if (code === 2 && value === 'ENTITIES') { inEntities = true; continue; } + if (code === 0) { + if (cur) out.push(cur); + cur = null; + if (value === 'ENDSEC') { inEntities = false; continue; } + if (inEntities) cur = { type: value, layer: '', values: new Map() }; + continue; + } + if (!cur) continue; + if (code === 8) cur.layer = value; + const list = cur.values.get(code); + if (list) list.push(value); else cur.values.set(code, [value]); + } + return out; +} diff --git a/src/parametric/src/model/sheetmetal.ts b/src/parametric/src/model/sheetmetal.ts new file mode 100644 index 0000000000..c5366e1149 --- /dev/null +++ b/src/parametric/src/model/sheetmetal.ts @@ -0,0 +1,346 @@ +// Sheet metal features: types, factories, validation and the bend math the +// geometry kernel and the flat pattern share. Lengths are millimetres and +// angles degrees, as everywhere in the document. + +import type { Vec2 } from '../math/vec'; +import { SketchIndex } from '../sketch/geom'; +import type { EdgeRef, FeatureBase, Id, Param, SkEntity } from './types'; + +/** How the flat length of a bend is found. */ +export type BendAllowanceType = 'kFactor' | 'bendAllowance' | 'bendDeduction'; +export type ReliefType = 'rectangular' | 'obround' | 'none'; + +/** The part's sheet metal parameters, kept on its first Base Flange. */ +export interface SheetMetalParams { + thickness: Param; + /** Inner bend radius. */ + radius: Param; + allowance: BendAllowanceType; + /** Position of the neutral fibre as a fraction of the thickness (0 to 1). */ + kFactor: number; + /** Bend allowance or bend deduction, for those allowance types. */ + allowanceValue: Param; + relief: ReliefType; + /** Relief width and extra depth as a multiple of the thickness. */ + reliefRatio: number; +} + +/** + * Base Flange from a sketch: a closed profile makes a flat plate, an open + * line/arc chain is thickened and extruded, with a bend at each sharp corner. + * A later Base Flange in a part is a Tab: a flat region added on a face of the + * sheet in the same thickness (its own sheet metal parameters are not used). + */ +export interface BaseFlangeFeature extends FeatureBase { + type: 'baseFlange'; + sketch: Id; + sm: SheetMetalParams; + /** Thickness on the other side of the sketch. */ + flip: boolean; + /** Thickness centred on the sketch. */ + mid: boolean; + /** Open profiles: how far the profile is extruded. */ + depth: Param; + depthEnd: 'blind' | 'midPlane'; + depthFlip: boolean; +} + +export type FlangeLengthRef = 'outer' | 'inner' | 'tangent'; +export type FlangePosition = 'materialInside' | 'materialOutside' | 'bendOutside'; + +export interface EdgeFlangeFeature extends FeatureBase { + type: 'edgeFlange'; + edges: EdgeRef[]; + length: Param; + angle: Param; + /** What the length is measured from: outer or inner virtual sharp, or the end of the bend. */ + lengthRef: FlangeLengthRef; + position: FlangePosition; + /** Bend to the other side. */ + flip: boolean; + /** Distances the flange stops short of each end of the edge (with bend reliefs). */ + offset1: Param; + offset2: Param; +} + +export type SketchedBendPosition = 'centerline' | FlangePosition; + +export interface SketchedBendFeature extends FeatureBase { + type: 'sketchedBend'; + sketch: Id; + angle: Param; + position: SketchedBendPosition; + /** Bend toward the other side of the face. */ + flip: boolean; + /** Keep the other side of the line fixed. */ + flipFixed: boolean; +} + +export interface HemFeature extends FeatureBase { + type: 'hem'; + edges: EdgeRef[]; + kind: 'closed' | 'open'; + length: Param; + /** Open hems: the gap between the sheet and the hem. */ + gap: Param; + position: 'materialInside' | 'bendOutside'; + flip: boolean; +} + +export type SheetMetalFeature = BaseFlangeFeature | EdgeFlangeFeature | SketchedBendFeature | HemFeature; + +export const SHEET_METAL_TYPES = ['baseFlange', 'edgeFlange', 'sketchedBend', 'hem'] as const; + +export const isSheetMetalType = (t: string): t is SheetMetalFeature['type'] => (SHEET_METAL_TYPES as readonly string[]).includes(t); + +/** Gap a closed hem leaves between the layers, as a fraction of the thickness (a zero radius has no bend). */ +export const CLOSED_HEM_GAP = 0.02; + +export const defaultSheetParams = (thickness: number): SheetMetalParams => ({ + thickness, radius: thickness, allowance: 'kFactor', kFactor: 0.5, allowanceValue: thickness * 1.5, relief: 'rectangular', reliefRatio: 0.5, +}); + +export const newBaseFlange = (id: Id, name: string, sketch: Id, thickness: number, depth: number): BaseFlangeFeature => ({ + id, name, type: 'baseFlange', sketch, sm: defaultSheetParams(thickness), flip: false, mid: false, depth, depthEnd: 'blind', depthFlip: false, +}); + +export const newEdgeFlange = (id: Id, name: string, length: number): EdgeFlangeFeature => ({ + id, name, type: 'edgeFlange', edges: [], length, angle: 90, lengthRef: 'outer', position: 'materialInside', flip: false, offset1: 0, offset2: 0, +}); + +export const newSketchedBend = (id: Id, name: string, sketch: Id): SketchedBendFeature => ({ + id, name, type: 'sketchedBend', sketch, angle: 90, position: 'centerline', flip: false, flipFixed: false, +}); + +export const newHem = (id: Id, name: string, length: number, gap: number): HemFeature => ({ + id, name, type: 'hem', edges: [], kind: 'closed', length, gap, position: 'materialInside', flip: false, +}); + +// ---- bend math ---- + +export interface BendParams { + thickness: number; + radius: number; + allowance: BendAllowanceType; + kFactor: number; + allowanceValue: number; +} + +const rad = (deg: number) => (deg * Math.PI) / 180; + +/** Outside setback: from the bend's tangent line to the virtual sharp of a surface of radius r. */ +export const setback = (angleDeg: number, r: number) => Math.tan(rad(angleDeg) / 2) * r; + +/** + * Flat length of a bend of the given angle and inner radius (the bend + * allowance). K-factor: BA = pi/180 * angle * (R + K*T). A bend allowance is + * used as given; a bend deduction BD gives BA = 2 * OSSB - BD, with the + * outside setback OSSB = tan(angle/2) * (R + T), up to 90 degrees. Past 90 + * degrees the setback grows without bound (a 180 degree hem has no virtual + * sharp), so those bends use the K-factor the deduction gives a 90 degree + * bend of the sheet's radius and thickness. + */ +export function bendAllowance(angleDeg: number, radius: number, p: BendParams): number { + switch (p.allowance) { + case 'bendAllowance': return p.allowanceValue; + case 'bendDeduction': { + if (angleDeg <= 90) return 2 * setback(angleDeg, radius + p.thickness) - p.allowanceValue; + const ba90 = 2 * (p.radius + p.thickness) - p.allowanceValue; + return rad(angleDeg) * (radius - p.radius) + (angleDeg / 90) * ba90; + } + default: return rad(angleDeg) * (radius + p.kFactor * p.thickness); + } +} + +/** Why sheet metal parameters cannot be used, or null. */ +export function sheetParamsError(p: BendParams): string | null { + if (!(p.thickness > 0)) return 'Thickness must be greater than zero'; + if (!(p.radius >= 0)) return 'The bend radius cannot be negative'; + if (p.allowance === 'kFactor' && !(p.kFactor >= 0 && p.kFactor <= 1)) return 'The K-factor must be between 0 and 1'; + if (p.allowance !== 'kFactor' && !Number.isFinite(p.allowanceValue)) return 'The bend allowance has an invalid value'; + return null; +} + +// ---- validation of files ---- + +const object = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const param = (v: unknown) => (typeof v === 'number' && Number.isFinite(v)) || typeof v === 'string'; +const finite = (v: unknown) => typeof v === 'number' && Number.isFinite(v); +const oneOf = (v: unknown, list: readonly string[]) => typeof v === 'string' && list.includes(v); +const edgeList = (v: unknown) => Array.isArray(v) && v.every((e) => object(e) && typeof e.name === 'string'); + +function validParams(v: unknown): boolean { + return object(v) && param(v.thickness) && param(v.radius) && oneOf(v.allowance, ['kFactor', 'bendAllowance', 'bendDeduction']) && finite(v.kFactor) + && param(v.allowanceValue) && oneOf(v.relief, ['rectangular', 'obround', 'none']) && finite(v.reliefRatio); +} + +/** Checks a sheet metal feature read from a file (its fields are walked by the tree and the rebuild). */ +export function validSheetMetalFeature(r: Record): boolean { + switch (r.type) { + case 'baseFlange': + return typeof r.sketch === 'string' && validParams(r.sm) && param(r.depth) && oneOf(r.depthEnd, ['blind', 'midPlane']); + case 'edgeFlange': + return edgeList(r.edges) && param(r.length) && param(r.angle) && param(r.offset1) && param(r.offset2) + && oneOf(r.lengthRef, ['outer', 'inner', 'tangent']) && oneOf(r.position, ['materialInside', 'materialOutside', 'bendOutside']); + case 'sketchedBend': + return typeof r.sketch === 'string' && param(r.angle) && oneOf(r.position, ['centerline', 'materialInside', 'materialOutside', 'bendOutside']); + case 'hem': + return edgeList(r.edges) && param(r.length) && param(r.gap) && oneOf(r.kind, ['closed', 'open']) && oneOf(r.position, ['materialInside', 'bendOutside']); + default: + return true; + } +} + +// ---- open profiles ---- + +export type ChainSeg = + | { k: 'line'; a: Vec2; b: Vec2; src: Id } + /** sweep: signed angle in radians, positive turning left (counter-clockwise). */ + | { k: 'arc'; c: Vec2; r: number; a: Vec2; b: Vec2; sweep: number; src: Id }; + +const d2 = (a: Vec2, b: Vec2) => Math.hypot(a[0] - b[0], a[1] - b[1]); + +/** + * The lines and arcs of a sketch as one open chain, in order from the end + * whose curve comes first in the sketch (so the thickness side stays put when + * the sketch is edited). An error says why the sketch is not one. + */ +export function openChain(entities: SkEntity[]): { segs: ChainSeg[] } | { error: string } { + const ix = new SketchIndex(entities); + const curves = entities.filter((e) => e.t !== 'point' && !e.construction); + if (!curves.length) return { error: 'The sketch has no lines or arcs' }; + if (curves.some((c) => c.t !== 'line' && c.t !== 'arc')) return { error: 'An open profile can only have lines and arcs' }; + const ends = curves.map((c) => (c.t === 'line' || c.t === 'arc' ? [ix.pt(c.a), ix.pt(c.b)] : []) as [Vec2, Vec2]); + let size = 0; + for (const [a, b] of ends) size = Math.max(size, Math.abs(a[0]), Math.abs(a[1]), Math.abs(b[0]), Math.abs(b[1]), d2(a, b)); + const tol = Math.max(1e-7, size * 1e-7); + const verts: Vec2[] = []; + const vertexOf = (p: Vec2) => { + const i = verts.findIndex((v) => d2(v, p) <= tol); + if (i >= 0) return i; + verts.push(p); + return verts.length - 1; + }; + const cv = ends.map(([a, b]) => [vertexOf(a), vertexOf(b)]); + if (cv.some(([a, b]) => a === b)) return { error: 'A curve of the profile has no length' }; + const incident: number[][] = verts.map(() => []); + cv.forEach(([a, b], i) => { incident[a].push(i); incident[b].push(i); }); + if (incident.some((l) => l.length > 2)) return { error: 'The open profile must be a single chain of lines and arcs without branches' }; + const tips = incident.flatMap((l, v) => (l.length === 1 ? [v] : [])); + if (tips.length !== 2) return { error: tips.length ? 'The open profile must be a single chain of lines and arcs' : 'The profile is closed' }; + // Start at the end whose curve comes first in the sketch. + let at = Math.min(incident[tips[0]][0], incident[tips[1]][0]) === incident[tips[0]][0] ? tips[0] : tips[1]; + const used = new Set(); + const segs: ChainSeg[] = []; + for (;;) { + const next = incident[at].find((i) => !used.has(i)); + if (next === undefined) break; + used.add(next); + const c = curves[next]; + const forward = cv[next][0] === at; + const [pa, pb] = forward ? ends[next] : [ends[next][1], ends[next][0]]; + if (c.t === 'line') segs.push({ k: 'line', a: pa, b: pb, src: c.id }); + else if (c.t === 'arc') { + const ctr = ix.pt(c.c); + let sweep = Math.atan2(ends[next][1][1] - ctr[1], ends[next][1][0] - ctr[0]) - Math.atan2(ends[next][0][1] - ctr[1], ends[next][0][0] - ctr[0]); + while (sweep <= 0) sweep += 2 * Math.PI; + segs.push({ k: 'arc', c: ctr, r: d2(ctr, ends[next][0]), a: pa, b: pb, sweep: forward ? sweep : -sweep, src: c.id }); + } + at = forward ? cv[next][1] : cv[next][0]; + } + if (used.size !== curves.length) return { error: 'The open profile must be a single chain of lines and arcs' }; + return { segs }; +} + +export interface OpenRun { + /** Flat x range of the straight part. */ + x0: number; + x1: number; + /** Start of the straight part in the sketch, and its direction. */ + a: Vec2; + d: Vec2; + src: Id; +} + +export interface OpenBend { + /** Flat x where the bend starts, and its flat width (bend allowance). */ + x: number; + width: number; + angle: number; + up: boolean; + radius: number; + src: Id; +} + +/** + * Unrolls an open profile: the straight parts and bends along the flat x + * axis. The sketch lies on the surface at height zl of the sheet (0 on the + * side the thickness grows from, T on the other, T/2 mid-plane); thickness + * grows to the left of the chain. Bends turning left go "up" (toward the + * material). A sharp corner gets the sheet's bend radius on its inside and + * is the virtual sharp of the sketched surface; an arc between two lines + * is a bend of its own radius. + */ +export function layoutOpenProfile(segs: ChainSeg[], p: BendParams, zl: number): { runs: OpenRun[]; bends: OpenBend[] } | { error: string } { + const T = p.thickness; + const dir = (a: Vec2, b: Vec2): Vec2 => { const l = d2(a, b); return [(b[0] - a[0]) / l, (b[1] - a[1]) / l]; }; + // Runs of collinear lines with what joins each to the next. + const runs: { a: Vec2; b: Vec2; src: Id }[] = []; + const joints: ({ k: 'sharp' } | { k: 'arc'; seg: Extract })[] = []; + for (let i = 0; i < segs.length; i++) { + const s = segs[i]; + if (s.k === 'arc') { + if (!runs.length || i === segs.length - 1 || segs[i + 1].k !== 'line') return { error: 'Arcs in an open profile must lie between two lines' }; + const prev = runs[runs.length - 1]; + const next = segs[i + 1] as Extract; + const tangent = (pt: Vec2): Vec2 => { const r: Vec2 = [(pt[0] - s.c[0]) / s.r, (pt[1] - s.c[1]) / s.r]; return s.sweep > 0 ? [-r[1], r[0]] : [r[1], -r[0]]; }; + const t0 = tangent(s.a), t1 = tangent(s.b), d0 = dir(prev.a, prev.b), d1 = dir(next.a, next.b); + if (Math.abs(t0[0] * d0[1] - t0[1] * d0[0]) > 1e-4 || t0[0] * d0[0] + t0[1] * d0[1] < 0 || Math.abs(t1[0] * d1[1] - t1[1] * d1[0]) > 1e-4 || t1[0] * d1[0] + t1[1] * d1[1] < 0) { + return { error: 'Arcs in an open profile must be tangent to the lines they join' }; + } + joints.push({ k: 'arc', seg: s }); + continue; + } + const prev = runs[runs.length - 1]; + if (prev && joints.length < runs.length) { + // Two lines meeting: one line if they go on straight, else a sharp bend. + const a = dir(prev.a, prev.b), b = dir(s.a, s.b); + if (Math.abs(a[0] * b[1] - a[1] * b[0]) < 1e-9 && a[0] * b[0] + a[1] * b[1] > 0) { prev.b = s.b; continue; } + joints.push({ k: 'sharp' }); + } + runs.push({ a: s.a, b: s.b, src: s.src }); + } + const tanHalf = (deg: number) => Math.tan((deg * Math.PI) / 360); + const bends: (OpenBend & { setback: number })[] = joints.map((j, i) => { + if (j.k === 'arc') { + const up = j.seg.sweep > 0; + return { x: 0, width: 0, angle: (Math.abs(j.seg.sweep) * 180) / Math.PI, up, radius: up ? j.seg.r - (T - zl) : j.seg.r - zl, src: j.seg.src, setback: 0 }; + } + const a = dir(runs[i].a, runs[i].b), b = dir(runs[i + 1].a, runs[i + 1].b); + const turn = Math.atan2(a[0] * b[1] - a[1] * b[0], a[0] * b[0] + a[1] * b[1]); + const angle = (Math.abs(turn) * 180) / Math.PI; + const up = turn > 0; + const R = p.radius; + return { x: 0, width: 0, angle, up, radius: R, src: runs[i].src, setback: tanHalf(angle) * (up ? R + T - zl : R + zl) }; + }); + for (const b of bends) { + if (b.angle > 179.5) return { error: 'The profile folds back on itself; the angle between lines must be less than 180 degrees' }; + if (b.radius < -1e-9) return { error: 'An arc of the profile is too small for the thickness on its inside' }; + b.radius = Math.max(0, b.radius); + b.width = bendAllowance(b.angle, b.radius, p); + if (!(b.width > 0)) return { error: 'The bend allowance must be greater than zero' }; + } + const out: OpenRun[] = []; + let x = 0; + for (let i = 0; i < runs.length; i++) { + const r = runs[i]; + const d = dir(r.a, r.b); + const sb0 = i > 0 ? bends[i - 1].setback : 0, sb1 = i < bends.length ? bends[i].setback : 0; + const L = d2(r.a, r.b) - sb0 - sb1; + if (L < 1e-6) return { error: 'A line of the profile is too short for the bend radius and thickness' }; + out.push({ x0: x, x1: x + L, a: [r.a[0] + d[0] * sb0, r.a[1] + d[1] * sb0], d, src: r.src }); + x += L; + if (i < bends.length) { bends[i].x = x; x += bends[i].width; } + } + return { runs: out, bends: bends.map(({ setback: _s, ...b }) => b) }; +} diff --git a/src/parametric/src/model/surfaces.ts b/src/parametric/src/model/surfaces.ts new file mode 100644 index 0000000000..0d905f1fe1 --- /dev/null +++ b/src/parametric/src/model/surfaces.ts @@ -0,0 +1,208 @@ +// Surface modeling features: names, parameters, references and factories. +// The geometry is built in src/kernel/surfaces.ts. + +import type { + DeleteFaceFeature, EdgeRef, FaceRef, Feature, Id, PlaneRef, SurfaceCutFeature, SurfaceExtendFeature, SurfaceExtrudeFeature, + SurfaceFillFeature, SurfaceKnitFeature, SurfaceLoftFeature, SurfaceOffsetFeature, SurfacePlanarFeature, SurfaceRevolveFeature, + SurfaceSweepFeature, SurfaceTrimFeature, ThickenFeature, +} from './types'; + +export type SurfaceFeature = + | SurfaceExtrudeFeature + | SurfaceRevolveFeature + | SurfaceSweepFeature + | SurfaceLoftFeature + | SurfacePlanarFeature + | SurfaceOffsetFeature + | SurfaceFillFeature + | SurfaceTrimFeature + | SurfaceExtendFeature + | SurfaceKnitFeature + | ThickenFeature + | SurfaceCutFeature + | DeleteFaceFeature; + +export type SurfaceFeatureType = SurfaceFeature['type']; + +export const SURFACE_LABELS: Record = { + surfaceExtrude: 'Extruded Surface', + surfaceRevolve: 'Revolved Surface', + surfaceSweep: 'Swept Surface', + surfaceLoft: 'Lofted Surface', + surfacePlanar: 'Planar Surface', + surfaceOffset: 'Offset Surface', + surfaceFill: 'Filled Surface', + surfaceTrim: 'Trim Surface', + surfaceExtend: 'Extend Surface', + surfaceKnit: 'Knit Surface', + thicken: 'Thicken', + surfaceCut: 'Cut With Surface', + deleteFace: 'Delete Face', +}; + +/** Base of the default names in the tree ("Surface-Extrude1", as other CAD systems name them). */ +export const SURFACE_BASE_NAMES: Record = { + surfaceExtrude: 'Surface-Extrude', + surfaceRevolve: 'Surface-Revolve', + surfaceSweep: 'Surface-Sweep', + surfaceLoft: 'Surface-Loft', + surfacePlanar: 'Surface-Plane', + surfaceOffset: 'Surface-Offset', + surfaceFill: 'Surface-Fill', + surfaceTrim: 'Surface-Trim', + surfaceExtend: 'Surface-Extend', + surfaceKnit: 'Surface-Knit', + thicken: 'Thicken', + surfaceCut: 'SurfaceCut', + deleteFace: 'Delete Face', +}; + +export const SURFACE_TYPES = new Set(Object.keys(SURFACE_LABELS)); + +/** The feature that made a surface body: its id before any ".n" ("f7.2" is f7's second body). */ +export const bodyFeatureOf = (body: Id): Id => body.split('.')[0]; + +export const isSurfaceFeature = (f: Feature): f is SurfaceFeature => SURFACE_TYPES.has(f.type); + +/** Surface features whose result is a surface body (shown, hidden and picked like one). */ +export function makesSurfaceBody(f: Feature): boolean { + if (!isSurfaceFeature(f)) return false; + if (f.type === 'thicken' || f.type === 'surfaceCut') return false; + if (f.type === 'surfaceKnit') return !f.solid; + if (f.type === 'deleteFace') return f.mode === 'delete'; + return true; +} + +export const SURFACE_PARAM_FIELDS = { + surfaceExtrude: [ + { path: 'depth', kind: 'length' as const, label: 'Depth' }, + { path: 'dir2.depth', kind: 'length' as const, label: 'Depth (Direction 2)' }, + ], + surfaceRevolve: [{ path: 'angle', kind: 'angle' as const, label: 'Angle' }], + surfaceOffset: [{ path: 'distance', kind: 'length' as const, label: 'Offset distance' }], + surfaceExtend: [{ path: 'distance', kind: 'length' as const, label: 'Distance' }], + surfaceKnit: [{ path: 'tolerance', kind: 'length' as const, label: 'Knit tolerance' }], + thicken: [{ path: 'thickness', kind: 'length' as const, label: 'Thickness' }], +}; + +export function surfaceIcon(f: SurfaceFeature): string { + if (f.type === 'thicken') return f.cut ? 'thickenCut' : 'thicken'; + return f.type; +} + +/** Sketches a surface feature consumes (shown nested under it in the tree). */ +export function surfaceSketches(f: SurfaceFeature): Id[] { + switch (f.type) { + case 'surfaceExtrude': + case 'surfaceRevolve': + return f.sketch ? [f.sketch] : []; + case 'surfaceSweep': + return [f.profile, f.path].filter((x): x is Id => !!x); + case 'surfaceLoft': + return f.profiles; + case 'surfacePlanar': + return f.sketch ? [f.sketch] : []; + case 'surfaceTrim': + return f.tool?.kind === 'sketch' ? [f.tool.sketch] : []; + default: + return []; + } +} + +/** Calls the visitors with every reference of a surface feature (for dependencies). */ +export function surfaceRefs(f: SurfaceFeature, visit: { name: (n: string) => void; plane: (p: PlaneRef | null | undefined) => void; axis: (a: SurfaceRevolveFeature['axis']) => void }) { + const faces = (l: FaceRef[]) => l.forEach((r) => visit.name(r.name)); + const edges = (l: EdgeRef[]) => l.forEach((r) => visit.name(r.name)); + switch (f.type) { + case 'surfaceRevolve': visit.axis(f.axis); break; + case 'surfacePlanar': edges(f.edges); break; + case 'surfaceOffset': faces(f.faces); break; + case 'surfaceFill': edges(f.edges); break; + case 'surfaceTrim': + faces(f.faces); + if (f.tool?.kind === 'plane') visit.plane(f.tool.plane); + else if (f.tool?.kind === 'surface') visit.name(f.tool.face.name); + break; + case 'surfaceExtend': edges(f.edges); break; + case 'surfaceKnit': faces(f.faces); break; + case 'thicken': faces(f.faces); break; + case 'surfaceCut': if (f.face) visit.name(f.face.name); break; + case 'deleteFace': faces(f.faces); break; + default: break; + } +} + +// ---- validation of files ---- + +const object = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const id = (v: unknown): v is string => typeof v === 'string' && v.length > 0; +const named = (v: unknown) => object(v) && typeof v.name === 'string'; +const list = (v: unknown, item: (x: unknown) => boolean) => Array.isArray(v) && v.every(item); +const optId = (v: unknown) => v == null || typeof v === 'string'; +const vec3 = (v: unknown) => Array.isArray(v) && v.length === 3 && v.every((c) => Number.isFinite(c)); +const param = (v: unknown) => (typeof v === 'number' && Number.isFinite(v)) || typeof v === 'string'; +const oneOf = (v: unknown, values: string[]) => typeof v === 'string' && values.includes(v); + +/** + * Whether a surface feature from a file has the fields the rebuild, the tree + * and the panels walk. `plane` and `axis` are the validators of the other features. + */ +export function validSurfaceFeature(f: Feature, plane: (v: unknown) => boolean, axis: (v: unknown) => boolean): boolean { + const r = f as unknown as Record; + switch (f.type) { + case 'surfaceExtrude': + return typeof r.sketch === 'string' && oneOf(r.end, ['blind', 'midPlane']) && param(r.depth) + && (r.dir2 == null || (object(r.dir2) && param(r.dir2.depth))); + case 'surfaceRevolve': + return typeof r.sketch === 'string' && axis(r.axis) && oneOf(r.end, ['blind', 'midPlane']) && param(r.angle); + case 'surfaceSweep': + return optId(r.profile) && optId(r.path); + case 'surfaceLoft': + return list(r.profiles, id); + case 'surfacePlanar': + return optId(r.sketch) && list(r.edges, named); + case 'surfaceOffset': + return list(r.faces, named) && param(r.distance); + case 'surfaceFill': + return list(r.edges, named); + case 'surfaceTrim': { + const t = r.tool; + const tool = t == null || (object(t) && ( + (t.kind === 'sketch' && typeof t.sketch === 'string') || (t.kind === 'plane' && t.plane != null && plane(t.plane)) || (t.kind === 'surface' && named(t.face)))); + return list(r.faces, named) && tool && list(r.keep, vec3); + } + case 'surfaceExtend': + return list(r.edges, named) && param(r.distance) && oneOf(r.mode, ['same', 'linear']); + case 'surfaceKnit': + return list(r.faces, named) && param(r.tolerance); + case 'thicken': + return list(r.faces, named) && param(r.thickness) && oneOf(r.side, ['front', 'back', 'both']); + case 'surfaceCut': + return r.face == null || named(r.face); + case 'deleteFace': + return list(r.faces, named) && oneOf(r.mode, ['delete', 'patch']); + default: + return true; + } +} + +// ---- factories ---- + +export function newSurfaceFeature(type: SurfaceFeatureType, fid: Id, name: string, size: number): SurfaceFeature { + const base = { id: fid, name }; + switch (type) { + case 'surfaceExtrude': return { ...base, type, sketch: '', end: 'blind', depth: size, flip: false, dir2: null }; + case 'surfaceRevolve': return { ...base, type, sketch: '', axis: null, end: 'blind', angle: 360, flip: false }; + case 'surfaceSweep': return { ...base, type, profile: null, path: null }; + case 'surfaceLoft': return { ...base, type, profiles: [], ruled: false }; + case 'surfacePlanar': return { ...base, type, sketch: null, edges: [] }; + case 'surfaceOffset': return { ...base, type, faces: [], distance: Math.max(size / 10, 1), flip: false }; + case 'surfaceFill': return { ...base, type, edges: [] }; + case 'surfaceTrim': return { ...base, type, faces: [], tool: null, keep: [], flip: false }; + case 'surfaceExtend': return { ...base, type, edges: [], distance: Math.max(size / 5, 1), mode: 'same' }; + case 'surfaceKnit': return { ...base, type, faces: [], tolerance: 0.01, solid: false }; + case 'thicken': return { ...base, type, faces: [], thickness: Math.max(size / 20, 1), side: 'front', cut: false }; + case 'surfaceCut': return { ...base, type, face: null, flip: false }; + case 'deleteFace': return { ...base, type, faces: [], mode: 'delete' }; + } +} diff --git a/src/parametric/src/model/types.ts b/src/parametric/src/model/types.ts index f7601e2496..7bdcf16479 100644 --- a/src/parametric/src/model/types.ts +++ b/src/parametric/src/model/types.ts @@ -4,6 +4,7 @@ // display unit system. import type { Vec2, Vec3, Frame } from '../math/vec'; +import type { BaseFlangeFeature, EdgeFlangeFeature, HemFeature, SketchedBendFeature } from './sheetmetal'; export type Id = string; @@ -336,6 +337,216 @@ export interface ImportFeature extends FeatureBase { fileName: string; } +// ---- Surfaces ---- +// Surface features make (or change) surface bodies: open sheets kept apart +// from the solid, each named after the feature that last made it. Thicken, +// Knit (as a solid) and Cut With Surface turn them into solid geometry. + +export interface SurfaceExtrudeFeature extends FeatureBase { + type: 'surfaceExtrude'; + sketch: Id; + end: 'blind' | 'midPlane'; + depth: Param; + flip: boolean; + /** Second direction (Blind), or null. */ + dir2: { depth: Param } | null; +} + +export interface SurfaceRevolveFeature extends FeatureBase { + type: 'surfaceRevolve'; + sketch: Id; + /** null picks the sketch's first centerline. */ + axis: AxisRef | null; + end: 'blind' | 'midPlane'; + angle: Param; + flip: boolean; +} + +export interface SurfaceSweepFeature extends FeatureBase { + type: 'surfaceSweep'; + profile: Id | null; + path: Id | null; +} + +export interface SurfaceLoftFeature extends FeatureBase { + type: 'surfaceLoft'; + profiles: Id[]; + ruled: boolean; +} + +/** A planar surface from the closed regions of a sketch, or from a closed loop of edges. */ +export interface SurfacePlanarFeature extends FeatureBase { + type: 'surfacePlanar'; + sketch: Id | null; + edges: EdgeRef[]; +} + +/** Offset copies of faces (of the solid or of surfaces); a distance of zero copies them. */ +export interface SurfaceOffsetFeature extends FeatureBase { + type: 'surfaceOffset'; + faces: FaceRef[]; + distance: Param; + flip: boolean; +} + +/** A patch filling a closed boundary of edges. */ +export interface SurfaceFillFeature extends FeatureBase { + type: 'surfaceFill'; + edges: EdgeRef[]; +} + +export type TrimTool = + | { kind: 'sketch'; sketch: Id } + | { kind: 'plane'; plane: PlaneRef } + | { kind: 'surface'; face: FaceRef }; + +/** Trims surface bodies with a sketch, plane or another surface, keeping the pieces picked (or one side). */ +export interface SurfaceTrimFeature extends FeatureBase { + type: 'surfaceTrim'; + /** A face of each surface body to trim. */ + faces: FaceRef[]; + tool: TrimTool | null; + /** Points on the pieces to keep; empty keeps the side the tool's normal points to (flip: the other). */ + keep: Vec3[]; + flip: boolean; +} + +/** Extends a surface past its boundary edges. */ +export interface SurfaceExtendFeature extends FeatureBase { + type: 'surfaceExtend'; + edges: EdgeRef[]; + distance: Param; + /** same: the surface carries on as it is; linear: tangent to it, straight. */ + mode: 'same' | 'linear'; +} + +/** Sews surface bodies into one, and into a solid when they close a volume. */ +export interface SurfaceKnitFeature extends FeatureBase { + type: 'surfaceKnit'; + /** A face of each surface body to knit. */ + faces: FaceRef[]; + tolerance: Param; + solid: boolean; +} + +/** Turns a surface body into a solid of a thickness: added to the solid body, or cut from it. */ +export interface ThickenFeature extends FeatureBase { + type: 'thicken'; + /** A face of the surface body to thicken. */ + faces: FaceRef[]; + thickness: Param; + /** front: along the surface normal; back: against it; both: half each way. */ + side: 'front' | 'back' | 'both'; + cut: boolean; +} + +/** Cuts the solid body with a surface, removing the material on the side its normal points to (flip: the other). */ +export interface SurfaceCutFeature extends FeatureBase { + type: 'surfaceCut'; + face: FaceRef | null; + flip: boolean; +} + +/** Removes faces from the solid, leaving a surface body (or patching the hole). */ +export interface DeleteFaceFeature extends FeatureBase { + type: 'deleteFace'; + faces: FaceRef[]; + mode: 'delete' | 'patch'; +} + +// ---- Weldments ---- + +/** A line or arc of a sketch, used as the path of a structural member. */ +export interface SegmentRef { + sketch: Id; + entity: Id; +} + +/** Segments whose members are joined by the group's corner treatment. */ +export interface MemberGroup { + segments: SegmentRef[]; +} + +export type CornerTreatment = 'miter' | 'butt1' | 'butt2'; + +export interface StructuralMemberFeature extends FeatureBase { + type: 'structuralMember'; + /** Profile library keys (see weldment-profiles.ts). */ + standard: string; + profile: string; + size: string; + groups: MemberGroup[]; + /** Profile rotation about the member axis, degrees. */ + rotation: Param; + mirror: boolean; + /** Profile point placed on the sketch segment. */ + pierce: string; + /** Joints between members of one group. */ + corner: CornerTreatment; + /** Gap at joints within a group. */ + gap: Param; + /** Members of later groups are trimmed or extended to members of earlier groups. */ + trimGroups: boolean; + /** Gap where a member is trimmed to a member of another group. */ + gap2: Param; +} + +/** A member of a structural member feature: its feature and segment ("sketch/entity"). */ +export interface MemberRef { + feature: Id; + member: string; +} + +export interface TrimExtendFeature extends FeatureBase { + type: 'trimExtend'; + /** Members to trim or extend. */ + members: MemberRef[]; + /** Planar faces, or members, to trim to. */ + boundary: 'faces' | 'members'; + faces: FaceRef[]; + boundaryMembers: MemberRef[]; + /** Members that stop short of the boundary are extended to it. */ + allowExtension: boolean; + /** Members trimmed to members follow their surface (coped) instead of a plane. */ + coped: boolean; + gap: Param; +} + +export interface EndCapFeature extends FeatureBase { + type: 'endCap'; + /** End faces of tube or pipe members. */ + faces: FaceRef[]; + thickness: Param; + /** Distance the cap's edge is set in from the member's edge. */ + offset: Param; + /** Outward adds the cap past the end; inward fits it inside the tube. */ + inward: boolean; +} + +export interface GussetFeature extends FeatureBase { + type: 'gusset'; + /** Two planar faces meeting at a corner. */ + faces: FaceRef[]; + shape: 'triangular' | 'polygonal'; + d1: Param; + d2: Param; + /** Polygonal: length of the straight edges at the ends of the legs. */ + d3: Param; + thickness: Param; + /** Where the plate lies across its thickness. */ + location: 'center' | 'side1' | 'side2'; + /** Corner clip for the weld at the inner corner (0 for none). */ + chamfer: Param; +} + +/** A solid fillet weld: a triangular bead along inside corner edges. */ +export interface WeldBeadFeature extends FeatureBase { + type: 'weldBead'; + edges: EdgeRef[]; + /** Leg length of the weld. */ + size: Param; +} + export type Feature = | SketchFeature | ExtrudeFeature @@ -351,7 +562,29 @@ export type Feature = | LoftFeature | SweepFeature | DraftFeature - | ImportFeature; + | ImportFeature + | SurfaceExtrudeFeature + | SurfaceRevolveFeature + | SurfaceSweepFeature + | SurfaceLoftFeature + | SurfacePlanarFeature + | SurfaceOffsetFeature + | SurfaceFillFeature + | SurfaceTrimFeature + | SurfaceExtendFeature + | SurfaceKnitFeature + | ThickenFeature + | SurfaceCutFeature + | DeleteFaceFeature + | BaseFlangeFeature + | EdgeFlangeFeature + | SketchedBendFeature + | HemFeature + | StructuralMemberFeature + | TrimExtendFeature + | EndCapFeature + | GussetFeature + | WeldBeadFeature; export type FeatureType = Feature['type']; @@ -391,7 +624,7 @@ export interface PartDocument { // ---- Drawings ---- -export type SheetSize = 'A4' | 'A3' | 'A2' | 'A1' | 'Letter' | 'Tabloid'; +export type SheetSize = 'A4' | 'A3' | 'A2' | 'A1' | 'Letter' | 'Tabloid' | 'ANSI C' | 'ANSI D'; export type DrawingViewKind = 'front' | 'back' | 'left' | 'right' | 'top' | 'bottom' | 'isometric'; export interface DrawingView { @@ -403,8 +636,146 @@ export interface DrawingView { hidden: boolean; /** Show overall width and height dimensions. */ dims: boolean; + /** + * What the view shows (absent: 'model', a standard view of the part from `kind`). + * Projected, section and auxiliary views look at the part from beside their parent + * view; a detail view magnifies a circle of its parent. For these, `kind` is only the + * parent's kind at creation and the direction comes from the parent. + */ + type?: DrawingViewType; + /** The view this one was made from (projected, section, detail and auxiliary views). */ + parent?: Id; + /** Projected views: on which side of the parent it is placed. */ + side?: DrawingSide; + /** + * Section and auxiliary views: the cutting (or folding) line on the parent, in the parent's + * view coordinates (model millimetres, y down): [x1, y1, x2, y2]. The view lies on the side + * of the line's left normal (direction (-(y2-y1), x2-x1) on paper with y down). + */ + line?: [number, number, number, number]; + /** Detail views: the circle on the parent, in the parent's view coordinates [cx, cy, r]. */ + circle?: [number, number, number]; + /** Own scale (model and detail views); absent: the sheet's (a detail view: twice its parent's). */ + scale?: number; + /** Letter of a section or detail view, or a caption replacing the view's label. */ + label?: string; + /** Smooth (tangent) edges shown (absent: shown). */ + tangent?: boolean; + /** Centre marks on circles seen end-on and centrelines of holes seen side-on (absent: off). */ + centerMarks?: boolean; + /** + * Where the view's geometry comes from (absent: this part). Assembly drawings name + * 'assembly' (components where the mates put them) or 'assembly:exploded' (the exploded + * view); see src/drawing/source.ts. A flat pattern view ('flat' type) uses the sheet + * metal part's flat pattern instead. + */ + source?: string; +} + +export type DrawingViewType = 'model' | 'projected' | 'section' | 'detail' | 'auxiliary' | 'flat'; +export type DrawingSide = 'left' | 'right' | 'above' | 'below'; + +/** A reference to model geometry seen in a view: a named model edge (as the kernel names them). */ +export interface DrawingRef { + /** Model edge name; an assembly source prefixes the component path. */ + edge: string; + /** The edge itself, its start or end point, or the centre of a circle or arc. */ + at: 'edge' | 'start' | 'end' | 'center'; +} + +export type DrawingDimKind = 'horizontal' | 'vertical' | 'aligned' | 'radius' | 'diameter' | 'angle'; + +interface DrawingAnnotationBase { + id: Id; + /** The view it belongs to (it moves with the view and is deleted with it). */ + view?: Id; +} + +/** A dimension measured from model geometry in a view: it follows the model as it changes. */ +export interface DrawingDimension extends DrawingAnnotationBase { + type: 'dimension'; + view: Id; + kind: DrawingDimKind; + /** One or two references (a line, a circle, two points, two lines...). */ + refs: DrawingRef[]; + /** Where the value sits, in the view's coordinates (model millimetres, y down). */ + at: [number, number]; + /** Decimal places (absent: the document's). */ + decimals?: number; + /** Text before the value, e.g. "2X ". */ + prefix?: string; +} + +/** Text on the sheet, with an optional leader arrow. */ +export interface DrawingNote extends DrawingAnnotationBase { + type: 'note'; + text: string; + /** Text position: in the view's coordinates with a view, else in sheet millimetres. */ + at: [number, number]; + /** Arrow tip of the leader (same coordinates as `at`). */ + leader?: [number, number]; + /** Text height in sheet millimetres (absent: 3.5). */ + size?: number; +} + +export interface DrawingCenterMark extends DrawingAnnotationBase { + type: 'centerMark'; + view: Id; + ref: DrawingRef; +} + +/** A centreline midway between two parallel edges (the sides of a cylinder or slot). */ +export interface DrawingCenterline extends DrawingAnnotationBase { + type: 'centerline'; + view: Id; + refs: [DrawingRef, DrawingRef]; +} + +/** Size and kind of the hole whose circle is referenced, with a leader. */ +export interface DrawingHoleCallout extends DrawingAnnotationBase { + type: 'holeCallout'; + view: Id; + ref: DrawingRef; + at: [number, number]; } +/** + * Item balloon: a circle with the item number and a leader to an edge of a component (an + * assembly drawing: its bill of materials row) or of a structural member (a weldment: its + * cut list item). + */ +export interface DrawingBalloon extends DrawingAnnotationBase { + type: 'balloon'; + view: Id; + ref: DrawingRef; + at: [number, number]; + /** Item number override (absent: the BOM row of the component the edge belongs to). */ + item?: number; + /** Where the leader meets a straight edge, as a fraction of it from its start (absent: its middle). */ + t?: number; +} + +/** Bill of materials table of a view's source (rows come from the source, so it follows the assembly). */ +export interface DrawingBom extends DrawingAnnotationBase { + type: 'bom'; + /** Top left corner on the sheet, in millimetres (with anchor 'bottomRight': its bottom right corner). */ + at: [number, number]; + /** The source whose rows it lists (absent: that of the first view). */ + source?: string; + /** Which corner `at` is (absent: the top left); a table on the title block grows upward from it. */ + anchor?: 'bottomRight'; +} + +/** Cut list table of a weldment part (rows from the part's structural members as built). */ +export interface DrawingCutList extends DrawingAnnotationBase { + type: 'cutList'; + /** Top left corner on the sheet, in millimetres (with anchor 'bottomRight': its bottom right corner). */ + at: [number, number]; + anchor?: 'bottomRight'; +} + +export type DrawingAnnotation = DrawingDimension | DrawingNote | DrawingCenterMark | DrawingCenterline | DrawingHoleCallout | DrawingBalloon | DrawingBom | DrawingCutList; + export interface DrawingDoc { sheet: SheetSize; landscape: boolean; @@ -414,4 +785,14 @@ export interface DrawingDoc { title: string; drawnBy: string; notes: string; + /** Annotations: dimensions, notes, centre marks... (absent: none). */ + annotations?: DrawingAnnotation[]; + /** Projection angle of projected views and of the title block's symbol (absent: third angle). */ + projection?: 'third' | 'first'; + /** + * The title block: 'full' adds the projection symbol, revision and sheet number + * (absent: the basic one of drawings made before it existed). + */ + titleBlock?: 'basic' | 'full'; + revision?: string; } diff --git a/src/parametric/src/model/units.ts b/src/parametric/src/model/units.ts index 9ad3e8ffd8..62e907e839 100644 --- a/src/parametric/src/model/units.ts +++ b/src/parametric/src/model/units.ts @@ -43,10 +43,14 @@ export function formatNumber(v: number, decimals: number): string { return /^-0\.?0*$/.test(s) ? s.slice(1) : s; } -/** Shortest round-trippable text for an editable value (no forced decimals). */ +/** + * Shortest text for an editable value (no forced decimals), to 15 significant + * digits: a value converted between units reads as typed (0.048 in, not the + * 0.04800000000000001 that 1.2192 mm / 25.4 gives) and keeps its precision. + */ export function formatEditable(v: number): string { if (!Number.isFinite(v)) return '0'; - return v.toString(); + return Number(v.toPrecision(15)).toString(); } export function formatLength(mm: number, units: UnitSystem, decimals: number, withUnit = false): string { diff --git a/src/parametric/src/model/validate-drawing.ts b/src/parametric/src/model/validate-drawing.ts index 266ab7a035..0685bfef9d 100644 --- a/src/parametric/src/model/validate-drawing.ts +++ b/src/parametric/src/model/validate-drawing.ts @@ -1,22 +1,103 @@ import type { DrawingDoc } from './types'; -const sheets = new Set(['A4', 'A3', 'A2', 'A1', 'Letter', 'Tabloid']); +const sheets = new Set(['A4', 'A3', 'A2', 'A1', 'Letter', 'Tabloid', 'ANSI C', 'ANSI D']); const kinds = new Set(['front', 'back', 'left', 'right', 'top', 'bottom', 'isometric']); +const types = new Set(['model', 'projected', 'section', 'detail', 'auxiliary', 'flat']); +const sides = new Set(['left', 'right', 'above', 'below']); +const dimKinds = new Set(['horizontal', 'vertical', 'aligned', 'radius', 'diameter', 'angle']); +const refAts = new Set(['edge', 'start', 'end', 'center']); const object = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); +const optional = (v: unknown, check: (x: unknown) => boolean) => v === undefined || check(v); +const str = (v: unknown) => typeof v === 'string'; +const bool = (v: unknown) => typeof v === 'boolean'; +const nums = (v: unknown, n: number) => Array.isArray(v) && v.length === n && v.every(finite); +const point = (v: unknown) => nums(v, 2); +const ref = (v: unknown) => object(v) && typeof v.edge === 'string' && typeof v.at === 'string' && refAts.has(v.at); -/** Check the sheet and every view before a file can replace the open document. */ +/** Check the sheet, every view and every annotation before a file can replace the open document. */ export function validDrawing(value: unknown): value is DrawingDoc { if (!object(value) || typeof value.sheet !== 'string' || !sheets.has(value.sheet) || typeof value.landscape !== 'boolean' || !finite(value.scale) || value.scale <= 0 || typeof value.title !== 'string' || typeof value.drawnBy !== 'string' || typeof value.notes !== 'string' || !Array.isArray(value.views)) return false; + if (!optional(value.projection, (p) => p === 'third' || p === 'first') + || !optional(value.titleBlock, (t) => t === 'basic' || t === 'full') + || !optional(value.revision, str)) return false; const ids = new Set(); for (const v of value.views) { if (!object(v) || typeof v.id !== 'string' || !v.id || ids.has(v.id) || typeof v.kind !== 'string' || !kinds.has(v.kind) || !finite(v.x) || !finite(v.y) || typeof v.hidden !== 'boolean' || typeof v.dims !== 'boolean') return false; + if (!optional(v.type, (t) => typeof t === 'string' && types.has(t)) + || !optional(v.parent, (p) => typeof p === 'string' && !!p) + || !optional(v.side, (s) => typeof s === 'string' && sides.has(s)) + || !optional(v.line, (l) => nums(l, 4) && ((l as number[])[0] !== (l as number[])[2] || (l as number[])[1] !== (l as number[])[3])) + || !optional(v.circle, (c) => nums(c, 3) && (c as number[])[2] > 0) + || !optional(v.scale, (s) => finite(s) && s > 0) + || !optional(v.label, str) || !optional(v.tangent, bool) || !optional(v.centerMarks, bool) || !optional(v.source, str)) return false; + // A flat pattern view stands alone (its geometry is the flat pattern, not a direction). + if (v.type === 'flat' && v.parent !== undefined) return false; + // A view made from another names it, and what defines it. + if (v.type && v.type !== 'model' && v.type !== 'flat') { + if (typeof v.parent !== 'string') return false; + if ((v.type === 'section' || v.type === 'auxiliary') && !v.line) return false; + if (v.type === 'detail' && !v.circle) return false; + } ids.add(v.id); } + // Parents exist (a view whose parent is missing could not be drawn or edited). + for (const v of value.views as Record[]) if (typeof v.parent === 'string' && (!ids.has(v.parent) || v.parent === v.id)) return false; + // Nor do views made from each other in a loop. + const parentOf = new Map((value.views as Record[]).map((v) => [v.id as string, typeof v.parent === 'string' ? v.parent : undefined])); + const rooted = new Set(); + for (const id of ids) { + const chain = new Set(); + for (let p: string | undefined = id; p !== undefined && !rooted.has(p); p = parentOf.get(p)) { + if (chain.has(p)) return false; + chain.add(p); + } + for (const p of chain) rooted.add(p); + } + // Only a detail view can be made from a flat pattern view (it has no direction to project from). + const flat = new Set((value.views as Record[]).filter((v) => v.type === 'flat').map((v) => v.id)); + for (const v of value.views as Record[]) if (typeof v.parent === 'string' && flat.has(v.parent) && v.type !== 'detail') return false; + if (value.annotations !== undefined) { + if (!Array.isArray(value.annotations)) return false; + const aids = new Set(); + for (const a of value.annotations) { + if (!object(a) || typeof a.id !== 'string' || !a.id || aids.has(a.id)) return false; + aids.add(a.id); + if (!optional(a.view, (v) => typeof v === 'string' && ids.has(v))) return false; + switch (a.type) { + case 'dimension': + if (typeof a.view !== 'string' || typeof a.kind !== 'string' || !dimKinds.has(a.kind) || !Array.isArray(a.refs) || a.refs.length < 1 || a.refs.length > 2 + || !a.refs.every(ref) || !point(a.at) || !optional(a.decimals, (n) => Number.isInteger(n) && (n as number) >= 0 && (n as number) <= 8) || !optional(a.prefix, str)) return false; + break; + case 'note': + if (typeof a.text !== 'string' || !point(a.at) || !optional(a.leader, point) || !optional(a.size, (n) => finite(n) && (n as number) > 0)) return false; + break; + case 'centerMark': + if (typeof a.view !== 'string' || !ref(a.ref)) return false; + break; + case 'centerline': + if (typeof a.view !== 'string' || !Array.isArray(a.refs) || a.refs.length !== 2 || !a.refs.every(ref)) return false; + break; + case 'holeCallout': + case 'balloon': + if (typeof a.view !== 'string' || !ref(a.ref) || !point(a.at) || !optional(a.item, (n) => Number.isInteger(n) && (n as number) > 0) + || !optional(a.t, (n) => finite(n) && (n as number) >= 0 && (n as number) <= 1)) return false; + break; + case 'bom': + if (!point(a.at) || !optional(a.source, str) || !optional(a.anchor, (x) => x === 'bottomRight')) return false; + break; + case 'cutList': + if (!point(a.at) || !optional(a.anchor, (x) => x === 'bottomRight')) return false; + break; + default: + return false; + } + } + } return true; } diff --git a/src/parametric/src/model/validate-feature.ts b/src/parametric/src/model/validate-feature.ts index ef46839a02..dc97aa7d4f 100644 --- a/src/parametric/src/model/validate-feature.ts +++ b/src/parametric/src/model/validate-feature.ts @@ -3,10 +3,42 @@ // and references, so a missing list or a reference without a name broke the // app after the file had replaced the open document. import type { Feature } from './types'; +import { isSurfaceFeature, validSurfaceFeature } from './surfaces'; +import { validSheetMetalFeature } from './sheetmetal'; const object = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const id = (v: unknown): v is string => typeof v === 'string' && v.length > 0; const named = (v: unknown) => object(v) && typeof v.name === 'string'; +const num = (v: unknown) => typeof v === 'number' && Number.isFinite(v); +// Face and edge references: a name, and a geometric signature that panels show +// ("Edge (line)") and the rebuild falls back on to tell split faces apart. A +// reference whose signature is missing or partly damaged still opens: the +// missing values are filled with neutral ones (no type, no position), so the +// panel says "Edge" and the rebuild finds the reference by its name, or says it +// is gone. Only a reference or signature that is not an object is refused. +function sigOf(v: unknown): Record | null { + if (!named(v)) return null; + const r = v as Record; + if (r.sig == null) r.sig = {}; + return object(r.sig) ? r.sig : null; +} +function faceRef(v: unknown): boolean { + const s = sigOf(v); + if (!s) return false; + if (typeof s.type !== 'string') s.type = ''; + if (!vec3(s.c)) s.c = [0, 0, 0]; + if (!num(s.area)) s.area = 0; + if (s.n != null && !vec3(s.n)) delete s.n; + return true; +} +function edgeRef(v: unknown): boolean { + const s = sigOf(v); + if (!s) return false; + if (typeof s.type !== 'string') s.type = ''; + if (!vec3(s.m)) s.m = [0, 0, 0]; + if (!num(s.len)) s.len = 0; + return true; +} const list = (v: unknown, item: (x: unknown) => boolean) => Array.isArray(v) && v.every(item); // A feature's own sketch may be '' (a panel or the Assistant creates it before a // sketch is picked); the rebuild reports that feature instead of failing the file. @@ -17,24 +49,46 @@ function plane(v: unknown): boolean { if (!object(v)) return false; if (v.kind === 'base') return ['front', 'top', 'right'].includes(String(v.plane)); if (v.kind === 'feature') return id(v.id); - return v.kind === 'face' && named(v.face) && (v.x == null || vec3(v.x)); + return v.kind === 'face' && faceRef(v.face) && (v.x == null || vec3(v.x)); } -const vec3 = (v: unknown) => Array.isArray(v) && v.length === 3 && v.every((c) => Number.isFinite(c)); +function vec3(v: unknown): boolean { + return Array.isArray(v) && v.length === 3 && v.every((c) => Number.isFinite(c)); +} function axis(v: unknown): boolean { if (v == null) return true; if (!object(v)) return false; if (v.kind === 'base') return ['x', 'y', 'z'].includes(String(v.axis)); - if (v.kind === 'edge') return named(v.edge); - if (v.kind === 'face') return named(v.face); + if (v.kind === 'edge') return edgeRef(v.edge); + if (v.kind === 'face') return faceRef(v.face); return v.kind === 'sketchLine' && id(v.sketch) && id(v.entity); } const patternDir = (v: unknown) => object(v) && axis(v.ref); +// Weldments: segments of layout sketches and members of structural member features. +const segment = (v: unknown) => object(v) && id(v.sketch) && id(v.entity); +const group = (v: unknown) => object(v) && list(v.segments, segment); +const memberRef = (v: unknown) => object(v) && id(v.feature) && typeof v.member === 'string'; +const text = (v: unknown) => typeof v === 'string'; +const oneOf = (v: unknown, values: string[]) => values.includes(String(v)); + +/** + * The face and edge references of any feature type (every "faces" and "edges" + * list, and a single "face"), with damaged signatures repaired in place. + */ +function refsValid(r: Record): boolean { + if (Array.isArray(r.edges) && !r.edges.every(edgeRef)) return false; + if (Array.isArray(r.faces) && !r.faces.every(faceRef)) return false; + if (r.face != null && !faceRef(r.face)) return false; + return !(object(r.tool) && r.tool.face != null && !faceRef(r.tool.face)); +} + export function validFeature(f: Feature): boolean { const r = f as unknown as Record; + if (!refsValid(r)) return false; + if (isSurfaceFeature(f)) return validSurfaceFeature(f, plane, axis); switch (f.type) { case 'extrude': case 'hole': @@ -60,6 +114,21 @@ export function validFeature(f: Feature): boolean { return list(r.profiles, id); case 'sweep': return (r.profile == null || id(r.profile)) && (r.path == null || id(r.path)); + case 'baseFlange': + case 'edgeFlange': + case 'sketchedBend': + case 'hem': + return validSheetMetalFeature(r); + case 'structuralMember': + return text(r.standard) && text(r.profile) && text(r.size) && text(r.pierce) && list(r.groups, group) && oneOf(r.corner, ['miter', 'butt1', 'butt2']); + case 'trimExtend': + return list(r.members, memberRef) && list(r.boundaryMembers, memberRef) && list(r.faces, named) && oneOf(r.boundary, ['faces', 'members']); + case 'endCap': + return list(r.faces, named); + case 'gusset': + return list(r.faces, named) && oneOf(r.shape, ['triangular', 'polygonal']) && oneOf(r.location, ['center', 'side1', 'side2']); + case 'weldBead': + return list(r.edges, named); default: return true; } diff --git a/src/parametric/src/model/weldment-profiles.ts b/src/parametric/src/model/weldment-profiles.ts new file mode 100644 index 0000000000..21b9e62309 --- /dev/null +++ b/src/parametric/src/model/weldment-profiles.ts @@ -0,0 +1,497 @@ +// Weldment profile library: cross-sections of standard structural shapes, +// generated in code from their standard dimensions (no profile files are +// copied from any product). Lengths are millimetres; inch sizes are +// converted exactly (25.4 mm/in). +// +// Dimension sources: +// - ISO (metric) hollow sections: EN 10219-2 (cold formed welded structural +// hollow sections). Square and rectangular tubes use the corner radii the +// standard gives for calculating section properties: outside radius 2t, +// inside radius t (t <= 6 mm); 2.5t / 1.5t (6 < t <= 10 mm); 3t / 2t above. +// Pipes: outside diameters of EN 10220 / EN 10219-2. +// - ISO angles: EN 10056-1 (equal leg angles, root radius r1, toe radius r2). +// - ISO channels: EN 10279 parallel flange channels (UPE), root radius r. +// - ISO I-beams: EN 10365 (IPE and HE A), root radius r. +// - ISO flat bar: EN 10058; round bar: EN 10060. +// - ANSI (inch) HSS: ASTM A500 sizes, modelled with the nominal wall t and an +// outside corner radius of 2t, inside radius t (the AISC Steel Construction +// Manual's basis for HSS section properties). +// - ANSI pipe: ASME B36.10M standard weight (Sch 40) outside diameter and wall. +// - ANSI angles: ASTM A6 / AISC Manual leg and thickness sizes. A6 does not fix +// the root and toe radii, so they are modelled with square corners. +// - ANSI channels: AISC Manual American Standard channels (C), depth d, flange +// width bf, web tw and average flange thickness tf on the standard 1:6 +// (16 2/3 %) inner flange slope, without fillets. +// - ANSI W shapes: AISC Manual (d, bf, tw, tf, and the fillet radius k_des - tf). +// - ANSI flat and round bar: common ASTM A36 bar sizes. + +export type WeldStandard = 'iso' | 'ansi'; +export type WeldProfileType = 'squareTube' | 'rectTube' | 'pipe' | 'angle' | 'channel' | 'beam' | 'flatBar' | 'roundBar'; + +export const WELD_STANDARDS: { value: WeldStandard; label: string }[] = [ + { value: 'iso', label: 'ISO (metric)' }, + { value: 'ansi', label: 'ANSI (inch)' }, +]; + +export const WELD_TYPES: { value: WeldProfileType; label: string }[] = [ + { value: 'squareTube', label: 'Square tube' }, + { value: 'rectTube', label: 'Rectangular tube' }, + { value: 'pipe', label: 'Pipe' }, + { value: 'angle', label: 'Angle' }, + { value: 'channel', label: 'Channel' }, + { value: 'beam', label: 'I/W-beam' }, + { value: 'flatBar', label: 'Flat bar' }, + { value: 'roundBar', label: 'Round bar' }, +]; + +/** A piece of a profile outline: a line, or an arc from angle a0 to a1 (radians; a1 < a0 runs clockwise). */ +export type PSeg = + | { k: 'line'; a: [number, number]; b: [number, number] } + | { k: 'arc'; c: [number, number]; r: number; a0: number; a1: number }; + +/** Outer loop counter-clockwise, holes clockwise. */ +export interface ProfileShape { + outer: PSeg[]; + holes: PSeg[][]; +} + +/** Dimensions of one size, in millimetres. */ +export interface ProfileDims { + /** Hollow sections: width B, height H, wall t. Pipe and round bar: D (and t). */ + B?: number; H?: number; t?: number; D?: number; + /** Open sections: depth h, flange or leg width b, web tw, flange tf, root radius r, toe radius r2. */ + h?: number; b?: number; tw?: number; tf?: number; r?: number; r2?: number; + /** Channels with sloped inner flange faces (the slope, as rise per run). */ + slope?: number; + /** Outside and inside corner radius of a hollow section. */ + ro?: number; ri?: number; +} + +export interface ProfileSize { + /** Key stored in the part file. */ + id: string; + /** Short size label (the combobox entry). */ + label: string; + /** Cut list description, e.g. "SQ TUBE 40 x 40 x 3". */ + desc: string; + dims: ProfileDims; +} + +const IN = 25.4; + +/** Corner radii of EN 10219-2 cold formed hollow sections. */ +function en10219Radii(t: number): { ro: number; ri: number } { + if (t <= 6) return { ro: 2 * t, ri: t }; + if (t <= 10) return { ro: 2.5 * t, ri: 1.5 * t }; + return { ro: 3 * t, ri: 2 * t }; +} + +const n = (v: number) => String(Math.round(v * 1000) / 1000); + +/** Inch fractions as written on sizes: 0.25 -> "1/4", 1.5 -> "1-1/2". */ +function frac(v: number): string { + const whole = Math.floor(v + 1e-9); + const rest = v - whole; + if (rest < 1e-9) return String(whole); + for (const d of [2, 4, 8, 16, 32]) { + const k = Math.round(rest * d); + if (Math.abs(rest * d - k) < 1e-6) { + const g = gcd(k, d); + const f = `${k / g}/${d / g}`; + return whole ? `${whole}-${f}` : f; + } + } + return n(v); +} + +function gcd(a: number, b: number): number { + return b ? gcd(b, a % b) : a; +} + +function isoSquare(B: number, t: number): ProfileSize { + return { id: `${n(B)}x${n(B)}x${n(t)}`, label: `${n(B)} x ${n(B)} x ${n(t)}`, desc: `SQ TUBE ${n(B)} x ${n(B)} x ${n(t)}`, dims: { B, H: B, t, ...en10219Radii(t) } }; +} + +function isoRect(H: number, B: number, t: number): ProfileSize { + return { id: `${n(H)}x${n(B)}x${n(t)}`, label: `${n(H)} x ${n(B)} x ${n(t)}`, desc: `RECT TUBE ${n(H)} x ${n(B)} x ${n(t)}`, dims: { B, H, t, ...en10219Radii(t) } }; +} + +function isoPipe(D: number, t: number): ProfileSize { + return { id: `${n(D)}x${n(t)}`, label: `${n(D)} x ${n(t)}`, desc: `PIPE ${n(D)} x ${n(t)}`, dims: { D, t } }; +} + +function isoAngle(b: number, t: number, r1: number, r2: number): ProfileSize { + return { id: `${n(b)}x${n(b)}x${n(t)}`, label: `${n(b)} x ${n(b)} x ${n(t)}`, desc: `L ${n(b)} x ${n(b)} x ${n(t)}`, dims: { h: b, b, t, r: r1, r2 } }; +} + +function upe(h: number, b: number, tw: number, tf: number, r: number): ProfileSize { + return { id: `UPE${h}`, label: `UPE ${h}`, desc: `UPE ${h}`, dims: { h, b, tw, tf, r } }; +} + +function ibeam(name: string, h: number, b: number, tw: number, tf: number, r: number): ProfileSize { + return { id: name.replace(/\s/g, ''), label: name, desc: name, dims: { h, b, tw, tf, r } }; +} + +function isoFlat(b: number, t: number): ProfileSize { + return { id: `${n(b)}x${n(t)}`, label: `${n(b)} x ${n(t)}`, desc: `FLAT BAR ${n(b)} x ${n(t)}`, dims: { B: b, H: t } }; +} + +function isoRound(D: number): ProfileSize { + return { id: `${n(D)}`, label: `Ø ${n(D)}`, desc: `ROUND BAR Ø ${n(D)}`, dims: { D } }; +} + +function hssSquare(B: number, t: number): ProfileSize { + const s = `${frac(B)} x ${frac(B)} x ${frac(t)}`; + return { id: s.replace(/ /g, ''), label: s, desc: `HSS ${s}`, dims: { B: B * IN, H: B * IN, t: t * IN, ro: 2 * t * IN, ri: t * IN } }; +} + +function hssRect(H: number, B: number, t: number): ProfileSize { + const s = `${frac(H)} x ${frac(B)} x ${frac(t)}`; + return { id: s.replace(/ /g, ''), label: s, desc: `HSS ${s}`, dims: { B: B * IN, H: H * IN, t: t * IN, ro: 2 * t * IN, ri: t * IN } }; +} + +function stdPipe(nps: string, D: number, t: number): ProfileSize { + return { id: nps.replace(/ /g, ''), label: `${nps} STD (${n(D)} x ${n(t)} in)`, desc: `PIPE ${nps} STD`, dims: { D: D * IN, t: t * IN } }; +} + +function ansiAngle(a: number, b: number, t: number): ProfileSize { + const s = `${frac(a)} x ${frac(b)} x ${frac(t)}`; + return { id: s.replace(/ /g, ''), label: s, desc: `L ${s}`, dims: { h: a * IN, b: b * IN, t: t * IN, r: 0, r2: 0 } }; +} + +function cChannel(name: string, d: number, bf: number, tw: number, tf: number): ProfileSize { + return { id: name.replace(/ /g, ''), label: name, desc: name, dims: { h: d * IN, b: bf * IN, tw: tw * IN, tf: tf * IN, r: 0, slope: 1 / 6 } }; +} + +function wShape(name: string, d: number, bf: number, tw: number, tf: number, kdes: number): ProfileSize { + return { id: name.replace(/ /g, ''), label: name, desc: name, dims: { h: d * IN, b: bf * IN, tw: tw * IN, tf: tf * IN, r: (kdes - tf) * IN } }; +} + +function ansiFlat(b: number, t: number): ProfileSize { + const s = `${frac(b)} x ${frac(t)}`; + return { id: s.replace(/ /g, ''), label: s, desc: `FLAT BAR ${s}`, dims: { B: b * IN, H: t * IN } }; +} + +function ansiRound(D: number): ProfileSize { + return { id: frac(D), label: `Ø ${frac(D)}`, desc: `ROUND BAR Ø ${frac(D)}`, dims: { D: D * IN } }; +} + +export const PROFILE_LIBRARY: Record> = { + iso: { + squareTube: [ + [20, 2], [25, 2], [30, 2], [30, 3], [40, 2], [40, 3], [40, 4], [50, 3], [50, 4], [50, 5], [60, 3], [60, 4], [60, 5], + [80, 4], [80, 5], [80, 6], [100, 4], [100, 5], [100, 6], [100, 8], [120, 6], [150, 6], [150, 8], + ].map(([B, t]) => isoSquare(B, t)), + rectTube: [ + [40, 20, 2], [50, 30, 3], [60, 40, 3], [60, 40, 4], [80, 40, 3], [80, 40, 4], [100, 50, 4], [100, 50, 5], [100, 60, 4], + [120, 60, 5], [120, 80, 5], [150, 100, 6], [200, 100, 6], + ].map(([H, B, t]) => isoRect(H, B, t)), + pipe: [ + [21.3, 2], [26.9, 2], [33.7, 2.6], [42.4, 2.6], [48.3, 3.2], [60.3, 3.2], [76.1, 3.2], [88.9, 3.2], [88.9, 4], + [114.3, 3.6], [114.3, 5], [139.7, 5], [168.3, 5], + ].map(([D, t]) => isoPipe(D, t)), + angle: [ + [20, 3, 3.5, 2], [25, 3, 3.5, 2], [30, 3, 5, 2.5], [40, 4, 6, 3], [40, 5, 6, 3], [50, 5, 7, 3.5], [50, 6, 7, 3.5], + [60, 6, 8, 4], [70, 7, 9, 4.5], [80, 8, 10, 5], [100, 10, 12, 6], + ].map(([b, t, r1, r2]) => isoAngle(b, t, r1, r2)), + channel: [ + upe(80, 50, 4, 7, 10), upe(100, 55, 4.5, 7.5, 10), upe(120, 60, 5, 8, 12), upe(140, 65, 5, 9, 12), + upe(160, 70, 5.5, 9.5, 12), upe(180, 75, 5.5, 10.5, 12), upe(200, 80, 6, 11, 13), + ], + beam: [ + ibeam('IPE 80', 80, 46, 3.8, 5.2, 5), ibeam('IPE 100', 100, 55, 4.1, 5.7, 7), ibeam('IPE 120', 120, 64, 4.4, 6.3, 7), + ibeam('IPE 140', 140, 73, 4.7, 6.9, 7), ibeam('IPE 160', 160, 82, 5, 7.4, 9), ibeam('IPE 180', 180, 91, 5.3, 8, 9), + ibeam('IPE 200', 200, 100, 5.6, 8.5, 12), ibeam('IPE 240', 240, 120, 6.2, 9.8, 15), ibeam('IPE 300', 300, 150, 7.1, 10.7, 15), + ibeam('HEA 100', 96, 100, 5, 8, 12), ibeam('HEA 120', 114, 120, 5, 8, 12), ibeam('HEA 140', 133, 140, 5.5, 8.5, 12), + ibeam('HEA 160', 152, 160, 6, 9, 15), ibeam('HEA 200', 190, 200, 6.5, 10, 18), + ], + flatBar: [[20, 3], [20, 5], [25, 5], [30, 5], [40, 5], [40, 8], [50, 5], [50, 10], [60, 8], [80, 10], [100, 10]].map(([b, t]) => isoFlat(b, t)), + roundBar: [6, 8, 10, 12, 16, 20, 25, 30, 40, 50].map(isoRound), + }, + ansi: { + squareTube: [ + [1.5, 1 / 8], [2, 1 / 8], [2, 3 / 16], [2, 1 / 4], [2.5, 3 / 16], [3, 3 / 16], [3, 1 / 4], [4, 1 / 4], [4, 3 / 8], + [5, 1 / 4], [6, 1 / 4], [6, 3 / 8], + ].map(([B, t]) => hssSquare(B, t)), + rectTube: [ + [2, 1, 1 / 8], [3, 2, 3 / 16], [3, 2, 1 / 4], [4, 2, 1 / 4], [4, 3, 1 / 4], [6, 2, 1 / 4], [6, 3, 1 / 4], [6, 4, 1 / 4], [8, 4, 1 / 4], + ].map(([H, B, t]) => hssRect(H, B, t)), + pipe: [ + stdPipe('1/2', 0.84, 0.109), stdPipe('3/4', 1.05, 0.113), stdPipe('1', 1.315, 0.133), stdPipe('1-1/4', 1.66, 0.14), + stdPipe('1-1/2', 1.9, 0.145), stdPipe('2', 2.375, 0.154), stdPipe('2-1/2', 2.875, 0.203), stdPipe('3', 3.5, 0.216), + stdPipe('4', 4.5, 0.237), stdPipe('6', 6.625, 0.28), + ], + angle: [ + [1, 1, 1 / 8], [1.5, 1.5, 3 / 16], [2, 2, 1 / 4], [2.5, 2.5, 1 / 4], [3, 3, 1 / 4], [3, 3, 3 / 8], [4, 4, 3 / 8], [4, 4, 1 / 2], + [3, 2, 1 / 4], [4, 3, 3 / 8], + ].map(([a, b, t]) => ansiAngle(a, b, t)), + channel: [ + cChannel('C 3 x 4.1', 3, 1.41, 0.17, 0.273), cChannel('C 4 x 5.4', 4, 1.58, 0.184, 0.296), cChannel('C 5 x 6.7', 5, 1.75, 0.19, 0.32), + cChannel('C 6 x 8.2', 6, 1.92, 0.2, 0.343), cChannel('C 8 x 11.5', 8, 2.26, 0.22, 0.39), cChannel('C 10 x 15.3', 10, 2.6, 0.24, 0.436), + cChannel('C 12 x 20.7', 12, 2.94, 0.282, 0.501), + ], + beam: [ + wShape('W 4 x 13', 4.16, 4.06, 0.28, 0.345, 0.595), wShape('W 6 x 9', 5.9, 3.94, 0.17, 0.215, 0.465), + wShape('W 6 x 15', 5.99, 5.99, 0.23, 0.26, 0.51), wShape('W 8 x 10', 7.89, 3.94, 0.17, 0.205, 0.505), + wShape('W 8 x 18', 8.14, 5.25, 0.23, 0.33, 0.63), wShape('W 10 x 12', 9.87, 3.96, 0.19, 0.21, 0.51), + wShape('W 12 x 14', 11.9, 3.97, 0.2, 0.225, 0.525), + ], + flatBar: [[1, 1 / 8], [1, 1 / 4], [1.5, 1 / 4], [2, 1 / 4], [2, 3 / 8], [3, 1 / 4], [3, 3 / 8], [4, 1 / 2]].map(([b, t]) => ansiFlat(b, t)), + roundBar: [0.25, 0.375, 0.5, 0.625, 0.75, 1, 1.25, 1.5, 2].map(ansiRound), + }, +}; + +export function profileSizes(standard: WeldStandard, type: WeldProfileType): ProfileSize[] { + // Own keys only: a damaged file's "constructor" or "toString" is no profile. + if (!Object.hasOwn(PROFILE_LIBRARY, standard) || !Object.hasOwn(PROFILE_LIBRARY[standard], type)) return []; + return PROFILE_LIBRARY[standard][type]; +} + +export function findProfile(standard: string, type: string, size: string): ProfileSize | null { + return profileSizes(standard as WeldStandard, type as WeldProfileType).find((s) => s.id === size) ?? null; +} + +/** Whether a profile type is a closed hollow section (end caps go on these). */ +export const isHollow = (type: string) => type === 'squareTube' || type === 'rectTube' || type === 'pipe'; + +// ---------- outline generation ---------- + +const line = (a: [number, number], b: [number, number]): PSeg => ({ k: 'line', a, b }); +const arc = (c: [number, number], r: number, a0: number, a1: number): PSeg => ({ k: 'arc', c, r, a0, a1 }); +const D90 = Math.PI / 2; + +/** A loop through corner points, rounding the corners with the given radii (positive: convex, CCW loop). */ +function roundedRect(w: number, h: number, r: number): PSeg[] { + const x = w / 2, y = h / 2; + if (r <= 1e-9) return [line([-x, -y], [x, -y]), line([x, -y], [x, y]), line([x, y], [-x, y]), line([-x, y], [-x, -y])]; + r = Math.min(r, x, y); + const out: PSeg[] = []; + const full = (a: [number, number], b: [number, number]) => { if (Math.hypot(b[0] - a[0], b[1] - a[1]) > 1e-9) out.push(line(a, b)); }; + full([-x + r, -y], [x - r, -y]); + out.push(arc([x - r, -y + r], r, -D90, 0)); + full([x, -y + r], [x, y - r]); + out.push(arc([x - r, y - r], r, 0, D90)); + full([x - r, y], [-x + r, y]); + out.push(arc([-x + r, y - r], r, D90, Math.PI)); + full([-x, y - r], [-x, -y + r]); + out.push(arc([-x + r, -y + r], r, Math.PI, 3 * D90)); + return out; +} + +export function reverseLoop(loop: PSeg[]): PSeg[] { + return loop.slice().reverse().map((s) => (s.k === 'line' ? line(s.b, s.a) : arc(s.c, s.r, s.a1, s.a0))); +} + +const circleLoop = (r: number): PSeg[] => [arc([0, 0], r, 0, 2 * Math.PI)]; + +/** Outer (and, for hollow sections, inner) outline of a profile, in its own coordinates. */ +export function profileShape(type: WeldProfileType | string, d: ProfileDims): ProfileShape { + switch (type) { + case 'squareTube': + case 'rectTube': { + const { B = 0, H = 0, t = 0, ro = 0, ri = 0 } = d; + return { outer: roundedRect(B, H, ro), holes: [reverseLoop(roundedRect(B - 2 * t, H - 2 * t, ri))] }; + } + case 'pipe': { + const { D = 0, t = 0 } = d; + return { outer: circleLoop(D / 2), holes: [reverseLoop(circleLoop(D / 2 - t))] }; + } + case 'roundBar': + return { outer: circleLoop((d.D ?? 0) / 2), holes: [] }; + case 'flatBar': + return { outer: roundedRect(d.B ?? 0, d.H ?? 0, 0), holes: [] }; + case 'angle': { + // Heel at the origin, legs along +x (width b) and +y (height h). + const { h = 0, b = 0, t = 0, r = 0, r2 = 0 } = d; + const o: PSeg[] = [line([0, 0], [b, 0])]; + if (r2 > 0) o.push(line([b, 0], [b, t - r2]), arc([b - r2, t - r2], r2, 0, D90)); + else o.push(line([b, 0], [b, t])); + o.push(line([r2 > 0 ? b - r2 : b, t], [t + r, t])); + if (r > 0) o.push(arc([t + r, t + r], r, 3 * D90, Math.PI)); + o.push(line([t, t + r], [t, r2 > 0 ? h - r2 : h])); + if (r2 > 0) o.push(arc([t - r2, h - r2], r2, 0, D90)); + o.push(line([r2 > 0 ? t - r2 : t, h], [0, h]), line([0, h], [0, 0])); + return { outer: o, holes: [] }; + } + case 'channel': { + // Web along the y axis at x 0..tw, flanges toward +x; depth h centred on y = 0. + const { h = 0, b = 0, tw = 0, tf = 0, r = 0, slope = 0 } = d; + const y = h / 2; + if (slope > 0) { + // Flange thickness tf is at the middle of the flange's inner face. + const run = (b - tw) / 2; + const toe = tf - run * slope, root = tf + run * slope; + const pts: [number, number][] = [[0, -y], [b, -y], [b, -y + toe], [tw, -y + root], [tw, y - root], [b, y - toe], [b, y], [0, y]]; + return { outer: pts.map((p, i) => line(p, pts[(i + 1) % pts.length])), holes: [] }; + } + const o: PSeg[] = [line([0, -y], [b, -y]), line([b, -y], [b, -y + tf]), line([b, -y + tf], [tw + r, -y + tf])]; + if (r > 0) o.push(arc([tw + r, -y + tf + r], r, 3 * D90, Math.PI)); + o.push(line([tw, -y + tf + r], [tw, y - tf - r])); + if (r > 0) o.push(arc([tw + r, y - tf - r], r, Math.PI, D90)); + o.push(line([tw + r, y - tf], [b, y - tf]), line([b, y - tf], [b, y]), line([b, y], [0, y]), line([0, y], [0, -y])); + return { outer: o, holes: [] }; + } + case 'beam': { + // Symmetric I section centred on the origin. + const { h = 0, b = 0, tw = 0, tf = 0, r = 0 } = d; + const x = b / 2, y = h / 2, w = tw / 2; + const o: PSeg[] = [line([-x, -y], [x, -y]), line([x, -y], [x, -y + tf]), line([x, -y + tf], [w + r, -y + tf])]; + if (r > 0) o.push(arc([w + r, -y + tf + r], r, 3 * D90, Math.PI)); + o.push(line([w, -y + tf + r], [w, y - tf - r])); + if (r > 0) o.push(arc([w + r, y - tf - r], r, Math.PI, D90)); + o.push(line([w + r, y - tf], [x, y - tf]), line([x, y - tf], [x, y]), line([x, y], [-x, y]), line([-x, y], [-x, y - tf]), line([-x, y - tf], [-w - r, y - tf])); + if (r > 0) o.push(arc([-w - r, y - tf - r], r, D90, 0)); + o.push(line([-w, y - tf - r], [-w, -y + tf + r])); + if (r > 0) o.push(arc([-w - r, -y + tf + r], r, 0, -D90)); + o.push(line([-w - r, -y + tf], [-x, -y + tf]), line([-x, -y + tf], [-x, -y])); + return { outer: o, holes: [] }; + } + default: + return { outer: [], holes: [] }; + } +} + +// ---------- section properties ---------- + +/** Contributions of one segment to the area and first moments (Green's theorem). */ +function segMoments(s: PSeg): { a: number; mx: number; my: number } { + if (s.k === 'line') { + const [x0, y0] = s.a, [x1, y1] = s.b; + // The same integrands as the arcs below (the usual polygon formula uses + // another form, which only agrees for whole polygons). + return { a: (x0 * y1 - x1 * y0) / 2, mx: ((y1 - y0) * (x0 * x0 + x0 * x1 + x1 * x1)) / 6, my: (-(x1 - x0) * (y0 * y0 + y0 * y1 + y1 * y1)) / 6 }; + } + const { c: [cx, cy], r, a0, a1 } = s; + const s0 = Math.sin(a0), s1 = Math.sin(a1), c0 = Math.cos(a0), c1 = Math.cos(a1); + // A = 1/2 ∮ x dy - y dx + const a = (r * r * (a1 - a0) + r * (cx * (s1 - s0) - cy * (c1 - c0))) / 2; + // ∬ x dA = 1/2 ∮ x² dy, with x = cx + r cos θ, dy = r cos θ dθ. + const ic = s1 - s0; + const ic2 = (a1 - a0) / 2 + (s1 * c1 - s0 * c0) / 2; + const ic3 = (s1 - s1 ** 3 / 3) - (s0 - s0 ** 3 / 3); + const mx = (cx * cx * r * ic + 2 * cx * r * r * ic2 + r ** 3 * ic3) / 2; + // ∬ y dA = -1/2 ∮ y² dx, with y = cy + r sin θ, dx = -r sin θ dθ. + const is = -(c1 - c0); + const is2 = (a1 - a0) / 2 - (s1 * c1 - s0 * c0) / 2; + const is3 = (-c1 + c1 ** 3 / 3) - (-c0 + c0 ** 3 / 3); + const my = (cy * cy * r * is + 2 * cy * r * r * is2 + r ** 3 * is3) / 2; + return { a, mx, my }; +} + +/** Area and centroid of a profile (holes subtract). */ +export function sectionProps(shape: ProfileShape): { area: number; centroid: [number, number] } { + let a = 0, mx = 0, my = 0; + for (const loop of [shape.outer, ...shape.holes]) { + for (const s of loop) { + const m = segMoments(s); + a += m.a; mx += m.mx; my += m.my; + } + } + return { area: a, centroid: a ? [mx / a, my / a] : [0, 0] }; +} + +/** Largest value of g·p over the outline (exact: line ends and arc extremes). */ +export function outlineMax(loop: PSeg[], g: [number, number]): number { + let best = -Infinity; + for (const s of loop) { + if (s.k === 'line') { + best = Math.max(best, g[0] * s.a[0] + g[1] * s.a[1], g[0] * s.b[0] + g[1] * s.b[1]); + continue; + } + const { c, r, a0, a1 } = s; + const at = (t: number) => g[0] * (c[0] + r * Math.cos(t)) + g[1] * (c[1] + r * Math.sin(t)); + best = Math.max(best, at(a0), at(a1)); + const gl = Math.hypot(g[0], g[1]); + if (gl > 0) { + // The arc's point facing g, if the arc passes it. + const th = Math.atan2(g[1], g[0]); + const lo = Math.min(a0, a1), hi = Math.max(a0, a1); + const k = Math.ceil((lo - th) / (2 * Math.PI)); + if (th + k * 2 * Math.PI <= hi + 1e-12) best = Math.max(best, g[0] * c[0] + g[1] * c[1] + r * gl); + } + } + return best; +} + +/** Points along the outline (line ends and arcs every few degrees). */ +export function outlinePoints(loop: PSeg[], stepDeg = 3): [number, number][] { + const out: [number, number][] = []; + for (const s of loop) { + if (s.k === 'line') { out.push(s.a, s.b); continue; } + const k = Math.max(2, Math.ceil(Math.abs(s.a1 - s.a0) / ((stepDeg * Math.PI) / 180))); + for (let i = 0; i <= k; i++) { + const t = s.a0 + ((s.a1 - s.a0) * i) / k; + out.push([s.c[0] + s.r * Math.cos(t), s.c[1] + s.r * Math.sin(t)]); + } + } + return out; +} + +/** Bounding box of an outline. */ +export function outlineBox(loop: PSeg[]): { min: [number, number]; max: [number, number] } { + return { + min: [-outlineMax(loop, [-1, 0]), -outlineMax(loop, [0, -1])], + max: [outlineMax(loop, [1, 0]), outlineMax(loop, [0, 1])], + }; +} + +// ---------- placement ---------- + +export type PiercePoint = 'centroid' | 'center' | 'tl' | 'tc' | 'tr' | 'ml' | 'mr' | 'bl' | 'bc' | 'br'; + +export const PIERCE_POINTS: { value: PiercePoint; label: string }[] = [ + { value: 'centroid', label: 'Centroid' }, + { value: 'center', label: 'Center of bounding box' }, + { value: 'tl', label: 'Top left corner' }, + { value: 'tc', label: 'Top edge center' }, + { value: 'tr', label: 'Top right corner' }, + { value: 'ml', label: 'Left edge center' }, + { value: 'mr', label: 'Right edge center' }, + { value: 'bl', label: 'Bottom left corner' }, + { value: 'bc', label: 'Bottom edge center' }, + { value: 'br', label: 'Bottom right corner' }, +]; + +export interface Placement { + pierce: PiercePoint; + /** Degrees, counter-clockwise looking along the member. */ + rotation: number; + mirror: boolean; +} + +/** Where a pierce point is on a profile (in the profile's own coordinates). */ +export function piercePointOf(shape: ProfileShape, p: PiercePoint): [number, number] { + if (p === 'centroid') return sectionProps(shape).centroid; + const { min, max } = outlineBox(shape.outer); + const cx = (min[0] + max[0]) / 2, cy = (min[1] + max[1]) / 2; + const x = p[1] === 'l' ? min[0] : p[1] === 'r' ? max[0] : cx; + const y = p[0] === 't' ? max[1] : p[0] === 'b' ? min[1] : cy; + return p === 'center' ? [cx, cy] : [x, y]; +} + +/** + * The profile moved so its pierce point is at the origin (where the sketch + * segment runs), mirrored about its vertical axis and turned. Loops keep + * their orientation (outer counter-clockwise). + */ +export function placeProfile(shape: ProfileShape, pl: Placement): ProfileShape { + return placeWith(shape, piercePointOf(shape, pl.pierce), pl); +} + +/** Like placeProfile, with the pierce point given (an end cap is placed by its member's profile). */ +export function placeWith(shape: ProfileShape, [px, py]: [number, number], pl: Placement): ProfileShape { + const a = (pl.rotation * Math.PI) / 180; + const ca = Math.cos(a), sa = Math.sin(a); + const m = pl.mirror ? -1 : 1; + const tp = (p: [number, number]): [number, number] => { + const x = (p[0] - px) * m, y = p[1] - py; + return [x * ca - y * sa, x * sa + y * ca]; + }; + const ta = (t: number) => (pl.mirror ? Math.PI - t : t) + a; + const map = (loop: PSeg[]): PSeg[] => { + const out = loop.map((s): PSeg => (s.k === 'line' ? line(tp(s.a), tp(s.b)) : arc(tp(s.c), s.r, ta(s.a0), ta(s.a1)))); + // A mirror reverses the direction the loop runs. + return pl.mirror ? reverseLoop(out) : out; + }; + return { outer: map(shape.outer), holes: shape.holes.map(map) }; +} diff --git a/src/parametric/src/model/weldments.ts b/src/parametric/src/model/weldments.ts new file mode 100644 index 0000000000..68fbf84010 --- /dev/null +++ b/src/parametric/src/model/weldments.ts @@ -0,0 +1,173 @@ +// Weldment features: factories, member identities and the cut list. + +import type { + EndCapFeature, GussetFeature, Id, MemberRef, PartDocument, SegmentRef, StructuralMemberFeature, TrimExtendFeature, UnitSystem, WeldBeadFeature, +} from './types'; +import { UNIT_SYSTEMS, formatNumber } from './units'; + +/** A member's key inside its feature: the sketch segment it runs along. */ +export const memberKey = (s: SegmentRef) => `${s.sketch}/${s.entity}`; + +/** + * The member a face of a structural member belongs to. Member faces are + * named ":/:". + */ +export function memberOfFace(name: string): MemberRef | null { + const m = /^([^:|@#/]+):([^:|@#/]+\/[^:|@#/]+):\d+(?:#\d+)?$/.exec(name); + return m ? { feature: m[1], member: m[2] } : null; +} + +export const sameMember = (a: MemberRef, b: MemberRef) => a.feature === b.feature && a.member === b.member; + +export const newStructuralMember = (id: Id, name: string, groups: SegmentRef[][] = []): StructuralMemberFeature => ({ + id, name, type: 'structuralMember', standard: 'iso', profile: 'squareTube', size: '40x40x3', + groups: groups.map((segments) => ({ segments })), rotation: 0, mirror: false, pierce: 'centroid', + corner: 'miter', gap: 0, trimGroups: true, gap2: 0, +}); + +export const newTrimExtend = (id: Id, name: string): TrimExtendFeature => ({ + id, name, type: 'trimExtend', members: [], boundary: 'faces', faces: [], boundaryMembers: [], allowExtension: true, coped: false, gap: 0, +}); + +export const newEndCap = (id: Id, name: string, thickness: number): EndCapFeature => ({ + id, name, type: 'endCap', faces: [], thickness, offset: 0, inward: false, +}); + +export const newGusset = (id: Id, name: string, size: number, thickness: number): GussetFeature => ({ + id, name, type: 'gusset', faces: [], shape: 'triangular', d1: size, d2: size, d3: size / 2, thickness, location: 'center', chamfer: 0, +}); + +export const newWeldBead = (id: Id, name: string, size: number): WeldBeadFeature => ({ id, name, type: 'weldBead', edges: [], size }); + +// ---------- cut list ---------- + +/** A member as built, reported by the geometry kernel with every rebuild. */ +export interface WeldMemberInfo { + /** Structural member feature. */ + feature: Id; + /** Sketch segment the member runs along ("sketch/entity"). */ + member: string; + group: number; + standard: string; + profile: string; + size: string; + /** e.g. "SQ TUBE 40 x 40 x 3". */ + desc: string; + /** Overall length (long point to long point), mm. */ + length: number; + /** End cut angles from square, degrees (0 for a square cut, 45 for a miter of a right-angle corner). */ + angle1: number; + angle2: number; + /** Volume of the member, mm³. */ + volume: number; + /** Cross-section area, mm². */ + area: number; + /** The member follows an arc. */ + curved?: boolean; + /** Radius of the arc it follows (sketch arc), mm. */ + radius?: number; +} + +export interface CutListItem { + item: number; + quantity: number; + description: string; + /** Length of one piece, mm. */ + length: number; + angle1: number; + angle2: number; + /** Mass of one piece, kg. */ + mass: number; + totalLength: number; + totalMass: number; + curved: boolean; + /** Radius of the arc a curved piece follows, mm. */ + radius?: number; + members: { feature: Id; member: string }[]; +} + +export interface CutList { + items: CutListItem[]; + /** Pieces in all. */ + count: number; + totalLength: number; + /** kg */ + totalMass: number; + /** The density used, kg/m³, and whether it is the part's material. */ + density: number; + material: string | null; + /** A later feature other than a cut (a fillet, a shell) changed the members: the masses are from before it. */ + massApproximate?: boolean; +} + +/** Lengths and angles closer than these make identical pieces. */ +export const CUT_LIST_TOLERANCE = { length: 0.01, angle: 0.01 }; + +/** + * The cut list of a part's weldment: identical members (same profile, same + * length and the same end angles, either way round, within the tolerance) + * are one item with their quantity. Mass uses the part's material (1000 + * kg/m³ when it has none, as mass properties do). Pass the latest build + * result (or its `weldments` list); a drawing's cut list table can use it. + */ +export function weldmentCutList(doc: Pick, build: WeldMemberInfo[] | { weldments?: WeldMemberInfo[] } | null | undefined): CutList { + const members = Array.isArray(build) ? build : build?.weldments; + const density = doc.material?.density ?? 1000; + const items: CutListItem[] = []; + const tol = CUT_LIST_TOLERANCE; + const close = (a: number, b: number, t: number) => Math.abs(a - b) <= t; + for (const m of members ?? []) { + // The smaller angle first, so a piece cut the other way round matches. + const [a1, a2] = m.angle1 <= m.angle2 ? [m.angle1, m.angle2] : [m.angle2, m.angle1]; + const mass = m.volume * 1e-9 * density; + // Curved pieces of one length are bent to different radii. + const sameBend = (it: CutListItem) => !it.curved || close(it.radius ?? 0, m.radius ?? 0, tol.length); + const same = items.find((it) => it.description === m.desc && it.curved === !!m.curved && close(it.length, m.length, tol.length) && close(it.angle1, a1, tol.angle) && close(it.angle2, a2, tol.angle) && sameBend(it)); + if (same) { + same.quantity++; + same.totalLength += m.length; + same.totalMass += mass; + same.members.push({ feature: m.feature, member: m.member }); + } else { + items.push({ + item: 0, quantity: 1, description: m.desc, length: m.length, angle1: a1, angle2: a2, mass, totalLength: m.length, totalMass: mass, + curved: !!m.curved, ...(m.curved && m.radius != null ? { radius: m.radius } : {}), members: [{ feature: m.feature, member: m.member }], + }); + } + } + for (const it of items) it.mass = it.totalMass / it.quantity; + items.sort((a, b) => a.description.localeCompare(b.description, 'en', { numeric: true }) || b.length - a.length || a.angle1 - b.angle1 || a.angle2 - b.angle2 || (a.radius ?? 0) - (b.radius ?? 0)); + items.forEach((it, i) => { it.item = i + 1; }); + return { + items, + count: items.reduce((s, it) => s + it.quantity, 0), + totalLength: items.reduce((s, it) => s + it.totalLength, 0), + totalMass: items.reduce((s, it) => s + it.totalMass, 0), + density, + material: doc.material?.name ?? null, + }; +} + +/** Cut list rows as text in the part's units: what the dialog shows and the CSV holds. */ +export function cutListRows(list: CutList, units: UnitSystem, decimals: number): { header: string[]; rows: string[][]; total: string[] } { + const u = UNIT_SYSTEMS[units]; + const len = (mm: number) => formatNumber(mm / u.scale, decimals); + const mass = (kg: number) => formatNumber(kg / u.massScale, Math.max(2, decimals)); + const ang = (d: number) => formatNumber(d, 2); + const m = list.massApproximate ? `${u.mass}, before later changes` : u.mass; + return { + header: ['Item', 'Qty', 'Description', `Length (${u.length})`, 'Angle 1 (°)', 'Angle 2 (°)', `Total length (${u.length})`, `Mass each (${m})`, `Total mass (${m})`], + rows: list.items.map((it) => [ + String(it.item), String(it.quantity), it.description + (it.curved ? (it.radius != null ? ` (curved, R ${len(it.radius)})` : ' (curved)') : ''), len(it.length), ang(it.angle1), ang(it.angle2), + len(it.totalLength), mass(it.mass), mass(it.totalMass), + ]), + total: ['', String(list.count), 'Total', '', '', '', len(list.totalLength), '', mass(list.totalMass)], + }; +} + +/** The cut list as CSV (RFC 4180 quoting). */ +export function cutListCsv(list: CutList, units: UnitSystem, decimals: number): string { + const { header, rows, total } = cutListRows(list, units, decimals); + const cell = (s: string) => (/[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s); + return [header, ...rows, total].map((r) => r.map(cell).join(',')).join('\r\n') + '\r\n'; +} diff --git a/src/parametric/src/styles/app.css b/src/parametric/src/styles/app.css index 03ff695f47..426078cd4b 100644 --- a/src/parametric/src/styles/app.css +++ b/src/parametric/src/styles/app.css @@ -250,6 +250,9 @@ a.icon-btn { text-decoration: none; } border-radius: var(--radius-sm); color: var(--text); font-size: var(--fs-xs); line-height: 1.15; text-align: center; } .tool .lbl { white-space: normal; overflow-wrap: anywhere; } +/* The sheet metal, surfaces, weldments, drawing and assembly tabs: labels break between words only, and a word wider than the button widens it. */ +:is(.cm-tools[data-tab='sheetMetal'], .cm-tools[data-tab='surfaces'], .cm-tools[data-tab='weldments'], .cm-tools[data-tab='drawing'], .cm-tools[data-tab='annotation'], .cm-tools[data-tab='assembly']) .tool:not(.row) { max-width: none; } +:is(.cm-tools[data-tab='sheetMetal'], .cm-tools[data-tab='surfaces'], .cm-tools[data-tab='weldments'], .cm-tools[data-tab='drawing'], .cm-tools[data-tab='annotation'], .cm-tools[data-tab='assembly']) .tool:not(.row) .lbl { overflow-wrap: normal; min-width: min-content; max-width: 68px; } .tool:hover:not(:disabled) { background: var(--hover); } .tool:active:not(:disabled) { background: var(--active); } .tool[aria-pressed='true'] { background: var(--accent-weak); border-color: var(--accent-border); } @@ -265,6 +268,9 @@ a.icon-btn { text-decoration: none; } .tool-caret:hover { background: var(--active); color: var(--text); } .cm-tabs { display: flex; gap: 0; padding: 0 6px; overflow-x: auto; scrollbar-width: none; } .cm-tabs::-webkit-scrollbar { display: none; } +.cm-tabs.more-end { mask-image: linear-gradient(to right, #000 calc(100% - 28px), transparent); } +.cm-tabs.more-start { mask-image: linear-gradient(to left, #000 calc(100% - 28px), transparent); } +.cm-tabs.more-start.more-end { mask-image: linear-gradient(to right, transparent, #000 28px, #000 calc(100% - 28px), transparent); } .cm-tabs [role='tab'] { background: none; border: 1px solid transparent; border-bottom: 0; padding: 3px 12px 4px; font-size: var(--fs-sm); color: var(--text-2); border-radius: var(--radius-sm) var(--radius-sm) 0 0; margin-top: 1px; white-space: nowrap; @@ -449,6 +455,12 @@ a.icon-btn { text-decoration: none; } .paper { position: relative; background: #fff; outline: 1px solid var(--border-strong); } .paper svg { display: block; } .view-sel { position: absolute; border: 1px dashed var(--accent); pointer-events: none; } +.drawing-ws.drw-tool, .drawing-ws.drw-tool:active { cursor: crosshair; } +.drw-overlay { position: absolute; left: 0; top: 0; pointer-events: none; } +.drw-overlay svg { display: block; overflow: visible; } +.drw-anno-list { display: flex; flex-direction: column; gap: 2px; } +.drw-tools { flex-wrap: wrap; gap: 4px; } +.drw-missing { color: var(--danger); } .drawing-busy:empty { padding: 0; border: 0; } .drawing-busy { position: absolute; left: 50%; top: 12px; transform: translateX(-50%); padding: 4px 12px; border-radius: var(--radius); background: var(--panel); border: 1px solid var(--border); color: var(--text-2); font-size: var(--fs-sm); pointer-events: none; } .drawing-empty { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); padding: 10px 14px; border-radius: var(--radius); background: var(--panel); border: 1px solid var(--border); color: var(--text-2); } @@ -617,6 +629,8 @@ a.icon-btn { text-decoration: none; } .cm-stack { flex-direction: row; align-items: stretch; } .tool.row { flex-direction: column; height: auto; min-width: 46px; max-width: 64px; padding: 4px; } .tool.row .lbl { white-space: normal; font-size: 10px; } + :is(.cm-tools[data-tab='sheetMetal'], .cm-tools[data-tab='surfaces'], .cm-tools[data-tab='weldments'], .cm-tools[data-tab='drawing'], .cm-tools[data-tab='annotation'], .cm-tools[data-tab='assembly']) .tool { max-width: none; } + :is(.cm-tools[data-tab='sheetMetal'], .cm-tools[data-tab='surfaces'], .cm-tools[data-tab='weldments'], .cm-tools[data-tab='drawing'], .cm-tools[data-tab='annotation'], .cm-tools[data-tab='assembly']) .tool:is(:not(.row), .row) .lbl { overflow-wrap: normal; min-width: min-content; max-width: 54px; } .leftpane { position: absolute; z-index: 20; left: 0; right: 0; bottom: 0; top: auto; width: 100% !important; max-width: none; height: min(52dvh, 460px); border-right: 0; border-top: 1px solid var(--border-strong); border-radius: 12px 12px 0 0; transform: translateY(105%); transition: transform 0.18s ease, height 0.18s ease; @@ -688,3 +702,11 @@ a.icon-btn { text-decoration: none; } :root :is(.ti[aria-selected='true'], .cmd-results [role='option'][aria-selected='true'], [role='tab'][aria-selected='true'], .icon-btn[aria-pressed='true'], .tool[aria-pressed='true'], .seg button[aria-pressed='true']) * { color: inherit; } } + +/* Weldments: structural member groups and the cut list table. */ +.weld-group { display: flex; flex-direction: column; gap: 2px; margin-bottom: 6px; } +.weld-group-rm { margin-left: auto; } +.weld-cutlist-wrap { overflow-x: auto; max-width: 100%; } +.weld-cutlist th, .weld-cutlist td { white-space: nowrap; } +.weld-cutlist th.num, .weld-cutlist td.num { text-align: right; } +.weld-cutlist tfoot th, .weld-cutlist tfoot td { font-weight: 600; border-bottom: none; } diff --git a/src/parametric/src/ui/icons.ts b/src/parametric/src/ui/icons.ts index d858b2989b..3d45db4766 100644 --- a/src/parametric/src/ui/icons.ts +++ b/src/parametric/src/ui/icons.ts @@ -10,6 +10,7 @@ import { Cloud, HardDrive, Pin, Scissors, MousePointer2, Hand, ZoomIn, ZoomOut, Rotate3d, Type, FileText, Users, Sparkles, ArrowUp, Square, SquarePen, Camera, Paperclip, Image as ImageIcon, ExternalLink, } from 'lucide'; +import { SURFACE_ICONS } from './surface-icons'; type IconNode = [string, Record][]; @@ -66,6 +67,16 @@ const CAD: Record = { mirror: [DASH('M12 2v20', '4 2 1 2'), P('M3 8l6-2v12l-6-2z', 'a'), P('M21 8l-6-2v12l6-2z')], plane: [P('M3 17l5-10h13l-5 10z', 'a'), P('M3 17l5-10h13l-5 10z')], axis: [DASH('M4 20L20 4', '5 2 1.5 2'), DOT(12, 12)], + // Sheet metal. + sheetMetal: [P('M3 10l9-4.5 9 4.5-9 4.5z', 'a'), P('M3 10l9-4.5 9 4.5-9 4.5z'), P('M3 10v2l9 4.5 9-4.5v-2'), P('M3 16l9 4.5 9-4.5', 'thin')], + baseFlange: [P('M3 15l9-4.5 9 4.5-9 4.5z', 'a'), P('M3 15l9-4.5 9 4.5-9 4.5z'), P('M3 15v1.5l9 4.5 9-4.5V15'), P('M12 3v5M9.5 5.5L12 8l2.5-2.5', 'thin')], + edgeFlange: [P('M3 15l9 4.5 9-4.5-9-4.5z', 's'), P('M12 10.5l9 4.5V7l-9-4.5z', 'a'), P('M3 15l9 4.5 9-4.5'), P('M3 15l9-4.5'), P('M12 10.5l9 4.5V7l-9-4.5z')], + sketchedBend: [P('M3 19l8-4h10l-8 4z', 's'), P('M11 15L8 5h10l3 10z', 'a'), P('M3 19l8-4h10l-8 4z'), P('M11 15L8 5h10l3 10'), DASH('M2 17h4', '1.5 1.5')], + hem: [P('M3 7h12a5 5 0 0 1 0 10H7', 'thick-a'), P('M3 7h12a5 5 0 0 1 0 10H7')], + flatPattern: [P('M9 3h6v6h6v6h-6v6H9v-6H3V9h6z', 'a'), P('M9 3h6v6h6v6h-6v6H9v-6H3V9h6z'), DASH('M9 9h6M9 15h6M9 9v6M15 9v6', '1.5 1.5')], + sheetThickness: [P('M4 8h16M4 16h16'), P('M12 2.5V8M12 21.5V16'), P('M10 5.5L12 8l2-2.5M10 18.5l2-2.5 2 2.5', 'thin')], + bendRadius: [P('M4 20v-8a8 8 0 0 1 8-8h8'), DASH('M12 12L6.5 6.5', '2 1.5'), DOT(12, 12)], + angle: [P('M4 20h16M4 20L16 6'), P('M11 20a7 7 0 0 0-2.2-5.1', 'thin')], measure: [P('M3 15l12-12 6 6-12 12z'), P('M7 11l2 2M10 8l2 2M13 5l2 2', 'thin')], massProperties: [P('M6 8h12l2 12H4z', 'a'), C(12, 5, 2), P('M10 15h4', 'thin')], sectionView: [P(CUBE_TOP, 's'), P(CUBE_LEFT), P(CUBE_RIGHT), P('M2 12l10-5 10 5-10 5z', 'a')], @@ -93,9 +104,25 @@ const CAD: Record = { part: [P(CUBE_TOP, 'a'), P(CUBE_LEFT, 's'), P(CUBE_RIGHT)], sketchFeature: [P('M3 17l5-4h13l-5 4z', 's'), P('M7 15l4-6 4 4 3-5', 'thin')], rollback: [P('M3 12h18', 'thick'), P('M8 8l-4 4 4 4')], + // Drawings: a sheet with views, and the view and annotation commands. + makeDrawing: [P('M5 2.5h10l4 4v15H5z', 's'), P('M15 2.5v4h4'), P('M8 10h4v4H8z', 'a'), P('M14 10h2.5v4H14M8 16h4v2.5H8')], + drawingProjected: [P('M3 8h7v8H3z', 'a'), P('M15 8h6v8h-6z'), P('M10 12h3', 'thin'), P('M11.5 10.5l1.5 1.5-1.5 1.5', 'thin')], + drawingSection: [P('M4 6h7v12H4z'), P('M13 6h7v12h-7z', 's'), P('M13 10l4-4M13 14l7-7M13 18l7-7M17 18l3-3', 'thin'), P('M12 3v18', 'thin')], + drawingDetail: [P('M3 14h8v6H3z'), C(9, 15, 3, 'a'), P('M11.5 13l3.5-3.5'), C(17.5, 7, 4)], + drawingAuxiliary: [P('M3 12h6v8H3z'), P('M9 12l3-4'), P('M13 4l6 4-3 5-6-4z', 'a')], + drawingCenterMark: [C(12, 12, 6), P('M12 3v4M12 10.5v3M12 17v4M3 12h4M10.5 12h3M17 12h4', 'thin')], + drawingHoleCallout: [C(7, 16, 4), P('M10 13l5-5h6'), P('M14 5h7', 'thin')], github: [P('M12 2C6.48 2 2 6.58 2 12.23c0 4.52 2.87 8.35 6.84 9.7.5.1.68-.22.68-.49 0-.24-.01-.88-.01-1.73-2.78.62-3.37-1.37-3.37-1.37-.46-1.18-1.11-1.5-1.11-1.5-.91-.64.07-.62.07-.62 1 .07 1.53 1.06 1.53 1.06.89 1.57 2.34 1.12 2.91.85.09-.66.35-1.12.63-1.37-2.22-.26-4.56-1.14-4.56-5.07 0-1.12.39-2.04 1.03-2.76-.1-.26-.45-1.3.1-2.71 0 0 .84-.28 2.75 1.05A9.4 9.4 0 0 1 12 6.94c.85 0 1.71.12 2.51.34 1.91-1.33 2.75-1.05 2.75-1.05.55 1.41.2 2.45.1 2.71.64.72 1.03 1.64 1.03 2.76 0 3.94-2.34 4.81-4.57 5.06.36.32.68.94.68 1.9 0 1.37-.01 2.47-.01 2.81 0 .27.18.6.69.49A10.13 10.13 0 0 0 22 12.23C22 6.58 17.52 2 12 2z', 'f nostroke')], + // Weldments. + structuralMember: [P('M3 10h8v8H3z', 'a'), P('M5.5 12.5h3v3h-3z'), P('M3 10l9-7h8l-9 7M11 18l9-7V3')], + trimExtend: [P('M3 9h10v6H3z', 'a'), DASH('M13 12h4', '2 1.5'), P('M17 3v18'), P('M21 6l-3 3M21 11l-3 3M21 16l-3 3', 'thin')], + endCap: [P('M3 8h12v8H3z', 's'), DASH('M3 10.5h12M3 13.5h12', '2 2'), P('M15 5.5h4v13h-4z', 'a')], + gusset: [P('M6 18V8l10 10z', 'a'), P('M4 3v17h17')], + cutList: [P('M3 5h18v14H3z', 's'), P('M3 10h18M3 14.5h18M9 5v14', 'thin')], + weldBead: [P('M4 20h17M4 20V3'), P('M4 20v-7l7 7z', 'a'), P('M6 17.5l1.5-1.5M6 14.5l1.5 1.5', 'thin')], // The 3×3 dot grid of the Apps launcher. apps: [5, 12, 19].flatMap((y) => [5, 12, 19].map((x) => C(x, y, 2, 'f'))), + ...SURFACE_ICONS, }; // Relation glyphs shown next to sketch geometry (16px grid). @@ -226,3 +253,17 @@ export function relationGlyph(type: string, size = 14): SVGSVGElement { } export const hasIcon = (name: string) => name in CAD || name in LUCIDE || (name.startsWith('rel:') && name.slice(4) in RELATION_GLYPHS); + +/** + * Adds icons from another module (a name to its drawing, or to the name of + * an icon it is drawn like). Existing names are never replaced. + */ +export function addIcons(icons: Record) { + for (const [name, v] of Object.entries(icons)) { + if (name in CAD || name in LUCIDE) continue; + const nodes = typeof v === 'string' ? CAD[v] ?? LUCIDE[v] : v; + if (nodes) CAD[name] = nodes; + } +} + +export type { IconNode }; diff --git a/src/parametric/src/ui/surface-icons.ts b/src/parametric/src/ui/surface-icons.ts new file mode 100644 index 0000000000..ceb2cac957 --- /dev/null +++ b/src/parametric/src/ui/surface-icons.ts @@ -0,0 +1,24 @@ +// Icons of the surface modeling commands (24px grid, the CAD icon style of +// icons.ts: "a" accent fill, "s" soft fill). A wavy sheet stands for a surface. + +type IconNode = [string, Record][]; + +const P = (d: string, cls?: string): [string, Record] => (cls ? ['path', { d, class: cls }] : ['path', { d }]); +const DASH = (d: string, dash = '3 2'): [string, Record] => ['path', { d, 'stroke-dasharray': dash }]; + +export const SURFACE_ICONS: Record = { + surfaceExtrude: [P('M3 18c3-2.5 6-2.5 9 0s6 2.5 9 0V11c-3 2.5-6 2.5-9 0s-6-2.5-9 0z', 'a'), P('M3 18c3-2.5 6-2.5 9 0s6 2.5 9 0', 'thick-a'), P('M3 18V11c3-2.5 6-2.5 9 0s6 2.5 9 0v7'), P('M12 2v7M9.5 4.5L12 2l2.5 2.5')], + surfaceRevolve: [DASH('M4 3v18', '4 2 1 2'), P('M8 5c5 3 5 11 0 14h8c5-3 5-11 0-14z', 'a'), P('M8 5c5 3 5 11 0 14M16 5c5 3 5 11 0 14'), P('M8 5h8M8 19h8', 'thin')], + surfaceSweep: [P('M3 20c5 0 6-12 15-12', 'thick-a'), P('M3 15c5 0 6-12 15-12'), P('M3 20c5 0 6-12 15-12'), P('M3 15v5M18 3v5')], + surfaceLoft: [P('M3 19c3-2 6-2 9 0M11 6c3-2 6-2 9 0', 'thick-a'), P('M3 19L11 6M12 19l8-13', 'thin'), P('M3 19c3-2 6-2 9 0M11 6c3-2 6-2 9 0')], + surfacePlanar: [P('M3 17l5-10h13l-5 10z', 'a'), P('M3 17l5-10h13l-5 10z'), P('M7 13h9', 'thin')], + surfaceOffset: [P('M3 20c3-2.5 6-2.5 9 0s6 2.5 9 0', 'thick-a'), P('M3 20c3-2.5 6-2.5 9 0s6 2.5 9 0'), DASH('M3 10c3-2.5 6-2.5 9 0s6 2.5 9 0', '2.5 2'), P('M12 13.5v5M10.5 15l1.5-1.5 1.5 1.5', 'thin')], + surfaceFill: [P('M5 7c4-3 10-3 14 0 2 4 1 9-3 11-4 2-9 1-11-3-1.5-3-1.5-6 0-8z', 'a'), P('M5 7c4-3 10-3 14 0 2 4 1 9-3 11-4 2-9 1-11-3-1.5-3-1.5-6 0-8z', 'thick'), P('M8 12c3-1.5 5-1.5 8 0', 'thin')], + surfaceTrim: [P('M3 17c3-2.5 6-2.5 9 0V9C9 6.5 6 6.5 3 9z', 'a'), P('M3 17c3-2.5 6-2.5 9 0V9C9 6.5 6 6.5 3 9z'), DASH('M12 17c3 2.5 6 2.5 9 0V9c-3 2.5-6 2.5-9 0', '2 2'), P('M12 3v18', 'thin')], + surfaceExtend: [P('M3 17c3-2.5 6-2.5 9 0V9C9 6.5 6 6.5 3 9z', 'a'), P('M3 17c3-2.5 6-2.5 9 0V9C9 6.5 6 6.5 3 9z'), DASH('M12 17c2 1.6 4 2.2 6 1.5M12 9c2 1.6 4 2.2 6 1.5', '2 2'), P('M16 13h5M19 11l2 2-2 2', 'thin')], + surfaceKnit: [P('M3 17c2-2 5-2 8 0V8C8 6 5 6 3 8z', 'a'), P('M13 17c3 2 6 2 8 0V8c-2 2-5 2-8 0z', 's'), P('M3 17c2-2 5-2 8 0V8C8 6 5 6 3 8zM13 17c3 2 6 2 8 0V8c-2 2-5 2-8 0z'), P('M10 10.5h4M10 13.5h4M10 16.5h4', 'thin')], + thicken: [P('M3 14c3-2.5 6-2.5 9 0s6 2.5 9 0V9c-3 2.5-6 2.5-9 0S6 6.5 3 9z', 'a'), P('M3 14c3-2.5 6-2.5 9 0s6 2.5 9 0v4c-3 2.5-6 2.5-9 0s-6-2.5-9 0z', 's'), P('M3 9c3-2.5 6-2.5 9 0s6 2.5 9 0v9c-3 2.5-6 2.5-9 0s-6-2.5-9 0z'), P('M3 14c3-2.5 6-2.5 9 0s6 2.5 9 0', 'thin')], + thickenCut: [P('M3 8l9-4 9 4v10l-9 4-9-4z', 's'), P('M3 8l9-4 9 4v10l-9 4-9-4z'), P('M7 11c2-1.5 4-1.5 5 0s3 1.5 5 0v4c-2 1.5-4 1.5-5 0s-3-1.5-5 0z', 'a'), P('M7 11c2-1.5 4-1.5 5 0s3 1.5 5 0v4c-2 1.5-4 1.5-5 0s-3-1.5-5 0z')], + surfaceCut: [P('M4 13l8-4 8 4v6l-8 4-8-4z', 's'), P('M4 13v6l8 4 8-4v-6'), DASH('M4 13l8 4 8-4M12 17v6', '2 1.5'), P('M2 12c3-3 7-3 10-1s7 2 10-1', 'thick-a'), P('M12 2v6M10 6l2 2 2-2', 'thin')], + deleteFace: [DASH('M4 8l8-4 8 4-8 4z', '2 2'), P('M4 8v9l8 4 8-4V8', 's'), P('M4 8v9l8 4 8-4V8M12 12v9'), P('M10 6.5l4 3M14 6.5l-4 3', 'thin')], +}; diff --git a/src/parametric/tests/assembly-kernel.test.ts b/src/parametric/tests/assembly-kernel.test.ts new file mode 100644 index 0000000000..5b097382d4 --- /dev/null +++ b/src/parametric/tests/assembly-kernel.test.ts @@ -0,0 +1,183 @@ +// Assemblies on the real OpenCascade kernel in Node: parts built per +// component, placed copies combined, interference, mass, STEP and STL. +import { beforeAll, describe, expect, it } from 'vitest'; +import init from 'replicad-opencascadejs'; +import * as R from 'replicad'; +import { AssemblyBuilder, type AsmPartResult, type AsmSceneItem } from '../src/kernel/assembly'; +import { bbox, setOc, subShapes, volumeOf, wrap } from '../src/kernel/occ'; +import { ModelBuilder } from '../src/kernel/build'; +import { placementMatrix } from '../src/assembly/compose'; +import { qAxisAngle } from '../src/math/vec'; +import type { Placement } from '../src/model/assembly'; +import { circle, extrude, rect, sketch } from './helpers'; +import { newSurfaceFeature } from '../src/model/surfaces'; +import type { Feature } from '../src/model/types'; + +beforeAll(async () => { + setOc(await init()); +}); + +const box = () => [sketch('S1', rect(0, 0, 20, 10)), extrude('E1', 'S1', 10)]; +const pin = () => [sketch('S1', circle(0, 0, 3)), extrude('E1', 'S1', 30)]; +const item = (part: string, pl: Placement, name: string): AsmSceneItem => ({ part, m: placementMatrix(pl), name, color: '#888888' }); +const at = (p: [number, number, number], q: [number, number, number, number] = [0, 0, 0, 1]): Placement => ({ p, q }); + +async function built(a: AssemblyBuilder) { + const res = await a.build([ + { key: 'box', features: box(), blobs: {}, quality: 0 }, + { key: 'pin', features: pin(), blobs: {}, quality: 0 }, + ]); + return Object.fromEntries(res.map((r) => [r.key, r])) as Record; +} + +describe('assembly geometry', () => { + it('builds each part once and reports its faces', async () => { + const a = new AssemblyBuilder(); + const parts = await built(a); + expect(parts.box.faces).toHaveLength(6); + expect(parts.box.mesh!.indices.length).toBeGreaterThan(0); + expect(parts.pin.faces.some((f) => f.type === 'cylinder')).toBe(true); + expect(parts.box.status.every((s) => s.ok)).toBe(true); + }); + + it('combines placed components: volume, centre of mass and projections', async () => { + const a = new AssemblyBuilder(); + await built(a); + // Two boxes side by side and a pin standing clear of them. + a.setScene([item('box', at([0, 0, 0]), 'box<1>'), item('box', at([30, 0, 0]), 'box<2>'), item('pin', at([100, 0, 0], qAxisAngle([1, 0, 0], Math.PI / 2)), 'pin<1>')]); + const mp = a.massProperties()!; + expect(mp.volume).toBeCloseTo(2 * 2000 + Math.PI * 9 * 30, 0); + const m = a.mass([7800, 7800, 2700])!; + expect(m.mass).toBeCloseTo((4000 * 7800 + Math.PI * 9 * 30 * 2700) * 1e-9, 6); + expect(m.open).toEqual([]); + // The rotated pin points along -y (its 30 mm length from z turned about x). + const combined = a.combined()!; + const solids = subShapes(combined, 'solid'); + expect(solids).toHaveLength(3); + const proj = a.project([{ id: 'front', dir: [0, 0, 1], x: [1, 0, 0], hidden: false }]); + expect(proj[0].visible.length).toBeGreaterThan(0); + // Measuring between faces of different components (indices in scene order). + const right = 6 + 0; // first face of box<2> + const d = a.measure({ kind: 'face', index: right }, { kind: 'face', index: 0 }); + expect(d.distance).toBeGreaterThanOrEqual(0); + }); + + it('weighs hidden components, but leaves them out of measuring, interference and export', async () => { + const a = new AssemblyBuilder(); + await built(a); + // A hidden box first: the shown pin's faces are numbered from 0, as the graphics area lists them. + a.setScene([{ ...item('box', at([0, 0, 0]), 'box<1>'), hidden: true }, item('pin', at([5, 5, -10]), 'pin<1>')]); + const m = a.mass([7800, 2700])!; + expect(m.volume).toBeCloseTo(2000 + Math.PI * 9 * 30, 0); + expect(m.mass).toBeCloseTo((2000 * 7800 + Math.PI * 9 * 30 * 2700) * 1e-9, 6); + expect(a.massProperties()!.volume).toBeCloseTo(2000 + Math.PI * 9 * 30, 0); + expect(a.interference()).toEqual([]); + expect(subShapes(a.combined()!, 'solid')).toHaveLength(1); + // Face 0 is the pin's (about 20 mm below the point; the hidden box is 30 mm or more away). + const d = a.measure({ kind: 'face', index: 0 }, { kind: 'vertex', p: [5, 5, 40] }); + expect(d.distance).toBeLessThan(25); + }); + + it('finds interfering components and the volume they share', async () => { + const a = new AssemblyBuilder(); + await built(a); + // box<2> overlaps box<1> by 5 mm in x (5 × 10 × 10); the pin passes through box<1> (r 3, 10 mm deep). + a.setScene([item('box', at([0, 0, 0]), 'box<1>'), item('box', at([15, 0, 0]), 'box<2>'), item('pin', at([5, 5, -10]), 'pin<1>'), item('box', at([0, 40, 0]), 'box<3>')]); + const pairs = a.interference(); + const find = (x: number, y: number) => pairs.find((p) => p.a === x && p.b === y); + expect(find(0, 1)!.volume).toBeCloseTo(500, 3); + expect(find(0, 2)!.volume).toBeCloseTo(Math.PI * 9 * 10, 1); + expect(find(0, 1)!.mesh!.indices.length).toBeGreaterThan(0); + // Touching without overlapping is not interference. + expect(pairs.some((p) => p.a === 3 || p.b === 3)).toBe(false); + expect(pairs).toHaveLength(2); + a.setScene([item('box', at([0, 0, 0]), 'box<1>'), item('box', at([20, 0, 0]), 'box<2>')]); + expect(a.interference()).toEqual([]); + }); + + it('reports a pair whose overlap cannot be computed as not checked, never as clear', async () => { + const a = new AssemblyBuilder(); + await built(a); + a.setScene([item('box', at([0, 0, 0]), 'box<1>'), item('box', at([15, 0, 0]), 'box<2>')]); + (a as unknown as { sharedSolid: () => never }).sharedSolid = () => { throw new Error('boolean failed'); }; + expect(a.interference()).toEqual([{ a: 0, b: 1, volume: 0, mesh: null, failed: true }]); + }); + + it('measures, draws and exports the surface bodies of a part, but weighs and checks interference of solids only', async () => { + const a = new AssemblyBuilder(); + // A 20 × 10 × 10 box with a 30 × 30 open surface sheet (an extruded line) above it. + const sheet: Feature[] = [ + sketch('S2', [{ id: 'q0', t: 'point', x: -5, y: 20 }, { id: 'q1', t: 'point', x: 25, y: 20 }, { id: 'ql', t: 'line', a: 'q0', b: 'q1' }]), + { ...newSurfaceFeature('surfaceExtrude', 'F1', 'F1', 10), sketch: 'S2', depth: 30 } as Feature, + ]; + const [withSheet] = await a.build([{ key: 'sheet', features: [...box(), ...sheet], blobs: {}, quality: 0 }]); + await built(a); + expect(withSheet.status.every((s) => s.ok)).toBe(true); + const solidFaces = withSheet.faces.filter((f) => !f.body).length; + expect(withSheet.faces.length).toBeGreaterThan(solidFaces); + // The sheet part first, then a box: the box's faces are numbered after the sheet's. + a.setScene([item('sheet', at([0, 0, 0]), 'plate<1>'), item('box', at([100, 0, 0]), 'box<1>')]); + const boxFace = withSheet.faces.length; // the first face of box<1> + expect(a.measure({ kind: 'face', index: boxFace }, { kind: 'vertex', p: [100, 5, 5] }).distance).toBeLessThan(10.01); + // The sheet itself can be measured (it is 20 above the box's base sketch plane, along y). + const sheetFace = withSheet.faces.findIndex((f) => f.body); + expect(a.measure({ kind: 'face', index: sheetFace }, { kind: 'vertex', p: [10, 30, 15] }).distance).toBeCloseTo(10, 4); + // STEP: the sheet goes in as a shell beside the solids. + const step = new TextDecoder().decode(await a.exportStep()); + expect(step).toMatch(/SHELL_BASED_SURFACE_MODEL|OPEN_SHELL/); + // Mass: solids only. + expect(a.mass([1000, 1000])!.volume).toBeCloseTo(4000, 0); + // Drawings: the front view reaches up to the sheet (y = 20). + const [front] = a.project([{ id: 'f', dir: [0, 0, 1], x: [1, 0, 0], hidden: false }]); + expect(front.bounds![3] - front.bounds![1]).toBeGreaterThan(19); + // Interference: the box overlapping only the sheet is not an interference of solids. + a.setScene([item('sheet', at([0, 0, 0]), 'plate<1>'), item('box', at([0, 15, 0]), 'box<2>')]); + expect(a.interference()).toEqual([]); + }); + + it('exports a STEP file with each component as a named solid, and leaves part export as it was', async () => { + const part = new ModelBuilder(); + await part.build({ features: box(), upTo: 2, blobs: {}, quality: 0 }); + const before = new TextDecoder().decode(part.exportStep('Block')).replace(/\d{4}-\d\d-\d\dT[\d:]+/g, ''); + const a = new AssemblyBuilder(); + await built(a); + a.setScene([item('box', at([0, 0, 0]), 'bracket<1>'), item('box', at([40, 0, 0], qAxisAngle([0, 0, 1], 0.5)), 'bracket<2>'), item('pin', at([0, 0, 20]), 'pin<1>')]); + const data = await a.exportStep(); + const text = new TextDecoder().decode(data); + expect(text).toContain('bracket<1>'); + expect(text).toContain('bracket<2>'); + expect(text).toContain('pin<1>'); + // Read back: three solids with the components' total volume. + const shape = await R.importSTEP(new Blob([data as BlobPart])); + const solids = subShapes(wrap(shape.wrapped), 'solid'); + expect(solids).toHaveLength(3); + const total = solids.reduce((s, x) => s + volumeOf(x), 0); + expect(total).toBeCloseTo(4000 + Math.PI * 9 * 30, 0); + // A part exported afterwards is written exactly as before. + const after = new TextDecoder().decode(part.exportStep('Block')).replace(/\d{4}-\d\d-\d\dT[\d:]+/g, ''); + expect(after).toBe(before); + const stl = a.exportStl(1); + const tris = new DataView(stl.buffer).getUint32(80, true); + expect(tris).toBeGreaterThan(24); + expect(stl.length).toBe(84 + tris * 50); + }); + + it('a STEP export read back has each component where it was placed, under its own name', async () => { + const a = new AssemblyBuilder(); + await built(a); + // The box (20 × 10 × 10 from the origin) moved, and turned a quarter about z. + a.setScene([item('box', at([100, 0, 0]), 'bracket<1>'), item('box', at([0, 50, 0], qAxisAngle([0, 0, 1], Math.PI / 2)), 'bracket<2>')]); + const data = await a.exportStep(); + const text = new TextDecoder().decode(data); + expect(text.match(/PRODUCT\('bracket<1>'/g)).toHaveLength(1); + expect(text.match(/PRODUCT\('bracket<2>'/g)).toHaveLength(1); + const shape = await R.importSTEP(new Blob([data as BlobPart])); + const boxes = subShapes(wrap(shape.wrapped), 'solid').map((x) => bbox(x)!).sort((p, q) => q.min[0] - p.min[0]); + const near = (v: number[], w: number[]) => v.forEach((x, i) => expect(x).toBeCloseTo(w[i], 3)); + near(boxes[0].min, [100, 0, 0]); + near(boxes[0].max, [120, 10, 10]); + // Turned: x from -10 to 0, y from 50 to 70. + near(boxes[1].min, [-10, 50, 0]); + near(boxes[1].max, [0, 70, 10]); + }); +}); diff --git a/src/parametric/tests/assembly-model.test.ts b/src/parametric/tests/assembly-model.test.ts new file mode 100644 index 0000000000..5d1c48356a --- /dev/null +++ b/src/parametric/tests/assembly-model.test.ts @@ -0,0 +1,166 @@ +import { describe, expect, it } from 'vitest'; +import { + ASSEMBLY_FORMAT, type AssemblyDocument, MAX_COMPONENTS, MAX_MATES, PartCache, assemblyBom, bomCsv, instanceName, isAssembly, newAssembly, nextAsmId, parseAnyDocument, parseAssembly, +} from '../src/model/assembly'; +import { DocStore, newDocument, parseDocument, serializeDocument, withUsedBlobs } from '../src/model/document'; +import { composeModel, placementMatrix, splitName, type PartGeometry } from '../src/assembly/compose'; +import { qAxisAngle } from '../src/math/vec'; +import type { MeshData } from '../src/kernel/protocol'; + +function sample(): AssemblyDocument { + const doc = newAssembly('Hinge'); + const block = newDocument('Block'); + block.material = { name: 'Steel', density: 7800 }; + const pin = newDocument('Pin'); + doc.blobs.a1 = serializeDocument(block); + doc.blobs.a2 = serializeDocument(pin); + doc.parts = [ + { id: 'p1', name: 'Block', source: { type: 'local', id: 'part-1' }, version: { modified: 5, size: 10 }, blob: 'a1', color: '#b8c4d2' }, + { id: 'p2', name: 'Pin', source: { type: 'cloud', path: '/u/Parts/Pin.parametric' }, version: null, blob: 'a2', color: '#e0a85a' }, + ]; + doc.components = [ + { id: 'c3', name: 'Block<1>', part: 'p1', placement: { p: [0, 0, 0], q: [0, 0, 0, 1] }, fixed: true }, + { id: 'c4', name: 'Pin<1>', part: 'p2', placement: { p: [10, 10, 0], q: qAxisAngle([1, 0, 0], 0.3) }, fixed: false }, + { id: 'c5', name: 'Pin<2>', part: 'p2', placement: { p: [30, 10, 0], q: [0, 0, 0, 1] }, fixed: false, hidden: true }, + { id: 'c6', name: 'Pin<3>', part: 'p2', placement: { p: [50, 10, 0], q: [0, 0, 0, 1] }, fixed: false, suppressed: true }, + ]; + doc.mates = [ + { id: 'm7', name: 'Concentric1', type: 'concentric', a: { comp: 'c3', face: { name: 'E1:side:h', sig: { type: 'cylinder', c: [10, 10, 5], area: 250 } } }, b: { comp: 'c4', face: { name: 'E1:side:k', sig: { type: 'cylinder', c: [0, 0, 15], area: 750 } } }, aligned: true }, + { id: 'm8', name: 'Distance1', type: 'distance', a: { plane: 'front' }, b: { comp: 'c4', edge: { name: 'a|b', sig: { type: 'circle', m: [0, 0, 0], len: 25 } } }, aligned: false, value: '=Gap*2', flip: true }, + { id: 'm9', name: 'Lock1', type: 'lock', a: { comp: 'c3' }, b: { comp: 'c5' }, aligned: true, rel: { p: [30, 10, 0], q: [0, 0, 0, 1] }, suppressed: true }, + ]; + doc.explode = [{ id: 'x10', name: 'Explode Step1', comps: ['c4'], dir: [0, 0, 1], distance: 50 }]; + doc.exploded = true; + doc.variables = [{ id: 'v11', name: 'Gap', expr: '2' }]; + return doc; +} + +describe('assembly documents', () => { + it('round-trips through the file format and keeps the parts it embeds', () => { + const doc = sample(); + const text = serializeDocument(doc as never); + expect(text.startsWith(`{"format":"${ASSEMBLY_FORMAT}"`)).toBe(true); + const back = parseAssembly(text); + expect(back).toEqual({ ...doc, nextId: 12 }); + expect(isAssembly(back)).toBe(true); + expect(parseAnyDocument(text)).toEqual(back); + // Each embedded copy is a part document of its own. + expect(parseDocument(back.blobs.a1).material?.name).toBe('Steel'); + }); + + it('opens parts exactly as before', () => { + const part = newDocument('Plate'); + const text = serializeDocument(part); + expect(parseAnyDocument(text)).toEqual(parseDocument(text)); + expect(() => parseAnyDocument('{}')).toThrow(/not a part/); + }); + + it('keeps used part copies out of undo history and drops unused ones from the file', () => { + const doc = sample(); + doc.blobs.old = 'stale copy'; + expect(Object.keys(withUsedBlobs(doc as never).blobs).sort()).toEqual(['a1', 'a2']); + const st = new DocStore(doc as never); + st.change('Rename', (d) => { d.name = 'Other'; }); + st.undo(); + expect(st.doc.name).toBe('Hinge'); + expect(st.doc.blobs.a1).toBe(doc.blobs.a1); + }); + + it('refuses damaged files with a clear message', () => { + const doc = sample(); + const bad = (patch: (d: Record) => void) => { + const raw = JSON.parse(serializeDocument(doc as never)); + patch(raw); + return () => parseAssembly(JSON.stringify(raw)); + }; + expect(bad((d) => { d.version = 2; })).toThrow(/newer version/); + expect(bad((d) => { delete d.components; })).toThrow(/damaged \(no component list\)/); + expect(bad((d) => { (d.components as { part: string }[])[0].part = 'nope'; })).toThrow(/invalid component/); + expect(bad((d) => { (d.parts as { blob: string }[])[0].blob = 'missing'; })).toThrow(/invalid part/); + expect(bad((d) => { (d.mates as { type: string }[])[0].type = 'glue'; })).toThrow(/invalid mate/); + expect(bad((d) => { (d.mates as { b: unknown }[])[0].b = { comp: 'c99' }; })).toThrow(/invalid mate/); + expect(bad((d) => { (d.explode as { comps: string[] }[])[0].comps = ['c99']; })).toThrow(/explode step/); + expect(bad((d) => { (d.components as { placement: unknown }[])[1].placement = { p: [0, 0], q: [0, 0, 0, 1] }; })).toThrow(/invalid component/); + expect(() => parseAssembly('not json')).toThrow(/not a valid assembly/); + }); + + it('refuses hand-edited files with NaN or infinite placements, duplicate ids or huge lists, without crashing', () => { + const text = serializeDocument(sample() as never); + const edit = (patch: (d: Record) => void) => { const raw = JSON.parse(text); patch(raw); return () => parseAssembly(JSON.stringify(raw)); }; + // JSON has no NaN: a hand edit writes a string, null, or a number too big for a double (read as Infinity). + expect(edit((d) => { d.components[1].placement.p[0] = 'NaN'; })).toThrow(/invalid component/); + expect(edit((d) => { d.components[1].placement.q[0] = null; })).toThrow(/invalid component/); + expect(() => parseAssembly(text.replace(/"p":\[[^\]]*\]/, '"p":[1e999,0,0]'))).toThrow(/invalid component/); + expect(edit((d) => { d.components[1].id = d.components[0].id; })).toThrow(/invalid component/); + expect(edit((d) => { d.mates[0].id = d.components[0].id; })).toThrow(/invalid mate/); + expect(edit((d) => { d.blobs = {}; })).toThrow(/invalid part/); + const many = (n: number) => edit((d) => { d.mates = []; d.explode = []; d.components = Array.from({ length: n }, (_, i) => ({ ...d.components[0], id: `k${i}`, name: `K<${i}>` })); }); + expect(many(MAX_COMPONENTS + 1)).toThrow(/more than Parametric can open/); + expect(many(MAX_COMPONENTS)).not.toThrow(); + expect(edit((d) => { d.mates = Array.from({ length: MAX_MATES + 1 }, (_, i) => ({ ...d.mates[0], id: `q${i}` })); })).toThrow(/mates, more than/); + // A step listing a component many times lists it once. + const steps = parseAssembly(JSON.stringify({ ...JSON.parse(text), explode: [{ ...JSON.parse(text).explode[0], comps: new Array(5000).fill(JSON.parse(text).explode[0].comps[0]) }] })); + expect(steps.explode[0].comps).toHaveLength(1); + }); + + it('allocates ids past those in use, and instance names per part', () => { + const doc = sample(); + const back = parseAssembly(JSON.stringify({ ...doc, nextId: 1 })); + expect(nextAsmId(back, 'c')).toBe('c12'); + expect(instanceName(back, 'Pin')).toBe('Pin<4>'); + expect(instanceName(back, 'Bracket')).toBe('Bracket<1>'); + }); + + it('lists the bill of materials: parts in order, quantities without suppressed components, materials', () => { + const doc = sample(); + const cache = new PartCache(parseDocument); + const rows = assemblyBom(doc, (id) => cache.get(doc, id).doc); + expect(rows.map((r) => [r.item, r.name, r.quantity, r.material])).toEqual([[1, 'Block', 1, 'Steel'], [2, 'Pin', 2, '']]); + expect(bomCsv(rows)).toBe('Item No.,Part Name,Quantity,Material\n1,Block,1,Steel\n2,Pin,2,'); + // Copied as tab-separated text: a comma in a name stays in its cell; a tab or quote is quoted. + const named = [{ ...rows[0], name: 'Plate, top' }, { ...rows[1], name: 'Pin\t"A"' }]; + expect(bomCsv(named, '\t')).toBe('Item No.\tPart Name\tQuantity\tMaterial\n1\tPlate, top\t1\tSteel\n2\t"Pin\t""A"""\t2\t'); + expect(bomCsv(named)).toBe('Item No.,Part Name,Quantity,Material\n1,"Plate, top",1,Steel\n2,"Pin\t""A""",2,'); + expect(assemblyBom(newAssembly())).toEqual([]); + }); + + it('reports a damaged part copy as an error of that part only', () => { + const doc = sample(); + doc.blobs.a2 = '{"format":"parametric-part","version":1,"features":[{"id":"x","type":"bogus"}]}'; + const cache = new PartCache(parseDocument); + expect(cache.get(doc, 'p1').doc).not.toBeNull(); + expect(cache.get(doc, 'p2').error).toMatch(/damaged/); + }); +}); + +describe('combined model', () => { + const tri = (): MeshData => ({ + positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]), indices: new Uint32Array([0, 1, 2]), + vertexFace: new Float32Array([0, 0, 0]), edgePositions: new Float32Array([0, 0, 0, 1, 0, 0]), edgeIds: new Float32Array([0, 0]), vertices: new Float32Array([0, 0, 0]), + }); + const geom = (): PartGeometry => ({ + mesh: tri(), faces: [{ name: 'F', type: 'plane', center: [0.3, 0.3, 0], area: 0.5, normal: [0, 0, 1], feature: 'E1' }], + edges: [{ name: 'E', type: 'line', a: [0, 0, 0], b: [1, 0, 0], mid: [0.5, 0, 0], length: 1, faces: [0], dir: [1, 0, 0] }], bbox: { min: [0, 0, 0], max: [1, 1, 0] }, cones: {}, + }); + + it('places each component and numbers faces and edges after those before it', () => { + const comp = (id: string) => ({ id, name: id, part: 'p', placement: { p: [0, 0, 0], q: [0, 0, 0, 1] }, fixed: false }) as never; + const m = composeModel([ + { comp: comp('c1'), placement: { p: [0, 0, 0], q: [0, 0, 0, 1] }, geom: geom(), color: [1, 0, 0] }, + { comp: comp('c2'), placement: { p: [10, 0, 0], q: qAxisAngle([0, 0, 1], Math.PI / 2) }, geom: geom(), color: [0, 1, 0] }, + ]); + expect(m.faces.map((f) => f.name)).toEqual(['c1#F', 'c2#F']); + expect(m.faces[1].feature).toBe('c2'); + expect(splitName(m.faces[1].name)).toEqual({ comp: 'c2', name: 'F' }); + expect([...m.mesh!.vertexFace]).toEqual([0, 0, 0, 1, 1, 1]); + expect([...m.mesh!.indices]).toEqual([0, 1, 2, 3, 4, 5]); + expect([...m.mesh!.edgeIds]).toEqual([0, 0, 1, 1]); + // (1, 0, 0) turned a quarter about z and moved to x = 10. + expect(m.mesh!.positions[12]).toBeCloseTo(10, 6); + expect(m.mesh!.positions[13]).toBeCloseTo(1, 6); + expect(m.edges[1].dir![1]).toBeCloseTo(1, 6); + expect([...m.faceColors]).toEqual([255, 0, 0, 255, 0, 255, 0, 255]); + expect(m.bbox!.max[0]).toBeCloseTo(10, 6); + expect(placementMatrix({ p: [1, 2, 3], q: [0, 0, 0, 1] })).toEqual([1, 0, 0, 1, 0, 1, 0, 2, 0, 0, 1, 3]); + }); +}); diff --git a/src/parametric/tests/assembly-solver.test.ts b/src/parametric/tests/assembly-solver.test.ts new file mode 100644 index 0000000000..8e5720282a --- /dev/null +++ b/src/parametric/tests/assembly-solver.test.ts @@ -0,0 +1,293 @@ +import { describe, expect, it } from 'vitest'; +import { type Geo, MateSolver, type SolverBody, type SolverMate, applyPlacement, fittingMates, initialMateSettings, matesMoving, matrixRank, placeGeo, relativePlacement } from '../src/assembly/solver'; +import { type Quat, type Vec3, cross, dot, len, normalize, qAxisAngle, qRotate, sub } from '../src/math/vec'; +import type { MateType, Placement } from '../src/model/assembly'; + +// A 10 mm cube centred on its origin: its six faces and a hole along y. +const face = (n: Vec3): Geo => ({ kind: 'plane', o: [n[0] * 5, n[1] * 5, n[2] * 5], n }); +const TOP = face([0, 1, 0]), BOTTOM = face([0, -1, 0]), RIGHT = face([1, 0, 0]), FRONT = face([0, 0, 1]), BACK = face([0, 0, -1]); +const HOLE: Geo = { kind: 'axis', p: [0, 0, 0], d: [0, 1, 0], r: 2, surface: 'cylinder' }; + +const body = (id: string, fixed: boolean, p: Vec3 = [0, 0, 0], q: Quat = [0, 0, 0, 1]): SolverBody => ({ id, fixed, placement: { p, q } }); +let n = 0; +const mate = (type: MateType, a: [string | null, Geo], b: [string | null, Geo], extra: Partial = {}): SolverMate => ({ + id: `m${++n}`, type, a: { body: a[0], geo: a[1] }, b: { body: b[0], geo: b[1] }, aligned: false, value: 0, flip: false, ...extra, +}); +const world = (pl: Map, id: string, g: Geo) => placeGeo(g, pl.get(id)!); +const tilted: Quat = qAxisAngle(normalize([1, 2, 3]), 0.6); + +describe('mate solver', () => { + it('coincident planes put the faces together, facing each other, leaving three degrees of freedom', () => { + const s = new MateSolver([body('base', true), body('blk', false, [30, 40, -7], tilted)], [mate('coincident', ['base', TOP], ['blk', BOTTOM])]); + const r = s.analyze(); + expect(r.status).toBe('under'); + expect(r.dof).toBe(3); + const bottom = world(r.placements, 'blk', BOTTOM) as Extract; + expect(bottom.o[1]).toBeCloseTo(5, 6); + expect(dot(bottom.n, [0, -1, 0])).toBeCloseTo(1, 8); + expect(r.defined.size).toBe(0); + }); + + it('three pairs of coincident faces fully define a block', () => { + const s = new MateSolver([body('base', true), body('blk', false, [12, 9, 3], tilted)], [ + mate('coincident', ['base', TOP], ['blk', BOTTOM]), + mate('coincident', ['base', RIGHT], ['blk', RIGHT], { aligned: true }), + mate('coincident', ['base', FRONT], ['blk', FRONT], { aligned: true }), + ]); + const r = s.analyze(); + expect(r.status).toBe('full'); + expect(r.dof).toBe(0); + expect(r.defined.has('blk')).toBe(true); + const p = r.placements.get('blk')!; + expect(p.p[0]).toBeCloseTo(0, 6); + expect(p.p[1]).toBeCloseTo(10, 6); + expect(p.p[2]).toBeCloseTo(0, 6); + }); + + it('reports the later of two conflicting mates and keeps the first', () => { + const s = new MateSolver([body('base', true), body('blk', false, [0, 20, 0])], [ + mate('coincident', ['base', TOP], ['blk', BOTTOM]), + mate('distance', ['base', TOP], ['blk', BOTTOM], { value: 5 }), + ]); + const r = s.analyze(); + expect(r.status).toBe('over'); + expect([...r.conflicts]).toEqual([s.mates[1].id]); + expect((world(r.placements, 'blk', BOTTOM) as { o: Vec3 }).o[1]).toBeCloseTo(5, 6); + }); + + it('a mate that cannot be formed is an error, not a conflict', () => { + const s = new MateSolver([body('base', true), body('blk', false, [0, 20, 0])], [ + mate('coincident', ['base', TOP], ['blk', BOTTOM]), + mate('coincident', ['blk', TOP], ['blk', BOTTOM]), + ]); + const r = s.analyze(); + expect(r.status).toBe('error'); + expect(r.conflicts.size).toBe(0); + expect(r.invalid.has(s.mates[1].id)).toBe(true); + expect(r.dof).toBe(3); + }); + + it('counts degrees of freedom right at a 0° or 180° angle and at a zero distance', () => { + for (const [value, aligned] of [[0, true], [180, true], [0, false], [180, false]] as [number, boolean][]) { + const r = new MateSolver([body('base', true), body('blk', false, [12, 9, 3], tilted)], [mate('angle', ['base', TOP], ['blk', TOP], { value, aligned })]).analyze(); + expect(r.status).toBe('under'); + // As a parallel mate: two turns are fixed. + expect(r.dof).toBe(4); + const n = (world(r.placements, 'blk', TOP) as { n: Vec3 }).n; + expect(dot(n, [0, 1, 0])).toBeCloseTo((value === 0) === aligned ? 1 : -1, 8); + } + expect(new MateSolver([body('base', true), body('blk', false, [12, 9, 3], tilted)], [mate('angle', ['base', TOP], ['blk', TOP], { value: 45, aligned: true })]).analyze().dof).toBe(5); + // Circular edges at zero distance: centres together, three moves fixed. + const rim: Geo = { kind: 'axis', p: [0, 5, 0], d: [0, 1, 0], r: 2, surface: 'circle' }; + const z = new MateSolver([body('base', true), body('blk', false, [12, 9, 3], tilted)], [mate('distance', ['base', rim], ['blk', rim], { value: 0 })]).analyze(); + expect(z.dof).toBe(3); + expect(len(sub((world(z.placements, 'blk', rim) as { p: Vec3 }).p, [0, 5, 0]))).toBeLessThan(1e-6); + // Parallel axes at zero distance: one line, sliding and turning left. + const zl = new MateSolver([body('base', true), body('pin', false, [5, 3, 2], tilted)], [mate('distance', ['base', HOLE], ['pin', { ...HOLE, surface: 'cone' } as Geo], { value: 0, aligned: true })]).analyze(); + expect(zl.dof).toBe(2); + }); + + it('distance keeps parallel faces apart by the value, on the side they start on', () => { + const s = new MateSolver([body('base', true), body('blk', false, [3, 40, 1], qAxisAngle([0, 0, 1], 0.2))], [mate('distance', ['base', TOP], ['blk', BOTTOM], { value: 12 })]); + const r = s.solve(); + expect(r.ok).toBe(true); + expect((world(r.placements, 'blk', BOTTOM) as { o: Vec3 }).o[1]).toBeCloseTo(17, 6); + const flipped = new MateSolver(s.bodies, [{ ...s.mates[0], flip: true }]).solve(); + expect((world(flipped.placements, 'blk', BOTTOM) as { o: Vec3 }).o[1]).toBeCloseTo(-7, 6); + }); + + it('concentric aligns axes and leaves sliding and turning free', () => { + const pin: Geo = { kind: 'axis', p: [0, 0, 0], d: [0, 0, 1], r: 2, surface: 'cylinder' }; + const s = new MateSolver([body('base', true), body('pin', false, [5, 3, 2], tilted)], [mate('concentric', ['base', HOLE], ['pin', pin], { aligned: true })]); + const r = s.analyze(); + expect(r.dof).toBe(2); + const a = world(r.placements, 'pin', pin) as { p: Vec3; d: Vec3 }; + expect(Math.abs(dot(a.d, [0, 1, 0]))).toBeCloseTo(1, 8); + expect(len(cross(a.p, [0, 1, 0]))).toBeCloseTo(0, 6); + }); + + it('parallel, perpendicular and angle mates set directions', () => { + const start = body('blk', false, [20, 0, 0], tilted); + const par = new MateSolver([body('base', true), start], [mate('parallel', ['base', TOP], ['blk', TOP], { aligned: true })]).analyze(); + expect(dot((world(par.placements, 'blk', TOP) as { n: Vec3 }).n, [0, 1, 0])).toBeCloseTo(1, 8); + expect(par.dof).toBe(4); + const perp = new MateSolver([body('base', true), start], [mate('perpendicular', ['base', TOP], ['blk', TOP])]).analyze(); + expect(dot((world(perp.placements, 'blk', TOP) as { n: Vec3 }).n, [0, 1, 0])).toBeCloseTo(0, 8); + expect(perp.dof).toBe(5); + const ang = new MateSolver([body('base', true), start], [mate('angle', ['base', TOP], ['blk', TOP], { value: 30, aligned: true })]).solve(); + expect(dot((world(ang.placements, 'blk', TOP) as { n: Vec3 }).n, [0, 1, 0])).toBeCloseTo(Math.cos(Math.PI / 6), 8); + }); + + it('tangent puts a cylinder against a plane', () => { + const roller: Geo = { kind: 'axis', p: [0, 0, 0], d: [1, 0, 0], r: 4, surface: 'cylinder' }; + const s = new MateSolver([body('base', true), body('roll', false, [0, 30, 0], qAxisAngle([0, 1, 0], 0.3))], [mate('tangent', ['base', TOP], ['roll', roller])]); + const r = s.solve(); + expect(r.ok).toBe(true); + const a = world(r.placements, 'roll', roller) as { p: Vec3; d: Vec3 }; + expect(a.p[1]).toBeCloseTo(9, 6); + expect(a.d[1]).toBeCloseTo(0, 8); + }); + + it('lock keeps two components where they were relative to each other', () => { + const a = body('a', false, [1, 2, 3], tilted), b = body('b', false, [10, 0, 0]); + const rel = relativePlacement(a.placement, b.placement); + const s = new MateSolver([body('base', true), a, b], [ + mate('coincident', ['base', TOP], ['a', BOTTOM]), + mate('lock', ['a', { kind: 'body' }], ['b', { kind: 'body' }], { rel }), + ]); + const r = s.analyze(); + expect(r.dof).toBe(3); + const after = relativePlacement(r.placements.get('a')!, r.placements.get('b')!); + expect(len(sub(after.p, rel.p))).toBeLessThan(1e-6); + }); + + it('mates to an assembly plane', () => { + const s = new MateSolver([body('blk', false, [4, 4, 4])], [mate('coincident', [null, { kind: 'plane', o: [0, 0, 0], n: [0, 0, 1] }], ['blk', BACK])]); + const r = s.solve(); + expect(r.ok).toBe(true); + expect((world(r.placements, 'blk', BACK) as { o: Vec3 }).o[2]).toBeCloseTo(0, 6); + }); + + it('turns a face that faces the wrong way for its alignment', () => { + const s = new MateSolver([body('base', true), body('blk', false, [0, 20, 0])], [mate('coincident', ['base', TOP], ['blk', TOP])]); + const r = s.solve(); + expect(r.ok).toBe(true); + expect(dot((world(r.placements, 'blk', TOP) as { n: Vec3 }).n, [0, -1, 0])).toBeCloseTo(1, 6); + }); + + it('dragging a lid on a hinge turns it about the hinge', () => { + // Base fixed; the lid's hinge axis (along z through its left edge) concentric with the base's pin. + const pin: Geo = { kind: 'axis', p: [0, 0, 0], d: [0, 0, 1], r: 1, surface: 'cylinder' }; + const lidHinge: Geo = { kind: 'axis', p: [-20, 0, 0], d: [0, 0, 1], r: 1, surface: 'cylinder' }; + const lidSide: Geo = { kind: 'plane', o: [0, 0, 5], n: [0, 0, 1] }; + const baseSide: Geo = { kind: 'plane', o: [0, 0, 5], n: [0, 0, 1] }; + const lid = body('lid', false, [20, 0, 0]); + const mates = [mate('concentric', ['base', pin], ['lid', lidHinge], { aligned: true }), mate('coincident', ['base', baseSide], ['lid', lidSide], { aligned: true })]; + const s = new MateSolver([body('base', true), lid], mates); + expect(s.analyze().dof).toBe(1); + // Grab the lid's far end (40 mm from the hinge) and drag it straight up. + const r = s.solve({ drag: { kind: 'move', body: 'lid', local: [20, 0, 0], target: [20, 30, 0] } }); + expect(r.ok).toBe(true); + const tip = applyPlacement(r.placements.get('lid')!, [20, 0, 0]); + // Still 40 mm from the hinge, and turned up toward the cursor. + expect(len(tip)).toBeCloseTo(40, 4); + expect(tip[1]).toBeGreaterThan(20); + const hinge = applyPlacement(r.placements.get('lid')!, [-20, 0, 0]); + expect(len(hinge)).toBeLessThan(1e-6); + }); + + it('a free drag follows the cursor; fixed components never move', () => { + const s = new MateSolver([body('base', true), body('blk', false)], []); + const r = s.solve({ drag: { kind: 'move', body: 'blk', local: [0, 0, 0], target: [5, 6, 7] } }); + const p = r.placements.get('blk')!.p; + expect(p[0]).toBeCloseTo(5, 3); + expect(p[1]).toBeCloseTo(6, 3); + const f = new MateSolver([body('base', true)], []).solve({ drag: { kind: 'move', body: 'base', local: [0, 0, 0], target: [5, 6, 7] } }); + expect(f.placements.get('base')!.p).toEqual([0, 0, 0]); + }); + + it('a drag slides a component without turning it when its mates let it slide', () => { + const turn = (q: Quat) => 2 * Math.acos(Math.min(1, Math.abs(q[3]))); + // Free, grabbed off its centre: carried exactly, not turned. + const free = new MateSolver([body('base', true), { ...body('blk', false, [40, 0, 0]), center: [0, 0, 0] }], []); + const r = free.solve({ maxIter: 25, drag: { kind: 'move', body: 'blk', local: [5, 5, 5], target: [100, 80, -60] } }); + expect(r.placements.get('blk')!.q).toEqual([0, 0, 0, 1]); + expect(applyPlacement(r.placements.get('blk')!, [5, 5, 5])).toEqual([100, 80, -60]); + // On a face (coincident), grabbed at a corner and dragged across in steps as the pointer + // moves: it slides on the face to the cursor and barely turns (it turned 9° before). + const onTop = mate('coincident', ['base', TOP], ['blk', BOTTOM]); + let pl: Placement = { p: [0, 10, 0], q: [0, 0, 0, 1] }; + for (let k = 1; k <= 10; k++) { + const s = new MateSolver([body('base', true), { ...body('blk', false), placement: pl, center: [0, 0, 0] }], [onTop]); + const res = s.solve({ maxIter: 25, drag: { kind: 'move', body: 'blk', local: [20, 5, 0], target: [0, 15, 8 * k] } }); + expect(res.ok).toBe(true); + pl = res.placements.get('blk')!; + } + const tip = applyPlacement(pl, [20, 5, 0]); + expect(Math.hypot(tip[0], tip[2] - 80)).toBeLessThan(1e-3); + expect(turn(pl.q)).toBeLessThan(0.01); + }); + + it('rotating toward an orientation respects mates', () => { + const s = new MateSolver([body('base', true), body('blk', false, [0, 10, 0])], [mate('coincident', ['base', TOP], ['blk', BOTTOM])]); + const r = s.solve({ drag: { kind: 'rotate', body: 'blk', q: qAxisAngle(normalize([1, 1, 0]), 0.5) } }); + expect(r.ok).toBe(true); + // Only the turn about the face normal is allowed. + expect(dot(qRotate(r.placements.get('blk')!.q, [0, -1, 0]), [0, -1, 0])).toBeCloseTo(1, 6); + }); + + it('suggests the mates that fit two entities and takes settings from where they are', () => { + expect(fittingMates(HOLE, { kind: 'axis', p: [0, 0, 0], d: [0, 1, 0], r: 2, surface: 'cylinder' })[0]).toBe('concentric'); + expect(fittingMates(TOP, BOTTOM)).toContain('coincident'); + expect(fittingMates(TOP, BOTTOM)).not.toContain('concentric'); + expect(fittingMates(TOP, { kind: 'axis', p: [0, 0, 0], d: [1, 0, 0], r: 3, surface: 'cylinder' })[0]).toBe('tangent'); + const st = initialMateSettings('distance', TOP, placeGeo(BOTTOM, { p: [0, 20, 0], q: [0, 0, 0, 1] })); + expect(st.value).toBeCloseTo(10, 9); + expect(st.flip).toBe(false); + expect(st.aligned).toBe(false); + }); + + it('computes matrix rank', () => { + expect(matrixRank([[1, 0, 0], [0, 1, 0], [1, 1, 0]], 3)).toBe(2); + expect(matrixRank([[1, 2], [2, 4]], 2)).toBe(1); + expect(matrixRank([], 3)).toBe(0); + }); + + it('tells fully defined components from those that move with an under-defined one', () => { + const full = (a: string, b: string) => [ + mate('coincident', [a, TOP], [b, BOTTOM]), + mate('coincident', [a, RIGHT], [b, RIGHT], { aligned: true }), + mate('coincident', [a, FRONT], [b, FRONT], { aligned: true }), + ]; + // c1 is fixed to the base; c3 is fixed to c2, which slides on c1; c4 turns on a pin. + const bodies = [body('base', true), body('c1', false, [20, 3, 1], tilted), body('c2', false, [40, 3, 1], tilted), body('c3', false, [60, 3, 1], tilted), body('c4', false, [80, 1, 1], tilted)]; + const r = new MateSolver(bodies, [ + ...full('base', 'c1'), mate('coincident', ['c1', TOP], ['c2', BOTTOM]), ...full('c2', 'c3'), + mate('concentric', ['base', HOLE], ['c4', HOLE], { aligned: true }), mate('coincident', ['base', TOP], ['c4', BOTTOM]), + ]).analyze(); + expect([...r.defined]).toEqual(['c1']); + expect(r.dof).toBe(3 + 1); + }); + + it('a drag solves only the mates of the components linked to the dragged one', () => { + const bodies = [body('base', true), body('a', false), body('b', false), body('c', false), body('d', false)]; + const ab = mate('coincident', ['a', TOP], ['b', BOTTOM]), bc = mate('coincident', ['b', TOP], ['c', BOTTOM]); + const baseA = mate('coincident', ['base', TOP], ['a', BOTTOM]), baseD = mate('coincident', ['base', TOP], ['d', BOTTOM]); + const planeC = mate('coincident', [null, FRONT], ['c', FRONT]); + const all = [ab, bc, baseA, baseD, planeC]; + // The base and the assembly planes do not move, so they do not link a to d. + expect(matesMoving('a', bodies, all).map((m) => m.id)).toEqual([ab, bc, baseA, planeC].map((m) => m.id)); + expect(matesMoving('d', bodies, all).map((m) => m.id)).toEqual([baseD.id]); + // A fixed component in a chain does not link either. + const fixedB = bodies.map((x) => (x.id === 'b' ? { ...x, fixed: true } : x)); + expect(matesMoving('a', fixedB, all).map((m) => m.id)).toEqual([ab, baseA].map((m) => m.id)); + }); + + it('analyses hundreds of components, most of them free, group by group', () => { + const bodies = [body('base', true)]; + const mates: SolverMate[] = []; + for (let i = 0; i < 400; i++) bodies.push(body(`c${i}`, false, [i * 13, 0, 0])); + // c0 on the base fully, c1 slides on c0; the other 398 are free. + mates.push(mate('coincident', ['base', TOP], ['c0', BOTTOM]), mate('coincident', ['base', RIGHT], ['c0', RIGHT], { aligned: true }), mate('coincident', ['base', FRONT], ['c0', FRONT], { aligned: true })); + mates.push(mate('coincident', ['c0', TOP], ['c1', BOTTOM])); + const r = new MateSolver(bodies, mates).analyze({ scale: 5000 }); + expect(r.dof).toBe(398 * 6 + 3); + expect([...r.defined]).toEqual(['c0']); + }); + + it('analyses an assembly of fifty components', () => { + const bodies = [body('c0', true)]; + const mates: SolverMate[] = []; + for (let i = 1; i < 50; i++) { + bodies.push(body(`c${i}`, false, [i * 13 + 1, i * 3, 2], tilted)); + mates.push(mate('coincident', [`c${i - 1}`, TOP], [`c${i}`, BOTTOM])); + mates.push(mate('coincident', [`c${i - 1}`, RIGHT], [`c${i}`, RIGHT], { aligned: true })); + if (i % 10) mates.push(mate('coincident', [`c${i - 1}`, FRONT], [`c${i}`, FRONT], { aligned: true })); + } + const r = new MateSolver(bodies, mates).analyze({ scale: 500 }); + expect(r.status).toBe('under'); + expect(r.dof).toBe(4); + // Every tenth component slides, and those after it with it. + expect([...r.defined]).toEqual(bodies.slice(1, 10).map((b) => b.id)); + }); +}); diff --git a/src/parametric/tests/assistant-tools.test.ts b/src/parametric/tests/assistant-tools.test.ts index 025b1ab539..cfa786637d 100644 --- a/src/parametric/tests/assistant-tools.test.ts +++ b/src/parametric/tests/assistant-tools.test.ts @@ -5,6 +5,7 @@ import init from 'replicad-opencascadejs'; import { setOc } from '../src/kernel/occ'; import type { SketchFeature } from '../src/model/types'; import { TestHost } from './assistant-host'; +import { newSurfaceFeature } from '../src/model/surfaces'; import { toolSpecs } from '../src/assistant/tools'; import { buildProfiles } from '../src/sketch/profiles'; @@ -194,6 +195,35 @@ describe('assistant tools', () => { expect(m.content).toMatch(/Mass 0\.0975\d* lb/); }); + it('counts and weighs surface bodies apart from the solid', async () => { + const h = new TestHost(); + await h.call('create_sketch', { plane: 'front', shapes: [{ type: 'rectangle', corner1: [0, 0], corner2: [20, 10] }] }); + await h.call('add_extrude', { sketch: 's1', depth: 5 }); + const solid = (await h.call('get_model', {})).content; + const faces = Number(/Body: (\d+) faces/.exec(solid)![1]); + expect(faces).toBe(6); + expect(solid).not.toMatch(/surface bod/); + // A 30 × 40 extruded surface from an open line beside the block, made outside the assistant. + h.store.change('Surface', (d) => { + d.features.push( + { id: 'sk9', name: 'Line', type: 'sketch', plane: { kind: 'base', plane: 'top' }, constraints: [], entities: [ + { id: 'a', t: 'point', x: 50, y: 0 }, { id: 'b', t: 'point', x: 80, y: 0 }, { id: 'l', t: 'line', a: 'a', b: 'b' }] }, + { ...newSurfaceFeature('surfaceExtrude', 'u9', 'Surface-Extrude1', 40), sketch: 'sk9' } as never, + ); + }); + await h.settle(); + const model = (await h.call('get_model', {})).content; + expect(model).toMatch(/Body: 6 faces, 12 edges; 1 surface body apart from the solid \(1 faces, 4 edges\)/); + const m = (await h.call('mass_properties', {})).content; + expect(m).toMatch(/Volume 1000 mm³/); + expect(m).toMatch(/Surface bodies: area 1200 mm², not included in the values above/); + // Surfaces alone: no solid. + h.store.change('Delete', (d) => { d.features = d.features.filter((f) => f.type !== 'extrude'); }); + await h.settle(); + expect((await h.call('mass_properties', {})).content).toMatch(/no solid, only surface bodies \(area 1200 mm²\)/); + expect((await h.call('get_model', {})).content).toMatch(/Body: no solid; 1 surface body/); + }); + it('edits a feature, reads it back and deletes with dependents', async () => { const { h } = await plate(); const f = h.store.doc.features[1].id; diff --git a/src/parametric/tests/document.test.ts b/src/parametric/tests/document.test.ts index f9c0426126..98dc423f43 100644 --- a/src/parametric/tests/document.test.ts +++ b/src/parametric/tests/document.test.ts @@ -3,6 +3,7 @@ import { DocStore, changeFeatureUnits, changeUnits, mapExpressions, newDocument, import { defaultName, dependencies, newChamfer, newExtrude, newHole } from '../src/model/features'; import type { ChamferFeature, ExtrudeFeature, Feature, SkDimension, SketchFeature } from '../src/model/types'; import { EXAMPLES } from '../src/app/examples'; +import { newEdgeFlange } from '../src/model/sheetmetal'; import { rect, sketch } from './helpers'; describe('document store', () => { @@ -214,6 +215,45 @@ describe('document store', () => { for (const ex of EXAMPLES) expect(() => parseDocument(serializeDocument(ex.make()))).not.toThrow(); }); + it('opens face and edge references with a missing or damaged signature, and refuses one that is not an object', () => { + const load = (f: object) => parseDocument(JSON.stringify({ format: 'parametric-part', version: 1, features: [{ id: 'f9', name: 'X', ...f }] })).features[0]; + const edge = { name: 'f1:a|f1:b', sig: { type: 'line', m: [0, 0, 0], len: 10 } }; + const face = { name: 'f1:cap1', sig: { type: 'plane', c: [0, 0, 0], n: [0, 0, 1], area: 10 } }; + const curved = { name: 'f1:side:c1', sig: { type: 'cylinder', c: [0, 0, 0], area: 10 } }; + const features = [ + { type: 'fillet', radius: 1, edges: [edge], faces: [curved] }, + { type: 'revolve', sketch: '', axis: { kind: 'edge', edge } }, + { type: 'plane', ref: { kind: 'face', face }, offset: 1 }, + { ...newEdgeFlange('f9', 'X', 20), edges: [edge] }, + { type: 'surfaceFill', edges: [edge] }, + { type: 'surfaceCut', face, flip: false }, + { type: 'surfaceTrim', faces: [face], tool: { kind: 'surface', face }, keep: [], flip: false }, + { type: 'endCap', faces: [face], thickness: 1, offset: 0, inward: false }, + ]; + const swap = (f: object, bad: unknown) => JSON.parse(JSON.stringify(f).replaceAll(JSON.stringify(edge), JSON.stringify(bad)).replaceAll(JSON.stringify(face), JSON.stringify(bad)).replaceAll(JSON.stringify(curved), JSON.stringify(bad))); + // Whole references open unchanged (a curved face has no normal). + for (const f of features) expect(load(f), f.type).toEqual({ id: 'f9', name: 'X', ...f }); + // A missing or partly damaged signature is filled with neutral values: no type, no position. + for (const f of features) { + for (const bad of [{ name: 'f1:x' }, { name: 'f1:x', sig: null }, { name: 'f1:x', sig: { type: 'line' } }, { name: 'f1:x', sig: { type: 7, c: [0, 0], m: 'x', area: null, n: [1] } }]) { + const text = JSON.stringify(load(swap(f, bad))); + expect(text, `${f.type} ${JSON.stringify(bad)}`).not.toContain('"sig":null'); + for (const m of text.matchAll(/"sig":(\{[^}]*\})/g)) { + const sig = JSON.parse(m[1]); + expect(typeof sig.type).toBe('string'); + const isEdge = Number.isFinite(sig.len); + expect(isEdge ? sig.m : sig.c).toEqual([0, 0, 0]); + if (!isEdge) expect(sig.area).toBe(0); + if (!isEdge) expect(sig.n).toBeUndefined(); + } + } + // Not an object at all: the file is damaged. + for (const bad of [{ name: 'f1:x', sig: 'line' }, { name: 'f1:x', sig: [1, 2] }, 'f1:x', { sig: {} }]) { + expect(() => load(swap(f, bad)), `${f.type} ${JSON.stringify(bad)}`).toThrow(/damaged/); + } + } + }); + it('repairs creation and modification times a date cannot hold', () => { const raw = { format: 'parametric-part', version: 1, features: [] }; for (const t of ['2026', null, 1e300]) { diff --git a/src/parametric/tests/drawing-kernel.test.ts b/src/parametric/tests/drawing-kernel.test.ts new file mode 100644 index 0000000000..343f9c6b88 --- /dev/null +++ b/src/parametric/tests/drawing-kernel.test.ts @@ -0,0 +1,184 @@ +// Drawing views on real parts, projected by the OpenCascade kernel in Node: section views +// (the cut face hatched, holes left open), and dimensions measured from model edges. +import { beforeAll, describe, expect, it } from 'vitest'; +import init from 'replicad-opencascadejs'; +import { ModelBuilder } from '../src/kernel/build'; +import { setOc } from '../src/kernel/occ'; +import type { ProjectionResult } from '../src/kernel/protocol'; +import type { DrawingDoc, Feature } from '../src/model/types'; +import { holeCount, holeInstance } from '../src/drawing/annotate'; +import { buildSheet, toSvg } from '../src/drawing/sheet'; +import { hatch, projectionRequest, resolveViews } from '../src/drawing/views'; +import { circle, extrude, rect, req, sketch } from './helpers'; + +beforeAll(async () => { + setOc(await init()); +}); + +/** Projects every view of a drawing the way the drawing workspace does. */ +function projectAll(b: ModelBuilder, d: DrawingDoc): Map { + const rs = resolveViews(d); + const out = new Map(); + for (const v of d.views) { + const r = rs.get(v.id); + if (!r) continue; + const [res] = b.project([projectionRequest(r, v.hidden)]); + out.set(v.id, res); + } + return out; +} + +const info = (edges: ReturnType extends Promise ? R : never) => ({ + partName: 'Plate', material: 'Steel', units: 'mm', date: '2026-01-01', formatLength: (v: number) => v.toFixed(2), + edges: () => (edges as { edges: import('../src/kernel/protocol').EdgeInfo[] }).edges, +}); + +describe('section views', () => { + // A 40 x 20 plate, 6 thick, with a 10 mm hole in the middle (front plane: x right, y up, z toward the front). + const plate = () => req([sketch('S1', [...rect(-20, -10, 20, 10), ...circle(0, 0, 5)]), extrude('E1', 'S1', 6)]); + + it('cuts a holed plate through the hole: the cut face is hatched with the hole left as a gap', async () => { + const b = new ModelBuilder(); + const res = await b.build(plate()); + const d: DrawingDoc = { + sheet: 'A4', landscape: true, scale: 2, title: '', drawnBy: '', notes: '', annotations: [], + views: [ + { id: 'v1', kind: 'front', x: 100, y: 120, hidden: false, dims: false }, + // A horizontal cutting line through the hole's centre, the section placed above it (third angle: seen from above). + { id: 'v2', kind: 'front', type: 'section', parent: 'v1', line: [30, 0, -30, 0], label: 'A', x: 100, y: 50, hidden: false, dims: false }, + ], + }; + const r = resolveViews(d).get('v2')!; + // Placed above, it looks down like a top view and keeps the half below the line. + expect(r.o.dir).toEqual([0, 1, 0]); + expect(r.align).toBe('x'); + expect(r.section!.n).toEqual([0, -1, 0]); + const proj = projectAll(b, d); + const sec = proj.get('v2')!; + // Cut faces: two 15 x 6 rectangles either side of the hole, in the view's coordinates (x along X, y down along -Z... the depth). + expect(sec.cut!.length).toBeGreaterThanOrEqual(8); + const xs = sec.cut!.flatMap((pl) => pl.filter((_, i) => i % 2 === 0)); + expect(Math.min(...xs)).toBeCloseTo(-20, 6); + expect(Math.max(...xs)).toBeCloseTo(20, 6); + // No outline crosses the hole. + for (const pl of sec.cut!) for (let i = 0; i + 3 < pl.length; i += 2) { + const [x1, x2] = [pl[i], pl[i + 2]]; + expect(Math.min(x1, x2) >= 5 - 1e-6 || Math.max(x1, x2) <= -5 + 1e-6).toBe(true); + } + // Hatched area: lines at 45 degrees across the two rectangles; none inside the hole. + const lines = hatch(sec.cut!, 45, 1); + expect(lines.length).toBeGreaterThan(10); + for (const [x1, y1, x2, y2] of lines) { + const mx = (x1 + x2) / 2; + expect(Math.abs(mx) >= 5 - 1e-6, `hatch at ${mx},${(y1 + y2) / 2}`).toBe(true); + } + // The hatch covers 2 x 15 x 6 = 180 mm2: total hatch length x spacing. + const total = lines.reduce((s, [x1, y1, x2, y2]) => s + Math.hypot(x2 - x1, y2 - y1), 0); + expect(total * 1).toBeCloseTo(180, -1); + // The sheet: the section's label, the cutting line's letters, and the hatch drawn in the view's group. + const sheet = buildSheet(d, proj, info(res)); + const svg = toSvg(sheet.items, sheet.w, sheet.h); + expect(svg).toContain('>SECTION A-A<'); + expect((svg.match(/>A { + const b = new ModelBuilder(); + await b.build(plate()); + const d: DrawingDoc = { + sheet: 'A4', landscape: true, scale: 2, title: '', drawnBy: '', notes: '', + views: [ + { id: 'v1', kind: 'front', x: 100, y: 120, hidden: false, dims: false }, + // Vertical line through the hole, drawn bottom to top: its left normal points right. + { id: 'v2', kind: 'front', type: 'section', parent: 'v1', line: [0, 15, 0, -15], label: 'B', x: 200, y: 120, hidden: false, dims: false }, + ], + }; + const r = resolveViews(d).get('v2')!; + expect(r.o.dir).toEqual([1, 0, 0]); + expect(r.align).toBe('y'); + const sec = projectAll(b, d).get('v2')!; + const ys = sec.cut!.flatMap((pl) => pl.filter((_, i) => i % 2 === 1)); + expect(Math.min(...ys)).toBeCloseTo(-10, 6); + expect(Math.max(...ys)).toBeCloseTo(10, 6); + const lines = hatch(sec.cut!, 45, 0.5); + for (const [, y1, , y2] of lines) expect(Math.abs((y1 + y2) / 2) >= 5 - 1e-6).toBe(true); + // First angle: the same placement looks from the other side. + const first = resolveViews({ ...d, projection: 'first' }).get('v2')!; + expect(first.o.dir).toEqual([-1, 0, 0]); + expect(first.section!.n).toEqual([1, 0, 0]); + }); + + it('a section that misses the part is empty, not an error', async () => { + const b = new ModelBuilder(); + await b.build(plate()); + const [res] = b.project([{ id: 's', dir: [0, 1, 0], x: [1, 0, 0], section: { p: [0, 50, 0], n: [0, 1, 0] } }]); + expect(res.bounds).toBeNull(); + expect(res.cut).toEqual([]); + }); +}); + +describe('model dimensions on a drawing', () => { + it('measures the plate and its hole from named model edges, and follows a model change', async () => { + const b = new ModelBuilder(); + const res = await b.build(req([sketch('S1', [...rect(-20, -10, 20, 10, 'r'), ...circle(0, 0, 5, 'c')]), extrude('E1', 'S1', 6)])); + const top = res.edges.find((e) => e.type === 'line' && Math.abs(e.a[1] - 10) < 1e-6 && Math.abs(e.b[1] - 10) < 1e-6 && Math.abs(e.a[2] - 6) < 1e-6)!; + const hole = res.edges.find((e) => e.type === 'circle' && Math.abs(e.center![2] - 6) < 1e-6)!; + const d: DrawingDoc = { + sheet: 'A4', landscape: true, scale: 1, title: '', drawnBy: '', notes: '', + views: [{ id: 'v1', kind: 'front', x: 100, y: 100, hidden: false, dims: false }], + annotations: [ + { id: 'a1', type: 'dimension', view: 'v1', kind: 'horizontal', refs: [{ edge: top.name, at: 'edge' }], at: [0, -20] }, + { id: 'a2', type: 'dimension', view: 'v1', kind: 'diameter', refs: [{ edge: hole.name, at: 'edge' }], at: [12, 12] }, + ], + }; + const sheet = buildSheet(d, projectAll(b, d), info(res)); + const svg = toSvg(sheet.items, sheet.w, sheet.h); + expect(svg).toContain('>40.00<'); + expect(svg).toContain('>Ø10.00<'); + // A wider plate and a larger hole: same edges by name, new values. + const res2 = await b.build(req([sketch('S1', [...rect(-30, -10, 30, 10, 'r'), ...circle(0, 0, 7, 'c')]), extrude('E1', 'S1', 6)])); + expect(res2.edges.some((e) => e.name === top.name)).toBe(true); + const svg2 = toSvg(buildSheet(d, projectAll(b, d), info(res2)).items, 297, 210); + expect(svg2).toContain('>60.00<'); + expect(svg2).toContain('>Ø14.00<'); + // An edge that is gone leaves the dimension marked as missing. + const gone: DrawingDoc = { ...d, annotations: [{ ...d.annotations![0], refs: [{ edge: 'no such edge', at: 'edge' }] } as never] }; + const svg3 = toSvg(buildSheet(gone, projectAll(b, gone), info(res2)).items, 297, 210); + expect(svg3).toContain('? (missing)'); + expect(svg3).toContain('fill="#d32f2f"'); + }); +}); + +describe('hole callouts', () => { + it('count the holes of a hole feature patterned and mirrored, from the faces that trace back to it', async () => { + const b = new ModelBuilder(); + const base: Feature[] = [sketch('S1', rect(-40, -20, 40, 20)), extrude('E1', 'S1', 5)]; + const r0 = await b.build(req(base)); + const top = r0.faces.find((f) => f.name === 'E1:cap1')!; + // Two hole centres, and a construction line locating them (its end points are not holes). + const pos = sketch('S2', [ + { id: 'hp', t: 'point', x: -30, y: 10 }, { id: 'hq', t: 'point', x: -30, y: -10 }, + { id: 'c1', t: 'point', x: -35, y: 15 }, { id: 'c2', t: 'point', x: -35, y: -15 }, { id: 'cl', t: 'line', a: 'c1', b: 'c2', construction: true }, + ], { kind: 'face', face: { name: top.name, sig: { type: 'plane', c: top.center, n: top.normal, area: top.area } } }); + const hole = { id: 'H', name: 'H', type: 'hole', sketch: 'S2', kind: 'counterbore', diameter: 4, end: 'throughAll', depth: 0, cbDiameter: 8, cbDepth: 1, csDiameter: 8, csAngle: 90, flip: false } as Feature; + const names = async (fs: Feature[]) => (await b.build(req([...base, pos, hole, ...fs]))).faces.map((f) => f.name); + expect(holeCount(await names([]), 'H')).toBe(2); + // Four along x (x = -30, -20, -10, 0): eight holes. + const pat = { id: 'P', name: 'P', type: 'linearPattern', seeds: ['H'], dir1: { ref: { kind: 'base', axis: 'x' }, spacing: 10, count: 4, flip: false }, dir2: null } as Feature; + const withPattern = await names([pat]); + expect(holeCount(withPattern, 'H')).toBe(8); + // The copies' faces name the hole feature, so the callout keeps its sizes. + const copy = withPattern.find((n) => n.includes('@P.'))!; + expect(holeInstance(copy)?.feature).toBe('H'); + // Mirrored about the right plane: the copies at -20 and -10 land at 20 and 10 (the one at 0 onto itself). + const mir = { id: 'M', name: 'M', type: 'mirror', seeds: ['P'], plane: { kind: 'base', plane: 'right' } } as Feature; + expect(holeCount(await names([pat, mir]), 'H')).toBe(12); + }); +}); diff --git a/src/parametric/tests/drawing-sources-kernel.test.ts b/src/parametric/tests/drawing-sources-kernel.test.ts new file mode 100644 index 0000000000..de5a4d3238 --- /dev/null +++ b/src/parametric/tests/drawing-sources-kernel.test.ts @@ -0,0 +1,166 @@ +// Drawing views of assemblies and sheet metal flat patterns on the real OpenCascade kernel: +// projections of placed components (collapsed or exploded, sectioned per component) and the +// flat pattern view's outline, bend lines and edges. +import { beforeAll, describe, expect, it } from 'vitest'; +import init from 'replicad-opencascadejs'; +import { AssemblyBuilder, type AsmSceneItem } from '../src/kernel/assembly'; +import { ModelBuilder } from '../src/kernel/build'; +import { setOc } from '../src/kernel/occ'; +import type { ProjectionResult } from '../src/kernel/protocol'; +import { placementMatrix } from '../src/assembly/compose'; +import { flatEdges, flatProjection } from '../src/drawing/flat'; +import { buildSheet, toSvg } from '../src/drawing/sheet'; +import { projectionRequest, resolveViews, viewPrims } from '../src/drawing/views'; +import { flatSize } from '../src/model/flat-pattern'; +import type { Placement } from '../src/model/assembly'; +import { newBaseFlange } from '../src/model/sheetmetal'; +import type { DrawingDoc, SkEntity } from '../src/model/types'; +import { circle, extrude, rect, req, sketch } from './helpers'; + +beforeAll(async () => { + setOc(await init()); +}, 60000); + +const item = (part: string, pl: Placement, name: string): AsmSceneItem => ({ part, m: placementMatrix(pl), name, color: '#888888' }); +const at = (p: [number, number, number]): Placement => ({ p, q: [0, 0, 0, 1] }); +const width = (r: ProjectionResult) => r.bounds![2] - r.bounds![0]; +const height = (r: ProjectionResult) => r.bounds![3] - r.bounds![1]; + +describe('assembly drawing projections', () => { + async function built() { + const a = new AssemblyBuilder(); + await a.build([ + // A 40 × 20 × 10 block with a Ø8 hole at (10, 10), and a Ø8 pin 30 long. + { key: 'block', features: [sketch('S1', [...rect(0, 0, 40, 20), ...circle(10, 10, 4)]), extrude('E1', 'S1', 10)], blobs: {}, quality: 0 }, + { key: 'pin', features: [sketch('S1', circle(0, 0, 4)), extrude('E1', 'S1', 30)], blobs: {}, quality: 0 }, + ]); + return a; + } + const right = { id: 'r', dir: [1, 0, 0] as [number, number, number], x: [0, 0, -1] as [number, number, number] }; + + it('projects the components where the items place them, leaving the scene alone', async () => { + const a = await built(); + a.setScene([item('block', at([0, 0, 0]), 'block<1>')]); + // Collapsed: the pin in the hole, its end flush with the block's front (z 10), 20 out the back. + const collapsed = a.projectItems([item('block', at([0, 0, 0]), 'block<1>'), item('pin', at([10, 10, -20]), 'pin<1>')], [right]); + expect(width(collapsed[0])).toBeCloseTo(30, 4); + expect(height(collapsed[0])).toBeCloseTo(20, 4); + // Exploded: the pin moved 60 along z. + const exploded = a.projectItems([item('block', at([0, 0, 0]), 'block<1>'), item('pin', at([10, 10, 40]), 'pin<1>')], [right]); + expect(width(exploded[0])).toBeCloseTo(70, 4); + // The scene (what measure and export use) is unchanged. + expect(a.sceneSize).toBe(1); + expect(width(a.project([right])[0])).toBeCloseTo(10, 4); + }); + + it('cuts each component of a section on its own, and says which component each cut outline belongs to', async () => { + const a = await built(); + const items = [item('block', at([0, 0, 0]), 'block<1>'), item('pin', at([10, 10, -20]), 'pin<1>')]; + // Horizontal plane through the hole's axis (y = 10), looking up from below. + const [sec] = a.projectItems(items, [{ id: 's', dir: [0, -1, 0], x: [1, 0, 0], section: { p: [0, 10, 0], n: [0, 1, 0] } }]); + expect(sec.cut!.length).toBeGreaterThanOrEqual(3); + expect(sec.cutGroups).toHaveLength(sec.cut!.length); + expect(new Set(sec.cutGroups)).toEqual(new Set([0, 1])); + // The pin, cut too, runs 20 past the block: 30 deep in all, 40 wide. + expect(width(sec)).toBeCloseTo(40, 4); + expect(height(sec)).toBeCloseTo(30, 4); + // The pin's cut face is an 8 × 30 rectangle. + const pinCut = sec.cut!.filter((_, i) => sec.cutGroups![i] === 1).flat(); + const xs = pinCut.filter((_, i) => i % 2 === 0), ys = pinCut.filter((_, i) => i % 2 === 1); + expect(Math.max(...xs) - Math.min(...xs)).toBeCloseTo(8, 4); + expect(Math.max(...ys) - Math.min(...ys)).toBeCloseTo(30, 4); + // Every component's cut is hatched, at its own angle. + const d: DrawingDoc = { + sheet: 'A4', landscape: true, scale: 2, title: '', drawnBy: '', notes: '', + views: [{ id: 'v1', kind: 'front', x: 80, y: 60, hidden: true, dims: false, source: 'assembly' }, + { id: 'v2', kind: 'front', type: 'section', parent: 'v1', line: [-5, -10, 45, -10], label: 'A', x: 80, y: 150, hidden: false, dims: false }], + }; + const r = resolveViews(d); + const proj = new Map(); + for (const v of d.views) proj.set(v.id, a.projectItems(items, [projectionRequest(r.get(v.id)!, v.hidden)])[0]); + const s = buildSheet(d, proj, { partName: 'A', material: '', units: 'mm', date: '', formatLength: (v) => v.toFixed(1) }); + const hatches = s.items.filter((it) => it.t === 'path' && it.view === 'v2' && it.w < 0.3 && /^M[^A-Z]*L[^A-Z]*M/.test(it.d)); + expect(hatches.length).toBe(2); + }); +}); + +describe('flat pattern views', () => { + const T = 2; + const chain = (pts: [number, number][]): SkEntity[] => [ + ...pts.map(([x, y], i) => ({ id: `p${i}`, t: 'point' as const, x, y })), + ...pts.slice(1).map((_, i) => ({ id: `l${i}`, t: 'line' as const, a: `p${i}`, b: `p${i + 1}` })), + ]; + + it('draws the flat outline at its size, with a bend line, and edges for dimensions', async () => { + const b = new ModelBuilder(); + const f = newBaseFlange('B1', 'B1', 'S1', T, 40); + const res = await b.build(req([sketch('S1', [...chain([[0, 0], [50, 0], [50, 30]])]), f])); + expect(res.status.every((s) => s.ok)).toBe(true); + const fp = b.flatPattern().pattern!; + const [fw, fh] = flatSize(fp); + const pr = flatProjection('k', fp); + expect(pr.bounds![2] - pr.bounds![0]).toBeCloseTo(fw, 4); + expect(pr.bounds![3] - pr.bounds![1]).toBeCloseTo(fh, 4); + // One of the flat sizes is the flange's depth; the other the two legs unbent. + expect([fw, fh].some((v) => Math.abs(v - 40) < 1e-6)).toBe(true); + expect(Math.max(fw, fh)).toBeGreaterThan(70); + expect(Math.max(fw, fh)).toBeLessThan(80); + expect(pr.bends).toHaveLength(1); + expect(pr.bends![0].angle).toBeCloseTo(90, 6); + // The bend line crosses the flat pattern from side to side. + const bl = pr.bends![0]; + expect(Math.hypot(bl.b[0] - bl.a[0], bl.b[1] - bl.a[1])).toBeCloseTo(40, 4); + // Its edges, seen by a flat view, are where its lines are. + const edges = flatEdges(fp); + expect(edges.length).toBe(fp.loops.reduce((n, l) => n + l.segs.length, 0)); + const d: DrawingDoc = { sheet: 'A4', landscape: true, scale: 1, title: '', drawnBy: '', notes: '', views: [{ id: 'v1', kind: 'front', type: 'flat', x: 150, y: 100, hidden: false, dims: true }] }; + const r = resolveViews(d).get('v1')!; + expect(r.source).toBe('flat'); + const prims = viewPrims(r, edges); + expect(prims.filter((p) => p.kind === 'line')).toHaveLength(4); + const xs = prims.flatMap((p) => [p.a[0], p.b[0]]), ys = prims.flatMap((p) => [p.a[1], p.b[1]]); + expect(Math.min(...xs)).toBeCloseTo(pr.bounds![0], 6); + expect(Math.max(...ys)).toBeCloseTo(pr.bounds![3], 6); + // On the sheet: the outline, the dashed bend line with its note, the overall size and the caption. + const s = buildSheet(d, new Map([['v1', pr]]), { partName: 'P', material: '', units: 'mm', date: '', formatLength: (v) => v.toFixed(2), edges: () => edges }); + const svg = toSvg(s.items, s.w, s.h); + expect(svg).toContain('>FLAT PATTERN<'); + expect(svg).toMatch(/>UP 90° R 2\.00<|>DOWN 90° R 2\.00${fw.toFixed(2)}<`); + expect(svg).toContain(`>${fh.toFixed(2)}<`); + expect(s.items.filter((it) => it.t === 'line' && it.dash?.length === 2)).toHaveLength(1); + // A detail of it shows the bend line too, cut off at its circle. + const cx = (bl.a[0] + bl.b[0]) / 2, cy = (bl.a[1] + bl.b[1]) / 2; + const dd: DrawingDoc = { ...d, views: [...d.views, { id: 'v2', kind: 'front', type: 'detail', parent: 'v1', circle: [cx, cy, 5], x: 60, y: 60, hidden: false, dims: false }] }; + const s2 = buildSheet(dd, new Map([['v1', pr], ['v2', pr]]), { partName: 'P', material: '', units: 'mm', date: '', formatLength: (v) => v.toFixed(2), edges: () => edges }); + const bendLines = s2.items.filter((it): it is Extract => it.t === 'line' && it.dash?.length === 2); + expect(bendLines).toHaveLength(2); + expect(Math.hypot(bendLines[1].x2 - bendLines[1].x1, bendLines[1].y2 - bendLines[1].y1)).toBeCloseTo(2 * 5 * 2, 4); + }); + + it('says on the sheet what the flat pattern leaves out', async () => { + const b = new ModelBuilder(); + // An L of sheet with a block added off the sheet: the flat pattern cannot show the block. + const res = await b.build(req([sketch('S1', chain([[0, 0], [50, 0], [50, 30]])), newBaseFlange('B1', 'B1', 'S1', T, 40), sketch('S2', rect(10, 10, 20, 20), { kind: 'base', plane: 'top' }), extrude('E2', 'S2', 5)])); + expect(res.status.every((s) => s.ok)).toBe(true); + const fp = b.flatPattern().pattern!; + expect(fp.notes.length).toBeGreaterThan(0); + const pr = flatProjection('k', fp); + const d: DrawingDoc = { sheet: 'A4', landscape: true, scale: 1, title: '', drawnBy: '', notes: '', views: [{ id: 'v1', kind: 'front', type: 'flat', x: 150, y: 100, hidden: false, dims: true }] }; + const s = buildSheet(d, new Map([['v1', pr]]), { partName: 'P', material: '', units: 'mm', date: '', formatLength: (v) => v.toFixed(2), edges: () => flatEdges(fp) }); + const texts = s.items.filter((it): it is Extract => it.t === 'text').map((it) => it.s).join('\n'); + expect(texts).toContain('Material the flat pattern cannot show is left out'); + // A part whose flat pattern shows everything has no such note. + const plain = flatProjection('k', { ...fp, notes: [] }); + const s2 = buildSheet(d, new Map([['v1', plain]]), { partName: 'P', material: '', units: 'mm', date: '', formatLength: (v) => v.toFixed(2), edges: () => flatEdges(fp) }); + expect(s2.items.some((it) => it.t === 'text' && it.s.includes('left out'))).toBe(false); + }); + + it('says why when the part cannot be flattened', () => { + const pr = flatProjection('k', null, 'Not a sheet metal part'); + expect(pr.bounds).toBeNull(); + const d: DrawingDoc = { sheet: 'A4', landscape: true, scale: 1, title: '', drawnBy: '', notes: '', views: [{ id: 'v1', kind: 'front', type: 'flat', x: 150, y: 100, hidden: false, dims: true }] }; + const svg = toSvg(buildSheet(d, new Map([['v1', pr]]), { partName: 'P', material: '', units: 'mm', date: '', formatLength: (v) => v.toFixed(2) }).items, 297, 210); + expect(svg).toContain('FLAT PATTERN: Not a sheet metal part'); + }); +}); diff --git a/src/parametric/tests/drawing-tables.test.ts b/src/parametric/tests/drawing-tables.test.ts new file mode 100644 index 0000000000..bb87e0a06b --- /dev/null +++ b/src/parametric/tests/drawing-tables.test.ts @@ -0,0 +1,303 @@ +// Bill of materials and cut list tables, balloons and their numbering, automatic balloon +// placement, and the drawing data they add (validated on open). +import { describe, expect, it } from 'vitest'; +import { buildSheet, standardLayout, toSvg } from '../src/drawing/sheet'; +import type { BomRow } from '../src/drawing/source'; +import { + BALLOON_R, TABLE_ROW_H, autoBalloons, balloonTip, bomTable, cutListTable, drawBalloon, drawTable, fitCell, splitTable, itemOfEdge, layoutTable, tableOrigin, tableSize, +} from '../src/drawing/tables'; +import { textWidth } from '../src/drawing/pdf'; +import { toDxf } from '../src/drawing/dxf'; +import type { Prim } from '../src/drawing/views'; +import { newAssembly, validateAssembly } from '../src/model/assembly'; +import { validDrawing } from '../src/model/validate-drawing'; +import { cutListRows, weldmentCutList, type WeldMemberInfo } from '../src/model/weldments'; +import type { DrawingDoc } from '../src/model/types'; +import type { Item } from '../src/drawing/sheet'; +import { SHEETS } from '../src/drawing/sheet'; +import { toolSpecs } from '../src/assistant/tools'; + +const rows: BomRow[] = [ + { item: 1, name: 'Base plate', material: 'Steel', qty: 1, prefixes: ['c1#'] }, + { item: 2, name: 'Pin', material: '', qty: 3, prefixes: ['c2#', 'c3#', 'c4#'] }, +]; + +describe('tables', () => { + it('lays out a bill of materials with fixed column widths, the header first', () => { + const t = bomTable(rows); + expect(t.header).toEqual(['ITEM NO.', 'PART NUMBER', 'MATERIAL', 'QTY.']); + expect(t.rows).toEqual([['1', 'Base plate', 'Steel', '1'], ['2', 'Pin', '', '3']]); + const { w, h } = tableSize(t); + expect(w).toBe(126); + expect(h).toBe(3 * TABLE_ROW_H); + // The same width whatever the rows hold (a table on the title block keeps its place). + expect(tableSize(bomTable([{ ...rows[0], name: 'A much longer part number than the column holds' }])).w).toBe(126); + const L = layoutTable(t, [100, 50]); + expect(L.box).toEqual([100, 50, 226, 50 + 3 * TABLE_ROW_H]); + expect(L.cols).toEqual([100, 116, 168, 212, 226]); + expect(L.rows).toEqual([50, 56, 62, 68]); + const cell = (s: string) => L.texts.find((x) => x.s === s)!; + // Header centred and bold; item numbers and quantities centred, names from the left. + expect(cell('PART NUMBER')).toMatchObject({ x: 142, anchor: 'middle', bold: true }); + expect(cell('Base plate')).toMatchObject({ anchor: 'start', bold: false }); + expect(cell('Base plate').x).toBeCloseTo(117.2, 6); + expect(cell('Base plate').y).toBeGreaterThan(56); + expect(cell('Base plate').y).toBeLessThan(62); + expect(cell('3')).toMatchObject({ x: 219, anchor: 'middle' }); + }); + + it('places a table on the title block by its bottom right corner, growing upward', () => { + const t = bomTable(rows); + expect(tableOrigin(t, [400, 255], 'bottomRight')).toEqual([400 - 126, 255 - 18]); + expect(layoutTable(t, [400, 255], 'bottomRight').box).toEqual([274, 237, 400, 255]); + expect(tableOrigin(t, [10, 10])).toEqual([10, 10]); + }); + + it('shrinks long values to fit their cell, then cuts them short', () => { + expect(fitCell('Pin', 40, 2.5)).toEqual({ s: 'Pin', size: 2.5 }); + const f = fitCell('A rather long name', 20, 2.5); + expect(f.size).toBeLessThan(2.5); + expect(textWidth(f.s, f.size)).toBeLessThanOrEqual(20 + 1e-9); + const g = fitCell('An extremely long part name that cannot fit in the cell at all', 20, 2.5); + expect(g.s.endsWith('…')).toBe(true); + expect(textWidth(g.s, g.size)).toBeLessThanOrEqual(20 + 1e-9); + }); + + it('writes a value cut short with an ellipsis that DXF can show', () => { + const items: Item[] = []; + drawTable(items, bomTable([{ item: 1, name: 'A very long part number that cannot fit in its cell at all, not even in the smallest legible text', material: 'Steel', qty: 1, prefixes: [] }]), [10, 10]); + const text = toDxf(items, 297, 210); + expect(text).toMatch(/\nA very long part.*\.\.\.\n/); + expect(text).not.toMatch(/\nA very long part.*\?\n/); + }); + + it('makes the cut list table from the cut list rows', () => { + const m = (feature: string, member: string, length: number, a1: number, a2: number): WeldMemberInfo => ({ + feature, member, group: 0, standard: 'iso', profile: 'squareTube', size: '40x40x3', desc: 'SQ TUBE 40 x 40 x 3', length, angle1: a1, angle2: a2, volume: length * 444, area: 444, + }); + const list = weldmentCutList({ material: null }, [m('M1', 's/a', 440, 45, 45), m('M1', 's/b', 240, 45, 45), m('M1', 's/c', 440, 45, 45), m('M1', 's/d', 240, 45, 45)]); + const r = cutListRows(list, 'MMGS', 1); + const t = cutListTable(r.rows, 'mm'); + expect(t.header).toEqual(['ITEM NO.', 'QTY.', 'DESCRIPTION', 'LENGTH (mm)', 'ANGLE1', 'ANGLE2']); + expect(t.rows).toEqual([['1', '2', 'SQ TUBE 40 x 40 x 3', '440.0', '45.00°', '45.00°'], ['2', '2', 'SQ TUBE 40 x 40 x 3', '240.0', '45.00°', '45.00°']]); + expect(t.widths).toHaveLength(6); + expect(tableSize(t).w).toBeLessThanOrEqual(170); + }); + + it('draws the table, a value missing from the source as a note, and both are boxes to pick', () => { + const d: DrawingDoc = { + sheet: 'A3', landscape: true, scale: 1, title: '', drawnBy: '', notes: '', views: [], + annotations: [{ id: 'a1', type: 'bom', at: [410, 255], anchor: 'bottomRight' }, { id: 'a2', type: 'cutList', at: [20, 20] }], + }; + const s = buildSheet(d, new Map(), { partName: 'A', material: '', units: 'mm', date: '', formatLength: (v) => v.toFixed(1), table: (a) => (a.type === 'bom' ? bomTable(rows) : null) }); + const svg = toSvg(s.items, s.w, s.h); + expect(svg).toContain('>PART NUMBER<'); + expect(svg).toContain('>Base plate<'); + expect(svg).toContain('CUT LIST? (no structural members)'); + expect(s.annos.find((a) => a.id === 'a1')!.box).toEqual([284, 237, 410, 255]); + expect(s.annos.find((a) => a.id === 'a2')).toBeTruthy(); + expect(s.warnings).toEqual([]); + }); + + it('continues a table too tall for the sheet in columns to its left, each with the header, all on the sheet', () => { + const many: BomRow[] = Array.from({ length: 60 }, (_, i) => ({ item: i + 1, name: `Part ${i + 1}`, material: '', qty: 1, prefixes: [`c${i}#`] })); + const d: DrawingDoc = { sheet: 'A3', landscape: true, scale: 1, title: '', drawnBy: '', notes: '', views: [], annotations: [{ id: 'a1', type: 'bom', at: [410, 255], anchor: 'bottomRight' }] }; + const s = buildSheet(d, new Map(), { partName: 'A', material: '', units: 'mm', date: '', formatLength: (v) => v.toFixed(1), table: () => bomTable(many) }); + const texts = s.items.filter((it): it is Extract => it.t === 'text'); + // Every row once, the header in each column, everything inside the border. + for (let i = 1; i <= 60; i++) expect(texts.filter((x) => x.s === `Part ${i}`)).toHaveLength(1); + expect(texts.filter((x) => x.s === 'PART NUMBER')).toHaveLength(2); + for (const x of texts) expect(x.y).toBeGreaterThan(10); + const box = s.annos.find((a) => a.id === 'a1')!.box; + expect(box[1]).toBeGreaterThanOrEqual(10); + expect(box[0]).toBeGreaterThanOrEqual(10); + expect(box[2]).toBe(410); + expect(box[3]).toBe(255); + // Item 1 is in the first column (on the right), the last item in the one left of it, both standing on the title block. + const first = texts.find((x) => x.s === 'Part 1')!, last = texts.find((x) => x.s === 'Part 60')!; + expect(last.x).toBeLessThan(first.x - tableSize(bomTable(many)).w); + expect(s.warnings).toEqual([]); + const parts = splitTable(bomTable(many), [410, 255], 'bottomRight', { top: 10, bottom: 287, left: 10, right: 410 }); + expect(parts.parts.length).toBe(2); + expect(parts.parts[0].t.rows[0][1]).toBe('Part 1'); + expect(parts.parts.every((p) => tableSize(p.t).h <= 245)).toBe(true); + expect(parts.fits).toBe(true); + }); + + it('says in red, and as a warning, when a table does not fit on the sheet even split', () => { + const many: BomRow[] = Array.from({ length: 400 }, (_, i) => ({ item: i + 1, name: `Part ${i + 1}`, material: '', qty: 1, prefixes: [] })); + const d: DrawingDoc = { sheet: 'A4', landscape: true, scale: 1, title: '', drawnBy: '', notes: '', views: [], annotations: [{ id: 'a1', type: 'bom', at: [287, 168], anchor: 'bottomRight' }] }; + const s = buildSheet(d, new Map(), { partName: 'A', material: '', units: 'mm', date: '', formatLength: (v) => v.toFixed(1), table: () => bomTable(many) }); + expect(s.warnings).toEqual(['The bill of materials does not fit on this sheet: use a larger sheet.']); + const note = s.items.find((it): it is Extract => it.t === 'text' && it.s.includes('DOES NOT FIT'))!; + expect(note.color).toBeTruthy(); + expect(note.x).toBeGreaterThanOrEqual(10); + expect(note.x + textWidth(note.s, note.size)).toBeLessThanOrEqual(287 + 1e-9); + expect(note.y).toBeGreaterThan(10); + }); +}); + +describe('balloons', () => { + it('numbers a balloon from the bill of materials row of the component its edge belongs to', () => { + expect(itemOfEdge('c1#E1:cap0|E1:side:1', rows)).toBe(1); + expect(itemOfEdge('c3#E1:cap1', rows)).toBe(2); + expect(itemOfEdge('c9#E1:cap1', rows)).toBeNull(); + // A component id that starts like another's is not taken for it. + expect(itemOfEdge('c11#E1:cap1', rows)).toBeNull(); + }); + + it('ends its leader on the middle of a line, on a circle toward the balloon, or on an arc’s middle', () => { + expect(balloonTip({ kind: 'line', a: [0, 0], b: [10, 0] }, [50, 50])).toEqual([5, 0]); + const tip = balloonTip({ kind: 'circle', c: [0, 0], r: 5, full: true, a: [5, 0], b: [5, 0], m: [-5, 0] }, [0, 20]); + expect(tip[0]).toBeCloseTo(0, 9); + expect(tip[1]).toBeCloseTo(5, 9); + expect(balloonTip({ kind: 'circle', c: [0, 0], r: 5, full: false, a: [5, 0], b: [-5, 0], m: [0, -5] }, [0, 20])).toEqual([0, -5]); + }); + + it('ends a leader attached to a line where it was attached', () => { + expect(balloonTip({ kind: 'line', a: [0, 0], b: [10, 0] }, [50, 50], 0.8)).toEqual([8, 0]); + expect(balloonTip({ kind: 'line', a: [0, 0], b: [10, 4] }, [50, 50], 0)).toEqual([0, 0]); + // On the sheet: the view's 20 long edge runs from x 90 to 110. + const d: DrawingDoc = { + sheet: 'A4', landscape: true, scale: 1, title: '', drawnBy: '', notes: '', + views: [{ id: 'v1', kind: 'front', x: 100, y: 100, hidden: false, dims: false, source: 'assembly' }], + annotations: [{ id: 'a1', type: 'balloon', view: 'v1', ref: { edge: 'c2#e1', at: 'edge' }, at: [30, -30], t: 0.8 }], + }; + const pr = { id: 'k', visible: ['M0 0L20 0'], hidden: [], bounds: [0, -10, 20, 0] as [number, number, number, number] }; + const edges = [{ name: 'c2#e1', type: 'line', a: [0, 0, 0] as [number, number, number], b: [20, 0, 0] as [number, number, number], mid: [10, 0, 0] as [number, number, number], length: 20, faces: [0, 1], dir: [1, 0, 0] as [number, number, number] }]; + const s = buildSheet(d, new Map([['v1', pr]]), { + partName: 'A', material: '', units: 'mm', date: '', formatLength: (v) => v.toFixed(1), edges: () => edges, itemOf: (_src, edge) => itemOfEdge(edge, rows), + }); + const dot = s.items.find((i): i is Extract => i.t === 'circle' && i.r === 0.3)!; + expect(dot.cx).toBeCloseTo(106, 9); + }); + + it('draws the number in a circle with a leader to a dot on the edge', () => { + const items: Item[] = []; + const box = drawBalloon(items, '12', [50, 50], [70, 50]); + expect(box).toEqual([50 - BALLOON_R, 50 - BALLOON_R, 50 + BALLOON_R, 50 + BALLOON_R]); + expect(items.filter((it) => it.t === 'circle')).toHaveLength(2); + const text = items.find((it) => it.t === 'text') as Extract; + expect(text).toMatchObject({ s: '12', x: 50, anchor: 'middle' }); + // The leader starts on the circle. + const leader = items.find((it) => it.t === 'line') as Extract; + expect(leader.x1).toBeCloseTo(50 + BALLOON_R, 9); + expect(leader.x2).toBe(70); + // A long number shrinks to stay inside the circle. + const more: Item[] = []; + drawBalloon(more, '1234', [0, 0], null); + const t2 = more.find((it) => it.t === 'text') as Extract; + expect(textWidth('1234', t2.size)).toBeLessThan(2 * BALLOON_R); + expect(more.some((it) => it.t === 'line')).toBe(false); + }); + + it('draws balloons on the sheet with the item number of their edge, or a red question mark', () => { + const d: DrawingDoc = { + sheet: 'A4', landscape: true, scale: 1, title: '', drawnBy: '', notes: '', + views: [{ id: 'v1', kind: 'front', x: 100, y: 100, hidden: false, dims: false, source: 'assembly' }], + annotations: [ + { id: 'a1', type: 'balloon', view: 'v1', ref: { edge: 'c2#e1', at: 'edge' }, at: [30, -30] }, + { id: 'a2', type: 'balloon', view: 'v1', ref: { edge: 'gone#e1', at: 'edge' }, at: [-30, -30] }, + { id: 'a3', type: 'balloon', view: 'v1', ref: { edge: 'c2#e1', at: 'edge' }, at: [30, 30], item: 7 }, + ], + }; + const pr = { id: 'k', visible: ['M0 0L20 0'], hidden: [], bounds: [0, -10, 20, 0] as [number, number, number, number] }; + const edges = [{ name: 'c2#e1', type: 'line', a: [0, 0, 0] as [number, number, number], b: [20, 0, 0] as [number, number, number], mid: [10, 0, 0] as [number, number, number], length: 20, faces: [0, 1], dir: [1, 0, 0] as [number, number, number] }]; + const s = buildSheet(d, new Map([['v1', pr]]), { + partName: 'A', material: '', units: 'mm', date: '', formatLength: (v) => v.toFixed(1), edges: () => edges, itemOf: (_src, edge) => itemOfEdge(edge, rows), + }); + const texts = s.items.filter((it): it is Extract => it.t === 'text' && it.anchor === 'middle' && it.size <= 3.5); + expect(texts.find((t) => t.s === '2')?.color).toBeUndefined(); + expect(texts.find((t) => t.s === '?')?.color).toBe('#d32f2f'); + expect(texts.find((t) => t.s === '7')).toBeTruthy(); + expect(s.annos.map((a) => a.id)).toEqual(['a1', 'a2', 'a3']); + }); + + it('places automatic balloons outside the view, apart, one per row it shows', () => { + const line = (edge: string, a: [number, number], b: [number, number]): Prim => ({ edge, kind: 'line', a, b }); + const prims: Prim[] = [ + line('c1#a', [0, 0], [100, 0]), line('c1#b', [100, 0], [100, 50]), line('c1#c', [100, 50], [0, 50]), line('c1#d', [0, 50], [0, 0]), + line('c2#a', [40, 20], [60, 20]), line('c2#b', [60, 20], [60, 30]), + line('c3#a', [45, 22], [55, 22]), + ]; + const plan = autoBalloons(prims, rows, [0, 0, 100, 50], 1); + expect(plan.map((p) => p.item).sort()).toEqual([1, 2]); + for (const p of plan) { + const inside = p.at[0] > -10 && p.at[0] < 110 && p.at[1] > -10 && p.at[1] < 60; + expect(inside).toBe(false); + expect(rows.find((r) => r.item === p.item)!.prefixes.some((x) => p.ref.edge.startsWith(x))).toBe(true); + expect(p.ref.at).toBe('edge'); + } + expect(Math.hypot(plan[0].at[0] - plan[1].at[0], plan[0].at[1] - plan[1].at[1])).toBeGreaterThanOrEqual(2 * BALLOON_R); + // Items already ballooned are skipped; rows the view does not show get none. + expect(autoBalloons(prims, rows, [0, 0, 100, 50], 1, new Set([1])).map((p) => p.item)).toEqual([2]); + expect(autoBalloons(prims.slice(0, 4), rows, [0, 0, 100, 50], 1).map((p) => p.item)).toEqual([1]); + // Many components close together are spread around the view. + const many: BomRow[] = Array.from({ length: 8 }, (_, i) => ({ item: i + 1, name: `P${i}`, qty: 1, prefixes: [`k${i}#`] })); + const crowded = many.map((_, i) => line(`k${i}#e`, [50 + i * 0.1, 0], [50 + i * 0.1, 1])); + const spread = autoBalloons(crowded, many, [0, 0, 100, 50], 1); + expect(spread).toHaveLength(8); + for (let i = 0; i < spread.length; i++) for (let j = i + 1; j < spread.length; j++) { + expect(Math.hypot(spread[i].at[0] - spread[j].at[0], spread[i].at[1] - spread[j].at[1])).toBeGreaterThan(2 * BALLOON_R); + } + }); +}); + +describe('drawing data', () => { + const base: DrawingDoc = { sheet: 'A4', landscape: true, scale: 1, title: '', drawnBy: '', notes: '', views: [{ id: 'v1', kind: 'front', x: 100, y: 100, hidden: true, dims: true }] }; + + it('accepts flat pattern views, cut lists, anchored tables and exploded assembly views', () => { + expect(validDrawing({ + ...base, + views: [...base.views, { id: 'v2', kind: 'front', type: 'flat', x: 1, y: 2, hidden: false, dims: true, scale: 0.5 }, + { id: 'v3', kind: 'front', type: 'detail', parent: 'v2', circle: [0, 0, 5], x: 1, y: 2, hidden: false, dims: false }, + { id: 'v4', kind: 'isometric', x: 1, y: 2, hidden: false, dims: false, source: 'assembly:exploded' }], + annotations: [ + { id: 'a1', type: 'bom', at: [400, 255], anchor: 'bottomRight' }, + { id: 'a2', type: 'cutList', at: [10, 10] }, + { id: 'a3', type: 'cutList', at: [10, 10], anchor: 'bottomRight' }, + { id: 'a4', type: 'balloon', view: 'v1', ref: { edge: 'c1#E1:cap0', at: 'edge' }, at: [0, 0] }, + ], + })).toBe(true); + }); + + it('rejects damaged ones', () => { + const bad = (patch: Partial | Record) => validDrawing({ ...base, ...patch }); + // A flat view made from another view, or a projected view made from a flat one. + expect(bad({ views: [...base.views, { id: 'v2', kind: 'front', type: 'flat', parent: 'v1', x: 0, y: 0, hidden: false, dims: true }] })).toBe(false); + expect(bad({ views: [...base.views, { id: 'v2', kind: 'front', type: 'flat', x: 0, y: 0, hidden: false, dims: true }, { id: 'v3', kind: 'right', type: 'projected', parent: 'v2', side: 'right', x: 0, y: 0, hidden: false, dims: false }] })).toBe(false); + expect(bad({ annotations: [{ id: 'a', type: 'cutList', at: [0] }] })).toBe(false); + expect(bad({ annotations: [{ id: 'a', type: 'cutList', at: [0, 0], anchor: 'middle' }] })).toBe(false); + expect(bad({ annotations: [{ id: 'a', type: 'bom', at: [0, 0], anchor: 'topRight' }] })).toBe(false); + expect(bad({ annotations: [{ id: 'a', type: 'balloon', view: 'v1', ref: { edge: 'e', at: 'edge' }, at: [0, 0], item: 0 }] })).toBe(false); + expect(bad({ annotations: [{ id: 'a', type: 'balloon', ref: { edge: 'e', at: 'edge' }, at: [0, 0] }] })).toBe(false); + expect(bad({ annotations: [{ id: 'a', type: 'balloon', view: 'v1', ref: { edge: 'e', at: 'edge' }, at: [0, 0], t: 1.5 }] })).toBe(false); + expect(bad({ annotations: [{ id: 'a', type: 'balloon', view: 'v1', ref: { edge: 'e', at: 'edge' }, at: [0, 0], t: '0.5' }] })).toBe(false); + expect(bad({ annotations: [{ id: 'a', type: 'balloon', view: 'v1', ref: { edge: 'e', at: 'edge' }, at: [0, 0], t: 0.25 }] })).toBe(true); + }); + + it('keeps an assembly’s drawing when the assembly is opened, and rejects a damaged one', () => { + const doc = { ...newAssembly('Asm'), drawing: { ...base, views: [{ ...base.views[0], source: 'assembly' }], annotations: [{ id: 'a1', type: 'bom', at: [10, 10] }] } }; + const back = validateAssembly(JSON.parse(JSON.stringify(doc))); + expect(back.drawing).toEqual(doc.drawing); + expect(validateAssembly(JSON.parse(JSON.stringify(newAssembly('Asm')))).drawing).toBeUndefined(); + expect(() => validateAssembly({ ...JSON.parse(JSON.stringify(doc)), drawing: { ...base, sheet: 'B7' } })).toThrow('The assembly file is damaged (invalid drawing).'); + }); + + it('keeps room above the title block for a table when laying out the standard views', () => { + const sheet = { w: 420, h: 297 }; + const plain = standardLayout(sheet, [0, 0, 0], [200, 100, 80]); + const kept = standardLayout(sheet, [0, 0, 0], [200, 100, 80], 32 + 40); + expect(kept.scale).toBeLessThanOrEqual(plain.scale); + // Default: as before. + expect(standardLayout(sheet, [0, 0, 0], [200, 100, 80], 32)).toEqual(plain); + }); +}); + +describe('the assistant’s drawing tool', () => { + it('offers every sheet size a drawing can have', () => { + const spec = toolSpecs().find((t) => t.function.name === 'drawing')!; + const sheet = (spec.function.parameters as { properties: { sheet: { enum: string[] } } }).properties.sheet; + expect([...sheet.enum].sort()).toEqual(Object.keys(SHEETS).sort()); + }); +}); diff --git a/src/parametric/tests/drawing-views.test.ts b/src/parametric/tests/drawing-views.test.ts new file mode 100644 index 0000000000..88beb66f99 --- /dev/null +++ b/src/parametric/tests/drawing-views.test.ts @@ -0,0 +1,415 @@ +// Drawing views, annotations and exports beyond the standard views: view directions and +// alignment, hatching and clipping, dimension measuring and formatting, the full title block, +// DXF, and validation of old and new drawings. +import { describe, expect, it } from 'vitest'; +import type { EdgeInfo, ProjectionResult } from '../src/kernel/protocol'; +import type { DrawingDoc, HoleFeature } from '../src/model/types'; +import { validDrawing } from '../src/model/validate-drawing'; +import { type Geo, drawDimension, guessKind, holeCalloutText, holeCount, holeInstance, holeSpecOf, measure } from '../src/drawing/annotate'; +import { circleArc, dxfText, toDxf } from '../src/drawing/dxf'; +import { type Item, buildSheet, switchProjection, toPdf, toSvg, viewCaption } from '../src/drawing/sheet'; +import { arcOverHalf, besideOrient, centerMarks, clipToCircle, dependents, hatch, holeAxes, resolveViews, standardOrient, viewPrims } from '../src/drawing/views'; +import { detailScale, nextLetter } from '../src/app/drawing'; + +const fmt = { length: (mm: number, d?: number) => mm.toFixed(d ?? 2), angle: (deg: number, d?: number) => `${deg.toFixed(d ?? 1)}°` }; +const base = (views: DrawingDoc['views'], extra: Partial = {}): DrawingDoc => ({ sheet: 'A3', landscape: true, scale: 1, title: 'T', drawnBy: '', notes: '', views, ...extra }); +const box = (id: string, w: number, h: number): ProjectionResult => ({ id, visible: [`M ${-w / 2} ${-h / 2} H ${w / 2} V ${h / 2} H ${-w / 2} Z`], hidden: [], bounds: [-w / 2, -h / 2, w / 2, h / 2] }); +const info = { partName: 'P', material: 'Steel', units: 'mm', date: '2026-01-01', formatLength: (v: number) => v.toFixed(2) }; + +describe('view directions', () => { + it('projects to each side in third and first angle like the standard views', () => { + const front = standardOrient('front'); + const near = (a: number[], b: number[]) => a.every((x, i) => Math.abs(x - b[i]) < 1e-12); + // Third angle: the view on a side is seen from that side. + expect(near(besideOrient(front, [1, 0], false).dir, [1, 0, 0])).toBe(true); + expect(near(besideOrient(front, [1, 0], false).x, standardOrient('right').x)).toBe(true); + expect(near(besideOrient(front, [0, -1], false).dir, [0, 1, 0])).toBe(true); + expect(near(besideOrient(front, [0, -1], false).x, standardOrient('top').x)).toBe(true); + expect(near(besideOrient(front, [0, 1], false).dir, [0, -1, 0])).toBe(true); + // First angle: right of the front is the view from the left, below it the view from above. + expect(near(besideOrient(front, [1, 0], true).dir, [-1, 0, 0])).toBe(true); + expect(near(besideOrient(front, [0, 1], true).dir, [0, 1, 0])).toBe(true); + expect(near(besideOrient(front, [0, 1], true).x, standardOrient('top').x)).toBe(true); + }); + + it('resolves projected, section and detail views from their parents, and drops orphans', () => { + const d = base([ + { id: 'v1', kind: 'front', x: 100, y: 100, hidden: true, dims: true }, + { id: 'v2', kind: 'right', type: 'projected', parent: 'v1', side: 'right', x: 200, y: 50, hidden: true, dims: false }, + { id: 'v3', kind: 'front', type: 'detail', parent: 'v2', circle: [1, 2, 5], x: 300, y: 200, hidden: false, dims: false }, + { id: 'v4', kind: 'front', type: 'projected', parent: 'gone', side: 'left', x: 0, y: 0, hidden: false, dims: false }, + ], { scale: 0.5 }); + const rs = resolveViews(d); + expect(rs.get('v2')).toMatchObject({ type: 'projected', align: 'y', scale: 0.5 }); + // A detail is twice its parent's scale unless given its own, and looks the same way. + expect(rs.get('v3')).toMatchObject({ type: 'detail', scale: 1, clip: { c: [1, 2], r: 5 } }); + expect(rs.get('v3')!.key).toBe(rs.get('v2')!.key); + expect(rs.has('v4')).toBe(false); + expect(viewCaption(d, rs.get('v2')!)).toBe('RIGHT'); + expect(viewCaption(d, rs.get('v3')!)).toBe('DETAIL A SCALE 1:1'); + expect(dependents(d, 'v1')).toEqual(['v2', 'v3']); + }); + + it('keeps a projected view aligned with its parent on the sheet', () => { + const d = base([ + { id: 'v1', kind: 'front', x: 100, y: 100, hidden: false, dims: false }, + { id: 'v2', kind: 'right', type: 'projected', parent: 'v1', side: 'right', x: 200, y: 37, hidden: false, dims: false }, + { id: 'v3', kind: 'top', type: 'projected', parent: 'v1', side: 'above', x: 13, y: 40, hidden: false, dims: false }, + ]); + // Bounds offset differently in each view: alignment is by model coordinates, not view centres. + const proj = new Map([ + ['v1', { id: 'v1', visible: ['M0 0L40 0L40 -20L0 -20Z'], hidden: [], bounds: [0, -20, 40, 0] }], + ['v2', { id: 'v2', visible: ['M-10 0L0 0L0 -20L-10 -20Z'], hidden: [], bounds: [-10, -20, 0, 0] }], + ['v3', { id: 'v3', visible: ['M0 0L40 0L40 10L0 10Z'], hidden: [], bounds: [0, 0, 40, 10] }], + ]); + const s = buildSheet(d, proj, info); + const p1 = s.placements.get('v1')!, p2 = s.placements.get('v2')!, p3 = s.placements.get('v3')!; + expect(p2.ty).toBe(p1.ty); + expect(p3.tx).toBe(p1.tx); + // The free axis is where the view was put. + expect((p2.frame.x0 + p2.frame.x1) / 2).toBeCloseTo(200, 9); + expect((p3.frame.y0 + p3.frame.y1) / 2).toBeCloseTo(40, 9); + }); + + it('switching the projection angle moves the views beside the front view to its other side, each still showing what it showed', () => { + const d = base([ + { id: 'v1', kind: 'front', x: 120, y: 150, hidden: false, dims: true }, + { id: 'v2', kind: 'top', x: 120, y: 80, hidden: false, dims: true }, + { id: 'v3', kind: 'right', x: 200, y: 150, hidden: false, dims: true }, + { id: 'v4', kind: 'isometric', x: 200, y: 80, hidden: false, dims: false }, + { id: 'v5', kind: 'back', type: 'projected', parent: 'v3', side: 'right', x: 260, y: 150, hidden: false, dims: false }, + { id: 'v6', kind: 'front', type: 'section', parent: 'v1', line: [-30, 0, 30, 0], label: 'A', x: 120, y: 230, hidden: false, dims: false }, + { id: 'v7', kind: 'front', type: 'detail', parent: 'v1', circle: [0, 0, 5], scale: 2, label: 'B', x: 330, y: 60, hidden: false, dims: false }, + ]); + const sizes: Record = { v1: 20, v2: 20, v3: 20, v4: 30, v5: 20, v6: 10, v7: 10 }; + const frameOf = (v: DrawingDoc['views'][number]) => ({ id: v.id, x0: v.x - sizes[v.id], y0: v.y - sizes[v.id], x1: v.x + sizes[v.id], y1: v.y + sizes[v.id] }); + // (A section's plane is the same; the point it is given by is the line's other end.) + const dirs = (x: DrawingDoc) => new Map([...resolveViews(x).values()].map((r) => [r.v.id, [r.o.dir, r.o.x, r.section ? [r.section.n, r.section.p[1]] : null]])); + const before = dirs(d); + const at = (x: DrawingDoc) => Object.fromEntries(x.views.map((v) => [v.id, [v.x, v.y]])); + const was = at(d); + switchProjection(d, 'first', frameOf); + expect(d.projection).toBe('first'); + const now = at(d); + const [fx, fy] = now.v1; + // Top below the front, right left of it, at the distances they had; the isometric view in the top view's row. + expect(now.v2[0]).toBeCloseTo(fx, 9); + expect(now.v2[1] - fy).toBeCloseTo(was.v1[1] - was.v2[1], 9); + expect(fx - now.v3[0]).toBeCloseTo(was.v3[0] - was.v1[0], 9); + expect(now.v3[1]).toBeCloseTo(fy, 9); + expect(now.v4[1]).toBeCloseTo(now.v2[1], 9); + // The projected view goes to the other side of the right view. + expect(d.views[4].side).toBe('left'); + expect(now.v3[0] - now.v5[0]).toBeCloseTo(was.v5[0] - was.v3[0], 9); + // The section keeps its place relative to the front (it is aligned with it); the detail stays put. + expect(now.v6[0] - fx).toBeCloseTo(was.v6[0] - was.v1[0], 9); + expect(now.v7).toEqual(was.v7); + // Every view looks the way it did. + expect(dirs(d)).toEqual(before); + // On the sheet (420 x 297) and clear of the title block. + for (const v of d.views) { const f = frameOf(v); expect(f.x0).toBeGreaterThanOrEqual(10); expect(f.y1).toBeLessThanOrEqual(287); } + // And back. + switchProjection(d, 'third', frameOf); + expect(dirs(d)).toEqual(before); + expect(d.views[4].side).toBe('right'); + expect(at(d).v2[1]).toBeLessThan(at(d).v1[1]); + expect(at(d).v3[0]).toBeGreaterThan(at(d).v1[0]); + }); + + it('picks the next free view letter, skipping I, O and Q', () => { + const d = base(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'].map((label, i) => ({ id: `s${i}`, kind: 'front', type: 'section', parent: 'v0', line: [0, 0, 1, 0] as [number, number, number, number], label, x: 0, y: 0, hidden: false, dims: false }))); + expect(nextLetter(d)).toBe('J'); + expect(detailScale(1)).toBe(2); + expect(detailScale(0.5)).toBe(1); + expect(detailScale(0.3)).toBe(1); + }); +}); + +describe('hatching and clipping', () => { + it('hatches a square with a square hole even-odd at 45 degrees', () => { + const outer = [0, 0, 10, 0, 10, 10, 0, 10, 0, 0], inner = [3, 3, 7, 3, 7, 7, 3, 7, 3, 3]; + const lines = hatch([outer, inner], 45, 0.25); + const area = lines.reduce((s, [x1, y1, x2, y2]) => s + Math.hypot(x2 - x1, y2 - y1), 0) * 0.25; + expect(area).toBeCloseTo(100 - 16, 0); + for (const [x1, y1, x2, y2] of lines) { + // Every line is at 45 degrees and none crosses the hole. + expect(Math.abs(Math.abs(x2 - x1) - Math.abs(y2 - y1))).toBeLessThan(1e-9); + const mx = (x1 + x2) / 2, my = (y1 + y2) / 2; + expect(mx > 3 + 1e-9 && mx < 7 - 1e-9 && my > 3 + 1e-9 && my < 7 - 1e-9).toBe(false); + } + expect(hatch([], 45, 1)).toEqual([]); + }); + + it('clips polylines to a circle', () => { + const parts = clipToCircle([[-10, 0], [10, 0]], [0, 0], 5); + expect(parts).toHaveLength(1); + expect(parts[0][0][0]).toBeCloseTo(-5, 9); + expect(parts[0][1][0]).toBeCloseTo(5, 9); + expect(clipToCircle([[-10, 9], [10, 9]], [0, 0], 5)).toEqual([]); + // In and out again: two pieces. + expect(clipToCircle([[0, 0], [10, 0], [10, 1], [0, 1]], [0, 0], 3)).toHaveLength(2); + }); +}); + +describe('model edges in a view', () => { + const edge = (name: string, e: Partial): EdgeInfo => ({ name, type: 'line', a: [0, 0, 0], b: [0, 0, 0], mid: [0, 0, 0], length: 1, faces: [0, 1], ...e }); + const hole = (name: string, z: number): EdgeInfo => edge(name, { type: 'circle', a: [13, 5, z], b: [13, 5, z], mid: [7, 5, z], center: [10, 5, z], axis: [0, 0, 1], radius: 3, length: 6 * Math.PI }); + const edges = [ + edge('top', { a: [0, 10, 0], b: [40, 10, 0], mid: [20, 10, 0], length: 40 }), + edge('seam', { a: [7, 5, 0], b: [7, 5, 6], faces: [3] }), + hole('h0', 0), hole('h6', 6), + ]; + it('sees lines and holes end on from the front, and holes edge on from above', () => { + const d = base([{ id: 'v1', kind: 'front', x: 0, y: 0, hidden: false, dims: false }, { id: 'v2', kind: 'top', x: 0, y: 0, hidden: false, dims: false }]); + const rs = resolveViews(d); + const front = viewPrims(rs.get('v1')!, edges); + expect(front.find((p) => p.edge === 'top')).toMatchObject({ kind: 'line', a: [0, -10], b: [40, -10] }); + expect(front.some((p) => p.edge === 'seam')).toBe(false); + expect(front.find((p) => p.edge === 'h0')).toMatchObject({ kind: 'arc', c: [10, -5], r: 3, full: true }); + // One centre mark for the two circles of the hole. + expect(centerMarks(front)).toEqual([{ c: [10, -5], r: 3, edge: 'h0' }]); + const top = viewPrims(rs.get('v2')!, edges); + const across = top.find((p) => p.edge === 'h6')!; + expect(across.kind).toBe('line'); + // The hole's axis, from the top: a centerline through both circles' centres. + const axes = holeAxes(rs.get('v2')!, edges); + expect(axes).toHaveLength(1); + expect(Math.abs(axes[0].a[1] - axes[0].b[1])).toBeCloseTo(6, 9); + expect(arcOverHalf({ a: [1, 0], b: [-1, 0], m: [0, 1], c: [0, 0] })).toBe(false); + expect(arcOverHalf({ a: [1, 0.1], b: [-1, 0.1], m: [0, -1], c: [0, 0] })).toBe(true); + }); +}); + +describe('dimensions', () => { + const L = (a: [number, number], b: [number, number]): Geo => ({ kind: 'line', a, b }); + const P = (p: [number, number]): Geo => ({ kind: 'point', p }); + const circle: Geo = { kind: 'circle', c: [5, 5], r: 2.5, full: true, a: [7.5, 5], b: [7.5, 5], m: [2.5, 5] }; + + it('chooses the kind from the geometry and where the value is placed', () => { + expect(guessKind([circle], [20, 0])).toBe('diameter'); + expect(guessKind([{ ...circle, full: false, a: [7.5, 5], b: [5, 2.5], m: [6.77, 3.23] }], [20, 0])).toBe('radius'); + expect(guessKind([L([0, 0], [10, 0])], [5, -5])).toBe('horizontal'); + expect(guessKind([L([0, 0], [10, 10])], [5, -20])).toBe('horizontal'); + expect(guessKind([L([0, 0], [10, 10])], [-20, 5])).toBe('vertical'); + expect(guessKind([L([0, 0], [10, 10])], [0, 10])).toBe('aligned'); + expect(guessKind([L([0, 0], [10, 0]), L([0, 0], [10, 10])], [9, 3])).toBe('angle'); + expect(guessKind([L([0, 0], [10, 0]), L([0, 4], [10, 4])], [5, 2])).toBe('vertical'); + expect(guessKind([P([0, 0]), L([5, -5], [5, 5])], [2, -8])).toBe('horizontal'); + }); + + it('measures lengths, distances, diameters, radii and angles', () => { + expect(measure('horizontal', [L([0, 0], [30, 40])])!.value).toBeCloseTo(30, 12); + expect(measure('vertical', [L([0, 0], [30, 40])])!.value).toBeCloseTo(40, 12); + expect(measure('aligned', [L([0, 0], [30, 40])])!.value).toBeCloseTo(50, 12); + expect(measure('vertical', [L([0, 0], [10, 0]), L([3, 7], [9, 7])])!.value).toBeCloseTo(7, 12); + expect(measure('aligned', [P([0, 0]), L([5, -5], [5, 5])])!.value).toBeCloseTo(5, 12); + expect(measure('diameter', [circle])!.value).toBe(5); + expect(measure('radius', [circle])!.value).toBe(2.5); + expect(measure('angle', [L([0, 0], [10, 0]), L([0, 0], [10, 10])])!.value).toBeCloseTo(45, 9); + expect(measure('angle', [L([0, 0], [10, 0]), L([0, 1], [10, 1])])).toBeNull(); + }); + + it('formats values in the document units with their decimals and symbols', () => { + const items: Item[] = []; + const pl = { T: (q: [number, number]): [number, number] => [100 + q[0] * 2, 100 + q[1] * 2], s: 2 }; + const texts = () => items.filter((i) => i.t === 'text').map((i) => (i as Extract).s); + drawDimension(items, { id: 'd', type: 'dimension', view: 'v', kind: 'diameter', refs: [], at: [15, -5] }, measure('diameter', [circle]), pl, fmt); + drawDimension(items, { id: 'd', type: 'dimension', view: 'v', kind: 'radius', refs: [], at: [6, 5] , decimals: 1 }, measure('radius', [circle]), pl, fmt); + drawDimension(items, { id: 'd', type: 'dimension', view: 'v', kind: 'vertical', refs: [], at: [-10, 20], prefix: '2X ' }, measure('vertical', [L([0, 0], [30, 40])]), pl, fmt); + drawDimension(items, { id: 'd', type: 'dimension', view: 'v', kind: 'angle', refs: [], at: [9, 3] }, measure('angle', [L([0, 0], [10, 0]), L([0, 0], [10, 10])]), pl, fmt); + expect(texts()).toEqual(['Ø5.00', 'R2.5', '2X 40.00', '45.0°']); + // A vertical value reads upward. + expect(items.find((i) => i.t === 'text' && i.s === '2X 40.00')).toMatchObject({ rotate: -90 }); + // Missing geometry: drawn where it was, in red, marked. + const gone: Item[] = []; + drawDimension(gone, { id: 'd', type: 'dimension', view: 'v', kind: 'diameter', refs: [], at: [0, 0] }, null, pl, fmt); + expect(gone).toEqual([expect.objectContaining({ t: 'text', s: 'Ø? (missing)', color: '#d32f2f' })]); + expect(holeCalloutText({ kind: 'counterbore', diameter: 6.6, cbDiameter: 11, cbDepth: 6.4, count: 4 }, fmt)).toBe('4X Ø6.60 THRU\nCBORE Ø11.00 DEEP 6.40'); + expect(holeCalloutText({ kind: 'countersink', diameter: 5, depth: 10, csDiameter: 10, csAngle: 90, count: 1 }, fmt)).toBe('Ø5.00 DEEP 10.00\nCSK Ø10.00 X 90°'); + }); + + it('counts the holes a hole feature makes from its faces, pattern and mirror copies included', () => { + const hole = { id: 'h', type: 'hole', name: 'Hole1', sketch: 's', kind: 'simple', diameter: 6, end: 'throughAll', depth: 10, cbDiameter: 11, cbDepth: 3, csDiameter: 12, csAngle: 90, flip: false } as HoleFeature; + expect(holeInstance('f2:p1:1@f5.3')).toEqual({ feature: 'f2', key: 'p1@f5.3' }); + expect(holeInstance('f2:p1:2#1')).toEqual({ feature: 'f2', key: 'p1' }); + expect(holeInstance('f1:cap0')).toBeNull(); + // Two holes, two faces each (a counterbore), a copy of each, and a copy of one mirrored; faces of other features. + const names = ['f2:p1:1', 'f2:p1:2', 'f2:p2:1', 'f2:p2:2', 'f2:p1:1@f5.1', 'f2:p1:2@f5.1', 'f2:p2:1@f5.1', 'f2:p1:1@f5.1@f6.1', 'f1:cap0', 'f1:side:bl2', 'f7:p1:1']; + expect(holeCount(names, 'f2')).toBe(5); + expect(holeCalloutText(holeSpecOf(hole, holeCount(names, 'f2')), fmt)).toBe('5X Ø6.00 THRU'); + expect(holeSpecOf({ ...hole, end: 'blind' }, 1)).toMatchObject({ count: 1, depth: 10 }); + }); +}); + +describe('sheet', () => { + it('draws the full title block with the projection symbol only when asked', () => { + const basic = toSvg(buildSheet(base([]), new Map(), info).items, 420, 297); + expect(basic).not.toContain('THIRD ANGLE'); + expect(basic).not.toContain('FIRST ANGLE<'); + expect(svg).toContain('>1 OF 1<'); + expect(svg).toContain('>B<'); + expect((svg.match(/ i.t === 'circle') as Extract[]; + const trapezoid = full.items.filter((i) => i.t === 'line' && i.w === 0.25 && Math.abs(i.y1 - i.y2) > 0.5 && Math.abs(i.x1 - i.x2) > 0.5) as Extract[]; + expect(circles[0].cx).toBeLessThan(Math.min(...trapezoid.map((l) => Math.min(l.x1, l.x2)))); + const third = buildSheet(base([], { titleBlock: 'full' }), new Map(), info); + const c3 = third.items.find((i) => i.t === 'circle') as Extract; + expect(c3.cx).toBeGreaterThan(circles[0].cx); + // PDF draws circles and colours. + const pdf = new TextDecoder().decode(toPdf(full.items, full.w, full.h, 'T')); + expect(pdf).toContain('(FIRST ANGLE) Tj'); + }); + + it('draws section hatching inside the view group, the cutting line and the caption', () => { + const d = base([ + { id: 'v1', kind: 'front', x: 100, y: 100, hidden: false, dims: false }, + { id: 'v2', kind: 'front', type: 'section', parent: 'v1', line: [-30, 0, 30, 0], label: 'C', x: 100, y: 200, hidden: false, dims: false }, + ]); + const sec = { ...box('v2', 40, 6), cut: [[-20, -3, 20, -3, 20, 3, -20, 3, -20, -3]] }; + const s = buildSheet(d, new Map([['v1', box('v1', 40, 20)], ['v2', sec]]), info); + const svg = toSvg(s.items, s.w, s.h); + expect(svg).toContain('>SECTION C-C<'); + expect((svg.match(/>C i.t === 'line' && i.w === 0.6)).toHaveLength(2); + }); + + it('marks an auxiliary view on its parent with an arrow square to the edge and the view letter', () => { + for (const projection of ['third', 'first'] as const) { + // The edge from (-20, 10) to (20, -10) on the parent at (100, 100); the view lies on its left normal's side (down and to the right). + const d = base([ + { id: 'v1', kind: 'front', x: 100, y: 100, hidden: false, dims: false }, + { id: 'v2', kind: 'front', type: 'auxiliary', parent: 'v1', line: [-20, 10, 20, -10], label: 'D', x: 50, y: 40, hidden: false, dims: false }, + ], { projection }); + const s = buildSheet(d, new Map([['v1', box('v1', 40, 20)], ['v2', box('v2', 30, 20)]]), info); + expect(s.items.some((i) => i.t === 'text' && i.s === 'VIEW D')).toBe(true); + const letter = s.items.find((i) => i.t === 'text' && i.s === 'D' && i.bold) as Extract; + expect(letter).toBeDefined(); + const tri = s.items.find((i) => i.t === 'tri') as Extract; + // The arrow points at the middle of the edge, from the side the view is seen from: + // third angle the view's side, first angle the other. + expect(Math.hypot(tri.a[0] - 100, tri.a[1] - 100)).toBeCloseTo(2, 6); + const n = [20, 40].map((q) => q / Math.hypot(20, 40)); + const side = (letter.x - 100) * n[0] + (letter.y - 1.75 - 100) * n[1]; + expect(projection === 'third' ? side > 10 : side < -10).toBe(true); + } + }); + + it('says where a section view is when its cutting line misses the part, and keeps it selectable', () => { + const d = base([ + { id: 'v1', kind: 'front', x: 100, y: 100, hidden: false, dims: false }, + { id: 'v2', kind: 'front', type: 'section', parent: 'v1', line: [30, 500, -30, 500], label: 'B', x: 150, y: 200, hidden: false, dims: false }, + ]); + const s = buildSheet(d, new Map([['v1', box('v1', 40, 20)], ['v2', { id: 'v2', visible: [], hidden: [], bounds: null, cut: [] }]]), info); + const note = s.items.find((i) => i.t === 'text' && i.s.startsWith('SECTION B-B:')) as Extract; + expect(note).toMatchObject({ s: 'SECTION B-B: THE CUTTING LINE MISSES THE PART', color: '#d32f2f' }); + const f = s.frames.find((q) => q.id === 'v2')!; + expect(f.x0).toBeLessThan(150); + expect(f.x1).toBeGreaterThan(150); + expect(f.y0).toBeLessThan(200); + // Still projecting: nothing yet. + expect(buildSheet(d, new Map([['v1', box('v1', 40, 20)]]), info).frames.map((q) => q.id)).toEqual(['v1']); + }); +}); + +describe('DXF', () => { + it('writes lines, true arcs, circles, text and arrowheads in millimetres with y up', () => { + const items: Item[] = [ + { t: 'line', x1: 0, y1: 10, x2: 20, y2: 10, w: 0.35 }, + { t: 'path', d: 'M10 0A5 5 0 0 1 0 0', tx: 100, ty: 50, s: 2, w: 0.35 }, + { t: 'circle', cx: 50, cy: 50, r: 4, w: 0.18 }, + { t: 'text', s: 'Ø10 ± 0.1 45°', x: 5, y: 5, size: 3, anchor: 'middle' }, + { t: 'tri', a: [0, 0], b: [1, 1], c: [1, -1] }, + { t: 'path', d: 'M0 0L5 0', tx: 0, ty: 0, s: 1, w: 0.18, dash: [1.6, 0.8] }, + ]; + const dxf = toDxf(items, 100, 100); + const lines = dxf.split('\n'); + expect(lines.slice(0, 2)).toEqual(['0', 'SECTION']); + expect(dxf.trimEnd().endsWith('0\nEOF')).toBe(true); + // The line is at y = 100 - 10. + const li = lines.indexOf('LINE'); + expect(lines.slice(li, li + 14)).toEqual(['LINE', '8', 'VISIBLE', '10', '0', '20', '90', '30', '0', '11', '20', '21', '90', '31']); + // The half circle: centre (5, 0) scaled by 2 and moved: (110, 50) on the sheet, y up 50; radius 10. + // It bulges down the sheet (sweep flag 1 turns clockwise with y down): with y up, 180 to 360 degrees. + const ai = lines.indexOf('ARC'); + expect(lines.slice(ai, ai + 15)).toEqual(['ARC', '8', 'VISIBLE', '10', '110', '20', '50', '30', '0', '40', '10', '50', '180', '51', '0']); + expect(lines).toContain('CIRCLE'); + expect(lines).toContain('SOLID'); + expect(dxf).toContain('%%c10 %%p 0.1 45%%d'); + expect(lines[lines.indexOf('HIDDEN', lines.indexOf('ENTITIES'))]).toBe('HIDDEN'); + expect(dxfText('Größe')).toBe('Gr??e'); + }); + + it('finds the centre of SVG arcs both ways round', () => { + const a = circleArc([10, 0], [0, 0], 5, false, true)!; + expect(a.c[0]).toBeCloseTo(5, 12); + expect(a.c[1]).toBeCloseTo(0, 12); + expect(a.sweep).toBeCloseTo(Math.PI, 12); + // Without the sweep flag the arc turns toward negative angles: around (10, 10), a quarter turn back. + const b = circleArc([10, 0], [0, 10], 10, false, false)!; + expect(b.c[0]).toBeCloseTo(10, 12); + expect(b.c[1]).toBeCloseTo(10, 12); + expect(b.sweep).toBeCloseTo(-Math.PI / 2, 12); + const c = circleArc([10, 0], [0, 10], 10, false, true)!; + expect(c.c[0]).toBeCloseTo(0, 12); + expect(c.sweep).toBeCloseTo(Math.PI / 2, 12); + }); +}); + +describe('validation', () => { + const old: DrawingDoc = { sheet: 'A4', landscape: true, scale: 0.5, title: '', drawnBy: '', notes: '', views: [{ id: 'v1', kind: 'front', x: 100, y: 100, hidden: true, dims: true }] }; + it('accepts drawings saved before views and annotations were added', () => { + expect(validDrawing(old)).toBe(true); + expect(validDrawing(JSON.parse(JSON.stringify(old)))).toBe(true); + }); + + it('accepts new views, annotations and sheet settings', () => { + const d: DrawingDoc = { + ...old, sheet: 'ANSI D', projection: 'first', titleBlock: 'full', revision: 'C', + views: [ + ...old.views, + { id: 'v2', kind: 'front', type: 'section', parent: 'v1', line: [0, 0, 10, 0], label: 'A', x: 1, y: 2, hidden: false, dims: false, centerMarks: true, tangent: false }, + { id: 'v3', kind: 'front', type: 'detail', parent: 'v2', circle: [0, 0, 5], scale: 2, label: 'B', x: 1, y: 2, hidden: false, dims: false }, + { id: 'v4', kind: 'right', type: 'projected', parent: 'v1', side: 'right', x: 1, y: 2, hidden: true, dims: false, source: 'part' }, + ], + annotations: [ + { id: 'a1', type: 'dimension', view: 'v1', kind: 'horizontal', refs: [{ edge: 'E1:side:1|E1:cap1', at: 'edge' }], at: [0, -10], decimals: 1, prefix: '2X ' }, + { id: 'a2', type: 'note', text: 'NOTE', at: [20, 20], leader: [10, 10], size: 3.5 }, + { id: 'a3', type: 'centerMark', view: 'v1', ref: { edge: 'h', at: 'edge' } }, + { id: 'a4', type: 'centerline', view: 'v1', refs: [{ edge: 'a', at: 'edge' }, { edge: 'b', at: 'edge' }] }, + { id: 'a5', type: 'holeCallout', view: 'v1', ref: { edge: 'h', at: 'edge' }, at: [5, 5] }, + { id: 'a6', type: 'balloon', view: 'v1', ref: { edge: 'part1/e', at: 'edge' }, at: [5, 5], item: 3 }, + { id: 'a7', type: 'bom', at: [300, 20] }, + ], + }; + expect(validDrawing(d)).toBe(true); + }); + + it('rejects damaged new fields', () => { + const bad = (patch: (d: Record & { views: Record[] }) => void) => { + const d = JSON.parse(JSON.stringify({ ...old, views: [...old.views, { id: 'v2', kind: 'front', type: 'section', parent: 'v1', line: [0, 0, 10, 0], x: 0, y: 0, hidden: false, dims: false }] })); + patch(d); + return validDrawing(d); + }; + expect(bad(() => {})).toBe(true); + expect(bad((d) => { d.views[1].parent = 'nope'; })).toBe(false); + expect(bad((d) => { delete d.views[1].line; })).toBe(false); + expect(bad((d) => { d.views[1].line = [0, 0, 0, 0]; })).toBe(false); + expect(bad((d) => { d.views[1].type = 'cutaway'; })).toBe(false); + expect(bad((d) => { d.views[1].scale = 0; })).toBe(false); + expect(bad((d) => { d.projection = 'second'; })).toBe(false); + expect(bad((d) => { d.sheet = 'B5'; })).toBe(false); + expect(bad((d) => { d.annotations = [{ id: 'a', type: 'dimension', view: 'v1', kind: 'diameter', refs: [], at: [0, 0] }]; })).toBe(false); + expect(bad((d) => { d.annotations = [{ id: 'a', type: 'note', text: 'x', at: [0, 0], view: 'nope' }]; })).toBe(false); + expect(bad((d) => { d.annotations = [{ id: 'a', type: 'sticker', at: [0, 0] }]; })).toBe(false); + expect(bad((d) => { d.annotations = [{ id: 'a', type: 'note', text: 'x', at: [0] }]; })).toBe(false); + // Views made from each other in a loop could never be drawn. + expect(bad((d) => { d.views[0].type = 'projected'; d.views[0].parent = 'v2'; d.views[0].side = 'left'; })).toBe(false); + expect(bad((d) => { d.views.push({ id: 'v3', kind: 'front', type: 'detail', parent: 'v3', circle: [0, 0, 5], x: 0, y: 0, hidden: false, dims: false }); })).toBe(false); + }); +}); diff --git a/src/parametric/tests/e2e/assembly.spec.ts b/src/parametric/tests/e2e/assembly.spec.ts new file mode 100644 index 0000000000..c0ae893f88 --- /dev/null +++ b/src/parametric/tests/e2e/assembly.spec.ts @@ -0,0 +1,699 @@ +import { type Page, expect, test } from '@playwright/test'; +import { chooseTheme, openApp } from './helpers'; + +type A = import('../../src/app/app').App; + +const pts = (prefix: string, p: [number, number][]) => [ + ...p.map(([x, y], i) => ({ id: `${prefix}p${i}`, t: 'point', x, y })), + ...p.map((_, i) => ({ id: `${prefix}l${i}`, t: 'line', a: `${prefix}p${i}`, b: `${prefix}p${(i + 1) % p.length}` })), +]; +const extrude = (id: string, sketch: string, depth: number) => ({ id, name: id, type: 'extrude', sketch, cut: false, end: 'blind', depth, flip: false, dir2: null, draft: 0, draftOutward: false, thin: null }); +/** A 40 × 20 × 10 block with a Ø8 through hole near one end. */ +const BLOCK = [ + { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: [...pts('r', [[0, 0], [40, 0], [40, 20], [0, 20]]), { id: 'hc', t: 'point', x: 10, y: 10 }, { id: 'h', t: 'circle', c: 'hc', r: 4 }], constraints: [] }, + extrude('E1', 'S1', 10), +]; +/** A Ø8 pin, 30 long. */ +const PIN = [ + { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: [{ id: 'c', t: 'point', x: 0, y: 0 }, { id: 'k', t: 'circle', c: 'c', r: 4 }], constraints: [] }, + extrude('E1', 'S1', 30), +]; + +async function makePart(page: Page, name: string, features: unknown[]) { + await page.evaluate(async ({ name, features }) => { + const a = (window as unknown as { __parametric: A }).__parametric; + await a.commands.get('new')!.run(); + a.store.change('Make part', (d) => { d.name = name; d.features = features as never; d.nextId = 100; }); + a.commands.run('save'); + }, { name, features }); + await expect(page).toHaveTitle(`${name} - Parametric`); +} + +/** Where the centre of a component's face (by its name in the part) is on the screen. */ +async function facePoint(page: Page, comp: string, face: string) { + const at = await page.evaluate(({ comp, face }) => { + const a = (window as unknown as { __parametric: A }).__parametric; + const id = a.assembly!.doc.components.find((c) => c.name === comp)!.id; + const f = a.faces.find((x) => x.name === `${id}#${face}`)!; + return a.viewport.project(f.center); + }, { comp, face }); + const box = (await page.locator('canvas.gl').boundingBox())!; + return { x: box.x + at[0], y: box.y + at[1] }; +} + +async function clickFace(page: Page, comp: string, face: string) { + const p = await facePoint(page, comp, face); + await page.mouse.click(p.x, p.y); +} + +async function insert(page: Page, name: string) { + void page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.commands.run('insertComponent'); }); + const dlg = page.getByRole('dialog', { name: 'Insert Components' }); + await dlg.getByRole('button', { name: new RegExp(`^${name} This browser`) }).click(); + await expect(dlg).toHaveCount(0); +} + +test('builds an assembly of two parts, mates them, drags, explodes, saves and reopens it', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await makePart(page, 'Block', BLOCK); + await makePart(page, 'Pin', PIN); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await expect(page).toHaveTitle(/Assembly\d+ - Parametric/); + await expect(page.getByRole('tab', { name: 'Assembly' })).toBeVisible(); + await expect(page.getByRole('tab', { name: 'Features' })).toBeHidden(); + await insert(page, 'Block'); + await insert(page, 'Pin'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await expect(tree.getByRole('treeitem', { name: '(f) Block<1>' })).toBeVisible(); + await expect(tree.getByRole('treeitem', { name: '(-) Pin<1>' })).toBeVisible(); + // The tree lists a component before its geometry arrives (slow under load). + await page.waitForFunction(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + return ['Block<1>', 'Pin<1>'].every((n) => { + const id = a.assembly?.doc.components.find((c) => c.name === n)?.id; + return !!id && a.faces.some((f) => f.feature === id && f.type === 'cylinder'); + }); + }); + // Concentric: the pin's round face and the block's hole, selected first. + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const comp = (n: string) => a.assembly!.doc.components.find((c) => c.name === n)!.id; + const cyl = (n: string) => a.faces.findIndex((f) => f.feature === comp(n) && f.type === 'cylinder'); + a.selection.set([cyl('Pin<1>'), cyl('Block<1>')].map((index) => ({ kind: 'face' as const, index, name: a.faces[index].name }))); + }); + await page.getByRole('toolbar').getByRole('button', { name: 'Mate', exact: true }).or(page.locator('.cm [data-cmd="mate"]')).first().click(); + const pm = page.locator('.pm'); + await expect(pm.getByRole('combobox', { name: 'Mate type' })).toHaveValue('concentric'); + await expect(pm.getByRole('status').filter({ hasText: 'degrees of freedom' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await expect(tree.getByRole('treeitem', { name: /Concentric1/ })).toBeVisible(); + const axisGap = () => page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const m = a.assembly!; + const pin = m.doc.components.find((c) => c.name === 'Pin<1>')!; + const pl = m.solved.get(pin.id)!; + return { x: pl.p[0], y: pl.p[1], z: pl.p[2] }; + }); + const before = await axisGap(); + expect(before.x).toBeCloseTo(10, 4); + expect(before.y).toBeCloseTo(10, 4); + await expect(page.locator('.statusbar')).toContainText('Under Defined (2 DOF)'); + + // Dragging the pin slides it along the hole: the mate holds. + const end = await facePoint(page, 'Pin<1>', 'E1:cap1'); + await page.mouse.move(end.x, end.y); + await page.mouse.down(); + await page.mouse.move(end.x + 40, end.y - 30, { steps: 5 }); + await page.mouse.move(end.x + 90, end.y - 60, { steps: 5 }); + await page.mouse.up(); + const after = await axisGap(); + expect(after.x).toBeCloseTo(10, 4); + expect(after.y).toBeCloseTo(10, 4); + expect(Math.abs(after.z - before.z)).toBeGreaterThan(1); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.store.undoLabel)).toBe('Move component'); + + // Coincident by clicking the pin's end and the block's front face. + await page.locator('.cm [data-cmd="mate"]').click(); + await clickFace(page, 'Pin<1>', 'E1:cap1'); + await clickFace(page, 'Block<1>', 'E1:cap1'); + await expect(pm.getByRole('combobox', { name: 'Mate type' })).toHaveValue('coincident'); + await pm.getByRole('button', { name: 'OK' }).click(); + await expect(tree.getByRole('treeitem', { name: /Coincident1/ })).toBeVisible(); + await expect(page.locator('.statusbar')).toContainText('Under Defined (1 DOF)'); + expect((await axisGap()).z).toBeCloseTo(-20, 4); + + // Exploded view: the pin moves out along Z, and back. + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.selection.set([{ kind: 'feature', id: a.assembly!.doc.components.find((c) => c.name === 'Pin<1>')!.id }]); + }); + await page.locator('.cm [data-cmd="explodedView"]').click(); + await pm.getByRole('combobox', { name: 'Explode direction' }).selectOption('z'); + await pm.getByRole('textbox', { name: 'Distance' }).fill('60'); + await pm.getByRole('textbox', { name: 'Distance' }).press('Enter'); + await pm.getByRole('button', { name: 'OK' }).click(); + await expect(tree.getByRole('treeitem', { name: /Explode Step1/ })).toBeVisible(); + const shownZ = () => page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const pin = a.assembly!.doc.components.find((c) => c.name === 'Pin<1>')!; + return a.assembly!.shownPlacement(pin.id)!.p[2]; + }); + expect(await shownZ()).toBeCloseTo(40, 4); + await page.locator('.cm [data-cmd="toggleExplode"]').click(); + expect(await shownZ()).toBeCloseTo(-20, 4); + + // Bill of materials. + await page.locator('.cm [data-cmd="billOfMaterials"]').click(); + const bom = page.getByRole('dialog', { name: 'Bill of Materials' }); + await expect(bom.getByRole('row')).toHaveCount(3); + await expect(bom.getByRole('row').nth(1)).toContainText('Block'); + await bom.locator('[data-value="close"]').click(); + + // Save, open another document, and open the assembly again. + await page.keyboard.press('Meta+s'); + await expect(page).toHaveTitle(/^Assembly\d+ - Parametric$/); + const title = await page.title(); + const name = title.replace(' - Parametric', ''); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('new'); }); + await expect(page).toHaveTitle(/^Part\d+ - Parametric$/); + await expect(page.getByRole('tab', { name: 'Features' })).toBeVisible(); + await expect(page.getByRole('tab', { name: 'Assembly' })).toBeHidden(); + void page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.commands.run('open'); }); + await page.getByRole('dialog', { name: 'Open' }).getByRole('button', { name: new RegExp(`^${name} This browser`) }).click(); + await expect(page).toHaveTitle(`${name} - Parametric`); + await expect(tree.getByRole('treeitem', { name: '(f) Block<1>' })).toBeVisible(); + await expect(tree.getByRole('treeitem', { name: /Concentric1/ })).toBeVisible(); + await expect(tree.getByRole('treeitem', { name: /Coincident1/ })).toBeVisible(); + await expect(page.locator('.statusbar')).toContainText('Under Defined (1 DOF)'); + expect((await axisGap()).z).toBeCloseTo(-20, 4); + // Undo and redo work in the reopened assembly. + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.assembly!.commit('Fix', (d) => { for (const c of d.components) c.fixed = true; }); + }); + await expect(tree.getByRole('treeitem', { name: '(f) Pin<1>' })).toBeVisible(); + await page.keyboard.press('Meta+z'); + await expect(tree.getByRole('treeitem', { name: '(-) Pin<1>' })).toBeVisible(); + expect(errors).toEqual([]); +}); + +test('editing a part from its assembly, interference, measuring and STEP export', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await makePart(page, 'Block', BLOCK); + await makePart(page, 'Pin', PIN); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await insert(page, 'Block'); + await insert(page, 'Pin'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await expect(tree.getByRole('treeitem', { name: '(-) Pin<1>' })).toBeVisible(); + // Pin in the hole, its far end flush with the block's front face. + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const m = a.assembly!; + const [block, pin] = m.doc.components; + const face = (c: string, name: string) => { const g = m.geometryOf(m.component(c)!.part)!; const f = g.faces.find((x) => x.name === name)!; return { name: f.name, sig: { type: f.type, c: f.center, n: f.normal, area: f.area } }; }; + const cyl = (c: string) => { const g = m.geometryOf(m.component(c)!.part)!; const f = g.faces.find((x) => x.type === 'cylinder')!; return { name: f.name, sig: { type: f.type, c: f.center, area: f.area } }; }; + m.commit('Add mates', (d) => { + d.mates.push({ id: 'm90', name: 'Concentric1', type: 'concentric', a: { comp: block.id, face: cyl(block.id) }, b: { comp: pin.id, face: cyl(pin.id) }, aligned: true }); + d.mates.push({ id: 'm91', name: 'Coincident1', type: 'coincident', a: { comp: block.id, face: face(block.id, 'E1:cap1') }, b: { comp: pin.id, face: face(pin.id, 'E1:cap1') }, aligned: true }); + }); + }); + await expect(page.locator('.statusbar')).toContainText('Under Defined (1 DOF)'); + // NaN until the assembly has solved (just after it is opened again), so a poll waits for it. + const pinZ = () => page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly; + return m?.solved.get(m.doc.components[1].id)?.p[2] ?? NaN; + }); + expect(await pinZ()).toBeCloseTo(-20, 4); + await page.keyboard.press('Meta+s'); + await expect(page).toHaveTitle(/^Assembly\d+ - Parametric$/); + const asmTitle = await page.title(); + + // No interference: the pin fits the hole exactly. + await page.locator('.cm [data-cmd="interference"]').click(); + await expect(page.locator('.pm')).toContainText('No interference'); + await page.locator('.pm').getByRole('button', { name: 'Close' }).click(); + + // Measure between faces of two components (the kernel places them too). + const gap = await page.evaluate(async () => { + const a = (window as unknown as { __parametric: A }).__parametric; + const m = a.assembly!; + const [block, pin] = m.doc.components; + const back = a.faces.findIndex((f) => f.name === `${block.id}#E1:cap0`); + const pinEnd = a.faces.findIndex((f) => f.name === `${pin.id}#E1:cap0`); + return (await a.kernel.measure({ kind: 'face', index: back }, { kind: 'face', index: pinEnd })).distance; + }); + expect(gap).toBeCloseTo(20, 4); + + // STEP export of the whole assembly, components as named solids. + const download = page.waitForEvent('download'); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('exportStep'); }); + const file = await (await download).path(); + const { readFileSync } = await import('node:fs'); + const step = new TextDecoder().decode(readFileSync(file)); + expect(step).toContain('Block<1>'); + expect(step).toContain('Pin<1>'); + + // Open the pin, make it longer, save, and go back: the assembly takes the change. + await tree.getByRole('treeitem', { name: '(-) Pin<1>' }).click(); + await page.locator('.cm [data-cmd="openPart"]').click(); + await expect(page).toHaveTitle('Pin - Parametric'); + await expect(page.getByRole('tab', { name: 'Features' })).toBeVisible(); + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.store.change('Longer', (d) => { (d.features[1] as { depth: number }).depth = 50; }); + }); + await page.keyboard.press('Meta+s'); + await expect(page).toHaveTitle('Pin - Parametric'); + await page.getByRole('button', { name: `Back to ${asmTitle.replace(' - Parametric', '')}` }).click(); + await expect(page).toHaveTitle(/Assembly\d+ - Parametric$/); + await expect(page.getByRole('region', { name: 'Notifications' })).toContainText('Pin changed since the assembly was saved'); + // The coincident mate holds the new end flush: the pin now starts 40 mm behind the face. + await expect.poll(pinZ).toBeCloseTo(-40, 4); + + // An overlapping second block is found by interference detection. + await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + m.commit('Overlap', (d) => { + d.components.push({ ...d.components[0], id: 'c99', name: 'Block<2>', fixed: false, placement: { p: [20, 0, 0], q: [0, 0, 0, 1] } }); + }, false); + }); + await page.locator('.cm [data-cmd="interference"]').click(); + await expect(page.locator('.pm')).toContainText('1 interference found'); + await expect(page.locator('.pm')).toContainText('Block<1> and Block<2>'); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.renderer.hasPreviewBody)).toBe(false); + expect(errors).toEqual([]); +}); + +test('the assembly workspace, its tree and the Mate panel have no serious accessibility violations', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await makePart(page, 'Block', BLOCK); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await insert(page, 'Block'); + await insert(page, 'Block'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await expect(tree.getByRole('treeitem', { name: '(-) Block<2>' })).toBeVisible(); + // Keyboard: rename from the tree with F2. + await tree.getByRole('treeitem', { name: '(-) Block<2>' }).focus(); + await page.keyboard.press('F2'); + await page.keyboard.type('Cover'); + await page.keyboard.press('Enter'); + await expect(tree.getByRole('treeitem', { name: '(-) Cover' })).toBeVisible(); + await page.locator('.cm [data-cmd="mate"]').click(); + await expect(page.locator('.pm')).toContainText('Select two entities to mate'); + await page.addScriptTag({ path: 'node_modules/axe-core/axe.min.js' }); + const violations = await page.evaluate(async () => { + // @ts-expect-error axe is injected above + const r = await window.axe.run(document, { resultTypes: ['violations'] }); + return r.violations + .filter((v: { impact: string }) => v.impact === 'serious' || v.impact === 'critical') + .map((v: { id: string; nodes: { target: string[] }[] }) => `${v.id}: ${v.nodes.slice(0, 3).map((n) => n.target.join(' ')).join(', ')}`); + }); + expect(violations).toEqual([]); + expect(errors).toEqual([]); +}); + +test('a new explode step never takes the name of one already in the list', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await makePart(page, 'Block', BLOCK); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await insert(page, 'Block'); + await insert(page, 'Block'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await expect(tree.getByRole('treeitem', { name: '(-) Block<2>' })).toBeVisible(); + const addStep = async () => { + await tree.getByRole('treeitem', { name: '(-) Block<2>' }).click(); + await page.locator('.cm [data-cmd="explodedView"]').click(); + await page.locator('.pm').getByRole('button', { name: 'OK' }).click(); + await expect(page.locator('.pm')).toHaveCount(0); + }; + await addStep(); + await addStep(); + await tree.getByRole('treeitem', { name: /^Explode Step1/ }).click(); + await page.keyboard.press('Delete'); + await page.getByRole('dialog', { name: 'Delete' }).getByRole('button', { name: 'Delete' }).click(); + await expect(tree.getByRole('treeitem', { name: /^Explode Step1/ })).toHaveCount(0); + await addStep(); + const names = () => page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.assembly!.doc.explode.map((s) => s.name)); + expect(await names()).toEqual(['Explode Step2', 'Explode Step3']); + expect(errors).toEqual([]); +}); + +test('a hidden component still counts in the mass properties of the assembly', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await makePart(page, 'Block', BLOCK); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await insert(page, 'Block'); + await insert(page, 'Block'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await expect(tree.getByRole('treeitem', { name: '(-) Block<2>' })).toBeVisible(); + const volume = async () => { + void page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.commands.run('massProperties'); }); + const dlg = page.getByRole('dialog', { name: 'Mass Properties' }); + const text = await dlg.getByRole('row').filter({ hasText: 'Volume' }).innerText(); + await dlg.locator('[data-value="ok"]').click(); + await expect(dlg).toHaveCount(0); + return Number(text.replace(/[^\d.]/g, '').replace(/3$/, '')); + }; + // Two 40 × 20 × 10 blocks with a Ø8 hole. + const one = 8000 - Math.PI * 16 * 10; + expect(await volume()).toBeCloseTo(2 * one, 0); + await tree.getByRole('treeitem', { name: '(-) Block<2>' }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Hide' }).click(); + await expect(tree.getByRole('treeitem', { name: /Block<2> \(hidden\)/ })).toBeVisible(); + expect(await volume()).toBeCloseTo(2 * one, 0); + await tree.getByRole('treeitem', { name: /Block<2> \(hidden\)/ }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Suppress' }).click(); + expect(await volume()).toBeCloseTo(one, 0); + expect(errors).toEqual([]); +}); + +test('the mates of a suppressed component show as suppressed in the tree', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await makePart(page, 'Block', BLOCK); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await insert(page, 'Block'); + await insert(page, 'Block'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await expect(tree.getByRole('treeitem', { name: '(-) Block<2>' })).toBeVisible(); + await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const [a, b] = m.doc.components; + m.commit('Lock', (d) => { d.mates.push({ id: 'm90', name: 'Lock1', type: 'lock', a: { comp: a.id }, b: { comp: b.id }, aligned: false, rel: { p: [60, 0, 0], q: [0, 0, 0, 1] } }); }); + }); + const mate = tree.getByRole('treeitem', { name: /^Lock1/ }); + await expect(mate).not.toHaveAttribute('aria-description', /Suppressed/); + await tree.getByRole('treeitem', { name: 'Block<2>', exact: true }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Suppress' }).click(); + await expect(mate).toHaveAttribute('aria-description', /Suppressed/); + await expect(mate).toHaveClass(/suppressed/); + expect(errors).toEqual([]); +}); + +test('Open Part on a component whose part file was deleted opens the copy kept in the assembly', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await makePart(page, 'Block', BLOCK); + await makePart(page, 'Pin', PIN); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await insert(page, 'Block'); + await insert(page, 'Pin'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await expect(tree.getByRole('treeitem', { name: '(-) Pin<1>' })).toBeVisible(); + await page.keyboard.press('Meta+s'); + await expect(page).toHaveTitle(/^Assembly\d+ - Parametric$/); + const name = (await page.title()).replace(' - Parametric', ''); + // The pin's file is deleted from this browser. + await page.evaluate(async () => { + const key = 'parametric:local-parts'; + const index = JSON.parse(localStorage.getItem(key)!) as { id: string; name: string }[]; + const pin = index.find((p) => p.name === 'Pin')!; + localStorage.setItem(key, JSON.stringify(index.filter((p) => p !== pin))); + const dir = await (await navigator.storage.getDirectory()).getDirectoryHandle('parametric-parts'); + await dir.removeEntry(`${pin.id}.parametric`); + }); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('new'); }); + await expect(page).toHaveTitle(/^Part\d+ - Parametric$/); + void page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.commands.run('open'); }); + await page.getByRole('dialog', { name: 'Open' }).getByRole('button', { name: new RegExp(`^${name} This browser`) }).click(); + await expect(page).toHaveTitle(`${name} - Parametric`); + const pin = tree.getByRole('treeitem', { name: '(-) Pin<1>' }); + await expect(pin).toHaveAttribute('aria-description', /part file of Pin was not found/); + await pin.click(); + await page.locator('.cm [data-cmd="openPart"]').click(); + await expect(page).toHaveTitle(/Pin - Parametric$/); + await expect(page.getByRole('region', { name: 'Notifications' })).toContainText('the copy kept in the assembly opened'); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.store.doc.features.length)).toBe(2); + expect(errors).toEqual([]); +}); + +test('dragging a fully defined component turns the view instead of adding an empty undo step', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await makePart(page, 'Block', BLOCK); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await insert(page, 'Block'); + await insert(page, 'Block'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await expect(tree.getByRole('treeitem', { name: '(-) Block<2>' })).toBeVisible(); + await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const [a, b] = m.doc.components; + m.commit('Lock', (d) => { d.mates.push({ id: 'm90', name: 'Lock1', type: 'lock', a: { comp: a.id }, b: { comp: b.id }, aligned: false, rel: { p: [60, 0, 0], q: [0, 0, 0, 1] } }); }); + }); + await expect(tree.getByRole('treeitem', { name: 'Block<2>', exact: true })).toBeVisible(); + const state = () => page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + return { undo: a.store.undoLabel, rot: a.renderer.camera.state().rot }; + }); + const before = await state(); + const p = await facePoint(page, 'Block<2>', 'E1:cap1'); + await page.mouse.move(p.x, p.y); + await page.mouse.down(); + await page.mouse.move(p.x + 60, p.y + 20, { steps: 5 }); + await page.mouse.up(); + const after = await state(); + expect(after.undo).toBe(before.undo); + expect(after.rot).not.toEqual(before.rot); + await expect(page.locator('.statusbar')).toContainText('Block<2> is fully defined'); + expect(errors).toEqual([]); +}); + +test('a mate whose face no longer exists shows as a mate error, not as over defined', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await makePart(page, 'Block', BLOCK); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await insert(page, 'Block'); + await insert(page, 'Block'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await expect(tree.getByRole('treeitem', { name: '(-) Block<2>' })).toBeVisible(); + await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const [a, b] = m.doc.components; + const face = (name: string) => ({ name, sig: { type: 'plane', c: [0, 0, 10] as [number, number, number], n: [0, 0, 1] as [number, number, number], area: 1 } }); + m.commit('Mate', (d) => { d.mates.push({ id: 'm90', name: 'Coincident1', type: 'coincident', a: { comp: a.id, face: face('E7:gone') }, b: { comp: b.id, face: face('E1:cap1') }, aligned: true }); }); + }); + await expect(page.locator('.statusbar')).toContainText('Mate Errors'); + await expect(page.locator('.statusbar')).not.toContainText('Over Defined'); + await expect(tree.getByRole('treeitem', { name: /^Coincident1/ })).toHaveAttribute('aria-description', /no longer exists/); + expect(errors).toEqual([]); +}); + +test('interference detection names a pair it could not check instead of reporting no interference', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await makePart(page, 'Block', BLOCK); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await insert(page, 'Block'); + await insert(page, 'Block'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await expect(tree.getByRole('treeitem', { name: '(-) Block<2>' })).toBeVisible(); + // The worker fails to compute the overlap of the two blocks. + await page.evaluate(() => { + const k = (window as unknown as { __parametric: A }).__parametric.kernel; + const real = k.assembly.bind(k); + k.assembly = (async (req: { op: string }) => (req.op === 'interference' ? [{ a: 0, b: 1, volume: 0, mesh: null, failed: true }] : real(req as never))) as typeof k.assembly; + }); + await page.locator('.cm [data-cmd="interference"]').click(); + await expect(page.locator('.pm')).toContainText('Could not check Block<1> / Block<2>'); + await expect(page.locator('.pm')).not.toContainText('No interference'); + expect(errors).toEqual([]); +}); + +test('an edit solves the mates once, not again in the rebuild after it', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await makePart(page, 'Block', BLOCK); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await insert(page, 'Block'); + await insert(page, 'Block'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await expect(tree.getByRole('treeitem', { name: '(-) Block<2>' })).toBeVisible(); + const r = await page.evaluate(async () => { + const a = (window as unknown as { __parametric: A }).__parametric; + const m = a.assembly!; + await a.whenBuilt(); + let calls = 0; + const solve = m.solveDoc.bind(m); + m.solveDoc = (d) => { calls++; return solve(d); }; + const [b1, b2] = m.doc.components; + m.commit('Lock', (d) => { d.mates.push({ id: 'm90', name: 'Lock1', type: 'lock', a: { comp: b1.id }, b: { comp: b2.id }, aligned: false, rel: { p: [60, 0, 0], q: [0, 0, 0, 1] } }); }); + await a.whenBuilt(); + return { calls, status: m.analysis?.status, defined: m.isDefined(b2.id) }; + }); + expect(r).toEqual({ calls: 1, status: 'full', defined: true }); + expect(errors).toEqual([]); +}); + +test('the properties of an assembly are called Assembly Properties, and of a part Part Properties again', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await expect(page.getByRole('tab', { name: 'Assembly' })).toBeVisible(); + const label = () => page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.commands.get('properties')!.label); + expect(await label()).toBe('Assembly Properties...'); + void page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.commands.run('properties'); }); + const dlg = page.getByRole('dialog', { name: 'Assembly Properties' }); + await expect(dlg).toBeVisible(); + await dlg.locator('[data-value="cancel"]').click(); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('new'); }); + await expect(page.getByRole('tab', { name: 'Features' })).toBeVisible(); + expect(await label()).toBe('Part Properties...'); + void page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.commands.run('properties'); }); + await expect(page.getByRole('dialog', { name: 'Part Properties' })).toBeVisible(); + expect(errors).toEqual([]); +}); + +test('Insert Components refuses the assembly itself, another assembly and a file that is not a part', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await makePart(page, 'Block', BLOCK); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await insert(page, 'Block'); + await expect(page.getByRole('tree', { name: 'Assembly design tree' }).getByRole('treeitem', { name: '(f) Block<1>' })).toBeVisible(); + await page.keyboard.press('Meta+s'); + await page.waitForFunction(() => { const a = (window as unknown as { __parametric: A }).__parametric; return !!a.location && !a.store.dirty; }); + const name = (await page.title()).replace(' - Parametric', ''); + const assemblyText = await page.evaluate(() => JSON.stringify((window as unknown as { __parametric: A }).__parametric.store.doc)); + // File bytes for Playwright, which wants a Node Buffer (the project has no Node types). + const bytes = (text: string) => (globalThis as unknown as { Buffer: { from(s: string): never } }).Buffer.from(text); + const notifications = page.getByRole('region', { name: 'Notifications' }); + const fromDevice = async (file: { name: string; mimeType: string; buffer: never }) => { + void page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.commands.run('insertComponent'); }); + const dlg = page.getByRole('dialog', { name: 'Insert Components' }); + // The open assembly is not offered as a part of itself. + await expect(dlg.getByRole('button', { name: /^Block This browser/ })).toBeVisible(); + await expect(dlg.getByRole('button', { name: new RegExp(`^${name} This browser`) })).toHaveCount(0); + const chooser = page.waitForEvent('filechooser'); + await dlg.getByRole('button', { name: 'From device...' }).click(); + await (await chooser).setFiles(file); + }; + await fromDevice({ name: 'Other.parametric', mimeType: 'application/json', buffer: bytes(assemblyText) }); + await expect(notifications).toContainText('Other.parametric is an assembly'); + await fromDevice({ name: 'notes.json', mimeType: 'application/json', buffer: bytes('{"hello": 1}') }); + await expect(notifications).toContainText('Could not insert the part'); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.assembly!.doc.components.length)).toBe(1); + expect(errors).toEqual([]); +}); + +test('every assembly operation undoes and redoes, also when the keys are pressed in quick succession', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await makePart(page, 'Block', BLOCK); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await insert(page, 'Block'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await expect(tree.getByRole('treeitem', { name: '(f) Block<1>' })).toBeVisible(); + const state = () => page.evaluate(async () => { + const a = (window as unknown as { __parametric: A }).__parametric; + await a.whenBuilt(); + const d = a.assembly!.doc; + const shown = d.components.filter((c) => !c.hidden && !c.suppressed).map((c) => c.id); + return { + doc: JSON.stringify({ c: d.components.map((c) => [c.name, !!c.hidden, !!c.suppressed, c.fixed]), m: d.mates.map((m) => [m.name, !!m.suppressed]), x: d.explode.map((s) => s.name), e: d.exploded }), + // The graphics area shows exactly the shown components. + shownOk: JSON.stringify([...new Set(a.faces.map((f) => f.feature))].sort()) === JSON.stringify([...shown].sort()), + }; + }); + const start = await state(); + const run = (label: string) => page.evaluate((label) => { + const a = (window as unknown as { __parametric: A }).__parametric; + const m = a.assembly!; + const [b1, b2] = m.doc.components; + const face = (name: string) => { const f = m.geometryOf(b1.part)!.faces.find((x) => x.name === name)!; return { name: f.name, sig: { type: f.type, c: f.center, n: f.normal, area: f.area } }; }; + if (label === 'mate') m.commit('Add mate', (d) => { d.mates.push({ id: 'm90', name: 'Coincident1', type: 'coincident', a: { comp: b1.id, face: face('E1:cap1') }, b: { comp: b2.id, face: face('E1:cap0') }, aligned: false }); }); + if (label === 'hide') m.commit('Hide', (d) => { d.components[1].hidden = true; }, false); + if (label === 'show') m.commit('Show', (d) => { delete d.components[1].hidden; }, false); + if (label === 'suppress') m.commit('Suppress', (d) => { d.components[1].suppressed = true; }); + if (label === 'unsuppress') m.commit('Unsuppress', (d) => { delete d.components[1].suppressed; }); + if (label === 'fix') m.commit('Fix', (d) => { d.components[1].fixed = true; }); + if (label === 'float') m.commit('Float', (d) => { d.components[1].fixed = false; }); + if (label === 'rename') m.rename(b2.id, 'Cover'); + if (label === 'explode') m.commit('Add explode step', (d) => { d.explode.push({ id: 'x91', name: 'Explode Step1', comps: [b2.id], dir: [0, 0, 1], distance: 30 }); d.exploded = true; }, false); + if (label === 'collapse') a.commands.run('toggleExplode'); + if (label === 'suppressMate') m.commit('Suppress', (d) => { d.mates[0].suppressed = true; }); + }, label); + await insert(page, 'Block'); + await expect(tree.getByRole('treeitem', { name: '(-) Block<2>' })).toBeVisible(); + const steps = ['mate', 'hide', 'show', 'suppress', 'unsuppress', 'fix', 'float', 'rename', 'explode', 'collapse', 'suppressMate']; + const states = [start, await state()]; + for (const s of steps) { await run(s); states.push(await state()); } + // Delete through the tree (with its confirmation). + await tree.getByRole('treeitem', { name: /^\(-\) Cover/ }).click(); + await page.keyboard.press('Delete'); + await page.getByRole('dialog', { name: 'Delete' }).getByRole('button', { name: 'Delete' }).click(); + await expect(tree.getByRole('treeitem', { name: /Cover/ })).toHaveCount(0); + states.push(await state()); + expect(states.every((s) => s.shownOk)).toBe(true); + // Every operation changed something (Show, Unsuppress and Float return to an earlier state). + expect(states.slice(1).every((s, i) => s.doc !== states[i].doc)).toBe(true); + // One step at a time, back to the start and forward again. + await page.locator('canvas.gl').focus(); + for (let i = states.length - 2; i >= 0; i--) { await page.keyboard.press('Meta+z'); expect(await state(), `undo to ${i}`).toEqual(states[i]); } + for (let i = 1; i < states.length; i++) { await page.keyboard.press('Meta+Shift+z'); expect(await state(), `redo to ${i}`).toEqual(states[i]); } + // All at once, without waiting for the rebuilds in between. + for (let i = 1; i < states.length; i++) await page.keyboard.press('Meta+z'); + expect(await state()).toEqual(states[0]); + for (let i = 1; i < states.length; i++) await page.keyboard.press('Meta+Shift+z'); + expect(await state()).toEqual(states[states.length - 1]); + expect(errors).toEqual([]); +}); + +test('the assembly tree and Mate panel work from the keyboard, the section view cuts the assembly, and the dark theme has no serious accessibility violations', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await makePart(page, 'Block', BLOCK); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await insert(page, 'Block'); + await insert(page, 'Block'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await expect(tree.getByRole('treeitem', { name: '(-) Block<2>' })).toBeVisible(); + await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const [a, b] = m.doc.components; + const face = (name: string) => { const f = m.geometryOf(a.part)!.faces.find((x) => x.name === name)!; return { name: f.name, sig: { type: f.type, c: f.center, n: f.normal, area: f.area } }; }; + m.commit('Mates', (d) => { + d.mates.push({ id: 'm90', name: 'Coincident1', type: 'coincident', a: { comp: a.id, face: face('E1:cap1') }, b: { comp: b.id, face: face('E1:cap0') }, aligned: false }); + d.mates.push({ id: 'm91', name: 'Coincident2', type: 'coincident', a: { comp: a.id, face: { ...face('E1:cap1'), name: 'E9:gone' } }, b: { comp: b.id, face: face('E1:cap0') }, aligned: false }); + }); + }); + // Keyboard: down the rows, collapse and expand the Mates folder, Enter edits a mate. + const row = (name: RegExp) => tree.getByRole('treeitem', { name }); + await row(/Block<2>/).first().focus(); + await page.keyboard.press('ArrowDown'); + await expect(row(/^Mates/)).toBeFocused(); + await expect(row(/^Mates/)).toHaveAttribute('aria-expanded', 'true'); + await page.keyboard.press('ArrowLeft'); + await expect(row(/^Mates/)).toHaveAttribute('aria-expanded', 'false'); + await expect(row(/^Coincident1/)).toHaveCount(0); + await page.keyboard.press('ArrowRight'); + await page.keyboard.press('ArrowRight'); + await expect(row(/^Coincident1/)).toBeFocused(); + await expect(row(/^Coincident2/)).toHaveAttribute('aria-description', /Error: The face it references on Block<1> no longer exists/); + await page.keyboard.press('Enter'); + const pm = page.locator('.pm'); + await expect(pm.getByRole('combobox', { name: 'Mate type' })).toHaveValue('coincident'); + await expect(pm.getByRole('button', { name: 'OK' })).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(pm).toHaveCount(0); + // The section view cuts the components. + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('sectionView'); }); + await expect(page.locator('.pm')).toContainText('Section Plane'); + expect(await page.evaluate(() => !!(window as unknown as { __parametric: A }).__parametric.renderer.section)).toBe(true); + await page.locator('.pm').getByRole('button', { name: 'OK' }).click(); + // Dark theme, with the tree's error and the status bar showing. + await chooseTheme(page, 'Dark'); + await expect(page.locator('.statusbar')).toContainText('Mate Errors'); + await page.addScriptTag({ path: 'node_modules/axe-core/axe.min.js' }); + const violations = await page.evaluate(async () => { + // @ts-expect-error axe is injected above + const r = await window.axe.run(document, { resultTypes: ['violations'] }); + return r.violations + .filter((v: { impact: string }) => v.impact === 'serious' || v.impact === 'critical') + .map((v: { id: string; nodes: { target: string[] }[] }) => `${v.id}: ${v.nodes.slice(0, 3).map((n) => n.target.join(' ')).join(', ')}`); + }); + expect(violations).toEqual([]); + expect(errors).toEqual([]); +}); diff --git a/src/parametric/tests/e2e/assistant.spec.ts b/src/parametric/tests/e2e/assistant.spec.ts index a683d91345..3ad9ec6a11 100644 --- a/src/parametric/tests/e2e/assistant.spec.ts +++ b/src/parametric/tests/e2e/assistant.spec.ts @@ -882,3 +882,27 @@ test('the assistant says drawing views could not be added or arranged when the p await expect(page.locator('.as-step.error').first()).toContainText('no solid to draw'); await expect(page.locator('.as-step.error').nth(1)).toContainText('arrange: there is no solid to draw'); }); + +test('in an assembly the assistant takes no messages, even when its pane opens after the assembly', async ({ page }) => { + await scriptModel(page); + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + // Another pane is shown when the assembly opens: the assistant is not on the page. + await page.getByRole('tab', { name: 'Parts' }).click(); + await page.evaluate(() => { void (window as unknown as { __parametric: import('../../src/app/app').App }).__parametric.commands.run('newAssembly'); }); + await expect.poll(() => page.evaluate(() => !!(window as unknown as { __parametric: import('../../src/app/app').App }).__parametric.assembly)).toBe(true); + await page.getByRole('tab', { name: 'Assistant' }).click(); + await expect(page.locator('.assistant').getByRole('status').filter({ hasText: 'The assistant works on parts' })).toBeVisible(); + expect(await page.locator('.as-composer').evaluate((el) => (el as HTMLElement).inert)).toBe(true); + // The ideas do not send a message either. + const idea = page.locator('.as-idea').first(); + await expect(idea).toBeDisabled(); + await idea.dispatchEvent('click'); + expect(await page.evaluate(() => (window as unknown as { __chatCalls: unknown[] }).__chatCalls.length)).toBe(0); + // A part opened again takes messages. + await page.evaluate(() => { void (window as unknown as { __parametric: import('../../src/app/app').App }).__parametric.commands.run('new'); }); + await expect(page.getByText('The assistant works on parts')).toHaveCount(0); + await expect(page.getByRole('textbox', { name: 'Message the assistant' })).toBeEditable(); + await expect(page.locator('.as-idea').first()).toBeEnabled(); + expect(errors).toEqual([]); +}); diff --git a/src/parametric/tests/e2e/drawing-sources.spec.ts b/src/parametric/tests/e2e/drawing-sources.spec.ts new file mode 100644 index 0000000000..1da31a7b7a --- /dev/null +++ b/src/parametric/tests/e2e/drawing-sources.spec.ts @@ -0,0 +1,437 @@ +// Drawings of assemblies (bill of materials, balloons, sections), of sheet metal parts +// (flat pattern views) and of weldments (cut list tables), saved and opened again. +import { type Page, expect, test } from '@playwright/test'; +import { newBaseFlange } from '../../src/model/sheetmetal'; +import { newStructuralMember } from '../../src/model/weldments'; +import { openApp } from './helpers'; + +type A = import('../../src/app/app').App; +type Ws = { + el: HTMLElement; pan: { x: number; y: number }; zoom: number; + placements: Map; + projectionOf(id: string): { cut?: number[][]; bounds: number[] | null } | undefined; +}; + +const pts = (prefix: string, p: [number, number][]) => [ + ...p.map(([x, y], i) => ({ id: `${prefix}p${i}`, t: 'point', x, y })), + ...p.map((_, i) => ({ id: `${prefix}l${i}`, t: 'line', a: `${prefix}p${i}`, b: `${prefix}p${(i + 1) % p.length}` })), +]; +const extrude = (id: string, sketch: string, depth: number) => ({ id, name: id, type: 'extrude', sketch, cut: false, end: 'blind', depth, flip: false, dir2: null, draft: 0, draftOutward: false, thin: null }); +const BLOCK = [ + { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: [...pts('r', [[0, 0], [40, 0], [40, 20], [0, 20]]), { id: 'hc', t: 'point', x: 10, y: 10 }, { id: 'h', t: 'circle', c: 'hc', r: 4 }], constraints: [] }, + extrude('E1', 'S1', 10), +]; +const PIN = [ + { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: [{ id: 'c', t: 'point', x: 0, y: 0 }, { id: 'k', t: 'circle', c: 'c', r: 4 }], constraints: [] }, + extrude('E1', 'S1', 30), +]; + +async function makePart(page: Page, name: string, features: unknown[], material = false) { + await page.evaluate(async ({ name, features, material }) => { + const a = (window as unknown as { __parametric: A }).__parametric; + await a.commands.get('new')!.run(); + a.store.change('Make part', (d) => { + d.name = name; d.features = features as never; d.nextId = 100; + if (material) d.material = { name: 'Steel', density: 7850 }; + }); + a.commands.run('save'); + }, { name, features, material }); + await expect(page).toHaveTitle(`${name} - Parametric`); +} + +async function insert(page: Page, name: string) { + void page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.commands.run('insertComponent'); }); + const dlg = page.getByRole('dialog', { name: 'Insert Components' }); + await dlg.getByRole('button', { name: new RegExp(`^${name} This browser`) }).click(); + await expect(dlg).toHaveCount(0); +} + +/** Client coordinates of a sheet point (millimetres). */ +async function at(page: Page, x: number, y: number) { + return page.evaluate(([x, y]) => { + const w = (window as unknown as { __parametric: A }).__parametric.drawing as unknown as Ws; + const r = w.el.getBoundingClientRect(); + return { x: r.left + w.pan.x + x * w.zoom, y: r.top + w.pan.y + y * w.zoom }; + }, [x, y]); +} + +async function clickSheet(page: Page, x: number, y: number) { + const p = await at(page, x, y); + await page.mouse.move(p.x, p.y); + await page.mouse.click(p.x, p.y); +} + +const drawing = (page: Page) => page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.store.doc.drawing!); + +async function save(page: Page) { + await page.keyboard.press('Meta+s'); + await expect(page).not.toHaveTitle(/^\*/); + return (await page.title()).replace(' - Parametric', ''); +} + +async function reopen(page: Page, name: string) { + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('new'); }); + await expect(page).toHaveTitle(/^Part\d+ - Parametric$/); + void page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.commands.run('open'); }); + await page.getByRole('dialog', { name: 'Open' }).getByRole('button', { name: new RegExp(`^${name} This browser`) }).click(); + await expect(page).toHaveTitle(`${name} - Parametric`); +} + +async function download(page: Page, name: 'PDF' | 'SVG' | 'DXF') { + const fs = await import('node:fs'); + const dl = page.waitForEvent('download'); + await page.locator('.pm').getByRole('button', { name, exact: true }).click(); + const file = await dl; + return new TextDecoder(name === 'SVG' ? 'utf-8' : 'latin1').decode(fs.readFileSync((await file.path())!)); +} + +test('an assembly drawing: bill of materials, auto and manual balloons, a section, exports, save and reopen', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await makePart(page, 'Block', BLOCK, true); + await makePart(page, 'Pin', PIN); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await insert(page, 'Block'); + await insert(page, 'Pin'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await expect(tree.getByRole('treeitem', { name: '(-) Pin<1>' })).toBeVisible(); + // The pin in the hole, its end flush with the block's front face, then exploded 60 along z. + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const m = a.assembly!; + const [block, pin] = m.doc.components; + const face = (c: string, name: string) => { const g = m.geometryOf(m.component(c)!.part)!; const f = g.faces.find((x) => x.name === name)!; return { name: f.name, sig: { type: f.type, c: f.center, n: f.normal, area: f.area } }; }; + const cyl = (c: string) => { const g = m.geometryOf(m.component(c)!.part)!; const f = g.faces.find((x) => x.type === 'cylinder')!; return { name: f.name, sig: { type: f.type, c: f.center, area: f.area } }; }; + m.commit('Add mates', (d) => { + d.mates.push({ id: 'm90', name: 'Concentric1', type: 'concentric', a: { comp: block.id, face: cyl(block.id) }, b: { comp: pin.id, face: cyl(pin.id) }, aligned: true }); + d.mates.push({ id: 'm91', name: 'Coincident1', type: 'coincident', a: { comp: block.id, face: face(block.id, 'E1:cap1') }, b: { comp: pin.id, face: face(pin.id, 'E1:cap1') }, aligned: true }); + d.explode.push({ id: 'x92', name: 'Explode Step1', comps: [pin.id], dir: [0, 0, 1], distance: 60 }); + }); + }); + await expect(page.locator('.statusbar')).toContainText('Under Defined (1 DOF)'); + + // The status bar's Drawing tab is there in an assembly, and makes the drawing. + await page.getByRole('tab', { name: 'Drawing' }).click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(4, { timeout: 30_000 }); + await expect(page.getByRole('tab', { name: 'Annotation' })).toBeVisible(); + let d = await drawing(page); + expect(d.sheet).toBe('A3'); + expect(d.views.every((v) => v.source === 'assembly')).toBe(true); + expect(d.annotations?.map((a) => a.type)).toEqual(['bom']); + // The bill of materials on the title block. + for (const s of ['ITEM NO.', 'PART NUMBER', 'QTY.', 'Block', 'Pin', 'Steel']) await expect(page.locator('.paper text', { hasText: new RegExp(`^${s.replace('.', '\\.')}$`) })).toHaveCount(1); + // The front view shows the collapsed assembly: the pin's 30 mm run inside the block's depth (10) makes the side view 30 wide. + const sideWidth = () => page.evaluate(() => { + const w = (window as unknown as { __parametric: A }).__parametric.drawing as unknown as Ws; + const b = w.projectionOf('v3')?.bounds; + return b ? b[2] - b[0] : -1; + }); + await expect.poll(sideWidth).toBeCloseTo(30, 3); + + // Auto Balloon on the front view: one balloon per part, numbered from the bill of materials. + await page.getByRole('button', { name: 'Front', exact: true }).click(); + await page.getByRole('tab', { name: 'Annotation' }).click(); + await page.locator('.cm [data-cmd="drawing:autoBalloon"]').click(); + await expect.poll(async () => (await drawing(page)).annotations!.filter((a) => a.type === 'balloon').length).toBe(2); + const items = () => page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + return a.store.doc.drawing!.annotations!.filter((x) => x.type === 'balloon').map((x) => x.type === 'balloon' ? a.drawing.itemOf('assembly', x.ref.edge) : null).sort(); + }); + expect(await items()).toEqual([1, 2]); + // Balloons sit outside the view they number. + const outside = await page.evaluate(() => { + const w = (window as unknown as { __parametric: A }).__parametric.drawing as unknown as Ws & { frames: { id: string; x0: number; y0: number; x1: number; y1: number }[] }; + const f = w.frames.find((x) => x.id === 'v1')!; + const p = w.placements.get('v1')!; + return (window as unknown as { __parametric: A }).__parametric.store.doc.drawing!.annotations!.filter((x) => x.type === 'balloon').every((x) => { + const ax = p.tx + (x as { at: number[] }).at[0] * p.s, ay = p.ty + (x as { at: number[] }).at[1] * p.s; + return ax < f.x0 || ax > f.x1 || ay < f.y0 || ay > f.y1; + }); + }); + expect(outside).toBe(true); + // Running it again adds none (every component has its balloon). + await page.locator('.cm [data-cmd="drawing:autoBalloon"]').click(); + await expect(page.getByText('Every component this view shows has a balloon already.')).toBeVisible(); + + // A balloon by hand: click an edge of the pin in the right view, then where the balloon goes. + const pinEdge = await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const w = a.drawing as unknown as Ws; + const p = w.placements.get('v3')!; + const pin = a.assembly!.doc.components[1].id; + const l = p.prims.filter((q) => q.kind === 'line' && q.edge.startsWith(`${pin}#`)).sort((x, y) => Math.hypot(y.b[0] - y.a[0], y.b[1] - y.a[1]) - Math.hypot(x.b[0] - x.a[0], x.b[1] - x.a[1]))[0]; + const t = 0.8; + return { x: p.tx + (l.a[0] + (l.b[0] - l.a[0]) * t) * p.s, y: p.ty + (l.a[1] + (l.b[1] - l.a[1]) * t) * p.s }; + }); + await page.locator('.cm [data-cmd="drawing:balloon"]').click(); + await clickSheet(page, pinEdge.x, pinEdge.y); + await clickSheet(page, pinEdge.x + 15, pinEdge.y - 25); + await expect.poll(async () => (await drawing(page)).annotations!.filter((a) => a.type === 'balloon' && a.view === 'v3').length).toBe(1); + expect(await items()).toEqual([1, 2, 2]); + await page.keyboard.press('Escape'); + // Its leader ends where the edge was clicked (or the vertex the click snapped to), not at the edge's middle. + const dots = await page.locator('.paper circle[r="0.3"]').evaluateAll((els) => els.map((e) => [Number(e.getAttribute('cx')), Number(e.getAttribute('cy'))])); + const snap = await page.evaluate(() => 7 / ((window as unknown as { __parametric: A }).__parametric.drawing as unknown as Ws).zoom); + expect(dots.some(([x, y]) => Math.hypot(x - pinEdge.x, y - pinEdge.y) <= snap + 0.01)).toBe(true); + + // A section view of the assembly: both components cut and hatched. + await page.getByRole('tab', { name: 'Drafting' }).click(); + await page.getByRole('button', { name: 'Front', exact: true }).click(); + await page.locator('.cm [data-cmd="drawing:section"]').click(); + const front = await page.evaluate(() => { + const w = (window as unknown as { __parametric: A }).__parametric.drawing as unknown as Ws & { frames: { id: string; x0: number; y0: number; x1: number; y1: number }[] }; + return w.frames.find((f) => f.id === 'v1')!; + }); + // Horizontal through the hole's centre (10 mm up the block): it snaps to the hole's centre. + const cy = front.y0 + (front.y1 - front.y0) / 2; + await clickSheet(page, front.x0 + 5, cy); + await clickSheet(page, front.x0 + 5, front.y1 + 75); + await expect.poll(async () => (await drawing(page)).views.length).toBe(5); + const sec = (await drawing(page)).views[4]; + expect(sec.type).toBe('section'); + await expect.poll(() => page.evaluate((id) => ((window as unknown as { __parametric: A }).__parametric.drawing as unknown as Ws).projectionOf(id)?.cut?.length ?? 0, sec.id)).toBeGreaterThanOrEqual(2); + + // An exploded view: the pin 60 mm out of the block. + await page.getByRole('button', { name: 'Right', exact: true }).click(); + await page.getByRole('checkbox', { name: /^Exploded/ }).check(); + await expect.poll(sideWidth).toBeCloseTo(70, 3); + await page.keyboard.press('Meta+z'); + await expect.poll(sideWidth).toBeCloseTo(30, 3); + + // The bill of materials follows the assembly: another pin makes its quantity 2. + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const m = a.assembly!; + const pin = m.doc.components[1]; + m.commit('Insert', (x) => { x.components.push({ ...structuredClone(pin), id: 'c99', name: 'Pin<2>', placement: { p: [60, 0, 0], q: [0, 0, 0, 1] }, fixed: true }); }); + }); + await expect.poll(() => page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const t = a.drawing.tableOf(a.store.doc.drawing!.annotations!.find((x) => x.type === 'bom') as never)!; + return t.rows.map((r) => r.join('|')); + })).toEqual(['1|Block|Steel|1', '2|Pin||2']); + + // PDF, SVG and DXF carry the table and the balloons. + const pdf = await download(page, 'PDF'); + expect(pdf.startsWith('%PDF')).toBe(true); + expect(pdf).toContain('(ITEM NO.) Tj'); + expect(pdf).toContain('(Block) Tj'); + expect(pdf).toContain('(SECTION A-A) Tj'); + const svg = await download(page, 'SVG'); + expect(svg).toContain('>PART NUMBER<'); + expect(svg).toContain('>Pin<'); + const dxf = await download(page, 'DXF'); + expect(dxf).toContain('\nPART NUMBER\n'); + expect(dxf.trimEnd().endsWith('EOF')).toBe(true); + + // Saved with the assembly and opened again. + const before = await drawing(page); + const name = await save(page); + await reopen(page, name); + await expect(tree.getByRole('treeitem', { name: '(f) Block<1>' })).toBeVisible(); + expect(await drawing(page)).toEqual(before); + await page.getByRole('tab', { name: 'Drawing' }).click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(5, { timeout: 30_000 }); + await expect(page.locator('.paper text', { hasText: /^PART NUMBER$/ })).toHaveCount(1); + expect(await items()).toEqual([1, 2, 2]); + // Back to the assembly: its own ribbon tab again. + await page.getByRole('tab', { name: 'Model' }).click(); + await expect(page.getByRole('tab', { name: 'Assembly' })).toHaveAttribute('aria-selected', 'true'); + expect(errors).toEqual([]); +}); + +test('an assembly drawing after a part’s only component is suppressed and brought back shows every view; its bill of materials stays on the title block of another sheet size', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + await makePart(page, 'Block', BLOCK); + await makePart(page, 'Pin', PIN); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await insert(page, 'Block'); + await insert(page, 'Pin'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await expect(tree.getByRole('treeitem', { name: '(-) Pin<1>' })).toBeVisible(); + const suppress = (on: boolean) => page.evaluate((on) => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + m.commit(on ? 'Suppress' : 'Unsuppress', (d) => { d.components[0].suppressed = on || undefined; }); + }, on); + await suppress(true); + await expect(tree.getByRole('treeitem', { name: /Block<1>/ })).toHaveClass(/suppressed/); + await expect(page.locator('.statusbar')).not.toContainText('Building'); + await suppress(false); + await expect(tree.getByRole('treeitem', { name: /Block<1>/ })).not.toHaveClass(/suppressed/); + await page.getByRole('tab', { name: 'Drawing' }).click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(4, { timeout: 30_000 }); + await expect(page.locator('.paper text', { hasText: /^Block$/ })).toHaveCount(1); + await expect(page.getByText('Could not project the views')).toHaveCount(0); + + // Auto Balloon on a view still being projected says to wait, then works once it is drawn. + const back = await page.evaluate(() => { + const ws = (window as unknown as { __parametric: A }).__parametric.drawing; + ws.addView('back'); + const id = ws.doc!.views[ws.doc!.views.length - 1].id; + ws.autoBalloon(id); + return id; + }); + await expect(page.getByText('Wait for the view to finish updating, then use Auto Balloon again.')).toBeVisible(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(5, { timeout: 30_000 }); + await page.evaluate((id) => { (window as unknown as { __parametric: A }).__parametric.drawing.autoBalloon(id); }, back); + await expect.poll(async () => (await drawing(page)).annotations!.filter((a) => a.type === 'balloon' && a.view === back).length).toBe(2); + await page.keyboard.press('Meta+z'); + await page.keyboard.press('Meta+z'); + await expect(page.locator('.paper g[data-view]')).toHaveCount(4); + + // The bill of materials stays on the title block when the sheet changes size or turns. + const bomAt = async () => (await drawing(page)).annotations!.find((a) => a.type === 'bom')!.at; + expect(await bomAt()).toEqual([410, 255]); + await page.getByRole('combobox', { name: 'Sheet size' }).selectOption('A4'); + await expect.poll(bomAt).toEqual([287, 168]); + await page.getByRole('checkbox', { name: 'Landscape' }).uncheck(); + await expect.poll(bomAt).toEqual([200, 255]); + const box = await page.locator('.paper text', { hasText: /^PART NUMBER$/ }).boundingBox(); + const sheet = await page.locator('.paper').boundingBox(); + expect(box!.x + box!.width).toBeLessThan(sheet!.x + sheet!.width); + expect(box!.y + box!.height).toBeLessThan(sheet!.y + sheet!.height); + expect(errors).toEqual([]); +}); + +test('a sheet metal part’s drawing: a flat pattern view with bend lines, notes and its size, saved and reopened', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + const flange = newBaseFlange('B1', 'Base-Flange1', 'S1', 2, 40); + // An L: 50 and 30 long with one 90° bend. + const sketch = { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], entities: [ + { id: 'p0', t: 'point', x: 0, y: 0 }, { id: 'p1', t: 'point', x: 50, y: 0 }, { id: 'p2', t: 'point', x: 50, y: 30 }, + { id: 'l0', t: 'line', a: 'p0', b: 'p1' }, { id: 'l1', t: 'line', a: 'p1', b: 'p2' }, + ] }; + await page.evaluate(({ sketch, flange }) => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.store.change('Make part', (d) => { d.name = 'Bracket'; d.features = [sketch, flange] as never; d.nextId = 100; }); + }, { sketch, flange }); + await expect.poll(() => page.evaluate(() => !!(window as unknown as { __parametric: A }).__parametric.bbox)).toBe(true); + const flat = await page.evaluate(async () => (await (window as unknown as { __parametric: A }).__parametric.kernel.flatPattern(0)).pattern!); + const fw = flat.max[0] - flat.min[0], fh = flat.max[1] - flat.min[1]; + expect(flat.bends).toHaveLength(1); + + await page.getByRole('tab', { name: 'Drawing' }).click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(4, { timeout: 30_000 }); + await page.getByRole('tab', { name: 'Drafting' }).click(); + await page.locator('.cm [data-cmd="drawing:flat"]').click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(5, { timeout: 30_000 }); + const v = (await drawing(page)).views[4]; + expect(v.type).toBe('flat'); + // In free room on the sheet, not on top of another view; a second one too, smaller where there is no room at the sheet's scale. + const overlaps = (id: string) => page.evaluate((id) => { + const fr = ((window as unknown as { __parametric: A }).__parametric.drawing as unknown as { frames: { id: string; x0: number; y0: number; x1: number; y1: number }[] }).frames; + const f = fr.find((q) => q.id === id)!; + return fr.filter((q) => q.id !== id && q.x0 < f.x1 && q.x1 > f.x0 && q.y0 < f.y1 && q.y1 > f.y0).map((q) => q.id); + }, id); + expect(await overlaps(v.id)).toEqual([]); + // It has no hidden lines or tangent edges to show. + await expect(page.getByRole('checkbox', { name: 'Center marks and hole centerlines' })).toBeVisible(); + await expect(page.getByRole('checkbox', { name: 'Show hidden lines' })).toHaveCount(0); + await expect(page.getByRole('checkbox', { name: 'Show tangent edges' })).toHaveCount(0); + await expect(page.getByRole('checkbox', { name: 'Hidden lines in Flat pattern view' })).toBeDisabled(); + await expect(page.getByRole('checkbox', { name: 'Hidden lines in Front view' })).toBeEnabled(); + await expect(page.locator('.paper text', { hasText: /^FLAT PATTERN/ })).toHaveCount(1); + // The bend line, dashed, with its note; the overall size as dimensions. + await expect(page.locator('.paper text', { hasText: /^UP 90° R / })).toHaveCount(1); + expect(await page.locator('.paper line[stroke-dasharray="4 1.5"]').count()).toBe(1); + const fmt = (x: number) => x.toFixed(2); + await expect(page.locator('.paper text', { hasText: new RegExp(`^${fmt(fw).replace('.', '\\.')}$`) })).not.toHaveCount(0); + await expect(page.locator('.paper text', { hasText: new RegExp(`^${fmt(fh).replace('.', '\\.')}$`) })).not.toHaveCount(0); + const bounds = await page.evaluate((id) => ((window as unknown as { __parametric: A }).__parametric.drawing as unknown as Ws).projectionOf(id)!.bounds!, v.id); + expect(bounds[2] - bounds[0]).toBeCloseTo(fw, 4); + expect(bounds[3] - bounds[1]).toBeCloseTo(fh, 4); + // Smart Dimension works on the flat pattern's edges. + const prims = await page.evaluate((id) => ((window as unknown as { __parametric: A }).__parametric.drawing as unknown as Ws).placements.get(id)!.prims.length, v.id); + expect(prims).toBeGreaterThanOrEqual(4); + // Only a detail view can be made from it. + await page.getByRole('button', { name: 'Flat pattern', exact: true }).click(); + await page.locator('.cm [data-cmd="drawing:projected"]').click(); + await expect(page.locator('.pm-msg.info', { hasText: 'Click the view to make it from.' })).toBeVisible(); + await page.keyboard.press('Escape'); + + const svg = await download(page, 'SVG'); + expect(svg).toContain('>FLAT PATTERN<'); + expect(svg).toMatch(/>UP 90° R [\d.]+ { (window as unknown as { __parametric: A }).__parametric.store.change('Deeper', (d) => { (d.features[1] as unknown as { depth: number }).depth = 90; }); }); + await expect.poll(() => page.evaluate(() => ((window as unknown as { __parametric: A }).__parametric.drawing as unknown as Ws).projectionOf('v5')?.bounds ?? null).then((b) => (b ? Math.max(b[2] - b[0], b[3] - b[1]) : 0))).toBeCloseTo(90, 3); + await page.getByRole('tab', { name: 'Drafting' }).click(); + await page.locator('.cm [data-cmd="drawing:flat"]').click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(6, { timeout: 30_000 }); + const v2 = (await drawing(page)).views[5]; + expect(v2.scale).toBeLessThan(1); + await expect.poll(() => overlaps(v2.id)).toEqual([]); + expect(errors).toEqual([]); +}); + +test('a weldment’s drawing: a cut list table that follows the part and balloons on members, saved and reopened', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + const frame = { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], entities: pts('r', [[0, 0], [400, 0], [400, 200], [0, 200]]) }; + const member = newStructuralMember('M1', 'Structural Member1', [['rl0', 'rl1', 'rl2', 'rl3'].map((entity) => ({ sketch: 'S1', entity }))]); + await page.evaluate(({ frame, member }) => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.store.change('Make part', (d) => { d.name = 'Frame'; d.features = [frame, member] as never; d.nextId = 100; }); + }, { frame, member }); + await expect.poll(() => page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.weldments.length)).toBe(4); + await page.getByRole('tab', { name: 'Drawing' }).click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(4, { timeout: 30_000 }); + await page.getByRole('tab', { name: 'Annotation' }).click(); + await page.locator('.cm [data-cmd="drawing:cutList"]').click(); + for (const s of ['ITEM NO.', 'QTY.', 'DESCRIPTION', 'LENGTH (mm)', 'ANGLE1', 'ANGLE2']) await expect(page.locator('.paper text', { hasText: new RegExp(`^${s.replace(/[.()]/g, '\\$&')}$`) })).toHaveCount(1); + const rows = () => page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + return a.drawing.tableOf(a.store.doc.drawing!.annotations!.find((x) => x.type === 'cutList') as never)!.rows; + }); + expect((await rows()).map((r) => [r[0], r[1], r[3], r[4], r[5]])).toEqual([['1', '2', '440.00', '45.00°', '45.00°'], ['2', '2', '240.00', '45.00°', '45.00°']]); + // It follows the model: a longer frame. + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.store.change('Longer', (d) => { + const s = d.features[0] as unknown as { entities: { id: string; x?: number }[] }; + for (const e of s.entities) if (e.id === 'rp1' || e.id === 'rp2') e.x = 500; + }); + }); + await expect.poll(async () => (await rows())[0][3]).toBe('540.00'); + // A balloon on a member takes its cut list item. + const edge = await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const w = a.drawing as unknown as Ws; + const p = w.placements.get('v1')!; + const l = p.prims.filter((q) => q.kind === 'line' && Math.abs(q.a[1] - q.b[1]) < 1e-6).sort((x, y) => Math.abs(y.b[0] - y.a[0]) - Math.abs(x.b[0] - x.a[0]))[0]; + return { x: p.tx + (l.a[0] * 0.7 + l.b[0] * 0.3) * p.s, y: p.ty + l.a[1] * p.s, item: a.drawing.itemOf('part', l.edge) }; + }); + expect(edge.item).not.toBeNull(); + await page.locator('.cm [data-cmd="drawing:balloon"]').click(); + await clickSheet(page, edge.x, edge.y); + await clickSheet(page, edge.x, edge.y - 20); + await expect.poll(async () => (await drawing(page)).annotations!.filter((a) => a.type === 'balloon').length).toBe(1); + await page.keyboard.press('Escape'); + const pdf = await download(page, 'PDF'); + expect(pdf).toContain('(DESCRIPTION) Tj'); + + const name = await save(page); + await reopen(page, name); + await page.getByRole('tab', { name: 'Drawing' }).click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(4, { timeout: 30_000 }); + await expect(page.locator('.paper text', { hasText: /^ANGLE1$/ })).toHaveCount(1); + await expect(page.locator('.paper text', { hasText: /^540\.00$/ })).not.toHaveCount(0); + // A view naming a source this part does not have (an assembly's, from an edited file) shows the part, not nothing. + await page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.drawing.update((d) => { d.views.push({ id: 'v9', kind: 'top', x: 330, y: 60, hidden: false, dims: false, source: 'assembly:exploded' }); }); }); + await expect(page.locator('.paper g[data-view]')).toHaveCount(5, { timeout: 30_000 }); + expect(errors).toEqual([]); +}); diff --git a/src/parametric/tests/e2e/drawing-views.spec.ts b/src/parametric/tests/e2e/drawing-views.spec.ts new file mode 100644 index 0000000000..936d3fd823 --- /dev/null +++ b/src/parametric/tests/e2e/drawing-views.spec.ts @@ -0,0 +1,377 @@ +import { type Page, expect, test } from '@playwright/test'; +import { openApp, waitForFeature } from './helpers'; + +type App = import('../../src/app/app').App; +type Ws = { + el: HTMLElement; pan: { x: number; y: number }; zoom: number; + frames: { id: string; x0: number; y0: number; x1: number; y1: number }[]; + placements: Map; +}; +const ws = (page: Page) => page.evaluate(() => { + const w = (window as unknown as { __parametric: App }).__parametric.drawing as unknown as Ws; + return { frames: w.frames }; +}); + +/** Client coordinates of a sheet point (millimetres). */ +async function at(page: Page, x: number, y: number) { + return page.evaluate(([x, y]) => { + const w = (window as unknown as { __parametric: App }).__parametric.drawing as unknown as Ws; + const r = w.el.getBoundingClientRect(); + return { x: r.left + w.pan.x + x * w.zoom, y: r.top + w.pan.y + y * w.zoom }; + }, [x, y]); +} + +async function clickSheet(page: Page, x: number, y: number) { + const p = await at(page, x, y); + await page.mouse.move(p.x, p.y); + await page.mouse.click(p.x, p.y); +} + +/** Sheet point of a view's prim (its middle, or a circle's rightmost point). */ +async function primPoint(page: Page, view: string, kind: 'line-h' | 'line-v' | 'circle'): Promise<{ x: number; y: number; edge: string }> { + return page.evaluate(([view, kind]) => { + const w = (window as unknown as { __parametric: App }).__parametric.drawing as unknown as Ws; + const p = w.placements.get(view)!; + const T = (q: [number, number]) => ({ x: p.tx + q[0] * p.s, y: p.ty + q[1] * p.s }); + const len = (q: { a: [number, number]; b: [number, number] }) => Math.hypot(q.b[0] - q.a[0], q.b[1] - q.a[1]); + if (kind === 'circle') { + const c = p.prims.filter((q) => q.kind === 'arc' && q.full).sort((a, b) => b.r! - a.r!)[0]; + return { ...T([c.c![0] + c.r!, c.c![1]]), edge: c.edge }; + } + const lines = p.prims.filter((q) => q.kind === 'line' && (kind === 'line-h' ? Math.abs(q.a[1] - q.b[1]) < 1e-6 : Math.abs(q.a[0] - q.b[0]) < 1e-6)); + const l = lines.sort((a, b) => len(b) - len(a))[0]; + // The place along it farthest from every corner and centre (which a click there would pick instead). + const pts = p.prims.flatMap((q) => (q.kind === 'arc' ? [q.c!, q.a, q.b] : [q.a, q.b])); + let best = 0.5, room = -1; + for (let t = 0.05; t < 0.96; t += 0.01) { + const x = l.a[0] + (l.b[0] - l.a[0]) * t, y = l.a[1] + (l.b[1] - l.a[1]) * t; + const m = Math.min(...pts.map((q) => Math.hypot(q[0] - x, q[1] - y))); + if (m > room) { room = m; best = t; } + } + return { ...T([l.a[0] + (l.b[0] - l.a[0]) * best, l.a[1] + (l.b[1] - l.a[1]) * best]), edge: l.edge }; + }, [view, kind] as const); +} + +const drawing = (page: Page) => page.evaluate(() => (window as unknown as { __parametric: App }).__parametric.store.doc.drawing!); + +test('Make Drawing is on the Drafting ribbon tab of the model, and opens the drawing with its own tabs', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await waitForFeature(page, 'Fillet1'); + const tabs = page.getByRole('tablist', { name: 'Command groups' }); + await expect(tabs.getByRole('tab', { name: 'Annotation' })).toBeHidden(); + await tabs.getByRole('tab', { name: 'Drafting' }).click(); + await page.locator('.cm-tools').getByRole('button', { name: 'Make Drawing' }).click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(4, { timeout: 30_000 }); + // In the drawing: Drafting and Annotation, not the model's tabs. + await expect(tabs.getByRole('tab', { name: 'Annotation' })).toBeVisible(); + await expect(tabs.getByRole('tab', { name: 'Features' })).toBeHidden(); + await expect(tabs.getByRole('tab', { name: 'Drafting' })).toHaveAttribute('aria-selected', 'true'); + // The full title block: third angle projection symbol and the sheet number. + await expect(page.locator('.paper text', { hasText: 'THIRD ANGLE' })).toHaveCount(1); + await expect(page.locator('.paper text', { hasText: '1 OF 1' })).toHaveCount(1); + // Center marks on the holes seen end on. + expect(await page.locator('.paper line').count()).toBeGreaterThan(20); + await page.getByRole('tab', { name: 'Model' }).click(); + await expect(tabs.getByRole('tab', { name: 'Features' })).toBeVisible(); + // Also in the File menu and the command search. + await page.getByRole('menubar').getByRole('menuitem', { name: 'File' }).click(); + await expect(page.getByRole('menuitem', { name: 'Make Drawing' })).toBeVisible(); + await page.keyboard.press('Escape'); + expect(errors).toEqual([]); +}); + +test('adds section and detail views, dimensions that follow the model, and exports them', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await waitForFeature(page, 'Fillet1'); + await page.getByRole('tab', { name: 'Drawing' }).click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(4, { timeout: 30_000 }); + // A roomier sheet. + await page.getByRole('combobox', { name: 'Sheet size' }).selectOption('A3'); + const tabs = page.getByRole('tablist', { name: 'Command groups' }); + const front = (await ws(page)).frames.find((f) => f.id === 'v1')!; + // Section: select the front view, Section View, click through the middle, then below the view. + await page.locator('.relations-list').getByRole('button', { name: 'Front', exact: true }).click(); + await page.locator('.cm-tools').getByRole('button', { name: 'Section View' }).click(); + await expect(page.getByRole('status').filter({ hasText: 'horizontal cutting line' }).first()).toBeVisible(); + const cy = (front.y0 + front.y1) / 2 + 0.3; + await clickSheet(page, (front.x0 + front.x1) / 2 + 0.7, cy); + await clickSheet(page, (front.x0 + front.x1) / 2, front.y1 + 25); + await expect(page.locator('.paper g[data-view]')).toHaveCount(5, { timeout: 30_000 }); + await expect(page.locator('.paper text', { hasText: 'SECTION A-A' })).toHaveCount(1); + const d1 = await drawing(page); + const sec = d1.views.find((v) => v.type === 'section')!; + expect(sec).toMatchObject({ parent: 'v1', label: 'A' }); + // Hatched: the section's group holds a hatch path of many short lines. + const hatchPaths = await page.locator(`.paper g[data-view="${sec.id}"] path`).evaluateAll((ps) => ps.map((p) => (p.getAttribute('d') ?? '').split('M').length)); + expect(Math.max(...hatchPaths)).toBeGreaterThan(5); + // Aligned below the front view: same x. + const fr = await ws(page); + const sf = fr.frames.find((f) => f.id === sec.id)!; + expect(sf.y0).toBeGreaterThan(front.y1); + // Dragged sideways it stays aligned (only moves up and down). + const before = sf; + const from = await at(page, (sf.x0 + sf.x1) / 2, (sf.y0 + sf.y1) / 2); + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(from.x + 60, from.y + 20, { steps: 4 }); + await page.mouse.up(); + const after = (await ws(page)).frames.find((f) => f.id === sec.id)!; + expect(after.x0).toBeCloseTo(before.x0, 6); + expect(after.y0).toBeGreaterThan(before.y0); + + // Detail: centre on the front view's corner, a radius, then a place on the sheet. + await page.locator('.relations-list').getByRole('button', { name: 'Front', exact: true }).click(); + await page.locator('.cm-tools').getByRole('button', { name: 'Detail View' }).click(); + await clickSheet(page, front.x0 + 5, front.y1 - 5); + await clickSheet(page, front.x0 + 15, front.y1 - 5); + await clickSheet(page, 330, 230); + await expect(page.locator('.paper g[data-view]')).toHaveCount(6, { timeout: 30_000 }); + await expect(page.locator('.paper text', { hasText: /^DETAIL B/ })).toHaveCount(1); + const det = (await drawing(page)).views.find((v) => v.type === 'detail')!; + expect(det.scale).toBeGreaterThan(d1.scale); + + // Smart Dimension on the Annotation tab: a horizontal edge of the front view. + await tabs.getByRole('tab', { name: 'Annotation' }).click(); + await page.locator('.cm-tools').getByRole('button', { name: 'Smart Dimension' }).click(); + const edge = await primPoint(page, 'v3', 'line-h'); + await clickSheet(page, edge.x, edge.y); + await clickSheet(page, edge.x, edge.y - 12); + const d2 = await drawing(page); + expect(d2.annotations!.filter((a) => a.type === 'dimension')).toHaveLength(1); + const dim = d2.annotations!.find((a) => a.type === 'dimension')!; + expect(dim).toMatchObject({ view: 'v3', kind: 'horizontal' }); + // The right view's horizontal edge is the extrusion's depth (30), and follows a change to 75. + const count = (s: string) => page.locator('.paper text').filter({ hasText: new RegExp(`^${s.replace('.', '\\.')}$`) }).count(); + const n30 = await count('30.00'); + expect(n30).toBeGreaterThan(0); + await page.evaluate(() => (window as unknown as { __parametric: App }).__parametric.store.change('Depth', (doc) => { + const f = doc.features.find((x) => x.id === 'f1'); + if (f?.type === 'extrude') f.depth = 75; + })); + await expect.poll(() => count('75.00'), { timeout: 30_000 }).toBe(n30); + await expect(page.locator('.drw-missing')).toHaveCount(0); + // A diameter on the front view's largest hole. + const hole = await primPoint(page, 'v2', 'circle'); + await clickSheet(page, hole.x, hole.y); + await clickSheet(page, hole.x + 12, hole.y - 10); + await expect(page.locator('.paper text', { hasText: /^Ø/ })).toHaveCount(1); + await page.keyboard.press('Escape'); + + // A note. + await page.locator('.cm-tools').getByRole('button', { name: 'Note' }).click(); + await clickSheet(page, 40, 260); + await page.getByRole('textbox', { name: 'Note text' }).fill('BREAK ALL EDGES'); + await page.getByRole('textbox', { name: 'Note text' }).press('Tab'); + await expect(page.locator('.paper text', { hasText: 'BREAK ALL EDGES' })).toHaveCount(1); + + // Exports carry all of it. + const fs = await import('node:fs'); + const read = async (name: 'PDF' | 'SVG' | 'DXF') => { + const dl = page.waitForEvent('download'); + await page.getByRole('button', { name, exact: true }).click(); + const file = await dl; + expect(file.suggestedFilename()).toBe(`Mounting Bracket.${name.toLowerCase()}`); + return new TextDecoder(name === 'SVG' ? 'utf-8' : 'latin1').decode(fs.readFileSync((await file.path())!)); + }; + const svg = await read('SVG'); + expect(svg).toContain('>SECTION A-A<'); + expect(svg).toMatch(/>DETAIL B/); + expect(svg).toContain('>BREAK ALL EDGES<'); + expect(svg).toMatch(/>\u00d8[\d.]+ (await drawing(page)).views.length).toBe(3); + expect((await drawing(page)).annotations!.some((a) => a.view === 'v1')).toBe(false); + expect(errors).toEqual([]); +}); + +test('Arrange standard views asks before deleting section views and dimensions, and is undone in one step', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await waitForFeature(page, 'Fillet1'); + await page.getByRole('tab', { name: 'Drawing' }).click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(4, { timeout: 30_000 }); + const arrange = page.getByRole('button', { name: 'Arrange standard views' }); + // Only standard views: arranged at once, as before. + await page.evaluate(() => (window as unknown as { __parametric: App }).__parametric.drawing.update((d) => { d.views[0].x += 5; }, 'Move view')); + await arrange.click(); + await expect(page.getByRole('dialog')).toHaveCount(0); + await page.evaluate(() => (window as unknown as { __parametric: App }).__parametric.drawing.update((d) => { + d.views.push({ id: 'v9', kind: 'front', type: 'section', parent: 'v1', line: [-60, 0, 60, 0], label: 'A', x: 60, y: 180, hidden: false, dims: false }); + (d.annotations ??= []).push({ id: 'a1', type: 'dimension', view: 'v1', kind: 'horizontal', refs: [{ edge: 'x', at: 'edge' }], at: [0, 30] }); + }, 'Section view')); + await expect(page.locator('.paper g[data-view]')).toHaveCount(5, { timeout: 30_000 }); + await arrange.click(); + const dialog = page.getByRole('dialog'); + await expect(dialog).toContainText('1 section, detail or other added view and 1 annotation on a view'); + await dialog.getByRole('button', { name: 'Cancel' }).click(); + expect((await drawing(page)).views).toHaveLength(5); + await arrange.click(); + await dialog.getByRole('button', { name: 'Arrange' }).click(); + await expect.poll(async () => (await drawing(page)).views.length).toBe(4); + expect((await drawing(page)).annotations).toEqual([]); + await page.keyboard.press('Meta+Z'); + await expect.poll(async () => (await drawing(page)).views.length).toBe(5); + expect((await drawing(page)).annotations).toHaveLength(1); + expect(errors).toEqual([]); +}); + +test('a drawing opened while the part is still building has its view and annotation commands once the views are laid out', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await expect(page.getByRole('treeitem', { name: 'Fillet1' })).toBeVisible(); + // Straight away, before the first rebuild is done. + await page.getByRole('tab', { name: 'Drawing' }).click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(4, { timeout: 30_000 }); + await expect(page.locator('.cm-tools').getByRole('button', { name: 'Projected View' })).toBeEnabled(); + await expect(page.locator('.cm-tools').getByRole('button', { name: 'Section View' })).toBeEnabled(); + expect(errors).toEqual([]); +}); + +test('a drawing command’s ribbon button is no longer pressed once the view is placed or the command is cancelled', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await waitForFeature(page, 'Fillet1'); + await page.getByRole('tab', { name: 'Drawing' }).click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(4, { timeout: 30_000 }); + const front = (await ws(page)).frames.find((f) => f.id === 'v1')!; + const button = page.locator('.cm-tools').getByRole('button', { name: 'Projected View' }); + await page.locator('.relations-list').getByRole('button', { name: 'Front', exact: true }).click(); + await button.click(); + await expect(button).toHaveAttribute('aria-pressed', 'true'); + await clickSheet(page, (front.x0 + front.x1) / 2, front.y1 + 40); + await expect(page.locator('.paper g[data-view]')).toHaveCount(5, { timeout: 30_000 }); + await expect(button).toHaveAttribute('aria-pressed', 'false'); + await button.click(); + await expect(button).toHaveAttribute('aria-pressed', 'true'); + await page.keyboard.press('Escape'); + await expect(button).toHaveAttribute('aria-pressed', 'false'); + expect(errors).toEqual([]); +}); + +test('a view placed with a click beside the paper is put on the sheet, with an auxiliary view’s arrow on its parent', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await waitForFeature(page, 'Fillet1'); + await page.getByRole('tab', { name: 'Drawing' }).click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(4, { timeout: 30_000 }); + const front = (await ws(page)).frames.find((f) => f.id === 'v1')!; + await page.locator('.relations-list').getByRole('button', { name: 'Front', exact: true }).click(); + await page.locator('.cm-tools').getByRole('button', { name: 'Auxiliary View' }).click(); + const edge = await primPoint(page, 'v1', 'line-v'); + await clickSheet(page, edge.x, edge.y); + // Left of the paper's edge. + await clickSheet(page, -6, (front.y0 + front.y1) / 2); + await expect(page.locator('.paper g[data-view]')).toHaveCount(5, { timeout: 30_000 }); + const aux = (await drawing(page)).views.find((v) => v.type === 'auxiliary')!; + const f = (await ws(page)).frames.find((q) => q.id === aux.id)!; + expect(f.x0).toBeGreaterThanOrEqual(10 - 1e-6); + await expect(page.locator('.paper text', { hasText: /^VIEW A$/ })).toHaveCount(1); + // The letter on the front view, at the arrow's tail. + await expect(page.locator('.paper text', { hasText: /^A$/ })).toHaveCount(1); + // A detail circle clicked out to the left of the paper too. + await page.locator('.relations-list').getByRole('button', { name: 'Front', exact: true }).click(); + await page.locator('.cm-tools').getByRole('button', { name: 'Detail View' }).click(); + await clickSheet(page, front.x0 + 5, front.y1 - 5); + await clickSheet(page, front.x0 + 12, front.y1 - 5); + await clickSheet(page, (front.x0 + front.x1) / 2, 215); + await expect(page.locator('.paper g[data-view]')).toHaveCount(6, { timeout: 30_000 }); + const det = (await drawing(page)).views.find((v) => v.type === 'detail')!; + const fd = (await ws(page)).frames.find((q) => q.id === det.id)!; + expect(fd.y1).toBeLessThanOrEqual(210 - 10 + 1e-6); + expect(errors).toEqual([]); +}); + +test('an annotation selected in the Annotations list moves with the arrow keys', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await waitForFeature(page, 'Fillet1'); + await page.getByRole('tab', { name: 'Drawing' }).click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(4, { timeout: 30_000 }); + await page.evaluate(() => (window as unknown as { __parametric: App }).__parametric.drawing.update((d) => { + d.annotations = [{ id: 'a1', type: 'note', text: 'DEBURR', at: [40, 150] }, { id: 'a2', type: 'note', text: 'IN VIEW', view: 'v1', at: [0, 20] }]; + }, 'Note')); + const at = async (id: string) => ((await drawing(page)).annotations!.find((a) => a.id === id) as { at: [number, number] }).at; + await page.locator('.drw-anno-list').getByRole('button', { name: 'Note: DEBURR', exact: true }).click(); + await page.keyboard.press('ArrowRight'); + await page.keyboard.press('Shift+ArrowDown'); + expect(await at('a1')).toEqual([41, 160]); + // In a view: a millimetre on the sheet, whatever the view's scale. + const s = await page.evaluate(() => ((window as unknown as { __parametric: App }).__parametric.drawing as unknown as Ws).placements.get('v1')!.s); + await page.locator('.drw-anno-list').getByRole('button', { name: 'Note: IN VIEW', exact: true }).click(); + await page.keyboard.press('ArrowLeft'); + const q = await at('a2'); + expect(q[0]).toBeCloseTo(-1 / s, 3); + expect(q[1]).toBe(20); + await page.keyboard.press('Meta+Z'); + await expect.poll(() => at('a2')).toEqual([0, 20]); + expect(errors).toEqual([]); +}); + +test('switching to first angle moves the top view below the front and the right view to its left, in one undo step', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await waitForFeature(page, 'Fillet1'); + await page.getByRole('tab', { name: 'Drawing' }).click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(4, { timeout: 30_000 }); + const centre = (f: { x0: number; y0: number; x1: number; y1: number }) => [(f.x0 + f.x1) / 2, (f.y0 + f.y1) / 2]; + const third = (await ws(page)).frames; + const before = await drawing(page); + await page.getByRole('combobox', { name: 'Projection angle' }).selectOption('first'); + await expect(page.locator('.paper text', { hasText: 'FIRST ANGLE' })).toHaveCount(1); + await expect.poll(async () => (await drawing(page)).views.find((v) => v.id === 'v2')!.y).toBeGreaterThan((await drawing(page)).views[0].y); + const first = (await ws(page)).frames; + const [f3, t3, r3] = ['v1', 'v2', 'v3'].map((id) => centre(third.find((f) => f.id === id)!)); + const [f1, t1, r1] = ['v1', 'v2', 'v3'].map((id) => centre(first.find((f) => f.id === id)!)); + expect(t1[0]).toBeCloseTo(f1[0], 3); + expect(t1[1] - f1[1]).toBeCloseTo(f3[1] - t3[1], 3); + expect(f1[0] - r1[0]).toBeCloseTo(r3[0] - f3[0], 3); + // Still the right view (its caption), now left of the front. + await expect(page.locator('.paper text', { hasText: /^RIGHT$/ })).toHaveCount(1); + for (const f of first) expect(f.x0).toBeGreaterThanOrEqual(10); + await page.keyboard.press('Meta+Z'); + await expect.poll(async () => (await drawing(page)).views).toEqual(before.views); + expect((await drawing(page)).projection ?? 'third').toBe('third'); + expect(errors).toEqual([]); +}); + +test('dragging a view never takes the views aligned with it off the sheet', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await waitForFeature(page, 'Fillet1'); + await page.getByRole('tab', { name: 'Drawing' }).click(); + await expect(page.locator('.paper g[data-view]')).toHaveCount(4, { timeout: 30_000 }); + // A projected view of the top view, far right on the sheet. + await page.evaluate(() => (window as unknown as { __parametric: App }).__parametric.drawing.update((d) => { + d.views.push({ id: 'v9', kind: 'right', type: 'projected', parent: 'v2', side: 'right', x: 255, y: d.views[1].y, hidden: false, dims: false }); + }, 'Projected view')); + await expect(page.locator('.paper g[data-view]')).toHaveCount(5, { timeout: 30_000 }); + const top = (await ws(page)).frames.find((f) => f.id === 'v2')!; + const from = await at(page, (top.x0 + top.x1) / 2, (top.y0 + top.y1) / 2); + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(from.x + 400, from.y, { steps: 6 }); + await page.mouse.up(); + const f = (await ws(page)).frames; + expect(f.find((q) => q.id === 'v9')!.x1).toBeLessThanOrEqual(297 - 10 + 1e-6); + // It moved as far as that allows, and the two still line up. + expect(f.find((q) => q.id === 'v2')!.x0).toBeGreaterThan(top.x0 + 1); + expect(f.find((q) => q.id === 'v9')!.y0).toBeCloseTo(f.find((q) => q.id === 'v2')!.y0, 6); + // From the keyboard too. + for (let i = 0; i < 5; i++) await page.keyboard.press('Shift+ArrowRight'); + expect((await ws(page)).frames.find((q) => q.id === 'v9')!.x1).toBeLessThanOrEqual(297 - 10 + 1e-6); + expect(errors).toEqual([]); +}); diff --git a/src/parametric/tests/e2e/kernel.spec.ts b/src/parametric/tests/e2e/kernel.spec.ts index e74dd3bb9f..4f61e429f2 100644 --- a/src/parametric/tests/e2e/kernel.spec.ts +++ b/src/parametric/tests/e2e/kernel.spec.ts @@ -291,3 +291,66 @@ test('an imported SolidWorks part rebuilds on a worker replaced for its memory a await expect(page.locator('.ti.error')).toHaveCount(0); expect(errors).toEqual([]); }); + +test('a geometry worker an assembly grew too big is replaced quietly, with the components where they were', async ({ page }) => { + type App = import('../../src/app/app').App; + type K = { worker: unknown; recycleBytes: number; baseHeap: number; generation: number }; + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: App }).__parametric?.kernelReady); + const pts = (p: [number, number][]) => [ + ...p.map(([x, y], i) => ({ id: `p${i}`, t: 'point', x, y })), + ...p.map((_, i) => ({ id: `l${i}`, t: 'line', a: `p${i}`, b: `p${(i + 1) % p.length}` })), + ]; + // Two 40 × 20 × 10 blocks, both kept in the browser, inserted into a new assembly overlapping. + for (const name of ['BlockA', 'BlockB']) { + await page.evaluate(async ({ name, entities }) => { + const a = (window as unknown as { __parametric: App }).__parametric; + await a.commands.get('new')!.run(); + a.store.change('Make part', (d) => { + d.name = name; + d.features = [ + { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities, constraints: [] }, + { id: 'E1', name: 'E1', type: 'extrude', sketch: 'S1', cut: false, end: 'blind', depth: 10, flip: false, dir2: null, draft: 0, draftOutward: false, thin: null }, + ] as never; + d.nextId = 100; + }); + a.commands.run('save'); + }, { name, entities: pts([[0, 0], [40, 0], [40, 20], [0, 20]]) }); + await expect(page).toHaveTitle(`${name} - Parametric`); + } + await page.evaluate(() => { void (window as unknown as { __parametric: App }).__parametric.commands.run('newAssembly'); }); + for (const name of ['BlockA', 'BlockB']) { + void page.evaluate(() => { (window as unknown as { __parametric: App }).__parametric.commands.run('insertComponent'); }); + const dlg = page.getByRole('dialog', { name: 'Insert Components' }); + await dlg.getByRole('button', { name: new RegExp(`^${name} This browser`) }).click(); + await expect(dlg).toHaveCount(0); + } + await expect(page.getByRole('tree', { name: 'Assembly design tree' }).getByRole('treeitem', { name: /BlockB<1>/ })).toBeVisible(); + const run = () => page.evaluate(async () => { + const app = (window as unknown as { __parametric: App }).__parametric; + await app.whenBuilt(); + const n = app.assembly!.doc.components.length; + const mass = await app.kernel.assembly<{ volume: number }>({ op: 'mass', densities: Array(n).fill(1000) }); + const hits = await app.kernel.assembly<{ volume: number }[]>({ op: 'interference' }); + return { volume: Math.round(mass.volume), pairs: hits.length, overlap: Math.round(hits.reduce((s, h) => s + h.volume, 0)) }; + }); + const before = await run(); + expect(before.volume).toBeGreaterThan(0); + const replaced = await page.evaluate(async () => { + const app = (window as unknown as { __parametric: App }).__parametric; + const k = app.kernel as unknown as K; + const first = k.worker, generation = k.generation; + // As if interference checks had grown the kernel far past what the assembly needs. + k.recycleBytes = 1; + k.baseHeap = 1; + await app.kernel.assembly({ op: 'interference' }); + return { replaced: k.worker !== first, sameGeneration: k.generation === generation }; + }); + expect(replaced).toEqual({ replaced: true, sameGeneration: true }); + // The new worker has the parts, placed: mass and interference come out as before. + await page.evaluate(() => { const k = (window as unknown as { __parametric: App }).__parametric.kernel as unknown as K; k.recycleBytes = 2 ** 30; }); + expect(await run()).toEqual(before); + await expect(page.locator('.toast', { hasText: 'restarted' })).toHaveCount(0); + expect(errors).toEqual([]); +}); diff --git a/src/parametric/tests/e2e/mobile.spec.ts b/src/parametric/tests/e2e/mobile.spec.ts index 2553539bee..5bc8a45b13 100644 --- a/src/parametric/tests/e2e/mobile.spec.ts +++ b/src/parametric/tests/e2e/mobile.spec.ts @@ -363,3 +363,54 @@ test('a small phone shows the equations table, Delete buttons included, without await expect(dialog.getByRole('button', { name: 'Delete Var1' })).toBeVisible(); expect(await dialog.locator('.dialog-body').evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true); }); + +test('the ribbon tab strip fades the edge with more tabs past it, also after the drawing hid and showed tabs', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await waitForFeature(page, 'Fillet1'); + const strip = page.locator('.cm-tabs'); + await expect(strip).toHaveClass(/more-end/); + // The View tab, last, scrolls into view: the fade moves to the start. + await page.locator('.cm-tabs [data-tab="view"]').click(); + await expect(strip).toHaveClass(/more-start/); + await expect(strip).not.toHaveClass(/more-end/); + // The drawing has two tabs, which fit: no fade. + type A = { __parametric: import('../../src/app/app').App }; + await page.evaluate(() => (window as unknown as A).__parametric.openDrawing()); + await expect(page.locator('.cm-tabs [data-tab="annotation"]')).toBeVisible(); + await expect(strip).not.toHaveClass(/more-(start|end)/); + // Back in the model all the tabs are there again, past the edge. + await page.evaluate(() => (window as unknown as A).__parametric.closeDrawing()); + await expect(page.locator('.cm-tabs [data-tab="features"]')).toBeVisible(); + await expect(strip).toHaveClass(/more-end/); + expect(errors).toEqual([]); +}); + +test('ribbon labels of the sheet metal, surfaces, weldments, drawing and assembly tabs break only between words', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await waitForFeature(page, 'Fillet1'); + type A = { __parametric: import('../../src/app/app').App }; + // Words of a label wider than the label: a word broken across lines. + const broken = () => page.evaluate(() => { + const c = document.createElement('canvas').getContext('2d')!; + return [...document.querySelectorAll('.cm-tools .tool .lbl')].flatMap((l) => { + const cs = getComputedStyle(l); + c.font = `${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`; + const tool = l.closest('.tool')!.getBoundingClientRect(), r = l.getBoundingClientRect(); + const words = l.textContent!.split(/\s+/).filter((w) => c.measureText(w).width > l.clientWidth + 0.5); + return words.length || r.left < tool.left - 0.5 || r.right > tool.right + 0.5 ? [l.textContent!] : []; + }); + }); + for (const tab of ['sheetMetal', 'surfaces', 'weldments', 'drawing']) { + await page.evaluate((t) => (window as unknown as A).__parametric.setRibbonTab(t), tab); + expect(await broken(), tab).toEqual([]); + } + await page.evaluate(() => { void (window as unknown as A).__parametric.commands.run('newAssembly'); }); + await expect(page.locator('.cm-tools [data-cmd="insertComponent"]')).toBeVisible(); + expect(await broken(), 'assembly').toEqual([]); + await page.evaluate(() => (window as unknown as A).__parametric.openDrawing()); + await page.evaluate(() => (window as unknown as A).__parametric.setRibbonTab('annotation')); + expect(await broken(), 'annotation').toEqual([]); + expect(errors).toEqual([]); +}); diff --git a/src/parametric/tests/e2e/sheetmetal.spec.ts b/src/parametric/tests/e2e/sheetmetal.spec.ts new file mode 100644 index 0000000000..d43e392a43 --- /dev/null +++ b/src/parametric/tests/e2e/sheetmetal.spec.ts @@ -0,0 +1,237 @@ +import { readFileSync } from 'node:fs'; +import { expect, test } from '@playwright/test'; +import { openApp, waitForFeature } from './helpers'; + +type App = import('../../src/app/app').App; +type W = { __parametric: App }; + +test.describe('sheet metal', () => { + test('builds a bracket from an L profile with an edge flange, flattens it and exports DXF', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + // An open L profile on the Front plane: 60 along X, then 40 up. + await page.evaluate(async () => { + const a = (window as unknown as W).__parametric; + const pts = [[0, 0], [60, 0], [60, 40]]; + a.store.change('Profile', (d) => { + d.features.push({ id: 's1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], entities: [ + ...pts.map(([x, y], i) => ({ id: `p${i}`, t: 'point' as const, x, y })), + { id: 'l0', t: 'line' as const, a: 'p0', b: 'p1' }, { id: 'l1', t: 'line' as const, a: 'p1', b: 'p2' }, + ] }); + }); + await a.whenBuilt(); + }); + await waitForFeature(page, 'Sketch1'); + await page.getByRole('treeitem', { name: 'Sketch1' }).click(); + await page.getByRole('tab', { name: 'Sheet Metal' }).click(); + await page.locator('[data-cmd="baseFlange"]').first().click(); + await expect(page.getByRole('heading', { name: 'Base Flange' })).toBeVisible(); + await page.getByRole('textbox', { name: 'Thickness' }).fill('2'); + await page.getByRole('textbox', { name: 'Thickness' }).press('Tab'); + await page.getByRole('textbox', { name: 'Bend radius' }).fill('1'); + await page.getByRole('textbox', { name: 'Bend radius' }).press('Tab'); + await page.getByRole('textbox', { name: 'Depth' }).fill('30'); + await page.getByRole('textbox', { name: 'Depth' }).press('Tab'); + await page.getByRole('button', { name: 'OK', exact: true }).first().click(); + await waitForFeature(page, 'Base-Flange1'); + await expect(page.getByRole('treeitem', { name: 'Sheet-Metal' })).toBeVisible(); + + // An edge flange on the free end of the vertical leg (its top edge, along the depth). + const edge = await page.evaluate(async () => { + const a = (window as unknown as W).__parametric; + await a.whenBuilt(); + const i = a.edges.findIndex((e) => e.type === 'line' && Math.abs(e.mid[1] - 40) < 1e-6 && Math.abs(e.mid[0] - 60) < 1e-6); + a.selection.set([{ kind: 'edge', index: i, name: a.edges[i].name }]); + return i; + }); + expect(edge).toBeGreaterThanOrEqual(0); + await page.locator('[data-cmd="edgeFlange"]').first().click(); + await expect(page.getByRole('heading', { name: 'Edge Flange' })).toBeVisible(); + await page.getByRole('textbox', { name: 'Length' }).fill('15'); + await page.getByRole('textbox', { name: 'Length' }).press('Tab'); + await page.getByRole('button', { name: 'OK', exact: true }).first().click(); + await waitForFeature(page, 'Edge-Flange1'); + await expect(page.locator('.ti.error')).toHaveCount(0); + + // The flat pattern: two bends, the size from the bend allowance formula. + await page.locator('[data-cmd="flatten"]').first().click(); + await expect(page.getByRole('heading', { name: 'Flat Pattern' })).toBeVisible(); + const notes = page.locator('.flat-bends tbody tr'); + await expect(notes).toHaveCount(2); + await expect(notes.first()).toContainText('UP 90° R 1'); + const ba = (Math.PI / 2) * (1 + 0.5 * 2); + // Base: 60 + 40 - 2 * 3 (outer virtual sharps); the flange, measured from its outer sharp, is 15 - 3 long and its bend cuts the leg back by 3. + const length = 60 + 40 - 2 * 3 + ba - 3 + ba + (15 - 3); + await expect(page.locator('.flat-size')).toContainText(`${length.toFixed(2)} mm × 30.00 mm`); + const flatShown = await page.evaluate(() => { const a = (window as unknown as W).__parametric; return a.bbox!.max[2] - a.bbox!.min[2]; }); + expect(flatShown).toBeCloseTo(30, 3); + + const download = page.waitForEvent('download'); + await page.getByRole('button', { name: 'Export DXF...' }).click(); + const file = await download; + expect(file.suggestedFilename()).toMatch(/\.dxf$/); + const dxf = new TextDecoder().decode(readFileSync((await file.path())!)); + expect(dxf).toContain('ENTITIES'); + expect(dxf.match(/\nBEND_UP\n/g)?.length).toBeGreaterThanOrEqual(2); + expect(dxf).toContain('OUTLINE'); + + // Leaving the flat pattern shows the folded part again; the tree's Flat-Pattern row opens it. + await page.getByRole('button', { name: 'Exit Flat Pattern' }).click(); + await expect(page.getByRole('heading', { name: 'Flat Pattern' })).toHaveCount(0); + const folded = await page.evaluate(() => { const a = (window as unknown as W).__parametric; return a.bbox!.max[1] - a.bbox!.min[1]; }); + expect(folded).toBeCloseTo(40, 3); + await page.getByRole('treeitem', { name: 'Flat-Pattern' }).click(); + await expect(page.getByRole('heading', { name: 'Flat Pattern' })).toBeVisible(); + await page.getByRole('button', { name: 'Exit Flat Pattern' }).click(); + + // Thicker sheet from the Sheet-Metal row rebuilds everything. + const volume = () => page.evaluate(async () => { const a = (window as unknown as W).__parametric; await a.whenBuilt(); return (await a.kernel.massProperties())!.volume; }); + const thin = await volume(); + await page.getByRole('treeitem', { name: 'Sheet-Metal' }).click(); + await page.getByRole('textbox', { name: 'Thickness' }).fill('3'); + await page.getByRole('textbox', { name: 'Thickness' }).press('Tab'); + await page.getByRole('button', { name: 'OK', exact: true }).first().click(); + await expect.poll(volume).toBeGreaterThan(thin * 1.4); + await expect(page.locator('.ti.error')).toHaveCount(0); + expect(errors).toEqual([]); + }); +}); + +test('an inch part gets sheet metal defaults that read as plain inch values', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + // A small open L profile (0.5 x 0.75 in) in an IPS part. + await page.evaluate(async () => { + const a = (window as unknown as W).__parametric; + const pts = [[0, 0], [12.7, 0], [12.7, 19.05]]; + a.store.change('Profile', (d) => { + d.units = 'IPS'; + d.features.push({ id: 's1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], entities: [ + ...pts.map(([x, y], i) => ({ id: `p${i}`, t: 'point' as const, x, y })), + { id: 'l0', t: 'line' as const, a: 'p0', b: 'p1' }, { id: 'l1', t: 'line' as const, a: 'p1', b: 'p2' }, + ] }); + }); + await a.whenBuilt(); + }); + await waitForFeature(page, 'Sketch1'); + await page.getByRole('treeitem', { name: 'Sketch1' }).click(); + await page.getByRole('tab', { name: 'Sheet Metal' }).click(); + await page.locator('[data-cmd="baseFlange"]').first().click(); + await expect(page.getByRole('heading', { name: 'Base Flange' })).toBeVisible(); + await expect(page.getByRole('textbox', { name: 'Thickness' })).toHaveValue('0.06'); + await expect(page.getByRole('textbox', { name: 'Bend radius' })).toHaveValue('0.06'); + await expect(page.getByRole('textbox', { name: 'Depth' })).toHaveValue('0.5'); + await page.getByRole('button', { name: 'OK', exact: true }).first().click(); + await waitForFeature(page, 'Base-Flange1'); + await page.evaluate(async () => { + const a = (window as unknown as W).__parametric; + await a.whenBuilt(); + const i = a.edges.findIndex((e) => e.type === 'line' && Math.abs(e.mid[1] - 19.05) < 1e-6); + a.selection.set([{ kind: 'edge', index: i, name: a.edges[i].name }]); + }); + await page.locator('[data-cmd="edgeFlange"]').first().click(); + await expect(page.getByRole('heading', { name: 'Edge Flange' })).toBeVisible(); + await expect(page.getByRole('textbox', { name: 'Length' })).toHaveValue('0.6'); + await page.getByRole('button', { name: 'Cancel' }).first().click(); + await page.locator('[data-cmd="hem"]').first().click(); + await expect(page.getByRole('heading', { name: 'Hem' })).toBeVisible(); + await expect(page.getByRole('textbox', { name: 'Length' })).toHaveValue('0.3'); + expect(errors).toEqual([]); +}); + +test('the Sheet-Metal and Flat-Pattern rows open from the keyboard and have a menu', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.evaluate(async () => { + const a = (window as unknown as W).__parametric; + const pts = [[0, 0], [40, 0], [40, 30], [0, 30]]; + a.store.change('Plate', (d) => { + d.features.push({ id: 's1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], entities: [ + ...pts.map(([x, y], i) => ({ id: `p${i}`, t: 'point' as const, x, y })), + ...pts.map((_, i) => ({ id: `l${i}`, t: 'line' as const, a: `p${i}`, b: `p${(i + 1) % 4}` })), + ] }); + d.features.push({ id: 'b1', name: 'Base-Flange1', type: 'baseFlange', sketch: 's1', flip: false, mid: false, depth: 10, depthEnd: 'blind', depthFlip: false, + sm: { thickness: 1, radius: 1, allowance: 'kFactor', kFactor: 0.5, allowanceValue: 1.5, relief: 'rectangular', reliefRatio: 0.5 } }); + }); + await a.whenBuilt(); + }); + await waitForFeature(page, 'Base-Flange1'); + await page.getByRole('treeitem', { name: 'Sheet-Metal' }).focus(); + await page.keyboard.press('Enter'); + await expect(page.getByRole('heading', { name: 'Base-Flange1' })).toBeVisible(); + // A bend deduction says how bends over 90 degrees are flattened. + const note = page.getByText('Bends over 90° use the K-factor this deduction gives a 90° bend.'); + await expect(note).toBeHidden(); + await page.getByRole('combobox', { name: 'Bend allowance type' }).selectOption('bendDeduction'); + await expect(note).toBeVisible(); + await page.getByRole('combobox', { name: 'Bend allowance type' }).selectOption('kFactor'); + await expect(note).toBeHidden(); + await page.keyboard.press('Escape'); + await expect(page.getByRole('heading', { name: 'Base-Flange1' })).toHaveCount(0); + await page.evaluate(() => (window as unknown as W).__parametric.whenBuilt()); + await page.getByRole('treeitem', { name: 'Flat-Pattern' }).focus(); + await expect(page.getByRole('treeitem', { name: 'Flat-Pattern' })).toBeFocused(); + await page.keyboard.press('Enter'); + await expect(page.getByRole('heading', { name: 'Flat Pattern' })).toBeVisible(); + await page.getByRole('button', { name: 'Exit Flat Pattern' }).click(); + await page.getByRole('treeitem', { name: 'Flat-Pattern' }).focus(); + await page.keyboard.press('Shift+F10'); + await expect(page.getByRole('menuitem', { name: /Flatten/ })).toBeVisible(); + await expect(page.getByRole('menuitem', { name: /Export DXF/ })).toBeVisible(); + await page.keyboard.press('Escape'); + expect(errors).toEqual([]); +}); + +test('with the first Base Flange suppressed, the Sheet-Metal row edits the one that makes the part', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + const thickness = (sm: number) => ({ thickness: sm, radius: 1, allowance: 'kFactor' as const, kFactor: 0.5, allowanceValue: 1.5, relief: 'rectangular' as const, reliefRatio: 0.5 }); + await page.evaluate(async (sm) => { + const a = (window as unknown as W).__parametric; + const plate = (id: string, plane: 'front' | 'top', w: number) => ({ id, name: id === 's1' ? 'Sketch1' : 'Sketch2', type: 'sketch' as const, plane: { kind: 'base' as const, plane }, constraints: [], entities: [ + ...[[0, 0], [w, 0], [w, 30], [0, 30]].map(([x, y], i) => ({ id: `${id}p${i}`, t: 'point' as const, x, y })), + ...[0, 1, 2, 3].map((i) => ({ id: `${id}l${i}`, t: 'line' as const, a: `${id}p${i}`, b: `${id}p${(i + 1) % 4}` })), + ] }); + const flange = (id: string, name: string, sketch: string, t: number) => ({ id, name, type: 'baseFlange' as const, sketch, flip: false, mid: false, depth: 10, depthEnd: 'blind' as const, depthFlip: false, sm: { ...sm, thickness: t } }); + a.store.change('Plates', (d) => { + d.features.push(plate('s1', 'front', 40), flange('b1', 'Base-Flange1', 's1', 1), plate('s2', 'top', 50), flange('b2', 'Base-Flange2', 's2', 2)); + (d.features[1] as { suppressed?: boolean }).suppressed = true; + }); + await a.whenBuilt(); + }, thickness(1)); + await waitForFeature(page, 'Base-Flange2'); + const volume = () => page.evaluate(async () => { const a = (window as unknown as W).__parametric; await a.whenBuilt(); return (await a.kernel.massProperties())!.volume; }); + expect(await volume()).toBeCloseTo(50 * 30 * 2, 3); + await page.getByRole('treeitem', { name: 'Sheet-Metal' }).click(); + await expect(page.getByRole('heading', { name: 'Base-Flange2' })).toBeVisible(); + await page.getByRole('textbox', { name: 'Thickness' }).fill('3'); + await page.getByRole('textbox', { name: 'Thickness' }).press('Tab'); + await page.getByRole('button', { name: 'OK', exact: true }).first().click(); + await expect.poll(volume).toBeCloseTo(50 * 30 * 3, 3); + expect(errors).toEqual([]); +}); + +test('an edge flange from a hand-edited file whose edge has no signature opens for editing', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.evaluate(async () => { + const a = (window as unknown as W).__parametric; + const pts = [[0, 0], [40, 0], [40, 30], [0, 30]]; + a.store.change('Plate', (d) => { + d.features.push({ id: 's1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], entities: [ + ...pts.map(([x, y], i) => ({ id: `p${i}`, t: 'point' as const, x, y })), + ...pts.map((_, i) => ({ id: `l${i}`, t: 'line' as const, a: `p${i}`, b: `p${(i + 1) % 4}` })), + ] }); + d.features.push({ id: 'b1', name: 'Base-Flange1', type: 'baseFlange', sketch: 's1', flip: false, mid: false, depth: 10, depthEnd: 'blind', depthFlip: false, + sm: { thickness: 1, radius: 1, allowance: 'kFactor', kFactor: 0.5, allowanceValue: 1.5, relief: 'rectangular', reliefRatio: 0.5 } }); + d.features.push({ id: 'e1', name: 'Edge-Flange1', type: 'edgeFlange', edges: [{ name: 'b1:gone' } as never], length: 10, angle: 90, lengthRef: 'outer', position: 'materialInside', flip: false, offset1: 0, offset2: 0 }); + }); + await a.whenBuilt(); + }); + await waitForFeature(page, 'Edge-Flange1'); + await expect(page.getByRole('treeitem', { name: 'Edge-Flange1' })).toHaveAttribute('aria-description', /no longer exists/); + await page.getByRole('treeitem', { name: 'Edge-Flange1' }).dblclick(); + await expect(page.getByRole('heading', { name: 'Edge-Flange1' })).toBeVisible(); + await expect(page.getByText('Edge', { exact: true })).toBeVisible(); + expect(errors).toEqual([]); +}); diff --git a/src/parametric/tests/e2e/surfaces.spec.ts b/src/parametric/tests/e2e/surfaces.spec.ts new file mode 100644 index 0000000000..06e4adc6aa --- /dev/null +++ b/src/parametric/tests/e2e/surfaces.spec.ts @@ -0,0 +1,303 @@ +import { type Page, expect, test } from '@playwright/test'; +import { canvasCenter, openApp, waitForFeature } from './helpers'; + +type A = import('../../src/app/app').App; +const app = (page: Page) => page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric); + +/** A new part with two profile sketches 20 mm apart: a straight line below and an arch above. */ +async function loftProfiles(page: Page) { + await page.getByRole('button', { name: /New part/ }).click(); + await app(page); + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.store.change('Profiles', (d) => { + d.features.push( + { id: 'pl', name: 'Plane1', type: 'plane', ref: { kind: 'base', plane: 'top' }, offset: 20, flip: false }, + { + id: 's1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'top' }, constraints: [], + entities: [{ id: 'a', t: 'point', x: 0, y: 0 }, { id: 'b', t: 'point', x: 40, y: 0 }, { id: 'l', t: 'line', a: 'a', b: 'b' }], + }, + { + id: 's2', name: 'Sketch2', type: 'sketch', plane: { kind: 'feature', id: 'pl' }, constraints: [], + entities: [{ id: 'c', t: 'point', x: 0, y: 0 }, { id: 'd', t: 'point', x: 20, y: -8 }, { id: 'e', t: 'point', x: 40, y: 0 }, { id: 'sp', t: 'spline', pts: ['c', 'd', 'e'] }], + }, + ); + }); + }); + await waitForFeature(page, 'Sketch2'); +} + +/** Surface bodies shown, by the feature that made them, with their total area. */ +const surfaceBodies = async (page: Page) => { + const faces = await surfaceFaces(page); + const out: Record = {}; + for (const f of faces) out[f.body!] = (out[f.body!] ?? 0) + f.area; + return out; +}; +const bodyCount = async (page: Page) => Object.keys(await surfaceBodies(page)).length; +const surfaceFaces = (page: Page) => page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.faces.filter((f) => f.body).map((f) => ({ name: f.name, area: f.area, body: f.body }))); + +test.describe('surfaces', () => { + test('lofts a surface, thickens it, and saves and reopens the part', async ({ page }) => { + const errors = await openApp(page); + await loftProfiles(page); + await page.getByRole('tab', { name: 'Surfaces' }).click(); + // Both profiles selected in the tree fill the loft's profiles. + await page.getByRole('treeitem', { name: 'Sketch1' }).click(); + await page.getByRole('treeitem', { name: 'Sketch2' }).click({ modifiers: ['ControlOrMeta'] }); + await page.locator('[data-cmd="surfaceLoft"]').first().click(); + await expect(page.getByRole('heading', { name: 'Lofted Surface' })).toBeVisible(); + await expect(page.locator('.pm .selbox').first()).toContainText('Sketch2'); + await page.getByRole('button', { name: 'OK', exact: true }).first().click(); + await waitForFeature(page, 'Surface-Loft1'); + await expect(page.locator('.ti.error')).toHaveCount(0); + await expect.poll(() => bodyCount(page)).toBe(1); + const [[body, area]] = Object.entries(await surfaceBodies(page)); + const face = { area }; + expect(body).toBe((await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.store.doc.features.at(-1)!.id))); + // A surface only: no solid volume, and its area stated apart. + const before = await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.kernel.massProperties()); + expect(before!.solid).toBe(false); + expect(before!.surfaceArea).toBeCloseTo(face.area, 3); + + // Thicken it by 2 mm: picked in the graphics area, the surface fills the panel. + await page.locator('[data-cmd="thicken"]').first().click(); + await expect(page.getByRole('heading', { name: 'Thicken' })).toBeVisible(); + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const i = a.faces.findIndex((f) => f.body); + a.panel!.onPick({ kind: 'face', index: i, name: a.faces[i].name }, false); + }); + await expect(page.locator('.pm .selbox').first()).toContainText('Surface-Loft1'); + const thickness = page.getByRole('textbox', { name: /Thickness/ }); + await thickness.fill('2'); + await thickness.press('Enter'); + await page.getByRole('button', { name: 'OK', exact: true }).first().click(); + await waitForFeature(page, 'Thicken1'); + await expect(page.locator('.ti.error')).toHaveCount(0); + await expect.poll(() => bodyCount(page)).toBe(0); + const mp = await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.kernel.massProperties()); + expect(mp!.solid).toBe(true); + expect(mp!.volume / (face.area * 2)).toBeGreaterThan(0.9); + expect(mp!.volume / (face.area * 2)).toBeLessThan(1.1); + + // Save to this browser and open it again. + await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.commands.run('save')); + await expect(page).toHaveTitle('Part1 - Parametric'); + await page.evaluate(async () => { await (window as unknown as { __parametric: A }).__parametric.commands.get('new')!.run(); }); + await expect(page.getByRole('treeitem', { name: 'Thicken1' })).toHaveCount(0); + await page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.commands.run('open'); }); + await page.getByRole('dialog', { name: 'Open' }).getByRole('button', { name: /^Part1 This browser/ }).click(); + await waitForFeature(page, 'Thicken1'); + await expect(page.getByRole('treeitem', { name: 'Surface-Loft1' })).toBeVisible(); + await expect(page.locator('.ti.error')).toHaveCount(0); + const types = await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.store.doc.features.map((f) => f.type)); + expect(types).toEqual(['plane', 'sketch', 'sketch', 'surfaceLoft', 'thicken']); + await expect.poll(async () => (await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.kernel.massProperties()))!.volume).toBeCloseTo(mp!.volume, 3); + expect(errors).toEqual([]); + }); + + test('hides and shows a surface from the design tree, and rolls back past it', async ({ page }) => { + const errors = await openApp(page); + await loftProfiles(page); + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.store.change('Loft', (d) => { d.features.push({ id: 'f9', name: 'Surface-Loft1', type: 'surfaceLoft', profiles: ['s1', 's2'], ruled: false }); }); + }); + await waitForFeature(page, 'Surface-Loft1'); + await expect.poll(() => bodyCount(page)).toBe(1); + await page.getByRole('treeitem', { name: 'Surface-Loft1' }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Hide' }).click(); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.store.feature('f9')!.hidden)).toBe(true); + // A hidden surface cannot be picked in the graphics area. + await page.getByRole('button', { name: /Zoom to Fit/ }).first().click().catch(() => {}); + const { x, y } = await canvasCenter(page); + await page.mouse.click(x, y); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.selection.items.filter((i) => i.kind === 'face').length)).toBe(0); + await page.getByRole('treeitem', { name: 'Surface-Loft1' }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Show' }).click(); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.store.feature('f9')!.hidden)).toBe(false); + // Suppressed, the surface is gone; unsuppressed it is back. + await page.getByRole('treeitem', { name: 'Surface-Loft1' }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Suppress' }).click(); + await expect.poll(() => bodyCount(page)).toBe(0); + await page.getByRole('treeitem', { name: 'Surface-Loft1' }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Unsuppress' }).click(); + await expect.poll(() => bodyCount(page)).toBe(1); + expect(errors).toEqual([]); + }); + + test('says STL leaves surfaces out: refused for surfaces only, a warning beside a solid', async ({ page }) => { + const errors = await openApp(page); + await loftProfiles(page); + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.store.change('Loft', (d) => { d.features.push({ id: 'f9', name: 'Surface-Loft1', type: 'surfaceLoft', profiles: ['s1', 's2'], ruled: false }); }); + }); + await waitForFeature(page, 'Surface-Loft1'); + await expect.poll(() => bodyCount(page)).toBe(1); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('exportStl'); }); + await expect(page.locator('.toast').filter({ hasText: 'STL files hold solids only' })).toBeVisible(); + // A block beside the surface: the STL has the block, and the toast says the surface is not in it. + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.store.change('Block', (d) => { + d.features.push( + { id: 's3', name: 'Sketch3', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], + entities: [{ id: 'p0', t: 'point', x: 60, y: 0 }, { id: 'p1', t: 'point', x: 70, y: 0 }, { id: 'p2', t: 'point', x: 70, y: 10 }, { id: 'p3', t: 'point', x: 60, y: 10 }, + { id: 'k0', t: 'line', a: 'p0', b: 'p1' }, { id: 'k1', t: 'line', a: 'p1', b: 'p2' }, { id: 'k2', t: 'line', a: 'p2', b: 'p3' }, { id: 'k3', t: 'line', a: 'p3', b: 'p0' }] }, + { id: 'e1', name: 'Boss-Extrude1', type: 'extrude', sketch: 's3', cut: false, end: 'blind', depth: 5, flip: false, dir2: null, draft: 0, draftOutward: false, thin: null }, + ); + }); + }); + await waitForFeature(page, 'Boss-Extrude1'); + await expect.poll(() => page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.faces.filter((f) => !f.body).length)).toBe(6); + const download = page.waitForEvent('download'); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('exportStl'); }); + expect((await download).suggestedFilename()).toMatch(/\.stl$/); + await expect(page.locator('.toast').filter({ hasText: 'surface bodies are not in the STL file' })).toBeVisible(); + expect(errors).toEqual([]); + }); + + test('a new extrude does not default to the sketch a surface already uses', async ({ page }) => { + const errors = await openApp(page); + await loftProfiles(page); + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.store.change('Loft', (d) => { d.features.push({ id: 'f9', name: 'Surface-Loft1', type: 'surfaceLoft', profiles: ['s1', 's2'], ruled: false }); }); + }); + await waitForFeature(page, 'Surface-Loft1'); + await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.selection.set([])); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('extrude'); }); + await expect(page.getByRole('heading', { name: 'Extrude' })).toBeVisible(); + await expect(page.locator('.pm .selbox').first()).not.toContainText('Sketch2'); + await page.keyboard.press('Escape'); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('surfaceExtrude'); }); + await expect(page.getByRole('heading', { name: 'Extruded Surface' })).toBeVisible(); + await expect(page.locator('.pm .selbox').first()).not.toContainText('Sketch2'); + await page.keyboard.press('Escape'); + expect(errors).toEqual([]); + }); + + test('lists the trim pieces to keep in the part\'s units', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await app(page); + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.store.change('Trim', (d) => { + d.units = 'IPS'; + d.features.push( + { id: 'pl', name: 'Plane1', type: 'plane', ref: { kind: 'base', plane: 'right' }, offset: 25.4, flip: false }, + { id: 's1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], + entities: [{ id: 'p0', t: 'point', x: 0, y: 0 }, { id: 'p1', t: 'point', x: 101.6, y: 0 }, { id: 'p2', t: 'point', x: 101.6, y: 101.6 }, { id: 'p3', t: 'point', x: 0, y: 101.6 }, + { id: 'k0', t: 'line', a: 'p0', b: 'p1' }, { id: 'k1', t: 'line', a: 'p1', b: 'p2' }, { id: 'k2', t: 'line', a: 'p2', b: 'p3' }, { id: 'k3', t: 'line', a: 'p3', b: 'p0' }] }, + { id: 'f1', name: 'Surface-Plane1', type: 'surfacePlanar', sketch: 's1', edges: [] }, + { id: 't1', name: 'Surface-Trim1', type: 'surfaceTrim', faces: [{ name: 'f1:p0', sig: { type: 'plane', c: [50.8, 50.8, 0], area: 10322.56 } }], + tool: { kind: 'plane', plane: { kind: 'feature', id: 'pl' } }, keep: [[12.7, 50.8, 0]], flip: false }, + ); + }); + }); + await waitForFeature(page, 'Surface-Trim1'); + await expect(page.locator('.ti.error')).toHaveCount(0); + await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.editFeature('t1')); + await expect(page.getByRole('heading', { name: 'Surface-Trim1' })).toBeVisible(); + await expect(page.locator('.pm')).toContainText('Piece at 0.50, 2.00, 0.00 in'); + await page.keyboard.press('Escape'); + expect(errors).toEqual([]); + }); + + test('leaves a hidden surface out of the drawing, and shows it again', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await app(page); + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.store.change('Part', (d) => { + d.features.push( + { id: 's1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], + entities: [{ id: 'p0', t: 'point', x: 0, y: 0 }, { id: 'p1', t: 'point', x: 20, y: 0 }, { id: 'p2', t: 'point', x: 20, y: 20 }, { id: 'p3', t: 'point', x: 0, y: 20 }, + { id: 'k0', t: 'line', a: 'p0', b: 'p1' }, { id: 'k1', t: 'line', a: 'p1', b: 'p2' }, { id: 'k2', t: 'line', a: 'p2', b: 'p3' }, { id: 'k3', t: 'line', a: 'p3', b: 'p0' }] }, + { id: 'e1', name: 'Boss-Extrude1', type: 'extrude', sketch: 's1', cut: false, end: 'blind', depth: 10, flip: false, dir2: null, draft: 0, draftOutward: false, thin: null }, + { id: 's2', name: 'Sketch2', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], + entities: [{ id: 'q0', t: 'point', x: 40, y: -10 }, { id: 'q1', t: 'point', x: 60, y: 30 }, { id: 'q2', t: 'line', a: 'q0', b: 'q1' }] }, + { id: 'f1', name: 'Surface-Extrude1', type: 'surfaceExtrude', sketch: 's2', end: 'blind', depth: 15, flip: false, dir2: null }, + ); + }); + }); + await waitForFeature(page, 'Surface-Extrude1'); + await expect.poll(() => bodyCount(page)).toBe(1); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('openDrawing'); }); + await expect(page.locator('.paper g[data-view]').first()).toBeAttached({ timeout: 30_000 }); + // How much the views draw: the length of their path data. + const drawn = () => page.evaluate(() => [...document.querySelectorAll('.paper g[data-view] path')].reduce((n, p) => n + (p.getAttribute('d')?.length ?? 0), 0)); + await expect.poll(drawn).toBeGreaterThan(0); + await page.waitForTimeout(500); + const shown = await drawn(); + await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.toggleHidden(['f1'], true)); + await expect.poll(drawn).toBeLessThan(shown); + await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.toggleHidden(['f1'], false)); + await expect.poll(drawn).toBe(shown); + expect(errors).toEqual([]); + }); + + test('Hide on a surface a trim replaced hides the trimmed surface; a thickened one cannot be hidden', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await app(page); + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.store.change('Trim', (d) => { + d.features.push( + { id: 'pl', name: 'Plane1', type: 'plane', ref: { kind: 'base', plane: 'right' }, offset: 10, flip: false }, + { id: 's1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], + entities: [{ id: 'p0', t: 'point', x: 0, y: 0 }, { id: 'p1', t: 'point', x: 40, y: 0 }, { id: 'p2', t: 'point', x: 40, y: 40 }, { id: 'p3', t: 'point', x: 0, y: 40 }, + { id: 'k0', t: 'line', a: 'p0', b: 'p1' }, { id: 'k1', t: 'line', a: 'p1', b: 'p2' }, { id: 'k2', t: 'line', a: 'p2', b: 'p3' }, { id: 'k3', t: 'line', a: 'p3', b: 'p0' }] }, + { id: 'f1', name: 'Surface-Plane1', type: 'surfacePlanar', sketch: 's1', edges: [] }, + { id: 't1', name: 'Surface-Trim1', type: 'surfaceTrim', faces: [{ name: 'f1:p0', sig: { type: 'plane', c: [20, 20, 0], area: 1600 } }], + tool: { kind: 'plane', plane: { kind: 'feature', id: 'pl' } }, keep: [], flip: false }, + ); + }); + }); + await waitForFeature(page, 'Surface-Trim1'); + await expect.poll(() => bodyCount(page)).toBe(1); + await page.getByRole('treeitem', { name: 'Surface-Plane1' }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Hide Surface-Trim1' }).click(); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.store.feature('t1')!.hidden)).toBe(true); + await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.toggleHidden(['t1'], false)); + // Thickened, no surface body shows it: the item says why it cannot hide anything. + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.store.change('Thicken', (d) => { d.features.push({ id: 'th', name: 'Thicken1', type: 'thicken', faces: [{ name: 'f1:p0', sig: { type: 'plane', c: [25, 20, 0], area: 1200 } }], thickness: 2, side: 'front', cut: false }); }); + }); + await waitForFeature(page, 'Thicken1'); + await expect.poll(() => bodyCount(page)).toBe(0); + await page.getByRole('treeitem', { name: 'Surface-Plane1' }).click({ button: 'right' }); + await expect(page.getByRole('menuitem', { name: /Hide \(a later feature used this surface\)/ })).toBeDisabled(); + await page.keyboard.press('Escape'); + expect(errors).toEqual([]); + }); + + test('shows a clear error when knit surfaces do not close a volume', async ({ page }) => { + const errors = await openApp(page); + await loftProfiles(page); + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.store.change('Loft', (d) => { d.features.push({ id: 'f9', name: 'Surface-Loft1', type: 'surfaceLoft', profiles: ['s1', 's2'], ruled: false }); }); + }); + await waitForFeature(page, 'Surface-Loft1'); + await expect.poll(() => bodyCount(page)).toBe(1); + await page.getByRole('tab', { name: 'Surfaces' }).click(); + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const i = a.faces.findIndex((f) => f.body); + a.selection.set([{ kind: 'face', index: i, name: a.faces[i].name }]); + }); + await page.locator('[data-cmd="surfaceKnit"]').first().click(); + await expect(page.getByRole('heading', { name: 'Knit Surface' })).toBeVisible(); + await page.getByText('Create solid').click(); + await expect(page.locator('.pm-msg.error')).toContainText('do not form a closed volume'); + await page.keyboard.press('Escape'); + expect(errors).toEqual([]); + }); +}); diff --git a/src/parametric/tests/e2e/weldments.spec.ts b/src/parametric/tests/e2e/weldments.spec.ts new file mode 100644 index 0000000000..697b6bd8e5 --- /dev/null +++ b/src/parametric/tests/e2e/weldments.spec.ts @@ -0,0 +1,306 @@ +import { readFileSync } from 'node:fs'; +import { expect, test } from '@playwright/test'; +import { canvasCenter, openApp, waitForFeature } from './helpers'; + +type App = import('../../src/app/app').App; +type W = { __parametric: App }; + +test.describe('weldments', () => { + test('sketches a rectangle, adds a structural member, shows the cut list, saves and reopens', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.getByRole('treeitem', { name: 'Front Plane' }).click(); + await page.getByRole('tab', { name: 'Sketch' }).click(); + await page.locator('[data-cmd="sketch"]').first().click(); + await expect(page.locator('.view-label')).toHaveText('Front'); + const { x, y } = await canvasCenter(page); + await page.locator('[data-cmd="tool:rectangle"]').click(); + await page.mouse.click(x - 150, y + 80); + await page.mouse.click(x + 150, y - 80); + await page.keyboard.press('Escape'); + // Structural Member finishes the sketch, whose lines become the first group. + await page.getByRole('tab', { name: 'Weldments' }).click(); + await page.locator('[data-cmd="structuralMember"]').first().click(); + await expect(page.getByRole('heading', { name: 'Structural Member' })).toBeVisible(); + const group = page.getByRole('group', { name: 'Group 1' }); + await expect(group.locator('.item')).toHaveCount(4); + await expect(group).toContainText('Line 1 of Sketch1'); + // Profile from the library. + await page.getByLabel('Type', { exact: true }).selectOption('rectTube'); + await page.getByLabel('Size', { exact: true }).selectOption('60x40x3'); + await page.getByRole('button', { name: 'OK', exact: true }).first().click(); + await waitForFeature(page, 'Structural Member1'); + await expect(page.locator('.ti.error')).toHaveCount(0); + // The first member of a part without a material makes it steel. + await expect(page.getByRole('treeitem', { name: 'Plain Carbon Steel' })).toBeVisible(); + await expect(page.getByRole('treeitem', { name: 'Cut list (4)' })).toBeVisible(); + + // The cut list: two pairs of mitered members. + await page.getByRole('treeitem', { name: 'Cut list (4)' }).click(); + const dialog = page.getByRole('dialog', { name: 'Cut List' }); + await expect(dialog).toBeVisible(); + const rows = dialog.locator('tbody tr'); + await expect(rows).toHaveCount(2); + await expect(rows.nth(0)).toContainText('RECT TUBE 60 x 40 x 3'); + await expect(rows.nth(0).locator('td').nth(1)).toHaveText('2'); + await expect(rows.nth(0).locator('td').nth(4)).toHaveText('45.00'); + const csv = page.waitForEvent('download'); + await dialog.getByRole('button', { name: 'Export CSV' }).click(); + const file = await csv; + expect(file.suggestedFilename()).toBe('Part1 cut list.csv'); + await dialog.getByRole('button', { name: 'Close', exact: true }).last().click(); + await expect(dialog).toHaveCount(0); + + // Editing a sketch line moves its member (the cut list follows). + const lengths = () => page.evaluate(() => (window as unknown as W).__parametric.weldments.map((m) => Math.round(m.length)).sort((a, b) => a - b)); + const before = await lengths(); + expect(before).toHaveLength(4); + await page.evaluate(() => { + const a = (window as unknown as W).__parametric; + a.store.change('Wider', (d) => { + const sk = d.features.find((f) => f.type === 'sketch')!; + if (sk.type !== 'sketch') return; + for (const e of sk.entities) if (e.t === 'point' && e.x > 0) e.x += 100; + }); + }); + await expect.poll(lengths).not.toEqual(before); + + // Save in this browser, reload, and open it again. + await page.evaluate(() => (window as unknown as W).__parametric.commands.run('save')); + await expect(page).toHaveTitle('Part1 - Parametric'); + const after = await lengths(); + await page.reload(); + await page.waitForFunction(() => (window as unknown as { __parametric?: App }).__parametric); + void page.evaluate(() => (window as unknown as W).__parametric.commands.run('open')); + await page.getByRole('dialog', { name: 'Open' }).getByRole('button', { name: /^Part1 This browser/ }).click(); + await waitForFeature(page, 'Structural Member1'); + await expect(page.getByRole('treeitem', { name: 'Cut list (4)' })).toBeVisible(); + await expect(page.locator('.ti.error')).toHaveCount(0); + expect(await lengths()).toEqual(after); + // Editing the feature opens its panel with its groups. + await page.getByRole('treeitem', { name: 'Structural Member1' }).dblclick(); + await expect(page.getByRole('heading', { name: 'Structural Member1' })).toBeVisible(); + await expect(page.getByRole('group', { name: 'Group 1' }).locator('.item')).toHaveCount(4); + await expect(page.getByLabel('Size', { exact: true })).toHaveValue('60x40x3'); + await page.keyboard.press('Escape'); + expect(errors).toEqual([]); + }); + + test('picks sketch lines in the graphics area, adds groups and warns before deleting the sketch', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.evaluate(() => { + const a = (window as unknown as W).__parametric; + a.store.change('Layout', (d) => { + const pts: [number, number][] = [[-60, 0], [60, 0], [0, -80]]; + d.features.push({ id: 's1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], entities: [ + ...pts.map(([x, y], i) => ({ id: `p${i}`, t: 'point' as const, x, y })), + { id: 'top', t: 'line', a: 'p0', b: 'p1' }, { id: 'post', t: 'line', a: 'p2', b: 'p0' }, + ] }); + }); + a.viewport.setView('front', false); + a.viewport.zoomToFit(false); + }); + await page.getByRole('tab', { name: 'Weldments' }).click(); + await page.locator('[data-cmd="structuralMember"]').first().click(); + await expect(page.getByRole('heading', { name: 'Structural Member' })).toBeVisible(); + // Click the top line in the graphics area. + const pos = (p: [number, number, number]) => page.evaluate((q) => { + const a = (window as unknown as W).__parametric; + const s = a.renderer.camera.project(q); + const r = a.renderer.canvas.getBoundingClientRect(); + return { x: r.left + s[0], y: r.top + s[1] }; + }, p); + const top = await pos([20, 0, 0]); + await page.mouse.click(top.x, top.y); + await expect(page.getByRole('group', { name: 'Group 1' }).locator('.item')).toHaveCount(1); + await page.getByRole('button', { name: 'New Group' }).click(); + const post = await pos([-30, -40, 0]); + await page.mouse.click(post.x, post.y); + await expect(page.getByRole('group', { name: 'Group 2' }).locator('.item')).toHaveCount(1); + await page.getByRole('button', { name: 'OK', exact: true }).first().click(); + await waitForFeature(page, 'Structural Member1'); + await expect(page.locator('.ti.error')).toHaveCount(0); + await expect(page.getByRole('treeitem', { name: 'Cut list (2)' })).toBeVisible(); + // Deleting the layout sketch names the member that needs it. + await page.getByRole('treeitem', { name: 'Sketch1' }).click(); + await page.keyboard.press('Delete'); + await expect(page.getByRole('dialog', { name: 'Delete' })).toContainText('Structural Member1'); + await page.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); + }); + + test('exports the cut list as CSV after the latest edit is rebuilt, and says why it is empty', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.evaluate(() => { + const a = (window as unknown as W).__parametric; + a.store.change('Layout', (d) => { + d.features.push({ id: 's1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], entities: [ + { id: 'a', t: 'point', x: 0, y: 0 }, { id: 'b', t: 'point', x: 0, y: 100 }, { id: 'l', t: 'line', a: 'a', b: 'b' }, + ] }); + d.features.push({ + id: 'm1', name: 'Structural Member1', type: 'structuralMember', standard: 'iso', profile: 'squareTube', size: '40x40x3', + groups: [{ segments: [{ sketch: 's1', entity: 'l' }] }], rotation: 0, mirror: false, pierce: 'centroid', corner: 'miter', gap: 0, trimGroups: true, gap2: 0, + }); + }); + }); + await expect(page.getByRole('treeitem', { name: 'Cut list (1)' })).toBeVisible(); + const download = page.waitForEvent('download'); + // Lengthen the post and export at once: the file has the new length. + await page.evaluate(() => { + const a = (window as unknown as W).__parametric; + a.store.change('Longer', (d) => { + const sk = d.features.find((f) => f.id === 's1'); + if (sk?.type === 'sketch') for (const e of sk.entities) if (e.id === 'b' && e.t === 'point') e.y = 300; + }); + void a.commands.run('cutListCsv'); + }); + const csv = new TextDecoder().decode(readFileSync((await (await download).path())!)).split('\r\n'); + expect(csv[1]).toMatch(/^1,1,SQ TUBE 40 x 40 x 3,300\.00,/); + // With its line deleted the member fails: the Cut list row says why it lists nothing. + await page.evaluate(() => { + const a = (window as unknown as W).__parametric; + a.store.change('Delete line', (d) => { + const sk = d.features.find((f) => f.id === 's1'); + if (sk?.type === 'sketch') sk.entities = sk.entities.filter((e) => e.id !== 'l'); + }); + }); + await page.getByRole('treeitem', { name: 'Cut list (0)' }).click(); + await expect(page.getByRole('region', { name: 'Notifications' })).toContainText('No structural members are built'); + expect(errors).toEqual([]); + }); + + test('the cut list mass leaves out a hole drilled through a member later', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.evaluate(() => { + const a = (window as unknown as W).__parametric; + a.store.change('Layout', (d) => { + d.features.push({ id: 's1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], entities: [ + { id: 'a', t: 'point', x: 0, y: 0 }, { id: 'b', t: 'point', x: 0, y: 100 }, { id: 'l', t: 'line', a: 'a', b: 'b' }, + ] }); + d.features.push({ + id: 'm1', name: 'Structural Member1', type: 'structuralMember', standard: 'iso', profile: 'squareTube', size: '40x40x3', + groups: [{ segments: [{ sketch: 's1', entity: 'l' }] }], rotation: 0, mirror: false, pierce: 'centroid', corner: 'miter', gap: 0, trimGroups: true, gap2: 0, + }); + // A 20 mm hole through one wall of the post. + d.features.push({ id: 's2', name: 'Sketch2', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], entities: [ + { id: 'c', t: 'point', x: 0, y: 50 }, { id: 'o', t: 'circle', c: 'c', r: 10 }, + ] }); + d.features.push({ id: 'h1', name: 'Cut-Extrude1', type: 'extrude', sketch: 's2', cut: true, end: 'throughAll', depth: 10, flip: false, dir2: null, draft: 0, draftOutward: false, thin: null }); + }); + }); + await waitForFeature(page, 'Cut-Extrude1'); + await expect(page.locator('.ti.error')).toHaveCount(0); + await page.getByRole('treeitem', { name: 'Cut list (1)' }).click(); + const dialog = page.getByRole('dialog', { name: 'Cut List' }); + // 4208 mm³ of tube less 942 mm³ of hole, at 1000 kg/m³ (no material). + await expect(dialog.locator('tbody tr').first().locator('td').nth(7)).toHaveText('41.14'); + await dialog.getByRole('button', { name: 'Close', exact: true }).last().click(); + expect(errors).toEqual([]); + }); + + test('a line picked together with its sketch makes one member', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.evaluate(() => { + const a = (window as unknown as W).__parametric; + a.store.change('Layout', (d) => { + d.features.push({ id: 's1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], entities: [ + { id: 'a', t: 'point', x: 0, y: 0 }, { id: 'b', t: 'point', x: 0, y: 100 }, { id: 'c', t: 'point', x: 100, y: 100 }, + { id: 'l', t: 'line', a: 'a', b: 'b' }, { id: 'm', t: 'line', a: 'b', b: 'c' }, + ] }); + }); + a.selection.set([{ kind: 'skseg', sketch: 's1', entity: 'l' }, { kind: 'feature', id: 's1' }]); + void a.commands.run('structuralMember'); + }); + await expect(page.getByRole('group', { name: 'Group 1' }).locator('.item')).toHaveText(['Line 1 of Sketch1', 'Line 2 of Sketch1']); + await page.getByRole('button', { name: 'OK', exact: true }).first().click(); + await waitForFeature(page, 'Structural Member1'); + await expect(page.getByRole('treeitem', { name: 'Cut list (2)' })).toBeVisible(); + await expect(page.locator('.ti.error')).toHaveCount(0); + expect(errors).toEqual([]); + }); + + test('trims a post to a plate face, caps it and adds a fillet bead from the Weldments tab', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.evaluate(() => { + const a = (window as unknown as W).__parametric; + a.store.change('Layout', (d) => { + const sq = [[-100, -100], [100, -100], [100, 100], [-100, 100]]; + d.features.push({ id: 's1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'top' }, constraints: [], entities: [ + ...sq.map(([x, y], i) => ({ id: `p${i}`, t: 'point' as const, x, y })), + ...sq.map((_, i) => ({ id: `l${i}`, t: 'line' as const, a: `p${i}`, b: `p${(i + 1) % 4}` })), + ] }); + d.features.push({ id: 'f2', name: 'Extrude1', type: 'extrude', sketch: 's1', cut: false, end: 'blind', depth: 10, flip: false, dir2: null, draft: 0, draftOutward: false, thin: null }); + d.features.push({ id: 's3', name: 'Sketch2', type: 'sketch', plane: { kind: 'base', plane: 'front' }, constraints: [], entities: [ + { id: 'a', t: 'point', x: 0, y: -30 }, { id: 'b', t: 'point', x: 0, y: 120 }, { id: 'post', t: 'line', a: 'a', b: 'b' }, + ] }); + }); + a.selection.set([{ kind: 'feature', id: 's3' }]); + void a.commands.run('structuralMember'); + }); + await expect(page.getByRole('group', { name: 'Group 1' }).locator('.item')).toHaveCount(1); + await page.getByRole('button', { name: 'OK', exact: true }).first().click(); + await waitForFeature(page, 'Structural Member1'); + // A face of the rebuilt part (waiting for the rebuild that makes it). + const face = async (test: string) => { + const find = () => page.evaluate((src) => { + const a = (window as unknown as W).__parametric; + const i = a.faces.findIndex(new Function('f', `return ${src}`) as (f: unknown) => boolean); + return { kind: 'face' as const, index: i, name: a.faces[i]?.name ?? '' }; + }, test); + await expect.poll(async () => (await find()).index).toBeGreaterThanOrEqual(0); + return find(); + }; + // Trim/Extend: the post (picked before the command) to the plate's top face. + const side = await face("/^[^:]+:s3\\/post:/.test(f.name) && f.type === 'plane' && Math.abs(f.normal[0] - 1) < 1e-6"); + await page.evaluate((it) => { const a = (window as unknown as W).__parametric; a.selection.set([it]); }, side); + await page.getByRole('tab', { name: 'Weldments' }).click(); + await page.locator('[data-cmd="trimExtend"]').first().click(); + await expect(page.getByRole('heading', { name: 'Trim/Extend' })).toBeVisible(); + await expect(page.getByRole('group', { name: 'Bodies to be trimmed' }).locator('.item')).toHaveCount(1); + // The member to trim is highlighted: all its faces. + const lit = () => page.evaluate(() => (window as unknown as W).__parametric.extraHighlights().filter((x) => x.kind === 'face' && /:s3\/post:/.test(x.name ?? '')).length); + await expect.poll(lit).toBeGreaterThan(3); + await page.getByRole('group', { name: 'Face/Plane' }).click(); + const top = await face("f.name === 'f2:cap1'"); + await page.evaluate((it) => (window as unknown as W).__parametric.panel!.onPick(it, false), top); + await expect(page.getByRole('group', { name: 'Face/Plane' }).locator('.item')).toHaveCount(1); + await page.getByRole('button', { name: 'OK', exact: true }).first().click(); + await waitForFeature(page, 'Trim/Extend1'); + await expect(page.locator('.ti.error')).toHaveCount(0); + await expect.poll(() => page.evaluate(() => Math.round((window as unknown as W).__parametric.weldments[0].length))).toBe(110); + // End cap on the post's top end. + const end = await face("/^[^:]+:s3\\/post:/.test(f.name) && f.type === 'plane' && f.center[1] > 119.9"); + await page.evaluate((it) => { const a = (window as unknown as W).__parametric; a.selection.set([it]); }, end); + await page.locator('[data-cmd="endCap"]').first().click(); + await expect(page.getByRole('group', { name: 'Faces' }).locator('.item')).toHaveCount(1); + await page.getByRole('button', { name: 'OK', exact: true }).first().click(); + await waitForFeature(page, 'End Cap1'); + await expect(page.locator('.ti.error')).toHaveCount(0); + // A fillet bead where the post stands on the plate. + const findEdge = () => page.evaluate(() => { + const a = (window as unknown as W).__parametric; + const i = a.edges.findIndex((e) => e.type === 'line' && Math.abs(e.mid[0] - 20) < 1e-6 && Math.abs(e.mid[1] - 10) < 1e-6); + return { kind: 'edge' as const, index: i, name: a.edges[i]?.name ?? '' }; + }); + await expect.poll(async () => (await findEdge()).index).toBeGreaterThanOrEqual(0); + const edge = await findEdge(); + await page.evaluate((it) => { const a = (window as unknown as W).__parametric; a.selection.set([it]); }, edge); + await page.locator('[data-cmd="weldBead"]').first().click(); + await expect(page.getByRole('group', { name: 'Edges' }).locator('.item')).toHaveCount(1); + await page.getByRole('button', { name: 'OK', exact: true }).first().click(); + await waitForFeature(page, 'Fillet Bead1'); + await expect(page.locator('.ti.error')).toHaveCount(0); + // Suppressing the member suppresses what was built on it. + await page.getByRole('treeitem', { name: 'Structural Member1' }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Suppress' }).click(); + await expect(page.getByRole('treeitem', { name: 'Trim/Extend1' })).toHaveClass(/suppressed/); + await expect(page.getByRole('treeitem', { name: 'End Cap1' })).toHaveClass(/suppressed/); + await expect(page.locator('.ti.error')).toHaveCount(0); + expect(errors).toEqual([]); + }); +}); diff --git a/src/parametric/tests/kernel-client.test.ts b/src/parametric/tests/kernel-client.test.ts index 86e1a75eab..c1f0bfd8d3 100644 --- a/src/parametric/tests/kernel-client.test.ts +++ b/src/parametric/tests/kernel-client.test.ts @@ -199,6 +199,67 @@ describe('kernel memory', () => { }); }); +describe('kernel memory of assemblies', () => { + type AsmMsg = Extract; + const part = (key: string) => ({ key, features: [], blobs: {}, quality: 1 }); + const item = (p: string) => ({ part: p, m: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], name: p, color: '#888888' }); + + it('replaces a worker an assembly grew too big once it is idle, giving the new one the parts and their places first', async () => { + const { client, workers, restarts, last } = setup({ recycleBytes: 1000 }); + last().answer('init'); + await client.ready; + const asm = async (r: AsmMsg['req'], heap: number) => { + const p = client.assembly(r); + const m = last().sent.filter((x) => x.type === 'asm').pop()!; + last().reply({ id: m.id, ok: true, result: true, heap }); + await p; + await flush(); + }; + const generation = client.generation; + await asm({ op: 'build', parts: [part('a'), part('b'), part('c')] }, 600); + await asm({ op: 'scene', items: [item('a'), item('b')] }, 600); + await asm({ op: 'drop', keep: ['a', 'b'] }, 600); + await asm({ op: 'interference' }, 1100); + expect(workers).toHaveLength(1); + // Not while another request is waiting: once the worker is idle. + const mass = client.assembly({ op: 'mass', densities: [1, 1] }); + await asm({ op: 'interference' }, 5000); + expect(workers).toHaveLength(1); + const m = workers[0].sent.filter((x) => x.type === 'asm').find((x) => (x as AsmMsg).req.op === 'mass')!; + workers[0].reply({ id: m.id, ok: true, result: { volume: 1 }, heap: 5000 }); + await expect(mass).resolves.toEqual({ volume: 1 }); + await flush(); + expect(workers).toHaveLength(2); + expect(workers[0].terminated).toBe(true); + // The new worker builds the parts still used and places them before anything else. + const sent = workers[1].sent as AsmMsg[]; + expect(sent.map((x) => x.type)).toEqual(['init', 'asm', 'asm']); + expect(sent[1].req).toEqual({ op: 'build', parts: [part('a'), part('b')] }); + expect(sent[2].req).toEqual({ op: 'scene', items: [item('a'), item('b')] }); + // To the assembly it is the same worker: nothing to rebuild, nobody told of a restart. + expect(client.generation).toBe(generation); + expect(restarts).toEqual([]); + }); + + it('rebuilds the part, not the assembly, in a worker replaced after the assembly closed', async () => { + const { client, workers, last } = setup({ recycleBytes: 1000 }); + last().answer('init'); + await client.ready; + const p = client.assembly({ op: 'build', parts: [part('a')] }); + last().reply({ id: last().sent.find((x) => x.type === 'asm')!.id, ok: true, result: true, heap: 500 }); + await p; + void client.assembly({ op: 'drop', keep: [] }); + last().answer('asm'); + await flush(); + const b = client.build(req(3)); + last().reply({ id: last().sent.filter((x) => x.type === 'build').pop()!.id, ok: true, result: { heap: 5000 } }); + await b; + await flush(); + expect(workers).toHaveLength(2); + expect(workers[1].sent.map((x) => x.type)).toEqual(['init', 'build']); + }); +}); + describe('imported file data', () => { const sentBuilds = (w: FakeWorker) => w.sent.filter((m) => m.type === 'build') as Extract[]; @@ -237,3 +298,16 @@ describe('imported file data', () => { expect(sentBuilds(workers[1]).map((m) => m.req.blobs)).toEqual([{ a: 'other', b: 'B' }]); }); }); + +describe('kernel client and assemblies', () => { + it('tells an assembly to build its parts again after a reset (Force Rebuild), as after a restart', async () => { + const { client, last } = setup(); + last().answer('init'); + await client.ready; + const g = client.generation; + const reset = client.reset(); + expect(client.generation).not.toBe(g); + last().answer('reset'); + await reset; + }); +}); diff --git a/src/parametric/tests/sheetmetal-math.test.ts b/src/parametric/tests/sheetmetal-math.test.ts new file mode 100644 index 0000000000..4492f19f64 --- /dev/null +++ b/src/parametric/tests/sheetmetal-math.test.ts @@ -0,0 +1,212 @@ +// Sheet metal without the kernel: bend allowance math, open profile layout, +// file validation and the DXF writer. +import { describe, expect, it } from 'vitest'; +import { + type BendParams, bendAllowance, layoutOpenProfile, newBaseFlange, newEdgeFlange, newHem, newSketchedBend, openChain, setback, sheetParamsError, + validSheetMetalFeature, +} from '../src/model/sheetmetal'; +import { type FlatPattern, bendNote, flatPatternDxf, flatSize, parseDxfEntities } from '../src/model/flat-pattern'; +import { DocStore, newDocument, parseDocument, serializeDocument } from '../src/model/document'; +import { consumedSketches, dependencies } from '../src/model/features'; +import type { SkEntity } from '../src/model/types'; + +const P = (over: Partial = {}): BendParams => ({ thickness: 2, radius: 1, allowance: 'kFactor', kFactor: 0.5, allowanceValue: 0, ...over }); + +function chain(pts: [number, number][], prefix = 'c'): SkEntity[] { + const ents: SkEntity[] = pts.map(([x, y], i) => ({ id: `${prefix}p${i}`, t: 'point', x, y })); + for (let i = 0; i + 1 < pts.length; i++) ents.push({ id: `${prefix}l${i}`, t: 'line', a: `${prefix}p${i}`, b: `${prefix}p${i + 1}` }); + return ents; +} + +describe('bend allowance', () => { + it('uses the K-factor formula BA = pi/180 * angle * (R + K*T)', () => { + expect(bendAllowance(90, 1, P())).toBeCloseTo((Math.PI / 180) * 90 * (1 + 0.5 * 2), 12); + expect(bendAllowance(45, 3, P({ kFactor: 0.33 }))).toBeCloseTo((Math.PI / 180) * 45 * (3 + 0.33 * 2), 12); + expect(bendAllowance(120, 0, P({ kFactor: 0 }))).toBe(0); + }); + + it('takes a bend allowance as given and turns a bend deduction into one', () => { + expect(bendAllowance(90, 1, P({ allowance: 'bendAllowance', allowanceValue: 3.2 }))).toBe(3.2); + // BD = 2 * OSSB - BA with OSSB = tan(45) * (R + T) = 3. + expect(bendAllowance(90, 1, P({ allowance: 'bendDeduction', allowanceValue: 2 }))).toBeCloseTo(4, 12); + expect(setback(90, 3)).toBeCloseTo(3, 12); + expect(setback(60, 3)).toBeCloseTo(3 * Math.tan(Math.PI / 6), 12); + }); + + it('uses the K-factor a bend deduction gives a 90 degree bend for bends over 90 degrees', () => { + // T 2, R 1, BD 2: BA90 = 2 * (1 + 2) - 2 = 4 = pi/2 * (1 + K*2), so K = (8/pi - 1) / 2 = 0.773. + const p = P({ allowance: 'bendDeduction', allowanceValue: 2 }); + const k = (8 / Math.PI - 1) / 2; + // Up to 90 degrees, unchanged: BA = 2 * tan(angle/2) * (R + T) - BD. + expect(bendAllowance(90, 1, p)).toBeCloseTo(4, 12); + expect(bendAllowance(60, 1, p)).toBeCloseTo(2 * Math.tan(Math.PI / 6) * 3 - 2, 12); + expect(bendAllowance(60, 1, p)).toBeCloseTo(1.464101615, 9); + // 120 degrees: 2pi/3 * (1 + 2K) = 4 * 120/90 = 5.333 (the old formula gave 2 * tan(60) * 3 - 2 = 8.39). + expect(bendAllowance(120, 1, p)).toBeCloseTo(((2 * Math.PI) / 3) * (1 + k * 2), 12); + expect(bendAllowance(120, 1, p)).toBeCloseTo(16 / 3, 9); + // 179.5 degrees: 4 * 179.5/90 = 7.978 (the old formula gave about 685). + expect(bendAllowance(179.5, 1, p)).toBeCloseTo((179.5 / 90) * 4, 9); + expect(bendAllowance(179.5, 1, p)).toBeCloseTo(7.977777778, 8); + }); + + it('gives a hem a finite allowance with a bend deduction (a 180 degree bend has no virtual sharp)', () => { + // BD 2 at 90 degrees: BA90 = 4 = pi/2 * (R + K*T) gives K; the hem uses it at its own radius. + const p = P({ allowance: 'bendDeduction', allowanceValue: 2 }); + const k = (4 / (Math.PI / 2) - 1) / 2; + expect(bendAllowance(180, 0.5, p)).toBeCloseTo(Math.PI * (0.5 + k * 2), 9); + expect(bendAllowance(180, 1, p)).toBeCloseTo(8, 9); + }); + + it('rejects parameters it cannot bend with', () => { + expect(sheetParamsError(P())).toBeNull(); + expect(sheetParamsError(P({ thickness: 0 }))).toMatch(/Thickness/); + expect(sheetParamsError(P({ radius: -1 }))).toMatch(/radius/); + expect(sheetParamsError(P({ kFactor: 1.2 }))).toMatch(/K-factor/); + expect(sheetParamsError(P({ allowance: 'bendAllowance', allowanceValue: NaN }))).toMatch(/allowance/); + }); +}); + +describe('open profiles', () => { + it('orders the chain from the end of the first curve in the sketch, whichever way lines were drawn', () => { + const ents: SkEntity[] = [ + { id: 'a', t: 'point', x: 50, y: 30 }, { id: 'b', t: 'point', x: 50, y: 0 }, { id: 'c', t: 'point', x: 0, y: 0 }, + { id: 'l2', t: 'line', a: 'a', b: 'b' }, { id: 'l1', t: 'line', a: 'c', b: 'b' }, + ]; + const r = openChain(ents); + if ('error' in r) throw new Error(r.error); + expect(r.segs.map((s) => [s.src, s.a, s.b])).toEqual([['l2', [50, 30], [50, 0]], ['l1', [50, 0], [0, 0]]]); + }); + + it('says why a sketch is not one open chain', () => { + expect(openChain([])).toEqual({ error: expect.stringMatching(/no lines/) }); + const square = [...chain([[0, 0], [1, 0], [1, 1], [0, 1]], 's'), { id: 'close', t: 'line', a: 'sp3', b: 'sp0' } as SkEntity]; + expect(openChain(square)).toEqual({ error: 'The profile is closed' }); + const t: SkEntity[] = [...chain([[0, 0], [10, 0]], 'a'), ...chain([[10, 0], [10, 10]], 'b'), ...chain([[10, 0], [20, 0]], 'd')]; + expect(openChain(t)).toEqual({ error: expect.stringMatching(/branches/) }); + expect(openChain([...chain([[0, 0], [10, 0]], 'a'), ...chain([[20, 0], [30, 0]], 'b')])).toEqual({ error: expect.stringMatching(/single chain/) }); + expect(openChain([{ id: 'c', t: 'point', x: 0, y: 0 }, { id: 'k', t: 'circle', c: 'c', r: 3 }])).toEqual({ error: expect.stringMatching(/lines and arcs/) }); + }); + + it('lays an L profile out flat: legs less their setbacks plus the bend allowance', () => { + const segs = (openChain(chain([[0, 0], [50, 0], [50, 30]])) as { segs: never }).segs; + const p = P(); + // Thickness on the inside of the corner (left of the chain): the sketch is the outside, setback tan(45)(R + T). + const out = layoutOpenProfile(segs, p, 0); + if ('error' in out) throw new Error(out.error); + expect(out.bends).toHaveLength(1); + expect(out.bends[0]).toMatchObject({ up: true, angle: expect.closeTo(90, 9), radius: 1, width: expect.closeTo(bendAllowance(90, 1, p), 12) }); + expect(out.runs[0]).toMatchObject({ x0: 0, x1: expect.closeTo(47, 9) }); + expect(out.runs[1].x1 - out.runs[1].x0).toBeCloseTo(27, 9); + expect(out.runs[1].x1).toBeCloseTo(47 + Math.PI + 27, 9); + // Thickness outside the corner: the sketch is the inside, setback tan(45) R. + const inside = layoutOpenProfile(segs, p, 2); + if ('error' in inside) throw new Error(inside.error); + expect(inside.runs[1].x1).toBeCloseTo(49 + Math.PI + 29, 9); + // Turning right goes down. + const right = layoutOpenProfile((openChain(chain([[0, 0], [50, 0], [50, -30]])) as { segs: never }).segs, p, 0); + if ('error' in right) throw new Error(right.error); + expect(right.bends[0].up).toBe(false); + }); + + it('joins lines that go on straight, and reports corners it cannot bend', () => { + const straight = layoutOpenProfile((openChain(chain([[0, 0], [20, 0], [50, 0], [50, 30]])) as { segs: never }).segs, P(), 0); + if ('error' in straight) throw new Error(straight.error); + expect(straight.runs).toHaveLength(2); + expect(straight.runs[0].x1).toBeCloseTo(47, 9); + const short = layoutOpenProfile((openChain(chain([[0, 0], [2, 0], [2, 30]])) as { segs: never }).segs, P(), 0); + expect(short).toEqual({ error: expect.stringMatching(/too short/) }); + const back = layoutOpenProfile((openChain(chain([[0, 0], [50, 0], [0, 0.0001]])) as { segs: never }).segs, P(), 0); + expect(back).toEqual({ error: expect.stringMatching(/folds back/) }); + }); + + it('uses a tangent arc as a bend of its radius and rejects one that is not tangent', () => { + const arc = (cx: number, cy: number): SkEntity[] => [ + { id: 'a', t: 'point', x: 0, y: 0 }, { id: 'b', t: 'point', x: 30, y: 0 }, { id: 'c', t: 'point', x: 35, y: 5 }, { id: 'd', t: 'point', x: 35, y: 30 }, + { id: 'o', t: 'point', x: cx, y: cy }, + { id: 'l1', t: 'line', a: 'a', b: 'b' }, { id: 'arc', t: 'arc', c: 'o', a: 'b', b: 'c' }, { id: 'l2', t: 'line', a: 'c', b: 'd' }, + ]; + const ok = layoutOpenProfile((openChain(arc(30, 5)) as { segs: never }).segs, P(), 0); + if ('error' in ok) throw new Error(ok.error); + expect(ok.bends[0]).toMatchObject({ up: true, radius: 3, angle: expect.closeTo(90, 9), src: 'arc' }); + expect(ok.runs[0].x1).toBeCloseTo(30, 9); + const bad = layoutOpenProfile((openChain(arc(32, 3)) as { segs: never }).segs, P(), 0); + expect(bad).toEqual({ error: expect.stringMatching(/tangent/) }); + }); +}); + +describe('sheet metal documents', () => { + function doc() { + const d = newDocument(); + d.features.push({ id: 's1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: chain([[0, 0], [10, 0], [10, 10]]), constraints: [] }); + const bf = newBaseFlange('f2', 'Base-Flange1', 's1', 1, 20); + bf.sm.thickness = '=T'; + d.variables.push({ id: 'v1', name: 'T', expr: '1.5' }); + const ef = { ...newEdgeFlange('f3', 'Edge-Flange1', 10), edges: [{ name: 'f2:end1|f2:cl1:a', sig: { type: 'line', m: [0, 0, 0] as [number, number, number], len: 20 } }] }; + d.features.push(bf, ef, newSketchedBend('f4', 'Sketched Bend1', 's1'), { ...newHem('f5', 'Hem1', 5, 0.5), edges: [] }); + return d; + } + + it('saves, opens and evaluates sheet metal features', () => { + const d = parseDocument(serializeDocument(doc())); + expect(d.features.map((f) => f.type)).toEqual(['sketch', 'baseFlange', 'edgeFlange', 'sketchedBend', 'hem']); + const resolved = new DocStore(d).resolve(); + expect(resolved.errors.size).toBe(0); + expect((resolved.features[1] as { sm: { thickness: number } }).sm.thickness).toBe(1.5); + expect(dependencies(d.features[2])).toEqual(['f2']); + expect(consumedSketches(d.features[1])).toEqual(['s1']); + expect(consumedSketches(d.features[3])).toEqual(['s1']); + }); + + it('rejects damaged sheet metal features', () => { + for (const damage of [ + (f: Record) => { if (f.type === 'baseFlange') delete f.sm; }, + (f: Record) => { if (f.type === 'baseFlange') (f.sm as Record).allowance = 'magic'; }, + (f: Record) => { if (f.type === 'edgeFlange') f.edges = [{}]; }, + (f: Record) => { if (f.type === 'edgeFlange') f.position = 'sideways'; }, + (f: Record) => { if (f.type === 'hem') f.kind = 'rolled'; }, + (f: Record) => { if (f.type === 'sketchedBend') f.sketch = 5; }, + ]) { + const d = doc(); + d.features.forEach((f) => damage(f as unknown as Record)); + expect(() => parseDocument(JSON.stringify(d))).toThrow(/damaged/); + } + expect(validSheetMetalFeature({ type: 'other' })).toBe(true); + }); +}); + +describe('flat pattern DXF', () => { + const pattern: FlatPattern = { + loops: [ + { outer: true, segs: [{ k: 'line', a: [0, 0], b: [100, 0] }, { k: 'arc', c: [100, 10], r: 10, a0: -Math.PI / 2, a1: 0 }, { k: 'line', a: [110, 10], b: [0, 10] }, { k: 'line', a: [0, 10], b: [0, 0] }] }, + { outer: false, segs: [{ k: 'circle', c: [50, 5], r: 2 }] }, + ], + bends: [{ a: [30, 0], b: [30, 10], up: false, angle: 45, radius: 1.5, allowance: 2, feature: 'f3' }], + thickness: 2, min: [0, 0], max: [110, 10], notes: [], placement: { o: [0, 0, 0], x: [1, 0, 0], y: [0, 1, 0], n: [0, 0, 1] }, + }; + + it('writes lines, arcs in degrees, circles and dashed bend lines with notes', () => { + const ents = parseDxfEntities(flatPatternDxf(pattern)); + expect(ents.map((e) => `${e.type}:${e.layer}`)).toEqual(['LINE:OUTLINE', 'ARC:OUTLINE', 'LINE:OUTLINE', 'LINE:OUTLINE', 'CIRCLE:CUTS', 'LINE:BEND_DOWN', 'TEXT:BEND_NOTES']); + const arc = ents[1].values; + expect([arc.get(50)![0], arc.get(51)![0], arc.get(40)![0]]).toEqual(['-90', '0', '10']); + expect(ents[5].values.get(6)).toEqual(['DASHED']); + expect(ents[6].values.get(1)).toEqual(['DOWN 45%%d R 1.5']); + expect(parseDxfEntities(flatPatternDxf(pattern, { notes: false })).some((e) => e.type === 'TEXT')).toBe(false); + }); + + it('declares its layers and line types and ends with EOF', () => { + const text = flatPatternDxf(pattern); + const lines = text.trim().split('\n'); + expect(lines.length % 2).toBe(0); + expect(lines.slice(-2)).toEqual(['0', 'EOF']); + for (const layer of ['OUTLINE', 'CUTS', 'BEND_UP', 'BEND_DOWN', 'BEND_NOTES']) expect(text).toContain(`\n2\n${layer}\n`); + expect(text).toContain('\n2\nDASHED\n'); + expect(text).toContain('AC1009'); + }); + + it('notes and sizes', () => { + expect(bendNote(pattern.bends[0])).toBe('DOWN 45° R 1.5'); + expect(bendNote({ ...pattern.bends[0], up: true, angle: 90 }, (v) => `${v.toFixed(2)} mm`)).toBe('UP 90° R 1.50 mm'); + expect(flatSize(pattern)).toEqual([110, 10]); + }); +}); diff --git a/src/parametric/tests/sheetmetal.test.ts b/src/parametric/tests/sheetmetal.test.ts new file mode 100644 index 0000000000..654805b680 --- /dev/null +++ b/src/parametric/tests/sheetmetal.test.ts @@ -0,0 +1,519 @@ +// Sheet metal features on the real OpenCascade kernel: volumes, bounding +// boxes and the flat pattern against the bend allowance formula. +import { beforeAll, describe, expect, it } from 'vitest'; +import init from 'replicad-opencascadejs'; +import { ModelBuilder } from '../src/kernel/build'; +import { setOc } from '../src/kernel/occ'; +import type { BuildResult } from '../src/kernel/protocol'; +import type { EdgeInfo, FaceInfo } from '../src/kernel/protocol'; +import type { EdgeRef, Feature, FilletFeature, SkEntity } from '../src/model/types'; +import { + type BaseFlangeFeature, type EdgeFlangeFeature, type HemFeature, type SketchedBendFeature, newBaseFlange, newEdgeFlange, newHem, newSketchedBend, +} from '../src/model/sheetmetal'; +import { flatPatternDxf, flatSize, parseDxfEntities } from '../src/model/flat-pattern'; +import { circle, extrude, rect, req, sketch } from './helpers'; + +beforeAll(async () => { + setOc(await init()); +}, 60000); + +const T = 2, R = 1, K = 0.5; +const BA90 = (Math.PI / 2) * (R + K * T); + +/** Open polyline sketch entities. */ +function chain(pts: [number, number][], prefix = 'c'): SkEntity[] { + const ents: SkEntity[] = pts.map(([x, y], i) => ({ id: `${prefix}p${i}`, t: 'point', x, y })); + for (let i = 0; i + 1 < pts.length; i++) ents.push({ id: `${prefix}l${i}`, t: 'line', a: `${prefix}p${i}`, b: `${prefix}p${i + 1}` }); + return ents; +} + +function base(id: string, sk: string, extra: Partial = {}): BaseFlangeFeature { + const f = newBaseFlange(id, id, sk, T, 40); + f.sm.radius = R; + f.sm.kFactor = K; + return { ...f, ...extra }; +} + +const edgeRef = (e: EdgeInfo): EdgeRef => ({ name: e.name, sig: { type: e.type, m: e.mid, len: e.length } }); + +function flange(id: string, edges: EdgeRef[], extra: Partial = {}): EdgeFlangeFeature { + return { ...newEdgeFlange(id, id, 20), edges, ...extra }; +} + +const volume = (b: ModelBuilder) => b.massProperties()!.volume; +const ok = (res: BuildResult) => expect(res.status.map((s) => s.error ?? s.warning ?? 'ok')).toEqual(res.status.map(() => 'ok')); +const size = (res: BuildResult) => res.bbox!.max.map((v, i) => v - res.bbox!.min[i]); + +/** Straight edges of a face parallel to a direction, longest first. */ +function edgesOn(res: BuildResult, face: FaceInfo, dir: [number, number, number]): EdgeInfo[] { + const fi = res.faces.indexOf(face); + return res.edges + .filter((e) => e.faces.includes(fi) && e.type === 'line' && Math.abs(e.dir![0] * dir[0] + e.dir![1] * dir[1] + e.dir![2] * dir[2]) > 0.999) + .sort((a, b) => b.length - a.length); +} + +describe('base flange', () => { + it('makes a flat plate from a closed profile', async () => { + const b = new ModelBuilder(); + const res = await b.build(req([sketch('S1', [...rect(0, 0, 100, 60), ...circle(50, 30, 10)]), base('B1', 'S1')])); + ok(res); + expect(volume(b)).toBeCloseTo((6000 - Math.PI * 100) * T, 3); + expect(size(res)).toEqual([expect.closeTo(100, 6), expect.closeTo(60, 6), expect.closeTo(T, 6)]); + expect(res.faces.map((f) => f.name)).toEqual(expect.arrayContaining(['B1:cap0', 'B1:cap1'])); + const flat = b.flatPattern().pattern!; + expect(flatSize(flat)).toEqual([expect.closeTo(100, 6), expect.closeTo(60, 6)]); + expect(flat.bends).toHaveLength(0); + expect(flat.loops.filter((l) => !l.outer)).toHaveLength(1); + expect(flat.notes).toEqual([]); + }); + + it('thickens an L profile with a bend at the corner (outer virtual sharps on the sketch)', async () => { + const b = new ModelBuilder(); + const res = await b.build(req([sketch('S1', chain([[0, 0], [50, 0], [50, 30]])), base('B1', 'S1')])); + ok(res); + // Material to the left of the chain: inside the corner, so the sketch is the outside. + expect(res.bbox!.min).toEqual([expect.closeTo(0, 6), expect.closeTo(0, 6), expect.closeTo(0, 6)]); + expect(res.bbox!.max).toEqual([expect.closeTo(50, 6), expect.closeTo(30, 6), expect.closeTo(40, 6)]); + const straight = (50 - (R + T)) + (30 - (R + T)); + const bendVolume = (Math.PI / 4) * ((R + T) ** 2 - R ** 2); + expect(volume(b)).toBeCloseTo((straight * T + bendVolume) * 40, 3); + const names = res.faces.map((f) => f.name); + expect(names).toEqual(expect.arrayContaining(['B1:cap0', 'B1:cap1', 'B1:end0', 'B1:end1', 'B1:bend:cl0:in', 'B1:bend:cl0:out', 'B1:cl0:a', 'B1:cl1:b'])); + const flat = b.flatPattern().pattern!; + // Flat length: A + B - 2 * setback + bend allowance. + expect(flatSize(flat)[0]).toBeCloseTo(50 + 30 - 2 * (R + T) + BA90, 6); + expect(flatSize(flat)[1]).toBeCloseTo(40, 6); + expect(flat.bends).toHaveLength(1); + expect(flat.bends[0]).toMatchObject({ up: true, angle: expect.closeTo(90, 9), radius: R, allowance: expect.closeTo(BA90, 9) }); + expect(flat.notes).toEqual([]); + }); + + it('bends the other way with the thickness flipped, and centres it on mid-plane', async () => { + const b = new ModelBuilder(); + let res = await b.build(req([sketch('S1', chain([[0, 0], [50, 0], [50, 30]])), base('B1', 'S1', { flip: true })])); + ok(res); + // Material outside the corner: the sketch is the inside. + expect(res.bbox!.min.slice(0, 2)).toEqual([expect.closeTo(0, 6), expect.closeTo(-T, 6)]); + expect(res.bbox!.max.slice(0, 2)).toEqual([expect.closeTo(50 + T, 6), expect.closeTo(30, 6)]); + expect(flatSize(b.flatPattern().pattern!)[0]).toBeCloseTo(50 + 30 - 2 * R + BA90, 6); + res = await b.build(req([sketch('S1', chain([[0, 0], [50, 0], [50, 30]])), base('B1', 'S1', { mid: true })])); + ok(res); + expect(res.bbox!.max[0]).toBeCloseTo(50 + T / 2, 6); + expect(flatSize(b.flatPattern().pattern!)[0]).toBeCloseTo(50 + 30 - 2 * (R + T / 2) + BA90, 6); + }); + + it('makes a U channel with two bends and uses an arc as a bend of its own radius', async () => { + const b = new ModelBuilder(); + let res = await b.build(req([sketch('S1', chain([[0, 30], [0, 0], [40, 0], [40, 30]])), base('B1', 'S1', { flip: true })])); + ok(res); + expect(b.flatPattern().pattern!.bends).toHaveLength(2); + // Line, tangent arc of radius 5 (the sketch is on the outside: inner radius 5 - T), line. + const ents: SkEntity[] = [ + { id: 'a', t: 'point', x: 0, y: 0 }, { id: 'b', t: 'point', x: 30, y: 0 }, { id: 'c', t: 'point', x: 35, y: 5 }, { id: 'd', t: 'point', x: 35, y: 30 }, + { id: 'o', t: 'point', x: 30, y: 5 }, + { id: 'l1', t: 'line', a: 'a', b: 'b' }, { id: 'arc', t: 'arc', c: 'o', a: 'b', b: 'c' }, { id: 'l2', t: 'line', a: 'c', b: 'd' }, + ]; + res = await b.build(req([sketch('S1', ents), base('B1', 'S1')])); + ok(res); + const flat = b.flatPattern().pattern!; + expect(flat.bends[0].radius).toBeCloseTo(5 - T, 9); + expect(flatSize(flat)[0]).toBeCloseTo(30 + 25 + (Math.PI / 2) * (5 - T + K * T), 6); + }); + + it('reports profiles it cannot use', async () => { + const b = new ModelBuilder(); + const branch: SkEntity[] = [...chain([[0, 0], [10, 0]], 'a'), ...chain([[10, 0], [10, 10]], 'b'), ...chain([[10, 0], [20, 0]], 'd')]; + let res = await b.build(req([sketch('S1', branch), base('B1', 'S1')])); + expect(res.status[1].error).toMatch(/single chain/); + res = await b.build(req([sketch('S1', chain([[0, 0], [2, 0], [2, 30]])), base('B1', 'S1')])); + expect(res.status[1].error).toMatch(/too short/); + // A chain that crosses itself, and one whose last leg runs into the first one's thickness. + res = await b.build(req([sketch('S1', chain([[0, 0], [50, 0], [50, 30], [20, 30], [20, -20]])), base('B1', 'S1')])); + expect(res.status[1].error).toMatch(/crosses itself/); + res = await b.build(req([sketch('S1', chain([[0, 0], [50, 0], [50, 30], [10, 30], [10, 1]])), base('B1', 'S1')])); + expect(res.status[1].error).toMatch(/crosses itself/); + res = await b.build(req([sketch('S1', chain([[0, 0], [50, 0], [50, 30], [10, 30], [10, 10]])), base('B1', 'S1')])); + ok(res); + res = await b.build(req([sketch('S1', rect(0, 0, 10, 10)), base('B1', 'S1', { sm: { ...base('x', 'x').sm, thickness: 0 } })])); + expect(res.status[1].error).toMatch(/Thickness/); + }); +}); + +/** A 100 x 60 plate on the front plane, its top face at z = T. */ +const plate = (): Feature[] => [sketch('S1', rect(0, 0, 100, 60, 'pl')), base('B1', 'S1')]; + +async function plateEdge(b: ModelBuilder, y = 60): Promise { + const res = await b.build(req(plate())); + const top = res.faces.find((f) => f.name === 'B1:cap1')!; + return edgesOn(res, top, [1, 0, 0]).find((e) => Math.abs(e.mid[1] - y) < 1e-6)!; +} + +describe('edge flange', () => { + it('adds a 90 degree flange inside the plate (material inside, outer virtual sharp)', async () => { + const b = new ModelBuilder(); + const e = await plateEdge(b); + const res = await b.build(req([...plate(), flange('F1', [edgeRef(e)])])); + ok(res); + // The outer face of the flange is flush with the plate's old edge; the flange is 20 high from the outer sharp. + expect(res.bbox!.max).toEqual([expect.closeTo(100, 6), expect.closeTo(60, 6), expect.closeTo(20, 6)]); + expect(res.bbox!.min).toEqual([expect.closeTo(0, 6), expect.closeTo(0, 6), expect.closeTo(0, 6)]); + const flatPlate = 60 - (R + T), flatFlange = 20 - (R + T); + const bendVolume = (Math.PI / 4) * ((R + T) ** 2 - R ** 2) * 100; + expect(volume(b)).toBeCloseTo((flatPlate + flatFlange) * T * 100 + bendVolume, 3); + const flat = b.flatPattern().pattern!; + expect(flatSize(flat)).toEqual([expect.closeTo(100, 6), expect.closeTo(flatPlate + BA90 + flatFlange, 6)]); + expect(flat.bends[0]).toMatchObject({ up: true, angle: 90 }); + expect(res.faces.map((f) => f.name)).toEqual(expect.arrayContaining(['F1:e0:bend:in', 'F1:e0:bend:out', 'F1:e0:flange:in', 'F1:e0:flange:out', 'F1:e0:end'])); + }); + + it('measures the length and places the bend as asked', async () => { + const b = new ModelBuilder(); + const e = await plateEdge(b); + // Bend outside, length from the bend's end: plate untouched, flange straight 20 past the bend. + let res = await b.build(req([...plate(), flange('F1', [edgeRef(e)], { position: 'bendOutside', lengthRef: 'tangent' })])); + ok(res); + expect(res.bbox!.max[1]).toBeCloseTo(60 + R + T, 6); + expect(res.bbox!.max[2]).toBeCloseTo(T + R + 20, 6); + expect(flatSize(b.flatPattern().pattern!)[1]).toBeCloseTo(60 + BA90 + 20, 6); + // Material outside, inner virtual sharp: the inner face is flush with the edge. + res = await b.build(req([...plate(), flange('F1', [edgeRef(e)], { position: 'materialOutside', lengthRef: 'inner' })])); + ok(res); + expect(res.bbox!.max[1]).toBeCloseTo(60 + T, 6); + expect(res.bbox!.max[2]).toBeCloseTo(20 + T, 6); + // Flipped: the flange goes down. + res = await b.build(req([...plate(), flange('F1', [edgeRef(e)], { flip: true })])); + ok(res); + expect(res.bbox!.min[2]).toBeCloseTo(T - 20, 6); + expect(b.flatPattern().pattern!.bends[0].up).toBe(false); + }); + + it('bends at other angles with the K-factor bend allowance', async () => { + for (const angle of [45, 120]) { + const b = new ModelBuilder(); + const e = await plateEdge(b); + const res = await b.build(req([...plate(), flange('F1', [edgeRef(e)], { angle, position: 'bendOutside', lengthRef: 'tangent' })])); + ok(res); + const a = (angle * Math.PI) / 180; + // Top of the flange's end: on its inner face below 90 degrees, its outer face past it. + const top = T + R + 20 * Math.sin(a) - (angle <= 90 ? R : R + T) * Math.cos(a); + expect(res.bbox!.max[2]).toBeCloseTo(top, 6); + const ba = a * (R + K * T); + expect(flatSize(b.flatPattern().pattern!)[1]).toBeCloseTo(60 + ba + 20, 6); + const bendVolume = (a / 2) * ((R + T) ** 2 - R ** 2) * 100; + expect(volume(b)).toBeCloseTo((60 + 20) * T * 100 + bendVolume, 3); + } + }); + + it('adds reliefs where the flange stops short of the edge', async () => { + const b = new ModelBuilder(); + const e = await plateEdge(b); + const res = await b.build(req([...plate(), flange('F1', [edgeRef(e)], { offset1: 10, offset2: 20 })])); + ok(res); + const rw = 0.5 * T; + const trim = R + T; + const flatPlate = 60 * 100 - trim * 70 - 2 * rw * (trim + rw); + const bendVolume = (Math.PI / 4) * ((R + T) ** 2 - R ** 2) * 70; + expect(volume(b)).toBeCloseTo(flatPlate * T + (20 - trim) * T * 70 + bendVolume, 3); + const flat = b.flatPattern().pattern!; + expect(flat.notes).toEqual([]); + expect(Math.abs(flat.bends[0].b[0] - flat.bends[0].a[0])).toBeCloseTo(70, 6); + }); + + it('flanges two edges in one feature, and rejects edges that are not sheet edges', async () => { + const b = new ModelBuilder(); + let res = await b.build(req(plate())); + const top = res.faces.find((f) => f.name === 'B1:cap1')!; + const [e1, e2] = edgesOn(res, top, [1, 0, 0]); + res = await b.build(req([...plate(), flange('F1', [edgeRef(e1), edgeRef(e2)])])); + ok(res); + expect(size(res)).toEqual([expect.closeTo(100, 6), expect.closeTo(60, 6), expect.closeTo(20, 6)]); + expect(b.flatPattern().pattern!.bends).toHaveLength(2); + // An edge across the thickness. + res = await b.build(req(plate())); + const short = res.edges.find((x) => x.type === 'line' && Math.abs(x.length - T) < 1e-6)!; + res = await b.build(req([...plate(), flange('F1', [edgeRef(short)])])); + expect(res.status[2].error).toMatch(/across its thickness/); + // A reference from a hand-edited file without its signature: found by name, else a clear error. + const name = edgeRef(e1).name; + ok(await b.build(req([...plate(), flange('F1', [{ name } as EdgeRef])]))); + res = await b.build(req([...plate(), flange('F1', [{ name: 'B1:gone' } as EdgeRef])])); + expect(res.status[2].error).toMatch(/no longer exists/); + // Without a sheet metal part. + res = await b.build(req([sketch('S1', rect(0, 0, 10, 10)), extrude('E1', 'S1', 5), flange('F1', [edgeRef(short)])])); + expect(res.status[2].error).toMatch(/Base Flange/); + }); + + it('says when a hole is where the bend of a flange goes', async () => { + const b = new ModelBuilder(); + const holed: Feature[] = [sketch('S1', [...rect(0, 0, 100, 60, 'pl'), ...circle(50, 58, 1.5)]), base('B1', 'S1')]; + let res = await b.build(req(holed)); + const top = res.faces.find((f) => f.name === 'B1:cap1')!; + const e = edgesOn(res, top, [1, 0, 0]).find((x) => Math.abs(x.mid[1] - 60) < 1e-6)!; + res = await b.build(req([...holed, flange('F1', [edgeRef(e)])])); + expect(res.status[2].error).toMatch(/hole or cut where its bend goes/); + ok(await b.build(req([...holed, flange('F1', [edgeRef(e)], { position: 'bendOutside' })]))); + }); + + it('says when a flange would run into the part instead of merging into it', async () => { + const b = new ModelBuilder(); + const L: Feature[] = [sketch('S1', chain([[0, 0], [60, 0], [60, 40]])), base('B1', 'S1')]; + let res = await b.build(req(L)); + // The top edge of the upright leg, on its inner face: a 135 degree flange back over the base reaches through it. + const e = res.edges.find((x) => x.type === 'line' && Math.abs(x.mid[1] - 40) < 1e-6 && Math.abs(x.mid[0] - (60 - T)) < 1e-6 && Math.abs(x.dir![2]) > 0.99)!; + res = await b.build(req([...L, flange('F1', [edgeRef(e)], { angle: 135, length: 80 })])); + expect(res.status[2].error).toMatch(/runs into the part/); + res = await b.build(req([...L, flange('F1', [edgeRef(e)], { angle: 135, length: 30 })])); + ok(res); + res = await b.build(req([...L, flange('F1', [edgeRef(e)], { angle: 135, length: 80, flip: true })])); + ok(res); + }); + + it('keeps fillets and holes on sheet metal faces through thickness changes', async () => { + const b = new ModelBuilder(); + const e = await plateEdge(b); + const f1 = flange('F1', [edgeRef(e)]); + let res = await b.build(req([...plate(), f1])); + const out = res.faces.find((f) => f.name === 'F1:e0:flange:out')!; + const corner = res.edges.find((x) => x.name.includes('F1:e0:end') && Math.abs(x.length - T) < 1e-6)!; + expect(corner).toBeTruthy(); + const fillet: FilletFeature = { id: 'FL', name: 'FL', type: 'fillet', edges: [edgeRef(corner)], faces: [], radius: 3 }; + const hole = sketch("S2", circle(50, -10, 3), { kind: 'face', face: { name: out.name, sig: { type: 'plane', c: out.center, n: out.normal, area: out.area } } }); + const cutHole = extrude('C1', 'S2', 1, { cut: true, end: 'throughAll' }); + res = await b.build(req([...plate(), f1, fillet, hole, cutHole])); + ok(res); + const v1 = volume(b); + const thicker = plate(); + (thicker[1] as BaseFlangeFeature).sm.thickness = 3; + res = await b.build(req([...thicker, f1, fillet, hole, cutHole])); + ok(res); + expect(volume(b)).toBeGreaterThan(v1); + // The hole through the flange shows in the flat pattern. + const flat = b.flatPattern().pattern!; + expect(flat.loops.filter((l) => !l.outer)).toHaveLength(1); + }); +}); + +describe('sketched bend and hem', () => { + it('bends a plate along a sketched line, keeping its flat size', async () => { + const b = new ModelBuilder(); + let res = await b.build(req(plate())); + const top = res.faces.find((f) => f.name === 'B1:cap1')!; + const line = sketch('S2', [{ id: 'p', t: 'point', x: 0, y: 40 }, { id: 'q', t: 'point', x: 100, y: 40 }, { id: 'l', t: 'line', a: 'p', b: 'q' }], + { kind: 'face', face: { name: top.name, sig: { type: 'plane', c: top.center, n: top.normal, area: top.area } } }); + const bend: SketchedBendFeature = newSketchedBend('SB', 'SB', 'S2'); + res = await b.build(req([...plate(), line, bend])); + ok(res); + expect(volume(b)).toBeCloseTo(6000 * T, 3); + const flat = b.flatPattern().pattern!; + expect(flatSize(flat)).toEqual([expect.closeTo(100, 6), expect.closeTo(60, 6)]); + expect(flat.bends).toHaveLength(1); + expect(flat.bends[0].a[1]).toBeCloseTo(40, 6); + // The side left of the line (drawn either way) stays on the plane, the other stands up 90 degrees. + expect(res.bbox!.max[1]).toBeCloseTo(60, 6); + expect(res.bbox!.min[1]).toBeGreaterThan(30); + expect(res.bbox!.max[2]).toBeCloseTo(T + R + (40 - BA90 / 2), 6); + expect(res.faces.map((f) => f.name)).toEqual(expect.arrayContaining(['SB:bend:in', 'SB:bend:out'])); + // A line drawn well past the face (its middle off the sheet) bends the same. + const long = sketch('S2', [{ id: 'p', t: 'point', x: 0, y: 40 }, { id: 'q', t: 'point', x: 300, y: 40 }, { id: 'l', t: 'line', a: 'p', b: 'q' }], line.plane); + ok(await b.build(req([...plate(), long, bend]))); + expect(flatSize(b.flatPattern().pattern!)).toEqual([expect.closeTo(100, 6), expect.closeTo(60, 6)]); + // The other side fixed. + res = await b.build(req([...plate(), line, { ...bend, flipFixed: true }])); + ok(res); + expect(res.bbox!.min[1]).toBeCloseTo(0, 6); + expect(res.bbox!.max[1]).toBeLessThan(50); + expect(res.bbox!.max[2]).toBeCloseTo(T + R + (20 - BA90 / 2), 6); + }); + + it('folds a closed and an open hem back over the sheet', async () => { + const b = new ModelBuilder(); + const e = await plateEdge(b); + const hem: HemFeature = { ...newHem('H1', 'H1', 10, 1), edges: [edgeRef(e)] }; + let res = await b.build(req([...plate(), hem])); + ok(res); + expect(res.bbox!.max[1]).toBeCloseTo(60, 6); + expect(res.bbox!.max[2]).toBeCloseTo(2 * T + 0.02 * T, 6); + res = await b.build(req([...plate(), { ...hem, kind: 'open' as const }])); + ok(res); + expect(res.bbox!.max[2]).toBeCloseTo(2 * T + 1, 6); + const r = 0.5; + const flat = b.flatPattern().pattern!; + expect(flatSize(flat)[1]).toBeCloseTo(60 - (r + T) + Math.PI * (r + K * T) + (10 - (r + T)), 6); + }); + + it('flattens a hem in a part that uses a bend deduction', async () => { + const b = new ModelBuilder(); + const e = await plateEdge(b); + const sheet = plate(); + Object.assign((sheet[1] as BaseFlangeFeature).sm, { allowance: 'bendDeduction', allowanceValue: 3 }); + const res = await b.build(req([...sheet, { ...newHem('H1', 'H1', 10, 1), edges: [edgeRef(e)], kind: 'open' as const }])); + ok(res); + // The deduction's 90 degree allowance (2 * (R + T) - 3) gives the K-factor for the hem's radius. + const r = 0.5, k = ((2 * (R + T) - 3) / (Math.PI / 2) - R) / T; + expect(flatSize(b.flatPattern().pattern!)[1]).toBeCloseTo(60 - (r + T) + Math.PI * (r + k * T) + (10 - (r + T)), 6); + // A 179.5 degree flange (bend outside, 20 past the bend): BA = 179.5/90 * (2 * (R + T) - 3), not 2 * tan(89.75) * 3 - 3. + const f = flange('F1', [edgeRef(e)], { angle: 179.5, position: 'bendOutside', lengthRef: 'tangent' }); + ok(await b.build(req([...sheet, f]))); + expect(flatSize(b.flatPattern().pattern!)[1]).toBeCloseTo(60 + (179.5 / 90) * 3 + 20, 6); + // 90 degrees as before: BA = 2 * (R + T) - BD. + ok(await b.build(req([...sheet, { ...f, angle: 90 }]))); + expect(flatSize(b.flatPattern().pattern!)[1]).toBeCloseTo(60 + 3 + 20, 6); + }); +}); + +describe('combinations', () => { + const faceRef = (f: FaceInfo) => ({ name: f.name, sig: { type: 'plane', c: f.center, n: f.normal, area: f.area } }); + + it('adds a tab on the sheet and flattens it with the plate', async () => { + const b = new ModelBuilder(); + const res = await b.build(req(plate())); + const top = res.faces.find((f) => f.name === 'B1:cap1')!; + // A 20 x 10 tab sticking out of the plate's top edge (sketch y is world y on this face). + const tab = sketch('S2', rect(40, 55, 60, 70, 'tb'), { kind: 'face', face: faceRef(top) }); + const r2 = await b.build(req([...plate(), tab, base('T1', 'S2')])); + ok(r2); + expect(volume(b)).toBeCloseTo((6000 + 20 * 10) * T, 3); + expect(size(r2)).toEqual([expect.closeTo(100, 6), expect.closeTo(70, 6), expect.closeTo(T, 6)]); + expect(flatSize(b.flatPattern().pattern!)).toEqual([expect.closeTo(100, 6), expect.closeTo(70, 6)]); + // The tab's edge takes a flange. + const tabEdge = r2.edges.find((e) => e.type === 'line' && Math.abs(e.mid[1] - 70) < 1e-6 && Math.abs(e.mid[2] - T) < 1e-6)!; + const r3 = await b.build(req([...plate(), tab, base('T1', 'S2'), flange('F1', [edgeRef(tabEdge)])])); + ok(r3); + expect(b.flatPattern().pattern!.bends).toHaveLength(1); + // Off the sheet, or open: errors. + const far = sketch('S2', rect(200, 200, 210, 210, 'tf'), { kind: 'face', face: faceRef(top) }); + expect((await b.build(req([...plate(), far, base('T1', 'S2')]))).status[3].error).toMatch(/touch/); + const open = sketch('S2', chain([[10, 10], [20, 10]], 'to'), { kind: 'face', face: faceRef(top) }); + expect((await b.build(req([...plate(), open, base('T1', 'S2')]))).status[3].error).toMatch(/tab/); + }); + + it('flanges the end of a flange, and carries flanges with a sketched bend', async () => { + const b = new ModelBuilder(); + const e = await plateEdge(b); + const f1 = flange('F1', [edgeRef(e)], { position: 'bendOutside', lengthRef: 'tangent' }); + let res = await b.build(req([...plate(), f1])); + // The top edge of the flange (on its inner face) gets a flange of its own, back over the plate. + const end = res.faces.find((f) => f.name === 'F1:e0:end')!; + const inner = res.faces.find((f) => f.name === 'F1:e0:flange:in')!; + const top = res.edges.find((x) => x.faces.includes(res.faces.indexOf(end)) && x.faces.includes(res.faces.indexOf(inner)))!; + const f2 = flange('F2', [edgeRef(top)], { position: 'bendOutside', lengthRef: 'tangent', length: 10 }); + res = await b.build(req([...plate(), f1, f2])); + ok(res); + let flat = b.flatPattern().pattern!; + expect(flatSize(flat)[1]).toBeCloseTo(60 + BA90 + 20 + BA90 + 10, 6); + expect(flat.notes).toEqual([]); + // A sketched bend across the plate moves the side with the flanges. + const plateTop = res.faces.find((f) => f.name === 'B1:cap1')!; + const line = sketch('S3', [{ id: 'p', t: 'point', x: 0, y: 20 }, { id: 'q', t: 'point', x: 100, y: 20 }, { id: 'l', t: 'line', a: 'p', b: 'q' }], { kind: 'face', face: faceRef(plateTop) }); + res = await b.build(req([...plate(), f1, f2, line, { ...newSketchedBend('SB', 'SB', 'S3'), flipFixed: true }])); + ok(res); + flat = b.flatPattern().pattern!; + expect(flatSize(flat)[1]).toBeCloseTo(60 + BA90 + 20 + BA90 + 10, 6); + expect(flat.bends).toHaveLength(3); + expect(flat.notes).toEqual([]); + // The y < 20 side stays; the rest stands up about the bend axis (y = 20 - BA/2, z = T + R), turning the + // flanges' top (z = T + R + 20 + R + T before) toward -y. + expect(res.bbox!.min[2]).toBeCloseTo(0, 6); + expect(res.bbox!.min[1]).toBeCloseTo(20 - BA90 / 2 + (T + R) - (T + R + 20 + R + T), 6); + // Highest: F1's bend, which reached R + T past y = 60. + expect(res.bbox!.max[2]).toBeCloseTo(T + R + (60 + R + T) - (20 - BA90 / 2) - BA90, 6); + }); + + it('says when a sketched bend would fold the sheet into itself', async () => { + const b = new ModelBuilder(); + const e = await plateEdge(b); + const f1 = flange('F1', [edgeRef(e)]); + const res = await b.build(req([...plate(), f1])); + const plateTop = res.faces.find((f) => f.name === 'B1:cap1')!; + // Folding the 20 wide side with the flange back over the plate drives the flange through it. + const line = sketch('S3', [{ id: 'p', t: 'point', x: 0, y: 40 }, { id: 'q', t: 'point', x: 100, y: 40 }, { id: 'l', t: 'line', a: 'p', b: 'q' }], { kind: 'face', face: faceRef(plateTop) }); + const bend = { ...newSketchedBend('SB', 'SB', 'S3'), flipFixed: true }; + expect((await b.build(req([...plate(), f1, line, { ...bend, angle: 170 }]))).status[4].error).toMatch(/folds the sheet into itself/); + ok(await b.build(req([...plate(), f1, line, { ...bend, angle: 90 }]))); + }); + + it('asks for offsets when two sloped flanges in one feature meet at a corner', async () => { + const b = new ModelBuilder(); + const res = await b.build(req(plate())); + const top = res.faces.find((f) => f.name === 'B1:cap1')!; + const e1 = edgesOn(res, top, [1, 0, 0]).find((e) => Math.abs(e.mid[1] - 60) < 1e-6)!; + const e2 = edgesOn(res, top, [0, 1, 0]).find((e) => Math.abs(e.mid[0] - 100) < 1e-6)!; + const f = flange('F1', [edgeRef(e1), edgeRef(e2)], { angle: 135 }); + expect((await b.build(req([...plate(), f]))).status[2].error).toMatch(/offsets/); + ok(await b.build(req([...plate(), { ...f, offset1: 16, offset2: 16 }]))); + }); + + it('flanges two edges meeting at a corner one after the other', async () => { + const b = new ModelBuilder(); + let res = await b.build(req(plate())); + const top = res.faces.find((f) => f.name === 'B1:cap1')!; + const e1 = edgesOn(res, top, [1, 0, 0]).find((e) => Math.abs(e.mid[1] - 60) < 1e-6)!; + const f1 = flange('F1', [edgeRef(e1)]); + res = await b.build(req([...plate(), f1])); + const top2 = res.faces.find((f) => f.name === 'B1:cap1')!; + const e2 = edgesOn(res, top2, [0, 1, 0]).find((e) => Math.abs(e.mid[0] - 100) < 1e-6)!; + res = await b.build(req([...plate(), f1, flange('F2', [edgeRef(e2)])])); + ok(res); + expect(size(res)).toEqual([expect.closeTo(100, 6), expect.closeTo(60, 6), expect.closeTo(20, 6)]); + const flat = b.flatPattern().pattern!; + expect(flat.bends).toHaveLength(2); + expect(flat.notes).toEqual([]); + }); + + it('patterns, mirrors and fillets the folded body like any body', async () => { + const b = new ModelBuilder(); + const e = await plateEdge(b); + const res = await b.build(req([...plate(), flange('F1', [edgeRef(e)])])); + const out = res.faces.find((f) => f.name === 'F1:e0:flange:out')!; + const hole = sketch('S2', circle(20, -10, 2), { kind: 'face', face: faceRef(out) }); + const cutHole = extrude('C1', 'S2', 1, { cut: true, end: 'throughAll' }); + const pattern = { id: 'LP', name: 'LP', type: 'linearPattern' as const, seeds: ['C1'], dir1: { ref: { kind: 'base' as const, axis: 'x' as const }, spacing: 20, count: 3, flip: false }, dir2: null }; + const r2 = await b.build(req([...plate(), flange('F1', [edgeRef(e)]), hole, cutHole, pattern])); + ok(r2); + const flat = b.flatPattern().pattern!; + expect(flat.loops.filter((l) => !l.outer)).toHaveLength(3); + expect(flat.notes).toEqual([]); + // A sheet metal feature is not a seed: copies of its wall alone would sit in the sheet without their bend cut. + const flangePattern = { ...pattern, seeds: ['F1'] }; + expect((await b.build(req([...plate(), flange('F1', [edgeRef(e)]), flangePattern]))).status[3].error).toMatch(/cannot be patterned/); + const mirror = { id: 'M', name: 'M', type: 'mirror' as const, seeds: [], plane: { kind: 'base' as const, plane: 'top' as const } }; + const r3 = await b.build(req([...plate(), flange('F1', [edgeRef(e)]), hole, cutHole, pattern, mirror])); + ok(r3); + expect(r3.bbox!.min[1]).toBeCloseTo(-60, 6); + }); +}); + +describe('flat pattern export', () => { + it('writes the outline, cuts and bend lines on their layers', async () => { + const b = new ModelBuilder(); + const e = await plateEdge(b); + await b.build(req([sketch('S1', [...rect(0, 0, 100, 60), ...circle(30, 30, 5)]), base('B1', 'S1'), flange('F1', [edgeRef(e)])])); + const flat = b.flatPattern().pattern!; + const dxf = flatPatternDxf(flat); + const ents = parseDxfEntities(dxf); + const layers = (l: string) => ents.filter((x) => x.layer === l); + expect(layers('OUTLINE').length).toBe(4); + expect(layers('OUTLINE').every((x) => x.type === 'LINE')).toBe(true); + expect(layers('CUTS').map((x) => x.type)).toEqual(['CIRCLE']); + expect(Number(layers('CUTS')[0].values.get(40)![0])).toBeCloseTo(5, 9); + expect(layers('BEND_UP').map((x) => x.type)).toEqual(['LINE']); + expect(layers('BEND_NOTES')[0].values.get(1)![0]).toBe('UP 90%%d R 1'); + // The outline lines join into one closed loop of the flat size. + const xs = layers('OUTLINE').flatMap((x) => [Number(x.values.get(10)![0]), Number(x.values.get(11)![0])]); + expect(Math.max(...xs) - Math.min(...xs)).toBeCloseTo(100, 6); + expect(dxf.trimEnd().endsWith('EOF')).toBe(true); + }); + + it('says what it leaves out', async () => { + const b = new ModelBuilder(); + const res = await b.build(req(plate())); + const top = res.faces.find((f) => f.name === 'B1:cap1')!; + // A boss on the sheet is not sheet metal. + const boss = sketch('S2', rect(10, 10, 20, 20), { kind: 'face', face: { name: top.name, sig: { type: 'plane', c: top.center, n: top.normal, area: top.area } } }); + await b.build(req([...plate(), boss, extrude('E1', 'S2', 5)])); + expect(b.flatPattern().pattern!.notes.join(' ')).toMatch(/cannot show/); + const plain = new ModelBuilder(); + await plain.build(req([sketch('S1', rect(0, 0, 10, 10)), extrude('E1', 'S1', 5)])); + expect(plain.flatPattern().error).toMatch(/no sheet metal/); + }); +}); diff --git a/src/parametric/tests/surfaces.test.ts b/src/parametric/tests/surfaces.test.ts new file mode 100644 index 0000000000..691e3c0074 --- /dev/null +++ b/src/parametric/tests/surfaces.test.ts @@ -0,0 +1,697 @@ +// Surface modeling on the real OpenCascade kernel in Node: surface bodies +// (made, changed and used by the surface features) and the solid path left +// as it was for parts without them. +import { beforeAll, describe, expect, it } from 'vitest'; +import init from 'replicad-opencascadejs'; +import { ModelBuilder } from '../src/kernel/build'; +import { setOc } from '../src/kernel/occ'; +import { flangeExample, bracketExample } from '../src/app/examples'; +import type { BuildResult } from '../src/kernel/protocol'; +import type { EdgeRef, FaceRef, Feature, SkEntity, SketchFeature } from '../src/model/types'; +import { newSurfaceFeature, type SurfaceFeature, type SurfaceFeatureType } from '../src/model/surfaces'; +import { dependencies, consumedSketches } from '../src/model/features'; +import { validFeature } from '../src/model/validate-feature'; +import { newDocument, parseDocument, serializeDocument } from '../src/model/document'; +import { circle, extrude, rect, req, sketch } from './helpers'; + +beforeAll(async () => { + setOc(await init()); +}); + +const P = (id: string, x: number, y: number): SkEntity => ({ id, t: 'point', x, y }); +const L = (id: string, a: string, b: string, construction = false): SkEntity => ({ id, t: 'line', a, b, ...(construction ? { construction } : {}) }); +/** An open polyline. */ +const open = (prefix: string, pts: [number, number][]): SkEntity[] => [ + ...pts.map(([x, y], i) => P(`${prefix}p${i}`, x, y)), + ...pts.slice(1).map((_, i) => L(`${prefix}l${i}`, `${prefix}p${i}`, `${prefix}p${i + 1}`)), +]; + +function surf(type: T, id: string, extra: Partial>): Feature { + return { ...newSurfaceFeature(type, id, id, 10), ...extra } as Feature; +} + +const ok = (res: BuildResult) => { + const bad = res.status.filter((s) => !s.ok); + expect(bad, JSON.stringify(bad)).toEqual([]); +}; + +/** Surface area of the build's surface bodies (from the face list). */ +const surfaceArea = (res: BuildResult) => res.faces.filter((f) => f.body).reduce((a, f) => a + f.area, 0); +const surfaceFaces = (res: BuildResult) => res.faces.filter((f) => f.body); +const faceRefOf = (res: BuildResult, pred: (f: BuildResult['faces'][number]) => boolean): FaceRef => { + const f = res.faces.find(pred); + if (!f) throw new Error('no such face'); + return { name: f.name, sig: { type: f.type, c: f.center, n: f.normal, area: f.area } }; +}; +const edgeRefOf = (res: BuildResult, pred: (e: BuildResult['edges'][number]) => boolean): EdgeRef[] => + res.edges.filter(pred).map((e) => ({ name: e.name, sig: { type: e.type, m: e.mid, len: e.length } })); + +const near = (a: number[], b: number[], tol = 1e-3) => a.every((v, i) => Math.abs(v - b[i]) < tol); + +describe('surface bodies', () => { + it('extrudes an open sketch into a surface body beside no solid', async () => { + const b = new ModelBuilder(); + const res = await b.build(req([sketch('S1', open('a', [[0, 0], [20, 0], [20, 10]])), surf('surfaceExtrude', 'F1', { sketch: 'S1', depth: 5 })])); + ok(res); + expect(b.hasBody).toBe(false); + expect(surfaceFaces(res)).toHaveLength(2); + expect(surfaceFaces(res).map((f) => f.name).sort()).toEqual(['F1:side:al0', 'F1:side:al1']); + expect(surfaceArea(res)).toBeCloseTo(150, 6); + expect(res.surfaces).toEqual({ face: 0, edge: 0 }); + expect(near(res.bbox!.min, [0, 0, 0]) && near(res.bbox!.max, [20, 10, 5])).toBe(true); + // The shared edge joins the two faces; the others bound one face each. + const shared = res.edges.filter((e) => e.faces.length === 2); + expect(shared).toHaveLength(1); + expect(res.edges.every((e) => e.body === 'F1')).toBe(true); + expect(res.mesh!.indices.length).toBeGreaterThan(0); + const mp = b.massProperties()!; + expect(mp.solid).toBe(false); + expect(mp.volume).toBe(0); + expect(mp.surfaceArea).toBeCloseTo(150, 6); + }); + + it('extrudes a closed sketch into an open tube, mid plane and in two directions', async () => { + const b = new ModelBuilder(); + let res = await b.build(req([sketch('S1', rect(0, 0, 10, 6)), surf('surfaceExtrude', 'F1', { sketch: 'S1', depth: 4, end: 'midPlane' })])); + ok(res); + expect(surfaceFaces(res)).toHaveLength(4); + expect(surfaceArea(res)).toBeCloseTo(32 * 4, 6); + expect(res.bbox!.min[2]).toBeCloseTo(-2, 6); + expect(res.bbox!.max[2]).toBeCloseTo(2, 6); + res = await b.build(req([sketch('S1', rect(0, 0, 10, 6)), surf('surfaceExtrude', 'F1', { sketch: 'S1', depth: 4, dir2: { depth: 1 } })])); + ok(res); + expect(res.bbox!.min[2]).toBeCloseTo(-1, 6); + expect(res.bbox!.max[2]).toBeCloseTo(4, 6); + expect(surfaceArea(res)).toBeCloseTo(32 * 5, 6); + }); + + it('revolves a line into a cylindrical surface, skipping the axis', async () => { + const b = new ModelBuilder(); + const ents = [...open('a', [[5, 0], [5, 10]]), P('c0', 0, -5), P('c1', 0, 15), L('cl', 'c0', 'c1', true)]; + const res = await b.build(req([sketch('S1', ents), surf('surfaceRevolve', 'F1', { sketch: 'S1', angle: 360 })])); + ok(res); + expect(surfaceArea(res)).toBeCloseTo(2 * Math.PI * 5 * 10, 3); + const half = await b.build(req([sketch('S1', ents), surf('surfaceRevolve', 'F1', { sketch: 'S1', angle: 180, end: 'midPlane' })])); + ok(half); + expect(surfaceArea(half)).toBeCloseTo(Math.PI * 5 * 10, 3); + // A line across the centerline says so. + const across = [...open('a', [[-5, 0], [5, 10]]), P('c0', 0, -5), P('c1', 0, 15), L('cl', 'c0', 'c1', true)]; + const bad = await b.build(req([sketch('S1', across), surf('surfaceRevolve', 'F1', { sketch: 'S1', angle: 360 })])); + expect(bad.status[1]).toMatchObject({ ok: false, error: expect.stringMatching(/crosses the axis of revolution/) }); + }); + + it('lofts open and closed profiles into surfaces, and sweeps an open profile', async () => { + const b = new ModelBuilder(); + const top = { kind: 'feature' as const, id: 'PL' }; + const plane: Feature = { id: 'PL', name: 'PL', type: 'plane', ref: { kind: 'base', plane: 'top' }, offset: 10, flip: false }; + // Two parallel lines 10 apart: a flat ruled strip. + let res = await b.build(req([plane, sketch('S1', open('a', [[0, 0], [10, 0]]), { kind: 'base', plane: 'top' }), sketch('S2', open('b', [[0, 0], [10, 0]]), top), + surf('surfaceLoft', 'F1', { profiles: ['S1', 'S2'] })])); + ok(res); + expect(surfaceArea(res)).toBeCloseTo(100, 4); + // Circles of radius 5 and 3, 10 apart: a frustum's side. + res = await b.build(req([plane, sketch('S1', circle(0, 0, 5), { kind: 'base', plane: 'top' }), sketch('S2', circle(0, 0, 3), top), + surf('surfaceLoft', 'F1', { profiles: ['S1', 'S2'], ruled: true })])); + ok(res); + expect(surfaceArea(res)).toBeCloseTo(Math.PI * (5 + 3) * Math.hypot(10, 2), 2); + // Mixed open and closed profiles cannot be lofted. + res = await b.build(req([plane, sketch('S1', circle(0, 0, 5), { kind: 'base', plane: 'top' }), sketch('S2', open('b', [[0, 0], [10, 0]]), top), + surf('surfaceLoft', 'F1', { profiles: ['S1', 'S2'] })])); + expect(res.status[3]).toMatchObject({ ok: false, error: expect.stringMatching(/all open or all closed/) }); + // Hundreds of profiles (a damaged file) are refused at once instead of lofting for minutes. + res = await b.build(req([plane, sketch('S1', circle(0, 0, 5), { kind: 'base', plane: 'top' }), sketch('S2', circle(0, 0, 3), top), + surf('surfaceLoft', 'F1', { profiles: Array.from({ length: 400 }, (_, i) => (i % 2 ? 'S2' : 'S1')) })])); + expect(res.status[3]).toMatchObject({ ok: false, error: expect.stringMatching(/at most 50 profiles/) }); + // A 5 mm line swept 20 mm up its own perpendicular. + res = await b.build(req([sketch('S1', open('p', [[0, 0], [5, 0]]), { kind: 'base', plane: 'top' }), sketch('S2', open('q', [[0, 0], [0, 20]]), { kind: 'base', plane: 'front' }), + surf('surfaceSweep', 'F1', { profile: 'S1', path: 'S2' })])); + ok(res); + expect(surfaceArea(res)).toBeCloseTo(100, 3); + }); + + it('makes planar surfaces from a sketch and from a loop of edges', async () => { + const b = new ModelBuilder(); + let res = await b.build(req([sketch('S1', [...rect(0, 0, 20, 10), ...circle(10, 5, 2)]), surf('surfacePlanar', 'F1', { sketch: 'S1' })])); + ok(res); + expect(surfaceArea(res)).toBeCloseTo(200 - Math.PI * 4, 4); + // The top edges of an extruded tube close a loop. + const tube = [sketch('S1', rect(0, 0, 10, 6)), surf('surfaceExtrude', 'F1', { sketch: 'S1', depth: 4 })]; + res = await b.build(req(tube)); + const topEdges = edgeRefOf(res, (e) => Math.abs(e.mid[2] - 4) < 1e-6); + expect(topEdges).toHaveLength(4); + res = await b.build(req([...tube, surf('surfacePlanar', 'F2', { sketch: null, edges: topEdges })])); + ok(res); + expect(surfaceFaces(res).filter((f) => f.body === 'F2')).toHaveLength(1); + expect(surfaceFaces(res).find((f) => f.body === 'F2')!.area).toBeCloseTo(60, 6); + // Edges that do not close a loop say so. + res = await b.build(req([...tube, surf('surfacePlanar', 'F2', { sketch: null, edges: topEdges.slice(0, 2) })])); + expect(res.status[2]).toMatchObject({ ok: false, error: expect.stringMatching(/closed loop/) }); + }); + + it('offsets faces of the solid and copies them at zero distance', async () => { + const b = new ModelBuilder(); + const box = [sketch('S1', rect(0, 0, 10, 10)), extrude('E1', 'S1', 10)]; + const res0 = await b.build(req(box)); + const top = faceRefOf(res0, (f) => f.name === 'E1:cap1'); + let res = await b.build(req([...box, surf('surfaceOffset', 'F1', { faces: [top], distance: 5 })])); + ok(res); + const off = surfaceFaces(res); + expect(off).toHaveLength(1); + expect(off[0].area).toBeCloseTo(100, 6); + expect(off[0].center[2]).toBeCloseTo(15, 6); + expect(b.massProperties()!.volume).toBeCloseTo(1000, 6); + // Flip offsets into the part; zero copies the face. + res = await b.build(req([...box, surf('surfaceOffset', 'F1', { faces: [top], distance: 5, flip: true })])); + expect(surfaceFaces(res)[0].center[2]).toBeCloseTo(5, 6); + res = await b.build(req([...box, surf('surfaceOffset', 'F1', { faces: [top], distance: 0 })])); + ok(res); + expect(surfaceFaces(res)[0].center[2]).toBeCloseTo(10, 6); + }); + + it('refuses to offset a curved face inward by its radius or more', async () => { + const b = new ModelBuilder(); + const cyl = [sketch('S1', circle(0, 0, 5)), extrude('E1', 'S1', 10)]; + const side = faceRefOf(await b.build(req(cyl)), (f) => f.type === 'cylinder'); + let res = await b.build(req([...cyl, surf('surfaceOffset', 'F1', { faces: [side], distance: 4, flip: true })])); + ok(res); + expect(surfaceFaces(res)[0].radius).toBeCloseTo(1, 6); + // 5 collapses the face onto the axis; 6 and 12 turned it inside out (radius 1 and 7). + for (const distance of [5, 6, 12]) { + res = await b.build(req([...cyl, surf('surfaceOffset', 'F1', { faces: [side], distance, flip: true })])); + expect(res.status[2]).toMatchObject({ ok: false, error: expect.stringMatching(/could not be offset/) }); + expect(surfaceFaces(res)).toHaveLength(0); + } + // Outward any distance is fine. + res = await b.build(req([...cyl, surf('surfaceOffset', 'F1', { faces: [side], distance: 12 })])); + ok(res); + expect(surfaceFaces(res)[0].radius).toBeCloseTo(17, 6); + }); + + it('fills a closed boundary of edges', async () => { + const b = new ModelBuilder(); + const tube = [sketch('S1', circle(0, 0, 5)), surf('surfaceExtrude', 'F1', { sketch: 'S1', depth: 10 })]; + let res = await b.build(req(tube)); + const rim = edgeRefOf(res, (e) => e.type === 'circle' && Math.abs(e.mid[2] - 10) < 1e-6); + expect(rim).toHaveLength(1); + res = await b.build(req([...tube, surf('surfaceFill', 'F2', { edges: rim })])); + ok(res); + expect(surfaceFaces(res).find((f) => f.body === 'F2')!.area).toBeCloseTo(Math.PI * 25, 2); + }); +}); + +describe('knit, thicken and cut', () => { + /** A 10 × 6 × 4 tube with both ends capped by planar surfaces. */ + async function cappedTube(b: ModelBuilder) { + const tube = [sketch('S1', rect(0, 0, 10, 6)), surf('surfaceExtrude', 'F1', { sketch: 'S1', depth: 4 })]; + const res = await b.build(req(tube)); + const bottom = edgeRefOf(res, (e) => Math.abs(e.mid[2]) < 1e-6); + const top = edgeRefOf(res, (e) => Math.abs(e.mid[2] - 4) < 1e-6); + return [...tube, surf('surfacePlanar', 'F2', { sketch: null, edges: bottom }), surf('surfacePlanar', 'F3', { sketch: null, edges: top })]; + } + + it('knits a closed set of surfaces into a solid of the right volume', async () => { + const b = new ModelBuilder(); + const parts = await cappedTube(b); + const res0 = await b.build(req(parts)); + const pick = (id: string) => faceRefOf(res0, (f) => f.body === id); + let res = await b.build(req([...parts, surf('surfaceKnit', 'K1', { faces: [pick('F1'), pick('F2'), pick('F3')], solid: true })])); + ok(res); + expect(b.hasBody).toBe(true); + expect(b.surfaceBodies()).toHaveLength(0); + expect(b.massProperties()!.volume).toBeCloseTo(240, 4); + expect(res.faces).toHaveLength(6); + // The solid's faces keep the surfaces' names. + expect(res.faces.map((f) => f.name)).toContain('F1:side:' + (parts[0] as SketchFeature).entities.find((e) => e.t === 'line')!.id); + // Without a cap the surfaces do not close. + res = await b.build(req([...parts, surf('surfaceKnit', 'K1', { faces: [pick('F1'), pick('F2')], solid: true })])); + expect(res.status[4]).toMatchObject({ ok: false, error: expect.stringMatching(/do not form a closed volume \(4 open edges\)/) }); + // The failed knit leaves the surfaces as they were. + expect(b.surfaceBodies()).toHaveLength(3); + // As a surface: one body of the three. + res = await b.build(req([...parts, surf('surfaceKnit', 'K1', { faces: [pick('F1'), pick('F2')] })])); + ok(res); + expect(b.surfaceBodies().map((x) => x.id).sort()).toEqual(['F3', 'K1']); + expect(surfaceFaces(res).filter((f) => f.body === 'K1')).toHaveLength(5); + // A tolerance as large as the part sews it into nothing. + res = await b.build(req([...parts, surf('surfaceKnit', 'K1', { faces: [pick('F1'), pick('F2')], tolerance: 1e6 })])); + expect(res.status[4]).toMatchObject({ ok: false, error: expect.stringMatching(/Use a smaller knit tolerance/) }); + }); + + it('knits a closed revolved surface (one face) into a solid, and thickens it', async () => { + const b = new ModelBuilder(); + const ball = [sketch('S1', [P('c0', 0, -5), P('c1', 0, 5), P('o', 0, 0), { id: 'arc', t: 'arc', c: 'o', a: 'c0', b: 'c1' }, P('x0', 0, -8), P('x1', 0, 8), L('cl', 'x0', 'x1', true)]), + surf('surfaceRevolve', 'R1', { sketch: 'S1', angle: 360 })]; + const face = faceRefOf(await b.build(req(ball)), (f) => f.body === 'R1'); + const res = await b.build(req([...ball, surf('surfaceKnit', 'K1', { faces: [face], solid: true })])); + ok(res); + expect(b.surfaceBodies()).toHaveLength(0); + expect(b.massProperties()!.volume).toBeCloseTo((4 / 3) * Math.PI * 125, 3); + // Thickened, it is a hollow ball: out, in or both ways. + const ballShell = (r0: number, r1: number) => (4 / 3) * Math.PI * (r1 ** 3 - r0 ** 3); + const sides = { front: ballShell(5, 6), back: ballShell(4, 5), both: ballShell(4.5, 5.5) }; + const got: number[] = []; + for (const side of ['front', 'back', 'both'] as const) { + ok(await b.build(req([...ball, surf('thicken', 'T1', { faces: [face], thickness: 1, side })]))); + got.push(b.massProperties()!.volume); + } + expect(got[2]).toBeCloseTo(sides.both, 3); + expect([got[0], got[1]].sort((x, y) => x - y)).toEqual([expect.closeTo(sides.back, 3), expect.closeTo(sides.front, 3)]); + const bad = await b.build(req([...ball, surf('thicken', 'T1', { faces: [face], thickness: 12, side: 'both' })])); + expect(bad.status[2]).toMatchObject({ ok: false, error: expect.stringMatching(/could not be thickened/) }); + }); + + it('thickens a surface into a solid of area × thickness, either side or both', async () => { + const b = new ModelBuilder(); + const base = [sketch('S1', rect(0, 0, 20, 10)), surf('surfacePlanar', 'F1', { sketch: 'S1' })]; + const res0 = await b.build(req(base)); + const face = faceRefOf(res0, (f) => f.body === 'F1'); + let res = await b.build(req([...base, surf('thicken', 'T1', { faces: [face], thickness: 2 })])); + ok(res); + expect(b.massProperties()!.volume).toBeCloseTo(400, 4); + expect(b.surfaceBodies()).toHaveLength(0); + expect(res.bbox!.min[2]).toBeCloseTo(0, 6); + expect(res.bbox!.max[2]).toBeCloseTo(2, 6); + res = await b.build(req([...base, surf('thicken', 'T1', { faces: [face], thickness: 2, side: 'back' })])); + expect(res.bbox!.min[2]).toBeCloseTo(-2, 6); + res = await b.build(req([...base, surf('thicken', 'T1', { faces: [face], thickness: 2, side: 'both' })])); + expect(res.bbox!.min[2]).toBeCloseTo(-1, 6); + expect(res.bbox!.max[2]).toBeCloseTo(1, 6); + expect(b.massProperties()!.volume).toBeCloseTo(400, 4); + }); + + it('thickens a lofted surface and a surface with sharp edges', async () => { + const b = new ModelBuilder(); + const plane: Feature = { id: 'PL', name: 'PL', type: 'plane', ref: { kind: 'base', plane: 'top' }, offset: 20, flip: false }; + const loft = [plane, sketch('S1', open('a', [[0, 0], [30, 0]]), { kind: 'base', plane: 'top' }), + sketch('S2', [P('b0', 0, 0), P('b1', 15, -5), P('b2', 30, 0), { id: 'bs', t: 'spline', pts: ['b0', 'b1', 'b2'] }], { kind: 'feature', id: 'PL' }), + surf('surfaceLoft', 'F1', { profiles: ['S1', 'S2'] })]; + let res = await b.build(req(loft)); + ok(res); + const area = surfaceArea(res); + res = await b.build(req([...loft, surf('thicken', 'T1', { faces: [faceRefOf(res, (f) => f.body === 'F1')], thickness: 1 })])); + ok(res); + expect(b.massProperties()!.volume / area).toBeGreaterThan(0.9); + expect(b.massProperties()!.volume / area).toBeLessThan(1.1); + // An L of two faces at a right angle. + const ell = [sketch('S1', open('a', [[0, 0], [20, 0], [20, 10]])), surf('surfaceExtrude', 'F1', { sketch: 'S1', depth: 5 })]; + const lRes = await b.build(req(ell)); + const lFace = faceRefOf(lRes, (f) => f.body === 'F1'); + res = await b.build(req([...ell, surf('thicken', 'T1', { faces: [lFace], thickness: 1 })])); + ok(res); + // 150 of slabs, less the 5 they overlap inside the corner or with the 5 of the corner filled outside it. + expect([145, 155].some((x) => Math.abs(b.massProperties()!.volume - x) < 1e-3)).toBe(true); + const front = b.massProperties()!.volume; + res = await b.build(req([...ell, surf('thicken', 'T1', { faces: [lFace], thickness: 1, side: 'back' })])); + ok(res); + expect(b.massProperties()!.volume).toBeCloseTo(300 - front, 3); + res = await b.build(req([...ell, surf('thicken', 'T1', { faces: [lFace], thickness: 1, side: 'both' })])); + ok(res); + expect(b.massProperties()!.volume).toBeCloseTo(150, 3); + // A closed rectangular tube, outward: 2 × (10 + 6) × 4 walls and the four corners. + const tube = [sketch('S1', rect(0, 0, 10, 6)), surf('surfaceExtrude', 'F1', { sketch: 'S1', depth: 4 })]; + res = await b.build(req(tube)); + res = await b.build(req([...tube, surf('thicken', 'T1', { faces: [faceRefOf(res, (f) => f.body === 'F1')], thickness: 1 })])); + ok(res); + expect([128 + 16, 128 - 16].some((x) => Math.abs(b.massProperties()!.volume - x) < 1e-3)).toBe(true); + }); + + it('thickens strongly curved surfaces by more or less than area × thickness', async () => { + const b = new ModelBuilder(); + // A dome of radius 5 (a quarter arc revolved about Y). + const dome = [sketch('S1', [P('c0', 0, -5), P('c1', 5, 0), P('o', 0, 0), { id: 'arc', t: 'arc', c: 'o', a: 'c0', b: 'c1' }, P('x0', 0, -8), P('x1', 0, 8), L('cl', 'x0', 'x1', true)]), + surf('surfaceRevolve', 'R1', { sketch: 'S1', angle: 360 })]; + const face = faceRefOf(await b.build(req(dome)), (f) => f.body === 'R1'); + const shell = (r0: number, r1: number) => (2 / 3) * Math.PI * (r1 ** 3 - r0 ** 3); + let res = await b.build(req([...dome, surf('thicken', 'T1', { faces: [face], thickness: 7 })])); + ok(res); + expect(b.massProperties()!.volume).toBeCloseTo(shell(5, 12), 3); + res = await b.build(req([...dome, surf('thicken', 'T1', { faces: [face], thickness: 4, side: 'back' })])); + ok(res); + expect(b.massProperties()!.volume).toBeCloseTo(shell(1, 5), 3); + // Inward past the centre cannot be thickened. + res = await b.build(req([...dome, surf('thicken', 'T1', { faces: [face], thickness: 6, side: 'back' })])); + expect(res.status[2]).toMatchObject({ ok: false, error: expect.stringMatching(/could not be thickened/) }); + // An open tube of radius 5 thickened 20 outward. + const tube = [sketch('S1', circle(0, 0, 5)), surf('surfaceExtrude', 'F1', { sketch: 'S1', depth: 10 })]; + const tf = faceRefOf(await b.build(req(tube)), (f) => f.body === 'F1'); + res = await b.build(req([...tube, surf('thicken', 'T1', { faces: [tf], thickness: 20, side: 'back' })])); + ok(res); + expect(b.massProperties()!.volume).toBeCloseTo(Math.PI * (25 ** 2 - 5 ** 2) * 10, 2); + }); + + it('cuts with a thickened surface', async () => { + const b = new ModelBuilder(); + const parts = [sketch('S1', rect(0, 0, 20, 20)), extrude('E1', 'S1', 10), + { ...sketch('S2', rect(5, 5, 15, 15)), plane: { kind: 'base', plane: 'front' } } as SketchFeature, surf('surfacePlanar', 'F1', { sketch: 'S2' })]; + // The surface lies on the bottom of the box and is thickened into it. + const res0 = await b.build(req(parts)); + const res = await b.build(req([...parts, surf('thicken', 'T1', { faces: [faceRefOf(res0, (f) => f.body === 'F1')], thickness: 3, cut: true })])); + ok(res); + expect(b.massProperties()!.volume).toBeCloseTo(4000 - 300, 3); + }); + + it('cuts the solid with a surface, keeping the side against its normal (or the other)', async () => { + const b = new ModelBuilder(); + const plane: Feature = { id: 'PL', name: 'PL', type: 'plane', ref: { kind: 'base', plane: 'front' }, offset: 3, flip: false }; + const parts = [sketch('S1', rect(0, 0, 10, 10)), extrude('E1', 'S1', 10), plane, sketch('S2', rect(-5, -5, 15, 15), { kind: 'feature', id: 'PL' }), surf('surfacePlanar', 'F1', { sketch: 'S2' })]; + const res0 = await b.build(req(parts)); + const face = faceRefOf(res0, (f) => f.body === 'F1'); + let res = await b.build(req([...parts, surf('surfaceCut', 'C1', { face })])); + ok(res); + // The surface faces +Z: the material above it goes. + expect(b.massProperties()!.volume).toBeCloseTo(300, 4); + // The surface stays, at the top of what is left. + expect(res.bbox!.max[2]).toBeCloseTo(3, 6); + expect(b.surfaceBodies()).toHaveLength(1); + res = await b.build(req([...parts, surf('surfaceCut', 'C1', { face, flip: true })])); + ok(res); + expect(b.massProperties()!.volume).toBeCloseTo(700, 4); + // The new face is named by the cut. + expect(res.faces.filter((f) => !f.body).some((f) => f.name.startsWith('C1:'))).toBe(true); + // A surface that misses the body. + const far: Feature = { id: 'PL', name: 'PL', type: 'plane', ref: { kind: 'base', plane: 'front' }, offset: 30, flip: false }; + res = await b.build(req([...parts.slice(0, 2), far, ...parts.slice(3), surf('surfaceCut', 'C1', { face: { ...face, sig: { ...face.sig, c: [5, 5, 30] } } })])); + expect(res.status[5]).toMatchObject({ ok: false, error: expect.stringMatching(/does not cut the body/) }); + }); +}); + +describe('trim, extend and delete face', () => { + const square = [sketch('S1', rect(0, 0, 20, 20)), surf('surfacePlanar', 'F1', { sketch: 'S1' })]; + // A plane at x = 5 (the Right plane faces +X). + const cutter: Feature = { id: 'PL', name: 'PL', type: 'plane', ref: { kind: 'base', plane: 'right' }, offset: 5, flip: false }; + + it('trims with a plane, keeping the side or the picked piece', async () => { + const b = new ModelBuilder(); + const res0 = await b.build(req([...square, cutter])); + const face = faceRefOf(res0, (f) => f.body === 'F1'); + let res = await b.build(req([...square, cutter, surf('surfaceTrim', 'T1', { faces: [face], tool: { kind: 'plane', plane: { kind: 'feature', id: 'PL' } } })])); + ok(res); + expect(surfaceArea(res)).toBeCloseTo(15 * 20, 4); + expect(b.surfaceBodies().map((x) => x.id)).toEqual(['T1']); + // The trimmed face keeps its name. + expect(surfaceFaces(res)[0].name).toBe('F1:p0'); + res = await b.build(req([...square, cutter, surf('surfaceTrim', 'T1', { faces: [face], tool: { kind: 'plane', plane: { kind: 'feature', id: 'PL' } }, flip: true })])); + expect(surfaceArea(res)).toBeCloseTo(5 * 20, 4); + res = await b.build(req([...square, cutter, surf('surfaceTrim', 'T1', { faces: [face], tool: { kind: 'plane', plane: { kind: 'feature', id: 'PL' } }, keep: [[2, 10, 0]] })])); + expect(surfaceArea(res)).toBeCloseTo(5 * 20, 4); + // A plane beyond the surface, on the side it keeps: it does not cross the surface, rather than "nothing left on that side". + const far = { ...cutter, offset: 50 } as Feature; + res = await b.build(req([...square, far, surf('surfaceTrim', 'T1', { faces: [face], tool: { kind: 'plane', plane: { kind: 'feature', id: 'PL' } } })])); + expect(res.status[3]).toMatchObject({ ok: false, error: expect.stringMatching(/does not cross the surface/) }); + }); + + it('trims with a sketch and with another surface', async () => { + const b = new ModelBuilder(); + const line = sketch('S2', open('t', [[-5, 10], [25, 10]])); + const res0 = await b.build(req([...square, line])); + const face = faceRefOf(res0, (f) => f.body === 'F1'); + let res = await b.build(req([...square, line, surf('surfaceTrim', 'T1', { faces: [face], tool: { kind: 'sketch', sketch: 'S2' }, keep: [[10, 15, 0]] })])); + ok(res); + expect(surfaceArea(res)).toBeCloseTo(200, 4); + expect(surfaceFaces(res)[0].center[1]).toBeCloseTo(15, 4); + // A vertical wall surface across the square at y = 5. + const wall = [sketch('S3', open('w', [[-5, 5], [25, 5]])), surf('surfaceExtrude', 'W1', { sketch: 'S3', depth: 10, end: 'midPlane' })]; + const res1 = await b.build(req([...square, ...wall])); + res = await b.build(req([...square, ...wall, surf('surfaceTrim', 'T1', { faces: [faceRefOf(res1, (f) => f.body === 'F1')], tool: { kind: 'surface', face: faceRefOf(res1, (f) => f.body === 'W1') }, keep: [[10, 1, 0]] })])); + ok(res); + expect(surfaceFaces(res).filter((f) => f.body === 'T1').reduce((a, f) => a + f.area, 0)).toBeCloseTo(100, 4); + }); + + it('trims a hole with a circle sketch, keeping one side or the other', async () => { + const b = new ModelBuilder(); + const hole = sketch('S2', circle(10, 10, 3)); + const face = faceRefOf(await b.build(req([...square, hole])), (f) => f.body === 'F1'); + // The square around the hole has the middle of its parameter range in the hole: + // both pieces were taken for the same side, and both kept (or neither, flipped). + const areas = []; + for (const flip of [false, true]) { + const res = await b.build(req([...square, hole, surf('surfaceTrim', 'T1', { faces: [face], tool: { kind: 'sketch', sketch: 'S2' }, flip })])); + ok(res); + expect(surfaceFaces(res)).toHaveLength(1); + areas.push(surfaceArea(res)); + } + expect(areas.sort((x, y) => x - y)[0]).toBeCloseTo(Math.PI * 9, 3); + expect(areas[1]).toBeCloseTo(400 - Math.PI * 9, 3); + }); + + it('extends a surface past an edge, the same surface or straight', async () => { + const b = new ModelBuilder(); + const res0 = await b.build(req(square)); + const right = edgeRefOf(res0, (e) => Math.abs(e.mid[0] - 20) < 1e-6); + expect(right).toHaveLength(1); + let res = await b.build(req([...square, surf('surfaceExtend', 'X1', { edges: right, distance: 5 })])); + ok(res); + expect(surfaceArea(res)).toBeCloseTo(25 * 20, 4); + expect(res.bbox!.max[0]).toBeCloseTo(25, 6); + res = await b.build(req([...square, surf('surfaceExtend', 'X1', { edges: right, distance: 5, mode: 'linear' })])); + ok(res); + expect(surfaceArea(res)).toBeCloseTo(25 * 20, 4); + expect(res.bbox!.max[0]).toBeCloseTo(25, 6); + }); + + it('extends a flat disc past its circular edge as a ring, not a rectangle', async () => { + const b = new ModelBuilder(); + const disc = [sketch('S1', circle(0, 0, 5)), surf('surfacePlanar', 'F1', { sketch: 'S1' })]; + const rim = edgeRefOf(await b.build(req(disc)), () => true); + // Same surface grew one side of the plane's range: a 12 × 10 rectangle. + let res = await b.build(req([...disc, surf('surfaceExtend', 'X1', { edges: rim, distance: 2 })])); + expect(res.status[2]).toMatchObject({ ok: false, error: expect.stringMatching(/Use Linear/) }); + // Linear made a flat sliver along one direction. + res = await b.build(req([...disc, surf('surfaceExtend', 'X1', { edges: rim, distance: 2, mode: 'linear' })])); + ok(res); + expect(surfaceArea(res)).toBeCloseTo(Math.PI * 49, 2); + expect(res.bbox!.min[0]).toBeCloseTo(-7, 3); + expect(res.bbox!.min[1]).toBeCloseTo(-7, 3); + expect(res.edges.filter((e) => e.faces.length === 2)).toHaveLength(1); + // A hole's edge grows into the hole, not over the face around it. + const holed = [sketch('S1', [...rect(-10, -10, 10, 10), ...circle(0, 0, 4)]), surf('surfacePlanar', 'F1', { sketch: 'S1' })]; + const hole = edgeRefOf(await b.build(req(holed)), (e) => e.type === 'circle'); + res = await b.build(req([...holed, surf('surfaceExtend', 'X1', { edges: hole, distance: 2, mode: 'linear' })])); + ok(res); + expect(surfaceArea(res)).toBeCloseTo(400 - Math.PI * 4, 2); + }); + + it('extends or offsets an edge or face named twice (a hand-edited file) once', async () => { + const b = new ModelBuilder(); + const res0 = await b.build(req(square)); + const right = edgeRefOf(res0, (e) => Math.abs(e.mid[0] - 20) < 1e-6); + // Twice made two overlapping strips; thousands took minutes. + let res = await b.build(req([...square, surf('surfaceExtend', 'X1', { edges: Array(2000).fill(right[0]), distance: 5, mode: 'linear' })])); + ok(res); + expect(surfaceFaces(res).map((f) => f.area).sort((x, y) => x - y)).toEqual([expect.closeTo(100, 4), expect.closeTo(400, 4)]); + const face = faceRefOf(res0, (f) => f.body === 'F1'); + res = await b.build(req([...square, surf('surfaceOffset', 'O1', { faces: [face, face], distance: 2 })])); + ok(res); + expect(surfaceFaces(res).filter((f) => f.body === 'O1')).toHaveLength(1); + }); + + it('deletes faces of the solid into a surface body, or patches the hole', async () => { + const b = new ModelBuilder(); + const box = [sketch('S1', rect(0, 0, 10, 10)), extrude('E1', 'S1', 10)]; + const res0 = await b.build(req(box)); + const top = faceRefOf(res0, (f) => f.name === 'E1:cap1'); + let res = await b.build(req([...box, surf('deleteFace', 'D1', { faces: [top] })])); + ok(res); + expect(b.hasBody).toBe(false); + expect(surfaceFaces(res)).toHaveLength(5); + expect(surfaceFaces(res).map((f) => f.name)).toContain('E1:cap0'); + res = await b.build(req([...box, surf('deleteFace', 'D1', { faces: [top], mode: 'patch' })])); + ok(res); + expect(b.massProperties()!.volume).toBeCloseTo(1000, 3); + }); +}); + +describe('surfaces with the rest of the part', () => { + it('sketches on a planar surface face and extrudes from it', async () => { + const b = new ModelBuilder(); + const plane: Feature = { id: 'PL', name: 'PL', type: 'plane', ref: { kind: 'base', plane: 'front' }, offset: 7, flip: false }; + const parts = [plane, sketch('S1', rect(0, 0, 20, 20), { kind: 'feature', id: 'PL' }), surf('surfacePlanar', 'F1', { sketch: 'S1' })]; + const res0 = await b.build(req(parts)); + const face = faceRefOf(res0, (f) => f.body === 'F1'); + const res = await b.build(req([...parts, sketch('S2', rect(2, 2, 6, 6), { kind: 'face', face }), extrude('E1', 'S2', 3)])); + ok(res); + expect(b.massProperties()!.volume).toBeCloseTo(48, 6); + expect(res.bbox!.min[2]).toBeCloseTo(7, 6); + expect(res.bbox!.max[2]).toBeCloseTo(10, 6); + }); + + it('says a surface face or edge picked for a solid feature is on a surface', async () => { + const b = new ModelBuilder(); + const parts = [sketch('S1', rect(0, 0, 10, 10)), extrude('E1', 'S1', 10), sketch('S2', open('a', [[20, 0], [30, 0], [30, 10]])), surf('surfaceExtrude', 'F1', { sketch: 'S2', depth: 10 })]; + const res0 = await b.build(req(parts)); + const edges = edgeRefOf(res0, (e) => e.body === 'F1' && e.faces.length === 2); + const face = faceRefOf(res0, (f) => f.body === 'F1'); + let res = await b.build(req([...parts, { id: 'FL', name: 'FL', type: 'fillet', edges, faces: [], radius: 1 }])); + expect(res.status[4]).toMatchObject({ ok: false, error: expect.stringMatching(/is on a surface body, not the solid/) }); + res = await b.build(req([...parts, { id: 'SH', name: 'SH', type: 'shell', faces: [face], thickness: 1, outward: false }])); + expect(res.status[4]).toMatchObject({ ok: false, error: expect.stringMatching(/is on a surface body, not the solid/) }); // Surface features are not seeds of a mirror or a pattern, each said in its own words. + res = await b.build(req([...parts, { id: 'M1', name: 'M1', type: 'mirror', seeds: ['F1'], plane: { kind: 'base', plane: 'right' } }])); + expect(res.status[4]).toMatchObject({ ok: false, error: expect.stringMatching(/^F1 cannot be mirrored/) }); + res = await b.build(req([...parts, { id: 'P1', name: 'P1', type: 'linearPattern', seeds: ['F1'], dir1: { ref: { kind: 'base', axis: 'x' }, spacing: 50, count: 2, flip: false }, dir2: null }])); + expect(res.status[4]).toMatchObject({ ok: false, error: expect.stringMatching(/^F1 cannot be patterned/) }); + }); + + it('exports surface bodies to STEP as shells beside the solid', async () => { + const b = new ModelBuilder(); + await b.build(req([sketch('S1', rect(0, 0, 10, 10)), extrude('E1', 'S1', 10), sketch('S2', open('a', [[0, 0], [20, 5]])), surf('surfaceExtrude', 'F1', { sketch: 'S2', depth: 30 })])); + const text = new TextDecoder().decode(b.exportStep('Part')); + expect(text).toMatch(/MANIFOLD_SOLID_BREP|BREP_WITH_VOIDS/); + expect(text).toMatch(/OPEN_SHELL|SHELL_BASED_SURFACE_MODEL/); + // Mass properties stay those of the solid. + const mp = b.massProperties()!; + expect(mp.volume).toBeCloseTo(1000, 6); + expect(mp.area).toBeCloseTo(600, 6); + expect(mp.surfaceArea).toBeCloseTo(Math.hypot(20, 5) * 30, 4); + }); + + it('leaves hidden surface bodies out of drawing views', async () => { + const b = new ModelBuilder(); + await b.build(req([sketch('S1', rect(0, 0, 10, 10)), extrude('E1', 'S1', 10), sketch('S2', open('a', [[20, 0], [40, 0]])), surf('surfaceExtrude', 'F1', { sketch: 'S2', depth: 10 })])); + const view = { id: 'v', dir: [0, 0, 1] as [number, number, number], x: [1, 0, 0] as [number, number, number], hidden: false }; + expect(b.project([view])[0].bounds![2]).toBeCloseTo(40, 3); + const [hidden] = b.project([{ ...view, hideSurfaces: ['F1'] }]); + expect(hidden.bounds![2]).toBeCloseTo(10, 3); + // STEP keeps them. + expect(new TextDecoder().decode(b.exportStep())).toMatch(/OPEN_SHELL|SHELL_BASED_SURFACE_MODEL/); + }); + + it('measures to a surface face by its index after the solid faces', async () => { + const b = new ModelBuilder(); + const res = await b.build(req([sketch('S1', rect(0, 0, 10, 10)), extrude('E1', 'S1', 10), sketch('S2', open('a', [[20, 0], [20, 10]])), surf('surfaceExtrude', 'F1', { sketch: 'S2', depth: 10 })])); + const si = res.faces.findIndex((f) => f.body === 'F1'); + const ti = res.faces.findIndex((f) => f.name.startsWith('E1:side:') && Math.abs(f.center[0] - 10) < 1e-6); + expect(si).toBe(6); + expect(b.measure({ kind: 'face', index: si }, { kind: 'face', index: ti }).distance).toBeCloseTo(10, 6); + }); + + it('builds a part without surface features exactly as before, after building one with them', async () => { + for (const doc of [flangeExample(), bracketExample()]) { + const fresh = new ModelBuilder(); + const a = await fresh.build(req(doc.features)); + const used = new ModelBuilder(); + await used.build(req([...doc.features, sketch('SX', open('z', [[0, 0], [50, 50]])), surf('surfaceExtrude', 'FX', { sketch: 'SX', depth: 20 })])); + const b = await used.build(req(doc.features)); + expect(b.surfaces).toBeUndefined(); + expect(a.surfaces).toBeUndefined(); + expect(b.faces).toEqual(a.faces); + expect(b.edges).toEqual(a.edges); + expect(b.bbox).toEqual(a.bbox); + expect(b.status).toEqual(a.status); + for (const k of ['positions', 'normals', 'indices', 'vertexFace', 'edgePositions', 'edgeIds', 'vertices'] as const) expect(Array.from(b.mesh![k])).toEqual(Array.from(a.mesh![k])); + expect(a.faces.some((f) => 'body' in f)).toBe(false); + expect(used.massProperties()!.surfaceArea).toBeUndefined(); + } + }); + + it('shows the same surfaces after an edit of the solid as when built afresh (their meshes are kept)', async () => { + const parts = (depth: number) => [sketch('S1', open('a', [[0, 0], [20, 5], [40, 0]])), surf('surfaceExtrude', 'F1', { sketch: 'S1', depth: 30 }), + sketch('S2', rect(0, -20, 10, -10, 'r')), extrude('E1', 'S2', depth)]; + const used = new ModelBuilder(); + await used.build(req(parts(5))); + const a = await used.build(req(parts(8))); + const b = await new ModelBuilder().build(req(parts(8))); + expect(a.faces).toEqual(b.faces); + expect(a.edges).toEqual(b.edges); + expect(a.bbox).toEqual(b.bbox); + for (const k of ['positions', 'normals', 'indices', 'vertexFace', 'edgePositions', 'edgeIds', 'vertices'] as const) expect(Array.from(a.mesh![k])).toEqual(Array.from(b.mesh![k])); + }); + + it('previews a surface feature over the part, and a thicken in place of it', async () => { + const b = new ModelBuilder(); + const base = [sketch('S1', rect(0, 0, 20, 10)), surf('surfacePlanar', 'F1', { sketch: 'S1' })]; + let res = await b.build(req([base[0]], { preview: base[1] })); + expect(res.previewKind).toBe('tool'); + expect(res.preview!.indices.length).toBeGreaterThan(0); + expect(res.surfaces).toBeUndefined(); + res = await b.build(req(base)); + const face = faceRefOf(res, (f) => f.body === 'F1'); + res = await b.build(req(base, { preview: surf('thicken', 'T1', { faces: [face], thickness: 2 }) })); + expect(res.previewKind).toBe('body'); + expect(res.previewError).toBeUndefined(); + // A failing preview says why. + res = await b.build(req(base, { preview: surf('surfaceKnit', 'K1', { faces: [face], solid: true }) })); + expect(res.previewError).toMatch(/do not form a closed volume/); + }); + + it('keeps the surfaces of the step before a failed surface feature', async () => { + const b = new ModelBuilder(); + const res = await b.build(req([sketch('S1', rect(0, 0, 20, 10)), surf('surfacePlanar', 'F1', { sketch: 'S1' }), + surf('surfaceOffset', 'O1', { faces: [] }), surf('surfaceExtrude', 'X1', { sketch: 'S1', depth: 3 })])); + expect(res.status[2]).toMatchObject({ ok: false, error: 'Select faces to offset' }); + expect(res.status[3].ok).toBe(true); + expect(b.surfaceBodies().map((x) => x.id)).toEqual(['F1', 'X1']); + // Only surfaces: STEP holds them. + expect(new TextDecoder().decode(b.exportStep())).toMatch(/OPEN_SHELL|SHELL_BASED_SURFACE_MODEL|ADVANCED_FACE/); + // STL does not, and says why. + expect(() => b.exportStl(1)).toThrow(/STL files hold solids only/); + }); + + it('lists references, consumed sketches and validates surface features from files', () => { + const face: FaceRef = { name: 'F1:p0', sig: { type: 'plane', c: [0, 0, 0], area: 1 } }; + const t = surf('thicken', 'T1', { faces: [face] }); + expect(dependencies(t)).toEqual(['F1']); + const trim = surf('surfaceTrim', 'T2', { faces: [face], tool: { kind: 'sketch', sketch: 'S9' } }); + expect(consumedSketches(trim)).toEqual(['S9']); + expect(dependencies(trim).sort()).toEqual(['F1', 'S9']); + expect(validFeature(trim)).toBe(true); + expect(validFeature({ ...trim, keep: [[1, 2]] } as unknown as Feature)).toBe(false); + expect(validFeature({ ...t, faces: [{}] } as unknown as Feature)).toBe(false); + expect(validFeature({ ...surf('surfaceExtrude', 'E', { sketch: 's' }), end: 'throughAll' } as unknown as Feature)).toBe(false); + }); +}); + +describe('surface features in files', () => { + const face: FaceRef = { name: 'F1:p0', sig: { type: 'plane', c: [10, 10, 0], area: 400 } }; + const edge: EdgeRef = { name: 'F1:p0#3', sig: { type: 'line', m: [20, 10, 0], len: 20 } }; + /** One of each surface feature, every field off its default. */ + const all = (): Feature[] => [ + sketch('S1', rect(0, 0, 20, 20, 'q')), + surf('surfacePlanar', 'F1', { sketch: 'S1' }), + surf('surfaceExtrude', 'F2', { sketch: 'S1', end: 'blind', depth: '5 + 1', flip: true, dir2: { depth: 2 } }), + surf('surfaceRevolve', 'F3', { sketch: 'S1', axis: { kind: 'base', axis: 'y' }, end: 'midPlane', angle: 90, flip: true }), + surf('surfaceSweep', 'F4', { profile: 'S1', path: 'S1' }), + surf('surfaceLoft', 'F5', { profiles: ['S1', 'S1'], ruled: true }), + surf('surfacePlanar', 'F6', { sketch: null, edges: [edge] }), + surf('surfaceOffset', 'F7', { faces: [face], distance: 0, flip: true }), + surf('surfaceFill', 'F8', { edges: [edge] }), + surf('surfaceTrim', 'F9', { faces: [face], tool: { kind: 'plane', plane: { kind: 'base', plane: 'right' } }, keep: [[1, 2, 3]], flip: true }), + surf('surfaceTrim', 'F10', { faces: [face], tool: { kind: 'surface', face } }), + surf('surfaceExtend', 'F11', { edges: [edge], distance: 3, mode: 'linear' }), + surf('surfaceKnit', 'F12', { faces: [face], tolerance: 0.2, solid: true }), + surf('thicken', 'F13', { faces: [face], thickness: 1.5, side: 'both', cut: true }), + surf('surfaceCut', 'F14', { face, flip: true }), + surf('deleteFace', 'F15', { faces: [face], mode: 'patch' }), + ]; + const file = (features: unknown[]) => JSON.stringify({ ...newDocument('P'), features }); + + it('saves and reopens every surface field as it was, and rebuilds the same', async () => { + const doc = { ...newDocument('P'), features: all() }; + const back = parseDocument(serializeDocument(doc)); + expect(back.features).toEqual(doc.features); + const a = await new ModelBuilder().build(req(doc.features)); + const b = await new ModelBuilder().build(req(back.features)); + expect(b.status).toEqual(a.status); + }); + + it('rejects damaged surface fields, and builds missing references as errors', async () => { + const bad = (patch: Record, i = 2) => { + const fs = all() as unknown as Record[]; + fs[i] = { ...fs[i], ...patch }; + return () => parseDocument(file(fs)); + }; + expect(bad({ type: 'surfaceWarp' })).toThrow(/damaged/); + // NaN is written as null. + expect(bad({ depth: null })).toThrow(/damaged/); + expect(bad({ distance: null }, 7)).toThrow(/damaged/); + expect(bad({ keep: [[1, 2]] }, 9)).toThrow(/damaged/); + expect(bad({ tool: { kind: 'surface' } }, 10)).toThrow(/damaged/); + expect(bad({ side: 'inside' }, 13)).toThrow(/damaged/); + expect(bad({ faces: 'F1:p0' }, 12)).toThrow(/damaged/); + // References to surfaces that are not there open, and their features say so. + const fs = [sketch('S1', rect(0, 0, 20, 20, 'q')), surf('thicken', 'T1', { faces: [{ ...face, name: 'F99:p0' }] }), surf('surfaceKnit', 'K1', { faces: [face] })]; + const doc = parseDocument(file(fs)); + const res = await new ModelBuilder().build(req(doc.features)); + expect(res.status[1]).toMatchObject({ ok: false, error: expect.stringMatching(/no longer exists|Select/) }); + expect(res.status[2]).toMatchObject({ ok: false, error: expect.stringMatching(/no longer exists/) }); + }); +}); diff --git a/src/parametric/tests/ui.test.ts b/src/parametric/tests/ui.test.ts index 05680a1554..5d94062107 100644 --- a/src/parametric/tests/ui.test.ts +++ b/src/parametric/tests/ui.test.ts @@ -235,6 +235,10 @@ describe('PropertyManager number fields', () => { expect(parseParam('2.6', 'count', ctx())).toMatchObject({ ok: true, value: 3 }); expect(parseParam('nope', 'length', ctx()).ok).toBe(false); expect(paramText(25.4, 'length', ctx('IPS'))).toBe('1'); + // Inch values converted from millimetres read as typed, not with float noise. + for (const v of ['0.048', '0.09', '0.06', '0.036', '1.1']) expect(paramText(Number(v) * 25.4, 'length', ctx('IPS'))).toBe(v); + expect(paramText(1.524, 'length', ctx('IPS'))).toBe('0.06'); + expect(paramText(0.1 + 0.2, 'length', ctx())).toBe('0.3'); expect(paramText('=Len', 'length', ctx())).toBe('=Len'); }); diff --git a/src/parametric/tests/weldment-profiles.test.ts b/src/parametric/tests/weldment-profiles.test.ts new file mode 100644 index 0000000000..6f6426ad0a --- /dev/null +++ b/src/parametric/tests/weldment-profiles.test.ts @@ -0,0 +1,210 @@ +// Weldment profile library: generated cross-sections against published +// section areas, closed outlines, placement and the cut list grouping. +import { describe, expect, it } from 'vitest'; +import { + type PSeg, type WeldProfileType, type WeldStandard, PROFILE_LIBRARY, WELD_STANDARDS, WELD_TYPES, findProfile, outlineBox, outlineMax, placeProfile, profileShape, + profileSizes, sectionProps, +} from '../src/model/weldment-profiles'; +import { type WeldMemberInfo, cutListCsv, cutListRows, memberOfFace, newEndCap, newGusset, newStructuralMember, newTrimExtend, newWeldBead, weldmentCutList } from '../src/model/weldments'; +import { newDocument, parseDocument, serializeDocument } from '../src/model/document'; +import { dependencies } from '../src/model/features'; + +const area = (standard: string, type: string, size: string) => { + const p = findProfile(standard, type, size); + if (!p) throw new Error(`no ${standard} ${type} ${size}`); + return sectionProps(profileShape(type, p.dims)).area; +}; +const IN2 = 25.4 * 25.4; +/** lb/ft of steel from an area in in² (0.2836 lb/in³). */ +const lbPerFt = (mm2: number) => (mm2 / IN2) * 12 * 0.2836; + +const ends = (s: PSeg): [[number, number], [number, number]] => + s.k === 'line' ? [s.a, s.b] : [[s.c[0] + s.r * Math.cos(s.a0), s.c[1] + s.r * Math.sin(s.a0)], [s.c[0] + s.r * Math.cos(s.a1), s.c[1] + s.r * Math.sin(s.a1)]]; + +describe('profile library', () => { + it('matches published areas of metric sections (cm²)', () => { + // EN 10219-2 hollow sections. + expect(area('iso', 'squareTube', '40x40x3') / 100).toBeCloseTo(4.21, 2); + expect(area('iso', 'squareTube', '100x100x5') / 100).toBeCloseTo(18.4, 1); + expect(area('iso', 'rectTube', '60x40x3') / 100).toBeCloseTo(5.41, 2); + expect(area('iso', 'rectTube', '100x50x4') / 100).toBeCloseTo(10.9, 1); + expect(area('iso', 'pipe', '48.3x3.2') / 100).toBeCloseTo(4.53, 2); + expect(area('iso', 'pipe', '114.3x3.6') / 100).toBeCloseTo(12.5, 1); + // EN 10056-1 equal angles. + expect(area('iso', 'angle', '50x50x5') / 100).toBeCloseTo(4.8, 1); + expect(area('iso', 'angle', '60x60x6') / 100).toBeCloseTo(6.91, 2); + expect(area('iso', 'angle', '100x100x10') / 100).toBeCloseTo(19.2, 1); + // EN 10279 UPE and EN 10365 IPE / HE A. + expect(area('iso', 'channel', 'UPE100') / 100).toBeCloseTo(12.5, 1); + expect(area('iso', 'channel', 'UPE200') / 100).toBeCloseTo(29.0, 1); + expect(area('iso', 'beam', 'IPE200') / 100).toBeCloseTo(28.5, 1); + expect(area('iso', 'beam', 'IPE300') / 100).toBeCloseTo(53.8, 1); + expect(area('iso', 'beam', 'HEA100') / 100).toBeCloseTo(21.2, 1); + expect(area('iso', 'flatBar', '40x5')).toBeCloseTo(200, 9); + expect(area('iso', 'roundBar', '20')).toBeCloseTo(Math.PI * 100, 9); + }); + + it('matches published weights and areas of inch sections', () => { + // AISC: HSS weights per foot (nominal wall). + expect(lbPerFt(area('ansi', 'squareTube', '2x2x1/8'))).toBeCloseTo(3.05, 1); + expect(lbPerFt(area('ansi', 'squareTube', '4x4x1/4'))).toBeCloseTo(12.21, 1); + expect(lbPerFt(area('ansi', 'rectTube', '4x2x1/4'))).toBeCloseTo(8.81, 1); + // ASME B36.10M standard pipe. + expect(lbPerFt(area('ansi', 'pipe', '2'))).toBeCloseTo(3.65, 1); + expect(lbPerFt(area('ansi', 'pipe', '4'))).toBeCloseTo(10.79, 1); + // AISC W shapes, in². + expect(area('ansi', 'beam', 'W8x18') / IN2).toBeCloseTo(5.26, 2); + expect(area('ansi', 'beam', 'W6x9') / IN2).toBeCloseTo(2.68, 2); + // Channels are modelled without their fillets: within 2 % of the tables. + expect(area('ansi', 'channel', 'C8x11.5') / IN2 / 3.37).toBeGreaterThan(0.98); + expect(area('ansi', 'channel', 'C8x11.5') / IN2 / 3.37).toBeLessThan(1); + expect(area('ansi', 'angle', '2x2x1/4') / IN2).toBeCloseTo(0.9375, 6); + }); + + it('finds no profile for names that are not in the library', () => { + for (const [standard, type] of [['toString', 'name'], ['constructor', 'name'], ['iso', 'constructor'], ['iso', '__proto__'], ['din', 'pipe']]) { + expect(findProfile(standard, type, 'x')).toBeNull(); + expect(profileSizes(standard as WeldStandard, type as WeldProfileType)).toEqual([]); + } + }); + + it('generates closed outlines for every size, with a positive area', () => { + for (const { value: std } of WELD_STANDARDS) { + for (const { value: type } of WELD_TYPES) { + const sizes = PROFILE_LIBRARY[std][type]; + expect(sizes.length).toBeGreaterThan(3); + for (const size of sizes) { + const sh = profileShape(type, size.dims); + const a = sectionProps(sh).area; + expect(a, `${std} ${type} ${size.id}`).toBeGreaterThan(0); + for (const loop of [sh.outer, ...sh.holes]) { + loop.forEach((s, i) => { + const next = loop[(i + 1) % loop.length]; + const [, b] = ends(s); + const [a0] = ends(next); + expect(Math.hypot(b[0] - a0[0], b[1] - a0[1]), `${std} ${type} ${size.id} segment ${i}`).toBeLessThan(1e-9); + }); + } + expect(new Set(sizes.map((x) => x.id)).size).toBe(sizes.length); + } + } + } + }); + + it('finds the centroid of an angle', () => { + // EN 10056-1: L 50 x 50 x 5 has its centroid 1.40 cm from the heel. + const p = findProfile('iso', 'angle', '50x50x5')!; + const c = sectionProps(profileShape('angle', p.dims)).centroid; + expect(c[0] / 10).toBeCloseTo(1.4, 1); + expect(c[1]).toBeCloseTo(c[0], 9); + }); + + it('places a profile by pierce point, rotation and mirror', () => { + const p = findProfile('iso', 'rectTube', '60x40x3')!; + const sh = profileShape('rectTube', p.dims); + const box = (s: typeof sh) => outlineBox(s.outer); + const plain = box(placeProfile(sh, { pierce: 'bl', rotation: 0, mirror: false })); + expect([...plain.min, ...plain.max].map((v) => v + 0)).toEqual([0, 0, 40, 60]); + const turned = box(placeProfile(sh, { pierce: 'bl', rotation: 90, mirror: false })); + expect(turned.min[0]).toBeCloseTo(-60, 9); + expect(turned.max[1]).toBeCloseTo(40, 9); + const mirrored = placeProfile(sh, { pierce: 'bl', rotation: 0, mirror: true }); + expect(box(mirrored).min[0]).toBeCloseTo(-40, 9); + // Mirroring keeps the outer loop counter-clockwise (positive area). + expect(sectionProps(mirrored).area).toBeCloseTo(sectionProps(sh).area, 9); + // The extreme of an arc is found between its ends. + expect(outlineMax([{ k: 'arc', c: [0, 0], r: 2, a0: 0, a1: Math.PI }], [0, 1])).toBeCloseTo(2, 12); + expect(outlineMax([{ k: 'arc', c: [0, 0], r: 2, a0: Math.PI, a1: Math.PI / 2 }], [1, 1])).toBeCloseTo(2, 12); + }); +}); + +describe('cut list', () => { + const m = (member: string, length: number, a1: number, a2: number, desc = 'SQ TUBE 40 x 40 x 3'): WeldMemberInfo => ({ + feature: 'f1', member, group: 0, standard: 'iso', profile: 'squareTube', size: '40x40x3', desc, length, angle1: a1, angle2: a2, volume: 420.8 * length, area: 420.8, + }); + + it('groups identical members within tolerance, either way round', () => { + const list = weldmentCutList({ material: { name: 'Plain Carbon Steel', density: 7800 } }, [ + m('s/a', 500, 0, 45), m('s/b', 500.004, 45, 0), m('s/c', 500, 45, 45), m('s/d', 300, 0, 0), m('s/e', 300, 0, 0, 'PIPE 48.3 x 3.2'), + ]); + expect(list.items.map((it) => [it.description, it.quantity, it.length, it.angle1, it.angle2])).toEqual([ + ['PIPE 48.3 x 3.2', 1, 300, 0, 0], + ['SQ TUBE 40 x 40 x 3', 2, 500, 0, 45], + ['SQ TUBE 40 x 40 x 3', 1, 500, 45, 45], + ['SQ TUBE 40 x 40 x 3', 1, 300, 0, 0], + ]); + expect(list.items.map((it) => it.item)).toEqual([1, 2, 3, 4]); + expect(list.count).toBe(5); + expect(list.items[1].totalMass).toBeCloseTo(420.8 * 1000.004 * 1e-9 * 7800, 9); + expect(list.material).toBe('Plain Carbon Steel'); + }); + + it('keeps curved pieces bent to different radii apart, and gives their radius', () => { + // A quarter circle of radius 200 and an eighth of radius 400 are both 314.16 long. + const arc = (member: string, r: number, sweep: number): WeldMemberInfo => ({ ...m(member, r * sweep, 0, 0), curved: true, radius: r }); + const list = weldmentCutList({ material: null }, [arc('s/a', 200, Math.PI / 2), arc('s/b', 400, Math.PI / 4), arc('s/c', 200, Math.PI / 2)]); + expect(list.items.map((it) => [it.quantity, it.radius])).toEqual([[2, 200], [1, 400]]); + expect(cutListRows(list, 'MMGS', 1).rows.map((r) => r[2])).toEqual(['SQ TUBE 40 x 40 x 3 (curved, R 200.0)', 'SQ TUBE 40 x 40 x 3 (curved, R 400.0)']); + }); + + it('writes CSV in the part units', () => { + const list = weldmentCutList({ material: null }, [m('s/a', 254, 0, 0, 'HSS 2 x 2 x 1/8, "A500"')]); + const csv = cutListCsv(list, 'IPS', 3).split('\r\n'); + expect(csv[0]).toBe('Item,Qty,Description,Length (in),Angle 1 (°),Angle 2 (°),Total length (in),Mass each (lb),Total mass (lb)'); + expect(csv[1].startsWith('1,1,"HSS 2 x 2 x 1/8, ""A500""",10.000,0.00,0.00,10.000,')).toBe(true); + expect(csv[2].startsWith(',1,Total,,,,10.000,,')).toBe(true); + // Masses from before a later fillet or shell say so. + expect(cutListRows({ ...list, massApproximate: true }, 'IPS', 3).header.slice(-2)).toEqual(['Mass each (lb, before later changes)', 'Total mass (lb, before later changes)']); + }); + + it('reads the member of a face name', () => { + expect(memberOfFace('f7:f3/l2:4')).toEqual({ feature: 'f7', member: 'f3/l2' }); + expect(memberOfFace('f7:f3/l2:4#1')).toEqual({ feature: 'f7', member: 'f3/l2' }); + expect(memberOfFace('f7:cap1')).toBeNull(); + expect(memberOfFace('f7:f3/l2:4|f8:cap0')).toBeNull(); + }); +}); + +describe('weldment features in part files', () => { + const doc = (features: unknown[]) => JSON.stringify({ ...newDocument('W'), features }); + const sm = { ...newStructuralMember('f2', 'Structural Member1', [[{ sketch: 'f1', entity: 'l1' }]]), rotation: '=Angle' }; + + it('opens weldment features and keeps their values', () => { + const d = parseDocument(doc([{ id: 'f1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: [], constraints: [] }, sm, + newTrimExtend('f3', 'Trim/Extend1'), newEndCap('f4', 'End Cap1', 3), newGusset('f5', 'Gusset1', 50, 5)])); + expect(d.features.map((f) => f.type)).toEqual(['sketch', 'structuralMember', 'trimExtend', 'endCap', 'gusset']); + expect((d.features[1] as typeof sm).rotation).toBe('=Angle'); + }); + + it('saves and reopens every weldment field', () => { + const face = (name: string) => ({ name, sig: { type: 'plane', c: [1, 2, 3] as [number, number, number], n: [0, 0, 1] as [number, number, number], area: 12 } }); + const features = [ + { id: 'f1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: [], constraints: [] }, + { + ...newStructuralMember('f2', 'Frame', [[{ sketch: 'f1', entity: 'l1' }], [{ sketch: 'f1', entity: 'l2' }, { sketch: 'f1', entity: 'a3' }]]), + standard: 'ansi', profile: 'beam', size: 'W6x15', rotation: 30, mirror: true, pierce: 'tl', corner: 'butt2', gap: 1.5, trimGroups: false, gap2: '=G', + }, + { ...newTrimExtend('f3', 'Trim'), members: [{ feature: 'f2', member: 'f1/l1' }], boundary: 'members', faces: [face('f2:f1/l2:3')], boundaryMembers: [{ feature: 'f2', member: 'f1/l2' }], allowExtension: false, coped: true, gap: 2 }, + { ...newEndCap('f4', 'Cap', 3), faces: [face('f2:f1/l1:0')], offset: 1, inward: true }, + { ...newGusset('f5', 'Gusset', 50, 5), faces: [face('f2:f1/l1:1'), face('f2:f1/l2:2')], shape: 'polygonal', d1: 60, d2: 40, d3: 20, location: 'side2', chamfer: 4 }, + { ...newWeldBead('f6', 'Bead', 4), edges: [{ name: 'f2:f1/l1:1|f2:f1/l2:2', sig: { type: 'line', m: [0, 0, 0] as [number, number, number], len: 40 } }] }, + ]; + const d = parseDocument(serializeDocument({ ...newDocument('W', 'IPS'), features: features as never })); + expect(d.units).toBe('IPS'); + expect(d.features).toEqual(features); + }); + + it('rejects damaged weldment features', () => { + expect(() => parseDocument(doc([{ ...sm, groups: [{ segments: [{ sketch: 'f1' }] }] }]))).toThrow(/damaged/); + expect(() => parseDocument(doc([{ ...sm, groups: 'x' }]))).toThrow(/damaged/); + expect(() => parseDocument(doc([{ ...sm, corner: 'weld' }]))).toThrow(/damaged/); + expect(() => parseDocument(doc([{ ...newTrimExtend('f3', 'T'), members: [{ member: 'a/b' }] }]))).toThrow(/damaged/); + expect(() => parseDocument(doc([{ ...newGusset('f5', 'G', 1, 1), faces: [{}] }]))).toThrow(/damaged/); + }); + + it('lists the sketches and members a weldment feature depends on', () => { + expect(dependencies(sm)).toEqual(['f1']); + const t = { ...newTrimExtend('f3', 'T'), members: [{ feature: 'f2', member: 'f1/l1' }], faces: [{ name: 'f9:cap1', sig: { type: 'plane', c: [0, 0, 0] as [number, number, number], area: 1 } }] }; + expect(dependencies(t).sort()).toEqual(['f2', 'f9']); + }); +}); diff --git a/src/parametric/tests/weldments.test.ts b/src/parametric/tests/weldments.test.ts new file mode 100644 index 0000000000..5a5deb1d37 --- /dev/null +++ b/src/parametric/tests/weldments.test.ts @@ -0,0 +1,488 @@ +// Weldments on the real OpenCascade kernel: structural members, corner +// treatments, trimming, end caps, gussets and the cut list. +import { beforeAll, describe, expect, it } from 'vitest'; +import init from 'replicad-opencascadejs'; +import { ModelBuilder } from '../src/kernel/build'; +import { type Sh, isValid, setOc } from '../src/kernel/occ'; +import type { Feature, SegmentRef, SkEntity, StructuralMemberFeature } from '../src/model/types'; +import { findProfile, profileShape, sectionProps } from '../src/model/weldment-profiles'; +import { newEndCap, newGusset, newStructuralMember, newTrimExtend, newWeldBead, weldmentCutList } from '../src/model/weldments'; +import { circle, extrude, rect, req, sketch } from './helpers'; + +beforeAll(async () => { + setOc(await init()); +}); + +const volume = (b: ModelBuilder) => b.massProperties()!.volume; +const body = (b: ModelBuilder) => (b as unknown as { current: { body: Sh } }).current.body; +const area = (type: string, size: string, standard = 'iso') => sectionProps(profileShape(type, findProfile(standard, type, size)!.dims)).area; + +/** A rectangle's four lines as segments ("r" prefixed ids: rl0 bottom, rl1 right, rl2 top, rl3 left). */ +const rectSegs = (sk: string): SegmentRef[] => [0, 1, 2, 3].map((i) => ({ sketch: sk, entity: `rl${i}` })); + +function member(id: string, groups: SegmentRef[][], extra: Partial = {}): StructuralMemberFeature { + return { ...newStructuralMember(id, id, groups), ...extra }; +} + +function line(id: string, a: [number, number], b: [number, number]): SkEntity[] { + return [{ id: `${id}a`, t: 'point', x: a[0], y: a[1] }, { id: `${id}b`, t: 'point', x: b[0], y: b[1] }, { id, t: 'line', a: `${id}a`, b: `${id}b` }]; +} + +async function build(features: Feature[]) { + const b = new ModelBuilder(); + const res = await b.build(req(features)); + return { b, res }; +} + +describe('structural members', () => { + it('builds a mitered rectangular frame of square tube', async () => { + const { b, res } = await build([sketch('S1', rect(0, 0, 200, 100, 'r')), member('M1', [rectSegs('S1')])]); + expect(res.status.every((s) => s.ok && !s.warning)).toBe(true); + const A = area('squareTube', '40x40x3'); + // EN 10219-2: 40 x 40 x 3 has 4.21 cm². + expect(A).toBeCloseTo(420.8, 0); + // A miter plane passes through the corner point, so each member holds the + // profile area times its centreline length. + expect(volume(b)).toBeCloseTo(A * 600, 0); + expect(isValid(body(b))).toBe(true); + const ms = res.weldments!; + expect(ms).toHaveLength(4); + const lengths = ms.map((m) => m.length).sort((x, y) => x - y); + // Long point to long point: the centreline plus half the tube each end. + expect(lengths[0]).toBeCloseTo(140, 6); + expect(lengths[1]).toBeCloseTo(140, 6); + expect(lengths[2]).toBeCloseTo(240, 6); + expect(lengths[3]).toBeCloseTo(240, 6); + for (const m of ms) { + expect(m.angle1).toBeCloseTo(45, 6); + expect(m.angle2).toBeCloseTo(45, 6); + expect(m.volume).toBeCloseTo(A * (m.length - 40), 0); + expect(m.desc).toBe('SQ TUBE 40 x 40 x 3'); + } + // Faces are named after the member they belong to. + expect(res.faces.some((f) => f.name.startsWith('M1:S1/rl0:'))).toBe(true); + }); + + it('leaves a gap between mitered ends', async () => { + const { b, res } = await build([sketch('S1', rect(0, 0, 200, 200, 'r')), member('M1', [rectSegs('S1')], { gap: 2 })]); + expect(res.status.every((s) => s.ok)).toBe(true); + const A = area('squareTube', '40x40x3'); + // Each end is set back 1 mm along the miter normal: sqrt(2) mm along the member. + expect(volume(b)).toBeCloseTo(A * (800 - 8 * Math.SQRT2), 0); + for (const m of res.weldments!) expect(m.length).toBeCloseTo(240 - 2 * Math.SQRT2, 6); + }); + + it('butts members at corners (end butt 1 and 2)', async () => { + for (const corner of ['butt1', 'butt2'] as const) { + const { b, res } = await build([sketch('S1', rect(0, 0, 200, 200, 'r')), member('M1', [rectSegs('S1')], { corner })]); + expect(res.status.every((s) => s.ok)).toBe(true); + const A = area('squareTube', '40x40x3'); + // Each member runs through one corner and is trimmed at the other: all four are 200 long, square cut. + for (const m of res.weldments!) { + expect(m.length).toBeCloseTo(200, 6); + expect(m.angle1).toBe(0); + expect(m.angle2).toBe(0); + } + expect(volume(b)).toBeCloseTo(A * 800, 0); + expect(isValid(body(b))).toBe(true); + } + }); + + it('joins members that are nearly in line on the plane between them, at a butt corner too', async () => { + // Two lines drawn as one straight run, 0.1 degrees off. + const turn = (0.1 * Math.PI) / 180; + const ents = [...line('a', [0, 0], [200, 0]), ...line('b', [200, 0], [200 + 200 * Math.cos(turn), 200 * Math.sin(turn)])]; + const A = area('squareTube', '40x40x3'); + for (const corner of ['butt1', 'butt2'] as const) { + const { b, res } = await build([sketch('S1', ents), member('M1', [[{ sketch: 'S1', entity: 'a' }, { sketch: 'S1', entity: 'b' }]], { corner })]); + expect(res.status.every((s) => s.ok)).toBe(true); + // Not a 23 m member running through, with the other cut along its length to a sliver. + for (const m of res.weldments!) { + expect(m.length).toBeCloseTo(200, 1); + expect(m.volume).toBeCloseTo(A * 200, 0); + } + expect(volume(b)).toBeCloseTo(A * 400, 0); + } + // The same between groups: the later member is not cut to a sliver along the earlier one's side. + const grouped = await build([sketch('S1', ents), member('M1', [[{ sketch: 'S1', entity: 'a' }], [{ sketch: 'S1', entity: 'b' }]])]); + expect(grouped.res.status.every((s) => s.ok)).toBe(true); + for (const m of grouped.res.weldments!) expect(m.length).toBeCloseTo(200, 1); + expect(volume(grouped.b)).toBeCloseTo(A * 400, 0); + // Off straight by less than the kernel's angle for merging faces, the members run exactly in line: a valid body. + for (const off of [0.03, 0.01, 0.001]) { + const t = (off * Math.PI) / 180; + const kink = [...line('a', [0, 0], [200, 0]), ...line('b', [200, 0], [200 + 200 * Math.cos(t), 200 * Math.sin(t)])]; + for (const corner of ['miter', 'butt1'] as const) { + for (const groups of [[[{ sketch: 'S1', entity: 'a' }, { sketch: 'S1', entity: 'b' }]], [[{ sketch: 'S1', entity: 'a' }], [{ sketch: 'S1', entity: 'b' }]]]) { + const k = await build([sketch('S1', kink), member('M1', groups, { corner })]); + expect(k.res.status.every((s) => s.ok && !s.warning)).toBe(true); + expect(isValid(body(k.b))).toBe(true); + for (const m of k.res.weldments!) expect(m.length).toBeCloseTo(200, 3); + } + } + } + // A sharp corner folding nearly back on itself is still butted, not mitred. + const back = [...line('a', [0, 0], [200, 0]), ...line('b', [200, 0], [200 - 200 * Math.cos(turn * 30), 200 * Math.sin(turn * 30)])]; + const { res } = await build([sketch('S1', back), member('M1', [[{ sketch: 'S1', entity: 'a' }, { sketch: 'S1', entity: 'b' }]], { corner: 'butt1' })]); + expect(res.status.every((s) => s.ok)).toBe(true); + expect(res.weldments!.map((m) => Math.round(m.angle1 + m.angle2))).toEqual([0, 87]); + }); + + it('trims later groups to earlier ones, and extends the earlier member over a joint', async () => { + // A T: a horizontal rail, and a post from below ending on the rail's centreline. + const ents = [...line('h', [-100, 0], [100, 0]), ...line('v', [0, -150], [0, 0])]; + const { b, res } = await build([sketch('S1', ents), member('M1', [[{ sketch: 'S1', entity: 'h' }], [{ sketch: 'S1', entity: 'v' }]])]); + expect(res.status.every((s) => s.ok)).toBe(true); + const A = area('squareTube', '40x40x3'); + const post = res.weldments!.find((m) => m.member === 'S1/v')!; + expect(post.length).toBeCloseTo(130, 6); + expect(volume(b)).toBeCloseTo(A * (200 + 130), 0); + // An L of two groups: the first member is extended to cover the second. + const l = [...line('h', [0, 0], [100, 0]), ...line('v', [0, -100], [0, 0])]; + const r2 = await build([sketch('S1', l), member('M1', [[{ sketch: 'S1', entity: 'h' }], [{ sketch: 'S1', entity: 'v' }]])]); + const ws = r2.res.weldments!; + expect(ws.find((m) => m.member === 'S1/h')!.length).toBeCloseTo(120, 6); + expect(ws.find((m) => m.member === 'S1/v')!.length).toBeCloseTo(80, 6); + expect(volume(r2.b)).toBeCloseTo(A * 200, 0); + }); + + it('joins members of different sketches (a table frame with legs)', async () => { + // Top frame on the Top plane (y = 0), a leg on the Front plane down from a corner. + const top = sketch('S1', rect(0, 0, 400, 300, 'r'), { kind: 'base', plane: 'top' }); + const legs = sketch('S2', line('leg', [0, -500], [0, 0])); + const { b, res } = await build([top, legs, member('M1', [rectSegs('S1'), [{ sketch: 'S2', entity: 'leg' }]])]); + expect(res.status.every((s) => s.ok)).toBe(true); + const leg = res.weldments!.find((m) => m.member === 'S2/leg')!; + // The leg stops at the underside of the frame. + expect(leg.length).toBeCloseTo(480, 6); + expect(isValid(body(b))).toBe(true); + }); + + it('places and turns the profile by its pierce point', async () => { + // An angle along x with its heel on the line: all material on one side. + const ents = line('h', [0, 0], [100, 0]); + const { res } = await build([sketch('S1', ents), member('M1', [[{ sketch: 'S1', entity: 'h' }]], { profile: 'angle', size: '50x50x5', pierce: 'bl' })]); + expect(res.status[1].ok).toBe(true); + const bb = res.bbox!; + expect(bb.min[0]).toBeCloseTo(0, 6); + expect(bb.max[0]).toBeCloseTo(100, 6); + // Profile x runs along U = sketch normal × direction = +y, profile y along the sketch normal (+z). + expect(bb.min[1]).toBeCloseTo(0, 4); + expect(bb.max[1]).toBeCloseTo(50, 4); + expect(bb.min[2]).toBeCloseTo(0, 4); + expect(bb.max[2]).toBeCloseTo(50, 4); + const turned = await build([sketch('S1', ents), member('M1', [[{ sketch: 'S1', entity: 'h' }]], { profile: 'angle', size: '50x50x5', pierce: 'bl', rotation: 90 })]); + expect(turned.res.bbox!.min[1]).toBeCloseTo(-50, 4); + const mirrored = await build([sketch('S1', ents), member('M1', [[{ sketch: 'S1', entity: 'h' }]], { profile: 'angle', size: '50x50x5', pierce: 'bl', mirror: true })]); + expect(mirrored.res.bbox!.min[1]).toBeCloseTo(-50, 4); + }); + + it('sweeps members along arcs, and follows sketch edits', async () => { + const arc: SkEntity[] = [ + { id: 'c', t: 'point', x: 0, y: 0 }, { id: 'a', t: 'point', x: 100, y: 0 }, { id: 'b', t: 'point', x: -100, y: 0 }, + { id: 'arc', t: 'arc', c: 'c', a: 'a', b: 'b' }, + ]; + const f = member('M1', [[{ sketch: 'S1', entity: 'arc' }]], { profile: 'pipe', size: '48.3x3.2' }); + const { b, res } = await build([sketch('S1', arc), f]); + expect(res.status[1].ok).toBe(true); + const A = area('pipe', '48.3x3.2'); + expect(A).toBeCloseTo(453.4, 0); + expect(volume(b)).toBeCloseTo(A * Math.PI * 100, 0); + expect(res.weldments![0].length).toBeCloseTo(Math.PI * 100, 4); + expect(res.weldments![0].curved).toBe(true); + expect(res.weldments![0].radius).toBeCloseTo(100, 9); + // Moving a sketch point moves the member. + const moved = structuredClone(arc); + (moved[1] as { x: number }).x = 150; (moved[2] as { x: number }).x = -150; + const r2 = await b.build(req([sketch('S1', moved), f])); + expect(r2.weldments![0].length).toBeCloseTo(Math.PI * 150, 4); + }); + + it('runs round a slot of lines and tangent arcs, and mitres an arc meeting a line at an angle', async () => { + // A slot: two 200 lines joined by half circles of radius 50. + const slot: SkEntity[] = [ + { id: 'a', t: 'point', x: 0, y: 0 }, { id: 'b', t: 'point', x: 200, y: 0 }, { id: 'c', t: 'point', x: 200, y: 100 }, { id: 'd', t: 'point', x: 0, y: 100 }, + { id: 'c1', t: 'point', x: 200, y: 50 }, { id: 'c2', t: 'point', x: 0, y: 50 }, + { id: 'l1', t: 'line', a: 'a', b: 'b' }, { id: 'r1', t: 'arc', c: 'c1', a: 'b', b: 'c' }, { id: 'l2', t: 'line', a: 'c', b: 'd' }, { id: 'r2', t: 'arc', c: 'c2', a: 'd', b: 'a' }, + ]; + const segs = ['l1', 'r1', 'l2', 'r2'].map((entity) => ({ sketch: 'S1', entity })); + const { b, res } = await build([sketch('S1', slot), member('M1', [segs], { profile: 'pipe', size: '33.7x2.6' })]); + expect(res.status.every((s) => s.ok)).toBe(true); + const A = area('pipe', '33.7x2.6'); + expect(volume(b)).toBeCloseTo(A * (400 + 100 * Math.PI), 0); + expect(isValid(body(b))).toBe(true); + for (const m of res.weldments!) { expect(m.angle1).toBe(0); expect(m.angle2).toBe(0); } + // A quarter arc meeting a line at a right angle: the miter cuts the arc's end. + const bend: SkEntity[] = [ + { id: 'o', t: 'point', x: 0, y: 0 }, { id: 'p', t: 'point', x: 100, y: 0 }, { id: 'q', t: 'point', x: 0, y: 100 }, { id: 'e', t: 'point', x: 100, y: -100 }, + { id: 'arc', t: 'arc', c: 'o', a: 'p', b: 'q' }, { id: 'ln', t: 'line', a: 'p', b: 'e' }, + ]; + const r2 = await build([sketch('S1', bend), member('M1', [[{ sketch: 'S1', entity: 'arc' }, { sketch: 'S1', entity: 'ln' }]], { profile: 'roundBar', size: '20' })]); + expect(r2.res.status.every((s) => s.ok)).toBe(true); + expect(isValid(body(r2.b))).toBe(true); + // The line arrives along -y and the arc leaves along +y: they run in line, cut square. + expect(volume(r2.b)).toBeCloseTo(Math.PI * 100 * (100 + 50 * Math.PI), 0); + // At a right angle (a line along x), the arc and the line are mitred. + const corner = structuredClone(bend); + Object.assign(corner[3], { x: 200, y: 0 }); + const r3 = await build([sketch('S1', corner), member('M1', [[{ sketch: 'S1', entity: 'arc' }, { sketch: 'S1', entity: 'ln' }]], { profile: 'roundBar', size: '20' })]); + expect(r3.res.status.every((s) => s.ok)).toBe(true); + expect(isValid(body(r3.b))).toBe(true); + const ln = r3.res.weldments!.find((m) => m.member === 'S1/ln')!; + const ar = r3.res.weldments!.find((m) => m.member === 'S1/arc')!; + expect(ln.length).toBeCloseTo(110, 6); + expect(ln.angle1 + ln.angle2).toBeCloseTo(45, 6); + expect(ar.angle1 + ar.angle2).toBeCloseTo(45, 6); + }); + + it('reports clear errors', async () => { + const r1 = await build([sketch('S1', rect(0, 0, 100, 100, 'r')), member('M1', [])]); + expect(r1.res.status[1]).toMatchObject({ ok: false, error: expect.stringMatching(/Select sketch lines or arcs/) }); + const r2 = await build([sketch('S1', rect(0, 0, 100, 100, 'r')), member('M1', [rectSegs('S1')], { size: 'nope' })]); + expect(r2.res.status[1].error).toMatch(/profile/); + const r3 = await build([sketch('S1', [...rect(0, 0, 100, 100, 'r'), ...line('d', [0, 0], [100, 100])]), member('M1', [[...rectSegs('S1'), { sketch: 'S1', entity: 'd' }]])]); + expect(r3.res.status[1].error).toMatch(/Three or more members/); + const r4 = await build([sketch('S1', rect(0, 0, 100, 100, 'r')), member('M1', [[{ sketch: 'S1', entity: 'gone' }]])]); + expect(r4.res.status[1].error).toMatch(/no longer in/); + const r5 = await build([member('M1', [[{ sketch: 'S9', entity: 'x' }]])]); + expect(r5.res.status[0].error).toMatch(/layout sketch/); + const arc: SkEntity[] = [ + { id: 'c', t: 'point', x: 0, y: 0 }, { id: 'a', t: 'point', x: 10, y: 0 }, { id: 'b', t: 'point', x: -10, y: 0 }, + { id: 'arc', t: 'arc', c: 'c', a: 'a', b: 'b' }, + ]; + const r6 = await build([sketch('S1', arc), member('M1', [[{ sketch: 'S1', entity: 'arc' }]], { size: '40x40x3' })]); + expect(r6.res.status[1].error).toMatch(/does not fit inside the arc/); + // Among several members, the message says which one. + const r7 = await build([sketch('S1', [...line('l', [0, 0], [100, 0]), ...arc]), member('M1', [[{ sketch: 'S1', entity: 'l' }], [{ sketch: 'S1', entity: 'arc' }]])]); + expect(r7.res.status[1].error).toMatch(/^Arc 1 of S1: The profile does not fit inside the arc/); + }); + + it('explains damaged or hand-edited members instead of crashing', async () => { + const s1 = sketch('S1', rect(0, 0, 100, 100, 'r')); + const bad = async (extra: Record) => (await build([s1, { ...member('M1', [rectSegs('S1')]), ...extra } as Feature])).res.status[1].error; + expect(await bad({ profile: 'zzz' })).toMatch(/Select a profile/); + expect(await bad({ standard: 'din' })).toMatch(/Select a profile/); + expect(await bad({ groups: [{ segments: [] }] })).toMatch(/Select sketch lines or arcs/); + expect(await bad({ rotation: 'abc' })).toMatch(/Rotation angle has an invalid value/); + expect(await bad({ gap2: {} })).toMatch(/Gap between groups has an invalid value/); + // A huge list of segments that are gone, or of the same ones again, fails at once. + expect(await bad({ groups: [{ segments: Array.from({ length: 100000 }, (_, i) => ({ sketch: 'S1', entity: `e${i}` })) }] })).toMatch(/no longer in S1/); + expect(await bad({ groups: Array.from({ length: 20000 }, () => ({ segments: rectSegs('S1') })) })).toMatch(/selected twice/); + }); +}); + +describe('trim/extend', () => { + // A plate on the Top plane, 10 thick (y 0..10), and a post on the Front plane. + const plate = () => [sketch('P', rect(-100, -100, 100, 100), { kind: 'base', plane: 'top' }), extrude('E1', 'P', 10)]; + + it('trims a member to a planar face', async () => { + const post = sketch('S1', line('v', [0, -50], [0, 100])); + const pre = await build([...plate(), post, member('M1', [[{ sketch: 'S1', entity: 'v' }]])]); + const top = pre.res.faces.find((f) => f.name === 'E1:cap1')!; + const t = { ...newTrimExtend('T1', 'T1'), members: [{ feature: 'M1', member: 'S1/v' }], faces: [{ name: top.name, sig: { type: top.type, c: top.center, n: top.normal, area: top.area } }] }; + const { b, res } = await build([...plate(), post, member('M1', [[{ sketch: 'S1', entity: 'v' }]]), t]); + expect(res.status.every((s) => s.ok && !s.warning)).toBe(true); + const A = area('squareTube', '40x40x3'); + expect(res.weldments![0].length).toBeCloseTo(90, 6); + // The plate is left whole, and the post stands on it. + expect(volume(b)).toBeCloseTo(200 * 200 * 10 + A * 90, 0); + expect(isValid(body(b))).toBe(true); + }); + + it('extends a member to a face only when allowed', async () => { + const post = sketch('S1', line('v', [0, 30], [0, 100])); + const pre = await build([...plate(), post, member('M1', [[{ sketch: 'S1', entity: 'v' }]])]); + const top = pre.res.faces.find((f) => f.name === 'E1:cap1')!; + const face = { name: top.name, sig: { type: top.type, c: top.center, n: top.normal, area: top.area } }; + const t = { ...newTrimExtend('T1', 'T1'), members: [{ feature: 'M1', member: 'S1/v' }], faces: [face] }; + const { b, res } = await build([...plate(), post, member('M1', [[{ sketch: 'S1', entity: 'v' }]]), t]); + expect(res.status[4].ok).toBe(true); + expect(res.weldments![0].length).toBeCloseTo(90, 6); + expect(volume(b)).toBeCloseTo(200 * 200 * 10 + area('squareTube', '40x40x3') * 90, 0); + const r2 = await build([...plate(), post, member('M1', [[{ sketch: 'S1', entity: 'v' }]]), { ...t, allowExtension: false }]); + expect(r2.res.status[4].warning).toMatch(/Allow extension/); + expect(r2.res.weldments![0].length).toBeCloseTo(70, 6); + }); + + it('keeps what features built after the member did: a later plate stays whole, a hole stays open', async () => { + const post = sketch('S1', line('v', [0, -50], [0, 100])); + const m1 = member('M1', [[{ sketch: 'S1', entity: 'v' }]]); + const A = area('squareTube', '40x40x3'); + // The plate is extruded after the member, round the post's foot. + const pre = await build([post, m1, ...plate()]); + const top = pre.res.faces.find((f) => f.name === 'E1:cap1')!; + const face = { name: top.name, sig: { type: top.type, c: top.center, n: top.normal, area: top.area } }; + const t = { ...newTrimExtend('T1', 'T1'), members: [{ feature: 'M1', member: 'S1/v' }], faces: [face] }; + const later = await build([post, m1, ...plate(), t]); + expect(later.res.status.every((s) => s.ok)).toBe(true); + expect(volume(later.b)).toBeCloseTo(200 * 200 * 10 + A * 90, 0); + // A hole drilled through the post before the trim is not filled again. + const hole = [sketch('H', circle(0, 50, 10)), extrude('C1', 'H', 100, { cut: true, end: 'throughAll' })]; + const drilled = await build([...plate(), post, m1, ...hole]); + const trimmed = await build([...plate(), post, m1, ...hole, { ...t, faces: [face] }]); + expect(trimmed.res.status.every((s) => s.ok)).toBe(true); + // Only the 50 below the plate goes. + expect(volume(trimmed.b)).toBeCloseTo(volume(drilled.b) - A * 50, 0); + }); + + it('leaves nothing of a later member where a trim already took it away', async () => { + // Blocks give the planes x = 50 and y = 30 to trim to. + const blocks = [sketch('K', [...rect(40, 200, 50, 220, 'ka'), ...rect(200, 20, 220, 30, 'kb')]), extrude('EK', 'K', 10)]; + const s1 = sketch('S1', [...line('h', [-100, 0], [100, 0]), ...line('v', [80, -40], [80, 200])]); + const ms = [member('MA', [[{ sketch: 'S1', entity: 'h' }]]), member('MB', [[{ sketch: 'S1', entity: 'v' }]])]; + const pre = await build([...blocks, s1, ...ms]); + const ref = (f: (typeof pre.res.faces)[number]) => ({ name: f.name, sig: { type: f.type, c: f.center, n: f.normal, area: f.area } }); + const fx = pre.res.faces.find((f) => f.type === 'plane' && Math.abs(f.normal![0] - 1) < 1e-9 && Math.abs(f.center[0] - 50) < 1e-6)!; + const fy = pre.res.faces.find((f) => f.type === 'plane' && Math.abs(f.normal![1] - 1) < 1e-9 && Math.abs(f.center[1] - 30) < 1e-6)!; + // The post is cut off above the rail, then the rail is cut short of where the post crossed it. + const t1 = { ...newTrimExtend('T1', 'T1'), members: [{ feature: 'MB', member: 'S1/v' }], faces: [ref(fy)] }; + const t2 = { ...newTrimExtend('T2', 'T2'), members: [{ feature: 'MA', member: 'S1/h' }], faces: [ref(fx)] }; + const { b, res } = await build([...blocks, s1, ...ms, t1, t2]); + expect(res.status.every((s) => s.ok)).toBe(true); + expect(volume(b)).toBeCloseTo(2 * 10 * 20 * 10 + area('squareTube', '40x40x3') * (150 + 170), 0); + }); + + it('trims a member to another member, planar or coped', async () => { + // Two groups would trim by themselves: here two features, trimmed after. + const ents = [...line('h', [-100, 0], [100, 0]), ...line('v', [0, -150], [0, 20])]; + const s1 = sketch('S1', ents); + const m1 = member('M1', [[{ sketch: 'S1', entity: 'h' }]], { profile: 'pipe', size: '88.9x3.2' }); + const m2 = member('M2', [[{ sketch: 'S1', entity: 'v' }]], { profile: 'pipe', size: '48.3x3.2' }); + const t = { ...newTrimExtend('T1', 'T1'), boundary: 'members' as const, members: [{ feature: 'M2', member: 'S1/v' }], boundaryMembers: [{ feature: 'M1', member: 'S1/h' }] }; + const planar = await build([s1, m1, m2, t]); + expect(planar.res.status.every((s) => s.ok)).toBe(true); + // The flat end touches the rail along a line only: not a valid solid, and it says so. + expect(planar.res.status[3].warning).toMatch(/not a valid solid: the trimmed end touches the boundary member along a line. Turn on Coped cut/); + const post = planar.res.weldments!.find((m) => m.member === 'S1/v')!; + expect(post.length).toBeCloseTo(150 - 88.9 / 2, 6); + const coped = await build([s1, m1, m2, { ...t, coped: true }]); + expect(coped.res.status.every((s) => s.ok && !s.warning)).toBe(true); + const cp = coped.res.weldments!.find((m) => m.member === 'S1/v')!; + // Fish-mouth: the long points reach to where the post's sides meet the rail's surface. + const R = 88.9 / 2, r = 48.3 / 2; + expect(cp.length).toBeCloseTo(150 - Math.sqrt(R * R - r * r), 1); + expect(isValid(body(coped.b))).toBe(true); + // The coped post fills the saddle: more material than the planar cut. + expect(volume(coped.b)).toBeGreaterThan(volume(planar.b)); + // A gap keeps the saddle that far off the rail. + const gapped = await build([s1, m1, m2, { ...t, coped: true, gap: 2 }]); + expect(gapped.res.status.every((s) => s.ok)).toBe(true); + expect(gapped.res.weldments!.find((m) => m.member === 'S1/v')!.length).toBeCloseTo(150 - Math.sqrt((R + 2) ** 2 - r * r), 1); + }); + + it('copes a post to a beam at its flange, leaving nothing between the flanges', async () => { + // An IPE 200 turned so its flanges are at y = -100 and 100; the post comes up from below, ending at its axis. + const ents = [...line('h', [-150, 0], [150, 0]), ...line('v', [0, -150], [0, 20])]; + const s1 = sketch('S1', ents); + const m1 = member('M1', [[{ sketch: 'S1', entity: 'h' }]], { profile: 'beam', size: 'IPE200', rotation: 90 }); + const m2 = member('M2', [[{ sketch: 'S1', entity: 'v' }]], { profile: 'pipe', size: '48.3x3.2' }); + const t = { ...newTrimExtend('T1', 'T1'), boundary: 'members' as const, coped: true, members: [{ feature: 'M2', member: 'S1/v' }], boundaryMembers: [{ feature: 'M1', member: 'S1/h' }] }; + const { b, res } = await build([s1, m1, m2, t]); + expect(res.status.every((s) => s.ok)).toBe(true); + const post = res.weldments!.find((m) => m.member === 'S1/v')!; + expect(post.length).toBeCloseTo(50, 6); + expect(post.volume).toBeCloseTo(area('pipe', '48.3x3.2') * 50, 0); + expect(isValid(body(b))).toBe(true); + }); +}); + +describe('end caps and gussets', () => { + it('caps a square-cut tube end, outward and inward', async () => { + const s1 = sketch('S1', line('v', [0, 0], [0, 100])); + const m1 = member('M1', [[{ sketch: 'S1', entity: 'v' }]]); + const pre = await build([s1, m1]); + const end = pre.res.faces.find((f) => f.type === 'plane' && f.center[1] > 99.9)!; + const ref = { name: end.name, sig: { type: end.type, c: end.center, n: end.normal, area: end.area } }; + const A = area('squareTube', '40x40x3'); + const out = await build([s1, m1, { ...newEndCap('C1', 'C1', 5), faces: [ref], offset: 2 }]); + expect(out.res.status.every((s) => s.ok)).toBe(true); + // A 36 x 36 cap with corner radius 4 (6 - 2), 5 thick. + const capArea = 36 * 36 - (4 - Math.PI) * 16; + expect(volume(out.b)).toBeCloseTo(A * 100 + capArea * 5, 0); + const inward = await build([s1, m1, { ...newEndCap('C1', 'C1', 5), faces: [ref], inward: true }]); + expect(inward.res.status.every((s) => s.ok)).toBe(true); + // Inside the 34 x 34 opening with its 3 mm corner radius. + const plug = 34 * 34 - (4 - Math.PI) * 9; + expect(volume(inward.b)).toBeCloseTo(A * 100 + plug * 5, 0); + // Not on a mitered end (a gap leaves the miter faces outside). + const frame = await build([sketch('S2', rect(0, 0, 100, 100, 'r')), member('M2', [rectSegs('S2')], { gap: 2 })]); + const miter = frame.res.faces.find((f) => f.type === 'plane' && f.normal && Math.abs(Math.abs(f.normal[0]) - Math.SQRT1_2) < 1e-6)!; + const bad = await build([sketch('S2', rect(0, 0, 100, 100, 'r')), member('M2', [rectSegs('S2')], { gap: 2 }), { ...newEndCap('C1', 'C1', 5), faces: [{ name: miter.name, sig: { type: 'plane', c: miter.center, n: miter.normal, area: miter.area } }] }]); + expect(bad.res.status[2].error).toMatch(/square-cut/); + }); + + it('adds a triangular gusset between two member faces', async () => { + // An L of two groups: rail along x at y = 0, post along y at x = 0, both 40 x 40. + const l = [...line('h', [0, 0], [300, 0]), ...line('v', [0, 0], [0, 300])]; + const s1 = sketch('S1', l); + const m1 = member('M1', [[{ sketch: 'S1', entity: 'h' }], [{ sketch: 'S1', entity: 'v' }]]); + const pre = await build([s1, m1]); + const sig = (f: typeof pre.res.faces[number]) => ({ name: f.name, sig: { type: f.type, c: f.center, n: f.normal, area: f.area } }); + const railTop = pre.res.faces.find((f) => f.type === 'plane' && f.normal![1] > 0.99 && Math.abs(f.center[1] - 20) < 1e-6)!; + const postSide = pre.res.faces.find((f) => f.type === 'plane' && f.normal![0] > 0.99 && Math.abs(f.center[0] - 20) < 1e-6)!; + const v0 = volume(pre.b); + const g = { ...newGusset('G1', 'G1', 60, 5), faces: [sig(railTop), sig(postSide)] }; + const { b, res } = await build([s1, m1, g]); + expect(res.status.every((s) => s.ok)).toBe(true); + expect(volume(b) - v0).toBeCloseTo(60 * 60 / 2 * 5, 0); + const ch = await build([s1, m1, { ...g, chamfer: 10 }]); + expect(volume(ch.b) - v0).toBeCloseTo((60 * 60 / 2 - 50) * 5, 0); + const poly = await build([s1, m1, { ...g, shape: 'polygonal' as const, d3: 20 }]); + // Pentagon (0,0) (60,0) (60,20) (20,60) (0,60). + expect(volume(poly.b) - v0).toBeCloseTo((60 * 60 - 40 * 40 / 2) * 5, 0); + }); +}); + +describe('fillet beads', () => { + it('welds a post to a plate along the inside corner, and refuses outside corners', async () => { + const plate = [sketch('P', rect(-100, -100, 100, 100), { kind: 'base', plane: 'top' }), extrude('E1', 'P', 10)]; + const post = [sketch('S1', line('v', [0, 10], [0, 110])), member('M1', [[{ sketch: 'S1', entity: 'v' }]])]; + const pre = await build([...plate, ...post]); + // The post's flat side (x = 20, 28 long between its corner radii) on the plate's top. + const e = pre.res.edges.find((x) => x.type === 'line' && Math.abs(x.mid[0] - 20) < 1e-6 && Math.abs(x.mid[1] - 10) < 1e-6)!; + expect(e.length).toBeCloseTo(28, 6); + const ref = (x: typeof e) => ({ name: x.name, sig: { type: x.type, m: x.mid, len: x.length } }); + const v0 = volume(pre.b); + const { b, res } = await build([...plate, ...post, { ...newWeldBead('W1', 'W1', 5), edges: [ref(e)] }]); + expect(res.status.every((s) => s.ok && !s.warning)).toBe(true); + expect(volume(b) - v0).toBeCloseTo((5 * 5) / 2 * 28, 3); + expect(isValid(body(b))).toBe(true); + // The plate's own outer edge is an outside corner. + const outer = pre.res.edges.find((x) => x.type === 'line' && Math.abs(x.mid[0] - 100) < 1e-6 && Math.abs(x.mid[1] - 10) < 1e-6)!; + const bad = await build([...plate, ...post, { ...newWeldBead('W1', 'W1', 5), edges: [ref(outer)] }]); + expect(bad.res.status[4].error).toMatch(/inside corners/); + }); +}); + +describe('cut list', () => { + it('groups identical members', async () => { + const { res } = await build([sketch('S1', rect(0, 0, 200, 100, 'r')), member('M1', [rectSegs('S1')])]); + const list = weldmentCutList({ material: { name: 'Plain Carbon Steel', density: 7800 } }, res); + expect(list.items).toHaveLength(2); + expect(list.count).toBe(4); + expect(list.items[0]).toMatchObject({ item: 1, quantity: 2, description: 'SQ TUBE 40 x 40 x 3' }); + expect(list.items[0].length).toBeCloseTo(240, 6); + expect(list.items[1].length).toBeCloseTo(140, 6); + const A = area('squareTube', '40x40x3'); + expect(list.totalMass).toBeCloseTo(A * 600 * 1e-9 * 7800, 6); + expect(list.totalLength).toBeCloseTo(760, 6); + }); + + it('measures what later cuts took from the members, on demand', async () => { + const post = sketch('S1', line('v', [0, 0], [0, 100])); + const m1 = member('M1', [[{ sketch: 'S1', entity: 'v' }]]); + const A = area('squareTube', '40x40x3'); + const plain = await build([post, m1]); + expect(plain.b.weldVolumes()).toEqual({ volumes: [], approximate: false }); + // A hole through the post, and a boss beside it (which takes nothing). + const hole = [sketch('H', circle(0, 50, 10)), extrude('C1', 'H', 100, { cut: true, end: 'throughAll' })]; + const boss = [sketch('B', rect(100, 0, 150, 50)), extrude('E1', 'B', 10)]; + const drilled = await build([post, m1, ...hole, ...boss]); + const v = drilled.b.weldVolumes(); + expect(v.approximate).toBe(false); + expect(v.volumes).toHaveLength(1); + // The 20 mm hole goes through one 3 mm wall (it runs one way from the sketch plane, the post's middle). + expect(v.volumes[0].volume).toBeCloseTo(A * 100 - 3 * Math.PI * 100, -1); + expect(v.volumes[0].volume).toBeCloseTo(volume(drilled.b) - 50 * 50 * 10, 0); + }); +});