diff --git a/docs/superpowers/plans/2026-11-24-refine-sketch-guides.md b/docs/superpowers/plans/2026-11-24-refine-sketch-guides.md new file mode 100644 index 0000000..f033258 --- /dev/null +++ b/docs/superpowers/plans/2026-11-24-refine-sketch-guides.md @@ -0,0 +1,84 @@ +# Refine sketch guides implementation plan + +**Goal:** Make an Edge guide the edge itself, with settings that say how far the solve may move it, +and let the user place guide points exactly: on sketch planes, along lines, fixed, by a move +widget, and held by segment constraints. + +**Spec:** `docs/superpowers/specs/2026-11-24-refine-sketch-guides-design.md`. Background: +`docs/superpowers/specs/2026-11-19-scan-restoration-design.md`, "How an edge is rebuilt". + +**Tech stack:** TypeScript, three.js, react-three-fiber, Zustand, Vitest, Playwright. + +## Global constraints + +- Today's solve is the Along preset: `position` absent or `along`, `path` absent or false, `fit` + absent or null (today's reach), `wallAngle` absent or null. Detect's proposals and the crease + brush never set the new fields, so their inputs and results are unchanged. +- Hand-placed guides take the session's next-guide settings: Corner, Fit 0, Use guide path on, + Wall angle Automatic, and Use guide plane on when the guide has a plane. +- Every guide point keeps a valid `triangle`: a point off the surface takes the nearest triangle. +- Lengths in mm. Commit subjects `() `, no attribution. +- Checks per step: `npx tsc --noEmit`, the step's `npx vitest run tests/unit/refine-...` files, + `npx playwright test tests/e2e/refine.spec.ts`, `npm run format:check`. + +## Step 1: Solve settings + +**Files:** `src/core/refine-edge.ts`, `src/core/store.ts`, `src/components/RefineControls.tsx`, +new `tests/unit/refine-guide-edge.test.ts`. + +1. `EdgeInput` gains `position`, `fit`, `path`, `wallAngle`, `plane` and `usePlane` (all + optional). `EdgePosition = 'corner' | 'top' | 'bottom' | 'along'`. +2. In `solvePart`, after `unbiasedFlanks`, a `settle` step turns the scan's flanks into the + segment's final flanks and edge: tell the surface from the wall, put the sketch plane in as the + surface (Use guide plane), find where the faces meet, the guide's edge (Corner: the guide; Top + and Bottom: the guide carried onto the meet by one offset; Along: the guide), move it toward the + meet by at most Fit (one offset with Use guide path, per point without), and build the wall + through that edge at the wall angle for a line or arc. Along with no settings is today's + `fitMeet` exactly. +3. `shareFlanks`, `clearCorners` and `resolveParts` refit the scan's flanks and call `settle`, so a + shared surface or a cleared corner keeps the guide's edge. +4. A closed single arc fits its circle to the parts' edges, not the meets, when settings are set. +5. A refusal carries a reason the status line names (`EdgeRefusal`). +6. Store: `RefineSession.edge` gains the new defaults; `addRefinePoint` writes them; + `setRefineEdge` sets them; `solveProposal`'s cache is keyed by the input, so new settings + invalidate it. +7. Panel: Position (segmented), Fit (mm field), Use guide path and Use guide plane (switches), Wall + angle (`AutoSetting`). +8. Tests: the design's Verification items for the solve (slot, Top and Bottom on a fillet, Fit, + Use guide path). Existing tests that place guides by hand and assert today's solve are pinned to + Along. + +## Step 2: Sketch planes and points + +**Files:** new `src/core/refine-sketch.ts` (planes, projection, nearest triangle, locks), store, +`RefinePointer.tsx`, `Viewport.tsx`, `RefineOverlay.tsx`, `RefineControls.tsx`, +`EditorContextMenu.tsx`, new `src/components/RefinePointWidget.tsx`. + +1. `SketchPlane {id, origin, normal, u, v}`; session `planes`, `edge.plane` (next guide), a + `picking` state for New plane (3 points, or a face) and for a point menu's second click (line + lock, Align). +2. Drawing on a plane: a click places the point where the ray meets the plane, also off the part; + the point takes the nearest triangle. +3. Point locks on `GuidePoint`: `lock?: {kind: 'line', origin, direction} | {kind: 'fixed'}`. + Dragging follows the plane, the line, or does not start. +4. Move widget on the chosen point: world axes, plane axes and a plane square, or the line; one + drag is one undo step; Escape restores. +5. Point menu on right-click of a handle: Lock (to a plane, new plane, line, Fixed, Unlock), Align + (Horizontal, Vertical, then a click), Constrain, Delete, through `EditorContextMenu`. +6. Plane grid drawn round the selected guide. + +## Step 3: Constraints + +**Files:** new `src/core/refine-constraints.ts`, store, overlay, menu. + +1. Damped least-squares solver in the plane's (u, v): weighted least change, the moved point + weighted heavily, fixed points held; every constraint within 1e-6 mm or the change is refused. +2. Kinds: Parallel, Perpendicular, Collinear, Equal, Tangent, Concentric, Horizontal, Vertical, + Align (point to point), Fixed. +3. Segment menu (right-click a guide line), point menu Constrain, icons beside segments and points + (right-click an icon to delete). +4. Every point move, constraint change and plane change runs the solver. + +## Step 4: Docs + +The Refine page in `src/docs` and an entry at the top of `src/docs/changelog.ts`. diff --git a/docs/superpowers/specs/2026-11-24-refine-sketch-guides-design.md b/docs/superpowers/specs/2026-11-24-refine-sketch-guides-design.md new file mode 100644 index 0000000..9b966f6 --- /dev/null +++ b/docs/superpowers/specs/2026-11-24-refine-sketch-guides-design.md @@ -0,0 +1,259 @@ +# Refine: guides you can place exactly + +Added 2026-11-24. Changes the Edge mode of Refine described in +[2026-11-19-scan-restoration-design.md](2026-11-19-scan-restoration-design.md). + +## Intent + +Outlining a feature with an Edge guide is hard to do cleanly, and the solve then ignores the +outline. On a slot in a scanned plate (part 7), a closed guide of two lines and two arcs solved +to a curve that loops back on itself and lands well off the slot. The user places a guide where +the feature's edge is, or should be, so the guide's path and shape are what the result should +follow. + +The goal of Refine is unchanged: trade the scan's noise for smoother curves, flatter surfaces +and consistent splines, with sharp edges where the guides say. + +## What the user asked for (product owner) + +1. **The guide is the edge.** The user can adjust how far the solve may move it to fit the scan. +2. **Locks on the solve:** use the guide's path; use the guide's plane. +3. **Wall angle:** the user can give the rough angle between the wall and the surface. +4. **Where the guide sits on a filleted edge:** along the fillet, at the top of the fillet, at + the bottom of the fillet, or at the projected right-angle corner the fillet rounds off. +5. **The result on a filleted edge is a sharp corner.** +6. **Sketch planes:** lock a guide's points to a plane the user defines, for example from 3 + points. +7. **Line lock:** a point slides along a line. +8. **Move widget:** clicking an existing point shows a widget to move it. +9. **Point menu:** right-click a point to Lock, Align, Constrain or Delete it. +10. **Align** moves a point level with another point the user clicks, along one of the plane's + axes, like Fusion 360's horizontal and vertical constraints. +11. **Constraints between segments,** as in Fusion 360 sketches, for example parallel. + +## Goals + +- A guide placed on a sketch plane, at the corner, with the solve locked to it, produces a + sharp edge exactly on the guide. +- The user can tell the solve which parts of the answer come from the guide and which from the + scan. +- Points can be placed and moved precisely: on a plane, along a line, by a widget, and held in + place by constraints. +- Today's behaviour stays available for guides that only mark an edge (Detect and the crease + brush). + +## Non-goals + +- Leaving a fillet or chamfer on the refined edge. The result is a sharp corner. +- Typed dimensions (lengths, radii, angles between segments). +- Thinning the mesh. Refine keeps moving vertices onto the fitted surfaces, as today. +- Saving sketch planes or constraints with the scene. They live in the Refine session. +- Constraints on spline segments. Points of a spline can still be locked, aligned and fixed. + +## Anti-goals + +- A solve that moves the edge farther from the guide than the user allowed. +- A guide whose locks or constraints silently stop holding after a drag, an undo or a solve. + +## Decisions + +Marked **(product owner)** where the user decided; the rest are the designer's calls. + +### Solve settings + +Per edge guide, shown in the Edge section of the Refine panel and stored with the guide like +Width, Strength and Ends (`RefineSession.edge` holds the values for the next guide; +`EdgeInput` carries each guide's own): + +| Setting | Values | Default for a hand-placed guide | +| ------------------- | ---------------------------------------------- | ------------------------------- | +| **Position** | Corner, Top of fillet, Bottom of fillet, Along | Corner | +| **Fit** | mm, from 0 | 0 | +| **Use guide path** | on, off | on | +| **Use guide plane** | on, off; only for a guide on a sketch plane | on when the guide has a plane | +| **Wall angle** | Automatic, or degrees | Automatic | + +The two faces either side of the edge are named as the user named them: the **surface** and the +**wall**. With a sketch plane, the surface is the face more nearly parallel to the plane. +Without one, the builder picks a deterministic rule (for example the face more nearly parallel +to the best-fit plane of the guide's points, falling back to the larger flank) and documents it. + +What each setting does: + +- **Position** says where the guide lies relative to the rounded edge on the scan. + - **Corner** (product owner): the guide is the sharp edge itself. + - **Top of fillet**: the guide lies on the surface, where the rounding starts. The edge is + where the surface meets the wall. + - **Bottom of fillet**: the guide lies on the wall, where the rounding ends. The edge is + where the wall meets the surface. + - **Along**: the guide lies somewhere on the rounding. The edge is where the two faces meet, + found from both sides. This is today's solve. +- **Fit** (product owner) is how far, in mm, the solved edge may move off the edge the guide + sets. At 0 the edge is exactly the guide (Corner) or exactly the guide carried across the + rounding (Top, Bottom). +- **Use guide path** (product owner) keeps the guide's shape. A line stays a line in its + direction, an arc keeps its centre and plane, a spline keeps its shape. Any move is one + offset for the whole segment, within Fit. Off, each place along the edge may move on its + own, within Fit, and the segment is refitted to its kind, as today. +- **Use guide plane** (product owner) makes the surface the sketch plane itself, not a fit to + the scan, when Position is Corner or Top. With Bottom or Along, the surface is fitted from + the scan but held parallel to the plane. The edge then stays in the plane. +- **Wall angle** (product owner) is the angle between the surface and the wall, 90 for a + square edge whether it is an outside corner or the rim of a slot. Automatic reads it from the + scan. Set, the wall's fit is + held within 5 degrees of it. With the edge on the guide and the surface known, a set angle + fixes a straight wall as a plane through the edge and an arc's wall as a cylinder or cone + round the arc's axis; the scan only says which side the wall is on. + +How the solve runs with these (replacing steps 2 and 3 of "How an edge is rebuilt"): + +1. Read the band as today, but measure Width from the guide's edge (below), not from a solved + edge, so a narrow slot's band does not reach the far wall. +2. Fit the surface: the sketch plane (Use guide plane), or the flank on the surface side. +3. Fit the wall from the flank on the wall side, through the edge when the edge is known + (Corner), and held to Wall angle when it is set. +4. The guide's edge: Corner, the guide; Top or Bottom, the guide carried across the rounding + onto where the faces meet, as one offset per segment when Use guide path is on; Along, + where the faces meet, as today. +5. Move toward where the faces meet by at most Fit, keeping the guide's shape when Use guide + path is on, then rebuild as today: band vertices onto their side's face, a chain of mesh + edges cut onto the edge. + +**Today's solve stays as a setting.** Along, Use guide path off, and Fit at today's reach (the +larger of 0.35 mm and 6 edge lengths) reproduces the current solve. Detect's proposals and the +crease brush use exactly these settings, so their tests and behaviour do not change. Existing +solve tests run with these settings. + +A solve that cannot hold the user's settings (no wall on either side, Fit too small for the +faces to meet the edge, a wall that cannot be fitted within 5 degrees of Wall angle) refuses +as today and the status line says which setting to change. + +### Sketch planes + +- A sketch plane is a session object: an origin, a normal, and in-plane axes `u` and `v`. The + session keeps a list; the panel names them Plane 1, Plane 2, and so on. +- **Making one:** in the Edge section, Plane > New plane, then either click 3 points on the + mesh, or click once on a flat face to fit a plane to the surface around the click (reuse the + plane fitting in `src/core/planes.ts` or `fitShape`). `u` runs from the first point to the + second, or along the face fit's longer extent. +- **Using one:** Plane chooses the plane the next guide is drawn on (None by default). A + guide's plane can also be set from the point menu (Lock > To plane), which projects all of + that guide's points onto it. Every point of a guide shares its plane; a guide is on one plane + or none. +- **Drawing on a plane:** while drawing a guide on a plane, a click places the point where the + cursor's ray meets the plane, not where it meets the mesh, including where the ray misses the + part. This is what lets a point sit on the true corner of a rounded scan. +- The plane is drawn as a faint grid square around the guide while that guide is selected, with + its `u` and `v` axes marked. +- Planes last until Apply or Cancel, and are part of the session's undo steps. + +### Points + +- Every guide point keeps a `triangle` because the band search starts from it + (`refine-band.ts:433-441`). A point off the surface takes the triangle nearest it, looked up + with the part's BVH. +- **Locks per point:** To line (slides along a line through two points the user clicks, guide + points or mesh points), Fixed (does not move), or none. A point on a plane is locked to the + plane through its guide. Unlock clears a point's own lock. +- **Dragging a point** keeps today's gesture: free points slide along the mesh, as now. A point + on a plane slides on the plane (ray meets plane). A point on a line slides along the line. A + fixed point does not drag. +- **Move widget:** clicking a point (the existing choose-a-point click) shows a translate widget + at it. Free point: three arrows along the world axes. On a plane: two arrows along `u` and `v` + and a square handle for the plane. On a line: one arrow along the line. Fixed: no widget. + Follow the Warp point handle (`WarpOverlay.tsx:436-520`, proxy object and `PrecisionDrag`). + One widget drag is one undo step, like a handle drag today, and Escape during it restores the + point. +- **Point menu** (right-click a point handle; today `RefinePointer` ignores buttons other than + 0): + - **Lock** > To plane (pick a plane or New plane), To line, Fixed, Unlock. + - **Align** > Horizontal, Vertical, then click another point: this point takes that point's + `v` (Horizontal) or `u` (Vertical) coordinate in the plane. It is kept as a constraint. + Disabled on a guide with no plane, with the reason shown. + - **Constrain** > the segment constraints (below) between the two segments that meet at this + point. Disabled at an open end or where neither segment is a line or arc. + - **Delete** removes the point, as Remove point does today. +- The menu uses the editor's context menu component and keyboard handling + (`EditorContextMenu.tsx`), with its own item list for points. + +### Constraints + +- Constraints hold only on a guide on a sketch plane and are solved in that plane's `u`, `v` + coordinates. +- **Kinds:** Parallel, Perpendicular, Collinear, Equal (length of two lines, or radius of two + arcs), Tangent (a line and an arc, or two arcs, that share a point), Concentric (two arcs), + Horizontal and Vertical (a line along `u` or `v`; between two points, Align), and Fixed (the point menu's Lock, Fixed). +- **Adding one:** right-click a segment's guide line for the segment menu, Constrain, pick the + kind, then click the other segment. Horizontal and Vertical on a line need no second click. + From a point menu, Constrain applies to the two segments meeting there with no second click. +- **Seeing and removing:** each constraint shows a small icon beside its segment or point, as in + Fusion. Right-click the icon to delete the constraint. +- **Solving:** the guide's points are solved together whenever a point moves, a constraint is + added or removed, or a plane changes: the moved point follows the cursor, the rest move as + little as possible, and every constraint holds within 1e-6 mm. Arcs keep their three points; + constraints on an arc read its centre and radius from them. +- **Conflicts:** a constraint that cannot be met with the existing ones is refused, nothing + changes, and the status line says so, as Fusion does. A drag that cannot be followed stops + at the nearest position that keeps every constraint. +- Constraints stay with the guide until it is accepted, and are part of undo steps. + +## Approaches considered + +**What a guide controls** reverses "What a guide controls" in the 2026-11-19 design, where the +guide was a hint and the edge was solved from the flanks (product owner, then and now). +(1) Keep the hint and cap how far the edge may move. (2) The guide is the edge, with settings +that say which parts come from the scan. **Chosen: 2 (product owner).** With 1 the edge still +comes from flank fits, which is what fails on the slot. + +**Constraint solver.** (1) A sketch solver library (for example FreeCAD's planegcs built to +WebAssembly). (2) A small damped least-squares solver written here. **Chosen: 2.** A guide +has at most a few dozen points, so a Levenberg-Marquardt solve with a numeric Jacobian runs in +well under a millisecond, and it adds no dependency or WebAssembly build to the app. + +**Where a plane lives.** (1) Per point. (2) Per guide, chosen from session planes. **Chosen: 2.** Constraints need every point of a guide in one plane, and several guides sharing a plane +is how a Fusion sketch works. + +## Builder's discretion + +- How the surface and wall are told apart without a plane. +- Exact UI layout of the new settings, keeping the panel's existing patterns (`AutoSetting` for + Wall angle, the segmented control for Position). +- Constraint icon art and placement. +- How the plane grid is drawn. +- Status line wording, following `docs/documentation.md` and the existing Refine copy. + +## Build order + +Each step ends with its tests passing and a commit. + +1. **Solve settings:** Position, Fit, Use guide path, Wall angle, with today's solve as the + Along preset for Detect and the crease brush. +2. **Sketch planes and points:** planes, drawing on a plane, Use guide plane, line lock, Fixed, + the move widget, the point menu with Lock, Align and Delete. +3. **Constraints:** the solver, segment and point Constrain menus, icons, conflict refusal. +4. **Docs:** the Refine page in `src/docs`, and an entry at the top of `src/docs/changelog.ts`. + +## Verification + +Unit tests on synthetic fixtures (`tests/unit`, alongside the `refine-*` tests): + +- A plate with a slot whose walls are rounded at the top: a closed guide of two lines and two + arcs on a plane on the plate's top face, Position Corner, Fit 0, Use guide plane, Wall angle 90. The cut edge lies within 0.002 mm of the guide everywhere, has no loops and is in one + piece; the plate's top within the band is flat to 0.002 mm. +- The same with Wall angle Automatic: the edge still lies on the guide. +- A 90 degree edge filleted at a known radius: guides at Top and at Bottom of the fillet, Fit + 0, produce the edge at the true corner within 0.005 mm. Along with Fit at today's reach + matches today's result. +- Fit: with Position Corner and the guide placed 0.2 mm off the true corner, Fit 0 keeps the + edge on the guide; Fit 0.3 moves it to the corner; Fit 0.1 moves it 0.1 and no farther. +- Use guide path: a line guide stays straight and parallel to itself after the solve. +- Constraint solver: each kind alone; the slot (two parallel lines, two tangent arcs, equal + radii) under a drag; a conflicting constraint refused with nothing changed. +- Session: plane from 3 points and from a face; drawing on a plane; line lock; Fixed; Align; + Delete; undo and redo of each; constraints kept through undo. + +End to end (`tests/e2e/refine.spec.ts`): right-click a point opens the point menu; the widget +moves a point on a plane and the point stays in the plane; adding Parallel then dragging keeps +the lines parallel; deleting a constraint from its icon. + +Existing refine unit and end-to-end tests keep passing. diff --git a/src/App.tsx b/src/App.tsx index 04280e6..4a10146 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -55,6 +55,7 @@ import { liveHost, liveSession, refineHoldsWork, + refineStatus, useEditor, type RefineMode, type WarpGizmo, @@ -676,6 +677,10 @@ function StatusBar() { // Escape keeps the tool while leaving would lose work, so the hint says how to leave. refineWork = useEditor( (s) => s.tool === 'refine' && s.refine?.stage === 'ready' && refineHoldsWork(s.refine), + ), + // The picks a Refine session waits for, or why its selected guide was refused. + refineSaid = useEditor((s) => + s.tool === 'refine' && s.refine?.stage === 'ready' ? refineStatus(s.refine) : null, ); const hold = useShortcut('holdOrbit'), cancel = useShortcut('cancel'), @@ -711,7 +716,7 @@ function StatusBar() { : surfacePainting ? `Drag to paint · Alt erases${smaller || larger ? ` · ${[smaller, larger].filter(Boolean).join(' / ')} brush size` : ''} · ${orbitHint} orbits` : refineMode - ? `${refineHints(refineMode, smaller, larger)}${refineWork ? ` ${refineLeaveHint}` : ''}` + ? `${refineSaid ?? refineHints(refineMode, smaller, larger)}${refineWork && !refineSaid ? ` ${refineLeaveHint}` : ''}` : warpStage === 'warp' ? warpAdd === 'line' ? `Drag on the surface to draw a line · Esc discards it · ${orbitHint} orbits` diff --git a/src/components/EditorContextMenu.tsx b/src/components/EditorContextMenu.tsx index 64cd67e..d8172fa 100644 --- a/src/components/EditorContextMenu.tsx +++ b/src/components/EditorContextMenu.tsx @@ -33,6 +33,14 @@ import type { CommandContext, CommandId } from '../core/commands'; import { useEditor } from '../core/store'; import type { EditorContextMenu as MenuLocation } from '../core/store'; import { BrushSettings } from './BrushSettings'; +import { + RefineConstraintItems, + RefinePointItems, + RefineSegmentItems, + refineConstraintTitle, + refinePointTitle, + refineSegmentTitle, +} from './RefinePointMenu'; const icons = { copy: Copy, @@ -78,6 +86,7 @@ function OpenContextMenu({ }) { const state = useEditor(); const brush = location.kind === 'brush'; + const { refinePoint, refineSegment, refineConstraint } = location; const brushTitle = activeBrush(state) === contactBrush ? 'Paint brush settings' : 'Brush settings'; const menu = useRef(null); @@ -184,7 +193,17 @@ function OpenContextMenu({ ref={menu} className={`editor-context-menu ${brush ? 'brush-context-menu' : ''}`} role={brush ? 'dialog' : 'menu'} - aria-label={brush ? brushTitle : 'Component actions'} + aria-label={ + brush + ? brushTitle + : refinePoint + ? 'Guide point actions' + : refineSegment + ? 'Guide segment actions' + : refineConstraint + ? 'Constraint actions' + : 'Component actions' + } tabIndex={-1} style={position} onContextMenu={(event) => event.preventDefault()} @@ -269,6 +288,29 @@ function OpenContextMenu({ Done + ) : refinePoint ? ( + <> +
+ {refinePointTitle(refinePoint)} + Guide point actions +
+ + + ) : refineSegment ? ( + <> +
+ {refineSegmentTitle(refineSegment)} + Guide segment actions +
+ + + ) : refineConstraint ? ( + <> +
+ {refineConstraintTitle(refineConstraint)} +
+ + ) : ( <>
diff --git a/src/components/RefineControls.tsx b/src/components/RefineControls.tsx index c014c3b..754da3f 100644 --- a/src/components/RefineControls.tsx +++ b/src/components/RefineControls.tsx @@ -2,10 +2,12 @@ import { useId, useMemo, useState, type ReactNode } from 'react'; import { useShallow } from 'zustand/react/shallow'; import { LoaderCircle, TriangleAlert } from 'lucide-react'; import { isTaskActive, useActivity } from '../core/activity'; -import type { EdgeInput, EdgeSolve } from '../core/refine-edge'; +import type { EdgeInput, EdgePosition, EdgeSolve } from '../core/refine-edge'; import type { RegionInput, RegionSolve, RegionShape, Treatment } from '../core/refine-region'; import { refineDraftLimit, + refineFailure, + refinePickingPrompt, refineEdited, refinePointRemovable, refineSolved, @@ -40,6 +42,7 @@ const editor = () => useEditor.getState(); /** What the panel shows of the session: everything but the painted triangles. */ const panelView = (refine: RefineSession | null) => refine && { + failure: refineFailure(refine), partId: refine.partId, stage: refine.stage, model: refine.model, @@ -49,6 +52,8 @@ const panelView = (refine: RefineSession | null) => features: refine.features, selected: refine.selected, chosenPoint: refine.chosenPoint, + planes: refine.planes, + picking: refine.picking, edge: refine.edge, region: refine.region, brush: refine.brush, @@ -267,6 +272,37 @@ function MillimetreField({ ); } +/** A number field in degrees on one row. */ +function DegreeField({ + label, + value, + mixed, + owned, + onSet, +}: { + label: string; + value: number; + mixed: boolean; + owned: () => boolean; + onSet: (value: number) => void; +}) { + return ( + + ); +} + /** A labelled choice of a few options; none is chosen when the targets differ. */ function Choice({ label, @@ -348,6 +384,12 @@ function EdgeControls({ view, targets, owned }: ModeProps) { settingOf(inputs, (i) => i.ends?.[k] ?? null, view.edge.ends[k]), ); const closed = inputs.length > 0 && inputs.every((i) => i.closed); + const position = settingOf(inputs, (i) => i.position ?? 'along', view.edge.position); + const fits = inputs.length ? inputs.map((i) => i.fit ?? null) : [view.edge.fit]; + const path = settingOf(inputs, (i) => !!i.path, view.edge.path); + const walls = inputs.length ? inputs.map((i) => i.wallAngle ?? null) : [view.edge.wallAngle]; + const planed = inputs.filter((i) => i.plane); + const usePlane = settingOf(planed, (i) => i.usePlane !== false, view.edge.usePlane); const solveOf = (f: RefineFeature) => refineSolved(editor().refine!, f) as EdgeSolve | null; const solve = targets.length === 1 ? solveOf(targets[0]) : null; // Each target keeps its own other end. @@ -391,8 +433,47 @@ function EdgeControls({ view, targets, owned }: ModeProps) { .map(({ id, feature, edited }) => ({ id, feature, edited })); return () => editor().restoreRefineFeatures(saved); }; + const planeIds = inputs.length + ? shared( + inputs.map((i) => i.plane?.id ?? 'none'), + 'none', + ) + : { value: view.edge.plane ?? 'none', mixed: false }; + const choosePlane = (choice: string) => { + if (choice === 'points' || choice === 'face') + return editor().startRefinePicking({ + kind: 'plane', + from: choice, + points: [], + lock: targets.length === 1 ? targets[0].id : null, + }); + editor().setRefinePlane(choice === 'none' ? null : choice); + }; return ( <> + +
+ Plane + +
How loosely the edge follows the guide's line, arc or spline, from no change to fully on it.

+ editor().setRefineEdge({ position })} + /> +

Where the guide lies on the rounded edge of the scan.

+ { + editor().setRefineEdge({ fit: 0 }); + return false; + }} + onSet={(fit) => editor().setRefineEdge({ fit })} + > + {(fit, mixed, set) => ( + + )} + +

+ How far the edge may move off the guide to fit the scan. Automatic reaches as far as the + rounding. +

+ editor().setRefineEdge({ path })} + /> + {planed.length ? ( + editor().setRefineEdge({ usePlane })} + /> + ) : null} + { + editor().setRefineEdge({ wallAngle: 90 }); + return false; + }} + onSet={(wallAngle) => editor().setRefineEdge({ wallAngle })} + > + {(angle, mixed, set) => ( + + )} + ) { + const picking = view.picking; + if (!picking) return null; + return ( +
+

+ {refinePickingPrompt(picking)} +

+ +
+ ); +} + /** Removes the chosen guide point, when the guide stays complete without it. */ function RemovePoint({ view }: Pick) { return ( @@ -497,6 +651,13 @@ function RemovePoint({ view }: Pick) { } const widthRange = { min: 0.1, max: 5 }; +const angleRange = { min: 10, max: 170 }; +const positionChoices: { id: EdgePosition; label: string }[] = [ + { id: 'corner', label: 'Corner' }, + { id: 'top', label: 'Top' }, + { id: 'bottom', label: 'Bottom' }, + { id: 'along', label: 'Along' }, +]; const reachRange = { min: 0.3, max: 5 }; const shapes: { id: RegionShape; label: string }[] = [ @@ -905,6 +1066,7 @@ export function RefineControls() { )}

{counts} + {view.failure && {view.failure}}

{view.folds ? (

diff --git a/src/components/RefineOverlay.tsx b/src/components/RefineOverlay.tsx index b40c3d7..3b81b72 100644 --- a/src/components/RefineOverlay.tsx +++ b/src/components/RefineOverlay.tsx @@ -33,6 +33,7 @@ import { import { contactColors } from '../core/surfaces'; import type { Part } from '../core/types'; import { refineCurves, refineHandles, type RefineHandle } from './RefinePointer'; +import { RefineSketch } from './RefineSketch'; import { warpRegionColor } from './SurfacePainter'; import { surfacePoints } from './surface-points'; import { closedColor, foldColor } from './WarpOverlay'; @@ -583,7 +584,7 @@ const Handles = memo(function Handles({ * accepted, dashed while pending), the selected edge's band, painted triangles, pending regions * with the selected one's kept detail outlined, and triangles an accept folded or could not cut. */ -export function RefineOverlay() { +export function RefineOverlay({ onPress }: { onPress: () => void }) { const refine = useEditor((s) => s.tool === 'refine' && s.refine?.stage === 'ready' ? s.refine : null, ); @@ -664,6 +665,7 @@ export function RefineOverlay() { chosenPoint={refine.chosenPoint} model={refine.model} /> + ); } diff --git a/src/components/RefinePointMenu.tsx b/src/components/RefinePointMenu.tsx new file mode 100644 index 0000000..f94890c --- /dev/null +++ b/src/components/RefinePointMenu.tsx @@ -0,0 +1,380 @@ +import type { ReactNode } from 'react'; +import { + AlignHorizontalJustifyCenter, + AlignVerticalJustifyCenter, + Grid2x2, + Grid2x2Plus, + LockKeyhole, + Slash, + Trash2, + UnlockKeyhole, +} from 'lucide-react'; +import { + type PairKind, + constraintLabels, + constraintRefusal, + pairFits, + pairKinds, + samePoint, +} from '../core/refine-constraints'; +import type { EdgeInput } from '../core/refine-edge'; +import { useEditor, type RefinePointSelection } from '../core/store'; + +const editor = () => useEditor.getState(); + +/** The guide and point a point menu acts on, while they still exist. */ +function pointOf(target: RefinePointSelection) { + const refine = editor().refine; + const feature = refine?.features.find((f) => f.id === target.feature); + if (!refine || feature?.state !== 'pending' || feature.feature.type !== 'edge') return null; + const input = feature.feature.input; + const point = input.segments[target.segment]?.points[target.index]; + return point ? { refine, input, point } : null; +} + +/** The menu's heading: which point of which guide. */ +export function refinePointTitle(target: RefinePointSelection) { + const found = pointOf(target); + if (!found) return 'Guide point'; + const lock = found.point.lock; + const plane = found.input.plane?.name; + const held = lock?.kind === 'fixed' ? 'fixed' : lock?.kind === 'line' ? 'on a line' : null; + return ['Guide point', plane ? `on ${plane}` : null, held].filter(Boolean).join(', '); +} + +/** One action of the point menu. */ +function Item({ + label, + icon, + disabled = false, + hint, + danger = false, + onSelect, + close, +}: { + label: string; + icon: ReactNode; + disabled?: boolean; + /** Why it is disabled, shown as its tooltip. */ + hint?: string; + danger?: boolean; + onSelect: () => void; + close: (restore?: boolean) => void; +}) { + return ( + + ); +} + +/** A labelled group of the point menu, after a separator unless it is the first. */ +function Group({ + label, + first = false, + children, +}: { + label: string; + first?: boolean; + children: ReactNode; +}) { + return ( +

+ {first ? null :
} + + {children} +
+ ); +} + +/** The point menu's actions: Lock, then Delete. */ +export function RefinePointItems({ + target, + close, +}: { + target: RefinePointSelection; + close: (restore?: boolean) => void; +}) { + const found = pointOf(target); + if (!found) return null; + const { refine, input, point } = found; + const { feature, segment, index } = target; + const lock = point.lock; + const item = { close }; + return ( + <> + + {refine.planes.map((plane) => ( + } + disabled={input.plane?.id === plane.id} + hint="The guide is on this plane." + onSelect={() => editor().setRefineGuidePlane(feature, plane.id)} + /> + ))} + } + onSelect={() => + editor().startRefinePicking({ + kind: 'plane', + from: 'points', + points: [], + lock: feature, + }) + } + /> + } + onSelect={() => editor().startRefinePicking({ kind: 'line', point: target, points: [] })} + /> + } + disabled={lock?.kind === 'fixed'} + hint="This point is fixed." + onSelect={() => editor().lockRefinePoint(feature, segment, index, { kind: 'fixed' })} + /> + } + disabled={!lock} + hint="This point has no lock of its own." + onSelect={() => editor().lockRefinePoint(feature, segment, index, null)} + /> + + + {(['horizontal', 'vertical'] as const).map((axis) => ( + + ) : ( + + ) + } + disabled={!input.plane} + hint="Align works on a guide on a sketch plane. Lock the guide to a plane first." + onSelect={() => + editor().startRefinePicking({ kind: 'align', axis, point: target, points: [] }) + } + /> + ))} + {input.plane ? null : ( +

Lock the guide to a plane to align its points.

+ )} +
+ + + + + } + danger + onSelect={() => editor().removeRefinePoint(feature, segment, index)} + /> + + + ); +} + +/** The two segments that meet at a point, or null at an open end or an arc's middle. */ +function meeting(input: EdgeInput, target: RefinePointSelection): [number, number] | null { + const point = input.segments[target.segment]?.points[target.index]; + if (!point) return null; + const found = input.segments.flatMap((s, i) => + s.points.some((p, k) => samePoint(p, point) && (k === 0 || k === s.points.length - 1)) + ? [i] + : [], + ); + return found.length === 2 ? [found[0], found[1]] : null; +} + +/** + * The segment constraints between two segments, each applied at once; or, with `pick`, each + * waiting for a click on the other segment. + */ +function PairItems({ + input, + feature, + pair, + pick, + close, +}: { + input: EdgeInput; + feature: string; + pair: [number, number] | null; + pick?: number; + close: (restore?: boolean) => void; +}) { + const kinds = + pick === undefined + ? pairKinds + : pairKinds.filter((kind) => + input.segments.some( + (s, i) => i !== pick && pairFits(kind, input.segments[pick].kind, s.kind), + ), + ); + const reason = (kind: PairKind) => { + if (!input.plane) + return 'Constraints work on a guide on a sketch plane. Lock the guide to a plane first.'; + if (pick !== undefined) return null; + if (!pair) return 'Two segments must meet at this point.'; + return constraintRefusal(input, { id: '', kind, segments: pair }); + }; + return ( + <> + {kinds.map((kind) => { + const why = reason(kind); + return ( + } + disabled={!!why} + hint={why ?? undefined} + onSelect={() => + pick === undefined + ? editor().addRefineConstraint(feature, { kind, segments: pair! }) + : editor().startRefinePicking({ + kind: 'constrain', + constraint: kind, + feature, + segment: pick, + points: [], + }) + } + /> + ); + })} + + ); +} + +/** The symbol a constraint is drawn with, in menus and beside the guide. */ +export const constraintGlyphs: Record = { + parallel: '∥', + perpendicular: '⊥', + collinear: '⋯', + equal: '=', + tangent: '⌒', + concentric: '◎', + horizontal: 'H', + vertical: 'V', + align: '⇹', +}; + +function ConstraintGlyph({ kind }: { kind: keyof typeof constraintLabels }) { + return ( + + ); +} + +/** The guide a segment menu acts on, while it still exists. */ +function guideOf(feature: string) { + const found = editor().refine?.features.find((f) => f.id === feature); + return found?.state === 'pending' && found.feature.type === 'edge' ? found.feature.input : null; +} + +/** A segment menu's heading. */ +export function refineSegmentTitle(target: { feature: string; segment: number }) { + const kind = guideOf(target.feature)?.segments[target.segment]?.kind; + return kind ? `Guide ${kind}` : 'Guide segment'; +} + +/** A segment's menu: Constrain, then the other segment's click; Horizontal and Vertical at once. */ +export function RefineSegmentItems({ + target, + close, +}: { + target: { feature: string; segment: number }; + close: (restore?: boolean) => void; +}) { + const input = guideOf(target.feature); + const segment = input?.segments[target.segment]; + if (!input || !segment) return null; + const line = segment.kind === 'line'; + return ( + + + {(['horizontal', 'vertical'] as const).map((kind) => ( + } + disabled={!input.plane || !line} + hint={ + input.plane + ? 'Only a line can be horizontal or vertical.' + : 'Constraints work on a guide on a sketch plane. Lock the guide to a plane first.' + } + onSelect={() => + editor().addRefineConstraint(target.feature, { kind, segments: [target.segment] }) + } + /> + ))} + + ); +} + +/** A constraint's menu: Delete. */ +export function RefineConstraintItems({ + target, + close, +}: { + target: { feature: string; id: string }; + close: (restore?: boolean) => void; +}) { + return ( + } + danger + onSelect={() => editor().removeRefineConstraint(target.feature, target.id)} + /> + ); +} + +/** A constraint menu's heading. */ +export function refineConstraintTitle(target: { feature: string; id: string }) { + const constraint = guideOf(target.feature)?.constraints?.find((c) => c.id === target.id); + return constraint ? `${constraintLabels[constraint.kind]} constraint` : 'Constraint'; +} diff --git a/src/components/RefinePointer.tsx b/src/components/RefinePointer.tsx index 90c9718..3a4869d 100644 --- a/src/components/RefinePointer.tsx +++ b/src/components/RefinePointer.tsx @@ -18,11 +18,14 @@ import { import { brushingRefine, paintingRefine, + refineDrawingPlane, useEditor, type RefineMode, type RefineSession, } from '../core/store'; import type { GuidePoint } from '../core/refine-band'; +import { drawnCurve } from '../core/refine-curve'; +import { lineNearRay, pointAt, rayOnPlane } from '../core/refine-sketch'; import type { RefineMesh } from '../core/refine-mesh'; import type { RefineBrush } from '../core/refine-brush'; import { prepareEditedForPicking } from '../core/bvh'; @@ -759,6 +762,45 @@ export function RefinePointerController({ pressed }: { pressed: () => boolean }) ); }; + /** + * The segment of a guide drawn as handles whose drawn line passes within reach of a client + * position on screen, nearest first; null when none does. + */ + const segmentAt = (refine: RefineSession, x: number, y: number) => { + const { camera } = get(); + const rect = canvas().getBoundingClientRect(); + const ids = new Set(refineHandles(refine).map((h) => h.feature)); + type Found = { feature: string; segment: number }; + let best = null as Found | null, + nearest = proposalPick * proposalPick; + for (const f of refine.features) { + if (!ids.has(f.id) || f.feature.type !== 'edge') continue; + f.feature.input.segments.forEach((segment, index) => { + if (segment.points.length < 2) return; + const curve = drawnCurve( + segment.kind, + segment.points.flatMap((p) => p.position), + refine.model?.step ?? 0.05, + 64, + ); + let previous: readonly [number, number] | null = null; + for (let i = 0; i < curve.points.length; i += 3) { + const spot = toScreen( + camera, + rect, + ...(curve.points.subarray(i, i + 3) as unknown as [number, number, number]), + ); + if (spot && previous) { + const [d] = segmentDistance(x, y, previous[0], previous[1], spot[0], spot[1]); + if (d <= nearest) [nearest, best] = [d, { feature: f.id, segment: index }]; + } + previous = spot; + } + }); + } + return best; + }; + /** The pending edge whose visible drawn curve passes within reach of a client position. */ const proposalAt = (refine: RefineSession, x: number, y: number) => { const { camera } = get(); @@ -963,8 +1005,41 @@ export function RefinePointerController({ pressed }: { pressed: () => boolean }) ); }; - /** Moves the dragged point to the model surface under the sample. */ + /** + * Where a point locked to a line, or of a guide on a plane, goes under the sample: the line's + * point nearest the ray, or where the ray meets the plane. Undefined for a free point. + */ + const heldOnRay = (d: HandleDrag): GuidePoint | null | undefined => { + const refine = useEditor.getState().refine; + const feature = refine?.features.find((f) => f.id === d.handle.feature)?.feature; + if (!refine?.model || feature?.type !== 'edge') return undefined; + const { lock } = d.current; + const plane = feature.input.plane; + if (lock?.kind !== 'line' && !plane) return undefined; + const { origin, direction } = raycaster.ray; + const o = origin.toArray(), + dir = direction.toArray(); + const position = + lock?.kind === 'line' ? lineNearRay(lock, o, dir) : rayOnPlane(plane!, o, dir); + if (!position) return null; + const point = pointAt(refine.model.mesh, position); + return point && { ...point, ...(lock ? { lock } : {}) }; + }; + + /** Moves the dragged point to the model surface under the sample, or along its lock. */ const dragSample = (d: HandleDrag, live: boolean) => { + if (d.current.lock?.kind === 'fixed') return true; + const held = heldOnRay(d); + if (held !== undefined) { + if (!held) return true; + const { handle } = d; + useEditor + .getState() + .moveRefinePoint(handle.feature, handle.segment, handle.index, held, !d.began); + d.began = true; + d.current = held; + return true; + } const [point, near] = nearPick(() => modelHitOnRay(d.partId)); if (near && live) return false; if (!point) return true; @@ -974,7 +1049,7 @@ export function RefinePointerController({ pressed }: { pressed: () => boolean }) .getState() .moveRefinePoint(handle.feature, handle.segment, handle.index, point, !d.began); d.began = true; - d.current = point; + d.current = { ...point, ...(d.current.lock ? { lock: d.current.lock } : {}) }; return true; }; const dragHandle = (d: HandleDrag, x: number, y: number) => { @@ -1282,6 +1357,8 @@ export function RefinePointerController({ pressed }: { pressed: () => boolean }) }; let pressX: [number, number] = [0, 0]; + /** Where the last primary press went down, for telling a click from a drag. */ + let pressAt: [number, number] = [0, 0]; let unpress: (() => void) | null = null; const clearPress = () => { pressedProposal = null; @@ -1293,6 +1370,7 @@ export function RefinePointerController({ pressed }: { pressed: () => boolean }) const down = (event: PointerEvent) => { clearPress(); cancelledPointer = null; + if (event.button === 0) pressAt = [event.clientX, event.clientY]; if (gesture?.waiting && event.button === 0 && canvas().contains(event.target as Node)) drainSamples(() => true); const state = useEditor.getState(), @@ -1309,7 +1387,9 @@ export function RefinePointerController({ pressed }: { pressed: () => boolean }) event.metaKey || event.altKey || blocked(state) || - !canvas().contains(event.target as Node) + !canvas().contains(event.target as Node) || + // While the session waits for picks, a press on a handle picks it on its click. + refine.picking ) return; const handle = event.shiftKey ? null : handleAt(refine, event.clientX, event.clientY, true); @@ -1353,6 +1433,11 @@ export function RefinePointerController({ pressed }: { pressed: () => boolean }) event.stopImmediatePropagation(); return; } + if (sketchClick(event)) { + event.stopImmediatePropagation(); + clearPress(); + return; + } const id = pressedProposal; clearPress(); const still = Math.hypot(event.clientX - pressX[0], event.clientY - pressX[1]) <= 5; @@ -1371,6 +1456,79 @@ export function RefinePointerController({ pressed }: { pressed: () => boolean }) ); }; + /** + * A click the session's sketching takes: a pick while it waits for picks, on a guide point or + * the part; or, in Edge mode with a guide drawn on a plane, a point where the ray meets the + * plane, also off the part. True when taken. + */ + const sketchClick = (event: MouseEvent) => { + const state = useEditor.getState(), + refine = state.refine; + if ( + event.button !== 0 || + state.tool !== 'refine' || + refine?.stage !== 'ready' || + !refine.model || + blocked(state) || + pressed() || + !canvas().contains(event.target as Node) || + Math.hypot(event.clientX - pressAt[0], event.clientY - pressAt[1]) > clickSlop + ) + return false; + const { clientX: x, clientY: y } = event; + if (refine.picking) { + const handle = handleAt(refine, x, y, false); + const segment = handle ? null : segmentAt(refine, x, y); + aimAt(x, y); + const point = handle ? handle.point : modelHitOnRay(refine.partId); + const on = handle + ? { point: { feature: handle.feature, segment: handle.segment, index: handle.index } } + : segment + ? { segment } + : {}; + if (point || segment) state.pickRefine(point ?? { triangle: 0, position: [0, 0, 0] }, on); + return true; + } + const plane = refineDrawingPlane(refine); + if (!plane || handleAt(refine, x, y, true)) return false; + aimAt(x, y); + const { origin, direction } = raycaster.ray; + const at = rayOnPlane(plane, origin.toArray(), direction.toArray()); + const point = at && pointAt(refine.model.mesh, at); + if (point) state.addRefinePoint(point); + return true; + }; + + /** A right-click on a guide point opens its menu. */ + const menu = (event: MouseEvent) => { + const state = useEditor.getState(), + refine = state.refine; + if ( + gesture || + state.tool !== 'refine' || + refine?.stage !== 'ready' || + refine.mode !== 'edge' || + blocked(state) || + !canvas().contains(event.target as Node) || + !ready() + ) + return; + const handle = handleAt(refine, event.clientX, event.clientY, false); + const line = handle ? null : segmentAt(refine, event.clientX, event.clientY); + if (!handle && !line) return; + event.preventDefault(); + event.stopImmediatePropagation(); + const feature = handle?.feature ?? line!.feature; + if (!refine.selected.includes(feature)) state.selectRefine([feature]); + state.openContextMenu({ + x: event.clientX, + y: event.clientY, + ...(handle + ? { refinePoint: { feature, segment: handle.segment, index: handle.index } } + : { refineSegment: line! }), + }); + }; + // The cursor: busy over the part while it has no index and one is being built, a pointer over a // handle or proposal. let shown: string | null = null, @@ -1443,6 +1601,7 @@ export function RefinePointerController({ pressed }: { pressed: () => boolean }) window.addEventListener('pointerdown', down, true); window.addEventListener('pointerup', released, true); window.addEventListener('click', click, true); + window.addEventListener('contextmenu', menu, true); window.addEventListener('pointermove', hover); return () => { discard(); @@ -1457,6 +1616,7 @@ export function RefinePointerController({ pressed }: { pressed: () => boolean }) window.removeEventListener('pointerdown', down, true); window.removeEventListener('pointerup', released, true); window.removeEventListener('click', click, true); + window.removeEventListener('contextmenu', menu, true); window.removeEventListener('pointermove', hover); if (shown && document.body.style.cursor === shown) document.body.style.cursor = before; }; diff --git a/src/components/RefineSketch.tsx b/src/components/RefineSketch.tsx new file mode 100644 index 0000000..91fa9a2 --- /dev/null +++ b/src/components/RefineSketch.tsx @@ -0,0 +1,348 @@ +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import { useThree } from '@react-three/fiber'; +import { Html } from '@react-three/drei'; +import { + BufferAttribute, + BufferGeometry, + LineBasicMaterial, + LineSegments, + Matrix4, + Object3D, + Points, + PointsMaterial, + Vector3, +} from 'three'; +import type { EdgeInput } from '../core/refine-edge'; +import { pointAt, planeCoordinates, planePoint, type SketchPlane } from '../core/refine-sketch'; +import { chosenRefinePoint, useEditor, type RefineSession } from '../core/store'; +import { ManagedTransformControls } from './ManagedTransformControls'; +import { constraintLabels, type GuideConstraint } from '../core/refine-constraints'; +import { constraintGlyphs } from './RefinePointMenu'; +import { pointAccent } from './WarpStroke'; + +const uColor = '#e5484d'; +const vColor = '#46a758'; +const gridColor = '#a4aab2'; +/** Grid lines across the square each way. */ +const gridLines = 8; + +/** + * The square of `plane` round a guide's points, with margin, as (u, v) bounds; a guide of one point + * takes a square of 2 mm. + */ +function squareOf(plane: SketchPlane, input: EdgeInput) { + const uv = input.segments.flatMap((s) => + s.points.map((p) => planeCoordinates(plane, p.position)), + ); + const [u0, u1] = [Math.min(...uv.map((p) => p[0])), Math.max(...uv.map((p) => p[0]))]; + const [v0, v1] = [Math.min(...uv.map((p) => p[1])), Math.max(...uv.map((p) => p[1]))]; + const size = Math.max(u1 - u0, v1 - v0, 1) * 1.3; + const [cu, cv] = [(u0 + u1) / 2, (v0 + v1) / 2]; + return { u0: cu - size / 2, u1: cu + size / 2, v0: cv - size / 2, v1: cv + size / 2, cu, cv }; +} + +/** A faint grid square of a selected guide's plane round its points, with its u and v axes. */ +function PlaneGrid({ plane, input }: { plane: SketchPlane; input: EdgeInput }) { + const invalidate = useThree((s) => s.invalidate); + const shape = useMemo(() => { + const { u0, u1, v0, v1, cu, cv } = squareOf(plane, input); + const grid: number[] = []; + for (let k = 0; k <= gridLines; k++) { + const u = u0 + ((u1 - u0) * k) / gridLines, + v = v0 + ((v1 - v0) * k) / gridLines; + grid.push(...planePoint(plane, u, v0), ...planePoint(plane, u, v1)); + grid.push(...planePoint(plane, u0, v), ...planePoint(plane, u1, v)); + } + const line = (points: number[], color: string, opacity: number) => { + const geometry = new BufferGeometry().setAttribute( + 'position', + new BufferAttribute(Float32Array.from(points), 3), + ); + const material = new LineBasicMaterial({ + color, + transparent: true, + opacity, + depthTest: false, + }); + const segments = new LineSegments(geometry, material); + segments.renderOrder = 5; + segments.raycast = () => {}; + return segments; + }; + const reach = (u1 - u0) / 2; + return [ + line(grid, gridColor, 0.25), + line([...planePoint(plane, cu, cv), ...planePoint(plane, cu + reach, cv)], uColor, 0.9), + line([...planePoint(plane, cu, cv), ...planePoint(plane, cu, cv + reach)], vColor, 0.9), + ]; + }, [plane, input]); + useEffect(() => { + invalidate(); + return () => + shape.forEach((line) => { + line.geometry.dispose(); + (line.material as LineBasicMaterial).dispose(); + }); + }, [shape, invalidate]); + return ( + <> + {shape.map((line, i) => ( + + ))} + + ); +} + +/** Where a constraint's icon sits: beside its first segment's middle, or its first point. */ +function anchorOf(input: EdgeInput, constraint: GuideConstraint): number[] | null { + if (constraint.kind === 'align') { + const { segment, index } = constraint.points[0]; + return input.segments[segment]?.points[index]?.position ?? null; + } + const points = input.segments[constraint.segments[0]]?.points; + if (!points?.length) return null; + if (points.length % 2) return points[points.length >> 1].position; + const [a, b] = [points[points.length / 2 - 1].position, points[points.length / 2].position]; + return [0, 1, 2].map((k) => (a[k] + b[k]) / 2); +} + +/** + * A small icon beside each constraint of a selected guide, and each fixed point, as a sketch shows + * them; a right-click on one opens its menu, to delete it. + */ +function ConstraintIcons({ feature, input }: { feature: string; input: EdgeInput }) { + const groups = new Map(); + for (const constraint of input.constraints ?? []) { + const at = anchorOf(input, constraint); + if (!at) continue; + const key = at.join(' '); + const group = groups.get(key) ?? { at, items: [] }; + group.items.push(constraint); + groups.set(key, group); + } + const fixed = input.segments.flatMap((s, segment) => + s.points.flatMap((p, index) => + p.lock?.kind === 'fixed' ? [{ at: p.position, segment, index }] : [], + ), + ); + const open = (event: React.MouseEvent, menu: object) => { + event.preventDefault(); + event.stopPropagation(); + useEditor.getState().openContextMenu({ x: event.clientX, y: event.clientY, ...menu }); + }; + return ( + <> + {[...groups.values()].map(({ at, items }) => ( + +
+ {items.map((c) => ( + open(event, { refineConstraint: { feature, id: c.id } })} + > + {constraintGlyphs[c.kind]} + + ))} +
+ + ))} + {fixed.map(({ at, segment, index }) => ( + +
+ open(event, { refinePoint: { feature, segment, index } })} + > + ⚓ + +
+ + ))} + + ); +} + +/** The points picked so far for a new plane or a line lock. */ +function Picked({ points }: { points: number[][] }) { + const shape = useMemo(() => { + const geometry = new BufferGeometry().setAttribute( + 'position', + new BufferAttribute(Float32Array.from(points.flat()), 3), + ); + const material = new PointsMaterial({ + color: pointAccent, + size: 9, + sizeAttenuation: false, + depthTest: false, + }); + const dots = new Points(geometry, material); + dots.renderOrder = 9; + dots.raycast = () => {}; + return dots; + }, [points]); + useEffect( + () => () => { + shape.geometry.dispose(); + (shape.material as PointsMaterial).dispose(); + }, + [shape], + ); + return ; +} + +/** Each selected guide's plane, and the picks under way. */ +export function RefineSketch({ refine, onPress }: { refine: RefineSession; onPress: () => void }) { + const planes = refine.features.flatMap((f) => + f.state === 'pending' && + f.feature.type === 'edge' && + f.feature.input.plane && + refine.selected.includes(f.id) + ? [{ id: f.id, input: f.feature.input, plane: f.feature.input.plane }] + : [], + ); + return ( + <> + {planes.map(({ id, input, plane }) => ( + + ))} + {planes.map(({ id, input }) => ( + + ))} + {refine.picking?.points.length ? : null} + + + ); +} + +/** + * The move widget on the chosen point: arrows along the world axes for a free point, along the + * plane's u and v with its square for a point of a guide on a plane, along the line for a point + * locked to one, none for a fixed point. One drag is one undo step; Escape puts the point back. + */ +function PointWidget({ refine, onPress }: { refine: RefineSession; onPress: () => void }) { + const chosen = chosenRefinePoint(refine); + const feature = chosen && refine.features.find((f) => f.id === chosen.feature); + const input = feature?.feature.type === 'edge' ? feature.feature.input : null; + const point = chosen && input?.segments[chosen.segment]?.points[chosen.index]; + if (!chosen || !input || !point || point.lock?.kind === 'fixed' || refine.picking) return null; + return ( + + ); +} + +function PointWidgetFor({ + target, + position, + plane, + line, + onPress, +}: { + target: { feature: string; segment: number; index: number }; + position: number[]; + plane: SketchPlane | null; + line: number[] | null; + onPress: () => void; +}) { + const proxy = useMemo(() => new Object3D(), []); + const drag = useRef<{ began: boolean } | null>(null); + const [version, setVersion] = useState(0); + const getRoot = useThree((s) => s.get), + invalidate = useThree((s) => s.invalidate); + // The widget's frame: x along u and y along v on a plane, x along a line, else the world's. + const quaternion = useMemo(() => { + const frame = new Matrix4(); + if (line) { + const x = new Vector3(...line).normalize(); + const helper = Math.abs(x.x) < 0.9 ? new Vector3(1, 0, 0) : new Vector3(0, 1, 0); + const y = new Vector3().crossVectors(x, helper).normalize(); + frame.makeBasis(x, y, new Vector3().crossVectors(x, y)); + } else if (plane) + frame.makeBasis( + new Vector3(...plane.u), + new Vector3(...plane.v), + new Vector3(...plane.normal), + ); + return new Object3D().quaternion.setFromRotationMatrix(frame).clone(); + }, [plane, line]); + const finish = useCallback(() => { + if (!drag.current) return; + drag.current = null; + useEditor.getState().endRefineDrag(); + const controls = getRoot().controls; + if (controls && 'enabled' in controls) controls.enabled = true; + setVersion((v) => v + 1); + invalidate(); + }, [getRoot, invalidate]); + useEffect(() => { + // Escape during a drag puts the point back where the drag found it. + const key = (event: KeyboardEvent) => { + if (event.key !== 'Escape' || !drag.current) return; + event.preventDefault(); + event.stopImmediatePropagation(); + useEditor.getState().cancelRefineDrag(); + finish(); + }; + window.addEventListener('keydown', key, true); + window.addEventListener('blur', finish); + return () => { + window.removeEventListener('keydown', key, true); + window.removeEventListener('blur', finish); + }; + }, [finish]); + useLayoutEffect(() => { + if (drag.current) return; + proxy.position.fromArray(position); + proxy.quaternion.copy(quaternion); + proxy.updateMatrixWorld(true); + invalidate(); + }, [position, quaternion, proxy, version, invalidate]); + return ( + <> + + { + onPress(); + useEditor.getState().beginRefineDrag(); + drag.current = { began: false }; + }} + onObjectChange={() => { + const current = drag.current; + const model = useEditor.getState().refine?.model; + if (!current || !model) return; + const at = proxy.position.toArray(); + const point = pointAt(model.mesh, at); + if (!point) return; + useEditor + .getState() + .moveRefinePoint(target.feature, target.segment, target.index, point, !current.began); + current.began = true; + }} + /> + + ); +} diff --git a/src/components/Viewport.tsx b/src/components/Viewport.tsx index 7a5658f..0efb86b 100644 --- a/src/components/Viewport.tsx +++ b/src/components/Viewport.tsx @@ -1236,7 +1236,11 @@ function Scene({ {refineSession ? ( - + { + gizmoPressed = true; + }} + /> ) : null} diff --git a/src/core/refine-band.ts b/src/core/refine-band.ts index 22978cf..3722e9e 100644 --- a/src/core/refine-band.ts +++ b/src/core/refine-band.ts @@ -7,11 +7,14 @@ import { } from './refine-curve'; import { type Shape, type ShapeKind, fitAuto, fitShape, shapeDistance } from './refine-fit'; import { type RefineMesh, type RefineTopology, vertexNormal, weldedCorner } from './refine-mesh'; +import type { PointLock } from './refine-sketch'; import type { Vec3 } from './types'; export interface GuidePoint { triangle: number; position: Vec3; + /** How the user locked the point; the solve never reads it. */ + lock?: PointLock; } export const enum BandZone { Soft = 0, @@ -133,7 +136,7 @@ const fitPoints = 1024; /** Robust scale of a residual per unit of median absolute residual. */ const madScale = 1.4826; /** Widest width `estimateWidth` returns, mm, unless the edge cannot be read within it. */ -const widestEstimate = 1; +export const widestEstimate = 1; const unset = -1; /** Min-heap of (distance, index) pairs on typed arrays that grow as needed. */ @@ -229,7 +232,7 @@ const length3 = (p: Float64Array, a: number, b: number) => Math.hypot(p[a * 3] - p[b * 3], p[a * 3 + 1] - p[b * 3 + 1], p[a * 3 + 2] - p[b * 3 + 2]); /** Mean length of the edges at the corners of the clicked triangles. */ -function localEdge(mesh: RefineMesh, topology: RefineTopology, points: GuidePoint[]) { +export function localEdge(mesh: RefineMesh, topology: RefineTopology, points: GuidePoint[]) { const { neighbourStart, neighbours } = topology; let sum = 0, count = 0; @@ -371,6 +374,7 @@ function gather( points: GuidePoint[], widthFor: (edge: number) => number, noise: number, + limit?: { curve: EdgeCurve; width: number }, ) { const { position } = mesh; const { neighbourStart, neighbours } = topology; @@ -383,6 +387,7 @@ function gather( segment: number[] = [], open: boolean[] = [], seed: boolean[] = []; + const permitted: boolean[] = []; const p = drawn.points, last = p.length / 3 - 1; const startTangent = new Float64Array(3), @@ -418,6 +423,10 @@ function gather( 0; inside = !before && !after; } + if (limit) { + closestOnCurve(limit.curve, x, y, z, at); + permitted.push(Math.hypot(x - at[0], y - at[1], z - at[2]) <= limit.width); + } const k = welded.length; slots.set(v, k); welded.push(v); @@ -435,7 +444,7 @@ function gather( for (const point of points) for (const corner of [0, 1, 2] as const) { const k = measure(weldedCorner(mesh, point.triangle, corner), unset); - if (!seed[k]) { + if (!seed[k] && (!limit || permitted[k])) { seed[k] = true; queue.push(k); } @@ -464,7 +473,13 @@ function gather( for (let j = neighbourStart[v]; j < neighbourStart[v + 1]; j++) { const k = measure(neighbours[j], segment[queue[q]]); const reach = ownEdge(neighbours[j]); - if (seed[k] || distance[k] >= reach + 3 * noise || lateral(k) >= reach) continue; + if ( + (limit && !permitted[k]) || + seed[k] || + distance[k] >= reach + 3 * noise || + lateral(k) >= reach + ) + continue; seed[k] = true; queue.push(k); } @@ -490,6 +505,7 @@ function gather( const v = welded[k]; for (let j = neighbourStart[v]; j < neighbourStart[v + 1]; j++) { const w = measure(neighbours[j], segment[k]); + if (limit && !permitted[w]) continue; if (!seed[w] && (distance[w] > width || !open[w])) continue; const d = gOf(k) + length3(position, v, welded[w]); if (d > width) continue; @@ -1146,6 +1162,7 @@ function classifyOriented( width: number | null, noise: number, away = 0, + widthEdge?: EdgeCurve, ) { const clicked = localEdge(mesh, topology, points); if (points.length < 2 || !(clicked > 0)) return null; @@ -1177,6 +1194,7 @@ function classifyOriented( reachOf(edge) + seedStart * edge + spanOf(edge), ), noise, + widthEdge && width !== null ? { curve: widthEdge, width } : undefined, ); const { vertices, edge } = band; const count = vertices.length; @@ -1727,11 +1745,11 @@ function classifyOriented( // cap past `gathered` is held to it, since vertices within the cap of the solved edge may lie // outside the gather. const result = (cap: number): EdgeBand | null => { - const width = Math.min(cap, gathered); + const width = Math.min(cap, widthEdge ? band.width : gathered); const keep: number[] = []; const counts = [0, 0]; for (let i = 0; i < count; i++) { - if (Math.abs(heldO[i]) > width) continue; + if (!widthEdge && Math.abs(heldO[i]) > width) continue; keep.push(i); if (runZone[i] === BandZone.Left || runZone[i] === BandZone.Right) counts[runZone[i] - 1]++; } @@ -1816,16 +1834,17 @@ function classify( points: GuidePoint[], width: number | null, noise: number, + widthEdge?: EdgeCurve, ) { if (points.length < 2) return null; const backward = drawnBackward(points); const oriented = backward ? [...points].reverse() : points; - let found = classifyOriented(mesh, topology, kind, oriented, width, noise); + let found = classifyOriented(mesh, topology, kind, oriented, width, noise, 0, widthEdge); // Where the solved edge strays past reach of the guide, a band reaching `width` from it there is // gathered once more, as far as the edge strayed. Should it stray further on that reading, the // band holds to what that gather covers. Should that reading show no edge, the first one stands, // and the band holds to what the first gather covers. - if (found && width !== null && width > found.gathered) + if (!widthEdge && found && width !== null && width > found.gathered) found = classifyOriented(mesh, topology, kind, oriented, width, noise, found.strayed) ?? found; if (!found || !backward) return found; return { @@ -1857,7 +1876,10 @@ export function buildBand( width: number, noise: number, known?: BandClassification | null, + widthEdge?: EdgeCurve, ): EdgeBand | null { + if (widthEdge) + return classify(mesh, topology, kind, points, width, noise, widthEdge)?.result(width) ?? null; const found = (known && width <= known.gathered ? known diff --git a/src/core/refine-constraints.ts b/src/core/refine-constraints.ts new file mode 100644 index 0000000..2bdc5f5 --- /dev/null +++ b/src/core/refine-constraints.ts @@ -0,0 +1,350 @@ +import { Matrix, pseudoInverse } from 'ml-matrix'; +import type { GuidePoint } from './refine-band'; +import type { GuideKind } from './refine-curve'; +import { type SketchPlane, planeCoordinates, planePoint } from './refine-sketch'; +import type { Vec3 } from './types'; + +/** Constraints between two segments of a guide. */ +export type PairKind = + 'parallel' | 'perpendicular' | 'collinear' | 'equal' | 'tangent' | 'concentric'; +/** Constraints on one line of a guide. */ +export type LineKind = 'horizontal' | 'vertical'; +/** A point of a guide, by segment and index; a point two segments share is either. */ +export interface PointRef { + segment: number; + index: number; +} +/** + * A constraint of a guide on a sketch plane, solved in the plane's (u, v): between two segments; + * on one line, along u (horizontal) or v (vertical); or a point level with another, its v taken + * (horizontal) or its u (vertical). A fixed point is the point's own lock. + */ +export type GuideConstraint = + | { id: string; kind: PairKind; segments: [number, number] } + | { id: string; kind: LineKind; segments: [number] } + | { id: string; kind: 'align'; axis: LineKind; points: [PointRef, PointRef] }; + +export const pairKinds: PairKind[] = [ + 'parallel', + 'perpendicular', + 'collinear', + 'equal', + 'tangent', + 'concentric', +]; +export const constraintLabels: Record = { + parallel: 'Parallel', + perpendicular: 'Perpendicular', + collinear: 'Collinear', + equal: 'Equal', + tangent: 'Tangent', + concentric: 'Concentric', + horizontal: 'Horizontal', + vertical: 'Vertical', + align: 'Align', +}; + +/** The most any constraint may miss by, mm, for a solve to count. */ +export const constraintTolerance = 1e-6; +/** Weight of the moved point's coordinates against the others' in the least change. */ +const movedWeight = 1e4; +const iterations = 200; + +/** A guide's points and segments as a constraint solve reads them. */ +export interface GuideShape { + segments: { kind: GuideKind; points: GuidePoint[] }[]; + plane?: SketchPlane | null; + constraints?: GuideConstraint[]; +} + +/** Whether two guide points are one: the same triangle and position. */ +export const samePoint = (a: GuidePoint, b: GuidePoint) => + a.triangle === b.triangle && a.position.every((x, k) => x === b.position[k]); + +/** Whether a pair constraint applies to two segments of these kinds. */ +export function pairFits(kind: PairKind, a: GuideKind, b: GuideKind) { + const lines = a === 'line' && b === 'line', + arcs = a === 'arc' && b === 'arc'; + switch (kind) { + case 'parallel': + case 'perpendicular': + case 'collinear': + return lines; + case 'equal': + return lines || arcs; + case 'tangent': + return (a === 'line' && b === 'arc') || (a === 'arc' && b === 'line') || arcs; + case 'concentric': + return arcs; + } +} + +/** The point two segments share, as an index of each, or null. */ +export function sharedPoint(shape: GuideShape, i: number, j: number) { + const [a, b] = [shape.segments[i].points, shape.segments[j].points]; + for (const [p, x] of a.entries()) + for (const [q, y] of b.entries()) if (samePoint(x, y)) return [p, q] as const; + return null; +} + +/** Why a constraint cannot be put on the guide, or null when it can. */ +export function constraintRefusal(shape: GuideShape, constraint: GuideConstraint): string | null { + if (!shape.plane) + return 'Constraints hold on a guide on a sketch plane. Lock the guide to a plane.'; + const kindOf = (i: number) => shape.segments[i]?.kind; + if (constraint.kind === 'align') { + const [p, q] = constraint.points.map((r) => shape.segments[r.segment]?.points[r.index]); + if (!p || !q) return 'Pick a point of the same guide.'; + return samePoint(p, q) ? 'Pick another point to align with.' : null; + } + if (constraint.kind === 'horizontal' || constraint.kind === 'vertical') + return kindOf(constraint.segments[0]) === 'line' + ? null + : 'Only a line can be horizontal or vertical.'; + const [i, j] = constraint.segments as [number, number]; + if (i === j || kindOf(i) === undefined || kindOf(j) === undefined) + return 'Pick another segment of the same guide.'; + if (!pairFits(constraint.kind, kindOf(i)!, kindOf(j)!)) + return `${constraintLabels[constraint.kind]} does not apply to a ${kindOf(i)} and a ${kindOf(j)}.`; + if (constraint.kind === 'tangent' && !sharedPoint(shape, i, j)) + return 'Tangent applies to two segments that meet.'; + return null; +} + +/** Circumcentre and radius of three 2D points; null when they are in a line. */ +function circle2(a: number[], b: number[], c: number[]) { + const d = 2 * (a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1])); + if (!(Math.abs(d) > 1e-12)) return null; + const sq = (p: number[]) => p[0] * p[0] + p[1] * p[1]; + const x = (sq(a) * (b[1] - c[1]) + sq(b) * (c[1] - a[1]) + sq(c) * (a[1] - b[1])) / d; + const y = (sq(a) * (c[0] - b[0]) + sq(b) * (a[0] - c[0]) + sq(c) * (b[0] - a[0])) / d; + return { centre: [x, y], radius: Math.hypot(a[0] - x, a[1] - y) }; +} + +/** What a solve is asked for: a point moved toward a target, and points held heavily in place. */ +export interface SolveRequest { + moved?: { point: GuidePoint; target: Vec3 }; + /** Points that move as little as the moved one; a fixed point never moves. */ + heavy?: GuidePoint[]; +} + +/** + * The guide's points solved so that every constraint, and every point's line lock, holds within + * `constraintTolerance`, in the plane's (u, v): the moved point as near its target as they allow, + * the rest moved as little as possible, fixed points not at all. The new position of each of the + * guide's points, by its index in `points`, or null when the constraints cannot all hold. + */ +export function solveGuide(shape: GuideShape, request: SolveRequest = {}) { + const plane = shape.plane; + const constraints = shape.constraints ?? []; + // Each distinct point once. + const points: GuidePoint[] = []; + const indexOf = (p: GuidePoint) => { + const k = points.findIndex((q) => samePoint(q, p)); + if (k >= 0) return k; + points.push(p); + return points.length - 1; + }; + const ids = shape.segments.map((s) => s.points.map(indexOf)); + const moved = request.moved ? indexOf(request.moved.point) : -1; + const heavy = new Set((request.heavy ?? []).map(indexOf)); + if (!plane) { + if (moved < 0) return points.map((p) => p.position); + return points.map((p, k) => (k === moved ? request.moved!.target : p.position)); + } + const n = points.length; + const start = points.map((p) => planeCoordinates(plane, p.position)); + if (moved >= 0) start[moved] = planeCoordinates(plane, request.moved!.target); + const fixed = points.map((p) => p.lock?.kind === 'fixed'); + // Variables: u and v of every point that is not fixed. + const slot = new Int32Array(n).fill(-1); + let count = 0; + for (let k = 0; k < n; k++) if (!fixed[k]) slot[k] = count++; + const weight = new Float64Array(count * 2).fill(1); + for (let k = 0; k < n; k++) + if (slot[k] >= 0 && (k === moved || heavy.has(k))) + weight[slot[k] * 2] = weight[slot[k] * 2 + 1] = movedWeight; + const coordinates = (x: Float64Array) => + start.map((p, k) => (slot[k] < 0 ? p : [x[slot[k] * 2], x[slot[k] * 2 + 1]])); + const lines = points.map((p) => { + if (p.lock?.kind !== 'line') return null; + const o = planeCoordinates(plane, p.lock.origin); + const e = planeCoordinates(plane, [ + p.lock.origin[0] + p.lock.direction[0], + p.lock.origin[1] + p.lock.direction[1], + p.lock.origin[2] + p.lock.direction[2], + ]); + const d = [e[0] - o[0], e[1] - o[1]]; + const length = Math.hypot(d[0], d[1]); + return length > 1e-12 ? { o, d: [d[0] / length, d[1] / length] } : null; + }); + const constrainedLines = new Set( + constraints.flatMap((c) => + c.kind === 'align' ? [] : c.segments.filter((i) => shape.segments[i].kind === 'line'), + ), + ); + const residuals = (x: Float64Array) => { + const p = coordinates(x); + const out: number[] = []; + const ends = (s: number) => [p[ids[s][0]], p[ids[s][ids[s].length - 1]]]; + const direction = (s: number) => { + const [a, b] = ends(s); + return [b[0] - a[0], b[1] - a[1]]; + }; + const unitOf = (d: number[]) => { + const length = Math.hypot(d[0], d[1]) || 1; + return [d[0] / length, d[1] / length]; + }; + const arc = (s: number) => { + const q = ids[s]; + return circle2(p[q[0]], p[q[q.length >> 1]], p[q[q.length - 1]]); + }; + for (const [k, line] of lines.entries()) + if (line && slot[k] >= 0) + out.push(line.d[0] * (p[k][1] - line.o[1]) - line.d[1] * (p[k][0] - line.o[0])); + for (const c of constraints) { + if (c.kind === 'align') { + const [a, b] = c.points.map((r) => p[ids[r.segment][r.index]]); + out.push(c.axis === 'horizontal' ? a[1] - b[1] : a[0] - b[0]); + continue; + } + if (c.kind === 'horizontal' || c.kind === 'vertical') { + const d = direction(c.segments[0]); + out.push(c.kind === 'horizontal' ? d[1] : d[0]); + continue; + } + const [i, j] = c.segments as [number, number]; + const [si, sj] = [shape.segments[i].kind, shape.segments[j].kind]; + if (c.kind === 'parallel' || c.kind === 'perpendicular') { + const [a, b] = [unitOf(direction(i)), direction(j)]; + out.push(c.kind === 'parallel' ? a[0] * b[1] - a[1] * b[0] : a[0] * b[0] + a[1] * b[1]); + } else if (c.kind === 'collinear') { + const a = unitOf(direction(i)); + const o = ends(i)[0]; + for (const q of ends(j)) out.push(a[0] * (q[1] - o[1]) - a[1] * (q[0] - o[0])); + } else if (c.kind === 'equal') { + if (si === 'line') out.push(Math.hypot(...direction(i)) - Math.hypot(...direction(j))); + else out.push((arc(i)?.radius ?? NaN) - (arc(j)?.radius ?? NaN)); + } else if (c.kind === 'concentric') { + const [a, b] = [arc(i), arc(j)]; + out.push((a?.centre[0] ?? NaN) - (b?.centre[0] ?? NaN)); + out.push((a?.centre[1] ?? NaN) - (b?.centre[1] ?? NaN)); + } else if (c.kind === 'tangent') { + const shared = sharedPoint(shape, i, j); + if (!shared) { + out.push(NaN); + continue; + } + const at = p[ids[i][shared[0]]]; + if (si === 'line' || sj === 'line') { + const [line, round] = si === 'line' ? [i, j] : [j, i]; + const d = unitOf(direction(line)); + const centre = arc(round)?.centre ?? [NaN, NaN]; + out.push(d[0] * (at[0] - centre[0]) + d[1] * (at[1] - centre[1])); + } else { + const [a, b] = [arc(i)?.centre ?? [NaN, NaN], arc(j)?.centre ?? [NaN, NaN]]; + const [ra, rb] = [ + [at[0] - a[0], at[1] - a[1]], + [at[0] - b[0], at[1] - b[1]], + ]; + out.push((ra[0] * rb[1] - ra[1] * rb[0]) / (Math.hypot(rb[0], rb[1]) || 1)); + } + } + } + return out; + }; + const x = new Float64Array(count * 2); + for (let k = 0; k < n; k++) if (slot[k] >= 0) [x[slot[k] * 2], x[slot[k] * 2 + 1]] = start[k]; + const largest = (r: number[]) => r.reduce((m, v) => Math.max(m, Math.abs(v)), 0); + let r = residuals(x); + const solved = () => r.every((v) => Number.isFinite(v)) && largest(r) <= constraintTolerance / 10; + const squares = (values: number[]) => values.reduce((sum, v) => sum + v * v, 0); + let damping = 1e-3; + for (let step = 0; step < iterations && r.length && count && !solved(); step++) { + if (!r.every((v) => Number.isFinite(v))) return null; + // Jacobian by central differences. + const m = r.length, + h = 1e-7; + const jacobian = Array.from({ length: m }, () => new Float64Array(count * 2)); + for (let v = 0; v < count * 2; v++) { + const keep = x[v]; + x[v] = keep + h; + const ahead = residuals(x); + x[v] = keep - h; + const behind = residuals(x); + x[v] = keep; + for (let i = 0; i < m; i++) jacobian[i][v] = (ahead[i] - behind[i]) / (2 * h); + } + // The least weighted change, damped: dx = -W^-1 J^T (J W^-1 J^T + lambda I)^+ r. The + // pseudo-inverse passes over constraints that repeat others, as two arcs tangent to two + // parallel lines make their radii equal already; the damping grows while a step would make the + // miss larger, so the guide eases into shape rather than collapsing into a degenerate one. + const a = Array.from({ length: m }, (_, i) => + Array.from({ length: m }, (_, j) => { + let sum = 0; + for (let v = 0; v < count * 2; v++) sum += (jacobian[i][v] * jacobian[j][v]) / weight[v]; + return sum; + }), + ); + const scale = Math.max(1e-12, ...a.map((row, i) => Math.abs(row[i]))); + const before = squares(r); + const from = Float64Array.from(x); + let improved = false; + for (let tries = 0; tries < 30 && !improved; tries++) { + const damped = a.map((row, i) => + row.map((value, j) => value + (i === j ? damping * scale : 0)), + ); + const b = pseudoInverse(new Matrix(damped), 1e-12 * scale) + .mmul(Matrix.columnVector(r)) + .to1DArray(); + for (let v = 0; v < count * 2; v++) { + let sum = 0; + for (let i = 0; i < m; i++) sum += jacobian[i][v] * b[i]; + x[v] = from[v] - sum / weight[v]; + } + const next = residuals(x); + if (next.every((v) => Number.isFinite(v)) && squares(next) < before) { + r = next; + improved = true; + damping = Math.max(1e-12, damping / 4); + } else damping *= 4; + } + if (!improved) { + x.set(from); + break; + } + } + if (r.length && !solved()) return null; + const solvedAt = coordinates(x); + for (const i of constrainedLines) { + const a = solvedAt[ids[i][0]], + b = solvedAt[ids[i].at(-1)!]; + if (Math.hypot(a[0] - b[0], a[1] - b[1]) <= constraintTolerance) return null; + } + return points.map((p, k): Vec3 => + slot[k] < 0 ? p.position : planePoint(plane, solvedAt[k][0], solvedAt[k][1]), + ); +} + +/** + * The guide's segments with every point at its solved position, or null when the constraints + * cannot hold. `place` gives each moved point its triangle. + */ +export function solvedSegments( + shape: S, + request: SolveRequest, + place: (from: GuidePoint, position: Vec3) => GuidePoint, +): S['segments'] | null { + const solved = solveGuide(shape, request); + if (!solved) return null; + const points: GuidePoint[] = []; + for (const s of shape.segments) + for (const p of s.points) if (!points.some((q) => samePoint(q, p))) points.push(p); + const moved = points.map((p, k) => + solved[k].every((x, a) => x === p.position[a]) ? p : place(p, solved[k]), + ); + return shape.segments.map((s) => ({ + ...s, + points: s.points.map((p) => moved[points.findIndex((q) => samePoint(q, p))]), + })); +} diff --git a/src/core/refine-edge.ts b/src/core/refine-edge.ts index 3b14afd..5ca20f0 100644 --- a/src/core/refine-edge.ts +++ b/src/core/refine-edge.ts @@ -4,10 +4,12 @@ import { BandZone, type EdgeBand, type GuidePoint, + localEdge, type BandClassification, buildBand, estimateBand, minBandAngle, + widestEstimate, } from './refine-band'; import { type CutResult, cutAlongField } from './refine-cut'; import { type Shape, type ShapeKind, fitShape, projectToShape, shapeDistance } from './refine-fit'; @@ -17,6 +19,7 @@ import { type GuideKind, closestOnCurve, curveTangent, + drawnCurve, fitCurve, joinCurves, } from './refine-curve'; @@ -32,6 +35,8 @@ import { vertexNormal, weldedCorner, } from './refine-mesh'; +import type { GuideConstraint } from './refine-constraints'; +import { type SketchPlane, bestPlaneNormal, nearestOnSurface } from './refine-sketch'; import type { Vec3 } from './types'; export interface Flank { @@ -59,11 +64,40 @@ export interface EdgeInput { * surface past the end. Ignored on a closed path. */ ends?: [EdgeEnd | null, EdgeEnd | null]; + /** + * Where the guide lies on the rounded edge of the scan; absent is `along`, today's solve, where the + * edge is where the two faces meet. + */ + position?: EdgePosition; + /** How far, mm, the solved edge may move off the guide's edge; null or absent is today's reach. */ + fit?: number | null; + /** Keep the guide's shape: any move is one offset per segment. Absent is off. */ + path?: boolean; + /** Degrees between the surface and the wall; null or absent reads it from the scan. */ + wallAngle?: number | null; + /** The sketch plane the guide's points lie on. */ + plane?: SketchPlane | null; + /** Take the surface from the plane, not the scan. Only read with a plane. */ + usePlane?: boolean; + /** Constraints between the guide's segments and points, in its plane; the solve never reads them. */ + constraints?: GuideConstraint[]; } +/** + * Where a guide lies relative to the rounded edge on the scan: on the sharp edge itself, where the + * rounding starts on the surface, where it ends on the wall, or somewhere on it. + */ +export type EdgePosition = 'corner' | 'top' | 'bottom' | 'along'; +/** + * Why `solveEdge` refused: no edge under the guide; no wall it could fit; a wall more than + * `wallTolerance` degrees off the wall angle; or a width that leaves no usable core. + */ +export type EdgeRefusal = 'edge' | 'wall' | 'angle' | 'width' | 'fit'; /** How the sharpness ends at an open guide's end: tapered along the edge, or held to the end. */ export type EdgeEnd = 'taper' | 'hold'; export interface EdgeSolve { bands: EdgeBand[]; + /** Surface side held to the sketch plane for each segment. */ + planeSides?: number[]; flanks: [Flank, Flank][]; /** The solved edge, all segments joined. */ curve: EdgeCurve; @@ -733,13 +767,377 @@ interface Part { kind: GuideKind; band: EdgeBand; edge: number; + /** The flanks the edge is rebuilt onto: the scan's, or as the guide's settings make them. */ flanks: [Flank, Flank]; + /** The flanks as read from the scan, which shared and cleared refits change. */ + scan: [Flank, Flank]; meet: { points: Float64Array; angles: number[] }; curve: EdgeCurve; samples: (FlankSample | null)[]; controls: number; + /** The guide's points as placed, and the guide drawn through them. */ + points: GuidePoint[]; + drawn: EdgeCurve; + carried?: EdgeCurve; + guide: GuideSettings; + /** The side that is the surface; the other is the wall. */ + surface: number; +} + +/** A guide's solve settings, resolved. */ +interface GuideSettings { + /** No setting differs from today's solve, which then runs exactly as it did. */ + legacy: boolean; + position: EdgePosition; + fit: number | null; + path: boolean; + wallAngle: number | null; + /** The plane taken as the surface, when Use guide plane is on. */ + plane: SketchPlane | null; + /** The normal the surface is told from the wall by: the plane's, or the guide's best-fit plane's. */ + reference: Vec3 | null; + /** The plane as a flank, one per orientation, so segments that share it share one flank. */ + planeFlanks: Map; +} + +/** Most degrees a wall read from the scan may lie off a set wall angle. */ +export const wallTolerance = 5; + +/** The guide's settings, resolved from `input`. */ +function settingsOf(input: EdgeInput): GuideSettings { + const plane = input.plane && input.usePlane !== false ? input.plane : null; + const position = input.position ?? 'along'; + const fit = input.fit ?? null; + const path = !!input.path; + const wallAngle = input.wallAngle ?? null; + const flat = input.segments.flatMap((segment) => segment.points.flatMap((p) => p.position)); + return { + legacy: position === 'along' && fit === null && !path && wallAngle === null && !plane, + position, + fit, + path, + wallAngle, + plane, + reference: input.plane?.normal ?? bestPlaneNormal(flat), + planeFlanks: new Map(), + }; +} + +/** A plane through `point` with unit `normal` as a flank, positive on the normal's side. */ +function planeFlank(point: ArrayLike, normal: ArrayLike): Flank { + const [px, py, pz] = [point[0], point[1], point[2]]; + const [nx, ny, nz] = [normal[0], normal[1], normal[2]]; + const signed = (x: number, y: number, z: number) => (x - px) * nx + (y - py) * ny + (z - pz) * nz; + return { + kind: 'plane', + signed, + distance: (x, y, z) => Math.abs(signed(x, y, z)), + project: (x, y, z, out) => { + const d = signed(x, y, z); + out[0] = x - d * nx; + out[1] = y - d * ny; + out[2] = z - d * nz; + }, + }; +} + +/** + * The surface swept by a straight line about an axis through `centre` along unit `axis`: in the + * half-plane of each point it is the line through (radius, 0) with unit normal `normal`, as + * (radial, axial). A cylinder when the normal is radial, a cone otherwise. + */ +function revolvedFlank( + centre: ArrayLike, + axis: ArrayLike, + radius: number, + normal: [number, number], +): Flank { + const d = [0, 0, 0], + e = [0, 0, 0]; + const read = (x: number, y: number, z: number) => { + d[0] = x - centre[0]; + d[1] = y - centre[1]; + d[2] = z - centre[2]; + const h = dot(d, axis); + for (let a = 0; a < 3; a++) e[a] = d[a] - h * axis[a]; + const rho = Math.hypot(e[0], e[1], e[2]); + for (let a = 0; a < 3; a++) e[a] = rho > 0 ? e[a] / rho : 0; + return (rho - radius) * normal[0] + h * normal[1]; + }; + return { + kind: normal[1] === 0 ? 'cylinder' : 'cone', + signed: read, + distance: (x, y, z) => Math.abs(read(x, y, z)), + project: (x, y, z, out) => { + const s = read(x, y, z); + out[0] = x - s * (normal[0] * e[0] + normal[1] * axis[0]); + out[1] = y - s * (normal[0] * e[1] + normal[1] * axis[1]); + out[2] = z - s * (normal[0] * e[2] + normal[1] * axis[2]); + }, + }; +} + +/** `v` with its part along unit `t` taken out, made unit; null when nothing is left. */ +function across(v: number[], t: number[]) { + const k = dot(v, t); + const w = [v[0] - k * t[0], v[1] - k * t[1], v[2] - k * t[2]]; + return Math.hypot(w[0], w[1], w[2]) > 1e-6 ? unit(w) : null; +} + +/** The median of each of `values`' `width` components. */ +function medianOf(values: number[][], width: number) { + return Array.from({ length: width }, (_, k) => median(values.map((v) => v[k]))); +} + +/** + * The wall's unit normal, given the surface's and the scan wall's (both across the edge): at + * `angle` degrees between surface and wall, on the side of the surface's normal the scan's wall + * lies, or the scan's own without an angle. `turn` turns a vector a quarter about the edge. + */ +function wallNormal( + surface: number[], + scan: number[], + angle: number | null, + turn: (v: number[]) => number[], +) { + if (angle === null) return scan; + const theta = ((180 - angle) * Math.PI) / 180; + const b = turn(surface); + const [c, s] = [Math.cos(theta), Math.sin(theta)]; + const options = [1, -1].map((sign) => surface.map((x, k) => c * x + sign * s * b[k])); + // Vectors of either 2 or 3 components. + const along = (v: number[]) => v.reduce((sum, x, k) => sum + x * scan[k], 0); + return along(options[0]) >= along(options[1]) ? options[0] : options[1]; +} + +/** + * The wall through a line or arc edge `curve`: a plane through a line, or a surface swept about an + * arc's axis, at `angle` to the surface, or at the scan wall's own angle without one. Null where + * the scan's wall runs along the edge. + */ +function wallThrough( + kind: GuideKind, + curve: EdgeCurve, + surface: Flank, + scan: Flank, + angle: number | null, +): Flank | null { + const p = curve.points, + n = p.length / 3; + const point = (k: number): Vec3 => [p[k * 3], p[k * 3 + 1], p[k * 3 + 2]]; + const circle = kind === 'arc' && n >= 3 ? circleOf(point(0), point(n >> 1), point(n - 1)) : null; + if (!circle) { + const [a, b] = [point(0), point(n - 1)]; + const t = unit([b[0] - a[0], b[1] - a[1], b[2] - a[2]]); + const middle = [0, 1, 2].map((k) => (a[k] + b[k]) / 2); + const ns = across(unit(gradient(surface, middle)), t); + const ws = across(unit(gradient(scan, middle)), t); + if (!ns || !ws) return null; + return planeFlank(middle, unit(wallNormal(ns, ws, angle, (v) => crossOf(t, v)))); + } + const { centre, radius, u, v } = circle; + const axis = crossOf(u, v); + const ns = [0, 0], + ws = [0, 0]; + for (let j = 0; j <= 8; j++) { + const q = point(Math.round(((n - 1) * j) / 8)); + const e = across([q[0] - centre[0], q[1] - centre[1], q[2] - centre[2]], axis); + if (!e) continue; + const [gs, gw] = [unit(gradient(surface, q)), unit(gradient(scan, q))]; + ns[0] += dot(gs, e); + ns[1] += dot(gs, axis); + ws[0] += dot(gw, e); + ws[1] += dot(gw, axis); + } + const [sl, wl] = [Math.hypot(ns[0], ns[1]), Math.hypot(ws[0], ws[1])]; + if (!(sl > 1e-6) || !(wl > 1e-6)) return null; + const normal = wallNormal([ns[0] / sl, ns[1] / sl], [ws[0] / wl, ws[1] / wl], angle, (w) => [ + -w[1], + w[0], + ]); + const length = Math.hypot(normal[0], normal[1]); + return revolvedFlank(centre, axis, radius, [normal[0] / length, normal[1] / length]); +} + +/** + * The guide moved by one offset toward the points where the faces meet, `meet` (xyz), at most + * `limit` mm: a line along itself, an arc radially about its centre in its plane, + * a spline as a whole. The offset is the median of the meet's offsets from the guide. + */ +function shifted( + kind: GuideKind, + points: GuidePoint[], + drawn: EdgeCurve, + meet: Float64Array, + limit: number, + edge: number, +): EdgeCurve { + const ps = points.map((p) => [...p.position]); + const flat = () => ps.flat(); + if (!(limit > 0) || meet.length < 3) return drawnCurve(kind, flat(), edge); + const count = meet.length / 3; + const m = (k: number) => [meet[k * 3], meet[k * 3 + 1], meet[k * 3 + 2]]; + const clamp = (o: number[]) => { + const length = Math.hypot(...o); + return length > limit ? o.map((x) => (x * limit) / length) : o; + }; + const circle = + kind === 'arc' && ps.length >= 3 + ? circleOf(ps[0] as Vec3, ps[ps.length >> 1] as Vec3, ps[ps.length - 1] as Vec3) + : null; + if (circle) { + const { centre, radius, u, v } = circle; + const axis = crossOf(u, v); + const offsets: number[] = []; + for (let k = 0; k < count; k++) { + const d = m(k).map((x, a) => x - centre[a]); + const h = dot(d, axis); + offsets.push(Math.hypot(...d.map((x, a) => x - h * axis[a])) - radius); + } + const radial = Math.max(-limit, Math.min(limit, median(offsets))); + for (const p of ps) { + const d = p.map((x, a) => x - centre[a]); + const h = dot(d, axis); + const e = unit(d.map((x, a) => x - h * axis[a])); + for (let a = 0; a < 3; a++) p[a] = centre[a] + h * axis[a] + (radius + radial) * e[a]; + } + return drawnCurve(kind, flat(), edge); + } + const at = new Float64Array(3); + const offsets: number[][] = []; + const [a, b] = [ps[0], ps[ps.length - 1]]; + const t = unit(b.map((x, k) => x - a[k])); + for (let k = 0; k < count; k++) { + const q = m(k); + if (kind === 'spline') { + onCurve(drawn, q[0], q[1], q[2], at); + offsets.push(q.map((x, c) => x - at[c])); + } else { + const d = q.map((x, c) => x - a[c]); + const along = dot(d, t); + offsets.push(d.map((x, c) => x - along * t[c])); + } + } + const o = clamp(medianOf(offsets, 3)); + for (const p of ps) for (let c = 0; c < 3; c++) p[c] += o[c]; + return drawnCurve(kind, flat(), edge); +} + +/** Each of `meet` (xyz) moved back toward its nearest point of `drawn` to lie within `limit` of it. */ +function heldTo(drawn: EdgeCurve, meet: Float64Array, limit: number) { + const out = new Float64Array(meet.length); + const at = new Float64Array(3); + for (let k = 0; k < meet.length; k += 3) { + onCurve(drawn, meet[k], meet[k + 1], meet[k + 2], at); + const d = [meet[k] - at[0], meet[k + 1] - at[1], meet[k + 2] - at[2]]; + const length = Math.hypot(d[0], d[1], d[2]); + const f = length > limit ? limit / length : 1; + for (let a = 0; a < 3; a++) out[k + a] = at[a] + d[a] * f; + } + return out; } +/** + * Makes the part's flanks and edge from its scan flanks and its guide's settings. Today's solve: + * where the scan's flanks meet, fitted as the guide's kind. Otherwise: the sketch plane taken as the + * surface (Use guide plane); the guide's edge, Corner the guide, Top or Bottom the guide carried onto + * where the faces meet, Along the guide; that edge moved toward where they meet by at most Fit, by + * one offset with Use guide path; then, for a line or an arc away from Along or with a wall angle, + * the wall built through the edge. Returns why it cannot, or null. + */ +function settle(part: Part): EdgeRefusal | null { + const { band, edge, guide, drawnKind, controls } = part; + const flanks: [Flank, Flank] = [part.scan[0], part.scan[1]]; + if (guide.legacy) { + const meet = meetFlanks(band, flanks); + if (meet.angles.length < 2 || median(meet.angles) < minBandAngle) return 'edge'; + const fitted = fitMeet(drawnKind, band.drawn, meet.points, controls, edge); + Object.assign(part, { flanks, meet, curve: fitted.curve, kind: fitted.kind }); + return null; + } + const [s, w] = [part.surface, 1 - part.surface]; + const { position, plane } = guide; + const drawn = part.drawn; + if (plane) { + const middle = new Float64Array(3); + curveAt(drawn, curveLength(drawn) / 2, middle); + const mid = [middle[0], middle[1], middle[2]]; + const sign = dot(plane.normal, gradient(part.scan[s], mid)) >= 0 ? 1 : -1; + const normal = plane.normal.map((x) => sign * x); + if (position === 'corner' || position === 'top') { + let flank = guide.planeFlanks.get(sign); + if (!flank) guide.planeFlanks.set(sign, (flank = planeFlank(plane.origin, normal))); + flanks[s] = flank; + } else { + const foot = new Float64Array(3); + part.scan[s].project(mid[0], mid[1], mid[2], foot); + flanks[s] = planeFlank(foot, normal); + } + } + const meet = meetFlanks(band, flanks); + if (meet.angles.length < 2) return 'wall'; + const reach = guide.fit ?? Math.max(0.35, 6 * edge); + let curve: EdgeCurve; + let kind = drawnKind; + const fitted = (points: Float64Array) => { + const fit = fitMeet(drawnKind, band.drawn, points, controls, edge); + kind = fit.kind; + return fit.curve; + }; + if (part.carried && reach === 0) curve = part.carried; + else if (position === 'top' || position === 'bottom') + curve = guide.path + ? shifted(drawnKind, part.points, drawn, meet.points, Infinity, edge) + : fitted(meet.points); + else if (reach === 0) curve = drawn; + else + curve = guide.path + ? shifted(drawnKind, part.points, drawn, meet.points, reach, edge) + : fitted(heldTo(drawn, meet.points, reach)); + if ((position !== 'along' || guide.wallAngle !== null) && kind !== 'spline') { + const wall = wallThrough(kind, curve, flanks[s], part.scan[w], guide.wallAngle); + if (!wall) return 'wall'; + flanks[w] = wall; + } else if (guide.wallAngle !== null) { + const off = Math.abs(180 - median(meet.angles) - guide.wallAngle); + if (off > wallTolerance) return 'angle'; + } + const settled = meetFlanks(band, flanks); + Object.assign(part, { + flanks, + curve, + kind, + meet: settled.angles.length >= 2 ? settled : meet, + }); + return null; +} + +/** + * Which side of a part is the surface: with a reference normal, the side whose normal at the guide's + * middle lies nearer it, either way; without one, the side with more flank vertices, Left on a tie. + */ +function surfaceSide(band: EdgeBand, scan: [Flank, Flank], reference: Vec3 | null) { + if (reference) { + const middle = new Float64Array(3); + curveAt(band.drawn, curveLength(band.drawn) / 2, middle); + const p = [middle[0], middle[1], middle[2]]; + const [a, b] = scan.map((flank) => Math.abs(dot(unit(gradient(flank, p)), reference))); + return a >= b ? 0 : 1; + } + let left = 0, + right = 0; + for (const zone of band.foundZone) + if (zone === BandZone.Left) left++; + else if (zone === BandZone.Right) right++; + return left >= right ? 0 : 1; +} + +/** + * Exported for the tests: which flank of a part is the surface, 0 (Left) or 1 (Right), as the solve + * tells them apart. + */ +export const surfaceOf = surfaceSide; + /** * Neighbouring flanks are one surface when one fit takes each one's refit vertices within its own * tolerance: `sameShare` of them within 3 local of the fit and their mean within local. @@ -756,7 +1154,21 @@ const pathSnaps = [0.25, 0.15, 0.05]; /** A sharp joint's corner reaches this many band widths from the joint. */ const jointReach = 2; -/** The segment solved as Task 7's single edge, or null when it shows no edge. */ +/** + * The points a guide's band is read from: a guide placed off the surface, as on the corner a + * rounding cuts off, reads it from the surface under it, since read from the air above an edge's + * crest the band cannot tell its sides. Today's solve reads the points as placed. + */ +function readFrom( + mesh: RefineMesh, + topology: RefineTopology, + points: GuidePoint[], + guide: GuideSettings, +) { + return guide.legacy ? points : points.map((p) => nearestOnSurface(mesh, topology, p)); +} + +/** The segment solved as Task 7's single edge, or why it cannot be. */ function solvePart( mesh: RefineMesh, topology: RefineTopology, @@ -765,16 +1177,41 @@ function solvePart( width: number, noise: number, known: BandClassification | null, -): Part | null { - const band = buildBand(mesh, topology, kind, points, width, noise, known); - if (!band) return null; + guide: GuideSettings, + carried?: EdgeCurve, +): Part | EdgeRefusal { + const seeds = readFrom(mesh, topology, points, guide); + if (guide.position === 'corner' && guide.fit !== null) { + const depths = seeds.map((seed, i) => + Math.hypot(...seed.position.map((x, a) => x - points[i].position[a])), + ); + if (median(depths) - guide.fit > deepestEdge * width) return 'fit'; + } + const band = buildBand( + mesh, + topology, + kind, + seeds, + width, + noise, + known, + carried ?? + (guide.position === 'corner' + ? drawnCurve( + kind, + points.flatMap((p) => p.position), + localEdge(mesh, topology, points), + ) + : undefined), + ); + if (!band) return 'edge'; const edge = bandEdgeLength(mesh, topology, band); const solved = unbiasedFlanks(mesh, topology, band, kind, points.length, noise, edge); - if (!solved) return null; + if (!solved) return 'edge'; // The band is built about the guide as drawn; from here on the segment is the kind its edge was // fitted as, an arc where a Line guide lies along an edge that curves. const { flanks, meet, curve, samples, kind: fitted } = solved; - if (median(meet.angles) < minBandAngle) return null; + if (median(meet.angles) < minBandAngle) return 'edge'; // An edge that lies farther from the surface than half the band's width, as at a fin whose faces // nearly meet, cannot be reached by moving the band's vertices. const members = Array.from({ length: band.vertices.length }, (_, i) => i); @@ -782,18 +1219,45 @@ function solvePart( const depths: number[] = []; for (let k = 0; k < meet.points.length; k += 3) depths.push(find(meet.points[k], meet.points[k + 1], meet.points[k + 2]).distance); - if (median(depths) > deepestEdge * band.width) return null; - return { + if (median(depths) > deepestEdge * band.width) return 'edge'; + const part: Part = { drawnKind: kind, kind: fitted, band, edge, flanks, + scan: [flanks[0], flanks[1]], meet, curve, samples, controls: points.length, + points, + drawn: guide.legacy + ? band.drawn + : drawnCurve( + kind, + points.flatMap((p) => p.position), + edge, + ), + guide, + carried, + surface: guide.legacy ? 0 : surfaceSide(band, flanks, guide.reference), }; + if (guide.legacy) return part; + const refusal = settle(part); + if (refusal) return refusal; + // Beyond the rebuild depth the scan cannot supply a corner at this offset. + if (guide.position === 'corner' && guide.fit !== null) { + const distances = []; + for (let k = 0; k < part.curve.points.length; k += 3) { + const [x, y, z] = part.curve.points.subarray(k, k + 3); + distances.push(find(x, y, z).distance); + } + if (median(distances) > deepestEdge * band.width) return 'fit'; + } + if (!carried && (guide.position === 'top' || guide.position === 'bottom')) + return solvePart(mesh, topology, kind, points, width, noise, known, guide, part.curve); + return part; } /** True when `sample` lies within tolerance of `flank`: `sameShare` within 3 local, mean within local. */ @@ -862,7 +1326,7 @@ function shareFlanks(parts: Part[], closed: boolean, noise: number) { const flank = group.length > 1 && fitTogether(parts, group, s, noise); if (!flank) continue; for (const i of group) { - parts[i].flanks[s] = flank; + parts[i].scan[s] = flank; changed.add(i); } } @@ -885,7 +1349,7 @@ function clearCorners(parts: Part[], joints: GuideJoint[], noise: number) { const [a, b] = [parts[i].curve.points, parts[j].curve.points]; const point = [0, 1, 2].map((c) => (a[a.length - 3 + c] + b[c]) / 2); for (const side of [0, 1]) { - const [f, g] = [parts[i].flanks[side], parts[j].flanks[side]]; + const [f, g] = [parts[i].scan[side], parts[j].scan[side]]; const [u, v] = [unit(gradient(f, point)), unit(gradient(g, point))]; if ((Math.acos(Math.min(1, Math.abs(dot(u, v)))) * 180) / Math.PI < minBandAngle) continue; far.push({ part: i, side, from: g, reach: cornerClear * parts[j].band.soft }); @@ -912,30 +1376,20 @@ function clearCorners(parts: Part[], joints: GuideJoint[], noise: number) { }); const shape = fitShape(points, normals, sample.kind, noise); if (!shape?.within) continue; - part.flanks[side] = shapeFlank(shape.shape); + part.scan[side] = shapeFlank(shape.shape); part.samples[side] = { points, normals, kind: sample.kind }; changed.add(index); } return resolveParts(parts, changed); } -/** Solves again where the flanks of each changed part meet. False when they no longer do. */ +/** Settles each changed part again from its scan flanks. False when one no longer settles. */ function resolveParts(parts: Part[], changed: Set) { for (const i of changed) { - const part = parts[i]; - part.meet = meetFlanks(part.band, part.flanks); - if (part.meet.angles.length < 2 || median(part.meet.angles) < minBandAngle) return false; - const fitted = fitMeet( - part.drawnKind, - part.band.drawn, - part.meet.points, - part.controls, - part.edge, - ); - part.curve = fitted.curve; - part.kind = fitted.kind; + const reason = settle(parts[i]); + if (reason) return reason; } - return true; + return null; } /** Length of a curve, the closing span included when it is closed. */ @@ -1157,8 +1611,15 @@ export function solveEdge( topology: RefineTopology, input: EdgeInput, noise: number, + why?: { reason: EdgeRefusal | null }, ): EdgeSolve | null { + const refuse = (reason: EdgeRefusal) => { + if (why) why.reason = reason; + return null; + }; + if (why) why.reason = null; const { closed } = input; + const guide = settingsOf(input); const count = input.segments.length; if (!count || input.joints.length !== (closed ? count : count - 1)) return null; const circle = closed && count === 1; @@ -1171,22 +1632,48 @@ export function solveEdge( if (width === null) { width = 0; for (const [i, { kind, points }] of segments.entries()) { - const estimate = estimateBand(mesh, topology, kind, points, noise); - if (!(estimate.width > 0)) return null; + const estimate = estimateBand( + mesh, + topology, + kind, + readFrom(mesh, topology, points, guide), + noise, + ); + if (!(estimate.width > 0)) return refuse('edge'); width = Math.max(width, estimate.width); known[i] = estimate.found; } } if (!(width > 0)) return null; const parts: Part[] = []; - for (const [i, { kind, points }] of segments.entries()) { - const part = solvePart(mesh, topology, kind, points, width, noise, known[i]); - if (!part) return null; - parts.push(part); + // Automatic width starts with the scan estimate. A guide-centred band may need more + // room to read both faces inside that width, especially on a densely sampled fillet. + for (;;) { + let failure: EdgeRefusal | null = null; + for (const [i, { kind, points }] of segments.entries()) { + const part = solvePart(mesh, topology, kind, points, width, noise, known[i], guide); + if (typeof part === 'string') { + failure = part; + break; + } + parts.push(part); + } + if (!failure) break; + if ( + failure !== 'edge' || + input.width !== null || + guide.position === 'along' || + width >= widestEstimate + ) + return refuse(failure); + parts.length = 0; + width = Math.min(widestEstimate, 1.5 * width); } const n = parts.length; - if (n > 1 && !clearCorners(parts, joints, noise)) return null; - if (n > 1 && !shareFlanks(parts, closed, noise)) return null; + if (n > 1) { + const reason = clearCorners(parts, joints, noise) ?? shareFlanks(parts, closed, noise); + if (reason) return refuse(reason); + } const edge = median(parts.map((part) => part.edge)); let curve: EdgeCurve; @@ -1195,7 +1682,8 @@ export function solveEdge( if (n === 1) { curve = parts[0].curve; bounds = [0, curveLength(curve)]; - } else if (circle) { + } else if (circle && guide.legacy) { + // Today's solve fits the circle where the faces meet; with settings, through the parts' edges. curve = fitCurve( 'arc', Float64Array.from(parts.flatMap((part) => [...part.meet.points])), @@ -1240,6 +1728,21 @@ export function solveEdge( : [0, ...starts, curveLength(curve)]; } + // Joining segments and refitting a clamped set of samples can both exceed the requested Fit. + if (!guide.legacy) { + const near = new Float64Array(3); + for (let k = 0; k < curve.points.length; k += 3) { + const [x, y, z] = curve.points.subarray(k, k + 3); + if ( + !parts.some((part) => { + const limit = (guide.fit ?? Math.max(0.35, 6 * part.edge)) + 1e-6; + closestOnCurve(part.carried ?? part.drawn, x, y, z, near); + return Math.hypot(x - near[0], y - near[1], z - near[2]) <= limit; + }) + ) + return refuse('fit'); + } + } const ends: [EdgeEnd, EdgeEnd] = closed ? ['hold', 'hold'] : [ @@ -1248,6 +1751,10 @@ export function solveEdge( ]; const solve: EdgeSolve = { bands: parts.map((part) => part.band), + planeSides: + guide.plane && (guide.position === 'corner' || guide.position === 'top') + ? parts.map((part) => part.surface) + : undefined, flanks: parts.map((part) => part.flanks), curve, sign: Int8Array.from(parts, (part) => @@ -1264,7 +1771,7 @@ export function solveEdge( const frame = frameOf(mesh, topology, solve); const surfaces = surfacesOf(mesh, topology, solve, frame); const weights = frameWeights(mesh, topology, solve, frame, surfaces); - return usableCore(mesh, solve, frame, weights, surfaces) ? solve : null; + return usableCore(mesh, solve, frame, weights, surfaces) ? solve : refuse('width'); } /** A joint of a solved path. */ @@ -2068,6 +2575,7 @@ export function applyEdge( const apartAt = new Float64Array(count); const p = [0, 0, 0]; const target = [0, 0, 0]; + const planeTarget = new Float64Array(3); const end = [0, 0, 0]; for (const [v, i] of indexOf) { const weight = strength * weights[i]; @@ -2087,9 +2595,12 @@ export function applyEdge( let apart = 0; for (const side of [nearer, 1 - nearer]) { surface.target(side, p[0], p[1], p[2], target); - let share = weight; + const onPlane = solve.planeSides?.[owner] === side; + if (onPlane) solve.flanks[owner][side].project(p[0], p[1], p[2], planeTarget); + const destination = onPlane ? planeTarget : target; + let share = onPlane && solve.curve.closed ? strength : weight; if (frame.corners.length) share *= cornerFade(solve, frame, owner, side, p); - for (let a = 0; a < 3; a++) end[a] = p[a] + share * (target[a] - p[a]); + for (let a = 0; a < 3; a++) end[a] = p[a] + share * (destination[a] - p[a]); apart = surface.distance(0, end[0], end[1], end[2]) - surface.distance(1, end[0], end[1], end[2]); if (side === nearer || apart > 0 === (side === 1)) { diff --git a/src/core/refine-sketch.ts b/src/core/refine-sketch.ts new file mode 100644 index 0000000..0d9623b --- /dev/null +++ b/src/core/refine-sketch.ts @@ -0,0 +1,394 @@ +import { BufferAttribute, BufferGeometry, Vector3 } from 'three'; +import { MeshBVH } from 'three-mesh-bvh'; +import type { GuidePoint } from './refine-band'; +import { type RefineMesh, type RefineTopology, weldedCorner } from './refine-mesh'; +import type { Vec3 } from './types'; + +/** + * A sketch plane of a Refine session: an origin, a unit normal and unit in-plane axes `u` and `v` + * (v = normal x u). Guides drawn on it keep their points in it. + */ +export interface SketchPlane { + id: string; + /** Shown as Plane 1, Plane 2, and so on, in the order the session made them. */ + name: string; + origin: Vec3; + normal: Vec3; + u: Vec3; + v: Vec3; +} + +const dot = (a: ArrayLike, b: ArrayLike) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +const cross = (a: ArrayLike, b: ArrayLike): Vec3 => [ + 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 unit = (a: ArrayLike): Vec3 => { + const length = Math.hypot(a[0], a[1], a[2]) || 1; + return [a[0] / length, a[1] / length, a[2] / length]; +}; + +/** A plane through `origin` with `normal`, `u` along `along` taken into the plane. Null when `along` is along the normal. */ +export function planeOf( + id: string, + name: string, + origin: ArrayLike, + normal: ArrayLike, + along: ArrayLike, +): SketchPlane | null { + const n = unit(normal); + const t = dot(along, n); + const inPlane = [along[0] - t * n[0], along[1] - t * n[1], along[2] - t * n[2]]; + if (!(Math.hypot(inPlane[0], inPlane[1], inPlane[2]) > 1e-9)) return null; + const u = unit(inPlane); + return { id, name, origin: [origin[0], origin[1], origin[2]], normal: n, u, v: cross(n, u) }; +} + +/** The plane through three points, `u` from the first to the second. Null when they are collinear. */ +export function planeThrough(id: string, name: string, a: Vec3, b: Vec3, c: Vec3) { + const ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + const ac = [c[0] - a[0], c[1] - a[1], c[2] - a[2]]; + const n = cross(ab, ac); + const scale = Math.hypot(...ab) * Math.hypot(...ac); + if (!(Math.hypot(n[0], n[1], n[2]) > 1e-6 * scale) || !(scale > 0)) return null; + return planeOf(id, name, a, n, ab); +} + +/** The point of the plane nearest `p`. */ +export function ontoPlane(plane: SketchPlane, p: ArrayLike): Vec3 { + const { origin, normal } = plane; + const h = + (p[0] - origin[0]) * normal[0] + + (p[1] - origin[1]) * normal[1] + + (p[2] - origin[2]) * normal[2]; + return [p[0] - h * normal[0], p[1] - h * normal[1], p[2] - h * normal[2]]; +} + +/** `p` in the plane's (u, v) coordinates. */ +export function planeCoordinates(plane: SketchPlane, p: ArrayLike): [number, number] { + const d = [p[0] - plane.origin[0], p[1] - plane.origin[1], p[2] - plane.origin[2]]; + return [dot(d, plane.u), dot(d, plane.v)]; +} + +/** The world point at (u, v) in the plane. */ +export function planePoint(plane: SketchPlane, u: number, v: number): Vec3 { + const { origin: o, u: a, v: b } = plane; + return [o[0] + u * a[0] + v * b[0], o[1] + u * a[1] + v * b[1], o[2] + u * a[2] + v * b[2]]; +} + +/** Where a ray meets the plane, or null when it runs along it or the plane lies behind it. */ +export function rayOnPlane( + plane: SketchPlane, + origin: ArrayLike, + direction: ArrayLike, +): Vec3 | null { + const along = dot(direction, plane.normal); + if (Math.abs(along) < 1e-9) return null; + const d = [plane.origin[0] - origin[0], plane.origin[1] - origin[1], plane.origin[2] - origin[2]]; + const t = dot(d, plane.normal) / along; + if (!(t >= 0)) return null; + return [origin[0] + t * direction[0], origin[1] + t * direction[1], origin[2] + t * direction[2]]; +} + +/** + * The normal of the plane that best fits `points` (xyz), or null when they lie near one line: the + * normal is the axis of least spread, given a middle spread of at least a tenth of the largest, in + * standard deviation. + */ +export function bestPlaneNormal(points: ArrayLike): Vec3 | null { + const n = points.length / 3; + if (n < 3) return null; + const c = [0, 0, 0]; + for (let i = 0; i < n; i++) for (let a = 0; a < 3; a++) c[a] += points[i * 3 + a] / n; + const m = [0, 0, 0, 0, 0, 0, 0, 0, 0]; + for (let i = 0; i < n; i++) { + const d = [0, 1, 2].map((a) => points[i * 3 + a] - c[a]); + for (let r = 0; r < 3; r++) for (let s = 0; s < 3; s++) m[r * 3 + s] += d[r] * d[s]; + } + // Power iteration for the largest axis, then for the largest in the plane across it. + const largest = (deflate: Vec3[]) => { + let x: number[] = [0.577, 0.578, 0.579]; + for (let k = 0; k < 100; k++) { + for (const q of deflate) { + const t = dot(x, q); + x = x.map((value, a) => value - t * q[a]); + } + const y = [0, 1, 2].map((r) => m[r * 3] * x[0] + m[r * 3 + 1] * x[1] + m[r * 3 + 2] * x[2]); + const length = Math.hypot(y[0], y[1], y[2]); + if (!(length > 0)) return { axis: unit(x), spread: 0 }; + x = y.map((value) => value / length); + } + const y = [0, 1, 2].map((r) => m[r * 3] * x[0] + m[r * 3 + 1] * x[1] + m[r * 3 + 2] * x[2]); + return { axis: unit(x), spread: dot(x, y) }; + }; + const first = largest([]); + const second = largest([first.axis]); + if (!(first.spread > 0) || second.spread < 0.01 * first.spread) return null; + return unit(cross(first.axis, second.axis)); +} + +/** The point of triangle (a, b, c) nearest p (Ericson's regions). */ +export function closestOnTriangle( + p: ArrayLike, + a: ArrayLike, + b: ArrayLike, + c: ArrayLike, +): Vec3 { + const sub = (x: ArrayLike, y: ArrayLike) => [ + x[0] - y[0], + x[1] - y[1], + x[2] - y[2], + ]; + const ab = sub(b, a), + ac = sub(c, a), + ap = sub(p, a); + const along = (s: ArrayLike, t: number[], f: number): Vec3 => [ + s[0] + t[0] * f, + s[1] + t[1] * f, + s[2] + t[2] * f, + ]; + const d1 = dot(ab, ap), + d2 = dot(ac, ap); + if (d1 <= 0 && d2 <= 0) return [a[0], a[1], a[2]]; + const bp = sub(p, b); + const d3 = dot(ab, bp), + d4 = dot(ac, bp); + if (d3 >= 0 && d4 <= d3) return [b[0], b[1], b[2]]; + const vc = d1 * d4 - d3 * d2; + if (vc <= 0 && d1 >= 0 && d3 <= 0) return along(a, ab, d1 / (d1 - d3)); + const cp = sub(p, c); + const d5 = dot(ab, cp), + d6 = dot(ac, cp); + if (d6 >= 0 && d5 <= d6) return [c[0], c[1], c[2]]; + const vb = d5 * d2 - d1 * d6; + if (vb <= 0 && d2 >= 0 && d6 <= 0) return along(a, ac, d2 / (d2 - d6)); + const va = d3 * d6 - d5 * d4; + if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) + return along(b, sub(c, b), (d4 - d3) / (d4 - d3 + (d5 - d6))); + const denom = 1 / (va + vb + vc); + const v = vb * denom, + w = vc * denom; + return [a[0] + ab[0] * v + ac[0] * w, a[1] + ab[1] * v + ac[1] * w, a[2] + ab[2] * v + ac[2] * w]; +} + +/** Rings of triangles `nearestOnSurface` always searches round a point's own triangle. */ +const surfaceRings = 3; +/** Most rings it searches while the nearest point keeps moving. */ +const surfaceRingsMost = 64; + +/** + * The surface point nearest a guide point, and its triangle: searched from the point's own triangle + * outward over shared vertices, `surfaceRings` rings and on while each ring finds a nearer point. The + * point's triangle must be the nearest, or near it. + */ +export function nearestOnSurface( + mesh: RefineMesh, + topology: RefineTopology, + point: GuidePoint, +): GuidePoint { + const { position } = mesh; + const corner = (t: number, k: 0 | 1 | 2) => { + const w = weldedCorner(mesh, t, k) * 3; + return position.subarray(w, w + 3); + }; + const p = point.position; + let best: GuidePoint = point, + nearest = Infinity; + const seen = new Set([point.triangle]); + let ring = [point.triangle]; + for (let r = 0; ring.length && r <= surfaceRingsMost; r++) { + let improved = false; + for (const t of ring) { + const q = closestOnTriangle(p, corner(t, 0), corner(t, 1), corner(t, 2)); + const d = Math.hypot(q[0] - p[0], q[1] - p[1], q[2] - p[2]); + if (d < nearest) { + nearest = d; + best = { triangle: t, position: q }; + improved = true; + } + } + if (r >= surfaceRings && !improved) break; + const next: number[] = []; + for (const t of ring) + for (const k of [0, 1, 2] as const) { + const w = weldedCorner(mesh, t, k); + for (let i = topology.triangleStart[w]; i < topology.triangleStart[w + 1]; i++) { + const u = topology.trianglesOf[i]; + if (!seen.has(u)) { + seen.add(u); + next.push(u); + } + } + } + ring = next; + } + return best; +} + +/** How a guide point is held: sliding along a line through `origin` along unit `direction`, or fixed. */ +export type PointLock = { kind: 'line'; origin: Vec3; direction: Vec3 } | { kind: 'fixed' }; + +/** The point of the line nearest `p`. */ +export function ontoLine(lock: Extract, p: ArrayLike): Vec3 { + const { origin: o, direction: d } = lock; + const t = (p[0] - o[0]) * d[0] + (p[1] - o[1]) * d[1] + (p[2] - o[2]) * d[2]; + return [o[0] + t * d[0], o[1] + t * d[1], o[2] + t * d[2]]; +} + +/** The line lock through two points, or null when they coincide. */ +export function lineThrough(a: ArrayLike, b: ArrayLike): PointLock | null { + const d = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + if (!(Math.hypot(d[0], d[1], d[2]) > 1e-9)) return null; + return { kind: 'line', origin: [a[0], a[1], a[2]], direction: unit(d) }; +} + +/** The point of the line nearest a ray: where the ray passes closest to it. */ +export function lineNearRay( + lock: Extract, + origin: ArrayLike, + direction: ArrayLike, +): Vec3 { + const { origin: o, direction: d } = lock; + const w = [o[0] - origin[0], o[1] - origin[1], o[2] - origin[2]]; + const b = dot(d, direction), + c = dot(direction, direction), + e = dot(d, w), + f = dot(direction, w); + const denominator = c - b * b; + // Along the ray's direction the line has no nearest point; it stays at its origin. + const t = Math.abs(denominator) < 1e-12 ? 0 : (b * f - c * e) / denominator; + return [o[0] + t * d[0], o[1] + t * d[1], o[2] + t * d[2]]; +} + +/** + * Where a guide point asked to go to `p` may go: nowhere for a fixed point, the nearest point of its + * line, else of its guide's plane, else `p`. A line lock on a guide with a plane is in that plane. + */ +export function heldPoint( + lock: PointLock | undefined, + plane: SketchPlane | null | undefined, + from: Vec3, + p: ArrayLike, +): Vec3 { + if (lock?.kind === 'fixed') return from; + if (lock?.kind === 'line') return ontoLine(lock, p); + if (plane) return ontoPlane(plane, p); + return [p[0], p[1], p[2]]; +} + +const trees = new WeakMap(); + +/** Closest triangle on the immutable session model, including across separate shells. */ +export function nearestTriangle(mesh: RefineMesh, p: ArrayLike): GuidePoint | null { + if (!mesh.triangleCount) return null; + let tree = trees.get(mesh); + if (!tree) { + const geometry = new BufferGeometry(); + geometry.setAttribute('position', new BufferAttribute(mesh.position, 3)); + const corners = mesh.corners.subarray(0, mesh.triangleCount * 3); + geometry.setIndex( + new BufferAttribute( + corners.map((i) => mesh.weldOf[i]), + 1, + ), + ); + tree = new MeshBVH(geometry, { indirect: true }); + trees.set(mesh, tree); + } + const hit = tree.closestPointToPoint(new Vector3(p[0], p[1], p[2])); + return hit && { triangle: hit.faceIndex, position: hit.point.toArray() }; +} + +/** A guide point at `p` itself, on the triangle nearest it. */ +export function pointAt(mesh: RefineMesh, p: ArrayLike) { + const found = nearestTriangle(mesh, p); + return found && { triangle: found.triangle, position: [p[0], p[1], p[2]] as Vec3 }; +} + +/** + * The plane fitted to the surface within `radius` of a clicked point, over the triangles joined to + * the clicked one: through their area-weighted centroid, with the normal of least spread facing as + * the clicked triangle does, and `u` along the spread's longest axis. Null where the surface there + * is not flat to a tenth of the radius. + */ +export function planeOfFace( + mesh: RefineMesh, + topology: RefineTopology, + point: GuidePoint, + radius: number, + id: string, + name: string, +): SketchPlane | null { + const { position } = mesh; + const p = point.position; + const seen = new Set([point.triangle]); + const queue = [point.triangle]; + const flat: number[] = []; + for (let q = 0; q < queue.length; q++) { + const t = queue[q]; + const corners = ([0, 1, 2] as const).map((k) => weldedCorner(mesh, t, k)); + for (const w of corners) flat.push(position[w * 3], position[w * 3 + 1], position[w * 3 + 2]); + for (const w of corners) { + if ( + Math.hypot(position[w * 3] - p[0], position[w * 3 + 1] - p[1], position[w * 3 + 2] - p[2]) > + radius + ) + continue; + for (let i = topology.triangleStart[w]; i < topology.triangleStart[w + 1]; i++) { + const u = topology.trianglesOf[i]; + if (!seen.has(u)) { + seen.add(u); + queue.push(u); + } + } + } + } + const normal = bestPlaneNormal(flat); + if (!normal) return null; + const n = flat.length / 3; + const c = [0, 0, 0]; + for (let i = 0; i < n; i++) for (let a = 0; a < 3; a++) c[a] += flat[i * 3 + a] / n; + let off = 0; + for (let i = 0; i < n; i++) + off = Math.max( + off, + Math.abs( + dot( + [0, 1, 2].map((a) => flat[i * 3 + a] - c[a]), + normal, + ), + ), + ); + if (off > radius / 10) return null; + // The clicked triangle's own facing. + const [a, b, d] = ([0, 1, 2] as const).map((k) => { + const w = weldedCorner(mesh, point.triangle, k) * 3; + return [position[w], position[w + 1], position[w + 2]]; + }); + const facing = cross( + [b[0] - a[0], b[1] - a[1], b[2] - a[2]], + [d[0] - a[0], d[1] - a[1], d[2] - a[2]], + ); + const sign = dot(facing, normal) * (mesh.flipped ? -1 : 1) >= 0 ? 1 : -1; + const oriented = normal.map((x) => x * sign); + // The longest spread in the plane. + let along: number[] = [1, 0, 0], + widest = -1; + for (let k = 0; k < 18; k++) { + const angle = (k * Math.PI) / 18; + const helper = Math.abs(oriented[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]; + const e1 = unit(cross(oriented, helper)); + const e2 = cross(oriented, e1); + const axis = e1.map((x, i) => Math.cos(angle) * x + Math.sin(angle) * e2[i]); + let spread = 0; + for (let i = 0; i < n; i++) + spread += + dot( + [0, 1, 2].map((a) => flat[i * 3 + a] - c[a]), + axis, + ) ** 2; + if (spread > widest) [widest, along] = [spread, axis]; + } + return planeOf(id, name, c, oriented, along); +} diff --git a/src/core/store.ts b/src/core/store.ts index 8ebaa71..ad4b9d6 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -85,7 +85,14 @@ import type { GuidePoint } from './refine-band'; import type { RefineBrush } from './refine-brush'; import type { EdgeCurve, GuideJoint, GuideKind } from './refine-curve'; import type { RefineProposal } from './refine-detect'; -import type { EdgeEnd, EdgeInput, EdgeSegment, EdgeSolve } from './refine-edge'; +import type { + EdgeEnd, + EdgeInput, + EdgePosition, + EdgeRefusal, + EdgeSegment, + EdgeSolve, +} from './refine-edge'; import { type RefineMesh, cloneRefineMesh, @@ -94,6 +101,24 @@ import { writeRefinedGeometry, } from './refine-mesh'; import type { RefineModel } from './refine-model'; +import { + type GuideConstraint, + type LineKind, + type PairKind, + type SolveRequest, + constraintRefusal, + solvedSegments, +} from './refine-constraints'; +import { + type PointLock, + type SketchPlane, + heldPoint, + lineThrough, + nearestTriangle, + ontoPlane, + planeOfFace, + planeThrough, +} from './refine-sketch'; import { patchRefinedGeometry, patchRefinedVertices } from './refine-preview'; import type { RegionInput, RegionSolve } from './refine-region'; import type { NavigationMode } from './navigation'; @@ -216,6 +241,12 @@ export interface EditorContextMenu { kind?: 'brush'; partId?: string; point?: SurfacePoint; + /** A Refine guide point: the menu is that point's. */ + refinePoint?: RefinePointSelection; + /** A segment of a Refine guide: the menu is that segment's. */ + refineSegment?: { feature: string; segment: number }; + /** A constraint of a Refine guide: the menu is that constraint's. */ + refineConstraint?: { feature: string; id: string }; } type Toast = { id: string; message: string; kind: 'success' | 'error' | 'info' }; const emptySurfacePair = (): SurfacePair => ({ id: uid(), source: null, target: null }); @@ -387,6 +418,7 @@ interface WarpRecovery { } export type RefineMode = 'edge' | 'region' | 'brush' | 'detect'; +type DistributiveOmit = T extends unknown ? Omit : never; export interface RefineFeature { id: string; state: 'pending' | 'accepted'; @@ -408,12 +440,27 @@ export interface RefineStep { triangles: number[]; /** Whether the selected guide's last spline segment still took points. */ drawing: boolean; + planes: SketchPlane[]; } -interface RefinePointSelection { +export interface RefinePointSelection { feature: string; segment: number; index: number; } +/** + * Clicks the session waits for: points for a new plane (three, or one on a flat face), after which + * the guide `lock` is put on it when set; or two points for a guide point's line lock. + */ +export type RefinePicking = + | { kind: 'plane'; from: 'points' | 'face'; points: Vec3[]; lock: string | null } + | { kind: 'line'; point: RefinePointSelection; points: Vec3[] } + | { kind: 'align'; axis: LineKind; point: RefinePointSelection; points: Vec3[] } + | { kind: 'constrain'; constraint: PairKind; feature: string; segment: number; points: Vec3[] }; +/** What a pick landed on, besides its point: a guide point, or a guide's segment. */ +export interface RefinePickTarget { + point?: RefinePointSelection; + segment?: { feature: string; segment: number }; +} export interface RefineSession { id: string; partId: string; @@ -438,6 +485,10 @@ export interface RefineSession { chosenPoint: RefinePointSelection | null; /** Painted triangles of the working surface: the region being made, or where Detect looks. */ triangles: number[]; + /** The session's sketch planes, in the order they were made. */ + planes: SketchPlane[]; + /** Clicks the session waits for, or null. Never in a step. */ + picking: RefinePicking | null; edge: { kind: GuideKind; width: number | null; @@ -445,6 +496,18 @@ export interface RefineSession { strength: number; /** How the sharpness ends at each end of an open guide; null decides automatically. */ ends: [EdgeEnd | null, EdgeEnd | null]; + /** Where the next guide lies on the rounded edge. */ + position: EdgePosition; + /** How far, mm, the next guide's edge may move to fit the scan; null is today's reach. */ + fit: number | null; + /** Whether the next guide's edge keeps the guide's shape. */ + path: boolean; + /** Degrees between the surface and the wall; null reads it from the scan. */ + wallAngle: number | null; + /** Whether a guide on a sketch plane takes its surface from the plane. */ + usePlane: boolean; + /** The id of the plane the next guide is drawn on, or null. */ + plane: string | null; }; region: Omit; brush: { kind: RefineBrush; strength: number }; @@ -653,7 +716,7 @@ interface EditorState { */ setRefineEdge: ( options: Partial, - each?: Record>>, + each?: Record>>, ) => void; /** * Goes to the selected pending regions when there are any, each with its own entry of `each` on @@ -688,6 +751,32 @@ interface EditorState { begin?: boolean, ) => void; removeRefinePoint: (feature: string, segment: number, index: number) => void; + /** Starts waiting for clicks on the part or on guide points, for a new plane or a line lock. */ + startRefinePicking: (picking: RefinePicking) => void; + cancelRefinePicking: () => void; + /** One click of the picking under way, on the part, a guide point or a guide's segment. */ + pickRefine: (point: GuidePoint, on?: RefinePickTarget) => void; + /** Adds a constraint to a guide on a plane, or says why it cannot hold and changes nothing. */ + addRefineConstraint: ( + feature: string, + constraint: DistributiveOmit, + hold?: GuidePoint[], + ) => boolean; + removeRefineConstraint: (feature: string, id: string) => void; + /** + * The plane, by id, of the selected pending edges, their points projected onto it, or of the next + * guide when none is selected. Null takes them off their plane. + */ + setRefinePlane: (plane: string | null) => void; + /** Puts a guide on a plane, its points projected onto it, or takes it off with null. */ + setRefineGuidePlane: (feature: string, plane: string | null) => void; + /** Locks a guide point, and every copy of it, to a line or in place; null unlocks it. */ + lockRefinePoint: ( + feature: string, + segment: number, + index: number, + lock: PointLock | null, + ) => void; clickRefinePoint: (feature: string, segment: number, index: number) => void; clearChosenRefinePoint: () => void; removeChosenRefinePoint: () => void; @@ -3703,7 +3792,8 @@ export const useEditor = create((set, get) => ({ const { refine } = get(); if (!refine) return; refineDrag = null; - const { kind, joint, ...feature } = options; + // The next guide's plane is chosen with setRefinePlane, which projects a guide's points. + const { kind, joint, plane: _, ...feature } = options; const next = { ...(kind ? { kind } : {}), ...(joint ? { joint } : {}) }; const touched = Object.keys(feature).length > 0 || Object.keys(each).length > 0; const features = touched @@ -3773,11 +3863,14 @@ export const useEditor = create((set, get) => ({ }, }); }, - addRefinePoint: (point, close = false) => { + addRefinePoint: (placed, close = false) => { const refine = readyRefine(); if (!refine || refine.mode !== 'edge') return; const { edge } = refine; const guide = drawnGuide(refine); + // A guide on a plane keeps its points in it. + const plane = guide ? guide.feature.input.plane : nextPlane(refine); + const point = plane ? onPlane(refine, plane, placed) : placed; if (!guide) { if (close) return; const feature: RefineFeature = { @@ -3793,6 +3886,12 @@ export const useEditor = create((set, get) => ({ width: edge.width, strength: edge.strength, ends: edge.ends, + position: edge.position, + fit: edge.fit, + path: edge.path, + wallAngle: edge.wallAngle, + usePlane: edge.usePlane, + ...(plane ? { plane } : {}), }, }, }; @@ -3840,18 +3939,31 @@ export const useEditor = create((set, get) => ({ drawing, }); }, - moveRefinePoint: (id, segment, index, point, begin) => { + moveRefinePoint: (id, segment, index, asked, begin) => { const refine = readyRefine(); const feature = refine?.features.find((f) => f.id === id); if (!refine || feature?.state !== 'pending' || feature.feature.type !== 'edge') return; const input = feature.feature.input; const old = input.segments[segment]?.points[index]; - if (!old) return; - // A point two segments share, or the closing point, moves in both. - const segments = input.segments.map((s) => ({ - ...s, - points: s.points.map((p) => (samePoint(p, old) ? point : p)), - })); + if (!old || old.lock?.kind === 'fixed') return; + // A locked point slides along its line, a point of a guide on a plane in the plane. + const held = heldPoint(old.lock, input.plane, old.position, asked.position); + const moved = held.some((x, k) => x !== asked.position[k]); + const { mesh } = refine.model!; + const point: GuidePoint = { + triangle: moved ? (nearestTriangle(mesh, held) ?? asked).triangle : asked.triangle, + position: held, + ...(old.lock ? { lock: old.lock } : {}), + }; + // A point two segments share, or the closing point, moves in both; with constraints the rest + // of the guide moves with it as little as they allow, and where they cannot follow it stops. + const segments = input.constraints?.length + ? constrained(refine, input, { moved: { point: old, target: point.position } }) + : input.segments.map((s) => ({ + ...s, + points: s.points.map((p) => (samePoint(p, old) ? point : p)), + })); + if (!segments) return; const features = withProposal(refine, id, { type: 'edge', input: { ...input, segments } }); const key = `${refine.id} ${id} ${segment} ${index}`; // One step per drag: further moves of the point just moved, with nothing between, extend it. @@ -3870,7 +3982,8 @@ export const useEditor = create((set, get) => ({ draftStatus, }; const built = builtDraft; - commitRefine({ features }); + // The chosen point stays chosen, so its move widget stays with it. + commitRefine({ features, chosenPoint: refine.chosenPoint }); refineDrag = { id, feature, @@ -3909,7 +4022,10 @@ export const useEditor = create((set, get) => ({ const feature = refine?.features.find((f) => f.id === id); if (!refine || feature?.state !== 'pending' || feature.feature.type !== 'edge') return; if (!feature.feature.input.segments[segment]?.points[index]) return; - const input = withoutPoint(feature.feature.input, segment, index); + const input = withConstraints( + feature.feature.input, + withoutPoint(feature.feature.input, segment, index), + ); commitRefine( input ? { features: withProposal(refine, id, { type: 'edge', input }) } @@ -3920,6 +4036,224 @@ export const useEditor = create((set, get) => ({ }, ); }, + startRefinePicking: (picking) => { + const refine = readyRefine(); + if (!refine) return; + refineDrag = null; + set({ refine: { ...refine, picking, mode: 'edge' } }); + }, + cancelRefinePicking: () => { + const { refine } = get(); + if (refine?.picking) set({ refine: { ...refine, picking: null } }); + }, + pickRefine: (point, on = {}) => { + const refine = readyRefine(); + const picking = refine?.picking; + if (!refine || !picking) return; + if (picking.kind === 'align') { + const other = on.point; + if (other?.feature !== picking.point.feature) + return get().notify('Click another point of the same guide to align with.', 'info'); + set({ refine: { ...refine, picking: null } }); + const guide = edgeOf(refine, other.feature); + const held = guide?.segments[other.segment]?.points[other.index]; + get().addRefineConstraint( + other.feature, + { + kind: 'align', + axis: picking.axis, + points: [ + { segment: picking.point.segment, index: picking.point.index }, + { segment: other.segment, index: other.index }, + ], + }, + held ? [held] : [], + ); + return; + } + if (picking.kind === 'constrain') { + const other = on.segment; + if (other?.feature !== picking.feature) + return get().notify('Click another segment of the same guide.', 'info'); + set({ refine: { ...refine, picking: null } }); + get().addRefineConstraint(picking.feature, { + kind: picking.constraint, + segments: [picking.segment, other.segment], + }); + return; + } + const points = [...picking.points, point.position]; + const { mesh, topology, step } = refine.model!; + if (picking.kind === 'line') { + if (points.length < 2) { + set({ refine: { ...refine, picking: { ...picking, points } } }); + return; + } + const lock = lineThrough(points[0], points[1]); + set({ refine: { ...refine, picking: null } }); + if (!lock) return get().notify(samePointsNotice, 'info'); + const { feature, segment, index } = picking.point; + get().lockRefinePoint(feature, segment, index, lock); + return; + } + const wanted = picking.from === 'face' ? 1 : 3; + if (points.length < wanted) { + set({ refine: { ...refine, picking: { ...picking, points } } }); + return; + } + const id = uid(); + const name = `Plane ${refine.planes.length + 1}`; + const plane = + picking.from === 'face' + ? planeOfFace(mesh, topology, point, Math.max(0.5, 8 * step), id, name) + : planeThrough(id, name, points[0], points[1], points[2]); + if (!plane) { + set({ refine: { ...refine, picking: null } }); + get().notify(picking.from === 'face' ? curvedFaceNotice : collinearNotice, 'info'); + return; + } + const planes = [...refine.planes, plane]; + const lock = refine.features.find((f) => f.id === picking.lock); + if (lock?.state === 'pending' && lock.feature.type === 'edge') { + const input = guideOnPlane(refine, lock.feature.input, plane); + if (!input) { + set({ refine: { ...refine, picking: null } }); + return get().notify(conflictNotice, 'info'); + } + commitRefine({ + planes, + picking: null, + features: withProposal(refine, lock.id, { type: 'edge', input }), + }); + return; + } + commitRefine({ planes, picking: null, edge: { ...refine.edge, plane: id } }); + }, + setRefinePlane: (id) => { + const refine = readyRefine(); + if (!refine) return; + refineDrag = null; + const plane = id === null ? null : refine.planes.find((p) => p.id === id); + if (plane === undefined) return; + let conflict = false; + let removed = false; + const features = updateSelected(refine, (proposal) => { + if (proposal.type !== 'edge') return null; + const input = guideOnPlane(refine, proposal.input, plane); + if (!input) { + conflict = true; + return null; + } + if (!plane && proposal.input.constraints?.length) removed = true; + return { type: 'edge', input }; + }); + if (conflict) return get().notify(conflictNotice, 'info'); + if (removed) get().notify(removedConstraintsNotice, 'info'); + if (features === refine.features) { + set({ refine: { ...refine, edge: { ...refine.edge, plane: id } } }); + return; + } + commitRefine({ features, chosenPoint: refine.chosenPoint }); + }, + setRefineGuidePlane: (featureId, id) => { + const refine = readyRefine(); + const feature = refine?.features.find((f) => f.id === featureId); + if (!refine || feature?.state !== 'pending' || feature.feature.type !== 'edge') return; + const plane = id === null ? null : refine.planes.find((p) => p.id === id); + if (plane === undefined) return; + const input = guideOnPlane(refine, feature.feature.input, plane); + if (!input) return get().notify(conflictNotice, 'info'); + if (!plane && feature.feature.input.constraints?.length) + get().notify(removedConstraintsNotice, 'info'); + commitRefine({ + features: withProposal(refine, featureId, { type: 'edge', input }), + chosenPoint: refine.chosenPoint, + }); + }, + lockRefinePoint: (featureId, segment, index, lock) => { + const refine = readyRefine(); + const feature = refine?.features.find((f) => f.id === featureId); + if (!refine || feature?.state !== 'pending' || feature.feature.type !== 'edge') return; + const input = feature.feature.input; + const old = input.segments[segment]?.points[index]; + if (!old) return; + // A line lock on a guide on a plane lies in the plane. + const plane = input.plane; + const held = + lock?.kind === 'line' && plane + ? lineThrough( + ontoPlane(plane, lock.origin), + ontoPlane(plane, [ + lock.origin[0] + lock.direction[0], + lock.origin[1] + lock.direction[1], + lock.origin[2] + lock.direction[2], + ]), + ) + : lock; + if (lock && !held) return get().notify(acrossPlaneNotice, 'info'); + const { mesh } = refine.model!; + const position = held ? heldPoint(held, plane, old.position, old.position) : old.position; + const { lock: _, ...bare } = old; + const point: GuidePoint = { + ...bare, + position, + triangle: + position === old.position + ? old.triangle + : (nearestTriangle(mesh, position) ?? old).triangle, + ...(held ? { lock: held } : {}), + }; + const placed = input.segments.map((s) => ({ + ...s, + points: s.points.map((p) => (samePoint(p, old) ? point : p)), + })); + const segments = input.constraints?.length + ? constrained(refine, { ...input, segments: placed }, { heavy: [point] }) + : placed; + if (!segments) return get().notify(conflictNotice, 'info'); + commitRefine({ + features: withProposal(refine, featureId, { type: 'edge', input: { ...input, segments } }), + chosenPoint: refine.chosenPoint, + }); + }, + addRefineConstraint: (featureId, asked, hold = []) => { + const refine = readyRefine(); + const feature = refine?.features.find((f) => f.id === featureId); + if (!refine || feature?.state !== 'pending' || feature.feature.type !== 'edge') return false; + const input = feature.feature.input; + const constraint = { ...asked, id: uid() } as GuideConstraint; + const refusal = constraintRefusal(input, constraint); + if (refusal) { + get().notify(refusal, 'info'); + return false; + } + const constraints = [...(input.constraints ?? []), constraint]; + const segments = constrained(refine, { ...input, constraints }, { heavy: hold }); + if (!segments) { + get().notify(conflictNotice, 'info'); + return false; + } + commitRefine({ + features: withProposal(refine, featureId, { + type: 'edge', + input: { ...input, segments, constraints }, + }), + chosenPoint: refine.chosenPoint, + }); + return true; + }, + removeRefineConstraint: (featureId, id) => { + const refine = readyRefine(); + const feature = refine?.features.find((f) => f.id === featureId); + if (!refine || feature?.state !== 'pending' || feature.feature.type !== 'edge') return; + const input = feature.feature.input; + const constraints = (input.constraints ?? []).filter((c) => c.id !== id); + if (constraints.length === input.constraints?.length) return; + commitRefine({ + features: withProposal(refine, featureId, { type: 'edge', input: { ...input, constraints } }), + chosenPoint: refine.chosenPoint, + }); + }, finishRefineGuide: () => { refineDrag = null; const { refine } = get(); @@ -4082,7 +4416,10 @@ export const useEditor = create((set, get) => ({ if (!stroke || !refine?.model) return; if (stroke.kind !== 'crease') { if (!stroke.moved) return; - commitRefine({ model: { ...stroke.model, mesh: stroke.mesh } }); + commitRefine({ + model: { ...stroke.model, mesh: stroke.mesh }, + features: refine.features.map((f) => refreshSketchTriangles(f, stroke.mesh)), + }); // Each dab only grew the bounds; they are measured afresh once the stroke ends. const { preview } = get().refine!; preview?.computeBoundingBox(); @@ -5736,7 +6073,17 @@ const newRefineSession = (part: Part, epoch: number): RefineSession => ({ selected: [], chosenPoint: null, triangles: [], - edge: { kind: 'line', width: null, joint: 'sharp', strength: 1, ends: [null, null] }, + planes: [], + picking: null, + edge: { + kind: 'line', + width: null, + joint: 'sharp', + strength: 1, + ends: [null, null], + ...handGuideDefaults, + plane: null, + }, region: { treatment: 'smooth', shape: 'auto', @@ -5955,12 +6302,14 @@ const refineStep = ({ selected, triangles, drawing, + planes, }: RefineSession): RefineStep => ({ model: model!, features, selected, triangles, drawing, + planes, }); /** @@ -6170,6 +6519,8 @@ interface SolveAttempt { input: unknown; solve: EdgeSolve | RegionSolve | null; tooLong: boolean; + /** Why an edge's solve was refused, when it was. */ + refusal?: EdgeRefusal | null; } const refineSolves = new WeakMap(); @@ -6189,7 +6540,13 @@ const sameSolveInput = (a: unknown, b: unknown) => { x.joints.length === y.joints.length && x.joints.every((joint, i) => joint === y.joints[i]) && (x.ends?.[0] ?? null) === (y.ends?.[0] ?? null) && - (x.ends?.[1] ?? null) === (y.ends?.[1] ?? null) + (x.ends?.[1] ?? null) === (y.ends?.[1] ?? null) && + (x.position ?? 'along') === (y.position ?? 'along') && + (x.fit ?? null) === (y.fit ?? null) && + !!x.path === !!y.path && + (x.wallAngle ?? null) === (y.wallAngle ?? null) && + (x.plane ?? null) === (y.plane ?? null) && + (x.usePlane ?? true) === (y.usePlane ?? true) ); }; @@ -6209,23 +6566,77 @@ function solveProposal

( const { edge, region, curve } = refineCode!; let solve: EdgeSolve | RegionSolve | null = null; let tooLong = false; + const why = { reason: null as EdgeRefusal | null }; try { solve = proposal.type === 'edge' - ? edge.solveEdge(mesh, model.topology, solvedForm(proposal.input), model.noise) + ? edge.solveEdge(mesh, model.topology, solvedForm(proposal.input), model.noise, why) : region.solveRegion(mesh, model.topology, proposal.input, model.noise); } catch (error) { if (proposal.type !== 'edge' || !(error instanceof curve.GuideLengthError)) throw error; tooLong = true; } - const attempt = { input: proposal.input, solve, tooLong }; + const attempt = { input: proposal.input, solve, tooLong, refusal: why.reason }; if (mesh === model.mesh) refineSolves.set(key, { ...attempt, mesh }); latestSolves.set(key, { ...attempt, model: model.mesh }); return solve as Solve; } -const edgeFailure = (input: EdgeInput) => - latestSolves.get(input.segments)?.tooLong ? longGuideNotice : noEdgeNotice; +const edgeFailure = (input: EdgeInput) => { + const latest = latestSolves.get(input.segments); + if (latest?.tooLong) return longGuideNotice; + if (latest?.refusal === 'fit') + return 'The faces cannot meet this edge within Fit. Increase Fit or move the guide.'; + if (latest?.refusal === 'width') + return 'The band is too narrow to rebuild this edge. Increase Width.'; + if (latest?.refusal === 'wall') return noWallNotice; + if (latest?.refusal === 'angle') return wallAngleNotice; + return noEdgeNotice; +}; + +/** What the session asks for while it waits for picks, with how many it has. */ +export function refinePickingPrompt(picking: RefinePicking) { + const wanted = + picking.kind === 'line' ? 2 : picking.kind === 'plane' && picking.from === 'points' ? 3 : 1; + const what = + picking.kind === 'line' + ? 'Click 2 points, on the part or on guide points, for the line.' + : picking.kind === 'align' + ? `Click the point to align this one with ${picking.axis === 'horizontal' ? 'horizontally' : 'vertically'}.` + : picking.kind === 'constrain' + ? 'Click the other segment of the guide.' + : picking.from === 'face' + ? 'Click a flat face of the part for the plane.' + : 'Click 3 points on the part for the plane.'; + return wanted > 1 ? `${what} ${picking.points.length} of ${wanted} picked.` : what; +} + +/** + * What the status line says in a ready session beyond its mode's hint: the picks it waits for, + * else why the selected guide was refused; null for neither. + */ +export function refineStatus(refine: RefineSession) { + if (refine.picking) return `${refinePickingPrompt(refine.picking)} Esc stops picking.`; + return refineFailure(refine); +} + +/** Current refusal for a selected guide, cleared as soon as its input or model changes. */ +export function refineFailure(refine: RefineSession) { + for (const f of refine.features) { + if (!refine.selected.includes(f.id) || f.state !== 'pending' || f.feature.type !== 'edge') + continue; + const input = f.feature.input; + const attempt = latestSolves.get(input.segments); + if ( + attempt && + !attempt.solve && + attempt.model === refine.model?.mesh && + sameSolveInput(attempt.input, input) + ) + return edgeFailure(input); + } + return null; +} /** * Folds one solve pass into the failures already reported, one record per feature id: a feature @@ -6316,6 +6727,35 @@ function wrotePositions(before: RefineMesh, after: RefineMesh, changed: Uint32Ar }); } +/** Keep sketch positions and constraints while a new working mesh changes their nearest faces. */ +function refreshSketchTriangles(feature: RefineFeature, mesh: RefineMesh): RefineFeature { + if (feature.state !== 'pending' || feature.feature.type !== 'edge') return feature; + const input = feature.feature.input; + if ( + !input.plane && + (input.position ?? 'along') === 'along' && + !input.segments.some((s) => s.points.some((p) => p.lock)) + ) + return feature; + const placed = new Map(); + let changed = false; + const segments = input.segments.map((s) => ({ + ...s, + points: s.points.map((p) => { + const known = placed.get(p); + if (known) return known; + const triangle = nearestTriangle(mesh, p.position)?.triangle ?? p.triangle; + const next = triangle === p.triangle ? p : { ...p, triangle }; + if (next !== p) changed = true; + placed.set(p, next); + return next; + }), + })); + return changed + ? { ...feature, feature: { type: 'edge', input: { ...input, segments } } } + : feature; +} + /** * Bakes `targets`, pending features of `features`, into the working surface in list order as one * step. A feature that does not solve stays as it was and is reported. Changes nothing when none @@ -6332,6 +6772,12 @@ function acceptFeatures( let folds = noFolds, skipped = noFolds; const byId = new Map(features.map((f) => [f.id, f])); + const sketchIds = features + .filter( + (f) => + f.state === 'pending' && f.feature.type === 'edge' && (f.origin === 'hand' || f.edited), + ) + .map((f) => f.id); const pass: { id: string; notice: string | null }[] = []; const unchanged = new Set(); let accepted = false; @@ -6422,6 +6868,10 @@ function acceptFeatures( model = { ...model, mesh }; byId.set(feature.id, { ...feature, state: 'accepted' }); } + for (const id of sketchIds) { + const pending = byId.get(id)!; + if (pending.state === 'pending') byId.set(id, refreshSketchTriangles(pending, model.mesh)); + } pass.push({ id: feature.id, notice: null }); accepted = true; } @@ -6803,11 +7253,35 @@ function shareCrease(mesh: RefineMesh, before: RefineMesh) { } /** What undo and redo reset: none of it is recorded in a step. */ -const unsteppedRefine = { draft: null, folds: noFolds, skipped: noFolds, chosenPoint: null }; +const unsteppedRefine = { + draft: null, + folds: noFolds, + skipped: noFolds, + chosenPoint: null, + picking: null, +}; const noEdgeNotice = 'No edge found under this guide. Move it onto the rounded edge or change Width.'; const longGuideNotice = 'This guide is too long for this mesh. Try a shorter guide.'; +const samePointsNotice = 'Pick two different points for the line.'; +const removedConstraintsNotice = 'Removing the sketch plane removed its guide constraints.'; +const conflictNotice = "This conflicts with the guide's other constraints. Nothing was changed."; +const collinearNotice = 'These points are in a line. Pick three points that make a triangle.'; +const curvedFaceNotice = 'This surface is not flat here. Click a flat face, or pick 3 points.'; +const acrossPlaneNotice = 'This line runs across the guide plane. Pick two points along it.'; +const noWallNotice = + 'No wall found beside this guide. Set Position to Along, or turn off Use guide plane.'; +const wallAngleNotice = + 'The wall here is more than 5° off Wall angle. Change Wall angle or set it to Automatic.'; +/** The settings a guide placed by hand starts with: its guide is the edge. */ +const handGuideDefaults = { + position: 'corner', + fit: 0, + path: true, + wallAngle: null, + usePlane: true, +} satisfies Partial; const smallRegionNotice = 'This area is too small to fit a surface. Paint more of it.'; const zeroStrengthNotice = 'This changes nothing at 0 % strength.'; const noChangeNotice = @@ -6879,6 +7353,97 @@ const solvable = (input: EdgeInput) => const samePoint = (a: GuidePoint, b: GuidePoint) => a.triangle === b.triangle && a.position.every((x, k) => x === b.position[k]); +/** The plane the next new guide is drawn on, or null. */ +function nextPlane(refine: RefineSession) { + return refine.planes.find((p) => p.id === refine.edge.plane) ?? null; +} + +/** The plane a click in Edge mode places its point on: the drawn guide's, or the next guide's. */ +export function refineDrawingPlane(refine: RefineSession) { + if (refine.mode !== 'edge') return null; + const guide = drawnGuide(refine); + return guide ? (guide.feature.input.plane ?? null) : nextPlane(refine); +} + +/** `point` projected onto `plane`, on the triangle nearest where it lands. */ +function onPlane(refine: RefineSession, plane: SketchPlane, point: GuidePoint): GuidePoint { + const position = ontoPlane(plane, point.position); + if (position.every((x, k) => x === point.position[k])) return point; + const { mesh } = refine.model!; + return { + ...point, + position, + triangle: (nearestTriangle(mesh, position) ?? point).triangle, + }; +} + +/** + * The guide on `plane`, every point projected onto it and on the triangle nearest where it lands, a + * point's line lock taken into the plane; null takes it off its plane and leaves its points. + */ +function guideOnPlane(refine: RefineSession, input: EdgeInput, plane: SketchPlane | null) { + // Constraints hold only in a plane: off one, they go. + if (!plane) { + const { plane: _, constraints: __, ...rest } = input; + return rest; + } + let conflict = false; + const moved = new Map(); + const segments = input.segments.map((s) => ({ + ...s, + points: s.points.map((p) => { + const same = [...moved.keys()].find((q) => samePoint(q, p)); + if (same) return moved.get(same)!; + let point = onPlane(refine, plane, p); + if ( + p.lock?.kind === 'fixed' && + Math.hypot(...point.position.map((x, i) => x - p.position[i])) > 1e-6 + ) + conflict = true; + if (p.lock?.kind === 'line') { + const { direction: d, origin: o } = p.lock; + const lock = lineThrough( + ontoPlane(plane, o), + ontoPlane(plane, [o[0] + d[0], o[1] + d[1], o[2] + d[2]]), + ); + if (!lock) conflict = true; + const { lock: _, ...bare } = point; + point = lock + ? { ...bare, lock, position: heldPoint(lock, plane, point.position, point.position) } + : bare; + } + moved.set(p, point); + return point; + }), + })); + if (conflict) return null; + const placed = { ...input, segments, plane }; + if (!input.constraints?.length) return placed; + const solved = constrained(refine, placed, {}); + return solved ? { ...placed, segments: solved } : null; +} + +/** + * The guide's segments solved so every constraint holds, each moved point on the triangle nearest + * where it lands; null when they cannot all hold. + */ +function constrained(refine: RefineSession, input: EdgeInput, request: SolveRequest) { + const { mesh } = refine.model!; + return solvedSegments(input, request, (from, position) => ({ + ...from, + position, + triangle: (nearestTriangle(mesh, position) ?? from).triangle, + })); +} + +/** The pending edge's input, or null. */ +function edgeOf(refine: RefineSession, id: string) { + const feature = refine.features.find((f) => f.id === id); + return feature?.state === 'pending' && feature.feature.type === 'edge' + ? feature.feature.input + : null; +} + /** The guide new points extend: the one selected feature when it is an open pending edge. */ function drawnGuide(refine: RefineSession) { if (refine.selected.length !== 1) return null; @@ -6948,6 +7513,41 @@ export function refinePointRemovable(refine: PointSelectionState) { return next !== null && solvable(next); } +/** + * `after`, the guide `before` changed, with the constraints of `before` whose segments and points it + * still has, unchanged, renumbered; the others go. + */ +function withConstraints(before: EdgeInput, after: EdgeInput | null): EdgeInput | null { + if (!after || !before.constraints?.length) return after; + const segmentOf = (i: number) => { + const old = before.segments[i]; + return after.segments.findIndex( + (s) => + s.kind === old.kind && + s.points.length === old.points.length && + s.points.every((p, k) => samePoint(p, old.points[k])), + ); + }; + const pointOf = (segment: number, index: number) => { + const old = before.segments[segment].points[index]; + for (const [s, { points }] of after.segments.entries()) { + const k = points.findIndex((p) => samePoint(p, old)); + if (k >= 0) return { segment: s, index: k }; + } + return null; + }; + const constraints = before.constraints.flatMap((c): GuideConstraint[] => { + if (c.kind === 'align') { + const points = c.points.map((r) => pointOf(r.segment, r.index)); + return points[0] && points[1] ? [{ ...c, points: [points[0], points[1]] }] : []; + } + const segments = c.segments.map(segmentOf); + if (segments.some((i) => i < 0)) return []; + return [{ ...c, segments } as GuideConstraint]; + }); + return { ...after, constraints }; +} + /** * The guide without point `index` of `segment`, or null when no point is left. A point two * segments share leaves the earlier one, which the later then starts from; the closing point opens diff --git a/src/docs/assembly-guides.ts b/src/docs/assembly-guides.ts index a455b3d..1b50ebd 100644 --- a/src/docs/assembly-guides.ts +++ b/src/docs/assembly-guides.ts @@ -541,11 +541,11 @@ export const assemblyGuides: DocArticle[] = [ id: 'guide-an-edge', title: 'Guide an edge', paragraphs: [ - 'A guide marks a softened edge for the tool to rebuild. Lay it along the rounding itself or close beside it.', + 'A guide is the edge you want: place it where the sharp edge is, or should be, and the tool rebuilds the surfaces on either side to meet in it. Position, Fit and the other settings below say how much of the answer comes from the guide and how much from the scan.', ], steps: [ 'In Edge mode, choose Line, Arc, or Spline under Guide.', - 'Click points on the rounded edge. A line takes two points and an arc three. For a spline, place at least two points, then press Enter to finish it.', + 'Click points along the edge. A line takes two points and an arc three. For a spline, place at least two points, then press Enter to finish it. To place points exactly, draw on a sketch plane (see Draw on a sketch plane).', 'Review the preview while the guide is selected. The solved edge is dashed, and the area the guide affects is tinted.', 'Press Enter or choose Accept to keep the edge, or choose Dismiss to discard it. Accept keeps the change in this session, and the edge is then drawn along the mesh edges that were cut. The preview shows the fit, not the cut. If the edge was cut in more than one piece, the breaks are marked and the panel says so, for example The edge was cut in 3 pieces. Undo to adjust the guide, or keep it.', 'Choose Apply to save the accepted changes to the part.', @@ -555,13 +555,95 @@ export const assemblyGuides: DocArticle[] = [ text: 'The tool shows No edge found under this guide. Move it onto the rounded edge or change Width. The guide stays in the session so you can move its points or change Width. If the panel warns that triangles fold over, undo the last step or reduce Width. A very long spline on a fine mesh is refused with This guide is too long for this mesh. Try a shorter guide. Accept leaves a guide or region pending when it would change nothing, for example at 0 % strength, and says so.', }, }, + { + id: 'guide-settings', + title: 'Say where the guide lies', + paragraphs: [ + 'The Edge panel sets these for each selected guide, or for the next guide when none is selected. The two faces either side of the edge are the surface and the wall. On a sketch plane the surface is the face nearer to parallel with the plane; otherwise it is the face nearer to parallel with the plane the guide’s points lie in, or, for a single straight guide, the face with more of the scan.', + ], + table: { + headers: ['Setting', 'Effect'], + rows: [ + [ + 'Position', + 'Where the guide lies on the rounded edge. Corner: the guide is the sharp edge itself, even where it runs in the air over the rounding. Top: the guide lies on the surface where the rounding starts. Bottom: it lies on the wall where the rounding ends. Along: it lies somewhere on the rounding, and the edge is where the two faces meet. The result is always a sharp edge.', + ], + [ + 'Fit', + 'How far, in mm, the edge may move off the guide to fit the scan. At 0 the edge is exactly the guide (Corner), or the guide carried across the rounding (Top, Bottom). Automatic fit reaches as far as the rounding, as Detect and the Crease brush do.', + ], + [ + 'Use guide path', + 'Keeps the guide’s shape. A line stays a line in its direction, an arc keeps its centre and plane, and a spline keeps its shape; any move is one offset for the whole segment. Off, each place along the edge moves on its own and the segment is fitted again.', + ], + [ + 'Use guide plane', + 'For a guide on a sketch plane. With Corner or Top the surface is the plane itself; with Bottom or Along it is fitted from the scan, parallel to the plane.', + ], + [ + 'Wall angle', + 'The angle between the surface and the wall: 90 for a square edge, outside or at the rim of a slot. Automatic reads it from the scan. A set angle builds a straight wall as a plane through the edge, and an arc’s wall round the arc’s axis.', + ], + ], + }, + note: { + title: 'Today’s solve', + text: 'New guides start at Corner, Fit 0 and Use guide path on, so the guide is the edge. For a guide that only marks a rounded edge, choose Along, turn on Automatic fit and turn off Use guide path. When a guide’s settings cannot hold, it is refused, and while it is selected the Refine panel and the status line at the bottom of the window say what to change, for example No wall found beside this guide. Set Position to Along, or turn off Use guide plane.', + }, + }, + { + id: 'sketch-planes', + title: 'Draw on a sketch plane', + paragraphs: [ + 'A sketch plane holds a guide’s points in one flat plane, so a point can sit on the true corner of a rounded edge, off the scan. Planes last until you choose Apply or Cancel, and making one is a step you can undo.', + 'While a guide on a plane is selected, its plane shows as a faint grid round it, with its u axis in red and its v axis in green.', + ], + steps: [ + 'In the Edge panel, open Plane and choose New plane from 3 points, then click three points on the part; or choose New plane from a face, then click a flat face. The first two of three points set the plane’s u axis.', + 'The new plane, Plane 1 and so on, is chosen for the next guide. Choose None to draw on the part again.', + 'Click to place points. Each lands where the pointer’s line of sight meets the plane, also where it misses the part.', + ], + note: { + title: 'Moving a guide onto a plane', + text: 'With guides selected, choosing a plane under Plane moves their points onto it. Lock in a point’s menu does the same for that point’s guide. If the new plane conflicts with locks or constraints, the guide stays where it is. While Refine waits for points, the status line says what to click and how many you have picked. Press Esc to stop picking points for a plane.', + }, + }, + { + id: 'point-locks', + title: 'Lock, move and align points', + paragraphs: [ + 'Right-click a guide point for its menu. Lock puts the guide on a plane (To Plane 1, or To a new plane), slides the point along a line through two points you click on the part or on guide points (To a line), or holds it still (Fixed). Unlock clears the point’s own lock. Align, on a guide on a plane, moves the point level with another point you click: Horizontal takes that point’s v, Vertical its u, and the two stay aligned. Constrain adds a constraint between the two segments that meet at the point. Delete removes the point, as Remove point does.', + 'Click a point to choose it: a move widget appears on it. A free point has arrows along the world axes; a point on a plane has arrows along u and v and a square that moves it in the plane; a point on a line has one arrow along the line; a fixed point has none. Dragging the point itself slides it over the part, on its plane, or along its line. Each drag is one undo step, and Esc during a drag puts the point back.', + ], + }, + { + id: 'constraints', + title: 'Constrain segments', + paragraphs: [ + 'On a guide on a sketch plane, constraints hold its segments in relation to each other, as in a CAD sketch. Right-click a segment’s line, choose a constraint, then click the other segment. Horizontal and Vertical apply to the line at once. From a point’s menu, Constrain applies to the two segments meeting there.', + 'Whenever a point moves, the guide is solved again: the moved point follows the pointer, the rest move as little as they can, and every constraint holds. Where a drag cannot be followed the point stops. A constraint that conflicts with the others is refused and nothing changes.', + 'Each constraint shows a small symbol beside its segment or point, and a fixed point shows an anchor. Right-click a symbol to delete its constraint. Constraints are part of undo, and taking a guide off its plane removes them in the same undo step.', + ], + table: { + headers: ['Constraint', 'Holds'], + rows: [ + ['Parallel ∥, Perpendicular ⊥', 'Two lines at that angle.'], + ['Collinear ⋯', 'Two lines on one straight line.'], + ['Equal =', 'Two lines of one length, or two arcs of one radius.'], + ['Tangent ⌒', 'A line and an arc, or two arcs, that meet, smoothly.'], + ['Concentric ◎', 'Two arcs about one centre.'], + ['Horizontal H, Vertical V', 'A line along the plane’s u or v axis.'], + ['Align ⇹', 'A point level with another, from the point menu.'], + ], + }, + }, { id: 'adjust-a-guide', title: 'Shape and adjust a guide', paragraphs: [ 'With one open pending guide selected, finish its current segment, pressing Enter for a spline. Click farther along the edge to start the next segment. Guide and Joints set how the next segment is drawn. The panel shows Applies to the next segment. Joints sets whether each new joint is Sharp, a corner, or Smooth.', 'Click the first handle of the selected open guide to close it. A single line cannot close. A three-point arc can close directly, and a spline you are still drawing can close after three points. On a multi-segment path, the starting point can finish the segment you are still drawing. If Refine needs to add a closing segment to a finished path, choose Line or Spline under Guide. Press Esc while placing an unfinished guide to discard it.', - 'Drag the points of a selected guide along the surface to adjust it. The preview updates when the pointer rests and when you let go, and Accept waits for it. Each completed drag that moves a handle is one undo step. Click a point of a selected guide to choose it; the chosen point is highlighted. Clicking the first point of an open guide that can close closes it instead. Remove point, Delete, or Backspace removes the chosen point when the guide stays complete, as one undo step. Remove point is in the Edge panel, and in Detect while a point is chosen. Choosing a point needs the pointer. Esc clears the choice first. With no point chosen, Delete dismisses the guide. Width is measured from the edge the tool finds, not from the guide. Automatic width lets the tool estimate how far to either side of that edge it reads and rebuilds the surface, up to 1 mm unless the edge cannot be read within 1 mm. Turn it off to set Width yourself. Strength sets how loosely the edge follows the guide’s line, arc or spline, from no change to fully on it.', + 'Drag the points of a selected guide to adjust it: along the surface, or on the guide’s plane or line. The preview updates when the pointer rests and when you let go, and Accept waits for it. Each completed drag that moves a handle is one undo step. Click a point of a selected guide to choose it; the chosen point is highlighted. Clicking the first point of an open guide that can close closes it instead. Remove point, Delete, or Backspace removes the chosen point when the guide stays complete, as one undo step. Remove point is in the Edge panel, and in Detect while a point is chosen. Choosing a point needs the pointer. Esc clears the choice first. With no point chosen, Delete dismisses the guide. Width is measured from the edge set by Position, before Fit moves it. Along measures from where the scan faces meet. Automatic width lets the tool estimate how far to either side of that edge it reads and rebuilds the surface, up to 1 mm unless the edge cannot be read within 1 mm. Turn it off to set Width yourself. Strength sets how loosely the edge follows the guide’s line, arc or spline, from no change to fully on it.', 'Ends sets Start and End separately for an open guide; the larger point marks the start. Choose Hold when Auto fades an edge that should run sharp into a corner, and Fade when Auto holds one that should die away.', ], table: { diff --git a/src/docs/changelog.ts b/src/docs/changelog.ts index 74e6de3..73517e3 100644 --- a/src/docs/changelog.ts +++ b/src/docs/changelog.ts @@ -19,6 +19,27 @@ export interface Release { // Newest first. Each title must be unique: it names the release's link. export const releases: Release[] = [ + { + date: '2026-11-24', + title: 'Guides you can place exactly', + changes: [ + { + kind: 'improved', + text: 'A Refine edge guide is now the edge itself. Position, Fit, Use guide path and Wall angle say where the guide lies on a rounded edge and how far the result may move to fit the scan. Width follows the guide’s edge around narrow slots. Choose Along with Automatic fit and Use guide path off for the earlier behaviour.', + guide: 'refine', + }, + { + kind: 'new', + text: 'Draw guides on sketch planes made from 3 points or a flat face. Lock points to a plane or a line or fix them, move them with a widget, and right-click a point for Lock, Align, Constrain and Delete.', + guide: 'refine', + }, + { + kind: 'new', + text: 'Constrain segments of a guide on a plane as in a CAD sketch: parallel, perpendicular, collinear, equal, tangent, concentric, horizontal and vertical. The guide stays in place if moving it to another plane would break a lock or constraint.', + guide: 'refine', + }, + ], + }, { date: '2026-11-24', title: 'Longer undo history', diff --git a/src/hooks/useWorkbench.ts b/src/hooks/useWorkbench.ts index f60df51..2d1a7a4 100644 --- a/src/hooks/useWorkbench.ts +++ b/src/hooks/useWorkbench.ts @@ -30,7 +30,8 @@ export const keyTools = { } as const; /** - * What Escape, Delete and Enter do in the Refine tool. Escape dismisses the guide being drawn in + * What Escape, Delete and Enter do in the Refine tool. Escape first stops waiting for picks (a new + * plane, a line lock) and lets go of a chosen point; then it dismisses the guide being drawn in * Edge mode and lets go of (deselects, never dismisses) a crease guide waiting in Brush mode; * otherwise, unless the session holds work leaving would lose, it returns false and the tool is * left. Delete dismisses and Enter accepts the mode's @@ -44,6 +45,10 @@ export function refineKey( const refine = state.refine?.stage === 'ready' ? state.refine : null; const point = refine && chosenRefinePoint(refine); if (action === 'cancel') { + if (refine?.picking) { + state.cancelRefinePicking(); + return true; + } if (point) { state.clearChosenRefinePoint(); return true; diff --git a/src/styles.css b/src/styles.css index 88d05b0..e85dfc2 100644 --- a/src/styles.css +++ b/src/styles.css @@ -4934,6 +4934,46 @@ optgroup { .context-action.danger:not(:disabled) svg { color: inherit; } +.context-hint { + margin: 0; + padding: 2px 9px 4px; + color: var(--muted); + font-size: 10px; +} +.constraint-glyph { + display: inline-flex; + justify-content: center; + width: 14px; + color: var(--muted); + font-size: 12px; + line-height: 1; +} +.refine-constraint-icons { + display: flex; + gap: 2px; + pointer-events: auto; + transform: translate(8px, 8px); +} +.refine-constraint-icon { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 16px; + height: 16px; + padding: 0 3px; + border-radius: 3px; + border: 1px solid var(--border); + background: var(--panel); + color: var(--text); + font-size: 11px; + line-height: 1; + cursor: context-menu; +} +.context-label { + padding: 2px 9px; + color: var(--muted); + font-size: 10px; +} .context-separator { height: 1px; margin: 5px 3px; @@ -6913,3 +6953,7 @@ optgroup { min-width: 28px; } } + +.refine-refusal { + display: block; +} diff --git a/tests/e2e/helpers/refine.ts b/tests/e2e/helpers/refine.ts index 94a28b6..23ca10e 100644 --- a/tests/e2e/helpers/refine.ts +++ b/tests/e2e/helpers/refine.ts @@ -307,6 +307,19 @@ export async function openRefine( await expect.poll(() => inStore(page, (s) => s.refine?.stage ?? null)).toBe('ready'); } +/** + * Sets the next guide to today's solve, where the guide marks the rounding and the edge is where + * the two faces meet: Position Along, Fit automatic, Use guide path off. + */ +export async function useAlongPreset(page: Page) { + await page.getByRole('radio', { name: 'Along', exact: true }).click(); + await page.getByRole('switch', { name: 'Choose fit automatically' }).click(); + await page.getByRole('switch', { name: 'Use guide path' }).click(); + await expect + .poll(() => inStore(page, (s) => s.refine!.edge)) + .toMatchObject({ position: 'along', fit: null, path: false }); +} + /** * Largest distance from their best straight line of the part's vertices on a sharp edge (where * faces around a vertex turn more than 60 degrees), along the middle of the top front edge. diff --git a/tests/e2e/refine.spec.ts b/tests/e2e/refine.spec.ts index 2a440dd..bd838e0 100644 --- a/tests/e2e/refine.spec.ts +++ b/tests/e2e/refine.spec.ts @@ -7,6 +7,7 @@ import { crest, drag, half, + fixture, inEditor, inStore, indexedBlockFixture, @@ -20,7 +21,10 @@ import { plateFixture, screen, surfaceCorner, + useAlongPreset, } from './helpers/refine'; +import { serializeGeometry } from '../../src/core/geometry'; +import { slottedPlate } from '../helpers/soft-edges'; import type { RegionSolve } from '../../src/core/refine-region'; import type { RefineMode } from '../../src/core/store'; import type { BufferGeometry } from 'three'; @@ -183,6 +187,7 @@ const rivetMeasure = (page: Page) => test('guides a straight edge, accepts it and applies it', async ({ page }) => { await openRefine(page); + await useAlongPreset(page); await clickSurface(page, crest(-3)); await clickSurface(page, crest(3)); await expect(page.getByText('0 accepted · 1 proposed')).toBeVisible(); @@ -259,6 +264,36 @@ test('places an arc', async ({ page }) => { expect(standoff).toBeLessThan(sagitta * 1.5); }); +test('previews a closed guide on the plane of a rounded slot', async ({ page }, info) => { + const geometry = serializeGeometry( + slottedPlate(0.35, 0.15, { step: 0.035, ripple: 0.01, noise: 0.006, indexed: true }), + ); + const scene = { ...fixture, parts: [{ ...fixture.parts[0], name: 'Slotted plate', geometry }] }; + await openRefine(page, { scene, view: '7' }); + await page.getByRole('combobox', { name: 'Plane' }).selectOption('points'); + for (const p of [ + [-1, 1, -0.85], + [1, 1, -0.85], + [0, 1, 0.85], + ] as Vec3[]) + await clickSurface(page, p); + await expect.poll(() => inStore(page, (s) => s.refine!.planes.length)).toBe(1); + await inStore(page, (s) => s.setRefineEdge({ width: 0.5, wallAngle: 90, joint: 'smooth' })); + const start: Vec3 = [-1.5, 1, -0.35]; + await clickSurface(page, start); + await clickSurface(page, [1.5, 1, -0.35]); + await page.getByRole('radio', { name: 'Arc', exact: true }).click(); + await clickSurface(page, [1.85, 1, 0]); + await clickSurface(page, [1.5, 1, 0.35]); + await page.getByRole('radio', { name: 'Line', exact: true }).click(); + await clickSurface(page, [-1.5, 1, 0.35]); + await page.getByRole('radio', { name: 'Arc', exact: true }).click(); + await clickSurface(page, [-1.85, 1, 0]); + await clickSurface(page, start); + await expect.poll(() => inStore(page, (s) => s.refine!.features[0]?.curve?.closed)).toBe(true); + await page.screenshot({ path: info.outputPath('slotted-plate.png') }); +}); + test('places a closed path and accepts it', async ({ page }) => { await openRefine(page); await page.getByRole('radio', { name: 'Line', exact: true }).click(); @@ -633,7 +668,9 @@ test('says so when a guide finds no edge', async ({ page }) => { await openRefine(page); await clickSurface(page, front(-2, 0)); await clickSurface(page, front(2, 0)); - await expect(page.getByText('No edge found under this guide.')).toBeVisible(); + await expect( + page.locator('.refine-counts').filter({ hasText: 'No edge found under this guide.' }), + ).toBeVisible(); }); const noEdge = 'No edge found under this guide. Move it onto the rounded edge or change Width.'; @@ -642,7 +679,7 @@ test('says once per guide that it finds no edge', async ({ page }) => { await openRefine(page); await clickSurface(page, front(-2, 1)); await clickSurface(page, front(2, 1)); - await expect(page.getByText(noEdge)).toBeVisible(); + await expect(page.locator('.refine-counts').filter({ hasText: noEdge })).toBeVisible(); await expect.poll(() => noticeCount(page, noEdge)).toBe(1); // A new Width for the same guide fails for the same reason: nothing new to say. await keepDraft(page); @@ -827,7 +864,19 @@ test('settings with no matching selection go to the next guide and region', asyn await page.getByRole('radio', { name: 'Smooth', exact: true }).click(); await expect .poll(() => inStore(page, (s) => s.refine!.edge)) - .toEqual({ kind: 'arc', width: 1.1, joint: 'smooth', strength: 0.5, ends: [null, null] }); + .toEqual({ + kind: 'arc', + width: 1.1, + joint: 'smooth', + strength: 0.5, + ends: [null, null], + position: 'corner', + fit: 0, + path: true, + wallAngle: null, + usePlane: true, + plane: null, + }); // Two arcs: three clicks, then two more. for (const x of [-3, -2, -1, 0, 1]) await clickSurface(page, crest(x)); await expect @@ -1434,3 +1483,213 @@ test('the Refine indexing status distinguishes the gestures that wait from click 'Preparing a dense mesh. Strokes, paint and handle drags wait. Single clicks still work.', ); }); + +/** The first guide's point `index` of segment `segment`, with its lock and the guide's plane. */ +const guidePoint = (page: Page, segment = 0, index = 0) => + inEditor( + page, + (store, [segment, index]) => { + const f = store.useEditor.getState().refine!.features[0]; + if (f?.feature.type !== 'edge') return null; + const { plane, segments } = f.feature.input; + const point = segments[segment].points[index]; + const offPlane = plane + ? Math.abs( + [0, 1, 2].reduce( + (sum, a) => sum + (point.position[a] - plane.origin[a]) * plane.normal[a], + 0, + ), + ) + : null; + return { position: point.position, lock: point.lock ?? null, offPlane }; + }, + [segment, index], + ); + +/** Screen position of the move widget's u arrow, once the overlay has drawn it. */ +async function uArrow(page: Page) { + const read = () => + page.evaluate(async () => { + interface Projected { + x: number; + y: number; + } + interface Arrow { + name: string; + matrixWorld: unknown; + geometry: { + computeBoundingSphere(): void; + boundingSphere: { + center: { clone(): { applyMatrix4(m: unknown): { project(c: unknown): Projected } } }; + }; + }; + } + interface Node { + type: string; + picker?: { translate: { children: Arrow[] } }; + } + const url = performance + .getEntriesByType('resource') + .map((entry) => entry.name) + .find((url) => url.includes('/@react-three_fiber.js'))!; + const root = (await import(url))._roots + .get(document.querySelector('canvas')) + .store.getState(); + const gizmos: Node[] = []; + root.scene.traverse((o: Node) => { + if (o.type === 'TransformControlsGizmo') gizmos.push(o); + }); + const arrow = gizmos[0]?.picker?.translate.children.find((c) => c.name === 'X'); + if (!arrow) return null; + arrow.geometry.computeBoundingSphere(); + const ndc = arrow.geometry.boundingSphere.center + .clone() + .applyMatrix4(arrow.matrixWorld) + .project(root.camera); + const box = document.querySelector('canvas')!.getBoundingClientRect(); + return { + x: box.x + ((ndc.x + 1) * box.width) / 2, + y: box.y + ((1 - ndc.y) * box.height) / 2, + }; + }); + await expect.poll(read, { timeout: 15000 }).not.toBeNull(); + return (await read())!; +} + +/** A plane through three clicks on the block's top face, seen from above. */ +async function topPlane(page: Page) { + await page.getByRole('combobox', { name: 'Plane' }).selectOption('points'); + // The panel and the status line both say what the session waits for. + await expect(page.locator('.refine-picking')).toContainText('Click 3 points on the part'); + await expect(page.locator('.status-context')).toHaveText( + 'Click 3 points on the part for the plane. 0 of 3 picked. Esc stops picking.', + ); + for (const p of [ + [-2, half[1], -1], + [2, half[1], -1], + [0, half[1], 1], + ] as Vec3[]) + await clickSurface(page, p); + await expect.poll(() => inStore(page, (s) => s.refine!.planes.length)).toBe(1); +} + +test('right-click on a guide point opens its menu, which fixes it', async ({ page }) => { + await openRefine(page); + await clickSurface(page, crest(-3)); + await clickSurface(page, crest(3)); + await expect(page.getByText('0 accepted · 1 proposed')).toBeVisible(); + const spot = await screen(page, (await guidePoint(page, 0, 1))!.position); + await page.mouse.click(spot.x, spot.y, { button: 'right' }); + const menu = page.getByRole('menu', { name: 'Guide point actions' }); + await expect(menu).toBeVisible(); + await expect(menu.getByRole('menuitem', { name: 'Unlock' })).toBeDisabled(); + await menu.getByRole('menuitem', { name: 'Fixed' }).click(); + await expect(menu).toBeHidden(); + await expect.poll(async () => (await guidePoint(page, 0, 1))?.lock).toEqual({ kind: 'fixed' }); +}); + +test('the move widget moves a point on a plane, and it stays in the plane', async ({ page }) => { + await openRefine(page, { view: '7' }); + await topPlane(page); + for (const p of [ + [-1, half[1], 0], + [1, half[1], 0], + ] as Vec3[]) + await clickSurface(page, p); + await expect(page.getByText('0 accepted · 1 proposed')).toBeVisible(); + const before = (await guidePoint(page, 0, 1))!; + expect(before.offPlane).toBeLessThan(1e-9); + // A click on the point chooses it and shows its widget. + const spot = await screen(page, before.position); + await page.mouse.click(spot.x, spot.y); + await expect.poll(() => inStore(page, (s) => s.refine!.chosenPoint?.index)).toBe(1); + // The u arrow of the widget, where the gizmo drew it, toward the camera. + const grip = await uArrow(page); + const undo = await inStore(page, (s) => s.refine!.undo.length); + await page.mouse.move(grip.x, grip.y); + await page.mouse.down(); + // Along the arrow, away from the point. + const away = Math.sign(grip.x - spot.x) || 1; + await page.mouse.move(grip.x + 30 * away, grip.y, { steps: 6 }); + await page.mouse.move(grip.x + 60 * away, grip.y, { steps: 6 }); + await page.mouse.up(); + const after = (await guidePoint(page, 0, 1))!; + expect(Math.abs(after.position[0] - before.position[0])).toBeGreaterThan(0.1); + expect(Math.abs(after.position[2] - before.position[2])).toBeLessThan(0.05); + expect(after.offPlane).toBeLessThan(1e-9); + // One drag is one step. + expect(await inStore(page, (s) => s.refine!.undo.length)).toBe(undo + 1); + expect( + await inStore( + page, + (s) => + s.refine!.features[0].feature.type === 'edge' && + s.refine!.features[0].feature.input.segments[0].points.length, + ), + ).toBe(2); +}); + +test('a Parallel constraint holds through a drag, and its icon deletes it', async ({ page }) => { + await openRefine(page, { view: '7' }); + await topPlane(page); + const y = half[1]; + const [a, b, c, d]: Vec3[] = [ + [-1, y, 1], + [-1, y, -1], + [1, y, -1], + [1.3, y, 1.1], + ]; + for (const p of [a, b, c, d]) await clickSurface(page, p); + await expect(page.getByText('0 accepted · 1 proposed')).toBeVisible(); + // The first line's menu, then Parallel, then a click on the third line. + const first = await screen(page, [-1, y, 0]); + await page.mouse.click(first.x, first.y, { button: 'right' }); + const menu = page.getByRole('menu', { name: 'Guide segment actions' }); + await expect(menu).toBeVisible(); + await menu.getByRole('menuitem', { name: 'Parallel' }).click(); + await expect(page.locator('.refine-picking')).toContainText( + 'Click the other segment of the guide.', + ); + await expect(page.locator('.status-context')).toContainText( + 'Click the other segment of the guide.', + ); + await clickSurface(page, [(c[0] + d[0]) / 2, y, (c[2] + d[2]) / 2]); + const parallelism = () => + inStore(page, (s) => { + const f = s.refine!.features[0]; + if (f.feature.type !== 'edge') return null; + const { segments, constraints } = f.feature.input; + const dir = (i: number) => { + const [p, q] = segments[i].points.map((point) => point.position); + const v = [0, 1, 2].map((k) => q[k] - p[k]); + const l = Math.hypot(...v); + return v.map((x) => x / l); + }; + const [u, w] = [dir(0), dir(2)]; + const cross = Math.hypot( + u[1] * w[2] - u[2] * w[1], + u[2] * w[0] - u[0] * w[2], + u[0] * w[1] - u[1] * w[0], + ); + return { kinds: (constraints ?? []).map((k) => k.kind), cross }; + }); + await expect.poll(async () => (await parallelism())?.kinds).toEqual(['parallel']); + expect((await parallelism())!.cross).toBeLessThan(1e-6); + // Dragging the last point keeps the lines parallel. + const before = (await guidePoint(page, 2, 1))!.position; + await drag(page, [d, [1.8, y, 0.4]]); + const after = (await guidePoint(page, 2, 1))!; + expect(Math.hypot(after.position[0] - before[0], after.position[2] - before[2])).toBeGreaterThan( + 0.1, + ); + expect(after.offPlane).toBeLessThan(1e-9); + expect((await parallelism())!.cross).toBeLessThan(1e-6); + // Its icon's menu deletes it. + const icon = page.getByRole('img', { name: 'Parallel constraint' }); + await expect(icon).toBeVisible({ timeout: 15000 }); + await icon.click({ button: 'right' }); + const iconMenu = page.getByRole('menu', { name: 'Constraint actions' }); + await expect(iconMenu).toBeVisible(); + await iconMenu.getByRole('menuitem', { name: 'Delete constraint' }).click(); + await expect.poll(async () => (await parallelism())?.kinds).toEqual([]); +}); diff --git a/tests/helpers/refine-session.ts b/tests/helpers/refine-session.ts index 2e0c72c..40c9942 100644 --- a/tests/helpers/refine-session.ts +++ b/tests/helpers/refine-session.ts @@ -38,6 +38,12 @@ export function setup( return scene; } +/** + * Today's solve for hand-placed guides: the guide marks the rounding and the edge is where the two + * faces meet, as Detect and the crease brush solve. + */ +export const alongPreset = { position: 'along', fit: null, path: false } as const; + /** Chooses the tool and waits for the session's model. */ export async function ready() { editor().setTool('refine'); diff --git a/tests/helpers/soft-edges.ts b/tests/helpers/soft-edges.ts index e37d8b4..6ba3cba 100644 --- a/tests/helpers/soft-edges.ts +++ b/tests/helpers/soft-edges.ts @@ -980,6 +980,51 @@ export function softSlot(fillet: number, options?: SoftOptions) { return extrudedOutline(outline, 1, fillet, options); } +/** A plate with a through-slot. Sweep its closed cross-section around the slot perimeter. */ +export function slottedPlate(radius: number, fillet: number, options?: SoftOptions) { + const surface = new Surface(options); + const { step } = surface.options; + const outline = new Path(true); + outline.line([-1.5, -radius], [1.5, -radius]); + outline.arc([1.5, 0], radius, -Math.PI / 2, Math.PI); + outline.line([1.5, radius], [-1.5, radius]); + outline.arc([-1.5, 0], radius, Math.PI / 2, Math.PI); + const profile = new Path(true); + profile.line([0, 0], [0, 1 - fillet]); + profile.arc([fillet, 1 - fillet], fillet, Math.PI, -Math.PI / 2); + profile.line([fillet, 1], [1, 1]); + profile.line([1, 1], [1, 0]); + profile.line([1, 0], [0, 0]); + const columns = Math.ceil(outline.length / step); + const rings: number[][] = []; + for (const segment of profile.segments) { + const rows = Math.ceil(segment.length / step); + for (let i = 0; i < rows; i++) { + const { + point: [offset, height], + normal: n, + } = segment.at((segment.length * i) / rows); + rings.push( + Array.from({ length: columns }, (_, j) => { + const { point, normal } = outline.at(((j + surface.wobble()) * outline.length) / columns); + return surface.add( + [point[0] + normal[0] * offset, point[1] + normal[1] * offset, height], + [-normal[0] * n[0], -normal[1] * n[0], -n[1]], + ); + }), + ); + } + } + rings.forEach((ring, i) => { + const next = rings[(i + 1) % rings.length]; + ring.forEach((a, j) => { + const k = (j + 1) % columns; + surface.quad(a, next[j], next[k], ring[k]); + }); + }); + return surface.geometry().rotateX(-Math.PI / 2); +} + /** * A prism over the polygon `corners` in (x, z), its upright edges rounded by `rounding` (over 0.5, * so the top's inner rim, 0.5 in from the wall, stays a simple polygon), extruded y 0..1 with the diff --git a/tests/unit/refine-constraints.test.ts b/tests/unit/refine-constraints.test.ts new file mode 100644 index 0000000..4a07b48 --- /dev/null +++ b/tests/unit/refine-constraints.test.ts @@ -0,0 +1,229 @@ +import { describe, expect, it } from 'vitest'; +import type { GuidePoint } from '../../src/core/refine-band'; +import type { GuideKind } from '../../src/core/refine-curve'; +import { + type GuideConstraint, + type GuideShape, + constraintRefusal, + solveGuide, +} from '../../src/core/refine-constraints'; +import { planeOf } from '../../src/core/refine-sketch'; +import type { Vec3 } from '../../src/core/types'; + +/** A plane tilted off the axes, so (u, v) are not world coordinates. */ +const plane = planeOf('p', 'Plane 1', [0.3, -0.2, 0.5], [0.2, 0.3, 1], [1, 0.1, 0])!; +const at = (u: number, v: number): GuidePoint => ({ + triangle: 0, + position: [0, 1, 2].map((a) => plane.origin[a] + u * plane.u[a] + v * plane.v[a]) as Vec3, +}); +const uv = (p: Vec3) => { + const d = [0, 1, 2].map((a) => p[a] - plane.origin[a]); + return [0, 1, 2].reduce((s, a) => s + d[a] * plane.u[a], 0) === undefined + ? [0, 0] + : [ + [0, 1, 2].reduce((s, a) => s + d[a] * plane.u[a], 0), + [0, 1, 2].reduce((s, a) => s + d[a] * plane.v[a], 0), + ]; +}; + +/** A guide through `points` (shared by value), one segment per entry of `kinds`. */ +function shape( + kinds: GuideKind[], + points: GuidePoint[], + constraints: GuideConstraint[], +): GuideShape { + let k = 0; + const segments = kinds.map((kind) => { + const count = kind === 'arc' ? 3 : 2; + const segment = { kind, points: points.slice(k, k + count) }; + k += count - 1; + return segment; + }); + return { segments, plane, constraints }; +} +const solvedUV = (s: GuideShape, request = {}) => solveGuide(s, request)?.map(uv) ?? null; +const angleOf = (a: number[], b: number[]) => Math.atan2(b[1] - a[1], b[0] - a[0]); +const circle = (a: number[], b: number[], c: number[]) => { + const d = 2 * (a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1])); + const sq = (p: number[]) => p[0] ** 2 + p[1] ** 2; + const x = (sq(a) * (b[1] - c[1]) + sq(b) * (c[1] - a[1]) + sq(c) * (a[1] - b[1])) / d; + const y = (sq(a) * (c[0] - b[0]) + sq(b) * (a[0] - c[0]) + sq(c) * (b[0] - a[0])) / d; + return { centre: [x, y], radius: Math.hypot(a[0] - x, a[1] - y) }; +}; +const near = (x: number, y = 0) => expect(Math.abs(x - y)).toBeLessThan(1e-6); + +describe('each constraint alone', () => { + // Three points: two lines meeting at the middle one. + const twoLines = [at(0, 0), at(2, 0.3), at(2.2, 2)]; + + it('horizontal and vertical', () => { + const h = solvedUV( + shape(['line'], [at(0, 0), at(2, 0.3)], [{ id: 'h', kind: 'horizontal', segments: [0] }]), + )!; + near(h[0][1], h[1][1]); + const v = solvedUV( + shape(['line'], [at(0, 0), at(0.3, 2)], [{ id: 'v', kind: 'vertical', segments: [0] }]), + )!; + near(v[0][0], v[1][0]); + }); + + it('parallel and perpendicular', () => { + const four = [at(0, 0), at(2, 0.3), at(2.2, 2), at(0.1, 2.4)]; + const p = solvedUV( + shape(['line', 'line', 'line'], four, [{ id: 'p', kind: 'parallel', segments: [0, 2] }]), + )!; + near(Math.sin(angleOf(p[0], p[1]) - angleOf(p[2], p[3]))); + const q = solvedUV( + shape(['line', 'line'], twoLines, [{ id: 'q', kind: 'perpendicular', segments: [0, 1] }]), + )!; + near(Math.cos(angleOf(q[0], q[1]) - angleOf(q[1], q[2]))); + }); + + it('collinear', () => { + const c = solvedUV( + shape( + ['line', 'line'], + [at(0, 0), at(1, 0.1), at(2, 0.4)], + [{ id: 'c', kind: 'collinear', segments: [0, 1] }], + ), + )!; + const cross = (a: number[], b: number[], q: number[]) => + (b[0] - a[0]) * (q[1] - a[1]) - (b[1] - a[1]) * (q[0] - a[0]); + near(cross(c[0], c[1], c[2])); + }); + + it('equal lines and equal arcs', () => { + const e = solvedUV( + shape(['line', 'line'], twoLines, [{ id: 'e', kind: 'equal', segments: [0, 1] }]), + )!; + near( + Math.hypot(e[1][0] - e[0][0], e[1][1] - e[0][1]), + Math.hypot(e[2][0] - e[1][0], e[2][1] - e[1][1]), + ); + const arcs = [at(0, 0), at(1, 1), at(2, 0), at(3.5, -1.5), at(5, 0)]; + const r = solvedUV( + shape(['arc', 'arc'], arcs, [{ id: 'r', kind: 'equal', segments: [0, 1] }]), + )!; + near(circle(r[0], r[1], r[2]).radius, circle(r[2], r[3], r[4]).radius); + }); + + it('concentric', () => { + const arcs = [at(0, 0), at(1, 1), at(2, 0), at(1.5, -0.6), at(0.4, -0.4)]; + const c = solvedUV( + shape(['arc', 'arc'], arcs, [{ id: 'c', kind: 'concentric', segments: [0, 1] }]), + )!; + const [a, b] = [circle(c[0], c[1], c[2]), circle(c[2], c[3], c[4])]; + near(a.centre[0], b.centre[0]); + near(a.centre[1], b.centre[1]); + }); + + it('tangent, a line and an arc', () => { + const t = solvedUV( + shape( + ['line', 'arc'], + [at(-2, 0.3), at(0, 0), at(1, 1), at(2, 0)], + [{ id: 't', kind: 'tangent', segments: [0, 1] }], + ), + )!; + const { centre } = circle(t[1], t[2], t[3]); + const d = [t[1][0] - t[0][0], t[1][1] - t[0][1]]; + near((d[0] * (t[1][0] - centre[0]) + d[1] * (t[1][1] - centre[1])) / Math.hypot(...d)); + }); + + it('align a point level with another', () => { + const s = shape(['line', 'line'], twoLines, [ + { + id: 'a', + kind: 'align', + axis: 'horizontal', + points: [ + { segment: 1, index: 1 }, + { segment: 0, index: 0 }, + ], + }, + ]); + const a = solvedUV(s, { heavy: [twoLines[0]] })!; + near(a[2][1], a[0][1]); + // The heavy point moves a ten-thousandth as much. + expect(Math.abs(a[0][1])).toBeLessThan(1e-3); + }); + + it('holds a fixed point and a point on its line', () => { + const fixed = { ...at(0, 0), lock: { kind: 'fixed' as const } }; + const lined = { + ...at(2, 0.3), + lock: { kind: 'line' as const, origin: at(2, 0.3).position, direction: plane.v }, + }; + const s = shape(['line'], [fixed, lined], [{ id: 'h', kind: 'horizontal', segments: [0] }]); + const p = solvedUV(s)!; + near(p[0][0]); + near(p[0][1]); + near(p[1][0], 2); + near(p[1][1], 0); + }); +}); + +describe('a slot under a drag', () => { + // Two lines and two arcs: lines parallel, arcs tangent to them and of equal radius. + const points = [ + at(-1.5, -1), + at(1.5, -1.1), + at(2.5, 0.1), + at(1.4, 1), + at(-1.6, 1.05), + at(-2.4, 0), + ]; + const segments = [ + { kind: 'line' as const, points: [points[0], points[1]] }, + { kind: 'arc' as const, points: [points[1], points[2], points[3]] }, + { kind: 'line' as const, points: [points[3], points[4]] }, + { kind: 'arc' as const, points: [points[4], points[5], points[0]] }, + ]; + const constraints: GuideConstraint[] = [ + { id: '1', kind: 'parallel', segments: [0, 2] }, + { id: '2', kind: 'tangent', segments: [0, 1] }, + { id: '3', kind: 'tangent', segments: [1, 2] }, + { id: '4', kind: 'tangent', segments: [2, 3] }, + { id: '5', kind: 'tangent', segments: [3, 0] }, + { id: '6', kind: 'equal', segments: [1, 3] }, + ]; + const slot: GuideShape = { segments, plane, constraints }; + + it('keeps every constraint as a point moves, the point following', () => { + const target = at(2.8, 0.3).position; + const solved = solveGuide(slot, { moved: { point: points[2], target } })!; + expect(solved).not.toBeNull(); + const p = solved.map(uv); + const arcA = circle(p[1], p[2], p[3]), + arcB = circle(p[4], p[5], p[0]); + near(arcA.radius, arcB.radius); + near(Math.sin(angleOf(p[0], p[1]) - angleOf(p[3], p[4]))); + const tangent = (a: number[], b: number[], c: number[]) => { + const d = [b[0] - a[0], b[1] - a[1]]; + return (d[0] * (b[0] - c[0]) + d[1] * (b[1] - c[1])) / Math.hypot(...d); + }; + near(tangent(p[0], p[1], arcA.centre)); + near(tangent(p[3], p[4], arcB.centre)); + // The moved point stays close to where it was asked to go. + const moved = uv(target); + expect(Math.hypot(p[2][0] - moved[0], p[2][1] - moved[1])).toBeLessThan(0.05); + }); +}); + +describe('a conflicting constraint', () => { + it('is refused by the solve, nothing moved', () => { + const a = { ...at(0, 0), lock: { kind: 'fixed' as const } }, + b = { ...at(2, 0.5), lock: { kind: 'fixed' as const } }; + const s = shape(['line'], [a, b], [{ id: 'h', kind: 'horizontal', segments: [0] }]); + expect(solveGuide(s)).toBeNull(); + }); + + it('is refused off a plane and between segments it does not fit', () => { + const s = shape(['line', 'arc'], [at(0, 0), at(1, 0), at(2, 1), at(1, 2)], []); + expect( + constraintRefusal({ ...s, plane: null }, { id: 'x', kind: 'horizontal', segments: [0] }), + ).toMatch(/plane/); + expect(constraintRefusal(s, { id: 'x', kind: 'parallel', segments: [0, 1] })).not.toBeNull(); + expect(constraintRefusal(s, { id: 'x', kind: 'tangent', segments: [0, 1] })).toBeNull(); + }); +}); diff --git a/tests/unit/refine-guide-edge.test.ts b/tests/unit/refine-guide-edge.test.ts new file mode 100644 index 0000000..e89c956 --- /dev/null +++ b/tests/unit/refine-guide-edge.test.ts @@ -0,0 +1,250 @@ +import { describe, expect, it } from 'vitest'; +import type { GuidePoint } from '../../src/core/refine-band'; +import { type EdgeCurve, closestOnCurve, drawnCurve } from '../../src/core/refine-curve'; +import { type EdgeInput, type EdgeRefusal, applyEdge, solveEdge } from '../../src/core/refine-edge'; +import { cloneRefineMesh } from '../../src/core/refine-mesh'; +import { planeOf } from '../../src/core/refine-sketch'; +import type { Vec3 } from '../../src/core/types'; +import { chainPieces, edgeLoops, modelOf, pointOn } from '../helpers/refine'; +import { extrudedProfile, slottedPlate } from '../helpers/soft-edges'; + +type Model = ReturnType; +const scan = { step: 0.06, ripple: 0.01, noise: 0.006 }; + +/** A guide point at `p` itself, on the triangle nearest it, as a click on a sketch plane places it. */ +const at = (model: Model, p: Vec3): GuidePoint => ({ + triangle: pointOn(model.mesh, p).triangle, + position: p, +}); + +/** The guide solved and applied once at its strength, or why it was refused. */ +function outcome(model: Model, input: EdgeInput) { + const why = { reason: null as EdgeRefusal | null }; + const solve = solveEdge(model.mesh, model.topology, input, model.noise, why); + if (!solve) return { solve: null, why: why.reason } as const; + const out = cloneRefineMesh(model.mesh, true); + const result = applyEdge(out, model.topology, solve, input.strength, true); + return { solve, out, result, chain: result.cut?.chain ?? new Uint32Array(0) } as const; +} +type Solved = Extract, { out: unknown }>; + +/** Largest distance from `curve` of the chain's vertices that `inside` admits. */ +function chainFrom(r: Solved, curve: EdgeCurve, inside: (p: number[]) => boolean = () => true) { + const near = new Float64Array(3); + let worst = 0, + seen = 0; + for (const v of r.chain) { + const p = [0, 1, 2].map((a) => r.out.position[v * 3 + a]); + if (!inside(p)) continue; + seen++; + closestOnCurve(curve, p[0], p[1], p[2], near); + worst = Math.max(worst, Math.hypot(p[0] - near[0], p[1] - near[1], p[2] - near[2])); + } + return seen ? worst : NaN; +} + +/** A 90 degree edge along z at the origin: top face y = 0 over x < 0, wall x = 0 below. */ +const corner = (fillet: number) => + modelOf( + extrudedProfile( + [ + [-2, 0], + [0, 0], + [0, -2], + ], + [fillet], + 4, + scan, + ), + ); +const trueCorner = drawnCurve('line', [0, 0, -2, 0, 0, 2], 0.02); +/** Clear of the open guide's tapered ends. */ +const middle = (p: number[]) => Math.abs(p[2]) < 0.8; + +const lineGuide = ( + model: Model, + from: [number, number], + to: [number, number], + settings: Partial, +): EdgeInput => ({ + segments: [{ kind: 'line', points: [at(model, [...from, -1.4]), at(model, [...to, 1.4])] }], + joints: [], + closed: false, + width: 0.6, + strength: 1, + ...settings, +}); + +/** A closed guide round the stadium slot's top rim, at its sharp corner y = 1, on the plane y = 1. */ +function slotGuide(model: Model, settings: Partial): EdgeInput { + const p = (x: number, z: number) => at(model, [x, 1, z]); + const plane = planeOf('plane', 'Plane 1', [0, 1, 0], [0, 1, 0], [1, 0, 0])!; + return { + segments: [ + { kind: 'line', points: [p(-1.5, -0.35), p(1.5, -0.35)] }, + { kind: 'arc', points: [p(1.5, -0.35), p(1.85, 0), p(1.5, 0.35)] }, + { kind: 'line', points: [p(1.5, 0.35), p(-1.5, 0.35)] }, + { kind: 'arc', points: [p(-1.5, 0.35), p(-1.85, 0), p(-1.5, -0.35)] }, + ], + joints: ['smooth', 'smooth', 'smooth', 'smooth'], + closed: true, + width: 0.5, + strength: 1, + position: 'corner', + fit: 0, + path: true, + plane, + usePlane: true, + ...settings, + }; +} + +/** Distance from the slot's sharp top rim: the stadium's outline at y = 1. */ +function offSlotRim(p: number[]) { + const [x, y, z] = p; + const ax = Math.abs(x); + const flat = ax <= 1.5 ? Math.abs(Math.abs(z) - 0.35) : Math.abs(Math.hypot(ax - 1.5, z) - 0.35); + return Math.hypot(flat, y - 1); +} + +describe('a guide placed at the corner of a slot on a sketch plane', () => { + const model = modelOf(slottedPlate(0.35, 0.15, { ...scan, step: 0.035 })); + + for (const wallAngle of [90, null]) + it(`cuts the edge on the guide in one piece at wall angle ${wallAngle ?? 'Automatic'}`, () => { + const r = outcome(model, slotGuide(model, { wallAngle })); + expect(r.solve, String(r.why)).not.toBeNull(); + const solved = r as Solved; + let worst = 0; + for (const v of solved.chain) + worst = Math.max(worst, offSlotRim([0, 1, 2].map((a) => solved.out.position[v * 3 + a]))); + expect(solved.result.pieces).toBe(1); + expect(chainPieces(solved.out, solved.chain)).toEqual([ + { size: solved.chain.length, ends: 0 }, + ]); + expect(edgeLoops(solved.result.cut!.edges, solved.chain)).toEqual([solved.chain.length]); + expect(worst).toBeLessThan(0.002); + // The unrounded top starts one fillet radius outside the slot wall. + const tops: number[] = []; + const members = new Set(solved.solve.bands.flatMap((b) => [...b.vertices])); + for (const v of members) { + const [x, y, z] = model.mesh.position.subarray(v * 3, v * 3 + 3); + const radius = Math.hypot(Math.max(0, Math.abs(x) - 1.5), z); + if (y > 0.95 && radius >= 0.35 + 0.15) + tops.push(Math.abs(solved.out.position[v * 3 + 1] - 1)); + } + expect(tops.length).toBeGreaterThan(100); + const top = Math.max(...tops); + expect(top).toBeLessThan(0.002); + }); +}); + +describe('Position on a filleted edge', () => { + const model = corner(0.15); + + it('puts the edge at the true corner from the top or the bottom of the fillet', () => { + const placed: ['top' | 'bottom', [number, number]][] = [ + ['top', [-0.15, 0]], + ['bottom', [0, -0.15]], + ]; + for (const [position, from] of placed) { + const r = outcome(model, lineGuide(model, from, from, { position, fit: 0, path: true })); + expect(r.solve, `${position}: ${r.why}`).not.toBeNull(); + expect(chainFrom(r as Solved, trueCorner, middle)).toBeLessThan(0.005); + } + }); + + it('cuts exactly on a corner guide in the air over the rounding', () => { + const r = outcome( + model, + lineGuide(model, [0, 0], [0, 0], { position: 'corner', fit: 0, path: true }), + ); + expect(chainFrom(r as Solved, trueCorner, middle)).toBeLessThan(0.002); + }); + + it("solves Along at today's reach as today", () => { + const guide = lineGuide(model, [-0.04, -0.04], [-0.04, -0.04], {}); + const today = outcome(model, guide) as Solved; + const along = outcome(model, { ...guide, position: 'along', fit: 0.36 }) as Solved; + const curve = today.solve.curve; + expect(chainFrom(along, curve, middle)).toBeLessThan(0.005); + expect(chainFrom(today, along.solve.curve, middle)).toBeLessThan(0.005); + }); +}); + +describe('Fit', () => { + const model = corner(0.15); + const off = (fit: number) => { + const r = outcome( + model, + lineGuide(model, [-0.2, 0], [-0.2, 0], { position: 'corner', fit, path: true }), + ); + expect(r.solve, String(r.why)).not.toBeNull(); + const p = (r as Solved).solve.curve.points; + return Math.hypot(p[0], p[1]); + }; + + it('names Fit when the guide is too far above the scan to rebuild', () => { + const r = outcome( + model, + lineGuide(model, [0, 0.34], [0, 0.34], { position: 'corner', fit: 0, path: true }), + ); + expect(r.why).toBe('fit'); + }); + + it('measures Width from the placed guide even when Fit moves the edge', () => { + const r = outcome( + model, + lineGuide(model, [-0.2, 0], [-0.2, 0], { position: 'corner', fit: 0.3, path: true }), + ); + const band = r.solve!.bands[0]; + for (const v of band.vertices) { + const [x, y] = model.mesh.position.subarray(v * 3, v * 3 + 2); + expect(Math.hypot(x + 0.2, y)).toBeLessThanOrEqual(band.width + 1e-8); + } + }); + + it('keeps the edge on the guide at 0', () => expect(off(0)).toBeCloseTo(0.2, 6)); + it('moves it to the corner when Fit reaches it', () => expect(off(0.3)).toBeLessThan(0.01)); + it('moves it no farther than Fit', () => expect(off(0.1)).toBeCloseTo(0.1, 3)); +}); + +describe('Use guide path', () => { + const model = corner(0.15); + + it('keeps a carried arc in its original plane', () => { + const model = modelOf(slottedPlate(0.35, 0.15, { ...scan, step: 0.035 })); + const guide = slotGuide(model, { position: 'top', usePlane: false, closed: false, joints: [] }); + const y = 1.015; + const points = [ + [1.5, y, -0.5], + [2, y, 0], + [1.5, y, 0.5], + ].map((p) => at(model, p as Vec3)); + const r = outcome(model, { ...guide, segments: [{ kind: 'arc', points }] }); + expect(r.solve, String(r.why)).not.toBeNull(); + const p = r.solve!.curve.points; + for (let k = 1; k < p.length; k += 3) expect(p[k]).toBeCloseTo(y, 9); + }); + + it('keeps a line straight and parallel to itself', () => { + // A guide on the rounding, a little askew to the edge. + const guide = lineGuide(model, [-0.06, -0.01], [-0.03, -0.02], { + position: 'along', + fit: 0.3, + path: true, + }); + const r = outcome(model, guide) as Solved; + const p = r.solve.curve.points, + n = p.length / 3; + const d = [0, 1, 2].map((a) => p[(n - 1) * 3 + a] - p[a]); + const g = [0.03, -0.01, 2.8]; + const cross = [d[1] * g[2] - d[2] * g[1], d[2] * g[0] - d[0] * g[2], d[0] * g[1] - d[1] * g[0]]; + expect(Math.hypot(...cross) / (Math.hypot(...d) * Math.hypot(...g))).toBeLessThan(1e-9); + for (let k = 1; k < n - 1; k++) { + const t = (p[k * 3 + 2] - p[2]) / d[2]; + const off = [0, 1, 2].map((a) => p[k * 3 + a] - p[a] - t * d[a]); + expect(Math.hypot(...off)).toBeLessThan(1e-9); + } + }); +}); diff --git a/tests/unit/refine-session.test.ts b/tests/unit/refine-session.test.ts index b593981..276f3c7 100644 --- a/tests/unit/refine-session.test.ts +++ b/tests/unit/refine-session.test.ts @@ -49,6 +49,7 @@ import { useXR } from '../../src/core/xr-session'; import type { Joint, Part } from '../../src/core/types'; import { changedVertices, closed, edgeNeighbours, modelOf, splitEdge } from '../helpers/refine'; import { + alongPreset, boxPart, differingAttributes, editor, @@ -120,6 +121,12 @@ describe('refine session lifecycle', () => { joint: 'sharp', strength: 1, ends: [null, null], + position: 'corner', + fit: 0, + path: true, + wallAngle: null, + usePlane: true, + plane: null, }); expect(session().region).toEqual({ treatment: 'smooth', @@ -410,6 +417,7 @@ describe('refine session steps', () => { selected: [], triangles: [], drawing: false, + planes: [], }); const models = [start]; for (let i = 0; i < 4; i++) models.push(movedModel(models[i], [i], [0, 0.01, 0])); @@ -514,6 +522,7 @@ describe('refine guides', () => { it('previews a line guide without changing the model, then bakes it on accept', async () => { setup([boxPart()], ['box']); await ready(); + editor().setRefineEdge(alongPreset); const model = session().model!; editor().addRefinePoint(crest(-1.6)); editor().addRefinePoint(crest(1.6)); @@ -1306,6 +1315,7 @@ describe('refine lifecycle edges', () => { selected: [], triangles: [], drawing: false, + planes: [], }); const oversized = { ...start, @@ -1371,7 +1381,7 @@ describe('refine session integrity', { timeout: 20_000 }, () => { it('closes a spline being drawn on its first point as one step, and solves it on a rim', async () => { setup([canPart()], ['can']); await ready(); - editor().setRefineEdge({ kind: 'spline', joint: 'smooth', width: 0.6 }); + editor().setRefineEdge({ kind: 'spline', joint: 'smooth', width: 0.6, ...alongPreset }); const points = [0, 1, 2, 3, 4].map((i) => rim((2 * Math.PI * i) / 5)); for (const point of points) editor().addRefinePoint(point); const undo = session().undo.length; @@ -2050,6 +2060,7 @@ describe('refine session integrity', { timeout: 20_000 }, () => { it('says failure before pieces before skipped triangles and undo removes the cut marks', async () => { setup([boxPart()], ['box']); await ready(); + editor().setRefineEdge(alongPreset); editor().addRefinePoint(top(-1)); editor().addRefinePoint(top(1)); const failed = session().selected[0]; diff --git a/tests/unit/refine-sketch-session.test.ts b/tests/unit/refine-sketch-session.test.ts new file mode 100644 index 0000000..54e6d48 --- /dev/null +++ b/tests/unit/refine-sketch-session.test.ts @@ -0,0 +1,343 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { EdgeInput } from '../../src/core/refine-edge'; +import { nearestTriangle } from '../../src/core/refine-sketch'; +import type { GuidePoint } from '../../src/core/refine-band'; +import { refineStatus, useEditor } from '../../src/core/store'; +import type { Vec3 } from '../../src/core/types'; +import { boxPart, editor, ready, session, setup, surfacePoint } from '../helpers/refine-session'; +import { useActivity } from '../../src/core/activity'; + +const initial = useEditor.getState(); +afterEach(() => { + editor().cancelRefine(); + useEditor.setState(initial); + useActivity.setState({ tasks: [], notifications: [] }); +}); + +/** The box's top face, y = 1.5, as a click on it. */ +const top = (x: number, z = 0) => surfacePoint([x, 1.5, z]); +const guide = (id = session().selected[0]): EdgeInput => { + const feature = session().features.find((f) => f.id === id)!.feature; + if (feature.type !== 'edge') throw new Error('not an edge'); + return feature.input; +}; +const pointOf = (segment: number, index: number) => guide().segments[segment].points[index]; +const offPlane = (p: Vec3) => { + const { origin, normal } = guide().plane!; + return Math.abs([0, 1, 2].reduce((sum, a) => sum + (p[a] - origin[a]) * normal[a], 0)); +}; +/** A point at `p` exactly, on the triangle the surface click nearest it found. */ +const at = (p: Vec3): GuidePoint => ({ triangle: surfacePoint(p).triangle, position: p }); + +/** A plane through three clicks on the box's top face. */ +function topPlane() { + editor().startRefinePicking({ kind: 'plane', from: 'points', points: [], lock: null }); + for (const p of [top(-1, -0.5), top(1, -0.5), top(0, 0.5)]) editor().pickRefine(p); + return session().planes.at(-1)!; +} + +describe('sketch planes', () => { + it('makes a plane from 3 points, chosen for the next guide, and undoes it', async () => { + setup([boxPart()], ['box']); + await ready(); + const undo = session().undo.length; + const plane = topPlane(); + expect(session().picking).toBeNull(); + expect(plane.name).toBe('Plane 1'); + expect(Math.abs(plane.normal[1])).toBeGreaterThan(0.999); + expect(plane.u[0]).toBeGreaterThan(0.999); + expect(session().edge.plane).toBe(plane.id); + expect(session().undo.length).toBe(undo + 1); + editor().undoRefine(); + expect(session().planes).toEqual([]); + editor().redoRefine(); + expect(session().planes).toEqual([plane]); + }); + + it('fits a plane to a flat face from one click', async () => { + setup([boxPart()], ['box']); + await ready(); + editor().startRefinePicking({ kind: 'plane', from: 'face', points: [], lock: null }); + editor().pickRefine(top(0.2, 0.1)); + const plane = session().planes[0]; + expect(plane.normal[1]).toBeGreaterThan(0.999); + expect(Math.abs(plane.origin[1] - 1.5)).toBeLessThan(0.01); + }); + + it('refuses a plane through points in a line and keeps nothing', async () => { + setup([boxPart()], ['box']); + await ready(); + editor().startRefinePicking({ kind: 'plane', from: 'points', points: [], lock: null }); + for (const x of [-1, 0, 1]) editor().pickRefine({ ...top(x), position: [x, 1.5, 0] }); + expect(session().planes).toEqual([]); + expect(session().picking).toBeNull(); + }); + + it('draws a guide on the plane, its points in it wherever they were placed', async () => { + setup([boxPart()], ['box']); + await ready(); + const plane = topPlane(); + editor().addRefinePoint(at([-1, 1.6, 0.9])); + editor().addRefinePoint(at([1, 1.4, 1.1])); + expect(guide().plane).toEqual(plane); + for (const p of guide().segments[0].points) expect(offPlane(p.position)).toBeLessThan(1e-9); + }); + + it('puts a guide on a plane from the point menu, and off it', async () => { + setup([boxPart()], ['box']); + await ready(); + editor().addRefinePoint(top(-1, 0.9)); + editor().addRefinePoint(top(1, 0.9)); + const id = session().selected[0]; + editor().setRefinePlane(null); + const plane = topPlane(); + // The plane was made for the next guide; the drawn one stays where it was until locked. + expect(guide(id).plane).toBeUndefined(); + editor().setRefineGuidePlane(id, plane.id); + for (const p of guide(id).segments[0].points) expect(offPlane(p.position)).toBeLessThan(1e-9); + editor().undoRefine(); + expect(guide(id).plane).toBeUndefined(); + }); +}); + +describe('point locks', () => { + async function planedGuide() { + setup([boxPart()], ['box']); + await ready(); + topPlane(); + editor().addRefinePoint(at([-1, 1.5, 0.9])); + editor().addRefinePoint(at([1, 1.5, 0.9])); + return session().selected[0]; + } + + it('slides a point locked to a line along it, in the plane', async () => { + const id = await planedGuide(); + editor().startRefinePicking({ + kind: 'line', + point: { feature: id, segment: 0, index: 1 }, + points: [], + }); + editor().pickRefine(at([1, 1.5, 0.9])); + editor().pickRefine(at([1, 1.5, -0.5])); + const lock = pointOf(0, 1).lock; + expect(lock?.kind).toBe('line'); + editor().moveRefinePoint(id, 0, 1, at([1.3, 1.5, 0.2]), true); + const p = pointOf(0, 1).position; + // On the line, which lies in the plane through the clicks, not quite level. + if (lock?.kind !== 'line') return; + const d = [0, 1, 2].map((a) => p[a] - lock.origin[a]); + const t = [0, 1, 2].reduce((sum, a) => sum + d[a] * lock.direction[a], 0); + expect(Math.hypot(...d.map((x, a) => x - t * lock.direction[a]))).toBeLessThan(1e-9); + expect(Math.abs(p[0] - 1)).toBeLessThan(0.01); + expect(Math.abs(p[2] - 0.2)).toBeLessThan(0.01); + expect(offPlane(p)).toBeLessThan(1e-9); + expect(pointOf(0, 1).lock).toEqual(lock); + }); + + it('keeps sketch locks and refreshes triangle seeds after a neighbouring cut', async () => { + setup([boxPart()], ['box']); + await ready(); + topPlane(); + for (const x of [-0.6, 0.7]) editor().addRefinePoint(at([x, 1.5, 1])); + const id = session().selected[0]; + editor().lockRefinePoint(id, 0, 0, { kind: 'fixed' }); + const before = guide(id); + editor().setRefineMode('brush'); + editor().setRefineBrush({ kind: 'crease', strength: 1 }); + editor().setRefineBrushRadius(0.4); + const crest = (x: number) => surfacePoint([x, 1.5 - 0.0879, 1 - 0.0879]); + editor().beginRefineStroke(crest(-1.5)); + for (let x = -1.4; x <= 1.5; x += 0.1) editor().moveRefineStroke(crest(x)); + editor().endRefineStroke(); + expect(session().features.some((f) => f.state === 'accepted')).toBe(true); + const points = guide(id).segments[0].points; + expect(points.map((p) => p.position)).toEqual(before.segments[0].points.map((p) => p.position)); + expect(points[0].lock).toEqual({ kind: 'fixed' }); + for (const point of points) + expect(point.triangle).toBe(nearestTriangle(session().model!.mesh, point.position)!.triangle); + editor().undoRefine(); + expect(guide(id)).toEqual(before); + }); + + it('keeps a fixed point where it is, until unlocked', async () => { + const id = await planedGuide(); + const before = pointOf(0, 0).position; + editor().lockRefinePoint(id, 0, 0, { kind: 'fixed' }); + editor().moveRefinePoint(id, 0, 0, at([-1.5, 1.5, 0.5]), true); + expect(pointOf(0, 0).position).toEqual(before); + editor().lockRefinePoint(id, 0, 0, null); + expect(pointOf(0, 0).lock).toBeUndefined(); + editor().moveRefinePoint(id, 0, 0, at([-1.5, 1.5, 0.5]), true); + expect(pointOf(0, 0).position).not.toEqual(before); + expect(offPlane(pointOf(0, 0).position)).toBeLessThan(1e-9); + editor().undoRefine(); + editor().undoRefine(); + expect(pointOf(0, 0).lock).toEqual({ kind: 'fixed' }); + }); + + it('moves a point of a guide on a plane within the plane', async () => { + const id = await planedGuide(); + editor().moveRefinePoint(id, 0, 1, at([1.2, 1.7, 0.5]), true); + expect(offPlane(pointOf(0, 1).position)).toBeLessThan(1e-9); + }); + + it('deletes a point and puts it back on undo', async () => { + const id = await planedGuide(); + editor().addRefinePoint(at([1, 1.5, -0.5])); + expect(guide(id).segments).toHaveLength(2); + editor().removeRefinePoint(id, 1, 1); + expect(guide(id).segments).toHaveLength(1); + editor().undoRefine(); + expect(guide(id).segments).toHaveLength(2); + }); + + it('keeps the chosen point chosen while it moves, for its widget', async () => { + const id = await planedGuide(); + editor().clickRefinePoint(id, 0, 1); + editor().moveRefinePoint(id, 0, 1, at([1.2, 1.5, 0.5]), true); + expect(session().chosenPoint).toEqual({ feature: id, segment: 0, index: 1 }); + }); +}); + +describe('constraints', () => { + /** A U of three lines on the top face's plane: A to B, B to C, C to D. */ + async function uGuide() { + setup([boxPart()], ['box']); + await ready(); + topPlane(); + for (const p of [ + [-1, 1.5, 0.5], + [-1, 1.5, -0.5], + [1, 1.5, -0.5], + [1.2, 1.5, 0.6], + ] as Vec3[]) + editor().addRefinePoint(at(p)); + return session().selected[0]; + } + const directionOf = (segment: number) => { + const [a, b] = guide().segments[segment].points.map((p) => p.position); + const d = [0, 1, 2].map((k) => b[k] - a[k]); + const length = Math.hypot(...d); + return d.map((x) => x / length); + }; + const crossLength = (a: number[], b: number[]) => + Math.hypot(a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]); + + it('keeps two lines parallel through a drag, and through undo and redo', async () => { + const id = await uGuide(); + expect(editor().addRefineConstraint(id, { kind: 'parallel', segments: [0, 2] })).toBe(true); + expect(crossLength(directionOf(0), directionOf(2))).toBeLessThan(1e-6); + editor().moveRefinePoint(id, 2, 1, at([1.5, 1.5, 0.9]), true); + expect(crossLength(directionOf(0), directionOf(2))).toBeLessThan(1e-6); + for (const s of guide().segments) + for (const p of s.points) expect(offPlane(p.position)).toBeLessThan(1e-9); + editor().undoRefine(); + expect(guide().constraints).toHaveLength(1); + editor().undoRefine(); + expect(guide().constraints ?? []).toHaveLength(0); + editor().redoRefine(); + expect(guide().constraints).toHaveLength(1); + }); + + it('refuses a constraint that conflicts, changing nothing', async () => { + const id = await uGuide(); + editor().lockRefinePoint(id, 0, 0, { kind: 'fixed' }); + editor().lockRefinePoint(id, 0, 1, { kind: 'fixed' }); + const before = session().features; + // Segment 0 runs along z; u runs along x, so Horizontal cannot hold with both ends fixed. + expect(editor().addRefineConstraint(id, { kind: 'horizontal', segments: [0] })).toBe(false); + expect(session().features).toBe(before); + }); + + it('refuses a rotated plane that conflicts with a fixed horizontal line', async () => { + const id = await uGuide(); + expect(editor().addRefineConstraint(id, { kind: 'horizontal', segments: [1] })).toBe(true); + editor().lockRefinePoint(id, 1, 0, { kind: 'fixed' }); + editor().lockRefinePoint(id, 1, 1, { kind: 'fixed' }); + const before = session(); + editor().startRefinePicking({ kind: 'plane', from: 'points', points: [], lock: id }); + for (const p of [top(-1, -0.5), top(-1, 0.5), top(1, 0.5)]) editor().pickRefine(p); + expect(session().features).toBe(before.features); + expect(session().planes).toBe(before.planes); + expect(session().undo).toBe(before.undo); + editor().setRefineGuidePlane(id, null); + expect(guide().constraints).toBeUndefined(); + expect(useActivity.getState().notifications.map((n) => n.message)).toContainEqual( + expect.stringMatching(/removed its guide constraints/), + ); + editor().undoRefine(); + expect(guide()).toEqual(before.features[0].feature.input); + }); + + it('aligns a point level with another it is clicked onto, and keeps it so', async () => { + const id = await uGuide(); + editor().startRefinePicking({ + kind: 'align', + axis: 'horizontal', + point: { feature: id, segment: 2, index: 1 }, + points: [], + }); + editor().pickRefine(pointOf(0, 1), { point: { feature: id, segment: 0, index: 1 } }); + const plane = guide().plane!; + const v = (p: Vec3) => [0, 1, 2].reduce((s, a) => s + (p[a] - plane.origin[a]) * plane.v[a], 0); + expect(Math.abs(v(pointOf(2, 1).position) - v(pointOf(0, 1).position))).toBeLessThan(1e-6); + expect(guide().constraints?.[0]).toMatchObject({ kind: 'align', axis: 'horizontal' }); + editor().moveRefinePoint(id, 0, 1, at([-1.2, 1.5, -0.8]), true); + expect(Math.abs(v(pointOf(2, 1).position) - v(pointOf(0, 1).position))).toBeLessThan(1e-6); + }); + + it('keeps the constraints of the segments a deleted point leaves', async () => { + const id = await uGuide(); + editor().addRefineConstraint(id, { kind: 'parallel', segments: [0, 2] }); + editor().addRefineConstraint(id, { kind: 'horizontal', segments: [1] }); + editor().removeRefinePoint(id, 2, 1); + expect(guide().segments).toHaveLength(2); + expect(guide().constraints).toEqual([ + expect.objectContaining({ kind: 'horizontal', segments: [1] }), + ]); + editor().removeRefineConstraint(id, guide().constraints![0].id); + expect(guide().constraints).toEqual([]); + }); + + it('refuses a constraint on a guide with no plane', async () => { + setup([boxPart()], ['box']); + await ready(); + editor().addRefinePoint(top(-1, 0.5)); + editor().addRefinePoint(top(1, 0.5)); + expect( + editor().addRefineConstraint(session().selected[0], { kind: 'horizontal', segments: [0] }), + ).toBe(false); + expect(useActivity.getState().notifications.map((n) => n.message)).toContainEqual( + expect.stringMatching(/sketch plane/), + ); + }); +}); + +describe('the status line', () => { + it('says what the session waits for while it picks, and counts the picks', async () => { + setup([boxPart()], ['box']); + await ready(); + expect(refineStatus(session())).toBeNull(); + editor().startRefinePicking({ kind: 'plane', from: 'points', points: [], lock: null }); + expect(refineStatus(session())).toBe( + 'Click 3 points on the part for the plane. 0 of 3 picked. Esc stops picking.', + ); + editor().pickRefine(top(-1, -0.5)); + expect(refineStatus(session())).toMatch(/1 of 3 picked/); + editor().cancelRefinePicking(); + expect(refineStatus(session())).toBeNull(); + }); + + it('says why the selected guide was refused', async () => { + setup([boxPart()], ['box']); + await ready(); + // On the flat middle of the top face there is no edge to rebuild. + editor().addRefinePoint(top(-1, 0)); + editor().addRefinePoint(top(1, 0)); + await vi.waitFor(() => + expect(refineStatus(session())).toMatch(/^No edge found under this guide/), + ); + editor().selectRefine([]); + expect(refineStatus(session())).toBeNull(); + }); +});