diff --git a/src/parametric/README.md b/src/parametric/README.md index 7521feb18..e6ef73aab 100644 --- a/src/parametric/README.md +++ b/src/parametric/README.md @@ -53,8 +53,10 @@ It runs entirely in the browser. The geometry kernel is OpenCascade compiled to **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. +- 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. Distance and angle mates can be limited to a range instead of a value (the component moves freely between a minimum and a maximum). 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. +- Mechanical mates: hinge (concentric and coincident in one, with optional angle limits from where it was added), slider (a straight edge or axis, or two planar faces, on each component: one move along it and no turn, with optional travel limits), gear (two axes turning by a ratio of pitch diameters or teeth, reversible for internal gears), rack and pinion (the rack's travel by the pinion's pitch diameter or a distance per turn), screw (a nut travelling a pitch per turn, right- or left-hand), width (a tab centred in a groove), slot (a pin travelling along a slot between its ends), cam follower (a vertex, a roller or a flat face kept on the cam's profile faces as it turns; convex profiles, exactly for round faces; a profile with a hollow is refused with its depth) and universal joint (two shafts at an angle β, the output turning by atan(tan φ / cos β), with an optional joint point where their axes meet). Gear, rack and screw mates hold from wherever the components are when they are added, and their turns add up past a full turn. +- 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, turning one gear turns the other, dragging a rack turns its pinion, and a drag stops at a mate's limits. Fixed components do not move. +- Motion studies (Motion Study): rotary motors (a constant speed in °/s or rpm, or oscillating; on a face or edge, or on a hinge), linear motors (constant speed or oscillating; along a face or edge, or on a slider) and mate drivers (a distance or angle mate's value at a constant speed, harmonic, or ramped between two values) drive the mechanism for a duration at a frame rate. Frames are calculated without freezing the interface (with progress, and a Cancel); the study stops and says why when a limit is reached or the mechanism locks up. Play, pause, loop and scrub through the motion; plot a point of a component (its displacement, velocity, acceleration, or its turn, angular velocity and acceleration) or what a mate measures against time, download the results as CSV, and check the frames for interference. Studies are listed in the design tree and saved with the assembly; editing the assembly puts their results out of date. - 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). @@ -83,6 +85,14 @@ It runs entirely in the browser. The geometry kernel is OpenCascade compiled to - Every toolpath is checked against the part; Simulate cuts the stock operation by operation and plays it back with the tool, coloured by what is finished, what is left and where the part would be cut, and reports rapid moves through the stock and material above the flutes. - Post Process writes G-code for Fanuc, Haas, LinuxCNC, Mach3/Mach4 or Grbl, in millimetres or inches, with arcs (G2/G3, helical) and drilling cycles (G81, G82, G83, G73) where the controller has them; preview it, copy it or download it. +**Analysis (static stress)** +- An Analysis tab sets up a linear static study of the part: the material (presets carry elastic modulus, Poisson's ratio, yield and tensile strength; custom materials take them too), fixtures, loads and the mesh, kept with the part in a Static Study folder of the design tree. Run meshes and solves it in a worker of its own, with progress and Cancel. +- Fixtures on faces: Fixed (no motion), Roller/Slider (no motion normal to the face; also a symmetry plane) and Fixed Hinge (a cylindrical face that may only turn about its axis). +- Loads: a total force on faces, normal to them or along a picked edge, face or axis (reversible); a pressure; gravity from the material's density. Values are in the part's units (N and MPa, or lbf and psi). Fixtures and loads refer to faces by name, so they follow dimension changes; ones whose faces are gone are marked in the tree. +- The mesh: 10-node quadratic tetrahedra whose boundary lies on the part's faces, edges and corners, with a coarse to fine setting (the automatic size follows the part's size and wall thickness) and its size, quality and volume reported. +- Results: von Mises stress, principal stresses, displacement (resultant and X, Y, Z), equivalent strain and factor of safety (yield over von Mises) plotted on the deformed shape (automatic or true scale, or undeformed) with a legend, the mesh on request and a probe that reads values where you click. The summary gives the largest stress and displacement and where, the smallest factor of safety, the reaction of each fixture against the applied loads (an equilibrium check) and the mesh and solver statistics; export it as CSV or a printable report. Stress above yield is flagged, as are fixtures that leave the part free to move (an unstable study is refused and the free motion named). Editing the part, the study or the material marks results out of date. +- Limits: linear static only (small displacements, linear elastic isotropic material: wood, being anisotropic, has no elastic properties), parts only (not assemblies), no contact, no thermal, modal or buckling analysis. The mesh is uniform: walls much thinner than the element size need a finer mesh (the volume check says so), and stresses at sharp inner corners and at the edges of fixed faces grow as the mesh is refined (singularities). + **Working with parts** - Design tree with rollback bar, suppress, rename, hide/show, edit and delete with dependency warnings. - Global variables and equations: type `=Width/2` in any dimension or feature value. @@ -118,7 +128,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. | +| 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. Limits are one-sided residuals, left out of the rank analysis. Cam followers touch the convex outline of the profile (exact arcs, and a polygon of finely divided arcs and corners), by its signed distance or, for a flat face, its support function. A universal joint holds its two yokes square (one equation), which gives the Cardan relation. Gear, rack and pinion and screw mates relate the motion since the start of each solve, and every solve starts where the last ended, so turns accumulate. Motion studies (`src/assembly/motion.ts`) solve frame by frame from the frame before with the motors as hard goals; results are finite differences of the frames. 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. | @@ -126,6 +136,7 @@ npm run build # type check, license check, production build in dist/ | Interface | `src/app`, `src/ui` | No framework. CommandManager, design tree, PropertyManager panels, sketch editor, dialogs. | | SolidWorks import | `src/formats/sldprt` | Reads the SolidWorks container (2015+ chunk format and the older OLE2), decodes the embedded Parasolid transmit and writes it as exact STEP for the kernel. Runs in the geometry worker. | | CAM | `src/model/cam.ts`, `src/cam`, `src/app/cam` | Toolpaths are generated in a worker of their own from a fine mesh of the part, in the setup's work coordinates. Drop-cutter (`src/cam/dropcutter.ts`) gives the lowest height a flat, ball, bull nose or conical cutter can reach at a point (face, edge and corner contacts, exact where a closed form exists). Where the tool can be at a height is where that is lower: its boundary is traced by marching squares with each crossing refined by bisection on the drop-cutter, and the passes inside it are offsets of a distance transform, cut from the innermost out. Parallel finishing follows drop-cutter heights along lines. The simulation lowers a height map of the stock along every move. Post processors write the moves with arcs fitted to them. | +| Analysis | `src/model/fea.ts`, `src/fea`, `src/app/fea` | Static stress analysis in a worker of its own, loaded on first use. The mesher (`src/fea/mesher.ts`) fills the solid with a body-centred cubic lattice (isosurface stuffing: exact inside tests by ray crossings of the kernel's triangulation, lattice points near the boundary warped onto it, lattice tetrahedra clipped with fixed stencils), moves vertices onto the part's corners and onto the edges between faces (splitting edges where a move would spoil an element), smooths, and adds midside nodes on the curved surface. The solver assembles 10-node tetrahedra into node-block sparse rows, applies fixtures as constraints in each node's own frame, and solves with conjugate gradients preconditioned by smoothed aggregation multigrid (rigid body modes as the near null space; block Gauss-Seidel smoothing). Fixtures are checked against rigid body motions before solving. | | Assistant | `src/assistant` | Tool-calling agent on Puter AI. Tools work on the document through a host interface (the app, or the kernel in Node for tests); each change rebuilds and is checked, failing steps are reverted, and a message's changes are squashed into one undo step. | | Platform | `src/platform` | Puter.js access, files (Puter or browser storage), theme. | diff --git a/src/parametric/src/app/assembly/index.ts b/src/parametric/src/app/assembly/index.ts index 0c9a4d389..cc5c83554 100644 --- a/src/parametric/src/app/assembly/index.ts +++ b/src/parametric/src/app/assembly/index.ts @@ -2,7 +2,7 @@ // 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 { Bolt, Boxes, Clapperboard, Cog, 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'; @@ -16,6 +16,7 @@ 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'; +import { MotionStudyPanel } from './motion-panel'; addIcons({ assembly: Boxes as unknown as IconNode, @@ -37,6 +38,18 @@ addIcons({ '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', + 'mate:hinge': [['path', { d: 'M4 6h7v12H4z', class: 'a' }], ['path', { d: 'M13 6h7v12h-7z' }], ['circle', { cx: 12, cy: 12, r: 2.2 }]], + 'mate:gear': Cog as unknown as IconNode, + 'mate:rackPinion': [['circle', { cx: 12, cy: 9, r: 5, class: 'a' }], ['path', { d: 'M3 18h18M5 18v-2.5M9 18v-2.5M13 18v-2.5M17 18v-2.5M21 18v-2.5' }]], + 'mate:screw': Bolt as unknown as IconNode, + 'mate:width': [['path', { d: 'M4 4v16M20 4v16' }], ['rect', { x: 9, y: 7, width: 6, height: 10, rx: 0.5, class: 'a' }], ['path', { d: 'M5.5 12h2M16.5 12h2' }]], + 'mate:slot': [['path', { d: 'M7 8h10a4 4 0 0 1 0 8H7a4 4 0 0 1 0-8z' }], ['circle', { cx: 9, cy: 12, r: 2, class: 'a' }]], + 'mate:slider': [['path', { d: 'M3 16h18' }], ['rect', { x: 8, y: 7, width: 8, height: 7, rx: 0.5, class: 'a' }], ['path', { d: 'M4 11l-2 2 2 2M20 11l2 2-2 2' }]], + 'mate:cam': [['path', { d: 'M12 20c-5 0-7-3-7-6 0-4 3-11 7-11s7 7 7 11c0 3-2 6-7 6z', class: 'a' }], ['circle', { cx: 12, cy: 14, r: 1.5 }]], + 'mate:universal': [['path', { d: 'M3 18l6-6M21 18l-6-6' }], ['circle', { cx: 12, cy: 10, r: 3.5, class: 'a' }], ['path', { d: 'M12 6.5v7M8.5 10h7' }]], + motionStudy: Clapperboard as unknown as IconNode, + play: [['path', { d: 'M7 4l13 8-13 8z', class: 'a' }]], + pause: [['path', { d: 'M7 4h3v16H7zM14 4h3v16h-3z', class: 'a' }]], }); /** The tabs an assembly shows; part tabs (sketch, features...) are hidden. */ @@ -47,7 +60,7 @@ export const ASSEMBLY_TAB: RibbonTab = { groups: [ [{ cmd: 'insertComponent' }, { cmd: 'mate' }], [{ stack: [{ cmd: 'moveComponent' }, { cmd: 'rotateComponent' }] }, { stack: [{ cmd: 'explodedView' }, { cmd: 'toggleExplode' }] }], - [{ cmd: 'interference' }, { cmd: 'billOfMaterials' }], + [{ cmd: 'interference' }, { cmd: 'billOfMaterials' }, { cmd: 'motionStudy' }], [{ stack: [{ cmd: 'updateParts' }, { cmd: 'openPart' }] }], ], }; @@ -112,7 +125,7 @@ export function installAssembly(app: App, files: FileOps, hooks: AppHooks) { }, }, { - id: 'mate', label: 'Mate', icon: 'mate', keywords: 'constraint coincident concentric distance angle parallel assembly', description: 'Position components relative to each other with mates.', + id: 'mate', label: 'Mate', icon: 'mate', keywords: 'constraint coincident concentric distance angle parallel assembly limit hinge slider prismatic gear rack pinion screw width slot cam follower universal joint mechanical', description: 'Position components relative to each other with mates.', enabled: () => asm() && hasComps(), run: () => openPanelWhenBuilt(() => new MatePanel(mode()!)), }, @@ -124,6 +137,10 @@ export function installAssembly(app: App, files: FileOps, hooks: AppHooks) { 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: 'motionStudy', label: 'Motion Study', icon: 'motionStudy', keywords: 'animation motor kinematics mechanism simulate plot velocity', description: 'Drive the mechanism with motors over time, play it back and plot positions, velocities and accelerations.', + enabled: () => asm() && hasComps(), run: () => openPanelWhenBuilt(() => new MotionStudyPanel(mode()!)), + }, { 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); } }, { @@ -205,7 +222,9 @@ export function installAssembly(app: App, files: FileOps, hooks: AppHooks) { 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 (st) { openPanelWhenBuilt(() => new ExplodePanel(m, st)); return; } + const study = m.study(id); + if (study) openPanelWhenBuilt(() => new MotionStudyPanel(m, study)); }; if (!app.assembly) { partTree = app.tree; partFlyout = app.flyout; } app.assembly = m; @@ -277,15 +296,30 @@ export function installAssembly(app: App, files: FileOps, hooks: AppHooks) { 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)); + // Gears and racks turn the other way round; mates of directions flip their alignment. + const reverses = mate.type === 'gear' || mate.type === 'rackPinion'; + const aligns = !['perpendicular', 'lock', 'tangent', 'width', 'slot', 'cam', 'universal'].includes(mate.type) && !reverses; 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] : []), + ...(aligns ? [{ label: 'Flip Mate Alignment', icon: 'reset', run: () => m.flipAlignment(mate.id) } as MenuItem] : []), + // (Only a flat follower face has sides: a vertex or roller follower has nothing to flip.) + ...(mate.type === 'cam' && 'face' in mate.b && mate.b.face.sig.type === 'plane' ? [{ label: 'Flip Follower Face', icon: 'reset', run: () => m.commit('Flip follower', (x) => { for (const y of x.mates) if (y.id === mate.id) y.flip = y.flip ? undefined : true; }) } as MenuItem] : []), + ...(reverses ? [{ label: 'Reverse Direction', icon: 'reset', run: () => m.commit('Reverse direction', (x) => { for (const y of x.mates) if (y.id === mate.id) y.reverse = y.reverse ? undefined : true; }) } 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 study = id ? m.study(id) : undefined; + if (study) { + return [ + { label: 'Edit Motion Study', icon: 'edit', run: () => m.edit(study.id) }, + { label: 'Rename', icon: 'text', shortcut: 'F2', run: () => app.startRename(study.id) }, + sep, + { label: 'Delete', icon: 'trash', shortcut: 'Delete', run: () => void m.deleteItems([study.id]) }, + ]; + } const step = id ? d.explode.find((x) => x.id === id) : undefined; if (step) { return [ diff --git a/src/parametric/src/app/assembly/mode.ts b/src/parametric/src/app/assembly/mode.ts index 26b16a9e5..0b355f8b0 100644 --- a/src/parametric/src/app/assembly/mode.ts +++ b/src/parametric/src/app/assembly/mode.ts @@ -5,7 +5,7 @@ // 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 type { AsmPartBuild, AsmPartResult, InterferencePair } 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'; @@ -13,10 +13,13 @@ 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, + type AsmComponent, type AsmPart, type AssemblyDocument, type ExplodeStep, type Mate, type MateRef, type MotionStudy, type Placement, MATE_LABELS, PartCache, asAssembly, mateComps, mateRefs, } 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 { type ComposedModel, type PartGeometry, camProfileOf, combinedName, composeModel, edgeGeo, faceGeo, findEdge, findFace, placementMatrix } from '../../assembly/compose'; +import { + type AnalysisResult, type CamProfile, type DragGoal, type Geo, MateSolver, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, mateBodies, matesMoving, relativePlacement, +} from '../../assembly/solver'; +import { type MotionResult, type MotionSetup, type MotorInput, MotionRun, framesSpread, profileOf, sameMotionGroups } from '../../assembly/motion'; import { parseColor } from '../../platform/theme'; import { confirmDialog, toast } from '../../ui/overlay'; import type { App } from '../app'; @@ -111,7 +114,7 @@ export class AssemblyMode { 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 }]); + const shownKey = JSON.stringify([app.kernel.generation, app.settings.quality, { ...doc, drawing: undefined, modified: undefined, blobs: undefined, studies: undefined }]); if (this.model && shownKey === this.shownKey && used.every((p) => this.geoms.has(this.key(p)))) return; this.shownKey = ''; const builds: AsmPartBuild[] = []; @@ -203,13 +206,45 @@ export class AssemblyMode { } return geo ? { body: c.id, geo } : `The ${'face' in ref ? 'face' : 'edge'} it references on ${c.name} cannot be mated`; } + if ('point' in ref) return { body: c.id, geo: { kind: 'point', p: ref.point } }; 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'); + /** Cam profiles by part copy and faces (a drag step solves the mates many times). */ + private profiles = new Map(); + + /** + * A cam mate's profile: its faces swept along one direction, as arcs (round + * faces, their extent from their circular edges) and corners (the other + * faces' edges and mesh vertices), in the cam's coordinates. + */ + camEntity(m: Mate, doc = this.doc): SolverEntity | string { + if (!('face' in m.a)) return 'A cam mate needs the faces of the cam\'s profile'; + const c = doc.components.find((x) => x.id === (m.a as { comp: Id }).comp); + if (!c) return 'Its component was deleted'; + const g = this.geometryOf(c.part); + const part = doc.parts.find((p) => p.id === c.part); + if (!g || !part) return `${c.name} is not built`; + const refs = [m.a.face, ...m.chain ?? []]; + const key = `${this.key(part)}|${JSON.stringify(refs)}`; + let prof = this.profiles.get(key); + if (!prof) { + prof = camProfileOf(g, refs, c.name); + if (this.profiles.size > 50) this.profiles.clear(); + this.profiles.set(key, prof); + } + return typeof prof === 'string' ? prof : { body: c.id, geo: prof }; + } + + /** Mate value in mm or degrees (a gear's teeth when its ratio is by teeth). */ + mateValue(m: Mate, v = m.value): number { + if (v === undefined) return 0; + return this.app.store.evalParam(v, m.type === 'angle' || m.type === 'hinge' ? 'angle' : m.by === 'ratio' ? 'count' : 'length'); + } + + /** What the value of a mate is called (for messages). */ + private valueName(m: Mate): string { + return m.type === 'angle' || m.type === 'hinge' ? 'Angle' : m.type === 'gear' ? (m.by === 'ratio' ? 'Teeth' : 'Pitch diameter') : m.type === 'screw' ? 'Pitch' : m.type === 'rackPinion' ? (m.by === 'revolution' ? 'Travel per turn' : 'Pitch diameter') : 'Distance'; } /** @@ -227,16 +262,24 @@ export class AssemblyMode { 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; + const ents = [m.type === 'cam' ? this.camEntity(m, doc) : this.entity(m.a, doc), this.entity(m.b, doc), m.a2 && this.entity(m.a2, doc), m.b2 && this.entity(m.b2, doc)]; + const bad = ents.find((e): e is string => typeof e === 'string'); + if (bad) { problems.set(m.id, bad); continue; } + const [a, b, a2, b2] = ents as (SolverEntity | undefined)[] as [SolverEntity, SolverEntity, SolverEntity | undefined, SolverEntity | undefined]; + let value = 0, value2: number | undefined, limit: { min: number; max: number } | undefined; try { value = this.mateValue(m); + if (m.value2 !== undefined) value2 = this.mateValue(m, m.value2); + if (m.limit) limit = { min: this.mateValue(m, m.limit.min), max: this.mateValue(m, m.limit.max) }; } catch (e) { - problems.set(m.id, `${m.type === 'angle' ? 'Angle' : 'Distance'}: ${(e as Error).message}`); + problems.set(m.id, `${this.valueName(m)}: ${(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 }); + mates.push({ + id: m.id, type: m.type, a, b, aligned: m.aligned, value, flip: !!m.flip, rel: m.rel, + ...(a2 ? { a2 } : {}), ...(b2 ? { b2 } : {}), ...(m.aligned2 !== undefined ? { aligned2: m.aligned2 } : {}), + ...(value2 !== undefined ? { value2 } : {}), ...(limit ? { limit } : {}), ...(m.by ? { by: m.by } : {}), ...(m.reverse ? { reverse: true } : {}), + }); } return { bodies, mates, problems, inactive }; } @@ -249,7 +292,7 @@ export class AssemblyMode { while (grew) { grew = false; for (const m of mates) { - const ids = [m.a.body, m.b.body]; + const ids = [m.a, m.b, m.a2, m.b2].flatMap((e) => (e ? [e.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; } @@ -365,12 +408,7 @@ export class AssemblyMode { // 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); + void app.kernel.assembly({ op: 'scene', items: this.sceneItems(all) }).catch(() => undefined); if (this.fitPending && model.bbox) { this.fitPending = false; app.viewport.zoomToFit(false, false); @@ -380,6 +418,15 @@ export class AssemblyMode { this.onShow(); } + /** The worker's scene of components placed as given. */ + private sceneItems(all: { comp: AsmComponent; placement: Placement }[]) { + const doc = this.doc; + return 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 } : {}) }; + }); + } + updateStatus() { const btn = this.app.shell.statusSketch; const a = this.analysis; @@ -429,9 +476,31 @@ export class AssemblyMode { 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; } + if (it.kind === 'vertex') { + const v = this.vertexOf(it.p); + return v ? { comp: v.comp, point: v.local } : null; + } return null; } + /** The component a picked vertex is a vertex of, and where it is in its part. */ + vertexOf(p: Vec3): { comp: Id; local: Vec3 } | null { + let best: { comp: Id; local: Vec3 } | null = null, bestD = Infinity; + for (const c of this.doc.components) { + const g = !c.suppressed && !c.hidden ? this.geometryOf(c.part) : null; + const pl = g?.mesh && this.shownPlacement(c.id); + if (!g?.mesh || !pl) continue; + const q: Quat = [-pl.q[0], -pl.q[1], -pl.q[2], pl.q[3]]; + const local = rotateBy(q, sub(p, pl.p)); + const vs = g.mesh.vertices; + for (let k = 0; k < vs.length; k += 3) { + const d = Math.hypot(vs[k] - local[0], vs[k + 1] - local[1], vs[k + 2] - local[2]); + if (d < bestD) { bestD = d; best = { comp: c.id, local: [vs[k], vs[k + 1], vs[k + 2]] }; } + } + } + return best && bestD < 1e-3 * Math.max(1, this.scale()) ? best : 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 } }; @@ -442,6 +511,10 @@ export class AssemblyMode { 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 ('point' in ref) { + const pl = this.shownPlacement(c.id); + return pl ? { kind: 'vertex', p: applyPlacement(pl, ref.point) } : null; + } if ('edge' in ref) { const m = this.model; const local = findEdge(g.edges, ref.edge); @@ -458,7 +531,7 @@ export class AssemblyMode { 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); } + if (m) for (const r of mateRefs(m)) { 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 }); } @@ -487,6 +560,8 @@ export class AssemblyMode { 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; + const st = this.study(it.id); + if (st) return `Motion study ${st.name}: ${st.duration} s, ${st.motors.length} ${st.motors.length === 1 ? 'motor' : 'motors'}`; } return null; } @@ -513,22 +588,51 @@ export class AssemblyMode { 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; + 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 ?? this.study(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); + const other = [...d.components, ...d.mates, ...d.explode, ...d.studies ?? []].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; + for (const x of [...d.components, ...d.mates, ...d.explode, ...d.studies ?? []]) if (x.id === id) x.name = name; }, false); } + /** + * Flip Mate Alignment. A hinge's touching faces flip with its axis (the + * component turns over; flipped alone, the axis could not hold with the + * faces), and its angle limits then count from where it turned over to. + */ + flipAlignment(id: Id) { + this.commit('Flip alignment', (d) => { + const m = d.mates.find((x) => x.id === id); + if (!m) return; + m.aligned = !m.aligned; + if (m.type !== 'hinge') return; + m.aligned2 = !m.aligned2; + if (!m.limit || !m.rel || !('comp' in m.a) || !('comp' in m.b)) return; + const limit = m.limit; + delete m.limit; + // (The components are put where it turned over to, so the solve with the limit starts there, at 0°.) + const pl = this.solveDoc(d).placements; + for (const c of d.components) { const p = pl.get(c.id); if (p && !c.fixed && !c.suppressed) c.placement = p; } + const at = (c: Id) => pl.get(c) ?? d.components.find((x) => x.id === c)?.placement; + const pa = at(m.a.comp), pb = at(m.b.comp); + if (pa && pb) m.rel = relativePlacement(pa, pb); + m.limit = limit; + }); + } + + study(id: Id): MotionStudy | undefined { + return this.doc.studies?.find((s) => s.id === id); + } + /** Double click or Enter on a tree row. */ edit(id: Id) { if (this.component(id)) this.app.selection.set([{ kind: 'feature', id }]); @@ -541,16 +645,22 @@ export class AssemblyMode { 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); + const studies = (doc.studies ?? []).filter((s) => ids.includes(s.id)); + const names = [...comps, ...doc.mates.filter((m) => ids.includes(m.id)), ...steps, ...studies].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)]); + const gone = new Set([...comps.map((c) => c.id), ...mates.map((m) => m.id), ...steps.map((s) => s.id), ...studies.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)); + // Motors of deleted components and mates go with them (a file keeps none that point nowhere). + if (d.studies) { + d.studies = d.studies.filter((s) => !gone.has(s.id)).map((s) => ({ ...s, motors: s.motors.filter((mo) => !(mo.mate && gone.has(mo.mate)) && !(mo.ref && 'comp' in mo.ref && gone.has(mo.ref.comp))) })); + if (!d.studies.length) delete d.studies; + } 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)); @@ -593,12 +703,160 @@ export class AssemblyMode { }); } + // ---------- motion studies ---------- + + /** Computed motion studies, with what they were computed from (see studyKey). */ + private motions = new Map(); + + /** What a study's results depend on: the study and everything the mates are solved from. */ + studyKey(st: MotionStudy): string { + return JSON.stringify([this.solveKey(this.doc), { ...st, id: undefined, name: undefined }]); + } + + /** A study's results, and whether they are those of the assembly (and study) as they are now. */ + motionOf(id: Id, st = this.study(id)): { result: MotionResult; current: boolean } | null { + const r = this.motions.get(id); + return r && st ? { result: r.result, current: r.key === this.studyKey(st) } : null; + } + + /** A study added to the document keeps the results computed while it was set up. */ + keepMotion(from: Id, to: Id) { + const r = this.motions.get(from); + this.motions.delete(from); + if (r) this.motions.set(to, r); + } + + /** Drops a study's results (those of a new study that was set up and cancelled, before the next one). */ + forgetMotion(id: Id) { + this.motions.delete(id); + } + + /** The solver input of a study, or why it cannot run. Components start where the mates put them now. */ + motionSetup(st: MotionStudy): MotionSetup | string { + const motors = st.motors.filter((m) => !m.suppressed); + if (!motors.length) return st.motors.length ? 'Every motor is suppressed: unsuppress one to drive the mechanism.' : 'Add a motor to drive the mechanism.'; + const { bodies, mates } = this.solverInput(); + const a = this.analysis; + const held = mates.filter((m) => !a?.conflicts.has(m.id) && !a?.invalid.has(m.id)); + const start = bodies.map((b) => ({ ...b, placement: this.solved.get(b.id) ?? b.placement })); + const names = new Map([...this.doc.mates.map((m) => [m.id, m.name] as [Id, string]), ...motors.map((m) => [m.id, m.name] as [Id, string])]); + const store = this.app.store; + const inputs: MotorInput[] = []; + for (const mo of motors) { + // Frequencies and rpm are plain numbers: evaluated as angles are (no length unit is applied). + const values = (kind: 'length' | 'angle') => ({ + profile: mo.profile, rpm: mo.rpm, reverse: mo.reverse, + ...Object.fromEntries((['speed', 'amplitude', 'from', 'to'] as const).filter((k) => mo[k] !== undefined).map((k) => [k, store.evalParam(mo[k]!, mo.rpm && k === 'speed' ? 'angle' : kind)])), + ...(mo.frequency !== undefined ? { frequency: store.evalParam(mo.frequency, 'angle') } : {}), + }); + try { + if (mo.kind === 'mate') { + const mt = this.doc.mates.find((x) => x.id === mo.mate); + const sm = held.find((x) => x.id === mo.mate); + if (!mt || (mt.type !== 'distance' && mt.type !== 'angle') || mt.limit) return `${mo.name}: the mate it drives must be a distance or angle mate without limits.`; + if (!sm) return `${mo.name}: ${mt.name} does not hold (suppressed, or with an error). Fix it to drive it.`; + inputs.push({ id: mo.id, name: mo.name, kind: 'mate', mate: mt.id, at: profileOf('mate', values(mt.type === 'angle' ? 'angle' : 'length'), st.duration, sm.value) }); + continue; + } + if (mo.mate) { + // On a hinge (rotary) or a slider (linear): its second component turns or slides relative to its first. + const mt = this.doc.mates.find((x) => x.id === mo.mate); + const sm = held.find((x) => x.id === mo.mate); + const want = mo.kind === 'rotary' ? 'hinge' : 'slider'; + if (!mt || mt.type !== want) return `${mo.name}: a ${mo.kind} motor goes on a ${want} mate.`; + if (!sm) return `${mo.name}: ${mt.name} does not hold (suppressed, or with an error). Fix it to drive it.`; + if (mateBodies(sm).every((id) => this.component(id)?.fixed)) return `${mo.name}: both components of ${mt.name} are fixed.`; + inputs.push({ id: mo.id, name: mo.name, kind: mo.kind, on: sm, at: profileOf(mo.kind, values(mo.kind === 'rotary' ? 'angle' : 'length'), st.duration) }); + continue; + } + const e = mo.ref ? this.entity(mo.ref) : 'It has no axis or direction'; + if (typeof e === 'string') return `${mo.name}: ${e}.`; + const comp = e.body ? this.component(e.body) : undefined; + if (!comp || comp.suppressed) return `${mo.name}: its component is suppressed.`; + if (comp.fixed) return `${mo.name}: ${comp.name} is fixed. Float it, or pick a face or edge of the component to move.`; + if (e.geo.kind !== 'axis' && e.geo.kind !== 'line' && e.geo.kind !== 'plane') return `${mo.name}: pick a round face or edge, a straight edge or a planar face for its ${mo.kind === 'rotary' ? 'axis' : 'direction'}.`; + inputs.push({ id: mo.id, name: mo.name, kind: mo.kind, body: comp.id, entity: e, at: profileOf(mo.kind, values(mo.kind === 'rotary' ? 'angle' : 'length'), st.duration) }); + } catch (err) { + return `${mo.name}: ${(err as Error).message}`; + } + } + return { bodies: start, mates: held, motors: inputs, duration: st.duration, fps: st.fps, scale: this.scale(), names }; + } + + /** + * Computes a study in slices of a few milliseconds, yielding to the + * interface between them (it stays responsive, and the progress shows). + * Null when cancelled; a message when it cannot run. + */ + async computeMotion(st: MotionStudy, id: Id, onProgress: (f: number) => void, cancelled: () => boolean): Promise { + const setup = this.motionSetup(st); + if (typeof setup === 'string') return setup; + const key = this.studyKey(st); + const run = new MotionRun(setup); + onProgress(0); + while (!run.done) { + const t0 = performance.now(); + while (!run.done && performance.now() - t0 < 12) run.step(); + onProgress(run.progress); + await yieldToUI(); + if (cancelled() || this.app.assembly !== this) return null; + } + this.motions.set(id, { key, result: run.result }); + return run.result; + } + + /** + * Interference over a study's motion: the worker's interference check on + * frames spread over it (at most `most`). The components the graphics area + * shows are put back in the worker's scene afterwards. Null when cancelled. + */ + async motionInterference(res: MotionResult, most: number, onProgress: (f: number) => void, cancelled: () => boolean): Promise<{ time: number; pairs: [Id, Id][]; failed: [Id, Id][] }[] | null> { + // Spread over the time (a study's frames are closer where it took smaller steps). + const picks = framesSpread(res.times, most); + const out: { time: number; pairs: [Id, Id][]; failed: [Id, Id][] }[] = []; + // The first frame checked: pairs that have not moved relative to each other since overlap as they did + // there (or could not be checked there, as the Interference Detection panel reports them). + let first: { placements: Placement[]; hits: [number, number][]; fails: [number, number][] } | null = null; + try { + for (const [k, i] of picks.entries()) { + const all = this.doc.components.filter((c) => !c.suppressed && this.geometryOf(c.part)).map((comp) => ({ comp, placement: res.frames[i].get(comp.id) ?? this.solved.get(comp.id) ?? comp.placement })); + await this.app.kernel.assembly({ op: 'scene', items: this.sceneItems(all) }); + const groups: number[] | undefined = first ? sameMotionGroups(first.placements, all.map((x) => x.placement)) : undefined; + const pairs = await this.app.kernel.assembly({ op: 'interference', mesh: false, ...(groups ? { groups } : {}) }); + if (cancelled() || this.app.assembly !== this) return null; + const hits: [number, number][] = pairs.filter((p) => !p.failed && p.volume > 1e-6).map((p) => [p.a, p.b] as [number, number]); + const fails: [number, number][] = pairs.filter((p) => p.failed).map((p) => [p.a, p.b] as [number, number]); + if (!first) first = { placements: all.map((x) => x.placement), hits, fails }; + else { + const kept = ([a, b]: [number, number]) => groups![a] === groups![b]; + hits.push(...first.hits.filter(kept)); + fails.push(...first.fails.filter(kept)); + } + const ids = (list: [number, number][]) => list.sort((x, y) => x[0] - y[0] || x[1] - y[1]).map(([a, b]) => [all[a].comp.id, all[b].comp.id] as [Id, Id]); + if (hits.length || fails.length) out.push({ time: res.times[i], pairs: ids(hits), failed: ids(fails) }); + onProgress((k + 1) / picks.length); + } + } finally { + if (this.app.assembly === this) this.show(); + } + return out; + } + dispose() { this.preview = null; this.explodePreview = null; } } +/** Lets the browser handle input and paint before going on (a message, not a timer: timers are slowed in background tabs). */ +function yieldToUI(): Promise { + return new Promise((resolve) => { + const ch = new MessageChannel(); + ch.port1.onmessage = () => { ch.port1.close(); resolve(); }; + ch.port2.postMessage(0); + }); +} + /** * Dragging components in the graphics area: the grabbed point follows the * cursor (Alt, or Rotate Component: the component turns), within what the diff --git a/src/parametric/src/app/assembly/motion-panel.ts b/src/parametric/src/app/assembly/motion-panel.ts new file mode 100644 index 000000000..5a1d4bc5c --- /dev/null +++ b/src/parametric/src/app/assembly/motion-panel.ts @@ -0,0 +1,739 @@ +// The Motion Study panel: a study's length and frame rate, its motors, +// computing its frames (in slices, cancelable, with progress), playing them +// back (play, pause, loop, scrub) and plotting results (a point of a +// component, its turn, or what a mate measures, with velocities and +// accelerations) that can be downloaded as CSV. + +import { type MotionResult, derivatives, mateSeries, pointPath, resultsCsv, turnPath, vectorDerivatives } from '../../assembly/motion'; +import { type SolverMate, relativePlacement } from '../../assembly/solver'; +import { type Quat, type Vec3, len } from '../../math/vec'; +import { type MotionMotor, type MotionProfile, type MotionStudy, MATE_LABELS, nextAsmId } from '../../model/assembly'; +import type { Id, Param } from '../../model/types'; +import { UNIT_SYSTEMS } from '../../model/units'; +import { download, safeName } from '../../platform/files'; +import { h } from '../../ui/dom'; +import { icon } from '../../ui/icons'; +import type { App } from '../app'; +import { type SelBoxItem, PropertyPanel, SelectionBox, checkbox, numberField, section, segmented, selectField } from '../pm'; +import type { SelItem } from '../selection'; +import type { AssemblyMode } from './mode'; + +type Quantity = 0 | 1 | 2; +type Axis = 'mag' | 'x' | 'y' | 'z'; + +const KIND_LABELS: Record = { rotary: 'Rotary motor', linear: 'Linear motor', mate: 'Mate driver' }; +const KIND_NAMES: Record = { rotary: 'RotaryMotor', linear: 'LinearMotor', mate: 'MateDriver' }; + +/** A new study's settings: 5 s at 30 frames a second. */ +const newStudy = (): MotionStudy => ({ id: '', name: '', duration: 5, fps: 30, motors: [] }); + +export class MotionStudyPanel extends PropertyPanel { + title = 'Motion Study'; + icon = 'motionStudy'; + private study: MotionStudy; + private readonly original: string; + /** Results are kept under the study's id ('' while a new study is set up). */ + private readonly key: Id; + /** A motor being added or changed, and where it goes in the list (-1: at the end). */ + private motor: MotionMotor | null = null; + private motorIndex = -1; + private computing = false; + private progress = 0; + private runs = 0; + private error: string | null = null; + private t = 0; + private playing = false; + private loop = false; + private speed = 1; + private raf = 0; + private last = 0; + private disposed = false; + private target = ''; + private point: { comp: Id; local: Vec3; label: string } | null = null; + private quantity: Quantity = 0; + private angular = false; + private axis: Axis = 'mag'; + private slider: HTMLInputElement | null = null; + private clock: HTMLElement | null = null; + private plotCursor: SVGLineElement | null = null; + private playBtn: HTMLButtonElement | null = null; + private bar: HTMLProgressElement | null = null; + /** The results the panel shows (to see when an edit of the assembly puts them out of date). */ + private shown: MotionResult | null = null; + private readonly unwatch: () => void; + + constructor(private mode: AssemblyMode, private existing: MotionStudy | null = null) { + super(); + this.study = structuredClone(existing ?? newStudy()); + this.original = JSON.stringify(this.study); + this.key = existing?.id ?? ''; + if (existing) { this.editingId = existing.id; this.title = `Motion Study: ${existing.name}`; } + // A new study starts without results (not with those of one set up before and cancelled). + else mode.forgetMotion(''); + this.helpText = 'Add motors that turn or move components (or drive a distance or angle mate), then Calculate. Play the motion back and plot how a component or mate moves. The study starts from where the components are now.'; + mode.app.selection.clear(); + // The assembly can change while the panel is open (a component dragged into a new start position): + // playback stops, and the results show as out of date. + this.unwatch = mode.app.store.on(() => { + if (this.disposed || this.computing || this.result() === this.shown) return; + this.play(false); + this.mode.previewPlacements(null); + this.app.refreshPanel(); + }); + } + + private get app(): App { + return this.mode.app; + } + + /** The results of this study as it is set up now (null when not computed, or out of date). */ + private result(): MotionResult | null { + const r = this.mode.motionOf(this.key, this.study); + return r?.current ? r.result : null; + } + + // ---------- panel ---------- + + render(): HTMLElement[] { + if (this.motor) return this.renderMotor(); + const res = this.result(); + this.shown = res; + const out = [this.studySection(), this.motorsSection(), this.calcSection(res)]; + if (res && res.frames.length > 1) out.push(this.playSection(res), this.resultsSection(res), this.interferenceSection(res)); + return out; + } + + // ---------- interference over the motion ---------- + + /** Frames checked for interference, for the results they were checked on. */ + private clashes: { result: MotionResult; list: { time: number; pairs: [Id, Id][]; failed: [Id, Id][] }[] } | null = null; + private checking = false; + + private interferenceSection(res: MotionResult): HTMLElement { + const items: HTMLElement[] = []; + if (this.checking) { + this.bar = h('progress', { max: '1', value: '0', 'aria-label': 'Interference check progress' }) as HTMLProgressElement; + const cancel = h('button', { class: 'btn small', type: 'button' }, 'Cancel'); + // (The check stops after the frame it is on, and puts the scene back.) + cancel.addEventListener('click', () => { this.runs++; this.checking = false; this.refreshTo('.kin-check'); }); + items.push(h('p', { class: 'field-label', role: 'status' }, 'Checking frames for interference...'), this.bar, cancel); + } else { + const run = h('button', { class: 'btn small kin-check', type: 'button' }, icon('interference', 14), 'Check Interference'); + run.addEventListener('click', () => void this.checkInterference(res)); + items.push(h('p', { class: 'field-label' }, `Finds components that overlap in ${Math.min(INTERFERENCE_FRAMES, res.frames.length)} frames spread over the motion.`), run); + const checked = this.clashes?.result === res ? this.clashes.list : null; + const c = checked?.filter((f) => f.pairs.length) ?? null; + const name = (id: Id) => this.mode.component(id)?.name ?? '?'; + // Pairs whose overlap could not be computed are not called clear (as the Interference Detection panel says). + const failed = new Map(); + for (const f of checked ?? []) for (const p of f.failed) { const k = p.join('|'); failed.set(k, { pair: p, frames: (failed.get(k)?.frames ?? 0) + 1 }); } + if (failed.size) items.push(h('p', { class: 'pm-msg error', role: 'alert' }, `Could not check ${[...failed.values()].map((x) => `${name(x.pair[0])} / ${name(x.pair[1])} (${x.frames} ${x.frames === 1 ? 'frame' : 'frames'})`).join(', ')}: the overlap could not be computed.`)); + if (c && !c.length && !failed.size) items.push(h('p', { class: 'pm-msg info', role: 'status' }, 'No interference in the frames checked.')); + if (c?.length) { + const list = h('div', { class: 'file-list', role: 'list', 'aria-label': 'Interference over the motion' }); + for (const f of c) { + 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' }, `${f.time.toFixed(2)} s`), h('span', { class: 'meta' }, f.pairs.map(([a, b]) => `${name(a)} and ${name(b)}`).join('; ')))); + b.addEventListener('click', () => { this.play(false); this.t = f.time; this.showAt(f.time); }); + list.append(h('div', { class: 'file-row', role: 'listitem' }, b)); + } + items.push(h('p', { class: 'pm-msg warn', role: 'status' }, `Components overlap in ${c.length} of the frames checked.`), list); + } + } + return section('Interference', items, { collapsed: false }); + } + + /** Settles when the last interference check has stopped using the worker's scene (a cancelled one finishes its frame). */ + private checked: Promise = Promise.resolve(); + private checkRun = 0; + + private async checkInterference(res: MotionResult) { + const run = ++this.runs; + this.checkRun = run; + this.play(false); + this.checking = true; + this.app.refreshPanel(); + let list: { time: number; pairs: [Id, Id][]; failed: [Id, Id][] }[] | null = null; + const before = this.checked; + let done = () => {}; + this.checked = new Promise((resolve) => { done = resolve; }); + try { + await before; + if (run === this.runs && !this.disposed) list = await this.mode.motionInterference(res, INTERFERENCE_FRAMES, (f) => { if (this.bar) this.bar.value = f; }, () => run !== this.runs || this.disposed); + } catch (e) { + if (!this.disposed && run === this.runs) this.error = (e as Error).message; + } finally { + done(); + } + // (Unless a newer check started after this one was cancelled.) + if (this.checkRun === run) this.checking = false; + if (this.disposed || run !== this.runs) return; + if (list) this.clashes = { result: res, list }; + this.app.refreshPanel(); + this.showAt(this.t); + } + + private studySection(): HTMLElement { + const num = (label: string, value: number, min: number, max: number, step: string, set: (v: number) => void) => { + const input = h('input', { class: 'input', type: 'number', min: String(min), max: String(max), step, value: String(value), 'aria-label': label }) as HTMLInputElement; + input.addEventListener('change', () => { + const v = Number(input.value); + const ok = Number.isFinite(v) && v >= min && v <= max; + input.setAttribute('aria-invalid', String(!ok)); + input.title = ok ? '' : `Between ${min} and ${max}`; + if (ok) { set(v); this.stale(); } + }); + return h('div', {}, h('div', { class: 'field-label', 'aria-hidden': 'true' }, label), input); + }; + return section('Study', [ + num('Duration (s)', this.study.duration, 0.1, 3600, '0.1', (v) => { this.study.duration = v; }), + num('Frames per second', this.study.fps, 1, 240, '1', (v) => { this.study.fps = Math.round(v); }), + ], { icon: 'motionStudy' }); + } + + private motorsSection(): HTMLElement { + const list = h('div', { class: 'file-list', role: 'list', 'aria-label': 'Motors' }); + this.study.motors.forEach((m, i) => { + const edit = h('button', { class: 'file-item', type: 'button', 'data-motor': m.id }, + h('span', { 'aria-hidden': 'true' }, icon(m.kind === 'mate' ? 'smartDimension' : m.kind === 'rotary' ? 'rotateComponent' : 'moveComponent', 16)), + h('span', { class: 'txt' }, h('span', { class: 'n' }, `${m.name}${m.suppressed ? ' (suppressed)' : ''}`), h('span', { class: 'meta' }, this.describeMotor(m)))); + edit.addEventListener('click', () => { this.motor = structuredClone(m); this.motorIndex = i; this.refreshTo(MOTOR_FIRST); }); + const del = h('button', { class: 'icon-btn', type: 'button', 'aria-label': `Delete ${m.name}` }, icon('trash', 14)); + del.addEventListener('click', () => { this.study.motors.splice(i, 1); this.stale(); this.refreshTo('.kin-add-motor'); }); + list.append(h('div', { class: 'file-row kin-motor', role: 'listitem' }, edit, del)); + }); + const add = h('button', { class: 'btn small kin-add-motor', type: 'button' }, icon('add', 14), 'Add Motor'); + add.addEventListener('click', () => { + this.motor = { id: '', name: '', kind: 'rotary', profile: 'constant', speed: 60 }; + this.motorIndex = -1; + this.refreshTo(MOTOR_FIRST); + }); + return section('Motors', [...(this.study.motors.length ? [list] : [h('p', { class: 'field-label' }, 'No motors yet: add one to drive the mechanism.')]), add]); + } + + private describeMotor(m: MotionMotor): string { + // Lengths in the document's units (linear motors, and mate drivers of distance mates). + const u = UNIT_SYSTEMS[this.mode.doc.units]; + const mt = m.kind === 'mate' ? this.mode.doc.mates.find((x) => x.id === m.mate) : undefined; + const lengthy = m.kind === 'linear' || mt?.type === 'distance'; + const v = (p: Param | undefined, len = lengthy) => (p === undefined ? '?' : typeof p === 'string' ? p : String(Math.round((len ? p / u.scale : p) * 1000) / 1000)); + const unit = m.kind === 'rotary' ? (m.rpm ? ' rpm' : '°/s') : lengthy ? ` ${u.length}/s` : '°/s'; + const what = m.mate ? this.mode.doc.mates.find((x) => x.id === m.mate)?.name ?? '?' : m.ref && 'comp' in m.ref ? this.mode.component(m.ref.comp)?.name ?? '?' : '?'; + const how = m.profile === 'constant' ? `${v(m.speed)}${unit}` : m.profile === 'oscillate' ? `±${v(m.amplitude)} at ${v(m.frequency, false)} Hz` : `${v(m.from)} to ${v(m.to)}`; + return `${KIND_LABELS[m.kind]}, ${what}: ${how}${m.reverse ? ', reversed' : ''}`; + } + + private calcSection(res: MotionResult | null): HTMLElement { + const items: HTMLElement[] = []; + const old = this.mode.motionOf(this.key, this.study); + if (this.computing) { + this.bar = h('progress', { max: '1', value: String(this.progress), 'aria-label': 'Calculation progress' }) as HTMLProgressElement; + const cancel = h('button', { class: 'btn small', type: 'button' }, 'Cancel'); + cancel.addEventListener('click', () => { this.runs++; this.computing = false; this.app.refreshPanel(); }); + items.push(h('p', { class: 'field-label', role: 'status' }, 'Calculating the motion...'), this.bar, cancel); + } else { + const calc = h('button', { class: 'btn small primary', type: 'button', disabled: !this.study.motors.length }, icon('rebuild', 14), res ? 'Calculate again' : 'Calculate'); + calc.addEventListener('click', () => void this.calculate()); + items.push(calc); + if (this.error) items.push(h('p', { class: 'pm-msg error', role: 'alert' }, this.error)); + else if (old && !old.current) items.push(h('p', { class: 'pm-msg warn', role: 'status' }, 'The results are out of date: the assembly or the study changed since they were calculated. Calculate again.')); + else if (res?.stop) items.push(h('p', { class: `pm-msg ${res.stop.kind === 'limit' ? 'warn' : 'error'}`, role: 'alert' }, res.stop.message)); + else if (res) items.push(h('p', { class: 'pm-msg info', role: 'status' }, `Calculated ${res.frames.length} frames.`)); + } + return section('Calculation', items); + } + + /** The study changed: results no longer match it (they stay cached for an undo of the change). */ + private stale() { + this.play(false); + this.error = null; + this.mode.previewPlacements(null); + this.app.refreshPanel(); + } + + private async calculate() { + // Not with a value it could not take (a duration of 0 would be calculated with the last good one). + if (!this.checkFields()) return; + this.setMessage(null); + const run = ++this.runs; + this.play(false); + this.computing = true; + this.progress = 0; + this.error = null; + this.app.refreshPanel(); + const st = structuredClone(this.study); + const r = await this.mode.computeMotion(st, this.key, (f) => { this.progress = f; if (this.bar) this.bar.value = f; }, () => run !== this.runs || this.disposed); + if (run !== this.runs || this.disposed) return; + this.computing = false; + if (typeof r === 'string') this.error = r; + this.t = 0; + this.app.refreshPanel(); + // (Not while a motor added meanwhile is being set up: its axis is picked on components that stand still.) + if (r && typeof r !== 'string') { this.showAt(0); if (r.frames.length > 1 && !r.stop && !this.motor) this.play(true); } + } + + // ---------- playback ---------- + + private playSection(res: MotionResult): HTMLElement { + const end = res.times[res.times.length - 1]; + const slider = h('input', { type: 'range', min: '0', max: '1000', step: '1', value: String(Math.round((this.t / Math.max(end, 1e-9)) * 1000)), 'aria-label': 'Study time', class: 'kin-slider' }) as HTMLInputElement; + slider.addEventListener('input', () => { this.play(false); this.t = (Number(slider.value) / 1000) * end; this.showAt(this.t); }); + // Arrow keys step one frame (a thousandth of the study can be short of the next frame, or skip many). + slider.addEventListener('keydown', (e) => { + const d = e.key === 'ArrowRight' || e.key === 'ArrowUp' ? 1 : e.key === 'ArrowLeft' || e.key === 'ArrowDown' ? -1 : 0; + if (!d || e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return; + e.preventDefault(); + this.play(false); + this.t = res.times[Math.max(0, Math.min(res.times.length - 1, frameAt(res, this.t) + d))]; + slider.value = String(Math.round((this.t / Math.max(end, 1e-9)) * 1000)); + this.showAt(this.t); + }); + this.slider = slider; + this.clock = h('div', { class: 'field-label kin-clock', 'aria-live': 'off' }); + const play = h('button', { class: 'btn small', type: 'button', disabled: this.checking }, icon(this.playing ? 'pause' : 'play', 16), this.playing ? 'Pause' : 'Play') as HTMLButtonElement; + play.addEventListener('click', () => this.play(!this.playing)); + this.playBtn = play; + const toStart = h('button', { class: 'icon-btn', type: 'button', 'aria-label': 'To the start', onclick: () => { this.play(false); this.t = 0; this.showAt(0); } }, icon('upToLine', 16)); + const toEnd = h('button', { class: 'icon-btn', type: 'button', 'aria-label': 'To the end', onclick: () => { this.play(false); this.t = end; this.showAt(end); } }, icon('downToLine', 16)); + const speed = selectField('Playback speed', String(this.speed), [{ value: '0.25', label: '¼ speed' }, { value: '0.5', label: '½ speed' }, { value: '1', label: 'Real time' }, { value: '2', label: '2× speed' }, { value: '5', label: '5× speed' }], (v) => { this.speed = Number(v); }); + queueMicrotask(() => this.showAt(this.t)); + return section('Playback', [h('div', { class: 'row kin-play' }, toStart, play, toEnd), slider, this.clock, checkbox('Loop', this.loop, (v) => { this.loop = v; }), speed]); + } + + private play(on: boolean) { + const res = this.result(); + // Not while the worker's scene is moved frame by frame for the interference check. + this.playing = on && !!res && !this.checking; + cancelAnimationFrame(this.raf); + if (this.playBtn) this.playBtn.replaceChildren(icon(this.playing ? 'pause' : 'play', 16), this.playing ? 'Pause' : 'Play'); + if (!this.playing || !res) return; + const end = res.times[res.times.length - 1]; + if (this.t >= end - 1e-9) this.t = 0; + this.last = performance.now(); + const tick = (now: number) => { + if (!this.playing || this.disposed) return; + const r = this.result(); + if (!r) { this.play(false); return; } + this.t += ((now - this.last) / 1000) * this.speed; + this.last = now; + if (this.t >= end) { + if (this.loop) this.t %= Math.max(end, 1e-9); + else { this.t = end; this.showAt(end); this.play(false); return; } + } + this.showAt(this.t); + this.raf = requestAnimationFrame(tick); + }; + this.raf = requestAnimationFrame(tick); + } + + /** Shows the frame at time t (the nearest computed one). */ + private showAt(t: number) { + const res = this.result(); + if (!res || this.disposed || this.checking) return; + const i = frameAt(res, t); + this.mode.previewPlacements(res.frames[i]); + const end = res.times[res.times.length - 1]; + if (this.slider && document.activeElement !== this.slider) this.slider.value = String(Math.round((t / Math.max(end, 1e-9)) * 1000)); + if (this.clock) this.clock.textContent = `${t.toFixed(2)} s / ${end.toFixed(2)} s`; + // (Read out as the time, not as the slider's 0 to 1000.) + this.slider?.setAttribute('aria-valuetext', `${t.toFixed(2)} s of ${end.toFixed(2)} s`); + if (this.plotCursor) { + const x = plotX(res.times[i], end); + this.plotCursor.setAttribute('x1', String(x)); + this.plotCursor.setAttribute('x2', String(x)); + } + } + + // ---------- results ---------- + + /** The mates a result can be plotted for (those that measure something). */ + private measurable(): SolverMate[] { + const { mates } = this.mode.solverInput(); + return mates.filter((m) => m.type === 'distance' || m.type === 'angle' || m.type === 'hinge' || (m.type === 'slider' && m.rel) || m.type === 'slot'); + } + + /** A mate's values over the motion. A hinge without limits (which keeps no 0° position) measures its turn from the start. */ + private mateSeries(res: MotionResult, m: SolverMate) { + if (m.type === 'hinge' && !m.rel) { + const at = (body?: Id | null) => (body ? res.frames[0].get(body) : undefined) ?? { p: [0, 0, 0] as Vec3, q: [0, 0, 0, 1] as Quat }; + m = { ...m, rel: relativePlacement(at(m.a.body), at(m.b.body)) }; + } + return mateSeries(res, m, 100); + } + + private resultsSection(res: MotionResult): HTMLElement { + const doc = this.mode.doc; + const comps = doc.components.filter((c) => !c.suppressed && !c.fixed); + const mates = this.measurable(); + const options = [ + ...comps.map((c) => ({ value: `comp:${c.id}`, label: `Component: ${c.name}` })), + ...mates.map((m) => ({ value: `mate:${m.id}`, label: `Mate: ${doc.mates.find((x) => x.id === m.id)?.name ?? m.id}` })), + ]; + if (!options.some((o) => o.value === this.target)) { + // The component the first motor drives, else the first one that moves. + const first = this.study.motors.find((m) => m.ref && 'comp' in m.ref)?.ref; + this.target = first && 'comp' in first && comps.some((c) => c.id === first.comp) ? `comp:${first.comp}` : options[0]?.value ?? ''; + } + if (!options.length) return section('Results', [h('p', { class: 'field-label' }, 'No component moves.')]); + const items: HTMLElement[] = [selectField('Result of', this.target, options, (v) => { this.target = v; this.point = null; this.app.refreshPanel(); }, 'part')]; + const isComp = this.target.startsWith('comp:'); + if (isComp) { + const comp = this.target.slice(5); + const box = new SelectionBox(this, 'Point (optional)', { vertex: true, face: true, edge: true }, (it) => this.pointOf(it, comp), (sel) => { + const p = sel[0]?.data as { comp: Id; local: Vec3; label: string } | undefined; + this.point = p ?? null; + this.app.refreshPanel(); + }, { single: true, placeholder: 'The component\'s origin; or select a vertex, edge or face of it', icon: 'point' }); + if (this.point) box.setItems([{ item: null, data: this.point, label: this.point.label }]); + items.push(box.el, + selectField('Quantity', `${this.angular ? 'a' : 'l'}${this.quantity}`, [ + { value: 'l0', label: 'Linear displacement' }, { value: 'l1', label: 'Linear velocity' }, { value: 'l2', label: 'Linear acceleration' }, + { value: 'a0', label: 'Angular displacement' }, { value: 'a1', label: 'Angular velocity' }, { value: 'a2', label: 'Angular acceleration' }, + ], (v) => { this.angular = v[0] === 'a'; this.quantity = Number(v[1]) as Quantity; this.app.refreshPanel(); }), + selectField('Vector component', this.axis, [{ value: 'mag', label: 'Magnitude' }, { value: 'x', label: 'X' }, { value: 'y', label: 'Y' }, { value: 'z', label: 'Z' }], (v) => { this.axis = v; this.app.refreshPanel(); })); + } else { + items.push(selectField('Quantity', String(this.quantity), [{ value: '0', label: 'Value' }, { value: '1', label: 'Rate of change' }, { value: '2', label: 'Second derivative' }], (v) => { this.quantity = Number(v) as Quantity; this.app.refreshPanel(); })); + } + const series = this.series(res); + if (series) items.push(this.plot(res, series)); + const csv = h('button', { class: 'btn small', type: 'button', disabled: !series }, icon('download', 14), 'Download CSV'); + csv.addEventListener('click', () => this.downloadCsv(res)); + items.push(csv); + return section('Results', items); + } + + /** A picked vertex, edge or face as a point of the component (its coordinates in the component). */ + private pointOf(it: SelItem, comp: Id): SelBoxItem | null { + const mode = this.mode; + let world: Vec3 | null = null, owner: Id | undefined, label = ''; + if (it.kind === 'vertex') { world = it.p; label = 'Vertex'; owner = mode.vertexOf(it.p)?.comp; } + if (it.kind === 'face') { const f = this.app.faces[it.index]; owner = mode.faceComponent(it.index)?.id; world = f?.center ?? null; label = `Face (${f?.type}) centre`; } + if (it.kind === 'edge') { const e = this.app.edges[it.index]; owner = mode.edgeComponent(it.index)?.id; world = e ? e.center ?? e.mid : null; label = `Edge (${e?.type}) ${e?.center ? 'centre' : 'midpoint'}`; } + const pl = mode.shownPlacement(comp); + if (!world || !pl || owner !== comp) return null; + const local = relativePlacement(pl, { p: world, q: [0, 0, 0, 1] }).p; + return { item: it, data: { comp, local, label }, label }; + } + + /** The plotted series: values per frame, with its name and unit. */ + private series(res: MotionResult): { values: number[]; name: string; unit: string } | null { + const u = UNIT_SYSTEMS[this.mode.doc.units]; + const per = ['', '/s', '/s²'][this.quantity]; + if (this.target.startsWith('mate:')) { + const m = this.measurable().find((x) => x.id === this.target.slice(5)); + const s = m && this.mateSeries(res, m); + if (!m || !s) return null; + const vals = this.quantity === 0 ? s.values : derivatives(res.times, s.values)[this.quantity === 1 ? 'd1' : 'd2']; + const lengthy = s.kind === 'length'; + const name = `${this.mode.doc.mates.find((x) => x.id === m.id)?.name ?? ''} ${['value', 'rate of change', 'second derivative'][this.quantity]}`; + return { values: lengthy ? vals.map((v) => v / u.scale) : vals, name, unit: `${lengthy ? u.length : '°'}${per}` }; + } + const comp = this.target.slice(5); + const vecs = this.vectors(res, comp); + const pick = (v: Vec3) => (this.axis === 'mag' ? len(v) : v['xyz'.indexOf(this.axis)]); + const list = vecs[this.angular ? 'angular' : 'linear'][this.quantity]; + const name = `${this.mode.component(comp)?.name ?? ''} ${this.angular ? 'angular' : 'linear'} ${['displacement', 'velocity', 'acceleration'][this.quantity]}${this.axis === 'mag' ? '' : ` ${this.axis.toUpperCase()}`}`; + return { values: list.map((v) => (this.angular ? pick(v) : pick(v) / u.scale)), name, unit: `${this.angular ? '°' : u.length}${per}` }; + } + + /** Displacement, velocity and acceleration vectors of the chosen point (mm) and of the component's turn (degrees). */ + private vectors(res: MotionResult, comp: Id): { linear: Vec3[][]; angular: Vec3[][] } { + const local = this.point?.comp === comp ? this.point.local : [0, 0, 0] as Vec3; + const path = pointPath(res, comp, local); + const disp = path.map((p) => [p[0] - path[0][0], p[1] - path[0][1], p[2] - path[0][2]] as Vec3); + const lin = vectorDerivatives(res.times, path); + const turn = turnPath(res, comp).map((v) => v.map((x) => (x * 180) / Math.PI) as Vec3); + const ang = vectorDerivatives(res.times, turn); + return { linear: [disp, lin.d1, lin.d2], angular: [turn, ang.d1, ang.d2] }; + } + + private plot(res: MotionResult, s: { values: number[]; name: string; unit: string }): HTMLElement { + const end = res.times[res.times.length - 1]; + // (A loop, not Math.min(...values): a long study has more frames than a call takes arguments.) + let min = Infinity, max = -Infinity; + for (const v of s.values) { if (v < min) min = v; if (v > max) max = v; } + if (!(min <= max)) min = max = 0; + // Differences smaller than this are rounding (a velocity or acceleration of a constant motion reads 1e-11, not 0). + const eps = 1e-6 * Math.max(1, Math.abs(min), Math.abs(max)); + // A constant is drawn across the middle. + const flat = !(max - min > eps); + const lo = flat ? min - 1 : min, hi = flat ? max + 1 : max; + const y = (v: number) => PLOT.top + (1 - (v - lo) / (hi - lo)) * (PLOT.h - PLOT.top - PLOT.bottom); + const pts = plotPoints(res.times, s.values, end).map((i) => `${plotX(res.times[i], end).toFixed(1)},${y(s.values[i]).toFixed(1)}`).join(' '); + const ns = 'http://www.w3.org/2000/svg'; + const el = (tag: K, attrs: Record, text?: string): SVGElementTagNameMap[K] => { + const e = document.createElementNS(ns, tag); + for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, String(v)); + if (text !== undefined) e.textContent = text; + return e; + }; + const fmtN = (v: number) => (Math.abs(v) >= 1000 || (Math.abs(v) < 0.01 && v !== 0) ? v.toExponential(2) : String(Math.round(v * 100) / 100)); + const fmtV = (v: number) => (Math.abs(v) < eps ? '0' : fmtN(v)); + const svg = el('svg', { viewBox: `0 0 ${PLOT.w} ${PLOT.h}`, class: 'kin-plot', role: 'img', 'aria-label': `Plot of ${s.name} (${s.unit}) against time, from ${fmtV(min)} to ${fmtV(max)}` }); + const x0 = PLOT.left, x1 = PLOT.w - PLOT.right, yb = PLOT.h - PLOT.bottom; + svg.append( + el('rect', { x: x0, y: PLOT.top, width: x1 - x0, height: yb - PLOT.top, class: 'kin-plot-frame' }), + ...(lo < 0 && hi > 0 ? [el('line', { x1: x0, x2: x1, y1: y(0), y2: y(0), class: 'kin-plot-zero' })] : []), + el('polyline', { points: pts, class: 'kin-plot-line' }), + el('text', { x: x0 - 4, y: flat ? y(max) + 3 : PLOT.top + 4, 'text-anchor': 'end', class: 'kin-plot-text' }, fmtV(flat ? max : hi)), + ...(flat ? [] : [el('text', { x: x0 - 4, y: yb, 'text-anchor': 'end', class: 'kin-plot-text' }, fmtV(lo))]), + el('text', { x: x0, y: PLOT.h - 4, class: 'kin-plot-text' }, '0 s'), + el('text', { x: x1, y: PLOT.h - 4, 'text-anchor': 'end', class: 'kin-plot-text' }, `${fmtN(end)} s`), + ); + const t = res.times[frameAt(res, this.t)]; + this.plotCursor = el('line', { x1: plotX(t, end), x2: plotX(t, end), y1: PLOT.top, y2: yb, class: 'kin-plot-cursor' }); + svg.append(this.plotCursor); + // Clicking the plot goes to that time. + svg.addEventListener('click', (e) => { + const r = svg.getBoundingClientRect(); + const fx = ((e.clientX - r.left) / r.width) * PLOT.w; + this.play(false); + this.t = Math.max(0, Math.min(end, ((fx - x0) / (x1 - x0)) * end)); + this.showAt(this.t); + }); + return h('div', { class: 'kin-plot-box' }, h('div', { class: 'field-label' }, `${s.name} (${s.unit})`), svg as unknown as HTMLElement); + } + + private downloadCsv(res: MotionResult) { + const u = UNIT_SYSTEMS[this.mode.doc.units]; + const cols: { name: string; values: number[] }[] = [{ name: 'Time (s)', values: res.times }]; + if (this.target.startsWith('mate:')) { + const m = this.measurable().find((x) => x.id === this.target.slice(5)); + const s = m && this.mateSeries(res, m); + if (!s) return; + const k = s.kind === 'length' ? 1 / u.scale : 1, unit = s.kind === 'length' ? u.length : 'deg'; + const d = derivatives(res.times, s.values); + cols.push({ name: `Value (${unit})`, values: s.values.map((v) => v * k) }, { name: `Rate (${unit}/s)`, values: d.d1.map((v) => v * k) }, { name: `Second derivative (${unit}/s^2)`, values: d.d2.map((v) => v * k) }); + } else { + const v = this.vectors(res, this.target.slice(5)); + const add = (name: string, list: Vec3[], unit: string, k: number) => { + for (const [i, a] of ['X', 'Y', 'Z'].entries()) cols.push({ name: `${name} ${a} (${unit})`, values: list.map((x) => x[i] * k) }); + cols.push({ name: `${name} magnitude (${unit})`, values: list.map((x) => len(x) * k) }); + }; + ['Displacement', 'Velocity', 'Acceleration'].forEach((n, i) => add(n, v.linear[i], `${u.length}${['', '/s', '/s^2'][i]}`, 1 / u.scale)); + ['Angle', 'Angular velocity', 'Angular acceleration'].forEach((n, i) => add(n, v.angular[i], `deg${['', '/s', '/s^2'][i]}`, 1)); + } + const label = this.target.startsWith('mate:') ? this.mode.doc.mates.find((x) => x.id === this.target.slice(5))?.name : this.mode.component(this.target.slice(5))?.name; + download(new Blob(csvParts(cols), { type: 'text/csv' }), `${safeName(this.study.name || 'Motion Study')} ${safeName(label ?? '')}.csv`); + } + + // ---------- a motor ---------- + + private renderMotor(): HTMLElement[] { + const m = this.motor!; + const ctx = this.app.unitContext(); + const set = (patch: Partial) => { Object.assign(this.motor!, patch); this.app.refreshPanel(); }; + const items: HTMLElement[] = [ + h('div', { class: 'field-label' }, 'Motor type'), + segmented('Motor type', m.kind, [{ value: 'rotary', label: 'Rotary' }, { value: 'linear', label: 'Linear' }, { value: 'mate', label: 'Mate' }], (v) => { + const p: MotionProfile = v !== 'mate' && m.profile === 'ramp' ? 'constant' : m.profile; + Object.assign(this.motor!, { kind: v, profile: p, ref: v === 'mate' ? undefined : m.ref, mate: undefined, rpm: v === 'rotary' ? m.rpm : undefined }); + if (p === 'constant' && m.speed === undefined) this.motor!.speed = 10; + this.app.refreshPanel(); + }), + ]; + if (m.kind === 'mate') { + const mates = this.mode.doc.mates.filter((x) => (x.type === 'distance' || x.type === 'angle') && !x.limit); + if (!mates.length) items.push(h('p', { class: 'pm-msg warn' }, 'The assembly has no distance or angle mate (without limits) to drive.')); + else { + if (!mates.some((x) => x.id === m.mate)) m.mate = mates[0].id; + items.push(selectField('Mate to drive', m.mate!, mates.map((x) => ({ value: x.id, label: `${x.name} (${MATE_LABELS[x.type]})` })), (v) => set({ mate: v }), 'mate')); + } + } else { + // On a hinge or slider, or on a face or edge of the component to move. + const want = m.kind === 'rotary' ? 'hinge' : 'slider'; + const mounts = this.mode.doc.mates.filter((x) => x.type === want); + if (m.mate && !mounts.some((x) => x.id === m.mate)) delete m.mate; + items.push(selectField('Motor on', m.mate ?? '', [{ value: '', label: 'A face or edge (select it below)' }, ...mounts.map((x) => ({ value: x.id, label: `${x.name} (${MATE_LABELS[x.type]})` }))], (v) => { + if (v) { this.motor!.mate = v; delete this.motor!.ref; } else delete this.motor!.mate; + this.app.refreshPanel(); + }, 'mate')); + } + if (m.kind !== 'mate' && !m.mate) { + const box = new SelectionBox(this, m.kind === 'rotary' ? 'Motor axis' : 'Motor direction', { face: true, edge: true }, (it) => { + const r = this.mode.refOf(it); + if (!r || !('comp' in r) || !('face' in r || 'edge' in r)) return null; + return { item: it, data: r, label: `${'face' in r ? `Face (${r.face.sig.type})` : `Edge (${r.edge.sig.type})`} of ${this.mode.component(r.comp)?.name ?? '?'}` }; + }, (sel) => { this.motor!.ref = sel[0]?.data as MotionMotor['ref']; }, { + single: true, icon: 'axis', + placeholder: m.kind === 'rotary' ? 'Select a round face or edge of the component to turn (or a straight edge or face along its axis)' : 'Select a straight edge or face of the component to move, along it (or across a face)', + }); + if (m.ref && 'comp' in m.ref) box.setItems([{ item: this.mode.itemOf(m.ref), data: m.ref, label: `${'face' in m.ref ? `Face (${m.ref.face.sig.type})` : 'edge' in m.ref ? `Edge (${m.ref.edge.sig.type})` : 'Component'} of ${this.mode.component(m.ref.comp)?.name ?? '?'}` }]); + items.push(box.el); + } + const profiles: { value: MotionProfile; label: string }[] = m.kind === 'mate' + ? [{ value: 'constant', label: 'Constant speed' }, { value: 'oscillate', label: 'Harmonic' }, { value: 'ramp', label: 'Linear ramp between values' }] + : [{ value: 'constant', label: 'Constant speed' }, { value: 'oscillate', label: 'Oscillating' }]; + items.push(selectField('Motion', m.profile, profiles, (v) => { + const defaults: Partial = v === 'constant' ? { speed: m.speed ?? 10 } : v === 'oscillate' ? { amplitude: m.amplitude ?? 10, frequency: m.frequency ?? 1 } : { from: m.from ?? 0, to: m.to ?? 10 }; + set({ profile: v, ...defaults }); + })); + const mate = m.kind === 'mate' ? this.mode.doc.mates.find((x) => x.id === m.mate) : undefined; + const kind = m.kind === 'rotary' || mate?.type === 'angle' ? 'angle' : 'length'; + const unit = kind === 'angle' ? '°' : UNIT_SYSTEMS[ctx.units].length; + // Number fields with the unit of what they hold (a speed's is per second). + const field = (label: string, key: 'speed' | 'amplitude' | 'frequency' | 'from' | 'to', k: 'length' | 'angle', shown: string) => { + const f = numberField({ label, value: m[key] ?? 0, kind: k, ctx, onChange: (v) => { this.motor![key] = v; } }); + const lab = f.querySelector('.field-label'); + if (lab) lab.textContent = `${label} (${shown})`; + return f; + }; + if (m.profile === 'constant') { + if (m.kind === 'rotary') { + items.push(field('Speed', 'speed', 'angle', m.rpm ? 'rpm' : '°/s'), + segmented('Speed unit', m.rpm ? 'rpm' : 'deg', [{ value: 'deg', label: '°/s' }, { value: 'rpm', label: 'rpm' }], (v) => set({ rpm: v === 'rpm' ? true : undefined }))); + } else items.push(field('Speed', 'speed', kind, `${unit}/s`)); + } else if (m.profile === 'oscillate') items.push(field('Amplitude', 'amplitude', kind, unit), field('Frequency', 'frequency', 'angle', 'Hz')); + else items.push(field('Start value', 'from', kind, unit), field('End value', 'to', kind, unit)); + if (m.profile !== 'ramp') items.push(checkbox('Reverse direction', !!m.reverse, (v) => { this.motor!.reverse = v || undefined; })); + items.push(checkbox('Suppressed', !!m.suppressed, (v) => { this.motor!.suppressed = v || undefined; })); + const done = h('button', { class: 'btn small primary', type: 'button' }, this.motorIndex < 0 ? 'Add' : 'Apply'); + done.addEventListener('click', () => this.finishMotor(true)); + const back = h('button', { class: 'btn small', type: 'button' }, 'Cancel'); + back.addEventListener('click', () => this.finishMotor(false)); + items.push(h('div', { class: 'row kin-motor-buttons' }, done, back)); + const form = section(this.motorIndex < 0 ? 'Add Motor' : `Motor: ${m.name}`, items, { icon: 'motionStudy' }); + form.classList.add('kin-motor-form'); + // Escape and Enter are the motor's Cancel and Add (or Apply), not the whole study's. + form.addEventListener('keydown', (e) => { + if (e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey) return; + const t = e.target as HTMLElement; + if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); this.finishMotor(false); } + // (Enter on a button presses it; in a number field it enters the value.) + else if (e.key === 'Enter' && !(t instanceof HTMLButtonElement) && !(t instanceof HTMLInputElement && t.type !== 'checkbox')) { e.preventDefault(); e.stopPropagation(); this.finishMotor(true); } + }); + return [form]; + } + + private finishMotor(save: boolean) { + const m = this.motor; + if (!m) return; + const had = this.el.contains(document.activeElement); + if (save) { + if (!this.checkFields()) return; + if (m.kind !== 'mate' && !m.ref && !m.mate) { this.setMessage('error', m.kind === 'rotary' ? 'Select the motor\'s axis (a round face or edge of the component to turn), or a hinge to put it on.' : 'Select the motor\'s direction (a straight edge or face of the component to move), or a slider to put it on.'); return; } + if (m.kind === 'mate' && !m.mate) { this.setMessage('error', 'Select the mate to drive.'); return; } + // Only the fields of its kind and profile are kept. + const keep: (keyof MotionMotor)[] = m.profile === 'constant' ? ['speed'] : m.profile === 'oscillate' ? ['amplitude', 'frequency'] : ['from', 'to']; + for (const k of ['speed', 'amplitude', 'frequency', 'from', 'to'] as const) if (!keep.includes(k)) delete m[k]; + if (m.kind !== 'rotary') delete m.rpm; + if (m.profile === 'ramp') delete m.reverse; + if (m.kind === 'mate' || m.mate) delete m.ref; else delete m.mate; + if (this.motorIndex < 0) { + // Ids and names are allocated as the document's would be (the study's own motors counted too). + const draft = { ...this.mode.doc, studies: [...(this.mode.doc.studies ?? []).filter((s) => s.id !== this.key), this.study] }; + m.id = nextAsmId(structuredClone({ ...draft, blobs: {} }), 'o'); + const all = draft.studies.flatMap((s) => s.motors); + let k = all.filter((x) => x.kind === m.kind).length + 1; + while (all.some((x) => x.name === `${KIND_NAMES[m.kind]}${k}`)) k++; + m.name = `${KIND_NAMES[m.kind]}${k}`; + this.study.motors.push(m); + } else this.study.motors[this.motorIndex] = m; + } + this.motor = null; + this.setMessage(null); + this.stale(); + // Keyboard focus goes back to the motor in the list (or to Add Motor). + if (had) (this.el.querySelector(`[data-motor="${CSS.escape(m.id)}"]`) ?? this.el.querySelector('.kin-add-motor'))?.focus(); + } + + /** Shows the panel again, with keyboard focus (when it was in the panel) on the first of `to` rather than lost. */ + private refreshTo(to: string) { + const had = this.el.contains(document.activeElement); + this.app.refreshPanel(); + if (had) this.el.querySelector(to)?.focus(); + } + + ok(): boolean { + if (this.motor) { this.finishMotor(true); if (this.motor) return false; } + this.play(false); + this.runs++; + this.mode.previewPlacements(null); + const st = structuredClone(this.study); + if (this.existing) this.mode.commit(`Edit ${st.name}`, (d) => { d.studies = (d.studies ?? []).map((s) => (s.id === st.id ? st : s)); }, false); + else { + this.mode.commit('Add motion study', (d) => { + st.id = nextAsmId(d, 's'); + let k = (d.studies?.length ?? 0) + 1; + while (d.studies?.some((s) => s.name.toLowerCase() === `motion study${k}`)) k++; + st.name = `Motion Study${k}`; + d.studies = [...d.studies ?? [], st]; + }, false); + this.mode.keepMotion('', st.id); + } + return true; + } + + cancel() { + this.play(false); + this.runs++; + this.mode.previewPlacements(null); + } + + get edited(): boolean { + return JSON.stringify(this.study) !== this.original || !!this.motor; + } + + dispose() { + this.disposed = true; + this.unwatch(); + this.playing = false; + cancelAnimationFrame(this.raf); + this.mode.previewPlacements(null); + } +} + +/** The first control of the motor form (where keyboard focus goes when it opens). */ +const MOTOR_FIRST = '.kin-motor-form .sec-body :is(button, select, input):not([disabled])'; + +/** The most frames checked for interference (each is a boolean check of every pair in the worker). */ +const INTERFERENCE_FRAMES = 40; + +/** (The left margin fits a value label of 8 characters, as -1.23e-3.) */ +const PLOT = { w: 280, h: 150, left: 50, right: 8, top: 8, bottom: 18 }; +const plotX = (t: number, end: number) => PLOT.left + (t / Math.max(end, 1e-9)) * (PLOT.w - PLOT.left - PLOT.right); + +/** + * The frames a plot line is drawn through: all of them, or for a long study + * the first, lowest, highest and last of each half unit across the plot (the + * line looks the same, with a few thousand points instead of every frame). + */ +function plotPoints(times: number[], values: number[], end: number): number[] { + const n = values.length; + const columns = 2 * (PLOT.w - PLOT.left - PLOT.right); + if (n <= 4 * columns) return values.map((_, i) => i); + const out: number[] = []; + let i = 0; + while (i < n) { + const c = Math.min(columns - 1, Math.floor((times[i] / Math.max(end, 1e-9)) * columns)); + let lo = i, hi = i, j = i; + while (j + 1 < n && Math.min(columns - 1, Math.floor((times[j + 1] / Math.max(end, 1e-9)) * columns)) === c) { + j++; + if (values[j] < values[lo]) lo = j; + if (values[j] > values[hi]) hi = j; + } + for (const k of [...new Set([i, lo, hi, j])].sort((a, b) => a - b)) out.push(k); + i = j + 1; + } + return out; +} + +/** + * A results CSV in parts of a few thousand rows, the same text as + * resultsCsv(cols) (a long study's would otherwise be one string of hundreds + * of megabytes, with its rows held besides). + */ +function csvParts(cols: { name: string; values: number[] }[], rows = 5000): string[] { + const n = Math.max(0, ...cols.map((c) => c.values.length)); + const head = resultsCsv(cols.map((c) => ({ name: c.name, values: [] }))); + const parts = [head]; + for (let i = 0; i < n; i += rows) parts.push(resultsCsv(cols.map((c) => ({ name: c.name, values: c.values.slice(i, i + rows) }))).slice(head.length)); + return parts; +} + +/** The frame nearest time t. */ +function frameAt(res: MotionResult, t: number): number { + let lo = 0, hi = res.times.length - 1; + while (lo < hi) { const m = (lo + hi + 1) >> 1; if (res.times[m] <= t + 1e-9) lo = m; else hi = m - 1; } + return lo + 1 < res.times.length && res.times[lo + 1] - t < t - res.times[lo] ? lo + 1 : lo; +} diff --git a/src/parametric/src/app/assembly/panels.ts b/src/parametric/src/app/assembly/panels.ts index 58e2702b5..1ffca66f0 100644 --- a/src/parametric/src/app/assembly/panels.ts +++ b/src/parametric/src/app/assembly/panels.ts @@ -8,11 +8,11 @@ import { type Vec3, add, normalize, qAxisAngle, qMul, scale } from '../../math/v 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 type { FaceRef, 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, + type AssemblyDocument, type ExplodeStep, type Mate, type MateRef, type MateType, type MechanicalMateType, type PartSource, type Placement, MATE_LABELS, MECHANICAL_MATES, assemblyBom, bomCsv, instanceName, + isAssembly, isMechanical, newPartBlobId, nextAsmId, nextPartColor, parseAnyDocument, } from '../../model/assembly'; import { type Geo, fittingMates, initialMateSettings, mateProblem, placeGeo, relativePlacement } from '../../assembly/solver'; import { @@ -25,7 +25,7 @@ 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 PickFilter, type SelBoxItem, PropertyPanel, SelectionBox, checkbox, numberField, section, segmented, selectField } from '../pm'; import type { SelItem } from '../selection'; import type { AssemblyMode } from './mode'; @@ -184,32 +184,80 @@ export function insertComponent(mode: AssemblyMode, picked: PickedPart) { // ---------- Mate ---------- -const MATE_TYPES: MateType[] = ['coincident', 'parallel', 'perpendicular', 'distance', 'angle', 'concentric', 'tangent', 'lock']; +const STANDARD_MATES: MateType[] = ['coincident', 'parallel', 'perpendicular', 'distance', 'angle', 'concentric', 'tangent', 'lock']; + +/** The selection boxes of a mechanical mate: their labels, what each takes, and how many entities. */ +const MECH_BOXES: Record = { + hinge: [ + { label: 'Concentric selections', placeholder: 'Select the pin and its hole (round faces or edges)', count: 2, filter: { face: true, edge: true } }, + { label: 'Coincident selections', placeholder: 'Select two planar faces that touch', count: 2, filter: { face: true, plane: true } }, + ], + gear: [{ label: 'Gears', placeholder: 'Select a round face or edge of each gear', count: 2, filter: { face: true, edge: true } }], + rackPinion: [{ label: 'Rack and pinion', placeholder: 'Select a straight edge of the rack and a round face or edge of the pinion', count: 2, filter: { face: true, edge: true } }], + screw: [{ label: 'Screw selections', placeholder: 'Select a round face or edge of the screw and of the nut', count: 2, filter: { face: true, edge: true } }], + width: [ + { label: 'Width selections', placeholder: 'Select the two faces of the groove', count: 2, filter: { face: true, plane: true } }, + { label: 'Tab selections', placeholder: 'Select the two faces of the tab', count: 2, filter: { face: true } }, + ], + slot: [ + { label: 'Slot ends', placeholder: 'Select the two round ends of the slot', count: 2, filter: { face: true, edge: true } }, + { label: 'Pin', placeholder: 'Select the pin (a round face or edge)', count: 1, filter: { face: true, edge: true } }, + ], + slider: [ + { label: 'First component', placeholder: 'Select a straight edge or axis, or two planar faces, of one component', count: 2, filter: { face: true, edge: true, plane: true } }, + { label: 'Second component', placeholder: 'Select the same on the component that slides', count: 2, filter: { face: true, edge: true } }, + ], + cam: [ + { label: 'Cam faces', placeholder: 'Select the faces around the cam (its profile)', count: 500, filter: { face: true } }, + { label: 'Follower', placeholder: 'Select the follower: a vertex, a roller (round face or edge) or a flat face', count: 1, filter: { face: true, edge: true, vertex: true } }, + ], + universal: [{ label: 'Shafts', placeholder: 'Select a round face or edge of each shaft (the input first)', count: 2, filter: { face: true, edge: true } }], +}; export class MatePanel extends PropertyPanel { title = 'Mate'; icon = 'mate'; private box!: SelectionBox; private refs: MateRef[] = []; + /** The second selection box of hinge, width and slot mates. */ + private refs2: MateRef[] = []; private type: MateType | null = null; private aligned = true; + private aligned2 = false; private flip = false; private value: Param = 10; + private value2: Param = 20; + private limitOn = false; + private min: Param = 0; + private max: Param = 10; + private by: 'ratio' | 'revolution' | 'point' | null = null; + private reverse = false; 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.'; + 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. Mechanical mates (hinge, slider, gear, rack and pinion, screw, width, slot, cam, universal joint) are in the list of mate types.'; if (existing) { this.editingId = existing.id; - this.refs = [existing.a, existing.b]; this.type = existing.type; this.aligned = existing.aligned; + this.aligned2 = !!existing.aligned2; this.flip = !!existing.flip; this.value = existing.value ?? (existing.type === 'angle' ? 90 : 10); + this.value2 = existing.value2 ?? 20; + this.limitOn = !!existing.limit; + if (existing.limit) { this.min = existing.limit.min; this.max = existing.limit.max; } + this.by = existing.by ?? null; + this.reverse = !!existing.reverse; this.auto = false; this.title = `Mate: ${existing.name}`; + const t = existing.type; + if (t === 'width' || t === 'slot') { this.refs = [existing.a, existing.a2!]; this.refs2 = [existing.b, ...(existing.b2 ? [existing.b2] : [])]; } + else if (t === 'slider') { this.refs = [existing.a, ...(existing.a2 ? [existing.a2] : [])]; this.refs2 = [existing.b, ...(existing.b2 ? [existing.b2] : [])]; } + else if (t === 'cam') { this.refs = [existing.a, ...(existing.chain ?? []).map((face) => ({ comp: (existing.a as { comp: Id }).comp, face }))]; this.refs2 = [existing.b]; } + else if (t === 'hinge') { this.refs = [existing.a, existing.b]; this.refs2 = [existing.a2!, existing.b2!]; } + else this.refs = [existing.a, existing.b]; } 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(); } @@ -228,11 +276,18 @@ export class MatePanel extends PropertyPanel { 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}`; + if ('point' in r) return `Vertex of ${c}`; return c; } - /** The type, alignment, side and value that fit the two entities where they are. */ + private get mech(): MechanicalMateType | null { + return this.type && isMechanical(this.type) ? this.type : null; + } + + /** The type, alignment, side and values that fit the entities where they are. */ private pickDefaults() { + const mech = this.mech; + if (mech) { this.mechDefaults(mech); return; } if (this.refs.length < 2) return; const [a, b] = this.refs.map((r) => this.geo(r)); if (!a || !b) return; @@ -243,90 +298,365 @@ export class MatePanel extends PropertyPanel { 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; + if (this.limitOn && typeof this.value === 'number') this.limitAround(this.value); + } + + /** Limits around the value a mate has where its entities are. */ + private limitAround(v: number) { + if (this.type === 'angle') { this.min = Math.max(0, Math.round(v - 30)); this.max = Math.min(180, Math.round(v + 30)); } + else if (this.type === 'hinge') { this.min = -45; this.max = 45; } + else if (this.type === 'slider') { this.min = -25; this.max = 25; } + else { this.min = Math.max(0, Math.round((v - 10) * 1000) / 1000); this.max = Math.round((v + 10) * 1000) / 1000; } + } + + private mechDefaults(t: MechanicalMateType) { + const g = this.refs.map((r) => this.geo(r)); + const round = (x: Geo | null | undefined) => (x && x.kind === 'axis' && x.r > 0 ? Math.round(2 * x.r * 1000) / 1000 : null); + if (g.length === 2 && g[0] && g[1]) { + if (t === 'hinge' || t === 'screw') this.aligned = initialMateSettings('concentric', g[0], g[1]).aligned; + if (t === 'gear' && this.by !== 'ratio') { this.value = round(g[0]) ?? 20; this.value2 = round(g[1]) ?? 20; } + if (t === 'rackPinion') { + // The pinion first: the round one. + if (g[0].kind === 'line' && g[1].kind === 'axis') this.refs = [this.refs[1], this.refs[0]]; + if (this.by !== 'revolution') this.value = round(this.geo(this.refs[0])) ?? 20; + } + } + if (t === 'hinge' && this.refs2.length === 2) { + const [a2, b2] = this.hingeFaces(); + const ga = a2 && this.geo(a2), gb = b2 && this.geo(b2); + if (ga && gb) this.aligned2 = initialMateSettings('coincident', ga, gb).aligned; + } + if (t === 'screw' && typeof this.value === 'number' && this.value === 10 && !this.existing) this.value = 1; + if (t === 'slider') { + // Each pair's alignment as the entities are now (the first entity of each component, then the second). + const al = (x?: MateRef, y?: MateRef) => { const gx = x && this.geo(x), gy = y && this.geo(y); return gx && gy ? initialMateSettings('coincident', gx, gy).aligned : null; }; + this.aligned = al(this.refs[0], this.refs2[0]) ?? this.aligned; + this.aligned2 = al(this.refs[1], this.refs2[1]) ?? this.aligned2; + } + } + + /** A hinge's two faces, the one on the first round entity's component first. */ + private hingeFaces(): [MateRef | undefined, MateRef | undefined] { + const [f, g] = this.refs2; + const comp = this.refs[0] && 'comp' in this.refs[0] ? this.refs[0].comp : null; + return f && g && 'comp' in g && g.comp === comp ? [g, f] : [f, g]; } 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 mech = this.mech; + const sections: HTMLElement[] = []; + if (mech) { + const boxes = MECH_BOXES[mech]; + const made: SelectionBox[] = []; + boxes.forEach((spec, i) => { + const box = new SelectionBox(this, spec.label, spec.filter, (it) => this.convert(it), (items) => { + if (items.length > spec.count) { box.setItems(items.slice(-spec.count)); return; } + const refs = items.map((x) => x.data as MateRef); + if (i === 0) this.refs = refs; else this.refs2 = refs; + this.mechDefaults(mech); + // A full box hands the picks on to the next one. + const next = made[i + 1]; + // (A slider's component takes one edge or axis, or two faces.) + const axisOnly = mech === 'slider' && refs.length === 1 && (() => { const g = this.geo(refs[0]); return g?.kind === 'line' || g?.kind === 'axis'; })(); + if ((refs.length === spec.count || axisOnly) && next && next.items.length < boxes[i + 1].count) this.activate(next); + this.mode.app.refreshPanel(); + this.update(); + }, { placeholder: spec.placeholder, icon: 'mate', single: spec.count === 1 }); + box.setItems((i === 0 ? this.refs : this.refs2).map((r) => ({ item: this.mode.itemOf(r), data: r, label: this.label(r) }))); + made.push(box); + }); + this.box = made[0]; + sections.push(section('Mate Selections', made.map((b) => b.el))); + } else { + 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) }))); + sections.push(section('Mate Selections', [this.box.el])); + } + const geos = !mech && this.refs.length === 2 ? this.refs.map((r) => this.geo(r)) : null; + const fits = geos && geos[0] && geos[1] ? STANDARD_MATES.filter((t) => t === 'lock' || !mateProblem(t, geos[0]!, geos[1]!)) : STANDARD_MATES; 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 typeSel = selectField('Mate type', type, [...fits, ...MECHANICAL_MATES].map((t) => ({ value: t, label: MATE_LABELS[t] })), (v) => this.setType(v), `mate:${type}`); + // The two kinds of mates in groups of their own. + const sel = typeSel.querySelector('select')!; + const group = (label: string, types: readonly MateType[]) => { + const g = h('optgroup', { label }); + for (const o of [...sel.options]) if (types.includes(o.value as MateType)) g.append(o); + return g; + }; + sel.append(group('Standard', STANDARD_MATES), group('Mechanical', MECHANICAL_MATES)); + sel.value = type; + sections.push(section('Mate Type', [typeSel])); + const extra = mech ? this.mechOptions(mech, ctx) : this.standardOptions(type, ctx); + if (extra.length) sections.push(section('Options', extra)); + sections.push(h('section', { class: 'pm-section' }, this.result)); + queueMicrotask(() => this.update()); + return sections; + } + + private setType(v: MateType) { + const was = this.mech; + this.type = v; + this.auto = false; + const now = this.mech; + // Entities picked for one kind of mate carry over as far as they fit the other. + // Whole components (picked in the tree) make no mechanical mate. + if (!was && now) { this.refs2 = []; this.refs = this.refs.filter((r) => !('comp' in r) || 'face' in r || 'edge' in r).slice(0, 2); } + if (was && !now) this.refs = this.refs.slice(0, 2); + if (now === 'gear' && this.by === 'revolution') this.by = null; + if (this.by && !((now === 'gear' && this.by === 'ratio') || (now === 'rackPinion' && this.by === 'revolution') || (now === 'universal' && this.by === 'point'))) this.by = null; + if (now === 'universal' && !this.existing) this.value = 0; + if (this.limitOn && v !== 'distance' && v !== 'angle' && v !== 'hinge' && v !== 'slider') this.limitOn = false; + // (Limits in degrees are not limits in millimetres: a hinge's or slider's start from its defaults.) + if (this.limitOn && (now === 'hinge' || now === 'slider') && was !== now) this.limitAround(0); + this.pickDefaults(); + this.mode.app.refreshPanel(); + this.update(); + } + + private standardOptions(type: MateType, ctx: ReturnType): HTMLElement[] { const extra: HTMLElement[] = []; + const kind = type === 'distance' ? 'length' : 'angle'; 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, + extra.push(checkbox(type === 'distance' ? 'Limit the distance (between two values)' : 'Limit the angle (between two values)', this.limitOn, (v) => { + this.limitOn = v; + if (v) { + const [a, b] = this.refs.map((r) => this.geo(r)); + const now = a && b ? initialMateSettings(type, a, b).value : typeof this.value === 'number' ? this.value : 10; + this.limitAround(now); + } + this.mode.app.refreshPanel(); + this.update(); + })); + if (this.limitOn) extra.push(...this.limitFields(kind, ctx)); + else extra.push(numberField({ + label: type === 'distance' ? 'Distance' : 'Angle', icon: type === 'distance' ? 'smartDimension' : 'angle', value: this.value, kind, ctx, min: 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 (type !== 'perpendicular' && type !== 'lock' && type !== 'tangent') extra.push(...this.alignment()); + return extra; + } + + private alignment(): HTMLElement[] { + return [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(); })]; + } + + private limitFields(kind: 'length' | 'angle', ctx: ReturnType): HTMLElement[] { + const angle = kind === 'angle' && this.type === 'angle'; + return [ + numberField({ label: 'Maximum', icon: kind === 'length' ? 'smartDimension' : 'angle', value: this.max, kind, ctx, min: angle ? 0 : undefined, max: angle ? 180 : undefined, onChange: (v) => { this.max = v; this.update(); } }), + numberField({ label: 'Minimum', icon: kind === 'length' ? 'smartDimension' : 'angle', value: this.min, kind, ctx, min: angle ? 0 : undefined, max: angle ? 180 : undefined, onChange: (v) => { this.min = v; this.update(); } }), + ]; + } + + private mechOptions(t: MechanicalMateType, ctx: ReturnType): HTMLElement[] { + const out: HTMLElement[] = []; + const reverse = (label: string) => checkbox(label, this.reverse, (v) => { this.reverse = v; this.update(); }); + switch (t) { + case 'hinge': + out.push(...this.alignment(), checkbox('Limit the angle (from where it is now)', this.limitOn, (v) => { + this.limitOn = v; + if (v) this.limitAround(0); + this.mode.app.refreshPanel(); + this.update(); + })); + if (this.limitOn) out.push(...this.limitFields('angle', ctx)); + break; + case 'gear': { + const teeth = this.by === 'ratio'; + out.push(h('div', { class: 'field-label' }, 'Ratio from'), segmented('Ratio from', teeth ? 'ratio' : 'diameter', [{ value: 'diameter', label: 'Pitch diameters' }, { value: 'ratio', label: 'Teeth' }], (v) => { + this.by = v === 'ratio' ? 'ratio' : null; + if (v === 'ratio') { this.value = 20; this.value2 = 40; } else this.mechDefaults('gear'); + this.mode.app.refreshPanel(); + this.update(); + })); + const kind = teeth ? 'count' : 'length'; + out.push( + numberField({ label: teeth ? 'Teeth of the first gear' : 'Pitch diameter of the first gear', value: this.value, kind, ctx, min: teeth ? 1 : 0, onChange: (v) => { this.value = v; this.update(); } }), + numberField({ label: teeth ? 'Teeth of the second gear' : 'Pitch diameter of the second gear', value: this.value2, kind, ctx, min: teeth ? 1 : 0, onChange: (v) => { this.value2 = v; this.update(); } }), + reverse('Reverse (an internal gear: both turn the same way)'), + ); + break; + } + case 'rackPinion': { + const per = this.by === 'revolution'; + out.push(h('div', { class: 'field-label' }, 'Rack travel from'), segmented('Rack travel from', per ? 'revolution' : 'diameter', [{ value: 'diameter', label: 'Pitch diameter' }, { value: 'revolution', label: 'Travel per turn' }], (v) => { + this.by = v === 'revolution' ? 'revolution' : null; + // (An equation is converted too, as its value: a pitch diameter is not a travel per turn.) + let now: number | null = null; + try { now = this.mode.app.store.evalParam(this.value, 'length'); } catch { /* left as it is: the field shows its error */ } + if (now !== null) this.value = Math.round((v === 'revolution' ? now * Math.PI : now / Math.PI) * 1000) / 1000; + this.mode.app.refreshPanel(); + this.update(); + })); + out.push( + numberField({ label: per ? 'Rack travel per turn of the pinion' : 'Pinion pitch diameter', icon: 'smartDimension', value: this.value, kind: 'length', ctx, min: 0, onChange: (v) => { this.value = v; this.update(); } }), + reverse('Reverse the direction'), + ); + break; + } + case 'screw': + out.push( + numberField({ label: 'Pitch (travel per turn)', icon: 'smartDimension', value: this.value, kind: 'length', ctx, min: 0, onChange: (v) => { this.value = v; this.update(); } }), + h('div', { class: 'field-label' }, 'Thread'), segmented('Thread', this.reverse ? 'left' : 'right', [{ value: 'right', label: 'Right-hand' }, { value: 'left', label: 'Left-hand' }], (v) => { this.reverse = v === 'left'; this.update(); }), + ...this.alignment(), + ); + break; + case 'slider': + out.push(...this.alignment(), checkbox('Limit the travel (from where it is now)', this.limitOn, (v) => { + this.limitOn = v; + if (v) this.limitAround(0); + this.mode.app.refreshPanel(); + this.update(); + })); + if (this.limitOn) out.push(...this.limitFields('length', ctx)); + break; + case 'cam': + if (this.refs2[0] && this.geo(this.refs2[0])?.kind === 'plane') out.push(checkbox('Flip the follower face (the cam on its other side)', this.flip, (v) => { this.flip = v; this.update(); })); + break; + case 'universal': + out.push(checkbox('Joint point: the shafts\' axes meet', this.by === 'point', (v) => { this.by = v ? 'point' : null; this.mode.app.refreshPanel(); this.update(); })); + if (this.by === 'point') out.push(numberField({ label: 'Joint point offset (along the first shaft)', icon: 'smartDimension', value: this.value, kind: 'length', ctx, onChange: (v) => { this.value = v; this.update(); } })); + break; + default: + break; } - 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') { + if ('comp' in r && !('face' in r) && !('edge' in r)) { // A component picked in the tree only takes a lock mate. - this.type = 'lock'; - this.auto = false; + if (this.mech) return null; + if (this.type !== 'lock') { this.type = 'lock'; this.auto = false; } } return { item: it, data: r, label: this.label(r) }; } + /** Where b sits in a's frame now (lock mates, and hinges measuring their angle). */ + private relNow(a: MateRef, b: MateRef): Placement | undefined { + const doc = this.mode.doc; + const at = (r: MateRef): Placement | undefined => ('comp' in r ? this.mode.solved.get(r.comp) ?? doc.components.find((c) => c.id === (r as { comp: Id }).comp)?.placement : { p: [0, 0, 0], q: [0, 0, 0, 1] }); + const pa = at(a), pb = at(b); + return pa && pb ? relativePlacement(pa, pb) : undefined; + } + + /** Where b sits in a's frame once the assembly is solved with the mate m (as relNow where it does not solve). */ + private relSolved(m: Mate, a: MateRef, b: MateRef): Placement | undefined { + 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; + if (r.invalid.has(id) || r.conflicts.has(id)) return this.relNow(a, b); + const at = (x: MateRef): Placement | undefined => ('comp' in x ? r.placements.get(x.comp) ?? d.components.find((c) => c.id === (x as { comp: Id }).comp)?.placement : { p: [0, 0, 0], q: [0, 0, 0, 1] }); + const pa = at(a), pb = at(b); + return pa && pb ? relativePlacement(pa, pb) : this.relNow(a, b); + } + + /** Where b sits in a's frame once b's axis passes through a universal joint's point (as relNow where it does not solve). */ + private relAtJoint(uj: Mate, a: MateRef, b: MateRef): Placement | undefined { + const e = this.mode.entity(a); + if (typeof e === 'string' || !('comp' in a) || (e.geo.kind !== 'axis' && e.geo.kind !== 'line')) return this.relNow(a, b); + let v: number; + try { v = this.mode.mateValue(uj); } catch { return this.relNow(a, b); } + // The joint point on a, and b's axis through it (a coincident mate standing in for the joint). + const point = add(e.geo.p, scale(normalize(e.geo.d), v)); + return this.relSolved({ ...uj, type: 'coincident', a: { comp: a.comp, point }, aligned: true, by: undefined, value: undefined }, a, b); + } + /** 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; + if (!this.type) return null; + const base = { id: this.existing?.id ?? '', name: this.existing?.name ?? '', type: this.type, aligned: this.aligned, ...(this.existing?.suppressed ? { suppressed: true } : {}) }; + const mech = this.mech; + if (mech) return this.mechMate(mech, base); + if (this.refs.length !== 2) return null; 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 limited = this.limitOn && (this.type === 'distance' || this.type === 'angle'); const m: Mate = { - id: this.existing?.id ?? '', name: this.existing?.name ?? '', type: this.type, a, b, aligned: this.aligned, + ...base, a, b, ...(this.type === 'distance' || this.type === 'angle' ? { value: this.value } : {}), + ...(limited ? { limit: { min: this.min, max: this.max } } : {}), ...(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); - } + if (this.type === 'lock') m.rel = this.relNow(a, b); return m; } + private mechMate(t: MechanicalMateType, base: Omit): Mate | null { + const [r0, r1] = this.refs; + // The position captured when the mate was added stays while its entities do. + const kept = (a: MateRef, b: MateRef) => (this.existing?.type === t && this.existing.rel && JSON.stringify([this.existing.a, this.existing.b]) === JSON.stringify([a, b]) ? this.existing.rel : this.relNow(a, b)); + if (t === 'slider') { + const n = this.refs.length; + if (!n || n !== this.refs2.length) return null; + const rel = kept(r0, this.refs2[0]); + return { + ...base, a: r0, b: this.refs2[0], ...(n === 2 ? { a2: r1, b2: this.refs2[1], aligned2: this.aligned2 } : {}), + ...(this.limitOn ? { limit: { min: this.min, max: this.max } } : {}), ...(rel ? { rel } : {}), + }; + } + if (t === 'cam') { + if (!this.refs.length || this.refs2.length !== 1 || !this.refs.every((r) => 'face' in r && 'comp' in r0 && r.comp === r0.comp)) return null; + return { ...base, a: r0, b: this.refs2[0], ...(this.refs.length > 1 ? { chain: this.refs.slice(1).map((r) => (r as { face: FaceRef }).face) } : {}), ...(this.flip ? { flip: true } : {}) }; + } + if (t === 'universal') { + if (this.refs.length !== 2) return null; + const uj: Mate = { ...base, a: r0, b: r1, ...(this.by === 'point' ? { by: 'point', value: this.value } : {}) }; + const keep = this.existing?.type === t && this.existing.rel && JSON.stringify([this.existing.a, this.existing.b]) === JSON.stringify([r0, r1]); + // The yokes are taken from where the shafts are once the joint point holds (it may tilt + // the second shaft), not from before: from there, adding the joint turned the shafts. + const rel = keep ? this.existing!.rel : this.by === 'point' ? this.relAtJoint(uj, r0, r1) : this.relNow(r0, r1); + return { ...uj, ...(rel ? { rel } : {}) }; + } + const counts = MECH_BOXES[t].map((x) => x.count); + if (this.refs.length !== counts[0] || (counts[1] && this.refs2.length !== counts[1])) return null; + switch (t) { + case 'hinge': { + const [a2, b2] = this.hingeFaces(); + const keep = this.existing?.type === 'hinge' && this.existing.rel && JSON.stringify([this.existing.a, this.existing.b]) === JSON.stringify([r0, r1]); + const hinge: Mate = { ...base, a: r0, b: r1, a2, b2, aligned2: this.aligned2 }; + if (!this.limitOn) return hinge; + // 0° is where the hinge puts the component, which may turn it about its axis (other mates hold it), not where it is before. + const rel = keep ? this.existing!.rel : this.relSolved(hinge, r0, r1); + return { ...hinge, limit: { min: this.min, max: this.max }, ...(rel ? { rel } : {}) }; + } + case 'gear': return { ...base, a: r0, b: r1, value: this.value, value2: this.value2, ...(this.by === 'ratio' ? { by: 'ratio' } : {}), ...(this.reverse ? { reverse: true } : {}) }; + case 'rackPinion': return { ...base, a: r0, b: r1, value: this.value, ...(this.by === 'revolution' ? { by: 'revolution' } : {}), ...(this.reverse ? { reverse: true } : {}) }; + case 'screw': return { ...base, a: r0, b: r1, value: this.value, ...(this.reverse ? { reverse: true } : {}) }; + case 'width': return { ...base, a: r0, a2: r1, b: this.refs2[0], b2: this.refs2[1] }; + case 'slot': return { ...base, a: r0, a2: r1, b: this.refs2[0] }; + } + return null; + } + 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}`; + // Limit mates are named for what they limit, as in "LimitDistance1". + const limited = !!m.limit && (m.type === 'distance' || m.type === 'angle'); + const kind = limited ? `Limit${MATE_LABELS[m.type]}` : MATE_LABELS[m.type]; + const n = d.mates.filter((x) => x.type === m.type && (!!x.limit && (x.type === 'distance' || x.type === 'angle')) === limited).length + 1; + let name = `${kind}${n}`; + for (let k = n + 1; d.mates.some((x) => x.name === name); k++) name = `${kind}${k}`; m.name = name; d.mates.push(m); } @@ -336,7 +666,13 @@ export class MatePanel extends PropertyPanel { 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; } + if (!m) { + const mech = this.mech; + this.result.textContent = mech ? `Select ${MECH_BOXES[mech].map((b) => b.label.toLowerCase()).join(' and ')}.` : 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); @@ -354,7 +690,7 @@ export class MatePanel extends PropertyPanel { ok(): boolean { const m = this.mate(); - if (!m) { this.setMessage('error', 'Select two entities to mate.'); return false; } + if (!m) { this.setMessage('error', this.mech ? `Select ${MECH_BOXES[this.mech].map((b) => b.label.toLowerCase()).join(' and ')}.` : '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); @@ -371,7 +707,7 @@ export class MatePanel extends PropertyPanel { } get edited(): boolean { - return this.refs.length === 2 && !this.existing; + return (this.refs.length > 0 || this.refs2.length > 0) && !this.existing; } } diff --git a/src/parametric/src/app/assembly/tree.ts b/src/parametric/src/app/assembly/tree.ts index 51ca59fc5..a8ddb0b54 100644 --- a/src/parametric/src/app/assembly/tree.ts +++ b/src/parametric/src/app/assembly/tree.ts @@ -1,7 +1,7 @@ // 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. +// CAD systems), the Mates folder, the exploded view steps and the motion +// studies. Same rows, keys and menus as the part tree. import type { Id } from '../../model/types'; import { BASE_PLANE_NAMES } from '../../model/planes'; @@ -19,7 +19,7 @@ interface Row { label: string; icon: string; depth: number; - kind: 'root' | 'plane' | 'origin' | 'component' | 'folder' | 'mate' | 'step'; + kind: 'root' | 'plane' | 'origin' | 'component' | 'folder' | 'mate' | 'step' | 'study'; children?: boolean; expanded?: boolean; muted?: string; @@ -82,6 +82,17 @@ export class AssemblyTree { 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'})` }); } + const studies = doc.studies ?? []; + if (studies.length) { + const open = !this.collapsed.has('studies'); + rows.push({ key: 'studies', item: null, label: 'Motion Studies', icon: 'motionStudy', depth: 1, kind: 'folder', children: true, expanded: open }); + if (open || this.filter) for (const s of studies) { + // Results computed for the assembly as it was before an edit are out of date. + const res = mode.motionOf(s.id, s); + const state = res ? (res.current ? (res.result.stop ? ', stopped early' : ', calculated') : ', out of date') : ''; + rows.push({ key: s.id, id: s.id, item: { kind: 'feature', id: s.id }, label: s.name, icon: 'motionStudy', depth: 2, kind: 'study', muted: ` (${s.motors.length} ${s.motors.length === 1 ? 'motor' : 'motors'}${state})` }); + } + } if (!this.filter) return rows; return rows.filter((r) => r.depth === 0 || r.label.toLowerCase().includes(this.filter)); } @@ -141,6 +152,7 @@ export class AssemblyTree { 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'); + else if (r.key === 'studies') app.openCommandMenu(['motionStudy'], e.clientX, e.clientY, 'Motion studies menu'); }); el.addEventListener('pointerenter', () => { if (r.item) sel.setHover(r.item); }); el.addEventListener('pointerleave', () => { if (r.item) sel.setHover(null); }); diff --git a/src/parametric/src/app/dialogs.ts b/src/parametric/src/app/dialogs.ts index 1462210c1..7ba0040a6 100644 --- a/src/parametric/src/app/dialogs.ts +++ b/src/parametric/src/app/dialogs.ts @@ -10,7 +10,7 @@ import { changeUnits, mapExpressions } from '../model/document'; import type { MaterialRef, SkCurve, SkDimension, UnitSystem, Variable } from '../model/types'; import { UNIT_SYSTEMS, formatNumber } from '../model/units'; import { BASE_FRAMES } from '../model/planes'; -import { MATERIALS } from '../model/materials'; +import { type ElasticProps, MATERIALS, MATERIAL_NOTES, elasticOf, validElastic } from '../model/materials'; import { uniqueId } from '../model/ids'; import { idFactory, mirrorAxisDirection, mirrorEntities, offsetCurves, pickMirrorAxis } from '../sketch/ops'; import { SketchIndex, tessellate } from '../sketch/geom'; @@ -204,7 +204,7 @@ function fieldLabel(text: string, field: HTMLElement): HTMLElement { export async function materialDialog(app: App) { const signal = app.documentSignal; const cur = app.store.doc.material; - const preset = cur && MATERIALS.find((m) => m.name === cur.name && m.density === cur.density); + const preset = cur && MATERIALS.find((m) => m.name === cur.name && m.density === cur.density && (cur.E === undefined || (cur.E === m.E && cur.nu === m.nu && cur.yield === m.yield && cur.uts === m.uts))); const select = h('select', { class: 'input', 'aria-label': 'Material' }) as HTMLSelectElement; select.append(h('option', { value: '' }, 'Not specified')); for (const m of MATERIALS) { @@ -213,41 +213,82 @@ export async function materialDialog(app: App) { select.append(o); } select.append(h('option', { value: '__custom' }, 'Custom...')); + const own = cur && !preset ? elasticOf(cur) : null; + const num = (v: number | undefined, label: string, step = 'any') => h('input', { class: 'input', type: 'number', min: '0', step, value: v === undefined ? '' : String(v), 'aria-label': label }) as HTMLInputElement; const customName = h('input', { class: 'input', value: cur && !preset ? cur.name : 'Custom material', 'aria-label': 'Custom material name' }) as HTMLInputElement; - const customDensity = h('input', { class: 'input', type: 'number', min: '0', step: 'any', value: String(cur?.density ?? 1000), 'aria-label': 'Density in kg per cubic metre' }) as HTMLInputElement; - const custom = h('div', { class: 'grid-form' }, fieldLabel('Name', customName), customName, fieldLabel('Density (kg/m³)', customDensity), customDensity); + const customDensity = num(cur?.density ?? 1000, 'Density in kg per cubic metre'); + // Elastic properties: optional, for stress analysis (GPa reads better than MPa for the modulus). + const customE = num(own ? own.E / 1000 : undefined, 'Elastic modulus in GPa'); + const customNu = num(own?.nu, 'Poisson\'s ratio'); + const customYield = num(own?.yield, 'Yield strength in MPa'); + const customUts = num(own?.uts, 'Tensile strength in MPa'); + const custom = h('div', { class: 'grid-form' }, fieldLabel('Name', customName), customName, fieldLabel('Density (kg/m³)', customDensity), customDensity, + fieldLabel('Elastic modulus (GPa)', customE), customE, fieldLabel('Poisson\'s ratio', customNu), customNu, + fieldLabel('Yield strength (MPa)', customYield), customYield, fieldLabel('Tensile strength (MPa)', customUts), customUts); + const customHint = h('p', { class: 'field-label' }, 'The elastic properties are needed for stress analysis; leave them all empty if the part will not be analyzed.'); if (cur && !preset) select.value = '__custom'; + // A preset's analysis properties, and what to keep in mind about them. + const props = h('div', { class: 'field-label fea-material-props', 'aria-live': 'polite' }); const error = h('div', { id: nextDomId('density-error'), class: 'field-label', role: 'alert', style: { color: 'var(--danger)' } }); customDensity.setAttribute('aria-describedby', error.id); + const elasticFields = [customE, customNu, customYield, customUts]; + for (const f of elasticFields) f.setAttribute('aria-describedby', error.id); + // The elastic fields that keep the set from being used (all empty is no set, not an error). + const badElastic = () => { + if (elasticFields.every((f) => !f.value.trim())) return []; + const bad = elasticFields.filter((f) => { + const v = Number(f.value); + return !f.value.trim() || !Number.isFinite(v) || (f === customNu ? v < 0 || v >= 0.5 : v <= 0); + }); + return bad.length ? bad : yieldAboveUts() ? [customYield, customUts] : []; + }; + // Yield above the tensile strength: the two are most likely swapped. + const yieldAboveUts = () => Number(customYield.value) > Number(customUts.value); + const customElastic = (): ElasticProps | null | 'invalid' => { + if (elasticFields.every((f) => !f.value.trim())) return null; + const e = { E: Number(customE.value) * 1000, nu: Number(customNu.value), yield: Number(customYield.value), uts: Number(customUts.value) }; + return elasticFields.some((f) => !f.value.trim()) || !validElastic(e) || yieldAboveUts() ? 'invalid' : e; + }; const validate = () => { const density = Number(customDensity.value); - const valid = select.value !== '__custom' || (Number.isFinite(density) && density > 0); - error.textContent = valid ? '' : 'Enter a finite, positive density.'; - if (valid) customDensity.removeAttribute('aria-invalid'); + const densityOk = select.value !== '__custom' || (Number.isFinite(density) && density > 0); + const elasticOk = select.value !== '__custom' || customElastic() !== 'invalid'; + const bad = elasticOk ? [] : badElastic(); + error.textContent = !densityOk ? 'Enter a finite, positive density.' : !elasticOk ? (bad[0] === customYield && bad.length === 2 && yieldAboveUts() ? 'The yield strength cannot be above the tensile strength.' : 'Enter all four elastic properties as positive numbers, with a Poisson\'s ratio from 0 to below 0.5 (or leave them all empty).') : ''; + if (densityOk) customDensity.removeAttribute('aria-invalid'); else customDensity.setAttribute('aria-invalid', 'true'); - return valid; + for (const f of elasticFields) { if (bad.includes(f)) f.setAttribute('aria-invalid', 'true'); else f.removeAttribute('aria-invalid'); } + return densityOk && elasticOk; }; - customDensity.addEventListener('input', () => { if (error.textContent) validate(); }); + for (const f of [customDensity, ...elasticFields]) f.addEventListener('input', () => { if (error.textContent) validate(); }); const sync = () => { - custom.hidden = select.value !== '__custom'; + custom.hidden = customHint.hidden = select.value !== '__custom'; + const m = MATERIALS.find((x) => x.name === select.value); + const e = m ? elasticOf(m) : null; + props.hidden = !m; + props.textContent = !m ? '' : (e ? `Elastic modulus ${formatGroup([e.E / 1000], 1)[0]} GPa, Poisson's ratio ${e.nu}, yield strength ${e.yield} MPa, tensile strength ${e.uts} MPa. ` : '') + (MATERIAL_NOTES[m.name] ?? (e ? 'Typical values.' : '')); if (custom.hidden) validate(); }; select.addEventListener('change', sync); sync(); const v = await showDialog({ title: 'Material', signal, - body: [h('p', {}, 'The material sets the density used for mass properties.'), select, custom, error], + body: [h('p', {}, 'The material sets the density used for mass properties, and the elastic properties used for stress analysis.'), select, props, custom, customHint, error], buttons: [{ label: 'Cancel', value: 'cancel' }, { label: 'Apply', value: 'ok', primary: true }], onAction: (action) => { - if (action === 'ok' && !validate()) { customDensity.focus(); return false; } + if (action === 'ok' && !validate()) { (customDensity.getAttribute('aria-invalid') ? customDensity : (badElastic()[0] ?? customE)).focus(); return false; } }, }); if (v !== 'ok' || signal.aborted) return; let m: MaterialRef | null = null; if (select.value === '__custom') { const d = Number(customDensity.value); - m = { name: customName.value.trim() || 'Custom material', density: d }; - } else if (select.value) m = MATERIALS.find((x) => x.name === select.value) ?? null; + const e = customElastic(); + m = { name: customName.value.trim() || 'Custom material', density: d, ...(e && e !== 'invalid' ? e : {}) }; + } else if (select.value) { + const p = MATERIALS.find((x) => x.name === select.value); + m = p ? { ...p } : null; + } app.store.change('Edit material', (doc) => { doc.material = m; }); } diff --git a/src/parametric/src/app/fea/index.ts b/src/parametric/src/app/fea/index.ts new file mode 100644 index 000000000..10e3a2e7d --- /dev/null +++ b/src/parametric/src/app/fea/index.ts @@ -0,0 +1,175 @@ +// Stress analysis in the interface: the Analysis tab of the CommandManager, +// its commands and the study's rows in the design tree. This module is small +// and loaded with the app; the panels, the plots and the analysis worker are +// loaded the first time a command needs them, so a part without a study +// costs nothing more to open. + +import { FIXTURE_ICONS, FIXTURE_LABELS, LOAD_ICONS, type FixtureType, type FeaLoadType, type StaticStudy } from '../../model/fea'; +import type { FaceRef } from '../../model/types'; +import { addIcons } from '../../ui/icons'; +import { toast } from '../../ui/overlay'; +import type { App, AppHooks } from '../app'; +import type { CamRow } from '../cam'; +import type { Command } from '../commands'; +import type { RibbonTab } from '../shell'; +import type { FeaWorkspace } from './workspace'; + +const P = (d: string, cls?: string): [string, Record] => (cls ? ['path', { d, class: cls }] : ['path', { d }]); +const C = (cx: number, cy: number, r: number, cls?: string): [string, Record] => (cls ? ['circle', { cx, cy, r, class: cls }] : ['circle', { cx, cy, r }]); + +addIcons({ + // A bracket with a stress gradient. + feaStudy: [P('M4 20V6h5v9h11v5z', 's'), P('M4 20V6h5v9h11v5z'), P('M6 8v2M6 12v2M11 17h2M15 17h2', 'a'), P('M14 3l3 3 3-3', 'thin')], + feaFixed: [P('M7 4h12v10H7z', 's'), P('M7 4h12v10H7z'), P('M4 3v14'), P('M1 6l3-3M1 10l3-3M1 14l3-3M1 18l3-3', 'thin')], + feaRoller: [P('M7 4h12v10H7z', 's'), P('M7 4h12v10H7z'), C(5, 7, 1.6, 'a'), C(5, 12, 1.6, 'a'), P('M2 3v14', 'thin')], + feaHinge: [C(12, 10, 6, 's'), C(12, 10, 6), C(12, 10, 2, 'a'), P('M5 21h14M12 16v5', 'thin')], + feaForce: [P('M4 15h16v5H4z', 's'), P('M4 15h16v5H4z'), P('M12 2v11', 'thick-a'), P('M9 10l3 3 3-3', 'a')], + feaPressure: [P('M4 15h16v5H4z', 's'), P('M4 15h16v5H4z'), P('M6 4v8M12 4v8M18 4v8', 'a'), P('M4.5 10l1.5 2 1.5-2M10.5 10l1.5 2 1.5-2M16.5 10l1.5 2 1.5-2', 'a')], + feaGravity: [P('M7 3h10v8H7z', 's'), P('M7 3h10v8H7z'), P('M12 12v9', 'thick-a'), P('M9 18l3 3 3-3', 'a'), P('M10 7h4', 'thin')], + feaMesh: [P('M3 20L12 4l9 16z', 's'), P('M3 20L12 4l9 16z'), P('M7.5 12h9M12 20l-4.5-8M12 20l4.5-8', 'thin')], + feaRun: [P('M6 4l14 8-14 8z', 'a'), P('M6 4l14 8-14 8z')], + feaResults: [['rect', { x: 4, y: 3, width: 6, height: 18, rx: 1, class: 's' }], P('M4 7h6M4 11h6M4 15h6', 'thin'), P('M13 5h7M13 12h7M13 19h7')], + feaReport: [P('M6 2h9l4 4v16H6z'), P('M15 2v4h4'), P('M9 18v-4M12 18v-7M15 18v-5', 'a')], + feaProbe: [P('M3 21l6-6'), C(13, 11, 6, 's'), C(13, 11, 6), P('M11 11h4M13 9v4', 'thin')], +}); + +let loading: Promise | null = null; +let workspace: FeaWorkspace | null = null; + +/** The analysis workspace, loaded (with the panels and the worker) the first time it is needed. */ +export async function feaWorkspace(app: App): Promise { + // A failed load (offline, an update replaced the files) is tried again by the next command. + loading ??= import('./workspace').catch((e: unknown) => { loading = null; throw e; }); + const m = await loading; + workspace ??= new m.FeaWorkspace(app); + return workspace; +} + +/** Runs fn with the workspace, loading it first; a failure to load or to start is told in a toast. */ +export function withWorkspace(app: App, fn: (ws: FeaWorkspace) => unknown) { + void feaWorkspace(app).then( + (ws) => Promise.resolve().then(() => fn(ws)).catch((e) => toast({ kind: 'error', message: `The analysis could not start: ${(e as Error).message}` })), + () => toast({ kind: 'error', message: 'The analysis could not be loaded. Check your connection and try again.' }), + ); +} + +/** The workspace if it has been loaded (the design tree shows results only then). */ +export function loadedFeaWorkspace(): FeaWorkspace | null { + return workspace; +} + +/** Index of a referenced face in the current part (by name, else the nearest face of the same kind and size), or -1. */ +export function faceIndexOf(app: App, ref: FaceRef): number { + const faces = app.faces; + const i = faces.findIndex((f) => f.name === ref.name && !f.body); + if (i >= 0) return i; + let best = -1, bd = Infinity; + faces.forEach((f, k) => { + if (f.body || f.type !== ref.sig.type) return; + const d = Math.hypot(f.center[0] - ref.sig.c[0], f.center[1] - ref.sig.c[1], f.center[2] - ref.sig.c[2]) + Math.abs(f.area - ref.sig.area) * 1e-3; + if (d < bd) { bd = d; best = k; } + }); + return bd < 1e-3 ? best : -1; +} + +export function installFea(app: App, hooks: AppHooks) { + const partOnly = () => !app.assembly && !app.inDrawing; + const withWs = (fn: (ws: FeaWorkspace) => void | Promise) => () => { + if (!partOnly()) return; + withWorkspace(app, fn); + }; + const hasStudy = () => partOnly() && !!app.store.doc.study; + const fixture = (type: FixtureType, desc: string, keywords: string): Command => ({ + id: `fea:${type}`, label: FIXTURE_LABELS[type], icon: FIXTURE_ICONS[type], description: desc, keywords: `fea analysis simulation fixture restraint support ${keywords}`, + enabled: partOnly, run: withWs((ws) => ws.newFixture(type)), + }); + const load = (type: FeaLoadType, label: string, desc: string, keywords: string): Command => ({ + id: `fea:${type}`, label, icon: LOAD_ICONS[type], description: desc, keywords: `fea analysis simulation load ${keywords}`, + enabled: partOnly, run: withWs((ws) => ws.newLoad(type)), + }); + const commands: Command[] = [ + { + id: 'fea:study', label: 'Static Study', icon: 'feaStudy', keywords: 'fea finite element analysis stress simulation static linear', + description: 'Set up a linear static stress analysis of the part: material, fixtures, loads and mesh.', enabled: partOnly, run: withWs((ws) => ws.openStudy()), + }, + fixture('fixed', 'Hold faces so they cannot move.', 'fixed clamp encastre'), + fixture('roller', 'Let faces slide along themselves but not move off them.', 'roller slider symmetry sliding'), + fixture('hinge', 'Let a cylindrical face (a pin hole) only turn about its axis.', 'hinge pin pivot bearing'), + load('force', 'Force', 'A total force on faces, normal to them or along a direction.', 'force newton push pull'), + load('pressure', 'Pressure', 'A pressure on faces, normal to them.', 'pressure psi pascal'), + load('gravity', 'Gravity', 'The part\'s own weight, from its material\'s density.', 'gravity weight self acceleration'), + { id: 'fea:mesh', label: 'Mesh', icon: 'feaMesh', keywords: 'fea mesh element size tetrahedra coarse fine', description: 'Set the element size and mesh the part.', enabled: hasStudy, run: withWs((ws) => ws.openMesh()) }, + { id: 'fea:run', label: 'Run', icon: 'feaRun', keywords: 'fea solve run calculate analysis', description: 'Mesh the part and solve the study.', enabled: hasStudy, run: withWs((ws) => ws.run()) }, + { + id: 'fea:results', label: 'Results', icon: 'feaResults', keywords: 'fea results stress displacement strain factor of safety plot von mises', description: 'Show the stress, displacement, strain and factor of safety plots.', + enabled: hasStudy, run: withWs((ws) => ws.showResults()), + }, + { id: 'fea:report', label: 'Report', icon: 'feaReport', keywords: 'fea report export csv print summary', description: 'Export the results summary as a CSV file or a printable report.', enabled: hasStudy, run: withWs((ws) => ws.report()) }, + ]; + app.commands.register(...commands); + + const tab: RibbonTab = { + id: 'analysis', label: 'Analysis', + groups: [ + [{ cmd: 'fea:study' }, { cmd: 'material' }], + [{ cmd: 'fea:fixed' }, { stack: [{ cmd: 'fea:roller' }, { cmd: 'fea:hinge' }] }], + [{ cmd: 'fea:force' }, { stack: [{ cmd: 'fea:pressure' }, { cmd: 'fea:gravity' }] }], + [{ cmd: 'fea:mesh' }, { cmd: 'fea:run' }], + [{ cmd: 'fea:results' }, { cmd: 'fea:report' }], + ], + labels: ['Study', 'Fixtures', 'Loads', 'Solve', 'Results'], + }; + // After CAM, before Drafting. + const at = hooks.ribbonTabs.findIndex((t) => t.id === 'drawing'); + hooks.ribbonTabs.splice(at < 0 ? hooks.ribbonTabs.length : at, 0, tab); + // A part opened with a study shows its symbols when the tab is chosen (the workspace loads then). + app.ribbonTabListeners.push((id) => { if (id === 'analysis' && app.store.doc.study && partOnly()) withWorkspace(app, (ws) => ws.redraw()); }); + // ...and when it is opened while the tab is shown (the symbols follow its first build). + app.store.on((reason) => { if (reason === 'load' && app.ribbonTabId === 'analysis' && app.store.doc.study && partOnly()) withWorkspace(app, (ws) => ws.redraw()); }); +} + +// ---------- design tree ---------- + +export function feaTreeRows(app: App, expanded: (key: string) => boolean): CamRow[] { + const s: StaticStudy | null | undefined = app.store.doc.study; + if (!s || app.assembly) return []; + const ws = loadedFeaWorkspace(); + const run = (fn: (ws: FeaWorkspace) => void) => () => withWorkspace(app, fn); + const open = expanded('fea'); + const state = ws?.state() ?? 'none'; + const rows: CamRow[] = [{ + key: 'fea', label: s.name, icon: 'feaStudy', depth: 1, children: true, expanded: open, selected: false, + muted: state === 'busy' ? ` ${ws?.progressText() ?? 'running'}` : '', + action: () => { if (app.ribbonTabId !== 'analysis') app.setRibbonTab('analysis'); }, + open: run((w) => w.openStudy()), + menu: (x, y) => app.openCommandMenu(['fea:run', 'fea:mesh', 'fea:results', 'fea:report', 'material'], x, y, 'Study menu'), + }]; + if (!open) return rows; + const missing = (faces: FaceRef[]) => (app.faces.length && faces.some((f) => faceIndexOf(app, f) < 0) ? { kind: 'error' as const, text: 'A face it uses is no longer in the part. Edit it and pick the faces again.' } : !faces.length ? { kind: 'error' as const, text: 'No faces picked' } : undefined); + for (const f of s.fixtures) { + rows.push({ + key: `fea:${f.id}`, label: f.name, icon: FIXTURE_ICONS[f.type], depth: 2, selected: ws?.focus === f.id, suppressed: !!f.suppressed, badge: missing(f.faces), + action: run((w) => w.focusItem(f.id)), open: run((w) => w.editItem(f.id)), menu: (x, y) => withWorkspace(app, (w) => w.itemMenu(f.id, x, y)), + }); + } + for (const l of s.loads) { + rows.push({ + key: `fea:${l.id}`, label: l.name, icon: LOAD_ICONS[l.type], depth: 2, selected: ws?.focus === l.id, suppressed: !!l.suppressed, badge: l.type === 'gravity' ? undefined : missing(l.faces), + action: run((w) => w.focusItem(l.id)), open: run((w) => w.editItem(l.id)), menu: (x, y) => withWorkspace(app, (w) => w.itemMenu(l.id, x, y)), + }); + } + const mesh = ws?.meshText() ?? ''; + rows.push({ + key: 'fea:mesh', label: 'Mesh', icon: 'feaMesh', depth: 2, muted: mesh ? ` ${mesh}` : ' (not meshed)', selected: false, + action: run((w) => w.openMesh()), open: run((w) => w.openMesh()), menu: (x, y) => app.openCommandMenu(['fea:mesh', 'fea:run'], x, y, 'Mesh menu'), + }); + rows.push({ + key: 'fea:results', label: 'Results', icon: 'feaResults', depth: 2, selected: false, + muted: state === 'none' ? ' (not run)' : state === 'busy' ? ' (running)' : '', + badge: state === 'stale' ? { kind: 'warn', text: 'Out of date: the part or the study changed since it was run. Run it again.' } : state === 'error' ? { kind: 'error', text: ws?.errorText() ?? 'The study could not be solved' } : undefined, + // Shows the results panel (with Run when there are none): a click in the tree does not start a solve. + action: run((w) => void w.openResults()), open: run((w) => void w.openResults()), menu: (x, y) => app.openCommandMenu(['fea:results', 'fea:run', 'fea:report'], x, y, 'Results menu'), + }); + return rows; +} + diff --git a/src/parametric/src/app/fea/panels.ts b/src/parametric/src/app/fea/panels.ts new file mode 100644 index 000000000..d7f8a4d90 --- /dev/null +++ b/src/parametric/src/app/fea/panels.ts @@ -0,0 +1,459 @@ +// PropertyManager panels of the analysis: the study (name, material, mesh), +// fixtures, loads, and the results with their plots, probe and summary. + +import type { FieldName } from '../../fea/results'; +import type { Vec3 } from '../../fea/static'; +import { FIXTURE_ICONS, FIXTURE_LABELS, GRAVITY, LOAD_ICONS, LOAD_LABELS, feaUnits, type FeaDir, type FeaFixture, type FeaLoad, type FixtureType } from '../../model/fea'; +import { elasticOf } from '../../model/materials'; +import type { FaceRef } from '../../model/types'; +import { formatNumber } from '../../model/units'; +import { h, nextDomId } from '../../ui/dom'; +import { icon } from '../../ui/icons'; +import type { App } from '../app'; +import { PropertyPanel, type SelBoxItem, SelectionBox, checkbox, section, segmented, selectField } from '../pm'; +import { edgeRef, faceRef, type SelItem } from '../selection'; +import { faceIndexOf } from './index'; +import { FIELD_LABELS, ResultPlot, fieldKind, formatValue } from './plot'; +import type { FeaWorkspace } from './workspace'; + +/** A number in a unit of its own (force, pressure, acceleration), stored in the base unit (value times scale). */ +function valueField(label: string, value: number, unit: string, scale: number, onChange: (v: number) => void, opts: { positive?: boolean } = {}): HTMLElement { + const id = nextDomId('fea'); + const show = (v: number) => Number((v / scale).toPrecision(8)).toString(); + const input = h('input', { class: 'input', id, inputmode: 'decimal', autocomplete: 'off', spellcheck: 'false', 'aria-label': `${label} (${unit})`, value: show(value) }) as HTMLInputElement; + const commit = () => { + const t = input.value.trim(); + const v = Number(t); + const bad = !t || !Number.isFinite(v) ? 'Enter a number' : opts.positive && !(v > 0) ? 'Must be greater than 0' : ''; + input.classList.toggle('invalid', !!bad); + if (bad) { input.setAttribute('aria-invalid', 'true'); input.title = bad; return; } + input.removeAttribute('aria-invalid'); + input.title = ''; + onChange(v * scale); + }; + input.addEventListener('input', commit); + input.addEventListener('change', commit); + return h('div', {}, h('label', { class: 'field-label', for: id }, `${label} (${unit})`), input); +} + +abstract class FeaPanel extends PropertyPanel { + readonly feaPanel = true; + constructor(readonly app: App, readonly ws: FeaWorkspace) { super(); } + + protected faceItems(refs: FaceRef[]): SelBoxItem[] { + return refs.map((r) => { + const i = faceIndexOf(this.app, r); + const item: SelItem | null = i >= 0 ? { kind: 'face', index: i, name: this.app.faces[i].name } : null; + return { item, data: r, label: item ? this.app.describe(item) : `${r.name} (missing)` }; + }); + } + + protected toFace(it: SelItem, type?: string): SelBoxItem | null { + if (it.kind !== 'face') return null; + const f = this.app.faces[it.index]; + if (!f || f.body) { this.setMessage('warn', 'Pick faces of the solid.'); return null; } + if (type && f.type !== type) { this.setMessage('warn', type === 'cylinder' ? 'Pick cylindrical faces (a pin hole or a shaft).' : 'Pick flat faces.'); return null; } + this.setMessage(null); + return { item: it, data: faceRef(f), label: this.app.describe(it) }; + } + + dispose() { + this.ws.redraw(); + } +} + +// ---------- study and mesh ---------- + +export class StudyPanel extends FeaPanel { + title = 'Static Study'; + icon = 'feaStudy'; + confirm = false; + private name: string; + private fineness: number; + + constructor(app: App, ws: FeaWorkspace) { + super(app, ws); + const s = ws.study!; + this.name = s.name; + this.fineness = s.mesh.fineness; + } + + /** Shows the progress (the status bar announces it); false when the panel has no progress bar yet (it is drawn again). */ + progress(b: { stage: string; progress: number }): boolean { + const bar = this.el.querySelector('progress'); + const label = this.el.querySelector('.fea-stage'); + if (bar) bar.value = b.progress; + if (label) label.textContent = b.stage; + return !!bar; + } + + private commit() { + const name = this.name.trim(); + this.app.store.change('Edit study', (d) => { + if (!d.study) return; + if (name) d.study.name = name; + d.study.mesh.fineness = this.fineness; + }); + } + + render(): HTMLElement[] { + const app = this.app, ws = this.ws; + const s = ws.study; + if (!s) return [section('Study', [h('p', { class: 'pm-msg' }, 'The study was deleted.')])]; + const nameInput = h('input', { class: 'input', value: this.name, 'aria-label': 'Study name' }) as HTMLInputElement; + // Taken after the focus moved on (Tab): the panel is drawn again then, and the focus stays where it went. + nameInput.addEventListener('change', () => { + // A study keeps a name: an emptied field shows it again. + if (!nameInput.value.trim()) nameInput.value = s.name; + this.name = nameInput.value; + setTimeout(() => this.commit()); + }); + const mat = app.store.doc.material; + const el = elasticOf(mat); + // In the part's stress unit, as the results are (psi in an inch part). + const su = feaUnits(app.store.doc.units); + const psi = (v: number) => `${Number((v / su.stressScale).toPrecision(3)).toLocaleString('en-US')} ${su.stress}`; + const elText = (e: NonNullable) => (su.stressScale === 1 ? `E ${formatNumber(e.E / 1000, 1)} GPa, ν ${e.nu}, yield ${e.yield} MPa` : `E ${psi(e.E)}, ν ${e.nu}, yield ${psi(e.yield)}`); + const matText = !mat ? 'No material chosen.' : el ? `${mat.name}: ${elText(el)}` : `${mat.name}: no elastic properties (cannot be analyzed).`; + const matBtn = h('button', { class: 'btn small', type: 'button', onclick: () => app.commands.run('material') }, icon('material', 16), 'Material...'); + // Mesh: coarse to fine. + const u = feaUnits(app.store.doc.units); + const slider = h('input', { type: 'range', min: '0', max: '1', step: '0.05', value: String(this.fineness), 'aria-label': 'Mesh density, coarse to fine', class: 'fea-slider' }) as HTMLInputElement; + const sizeText = h('div', { class: 'field-label', 'aria-live': 'polite' }); + const describe = () => { + const z = ws.sizes(this.fineness); + sizeText.textContent = z ? `Element size ${formatNumber(z.size / u.lengthScale, app.store.doc.decimals)} ${u.length} (automatic ${formatNumber(z.auto / u.lengthScale, app.store.doc.decimals)}), about ${z.dofs.toLocaleString('en-US')} unknowns${z.finest ? ' (the finest mesh solvable here)' : ''}` : 'Element size: found when the part is first meshed.'; + }; + describe(); + slider.addEventListener('input', () => { this.fineness = Number(slider.value); describe(); }); + slider.addEventListener('change', () => this.commit()); + const meshBtn = h('button', { class: 'btn small', type: 'button', disabled: !!ws.busy, onclick: () => void ws.meshNow() }, icon('feaMesh', 16), 'Mesh Now'); + const runBtn = h('button', { class: 'btn small primary', type: 'button', disabled: !!ws.busy, onclick: () => void ws.run() }, icon('feaRun', 16), 'Run'); + const m = ws.mesh; + const stats: HTMLElement[] = []; + if (ws.busy) stats.push(h('p', { class: 'field-label fea-stage' }, ws.busy.stage), h('progress', { max: '1', value: String(ws.busy.progress), 'aria-label': 'Progress' }), h('button', { class: 'btn small', type: 'button', onclick: () => ws.cancel() }, 'Cancel')); + if (m) { + const st = m.info.stats; + const volErr = (st.volume / st.surfaceVolume - 1) * 100; + stats.push(h('table', { class: 'table fea-stats' }, h('tbody', {}, + ...([ + ['Elements', st.elements.toLocaleString('en-US')], ['Nodes', st.nodes.toLocaleString('en-US')], + ['Element size', `${formatNumber(st.size / u.lengthScale, app.store.doc.decimals)} ${u.length}`], + ['Quality (worst / mean)', `${st.minQuality.toFixed(2)} / ${st.meanQuality.toFixed(2)}`], + ['Dihedral angles', `${st.minDihedral.toFixed(1)}° to ${st.maxDihedral.toFixed(1)}°`], + ['Volume against the part', `${volErr >= 0 ? '+' : ''}${volErr.toFixed(2)}%`], + ] as [string, string][]).map(([k, v]) => h('tr', {}, h('th', {}, k), h('td', { class: 'num' }, v)))))); + if (Math.abs(volErr) > 2) stats.push(h('p', { class: 'pm-msg warn', role: 'note' }, 'The mesh misses part of the volume: some walls are thinner than the elements. Use a finer mesh.')); + if (!ws.meshCurrent()) stats.push(h('p', { class: 'pm-msg warn', role: 'note' }, 'The part changed since it was meshed.')); + } + if (ws.error?.message && !ws.busy) stats.push(h('p', { class: 'pm-msg error', role: 'alert' }, ws.error.message)); + return [ + section('Study', [h('label', { class: 'field-label' }, 'Name'), nameInput, h('p', { class: 'field-label' }, 'Linear static: small displacements, linear elastic isotropic material.')], { icon: 'feaStudy' }), + section('Material', [h('p', { class: 'field-label fea-material' }, matText), matBtn], { icon: 'material' }), + section('Mesh', [h('div', { class: 'row fea-slider-row' }, h('span', { class: 'field-label' }, 'Coarse'), slider, h('span', { class: 'field-label' }, 'Fine')), sizeText, h('div', { class: 'row' }, meshBtn, runBtn), ...stats], { icon: 'feaMesh' }), + section('Delete', [h('button', { class: 'btn small danger', type: 'button', onclick: () => ws.deleteStudy() }, icon('trash', 16), 'Delete Study')], { collapsed: true }), + ]; + } + + ok() { return true; } + + dispose() { + super.dispose(); + this.app.renderer.setLines('feaMesh', null); + } +} + +// ---------- fixtures ---------- + +export class FixturePanel extends FeaPanel { + title: string; + icon: string; + + constructor(app: App, ws: FeaWorkspace, private f: FeaFixture, private creating: boolean) { + super(app, ws); + this.title = creating ? FIXTURE_LABELS[f.type] : f.name; + this.icon = FIXTURE_ICONS[f.type]; + } + + get present(): boolean { + return !!this.ws.study && (this.creating || this.ws.study.fixtures.some((x) => x.id === this.f.id)); + } + + get edited() { return true; } + + render(): HTMLElement[] { + const f = this.f; + const type = segmented('Fixture type', f.type, (['fixed', 'roller', 'hinge'] as FixtureType[]).map((t) => ({ value: t, label: FIXTURE_LABELS[t] })), (t) => { + f.type = t; + if (t === 'hinge') f.faces = f.faces.filter((r) => r.sig.type === 'cylinder'); + this.app.refreshPanel(); + }); + const help = f.type === 'fixed' ? 'The faces cannot move in any direction.' : f.type === 'roller' ? 'The faces can slide along themselves but not move off them (no motion normal to the face): also a symmetry plane.' : 'The cylindrical faces can only turn about their axis (a pin): no radial or axial motion.'; + const box = new SelectionBox(this, 'Faces', { face: true }, (it) => this.toFace(it, f.type === 'hinge' ? 'cylinder' : undefined), (items) => { f.faces = items.map((i) => i.data as FaceRef); }, { placeholder: 'Pick the faces to hold', icon: FIXTURE_ICONS[f.type] }); + box.setItems(this.faceItems(f.faces)); + return [section('Type', [type, h('p', { class: 'field-label' }, help)], { icon: FIXTURE_ICONS[f.type] }), section('Faces', [box.el])]; + } + + ok(): boolean { + const f = this.f; + if (!f.faces.length) { this.setMessage('error', 'Pick at least one face.'); return false; } + const label = this.creating ? `Add ${f.name}` : `Edit ${f.name}`; + this.app.store.change(label, (d) => { + if (!d.study) return; + const i = d.study.fixtures.findIndex((x) => x.id === f.id); + if (i >= 0) d.study.fixtures[i] = structuredClone(f); + else d.study.fixtures.push(structuredClone(f)); + }); + return true; + } +} + +// ---------- loads ---------- + +type DirChoice = 'normal' | 'x' | 'y' | 'z' | 'ref'; + +export class LoadPanel extends FeaPanel { + title: string; + icon: string; + private refItems: SelBoxItem[] = []; + + constructor(app: App, ws: FeaWorkspace, private l: FeaLoad, private creating: boolean) { + super(app, ws); + this.title = creating ? LOAD_LABELS[l.type] : l.name; + this.icon = LOAD_ICONS[l.type]; + if ((l.type === 'force' || l.type === 'gravity') && l.dir && l.dir.kind !== 'base') this.refItems = this.dirItems(l.dir); + } + + get present(): boolean { + return !!this.ws.study && (this.creating || this.ws.study.loads.some((x) => x.id === this.l.id)); + } + + get edited() { return true; } + + private dirItems(d: FeaDir): SelBoxItem[] { + if (d.kind === 'face') return this.faceItems([d.face]).map((x) => ({ ...x, data: d })); + if (d.kind === 'edge') { + const i = this.app.edges.findIndex((e) => e.name === d.edge.name); + const item: SelItem | null = i >= 0 ? { kind: 'edge', index: i, name: d.edge.name } : null; + return [{ item, data: d, label: item ? this.app.describe(item) : `${d.edge.name} (missing)` }]; + } + return []; + } + + private toDir(it: SelItem): SelBoxItem | null { + if (it.kind === 'face') { + const f = this.app.faces[it.index]; + if (!f || !(f.normal || f.axis)) { this.setMessage('warn', 'Pick a flat face (its normal) or a cylindrical face (its axis), or a straight edge.'); return null; } + return { item: it, data: { kind: 'face', face: faceRef(f) } satisfies FeaDir, label: this.app.describe(it) }; + } + if (it.kind === 'edge') { + const e = this.app.edges[it.index]; + if (!e || !(e.dir || e.axis)) { this.setMessage('warn', 'Pick a straight edge (its direction) or a circular edge (its axis).'); return null; } + return { item: it, data: { kind: 'edge', edge: edgeRef(e) } satisfies FeaDir, label: this.app.describe(it) }; + } + return null; + } + + render(): HTMLElement[] { + const l = this.l, app = this.app; + const u = feaUnits(app.store.doc.units); + const out: HTMLElement[] = []; + if (l.type !== 'gravity') { + const box = new SelectionBox(this, 'Faces', { face: true }, (it) => this.toFace(it), (items) => { l.faces = items.map((i) => i.data as FaceRef); }, { placeholder: 'Pick the faces it acts on', icon: LOAD_ICONS[l.type] }); + box.setItems(this.faceItems(l.faces)); + out.push(section('Faces', [box.el], { icon: LOAD_ICONS[l.type] })); + } + const value = l.type === 'force' ? valueField('Total force', l.value, u.force, u.forceScale, (v) => { l.value = v; }, { positive: true }) + : l.type === 'pressure' ? valueField('Pressure', l.value, u.stress, u.stressScale, (v) => { l.value = v; }, { positive: true }) + : valueField('Acceleration', l.value, u.accel, u.accelScale, (v) => { l.value = v; }, { positive: true }); + const items: HTMLElement[] = [value]; + if (l.type === 'force' || l.type === 'gravity') { + const choice: DirChoice = this.pickRef ? 'ref' : !l.dir ? 'normal' : l.dir.kind === 'base' ? l.dir.axis : 'ref'; + const options: { value: DirChoice; label: string }[] = [ + ...(l.type === 'force' ? [{ value: 'normal' as DirChoice, label: 'Normal to the faces' }] : []), + { value: 'x', label: 'Along X' }, { value: 'y', label: 'Along Y' }, { value: 'z', label: 'Along Z' }, + { value: 'ref', label: 'Along a picked edge or face' }, + ]; + items.push(selectField('Direction', choice, options, (v) => { + if (v === 'normal' && l.type === 'force') l.dir = null; + else if (v === 'x' || v === 'y' || v === 'z') l.dir = { kind: 'base', axis: v }; + else if (v === 'ref') l.dir = (this.refItems[0]?.data as FeaDir | undefined) ?? (l.type === 'force' ? null : l.dir); + // Picking a reference: the choice stays shown while the direction is not picked yet. + this.pickRef = v === 'ref' && !this.refItems.length; + app.refreshPanel(); + })); + if (choice === 'ref') { + const ref = new SelectionBox(this, 'Direction reference', { face: true, edge: true }, (it) => this.toDir(it), (sel) => { + this.refItems = sel; + if (sel[0]) l.dir = sel[0].data as FeaDir; + else this.pickRef = true; + }, { single: true, placeholder: 'Pick an edge or a face', icon: 'axis' }); + ref.setItems(this.refItems); + items.push(ref.el); + queueMicrotask(() => this.activate(ref)); + } + } + items.push(checkbox(l.type === 'gravity' ? 'Reverse direction' : l.type === 'pressure' ? 'Reverse direction (pull on the faces)' : 'Reverse direction', l.flip, (v) => { l.flip = v; this.ws.redraw(); })); + const help = l.type === 'force' ? (l.dir ? 'The total force is spread evenly over the faces\' area.' : 'Normal to the faces, pressing on them: spread as a pressure (on a curved face the pieces point different ways).') + : l.type === 'pressure' ? 'Pushes into the faces, normal to them everywhere.' : `The part's weight from its density, along the direction (${(GRAVITY / u.accelScale).toFixed(u.accel === 'm/s²' ? 3 : 1)} ${u.accel} is standard gravity).`; + out.push(section('Value', [...items, h('p', { class: 'field-label' }, help)], { icon: LOAD_ICONS[l.type] })); + return out; + } + + private pickRef = false; + + ok(): boolean { + const l = this.l; + if (l.type !== 'gravity' && !l.faces.length) { this.setMessage('error', 'Pick at least one face.'); return false; } + if (!(l.value > 0) || !Number.isFinite(l.value)) { this.setMessage('error', 'Enter a value greater than 0.'); return false; } + if (this.pickRef && (l.type === 'force' || l.type === 'gravity') && !this.refItems.length) { this.setMessage('error', 'Pick an edge or face for the direction.'); return false; } + this.app.store.change(this.creating ? `Add ${l.name}` : `Edit ${l.name}`, (d) => { + if (!d.study) return; + const i = d.study.loads.findIndex((x) => x.id === l.id); + if (i >= 0) d.study.loads[i] = structuredClone(l); + else d.study.loads.push(structuredClone(l)); + }); + return true; + } +} + +// ---------- results ---------- + +const FIELDS: FieldName[] = ['vonMises', 'p1', 'p2', 'p3', 'disp', 'ux', 'uy', 'uz', 'strain', 'fos']; + +export class ResultsPanel extends FeaPanel { + title = 'Results'; + icon = 'feaResults'; + confirm = false; + private plot: ResultPlot | null = null; + private plotted: unknown = null; + private field: FieldName = 'vonMises'; + + /** Shows the progress (the status bar announces it); false when the panel has no progress bar yet (it is drawn again). */ + progress(b: { stage: string; progress: number }): boolean { + const bar = this.el.querySelector('progress'); + const label = this.el.querySelector('.fea-stage'); + if (bar) bar.value = b.progress; + if (label) label.textContent = b.stage; + return !!bar; + } + + render(): HTMLElement[] { + const app = this.app, ws = this.ws; + if (ws.busy) { + return [section('Running', [ + h('p', { class: 'field-label fea-stage' }, ws.busy.stage), + h('progress', { max: '1', value: String(ws.busy.progress), 'aria-label': 'Analysis progress' }), + h('button', { class: 'btn small', type: 'button', onclick: () => ws.cancel() }, 'Cancel'), + ], { icon: 'feaRun' })]; + } + const res = ws.result; + const err = ws.error; + const msgs: HTMLElement[] = []; + if (err) msgs.push(h('p', { class: 'pm-msg error', role: 'alert' }, err.message)); + if (!res) { + this.disposePlot(); + return [section('Results', [...msgs, h('p', { class: 'field-label' }, 'Run the study to see its results.'), h('button', { class: 'btn small primary', type: 'button', onclick: () => void ws.run() }, icon('feaRun', 16), 'Run')], { icon: 'feaResults' })]; + } + const s = res.sol.summary; + for (const w of s.warnings ?? []) msgs.push(h('p', { class: 'pm-msg warn', role: 'note' }, w)); + if (ws.state() === 'stale') msgs.push(h('p', { class: 'pm-msg warn', role: 'note' }, 'Out of date: the part, the study or the material changed since it was run.'), h('button', { class: 'btn small', type: 'button', onclick: () => void ws.run() }, icon('feaRun', 16), 'Run Again')); + if (s.maxVonMises.value > res.yield) msgs.push(h('p', { class: 'pm-msg error', role: 'alert' }, `The highest von Mises stress (${formatValue(app, s.maxVonMises.value, 'stress')}) is above the yield strength of ${res.material} (${formatValue(app, res.yield, 'stress')}): the part would yield there, and a linear analysis no longer describes it.`)); + const b = app.bbox; + const size = b ? Math.hypot(b.max[0] - b.min[0], b.max[1] - b.min[1], b.max[2] - b.min[2]) : 0; + if (size && s.maxDisplacement.value > 0.05 * size) msgs.push(h('p', { class: 'pm-msg warn', role: 'note' }, 'The part moves by more than 5% of its size: a linear (small displacement) analysis may not describe it well.')); + // The plot. + if (!this.plot) { + this.plot = new ResultPlot(app, res.mesh, res.sol, res.yield); + this.plot.onProbe = () => this.drawProbes(); + this.plotted = res; + this.ws.plotting = true; + const plot = this.plot; + this.ws.plotCaption = () => plot.caption(); + this.ws.redraw(); + this.plot.field = this.field; + this.plot.draw(); + } else if (this.plotted !== res) { + this.plotted = res; + this.plot.setResult(res.mesh, res.sol, res.yield); + } + const plot = this.plot; + const field = selectField('Plot', plot.field, FIELDS.map((f) => ({ value: f, label: FIELD_LABELS[f] })), (v) => { plot.field = this.field = v; plot.draw(); this.drawProbes(); }); + const deform = selectField<'auto' | 'true' | 'none'>('Deformed shape', plot.deform, [{ value: 'auto', label: 'Deformed (automatic scale)' }, { value: 'true', label: 'Deformed (true scale)' }, { value: 'none', label: 'Undeformed' }], (v) => { plot.deform = v; plot.draw(); }); + const mesh = checkbox('Show the mesh', plot.showMesh, (v) => { plot.showMesh = v; plot.draw(); }); + const probe = h('button', { class: 'btn small', type: 'button', 'aria-pressed': String(plot.probing) }, icon('feaProbe', 16), 'Probe') as HTMLButtonElement; + probe.addEventListener('click', () => { plot.setProbing(!plot.probing); probe.setAttribute('aria-pressed', String(plot.probing)); this.drawProbes(); }); + const clear = h('button', { class: 'btn small', type: 'button', onclick: () => { plot.probes = []; plot.draw(); this.drawProbes(); } }, 'Clear'); + this.probeList = h('div', { class: 'fea-probes', 'aria-live': 'polite' }); + queueMicrotask(() => this.drawProbes()); + const rows: [string, string][] = [ + ['Max von Mises stress', formatValue(app, s.maxVonMises.value, 'stress')], + [' at', this.point(s.maxVonMises.at)], + ['Yield strength', `${formatValue(app, res.yield, 'stress')} (${res.material})`], + ['Min factor of safety', s.maxVonMises.value > 0 ? (res.yield / s.maxVonMises.value).toFixed(2) : '∞'], + ['Max displacement', formatValue(app, s.maxDisplacement.value, 'length')], + [' at', this.point(s.maxDisplacement.at)], + ['Max principal stress', formatValue(app, s.maxP1.value, 'stress')], + ['Min principal stress', formatValue(app, s.minP3.value, 'stress')], + ['Max equivalent strain', s.maxStrain.value.toExponential(3)], + ]; + const u = feaUnits(app.store.doc.units); + const force = (v: Vec3) => `${v.map((x) => formatNumber(x / u.forceScale, 3)).join(', ')} ${u.force}`; + const total = s.reactions.reduce((a, r) => [a[0] + r[0], a[1] + r[1], a[2] + r[2]], [0, 0, 0]); + const imbalance = Math.hypot(total[0] + s.applied[0], total[1] + s.applied[1], total[2] + s.applied[2]) / Math.max(Math.hypot(...s.applied), 1e-30); + const forces: [string, string][] = [ + ['Applied loads (sum)', force(s.applied)], + ...res.fixtureNames.map((n, i) => [`Reaction: ${n}`, force(s.reactions[i])] as [string, string]), + ['Reactions (sum)', force(total)], + ['Equilibrium error', `${(imbalance * 100).toExponential(1)}%`], + ]; + const st = res.mesh.stats; + const solve: [string, string][] = [ + ['Mesh', `${st.elements.toLocaleString('en-US')} elements, ${st.nodes.toLocaleString('en-US')} nodes`], + ['Unknowns', s.dofs.toLocaleString('en-US')], + ['Element quality (worst)', st.minQuality.toFixed(2)], + ['Solver', `${s.iterations} iterations, ${((s.ms.assemble + s.ms.setup + s.ms.solve + s.ms.stress) / 1000).toFixed(1)} s`], + ]; + const table = (r: [string, string][], cls: string) => h('table', { class: `table ${cls}` }, h('tbody', {}, ...r.map(([k, v]) => h('tr', {}, h('th', {}, k.trim()), h('td', { class: 'num' }, v))))); + return [ + ...(msgs.length ? [section('Messages', msgs)] : []), + section('Plot', [field, deform, mesh, h('div', { class: 'row' }, probe, clear), this.probeList], { icon: 'feaResults' }), + section('Summary', [table(rows, 'fea-summary')], { icon: 'feaStudy' }), + section('Forces', [table(forces, 'fea-forces')], { collapsed: false }), + section('Mesh and solver', [table(solve, 'fea-solve')], { collapsed: true }), + section('Export', [h('div', { class: 'row' }, h('button', { class: 'btn small', type: 'button', onclick: () => ws.report() }, icon('feaReport', 16), 'Report...'))]), + ]; + } + + private probeList: HTMLElement | null = null; + + private point(p: Vec3): string { + const u = feaUnits(this.app.store.doc.units); + return `(${p.map((x) => formatNumber(x / u.lengthScale, this.app.store.doc.decimals)).join(', ')}) ${u.length}`; + } + + private drawProbes() { + const list = this.probeList, plot = this.plot; + if (!list || !plot) return; + list.textContent = ''; + if (plot.probing && !plot.probes.length) list.append(h('p', { class: 'field-label' }, 'Click the plot to read the value there.')); + const kind = fieldKind(plot.field); + plot.probes.forEach((p, i) => list.append(h('div', { class: 'fea-probe' }, h('b', {}, `${i + 1}`), h('span', {}, formatValue(this.app, p.value, kind)), h('span', { class: 'field-label' }, this.point(plot.probePoint(p)))))); + } + + private disposePlot() { + if (!this.plot) return; + this.plot.dispose(); + this.plot = null; + this.ws.plotting = false; + this.ws.plotCaption = null; + this.ws.redraw(); + } + + ok() { return true; } + + dispose() { + this.disposePlot(); + super.dispose(); + } +} diff --git a/src/parametric/src/app/fea/plot.ts b/src/parametric/src/app/fea/plot.ts new file mode 100644 index 000000000..eb732bc3c --- /dev/null +++ b/src/parametric/src/app/fea/plot.ts @@ -0,0 +1,264 @@ +// A result plot in the graphics area: the mesh's boundary, deformed by the +// displacements times a scale, coloured by a field with a legend, the mesh +// lines on request, and probe pins that read the field where they are put. + +import { type FeaMeshInfo, type FeaSolution, type FieldName, SUB, colorAt, fieldValues, interpolate, rayHit } from '../../fea/results'; +import type { Vec3 } from '../../fea/static'; +import { feaUnits } from '../../model/fea'; +import type { SolidBatch } from '../../render/renderer'; +import { h } from '../../ui/dom'; +import type { App } from '../app'; +import type { ViewportTool } from '../viewport'; + +export const FIELD_LABELS: Record = { + vonMises: 'von Mises stress', p1: 'Principal stress 1 (largest)', p2: 'Principal stress 2', p3: 'Principal stress 3 (smallest)', + disp: 'Displacement', ux: 'Displacement X', uy: 'Displacement Y', uz: 'Displacement Z', strain: 'Equivalent strain', fos: 'Factor of safety', +}; + +export type FieldKind = 'stress' | 'length' | 'none'; +export const fieldKind = (f: FieldName): FieldKind => (f === 'vonMises' || f === 'p1' || f === 'p2' || f === 'p3' ? 'stress' : f === 'disp' || f === 'ux' || f === 'uy' || f === 'uz' ? 'length' : 'none'); + +/** Factor of safety plots stop at this value (larger ones show its colour). */ +export const FOS_CAP = 10; + +export interface Probe { + at: Vec3; + value: number; + tri: number; + s: number; + t: number; +} + +/** A value with its unit in the part's units: stress (MPa in), displacement (mm in), or a plain number. */ +export function formatValue(app: App, v: number, kind: FieldKind): string { + if (!Number.isFinite(v)) return v > 0 ? '∞' : '–'; + const u = feaUnits(app.store.doc.units); + const sig = (x: number, d = 4) => (x === 0 ? '0' : Math.abs(x) >= 1e5 || Math.abs(x) < 1e-3 ? x.toExponential(d - 1) : Number(x.toPrecision(d)).toString()); + if (kind === 'stress') return `${sig(v / u.stressScale)} ${u.stress}`; + if (kind === 'length') return `${sig(v / u.lengthScale)} ${u.length}`; + return sig(v); +} + +export class ResultPlot { + field: FieldName = 'vonMises'; + /** 'auto': the largest displacement shown as a twentieth of the part's size; 'true': as it is; 'none': undeformed. */ + deform: 'auto' | 'true' | 'none' = 'auto'; + showMesh = false; + probes: Probe[] = []; + probing = false; + private legend: HTMLElement | null = null; + private pins: HTMLElement | null = null; + private positions: Float32Array | null = null; + private values: Float32Array | null = null; + private modelHidden = false; + private prevCamera: (() => void) | null = null; + private tool: ViewportTool | null = null; + onProbe: () => void = () => {}; + + constructor(private readonly app: App, private mesh: FeaMeshInfo, private sol: FeaSolution, private yieldStrength: number) {} + + setResult(mesh: FeaMeshInfo, sol: FeaSolution, yieldStrength: number) { + this.mesh = mesh; + this.sol = sol; + this.yieldStrength = yieldStrength; + this.probes = []; + this.draw(); + } + + /** The deformation scale in use. */ + scale(): number { + if (this.deform === 'none') return 0; + if (this.deform === 'true') return 1; + const max = this.sol.summary.maxDisplacement.value; + const st = this.mesh.stats; + const b = this.bounds(); + const size = Math.hypot(b[3] - b[0], b[4] - b[1], b[5] - b[2]) || st.size * 10; + return max > 0 ? (0.05 * size) / max : 0; + } + + private bounds(): number[] { + const P = this.mesh.nodes; + const b = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity]; + for (let i = 0; i < P.length; i += 3) for (let k = 0; k < 3; k++) { b[k] = Math.min(b[k], P[i + k]); b[k + 3] = Math.max(b[k + 3], P[i + k]); } + return b; + } + + /** Range of the shown field (factor of safety: from its smallest to the cap). */ + range(): [number, number] { + const v = this.values ?? fieldValues(this.sol, this.field, this.yieldStrength); + let lo = Infinity, hi = -Infinity; + for (let i = 0; i < v.length; i++) { const x = this.field === 'fos' ? Math.min(v[i], FOS_CAP) : v[i]; if (x < lo) lo = x; if (x > hi) hi = x; } + if (this.field === 'fos') hi = Math.max(hi, lo); + return [lo, hi]; + } + + draw() { + const app = this.app, r = app.renderer; + const { nodes, tris, triFace } = this.mesh; + const values = fieldValues(this.sol, this.field, this.yieldStrength); + this.values = values; + const [lo, hi] = this.range(); + const k = this.scale(); + const U = this.sol.fields[0]; + const n = nodes.length / 3; + const pos = new Float32Array(n * 3); + for (let i = 0; i < n * 3; i++) pos[i] = nodes[i] + k * U[i]; + this.positions = pos; + // Vertices per node and face, so normals are smooth within a face and sharp between faces. + const vid = new Map(); + const vp: number[] = [], vc: number[] = [], idx: number[] = []; + const nf = 1 + Math.max(0, ...triFace); + const tcol = (x: number) => { + const t = hi > lo ? (Math.min(x, this.field === 'fos' ? FOS_CAP : Infinity) - lo) / (hi - lo) : 0.5; + // Low factors of safety are the ones to see: red. + return colorAt(this.field === 'fos' ? 1 - t : t); + }; + const vertex = (node: number, face: number) => { + const key = node * (nf + 1) + face + 1; + let v = vid.get(key); + if (v === undefined) { + v = vp.length / 3; + vid.set(key, v); + vp.push(pos[node * 3], pos[node * 3 + 1], pos[node * 3 + 2]); + vc.push(...tcol(values[node]), 255); + } + return v; + }; + const nt = tris.length / 6; + for (let f = 0; f < nt; f++) { + for (const [a, b, c] of SUB) idx.push(vertex(tris[f * 6 + a], triFace[f]), vertex(tris[f * 6 + b], triFace[f]), vertex(tris[f * 6 + c], triFace[f])); + } + const nor = new Float32Array(vp.length); + for (let q = 0; q < idx.length; q += 3) { + const a = idx[q] * 3, b = idx[q + 1] * 3, c = idx[q + 2] * 3; + const ux = vp[b] - vp[a], uy = vp[b + 1] - vp[a + 1], uz = vp[b + 2] - vp[a + 2], wx = vp[c] - vp[a], wy = vp[c + 1] - vp[a + 1], wz = vp[c + 2] - vp[a + 2]; + const nx = uy * wz - uz * wy, ny = uz * wx - ux * wz, nz = ux * wy - uy * wx; + for (const v of [a, b, c]) { nor[v] += nx; nor[v + 1] += ny; nor[v + 2] += nz; } + } + for (let i = 0; i < nor.length; i += 3) { const l = Math.hypot(nor[i], nor[i + 1], nor[i + 2]) || 1; nor[i] /= l; nor[i + 1] /= l; nor[i + 2] /= l; } + const batch: SolidBatch = { positions: new Float32Array(vp), normals: nor, colors: new Uint8Array(vc), indices: new Uint32Array(idx) }; + if (!this.modelHidden) { r.setModel(null, 1, 1); this.modelHidden = true; } + r.setSolid('feaPlot', batch); + if (this.showMesh) { + const L = this.mesh.lines; + // The mesh lines follow the deformed shape: move each end point by its node's displacement (nodes found by position). + const at = new Map(); + for (let i = 0; i < n; i++) at.set(`${nodes[i * 3]},${nodes[i * 3 + 1]},${nodes[i * 3 + 2]}`, i); + const lp = new Float32Array(L.length); + for (let i = 0; i < L.length; i += 3) { + const v = at.get(`${L[i]},${L[i + 1]},${L[i + 2]}`); + for (let c = 0; c < 3; c++) lp[i + c] = L[i + c] + (v === undefined ? 0 : k * U[v * 3 + c]); + } + r.setLines('feaMesh', { positions: lp, colors: new Uint8Array((L.length / 6) * 4).map((_, i) => (i % 4 === 3 ? 160 : 30)), width: 1, depth: 'test', order: 6, bias: 4e-5 }); + } else r.setLines('feaMesh', null); + // Probes follow the deformed shape and the field shown. + for (const p of this.probes) { + p.value = interpolate(values, tris, p.tri, p.s, p.t); + p.at = [0, 1, 2].map((c) => interpolate(pos, tris, p.tri, p.s, p.t, 3, c)) as Vec3; + } + this.drawLegend(lo, hi); + this.placePins(); + if (!this.prevCamera) { + const prev = r.onCamera; + this.prevCamera = prev; + r.onCamera = () => { prev(); this.placePins(); }; + } + } + + /** What the plot shows, in words (the printed report has no legend of its own). */ + caption(): string { + const [lo, hi] = this.range(); + const kind = fieldKind(this.field); + const top = this.field === 'fos' && hi >= FOS_CAP ? `${FOS_CAP} or more` : formatValue(this.app, hi, kind); + const colours = this.field === 'fos' ? 'red lowest, blue highest' : 'blue lowest, red highest'; + const k = this.scale(); + const shape = this.deform === 'none' ? 'undeformed shape' : `deformation scale ${k >= 100 ? Math.round(k).toLocaleString('en-US') : Number(k.toPrecision(3))}${this.deform === 'true' ? ' (true scale)' : ''}`; + return `${FIELD_LABELS[this.field]} from ${formatValue(this.app, lo, kind)} to ${top} (${colours}); ${shape}.`; + } + + private drawLegend(lo: number, hi: number) { + const app = this.app; + this.legend?.remove(); + const kind = fieldKind(this.field); + const u = feaUnits(app.store.doc.units); + const unit = kind === 'stress' ? u.stress : kind === 'length' ? u.length : ''; + const ticks = h('div', { class: 'fea-legend-ticks' }); + const N = 6; + // The ticks share their decimals (enough for the step between them), so they line up and read evenly. + const scaleOf = kind === 'stress' ? u.stressScale : kind === 'length' ? u.lengthScale : 1; + const step = (hi - lo) / scaleOf / (N - 1); + // Values of 100,000 and more read better as powers of ten, as elsewhere (formatValue). + const big = Math.max(Math.abs(lo), Math.abs(hi)) / scaleOf >= 1e5; + const digits = step > 0 && !big ? 2 - Math.floor(Math.log10(step)) : NaN; + for (let i = 0; i < N; i++) { + const v = hi - ((hi - lo) * i) / (N - 1); + const fixed = digits <= 8 ? (v / scaleOf).toFixed(Math.max(0, digits)).replace(/^-(0\.?0*)$/, '$1') : null; + const top = this.field === 'fos' && i === 0 && hi >= FOS_CAP ? `≥ ${FOS_CAP}` : fixed ?? formatValue(app, v, kind).replace(` ${unit}`, ''); + ticks.append(h('span', {}, top)); + } + const stops = Array.from({ length: 9 }, (_, i) => { const c = colorAt(this.field === 'fos' ? i / 8 : 1 - i / 8); return `rgb(${c.join(',')}) ${(i / 8) * 100}%`; }); + const bar = h('div', { class: 'fea-legend-bar', style: { background: `linear-gradient(to bottom, ${stops.join(', ')})` } }); + const extra: HTMLElement[] = []; + if (kind === 'stress' && this.field === 'vonMises') extra.push(h('div', { class: 'fea-legend-note' }, `Yield strength: ${formatValue(app, this.yieldStrength, 'stress')}`)); + const k = this.scale(); + extra.push(h('div', { class: 'fea-legend-note' }, this.deform === 'none' ? 'Undeformed shape' : `Deformation scale: ${k >= 100 ? Math.round(k).toLocaleString('en-US') : Number(k.toPrecision(3))}${this.deform === 'true' ? ' (true scale)' : ''}`)); + this.legend = h('div', { class: 'fea-legend', role: 'img', 'aria-label': `Legend: ${FIELD_LABELS[this.field]} from ${formatValue(app, lo, kind)} to ${formatValue(app, hi, kind)}` }, + h('div', { class: 'fea-legend-title' }, `${FIELD_LABELS[this.field]}${unit ? ` (${unit})` : ''}`), + h('div', { class: 'fea-legend-scale' }, bar, ticks), ...extra); + app.shell.viewport.append(this.legend); + } + + private placePins() { + const app = this.app; + if (!this.pins) { this.pins = h('div', { class: 'fea-pins', 'aria-hidden': 'true' }); app.shell.viewport.append(this.pins); } + this.pins.textContent = ''; + const cam = app.renderer.camera; + const kind = fieldKind(this.field); + this.probes.forEach((p, i) => { + const [x, y, z] = cam.project(p.at); + if (z < -1 || z > 1) return; + this.pins!.append(h('div', { class: 'fea-pin', style: { left: `${x}px`, top: `${y}px` } }, h('span', {}, `${i + 1}: ${formatValue(app, p.value, kind)}`))); + }); + } + + /** Turns probing on or off: a click on the plot reads the field there. */ + setProbing(on: boolean) { + this.probing = on; + const vp = this.app.viewport; + if (on) { + this.tool = { + click: (ev) => { + const hit = this.positions && rayHit(this.positions, this.mesh.tris, ev.ray.o, ev.ray.d); + if (!hit || !this.values) return true; + const at = [0, 1, 2].map((c) => interpolate(this.positions!, this.mesh.tris, hit.tri, hit.u, hit.v, 3, c)) as Vec3; + this.probes.push({ at, value: interpolate(this.values, this.mesh.tris, hit.tri, hit.u, hit.v), tri: hit.tri, s: hit.u, t: hit.v }); + this.placePins(); + this.onProbe(); + return true; + }, + }; + vp.tool = this.tool; + } else if (vp.tool === this.tool) { + vp.tool = null; + this.tool = null; + } + } + + /** Undeformed position of a probe (for listing it in model coordinates). */ + probePoint(p: Probe): Vec3 { + const { nodes, tris } = this.mesh; + return [0, 1, 2].map((c) => interpolate(nodes, tris, p.tri, p.s, p.t, 3, c)) as Vec3; + } + + dispose() { + const app = this.app; + this.setProbing(false); + if (this.prevCamera) { app.renderer.onCamera = this.prevCamera; this.prevCamera = null; } + app.renderer.setSolid('feaPlot', null); + app.renderer.setLines('feaMesh', null); + this.legend?.remove(); + this.pins?.remove(); + this.legend = this.pins = null; + if (this.modelHidden) { app.showModelMesh(); this.modelHidden = false; } + } +} diff --git a/src/parametric/src/app/fea/report.ts b/src/parametric/src/app/fea/report.ts new file mode 100644 index 000000000..eaff78494 --- /dev/null +++ b/src/parametric/src/app/fea/report.ts @@ -0,0 +1,110 @@ +// The results summary as a CSV file or a printable report (HTML in a new +// window, printed or saved as PDF by the browser). + +import { feaUnits } from '../../model/fea'; +import { formatNumber } from '../../model/units'; +import { download } from '../../platform/files'; +import type { Vec3 } from '../../fea/static'; +import { h } from '../../ui/dom'; +import { showDialog, toast } from '../../ui/overlay'; +import type { App } from '../app'; +import type { FeaResult, FeaWorkspace } from './workspace'; + +interface Line { section: string; name: string; value: string; unit: string } + +/** The summary as rows: section, quantity, value (in the part's units), unit. */ +export function summaryRows(app: App, ws: FeaWorkspace, r: FeaResult): Line[] { + const u = feaUnits(app.store.doc.units); + const s = r.sol.summary, st = r.mesh.stats; + const out: Line[] = []; + const add = (section: string, name: string, value: string | number, unit = '') => out.push({ section, name, value: typeof value === 'number' ? String(Number(value.toPrecision(6))) : value, unit }); + const L = (x: number) => x / u.lengthScale, S = (x: number) => x / u.stressScale, F = (x: number) => x / u.forceScale; + const at = (p: Vec3) => p.map((x) => formatNumber(L(x), app.store.doc.decimals)).join(' '); + add('Study', 'Part', app.store.doc.name); + add('Study', 'Study', ws.study?.name ?? ''); + add('Study', 'Type', 'Linear static (small displacements, linear elastic isotropic material)'); + add('Study', 'Solved', new Date(r.when).toISOString()); + add('Study', 'Up to date', ws.state() === 'ok' ? 'yes' : 'no (the part or the study changed since)'); + add('Material', 'Name', r.material); + add('Material', 'Elastic modulus', S(r.input.E), u.stress); + add('Material', 'Poisson\'s ratio', r.input.nu); + add('Material', 'Yield strength', S(r.yield), u.stress); + add('Material', 'Tensile strength', S(r.uts), u.stress); + add('Material', 'Density', r.input.density * 1e12, 'kg/m³'); + add('Results', 'Max von Mises stress', S(s.maxVonMises.value), u.stress); + add('Results', 'Max von Mises stress at', at(s.maxVonMises.at), u.length); + add('Results', 'Min factor of safety (yield / von Mises)', s.maxVonMises.value > 0 ? r.yield / s.maxVonMises.value : 'infinite'); + add('Results', 'Max displacement', L(s.maxDisplacement.value), u.length); + add('Results', 'Max displacement at', at(s.maxDisplacement.at), u.length); + add('Results', 'Max principal stress', S(s.maxP1.value), u.stress); + add('Results', 'Min principal stress', S(s.minP3.value), u.stress); + add('Results', 'Max equivalent strain', s.maxStrain.value); + for (const w of s.warnings ?? []) add('Results', 'Note', w); + add('Results', 'Yielding', s.maxVonMises.value > r.yield ? 'yes: stress above yield, the linear analysis no longer holds there' : 'no'); + // One quantity per row, its unit in the unit column. + r.loadNames.forEach((n, i) => { + const ld = r.input.loads[i]; + if (ld.kind === 'gravity') { add('Loads', `${n} acceleration`, Math.hypot(...ld.accel) / u.accelScale, u.accel); return; } + if (ld.kind === 'pressure') add('Loads', `${n} pressure`, S(ld.value), u.stress); + else add('Loads', `${n} force`, F(ld.total), u.force); + add('Loads', `${n} area`, s.loadAreas[i] / u.lengthScale ** 2, `${u.length}²`); + }); + for (const [k, v] of [['X', 0], ['Y', 1], ['Z', 2]] as const) add('Forces', `Applied loads (sum) ${k}`, F(s.applied[v]), u.force); + r.fixtureNames.forEach((n, i) => { for (const [k, v] of [['X', 0], ['Y', 1], ['Z', 2]] as const) add('Forces', `Reaction ${n} ${k}`, F(s.reactions[i][v]), u.force); }); + const total = s.reactions.reduce((a, x) => [a[0] + x[0], a[1] + x[1], a[2] + x[2]], [0, 0, 0]); + const imbalance = Math.hypot(total[0] + s.applied[0], total[1] + s.applied[1], total[2] + s.applied[2]) / Math.max(Math.hypot(...s.applied), 1e-30); + add('Forces', 'Equilibrium error (|reactions + loads| / |loads|)', imbalance); + add('Mesh', 'Element type', '10-node quadratic tetrahedra'); + add('Mesh', 'Element size', L(st.size), u.length); + add('Mesh', 'Elements', st.elements); + add('Mesh', 'Nodes', st.nodes); + add('Mesh', 'Unknowns', s.dofs); + add('Mesh', 'Worst element quality (mean ratio)', st.minQuality); + add('Mesh', 'Mean element quality', st.meanQuality); + add('Mesh', 'Volume against the part', `${((st.volume / st.surfaceVolume - 1) * 100).toFixed(3)}`, '%'); + add('Solver', 'Method', `Conjugate gradients, ${s.solver}`); + add('Solver', 'Iterations', s.iterations); + add('Solver', 'Relative residual', s.residual); + add('Solver', 'Time', (s.ms.assemble + s.ms.setup + s.ms.solve + s.ms.stress) / 1000, 's'); + return out; +} + +const csvCell = (v: string) => (/[",\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v); + +export function summaryCsv(rows: Line[]): string { + return ['Section,Quantity,Value,Unit', ...rows.map((r) => [r.section, r.name, r.value, r.unit].map(csvCell).join(','))].join('\n') + '\n'; +} + +const esc = (s: string) => s.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]!); + +export function reportHtml(title: string, rows: Line[], image: string | null, caption = ''): string { + const sections = [...new Set(rows.map((r) => r.section))]; + const body = sections.map((s) => `

${esc(s)}

${rows.filter((r) => r.section === s).map((r) => ``).join('')}
${esc(r.name)}${esc(r.value)}${r.unit ? ` ${esc(r.unit)}` : ''}
`).join(''); + return `${esc(title)}

${esc(title)}

${image ? `
${esc(caption || 'Result plot')}${caption ? `
${esc(caption)}
` : ''}
` : ''}${body} +

Linear static analysis: small displacements, linear elastic isotropic material, no contact. Stresses at sharp inner corners and at the edges of fixed faces can grow without bound as the mesh is refined (stress singularities); judge them by the stresses a little away from such spots.

`; +} + +export async function reportDialog(app: App, ws: FeaWorkspace, r: FeaResult) { + const rows = summaryRows(app, ws, r); + const name = `${app.store.doc.name || 'Part'} - ${ws.study?.name ?? 'Static Study'}`; + const v = await showDialog({ + title: 'Results Report', signal: app.documentSignal, + body: [h('p', {}, 'Export the study\'s summary: material, loads, reaction forces, the largest stress and displacement, the factor of safety and the mesh.')], + buttons: [{ label: 'Cancel', value: 'cancel' }, { label: 'Download CSV', value: 'csv' }, { label: 'Printable Report', value: 'html', primary: true }], + }); + if (v === 'csv') download(summaryCsv(rows), `${name}.csv`, 'text/csv'); + if (v === 'html') { + const image = ws.plotting ? app.renderer.capture(1400) : null; + const html = reportHtml(name, rows, image, image ? ws.plotCaption?.() ?? '' : ''); + const w = window.open('', '_blank'); + if (!w) { download(html, `${name}.html`, 'text/html'); toast({ kind: 'info', message: 'The report was downloaded (the browser blocked the new window): open it and print it.' }); return; } + w.document.write(html); + w.document.close(); + setTimeout(() => { try { w.print(); } catch { /* the user prints it */ } }, 300); + } +} diff --git a/src/parametric/src/app/fea/workspace.ts b/src/parametric/src/app/fea/workspace.ts new file mode 100644 index 000000000..c1ab417e0 --- /dev/null +++ b/src/parametric/src/app/fea/workspace.ts @@ -0,0 +1,641 @@ +// The stress analysis of the open part: the boundary triangulation from the +// geometry kernel, the mesh and the solution from the analysis worker (kept +// until the part, the study or the material changes, then marked out of +// date), the study's symbols in the graphics area, and the result plots. +// Loaded the first time an analysis command runs. + +import { FeaCancelled, FeaClient } from '../../fea/client'; +import type { FeaMeshInfo, FeaSolution } from '../../fea/results'; +import type { FixtureInput, LoadInput, StaticInput, Vec3 } from '../../fea/static'; +import { defaultElementSize, estimateDofs, maxElementSize, minElementSize } from '../../fea/mesher'; +import type { FeaSurface } from '../../kernel/protocol'; +import { FIXTURE_LABELS, LOAD_LABELS, elementSizeFor, feaUnits, newStudy, nextStudyName, type FeaDir, type FeaFixture, type FeaLoad, type FeaLoadType, type FixtureType, type StaticStudy } from '../../model/fea'; +import { elasticOf } from '../../model/materials'; +import { formatNumber } from '../../model/units'; +import { allocateId } from '../../model/document'; +import type { Id } from '../../model/types'; +import { type MenuItem, openMenu } from '../../ui/menu'; +import { promptDialog, toast } from '../../ui/overlay'; +import type { App } from '../app'; +import { faceIndexOf } from './index'; +import { FixturePanel, LoadPanel, ResultsPanel, StudyPanel } from './panels'; +import { reportDialog } from './report'; + +export type StudyState = 'none' | 'busy' | 'ok' | 'stale' | 'error'; + +interface SurfaceState { + /** The part's shape it was read from (see shapeKey). */ + version: string; + data: FeaSurface; + /** Surface area (mm^2). */ + area: number; + /** Automatic, largest and smallest element sizes (mm). */ + auto: number; + max: number; + min: number; + diag: number; +} + +export interface FeaResult { + key: string; + mesh: FeaMeshInfo; + sol: FeaSolution; + input: StaticInput; + /** Yield and tensile strength (MPa) and material name when it was solved. */ + yield: number; + uts: number; + material: string; + size: number; + /** Names of the fixtures and loads, in input order. */ + fixtureNames: string[]; + loadNames: string[]; + when: number; +} + +const FIX_COLOR = [40, 170, 90]; +const LOAD_COLOR = [210, 60, 150]; + +export class FeaWorkspace { + readonly client = new FeaClient(); + /** The fixture or load selected in the tree (its faces highlighted). */ + focus: Id | null = null; + private surface: SurfaceState | null = null; + private surfaceLoading: Promise | null = null; + mesh: { key: string; info: FeaMeshInfo; size: number; version: string } | null = null; + result: FeaResult | null = null; + busy: { stage: string; progress: number } | null = null; + error: { key: string; message: string } | null = null; + private generation = 0; + private seenVersion = -1; + private shape: { version: number; key: string } | null = null; + /** Results panel open: it draws the plot (the study's symbols are hidden). */ + plotting = false; + /** What the open plot shows, in words (for the report). */ + plotCaption: (() => string) | null = null; + + constructor(readonly app: App) { + app.store.on((reason) => { + if (reason === 'load') this.reset(); + const s = this.study; + if (this.focus && !s?.fixtures.some((f) => f.id === this.focus) && !s?.loads.some((l) => l.id === this.focus)) this.focus = null; + // A fixture or load deleted (or its study undone) while its panel is open: OK would bring it back. + const p = app.panel; + if ((p instanceof FixturePanel || p instanceof LoadPanel) && !p.present) void app.closePanel(false); + this.changed(); + }); + app.ribbonTabListeners.push(() => this.redraw()); + app.commands.onChange(() => { + // A new part shape: the mesh and the results are out of date (results stay, marked), or current + // again when the shape is back (an edit cancelled, undone and redone). + if (this.seenVersion !== app.geometryVersion) { + this.seenVersion = app.geometryVersion; + // The fixtures' and loads' symbols go on the new faces. + if (this.surface) this.changed(); + else this.redraw(); + } + }); + } + + private reset() { + this.client.cancel(); + this.surface = null; + this.mesh = null; + this.result = null; + this.busy = null; + this.error = null; + this.focus = null; + this.generation++; + } + + get study(): StaticStudy | null { + return this.app.store.doc.study ?? null; + } + + /** Redraws the tree and the graphics. */ + changed() { + this.redraw(); + this.app.renderTrees(); + if (this.app.panel instanceof ResultsPanel || this.app.panel instanceof StudyPanel) this.app.refreshPanel(); + } + + // ---------- state ---------- + + /** What the results depend on: the part's shape, the mesh size, the study's fixtures and loads, the material. */ + solveKey(size?: number, version?: string, study?: string): string { + return JSON.stringify([version ?? this.shapeKey(), size ?? this.sizeOf(), study ?? this.studyKey()]); + } + + /** + * The part's shape: a hash of its body mesh and face names. The geometry + * version moves on with every new mesh, also one of the same shape (an edit + * cancelled, an undo and a redo), which would put results out of date for nothing. + */ + shapeKey(): string { + const app = this.app, v = app.geometryVersion; + if (this.shape?.version === v) return this.shape.key; + const m = app.modelMesh; + let a = 0x811c9dc5, b = 0x2545f491; + const mix = (x: number) => { a = Math.imul(a ^ x, 0x01000193); b = Math.imul(b ^ x, 0x5bd1e995); b ^= b >>> 13; }; + if (m) { + // The points and their faces (the triangles between them follow from the shape). + for (const arr of [new Uint32Array(m.positions.buffer, m.positions.byteOffset, m.positions.length), new Uint32Array(m.vertexFace.buffer, m.vertexFace.byteOffset, m.vertexFace.length)]) { + mix(arr.length); + for (let i = 0; i < arr.length; i++) mix(arr[i]); + } + } + for (const f of app.faces) for (let i = 0; i < f.name.length; i++) mix(f.name.charCodeAt(i)); + const key = m ? `${(a >>> 0).toString(36)}${(b >>> 0).toString(36)}:${m.indices.length}:${app.faces.length}` : 'none'; + this.shape = { version: v, key }; + return key; + } + + /** Whether the mesh is of the part's current shape. */ + meshCurrent(): boolean { + return !!this.mesh && this.mesh.version === this.shapeKey(); + } + + /** The study's fixtures and loads and the material, as the results depend on them. */ + private studyKey(): string { + const s = this.study; + const strip = (x: FeaFixture | FeaLoad) => { const { name: _n, ...rest } = x; void _n; return rest; }; + return JSON.stringify([s ? [s.fixtures.map(strip), s.loads.map(strip)] : null, elasticOf(this.app.store.doc.material), this.app.store.doc.material?.density]); + } + + private sizeOf(): number { + const s = this.study, sf = this.surface; + return sf && s ? elementSizeFor(sf.auto, sf.max, s.mesh.fineness, sf.min) : 0; + } + + state(): StudyState { + if (this.busy) return 'busy'; + if (this.error && !this.result) return 'error'; + if (!this.result) return 'none'; + if (!this.surface || this.surface.version !== this.shapeKey() || this.result.key !== this.solveKey()) return 'stale'; + return 'ok'; + } + + progressText(): string { + return this.busy ? `${this.busy.stage}${this.busy.progress > 0 ? ` ${Math.round(this.busy.progress * 100)}%` : ''}` : ''; + } + + errorText(): string { + return this.error?.message ?? ''; + } + + meshText(): string { + const m = this.mesh; + if (!m) return ''; + const st = m.info.stats; + return `(${st.elements.toLocaleString('en-US')} elements${this.meshCurrent() ? '' : ', out of date'})`; + } + + /** Can the study run now (a part with a solid, nothing being edited)? */ + ready(): string | null { + const app = this.app; + if (app.assembly) return 'Stress analysis works on parts. Open the part to analyze it.'; + if (!app.bbox) return 'The part has no solid body to analyze yet.'; + if (app.sketchEditor || (app.panel?.editingId)) return 'Finish the feature or sketch being edited first.'; + return null; + } + + // ---------- geometry ---------- + + /** The part's boundary from the kernel, with the automatic and largest element sizes. */ + async surfaceState(): Promise { + const app = this.app; + await app.whenBuilt(); + const version = this.shapeKey(); + if (this.surface && this.surface.version === version) return this.surface; + if (this.surfaceLoading) return this.surfaceLoading; + this.surfaceLoading = (async () => { + try { + const b = app.bbox; + const diag = b ? Math.hypot(b.max[0] - b.min[0], b.max[1] - b.min[1], b.max[2] - b.min[2]) : 100; + const data = await app.kernel.feaSurface(diag * 3e-4); + let area = 0; + const P = data.positions, I = data.indices; + for (let t = 0; t < I.length; t += 3) { + const a = I[t] * 3, b2 = I[t + 1] * 3, c = I[t + 2] * 3; + const ux = P[b2] - P[a], uy = P[b2 + 1] - P[a + 1], uz = P[b2 + 2] - P[a + 2], wx = P[c] - P[a], wy = P[c + 1] - P[a + 1], wz = P[c + 2] - P[a + 2]; + area += 0.5 * Math.hypot(uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx); + } + const st: SurfaceState = { version, data, diag, area, auto: defaultElementSize(data.volume, area, diag), max: maxElementSize(data.volume, area, diag), min: minElementSize(data.volume, area, diag) }; + if (this.shapeKey() !== version) return this.surfaceState(); + this.surface = st; + return st; + } finally { + this.surfaceLoading = null; + } + })(); + return this.surfaceLoading; + } + + /** Element size and estimated size of the problem for a fineness (null before the surface is known). */ + sizes(fineness: number): { size: number; auto: number; dofs: number; finest: boolean } | null { + const sf = this.surface; + if (!sf) return null; + const size = elementSizeFor(sf.auto, sf.max, fineness, sf.min); + // finest: held at the smallest size a browser can solve (a finer setting would be smaller). + return { size, auto: sf.auto, dofs: estimateDofs(sf.data.volume, size, sf.area), finest: elementSizeFor(sf.auto, sf.max, fineness) < sf.min }; + } + + private setBusy(stage: string, progress: number) { + const was = this.busy?.stage; + this.busy = { stage, progress }; + this.app.setStatus(this.progressText()); + // The tree and panel show the stage; redraw them on a new stage or every few percent. + if (was !== stage || Math.round(progress * 100) % 5 === 0) { + this.app.renderTrees(); + const p = this.app.panel; + // A panel drawn before the run started shows it now (its progress bar, Cancel, disabled buttons). + if ((p instanceof ResultsPanel || p instanceof StudyPanel) && !p.progress(this.busy)) this.app.refreshPanel(); + } + } + + /** Meshes the part at the study's size if the mesh is not current. */ + async ensureMesh(): Promise<{ info: FeaMeshInfo; size: number; version: string } | null> { + const s = this.study; + if (!s) return null; + const gen = this.generation; + this.setBusy('Preparing the part', 0); + const sf = await this.surfaceState(); + if (gen !== this.generation) return null; + const size = elementSizeFor(sf.auto, sf.max, s.mesh.fineness, sf.min); + const key = `${sf.version}|${size}`; + if (this.mesh?.key === key && this.client.meshed) return this.mesh; + this.setBusy('Meshing', 0); + // A copy: the surface stays here for the next mesh (the worker gets its own). + const surface = { positions: sf.data.positions.slice(), indices: sf.data.indices.slice(), triFace: sf.data.triFace.slice() }; + const info = await this.client.mesh(surface, size, (stage, v) => this.setBusy(`Meshing: ${stage.toLowerCase()}`, v), sf.min); + if (gen !== this.generation) return null; + this.mesh = { key, info, size, version: sf.version }; + return this.mesh; + } + + /** A note when the mesh had to be finer than the size set (the part's walls are thinner). */ + private finerNote(m: { info: FeaMeshInfo; size: number }): string { + if (!(m.info.stats.size < m.size * 0.999)) return ''; + const u = feaUnits(this.app.store.doc.units); + return ` (elements of ${formatNumber(m.info.stats.size / u.lengthScale, this.app.store.doc.decimals)} ${u.length}: the part's walls are thinner than the size set)`; + } + + /** Meshes the part (from the mesh panel). */ + async meshNow(): Promise { + const why = this.ready(); + if (why) { toast({ kind: 'info', message: why }); return; } + if (this.busy) return; + const gen = this.generation; + try { + await this.ensureMesh(); + this.error = null; + } catch (e) { + if (!(e instanceof FeaCancelled)) this.error = { key: '', message: (e as Error).message }; + } finally { + // Cancelled (or the part closed): the status says so already, and a run started since keeps its progress. + if (gen === this.generation) { + this.busy = null; + this.app.setStatus(this.mesh ? `Meshed: ${this.mesh.info.stats.elements.toLocaleString('en-US')} elements, ${this.mesh.info.stats.nodes.toLocaleString('en-US')} nodes${this.finerNote(this.mesh)}` : this.error?.message ?? '', !this.mesh); + this.changed(); + } + } + } + + // ---------- the study as solver input ---------- + + /** Direction of a reference (unit vector), or null if it cannot be found in the part. */ + dirOf(d: FeaDir): Vec3 | null { + const app = this.app; + if (d.kind === 'base') return d.axis === 'x' ? [1, 0, 0] : d.axis === 'y' ? [0, 1, 0] : [0, 0, 1]; + if (d.kind === 'face') { + const i = faceIndexOf(app, d.face); + const f = app.faces[i]; + if (!f) return null; + const v = f.normal ?? f.axis?.d; + return v ? [v[0], v[1], v[2]] : null; + } + const e = app.edges.find((x) => x.name === d.edge.name) ?? null; + if (!e) return null; + const v = e.dir ?? e.axis; + if (v) return [v[0], v[1], v[2]]; + const l = Math.hypot(e.b[0] - e.a[0], e.b[1] - e.a[1], e.b[2] - e.a[2]); + return l > 0 ? [(e.b[0] - e.a[0]) / l, (e.b[1] - e.a[1]) / l, (e.b[2] - e.a[2]) / l] : null; + } + + /** The study for the solver: face indices, directions, the material (throws a message for the user). */ + inputOf(s: StaticStudy): { input: StaticInput; fixtureNames: string[]; loadNames: string[] } { + const app = this.app; + const mat = app.store.doc.material; + const el = elasticOf(mat); + if (!mat) throw new Error('Choose the part\'s material first (Material on the Analysis tab).'); + if (!el) throw new Error(`${mat.name} has no elastic properties for analysis${/oak|pine|wood/i.test(mat.name) ? ' (wood is anisotropic)' : ''}. Choose another material, or give a custom one its elastic modulus, Poisson's ratio and strengths.`); + const faces = (refs: FeaFixture['faces'], what: string) => { + const out = refs.map((r) => faceIndexOf(app, r)); + if (!out.length) throw new Error(`${what}: pick the faces it acts on.`); + if (out.some((i) => i < 0)) throw new Error(`${what}: a face it uses is no longer in the part. Edit it and pick the faces again.`); + return out; + }; + const fixtures: FixtureInput[] = []; + const fixtureNames: string[] = []; + for (const f of s.fixtures) { + if (f.suppressed) continue; + const idx = faces(f.faces, f.name); + if (f.type === 'hinge') { + const cyl = app.faces[idx[0]]; + if (!idx.every((i) => app.faces[i].type === 'cylinder') || !cyl.axis) throw new Error(`${f.name}: a fixed hinge goes on cylindrical faces (a pin hole or a shaft).`); + fixtures.push({ kind: 'hinge', faces: idx, axis: { p: cyl.axis.p, d: cyl.axis.d } }); + } else fixtures.push({ kind: f.type, faces: idx }); + fixtureNames.push(f.name); + } + const loads: LoadInput[] = []; + const loadNames: string[] = []; + for (const l of s.loads) { + if (l.suppressed) continue; + if (!(l.value > 0) || !Number.isFinite(l.value)) throw new Error(`${l.name}: its value must be greater than 0.`); + const sign = l.flip ? -1 : 1; + if (l.type === 'gravity') { + const d = this.dirOf(l.dir); + if (!d) throw new Error(`${l.name}: its direction reference is no longer in the part.`); + loads.push({ kind: 'gravity', accel: [d[0] * l.value * sign, d[1] * l.value * sign, d[2] * l.value * sign] }); + } else if (l.type === 'pressure') { + loads.push({ kind: 'pressure', faces: faces(l.faces, l.name), value: l.value * sign }); + } else { + const idx = faces(l.faces, l.name); + if (!l.dir) loads.push({ kind: 'force', faces: idx, total: l.value * sign, dir: null }); + else { + const d = this.dirOf(l.dir); + if (!d) throw new Error(`${l.name}: its direction reference is no longer in the part.`); + loads.push({ kind: 'force', faces: idx, total: l.value, dir: [d[0] * sign, d[1] * sign, d[2] * sign] }); + } + } + loadNames.push(l.name); + } + if (!fixtures.length) throw new Error('Add a fixture: without one the part is free to move.'); + if (!loads.length) throw new Error('Add a load: a force, a pressure or gravity.'); + return { input: { E: el.E, nu: el.nu, density: mat.density * 1e-12, fixtures, loads }, fixtureNames, loadNames }; + } + + // ---------- running ---------- + + /** Meshes (if needed) and solves the study, then shows the results. */ + async run(): Promise { + const s = this.study; + if (!s) { this.openStudy(); return; } + const why = this.ready(); + if (why) { toast({ kind: 'info', message: why }); return; } + if (this.busy) return; + const gen = ++this.generation; + // The faces are found in the part as it is built: a change just made (Run right after an edit) is built first. + this.setBusy('Preparing the part', 0); + await this.app.whenBuilt(); + if (gen !== this.generation) return; + let resolved: ReturnType; + // What is solved is the study and material as they are now (they may change while it runs). + const studyKey = this.studyKey(), shape = this.shapeKey(); + try { + resolved = this.inputOf(this.study ?? s); + } catch (e) { + this.busy = null; + this.error = { key: this.solveKey(), message: (e as Error).message }; + this.changed(); + void this.openResults(); + return; + } + this.error = null; + const el = elasticOf(this.app.store.doc.material)!, matName = this.app.store.doc.material?.name ?? ''; + void this.openResults(); + try { + const m = await this.ensureMesh(); + if (!m || gen !== this.generation) return; + // The faces were found in another shape than the one meshed (the part changed while it started). + if (m.version !== shape) throw new Error('The part changed while the analysis started. Run it again.'); + // Rollers are held along their faces' true surfaces (a cone's, a sphere's), as the part gives them. + const surfaces = this.surface?.version === m.version ? this.surface.data.surfaces : null; + if (surfaces) for (const fx of resolved.input.fixtures) if (fx.kind === 'roller') fx.surfaces = fx.faces.map((i) => surfaces[i] ?? null); + // The shape meshed and the study read at the start: a change during the run leaves the results out of date. + const key = this.solveKey(m.size, m.version, studyKey); + const t0 = performance.now(); + const sol = await this.client.solve(resolved.input, (stage, v) => this.setBusy(stage, v)); + if (gen !== this.generation) return; + this.result = { + key, mesh: m.info, sol, input: resolved.input, yield: el.yield, uts: el.uts, material: matName, size: m.size, + fixtureNames: resolved.fixtureNames, loadNames: resolved.loadNames, when: Date.now(), + }; + this.busy = null; + this.app.setStatus(`Solved in ${((performance.now() - t0) / 1000).toFixed(1)} s: ${sol.summary.dofs.toLocaleString('en-US')} degrees of freedom${this.finerNote(m)}`); + } catch (e) { + if (e instanceof FeaCancelled) { this.app.setStatus('Analysis cancelled'); } + else { this.error = { key: this.solveKey(), message: (e as Error).message }; this.app.setStatus((e as Error).message, true); } + } finally { + if (gen === this.generation) this.busy = null; + this.changed(); + } + } + + cancel() { + this.generation++; + this.client.cancel(); + this.busy = null; + // Also when it stops before the worker started (preparing the part): the status no longer shows a stage. + this.app.setStatus('Analysis cancelled'); + this.changed(); + } + + // ---------- panels ---------- + + /** Creates the study if there is none (one undo step); returns it. */ + ensureStudy(): StaticStudy { + if (!this.study) { + this.app.store.change('New static study', (d) => { d.study = newStudy(allocateId(d, 'st')); }); + this.app.setRibbonTab('analysis'); + } + return this.study!; + } + + openStudy() { + const why = this.ready(); + if (why) { toast({ kind: 'info', message: why }); return; } + this.ensureStudy(); + this.app.exitModes(); + void this.app.openPanel(new StudyPanel(this.app, this)); + void this.surfaceState().then(() => this.app.panel instanceof StudyPanel && this.app.refreshPanel()).catch(() => {}); + } + + openMesh() { + this.openStudy(); + } + + newFixture(type: FixtureType) { + const why = this.ready(); + if (why) { toast({ kind: 'info', message: why }); return; } + const s = this.ensureStudy(); + const faces = this.app.selection.ofKind('face').map((it) => this.app.faces[it.index]).filter((f) => f && !f.body && (type !== 'hinge' || f.type === 'cylinder')); + const f: FeaFixture = { id: allocateId(this.app.store.doc, 'fx'), name: nextStudyName(s, FIXTURE_LABELS[type].replace(/\/.*/, '')), type, faces: faces.map((x) => ({ name: x.name, sig: { type: x.type, c: x.center, n: x.normal, area: x.area } })) }; + this.app.exitModes(); + void this.app.openPanel(new FixturePanel(this.app, this, f, true)); + } + + newLoad(type: FeaLoadType) { + const why = this.ready(); + if (why) { toast({ kind: 'info', message: why }); return; } + const s = this.ensureStudy(); + const faces = this.app.selection.ofKind('face').map((it) => this.app.faces[it.index]).filter((f) => f && !f.body).map((x) => ({ name: x.name, sig: { type: x.type, c: x.center, n: x.normal, area: x.area } })); + const id = allocateId(this.app.store.doc, 'ld'); + const name = nextStudyName(s, LOAD_LABELS[type]); + // 100 N or 100 lbf, 1 MPa or 100 psi: round numbers in the part's units. + const u = feaUnits(this.app.store.doc.units), inch = this.app.store.doc.units === 'IPS'; + const l: FeaLoad = type === 'force' ? { id, name, type, faces, value: 100 * u.forceScale, dir: null, flip: false } + : type === 'pressure' ? { id, name, type, faces, value: (inch ? 100 : 1) * u.stressScale, flip: false } + : { id, name, type, value: 9806.65, dir: { kind: 'base', axis: 'y' }, flip: true }; + this.app.exitModes(); + void this.app.openPanel(new LoadPanel(this.app, this, l, true)); + } + + editItem(id: Id) { + const s = this.study; + const fx = s?.fixtures.find((x) => x.id === id), ld = s?.loads.find((x) => x.id === id); + if (!fx && !ld) return; + this.focus = id; + this.app.exitModes(); + if (fx) void this.app.openPanel(new FixturePanel(this.app, this, structuredClone(fx), false)); + else void this.app.openPanel(new LoadPanel(this.app, this, structuredClone(ld!), false)); + } + + focusItem(id: Id) { + this.focus = this.focus === id ? null : id; + if (this.app.ribbonTabId !== 'analysis') this.app.setRibbonTab('analysis'); + this.changed(); + } + + itemMenu(id: Id, x: number, y: number) { + const s = this.study; + const item = s?.fixtures.find((f) => f.id === id) ?? s?.loads.find((l) => l.id === id); + if (!item) return; + const mutate = (label: string, fn: (it: FeaFixture | FeaLoad, st: StaticStudy) => void) => this.app.store.change(label, (d) => { + const st = d.study; + const it = st?.fixtures.find((f) => f.id === id) ?? st?.loads.find((l) => l.id === id); + if (st && it) fn(it, st); + }); + const items: MenuItem[] = [ + { label: 'Edit', icon: 'edit', run: () => this.editItem(id) }, + { label: item.suppressed ? 'Unsuppress' : 'Suppress', icon: item.suppressed ? 'eye' : 'eyeOff', run: () => mutate(item.suppressed ? 'Unsuppress' : 'Suppress', (it) => { it.suppressed = !it.suppressed || undefined; }) }, + { + label: 'Rename', icon: 'text', run: () => void promptDialog('Rename', 'Name', item.name, (v) => (v.trim() ? null : 'Enter a name'), this.app.documentSignal).then((name) => { + if (name && name.trim() !== item.name) mutate('Rename', (it) => { it.name = name.trim(); }); + }), + }, + { separator: true }, + { label: 'Delete', icon: 'trash', run: () => mutate(`Delete ${item.name}`, (_it, st) => { st.fixtures = st.fixtures.filter((f) => f.id !== id); st.loads = st.loads.filter((l) => l.id !== id); }) }, + ]; + openMenu(items, x, y, { label: `${item.name} menu` }); + } + + /** Opens the results panel (it shows progress while the study runs). */ + async openResults() { + if (this.app.panel instanceof ResultsPanel) { this.app.refreshPanel(); return; } + this.app.exitModes(); + await this.app.openPanel(new ResultsPanel(this.app, this)); + } + + /** Shows the results, running the study first if it has never run. */ + async showResults() { + if (!this.result && !this.busy && !this.error) { await this.run(); return; } + await this.openResults(); + } + + report() { + if (!this.result) { toast({ kind: 'info', message: 'Run the study first: there are no results to report yet.' }); return; } + void reportDialog(this.app, this, this.result); + } + + deleteStudy() { + if (this.app.panel instanceof ResultsPanel || this.app.panel instanceof StudyPanel) void this.app.closePanel(false); + this.app.store.change('Delete study', (d) => { d.study = null; }); + this.reset(); + this.changed(); + } + + // ---------- display ---------- + + private shown(): boolean { + const app = this.app; + if (app.inDrawing || app.assembly || app.sketchEditor || this.plotting) return false; + return app.ribbonTabId === 'analysis' || app.panel instanceof FixturePanel || app.panel instanceof LoadPanel || app.panel instanceof StudyPanel; + } + + /** Triangles of a face of the shown model. */ + private faceTris(index: number, out: number[]) { + const m = this.app.modelMesh; + if (!m) return; + const idx = m.indices, P = m.positions, vf = m.vertexFace; + for (let t = 0; t < idx.length; t += 3) { + if (Math.round(vf[idx[t]]) !== index) continue; + for (let k = 0; k < 3; k++) { const v = idx[t + k] * 3; out.push(P[v], P[v + 1], P[v + 2]); } + } + } + + /** The fixtures and loads on the model (tinted faces, arrows), and the mesh while its panel is open. */ + redraw() { + const r = this.app.renderer; + if (!r) return; + const s = this.study; + if (!s || !this.shown()) { + r.setTris('feaFix', null); r.setLines('feaArrows', null); + if (!this.plotting) r.setLines('feaMesh', null); + return; + } + const tri: number[] = [], col: number[] = []; + const arrows: number[] = [], acol: number[] = []; + const b = this.app.bbox; + const size = b ? Math.hypot(b.max[0] - b.min[0], b.max[1] - b.min[1], b.max[2] - b.min[2]) * 0.08 : 10; + const arrow = (p: Vec3, d: Vec3, c: number[]) => { + // From the tail to the point it presses on. + const t: Vec3 = [p[0] - d[0] * size, p[1] - d[1] * size, p[2] - d[2] * size]; + const side: Vec3 = Math.abs(d[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]; + const n: Vec3 = [d[1] * side[2] - d[2] * side[1], d[2] * side[0] - d[0] * side[2], d[0] * side[1] - d[1] * side[0]]; + const nl = Math.hypot(...n) || 1; + const h = size * 0.25; + const back: Vec3 = [p[0] - d[0] * h, p[1] - d[1] * h, p[2] - d[2] * h]; + arrows.push(...t, ...p, ...p, back[0] + (n[0] / nl) * h * 0.5, back[1] + (n[1] / nl) * h * 0.5, back[2] + (n[2] / nl) * h * 0.5, ...p, back[0] - (n[0] / nl) * h * 0.5, back[1] - (n[1] / nl) * h * 0.5, back[2] - (n[2] / nl) * h * 0.5); + for (let k = 0; k < 3; k++) acol.push(...c, 255); + }; + const tint = (faces: FeaFixture['faces'], c: number[], focused: boolean) => { + for (const ref of faces) { + const i = faceIndexOf(this.app, ref); + if (i < 0) continue; + const before = tri.length; + this.faceTris(i, tri); + for (let k = before; k < tri.length; k += 3) col.push(...c, focused ? 150 : 95); + } + }; + for (const f of s.fixtures) if (!f.suppressed) tint(f.faces, FIX_COLOR, this.focus === f.id); + for (const l of s.loads) { + if (l.suppressed) continue; + if (l.type === 'gravity') { + const d = this.dirOf(l.dir); + if (d && b) { + const c: Vec3 = [(b.min[0] + b.max[0]) / 2, (b.min[1] + b.max[1]) / 2, (b.min[2] + b.max[2]) / 2]; + const sg = l.flip ? -1 : 1; + arrow(c, [d[0] * sg, d[1] * sg, d[2] * sg], LOAD_COLOR); + } + continue; + } + tint(l.faces, LOAD_COLOR, this.focus === l.id); + for (const ref of l.faces) { + const f = this.app.faces[faceIndexOf(this.app, ref)]; + if (!f) continue; + let d: Vec3 | null = null; + const sg = l.flip ? -1 : 1; + if (l.type === 'force' && l.dir) { const v = this.dirOf(l.dir); if (v) d = [v[0] * sg, v[1] * sg, v[2] * sg]; } + else if (f.normal) d = [-f.normal[0] * sg, -f.normal[1] * sg, -f.normal[2] * sg]; + if (d) arrow(f.center, d, LOAD_COLOR); + } + } + r.setTris('feaFix', tri.length ? { positions: new Float32Array(tri), colors: new Uint8Array(col), depth: 'test', order: 2 } : null); + r.setLines('feaArrows', arrows.length ? { positions: new Float32Array(arrows), colors: new Uint8Array(acol), width: 2.5, depth: 'always', order: 8 } : null); + // The mesh while the study panel is open. + const m = this.mesh; + if (m && this.app.panel instanceof StudyPanel && this.meshCurrent()) { + r.setLines('feaMesh', { positions: m.info.lines, colors: new Uint8Array((m.info.lines.length / 6) * 4).fill(0).map((_, i) => (i % 4 === 3 ? 200 : 40)), width: 1, depth: 'test', order: 6, bias: 4e-5 }); + } else if (!this.plotting) r.setLines('feaMesh', null); + } +} diff --git a/src/parametric/src/app/tree.ts b/src/parametric/src/app/tree.ts index 53528cddc..0f46b2fe7 100644 --- a/src/parametric/src/app/tree.ts +++ b/src/parametric/src/app/tree.ts @@ -12,6 +12,7 @@ import type { App } from './app'; import type { SelItem } from './selection'; import { sheetMetalTreeRows } from './sheetmetal-panels'; import { camTreeRows } from './cam'; +import { feaTreeRows } from './fea'; interface Row { key: string; @@ -98,6 +99,8 @@ export class FeatureTree { } // CAM: setups and their operations, open unless closed (the set holds the closed ones). rows.push(...camTreeRows(app, (k) => !this.expanded.has(k) || !!this.filter).map((r) => ({ ...r, item: null }))); + // Stress analysis: the study's fixtures, loads, mesh and results. + rows.push(...feaTreeRows(app, (k) => !this.expanded.has(k) || !!this.filter).map((r) => ({ ...r, item: null }))); if (!this.filter) return rows; return rows.filter((r) => r.depth === 0 || r.label.toLowerCase().includes(this.filter)); } @@ -123,7 +126,7 @@ export class FeatureTree { const f = r.feature; const index = f ? doc.features.indexOf(f) : -1; // Rollback bar sits after the last built top-level feature. - if (!rollbackPlaced && ((f && r.depth === 1 && index >= built) || r.key === 'cam')) { + if (!rollbackPlaced && ((f && r.depth === 1 && index >= built) || r.key === 'cam' || r.key === 'fea')) { this.list.append(this.rollbackBar()); rollbackPlaced = true; } diff --git a/src/parametric/src/assembly/compose.ts b/src/parametric/src/assembly/compose.ts index 33b4ebb00..92a9de6d5 100644 --- a/src/parametric/src/assembly/compose.ts +++ b/src/parametric/src/assembly/compose.ts @@ -7,10 +7,10 @@ import type { EdgeInfo, FaceInfo, MeshData } from '../kernel/protocol'; import type { Frame, Vec3 } from '../math/vec'; -import { qRotate } from '../math/vec'; +import { cross, dot, normalize, 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'; +import { type CamProfile, type Geo, type ProfileArc, applyPlacement, camProfile } from './solver'; /** What the worker built for a part. */ export interface PartGeometry { @@ -191,3 +191,45 @@ export function edgeGeo(geom: PartGeometry, index: number): Geo | null { 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; } + +/** A cam's profile from the faces of its part, or why it cannot be one. */ +export function camProfileOf(g: PartGeometry, refs: FaceRef[], name: string): CamProfile | string { + const arcs: ProfileArc[] = [], points: Vec3[] = []; + let d: Vec3 | null = null; + const normals: Vec3[] = []; + for (const ref of refs) { + const i = findFace(g.faces, ref); + if (i < 0) return `A face of the cam's profile on ${name} no longer exists`; + const f = g.faces[i]; + const edges = g.edges.filter((e) => e.faces.includes(i)); + if (f.type === 'cylinder' && f.axis && f.radius) { + const ax = normalize(f.axis.d); + if (d && Math.abs(dot(d, ax)) < 0.9999) return 'The faces of the cam\'s profile must all run along one direction (the cam\'s sides)'; + d ??= ax; + // Its extent from a circular edge: a whole circle closes on itself. + const e = edges.find((x) => x.type === 'circle' && x.radius && Math.abs(x.radius - f.radius!) < 1e-6 * Math.max(1, f.radius!)); + const whole = !e || Math.abs(e.length - 2 * Math.PI * f.radius) < 1e-6 * f.radius; + arcs.push({ c: f.axis.p, r: f.radius, ...(whole ? {} : { ends: [e!.a, e!.b, e!.mid] as [Vec3, Vec3, Vec3] }) }); + continue; + } + if (f.type === 'plane' && f.normal) normals.push(normalize(f.normal)); + for (const e of edges) points.push(e.a, e.b, e.mid); + // Curved faces of other kinds: their mesh vertices (as close as the mesh is to the face). + const m = g.mesh; + if (m && f.type !== 'plane') for (let k = 0; k < m.vertexFace.length; k++) if (m.vertexFace[k] === i) points.push([m.positions[k * 3], m.positions[k * 3 + 1], m.positions[k * 3 + 2]]); + } + if (!d) { + for (let i = 0; i < normals.length && !d; i++) for (let j = i + 1; j < normals.length && !d; j++) { const x = cross(normals[i], normals[j]); if (Math.hypot(...x) > 1e-3) d = normalize(x); } + } + if (!d) return 'Select the faces around the cam (its sides): their direction cannot be told from these'; + if (normals.some((n) => Math.abs(dot(n, d!)) > 1e-6)) return 'The faces of the cam\'s profile must all run along one direction (the cam\'s sides, not its ends)'; + // The profile goes all the way round: the sides meet along straight edges in the direction + // of the axis, and a face beside a selected one there must be selected too (else the + // follower would ride across the gap as if the cam were flat there). + const picked = new Set(refs.map((r) => findFace(g.faces, r))); + for (const e of g.edges) { + if (e.type !== 'line' || !e.dir || Math.abs(dot(normalize(e.dir), d)) < 0.9999 || !e.faces.some((i) => picked.has(i))) continue; + if (e.faces.some((i) => !picked.has(i))) return 'Select all the faces around the cam (its sides): the profile must go all the way round'; + } + return camProfile(d, arcs, points); +} diff --git a/src/parametric/src/assembly/motion.ts b/src/parametric/src/assembly/motion.ts new file mode 100644 index 000000000..4525b73df --- /dev/null +++ b/src/parametric/src/assembly/motion.ts @@ -0,0 +1,456 @@ +// Motion studies: an assembly's mechanism driven by motors over time. +// +// Each frame is a solve of the mates from the frame before (a warm start), +// with the motors as hard goals: a rotary motor turns its component by what +// its profile turns it in that frame, a linear motor moves it, a mate driver +// sets its mate's value. Coupling mates (gears, racks, screws) measure motion +// from the frame before, so their turns add up over the study. A frame that +// cannot be solved stops the study: a limit is reached, or the mechanism +// locks up (the motors ask for a motion the mates do not allow). +// +// Results come from the frames: positions of a point of a component, its +// turn, or what a mate measures, with velocities and accelerations by finite +// differences. + +import type { Quat, Vec3 } from '../math/vec'; +import { add, dot, len, normalize, qMul, qRotate } from '../math/vec'; +import type { MotionMotor, Placement } from '../model/assembly'; +import type { Id } from '../model/types'; +import { + CONFLICT_TOL, type Drive, type Geo, MateSolver, type SolverBody, type SolverEntity, type SolverMate, applyPlacement, mateBodies, matesMoving, mateMeasure, placeGeo, quatRotVec, sliderDirection, turnAngle, +} from './solver'; + +/** A motor ready to run: what it moves and its motion over time. */ +export interface MotorInput { + id: Id; + name: string; + kind: MotionMotor['kind']; + /** Rotary and linear: the component moved, and the axis or direction entity (on it, or on another component). */ + body?: Id; + entity?: SolverEntity; + /** Mate driver: the mate whose value it sets. */ + mate?: Id; + /** A rotary motor on a hinge, a linear one on a slider: it turns or slides the mate's second component relative to its first. */ + on?: SolverMate; + /** Rotary: the turn (radians); linear: the travel (mm), from the start of the study. Mate driver: the mate's value (mm or degrees). */ + at: (t: number) => number; +} + +/** Numbers of a motor's profile, evaluated (degrees, mm, seconds, Hz). */ +export interface ProfileValues { + profile: MotionMotor['profile']; + speed?: number; + rpm?: boolean; + amplitude?: number; + frequency?: number; + from?: number; + to?: number; + reverse?: boolean; +} + +/** + * A motor's motion over time. Rotary motors give radians, linear ones mm; + * a mate driver gives its mate's value, starting from `base` (the value the + * mate has) unless it ramps between two values. + */ +export function profileOf(kind: MotionMotor['kind'], p: ProfileValues, duration: number, base = 0): (t: number) => number { + const sign = p.reverse ? -1 : 1; + // Rotary values are in degrees (rpm for speeds when asked), turned into radians. + const k = kind === 'rotary' ? Math.PI / 180 : 1; + const speed = (p.speed ?? 0) * (kind === 'rotary' && p.rpm ? 6 : 1); + if (p.profile === 'constant') return (t) => base + sign * k * speed * t; + if (p.profile === 'oscillate') { + const a = p.amplitude ?? 0, f = p.frequency ?? 0; + return (t) => base + sign * k * a * Math.sin(2 * Math.PI * f * t); + } + const from = p.from ?? 0, to = p.to ?? 0; + return (t) => from + ((to - from) * Math.min(1, Math.max(0, t / Math.max(duration, 1e-9)))); +} + +export interface MotionSetup { + bodies: SolverBody[]; + /** The mates that hold (conflicting and broken ones left out). */ + mates: SolverMate[]; + motors: MotorInput[]; + duration: number; + fps: number; + /** The assembly's size (see SolveOptions.scale). */ + scale: number; + /** Names of mates and motors, for the messages. */ + names?: Map; +} + +export interface MotionStop { + /** Seconds. */ + time: number; + kind: 'limit' | 'locked'; + message: string; + /** The mate whose limit was reached, or that could not hold. */ + mate?: Id; +} + +export interface MotionResult { + /** Seconds, one per frame computed. */ + times: number[]; + /** + * Placements of every component in each frame. Frames after the first keep + * only the components that move (get and has give the others' placements + * from the first frame), so long studies of large assemblies fit in memory. + */ + frames: Map[]; + /** Why the study stopped before its end, or null. */ + stop: MotionStop | null; + /** The study's length (seconds), even when it stopped early. */ + duration: number; +} + +/** + * Steps a study frame by frame (so the caller can share the time: see + * runMotion). The first frame is the assembly as it is. + */ +export class MotionRun { + readonly count: number; + readonly dt: number; + readonly result: MotionResult; + private k = 0; + private solverMates: SolverMate[]; + /** The components the solved mates and the motors reference: the others stay where they are. */ + private bodies: SolverBody[]; + + constructor(private setup: MotionSetup) { + this.count = Math.max(1, Math.round(setup.duration * setup.fps)); + this.dt = setup.duration / this.count; + // Only what the motors move is solved: the mates of the components they drive and those linked to them. + const moving = new Set(); + const floating = new Set(setup.bodies.filter((b) => !b.fixed).map((b) => b.id)); + for (const m of setup.motors) { + // (A fixed component links nothing: from it, every mate to the ground would be solved.) + const ids = (m.on ? mateBodies(m.on) : m.body ? [m.body] : setup.mates.filter((x) => x.id === m.mate).flatMap(mateBodies)).filter((id) => floating.has(id)); + for (const id of ids) for (const x of matesMoving(id, setup.bodies, setup.mates)) moving.add(x); + } + this.solverMates = setup.mates.filter((x) => moving.has(x)); + const used = new Set(this.solverMates.flatMap(mateBodies)); + for (const m of setup.motors) for (const id of m.on ? mateBodies(m.on) : m.body ? [m.body] : []) used.add(id); + this.bodies = setup.bodies.filter((b) => used.has(b.id)); + const first = new Map(setup.bodies.map((b) => [b.id, b.placement])); + this.result = { times: [0], frames: [first], stop: null, duration: setup.duration }; + } + + get done(): boolean { + return this.k >= this.count || !!this.result.stop; + } + + /** Frames computed so far, out of count + 1. */ + get progress(): number { + return this.k / this.count; + } + + /** + * Computes the next frame; false once the study is over (or stopped). A + * frame the solver cannot reach in one step (a fast motor turns a part more + * than half a turn in it, which no solve can tell from the turn back), or in + * which a part turns more than a quarter turn (a small gear driven by a + * large one), is computed again in smaller steps, each kept as a frame of + * its own (so the turns read from the frames add up). + */ + step(): boolean { + if (this.done) return false; + const t0 = this.k * this.dt, t1 = (this.k + 1) * this.dt; + const prev = this.result.frames[this.result.frames.length - 1]; + this.k++; + // A mate driver taking its mate past what the mate can be stops the study there, the last frame where it gets to. + const out = this.leaves(t0, t1); + if (out) { + if (out.time > t0 + 1e-9) { + const r = this.span(prev, t0, out.time); + if (r.r.ok) { this.result.times.push(out.time); this.result.frames.push(new LaterFrame(r.r.placements, this.result.frames[0])); } + } + this.result.stop = out.stop; + return false; + } + let failed: ReturnType | null = null; + for (const parts of [1, 4, 16]) { + const times: number[] = [], frames: Map[] = []; + let from = prev, fast = false; + failed = null; + for (let j = 1; j <= parts; j++) { + const ta = t0 + ((t1 - t0) * (j - 1)) / parts, tb = j === parts ? t1 : t0 + ((t1 - t0) * j) / parts; + const r = this.span(from, ta, tb); + if (!r.r.ok) { failed = r; break; } + if (parts < 16 && this.bodies.some((b) => !b.fixed && turnAngle(r.r.placements.get(b.id)?.q ?? b.placement.q, from.get(b.id)?.q ?? b.placement.q) > Math.PI / 2)) { fast = true; break; } + times.push(tb); + frames.push(new LaterFrame(r.r.placements, this.result.frames[0])); + from = r.r.placements; + } + if (!failed && !fast) { + this.result.times.push(...times); + this.result.frames.push(...frames); + return !this.done; + } + } + const f = failed!; + this.result.stop = this.whyStopped(f.solver, f.r.placements, f.from, f.mates, f.r.residuals, t1); + return false; + } + + /** + * The first time in (t0, t1] a mate driver takes its mate's value out of + * what the mate can be: a distance below zero (the other side is the + * mate's flip, not a negative distance), an angle outside 0° to 180°. + */ + private leaves(t0: number, t1: number): { time: number; stop: MotionStop } | null { + let first: { time: number; stop: MotionStop } | null = null; + for (const m of this.setup.motors) { + if (m.kind !== 'mate') continue; + const mate = this.setup.mates.find((x) => x.id === m.mate); + if (!mate || (mate.type !== 'distance' && mate.type !== 'angle')) continue; + const hi = mate.type === 'angle' ? 180 : Infinity; + const bad = (t: number) => { const v = m.at(t); return !(v >= -1e-9 && v <= hi + 1e-9); }; + if (!bad(t1)) continue; + // Where it crosses (the value moves on smoothly within a frame). + let lo = t0, up = t1; + for (let i = 0; i < 50 && up - lo > 1e-9; i++) { const mid = (lo + up) / 2; if (bad(mid)) up = mid; else lo = mid; } + if (first && first.time <= lo) continue; + const name = (id: Id) => this.setup.names?.get(id) ?? id; + const time = Math.round(lo * 1e4) / 1e4; + const why = mate.type === 'distance' ? 'below zero (a distance cannot be negative: the other side is the mate\'s Flip option)' : `${m.at(up) < 0 ? 'below 0°' : 'past 180°'} (an angle mate measures 0° to 180°)`; + first = { time: lo, stop: { time, kind: 'limit', mate: mate.id, message: `${this.setup.names?.get(m.id) ?? m.name} takes ${name(mate.id)} ${why} at ${time} s: the motion stops there.` } }; + } + return first; + } + + /** Solves the motion from `prev` (at time t0) to time t1. */ + private span(prev: Map, t0: number, t1: number) { + const s = this.setup; + const drives: Drive[] = []; + let mates = this.solverMates; + for (const m of s.motors) { + if (m.kind === 'mate') { + const v = m.at(t1); + mates = mates.map((x) => (x.id === m.mate ? { ...x, value: v } : x)); + continue; + } + if (m.on) { const d = mountedDrive(m.on, prev, s.bodies, m.kind, m.at(t1) - m.at(t0)); if (d) drives.push(d); continue; } + if (!m.body || !m.entity) continue; + const g = placeGeo(m.entity.geo, m.entity.body ? prev.get(m.entity.body) ?? null : null); + const dir = directionOf(g); + if (!dir) continue; + const amount = m.at(t1) - m.at(t0); + if (m.kind === 'rotary') drives.push({ kind: 'rotate', body: m.body, axis: dir, amount }); + else { + // A point of the moved component: the entity's, when it is on it. + const local: Vec3 = m.entity.body === m.body ? pointOfGeo(m.entity.geo) ?? [0, 0, 0] : s.bodies.find((b) => b.id === m.body)?.center ?? [0, 0, 0]; + drives.push({ kind: 'translate', body: m.body, local, dir, amount }); + } + } + const bodies = this.bodies.map((b) => ({ ...b, placement: prev.get(b.id) ?? b.placement })); + const solver = new MateSolver(bodies, mates); + return { r: solver.solve({ scale: s.scale, drives, maxIter: 80 }), solver, mates, from: prev }; + } + + private whyStopped(solver: MateSolver, pl: Map, prev: Map, mates: SolverMate[], residuals: Map, t: number): MotionStop { + const name = (id: Id) => this.setup.names?.get(id) ?? id; + const time = Math.round(t * 1e4) / 1e4; + // A limit reached: its one-sided row is what does not hold. + for (const m of mates) { + if (!(m.limit || m.type === 'slot')) continue; + const all = solver.mateResidual(m, pl, this.setup.scale, prev, true) ?? []; + const eq = solver.mateResidual(m, pl, this.setup.scale, prev, false) ?? []; + // (Kept at one value, the limit is an equation: the mate not holding is the limit reached.) + const fixed = m.limit && m.limit.min === m.limit.max && (residuals.get(m.id) ?? 0) > CONFLICT_TOL; + if (fixed || (Math.abs(all[all.length - 1] ?? 0) > CONFLICT_TOL && all.length > eq.length)) { + return { time, kind: 'limit', mate: m.id, message: `${name(m.id)} reached its limit at ${time} s: the motion stops there.` }; + } + } + let worst: Id | undefined, w = 0; + for (const [id, v] of residuals) if (v > w) { w = v; worst = id; } + const which = worst && w > CONFLICT_TOL ? ` (${name(worst)} cannot hold)` : ''; + return { time, kind: 'locked', mate: worst && w > CONFLICT_TOL ? worst : undefined, message: `The mechanism locks up at ${time} s${which}: the motors ask for a motion the mates do not allow.` }; + } +} + +/** + * The drive of a motor on a hinge or slider: the second component turns + * about the hinge's axis, or slides along the slider, relative to the first + * (in the first's coordinates). When the second is fixed, the first moves + * the other way, measured in the second's coordinates. + */ +function mountedDrive(on: SolverMate, prev: Map, bodies: SolverBody[], kind: MotorInput['kind'], amount: number): Drive | null { + const fixed = (id: Id | null) => !id || !!bodies.find((b) => b.id === id)?.fixed; + const dir = kind === 'rotary' ? (on.a.geo.kind === 'axis' || on.a.geo.kind === 'line' ? normalize(on.a.geo.d) : null) : sliderDirection(on); + if (!dir) return null; + const pa = (on.a.body && prev.get(on.a.body)) || IDENT, pb = (on.b.body && prev.get(on.b.body)) || IDENT; + const pointB = pointOfGeo(on.b.geo) ?? [0, 0, 0], pointA = pointOfGeo(on.a.geo) ?? [0, 0, 0]; + if (!fixed(on.b.body)) { + return kind === 'rotary' ? { kind: 'relTurn', body: on.b.body!, base: on.a.body, axis: dir, amount } : { kind: 'relSlide', body: on.b.body!, base: on.a.body, local: pointB, dir, amount }; + } + if (fixed(on.a.body)) return null; + // a's direction in b's coordinates (where they are now). + const inB = qRotate([-pb.q[0], -pb.q[1], -pb.q[2], pb.q[3]], qRotate(pa.q, dir)); + return kind === 'rotary' ? { kind: 'relTurn', body: on.a.body!, base: on.b.body, axis: inB, amount: -amount } : { kind: 'relSlide', body: on.a.body!, base: on.b.body, local: pointA, dir: inB, amount: -amount }; +} + +const IDENT: Placement = { p: [0, 0, 0], q: [0, 0, 0, 1] }; + +/** A frame after the first: the components that move, and the others where the first frame has them. */ +class LaterFrame extends Map { + constructor(moved: Map, private first: Map) { + super(moved); + } + + override get(id: Id): Placement | undefined { + return super.get(id) ?? this.first.get(id); + } + + override has(id: Id): boolean { + return super.has(id) || this.first.has(id); + } +} + +const directionOf = (g: Geo): Vec3 | null => (g.kind === 'plane' ? normalize(g.n) : g.kind === 'axis' || g.kind === 'line' ? normalize(g.d) : null); +const pointOfGeo = (g: Geo): Vec3 | null => (g.kind === 'plane' ? g.o : g.kind === 'axis' || g.kind === 'line' || g.kind === 'point' ? g.p : g.kind === 'sphere' ? g.c : null); + +/** Runs a whole study at once (tests; the app runs it in slices, see AssemblyMode). */ +export function computeMotion(setup: MotionSetup): MotionResult { + const run = new MotionRun(setup); + while (run.step()); + return run.result; +} + +// ---------- results ---------- + +/** `most` frames (or all of them) spread evenly over a study's time: their indices, the first and last included. */ +export function framesSpread(times: number[], most: number): number[] { + const n = times.length, m = Math.min(n, Math.max(1, most)); + if (m < 2) return [0]; + if (m === n) return times.map((_, i) => i); + const end = times[n - 1], out: number[] = []; + for (let k = 0; k < m; k++) { + const t = (end * k) / (m - 1); + let lo = 0, hi = n - 1; + while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (times[mid] <= t) lo = mid; else hi = mid - 1; } + const near = lo + 1 < n && times[lo + 1] - t < t - times[lo] ? lo + 1 : lo; + // Each a frame of its own, with room left for the rest. + out.push(Math.min(Math.max(near, k ? out[k - 1] + 1 : 0), n - m + k)); + } + return out; +} + +/** + * Groups of placements that moved the same rigid way from `from` to `to` + * (a group number for each): two components in one group did not move + * relative to each other, so they overlap now just as they did there. + */ +export function sameMotionGroups(from: Placement[], to: Placement[]): number[] { + const keys = new Map(); + return to.map((b, i) => { + const a = from[i]; + // The motion: a turn dq, then a move dp (b = dq a + dp). + let dq = qMul(b.q, [-a.q[0], -a.q[1], -a.q[2], a.q[3]]); + if (dq[3] < 0) dq = [-dq[0], -dq[1], -dq[2], -dq[3]]; + const r = qRotate(dq, a.p), dp = [b.p[0] - r[0], b.p[1] - r[1], b.p[2] - r[2]]; + const key = [...dq.map((v) => Math.round(v * 1e9)), ...dp.map((v) => Math.round(v * 1e6))].join(','); + if (!keys.has(key)) keys.set(key, keys.size); + return keys.get(key)!; + }); +} + +/** Where a point of a component (its local coordinates) is in each frame. */ +export function pointPath(res: MotionResult, body: Id, local: Vec3): Vec3[] { + return res.frames.map((f) => applyPlacement(f.get(body) ?? { p: [0, 0, 0], q: [0, 0, 0, 1] }, local)); +} + +/** + * A component's turn in each frame as a rotation vector (radians) added up + * frame by frame: about a fixed axis it is the axis times the whole angle, + * past a full turn. + */ +export function turnPath(res: MotionResult, body: Id): Vec3[] { + const out: Vec3[] = []; + let acc: Vec3 = [0, 0, 0]; + let prev: Quat | null = null; + for (const f of res.frames) { + const q = f.get(body)?.q ?? [0, 0, 0, 1]; + if (prev) acc = add(acc, quatRotVec(qMul(q, [-prev[0], -prev[1], -prev[2], prev[3]]))); + out.push(acc); + prev = q; + } + return out; +} + +/** What a mate measures in each frame (degrees unwrapped past ±180°), or null when it measures nothing. */ +export function mateSeries(res: MotionResult, mate: SolverMate, L = 100): { values: number[]; kind: 'length' | 'angle' } | null { + const first = mateMeasure(mate, res.frames[0], L); + if (!first) return null; + const values: number[] = []; + let last = first.value, acc = first.value; + for (const f of res.frames) { + const v = mateMeasure(mate, f, L)?.value ?? last; + if (first.kind === 'angle' && mate.type === 'hinge') { + let d = v - last; + d -= 360 * Math.round(d / 360); + acc += d; + } else acc = v; + last = v; + values.push(acc); + } + return { values, kind: first.kind }; +} + +/** + * First and second derivatives of samples at times t: central differences, + * and at the first and last samples one-sided differences as accurate (the + * slope through three samples; the second derivative carried on in a line + * from the two beside it). + */ +export function derivatives(t: number[], v: number[]): { d1: number[]; d2: number[] } { + const n = v.length; + const d1 = new Array(n).fill(0), d2 = new Array(n).fill(0); + if (n < 2) return { d1, d2 }; + if (n < 3) { + d1[0] = d1[1] = (v[1] - v[0]) / (t[1] - t[0] || 1); + return { d1, d2 }; + } + // The slope of the parabola through each sample and the two beside it (steps h1 before, h2 after: + // the frames of a study are not evenly spaced where it took smaller steps). + for (let i = 1; i < n - 1; i++) { + const h1 = t[i] - t[i - 1], h2 = t[i + 1] - t[i]; + d1[i] = (-h2 / (h1 * (h1 + h2))) * v[i - 1] + ((h2 - h1) / (h1 * h2)) * v[i] + (h1 / (h2 * (h1 + h2))) * v[i + 1]; + } + // The slope at an end of the parabola through it and the two samples beside it (steps h1 then h2 away). + const end = (f0: number, f1: number, f2: number, h1: number, h2: number) => (-(2 * h1 + h2) / (h1 * (h1 + h2))) * f0 + ((h1 + h2) / (h1 * h2)) * f1 - (h1 / (h2 * (h1 + h2))) * f2; + d1[0] = end(v[0], v[1], v[2], t[1] - t[0], t[2] - t[1]); + d1[n - 1] = -end(v[n - 1], v[n - 2], v[n - 3], t[n - 1] - t[n - 2], t[n - 2] - t[n - 3]); + for (let i = 0; i < n; i++) { + const j = Math.min(n - 2, Math.max(1, i)); + const h1 = t[j] - t[j - 1], h2 = t[j + 1] - t[j]; + // Second difference on uneven steps (the last frame of a study can be shorter). + d2[i] = (2 * ((v[j + 1] - v[j]) / h2 - (v[j] - v[j - 1]) / h1)) / (h1 + h2); + } + if (n >= 4) { + d2[0] = d2[1] + ((d2[1] - d2[2]) * (t[1] - t[0])) / (t[2] - t[1]); + d2[n - 1] = d2[n - 2] + ((d2[n - 2] - d2[n - 3]) * (t[n - 1] - t[n - 2])) / (t[n - 2] - t[n - 3]); + } + return { d1, d2 }; +} + +/** The magnitude of each vector. */ +export const magnitudes = (vs: Vec3[]): number[] => vs.map(len); + +/** Components and magnitude of vectors differentiated: the velocity or acceleration of a path. */ +export function vectorDerivatives(t: number[], vs: Vec3[]): { d1: Vec3[]; d2: Vec3[] } { + const axes = [0, 1, 2].map((k) => derivatives(t, vs.map((v) => v[k]))); + return { d1: vs.map((_, i) => [axes[0].d1[i], axes[1].d1[i], axes[2].d1[i]]), d2: vs.map((_, i) => [axes[0].d2[i], axes[1].d2[i], axes[2].d2[i]]) }; +} + +/** CSV of named columns (the first is the time). */ +export function resultsCsv(columns: { name: string; values: number[] }[]): string { + const n = Math.max(0, ...columns.map((c) => c.values.length)); + const cell = (s: string) => (/[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s); + const rows = [columns.map((c) => cell(c.name)).join(',')]; + for (let i = 0; i < n; i++) rows.push(columns.map((c) => (Number.isFinite(c.values[i]) ? String(Math.round(c.values[i] * 1e9) / 1e9) : '')).join(',')); + return rows.join('\n'); +} + +/** The angle (degrees) a turn path turns about a direction. */ +export const degreesAbout = (path: Vec3[], axis: Vec3): number[] => path.map((v) => (dot(v, normalize(axis)) * 180) / Math.PI); diff --git a/src/parametric/src/assembly/solver.ts b/src/parametric/src/assembly/solver.ts index cc4e84990..1b913bfd2 100644 --- a/src/parametric/src/assembly/solver.ts +++ b/src/parametric/src/assembly/solver.ts @@ -13,11 +13,25 @@ // 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. +// +// Limits (distance and angle mates kept between two values, a hinge's angle +// range, a slot's ends) are one-sided residuals: zero inside the range, the +// overshoot outside it. They take no degree of freedom away (the rank +// analysis leaves them out) but stop a drag at the limit. +// +// Gear, rack and pinion and screw mates relate motions, not positions: how +// far a component turned or slid since the start of the solve (the +// placements it started from), read from the solver's own rotation +// variables, so a single solve can turn them any amount (a rack pulled far +// in one pointer move, or moved by a mate's new value). Every solve starts +// where the last one ended (a drag step, a motion study frame, the document +// after a commit), so the turns add up: a gear driven round and round keeps +// its ratio past ±180°. -import type { Quat, Vec3 } from '../math/vec'; -import { add, cross, dot, len, normalize, qMul, qNormalize, qRotate, scale, sub } from '../math/vec'; +import type { Quat, Vec2, Vec3 } from '../math/vec'; +import { add, cross, dot, len, normalize, perpendicular, qMul, qNormalize, qRotate, scale, sub } from '../math/vec'; import type { Id } from '../model/types'; -import type { MateType, Placement } from '../model/assembly'; +import { type MateType, type Placement, isMechanical } from '../model/assembly'; /** Geometry of a mate entity, in the coordinates of its component (or the assembly for ground). */ export type Geo = @@ -28,7 +42,26 @@ export type Geo = | { kind: 'point'; p: Vec3 } | { kind: 'sphere'; c: Vec3; r: number } /** A whole component (lock mates). */ - | { kind: 'body' }; + | { kind: 'body' } + /** A cam's profile: a closed curve swept along d, in its plane (o, u, v): see camProfile. */ + | CamProfile; + +/** + * A cam's profile in the cam's coordinates. Followers touch its convex + * outline: a circle, or a polygon (arcs divided at every degree, with the + * corners) whose arcs are kept too, so contact on them is exact. `concave`: + * how deep the profile dips inside that outline (zero when it is convex). + */ +export interface CamProfile { + kind: 'profile'; + o: Vec3; d: Vec3; u: Vec3; v: Vec3; + circle: { c: Vec2; r: number } | null; + /** Counter-clockwise convex polygon (when not a circle): the arcs divided, with the corners. */ + hull: Vec2[]; + /** The arcs themselves (counter-clockwise from a0 by span), so contact on them is exact. */ + arcs: { c: Vec2; r: number; a0: number; span: number }[]; + concave: number; +} export interface SolverEntity { /** The component the geometry belongs to; null for the assembly itself (its planes). */ @@ -45,10 +78,40 @@ export interface SolverMate { /** Distance in mm, angle in degrees. */ value: number; flip: boolean; - /** Lock: b's placement in a's frame. */ + /** Lock: b's placement in a's frame. Hinge: where b was in a's frame at 0° (for its limits). */ rel?: Placement; + /** Second entities: a hinge's coincident faces, a width mate's second groove and tab faces, a slot's second end. */ + a2?: SolverEntity; + b2?: SolverEntity; + /** Hinge: alignment of the coincident faces. */ + aligned2?: boolean; + /** Distance (mm) or angle (degrees) range; a hinge's turn range (degrees). */ + limit?: { min: number; max: number }; + /** Gear: b's pitch diameter or part of the ratio (value is a's). */ + value2?: number; + /** Rack and pinion: value is the travel per turn (not the pitch diameter). Universal joint: the axes meet at a joint point. */ + by?: 'ratio' | 'revolution' | 'point'; + /** Gear, rack and pinion: the other way round; screw: left-hand. */ + reverse?: boolean; } +/** + * A motor's motion over one solve (a motion study frame), from where the + * component starts: a turn (radians) about a direction in the assembly, or a + * move (mm) of a point of it along one. + */ +export type Drive = + | { kind: 'rotate'; body: Id; axis: Vec3; amount: number } + | { kind: 'translate'; body: Id; local: Vec3; dir: Vec3; amount: number } + /** + * A motor on a hinge or slider: body turns about `axis`, or its point + * `local` moves along `dir`, relative to `base` (both in base's coordinates). + */ + | { kind: 'relTurn'; body: Id; base: Id | null; axis: Vec3; amount: number } + | { kind: 'relSlide'; body: Id; base: Id | null; local: Vec3; dir: Vec3; amount: number }; + +const driveBodies = (d: Drive): Id[] => (d.kind === 'relTurn' || d.kind === 'relSlide') && d.base ? [d.body, d.base] : [d.body]; + export interface SolverBody { id: Id; fixed: boolean; @@ -68,6 +131,8 @@ export interface SolveOptions { drag?: DragGoal | null; /** Relative resistance of a body to moving (higher moves less). */ weight?: (id: Id) => number; + /** Motors: hard goals, held like mates. */ + drives?: Drive[]; } export interface SolveResult { @@ -77,6 +142,8 @@ export interface SolveResult { /** Largest residual of each mate (normalised), after solving. */ residuals: Map; iterations: number; + /** Largest residual of the drives (normalised). */ + driveResidual?: number; } /** 'error': a mate cannot be formed (its face is gone, or the entities do not fit its type); none conflict. */ @@ -116,6 +183,30 @@ export function rotVecQuat(w: Vec3): Quat { const qConj = (q: Quat): Quat => [-q[0], -q[1], -q[2], q[3]]; +/** The angle (radians, 0 to π) orientation q is turned from q0. */ +export const turnAngle = (q: Quat, q0: Quat): number => { + const d = qMul(q, qConj(q0)); + return 2 * Math.atan2(Math.hypot(d[0], d[1], d[2]), Math.abs(d[3])); +}; + +/** How far (radians, in (-π, π]) orientation q is turned from q0 about the unit direction d (both in the same frame). */ +export function turnAbout(q: Quat, q0: Quat, d: Vec3): number { + const dq = qMul(q, qConj(q0)); + const s = dq[3] < 0 ? -1 : 1; + return 2 * Math.atan2(s * (dq[0] * d[0] + dq[1] * d[1] + dq[2] * d[2]), s * dq[3]); +} + +const IDENT: Placement = { p: [0, 0, 0], q: [0, 0, 0, 1] }; + +/** The components a mate's entities belong to (each once). */ +export function mateBodies(m: SolverMate): Id[] { + // Most mates have one entity on each side (the hot path of every drag step). + if (!m.a2 && !m.b2) return m.a.body ? (m.b.body && m.b.body !== m.a.body ? [m.a.body, m.b.body] : [m.a.body]) : m.b.body ? [m.b.body] : []; + const out: Id[] = []; + for (const e of [m.a, m.b, m.a2, m.b2]) if (e?.body && !out.includes(e.body)) out.push(e.body); + return out; +} + /** Rotation vector (axis times angle) of a quaternion. */ export function quatRotVec(q: Quat): Vec3 { const s = q[3] < 0 ? -1 : 1; @@ -322,6 +413,471 @@ export function initialMateSettings(type: MateType, a: Geo, b: Geo): { aligned: return { aligned, flip, value }; } +// ---------- limits ---------- + +/** + * A distance mate's conditions apart from the distance (parallel faces...) + * and the distance it measures (signed for a plane: on the flipped side it + * is the distance below), or null when the entities cannot take one. + */ +export function distanceParts(a: Geo, b: Geo, o: { aligned: boolean; flip: boolean; scale: number }, swapped = false): { eq: number[]; d: number } | null { + const s = o.flip ? -1 : 1; + const match = (da: Vec3, db: Vec3) => (o.aligned ? sub(da, db) : add(da, db)); + const sw = () => (swapped ? null : distanceParts(b, a, o, true)); + if (a.kind === 'body' || b.kind === 'body') return null; + if (a.kind === 'plane' && b.kind === 'plane') return { eq: match(a.n, b.n), d: s * dot(sub(b.o, a.o), a.n) }; + if (b.kind === 'plane') return sw(); + if (a.kind === 'plane') { + const p = pointOf(b); + if (!p) return null; + const eq = isAxisLike(b) && !(b.kind === 'axis' && b.surface === 'circle') ? [dot(dirOf(b)!, a.n)] : []; + return { eq, d: s * dot(sub(p, a.o), a.n) }; + } + if (isPointLike(a) && isPointLike(b)) return { eq: [], d: len(sub(pointOf(a)!, pointOf(b)!)) }; + if (isAxisLike(a) && isAxisLike(b) && !isPointLike(a) && !isPointLike(b)) return { eq: match(dirOf(a)!, dirOf(b)!), d: len(cross(sub(pointOf(b)!, pointOf(a)!), dirOf(a)!)) }; + if (isAxisLike(a) && isPointLike(b)) return { eq: [], d: len(cross(sub(pointOf(b)!, pointOf(a)!), dirOf(a)!)) }; + if (isAxisLike(b) && isPointLike(a)) return sw(); + return null; +} + +/** The angle (degrees, 0 to 180) between two entities' directions, measured as an angle mate with that alignment does. */ +export function angleOf(a: Geo, b: Geo, aligned: boolean): number | null { + const da = dirOf(a), db = dirOf(b); + if (!da || !db) return null; + return (Math.acos(Math.max(-1, Math.min(1, (aligned ? 1 : -1) * dot(da, db)))) * 180) / Math.PI; +} + +/** The overshoot of v past [min, max] (zero inside). */ +const outside = (v: number, min: number, max: number) => (v > max ? v - max : v < min ? v - min : 0); + +/** + * The overshoot of a turn t (radians, in (-π, π]) past [min, max], read on + * the circle: a hinge kept between 0° and 270° is inside at 190° (which + * reads as -170°), and past the nearer end outside the range. + */ +function outsideTurn(t: number, min: number, max: number): number { + const full = 2 * Math.PI; + if (max - min >= full) return 0; + const u = min + ((((t - min) % full) + full) % full); + if (u <= max) return 0; + const over = u - max, under = u - (min + full); + return over <= -under ? over : under; +} + +/** A distance or angle mate kept between limits: its other conditions, and the overshoot (when `ineq`). */ +function limitEquations(type: 'distance' | 'angle', a: Geo, b: Geo, o: EqOpts, lim: { min: number; max: number }, ineq: boolean): number[] | null { + if (type === 'angle') { + const da = dirOf(a), db = dirOf(b); + if (!da || !db || a.kind === 'body' || b.kind === 'body') return null; + // On the cosine (smooth where the angle is 0° or 180°): cos falls as the angle grows. + const c = (o.aligned ? 1 : -1) * dot(da, db); + return ineq ? [outside(c, Math.cos((lim.max * Math.PI) / 180), Math.cos((lim.min * Math.PI) / 180))] : []; + } + const d = distanceParts(a, b, o); + if (!d) return null; + return [...d.eq, ...(ineq ? [outside(d.d, lim.min, lim.max) / o.scale] : [])]; +} + +// ---------- mechanical mates ---------- + +/** The entities of a mechanical mate placed in the assembly, with the placements of their components now and at the start of the solve. */ +interface MechContext { + m: SolverMate; + ga: Geo; gb: Geo; ga2: Geo | null; gb2: Geo | null; + pa: Placement; pb: Placement; ra: Placement; rb: Placement; + /** Placement of an entity's component, now and at the start. */ + now: (e: SolverEntity) => Placement; + start: (e: SolverEntity) => Placement; + /** How far an entity's component turned about a direction (in the assembly) since the start, in radians. */ + turned: (e: SolverEntity, d: Vec3) => number; + L: number; + ineq: boolean; +} + +/** A hinge's turn (radians) from where it was at 0° (rel), about a's axis. */ +function hingeTurn(m: SolverMate, pa: Placement, pb: Placement): number | null { + if (!m.rel || m.a.geo.kind !== 'axis') return null; + const rel = relativePlacement(pa, pb); + return turnAbout(rel.q, m.rel.q, normalize(m.a.geo.d)); +} + +/** + * Rack and pinion: which way the rack moves as the pinion turns forward, + * from where the rack is beside the pinion (its teeth move with the pinion's + * near side). + */ +function rackSense(dp: Vec3, cp: Vec3, u: Vec3, pr: Vec3): number { + const w = sub(pr, cp); + const n = sub(sub(w, scale(dp, dot(w, dp))), scale(u, dot(w, u))); + const s = dot(cross(dp, n), u); + return s < 0 ? -1 : 1; +} + +function mechanicalEquations(c: MechContext): number[] | null { + const { m, ga, gb, ga2, gb2, L } = c; + const o = { aligned: m.aligned, value: m.value, flip: m.flip, scale: L }; + switch (m.type) { + case 'hinge': { + if (!ga2 || !gb2) return null; + const conc = equations('concentric', ga, gb, o, null, null), plane = equations('coincident', ga2, gb2, { ...o, aligned: !!m.aligned2 }, null, null); + if (!conc || !plane || ga.kind !== 'axis' || gb.kind !== 'axis' || ga2.kind !== 'plane' || gb2.kind !== 'plane') return null; + if (!m.limit) return [...conc, ...plane]; + const t = hingeTurn(m, c.pa, c.pb); + if (t === null) return null; + // (Kept at one angle, the limit is an equation: it takes the turn away.) + return [...conc, ...plane, ...(c.ineq || m.limit.min === m.limit.max ? [outsideTurn(t, (m.limit.min * Math.PI) / 180, (m.limit.max * Math.PI) / 180)] : [])]; + } + case 'gear': { + if (!isAxisLike(ga) || !isAxisLike(gb) || !m.a.body || !m.b.body) return null; + const da = normalize(dirOf(ga)!), db0 = normalize(dirOf(gb)!); + // Parallel axes turn about the same direction: external gears turn opposite ways. Which + // way round is told where the solve started (bevel gears' axes are square: that the + // way did not change with every tiny tilt of them). + const sense = dot(normalize(qRotate(c.ra.q, dirOf(m.a.geo)!)), normalize(qRotate(c.rb.q, dirOf(m.b.geo)!))); + const db = sense < -1e-9 ? scale(db0, -1) : db0; + const ta = c.turned(m.a, da), tb = c.turned(m.b, db); + const va = m.value, vb = m.value2 ?? 0; + if (!(va > 0) || !(vb > 0)) return null; + return [(va * ta + (m.reverse ? -1 : 1) * vb * tb) / Math.max(va, vb)]; + } + case 'rackPinion': { + // a: the pinion (an axis), b: the rack (a straight edge, along which it moves). + if (!isAxisLike(ga) || gb.kind !== 'line' || m.b.geo.kind !== 'line' || !(m.value > 0)) return null; + const dp = normalize(dirOf(ga)!), u = normalize(gb.d); + const turn = m.a.body ? c.turned(m.a, dp) : 0; + const local = m.b.geo.p; + const moved = dot(sub(applyPlacement(c.pb, local), applyPlacement(c.rb, local)), u); + const sense = rackSense(placeGeoDir(m.a.geo, c.ra), pointOf(placeGeo(m.a.geo, c.ra))!, normalize(qRotate(c.rb.q, m.b.geo.d)), applyPlacement(c.rb, local)); + const perRadian = m.by === 'revolution' ? m.value / (2 * Math.PI) : m.value / 2; + return [(moved - (m.reverse ? -1 : 1) * sense * perRadian * turn) / L]; + } + case 'screw': { + const conc = equations('concentric', ga, gb, o, null, null); + if (!conc || ga.kind !== 'axis' || gb.kind !== 'axis' || m.a.geo.kind !== 'axis' || m.b.geo.kind !== 'axis' || !m.value) return null; + // b's turn and travel along a's axis, in a's frame (a nut on a screw that itself moves). + const dl = normalize(m.a.geo.d); + const rel = relativePlacement(c.pa, c.pb), rel0 = relativePlacement(c.ra, c.rb); + const dw = normalize(qRotate(c.pa.q, dl)); + const turn = c.turned(m.b, dw) - c.turned(m.a, dw); + const travel = dot(sub(applyPlacement(rel, m.b.geo.p), applyPlacement(rel0, m.b.geo.p)), dl); + return [...conc, (travel - ((m.reverse ? -1 : 1) * m.value * turn) / (2 * Math.PI)) / L]; + } + case 'width': { + if (!ga2 || !gb2 || ga.kind !== 'plane' || gb.kind !== 'plane' || ga2.kind !== 'plane' || gb2.kind !== 'plane') return null; + // The tab's mid plane on the groove's: parallel, and centred. + const mid = (p: Vec3, q: Vec3) => scale(add(p, q), 0.5); + return [...cross(ga.n, gb.n), dot(sub(mid(gb.o, gb2.o), mid(ga.o, ga2.o)), ga.n) / L]; + } + case 'slider': { + if (!m.rel) return null; + const rel = relativePlacement(c.pa, c.pb); + let rows: number[] | null, dir: Vec3 | null; + if (!ga2 || !gb2) { + // Axes or straight edges: on one line, and no turn about it from where it was added. + if (!isAxisLike(ga) || !isAxisLike(gb) || !isAxisLike(m.a.geo)) return null; + dir = normalize(dirOf(m.a.geo)!); + const da = normalize(dirOf(ga)!), db = normalize(dirOf(gb)!); + rows = [...(m.aligned ? sub(da, db) : add(da, db)), ...scale(cross(sub(pointOf(gb)!, pointOf(ga)!), da), 1 / L), turnAbout(rel.q, sliderStart(m, dir), dir)]; + } else { + // Two pairs of faces flush: they slide along the line where the faces meet. + const p1 = equations('coincident', ga, gb, o, null, null), p2 = equations('coincident', ga2, gb2, { ...o, aligned: !!m.aligned2 }, null, null); + if (!p1 || !p2 || m.a.geo.kind !== 'plane' || m.a2?.geo.kind !== 'plane') return null; + dir = normalize(cross(m.a.geo.n, m.a2.geo.n)); + rows = [...p1, ...p2]; + } + if (!m.limit) return rows; + return [...rows, ...(c.ineq || m.limit.min === m.limit.max ? [outside(sliderTravel(m, rel, dir), m.limit.min, m.limit.max) / L] : [])]; + } + case 'cam': { + const prof = m.a.geo; + if (prof.kind !== 'profile') return null; + // The follower in the cam's coordinates, then in its profile's plane. + const qi: Quat = [-c.pa.q[0], -c.pa.q[1], -c.pa.q[2], c.pa.q[3]]; + const local = (p: Vec3) => qRotate(qi, sub(p, c.pa.p)); + const in2 = (p: Vec3): Vec2 => { const w = sub(local(p), prof.o); return [dot(w, prof.u), dot(w, prof.v)]; }; + if (gb.kind === 'point') return [profileDistance(prof, in2(gb.p)) / L]; + if (gb.kind === 'sphere') return [(profileDistance(prof, in2(gb.c)) - gb.r) / L]; + if (gb.kind === 'axis') return [(profileDistance(prof, in2(gb.p)) - gb.r) / L]; + if (gb.kind === 'plane') { + // A flat face touches the cam where the cam reaches furthest toward it (the cam on its outer side). + const n = qRotate(qi, scale(gb.n, m.flip ? -1 : 1)); + const n2: Vec2 = [dot(n, prof.u), dot(n, prof.v)]; + const nl = Math.hypot(n2[0], n2[1]); + if (nl < 1e-9) return null; + const u2: Vec2 = [n2[0] / nl, n2[1] / nl]; + const o2 = in2(gb.o); + return [(-profileSupport(prof, [-u2[0], -u2[1]]) - (o2[0] * u2[0] + o2[1] * u2[1])) / L]; + } + return null; + } + case 'universal': { + if (!m.rel || !isAxisLike(ga) || !isAxisLike(gb) || !m.a.body || !m.b.body) return null; + const y = yokes(m); + if (!y) return null; + // The cross piece holds the two yokes square to each other. + const rows = [dot(qRotate(c.pa.q, y.a), qRotate(c.pb.q, y.b))]; + if (m.by !== 'point') return rows; + // The axes meet at the joint point, `value` along a's axis. + const j = applyPlacement(c.pa, add(pointOf(m.a.geo)!, scale(normalize(dirOf(m.a.geo)!), m.value))); + return [...rows, ...scale(cross(sub(j, pointOf(gb)!), normalize(dirOf(gb)!)), 1 / L)]; + } + case 'slot': { + if (!ga2 || !isAxisLike(ga) || !isAxisLike(ga2)) return null; + const da = normalize(dirOf(ga)!), p1 = pointOf(ga)!, w = sub(pointOf(ga2)!, p1); + const along = sub(w, scale(da, dot(w, da))); + const length = len(along); + const pb = pointOf(gb); + if (length < 1e-9 || !pb) return null; + const u = scale(along, 1 / length), ns = cross(da, u); + const off = sub(pb, p1); + // An axis (a pin) stays parallel to the slot's ends; it, or a point, stays on the plane through them, between the ends. + const par = gb.kind === 'axis' || gb.kind === 'line' ? cross(da, normalize(dirOf(gb)!)) : []; + return [...par, dot(off, ns) / L, ...(c.ineq ? [outside(dot(off, u), 0, length) / L] : [])]; + } + } + return null; +} + +const placeGeoDir = (g: Geo, pl: Placement): Vec3 => normalize(qRotate(pl.q, dirOf(g) ?? [0, 0, 1])); + +/** A slider's travel (mm) from where it was added: b's entity along the slide, in a's coordinates. */ +function sliderTravel(m: SolverMate, rel: Placement, dir: Vec3): number { + const p = pointOf(m.b.geo) ?? [0, 0, 0]; + return dot(sub(applyPlacement(rel, p), applyPlacement(m.rel!, p)), dir); +} + +/** + * Where b was in a's frame (its orientation) when a slider on straight edges + * was added, turned over (half a turn across b's edge) when the slider's + * alignment is the other way from the edges' there: its turn about the + * slide is measured from that (from where it was added, half a turn away, + * it has no turn to measure: the slider showed a freedom it did not have). + */ +function sliderStart(m: SolverMate, dir: Vec3): Quat { + const q = m.rel!.q, db = normalize(dirOf(m.b.geo)!); + if ((dot(dir, qRotate(q, db)) >= 0) === m.aligned) return q; + const e = perpendicular(db); + return qMul(q, [e[0], e[1], e[2], 0]); +} + +/** The direction a slider slides, in a's coordinates. */ +export function sliderDirection(m: SolverMate): Vec3 | null { + if (m.a2?.geo.kind === 'plane' && m.a.geo.kind === 'plane') { const d = cross(m.a.geo.n, m.a2.geo.n); return len(d) > 1e-9 ? normalize(d) : null; } + const d = dirOf(m.a.geo); + return d ? normalize(d) : null; +} + +/** + * The yokes of a universal joint, each in its shaft's coordinates: a's in + * the plane of the two axes where the joint was added, b's square to it and + * to b's axis. Measured from there, b turns by atan(tan φ / cos β) as a + * turns by φ (β the angle between the axes). + */ +function yokes(m: SolverMate): { a: Vec3; b: Vec3 } | null { + const da = dirOf(m.a.geo), db = dirOf(m.b.geo); + if (!da || !db || !m.rel) return null; + const a = normalize(da); + const bInA = normalize(qRotate(m.rel.q, db)); + const off = sub(bInA, scale(a, dot(bInA, a))); + const ya = len(off) > 1e-9 ? normalize(off) : perpendicular(a); + const yb = normalize(cross(bInA, ya)); + return { a: ya, b: qRotate([-m.rel.q[0], -m.rel.q[1], -m.rel.q[2], m.rel.q[3]], yb) }; +} + +// ---------- cam profiles ---------- + +/** A circular arc of a cam's profile: centre and radius, and (unless it is a whole circle) its ends and a point between them. */ +export interface ProfileArc { c: Vec3; r: number; ends?: [Vec3, Vec3, Vec3] } + +/** + * A cam's profile from its round faces (arcs about axes along d) and the + * corners of its other faces (points), all in the cam's coordinates. A + * single whole circle stays a circle; otherwise the outline is the convex + * hull of the arcs (divided at every degree) and the points, the arcs kept + * for exact contact. Where the profile lies inside that outline it is + * concave, and `concave` says by how much. + */ +export function camProfile(d0: Vec3, arcs: ProfileArc[], points: Vec3[]): CamProfile { + const d = normalize(d0); + const u = perpendicular(d), v = cross(d, u); + const o = arcs[0]?.c ?? points[0] ?? [0, 0, 0]; + const in2 = (p: Vec3): Vec2 => { const w = sub(p, o); return [dot(w, u), dot(w, v)]; }; + const base = { kind: 'profile' as const, o, d, u, v }; + const whole = arcs.filter((a) => !a.ends); + if (arcs.length === 1 && whole.length === 1) { + const c = in2(whole[0].c), r = whole[0].r; + // Corners of other faces on the circle (its caps' edges, say) change nothing. + if (points.every((p) => Math.abs(Math.hypot(in2(p)[0] - c[0], in2(p)[1] - c[1]) - r) < 1e-6 * Math.max(1, r))) return { ...base, circle: { c, r }, hull: [], arcs: [], concave: 0 }; + } + const pts: Vec2[] = points.map(in2); + const exact: CamProfile['arcs'] = []; + for (const a of arcs) { + const c = in2(a.c); + const ang = (p: Vec3) => { const q = in2(p); return Math.atan2(q[1] - c[1], q[0] - c[0]); }; + let a0 = 0, sweep = 2 * Math.PI; + if (a.ends) { + // From one end through the middle point to the other. + a0 = ang(a.ends[0]); + const am = ang(a.ends[2]), a1 = ang(a.ends[1]); + const ccw = (x: number) => ((x - a0) % (2 * Math.PI) + 2 * Math.PI) % (2 * Math.PI); + sweep = ccw(am) <= ccw(a1) ? ccw(a1) : ccw(a1) - 2 * Math.PI; + } + exact.push({ c, r: a.r, a0: sweep >= 0 ? a0 : a0 + sweep, span: Math.abs(sweep) }); + const n = Math.max(8, Math.ceil(Math.abs(sweep) / (Math.PI / 180))); + for (let k = 0; k <= n; k++) { const t = a0 + (sweep * k) / n; pts.push([c[0] + a.r * Math.cos(t), c[1] + a.r * Math.sin(t)]); } + } + const hull = convexHull(pts); + let concave = 0; + for (const p of pts) concave = Math.max(concave, -polygonDistance(hull, p)); + return { ...base, circle: null, hull, arcs: exact, concave }; +} + +/** Whether the direction of w lies on an arc (counter-clockwise from a0 by span). */ +const onArc = (a: CamProfile['arcs'][number], w: Vec2) => (((Math.atan2(w[1], w[0]) - a.a0) % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI) <= a.span + 1e-12; + +/** Counter-clockwise convex hull (monotone chain). */ +function convexHull(pts: Vec2[]): Vec2[] { + const p = [...pts].sort((a, b) => a[0] - b[0] || a[1] - b[1]); + if (p.length < 3) return p; + const turn = (o: Vec2, a: Vec2, b: Vec2) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]); + const lower: Vec2[] = [], upper: Vec2[] = []; + for (const x of p) { while (lower.length >= 2 && turn(lower[lower.length - 2], lower[lower.length - 1], x) <= 1e-12) lower.pop(); lower.push(x); } + for (let i = p.length - 1; i >= 0; i--) { const x = p[i]; while (upper.length >= 2 && turn(upper[upper.length - 2], upper[upper.length - 1], x) <= 1e-12) upper.pop(); upper.push(x); } + return [...lower.slice(0, -1), ...upper.slice(0, -1)]; +} + +/** Signed distance from a point to a convex polygon (negative inside). */ +function polygonDistance(h: Vec2[], x: Vec2): number { + let inside = true, best = Infinity, depth = Infinity; + for (let i = 0; i < h.length; i++) { + const a = h[i], b = h[(i + 1) % h.length]; + const ex = b[0] - a[0], ey = b[1] - a[1], l2 = ex * ex + ey * ey || 1; + const wx = x[0] - a[0], wy = x[1] - a[1]; + const side = (ex * wy - ey * wx) / Math.sqrt(l2); + if (side < 0) inside = false; + depth = Math.min(depth, side); + const t = Math.max(0, Math.min(1, (wx * ex + wy * ey) / l2)); + best = Math.min(best, Math.hypot(wx - t * ex, wy - t * ey)); + } + return inside ? -depth : best; +} + +/** Signed distance from a point in the profile's plane to its outline. */ +export function profileDistance(p: CamProfile, x: Vec2): number { + if (p.circle) return Math.hypot(x[0] - p.circle.c[0], x[1] - p.circle.c[1]) - p.circle.r; + const poly = polygonDistance(p.hull, x); + // The arcs a point faces give its exact distance; the polygon's chords lie a little inside them. + let out = Infinity, inside = -Infinity; + for (const a of p.arcs) { + const w: Vec2 = [x[0] - a.c[0], x[1] - a.c[1]]; + if (!onArc(a, w)) continue; + const d = Math.hypot(w[0], w[1]) - a.r; + out = Math.min(out, d); + inside = Math.max(inside, d); + } + // Outside (or between a chord and its arc): the nearest of the edges and arcs, none nearer than the outline. + if (poly >= 0) return Math.min(poly, out); + // Inside, near an arc (no deeper than the sag of its chords, 1° apart): the arc's. + return inside >= poly - 4e-5 * Math.max(1, ...p.arcs.map((a) => a.r)) ? inside : poly; +} + +/** How far the outline reaches along a unit direction (its support function). */ +export function profileSupport(p: CamProfile, u: Vec2): number { + if (p.circle) return p.circle.c[0] * u[0] + p.circle.c[1] * u[1] + p.circle.r; + let best = -Infinity; + for (const q of p.hull) best = Math.max(best, q[0] * u[0] + q[1] * u[1]); + for (const a of p.arcs) if (onArc(a, u)) best = Math.max(best, a.c[0] * u[0] + a.c[1] * u[1] + a.r); + return best; +} + +/** Why the entities (and values) of a mechanical mate do not make one, or null when they do. */ +export function mechanicalProblem(m: Pick): string | null { + const { a, b, a2, b2 } = m; + const axis = (e?: SolverEntity) => !!e && (e.geo.kind === 'axis' || e.geo.kind === 'line'); + const round = (e?: SolverEntity) => !!e && e.geo.kind === 'axis'; + const plane = (e?: SolverEntity) => !!e && e.geo.kind === 'plane'; + const parallel = (x: SolverEntity, y: SolverEntity) => x.body === y.body && Math.abs(dot(normalize(dirOf(x.geo)!), normalize(dirOf(y.geo)!))) > 0.9999; + switch (m.type) { + case 'slider': + if (!a.body && !b.body) return 'A slider needs a component'; + if (!m.rel) return 'The slider has no stored position'; + if (a2 || b2) { + if (!plane(a) || !plane(a2) || !plane(b) || !plane(b2)) return 'A slider needs a straight edge or axis on each component, or two planar faces on each'; + if (a2!.body !== a.body || b2!.body !== b.body) return 'Each component\'s two faces must be faces of that component'; + if (Math.abs(dot(normalize(dirOf(a.geo)!), normalize(dirOf(a2!.geo)!))) > 0.999) return 'The two faces on each component must not be parallel (the slider moves along the line where they meet)'; + } else if (!axis(a) || !axis(b)) return 'A slider needs a straight edge or axis on each component, or two planar faces on each'; + return m.limit && !(m.limit.min <= m.limit.max) ? 'The smallest travel must not be more than the largest' : null; + case 'cam': { + if (a.geo.kind !== 'profile') return 'A cam mate needs the faces of the cam\'s profile and a follower'; + if (!a.body || a.body === b.body) return 'The cam and the follower must be different components'; + if (!['point', 'sphere', 'axis', 'plane'].includes(b.geo.kind)) return 'The follower must be a vertex, a round face or edge (a roller) or a planar face'; + const size = a.geo.circle ? a.geo.circle.r : Math.max(1, ...a.geo.hull.map((q) => Math.hypot(q[0], q[1]))); + if (a.geo.concave > 1e-6 * Math.max(1, size)) return `The cam's profile has a hollow ${Math.round(a.geo.concave * 1000) / 1000} mm deep: a follower cannot stay in contact there. Cam mates follow convex profiles (an eccentric, lobes and flats).`; + return b.geo.kind === 'plane' && Math.abs(dot(normalize(b.geo.n), a.geo.d)) > 0.999 ? 'The flat follower face must face the cam across its axis, not along it' : null; + } + case 'universal': + if (!axis(a) || !axis(b) || !a.body || !b.body) return 'A universal joint needs a round face or edge (or an axis) on each of two shafts'; + if (!m.rel) return 'The universal joint has no stored position'; + // Square to each other the yokes cannot both cross the shafts' plane: such a joint cannot turn. + return Math.abs(dot(normalize(dirOf(a.geo)!), normalize(qRotate(m.rel.q, dirOf(b.geo)!)))) < 1e-3 ? 'The shafts of a universal joint must not be at 90° to each other (it cannot turn there)' : null; + case 'hinge': + if (!round(a) || !round(b) || !plane(a2) || !plane(b2)) return 'A hinge needs two round faces or edges (the pin and its hole) and two planar faces that touch'; + if (a2!.body !== a.body || b2!.body !== b.body) return 'Each planar face of a hinge must be on the component of the round entity selected with it'; + if (m.limit && !(m.limit.min <= m.limit.max)) return 'The smallest angle must not be more than the largest'; + return null; + case 'gear': + if (!axis(a) || !axis(b) || !a.body || !b.body) return 'A gear mate needs a round face or edge (or an axis) on each of two components'; + return m.value > 0 && (m.value2 ?? 0) > 0 ? null : 'The gear values must be more than zero'; + case 'rackPinion': + if (!round(a) || b.geo.kind !== 'line' || !b.body) return 'A rack and pinion mate needs a straight edge of the rack and a round face or edge of the pinion'; + return m.value > 0 ? null : 'The pitch diameter (or travel per turn) must be more than zero'; + case 'screw': + if (!round(a) || !round(b) || !a.body || !b.body) return 'A screw mate needs a round face or edge on each of two components'; + return m.value ? null : 'The pitch must not be zero'; + case 'width': + if (!plane(a) || !plane(a2) || !plane(b) || !plane(b2)) return 'A width mate needs two planar faces of the groove and two of the tab'; + if (!parallel(a, a2!) || !parallel(b, b2!)) return 'The two groove faces (and the two tab faces) must be parallel faces of one component'; + return a.body === b.body ? 'The groove and the tab must be on different components' : null; + case 'slot': + if (!round(a) || !round(a2)) return 'A slot mate needs the two round ends of the slot and a pin (a round face or edge, an axis or a point)'; + if (!parallel(a, a2!)) return 'The two ends must be on the same component, and parallel'; + if (len(cross(sub(pointOf(a2!.geo)!, pointOf(a.geo)!), normalize(dirOf(a.geo)!))) < 1e-6) return 'Select the two ends of the slot (they are the same axis)'; + if (b.geo.kind === 'plane' || b.geo.kind === 'body') return 'The pin must be a round face or edge, a straight edge or a point'; + return a.body === b.body ? 'The pin and the slot must be on different components' : null; + } + return null; +} + +/** + * What a mate measures where the components are (a result of a motion + * study): the distance or angle between its entities, a hinge's turn, a + * pin's travel along its slot; null for the others. + */ +export function mateMeasure(m: SolverMate, pl: Map, L = 100): { value: number; kind: 'length' | 'angle' } | null { + const at = (e?: SolverEntity) => (e?.body ? pl.get(e.body) ?? null : null); + const ga = placeGeo(m.a.geo, at(m.a)), gb = placeGeo(m.b.geo, at(m.b)); + if (m.type === 'distance') { const d = distanceParts(ga, gb, { aligned: m.aligned, flip: m.flip, scale: L }); return d ? { value: d.d, kind: 'length' } : null; } + if (m.type === 'angle') { const a = angleOf(ga, gb, m.aligned); return a === null ? null : { value: a, kind: 'angle' }; } + if (m.type === 'hinge') { + const pa = at(m.a) ?? IDENT, pb = at(m.b) ?? IDENT; + const rel = m.rel ?? null; + if (!rel || m.a.geo.kind !== 'axis') return null; + return { value: (turnAbout(relativePlacement(pa, pb).q, rel.q, normalize(m.a.geo.d)) * 180) / Math.PI, kind: 'angle' }; + } + if (m.type === 'slider' && m.rel) { + const dir = sliderDirection(m); + return dir ? { value: sliderTravel(m, relativePlacement(at(m.a) ?? IDENT, at(m.b) ?? IDENT), dir), kind: 'length' } : null; + } + if (m.type === 'slot' && m.a2) { + const ga2 = placeGeo(m.a2.geo, at(m.a2)); + const da = dirOf(ga), p1 = pointOf(ga), p2 = pointOf(ga2), pb = pointOf(gb); + if (!da || !p1 || !p2 || !pb) return null; + const d = normalize(da), w = sub(p2, p1), along = sub(w, scale(d, dot(w, d))); + return len(along) > 1e-9 ? { value: dot(sub(pb, p1), normalize(along)), kind: 'length' } : null; + } + return null; +} + // ---------- the solver ---------- interface System { @@ -348,19 +904,26 @@ export class MateSolver { 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); + for (const m of mates) for (const id of mateBodies(m)) involved.add(id); if (opts.drag) involved.add(opts.drag.body); + const drives = opts.drives ?? []; + for (const d of drives) for (const id of driveBodies(d)) involved.add(id); 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])); + // Where the components start: what gear, rack and pinion and screw mates, and motors, measure motion from. + const ref = placements; const weights = vars.map((id) => Math.sqrt(Math.max(1e-6, opts.weight?.(id) ?? 1))); const n = vars.length * 6; const residuals = new Map(); + // Gear, rack and pinion and screw mates read the components' turns from the variables (see mateResidual). + const coupled = mates.some((m) => m.type === 'gear' || m.type === 'rackPinion' || m.type === 'screw'); + const turnsOf = coupled ? new WeakMap, Map>() : null; const evalMates = (pl: Map) => { residuals.clear(); let worst = 0; for (const m of mates) { - const r = this.mateResidual(m, pl, L); + const r = this.mateResidual(m, pl, L, ref, true, turnsOf?.get(pl)); const v = r ? Math.max(0, ...r.map(Math.abs)) : Infinity; residuals.set(m.id, v); worst = Math.max(worst, v); @@ -369,14 +932,15 @@ export class MateSolver { }; // 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)) { + if (drag?.kind === 'move' && sys.index.has(drag.body) && !drives.length && !mates.some((m) => mateBodies(m).includes(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); } + const driveWorst = (pl: Map) => Math.max(0, ...driveResidual(drives, pl, ref, L).map(Math.abs)); if (!n) { - const worst = evalMates(placements); - return { placements, ok: worst < CONFLICT_TOL, residuals, iterations: 0 }; + const worst = evalMates(placements), dw = driveWorst(placements); + return { placements, ok: worst < CONFLICT_TOL && dw < CONFLICT_TOL, residuals, iterations: 0, driveResidual: dw }; } // While a move drag pulls, turning costs more than sliding: a component // its mates let slide follows the cursor without spinning, and one they @@ -386,12 +950,15 @@ export class MateSolver { 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))); + turnsOf?.set(out, turnsAt(vars, xv)); 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) ?? [])); + const turns = turnsOf?.get(pl); + for (const m of mates) out.push(...(this.mateResidual(m, pl, L, ref, true, turns) ?? [])); + if (drives.length) out.push(...driveResidual(drives, pl, ref, L)); if (withDrag && opts.drag) out.push(...dragResidual(opts.drag, pl, L).map((v) => v * dragWeight)); return out; }; @@ -407,7 +974,7 @@ export class MateSolver { 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 J = this.jacobian(x, sys, placements, mates, withDrag ? opts.drag ?? null : null, dragWeight, r.length, n, vw, L, drives, coupled); 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++) { @@ -462,8 +1029,8 @@ export class MateSolver { run(false, maxIter); } else run(false, maxIter); const final = at(x); - const worst = evalMates(final); - return { placements: final, ok: worst < CONFLICT_TOL, residuals, iterations }; + const worst = evalMates(final), dw = driveWorst(final); + return { placements: final, ok: worst < CONFLICT_TOL && dw < CONFLICT_TOL, residuals, iterations, driveResidual: dw }; } /** @@ -471,7 +1038,7 @@ export class MateSolver { * 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[][] { + private jacobian(x: number[], sys: System, base: Map, mates: SolverMate[], drag: DragGoal | null, dragWeight: number, m: number, n: number, vw: number[], L: number, drives: Drive[] = [], coupled = false): number[][] { const J = Array.from({ length: m }, () => new Array(n).fill(0)); const h = 1e-6; const current = new Map(base); @@ -479,11 +1046,13 @@ export class MateSolver { // 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 turns = coupled ? turnsAt(sys.vars, x) : undefined; 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)); + turns?.set(id, [xv[3], xv[4], xv[5]]); return work; }; const block = (row: number, bodies: (Id | null)[], f: (pl: Map) => number[]) => { @@ -495,25 +1064,42 @@ export class MateSolver { 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)!); + turns?.set(id, [x[k + 3], x[k + 4], x[k + 5]]); } }; let row = 0; for (const mt of mates) { - const f = (pl: Map) => this.mateResidual(mt, pl, L) ?? []; + const f = (pl: Map) => this.mateResidual(mt, pl, L, base, true, turns) ?? []; const len0 = f(current).length; - block(row, [mt.a.body, mt.b.body], f); + block(row, mateBodies(mt), f); row += len0; } + for (const d of drives) { block(row, driveBodies(d), (pl) => driveResidual([d], pl, base, L)); row++; } 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 { + /** + * A mate's residuals with the components where `pl` puts them; null when + * it cannot be formed. `ref`: where the components started (what coupling + * mates measure motion from). `ineq`: with the rows of limits (left out of + * the rank analysis: a limit takes no freedom away). `turns`: how far each + * moving component turned from `ref` (a rotation vector, which unlike the + * orientation itself goes on past half a turn); without it the turns are + * read from the orientations. + */ + mateResidual(m: SolverMate, pl: Map, L: number, ref: Map = pl, ineq = true, turns?: Map): 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); + if (isMechanical(m.type)) return mechanicalResidual(m, pl, ref, pa, pb, L, ineq, turns); + const o = { aligned: m.aligned, value: m.value, flip: m.flip, scale: L, rel: m.rel }; + if (m.limit && (m.type === 'distance' || m.type === 'angle')) { + // Kept at one value it is that value's mate (it takes the freedom away). + if (m.limit.min === m.limit.max) return equations(m.type, placeGeo(m.a.geo, pa), placeGeo(m.b.geo, pb), { ...o, value: m.limit.min }, pa, pb); + return limitEquations(m.type, placeGeo(m.a.geo, pa), placeGeo(m.b.geo, pb), o, m.limit, ineq); + } + return equations(m.type, placeGeo(m.a.geo, pa), placeGeo(m.b.geo, pb), o, pa, pb); } /** @@ -541,7 +1127,15 @@ export class MateSolver { } res = this.solve(opts, kept, placements); } - const active = usable.filter((m) => !conflicts.has(m.id)); + // A rack along its pinion's axis, where the mates put them, is no rack and pinion + // (told where they end up, so solving again from there says the same). + let racks = false; + for (const m of usable) { + const why = m.type === 'rackPinion' && !conflicts.has(m.id) ? rackProblem(m, res.placements) : null; + if (why) { invalid.set(m.id, why); racks = true; } + } + if (racks) res = this.solve(opts, usable.filter((m) => !conflicts.has(m.id) && !invalid.has(m.id)), res.placements); + const active = usable.filter((m) => !conflicts.has(m.id) && !invalid.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 @@ -557,8 +1151,8 @@ export class MateSolver { 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 ids = mateBodies(m).filter((id) => parent.has(id)); + for (let i = 1; i < ids.length; i++) parent.set(root(ids[i]), root(ids[0])); } const groups = new Map(); for (const b of floating) { @@ -567,7 +1161,7 @@ export class MateSolver { 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)); + const id = mateBodies(m).find((x) => parent.has(x)); if (id) groups.get(root(id))!.mates.push(m); } let dof = 0; @@ -578,11 +1172,15 @@ export class MateSolver { if (!g.mates.length) { dof += n; continue; } const index = new Map(g.bodies.map((b, i) => [b.id, i])); const J: number[][] = []; + // Gear, rack and pinion and screw mates hold at the start of every solve whatever their + // ratio, so one that contradicts the mates before it is found here: see contradicts. + const coupled = g.mates.some(isCoupling) ? new Map(g.bodies.map((b) => [b.id, b.id])) : null; + const top = (id: Id): Id => { let r = id; while (coupled!.get(r) !== r) r = coupled!.get(r)!; return r; }; for (const m of g.mates) { - const base = this.mateResidual(m, pl, L); + const base = this.mateResidual(m, pl, L, pl, false); if (!base) continue; const block = base.map(() => new Array(n).fill(0)); - for (const id of new Set([m.a.body, m.b.body])) { + for (const id of mateBodies(m)) { if (!id || !index.has(id)) continue; const i = index.get(id)!; const center = g.bodies[i].center ?? [0, 0, 0]; @@ -590,14 +1188,23 @@ export class MateSolver { 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)!; + const rp = this.mateResidual(m, work, L, pl, false)!; x[j] = -1e-6; work.set(id, placementWith(pl.get(id)!, center, x, 0, L)); - const rm = this.mateResidual(m, work, L)!; + const rm = this.mateResidual(m, work, L, pl, false)!; 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)!); } + if (coupled) { + const ids = mateBodies(m).filter((id) => index.has(id)); + // Only where the mates before it already link its components (a loop) can it contradict them. + if (isCoupling(m) && ids.length > 1 && ids.every((id) => top(id) === top(ids[0])) && contradicts(J, block[block.length - 1], ids.map((id) => index.get(id)!), n)) { + conflicts.add(m.id); + continue; + } + for (const id of ids.slice(1)) coupled.set(top(id), top(ids[0])); + } J.push(...block); } // A component is fully defined when no motion the mates allow moves it: @@ -620,12 +1227,45 @@ export class MateSolver { 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 (!mateBodies(m).length) return 'A mate needs at least one component'; if (m.type === 'lock' && !m.rel) return 'The lock mate has no stored position'; + if (m.limit) { + if (!(m.limit.min <= m.limit.max)) return 'The smallest value must not be more than the largest'; + if (m.type === 'angle' && (m.limit.min < 0 || m.limit.max > 180)) return 'Angle limits are between 0° and 180°'; + if (m.type === 'hinge' && !m.rel) return 'The hinge has no stored position to measure its angle from'; + } + if (isMechanical(m.type)) return mechanicalProblem(m); return m.type === 'lock' ? null : mateProblem(m.type, m.a.geo, m.b.geo); } } +/** A rack along its pinion's axis (where `pl` puts them) is no rack and pinion: it would move as a screw. */ +function rackProblem(m: SolverMate, pl: Map): string | null { + const at = (e: SolverEntity) => (e.body ? pl.get(e.body) ?? null : null); + const dp = dirOf(placeGeo(m.a.geo, at(m.a))), u = dirOf(placeGeo(m.b.geo, at(m.b))); + return dp && u && Math.abs(dot(normalize(dp), normalize(u))) > 0.999 ? 'The rack must run across the pinion\'s axis, not along it' : null; +} + +/** + * A mechanical mate's residuals (see mateResidual). On its own: the closures + * here would make every call of mateResidual allocate, plain mates too. + */ +function mechanicalResidual(m: SolverMate, pl: Map, ref: Map, pa: Placement | null, pb: Placement | null, L: number, ineq: boolean, turns?: Map): number[] | null { + const now = (e: SolverEntity) => (e.body ? pl.get(e.body) ?? IDENT : IDENT); + const start = (e: SolverEntity) => (e.body ? ref.get(e.body) ?? now(e) : IDENT); + for (const e of [m.a2, m.b2]) if (e?.body && !pl.get(e.body)) return null; + const turned = (e: SolverEntity, d: Vec3) => { + if (!e.body) return 0; + if (!turns) return turnAbout(now(e).q, start(e).q, d); + const w = turns.get(e.body); + return w ? dot(w, d) : 0; + }; + return mechanicalEquations({ + m, ga: placeGeo(m.a.geo, pa), gb: placeGeo(m.b.geo, pb), ga2: m.a2 ? placeGeo(m.a2.geo, m.a2.body ? now(m.a2) : null) : null, gb2: m.b2 ? placeGeo(m.b2.geo, m.b2.body ? now(m.b2) : null) : null, + pa: now(m.a), pb: now(m.b), ra: start(m.a), rb: start(m.b), now, start, turned, L, ineq, + }); +} + /** * The mates that can move a component: those of the floating components * linked to it through mates between floating components. Mates of other @@ -635,14 +1275,63 @@ export class MateSolver { 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]); + // The floating components of each mate, found once (this runs on every drag step). + const each = mates.map((m) => mateBodies(m).filter((id) => floating.has(id))); 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; } + for (const ids of each) { + if (ids.length > 1 && ids.some((id) => linked.has(id)) && ids.some((id) => !linked.has(id))) { for (const id of ids) linked.add(id); grew = true; } + } + } + return mates.filter((m) => mateBodies(m).some((id) => linked.has(id))); +} + +const isCoupling = (m: SolverMate) => m.type === 'gear' || m.type === 'rackPinion' || m.type === 'screw'; + +/** + * Whether a coupling mate (its row `c` of the Jacobian) contradicts the mates + * before it (rows J, n variables): they let its components (`bodies`, by + * index) move, related another way, and with it they cannot move at all (two + * gear mates with different ratios between the same gears: they hold only + * while nothing turns). + */ +function contradicts(J: number[][], c: number[], bodies: number[], n: number): boolean { + const { basis } = nullSpace(J, n); + if (!basis.length) return false; + let vmax = 0, cmax = 0; + for (const v of basis) for (const x of v) vmax = Math.max(vmax, Math.abs(x)); + for (const x of c) cmax = Math.max(cmax, Math.abs(x)); + // What the mate asks of each motion the others allow. + const g = basis.map((v) => v.reduce((s, x, j) => s + x * c[j], 0)); + const gg = g.reduce((s, x) => s + x * x, 0); + if (Math.sqrt(gg) <= 1e-7 * cmax * vmax) return false; + let moved = false; + for (const b of bodies) { + for (let j = b * 6; j < b * 6 + 6; j++) { + const row = basis.map((v) => v[j]); + const rmax = Math.max(...row.map(Math.abs)); + if (rmax <= 1e-6 * vmax) continue; + moved = true; + // With the mate, this variable can still change unless it changes only along g. + const k = row.reduce((s, x, i) => s + x * g[i], 0) / gg; + if (row.some((x, i) => Math.abs(x - k * g[i]) > 1e-6 * rmax)) return false; } } - return mates.filter((m) => (m.a.body && linked.has(m.a.body)) || (m.b.body && linked.has(m.b.body))); + return moved; +} + +/** How far each drive is from its motion: radians for turns, lengths over L for moves. */ +function driveResidual(drives: Drive[], pl: Map, ref: Map, L: number): number[] { + return drives.map((d) => { + const p = pl.get(d.body), p0 = ref.get(d.body); + if (!p || !p0) return 0; + if (d.kind === 'rotate') return turnAbout(p.q, p0.q, d.axis) - d.amount; + if (d.kind === 'translate') return (dot(sub(applyPlacement(p, d.local), applyPlacement(p0, d.local)), d.dir) - d.amount) / L; + const b = d.base ? pl.get(d.base) ?? IDENT : IDENT, b0 = d.base ? ref.get(d.base) ?? IDENT : IDENT; + const rel = relativePlacement(b, p), rel0 = relativePlacement(b0, p0); + if (d.kind === 'relTurn') return turnAbout(rel.q, rel0.q, d.axis) - d.amount; + return (dot(sub(applyPlacement(rel, d.local), applyPlacement(rel0, d.local)), d.dir) - d.amount) / L; + }); } function dragResidual(goal: DragGoal, pl: Map, L: number): number[] { @@ -657,6 +1346,9 @@ function dragResidual(goal: DragGoal, pl: Map, L: number): number const sumSq = (r: number[]) => r.reduce((s, v) => s + v * v, 0); +/** The rotation vectors of the variables (each component's turn from where the solve started). */ +const turnsAt = (vars: Id[], x: number[]): Map => new Map(vars.map((id, i) => [id, [x[i * 6 + 3], x[i * 6 + 4], x[i * 6 + 5]] as Vec3])); + /** 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; diff --git a/src/parametric/src/fea/amg.ts b/src/parametric/src/fea/amg.ts new file mode 100644 index 000000000..4fe6929b3 --- /dev/null +++ b/src/parametric/src/fea/amg.ts @@ -0,0 +1,772 @@ +// Sparse block matrices and the linear solver: preconditioned conjugate +// gradients with a smoothed aggregation algebraic multigrid preconditioner +// (Vanek, Mandel and Brezina 1996) built for elasticity: nodes are grouped +// into aggregates, each aggregate's six rigid body motions (three +// translations, three rotations) span its coarse degrees of freedom, and the +// tentative prolongator is smoothed with one damped block Jacobi step. A +// V-cycle with block Gauss-Seidel smoothing (forward before, backward after: +// symmetric, so conjugate gradients may use it) and a dense Cholesky solve on +// the coarsest level. Block Jacobi is kept as a fallback preconditioner. +// +// Matrices are stored in block rows: the fine level in 3 x 3 node blocks, +// coarse levels in 6 x 6 aggregate blocks. + +export interface BlockMatrix { + /** Block rows (= block columns). */ + n: number; + /** Block size. */ + b: number; + rowPtr: Int32Array; + col: Int32Array; + /** b * b values per block, row-major. */ + val: Float64Array; +} + +/** Prolongator: n fine block rows of size b, m coarse block columns of size c. */ +export interface Prolongator { + n: number; + m: number; + b: number; + c: number; + rowPtr: Int32Array; + col: Int32Array; + val: Float64Array; +} + +/** y = A x */ +export function matvec(A: BlockMatrix, x: Float64Array, y: Float64Array) { + const { n, b, rowPtr, col, val } = A; + if (b === 3) { + for (let i = 0; i < n; i++) { + let y0 = 0, y1 = 0, y2 = 0; + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) { + const j = col[q] * 3, v = q * 9; + const x0 = x[j], x1 = x[j + 1], x2 = x[j + 2]; + y0 += val[v] * x0 + val[v + 1] * x1 + val[v + 2] * x2; + y1 += val[v + 3] * x0 + val[v + 4] * x1 + val[v + 5] * x2; + y2 += val[v + 6] * x0 + val[v + 7] * x1 + val[v + 8] * x2; + } + y[i * 3] = y0; y[i * 3 + 1] = y1; y[i * 3 + 2] = y2; + } + return; + } + const bb = b * b; + if (b === 6) { + // Coarse levels: the same sums with the six x values in registers. + for (let i = 0; i < n; i++) { + for (let r = 0; r < 6; r++) y[i * 6 + r] = 0; + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) { + const j = col[q] * 6, v = q * 36; + const x0 = x[j], x1 = x[j + 1], x2 = x[j + 2], x3 = x[j + 3], x4 = x[j + 4], x5 = x[j + 5]; + for (let r = 0; r < 6; r++) { + const w = v + r * 6; + y[i * 6 + r] += val[w] * x0 + val[w + 1] * x1 + val[w + 2] * x2 + val[w + 3] * x3 + val[w + 4] * x4 + val[w + 5] * x5; + } + } + } + return; + } + for (let i = 0; i < n; i++) { + for (let r = 0; r < b; r++) y[i * b + r] = 0; + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) { + const j = col[q] * b, v = q * bb; + for (let r = 0; r < b; r++) { + let s = 0; + for (let c = 0; c < b; c++) s += val[v + r * b + c] * x[j + c]; + y[i * b + r] += s; + } + } + } +} + +/** Sparsity pattern of the node blocks of a mesh (nodes sharing an element), columns sorted. */ +export function meshPattern(nNodes: number, elems: Int32Array, perElem: number): BlockMatrix { + const ne = elems.length / perElem; + const start = new Int32Array(nNodes + 1); + for (let q = 0; q < elems.length; q++) start[elems[q] + 1]++; + for (let i = 0; i < nNodes; i++) start[i + 1] += start[i]; + const fill = start.slice(); + const items = new Int32Array(elems.length); + for (let e = 0; e < ne; e++) for (let k = 0; k < perElem; k++) items[fill[elems[e * perElem + k]]++] = e; + const stamp = new Int32Array(nNodes).fill(-1); + const rowPtr = new Int32Array(nNodes + 1); + const cols: number[] = []; + const row: number[] = []; + for (let i = 0; i < nNodes; i++) { + row.length = 0; + for (let q = start[i]; q < start[i + 1]; q++) { + const e = items[q]; + for (let k = 0; k < perElem; k++) { + const j = elems[e * perElem + k]; + if (stamp[j] !== i) { stamp[j] = i; row.push(j); } + } + } + row.sort((a, b) => a - b); + for (const j of row) cols.push(j); + rowPtr[i + 1] = cols.length; + } + const col = Int32Array.from(cols); + return { n: nNodes, b: 3, rowPtr, col, val: new Float64Array(col.length * 9) }; +} + +/** Position of block (i, j) in A, or -1. */ +export function blockAt(A: BlockMatrix, i: number, j: number): number { + let lo = A.rowPtr[i], hi = A.rowPtr[i + 1] - 1; + const col = A.col; + while (lo <= hi) { + const m = (lo + hi) >> 1; + const c = col[m]; + if (c === j) return m; + if (c < j) lo = m + 1; + else hi = m - 1; + } + return -1; +} + +// ---------- small dense helpers ---------- + +/** Inverse of a symmetric positive b x b block (Gauss-Jordan); a singular one gives the inverse of its diagonal part where possible. */ +function invertBlock(src: Float64Array, off: number, b: number, out: Float64Array, oOff: number) { + const a = new Float64Array(b * b * 2); + for (let r = 0; r < b; r++) { for (let c = 0; c < b; c++) a[r * 2 * b + c] = src[off + r * b + c]; a[r * 2 * b + b + r] = 1; } + let scale = 0; + for (let r = 0; r < b; r++) scale = Math.max(scale, Math.abs(src[off + r * b + r])); + for (let c = 0; c < b; c++) { + let p = c, pv = Math.abs(a[c * 2 * b + c]); + for (let r = c + 1; r < b; r++) { const v = Math.abs(a[r * 2 * b + c]); if (v > pv) { pv = v; p = r; } } + if (!(pv > 1e-12 * scale) || !(pv > 0)) { + // A degree of freedom with no stiffness (a dummy coarse one): leave it alone. + for (let r = 0; r < b; r++) a[r * 2 * b + c] = r === c ? 1 : 0; + for (let k = 0; k < 2 * b; k++) a[c * 2 * b + k] = k === c || k === b + c ? 1 : 0; + for (let r = 0; r < b; r++) if (r !== c) a[r * 2 * b + b + c] = 0; + continue; + } + if (p !== c) for (let k = 0; k < 2 * b; k++) { const t = a[c * 2 * b + k]; a[c * 2 * b + k] = a[p * 2 * b + k]; a[p * 2 * b + k] = t; } + const d = a[c * 2 * b + c]; + for (let k = 0; k < 2 * b; k++) a[c * 2 * b + k] /= d; + for (let r = 0; r < b; r++) { + if (r === c) continue; + const f = a[r * 2 * b + c]; + if (f === 0) continue; + for (let k = 0; k < 2 * b; k++) a[r * 2 * b + k] -= f * a[c * 2 * b + k]; + } + } + for (let r = 0; r < b; r++) for (let c = 0; c < b; c++) out[oOff + r * b + c] = a[r * 2 * b + b + c]; +} + +function blockDiagInverse(A: BlockMatrix): Float64Array { + const { n, b } = A; + const bb = b * b; + const out = new Float64Array(n * bb); + for (let i = 0; i < n; i++) { + const q = blockAt(A, i, i); + if (q < 0) { for (let r = 0; r < b; r++) out[i * bb + r * b + r] = 1; continue; } + invertBlock(A.val, q * bb, b, out, i * bb); + } + return out; +} + +// ---------- multigrid ---------- + +/** Strength of connection for aggregation (relative block norm). */ +const THETA = 0.08; + +interface Level { + A: BlockMatrix; + Dinv: Float64Array; + P: Prolongator | null; + /** Work vectors. */ + x: Float64Array; + r: Float64Array; + t: Float64Array; +} + +export interface Preconditioner { + apply(r: Float64Array, z: Float64Array): void; + levels: number; + description: string; +} + +/** Block Jacobi preconditioner. */ +export function blockJacobi(A: BlockMatrix): Preconditioner { + const D = blockDiagInverse(A); + const b = A.b, bb = b * b; + return { + levels: 1, description: 'block Jacobi', + apply(r, z) { + for (let i = 0; i < A.n; i++) for (let p = 0; p < b; p++) { + let s = 0; + for (let c = 0; c < b; c++) s += D[i * bb + p * b + c] * r[i * b + c]; + z[i * b + p] = s; + } + }, + }; +} + +/** + * Smoothed aggregation multigrid for a 3D elasticity matrix in node blocks, + * with the nodes' coordinates for the rigid body motions. + */ +export function smoothedAggregation(A: BlockMatrix, coords: Float64Array, opts: { + coarsest?: number; progress?: (f: number) => void; debug?: (m: string) => void; + /** Nodes whose unknowns are in their own frame: 3 x 3 rotation per node (columns: local axes in global coordinates), row-major. */ + frames?: Float64Array; + /** Number of leading local unknowns of each node that are held (removed from the problem). */ + held?: Int8Array; +} = {}): Preconditioner { + const coarsest = opts.coarsest ?? 900; + // Rigid body motions of each node, about the centroid and scaled to the part's size (well conditioned). + const n0 = A.n; + const c0 = [0, 0, 0]; + for (let i = 0; i < n0; i++) for (let d = 0; d < 3; d++) c0[d] += coords[i * 3 + d] / n0; + let L = 0; + for (let i = 0; i < n0; i++) L = Math.max(L, Math.hypot(coords[i * 3] - c0[0], coords[i * 3 + 1] - c0[1], coords[i * 3 + 2] - c0[2])); + L = L || 1; + // B: per node b x 6 (row-major). + let B: Float64Array = new Float64Array(n0 * 18); + for (let i = 0; i < n0; i++) { + const x = (coords[i * 3] - c0[0]) / L, y = (coords[i * 3 + 1] - c0[1]) / L, z = (coords[i * 3 + 2] - c0[2]) / L; + // u = t + w x r: rows ux, uy, uz; columns tx, ty, tz, wx, wy, wz. + B.set([1, 0, 0, 0, z, -y, 0, 1, 0, -z, 0, x, 0, 0, 1, y, -x, 0], i * 18); + // The motions in the node's own frame (R^T B), none in the held directions. + const R = opts.frames, k = opts.held?.[i] ?? 0; + if (R && (k || R[i * 9] !== 1 || R[i * 9 + 4] !== 1 || R[i * 9 + 8] !== 1)) { + const g = B.slice(i * 18, i * 18 + 18); + for (let r = 0; r < 3; r++) for (let j = 0; j < 6; j++) B[i * 18 + r * 6 + j] = r < k ? 0 : R[i * 9 + r] * g[j] + R[i * 9 + 3 + r] * g[6 + j] + R[i * 9 + 6 + r] * g[12 + j]; + } + } + const levels: Level[] = []; + let cur = A; + for (let depth = 0; depth < 12; depth++) { + const Dinv = blockDiagInverse(cur); + const N = cur.n * cur.b; + const lvl: Level = { A: cur, Dinv, P: null, x: new Float64Array(N), r: new Float64Array(N), t: new Float64Array(N) }; + levels.push(lvl); + if (N <= coarsest) break; + let t = performance.now(); + const lap = (what: string) => { if (!opts.debug) return; const n = performance.now(); opts.debug(`level ${depth} ${what}: ${(n - t).toFixed(0)} ms`); t = n; }; + const agg = aggregate(cur, depth === 0 ? THETA : THETA * 0.5 ** depth); + lap(`aggregate (${agg.count} of ${cur.n})`); + if (agg.count * 6 >= N * 0.8 || agg.count < 2) break; + const { P, Bc } = tentative(cur.b, agg, B); + lap('tentative'); + const Ps = smoothProlongator(cur, Dinv, P); + lap(`smooth (${Ps.col.length} blocks)`); + const Ac = galerkin(cur, Ps); + lap(`galerkin (${Ac.col.length} blocks)`); + lvl.P = Ps; + B = Bc; + cur = Ac; + opts.progress?.(Math.min(0.9, (depth + 1) / 4)); + } + // Coarsest level: dense Cholesky (with a tiny shift if the level has dummy degrees of freedom). + const last = levels[levels.length - 1]; + const dense = denseCholesky(last.A); + const vcycle = (k: number, b: Float64Array, x: Float64Array) => { + const lv = levels[k]; + if (k === levels.length - 1) { dense(b, x); return; } + x.fill(0); + gaussSeidel(lv.A, lv.Dinv, b, x, true); + matvec(lv.A, x, lv.t); + for (let i = 0; i < b.length; i++) lv.r[i] = b[i] - lv.t[i]; + const nx = levels[k + 1]; + const rc = new Float64Array(nx.A.n * nx.A.b); + restrict(lv.P!, lv.r, rc); + const xc = new Float64Array(rc.length); + vcycle(k + 1, rc, xc); + prolongAdd(lv.P!, xc, x); + gaussSeidel(lv.A, lv.Dinv, b, x, false); + }; + return { + levels: levels.length, + description: `smoothed aggregation multigrid, ${levels.length} levels (${levels.map((l) => l.A.n * l.A.b).join(', ')} unknowns)`, + apply(r, z) { vcycle(0, r, z); }, + }; +} + +/** Groups nodes into aggregates: a node and its strongly connected neighbours, then the rest joined to a neighbour's. */ +function aggregate(A: BlockMatrix, theta: number): { of: Int32Array; count: number } { + const { n, b, rowPtr, col, val } = A; + const bb = b * b; + const norm = (q: number) => { let s = 0; for (let k = 0; k < bb; k++) s += val[q * bb + k] ** 2; return Math.sqrt(s); }; + const diag = new Float64Array(n); + for (let i = 0; i < n; i++) { const q = blockAt(A, i, i); diag[i] = q >= 0 ? norm(q) : 0; } + const strong = (i: number, q: number) => { const j = col[q]; return j !== i && norm(q) > theta * Math.sqrt(diag[i] * diag[j]); }; + const of = new Int32Array(n).fill(-1); + let count = 0; + // Pass 1: whole neighbourhoods. + for (let i = 0; i < n; i++) { + if (of[i] >= 0) continue; + let free = true, any = false; + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) if (strong(i, q)) { any = true; if (of[col[q]] >= 0) { free = false; break; } } + if (!free || !any) continue; + of[i] = count; + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) if (strong(i, q)) of[col[q]] = count; + count++; + } + // Pass 2: the rest join the neighbouring aggregate they are most strongly connected to. + const pass1 = of.slice(); + for (let i = 0; i < n; i++) { + if (of[i] >= 0) continue; + let best = -1, bv = 0; + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) { + const j = col[q]; + if (j === i || pass1[j] < 0) continue; + const v = norm(q) / Math.sqrt(diag[i] * diag[j] || 1); + if (v > bv) { bv = v; best = pass1[j]; } + } + if (best >= 0) of[i] = best; + } + // Pass 3: whatever is left (isolated groups) makes aggregates of its own. + for (let i = 0; i < n; i++) { + if (of[i] >= 0) continue; + of[i] = count; + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) if (of[col[q]] < 0) of[col[q]] = count; + count++; + } + return { of, count }; +} + +/** + * Tentative prolongator: per aggregate, the rigid body motions of its nodes + * orthonormalised (QR); R becomes the coarse level's rigid body motions. + */ +function tentative(b: number, agg: { of: Int32Array; count: number }, B: Float64Array): { P: Prolongator; Bc: Float64Array } { + const n = agg.of.length; + const members: number[][] = Array.from({ length: agg.count }, () => []); + for (let i = 0; i < n; i++) members[agg.of[i]].push(i); + const c = 6; + const val = new Float64Array(n * b * c); + const Bc = new Float64Array(agg.count * c * c); + for (let a = 0; a < agg.count; a++) { + const nodes = members[a]; + const rows = nodes.length * b; + // Q: rows x 6, column-major for Gram-Schmidt. + const Q = new Float64Array(rows * c); + nodes.forEach((i, k) => { for (let r = 0; r < b; r++) for (let j = 0; j < c; j++) Q[j * rows + k * b + r] = B[i * b * c + r * c + j]; }); + const R = new Float64Array(c * c); + let ref = 0; + for (let j = 0; j < c; j++) { let s = 0; for (let r = 0; r < rows; r++) s += Q[j * rows + r] ** 2; ref = Math.max(ref, Math.sqrt(s)); } + for (let j = 0; j < c; j++) { + // Twice, for orthogonality to machine precision. + for (let pass = 0; pass < 2; pass++) { + for (let k = 0; k < j; k++) { + let d = 0; + for (let r = 0; r < rows; r++) d += Q[k * rows + r] * Q[j * rows + r]; + R[k * c + j] += d; + for (let r = 0; r < rows; r++) Q[j * rows + r] -= d * Q[k * rows + r]; + } + } + let s = 0; + for (let r = 0; r < rows; r++) s += Q[j * rows + r] ** 2; + s = Math.sqrt(s); + if (s > 1e-10 * ref) { + R[j * c + j] = s; + for (let r = 0; r < rows; r++) Q[j * rows + r] /= s; + } else { + // Dependent motion (too few nodes to tell it apart): a dummy coarse unknown. + for (let r = 0; r < rows; r++) Q[j * rows + r] = 0; + } + } + nodes.forEach((i, k) => { for (let r = 0; r < b; r++) for (let j = 0; j < c; j++) val[i * b * c + r * c + j] = Q[j * rows + k * b + r]; }); + Bc.set(R, a * c * c); + } + const rowPtr = new Int32Array(n + 1); + for (let i = 0; i < n; i++) rowPtr[i + 1] = i + 1; + return { P: { n, m: agg.count, b, c, rowPtr, col: Int32Array.from(agg.of), val }, Bc }; +} + +/** Largest eigenvalue of D^-1 A, by power iteration. */ +function spectralRadius(A: BlockMatrix, Dinv: Float64Array): number { + const N = A.n * A.b, b = A.b, bb = b * b; + let x = new Float64Array(N); + for (let i = 0; i < N; i++) x[i] = Math.sin(i * 12.9898 + 1) + 1.1; + const y = new Float64Array(N); + let lam = 1; + for (let it = 0; it < 15; it++) { + let nx = 0; + for (let i = 0; i < N; i++) nx += x[i] * x[i]; + nx = Math.sqrt(nx); + for (let i = 0; i < N; i++) x[i] /= nx; + matvec(A, x, y); + const z = new Float64Array(N); + for (let i = 0; i < A.n; i++) for (let p = 0; p < b; p++) { let s = 0; for (let c = 0; c < b; c++) s += Dinv[i * bb + p * b + c] * y[i * b + c]; z[i * b + p] = s; } + let nz = 0; + for (let i = 0; i < N; i++) nz += z[i] * z[i]; + lam = Math.sqrt(nz); + x = z; + } + return lam; +} + +/** P = (I - w D^-1 A) P0, with w = 4 / (3 rho(D^-1 A)). */ +function smoothProlongator(A: BlockMatrix, Dinv: Float64Array, P0: Prolongator): Prolongator { + const w = 4 / 3 / spectralRadius(A, Dinv); + const { n, b, rowPtr, col, val } = A; + const c = P0.c, bb = b * b, bc = b * c; + const outPtr = new Int32Array(n + 1); + let outCol = new Int32Array(Math.max(16, n * 8)); + let outVal = new Float64Array(outCol.length * bc); + let nnz = 0; + // (A P0) row block i in a dense accumulator over the coarse columns, with the columns it touches. + const acc = new Float64Array(P0.m * bc); + const mark = new Int32Array(P0.m).fill(-1); + const rows: number[] = []; + for (let i = 0; i < n; i++) { + rows.length = 0; + // (A P0) row block i: sum over j of A_ij P0_j (P0 has one block per row). + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) { + const j = col[q]; + const J = P0.col[j], o = J * bc; + if (mark[J] !== i) { mark[J] = i; rows.push(J); acc.fill(0, o, o + bc); } + for (let r = 0; r < b; r++) for (let k = 0; k < c; k++) { + let s = 0; + for (let m = 0; m < b; m++) s += val[q * bb + r * b + m] * P0.val[j * bc + m * c + k]; + acc[o + r * c + k] += s; + } + } + const own = P0.col[i]; + const hasOwn = mark[own] === i; + if (!hasOwn) rows.push(own); + rows.sort((x, y) => x - y); + if (nnz + rows.length > outCol.length) { + const size = Math.max(outCol.length * 2, nnz + rows.length); + const gc = new Int32Array(size); gc.set(outCol); outCol = gc; + const gv = new Float64Array(size * bc); gv.set(outVal); outVal = gv; + } + for (const J of rows) { + // -w D^-1 (A P0) + const t = nnz * bc, o = J * bc; + if (J !== own || hasOwn) for (let r = 0; r < b; r++) for (let k = 0; k < c; k++) { let s = 0; for (let m = 0; m < b; m++) s += Dinv[i * bb + r * b + m] * acc[o + m * c + k]; outVal[t + r * c + k] = -w * s; } + if (J === own) for (let r = 0; r < bc; r++) outVal[t + r] += P0.val[i * bc + r]; + outCol[nnz++] = J; + } + outPtr[i + 1] = nnz; + } + return { n, m: P0.m, b, c, rowPtr: outPtr, col: outCol.slice(0, nnz), val: outVal.slice(0, nnz * bc) }; +} + +/** + * Coarse matrix P^T A P (A symmetric): the pattern first, then fine row by + * fine row, (A P)_i in a dense accumulator over the coarse columns and + * P_iI^T (A P)_iJ added into the upper blocks (J >= I) of the coarse row, + * which are mirrored into the lower ones at the end. + */ +export function galerkin(A: BlockMatrix, P: Prolongator): BlockMatrix { + const { n, b, rowPtr, col, val } = A; + const M = P.m, c = P.c, bb = b * b, bc = b * c, cc = c * c; + const mark = new Int32Array(M).fill(-1); + // Pattern of A P: coarse columns of each fine row. + const apPtr = new Int32Array(n + 1); + let apCol = new Int32Array(Math.max(16, n * 8)); + let na = 0; + for (let i = 0; i < n; i++) { + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) { + const j = col[q]; + for (let p = P.rowPtr[j]; p < P.rowPtr[j + 1]; p++) { + const J = P.col[p]; + if (mark[J] === i) continue; + mark[J] = i; + if (na === apCol.length) { const g = new Int32Array(na * 2); g.set(apCol); apCol = g; } + apCol[na++] = J; + } + } + apPtr[i + 1] = na; + } + // Pattern of the coarse matrix: row I gathers the columns of (A P)_i over the fine rows i that P maps to I. + const tPtr = new Int32Array(M + 1); + for (let p = 0; p < P.col.length; p++) tPtr[P.col[p] + 1]++; + for (let I = 0; I < M; I++) tPtr[I + 1] += tPtr[I]; + const tRow = new Int32Array(P.col.length); + { + const fill = tPtr.slice(); + for (let i = 0; i < n; i++) for (let p = P.rowPtr[i]; p < P.rowPtr[i + 1]; p++) tRow[fill[P.col[p]]++] = i; + } + mark.fill(-1); + const rp = new Int32Array(M + 1); + let cl = new Int32Array(Math.max(16, M * 16)); + let nnz = 0; + for (let I = 0; I < M; I++) { + const s0 = nnz; + for (let t = tPtr[I]; t < tPtr[I + 1]; t++) { + const i = tRow[t]; + for (let q = apPtr[i]; q < apPtr[i + 1]; q++) { + const J = apCol[q]; + if (mark[J] === I) continue; + mark[J] = I; + if (nnz === cl.length) { const g = new Int32Array(nnz * 2); g.set(cl); cl = g; } + cl[nnz++] = J; + } + } + cl.subarray(s0, nnz).sort(); + rp[I + 1] = nnz; + } + cl = cl.slice(0, nnz); + const vl = new Float64Array(nnz * cc); + const find = (I: number, J: number) => { + let lo = rp[I], hi = rp[I + 1] - 1; + while (lo <= hi) { const m = (lo + hi) >> 1, x = cl[m]; if (x === J) return m; if (x < J) lo = m + 1; else hi = m - 1; } + return -1; + }; + // Values. + const acc = new Float64Array(M * bc); + const Pv = P.val; + for (let i = 0; i < n; i++) { + const a0 = apPtr[i], a1 = apPtr[i + 1]; + for (let q = a0; q < a1; q++) acc.fill(0, apCol[q] * bc, apCol[q] * bc + bc); + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) { + const j = col[q], av = q * bb; + for (let p = P.rowPtr[j]; p < P.rowPtr[j + 1]; p++) { + const o = P.col[p] * bc, pv = p * bc; + for (let r = 0; r < b; r++) { + const ar = av + r * b, orow = o + r * c; + for (let m = 0; m < b; m++) { + const x = val[ar + m]; + if (x === 0) continue; + const pm = pv + m * c; + if (c === 6) { + acc[orow] += x * Pv[pm]; acc[orow + 1] += x * Pv[pm + 1]; acc[orow + 2] += x * Pv[pm + 2]; + acc[orow + 3] += x * Pv[pm + 3]; acc[orow + 4] += x * Pv[pm + 4]; acc[orow + 5] += x * Pv[pm + 5]; + } else for (let k = 0; k < c; k++) acc[orow + k] += x * Pv[pm + k]; + } + } + } + } + for (let p = P.rowPtr[i]; p < P.rowPtr[i + 1]; p++) { + const I = P.col[p], pv = p * bc; + for (let q = a0; q < a1; q++) { + const J = apCol[q]; + if (J < I) continue; + const d = find(I, J) * cc, o = J * bc; + // P_iI^T (b x c)^T * (A P)_iJ (b x c) + for (let m = 0; m < b; m++) { + const pm = pv + m * c, om = o + m * c; + for (let r = 0; r < c; r++) { + const x = Pv[pm + r]; + if (x === 0) continue; + const dr = d + r * c; + if (c === 6) { + vl[dr] += x * acc[om]; vl[dr + 1] += x * acc[om + 1]; vl[dr + 2] += x * acc[om + 2]; + vl[dr + 3] += x * acc[om + 3]; vl[dr + 4] += x * acc[om + 4]; vl[dr + 5] += x * acc[om + 5]; + } else for (let k = 0; k < c; k++) vl[dr + k] += x * acc[om + k]; + } + } + } + } + } + // Lower blocks from the upper ones. + for (let I = 0; I < M; I++) { + for (let q = rp[I]; q < rp[I + 1]; q++) { + const J = cl[q]; + if (J <= I) continue; + const d = find(J, I) * cc, s = q * cc; + for (let r = 0; r < c; r++) for (let k = 0; k < c; k++) vl[d + k * c + r] = vl[s + r * c + k]; + } + } + for (let I = 0; I < M; I++) { + // A dummy coarse unknown (no stiffness) gets a unit diagonal so the level stays solvable. + const f = find(I, I); + if (f >= 0) { + const d = f * cc; + let scale = 0; + for (let r = 0; r < c; r++) scale = Math.max(scale, vl[d + r * c + r]); + for (let r = 0; r < c; r++) if (!(vl[d + r * c + r] > 1e-12 * scale)) { + let off = 0; + for (let k = 0; k < c; k++) off += Math.abs(vl[d + r * c + k]); + if (off <= 1e-12 * scale) vl[d + r * c + r] = scale || 1; + } + } + } + return { n: P.m, b: c, rowPtr: rp, col: cl, val: vl }; +} + +function restrict(P: Prolongator, r: Float64Array, out: Float64Array) { + out.fill(0); + const { n, b, c, rowPtr, col, val } = P; + const bc = b * c; + if (b === 3 && c === 6) { + for (let i = 0; i < n; i++) { + const r0 = r[i * 3], r1 = r[i * 3 + 1], r2 = r[i * 3 + 2]; + for (let p = rowPtr[i]; p < rowPtr[i + 1]; p++) { + const J = col[p] * 6, v = p * 18; + for (let k = 0; k < 6; k++) out[J + k] += val[v + k] * r0 + val[v + 6 + k] * r1 + val[v + 12 + k] * r2; + } + } + return; + } + for (let i = 0; i < n; i++) { + for (let p = rowPtr[i]; p < rowPtr[i + 1]; p++) { + const J = col[p] * c; + for (let k = 0; k < c; k++) { + let s = 0; + for (let m = 0; m < b; m++) s += val[p * bc + m * c + k] * r[i * b + m]; + out[J + k] += s; + } + } + } +} + +function prolongAdd(P: Prolongator, xc: Float64Array, x: Float64Array) { + const { n, b, c, rowPtr, col, val } = P; + const bc = b * c; + if (b === 3 && c === 6) { + for (let i = 0; i < n; i++) { + let x0 = 0, x1 = 0, x2 = 0; + for (let p = rowPtr[i]; p < rowPtr[i + 1]; p++) { + const J = col[p] * 6, v = p * 18; + const c0 = xc[J], c1 = xc[J + 1], c2 = xc[J + 2], c3 = xc[J + 3], c4 = xc[J + 4], c5 = xc[J + 5]; + x0 += val[v] * c0 + val[v + 1] * c1 + val[v + 2] * c2 + val[v + 3] * c3 + val[v + 4] * c4 + val[v + 5] * c5; + x1 += val[v + 6] * c0 + val[v + 7] * c1 + val[v + 8] * c2 + val[v + 9] * c3 + val[v + 10] * c4 + val[v + 11] * c5; + x2 += val[v + 12] * c0 + val[v + 13] * c1 + val[v + 14] * c2 + val[v + 15] * c3 + val[v + 16] * c4 + val[v + 17] * c5; + } + x[i * 3] += x0; x[i * 3 + 1] += x1; x[i * 3 + 2] += x2; + } + return; + } + for (let i = 0; i < n; i++) { + for (let p = rowPtr[i]; p < rowPtr[i + 1]; p++) { + const J = col[p] * c; + for (let m = 0; m < b; m++) { + let s = 0; + for (let k = 0; k < c; k++) s += val[p * bc + m * c + k] * xc[J + k]; + x[i * b + m] += s; + } + } + } +} + +/** One block Gauss-Seidel sweep, forward or backward. */ +function gaussSeidel(A: BlockMatrix, Dinv: Float64Array, rhs: Float64Array, x: Float64Array, forward: boolean) { + const { n, b, rowPtr, col, val } = A; + if (b === 3) { + // The fine level (most of the time): the same sums, unrolled. + for (let k = 0; k < n; k++) { + const i = forward ? k : n - 1 - k; + let s0 = rhs[i * 3], s1 = rhs[i * 3 + 1], s2 = rhs[i * 3 + 2]; + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) { + const j = col[q]; + if (j === i) continue; + const v = q * 9, x0 = x[j * 3], x1 = x[j * 3 + 1], x2 = x[j * 3 + 2]; + s0 -= val[v] * x0 + val[v + 1] * x1 + val[v + 2] * x2; + s1 -= val[v + 3] * x0 + val[v + 4] * x1 + val[v + 5] * x2; + s2 -= val[v + 6] * x0 + val[v + 7] * x1 + val[v + 8] * x2; + } + const d = i * 9; + x[i * 3] = Dinv[d] * s0 + Dinv[d + 1] * s1 + Dinv[d + 2] * s2; + x[i * 3 + 1] = Dinv[d + 3] * s0 + Dinv[d + 4] * s1 + Dinv[d + 5] * s2; + x[i * 3 + 2] = Dinv[d + 6] * s0 + Dinv[d + 7] * s1 + Dinv[d + 8] * s2; + } + return; + } + const bb = b * b; + const s = new Float64Array(b); + for (let k = 0; k < n; k++) { + const i = forward ? k : n - 1 - k; + for (let r = 0; r < b; r++) s[r] = rhs[i * b + r]; + for (let q = rowPtr[i]; q < rowPtr[i + 1]; q++) { + const j = col[q]; + if (j === i) continue; + if (b === 6) { + const o = j * 6, x0 = x[o], x1 = x[o + 1], x2 = x[o + 2], x3 = x[o + 3], x4 = x[o + 4], x5 = x[o + 5]; + for (let r = 0; r < 6; r++) { + const w = q * 36 + r * 6; + s[r] -= val[w] * x0 + val[w + 1] * x1 + val[w + 2] * x2 + val[w + 3] * x3 + val[w + 4] * x4 + val[w + 5] * x5; + } + continue; + } + for (let r = 0; r < b; r++) { + let t = 0; + for (let m = 0; m < b; m++) t += val[q * bb + r * b + m] * x[j * b + m]; + s[r] -= t; + } + } + for (let r = 0; r < b; r++) { + let t = 0; + for (let m = 0; m < b; m++) t += Dinv[i * bb + r * b + m] * s[m]; + x[i * b + r] = t; + } + } +} + +/** Dense Cholesky solve of a (small) block matrix; a zero pivot (a free motion) is skipped. */ +function denseCholesky(A: BlockMatrix): (b: Float64Array, x: Float64Array) => void { + const N = A.n * A.b, bs = A.b, bb = bs * bs; + const M = new Float64Array(N * N); + for (let i = 0; i < A.n; i++) for (let q = A.rowPtr[i]; q < A.rowPtr[i + 1]; q++) { + const j = A.col[q]; + for (let r = 0; r < bs; r++) for (let c = 0; c < bs; c++) M[(i * bs + r) * N + j * bs + c] = A.val[q * bb + r * bs + c]; + } + let scale = 0; + for (let i = 0; i < N; i++) scale = Math.max(scale, M[i * N + i]); + const skip = new Uint8Array(N); + for (let k = 0; k < N; k++) { + let d = M[k * N + k]; + for (let p = 0; p < k; p++) d -= M[k * N + p] ** 2; + if (!(d > 1e-13 * scale)) { skip[k] = 1; M[k * N + k] = 1; for (let i = k + 1; i < N; i++) M[i * N + k] = 0; continue; } + const l = Math.sqrt(d); + M[k * N + k] = l; + for (let i = k + 1; i < N; i++) { + let s = M[i * N + k]; + for (let p = 0; p < k; p++) s -= M[i * N + p] * M[k * N + p]; + M[i * N + k] = s / l; + } + } + return (b, x) => { + for (let i = 0; i < N; i++) { + if (skip[i]) { x[i] = 0; continue; } + let s = b[i]; + for (let p = 0; p < i; p++) s -= M[i * N + p] * x[p]; + x[i] = s / M[i * N + i]; + } + for (let i = N - 1; i >= 0; i--) { + if (skip[i]) { x[i] = 0; continue; } + let s = x[i]; + for (let p = i + 1; p < N; p++) s -= M[p * N + i] * x[p]; + x[i] = s / M[i * N + i]; + } + }; +} + +export interface CgResult { + iterations: number; + residual: number; + converged: boolean; +} + +/** Preconditioned conjugate gradients from x = 0; tol is relative to |b|. */ +export function pcg(A: BlockMatrix, b: Float64Array, x: Float64Array, M: Preconditioner, opts: { tol?: number; maxIter?: number; progress?: (it: number, rel: number) => void } = {}): CgResult { + const N = b.length; + const tol = opts.tol ?? 1e-8; + const maxIter = opts.maxIter ?? 2000; + const r = new Float64Array(N), z = new Float64Array(N), p = new Float64Array(N), q = new Float64Array(N); + x.fill(0); + r.set(b); + let bn = 0; + for (let i = 0; i < N; i++) bn += b[i] * b[i]; + bn = Math.sqrt(bn); + if (!(bn > 0)) return { iterations: 0, residual: 0, converged: true }; + M.apply(r, z); + p.set(z); + let rz = 0; + for (let i = 0; i < N; i++) rz += r[i] * z[i]; + let rel = 1; + for (let it = 1; it <= maxIter; it++) { + matvec(A, p, q); + let pq = 0; + for (let i = 0; i < N; i++) pq += p[i] * q[i]; + if (!(pq > 0)) return { iterations: it, residual: rel, converged: false }; + const alpha = rz / pq; + let rn = 0; + for (let i = 0; i < N; i++) { x[i] += alpha * p[i]; r[i] -= alpha * q[i]; rn += r[i] * r[i]; } + rel = Math.sqrt(rn) / bn; + opts.progress?.(it, rel); + if (rel <= tol) return { iterations: it, residual: rel, converged: true }; + M.apply(r, z); + let rz2 = 0; + for (let i = 0; i < N; i++) rz2 += r[i] * z[i]; + const beta = rz2 / rz; + rz = rz2; + for (let i = 0; i < N; i++) p[i] = z[i] + beta * p[i]; + } + return { iterations: maxIter, residual: rel, converged: false }; +} diff --git a/src/parametric/src/fea/client.ts b/src/parametric/src/fea/client.ts new file mode 100644 index 000000000..027249da1 --- /dev/null +++ b/src/parametric/src/fea/client.ts @@ -0,0 +1,112 @@ +// The interface side of the stress analysis worker. Requests run one at a +// time; cancelling stops the worker (a computation in progress cannot be +// interrupted otherwise) and the next request starts a new one, which meshes +// again. + +import type { StaticInput } from './static'; +import type { FeaSurfaceData } from './surface'; +import type { FeaMeshInfo, FeaSolution } from './results'; +import type { FeaWorkerRequest, FeaWorkerResponse } from './worker'; + +type Payload = { type: 'mesh'; surface: FeaSurfaceData; size: number; min?: number } | { type: 'solve'; input: StaticInput }; + +interface Pending { + resolve: (v: unknown) => void; + reject: (e: Error) => void; + progress?: (stage: string, v: number) => void; +} + +export class FeaCancelled extends Error { + constructor() { super('Cancelled'); } +} + +/** An error from the worker; `user`: its message is written for the user (else an internal failure). */ +export class FeaEngineError extends Error { + constructor(message: string, readonly user: boolean) { + super(user ? message : `The analysis ran into a problem (${message})`); + } +} + +export class FeaClient { + private worker: Worker | null = null; + private nextId = 1; + private pending = new Map(); + /** Whether the worker holds a mesh (a new worker has none). */ + meshed = false; + + constructor(private readonly create: () => Worker = () => new Worker(new URL('./worker.ts', import.meta.url), { type: 'module', name: 'analysis' })) {} + + private ensure(): Worker { + if (this.worker) return this.worker; + const w = this.create(); + let started = false; + w.onmessage = (ev: MessageEvent) => { + const r = ev.data; + started = true; + if (r.type === 'ready') return; + const p = this.pending.get(r.id); + if (!p) return; + if (r.type === 'progress') { p.progress?.(r.stage, r.value); return; } + this.pending.delete(r.id); + if (r.type === 'done') p.resolve(r.result); + else p.reject(new FeaEngineError(r.error, r.user)); + }; + w.onerror = (ev) => { + ev.preventDefault?.(); + // A worker that never started could not load its code (offline, or the app was updated): not the part's fault. + this.fail(new Error(started + ? `The analysis stopped${ev.message ? ` (${ev.message})` : ''}. The part may be too large for this mesh size: try a coarser mesh.` + : `The analysis could not start${ev.message ? ` (${ev.message})` : ''}. Check the connection and reload the page.`)); + }; + this.worker = w; + this.meshed = false; + return w; + } + + private send(payload: Payload, progress?: (stage: string, v: number) => void, transfer: Transferable[] = []): Promise { + const w = this.ensure(); + const id = this.nextId++; + return new Promise((resolve, reject) => { + this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, progress }); + w.postMessage({ id, ...payload } as FeaWorkerRequest, transfer); + }); + } + + /** + * Meshes the surface in the worker, finer down to `min` where its walls need it (the stats give the size + * used); its arrays are moved there (they are empty here afterwards). + */ + async mesh(surface: FeaSurfaceData, size: number, progress?: (stage: string, v: number) => void, min = size): Promise { + this.meshed = false; + const info = await this.send({ type: 'mesh', surface, size, min }, progress, [surface.positions.buffer, surface.indices.buffer, surface.triFace.buffer] as ArrayBuffer[]); + this.meshed = true; + return info; + } + + solve(input: StaticInput, progress?: (stage: string, v: number) => void): Promise { + return this.send({ type: 'solve', input }, progress); + } + + /** Stops whatever is running (its promise rejects with FeaCancelled); the mesh goes with the worker. */ + cancel() { + if (!this.pending.size) return; + this.fail(new FeaCancelled()); + } + + private fail(e: Error) { + this.worker?.terminate(); + this.worker = null; + this.meshed = false; + const all = [...this.pending.values()]; + this.pending.clear(); + for (const p of all) p.reject(e); + } + + get busy(): boolean { + return this.pending.size > 0; + } + + dispose() { + this.fail(new FeaCancelled()); + } +} diff --git a/src/parametric/src/fea/elements.ts b/src/parametric/src/fea/elements.ts new file mode 100644 index 000000000..d7338fc3b --- /dev/null +++ b/src/parametric/src/fea/elements.ts @@ -0,0 +1,192 @@ +// 10-node (quadratic) tetrahedra and 6-node boundary triangles for linear +// isotropic elasticity: stiffness by 4-point Gauss quadrature (exact for +// straight-sided elements), consistent nodal loads for body forces and for +// tractions and pressures on curved faces, and stresses at the nodes. + +import { GAUSS4, quadDerivs } from './mesher'; + +/** Lame constants of an isotropic material. */ +export function lame(E: number, nu: number): { lambda: number; mu: number } { + return { lambda: (E * nu) / ((1 + nu) * (1 - 2 * nu)), mu: E / (2 * (1 + nu)) }; +} + +/** Shape functions of the 10-node tetrahedron at volume coordinates (L1, L2, L3). */ +export function quadShape(l1: number, l2: number, l3: number, out: Float64Array) { + const l0 = 1 - l1 - l2 - l3; + out[0] = l0 * (2 * l0 - 1); out[1] = l1 * (2 * l1 - 1); out[2] = l2 * (2 * l2 - 1); out[3] = l3 * (2 * l3 - 1); + out[4] = 4 * l0 * l1; out[5] = 4 * l1 * l2; out[6] = 4 * l2 * l0; out[7] = 4 * l0 * l3; out[8] = 4 * l1 * l3; out[9] = 4 * l2 * l3; +} + +const dN = new Float64Array(30); + +/** + * Gradients of the shape functions (x, y, z per node, 30 values) at volume + * coordinates; returns the Jacobian determinant (6 times the volume for a straight element). + */ +export function shapeGradients(X: ArrayLike, nodes: ArrayLike, off: number, l1: number, l2: number, l3: number, g: Float64Array): number { + quadDerivs(l1, l2, l3, dN); + let j00 = 0, j01 = 0, j02 = 0, j10 = 0, j11 = 0, j12 = 0, j20 = 0, j21 = 0, j22 = 0; + for (let a = 0; a < 10; a++) { + const n = nodes[off + a] * 3; + const x = X[n], y = X[n + 1], z = X[n + 2]; + const d0 = dN[a * 3], d1 = dN[a * 3 + 1], d2 = dN[a * 3 + 2]; + j00 += d0 * x; j01 += d0 * y; j02 += d0 * z; + j10 += d1 * x; j11 += d1 * y; j12 += d1 * z; + j20 += d2 * x; j21 += d2 * y; j22 += d2 * z; + } + const c00 = j11 * j22 - j12 * j21, c01 = j02 * j21 - j01 * j22, c02 = j01 * j12 - j02 * j11; + const c10 = j12 * j20 - j10 * j22, c11 = j00 * j22 - j02 * j20, c12 = j02 * j10 - j00 * j12; + const c20 = j10 * j21 - j11 * j20, c21 = j01 * j20 - j00 * j21, c22 = j00 * j11 - j01 * j10; + const det = j00 * c00 + j01 * c10 + j02 * c20; + const inv = 1 / det; + // dN/dx = J^-1 dN/dxi, with J[i][j] = dx_j/dxi_i. + for (let a = 0; a < 10; a++) { + const d0 = dN[a * 3], d1 = dN[a * 3 + 1], d2 = dN[a * 3 + 2]; + g[a * 3] = (c00 * d0 + c01 * d1 + c02 * d2) * inv; + g[a * 3 + 1] = (c10 * d0 + c11 * d1 + c12 * d2) * inv; + g[a * 3 + 2] = (c20 * d0 + c21 * d1 + c22 * d2) * inv; + } + return det; +} + +const grad = new Float64Array(30); + +/** + * Element stiffness (30 x 30, row-major, node-major degrees of freedom) of + * element e: K_ab^ij = int lambda a_i b_j + mu a_j b_i + mu delta_ij (a . b) dV. + * Returns false if the element is inverted. + */ +export function elementStiffness(X: ArrayLike, tets: ArrayLike, e: number, lambda: number, mu: number, K: Float64Array): boolean { + K.fill(0); + for (const [l1, l2, l3, w] of GAUSS4) { + const det = shapeGradients(X, tets, e * 10, l1, l2, l3, grad); + if (!(det > 0)) return false; + const f = det * w; + for (let a = 0; a < 10; a++) { + const ax = grad[a * 3], ay = grad[a * 3 + 1], az = grad[a * 3 + 2]; + for (let b = a; b < 10; b++) { + const bx = grad[b * 3], by = grad[b * 3 + 1], bz = grad[b * 3 + 2]; + const dot = mu * (ax * bx + ay * by + az * bz); + const r = a * 3, c = b * 3; + K[r * 30 + c] += f * (lambda * ax * bx + mu * ax * bx + dot); + K[r * 30 + c + 1] += f * (lambda * ax * by + mu * ay * bx); + K[r * 30 + c + 2] += f * (lambda * ax * bz + mu * az * bx); + K[(r + 1) * 30 + c] += f * (lambda * ay * bx + mu * ax * by); + K[(r + 1) * 30 + c + 1] += f * (lambda * ay * by + mu * ay * by + dot); + K[(r + 1) * 30 + c + 2] += f * (lambda * ay * bz + mu * az * by); + K[(r + 2) * 30 + c] += f * (lambda * az * bx + mu * ax * bz); + K[(r + 2) * 30 + c + 1] += f * (lambda * az * by + mu * ay * bz); + K[(r + 2) * 30 + c + 2] += f * (lambda * az * bz + mu * az * bz + dot); + } + } + } + // Mirror the upper node blocks. + for (let a = 0; a < 10; a++) for (let b = a + 1; b < 10; b++) { + for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) K[(b * 3 + j) * 30 + a * 3 + i] = K[(a * 3 + i) * 30 + b * 3 + j]; + } + return true; +} + +const Nv = new Float64Array(10); + +/** Adds the consistent nodal loads of a body force b (force per volume) on element e to F. Returns the element's volume. */ +export function addBodyForce(X: ArrayLike, tets: ArrayLike, e: number, b: ArrayLike, F: Float64Array): number { + let vol = 0; + for (const [l1, l2, l3, w] of GAUSS4) { + const det = shapeGradients(X, tets, e * 10, l1, l2, l3, grad); + quadShape(l1, l2, l3, Nv); + const f = det * w; + vol += f; + for (let a = 0; a < 10; a++) { + const n = tets[e * 10 + a] * 3; + F[n] += Nv[a] * f * b[0]; F[n + 1] += Nv[a] * f * b[1]; F[n + 2] += Nv[a] * f * b[2]; + } + } + return vol; +} + +// 6-point Gauss rule on the triangle (degree 4): (s, t, weight of the unit triangle, area 1/2). +const TA = 0.445948490915965, TB = 0.091576213509771, WA = 0.223381589678011 / 2, WB = 0.109951743655322 / 2; +const TRI6: [number, number, number][] = [ + [TA, TA, WA], [1 - 2 * TA, TA, WA], [TA, 1 - 2 * TA, WA], + [TB, TB, WB], [1 - 2 * TB, TB, WB], [TB, 1 - 2 * TB, WB], +]; + +/** Shape functions and their s, t derivatives of the 6-node triangle (corners 0-2, then edges 01, 12, 20). */ +function triShape(s: number, t: number, N: Float64Array, Ns: Float64Array, Nt: Float64Array) { + const r = 1 - s - t; + N[0] = r * (2 * r - 1); N[1] = s * (2 * s - 1); N[2] = t * (2 * t - 1); N[3] = 4 * r * s; N[4] = 4 * s * t; N[5] = 4 * t * r; + Ns[0] = 1 - 4 * r; Ns[1] = 4 * s - 1; Ns[2] = 0; Ns[3] = 4 * (r - s); Ns[4] = 4 * t; Ns[5] = -4 * t; + Nt[0] = 1 - 4 * r; Nt[1] = 0; Nt[2] = 4 * t - 1; Nt[3] = -4 * s; Nt[4] = 4 * s; Nt[5] = 4 * (r - t); +} + +const tN = new Float64Array(6), tNs = new Float64Array(6), tNt = new Float64Array(6); + +/** + * Integrates over boundary triangle f (6 nodes): calls fn(node slot, weight N_a dA, n dA) per + * quadrature point and node, with n dA the area-weighted outward normal. Returns its area. + */ +export function integrateTriangle(X: ArrayLike, tris: ArrayLike, f: number, fn?: (a: number, w: number, nx: number, ny: number, nz: number) => void): number { + let area = 0; + for (const [s, t, w] of TRI6) { + triShape(s, t, tN, tNs, tNt); + let sx = 0, sy = 0, sz = 0, tx = 0, ty = 0, tz = 0; + for (let a = 0; a < 6; a++) { + const n = tris[f * 6 + a] * 3; + sx += tNs[a] * X[n]; sy += tNs[a] * X[n + 1]; sz += tNs[a] * X[n + 2]; + tx += tNt[a] * X[n]; ty += tNt[a] * X[n + 1]; tz += tNt[a] * X[n + 2]; + } + const nx = (sy * tz - sz * ty) * w, ny = (sz * tx - sx * tz) * w, nz = (sx * ty - sy * tx) * w; + const dA = Math.hypot(nx, ny, nz); + area += dA; + if (fn) for (let a = 0; a < 6; a++) fn(a, tN[a] * dA, tN[a] * nx, tN[a] * ny, tN[a] * nz); + } + return area; +} + +/** Natural coordinates of the 10 nodes of the tetrahedron (L1, L2, L3). */ +export const TET_NODES: [number, number, number][] = [ + [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], [0.5, 0, 0], [0.5, 0.5, 0], [0, 0.5, 0], [0, 0, 0.5], [0.5, 0, 0.5], [0, 0.5, 0.5], +]; + +/** + * Strain (xx, yy, zz, xy, yz, zx as tensor components) at each node of element e from + * the displacements U; 60 values (6 per node). + */ +export function elementNodeStrains(X: ArrayLike, tets: ArrayLike, e: number, U: ArrayLike, out: Float64Array) { + for (let k = 0; k < 10; k++) { + const [l1, l2, l3] = TET_NODES[k]; + shapeGradients(X, tets, e * 10, l1, l2, l3, grad); + let uxx = 0, uxy = 0, uxz = 0, uyx = 0, uyy = 0, uyz = 0, uzx = 0, uzy = 0, uzz = 0; + for (let a = 0; a < 10; a++) { + const n = tets[e * 10 + a] * 3; + const gx = grad[a * 3], gy = grad[a * 3 + 1], gz = grad[a * 3 + 2]; + const ux = U[n], uy = U[n + 1], uz = U[n + 2]; + uxx += ux * gx; uxy += ux * gy; uxz += ux * gz; + uyx += uy * gx; uyy += uy * gy; uyz += uy * gz; + uzx += uz * gx; uzy += uz * gy; uzz += uz * gz; + } + const o = k * 6; + out[o] = uxx; out[o + 1] = uyy; out[o + 2] = uzz; + out[o + 3] = (uxy + uyx) / 2; out[o + 4] = (uyz + uzy) / 2; out[o + 5] = (uzx + uxz) / 2; + } +} + +/** Eigenvalues of a symmetric 3 x 3 tensor (xx, yy, zz, xy, yz, zx), largest first. */ +export function principal(xx: number, yy: number, zz: number, xy: number, yz: number, zx: number): [number, number, number] { + const p1 = xy * xy + yz * yz + zx * zx; + const q = (xx + yy + zz) / 3; + if (p1 <= 1e-30 * (xx * xx + yy * yy + zz * zz + 1e-300)) { + const v = [xx, yy, zz].sort((a, b) => b - a); + return [v[0], v[1], v[2]]; + } + const p2 = (xx - q) ** 2 + (yy - q) ** 2 + (zz - q) ** 2 + 2 * p1; + const p = Math.sqrt(p2 / 6); + const bxx = (xx - q) / p, byy = (yy - q) / p, bzz = (zz - q) / p, bxy = xy / p, byz = yz / p, bzx = zx / p; + const detB = bxx * (byy * bzz - byz * byz) - bxy * (bxy * bzz - byz * bzx) + bzx * (bxy * byz - byy * bzx); + const r = Math.max(-1, Math.min(1, detB / 2)); + const phi = Math.acos(r) / 3; + const e1 = q + 2 * p * Math.cos(phi); + const e3 = q + 2 * p * Math.cos(phi + (2 * Math.PI) / 3); + return [e1, 3 * q - e1 - e3, e3]; +} diff --git a/src/parametric/src/fea/mesher.ts b/src/parametric/src/fea/mesher.ts new file mode 100644 index 000000000..11c2837c2 --- /dev/null +++ b/src/parametric/src/fea/mesher.ts @@ -0,0 +1,950 @@ +// Volume mesher: 10-node tetrahedra filling the part. +// +// 1. Isosurface stuffing (after Labelle and Shewchuk, 2007): a body-centred +// cubic lattice is laid over the part; lattice points are classified inside +// or outside by exact ray crossing counts, lattice edges that cross the +// boundary are cut where they cross it, lattice points close to a cut are +// moved onto it ("warped"), and every lattice tetrahedron is clipped to the +// part with fixed stencils. Quadrilaterals shared by neighbours are split +// through their lowest numbered corner, so neighbours always agree. +// 2. Feature recovery: the stuffed boundary passes through the part's +// surface but cuts across its edges and corners. Mesh vertices are moved +// onto the corners and then onto the edges between faces, so that every +// boundary triangle lies on one B-rep face (faces carrying loads and +// fixtures are covered exactly). Moves that would spoil a tetrahedron are +// refused. +// 3. Interior vertices are smoothed where that improves the worst element +// around them. +// 4. Quadratic nodes are added at edge midpoints; those on the boundary are +// put on the curved surface (or on the edge between two faces). +// +// The lattice is uniform: features thinner than about the element size are +// meshed coarsely or missed, which the volume check reports. + +import { SurfaceIndex } from './surface'; + +export interface MeshOptions { + /** Target element size (lattice spacing), mm. */ + size: number; + progress?: (stage: string, fraction: number) => void; + /** Development: logs statistics after each stage. */ + debug?: (msg: string) => void; +} + +export interface TetMesh { + /** xyz of every node: corner nodes first, then midside nodes. */ + nodes: Float64Array; + /** Number of corner nodes. */ + corners: number; + /** 10 nodes per element: corners 0-3, then midside nodes of edges 01, 12, 20, 03, 13, 23. */ + tets: Int32Array; + /** 6 nodes per boundary triangle: corners, then midside nodes of edges 01, 12, 20 (outward normal by the right hand rule). */ + tris: Int32Array; + /** B-rep face of each boundary triangle. */ + triFace: Int32Array; + stats: MeshStats; +} + +export interface MeshStats { + size: number; + nodes: number; + elements: number; + /** Volume of the mesh and of the boundary it was made from (mm^3). */ + volume: number; + surfaceVolume: number; + /** Mean ratio quality (1 regular, 0 flat): worst and average. */ + minQuality: number; + meanQuality: number; + /** Smallest and largest dihedral angle of the corner tetrahedra (degrees). */ + minDihedral: number; + maxDihedral: number; + /** Elements whose quadratic shape had to be straightened (their surface stays flat). */ + straightened: number; + /** Boundary triangles whose face could not be told from their corners. */ + unassigned: number; + /** Separate pieces of mesh. */ + pieces: number; +} + +const ALPHA_LONG = 0.24917; +const ALPHA_SHORT = 0.41189; + +/** Edges of a 10-node tetrahedron (corner pairs), in midside node order. */ +export const TET_EDGES: [number, number][] = [[0, 1], [1, 2], [2, 0], [0, 3], [1, 3], [2, 3]]; + +export class MeshError extends Error { + /** thin: the elements were too large for the part's walls (a finer mesh may work). */ + constructor(message: string, readonly thin = false) { + super(message); + } +} + +export function tetVolume(P: ArrayLike, a: number, b: number, c: number, d: number): number { + const ax = P[a * 3], ay = P[a * 3 + 1], az = P[a * 3 + 2]; + const bx = P[b * 3] - ax, by = P[b * 3 + 1] - ay, bz = P[b * 3 + 2] - az; + const cx = P[c * 3] - ax, cy = P[c * 3 + 1] - ay, cz = P[c * 3 + 2] - az; + const dx = P[d * 3] - ax, dy = P[d * 3 + 1] - ay, dz = P[d * 3 + 2] - az; + return (bx * (cy * dz - cz * dy) - by * (cx * dz - cz * dx) + bz * (cx * dy - cy * dx)) / 6; +} + +/** Mean ratio quality of a tetrahedron: 1 for a regular one, 0 (or negative) for flat (inverted) ones. */ +export function tetQuality(P: ArrayLike, a: number, b: number, c: number, d: number): number { + const v = tetVolume(P, a, b, c, d); + const l2 = (i: number, j: number) => (P[i * 3] - P[j * 3]) ** 2 + (P[i * 3 + 1] - P[j * 3 + 1]) ** 2 + (P[i * 3 + 2] - P[j * 3 + 2]) ** 2; + const s = l2(a, b) + l2(a, c) + l2(a, d) + l2(b, c) + l2(b, d) + l2(c, d); + if (!(s > 0)) return 0; + return (12 * Math.sign(v) * Math.cbrt(9 * v * v)) / s; +} + +function dihedrals(P: ArrayLike, n: number[]): number[] { + const p = (i: number) => [P[n[i] * 3], P[n[i] * 3 + 1], P[n[i] * 3 + 2]]; + const sub = (a: number[], b: number[]) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; + const cr = (a: number[], b: number[]) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + const out: number[] = []; + for (const [i, j] of TET_EDGES) { + const [k, l] = [0, 1, 2, 3].filter((q) => q !== i && q !== j); + const e = sub(p(j), p(i)); + const n1 = cr(e, sub(p(k), p(i))), n2 = cr(e, sub(p(l), p(i))); + const c = (n1[0] * n2[0] + n1[1] * n2[1] + n1[2] * n2[2]) / (Math.hypot(...n1) * Math.hypot(...n2) || 1); + out.push((Math.acos(Math.max(-1, Math.min(1, c))) * 180) / Math.PI); + } + return out; +} + +/** + * Unknowns a part may be solved with: about 2 GB at the peak in the browser's worker and 20 s (measured: + * 961k unknowns, 2.4 GB, 21 s; 2.1M took 4.3 GB). Finer meshes are not offered. + */ +export const MAX_DOFS = 1_000_000; + +/** Default element size for a part: fine enough for its walls, bounded so the problem stays solvable in a browser. */ +export function defaultElementSize(volume: number, area: number, diag: number): number { + // 2V/A is the thickness of a plate (and a third of a cube's side). + const wall = area > 0 ? (2 * volume) / area : diag / 10; + const h = Math.min(diag / 25, wall / 1.5); + // Keep the default near 150k unknowns. + let floor = Math.cbrt(Math.max(volume, 1e-9) / 2300); + // Thin walls (a plate, sheet metal): a solid mesh needs elements no thicker than the walls, as many as that + // takes (up to the most a browser can solve). + if (floor > wall) floor = Math.max(wall, sizeForDofs(volume, area, MAX_DOFS)); + return Math.max(h, floor, diag / 400); +} + +/** Largest element size that still meshes the part's walls (about their thickness). */ +export function maxElementSize(volume: number, area: number, diag: number): number { + const wall = area > 0 ? (2 * volume) / area : diag / 10; + return Math.max(wall, defaultElementSize(volume, area, diag)); +} + +/** Smallest element size offered: no more than about MAX_DOFS unknowns (nor larger than the default). */ +export function minElementSize(volume: number, area: number, diag: number): number { + return Math.min(defaultElementSize(volume, area, diag), sizeForDofs(volume, area, MAX_DOFS)); +} + +/** + * Estimated degrees of freedom of a mesh of the given element size: a part of the volume and a part of the + * surface (the elements cut at the boundary), fitted to meshes of a cube, a bracket and a 1.5 mm plate (within 3%). + */ +export function estimateDofs(volume: number, size: number, area = 0): number { + return Math.round((47.3 * volume) / size ** 3 + (20.9 * area) / size ** 2); +} + +/** Element size whose mesh has about `dofs` degrees of freedom (see estimateDofs). */ +export function sizeForDofs(volume: number, area: number, dofs: number): number { + const V = Math.max(volume, 1e-9), A = Math.max(area, 0); + let lo = Math.cbrt((47.3 * V) / dofs), hi = 2 * (lo + Math.sqrt((20.9 * A) / dofs)); + for (let i = 0; i < 60; i++) { const m = (lo + hi) / 2; if (estimateDofs(V, m, A) > dofs) lo = m; else hi = m; } + return hi; +} + +/** + * Meshes at the element size asked for or, where the part's walls are thinner than that, at the largest + * size down to `min` (in steps of 1.25) that meshes them; the mesh's stats give the size used. + */ +export function meshWalls(surf: SurfaceIndex, opts: MeshOptions & { min: number }): TetMesh { + for (let size = opts.size; ; size = Math.max(opts.min, size / 1.25)) { + try { + return meshSolid(surf, { ...opts, size }); + } catch (e) { + if (!(e instanceof MeshError) || !e.thin) throw e; + if (size <= opts.min * 1.001) { + throw new MeshError(`${e.message.replace(/ Choose a finer mesh\.$/, '')} Elements small enough for those walls would make more unknowns than a browser can solve.`, true); + } + } + } +} + +export function meshSolid(surf: SurfaceIndex, opts: MeshOptions): TetMesh { + const h = opts.size; + const progress = opts.progress ?? (() => {}); + if (!(h > 0) || !surf.nt) throw new MeshError('The part has no solid to mesh.'); + const ext = [0, 1, 2].map((d) => surf.max[d] - surf.min[d]); + // Lattice origin a cell and an odd fraction outside the part: no lattice point lands exactly on a flat face. + const frac = [0.1374, 0.2653, 0.3917]; + const o = [0, 1, 2].map((d) => surf.min[d] - h * (1 + frac[d])); + const n = [0, 1, 2].map((d) => Math.ceil((ext[d] + 2 * h) / h) + 1); + const [nx, ny, nz] = n; + const NB = (nx + 1) * (ny + 1) * (nz + 1); + const NR = nx * ny * nz; + const NV = NB + NR; + if (NV > 60e6) throw new MeshError('The elements are too small for this part. Choose a coarser mesh.'); + const bId = (i: number, j: number, k: number) => i + (nx + 1) * (j + (ny + 1) * k); + const rId = (i: number, j: number, k: number) => NB + i + nx * (j + ny * k); + const latticePos = (v: number, out: number[]) => { + if (v < NB) { + const i = v % (nx + 1), r = (v - i) / (nx + 1), j = r % (ny + 1), k = (r - j) / (ny + 1); + out[0] = o[0] + i * h; out[1] = o[1] + j * h; out[2] = o[2] + k * h; + } else { + const w = v - NB, i = w % nx, r = (w - i) / nx, j = r % ny, k = (r - j) / ny; + out[0] = o[0] + (i + 0.5) * h; out[1] = o[1] + (j + 0.5) * h; out[2] = o[2] + (k + 0.5) * h; + } + return out; + }; + + // ---- classify lattice points ---- + progress('Classifying lattice points', 0); + const sign = new Int8Array(NV).fill(-1); + const scan = (yz: (j: number, k: number) => [number, number], count: number, xAt: (i: number) => number, id: (i: number, j: number, k: number) => number, nj: number, nk: number) => { + for (let k = 0; k < nk; k++) { + for (let j = 0; j < nj; j++) { + const [y, z] = yz(j, k); + const { x } = surf.xCrossings(y, z); + if (!x.length) continue; + // Points before the first crossing are outside; each crossing flips. + let c = 0; + for (let i = 0; i < count; i++) { + const xi = xAt(i); + while (c < x.length && x[c] <= xi) c++; + if (c & 1) sign[id(i, j, k)] = 1; + } + } + } + }; + scan((j, k) => [o[1] + j * h, o[2] + k * h], nx + 1, (i) => o[0] + i * h, bId, ny + 1, nz + 1); + scan((j, k) => [o[1] + (j + 0.5) * h, o[2] + (k + 0.5) * h], nx, (i) => o[0] + (i + 0.5) * h, rId, ny, nz); + + // ---- neighbours of a lattice point: [vertex, long edge?] ---- + const neighbours = (v: number, out: number[]): number => { + let m = 0; + if (v < NB) { + const i = v % (nx + 1), r = (v - i) / (nx + 1), j = r % (ny + 1), k = (r - j) / (ny + 1); + if (i > 0) out[m++] = bId(i - 1, j, k); + if (i < nx) out[m++] = bId(i + 1, j, k); + if (j > 0) out[m++] = bId(i, j - 1, k); + if (j < ny) out[m++] = bId(i, j + 1, k); + if (k > 0) out[m++] = bId(i, j, k - 1); + if (k < nz) out[m++] = bId(i, j, k + 1); + const long = m; + for (let c = 0; c < 8; c++) { + const a = i - 1 + (c & 1), b = j - 1 + ((c >> 1) & 1), d = k - 1 + ((c >> 2) & 1); + if (a >= 0 && b >= 0 && d >= 0 && a < nx && b < ny && d < nz) out[m++] = rId(a, b, d); + } + return m * 16 + long; + } + const w = v - NB, i = w % nx, r = (w - i) / nx, j = r % ny, k = (r - j) / ny; + if (i > 0) out[m++] = rId(i - 1, j, k); + if (i < nx - 1) out[m++] = rId(i + 1, j, k); + if (j > 0) out[m++] = rId(i, j - 1, k); + if (j < ny - 1) out[m++] = rId(i, j + 1, k); + if (k > 0) out[m++] = rId(i, j, k - 1); + if (k < nz - 1) out[m++] = rId(i, j, k + 1); + const long = m; + for (let c = 0; c < 8; c++) out[m++] = bId(i + (c & 1), j + ((c >> 1) & 1), k + ((c >> 2) & 1)); + return m * 16 + long; + }; + + // ---- cut points ---- + progress('Cutting the lattice', 0.15); + const ekey = (a: number, b: number) => (a < b ? a * NV + b : b * NV + a); + const cutIndex = new Map(); + const cutPos: number[] = []; + const cutTri: number[] = []; + const nb: number[] = new Array(14); + const pa = [0, 0, 0], pb = [0, 0, 0]; + for (let v = 0; v < NV; v++) { + if (sign[v] !== 1) continue; + const m = neighbours(v, nb) >> 4; + latticePos(v, pa); + for (let q = 0; q < m; q++) { + const w = nb[q]; + if (sign[w] !== -1) continue; + latticePos(w, pb); + const hit = surf.segmentHit(pa, pb); + let p: number[], tri: number; + if (hit) { + p = [pa[0] + (pb[0] - pa[0]) * hit.t, pa[1] + (pb[1] - pa[1]) * hit.t, pa[2] + (pb[2] - pa[2]) * hit.t]; + tri = hit.tri; + } else { + // A crossing too close to a triangle edge for the segment test: the nearest boundary point to the edge's middle. + const mid = [(pa[0] + pb[0]) / 2, (pa[1] + pb[1]) / 2, (pa[2] + pb[2]) / 2]; + const c = surf.closest(mid, h * 2); + if (!c) { p = mid; tri = -1; } else { + const dx = pb[0] - pa[0], dy = pb[1] - pa[1], dz = pb[2] - pa[2]; + const t = Math.max(0.05, Math.min(0.95, ((c.p[0] - pa[0]) * dx + (c.p[1] - pa[1]) * dy + (c.p[2] - pa[2]) * dz) / (dx * dx + dy * dy + dz * dz))); + p = [pa[0] + dx * t, pa[1] + dy * t, pa[2] + dz * t]; + tri = c.tri; + } + } + cutIndex.set(ekey(v, w), cutTri.length); + cutPos.push(p[0], p[1], p[2]); + cutTri.push(tri); + } + } + + // ---- warp lattice points onto cuts close to them ---- + progress('Warping', 0.3); + const warped = new Map(); + const candidates = new Set(); + for (const k of cutIndex.keys()) { const a = Math.floor(k / NV); candidates.add(a); candidates.add(k - a * NV); } + for (const v of [...candidates].sort((a, b) => a - b)) { + const meta = neighbours(v, nb); + const m = meta >> 4, long = meta & 15; + latticePos(v, pa); + let best = -1, bd = Infinity; + for (let q = 0; q < m; q++) { + const ci = cutIndex.get(ekey(v, nb[q])); + if (ci === undefined) continue; + latticePos(nb[q], pb); + const L = Math.hypot(pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]); + const d = Math.hypot(cutPos[ci * 3] - pa[0], cutPos[ci * 3 + 1] - pa[1], cutPos[ci * 3 + 2] - pa[2]); + if (d < (q < long ? ALPHA_LONG : ALPHA_SHORT) * L && d < bd) { bd = d; best = ci; } + } + if (best < 0) continue; + warped.set(v, { p: [cutPos[best * 3], cutPos[best * 3 + 1], cutPos[best * 3 + 2]], tri: cutTri[best] }); + sign[v] = 0; + for (let q = 0; q < m; q++) cutIndex.delete(ekey(v, nb[q])); + } + + // ---- stuff the lattice tetrahedra ---- + progress('Filling', 0.4); + // Node references: lattice points (< NV), cut points (NV + cut), Steiner points (NV + cuts + s). + const NC = cutTri.length; + const steiner: number[] = []; + const out: number[] = []; + let coned = 0; + const refPos = (r: number, dst: number[], at: number) => { + if (r < NV) { + const w = warped.get(r); + if (w) { dst[at] = w.p[0]; dst[at + 1] = w.p[1]; dst[at + 2] = w.p[2]; return; } + latticePos(r, pa); + dst[at] = pa[0]; dst[at + 1] = pa[1]; dst[at + 2] = pa[2]; + } else if (r < NV + NC) { + const c = r - NV; + dst[at] = cutPos[c * 3]; dst[at + 1] = cutPos[c * 3 + 1]; dst[at + 2] = cutPos[c * 3 + 2]; + } else { + const s = r - NV - NC; + dst[at] = steiner[s * 3]; dst[at + 1] = steiner[s * 3 + 1]; dst[at + 2] = steiner[s * 3 + 2]; + } + }; + const tmp = new Array(12).fill(0); + const vol4 = (a: number, b: number, c: number, d: number) => { + refPos(a, tmp, 0); refPos(b, tmp, 3); refPos(c, tmp, 6); refPos(d, tmp, 9); + return tetVolume(tmp, 0, 1, 2, 3); + }; + const cut = (p: number, m: number) => { + const c = cutIndex.get(ekey(p, m)); + if (c === undefined) throw new MeshError('The mesher lost a boundary crossing.'); + return NV + c; + }; + /** Emits sub-tetrahedra of one convex piece; they must all have one orientation, else the piece is coned from its centroid. */ + const emit = (tets: number[][], faces: number[][] | null) => { + const vols = tets.map((t) => vol4(t[0], t[1], t[2], t[3])); + const scale = Math.max(...vols.map(Math.abs)); + const pos = vols.every((v) => v > 1e-9 * scale), neg = vols.every((v) => v < -1e-9 * scale); + if (pos || neg || !faces) { + tets.forEach((t, i) => { if (vols[i] < 0) out.push(t[0], t[2], t[1], t[3]); else if (vols[i] > 0) out.push(t[0], t[1], t[2], t[3]); }); + return; + } + // Cone the faces from the centroid of the piece's corners. + const corners = [...new Set(faces.flat())]; + const c = [0, 0, 0]; + for (const r of corners) { refPos(r, tmp, 0); c[0] += tmp[0]; c[1] += tmp[1]; c[2] += tmp[2]; } + const s = NV + NC + steiner.length / 3; + steiner.push(c[0] / corners.length, c[1] / corners.length, c[2] / corners.length); + const cone = faces.map((f) => [f[0], f[1], f[2], s]); + const cv = cone.map((t) => vol4(t[0], t[1], t[2], t[3])); + coned++; + cone.forEach((t, i) => { if (cv[i] < 0) out.push(t[0], t[2], t[1], t[3]); else if (cv[i] > 0) out.push(t[0], t[1], t[2], t[3]); }); + }; + /** A quadrilateral (cyclic) as two triangles split through its lowest reference. */ + const quad = (q: number[]): number[][] => { + const m = q.indexOf(Math.min(...q)); + return m % 2 === 0 ? [[q[0], q[1], q[2]], [q[0], q[2], q[3]]] : [[q[1], q[2], q[3]], [q[1], q[3], q[0]]]; + }; + const prism = (a: number, b: number, c: number, d: number, e: number, f: number) => { + // Rotate and turn over until the lowest reference is a (Dompierre et al. 1999). + let P = [a, b, c, d, e, f]; + const m = P.indexOf(Math.min(...P)); + if (m >= 3) P = [P[3], P[4], P[5], P[0], P[1], P[2]]; + const r = m % 3; + P = [P[r], P[(r + 1) % 3], P[(r + 2) % 3], P[3 + r], P[3 + (r + 1) % 3], P[3 + (r + 2) % 3]]; + const [A, B, C, D, E, F] = P; + const tets = Math.min(B, F) < Math.min(C, E) ? [[A, B, C, F], [A, B, F, E], [A, E, F, D]] : [[A, B, C, E], [A, E, C, F], [A, E, F, D]]; + const faces = [[A, B, C], [D, E, F], ...quad([A, B, E, D]), ...quad([B, C, F, E]), ...quad([C, A, D, F])]; + emit(tets, faces); + }; + const pyramid = (q: number[], apex: number) => { + const base = quad(q); + emit(base.map((t) => [t[0], t[1], t[2], apex]), [...base, [q[0], q[1], apex], [q[1], q[2], apex], [q[2], q[3], apex], [q[3], q[0], apex]]); + }; + const centroid = [0, 0, 0]; + const stuff = (t: number[]) => { + const P: number[] = [], Z: number[] = [], M: number[] = []; + for (const v of t) (sign[v] > 0 ? P : sign[v] < 0 ? M : Z).push(v); + if (!P.length) { + if (Z.length !== 4) return; + // Four boundary points: inside if its middle is. + centroid[0] = centroid[1] = centroid[2] = 0; + for (const v of t) { refPos(v, tmp, 0); centroid[0] += tmp[0] / 4; centroid[1] += tmp[1] / 4; centroid[2] += tmp[2] / 4; } + if (surf.inside(centroid)) emit([t], null); + return; + } + if (!M.length) { emit([t], null); return; } + if (P.length === 1) { + const p = P[0]; + if (M.length === 3) emit([[p, cut(p, M[0]), cut(p, M[1]), cut(p, M[2])]], null); + else if (M.length === 2) emit([[p, Z[0], cut(p, M[0]), cut(p, M[1])]], null); + else emit([[p, Z[0], Z[1], cut(p, M[0])]], null); + } else if (P.length === 2) { + const [p0, p1] = P; + if (M.length === 2) prism(p0, cut(p0, M[0]), cut(p0, M[1]), p1, cut(p1, M[0]), cut(p1, M[1])); + else pyramid([p0, p1, cut(p1, M[0]), cut(p0, M[0])], Z[0]); + } else { + const m = M[0]; + prism(P[0], P[1], P[2], cut(P[0], m), cut(P[1], m), cut(P[2], m)); + } + }; + const four = [0, 0, 0, 0]; + const cells = [[0, 0], [-1, 0], [-1, -1], [0, -1]]; + for (let d = 0; d < 3; d++) { + const d1 = (d + 1) % 3, d2 = (d + 2) % 3; + const lim = [nx, ny, nz]; + for (let k = 0; k <= nz; k++) for (let j = 0; j <= ny; j++) for (let i = 0; i <= nx; i++) { + const idx = [i, j, k]; + if (idx[d] >= lim[d]) continue; + const b0 = bId(i, j, k); + const e = [i, j, k]; e[d]++; + const b1 = bId(e[0], e[1], e[2]); + const r: number[] = []; + for (const [a, b] of cells) { + const c = [i, j, k]; c[d1] += a; c[d2] += b; + if (c[0] < 0 || c[1] < 0 || c[2] < 0 || c[0] >= nx || c[1] >= ny || c[2] >= nz) break; + r.push(rId(c[0], c[1], c[2])); + } + if (r.length < 4) continue; + if (sign[b0] < 0 && sign[b1] < 0 && r.every((v) => sign[v] < 0)) continue; + for (let q = 0; q < 4; q++) { + four[0] = b0; four[1] = b1; four[2] = r[q]; four[3] = r[(q + 1) % 4]; + stuff(four); + } + } + } + if (!out.length) throw new MeshError('The mesh is empty: the elements are too large for this part. Choose a finer mesh.', true); + + // ---- compact the nodes ---- + progress('Recovering edges', 0.55); + const refMap = new Map(); + const tets = new Int32Array(out.length); + const posList: number[] = []; + const triOf: number[] = []; + for (let q = 0; q < out.length; q++) { + const r = out[q]; + let id = refMap.get(r); + if (id === undefined) { + id = triOf.length; + refMap.set(r, id); + refPos(r, tmp, 0); + posList.push(tmp[0], tmp[1], tmp[2]); + triOf.push(r < NV ? (warped.get(r)?.tri ?? -1) : r < NV + NC ? cutTri[r - NV] : -1); + } + tets[q] = id; + } + const W = new WorkMesh(posList, Array.from(tets), h); + const qstat = (label: string) => { + if (!opts.debug) return; + let mq = Infinity, bad = 0; + for (let t = 0; t < W.nt; t++) { const q = W.quality(t); mq = Math.min(mq, q); if (q < 0.2) bad++; } + opts.debug(`${label}: min quality ${mq.toFixed(3)}, below 0.2: ${bad} of ${W.nt}, coned ${coned}, nodes ${W.nn}`); + }; + qstat('stuffed'); + { + const bt = boundaryOf(W.typed()); + for (const v of bt.tris) W.onB[v] = 1; + } + // Labels: the faces a boundary vertex is on. + for (let v = 0; v < W.nn; v++) { + if (!W.onB[v]) continue; + if (triOf[v] >= 0) { W.labels[v] = [surf.face[triOf[v]]]; continue; } + const c = surf.closest(W.pos(v), h); + W.labels[v] = c ? [surf.face[c.tri]] : []; + } + + // ---- corners ---- + const bverts: number[] = []; + for (let v = 0; v < W.nn; v++) if (W.onB[v]) bverts.push(v); + const vgrid = new PointGrid(W.P, bverts, h); + for (const c of surf.corners) { + const cp = surf.vertex(c.v); + const near = vgrid.near(cp, h * 0.9).filter((v) => !W.locked[v] && W.labels[v].some((f) => c.faces.includes(f))); + near.sort((a, b) => dist2(W.P, a, cp) - dist2(W.P, b, cp)); + for (const v of near.slice(0, 4)) { + if (W.move(v, cp, 0.1)) { W.locked[v] = 1; W.labels[v] = [...c.faces]; break; } + } + } + + // ---- edges between faces ---- + const disjoint = (a: number[], b: number[]) => !a.some((x) => b.includes(x)); + /** Faces a, b of two vertices' labels that meet along an edge of the part. */ + const seamOf = (u: number, w: number): [number, number] | null => { + for (const fa of W.labels[u]) for (const fb of W.labels[w]) if (fa >= 0 && fb >= 0 && fa !== fb && surf.adjacent(fa, fb)) return [fa, fb]; + return null; + }; + let lastEdges = Infinity; + for (let pass = 0; pass < 6; pass++) { + const edges: { u: number; w: number; a: number; b: number; d2: number }[] = []; + forBoundaryEdges(boundaryOf(W.typed()).tris, (u, w) => { + if (!disjoint(W.labels[u], W.labels[w])) return; + const s = seamOf(u, w); + if (!s) return; + const m = [(W.P[u * 3] + W.P[w * 3]) / 2, (W.P[u * 3 + 1] + W.P[w * 3 + 1]) / 2, (W.P[u * 3 + 2] + W.P[w * 3 + 2]) / 2]; + const q = surf.closestOnSeam(s[0], s[1], m); + if (q && q.d2 < h * h) edges.push({ u, w, a: s[0], b: s[1], d2: q.d2 }); + }); + if (!edges.length) break; + // No fewer crossings than the last pass (moves refused, splits making new ones): more passes would only + // split and squash elements (slivers of quality 0.01 on a coarse bracket), so stop. + if (edges.length >= lastEdges) break; + lastEdges = edges.length; + edges.sort((p, q) => p.d2 - q.d2); + let moved = 0, split = 0, refused = 0; + for (const e of edges) { + const { u, w, a, b } = e; + // Still a crossing edge (an earlier move may have settled it)? + if (!disjoint(W.labels[u], W.labels[w]) || !W.hasEdge(u, w)) continue; + // Move the end nearer the seam onto it, else the other end. + const ends = [u, w].filter((v) => !W.locked[v]).map((v) => ({ v, q: surf.closestOnSeam(a, b, W.pos(v))! })).filter((x) => x.q && x.q.d2 < h * h).sort((p, q) => p.q.d2 - q.q.d2); + let done = false; + for (const x of ends) { + if (W.move(x.v, x.q.p, 0.12)) { W.locked[x.v] = 1; W.labels[x.v] = [a, b]; moved++; done = true; break; } + } + if (done) continue; + // Neither end can go: split the edge and put the new vertex on the seam. + const m = [(W.P[u * 3] + W.P[w * 3]) / 2, (W.P[u * 3 + 1] + W.P[w * 3 + 1]) / 2, (W.P[u * 3 + 2] + W.P[w * 3 + 2]) / 2]; + const q = surf.closestOnSeam(a, b, m); + if (!q) continue; + const x = W.split(u, w); + W.onB[x] = 1; + if (W.move(x, q.p, 0.05)) { W.locked[x] = 1; W.labels[x] = [a, b]; split++; continue; } + // Partly there is still better than across the corner. + const half = [(m[0] + q.p[0]) / 2, (m[1] + q.p[1]) / 2, (m[2] + q.p[2]) / 2]; + W.move(x, half, 0.05); + const c = surf.closest(W.pos(x), h, new Set([a, b])); + W.labels[x] = c ? [surf.face[c.tri]] : [a]; + refused++; + } + opts.debug?.(`pass ${pass}: ${edges.length} crossing edges, ${moved} moved, ${split} split, ${refused} left`); + if (!moved && !split) break; + } + + qstat('snapped'); + if (opts.debug) { + let open = 0; + forBoundaryEdges(boundaryOf(W.typed()).tris, (u, w) => { if (disjoint(W.labels[u], W.labels[w])) open++; }); + opts.debug(`crossing edges left: ${open}`); + } + // ---- smooth interior vertices ---- + progress('Improving elements', 0.65); + W.smooth(4); + qstat('smoothed'); + + // Elements that ended up flat are dropped. + const ideal = (h ** 3) / 12; + const lin = W.typed(); + const P = lin.P, nn = lin.nn, labels = W.labels; + const keep: number[] = []; + for (let t = 0; t < lin.nt; t++) if (tetVolume(P, lin.tets[t * 4], lin.tets[t * 4 + 1], lin.tets[t * 4 + 2], lin.tets[t * 4 + 3]) > 1e-9 * ideal) keep.push(t); + let T4 = lin.tets; + if (keep.length < lin.nt) { + T4 = new Int32Array(keep.length * 4); + keep.forEach((t, i) => T4.set(lin.tets.subarray(t * 4, t * 4 + 4), i * 4)); + } + const bnd = boundaryOf({ P, tets: T4, nn, nt: T4.length / 4 }); + const NT = T4.length / 4; + + // ---- faces of boundary triangles ---- + const B = bnd.tris; + const nb3 = B.length / 3; + const triFace = new Int32Array(nb3).fill(-1); + let unassigned = 0; + for (let f = 0; f < nb3; f++) { + const a = B[f * 3], b = B[f * 3 + 1], c = B[f * 3 + 2]; + for (const v of [a, b, c]) if (!labels[v].length) { const q = surf.closest([P[v * 3], P[v * 3 + 1], P[v * 3 + 2]], h * 2); labels[v] = q ? [surf.face[q.tri]] : [-1]; } + const common = labels[a].filter((x) => x >= 0 && labels[b].includes(x) && labels[c].includes(x)); + if (common.length === 1) { triFace[f] = common[0]; continue; } + const cen = [(P[a * 3] + P[b * 3] + P[c * 3]) / 3, (P[a * 3 + 1] + P[b * 3 + 1] + P[c * 3 + 1]) / 3, (P[a * 3 + 2] + P[b * 3 + 2] + P[c * 3 + 2]) / 3]; + const q = surf.closest(cen, h * 2, common.length ? new Set(common) : null) ?? surf.closest(cen, h * 4); + triFace[f] = q ? surf.face[q.tri] : -1; + if (!common.length) unassigned++; + } + + // ---- quadratic nodes ---- + progress('Adding midside nodes', 0.75); + const edgeMap = new Map(); + const mid: number[] = []; + const T10 = new Int32Array(NT * 10); + const eKey = (a: number, b: number) => (a < b ? a * nn + b : b * nn + a); + for (let t = 0; t < NT; t++) { + for (let k = 0; k < 4; k++) T10[t * 10 + k] = T4[t * 4 + k]; + TET_EDGES.forEach(([i, j], e) => { + const a = T4[t * 4 + i], b = T4[t * 4 + j]; + const key = eKey(a, b); + let m = edgeMap.get(key); + if (m === undefined) { + m = nn + mid.length / 3; + edgeMap.set(key, m); + mid.push((P[a * 3] + P[b * 3]) / 2, (P[a * 3 + 1] + P[b * 3 + 1]) / 2, (P[a * 3 + 2] + P[b * 3 + 2]) / 2); + } + T10[t * 10 + 4 + e] = m; + }); + } + const N = new Float64Array(P.length + mid.length); + N.set(P); + N.set(mid, P.length); + const straight = new Float64Array(mid); + // Boundary midside nodes onto the curved surface: the faces of the triangles beside the edge. + const edgeFaces = new Map(); + for (let f = 0; f < nb3; f++) { + for (const [i, j] of [[0, 1], [1, 2], [2, 0]]) { + const key = eKey(B[f * 3 + i], B[f * 3 + j]); + let l = edgeFaces.get(key); + if (!l) edgeFaces.set(key, (l = [])); + if (triFace[f] >= 0 && !l.includes(triFace[f])) l.push(triFace[f]); + } + } + const movedMid: number[] = []; + for (const [key, faces] of edgeFaces) { + const m = edgeMap.get(key); + if (m === undefined || !faces.length) continue; + const a = Math.floor(key / nn), b = key - a * nn; + const p = [N[m * 3], N[m * 3 + 1], N[m * 3 + 2]]; + const len = Math.sqrt(dist2(N, a, [N[b * 3], N[b * 3 + 1], N[b * 3 + 2]])); + let q: number[] | null = null; + // An edge along the seam of two faces stays on the seam (both its ends are on it). + const seam = faces.length === 2 ? faces : []; + if (seam.length === 2 && labels[a].includes(seam[0]) && labels[a].includes(seam[1]) && labels[b].includes(seam[0]) && labels[b].includes(seam[1])) { + const s = surf.closestOnSeam(seam[0], seam[1], p); + if (s && s.d2 < (len * 0.5) ** 2) q = s.p; + } + if (!q && faces.length === 1) { + const c = surf.closest(p, len * 0.5, new Set(faces)); + if (c) q = c.p; + } + if (!q) continue; + N[m * 3] = q[0]; N[m * 3 + 1] = q[1]; N[m * 3 + 2] = q[2]; + movedMid.push(m); + } + // Curved elements must stay valid: straighten those with a non-positive Jacobian anywhere. + progress('Checking elements', 0.85); + let straightened = 0; + for (let pass = 0; pass < 4; pass++) { + let bad = 0; + for (let t = 0; t < NT; t++) { + if (quadraticValid(N, T10, t)) continue; + bad++; + for (let k = 4; k < 10; k++) { + const m = T10[t * 10 + k], s = (m - nn) * 3; + N[m * 3] = straight[s]; N[m * 3 + 1] = straight[s + 1]; N[m * 3 + 2] = straight[s + 2]; + } + } + straightened += bad; + if (!bad) break; + } + + // Boundary triangles with their midside nodes. + const tris = new Int32Array(nb3 * 6); + for (let f = 0; f < nb3; f++) { + const a = B[f * 3], b = B[f * 3 + 1], c = B[f * 3 + 2]; + tris.set([a, b, c, edgeMap.get(eKey(a, b))!, edgeMap.get(eKey(b, c))!, edgeMap.get(eKey(c, a))!], f * 6); + } + + // ---- statistics ---- + progress('Statistics', 0.95); + let minQ = Infinity, sumQ = 0, minD = 180, maxD = 0; + for (let t = 0; t < NT; t++) { + const n4 = [T4[t * 4], T4[t * 4 + 1], T4[t * 4 + 2], T4[t * 4 + 3]]; + const q = tetQuality(P, n4[0], n4[1], n4[2], n4[3]); + minQ = Math.min(minQ, q); sumQ += q; + for (const d of dihedrals(P, n4)) { minD = Math.min(minD, d); maxD = Math.max(maxD, d); } + } + let volume = 0; + for (let t = 0; t < NT; t++) volume += quadraticVolume(N, T10, t); + // Walls much thinner than the elements come out ragged, with whole layers missing: results on such a mesh mean nothing. + const surfaceVolume = surf.volume(); + const off = volume / Math.abs(surfaceVolume) - 1; + if (!(Math.abs(off) <= 0.1)) throw new MeshError(`The mesh ${off < 0 ? 'misses' : 'adds'} ${Math.round(Math.abs(off) * 100)}% of the part's volume: some of its walls are thinner than the elements. Choose a finer mesh.`, true); + return { + nodes: N, corners: nn, tets: T10, tris, triFace, + stats: { + size: h, nodes: N.length / 3, elements: NT, volume, surfaceVolume, minQuality: minQ, meanQuality: sumQ / NT, + minDihedral: minD, maxDihedral: maxD, straightened, unassigned, pieces: countPieces(T4, nn), + }, + }; +} + +// ---------- helpers ---------- + +function dist2(P: ArrayLike, v: number, p: ArrayLike): number { + return (P[v * 3] - p[0]) ** 2 + (P[v * 3 + 1] - p[1]) ** 2 + (P[v * 3 + 2] - p[2]) ** 2; +} + +interface LinearMesh { P: Float64Array; tets: Int32Array; nn: number; nt: number } + +/** Boundary triangles (faces of one tetrahedron only), oriented outward, in the order they are first met. */ +function boundaryOf(m: LinearMesh): { tris: Int32Array } { + const { tets, nn } = m; + const nt = tets.length / 4; + // Faces opposite each corner, ordered so their normal points out of a positive tetrahedron. + const F = [[1, 2, 3], [0, 3, 2], [0, 1, 3], [0, 2, 1]]; + // Faces by their two lowest corners: [third corner, face number] pairs. + const byPair = new Map(); + const out = new Int32Array(nt * 12); + const single = new Uint8Array(nt * 4); + let nf = 0; + for (let t = 0; t < nt; t++) { + for (const f of F) { + const a = tets[t * 4 + f[0]], b = tets[t * 4 + f[1]], c = tets[t * 4 + f[2]]; + const lo = Math.min(a, b, c), hi = Math.max(a, b, c), mid = a + b + c - lo - hi; + const key = lo * nn + mid; + let l = byPair.get(key); + if (!l) byPair.set(key, (l = [])); + let twin = -1; + for (let q = 0; q < l.length; q += 2) if (l[q] === hi) { twin = l[q + 1]; break; } + if (twin >= 0) { single[twin] = 0; continue; } + l.push(hi, nf); + out[nf * 3] = a; out[nf * 3 + 1] = b; out[nf * 3 + 2] = c; + single[nf++] = 1; + } + } + let n = 0; + for (let f = 0; f < nf; f++) if (single[f]) n++; + const tris = new Int32Array(n * 3); + for (let f = 0, k = 0; f < nf; f++) if (single[f]) { tris[k++] = out[f * 3]; tris[k++] = out[f * 3 + 1]; tris[k++] = out[f * 3 + 2]; } + return { tris }; +} + +function forBoundaryEdges(tris: Int32Array, fn: (a: number, b: number) => void) { + const seen = new Set(); + for (let f = 0; f < tris.length; f += 3) { + for (const [i, j] of [[0, 1], [1, 2], [2, 0]]) { + const a = tris[f + i], b = tris[f + j]; + const key = a < b ? `${a},${b}` : `${b},${a}`; + if (seen.has(key)) continue; + seen.add(key); + fn(a, b); + } + } +} + +export function vertexTets(m: LinearMesh): { start: Int32Array; items: Int32Array } { + const { tets, nn } = m; + const nt = tets.length / 4; + const start = new Int32Array(nn + 1); + for (let q = 0; q < tets.length; q++) start[tets[q] + 1]++; + for (let i = 0; i < nn; i++) start[i + 1] += start[i]; + const fill = start.slice(); + const items = new Int32Array(tets.length); + for (let t = 0; t < nt; t++) for (let k = 0; k < 4; k++) items[fill[tets[t * 4 + k]]++] = t; + return { start, items }; +} + +function countPieces(tets: Int32Array, nn: number): number { + const parent = new Int32Array(nn).map((_, i) => i); + const find = (x: number): number => { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }; + const used = new Uint8Array(nn); + for (let t = 0; t < tets.length; t += 4) { + for (let k = 0; k < 4; k++) used[tets[t + k]] = 1; + const a = find(tets[t]); + for (let k = 1; k < 4; k++) { const b = find(tets[t + k]); if (a !== b) parent[b] = a; } + } + let n = 0; + for (let i = 0; i < nn; i++) if (used[i] && find(i) === i) n++; + return n; +} + +/** Derivatives of the 10-node shape functions in volume coordinates (L1, L2, L3; L0 = 1 - L1 - L2 - L3) at a point. */ +export function quadDerivs(l1: number, l2: number, l3: number, out: Float64Array) { + const l0 = 1 - l1 - l2 - l3; + // dN/dL1, dN/dL2, dN/dL3 for each node (3 per node). + // Corners: N0 = L0(2L0-1), Ni = Li(2Li-1). + const d0 = 1 - 4 * l0; + out.fill(0); + out[0] = d0; out[1] = d0; out[2] = d0; + out[3] = 4 * l1 - 1; + out[7] = 4 * l2 - 1; + out[11] = 4 * l3 - 1; + // Edges 01, 12, 20, 03, 13, 23: N = 4 La Lb. + // 01: 4 L0 L1 + out[12] = 4 * (l0 - l1); out[13] = -4 * l1; out[14] = -4 * l1; + // 12: 4 L1 L2 + out[15] = 4 * l2; out[16] = 4 * l1; out[17] = 0; + // 20: 4 L2 L0 + out[18] = -4 * l2; out[19] = 4 * (l0 - l2); out[20] = -4 * l2; + // 03: 4 L0 L3 + out[21] = -4 * l3; out[22] = -4 * l3; out[23] = 4 * (l0 - l3); + // 13: 4 L1 L3 + out[24] = 4 * l3; out[25] = 0; out[26] = 4 * l1; + // 23: 4 L2 L3 + out[27] = 0; out[28] = 4 * l3; out[29] = 4 * l2; +} + +/** 4-point Gauss rule on the tetrahedron (degree 2): volume coordinates (L1, L2, L3) and weight (of the unit tetrahedron, volume 1/6). */ +const GA = 0.5854101966249685, GB = 0.1381966011250105; +export const GAUSS4: [number, number, number, number][] = [[GB, GB, GB, 1 / 24], [GA, GB, GB, 1 / 24], [GB, GA, GB, 1 / 24], [GB, GB, GA, 1 / 24]]; + +const dN = new Float64Array(30); + +/** Jacobian determinant of element t at volume coordinates (l1, l2, l3). */ +export function quadJacobian(N: ArrayLike, T: ArrayLike, t: number, l1: number, l2: number, l3: number): number { + quadDerivs(l1, l2, l3, dN); + let j00 = 0, j01 = 0, j02 = 0, j10 = 0, j11 = 0, j12 = 0, j20 = 0, j21 = 0, j22 = 0; + for (let a = 0; a < 10; a++) { + const n = T[t * 10 + a] * 3; + const x = N[n], y = N[n + 1], z = N[n + 2]; + const g0 = dN[a * 3], g1 = dN[a * 3 + 1], g2 = dN[a * 3 + 2]; + j00 += g0 * x; j01 += g0 * y; j02 += g0 * z; + j10 += g1 * x; j11 += g1 * y; j12 += g1 * z; + j20 += g2 * x; j21 += g2 * y; j22 += g2 * z; + } + return j00 * (j11 * j22 - j12 * j21) - j01 * (j10 * j22 - j12 * j20) + j02 * (j10 * j21 - j11 * j20); +} + +const CHECK_POINTS: [number, number, number][] = [ + [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], [0.5, 0, 0], [0.5, 0.5, 0], [0, 0.5, 0], [0, 0, 0.5], [0.5, 0, 0.5], [0, 0.5, 0.5], + ...GAUSS4.map(([a, b, c]) => [a, b, c] as [number, number, number]), +]; + +/** Whether a curved element's Jacobian is positive at its nodes and quadrature points (and not much smaller than its straight value). */ +function quadraticValid(N: ArrayLike, T: ArrayLike, t: number): boolean { + const lin = 6 * tetVolume(N, T[t * 10], T[t * 10 + 1], T[t * 10 + 2], T[t * 10 + 3]); + for (const [a, b, c] of CHECK_POINTS) if (!(quadJacobian(N, T, t, a, b, c) > 0.1 * lin)) return false; + return true; +} + +export function quadraticVolume(N: ArrayLike, T: ArrayLike, t: number): number { + let v = 0; + for (const [a, b, c, w] of GAUSS4) v += quadJacobian(N, T, t, a, b, c) * w; + return v; +} + +/** Points near a point, by bins. */ +class PointGrid { + private bins = new Map(); + constructor(private P: ArrayLike, ids: number[], private c: number) { + for (const v of ids) { + const k = this.key(P[v * 3], P[v * 3 + 1], P[v * 3 + 2]); + let l = this.bins.get(k); + if (!l) this.bins.set(k, (l = [])); + l.push(v); + } + } + private key(x: number, y: number, z: number) { + return `${Math.floor(x / this.c)},${Math.floor(y / this.c)},${Math.floor(z / this.c)}`; + } + near(p: ArrayLike, r: number): number[] { + const out: number[] = []; + const lo = [0, 1, 2].map((d) => Math.floor((p[d] - r) / this.c)), hi = [0, 1, 2].map((d) => Math.floor((p[d] + r) / this.c)); + for (let x = lo[0]; x <= hi[0]; x++) for (let y = lo[1]; y <= hi[1]; y++) for (let z = lo[2]; z <= hi[2]; z++) { + for (const v of this.bins.get(`${x},${y},${z}`) ?? []) if (dist2(this.P, v, p) <= r * r) out.push(v); + } + return out; + } +} + +/** A tetrahedral mesh being edited: vertices move, edges split. */ +class WorkMesh { + P: number[]; + T: number[]; + vt: number[][]; + onB: number[] = []; + labels: number[][] = []; + locked: number[] = []; + constructor(P: number[], T: number[], private h: number) { + this.P = P; + this.T = T; + this.vt = Array.from({ length: P.length / 3 }, () => []); + for (let t = 0; t < T.length / 4; t++) for (let k = 0; k < 4; k++) this.vt[T[t * 4 + k]].push(t); + const n = P.length / 3; + this.onB = new Array(n).fill(0); + this.locked = new Array(n).fill(0); + this.labels = Array.from({ length: n }, () => []); + } + get nn() { return this.P.length / 3; } + get nt() { return this.T.length / 4; } + pos(v: number): number[] { return [this.P[v * 3], this.P[v * 3 + 1], this.P[v * 3 + 2]]; } + quality(t: number) { const T = this.T; return tetQuality(this.P, T[t * 4], T[t * 4 + 1], T[t * 4 + 2], T[t * 4 + 3]); } + worst(v: number) { let w = Infinity; for (const t of this.vt[v]) w = Math.min(w, this.quality(t)); return w; } + hasEdge(u: number, w: number) { return this.vt[u].some((t) => this.vt[w].includes(t)); } + /** Moves v to p unless an element around it would get worse than minQ (or than the worst it had). */ + move(v: number, p: ArrayLike, minQ: number): boolean { + const old = this.pos(v); + const before = this.worst(v); + this.P[v * 3] = p[0]; this.P[v * 3 + 1] = p[1]; this.P[v * 3 + 2] = p[2]; + if (this.worst(v) >= Math.min(minQ, before)) return true; + this.P[v * 3] = old[0]; this.P[v * 3 + 1] = old[1]; this.P[v * 3 + 2] = old[2]; + return false; + } + /** Splits edge u-w at its middle; returns the new vertex. */ + split(u: number, w: number): number { + const x = this.nn; + this.P.push((this.P[u * 3] + this.P[w * 3]) / 2, (this.P[u * 3 + 1] + this.P[w * 3 + 1]) / 2, (this.P[u * 3 + 2] + this.P[w * 3 + 2]) / 2); + this.vt.push([]); + this.onB.push(0); + this.locked.push(0); + this.labels.push([]); + const shared = this.vt[u].filter((t) => this.vt[w].includes(t)); + for (const t of shared) { + // t keeps u (w becomes x); the copy keeps w (u becomes x): both keep the orientation. + const nt = this.nt; + const copy = this.T.slice(t * 4, t * 4 + 4); + for (let k = 0; k < 4; k++) { + if (this.T[t * 4 + k] === w) this.T[t * 4 + k] = x; + if (copy[k] === u) copy[k] = x; + } + this.T.push(...copy); + this.vt[w] = this.vt[w].filter((q) => q !== t); + this.vt[w].push(nt); + this.vt[x].push(t, nt); + for (const c of copy) if (c !== x && c !== w) this.vt[c].push(nt); + } + return x; + } + /** Moves interior vertices where that raises the worst element around them. */ + smooth(passes: number) { + for (let pass = 0; pass < passes; pass++) { + for (let v = 0; v < this.nn; v++) { + if (this.onB[v]) continue; + const worst = this.worst(v); + if (worst > 0.45) continue; + const nb = new Set(); + for (const t of this.vt[v]) for (let k = 0; k < 4; k++) if (this.T[t * 4 + k] !== v) nb.add(this.T[t * 4 + k]); + const c = [0, 0, 0]; + for (const w of nb) { c[0] += this.P[w * 3] / nb.size; c[1] += this.P[w * 3 + 1] / nb.size; c[2] += this.P[w * 3 + 2] / nb.size; } + const old = this.pos(v); + let best = worst, bestP = old; + // The middle of the neighbours, part way there, and small steps along the axes. + const step = this.h * 0.08; + const tries = [c, [0, 1, 2].map((d) => old[d] + (c[d] - old[d]) * 0.5)]; + for (let d = 0; d < 3; d++) for (const sgn of [-1, 1]) { const p = old.slice(); p[d] += sgn * step; tries.push(p); } + for (const p of tries) { + this.P[v * 3] = p[0]; this.P[v * 3 + 1] = p[1]; this.P[v * 3 + 2] = p[2]; + const q = this.worst(v); + if (q > best) { best = q; bestP = p; } + } + this.P[v * 3] = bestP[0]; this.P[v * 3 + 1] = bestP[1]; this.P[v * 3 + 2] = bestP[2]; + } + } + } + typed(): LinearMesh { + return { P: Float64Array.from(this.P), tets: Int32Array.from(this.T), nn: this.nn, nt: this.nt }; + } +} diff --git a/src/parametric/src/fea/results.ts b/src/parametric/src/fea/results.ts new file mode 100644 index 000000000..c2e3f1b80 --- /dev/null +++ b/src/parametric/src/fea/results.ts @@ -0,0 +1,184 @@ +// What the interface gets from the analysis: the mesh's boundary (the +// surface the results are drawn on, with its own node numbering), the +// fields at those nodes, and a summary over the whole mesh. Also the +// helpers that turn fields into colours and values at a point. + +import type { MeshStats, TetMesh } from './mesher'; +import type { StaticInput, StaticResult, Vec3 } from './static'; + +export interface FeaMeshInfo { + stats: MeshStats; + /** xyz of the boundary nodes (corner and midside). */ + nodes: Float32Array; + /** 6 boundary nodes per triangle: corners, then midside nodes of edges 01, 12, 20. */ + tris: Uint32Array; + /** B-rep face of each triangle. */ + triFace: Int32Array; + /** Element edges on the boundary as segments (each edge through its midside node), for showing the mesh. */ + lines: Float32Array; +} + +export type FieldName = 'vonMises' | 'p1' | 'p2' | 'p3' | 'disp' | 'ux' | 'uy' | 'uz' | 'strain' | 'fos'; + +export interface Extreme { + value: number; + at: Vec3; +} + +export interface FeaSummary { + maxVonMises: Extreme; + maxDisplacement: Extreme; + maxP1: Extreme; + minP3: Extreme; + maxStrain: Extreme; + reactions: Vec3[]; + applied: Vec3; + loadAreas: number[]; + dofs: number; + iterations: number; + residual: number; + solver: string; + ms: StaticResult['ms']; + /** Mass of the part (kg) when gravity is applied, else 0. */ + mass: number; + warnings: string[]; +} + +export interface FeaSolution { + /** Per boundary node: displacement (3 per node), von Mises, principal stresses 1-3, equivalent strain. */ + fields: Float32Array[]; + summary: FeaSummary; +} + +/** The boundary of a mesh with its nodes renumbered; `map` gives each boundary node's mesh node. */ +export function meshView(mesh: TetMesh): { info: FeaMeshInfo; map: Int32Array } { + const remap = new Map(); + const map: number[] = []; + const tris = new Uint32Array(mesh.tris.length); + for (let q = 0; q < mesh.tris.length; q++) { + const v = mesh.tris[q]; + let id = remap.get(v); + if (id === undefined) { id = map.length; remap.set(v, id); map.push(v); } + tris[q] = id; + } + const nodes = new Float32Array(map.length * 3); + map.forEach((v, i) => { nodes[i * 3] = mesh.nodes[v * 3]; nodes[i * 3 + 1] = mesh.nodes[v * 3 + 1]; nodes[i * 3 + 2] = mesh.nodes[v * 3 + 2]; }); + const seen = new Set(); + const lines: number[] = []; + const nt = tris.length / 6; + for (let f = 0; f < nt; f++) { + for (const [a, b, m] of [[0, 1, 3], [1, 2, 4], [2, 0, 5]]) { + const key = tris[f * 6 + m]; + if (seen.has(key)) continue; + seen.add(key); + for (const [p, q] of [[a, m], [m, b]]) { + const i = tris[f * 6 + p] * 3, j = tris[f * 6 + q] * 3; + lines.push(nodes[i], nodes[i + 1], nodes[i + 2], nodes[j], nodes[j + 1], nodes[j + 2]); + } + } + } + return { info: { stats: mesh.stats, nodes, tris, triFace: Int32Array.from(mesh.triFace), lines: Float32Array.from(lines) }, map: Int32Array.from(map) }; +} + +function extreme(mesh: TetMesh, values: ArrayLike, sign = 1): Extreme { + let best = 0, bv = -Infinity; + for (let v = 0; v < values.length; v++) if (sign * values[v] > bv) { bv = sign * values[v]; best = v; } + return { value: values[best] ?? 0, at: [mesh.nodes[best * 3], mesh.nodes[best * 3 + 1], mesh.nodes[best * 3 + 2]] }; +} + +export function solutionOf(mesh: TetMesh, map: Int32Array, r: StaticResult, input: StaticInput): FeaSolution { + const n = map.length; + const U = new Float32Array(n * 3); + const pick = (src: Float64Array) => { const out = new Float32Array(n); for (let i = 0; i < n; i++) out[i] = src[map[i]]; return out; }; + for (let i = 0; i < n; i++) for (let k = 0; k < 3; k++) U[i * 3 + k] = r.U[map[i] * 3 + k]; + const N = r.vonMises.length; + const disp = new Float64Array(N); + for (let v = 0; v < N; v++) disp[v] = Math.hypot(r.U[v * 3], r.U[v * 3 + 1], r.U[v * 3 + 2]); + const gravity = input.loads.find((l) => l.kind === 'gravity'); + const g = gravity && gravity.kind === 'gravity' ? Math.hypot(...gravity.accel) : 0; + return { + fields: [U, pick(r.vonMises), pick(r.p1), pick(r.p2), pick(r.p3), pick(r.strain)], + summary: { + maxVonMises: extreme(mesh, r.vonMises), maxDisplacement: extreme(mesh, disp), maxP1: extreme(mesh, r.p1), minP3: extreme(mesh, r.p3, -1), maxStrain: extreme(mesh, r.strain), + reactions: r.reactions, applied: r.applied, loadAreas: r.loadAreas, dofs: r.dofs, iterations: r.iterations, residual: r.residual, solver: r.solver, ms: r.ms, + mass: g > 0 ? mesh.stats.volume * input.density * 1000 : 0, warnings: r.warnings, + }, + }; +} + +/** Values of a field at the boundary nodes (factor of safety needs the yield strength). */ +export function fieldValues(sol: FeaSolution, field: FieldName, yieldStrength: number): Float32Array { + const [U, vm, p1, p2, p3, strain] = sol.fields; + const n = vm.length; + if (field === 'vonMises') return vm; + if (field === 'p1') return p1; + if (field === 'p2') return p2; + if (field === 'p3') return p3; + if (field === 'strain') return strain; + const out = new Float32Array(n); + if (field === 'fos') { for (let i = 0; i < n; i++) out[i] = vm[i] > 0 ? yieldStrength / vm[i] : Infinity; return out; } + if (field === 'disp') { for (let i = 0; i < n; i++) out[i] = Math.hypot(U[i * 3], U[i * 3 + 1], U[i * 3 + 2]); return out; } + const k = field === 'ux' ? 0 : field === 'uy' ? 1 : 2; + for (let i = 0; i < n; i++) out[i] = U[i * 3 + k]; + return out; +} + +/** Rainbow colour map (blue low, red high), t in 0..1, as RGB 0..255. */ +export function colorAt(t: number): [number, number, number] { + const x = Math.max(0, Math.min(1, t)); + // Blue, cyan, green, yellow, red. + const stops: [number, number, number][] = [[20, 60, 220], [0, 190, 230], [40, 200, 80], [250, 220, 30], [225, 40, 30]]; + const s = x * (stops.length - 1); + const i = Math.min(stops.length - 2, Math.floor(s)); + const f = s - i; + return [0, 1, 2].map((k) => Math.round(stops[i][k] + (stops[i + 1][k] - stops[i][k]) * f)) as [number, number, number]; +} + +/** + * Where a ray first meets the (possibly deformed) result surface: the triangle, + * its barycentric coordinates on the flat corner triangle, and the point. + */ +export function rayHit(positions: Float32Array, tris: Uint32Array, o: Vec3, d: Vec3): { tri: number; u: number; v: number; t: number } | null { + let best: { tri: number; u: number; v: number; t: number } | null = null; + const nt = tris.length / 6; + for (let f = 0; f < nt; f++) { + // The six-node triangle as four flat ones (corners and midside nodes). + for (const [a, b, c, map] of SUB) { + const ia = tris[f * 6 + a] * 3, ib = tris[f * 6 + b] * 3, ic = tris[f * 6 + c] * 3; + const e1 = [positions[ib] - positions[ia], positions[ib + 1] - positions[ia + 1], positions[ib + 2] - positions[ia + 2]]; + const e2 = [positions[ic] - positions[ia], positions[ic + 1] - positions[ia + 1], positions[ic + 2] - positions[ia + 2]]; + const p = [d[1] * e2[2] - d[2] * e2[1], d[2] * e2[0] - d[0] * e2[2], d[0] * e2[1] - d[1] * e2[0]]; + const det = e1[0] * p[0] + e1[1] * p[1] + e1[2] * p[2]; + if (Math.abs(det) < 1e-12) continue; + const s = [o[0] - positions[ia], o[1] - positions[ia + 1], o[2] - positions[ia + 2]]; + const u = (s[0] * p[0] + s[1] * p[1] + s[2] * p[2]) / det; + if (u < 0 || u > 1) continue; + const q = [s[1] * e1[2] - s[2] * e1[1], s[2] * e1[0] - s[0] * e1[2], s[0] * e1[1] - s[1] * e1[0]]; + const v = (d[0] * q[0] + d[1] * q[1] + d[2] * q[2]) / det; + if (v < 0 || u + v > 1) continue; + const t = (e2[0] * q[0] + e2[1] * q[1] + e2[2] * q[2]) / det; + if (t <= 0 || (best && t >= best.t)) continue; + // Back to the parent triangle's coordinates. + const L = map(1 - u - v, u, v); + best = { tri: f, u: L[1], v: L[2], t }; + } + } + return best; +} + +/** Sub-triangles of a six-node triangle (slots), with the map from their barycentric coordinates to the parent's (r, s, t). */ +export const SUB: [number, number, number, (a: number, b: number, c: number) => [number, number, number]][] = [ + [0, 3, 5, (a, b, c) => [a + b / 2 + c / 2, b / 2, c / 2]], + [3, 1, 4, (a, b, c) => [a / 2, a / 2 + b + c / 2, c / 2]], + [5, 4, 2, (a, b, c) => [a / 2, b / 2, a / 2 + b / 2 + c]], + [3, 4, 5, (a, b, c) => [a / 2 + c / 2, a / 2 + b / 2, b / 2 + c / 2]], +]; + +/** Value of a node field at (s, t) on six-node triangle f (quadratic interpolation). */ +export function interpolate(values: ArrayLike, tris: Uint32Array, f: number, s: number, t: number, stride = 1, comp = 0): number { + const r = 1 - s - t; + const N = [r * (2 * r - 1), s * (2 * s - 1), t * (2 * t - 1), 4 * r * s, 4 * s * t, 4 * t * r]; + let out = 0; + for (let a = 0; a < 6; a++) out += N[a] * values[tris[f * 6 + a] * stride + comp]; + return out; +} diff --git a/src/parametric/src/fea/static.ts b/src/parametric/src/fea/static.ts new file mode 100644 index 000000000..06840e930 --- /dev/null +++ b/src/parametric/src/fea/static.ts @@ -0,0 +1,693 @@ +// Linear static analysis on a quadratic tetrahedral mesh: assembly of the +// stiffness matrix, loads, fixtures (as constraints in each node's own +// directions), the check that the fixtures hold the part, the solve, and the +// stresses, strains and reactions that come out of it. +// +// Units: millimetres, newtons, megapascals (N/mm^2), tonnes per cubic +// millimetre for density (so density times mm/s^2 is N/mm^3). + +import { type Preconditioner, blockAt, blockJacobi, meshPattern, pcg, smoothedAggregation } from './amg'; +import { addBodyForce, elementNodeStrains, elementStiffness, integrateTriangle, lame, principal } from './elements'; +import type { TetMesh } from './mesher'; +import type { FeaFaceSurface } from '../kernel/protocol'; + +export type Vec3 = [number, number, number]; + +export type FixtureInput = + | { kind: 'fixed'; faces: number[] } + /** + * No motion normal to the faces (each node: the surface normal there, from `surfaces` where given (one per + * face), else from the mesh). + */ + | { kind: 'roller'; faces: number[]; surfaces?: FeaFaceSurface[] } + /** A cylindrical face that may only turn about its axis (no radial or axial motion). */ + | { kind: 'hinge'; faces: number[]; axis: { p: Vec3; d: Vec3 } }; + +export type LoadInput = + /** Total force spread evenly over the faces' area: along dir, or (dir null) pressing on the faces as a pressure would. */ + | { kind: 'force'; faces: number[]; total: number; dir: Vec3 | null } + /** Pressure (MPa), pushing into the faces. */ + | { kind: 'pressure'; faces: number[]; value: number } + /** Acceleration of gravity (mm/s^2): the part's weight acts along it. */ + | { kind: 'gravity'; accel: Vec3 }; + +export interface StaticInput { + /** Elastic modulus (MPa), Poisson's ratio, density (t/mm^3). */ + E: number; + nu: number; + density: number; + fixtures: FixtureInput[]; + loads: LoadInput[]; +} + +export interface StaticResult { + /** Displacement per node (x, y, z). */ + U: Float64Array; + /** Per node: von Mises stress, principal stresses (largest first), equivalent strain. */ + vonMises: Float64Array; + p1: Float64Array; + p2: Float64Array; + p3: Float64Array; + strain: Float64Array; + /** Stress components per node (xx, yy, zz, xy, yz, zx). */ + stress: Float64Array; + /** Reaction force of each fixture, and the sum of the applied loads (N). */ + reactions: Vec3[]; + applied: Vec3; + /** Area each load acts on, as meshed (mm^2): 0 for gravity. */ + loadAreas: number[]; + dofs: number; + /** Things the user should know about the solution (a free motion held by weak springs). */ + warnings: string[]; + iterations: number; + residual: number; + solver: string; + ms: { assemble: number; setup: number; solve: number; stress: number }; +} + +/** A study the solver cannot run, with a message for the user. */ +export class StudyError extends Error {} + +const AXES = ['X', 'Y', 'Z']; + +/** + * Whether the fixtures hold every piece of the mesh: rigid motions they do + * not stop are described ('free to move along X', 'free to turn about ...'). + */ +export function rigidMotions(mesh: TetMesh, constrained: Map): string[] { + return freeMotions(mesh, constrained).map((m) => m.text); +} + +/** A rigid motion the fixtures allow: u = t + w x (x - c) / L on the nodes of one piece. */ +export interface FreeMotion { + text: string; + v: number[]; + c: Vec3; + L: number; + /** Whether a node belongs to the piece. */ + has: (node: number) => boolean; +} + +export function freeMotions(mesh: TetMesh, constrained: Map): FreeMotion[] { + const X = mesh.nodes, nn = mesh.nodes.length / 3; + // Pieces of the mesh (connected through elements). + const parent = new Int32Array(nn).map((_, i) => i); + const find = (x: number): number => { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }; + const T = mesh.tets; + for (let e = 0; e < T.length; e += 10) { const a = find(T[e]); for (let k = 1; k < 10; k++) { const b = find(T[e + k]); if (a !== b) parent[b] = a; } } + const pieces = new Map(); + for (let e = 0; e < T.length; e += 10) { + for (let k = 0; k < 10; k++) { + const v = T[e + k], r = find(v); + let p = pieces.get(r); + if (!p) pieces.set(r, (p = { c: [0, 0, 0], n: 0, M: new Array(36).fill(0) })); + } + } + const seen = new Uint8Array(nn); + for (let e = 0; e < T.length; e++) { + const v = T[e]; + if (seen[v]) continue; + seen[v] = 1; + const p = pieces.get(find(v))!; + p.c[0] += X[v * 3]; p.c[1] += X[v * 3 + 1]; p.c[2] += X[v * 3 + 2]; p.n++; + } + let L = 0; + for (const p of pieces.values()) { p.c = [p.c[0] / p.n, p.c[1] / p.n, p.c[2] / p.n]; } + for (let v = 0; v < nn; v++) if (seen[v]) { const p = pieces.get(find(v))!; L = Math.max(L, Math.hypot(X[v * 3] - p.c[0], X[v * 3 + 1] - p.c[1], X[v * 3 + 2] - p.c[2])); } + L = L || 1; + // Each constrained direction d at x stops the rigid motions (t, w) with d.t + ((x - c) x d).w != 0. + for (const [v, dirs] of constrained) { + const p = pieces.get(find(v)); + if (!p) continue; + const r = [(X[v * 3] - p.c[0]) / L, (X[v * 3 + 1] - p.c[1]) / L, (X[v * 3 + 2] - p.c[2]) / L]; + for (const d of dirs) { + const row = [d[0], d[1], d[2], r[1] * d[2] - r[2] * d[1], r[2] * d[0] - r[0] * d[2], r[0] * d[1] - r[1] * d[0]]; + for (let i = 0; i < 6; i++) for (let j = 0; j < 6; j++) p.M[i * 6 + j] += row[i] * row[j]; + } + } + const free: FreeMotion[] = []; + const several = pieces.size > 1; + let k = 0; + for (const [root, p] of pieces) { + k++; + const motion = (text: string, v: number[]): FreeMotion => ({ text, v, c: p.c, L, has: (node) => find(node) === root }); + const { values, vectors } = jacobiEigen(p.M, 6); + const top = Math.max(...values, 0); + // The free motions: eigenvectors of (nearly) zero eigenvalues. + const nul: number[][] = []; + values.forEach((lam, i) => { if (!(top > 0) || lam <= 1e-9 * top) nul.push(vectors.slice(i * 6, i * 6 + 6)); }); + if (!nul.length) continue; + const where = several ? ` (piece ${k} of ${pieces.size})` : ''; + // Name them along the axes where they are: a motion along X is free if its projection on the free motions is whole. + const inNull = (v: number[]) => { let s = 0; for (const n of nul) { let d = 0; for (let q = 0; q < 6; q++) d += n[q] * v[q]; s += d * d; } return s; }; + const named: string[] = []; + for (let a = 0; a < 3; a++) { const v = [0, 0, 0, 0, 0, 0]; v[a] = 1; if (inNull(v) > 0.98) named.push(`free to move along ${AXES[a]}`); } + // Turning about an axis along X (through any point): some free motion has a rotation part along X alone. + for (let a = 0; a < 3; a++) { + // Largest |w_a| / |w| over the free motions' span: the rotation parts' Gram matrix. + const W = nul.map((n) => [n[3], n[4], n[5]]); + const G = W.map((x) => W.map((y) => x[0] * y[0] + x[1] * y[1] + x[2] * y[2])); + const g = W.map((x) => x[a]); + // Best combination c maximising (g.c)^2 / (c.G.c): solve G c = g (least squares by Jacobi eigen). + const m = W.length; + const { values: gv, vectors: gV } = jacobiEigen(G.flat(), m); + let ratio = 0; + const gmax = Math.max(...gv, 0); + gv.forEach((lam, i) => { if (lam > 1e-9 * gmax && gmax > 0) { let d = 0; for (let q = 0; q < m; q++) d += gV[i * m + q] * g[q]; ratio += (d * d) / lam; } }); + if (ratio > 0.98) named.push(`free to turn about ${AXES[a]}`); + } + if (named.length >= nul.length) { named.forEach((n, i) => free.push(motion(n + where, nul[Math.min(i, nul.length - 1)]))); for (let i = named.length; i < nul.length; i++) free.push(motion('', nul[i])); continue; } + // Otherwise the eigenvectors as they are. + for (const v of nul) { + const t = Math.hypot(v[0], v[1], v[2]), w = Math.hypot(v[3], v[4], v[5]); + if (w < 0.05 * t) free.push(motion(`free to move ${describeDir([v[0], v[1], v[2]])}${where}`, v)); + else free.push(motion(`free to turn ${describeDir([v[3] / w, v[4] / w, v[5] / w], 'about')}${where}`, v)); + } + } + return free; +} + +function describeDir(d: number[], prep = 'along'): string { + const n = Math.hypot(d[0], d[1], d[2]) || 1; + const u = d.map((x) => x / n); + const i = [0, 1, 2].reduce((b, k) => (Math.abs(u[k]) > Math.abs(u[b]) ? k : b), 0); + if (Math.abs(u[i]) > 0.999) return `${prep} ${AXES[i]}`; + return `${prep} (${u.map((x) => x.toFixed(2)).join(', ')})`; +} + +/** Eigenvalues and vectors (rows of `vectors`) of a symmetric n x n matrix (cyclic Jacobi). */ +export function jacobiEigen(Ain: number[], n: number): { values: number[]; vectors: number[] } { + const A = Ain.slice(); + const V = new Array(n * n).fill(0); + for (let i = 0; i < n; i++) V[i * n + i] = 1; + for (let sweep = 0; sweep < 60; sweep++) { + let off = 0; + for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) off += A[i * n + j] ** 2; + if (off < 1e-30) break; + for (let p = 0; p < n; p++) for (let q = p + 1; q < n; q++) { + const apq = A[p * n + q]; + if (Math.abs(apq) < 1e-300) continue; + const theta = (A[q * n + q] - A[p * n + p]) / (2 * apq); + const t = Math.sign(theta || 1) / (Math.abs(theta) + Math.sqrt(theta * theta + 1)); + const c = 1 / Math.sqrt(t * t + 1), s = t * c; + for (let k = 0; k < n; k++) { + const akp = A[k * n + p], akq = A[k * n + q]; + A[k * n + p] = c * akp - s * akq; A[k * n + q] = s * akp + c * akq; + } + for (let k = 0; k < n; k++) { + const apk = A[p * n + k], aqk = A[q * n + k]; + A[p * n + k] = c * apk - s * aqk; A[q * n + k] = s * apk + c * aqk; + } + for (let k = 0; k < n; k++) { + const vkp = V[k * n + p], vkq = V[k * n + q]; + V[k * n + p] = c * vkp - s * vkq; V[k * n + q] = s * vkp + c * vkq; + } + } + } + const values = Array.from({ length: n }, (_, i) => A[i * n + i]); + const vectors: number[] = []; + for (let i = 0; i < n; i++) for (let k = 0; k < n; k++) vectors.push(V[k * n + i]); + return { values, vectors }; +} + +/** Nodes of the boundary triangles on the given faces. */ +function faceNodes(mesh: TetMesh, faces: Set): number[] { + const out = new Set(); + for (let f = 0; f < mesh.triFace.length; f++) if (faces.has(mesh.triFace[f])) for (let a = 0; a < 6; a++) out.add(mesh.tris[f * 6 + a]); + return [...out]; +} + +/** The constrained directions of each node (global unit vectors); `by` gets the fixture of each direction. */ +export function constraintsOf(mesh: TetMesh, fixtures: FixtureInput[], by?: Map): Map { + const X = mesh.nodes; + const out = new Map(); + let fixture = 0; + const add = (v: number, d: Vec3) => { + let l = out.get(v); if (!l) out.set(v, (l = [])); l.push(d); + if (by) { let w = by.get(v); if (!w) by.set(v, (w = [])); w.push(fixture); } + }; + fixtures.forEach((fx, i) => { + fixture = i; + const faces = new Set(fx.faces); + const nodes = faceNodes(mesh, faces); + if (!nodes.length) throw new StudyError(`Fixture ${i + 1}: its faces are not in the mesh.`); + if (fx.kind === 'fixed') { for (const v of nodes) { add(v, [1, 0, 0]); add(v, [0, 1, 0]); add(v, [0, 0, 1]); } return; } + if (fx.kind === 'roller') { + // The surface normal at each node on each face: the (area weighted) normals of the face's triangles around it. + const triNormal = (f: number): Vec3 => { + const a = mesh.tris[f * 6] * 3, b = mesh.tris[f * 6 + 1] * 3, c = mesh.tris[f * 6 + 2] * 3; + const ux = X[b] - X[a], uy = X[b + 1] - X[a + 1], uz = X[b + 2] - X[a + 2], wx = X[c] - X[a], wy = X[c + 1] - X[a + 1], wz = X[c + 2] - X[a + 2]; + return [uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx]; + }; + // A flat face is held along its own normal at every node: the odd triangle the mesher could not fit + // to a sharp corner would otherwise hold the part in directions a roller leaves free. + // Its normal: the mean of the triangles' normals, then again of those near it. + const flat = new Map(); + for (const near of [-1, 0.95, 0.9999]) { + const sum = new Map(); + for (let f = 0; f < mesh.triFace.length; f++) { + if (!faces.has(mesh.triFace[f])) continue; + const fn = triNormal(f), was = flat.get(mesh.triFace[f])?.n; + if (was && !(fn[0] * was[0] + fn[1] * was[1] + fn[2] * was[2] > near * Math.hypot(fn[0], fn[1], fn[2]))) continue; + let s = sum.get(mesh.triFace[f]); + if (!s) sum.set(mesh.triFace[f], (s = [0, 0, 0])); + s[0] += fn[0]; s[1] += fn[1]; s[2] += fn[2]; + } + for (const [face, s] of sum) { const l = Math.hypot(s[0], s[1], s[2]); if (l > 0) flat.set(face, { n: [s[0] / l, s[1] / l, s[2] / l], on: 0, all: 0 }); } + } + for (let f = 0; f < mesh.triFace.length; f++) { + const p = flat.get(mesh.triFace[f]); + if (!p) continue; + const fn = triNormal(f), l = Math.hypot(fn[0], fn[1], fn[2]); + p.all += l; + if (fn[0] * p.n[0] + fn[1] * p.n[1] + fn[2] * p.n[2] > l * (1 - 1e-9)) p.on += l; + } + for (const [face, p] of flat) if (!(p.on >= 0.95 * p.all)) flat.delete(face); + // The faces' surfaces where the part says what they are (else found from the mesh as far as it tells). + const unit = (d: Vec3): Vec3 => { const l = Math.hypot(d[0], d[1], d[2]) || 1; return [d[0] / l, d[1] / l, d[2] / l]; }; + const cyl = new Map(); + const sphere = new Map(), rev = new Map(); + fx.surfaces?.forEach((sf, i) => { + const face = fx.faces[i]; + if (!sf) return; + if (sf.kind === 'plane') flat.set(face, { n: unit(sf.n), on: 0, all: 0 }); + else if (sf.kind === 'sphere') { flat.delete(face); sphere.set(face, sf.c); } + else { flat.delete(face); (sf.cylinder ? cyl : rev).set(face, { c: sf.p, a: unit(sf.d) }); } + }); + // A cylindrical face is held radially from its axis: the facets' normals lean along the axis and around + // it, and would hold a shaft on a roller against sliding along and turning about its axis. + for (const face of faces) if (!flat.has(face) && !cyl.has(face) && !sphere.has(face) && !rev.has(face)) { const c = cylinderOf(mesh, face); if (c) cyl.set(face, c); } + const radial = (v: number, { c, a }: { c: Vec3; a: Vec3 }): Vec3 => { + const r: Vec3 = [X[v * 3] - c[0], X[v * 3 + 1] - c[1], X[v * 3 + 2] - c[2]]; + const t = r[0] * a[0] + r[1] * a[1] + r[2] * a[2]; + return [r[0] - t * a[0], r[1] - t * a[1], r[2] - t * a[2]]; + }; + const nrm = new Map>(); + for (let f = 0; f < mesh.triFace.length; f++) { + const face = mesh.triFace[f]; + if (!faces.has(face)) continue; + const cf = cyl.get(face); + const fn = flat.get(face)?.n ?? (cf || sphere.has(face) ? null : triNormal(f)); + for (let q = 0; q < 6; q++) { + const v = mesh.tris[f * 6 + q]; + const sc = sphere.get(face); + if (cf || sc) { let byFace = nrm.get(v); if (!byFace) nrm.set(v, (byFace = new Map())); byFace.set(face, cf ? radial(v, cf) : [X[v * 3] - sc![0], X[v * 3 + 1] - sc![1], X[v * 3 + 2] - sc![2]]); continue; } + let byFace = nrm.get(v); + if (!byFace) nrm.set(v, (byFace = new Map())); + let n = byFace.get(face); + if (!n) byFace.set(face, (n = [0, 0, 0])); + n[0] += fn![0]; n[1] += fn![1]; n[2] += fn![2]; + } + } + // A node on the edge between two of the faces is held normal to each (to their average where they meet + // nearly tangent, as a fillet meets a flat face). + for (const [v, byFace] of nrm) { + const dirs: Vec3[] = []; + for (const [face, n] of byFace) { + // On a surface of revolution (a cone, a torus) the normal has no part around the axis: turning about + // the axis stays free however the facets lean. + const rf = rev.get(face); + if (rf) { + const r = radial(v, rf), t: Vec3 = [rf.a[1] * r[2] - rf.a[2] * r[1], rf.a[2] * r[0] - rf.a[0] * r[2], rf.a[0] * r[1] - rf.a[1] * r[0]]; + const tl = Math.hypot(t[0], t[1], t[2]); + if (tl > 0) { const s = (n[0] * t[0] + n[1] * t[1] + n[2] * t[2]) / (tl * tl); n[0] -= s * t[0]; n[1] -= s * t[1]; n[2] -= s * t[2]; } + } + const l = Math.hypot(n[0], n[1], n[2]); + if (!(l > 0)) continue; + const u: Vec3 = [n[0] / l, n[1] / l, n[2] / l]; + const near = dirs.find((d) => (d[0] * u[0] + d[1] * u[1] + d[2] * u[2]) / Math.hypot(d[0], d[1], d[2]) > 0.85); + if (near) { near[0] += u[0]; near[1] += u[1]; near[2] += u[2]; } else dirs.push(u); + } + for (const d of dirs) { const l = Math.hypot(d[0], d[1], d[2]); add(v, [d[0] / l, d[1] / l, d[2] / l]); } + } + return; + } + const { p, d } = fx.axis; + const dl = Math.hypot(d[0], d[1], d[2]) || 1; + const ax: Vec3 = [d[0] / dl, d[1] / dl, d[2] / dl]; + for (const v of nodes) { + const r = [X[v * 3] - p[0], X[v * 3 + 1] - p[1], X[v * 3 + 2] - p[2]]; + const t = r[0] * ax[0] + r[1] * ax[1] + r[2] * ax[2]; + const rad: Vec3 = [r[0] - t * ax[0], r[1] - t * ax[1], r[2] - t * ax[2]]; + const rl = Math.hypot(rad[0], rad[1], rad[2]); + add(v, ax); + if (rl > 1e-9) add(v, [rad[0] / rl, rad[1] / rl, rad[2] / rl]); + else { add(v, [1, 0, 0]); add(v, [0, 1, 0]); add(v, [0, 0, 1]); } + } + }); + return out; +} + +/** + * The axis of a face if it is cylindrical (as far as the mesh tells): its triangles' normals all square to + * one direction, and its corner nodes lie at one distance from a line along it. A point on the axis and its + * unit direction, or null. + */ +function cylinderOf(mesh: TetMesh, face: number): { c: Vec3; a: Vec3 } | null { + const X = mesh.nodes, T = mesh.tris; + const C = new Array(9).fill(0); + const nodes = new Set(); + for (let f = 0; f < mesh.triFace.length; f++) { + if (mesh.triFace[f] !== face) continue; + const a = T[f * 6] * 3, b = T[f * 6 + 1] * 3, c = T[f * 6 + 2] * 3; + const ux = X[b] - X[a], uy = X[b + 1] - X[a + 1], uz = X[b + 2] - X[a + 2], wx = X[c] - X[a], wy = X[c + 1] - X[a + 1], wz = X[c + 2] - X[a + 2]; + const n = [uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx]; + const l = Math.hypot(n[0], n[1], n[2]); + if (!(l > 0)) continue; + for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) C[i * 3 + j] += (n[i] * n[j]) / l; + for (let q = 0; q < 3; q++) nodes.add(T[f * 6 + q]); + } + const { values, vectors } = jacobiEigen(C, 3); + const order = [0, 1, 2].sort((i, j) => values[i] - values[j]); + const tr = values[0] + values[1] + values[2]; + // The normals go round the axis (not a nearly flat strip, nor a sphere or cone). + if (!(tr > 0) || !(values[order[0]] < 0.05 * tr) || !(values[order[1]] > 0.1 * tr)) return null; + const a: Vec3 = [vectors[order[0] * 3], vectors[order[0] * 3 + 1], vectors[order[0] * 3 + 2]]; + const e1: Vec3 = [vectors[order[1] * 3], vectors[order[1] * 3 + 1], vectors[order[1] * 3 + 2]]; + const e2: Vec3 = [a[1] * e1[2] - a[2] * e1[1], a[2] * e1[0] - a[0] * e1[2], a[0] * e1[1] - a[1] * e1[0]]; + // Circle through the nodes in the plane across the axis (least squares: u^2 + v^2 + D u + E v + F = 0). + const pts: [number, number][] = []; + for (const v of nodes) { const x = X[v * 3], y = X[v * 3 + 1], z = X[v * 3 + 2]; pts.push([x * e1[0] + y * e1[1] + z * e1[2], x * e2[0] + y * e2[1] + z * e2[2]]); } + if (pts.length < 6) return null; + const u0 = pts.reduce((s, p) => s + p[0], 0) / pts.length, v0 = pts.reduce((s, p) => s + p[1], 0) / pts.length; + const N = [0, 0, 0, 0, 0, 0, 0, 0, 0], rhs = [0, 0, 0]; + for (const [pu, pv] of pts) { + const u = pu - u0, v = pv - v0, row = [u, v, 1], w = -(u * u + v * v); + for (let i = 0; i < 3; i++) { rhs[i] += row[i] * w; for (let j = 0; j < 3; j++) N[i * 3 + j] += row[i] * row[j]; } + } + const sol = solve3(N, rhs); + if (!sol) return null; + const cu = -sol[0] / 2, cv = -sol[1] / 2, r2 = cu * cu + cv * cv - sol[2]; + if (!(r2 > 0)) return null; + const r = Math.sqrt(r2); + let near = 0; + for (const [pu, pv] of pts) if (Math.abs(Math.hypot(pu - u0 - cu, pv - v0 - cv) - r) < 0.02 * r) near++; + if (near < 0.9 * pts.length) return null; + const U = cu + u0, V = cv + v0; + const c: Vec3 = [U * e1[0] + V * e2[0], U * e1[1] + V * e2[1], U * e1[2] + V * e2[2]]; + // The facets face (nearly) straight away from the axis found. + let on = 0, all = 0; + for (let f = 0; f < mesh.triFace.length; f++) { + if (mesh.triFace[f] !== face) continue; + const p = [0, 0, 0]; + for (let q = 0; q < 3; q++) for (let d = 0; d < 3; d++) p[d] += X[T[f * 6 + q] * 3 + d] / 3 - c[d] / 3; + const t = p[0] * a[0] + p[1] * a[1] + p[2] * a[2]; + const rad = [p[0] - t * a[0], p[1] - t * a[1], p[2] - t * a[2]]; + const A = T[f * 6] * 3, B = T[f * 6 + 1] * 3, Cc = T[f * 6 + 2] * 3; + const ux = X[B] - X[A], uy = X[B + 1] - X[A + 1], uz = X[B + 2] - X[A + 2], wx = X[Cc] - X[A], wy = X[Cc + 1] - X[A + 1], wz = X[Cc + 2] - X[A + 2]; + const n = [uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx]; + const l = Math.hypot(n[0], n[1], n[2]), rl = Math.hypot(rad[0], rad[1], rad[2]); + all += l; + if (rl > 0 && Math.abs(n[0] * rad[0] + n[1] * rad[1] + n[2] * rad[2]) > 0.95 * l * rl) on += l; + } + return on >= 0.9 * all ? { c, a } : null; +} + +/** Solution of a 3 x 3 system (Cramer's rule), or null if it is singular. */ +function solve3(M: number[], b: number[]): number[] | null { + const det = (m: number[]) => m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + m[2] * (m[3] * m[7] - m[4] * m[6]); + const d = det(M); + if (!(Math.abs(d) > 0)) return null; + return [0, 1, 2].map((k) => { const m = M.slice(); for (let i = 0; i < 3; i++) m[i * 3 + k] = b[i]; return det(m) / d; }); +} + +/** The unit part of d across the (orthonormal) directions, or null if d is (nearly) in their span. */ +function orthogonalTo(dir: Vec3, basis: Vec3[]): Vec3 | null { + const d: Vec3 = [dir[0], dir[1], dir[2]]; + for (const e of basis) { const s = d[0] * e[0] + d[1] * e[1] + d[2] * e[2]; d[0] -= s * e[0]; d[1] -= s * e[1]; d[2] -= s * e[2]; } + const l = Math.hypot(d[0], d[1], d[2]); + return l > 1e-3 ? [d[0] / l, d[1] / l, d[2] / l] : null; +} + +/** Orthonormal basis (columns of a 3 x 3 rotation, row-major) whose first k columns span the directions; returns k. */ +function constraintBasis(dirs: Vec3[], R: Float64Array, off: number): number { + const basis: Vec3[] = []; + for (const d of dirs) { + const v: Vec3 = [d[0], d[1], d[2]]; + for (const b of basis) { const s = v[0] * b[0] + v[1] * b[1] + v[2] * b[2]; v[0] -= s * b[0]; v[1] -= s * b[1]; v[2] -= s * b[2]; } + const l = Math.hypot(v[0], v[1], v[2]); + if (l > 1e-3) basis.push([v[0] / l, v[1] / l, v[2] / l]); + if (basis.length === 3) break; + } + const k = basis.length; + // Complete to a right-handed frame. + for (const e of [[1, 0, 0], [0, 1, 0], [0, 0, 1]] as Vec3[]) { + if (basis.length === 3) break; + const v: Vec3 = [e[0], e[1], e[2]]; + for (const b of basis) { const s = v[0] * b[0] + v[1] * b[1] + v[2] * b[2]; v[0] -= s * b[0]; v[1] -= s * b[1]; v[2] -= s * b[2]; } + const l = Math.hypot(v[0], v[1], v[2]); + if (l > 0.3) basis.push([v[0] / l, v[1] / l, v[2] / l]); + } + for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) R[off + r * 3 + c] = basis[c][r]; + return k; +} + +/** The loads as nodal forces; also the total applied force and each load's meshed area. */ +export function loadVector(mesh: TetMesh, input: StaticInput): { F: Float64Array; applied: Vec3; areas: number[] } { + const X = mesh.nodes, N = X.length / 3; + const F = new Float64Array(N * 3); + const areas: number[] = []; + input.loads.forEach((ld, i) => { + if (ld.kind === 'gravity') { + const b = [input.density * ld.accel[0], input.density * ld.accel[1], input.density * ld.accel[2]]; + for (let e = 0; e < mesh.tets.length / 10; e++) addBodyForce(X, mesh.tets, e, b, F); + areas.push(0); + return; + } + const faces = new Set(ld.faces); + const tris: number[] = []; + for (let f = 0; f < mesh.triFace.length; f++) if (faces.has(mesh.triFace[f])) tris.push(f); + if (!tris.length) throw new StudyError(`Load ${i + 1}: its faces are not in the mesh.`); + let area = 0; + for (const f of tris) area += integrateTriangle(X, mesh.tris, f); + areas.push(area); + if (ld.kind === 'force' && ld.dir) { + const l = Math.hypot(ld.dir[0], ld.dir[1], ld.dir[2]) || 1; + const t = [(ld.total * ld.dir[0]) / l / area, (ld.total * ld.dir[1]) / l / area, (ld.total * ld.dir[2]) / l / area]; + for (const f of tris) integrateTriangle(X, mesh.tris, f, (a, w) => { const n = mesh.tris[f * 6 + a] * 3; F[n] += t[0] * w; F[n + 1] += t[1] * w; F[n + 2] += t[2] * w; }); + return; + } + // Pressure (or a normal force as the pressure that adds up to it on a flat face): along the inward normal. + const p = ld.kind === 'pressure' ? ld.value : ld.total / area; + for (const f of tris) integrateTriangle(X, mesh.tris, f, (a, _w, nx, ny, nz) => { const n = mesh.tris[f * 6 + a] * 3; F[n] -= p * nx; F[n + 1] -= p * ny; F[n + 2] -= p * nz; }); + }); + const applied: Vec3 = [0, 0, 0]; + for (let v = 0; v < N; v++) { applied[0] += F[v * 3]; applied[1] += F[v * 3 + 1]; applied[2] += F[v * 3 + 2]; } + return { F, applied, areas }; +} + +export function solveStatic(mesh: TetMesh, input: StaticInput, progress: (stage: string, f: number) => void = () => {}, debug?: (m: string) => void): StaticResult { + const t0 = performance.now(); + const X = mesh.nodes, N = X.length / 3; + if (!(input.E > 0) || !(input.nu >= 0 && input.nu < 0.5)) throw new StudyError('The material\'s elastic properties are not valid.'); + if (!input.fixtures.length) throw new StudyError('The study has no fixtures: the part is free to move. Add a fixture to hold it.'); + if (!input.loads.length) throw new StudyError('The study has no loads. Add a force, pressure or gravity.'); + const fixtureOf = new Map(); + const constrained = constraintsOf(mesh, input.fixtures, fixtureOf); + const free = freeMotions(mesh, constrained); + const { F, applied, areas } = loadVector(mesh, input); + const warnings: string[] = []; + // A free rigid motion is acceptable only if the loads do no work on it (a pinned link pulled along its + // length): it is then held by springs too weak to change the result. Otherwise the part would accelerate. + const texts = () => [...new Set(free.map((m) => m.text).filter(Boolean))].join(', '); + if (free.length) { + const modeAt = (m: FreeMotion, v: number) => { + const r = [(X[v * 3] - m.c[0]) / m.L, (X[v * 3 + 1] - m.c[1]) / m.L, (X[v * 3 + 2] - m.c[2]) / m.L]; + return [m.v[0] + m.v[4] * r[2] - m.v[5] * r[1], m.v[1] + m.v[5] * r[0] - m.v[3] * r[2], m.v[2] + m.v[3] * r[1] - m.v[4] * r[0]]; + }; + // The loads' work on the motion against what they could do at most (all of them along it where they act). + const unbalanced = free.some((m) => { + let work = 0, most = 0; + for (let v = 0; v < N; v++) { + if (!m.has(v)) continue; + const f = Math.hypot(F[v * 3], F[v * 3 + 1], F[v * 3 + 2]); + if (!f) continue; + const u = modeAt(m, v); + work += F[v * 3] * u[0] + F[v * 3 + 1] * u[1] + F[v * 3 + 2] * u[2]; + most += f * Math.hypot(u[0], u[1], u[2]); + } + return Math.abs(work) > 1e-3 * most; + }); + if (unbalanced) throw new StudyError(`The fixtures do not hold the part against its loads: it is ${texts()}, and the loads would move it that way (an unstable study). Add fixtures (or change them) so that it cannot move or turn as a rigid body.`); + // What is left of that work comes from the mesh not being exactly symmetric: take it out of the loads. + for (let pass = 0; pass < 2; pass++) for (const m of free) { + let fu = 0, uu = 0; + for (let v = 0; v < N; v++) { if (!m.has(v)) continue; const u = modeAt(m, v); fu += F[v * 3] * u[0] + F[v * 3 + 1] * u[1] + F[v * 3 + 2] * u[2]; uu += u[0] ** 2 + u[1] ** 2 + u[2] ** 2; } + if (!(uu > 0)) continue; + for (let v = 0; v < N; v++) { if (!m.has(v)) continue; const u = modeAt(m, v); for (let c = 0; c < 3; c++) F[v * 3 + c] -= (fu / uu) * u[c]; } + } + applied[0] = applied[1] = applied[2] = 0; + for (let v = 0; v < N; v++) for (let c = 0; c < 3; c++) applied[c] += F[v * 3 + c]; + warnings.push(`The fixtures leave the part ${texts()}; the loads do not push it that way, so it was solved with weak springs holding that motion. Check that this is intended.`); + } + + // ---- assembly ---- + progress('Assembling', 0); + const A = meshPattern(N, mesh.tets, 10); + const { lambda, mu } = lame(input.E, input.nu); + const Ke = new Float64Array(900); + const ne = mesh.tets.length / 10; + const slot = new Int32Array(100); + for (let e = 0; e < ne; e++) { + if (!elementStiffness(X, mesh.tets, e, lambda, mu, Ke)) throw new StudyError('The mesh has an inverted element. Try another mesh size.'); + for (let a = 0; a < 10; a++) for (let b = 0; b < 10; b++) slot[a * 10 + b] = blockAt(A, mesh.tets[e * 10 + a], mesh.tets[e * 10 + b]); + for (let a = 0; a < 10; a++) for (let b = 0; b < 10; b++) { + const q = slot[a * 10 + b] * 9; + for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) A.val[q + i * 3 + j] += Ke[(a * 3 + i) * 30 + b * 3 + j]; + } + if ((e & 4095) === 0) progress('Assembling', e / ne); + } + // Rows of the constrained nodes as assembled, for the reactions. + const reactionRows = new Map(); + for (const v of constrained.keys()) reactionRows.set(v, { cols: A.col.slice(A.rowPtr[v], A.rowPtr[v + 1]), vals: A.val.slice(A.rowPtr[v] * 9, A.rowPtr[v + 1] * 9) }); + const Forig = F.slice(); + + // ---- constraints: each constrained node in its own frame, the constrained directions removed ---- + const R = new Float64Array(N * 9); + const k = new Int8Array(N); + for (let v = 0; v < N; v++) { R[v * 9] = R[v * 9 + 4] = R[v * 9 + 8] = 1; } + for (const [v, dirs] of constrained) k[v] = constraintBasis(dirs, R, v * 9); + const rotated = new Uint8Array(N); + for (const v of constrained.keys()) rotated[v] = k[v] < 3 ? 1 : 0; + const tmp = new Float64Array(9); + for (let i = 0; i < N; i++) { + for (let q = A.rowPtr[i]; q < A.rowPtr[i + 1]; q++) { + const j = A.col[q]; + if (!rotated[i] && !rotated[j] && !k[i] && !k[j]) continue; + const o = q * 9; + if (rotated[i] || rotated[j]) { + // R_i^T A_ij R_j + for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) { + let s = 0; + for (let m = 0; m < 3; m++) for (let l = 0; l < 3; l++) s += R[i * 9 + m * 3 + r] * A.val[o + m * 3 + l] * R[j * 9 + l * 3 + c]; + tmp[r * 3 + c] = s; + } + A.val.set(tmp, o); + } + for (let r = 0; r < k[i]; r++) for (let c = 0; c < 3; c++) A.val[o + r * 3 + c] = 0; + for (let c = 0; c < k[j]; c++) for (let r = 0; r < 3; r++) A.val[o + r * 3 + c] = 0; + } + } + const diagScale = (() => { let s = 0; for (let i = 0; i < N; i++) { const q = blockAt(A, i, i) * 9; s = Math.max(s, A.val[q], A.val[q + 4], A.val[q + 8]); } return s; })(); + if (free.length) { + // Weak springs hold the free motions: on the free directions of the held nodes (they hardly move there), + // or on every node of a piece nothing holds. + const held = (m: FreeMotion) => { for (const v of constrained.keys()) if (m.has(v)) return true; return false; }; + const onHeld = free.every(held); + const ks = diagScale * (onHeld ? 1e-6 : 1e-10); + for (let i = 0; i < N; i++) { + if (onHeld ? !k[i] : false) continue; + const q = blockAt(A, i, i) * 9; + for (let r = k[i]; r < 3; r++) A.val[q + r * 4] += ks; + } + } + for (let i = 0; i < N; i++) { + if (!k[i]) continue; + const q = blockAt(A, i, i) * 9; + for (let r = 0; r < k[i]; r++) A.val[q + r * 4] = diagScale; + const f = [F[i * 3], F[i * 3 + 1], F[i * 3 + 2]]; + for (let r = 0; r < 3; r++) F[i * 3 + r] = r < k[i] ? 0 : R[i * 9 + r] * f[0] + R[i * 9 + 3 + r] * f[1] + R[i * 9 + 6 + r] * f[2]; + } + const tAsm = performance.now(); + + // ---- solve ---- + progress('Preparing the solver', 0); + let M: Preconditioner; + try { + M = smoothedAggregation(A, X, { progress: (f) => progress('Preparing the solver', f), debug, frames: R, held: k }); + } catch { + M = blockJacobi(A); + } + const tSetup = performance.now(); + const Ul = new Float64Array(N * 3); + // Progress: the residual's fall from 1 to the tolerance (it may first rise above 1). + const solved = (rel: number) => Math.max(0, Math.min(0.99, Math.log10(1 / Math.max(rel, 1e-12)) / 9)); + const maxIter = 800; + let res = pcg(A, F, Ul, M, { tol: 1e-9, maxIter, progress: (it, rel) => { if (it % 5 === 0) progress('Solving', solved(rel)); } }); + if (!res.converged && M.levels > 1 && res.iterations < maxIter) { + // The multigrid broke down: fall back on the simple preconditioner (slow, but it does not depend on the + // aggregation). Not when it merely converged slowly: block Jacobi would take far longer to fail too. + M = blockJacobi(A); + res = pcg(A, F, Ul, M, { tol: 1e-9, maxIter: 20000, progress: (it, rel) => { if (it % 25 === 0) progress('Solving', solved(rel)); } }); + } + if (!res.converged && !(res.residual < 1e-5)) { + throw new StudyError(input.nu > 0.49 + ? `The solver did not converge: the material's Poisson's ratio (${input.nu}) is so close to 0.5 that it is nearly incompressible, which this solver cannot handle. Use a Poisson's ratio of 0.49 or less.` + : 'The solver did not converge. The study may be poorly constrained, or the mesh may have very poor elements: try another mesh size.'); + } + const tSolve = performance.now(); + // Back to global directions. + const U = new Float64Array(N * 3); + for (let v = 0; v < N; v++) { + for (let r = 0; r < 3; r++) U[v * 3 + r] = R[v * 9 + r * 3] * Ul[v * 3] + R[v * 9 + r * 3 + 1] * Ul[v * 3 + 1] + R[v * 9 + r * 3 + 2] * Ul[v * 3 + 2]; + } + + // ---- reactions ---- + const reactions: Vec3[] = input.fixtures.map(() => [0, 0, 0]); + for (const [v, row] of reactionRows) { + const r = [-Forig[v * 3], -Forig[v * 3 + 1], -Forig[v * 3 + 2]]; + for (let q = 0; q < row.cols.length; q++) { + const j = row.cols[q] * 3, o = q * 9; + for (let a = 0; a < 3; a++) r[a] += row.vals[o + a * 3] * U[j] + row.vals[o + a * 3 + 1] * U[j + 1] + row.vals[o + a * 3 + 2] * U[j + 2]; + } + // A node held by several fixtures: the reaction along each direction held there (as the constraint frame + // takes them) is shared equally by the fixtures that hold that direction (two fixed fixtures on one face, + // a roller and a fixed face on their common edge), the first one gets what is left (the weak springs' share). + const dirs = constrained.get(v)!, who = fixtureOf.get(v)!; + const own = new Map(); + for (let q = 0; q < dirs.length; q++) { + let b = own.get(who[q]); + if (!b) own.set(who[q], (b = [])); + const d = orthogonalTo(dirs[q], b); + if (d) b.push(d); + } + const basis: Vec3[] = []; + for (let q = 0; q < dirs.length && basis.length < 3; q++) { + const e = orthogonalTo(dirs[q], basis); + if (!e) continue; + basis.push(e); + const c = r[0] * e[0] + r[1] * e[1] + r[2] * e[2]; + const sharers: number[] = []; + for (const [f, b] of own) if (b.reduce((sum, x) => sum + (x[0] * e[0] + x[1] * e[1] + x[2] * e[2]) ** 2, 0) > 0.999) sharers.push(f); + if (!sharers.length) sharers.push(who[q]); + for (const f of sharers) for (let a = 0; a < 3; a++) reactions[f][a] += (c * e[a]) / sharers.length; + for (let a = 0; a < 3; a++) r[a] -= c * e[a]; + } + for (let a = 0; a < 3; a++) reactions[who[0]][a] += r[a]; + } + + // ---- stresses ---- + progress('Computing stresses', 0); + const S = new Float64Array(N * 6), Eps = new Float64Array(N * 6), count = new Float64Array(N); + const strains = new Float64Array(60); + for (let e = 0; e < ne; e++) { + elementNodeStrains(X, mesh.tets, e, U, strains); + for (let a = 0; a < 10; a++) { + const v = mesh.tets[e * 10 + a]; + count[v]++; + for (let c = 0; c < 6; c++) Eps[v * 6 + c] += strains[a * 6 + c]; + } + } + const vonMises = new Float64Array(N), p1 = new Float64Array(N), p2 = new Float64Array(N), p3 = new Float64Array(N), strain = new Float64Array(N); + for (let v = 0; v < N; v++) { + const n = count[v] || 1; + const exx = Eps[v * 6] / n, eyy = Eps[v * 6 + 1] / n, ezz = Eps[v * 6 + 2] / n, exy = Eps[v * 6 + 3] / n, eyz = Eps[v * 6 + 4] / n, ezx = Eps[v * 6 + 5] / n; + const tr = exx + eyy + ezz; + const sxx = lambda * tr + 2 * mu * exx, syy = lambda * tr + 2 * mu * eyy, szz = lambda * tr + 2 * mu * ezz; + const sxy = 2 * mu * exy, syz = 2 * mu * eyz, szx = 2 * mu * ezx; + S.set([sxx, syy, szz, sxy, syz, szx], v * 6); + vonMises[v] = Math.sqrt(0.5 * ((sxx - syy) ** 2 + (syy - szz) ** 2 + (szz - sxx) ** 2) + 3 * (sxy * sxy + syz * syz + szx * szx)); + const pr = principal(sxx, syy, szz, sxy, syz, szx); + p1[v] = pr[0]; p2[v] = pr[1]; p3[v] = pr[2]; + const m = tr / 3; + const dev = (exx - m) ** 2 + (eyy - m) ** 2 + (ezz - m) ** 2 + 2 * (exy * exy + eyz * eyz + ezx * ezx); + strain[v] = Math.sqrt((2 / 3) * dev); + } + const tEnd = performance.now(); + return { + U, vonMises, p1, p2, p3, strain, stress: S, reactions, applied, loadAreas: areas, dofs: N * 3, warnings, + iterations: res.iterations, residual: res.residual, solver: M.description, + ms: { assemble: tAsm - t0, setup: tSetup - tAsm, solve: tSolve - tSetup, stress: tEnd - tSolve }, + }; +} + diff --git a/src/parametric/src/fea/surface.ts b/src/parametric/src/fea/surface.ts new file mode 100644 index 000000000..2655beb2a --- /dev/null +++ b/src/parametric/src/fea/surface.ts @@ -0,0 +1,378 @@ +// The part's boundary as the kernel triangulates it (a closed triangle mesh +// whose triangles know their B-rep face), indexed for the queries the mesher +// needs: which side of the boundary a point is on, where a segment crosses +// it, and the nearest point on it (on any face, on given faces, or on the +// edges between two faces). +// +// Inside tests count crossings of a ray along +x. They are exact in the sense +// that matters: a ray through a shared edge or vertex is counted once, +// because every edge function is evaluated with its end points in one +// canonical order (both triangles get the same number) and zeros are broken +// by a fixed rule (as if the ray were moved by an infinitesimal amount). + +export interface FeaSurfaceData { + /** xyz per vertex (a vertex may repeat, once per face it is on). */ + positions: Float32Array | Float64Array; + /** Three vertex indices per triangle. */ + indices: Uint32Array | Int32Array; + /** B-rep face index of each triangle. */ + triFace: Int32Array; +} + +export interface ClosestHit { + p: [number, number, number]; + tri: number; + d2: number; +} + +const EPS_AREA = 0; + +export class SurfaceIndex { + /** Welded vertices (exact coordinates), xyz. */ + readonly v: Float64Array; + /** Triangles over welded vertices. */ + readonly t: Int32Array; + readonly face: Int32Array; + readonly nt: number; + readonly min: [number, number, number] = [Infinity, Infinity, Infinity]; + readonly max: [number, number, number] = [-Infinity, -Infinity, -Infinity]; + /** Bins of triangles over (y, z) for rays along x. */ + private yz: { y0: number; z0: number; c: number; ny: number; nz: number; start: Int32Array; items: Int32Array }; + /** 3D bins of triangles for segment and nearest point queries. */ + private g: { o: [number, number, number]; c: number; n: [number, number, number]; start: Int32Array; items: Int32Array }; + /** Edges between faces: per face pair key, segments (welded vertex pairs). */ + private seams = new Map(); + /** Welded vertices where three or more faces meet, with their faces. */ + readonly corners: { v: number; faces: number[] }[] = []; + + constructor(data: FeaSurfaceData) { + const P = data.positions, I = data.indices; + const key = new Map(); + const remap = new Int32Array(P.length / 3); + const vs: number[] = []; + for (let i = 0; i < remap.length; i++) { + const x = P[i * 3], y = P[i * 3 + 1], z = P[i * 3 + 2]; + const k = `${x},${y},${z}`; + let id = key.get(k); + if (id === undefined) { id = vs.length / 3; key.set(k, id); vs.push(x, y, z); } + remap[i] = id; + } + this.v = Float64Array.from(vs); + // Triangles that collapse after welding have no area and carry nothing. + const tris: number[] = [], faces: number[] = []; + for (let k = 0; k < I.length / 3; k++) { + const a = remap[I[k * 3]], b = remap[I[k * 3 + 1]], c = remap[I[k * 3 + 2]]; + if (a === b || b === c || a === c) continue; + tris.push(a, b, c); + faces.push(data.triFace[k]); + } + this.t = Int32Array.from(tris); + this.face = Int32Array.from(faces); + this.nt = faces.length; + const V = this.v; + for (let i = 0; i < V.length; i += 3) for (let k = 0; k < 3; k++) { this.min[k] = Math.min(this.min[k], V[i + k]); this.max[k] = Math.max(this.max[k], V[i + k]); } + this.yz = this.buildYz(); + this.g = this.buildGrid(); + this.buildSeams(); + } + + get diag(): number { + return Math.hypot(this.max[0] - this.min[0], this.max[1] - this.min[1], this.max[2] - this.min[2]); + } + + /** Area of each face (by index, up to the largest index present). */ + faceAreas(): number[] { + const out: number[] = []; + for (let k = 0; k < this.nt; k++) { + const f = this.face[k]; + while (out.length <= f) out.push(0); + out[f] += this.triArea(k); + } + return out; + } + + triArea(k: number): number { + const V = this.v, a = this.t[k * 3] * 3, b = this.t[k * 3 + 1] * 3, c = this.t[k * 3 + 2] * 3; + const ux = V[b] - V[a], uy = V[b + 1] - V[a + 1], uz = V[b + 2] - V[a + 2]; + const wx = V[c] - V[a], wy = V[c + 1] - V[a + 1], wz = V[c + 2] - V[a + 2]; + return 0.5 * Math.hypot(uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx); + } + + /** Volume enclosed (divergence theorem; positive when the triangles face outward). */ + volume(): number { + const V = this.v, T = this.t; + let s = 0; + for (let k = 0; k < this.nt; k++) { + const a = T[k * 3] * 3, b = T[k * 3 + 1] * 3, c = T[k * 3 + 2] * 3; + s += V[a] * (V[b + 1] * V[c + 2] - V[b + 2] * V[c + 1]) - V[a + 1] * (V[b] * V[c + 2] - V[b + 2] * V[c]) + V[a + 2] * (V[b] * V[c + 1] - V[b + 1] * V[c]); + } + return s / 6; + } + + // ---------- rays along x ---------- + + private buildYz() { + const V = this.v, T = this.t; + const area = (this.max[1] - this.min[1]) * (this.max[2] - this.min[2]); + const c = Math.max(Math.sqrt(Math.max(area, 1e-12) / Math.max(1, this.nt)) * 2, 1e-9); + const ny = Math.max(1, Math.min(2048, Math.ceil((this.max[1] - this.min[1]) / c) + 1)); + const nz = Math.max(1, Math.min(2048, Math.ceil((this.max[2] - this.min[2]) / c) + 1)); + const cy = Math.max((this.max[1] - this.min[1]) / ny, 1e-12), cz = Math.max((this.max[2] - this.min[2]) / nz, 1e-12); + const cc = Math.max(cy, cz); + const y0 = this.min[1], z0 = this.min[2]; + const nY = Math.max(1, Math.ceil((this.max[1] - y0) / cc) + 1), nZ = Math.max(1, Math.ceil((this.max[2] - z0) / cc) + 1); + const count = new Int32Array(nY * nZ + 1); + const range = (k: number) => { + let ya = Infinity, yb = -Infinity, za = Infinity, zb = -Infinity; + for (let q = 0; q < 3; q++) { const i = T[k * 3 + q] * 3; ya = Math.min(ya, V[i + 1]); yb = Math.max(yb, V[i + 1]); za = Math.min(za, V[i + 2]); zb = Math.max(zb, V[i + 2]); } + return [Math.max(0, Math.floor((ya - y0) / cc)), Math.min(nY - 1, Math.floor((yb - y0) / cc)), Math.max(0, Math.floor((za - z0) / cc)), Math.min(nZ - 1, Math.floor((zb - z0) / cc))]; + }; + for (let k = 0; k < this.nt; k++) { + const [a, b, e, f] = range(k); + for (let j = e; j <= f; j++) for (let i = a; i <= b; i++) count[j * nY + i + 1]++; + } + for (let i = 1; i < count.length; i++) count[i] += count[i - 1]; + const fill = count.slice(); + const items = new Int32Array(count[count.length - 1]); + for (let k = 0; k < this.nt; k++) { + const [a, b, e, f] = range(k); + for (let j = e; j <= f; j++) for (let i = a; i <= b; i++) items[fill[j * nY + i]++] = k; + } + return { y0, z0, c: cc, ny: nY, nz: nZ, start: count, items }; + } + + /** + * Edge function of welded vertices a, b at point (y, z) in the (y, z) projection, + * evaluated with the end points in a fixed order so that both triangles on an edge agree. + */ + private edgeFn(a: number, b: number, y: number, z: number): number { + const V = this.v; + if (a > b) return -this.edgeFn(b, a, y, z); + const ay = V[a * 3 + 1], az = V[a * 3 + 2], by = V[b * 3 + 1], bz = V[b * 3 + 2]; + return (by - ay) * (z - az) - (bz - az) * (y - ay); + } + + /** Whether an edge (a to b, the triangle on its left in (y, z)) owns points exactly on it. */ + private owns(a: number, b: number): boolean { + const V = this.v; + const dy = V[b * 3 + 1] - V[a * 3 + 1], dz = V[b * 3 + 2] - V[a * 3 + 2]; + return dz > 0 || (dz === 0 && dy < 0); + } + + /** + * Where the line {(t, y, z)} crosses the boundary: x values in increasing + * order, with the triangle crossed. Triangles seen edge-on are not crossed. + */ + xCrossings(y: number, z: number): { x: number[]; tri: number[] } { + const g = this.yz; + const i = Math.floor((y - g.y0) / g.c), j = Math.floor((z - g.z0) / g.c); + const xs: number[] = [], ts: number[] = []; + if (i < 0 || j < 0 || i >= g.ny || j >= g.nz) return { x: xs, tri: ts }; + const cell = j * g.ny + i; + const T = this.t, V = this.v; + for (let q = g.start[cell]; q < g.start[cell + 1]; q++) { + const k = g.items[q]; + let a = T[k * 3], b = T[k * 3 + 1], c = T[k * 3 + 2]; + let o = this.edgeFn(a, b, V[c * 3 + 1], V[c * 3 + 2]); + if (o === EPS_AREA) continue; + if (o < 0) { const s = b; b = c; c = s; o = -o; } + const w0 = this.edgeFn(b, c, y, z), w1 = this.edgeFn(c, a, y, z), w2 = this.edgeFn(a, b, y, z); + if (w0 < 0 || w1 < 0 || w2 < 0) continue; + if ((w0 === 0 && !this.owns(b, c)) || (w1 === 0 && !this.owns(c, a)) || (w2 === 0 && !this.owns(a, b))) continue; + const s = w0 + w1 + w2; + if (!(s > 0)) continue; + xs.push((w0 * V[a * 3] + w1 * V[b * 3] + w2 * V[c * 3]) / s); + ts.push(k); + } + const order = xs.map((_, n) => n).sort((p, q) => xs[p] - xs[q]); + return { x: order.map((n) => xs[n]), tri: order.map((n) => ts[n]) }; + } + + /** Whether a point is inside the closed boundary. */ + inside(p: ArrayLike): boolean { + const { x } = this.xCrossings(p[1], p[2]); + let n = 0; + for (const v of x) if (v > p[0]) n++; + return (n & 1) === 1; + } + + // ---------- 3D bins ---------- + + private buildGrid() { + const V = this.v, T = this.t; + const ext = [this.max[0] - this.min[0], this.max[1] - this.min[1], this.max[2] - this.min[2]]; + // About two triangles per occupied cell, bounded in total. + const avgEdge = Math.sqrt((this.faceAreas().reduce((a, b) => a + b, 0) / Math.max(1, this.nt)) * 2); + let c = Math.max(avgEdge * 1.5, this.diag / 400, 1e-9); + while ((ext[0] / c + 1) * (ext[1] / c + 1) * (ext[2] / c + 1) > 8e6) c *= 1.5; + const o: [number, number, number] = [this.min[0] - c * 0.5, this.min[1] - c * 0.5, this.min[2] - c * 0.5]; + const n: [number, number, number] = [Math.ceil(ext[0] / c) + 2, Math.ceil(ext[1] / c) + 2, Math.ceil(ext[2] / c) + 2]; + const range = (k: number) => { + const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity]; + for (let q = 0; q < 3; q++) for (let d = 0; d < 3; d++) { const v = V[T[k * 3 + q] * 3 + d]; lo[d] = Math.min(lo[d], v); hi[d] = Math.max(hi[d], v); } + return [0, 1, 2].flatMap((d) => [Math.max(0, Math.floor((lo[d] - o[d]) / c)), Math.min(n[d] - 1, Math.floor((hi[d] - o[d]) / c))]); + }; + const count = new Int32Array(n[0] * n[1] * n[2] + 1); + for (let k = 0; k < this.nt; k++) { + const r = range(k); + for (let z = r[4]; z <= r[5]; z++) for (let y = r[2]; y <= r[3]; y++) for (let x = r[0]; x <= r[1]; x++) count[(z * n[1] + y) * n[0] + x + 1]++; + } + for (let i = 1; i < count.length; i++) count[i] += count[i - 1]; + const fill = count.slice(); + const items = new Int32Array(count[count.length - 1]); + for (let k = 0; k < this.nt; k++) { + const r = range(k); + for (let z = r[4]; z <= r[5]; z++) for (let y = r[2]; y <= r[3]; y++) for (let x = r[0]; x <= r[1]; x++) items[fill[(z * n[1] + y) * n[0] + x]++] = k; + } + return { o, c, n, start: count, items }; + } + + /** Calls fn with each triangle whose bins meet the box (a triangle may come more than once). */ + private eachNear(lo: ArrayLike, hi: ArrayLike, fn: (k: number) => void) { + const g = this.g; + const r = [0, 1, 2].flatMap((d) => [Math.max(0, Math.floor((lo[d] - g.o[d]) / g.c)), Math.min(g.n[d] - 1, Math.floor((hi[d] - g.o[d]) / g.c))]); + for (let z = r[4]; z <= r[5]; z++) for (let y = r[2]; y <= r[3]; y++) for (let x = r[0]; x <= r[1]; x++) { + const cell = (z * g.n[1] + y) * g.n[0] + x; + for (let q = g.start[cell]; q < g.start[cell + 1]; q++) fn(g.items[q]); + } + } + + /** + * Where the segment p-q crosses the boundary: the parameter t in (0, 1) and + * the triangle, the crossing nearest to p; null when none is found. + */ + segmentHit(p: ArrayLike, q: ArrayLike): { t: number; tri: number } | null { + const lo = [Math.min(p[0], q[0]), Math.min(p[1], q[1]), Math.min(p[2], q[2])]; + const hi = [Math.max(p[0], q[0]), Math.max(p[1], q[1]), Math.max(p[2], q[2])]; + const dx = q[0] - p[0], dy = q[1] - p[1], dz = q[2] - p[2]; + const V = this.v, T = this.t; + let best: { t: number; tri: number } | null = null; + this.eachNear(lo, hi, (k) => { + const a = T[k * 3] * 3, b = T[k * 3 + 1] * 3, c = T[k * 3 + 2] * 3; + const e1x = V[b] - V[a], e1y = V[b + 1] - V[a + 1], e1z = V[b + 2] - V[a + 2]; + const e2x = V[c] - V[a], e2y = V[c + 1] - V[a + 1], e2z = V[c + 2] - V[a + 2]; + const px = dy * e2z - dz * e2y, py = dz * e2x - dx * e2z, pz = dx * e2y - dy * e2x; + const det = e1x * px + e1y * py + e1z * pz; + if (det === 0) return; + const inv = 1 / det; + const sx = p[0] - V[a], sy = p[1] - V[a + 1], sz = p[2] - V[a + 2]; + const u = (sx * px + sy * py + sz * pz) * inv; + if (u < -1e-12 || u > 1 + 1e-12) return; + const qx = sy * e1z - sz * e1y, qy = sz * e1x - sx * e1z, qz = sx * e1y - sy * e1x; + const v = (dx * qx + dy * qy + dz * qz) * inv; + if (v < -1e-12 || u + v > 1 + 1e-12) return; + const t = (e2x * qx + e2y * qy + e2z * qz) * inv; + if (t < 0 || t > 1) return; + if (!best || t < best.t) best = { t, tri: k }; + }); + return best; + } + + /** Nearest point of triangle k to p. */ + closestOnTri(k: number, p: ArrayLike): [number, number, number] { + const V = this.v, T = this.t; + const a = T[k * 3] * 3, b = T[k * 3 + 1] * 3, c = T[k * 3 + 2] * 3; + return closestOnTriangle(p, V[a], V[a + 1], V[a + 2], V[b], V[b + 1], V[b + 2], V[c], V[c + 1], V[c + 2]); + } + + /** + * Nearest point on the boundary within radius r of p (on the given faces + * only, if any), or null when there is none that close. + */ + closest(p: ArrayLike, r: number, faces?: ReadonlySet | null): ClosestHit | null { + let best: ClosestHit | null = null; + let lim = r * r; + this.eachNear([p[0] - r, p[1] - r, p[2] - r], [p[0] + r, p[1] + r, p[2] + r], (k) => { + if (faces && !faces.has(this.face[k])) return; + const c = this.closestOnTri(k, p); + const d2 = (c[0] - p[0]) ** 2 + (c[1] - p[1]) ** 2 + (c[2] - p[2]) ** 2; + if (d2 <= lim && (!best || d2 < best.d2)) { best = { p: c, tri: k, d2 }; lim = d2; } + }); + return best; + } + + // ---------- face boundaries ---------- + + private buildSeams() { + const T = this.t; + const edgeFaces = new Map(); + const nv = this.v.length / 3; + const vertFaces: Set[] = []; + for (let k = 0; k < this.nt; k++) { + for (let q = 0; q < 3; q++) { + const a = T[k * 3 + q], b = T[k * 3 + (q + 1) % 3]; + const key = Math.min(a, b) * nv + Math.max(a, b); + let l = edgeFaces.get(key); + if (!l) edgeFaces.set(key, (l = [])); + l.push(this.face[k]); + (vertFaces[a] ??= new Set()).add(this.face[k]); + } + } + for (const [key, fs] of edgeFaces) { + const uniq = [...new Set(fs)]; + if (uniq.length < 2) continue; + const a = Math.floor(key / nv), b = key - a * nv; + for (let i = 0; i < uniq.length; i++) for (let j = i + 1; j < uniq.length; j++) { + const pk = pairKey(uniq[i], uniq[j]); + let l = this.seams.get(pk); + if (!l) this.seams.set(pk, (l = [])); + l.push(a, b); + } + } + vertFaces.forEach((s, v) => { if (s && s.size >= 3) this.corners.push({ v, faces: [...s] }); }); + } + + /** Whether faces a and b share an edge. */ + adjacent(a: number, b: number): boolean { + return this.seams.has(pairKey(a, b)); + } + + /** Nearest point on the edge between faces a and b (squared distance), or null if they do not meet. */ + closestOnSeam(a: number, b: number, p: ArrayLike): { p: [number, number, number]; d2: number } | null { + const segs = this.seams.get(pairKey(a, b)); + if (!segs) return null; + const V = this.v; + let best: [number, number, number] | null = null, bd = Infinity; + for (let i = 0; i < segs.length; i += 2) { + const s = segs[i] * 3, e = segs[i + 1] * 3; + const dx = V[e] - V[s], dy = V[e + 1] - V[s + 1], dz = V[e + 2] - V[s + 2]; + const l2 = dx * dx + dy * dy + dz * dz; + let t = l2 > 0 ? ((p[0] - V[s]) * dx + (p[1] - V[s + 1]) * dy + (p[2] - V[s + 2]) * dz) / l2 : 0; + t = Math.max(0, Math.min(1, t)); + const c: [number, number, number] = [V[s] + dx * t, V[s + 1] + dy * t, V[s + 2] + dz * t]; + const d2 = (c[0] - p[0]) ** 2 + (c[1] - p[1]) ** 2 + (c[2] - p[2]) ** 2; + if (d2 < bd) { bd = d2; best = c; } + } + return best ? { p: best, d2: bd } : null; + } + + vertex(i: number): [number, number, number] { + return [this.v[i * 3], this.v[i * 3 + 1], this.v[i * 3 + 2]]; + } +} + +const pairKey = (a: number, b: number) => (a < b ? `${a}|${b}` : `${b}|${a}`); + +/** Nearest point of triangle abc to p (Ericson, Real-Time Collision Detection 5.1.5). */ +export function closestOnTriangle(p: ArrayLike, ax: number, ay: number, az: number, bx: number, by: number, bz: number, cx: number, cy: number, cz: number): [number, number, number] { + const abx = bx - ax, aby = by - ay, abz = bz - az; + const acx = cx - ax, acy = cy - ay, acz = cz - az; + const apx = p[0] - ax, apy = p[1] - ay, apz = p[2] - az; + const d1 = abx * apx + aby * apy + abz * apz, d2 = acx * apx + acy * apy + acz * apz; + if (d1 <= 0 && d2 <= 0) return [ax, ay, az]; + const bpx = p[0] - bx, bpy = p[1] - by, bpz = p[2] - bz; + const d3 = abx * bpx + aby * bpy + abz * bpz, d4 = acx * bpx + acy * bpy + acz * bpz; + if (d3 >= 0 && d4 <= d3) return [bx, by, bz]; + const vc = d1 * d4 - d3 * d2; + if (vc <= 0 && d1 >= 0 && d3 <= 0) { const v = d1 / (d1 - d3); return [ax + abx * v, ay + aby * v, az + abz * v]; } + const cpx = p[0] - cx, cpy = p[1] - cy, cpz = p[2] - cz; + const d5 = abx * cpx + aby * cpy + abz * cpz, d6 = acx * cpx + acy * cpy + acz * cpz; + if (d6 >= 0 && d5 <= d6) return [cx, cy, cz]; + const vb = d5 * d2 - d1 * d6; + if (vb <= 0 && d2 >= 0 && d6 <= 0) { const w = d2 / (d2 - d6); return [ax + acx * w, ay + acy * w, az + acz * w]; } + const va = d3 * d6 - d5 * d4; + if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { const w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); return [bx + (cx - bx) * w, by + (cy - by) * w, bz + (cz - bz) * w]; } + const denom = 1 / (va + vb + vc); + const v = vb * denom, w = vc * denom; + return [ax + abx * v + acx * w, ay + aby * v + acy * w, az + abz * v + acz * w]; +} diff --git a/src/parametric/src/fea/worker.ts b/src/parametric/src/fea/worker.ts new file mode 100644 index 000000000..59e04bfbe --- /dev/null +++ b/src/parametric/src/fea/worker.ts @@ -0,0 +1,52 @@ +/// +// Stress analysis worker: meshes the part and solves studies away from the +// interface. It keeps the last mesh, so a study changed without changing the +// part or the mesh size is solved again without meshing. + +import { MeshError, type TetMesh, meshWalls } from './mesher'; +import { type StaticInput, StudyError, solveStatic } from './static'; +import { SurfaceIndex, type FeaSurfaceData } from './surface'; +import { type FeaMeshInfo, type FeaSolution, meshView, solutionOf } from './results'; + +declare const self: DedicatedWorkerGlobalScope; + +export type FeaWorkerRequest = + /** min: the smallest element size to go down to where the walls are thinner than size. */ + | { id: number; type: 'mesh'; surface: FeaSurfaceData; size: number; min?: number } + | { id: number; type: 'solve'; input: StaticInput }; + +export type FeaWorkerResponse = + /** Sent once when the worker's code has loaded. */ + | { id: 0; type: 'ready' } + | { id: number; type: 'progress'; stage: string; value: number } + | { id: number; type: 'done'; result: unknown } + | { id: number; type: 'error'; error: string; user: boolean }; + +let mesh: TetMesh | null = null; +let viewMap: Int32Array | null = null; + +self.postMessage({ id: 0, type: 'ready' } satisfies FeaWorkerResponse); + +self.onmessage = (ev: MessageEvent) => { + const msg = ev.data; + const progress = (stage: string, value: number) => self.postMessage({ id: msg.id, type: 'progress', stage, value } satisfies FeaWorkerResponse); + try { + if (msg.type === 'mesh') { + mesh = null; + const surf = new SurfaceIndex(msg.surface); + mesh = meshWalls(surf, { size: msg.size, min: msg.min ?? msg.size, progress }); + const v = meshView(mesh); + viewMap = v.map; + const info: FeaMeshInfo = v.info; + self.postMessage({ id: msg.id, type: 'done', result: info } satisfies FeaWorkerResponse, [info.nodes.buffer, info.tris.buffer, info.triFace.buffer, info.lines.buffer] as ArrayBuffer[]); + return; + } + if (!mesh || !viewMap) throw new StudyError('Mesh the part first.'); + const res = solveStatic(mesh, msg.input, progress); + const sol: FeaSolution = solutionOf(mesh, viewMap, res, msg.input); + self.postMessage({ id: msg.id, type: 'done', result: sol } satisfies FeaWorkerResponse, sol.fields.map((f) => f.buffer) as ArrayBuffer[]); + } catch (e) { + const user = e instanceof StudyError || e instanceof MeshError; + self.postMessage({ id: msg.id, type: 'error', error: (e as Error).message ?? String(e), user } satisfies FeaWorkerResponse); + } +}; diff --git a/src/parametric/src/kernel/assembly.ts b/src/parametric/src/kernel/assembly.ts index f5dd43208..2ab885be1 100644 --- a/src/parametric/src/kernel/assembly.ts +++ b/src/parametric/src/kernel/assembly.ts @@ -80,7 +80,12 @@ export type AsmRequest = | { op: 'build'; parts: AsmPartBuild[] } | { op: 'scene'; items: AsmSceneItem[] } | { op: 'drop'; keep: string[] } - | { op: 'interference' } + /** + * groups: a group per scene item; pairs in one group are not checked (they did not + * move relative to each other since a check the caller keeps). mesh: false leaves + * out the meshes of the shared solids. + */ + | { op: 'interference'; groups?: number[]; mesh?: boolean } /** 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). */ @@ -108,9 +113,7 @@ export class AssemblyBuilder { 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; } }); + const cones = coneAxes(res); 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(); @@ -314,7 +317,7 @@ export class AssemblyBuilder { * 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[] { + interference(opts: { groups?: number[]; mesh?: boolean } = {}): InterferencePair[] { const list = this.bodies().map((b) => ({ ...b, box: bbox(b.shape) })); const all = this.combined(); const ab = all ? bbox(all) : null; @@ -324,6 +327,7 @@ export class AssemblyBuilder { 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 (opts.groups && opts.groups[A.i] === opts.groups[B.i]) continue; if (!A.box || !B.box || !boxesOverlap(A.box, B.box)) continue; let shared: Sh, v: number; try { @@ -335,7 +339,7 @@ export class AssemblyBuilder { } 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) }); + out.push({ a: A.i, b: B.i, volume: v, mesh: opts.mesh === false ? null : meshOf(shared, diag) }); } } return out; @@ -448,21 +452,19 @@ export function place(shape: Sh, m: number[]): Sh { } } -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(); - } +/** + * The axes of a part's conical faces (by face index), from a circular edge of + * each (this OpenCascade build cannot give a cone's own axis: its gp_Cone is + * not bound). + */ +function coneAxes(res: BuildResult): AsmPartResult['cones'] { + const cones: AsmPartResult['cones'] = {}; + res.faces.forEach((f, i) => { + if (f.type !== 'cone') return; + const e = res.edges.find((x) => x.type === 'circle' && x.center && x.axis && x.faces.includes(i)); + if (e) cones[i] = { p: e.center!, d: e.axis! }; + }); + return cones; } function boxesOverlap(a: { min: Vec3; max: Vec3 }, b: { min: Vec3; max: Vec3 }): boolean { diff --git a/src/parametric/src/kernel/build.ts b/src/parametric/src/kernel/build.ts index 7282147cd..4ab3c2867 100644 --- a/src/parametric/src/kernel/build.ts +++ b/src/parametric/src/kernel/build.ts @@ -28,7 +28,7 @@ import { hasExternal, resolveExternal } from '../sketch/external'; import { solveSketch } from '../sketch/solver'; import { measureDimension } from '../sketch/ops'; import type { - BuildRequest, BuildResult, EdgeInfo, FaceInfo, FeatureStatus, FlatPatternResult, MassProperties, MeasureResult, MeasureTarget, MeshData, + BuildRequest, BuildResult, EdgeInfo, FaceInfo, FeaFaceSurface, FeaSurface, FeatureStatus, FlatPatternResult, MassProperties, MeasureResult, MeasureTarget, MeshData, ProjectionRequest, ProjectionResult, WeldVolumes, } from './protocol'; import { type WeldCtx, type WeldState, applyEndCap, applyGusset, applyStructuralMember, applyTrimExtend, applyWeldBead } from './weldments'; @@ -1808,6 +1808,33 @@ export class ModelBuilder { } } + /** + * The solid's boundary triangulated for the stress analysis mesher: each + * triangle with the index of its face (as in the build result's faces), + * at a chordal tolerance (mm), with the solid's exact volume. + */ + feaSurface(tolerance: number): FeaSurface { + const st = this.current; + if (!st.body) throw new FeatureError('The part has no solid body to analyze.'); + const b = boxOf(st.body); + const tol = Math.max(tolerance, (b ? dist(b.min, b.max) : 1) * 2e-5); + const m = meshShape(st.body, tol, 0.15); + const faceIndex = new ShapeIndex(st.faces.map((f) => f.shape)); + const triFace = new Int32Array(m.indices.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], hash = m.faceGroups[g + 2]; + const cands = faceIndex.findHash(hash); + const fi = cands.find((c) => !claimed.has(c)) ?? cands[0] ?? -1; + claimed.add(fi); + for (let t = start; t < start + count; t += 3) triFace[t / 3] = fi; + } + // The circular edges of each face (the axes of its surfaces of revolution). + const circles: EdgeDesc[][] = []; + for (const e of this.edgesOf(st)) if (e.desc.type === 'circle') for (const fi of e.faces) (circles[fi] ??= []).push(e.desc); + return { positions: m.positions, indices: m.indices, triFace, volume: volumeOf(st.body), faceNames: st.faces.map((f) => f.name), surfaces: st.faces.map((f, i) => feaFaceSurface(f.desc, circles[i] ?? [])) }; + } + exportBrep(): string { const body = this.current.body; if (!body) throw new FeatureError('There is no geometry to export'); @@ -2197,3 +2224,17 @@ export function eigenSym3(m: number[]): { moments: Vec3; axes: [Vec3, Vec3, Vec3 return { moments, axes }; } + +/** + * A face's surface for the stress analysis (see FeaFaceSurface): a plane, a sphere or a surface of + * revolution (a cone, a torus or other, its axis read from a circular edge of the face: this build of + * OpenCascade cannot give a cone's or a torus's axis). + */ +function feaFaceSurface(d: SurfDesc, circles: EdgeDesc[]): FeaFaceSurface { + if (d.type === 'plane') return { kind: 'plane', n: d.d }; + if (d.type === 'sphere') return { kind: 'sphere', c: d.p }; + if (d.type === 'cylinder') return { kind: 'revolution', p: d.p, d: d.d, cylinder: true }; + if (d.type !== 'cone' && d.type !== 'torus' && d.type !== 'revolution') return null; + const c = circles.find((e) => e.center && e.axis); + return c ? { kind: 'revolution', p: c.center!, d: c.axis!, cylinder: false } : null; +} diff --git a/src/parametric/src/kernel/client.ts b/src/parametric/src/kernel/client.ts index 5c25eea65..60b1c6b50 100644 --- a/src/parametric/src/kernel/client.ts +++ b/src/parametric/src/kernel/client.ts @@ -10,7 +10,7 @@ import type { SolidWorksImport } from '../formats/sldprt'; import type { Id } from '../model/types'; import type { AsmPartBuild, AsmRequest, AsmSceneItem } from './assembly'; -import type { BuildRequest, BuildResult, FlatPatternResult, MassProperties, MeasureResult, MeasureTarget, MeshData, ProjectionRequest, ProjectionResult, WeldVolumes, WorkerRequest, WorkerResponse } from './protocol'; +import type { BuildRequest, BuildResult, FeaSurface, 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'] }; @@ -291,6 +291,11 @@ export class KernelClient { return this.call({ type: 'export', format, quality, name }); } + /** The solid's boundary for the stress analysis mesher (see ModelBuilder.feaSurface). */ + feaSurface(tolerance: number): Promise { + return this.call({ type: 'feaSurface', tolerance }); + } + exportBrep(): Promise { return this.call({ type: 'export', format: 'brep', quality: 1 }); } diff --git a/src/parametric/src/kernel/protocol.ts b/src/parametric/src/kernel/protocol.ts index 077a4e4af..d6f25a683 100644 --- a/src/parametric/src/kernel/protocol.ts +++ b/src/parametric/src/kernel/protocol.ts @@ -184,6 +184,25 @@ export interface ProjectionResult { cutGroups?: number[]; } +/** + * A face's surface where the stress analysis can use it (a roller holds it along the true normal): a + * plane's outward normal, a sphere's centre, the axis of a surface of revolution (`cylinder` for a cylinder). + */ +export type FeaFaceSurface = { kind: 'plane'; n: Vec3 } | { kind: 'sphere'; c: Vec3 } | { kind: 'revolution'; p: Vec3; d: Vec3; cylinder: boolean } | null; + +/** The solid's boundary triangulated for the stress analysis mesher (see ModelBuilder.feaSurface). */ +export interface FeaSurface { + positions: Float32Array; + indices: Uint32Array; + /** Face of each triangle: an index into the build result's faces. */ + triFace: Int32Array; + /** Exact volume of the solid (mm^3). */ + volume: number; + faceNames: string[]; + /** The surface of each face (by index, as triFace). */ + surfaces: FeaFaceSurface[]; +} + export type WorkerRequest = | { id: number; type: 'init' } | { id: number; type: 'reset' } @@ -200,6 +219,8 @@ export type WorkerRequest = | { 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 } + /** The solid's boundary for the stress analysis mesher, at a chordal tolerance (mm). */ + | { id: number; type: 'feaSurface'; tolerance: number } | { 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 } diff --git a/src/parametric/src/kernel/worker.ts b/src/parametric/src/kernel/worker.ts index c8698f52c..d3d6136f1 100644 --- a/src/parametric/src/kernel/worker.ts +++ b/src/parametric/src/kernel/worker.ts @@ -130,12 +130,18 @@ async function handle(ev: MessageEvent) { : 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() + : r.op === 'interference' ? assembly.interference({ groups: r.groups, mesh: r.mesh }) : 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 'feaSurface': { + if (assembly.active) throw new Error('Stress analysis works on parts.'); + const res = builder.feaSurface(msg.tolerance); + reply({ id: msg.id, ok: true, result: res }, [res.positions.buffer, res.indices.buffer, res.triFace.buffer] as ArrayBuffer[]); + return; + } case 'checkImport': reply({ id: msg.id, ok: true, result: await checkStep(msg.text) }); return; diff --git a/src/parametric/src/main.ts b/src/parametric/src/main.ts index ca0356de1..779148d57 100644 --- a/src/parametric/src/main.ts +++ b/src/parametric/src/main.ts @@ -3,6 +3,7 @@ import { App } from './app/app'; import { makeHooks, registerCommands } from './app/actions'; import { installAssembly } from './app/assembly'; import { installCam } from './app/cam'; +import { installFea } from './app/fea'; import { FileOps } from './app/fileops'; import { StartScreen, bindAccountMenu, bindUserMenu, refreshAccount } from './app/start'; import { TaskPane, recentItems } from './app/taskpane'; @@ -34,6 +35,7 @@ async function boot() { const hooks = makeHooks(app); installAssembly(app, files, hooks); installCam(app, hooks); + installFea(app, 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 index b13edd53d..790364adf 100644 --- a/src/parametric/src/model/assembly.ts +++ b/src/parametric/src/model/assembly.ts @@ -58,12 +58,25 @@ export interface AsmComponent { suppressed?: boolean; } -export type MateType = 'coincident' | 'parallel' | 'perpendicular' | 'distance' | 'angle' | 'concentric' | 'tangent' | 'lock'; +export type MateType = 'coincident' | 'parallel' | 'perpendicular' | 'distance' | 'angle' | 'concentric' | 'tangent' | 'lock' | MechanicalMateType; + +/** + * Mechanical mates. A hinge is concentric and coincident in one; width and + * slot take two entities on a side. Gear, rack and pinion and screw couple + * how far one component turns to how far another turns or slides: they + * relate motions, not positions, so they hold from wherever the components + * are when they are added (see the solver). + */ +export type MechanicalMateType = 'hinge' | 'slider' | 'gear' | 'rackPinion' | 'screw' | 'width' | 'slot' | 'cam' | 'universal'; +export const MECHANICAL_MATES: readonly MechanicalMateType[] = ['hinge', 'slider', 'gear', 'rackPinion', 'screw', 'width', 'slot', 'cam', 'universal']; +export const isMechanical = (t: MateType): t is MechanicalMateType => (MECHANICAL_MATES as readonly string[]).includes(t); /** 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 } + /** A vertex of a component, in its part's coordinates (cam followers). */ + | { comp: Id; point: Vec3 } | { comp: Id } | { plane: BasePlane }; @@ -80,8 +93,84 @@ export interface Mate { /** 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. */ + /** + * Lock mates: where b sits in a's frame. Hinges with angle limits: where b + * sat in a's frame at 0°. Sliders: where b sat when added (their turn is + * held, their travel measured from there). Universal joints: where the + * shafts were when added (the yokes' directions are taken from it). + */ rel?: Placement; + /** + * The second pair of entities: a hinge's coincident faces (a2 on a's + * component, b2 on b's), a width mate's groove (a, a2) and tab (b, b2) + * faces, a slot's two end faces (a, a2; b is the pin), a slider's second + * planar face on each component. + */ + a2?: MateRef; + b2?: MateRef; + /** Hinge, slider: alignment of the second pair (aligned is that of the first). */ + aligned2?: boolean; + /** Cam: the profile's faces after a (all on a's component); b is the follower. */ + chain?: FaceRef[]; + /** + * Distance and angle mates: the entities move freely between these values + * (value is where they were set up). Hinges: the turn from where the hinge + * was added (rel), in degrees. + */ + limit?: { min: Param; max: Param }; + /** Gear: b's pitch diameter (value is a's), or b's part of the ratio. */ + value2?: Param; + /** + * Gear: 'ratio' when the values are a ratio rather than pitch diameters. + * Rack and pinion: 'revolution' when value is the rack's travel per turn + * rather than the pinion's pitch diameter. Universal joint: 'point' when + * the shafts' axes meet at a joint point, value along a's axis from its + * entity. + */ + by?: 'ratio' | 'revolution' | 'point'; + /** Gear, rack and pinion: the other way round. Screw: a left-hand thread. Cam: the flat follower's other side. */ + reverse?: boolean; +} + +/** What a motor does over time: a constant speed, a back and forth (sine), or a ramp between two values. */ +export type MotionProfile = 'constant' | 'oscillate' | 'ramp'; + +/** + * A motor of a motion study. Rotary motors turn a component about an axis, + * linear motors move it along a direction (both taken from a face or edge; + * the component is that of the entity); a mate driver changes the value of + * a distance or angle mate. Values are in mm, degrees and seconds. + */ +export interface MotionMotor { + id: Id; + name: string; + kind: 'rotary' | 'linear' | 'mate'; + /** Rotary and linear: the axis or direction, on the component it moves (or `mate`). */ + ref?: MateRef; + /** Mate driver: the distance or angle mate. Rotary: a hinge it turns; linear: a slider it moves (b relative to a). */ + mate?: Id; + profile: MotionProfile; + /** Constant: speed (mm/s, deg/s, or rpm when `rpm`). */ + speed?: Param; + rpm?: boolean; + /** Oscillate: amplitude (mm or degrees) and frequency (Hz). */ + amplitude?: Param; + frequency?: Param; + /** Ramp (mate drivers): the value at the start and at the end of the study. */ + from?: Param; + to?: Param; + reverse?: boolean; + suppressed?: boolean; +} + +export interface MotionStudy { + id: Id; + name: string; + /** Seconds. */ + duration: number; + /** Frames computed per second. */ + fps: number; + motors: MotionMotor[]; } export interface ExplodeStep { @@ -103,11 +192,14 @@ export interface AssemblyDocument extends Omit = { coincident: 'Coincident', parallel: 'Parallel', perpendicular: 'Perpendicular', distance: 'Distance', angle: 'Angle', concentric: 'Concentric', tangent: 'Tangent', lock: 'Lock', + hinge: 'Hinge', slider: 'Slider', gear: 'Gear', rackPinion: 'Rack Pinion', screw: 'Screw', width: 'Width', slot: 'Slot', cam: 'Cam', universal: 'Universal Joint', }; /** Distinct component colours, picked in turn for each new part. */ @@ -156,6 +248,8 @@ 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; +/** The most motion studies, motors per study, and frames a study may compute. */ +export const MAX_STUDIES = 100, MAX_MOTORS = 50, MAX_FRAMES = 20000; 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; @@ -175,9 +269,50 @@ function validMateRef(v: unknown, comps: Set): boolean { 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); + if ('point' in v) return isVec(v.point); return true; } +/** The new fields of a mate (limits, second entities, mechanical settings), each only where its type has it. */ +function validMateExtras(m: Record, comps: Set): boolean { + const t = m.type as MateType; + const has = (k: string) => m[k] !== undefined; + const isBool = (k: string) => !has(k) || typeof m[k] === 'boolean'; + if (has('a2') && (!['hinge', 'width', 'slot', 'slider'].includes(t) || !validMateRef(m.a2, comps))) return false; + if (has('b2') && (!['hinge', 'width', 'slider'].includes(t) || !validMateRef(m.b2, comps))) return false; + if (!isBool('aligned2') || !isBool('reverse')) return false; + if (has('value2') && (t !== 'gear' || !isParam(m.value2))) return false; + if (has('limit') && (!['distance', 'angle', 'hinge', 'slider'].includes(t) || !isObj(m.limit) || !isParam(m.limit.min) || !isParam(m.limit.max))) return false; + if (has('by') && !((t === 'gear' && m.by === 'ratio') || (t === 'rackPinion' && m.by === 'revolution') || (t === 'universal' && m.by === 'point'))) return false; + // A cam's other profile faces: faces of its component. + if (has('chain') && (t !== 'cam' || !Array.isArray(m.chain) || m.chain.length > 500 || !m.chain.every(validFaceRef) || !isObj(m.a) || !('face' in m.a))) return false; + // Vertices are followers of cams only. + if ([m.a, m.a2, m.b2, ...(t === 'cam' ? [] : [m.b])].some((r) => isObj(r) && 'point' in r)) return false; + if (!isMechanical(t)) return !has('aligned2') && !has('reverse'); + // What each mechanical mate needs; its entities are faces, edges, vertices or planes (not whole components). + const needs: Record = { + hinge: ['a2', 'b2'], slider: ['rel'], width: ['a2', 'b2'], slot: ['a2'], gear: ['value', 'value2'], rackPinion: ['value'], screw: ['value'], cam: [], universal: ['rel'], + }; + if (needs[t].some((k) => !has(k))) return false; + // A slider takes one entity, or two faces, on each component; a joint point has its offset. + if (t === 'slider' && has('a2') !== has('b2')) return false; + if (t === 'universal' && (m.by === 'point') !== has('value')) return false; + return [m.a, m.b, m.a2, m.b2].every((r) => r === undefined || (isObj(r) && ('plane' in r || 'face' in r || 'edge' in r || 'point' in r))); +} + +function validMotor(v: unknown, comps: Set, mates: Set): boolean { + if (!isObj(v) || !isStr(v.id) || typeof v.name !== 'string' || !['rotary', 'linear', 'mate'].includes(v.kind as string) || !['constant', 'oscillate', 'ramp'].includes(v.profile as string)) return false; + for (const k of ['speed', 'amplitude', 'frequency', 'from', 'to']) if (v[k] !== undefined && !isParam(v[k])) return false; + for (const k of ['rpm', 'reverse', 'suppressed']) if (v[k] !== undefined && typeof v[k] !== 'boolean') return false; + const need = v.profile === 'constant' ? ['speed'] : v.profile === 'oscillate' ? ['amplitude', 'frequency'] : ['from', 'to']; + if (need.some((k) => v[k] === undefined)) return false; + if (v.kind === 'mate') return isStr(v.mate) && mates.has(v.mate) && v.ref === undefined && v.rpm === undefined; + // Rotary and linear motors move the component of a face or edge (or turn a hinge, move a slider), at a constant speed or back and forth. + if (v.profile === 'ramp' || (v.rpm !== undefined && v.kind !== 'rotary')) return false; + if (v.mate !== undefined) return isStr(v.mate) && mates.has(v.mate) && v.ref === undefined; + return isObj(v.ref) && isStr(v.ref.comp) && ('face' in v.ref || 'edge' in v.ref) && validMateRef(v.ref, comps); +} + 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)))); } @@ -227,13 +362,28 @@ export function validateAssembly(raw: unknown): AssemblyDocument { 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'); + if (!validMateExtras(m, compIds)) throw damaged('invalid mate'); ids.add(m.id); } + const mateIds = new Set(mates.map((m) => (m as Mate).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); } + // Motion studies (files from before them have none). + if (d.studies !== undefined && !Array.isArray(d.studies)) throw damaged('invalid motion study'); + const studies = (d.studies ?? []) as unknown[]; + if (studies.length > MAX_STUDIES) throw new Error(`This assembly has ${studies.length} motion studies, more than Parametric can open (at most ${MAX_STUDIES}).`); + for (const s of studies) { + if (!isObj(s) || !isStr(s.id) || ids.has(s.id) || typeof s.name !== 'string' || !isNum(s.duration) || s.duration <= 0 || s.duration > 3600 || !isNum(s.fps) || s.fps < 1 || s.fps > 240 + || s.duration * s.fps > MAX_FRAMES || !Array.isArray(s.motors) || s.motors.length > MAX_MOTORS) throw damaged('invalid motion study'); + ids.add(s.id); + for (const mo of s.motors) { + if (!validMotor(mo, compIds, mateIds) || ids.has((mo as MotionMotor).id)) throw damaged('invalid motor'); + ids.add((mo as MotionMotor).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); @@ -268,6 +418,7 @@ export function validateAssembly(raw: unknown): AssemblyDocument { })).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, + ...(studies.length ? { studies: (studies as MotionStudy[]).map((s) => ({ id: s.id, name: s.name || s.id, duration: s.duration, fps: s.fps, motors: s.motors.map(motorCopy) })) } : {}), ...(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, @@ -302,9 +453,18 @@ export function parseAnyDocument(text: string): PartDocument | AssemblyDocument } } -/** Allocates a new id in an assembly (components, parts, mates, explode steps). */ +/** A motor with only the fields it may have (a file's other fields are dropped). */ +function motorCopy(m: MotionMotor): MotionMotor { + const out: MotionMotor = { id: m.id, name: m.name || m.id, kind: m.kind, profile: m.profile }; + for (const k of ['ref', 'mate', 'speed', 'amplitude', 'frequency', 'from', 'to'] as const) if (m[k] !== undefined) (out as unknown as Record)[k] = structuredClone(m[k]); + for (const k of ['rpm', 'reverse', 'suppressed'] as const) if (m[k] === true) out[k] = true; + return out; +} + +/** Allocates a new id in an assembly (components, parts, mates, explode steps, motion studies and motors). */ 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)]); + const studies = doc.studies ?? []; + 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), ...studies.flatMap((s) => [s.id, ...s.motors.map((m) => m.id)])]); let id: string; do id = `${prefix}${doc.nextId++}`; while (used.has(id)); return id; @@ -331,10 +491,16 @@ export function nextPartColor(doc: AssemblyDocument): string { return PART_COLORS.find((c) => !used.has(c)) ?? PART_COLORS[doc.parts.length % PART_COLORS.length]; } +/** The entities a mate references (its second pair, and a cam's other faces, too). */ +export const mateRefs = (m: Mate): MateRef[] => [ + m.a, m.b, ...(m.a2 ? [m.a2] : []), ...(m.b2 ? [m.b2] : []), + ...(m.chain && 'comp' in m.a ? m.chain.map((face) => ({ comp: (m.a as { comp: Id }).comp, face })) : []), +]; + /** 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); + for (const r of mateRefs(m)) if ('comp' in r && !out.includes(r.comp)) out.push(r.comp); return out; } diff --git a/src/parametric/src/model/document.ts b/src/parametric/src/model/document.ts index a1df14d3b..df138a6a9 100644 --- a/src/parametric/src/model/document.ts +++ b/src/parametric/src/model/document.ts @@ -12,6 +12,8 @@ import { validFeature } from './validate-feature'; import { validSketch } from './validate-sketch'; import { validDrawing } from './validate-drawing'; import { camIds, normalizeCam } from './cam'; +import { normalizeMaterial } from './materials'; +import { parseStudy, studyIds } from './fea'; import { solveSketch } from '../sketch/solver'; import { hasExternal } from '../sketch/external'; @@ -81,14 +83,17 @@ export function parseDocument(text: string): PartDocument { // Times a Date can hold (the drawing's title block shows the modified day). for (const k of ['created', 'modified'] as const) if (!Number.isFinite(doc[k]) || Math.abs(doc[k]) > 8.64e15) doc[k] = base[k]; if (doc.material != null && !(isObj(doc.material) && typeof doc.material.name === 'string' && Number.isFinite(doc.material.density) && doc.material.density > 0)) doc.material = null; + // Elastic properties that are not a complete, valid set are dropped (the material stays). + if (doc.material) doc.material = normalizeMaterial(doc.material); if (doc.drawing != null && !validDrawing(doc.drawing)) throw new Error('The part file is damaged (invalid drawing).'); // Machining data that cannot be read is dropped rather than refusing the part. if (doc.cam != null) doc.cam = normalizeCam(doc.cam); + if (doc.study != null) doc.study = parseStudy(doc.study); for (const f of doc.features) if (typeof f.name !== 'string' || !f.name) f.name = f.id; // New feature ids must not collide with existing ones, even when the file's // counter is missing or stale. let maxId = 0; - for (const f of [...doc.features, ...doc.variables, ...camIds(doc.cam).map((id) => ({ id }))]) { + for (const f of [...doc.features, ...doc.variables, ...camIds(doc.cam).map((id) => ({ id })), ...studyIds(doc.study).map((id) => ({ id }))]) { const m = /^[a-z]+(\d+)$/i.exec(String(f?.id ?? '')); const suffix = m ? Number(m[1]) : NaN; // Unsafe suffixes cannot be emitted by the numeric allocator. diff --git a/src/parametric/src/model/fea.ts b/src/parametric/src/model/fea.ts new file mode 100644 index 000000000..be5b79501 --- /dev/null +++ b/src/parametric/src/model/fea.ts @@ -0,0 +1,204 @@ +// Static stress analysis study kept with the part: fixtures and loads on +// faces (by reference, so they follow the part through dimension changes) +// and the mesh setting. Values are stored in millimetres, newtons, +// megapascals (N/mm^2) and mm/s^2, whatever the display units. Results are +// not stored: they are computed again from the part and the study. + +import type { AxisRef, FaceRef, Id, PartDocument, UnitSystem } from './types'; +import { UNIT_SYSTEMS } from './units'; + +/** A direction: a base axis, a straight edge (or the axis of a circular one), or a face (its normal, or a cylinder's axis). */ +export type FeaDir = Exclude; + +export type FixtureType = 'fixed' | 'roller' | 'hinge'; + +export interface FeaFixture { + id: Id; + name: string; + type: FixtureType; + faces: FaceRef[]; + suppressed?: boolean; +} + +/** A total force spread over the faces: normal to them (dir null, pressing on them) or along a direction. */ +export interface FeaForce { + id: Id; + name: string; + type: 'force'; + faces: FaceRef[]; + /** Newtons. */ + value: number; + dir: FeaDir | null; + flip: boolean; + suppressed?: boolean; +} + +/** A pressure on the faces, pushing into them (flip: pulling). */ +export interface FeaPressure { + id: Id; + name: string; + type: 'pressure'; + faces: FaceRef[]; + /** MPa (N/mm^2). */ + value: number; + flip: boolean; + suppressed?: boolean; +} + +/** The part's own weight: the acceleration of gravity along a direction. */ +export interface FeaGravity { + id: Id; + name: string; + type: 'gravity'; + /** mm/s^2. */ + value: number; + dir: FeaDir; + flip: boolean; + suppressed?: boolean; +} + +export type FeaLoad = FeaForce | FeaPressure | FeaGravity; +export type FeaLoadType = FeaLoad['type']; + +export interface StaticStudy { + id: Id; + name: string; + fixtures: FeaFixture[]; + loads: FeaLoad[]; + /** Mesh fineness from 0 (coarse: twice the automatic element size) to 1 (fine: half of it). */ + mesh: { fineness: number }; +} + +export const FIXTURE_LABELS: Record = { fixed: 'Fixed', roller: 'Roller/Slider', hinge: 'Fixed Hinge' }; +export const LOAD_LABELS: Record = { force: 'Force', pressure: 'Pressure', gravity: 'Gravity' }; +export const FIXTURE_ICONS: Record = { fixed: 'feaFixed', roller: 'feaRoller', hinge: 'feaHinge' }; +export const LOAD_ICONS: Record = { force: 'feaForce', pressure: 'feaPressure', gravity: 'feaGravity' }; + +/** Standard gravity, mm/s^2. */ +export const GRAVITY = 9806.65; + +export function newStudy(id: Id): StaticStudy { + return { id, name: 'Static Study', fixtures: [], loads: [], mesh: { fineness: 0.5 } }; +} + +/** Element size for a fineness, from the automatic size (no larger than the part's walls allow, nor smaller than min). */ +export function elementSizeFor(auto: number, max: number, fineness: number, min = 0): number { + return Math.max(min, Math.min(max, auto * 2 ** (1 - 2 * Math.max(0, Math.min(1, fineness))))); +} + +// ---------- units ---------- + +export interface FeaUnits { + force: string; + /** Newtons per display force unit. */ + forceScale: number; + stress: string; + /** MPa per display stress unit. */ + stressScale: number; + accel: string; + /** mm/s^2 per display acceleration unit. */ + accelScale: number; + length: string; + /** mm per display length unit. */ + lengthScale: number; +} + +export function feaUnits(units: UnitSystem): FeaUnits { + const u = UNIT_SYSTEMS[units]; + if (units === 'IPS') return { force: 'lbf', forceScale: 4.4482216152605, stress: 'psi', stressScale: 0.00689475729316836, accel: 'in/s²', accelScale: 25.4, length: u.length, lengthScale: u.scale }; + return { force: 'N', forceScale: 1, stress: 'MPa', stressScale: 1, accel: 'm/s²', accelScale: 1000, length: u.length, lengthScale: u.scale }; +} + +// ---------- reading files ---------- + +const isObj = (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 vec3 = (v: unknown) => Array.isArray(v) && v.length === 3 && v.every(finite); +const str = (v: unknown): v is string => typeof v === 'string'; + +function faceRefOf(v: unknown): FaceRef | null { + if (!isObj(v) || !str(v.name) || !isObj(v.sig)) return null; + const s = v.sig; + if (!str(s.type) || !vec3(s.c) || !finite(s.area) || (s.n != null && !vec3(s.n))) return null; + return { name: v.name, sig: { type: s.type, c: s.c as FaceRef['sig']['c'], area: s.area, ...(s.n != null ? { n: s.n as FaceRef['sig']['c'] } : {}) } }; +} + +function dirOf(v: unknown): FeaDir | null { + if (!isObj(v)) return null; + if (v.kind === 'base') return v.axis === 'x' || v.axis === 'y' || v.axis === 'z' ? { kind: 'base', axis: v.axis } : null; + if (v.kind === 'face') { const face = faceRefOf(v.face); return face ? { kind: 'face', face } : null; } + if (v.kind === 'edge' && isObj(v.edge) && str(v.edge.name) && isObj(v.edge.sig)) { + const s = v.edge.sig; + if (!str(s.type) || !vec3(s.m) || !finite(s.len)) return null; + return { kind: 'edge', edge: { name: v.edge.name, sig: { type: s.type, m: s.m as [number, number, number], len: s.len } } }; + } + return null; +} + +function facesOf(v: unknown): FaceRef[] | null { + if (!Array.isArray(v)) return null; + const out = v.map(faceRefOf); + return out.every((f): f is FaceRef => !!f) ? out : null; +} + +const bad = (what: string): never => { throw new Error(`The part file is damaged (invalid study: ${what}).`); }; + +/** + * Checks a study read from a file, strictly: anything that is not a study + * as this version writes it is refused with a message (a damaged study is + * not silently changed into another one). + */ +export function parseStudy(raw: unknown): StaticStudy { + if (!isObj(raw) || !str(raw.id) || !raw.id || !str(raw.name)) bad('identity'); + const r = raw as Record; + if (!Array.isArray(r.fixtures) || !Array.isArray(r.loads) || !isObj(r.mesh)) bad('lists'); + const ids = new Set([r.id as string]); + const ident = (o: Record, what: string) => { + if (!str(o.id) || !o.id || ids.has(o.id) || !str(o.name)) bad(`${what} identity`); + ids.add(o.id as string); + if (o.suppressed !== undefined && typeof o.suppressed !== 'boolean') bad(`${what} suppression`); + return { id: o.id as string, name: o.name as string, ...(o.suppressed ? { suppressed: true } : {}) }; + }; + const fixtures = (r.fixtures as unknown[]).map((f): FeaFixture => { + if (!isObj(f)) return bad('fixture'); + const base = ident(f, 'fixture'); + if (f.type !== 'fixed' && f.type !== 'roller' && f.type !== 'hinge') bad('fixture type'); + const faces = facesOf(f.faces) ?? bad('fixture faces'); + return { ...base, type: f.type as FixtureType, faces }; + }); + const loads = (r.loads as unknown[]).map((l): FeaLoad => { + if (!isObj(l)) return bad('load'); + const base = ident(l, 'load'); + // Loads are positive amounts (their direction says which way): the panels never write others. + if (!finite(l.value) || (l.value as number) <= 0) bad('load value'); + if (typeof l.flip !== 'boolean') bad('load direction'); + const value = l.value as number, flip = l.flip as boolean; + if (l.type === 'force') { + const faces = facesOf(l.faces) ?? bad('force faces'); + const dir = l.dir == null ? null : (dirOf(l.dir) ?? bad('force direction')); + return { ...base, type: 'force', faces, value, dir, flip }; + } + if (l.type === 'pressure') return { ...base, type: 'pressure', faces: facesOf(l.faces) ?? bad('pressure faces'), value, flip }; + if (l.type === 'gravity') return { ...base, type: 'gravity', value, dir: dirOf(l.dir) ?? bad('gravity direction'), flip }; + return bad('load type'); + }); + const m = r.mesh as Record; + if (!finite(m.fineness) || m.fineness < 0 || m.fineness > 1) bad('mesh'); + return { id: r.id as string, name: r.name as string, fixtures, loads, mesh: { fineness: m.fineness as number } }; +} + +/** Ids used by a study (so new ids never collide with them). */ +export function studyIds(s: StaticStudy | null | undefined): string[] { + return s ? [s.id, ...s.fixtures.map((f) => f.id), ...s.loads.map((l) => l.id)] : []; +} + +export function studyOf(doc: PartDocument): StaticStudy | null { + return doc.study ?? null; +} + +/** Name for a new fixture or load, as features and CAM operations are named: the label's words run together and the first number not taken ("FixedHinge1"). */ +export function nextStudyName(s: StaticStudy, label: string): string { + const used = new Set([...s.fixtures, ...s.loads].map((x) => x.name.toLowerCase())); + const base = label.replace(/[^A-Za-z]/g, ''); + for (let i = 1; ; i++) if (!used.has(`${base}${i}`.toLowerCase())) return `${base}${i}`; +} diff --git a/src/parametric/src/model/materials.ts b/src/parametric/src/model/materials.ts index 76565d983..50c4e3505 100644 --- a/src/parametric/src/model/materials.ts +++ b/src/parametric/src/model/materials.ts @@ -1,24 +1,77 @@ -// Material presets: name and density (kg/m^3) used for mass properties. +// Material presets: density (kg/m^3) for mass properties, and the elastic +// properties a static stress analysis needs: elastic modulus and yield and +// tensile strength in MPa, Poisson's ratio. Values are typical published +// figures for the grade named (room temperature); real parts vary with +// temper, heat treatment and, for plastics, with moisture and print settings. import type { MaterialRef } from './types'; export const MATERIALS: MaterialRef[] = [ - { name: 'Plain Carbon Steel', density: 7800 }, - { name: 'Stainless Steel (304)', density: 8000 }, - { name: 'Alloy Steel', density: 7700 }, - { name: 'Cast Iron', density: 7200 }, - { name: 'Aluminum 6061', density: 2700 }, - { name: 'Aluminum 7075', density: 2810 }, - { name: 'Brass', density: 8500 }, - { name: 'Copper', density: 8900 }, - { name: 'Titanium (Ti-6Al-4V)', density: 4430 }, - { name: 'ABS', density: 1040 }, - { name: 'PLA', density: 1240 }, - { name: 'PETG', density: 1270 }, - { name: 'Nylon 6/6', density: 1140 }, - { name: 'Acrylic (PMMA)', density: 1190 }, - { name: 'Polycarbonate', density: 1200 }, + { name: 'Plain Carbon Steel', density: 7800, E: 200000, nu: 0.29, yield: 250, uts: 400 }, + { name: 'Stainless Steel (304)', density: 8000, E: 193000, nu: 0.29, yield: 215, uts: 505 }, + { name: 'Alloy Steel', density: 7700, E: 205000, nu: 0.29, yield: 415, uts: 655 }, + { name: 'Cast Iron', density: 7200, E: 110000, nu: 0.26, yield: 200, uts: 200 }, + { name: 'Aluminum 6061', density: 2700, E: 68900, nu: 0.33, yield: 276, uts: 310 }, + { name: 'Aluminum 7075', density: 2810, E: 71700, nu: 0.33, yield: 503, uts: 572 }, + { name: 'Brass', density: 8500, E: 100000, nu: 0.33, yield: 240, uts: 370 }, + { name: 'Copper', density: 8900, E: 117000, nu: 0.34, yield: 70, uts: 220 }, + { name: 'Titanium (Ti-6Al-4V)', density: 4430, E: 113800, nu: 0.34, yield: 880, uts: 950 }, + { name: 'ABS', density: 1040, E: 2200, nu: 0.35, yield: 40, uts: 44 }, + { name: 'PLA', density: 1240, E: 3500, nu: 0.36, yield: 50, uts: 60 }, + { name: 'PETG', density: 1270, E: 2100, nu: 0.38, yield: 50, uts: 53 }, + { name: 'Nylon 6/6', density: 1140, E: 2800, nu: 0.39, yield: 70, uts: 80 }, + { name: 'Acrylic (PMMA)', density: 1190, E: 3200, nu: 0.37, yield: 70, uts: 70 }, + { name: 'Polycarbonate', density: 1200, E: 2400, nu: 0.37, yield: 62, uts: 66 }, + // Wood is anisotropic (stiffer and stronger along the grain several times over): + // an isotropic analysis would mislead, so it has no elastic properties. { name: 'Oak', density: 750 }, { name: 'Pine', density: 510 }, - { name: 'Glass', density: 2500 }, + { name: 'Glass', density: 2500, E: 70000, nu: 0.22, yield: 40, uts: 40 }, ]; + +/** Notes shown with a preset's analysis properties. */ +export const MATERIAL_NOTES: Record = { + 'Cast Iron': 'Brittle (gray iron): no yield point, so its tensile strength stands in for yield.', + ABS: 'Typical values: plastics vary with grade, temperature and moisture.', + PLA: 'Typical values for molded plastic: 3D printed parts are weaker and stiffer along the layers than across them.', + PETG: 'Typical values for molded plastic: 3D printed parts are weaker and stiffer along the layers than across them.', + 'Nylon 6/6': 'Typical dry values: nylon absorbs moisture and becomes softer and weaker.', + 'Acrylic (PMMA)': 'Brittle: its tensile strength stands in for yield. Typical values.', + Polycarbonate: 'Typical values: plastics vary with grade, temperature and moisture.', + Oak: 'Wood is anisotropic: it cannot be analyzed as an isotropic material.', + Pine: 'Wood is anisotropic: it cannot be analyzed as an isotropic material.', + Glass: 'Brittle: its design tensile strength stands in for yield.', +}; + +/** Elastic properties of a material in MPa (E, yield, ultimate) and Poisson's ratio. */ +export interface ElasticProps { + E: number; + nu: number; + yield: number; + uts: number; +} + +/** Whether a value is a usable elastic property set (Poisson's ratio below 0.5: incompressible solids cannot be analyzed this way). */ +export function validElastic(m: Partial): m is ElasticProps { + const pos = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v > 0; + return pos(m.E) && typeof m.nu === 'number' && Number.isFinite(m.nu) && m.nu >= 0 && m.nu < 0.5 && pos(m.yield) && pos(m.uts); +} + +/** + * The elastic properties of the part's material: its own, else those of the + * preset of that name and density (parts saved before materials had them). + * Null when it has none (wood, a custom material without them, no material). + */ +export function elasticOf(m: MaterialRef | null | undefined): ElasticProps | null { + if (!m) return null; + if (validElastic(m)) return { E: m.E, nu: m.nu, yield: m.yield, uts: m.uts }; + if (m.E !== undefined) return null; + const preset = MATERIALS.find((p) => p.name === m.name && p.density === m.density); + return preset && validElastic(preset) ? { E: preset.E, nu: preset.nu, yield: preset.yield, uts: preset.uts } : null; +} + +/** A material read from a file: the elastic properties are kept only as a complete, valid set. */ +export function normalizeMaterial(m: MaterialRef): MaterialRef { + const { E, nu, yield: sy, uts, ...rest } = m; + return validElastic({ E, nu, yield: sy, uts }) ? { ...rest, E, nu, yield: sy, uts } : rest; +} diff --git a/src/parametric/src/model/types.ts b/src/parametric/src/model/types.ts index ce29b8a86..1a9791927 100644 --- a/src/parametric/src/model/types.ts +++ b/src/parametric/src/model/types.ts @@ -6,6 +6,7 @@ import type { Vec2, Vec3, Frame } from '../math/vec'; import type { BaseFlangeFeature, EdgeFlangeFeature, HemFeature, SketchedBendFeature } from './sheetmetal'; import type { CamDoc } from './cam'; +import type { StaticStudy } from './fea'; export type Id = string; @@ -599,6 +600,14 @@ export interface MaterialRef { name: string; /** kg/m^3 */ density: number; + /** + * Elastic properties for stress analysis (all four, or none): elastic modulus, + * yield and ultimate tensile strength in MPa, and Poisson's ratio. + */ + E?: number; + nu?: number; + yield?: number; + uts?: number; } export interface PartDocument { @@ -620,6 +629,8 @@ export interface PartDocument { drawing?: DrawingDoc | null; /** Machining: tools, setups and operations (see model/cam.ts), if any. */ cam?: CamDoc | null; + /** Static stress analysis: fixtures, loads and mesh setting (see model/fea.ts), if any. */ + study?: StaticStudy | null; nextId: number; created: number; modified: number; diff --git a/src/parametric/src/styles/app.css b/src/parametric/src/styles/app.css index 0f324e181..10d4f9fa7 100644 --- a/src/parametric/src/styles/app.css +++ b/src/parametric/src/styles/app.css @@ -251,8 +251,8 @@ a.icon-btn { text-decoration: none; } } .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; } +: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'], .cm-tools[data-tab='analysis']) .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'], .cm-tools[data-tab='analysis']) .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); } @@ -629,8 +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; } + :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'], .cm-tools[data-tab='analysis']) .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'], .cm-tools[data-tab='analysis']) .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; @@ -716,6 +716,18 @@ a.icon-btn { text-decoration: none; } .cam-play { gap: 6px; align-items: center; } .cam-slider { width: 100%; accent-color: var(--accent); } .cam-clock { font-family: var(--font-mono); } +/* Motion studies (assemblies) */ +.kin-play { gap: 6px; align-items: center; } +.kin-slider { width: 100%; accent-color: var(--accent); } +.kin-clock { font-family: var(--font-mono); } +.kin-motor-buttons { gap: 6px; justify-content: flex-end; margin-top: 6px; } +.kin-plot-box { margin: 6px 0; } +.kin-plot { display: block; width: 100%; height: auto; background: var(--panel-2); border: 1px solid var(--border); border-radius: var(--radius-sm); cursor: crosshair; } +.kin-plot-frame { fill: none; stroke: var(--border); } +.kin-plot-zero { stroke: var(--border-strong); stroke-dasharray: 3 3; } +.kin-plot-line { fill: none; stroke: var(--accent); stroke-width: 1.5; stroke-linejoin: round; } +.kin-plot-cursor { stroke: var(--danger); stroke-width: 1; } +.kin-plot-text { fill: var(--text-2); font-size: 9px; font-family: var(--font-mono); } .cam-legend { display: flex; flex-wrap: wrap; gap: 4px 12px; font-size: var(--fs-sm); color: var(--text-2); } .cam-legend span { display: inline-flex; align-items: center; gap: 5px; } .cam-legend i { width: 12px; height: 12px; border-radius: 3px; border: 1px solid var(--border-strong); } @@ -741,3 +753,30 @@ a.icon-btn { text-decoration: none; } .cam-tools, .cam-post { grid-template-columns: minmax(0, 1fr); } .cam-gcode { height: 220px; } } + +/* Stress analysis: result legend, probe pins, panels. */ +.fea-legend { position: absolute; right: 14px; top: 64px; z-index: 2; padding: 8px 10px; background: color-mix(in srgb, var(--panel) 88%, transparent); border: 1px solid var(--border); border-radius: var(--radius); font-size: var(--fs-sm); color: var(--text); pointer-events: none; max-width: 220px; } +.fea-legend-title { font-weight: 600; margin-bottom: 6px; } +.fea-legend-scale { display: flex; gap: 8px; height: 180px; } +.fea-legend-bar { width: 16px; border-radius: 3px; border: 1px solid var(--border-strong); } +.fea-legend-ticks { display: flex; flex-direction: column; justify-content: space-between; font-variant-numeric: tabular-nums; } +.fea-legend-note { margin-top: 6px; color: var(--text-2); } +.fea-pins { position: absolute; inset: 0; pointer-events: none; z-index: 2; overflow: hidden; } +.fea-pin { position: absolute; width: 0; height: 0; } +.fea-pin::before { content: ''; position: absolute; left: -4px; top: -4px; width: 8px; height: 8px; border-radius: 50%; background: var(--text); border: 2px solid var(--panel); } +.fea-pin span { position: absolute; left: 8px; top: -22px; white-space: nowrap; padding: 2px 6px; border-radius: 4px; background: var(--panel); border: 1px solid var(--border-strong); font-size: var(--fs-sm); font-variant-numeric: tabular-nums; } +.fea-probes { display: flex; flex-direction: column; gap: 4px; margin-top: 6px; } +.fea-probe { display: grid; grid-template-columns: 18px auto 1fr; gap: 6px; align-items: baseline; font-variant-numeric: tabular-nums; } +.fea-slider-row { align-items: center; gap: 8px; } +.fea-slider { flex: 1; min-width: 0; } +.fea-stats td.num, .fea-summary td.num, .fea-forces td.num, .fea-solve td.num { text-align: right; font-variant-numeric: tabular-nums; } +.fea-summary th, .fea-forces th, .fea-solve th, .fea-stats th { font-weight: 500; } +.fea-material-props { margin-top: 6px; } +@media (max-width: 760px) { + /* Under the view toolbar: the bottom of the graphics area is under the panel sheet on phones. */ + .fea-legend { top: 52px; right: 8px; max-width: 200px; padding: 6px 8px; } + .fea-legend-title { margin-bottom: 4px; } + .fea-legend-scale { height: 96px; } + .fea-legend-ticks { line-height: 1.15; } + .fea-legend-note { margin-top: 2px; font-size: 11px; } +} diff --git a/src/parametric/tests/assembly-fuzz.test.ts b/src/parametric/tests/assembly-fuzz.test.ts new file mode 100644 index 000000000..aa0344a4f --- /dev/null +++ b/src/parametric/tests/assembly-fuzz.test.ts @@ -0,0 +1,162 @@ +// Random small assemblies (a fixed seed each): plain and mechanical mates with +// limits, gears, racks, screws, slots, width, cams and universal joints between +// 3 to 8 components, one of them grounded. Every one must keep the invariants: +// the degrees of freedom are the rank deficiency of the mates' Jacobian, every +// motion called free keeps the mates (to second order), nothing turns NaN or +// throws, solving again where it was saved changes nothing, and a motion study +// on each hinge or slider stays within every limit and stops with a message. +import { expect, it } from 'vitest'; +import { type Geo, MateSolver, type SolverBody, type SolverMate, applyPlacement, camProfile, mateMeasure, matrixRank, nullSpace, relativePlacement, rotVecQuat } from '../src/assembly/solver'; +import { type MotorInput, computeMotion, profileOf } from '../src/assembly/motion'; +import { type Quat, type Vec3, add, qMul, qNormalize, qRotate, sub, normalize } from '../src/math/vec'; +import type { MateType, Placement } from '../src/model/assembly'; + +function rng(seed: number) { let s = seed >>> 0; return () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; }; } +const Z: Vec3 = [0, 0, 1], X: Vec3 = [1, 0, 0]; +type R = () => number; +const pickOf = (r: R, a: T[]) => a[Math.floor(r() * a.length)]; + +function makeAssembly(seed: number) { + const r = rng(seed); + const nb = 3 + Math.floor(r() * 6); + const bodies: SolverBody[] = [{ id: 'g', fixed: true, placement: { p: [0, 0, 0], q: [0, 0, 0, 1] }, center: [0, 0, 0] }]; + for (let i = 1; i < nb; i++) { + const q = qNormalize([r() - 0.5, r() - 0.5, r() - 0.5, 1 + r()] as Quat); + bodies.push({ id: `b${i}`, fixed: r() < 0.1, placement: { p: [(r() - 0.5) * 80, (r() - 0.5) * 80, (r() - 0.5) * 80], q: r() < 0.5 ? [0, 0, 0, 1] : q }, center: [r() * 10, r() * 10, r() * 10] }); + } + const pl = new Map(bodies.map((b) => [b.id, b.placement])); + const rel = (a: string, b: string) => relativePlacement(pl.get(a)!, pl.get(b)!); + const axis = (p: Vec3 = [0, 0, 0], d: Vec3 = Z, rad = 2): Geo => ({ kind: 'axis', p, d, r: rad, surface: 'cylinder' }); + const plane = (o: Vec3, n: Vec3): Geo => ({ kind: 'plane', o, n }); + const line = (p: Vec3, d: Vec3): Geo => ({ kind: 'line', p, d }); + const mates: SolverMate[] = []; + const nm = 1 + Math.floor(r() * (nb + 2)); + let k = 0; + for (let i = 0; i < nm; i++) { + const ids = bodies.map((b) => b.id); + const a = pickOf(r, ids); + let b = pickOf(r, ids); + if (b === a) b = ids[(ids.indexOf(a) + 1) % ids.length]; + const base = { id: `m${++k}`, aligned: r() < 0.7, value: 0, flip: r() < 0.2 }; + const lim = (lo: number, hi: number) => { const x = lo + r() * (hi - lo), y = lo + r() * (hi - lo); return r() < 0.15 ? { min: x, max: x } : { min: Math.min(x, y), max: Math.max(x, y) }; }; + const t: MateType = pickOf(r, ['coincident', 'concentric', 'distance', 'angle', 'parallel', 'hinge', 'hinge', 'slider', 'gear', 'rackPinion', 'screw', 'width', 'slot', 'cam', 'universal', 'distance', 'angle'] as MateType[]); + const P = (): Vec3 => [Math.round((r() - 0.5) * 20), Math.round((r() - 0.5) * 20), Math.round((r() - 0.5) * 20)]; + const N = (): Vec3 => pickOf(r, [X, Z, [0, 1, 0], [0, 0, -1], [-1, 0, 0]] as Vec3[]); + let m: SolverMate; + switch (t) { + case 'coincident': case 'parallel': m = { ...base, type: t, a: { body: a, geo: plane(P(), N()) }, b: { body: b, geo: plane(P(), N()) } }; break; + case 'concentric': m = { ...base, type: t, a: { body: a, geo: axis(P(), N()) }, b: { body: b, geo: axis(P(), N()) } }; break; + case 'distance': m = { ...base, type: t, value: r() * 30, a: { body: a, geo: r() < 0.5 ? plane(P(), N()) : { kind: 'point', p: P() } }, b: { body: b, geo: r() < 0.5 ? plane(P(), N()) : { kind: 'point', p: P() } }, ...(r() < 0.6 ? { limit: lim(-10, 40) } : {}) }; break; + case 'angle': m = { ...base, type: t, value: r() * 180, a: { body: a, geo: plane(P(), N()) }, b: { body: b, geo: plane(P(), N()) }, ...(r() < 0.6 ? { limit: lim(0, 180) } : {}) }; break; + case 'hinge': m = { ...base, type: t, a: { body: a, geo: axis(P()) }, b: { body: b, geo: axis(P()) }, a2: { body: a, geo: plane([0, 0, 0], Z) }, b2: { body: b, geo: plane([0, 0, 0], [0, 0, -1]) }, aligned2: r() < 0.3, ...(r() < 0.5 ? { rel: rel(a, b), limit: lim(-200, 200) } : {}) }; break; + case 'slider': m = { ...base, type: t, rel: rel(a, b), a: { body: a, geo: line(P(), X) }, b: { body: b, geo: line(P(), X) }, ...(r() < 0.5 ? { limit: lim(-30, 30) } : {}) }; break; + case 'gear': m = { ...base, type: t, value: 5 + r() * 40, value2: 5 + r() * 40, reverse: r() < 0.3, a: { body: a, geo: axis(P()) }, b: { body: b, geo: axis(P(), r() < 0.3 ? X : Z) } }; break; + case 'rackPinion': m = { ...base, type: t, value: 5 + r() * 40, by: r() < 0.3 ? 'revolution' : undefined, a: { body: a, geo: axis(P()) }, b: { body: b, geo: line(P(), pickOf(r, [X, [0, 1, 0], Z] as Vec3[])) } }; break; + case 'screw': m = { ...base, type: t, value: (r() - 0.5) * 6, a: { body: a, geo: axis(P()) }, b: { body: b, geo: axis(P()) } }; break; + case 'width': { const w = 5 + r() * 10, tw = r() * 8; m = { ...base, type: t, a: { body: a, geo: plane([-w, 0, 0], X) }, a2: { body: a, geo: plane([w, 0, 0], [-1, 0, 0]) }, b: { body: b, geo: plane([-tw, 0, 0], [-1, 0, 0]) }, b2: { body: b, geo: plane([tw, 0, 0], X) } }; break; } + case 'slot': m = { ...base, type: t, a: { body: a, geo: axis([0, 0, 0]) }, a2: { body: a, geo: axis([r() < 0.1 ? 0 : 5 + r() * 30, 0, 0]) }, b: { body: b, geo: r() < 0.5 ? axis(P()) : { kind: 'point', p: P() } } }; break; + case 'cam': { const prof = r() < 0.5 ? camProfile(Z, [{ c: [0, -3 - r() * 5, 0], r: 10 + r() * 10 }], []) : camProfile(Z, [], [[-10, -10, 0], [10, -10, 0], [10, 10, 0], [r() < 0.3 ? 0 : -10, r() < 0.3 ? 4 : 10, 0]]); m = { ...base, type: t, a: { body: a, geo: prof }, b: { body: b, geo: pickOf(r, [{ kind: 'point', p: P() }, axis(P(), Z, 3), plane(P(), [0, -1, 0]), plane(P(), Z)] as Geo[]) } }; break; } + default: m = { ...base, type: 'universal', rel: rel(a, b), a: { body: a, geo: axis(P()) }, b: { body: b, geo: axis(P(), r() < 0.5 ? Z : normalize([0.3, 0, 1])) }, ...(r() < 0.3 ? { by: 'point', value: r() * 10 } : {}) }; + } + mates.push(m); + } + return { bodies, mates }; +} + +const finitePl = (pl: Map) => [...pl.values()].every((p) => [...p.p, ...p.q].every(Number.isFinite)); + +function placementWith(base: Placement, center: Vec3, x: number[], L: number): Placement { + const dq = rotVecQuat([x[3], x[4], x[5]]); + const c = applyPlacement(base, center); + return { p: add(add(qRotate(dq, sub(base.p, c)), c), [x[0] * L, x[1] * L, x[2] * L]), q: qNormalize(qMul(dq, base.q)) }; +} + +function fuzzOne(seed: number, log: string[]) { + const { bodies, mates } = makeAssembly(seed); + const L = 100; + const s = new MateSolver(bodies, mates); + let an; + try { an = s.analyze({ scale: L }); } catch (e) { log.push(`seed ${seed}: analyze threw ${(e as Error).stack}`); return; } + if (!finitePl(an.placements)) { log.push(`seed ${seed}: non-finite placements`); return; } + // (a) DOF vs rank of an independent Jacobian of the active mates (all floating bodies). + const active = mates.filter((m) => !an.conflicts.has(m.id) && !an.invalid.has(m.id)); + const floating = bodies.filter((b) => !b.fixed); + const n = floating.length * 6; + const pl = an.placements; + const rows: number[][] = []; + const allHold = active.every((m) => (s.mateResidual(m, pl, L, pl, true) ?? [Infinity]).every((v) => Math.abs(v) < 1e-6)); + for (const m of active) { + const r0 = s.mateResidual(m, pl, L, pl, false) ?? []; + const blk = r0.map(() => new Array(n).fill(0)); + floating.forEach((b, bi) => { + for (let j = 0; j < 6; j++) { + const x = [0, 0, 0, 0, 0, 0]; + x[j] = 1e-6; const rp = s.mateResidual(m, new Map(pl).set(b.id, placementWith(pl.get(b.id)!, b.center ?? [0, 0, 0], x, L)), L, pl, false) ?? []; + x[j] = -1e-6; const rm = s.mateResidual(m, new Map(pl).set(b.id, placementWith(pl.get(b.id)!, b.center ?? [0, 0, 0], x, L)), L, pl, false) ?? []; + for (let i = 0; i < r0.length; i++) blk[i][bi * 6 + j] = (rp[i] - rm[i]) / 2e-6; + } + }); + rows.push(...blk); + } + const dof = n - matrixRank(rows, n); + // Every motion the rank calls free keeps the mates to second order (a residual with a vanishing gradient would not). + if (allHold && n) { + for (const v of nullSpace(rows, n).basis) { + const mx = Math.max(...v.map(Math.abs)); + const moved = new Map(pl); + floating.forEach((b, bi) => moved.set(b.id, placementWith(pl.get(b.id)!, b.center ?? [0, 0, 0], v.slice(bi * 6, bi * 6 + 6).map((x) => (x / mx) * 1e-4), L))); + let worst = 0, who = ''; + for (const m of active) { if (m.type === 'cam') continue; const rr = s.mateResidual(m, moved, L, pl, false) ?? []; for (const x of rr) if (Math.abs(x) > worst) { worst = Math.abs(x); who = `${m.id} ${m.type}`; } } + if (worst > 1e-5) { log.push(`seed ${seed}: a free motion breaks ${who} by ${worst.toExponential(2)}`); break; } + } + } + if (dof !== an.dof && allHold) log.push(`seed ${seed}: dof ${an.dof} reported, rank says ${dof} (status ${an.status}, types ${active.map((m) => m.type).join(',')})`); + // (b) drags never produce NaN or throw. + const r = rng(seed + 7); + for (const b of floating.slice(0, 3)) { + try { + const d = s.solve({ scale: L, drag: r() < 0.5 ? { kind: 'move', body: b.id, local: [0, 0, 0], target: [(r() - 0.5) * 100, (r() - 0.5) * 100, (r() - 0.5) * 100] } : { kind: 'rotate', body: b.id, q: qNormalize([r() - 0.5, r() - 0.5, r() - 0.5, r()]) }, maxIter: 25 }, active, pl); + if (!finitePl(d.placements)) log.push(`seed ${seed}: drag gave non-finite placements`); + } catch (e) { log.push(`seed ${seed}: drag threw ${(e as Error).stack}`); } + } + // (c) solving again from the solved (saved) placements keeps them. + if (an.status !== 'over' && allHold) { + const again = new MateSolver(bodies.map((b) => ({ ...b, placement: pl.get(b.id)! })), mates).analyze({ scale: L }); + let worst = 0; + for (const [id, p] of again.placements) { const q = pl.get(id)!; worst = Math.max(worst, Math.hypot(...sub(p.p, q.p)), Math.min(Math.hypot(...p.q.map((v, i) => v - q.q[i])), Math.hypot(...p.q.map((v, i) => v + q.q[i])))); } + if (worst > 1e-3) log.push(`seed ${seed}: re-solve moved by ${worst.toExponential(2)}`); + if (again.dof !== an.dof || again.status !== an.status) log.push(`seed ${seed}: re-solve status ${an.status}/${an.dof} -> ${again.status}/${again.dof}`); + } + // (d) a motion study over each hinge or slider. + for (const m of active.filter((x) => x.type === 'hinge' || x.type === 'slider')) { + if (mates.every((x) => x === m || !x)) continue; + const motor: MotorInput = { id: 'mo', name: 'Motor', kind: m.type === 'hinge' ? 'rotary' : 'linear', on: m, at: profileOf(m.type === 'hinge' ? 'rotary' : 'linear', { profile: 'oscillate', amplitude: m.type === 'hinge' ? 120 : 25, frequency: 0.5 }, 2) }; + if (m.a.body && m.b.body && bodies.find((b) => b.id === m.a.body)?.fixed && bodies.find((b) => b.id === m.b.body)?.fixed) continue; + let res; + try { res = computeMotion({ bodies: bodies.map((b) => ({ ...b, placement: pl.get(b.id)! })), mates: active, motors: [motor], duration: 2, fps: 15, scale: L, names: new Map(mates.map((x) => [x.id, `Mate ${x.id}`])) }); } catch (e) { log.push(`seed ${seed}: motion threw ${(e as Error).stack}`); continue; } + if (!res.frames.every(finitePl)) log.push(`seed ${seed}: motion NaN`); + if (res.stop && (!res.stop.message || /undefined|NaN/.test(res.stop.message))) log.push(`seed ${seed}: bad stop message ${res.stop.message}`); + for (const x of active) { + if (!x.limit) continue; + for (const f of res.frames) { + const v = mateMeasure(x, f, L); + if (!v) continue; + let val = v.value; + if (x.type === 'hinge') { if (x.limit.max - x.limit.min >= 360) continue; const mid = (x.limit.min + x.limit.max) / 2; val = mid + ((((val - mid + 180) % 360) + 360) % 360) - 180; } + const tol = v.kind === 'angle' ? 1e-3 : 1e-3; + if (x.type === 'angle' || x.type === 'distance' || x.type === 'slider' || x.type === 'hinge') { + if (x.type === 'distance' && x.limit.min < 0 && !(x.a.geo.kind === 'plane' || x.b.geo.kind === 'plane')) continue; + if (val < x.limit.min - tol || val > x.limit.max + tol) { log.push(`seed ${seed}: ${x.type} limit [${x.limit.min.toFixed(2)}, ${x.limit.max.toFixed(2)}] exceeded: ${val.toFixed(4)} (motor on ${m.type} ${m.id}, frame ok)`); break; } + } + } + } + } +} + + +it('random assemblies keep the solver invariants', () => { + const log: string[] = []; + // Seeds 5, 187 (and 402) and 2107 found a rack checked where it started, bevel gears flipping sense and a turned-over slider. + for (const seed of [...Array.from({ length: 40 }, (_, i) => i + 1), 187, 402, 2107]) fuzzOne(seed, log); + expect(log).toEqual([]); +}, 60_000); diff --git a/src/parametric/tests/assembly-kernel.test.ts b/src/parametric/tests/assembly-kernel.test.ts index 5b097382d..9f571d92a 100644 --- a/src/parametric/tests/assembly-kernel.test.ts +++ b/src/parametric/tests/assembly-kernel.test.ts @@ -6,7 +6,8 @@ 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 { faceGeo, placementMatrix } from '../src/assembly/compose'; +import { mateProblem } from '../src/assembly/solver'; import { qAxisAngle } from '../src/math/vec'; import type { Placement } from '../src/model/assembly'; import { circle, extrude, rect, sketch } from './helpers'; @@ -95,6 +96,38 @@ describe('assembly geometry', () => { expect(a.interference()).toEqual([]); }); + it('checks only pairs in different groups, and leaves out meshes when asked (a motion study frame by frame)', 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>'), item('pin', at([5, 5, -10]), 'pin<1>')]); + const pairs = a.interference({ mesh: false, groups: [0, 0, 1] }); + expect(pairs.map((p) => [p.a, p.b])).toEqual([[0, 2]]); + expect(pairs[0].volume).toBeCloseTo(Math.PI * 9 * 10, 1); + expect(pairs[0].mesh).toBeNull(); + }); + + it('gives conical faces (a chamfered shaft) an axis for mates', async () => { + const a = new AssemblyBuilder(); + const shaft = [sketch('S1', circle(5, 7, 4)), extrude('E1', 'S1', 30)]; + const [plain] = await a.build([{ key: 'p', features: shaft, blobs: {}, quality: 0 }]); + const top = plain.faces.find((f) => f.name === 'E1:cap1')!; + const chamfer = { id: 'C', name: 'C', type: 'chamfer', edges: [], faces: [{ name: top.name, sig: { type: top.type, c: top.center, n: top.normal, area: top.area } }], mode: 'distance', distance: 1, distance2: 1, angle: 45, flip: false } as unknown as Feature; + const [res] = await a.build([{ key: 'c', features: [...shaft, chamfer], blobs: {}, quality: 0 }]); + const i = res.faces.findIndex((f) => f.type === 'cone'); + expect(i).toBeGreaterThanOrEqual(0); + const ax = res.cones[i]; + expect(ax).toBeTruthy(); + // Along z, through the shaft's centre (5, 7). + expect(Math.abs(ax.d[2])).toBeCloseTo(1, 9); + expect(ax.p[0]).toBeCloseTo(5, 6); + expect(ax.p[1]).toBeCloseTo(7, 6); + // A concentric mate on it: the cone's axis on a cylinder's. + const g = { mesh: res.mesh, faces: res.faces, edges: res.edges, bbox: res.bbox, cones: res.cones }; + const cone = faceGeo(g, i)!; + expect(cone).toMatchObject({ kind: 'axis', surface: 'cone' }); + expect(mateProblem('concentric', cone, { kind: 'axis', p: [0, 0, 0], d: [0, 0, 1], r: 4, surface: 'cylinder' })).toBeNull(); + }); + it('reports a pair whose overlap cannot be computed as not checked, never as clear', async () => { const a = new AssemblyBuilder(); await built(a); diff --git a/src/parametric/tests/assembly-kinematics.test.ts b/src/parametric/tests/assembly-kinematics.test.ts new file mode 100644 index 000000000..94e4d401e --- /dev/null +++ b/src/parametric/tests/assembly-kinematics.test.ts @@ -0,0 +1,784 @@ +import { describe, expect, it } from 'vitest'; +import { type Geo, MateSolver, type SolverBody, type SolverMate, applyPlacement, camProfile, mateBodies, mateMeasure, matesMoving, placeGeo, profileSupport, relativePlacement, turnAbout } from '../src/assembly/solver'; +import { type PartGeometry, camProfileOf } from '../src/assembly/compose'; +import { type MotorInput, MotionRun, computeMotion, degreesAbout, derivatives, framesSpread, mateSeries, pointPath, profileOf, resultsCsv, sameMotionGroups, turnPath, vectorDerivatives } from '../src/assembly/motion'; +import { type Quat, type Vec3, dot, len, normalize, qAxisAngle, qMul, qRotate, sub } from '../src/math/vec'; +import type { MateType, Placement } from '../src/model/assembly'; + +const Z: Vec3 = [0, 0, 1], Y3: Vec3 = [0, 1, 0]; +const plane = (o: Vec3, n: Vec3): Geo => ({ kind: 'plane', o, n }); +const axis = (p: Vec3, d: Vec3 = Z, r = 2): Geo => ({ kind: 'axis', p, d, r, 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 }, center: [0, 0, 0] }); +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: true, value: 0, flip: false, ...extra, +}); +/** A hinge between a's axis at pa and b's at pb (both along z), their z = 0 faces touching. */ +const hinge = (a: string, pa: Vec3, b: string, pb: Vec3, extra: Partial = {}) => mate('hinge', [a, axis(pa)], [b, axis(pb)], { + a2: { body: a, geo: plane([0, 0, 0], Z) }, b2: { body: b, geo: plane([0, 0, 0], [0, 0, -1]) }, aligned2: false, ...extra, +}); +const deg = (r: number) => (r * 180) / Math.PI; +const angleZ = (q: Quat) => Math.atan2(qRotate(q, [1, 0, 0])[1], qRotate(q, [1, 0, 0])[0]); +const rotary = (bodyId: string, entity: Geo, speed: number, extra: Partial = {}): MotorInput => ({ + id: 'motor', name: 'RotaryMotor1', kind: 'rotary', body: bodyId, entity: { body: bodyId, geo: entity }, at: profileOf('rotary', { profile: 'constant', speed }, 1), ...extra, +}); + +describe('limit mates', () => { + const TOP = plane([0, 5, 0], [0, 1, 0]), BOTTOM = plane([0, -5, 0], [0, -1, 0]); + const blockOnSlide = (limit: { min: number; max: number }, y = 40) => { + const bodies = [body('base', true), body('blk', false, [3, y, 1])]; + // Kept upright and sliding along y only (two faces), with the distance between the limits. + const mates = [ + mate('coincident', ['base', plane([5, 0, 0], [1, 0, 0])], ['blk', plane([5, 0, 0], [1, 0, 0])]), + mate('coincident', ['base', plane([0, 0, 5], Z)], ['blk', plane([0, 0, 5], Z)]), + mate('distance', ['base', TOP], ['blk', BOTTOM], { aligned: false, limit, value: 10 }), + ]; + return new MateSolver(bodies, mates); + }; + const gap = (pl: Map) => (placeGeo(BOTTOM, pl.get('blk')!) as { o: Vec3 }).o[1] - 5; + + it('a distance limit lets the component move between its values, and stops a drag at them', () => { + const s = blockOnSlide({ min: 5, max: 20 }); + const r = s.analyze(); + // Moved in to the largest distance, still free to slide: one degree of freedom. + expect(gap(r.placements)).toBeCloseTo(20, 4); + expect(r.status).toBe('under'); + expect(r.dof).toBe(1); + expect(r.defined.size).toBe(0); + // Inside the range it stays where it is put. + const inside = blockOnSlide({ min: 5, max: 20 }, 22).solve(); + expect(gap(inside.placements)).toBeCloseTo(12, 9); + // Dragged far down, it stops at the smallest distance. + const down = s.solve({ drag: { kind: 'move', body: 'blk', local: [0, 0, 0], target: [0, -100, 0] } }, s.mates, r.placements); + expect(down.ok).toBe(true); + expect(gap(down.placements)).toBeCloseTo(5, 4); + const up = s.solve({ drag: { kind: 'move', body: 'blk', local: [0, 0, 0], target: [0, 300, 0] } }, s.mates, r.placements); + expect(gap(up.placements)).toBeCloseTo(20, 4); + }); + + it('a limit that cannot be met with the other mates conflicts; one upside down is a mate error', () => { + const base = blockOnSlide({ min: 5, max: 20 }); + const over = new MateSolver(base.bodies, [...base.mates, mate('distance', ['base', TOP], ['blk', BOTTOM], { aligned: false, value: 30 })]).analyze(); + expect(over.status).toBe('over'); + expect(over.conflicts.size).toBe(1); + const bad = blockOnSlide({ min: 20, max: 5 }).analyze(); + expect(bad.status).toBe('error'); + expect([...bad.invalid.values()][0]).toMatch(/smallest/); + }); + + it('a limit whose smallest and largest values are equal holds the component there (it takes the freedom away)', () => { + const r = blockOnSlide({ min: 12, max: 12 }).analyze(); + expect(r.status).toBe('full'); + expect(r.dof).toBe(0); + expect(r.defined.has('blk')).toBe(true); + expect(gap(r.placements)).toBeCloseTo(12, 6); + const start: Placement = { p: [0, 0, 0], q: [0, 0, 0, 1] }; + const held = new MateSolver([body('base', true), body('lid', false)], [mate('hinge', ['base', axis([0, 0, 0])], ['lid', axis([0, 0, 0])], { a2: { body: 'base', geo: plane([0, 0, 0], Z) }, b2: { body: 'lid', geo: plane([0, 0, 0], [0, 0, -1]) }, aligned2: false, rel: start, limit: { min: 20, max: 20 } })]).analyze(); + expect(held.dof).toBe(0); + expect(deg(angleZ(held.placements.get('lid')!.q))).toBeCloseTo(20, 4); + }); + + it('an angle limit stops a lid turning on its hinge', () => { + const lidTop = plane([20, 1, 0], [0, 1, 0]); + const mates = [ + mate('concentric', ['base', axis([0, 0, 0])], ['lid', axis([0, 0, 0])]), + mate('coincident', ['base', plane([0, 0, 0], Z)], ['lid', plane([0, 0, 0], Z)]), + mate('angle', ['base', plane([0, 0, 0], [0, 1, 0])], ['lid', lidTop], { limit: { min: 0, max: 60 }, value: 0 }), + ]; + const s = new MateSolver([body('base', true), body('lid', false)], mates); + const r = s.analyze(); + expect(r.dof).toBe(1); + // Dragging the lid's end straight up: it turns until 60°, then stops. + let pl = r.placements; + for (let k = 1; k <= 8; k++) pl = s.solve({ drag: { kind: 'move', body: 'lid', local: [40, 0, 0], target: [0, 10 * k, 0] } }, s.mates, pl).placements; + expect(deg(angleZ(pl.get('lid')!.q))).toBeCloseTo(60, 3); + }); +}); + +describe('mechanical mates', () => { + it('a hinge is concentric and coincident in one, with angle limits from where it was added', () => { + const lid = body('lid', false, [5, 3, 7], qAxisAngle(normalize([1, 2, 0]), 0.3)); + const free = new MateSolver([body('base', true), lid], [hinge('base', [0, 0, 0], 'lid', [0, 0, 0])]).analyze(); + expect(free.dof).toBe(1); + const p = free.placements.get('lid')!; + expect(len(applyPlacement(p, [0, 0, 0]))).toBeLessThan(1e-6); + expect(dot(qRotate(p.q, Z), Z)).toBeCloseTo(1, 8); + // With limits of -30° to 45° measured from the lid where it is now. + const start: Placement = { p: [0, 0, 0], q: [0, 0, 0, 1] }; + const limited = hinge('base', [0, 0, 0], 'lid', [0, 0, 0], { rel: relativePlacement(start, start), limit: { min: -30, max: 45 } }); + const s = new MateSolver([body('base', true), body('lid', false)], [limited]); + expect(s.analyze().dof).toBe(1); + let pl = new Map([['base', start], ['lid', start]]); + for (let k = 1; k <= 12; k++) pl = s.solve({ drag: { kind: 'rotate', body: 'lid', q: qAxisAngle(Z, (k * 10 * Math.PI) / 180) } }, s.mates, pl).placements; + expect(deg(angleZ(pl.get('lid')!.q))).toBeCloseTo(45, 3); + expect(mateMeasure(limited, pl)!.value).toBeCloseTo(45, 3); + for (let k = 1; k <= 12; k++) pl = s.solve({ drag: { kind: 'rotate', body: 'lid', q: qAxisAngle(Z, ((45 - k * 10) * Math.PI) / 180) } }, s.mates, pl).placements; + expect(deg(angleZ(pl.get('lid')!.q))).toBeCloseTo(-30, 3); + // Faces on the wrong components are refused. + const crossed = { ...limited, a2: limited.b2, b2: limited.a2 }; + expect(new MateSolver([body('base', true), body('lid', false)], [crossed]).analyze().invalid.get(crossed.id)).toMatch(/component of the round entity/); + }); + + it('hinge limits past ±180° (a door that opens 270°) stop at their ends, not at 180°', () => { + const start: Placement = { p: [0, 0, 0], q: [0, 0, 0, 1] }; + const door = hinge('base', [0, 0, 0], 'lid', [0, 0, 0], { rel: relativePlacement(start, start), limit: { min: 0, max: 270 } }); + const bodies = [body('base', true), body('lid', false)]; + const run = (speed: number) => computeMotion({ bodies, mates: [door], motors: [{ id: 'mo', name: 'RotaryMotor1', kind: 'rotary', on: door, at: profileOf('rotary', { profile: 'constant', speed }, 4) }], duration: 4, fps: 10, scale: 100 }); + const open = run(90); + expect(open.stop?.kind).toBe('limit'); + expect(open.stop?.time).toBeCloseTo(3.1, 6); + expect(degreesAbout(turnPath(open, 'lid'), Z).at(-1)).toBeCloseTo(270, 4); + expect(mateSeries(open, door)!.values.at(-1)).toBeCloseTo(270, 4); + // Kept at one angle, it cannot turn: the study stops at that limit. + const shut0 = { ...door, limit: { min: 0, max: 0 } }; + const stuck = computeMotion({ bodies, mates: [shut0], motors: [{ id: 'mo', name: 'RotaryMotor1', kind: 'rotary', on: shut0, at: profileOf('rotary', { profile: 'constant', speed: 90 }, 4) }], duration: 4, fps: 10, scale: 100 }); + expect(stuck.stop?.kind).toBe('limit'); + expect(stuck.stop?.mate).toBe(door.id); + // The other way it is at its end already. + const shut = run(-90); + expect(shut.stop?.kind).toBe('limit'); + expect(shut.frames).toHaveLength(1); + // Dragged round past 180°, it stops at 270°. + const s = new MateSolver(bodies, [door]); + let pl = new Map([['base', start], ['lid', start]]); + for (let k = 1; k <= 32; k++) pl = s.solve({ drag: { kind: 'rotate', body: 'lid', q: qAxisAngle(Z, (k * 10 * Math.PI) / 180) } }, s.mates, pl).placements; + expect(mateMeasure(door, pl)!.value).toBeCloseTo(-90, 3); + }); + + /** Two gears on hinges, 30 mm apart: A (pitch Ø20) at the origin, B (Ø40) beside it. */ + const gears = (extra: Partial = {}) => { + const bodies = [body('g', true), body('A', false), body('B', false, [30, 0, 0])]; + const mates = [hinge('g', [0, 0, 0], 'A', [0, 0, 0]), hinge('g', [30, 0, 0], 'B', [0, 0, 0]), mate('gear', ['A', axis([0, 0, 0])], ['B', axis([0, 0, 0], [0, 0, -1])], { value: 20, value2: 40, ...extra })]; + return new MateSolver(bodies, mates); + }; + + it('a gear mate couples two turns by the ratio, the other way round, past ±180°', () => { + const s = gears(); + const r = s.analyze(); + expect(r.status).toBe('under'); + expect(r.dof).toBe(1); + // Turning A by 30° steps to 390° (dragged round): B turns half as far the other way, also past 180°. + let pl = r.placements; + let a = 0, b = 0; + for (let k = 1; k <= 13; k++) { + const next = s.solve({ drag: { kind: 'rotate', body: 'A', q: qAxisAngle(Z, (k * 30 * Math.PI) / 180) } }, s.mates, pl); + expect(next.ok).toBe(true); + a += turnAbout(next.placements.get('A')!.q, pl.get('A')!.q, Z); + b += turnAbout(next.placements.get('B')!.q, pl.get('B')!.q, Z); + pl = next.placements; + } + expect(deg(a)).toBeCloseTo(390, 2); + expect(deg(b)).toBeCloseTo(-195, 2); + // B's orientation is that turn, not one wrapped to ±180°. + expect(dot(qRotate(pl.get('B')!.q, [1, 0, 0]), [Math.cos(b), Math.sin(b), 0])).toBeCloseTo(1, 6); + // Reversed (an internal gear): the same way round. + const rev = gears({ reverse: true }); + const turned = rev.solve({ drag: { kind: 'rotate', body: 'A', q: qAxisAngle(Z, 0.5) } }, rev.mates); + expect(turnAbout(turned.placements.get('B')!.q, [0, 0, 0, 1], Z)).toBeCloseTo(0.25, 5); + }); + + it('a gear mate contradicting the mates before it is over defined; a repeated or consistent one is not', () => { + const s = gears(); + const [h1, h2, g1] = s.mates; + const other = { ...g1, id: 'g2', value2: 60 }; + const r = new MateSolver(s.bodies, [h1, h2, g1, other]).analyze(); + expect(r.status).toBe('over'); + expect([...r.conflicts]).toEqual(['g2']); + expect(r.dof).toBe(1); + expect(new MateSolver(s.bodies, [h1, h2, g1, { ...g1, id: 'g3' }]).analyze().status).toBe('under'); + // Three external gears in a ring cannot turn; with an internal one (reversed) they can. + const C = body('C', false, [15, 26, 0]); + const ring = (reverse: boolean) => [h1, h2, hinge('g', [15, 26, 0], 'C', [0, 0, 0]), { ...g1, value2: 20 }, mate('gear', ['B', axis([0, 0, 0])], ['C', axis([0, 0, 0])], { value: 20, value2: 20 }), mate('gear', ['C', axis([0, 0, 0])], ['A', axis([0, 0, 0])], { value: 20, value2: 20, reverse, id: 'last' })]; + const odd = new MateSolver([...s.bodies, C], ring(false)).analyze(); + expect([...odd.conflicts]).toEqual(['last']); + const even = new MateSolver([...s.bodies, C], ring(true)).analyze(); + expect(even.status).toBe('under'); + expect(even.dof).toBe(1); + // A gear meshing with a fixed one just holds it. + const held = new MateSolver(s.bodies, [h1, h2, mate('gear', ['A', axis([0, 0, 0])], ['g', axis([30, 0, 0])], { value: 20, value2: 40 })]).analyze(); + expect(held.conflicts.size).toBe(0); + expect(held.defined.has('A')).toBe(true); + }); + + it('bevel gears (square axes) keep their sense as the axes tilt a little either way', () => { + const X3: Vec3 = [1, 0, 0]; + const g = mate('gear', ['A', axis([0, 0, 0])], ['B', axis([0, 0, 0], X3)], { value: 20, value2: 20 }); + const s = new MateSolver([body('A', false), body('B', false, [20, 0, 10])], [g]); + const start = new Map(s.bodies.map((b) => [b.id, b.placement])); + // A turned 0.01 about z, B 0.01 about x and tilted a hair about y one way or the other. + const at = (tilt: number) => new Map(start).set('A', { p: [0, 0, 0], q: qAxisAngle(Z, 0.01) }).set('B', { p: [20, 0, 10], q: qMul(qAxisAngle([0, 1, 0], tilt), qAxisAngle(X3, 0.01)) }); + const r1 = s.mateResidual(g, at(1e-7), 100, start)![0], r2 = s.mateResidual(g, at(-1e-7), 100, start)![0]; + expect(Math.abs(r1 - r2)).toBeLessThan(1e-6); + }); + + it('dragging one gear by a tooth turns the other', () => { + const s = gears(); + let pl = s.analyze().placements; + // Grab A's rim at (10, 0) and pull it up: A turns, and B with it. + for (let k = 1; k <= 6; k++) pl = s.solve({ drag: { kind: 'move', body: 'A', local: [10, 0, 0], target: [10, 3 * k, 0] } }, s.mates, pl).placements; + const ta = angleZ(pl.get('A')!.q), tb = angleZ(pl.get('B')!.q); + expect(ta).toBeGreaterThan(0.5); + expect(tb).toBeCloseTo(-ta / 2, 5); + }); + + it('a gear pair keeps its ratio over a full turn of a motor', () => { + const s = gears(); + const res = computeMotion({ bodies: s.bodies, mates: s.mates, motors: [rotary('A', axis([0, 0, 0]), 360)], duration: 1.5, fps: 40, scale: 100 }); + expect(res.stop).toBeNull(); + expect(res.frames).toHaveLength(61); + const a = degreesAbout(turnPath(res, 'A'), Z), b = degreesAbout(turnPath(res, 'B'), Z); + expect(a[60]).toBeCloseTo(540, 4); + for (let i = 0; i < a.length; i++) expect(b[i]).toBeCloseTo(-a[i] / 2, 4); + // Angular velocity from the frames: 360°/s and −180°/s. + const w = derivatives(res.times, b).d1; + expect(w[30]).toBeCloseTo(-180, 3); + }); + + it('a motor (or a gear it drives) turning more than half a turn a frame is followed in smaller steps', () => { + // 1000 rpm at 30 frames a second: 200° a frame. + const s = gears(); + const fast = computeMotion({ bodies: s.bodies, mates: s.mates, motors: [rotary('A', axis([0, 0, 0]), 1000, { at: profileOf('rotary', { profile: 'constant', speed: 1000, rpm: true }, 1) })], duration: 0.5, fps: 30, scale: 100 }); + expect(fast.stop).toBeNull(); + expect(fast.times[fast.times.length - 1]).toBeCloseTo(0.5, 12); + for (let i = 1; i < fast.times.length; i++) expect(fast.times[i]).toBeGreaterThan(fast.times[i - 1]); + expect(degreesAbout(turnPath(fast, 'A'), Z).at(-1)).toBeCloseTo(3000, 3); + expect(degreesAbout(turnPath(fast, 'B'), Z).at(-1)).toBeCloseTo(-1500, 3); + // A slow motor on the large gear: the small one turns 240° a frame. + const big = new MateSolver(s.bodies, [s.mates[0], s.mates[1], { ...s.mates[2], value: 40, value2: 10 }]); + const res = computeMotion({ bodies: big.bodies, mates: big.mates, motors: [rotary('A', axis([0, 0, 0]), 1800)], duration: 0.5, fps: 30, scale: 100 }); + expect(res.stop).toBeNull(); + expect(degreesAbout(turnPath(res, 'B'), Z).at(-1)).toBeCloseTo(-3600, 3); + }); + + /** A pinion (Ø20) on a hinge at the origin, its rack below it sliding along x. */ + const rackAndPinion = (extra: Partial = {}) => { + const bodies = [body('g', true), body('P', false), body('R', false, [0, -10, 0])]; + const mates = [ + hinge('g', [0, 0, 0], 'P', [0, 0, 0]), + mate('coincident', ['g', plane([0, -10, 0], [0, 1, 0])], ['R', plane([0, 0, 0], [0, 1, 0])]), + mate('coincident', ['g', plane([0, 0, 0], Z)], ['R', plane([0, 0, 0], Z)]), + mate('rackPinion', ['P', axis([0, 0, 0])], ['R', { kind: 'line', p: [0, 0, 0], d: [1, 0, 0] }], { value: 20, ...extra }), + ]; + return new MateSolver(bodies, mates); + }; + + it('rack and pinion: turning the pinion moves the rack, and dragging the rack turns the pinion', () => { + const s = rackAndPinion(); + expect(s.analyze().dof).toBe(1); + const res = computeMotion({ bodies: s.bodies, mates: s.mates, motors: [rotary('P', axis([0, 0, 0]), 90)], duration: 1, fps: 20, scale: 100 }); + expect(res.stop).toBeNull(); + // A quarter turn moves the rack by a quarter of the pitch circle, the way the pinion's bottom moves. + expect(res.frames[20].get('R')!.p[0]).toBeCloseTo((Math.PI / 2) * 10, 5); + // Dragged 10π mm along: the pinion turns half a turn (past 90°, in steps as a pointer moves). + let pl = s.analyze().placements; + for (let k = 1; k <= 10; k++) pl = s.solve({ drag: { kind: 'move', body: 'R', local: [0, 0, 0], target: [k * Math.PI, -10, 0] } }, s.mates, pl).placements; + expect(pl.get('R')!.p[0]).toBeCloseTo(10 * Math.PI, 3); + expect(Math.abs(deg(angleZ(pl.get('P')!.q)))).toBeCloseTo(180, 2); + // Pulled 50 mm in one pointer move (more than half a turn of the pinion): the rack follows, the pinion turns 5 rad with it. + for (const dx of [50, 80]) { + const one = s.solve({ drag: { kind: 'move', body: 'R', local: [0, 0, 0], target: [dx, -10, 0] } }, s.mates, s.analyze().placements); + expect(one.ok).toBe(true); + expect(one.placements.get('R')!.p[0]).toBeCloseTo(dx, 3); + const t = dx / 10; + expect(dot(qRotate(one.placements.get('P')!.q, [1, 0, 0]), [Math.cos(t), Math.sin(t), 0])).toBeCloseTo(1, 6); + } + // A mate's new value moving the rack 50 or 100 mm at once: the pinion turns with it (not a conflict). + for (const v of [50, 100]) { + const to = mate('distance', ['g', plane([0, 0, 0], [1, 0, 0])], ['R', plane([0, 0, 0], [1, 0, 0])], { value: v }); + const r = new MateSolver(s.bodies, [...s.mates, to]).analyze(); + expect(r.status).toBe('full'); + expect(r.placements.get('R')!.p[0]).toBeCloseTo(v, 6); + expect(dot(qRotate(r.placements.get('P')!.q, [1, 0, 0]), [Math.cos(v / 10), Math.sin(v / 10), 0])).toBeCloseTo(1, 6); + } + // A rack along the pinion's axis is refused. + const along = { ...s.mates[3], b: { body: 'R', geo: { kind: 'line', p: [0, 0, 0], d: [0, 0, 1] } as Geo } }; + const bad = new MateSolver(s.bodies, [...s.mates.slice(0, 3), along]).analyze(); + expect(bad.status).toBe('error'); + expect(bad.invalid.get(along.id)).toMatch(/across the pinion's axis/); + // Along the axis where it was put, across it where the other mates put it: told where they end up + // (so the assembly opened again, solved where it was saved, says the same). + const turnedR = body('R', false, [0, -10, 0], qAxisAngle([0, 1, 0], -Math.PI / 2)); + const squared = [...s.mates.slice(0, 2), mate('parallel', ['g', plane([0, 0, 0], Z)], ['R', plane([0, 0, 0], Z)]), s.mates[3]]; + const first = new MateSolver([s.bodies[0], s.bodies[1], turnedR], squared).analyze(); + expect(first.invalid.size).toBe(0); + const reopened = new MateSolver([s.bodies[0], s.bodies[1], { ...turnedR, placement: first.placements.get('R')! }], squared).analyze(); + expect([reopened.status, reopened.dof]).toEqual([first.status, first.dof]); + // By travel per turn, and reversed. + const per = rackAndPinion({ by: 'revolution', value: 50, reverse: true }); + const r2 = computeMotion({ bodies: per.bodies, mates: per.mates, motors: [rotary('P', axis([0, 0, 0]), 360)], duration: 1, fps: 30, scale: 100 }); + expect(r2.frames[30].get('R')!.p[0]).toBeCloseTo(-50, 4); + }); + + it('a screw turns a nut along its axis by the pitch per turn, right or left hand', () => { + const run = (reverse: boolean) => { + const mates = [mate('screw', ['g', axis([0, 0, 0])], ['N', axis([0, 0, 0])], { value: 2, reverse })]; + const s = new MateSolver([body('g', true), body('N', false, [0, 0, 5])], mates); + expect(s.analyze().dof).toBe(1); + return computeMotion({ bodies: s.bodies, mates, motors: [rotary('N', axis([0, 0, 0]), 360)], duration: 3, fps: 24, scale: 50 }); + }; + const right = run(false); + expect(right.stop).toBeNull(); + expect(right.frames[72].get('N')!.p[2]).toBeCloseTo(11, 4); + expect(run(true).frames[72].get('N')!.p[2]).toBeCloseTo(-1, 4); + }); + + it('a width mate centres a tab in a groove', () => { + const groove: [Geo, Geo] = [plane([-10, 0, 0], [1, 0, 0]), plane([10, 0, 0], [-1, 0, 0])]; + const tab: [Geo, Geo] = [plane([-3, 0, 0], [-1, 0, 0]), plane([3, 0, 0], [1, 0, 0])]; + const m = mate('width', ['g', groove[0]], ['T', tab[0]], { a2: { body: 'g', geo: groove[1] }, b2: { body: 'T', geo: tab[1] } }); + const s = new MateSolver([body('g', true), body('T', false, [6, 2, 1], qAxisAngle([0, 1, 0], 0.2))], [m]); + const r = s.analyze(); + expect(r.dof).toBe(3); + const t = r.placements.get('T')!; + expect(t.p[0]).toBeCloseTo(0, 6); + expect(Math.abs(qRotate(t.q, [1, 0, 0])[0])).toBeCloseTo(1, 8); + const skew = { ...m, a2: { body: 'g', geo: plane([10, 0, 0], normalize([-1, 1, 0])) } }; + expect(new MateSolver(s.bodies, [skew]).analyze().invalid.get(skew.id)).toMatch(/parallel/); + }); + + it('a slot mate keeps a pin on the slot, between its ends', () => { + const m = mate('slot', ['g', axis([0, 0, 0], Z, 3)], ['pin', axis([0, 0, 0], Z, 3)], { a2: { body: 'g', geo: axis([30, 0, 0], Z, 3) } }); + const s = new MateSolver([body('g', true), body('pin', false, [10, 5, 3], qAxisAngle([1, 0, 0], 0.2))], [m]); + const r = s.analyze(); + expect(r.dof).toBe(3); + const p = r.placements.get('pin')!; + expect(p.p[1]).toBeCloseTo(0, 6); + expect(dot(qRotate(p.q, Z), Z)).toBeCloseTo(1, 8); + expect(mateMeasure(m, r.placements)!.value).toBeCloseTo(p.p[0], 6); + // Dragged past the end, it stops there. + let pl = r.placements; + for (let k = 1; k <= 5; k++) pl = s.solve({ drag: { kind: 'move', body: 'pin', local: [0, 0, 0], target: [10 + 10 * k, 0, p.p[2]] } }, s.mates, pl).placements; + expect(pl.get('pin')!.p[0]).toBeCloseTo(30, 4); + const same = { ...m, a2: { body: 'g', geo: axis([0, 0, 9], Z, 3) } }; + expect(new MateSolver(s.bodies, [same]).analyze().invalid.get(same.id)).toMatch(/same axis/); + }); + + it('mates of more than two components link them for dragging', () => { + const m = mate('width', ['a', plane([0, 0, 0], [1, 0, 0])], ['b', plane([0, 0, 0], [1, 0, 0])], { a2: { body: 'c', geo: plane([1, 0, 0], [1, 0, 0]) }, b2: { body: 'b', geo: plane([1, 0, 0], [1, 0, 0]) } }); + expect(mateBodies(m)).toEqual(['a', 'b', 'c']); + const bodies = [body('a', false), body('b', false), body('c', false), body('d', false)]; + expect(matesMoving('c', bodies, [m]).map((x) => x.id)).toEqual([m.id]); + }); +}); + +describe('motion studies', () => { + const r = 20, l = 60; + /** A crank (r), rod (l) and slider on x, the crank at θ0 (degrees). */ + const crankSlider = (theta0: number, extraMates: SolverMate[] = []) => { + const th = (theta0 * Math.PI) / 180; + const pin: Vec3 = [r * Math.cos(th), r * Math.sin(th), 0]; + const phi = Math.asin((-r * Math.sin(th)) / l); + const x = pin[0] + l * Math.cos(phi); + const bodies = [body('g', true), body('crank', false, [0, 0, 0], qAxisAngle(Z, th)), body('rod', false, pin, qAxisAngle(Z, phi)), body('slider', false, [x, 0, 0])]; + const mates = [ + hinge('g', [0, 0, 0], 'crank', [0, 0, 0]), + hinge('crank', [r, 0, 0], 'rod', [0, 0, 0]), + hinge('rod', [l, 0, 0], 'slider', [0, 0, 0]), + mate('coincident', ['g', plane([0, 0, 0], [0, 1, 0])], ['slider', plane([0, 0, 0], [0, 1, 0])]), + ...extraMates, + ]; + return { bodies, mates }; + }; + const slide = (theta: number) => { + const t = (theta * Math.PI) / 180; + return r * Math.cos(t) + Math.sqrt(l * l - r * r * Math.sin(t) ** 2); + }; + + it('a crank-slider has one degree of freedom and its slider follows the closed-form position', () => { + const cs = crankSlider(30); + expect(new MateSolver(cs.bodies, cs.mates).analyze().dof).toBe(1); + const res = computeMotion({ ...cs, motors: [rotary('crank', axis([0, 0, 0]), 90)], duration: 4, fps: 25, scale: 200 }); + expect(res.stop).toBeNull(); + expect(res.times).toHaveLength(101); + res.frames.forEach((f, i) => expect(f.get('slider')!.p[0]).toBeCloseTo(slide(30 + 90 * res.times[i]), 4)); + // Velocity and acceleration of the slider from the frames, against the derivatives of the formula. + const path = pointPath(res, 'slider', [0, 0, 0]); + const { d1, d2 } = vectorDerivatives(res.times, path); + const h = 1e-4, x = (t: number) => slide(30 + 90 * t); + const v = (t: number) => (x(t + h) - x(t - h)) / (2 * h), a = (t: number) => (x(t + h) - 2 * x(t) + x(t - h)) / (h * h); + expect(d1[50][0]).toBeCloseTo(v(2), 0); + expect(d2[50][0] / a(2)).toBeCloseTo(1, 1); + // A crank angle reading past a full turn: 30° + 360°. + expect(degreesAbout(turnPath(res, 'crank'), Z)[100]).toBeCloseTo(360, 3); + }); + + it('stops at a limit and says which', () => { + // The slider kept beyond 45 mm from the crank's axis: the crank turning down toward 180° pushes it there. + const limit = mate('distance', ['g', plane([0, 0, 0], [1, 0, 0])], ['slider', plane([0, 0, 0], [1, 0, 0])], { limit: { min: 45, max: 100 }, value: 60 }); + const cs = crankSlider(30, [limit]); + const res = computeMotion({ ...cs, motors: [rotary('crank', axis([0, 0, 0]), 90)], duration: 4, fps: 25, scale: 200, names: new Map([[limit.id, 'LimitDistance1']]) }); + expect(res.stop?.kind).toBe('limit'); + expect(res.stop?.mate).toBe(limit.id); + expect(res.stop?.message).toMatch(/LimitDistance1 reached its limit/); + const last = res.frames[res.frames.length - 1].get('slider')!.p[0]; + expect(last).toBeGreaterThan(45 - 1e-6); + expect(last).toBeLessThan(47); + }); + + it('reports a mechanism that locks up', () => { + // The crank also held at its angle by an angle mate: the motor cannot turn it. + const held = mate('angle', ['g', plane([0, 0, 0], [0, 1, 0])], ['crank', plane([0, 0, 0], [0, 1, 0])], { value: 30 }); + const cs = crankSlider(30, [held]); + const res = computeMotion({ ...cs, motors: [rotary('crank', axis([0, 0, 0]), 90)], duration: 1, fps: 10, scale: 200 }); + expect(res.stop?.kind).toBe('locked'); + expect(res.stop?.time).toBeCloseTo(0.1, 6); + expect(res.frames).toHaveLength(1); + }); + + it('drives a distance mate by a ramp, and the crank follows', () => { + const drive = mate('distance', ['g', plane([0, 0, 0], [1, 0, 0])], ['slider', plane([0, 0, 0], [1, 0, 0])], { value: slide(30) }); + const cs = crankSlider(30, [drive]); + expect(new MateSolver(cs.bodies, cs.mates).analyze().dof).toBe(0); + const motor: MotorInput = { id: 'mo', name: 'MateDriver1', kind: 'mate', mate: drive.id, at: profileOf('mate', { profile: 'ramp', from: slide(30), to: 50 }, 2) }; + const run = new MotionRun({ ...cs, motors: [motor], duration: 2, fps: 10, scale: 200 }); + let steps = 0; + while (run.step()) steps++; + expect(steps).toBe(19); + expect(run.done).toBe(true); + const res = run.result; + expect(res.stop).toBeNull(); + res.frames.forEach((f, i) => expect(f.get('slider')!.p[0]).toBeCloseTo(slide(30) + ((50 - slide(30)) * res.times[i]) / 2, 5)); + // The crank's angle where the slider is at 50 mm: r cos θ + √(l² − r² sin² θ) = 50. + const th = angleZ(res.frames[20].get('crank')!.q); + expect(slide(deg(th))).toBeCloseTo(50, 4); + // The mate's measure as a result: its distance. + expect(mateSeries(res, drive)!.values[20]).toBeCloseTo(50, 5); + }); + + it('a mate driver stops where it would take a distance below zero or an angle outside 0° to 180°', () => { + // A block sliding along y on the ground, 10 from it, driven toward it at 3 mm/s for 5 s. + const slide = [mate('coincident', ['g', plane([5, 0, 0], [1, 0, 0])], ['b', plane([5, 0, 0], [1, 0, 0])]), mate('coincident', ['g', plane([0, 0, 5], Z)], ['b', plane([0, 0, 5], Z)])]; + const gap = mate('distance', ['g', plane([0, 0, 0], [0, 1, 0])], ['b', plane([0, 0, 0], [0, 1, 0])], { value: 10 }); + const bodies = [body('g', true), body('b', false, [0, 10, 0])]; + const driver: MotorInput = { id: 'mo', name: 'MateDriver1', kind: 'mate', mate: gap.id, at: profileOf('mate', { profile: 'constant', speed: -3 }, 5, 10) }; + const res = computeMotion({ bodies, mates: [...slide, gap], motors: [driver], duration: 5, fps: 10, scale: 100, names: new Map([[gap.id, 'Distance1']]) }); + expect(res.stop?.kind).toBe('limit'); + expect(res.stop?.mate).toBe(gap.id); + expect(res.stop?.time).toBeCloseTo(10 / 3, 3); + expect(res.stop?.message).toMatch(/MateDriver1 takes Distance1 below zero .* at 3\.333\d? s/); + // It ends touching (no frame past it), the last frame where the distance reaches zero. + expect(res.times.at(-1)).toBeCloseTo(10 / 3, 6); + for (const f of res.frames) expect(f.get('b')!.p[1]).toBeGreaterThan(-1e-6); + expect(res.frames.at(-1)!.get('b')!.p[1]).toBeCloseTo(0, 5); + // An angle swung past 180°: stopped there. + const hingeMates = [mate('concentric', ['g', axis([0, 0, 0])], ['b', axis([0, 0, 0])]), mate('coincident', ['g', plane([0, 0, 0], Z)], ['b', plane([0, 0, 0], Z)])]; + const ang = mate('angle', ['g', plane([0, 0, 0], [0, 1, 0])], ['b', plane([0, 0, 0], [0, 1, 0])], { value: 150 }); + const swing: MotorInput = { id: 'mo', name: 'MateDriver1', kind: 'mate', mate: ang.id, at: profileOf('mate', { profile: 'oscillate', amplitude: 60, frequency: 0.25 }, 2, 150) }; + const r2 = computeMotion({ bodies: [body('g', true), body('b', false, [0, 0, 0], qAxisAngle(Z, (150 * Math.PI) / 180))], mates: [...hingeMates, ang], motors: [swing], duration: 2, fps: 20, scale: 100 }); + expect(r2.stop?.kind).toBe('limit'); + expect(r2.stop?.message).toMatch(/past 180°/); + expect(r2.stop?.time).toBeCloseTo(Math.asin(0.5) / (2 * Math.PI * 0.25), 3); + }); + + it('profiles: constant speed (deg/s or rpm), oscillation, ramp, reversed', () => { + expect(profileOf('rotary', { profile: 'constant', speed: 90 }, 1)(2)).toBeCloseTo(Math.PI, 12); + expect(profileOf('rotary', { profile: 'constant', speed: 60, rpm: true }, 1)(0.5)).toBeCloseTo(Math.PI, 9); + expect(profileOf('linear', { profile: 'oscillate', amplitude: 10, frequency: 0.25, reverse: true }, 1)(1)).toBeCloseTo(-10, 12); + expect(profileOf('mate', { profile: 'constant', speed: 5 }, 1, 20)(2)).toBe(30); + expect(profileOf('mate', { profile: 'ramp', from: 10, to: 30 }, 4)(1)).toBe(15); + expect(profileOf('mate', { profile: 'ramp', from: 10, to: 30 }, 4)(9)).toBe(30); + }); + + it('a linear motor moves a component along a direction', () => { + const mates = [mate('coincident', ['g', plane([0, 0, 0], [0, 1, 0])], ['s', plane([0, 0, 0], [0, 1, 0])]), mate('coincident', ['g', plane([0, 0, 0], Z)], ['s', plane([0, 0, 0], Z)])]; + const motor: MotorInput = { id: 'mo', name: 'LinearMotor1', kind: 'linear', body: 's', entity: { body: 's', geo: { kind: 'line', p: [0, 0, 0], d: [1, 0, 0] } }, at: profileOf('linear', { profile: 'oscillate', amplitude: 10, frequency: 0.5 }, 2) }; + const res = computeMotion({ bodies: [body('g', true), body('s', false)], mates, motors: [motor], duration: 2, fps: 20, scale: 100 }); + res.frames.forEach((f, i) => expect(f.get('s')!.p[0]).toBeCloseTo(10 * Math.sin(Math.PI * res.times[i]), 6)); + }); + + it('frames keep only the components that move (a long study of a large assembly fits in memory)', () => { + const cs = crankSlider(30); + // 500 components the mechanism does not touch, one of them turned and floating. + const idle = Array.from({ length: 500 }, (_, i) => body(`idle${i}`, i > 0, [i, 50, 0], i === 1 ? qAxisAngle(Z, 0.5) : [0, 0, 0, 1])); + const res = computeMotion({ bodies: [...cs.bodies, ...idle], mates: cs.mates, motors: [rotary('crank', axis([0, 0, 0]), 90)], duration: 4, fps: 25, scale: 200 }); + expect(res.stop).toBeNull(); + expect(res.frames).toHaveLength(101); + expect(res.frames[50].size).toBeLessThan(10); + // The others read where they are. + expect(res.frames[50].has('idle1')).toBe(true); + expect(res.frames[50].get('idle1')).toEqual(idle[1].placement); + expect(pointPath(res, 'idle1', [1, 0, 0])[100]).toEqual(pointPath(res, 'idle1', [1, 0, 0])[0]); + expect(degreesAbout(turnPath(res, 'idle1'), Z)[100]).toBe(0); + res.frames.forEach((f, i) => expect(f.get('slider')!.p[0]).toBeCloseTo(slide(30 + 90 * res.times[i]), 4)); + const gap = mate('distance', ['idle1', plane([0, 0, 0], [1, 0, 0])], ['slider', plane([0, 0, 0], [1, 0, 0])], { value: 0 }); + const series = mateSeries(res, gap)!.values; + expect(series[100] - series[0]).toBeCloseTo(slide(390) - slide(30), 4); + }); + + it('spreads interference checks over the time, and groups components that moved together', () => { + // Frames 0.1 s apart, then (a fast stretch) 0.025 s apart. + const times = [0, 0.1, 0.2, 0.225, 0.25, 0.275, 0.3, 0.325, 0.35, 0.375, 0.4]; + expect(framesSpread(times, 5)).toEqual([0, 1, 2, 6, 10]); + expect(framesSpread(times, 50)).toHaveLength(11); + // As many as asked for, each a frame of its own (frames 0.1 s apart where 0.05 s would be wanted). + const picks = framesSpread([0, 0.1, 0.2, 0.3, 0.325, 0.35, 0.375, 0.4], 7); + expect(picks).toEqual([0, 1, 2, 3, 4, 5, 7]); + expect(framesSpread([0], 40)).toEqual([0]); + const at = (p: Vec3, q: Quat = [0, 0, 0, 1]): Placement => ({ p, q }); + const turn = qAxisAngle(Z, 0.7); + const from = [at([0, 0, 0]), at([10, 0, 0]), at([0, 5, 0]), at([3, 3, 3]), at([1, 2, 3])]; + // 0 and 1 still; 2 and 3 turned together about z; 4 moved. + const rot = (p: Placement): Placement => ({ p: qRotate(turn, p.p), q: turn }); + const g = sameMotionGroups(from, [from[0], from[1], rot(from[2]), rot(from[3]), at([1, 2, 4])]); + expect(g[0]).toBe(g[1]); + expect(g[2]).toBe(g[3]); + expect(new Set([g[0], g[2], g[4]]).size).toBe(3); + }); + + it('differentiates samples and writes CSV', () => { + const t = [0, 0.1, 0.2, 0.3, 0.4]; + const { d1, d2 } = derivatives(t, t.map((x) => x * x)); + expect(d1[2]).toBeCloseTo(0.4, 12); + expect(d2[2]).toBeCloseTo(2, 9); + expect(d2[0]).toBeCloseTo(2, 9); + // At the first and last samples too: the velocity of t² there, and of a harmonic motion's acceleration (zero at its middle position). + expect(d1[0]).toBeCloseTo(0, 12); + expect(d1[4]).toBeCloseTo(0.8, 12); + const ts = Array.from({ length: 31 }, (_, i) => i / 30), x = ts.map((s) => 10 * Math.sin(2 * Math.PI * s)); + const h = derivatives(ts, x), peak = 10 * (2 * Math.PI) ** 2; + expect(Math.abs(h.d2[0])).toBeLessThan(0.02 * peak); + expect(Math.abs(h.d2[30])).toBeLessThan(0.02 * peak); + expect(h.d1[0] / (20 * Math.PI)).toBeCloseTo(1, 1); + // Frames not evenly spaced (a study took smaller steps between 0.5 s and 0.8 s): the slope where the steps change is as good as elsewhere. + const tu: number[] = []; + for (let k = 0; k <= 20; k++) { if (k > 5 && k <= 8) for (let j = 1; j < 4; j++) tu.push((k - 1 + j / 4) / 10); tu.push(k / 10); } + const f = (s: number) => 400 * Math.sin(2 * Math.PI * s), df = (s: number) => 800 * Math.PI * Math.cos(2 * Math.PI * s); + const even = Array.from({ length: 21 }, (_, k) => k / 10), de = derivatives(even, even.map(f)).d1; + const worstEven = Math.max(...even.map((s, i) => Math.abs(de[i] - df(s)))); + const du = derivatives(tu, tu.map(f)).d1; + tu.forEach((s, i) => expect(Math.abs(du[i] - df(s))).toBeLessThanOrEqual(worstEven + 1e-9)); + expect(derivatives([0, 0.5], [1, 2]).d1).toEqual([2, 2]); + expect(resultsCsv([{ name: 'Time (s)', values: [0, 0.5] }, { name: 'X, mm', values: [1, 2.25] }])).toBe('Time (s),"X, mm"\n0,1\n0.5,2.25'); + expect(len(sub(pointPath({ times: [0], frames: [new Map([['a', { p: [1, 2, 3], q: [0, 0, 0, 1] }]])], stop: null, duration: 1 }, 'a', [1, 0, 0])[0], [2, 2, 3]))).toBe(0); + }); +}); + +describe('slider, cam and universal joint mates', () => { + const X: Vec3 = [1, 0, 0], Y: Vec3 = [0, 1, 0]; + const line = (p: Vec3, d: Vec3): Geo => ({ kind: 'line', p, d }); + const at0: Placement = { p: [0, 0, 0], q: [0, 0, 0, 1] }; + /** A slider of `b` along x on the ground's x axis (straight edges), from where b is. */ + const slider = (b: SolverBody, extra: Partial = {}) => mate('slider', ['g', line([0, 0, 0], X)], [b.id, line([0, 0, 0], X)], { rel: relativePlacement(at0, b.placement), ...extra }); + + it('a slider on straight edges leaves one move along them, no turn, and stops at its travel limits', () => { + const blk = body('blk', false, [5, 3, -2]); + const s = new MateSolver([body('g', true), blk], [slider(blk, { limit: { min: -10, max: 20 } })]); + const r = s.analyze(); + expect(r.status).toBe('under'); + expect(r.dof).toBe(1); + const p = r.placements.get('blk')!; + expect(Math.hypot(p.p[1], p.p[2])).toBeLessThan(1e-6); + expect(p.q[3]).toBeCloseTo(1, 9); + // Dragged up and along: it only slides, and stops 20 mm from where it was added. + let pl = r.placements; + for (let k = 1; k <= 8; k++) pl = s.solve({ drag: { kind: 'move', body: 'blk', local: [0, 0, 0], target: [5 + 5 * k, 30, 0] } }, s.mates, pl).placements; + expect(pl.get('blk')!.p[0]).toBeCloseTo(25, 4); + expect(pl.get('blk')!.p[1]).toBeCloseTo(0, 6); + expect(mateMeasure(s.mates[0], pl)!.value).toBeCloseTo(20, 4); + // A turn about the edge is held too. + const turned = s.solve({ drag: { kind: 'rotate', body: 'blk', q: qAxisAngle(X, 0.8) } }, s.mates, pl); + expect(turned.placements.get('blk')!.q[3]).toBeCloseTo(1, 6); + }); + + it('a slider on straight edges set to the other alignment turns the component over, and leaves one freedom', () => { + const blk = body('blk', false, [3, 4, 5]); + const m = slider(blk, { aligned: false }); + const r = new MateSolver([body('g', true), blk], [m]).analyze(); + expect(r.dof).toBe(1); + const q = r.placements.get('blk')!.q; + expect(qRotate(q, X)[0]).toBeCloseTo(-1, 6); + expect(qRotate(q, Z)[2]).toBeCloseTo(1, 6); + const again = new MateSolver([body('g', true), { ...blk, placement: r.placements.get('blk')! }], [m]).analyze(); + expect(again.dof).toBe(1); + expect(again.placements.get('blk')!.q.map((v, i) => Math.abs(v - q[i]) < 1e-6 || Math.abs(v + q[i]) < 1e-6).every(Boolean)).toBe(true); + }); + + it('a slider on two faces of each component slides along the line where they meet', () => { + const m = mate('slider', ['g', plane([0, 0, 0], Y)], ['blk', plane([0, 0, 0], [0, -1, 0])], { + a2: { body: 'g', geo: plane([0, 0, 0], Z) }, b2: { body: 'blk', geo: plane([0, 0, 0], [0, 0, -1]) }, aligned: false, aligned2: false, rel: at0, + }); + const r = new MateSolver([body('g', true), body('blk', false, [7, 4, 3], qAxisAngle(normalize([1, 1, 1]), 0.2))], [m]).analyze(); + expect(r.dof).toBe(1); + const p = r.placements.get('blk')!; + expect(Math.hypot(p.p[1], p.p[2])).toBeLessThan(1e-6); + const bad = { ...m, a2: { body: 'g', geo: plane([0, 5, 0], Y) } }; + expect(new MateSolver([body('g', true), body('blk', false)], [bad]).analyze().invalid.get(bad.id)).toMatch(/must not be parallel/); + }); + + it('motors on a slider and on a hinge drive them directly', () => { + const blk = body('blk', false, [0, 0, 0]); + const sl = slider(blk); + const lin: MotorInput = { id: 'mo', name: 'LinearMotor1', kind: 'linear', on: sl, at: profileOf('linear', { profile: 'constant', speed: 4 }, 3) }; + const res = computeMotion({ bodies: [body('g', true), blk], mates: [sl], motors: [lin], duration: 3, fps: 10, scale: 100 }); + expect(res.stop).toBeNull(); + res.frames.forEach((f, i) => expect(f.get('blk')!.p[0]).toBeCloseTo(4 * res.times[i], 6)); + // A hinge whose second component is fixed: the first turns, the other way. + const h = hinge('arm', [0, 0, 0], 'g', [0, 0, 0]); + const rot: MotorInput = { id: 'mo', name: 'RotaryMotor1', kind: 'rotary', on: h, at: profileOf('rotary', { profile: 'constant', speed: 90 }, 1) }; + const r2 = computeMotion({ bodies: [body('g', true), body('arm', false)], mates: [h], motors: [rot], duration: 1, fps: 20, scale: 100 }); + expect(r2.stop).toBeNull(); + expect(degreesAbout(turnPath(r2, 'arm'), Z)[20]).toBeCloseTo(-90, 5); + }); + + /** A cam turning on a hinge about z at the origin; a follower sliding along y on the line x = 0. */ + const camRig = (profile: Geo, follower: Geo, y0: number) => { + const fol = body('fol', false, [0, y0, 0]); + const mates = [ + hinge('g', [0, 0, 0], 'cam', [0, 0, 0]), + mate('slider', ['g', line([0, 0, 0], Y)], ['fol', line([0, 0, 0], Y)], { rel: relativePlacement(at0, fol.placement) }), + mate('cam', ['cam', profile], ['fol', follower]), + ]; + const drive: MotorInput = { id: 'mo', name: 'RotaryMotor1', kind: 'rotary', on: mates[0], at: profileOf('rotary', { profile: 'constant', speed: 90 }, 4) }; + return { bodies: [body('g', true), body('cam', false), fol], mates, motors: [drive] }; + }; + const e = 6, R = 20; + /** An eccentric: a round face of radius R whose axis is e from the turning axis (its low side up at first). */ + const eccentric = camProfile(Z, [{ c: [0, -e, 0], r: R }], []); + + it('an eccentric cam lifts a flat follower by e(1 − cos θ) over a turn', () => { + expect(eccentric.circle).not.toBeNull(); + const rig = camRig(eccentric, plane([0, 0, 0], [0, -1, 0]), R - e); + expect(new MateSolver(rig.bodies, rig.mates).analyze().dof).toBe(1); + const res = computeMotion({ ...rig, duration: 4, fps: 60, scale: 100 }); + expect(res.stop).toBeNull(); + const theta = degreesAbout(turnPath(res, 'cam'), Z).map((d) => (d * Math.PI) / 180); + expect(theta[240]).toBeCloseTo(2 * Math.PI, 6); + res.frames.forEach((f, i) => expect(f.get('fol')!.p[1] - (R - e)).toBeCloseTo(e * (1 - Math.cos(theta[i])), 7)); + }); + + it('roller and knife-edge followers on an eccentric match the closed form', () => { + const rho = 5; + const lift = (th: number, r: number) => { const cx = e * Math.sin(th), cy = -e * Math.cos(th); return cy + Math.sqrt(r * r - cx * cx); }; + for (const [follower, r] of [[axis([0, 0, 0], Z, rho), R + rho], [{ kind: 'point', p: [0, 0, 0] } as Geo, R]] as [Geo, number][]) { + const rig = camRig(eccentric, follower, r - e); + const res = computeMotion({ ...rig, duration: 4, fps: 60, scale: 100 }); + expect(res.stop).toBeNull(); + const theta = degreesAbout(turnPath(res, 'cam'), Z).map((d) => (d * Math.PI) / 180); + res.frames.forEach((f, i) => expect(f.get('fol')!.p[1]).toBeCloseTo(lift(theta[i], r), 7)); + } + }); + + it('a lobed cam (arcs and corners) lifts a flat follower to its nose; a hollow profile is refused', () => { + // A base circle of 20 and a nose of 5 at 25 above the axis, joined by tangent lines (touching both at 90° ± 53.13°). + const p = (r: number, deg: number, c: Vec3 = [0, 0, 0]): Vec3 => [c[0] + r * Math.cos((deg * Math.PI) / 180), c[1] + r * Math.sin((deg * Math.PI) / 180), 0]; + const t = (Math.acos(0.6) * 180) / Math.PI, nose: Vec3 = [0, 25, 0]; + const lobed = camProfile(Z, [{ c: [0, 0, 0], r: 20, ends: [p(20, 90 + t), p(20, 90 - t), p(20, 270)] }, { c: nose, r: 5, ends: [p(5, 90 - t, nose), p(5, 90 + t, nose), p(5, 90, nose)] }], []); + expect(lobed.concave).toBeLessThan(1e-9); + const rig = camRig(lobed, plane([0, 0, 0], [0, -1, 0]), 30); + const res = computeMotion({ ...rig, duration: 2, fps: 60, scale: 100 }); + expect(res.stop).toBeNull(); + expect(res.frames[0].get('fol')!.p[1]).toBeCloseTo(30, 6); + // Half a turn: the base circle under the follower. + expect(res.frames[120].get('fol')!.p[1]).toBeCloseTo(20, 7); + // A notch: corners of a square with one side dented in. + const notched = camProfile(Z, [], [[-10, -10, 0], [10, -10, 0], [10, 10, 0], [0, 4, 0], [-10, 10, 0]]); + expect(notched.concave).toBeCloseTo(6, 9); + const bad = new MateSolver(rig.bodies, [...rig.mates.slice(0, 2), mate('cam', ['cam', notched], ['fol', plane([0, 0, 0], [0, -1, 0])])]).analyze(); + expect([...bad.invalid.values()][0]).toMatch(/hollow 6 mm deep/); + }); + + /** Two shafts on hinges, meeting at the origin: a along z, b at β to it in the xz plane. */ + const uJoint = (betaDeg: number) => { + const b = (betaDeg * Math.PI) / 180; + const db: Vec3 = [Math.sin(b), 0, Math.cos(b)]; + const qb = qAxisAngle(Y, b); + const bodies = [body('g', true), body('A', false), body('B', false, [0, 0, 0], qb)]; + const mates = [ + hinge('g', [0, 0, 0], 'A', [0, 0, 0]), + mate('hinge', ['g', { kind: 'axis', p: [0, 0, 0], d: db, r: 2, surface: 'cylinder' }], ['B', axis([0, 0, 0])], { a2: { body: 'g', geo: plane([0, 0, 0], db) }, b2: { body: 'B', geo: plane([0, 0, 0], [0, 0, -1]) }, aligned2: false }), + mate('universal', ['A', axis([0, 0, 0])], ['B', axis([0, 0, 0])], { rel: relativePlacement(at0, { p: [0, 0, 0], q: qb }) }), + ]; + return { bodies, mates, db, b }; + }; + + it('a universal joint turns its output by atan(tan φ / cos β) over a full turn, with that velocity ratio', () => { + const u = uJoint(30); + expect(new MateSolver(u.bodies, u.mates).analyze().dof).toBe(1); + const motor: MotorInput = { id: 'mo', name: 'RotaryMotor1', kind: 'rotary', on: u.mates[0], at: profileOf('rotary', { profile: 'constant', speed: 90 }, 4) }; + const res = computeMotion({ bodies: u.bodies, mates: u.mates, motors: [motor], duration: 4, fps: 90, scale: 100 }); + expect(res.stop).toBeNull(); + const phi = degreesAbout(turnPath(res, 'A'), Z).map((d) => (d * Math.PI) / 180); + const out = degreesAbout(turnPath(res, 'B'), u.db).map((d) => (d * Math.PI) / 180); + // The closed form, unwrapped past ±90° and ±180°. + let prev = 0, acc = 0; + const expected = phi.map((f) => { const a = Math.atan2(Math.sin(f), Math.cos(u.b) * Math.cos(f)); let d = a - prev; d -= 2 * Math.PI * Math.round(d / (2 * Math.PI)); acc += d; prev = a; return acc; }); + expect(phi[360]).toBeCloseTo(2 * Math.PI, 6); + out.forEach((v, i) => expect(v).toBeCloseTo(expected[i], 6)); + expect(out[360]).toBeCloseTo(2 * Math.PI, 6); + // Velocity ratio from the frames against cos β / (cos²β cos²φ + sin²φ). + const w1 = derivatives(res.times, phi).d1, w2 = derivatives(res.times, out).d1; + for (const i of [0, 45, 90, 135, 200, 300]) { + const f = phi[i], k = Math.cos(u.b) / (Math.cos(u.b) ** 2 * Math.cos(f) ** 2 + Math.sin(f) ** 2); + expect(w2[i] / w1[i]).toBeCloseTo(k, 2); + } + }); + + it('a universal joint with straight shafts turns 1:1, and can hold its joint point', () => { + const u = uJoint(0); + const motor: MotorInput = { id: 'mo', name: 'RotaryMotor1', kind: 'rotary', on: u.mates[0], at: profileOf('rotary', { profile: 'constant', speed: 120 }, 3) }; + const res = computeMotion({ bodies: u.bodies, mates: u.mates, motors: [motor], duration: 3, fps: 30, scale: 100 }); + const a = degreesAbout(turnPath(res, 'A'), Z), b = degreesAbout(turnPath(res, 'B'), Z); + a.forEach((v, i) => expect(b[i]).toBeCloseTo(v, 6)); + expect(a[90]).toBeCloseTo(360, 5); + // Free shafts with a joint point 10 along a's axis: b's axis passes through it. + const joint = mate('universal', ['A', axis([0, 0, 0])], ['B', axis([0, 0, 0])], { rel: relativePlacement(at0, { p: [3, 4, 30], q: qAxisAngle(Y, 0.4) }), by: 'point', value: 10 }); + const r = new MateSolver([body('A', true), body('B', false, [3, 4, 30], qAxisAngle(Y, 0.4))], [joint]).analyze(); + expect(r.dof).toBe(3); + const pb = r.placements.get('B')!; + const db = qRotate(pb.q, Z); + const off = sub([0, 0, 10], pb.p); + expect(len([off[1] * db[2] - off[2] * db[1], off[2] * db[0] - off[0] * db[2], off[0] * db[1] - off[1] * db[0]])).toBeLessThan(1e-6); + }); + + it('a universal joint between shafts at 90° is refused (it cannot turn), one at 89° works', () => { + const square = uJoint(90); + const r = new MateSolver(square.bodies, square.mates).analyze(); + expect(r.status).toBe('error'); + expect(r.invalid.get(square.mates[2].id)).toMatch(/90°/); + const steep = uJoint(89); + const s = new MateSolver(steep.bodies, steep.mates).analyze(); + expect(s.invalid.size).toBe(0); + expect(s.dof).toBe(1); + }); +}); + +describe('cam profiles from part faces', () => { + const deg = (r: number, a: number, c: Vec3 = [0, 0, 0], z = 0): Vec3 => [c[0] + r * Math.cos((a * Math.PI) / 180), c[1] + r * Math.sin((a * Math.PI) / 180), z]; + const t = (Math.acos(0.6) * 180) / Math.PI, nose: Vec3 = [0, 25, 0]; + const cyl = (name: string, c: Vec3, r: number) => ({ name, type: 'cylinder', center: c, area: 1, axis: { p: c, d: Z }, radius: r, feature: 'E1' }); + const flat = (name: string, n: Vec3, c: Vec3) => ({ name, type: 'plane', center: c, area: 1, normal: n, feature: 'E1' }); + const arc = (name: string, face: number, c: Vec3, r: number, a0: number, a1: number, am: number) => ({ name, type: 'circle', a: deg(r, a0, c), b: deg(r, a1, c), mid: deg(r, am, c), length: (r * Math.abs(a1 - a0) * Math.PI) / 180, faces: [face], center: c, axis: Z, radius: r }); + const seg = (name: string, face: number, a: Vec3, b: Vec3) => ({ name, type: 'line', a, b, mid: [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2, 0] as Vec3, length: len(sub(b, a)), faces: [face], dir: normalize(sub(b, a)) }); + // A lobed cam: base circle 20, nose 5 at 25, two flanks tangent to both. + const lobed = { + mesh: null, bbox: null, cones: {}, + faces: [cyl('base', [0, 0, 0], 20), cyl('nose', nose, 5), flat('right', normalize(deg(1, 90 - t)), deg(20, 90 - t)), flat('left', normalize(deg(1, 90 + t)), deg(20, 90 + t))], + edges: [ + arc('e0', 0, [0, 0, 0], 20, 90 + t, 90 - t + 360, 270), arc('e1', 1, nose, 5, 90 - t, 90 + t, 90), + seg('e2', 2, deg(20, 90 - t), deg(5, 90 - t, nose)), seg('e3', 3, deg(20, 90 + t), deg(5, 90 + t, nose)), + // Where the sides meet, along the axis (base and right flank, right flank and nose, ...). + ...([[0, 2, deg(20, 90 - t)], [2, 1, deg(5, 90 - t, nose)], [1, 3, deg(5, 90 + t, nose)], [3, 0, deg(20, 90 + t)]] as [number, number, Vec3][]).map(([f, g, p], k) => ({ ...seg(`s${k}`, f, p, [p[0], p[1], 10]), faces: [f, g] })), + ], + } as unknown as PartGeometry; + const ref = (name: string) => ({ name, sig: { type: 'x', c: [0, 0, 0] as Vec3, area: 1 } }); + + it('reads arcs from round faces and their edges, corners from flat faces, and an eccentric as a circle', () => { + const p = camProfileOf(lobed, ['base', 'nose', 'right', 'left'].map(ref), 'Cam<1>'); + if (typeof p === 'string') throw new Error(p); + expect(p.circle).toBeNull(); + expect(p.concave).toBeLessThan(1e-9); + const up = profileSupport(p, [dot(Y3, p.u), dot(Y3, p.v)]), down = profileSupport(p, [-dot(Y3, p.u), -dot(Y3, p.v)]); + expect(up).toBeCloseTo(30, 9); + expect(down).toBeCloseTo(20, 9); + // Just the base face, whole: a circle. + const whole = camProfileOf({ ...lobed, faces: [cyl('base', [5, 0, 0], 20)], edges: [{ ...arc('e', 0, [5, 0, 0], 20, 0, 360, 180), a: deg(20, 0, [5, 0, 0]), b: deg(20, 0, [5, 0, 0]) }] } as unknown as PartGeometry, [ref('base')], 'Cam<1>'); + expect(typeof whole !== 'string' && whole.circle?.r).toBe(20); + // An end face (across the axis) is not part of a profile. + expect(camProfileOf({ ...lobed, faces: [...lobed.faces, flat('end', Z, [0, 0, 10])] } as unknown as PartGeometry, ['base', 'end'].map(ref), 'Cam<1>')).toMatch(/one direction/); + }); + + it('refuses a profile that does not go all the way round (the follower would ride across the gap)', () => { + for (const some of [['base', 'nose'], ['right', 'left'], ['base', 'nose', 'right']]) expect(camProfileOf(lobed, some.map(ref), 'Cam<1>')).toMatch(/all the way round/); + expect(typeof camProfileOf(lobed, ['left', 'nose', 'base', 'right'].map(ref), 'Cam<1>')).toBe('object'); + }); +}); diff --git a/src/parametric/tests/assembly-model.test.ts b/src/parametric/tests/assembly-model.test.ts index 5d1c48356..827631981 100644 --- a/src/parametric/tests/assembly-model.test.ts +++ b/src/parametric/tests/assembly-model.test.ts @@ -164,3 +164,107 @@ describe('combined model', () => { expect(placementMatrix({ p: [1, 2, 3], q: [0, 0, 0, 1] })).toEqual([1, 0, 0, 1, 0, 1, 0, 2, 0, 0, 1, 3]); }); }); + +describe('mechanical mates and motion studies in files', () => { + const face = (name: string) => ({ name, sig: { type: 'plane', c: [0, 0, 0] as [number, number, number], area: 10, n: [0, 0, 1] as [number, number, number] } }); + const cyl = (name: string) => ({ name, sig: { type: 'cylinder', c: [0, 0, 0] as [number, number, number], area: 10 } }); + function kinematic(): AssemblyDocument { + const doc = sample(); + doc.mates.push( + { id: 'm20', name: 'Hinge1', type: 'hinge', a: { comp: 'c3', face: cyl('h') }, b: { comp: 'c4', face: cyl('k') }, a2: { comp: 'c3', face: face('f1') }, b2: { comp: 'c4', face: face('f2') }, aligned: true, aligned2: false, limit: { min: -30, max: '=Gap*20' }, rel: { p: [0, 0, 0], q: [0, 0, 0, 1] } }, + { id: 'm21', name: 'Gear1', type: 'gear', a: { comp: 'c4', face: cyl('k') }, b: { comp: 'c5', face: cyl('k') }, aligned: true, value: 20, value2: 40, reverse: true }, + { id: 'm22', name: 'Gear2', type: 'gear', a: { comp: 'c4', face: cyl('k') }, b: { comp: 'c5', face: cyl('k') }, aligned: true, value: 1, value2: 3, by: 'ratio' }, + { id: 'm23', name: 'Rack Pinion1', type: 'rackPinion', a: { comp: 'c4', face: cyl('k') }, b: { comp: 'c5', edge: { name: 'e', sig: { type: 'line', m: [0, 0, 0], len: 5 } } }, aligned: true, value: 50, by: 'revolution' }, + { id: 'm24', name: 'Screw1', type: 'screw', a: { comp: 'c3', face: cyl('h') }, b: { comp: 'c4', face: cyl('k') }, aligned: true, value: 1.5, reverse: true }, + { id: 'm25', name: 'Width1', type: 'width', a: { comp: 'c3', face: face('g1') }, a2: { comp: 'c3', face: face('g2') }, b: { comp: 'c4', face: face('t1') }, b2: { comp: 'c4', face: face('t2') }, aligned: true }, + { id: 'm26', name: 'Slot1', type: 'slot', a: { comp: 'c3', face: cyl('s1') }, a2: { comp: 'c3', face: cyl('s2') }, b: { comp: 'c4', face: cyl('k') }, aligned: true }, + { id: 'm27', name: 'LimitDistance1', type: 'distance', a: { plane: 'top' }, b: { comp: 'c4', face: face('t1') }, aligned: true, value: 10, limit: { min: 5, max: 20 } }, + ); + doc.studies = [{ + id: 's30', name: 'Motion Study1', duration: 2, fps: 30, motors: [ + { id: 'o31', name: 'RotaryMotor1', kind: 'rotary', ref: { comp: 'c4', face: cyl('k') }, profile: 'constant', speed: 60, rpm: true }, + { id: 'o32', name: 'LinearMotor1', kind: 'linear', ref: { comp: 'c5', edge: { name: 'e', sig: { type: 'line', m: [0, 0, 0], len: 5 } } }, profile: 'oscillate', amplitude: 5, frequency: '=Gap', reverse: true }, + { id: 'o33', name: 'MateDriver1', kind: 'mate', mate: 'm27', profile: 'ramp', from: 5, to: 20, suppressed: true }, + ], + }]; + return doc; + } + + it('round-trips mechanical mates, limits and motion studies, and allocates ids past them', () => { + const doc = kinematic(); + const back = parseAssembly(serializeDocument(doc as never)); + expect(back).toEqual({ ...doc, nextId: 34 }); + expect(nextAsmId(back, 'm')).toBe('m34'); + // Files from before studies have none, and say nothing about them. + expect('studies' in parseAssembly(serializeDocument(sample() as never))).toBe(false); + }); + + it('refuses mechanical mates and studies with bad or misplaced fields', () => { + const text = serializeDocument(kinematic() as never); + const edit = (patch: (d: Record) => void) => { const raw = JSON.parse(text); patch(raw); return () => parseAssembly(JSON.stringify(raw)); }; + const mate = (id: string) => (d: Record) => d.mates.find((m: { id: string }) => m.id === id); + expect(edit((d) => { delete mate('m20')(d).b2; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m20')(d).a2 = { comp: 'c99', face: face('x') }; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m20')(d).a2 = { comp: 'c3' }; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m20')(d).limit = { min: 1 }; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m20')(d).aligned2 = 'yes'; })).toThrow(/invalid mate/); + expect(edit((d) => { delete mate('m21')(d).value2; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m21')(d).reverse = 1; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m21')(d).by = 'revolution'; })).toThrow(/invalid mate/); + expect(edit((d) => { delete mate('m24')(d).value; })).toThrow(/invalid mate/); + expect(edit((d) => { d.mates[0].a2 = d.mates[0].a; })).toThrow(/invalid mate/); + expect(edit((d) => { d.mates[0].limit = { min: 0, max: 1 }; })).toThrow(/invalid mate/); + expect(edit((d) => { d.mates[0].reverse = true; })).toThrow(/invalid mate/); + expect(edit((d) => { d.mates[0].value2 = 3; })).toThrow(/invalid mate/); + expect(edit((d) => { d.studies = {}; })).toThrow(/invalid motion study/); + expect(edit((d) => { d.studies[0].fps = 0; })).toThrow(/invalid motion study/); + expect(edit((d) => { d.studies[0].duration = 3000; d.studies[0].fps = 100; })).toThrow(/invalid motion study/); + expect(edit((d) => { d.studies[0].id = 'c3'; })).toThrow(/invalid motion study/); + expect(edit((d) => { d.studies[0].motors[0].ref = { comp: 'c99', face: face('x') }; })).toThrow(/invalid motor/); + expect(edit((d) => { d.studies[0].motors[0].profile = 'ramp'; d.studies[0].motors[0].from = 0; d.studies[0].motors[0].to = 1; })).toThrow(/invalid motor/); + expect(edit((d) => { delete d.studies[0].motors[0].speed; })).toThrow(/invalid motor/); + expect(edit((d) => { d.studies[0].motors[1].rpm = true; })).toThrow(/invalid motor/); + expect(edit((d) => { d.studies[0].motors[2].mate = 'm99'; })).toThrow(/invalid motor/); + expect(edit((d) => { d.studies[0].motors[2].ref = d.studies[0].motors[0].ref; })).toThrow(/invalid motor/); + expect(edit((d) => { d.studies[0].motors[1].id = d.studies[0].motors[0].id; })).toThrow(/invalid motor/); + expect(edit((d) => { d.studies[0].motors[0].kind = 'jet'; })).toThrow(/invalid motor/); + // Unknown fields of a motor are dropped. + const back = parseAssembly(JSON.stringify({ ...JSON.parse(text), studies: [{ ...JSON.parse(text).studies[0], motors: [{ ...JSON.parse(text).studies[0].motors[0], extra: 1 }] }] })); + expect('extra' in back.studies![0].motors[0]).toBe(false); + }); + + it('round-trips sliders, cams and universal joints, and motors on hinges and sliders; refuses them malformed', () => { + const doc = kinematic(); + const edge = { name: 'e', sig: { type: 'line', m: [0, 0, 0] as [number, number, number], len: 5 } }; + const rel = { p: [1, 2, 3] as [number, number, number], q: [0, 0, 0, 1] as [number, number, number, number] }; + doc.mates.push( + { id: 'm40', name: 'Slider1', type: 'slider', a: { comp: 'c3', edge }, b: { comp: 'c4', edge }, aligned: true, rel, limit: { min: -5, max: '=Gap*10' } }, + { id: 'm41', name: 'Slider2', type: 'slider', a: { comp: 'c3', face: face('f1') }, a2: { comp: 'c3', face: face('f2') }, b: { comp: 'c4', face: face('f3') }, b2: { comp: 'c4', face: face('f4') }, aligned: false, aligned2: true, rel }, + { id: 'm42', name: 'Cam1', type: 'cam', a: { comp: 'c3', face: cyl('lobe') }, chain: [face('flank'), cyl('nose')], b: { comp: 'c4', point: [1, 2, 3] }, aligned: true, flip: true }, + { id: 'm43', name: 'Universal Joint1', type: 'universal', a: { comp: 'c3', face: cyl('h') }, b: { comp: 'c4', face: cyl('k') }, aligned: true, rel, by: 'point', value: '=Gap' }, + ); + doc.studies![0].motors.push( + { id: 'o44', name: 'RotaryMotor2', kind: 'rotary', mate: 'm20', profile: 'constant', speed: 30 }, + { id: 'o45', name: 'LinearMotor2', kind: 'linear', mate: 'm40', profile: 'oscillate', amplitude: 3, frequency: 1 }, + ); + const text = serializeDocument(doc as never); + expect(parseAssembly(text)).toEqual({ ...doc, nextId: 46 }); + const edit = (patch: (d: Record) => void) => { const raw = JSON.parse(text); patch(raw); return () => parseAssembly(JSON.stringify(raw)); }; + const mate = (id: string) => (d: Record) => d.mates.find((m: { id: string }) => m.id === id); + expect(edit((d) => { delete mate('m40')(d).rel; })).toThrow(/invalid mate/); + expect(edit((d) => { delete mate('m41')(d).b2; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m40')(d).limit = { min: 'x' , max: null }; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m42')(d).chain = 'flank'; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m42')(d).chain = [{ name: 'x' }]; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m42')(d).b = { comp: 'c4', point: [1, 2] }; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m42')(d).a = { comp: 'c3', point: [1, 2, 3] }; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m21')(d).chain = [face('x')]; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m21')(d).b = { comp: 'c5', point: [0, 0, 0] }; })).toThrow(/invalid mate/); + expect(edit((d) => { delete mate('m43')(d).value; })).toThrow(/invalid mate/); + expect(edit((d) => { delete mate('m43')(d).rel; })).toThrow(/invalid mate/); + expect(edit((d) => { mate('m43')(d).by = 'ratio'; })).toThrow(/invalid mate/); + expect(edit((d) => { d.studies[0].motors[3].ref = d.studies[0].motors[0].ref; })).toThrow(/invalid motor/); + expect(edit((d) => { d.studies[0].motors[3].mate = 'm99'; })).toThrow(/invalid motor/); + expect(edit((d) => { d.studies[0].motors[4].profile = 'ramp'; d.studies[0].motors[4].from = 0; d.studies[0].motors[4].to = 1; })).toThrow(/invalid motor/); + }); +}); diff --git a/src/parametric/tests/e2e/analysis.spec.ts b/src/parametric/tests/e2e/analysis.spec.ts new file mode 100644 index 000000000..2cf37680e --- /dev/null +++ b/src/parametric/tests/e2e/analysis.spec.ts @@ -0,0 +1,598 @@ +import { type Page, expect, test } from '@playwright/test'; +import { openApp } from './helpers'; + +type W = { __parametric: import('../../src/app/app').App }; + +/** Where the centre of a face (by name) is on the page, once the camera stopped moving. */ +async function facePoint(page: Page, name: string): Promise<{ x: number; y: number }> { + return page.evaluate(async (name) => { + const a = (window as unknown as W).__parametric; + await a.whenBuilt(); + const f = a.faces.find((x) => x.name === name)!; + const at = () => { + const [x, y] = a.viewport.project(f.center); + const r = a.viewport.canvas.getBoundingClientRect(); + return { x: r.x + x, y: r.y + y }; + }; + let last = at(); + for (let i = 0; i < 40; i++) { + await new Promise((r) => setTimeout(r, 50)); + const n = at(); + if (Math.abs(n.x - last.x) + Math.abs(n.y - last.y) < 0.5) break; + last = n; + } + return last; + }, name); +} + +test('sets up a static study, runs it, reads the plot and saves it with the part', async ({ page }) => { + test.setTimeout(240_000); + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await page.waitForFunction(() => !!(window as unknown as W).__parametric.bbox); + await page.getByRole('tab', { name: 'Analysis' }).click(); + + // Material: the preset's elastic properties are shown; Alloy Steel is chosen. + await page.locator('.cm-tools [data-cmd="material"]').click(); + const mat = page.getByRole('dialog', { name: 'Material' }); + await expect(mat.locator('.fea-material-props')).toContainText('Elastic modulus 68.9 GPa'); + await mat.getByLabel('Material', { exact: true }).selectOption({ label: 'Alloy Steel (7700 kg/m³)' }); + await expect(mat.locator('.fea-material-props')).toContainText('yield strength 415 MPa'); + await mat.getByRole('button', { name: 'Apply' }).click(); + + // A fixed face, picked in the graphics area. + await page.locator('[data-cmd="fea:fixed"]').click(); + await expect(page.locator('.pm-head').getByText('Fixed', { exact: true })).toBeVisible(); + let p = await facePoint(page, 'f1:side:bl1'); + await page.mouse.click(p.x, p.y); + await expect(page.getByRole('group', { name: 'Faces' })).toContainText('Face'); + await page.locator('.confirm-corner .ok').click(); + await expect(page.getByRole('treeitem', { name: /^Fixed1/ })).toBeVisible(); + + // A 500 N force pressing on the top of the upright. + await page.locator('[data-cmd="fea:force"]').click(); + p = await facePoint(page, 'f1:side:bl4'); + await page.mouse.click(p.x, p.y); + await page.getByLabel('Total force (N)').fill('500'); + await page.locator('.confirm-corner .ok').click(); + await expect(page.getByRole('treeitem', { name: /^Force1/ })).toBeVisible(); + expect(await page.evaluate(() => (window as unknown as W).__parametric.store.doc.study!.loads[0])).toMatchObject({ type: 'force', value: 500, dir: null, faces: [{ name: 'f1:side:bl4' }] }); + + // Run: the plot, its legend and the summary. + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + await expect(page.locator('.fea-legend')).toContainText('von Mises stress (MPa)'); + await expect(page.locator('.fea-legend')).toContainText('Yield strength: 415 MPa'); + const summary = page.locator('.fea-summary'); + await expect(summary).toContainText('Max von Mises stress'); + await expect(summary).toContainText('Min factor of safety'); + // Equilibrium: the reaction carries the 500 N. + await expect(page.locator('.fea-forces')).toContainText('0.000, 500.000, 0.000 N'); + + // Displacement plot, then a probe on the top of the base. + await page.getByLabel('Plot', { exact: true }).selectOption('disp'); + await expect(page.locator('.fea-legend')).toContainText('Displacement (mm)'); + await page.getByLabel('Plot', { exact: true }).selectOption('vonMises'); + await page.getByRole('button', { name: 'Probe' }).click(); + p = await facePoint(page, 'f1:side:bl2'); + await page.mouse.click(p.x + 30, p.y); + await expect(page.locator('.fea-probe')).toHaveCount(1); + await expect(page.locator('.fea-probe')).toContainText('MPa'); + await expect(page.locator('.fea-pin')).toHaveCount(1); + + // Editing the study puts the results out of date. + await page.getByRole('button', { name: 'Close', exact: true }).click(); + await expect(page.locator('.fea-legend')).toHaveCount(0); + await expect(page.getByRole('treeitem', { name: /^Results/ })).toBeVisible(); + await expect(page.getByRole('treeitem', { name: /^Results/ })).not.toHaveAttribute('aria-description', /Out of date/); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Edit', (d) => { d.study!.loads[0].value = 600; })); + await expect(page.getByRole('treeitem', { name: /^Results/ })).toHaveAttribute('aria-description', /Out of date/); + + // Saved with the part, and read back. + await page.evaluate(() => (window as unknown as W).__parametric.commands.run('save')); + const saveAs = page.getByRole('dialog', { name: 'Save As' }); + if (await saveAs.isVisible().catch(() => false)) await saveAs.getByRole('button', { name: 'Save' }).click(); + await expect(page).toHaveTitle(/Mounting Bracket - Parametric/); + // The title is the sample's already: wait for the save itself (the part has a file, written with the edit). + const readSaved = () => page.evaluate(async (url) => { + const { loadText } = await import(url); + const a = (window as unknown as W).__parametric; + return a.location ? JSON.parse(await loadText(a.location)) : null; + }, '/src/platform/files.ts'); + await expect.poll(async () => (await readSaved().catch(() => null))?.study?.loads?.[0]?.value ?? null).toBe(600); + const saved = await readSaved(); + expect(saved.study.fixtures).toHaveLength(1); + expect(saved.study.loads[0]).toMatchObject({ type: 'force', value: 600 }); + expect(saved.material).toMatchObject({ name: 'Alloy Steel', E: 205000 }); + await page.evaluate(async ({ text, url }) => { + const a = (window as unknown as W).__parametric; + const { parseDocument } = await import(url) as typeof import('../../src/model/document'); + a.loadDocument(parseDocument(text), null); + }, { text: JSON.stringify(saved), url: '/src/model/document.ts' }); + await page.getByRole('tab', { name: 'Analysis' }).click(); + await expect(page.getByRole('treeitem', { name: /^Force1/ })).toBeVisible(); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + await expect(page.locator('.fea-forces')).toContainText('0.000, 600.000, 0.000 N'); + expect(errors).toEqual([]); +}); + +test('explains a study that cannot run', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await page.waitForFunction(() => !!(window as unknown as W).__parametric.bbox); + await page.getByRole('tab', { name: 'Analysis' }).click(); + // No fixtures: the results panel says what is missing. + await page.locator('[data-cmd="fea:force"]').click(); + const p = await facePoint(page, 'f1:side:bl4'); + await page.mouse.click(p.x, p.y); + await page.locator('.confirm-corner .ok').click(); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.getByRole('alert').filter({ hasText: 'Add a fixture' })).toBeVisible(); + // A roller alone leaves the part free to slide: unstable. + await page.getByRole('button', { name: 'Close', exact: true }).click(); + await page.locator('[data-cmd="fea:roller"]').click(); + const q = await facePoint(page, 'f1:side:bl1'); + await page.mouse.click(q.x, q.y); + await page.locator('.confirm-corner .ok').click(); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.getByRole('alert').filter({ hasText: /unstable/ })).toBeVisible({ timeout: 60_000 }); + expect(errors).toEqual([]); +}); + +/** The bracket with Alloy Steel and a study holding one fixture and one force (set in the document, one undo step). */ +async function bracketStudy(page: Page) { + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await page.waitForFunction(() => !!(window as unknown as W).__parametric.bbox); + await page.evaluate(async () => { + const a = (window as unknown as W).__parametric; + await a.whenBuilt(); + const ref = (n: string) => { const f = a.faces.find((x) => x.name === n)!; return { name: f.name, sig: { type: f.type, c: f.center, n: f.normal, area: f.area } }; }; + a.store.change('Set up', (d) => { + d.material = { name: 'Alloy Steel', density: 7700, E: 205000, nu: 0.29, yield: 415, uts: 655 }; + d.study = { id: 'st900', name: 'Static Study', fixtures: [{ id: 'fx901', name: 'Fixed1', type: 'fixed', faces: [ref('f1:side:bl1')] }], loads: [{ id: 'ld902', name: 'Force1', type: 'force', faces: [ref('f1:side:bl4')], value: 500, dir: null, flip: false }], mesh: { fineness: 0.2 } }; + }); + }); + await page.getByRole('tab', { name: 'Analysis' }).click(); + await expect(page.getByRole('treeitem', { name: /^Force1/ })).toBeVisible(); +} + +test('a load direction to pick stays chosen until it is picked', async ({ page }) => { + const errors = await openApp(page); + await bracketStudy(page); + // "Along a picked edge or face" stays chosen while the edge is picked. + for (const cmd of ['fea:force', 'fea:gravity']) { + await page.locator(`[data-cmd="${cmd}"]`).click(); + const dir = page.getByLabel('Direction', { exact: true }); + await dir.selectOption('ref'); + await expect(page.getByRole('group', { name: 'Direction reference' })).toBeVisible(); + await expect(dir).toHaveValue('ref'); + if (cmd === 'fea:gravity') { + await page.locator('.confirm-corner .ok').click(); + await expect(page.locator('.pm-msg')).toContainText('Pick an edge or face for the direction'); + } + await page.locator('.confirm-corner .cancel').click(); + } + expect(errors).toEqual([]); +}); + +test('the panel of a fixture or load closes when it is deleted', async ({ page }) => { + const errors = await openApp(page); + await bracketStudy(page); + // Editing Force1 when it is deleted (here by Undo of its study): OK must not bring it back. + await page.getByRole('treeitem', { name: /^Force1/ }).dblclick(); + await expect(page.locator('.pm-head').getByText('Force1', { exact: true })).toBeVisible(); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Delete Force1', (d) => { d.study!.loads = []; })); + await expect(page.locator('.pm-head')).toHaveCount(0); + expect(await page.evaluate(() => (window as unknown as W).__parametric.store.doc.study!.loads)).toEqual([]); + // A new fixture when the study goes (Undo): its panel closes too. + await page.locator('[data-cmd="fea:fixed"]').click(); + await expect(page.locator('.pm-head').getByText('Fixed', { exact: true })).toBeVisible(); + await page.keyboard.press('Meta+z'); + await page.keyboard.press('Meta+z'); + await expect.poll(() => page.evaluate(() => (window as unknown as W).__parametric.store.doc.study ?? null)).toBeNull(); + await expect(page.locator('.pm-head')).toHaveCount(0); + expect(errors).toEqual([]); +}); + +test('the results panel shows the progress of the first run, with Cancel', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Finer', (d) => { d.study!.mesh.fineness = 0.7; })); + await page.locator('[data-cmd="fea:run"]').click(); + const bar = page.getByRole('progressbar', { name: 'Analysis progress' }); + await expect(bar).toBeVisible(); + await expect(page.locator('.fea-stage')).not.toBeEmpty(); + // Each stage is announced once, by the status bar (the panel's stage line is not a second live region). + await expect(page.locator('.statusbar .msg')).toHaveAttribute('role', 'status'); + await expect(page.locator('.fea-stage')).not.toHaveAttribute('role', /./); + await expect(page.locator('.fea-stage').locator('xpath=ancestor-or-self::*[@aria-live or @role="status" or @role="alert"]')).toHaveCount(0); + await page.locator('.pm-content').getByRole('button', { name: 'Cancel' }).click(); + await expect(bar).toHaveCount(0); + await expect(page.getByText('Run the study to see its results.')).toBeVisible(); + await expect(page.locator('.statusbar .msg')).toHaveText('Analysis cancelled'); + // Mesh Now in the study panel shows its progress too. + await page.locator('[data-cmd="fea:study"]').click(); + // The cancelled run may have finished meshing before it was cancelled (its mesh's stats stay shown). + const statsBefore = await page.locator('.fea-stats').count(); + await page.getByRole('button', { name: 'Mesh Now' }).click(); + await expect(page.getByRole('progressbar', { name: 'Progress' })).toBeVisible(); + await expect(page.getByRole('button', { name: 'Mesh Now' })).toBeDisabled(); + // It can be cancelled there (no new mesh is shown), and meshed again. + await page.locator('.pm-content').getByRole('button', { name: 'Cancel' }).click(); + await expect(page.getByRole('progressbar', { name: 'Progress' })).toHaveCount(0); + await expect(page.locator('.fea-stats')).toHaveCount(statsBefore); + await expect(page.locator('.statusbar .msg')).toHaveText('Analysis cancelled'); + await page.getByRole('button', { name: 'Mesh Now' }).click(); + await expect(page.locator('.fea-stats')).toBeVisible({ timeout: 120_000 }); + expect(errors).toEqual([]); +}); + +test('a study edited while it runs leaves its results out of date', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Finer', (d) => { d.study!.mesh.fineness = 0.7; })); + await page.locator('[data-cmd="fea:run"]').click(); + // While the part is being meshed, the force goes from 500 to 900 N. + await expect(page.locator('.fea-stage')).toContainText('Meshing', { timeout: 60_000 }); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Edit', (d) => { d.study!.loads[0].value = 900; })); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + // Solved with 500 N: shown as out of date. + await expect(page.locator('.fea-forces')).toContainText('0.000, 500.000, 0.000 N'); + await expect(page.getByRole('note').filter({ hasText: 'Out of date' })).toBeVisible(); + await expect(page.getByRole('button', { name: 'Run Again' })).toBeVisible(); + expect(errors).toEqual([]); +}); + +test('results stay up to date when the part is edited back to the shape solved', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + await page.getByRole('button', { name: 'Close', exact: true }).click(); + const results = page.getByRole('treeitem', { name: /^Results/ }); + await expect(results).not.toHaveAttribute('aria-description', /Out of date/); + // A feature opened for editing and cancelled: the same shape. + const v0 = await page.evaluate(() => (window as unknown as W).__parametric.geometryVersion); + await page.getByRole('treeitem', { name: /^Extrude1/ }).dblclick(); + await expect(page.locator('.pm-head').getByText('Extrude1')).toBeVisible(); + await page.locator('.confirm-corner .cancel').click(); + await expect(page.locator('.pm-head')).toHaveCount(0); + await page.evaluate(() => (window as unknown as W).__parametric.whenBuilt()); + expect(await page.evaluate(() => (window as unknown as W).__parametric.geometryVersion)).toBeGreaterThan(v0); + await expect(results).not.toHaveAttribute('aria-description', /Out of date/); + // A new shape puts them out of date; Undo brings the solved shape back. + await page.evaluate(() => { + const a = (window as unknown as W).__parametric; + a.store.change('Deeper', (d) => { const f = d.features.find((x) => x.name === 'Extrude1') as unknown as { depth: number }; f.depth = 33.3; }); + }); + await expect(results).toHaveAttribute('aria-description', /Out of date/); + await page.keyboard.press('Meta+z'); + await expect(results).not.toHaveAttribute('aria-description', /Out of date/); + expect(errors).toEqual([]); +}); + +test('loads of an inch part are in pounds-force and psi, with round defaults', async ({ page }) => { + const errors = await openApp(page); + await bracketStudy(page); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Units', (d) => { d.units = 'IPS'; })); + await page.locator('[data-cmd="fea:force"]').click(); + await expect(page.getByLabel('Total force (lbf)')).toHaveValue('100'); + await page.locator('.confirm-corner .cancel').click(); + await page.locator('[data-cmd="fea:pressure"]').click(); + await expect(page.getByLabel('Pressure (psi)')).toHaveValue('100'); + await page.locator('.confirm-corner .cancel').click(); + await page.locator('[data-cmd="fea:gravity"]').click(); + await expect(page.getByLabel('Acceleration (in/s²)')).toHaveValue('386.08858'); + await page.locator('.confirm-corner .cancel').click(); + // The material's stiffness and strength in psi, as the results are. + await page.locator('[data-cmd="fea:study"]').click(); + await expect(page.locator('.fea-material')).toHaveText('Alloy Steel: E 29,700,000 psi, ν 0.29, yield 60,200 psi'); + await page.getByRole('button', { name: 'Close', exact: true }).click(); + // Force1 (500 N) reads in lbf, and a value typed in lbf is kept in newtons. + await page.getByRole('treeitem', { name: /^Force1/ }).dblclick(); + await expect(page.getByLabel('Total force (lbf)')).toHaveValue('112.40447'); + await page.getByLabel('Total force (lbf)').fill('50'); + await page.locator('.confirm-corner .ok').click(); + await expect(page.locator('.pm-head')).toHaveCount(0); + expect(await page.evaluate(() => (window as unknown as W).__parametric.store.doc.study!.loads[0].value)).toBeCloseTo(222.411, 3); + expect(errors).toEqual([]); +}); + +test('the printable report says what its plot shows', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + await page.getByLabel('Plot', { exact: true }).selectOption('disp'); + await page.getByRole('button', { name: 'Report...' }).click(); + const popup = page.waitForEvent('popup'); + await page.getByRole('dialog', { name: 'Results Report' }).getByRole('button', { name: 'Printable Report' }).click(); + const report = await popup; + await report.evaluate(() => { window.print = () => {}; }); + await expect(report.locator('figcaption')).toContainText(/^Displacement from 0 mm to 0\.\d+ mm \(blue lowest, red highest\); deformation scale \d+/); + await expect(report.locator('img')).toHaveAttribute('alt', /^Displacement from/); + await report.close(); + expect(errors).toEqual([]); +}); + +test('the fixture and load symbols follow the part when it is edited', async ({ page }) => { + const errors = await openApp(page); + await bracketStudy(page); + // Highest Z of the tinted faces of the fixtures and loads. + const top = () => page.evaluate(() => { + const r = (window as unknown as W).__parametric.renderer as unknown as { tris: Map }; + const p = r.tris.get('feaFix')?.positions; + let z = -Infinity; + for (let i = 2; p && i < p.length; i += 3) z = Math.max(z, p[i]); + return z; + }); + await expect.poll(top).toBeCloseTo(30, 3); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Deeper', (d) => { (d.features.find((x) => x.name === 'Extrude1') as unknown as { depth: number }).depth = 80; })); + await expect.poll(top).toBeCloseTo(80, 3); + expect(errors).toEqual([]); +}); + +test('a part with a study opened while the Analysis tab is shown shows its fixtures and loads', async ({ page, browser }) => { + const errors = await openApp(page); + await bracketStudy(page); + const text = await page.evaluate(async (url) => { + const { serializeDocument } = await import(url) as typeof import('../../src/model/document'); + return serializeDocument((window as unknown as W).__parametric.store.doc); + }, '/src/model/document.ts'); + // A new window, where the analysis has not been loaded yet. + const other = await (await browser.newContext({ viewport: { width: 1440, height: 900 } })).newPage(); + const otherErrors = await openApp(other); + await other.getByRole('button', { name: /New part/ }).click(); + await other.getByRole('tab', { name: 'Analysis' }).click(); + await other.evaluate(async ({ text, url }) => { + const { parseDocument } = await import(url) as typeof import('../../src/model/document'); + (window as unknown as W).__parametric.loadDocument(parseDocument(text), null); + }, { text, url: '/src/model/document.ts' }); + await expect(other.getByRole('tab', { name: 'Analysis' })).toHaveAttribute('aria-selected', 'true'); + await expect.poll(() => other.evaluate(() => ((window as unknown as W).__parametric.renderer as unknown as { tris: Map }).tris.has('feaFix'))).toBe(true); + await other.context().close(); + expect(errors).toEqual([]); + expect(otherErrors).toEqual([]); +}); + +test.describe('on a phone', () => { + test.use({ viewport: { width: 412, height: 839 }, isMobile: true, hasTouch: true }); + + test('the result legend shows above the panel sheet, below the view toolbar', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.evaluate(() => (window as unknown as W).__parametric.commands.run('fea:run')); + await expect(page.locator('.fea-summary')).toBeAttached({ timeout: 120_000 }); + const legend = (await page.locator('.fea-legend').boundingBox())!; + const sheet = (await page.locator('.leftpane').boundingBox())!; + expect(legend.y + legend.height).toBeLessThanOrEqual(sheet.y); + expect(legend.x + legend.width).toBeLessThanOrEqual(412); + // The ticks stay inside the colour scale. + const ticks = (await page.locator('.fea-legend-ticks').boundingBox())!; + const bar = (await page.locator('.fea-legend-bar').boundingBox())!; + expect(ticks.y + ticks.height).toBeLessThanOrEqual(bar.y + bar.height + 1); + expect(errors).toEqual([]); + }); + + test('the Analysis ribbon labels break only between words', async ({ page }) => { + const errors = await openApp(page); + await bracketStudy(page); + // Words of a label wider than the label: a word broken across lines ("Roller/Slid er"). + const broken = await 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}`; + return l.textContent!.split(/\s+/).some((w) => c.measureText(w).width > l.clientWidth + 0.5) ? [l.textContent!] : []; + }); + }); + expect(broken).toEqual([]); + expect(errors).toEqual([]); + }); +}); + +test('Tab from the study name keeps the keyboard focus in the study panel', async ({ page }) => { + const errors = await openApp(page); + await bracketStudy(page); + await page.locator('[data-cmd="fea:study"]').click(); + await page.getByLabel('Study name').fill('Bracket Load Case'); + await page.keyboard.press('Tab'); + await expect.poll(() => page.evaluate(() => (window as unknown as W).__parametric.store.doc.study!.name)).toBe('Bracket Load Case'); + // The panel was drawn again with the new name: the focus is on the next control, not lost to the page. + await page.waitForTimeout(100); + expect(await page.evaluate(() => !!document.activeElement?.closest('.pm-content') && document.activeElement.getAttribute('aria-label') !== 'Study name')).toBe(true); + // An emptied name: the study keeps its name, and the field shows it. + await page.getByLabel('Study name').fill(' '); + await page.keyboard.press('Tab'); + await expect(page.getByLabel('Study name')).toHaveValue('Bracket Load Case'); + expect(await page.evaluate(() => (window as unknown as W).__parametric.store.doc.study!.name)).toBe('Bracket Load Case'); + expect(errors).toEqual([]); +}); + +test('the legend ticks share their decimals', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + const decimals = async () => (await page.locator('.fea-legend-ticks span').allInnerTexts()).filter((t) => !t.startsWith('≥')).map((t) => { + expect(t).toMatch(/^-?\d+(\.\d+)?$/); + return t.split('.')[1]?.length ?? 0; + }); + for (const field of ['vonMises', 'disp', 'strain', 'fos']) { + await page.getByLabel('Plot', { exact: true }).selectOption(field); + const d = await decimals(); + expect(d.length, field).toBeGreaterThan(3); + expect(new Set(d).size, field).toBe(1); + } + // A huge load: powers of ten rather than 12-digit numbers. + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Huge', (d) => { d.study!.loads[0].value = 1e12; })); + await page.getByRole('button', { name: 'Run Again' }).click(); + await expect(page.locator('.fea-summary')).toContainText('e+11 MPa', { timeout: 120_000 }); + await page.getByLabel('Plot', { exact: true }).selectOption('vonMises'); + for (const t of await page.locator('.fea-legend-ticks span').allInnerTexts()) expect(t.length, t).toBeLessThanOrEqual(10); + expect(errors).toEqual([]); +}); + +test('the CSV summary has one quantity per row, with its unit in the unit column', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Gravity', (d) => { d.study!.loads.push({ id: 'ld903', name: 'Gravity1', type: 'gravity', value: 9806.65, dir: { kind: 'base', axis: 'y' }, flip: true }); })); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + await page.getByRole('button', { name: 'Report...' }).click(); + const download = page.waitForEvent('download'); + await page.getByRole('dialog', { name: 'Results Report' }).getByRole('button', { name: 'Download CSV' }).click(); + const file = await download; + expect(file.suggestedFilename()).toBe('Mounting Bracket - Static Study.csv'); + const csv = (await (await file.createReadStream()).toArray()).join(''); + expect(csv).toContain('\nLoads,Force1 force,500,N\n'); + expect(csv).toContain('\nLoads,Force1 area,240,mm²\n'); + expect(csv).toContain('\nLoads,Gravity1 acceleration,9.80665,m/s²\n'); + // Every row: section, quantity, a value without its unit, the unit. + for (const line of csv.trim().split('\n').slice(1)) expect(line, line).not.toMatch(/,[-\d.e]+ (N|MPa|mm|%)/); + expect(errors).toEqual([]); +}); + +test('Run right after an edit that renumbers the faces loads the faces picked', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.locator('[data-cmd="fea:study"]').click(); + await page.getByRole('button', { name: 'Close', exact: true }).click(); + // Suppressing the fillet renumbers the faces; Run comes before the part is rebuilt. + await page.evaluate(() => { + const a = (window as unknown as W).__parametric; + a.store.change('Suppress', (d) => { d.features.find((x) => x.name === 'Fillet1')!.suppressed = true; }); + a.commands.run('fea:run'); + }); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + // The force on the top of the upright, held at the end of the base. + await expect(page.locator('.fea-forces')).toContainText('0.000, 500.000, 0.000 N'); + expect(errors).toEqual([]); +}); + +test('the analysis loads on a later try when its code failed to load', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await page.waitForFunction(() => !!(window as unknown as W).__parametric.bbox); + await page.route(/\/src\/app\/fea\/workspace\.ts/, (r) => r.abort()); + await page.getByRole('tab', { name: 'Analysis' }).click(); + await page.locator('[data-cmd="fea:study"]').click(); + await expect(page.locator('.toast')).toContainText('The analysis could not be loaded. Check your connection and try again.'); + await page.unroute(/\/src\/app\/fea\/workspace\.ts/); + await page.locator('[data-cmd="fea:study"]').click(); + await expect(page.locator('.pm-head').getByText('Static Study')).toBeVisible(); + // The failed fetch is the only error. + expect(errors.filter((e) => !/workspace\.ts|ERR_FAILED/.test(e))).toEqual([]); +}); + +test('clicking Results in the design tree shows the results panel without starting a solve', async ({ page }) => { + const errors = await openApp(page); + await bracketStudy(page); + await page.getByRole('treeitem', { name: /^Results/ }).click(); + await expect(page.getByText('Run the study to see its results.')).toBeVisible(); + await expect(page.getByRole('progressbar')).toHaveCount(0); + await expect(page.locator('.statusbar .msg')).not.toContainText(/Preparing|Meshing|Solv/); + // Its Run button solves it. + await page.locator('.pm-content').getByRole('button', { name: 'Run', exact: true }).click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + expect(errors).toEqual([]); +}); + +test('Run Again from the results panel shows the run, with Cancel', async ({ page }) => { + test.setTimeout(240_000); + const errors = await openApp(page); + await bracketStudy(page); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + // A finer mesh (a longer run), run again from the open results panel. + await page.evaluate(() => (window as unknown as W).__parametric.store.change('Finer', (d) => { d.study!.mesh.fineness = 0.8; })); + await page.getByRole('button', { name: 'Run Again' }).click(); + const bar = page.getByRole('progressbar', { name: 'Analysis progress' }); + await expect(bar).toBeVisible(); + await expect(page.locator('.fea-stage')).not.toBeEmpty(); + await page.locator('.pm-content').getByRole('button', { name: 'Cancel' }).click(); + await expect(bar).toHaveCount(0); + await expect(page.locator('.statusbar .msg')).toHaveText('Analysis cancelled'); + // And from Run on the ribbon, with the (out of date) results still shown. + await page.locator('[data-cmd="fea:run"]').click(); + await expect(bar).toBeVisible(); + await page.locator('.pm-content').getByRole('button', { name: 'Cancel' }).click(); + await expect(bar).toHaveCount(0); + expect(errors).toEqual([]); +}); + +test('a 1.5 mm plate meshes and solves at the default size; Fine stops at what a browser can solve', async ({ page }) => { + test.setTimeout(240_000); + const errors = await openApp(page); + await page.getByRole('button', { name: /Mounting Bracket/ }).click(); + await page.waitForFunction(() => !!(window as unknown as W).__parametric.bbox); + // The part becomes a 100 x 50 x 1.5 plate, fixed at one end and pushed down at the other. + await page.evaluate(async () => { + const a = (window as unknown as W).__parametric; + const pts = [[0, 0], [100, 0], [100, 50], [0, 50]]; + a.store.change('Plate', (d) => { + d.features = [ + { 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}` }))] }, + { id: 'f1', name: 'Extrude1', type: 'extrude', sketch: 's1', cut: false, end: 'blind', depth: 1.5, flip: false, dir2: null, draft: 0, draftOutward: false, thin: null }, + ] as typeof d.features; + }); + await a.whenBuilt(); + const ref = (nx: number) => { const f = a.faces.find((x) => x.normal && Math.abs(x.normal[0] - nx) < 1e-9)!; return { name: f.name, sig: { type: f.type, c: f.center, n: f.normal, area: f.area } }; }; + a.store.change('Set up', (d) => { + d.material = { name: 'Alloy Steel', density: 7700, E: 205000, nu: 0.29, yield: 415, uts: 655 }; + d.study = { id: 'st900', name: 'Static Study', fixtures: [{ id: 'fx901', name: 'Fixed1', type: 'fixed', faces: [ref(-1)] }], loads: [{ id: 'ld902', name: 'Force1', type: 'force', faces: [ref(1)], value: 10, dir: { kind: 'base', axis: 'z' }, flip: true }], mesh: { fineness: 0.5 } }; + }); + }); + await page.getByRole('tab', { name: 'Analysis' }).click(); + await page.locator('[data-cmd="fea:study"]').click(); + await page.getByRole('button', { name: 'Mesh Now' }).click(); + await expect(page.locator('.fea-stats')).toBeVisible({ timeout: 120_000 }); + const sizeText = page.locator('.pm-content .field-label[aria-live]'); + await expect(sizeText).toContainText(/Element size 1\.4\d mm \(automatic 1\.4\d\), about [\d,]+ unknowns$/); + // The finest setting is held at about a million unknowns. + await page.getByLabel('Mesh density, coarse to fine').fill('1'); + await expect(sizeText).toContainText(/about 1,000,000 unknowns \(the finest mesh solvable here\)/); + await page.getByLabel('Mesh density, coarse to fine').fill('0.5'); + await page.getByRole('button', { name: 'Close', exact: true }).click(); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 180_000 }); + // Beam theory: 10 N at the end of a 100 mm cantilever, 50 x 1.5, E 205 GPa: 1.156 mm (a plate is a little stiffer). + const disp = await page.locator('.fea-summary tr', { hasText: 'Max displacement' }).locator('td').first().innerText(); + const d = Number(disp.replace(/[^\d.]/g, '')); + expect(d).toBeGreaterThan(1.04); + expect(d).toBeLessThan(1.16); + expect(errors).toEqual([]); +}); + +test('a roller on a cone leaves the part free to turn about the cone axis', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await page.getByRole('button', { name: /Pipe Flange/ }).click(); + await page.waitForFunction(() => !!(window as unknown as W).__parametric.bbox); + // The flange on a roller on its chamfer (a cone about Y), pressed down on its top. + await page.evaluate(async () => { + const a = (window as unknown as W).__parametric; + await a.whenBuilt(); + const ref = (f: (typeof a.faces)[number]) => ({ name: f.name, sig: { type: f.type, c: f.center, n: f.normal, area: f.area } }); + const cone = a.faces.find((f) => f.type === 'cone')!; + const top = a.faces.filter((f) => f.normal && f.normal[1] > 0.99).sort((p, q) => q.area - p.area)[0]; + a.store.change('Set up', (d) => { + d.study = { id: 'st900', name: 'Static Study', fixtures: [{ id: 'fx901', name: 'Roller1', type: 'roller', faces: [ref(cone)] }], loads: [{ id: 'ld902', name: 'Pressure1', type: 'pressure', faces: [ref(top)], value: 1, flip: false }], mesh: { fineness: 0.3 } }; + }); + }); + await page.getByRole('tab', { name: 'Analysis' }).click(); + await page.locator('[data-cmd="fea:run"]').click(); + await expect(page.locator('.fea-summary')).toBeVisible({ timeout: 120_000 }); + await expect(page.locator('.pm-content')).toContainText('free to turn about Y'); + expect(errors).toEqual([]); +}); diff --git a/src/parametric/tests/e2e/assembly-kinematics.spec.ts b/src/parametric/tests/e2e/assembly-kinematics.spec.ts new file mode 100644 index 000000000..96b5ea534 --- /dev/null +++ b/src/parametric/tests/e2e/assembly-kinematics.spec.ts @@ -0,0 +1,1311 @@ +import { type Page, expect, test } from '@playwright/test'; +import { 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 }); +const circle = (id: string, x: number, y: number, r: number) => [{ id: `${id}c`, t: 'point', x, y }, { id, t: 'circle', c: `${id}c`, r }]; +/** A 100 × 40 × 10 plate with Ø20 holes 30 mm apart (for gears of Ø20 and Ø40 pitch). */ +const PLATE = [ + { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: [...pts('r', [[0, 0], [100, 0], [100, 40], [0, 40]]), ...circle('h1', 20, 20, 10), ...circle('h2', 50, 20, 10)], constraints: [] }, + extrude('E1', 'S1', 10), +]; +const disc = (r: number) => [ + { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: circle('k', 0, 0, r), constraints: [] }, + extrude('E1', 'S1', 5), +]; +/** An eccentric cam: a Ø40 disc whose Ø8 bore is 5 off its centre, 10 thick. */ +const CAM = [ + { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: [...circle('k', 5, 0, 20), ...circle('hb', 0, 0, 4)], constraints: [] }, + extrude('E1', 'S1', 10), +]; +/** A Ø8 shaft, 30 long. */ +const SHAFT = [ + { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: circle('k', 0, 0, 4), constraints: [] }, + extrude('E1', 'S1', 30), +]; +/** A 100 × 10 × 10 bar (a rack, or a tab). */ +const BAR = [ + { id: 'S1', name: 'Sketch1', type: 'sketch', plane: { kind: 'base', plane: 'front' }, entities: pts('r', [[0, 0], [100, 0], [100, 10], [0, 10]]), constraints: [] }, + extrude('E1', 'S1', 10), +]; + +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`); +} + +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); +} + +/** Waits until every listed component's faces are shown. */ +async function built(page: Page, names: string[]) { + await page.waitForFunction((names) => { + const a = (window as unknown as { __parametric: A }).__parametric; + return names.every((n) => { + const id = a.assembly?.doc.components.find((c) => c.name === n)?.id; + return !!id && a.faces.some((f) => f.feature === id); + }); + }, names); +} + +/** A face (by its name in the part) or edge of a component, as the graphics area picks it. */ +type Pick = { comp: string; face?: string; edge?: 'x' }; +async function picked(page: Page, p: Pick) { + return page.evaluate(({ comp, face, edge }) => { + const a = (window as unknown as { __parametric: A }).__parametric; + const id = a.assembly!.doc.components.find((c) => c.name === comp)!.id; + if (edge) { + // A straight edge along x. + const index = a.edges.findIndex((e) => e.name.startsWith(`${id}#`) && e.type === 'line' && Math.abs(e.dir?.[0] ?? 0) > 0.99); + return { kind: 'edge' as const, index, name: a.edges[index].name }; + } + const index = a.faces.findIndex((f) => f.name === `${id}#${face}`); + return { kind: 'face' as const, index, name: a.faces[index].name }; + }, p); +} + +/** Selects in the graphics area before a command opens (as clicking faces does). */ +async function select(page: Page, picks: Pick[]) { + const items = await Promise.all(picks.map((p) => picked(page, p))); + await page.evaluate((items) => { (window as unknown as { __parametric: A }).__parametric.selection.set(items); }, items); +} + +/** A pick in the graphics area while a panel is open (what a click on the face does). */ +async function pick(page: Page, p: Pick) { + const item = await picked(page, p); + await page.evaluate((item) => { const a = (window as unknown as { __parametric: A }).__parametric; a.panel!.onPick(item, false); }, item); +} + +async function openMate(page: Page, type: string) { + await page.locator('.cm [data-cmd="mate"]').click(); + const pm = page.locator('.pm'); + await pm.getByRole('combobox', { name: 'Mate type' }).selectOption(type); + return pm; +} + +/** Serious and critical accessibility violations on the page (axe). */ +async function axeViolations(page: Page): Promise { + await page.addScriptTag({ path: 'node_modules/axe-core/axe.min.js' }); + return 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(', ')}`); + }); +} + +async function newAssemblyWith(page: Page, parts: [string, unknown[]][], comps: string[]) { + await page.getByRole('button', { name: /New part/ }).click(); + await page.waitForFunction(() => (window as unknown as { __parametric?: A }).__parametric?.kernelReady); + for (const [name, f] of parts) await makePart(page, name, f); + await page.evaluate(() => { void (window as unknown as { __parametric: A }).__parametric.commands.run('newAssembly'); }); + await expect(page.getByRole('tab', { name: 'Assembly' })).toBeVisible(); + for (const c of comps) await insert(page, c); +} + +test('hinges and a gear through the Mate panel, a motion study that plays and plots, saved and opened again', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Small', disc(10)], ['Large', disc(20)]], ['Plate', 'Small', 'Large']); + await built(page, ['Plate<1>', 'Small<1>', 'Large<1>']); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + + // Hinges: the gear's round face in the plate's hole, its back face on the plate's front. + for (const [gear, hole] of [['Small<1>', 'E1:side:h1'], ['Large<1>', 'E1:side:h2']]) { + await select(page, [{ comp: gear, face: 'E1:side:k' }, { comp: 'Plate<1>', face: hole }]); + const pm = await openMate(page, 'hinge'); + await expect(pm.getByRole('group', { name: 'Concentric selections' })).toContainText(gear); + await pm.getByRole('group', { name: 'Coincident selections' }).click(); + await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); + await pick(page, { comp: gear, face: 'E1:cap0' }); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + if (gear === 'Small<1>') expect(await axeViolations(page)).toEqual([]); + await pm.getByRole('button', { name: 'OK' }).click(); + } + await expect(tree.getByRole('treeitem', { name: /^Hinge2/ })).toBeVisible(); + await expect(page.locator('.statusbar')).toContainText('Under Defined (2 DOF)'); + + // Gear: pitch diameters from the round faces (20 and 40). + await select(page, [{ comp: 'Small<1>', face: 'E1:side:k' }, { comp: 'Large<1>', face: 'E1:side:k' }]); + const pm = await openMate(page, 'gear'); + await expect(pm.getByRole('textbox', { name: 'Pitch diameter of the first gear' })).toHaveValue('20'); + await expect(pm.getByRole('textbox', { name: 'Pitch diameter of the second gear' })).toHaveValue('40'); + await expect(pm.getByRole('status').filter({ hasText: '1 degrees of freedom' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await expect(tree.getByRole('treeitem', { name: /^Gear1/ })).toBeVisible(); + await expect(page.locator('.statusbar')).toContainText('Under Defined (1 DOF)'); + + // Rotate the small gear by dragging: the large one turns half as far, the other way. + const turns = () => page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const z = (n: string) => { const q = m.solved.get(m.doc.components.find((c) => c.name === n)!.id)!.q; return (2 * Math.atan2(q[2], q[3]) * 180) / Math.PI; }; + return { small: z('Small<1>'), large: z('Large<1>') }; + }); + const before = await turns(); + await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const id = m.doc.components.find((c) => c.name === 'Small<1>')!.id; + let pl = new Map(m.solved); + for (let k = 1; k <= 4; k++) pl = m.dragSolve({ kind: 'rotate', body: id, q: [0, 0, Math.sin((k * 10 * Math.PI) / 360), Math.cos((k * 10 * Math.PI) / 360)] }, pl); + m.commitPlacements('Rotate component', pl); + }); + const after = await turns(); + expect(after.small - before.small).toBeGreaterThan(20); + expect(after.large - before.large).toBeCloseTo(-(after.small - before.small) / 2, 3); + + // A motion study: a rotary motor on the small gear at 90°/s for 4 s. + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await expect(pm.getByRole('button', { name: 'Calculate' })).toBeDisabled(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('group', { name: 'Motor axis' }).click(); + await pick(page, { comp: 'Small<1>', face: 'E1:side:k' }); + await expect(pm.getByRole('group', { name: 'Motor axis' })).toContainText('Small<1>'); + await pm.getByRole('textbox', { name: 'Speed' }).fill('90'); + await pm.getByRole('textbox', { name: 'Speed' }).press('Enter'); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); + await expect(pm.getByRole('listitem').filter({ hasText: 'RotaryMotor1' })).toContainText('Small<1>: 90°/s'); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).fill('4'); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).press('Enter'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 121 frames' })).toBeVisible(); + // It plays: the time moves on and the large gear turns. + const clock = pm.locator('.kin-clock'); + await expect(clock).toContainText('/ 4.00 s'); + await expect.poll(async () => Number((await clock.innerText()).split(' ')[0]), { timeout: 10_000 }).toBeGreaterThan(0.3); + await pm.getByRole('button', { name: 'Pause' }).click(); + await expect(pm.getByRole('button', { name: 'Play', exact: true })).toBeVisible(); + // Scrubbed to the end: the small gear turned 360°, the large one 180° back. + await pm.getByRole('button', { name: 'To the end' }).click(); + await expect(clock).toContainText('4.00 s / 4.00 s'); + const shown = await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const z = (n: string) => { const q = m.shownPlacement(m.doc.components.find((c) => c.name === n)!.id)!.q; return (2 * Math.atan2(q[2], q[3]) * 180) / Math.PI; }; + // Both read in (-180°, 180°]: compared a full turn apart. + const d = z('Large<1>') - z('Small<1>') / -2; + return d - 360 * Math.round(d / 360); + }); + expect(Math.abs(shown)).toBeLessThan(1e-3); + // Plot the large gear's turn about Z. + await pm.getByRole('combobox', { name: 'Result of' }).selectOption({ label: 'Component: Large<1>' }); + await pm.getByRole('combobox', { name: 'Quantity' }).selectOption({ label: 'Angular displacement' }); + await pm.getByRole('combobox', { name: 'Vector component' }).selectOption({ label: 'Z' }); + const plot = pm.getByRole('img', { name: /Plot of Large<1> angular displacement Z/ }); + await expect(plot).toHaveAttribute('aria-label', /from -180 to 0/); + await pm.getByRole('combobox', { name: 'Quantity' }).selectOption({ label: 'Angular velocity' }); + await expect(pm.getByRole('img', { name: /angular velocity Z \(°\/s\)/ })).toHaveAttribute('aria-label', /from -45 to -45/); + expect(await axeViolations(page)).toEqual([]); + const download = page.waitForEvent('download'); + await pm.getByRole('button', { name: 'Download CSV' }).click(); + const { readFileSync } = await import('node:fs'); + const csv = new TextDecoder().decode(readFileSync(await (await download).path())).split('\n'); + expect(csv[0]).toContain('Time (s),Displacement X (mm)'); + expect(csv[0]).toContain('Angle Z (deg)'); + expect(csv).toHaveLength(122); + const col = csv[0].split(',').indexOf('Angle Z (deg)'); + expect(Number(csv[121].split(',')[col])).toBeCloseTo(-180, 3); + await pm.getByRole('button', { name: 'OK' }).click(); + const study = tree.getByRole('treeitem', { name: /^Motion Study1/ }); + await expect(study).toContainText('(1 motor, calculated)'); + + // Editing the assembly puts the results out of date; undo brings them back. + await tree.getByRole('treeitem', { name: /^Gear1/ }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Reverse Direction' }).click(); + await expect(study).toContainText('out of date'); + await page.keyboard.press('Meta+z'); + await expect(study).toContainText('calculated'); + + // Saved and opened again: mates and study are kept. + await page.keyboard.press('Meta+s'); + await expect(page).toHaveTitle(/^Assembly\d+ - Parametric$/); + const name = (await page.title()).replace(' - 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`); + await expect(tree.getByRole('treeitem', { name: /^Gear1/ })).toBeVisible(); + await expect(tree.getByRole('treeitem', { name: /^Hinge1/ })).toBeVisible(); + await expect(tree.getByRole('treeitem', { name: /^Motion Study1 \(1 motor\)/ })).toBeVisible(); + await expect(page.locator('.statusbar')).toContainText('Under Defined (1 DOF)'); + // Opened from the tree, it calculates again. + await tree.getByRole('treeitem', { name: /^Motion Study1/ }).dblclick(); + await expect(pm.getByRole('listitem').filter({ hasText: 'RotaryMotor1' })).toBeVisible(); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 121 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Cancel' }).click(); + + // The small gear's hinge limited to ±45° from where it is: the study stops there. + await tree.getByRole('treeitem', { name: /^Hinge1/ }).dblclick(); + await expect(pm.getByRole('combobox', { name: 'Mate type' })).toHaveValue('hinge'); + await pm.getByRole('checkbox', { name: /Limit the angle/ }).check(); + await expect(pm.getByRole('textbox', { name: 'Maximum' })).toHaveValue('45'); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.assembly!.doc.mates.find((m) => m.name === 'Hinge1'))).toMatchObject({ limit: { min: -45, max: 45 }, rel: { q: expect.any(Array) } }); + await expect(tree.getByRole('treeitem', { name: /^Motion Study1/ })).toBeVisible(); + await tree.getByRole('treeitem', { name: /^Motion Study1/ }).dblclick(); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('alert').filter({ hasText: /Hinge1 reached its limit at 0\.5\d* s/ })).toBeVisible(); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); + +test('limit, width, slot, screw and rack and pinion mates through the Mate panel; a study stops at a limit', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Bar', BAR], ['Small', disc(10)]], ['Plate', 'Bar', 'Small']); + await built(page, ['Plate<1>', 'Bar<1>', 'Small<1>']); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + const pm = page.locator('.pm'); + const suppress = async (name: RegExp) => { + await tree.getByRole('treeitem', { name }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Suppress' }).click(); + await expect(tree.getByRole('treeitem', { name })).toHaveAttribute('aria-description', /Suppressed/); + }; + const noError = async (name: RegExp) => { + await expect(tree.getByRole('treeitem', { name })).toBeVisible(); + await expect(tree.getByRole('treeitem', { name })).not.toHaveAttribute('aria-description', /Error/); + }; + + // Width: the bar centred between the plate's two ends. + await page.locator('.cm [data-cmd="mate"]').click(); + await pm.getByRole('combobox', { name: 'Mate type' }).selectOption('width'); + await pick(page, { comp: 'Plate<1>', face: 'E1:side:rl1' }); + await pick(page, { comp: 'Plate<1>', face: 'E1:side:rl3' }); + await expect(pm.getByRole('group', { name: 'Tab selections' })).toHaveClass(/active/); + await pick(page, { comp: 'Bar<1>', face: 'E1:side:rl1' }); + await pick(page, { comp: 'Bar<1>', face: 'E1:side:rl3' }); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await noError(/^Width1/); + const barX = () => page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + return m.solved.get(m.doc.components.find((c) => c.name === 'Bar<1>')!.id)!.p[0]; + }); + // The bar is as long as the plate: centred, it lines up with it. + expect(await barX()).toBeCloseTo(0, 4); + await suppress(/^Width1/); + + // A limit distance: the bar kept 5 to 15 mm in front of the plate. + await select(page, [{ comp: 'Plate<1>', face: 'E1:cap1' }, { comp: 'Bar<1>', face: 'E1:cap0' }]); + await openMate(page, 'distance'); + await pm.getByRole('checkbox', { name: /Limit the distance/ }).check(); + await pm.getByRole('textbox', { name: 'Maximum' }).fill('15'); + await pm.getByRole('textbox', { name: 'Maximum' }).press('Enter'); + await pm.getByRole('textbox', { name: 'Minimum' }).fill('5'); + await pm.getByRole('textbox', { name: 'Minimum' }).press('Enter'); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds. 10 degrees of freedom' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await noError(/^LimitDistance1/); + const gapZ = () => page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + // The bar starts behind the plate's front face: the distance is on that side. + return Math.abs(m.solved.get(m.doc.components.find((c) => c.name === 'Bar<1>')!.id)!.p[2] - 10); + }); + const gap = await gapZ(); + expect(gap).toBeGreaterThan(5 - 1e-4); + expect(gap).toBeLessThan(15 + 1e-4); + // A linear motor pushing the bar away: the study stops at the limit. + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('group', { name: 'Motor type' }).getByRole('button', { name: 'Linear' }).click(); + await pm.getByRole('group', { name: 'Motor direction' }).click(); + await pick(page, { comp: 'Bar<1>', face: 'E1:cap1' }); + await pm.getByRole('textbox', { name: 'Speed' }).fill('10'); + await pm.getByRole('textbox', { name: 'Speed' }).press('Enter'); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('alert').filter({ hasText: 'LimitDistance1 reached its limit' })).toBeVisible(); + // The bar moves through the plate (where the width mate left it): interference over the motion lists the frames. + await pm.getByRole('button', { name: 'Check Interference' }).click(); + await expect(pm.getByRole('status').filter({ hasText: /Components overlap in \d+ of the frames checked/ })).toBeVisible({ timeout: 60_000 }); + const clashes = pm.getByRole('list', { name: 'Interference over the motion' }).getByRole('listitem'); + await expect(clashes.first()).toContainText(/Plate<1> and Bar<1>|Bar<1> and Plate<1>/); + await clashes.last().getByRole('button').click(); + await expect(pm.locator('.kin-clock')).toContainText(/^0\.\d\d s \//); + await pm.getByRole('button', { name: 'Cancel' }).click(); + await suppress(/^LimitDistance1/); + + // Slot: the small disc's round face between the plate's two holes (the slot's ends). + await page.locator('.cm [data-cmd="mate"]').click(); + await pm.getByRole('combobox', { name: 'Mate type' }).selectOption('slot'); + await pick(page, { comp: 'Plate<1>', face: 'E1:side:h1' }); + await pick(page, { comp: 'Plate<1>', face: 'E1:side:h2' }); + await pick(page, { comp: 'Small<1>', face: 'E1:side:k' }); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds. 9 degrees of freedom' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await noError(/^Slot1/); + await suppress(/^Slot1/); + + // Screw: the disc in the first hole, 2 mm a turn, left-hand. + await select(page, [{ comp: 'Plate<1>', face: 'E1:side:h1' }, { comp: 'Small<1>', face: 'E1:side:k' }]); + await openMate(page, 'screw'); + await pm.getByRole('textbox', { name: 'Pitch (travel per turn)' }).fill('2'); + await pm.getByRole('textbox', { name: 'Pitch (travel per turn)' }).press('Enter'); + await pm.getByRole('group', { name: 'Thread' }).getByRole('button', { name: 'Left-hand' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await noError(/^Screw1/); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.assembly!.doc.mates.find((m) => m.name === 'Screw1'))).toMatchObject({ type: 'screw', value: 2, reverse: true }); + await suppress(/^Screw1/); + + // Rack and pinion: the bar's straight edge and the disc's round face (picked the other way round). + await select(page, [{ comp: 'Bar<1>', edge: 'x' }, { comp: 'Small<1>', face: 'E1:side:k' }]); + await openMate(page, 'rackPinion'); + await expect(pm.getByRole('textbox', { name: 'Pinion pitch diameter' })).toHaveValue('20'); + await pm.getByRole('group', { name: 'Rack travel from' }).getByRole('button', { name: 'Travel per turn' }).click(); + await expect(pm.getByRole('textbox', { name: 'Rack travel per turn of the pinion' })).toHaveValue('62.832'); + await pm.getByRole('button', { name: 'OK' }).click(); + await noError(/^Rack Pinion1/); + const rp = () => page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.assembly!.doc.mates.find((m) => m.name === 'Rack Pinion1')!); + // The pinion first, whichever was picked first. + expect((await rp()).a).toMatchObject({ face: { name: 'E1:side:k' } }); + expect(await rp()).toMatchObject({ by: 'revolution', value: 62.832 }); + await tree.getByRole('treeitem', { name: /^Rack Pinion1/ }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Reverse Direction' }).click(); + expect((await rp()).reverse).toBe(true); + + // Edited from the tree: the panel shows what it has. + await tree.getByRole('treeitem', { name: /^Rack Pinion1/ }).dblclick(); + await expect(pm.getByRole('combobox', { name: 'Mate type' })).toHaveValue('rackPinion'); + await expect(pm.getByRole('checkbox', { name: 'Reverse the direction' })).toBeChecked(); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); + +test('slider, cam follower and universal joint through the Mate panel; motors on a slider and a hinge', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Bar', BAR], ['Cam', CAM], ['Shaft', SHAFT]], ['Plate', 'Bar', 'Cam', 'Shaft', 'Shaft']); + await built(page, ['Plate<1>', 'Bar<1>', 'Cam<1>', 'Shaft<1>', 'Shaft<2>']); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + const pm = page.locator('.pm'); + await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.selection.clear()); + + // Slider: the bar flush on the plate's front and right faces, sliding along y, at most 25 mm either way. + await page.locator('.cm [data-cmd="mate"]').click(); + await pm.getByRole('combobox', { name: 'Mate type' }).selectOption('slider'); + await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); + await pick(page, { comp: 'Plate<1>', face: 'E1:side:rl1' }); + await expect(pm.getByRole('group', { name: 'Second component' })).toHaveClass(/active/); + await pick(page, { comp: 'Bar<1>', face: 'E1:cap0' }); + await pick(page, { comp: 'Bar<1>', face: 'E1:side:rl1' }); + await pm.getByRole('checkbox', { name: /Limit the travel/ }).check(); + await expect(pm.getByRole('textbox', { name: 'Maximum' })).toHaveValue('25'); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await expect(tree.getByRole('treeitem', { name: /^Slider1/ })).toBeVisible(); + const bar = () => page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + return m.solved.get(m.doc.components.find((c) => c.name === 'Bar<1>')!.id)!.p; + }); + expect((await bar())[0]).toBeCloseTo(0, 4); + expect((await bar())[2]).toBeCloseTo(10, 4); + // A linear motor on the slider at 10 mm/s: it stops at the limit after 2.5 s. + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('group', { name: 'Motor type' }).getByRole('button', { name: 'Linear' }).click(); + await pm.getByRole('combobox', { name: 'Motor on' }).selectOption({ label: 'Slider1 (Slider)' }); + await pm.getByRole('textbox', { name: 'Speed' }).fill('10'); + await pm.getByRole('textbox', { name: 'Speed' }).press('Enter'); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); + await expect(pm.getByRole('listitem').filter({ hasText: 'LinearMotor1' })).toContainText('Slider1: 10 mm/s'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('alert').filter({ hasText: /Slider1 reached its limit at 2\.5\d* s/ })).toBeVisible(); + await pm.getByRole('button', { name: 'Cancel' }).click(); + // Without the limit, for the cam to push it. + await tree.getByRole('treeitem', { name: /^Slider1/ }).dblclick(); + await pm.getByRole('checkbox', { name: /Limit the travel/ }).uncheck(); + await pm.getByRole('button', { name: 'OK' }).click(); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.assembly!.doc.mates.find((m) => m.name === 'Slider1')!.limit)).toBeUndefined(); + + // The cam on a hinge in the plate's first hole. + await select(page, [{ comp: 'Cam<1>', face: 'E1:side:hb' }, { comp: 'Plate<1>', face: 'E1:side:h1' }]); + await openMate(page, 'hinge'); + await pm.getByRole('group', { name: 'Coincident selections' }).click(); + await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); + await pick(page, { comp: 'Cam<1>', face: 'E1:cap0' }); + await pm.getByRole('button', { name: 'OK' }).click(); + await expect(tree.getByRole('treeitem', { name: /^Hinge1/ })).toBeVisible(); + + // Cam: the eccentric's round face, the bar's bottom face as a flat follower. + await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.selection.clear()); + await openMate(page, 'cam'); + await pick(page, { comp: 'Cam<1>', face: 'E1:side:k' }); + await pm.getByRole('group', { name: 'Follower' }).click(); + await pick(page, { comp: 'Bar<1>', face: 'E1:side:rl0' }); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await expect(tree.getByRole('treeitem', { name: /^Cam1/ })).toBeVisible(); + await expect(tree.getByRole('treeitem', { name: /^Cam1/ })).not.toHaveAttribute('aria-description', /Error/); + + // A rotary motor on the hinge turns the cam a full turn: the bar's bottom stays on the eccentric's top. + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('combobox', { name: 'Motor on' }).selectOption({ label: 'Hinge1 (Hinge)' }); + await pm.getByRole('textbox', { name: 'Speed' }).fill('90'); + await pm.getByRole('textbox', { name: 'Speed' }).press('Enter'); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).fill('4'); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).press('Enter'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 121 frames' })).toBeVisible(); + const follow = await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const m = a.assembly!; + const res = (a.panel as unknown as { result(): { frames: Map[] } }).result(); + const id = (n: string) => m.doc.components.find((c) => c.name === n)!.id; + const rot = (q: number[], v: number[]) => { + const [x, y, z, w] = q; + const t = [2 * (y * v[2] - z * v[1]), 2 * (z * v[0] - x * v[2]), 2 * (x * v[1] - y * v[0])]; + return [v[0] + w * t[0] + y * t[2] - z * t[1], v[1] + w * t[1] + z * t[0] - x * t[2], v[2] + w * t[2] + x * t[1] - y * t[0]]; + }; + let worst = 0, lo = Infinity, hi = -Infinity; + for (const f of res.frames) { + const cam = f.get(id('Cam<1>'))!, b = f.get(id('Bar<1>'))!; + // The eccentric's top: its centre (5 off the bore, in the cam) plus its radius. + const top = rot(cam.q, [5, 0, 0])[1] + cam.p[1] + 20; + worst = Math.max(worst, Math.abs(b.p[1] - top)); + lo = Math.min(lo, b.p[1]); hi = Math.max(hi, b.p[1]); + } + return { worst, lift: hi - lo }; + }); + expect(follow.worst).toBeLessThan(1e-6); + // The follower rises and falls by twice the eccentricity. + expect(follow.lift).toBeCloseTo(10, 3); + await pm.getByRole('button', { name: 'Cancel' }).click(); + + // Universal joint between the two shafts, with a joint point. + await select(page, [{ comp: 'Shaft<1>', face: 'E1:side:k' }, { comp: 'Shaft<2>', face: 'E1:side:k' }]); + await openMate(page, 'universal'); + await expect(pm.getByRole('group', { name: 'Shafts' })).toContainText('Shaft<2>'); + await pm.getByRole('checkbox', { name: /Joint point/ }).check(); + await pm.getByRole('textbox', { name: 'Joint point offset (along the first shaft)' }).fill('15'); + await pm.getByRole('textbox', { name: 'Joint point offset (along the first shaft)' }).press('Enter'); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await expect(tree.getByRole('treeitem', { name: /^Universal Joint1/ })).toBeVisible(); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.assembly!.doc.mates.find((m) => m.name === 'Universal Joint1'))).toMatchObject({ type: 'universal', by: 'point', value: 15, rel: { q: expect.any(Array) } }); + + // Flip and suppress from the Mates folder; undo; the edits survive saving and opening again. + await tree.getByRole('treeitem', { name: /^Cam1/ }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Flip Follower Face' }).click(); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.assembly!.doc.mates.find((m) => m.name === 'Cam1')!.flip)).toBe(true); + await page.keyboard.press('Meta+z'); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.assembly!.doc.mates.find((m) => m.name === 'Cam1')!.flip)).toBeUndefined(); + await tree.getByRole('treeitem', { name: /^Universal Joint1/ }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Suppress' }).click(); + await expect(tree.getByRole('treeitem', { name: /^Universal Joint1/ })).toHaveAttribute('aria-description', /Suppressed/); + await page.keyboard.press('Meta+s'); + await expect(page).toHaveTitle(/^Assembly\d+ - Parametric$/); + const name = (await page.title()).replace(' - 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`); + for (const n of [/^Slider1/, /^Hinge1/, /^Cam1/]) await expect(tree.getByRole('treeitem', { name: n })).not.toHaveAttribute('aria-description', /Error|Suppressed/); + await expect(tree.getByRole('treeitem', { name: /^Universal Joint1/ })).toHaveAttribute('aria-description', /Suppressed/); + // Edited from the tree, the cam shows its faces and follower. + await tree.getByRole('treeitem', { name: /^Cam1/ }).dblclick(); + await expect(pm.getByRole('group', { name: 'Cam faces' })).toContainText('Face (cylinder) of Cam<1>'); + await expect(pm.getByRole('group', { name: 'Follower' })).toContainText('Face (plane) of Bar<1>'); + expect(await axeViolations(page)).toEqual([]); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); + +/** The plate with the two discs on hinges in its holes, geared together; the Mates folder then has Hinge1, Hinge2 and Gear1. */ +async function hingedGears(page: Page) { + await newAssemblyWith(page, [['Plate', PLATE], ['Small', disc(10)], ['Large', disc(20)]], ['Plate', 'Small', 'Large']); + await built(page, ['Plate<1>', 'Small<1>', 'Large<1>']); + const pm = page.locator('.pm'); + for (const [gear, hole] of [['Small<1>', 'E1:side:h1'], ['Large<1>', 'E1:side:h2']]) { + await select(page, [{ comp: gear, face: 'E1:side:k' }, { comp: 'Plate<1>', face: hole }]); + await openMate(page, 'hinge'); + await pm.getByRole('group', { name: 'Coincident selections' }).click(); + await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); + await pick(page, { comp: gear, face: 'E1:cap0' }); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + } + await select(page, [{ comp: 'Small<1>', face: 'E1:side:k' }, { comp: 'Large<1>', face: 'E1:side:k' }]); + await openMate(page, 'gear'); + await expect(pm.getByRole('status').filter({ hasText: '1 degrees of freedom' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + return pm; +} + +/** Adds a rotary motor on Hinge1 to the open Motion Study panel. */ +async function hingeMotor(page: Page, speed = '90') { + const pm = page.locator('.pm'); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('combobox', { name: 'Motor on' }).selectOption({ label: 'Hinge1 (Hinge)' }); + await pm.getByRole('textbox', { name: 'Speed' }).fill(speed); + await pm.getByRole('textbox', { name: 'Speed' }).press('Enter'); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); +} + +test('the Motion Study panel: a new study starts without results', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + // A study set up, calculated and cancelled: the next new study has no results, not out of date ones. + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Cancel' }).click(); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await expect(pm.getByText('No motors yet')).toBeVisible(); + await expect(pm.locator('.pm-msg.warn')).toHaveCount(0); + await expect(pm.getByText(/out of date/)).toHaveCount(0); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); + +test('the Motion Study panel plots a study of more frames than a function call takes arguments', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Pause' }).click(); + // The frames of a 1000 s study at 200 frames a second (as long to compute as 25 s here), from the 151 calculated. + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + type R = { times: number[]; frames: unknown[]; duration: number }; + const r = (a.assembly as unknown as { motions: Map }).motions.get('')!.result; + const n = 200_001, frames = r.frames.slice(0, 150), times = Array.from({ length: n }, (_, i) => i / 200); + r.frames = times.map((_, i) => frames[i % 150]); + r.times = times; + r.duration = 1000; + a.refreshPanel(); + }); + await expect(pm.locator('.kin-clock')).toContainText('/ 1000.00 s'); + const plot = pm.getByRole('img', { name: /^Plot of Small<1> linear displacement/ }); + await expect(plot).toBeVisible(); + // The line is drawn through a few points a pixel, not all 200 001. + const points = await plot.locator('polyline').evaluate((e) => (e.getAttribute('points') ?? '').split(' ').length); + expect(points).toBeGreaterThan(400); + expect(points).toBeLessThan(2000); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); + +test('the Motion Study panel: Escape and Enter in a motor cancel or add the motor, not the study, and keyboard focus follows', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + // Opened from the keyboard, the motor's first control takes focus. + await pm.getByRole('button', { name: 'Delete RotaryMotor1' }).focus(); + await page.keyboard.press('Tab'); + await expect(pm.getByRole('button', { name: 'Add Motor' })).toBeFocused(); + await page.keyboard.press('Enter'); + await expect(pm.getByRole('group', { name: 'Motor type' }).getByRole('button', { name: 'Rotary' })).toBeFocused(); + // Escape leaves the motor: the study and its first motor stay, focus is on Add Motor again. + await pm.getByRole('checkbox', { name: 'Reverse direction' }).focus(); + await page.keyboard.press('Escape'); + await expect(pm.getByRole('heading', { name: 'Motion Study' })).toBeVisible(); + await expect(pm.getByRole('listitem')).toHaveCount(1); + await expect(pm.getByRole('button', { name: 'Add Motor' })).toBeFocused(); + // Enter on a checkbox of the motor adds it. + await page.keyboard.press('Enter'); + await pm.getByRole('combobox', { name: 'Motor on' }).selectOption({ label: 'Hinge2 (Hinge)' }); + await pm.getByRole('checkbox', { name: 'Reverse direction' }).focus(); + await page.keyboard.press('Enter'); + await expect(pm.getByRole('listitem')).toHaveCount(2); + await expect(pm.getByRole('listitem').nth(1)).toContainText('Hinge2'); + await expect(pm.getByRole('listitem').nth(1).getByRole('button').first()).toBeFocused(); + // Escape outside a motor still cancels the panel. + await page.keyboard.press('Escape'); + await expect(pm).toHaveCount(0); + expect(errors).toEqual([]); +}); + +test('the Motion Study panel: dragging a component while it plays stops the playback and puts the results out of date', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page, '30'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await expect(pm.getByRole('button', { name: 'Pause' })).toBeVisible(); + // Drag the large gear round (it turns on its hinge) while the study plays. + const at = await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const id = a.assembly!.doc.components.find((c) => c.name === 'Large<1>')!.id; + const f = a.faces.find((x) => x.name === `${id}#E1:cap1`)!; + return a.viewport.project([f.center[0] + 12, f.center[1] + 12, f.center[2]]); + }); + const box = (await page.locator('canvas.gl').boundingBox())!; + await page.mouse.move(box.x + at[0], box.y + at[1]); + await page.mouse.down(); + await page.mouse.move(box.x + at[0] + 30, box.y + at[1] - 30, { steps: 5 }); + await expect(pm.getByRole('button', { name: 'Play', exact: true })).toBeVisible(); + // (Playback no longer moves the gears under the drag.) + const clock = await pm.locator('.kin-clock').innerText(); + await page.waitForTimeout(300); + await expect(pm.locator('.kin-clock')).toHaveText(clock); + await page.mouse.move(box.x + at[0] + 40, box.y + at[1] - 70, { steps: 5 }); + await page.mouse.up(); + expect(await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.store.undoLabel)).toBe('Move component'); + await expect(pm.getByRole('status').filter({ hasText: 'The results are out of date' })).toBeVisible(); + await expect(pm.getByRole('button', { name: /^(Play|Pause)$/ })).toHaveCount(0); + // The components are shown where the drag left them, not at a frame of the old motion. + const shown = await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const id = m.doc.components.find((c) => c.name === 'Large<1>')!.id; + return [m.shownPlacement(id)!.q, m.solved.get(id)!.q]; + }); + for (let i = 0; i < 4; i++) expect(shown[0][i]).toBeCloseTo(shown[1][i], 9); + // Calculated again from there, it plays. + await pm.getByRole('button', { name: 'Calculate', exact: true }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); + +test('a motion study plots how far a slider travels', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Bar', BAR]], ['Plate', 'Bar']); + await built(page, ['Plate<1>', 'Bar<1>']); + const pm = page.locator('.pm'); + await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.selection.clear()); + await page.locator('.cm [data-cmd="mate"]').click(); + await pm.getByRole('combobox', { name: 'Mate type' }).selectOption('slider'); + await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); + await pick(page, { comp: 'Plate<1>', face: 'E1:side:rl1' }); + await pick(page, { comp: 'Bar<1>', face: 'E1:cap0' }); + await pick(page, { comp: 'Bar<1>', face: 'E1:side:rl1' }); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + // A linear motor on the slider at 10 mm/s for 2 s. + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('group', { name: 'Motor type' }).getByRole('button', { name: 'Linear' }).click(); + await pm.getByRole('combobox', { name: 'Motor on' }).selectOption({ label: 'Slider1 (Slider)' }); + await pm.getByRole('textbox', { name: 'Speed' }).fill('10'); + await pm.getByRole('textbox', { name: 'Speed' }).press('Enter'); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).fill('2'); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).press('Enter'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 61 frames' })).toBeVisible(); + await pm.getByRole('combobox', { name: 'Result of' }).selectOption({ label: 'Mate: Slider1' }); + await expect(pm.getByRole('img', { name: /^Plot of Slider1 value \(mm\)/ })).toHaveAttribute('aria-label', /from -?0 to 20$|from -20 to -?0$/); + await pm.getByRole('combobox', { name: 'Quantity' }).selectOption({ label: 'Rate of change' }); + await expect(pm.getByRole('img', { name: /^Plot of Slider1 rate of change \(mm\/s\)/ })).toHaveAttribute('aria-label', /from (-10 to -10|10 to 10)$/); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); + +test('motion study plots label their values within the plot, without rounding noise', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Pause' }).click(); + const labels = () => pm.locator('.kin-plot text').evaluateAll((ts) => ts.map((t) => ({ text: t.textContent, x: (t as SVGTextElement).getBBox().x }))); + // The small gear turns about its own origin: that point does not move. + const plot = pm.getByRole('img', { name: /^Plot of Small<1> linear displacement/ }); + await expect(plot).toHaveAttribute('aria-label', /from 0 to 0$/); + for (const l of await labels()) expect(l.x, l.text ?? '').toBeGreaterThanOrEqual(0); + // Every label of a small value fits too. + await pm.getByRole('combobox', { name: 'Result of' }).selectOption({ label: 'Component: Large<1>' }); + await pm.getByRole('combobox', { name: 'Quantity' }).selectOption({ label: 'Angular acceleration' }); + await expect(pm.getByRole('img', { name: /^Plot of Large<1> angular acceleration/ })).toHaveAttribute('aria-label', /from 0 to 0$/); + for (const l of await labels()) expect(l.x, l.text ?? '').toBeGreaterThanOrEqual(0); + // The longest label (8 characters) fits too. + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const svg = a.panel!.el.querySelector('.kin-plot text')!; + svg.textContent = '-1.23e-3'; + }); + for (const l of await labels()) expect(l.x, l.text ?? '').toBeGreaterThanOrEqual(0); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); + +test('the motion study time slider works from the keyboard and reads out the time', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Pause' }).click(); + await pm.getByRole('button', { name: 'To the start' }).click(); + const slider = pm.getByRole('slider', { name: 'Study time' }); + await expect(slider).toHaveAttribute('aria-valuetext', '0.00 s of 5.00 s'); + await slider.focus(); + await page.keyboard.press('End'); + await expect(pm.locator('.kin-clock')).toHaveText('5.00 s / 5.00 s'); + await expect(slider).toHaveAttribute('aria-valuetext', '5.00 s of 5.00 s'); + await page.keyboard.press('PageDown'); + await expect(slider).toHaveAttribute('aria-valuetext', '4.50 s of 5.00 s'); + // The arrow keys step one frame (30 a second), not a thousandth of the study. + await page.keyboard.press('ArrowRight'); + await expect(slider).toHaveAttribute('aria-valuetext', '4.53 s of 5.00 s'); + await page.keyboard.press('ArrowLeft'); + await page.keyboard.press('ArrowLeft'); + await expect(slider).toHaveAttribute('aria-valuetext', '4.47 s of 5.00 s'); + await page.keyboard.press('Home'); + await page.keyboard.press('ArrowLeft'); + await expect(slider).toHaveAttribute('aria-valuetext', '0.00 s of 5.00 s'); + await page.keyboard.press('ArrowUp'); + await expect(slider).toHaveAttribute('aria-valuetext', '0.03 s of 5.00 s'); + await pm.getByRole('button', { name: 'Cancel' }).click(); + expect(errors).toEqual([]); +}); + +test('an interference check over a motion can be cancelled, and checked again', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + // Each frame's check waits a while in the worker, so the check is still running when Cancel is pressed. + await page.evaluate(() => { + const k = (window as unknown as { __parametric: A }).__parametric.kernel as unknown as { assembly: (op: { op: string }) => Promise }; + const real = k.assembly.bind(k); + k.assembly = async (op) => { const r = await real(op); if (op.op === 'interference') await new Promise((done) => setTimeout(done, 100)); return r; }; + }); + await pm.getByRole('button', { name: 'Check Interference' }).click(); + const section = pm.locator('.pm-section').filter({ has: page.getByRole('progressbar', { name: 'Interference check progress' }) }); + await section.getByRole('button', { name: 'Cancel' }).click(); + await expect(pm.getByRole('progressbar', { name: 'Interference check progress' })).toHaveCount(0); + await expect(pm.getByRole('button', { name: 'Check Interference' })).toBeFocused(); + await expect(pm.getByText('No interference in the frames checked.')).toHaveCount(0); + // The panel stays open, plays, and checks again to the end. + await expect(pm.getByRole('heading', { name: 'Motion Study' })).toBeVisible(); + await pm.getByRole('button', { name: 'Check Interference' }).click(); + await expect(pm.getByText('No interference in the frames checked.')).toBeVisible({ timeout: 30_000 }); + await pm.getByRole('button', { name: 'Play', exact: true }).click(); + await expect(pm.getByRole('button', { name: 'Pause' })).toBeVisible(); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); + +test('a motion study plots a picked vertex of the component even where another component touches it', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Bar', BAR], ['Small', disc(10)]], ['Plate', 'Bar', 'Small']); + await built(page, ['Plate<1>', 'Bar<1>', 'Small<1>']); + const pm = page.locator('.pm'); + // The disc's face centre sits on the bar's corner (both at the same place, 50 mm in front of the plate). + await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + m.commit('Place', (d) => { for (const c of d.components) if (!c.fixed) c.placement = { p: [0, 0, 50], q: [0, 0, 0, 1] }; }); + }); + await page.waitForFunction(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + return m.doc.components.every((c) => c.fixed || m.shownPlacement(c.id)!.p[2] === 50); + }); + // A linear motor moving the bar along x at 10 mm/s. + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('group', { name: 'Motor type' }).getByRole('button', { name: 'Linear' }).click(); + await pm.getByRole('group', { name: 'Motor direction' }).click(); + await pick(page, { comp: 'Bar<1>', edge: 'x' }); + await pm.getByRole('textbox', { name: 'Speed' }).fill('10'); + await pm.getByRole('textbox', { name: 'Speed' }).press('Enter'); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Pause' }).click(); + await pm.getByRole('button', { name: 'To the start' }).click(); + await pm.getByRole('combobox', { name: 'Result of' }).selectOption({ label: 'Component: Bar<1>' }); + // The bar's corner vertex (where the disc's face centre is) is a point of the bar. + await pm.getByRole('group', { name: 'Point (optional)' }).click(); + await page.evaluate(() => { (window as unknown as { __parametric: A }).__parametric.panel!.onPick({ kind: 'vertex', p: [0, 0, 50] }, false); }); + await expect(pm.getByRole('group', { name: 'Point (optional)' })).toContainText('Vertex'); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); + +test('a motion study is not calculated with a duration it refused', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + const duration = pm.getByRole('spinbutton', { name: 'Duration (s)' }); + await duration.fill('0'); + await duration.press('Enter'); + await expect(duration).toHaveAttribute('aria-invalid', 'true'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('alert')).toContainText('Duration (s): Between 0.1 and 3600'); + await expect(duration).toBeFocused(); + await expect(pm.getByText(/Calculated \d+ frames/)).toHaveCount(0); + await duration.fill('2'); + await duration.press('Enter'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 61 frames' })).toBeVisible(); + await expect(pm.getByRole('alert')).toHaveCount(0); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); + +test('Flip Mate Alignment turns a hinged component over instead of making the hinge over defined', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Small', disc(10)], ['Large', disc(20)]], ['Plate', 'Small', 'Large']); + await built(page, ['Plate<1>', 'Small<1>', 'Large<1>']); + const pm = page.locator('.pm'); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + // Hinge1 free, Hinge2 limited to ±45°. + for (const [gear, hole] of [['Small<1>', 'E1:side:h1'], ['Large<1>', 'E1:side:h2']]) { + await select(page, [{ comp: gear, face: 'E1:side:k' }, { comp: 'Plate<1>', face: hole }]); + await openMate(page, 'hinge'); + await pm.getByRole('group', { name: 'Coincident selections' }).click(); + await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); + await pick(page, { comp: gear, face: 'E1:cap0' }); + if (gear === 'Large<1>') await pm.getByRole('checkbox', { name: /Limit the angle/ }).check(); + await expect(pm.getByRole('status').filter({ hasText: 'The mate holds' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + } + const capZ = (name: string) => page.evaluate((name) => { + // Where the disc's back face (z = 0 in the part) is: on the plate's front (z = 10), or turned over into the plate. + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const pl = m.solved.get(m.doc.components.find((c) => c.name === name)!.id)!; + const [x, y] = pl.q; + return { z: pl.p[2], nz: 1 - 2 * (x * x + y * y) }; + }, name); + for (const name of ['Hinge1', 'Hinge2']) { + const row = tree.getByRole('treeitem', { name: new RegExp(`^${name}`) }); + await row.click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Flip Mate Alignment' }).click(); + await expect(row).not.toHaveAttribute('aria-description', /Error|Over/); + await expect(page.locator('.statusbar')).not.toContainText('Over Defined'); + } + // Both discs turned over: their back faces now face the other way. + expect((await capZ('Small<1>')).nz).toBeCloseTo(-1, 6); + expect((await capZ('Large<1>')).nz).toBeCloseTo(-1, 6); + // The limited hinge still turns 45° either way from where it turned over to, and no further. + const turned = await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const id = m.doc.components.find((c) => c.name === 'Large<1>')!.id; + const mul = (a: number[], b: number[]) => [a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1], a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0], a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3], a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2]]; + const q0 = m.solved.get(id)!.q; + return [1, -1].map((dir) => { + let pl = new Map(m.solved); + for (let k = 1; k <= 8; k++) pl = m.dragSolve({ kind: 'rotate', body: id, q: mul([0, 0, Math.sin((dir * k * 10 * Math.PI) / 360), Math.cos((k * 10 * Math.PI) / 360)], q0) as [number, number, number, number] }, pl); + const d = mul(pl.get(id)!.q, [-q0[0], -q0[1], -q0[2], q0[3]]); + return (2 * Math.acos(Math.min(1, Math.abs(d[3]))) * 180) / Math.PI; + }); + }); + expect(turned[0]).toBeCloseTo(45, 3); + expect(turned[1]).toBeCloseTo(45, 3); + // One undo step each. + await page.keyboard.press('Meta+z'); + await page.keyboard.press('Meta+z'); + expect((await capZ('Small<1>')).nz).toBeCloseTo(1, 6); + expect((await capZ('Large<1>')).nz).toBeCloseTo(1, 6); + expect(errors).toEqual([]); +}); + +test('a rack and pinion pitch diameter given as an equation turns into the travel per turn', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Bar', BAR], ['Small', disc(10)]], ['Plate', 'Bar', 'Small']); + await built(page, ['Plate<1>', 'Bar<1>', 'Small<1>']); + await select(page, [{ comp: 'Bar<1>', edge: 'x' }, { comp: 'Small<1>', face: 'E1:side:k' }]); + const pm = await openMate(page, 'rackPinion'); + const diameter = pm.getByRole('textbox', { name: 'Pinion pitch diameter' }); + await diameter.fill('=10*2'); + await diameter.press('Enter'); + await pm.getByRole('group', { name: 'Rack travel from' }).getByRole('button', { name: 'Travel per turn' }).click(); + await expect(pm.getByRole('textbox', { name: 'Rack travel per turn of the pinion' })).toHaveValue('62.832'); + await pm.getByRole('group', { name: 'Rack travel from' }).getByRole('button', { name: 'Pitch diameter' }).click(); + await expect(diameter).toHaveValue('20'); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); + +test('a motion study does not start playing while a motor added during the calculation is set up', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).fill('60'); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).press('Enter'); + await pm.getByRole('spinbutton', { name: 'Frames per second' }).fill('240'); + await pm.getByRole('spinbutton', { name: 'Frames per second' }).press('Enter'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('progressbar', { name: 'Calculation progress' })).toBeVisible(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + const state = () => page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const p = a.panel as unknown as { computing: boolean; playing: boolean }; + return { computing: p.computing, playing: p.playing }; + }); + await expect.poll(async () => (await state()).computing, { timeout: 60_000 }).toBe(false); + await page.waitForTimeout(300); + expect((await state()).playing).toBe(false); + // Back from the motor, the results are there to play. + await pm.getByRole('button', { name: 'Cancel' }).last().click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 14401 frames' })).toBeVisible(); + await expect(pm.getByRole('button', { name: 'Play', exact: true })).toBeVisible(); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); + +test('a motion study whose motors are all suppressed says so when calculated', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('combobox', { name: 'Motor on' }).selectOption({ label: 'Hinge1 (Hinge)' }); + await pm.getByRole('checkbox', { name: 'Suppressed' }).check(); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); + await expect(pm.getByRole('listitem')).toContainText('RotaryMotor1 (suppressed)'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('alert')).toHaveText('Every motor is suppressed: unsuppress one to drive the mechanism.'); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); + +test('the Mate panel does not carry a hinge\'s angle limits over to a slider as lengths', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Bar', BAR]], ['Plate', 'Bar']); + await built(page, ['Plate<1>', 'Bar<1>']); + await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.selection.clear()); + const pm = await openMate(page, 'hinge'); + await pm.getByRole('checkbox', { name: /Limit the angle/ }).check(); + await expect(pm.getByRole('textbox', { name: 'Maximum' })).toHaveValue('45'); + await pm.getByRole('combobox', { name: 'Mate type' }).selectOption('slider'); + await expect(pm.getByRole('checkbox', { name: /Limit the travel/ })).toBeChecked(); + await expect(pm.getByRole('textbox', { name: 'Maximum' })).toHaveValue('25'); + await expect(pm.getByRole('textbox', { name: 'Minimum' })).toHaveValue('-25'); + await pm.getByRole('combobox', { name: 'Mate type' }).selectOption('hinge'); + await expect(pm.getByRole('textbox', { name: 'Maximum' })).toHaveValue('45'); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); + +test('a cam mate with a roller follower offers no Flip Follower Face', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Cam', CAM], ['Shaft', SHAFT], ['Bar', BAR]], ['Plate', 'Cam', 'Shaft', 'Bar']); + await built(page, ['Plate<1>', 'Cam<1>', 'Shaft<1>', 'Bar<1>']); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await page.evaluate(() => (window as unknown as { __parametric: A }).__parametric.selection.clear()); + // The shaft's round face rolls on the cam; the bar's flat face follows it too. + for (const follower of [{ comp: 'Shaft<1>', face: 'E1:side:k' }, { comp: 'Bar<1>', face: 'E1:side:rl0' }]) { + const pm = await openMate(page, 'cam'); + await pick(page, { comp: 'Cam<1>', face: 'E1:side:k' }); + await pm.getByRole('group', { name: 'Follower' }).click(); + await pick(page, follower); + await expect(pm.getByRole('group', { name: 'Follower' })).toContainText(follower.comp); + await pm.getByRole('button', { name: 'OK' }).click(); + } + await tree.getByRole('treeitem', { name: /^Cam1/ }).click({ button: 'right' }); + await expect(page.getByRole('menuitem', { name: 'Suppress' })).toBeVisible(); + await expect(page.getByRole('menuitem', { name: 'Flip Follower Face' })).toHaveCount(0); + await page.keyboard.press('Escape'); + await tree.getByRole('treeitem', { name: /^Cam2/ }).click({ button: 'right' }); + await expect(page.getByRole('menuitem', { name: 'Flip Follower Face' })).toBeVisible(); + await page.keyboard.press('Escape'); + expect(errors).toEqual([]); +}); + +test('interference over a motion lists a part sunk into another in every frame', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + // A second plate, fixed half into the first one and into the large gear. + await insert(page, 'Plate'); + await built(page, ['Plate<2>']); + await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + m.commit('Sink', (d) => { const c = d.components.find((x) => x.name === 'Plate<2>')!; c.placement = { p: [50, 30, 5], q: [0, 0, 0, 1] }; c.fixed = true; }); + }); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Check Interference' }).click(); + await expect(pm.getByRole('status').filter({ hasText: /overlap in|No interference/ })).toHaveText('Components overlap in 40 of the frames checked.', { timeout: 60_000 }); + const list = await pm.getByRole('list', { name: 'Interference over the motion' }).getByRole('listitem').allInnerTexts(); + expect(list).toHaveLength(40); + for (const f of list) expect(f).toContain('Plate<1> and Plate<2>'); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); + +test('interference over a motion checked again after cancelled checks lists the same frames', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Bar', BAR]], ['Plate', 'Bar', 'Bar']); + await built(page, ['Plate<1>', 'Bar<1>', 'Bar<2>']); + const pm = page.locator('.pm'); + // The first bar slides along the plate (along y) through the second, fixed 27 mm up: they overlap for part of the motion only. + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + a.selection.clear(); + a.assembly!.commit('Place', (d) => { const c = d.components.find((x) => x.name === 'Bar<2>')!; c.placement = { p: [0, 27, 10], q: [0, 0, 0, 1] }; c.fixed = true; }); + }); + await page.locator('.cm [data-cmd="mate"]').click(); + await pm.getByRole('combobox', { name: 'Mate type' }).selectOption('slider'); + await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); + await pick(page, { comp: 'Plate<1>', face: 'E1:side:rl1' }); + await pick(page, { comp: 'Bar<1>', face: 'E1:cap0' }); + await pick(page, { comp: 'Bar<1>', face: 'E1:side:rl1' }); + await pm.getByRole('button', { name: 'OK' }).click(); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await pm.getByRole('button', { name: 'Add Motor' }).click(); + await pm.getByRole('group', { name: 'Motor type' }).getByRole('button', { name: 'Linear' }).click(); + await pm.getByRole('combobox', { name: 'Motor on' }).selectOption({ label: 'Slider1 (Slider)' }); + await pm.getByRole('textbox', { name: 'Speed' }).fill('10'); + await pm.getByRole('textbox', { name: 'Speed' }).press('Enter'); + await pm.getByRole('button', { name: 'Add', exact: true }).click(); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Pause' }).click(); + const list = () => pm.getByRole('list', { name: 'Interference over the motion' }).getByRole('listitem').allInnerTexts(); + const done = pm.getByRole('status').filter({ hasText: /overlap in|No interference/ }); + await pm.getByRole('button', { name: 'Check Interference' }).click(); + await expect(done).toHaveText('Components overlap in 15 of the frames checked.', { timeout: 60_000 }); + const first = await list(); + expect(first[0]).toMatch(/^1\.80 s\nBar<1> and Bar<2>$/); + // Shown where the bars overlap (the frames a mixed up scene would add to are those where they do not). + const overlapping = () => pm.getByRole('list', { name: 'Interference over the motion' }).getByRole('button').first().click(); + await overlapping(); + // Each frame's check waits in the worker; checks cancelled part way (one while it plays back), then one to the end. + await page.evaluate(() => { + const k = (window as unknown as { __parametric: A }).__parametric.kernel as unknown as { assembly: (op: { op: string }) => Promise }; + const real = k.assembly.bind(k); + // (The scene op is slowed too, so a cancelled check is still at work when the next one starts.) + k.assembly = async (op) => { const r = await real(op); if (op.op === 'interference' || op.op === 'scene') await new Promise((later) => setTimeout(later, op.op === 'scene' ? 150 : 40)); return r; }; + }); + for (let round = 0; round < 3; round++) { + await pm.getByRole('button', { name: 'Check Interference' }).click(); + await page.waitForTimeout(500 + 300 * round); + await pm.locator('.pm-section').filter({ has: page.getByRole('progressbar', { name: 'Interference check progress' }) }).getByRole('button', { name: 'Cancel' }).click(); + if (round === 1) { + await pm.getByRole('button', { name: 'Play', exact: true }).click(); + await page.waitForTimeout(200); + await pm.getByRole('button', { name: 'Pause' }).click(); + await overlapping(); + } + } + await pm.getByRole('button', { name: 'Check Interference' }).click(); + await expect(done).toHaveText('Components overlap in 15 of the frames checked.', { timeout: 60_000 }); + expect(await list()).toEqual(first); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); + +test('a long motion study downloads as CSV in parts that join into the same rows', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + // 30 s at 240 frames a second: 7201 rows, over the 5000 of a part. + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).fill('30'); + await pm.getByRole('spinbutton', { name: 'Duration (s)' }).press('Enter'); + await pm.getByRole('spinbutton', { name: 'Frames per second' }).fill('240'); + await pm.getByRole('spinbutton', { name: 'Frames per second' }).press('Enter'); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 7201 frames' })).toBeVisible({ timeout: 60_000 }); + await pm.getByRole('button', { name: 'Pause' }).click(); + const download = page.waitForEvent('download'); + await pm.getByRole('button', { name: 'Download CSV' }).click(); + const { readFileSync } = await import('node:fs'); + const text = new TextDecoder().decode(readFileSync(await (await download).path())); + expect(text.endsWith('\n')).toBe(false); + const lines = text.split('\n'); + expect(lines).toHaveLength(7202); + expect(lines[0]).toMatch(/^Time \(s\),Displacement X \(mm\),/); + const cols = lines[0].split(',').length; + for (const [i, l] of lines.entries()) if (i) { + expect(l.split(',')).toHaveLength(cols); + expect(Number(l.split(',')[0])).toBeCloseTo((i - 1) / 240, 6); + } + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); + +test('a motion study plots the turn of a hinge without limits, from where it started', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + const pm = await hingedGears(page); + await page.locator('.cm [data-cmd="motionStudy"]').click(); + await hingeMotor(page); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: 'Calculated 151 frames' })).toBeVisible(); + await pm.getByRole('button', { name: 'Pause' }).click(); + // 90°/s for 5 s: the small gear's hinge turns 450°, the large one's half as far the other way. + await pm.getByRole('combobox', { name: 'Result of' }).selectOption({ label: 'Mate: Hinge1' }); + await expect(pm.getByRole('img', { name: /^Plot of Hinge1 value \(°\)/ })).toHaveAttribute('aria-label', /from (0 to 450|-450 to 0)$/); + await pm.getByRole('combobox', { name: 'Result of' }).selectOption({ label: 'Mate: Hinge2' }); + await expect(pm.getByRole('img', { name: /^Plot of Hinge2 value \(°\)/ })).toHaveAttribute('aria-label', /from (0 to 225|-225 to 0)$/); + await pm.getByRole('combobox', { name: 'Quantity' }).selectOption({ label: 'Rate of change' }); + await expect(pm.getByRole('img', { name: /^Plot of Hinge2 rate of change \(°\/s\)/ })).toHaveAttribute('aria-label', /from (45 to 45|-45 to -45)$/); + const download = page.waitForEvent('download'); + await pm.getByRole('button', { name: 'Download CSV' }).click(); + const { readFileSync } = await import('node:fs'); + const csv = new TextDecoder().decode(readFileSync(await (await download).path())).split('\n'); + expect(csv[0]).toBe('Time (s),Value (deg),Rate (deg/s),Second derivative (deg/s^2)'); + expect(Math.abs(Number(csv[151].split(',')[1]))).toBeCloseTo(225, 3); + await pm.getByRole('button', { name: 'Cancel' }).first().click(); + expect(errors).toEqual([]); +}); + +test('a limited hinge counts its angle from where it puts the component, even when it turns it about its axis', async ({ page }) => { + test.setTimeout(120_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE]], ['Plate', 'Plate']); + await built(page, ['Plate<1>', 'Plate<2>']); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + // The second plate turns about its second hole, on the first plate's, and is turned 90° about it. + await select(page, [{ comp: 'Plate<2>', face: 'E1:side:h2' }, { comp: 'Plate<1>', face: 'E1:side:h2' }]); + let pm = await openMate(page, 'concentric'); + await pm.getByRole('button', { name: 'OK' }).click(); + await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + m.commit('Turn', (d) => { const c = d.components.find((x) => x.name === 'Plate<2>')!; c.placement = { p: [70, -30, 10], q: [0, 0, Math.SQRT1_2, Math.SQRT1_2] }; }, false); + }); + // A hinge on the first holes turns it back 90° to line them up: limited to ±45° from there, it holds. + await select(page, [{ comp: 'Plate<2>', face: 'E1:side:h1' }, { comp: 'Plate<1>', face: 'E1:side:h1' }]); + pm = await openMate(page, 'hinge'); + await pm.getByRole('group', { name: 'Coincident selections' }).click(); + await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); + await pick(page, { comp: 'Plate<2>', face: 'E1:cap0' }); + await pm.getByRole('checkbox', { name: /Limit the angle/ }).check(); + await expect(pm.getByRole('status').filter({ hasText: 'The assembly is fully defined.' })).toBeVisible(); + await pm.getByRole('button', { name: 'OK' }).click(); + await expect(tree.getByRole('treeitem', { name: /^Hinge1/ })).not.toHaveAttribute('aria-description', /Error/); + await expect(page.locator('.statusbar')).toContainText('Fully Defined'); + expect(errors).toEqual([]); +}); + +test('interference over a motion reports a pair whose overlap could not be computed, in every frame it was checked', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Small', disc(10)], ['Large', disc(20)]], ['Plate', 'Small', 'Large']); + await built(page, ['Plate<1>', 'Small<1>', 'Large<1>']); + await select(page, [{ comp: 'Large<1>', face: 'E1:side:k' }, { comp: 'Plate<1>', face: 'E1:side:h2' }]); + const pm = await openMate(page, 'hinge'); + await pm.getByRole('group', { name: 'Coincident selections' }).click(); + await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); + await pick(page, { comp: 'Large<1>', face: 'E1:cap0' }); + await pm.getByRole('button', { name: 'OK' }).click(); + await page.evaluate(() => { + const a = (window as unknown as { __parametric: A }).__parametric; + const m = a.assembly!; + const id = m.doc.mates[0].id; + m.commit('Study', (d) => { d.studies = [{ id: 's90', name: 'Motion Study1', duration: 2, fps: 30, motors: [{ id: 'o91', name: 'RotaryMotor1', kind: 'rotary', mate: id, profile: 'constant', speed: 90 }] }]; }); + // The worker cannot compute the overlap of scene items 0 and 1 (wherever it checks them). + const k = a.kernel as unknown as { assembly: (r: { op: string; groups?: number[] }) => Promise }; + const orig = k.assembly.bind(k); + k.assembly = async (r) => { + const out = await orig(r); + if (r.op === 'interference' && (!r.groups || r.groups[0] !== r.groups[1])) return [{ a: 0, b: 1, volume: 0, mesh: null, failed: true }, ...(out as unknown[])]; + return out; + }; + }); + const tree = page.getByRole('tree', { name: 'Assembly design tree' }); + await tree.getByRole('treeitem', { name: /^Motion Study1/ }).dblclick(); + await pm.getByRole('button', { name: 'Calculate' }).click(); + await expect(pm.getByRole('status').filter({ hasText: /Calculated/ })).toBeVisible(); + await pm.getByRole('button', { name: 'Check Interference' }).click(); + await expect(pm.getByRole('button', { name: 'Check Interference' })).toBeVisible({ timeout: 60_000 }); + // Not called clear: the pair stays still, so it is checked once and kept for every frame. + await expect(pm.getByRole('alert').filter({ hasText: 'Could not check Plate<1> / Small<1> (40 frames): the overlap could not be computed.' })).toBeVisible(); + await expect(pm.getByRole('status').filter({ hasText: 'No interference in the frames checked' })).toHaveCount(0); + expect(errors).toEqual([]); +}); + +test('a universal joint with a joint point takes its yokes where the point puts the shafts (adding it turned the input shaft 18°)', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await newAssemblyWith(page, [['Plate', PLATE], ['Shaft', SHAFT]], ['Plate', 'Shaft', 'Shaft']); + await built(page, ['Plate<1>', 'Shaft<1>', 'Shaft<2>']); + await select(page, [{ comp: 'Shaft<1>', face: 'E1:side:k' }, { comp: 'Plate<1>', face: 'E1:side:h1' }]); + let pm = await openMate(page, 'hinge'); + await pm.getByRole('group', { name: 'Coincident selections' }).click(); + await pick(page, { comp: 'Plate<1>', face: 'E1:cap1' }); + await pick(page, { comp: 'Shaft<1>', face: 'E1:cap0' }); + await pm.getByRole('button', { name: 'OK' }).click(); + // Shaft<2> pivots on a ball at C (its end), tilted. + await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const C = [40, 35, 60] as [number, number, number]; + const s = Math.sin(0.45), c = Math.cos(0.45), k = Math.SQRT1_2; + m.commit('Ball', (d) => { + const plate = d.components.find((x) => x.name === 'Plate<1>')!, sh = d.components.find((x) => x.name === 'Shaft<2>')!; + sh.placement = { p: C, q: [k * s, k * s, 0, c] }; + d.mates.push({ id: 'm900', name: 'Ball', type: 'coincident', a: { comp: plate.id, point: C }, b: { comp: sh.id, point: [0, 0, 0] }, aligned: true } as never); + }); + }); + const turn = () => page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const q = (n: string) => m.solved.get(m.doc.components.find((c) => c.name === n)!.id)!.q; + const a = q('Shaft<1>'); + return { a: (2 * Math.atan2(a[2], a[3]) * 180) / Math.PI, b: q('Shaft<2>') }; + }); + const before = await turn(); + await select(page, [{ comp: 'Shaft<1>', face: 'E1:side:k' }, { comp: 'Shaft<2>', face: 'E1:side:k' }]); + pm = await openMate(page, 'universal'); + await pm.getByRole('checkbox', { name: /Joint point/ }).check(); + await pm.getByRole('textbox', { name: 'Joint point offset (along the first shaft)' }).fill('15'); + await pm.getByRole('textbox', { name: 'Joint point offset (along the first shaft)' }).press('Enter'); + await pm.getByRole('button', { name: 'OK' }).click(); + const after = await turn(); + await expect(page.locator('.statusbar')).toContainText('Under Defined (1 DOF)'); + expect(Math.abs(after.a - before.a)).toBeLessThan(3); + const phase = await page.evaluate(() => { + const m = (window as unknown as { __parametric: A }).__parametric.assembly!; + const uj = m.doc.mates.find((x) => x.type === 'universal')!; + const rot = (q: number[], v: number[]) => { const [x, y, z, w] = q; const t = [2 * (y * v[2] - z * v[1]), 2 * (z * v[0] - x * v[2]), 2 * (x * v[1] - y * v[0])]; return [v[0] + w * t[0] + y * t[2] - z * t[1], v[1] + w * t[1] + z * t[0] - x * t[2], v[2] + w * t[2] + x * t[1] - y * t[0]]; }; + const conj = (q: number[]) => [-q[0], -q[1], -q[2], q[3]]; + const mul = (a: number[], b: number[]) => [a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1], a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0], a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3], a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2]]; + const dot = (a: number[], b: number[]) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + const cross = (a: number[], b: number[]) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + const nrm = (a: number[]) => { const l = Math.hypot(a[0], a[1], a[2]); return a.map((x) => x / l); }; + const Z = [0, 0, 1]; + const bInA0 = rot(uj.rel!.q, Z); + const ya = nrm(bInA0.map((v, i) => v - Z[i] * dot(Z, bInA0))); + const ca = m.doc.components.find((c) => c.name === 'Shaft<1>')!.id, cb = m.doc.components.find((c) => c.name === 'Shaft<2>')!.id; + const qa = m.solved.get(ca)!.q, qb = m.solved.get(cb)!.q; + const bInA = rot(mul(conj(qa), qb), Z); + const n = nrm(cross(Z, bInA)); + return (Math.asin(Math.abs(dot(ya, n))) * 180) / Math.PI; + }); + // The first yoke lies in the plane of the two shafts where the joint holds (it was 64° out of it). + expect(phase).toBeLessThan(3); + expect(errors).toEqual([]); +}); diff --git a/src/parametric/tests/e2e/dialogs.spec.ts b/src/parametric/tests/e2e/dialogs.spec.ts index b6cd2e7f6..14ba29d69 100644 --- a/src/parametric/tests/e2e/dialogs.spec.ts +++ b/src/parametric/tests/e2e/dialogs.spec.ts @@ -97,7 +97,7 @@ test('a density error does not prevent selecting a preset material', async ({ pa await dialog.getByRole('button', { name: 'Apply' }).click(); await expect(dialog).toHaveCount(0); expect(await page.evaluate(() => (window as unknown as Handle).__parametric.store.doc.material)) - .toEqual({ name: 'Aluminum 6061', density: 2700 }); + .toEqual({ name: 'Aluminum 6061', density: 2700, E: 68900, nu: 0.33, yield: 276, uts: 310 }); expect(errors).toEqual([]); }); @@ -200,3 +200,50 @@ test('Equations shows what a value being typed evaluates to, and what uses it, b await dialog.getByRole('button', { name: 'Cancel' }).click(); expect(await page.evaluate(() => (window as unknown as Handle).__parametric.store.doc.variables.map((v) => v.expr))).toEqual(['10', 'Width/2']); }); + +test('an invalid elastic property of a custom material is the field marked and focused', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.evaluate(() => (window as unknown as Handle).__parametric.commands.run('material')); + const dialog = page.getByRole('dialog', { name: 'Material', exact: true }); + await dialog.getByRole('combobox').selectOption('__custom'); + const e = dialog.getByLabel('Elastic modulus in GPa'), nu = dialog.getByLabel("Poisson's ratio"), sy = dialog.getByLabel('Yield strength in MPa'), uts = dialog.getByLabel('Tensile strength in MPa'); + await e.fill('200'); + await nu.fill('0.5'); + await sy.fill('250'); + await uts.fill('400'); + await dialog.getByRole('button', { name: 'Apply' }).click(); + await expect(nu).toBeFocused(); + await expect(nu).toHaveAttribute('aria-invalid', 'true'); + for (const ok of [e, sy, uts]) await expect(ok).not.toHaveAttribute('aria-invalid'); + await expect(nu).toHaveAccessibleDescription(/Poisson's ratio from 0 to below 0\.5/); + // Corrected: applied with the modulus in MPa. + await nu.fill('0.3'); + await expect(nu).not.toHaveAttribute('aria-invalid'); + await dialog.getByRole('button', { name: 'Apply' }).click(); + await expect(dialog).toHaveCount(0); + expect(await page.evaluate(() => (window as unknown as Handle).__parametric.store.doc.material)) + .toEqual({ name: 'Custom material', density: 1000, E: 200000, nu: 0.3, yield: 250, uts: 400 }); + expect(errors).toEqual([]); +}); + +test('a custom material whose yield strength is above its tensile strength is refused', async ({ page }) => { + const errors = await openApp(page); + await page.getByRole('button', { name: /New part/ }).click(); + await page.evaluate(() => (window as unknown as Handle).__parametric.commands.run('material')); + const dialog = page.getByRole('dialog', { name: 'Material', exact: true }); + await dialog.getByRole('combobox').selectOption('__custom'); + await dialog.getByLabel('Elastic modulus in GPa').fill('200'); + await dialog.getByLabel("Poisson's ratio").fill('0.3'); + await dialog.getByLabel('Yield strength in MPa').fill('400'); + await dialog.getByLabel('Tensile strength in MPa').fill('250'); + await dialog.getByRole('button', { name: 'Apply' }).click(); + await expect(dialog.getByRole('alert')).toHaveText('The yield strength cannot be above the tensile strength.'); + await expect(dialog.getByLabel('Yield strength in MPa')).toBeFocused(); + await expect(dialog.getByLabel('Tensile strength in MPa')).toHaveAttribute('aria-invalid', 'true'); + await dialog.getByLabel('Tensile strength in MPa').fill('450'); + await dialog.getByRole('button', { name: 'Apply' }).click(); + await expect(dialog).toHaveCount(0); + expect(await page.evaluate(() => (window as unknown as Handle).__parametric.store.doc.material)).toMatchObject({ yield: 400, uts: 450 }); + expect(errors).toEqual([]); +}); diff --git a/src/parametric/tests/fea-client.test.ts b/src/parametric/tests/fea-client.test.ts new file mode 100644 index 000000000..313667f1e --- /dev/null +++ b/src/parametric/tests/fea-client.test.ts @@ -0,0 +1,156 @@ +// The stress analysis worker's interface side and the worker itself (run in +// this thread with a stand-in for the worker scope): progress, results, +// errors written for the user or not, Cancel, a worker that dies, the arrays +// that are moved rather than copied. +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import init from 'replicad-opencascadejs'; +import { ModelBuilder } from '../src/kernel/build'; +import { setOc } from '../src/kernel/occ'; +import { FeaCancelled, FeaClient, FeaEngineError } from '../src/fea/client'; +import type { FeaWorkerRequest, FeaWorkerResponse } from '../src/fea/worker'; +import type { FeaSurfaceData } from '../src/fea/surface'; +import { extrude, rect, req, sketch } from './helpers'; + +/** The worker module, loaded with `self` standing for its global scope. */ +type Scope = { onmessage: ((ev: MessageEvent) => void) | null; postMessage: (m: FeaWorkerResponse, t?: Transferable[]) => void }; +const scope: Scope = { onmessage: null, postMessage: () => {} }; +const g = globalThis as unknown as { self?: unknown }; +const hadSelf = 'self' in g, oldSelf = g.self; +let firstMessage: FeaWorkerResponse | undefined; + +beforeAll(async () => { + setOc(await init()); + g.self = scope; + scope.postMessage = (m) => { firstMessage ??= m; }; + await import('../src/fea/worker'); +}); +afterAll(() => { if (hadSelf) g.self = oldSelf; else delete g.self; }); + +/** A Worker that runs the worker module in this thread (asynchronously, like a real one). */ +class LocalWorker { + onmessage: ((ev: MessageEvent) => void) | null = null; + onerror: ((ev: ErrorEvent) => void) | null = null; + terminated = false; + posted: { msg: FeaWorkerRequest; transfer: Transferable[] }[] = []; + replies: { msg: FeaWorkerResponse; transfer: Transferable[] }[] = []; + postMessage(msg: FeaWorkerRequest, transfer: Transferable[] = []) { + this.posted.push({ msg, transfer }); + setTimeout(() => { + if (this.terminated) return; + scope.postMessage = (m, t = []) => { this.replies.push({ msg: m, transfer: t }); if (!this.terminated) this.onmessage?.({ data: m } as MessageEvent); }; + scope.onmessage!({ data: msg } as MessageEvent); + }, 0); + } + terminate() { this.terminated = true; } +} + +/** A Worker that never answers. */ +class SilentWorker { + onmessage: ((ev: MessageEvent) => void) | null = null; + onerror: ((ev: Partial & { preventDefault?: () => void }) => void) | null = null; + terminated = false; + postMessage() {} + terminate() { this.terminated = true; } +} + +async function barSurface(): Promise<{ surface: FeaSurfaceData; faces: { normal?: number[] | null }[] }> { + const b = new ModelBuilder(); + const res = await b.build(req([sketch('s1', rect(0, 0, 60, 10)), extrude('f1', 's1', 10)], { quality: 1 })); + const fs = b.feaSurface(0.05); + return { surface: { positions: fs.positions, indices: fs.indices, triFace: fs.triFace }, faces: res.faces }; +} + +describe('analysis worker and client', () => { + it('meshes and solves with progress, moving the large arrays both ways', async () => { + const workers: LocalWorker[] = []; + const client = new FeaClient(() => { const w = new LocalWorker(); workers.push(w); return w as unknown as Worker; }); + const { surface, faces } = await barSurface(); + const stages = new Set(); + const info = await client.mesh(surface, 4, (s) => stages.add(s)); + expect(client.meshed).toBe(true); + expect(info.stats.elements).toBeGreaterThan(0); + expect(stages.has('Filling')).toBe(true); + // The surface went to the worker (moved, not copied), and the mesh came back the same way. + const sent = workers[0].posted[0]; + expect(sent.transfer).toContain(surface.positions.buffer); + expect(sent.transfer).toContain(surface.indices.buffer); + expect(workers[0].replies.at(-1)!.transfer).toContain(info.nodes.buffer); + const fixed = faces.findIndex((f) => f.normal?.[0] === -1), tip = faces.findIndex((f) => f.normal?.[0] === 1); + const solving: number[] = []; + const sol = await client.solve({ E: 200000, nu: 0.3, density: 7.85e-9, fixtures: [{ kind: 'fixed', faces: [fixed] }], loads: [{ kind: 'force', faces: [tip], total: 100, dir: [0, -1, 0] }] }, (s, v) => { if (s === 'Solving') solving.push(v); }); + expect(sol.fields).toHaveLength(6); + expect(sol.summary.maxDisplacement.value).toBeGreaterThan(0); + expect(workers[0].replies.at(-1)!.transfer).toEqual(sol.fields.map((f) => f.buffer)); + expect(solving.every((v) => v >= 0 && v <= 1)).toBe(true); + expect(workers).toHaveLength(1); + client.dispose(); + expect(workers[0].terminated).toBe(true); + }, 120000); + + it('passes on the messages written for the user, and wraps internal failures', async () => { + const client = new FeaClient(() => new LocalWorker() as unknown as Worker); + // An empty surface: a mesh error for the user. + const e2 = await client.mesh({ positions: new Float32Array(0), indices: new Uint32Array(0), triFace: new Int32Array(0) }, 1).catch((e) => e); + expect(e2.user).toBe(true); + expect(e2.message).toMatch(/no solid to mesh/); + expect(client.meshed).toBe(false); + // Solving without a mesh (the failed one replaced the last): a study error, as it is. + const e1 = await client.solve({ E: 1, nu: 0.3, density: 0, fixtures: [], loads: [] }).catch((e) => e); + expect(e1).toBeInstanceOf(FeaEngineError); + expect(e1.user).toBe(true); + expect(e1.message).toBe('Mesh the part first.'); + // Damaged input (triangles naming vertices that are not there): an internal failure, said as one. + const e3 = await client.mesh({ positions: new Float32Array([0, 0, 0]), indices: new Uint32Array([0, 5, 9]), triFace: new Int32Array([0]) }, 1).catch((e) => e); + expect(e3).toBeInstanceOf(FeaEngineError); + expect(e3.message).toMatch(/^The analysis ran into a problem|no solid/); + client.dispose(); + }, 60000); + + it('cancels at once: the request rejects, the worker is stopped and the next request starts a new one', async () => { + const workers: SilentWorker[] = []; + const client = new FeaClient(() => { const w = new SilentWorker(); workers.push(w); return w as unknown as Worker; }); + const p = client.mesh({ positions: new Float32Array(9), indices: new Uint32Array(3), triFace: new Int32Array(1) }, 1); + const q = client.solve({ E: 1, nu: 0.3, density: 0, fixtures: [], loads: [] }); + expect(client.busy).toBe(true); + client.cancel(); + await expect(p).rejects.toBeInstanceOf(FeaCancelled); + await expect(q).rejects.toBeInstanceOf(FeaCancelled); + expect(workers[0].terminated).toBe(true); + expect(client.busy).toBe(false); + expect(client.meshed).toBe(false); + // Cancel with nothing running leaves the worker alone. + const r = client.solve({ E: 1, nu: 0.3, density: 0, fixtures: [], loads: [] }); + expect(workers).toHaveLength(2); + client.cancel(); + await expect(r).rejects.toBeInstanceOf(FeaCancelled); + client.cancel(); + expect(workers).toHaveLength(2); + }); + + it('the worker says when its code has loaded', () => { + expect(firstMessage).toEqual({ id: 0, type: 'ready' }); + }); + + it('a worker that cannot load its code says so, not that the part is too large', async () => { + const workers: SilentWorker[] = []; + const client = new FeaClient(() => { const w = new SilentWorker(); workers.push(w); return w as unknown as Worker; }); + const p = client.mesh({ positions: new Float32Array(9), indices: new Uint32Array(3), triFace: new Int32Array(1) }, 1); + workers[0].onerror!({ preventDefault: () => {} }); + await expect(p).rejects.toThrow(/could not start.*reload the page/); + await expect(p).rejects.not.toThrow(/coarser mesh/); + expect(client.busy).toBe(false); + }); + + it('a worker that dies (out of memory) fails its requests with advice instead of hanging', async () => { + const workers: SilentWorker[] = []; + const client = new FeaClient(() => { const w = new SilentWorker(); workers.push(w); return w as unknown as Worker; }); + const p = client.solve({ E: 1, nu: 0.3, density: 0, fixtures: [], loads: [] }); + workers[0].onmessage!({ data: { id: 0, type: 'ready' } } as MessageEvent); + let prevented = false; + workers[0].onerror!({ message: 'Uncaught RangeError: Array buffer allocation failed', preventDefault: () => { prevented = true; } }); + await expect(p).rejects.toThrow(/Array buffer allocation failed.*coarser mesh/); + expect(prevented).toBe(true); + expect(workers[0].terminated).toBe(true); + expect(client.busy).toBe(false); + }); +}); diff --git a/src/parametric/tests/fea-mesher.test.ts b/src/parametric/tests/fea-mesher.test.ts new file mode 100644 index 000000000..184cb86c2 --- /dev/null +++ b/src/parametric/tests/fea-mesher.test.ts @@ -0,0 +1,159 @@ +// Volume meshing for stress analysis on parts built by the real kernel: +// positive elements, the mesh's volume against the solid's, faces covered by +// boundary triangles of their own, and every example part meshed. +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 { EXAMPLES } from '../src/app/examples'; +import { SurfaceIndex } from '../src/fea/surface'; +import { MAX_DOFS, MeshError, type TetMesh, defaultElementSize, estimateDofs, maxElementSize, meshSolid, meshWalls, minElementSize, quadJacobian, tetVolume } from '../src/fea/mesher'; +import { elementSizeFor } from '../src/model/fea'; +import { integrateTriangle } from '../src/fea/elements'; +import type { Feature } from '../src/model/types'; +import { circle, extrude, rect, req, sketch } from './helpers'; + +beforeAll(async () => { + setOc(await init()); +}); + +async function surfaceOf(features: Feature[], tol = 0.01) { + const b = new ModelBuilder(); + const res = await b.build(req(features, { quality: 1 })); + expect(res.status.every((s) => s.ok)).toBe(true); + const fs = b.feaSurface(tol); + return { surf: new SurfaceIndex(fs), fs, faces: res.faces }; +} + +/** Every element positive, at its corners and at its quadrature points. */ +function expectValid(m: TetMesh) { + const ne = m.tets.length / 10; + for (let e = 0; e < ne; e++) { + const t = m.tets; + expect(tetVolume(m.nodes, t[e * 10], t[e * 10 + 1], t[e * 10 + 2], t[e * 10 + 3])).toBeGreaterThan(0); + for (const [a, b, c] of [[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], [0.25, 0.25, 0.25]]) expect(quadJacobian(m.nodes, t, e, a, b, c)).toBeGreaterThan(0); + } +} + +/** Area of the mesh's boundary triangles on each face. */ +function meshFaceAreas(m: TetMesh): Map { + const out = new Map(); + for (let f = 0; f < m.triFace.length; f++) out.set(m.triFace[f], (out.get(m.triFace[f]) ?? 0) + integrateTriangle(m.nodes, m.tris, f)); + return out; +} + +describe('volume mesher', () => { + it('meshes a box exactly: volume, faces, edges and corners', async () => { + const { surf, faces } = await surfaceOf([sketch('s1', rect(0, 0, 200, 20)), extrude('f1', 's1', 10)]); + expect(surf.volume()).toBeCloseTo(40000, 3); + const m = meshSolid(surf, { size: 4 }); + expectValid(m); + expect(m.stats.volume / 40000).toBeCloseTo(1, 6); + expect(m.stats.unassigned).toBe(0); + expect(m.stats.pieces).toBe(1); + const areas = meshFaceAreas(m); + faces.forEach((f, i) => expect(areas.get(i)! / f.area).toBeCloseTo(1, 4)); + expect(m.stats.minQuality).toBeGreaterThan(0.15); + }, 60000); + + it('meshes a plate with a hole: curved boundary on the cylinder', async () => { + const { surf, fs, faces } = await surfaceOf([sketch('s1', [...rect(-50, -25, 50, 25), ...circle(0, 0, 5)]), extrude('f1', 's1', 4)]); + const m = meshSolid(surf, { size: 1.5 }); + expectValid(m); + // Quadratic elements follow the hole: the volume is within a few parts in ten thousand of the exact one. + expect(Math.abs(m.stats.volume / fs.volume - 1)).toBeLessThan(5e-4); + const areas = meshFaceAreas(m); + const hole = faces.findIndex((f) => f.type === 'cylinder'); + expect(areas.get(hole)! / faces[hole].area).toBeCloseTo(1, 2); + faces.forEach((f, i) => expect(Math.abs(areas.get(i)! / f.area - 1)).toBeLessThan(0.01)); + }, 60000); + + it('meshes the same part the same way every time', async () => { + const { surf } = await surfaceOf([sketch('s1', [...rect(-20, -20, 20, 20), ...circle(0, 0, 8)]), extrude('f1', 's1', 30)]); + const a = meshSolid(surf, { size: 2.5 }), b = meshSolid(surf, { size: 2.5 }); + expect(Array.from(b.nodes)).toEqual(Array.from(a.nodes)); + expect(Array.from(b.tets)).toEqual(Array.from(a.tets)); + expect(Array.from(b.triFace)).toEqual(Array.from(a.triFace)); + }, 60000); + + /** The sizes the mesh panel offers for a part: automatic, largest, smallest, and the one for a fineness. */ + const sizesOf = (surf: SurfaceIndex, volume: number) => { + const area = surf.faceAreas().reduce((a, b) => a + b, 0); + const auto = defaultElementSize(volume, area, surf.diag), max = maxElementSize(volume, area, surf.diag), min = minElementSize(volume, area, surf.diag); + return { area, auto, max, min, at: (fineness: number) => elementSizeFor(auto, max, fineness, min) }; + }; + + it('meshes a 1.5 mm plate at the default size: elements as thick as the plate, the unknowns estimated', async () => { + // 200 x 100 x 1.5: the default for its volume alone (2.35 mm) left no mesh in the plate. + const { surf, fs } = await surfaceOf([sketch('s1', rect(0, 0, 200, 100)), extrude('f1', 's1', 1.5)]); + const z = sizesOf(surf, fs.volume); + const size = z.at(0.5); + expect(size).toBeLessThanOrEqual(1.5); + const m = meshSolid(surf, { size }); + expect(Math.abs(m.stats.volume / fs.volume - 1)).toBeLessThan(1e-3); + expect(m.stats.pieces).toBe(1); + const est = estimateDofs(fs.volume, size, z.area); + expect(Math.abs(est / (m.stats.nodes * 3) - 1)).toBeLessThan(0.1); + // Fine stops at what a browser can solve. + expect(estimateDofs(fs.volume, z.at(1), z.area)).toBeLessThanOrEqual(MAX_DOFS * 1.001); + }, 60000); + + it('keeps the sizes of compact parts, and caps their fine end at what a browser can solve', async () => { + const { surf, fs } = await surfaceOf([sketch('s1', rect(0, 0, 50, 50)), extrude('f1', 's1', 50)]); + const z = sizesOf(surf, fs.volume); + expect(z.at(0.5)).toBeCloseTo(Math.cbrt(125000 / 2300), 6); + expect(z.at(1)).toBeCloseTo(Math.cbrt(125000 / 2300) / 2, 6); + // Within 5% of the 960,960 unknowns of that mesh. + expect(Math.abs(estimateDofs(fs.volume, z.at(1), z.area) / 960960 - 1)).toBeLessThan(0.05); + // A plate with many holes: half the automatic size would be 1.2 million unknowns. + const big = await surfaceOf([sketch('s1', [...rect(0, 0, 200, 100), ...Array.from({ length: 40 }, (_, i) => circle(10 + (i % 10) * 20, 12.5 + Math.floor(i / 10) * 25, 4)).flat()]), extrude('f1', 's1', 5)]); + const zb = sizesOf(big.surf, big.fs.volume); + expect(zb.at(1)).toBeGreaterThan(zb.auto / 2); + expect(estimateDofs(big.fs.volume, zb.at(1), zb.area)).toBeCloseTo(MAX_DOFS, -3); + }, 60000); + + it('meshes finer where walls are thinner than the size set (a thin plate with a thick boss)', async () => { + const { surf, fs } = await surfaceOf([sketch('s1', rect(0, 0, 200, 100)), extrude('f1', 's1', 1.5), sketch('s2', circle(100, 50, 12)), extrude('f2', 's2', 25)]); + const z = sizesOf(surf, fs.volume); + const size = z.at(0.5); + expect(() => meshSolid(surf, { size })).toThrow(/walls are thinner than the elements/); + const m = meshWalls(surf, { size, min: z.min }); + expect(m.stats.size).toBeLessThan(size); + expect(m.stats.size).toBeGreaterThanOrEqual(z.min); + expect(Math.abs(m.stats.volume / fs.volume - 1)).toBeLessThan(1e-2); + }, 60000); + + it('refuses a plate too thin for any mesh a browser can solve, instead of meshing a fraction of it', async () => { + // 100 x 100 x 0.5: elements as thin as that would make several million unknowns. + const { surf, fs } = await surfaceOf([sketch('s1', rect(0, 0, 100, 100)), extrude('f1', 's1', 0.5)]); + const z = sizesOf(surf, fs.volume); + expect(z.at(1)).toBeGreaterThan(0.5); + expect(() => meshSolid(surf, { size: z.at(1) })).toThrow(MeshError); + expect(() => meshSolid(surf, { size: z.at(1) })).toThrow(/misses \d+% of the part's volume/); + expect(() => meshWalls(surf, { size: z.at(0.5), min: z.min })).toThrow(/misses \d+% of the part's volume: some of its walls are thinner than the elements\. Elements small enough for those walls would make more unknowns than a browser can solve\./); + }, 60000); + + for (const ex of EXAMPLES) { + it(`meshes the ${ex.name} example at its automatic size, coarse and fine`, async () => { + const { surf, fs, faces } = await surfaceOf(ex.make().features); + const area = surf.faceAreas().reduce((a, b) => a + b, 0); + const auto = defaultElementSize(fs.volume, area, surf.diag); + const max = maxElementSize(fs.volume, area, surf.diag); + for (const size of [elementSizeFor(auto, max, 0), elementSizeFor(auto, max, 0.5), elementSizeFor(auto, max, 1)]) { + const m = meshSolid(surf, { size }); + expectValid(m); + expect(m.stats.pieces).toBe(1); + // Coarse meshes may cut a little off small fillets (below the 2% the mesh panel warns about). + expect(Math.abs(m.stats.volume / fs.volume - 1)).toBeLessThan(size > auto ? 0.02 : 0.004); + // No slivers on the bracket: the edge recovery stops before it squashes elements (it went to 0.008 coarse). + if (ex.id === 'bracket') expect(m.stats.minQuality, `quality at ${size}`).toBeGreaterThan(0.04); + // Every face of the part is meshed, the large ones to within a few percent of their area. + const areas = meshFaceAreas(m); + faces.forEach((f, i) => { + expect(areas.get(i) ?? 0, `${f.name} (${f.type}) at ${size}`).toBeGreaterThan(0); + if (f.area > 40 * size * size) expect(Math.abs((areas.get(i) ?? 0) / f.area - 1), `${f.name} at ${size}`).toBeLessThan(size > auto ? 0.1 : 0.03); + }); + } + }, 120000); + } +}); diff --git a/src/parametric/tests/fea-model.test.ts b/src/parametric/tests/fea-model.test.ts new file mode 100644 index 000000000..24bf8e526 --- /dev/null +++ b/src/parametric/tests/fea-model.test.ts @@ -0,0 +1,154 @@ +// The study saved with the part, materials' elastic properties, and the +// results summary export: round trips, old files, refused damage. +import { describe, expect, it } from 'vitest'; +import { newDocument, parseDocument, serializeDocument } from '../src/model/document'; +import { type StaticStudy, elementSizeFor, feaUnits, newStudy, nextStudyName, parseStudy, studyIds } from '../src/model/fea'; +import { MATERIALS, elasticOf, normalizeMaterial, validElastic } from '../src/model/materials'; +import { colorAt, interpolate } from '../src/fea/results'; +import { principal } from '../src/fea/elements'; +import { reportHtml, summaryCsv } from '../src/app/fea/report'; + +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 } }); + +function study(): StaticStudy { + const s = newStudy('st3'); + s.fixtures.push({ id: 'fx4', name: 'Fixed1', type: 'fixed', faces: [face('f1:cap0')] }); + s.fixtures.push({ id: 'fx5', name: 'Hinge1', type: 'hinge', faces: [{ name: 'f2:h1:1', sig: { type: 'cylinder', c: [0, 0, 0], area: 50 } }], suppressed: true }); + s.loads.push({ id: 'ld6', name: 'Force1', type: 'force', faces: [face('f1:cap1')], value: 250, dir: { kind: 'edge', edge: { name: 'e1', sig: { type: 'line', m: [0, 0, 0], len: 10 } } }, flip: true }); + s.loads.push({ id: 'ld7', name: 'Pressure1', type: 'pressure', faces: [face('f1:side:bl2')], value: 2, flip: false }); + s.loads.push({ id: 'ld8', name: 'Gravity1', type: 'gravity', value: 9806.65, dir: { kind: 'base', axis: 'y' }, flip: true }); + s.mesh.fineness = 0.75; + return s; +} + +describe('static study in the part file', () => { + it('saves and reads a study unchanged, and new ids never collide with its ids', () => { + const doc = newDocument(); + doc.study = study(); + const back = parseDocument(serializeDocument(doc)); + expect(back.study).toEqual(doc.study); + expect(back.nextId).toBeGreaterThan(8); + expect(studyIds(back.study)).toEqual(['st3', 'fx4', 'fx5', 'ld6', 'ld7', 'ld8']); + }); + + it('opens parts without a study, and with a null one', () => { + expect(parseDocument(serializeDocument(newDocument())).study).toBeUndefined(); + expect(parseDocument(JSON.stringify({ ...newDocument(), study: null })).study).toBeNull(); + }); + + it('refuses a damaged study with a message', () => { + const bad: [string, (s: Record) => void][] = [ + ['no fixture list', (s) => { delete s.fixtures; }], + ['unknown fixture type', (s) => { (s.fixtures as Record[])[0].type = 'glued'; }], + ['face without signature', (s) => { (s.fixtures as { faces: unknown[] }[])[0].faces = [{ name: 'x' }]; }], + ['duplicate ids', (s) => { (s.loads as Record[])[0].id = 'fx4'; }], + ['value not a number', (s) => { (s.loads as Record[])[1].value = '2 MPa'; }], + ['zero force', (s) => { (s.loads as Record[])[0].value = 0; }], + ['negative pressure', (s) => { (s.loads as Record[])[1].value = -2; }], + ['unknown load type', (s) => { (s.loads as Record[])[1].type = 'torque'; }], + ['gravity without a direction', (s) => { delete (s.loads as Record[])[2].dir; }], + ['bad direction', (s) => { (s.loads as Record[])[0].dir = { kind: 'base', axis: 'w' }; }], + ['fineness out of range', (s) => { s.mesh = { fineness: 3 }; }], + ['not an object', (s) => { for (const k of Object.keys(s)) delete s[k]; }], + ]; + for (const [what, damage] of bad) { + const raw = JSON.parse(JSON.stringify(study())) as Record; + damage(raw); + expect(() => parseStudy(raw), what).toThrow(/invalid study/); + expect(() => parseDocument(JSON.stringify({ ...newDocument(), study: raw })), what).toThrow(/damaged \(invalid study/); + } + }); + + it('drops unknown keys and keeps only what a study holds', () => { + const raw = { ...study(), extra: 1 } as Record; + (raw.fixtures as Record[])[0].colour = 'red'; + const s = parseStudy(raw); + expect('extra' in s).toBe(false); + expect('colour' in s.fixtures[0]).toBe(false); + }); + + it('sizes elements from the automatic size, never beyond the walls', () => { + expect(elementSizeFor(4, 100, 0.5)).toBeCloseTo(4); + expect(elementSizeFor(4, 100, 1)).toBeCloseTo(2); + expect(elementSizeFor(4, 100, 0)).toBeCloseTo(8); + expect(elementSizeFor(4, 6, 0)).toBeCloseTo(6); + }); + + it('shows forces and stresses in the part\'s units', () => { + expect(feaUnits('MMGS')).toMatchObject({ force: 'N', stress: 'MPa', length: 'mm' }); + expect(feaUnits('IPS')).toMatchObject({ force: 'lbf', stress: 'psi', length: 'in' }); + expect(1 / feaUnits('IPS').stressScale).toBeCloseTo(145.04, 1); + }); +}); + +describe('materials for analysis', () => { + it('has elastic properties for every preset but wood', () => { + for (const m of MATERIALS) expect(!!elasticOf(m), m.name).toBe(!/Oak|Pine/.test(m.name)); + const steel = elasticOf(MATERIALS[0])!; + expect(steel.E).toBeGreaterThan(190000); + expect(steel.yield).toBeLessThan(steel.uts); + }); + + it('finds the properties of a preset saved before materials had them', () => { + expect(elasticOf({ name: 'Aluminum 6061', density: 2700 })?.E).toBe(68900); + expect(elasticOf({ name: 'Aluminum 6061', density: 2600 })).toBeNull(); + expect(elasticOf({ name: 'Custom', density: 1000 })).toBeNull(); + expect(elasticOf(null)).toBeNull(); + }); + + it('keeps a custom material\'s properties only as a complete, valid set', () => { + const ok = { name: 'Custom', density: 1000, E: 1000, nu: 0.3, yield: 10, uts: 12 }; + expect(normalizeMaterial(ok)).toEqual(ok); + expect(normalizeMaterial({ ...ok, nu: 0.5 })).toEqual({ name: 'Custom', density: 1000 }); + expect(normalizeMaterial({ name: 'Custom', density: 1000, E: 1000 })).toEqual({ name: 'Custom', density: 1000 }); + expect(validElastic({ E: -1, nu: 0.3, yield: 1, uts: 1 })).toBe(false); + const doc = parseDocument(JSON.stringify({ ...newDocument(), material: { ...ok, E: 'stiff' } })); + expect(doc.material).toEqual({ name: 'Custom', density: 1000 }); + expect(parseDocument(JSON.stringify({ ...newDocument(), material: ok })).material).toEqual(ok); + }); +}); + +describe('result helpers', () => { + it('finds principal stresses', () => { + const p = principal(10, 0, 0, 0, 0, 0); + expect(p[0]).toBeCloseTo(10); + const q = principal(0, 0, 0, 5, 0, 0); + expect(q[0]).toBeCloseTo(5); + expect(q[2]).toBeCloseTo(-5); + expect(q[1]).toBeCloseTo(0); + }); + + it('interpolates on six-node triangles and maps colours', () => { + const tris = new Uint32Array([0, 1, 2, 3, 4, 5]); + const v = [0, 1, 0, 0.5, 0.5, 0]; + expect(interpolate(v, tris, 0, 0.5, 0)).toBeCloseTo(0.5); + expect(interpolate(v, tris, 0, 1, 0)).toBeCloseTo(1); + expect(colorAt(0)[2]).toBeGreaterThan(colorAt(0)[0]); + expect(colorAt(1)[0]).toBeGreaterThan(colorAt(1)[2]); + }); + + it('writes the summary as CSV, quoting what needs it', () => { + const csv = summaryCsv([{ section: 'Results', name: 'Max von Mises stress', value: '12.5', unit: 'MPa' }, { section: 'Study', name: 'Part', value: 'Bracket, "A"', unit: '' }]); + expect(csv.split('\n')[0]).toBe('Section,Quantity,Value,Unit'); + expect(csv).toContain('Results,Max von Mises stress,12.5,MPa'); + expect(csv).toContain('Study,Part,"Bracket, ""A""",'); + }); + + it('prints the report without splitting a row, the plot or the closing note across pages, nor leaving a heading at a page foot', () => { + const html = reportHtml('Part - Study', [{ section: 'Results', name: 'Max von Mises stress', value: '12.5', unit: 'MPa' }], 'data:image/png;base64,AA==', 'von Mises stress '); + const css = /