From 032fdfbb28e833aab131db804513848e51950c47 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 17 Nov 2026 23:01:46 -0800 Subject: [PATCH 01/25] Add the design for warp handles, feathering and grid contrast --- .../specs/2026-11-17-warp-handles-design.md | 283 ++++++++++++++++++ 1 file changed, 283 insertions(+) create mode 100644 docs/superpowers/specs/2026-11-17-warp-handles-design.md diff --git a/docs/superpowers/specs/2026-11-17-warp-handles-design.md b/docs/superpowers/specs/2026-11-17-warp-handles-design.md new file mode 100644 index 0000000..83c2398 --- /dev/null +++ b/docs/superpowers/specs/2026-11-17-warp-handles-design.md @@ -0,0 +1,283 @@ +# Warp: visible grid, fitted brush, handles with reach, feathered edges + +Status: design, revised after review. Date: 2026-11-17. Follows +[the mesh warp design](2026-11-17-mesh-warp-design.md). + +## Intent + +Warp shipped and the product owner used it on real models: mostly 32 mm to 100 mm +miniatures. Six problems came back. This change fixes them without changing what Warp is: a +grid over a part, control points on it, an as-rigid-as-possible solve, a bake on Apply. + +| # | Reported | +| --- | ------------------------------------------------------------------------------------------------- | +| 1 | The grid has almost no contrast over the model, least of all with Distinct part colors. | +| 2 | The region brush slider is too coarse: good sizes for these models sit in a sliver of its travel. | +| 3 | With Whole part there are no pins, so dragging one point just moves the model. | +| 4 | A control point moves a spike. Its radius and falloff need to be configurable. | +| 5 | A painted region warps with a hard crease at its perimeter. An option should feather it. | +| 6 | Several points in a row give a row of peaks. A line or an area should move as one. | + +## Goals + +- Each of the six, as the product owner described it. +- Everything a session could do before still works. A point with radius 0 solves exactly as + today, and adding an unmoved point never changes the surface. + +## Non-goals + +- Phase 2 topology change, MCP tools, headset support, re-editable warps. +- Changing the Align tool's contact brush: its slider and its radius are untouched. +- Rotating or scaling a single line or area handle about itself. Handles translate. + +## Anti-goals + +- Moving a vertex outside the region the user can see. With feathering on, the feather band + is shown and is part of the region; everything beyond it, and its outer border, keeps + exact position and normal bits. +- Slower drags. A drag frame must cost no more than today for the same grid, measured. +- Export bytes changing for parts that were not warped. + +## How it works today + +- `warp-region.ts` welds the part and marks welded vertices Outside, Border or Interior from + the painted faces. Its adjacency covers region triangles only. `warp-grid.ts` simplifies + the region to roughly 60–4000 nodes (real scan vertices; `LockBorder` can exceed the + target); border nodes are `fixed`. +- `warp-solve.ts` runs ARAP on the grid. A `WarpConstraint` ties a weighted set of nodes to + a world target at strength 1000; weights are normalised, so they cannot carry stiffness. + Fixed nodes are left out of the system. A control point is the barycentric sum of three + skinned triangle corners (up to 12 nodes, plus a part held by fixed corners), and the + constraint models exactly that. +- `warp-bind.ts` skins every dense vertex to its 4 nearest nodes by surface distance. + `warp-evaluate.ts` writes skinned positions for interior vertices, then normals and folds. +- `store.ts` holds the `WarpSession`: `points: WarpPoint[]` (face, barycentric, binding, + pin, target), `gapTargets`, session undo. A new point's `pin` is the surface where it is + when clicked, not rest. `transform-selection.ts` presents selected points to every + transform tool as position-only targets, and `moveWarpPoints` takes one target per point. +- `WarpOverlay.tsx` draws grid edges as straight 1 px chords between nodes, `#b9e3dd` at + 55 % opacity. The Distinct palette is OKLCH lightness 0.62–0.84, nearly the same tone. +- `SurfaceBrushControls.tsx` (shared with Align) has a linear 0.1–20 mm slider over the + shared `brushRadius`. + +## Design + +### 1. Grid contrast + +Draw grid edges as fat lines (`LineSegments2` and `LineMaterial`): an opaque dark core +about 1.5 px wide over a light casing about 3.5 px wide at partial opacity, both from one +shared, preallocated endpoint buffer (two endpoints per edge) updated in place per frame. +The far side stays hidden. + +A grid edge is a straight chord between two scan vertices, so on a convex surface its +middle runs under the surface and is hidden however it is coloured. Measure it: on a curved +convex part at default density, find how much front-facing grid length is actually drawn. +If more than about a tenth is hidden, pull the lines toward the camera by a small amount +scaled to each edge's length (a depth bias in the line material). Only if that is not enough, +lay each edge along the surface instead. + +Acceptance: over each of the first 24 Distinct colours, and over white and near-black parts, +in the light and dark themes, grid pixels reach at least 3:1 contrast against the surface +beside them; at least 90 % of front-facing grid length is visible on the curved part; the +far side does not show through; the grid stays readable at the highest density. + +### 2. Brush size fitted to the part + +Warp gets its own brush radius, separate from Align's. The cursor, region painting, area +handles (section 6) and the brush-size shortcuts all use it while warping. + +- `SurfaceBrushControls` takes an optional value, setter and slider range. Warp passes a + range fitted to the part: 0.1 mm to a quarter of the part's size (clamped to 2–100 mm) on + a logarithmic slider, so each doubling takes the same travel. The numeric field still + accepts 0.05–100 mm and steps by 0.1 mm. +- The part's size is its local bounding box times its scale, largest axis, so turning the + part does not change it. A 32 mm model gets 0.1–8 mm with about 0.9 mm at mid-travel. +- Warp's radius starts at 3 % of the part's size, and keeps whatever the user then sets. + +### 3. Even pins + +**Distribute points** in the Control points section: a count (4, 8, 16, 32; default 8) and a +button. It adds that many unmoved points by farthest-point sampling over the grid's free +nodes, measured along grid edges, seeded by the points already present. It is deterministic +(fixed first seed and tie-break), never puts two points on one node, gives each disconnected +piece of the region a point before doubling up, and stops at the number of free nodes. Each +point sits on a node's own scan vertex and pins the surface where it is now. One session +undo step. + +Distributed points are ordinary points with radius 0 (section 4), marked automatic until +the user moves or edits them. + +When the region is effectively the whole part (Whole part, or Painted with nothing +painted), the Region stage shows "Place points automatically" (on, with the same count), +and the first lay of the grid distributes them. Changing density, returning from Edit +region, or deleting them never places them again. Close gap removes automatic points that +are still untouched and sit on the nodes it is about to pull, in the same undo step, so a +seam still closes; points the user placed or moved are kept. + +### 4. Radius and falloff + +Every handle (a control point, or a line or area from section 6) has a **radius** in mm and +a **falloff** from 0 to 100 %, edited in the Control points section for the selected +handles. New handles take the last values used. Radius is 0 ("point only") or a value on a +fitted logarithmic slider. Defaults: radius 6 % of the part's size, but no more than a +quarter of the region's extent; falloff 100 %. + +The handle's sample constraints stay exactly as they are today, at every radius: they are +what puts the grabbed surface on the target. Radius adds **guides** around them. + +- **Reach.** One bounded multi-source Dijkstra over grid edges (world rest lengths), seeded + from the nodes each sample is bound to, at their distance from the sample. Free nodes + within the radius are in reach. Cached per handle; falloff remaps cached distances. +- **Weight.** `w` is 1 out to `radius × (1 − falloff)`, then a smoothstep to 0 at the + radius. Falloff 0 is a hard-edged plateau, with no division by a zero width. +- **Guide.** Each node in reach gets a soft target `base(n) + w × D`, where `D` is how far + the handle has moved from its pin, at stiffness `κ × w × (that node's edge diagonal)`. + Stiffness reaches zero at the radius, so nothing switches on abruptly there. +- **Baseline.** `base(n)` is where the node was when the guide was made, so an unmoved + handle's guide holds the surface as it is and adding a handle changes nothing. Whenever a + handle's reach is rebuilt (radius change, density change), `base(n)` is the node's current + settled position minus `w_before(n) × D`, with `w_before` the weight that node had from + this handle before the change. After a density change this reproduces the shape that was + there; after a radius change it widens or narrows the handle's own bump. +- **Several handles on one node.** Stiffnesses add, and the target is their + stiffness-weighted mean. There is no case with two exact but different answers: only + sample constraints are exact. +- **Solver.** `solveWarp` takes an optional per-node guide set (node, stiffness, target): + one diagonal term and one right-hand-side term per node. Guide nodes and stiffnesses are + part of the cached system's key; targets are not, so a drag reuses the system. +- Gap targets stay full-strength constraints and are not skipped under a guide. +- If the radius reaches no node beyond the sample's own, the handle behaves as radius 0 and + the panel says that a finer grid would let the radius take effect. + +`κ` is the builder's to set. It is right when, on a fine flat sheet with a far fixed border, +a point lifted by `h` with falloff 100 % gives a written surface that falls monotonically +from the point, is at least `0.9 h` at a tenth of the radius, within `0.1 h` of +`h × smoothstep` across the radius, and under `0.03 h` beyond it. + +### 5. Feathered edge + +Region stage, painted regions only: **Feather edge**, off by default, with a width in mm +(fitted logarithmic slider, starting at Warp's brush radius). The choice is remembered for +the page session. Off, or width 0, builds exactly today's region with its fixed edge. + +- **Growth.** The build worker keeps the painted-face mask, builds whole-mesh welded + topology once, and runs a bounded Dijkstra over world-length edges outward from the + painted edge through unpainted vertices. Unpainted faces with all three vertices within + the width join the region. Role, grid, solve and the fixed border then come from the grown + region, so the painted edge is free. +- **Blend.** Every welded vertex gets `b`: 1 on painted faces, 0 on the actual outer border, + and between them a smoothstep of `d_out / (d_in + d_out)`, its surface distances to the + outer border and to the painted edge. Endpoints are set explicitly. +- **One written surface.** `warp-evaluate` blends once, in the welded world buffer, before + the local write: `rest + b × (skinned − rest)`. Folds, normals, moved bounds and upload + ranges all read that. The outer border keeps its position and normal bits. +- **Handles stay on the paint.** A handle can be added only on a painted face, and + rebinding drops samples whose face is no longer painted. A handle's reach stops at the + painted edge; the band carries the bend the rest of the way. Painted corners have `b = 1`, + so bindings and pins need no blend. +- **Readouts.** The grid overlay draws nodes at their written positions and draws the band + fainter. The seam readout measures painted vertices only. Close gap targets painted nodes + only. +- **Coarse meshes.** Where triangles beside the paint are larger than the width, nothing + can join and that stretch keeps a fixed edge. If no face joined at all, the panel says the + mesh is too coarse there for that width. + +Acceptance: on a dense sheet with a six-ring band or wider, the change in angle between +adjacent faces at the painted edge and at the outer border is under a fifth of what the same +drag gives with feathering off; vertices outside the band keep exact bits; the same on a +mirrored, non-uniformly scaled part. + +### 6. Line and area handles + +In the Warp stage an **Add** selector chooses what a press on the surface makes: + +- **Point**: a click adds a control point (today). +- **Line**: press and drag draws a line; release makes one line handle. +- **Area**: press and drag paints with Warp's brush; release makes one area handle from the + faces painted in that stroke. + +**Input.** A stroke is a draft owned by one pointer. On press, camera navigation, pivot +picking, free transform, gizmo handles and point markers take priority over starting one. +An unmodified primary drag on the region draws; middle, right and Space navigation still +work. Release commits once; Escape, pointer cancel and window blur discard. The click that +ends a stroke adds no point, also when a short line is rejected. Hits come from the warped +preview. A line breaks where the pointer leaves the surface or jumps to a disconnected +spot, and only its longest run is kept. Area painting measures distance on the warped +preview and connectivity on the source mesh, and does not touch the region or its paint +history. + +**Handle.** One selectable object: `kind`, immutable samples (each a surface binding with +its pin), for an area its source faces, shared radius and falloff, and one target for its +centre. It is selected, moved, deleted and undone as one; all its samples move by the same +translation. In a multiple selection, rotate and scale move handle centres about the pivot, +as for points. Snap to neighbour snaps the centre and carries the rest with it. It is drawn +as its line or its tinted area with one marker at the centre. + +**Samples.** A line is resampled by arc length to half the local node spacing; an area +takes up to a few dozen face centres spread by farthest-point sampling, always including +the first hit. Samples with the same bound nodes are merged, so pointer speed does not +change stiffness. An area smaller than a grid cell still has several samples, so it lifts a +small plateau rather than a peak. + +**Reach.** The footprint is the nodes bound to the samples, plus for an area the nodes on +its faces. Section 4 applies with distance measured from the footprint: radius 0 gives a +continuous ridge or a rigid patch, and a radius above 0 adds the smooth skirt. + +Acceptance: along a line handle moved by `h`, the written surface between samples stays +within `0.1 h` of `h`; several interior points of an area do the same, including an area +smaller than a cell and a 60-node grid. + +### Data model + +`WarpPoint` becomes the handle above. A point is a handle with one sample and keeps its +`target` meaning. `moveWarpPoints` keeps taking one target per handle. `selectedPoints`, +session undo (which compares radius and falloff as well as targets), rebinding after a +density or region change, undo snapshots, Apply's restart and the live-refusal recovery all +carry handles. Rebinding drops samples whose face left the region and a handle with none +left. + +A pure module, `warp-handles.ts`, turns handles and a model into solver input: reach, +weights, guides and baselines, and farthest-point distribution. It is unit-tested without +the store. + +## Approaches considered + +**Radius and falloff.** (1) Keep the sample constraint and add soft guides whose target and +stiffness both taper (chosen). (2) Hard targets on every node in reach: review showed it +loses the barycentric constraint (a 1 mm drag moved the grabbed surface 0.33 mm in a hard +case), has no answer where two handles both demand exactness, and switches a strength-1000 +row on at the radius. (3) A second-order energy so points stop spiking unaided: no radius to +set, and a new solver. + +**Baseline.** (1) Guides relative to rest: dragging a point on an already bent limb would +dent a ring around it. (2) Guides relative to where the surface was (chosen). + +**Feather.** (1) Grow the region and taper the written displacement (chosen). (2) Clamp +rotations at border nodes: smoothness would depend on grid density. (3) Taper inward only: +nothing outside the paint moves, which is not what was asked. + +**Lines and areas.** (1) One handle, many samples, one translation (chosen). (2) Group +existing points: each still spikes and carries its own radius. (3) A full pose per handle +with rotation and scale: every transform entry point discards those for a single target +today; not asked for. + +## Order of work + +1. In parallel: (a) grid contrast and Warp's brush; (b) handle model, radius and falloff, + Distribute points; (c) feather growth and the written surface. +2. Merge. Line and area handles on top of (b). +3. Integration: reach stops at the painted edge; handle eligibility and Close gap with + feather; end-to-end checks; release note in `src/docs/changelog.ts`. + +## Verification + +- Unit: the acceptance figures above; radius 0 reproduces today's constraints bit for bit; + a pin added after a deformation changes nothing; overlapping handles; a coarse grid and an + off-grid point; Close gap on a whole-part seam with automatic points; distribution is even + and deterministic; welded duplicates stay identical; a closed mesh stays closed. +- End to end: whole part with automatic points bends instead of translating; a line drag + gives a ridge, moves no camera and adds no stray point; radius and falloff change the + result; feather leaves no crease; Apply, undo, cancel, density change. +- Performance: `warp-benchmark` before and after, plus a wide handle on a 4000-node grid. +- Existing warp unit, session and e2e suites pass (with the whole-part fixtures choosing + their pin policy explicitly); `npm run build` and `npm run format:check` pass. From a442cdcb97bfa4c7c2a25d05b7d01b91a1b1d20f Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 17 Nov 2026 23:02:30 -0800 Subject: [PATCH 02/25] Add a logarithmic slider and a part size helper for Warp --- src/components/ui.tsx | 50 +++++++++++++++++++++++++++++++++++++++++++ src/core/geometry.ts | 17 +++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/src/components/ui.tsx b/src/components/ui.tsx index 8db4b55..156febd 100644 --- a/src/components/ui.tsx +++ b/src/components/ui.tsx @@ -432,6 +432,56 @@ export function RangeInput({ ); } +/** + * A slider where each doubling of the value takes the same travel. With `zero`, the far left + * is 0 and the scale starts just after it. + */ +export function LogRangeInput({ + label, + value, + min, + max, + zero = false, + className, + disabled, + onChange, +}: { + label: string; + value: number; + min: number; + max: number; + zero?: boolean; + className?: string; + disabled?: boolean; + onChange: (value: number) => void; +}) { + const steps = 200, + first = zero ? 1 : 0; + const span = Math.log(max / min); + const clamped = Math.min(max, Math.max(min, value)); + const position = + zero && value <= 0 ? 0 : first + Math.round((Math.log(clamped / min) / span) * (steps - first)); + return ( + { + const at = Number(event.target.value); + if (zero && at === 0) return onChange(0); + const raw = min * Math.exp((span * (at - first)) / (steps - first)); + onChange(Number(raw.toPrecision(raw < 1 ? 2 : 3))); + }} + /> + ); +} + export function Switch({ label, checked, diff --git a/src/core/geometry.ts b/src/core/geometry.ts index 89f85b6..a66d44c 100644 --- a/src/core/geometry.ts +++ b/src/core/geometry.ts @@ -50,6 +50,23 @@ export function transformFromMatrix) { + if (!part.geometry.boundingBox) part.geometry.computeBoundingBox(); + const size = part.geometry.boundingBox!.getSize(new Vector3()); + return Math.max( + size.x * Math.abs(part.scale[0]), + size.y * Math.abs(part.scale[1]), + size.z * Math.abs(part.scale[2]), + ); +} + +/** Slider limits in mm for a brush, radius or width on a part of this size. */ +export const fittedSizeRange = (size: number) => ({ + min: 0.1, + max: Math.min(100, Math.max(2, Number((size / 4).toPrecision(2)))), +}); + /** A connected anchor takes priority over a custom pivot, then the visible mesh center. */ export function partPivot(part: Part, localAnchor?: Vec3): Vector3 { const localPivot = localAnchor ?? part.pivot; From 5cf07693f6bf389df61ede813b20bf1c1dca89d8 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 17 Nov 2026 23:31:57 -0800 Subject: [PATCH 03/25] Give Warp its own brush radius, fitted to the part --- src/components/SurfaceBrushControls.tsx | 53 ++++++--- src/components/SurfacePainter.tsx | 4 +- src/components/WarpControls.tsx | 12 +- src/core/store.ts | 36 +++++- src/hooks/useWorkbench.ts | 27 +++-- tests/e2e/warp-brush.spec.ts | 70 ++++++++++++ tests/e2e/warp.spec.ts | 9 +- tests/unit/warp-brush.test.ts | 144 ++++++++++++++++++++++++ tests/unit/warp-session.test.ts | 14 +-- 9 files changed, 331 insertions(+), 38 deletions(-) create mode 100644 tests/e2e/warp-brush.spec.ts create mode 100644 tests/unit/warp-brush.test.ts diff --git a/src/components/SurfaceBrushControls.tsx b/src/components/SurfaceBrushControls.tsx index ea68a31..c5f375f 100644 --- a/src/components/SurfaceBrushControls.tsx +++ b/src/components/SurfaceBrushControls.tsx @@ -1,9 +1,21 @@ import { Eraser, Paintbrush, Undo2 } from 'lucide-react'; import { useEditor } from '../core/store'; -import { NumericInput } from './ui'; +import { LogRangeInput, NumericInput } from './ui'; -export function SurfaceBrushControls() { - const radius = useEditor((state) => state.brushRadius), +type EditorState = ReturnType; + +/** With `fitted`, the radius is the caller's and the slider is logarithmic over its range. */ +export function SurfaceBrushControls({ + fitted, +}: { + fitted?: { + radius: (state: EditorState) => number; + range: { min: number; max: number }; + set: (radius: number) => void; + }; +} = {}) { + const radius = useEditor((state) => (fitted ? fitted.radius(state) : state.brushRadius)), + setRadius = fitted?.set ?? ((radius: number) => useEditor.getState().setBrush({ radius })), erase = useEditor((state) => state.brushErase), history = useEditor((state) => state.paintHistory), plane = useEditor((state) => state.brushPlane); @@ -40,21 +52,32 @@ export function SurfaceBrushControls() { value={radius} min={0.05} max={100} - step={0.5} - onCommit={(value) => useEditor.getState().setBrush({ radius: value })} + step={fitted ? 0.1 : 0.5} + onCommit={setRadius} /> mm - useEditor.getState().setBrush({ radius: Number(event.target.value) })} - /> + {fitted ? ( + + ) : ( + setRadius(Number(event.target.value))} + /> + )}
Stay on seed plane diff --git a/src/components/SurfacePainter.tsx b/src/components/SurfacePainter.tsx index f9d8a89..828e173 100644 --- a/src/components/SurfacePainter.tsx +++ b/src/components/SurfacePainter.tsx @@ -1,6 +1,6 @@ import { useEffect, useMemo } from 'react'; import { DoubleSide, MeshBasicMaterial, Quaternion, Vector3 } from 'three'; -import { paintingWarpRegion, useEditor } from '../core/store'; +import { paintingWarpRegion, useEditor, warpBrushRadius } from '../core/store'; import { contactColors, patchGeometry } from '../core/surfaces'; import { worldNormal, worldPoint } from '../core/geometry'; import { solveAlignment } from '../core/alignment'; @@ -123,7 +123,7 @@ function FlushPreview() { } export function PaintCursor({ part, hit }: { part: Part; hit: SurfacePoint | null }) { - const radius = useEditor((s) => s.brushRadius), + const radius = useEditor((s) => (paintingWarpRegion(s) ? warpBrushRadius(s) : s.brushRadius)), erase = useEditor((s) => s.brushErase), op = useEditor((s) => s.operation), tool = useEditor((s) => s.tool), diff --git a/src/components/WarpControls.tsx b/src/components/WarpControls.tsx index c993fdd..67fc182 100644 --- a/src/components/WarpControls.tsx +++ b/src/components/WarpControls.tsx @@ -1,6 +1,7 @@ import { LoaderCircle, TriangleAlert } from 'lucide-react'; import { clipLimits } from '../core/clipping'; -import { useEditor, warpChanges } from '../core/store'; +import { fittedSizeRange, partSize } from '../core/geometry'; +import { useEditor, warpBrushRadius, warpChanges } from '../core/store'; import { warpDensityNodes } from '../core/warp-grid'; import { SurfaceBrushControls } from './SurfaceBrushControls'; import { TransformAdjustments } from './TransformAdjustments'; @@ -35,6 +36,13 @@ export function WarpControls() { ); if (warp.stage === 'region') { const painted = warp.region === 'painted'; + const brush = part + ? { + radius: warpBrushRadius, + range: fittedSizeRange(partSize(part)), + set: useEditor.getState().setWarpBrushRadius, + } + : undefined; return (
@@ -56,7 +64,7 @@ export function WarpControls() { /> {painted ? ( <> - +

{warp.faces.length ? `${warp.faces.length.toLocaleString()} triangles painted.` diff --git a/src/core/store.ts b/src/core/store.ts index 061065c..1b9da6c 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -17,7 +17,15 @@ import { Vector3, } from 'three'; import { MeshBVH } from 'three-mesh-bvh'; -import { binaryGeometry, partMatrix, quat, triangleCount, uid, worldPoint } from './geometry'; +import { + binaryGeometry, + partMatrix, + partSize, + quat, + triangleCount, + uid, + worldPoint, +} from './geometry'; import { markInteraction } from './display-performance'; import { anchorError, @@ -265,6 +273,8 @@ interface EditorState { brushRadius: number; brushErase: boolean; brushPlane: BrushPlaneSettings; + /** Warp's own brush radius, for the part it was set on. Align's brushRadius is separate. */ + warpBrush: { partId: string; radius: number } | null; /** The state before each stroke: contact patches, or the warp region while warping. */ paintHistory: (SurfacePair[] | Pick)[]; operation: AssemblyOperation; @@ -344,6 +354,7 @@ interface EditorState { erase?: boolean; plane?: Partial; }) => void; + setWarpBrushRadius: (radius: number) => void; addSurfacePair: () => void; chooseSurface: (pairId: string, side: SurfaceSide) => void; paintSurface: (point: SurfacePoint, face: number, erase?: boolean, begin?: boolean) => boolean; @@ -879,6 +890,7 @@ export const useEditor = create((set, get) => ({ brushRadius: 3, brushErase: false, brushPlane: { enabled: false, angle: 20, distance: 0.5 }, + warpBrush: null, paintHistory: [], operation: blankOperation(), warp: null, @@ -1300,6 +1312,14 @@ export const useEditor = create((set, get) => ({ : state.brushPlane.distance, }, })), + setWarpBrushRadius: (radius) => + set((state) => + state.warp && Number.isFinite(radius) + ? { + warpBrush: { partId: state.warp.partId, radius: Math.max(0.05, Math.min(100, radius)) }, + } + : {}, + ), addSurfacePair: () => set((state) => { const unfinished = state.operation.surfacePairs.find( @@ -1528,7 +1548,7 @@ export const useEditor = create((set, get) => ({ const erasing = erase || state.brushErase; let faces: number[]; try { - faces = facesUnderBrush(part, point, state.brushRadius, face, { + faces = facesUnderBrush(part, point, warpBrushRadius(state), face, { plane: erasing ? undefined : state.brushPlane, patch: { partId: part.id, faces: warp.faces, seed: warp.seed }, }); @@ -2654,6 +2674,18 @@ export const sceneLighting = (state: EditorState) => state.scene.lighting ?? sta export const paintingWarpRegion = (state: Pick) => state.tool === 'warp' && state.warp?.stage === 'region' && state.warp.region === 'painted'; +/** Warp's starting brush radius: 3 % of the part's size. */ +export const fittedWarpBrushRadius = (part: Pick) => + Math.max(0.05, Math.min(100, Number((partSize(part) * 0.03).toPrecision(2)))); + +/** The brush radius everything uses while warping: what was set on this part, or its fitted start. */ +export function warpBrushRadius(state: Pick) { + const { warp, warpBrush } = state; + if (warpBrush && warpBrush.partId === warp?.partId) return warpBrush.radius; + const part = warp && state.scene.parts.find((part) => part.id === warp.partId); + return part ? fittedWarpBrushRadius(part) : 0; +} + export const canUndo = (state: EditorState) => state.sharedHistory ? state.sharedHistory.undo > 0 : state.past.length > 0; export const canRedo = (state: EditorState) => diff --git a/src/hooks/useWorkbench.ts b/src/hooks/useWorkbench.ts index 63dcbb4..6345b7b 100644 --- a/src/hooks/useWorkbench.ts +++ b/src/hooks/useWorkbench.ts @@ -1,6 +1,12 @@ import { useEffect, useRef } from 'react'; import { joinLiveSession } from '../core/live'; -import { committedScene, liveSession, paintingWarpRegion, useEditor } from '../core/store'; +import { + committedScene, + liveSession, + paintingWarpRegion, + useEditor, + warpBrushRadius, +} from '../core/store'; import { readRecovery, saveRecovery } from '../core/recovery'; import { driveAutosave, useDrive } from '../core/drive-sync'; import { chooseTransformTool, executeEditorCommand, shortcutCommand } from '../core/commands'; @@ -173,15 +179,20 @@ export function useKeyboard(openScene: () => void, searchParts: () => void) { state.setOperation({ mode: 'surface' }); return; case 'brushSmaller': - case 'brushLarger': - if (!paintingSurface && !paintingWarpRegion(state)) return; + case 'brushLarger': { + const warping = paintingWarpRegion(state); + if (!paintingSurface && !warping) return; event.preventDefault(); - state.setBrush({ - radius: Number( - (state.brushRadius * (action === 'brushSmaller' ? 0.8 : 1.25)).toFixed(2), - ), - }); + const radius = Number( + ( + (warping ? warpBrushRadius(state) : state.brushRadius) * + (action === 'brushSmaller' ? 0.8 : 1.25) + ).toFixed(2), + ); + if (warping) state.setWarpBrushRadius(radius); + else state.setBrush({ radius }); return; + } case 'orbitTool': case 'panTool': { event.preventDefault(); diff --git a/tests/e2e/warp-brush.spec.ts b/tests/e2e/warp-brush.spec.ts new file mode 100644 index 0000000..a020424 --- /dev/null +++ b/tests/e2e/warp-brush.spec.ts @@ -0,0 +1,70 @@ +import { expect, test, type Page } from '@playwright/test'; + +const browserErrors = new WeakMap(); +test.beforeEach(({ page }) => { + const errors: string[] = []; + browserErrors.set(page, errors); + page.on('pageerror', (error) => errors.push(error.message)); + page.on('console', (message) => { + if (message.type() === 'error') errors.push(message.text()); + }); +}); +test.afterEach(async ({ page }) => { + expect(browserErrors.get(page)).toEqual([]); +}); + +async function brushes(page: Page) { + return page.evaluate(async () => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { useEditor, warpBrushRadius } = await import( + urls.find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))! + ); + const root = (await import(urls.find((url) => url.includes('/@react-three_fiber.js'))!))._roots + .get(document.querySelector('canvas')) + .store.getState(); + let ring: number | null = null; + root.scene.traverse((object: any) => { + if (object.geometry?.type === 'RingGeometry') ring = object.geometry.parameters.innerRadius; + }); + const state = useEditor.getState(); + return { warp: warpBrushRadius(state) as number, align: state.brushRadius as number, ring }; + }); +} + +test("Warp's brush is fitted to the part and has its own radius", async ({ page }) => { + // The sample opens with its 31 mm torso selected. + await page.goto('/'); + await expect(page.locator('canvas')).toBeVisible(); + await page.keyboard.press('w'); + const radius = page.getByRole('spinbutton', { name: 'Brush radius', exact: true }), + slider = page.getByRole('slider', { name: 'Brush radius slider' }); + await expect(radius).toHaveValue('0.93'); + const start = await brushes(page); + expect(start.warp).toBe(0.93); + + // 0.1 mm to a quarter of the part, each doubling taking the same travel. + await slider.fill('100'); + expect((await brushes(page)).warp).toBeCloseTo(Math.sqrt(0.1 * 7.8), 2); + await slider.fill('200'); + expect((await brushes(page)).warp).toBe(7.8); + await radius.fill('2.4'); + await radius.press('Enter'); + await expect(slider).toHaveValue(String(Math.round((Math.log(24) / Math.log(78)) * 200))); + const typed = await brushes(page); + expect(typed.warp).toBe(2.4); + expect(typed.align).toBe(start.align); + + // The cursor ring draws Warp's radius. + const box = (await page.locator('canvas').boundingBox())!; + // The middle of the torso's front. + const [x, y] = await page.evaluate(async () => { + 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(); + return root.camera.position.clone().set(0, 76, 10).project(root.camera).toArray(); + }); + await page.mouse.move(box.x + ((x + 1) / 2) * box.width, box.y + ((1 - y) / 2) * box.height); + await expect.poll(async () => (await brushes(page)).ring).toBe(2.4); +}); diff --git a/tests/e2e/warp.spec.ts b/tests/e2e/warp.spec.ts index 24aca0e..b1febbe 100644 --- a/tests/e2e/warp.spec.ts +++ b/tests/e2e/warp.spec.ts @@ -41,7 +41,7 @@ test.afterEach(async ({ page }) => { async function editorState(page: Page) { return page.evaluate(async () => { const urls = performance.getEntriesByType('resource').map((entry) => entry.name); - const { useEditor } = await import( + const { useEditor, warpBrushRadius } = await import( urls.find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))! ); const fiber = await import(urls.find((url) => url.includes('/@react-three_fiber.js'))!); @@ -54,6 +54,7 @@ async function editorState(page: Page) { stage: (warp?.stage ?? null) as string | null, faces: (warp?.faces.length ?? 0) as number, brushRadius: state.brushRadius as number, + warpBrushRadius: warpBrushRadius(state) as number, points: (warp?.points ?? []).map((point: any) => ({ at: point.target ?? point.pin, moved: point.target !== null, @@ -235,8 +236,12 @@ test('closes a seam, moves a control point, applies, undoes and cancels', async await expect(page.locator('.statusbar')).toContainText( 'Paint the area to warp, or choose Whole part · Alt erases', ); + // Warp's brush starts at 3 % of the 20 mm block, and ] sizes it without touching Align's. + expect((await editorState(page)).warpBrushRadius).toBe(0.6); await page.keyboard.press(']'); - expect((await editorState(page)).brushRadius).toBeCloseTo(3.75, 5); + const sized = await editorState(page); + expect(sized.warpBrushRadius).toBeCloseTo(0.75, 5); + expect(sized.brushRadius).toBe(original.brushRadius); const [start, end] = [await screen(page, [-4, 10, 10]), await screen(page, [2, 10, 10])]; await page.mouse.move(start.x, start.y); await page.mouse.down(); diff --git a/tests/unit/warp-brush.test.ts b/tests/unit/warp-brush.test.ts new file mode 100644 index 0000000..f27fa95 --- /dev/null +++ b/tests/unit/warp-brush.test.ts @@ -0,0 +1,144 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { PlaneGeometry, Triangle, Vector3, type BufferGeometry } from 'three'; +import { fittedSizeRange, partSize, triangleCount } from '../../src/core/geometry'; +import { fittedWarpBrushRadius, useEditor, warpBrushRadius } from '../../src/core/store'; +import { readFace } from '../../src/core/surfaces'; +import type { Part, SurfacePoint } from '../../src/core/types'; + +function plate(id: string, size = 40, scale: Part['scale'] = [1, 1, 1]): Part { + return { + id, + name: id, + geometry: new PlaneGeometry(size, size, 32, 32), + position: [0, 0, 0], + quaternion: [0, 0, 0, 1], + scale, + color: '#aabbcc', + visible: true, + locked: false, + source: 'test', + }; +} + +function faceAt(geometry: BufferGeometry, x: number, y: number) { + const triangle = new Triangle(), + point = new Vector3(x, y, 0), + closest = new Vector3(); + for (let face = 0; face < triangleCount(geometry); face++) { + readFace(geometry, face, triangle); + if (triangle.closestPointToPoint(point, closest).distanceTo(point) < 1e-6) return face; + } + throw new Error('No face under the point.'); +} + +const hit = (partId: string, x: number, y: number): SurfacePoint => ({ + partId, + point: [x, y, 0], + normal: [0, 0, 1], +}); + +const editor = () => useEditor.getState(); + +function warp(...parts: Part[]) { + editor().setScene({ name: 'Brush', parts, joints: [] }); + useEditor.setState({ selected: [parts[0].id] }); + editor().setTool('warp'); +} + +/** Paints one dab at the plate's centre and returns how many faces it covered. */ +function dab(part: Part) { + editor().paintWarpRegion(hit(part.id, 0, 0), faceAt(part.geometry, 0, 0), false, true); + editor().endPaintStroke(); + return editor().warp!.faces.length; +} + +const initial = useEditor.getState(); +afterEach(() => { + editor().cancelWarp(); + useEditor.setState(initial); +}); + +describe('part size', () => { + it('is the largest scaled side, whichever way the part is turned', () => { + const part = { ...plate('a', 32), scale: [1, 2, 1] as Part['scale'] }; + expect(partSize(part)).toBeCloseTo(64); + const turned: Part = { ...part, quaternion: [0, 0, Math.SQRT1_2, Math.SQRT1_2] }; + expect(partSize(turned)).toBeCloseTo(64); + expect(partSize({ ...part, scale: [-1, 1, 1] })).toBeCloseTo(32); + }); + + it('fits a 32 mm model from 0.1 mm to a quarter of its size, clamped to 2–100 mm', () => { + expect(fittedSizeRange(32)).toEqual({ min: 0.1, max: 8 }); + expect(fittedSizeRange(100)).toEqual({ min: 0.1, max: 25 }); + expect(fittedSizeRange(4)).toEqual({ min: 0.1, max: 2 }); + expect(fittedSizeRange(1000)).toEqual({ min: 0.1, max: 100 }); + // Each doubling takes the same travel, so mid-travel is the geometric mean. + const { min, max } = fittedSizeRange(32); + expect(Math.sqrt(min * max)).toBeCloseTo(0.89, 2); + }); +}); + +describe("Warp's brush", () => { + it('starts at 3 % of the part size', () => { + warp(plate('a', 32)); + expect(warpBrushRadius(editor())).toBe(0.96); + editor().cancelWarp(); + warp(plate('b', 40, [2.5, 1, 1])); + expect(warpBrushRadius(editor())).toBe(3); + expect(fittedWarpBrushRadius(plate('c', 1))).toBe(0.05); + }); + + it("is separate from Align's brush both ways", () => { + warp(plate('a')); + const align = editor().brushRadius; + editor().setWarpBrushRadius(5); + expect(warpBrushRadius(editor())).toBe(5); + expect(editor().brushRadius).toBe(align); + editor().setBrush({ radius: 12 }); + expect(warpBrushRadius(editor())).toBe(5); + expect(editor().brushRadius).toBe(12); + }); + + it('keeps what was set across sessions on the same part, not on another', () => { + const a = plate('a'), + b = plate('b'); + warp(a, b); + editor().setWarpBrushRadius(2.5); + editor().cancelWarp(); + editor().setTool('select'); + warp(a, b); + expect(warpBrushRadius(editor())).toBe(2.5); + editor().cancelWarp(); + editor().setTool('select'); + useEditor.setState({ selected: ['b'] }); + editor().setTool('warp'); + expect(warpBrushRadius(editor())).toBe(fittedWarpBrushRadius(b)); + }); + + it('clamps to the numeric field and ignores values that are not numbers', () => { + warp(plate('a')); + editor().setWarpBrushRadius(0.01); + expect(warpBrushRadius(editor())).toBe(0.05); + editor().setWarpBrushRadius(500); + expect(warpBrushRadius(editor())).toBe(100); + editor().setWarpBrushRadius(Number.NaN); + expect(warpBrushRadius(editor())).toBe(100); + }); + + it('sets how much a dab paints, whatever Align uses', () => { + const part = plate('a'); + warp(part); + editor().setBrush({ radius: 20 }); + editor().setWarpBrushRadius(1); + const small = dab(part); + editor().undoPaintStroke(); + expect(editor().warp!.faces).toEqual([]); + editor().setBrush({ radius: 0.1 }); + editor().setWarpBrushRadius(6); + const large = dab(part); + // Cells are 1.25 mm, so a 1 mm dab covers a few faces and a 6 mm dab a disc of them. + expect(small).toBeGreaterThan(0); + expect(small).toBeLessThan(16); + expect(large).toBeGreaterThan(small * 10); + }); +}); diff --git a/tests/unit/warp-session.test.ts b/tests/unit/warp-session.test.ts index e52a630..3168ad0 100644 --- a/tests/unit/warp-session.test.ts +++ b/tests/unit/warp-session.test.ts @@ -136,7 +136,7 @@ function solid(id: string, geometry: BufferGeometry, position: Vec3): Part { /** Paints a disc of the plate around a mesh-local point and lays the grid over it. */ async function warpDisc(part: Part, x: number, y: number, radius: number) { editor().setTool('warp'); - editor().setBrush({ radius, erase: false }); + editor().setWarpBrushRadius(radius); editor().paintWarpRegion(hit(part.id, x, y), faceAt(part.geometry, x, y), false, true); editor().endPaintStroke(); await editor().layWarpGrid(); @@ -260,7 +260,7 @@ describe('warp session', () => { b = plate('b', 50); setup([a, b], ['a']); editor().setTool('warp'); - editor().setBrush({ radius: 3, erase: false }); + editor().setWarpBrushRadius(3); expect(editor().paintWarpRegion(hit('b', 0, 0), faceAt(b.geometry, 0, 0), false, true)).toBe( false, @@ -429,7 +429,7 @@ describe('warp session', () => { editor().setWarpRegion('painted'); expect(session().stage).toBe('region'); - editor().setBrush({ radius: 6, erase: false }); + editor().setWarpBrushRadius(6); expect( editor().paintWarpRegion(hit('a', -10, 0), faceAt(a.geometry, -10, 0), false, true), ).toBe(true); @@ -1479,7 +1479,7 @@ describe('warp commands', () => { editor().patchParts(['a'], { color: '#112233' }); expect(editor().past).toHaveLength(1); editor().setTool('warp'); - editor().setBrush({ radius: 3, erase: false }); + editor().setWarpBrushRadius(3); editor().paintWarpRegion(hit('a', 0, 0), faceAt(a.geometry, 0, 0), false, true); editor().endPaintStroke(); const first = session().faces; @@ -1527,7 +1527,7 @@ describe('warp commands', () => { setup([a], ['a']); editor().patchParts(['a'], { color: '#112233' }); editor().setTool('warp'); - editor().setBrush({ radius: 3, erase: false }); + editor().setWarpBrushRadius(3); editor().paintWarpRegion(hit('a', 0, 0), faceAt(a.geometry, 0, 0), false, true); editor().endPaintStroke(); const painted = session().faces; @@ -1583,7 +1583,7 @@ describe('warp commands', () => { editor().undo(); editor().setTool('warp'); expect(editorCommands().redo.enabled).toBe(true); - editor().setBrush({ radius: 3, erase: false }); + editor().setWarpBrushRadius(3); editor().paintWarpRegion(hit('a', 0, 0), faceAt(a.geometry, 0, 0), false, true); editor().endPaintStroke(); expect(editorCommands().redo.enabled).toBe(false); @@ -1605,7 +1605,7 @@ describe('warp commands', () => { setup([a], ['a']); editor().setTool('warp'); expect(editorCommands().undo.enabled).toBe(false); - editor().setBrush({ radius: 3, erase: false }); + editor().setWarpBrushRadius(3); editor().paintWarpRegion(hit('a', 0, 0), faceAt(a.geometry, 0, 0), false, true); editor().endPaintStroke(); expect(editorCommands().undo.enabled).toBe(true); From ac62dfc5d934495692b2d018e73715e839e455a6 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 17 Nov 2026 23:31:57 -0800 Subject: [PATCH 04/25] Draw the warp grid with a dark core and light casing --- src/components/WarpOverlay.tsx | 215 +++++++++++++++++-- tests/e2e/warp-grid.spec.ts | 380 +++++++++++++++++++++++++++++++++ 2 files changed, 574 insertions(+), 21 deletions(-) create mode 100644 tests/e2e/warp-grid.spec.ts diff --git a/src/components/WarpOverlay.tsx b/src/components/WarpOverlay.tsx index dfa1690..4b87d5f 100644 --- a/src/components/WarpOverlay.tsx +++ b/src/components/WarpOverlay.tsx @@ -3,7 +3,19 @@ import type { ReactNode } from 'react'; import { useThree } from '@react-three/fiber'; import type { ThreeEvent } from '@react-three/fiber'; import { ScreenSizer } from '@react-three/drei'; -import { BufferAttribute, BufferGeometry, Color, DoubleSide, Object3D, type Mesh } from 'three'; +import { + BufferAttribute, + BufferGeometry, + Color, + DoubleSide, + InstancedInterleavedBuffer, + InterleavedBufferAttribute, + Object3D, + type Mesh, +} from 'three'; +import { LineMaterial } from 'three/addons/lines/LineMaterial.js'; +import { LineSegments2 } from 'three/addons/lines/LineSegments2.js'; +import { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js'; import { partMatrix, transformFromMatrix } from '../core/geometry'; import { hiddenByIsolation } from '../core/isolation'; import { PrecisionDrag } from '../core/precision'; @@ -161,36 +173,197 @@ function Seam({ warp }: { warp: WarpSession }) { ); } -/** Grid edges as thin lines between the deformed node positions. */ +/** World position of each grid node, as the grid is drawn. */ +const gridNodePositions = (warp: WarpSession) => warp.state!.positions; + +/** + * Grid edges are chords between scan vertices, so on a curved surface their middles dip under + * it. Each edge is drawn nearer the camera by this many times its estimated dip, over the cosine + * of the angle it is seen at, and never by more than a quarter of its length. + */ +const gridDepthBias = 2; +/** + * A sharper turn between node normals than half a radian is a crease, which no small bias + * lifts a chord over. Squared, as |n_a - n_b|². + */ +const maxTurn = (2 * Math.sin(0.25)) ** 2; + +/** A grid line material whose edges are pulled toward the camera by `gridDepthBias`. */ +function gridMaterial(color: string, linewidth: number, opacity: number) { + const material = new LineMaterial({ + color, + linewidth, + opacity, + transparent: true, + depthWrite: false, + toneMapped: false, + }); + material.uniforms.depthBias = { value: gridDepthBias }; + const end = 'vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );'; + material.vertexShader = material.vertexShader + .replace( + 'uniform float linewidth;', + 'uniform float linewidth;\nuniform float depthBias;\nattribute vec3 instanceNormal;\nattribute float instanceSag;', + ) + .replace( + end, + `${end} + bool perspectiveView = projectionMatrix[ 2 ][ 3 ] == - 1.0; + vec3 toEye = perspectiveView ? normalize( - start.xyz - end.xyz ) : vec3( 0.0, 0.0, 1.0 ); + vec3 normal = normalMatrix * instanceNormal; + float facing = max( abs( dot( normal, toEye ) ) / max( length( normal ), 1e-6 ), 0.1 ); + float pull = min( depthBias * instanceSag / facing, 0.25 * distance( start.xyz, end.xyz ) ); + if ( perspectiveView ) { + start.xyz *= max( 0.5, 1.0 - pull / length( start.xyz ) ); + end.xyz *= max( 0.5, 1.0 - pull / length( end.xyz ) ); + } else { + start.z += pull; + end.z += pull; + }`, + ); + return material; +} + +/** Area-weighted unit normal per node, from the grid's own triangles. */ +function nodeNormals(nodes: ArrayLike, triangles: Uint32Array, out: Float64Array) { + out.fill(0); + for (let t = 0; t < triangles.length; t += 3) { + const a = triangles[t] * 3, + b = triangles[t + 1] * 3, + c = triangles[t + 2] * 3; + const ux = nodes[b] - nodes[a], + uy = nodes[b + 1] - nodes[a + 1], + uz = nodes[b + 2] - nodes[a + 2], + vx = nodes[c] - nodes[a], + vy = nodes[c + 1] - nodes[a + 1], + vz = nodes[c + 2] - nodes[a + 2]; + const x = uy * vz - uz * vy, + y = uz * vx - ux * vz, + z = ux * vy - uy * vx; + out[a] += x; + out[a + 1] += y; + out[a + 2] += z; + out[b] += x; + out[b + 1] += y; + out[b + 2] += z; + out[c] += x; + out[c + 1] += y; + out[c + 2] += z; + } + for (let n = 0; n < out.length; n += 3) { + const scale = + 1 / (Math.sqrt(out[n] * out[n] + out[n + 1] * out[n + 1] + out[n + 2] * out[n + 2]) || 1); + out[n] *= scale; + out[n + 1] *= scale; + out[n + 2] *= scale; + } +} + +/** + * Grid edges between the deformed node positions: a dark core over a light casing, so they + * read over light and dark surfaces alike. Both draw from one endpoint buffer. + */ function GridLines({ warp }: { warp: WarpSession }) { const model = warp.model!; const invalidate = useThree((s) => s.invalidate); - const geometry = useMemo(() => { + const size = useThree((s) => s.size); + const grid = useMemo(() => { const { edgeStart, edges } = model.grid; - const pairs: number[] = []; + let count = 0; for (let n = 0; n + 1 < edgeStart.length; n++) + for (let k = edgeStart[n]; k < edgeStart[n + 1]; k++) if (edges[k] > n) count++; + const pairs = new Uint32Array(count * 2); + for (let n = 0, e = 0; n + 1 < edgeStart.length; n++) for (let k = edgeStart[n]; k < edgeStart[n + 1]; k++) - if (edges[k] > n) pairs.push(n, edges[k]); - const geometry = new BufferGeometry(); - geometry.setAttribute( - 'position', - new BufferAttribute(new Float32Array(model.restNodes.length), 3), - ); - geometry.setIndex(pairs); - return geometry; + if (edges[k] > n) { + pairs[e++] = n; + pairs[e++] = edges[k]; + } + // Per edge: both ends, its normal, and how far its middle dips under the surface. + const buffer = new InstancedInterleavedBuffer(new Float32Array(count * 10), 10, 1); + const geometry = new LineSegmentsGeometry(); + geometry.setAttribute('instanceStart', new InterleavedBufferAttribute(buffer, 3, 0)); + geometry.setAttribute('instanceEnd', new InterleavedBufferAttribute(buffer, 3, 3)); + geometry.setAttribute('instanceNormal', new InterleavedBufferAttribute(buffer, 3, 6)); + geometry.setAttribute('instanceSag', new InterleavedBufferAttribute(buffer, 1, 9)); + geometry.instanceCount = count; + const casing = new LineSegments2(geometry, gridMaterial('#f2f5f4', 4.5, 0.85)), + core = new LineSegments2(geometry, gridMaterial('#0e1114', 2, 1)); + casing.name = 'warp-grid:casing'; + core.name = 'warp-grid:core'; + casing.renderOrder = 6; + core.renderOrder = 7; + for (const line of [casing, core]) { + line.frustumCulled = false; + line.raycast = noRaycast; + } + return { + pairs, + buffer, + normals: new Float64Array(model.restNodes.length), + geometry, + casing, + core, + }; }, [model]); - useEffect(() => () => geometry.dispose(), [geometry]); + useEffect( + () => () => { + grid.geometry.dispose(); + grid.casing.material.dispose(); + grid.core.material.dispose(); + }, + [grid], + ); + useLayoutEffect(() => { + grid.casing.material.resolution.set(size.width, size.height); + grid.core.material.resolution.set(size.width, size.height); + invalidate(); + }, [grid, size, invalidate]); useLayoutEffect(() => { - const position = geometry.getAttribute('position') as BufferAttribute; - (position.array as Float32Array).set(warp.state!.positions); - position.needsUpdate = true; - geometry.computeBoundingSphere(); + const nodes = gridNodePositions(warp), + { pairs, buffer, normals } = grid; + nodeNormals(nodes, model.grid.triangles, normals); + const array = buffer.array as Float32Array; + for (let e = 0; e < pairs.length / 2; e++) { + const a = pairs[e * 2] * 3, + b = pairs[e * 2 + 1] * 3, + o = e * 10; + for (let i = 0; i < 3; i++) { + array[o + i] = nodes[a + i]; + array[o + 3 + i] = nodes[b + i]; + array[o + 6 + i] = normals[a + i] + normals[b + i]; + } + const dx = nodes[b] - nodes[a], + dy = nodes[b + 1] - nodes[a + 1], + dz = nodes[b + 2] - nodes[a + 2]; + // Normals that spread apart along the edge mean a convex surface, above the chord there. + const convex = + (normals[b] - normals[a]) * dx + + (normals[b + 1] - normals[a + 1]) * dy + + (normals[b + 2] - normals[a + 2]) * dz > + 0; + if (!convex) { + array[o + 9] = 0; + continue; + } + // An arc of length L whose normals turn by θ dips about L θ / 8 below its chord, and + // |n_a - n_b| is θ closely enough below the cap. + const turn = + 2 - + 2 * + (normals[a] * normals[b] + + normals[a + 1] * normals[b + 1] + + normals[a + 2] * normals[b + 2]); + array[o + 9] = Math.sqrt((dx * dx + dy * dy + dz * dz) * Math.min(turn, maxTurn)) / 8; + } + buffer.needsUpdate = true; invalidate(); - }, [geometry, warp, invalidate]); + }, [grid, warp, model, invalidate]); return ( - - - + <> + + + ); } diff --git a/tests/e2e/warp-grid.spec.ts b/tests/e2e/warp-grid.spec.ts new file mode 100644 index 0000000..a427387 --- /dev/null +++ b/tests/e2e/warp-grid.spec.ts @@ -0,0 +1,380 @@ +import { expect, test, type Page } from '@playwright/test'; +import { LatheGeometry, SphereGeometry, Vector2, type BufferGeometry } from 'three'; +import { serializeGeometry } from '../../src/core/geometry'; +import { distinctColor } from '../../src/core/appearance'; + +// A curved convex part about the size of a miniature's head or shoulder pad. +const radius = 15; +const ball = new SphereGeometry(radius, 96, 64); + +/** A dome 0.8 mm thick, like a cloak: its inner surface must never show through. */ +function dome() { + const arc = (r: number) => + Array.from({ length: 41 }, (_, i) => { + const a = (i / 40) * (Math.PI / 2); + return new Vector2(r * Math.cos(a), r * Math.sin(a)); + }); + const outer = arc(radius), + inner = arc(radius - 0.8).reverse(); + return new LatheGeometry([...outer, ...inner, outer[0]], 96); +} + +const scene = (geometry: BufferGeometry) => ({ + format: 'kitbasher', + version: 1, + units: 'mm', + name: 'Warp grid', + joints: [], + parts: [ + { + id: 'ball', + name: 'Scanned ball', + position: [0, radius, 0], + color: '#d4a272', + geometry: serializeGeometry(geometry), + quaternion: [0, 0, 0, 1], + scale: [1, 1, 1], + visible: true, + locked: false, + source: 'test', + }, + ], +}); + +const browserErrors = new WeakMap(); +test.beforeEach(({ page }) => { + const errors: string[] = []; + browserErrors.set(page, errors); + page.on('pageerror', (error) => errors.push(error.message)); + page.on('console', (message) => { + if (message.type() === 'error') errors.push(message.text()); + }); +}); +test.afterEach(async ({ page }) => { + expect(browserErrors.get(page)).toEqual([]); +}); + +async function layGrid(page: Page, geometry: BufferGeometry = ball) { + await page.goto('/'); + await expect(page.locator('canvas')).toBeVisible(); + await page.getByLabel('Open Kitbasher scene').setInputFiles({ + name: 'grid.kitbash', + mimeType: 'application/json', + buffer: Buffer.from(JSON.stringify(scene(geometry))), + }); + await page.getByRole('button', { name: 'Open scene', exact: true }).click(); + await page.locator('.part-select[title="Scanned ball"]').click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.keyboard.press('w'); + await page.getByRole('radio', { name: 'Whole part', exact: true }).click(); + await page.getByRole('button', { name: 'Lay grid', exact: true }).click(); + await expect(page.getByRole('button', { name: 'Close gap', exact: true })).toBeEnabled(); +} + +async function setDensity(page: Page, level: number) { + await page.getByRole('slider', { name: 'Grid density' }).fill(String(level)); + await expect(page.getByRole('button', { name: 'Close gap', exact: true })).toBeEnabled(); + await expect + .poll(() => + page.evaluate(async () => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { useEditor } = await import( + urls.find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))! + ); + const { warp } = useEditor.getState(); + return warp.stage === 'warp' ? warp.density : -1; + }), + ) + .toBe(level); +} + +/** Points the camera at the part's centre from a direction, at 70 mm. */ +async function lookFrom(page: Page, direction: number[]) { + await page.evaluate( + async ({ direction, radius }) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const root = ( + await import(urls.find((url) => url.includes('/@react-three_fiber.js'))!) + )._roots + .get(document.querySelector('canvas')) + .store.getState(); + const { camera, controls } = root; + const centre = camera.position.clone().set(0, radius, 0); + const offset = camera.position.clone().fromArray(direction).normalize().multiplyScalar(70); + controls.target.copy(centre); + camera.position.copy(centre).add(offset); + camera.lookAt(centre); + controls.update(); + root.invalidate(); + }, + { direction, radius }, + ); +} + +/** + * Draws the grid's own core material over the part's depth, offscreen, and counts its pixels. + * On the ball: edges facing the camera with and without the depth test, and edges well round + * the back with it. On the dome: edges of its inner surface, and of the rest, with it. + */ +async function gridPixels(page: Page, part: 'ball' | 'dome') { + return page.evaluate( + async ({ part, radius }) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const THREE = await import(urls.find((url) => /\/deps\/three\.js/.test(url))!); + const root = ( + await import(urls.find((url) => url.includes('/@react-three_fiber.js'))!) + )._roots + .get(document.querySelector('canvas')) + .store.getState(); + const { gl, camera, size } = root; + const core = root.scene.getObjectByName('warp-grid:core'); + const mesh = root.scene.getObjectByName('part:ball'); + const { array: ends, stride } = core.geometry.getAttribute('instanceStart').data; + const centre = new THREE.Vector3(0, radius, 0), + eye = camera.getWorldPosition(new THREE.Vector3()); + const point = (i: number) => new THREE.Vector3().fromArray(ends, i); + // How squarely a point on the ball faces the camera. + const facing = (p: InstanceType) => + p.clone().sub(centre).normalize().dot(eye.clone().sub(p).normalize()); + const inside = (p: InstanceType) => + p.distanceTo(centre) < radius - 0.4 && p.y > radius + 0.8; + const sets: Record = {}; + const add = (name: string, i: number) => + (sets[name] ??= []).push(...ends.subarray(i, i + stride)); + for (let i = 0; i < ends.length; i += stride) { + const a = point(i), + b = point(i + 3); + if (part === 'dome') add(inside(a) && inside(b) ? 'inner' : 'outer', i); + else if (facing(a.clone().add(b).multiplyScalar(0.5)) > 0) add('front', i); + // An edge that crosses the outline is neither. + else if (facing(a) < -0.2 && facing(b) < -0.2) add('back', i); + } + const target = new THREE.WebGLRenderTarget(size.width, size.height); + const surface = new THREE.Mesh( + mesh.geometry, + new THREE.MeshBasicMaterial({ + color: 0x000000, + polygonOffset: true, + polygonOffsetFactor: 1, + polygonOffsetUnits: 1, + }), + ); + surface.matrixAutoUpdate = false; + surface.matrix.copy(mesh.matrixWorld); + const pixels = new Uint8Array(size.width * size.height * 4); + const count = (edges: number[] = [], depthTest = true) => { + if (!edges.length) return 0; + const scene = new THREE.Scene(); + scene.background = new THREE.Color(0x000000); + const geometry = new core.geometry.constructor(); + const buffer = new THREE.InstancedInterleavedBuffer(new Float32Array(edges), stride, 1); + for (const [name, attribute] of Object.entries(core.geometry.attributes) as any) + if (attribute.isInterleavedBufferAttribute) + geometry.setAttribute( + name, + new THREE.InterleavedBufferAttribute(buffer, attribute.itemSize, attribute.offset), + ); + geometry.instanceCount = edges.length / stride; + const material = core.material.clone(); + material.color.set(0xffffff); + material.depthTest = depthTest; + material.resolution.set(size.width, size.height); + const line = new core.constructor(geometry, material); + line.frustumCulled = false; + scene.add(surface, line); + gl.setRenderTarget(target); + gl.render(scene, camera); + gl.readRenderTargetPixels(target, 0, 0, size.width, size.height, pixels); + gl.setRenderTarget(null); + geometry.dispose(); + material.dispose(); + let lit = 0; + for (let p = 0; p < pixels.length; p += 4) if (pixels[p] > 127) lit++; + return lit; + }; + const result: Record = + part === 'dome' + ? { inner: count(sets.inner), outer: count(sets.outer) } + : { + front: count(sets.front, false), + shown: count(sets.front), + back: count(sets.back), + }; + target.dispose(); + surface.material.dispose(); + return { edges: ends.length / stride, ...result } as Record; + }, + { part, radius }, + ); +} + +/** WCAG contrast between drawn grid pixels and the same pixels with the grid hidden. */ +async function gridContrast(page: Page, colors: string[]) { + return page.evaluate( + async ({ colors, radius }) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const THREE = await import(urls.find((url) => /\/deps\/three\.js/.test(url))!); + const root = ( + await import(urls.find((url) => url.includes('/@react-three_fiber.js'))!) + )._roots + .get(document.querySelector('canvas')) + .store.getState(); + const { gl, camera, scene } = root; + const grid = ['warp-grid:casing', 'warp-grid:core'].map((name) => + scene.getObjectByName(name), + ); + const part = scene.getObjectByName('part:ball'); + const { array: ends, stride } = grid[1].geometry.getAttribute('instanceStart').data; + const canvas = gl.domElement as HTMLCanvasElement, + width = canvas.width, + height = canvas.height; + const context = gl.getContext() as WebGL2RenderingContext; + const read = () => { + gl.setRenderTarget(null); + gl.render(scene, camera); + const pixels = new Uint8Array(width * height * 4); + context.readPixels(0, 0, width, height, context.RGBA, context.UNSIGNED_BYTE, pixels); + return pixels; + }; + const channel = (v: number) => { + const c = v / 255; + return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; + }; + const luminance = (p: Uint8Array, i: number) => + 0.2126 * channel(p[i]) + 0.7152 * channel(p[i + 1]) + 0.0722 * channel(p[i + 2]); + // Points a third and two thirds along each edge that faces the camera squarely. + const centre = new THREE.Vector3(0, radius, 0), + eye = camera.getWorldPosition(new THREE.Vector3()); + const samples: [number, number][] = []; + const a = new THREE.Vector3(), + b = new THREE.Vector3(), + p = new THREE.Vector3(); + for (let i = 0; i < ends.length; i += stride) { + a.fromArray(ends, i); + b.fromArray(ends, i + 3); + for (const t of [1 / 3, 2 / 3]) { + p.lerpVectors(a, b, t); + const normal = p.clone().sub(centre).normalize(), + view = eye.clone().sub(p).normalize(); + if (normal.dot(view) < 0.5) continue; + p.project(camera); + if (Math.abs(p.x) > 0.95 || Math.abs(p.y) > 0.95) continue; + samples.push([Math.round(((p.x + 1) / 2) * width), Math.round(((p.y + 1) / 2) * height)]); + } + } + const results: { color: string; worst: number; low: number; median: number }[] = []; + const material = part.material; + const original = material.color.getHex(); + for (const color of colors) { + material.color.set(color); + const shown = read(); + grid.forEach((line: any) => (line.visible = false)); + const bare = read(); + grid.forEach((line: any) => (line.visible = true)); + const contrasts = samples.map(([x, y]) => { + let best = 1; + for (let dy = -2; dy <= 2; dy++) + for (let dx = -2; dx <= 2; dx++) { + const i = ((y + dy) * width + x + dx) * 4; + const [l1, l2] = [luminance(shown, i), luminance(bare, i)].sort((m, n) => n - m); + best = Math.max(best, (l1 + 0.05) / (l2 + 0.05)); + } + return best; + }); + contrasts.sort((m, n) => m - n); + results.push({ + color, + worst: contrasts[0], + low: contrasts[Math.floor(contrasts.length * 0.02)], + median: contrasts[Math.floor(contrasts.length / 2)], + }); + } + material.color.setHex(original); + root.invalidate(); + return { samples: samples.length, results }; + }, + { colors, radius }, + ); +} + +async function setLighting(page: Page, preset: string) { + await page.evaluate(async (preset) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { useEditor } = await import( + urls.find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))! + ); + const { presetLighting } = await import( + urls.find((url) => /\/src\/core\/lighting\.ts(?:\?.*)?$/.test(url))! + ); + useEditor.setState((state: any) => ({ + scene: { ...state.scene, lighting: presetLighting(preset) }, + })); + }, preset); + // Lights and shadows take a frame to follow. + await page.waitForTimeout(200); +} + +// The design asks for 90 % at the default density; coarser grids have longer, deeper chords. +const visibleShare = [ + [0, 0.85], + [3, 0.9], + [6, 0.9], +] as const; + +test('the grid is drawn along nearly all of a curved part and not through it', async ({ page }) => { + await layGrid(page); + for (const [level, share] of visibleShare) { + await setDensity(page, level); + for (const [view, direction] of [ + ['front', [0, 0.2, 1]], + ['glancing', [1, 0.15, 0.3]], + ] as const) { + await lookFrom(page, [...direction]); + const grid = await gridPixels(page, 'ball'); + test.info().annotations.push({ + type: `density ${level}, ${view}`, + description: JSON.stringify(grid), + }); + expect(grid.front).toBeGreaterThan(1000); + expect(grid.shown / grid.front, `density ${level}, ${view}`).toBeGreaterThan(share); + expect(grid.back / grid.front, `density ${level}, ${view}`).toBeLessThan(0.002); + } + } +}); + +test('the inner surface of a thin part never shows through its outer one', async ({ page }) => { + await layGrid(page, dome()); + for (const level of [0, 3]) { + await setDensity(page, level); + for (const direction of [ + [0.2, 1, 0.3], + [1, 0.6, 0.2], + ]) { + await lookFrom(page, direction); + const grid = await gridPixels(page, 'dome'); + test.info().annotations.push({ + type: `density ${level}, from ${direction}`, + description: JSON.stringify(grid), + }); + expect(grid.outer).toBeGreaterThan(1000); + expect(grid.inner).toBeLessThan(grid.outer * 0.002); + } + } +}); + +test('grid lines stand out over light, dark and Distinct colours in every lighting', async ({ + page, +}) => { + await layGrid(page); + const colors = [...Array.from({ length: 24 }, (_, i) => distinctColor(i)), '#ffffff', '#1c1c1c']; + for (const preset of ['studio', 'soft', 'headlight', 'dramatic']) { + await setLighting(page, preset); + const { samples, results } = await gridContrast(page, colors); + test.info().annotations.push({ type: preset, description: JSON.stringify(results) }); + expect(samples).toBeGreaterThan(200); + // Nearly every point along the lines reaches 3:1 against the surface under it. + for (const result of results) + expect(result.low, `${preset} ${result.color}`).toBeGreaterThan(3); + } +}); From 0271454df62d0996cabc63e2ed331120462324f4 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 17 Nov 2026 23:55:01 -0800 Subject: [PATCH 05/25] Add a feathered edge to painted warp regions --- src/components/WarpControls.tsx | 69 ++- src/components/WarpOverlay.tsx | 4 +- src/core/store.ts | 52 ++- src/core/warp-evaluate.ts | 65 ++- src/core/warp-feather.ts | 244 ++++++++++ src/core/warp-model.ts | 79 +++- src/core/warp-neighbour.ts | 14 +- src/core/warp-region.ts | 7 +- tests/unit/warp-feather-session.test.ts | 173 +++++++ tests/unit/warp-feather.test.ts | 596 ++++++++++++++++++++++++ 10 files changed, 1278 insertions(+), 25 deletions(-) create mode 100644 src/core/warp-feather.ts create mode 100644 tests/unit/warp-feather-session.test.ts create mode 100644 tests/unit/warp-feather.test.ts diff --git a/src/components/WarpControls.tsx b/src/components/WarpControls.tsx index 67fc182..b0a7849 100644 --- a/src/components/WarpControls.tsx +++ b/src/components/WarpControls.tsx @@ -2,10 +2,11 @@ import { LoaderCircle, TriangleAlert } from 'lucide-react'; import { clipLimits } from '../core/clipping'; import { fittedSizeRange, partSize } from '../core/geometry'; import { useEditor, warpBrushRadius, warpChanges } from '../core/store'; +import type { Part } from '../core/types'; import { warpDensityNodes } from '../core/warp-grid'; import { SurfaceBrushControls } from './SurfaceBrushControls'; import { TransformAdjustments } from './TransformAdjustments'; -import { NumericInput, RadioGroup, Section } from './ui'; +import { LogRangeInput, NumericInput, RadioGroup, Section } from './ui'; /** Ends the session without a notice and leaves the tool. */ function cancel() { @@ -14,11 +15,61 @@ function cancel() { state.setTool('select'); } +/** Feathered edge for a painted region: a switch, and a width once it is on. */ +function FeatherEdge({ part }: { part: Part | undefined }) { + const feather = useEditor((s) => s.warpFeather); + const brushRadius = useEditor(warpBrushRadius); + const width = feather.width ?? brushRadius; + const range = fittedSizeRange(part ? partSize(part) : 0); + const setWidth = (value: number) => useEditor.getState().setWarpFeather({ width: value }); + return ( + <> +

+ Feather edge + +
+ {feather.enabled ? ( + <> + + + + ) : null} + + ); +} + export function WarpControls() { const warp = useEditor((s) => s.warp); const part = useEditor((s) => s.warp ? s.scene.parts.find((p) => p.id === s.warp!.partId) : undefined, ); + const feathered = useEditor((s) => s.warpFeather.enabled); if (!warp) return (
@@ -48,9 +99,11 @@ export function WarpControls() {

Warping {part?.name}.{' '} - {painted - ? 'Paint the area to bend. Its edge stays where it is.' - : 'Every surface of the part can bend.'} + {!painted + ? 'Every surface of the part can bend.' + : feathered + ? 'Paint the area to bend. Its edge blends into the surface around it.' + : 'Paint the area to bend. Its edge stays where it is.'}

+ ) : null}
@@ -113,6 +167,13 @@ export function WarpControls() { Fine

Coarser grids bend broadly. Finer grids bend locally.

+ {warp.model?.feather?.joined === 0 ? ( +

+

+ ) : null} {building ? (

+ + +

+ {selected.length + ? radius > 0 + ? `Moves the surface within ${Number(radius.toPrecision(3))} mm of the selected ${selected.length === 1 ? 'point' : 'points'}. New points use the same settings.` + : `The selected ${selected.length === 1 ? 'point moves' : 'points move'} the surface at the point only.` + : 'New points use this radius and falloff.'} + {coarse + ? ' This grid is too coarse for that radius here. A finer grid lets it take effect.' + : ''} +

+
+ + +
+
+ ); +} + /** Ends the session without a notice and leaves the tool. */ function cancel() { const state = useEditor.getState(); @@ -126,6 +266,36 @@ export function WarpControls() { ) : null} + {warpWholePart(warp) && warp.firstLay ? ( +
+ + +
+ ) : null}

Coarser grids bend broadly. Finer grids bend locally.

- {warp.model?.feather?.joined === 0 ? ( + {warp.model?.feather?.joined === 0 && warp.model.feather.edge > 0 ? (

) : null} + {warp.model?.feather?.anchored ? ( +

+

+ ) : null} {building ? (

@@ -337,19 +340,27 @@ export function WarpControls() { Fine

Coarser grids bend broadly. Finer grids bend locally.

- {warp.model?.feather?.joined === 0 && warp.model.feather.edge > 0 ? ( + {featherNote === 'unanchored' ? (

) : null} - {warp.model?.feather?.anchored ? ( + {featherNote === 'coarse' ? (

+ ) : null} + {featherNote === 'anchored' ? ( +

+

) : null} {building ? ( diff --git a/src/core/warp-feather.ts b/src/core/warp-feather.ts index 49121b2..bea0f36 100644 --- a/src/core/warp-feather.ts +++ b/src/core/warp-feather.ts @@ -80,8 +80,8 @@ export interface WarpGrowth { * Distance spreads only across shared edges: each welded vertex is split into fans of faces that * share an edge there, so growth never crosses onto another surface through a single shared * vertex. Band vertices on a mesh boundary are pinned, so a rim or hole inside the band stays put. - * Where the band would leave a connected piece no fixed vertex at all, its farthest ring stays - * unjoined as an anchor. + * Where the band would leave an edge-connected piece no fixed boundary edge, its farthest ring + * stays unjoined as an anchor. */ export function growWarpRegion( corner: Uint32Array, @@ -276,8 +276,11 @@ export function growWarpRegion( } /** - * For each connected piece of the grown region that had a fixed edge before growth and has none - * after, leaves its farthest band ring unjoined so that ring stays fixed. Returns how many pieces. + * For each edge-connected piece of the grown region with no fixed boundary edge, leaves its + * farthest band ring unjoined so that ring stays fixed. Returns how many pieces. + * + * A fixed boundary edge is one region face uses alone, with both ends fixed. Grid simplification + * locks such edges, so they survive into the grid; a lone fixed vertex may not. */ function anchorSwallowed( corner: Uint32Array, @@ -307,7 +310,6 @@ function anchorSwallowed( let anchored = 0; for (let seed = 0; seed < faceCount; seed++) { if (!join[seed] || piece[seed] >= 0) continue; - // Region faces connected through welded vertices, as the solve sees them. const members: number[] = []; let hasFixed = false; piece[seed] = seed; @@ -316,15 +318,25 @@ function anchorSwallowed( const f = stack.pop()!; members.push(f); for (let k = 0; k < 3; k++) { - const v = corner[f * 3 + k]; - if (fixed[v]) hasFixed = true; - for (let e = start[v]; e < start[v + 1]; e++) { + const a = corner[f * 3 + k], + b = corner[f * 3 + ((k + 1) % 3)]; + if (a === b) continue; + // Region faces across edge ab, this one included. + let uses = 0; + for (let e = start[a]; e < start[a + 1]; e++) { const g = (incident[e] - (incident[e] % 3)) / 3; - if (piece[g] < 0 && inRegion(g)) { + if ( + !inRegion(g) || + (corner[g * 3] !== b && corner[g * 3 + 1] !== b && corner[g * 3 + 2] !== b) + ) + continue; + uses++; + if (piece[g] < 0) { piece[g] = seed; stack.push(g); } } + if (uses === 1 && fixed[a] && fixed[b]) hasFixed = true; } } if (hasFixed) continue; diff --git a/src/core/warp-model.ts b/src/core/warp-model.ts index 6001c4b..59d103b 100644 --- a/src/core/warp-model.ts +++ b/src/core/warp-model.ts @@ -29,6 +29,19 @@ export interface WarpFeather { fixedEdge: number; /** Connected pieces the band would have covered entirely, where its farthest ring stays fixed. */ anchored: number; + /** A piece of the grown region still had no fixed grid nodes, so the feather was dropped. */ + unanchored: boolean; +} + +/** The one feather warning the panel shows, if any. */ +export function featherWarning( + feather: WarpFeather | null | undefined, +): 'unanchored' | 'anchored' | 'coarse' | null { + if (!feather) return null; + if (feather.unanchored) return 'unanchored'; + if (feather.anchored) return 'anchored'; + if (feather.joined === 0 && feather.edge > 0) return 'coarse'; + return null; } export interface WarpModel { @@ -70,14 +83,21 @@ export async function buildWarpModel(input: WarpModelInput): Promise faces?.length && width > 0 ? growWarpRegion(weld.indices, weld.vertices, positions, index, matrix, faces, width) : null; - const grown = growth && growth.joined > 0 ? growth : null; - const region = buildWarpRegion( + let grown = growth && growth.joined > 0 ? growth : null; + let region = buildWarpRegion( geometry, grown ? grown.faces : faces, weld, grown ? grown.pinned : undefined, ); - const grid = await buildWarpGrid(region, density); + let grid = await buildWarpGrid(region, density); + let unanchored = false; + if (grown && !bandPiecesHeld(region, grid, grown.paintedFace)) { + unanchored = true; + grown = null; + region = buildWarpRegion(geometry, faces, weld); + grid = await buildWarpGrid(region, density); + } const m = matrix; const restWorld = new Float64Array(region.rest.length); @@ -109,6 +129,7 @@ export async function buildWarpModel(input: WarpModelInput): Promise edge: growth.edge, fixedEdge, anchored: growth.anchored, + unanchored, }; } if (grown) { @@ -134,6 +155,58 @@ export async function buildWarpModel(input: WarpModelInput): Promise }; } +/** + * Whether every edge-connected piece of the region that holds band faces has at least two fixed + * grid nodes. One alone lets the piece swing about it. + */ +function bandPiecesHeld(region: WarpRegion, grid: WarpGrid, paintedFace: Uint8Array) { + const { weldedCount, triangles, faces } = region; + const count = faces.length; + const start = new Uint32Array(weldedCount + 1); + for (let i = 0; i < triangles.length; i++) start[triangles[i] + 1]++; + for (let v = 0; v < weldedCount; v++) start[v + 1] += start[v]; + const incident = new Uint32Array(triangles.length); + const fill = start.slice(0, weldedCount); + for (let i = 0; i < triangles.length; i++) incident[fill[triangles[i]]++] = (i - (i % 3)) / 3; + + const piece = new Int32Array(count).fill(-1); + const counted = new Int32Array(weldedCount).fill(-1); + const stack: number[] = []; + for (let seed = 0; seed < count; seed++) { + if (piece[seed] >= 0) continue; + let band = false, + fixed = 0; + piece[seed] = seed; + stack.push(seed); + while (stack.length) { + const t = stack.pop()!; + if (!paintedFace[faces[t]]) band = true; + for (let k = 0; k < 3; k++) { + const a = triangles[t * 3 + k], + b = triangles[t * 3 + ((k + 1) % 3)]; + const node = grid.nodeOf[a]; + if (node !== 0xffffffff && grid.fixed[node] && counted[a] !== seed) { + counted[a] = seed; + fixed++; + } + if (a === b) continue; + for (let e = start[a]; e < start[a + 1]; e++) { + const u = incident[e]; + if ( + piece[u] < 0 && + (triangles[u * 3] === b || triangles[u * 3 + 1] === b || triangles[u * 3 + 2] === b) + ) { + piece[u] = seed; + stack.push(u); + } + } + } + } + if (band && fixed < 2) return false; + } + return true; +} + /** Whether a geometry face is painted: in the region and, when feathered, not in the band. */ export function isPaintedFace(model: WarpModel, face: number) { const triangle = regionTriangleOf(model.region, face); diff --git a/tests/unit/warp-feather.test.ts b/tests/unit/warp-feather.test.ts index 8c72499..ae6e400 100644 --- a/tests/unit/warp-feather.test.ts +++ b/tests/unit/warp-feather.test.ts @@ -24,6 +24,7 @@ import { } from '../../src/core/warp-evaluate'; import { buildWarpModel, + featherWarning, isPaintedFace, isPaintedNode, warpNodeBlend, @@ -279,6 +280,30 @@ describe('feathered region growth', () => { expect(blend![ray[i]]).toBeLessThanOrEqual(blend![ray[i - 1]]); }); + it('shows one feather warning: none when joined, coarse when nothing joined, else the anchor', async () => { + const g = sheet(); + const joined = await buildWarpModel(inputOf(g, disc(g, 10), 3)); + expect(joined.feather).toMatchObject({ anchored: 0, unanchored: false }); + expect(joined.feather!.joined).toBeGreaterThan(0); + expect(featherWarning(joined.feather)).toBeNull(); + + const coarse = new PlaneGeometry(60, 60, 6, 6); + const tooCoarse = await buildWarpModel(inputOf(coarse, disc(coarse, 12), 1)); + expect(tooCoarse.feather).toMatchObject({ joined: 0, anchored: 0 }); + expect(featherWarning(tooCoarse.feather)).toBe('coarse'); + + // The anchor takes the whole band, so nothing joins, but the mesh is not too coarse. + const sphere = new SphereGeometry(10, 64, 48); + const faces: number[] = []; + for (let f = 0; f < faceCount(sphere); f++) if (centroid(sphere, f).y < 9.98) faces.push(f); + const anchored = await buildWarpModel(inputOf(sphere, faces, 4)); + expect(anchored.feather).toMatchObject({ joined: 0, edge: 64, anchored: 1 }); + expect(featherWarning(anchored.feather)).toBe('anchored'); + + expect(featherWarning(null)).toBeNull(); + expect(featherWarning({ ...anchored.feather!, unanchored: true })).toBe('unanchored'); + }); + it('keeps a fixed edge and says so when the mesh is too coarse for the width', async () => { const g = new PlaneGeometry(60, 60, 6, 6); const faces = disc(g, 12); @@ -291,6 +316,7 @@ describe('feathered region growth', () => { edge: expect.any(Number), fixedEdge: expect.any(Number), anchored: 0, + unanchored: false, }); expect(model.feather!.edge).toBeGreaterThan(0); expect(model.feather!.fixedEdge).toBeGreaterThan(0); @@ -504,6 +530,27 @@ describe('feathered surface', () => { expectOutsideKept(on, soft.out); }); + // Recorded, not passing: under a centred drag a six-ring band leaves the painted edge at 0.219 + // (regular) and 0.271 (irregular) of the unfeathered crease, above the design's 0.20. These + // limits hold it where it is. + it('holds the painted edge of a six-ring band to its recorded share under a centred drag', async () => { + for (const [g, limit] of [ + [sheet(), 0.222], + [irregularSheet(), 0.275], + ] as const) { + const { offEdge, onEdge, onOuter, rings } = await compareCreases( + g, + disc(g, 10), + 4.5, + undefined, + cluster, + ); + expect(rings).toBe(6); + expect(onEdge / offEdge).toBeLessThan(limit); + expect(onOuter).toBeLessThan(offEdge / 5); + } + }); + it('keeps a wider band smooth under a drag in the middle of the paint', async () => { const g = sheet(); const { offEdge, onEdge, onOuter, rings } = await compareCreases( @@ -595,10 +642,19 @@ describe('feathered surface at the default density', () => { expect(edge).toBeLessThanOrEqual(1.25 * interior + 0.1); it('leaves the painted edge no rougher than the paint inside it', async () => { - for (const at of [cluster, edgeCluster]) { + // Absolute limits, about 2% over what each strip measures now, so neither can get rougher. + const limits = [ + { at: cluster, strip: [0.87, 1.87], interior: [0.94, 1.67] }, + { at: edgeCluster, strip: [1.09, 2.4], interior: [1.22, 3.86] }, + ]; + for (const { at, strip: stripLimit, interior: interiorLimit } of limits) { const { strip, interior } = await edgeAgainstInterior(at); within(p95(strip), p95(interior)); within(strip.at(-1)!, interior.at(-1)!); + expect(p95(strip)).toBeLessThan(stripLimit[0]); + expect(strip.at(-1)!).toBeLessThan(stripLimit[1]); + expect(p95(interior)).toBeLessThan(interiorLimit[0]); + expect(interior.at(-1)!).toBeLessThan(interiorLimit[1]); } }); @@ -927,7 +983,7 @@ describe('feathered band limits', () => { expect(faceCount(g) - faces.length).toBe(448); const model = await buildWarpModel(inputOf(g, faces, 4)); expect(model.feather!.anchored).toBe(1); - expect(model.grid.fixed.reduce((n, x) => n + x, 0)).toBeGreaterThan(0); + expect(model.grid.fixed.reduce((n, x) => n + x, 0)).toBe(64); const drag = [new Vector3(10, 0, 0), new Vector3(1, 0, 0)] as const; const { out } = pull(model, g, ...drag); // The pole is in the anchor and keeps its bits. The far side swings about the fixed cap @@ -942,6 +998,55 @@ describe('feathered band limits', () => { expectOutsideKept(model, out); }); + it('anchors a closed part that another face touches at a single vertex', async () => { + // The vertex it touches is fixed, but a lone vertex is no fixed edge and the grid may drop it. + for (const contact of [(p: Vector3) => p.y < -9.999, (p: Vector3) => p.x < -9.99]) { + const sphere = new SphereGeometry(10, 64, 48); + const position = sphere.getAttribute('position'); + const p = new Vector3(); + let touch = 0; + while (!contact(p.fromBufferAttribute(position, touch))) touch++; + const out = p.clone().multiplyScalar(1.2); + const g = new BufferGeometry(); + g.setAttribute( + 'position', + new BufferAttribute( + new Float32Array([ + ...position.array, + out.x + 0.5, + out.y, + out.z, + out.x, + out.y + 0.5, + out.z, + ]), + 3, + ), + ); + const normal = sphere.getAttribute('normal'); + g.setAttribute( + 'normal', + new BufferAttribute(new Float32Array([...normal.array, 0, 0, 1, 0, 0, 1]), 3), + ); + g.setIndex([...sphere.index!.array, touch, position.count, position.count + 1]); + const faces: number[] = []; + for (let f = 0; f < faceCount(sphere); f++) if (centroid(g, f).y < 9.6) faces.push(f); + expect(faceCount(g) - faces.length).toBe(449); + const drag = [new Vector3(10, 0, 0), new Vector3(1, 0, 0)] as const; + const plain = await buildWarpModel(inputOf(g, faces)); + expect(plain.grid.fixed.reduce((n, x) => n + x, 0)).toBe(64); + expect( + largestMove(g, plain.positions, pull(plain, g, ...drag).out.positions, (q) => q.y > 9.9), + ).toBe(0); + const model = await buildWarpModel(inputOf(g, faces, 4)); + expect(model.feather).toMatchObject({ anchored: 1, unanchored: false }); + expect(model.grid.fixed.reduce((n, x) => n + x, 0)).toBe(64); + const { out: moved } = pull(model, g, ...drag); + expect(largestMove(g, model.positions, moved.positions, (q) => q.y > 9.9)).toBe(0); + expectOutsideKept(model, moved); + } + }); + it('keeps an unpainted rim inside the band fixed and feathers toward it', async () => { const g = sheet(); // The band reaches the sheet's open edge at x = 30. From 108b5e6969d12057bc632cb4bf623064a4ee0451 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Wed, 18 Nov 2026 01:45:29 -0800 Subject: [PATCH 10/25] Rework warp handle guides around baseline snapshots --- .../specs/2026-11-17-warp-handles-design.md | 127 +-- src/components/WarpControls.tsx | 138 +++- src/components/WarpOverlay.tsx | 73 +- src/core/store.ts | 508 ++++++++---- src/core/warp-handles.ts | 738 ++++++++++++------ tests/e2e/warp.spec.ts | 83 ++ tests/unit/free-transform.test.ts | 1 + tests/unit/transform-selection.test.ts | 10 + tests/unit/warp-benchmark.test.ts | 17 +- tests/unit/warp-first-drag.test.ts | 180 +++++ tests/unit/warp-handles.test.ts | 681 +++++++++++----- tests/unit/warp-session.test.ts | 398 ++++++++-- 12 files changed, 2163 insertions(+), 791 deletions(-) create mode 100644 tests/unit/warp-first-drag.test.ts diff --git a/docs/superpowers/specs/2026-11-17-warp-handles-design.md b/docs/superpowers/specs/2026-11-17-warp-handles-design.md index 83c2398..85369bb 100644 --- a/docs/superpowers/specs/2026-11-17-warp-handles-design.md +++ b/docs/superpowers/specs/2026-11-17-warp-handles-design.md @@ -97,12 +97,13 @@ handles (section 6) and the brush-size shortcuts all use it while warping. ### 3. Even pins **Distribute points** in the Control points section: a count (4, 8, 16, 32; default 8) and a -button. It adds that many unmoved points by farthest-point sampling over the grid's free -nodes, measured along grid edges, seeded by the points already present. It is deterministic -(fixed first seed and tie-break), never puts two points on one node, gives each disconnected -piece of the region a point before doubling up, and stops at the number of free nodes. Each -point sits on a node's own scan vertex and pins the surface where it is now. One session -undo step. +button. It adds that many unmoved points. First every connected piece of the region that has no +point gets one, larger pieces first, at its node farthest along the grid from its edge. Then +farthest-point sampling over the free nodes, measured along grid edges, from the points +present, those chosen and the region's edge. It is deterministic (lowest node first among +ties), never puts two points on one node, and stops at the number of free nodes. Each point sits +on a node's own scan vertex and pins the surface where it is now. One session undo step. With a +feathered region it uses painted free nodes only. Distributed points are ordinary points with radius 0 (section 4), marked automatic until the user moves or edits them. @@ -110,49 +111,62 @@ the user moves or edits them. When the region is effectively the whole part (Whole part, or Painted with nothing painted), the Region stage shows "Place points automatically" (on, with the same count), and the first lay of the grid distributes them. Changing density, returning from Edit -region, or deleting them never places them again. Close gap removes automatic points that -are still untouched and sit on the nodes it is about to pull, in the same undo step, so a -seam still closes; points the user placed or moved are kept. +region, or deleting them never places them again. + +An untouched automatic point inside the reach of a moved handle rides to where the guides take +the surface at its nodes, so a bump rises smoothly over it instead of pinching; it holds its pin +wherever nothing guided moves. A point the user placed always holds. + +Close gap releases, in the same undo step, the untouched automatic points that would hold its +seam open: it walks the grid from the nodes it pulls, never onto a node facing away from where +its pulled node goes, settles once without the automatic points it reached, and releases those +whose spot that settle moves by more than 5 % of the largest pull. Points on other pieces, on +the far side of a thin wall, or that the seam would not move stay. Points the user placed or +moved are kept. ### 4. Radius and falloff -Every handle (a control point, or a line or area from section 6) has a **radius** in mm and -a **falloff** from 0 to 100 %, edited in the Control points section for the selected -handles. New handles take the last values used. Radius is 0 ("point only") or a value on a -fitted logarithmic slider. Defaults: radius 6 % of the part's size, but no more than a -quarter of the region's extent; falloff 100 %. - -The handle's sample constraints stay exactly as they are today, at every radius: they are -what puts the grabbed surface on the target. Radius adds **guides** around them. - -- **Reach.** One bounded multi-source Dijkstra over grid edges (world rest lengths), seeded - from the nodes each sample is bound to, at their distance from the sample. Free nodes - within the radius are in reach. Cached per handle; falloff remaps cached distances. -- **Weight.** `w` is 1 out to `radius × (1 − falloff)`, then a smoothstep to 0 at the - radius. Falloff 0 is a hard-edged plateau, with no division by a zero width. -- **Guide.** Each node in reach gets a soft target `base(n) + w × D`, where `D` is how far - the handle has moved from its pin, at stiffness `κ × w × (that node's edge diagonal)`. - Stiffness reaches zero at the radius, so nothing switches on abruptly there. -- **Baseline.** `base(n)` is where the node was when the guide was made, so an unmoved - handle's guide holds the surface as it is and adding a handle changes nothing. Whenever a - handle's reach is rebuilt (radius change, density change), `base(n)` is the node's current - settled position minus `w_before(n) × D`, with `w_before` the weight that node had from - this handle before the change. After a density change this reproduces the shape that was - there; after a radius change it widens or narrows the handle's own bump. -- **Several handles on one node.** Stiffnesses add, and the target is their - stiffness-weighted mean. There is no case with two exact but different answers: only - sample constraints are exact. -- **Solver.** `solveWarp` takes an optional per-node guide set (node, stiffness, target): - one diagonal term and one right-hand-side term per node. Guide nodes and stiffnesses are - part of the cached system's key; targets are not, so a drag reuses the system. -- Gap targets stay full-strength constraints and are not skipped under a guide. -- If the radius reaches no node beyond the sample's own, the handle behaves as radius 0 and - the panel says that a finer grid would let the radius take effect. - -`κ` is the builder's to set. It is right when, on a fine flat sheet with a far fixed border, -a point lifted by `h` with falloff 100 % gives a written surface that falls monotonically -from the point, is at least `0.9 h` at a tenth of the radius, within `0.1 h` of -`h × smoothstep` across the radius, and under `0.03 h` beyond it. +Every handle has a **radius** in mm and a **falloff** from 0 to 100 %, edited in the Control +points section for the selected handles. New handles take the last values set. Until the user +sets a radius, a new point takes the larger of 6 % of the part's size and 4.5 node spacings +where it is clicked, no more than a quarter of the region's extent. Radius 0 is a bare point; +automatic points are radius 0. Effectively whole regions are laid at the 2,000-node level and +painted ones at 500 unless the user has chosen a density. + +The handle's sample constraints stay exactly as they are at every radius: they place the grab. +Radius adds soft per-node **guides** around them. + +- **Baseline.** A handle refers to a snapshot of the settled grid (positions and rotations), + taken when it is created, and replaced by the settled grid when an unmoved handle with no + active guides starts its first move or first gets a radius. Snapshots are never changed and + are shared by reference between handles made on the same surface and all undo versions. +- **Reach.** Distance from the footprint is the larger of the straight-line distance and the + path along grid edges divided by 1.16 (the overstatement of edge paths on the simplified + flat grids, median 1.06, 99th percentile 1.15). It is round on flat areas and cannot cross a + fold. Fixed nodes, and with a feather unpainted ones, are never reached. A footprint is a set + of source points plus nodes that move as one; a point's footprint is its sample alone. +- **Weight.** `w` is 1 out to `radius − fade`, then a smoothstep to 0 at the radius. The fade + runs from 1.5 node spacings, the narrowest the grid holds, at falloff 0 to the whole radius at + falloff 100 %, so every step of the slider changes the result. The panel states the fade. +- **Activation.** All of a handle's radius guides are scaled by a smoothstep that rises from 0 + at one local node spacing of radius to 1 at two, so the surface is continuous in the radius. +- **Terms.** At each node a handle has a profile: unmoved, `w`, holding softly over its radius; + moved, 1 out to the radius, fading over a band of 2.5 spacings (3.5 at falloff 0) to a quarter, + then to 0 over 10 more spacings. It drives the node toward `baseline + offset` at stiffness + `κ w diag` and holds it at its baseline for the rest of the profile, so alone it targets + `baseline + w × offset`, never more than the offset. A holding term, and all of an unmoved + handle's profile, gives way by the largest driving weight any other moved handle has there. + Unmoved becomes moved over the first quarter spacing of travel, so nothing jumps. `κ = 4`. +- **Accumulation.** Stiffnesses add and the target is their stiffness-weighted mean; nothing + depends on the order of handles. Gap-target nodes get no guides. +- **Solver.** `solveWarp` takes the per-node guide set. Guide nodes and stiffnesses are part of + the cached system's key; targets are not, so a drag reuses the system. +- **Edits.** A radius or falloff change only recomputes reach and weights; nothing settles on a + slider frame. Each slider gesture has one owner and is one undo step. + +On a fine flat sheet with a far fixed border, a point lifted by `h` with falloff 100 % falls +monotonically from the point, is 0.957 h at a tenth of the radius, within 0.08 h of +`h × smoothstep` across the radius and under 0.02 h beyond it. ### 5. Feathered edge @@ -229,16 +243,19 @@ smaller than a cell and a 60-node grid. ### Data model -`WarpPoint` becomes the handle above. A point is a handle with one sample and keeps its -`target` meaning. `moveWarpPoints` keeps taking one target per handle. `selectedPoints`, -session undo (which compares radius and falloff as well as targets), rebinding after a -density or region change, undo snapshots, Apply's restart and the live-refusal recovery all -carry handles. Rebinding drops samples whose face left the region and a handle with none -left. +`WarpPoint` is a `WarpHandle`: `kind` (`point`; `line` and `area` are reserved), immutable +samples, `radius`, `falloff`, `auto`, one `target` (null while unmoved), `baseline` (a shared +snapshot) and a cached `reach`. `moveWarpPoints` keeps taking one target per handle. + +Each session undo step holds the points, gap targets, the settled grid they held and the +settings new points take, so undo restores the surface exactly without solving. Laying the +same region at the same density and feather keeps the model. A real rebuild carries each +distinct snapshot to the new grid once, through the old binding of each new node's scan vertex, +rebinds samples, and drops handles whose samples are bound only to fixed nodes, from the session +and its undo steps; undo across it settles from the carried grid. -A pure module, `warp-handles.ts`, turns handles and a model into solver input: reach, -weights, guides and baselines, and farthest-point distribution. It is unit-tested without -the store. +A pure module, `warp-handles.ts`, turns handles and a model into solver input: reach, weights, +guides, snapshots and their transfer, and distribution. It is unit-tested without the store. ## Approaches considered diff --git a/src/components/WarpControls.tsx b/src/components/WarpControls.tsx index 2f84a1e..3f97f71 100644 --- a/src/components/WarpControls.tsx +++ b/src/components/WarpControls.tsx @@ -1,4 +1,10 @@ -import { useEffect, useMemo, useRef } from 'react'; +import { + useEffect, + useMemo, + useRef, + type FocusEvent, + type PointerEvent as ReactPointerEvent, +} from 'react'; import { LoaderCircle, TriangleAlert } from 'lucide-react'; import { clipLimits } from '../core/clipping'; import { fittedSizeRange, partSize } from '../core/geometry'; @@ -13,68 +19,110 @@ import { } from '../core/store'; import type { Part } from '../core/types'; import { warpDensityNodes } from '../core/warp-grid'; +import { fadeWidth, handleGuides } from '../core/warp-handles'; import { featherWarning } from '../core/warp-model'; import { SurfaceBrushControls } from './SurfaceBrushControls'; import { TransformAdjustments } from './TransformAdjustments'; import { LogRangeInput, NumericInput, RadioGroup, Section } from './ui'; type PointSettings = { radius?: number; falloff?: number }; +type Slider = 'radius' | 'falloff'; /** - * Sends a slider's changes to the selected points at most once a frame, and its release as one - * step. A range input fires a native change when it is let go, by pointer or by key. + * A slider gesture on the selected points' settings. It belongs to the slider it began on and, + * for a drag, to its pointer. Changes reach the points at most once a frame, and the gesture ends + * exactly once, as one step: on release, the slider's own change, pointer cancel, lost capture + * or window blur. Blur from any other control ends nothing. */ function usePointSettingsGesture() { - const pending = useRef(null), - frame = useRef(0), - container = useRef(null); - const end = useMemo(() => { - const finish = () => { - cancelAnimationFrame(frame.current); - frame.current = 0; - window.removeEventListener('pointerup', finish); - const patch = pending.current; - pending.current = null; - if (patch) useEditor.getState().setWarpPointSettings(patch, 'end'); + const current = useRef<{ + slider: Slider; + pointer: number | null; + patch: PointSettings | null; + frame: number; + } | null>(null); + const gesture = useMemo(() => { + const release = (event: PointerEvent) => { + const owner = current.current; + if (owner && (owner.pointer === null || owner.pointer === event.pointerId)) end(); }; - return finish; - }, []); - useEffect(() => { - const element = container.current!; - element.addEventListener('change', end); - return () => { - element.removeEventListener('change', end); + const blur = () => end(); + const end = (slider?: Slider) => { + const owner = current.current; + if (!owner || (slider && owner.slider !== slider)) return; + current.current = null; + cancelAnimationFrame(owner.frame); + window.removeEventListener('pointerup', release); + window.removeEventListener('pointercancel', release); + window.removeEventListener('blur', blur); + if (owner.patch) useEditor.getState().setWarpPointSettings(owner.patch, 'end'); + }; + const begin = (slider: Slider, pointer: number | null) => { end(); + current.current = { slider, pointer, patch: null, frame: 0 }; + window.addEventListener('pointerup', release); + window.addEventListener('pointercancel', release); + window.addEventListener('blur', blur); + }; + const change = (slider: Slider, patch: PointSettings) => { + if (current.current?.slider !== slider) begin(slider, null); + const owner = current.current!; + owner.patch = { ...owner.patch, ...patch }; + if (owner.frame) return; + owner.frame = requestAnimationFrame(() => { + owner.frame = 0; + if (current.current === owner && owner.patch) + useEditor.getState().setWarpPointSettings(owner.patch, 'drag'); + }); }; - }, [end]); - const drag = (patch: PointSettings) => { - if (!pending.current) window.addEventListener('pointerup', end); - pending.current = { ...pending.current, ...patch }; - if (frame.current) return; - frame.current = requestAnimationFrame(() => { - frame.current = 0; - if (pending.current) useEditor.getState().setWarpPointSettings(pending.current, 'drag'); - }); - }; - return { container, drag, end }; + return { begin, change, end }; + }, []); + useEffect(() => () => gesture.end(), [gesture]); + return gesture; } +const isSlider = (target: EventTarget) => + target instanceof HTMLInputElement && target.type === 'range'; + /** Radius, falloff and Distribute points, for the selected points or for new ones. */ function PointSettingsControls({ warp, part }: { warp: WarpSession; part: Part | undefined }) { - const { container, drag, end } = usePointSettingsGesture(); + const gesture = usePointSettingsGesture(); const selected = warp.points.filter((point) => warp.selectedPoints.includes(point.id)); const shown = selected[0]; const radius = shown ? shown.radius : warpPointRadius(warp, part); const falloff = shown ? shown.falloff : warp.pointFalloff; const { max } = fittedSizeRange(part ? partSize(part) : 40); - const coarse = selected.some( - (point) => point.radius > 0 && point.reach && !point.reach.effective, - ); + const coarse = selected.some((point) => point.radius > 0 && !handleGuides(point)); + const fade = shown && handleGuides(shown) ? fadeWidth(shown) : null; const commit = (patch: PointSettings) => useEditor.getState().setWarpPointSettings(patch, 'end'); - const gesture = { onKeyUp: end, onBlur: end }; + const owned = (slider: Slider) => ({ + 'data-slider': slider, + onPointerDown: (event: ReactPointerEvent) => { + if (isSlider(event.target)) gesture.begin(slider, event.pointerId); + }, + onBlur: (event: FocusEvent) => { + if (isSlider(event.target)) gesture.end(slider); + }, + onLostPointerCapture: (event: ReactPointerEvent) => { + if (isSlider(event.target)) gesture.end(slider); + }, + }); + const container = useRef(null); + useEffect(() => { + const element = container.current!; + // A range input fires a native change when it is let go, by pointer or by key. + const changed = (event: Event) => { + const slider = (event.target as Element) + .closest('[data-slider]') + ?.getAttribute('data-slider'); + if (slider && isSlider(event.target!)) gesture.end(slider as Slider); + }; + element.addEventListener('change', changed); + return () => element.removeEventListener('change', changed); + }, [gesture]); return (
-
diff --git a/src/core/commands.ts b/src/core/commands.ts index 7e53521..83b941a 100644 --- a/src/core/commands.ts +++ b/src/core/commands.ts @@ -117,7 +117,7 @@ export function editorCommands(context: CommandContext = {}) { () => { const target = undoTarget(state); if (target === 'stroke') state.undoPaintStroke(); - else if (target === 'warp') state.undoWarpEdit(); + else if (target === 'warp') void state.undoWarpEdit(); else if (target === 'scene') state.undo(); }, idle && undoAvailable(state), diff --git a/src/core/store.ts b/src/core/store.ts index 09854c7..7c5645f 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -94,9 +94,10 @@ import { warpUpdateRanges, type WarpOutput, } from './warp-evaluate'; -import { defaultWarpDensity, warpDensityNodes } from './warp-grid'; +import { defaultWarpDensity, warpDensityNodes, type WarpGrid } from './warp-grid'; import { distributionNodes, + handleCarry, handleConstraints, handleGuides, heldWhereItIs, @@ -269,6 +270,8 @@ export interface WarpSession { undo: WarpEdit[]; /** The last edit's solve has not converged yet. It goes on settling in idle frames. */ settling: boolean; + /** Apply was pressed while settling: it bakes once the surface settles, unless an edit comes. */ + applying?: boolean; } /** * A session step: the points and gap targets, the settled grid they held, and the settings new @@ -277,8 +280,25 @@ export interface WarpSession { type WarpEdit = Pick< WarpSession, 'points' | 'gapTargets' | 'surface' | 'pointRadius' | 'pointFalloff' ->; +> & { + /** On the step a density change records: the grid it undoes to, rebuilt when it is undone. */ + grid?: WarpGridStep; +}; type WarpLaid = { faces: number[] | null; density: number; feather: number }; +/** + * The grid a density change left. Its steps' snapshots name `token` instead of the grid, so the old + * model can be let go; undoing rebuilds it from `laid` and puts them back on it. + */ +interface WarpGridStep { + laid: WarpLaid; + region: WarpSession['region']; + faces: number[]; + seed: WarpSession['seed']; + densityChosen: boolean; + token: WarpGrid; + /** Of the old model, to tell that the rebuild is the same grid. */ + fingerprint: number; +} export interface WarpFeatherOption { enabled: boolean; @@ -444,8 +464,13 @@ interface EditorState { distributeWarpPoints: () => void; /** Pulls the grid nodes that face a nearby part onto its surface, at the overlap depth. */ closeWarpGap: () => void; - undoWarpEdit: () => void; - /** Bakes the warp into the part as one undo step, then starts again on the result. */ + /** Undoes a session step. Undoing a density change rebuilds the grid it left; this awaits it. */ + undoWarpEdit: () => Promise; + /** + * Bakes the warp into the part as one undo step, then starts again on the result. A surface + * still settling settles first: in the browser in idle steps, baking once it settles and + * returning false meanwhile. + */ applyWarp: () => boolean; /** The live server took the applied warp, or refused it. */ submitWarp: () => void; @@ -581,6 +606,7 @@ const newWarpSession = (part: Part, epoch: number, faces: number[] = []): WarpSe seam: null, undo: [], settling: false, + applying: false, }); export const warpDistributeCounts = [4, 8, 16, 32] as const; @@ -637,7 +663,10 @@ export function warpPointRadius( return radius > 0 ? Number(radius.toPrecision(2)) : 0; } -type WarpSettled = Pick & { stage: 'region' | 'warp'; density: number }; +type WarpSettled = Pick & { + stage: 'region' | 'warp'; + density: number; +}; // The grid build in flight, and the stage, density and feather to return to if it is cancelled or // fails. let warpBuild: { controller: AbortController; from: WarpSettled } | null = null; @@ -645,8 +674,18 @@ let warpBuild: { controller: AbortController; from: WarpSettled } | null = null; /** The session before this build, or before the build in flight that it replaces. */ const settledWarp = (warp: WarpSession): WarpSettled => warp.stage === 'building' - ? (warpBuild?.from ?? { stage: 'region', density: warp.density, feather: warp.feather }) - : { stage: warp.stage, density: warp.density, feather: warp.feather }; + ? (warpBuild?.from ?? { + stage: 'region', + density: warp.density, + feather: warp.feather, + densityChosen: warp.densityChosen, + }) + : { + stage: warp.stage, + density: warp.density, + feather: warp.feather, + densityChosen: warp.densityChosen, + }; function abortWarpBuild() { const build = warpBuild; @@ -714,6 +753,23 @@ function warpBinding(model: WarpModel, triangle: number, barycentric: Vec3) { }; } +/** + * Why a new model would drop a handle: none of its samples is painted there, or every node they are + * bound to is fixed, so it could not move the surface. Null when it stays. + */ +function droppedBy(model: WarpModel, handle: WarpPoint): 'unpainted' | 'fixed' | null { + const painted = handle.samples.filter(({ face }) => isPaintedFace(model, face)); + if (!painted.length) return 'unpainted'; + const { fixed } = model.grid; + return painted.every(({ face, barycentric }) => + warpBinding(model, regionTriangleOf(model.region, face), barycentric).binding.node.every( + (node) => fixed[node], + ), + ) + ? 'fixed' + : null; +} + /** * Binds a handle to a new model, dropping samples and an area's faces that are no longer painted * in its region, and samples the new grid binds exactly as another. Null when no sample is left, @@ -828,6 +884,25 @@ export function warpShortfall(warp: WarpSession) { /** A selected handle whose surface stops farther than this from its target says so, mm. */ export const warpShortfallShown = 0.02; +/** + * How far the written surface has moved from the pins of the selected unmoved handles the user + * placed, at worst, mm. Untouched automatic points ride with the surface, so they are left out. + */ +export function warpPinDrift(warp: WarpSession) { + const { model, state } = warp; + if (!model || !state || warp.stage !== 'warp') return 0; + let worst = 0; + for (const point of warp.points) + if (point.target === null && !point.auto && warp.selectedPoints.includes(point.id)) { + const at = writtenCentre(model, state, point); + worst = Math.max( + worst, + Math.hypot(at[0] - point.pin[0], at[1] - point.pin[1], at[2] - point.pin[2]), + ); + } + return worst; +} + /** Whether Apply would change the mesh. */ export const warpChanges = (warp: WarpSession) => warp.gapTargets.length > 0 || warp.points.some(holdsWarp); @@ -845,6 +920,7 @@ type WarpSolveInput = Pick; function warpConstraints( { model, points, gapTargets }: WarpSolveInput, guides: WarpGuides | undefined, + carry?: ReadonlyMap, ): WarpConstraint[] { const rest = model!.restNodes; return [ @@ -853,6 +929,7 @@ function warpConstraints( model!, guides, gapTargets.map(({ node }) => node), + carry, ), // A seam closes as exactly as a point the user moved lands. ...gapTargets.map(({ node, target }) => ({ @@ -873,6 +950,26 @@ const sessionGuides = ({ model, points, gapTargets }: WarpSolveInput) => gapTargets.map(({ node }) => node), ); +/** + * What the solve is given: guides and constraints, with each grab the fixed edge or a pin holds + * back carrying only the share of its offset it can. A drag frame solves without priority. + */ +function warpSolveInput(warp: WarpSolveInput, drag = false) { + const exact = warp.gapTargets.map(({ node }) => node); + const plain = (constraints: WarpConstraint[]) => + drag + ? constraints.map(({ strength, ...constraint }) => (void strength, constraint)) + : constraints; + let guides = sessionGuides(warp); + let constraints = plain(warpConstraints(warp, guides)); + const carry = handleCarry(warp.model!, warp.points, constraints, guides, exact); + if (carry.size) { + guides = warpGuides(warp.model!, warp.points, exact, carry); + constraints = plain(warpConstraints(warp, guides, carry)); + } + return { guides, constraints }; +} + /** World box around the grid as it is now deformed. */ function warpBounds(state: WarpState) { const box = new Box3(), @@ -1006,21 +1103,13 @@ function solveWarpSession( measure = true, ): WarpSession { const model = warp.model!; - const guides = sessionGuides(warp); - const constraints = warpConstraints(warp, guides); + // A drag frame costs what it did before priority: the end of the gesture lands the handle. + const { guides, constraints } = warpSolveInput(warp, gesture === 'drag'); let move = 0; // With nothing holding it, the grid rests rather than staying where the last points left it. if (!constraints.length) warp = { ...warp, state: createWarpState(model.restNodes) }; else if (gesture === 'drag') - // A drag frame costs what it did before priority: the end of the gesture lands the handle. - solveWarp( - model.grid, - model.restNodes, - constraints.map(({ strength, ...constraint }) => (void strength, constraint)), - warp.state!, - warpDragIterations, - guides, - ); + solveWarp(model.grid, model.restNodes, constraints, warp.state!, warpDragIterations, guides); else move = settleGrid(model, constraints, warp.state!, guides); if (gesture === 'end') return showWarp( @@ -1058,6 +1147,13 @@ let warpSettled: { } = { warp: null, iterations: 0, drawn: 0 }; let settleTimer: ReturnType | undefined; +/** Stops idle settling and lets go of the session it was settling. */ +function forgetWarpSettle() { + clearTimeout(settleTimer); + settleTimer = undefined; + warpSettled = { warp: null, iterations: 0, drawn: 0 }; +} + function scheduleWarpSettle() { if (typeof window === 'undefined' || settleTimer !== undefined) return; settleTimer = setTimeout(() => { @@ -1085,8 +1181,9 @@ function stepWarpSettle(budget: number) { ) { progress.warp = warp; progress.iterations = 0; - progress.guides = sessionGuides(warp); - progress.constraints = warpConstraints(warp, progress.guides); + const input = warpSolveInput(warp); + progress.guides = input.guides; + progress.constraints = input.constraints; } const deadline = performance.now() + budget; let move = Infinity; @@ -1106,17 +1203,19 @@ function stepWarpSettle(budget: number) { performance.now() < deadline ); if (move < warpConvergedMove || progress.iterations >= warpSettleLimit) { - const next = showWarp(scene, { ...warp, settling: false, surface: null }); - progress.warp = null; + // An Apply waiting for this replaces the session, so the seam is not measured. + const next = showWarp(scene, { ...warp, settling: false, surface: null }, !warp.applying); + forgetWarpSettle(); useEditor.setState({ warp: next }); + if (next.applying) useEditor.getState().applyWarp(); return false; } const now = performance.now(); let next = warp; if (now - progress.drawn >= warpSettleRedraw) { progress.drawn = now; - deformWarpPreview(warp, 'drag'); - next = { ...warp }; + // Folds are counted on the surface shown, so the panel never reports an older one. + next = { ...warp, folds: deformWarpPreview(warp, 'end')! }; progress.warp = next; } if (next !== warp) useEditor.setState({ warp: next }); @@ -2113,7 +2212,7 @@ export const useEditor = create((set, get) => ({ }, layWarpGrid: async () => { const { warp } = get(); - if (warp) await layWarp(settledWarp(warp), true); + if (warp) await layWarp(settledWarp(warp), 'region'); }, setWarpDensity: async (density) => { const { warp } = get(); @@ -2125,7 +2224,7 @@ export const useEditor = create((set, get) => ({ } const from = settledWarp(warp); set({ warp: { ...warp, density: level, densityChosen: true } }); - if (warp.stage !== 'region') await layWarp(from); + if (warp.stage !== 'region') await layWarp(from, 'density'); }, setWarpFeather: (patch) => set((state) => { @@ -2142,8 +2241,7 @@ export const useEditor = create((set, get) => ({ abortWarpBuild(); clearTimeout(seamTimer); warpDrag = null; - clearTimeout(settleTimer); - settleTimer = undefined; + forgetWarpSettle(); disposeWarpPreview(warp.preview); set({ warp: null, painting: false, paintHistory: [] }); if (notice) get().notify(notice, 'info'); @@ -2406,9 +2504,7 @@ export const useEditor = create((set, get) => ({ // Found on the surface the points alone hold, so pressing again or changing the overlap keeps // the nodes earlier targets pulled in. const held = createWarpState(model.restNodes); - const pointsOnly = { ...warp, gapTargets: [] }; - const guides = sessionGuides(pointsOnly); - const constraints = warpConstraints(pointsOnly, guides); + const { guides, constraints } = warpSolveInput({ ...warp, gapTargets: [] }); if (constraints.length) settleGrid(model, constraints, held, guides); const { neighbours, indexing } = warpNeighbours(state.scene, warp.partId, warpBounds(held)); if (indexing.length) { @@ -2444,8 +2540,8 @@ export const useEditor = create((set, get) => ({ positions: warp.state!.positions.slice(), rotations: warp.state!.rotations.slice(), }; - const guides = sessionGuides(free); - settleGrid(model, warpConstraints(free, guides), trial, guides); + const input = warpSolveInput(free); + settleGrid(model, input.constraints, trial, input.guides); let pull = 0; for (const { node, target } of gapTargets) pull = Math.max(pull, distanceTo(held.positions, node, target)); @@ -2487,9 +2583,12 @@ export const useEditor = create((set, get) => ({ const state = get(), warp = state.warp, step = warp?.undo.at(-1); - if (!warp || !step) return; + // A grid being built finishes or is cancelled first. + if (!warp || !step || warp.stage === 'building') return Promise.resolve(); warpDrag = null; + if (step.grid) return layWarp(settledWarp(warp), step.grid); set({ warp: restoreWarp(state.scene, { ...warp, undo: warp.undo.slice(0, -1) }, step) }); + return Promise.resolve(); }, applyWarp: () => { const state = get(), @@ -2506,7 +2605,19 @@ export const useEditor = create((set, get) => ({ state.notify(`Unlock ${part.name} to apply the warp.`, 'info'); return false; } + // A surface still settling would bake a shape that is still changing: it settles first, in idle + // steps, and bakes then. Without idle frames to settle in, it settles here. + if (warp.settling) { + if (!warp.applying) set({ warp: { ...warp, applying: true } }); + if (typeof window !== 'undefined') { + scheduleWarpSettle(); + return false; + } + finishWarpSettling(); + return get().scene.parts.some((p) => p.id === part.id && p.geometry !== part.geometry); + } warpDrag = null; + forgetWarpSettle(); // The session starts again on the result, keeping the region and options. const { region, @@ -2526,8 +2637,8 @@ export const useEditor = create((set, get) => ({ const keep = !state.warpPending && (state.liveStatus === 'connected' || state.liveStatus === 'disconnected'); - // Exactly the surface shown. A grid still settling stops where it is. - const settled = { ...warp, settling: false }; + // Exactly the surface shown, which has settled. + const settled = { ...warp, applying: false }; const geometry = appliedWarpGeometry(warp.source, settled.output!); const warped: Part = { ...part, geometry, source: `Warp · ${part.source}` }; if (!keep) disposeWarpPreview(settled.preview); @@ -3574,29 +3685,125 @@ const sameLaid = (a: WarpLaid, b: WarpLaid) => a.faces.length === b.faces.length && a.faces.every((face, i) => face === b.faces![i]))); +/** A hash of what a grid build makes, to tell that a rebuild made the same model. */ +function warpFingerprint(model: WarpModel) { + let hash = 0x811c9dc5; + const { grid, binding } = model; + for (const array of [ + grid.nodes, + grid.fixed, + grid.edgeStart, + grid.edges, + model.restNodes, + binding.node, + binding.weight, + model.blend, + ]) { + if (!array) continue; + const words = + array.byteOffset % 4 === 0 && array.byteLength % 4 === 0 + ? new Uint32Array(array.buffer, array.byteOffset, array.byteLength / 4) + : new Uint8Array(array.buffer, array.byteOffset, array.byteLength); + hash = Math.imul(hash ^ words.length, 0x01000193); + for (let i = 0; i < words.length; i++) hash = Math.imul(hash ^ words[i], 0x01000193); + } + return hash >>> 0; +} + +/** A grid that stands for one no model holds any more, in the steps recorded on it. */ +const detachedGrid = (): WarpGrid => ({ + nodes: new Uint32Array(0), + nodeOf: new Uint32Array(0), + fixed: new Uint8Array(0), + triangles: new Uint32Array(0), + edgeStart: new Uint32Array(1), + edges: new Uint32Array(0), +}); + +/** + * Steps with every snapshot on grid `from` moved to grid `to`, sharing what they shared. Points + * moved off a model lose their reach and their bindings' caches; points moved onto `model` measure + * their reach on it. + */ +function moveSteps(steps: WarpEdit[], from: WarpGrid, to: WarpGrid, model?: WarpModel) { + const snapshots = new Map(); + const snapshot = (value: WarpSnapshot) => { + if (value.grid !== from) return value; + let moved = snapshots.get(value); + if (!moved) snapshots.set(value, (moved = { ...value, grid: to })); + return moved; + }; + const points = new Map(); + const point = (value: WarpPoint) => { + if (value.baseline.grid !== from) return value; + let moved = points.get(value); + if (!moved) { + moved = model + ? reachHandle(model, { ...value, baseline: snapshot(value.baseline), reach: null }) + : { + ...value, + baseline: snapshot(value.baseline), + reach: null, + // New arrays, so nothing cached for the old grid stays reachable through them. + samples: value.samples.map((sample) => ({ + ...sample, + binding: { + ...sample.binding, + node: [...sample.binding.node], + weight: [...sample.binding.weight], + }, + })), + }; + points.set(value, moved); + } + return moved; + }; + return steps.map((step) => ({ + ...step, + points: step.points.map(point), + surface: step.surface && snapshot(step.surface), + })); +} + /** * Lays the session's grid. A build that stops returns the session to `from`. Laying from the region - * stage takes the page's feather option; a rebuild keeps the feather the session was laid with. + * stage takes the page's feather option; a rebuild keeps the feather the session was laid with. A + * density change is one session undo step, and undoing it, given its grid step, rebuilds the grid + * it left and restores that step on it exactly. A density change that would drop a handle, or a new + * region that would leave a moved one on its fixed edge rather than outside the paint, is not made. */ -async function layWarp(from: WarpSettled, fromRegion = false) { +async function layWarp(from: WarpSettled, kind: 'region' | 'density' | WarpGridStep) { const state = useEditor.getState(), warp = state.warp; const part = warp && state.scene.parts.find((p) => p.id === warp.partId); if (!warp || part?.geometry !== warp.source) return; abortWarpBuild(); + const restore = typeof kind === 'object' ? kind : null; // An empty painted region would leave the grid nothing to simplify, so it means the whole part. - const faces = warp.region === 'painted' && warp.faces.length ? warp.faces : null; - const feather = !faces - ? 0 - : !fromRegion - ? (warp.feather ?? 0) - : state.warpFeather.enabled - ? (state.warpFeather.width ?? warpBrushRadius(state)) - : 0; - const density = warp.densityChosen ? warp.density : faces ? defaultWarpDensity : warpWholeDensity; + const faces = restore + ? restore.laid.faces + : warp.region === 'painted' && warp.faces.length + ? warp.faces + : null; + const feather = restore + ? restore.laid.feather + : !faces + ? 0 + : kind === 'density' + ? (warp.feather ?? 0) + : state.warpFeather.enabled + ? (state.warpFeather.width ?? warpBrushRadius(state)) + : 0; + const density = restore + ? restore.laid.density + : warp.densityChosen + ? warp.density + : faces + ? defaultWarpDensity + : warpWholeDensity; const laid: WarpLaid = { faces, density, feather }; // The same region at the same density keeps its grid, so nothing moves. - if (warp.model && warp.laid && sameLaid(warp.laid, laid)) { + if (!restore && warp.model && warp.laid && sameLaid(warp.laid, laid)) { if (warp.settling) scheduleWarpSettle(); useEditor.setState({ painting: false, @@ -3643,9 +3850,81 @@ async function layWarp(from: WarpSettled, fromRegion = false) { const current = useEditor.getState().warp; if (warpBuild !== build || !current) return; warpBuild = null; + const { scene, notify } = useEditor.getState(); + const old = current.model; + + if (restore) { + forgetWarpSettle(); + const output = createWarpOutput(model); + disposeWarpPreview(current.preview); + const same = warpFingerprint(model) === restore.fingerprint; + const rest = { ...snapshotOf(model.grid, createWarpState(model.restNodes)), settled: false }; + // Rebuilt the same, every step recorded on that grid goes back on it as it was. Otherwise + // each settles again from rest on the new one. + const recorded = current.undo.map((step) => step.surface?.grid === restore.token); + const steps = moveSteps(current.undo, restore.token, model.grid, model).map((step, i) => + same || !recorded[i] + ? step + : { + ...step, + points: step.points.flatMap((point) => { + const handle = rebindHandle(model, point); + return handle ? [{ ...handle, baseline: rest }] : []; + }), + gapTargets: [], + surface: rest, + }, + ); + const { grid: _, ...edit } = steps.at(-1)!; + void _; + const next: WarpSession = { + ...current, + stage: 'warp', + region: restore.region, + faces: restore.faces, + seed: restore.seed, + density, + densityChosen: restore.densityChosen, + feather, + laid, + model, + state: createWarpState(model.restNodes), + surface: null, + output, + preview: warpPreview(current.source, output), + folds: new Uint32Array(0), + seam: null, + settling: false, + undo: steps.slice(0, -1), + }; + useEditor.setState({ paintHistory: [], warp: restoreWarp(scene, next, edit) }); + completeTask(taskId, `${model.grid.nodes.length.toLocaleString()} grid nodes`); + if (!same) + notify('The earlier grid came out different, so its surface was solved again.', 'info'); + return; + } + + // A density change keeps every handle, and a new region every moved handle it still paints. + const dropped = current.points.map((point) => droppedBy(model, point)); + const refused = + kind === 'density' + ? dropped.some((reason) => reason) + : dropped.some((reason, i) => reason === 'fixed' && current.points[i].target !== null); + if (refused) { + cancelTask(taskId, 'Grid not changed.'); + useEditor.setState({ warp: { ...current, ...from } }); + if (current.settling) scheduleWarpSettle(); + notify( + kind === 'density' + ? 'That grid is too coarse for the points on this region, so the density stays as it was.' + : 'Points you moved would be held by the edge of the new region, so the grid was not laid. Paint farther around them, or delete them first.', + 'info', + ); + return; + } + // Each settled grid the session keeps is carried to the new grid once, so every version of a // handle and every undo step goes on sharing it. - const old = current.model; const carried = new Map(); const carry = (snapshot: WarpSnapshot) => { let next = carried.get(snapshot); @@ -3670,6 +3949,44 @@ async function layWarp(from: WarpSettled, fromRegion = false) { const points = rebind(current.points); const kept = new Set(points.map((point) => point.id)); const start = current.surface ? carry(current.surface) : null; + // A density change is a step of its own. The steps before it stay on the grid they were + // recorded on, which undoing it rebuilds. + let undo: WarpEdit[]; + if (kind === 'density' && old && current.laid) { + const token = detachedGrid(); + const [step, ...earlier] = moveSteps( + [warpEdit(current), ...current.undo.slice(-(warpUndoLimit - 1))], + old.grid, + token, + ); + undo = [ + ...earlier, + { + ...step, + grid: { + laid: current.laid, + region: current.region, + faces: current.faces, + seed: current.seed, + densityChosen: from.densityChosen, + token, + fingerprint: warpFingerprint(old), + }, + }, + ]; + } else + // Steps must bind to the same grid as the session; gap targets name old nodes. + undo = current.undo.map(({ grid, ...step }) => { + void grid; + return { + ...step, + points: rebind(step.points), + gapTargets: [], + surface: step.surface && carry(step.surface), + }; + }); + // The idle steps would otherwise go on holding the session on the old grid. + forgetWarpSettle(); const output = createWarpOutput(model); disposeWarpPreview(current.preview); let next: WarpSession = { @@ -3691,13 +4008,7 @@ async function layWarp(from: WarpSettled, fromRegion = false) { folds: new Uint32Array(0), seam: null, settling: false, - // Steps must bind to the same grid as the session; gap targets name old nodes. - undo: current.undo.map((step) => ({ - ...step, - points: rebind(step.points), - gapTargets: [], - surface: step.surface && carry(step.surface), - })), + undo, }; // A grid nothing holds rests, and its preview keeps the source's bits. const resting = !next.points.some(holdsWarp); @@ -3708,18 +4019,21 @@ async function layWarp(from: WarpSettled, fromRegion = false) { // Without a fixed border, unmoved points are what stop a drag moving the whole part. if (current.firstLay && current.autoPoints && !faces) next = { ...next, points: [...points, ...distributedPoints(next, current.distributeCount)] }; - const { scene } = useEditor.getState(); useEditor.setState({ // Stroke undo stays available until a grid replaces the region it painted. paintHistory: [], warp: resting ? { ...next, seam: warpSeam(scene, next) } : solveWarpSession(scene, next, 'end'), }); completeTask(taskId, `${model.grid.nodes.length.toLocaleString()} grid nodes`); - const { notify } = useEditor.getState(); if (current.gapTargets.length) notify('Close gap again to close the seam at this density.', 'info'); - if (points.length < current.points.length) + if (dropped.includes('unpainted')) notify('Some control points were outside the new region and were removed.', 'info'); + if (dropped.includes('fixed')) + notify( + 'Some unmoved control points were on the edge of the new region and were removed.', + 'info', + ); } // A warp is built from one geometry of one scene. Undo, another editor, opening a file @@ -3751,6 +4065,22 @@ useEditor.subscribe((state, previous) => { state.cancelWarp(edited ? 'Warp discarded. Use Apply to keep a warp.' : undefined); }); +// An Apply waiting for the surface to settle is dropped by any edit before it: another drag, +// undo, a new grid, or leaving the warp stage. +useEditor.subscribe((state, previous) => { + const { warp } = state, + before = previous.warp; + if ( + warp?.applying && + before && + (warp.points !== before.points || + warp.gapTargets !== before.gapTargets || + warp.model !== before.model || + warp.stage !== 'warp') + ) + useEditor.setState({ warp: { ...warp, applying: false } }); +}); + export function measureDistance() { const state = useEditor.getState(); if (state.measurement.length !== 2) return null; diff --git a/src/core/warp-evaluate.ts b/src/core/warp-evaluate.ts index 24e90a1..9d85f93 100644 --- a/src/core/warp-evaluate.ts +++ b/src/core/warp-evaluate.ts @@ -191,6 +191,32 @@ function skinVertex( return true; } +/** + * World positions of the listed welded vertices as `evaluateWarp` skins them for `state`, before + * any feather blend, three values each. A vertex the warp does not move gets NaN. + */ +export function skinnedWorldPositions( + model: WarpModel, + state: WarpState, + vertices: ArrayLike, +): Float64Array { + const { region } = model; + const rotation = new Float64Array(model.grid.nodes.length * 9), + skin = new Float64Array(model.grid.nodes.length * 9), + shift = new Float64Array(model.grid.nodes.length * 3); + writeNodeMaps(model, state, rotation, skin); + const skinned = skinOf(model); + writeShifts(skinned, state.positions, skin, shift); + const out = new Float64Array(vertices.length * 3).fill(NaN); + for (let i = 0; i < vertices.length; i++) { + const v = vertices[i]; + if (v >= region.weldedCount || region.role[v] !== WarpRole.Interior) continue; + if (!skinVertex(skinned, state.positions, skin, shift, v, out, i * 3)) + out.fill(NaN, i * 3, i * 3 + 3); + } + return out; +} + /** * Mesh-local positions of the listed welded vertices exactly as `evaluateWarp` writes them for * `state`, without writing a whole mesh. A vertex the warp does not move keeps the bits of diff --git a/src/core/warp-handles.ts b/src/core/warp-handles.ts index c3b51fa..1f1b847 100644 --- a/src/core/warp-handles.ts +++ b/src/core/warp-handles.ts @@ -2,10 +2,13 @@ import type { Vec3 } from './types'; import { bindTrianglePoint, warpBindingNodes, type WarpPointBinding } from './warp-bind'; import type { WarpGrid } from './warp-grid'; import { isPaintedNode, type WarpModel } from './warp-model'; -import { regionTriangleOf, WarpRole } from './warp-region'; -import { deformPoint } from './warp-evaluate'; +import { regionTriangleOf } from './warp-region'; +import { deformPoint, skinnedWorldPositions } from './warp-evaluate'; import { + modelledResponse, + responseShrink, warpNodeStiffness, + warpResponse, type WarpConstraint, type WarpGuides, type WarpState, @@ -170,6 +173,7 @@ export function handleConstraints( model?: WarpModel, guides?: WarpGuides, exact: Iterable = [], + carry?: ReadonlyMap, ): WarpConstraint[] { const riding = !!model && @@ -178,7 +182,8 @@ export function handleConstraints( const constraints: WarpConstraint[] = []; const owner: number[] = []; handles.forEach((handle, h) => { - const offset = handleOffset(handle); + const share = carry?.get(handle) ?? 1; + const offset = handleOffset(handle).map((value) => share * value) as Vec3; const rides = riding && untouchedAuto(handle); for (const sample of handle.samples) { const ride = rides ? rideOffset(model!, guides!, handle.baseline, sample.binding) : null; @@ -191,7 +196,7 @@ export function handleConstraints( ? ride ? [sample.pin[0] + ride[0], sample.pin[1] + ride[1], sample.pin[2] + ride[2]] : sample.pin - : samePosition(sample.pin, handle.pin) + : share === 1 && samePosition(sample.pin, handle.pin) ? handle.target : [sample.pin[0] + offset[0], sample.pin[1] + offset[1], sample.pin[2] + offset[2]], }); @@ -209,6 +214,20 @@ export function handleConstraints( }); const fixed = model?.grid.fixed; const edgeStart = model?.grid.edgeStart; + // The free nodes moved handles' samples are bound to, and those beside them: a pin the user + // placed there holds as firmly as the handle pulls. + const grabbed = new Set(); + if (model) + for (const handle of handles) { + if (handle.target === null) continue; + for (const { binding } of handle.samples) + for (const n of binding.node) { + if (fixed![n]) continue; + grabbed.add(n); + for (let e = edgeStart![n]; e < edgeStart![n + 1]; e++) + if (!fixed![model.grid.edges[e]]) grabbed.add(model.grid.edges[e]); + } + } constraints.forEach((constraint, c) => { const handle = handles[owner[c]]; if (untouchedAuto(handle)) return; @@ -218,13 +237,13 @@ export function handleConstraints( const own = reach?.grid === model?.grid ? reach?.node.subarray(0, reach.own) : undefined; // A moved point lands; a line or an area does by moving its footprint as one, and many stiff // samples on the same nodes would only slow the solve. Otherwise a sample outranks fully on - // shared nodes, and under guides by how firmly they hold its nodes, so the surface stays - // continuous as a radius reaches them. + // shared nodes, a pin also beside a moved handle's nodes, and under guides by how firmly they + // hold its nodes, so the surface stays continuous as a radius reaches them. let contest = handle.target !== null && handle.samples.length === 1 ? 1 : 0; for (let k = 0; k < node.length && contest < 1; k++) { const n = node[k]; if (fixed?.[n]) continue; - if (held.get(n) === -1) contest = 1; + if (held.get(n) === -1 || (handle.target === null && grabbed.has(n))) contest = 1; else if (guides && edgeStart && !own?.includes(n)) { const g = guideIndex(guides, n); if (g >= 0) @@ -643,6 +662,7 @@ export function warpGuides( model: WarpModel, handles: readonly WarpHandle[], exact: Iterable = [], + carry?: ReadonlyMap, ): WarpGuides | undefined { const { grid } = model; const guiding = handles.filter( @@ -682,7 +702,9 @@ export function warpGuides( weight[i] = reach.activation * w; profile[i] = reach.activation * ((1 - motion) * w + motion * held); } - return { handle, reach, weight, profile, motion, offset: handleOffset(handle) }; + const share = carry?.get(handle) ?? 1; + const offset = handleOffset(handle).map((value) => share * value) as Vec3; + return { handle, reach, weight, profile, motion, offset }; }); // The two largest driving weights at each node, and whose the largest is. const first = new Float64Array(count), @@ -735,6 +757,130 @@ export function warpGuides( return guides; } +/** + * How far any grid node may move, per mm a grab travels, when the grab is bound partly to fixed + * nodes or would move a pin the user placed: past this it stops short instead of overdriving the + * few free nodes it has. + */ +export const warpCarryLimit = 1.25; +/** + * How far apart the ends of a grid edge against the fixed edge, or against a pin that must hold, + * may move, as a share of its rest length, under a grab held back that way. Steeper, and the + * scan's relief folds. + */ +export const warpCreaseStrain = 1; +/** The least share of its determinant a node map beside such an edge or pin keeps under it. */ +export const warpMapFloor = 0.5; +/** How far a moved handle may move a stationary pin the user placed, mm. */ +export const warpPinHold = 0.005; + +/** Share of a binding's weight on free nodes. */ +const freeShare = (binding: WarpPointBinding, fixed: Uint8Array) => + binding.node.reduce((sum, n, k) => sum + (fixed[n] ? 0 : binding.weight[k]), 0); + +/** + * The share of its offset each moved handle can carry, for the handles that must stop short: those + * bound partly to fixed nodes, and those that would move a stationary pin the user placed. From + * the solve's linear response to the handle's travel with rotations held, a handle carries as far + * as keeps every node within `warpCarryLimit` of its travel, the pins within `warpPinHold`, the + * edges against the fixed nodes, and against those pins, within `warpCreaseStrain`, and the node + * maps beside them above `warpMapFloor`. `constraints` and `guides` are what the solve is given, + * the handles' constraints first in order. Handles on fully free surface with no pin they would + * move are never in the map. + */ +export function handleCarry( + model: WarpModel, + handles: readonly WarpHandle[], + constraints: WarpConstraint[], + guides: WarpGuides | undefined, + exact: Iterable = [], +): Map { + const carry = new Map(); + const { grid, restNodes } = model; + const { fixed, edgeStart, edges } = grid; + const first: number[] = []; + let count = 0; + for (const handle of handles) { + first.push(count); + count += handle.samples.length; + } + const pins = handles.flatMap((handle, h) => (handle.target === null && !handle.auto ? [h] : [])); + handles.forEach((handle, h) => { + if (handle.target === null) return; + const offset = handleOffset(handle); + const travel = Math.hypot(offset[0], offset[1], offset[2]); + if (!(travel > 0)) return; + const held = handle.samples.some(({ binding }) => freeShare(binding, fixed) < 1 - 1e-9); + // The pins its constraints fight directly: bound to its nodes or beside them. + const near = new Set(); + for (const { binding } of handle.samples) + for (const n of binding.node) { + near.add(n); + for (let e = edgeStart[n]; e < edgeStart[n + 1]; e++) near.add(edges[e]); + } + const close = pins.filter((p) => + handles[p].samples.some(({ binding }) => binding.node.some((n) => near.has(n))), + ); + if (!held && !close.length) return; + const share = new Float64Array(constraints.length); + for (let s = 0; s < handle.samples.length; s++) share[first[h] + s] = 1; + let guideShare: Float64Array | undefined; + if (guides && handleGuides(handle)) { + const without = warpGuides(model, handles, exact, new Map([[handle, 0]])); + if (without && without.node.length === guides.node.length) { + guideShare = new Float64Array(guides.node.length); + for (let g = 0; g < guideShare.length; g++) { + let along = 0; + for (let a = 0; a < 3; a++) + along += (guides.target[g * 3 + a] - without.target[g * 3 + a]) * offset[a]; + guideShare[g] = along / (travel * travel); + } + } + } + const response = warpResponse(grid, restNodes, constraints, guides, share, guideShare); + let pinned = 0; + for (const p of close) + for (let s = 0; s < handles[p].samples.length; s++) + pinned = Math.max( + pinned, + Math.abs(modelledResponse(grid, restNodes, constraints[first[p] + s], response)), + ); + const pulls = pinned * travel > warpPinHold; + if (!held && !pulls) return; + // What holds the surface still: the fixed nodes and, when they must hold, the pins' nodes. + const anchored = pulls ? fixed.slice() : fixed; + if (pulls) + for (const p of close) + for (const { binding } of handles[p].samples) for (const n of binding.node) anchored[n] = 1; + // How far nodes move, and how steeply the edges against what holds still rise, per mm. + let largest = 0, + strain = 0; + for (let n = 0; n < response.length; n++) { + largest = Math.max(largest, Math.abs(response[n])); + if (fixed[n]) continue; + for (let e = edgeStart[n]; e < edgeStart[n + 1]; e++) { + const j = edges[e]; + if (!anchored[j] || anchored[n]) continue; + const length = Math.hypot( + restNodes[n * 3] - restNodes[j * 3], + restNodes[n * 3 + 1] - restNodes[j * 3 + 1], + restNodes[n * 3 + 2] - restNodes[j * 3 + 2], + ); + if (length > 0) strain = Math.max(strain, Math.abs(response[n] - response[j]) / length); + } + } + let carried = largest > warpCarryLimit ? warpCarryLimit / largest : 1; + if (strain * travel > warpCreaseStrain) + carried = Math.min(carried, warpCreaseStrain / (strain * travel)); + const u: Vec3 = [offset[0] / travel, offset[1] / travel, offset[2] / travel]; + const shrink = responseShrink(grid, restNodes, response, u, anchored) * travel; + if (shrink > 1 - warpMapFloor) carried = Math.min(carried, (1 - warpMapFloor) / shrink); + if (pulls) carried = Math.min(carried, warpPinHold / (pinned * travel)); + if (carried < 1) carry.set(handle, carried); + }); + return carry; +} + /** Each node's weight from the handle's radius and falloff, for drawing its reach. */ export function reachWeights(handle: WarpHandle) { const reach = handle.reach!; @@ -762,8 +908,8 @@ export const snapshotOf = ( }); /** - * A snapshot carried from one grid to another: each node of `to` sits where `from`'s binding of - * its scan vertex puts it under the snapshot, turned by the blend of its bound nodes' rotations. + * A snapshot carried from one grid to another: each node of `to` sits where the preview writes its + * scan vertex under the snapshot on `from`, turned by the blend of its bound nodes' rotations. * Vertices `from` did not move stay at rest. A vertex `from` feathered and `to` paints sits where * it was written. */ @@ -773,23 +919,23 @@ export function transferSnapshot( to: WarpModel, ): WarpSnapshot { const K = warpBindingNodes; - const { binding, region, restNodes, restWorld } = from; - const { positions: P, rotations: Q } = snapshot; + const { binding, restWorld } = from; + const { rotations: Q } = snapshot; const count = to.grid.nodes.length; const positions = to.restNodes.slice(), rotations = new Float64Array(count * 4); - const r = new Float64Array(9); + const skinned = skinnedWorldPositions(from, snapshot, to.grid.nodes); for (let n = 0; n < count; n++) { rotations[n * 4 + 3] = 1; const v = to.grid.nodes[n]; - if (v >= region.weldedCount || region.role[v] !== WarpRole.Interior) continue; + const px = skinned[n * 3], + py = skinned[n * 3 + 1], + pz = skinned[n * 3 + 2]; + if (Number.isNaN(px)) continue; const x = restWorld[v * 3], y = restWorld[v * 3 + 1], z = restWorld[v * 3 + 2]; - let px = 0, - py = 0, - pz = 0, - qx = 0, + let qx = 0, qy = 0, qz = 0, qw = 0, @@ -802,13 +948,6 @@ export function transferSnapshot( b = Q[j * 4 + 1], c = Q[j * 4 + 2], d = Q[j * 4 + 3]; - rotationOf(r, a, b, c, d); - const ox = x - restNodes[j * 3], - oy = y - restNodes[j * 3 + 1], - oz = z - restNodes[j * 3 + 2]; - px += w * (r[0] * ox + r[1] * oy + r[2] * oz + P[j * 3]); - py += w * (r[3] * ox + r[4] * oy + r[5] * oz + P[j * 3 + 1]); - pz += w * (r[6] * ox + r[7] * oy + r[8] * oz + P[j * 3 + 2]); // Quaternions q and −q turn alike, so each joins the blend on the side of the first. const sign = total > 0 && a * qx + b * qy + c * qz + d * qw < 0 ? -w : w; qx += sign * a; @@ -821,9 +960,9 @@ export function transferSnapshot( // A vertex in the old feather band that the new region paints takes the position it was // written at. Where a feather still applies the blend comes later, so it stays unblended. const b = from.blend && isPaintedNode(to, n) ? from.blend[v] : 1; - positions[n * 3] = b === 1 ? px / total : x + b * (px / total - x); - positions[n * 3 + 1] = b === 1 ? py / total : y + b * (py / total - y); - positions[n * 3 + 2] = b === 1 ? pz / total : z + b * (pz / total - z); + positions[n * 3] = b === 1 ? px : x + b * (px - x); + positions[n * 3 + 1] = b === 1 ? py : y + b * (py - y); + positions[n * 3 + 2] = b === 1 ? pz : z + b * (pz - z); if (b < 1) { // Turned as far as it was written: part way from no turn. const side = qw < 0 ? -b : b; @@ -841,18 +980,6 @@ export function transferSnapshot( return { grid: to.grid, positions, rotations, settled: false, converged: false }; } -function rotationOf(out: Float64Array, x: number, y: number, z: number, w: number) { - out[0] = 1 - 2 * (y * y + z * z); - out[1] = 2 * (x * y - z * w); - out[2] = 2 * (x * z + y * w); - out[3] = 2 * (x * y + z * w); - out[4] = 1 - 2 * (x * x + z * z); - out[5] = 2 * (y * z - x * w); - out[6] = 2 * (x * z - y * w); - out[7] = 2 * (y * z + x * w); - out[8] = 1 - 2 * (x * x + y * y); -} - const cornerTriangles = new WeakMap(); /** A region triangle using each welded vertex, as triangle × 3 + corner, or -1. */ diff --git a/src/core/warp-solve.ts b/src/core/warp-solve.ts index c3237ff..7394bfb 100644 --- a/src/core/warp-solve.ts +++ b/src/core/warp-solve.ts @@ -887,6 +887,126 @@ function fitRotations( } } +const responses = new WeakMap< + WarpSystem, + { share: Float64Array; guideShare: Float64Array; response: Float64Array } +>(); + +/** + * How far each node moves, per mm, when the targets move together along one direction with + * rotations held: constraint `c` by `share[c]` of that and guide entry `g` by `guideShare[g]`. + * The system is the one `solveWarp` builds for these constraints and guides, so it is reused. + * Fixed nodes get 0. + */ +export function warpResponse( + grid: WarpGrid, + restNodes: Float64Array, + constraints: WarpConstraint[], + guides: WarpGuides | undefined, + share: ArrayLike, + guideShare: ArrayLike = [], +): Float64Array { + const { key } = constraintTerms(constraints, grid, restNodes); + const guiding = guideKey(guides); + let system = systems.get(grid); + if (!system || !sameKey(system.key, key) || !sameKey(system.guideKey, guiding)) + systems.set(grid, (system = buildSystem(grid, restNodes, key, guiding))); + const cached = responses.get(system); + if ( + cached && + sameKey(cached.share, Array.from(share)) && + sameKey(cached.guideShare, Array.from(guideShare)) + ) + return cached.response; + const { row, rhs, x } = system; + rhs.fill(0); + x.fill(0); + for (let i = 0; i < key.length;) { + const length = key[i + 1], + strength = key[i + 2]; + const nodes = i + 3, + weights = nodes + length; + const s = share[key[i]]; + if (s) + for (let k = 0; k < length; k++) { + const r = row[key[nodes + k]]; + if (r >= 0) rhs[r * 3] += strength * key[weights + k] * s; + } + i = weights + length; + } + if (guides) + for (let g = 0; g < guideShare.length; g++) { + const r = row[guides.node[g]]; + if (r >= 0) rhs[r * 3] += guides.stiffness[g] * guideShare[g]; + } + conjugateGradient(system); + const response = new Float64Array(grid.fixed.length); + for (let k = 0; k < system.freeNodes.length; k++) response[system.freeNodes[k]] = x[k * 3]; + responses.set(system, { + share: Float64Array.from(share), + guideShare: Float64Array.from(guideShare), + response, + }); + return response; +} + +/** + * For a node response from `warpResponse` along unit direction `u`, the most the skin map of a free + * node beside an `anchored` one loses of its determinant per mm, to first order with rotations + * held: the map gains u (Σ_e (r_n − r_j) B e)ᵀ, which turns it inside out once that loss reaches 1. + */ +export function responseShrink( + grid: WarpGrid, + restNodes: Float64Array, + response: ArrayLike, + u: Vec3, + anchored: ArrayLike, +) { + const frame = stretchFrame(grid, restNodes); + const { edgeStart, edges } = grid; + const { inverse: b, edge } = frame; + let worst = 0; + for (let n = 0; n < grid.fixed.length; n++) { + if (!stretches(grid, frame, n)) continue; + let beside = false; + for (let e = edgeStart[n]; e < edgeStart[n + 1]; e++) beside ||= !!anchored[edges[e]]; + if (!beside) continue; + let gx = 0, + gy = 0, + gz = 0; + for (let e = edgeStart[n]; e < edgeStart[n + 1]; e++) { + const d = response[n] - response[edges[e]]; + gx += d * edge[e * 3]; + gy += d * edge[e * 3 + 1]; + gz += d * edge[e * 3 + 2]; + } + const i = n * 9; + const shrink = -( + u[0] * (b[i] * gx + b[i + 1] * gy + b[i + 2] * gz) + + u[1] * (b[i + 3] * gx + b[i + 4] * gy + b[i + 5] * gz) + + u[2] * (b[i + 6] * gx + b[i + 7] * gy + b[i + 8] * gz) + ); + if (shrink > worst) worst = shrink; + } + return worst; +} + +/** How far a constraint's modelled point moves for a node response from `warpResponse`, per mm. */ +export function modelledResponse( + grid: WarpGrid, + restNodes: Float64Array, + constraint: WarpConstraint, + response: ArrayLike, +) { + const { node, weight } = constraint; + let sum = 0; + for (let k = 0; k < node.length; k++) sum += weight[k]; + const term = termOf(constraint, grid, restNodes, sum); + let moved = 0; + term.node.forEach((n, k) => (moved += term.coefficient[k] * response[n])); + return moved; +} + /** * Warm-starts from and updates `state`. Returns the largest node move in the last iteration, mm. * Several guides on one node add. diff --git a/src/styles.css b/src/styles.css index 3cc866b..ee0a9d5 100644 --- a/src/styles.css +++ b/src/styles.css @@ -6580,6 +6580,9 @@ optgroup { font-size: 11px; color: var(--muted); } +.warp-settling { + margin: 12px 16px 0; +} .warp-gap-row { display: flex; align-items: center; diff --git a/tests/e2e/warp.spec.ts b/tests/e2e/warp.spec.ts index e2b9de3..cb5f419 100644 --- a/tests/e2e/warp.spec.ts +++ b/tests/e2e/warp.spec.ts @@ -445,6 +445,78 @@ test('a whole part gets pins of its own, so a moved point bends it, shaped by ra expect((await editorState(page)).points).toHaveLength(17); }); +test('says the surface is still settling, and Apply waits for it to settle', async ({ page }) => { + await open(page, { + ...fixture, + parts: fixture.parts.map((part) => + part.id === 'block' + ? { ...part, geometry: serializeGeometry(new BoxGeometry(20, 20, 20, 52, 52, 52)) } + : part, + ), + }); + await page.keyboard.press('w'); + await page.getByRole('radio', { name: 'Whole part', exact: true }).click(); + await page.getByRole('button', { name: 'Lay grid', exact: true }).click(); + await expect(page.getByRole('button', { name: 'Close gap', exact: true })).toBeEnabled(); + // The finest grid settles longest. + await page.getByRole('slider', { name: 'Grid density', exact: true }).fill('6'); + await expect(page.getByRole('button', { name: 'Close gap', exact: true })).toBeEnabled(); + const front = await screen(page, [-4.5, 10.5, 10]); + await page.mouse.click(front.x, front.y); + const radius = page.getByRole('spinbutton', { name: 'Point radius', exact: true }); + await radius.fill('0'); + await radius.press('Tab'); + // Records the surface shown when Apply is pressed, and when it stops settling. + await page.evaluate(async () => { + const url = performance + .getEntriesByType('resource') + .map((entry) => entry.name) + .find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))!; + const { useEditor } = await import(url); + const w = window as unknown as { pressed: number[] | null; settled: number[] | null }; + const shown = () => + Array.from(useEditor.getState().warp.preview.getAttribute('position').array) as number[]; + w.pressed = w.settled = null; + document.addEventListener( + 'click', + (event) => { + if ((event.target as Element).closest('.warp-actions .button.primary')) w.pressed = shown(); + }, + true, + ); + useEditor.subscribe((state: any, previous: any) => { + if (previous.warp?.settling && state.warp && !state.warp.settling) w.settled = shown(); + }); + }); + const settling = page.locator('.warp-settling'); + const apply = page.getByRole('button', { name: 'Apply', exact: true }); + await expect(settling).toHaveCount(0); + // A real drag on the gizmo's X arrow, released. + const handle = await moveHandle(page); + await page.mouse.move(handle.x, handle.y); + await page.mouse.down(); + await page.mouse.move(handle.x + 240, handle.y, { steps: 8 }); + await page.mouse.up(); + await expect(settling).toContainText('The surface is still settling. Apply waits for it.'); + await apply.click(); + const applying = page.getByRole('button', { name: 'Applying…', exact: true }); + await expect(applying).toBeDisabled(); + await expect(applying).toHaveAttribute('aria-busy', 'true'); + await expect(settling).toContainText('Applying once the surface settles…'); + // Input still reaches the page while it settles. + await page.mouse.move(front.x + 40, front.y + 40); + await expect.poll(async () => (await editorState(page)).source).toBe('Warp · test'); + const applied = await editorState(page); + const { pressed, settled } = await page.evaluate(() => { + const w = window as unknown as { pressed: number[]; settled: number[] }; + return { pressed: w.pressed, settled: w.settled }; + }); + expect(applied.stage).toBe('region'); + // It baked the settled surface, which had gone on moving after the button was pressed. + expect(applied.mesh).toEqual(settled); + expect(differs(settled, pressed)).toBe(true); +}); + test.describe('with clipping on, as by default', () => { test.use({ storageState: { cookies: [], origins: [] } }); diff --git a/tests/unit/warp-feather-session.test.ts b/tests/unit/warp-feather-session.test.ts index 72afb1f..f3e504b 100644 --- a/tests/unit/warp-feather-session.test.ts +++ b/tests/unit/warp-feather-session.test.ts @@ -256,4 +256,49 @@ describe('a feathered region painted wider', () => { // As close as the carried grid holds painted vertices, rather than the unblended solve. expect(worst).toBeLessThan(0.03); }); + + it('gives every newly painted node the baseline that was written there', async () => { + editor().setWarpFeather({ enabled: true, width: 7 }); + const part = plate(); + await layOn(part, disc(part.geometry, 8)); + const old = session().model!; + editor().setWarpPointSettings({ radius: 20 }, 'end'); + editor().addWarpPoint(hit(0.3, 0.2), faceAt(part.geometry, 0.3, 0.2)); + editor().moveWarpPoints([{ id: session().points[0].id, target: [0.3, 0.2, 2.5] }], 'end'); + finishWarpSettling(); + editor().selectWarpPoints([]); + editor().setWarpPointSettings({ radius: 6 }, 'end'); + editor().addWarpPoint(hit(3.1, 1.2), faceAt(part.geometry, 3.1, 1.2)); + const written = Float64Array.from(session().output!.positions); + + editor().setWarpRegion('painted'); + useEditor.setState({ warp: { ...session(), faces: disc(part.geometry, 14) } }); + await editor().layWarpGrid(); + const model = session().model!; + const { baseline } = session().points[1]; + const first = new Int32Array(old.region.weldedCount).fill(-1); + old.region.weldOf.forEach((v, g) => { + if (v !== 0xffffffff && first[v] < 0) first[v] = g; + }); + let painted = 0, + nearlyPainted = 0, + worst = 0; + for (let n = 0; n < model.grid.nodes.length; n++) { + const v = model.grid.nodes[n]; + if (!isPaintedNode(model, n) || old.blend![v] === 1 || first[v] < 0) continue; + painted++; + if (old.blend![v] >= 0.9) nearlyPainted++; + // The plate sits at the origin, so its local positions are world positions. + worst = Math.max( + worst, + Math.hypot( + ...[0, 1, 2].map((a) => baseline.positions[n * 3 + a] - written[first[v] * 3 + a]), + ), + ); + } + expect(painted).toBeGreaterThan(40); + expect(nearlyPainted).toBeGreaterThan(0); + // Single-precision rounding of the written mesh. + expect(worst).toBeLessThan(1e-5); + }); }); diff --git a/tests/unit/warp-held-grab.test.ts b/tests/unit/warp-held-grab.test.ts new file mode 100644 index 0000000..7c2b0e8 --- /dev/null +++ b/tests/unit/warp-held-grab.test.ts @@ -0,0 +1,286 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { BufferAttribute, BufferGeometry, PlaneGeometry, Triangle, Vector3 } from 'three'; +import { triangleCount } from '../../src/core/geometry'; +import { + finishWarpSettling, + useEditor, + warpPinDrift, + warpShortfall, + warpShortfallShown, + type WarpPoint, +} from '../../src/core/store'; +import { readFace } from '../../src/core/surfaces'; +import type { Part, SurfacePoint, Vec3 } from '../../src/core/types'; +import { deformPoint } from '../../src/core/warp-evaluate'; +import { defaultWarpDensity } from '../../src/core/warp-grid'; +import { WarpRole } from '../../src/core/warp-region'; +import { skinMapOf } from '../../src/core/warp-solve'; + +const editor = () => useEditor.getState(); +const session = () => useEditor.getState().warp!; +const current = (id: string) => session().points.find((point) => point.id === id)!; +const distance = (a: ArrayLike, b: ArrayLike) => + Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]); +const deformed = (point: WarpPoint) => + deformPoint( + session().model!, + session().state!, + point.samples[0].binding, + point.samples[0].restWorld, + ); + +const initial = useEditor.getState(); +afterEach(() => { + editor().cancelWarp(); + useEditor.setState(initial); +}); + +function part(geometry: BufferGeometry): Part { + const count = geometry.getAttribute('position').count; + geometry.setAttribute('color', new BufferAttribute(new Float32Array(count * 3).fill(0.5), 3)); + return { + id: 'p', + name: 'p', + geometry, + position: [0, 0, 0], + quaternion: [0, 0, 0, 1], + scale: [1, 1, 1], + color: '#aabbcc', + visible: true, + locked: false, + source: 'test', + }; +} + +/** A 16 mm sheet of 0.1 mm triangles with relief a few tenths of a millimetre deep, like a scan. */ +function relief() { + const geometry = new PlaneGeometry(16, 16, 160, 160); + geometry.deleteAttribute('uv'); + const position = geometry.getAttribute('position'); + for (let i = 0; i < position.count; i++) { + const x = position.getX(i), + y = position.getY(i); + position.setZ( + i, + 0.075 * Math.sin(2.1 * x + 0.4) * Math.cos(1.7 * y) + + 0.036 * Math.sin(5.3 * x - 3.1 * y) + + 0.015 * Math.cos(11 * y + 7 * x), + ); + } + geometry.computeVertexNormals(); + return geometry; +} + +const hitOn = (geometry: BufferGeometry, face: number): SurfacePoint => { + const triangle = readFace(geometry, face); + return { + partId: 'p', + point: triangle.getMidpoint(new Vector3()).toArray(), + normal: triangle.getNormal(new Vector3()).toArray(), + }; +}; + +/** Starts Warp on the sheet with a 1.5 mm brush disc painted at its middle, feather off. */ +async function paintedDisc(geometry: BufferGeometry, density?: number) { + editor().setScene({ name: 'Held', parts: [part(geometry)], joints: [] }); + useEditor.setState({ selected: ['p'] }); + editor().setTool('warp'); + editor().setWarpBrushRadius(1.5); + let middle = 0; + for (let face = 1, best = Infinity; face < triangleCount(geometry); face++) { + const centre = readFace(geometry, face).getMidpoint(new Vector3()); + const from = Math.hypot(centre.x, centre.y); + if (from < best) [best, middle] = [from, face]; + } + editor().paintWarpRegion(hitOn(geometry, middle), middle, false, true); + editor().endPaintStroke(); + if (density !== undefined) await editor().setWarpDensity(density); + await editor().layWarpGrid(); + return middle; +} + +/** Share of a point's binding weight on free nodes. */ +const freeShare = (point: WarpPoint) => { + const { binding } = point.samples[0]; + const { fixed } = session().model!.grid; + return binding.node.reduce((sum, n, k) => sum + (fixed[n] ? 0 : binding.weight[k]), 0); +}; + +/** The painted face with one corner on the fixed edge whose centre is bound least to free nodes. */ +function edgeFace(geometry: BufferGeometry) { + const { region } = session().model!; + let face = -1, + least = Infinity; + for (let t = 0; t < region.faces.length; t++) { + const border = [0, 1, 2].filter( + (c) => region.role[region.triangles[t * 3 + c]] === WarpRole.Border, + ).length; + if (border !== 1) continue; + editor().addWarpPoint(hitOn(geometry, region.faces[t]), region.faces[t]); + const point = session().points.at(-1); + if (point && freeShare(point) < least) [least, face] = [freeShare(point), region.faces[t]]; + if (point) editor().undoWarpEdit(); + } + return { face, free: least }; +} + +/** Pulls a new point on `face` 1 mm along the face's normal and settles. */ +function pull(geometry: BufferGeometry, face: number, radius: number | null) { + useEditor.setState({ warp: { ...session(), pointRadius: radius } }); + editor().addWarpPoint(hitOn(geometry, face), face); + const point = session().points.at(-1)!; + const before = session().state!.positions.slice(); + const triangle = readFace(geometry, face); + const target = triangle + .getMidpoint(new Vector3()) + .addScaledVector(triangle.getNormal(new Vector3()), 1) + .toArray() as Vec3; + editor().moveWarpPoints([{ id: point.id, target }], 'end'); + finishWarpSettling(); + editor().selectWarpPoints([point.id]); + const { model, state } = session(); + let excursion = 0; + for (let n = 0; n < before.length / 3; n++) + excursion = Math.max( + excursion, + distance(state!.positions.subarray(n * 3), before.subarray(n * 3)), + ); + let inverted = 0; + const map = new Float64Array(9); + for (let n = 0; n < model!.grid.nodes.length; n++) { + skinMapOf(model!.grid, model!.restNodes, state!, n, map); + const det = + map[0] * (map[4] * map[8] - map[5] * map[7]) - + map[1] * (map[3] * map[8] - map[5] * map[6]) + + map[2] * (map[3] * map[7] - map[4] * map[6]); + if (det <= 0) inverted++; + } + return { point: current(point.id), target, excursion, inverted, folds: session().folds.length }; +} + +describe('a grab bound partly to the fixed edge', () => { + it('stops short and says so rather than throwing a spike', async () => { + const geometry = relief(); + await paintedDisc(geometry); + const { face, free } = edgeFace(geometry); + // Most of its weight is on fixed nodes, as at the reviewer's painted edge. + expect(free).toBeLessThan(0.5); + for (const radius of [null, 0]) { + const { point, target, excursion, inverted, folds } = pull(geometry, face, radius); + if (radius === null) expect(point.radius).toBeGreaterThan(0.5); + // No node moves much farther than the grab was asked to, nothing turns inside out. + expect(excursion).toBeLessThan(1.3); + expect(inverted).toBe(0); + expect(folds).toBe(0); + // The point stops short and the panel says how far. + const short = distance(deformed(point), target); + expect(short).toBeGreaterThan(warpShortfallShown); + expect(warpShortfall(session())).toBeCloseTo(short, 9); + editor().undoWarpEdit(); + editor().undoWarpEdit(); + } + }, 30_000); + + it('leaves a grab on free surface landing where it did', async () => { + for (const density of [0, defaultWarpDensity]) { + const geometry = relief(); + const middle = await paintedDisc(geometry, density); + const { point, target } = pull(geometry, middle, null); + expect(freeShare(point)).toBe(1); + const tolerance = density === 0 ? 0.03 : 0.01; + expect(distance(deformed(point), target)).toBeLessThan(tolerance); + expect(warpShortfall(session())).toBeLessThan(warpShortfallShown); + editor().cancelWarp(); + } + }); +}); + +function plate() { + return part(new PlaneGeometry(40, 40, 64, 64)); +} + +function faceAt(geometry: BufferGeometry, x: number, y: number) { + const triangle = new Triangle(), + point = new Vector3(x, y, 0), + closest = new Vector3(); + for (let face = 0; face < triangleCount(geometry); face++) { + readFace(geometry, face, triangle); + if (triangle.closestPointToPoint(point, closest).distanceTo(point) < 1e-6) return face; + } + throw new Error('No face under the point.'); +} + +function addAt(geometry: BufferGeometry, x: number, y: number) { + editor().addWarpPoint( + { partId: 'p', point: [x, y, 0], normal: [0, 0, 1] }, + faceAt(geometry, x, y), + ); + return session().points.at(-1)!; +} + +describe('a pin the user placed', () => { + it('holds against a point moved beside it, which stops short instead', async () => { + for (const whole of [false, true]) + for (const radius of [null, 0]) + for (const gap of [0, 0.03, 0.25]) { + const p = plate(); + editor().setScene({ name: 'Pins', parts: [p], joints: [] }); + useEditor.setState({ selected: ['p'] }); + editor().setTool('warp'); + if (!whole) { + editor().setWarpBrushRadius(12); + editor().paintWarpRegion( + { partId: 'p', point: [0, 0, 0], normal: [0, 0, 1] }, + faceAt(p.geometry, 0, 0), + false, + true, + ); + editor().endPaintStroke(); + } + await editor().layWarpGrid(); + if (radius !== null) editor().setWarpPointSettings({ radius }, 'end'); + const pin = addAt(p.geometry, 0.5, 0.3); + const moved = addAt(p.geometry, 0.5 + gap, 0.3); + const target: Vec3 = [0.5 + gap, 0.3, 2]; + editor().moveWarpPoints([{ id: moved.id, target }], 'end'); + finishWarpSettling(); + const label = `${whole ? 'whole' : 'painted'}, radius ${radius}, ${gap} mm apart`; + // The pin stays where it was put. + expect(distance(deformed(current(pin.id)), pin.pin), label).toBeLessThan(0.01); + editor().selectWarpPoints([pin.id]); + expect(warpPinDrift(session()), label).toBeLessThan(warpShortfallShown); + // The moved point is the one that stops short, and says so. + editor().selectWarpPoints([moved.id]); + const short = distance(deformed(current(moved.id)), target); + expect(warpShortfall(session()), label).toBeCloseTo(short, 9); + if (gap < 0.1) expect(short, label).toBeGreaterThan(warpShortfallShown); + editor().cancelWarp(); + } + }, 60_000); + + it('reports how far the surface has moved from it', async () => { + const p = plate(); + editor().setScene({ name: 'Pins', parts: [p], joints: [] }); + useEditor.setState({ selected: ['p'] }); + editor().setTool('warp'); + await editor().layWarpGrid(); + const pin = addAt(p.geometry, 0.5, 0.3); + editor().selectWarpPoints([pin.id]); + expect(warpPinDrift(session())).toBeLessThan(1e-9); + // Held 0.1 mm above where the surface is written. + const lifted: Vec3 = [pin.pin[0], pin.pin[1], pin.pin[2] + 0.1]; + useEditor.setState({ + warp: { + ...session(), + points: session().points.map((point) => + point.id === pin.id ? { ...point, pin: lifted } : point, + ), + }, + }); + expect(warpPinDrift(session())).toBeCloseTo(0.1, 6); + // An automatic point rides, so it reports nothing. + const auto = session().points.find((point) => point.auto)!; + editor().selectWarpPoints([auto.id]); + expect(warpPinDrift(session())).toBe(0); + }); +}); diff --git a/tests/unit/warp-session.test.ts b/tests/unit/warp-session.test.ts index 0048f95..bdd0122 100644 --- a/tests/unit/warp-session.test.ts +++ b/tests/unit/warp-session.test.ts @@ -2281,7 +2281,7 @@ describe('warp handles', () => { expect(warpTasks()).toHaveLength(tasks); }); - it('undo after a density change comes back close to each step', async () => { + it('a density change is one undo step, and undo restores it and each step before exactly', async () => { const a = plate('a', 0, 64); setup([a], ['a']); await warpDisc(a, 0, 0, 14); @@ -2291,31 +2291,119 @@ describe('warp handles', () => { const q = addAt(a, 2.5, 0.5); move(q.id, [2.5, 0.5, -1]); const surfaces: number[][] = []; - surfaces.push(positionsOf(session().preview!)); + const record = () => { + finishWarpSettling(); + surfaces.push(positionsOf(session().preview!)); + }; + record(); editor().selectWarpPoints([p.id]); editor().setWarpPointSettings({ radius: 8 }, 'end'); - surfaces.push(positionsOf(session().preview!)); + record(); editor().setWarpPointSettings({ falloff: 0.6 }, 'end'); - surfaces.push(positionsOf(session().preview!)); + record(); // Through the overlap. move(p.id, [0, 0, 2.5]); - const last = positionsOf(session().preview!); - const worst = (a: number[], b: number[]) => - Math.max(...a.map((value, i) => Math.abs(value - b[i]))); + record(); + const { model, undo, points, gapTargets } = session(); + const steps = undo.length; + const normals = Array.from(session().preview!.getAttribute('normal').array); await editor().setWarpDensity(4); - const errors = [worst(positionsOf(session().preview!), last)]; - for (let step = surfaces.length - 1; step >= 0; step--) { - editor().undoWarpEdit(); - errors.push(worst(positionsOf(session().preview!), surfaces[step])); + expect(session().model).not.toBe(model); + expect(session().undo).toHaveLength(steps + 1); + // The steps recorded on the old grid no longer hold it, and the step undoing to it names it. + const grid = session().undo.at(-1)!.grid!; + expect(grid.laid.density).toBe(defaultWarpDensity); + for (const step of session().undo) { + expect(step.surface!.grid).not.toBe(model!.grid); + for (const point of step.points) expect(point.baseline.grid).not.toBe(model!.grid); + } + + await editor().undoWarpEdit(); + expect(session()).toMatchObject({ stage: 'warp', density: defaultWarpDensity }); + expect(session().model).not.toBe(model); + expect(session().model!.grid.nodes).toEqual(model!.grid.nodes); + expect(session().undo).toHaveLength(steps); + expect( + session().points.map(({ id, target, radius, falloff }) => [id, target, radius, falloff]), + ).toEqual(points.map(({ id, target, radius, falloff }) => [id, target, radius, falloff])); + expect(session().gapTargets).toEqual(gapTargets); + // Bit for bit as it was written before the change. + expect(positionsOf(session().preview!)).toEqual(surfaces.at(-1)); + expect(Array.from(session().preview!.getAttribute('normal').array)).toEqual(normals); + for (let step = surfaces.length - 2; step >= 0; step--) { + await editor().undoWarpEdit(); + expect(positionsOf(session().preview!)).toEqual(surfaces[step]); } - // Each step comes back as closely as the new grid holds the current surface itself. - for (const error of errors) expect(error).toBeLessThan(errors[0] * 1.05 + 0.02); - // Largest beside the downward point, whose dip around it is a node spacing wide. The evenly - // spaced grids at the two densities place that dip differently: 0.56 to 1.69 mm as the point - // shifts by up to 0.6 mm, where the simplifier's grids, on this plate's rows at both densities, - // gave 0.50 to 0.89. - expect(errors[0]).toBeLessThan(1.4); + }); + + it('a density change that would drop a handle is not made, and says why', async () => { + for (const feather of [false, true]) + for (const [x, y] of [ + [0.97, 0.02], + [-0.61, 0.41], + [0.56, -0.97], + ]) { + // A sheet as fine as a scan: on the coarsest grid a 1.5 mm disc's painted edge is all + // that is left, so these spots are bound only to fixed nodes there. + const a = { ...plate('a'), geometry: new PlaneGeometry(16, 16, 320, 320) }; + setup([a], ['a']); + useEditor.setState({ warpFeather: { enabled: feather, width: feather ? 0.5 : null } }); + await warpDisc(a, 0, 0, 1.5); + const p = addAt(a, x, y); + move(p.id, [x, y, 0.3]); + finishWarpSettling(); + const before = session(); + const surface = positionsOf(before.preview!); + useEditor.setState({ toast: null }); + await editor().setWarpDensity(0); + const label = `feather ${feather}, ${x}, ${y}`; + expect(session().model, label).toBe(before.model); + expect(session().points, label).toBe(before.points); + expect(session().undo, label).toBe(before.undo); + expect(session(), label).toMatchObject({ + stage: 'warp', + density: defaultWarpDensity, + densityChosen: false, + }); + expect(positionsOf(session().preview!), label).toEqual(surface); + expect(toast(), label).toBe( + 'That grid is too coarse for the points on this region, so the density stays as it was.', + ); + editor().cancelWarp(); + } + useEditor.setState({ warpFeather: { enabled: false, width: null } }); + }, 60_000); + + it('a new region that would leave a moved point on its fixed edge is not laid', async () => { + const a = plate('a', 0, 64); + setup([a], ['a']); + await warpDisc(a, 0, 0, 12); + editor().setWarpPointSettings({ radius: 0 }, 'end'); + const p = addAt(a, 6.1, 0.2); + move(p.id, [6.1, 0.2, 1]); + const before = session(); + // A thin strip around the point, so every node it is bound to is on the strip's edge. + const strip = Array.from({ length: triangleCount(a.geometry) }, (_, f) => f).filter((f) => { + const centre = readFace(a.geometry, f).getMidpoint(new Vector3()); + return Math.abs(centre.y - 0.2) < 0.4 && centre.x > -8 && centre.x < 8; + }); + expect(strip).toContain(p.samples[0].face); + editor().setWarpRegion('painted'); + useEditor.setState({ toast: null, warp: { ...session(), faces: strip } }); + await editor().layWarpGrid(); + expect(session().stage).toBe('region'); + expect(session().model).toBe(before.model); + expect(session().points).toBe(before.points); + expect(session().faces).toBe(strip); + expect(toast()).toBe( + 'Points you moved would be held by the edge of the new region, so the grid was not laid. Paint farther around them, or delete them first.', + ); + // Painted back, the grid it had is kept. + useEditor.setState({ warp: { ...session(), faces: before.faces } }); + await editor().layWarpGrid(); + expect(session().model).toBe(before.model); + expect(session().points).toBe(before.points); }); it('a rebuild drops points that could only sit on fixed nodes, from undo steps too', async () => { @@ -2509,7 +2597,9 @@ describe('warp handles that must land', () => { expect(warpShortfall(session())).toBeLessThan(0.01); }); - it('Apply bakes exactly the surface shown, also while it is still settling', async () => { + it('Apply waits for a settling surface and bakes it settled, exactly as then shown', async () => { + // Idle settling runs in a browser window. + vi.stubGlobal('window', globalThis); for (const radius of [0, null]) { const a = plate('a', 0, 64); setup([a], ['a']); @@ -2517,14 +2607,90 @@ describe('warp handles that must land', () => { await editor().layWarpGrid(); if (radius !== null) editor().setWarpPointSettings({ radius }, 'end'); const p = addAt(a, 0.3, 0.2); + // The same edit settled to the end, for reference. + move(p.id, [0.3, 0.2, 3]); + finishWarpSettling(); + const settled = positionsOf(session().preview!); + editor().undoWarpEdit(); move(p.id, [0.3, 0.2, 3]); expect(session().settling).toBe(true); const shown = positionsOf(session().preview!); - expect(editor().applyWarp()).toBe(true); - expect(positionsOf(partOf('a').geometry)).toEqual(shown); + // The surface still has some way to go. + expect(shown).not.toEqual(settled); + const source = partOf('a').geometry; + expect(editor().applyWarp()).toBe(false); + expect(session().applying).toBe(true); + expect(partOf('a').geometry).toBe(source); + finishWarpSettling(); + expect(partOf('a').geometry).not.toBe(source); + expect(positionsOf(partOf('a').geometry)).toEqual(settled); + expect(session().stage).toBe('region'); + expect(editor().past).toHaveLength(1); editor().cancelWarp(); } - }); + vi.unstubAllGlobals(); + // Without a window it settles within Apply, to the same surface. + const b = plate('b', 0, 64); + setup([b], ['b']); + editor().setTool('warp'); + await editor().layWarpGrid(); + const q = addAt(b, 0.3, 0.2); + move(q.id, [0.3, 0.2, 3]); + finishWarpSettling(); + const settled = positionsOf(session().preview!); + editor().undoWarpEdit(); + move(q.id, [0.3, 0.2, 3]); + expect(session().settling).toBe(true); + expect(editor().applyWarp()).toBe(true); + expect(positionsOf(partOf('b').geometry)).toEqual(settled); + editor().cancelWarp(); + // A settled surface bakes at once, exactly as shown. + const a = plate('a', 0, 64); + setup([a], ['a']); + editor().setTool('warp'); + await editor().layWarpGrid(); + move(addAt(a, 0.3, 0.2).id, [0.3, 0.2, 3]); + finishWarpSettling(); + const shown = positionsOf(session().preview!); + expect(editor().applyWarp()).toBe(true); + expect(positionsOf(partOf('a').geometry)).toEqual(shown); + }, 30_000); + + it('an edit, a new grid or Cancel drops an Apply waiting for the surface to settle', async () => { + const edits: [string, (id: string) => void | Promise][] = [ + ['undo', () => editor().undoWarpEdit()], + ['drag', (id) => move(id, [0.3, 0.2, 2.5], 'drag')], + ['density', () => editor().setWarpDensity(4)], + ['cancel', () => editor().cancelWarp()], + ['leaving the tool', () => editor().setTool('select')], + ]; + vi.stubGlobal('window', globalThis); + for (const [name, edit] of edits) { + const a = plate('a', 0, 64); + setup([a], ['a']); + editor().setTool('warp'); + await editor().layWarpGrid(); + const p = addAt(a, 0.3, 0.2); + move(p.id, [0.3, 0.2, 3]); + expect(session().settling, name).toBe(true); + const source = partOf('a').geometry; + editor().applyWarp(); + expect(session().applying, name).toBe(true); + await edit(p.id); + const warp = editor().warp; + if (warp) { + expect(warp.applying, name).toBe(false); + if (name === 'drag') move(p.id, [0.3, 0.2, 2.5], 'end'); + finishWarpSettling(); + expect(editor().warp!.stage, name).toBe('warp'); + } + expect(partOf('a').geometry, name).toBe(source); + expect(editor().past, name).toHaveLength(0); + editor().cancelWarp(); + editor().setTool('select'); + } + vi.unstubAllGlobals(); + }, 30_000); it('settles a grid until it has converged, so an edit settles only what it changed', async () => { const { lift } = await ridden(); @@ -2668,6 +2834,11 @@ describe('line and area handles through a session', () => { intact(); lifted(); expect(current(handle.id).samples.length).toBeLessThanOrEqual(handle.samples.length); + // The density change is a step of its own. + await editor().undoWarpEdit(); + expect(session().density).toBe(defaultWarpDensity); + intact(); + lifted(); editor().undoWarpEdit(); expect(current(handle.id).radius).toBe(0); intact(); From 1c0ab6a363d27ce45ceb4d16b26443180ba25501 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Wed, 18 Nov 2026 16:24:15 -0800 Subject: [PATCH 18/25] Add line and area warp handles drawn by a stroke --- .../specs/2026-11-17-warp-handles-design.md | 122 +++- src/App.tsx | 9 +- src/components/SurfacePainter.tsx | 22 +- src/components/Viewport.tsx | 11 +- src/components/WarpControls.tsx | 57 +- src/components/WarpOverlay.tsx | 8 +- src/components/WarpStroke.tsx | 664 ++++++++++++++++++ src/core/store.ts | 75 ++ src/core/warp-handles.ts | 88 ++- src/core/warp-strokes.ts | 391 +++++++++++ src/hooks/useWorkbench.ts | 3 +- tests/e2e/warp-strokes.spec.ts | 338 +++++++++ tests/unit/warp-handles.test.ts | 38 +- tests/unit/warp-session.test.ts | 34 +- tests/unit/warp-strokes.test.ts | 450 ++++++++++++ 15 files changed, 2239 insertions(+), 71 deletions(-) create mode 100644 src/components/WarpStroke.tsx create mode 100644 src/core/warp-strokes.ts create mode 100644 tests/e2e/warp-strokes.spec.ts create mode 100644 tests/unit/warp-strokes.test.ts diff --git a/docs/superpowers/specs/2026-11-17-warp-handles-design.md b/docs/superpowers/specs/2026-11-17-warp-handles-design.md index 29dd044..0ff31c1 100644 --- a/docs/superpowers/specs/2026-11-17-warp-handles-design.md +++ b/docs/superpowers/specs/2026-11-17-warp-handles-design.md @@ -297,49 +297,95 @@ mirrored, non-uniformly scaled part. ### 6. Line and area handles -In the Warp stage an **Add** selector chooses what a press on the surface makes: +In the Warp stage an **Add** selector in the Control points section chooses what a press on the +surface makes, and says so in a line: - **Point**: a click adds a control point (today). - **Line**: press and drag draws a line; release makes one line handle. -- **Area**: press and drag paints with Warp's brush; release makes one area handle from the - faces painted in that stroke. - -**Input.** A stroke is a draft owned by one pointer. On press, camera navigation, pivot -picking, free transform, gizmo handles and point markers take priority over starting one. -An unmodified primary drag on the region draws; middle, right and Space navigation still -work. Release commits once; Escape, pointer cancel and window blur discard. The click that -ends a stroke adds no point, also when a short line is rejected. Hits come from the warped -preview. A line breaks where the pointer leaves the surface or jumps to a disconnected -spot, and only its longest run is kept. Area painting measures distance on the warped -preview and connectivity on the source mesh, and does not touch the region or its paint -history. - -**Handle.** One selectable object: `kind`, immutable samples (each a surface binding with -its pin), for an area its source faces, shared radius and falloff, and one target for its -centre. It is selected, moved, deleted and undone as one; all its samples move by the same -translation. In a multiple selection, rotate and scale move handle centres about the pivot, -as for points. Snap to neighbour snaps the centre and carries the rest with it. It is drawn -as its line or its tinted area with one marker at the centre. - -**Samples.** A line is resampled by arc length to half the local node spacing; an area -takes up to a few dozen face centres spread by farthest-point sampling, always including -the first hit. Samples with the same bound nodes are merged, so pointer speed does not -change stiffness. An area smaller than a grid cell still has several samples, so it lifts a -small plateau rather than a peak. - -**Reach.** The footprint is the nodes bound to the samples, plus for an area the nodes on -its faces. Section 4 applies with distance measured from the footprint: radius 0 gives a -continuous ridge or a rigid patch, and a radius above 0 adds the smooth skirt. - -Acceptance: along a line handle moved by `h`, the written surface between samples stays -within `0.1 h` of `h`; several interior points of an area do the same, including an area -smaller than a cell and a 60-node grid. +- **Area**: press and drag paints with Warp's brush (its radius, cursor and size shortcuts, and a + radius field under the selector); release makes one area handle from the faces painted in that + stroke. + +**Input.** A stroke is a draft owned by one pointer (`WarpStroke.tsx`). It starts only on an +unmodified primary press on a painted face of the warped part, when no camera navigation (middle +and right buttons, Space, the orbit and pan tools), pivot picking, free transform or exploded view +is in force; a point marker stops the press before it reaches the surface. The camera's controls +are switched off for that press, so a stroke never orbits, and a primary drag that begins off the +region still does. A gizmo handle hears the press after the surface does, so the first pointer move +or the release after a gizmo press discards the draft. The pointer's path is sampled every 2 screen +pixels, whatever the pointer's speed, by a raycast on the warped preview that another part in front +blocks. Release commits once; Escape, pointer cancel, lost pointer capture, window blur, camera +navigation starting and the session changing discard. The click that ends a stroke adds no point +and changes no selection, also when a line is rejected; in Line and Area mode a click adds nothing. +A line shorter than 4 px makes nothing; an area from a press alone is the one dab. + +A line breaks where the pointer leaves the paint or jumps to a disconnected spot: two successive +hits are joined when they share a bound node, or when the grid joins their nodes by a path no +longer than 1.5 times the straight line between them plus 2.5 node spacings. Only the longest run, +by length at rest, is kept. + +Area painting measures distance on the warped preview, in world space, from the hit to each +triangle, and connectivity on the source mesh: it walks the warp region's own welded triangles +from the hit face through painted faces turned within about 78° of the hit face, as region +painting picks them. It never touches the region or its paint history. The region's triangles +around each welded vertex are listed once per grid: on a 4.2-million-triangle part the first dab +costs 36 ms, where the first region dab builds whole-mesh face adjacency in 4.0 s; later dabs cost +under a millisecond. Dabs are a quarter of the brush radius apart along the stroke. + +**Handle.** One selectable object: `kind`, immutable samples (each a surface binding with its pin), +for an area its source `faces`, for a line its drawn `path` (up to 512 spots on faces, for drawing +only), shared radius and falloff, and one target for its centre. A line's `pin` is the surface +halfway along the stroke; an area's is the surface at the face centre nearest its area-weighted +centroid; both are pinned where the surface is shown, as a clicked point is. It is selected, +moved, deleted and undone as one; all its samples move by the same translation. In a multiple +selection, rotate and scale move handle centres about the pivot, as for points, and a single line +or area ignores them. Snap to neighbour snaps the centre and carries the rest with it. Making one +is one session undo step and selects it; a new line or area takes the panel's radius and falloff, +its default radius from the spacing at its samples' nodes. + +It is drawn as its line on the written surface, or its faces hatched in diagonal stripes of the +handle colour and a dark tone with their outline, and one marker at the centre. Lines are a dark +5 px casing under a 2.5 px core in the point markers' colours (selected and idle), drawn 4 px +nearer the eye so a line's width does not sink into a surface sloping across it; the stripes leave +the surface showing between them. Shapes are built when a handle's path or faces change; a solve +only rewrites their positions, read from the preview. While drawing, the line so far or the faces +painted so far are drawn the same way on the warped surface, appended in place. + +**Samples.** A line's hits are taken about every half local node spacing along the surface at +rest, keeping the first and the last, then one sample is kept for each set of grid nodes the +inner ones are bound to, so pointer speed does not change stiffness; both ends are always kept. +An area takes up to 32 face centres spread by farthest-point sampling at rest from the first hit, +at least 4 and about half a node spacing apart; an area of fewer than 4 faces also offers a spot +toward each corner of each face, so even one face has several samples and lifts a small plateau +rather than a peak. On the 32 mm torso scan, a line drawn across the chest took 35 samples and one +across the shoulder 10; an area painted on the chest took 3,300 to 3,500 faces and 32 samples, and one on +the shoulder 1,501 faces and 13. + +**Footprint.** A line or an area moves as one the free nodes within 0.75 node spacings (each +node's own) of the line through its samples in order, or of an area's samples, found by walking +the grid from the nodes the samples are bound to; a sample with none of its nodes among them adds +its most heavily bound one; an area also moves the free nodes on its faces. Every bound free node +seeds the reach's paths, and straight-line distance is measured from the samples and an area's +outline. Taking every node a sample is bound to, as first written, made the ridge's width depend on +which triangles the samples fell in: a binding reaches one to one and a half spacings, unevenly to +either side, and two samplings of one stroke differed by a quarter of the lift. Section 4 applies +with distance measured from the footprint: radius 0 gives a continuous ridge or a rigid patch, and a +radius above 0 adds the smooth skirt. + +Acceptance: along a line handle moved by `h`, the written surface between samples stays within +`0.1 h` of `h`, and no local maximum stands more than `0.05 h` above its neighbours; several interior +points of an area do the same, including an area smaller than a cell and a 60-node grid; the same +stroke drawn slowly and quickly gives results within `0.02 h`. Measured: a line within 0.017 h +(radius 0: 0.005 h) with no peak above 0.011 h at default density, within 0.012 h on a 60-node +ball; areas within 0.01 h; slow and quick within 0.002 h. On the 32 mm torso scan, lifted 1.92 mm, +a line across the chest stays between 1.912 and 1.921 mm (default radius: 1.901 and 1.927), where +points placed along the same path range from 0.71 to 2.03 mm. ### Data model -`WarpPoint` is a `WarpHandle`: `kind` (`point`; `line` and `area` are reserved), immutable -samples, for an area its source `faces`, `radius`, `falloff`, `auto`, one `target` (null while -unmoved), `baseline` (a shared snapshot) and a cached `reach`. `moveWarpPoints` keeps taking one +`WarpPoint` is a `WarpHandle`: `kind` (`point`, `line` or `area`), immutable samples, for an area +its source `faces`, for a line its drawn `path`, `radius`, `falloff`, `auto`, one `target` (null +while unmoved), `baseline` (a shared snapshot) and a cached `reach`. `moveWarpPoints` keeps taking one target per handle. Each session undo step holds the points, gap targets, the settled grid they held and the @@ -369,6 +415,8 @@ settles undo across it from there. A pure module, `warp-handles.ts`, turns handles and a model into solver input: reach, weights, guides, snapshots and their transfer, and distribution. It is unit-tested without the store. +`warp-strokes.ts` turns a stroke into samples: line resampling and merging, break detection, the +area brush and area sampling; `addWarpStroke` in the store builds the handle. ## Approaches considered diff --git a/src/App.tsx b/src/App.tsx index ff787a1..1c6ae75 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -619,7 +619,8 @@ function StatusBar() { navigationMode = useEditor((s) => (s.temporaryOrbit ? 'orbit' : s.navigationMode)), indexing = useEditor((s) => s.indexingMeshes > 0), live = useEditor((s) => s.liveStatus), - warpStage = useEditor((s) => (s.tool === 'warp' ? s.warp?.stage : undefined)); + warpStage = useEditor((s) => (s.tool === 'warp' ? s.warp?.stage : undefined)), + warpAdd = useEditor((s) => s.warpAdd); const hold = useShortcut('holdOrbit'), cancel = useShortcut('cancel'), pivot = useShortcut('pivot'), @@ -652,7 +653,11 @@ function StatusBar() { : surfacePainting ? `Drag to paint · Alt erases${smaller || larger ? ` · ${[smaller, larger].filter(Boolean).join(' / ')} brush size` : ''} · ${orbitHint} orbits` : warpStage === 'warp' - ? 'Click the surface to add a control point · Drag a handle to warp · Shift for fine adjustment' + ? warpAdd === 'line' + ? `Drag on the surface to draw a line · Esc discards it · ${orbitHint} orbits` + : warpAdd === 'area' + ? `Drag to paint an area${smaller || larger ? ` · ${[smaller, larger].filter(Boolean).join(' / ')} brush size` : ''} · Esc discards it · ${orbitHint} orbits` + : 'Click the surface to add a control point · Drag a handle to warp · Shift for fine adjustment' : warpStage ? `Paint the area to warp, or choose Whole part · Alt erases · ${orbitHint} orbits` : tool === 'align' diff --git a/src/components/SurfacePainter.tsx b/src/components/SurfacePainter.tsx index 828e173..f89b8d2 100644 --- a/src/components/SurfacePainter.tsx +++ b/src/components/SurfacePainter.tsx @@ -1,11 +1,12 @@ import { useEffect, useMemo } from 'react'; import { DoubleSide, MeshBasicMaterial, Quaternion, Vector3 } from 'three'; -import { paintingWarpRegion, useEditor, warpBrushRadius } from '../core/store'; +import { paintingWarpArea, paintingWarpRegion, useEditor, warpBrushRadius } from '../core/store'; import { contactColors, patchGeometry } from '../core/surfaces'; import { worldNormal, worldPoint } from '../core/geometry'; import { solveAlignment } from '../core/alignment'; import { partDisplay } from '../core/alignment-visibility'; import type { Part, SurfacePatch, SurfacePoint } from '../core/types'; +import { pointAccent } from './WarpStroke'; export const warpRegionColor = '#80cbc4'; @@ -123,15 +124,18 @@ function FlushPreview() { } export function PaintCursor({ part, hit }: { part: Part; hit: SurfacePoint | null }) { - const radius = useEditor((s) => (paintingWarpRegion(s) ? warpBrushRadius(s) : s.brushRadius)), + const radius = useEditor((s) => + paintingWarpRegion(s) || paintingWarpArea(s) ? warpBrushRadius(s) : s.brushRadius, + ), erase = useEditor((s) => s.brushErase), op = useEditor((s) => s.operation), tool = useEditor((s) => s.tool), navigationMode = useEditor((s) => (s.temporaryOrbit ? 'orbit' : s.navigationMode)), pivotPicking = useEditor((s) => s.pivotPicking); const warpRegion = useEditor((s) => paintingWarpRegion(s) && s.warp!.partId === part.id); + const warpArea = useEditor((s) => paintingWarpArea(s) && s.warp!.partId === part.id); const contact = tool === 'align' && op.mode === 'surface' && !!op.activeSurface; - if (!hit || (!contact && !warpRegion) || navigationMode || pivotPicking) return null; + if (!hit || (!contact && !warpRegion && !warpArea) || navigationMode || pivotPicking) return null; const index = op.surfacePairs.findIndex((pair) => pair.id === op.activeSurface?.pairId); const normal = worldNormal(part, hit), position = worldPoint(part, hit).addScaledVector(normal, 0.03); @@ -142,11 +146,13 @@ export function PaintCursor({ part, hit }: { part: Part; hit: SurfacePoint | nul {}; // A press on a gizmo handle also reaches whatever lies under it, but it is not a selection click. let gizmoPressed = false; +const gizmoWasPressed = () => gizmoPressed; const PartMesh = memo(function PartMesh({ part, @@ -244,6 +247,8 @@ const PartMesh = memo(function PartMesh({ state.notify('Reset the exploded view before adding control points.', 'info'); return; } + // Lines and areas are made by their strokes. + if (state.warpAdd !== 'point') return; state.addWarpPoint(toSurface(event), event.faceIndex); return; } @@ -308,13 +313,13 @@ const PartMesh = memo(function PartMesh({ } else if (paintingWarpRegion(state)) { event.stopPropagation(); state.paintWarpRegion(toSurface(event), event.faceIndex, event.altKey, true); - } + } else if (beginWarpStroke(event, part.id)) event.stopPropagation(); }} onPointerMove={(event) => { const state = useEditor.getState(); const contact = state.tool === 'align' && state.operation.mode === 'surface'; if ( - (!contact && !paintingWarpRegion(state)) || + (!contact && !paintingWarpRegion(state) && !paintingWarpArea(state)) || state.navigationMode || state.temporaryOrbit || state.pivotPicking || @@ -1143,6 +1148,7 @@ function Scene({ }} pressed={() => gizmoPressed} /> + @@ -1259,6 +1265,7 @@ export function Viewport() { event.type !== 'click' || event.button !== 0 || gizmoPressed || + endingWarpStroke() || state.temporaryOrbit || state.navigationMode || state.pivotPicking || diff --git a/src/components/WarpControls.tsx b/src/components/WarpControls.tsx index dc9620b..c0ffb36 100644 --- a/src/components/WarpControls.tsx +++ b/src/components/WarpControls.tsx @@ -222,6 +222,60 @@ function PointSettingsControls({ warp, part }: { warp: WarpSession; part: Part | ); } +const addHelp = { + point: 'Click the surface to add a control point.', + line: 'Drag on the surface to draw a line. It moves as one handle.', + area: 'Drag on the surface to paint an area. It moves as one handle.', +} as const; + +/** What a press on the surface makes, and for an area, Warp's brush size. */ +function AddControls({ part }: { part: Part | undefined }) { + const mode = useEditor((s) => s.warpAdd); + const radius = useEditor(warpBrushRadius); + const range = fittedSizeRange(part ? partSize(part) : 0); + const setRadius = (value: number) => useEditor.getState().setWarpBrushRadius(value); + return ( +
+ useEditor.getState().setWarpAdd(value)} + /> +

{addHelp[mode]}

+ {mode === 'area' ? ( + <> + + + + ) : null} +
+ ); +} + /** Ends the session without a notice and leaves the tool. */ function cancel() { const state = useEditor.getState(); @@ -451,10 +505,11 @@ export function WarpControls() { {building ? null : (
+

{warp.points.length ? `${warp.points.length} ${warp.points.length === 1 ? 'point' : 'points'}, ${selected} selected. Shift+click a point to add it to the selection. Delete removes the selected points.` - : 'Click the surface to add a control point. A point holds the surface where it is until you move it.'} + : 'A control point holds the surface where it is until you move it.'}

diff --git a/src/components/WarpOverlay.tsx b/src/components/WarpOverlay.tsx index ca7dd65..39c8b70 100644 --- a/src/components/WarpOverlay.tsx +++ b/src/components/WarpOverlay.tsx @@ -31,11 +31,10 @@ import { ManagedTransformControls } from './ManagedTransformControls'; import { warpRegionColor } from './SurfacePainter'; import { gridNodePositions, WarpGrid } from './WarpGrid'; import { surfacePoints } from './surface-points'; +import { pointAccent, pointIdle, WarpHandleShapes } from './WarpStroke'; const noRaycast: Mesh['raycast'] = () => {}; -const pointAccent = '#ed9b54', - pointIdle = '#e9eaec', - autoIdle = '#a4aab2', +const autoIdle = '#a4aab2', foldColor = '#f06a6a'; const closedColor = new Color('#7fd18b'), openColor = new Color('#f06a6a'); @@ -75,6 +74,7 @@ export function WarpOverlay({ onPress, pressed }: { onPress: () => void; pressed {warp.seam ? : null} + {warp.points.map((point) => ( ) => event.stopPropagation()} onClick={(event: ThreeEvent) => { event.stopPropagation(); const state = useEditor.getState(); diff --git a/src/components/WarpStroke.tsx b/src/components/WarpStroke.tsx new file mode 100644 index 0000000..2502483 --- /dev/null +++ b/src/components/WarpStroke.tsx @@ -0,0 +1,664 @@ +import { useEffect, useLayoutEffect, useMemo } from 'react'; +import { useThree } from '@react-three/fiber'; +import type { ThreeEvent } from '@react-three/fiber'; +import { + BufferAttribute, + BufferGeometry, + Color, + DoubleSide, + Group, + Mesh, + MeshBasicMaterial, + Raycaster, + Vector2, + Vector3, + type InstancedInterleavedBuffer, + type Intersection, +} from 'three'; +import { LineMaterial } from 'three/addons/lines/LineMaterial.js'; +import { LineSegments2 } from 'three/addons/lines/LineSegments2.js'; +import { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js'; +import { + strokingWarp, + useEditor, + warpBrushRadius, + type WarpPoint, + type WarpSession, +} from '../core/store'; +import type { Part, Vec3 } from '../core/types'; +import type { WarpSample } from '../core/warp-handles'; +import { isPaintedFace, type WarpModel } from '../core/warp-model'; +import { + areaBrushFaces, + faceBarycentric, + facePoint, + strokeConnected, + strokeSample, + type WarpStrokePoint, +} from '../core/warp-strokes'; +import { partMeshes } from '../xr/part-meshes'; + +/** Handle colours, shared with the point markers. */ +export const pointAccent = '#ed9b54', + pointIdle = '#e9eaec'; +const casingColor = '#15181b'; + +/** Screen pixels between the spots a stroke is sampled at, whatever the pointer's speed. */ +const strokeStep = 2; +/** A line drawn shorter than this many pixels makes nothing. */ +const shortStroke = 4; +/** Area dabs are this share of the brush radius apart along the stroke. */ +const dabSpacing = 0.25; +/** + * How far a line is drawn toward the eye, in pixels. Its width is screen-aligned at one depth, so + * without this half of it would sink into a surface sloping across it. + */ +const lineLift = 4; + +/** A line material whose segments sit `lineLift` pixels nearer the eye than their points. */ +function liftedLine(color: string, width: number) { + const material = new LineMaterial({ color, linewidth: width }); + material.onBeforeCompile = (shader) => { + shader.vertexShader = shader.vertexShader.replace( + 'vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );', + `vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 ); + { + bool eye = projectionMatrix[ 2 ][ 3 ] == - 1.0; + float pixel = 2.0 / ( projectionMatrix[ 1 ][ 1 ] * resolution.y ); + if ( eye ) { + start.xyz -= normalize( start.xyz ) * ${lineLift.toFixed(1)} * pixel * - start.z; + end.xyz -= normalize( end.xyz ) * ${lineLift.toFixed(1)} * pixel * - end.z; + } else { + start.z += ${lineLift.toFixed(1)} * pixel; + end.z += ${lineLift.toFixed(1)} * pixel; + } + }`, + ); + }; + return material; +} + +/** + * Line segments on a surface, as a dark casing under a coloured core so they read on any part + * colour. Positions are written in place; the buffer grows only when it must. + */ +class SurfaceSegments { + readonly geometry = new LineSegmentsGeometry(); + readonly core: LineSegments2; + readonly casing: LineSegments2; + private array = new Float32Array(0); + count = 0; + constructor(color: string) { + this.casing = new LineSegments2(this.geometry, liftedLine(casingColor, 5)); + // The core of every segment draws over the casing of its neighbours. + this.casing.material.depthWrite = false; + this.core = new LineSegments2(this.geometry, liftedLine(color, 2.5)); + for (const [line, order] of [ + [this.casing, 6], + [this.core, 7], + ] as const) { + line.renderOrder = order; + line.frustumCulled = false; + line.raycast = () => {}; + } + } + setColor(color: string) { + (this.core.material as LineMaterial).color.set(color); + } + /** Room for `segments`, keeping those written. */ + reserve(segments: number) { + if (segments * 6 <= this.array.length) return this.array; + const array = new Float32Array(Math.max(segments, 2 * (this.array.length / 6), 16) * 6); + array.set(this.array); + this.array = array; + this.geometry.setPositions(array); + return array; + } + /** Shows the first `count` segments written. */ + show(count: number) { + this.count = count; + this.geometry.instanceCount = count; + const start = this.geometry.getAttribute('instanceStart') as unknown as + { data: InstancedInterleavedBuffer } | undefined; + if (start) start.data.needsUpdate = true; + this.casing.visible = this.core.visible = count > 0; + } + dispose() { + this.geometry.dispose(); + (this.core.material as LineMaterial).dispose(); + (this.casing.material as LineMaterial).dispose(); + } +} + +/** Faces drawn with diagonal stripes of a colour and a dark tone, so the surface shows between. */ +class StripedFaces { + readonly geometry = new BufferGeometry(); + readonly mesh: Mesh; + private array = new Float32Array(0); + private attribute = new BufferAttribute(this.array, 3); + constructor(color: string) { + const material = new MeshBasicMaterial({ + color, + side: DoubleSide, + transparent: true, + opacity: 0.45, + depthWrite: false, + polygonOffset: true, + polygonOffsetFactor: -3, + polygonOffsetUnits: -3, + }); + const dark = new Color(casingColor); + material.onBeforeCompile = (shader) => { + shader.uniforms.stripeDark = { value: dark }; + shader.fragmentShader = shader.fragmentShader + .replace('void main() {', 'uniform vec3 stripeDark;\nvoid main() {') + .replace( + '#include ', + `#include + diffuseColor.rgb = mod( gl_FragCoord.x + gl_FragCoord.y, 10.0 ) < 4.0 ? stripeDark : diffuseColor.rgb;`, + ); + }; + this.mesh = new Mesh(this.geometry, material); + this.mesh.renderOrder = 5; + this.mesh.frustumCulled = false; + this.mesh.raycast = () => {}; + this.geometry.setAttribute('position', this.attribute); + } + setColor(color: string) { + (this.mesh.material as MeshBasicMaterial).color.set(color); + } + reserve(faces: number) { + if (faces * 9 <= this.array.length) return this.array; + const array = new Float32Array(Math.max(faces, 2 * (this.array.length / 9), 64) * 9); + array.set(this.array); + this.array = array; + this.attribute = new BufferAttribute(array, 3); + this.geometry.setAttribute('position', this.attribute); + return array; + } + show(faces: number) { + this.attribute.needsUpdate = true; + this.geometry.setDrawRange(0, faces * 3); + this.mesh.visible = faces > 0; + } + dispose() { + this.geometry.dispose(); + (this.mesh.material as MeshBasicMaterial).dispose(); + } +} + +/** Writes a face's three warped corners, mesh-local, at `offset`. */ +function writeFace( + model: WarpModel, + positions: ArrayLike, + face: number, + out: Float32Array, + offset: number, +) { + for (let c = 0; c < 3; c++) { + const v = model.index?.[face * 3 + c] ?? face * 3 + c; + out[offset + c * 3] = positions[v * 3]; + out[offset + c * 3 + 1] = positions[v * 3 + 1]; + out[offset + c * 3 + 2] = positions[v * 3 + 2]; + } +} + +interface Draft { + kind: 'line' | 'area'; + pointer: number; + partId: string; + model: WarpModel; + /** Where the stroke was last sampled, client pixels. */ + x: number; + y: number; + travelled: number; + /** Unbroken stretches of a line, each with its length at rest. */ + runs: { points: WarpStrokePoint[]; length: number }[]; + previous: WarpSample | null; + broken: boolean; + /** Line segments drawn so far. */ + drawn: number; + faces: Set; + first: WarpStrokePoint | null; + dab: Vector3 | null; + radius: number; + controls: { enabled: boolean } | null; +} + +let draft: Draft | null = null; +let starter: ((event: ThreeEvent, partId: string) => boolean) | null = null; +// The click that ends a stroke follows its pointer up; it must not add or select anything. +let swallowing = false; + +/** + * Starts a line or area stroke from a press on the warped surface, when the Add mode draws and + * nothing else owns the press. Returns whether it started. + */ +export const beginWarpStroke = (event: ThreeEvent, partId: string) => + starter?.(event, partId) ?? false; + +/** Whether the click under way ends a stroke rather than picks. */ +export const endingWarpStroke = () => swallowing; + +/** + * Owns a stroke from press to release: samples the pointer's path every few pixels on the warped + * surface, draws the line or the faces painted so far, and makes one handle on release. Escape, + * pointer cancel, lost capture, window blur, camera navigation and a gizmo press discard it. + */ +export function WarpStrokeController({ pressed }: { pressed: () => boolean }) { + const get = useThree((s) => s.get), + invalidate = useThree((s) => s.invalidate); + const view = useMemo(() => { + const group = new Group(); + group.matrixAutoUpdate = false; + const line = new SurfaceSegments(pointAccent); + const fill = new StripedFaces(pointAccent); + group.add(line.casing, line.core, fill.mesh); + line.show(0); + fill.show(0); + return { group, line, fill }; + }, []); + useEffect(() => () => (view.line.dispose(), view.fill.dispose()), [view]); + + useEffect(() => { + const raycaster = new Raycaster(); + raycaster.firstHitOnly = true; + const ndc = new Vector2(); + const canvas = () => { + const { events, gl } = get(); + return events.connected instanceof HTMLElement ? events.connected : gl.domElement; + }; + const output = () => useEditor.getState().warp?.output?.positions; + + /** The spot under a client position on the warped part, or null off it or behind another. */ + const hitAt = (d: Draft, x: number, y: number): WarpStrokePoint | null => { + const own = partMeshes.get(d.partId); + const positions = output(); + if (!own || !positions) return null; + const rect = canvas().getBoundingClientRect(); + ndc.set(((x - rect.left) / rect.width) * 2 - 1, -((y - rect.top) / rect.height) * 2 + 1); + raycaster.setFromCamera(ndc, get().camera); + let nearest: Intersection | null = null; + for (const mesh of partMeshes.values()) { + const hits = raycaster.intersectObject(mesh, false); + if (hits.length && (!nearest || hits[0].distance < nearest.distance)) nearest = hits[0]; + } + if (!nearest || nearest.object !== own || nearest.faceIndex == null) return null; + const local = own.worldToLocal(nearest.point.clone()).toArray() as Vec3; + return { + face: nearest.faceIndex, + barycentric: faceBarycentric(d.model, positions, nearest.faceIndex, local), + }; + }; + + const drawLine = (d: Draft, positions: ArrayLike) => { + let segments = 0; + for (const run of d.runs) segments += Math.max(0, run.points.length - 1); + if (segments === d.drawn) return; + const array = view.line.reserve(segments); + let s = 0; + const a: Vec3 = [0, 0, 0], + b: Vec3 = [0, 0, 0]; + for (const run of d.runs) + for (let i = 1; i < run.points.length; i++, s++) { + // Only segments added since the last draw are written. + if (s < d.drawn) continue; + facePoint(d.model, positions, run.points[i - 1], a); + facePoint(d.model, positions, run.points[i], b); + array.set(a, s * 6); + array.set(b, s * 6 + 3); + } + d.drawn = segments; + view.line.show(segments); + }; + + const addLine = (d: Draft, point: WarpStrokePoint | null) => { + const state = useEditor.getState().warp?.state; + const sample = point && state ? strokeSample(d.model, state, point) : null; + if (!sample) { + d.broken = true; + d.previous = null; + return; + } + if (d.previous && !strokeConnected(d.model, d.previous, sample)) d.broken = true; + if (d.broken || !d.runs.length) d.runs.push({ points: [], length: 0 }); + const run = d.runs[d.runs.length - 1]; + if (d.previous && !d.broken) + run.length += Math.hypot( + ...sample.restWorld.map((value, a) => value - d.previous!.restWorld[a]), + ); + run.points.push(point!); + d.previous = sample; + d.broken = false; + }; + + const dab = (d: Draft, point: WarpStrokePoint | null, positions: ArrayLike) => { + if (!point || !isPaintedFace(d.model, point.face)) return; + const local = facePoint(d.model, positions, point); + const at = new Vector3(...local).applyMatrix4(view.group.matrix); + if (d.dab && d.dab.distanceTo(at) < dabSpacing * d.radius) return; + d.dab = at; + d.first ??= point; + const added = areaBrushFaces(d.model, positions, point, d.radius).filter( + (face) => !d.faces.has(face), + ); + if (!added.length) return; + const start = d.faces.size; + const array = view.fill.reserve(start + added.length); + added.forEach((face, i) => { + d.faces.add(face); + writeFace(d.model, positions, face, array, (start + i) * 9); + }); + view.fill.show(d.faces.size); + }; + + const sample = (d: Draft, point: WarpStrokePoint | null) => { + const positions = output(); + if (!positions) return; + if (d.kind === 'line') addLine(d, point); + else dab(d, point, positions); + }; + + /** Samples the path from the last sampled spot toward a client position, every few pixels. */ + const follow = (d: Draft, x: number, y: number) => { + const dx = x - d.x, + dy = y - d.y; + const length = Math.hypot(dx, dy); + const steps = Math.floor(length / strokeStep); + for (let i = 1; i <= steps; i++) { + const t = (i * strokeStep) / length; + sample(d, hitAt(d, d.x + dx * t, d.y + dy * t)); + } + if (steps) { + d.travelled += steps * strokeStep; + d.x += (dx * steps * strokeStep) / length; + d.y += (dy * steps * strokeStep) / length; + } + }; + + const redraw = (d: Draft) => { + const positions = output(); + if (positions && d.kind === 'line') drawLine(d, positions); + invalidate(); + }; + + const end = () => { + const d = draft; + if (!d) return null; + draft = null; + window.removeEventListener('pointermove', move, true); + window.removeEventListener('pointerup', up, true); + window.removeEventListener('pointercancel', cancel, true); + window.removeEventListener('blur', discard); + window.removeEventListener('keydown', key, true); + canvas().removeEventListener('lostpointercapture', lost); + try { + canvas().releasePointerCapture(d.pointer); + } catch { + // Already released. + } + if (d.controls) d.controls.enabled = true; + view.line.show(0); + view.fill.show(0); + unsubscribe?.(); + unsubscribe = null; + invalidate(); + return d; + }; + const discard = () => void end(); + + const move = (event: PointerEvent) => { + const d = draft; + if (!d || event.pointerId !== d.pointer) return; + if (pressed()) return discard(); + const events = event.getCoalescedEvents?.() ?? []; + for (const e of events.length ? events : [event]) follow(d, e.clientX, e.clientY); + redraw(d); + }; + const up = (event: PointerEvent) => { + const d = draft; + if (!d || event.pointerId !== d.pointer) return; + swallowing = true; + setTimeout(() => (swallowing = false)); + if (pressed()) return discard(); + // The spot let go over closes the stroke. + follow(d, event.clientX, event.clientY); + if (Math.hypot(event.clientX - d.x, event.clientY - d.y) > 0.5) { + d.travelled += Math.hypot(event.clientX - d.x, event.clientY - d.y); + sample(d, hitAt(d, event.clientX, event.clientY)); + } + end(); + const state = useEditor.getState(); + if (d.kind === 'line') { + if (d.travelled < shortStroke) return; + const longest = d.runs.reduce( + (best, run) => (!best || run.length > best.length ? run : best), + null, + ); + if (longest && longest.points.length > 1) + state.addWarpStroke({ kind: 'line', points: longest.points }); + } else if (d.first && d.faces.size) + state.addWarpStroke({ kind: 'area', faces: [...d.faces], first: d.first }); + }; + const cancel = (event: PointerEvent) => { + if (draft && event.pointerId === draft.pointer) discard(); + }; + const lost = (event: PointerEvent) => { + if (draft && event.pointerId === draft.pointer) discard(); + }; + const key = (event: KeyboardEvent) => { + if (!draft || event.key !== 'Escape') return; + event.preventDefault(); + event.stopPropagation(); + discard(); + }; + let unsubscribe: (() => void) | null = null; + + starter = (event, partId) => { + const state = useEditor.getState(), + warp = state.warp; + const model = warp?.model; + const face = event.faceIndex; + if ( + draft || + !strokingWarp(state) || + !model || + !warp?.output || + warp.partId !== partId || + face == null || + !isPaintedFace(model, face) || + event.button !== 0 || + event.shiftKey || + event.ctrlKey || + event.metaKey || + event.altKey || + state.navigationMode || + state.temporaryOrbit || + state.pivotPicking || + state.freeTransform || + state.view.explode || + pressed() + ) + return false; + const mesh = event.object as Mesh; + const local = mesh.worldToLocal(event.point.clone()).toArray() as Vec3; + const first = { + face, + barycentric: faceBarycentric(model, warp.output.positions, face, local), + }; + // The camera's controls see this press after it; a stroke owns it instead. + const controls = get().controls as { enabled: boolean } | null; + const owned = controls?.enabled ? controls : null; + if (owned) owned.enabled = false; + const d: Draft = { + kind: state.warpAdd === 'area' ? 'area' : 'line', + pointer: event.pointerId, + partId, + model, + x: event.nativeEvent.clientX, + y: event.nativeEvent.clientY, + travelled: 0, + runs: [], + previous: null, + broken: false, + drawn: 0, + faces: new Set(), + first: null, + dab: null, + radius: warpBrushRadius(state), + controls: owned, + }; + draft = d; + mesh.updateWorldMatrix(true, false); + view.group.matrix.copy(mesh.matrixWorld); + view.group.matrixWorldNeedsUpdate = true; + view.line.show(0); + view.fill.show(0); + window.addEventListener('pointermove', move, true); + window.addEventListener('pointerup', up, true); + window.addEventListener('pointercancel', cancel, true); + window.addEventListener('blur', discard); + window.addEventListener('keydown', key, true); + const element = canvas(); + element.addEventListener('lostpointercapture', lost); + try { + element.setPointerCapture(event.pointerId); + } catch { + // A pointer that is not active cannot be captured; window listeners still follow it. + } + // Anything that takes the pointer or the session away ends the stroke. + unsubscribe = useEditor.subscribe((s) => { + if ( + draft === d && + (!strokingWarp(s) || + s.warp?.model !== d.model || + s.temporaryOrbit || + !!s.navigationMode || + s.pivotPicking || + !!s.freeTransform || + s.view.explode > 0) + ) + discard(); + }); + sample(d, first); + redraw(d); + return true; + }; + return () => { + discard(); + starter = null; + }; + }, [get, invalidate, pressed, view]); + + return ; +} + +/** Boundary edges of a set of faces, as pairs of face corners: face × 3 + corner. */ +function boundaryCorners(model: WarpModel, faces: readonly number[]) { + const { weldOf, weldedCount } = model.region; + const welded = (face: number, c: number) => weldOf[model.index?.[face * 3 + c] ?? face * 3 + c]; + const count = new Map(); + const key = (a: number, b: number) => (a < b ? a * weldedCount + b : b * weldedCount + a); + for (const face of faces) + for (let c = 0; c < 3; c++) { + const k = key(welded(face, c), welded(face, (c + 1) % 3)); + count.set(k, (count.get(k) ?? 0) + 1); + } + const corners: number[] = []; + for (const face of faces) + for (let c = 0; c < 3; c++) + if (count.get(key(welded(face, c), welded(face, (c + 1) % 3))) === 1) + corners.push(face * 3 + c, face * 3 + ((c + 1) % 3)); + return corners; +} + +/** + * A line handle as its line on the written surface, and an area handle as its faces tinted with + * its outline, in the colours of the point markers. Shapes are built when a handle's path or + * faces change; each solve only rewrites their positions. + */ +export function WarpHandleShapes({ warp, part }: { warp: WarpSession; part: Part }) { + const handles = warp.points.filter((point) => point.kind !== 'point'); + if (!handles.length) return null; + return ( + + {handles.map((handle) => ( + + ))} + + ); +} + +function HandleShape({ + handle, + warp, + selected, +}: { + handle: WarpPoint; + warp: WarpSession; + selected: boolean; +}) { + const invalidate = useThree((s) => s.invalidate); + const model = warp.model!; + const { path, faces } = handle; + const shape = useMemo(() => { + const group = new Group(); + const line = new SurfaceSegments(pointIdle); + group.add(line.casing, line.core); + if (faces) { + const fill = new StripedFaces(pointIdle); + group.add(fill.mesh); + fill.reserve(faces.length); + return { group, line, fill, corners: boundaryCorners(model, faces) }; + } + return { group, line, fill: null, corners: null }; + }, [model, faces]); + useEffect(() => () => (shape.line.dispose(), shape.fill?.dispose()), [shape]); + useLayoutEffect(() => { + shape.line.setColor(selected ? pointAccent : pointIdle); + shape.fill?.setColor(selected ? pointAccent : pointIdle); + invalidate(); + }, [shape, selected, invalidate]); + const positions = warp.output?.positions; + // Each solve writes the preview in place and makes a new session object. + useLayoutEffect(() => { + if (!positions) return; + const { line, fill, corners } = shape; + const a: Vec3 = [0, 0, 0]; + if (fill && faces && corners) { + const array = fill.reserve(faces.length); + faces.forEach((face, i) => writeFace(model, positions, face, array, i * 9)); + fill.show(faces.length); + const segments = corners.length / 2; + const ends = line.reserve(segments); + for (let i = 0; i < corners.length; i++) { + const corner = corners[i]; + const v = model.index?.[corner] ?? corner; + ends[i * 3] = positions[v * 3]; + ends[i * 3 + 1] = positions[v * 3 + 1]; + ends[i * 3 + 2] = positions[v * 3 + 2]; + } + line.show(segments); + } else if (path && path.length > 1) { + const ends = line.reserve(path.length - 1); + const b: Vec3 = [0, 0, 0]; + facePoint(model, positions, path[0], a); + for (let i = 1; i < path.length; i++) { + facePoint(model, positions, path[i], b); + ends.set(a, (i - 1) * 6); + ends.set(b, (i - 1) * 6 + 3); + a[0] = b[0]; + a[1] = b[1]; + a[2] = b[2]; + } + line.show(path.length - 1); + } + invalidate(); + }, [shape, warp, positions, model, path, faces, invalidate]); + return ; +} diff --git a/src/core/store.ts b/src/core/store.ts index 7c5645f..6d8c82e 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -118,6 +118,7 @@ import { } from './warp-handles'; import { buildWarpModelJob } from './warp-job'; import { isPaintedFace, type WarpModel, type WarpModelInput } from './warp-model'; +import { areaSamples, lineSamples, thinPath, type WarpStrokePoint } from './warp-strokes'; import { closeGapTargets, measureSeam, @@ -221,6 +222,11 @@ export interface WarpBaseline { } export type WarpGizmo = 'translate' | 'rotate' | 'scale' | 'transform'; +export type WarpAddMode = 'point' | 'line' | 'area'; +/** A line as its hits along the surface, or an area as the faces one stroke painted. */ +export type WarpStroke = + | { kind: 'line'; points: WarpStrokePoint[] } + | { kind: 'area'; faces: number[]; first: WarpStrokePoint }; /** A control point: a handle with one sample. */ export type WarpPoint = WarpHandle; export interface WarpSession { @@ -350,6 +356,8 @@ interface EditorState { warp: WarpSession | null; /** Feathered edge for painted warp regions, remembered for the page session and never saved. */ warpFeather: WarpFeatherOption; + /** What a press on the surface makes in the Warp stage, remembered for the page session. */ + warpAdd: WarpAddMode; /** First warp in the queued or submitted edit, available to reopen if that batch is refused. */ warpPending: WarpRecovery | null; warpInFlight: WarpRecovery | null; @@ -442,6 +450,9 @@ interface EditorState { cancelWarp: (notice?: string) => void; /** Adds a control point where the warped surface was clicked, and selects it. */ addWarpPoint: (point: SurfacePoint, face: number) => void; + setWarpAdd: (mode: WarpAddMode) => void; + /** Makes one line or area handle from a stroke on the warped surface, and selects it. */ + addWarpStroke: (stroke: WarpStroke) => boolean; /** Removes these points, or the selected ones. */ removeWarpPoints: (ids?: string[]) => void; selectWarpPoints: (ids: string[], additive?: boolean) => void; @@ -1508,6 +1519,7 @@ export const useEditor = create((set, get) => ({ operation: blankOperation(), warp: null, warpFeather: { enabled: false, width: null }, + warpAdd: 'point', warpPending: null, warpInFlight: null, view: { @@ -2313,6 +2325,61 @@ export const useEditor = create((set, get) => ({ }, }); }, + setWarpAdd: (warpAdd) => set({ warpAdd }), + addWarpStroke: (stroke) => { + const state = get(), + warp = state.warp, + model = warp?.model; + if (!warp || !model || !warp.state || state.tool !== 'warp' || warp.stage !== 'warp') + return false; + const made = + stroke.kind === 'line' + ? lineSamples(model, warp.state, stroke.points) + : areaSamples(model, warp.state, stroke.faces, stroke.first); + if (!made || (stroke.kind === 'line' && made.samples.length < 2)) { + state.notify( + stroke.kind === 'line' + ? 'Draw a longer line on the painted area.' + : 'Paint on the painted area.', + 'info', + ); + return false; + } + const eligible = warpEligibleNodes(model); + const nodes = new Set(); + for (const { binding } of made.samples) + for (const node of binding.node) if (eligible[node]) nodes.add(node); + const part = state.scene.parts.find((p) => p.id === warp.partId); + const faces = + stroke.kind === 'area' + ? [...new Set(stroke.faces)].filter((f) => isPaintedFace(model, f)) + : []; + // It holds the settled surface where it is, so adding it changes nothing. + const added = reachHandle(model, { + id: uid(), + kind: stroke.kind, + samples: made.samples, + ...(stroke.kind === 'area' + ? { faces: faces.sort((a, b) => a - b) } + : { path: thinPath(stroke.points.filter(({ face }) => isPaintedFace(model, face))) }), + pin: made.pin, + target: null, + radius: warpPointRadius(warp, part, spacingAt(model, nodes)), + falloff: warp.pointFalloff, + auto: false, + baseline: settledOf(warp), + reach: null, + }); + set({ + warp: { + ...warp, + points: [...warp.points, added], + selectedPoints: [added.id], + undo: withUndo(warp), + }, + }); + return true; + }, removeWarpPoints: (ids) => { const state = get(), warp = state.warp; @@ -3528,6 +3595,14 @@ export const sceneLighting = (state: EditorState) => state.scene.lighting ?? sta export const paintingWarpRegion = (state: Pick) => state.tool === 'warp' && state.warp?.stage === 'region' && state.warp.region === 'painted'; +/** Whether a press on the warped surface draws a line or paints an area rather than adds a point. */ +export const strokingWarp = (state: Pick) => + state.tool === 'warp' && state.warp?.stage === 'warp' && state.warpAdd !== 'point'; + +/** Whether Warp's brush paints an area handle: the Area mode of the Warp stage. */ +export const paintingWarpArea = (state: Pick) => + strokingWarp(state) && state.warpAdd === 'area'; + /** Warp's starting brush radius: 3 % of the part's size. */ export const fittedWarpBrushRadius = (part: Pick) => Math.max(0.05, Math.min(100, Number((partSize(part) * 0.03).toPrecision(2)))); diff --git a/src/core/warp-handles.ts b/src/core/warp-handles.ts index 1f1b847..7bec25e 100644 --- a/src/core/warp-handles.ts +++ b/src/core/warp-handles.ts @@ -75,6 +75,8 @@ export interface WarpHandle { samples: readonly WarpSample[]; /** An area's source faces, geometry face ids. Its footprint covers the nodes on them. */ faces?: readonly number[]; + /** A line as drawn, on geometry faces: what is shown of it, not what it holds. */ + path?: readonly { face: number; barycentric: Vec3 }[]; /** Where the handle's target is measured from: a point's sample pin. */ pin: Vec3; /** Null while unmoved, when the handle acts as a pin. */ @@ -359,10 +361,36 @@ export function warpEligibleNodes(model: WarpModel) { /** What a footprint is made from. Without a kind, a handle is a point. */ type WarpFootprintOf = Pick & Partial>; +/** + * A line or an area moves as one the free nodes within this many node spacings of it. A sample's + * binding reaches farther, unevenly to either side, so taking every node bound would make the + * ridge's width depend on which triangles the samples fell in, and so on pointer speed. + */ +export const warpFootprintSpacings = 0.75; + +/** Distance from a point to the segment from `a` to `b`. */ +function segmentDistance(p: ArrayLike, a: Vec3, b: Vec3) { + const ux = b[0] - a[0], + uy = b[1] - a[1], + uz = b[2] - a[2]; + const length = ux * ux + uy * uy + uz * uz; + const t = + length > 0 + ? Math.max( + 0, + Math.min(1, ((p[0] - a[0]) * ux + (p[1] - a[1]) * uy + (p[2] - a[2]) * uz) / length), + ) + : 0; + return Math.hypot(p[0] - a[0] - t * ux, p[1] - a[1] - t * uy, p[2] - a[2] - t * uz); +} + /** * Where a handle's reach is measured from, by kind. A point is its samples alone. A line or an area - * moves the free nodes its samples are bound to as one, and an area also the free nodes on its - * faces still in the region. Paths start at all of them. + * moves as one the free nodes on it: within `warpFootprintSpacings` of the line through its + * samples in order, or of an area's samples, found along the grid from the nodes the samples are + * bound to. A sample with none of its own nodes among them adds its most heavily bound one. An area + * also moves the free nodes on its faces still in the region, and straight-line distance is also + * measured from its outline. Paths start at every free node the samples are bound to. */ export function handleFootprint(model: WarpModel, handle: WarpFootprintOf): WarpFootprint { const eligible = warpEligibleNodes(model); @@ -371,19 +399,69 @@ export function handleFootprint(model: WarpModel, handle: WarpFootprintOf): Warp for (const { binding } of handle.samples) for (const n of binding.node) if (eligible[n]) seeds.add(n); const sources = handle.samples.map(({ restWorld }) => restWorld); - if (handle.kind && handle.kind !== 'point') for (const n of seeds) nodes.add(n); + if (handle.kind && handle.kind !== 'point') { + const { restNodes } = model; + const { edgeStart, edges } = model.grid; + const on = (n: number) => { + const at = restNodes.subarray(n * 3, n * 3 + 3); + const limit = warpFootprintSpacings * spacingAt(model, [n]); + for (let s = 0; s < sources.length; s++) { + const d = + handle.kind === 'line' && s > 0 + ? segmentDistance(at, sources[s - 1], sources[s]) + : Math.hypot(at[0] - sources[s][0], at[1] - sources[s][1], at[2] - sources[s][2]); + if (d <= limit) return true; + } + return false; + }; + const seen = new Set(seeds), + stack = [...seeds]; + while (stack.length) { + const n = stack.pop()!; + const inside = on(n); + if (inside) nodes.add(n); + else if (!seeds.has(n)) continue; + for (let e = edgeStart[n]; e < edgeStart[n + 1]; e++) { + const j = edges[e]; + if (eligible[j] && !seen.has(j)) { + seen.add(j); + stack.push(j); + } + } + } + for (const { binding } of handle.samples) { + if (binding.node.some((n) => nodes.has(n))) continue; + let heaviest = -1; + binding.node.forEach((n, k) => { + if (eligible[n] && (heaviest < 0 || binding.weight[k] > binding.weight[heaviest])) + heaviest = k; + }); + if (heaviest >= 0) nodes.add(binding.node[heaviest]); + } + } if (handle.kind === 'area' && handle.faces) { const { region, grid, restWorld } = model; + const { weldedCount } = region; + // Straight-line distance from outside an area is to its outline, so the outline's vertices + // are its sources: all of its corners would cost a measure each per node reached. + const edges = new Map(); for (const face of handle.faces) { const triangle = regionTriangleOf(region, face); if (triangle < 0) continue; for (let c = 0; c < 3; c++) { - const v = region.triangles[triangle * 3 + c]; - sources.push([restWorld[v * 3], restWorld[v * 3 + 1], restWorld[v * 3 + 2]]); + const v = region.triangles[triangle * 3 + c], + w = region.triangles[triangle * 3 + ((c + 1) % 3)]; const n = grid.nodeOf[v]; if (n !== 0xffffffff && eligible[n]) nodes.add(n); + const key = v < w ? v * weldedCount + w : w * weldedCount + v; + edges.set(key, (edges.get(key) ?? 0) + 1); } } + const outline = new Set(); + for (const [key, count] of edges) + if (count === 1) outline.add(Math.floor(key / weldedCount)).add(key % weldedCount); + for (const v of [...outline].sort((a, b) => a - b)) + sources.push([restWorld[v * 3], restWorld[v * 3 + 1], restWorld[v * 3 + 2]]); } const sorted = (set: Set) => [...set].sort((a, b) => a - b); for (const n of nodes) seeds.add(n); diff --git a/src/core/warp-strokes.ts b/src/core/warp-strokes.ts new file mode 100644 index 0000000..e73b2a8 --- /dev/null +++ b/src/core/warp-strokes.ts @@ -0,0 +1,391 @@ +import { Triangle, Vector3 } from 'three'; +import type { Vec3 } from './types'; +import { bindTrianglePoint } from './warp-bind'; +import { deformPoint } from './warp-evaluate'; +import { spacingAt, warpEligibleNodes, type WarpSample } from './warp-handles'; +import { isPaintedFace, type WarpModel } from './warp-model'; +import { regionTriangleOf } from './warp-region'; +import type { WarpState } from './warp-solve'; + +/** A spot on a geometry face, as a stroke hit it on the warped surface. */ +export interface WarpStrokePoint { + face: number; + barycentric: Vec3; +} + +/** A line handle's drawn path keeps at most this many points. */ +export const warpPathLimit = 512; +/** A line takes a sample about every this many node spacings along it. */ +export const warpLineStep = 0.5; +/** An area takes at most this many samples, and at least this many where its faces allow. */ +export const warpAreaSamples = { max: 32, min: 4 }; + +/** The barycentric coordinates of a mesh-local point on a face of `positions`, clamped onto it. */ +export function faceBarycentric( + model: WarpModel, + positions: ArrayLike, + face: number, + point: Vec3, +) { + const corner = (c: number) => { + const v = model.index?.[face * 3 + c] ?? face * 3 + c; + return new Vector3(positions[v * 3], positions[v * 3 + 1], positions[v * 3 + 2]); + }; + const weights = new Triangle(corner(0), corner(1), corner(2)) + .getBarycoord(new Vector3(...point), new Vector3()) + ?.toArray() + .map((w) => Math.max(0, w)) ?? [1, 1, 1]; + const sum = weights[0] + weights[1] + weights[2]; + return weights.map((w) => w / sum) as Vec3; +} + +/** A mesh-local point on a face of `positions`. */ +export function facePoint( + model: WarpModel, + positions: ArrayLike, + { face, barycentric }: WarpStrokePoint, + out: Vec3 = [0, 0, 0], +): Vec3 { + out[0] = out[1] = out[2] = 0; + for (let c = 0; c < 3; c++) { + const v = model.index?.[face * 3 + c] ?? face * 3 + c; + for (let a = 0; a < 3; a++) out[a] += barycentric[c] * positions[v * 3 + a]; + } + return out; +} + +/** + * A sample on a painted face, pinned where `state` writes it, as a clicked point is. Null off the + * paint, or where only fixed nodes hold the spot. + */ +export function strokeSample( + model: WarpModel, + state: Pick, + { face, barycentric }: WarpStrokePoint, +): WarpSample | null { + if (!isPaintedFace(model, face)) return null; + const triangle = regionTriangleOf(model.region, face); + const restWorld: Vec3 = [0, 0, 0]; + for (let c = 0; c < 3; c++) { + const v = model.region.triangles[triangle * 3 + c]; + for (let a = 0; a < 3; a++) restWorld[a] += barycentric[c] * model.restWorld[v * 3 + a]; + } + const binding = bindTrianglePoint( + model.region, + model.binding, + model.restWorld, + triangle, + barycentric, + ); + const { fixed } = model.grid; + if (binding.node.every((node) => fixed[node])) return null; + return { + face, + barycentric, + binding, + restWorld, + pin: deformPoint(model, state as WarpState, binding, restWorld), + }; +} + +const distance = (a: ArrayLike, b: ArrayLike) => + Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]); + +/** Mean grid spacing at the free nodes a sample is bound to. */ +export function sampleSpacing(model: WarpModel, sample: Pick) { + const eligible = warpEligibleNodes(model); + const free = sample.binding.node.filter((n) => eligible[n]); + return spacingAt(model, free.length ? free : sample.binding.node); +} + +const nodeKey = (sample: WarpSample) => + [...new Set(sample.binding.node)].sort((a, b) => a - b).join(','); + +/** + * Whether two stroke samples lie on one stretch of surface: the grid joins their nodes by a path + * not much longer than the straight line between them. A pointer that crosses a silhouette onto + * a surface behind it jumps far along the grid for a short way on screen. + */ +export function strokeConnected(model: WarpModel, a: WarpSample, b: WarpSample) { + const shared = new Set(a.binding.node); + if (b.binding.node.some((n) => shared.has(n))) return true; + const jump = distance(a.restWorld, b.restWorld); + const spacing = Math.max(sampleSpacing(model, a), sampleSpacing(model, b)); + const limit = 1.5 * jump + 2.5 * spacing; + const { edgeStart, edges } = model.grid; + const rest = model.restNodes; + const at = (n: number) => [rest[n * 3], rest[n * 3 + 1], rest[n * 3 + 2]]; + const goal = new Map(b.binding.node.map((n) => [n, distance(at(n), b.restWorld)])); + const best = new Map(); + const open: [number, number][] = []; + for (const n of a.binding.node) { + const d = distance(at(n), a.restWorld); + if (d < (best.get(n) ?? Infinity)) { + best.set(n, d); + open.push([d, n]); + } + } + while (open.length) { + let low = 0; + for (let i = 1; i < open.length; i++) if (open[i][0] < open[low][0]) low = i; + const [d, i] = open[low]; + open[low] = open[open.length - 1]; + open.pop(); + if (d > (best.get(i) ?? Infinity) || d > limit) continue; + const end = goal.get(i); + if (end !== undefined && d + end <= limit) return true; + for (let e = edgeStart[i]; e < edgeStart[i + 1]; e++) { + const j = edges[e]; + const next = d + distance(at(i), at(j)); + if (next <= limit && next < (best.get(j) ?? Infinity)) { + best.set(j, next); + open.push([next, j]); + } + } + } + return false; +} + +/** + * A drawn line's samples: its hits taken about every half node spacing along the surface at rest, + * keeping the first and the last, then one sample for each set of grid nodes they are bound to, so + * pointer speed does not change how firmly the line holds. `pin` is where the surface is halfway + * along it. + */ +export function lineSamples( + model: WarpModel, + state: Pick, + points: readonly WarpStrokePoint[], +): { samples: WarpSample[]; pin: Vec3; length: number } | null { + const hits = points.flatMap((point) => strokeSample(model, state, point) ?? []); + if (!hits.length) return null; + const along = [0]; + for (let i = 1; i < hits.length; i++) + along.push(along[i - 1] + distance(hits[i - 1].restWorld, hits[i].restWorld)); + const length = along[along.length - 1]; + const step = (i: number) => warpLineStep * sampleSpacing(model, hits[i]); + const chosen = [0]; + let next = step(0); + for (let i = 1; i < hits.length - 1; i++) { + const last = chosen[chosen.length - 1]; + const target = along[last] + next; + if (along[i] < target) continue; + // The hit nearest the target, which may be the one before. + const pick = i - 1 > last && target - along[i - 1] < along[i] - target ? i - 1 : i; + chosen.push(pick); + next = step(pick); + if (pick < i) i--; + } + const end = hits.length - 1; + if (end > 0) { + if (chosen.length > 1 && along[end] - along[chosen[chosen.length - 1]] < 0.5 * next) + chosen.pop(); + chosen.push(end); + } + // One sample per set of bound nodes, and both ends. + const kept = new Map(); + for (const i of chosen) { + const key = i === 0 || i === end ? `end ${i}` : nodeKey(hits[i]); + if (!kept.has(key)) kept.set(key, i); + } + const order = [...kept.values()].sort((a, b) => a - b); + let middle = 0; + for (let i = 1; i < hits.length; i++) + if (Math.abs(along[i] - length / 2) < Math.abs(along[middle] - length / 2)) middle = i; + return { samples: order.map((i) => hits[i]), pin: hits[middle].pin, length }; +} + +/** At most `limit` points spread evenly along a path, keeping its ends. */ +export function thinPath(points: readonly T[], limit = warpPathLimit): T[] { + if (points.length <= limit) return points.slice(); + return Array.from( + { length: limit }, + (_, i) => points[Math.round((i * (points.length - 1)) / (limit - 1))], + ); +} + +const vertexTriangles = new WeakMap(); + +/** The region triangles around each welded vertex, built once per model. */ +function trianglesAround(model: WarpModel) { + let around = vertexTriangles.get(model); + if (!around) { + const { triangles, weldedCount } = model.region; + const start = new Uint32Array(weldedCount + 1); + for (let i = 0; i < triangles.length; i++) start[triangles[i] + 1]++; + for (let v = 0; v < weldedCount; v++) start[v + 1] += start[v]; + const fill = start.slice(0, weldedCount); + const list = new Uint32Array(triangles.length); + for (let i = 0; i < triangles.length; i++) list[fill[triangles[i]]++] = Math.floor(i / 3); + around = { start, triangles: list }; + vertexTriangles.set(model, around); + } + return around; +} + +const visits = new WeakMap(); + +/** + * The painted faces Warp's brush covers around a hit on the warped surface: those connected to the + * hit face through the source mesh whose warped triangle comes within `radius` of the hit and + * faces the same way, as region painting picks them. `positions` are the warped mesh-local + * positions; distance is measured in world space. + */ +export function areaBrushFaces( + model: WarpModel, + positions: ArrayLike, + hit: WarpStrokePoint, + radius: number, +): number[] { + const seed = regionTriangleOf(model.region, hit.face); + if (seed < 0 || !isPaintedFace(model, hit.face) || !(radius > 0)) return []; + const { region, painted } = model; + const around = trianglesAround(model); + let visit = visits.get(model); + if (!visit) visits.set(model, (visit = { mark: new Uint32Array(region.faces.length), stamp: 0 })); + if (++visit.stamp === 0xffffffff) { + visit.mark.fill(0); + visit.stamp = 1; + } + const { mark, stamp } = visit; + const m = model.matrix; + const world = (face: number, c: number, out: Vector3) => { + const v = model.index?.[face * 3 + c] ?? face * 3 + c; + const x = positions[v * 3], + y = positions[v * 3 + 1], + z = positions[v * 3 + 2]; + return out.set( + m[0] * x + m[4] * y + m[8] * z + m[12], + m[1] * x + m[5] * y + m[9] * z + m[13], + m[2] * x + m[6] * y + m[10] * z + m[14], + ); + }; + const triangle = new Triangle(), + closest = new Vector3(), + normal = new Vector3(); + const load = (t: number) => { + const face = region.faces[t]; + world(face, 0, triangle.a); + world(face, 1, triangle.b); + world(face, 2, triangle.c); + return triangle; + }; + const centre = new Vector3(); + facePoint(model, positions, hit, [0, 0, 0]).forEach((value, a) => centre.setComponent(a, value)); + centre.set( + m[0] * centre.x + m[4] * centre.y + m[8] * centre.z + m[12], + m[1] * centre.x + m[5] * centre.y + m[9] * centre.z + m[13], + m[2] * centre.x + m[6] * centre.y + m[10] * centre.z + m[14], + ); + const facing = load(seed).getNormal(new Vector3()); + const queue = [seed]; + mark[seed] = stamp; + for (let q = 0; q < queue.length; q++) { + const t = queue[q]; + for (let c = 0; c < 3; c++) { + const v = region.triangles[t * 3 + c]; + for (let k = around.start[v]; k < around.start[v + 1]; k++) { + const u = around.triangles[k]; + if (mark[u] === stamp) continue; + mark[u] = stamp; + if (painted && painted[u] !== 1) continue; + load(u); + if (triangle.getArea() < 1e-14) continue; + if (triangle.getNormal(normal).dot(facing) < 0.2) continue; + if ( + triangle.closestPointToPoint(centre, closest).distanceToSquared(centre) > + radius * radius + ) + continue; + queue.push(u); + } + } + } + return queue.map((t) => region.faces[t]).sort((a, b) => a - b); +} + +const cornerWeights: Vec3[] = [ + [0.6, 0.2, 0.2], + [0.2, 0.6, 0.2], + [0.2, 0.2, 0.6], +]; +const third: Vec3 = [1 / 3, 1 / 3, 1 / 3]; + +/** + * An area's samples: face centres spread by farthest-point sampling at rest from the first hit, up + * to a few dozen, about half a node spacing apart. An area of fewer faces than that also takes + * spots toward each face's corners, so even one face holds several samples and lifts as a small + * plateau. `pin` is where the surface is at the face centre nearest the area's centroid. + */ +export function areaSamples( + model: WarpModel, + state: Pick, + faces: readonly number[], + first: WarpStrokePoint, +): { samples: WarpSample[]; pin: Vec3 } | null { + const start = strokeSample(model, state, first); + const painted = faces.filter((face) => isPaintedFace(model, face)); + if (!painted.length) return null; + const rest = (point: WarpStrokePoint) => { + const triangle = regionTriangleOf(model.region, point.face); + const out: Vec3 = [0, 0, 0]; + for (let c = 0; c < 3; c++) { + const v = model.region.triangles[triangle * 3 + c]; + for (let a = 0; a < 3; a++) out[a] += point.barycentric[c] * model.restWorld[v * 3 + a]; + } + return out; + }; + const candidates: WarpStrokePoint[] = painted.map((face) => ({ face, barycentric: third })); + if (painted.length < warpAreaSamples.min) + for (const face of painted) + for (const barycentric of cornerWeights) candidates.push({ face, barycentric }); + const at = candidates.map(rest); + // The area-weighted centroid, for the centre. + const centroid: Vec3 = [0, 0, 0]; + let area = 0; + const triangle = new Triangle(); + for (const face of painted) { + const t = regionTriangleOf(model.region, face); + const corner = (c: number, out: Vector3) => { + const v = model.region.triangles[t * 3 + c]; + return out.set( + model.restWorld[v * 3], + model.restWorld[v * 3 + 1], + model.restWorld[v * 3 + 2], + ); + }; + corner(0, triangle.a); + corner(1, triangle.b); + corner(2, triangle.c); + const weight = triangle.getArea(); + const mid = rest({ face, barycentric: third }); + for (let a = 0; a < 3; a++) centroid[a] += weight * mid[a]; + area += weight; + } + if (area > 0) for (let a = 0; a < 3; a++) centroid[a] /= area; + const spacing = sampleSpacing(model, start ?? strokeSample(model, state, candidates[0])!); + const apart = warpLineStep * spacing; + const near = new Float64Array(candidates.length).fill(Infinity); + const chosen: WarpSample[] = []; + const take = (sample: WarpSample) => { + chosen.push(sample); + for (let i = 0; i < at.length; i++) + near[i] = Math.min(near[i], distance(at[i], sample.restWorld)); + }; + if (start) take(start); + while (chosen.length < warpAreaSamples.max) { + let best = -1; + for (let i = 0; i < near.length; i++) + if (near[i] > 0 && (best < 0 || near[i] > near[best])) best = i; + if (best < 0 || (chosen.length >= warpAreaSamples.min && near[best] < apart)) break; + const sample = strokeSample(model, state, candidates[best]); + if (sample) take(sample); + else near[best] = 0; + } + if (!chosen.length) return null; + let middle = -1; + for (let i = 0; i < candidates.length; i++) + if (middle < 0 || distance(at[i], centroid) < distance(at[middle], centroid)) middle = i; + const pin = strokeSample(model, state, candidates[middle])?.pin ?? chosen[0].pin; + return { samples: chosen, pin }; +} diff --git a/src/hooks/useWorkbench.ts b/src/hooks/useWorkbench.ts index 6345b7b..59de598 100644 --- a/src/hooks/useWorkbench.ts +++ b/src/hooks/useWorkbench.ts @@ -3,6 +3,7 @@ import { joinLiveSession } from '../core/live'; import { committedScene, liveSession, + paintingWarpArea, paintingWarpRegion, useEditor, warpBrushRadius, @@ -180,7 +181,7 @@ export function useKeyboard(openScene: () => void, searchParts: () => void) { return; case 'brushSmaller': case 'brushLarger': { - const warping = paintingWarpRegion(state); + const warping = paintingWarpRegion(state) || paintingWarpArea(state); if (!paintingSurface && !warping) return; event.preventDefault(); const radius = Number( diff --git a/tests/e2e/warp-strokes.spec.ts b/tests/e2e/warp-strokes.spec.ts new file mode 100644 index 0000000..8a975be --- /dev/null +++ b/tests/e2e/warp-strokes.spec.ts @@ -0,0 +1,338 @@ +import { expect, test, type Page } from '@playwright/test'; +import { BoxGeometry } from 'three'; +import { serializeGeometry } from '../../src/core/geometry'; + +// A 20 mm block whose front face, at z = 10 in the world, is painted and warped. +const fixture = { + format: 'kitbasher', + version: 1, + units: 'mm', + name: 'Warp strokes', + joints: [], + parts: [ + { + id: 'block', + name: 'Scanned block', + position: [0, 10, 0], + color: '#d4a272', + geometry: serializeGeometry(new BoxGeometry(20, 20, 20, 40, 40, 40)), + quaternion: [0, 0, 0, 1], + scale: [1, 1, 1], + visible: true, + locked: false, + source: 'test', + }, + ], +}; + +const browserErrors = new WeakMap(); +test.beforeEach(({ page }) => { + const errors: string[] = []; + browserErrors.set(page, errors); + page.on('pageerror', (error) => errors.push(error.message)); + page.on('console', (message) => { + if (message.type() === 'error') errors.push(message.text()); + }); +}); +test.afterEach(async ({ page }) => { + expect(browserErrors.get(page)).toEqual([]); + await expect(page.locator('vite-error-overlay')).toHaveCount(0); +}); + +async function state(page: Page) { + return page.evaluate(async () => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { useEditor } = await import( + urls.find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))! + ); + const fiber = await import(urls.find((url) => url.includes('/@react-three_fiber.js'))!); + const root = fiber._roots.get(document.querySelector('canvas')).store.getState(); + const editor = useEditor.getState(), + warp = editor.warp; + return { + stage: (warp?.stage ?? null) as string | null, + region: (warp?.faces.length ?? 0) as number, + paintHistory: editor.paintHistory.length as number, + handles: (warp?.points ?? []).map((point: any) => ({ + id: point.id as string, + kind: point.kind as string, + samples: point.samples.length as number, + faces: (point.faces?.length ?? 0) as number, + at: (point.target ?? point.pin) as number[], + moved: point.target !== null, + })), + selected: (warp?.selectedPoints ?? []) as string[], + undo: (warp?.undo.length ?? 0) as number, + camera: root.camera.position.toArray() as number[], + controls: root.controls.enabled as boolean, + }; + }); +} + +/** Screen position of a world point. */ +async function screen(page: Page, world: number[]) { + const box = (await page.locator('canvas').boundingBox())!; + const ndc = await page.evaluate(async (world) => { + 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(); + return root.camera.position.clone().fromArray(world).project(root.camera).toArray(); + }, world); + return { x: box.x + ((ndc[0] + 1) * box.width) / 2, y: box.y + ((1 - ndc[1]) * box.height) / 2 }; +} + +/** Screen position of an arrow of the move gizmo on the selected handle. */ +async function moveHandle(page: Page, axis: 'X' | 'Y' | 'Z') { + const box = (await page.locator('canvas').boundingBox())!; + const ndc = await page.evaluate(async (axis) => { + 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(); + let controls: any; + root.scene.traverse((object: any) => { + if (object.isTransformControls && object.visible) controls = object; + }); + const handle = controls.gizmo.picker.translate.children.find((o: any) => o.name === axis); + handle.geometry.computeBoundingBox(); + const point = handle.geometry.boundingBox.getCenter(root.camera.position.clone()); + handle.localToWorld(point); + return point.project(root.camera).toArray(); + }, axis); + return { x: box.x + ((ndc[0] + 1) * box.width) / 2, y: box.y + ((1 - ndc[1]) * box.height) / 2 }; +} + +/** Opens the block, paints most of its front face and lays the grid. */ +async function warpFront(page: Page) { + await page.goto('/'); + await expect(page.locator('canvas')).toBeVisible(); + await page.getByLabel('Open Kitbasher scene').setInputFiles({ + name: 'strokes.kitbash', + mimeType: 'application/json', + buffer: Buffer.from(JSON.stringify(fixture)), + }); + await page.getByRole('button', { name: 'Open scene', exact: true }).click(); + await page.locator('.part-select[title="Scanned block"]').click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.keyboard.press('w'); + const radius = page.getByRole('spinbutton', { name: 'Brush radius', exact: true }); + await radius.fill('8.5'); + await radius.press('Enter'); + const centre = await screen(page, [0, 10, 10]); + await page.mouse.click(centre.x, centre.y); + await page.getByRole('button', { name: 'Lay grid', exact: true }).click(); + await expect(page.getByRole('radio', { name: 'Line', exact: true })).toBeVisible(); +} + +/** Drags with the primary button through world points, in `steps` pointer moves per leg. */ +async function drag(page: Page, through: number[][], steps = 12) { + const spots = await Promise.all(through.map((point) => screen(page, point))); + await page.mouse.move(spots[0].x, spots[0].y); + await page.mouse.down(); + for (const spot of spots.slice(1)) await page.mouse.move(spot.x, spot.y, { steps }); + await page.mouse.up(); +} + +test('a line drawn on the surface makes one handle without moving the camera', async ({ page }) => { + await warpFront(page); + await page.getByRole('radio', { name: 'Line', exact: true }).click(); + await expect(page.locator('.warp-add')).toContainText('Drag on the surface to draw a line.'); + await expect(page.locator('.statusbar')).toContainText('Drag on the surface to draw a line'); + const before = await state(page); + await drag(page, [ + [-5, 8, 10], + [5, 11, 10], + ]); + const drawn = await state(page); + expect(drawn.camera).toEqual(before.camera); + expect(drawn.controls).toBe(true); + expect(drawn.handles).toHaveLength(before.handles.length + 1); + const line = drawn.handles.at(-1)!; + expect(line.kind).toBe('line'); + expect(line.samples).toBeGreaterThan(3); + expect(drawn.selected).toEqual([line.id]); + expect(drawn.undo).toBe(before.undo + 1); + + // A short stroke makes nothing, and the click that ends it adds no point. + const near = await screen(page, [0, 6, 10]); + await page.mouse.move(near.x, near.y); + await page.mouse.down(); + await page.mouse.move(near.x + 2, near.y + 1); + await page.mouse.up(); + const short = await state(page); + expect(short.handles).toHaveLength(drawn.handles.length); + expect(short.selected).toEqual(drawn.selected); + expect(short.undo).toBe(drawn.undo); + + // A click on the surface in Line mode adds nothing either. + await page.mouse.click(near.x, near.y); + expect((await state(page)).handles).toHaveLength(drawn.handles.length); + + // Escape and losing the window discard a stroke in progress. + for (const interrupt of [ + () => page.keyboard.press('Escape'), + () => page.evaluate(() => window.dispatchEvent(new Event('blur'))), + ]) { + const [from, to] = [await screen(page, [-5, 4, 10]), await screen(page, [4, 4, 10])]; + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(to.x, to.y, { steps: 8 }); + await interrupt(); + await page.mouse.up(); + const after = await state(page); + expect(after.handles).toHaveLength(drawn.handles.length); + expect(after.stage).toBe('warp'); + expect(after.controls).toBe(true); + expect(after.camera).toEqual(before.camera); + } +}); + +test('middle drag and Space drag still navigate in Line and Area mode', async ({ page }) => { + await warpFront(page); + for (const mode of ['Line', 'Area']) { + await page.getByRole('radio', { name: mode, exact: true }).click(); + const start = await state(page); + const [from, to] = [await screen(page, [-4, 10, 10]), await screen(page, [4, 12, 10])]; + await page.mouse.move(from.x, from.y); + await page.mouse.down({ button: 'middle' }); + await page.mouse.move(to.x, to.y, { steps: 8 }); + await page.mouse.up({ button: 'middle' }); + const middle = await state(page); + expect(middle.camera).not.toEqual(start.camera); + expect(middle.handles).toHaveLength(start.handles.length); + + await page.keyboard.down('Space'); + await page.mouse.move(to.x, to.y); + await page.mouse.down(); + await page.mouse.move(from.x, from.y, { steps: 8 }); + await page.mouse.up(); + await page.keyboard.up('Space'); + const space = await state(page); + expect(space.camera).not.toEqual(middle.camera); + expect(space.handles).toHaveLength(start.handles.length); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + } +}); + +test('a press on a marker or the gizmo selects or drags it and starts no stroke', async ({ + page, +}) => { + await warpFront(page); + await page.getByRole('radio', { name: 'Line', exact: true }).click(); + await drag(page, [ + [-5, 8, 10], + [5, 8, 10], + ]); + await drag(page, [ + [-5, 13, 10], + [5, 13, 10], + ]); + const two = await state(page); + expect(two.handles).toHaveLength(2); + expect(two.selected).toEqual([two.handles[1].id]); + + // Pressing on the first line's marker and letting go selects it. + const marker = await screen(page, two.handles[0].at); + await page.mouse.move(marker.x, marker.y); + await page.mouse.down(); + await page.mouse.move(marker.x + 3, marker.y + 1, { steps: 2 }); + await page.mouse.up(); + const picked = await state(page); + expect(picked.handles).toHaveLength(2); + expect(picked.selected).toEqual([two.handles[0].id]); + + // Dragging the gizmo moves the handle and draws nothing. + const arrow = await moveHandle(page, 'X'); + await page.mouse.move(arrow.x, arrow.y); + await page.mouse.down(); + await page.mouse.move(arrow.x + 40, arrow.y, { steps: 6 }); + await page.mouse.up(); + const moved = await state(page); + expect(moved.handles).toHaveLength(2); + expect(moved.handles[0].moved).toBe(true); + expect(moved.handles[0].at[0]).toBeGreaterThan(two.handles[0].at[0] + 0.5); + expect(moved.undo).toBe(picked.undo + 1); + expect(moved.controls).toBe(true); +}); + +test('an area stroke leaves the region and its paint history alone', async ({ page }) => { + await warpFront(page); + await page.getByRole('radio', { name: 'Area', exact: true }).click(); + await expect(page.getByRole('spinbutton', { name: 'Brush radius', exact: true })).toBeVisible(); + const before = await state(page); + await drag(page, [ + [-3, 9, 10], + [3, 10, 10], + ]); + const painted = await state(page); + expect(painted.camera).toEqual(before.camera); + expect(painted.handles).toHaveLength(before.handles.length + 1); + const area = painted.handles.at(-1)!; + expect(area.kind).toBe('area'); + expect(area.faces).toBeGreaterThan(10); + expect(area.samples).toBeGreaterThanOrEqual(4); + expect(painted.selected).toEqual([area.id]); + expect(painted.region).toBe(before.region); + expect(painted.paintHistory).toBe(before.paintHistory); + expect(painted.undo).toBe(before.undo + 1); + + // Undo takes the whole area away. + await page.keyboard.press('ControlOrMeta+z'); + expect((await state(page)).handles).toHaveLength(before.handles.length); +}); + +test('the first drag of a new line with the default radius lifts a smooth ridge', async ({ + page, +}) => { + await warpFront(page); + await page.getByRole('radio', { name: 'Line', exact: true }).click(); + await drag(page, [ + [-5, 9, 10], + [5, 11, 10], + ]); + // Seen from the right, the move gizmo's Z arrow lies across the screen. + await page.keyboard.press('3'); + const arrow = await moveHandle(page, 'Z'); + await page.mouse.move(arrow.x, arrow.y); + await page.mouse.down(); + // Towards the front, past the block's face. + const to = await screen(page, [0, 10, 12]); + const from = await screen(page, [0, 10, 10]); + await page.mouse.move(arrow.x + (to.x - from.x), arrow.y, { steps: 10 }); + await page.mouse.up(); + const ridge = await page.evaluate(async () => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { useEditor } = await import( + urls.find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))! + ); + const { facePoint } = await import( + urls.find((url) => /\/src\/core\/warp-strokes\.ts(?:\?.*)?$/.test(url))! + ); + const warp = useEditor.getState().warp; + const line = warp.points.at(-1); + const model = warp.model; + const lift = line.target[2] - line.pin[2]; + // Each drawn spot along the line, as far as the written surface has moved it. + const rises = line.path.map( + (spot: any) => + facePoint(model, warp.output.positions, spot)[2] - + facePoint(model, model.positions, spot)[2], + ); + return { lift, rises, radius: line.radius }; + }); + expect(ridge.radius).toBeGreaterThan(0); + expect(ridge.lift).toBeGreaterThan(1); + // Between the line's ends the ridge stands at the lift, with no peak at any sample. + const inner = ridge.rises.slice( + Math.floor(ridge.rises.length * 0.1), + Math.ceil(ridge.rises.length * 0.9), + ); + for (const rise of inner) expect(Math.abs(rise - ridge.lift)).toBeLessThan(0.1 * ridge.lift); + for (let i = 1; i < inner.length - 1; i++) + expect(inner[i] - Math.min(inner[i - 1], inner[i + 1])).toBeLessThan(0.05 * ridge.lift); +}); diff --git a/tests/unit/warp-handles.test.ts b/tests/unit/warp-handles.test.ts index a808233..8b0ad01 100644 --- a/tests/unit/warp-handles.test.ts +++ b/tests/unit/warp-handles.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'; import { BoxGeometry, BufferGeometry, + Line3, Matrix4, PlaneGeometry, SphereGeometry, @@ -26,9 +27,11 @@ import { reachHandle, reachWeight, snapshotOf, + spacingAt, transferSnapshot, uniqueSamples, bandWidth, + warpFootprintSpacings, warpGuides, warpPathStretch, warpPriorityStrength, @@ -802,6 +805,27 @@ describe('point handles', () => { }); describe('footprints', () => { + /** The free nodes within the footprint's reach of the line through the samples, or of each. */ + function onHandle(model: WarpModel, samples: WarpHandle['samples'], kind: 'line' | 'area') { + const nodes: number[] = []; + const points = samples.map(({ restWorld }) => new Vector3(...restWorld)); + for (let n = 0; n < model.grid.nodes.length; n++) { + if (model.grid.fixed[n]) continue; + const at = new Vector3().fromArray(model.restNodes, n * 3); + const d = Math.min( + ...points.map((p, i) => + kind === 'line' && i > 0 + ? new Line3(points[i - 1], p) + .closestPointToPoint(at, true, new Vector3()) + .distanceTo(at) + : p.distanceTo(at), + ), + ); + if (d <= warpFootprintSpacings * spacingAt(model, [n])) nodes.push(n); + } + return nodes; + } + it('are built by kind and keep reach while the footprint is the same', async () => { const { geometry, model } = await sheet(3, 120); const state = createWarpState(model.restNodes); @@ -817,18 +841,22 @@ describe('footprints', () => { .sort((a, b) => a - b); expect(handleFootprint(model, { kind: 'point', samples }).nodes).toEqual([]); const line = reachHandle(model, { ...point, kind: 'line', samples }); - expect(handleFootprint(model, line).nodes).toEqual(bound); - expect(Array.from(line.reach!.node.subarray(0, line.reach!.own))).toEqual(bound); + const along = onHandle(model, samples, 'line'); + // Nodes beside the line that a binding also reaches are not on it. + expect(bound.filter((n) => !along.includes(n)).length).toBeGreaterThan(0); + expect(handleFootprint(model, line).nodes).toEqual(along); + expect(handleFootprint(model, line).seeds).toEqual(bound); + expect(Array.from(line.reach!.node.subarray(0, line.reach!.own))).toEqual(along); // The same footprint at the same radius keeps its reach; another radius measures it again. expect(reachHandle(model, { ...line, falloff: 0.3 }).reach).toBe(line.reach); const wider = reachHandle(model, { ...line, radius: 5 }); expect(wider.reach).not.toBe(line.reach); - expect(wider.reach!.own).toBe(bound.length); + expect(wider.reach!.own).toBe(along.length); // An area also holds the nodes on its faces. const faces = disc(geometry, 9); const area = reachHandle(model, { ...point, kind: 'area', samples, faces }); - const onFaces = new Set(bound); + const onFaces = new Set(onHandle(model, samples, 'area')); for (const face of faces) { const triangle = readFace(geometry, face); for (const corner of [triangle.a, triangle.b, triangle.c]) { @@ -841,7 +869,7 @@ describe('footprints', () => { } } expect(area.reach!.own).toBe(onFaces.size); - expect(area.reach!.own).toBeGreaterThan(bound.length); + expect(area.reach!.own).toBeGreaterThan(along.length); }); }); diff --git a/tests/unit/warp-session.test.ts b/tests/unit/warp-session.test.ts index bdd0122..958bd26 100644 --- a/tests/unit/warp-session.test.ts +++ b/tests/unit/warp-session.test.ts @@ -5,6 +5,7 @@ import { BufferAttribute, BufferGeometry, DoubleSide, + Line3, PlaneGeometry, Ray, Triangle, @@ -44,6 +45,8 @@ import { handleGuides, reachHandle, snapshotOf, + spacingAt, + warpFootprintSpacings, warpPriorityStrength, type WarpSample, } from '../../src/core/warp-handles'; @@ -2766,12 +2769,28 @@ describe('line and area handles through a session', () => { return handle; } - /** The free nodes the footprint must hold: its samples' and, for an area, those on its faces. */ + /** + * The free nodes the footprint must hold: those within its reach of the line through its samples + * or of an area's samples, and those on an area's faces. + */ function footprintNodes(handle: WarpPoint) { const model = session().model!; const nodes = new Set(); - for (const { binding } of handle.samples) - for (const n of binding.node) if (!model.grid.fixed[n]) nodes.add(n); + const points = handle.samples.map(({ restWorld }) => new Vector3(...restWorld)); + for (let n = 0; n < model.grid.nodes.length; n++) { + if (model.grid.fixed[n]) continue; + const at = new Vector3().fromArray(model.restNodes, n * 3); + const near = points.map((p, i) => + handle.kind === 'line' && i > 0 + ? new Line3(points[i - 1], p).closestPointToPoint(at, true, new Vector3()) + : p, + ); + if ( + Math.min(...near.map((p) => p.distanceTo(at))) <= + warpFootprintSpacings * spacingAt(model, [n]) + ) + nodes.add(n); + } for (const face of handle.faces ?? []) { const triangle = regionTriangleOf(model.region, face); for (let c = 0; c < 3; c++) { @@ -2856,9 +2875,9 @@ describe('line and area handles through a session', () => { const line = handleOf('line', samples); expect(line.samples).toHaveLength(13); const between = Array.from({ length: 12 }, (_, i): [number, number] => [-2.75 + i * 0.5, 0.3]); - // On the evenly spaced grid a radius of 4 pulls a footprint node 0.1 mm under the ridge, and - // the line's end samples ride their nodes' tilted skin maps to 1.971 and 2.056 mm. - await lifecycle(line, between, 0.06); + // At radius 0 the ridge holds within 1.995 and 2.010 mm. A radius of 4 starts its skirt at the + // line, so the line's end samples ride their nodes' tilted skin maps to 1.978 and 2.072 mm. + await lifecycle(line, between, 0.08); }); it('an area moves as one patch, also one smaller than a grid cell', async () => { @@ -2874,7 +2893,8 @@ describe('line and area handles through a session', () => { const area = handleOf('area', samples, faces); expect(area.faces).toEqual(faces); const inside = centres.map((c): [number, number] => [c.x, c.y]); - await lifecycle(area, inside, 0.05); + // A radius of 4 tilts the rim's face centres to 1.927 and 2.037 mm. + await lifecycle(area, inside, 0.08); // One face, smaller than a cell, with a few samples on it. editor().cancelWarp(); diff --git a/tests/unit/warp-strokes.test.ts b/tests/unit/warp-strokes.test.ts new file mode 100644 index 0000000..4029a7f --- /dev/null +++ b/tests/unit/warp-strokes.test.ts @@ -0,0 +1,450 @@ +import { writeFileSync } from 'node:fs'; +import { afterEach, describe, expect, it } from 'vitest'; +import { BufferAttribute, PlaneGeometry, SphereGeometry, Triangle, Vector3 } from 'three'; +import type { BufferGeometry } from 'three'; +import { triangleCount } from '../../src/core/geometry'; +import { finishWarpSettling, useEditor, type WarpPoint } from '../../src/core/store'; +import { readFace } from '../../src/core/surfaces'; +import { defaultWarpDensity } from '../../src/core/warp-grid'; +import { + areaBrushFaces, + facePoint, + lineSamples, + type WarpStrokePoint, +} from '../../src/core/warp-strokes'; +import type { Part, SceneDocument, Vec3 } from '../../src/core/types'; + +function partOf(geometry: BufferGeometry): Part { + const count = geometry.getAttribute('position').count; + geometry.setAttribute('color', new BufferAttribute(new Float32Array(count * 3).fill(0.5), 3)); + return { + id: 'a', + name: 'a', + geometry, + position: [0, 0, 0], + quaternion: [0, 0, 0, 1], + scale: [1, 1, 1], + color: '#aabbcc', + visible: true, + locked: false, + source: 'test', + }; +} + +/** + * A 40 mm plate painted in a 14 mm disc at default density, or a 16 mm ball laid whole on a + * 60-node grid: a painted disc of a fine plate has more border vertices than 60, all fixed. + */ +const surfaces = { + plate: { + label: 'default density', + make: () => partOf(new PlaneGeometry(40, 40, 64, 64)), + density: defaultWarpDensity, + onto: (p: Vec3): Vec3 => [p[0], p[1], 0], + }, + ball: { + label: 'a 60-node grid', + make: () => partOf(new SphereGeometry(16, 48, 32)), + density: 0, + onto: (p: Vec3): Vec3 => { + const length = Math.hypot(...p); + return [(16 * p[0]) / length, (16 * p[1]) / length, (16 * p[2]) / length]; + }, + }, +}; +type Surface = (typeof surfaces)[keyof typeof surfaces]; + +const editor = () => useEditor.getState(); +const session = () => useEditor.getState().warp!; +const initial = useEditor.getState(); +afterEach(() => { + editor().cancelWarp(); + useEditor.setState(initial); +}); + +/** The face nearest a mesh-local point and the point's barycentric coordinates on it. */ +function surfaceAt(part: Part, at: Vec3): WarpStrokePoint { + const triangle = new Triangle(), + point = new Vector3(...at), + closest = new Vector3(); + let face = -1, + nearest = Infinity; + for (let f = 0; f < triangleCount(part.geometry); f++) { + readFace(part.geometry, f, triangle); + const d = triangle.closestPointToPoint(point, closest).distanceToSquared(point); + if (d < nearest) { + nearest = d; + face = f; + } + } + readFace(part.geometry, face, triangle).closestPointToPoint(point, closest); + const barycentric = triangle.getBarycoord(closest, new Vector3())!.toArray() as Vec3; + return { face, barycentric }; +} + +async function lay(surface: Surface) { + const part = surface.make(); + const scene: SceneDocument = { name: 'Warp', parts: [part], joints: [] }; + editor().setScene(scene); + useEditor.setState({ selected: [part.id] }); + editor().setTool('warp'); + editor().setWarpBrushRadius(14); + if (surface.density === 0) editor().setWarpRegion('whole'); + else { + editor().paintWarpRegion( + { partId: part.id, point: [0, 0, 0], normal: [0, 0, 1] }, + surfaceAt(part, [0, 0, 0]).face, + false, + true, + ); + editor().endPaintStroke(); + } + await editor().setWarpDensity(surface.density); + await editor().layWarpGrid(); + expect(session().stage).toBe('warp'); + if (surface.density === 0) expect(session().model!.grid.nodes.length).toBeLessThan(80); + return part; +} + +const lerp = (a: Vec3, b: Vec3, t: number): Vec3 => [ + a[0] + (b[0] - a[0]) * t, + a[1] + (b[1] - a[1]) * t, + a[2] + (b[2] - a[2]) * t, +]; + +/** Hits along a stroke on the surface, every `step` of its chord from `phase` past its start. */ +function stroke(part: Part, surface: Surface, from: Vec3, to: Vec3, step: number, phase = 0) { + const length = Math.hypot(to[0] - from[0], to[1] - from[1], to[2] - from[2]); + const at = (t: number) => surfaceAt(part, surface.onto(lerp(from, to, t / length))); + const points = [at(0)]; + for (let t = phase || step; t < length; t += step) points.push(at(t)); + points.push(at(length)); + return points; +} + +/** How far the written surface has moved a mesh-local spot up, read from the preview itself. */ +function lifted(part: Part, at: Vec3) { + const spot = surfaceAt(part, at); + const model = session().model!; + return ( + facePoint(model, session().output!.positions, spot)[2] - + facePoint(model, model.positions, spot)[2] + ); +} + +const latest = () => session().points.at(-1)!; +function lift(handle: WarpPoint, h: number) { + editor().moveWarpPoints( + [{ id: handle.id, target: [handle.pin[0], handle.pin[1], handle.pin[2] + h] }], + 'end', + ); + finishWarpSettling(); +} + +/** How far each spot every 0.05 mm along the line, between its first and last samples, rose. */ +function profile(part: Part, surface: Surface, handle: WarpPoint) { + const a = handle.samples[0].restWorld, + b = handle.samples.at(-1)!.restWorld; + const count = Math.max(2, Math.round(Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]) / 0.05)); + return Array.from({ length: count + 1 }, (_, i) => + lifted(part, surface.onto(lerp(a, b, i / count))), + ); +} + +/** The most any local maximum stands above the lowest point within `window` probes each side. */ +function worstPeak(zs: number[], window: number) { + let worst = 0; + for (let i = 1; i < zs.length - 1; i++) { + if (!(zs[i] >= zs[i - 1] && zs[i] >= zs[i + 1])) continue; + const left = Math.min(...zs.slice(Math.max(0, i - window), i)); + const right = Math.min(...zs.slice(i + 1, i + 1 + window)); + worst = Math.max(worst, zs[i] - Math.max(left, right)); + } + return worst; +} + +// Measured figures, written where WARP_STROKE_FIGURES says. +const figures: Record = {}; +afterEach(() => { + if (process.env.WARP_STROKE_FIGURES) + writeFileSync(process.env.WARP_STROKE_FIGURES, JSON.stringify(figures, null, 1)); +}); + +const h = 2; +// An 8 mm stroke near the middle of the plate, or across the front of the ball. +const from: Vec3 = [-4, 0.3, 16], + to: Vec3 = [4, 1.1, 16]; + +describe('line handles', () => { + for (const surface of Object.values(surfaces)) + for (const radius of [0, null]) + it(`lift a continuous ridge with no peaks on ${surface.label}, ${radius === 0 ? 'radius 0' : 'default radius'}`, async () => { + const part = await lay(surface); + if (radius !== null) editor().setWarpPointSettings({ radius }, 'end'); + const points = stroke(part, surface, from, to, 0.04); + const steps = session().undo.length; + expect(editor().addWarpStroke({ kind: 'line', points })).toBe(true); + const line = latest(); + expect(line.kind).toBe('line'); + expect(session().selectedPoints).toEqual([line.id]); + expect(session().undo).toHaveLength(steps + 1); + lift(line, h); + const zs = profile(part, surface, line); + const worst = Math.max(...zs.map((z) => Math.abs(z - h))); + const peak = worstPeak(zs, Math.round(line.reach!.spacing / 0.05)); + figures[`line, ${surface.label}, radius ${line.radius}`] = { + samples: line.samples.length, + spacing: line.reach!.spacing, + worst: worst / h, + peak: peak / h, + }; + expect(worst).toBeLessThan(0.1 * h); + expect(peak).toBeLessThan(0.05 * h); + }); + + for (const surface of Object.values(surfaces)) + it(`give the same result for the same stroke drawn slowly or quickly on ${surface.label}`, async () => { + const part = await lay(surface); + const results: number[][] = []; + const counts: number[] = []; + for (const [step, phase] of [ + [0.02, 0], + [0.09, 0.05], + ]) { + editor().addWarpStroke({ + kind: 'line', + points: stroke(part, surface, [-4, -2, 16], [3.5, 2.5, 16], step, phase), + }); + const line = latest(); + counts.push(line.samples.length); + lift(line, h); + const zs: number[] = []; + for (let x = -6; x <= 6; x += 0.5) + for (let y = -4; y <= 4; y += 0.5) zs.push(lifted(part, surface.onto([x, y, 16]))); + results.push(zs); + editor().undoWarpEdit(); + editor().undoWarpEdit(); + } + const difference = Math.max(...results[0].map((z, i) => Math.abs(z - results[1][i]))); + figures[`slow and quick, ${surface.label}`] = { counts, difference: difference / h }; + expect(difference).toBeLessThan(0.02 * h); + }); + + it('take a sample about every half spacing and merge those bound alike, keeping both ends', async () => { + const surface = { ...surfaces.plate, make: () => partOf(new PlaneGeometry(40, 40, 8, 8)) }; + const part = await lay(surface); + const model = session().model!; + // On a coarse mesh, every hit inside one triangle is bound to the same nodes. + const points = stroke(part, surface, [-6, 0.3, 0], [6, 0.3, 0], 0.02); + const made = lineSamples(model, session().state!, points)!; + const inner = made.samples.slice(1, -1); + const keys = inner.map((s) => [...new Set(s.binding.node)].sort().join()); + expect(new Set(keys).size).toBe(keys.length); + expect(made.samples[0].restWorld[0]).toBeCloseTo(-6, 9); + expect(made.samples.at(-1)!.restWorld[0]).toBeCloseTo(6, 9); + figures['coarse mesh line'] = { hits: points.length, samples: made.samples.length }; + }); +}); + +describe('area handles', () => { + async function area(surface: Surface, radius: number, centre: Vec3) { + const part = await lay(surface); + editor().setWarpPointSettings({ radius: 0 }, 'end'); + const first = surfaceAt(part, surface.onto(centre)); + const faces = areaBrushFaces(session().model!, session().output!.positions, first, radius); + expect(editor().addWarpStroke({ kind: 'area', faces, first })).toBe(true); + const handle = latest(); + expect(handle.kind).toBe('area'); + expect(handle.faces).toEqual(faces); + lift(handle, h); + return { part, handle, faces }; + } + + for (const surface of Object.values(surfaces)) { + it(`lift a plateau on ${surface.label}`, async () => { + const { part, handle, faces } = await area(surface, 1.5, [2, -2, 16]); + const zs = faces.map((face) => + lifted(part, readFace(part.geometry, face).getMidpoint(new Vector3()).toArray()), + ); + const worst = Math.max(...zs.map((z) => Math.abs(z - h))); + figures[`area, ${surface.label}`] = { + samples: handle.samples.length, + faces: faces.length, + worst: worst / h, + }; + expect(worst).toBeLessThan(0.1 * h); + }); + + it(`lift an area smaller than a grid cell as a plateau on ${surface.label}`, async () => { + const { part, handle, faces } = await area(surface, 0.02, [2.1, -2.2, 16]); + expect(faces.length).toBeLessThan(4); + expect(handle.samples.length).toBeGreaterThanOrEqual(4); + const spots: Vec3[] = []; + for (const face of faces) { + const t = readFace(part.geometry, face); + for (const w of [ + [0.6, 0.2, 0.2], + [0.2, 0.6, 0.2], + [0.2, 0.2, 0.6], + [1 / 3, 1 / 3, 1 / 3], + ]) + spots.push( + new Vector3() + .addScaledVector(t.a, w[0]) + .addScaledVector(t.b, w[1]) + .addScaledVector(t.c, w[2]) + .toArray(), + ); + } + const worst = Math.max(...spots.map((spot) => Math.abs(lifted(part, spot) - h))); + const largest = Math.max( + ...faces.map((face) => { + const t = readFace(part.geometry, face); + return Math.max(t.a.distanceTo(t.b), t.b.distanceTo(t.c), t.c.distanceTo(t.a)); + }), + ); + expect(largest).toBeLessThan(handle.reach!.spacing); + figures[`small area, ${surface.label}`] = { + samples: handle.samples.length, + faces: faces.length, + spacing: handle.reach!.spacing, + worst: worst / h, + }; + expect(worst).toBeLessThan(0.1 * h); + }); + } + + it('paint connected faces within the radius on the warped surface, and leave the region alone', async () => { + const part = await lay(surfaces.plate); + const first = surfaceAt(part, [0, 0, 0]); + const faces = areaBrushFaces(session().model!, session().output!.positions, first, 1); + expect(faces.length).toBeGreaterThan(4); + for (const face of faces) + expect( + readFace(part.geometry, face).closestPointToPoint(new Vector3(), new Vector3()).length(), + ).toBeLessThanOrEqual(1 + 1e-9); + const { faces: region, seed } = session(); + const history = editor().paintHistory; + expect(editor().addWarpStroke({ kind: 'area', faces, first })).toBe(true); + expect(session().faces).toBe(region); + expect(session().seed).toBe(seed); + expect(editor().paintHistory).toBe(history); + }); + + it('paint only faces turned toward the brush', async () => { + const part = await lay(surfaces.ball); + const first = surfaceAt(part, [0, 0, 16]); + // The whole ball is within 40 mm of the hit; only the cap facing it is painted. + const faces = areaBrushFaces(session().model!, session().output!.positions, first, 40); + expect(faces.length).toBeGreaterThan(100); + for (const face of faces) + expect(readFace(part.geometry, face).getMidpoint(new Vector3()).z).toBeGreaterThan(0); + }); +}); + +describe('handles made by strokes through a session', () => { + for (const kind of ['line', 'area'] as const) + it(`keep a ${kind} whole through edits, a re-lay, undo, a live refusal and Apply`, async () => { + const part = await lay(surfaces.plate); + const surface = surfaces.plate; + if (kind === 'line') + editor().addWarpStroke({ + kind, + points: stroke(part, surface, [-3, -1, 0], [3, 1.5, 0], 0.03), + }); + else { + const first = surfaceAt(part, [1, -1, 0]); + editor().addWarpStroke({ + kind, + faces: areaBrushFaces(session().model!, session().output!.positions, first, 1.5), + first, + }); + } + const made = latest(); + const id = made.id; + const current = () => session().points.find((point) => point.id === id)!; + /** The handle is there, with its faces, and its footprint measured on the current grid. */ + const whole = () => { + const handle = current(); + expect(handle.kind).toBe(kind); + expect(handle.faces).toEqual(made.faces); + expect(handle.path).toEqual(made.path); + expect(handle.samples.length).toBeGreaterThan(1); + expect(handle.reach!.grid).toBe(session().model!.grid); + expect(handle.reach!.own).toBeGreaterThan(2); + }; + /** The handle's spots stand at its lift. */ + const holds = (h: number) => { + finishWarpSettling(); + const handle = current(); + for (const { face, barycentric } of handle.samples) { + const model = session().model!; + const rise = + facePoint(model, session().output!.positions, { face, barycentric })[2] - + facePoint(model, model.positions, { face, barycentric })[2]; + expect(Math.abs(rise - h)).toBeLessThan(0.1 * Math.max(h, 1)); + } + }; + whole(); + const steps: number[] = [session().undo.length]; + lift(current(), h); + steps.push(session().undo.length); + whole(); + holds(h); + editor().selectWarpPoints([id]); + editor().setWarpPointSettings({ radius: 4 }, 'end'); + editor().setWarpPointSettings({ falloff: 0.3 }, 'end'); + steps.push(session().undo.length); + expect(current()).toMatchObject({ radius: 4, falloff: 0.3 }); + whole(); + holds(h); + await editor().setWarpDensity(defaultWarpDensity + 1); + whole(); + holds(h); + // Edit region, paint more, and lay the grid again. + editor().setWarpRegion('painted'); + editor().paintWarpRegion( + { partId: part.id, point: [10, 0, 0], normal: [0, 0, 1] }, + surfaceAt(part, [10, 0, 0]).face, + false, + true, + ); + editor().endPaintStroke(); + await editor().layWarpGrid(); + expect(session().stage).toBe('warp'); + whole(); + holds(h); + // Undo steps back through the falloff, the radius and the move, keeping the handle. + await editor().undoWarpEdit(); + // The density step was recorded on the region before the re-lay and has nothing to restore. + if (current().falloff !== 1) await editor().undoWarpEdit(); + expect(current().falloff).toBe(1); + expect(current().radius).toBe(4); + await editor().undoWarpEdit(); + expect(current().radius).toBe(made.radius); + whole(); + holds(h); + await editor().undoWarpEdit(); + expect(current().target).toBeNull(); + whole(); + lift(current(), h); + // A refused live Apply reopens the session with the handle as it was. + useEditor.setState({ liveStatus: 'connected' }); + const confirmed = editor().scene; + const shown = Array.from(session().preview!.getAttribute('position').array); + expect(editor().applyWarp()).toBe(true); + expect(Array.from(editor().scene.parts[0].geometry.getAttribute('position').array)).toEqual( + shown, + ); + editor().receiveScene(confirmed); + useEditor.setState({ tool: 'select' }); + editor().settleWarp(false); + whole(); + expect(current().target).not.toBeNull(); + holds(h); + useEditor.setState({ liveStatus: 'disconnected' }); + expect(editor().applyWarp()).toBe(true); + // Apply starts again on the result. + expect(session().points.some((point) => point.id === id)).toBe(false); + }); +}); From 77e93d4b5391f438a55b880fd15407fc0b650a6b Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Wed, 18 Nov 2026 17:42:51 -0800 Subject: [PATCH 19/25] Make region re-lays undoable and fix warp stroke edge cases --- .../specs/2026-11-17-warp-handles-design.md | 64 ++- src/components/WarpControls.tsx | 24 +- src/components/WarpStroke.tsx | 146 ++++-- src/core/store.ts | 256 ++++++++-- src/core/warp-strokes.ts | 224 +++++++- tests/e2e/warp-strokes.spec.ts | 483 ++++++++++++++++-- tests/unit/warp-session.test.ts | 204 +++++++- tests/unit/warp-strokes.test.ts | 289 ++++++++++- 8 files changed, 1526 insertions(+), 164 deletions(-) diff --git a/docs/superpowers/specs/2026-11-17-warp-handles-design.md b/docs/superpowers/specs/2026-11-17-warp-handles-design.md index 0ff31c1..0faa4f4 100644 --- a/docs/superpowers/specs/2026-11-17-warp-handles-design.md +++ b/docs/superpowers/specs/2026-11-17-warp-handles-design.md @@ -180,6 +180,14 @@ from where it is written before closing. Points on other pieces, on the far side of a thin wall, or that the seam would not move stay. Points the user placed or moved are kept. +Close gap's targets yield to the samples of stationary points, lines and areas the user placed: +it withholds the targets on each sample's nodes and those beside them, settles a trial from the +surface as shown, and for each sample the trial moves by more than 0.005 mm, the pin-hold rule's +limit, withholds the next ring of grid edges around it, up to twelve rounds. The seam readout then +reports the gap left there, and the panel says that Close gap leaves the seam open around points +the user placed. On two plates 1 mm apart, laid whole (2,129 nodes), a held point moved 0.00007 mm +and a held line's samples at most 0.0027 mm, where the seam had moved them 0.78 and 0.72 mm. + ### 4. Radius and falloff Every handle has a **radius** in mm and a **falloff** from 0 to 100 %, edited in the Control @@ -212,7 +220,10 @@ Radius adds soft per-node **guides** around them. reached its target by overdriving the few free nodes it had: on a scan a 1 mm pull beside the fixed edge moved a node 4.5 mm and turned node maps inside out. Handles on free surface with no such pin beside them are left alone. The panel states a moved handle's shortfall from its - target, and an unmoved one's drift from its pin, once either exceeds 0.02 mm. + target, and an unmoved one's drift from its pin, once either exceeds 0.02 mm, with its cause in + one sentence: a point the user placed beside it, the fixed edge (with the remedy: feather the + edge, or grab farther inside the paint), Close gap's targets beside it, or a point on the same + spot; a drift names Close gap or a moved point, whichever the grid reaches first from the pin. - **Settling.** The end of an edit settles for up to 50 iterations. A solve whose last iteration still moved a node by 1 µm or more is marked settling and goes on in idle steps of 8 ms, redrawing every 200 ms and counting folds on each redraw, until it converges (or 20,000 @@ -220,7 +231,8 @@ Radius adds soft per-node **guides** around them. surface exactly as shown, settling on from there if it was. Apply bakes the preview as shown, and only a settled one: pressed while settling, the button shows it is applying and the settle finishes in the same idle steps, so input goes on, then bakes. Any edit before then (another - drag, undo, a density change, Edit region), Cancel or leaving the tool drops the waiting Apply. + drag, undo, a density change, Edit region), a stroke starting, Cancel or leaving the tool drops + the waiting Apply. Apply and Cancel let go of the session the idle steps were settling. An edit that changes nothing settles nothing. @@ -307,7 +319,8 @@ surface makes, and says so in a line: stroke. **Input.** A stroke is a draft owned by one pointer (`WarpStroke.tsx`). It starts only on an -unmodified primary press on a painted face of the warped part, when no camera navigation (middle +unmodified primary press on a painted face of the warped part, where no other part is nearer the eye +at the press, when no camera navigation (middle and right buttons, Space, the orbit and pan tools), pivot picking, free transform or exploded view is in force; a point marker stops the press before it reaches the surface. The camera's controls are switched off for that press, so a stroke never orbits, and a primary drag that begins off the @@ -315,7 +328,8 @@ region still does. A gizmo handle hears the press after the surface does, so the or the release after a gizmo press discards the draft. The pointer's path is sampled every 2 screen pixels, whatever the pointer's speed, by a raycast on the warped preview that another part in front blocks. Release commits once; Escape, pointer cancel, lost pointer capture, window blur, camera -navigation starting and the session changing discard. The click that ends a stroke adds no point +navigation starting, another Add mode being chosen and the session changing discard. A stroke that +starts drops an Apply waiting for the surface to settle. The click that ends a stroke adds no point and changes no selection, also when a line is rejected; in Line and Area mode a click adds nothing. A line shorter than 4 px makes nothing; an area from a press alone is the one dab. @@ -345,15 +359,24 @@ its default radius from the spacing at its samples' nodes. It is drawn as its line on the written surface, or its faces hatched in diagonal stripes of the handle colour and a dark tone with their outline, and one marker at the centre. Lines are a dark -5 px casing under a 2.5 px core in the point markers' colours (selected and idle), drawn 4 px -nearer the eye so a line's width does not sink into a surface sloping across it; the stripes leave -the surface showing between them. Shapes are built when a handle's path or faces change; a solve +5 px casing under a 2.5 px core in the point markers' colours (selected and idle). Each corner of a +line's width lies where its view ray meets the surface's tangent plane at the line, as the grid's +do, so the width does not sink into a surface sloping across it, then nearer by a pixel or 0.05 mm, +whichever is less, measured across the surface (up to twice that along the ray where the surface +turns away). A surface 0.2 mm or more in front, or the other side of a 0.2 mm wall, hides it. The +stripes leave the surface showing between them. Shapes are built when a handle's path or faces change; a solve only rewrites their positions, read from the preview. While drawing, the line so far or the faces painted so far are drawn the same way on the warped surface, appended in place. **Samples.** A line's hits are taken about every half local node spacing along the surface at rest, keeping the first and the last, then one sample is kept for each set of grid nodes the inner ones are bound to, so pointer speed does not change stiffness; both ends are always kept. +Where the surface between two kept samples stands off their chord by more than 3.5 % of it, the hit +farthest from the chord is kept too and both halves are looked at again, so a line over tight +curvature keeps samples along it even when it is about one node spacing long or shorter. On a +32 mm open half-pipe of radius 0.9 mm laid whole at the coarsest density (spacing 4.3 mm), a +±25° line around it kept 5 samples instead of 2 and, lifted 0.5 mm, stands between 0.497 and +0.503 mm, where two samples left it between −0.88 and 0.73 mm. An area takes up to 32 face centres spread by farthest-point sampling at rest from the first hit, at least 4 and about half a node spacing apart; an area of fewer than 4 faces also offers a spot toward each corner of each face, so even one face has several samples and lifts a small plateau @@ -392,8 +415,11 @@ Each session undo step holds the points, gap targets, the settled grid they held settings new points take, so undo restores the surface exactly without solving. Laying the same region at the same density and feather keeps the model. A real rebuild carries each distinct snapshot to the new grid once, writing each new node where the preview's own skinning -wrote its scan vertex, and rebinds samples, dropping those bound exactly as another and an area's -faces no longer painted. A vertex in the old feather band that the new region paints is carried +wrote its scan vertex, and rebinds samples, dropping those bound exactly as another. A line keeps +its longest unbroken run of painted samples and its drawn path between them; an area keeps its +largest connected piece of painted faces and the samples on it. Either is centred again on what is +left, its target moved by as much as its centre; a line left with fewer than two samples, or an area +with none, is dropped with the notice that points were removed. A vertex in the old feather band that the new region paints is carried at the position it was written at; where a feather still applies, it stays unblended so the blend applies once. @@ -403,15 +429,17 @@ too coarse for the points on this region. Laying a new region is not made either leave a moved handle bound only to fixed nodes; a handle the repaint leaves outside the paint is dropped with a notice, and so is an unmoved one left on the new region's edge. -A density change is one session undo step. The steps before it stay on the grid they were -recorded on: their snapshots name a stand-in for it, their points let go of their reach and of -binding arrays the solver caches against the old grid, and the step the change records keeps the -region, density and feather that grid was laid from, with a hash of the model built. Undoing it -rebuilds that grid (the build is deterministic, one build's time), checks the hash, puts every -step recorded on it back on the rebuilt grid and restores the surface exactly; undoing further -restores each earlier step exactly. A rebuild that hashed differently would settle those steps -again from rest and say so. Laying a new region still carries every step to the new grid and -settles undo across it from there. +A density change is one session undo step, and so is laying the grid on a changed region. The +steps before it stay on the grid they were recorded on: their snapshots name a stand-in for it, +their points let go of their reach and of binding arrays the solver caches against the old grid, +and the step the change records keeps the region as painted, the density and feather that grid was +laid from, with a hash of the model built. Undoing it rebuilds that grid (the build is +deterministic, one build's time), checks the hash, puts every step recorded on it back on the +rebuilt grid and restores the region, the handles and the surface exactly; undoing further restores +each earlier step exactly, and undoing an earlier layout step rebuilds the grid it names in turn. +Steps recorded on still earlier grids keep their own stand-ins and grid steps untouched. A rebuild +that hashed differently would settle those steps again from rest and say so. Only the current +handles are carried to a new grid. A pure module, `warp-handles.ts`, turns handles and a model into solver input: reach, weights, guides, snapshots and their transfer, and distribution. It is unit-tested without the store. diff --git a/src/components/WarpControls.tsx b/src/components/WarpControls.tsx index c0ffb36..60dc5bd 100644 --- a/src/components/WarpControls.tsx +++ b/src/components/WarpControls.tsx @@ -14,8 +14,10 @@ import { warpChanges, warpDistributeCounts, warpPinDrift, + warpPinDriftCause, warpPointRadius, warpShortfall, + warpShortfallCause, warpShortfallShown, warpWholePart, type WarpSession, @@ -87,6 +89,13 @@ function usePointSettingsGesture() { const isSlider = (target: EventTarget) => target instanceof HTMLInputElement && target.type === 'range'; +const shortfallCauses = { + pin: 'A point you placed beside it holds it back.', + edge: 'The fixed edge of the region holds it back, so feather the edge or grab farther inside the paint.', + gap: 'Close gap holds the surface beside it.', + spot: 'A point on the same spot holds it back.', +} as const; + /** Radius, falloff and Distribute points, for the selected points or for new ones. */ function PointSettingsControls({ warp, part }: { warp: WarpSession; part: Part | undefined }) { const gesture = usePointSettingsGesture(); @@ -185,16 +194,18 @@ function PointSettingsControls({ warp, part }: { warp: WarpSession; part: Part |

) : null} {drift > warpShortfallShown ? (

) : null}
@@ -555,6 +566,11 @@ export function WarpControls() {
) : null} + {seam && seam.largestGap > 0 && warp.gapHeld ? ( +

+ Close gap leaves the seam open around points you placed, so they keep their place. +

+ ) : null}
{folds ? (

diff --git a/src/components/WarpStroke.tsx b/src/components/WarpStroke.tsx index 2502483..90add44 100644 --- a/src/components/WarpStroke.tsx +++ b/src/components/WarpStroke.tsx @@ -7,12 +7,13 @@ import { Color, DoubleSide, Group, + InstancedInterleavedBuffer, + InterleavedBufferAttribute, Mesh, MeshBasicMaterial, Raycaster, Vector2, Vector3, - type InstancedInterleavedBuffer, type Intersection, } from 'three'; import { LineMaterial } from 'three/addons/lines/LineMaterial.js'; @@ -50,30 +51,69 @@ const shortStroke = 4; /** Area dabs are this share of the brush radius apart along the stroke. */ const dabSpacing = 0.25; /** - * How far a line is drawn toward the eye, in pixels. Its width is screen-aligned at one depth, so - * without this half of it would sink into a surface sloping across it. + * How far a line stands off the surface toward the eye: pixels, and at most mm, measured across the + * surface and so up to twice as far along a ray where it turns away. Each corner of its width lies + * on the surface's tangent plane at the line, so the width does not sink into a surface sloping + * across it, and a surface 0.2 mm or more in front, or the other side of a 0.2 mm wall, hides it. */ -const lineLift = 4; +const lineLift = 1; +const lineLiftMax = 0.05; -/** A line material whose segments sit `lineLift` pixels nearer the eye than their points. */ +const glsl = (value: number) => (Number.isInteger(value) ? `${value}.0` : `${value}`); + +/** A line material whose corners lie on the surface's tangent plane, lifted a little toward the eye. */ function liftedLine(color: string, width: number) { const material = new LineMaterial({ color, linewidth: width }); material.onBeforeCompile = (shader) => { - shader.vertexShader = shader.vertexShader.replace( - 'vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );', - `vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 ); - { - bool eye = projectionMatrix[ 2 ][ 3 ] == - 1.0; - float pixel = 2.0 / ( projectionMatrix[ 1 ][ 1 ] * resolution.y ); - if ( eye ) { - start.xyz -= normalize( start.xyz ) * ${lineLift.toFixed(1)} * pixel * - start.z; - end.xyz -= normalize( end.xyz ) * ${lineLift.toFixed(1)} * pixel * - end.z; - } else { - start.z += ${lineLift.toFixed(1)} * pixel; - end.z += ${lineLift.toFixed(1)} * pixel; - } - }`, - ); + shader.vertexShader = shader.vertexShader + .replace( + 'attribute vec3 instanceEnd;', + `attribute vec3 instanceEnd; + attribute vec3 instanceNormalStart; + attribute vec3 instanceNormalEnd;`, + ) + .replace( + 'gl_Position = clip;', + `gl_Position = clip; + { + vec3 centre = position.y < 0.5 ? start.xyz : end.xyz; + vec3 normal = normalMatrix * ( position.y < 0.5 ? instanceNormalStart : instanceNormalEnd ); + vec2 ndc = clip.xy / clip.w; + float depth = perspective ? - centre.z : 1.0; + float pixel = 2.0 * depth / ( projectionMatrix[ 1 ][ 1 ] * resolution.y ); + float limit = 8.0 * ( 0.5 * linewidth + 1.0 ) * pixel; + // Along the view ray, so where the surface turns away the line stands as far off it. + float facing = dot( normal, normal ) > 1e-24 + ? abs( dot( normalize( normal ), perspective ? normalize( - centre ) : vec3( 0.0, 0.0, 1.0 ) ) ) + : 1.0; + float lift = min( ${glsl(lineLift)} * pixel, ${glsl(lineLiftMax)} ) / max( facing, 0.5 ); + float facingLimit = 1e-6 * length( normal ); + vec3 corner; + if ( perspective ) { + vec3 ray = vec3( + ( ndc.x + projectionMatrix[ 2 ][ 0 ] ) / projectionMatrix[ 0 ][ 0 ], + ( ndc.y + projectionMatrix[ 2 ][ 1 ] ) / projectionMatrix[ 1 ][ 1 ], + - 1.0 ); + float toward = dot( normal, ray ); + float t = abs( toward ) > facingLimit * length( ray ) ? dot( normal, centre ) / toward : depth; + t = clamp( t, depth - limit, depth + 16.0 * limit ); + corner = ray * t; + float near = projectionMatrix[ 3 ][ 2 ] / ( projectionMatrix[ 2 ][ 2 ] - 1.0 ); + corner -= normalize( corner ) * min( lift, max( 0.0, 0.5 * ( t - near ) ) * length( corner ) / t ); + } else { + vec2 xy = vec2( + ( ndc.x - projectionMatrix[ 3 ][ 0 ] ) / projectionMatrix[ 0 ][ 0 ], + ( ndc.y - projectionMatrix[ 3 ][ 1 ] ) / projectionMatrix[ 1 ][ 1 ] ); + float z = abs( normal.z ) > facingLimit + ? centre.z - dot( normal.xy, xy - centre.xy ) / normal.z + : centre.z; + z = clamp( z, centre.z - 16.0 * limit, centre.z + limit ); + float near = ( projectionMatrix[ 3 ][ 2 ] + 1.0 ) / projectionMatrix[ 2 ][ 2 ]; + corner = vec3( xy, z + min( lift, max( 0.0, 0.5 * ( - near - z ) ) ) ); + } + gl_Position = projectionMatrix * vec4( corner, 1.0 ); + }`, + ); }; return material; } @@ -87,6 +127,8 @@ class SurfaceSegments { readonly core: LineSegments2; readonly casing: LineSegments2; private array = new Float32Array(0); + /** Each segment's surface normal at its start and end, mesh-local, beside `array`. */ + normals = new Float32Array(0); count = 0; constructor(color: string) { this.casing = new LineSegments2(this.geometry, liftedLine(casingColor, 5)); @@ -105,22 +147,31 @@ class SurfaceSegments { setColor(color: string) { (this.core.material as LineMaterial).color.set(color); } - /** Room for `segments`, keeping those written. */ + /** Room for `segments`, keeping those written; their normals go in `normals`. */ reserve(segments: number) { if (segments * 6 <= this.array.length) return this.array; - const array = new Float32Array(Math.max(segments, 2 * (this.array.length / 6), 16) * 6); + const length = Math.max(segments, 2 * (this.array.length / 6), 16) * 6; + const array = new Float32Array(length), + normals = new Float32Array(length); array.set(this.array); + normals.set(this.normals); this.array = array; + this.normals = normals; this.geometry.setPositions(array); + const buffer = new InstancedInterleavedBuffer(normals, 6, 1); + this.geometry.setAttribute('instanceNormalStart', new InterleavedBufferAttribute(buffer, 3, 0)); + this.geometry.setAttribute('instanceNormalEnd', new InterleavedBufferAttribute(buffer, 3, 3)); return array; } /** Shows the first `count` segments written. */ show(count: number) { this.count = count; this.geometry.instanceCount = count; - const start = this.geometry.getAttribute('instanceStart') as unknown as - { data: InstancedInterleavedBuffer } | undefined; - if (start) start.data.needsUpdate = true; + for (const name of ['instanceStart', 'instanceNormalStart']) { + const attribute = this.geometry.getAttribute(name) as unknown as + { data: InstancedInterleavedBuffer } | undefined; + if (attribute) attribute.data.needsUpdate = true; + } this.casing.visible = this.core.visible = count > 0; } dispose() { @@ -187,6 +238,29 @@ class StripedFaces { } } +/** Writes a face's normal on `positions`, mesh-local and unnormalised, at `offset`. */ +function writeNormal( + model: WarpModel, + positions: ArrayLike, + face: number, + out: Float32Array, + offset: number, +) { + const v = (c: number) => (model.index?.[face * 3 + c] ?? face * 3 + c) * 3; + const a = v(0), + b = v(1), + c = v(2); + const ux = positions[b] - positions[a], + uy = positions[b + 1] - positions[a + 1], + uz = positions[b + 2] - positions[a + 2], + wx = positions[c] - positions[a], + wy = positions[c + 1] - positions[a + 1], + wz = positions[c + 2] - positions[a + 2]; + out[offset] = uy * wz - uz * wy; + out[offset + 1] = uz * wx - ux * wz; + out[offset + 2] = ux * wy - uy * wx; +} + /** Writes a face's three warped corners, mesh-local, at `offset`. */ function writeFace( model: WarpModel, @@ -271,7 +345,11 @@ export function WarpStrokeController({ pressed }: { pressed: () => boolean }) { const output = () => useEditor.getState().warp?.output?.positions; /** The spot under a client position on the warped part, or null off it or behind another. */ - const hitAt = (d: Draft, x: number, y: number): WarpStrokePoint | null => { + const hitAt = ( + d: Pick, + x: number, + y: number, + ): WarpStrokePoint | null => { const own = partMeshes.get(d.partId); const positions = output(); if (!own || !positions) return null; @@ -307,6 +385,8 @@ export function WarpStrokeController({ pressed }: { pressed: () => boolean }) { facePoint(d.model, positions, run.points[i], b); array.set(a, s * 6); array.set(b, s * 6 + 3); + writeNormal(d.model, positions, run.points[i - 1].face, view.line.normals, s * 6); + writeNormal(d.model, positions, run.points[i].face, view.line.normals, s * 6 + 3); } d.drawn = segments; view.line.show(segments); @@ -480,12 +560,12 @@ export function WarpStrokeController({ pressed }: { pressed: () => boolean }) { pressed() ) return false; + // A press on another part in front reaches this one too; it starts nothing. + const first = hitAt({ partId, model }, event.nativeEvent.clientX, event.nativeEvent.clientY); + if (!first || !isPaintedFace(model, first.face)) return false; const mesh = event.object as Mesh; - const local = mesh.worldToLocal(event.point.clone()).toArray() as Vec3; - const first = { - face, - barycentric: faceBarycentric(model, warp.output.positions, face, local), - }; + // A stroke takes the press, so an Apply waiting for the surface to settle no longer bakes. + if (warp.applying) useEditor.setState({ warp: { ...warp, applying: false } }); // The camera's controls see this press after it; a stroke owns it instead. const controls = get().controls as { enabled: boolean } | null; const owned = controls?.enabled ? controls : null; @@ -531,6 +611,7 @@ export function WarpStrokeController({ pressed }: { pressed: () => boolean }) { if ( draft === d && (!strokingWarp(s) || + (s.warpAdd === 'area' ? 'area' : 'line') !== d.kind || s.warp?.model !== d.model || s.temporaryOrbit || !!s.navigationMode || @@ -642,6 +723,7 @@ function HandleShape({ ends[i * 3] = positions[v * 3]; ends[i * 3 + 1] = positions[v * 3 + 1]; ends[i * 3 + 2] = positions[v * 3 + 2]; + writeNormal(model, positions, Math.floor(corner / 3), line.normals, i * 3); } line.show(segments); } else if (path && path.length > 1) { @@ -652,6 +734,8 @@ function HandleShape({ facePoint(model, positions, path[i], b); ends.set(a, (i - 1) * 6); ends.set(b, (i - 1) * 6 + 3); + writeNormal(model, positions, path[i - 1].face, line.normals, (i - 1) * 6); + writeNormal(model, positions, path[i].face, line.normals, (i - 1) * 6 + 3); a[0] = b[0]; a[1] = b[1]; a[2] = b[2]; diff --git a/src/core/store.ts b/src/core/store.ts index 6d8c82e..a3dbb64 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -110,6 +110,7 @@ import { untouchedAuto, warpEligibleNodes, warpGuides, + warpPinHold, warpPriorityStrength, writtenCentre, type WarpHandle, @@ -118,7 +119,13 @@ import { } from './warp-handles'; import { buildWarpModelJob } from './warp-job'; import { isPaintedFace, type WarpModel, type WarpModelInput } from './warp-model'; -import { areaSamples, lineSamples, thinPath, type WarpStrokePoint } from './warp-strokes'; +import { + areaSamples, + lineSamples, + survivingStroke, + thinPath, + type WarpStrokePoint, +} from './warp-strokes'; import { closeGapTargets, measureSeam, @@ -258,6 +265,8 @@ export interface WarpSession { points: WarpPoint[]; selectedPoints: string[]; gapTargets: { node: number; target: Vec3 }[]; + /** How many targets the last Close gap withheld because points the user placed hold the surface. */ + gapHeld?: number; snap: boolean; overlap: number; gizmo: WarpGizmo; @@ -285,21 +294,24 @@ export interface WarpSession { */ type WarpEdit = Pick< WarpSession, - 'points' | 'gapTargets' | 'surface' | 'pointRadius' | 'pointFalloff' + 'points' | 'gapTargets' | 'gapHeld' | 'surface' | 'pointRadius' | 'pointFalloff' > & { - /** On the step a density change records: the grid it undoes to, rebuilt when it is undone. */ + /** On the step a new grid records: the grid it undoes to, rebuilt when it is undone. */ grid?: WarpGridStep; }; -type WarpLaid = { faces: number[] | null; density: number; feather: number }; +type WarpLaid = { + faces: number[] | null; + density: number; + feather: number; + /** The region as painted when the grid was laid, which undoing a later grid paints again. */ + painted: Pick; +}; /** - * The grid a density change left. Its steps' snapshots name `token` instead of the grid, so the old - * model can be let go; undoing rebuilds it from `laid` and puts them back on it. + * The grid a density change or a new region left. Its steps' snapshots name `token` instead of the + * grid, so the old model can be let go; undoing rebuilds it from `laid` and puts them back on it. */ interface WarpGridStep { laid: WarpLaid; - region: WarpSession['region']; - faces: number[]; - seed: WarpSession['seed']; densityChosen: boolean; token: WarpGrid; /** Of the old model, to tell that the rebuild is the same grid. */ @@ -769,7 +781,9 @@ function warpBinding(model: WarpModel, triangle: number, barycentric: Vec3) { * bound to is fixed, so it could not move the surface. Null when it stays. */ function droppedBy(model: WarpModel, handle: WarpPoint): 'unpainted' | 'fixed' | null { - const painted = handle.samples.filter(({ face }) => isPaintedFace(model, face)); + const left = survivingStroke(model, handle); + if (!left) return 'unpainted'; + const painted = left.samples.filter(({ face }) => isPaintedFace(model, face)); if (!painted.length) return 'unpainted'; const { fixed } = model.grid; return painted.every(({ face, barycentric }) => @@ -782,13 +796,16 @@ function droppedBy(model: WarpModel, handle: WarpPoint): 'unpainted' | 'fixed' | } /** - * Binds a handle to a new model, dropping samples and an area's faces that are no longer painted - * in its region, and samples the new grid binds exactly as another. Null when no sample is left, - * or when every node the samples are bound to is fixed, so it could not move the surface. + * Binds a handle to a new model, keeping what is left of a line or an area on its paint, and + * dropping samples the new grid binds exactly as another. Null when no sample is left, when too + * little of a line is, or when every node the samples are bound to is fixed, so it could not move + * the surface. */ function rebindHandle(model: WarpModel, handle: WarpPoint): WarpPoint | null { + const left = survivingStroke(model, handle); + if (!left) return null; const samples = uniqueSamples( - handle.samples.flatMap((sample) => { + left.samples.flatMap((sample) => { const triangle = isPaintedFace(model, sample.face) ? regionTriangleOf(model.region, sample.face) : -1; @@ -799,8 +816,8 @@ function rebindHandle(model: WarpModel, handle: WarpPoint): WarpPoint | null { ); const { fixed } = model.grid; if (samples.every(({ binding }) => binding.node.every((node) => fixed[node]))) return null; - const faces = handle.faces?.filter((face) => isPaintedFace(model, face)); - return reachHandle(model, { ...handle, samples, ...(faces ? { faces } : {}), reach: null }); + const faces = left.faces?.filter((face) => isPaintedFace(model, face)); + return reachHandle(model, { ...left, samples, ...(faces ? { faces } : {}), reach: null }); } /** The session's settled grid as a snapshot, or the grid as shown while it is still settling. */ @@ -850,6 +867,7 @@ export const isWarpDragging = () => const warpEdit = (warp: WarpSession): WarpEdit => ({ points: warp.points, gapTargets: warp.gapTargets, + gapHeld: warp.gapHeld ?? 0, surface: warp.model && warp.state ? settledOf(warp) : warp.surface, pointRadius: warp.pointRadius, pointFalloff: warp.pointFalloff, @@ -914,6 +932,97 @@ export function warpPinDrift(warp: WarpSession) { return worst; } +/** The nodes a handle's samples are bound to and those beside them. */ +function nodesAround(model: WarpModel, handle: WarpPoint) { + const { edgeStart, edges } = model.grid; + const near = new Set(); + for (const { binding } of handle.samples) + for (const n of binding.node) { + near.add(n); + for (let e = edgeStart[n]; e < edgeStart[n + 1]; e++) near.add(edges[e]); + } + return near; +} + +/** + * What holds back the selected moved handle that stops farthest short: a stationary point the user + * placed on or beside its nodes, the fixed edge its samples are partly bound to, or Close gap's + * targets beside it. Null when none of these is there. + */ +export function warpShortfallCause(warp: WarpSession): 'pin' | 'edge' | 'gap' | null { + const { model, state } = warp; + if (!model || !state) return null; + let worst: WarpPoint | null = null, + far = 0; + for (const point of warp.points) + if (point.target && warp.selectedPoints.includes(point.id)) { + const at = writtenCentre(model, state, point); + const d = Math.hypot(...at.map((value, a) => value - point.target![a])); + if (d > far) [worst, far] = [point, d]; + } + if (!worst) return null; + const near = nodesAround(model, worst); + const { fixed } = model.grid; + if ( + warp.points.some( + (point) => + point.target === null && + !point.auto && + point.samples.some(({ binding }) => binding.node.some((n) => near.has(n))), + ) + ) + return 'pin'; + // A binding's fixed corners carry the rest of its weight. + const free = (binding: WarpPoint['samples'][number]['binding']) => + binding.node.reduce((sum, n, k) => sum + (fixed[n] ? 0 : binding.weight[k]), 0); + if (worst.samples.some(({ binding }) => free(binding) < 1 - 1e-9)) return 'edge'; + if (warp.gapTargets.some(({ node }) => near.has(node))) return 'gap'; + return null; +} + +/** + * What moves the selected stationary point that has drifted farthest from its pin: Close gap's + * targets or a moved handle, whichever the grid reaches first from its nodes. + */ +export function warpPinDriftCause(warp: WarpSession): 'gap' | 'moved' { + const { model, state } = warp; + if (!model || !state || !warp.gapTargets.length) return 'moved'; + let worst: WarpPoint | null = null, + far = 0; + for (const point of warp.points) + if (point.target === null && !point.auto && warp.selectedPoints.includes(point.id)) { + const at = writtenCentre(model, state, point); + const d = Math.hypot(...at.map((value, a) => value - point.pin[a])); + if (d > far) [worst, far] = [point, d]; + } + if (!worst) return 'moved'; + const gap = new Set(warp.gapTargets.map(({ node }) => node)); + const moved = new Set(); + for (const point of warp.points) + if (point.target !== null) + for (const { binding } of point.samples) for (const n of binding.node) moved.add(n); + const { edgeStart, edges } = model.grid; + const seen = new Set(); + const queue: number[] = []; + for (const { binding } of worst.samples) + for (const n of binding.node) + if (!seen.has(n)) { + seen.add(n); + queue.push(n); + } + for (let q = 0; q < queue.length; q++) { + const n = queue[q]; + if (moved.has(n)) return 'moved'; + if (gap.has(n)) return 'gap'; + for (let e = edgeStart[n]; e < edgeStart[n + 1]; e++) + if (!seen.has(edges[e])) { + seen.add(edges[e]); + queue.push(edges[e]); + } + } + return 'moved'; +} + /** Whether Apply would change the mesh. */ export const warpChanges = (warp: WarpSession) => warp.gapTargets.length > 0 || warp.points.some(holdsWarp); @@ -1361,6 +1470,79 @@ const gapAwayCosine = 0.25; // holds the seam open. const gapHoldShare = 0.05; +// Close gap settles a trial this many times at most, each time withholding more of its targets +// around the samples the user holds that it still moves. +const gapYieldRounds = 12; +// A trial settles until an iteration moves no node by more than this, or for this many iterations. +const gapTrialMove = 1e-5; +const gapTrialIterations = 4000; + +/** + * The gap targets without those that would move a sample of a stationary handle the user placed: + * around each such sample, targets within a ring of grid edges are withheld, and the ring grows + * until a settled trial keeps it within `warpPinHold` of where it is written now. Returns the + * targets kept, how many were withheld, and the settled trial to start the solve from. + */ +function yieldingGapTargets( + warp: WarpSession, + points: WarpPoint[], + gapTargets: { node: number; target: Vec3 }[], +) { + const model = warp.model!, + state = warp.state!; + const samples = points.flatMap((point) => + point.target === null && !point.auto ? point.samples : [], + ); + if (!samples.length || !gapTargets.length) return { gapTargets, held: 0, trial: null }; + const { edgeStart, edges, fixed } = model.grid; + const count = model.grid.nodes.length; + // Grid edges from each sample's nodes, out as far as any ring could grow. + const hops = samples.map(({ binding }) => { + const hop = new Uint16Array(count).fill(0xffff); + const queue: number[] = []; + for (const n of binding.node) + if (!fixed[n] && hop[n]) { + hop[n] = 0; + queue.push(n); + } + for (let q = 0; q < queue.length; q++) { + const i = queue[q]; + if (hop[i] >= gapYieldRounds + 1) continue; + for (let e = edgeStart[i]; e < edgeStart[i + 1]; e++) + if (hop[edges[e]] === 0xffff) { + hop[edges[e]] = hop[i] + 1; + queue.push(edges[e]); + } + } + return hop; + }); + const now = samples.map(({ binding, restWorld }) => + deformPoint(model, state, binding, restWorld), + ); + // A sample's own nodes and those beside them carry its skin map, so they are never pulled. + const ring = samples.map(() => 1); + const trial = { positions: state.positions.slice(), rotations: state.rotations.slice() }; + let kept = gapTargets; + for (let round = 0; round < gapYieldRounds; round++) { + kept = gapTargets.filter(({ node }) => hops.every((hop, s) => hop[node] > ring[s])); + const { guides, constraints } = warpSolveInput({ model, points, gapTargets: kept }); + if (constraints.length) + for (let i = 0; i < gapTrialIterations; i++) + if (solveWarp(model.grid, model.restNodes, constraints, trial, 1, guides) < gapTrialMove) + break; + let moved = false; + samples.forEach(({ binding, restWorld }, s) => { + const at = deformPoint(model, trial, binding, restWorld); + if (Math.hypot(...at.map((value, a) => value - now[s][a])) > warpPinHold) { + ring[s]++; + moved = true; + } + }); + if (!moved) break; + } + return { gapTargets: kept, held: gapTargets.length - kept.length, trial }; +} + const distanceTo = (positions: Float64Array, node: number, target: Vec3) => Math.hypot( positions[node * 3] - target[0], @@ -2340,7 +2522,9 @@ export const useEditor = create((set, get) => ({ state.notify( stroke.kind === 'line' ? 'Draw a longer line on the painted area.' - : 'Paint on the painted area.', + : stroke.faces.some((face) => isPaintedFace(model, face)) + ? 'This spot is fixed. Paint farther inside the warp region.' + : 'Paint on the painted area.', 'info', ); return false; @@ -2630,16 +2814,20 @@ export const useEditor = create((set, get) => ({ released.add(point.id); } const points = warp.points.filter((point) => !released.has(point.id)); - if (same(gapTargets, warp.gapTargets) && points.length === warp.points.length) return; + // Samples the user holds still keep their place: the seam stays open around them. + const yielded = yieldingGapTargets(warp, points, gapTargets); + if (same(yielded.gapTargets, warp.gapTargets) && points.length === warp.points.length) return; const kept = new Set(points.map((point) => point.id)); set({ warp: solveWarpSession( state.scene, { ...warp, + ...(yielded.trial ? { state: yielded.trial } : {}), points, selectedPoints: warp.selectedPoints.filter((id) => kept.has(id)), - gapTargets, + gapTargets: yielded.gapTargets, + gapHeld: yielded.held, undo: withUndo(warp), }, 'end', @@ -3843,9 +4031,10 @@ function moveSteps(steps: WarpEdit[], from: WarpGrid, to: WarpGrid, model?: Warp /** * Lays the session's grid. A build that stops returns the session to `from`. Laying from the region * stage takes the page's feather option; a rebuild keeps the feather the session was laid with. A - * density change is one session undo step, and undoing it, given its grid step, rebuilds the grid - * it left and restores that step on it exactly. A density change that would drop a handle, or a new - * region that would leave a moved one on its fixed edge rather than outside the paint, is not made. + * density change or a new region is one session undo step, and undoing it, given its grid step, + * rebuilds the grid it left and restores that step on it exactly. A density change that would drop + * a handle, or a new region that would leave a moved one on its fixed edge rather than outside the + * paint, is not made. */ async function layWarp(from: WarpSettled, kind: 'region' | 'density' | WarpGridStep) { const state = useEditor.getState(), @@ -3876,7 +4065,12 @@ async function layWarp(from: WarpSettled, kind: 'region' | 'density' | WarpGridS : faces ? defaultWarpDensity : warpWholeDensity; - const laid: WarpLaid = { faces, density, feather }; + const laid: WarpLaid = restore?.laid ?? { + faces, + density, + feather, + painted: { region: warp.region, faces: warp.faces, seed: warp.seed }, + }; // The same region at the same density keeps its grid, so nothing moves. if (!restore && warp.model && warp.laid && sameLaid(warp.laid, laid)) { if (warp.settling) scheduleWarpSettle(); @@ -3947,6 +4141,7 @@ async function layWarp(from: WarpSettled, kind: 'region' | 'density' | WarpGridS return handle ? [{ ...handle, baseline: rest }] : []; }), gapTargets: [], + gapHeld: 0, surface: rest, }, ); @@ -3955,9 +4150,7 @@ async function layWarp(from: WarpSettled, kind: 'region' | 'density' | WarpGridS const next: WarpSession = { ...current, stage: 'warp', - region: restore.region, - faces: restore.faces, - seed: restore.seed, + ...restore.laid.painted, density, densityChosen: restore.densityChosen, feather, @@ -4024,10 +4217,10 @@ async function layWarp(from: WarpSettled, kind: 'region' | 'density' | WarpGridS const points = rebind(current.points); const kept = new Set(points.map((point) => point.id)); const start = current.surface ? carry(current.surface) : null; - // A density change is a step of its own. The steps before it stay on the grid they were - // recorded on, which undoing it rebuilds. + // A density change or a new region is a step of its own. The steps before it stay on the grid + // they were recorded on, which undoing it rebuilds. let undo: WarpEdit[]; - if (kind === 'density' && old && current.laid) { + if (old && current.laid) { const token = detachedGrid(); const [step, ...earlier] = moveSteps( [warpEdit(current), ...current.undo.slice(-(warpUndoLimit - 1))], @@ -4040,9 +4233,6 @@ async function layWarp(from: WarpSettled, kind: 'region' | 'density' | WarpGridS ...step, grid: { laid: current.laid, - region: current.region, - faces: current.faces, - seed: current.seed, densityChosen: from.densityChosen, token, fingerprint: warpFingerprint(old), @@ -4057,6 +4247,7 @@ async function layWarp(from: WarpSettled, kind: 'region' | 'density' | WarpGridS ...step, points: rebind(step.points), gapTargets: [], + gapHeld: 0, surface: step.surface && carry(step.surface), }; }); @@ -4079,6 +4270,7 @@ async function layWarp(from: WarpSettled, kind: 'region' | 'density' | WarpGridS points, selectedPoints: current.selectedPoints.filter((id) => kept.has(id)), gapTargets: [], + gapHeld: 0, firstLay: false, folds: new Uint32Array(0), seam: null, diff --git a/src/core/warp-strokes.ts b/src/core/warp-strokes.ts index e73b2a8..d8a3d83 100644 --- a/src/core/warp-strokes.ts +++ b/src/core/warp-strokes.ts @@ -2,7 +2,7 @@ import { Triangle, Vector3 } from 'three'; import type { Vec3 } from './types'; import { bindTrianglePoint } from './warp-bind'; import { deformPoint } from './warp-evaluate'; -import { spacingAt, warpEligibleNodes, type WarpSample } from './warp-handles'; +import { spacingAt, warpEligibleNodes, type WarpHandle, type WarpSample } from './warp-handles'; import { isPaintedFace, type WarpModel } from './warp-model'; import { regionTriangleOf } from './warp-region'; import type { WarpState } from './warp-solve'; @@ -188,13 +188,66 @@ export function lineSamples( const key = i === 0 || i === end ? `end ${i}` : nodeKey(hits[i]); if (!kept.has(key)) kept.set(key, i); } - const order = [...kept.values()].sort((a, b) => a - b); + const order = followSurface( + hits, + [...kept.values()].sort((a, b) => a - b), + ); let middle = 0; for (let i = 1; i < hits.length; i++) if (Math.abs(along[i] - length / 2) < Math.abs(along[middle] - length / 2)) middle = i; return { samples: order.map((i) => hits[i]), pin: hits[middle].pin, length }; } +/** + * How far the surface a line is drawn on may stand off the chord between two of its samples, as a + * share of the chord, before a hit between them is kept too. + */ +export const warpLineBend = 0.035; + +/** Distance from a point to the segment from `a` to `b`. */ +function segmentDistance(p: Vec3, a: Vec3, b: Vec3) { + const u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + const length = u[0] * u[0] + u[1] * u[1] + u[2] * u[2]; + const t = + length > 0 + ? Math.max( + 0, + Math.min( + 1, + ((p[0] - a[0]) * u[0] + (p[1] - a[1]) * u[1] + (p[2] - a[2]) * u[2]) / length, + ), + ) + : 0; + return Math.hypot(p[0] - a[0] - t * u[0], p[1] - a[1] - t * u[1], p[2] - a[2] - t * u[2]); +} + +/** + * The kept hits, with more wherever the surface between two of them stands off their chord by more + * than `warpLineBend` of it: the hit farthest from the chord is kept, and both halves are looked at + * again. On tight curvature even a line about one node spacing long keeps samples along it. + */ +function followSurface(hits: readonly WarpSample[], order: number[]) { + const kept: number[] = [order[0]]; + const split = (a: number, b: number) => { + const chord = distance(hits[a].restWorld, hits[b].restWorld); + let far = -1, + most = warpLineBend * chord; + for (let i = a + 1; i < b; i++) { + const d = segmentDistance(hits[i].restWorld, hits[a].restWorld, hits[b].restWorld); + if (d > most) [far, most] = [i, d]; + } + if (far < 0) return; + split(a, far); + kept.push(far); + split(far, b); + }; + for (let k = 1; k < order.length; k++) { + split(order[k - 1], order[k]); + kept.push(order[k]); + } + return kept; +} + /** At most `limit` points spread evenly along a path, keeping its ends. */ export function thinPath(points: readonly T[], limit = warpPathLimit): T[] { if (points.length <= limit) return points.slice(); @@ -315,7 +368,8 @@ const third: Vec3 = [1 / 3, 1 / 3, 1 / 3]; * An area's samples: face centres spread by farthest-point sampling at rest from the first hit, up * to a few dozen, about half a node spacing apart. An area of fewer faces than that also takes * spots toward each face's corners, so even one face holds several samples and lifts as a small - * plateau. `pin` is where the surface is at the face centre nearest the area's centroid. + * plateau. `pin` is where the surface is at the face centre nearest the area's centroid. Null when + * no spot on the faces is painted and free. */ export function areaSamples( model: WarpModel, @@ -363,8 +417,12 @@ export function areaSamples( area += weight; } if (area > 0) for (let a = 0; a < 3; a++) centroid[a] /= area; - const spacing = sampleSpacing(model, start ?? strokeSample(model, state, candidates[0])!); - const apart = warpLineStep * spacing; + // Spaced by the grid at the first spot that can hold; none can where fixed nodes alone bind it. + let spaced = start; + for (let i = 0; !spaced && i < candidates.length; i++) + spaced = strokeSample(model, state, candidates[i]); + if (!spaced) return null; + const apart = warpLineStep * sampleSpacing(model, spaced); const near = new Float64Array(candidates.length).fill(Infinity); const chosen: WarpSample[] = []; const take = (sample: WarpSample) => { @@ -389,3 +447,159 @@ export function areaSamples( const pin = strokeSample(model, state, candidates[middle])?.pin ?? chosen[0].pin; return { samples: chosen, pin }; } + +/** A spot's mesh-local rest position carried to world space. */ +function restWorldOf(model: WarpModel, point: WarpStrokePoint): Vec3 { + const [x, y, z] = facePoint(model, model.positions, point); + const m = model.matrix; + return [ + m[0] * x + m[4] * y + m[8] * z + m[12], + m[1] * x + m[5] * y + m[9] * z + m[13], + m[2] * x + m[6] * y + m[10] * z + m[14], + ]; +} + +/** The handle centred on `pin`, its target moved with its centre. */ +function recentred(handle: WarpHandle, pin: Vec3) { + const target = handle.target; + return { + pin, + target: target && ([0, 1, 2].map((a) => target[a] + pin[a] - handle.pin[a]) as Vec3), + }; +} + +/** + * What is left of a line or an area on a model's paint: a line's longest unbroken run of painted + * samples, with its drawn path between them, or an area's largest connected piece of painted + * faces, with the samples on it. Each is centred again on what is left, its target moved by as + * much as its centre. The handle itself when nothing was lost, and null when a line keeps fewer + * than two samples or an area none. + */ +export function survivingStroke(model: WarpModel, handle: WarpHandle): WarpHandle | null { + if (handle.kind === 'line') return survivingLine(model, handle); + if (handle.kind === 'area') return survivingArea(model, handle); + return handle; +} + +function survivingLine(model: WarpModel, handle: WarpHandle): WarpHandle | null { + const { samples } = handle; + const path = handle.path ?? []; + const painted = path.map(({ face }) => isPaintedFace(model, face)); + if (samples.every(({ face }) => isPaintedFace(model, face)) && painted.every(Boolean)) + return handle; + // Where along the drawn path each sample lies; both are in stroke order. + const at = path.map((point) => restWorldOf(model, point)); + let from = 0; + const index = samples.map(({ restWorld }) => { + let best = from; + for (let i = from + 1; i < at.length; i++) + if (distance(at[i], restWorld) < distance(at[best], restWorld)) best = i; + return (from = best); + }); + // Unbroken runs of painted samples joined by painted path. + const runs: number[][] = [[]]; + samples.forEach(({ face }, s) => { + const run = runs[runs.length - 1]; + if (!isPaintedFace(model, face) || (path.length && !painted[index[s]])) { + if (run.length) runs.push([]); + } else if ( + run.length && + path.length && + !painted.slice(index[run[run.length - 1]], index[s] + 1).every(Boolean) + ) + runs.push([s]); + else run.push(s); + }); + const lengthOf = (run: number[]) => { + let length = 0; + for (let k = 1; k < run.length; k++) + length += distance(samples[run[k - 1]].restWorld, samples[run[k]].restWorld); + return length; + }; + let longest: number[] = []; + for (const run of runs) if (run.length > 1 && lengthOf(run) > lengthOf(longest)) longest = run; + if (longest.length < 2) return null; + const kept = longest.map((s) => samples[s]); + // The surface halfway along what is left. + const half = lengthOf(longest) / 2; + let pin: Vec3 = kept[0].pin; + for (let k = 1, along = 0; k < kept.length; k++) { + const step = distance(kept[k - 1].restWorld, kept[k].restWorld); + if (along + step >= half) { + const t = step > 0 ? (half - along) / step : 0; + pin = [0, 1, 2].map( + (a) => kept[k - 1].pin[a] + t * (kept[k].pin[a] - kept[k - 1].pin[a]), + ) as Vec3; + break; + } + along += step; + } + return { + ...handle, + samples: kept, + ...(path.length ? { path: path.slice(index[longest[0]], index[longest.at(-1)!] + 1) } : {}), + ...recentred(handle, pin), + }; +} + +function survivingArea(model: WarpModel, handle: WarpHandle): WarpHandle | null { + const faces = handle.faces ?? []; + const { samples } = handle; + const left = faces.filter((face) => isPaintedFace(model, face)); + if (left.length === faces.length && samples.every(({ face }) => isPaintedFace(model, face))) + return handle; + // Pieces of what is left that share an edge, by area at rest. + const { region, restWorld } = model; + const { weldedCount } = region; + const parent = left.map((_, i) => i); + const root = (i: number): number => (parent[i] === i ? i : (parent[i] = root(parent[i]))); + const edges = new Map(); + left.forEach((face, i) => { + const t = regionTriangleOf(region, face); + for (let c = 0; c < 3; c++) { + const v = region.triangles[t * 3 + c], + w = region.triangles[t * 3 + ((c + 1) % 3)]; + const key = v < w ? v * weldedCount + w : w * weldedCount + v; + const other = edges.get(key); + if (other === undefined) edges.set(key, i); + else parent[root(i)] = root(other); + } + }); + const triangle = new Triangle(); + const corner = (t: number, c: number, out: Vector3) => { + const v = region.triangles[t * 3 + c]; + return out.set(restWorld[v * 3], restWorld[v * 3 + 1], restWorld[v * 3 + 2]); + }; + const area = new Map(), + centroid = new Map(); + left.forEach((face, i) => { + const t = regionTriangleOf(region, face); + corner(t, 0, triangle.a); + corner(t, 1, triangle.b); + corner(t, 2, triangle.c); + const weight = triangle.getArea(); + const mid = triangle.getMidpoint(new Vector3()); + const r = root(i); + area.set(r, (area.get(r) ?? 0) + weight); + const sum = centroid.get(r) ?? [0, 0, 0]; + sum[0] += weight * mid.x; + sum[1] += weight * mid.y; + sum[2] += weight * mid.z; + centroid.set(r, sum); + }); + let largest = -1; + for (const [r, a] of area) if (largest < 0 || a > area.get(largest)!) largest = r; + const piece = new Set(left.filter((_, i) => root(i) === largest)); + const kept = samples.filter(({ face }) => piece.has(face)); + if (!kept.length) return null; + const mean = centroid.get(largest)!.map((value) => value / (area.get(largest) || 1)); + let middle = kept[0]; + for (const sample of kept) + if (distance(sample.restWorld, mean) < distance(middle.restWorld, mean)) middle = sample; + return { + ...handle, + samples: kept, + faces: faces.filter((face) => piece.has(face)), + ...recentred(handle, middle.pin), + }; +} diff --git a/tests/e2e/warp-strokes.spec.ts b/tests/e2e/warp-strokes.spec.ts index 8a975be..bdb1abc 100644 --- a/tests/e2e/warp-strokes.spec.ts +++ b/tests/e2e/warp-strokes.spec.ts @@ -1,29 +1,37 @@ import { expect, test, type Page } from '@playwright/test'; -import { BoxGeometry } from 'three'; +import { BoxGeometry, type BufferGeometry } from 'three'; import { serializeGeometry } from '../../src/core/geometry'; -// A 20 mm block whose front face, at z = 10 in the world, is painted and warped. -const fixture = { +const part = ( + id: string, + name: string, + geometry: BufferGeometry, + position: number[], + color = '#d4a272', +) => ({ + id, + name, + position, + color, + geometry: serializeGeometry(geometry), + quaternion: [0, 0, 0, 1], + scale: [1, 1, 1], + visible: true, + locked: false, + source: 'test', +}); +const sceneOf = (parts: ReturnType[]) => ({ format: 'kitbasher', version: 1, units: 'mm', name: 'Warp strokes', joints: [], - parts: [ - { - id: 'block', - name: 'Scanned block', - position: [0, 10, 0], - color: '#d4a272', - geometry: serializeGeometry(new BoxGeometry(20, 20, 20, 40, 40, 40)), - quaternion: [0, 0, 0, 1], - scale: [1, 1, 1], - visible: true, - locked: false, - source: 'test', - }, - ], -}; + parts, +}); + +// A 20 mm block whose front face, at z = 10 in the world, is painted and warped. +const block = part('block', 'Scanned block', new BoxGeometry(20, 20, 20, 40, 40, 40), [0, 10, 0]); +const fixture = sceneOf([block]); const browserErrors = new WeakMap(); test.beforeEach(({ page }) => { @@ -105,29 +113,74 @@ async function moveHandle(page: Page, axis: 'X' | 'Y' | 'Z') { return { x: box.x + ((ndc[0] + 1) * box.width) / 2, y: box.y + ((1 - ndc[1]) * box.height) / 2 }; } -/** Opens the block, paints most of its front face and lays the grid. */ -async function warpFront(page: Page) { +/** + * Opens a scene, by default the block, paints most of the front of the named part around a world + * point and lays the grid. + */ +async function warpFront( + page: Page, + scene: object = fixture, + name = 'Scanned block', + at = [0, 10, 10], +) { await page.goto('/'); await expect(page.locator('canvas')).toBeVisible(); await page.getByLabel('Open Kitbasher scene').setInputFiles({ name: 'strokes.kitbash', mimeType: 'application/json', - buffer: Buffer.from(JSON.stringify(fixture)), + buffer: Buffer.from(JSON.stringify(scene)), }); await page.getByRole('button', { name: 'Open scene', exact: true }).click(); - await page.locator('.part-select[title="Scanned block"]').click(); + await page.locator(`.part-select[title="${name}"]`).click(); await page.keyboard.press('1'); await page.keyboard.press('Home'); await page.keyboard.press('w'); const radius = page.getByRole('spinbutton', { name: 'Brush radius', exact: true }); await radius.fill('8.5'); await radius.press('Enter'); - const centre = await screen(page, [0, 10, 10]); + const centre = await screen(page, at); await page.mouse.click(centre.x, centre.y); await page.getByRole('button', { name: 'Lay grid', exact: true }).click(); await expect(page.getByRole('radio', { name: 'Line', exact: true })).toBeVisible(); } +/** + * The world depth of the named part's written surface under a screen position, or null where the + * pointer misses it or another part is in front. + */ +async function surfaceDepth(page: Page, spot: { x: number; y: number }, partId: string) { + const box = (await page.locator('canvas').boundingBox())!; + const ndc = [((spot.x - box.x) / box.width) * 2 - 1, 1 - ((spot.y - box.y) / box.height) * 2]; + return page.evaluate( + async ({ ndc, partId }) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { useEditor } = await import( + urls.find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))! + ); + const root = ( + await import(urls.find((url) => url.includes('/@react-three_fiber.js'))!) + )._roots + .get(document.querySelector('canvas')) + .store.getState(); + const { partMeshes } = await import( + urls.find((url) => /\/src\/xr\/part-meshes\.ts(?:\?.*)?$/.test(url))! + ); + const warp = useEditor.getState().warp; + root.raycaster.setFromCamera({ x: ndc[0], y: ndc[1] }, root.camera); + let nearest: any = null; + for (const mesh of partMeshes.values()) { + const hit = root.raycaster.intersectObject(mesh, false)[0]; + if (hit && (!nearest || hit.distance < nearest.distance)) nearest = hit; + } + const own = partMeshes.get(partId); + return nearest && nearest.object === own && own.geometry === warp.preview + ? (nearest.point.z as number) + : null; + }, + { ndc, partId }, + ); +} + /** Drags with the primary button through world points, in `steps` pointer moves per leg. */ async function drag(page: Page, through: number[][], steps = 12) { const spots = await Promise.all(through.map((point) => screen(page, point))); @@ -137,6 +190,18 @@ async function drag(page: Page, through: number[][], steps = 12) { await page.mouse.up(); } +/** Runs a function of the editor store in the page, given `args`. */ +async function inStore(page: Page, body: string, args: unknown = null): Promise { + return page.evaluate( + async ({ body, args }) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const store = await import(urls.find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))!); + return new Function('store', 'args', body)(store, args); + }, + { body, args }, + ); +} + test('a line drawn on the surface makes one handle without moving the camera', async ({ page }) => { await warpFront(page); await page.getByRole('radio', { name: 'Line', exact: true }).click(); @@ -305,34 +370,352 @@ test('the first drag of a new line with the default radius lifts a smooth ridge' const from = await screen(page, [0, 10, 10]); await page.mouse.move(arrow.x + (to.x - from.x), arrow.y, { steps: 10 }); await page.mouse.up(); - const ridge = await page.evaluate(async () => { - const urls = performance.getEntriesByType('resource').map((entry) => entry.name); - const { useEditor } = await import( - urls.find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))! - ); - const { facePoint } = await import( - urls.find((url) => /\/src\/core\/warp-strokes\.ts(?:\?.*)?$/.test(url))! + await inStore(page, 'store.finishWarpSettling();'); + const lift = await inStore( + page, + 'const line = store.useEditor.getState().warp.points.at(-1); return line.target[2] - line.pin[2];', + ); + const radius = await inStore( + page, + 'return store.useEditor.getState().warp.points.at(-1).radius;', + ); + // Seen from the front again, each spot the pointer passed over is picked on screen and the + // written surface found under it: the line's own record of itself plays no part. + await page.keyboard.press('1'); + const rises: (number | null)[] = []; + for (let i = 0; i <= 40; i++) { + const t = i / 40; + const spot = await screen(page, [-5 + 10 * t, 9 + 2 * t, 10]); + rises.push(await surfaceDepth(page, spot, 'block')); + } + expect(radius).toBeGreaterThan(0); + expect(lift).toBeGreaterThan(1); + const found = rises.flatMap((z) => (z === null ? [] : [z - 10])); + expect(found.length).toBeGreaterThanOrEqual(38); + // Both ends, and every spot between them, stand at the lift with no peak anywhere. + expect(rises[0]).not.toBeNull(); + expect(rises.at(-1)).not.toBeNull(); + for (const rise of found) expect(Math.abs(rise - lift)).toBeLessThan(0.1 * lift); + for (let i = 1; i < found.length - 1; i++) + expect(found[i] - Math.min(found[i - 1], found[i + 1])).toBeLessThan(0.05 * lift); +}); + +test('a press on a part in front makes no handle on the part behind', async ({ page }) => { + // An opaque cover 4 mm in front of the left of the block's painted face. + const cover = part('cover', 'Cover', new BoxGeometry(8, 20, 1), [-6, 10, 14], '#3a4a5a'); + await warpFront(page, sceneOf([block, cover])); + const before = await state(page); + await page.getByRole('radio', { name: 'Area', exact: true }).click(); + const onCover = await screen(page, [-6, 10, 14.5]); + await page.mouse.click(onCover.x, onCover.y); + expect((await state(page)).handles).toHaveLength(before.handles.length); + + // A line pressed on the cover is no stroke, even once it comes out over the painted face. + await page.getByRole('radio', { name: 'Line', exact: true }).click(); + const out = await screen(page, [5, 10, 10]); + await page.mouse.move(onCover.x, onCover.y); + await page.mouse.down(); + await page.mouse.move(onCover.x + 4, onCover.y, { steps: 2 }); + expect((await state(page)).controls).toBe(true); + await page.mouse.move(out.x, out.y, { steps: 12 }); + expect((await state(page)).controls).toBe(true); + await page.mouse.up(); + const after = await state(page); + expect(after.handles).toHaveLength(before.handles.length); + expect(after.undo).toBe(before.undo); + + // Beside the cover a press still draws. + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await drag(page, [ + [1, 8, 10], + [7, 12, 10], + ]); + expect((await state(page)).handles).toHaveLength(before.handles.length + 1); +}); + +test('switching between Line and Area during a press discards the stroke', async ({ page }) => { + await warpFront(page); + for (const [from, to] of [ + ['line', 'area'], + ['area', 'line'], + ] as const) { + await inStore(page, 'store.useEditor.getState().setWarpAdd(args);', from); + const before = await state(page); + const [a, b] = [await screen(page, [-5, 8, 10]), await screen(page, [5, 11, 10])]; + await page.mouse.move(a.x, a.y); + await page.mouse.down(); + await page.mouse.move((a.x + b.x) / 2, (a.y + b.y) / 2, { steps: 6 }); + await inStore(page, 'store.useEditor.getState().setWarpAdd(args);', to); + await page.mouse.move(b.x, b.y, { steps: 6 }); + await page.mouse.up(); + const after = await state(page); + expect(after.handles, `${from} to ${to}`).toHaveLength(before.handles.length); + expect(after.undo, `${from} to ${to}`).toBe(before.undo); + expect(after.controls, `${from} to ${to}`).toBe(true); + } +}); + +test('a stroke drops an Apply waiting for the surface to settle', async ({ page }) => { + await warpFront(page); + await page.getByRole('radio', { name: 'Line', exact: true }).click(); + await drag(page, [ + [-5, 13, 10], + [5, 13, 10], + ]); + // The line is lifted and the surface set back to rest, so it settles again from there; idle + // settling is held until the stroke below has begun. + const geometry = await inStore( + page, + ` + const { useEditor, finishWarpSettling } = store; + const line = useEditor.getState().warp.points.at(-1); + useEditor.getState().moveWarpPoints( + [{ id: line.id, target: [line.pin[0], line.pin[1], line.pin[2] + 2] }], + 'end', ); + finishWarpSettling(); const warp = useEditor.getState().warp; - const line = warp.points.at(-1); - const model = warp.model; - const lift = line.target[2] - line.pin[2]; - // Each drawn spot along the line, as far as the written surface has moved it. - const rises = line.path.map( - (spot: any) => - facePoint(model, warp.output.positions, spot)[2] - - facePoint(model, model.positions, spot)[2], - ); - return { lift, rises, radius: line.radius }; - }); - expect(ridge.radius).toBeGreaterThan(0); - expect(ridge.lift).toBeGreaterThan(1); - // Between the line's ends the ridge stands at the lift, with no peak at any sample. - const inner = ridge.rises.slice( - Math.floor(ridge.rises.length * 0.1), - Math.ceil(ridge.rises.length * 0.9), + const rotations = new Float64Array(warp.state.rotations.length); + for (let i = 3; i < rotations.length; i += 4) rotations[i] = 1; + window.__held = []; + window.__setTimeout = window.setTimeout; + window.setTimeout = (run, ...rest) => + String(run).includes('stepWarpSettle') + ? (window.__held.push(run), 0) + : window.__setTimeout(run, ...rest); + useEditor.setState({ + warp: { ...warp, state: { positions: warp.model.restNodes.slice(), rotations }, settling: true }, + }); + useEditor.getState().applyWarp(); + window.__geometry = useEditor.getState().scene.parts[0].geometry; + return useEditor.getState().warp.applying; + `, ); - for (const rise of inner) expect(Math.abs(rise - ridge.lift)).toBeLessThan(0.1 * ridge.lift); - for (let i = 1; i < inner.length - 1; i++) - expect(inner[i] - Math.min(inner[i - 1], inner[i + 1])).toBeLessThan(0.05 * ridge.lift); + expect(geometry).toBe(true); + const [a, b] = [await screen(page, [-5, 7, 10]), await screen(page, [5, 7, 10])]; + await page.mouse.move(a.x, a.y); + await page.mouse.down(); + await page.mouse.move((a.x + b.x) / 2, a.y, { steps: 6 }); + // Settling to the end while the stroke is held bakes nothing. + const during = await inStore<{ applying: boolean; baked: boolean; handles: number }>( + page, + ` + const { useEditor, finishWarpSettling } = store; + const applying = useEditor.getState().warp.applying; + window.setTimeout = window.__setTimeout; + for (const run of window.__held) run(); + finishWarpSettling(); + return { + applying, + baked: useEditor.getState().scene.parts[0].geometry !== window.__geometry, + handles: useEditor.getState().warp.points.length, + }; + `, + ); + expect(during).toEqual({ applying: false, baked: false, handles: 1 }); + await page.mouse.move(b.x, b.y, { steps: 6 }); + await page.mouse.up(); + const after = await state(page); + expect(after.handles).toHaveLength(2); + expect(after.handles[1].kind).toBe('line'); + expect( + await inStore( + page, + 'return store.useEditor.getState().scene.parts[0].geometry === window.__geometry;', + ), + ).toBe(true); }); + +/** + * How much of the drawn lines of line and area handles shows, near the screen path through world + * points and everywhere: the pixels they cover when they pass every depth test, and how many of + * those look the same when they are drawn as they are, depth-tested against the surface. + */ +async function strokeShare(page: Page, path: number[][]) { + return page.evaluate(async (path) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const root = (await import(urls.find((url) => url.includes('/@react-three_fiber.js'))!))._roots + .get(document.querySelector('canvas')) + .store.getState(); + await new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))); + const { gl, scene, camera, size } = root; + const lines: any[] = []; + scene.traverse((object: any) => { + if (object.visible && object.material?.isLineMaterial) lines.push(object); + }); + const canvas = gl.domElement as HTMLCanvasElement; + const { width, height } = canvas; + const context = gl.getContext() as WebGL2RenderingContext; + const read = () => { + gl.setRenderTarget(null); + gl.render(scene, camera); + const pixels = new Uint8Array(width * height * 4); + context.readPixels(0, 0, width, height, context.RGBA, context.UNSIGNED_BYTE, pixels); + return pixels; + }; + const shown = read(); + // Passing every depth test, still writing depth, so what is drawn after them is unchanged. + const depthFunc = lines.map((line) => line.material.depthFunc); + for (const line of lines) line.material.depthFunc = 1; + const all = read(); + for (const line of lines) line.visible = false; + const none = read(); + lines.forEach((line, i) => { + line.visible = true; + line.material.depthFunc = depthFunc[i]; + }); + root.invalidate(); + const ratio = width / size.width; + const ends = path.map((p) => { + const v = camera.position.clone().fromArray(p).project(camera); + return [((v.x + 1) / 2) * width, ((v.y + 1) / 2) * height]; + }); + const near = (x: number, y: number) => { + for (let i = 1; i < ends.length; i++) { + const [ax, ay] = ends[i - 1], + [bx, by] = ends[i]; + const ux = bx - ax, + uy = by - ay; + const t = Math.max(0, Math.min(1, ((x - ax) * ux + (y - ay) * uy) / (ux * ux + uy * uy))); + if (Math.hypot(x - ax - t * ux, y - ay - t * uy) <= 6 * ratio) return true; + } + return false; + }; + const differ = (a: Uint8Array, b: Uint8Array, i: number) => + Math.max( + Math.abs(a[i] - b[i]), + Math.abs(a[i + 1] - b[i + 1]), + Math.abs(a[i + 2] - b[i + 2]), + ) > 16; + const tally = { line: { drawn: 0, shown: 0 }, all: { drawn: 0, shown: 0 } }; + for (let y = 0; y < height; y++) + for (let x = 0; x < width; x++) { + const i = (y * width + x) * 4; + if (!differ(all, none, i)) continue; + const seen = differ(all, shown, i) ? 0 : 1; + tally.all.drawn++; + tally.all.shown += seen; + if (near(x, y)) { + tally.line.drawn++; + tally.line.shown += seen; + } + } + let length = 0; + for (let i = 1; i < ends.length; i++) + length += Math.hypot(ends[i][0] - ends[i - 1][0], ends[i][1] - ends[i - 1][1]) / ratio; + return { ...tally, length }; + }, path); +} + +/** Moves the camera along its line of sight until a CSS pixel at its target is `size` mm. */ +async function pixelAt(page: Page, size: number) { + await page.evaluate(async (size) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const root = (await import(urls.find((url) => url.includes('/@react-three_fiber.js'))!))._roots + .get(document.querySelector('canvas')) + .store.getState(); + const { camera, controls } = root; + const target = controls.target.clone(); + const tan = Math.tan((camera.fov * Math.PI) / 360); + const distance = (size * root.size.height) / (2 * tan); + camera.position.sub(target).setLength(distance).add(target); + camera.lookAt(target); + controls.update(); + root.invalidate(); + await new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))); + }, size); +} + +/** + * Turns the camera about its target, by `degrees` about the vertical, half way round by default, + * or about its own horizontal to look down across the surface. + */ +async function turnAround(page: Page, degrees = 180, tilt = false) { + await page.evaluate( + async ({ degrees, tilt }) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const root = ( + await import(urls.find((url) => url.includes('/@react-three_fiber.js'))!) + )._roots + .get(document.querySelector('canvas')) + .store.getState(); + const { camera, controls } = root; + const target = controls.target.clone(); + const offset = camera.position.clone().sub(target); + const axis = tilt ? offset.clone().cross(camera.up).normalize() : camera.up; + camera.position.copy(target).add(offset.applyAxisAngle(axis, (degrees * Math.PI) / 180)); + camera.lookAt(target); + controls.update(); + root.invalidate(); + await new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))); + }, + { degrees, tilt }, + ); +} + +for (const colors of ['light', 'dark', 'distinct'] as const) + test(`a line and an area on the front of a thin plate show from the front, also turned away, and not from behind, ${colors}`, async ({ + page, + }) => { + // A 0.2 mm plate, painted on its front at z = 0.1. + const plate = part( + 'plate', + 'Thin plate', + new BoxGeometry(20, 20, 0.2, 40, 40, 1), + [0, 10, 0], + colors === 'dark' ? '#1c1c1c' : '#e4e0d8', + ); + await warpFront(page, sceneOf([plate]), 'Thin plate', [0, 10, 0.1]); + if (colors === 'distinct') + await inStore(page, "store.useEditor.getState().setView({ partColors: 'distinct' });"); + // Radius 0, so no reach is drawn around the handles. + await inStore(page, "store.useEditor.getState().setWarpPointSettings({ radius: 0 }, 'end');"); + // Zoomed out as a 100 mm part is framed, where the old lift of a few pixels exceeded 0.2 mm. + await pixelAt(page, 0.1); + await page.getByRole('radio', { name: 'Line', exact: true }).click(); + const line = [ + [-6, 7, 0.1], + [6, 9, 0.1], + ]; + await drag(page, line); + await page.getByRole('radio', { name: 'Area', exact: true }).click(); + const brush = page.getByRole('spinbutton', { name: 'Brush radius', exact: true }); + await brush.fill('1.5'); + await brush.press('Enter'); + await drag(page, [ + [-2, 13, 0.1], + [2, 13.5, 0.1], + ]); + expect((await state(page)).handles.map((handle: { kind: string }) => handle.kind)).toEqual([ + 'line', + 'area', + ]); + // Nothing selected, so no gizmo is drawn, and no brush cursor. + await inStore(page, 'store.useEditor.getState().selectWarpPoints([]);'); + await page.getByRole('radio', { name: 'Point', exact: true }).click(); + await page.mouse.move(0, 0); + const front = await strokeShare(page, line); + // Looked at 65° from above, the half of its width beyond the line would sink into the + // surface if its corners were not laid on it. + await turnAround(page, 65, true); + const slope = await strokeShare(page, line); + await turnAround(page, -65, true); + await turnAround(page); + const back = await strokeShare(page, line); + test.info().annotations.push({ + type: 'pixels', + description: JSON.stringify({ front, slope, back }), + }); + // Drawn along its whole length, at least the core's width. + expect(front.line.drawn).toBeGreaterThan(2.5 * front.length); + expect(front.all.drawn).toBeGreaterThan(2 * front.line.drawn); + expect(front.line.shown).toBeGreaterThan(0.99 * front.line.drawn); + expect(front.all.shown).toBeGreaterThan(0.99 * front.all.drawn); + expect(slope.line.drawn).toBeGreaterThan(2.5 * slope.length); + expect(slope.line.shown).toBeGreaterThan(0.99 * slope.line.drawn); + expect(slope.all.shown).toBeGreaterThan(0.99 * slope.all.drawn); + // From behind, the plate hides all of it. + expect(back.all.drawn).toBeGreaterThan(0.9 * front.all.drawn); + expect(back.all.shown).toBeLessThan(0.002 * back.all.drawn); + }); diff --git a/tests/unit/warp-session.test.ts b/tests/unit/warp-session.test.ts index 958bd26..e5cc26e 100644 --- a/tests/unit/warp-session.test.ts +++ b/tests/unit/warp-session.test.ts @@ -28,8 +28,11 @@ import { isWarpDragging, useEditor, warpChanges, + warpPinDrift, + warpPinDriftCause, warpRadiusSpacings, warpShortfall, + warpShortfallCause, warpShortfallShown, warpWholeDensity, type WarpBaseline, @@ -47,6 +50,7 @@ import { snapshotOf, spacingAt, warpFootprintSpacings, + warpPinHold, warpPriorityStrength, type WarpSample, } from '../../src/core/warp-handles'; @@ -118,6 +122,13 @@ function faceAt(geometry: BufferGeometry, x: number, y: number, z = 0) { throw new Error('No face under the point.'); } +/** Barycentric coordinates of a mesh-local point on the z = 0 plate, on the face containing it. */ +function barycentricAt(part: Part, x: number, y: number) { + return readFace(part.geometry, faceAt(part.geometry, x, y)) + .getBarycoord(new Vector3(x, y, 0), new Vector3())! + .toArray() as Vec3; +} + const hit = (partId: string, x: number, y: number, z = 0): SurfacePoint => ({ partId, point: [x, y, z], @@ -524,10 +535,17 @@ describe('warp session', () => { ); expect(kept.target).toEqual([-10, 1, 3]); expect(kept.pin).toEqual(inside.pin); - expect(warp.undo).toHaveLength(1); - expect(warp.undo[0]).toMatchObject({ points: [kept], gapTargets: [] }); - expect(warp.undo[0].surface!.grid).toBe(model.grid); - expect(kept.baseline).toBe(warp.undo[0].surface); + expect(kept.baseline.grid).toBe(model.grid); + // The new region is one step of its own; the steps before it stay on the grid it replaced. + expect(warp.undo).toHaveLength(2); + const [earlier, relaid] = warp.undo; + expect(relaid.grid!.laid.faces).toBeNull(); + expect(relaid.grid!.laid.painted).toMatchObject({ region: 'painted', faces: [] }); + expect(relaid.points.map((p) => p.id)).toEqual(['inside', 'outside']); + expect(relaid.gapTargets).toEqual(gapTargets); + expect(earlier.points.map((p) => p.id)).toEqual(['inside', 'outside']); + expect(earlier.gapTargets).toEqual(gapTargets); + for (const step of warp.undo) expect(step.surface!.grid).not.toBe(whole.grid); // A density change rebuilds the grid and keeps every point that is still inside. editor().setWarpRegion('whole'); @@ -2015,6 +2033,80 @@ describe('warp handles', () => { expect(session().points.map(({ id }) => id)).toContain(touched.id); }); + it('close gap leaves the points, lines and areas the user holds where they are, and the seam open there', async () => { + const a = plate('a', 0, 64); + // Facing it, 1 mm in front. + const b: Part = { ...plate('b'), position: [0, 0, 1], quaternion: [0, 1, 0, 0] }; + for (const region of ['whole', 'painted'] as const) { + setup([a, b], ['a']); + editor().setTool('warp'); + editor().setWarpOptions({ autoPoints: false }); + if (region === 'whole') { + editor().setWarpRegion('whole'); + await editor().layWarpGrid(); + } else await warpDisc(a, 0, 0, 14); + const label = region; + addAt(a, 3, 2); + const spots = Array.from({ length: 120 }, (_, i) => { + const x = -6 + (12 * i) / 119, + y = -4 + i / 119; + return { face: faceAt(a.geometry, x, y), barycentric: barycentricAt(a, x, y) }; + }); + expect(editor().addWarpStroke({ kind: 'line', points: spots })).toBe(true); + const first = { face: faceAt(a.geometry, -5, 5), barycentric: barycentricAt(a, -5, 5) }; + const faces = Array.from({ length: triangleCount(a.geometry) }, (_, f) => f).filter( + (f) => + readFace(a.geometry, f) + .getMidpoint(new Vector3()) + .distanceTo(new Vector3(-5, 5, 0)) < 1.2, + ); + expect(editor().addWarpStroke({ kind: 'area', faces, first })).toBe(true); + finishWarpSettling(); + const model = session().model!; + const held = session().points; + const where = () => + held.flatMap((point) => + point.samples.map(({ binding, restWorld }) => + deformPoint(model, session().state!, binding, restWorld), + ), + ); + const before = where(); + editor().closeWarpGap(); + finishWarpSettling(); + const { gapTargets, gapHeld, state, seam } = session(); + expect(gapTargets.length, label).toBeGreaterThan(100); + expect(gapHeld, label).toBeGreaterThan(0); + where().forEach((at, i) => + expect(distance(at, before[i]), `${label}, sample ${i}`).toBeLessThanOrEqual(warpPinHold), + ); + // The seam closes elsewhere, and stays open where they hold it. + for (const { node, target } of gapTargets) + expect(distance(state!.positions.subarray(node * 3, node * 3 + 3), target)).toBeLessThan( + 0.05, + ); + expect(seam!.largestGap, label).toBeGreaterThan(0.5); + editor().selectWarpPoints(held.map(({ id }) => id)); + expect(warpPinDrift(session()), label).toBeLessThanOrEqual(warpPinHold); + editor().cancelWarp(); + } + }); + + it('names Close gap or a moved handle as what pulls a held point, whichever is nearer', async () => { + const a = plate('a', 0, 32); + setup([a], ['a']); + await warpDisc(a, 0, 0, 12); + editor().setWarpPointSettings({ radius: 0 }, 'end'); + const pin = addAt(a, 0.5, 0.3); + const far = addAt(a, -8, 0.3); + move(far.id, [-8, 0.3, 1]); + editor().selectWarpPoints([pin.id]); + const node = pin.samples[0].binding.node[0]; + const gap = [{ node, target: [0, 0, 0] as Vec3 }]; + expect(warpPinDriftCause(session())).toBe('moved'); + useEditor.setState({ warp: { ...session(), gapTargets: gap } }); + expect(warpPinDriftCause(session())).toBe('gap'); + }); + it('close gap closes the box seam whatever the number of automatic points', async () => { for (const count of [8, 16, 32]) { const block = solid('block', new BoxGeometry(20, 20, 20, 12, 12, 12), [0, 0, 0]); @@ -2340,6 +2432,68 @@ describe('warp handles', () => { } }); + it('a new region is one undo step, and undo restores it, the density change and each step before exactly', async () => { + for (const feather of [false, true]) { + const a = plate('a', 0, 64); + setup([a], ['a']); + useEditor.setState({ warpFeather: { enabled: feather, width: feather ? 2 : null } }); + await warpDisc(a, 0, 0, 10); + editor().setWarpPointSettings({ radius: 5 }, 'end'); + const label = `feather ${feather}`; + const record = () => { + finishWarpSettling(); + const warp = session(); + return { + surface: positionsOf(warp.preview!), + normals: Array.from(warp.preview!.getAttribute('normal').array), + region: warp.faces, + density: warp.density, + nodes: Array.from(warp.model!.grid.nodes), + undo: warp.undo.length, + points: warp.points.map(({ id, pin, target, radius, falloff, samples, baseline }) => ({ + id, + pin, + target, + radius, + falloff, + samples: samples.map(({ pin, binding }) => ({ pin, binding })), + baseline: Array.from(baseline.positions), + })), + }; + }; + // Bend the plate, then place a second handle on the bend and edit it. + const p = addAt(a, -2, 0); + move(p.id, [-2, 0, 2]); + const history = [record()]; + const q = addAt(a, 1, 0.5, deformed(p)[2]); + history.push(record()); + editor().selectWarpPoints([q.id]); + editor().setWarpPointSettings({ radius: 3 }, 'end'); + history.push(record()); + move(q.id, [1, 0.5, 2.5]); + history.push(record()); + await editor().setWarpDensity(4); + history.push(record()); + const density = session().undo.at(-1)!.grid!; + // Expand the paint and lay the grid again. + editor().setWarpRegion('painted'); + editor().paintWarpRegion(hit('a', 9, 0), faceAt(a.geometry, 9, 0), false, true); + editor().endPaintStroke(); + await editor().layWarpGrid(); + expect(session().stage, label).toBe('warp'); + expect(session().faces.length, label).toBeGreaterThan(history.at(-1)!.region.length); + expect(session().undo, label).toHaveLength(history.at(-1)!.undo + 1); + expect(session().undo.at(-1)!.grid!.laid.painted.faces, label).toBe(history.at(-1)!.region); + expect(session().undo.at(-2)!.grid, label).toBe(density); + for (let step = history.length - 1; step >= 0; step--) { + await editor().undoWarpEdit(); + expect(record(), `${label}, step ${step}`).toEqual(history[step]); + } + editor().cancelWarp(); + } + useEditor.setState({ warpFeather: { enabled: false, width: null } }); + }, 60_000); + it('a density change that would drop a handle is not made, and says why', async () => { for (const feather of [false, true]) for (const [x, y] of [ @@ -2409,7 +2563,7 @@ describe('warp handles', () => { expect(session().points).toBe(before.points); }); - it('a rebuild drops points that could only sit on fixed nodes, from undo steps too', async () => { + it('a rebuild drops points that could only sit on fixed nodes, and undo brings them back', async () => { const a = plate('a'); setup([a], ['a']); await warpDisc(a, 0, 0, 12); @@ -2427,10 +2581,13 @@ describe('warp handles', () => { useEditor.setState({ toast: null, warp: { ...session(), region: 'painted', faces: row } }); await editor().layWarpGrid(); expect(session().points.map((point) => point.id)).toEqual([kept.id]); - for (const step of session().undo) - expect(step.points.map((point) => point.id)).not.toContain(lost.id); expect(toast()).toBe('Some control points were outside the new region and were removed.'); expect(warpChanges(session())).toBe(false); + const { faces } = session().undo.at(-1)!.grid!.laid.painted; + await editor().undoWarpEdit(); + expect(session().points.map((point) => point.id)).toEqual([kept.id, lost.id]); + expect(session().faces).toBe(faces); + expect(warpChanges(session())).toBe(true); }); it('points without a radius solve bit for bit as their own constraints, a moved one held first', async () => { @@ -2593,6 +2750,7 @@ describe('warp handles that must land', () => { const short = distance(deformed(current(p.id)), [0.53, 0.31, 2]); expect(short).toBeGreaterThan(warpShortfallShown); expect(warpShortfall(session())).toBeCloseTo(short, 9); + expect(warpShortfallCause(session())).toBe('pin'); // It is the pin's own spot that holds it, not the grid. editor().removeWarpPoints([pin.id]); finishWarpSettling(); @@ -2600,6 +2758,38 @@ describe('warp handles that must land', () => { expect(warpShortfall(session())).toBeLessThan(0.01); }); + it('names the fixed edge when it holds a grab back', async () => { + const a = plate('a', 0, 32); + setup([a], ['a']); + await warpDisc(a, 0, 0, 12); + editor().setWarpPointSettings({ radius: 0 }, 'end'); + const model = session().model!; + // The first spot in from the disc's edge whose point is bound partly to its fixed edge. + let p: WarpPoint | undefined, + x = 11.9; + for (; x > 8 && !p; x -= 0.1) { + if (!model.region.faces.includes(faceAt(a.geometry, x, 0.3))) continue; + const count = session().points.length; + const added = addAt(a, x, 0.3); + if (session().points.length === count) continue; + if (added.samples[0].binding.weight.reduce((sum, w) => sum + w, 0) < 0.9) p = added; + else editor().undoWarpEdit(); + } + x += 0.1; + expect(p).toBeDefined(); + move(p!.id, [x, 0.3, 3]); + finishWarpSettling(); + editor().selectWarpPoints([p!.id]); + expect(warpShortfall(session())).toBeGreaterThan(warpShortfallShown); + expect(warpShortfallCause(session())).toBe('edge'); + // Grabbed farther inside, it lands. + const q = addAt(a, 2, 0.3); + move(q.id, [2, 0.3, 3]); + finishWarpSettling(); + editor().selectWarpPoints([q.id]); + expect(warpShortfall(session())).toBeLessThan(warpShortfallShown); + }); + it('Apply waits for a settling surface and bakes it settled, exactly as then shown', async () => { // Idle settling runs in a browser window. vi.stubGlobal('window', globalThis); diff --git a/tests/unit/warp-strokes.test.ts b/tests/unit/warp-strokes.test.ts index 4029a7f..38d0001 100644 --- a/tests/unit/warp-strokes.test.ts +++ b/tests/unit/warp-strokes.test.ts @@ -1,15 +1,30 @@ import { writeFileSync } from 'node:fs'; import { afterEach, describe, expect, it } from 'vitest'; -import { BufferAttribute, PlaneGeometry, SphereGeometry, Triangle, Vector3 } from 'three'; +import { + BufferAttribute, + CylinderGeometry, + PlaneGeometry, + SphereGeometry, + Triangle, + Vector3, +} from 'three'; import type { BufferGeometry } from 'three'; import { triangleCount } from '../../src/core/geometry'; -import { finishWarpSettling, useEditor, type WarpPoint } from '../../src/core/store'; +import { + finishWarpSettling, + useEditor, + warpPinDrift, + warpShortfallShown, + type WarpPoint, +} from '../../src/core/store'; import { readFace } from '../../src/core/surfaces'; import { defaultWarpDensity } from '../../src/core/warp-grid'; +import { isPaintedFace } from '../../src/core/warp-model'; import { areaBrushFaces, facePoint, lineSamples, + strokeSample, type WarpStrokePoint, } from '../../src/core/warp-strokes'; import type { Part, SceneDocument, Vec3 } from '../../src/core/types'; @@ -230,6 +245,57 @@ describe('line handles', () => { expect(difference).toBeLessThan(0.02 * h); }); + for (const span of [25, 45]) + it(`keep samples along a short line over tight curvature on the coarsest grid, ±${span}°`, async () => { + // A 32 mm open half-pipe of radius 0.9 mm along y, laid whole at the coarsest density and + // held by two points near its ends. Its grid spacing is several times the line's length. + const R = 0.9; + const part = partOf(new CylinderGeometry(R, R, 32, 32, 400, true, -Math.PI / 2, Math.PI)); + editor().setScene({ name: 'Warp', parts: [part], joints: [] }); + useEditor.setState({ selected: [part.id] }); + editor().setTool('warp'); + editor().setWarpOptions({ autoPoints: false }); + editor().setWarpRegion('whole'); + await editor().setWarpDensity(0); + await editor().layWarpGrid(); + editor().setWarpPointSettings({ radius: 0 }, 'end'); + for (const y of [-15, 15]) { + const pin = surfaceAt(part, [0, y, R]); + editor().addWarpPoint({ partId: part.id, point: [0, y, R], normal: [0, 0, 1] }, pin.face); + } + // Around the pipe, rising a little along it. + const around = (a: number) => + surfaceAt(part, [R * Math.sin(a), 1.3 + 0.2 * a, R * Math.cos(a)]); + const a = (span * Math.PI) / 180; + const points = Array.from({ length: 120 }, (_, i) => around(-a + (2 * a * i) / 119)); + expect(editor().addWarpStroke({ kind: 'line', points })).toBe(true); + const line = latest(); + const spacing = line.reach!.spacing; + expect(spacing).toBeGreaterThan(2 * R * a); + expect(line.samples.length).toBeGreaterThan(3); + const lift = 0.5; + editor().moveWarpPoints( + [{ id: line.id, target: [line.pin[0], line.pin[1], line.pin[2] + lift] }], + 'end', + ); + finishWarpSettling(); + const model = session().model!; + const rises = points.map( + (p) => + facePoint(model, session().output!.positions, p)[2] - + facePoint(model, model.positions, p)[2], + ); + figures[`short curved line, ±${span}°`] = { + samples: line.samples.length, + spacing, + ends: [rises[0], rises.at(-1)], + highest: Math.max(...rises), + lowest: Math.min(...rises), + }; + // Both ends land, and nothing between them stands above or sinks below the lift. + for (const rise of rises) expect(Math.abs(rise - lift)).toBeLessThan(0.05 * lift); + }, 30_000); + it('take a sample about every half spacing and merge those bound alike, keeping both ends', async () => { const surface = { ...surfaces.plate, make: () => partOf(new PlaneGeometry(40, 40, 8, 8)) }; const part = await lay(surface); @@ -331,6 +397,64 @@ describe('area handles', () => { expect(editor().paintHistory).toBe(history); }); + it('refuse a dab whose faces are all held by fixed nodes, and say to paint farther inside', async () => { + // A sheet as fine as a scan, painted in a small disc on the coarsest grid: most of the disc + // is bound only to its fixed edge. + const part = partOf(new PlaneGeometry(16, 16, 320, 320)); + editor().setScene({ name: 'Warp', parts: [part], joints: [] }); + useEditor.setState({ selected: [part.id] }); + editor().setTool('warp'); + editor().setWarpBrushRadius(1.5); + editor().paintWarpRegion( + { partId: part.id, point: [0, 0, 0], normal: [0, 0, 1] }, + surfaceAt(part, [0, 0, 0]).face, + false, + true, + ); + editor().endPaintStroke(); + await editor().setWarpDensity(0); + await editor().layWarpGrid(); + const { model, state } = session(); + const third: Vec3 = [1 / 3, 1 / 3, 1 / 3]; + const fixed = Array.from(model!.region.faces).filter( + (face) => + strokeSample(model!, state!, { face, barycentric: third }) === null && + [ + [0.6, 0.2, 0.2], + [0.2, 0.6, 0.2], + [0.2, 0.2, 0.6], + ].every( + (barycentric) => + strokeSample(model!, state!, { face, barycentric: barycentric as Vec3 }) === null, + ), + ); + expect(fixed.length).toBeGreaterThan(10); + // Fixed faces alone, and fixed faces first with a free one last. + const free = Array.from(model!.region.faces).find( + (face) => strokeSample(model!, state!, { face, barycentric: third }) !== null, + )!; + useEditor.setState({ toast: null }); + expect( + editor().addWarpStroke({ + kind: 'area', + faces: fixed.slice(0, 20), + first: { face: fixed[0], barycentric: third }, + }), + ).toBe(false); + expect(session().points).toHaveLength(0); + expect(useEditor.getState().toast?.message).toBe( + 'This spot is fixed. Paint farther inside the warp region.', + ); + expect( + editor().addWarpStroke({ + kind: 'area', + faces: [...fixed.slice(0, 20), free], + first: { face: fixed[0], barycentric: third }, + }), + ).toBe(true); + expect(latest().samples.length).toBeGreaterThan(0); + }); + it('paint only faces turned toward the brush', async () => { const part = await lay(surfaces.ball); const first = surfaceAt(part, [0, 0, 16]); @@ -343,6 +467,104 @@ describe('area handles', () => { }); describe('handles made by strokes through a session', () => { + /** Lays the plate's grid again over the painted faces whose centres pass `keep`. */ + async function shrink(part: Part, keep: (centre: Vector3) => boolean) { + editor().setWarpRegion('painted'); + const faces = session().faces.filter((face) => + keep(readFace(part.geometry, face).getMidpoint(new Vector3())), + ); + useEditor.setState({ toast: null, warp: { ...session(), faces } }); + await editor().layWarpGrid(); + expect(session().stage).toBe('warp'); + } + const offset = (handle: WarpPoint) => + handle.target ? handle.target.map((value, a) => value - handle.pin[a]) : null; + + for (const moved of [false, true]) + it(`keep the run of a ${moved ? 'moved' : 'still'} line left on a smaller region, centred on it`, async () => { + const part = await lay(surfaces.plate); + editor().addWarpStroke({ + kind: 'line', + points: stroke(part, surfaces.plate, [-9, 0.3, 0], [9, 1.1, 0], 0.03), + }); + const made = latest(); + if (moved) lift(made, h); + const before = session().points.find(({ id }) => id === made.id)!; + // The region now stops at x = 2.5; the samples beyond it are lost. + await shrink(part, (centre) => centre.x < 2.5); + const line = session().points.find(({ id }) => id === made.id)!; + const model = session().model!; + expect(line.path!.length).toBeGreaterThan(10); + for (const spot of line.path!) expect(isPaintedFace(model, spot.face)).toBe(true); + for (const sample of line.samples) expect(isPaintedFace(model, sample.face)).toBe(true); + const xs = line.samples.map(({ restWorld }) => restWorld[0]); + expect(Math.max(...xs)).toBeLessThan(2.5); + expect(Math.max(...xs)).toBeGreaterThan(1); + // Centred on what is left, which the gizmo shows, with the same offset as before. + const middle = (Math.min(...xs) + Math.max(...xs)) / 2; + expect(Math.abs(line.pin[0] - middle)).toBeLessThan(0.5); + expect(line.pin[2]).toBeCloseTo(0, 6); + if (moved) offset(line)!.forEach((d, a) => expect(d).toBeCloseTo(offset(before)![a], 9)); + else expect(line.target).toBeNull(); + editor().selectWarpPoints([line.id]); + finishWarpSettling(); + if (!moved) expect(warpPinDrift(session())).toBeLessThan(warpShortfallShown); + // Undo gives the whole line back. + await editor().undoWarpEdit(); + expect(session().points.find(({ id }) => id === made.id)).toMatchObject({ + pin: before.pin, + target: before.target, + path: before.path, + }); + }); + + it('drop a line with too little left on a smaller region, with the notice', async () => { + const part = await lay(surfaces.plate); + editor().addWarpStroke({ + kind: 'line', + points: stroke(part, surfaces.plate, [-9, 0.3, 0], [9, 1.1, 0], 0.03), + }); + const made = latest(); + const xs = made.samples.map(({ restWorld }) => restWorld[0]); + // Only the last sample's end of the region is left. + const cut = (Math.max(...xs) + [...xs].sort((a, b) => a - b).at(-2)!) / 2; + await shrink(part, (centre) => centre.x > cut); + expect(session().points.some(({ id }) => id === made.id)).toBe(false); + expect(useEditor.getState().toast?.message).toBe( + 'Some control points were outside the new region and were removed.', + ); + }); + + for (const moved of [false, true]) + it(`keep the largest piece of a ${moved ? 'moved' : 'still'} area left on a smaller region, centred on it`, async () => { + const part = await lay(surfaces.plate); + const first = surfaceAt(part, [4, 0, 0]); + editor().addWarpStroke({ + kind: 'area', + faces: areaBrushFaces(session().model!, session().output!.positions, first, 3), + first, + }); + const made = latest(); + if (moved) lift(made, h); + const before = session().points.find(({ id }) => id === made.id)!; + await shrink(part, (centre) => centre.x < 4.5); + const area = session().points.find(({ id }) => id === made.id)!; + const model = session().model!; + expect(area.faces!.length).toBeLessThan(made.faces!.length); + for (const face of area.faces!) expect(isPaintedFace(model, face)).toBe(true); + for (const sample of area.samples) expect(area.faces).toContain(sample.face); + const xs = area.faces!.map( + (face) => readFace(part.geometry, face).getMidpoint(new Vector3()).x, + ); + expect(area.pin[0]).toBeLessThan(Math.max(...xs)); + expect(area.pin[0]).toBeGreaterThan(Math.min(...xs)); + expect(area.pin[0]).toBeLessThan(before.pin[0]); + if (moved) offset(area)!.forEach((d, a) => expect(d).toBeCloseTo(offset(before)![a], 9)); + editor().selectWarpPoints([area.id]); + finishWarpSettling(); + if (!moved) expect(warpPinDrift(session())).toBeLessThan(warpShortfallShown); + }); + for (const kind of ['line', 'area'] as const) it(`keep a ${kind} whole through edits, a re-lay, undo, a live refusal and Apply`, async () => { const part = await lay(surfaces.plate); @@ -385,22 +607,56 @@ describe('handles made by strokes through a session', () => { expect(Math.abs(rise - h)).toBeLessThan(0.1 * Math.max(h, 1)); } }; + /** What each undo step must give back exactly: surface, region, grid and every handle. */ + const record = () => { + finishWarpSettling(); + const warp = session(); + return { + surface: Array.from(warp.preview!.getAttribute('position').array), + normals: Array.from(warp.preview!.getAttribute('normal').array), + region: warp.faces, + density: warp.density, + nodes: Array.from(warp.model!.grid.nodes), + undo: warp.undo.length, + handles: warp.points.map((handle) => ({ + id: handle.id, + kind: handle.kind, + pin: handle.pin, + target: handle.target, + radius: handle.radius, + falloff: handle.falloff, + faces: handle.faces, + path: handle.path, + samples: handle.samples.map(({ face, barycentric, restWorld, pin, binding }) => ({ + face, + barycentric, + restWorld, + pin, + binding, + })), + baseline: Array.from(handle.baseline.positions), + })), + }; + }; whole(); - const steps: number[] = [session().undo.length]; + const history = [record()]; lift(current(), h); - steps.push(session().undo.length); + history.push(record()); whole(); holds(h); editor().selectWarpPoints([id]); editor().setWarpPointSettings({ radius: 4 }, 'end'); + history.push(record()); editor().setWarpPointSettings({ falloff: 0.3 }, 'end'); - steps.push(session().undo.length); + history.push(record()); expect(current()).toMatchObject({ radius: 4, falloff: 0.3 }); whole(); holds(h); await editor().setWarpDensity(defaultWarpDensity + 1); whole(); holds(h); + history.push(record()); + const grid = session().undo.at(-1)!.grid!; // Edit region, paint more, and lay the grid again. editor().setWarpRegion('painted'); editor().paintWarpRegion( @@ -412,21 +668,20 @@ describe('handles made by strokes through a session', () => { editor().endPaintStroke(); await editor().layWarpGrid(); expect(session().stage).toBe('warp'); + expect(session().faces).not.toEqual(history.at(-1)!.region); + expect(session().undo).toHaveLength(history.at(-1)!.undo + 1); whole(); holds(h); - // Undo steps back through the falloff, the radius and the move, keeping the handle. - await editor().undoWarpEdit(); - // The density step was recorded on the region before the re-lay and has nothing to restore. - if (current().falloff !== 1) await editor().undoWarpEdit(); - expect(current().falloff).toBe(1); - expect(current().radius).toBe(4); - await editor().undoWarpEdit(); - expect(current().radius).toBe(made.radius); - whole(); - holds(h); - await editor().undoWarpEdit(); + // The density step keeps the grid it rebuilds and its fingerprint through the re-lay. + expect(session().undo.at(-2)!.grid).toBe(grid); + // Each undo gives back the step before it exactly: the re-lay, the density change, the + // falloff, the radius and the move. + for (let step = history.length - 1; step >= 0; step--) { + await editor().undoWarpEdit(); + expect(record()).toEqual(history[step]); + whole(); + } expect(current().target).toBeNull(); - whole(); lift(current(), h); // A refused live Apply reopens the session with the handle as it was. useEditor.setState({ liveStatus: 'connected' }); From ec222479516c12341f9694157675764a620aa682 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Wed, 18 Nov 2026 17:44:11 -0800 Subject: [PATCH 20/25] Lighten the warp grid as it gets denser and drop fans into fixed edges --- .../specs/2026-11-17-warp-handles-design.md | 61 ++++-- src/components/WarpGrid.tsx | 87 +++++--- src/core/warp-grid-path.ts | 183 ++++++++++++++-- tests/e2e/helpers/warp-grid.ts | 22 +- tests/e2e/warp-grid.spec.ts | 200 +++++++++++++----- tests/unit/warp-grid-path.test.ts | 116 ++++++++++ 6 files changed, 543 insertions(+), 126 deletions(-) diff --git a/docs/superpowers/specs/2026-11-17-warp-handles-design.md b/docs/superpowers/specs/2026-11-17-warp-handles-design.md index 0faa4f4..1da8ab3 100644 --- a/docs/superpowers/specs/2026-11-17-warp-handles-design.md +++ b/docs/superpowers/specs/2026-11-17-warp-handles-design.md @@ -91,20 +91,39 @@ again remembers how far it bent the line; a view leaves out those that bend it b its smallest pixel on the grid, and never by more than 0.0375 mm, so a chord never dips under the pull toward the camera. Evenly spaced points always show. +Not every grid edge is drawn. The grid keeps every vertex of a fixed border, and of a whole +part's open edge, so where its inside is sparse against them (on a painted region of a dense scan, +726 of 867 nodes on the torso; on an open 80 × 80 plate at the coarsest density, 320 of 321) a +node inside would send a fan of lines to dozens of them. Edges between nodes inside and edges along +the outline are all drawn. From each node inside, lines to the outline are chosen shortest first, +each as far in angle as can be from the node's other lines, at most four and none closer than 40° +to another; edges across the inside between two outline nodes are not drawn. The solve and the +model keep every edge. The grid's typical cell, which scales line weight, leaves out the outline, +whose edges run at the mesh's own resolution. + Coarser nets of the grid's own edges keep a readable grid when its cells are too small to show: level k picks nodes of the net below about 2^k typical edges apart along it and joins each two whose shares of it meet by the shortest way along it, up to three levels. Each comes in over an -octave of its own cells as the net below it goes, its core from 10 to 20 px and its casing, which -shows only on dark parts, from 24 to 48 px; the first net's core comes in only as the grid's own -is nearly gone, so on a light part the grid covers no more than it does at default density. Edges -are drawn coarsest first, and each draw leaves out the levels whose largest cell is too small on -screen for it to show. +octave of its own cells, from 10 to 20 px, as the net below it goes, core and casing alike. An edge +of two nets shows with the sum of their strengths, so it stays whole as one hands over to the +next and the grid never dims as it zooms. A net's cells count as half their size for ink: its +lines wind along the grid, so lie closer than a triangle grid's of the same cells. Edges are drawn +coarsest first, and each draw leaves out the levels whose largest cell is too small on screen for +it to show. Edges are drawn as screen-space quads (`WarpGrid.tsx`) in two draws over one instanced -geometry: an opaque dark core 1.5 px wide, and a light casing 4 px wide drawn first with MAX -blending, so it lifts only what is darker than itself and leaves light and mid colours alone. -The core is full while cells are 13 px or more on screen (shrunk as the surface turns away), -then thins to 1 px and fades out by 6 px; the casing fades out between 22 and 12 px cells. +geometry: a dark core, and a light casing drawn first with MAX blending, so it lifts only what is +darker than itself and leaves light and mid colours alone. Each line carries ink in proportion to +its cell's size on screen, so the grid puts about the same ink on the part at any density or zoom: +at cells of 40 px or more the core is 1.5 px and opaque and the casing 4 px, as dark and crisp as +they ever were; below that the core's opacity falls as the 1.5 power of the cell's size over 40 px +(blending in sRGB darkens faster than opacity grows, so this keeps the luminance ink about in +proportion) and the casing's in proportion to it, the core thinning to 1 px and the casing to +2.5 px below half strength. A shown line never falls below an opacity of 0.25 for the core or 0.35 +for the casing, so a dense grid stays visible rather than vanishing. The cell's size is measured +as foreshortened where the surface turns away, down to half, so crowded lines on a slope stay +light without the grid going patchy. A grid's own core fades out between 11 and 5 px cells by the +fully foreshortened cell, and its casing between 12 and 6 px by the cell facing the camera. Each corner's depth is where its view ray meets the surface's tangent plane at the line, then nearer by at most a pixel or 0.05 mm, and never more than halfway to the near plane, so any opaque surface 0.2 mm or more in front hides the line in either projection at working @@ -121,15 +140,23 @@ shows on a slope while a surface 0.2 mm or more in front hides it, or the part o covers, at working distance. While Interference inspection draws the part see-through, the grid is hidden. -Acceptance: at about 300 px across at default density, no more than about a third of the -part's pixels change by more than 1.5:1; the core's centre reaches 3:1 over the first 24 -Distinct colours and white at that zoom and close up, from two directions; the line reaches -3:1 on a near-black part; at least 90 % of front-facing grid length is visible on the curved -part; the far side, the other sheet of a thin shell and anything 0.2 mm or more behind an -opaque surface do not show through at working distance; the grid stays on the written surface before and after +Acceptance: the grid reads as a light overlay with the model the subject. With a part about 500 px +across at the whole-part default of 2,000 nodes, and about 300 px across at 500, 2,000 and 4,000 +nodes, it changes by more than 1.5:1 less than 16 % of the part's pixels on any Distinct colour, +the editor's default and white, and less than 20 % on a near-black part (on the torso and Tomb +Crawler scans, 33 % and 31 % before, 13 % after). Its visibility floor: at 500, 2,000 and 4,000 +nodes from about 500 px across to 200, on every Distinct colour and a near-black part, it changes +by more than 1.2:1 more than 8 % of the part's pixels (the old 1 px chords managed 0.2 to 1.6 %). +Where cells are 40 px or more on screen, the core's centre reaches 3:1 over the first 24 Distinct +colours and white from two directions and in an orthographic view, and the line reaches 3:1 on a +near-black part and in every lighting preset. No node inside the outline draws more than four +lines to it; the open plate at the coarsest density, its centre pulled, changes under 5 % of its +pixels (40 % before). At least 90 % of front-facing grid length is visible on the curved part; the +far side, the other sheet of a thin shell and anything 0.2 mm or more behind an opaque surface do +not show through at working distance; the grid stays on the written surface before and after deformation, no drawn point more than 0.1 mm off it on a coarse grid over a fine mesh from the -first surface written after a pull, and no line moving once it is released; at the -highest density a coarser net still shows as the part is zoomed out, without a sudden change. +first surface written after a pull, and no line moving once it is released; at the highest +density a coarser net still shows as the part is zoomed out, without a sudden change. ### 2. Brush size fitted to the part diff --git a/src/components/WarpGrid.tsx b/src/components/WarpGrid.tsx index 6be1efb..e57ea8b 100644 --- a/src/components/WarpGrid.tsx +++ b/src/components/WarpGrid.tsx @@ -28,7 +28,7 @@ import { writtenNodePositions } from '../core/warp-evaluate'; import type { WarpModel } from '../core/warp-model'; import { traceWarpGridPath, - typicalLength, + warpGridCell, warpGridChords, warpGridLevels, warpGridShiftWidth, @@ -50,22 +50,33 @@ export function gridNodePositions(warp: WarpSession) { } /** - * How grid lines are drawn, in CSS pixels against the cell's length on screen. The dark core is - * what makes the grid stand out: full width and opaque down to `coreFull`, then thinner to - * `coreThin` px and fading out to `coreGone`, by cells shrunk as the surface turns away. The - * light casing lifts only what is darker than it, so it shows on dark parts and leaves light ones - * alone, and fades out from `casingFull` to `casingGone`. + * How grid lines are drawn, in CSS pixels against the cell's length on screen. Each line carries + * ink in proportion to its cell's size, so the grid puts about as much ink on the part however + * fine it is or however far away: full width and opacity from `inkFull` px cells; below that, an + * opacity of the ink's power `inkCurve` (blending in sRGB darkens faster than opacity grows) but + * never below `inkFloor` (`casingFloor` for the casing) while the line shows, and thinner below + * `inkWide`. The dark core makes the grid stand out on light parts; the light casing lifts only + * what is darker than it, so it shows on dark parts and leaves light ones alone. A grid's own + * lines fade out from `coreFull` to `coreGone` px cells, by cells shrunk as the surface turns + * away, and its casing from `casingFull` to `casingGone`. */ export const warpGridStyle = { core: '#0e1114', coreWidth: 1.5, coreThin: 1, - coreFull: 13, - coreGone: 6, + coreFull: 11, + coreGone: 5, casing: '#b0b5b8', casingWidth: 4, - casingFull: 22, - casingGone: 12, + casingThin: 2.5, + casingFull: 12, + casingGone: 6, + inkFull: 40, + inkCurve: 1.5, + casingCurve: 1, + inkFloor: 0.25, + casingFloor: 0.35, + inkWide: 0.5, /** * Coarser nets of the grid's own edges, for when its cells are too small to show: each comes in * over an octave of its own cells, from `coarseGone` to `coarseFull` px, as the net below it @@ -73,9 +84,8 @@ export const warpGridStyle = { */ coarseFull: 20, coarseGone: 10, - /** The same for their casing, which shows only on dark parts: about a default grid's cells. */ - coarseCasingFull: 48, - coarseCasingGone: 24, + /** Their cells count as this share of their size for ink: their lines wind, so lie closer. */ + coarseInk: 0.5, /** How far a line may sit behind the surface and still show: pixels, and at most mm. */ tolerance: 1, toleranceMax: 0.05, @@ -114,17 +124,28 @@ float fadeIn( float level, float pixels, vec2 own, vec2 coarse ) { return clamp( ( pixels * exp2( level ) - range.x ) / ( range.y - range.x ), 0.0, 1.0 ); } +// How strongly a line shows, as far as its net has come in, for cells of so many px: all of it +// from inkFull px, and less as they shrink, though never below the floor. +float strength( float shown, float pixels ) { + float ink = clamp( pixels / ${glsl(style.inkFull)}, 0.0, 1.0 ); +#ifdef CASING + return shown * max( pow( ink, ${glsl(style.casingCurve)} ), ${glsl(style.casingFloor)} ); +#else + return shown * max( pow( ink, ${glsl(style.inkCurve)} ), ${glsl(style.inkFloor)} ); +#endif +} + // How strongly this edge shows as part of the coarser nets it is in, each of which comes in as -// the one below it goes, or, when late, only as the grid's own is nearly gone. -float coarseStrength( float pixels, vec2 own, vec2 coarse, bool late ) { - float strength = 0.0; +// the one below it goes. They add up, so an edge of both nets stays whole as one hands over. +float coarseStrength( float pixels, vec2 own, vec2 coarse ) { + float sum = 0.0; for ( int level = 1; level <= 3; level++ ) { if ( exp2( float( level ) ) > instanceCell + 0.5 ) break; float below = 1.0 - fadeIn( float( level - 1 ), pixels, own, coarse ); - if ( late && level == 1 ) below *= below; - strength = max( strength, min( below, fadeIn( float( level ), pixels, own, coarse ) ) ); + float shown = min( below, fadeIn( float( level ), pixels, own, coarse ) ); + sum += strength( shown, pixels * exp2( float( level ) ) * ${glsl(style.coarseInk)} ); } - return strength; + return sum; } // As three's LineMaterial: a segment crossing the camera plane ends at the near plane. @@ -166,28 +187,26 @@ void main() { facing = abs( dot( normalize( normal ), perspective ? normalize( - centre ) : vec3( 0.0, 0.0, 1.0 ) ) ); float cellPixels = cell / pixel * max( facing, 0.04 ); float openPixels = cell / pixel; + // Ink follows cells as they crowd where the surface turns away, down to half. + float inkPixels = cell / pixel * max( facing, 0.5 ); // An edge of a coarser net also shows as part of it once the grid's own cells are too small, by // zoom alone: where the surface turns away the coarse nets would crowd as the grid does. bool coarse = instanceCell > 1.5; + vec2 coarseRange = vec2( ${glsl(style.coarseGone)}, ${glsl(style.coarseFull)} ); #ifdef CASING - vHalf = 0.5 * ${glsl(style.casingWidth)}; // Where the surface turns away, the casing still edges the core: it lifts only dark parts. vec2 own = vec2( ${glsl(style.casingGone)}, ${glsl(style.casingFull)} ); - vAlpha = smoothstep( own.x, own.y, openPixels ); - if ( coarse ) - vAlpha = max( vAlpha, smoothstep( 0.0, 1.0, coarseStrength( openPixels, own, - vec2( ${glsl(style.coarseCasingGone)}, ${glsl(style.coarseCasingFull)} ), false ) ) ); + vAlpha = strength( smoothstep( own.x, own.y, openPixels ), inkPixels ); + if ( coarse ) vAlpha = min( 1.0, vAlpha + coarseStrength( openPixels, own, coarseRange ) ); + vHalf = 0.5 * mix( ${glsl(style.casingThin)}, ${glsl(style.casingWidth)}, + smoothstep( ${glsl(style.inkWide)}, 1.0, vAlpha ) ); float cap = 0.0; #else - // The first coarse net's core comes in late, so on a light part the grid covers no more than - // at its default density. vec2 own = vec2( ${glsl(style.coreGone)}, ${glsl(style.coreFull)} ); - float strength = fadeIn( 0.0, cellPixels, own, own ); - if ( coarse ) - strength = max( strength, coarseStrength( openPixels, own, - vec2( ${glsl(style.coarseGone)}, ${glsl(style.coarseFull)} ), true ) ); - vHalf = 0.5 * mix( ${glsl(style.coreThin)}, ${glsl(style.coreWidth)}, strength ); - vAlpha = smoothstep( 0.0, 1.0, strength ); + vAlpha = strength( smoothstep( 0.0, 1.0, fadeIn( 0.0, cellPixels, own, own ) ), inkPixels ); + if ( coarse ) vAlpha = min( 1.0, vAlpha + coarseStrength( openPixels, own, coarseRange ) ); + vHalf = 0.5 * mix( ${glsl(style.coreThin)}, ${glsl(style.coreWidth)}, + smoothstep( ${glsl(style.inkWide)}, 1.0, vAlpha ) ); float cap = vHalf; #endif // A pixel beyond the line's edge, for antialiasing. @@ -421,7 +440,7 @@ function SurfaceWarpGrid({ warp }: { warp: WarpSession }) { shifts.needsUpdate = true; const uniforms = { resolution: { value: new Vector2(1, 1) }, - cell: { value: typicalLength(path.length) }, + cell: { value: warpGridCell(path) }, shifted: { value: false }, shifts: { value: shifts }, }; @@ -652,7 +671,7 @@ function SurfaceWarpGrid({ warp }: { warp: WarpSession }) { if (largest * 2 ** level > (level ? coarseGone : gone)) return drawing.levelEnd[level]; return 0; }; - counts.casing = shown(style.casingGone, style.coarseCasingGone); + counts.casing = shown(style.casingGone, style.coarseGone); counts.core = shown(style.coreGone, style.coarseGone); casing.visible = counts.casing > 0; core.visible = counts.core > 0; diff --git a/src/core/warp-grid-path.ts b/src/core/warp-grid-path.ts index 1188645..4fa8c47 100644 --- a/src/core/warp-grid-path.ts +++ b/src/core/warp-grid-path.ts @@ -22,6 +22,8 @@ export interface WarpGridPath { along: Float32Array; /** World rest length of each grid edge. */ length: Float32Array; + /** 1 for each edge along the grid's outline: its fixed border or the part's open edge. */ + outline: Uint8Array; /** The geometry vertex holding each node's written position; null until traced. */ nodeVertex: Uint32Array | null; /** Per edge, two geometry vertices whose normals the line takes at its nodes; null until traced. */ @@ -134,27 +136,159 @@ export function warpGridEvenPoints( } } -/** The grid's edges as straight chords: what is drawn until a path is traced. */ -export function warpGridChords(model: WarpModel): WarpGridPath { - const { edgeStart, edges } = model.grid; - let count = 0; - for (let n = 0; n + 1 < edgeStart.length; n++) - for (let k = edgeStart[n]; k < edgeStart[n + 1]; k++) if (edges[k] > n) count++; - const ends = new Uint32Array(count * 2), - length = new Float32Array(count); +/** + * Lines a node inside the grid draws to its outline at most, and the least angle between any two + * of its lines for one more to be drawn. + */ +export const warpGridRimLimits = { lines: 4, apart: (40 * Math.PI) / 180 }; + +/** + * The grid edges drawn, as node pairs, and which lie along its outline. The grid keeps every + * vertex of its fixed border and of the part's open edge, so where its inside is sparse against + * them, a node inside would draw a fan of lines out to dozens of them. Edges between nodes inside, + * and along the outline, are all drawn; from each node inside, only a few to the outline, each as + * far as can be from its other lines, shortest first; edges across the inside between two outline + * nodes, none. + */ +export function warpGridDrawnEdges(model: WarpModel, limits = warpGridRimLimits) { + const { edgeStart, edges, triangles, fixed } = model.grid; const rest = model.restNodes; - for (let n = 0, e = 0; n + 1 < edgeStart.length; n++) + const nodeCount = edgeStart.length - 1; + // Grid triangles at each edge, to find the outline: edges of one triangle. + const at = (n: number, m: number) => { + for (let k = edgeStart[n]; k < edgeStart[n + 1]; k++) if (edges[k] === m) return k; + return -1; + }; + const faces = new Uint8Array(edges.length); + const normal = new Float64Array(nodeCount * 3); + for (let t = 0; t < triangles.length; t += 3) { + const a = triangles[t], + b = triangles[t + 1], + c = triangles[t + 2]; + for (const [n, m] of [ + [a, b], + [b, c], + [c, a], + ]) { + for (const k of [at(n, m), at(m, n)]) if (k >= 0 && faces[k] < 255) faces[k]++; + } + const ux = rest[b * 3] - rest[a * 3], + uy = rest[b * 3 + 1] - rest[a * 3 + 1], + uz = rest[b * 3 + 2] - rest[a * 3 + 2], + vx = rest[c * 3] - rest[a * 3], + vy = rest[c * 3 + 1] - rest[a * 3 + 1], + vz = rest[c * 3 + 2] - rest[a * 3 + 2]; + const x = uy * vz - uz * vy, + y = uz * vx - ux * vz, + z = ux * vy - uy * vx; + for (const n of [a, b, c]) { + normal[n * 3] += x; + normal[n * 3 + 1] += y; + normal[n * 3 + 2] += z; + } + } + const rim = new Uint8Array(nodeCount); + for (let n = 0; n < nodeCount; n++) { + if (fixed[n]) rim[n] = 1; + for (let k = edgeStart[n]; k < edgeStart[n + 1]; k++) + if (faces[k] === 1) rim[n] = rim[edges[k]] = 1; + } + const length = (n: number, m: number) => + Math.hypot( + rest[m * 3] - rest[n * 3], + rest[m * 3 + 1] - rest[n * 3 + 1], + rest[m * 3 + 2] - rest[n * 3 + 2], + ); + // Per node inside, the outline nodes it draws a line to. + const chosen = new Set(); + const angles: number[] = [], + candidates: { m: number; angle: number; length: number }[] = []; + const turn = (a: number, b: number) => { + const d = Math.abs(a - b) % (2 * Math.PI); + return Math.min(d, 2 * Math.PI - d); + }; + for (let n = 0; n < nodeCount; n++) { + if (rim[n]) continue; + angles.length = candidates.length = 0; + // Directions in the plane across the node's normal. + let nx = normal[n * 3], + ny = normal[n * 3 + 1], + nz = normal[n * 3 + 2]; + const l = Math.hypot(nx, ny, nz) || 1; + nx /= l; + ny /= l; + nz /= l; + const ax = Math.abs(nx) < 0.9 ? 1 : 0, + ay = ax ? 0 : 1; + let ux = ay * nz, + uy = -ax * nz, + uz = ax * ny - ay * nx; + const lu = Math.hypot(ux, uy, uz) || 1; + ux /= lu; + uy /= lu; + uz /= lu; + const vx = ny * uz - nz * uy, + vy = nz * ux - nx * uz, + vz = nx * uy - ny * ux; + for (let k = edgeStart[n]; k < edgeStart[n + 1]; k++) { + const m = edges[k]; + const dx = rest[m * 3] - rest[n * 3], + dy = rest[m * 3 + 1] - rest[n * 3 + 1], + dz = rest[m * 3 + 2] - rest[n * 3 + 2]; + const angle = Math.atan2(dx * vx + dy * vy + dz * vz, dx * ux + dy * uy + dz * uz); + if (rim[m]) candidates.push({ m, angle, length: length(n, m) }); + else angles.push(angle); + } + candidates.sort((p, q) => p.length - q.length); + for (let drawn = 0; drawn < limits.lines; drawn++) { + let best = -1, + widest = -1; + for (let c = 0; c < candidates.length; c++) { + if (candidates[c].m < 0) continue; + let least = Infinity; + for (const angle of angles) least = Math.min(least, turn(angle, candidates[c].angle)); + if (least > widest) { + widest = least; + best = c; + } + } + if (best < 0 || widest < limits.apart) break; + angles.push(candidates[best].angle); + chosen.add(n * nodeCount + candidates[best].m); + candidates[best].m = -1; + } + } + const pairs: number[] = [], + outline: number[] = []; + for (let n = 0; n < nodeCount; n++) for (let k = edgeStart[n]; k < edgeStart[n + 1]; k++) { const m = edges[k]; if (m <= n) continue; - ends[e * 2] = n; - ends[e * 2 + 1] = m; - length[e++] = Math.hypot( - rest[m * 3] - rest[n * 3], - rest[m * 3 + 1] - rest[n * 3 + 1], - rest[m * 3 + 2] - rest[n * 3 + 2], - ); + const along = faces[k] === 1; + if (rim[n] && rim[m] && !along) continue; + if (rim[n] !== rim[m] && !chosen.has(rim[n] ? m * nodeCount + n : n * nodeCount + m)) + continue; + pairs.push(n, m); + outline.push(along ? 1 : 0); } + return { ends: Uint32Array.from(pairs), outline: Uint8Array.from(outline) }; +} + +/** The grid's drawn edges as straight chords: what is drawn until a path is traced. */ +export function warpGridChords(model: WarpModel): WarpGridPath { + const { ends, outline } = warpGridDrawnEdges(model); + const count = outline.length; + const length = new Float32Array(count); + const rest = model.restNodes; + for (let e = 0; e < count; e++) { + const n = ends[e * 2], + m = ends[e * 2 + 1]; + length[e] = Math.hypot( + rest[m * 3] - rest[n * 3], + rest[m * 3 + 1] - rest[n * 3 + 1], + rest[m * 3 + 2] - rest[n * 3 + 2], + ); + } return { ends, start: new Uint32Array(count + 1), @@ -163,6 +297,7 @@ export function warpGridChords(model: WarpModel): WarpGridPath { t: new Float32Array(0), along: new Float32Array(0), length, + outline, nodeVertex: null, endVertex: null, crossings: null, @@ -260,7 +395,7 @@ export function* traceWarpGridPath( limits = warpGridPathLimits, ): Generator { const chords = warpGridChords(model); - const { ends, length } = chords; + const { ends, length, outline } = chords; const { region, grid, restWorld: p, index } = model; const { weldOf, weldedCount, triangles, faces, adjacencyStart, adjacency } = region; const slice = 1 << 16; @@ -666,6 +801,7 @@ export function* traceWarpGridPath( for (let i = 0; i < edgeCount; i++) drawnCount += drawn[i]; const outEnds = new Uint32Array(drawnCount * 2), outLength = new Float32Array(drawnCount), + outOutline = new Uint8Array(drawnCount), outEndVertex = new Uint32Array(drawnCount * 2), start = new Uint32Array(drawnCount + 1); const crossings: WarpGridCrossings = { @@ -688,6 +824,7 @@ export function* traceWarpGridPath( outEndVertex[d * 2] = endVertex[e * 2]; outEndVertex[d * 2 + 1] = endVertex[e * 2 + 1]; outLength[d] = length[e]; + outOutline[d] = outline[e]; start[++d] = kept.size; } const nodeVertex = new Uint32Array(nodeCount); @@ -700,6 +837,7 @@ export function* traceWarpGridPath( t: kept.t.slice(0, kept.size), along: kept.along.slice(0, kept.size), length: outLength, + outline: outOutline, nodeVertex, endVertex: outEndVertex, crossings, @@ -853,6 +991,15 @@ export function typicalLength(lengths: ArrayLike) { return sorted[sorted.length >> 1] || 1; } +/** + * A path's typical cell: the middle of its edges' lengths, leaving out its outline, which keeps + * every border vertex and so runs at the mesh's own resolution. + */ +export function warpGridCell(path: Pick) { + const inside = path.length.filter((_, e) => !path.outline[e]); + return typicalLength(inside.length ? inside : path.length); +} + /** * Per drawn edge, the coarsest level whose net holds it: 0 for the grid alone. Level k picks * nodes of level k - 1's net about 2^k typical edges apart along it, gives each of its nodes to @@ -879,7 +1026,7 @@ export function warpGridLevels( incident[fill[ends[e * 2]]++] = e; incident[fill[ends[e * 2 + 1]]++] = e; } - const cell = typicalLength(length); + const cell = warpGridCell(path); const distance = new Float64Array(nodeCount), near = new Float64Array(nodeCount), owner = new Int32Array(nodeCount), diff --git a/tests/e2e/helpers/warp-grid.ts b/tests/e2e/helpers/warp-grid.ts index 7ad09ef..92119a4 100644 --- a/tests/e2e/helpers/warp-grid.ts +++ b/tests/e2e/helpers/warp-grid.ts @@ -673,14 +673,15 @@ const luminanceSource = ` /** * WCAG contrast of the grid against the surface beside it, per part colour. Samples are the - * middles of segments on surface facing the camera squarely, away from nodes; at each, `core` + * middles of segments on surface facing the camera at least as squarely as `facing`, the cosine + * of the angle between the surface's normal and the view, away from nodes; at each, `core` * is the contrast at the line's centre (the pixels whose centres the 1.5 px core covers) and `line` the best * across the line's full width, each between the drawn image and the same pixels with the grid * hidden. Returns the worst and the fifth-percentile sample for each colour. */ -export async function gridContrast(page: Page, colors: string[], partId = 'ball') { +export async function gridContrast(page: Page, colors: string[], partId = 'ball', facing = 0.5) { return page.evaluate( - async ({ colors, luminanceSource, viewDepthsSource, partId }) => { + async ({ colors, luminanceSource, viewDepthsSource, partId, facing }) => { const luminance = new Function(luminanceSource)() as (p: Uint8Array, i: number) => number; const viewDepths = new Function(viewDepthsSource)(); const urls = performance.getEntriesByType('resource').map((entry) => entry.name); @@ -742,7 +743,7 @@ export async function gridContrast(page: Page, colors: string[], partId = 'ball' const view = camera.isOrthographicCamera ? forward.clone().negate() : eye.clone().sub(p).normalize(); - if (normal.dot(view) < 0.5) continue; + if (normal.dot(view) < facing) continue; const depth = -p.clone().applyMatrix4(camera.matrixWorldInverse).z; a.project(camera); b.project(camera); @@ -811,14 +812,15 @@ export async function gridContrast(page: Page, colors: string[], partId = 'ball' root.invalidate(); return { samples: samples.length, results }; }, - { colors, luminanceSource, viewDepthsSource, partId }, + { colors, luminanceSource, viewDepthsSource, partId, facing }, ); } /** * Over every pixel of the warped part: the share the grid touches at all (any channel differs by - * more than 12 levels) and the share it changes noticeably (luminance contrast above 1.5:1), - * between the drawn image and the same view with the grid hidden. `color`, when given, is the + * more than 12 levels), the share it changes perceptibly (luminance contrast above 1.2:1) and the + * share it changes noticeably (above 1.5:1), between the drawn image and the same view with the + * grid hidden. `color`, when given, is the * part's colour while measuring. */ export async function gridCoverage(page: Page, partId = 'ball', color?: string) { @@ -872,6 +874,7 @@ export async function gridCoverage(page: Page, partId = 'ball', color?: string) root.invalidate(); let pixels = 0, touched = 0, + perceptible = 0, noticeable = 0; for (let i = 0; i < width * height * 4; i += 4) { if (silhouette[i] < 128) continue; @@ -885,11 +888,14 @@ export async function gridCoverage(page: Page, partId = 'ball', color?: string) ) touched++; const [l1, l2] = [luminance(shown, i), luminance(bare, i)].sort((m, n) => n - m); - if ((l1 + 0.05) / (l2 + 0.05) > 1.5) noticeable++; + const contrast = (l1 + 0.05) / (l2 + 0.05); + if (contrast > 1.2) perceptible++; + if (contrast > 1.5) noticeable++; } return { pixels: pixels / (width / size.width) ** 2, touched: touched / pixels, + perceptible: perceptible / pixels, noticeable: noticeable / pixels, }; }, diff --git a/tests/e2e/warp-grid.spec.ts b/tests/e2e/warp-grid.spec.ts index 496bb23..b2f199d 100644 --- a/tests/e2e/warp-grid.spec.ts +++ b/tests/e2e/warp-grid.spec.ts @@ -56,22 +56,36 @@ function coveredBox() { const distinct = [...Array.from({ length: 24 }, (_, i) => distinctColor(i)), '#ffffff']; const nearBlack = '#1c1c1c'; -/** At default density the grid's dark core stands out at its centre on every colour. */ +/** + * Lines carry full ink only where cells are large on screen: 40 px or more. Contrast is measured + * there, on surface facing the camera this squarely, so its cells keep nearly their full size. + */ +const squarely = 0.9; + +/** Where cells are large on screen, the grid's dark core stands out at its centre on every colour. */ async function expectCoreContrast(page: Page, label: string) { - const { samples, results } = await gridContrast(page, distinct); + const { cell } = await partAcross(page); + expect(cell * squarely, `${label}: cells on screen`).toBeGreaterThan(40); + const { samples, results } = await gridContrast(page, distinct, 'ball', squarely); note(`${label} core`, results); - expect(samples, label).toBeGreaterThan(150); + expect(samples, label).toBeGreaterThan(100); for (const { color, core } of results) expect(core.low, `${label} ${color}: fifth percentile at the core`).toBeGreaterThan(3); } -/** On a near-black part, the light casing makes the line stand out. */ +/** Where cells are large on screen, on a near-black part, the light casing makes the line stand out. */ async function expectCasingContrast(page: Page, label: string) { - const { results } = await gridContrast(page, [nearBlack]); + const { results } = await gridContrast(page, [nearBlack], 'ball', squarely); note(`${label} casing`, results); expect(results[0].line.low, `${label}: fifth percentile across the line`).toBeGreaterThan(3); } +/** + * The visibility floor: on every Distinct colour, white and a near-black part, the grid changes + * the luminance of at least this share of the part's pixels by more than 1.2:1. + */ +const visible = 0.08; + test('the grid lies along a curved part, all of its facing side drawn and none of the rest', async ({ page, }) => { @@ -592,40 +606,117 @@ test('on a scan-like part, failed walks are drawn along the surface, never acros expect(gap.rerouted).toBe(gap.failed); // What is measured is drawn and shows: segments between points, some along rerouted edges. expect(gap.segments).toBeGreaterThan(gap.edges); - expect(gap.reroutedSamples).toBeGreaterThan(100); + expect(gap.reroutedSamples).toBeGreaterThan(50); expect(cover.touched).toBeGreaterThan(0.05); expect(gap.worst).toBeLessThan(0.05); } }); -test('at default density the grid leaves most of the part as it is, and the finest grid more', async ({ +test('at the whole-part default the grid leaves most of the part as it is, and no more at any density', async ({ page, }) => { + test.setTimeout(180_000); await layGrid(page, ball()); - // About 300 px across, as a part this size is with a whole model in view. - await lookFrom(page, [0, 0.2, 1], 125); - const { across } = await partAcross(page); - expect(across).toBeGreaterThan(280); - expect(across).toBeLessThan(330); - for (const [level, most] of [ - [3, 0.34], - [6, 0.25], + const light = ['#d4a272', ...distinct]; + // About 500 px across, as a whole scanned part fills the view, and 300 px, as with a model. + for (const [across, distance] of [ + [500, 80], + [300, 125], ] as const) { + await lookFrom(page, [0, 0.2, 1], distance); + const { across: width } = await partAcross(page); + expect(width).toBeGreaterThan(across * 0.93); + expect(width).toBeLessThan(across * 1.1); + for (const level of [5, 3, 6]) { + // The whole-part default is held to every colour; the others to the part's own and white. + if (level !== 5 && across === 500) continue; + await setDensity(page, level); + for (const [view, direction] of [ + ['front', [0, 0.2, 1]], + ['side', [1, 0.5, 0.4]], + ] as const) { + await lookFrom(page, [...direction], distance); + const label = `density ${level}, ${across} px, ${view}`; + const noticeable: Record = {}; + for (const color of level === 5 ? light : ['#d4a272', '#ffffff']) + noticeable[color] = (await gridCoverage(page, 'ball', color)).noticeable; + noticeable[nearBlack] = (await gridCoverage(page, 'ball', nearBlack)).noticeable; + note(label, noticeable); + for (const [color, share] of Object.entries(noticeable)) + expect(share, `${label} ${color}`).toBeLessThan(color === nearBlack ? 0.2 : 0.16); + } + } + } +}); + +test('the grid stays visible on every Distinct colour, white and a near-black part', async ({ + page, +}) => { + test.setTimeout(240_000); + await layGrid(page, ball()); + for (const level of [3, 5, 6]) { await setDensity(page, level); - for (const [view, direction] of [ - ['front', [0, 0.2, 1]], - ['side', [1, 0.5, 0.4]], - ] as const) { - await lookFrom(page, [...direction], 125); - const cover = await gridCoverage(page); - note(`density ${level}, ${view}`, cover); - expect(cover.noticeable, `density ${level}, ${view}`).toBeLessThan(most); - // The grid is still there. - expect(cover.noticeable, `density ${level}, ${view}`).toBeGreaterThan(0.1); + for (const distance of [80, 125, 200]) { + await lookFrom(page, [0, 0.2, 1], distance); + const label = `density ${level}, ${distance} mm`; + const perceptible: Record = {}; + for (const color of [...distinct, nearBlack]) + perceptible[color] = (await gridCoverage(page, 'ball', color)).perceptible; + note(label, perceptible); + for (const [color, share] of Object.entries(perceptible)) + expect(share, `${label} ${color}`).toBeGreaterThan(visible); } } }); +test('the plate at the coarsest density draws its outline and a few lines inside, not a fan', async ({ + page, +}) => { + await layGrid(page, new PlaneGeometry(40, 40, 80, 80), flat, [], 0); + const pulled = await pullPlate(page); + expect(pulled.rise).toBeGreaterThan(1.8); + await gridTraced(page); + const lines = await page.evaluate(async () => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const root = (await import(urls.find((url) => url.includes('/@react-three_fiber.js'))!))._roots + .get(document.querySelector('canvas')) + .store.getState(); + const { useEditor } = await import( + urls.find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))! + ); + const { model } = useEditor.getState().warp; + const { path } = root.scene.getObjectByName('warp-grid').userData.drawing; + const p = model.restNodes; + // In the world the plate lies flat at y = 15, its border 20 mm out along x and z. + const border = (n: number) => + Math.abs(Math.abs(p[n * 3]) - 20) < 1e-4 || Math.abs(Math.abs(p[n * 3 + 2]) - 20) < 1e-4; + const count = (ends: ArrayLike) => { + const lines = new Map(); + for (let e = 0; e < ends.length; e += 2) { + const [a, b] = [ends[e], ends[e + 1]]; + if (border(a) === border(b)) continue; + const inside = border(a) ? b : a; + lines.set(inside, (lines.get(inside) ?? 0) + 1); + } + return Math.max(0, ...lines.values()); + }; + const { edgeStart, edges } = model.grid; + const grid: number[] = []; + for (let n = 0; n + 1 < edgeStart.length; n++) + for (let k = edgeStart[n]; k < edgeStart[n + 1]; k++) grid.push(n, edges[k]); + return { grid: count(grid) / 2, drawn: count(path.ends) }; + }); + note('lines to the border', lines); + // The grid itself fans out from a node inside to dozens of border nodes; the drawing does not. + expect(lines.grid).toBeGreaterThan(50); + expect(lines.drawn).toBeGreaterThan(0); + expect(lines.drawn).toBeLessThanOrEqual(4); + await lookFrom(page, [0.1, 1, 0.5], 80); + const cover = await gridCoverage(page, 'ball'); + note('cover', cover); + expect(cover.noticeable).toBeLessThan(0.05); +}); + test('at the highest density a coarser net of the grid stays readable as you zoom out', async ({ page, }) => { @@ -639,43 +730,48 @@ test('at the highest density a coarser net of the grid stays readable as you zoo await lookFrom(page, [0, 0.2, 1], 125); const bar: Record = {}; for (const color of [purple, nearBlack]) - bar[color] = Math.max(0.34, (await gridCoverage(page, 'ball', color)).noticeable); + bar[color] = Math.max(0.16, (await gridCoverage(page, 'ball', color)).noticeable); await setDensity(page, 6); // From about 400 px across to 150, where the finest grid's own cells are too small to show. - const steps: Record = { [purple]: [], [nearBlack]: [] }; + const steps: Record = { + [purple]: [], + [nearBlack]: [], + }; for (let distance = 100; distance <= 260; distance *= 1.1) { await lookFrom(page, [0, 0.2, 1], distance); - for (const color of [purple, nearBlack]) - steps[color].push((await gridCoverage(page, 'ball', color)).noticeable); + for (const color of [purple, nearBlack]) { + const { perceptible, noticeable } = await gridCoverage(page, 'ball', color); + steps[color].push({ perceptible, noticeable }); + } } note('bar', bar); - note('noticeable', steps); + note('steps', steps); for (const [color, shares] of Object.entries(steps)) { - for (const share of shares) expect(share, `${color}: still a grid`).toBeGreaterThan(0.1); + for (const { perceptible } of shares) + expect(perceptible, `${color}: still a grid`).toBeGreaterThan(visible); // About 300 px across it covers no more than the default grid does. - expect(shares[3], color).toBeLessThan(bar[color]); + expect(shares[3].noticeable, color).toBeLessThan(bar[color]); // No step of the zoom changes much of what it covers at once. for (let i = 1; i < shares.length; i++) - expect(Math.abs(shares[i] - shares[i - 1]), `${color}, step ${i}`).toBeLessThan(0.12); + expect( + Math.abs(shares[i].noticeable - shares[i - 1].noticeable), + `${color}, step ${i}`, + ).toBeLessThan(0.12); } }); -test('the core stands out on Distinct colours and white, and the casing on a near-black part', async ({ +test('where cells are large on screen, the core stands out on Distinct colours and white, and the casing on a near-black part', async ({ page, }) => { await layGrid(page, ball()); - for (const [zoom, distance] of [ - ['overview', 125], - ['close', 70], - ] as const) - for (const [view, direction] of [ - ['front', [0, 0.2, 1]], - ['side', [1, 0.5, 0.4]], - ] as const) { - await lookFrom(page, [...direction], distance); - await expectCoreContrast(page, `${zoom}, ${view}`); - await expectCasingContrast(page, `${zoom}, ${view}`); - } + for (const [view, direction] of [ + ['front', [0, 0.2, 1]], + ['side', [1, 0.5, 0.4]], + ] as const) { + await lookFrom(page, [...direction], 70); + await expectCoreContrast(page, `close, ${view}`); + await expectCasingContrast(page, `close, ${view}`); + } }); test('the line stands out in every lighting', async ({ page }) => { @@ -684,9 +780,14 @@ test('the line stands out in every lighting', async ({ page }) => { for (const preset of ['studio', 'soft', 'headlight', 'dramatic']) { await setLighting(page, preset); // Where a preset leaves the surface in shadow, the casing carries the line. - const { samples, results } = await gridContrast(page, [...distinct, nearBlack]); + const { samples, results } = await gridContrast( + page, + [...distinct, nearBlack], + 'ball', + squarely, + ); note(preset, results); - expect(samples).toBeGreaterThan(150); + expect(samples).toBeGreaterThan(100); for (const { color, line } of results) expect(line.low, `${preset} ${color}: fifth percentile across the line`).toBeGreaterThan(3); } @@ -706,7 +807,8 @@ test('the grid is whole and stands out with an orthographic camera', async ({ pa expect(grid.shares.core.back.shown, view).toBeLessThan(0.002); expect(grid.shares.casing.back.shown, view).toBeLessThan(0.002); } - await lookFrom(page, [0, 0.2, 1], 200); + // Zoomed in until cells are large on screen. + await lookFrom(page, [0, 0.2, 1], 200, 20); await expectCoreContrast(page, 'orthographic'); }); diff --git a/tests/unit/warp-grid-path.test.ts b/tests/unit/warp-grid-path.test.ts index 3580d3e..8fee5ad 100644 --- a/tests/unit/warp-grid-path.test.ts +++ b/tests/unit/warp-grid-path.test.ts @@ -22,6 +22,7 @@ import { buildWarpModel, type WarpModel } from '../../src/core/warp-model'; import { traceWarpGridPathNow, warpGridChords, + warpGridDrawnEdges, WarpGridDrawing, warpGridPathLimits, warpGridSegments, @@ -206,6 +207,121 @@ describe('grid paths', () => { }); }); +/** + * The grid's edges and the drawn ones, by node pair, with each node inside the outline's drawn + * lines to it and grid edges to it. `rim` says which nodes are on the outline. + */ +function linesToOutline(m: WarpModel, rim: (n: number) => boolean) { + const { edgeStart, edges } = m.grid; + const nodeCount = edgeStart.length - 1; + const { ends } = warpGridDrawnEdges(m); + const drawn = new Set(); + for (let e = 0; e < ends.length; e += 2) + drawn.add(Math.min(ends[e], ends[e + 1]) * nodeCount + Math.max(ends[e], ends[e + 1])); + const inside: { node: number; lines: number[]; edges: number }[] = []; + let gridEdges = 0; + for (let n = 0; n < nodeCount; n++) { + const node = { node: n, lines: [] as number[], edges: 0 }; + for (let k = edgeStart[n]; k < edgeStart[n + 1]; k++) { + const m = edges[k]; + if (m > n) gridEdges++; + if (rim(n) || !rim(m)) continue; + node.edges++; + if (drawn.has(Math.min(n, m) * nodeCount + Math.max(n, m))) node.lines.push(m); + } + if (!rim(n)) inside.push(node); + } + return { drawn, nodeCount, inside, gridEdges }; +} + +/** The most lines a node inside may draw to the outline. */ +const handful = 4; + +describe('drawn grid edges', () => { + it('join each node inside to the outline by a few lines spread around it, never a fan', async () => { + // The 80 by 80 plate at the coarsest density: every border vertex is a node, and few are not. + const m = await model(new PlaneGeometry(40, 40, 80, 80), 0); + const p = m.restNodes; + const onBorder = (n: number) => + Math.abs(Math.abs(p[n * 3]) - 20) < 1e-6 || Math.abs(Math.abs(p[n * 3 + 1]) - 20) < 1e-6; + const { drawn, nodeCount, inside } = linesToOutline(m, onBorder); + expect(inside.length).toBeGreaterThan(0); + expect(Math.max(...inside.map((node) => node.edges))).toBeGreaterThan(50); + for (const { node, lines, edges } of inside) { + expect(lines.length).toBeGreaterThan(0); + expect(lines.length).toBeLessThanOrEqual(Math.min(edges, handful)); + // Every two lines from the node turn apart by 30° or more. + const angles = lines.map((m) => + Math.atan2(p[m * 3 + 1] - p[node * 3 + 1], p[m * 3] - p[node * 3]), + ); + for (let i = 0; i < angles.length; i++) + for (let j = i + 1; j < angles.length; j++) { + const turn = Math.abs(angles[i] - angles[j]) % (2 * Math.PI); + expect(Math.min(turn, 2 * Math.PI - turn)).toBeGreaterThanOrEqual(Math.PI / 6); + } + } + // The border is drawn whole, and nothing crosses the inside from one border node to another. + const side = (n: number) => + Math.abs(Math.abs(p[n * 3]) - 20) < 1e-6 + ? `x${Math.sign(p[n * 3])}` + : `y${Math.sign(p[n * 3 + 1])}`; + let along = 0; + for (const key of drawn) { + const a = Math.floor(key / nodeCount), + b = key % nodeCount; + if (!onBorder(a) || !onBorder(b)) continue; + along++; + const corner = (n: number) => + Math.abs(Math.abs(p[n * 3]) - 20) < 1e-6 && Math.abs(Math.abs(p[n * 3 + 1]) - 20) < 1e-6; + if (!corner(a) && !corner(b)) expect(side(a)).toBe(side(b)); + } + expect(along).toBe(320); + }); + + it("draw a painted region's fixed border as its outline and every edge between free nodes", async () => { + const geometry = new PlaneGeometry(40, 40, 80, 80); + const centres = new Vector3(); + const faces: number[] = []; + const index = geometry.index!, + position = geometry.getAttribute('position'); + for (let f = 0; f < index.count / 3; f++) { + centres.set(0, 0, 0); + for (let k = 0; k < 3; k++) + centres.add(new Vector3().fromBufferAttribute(position, index.getX(f * 3 + k))); + if (centres.divideScalar(3).length() < 8) faces.push(f); + } + const m = await buildWarpModel({ + positions: new Float32Array(position.array), + index: new Uint32Array(index.array), + normals: null, + matrix: new Matrix4().elements.slice(), + faces, + density: 0, + }); + const fixed = (n: number) => m.grid.fixed[n] === 1; + expect(m.grid.fixed.reduce((a, b) => a + b, 0)).toBeGreaterThan(100); + const { drawn, nodeCount, inside } = linesToOutline(m, fixed); + for (const { lines } of inside) expect(lines.length).toBeLessThanOrEqual(handful); + const { edgeStart, edges } = m.grid; + let rimEdges = 0; + for (let n = 0; n < nodeCount; n++) + for (let k = edgeStart[n]; k < edgeStart[n + 1]; k++) { + const o = edges[k]; + if (o <= n) continue; + if (!fixed(n) && !fixed(o)) expect(drawn.has(n * nodeCount + o)).toBe(true); + if (fixed(n) && fixed(o) && drawn.has(n * nodeCount + o)) rimEdges++; + } + // The outline closes: one edge per fixed node around the disc. + expect(rimEdges).toBe(m.grid.fixed.reduce((a, b) => a + b, 0)); + }); + + it('draw every edge of a grid without an outline', async () => { + const m = await model(sphere(), 3); + const { drawn, gridEdges } = linesToOutline(m, () => false); + expect(drawn.size).toBe(gridEdges); + }); +}); + /** The furthest any drawn segment strays from a surface, sampled along each segment. */ function worstGap(surface: BufferGeometry, drawn: Float32Array) { const bvh = new MeshBVH(surface); From 486773b6811a8aceecb83fd64b1a84d2a1a9f047 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Wed, 18 Nov 2026 19:05:13 -0800 Subject: [PATCH 21/25] Restore feather, paint and selection with warp undo --- .../specs/2026-11-17-warp-handles-design.md | 46 ++++-- src/components/WarpControls.tsx | 4 +- src/core/store.ts | 95 +++++++++--- src/core/warp-handles.ts | 46 +++++- tests/e2e/warp-grid.spec.ts | 70 +++++++++ tests/e2e/warp-strokes.spec.ts | 138 ++++++++++++++++++ tests/unit/free-transform.test.ts | 18 +-- tests/unit/transform-selection.test.ts | 1 + tests/unit/warp-feather-session.test.ts | 40 +++++ tests/unit/warp-session.test.ts | 137 ++++++++++++++++- tests/unit/warp-strokes.test.ts | 54 +++++++ 11 files changed, 594 insertions(+), 55 deletions(-) diff --git a/docs/superpowers/specs/2026-11-17-warp-handles-design.md b/docs/superpowers/specs/2026-11-17-warp-handles-design.md index 1da8ab3..d9178f3 100644 --- a/docs/superpowers/specs/2026-11-17-warp-handles-design.md +++ b/docs/superpowers/specs/2026-11-17-warp-handles-design.md @@ -212,13 +212,15 @@ it withholds the targets on each sample's nodes and those beside them, settles a surface as shown, and for each sample the trial moves by more than 0.005 mm, the pin-hold rule's limit, withholds the next ring of grid edges around it, up to twelve rounds. The seam readout then reports the gap left there, and the panel says that Close gap leaves the seam open around points -the user placed. On two plates 1 mm apart, laid whole (2,129 nodes), a held point moved 0.00007 mm -and a held line's samples at most 0.0027 mm, where the seam had moved them 0.78 and 0.72 mm. +the user placed, also when it withholds every target and so changes nothing and adds no step. On +two plates 1 mm apart, laid whole (2,129 nodes), a held point moved 0.00007 mm and a held line's +samples at most 0.0027 mm, where the seam had moved them 0.78 and 0.72 mm. ### 4. Radius and falloff Every handle has a **radius** in mm and a **falloff** from 0 to 100 %, edited in the Control -points section for the selected handles. New handles take the last values set. Until the user +points section for the selected handles. New handles take the last values set; with nothing +selected, setting one is a session undo step of its own. Until the user sets a radius, a new point takes the larger of 6 % of the part's size and 4.5 node spacings where it is clicked, no more than a quarter of the region's extent. Radius 0 is a bare point; automatic points are radius 0. Effectively whole regions are laid at the 2,000-node level and @@ -305,7 +307,10 @@ monotonically from the point, is 0.957 h at a tenth of the radius, within 0.08 h Region stage, painted regions only: **Feather edge**, off by default, with a width in mm (fitted logarithmic slider, starting at Warp's brush radius). The choice is remembered for -the page session. Off, or width 0, builds exactly today's region with its fixed edge. +the page session and starts each new session. A session keeps its own switch and width, which the +grid is laid with and which undoing back to a layout restores with it, so Edit region then Lay +grid with nothing changed keeps the grid. Off, or width 0, builds exactly today's region with its +fixed edge. - **Growth.** The build worker keeps the painted-face mask, builds whole-mesh welded topology once, and runs a bounded Dijkstra over world-length edges outward from the @@ -418,9 +423,15 @@ its most heavily bound one; an area also moves the free nodes on its faces. Ever seeds the reach's paths, and straight-line distance is measured from the samples and an area's outline. Taking every node a sample is bound to, as first written, made the ridge's width depend on which triangles the samples fell in: a binding reaches one to one and a half spacings, unevenly to -either side, and two samplings of one stroke differed by a quarter of the lift. Section 4 applies -with distance measured from the footprint: radius 0 gives a continuous ridge or a rigid patch, and a -radius above 0 adds the smooth skirt. +either side, and two samplings of one stroke differed by a quarter of the lift. A short curved line +is the exception: one no longer than five node spacings that stands off its chord by more than +3.5 % of it, with a radius between one and four spacings, moves every free node its samples are +bound to. There the guides fade across those nodes while the samples pull them whole, and the +surface between the samples rose: on a small patch painted on the 35 mm Tomb Crawler at the default +density, a 1 mm line lifted 0.5 mm stood between 0.36 and 0.66 mm, and moving those nodes as one +keeps it between 0.45 and 0.51 mm, and at 41 spots along it between 0.48 and 0.51 mm. A whole part's default radius is wider, and longer or straighter +lines keep the narrower footprint. Section 4 applies with distance measured from the footprint: +radius 0 gives a continuous ridge or a rigid patch, and a radius above 0 adds the smooth skirt. Acceptance: along a line handle moved by `h`, the written surface between samples stays within `0.1 h` of `h`, and no local maximum stands more than `0.05 h` above its neighbours; several interior @@ -438,11 +449,14 @@ its source `faces`, for a line its drawn `path`, `radius`, `falloff`, `auto`, on while unmoved), `baseline` (a shared snapshot) and a cached `reach`. `moveWarpPoints` keeps taking one target per handle. -Each session undo step holds the points, gap targets, the settled grid they held and the -settings new points take, so undo restores the surface exactly without solving. Laying the -same region at the same density and feather keeps the model. A real rebuild carries each -distinct snapshot to the new grid once, writing each new node where the preview's own skinning -wrote its scan vertex, and rebinds samples, dropping those bound exactly as another. A line keeps +Each session undo step holds the points, which of them were selected, gap targets, the settled grid +they held and the settings new points take, so undo restores the surface exactly without solving +and selects again the handles it brings back that were selected. Laying the same region at the same +density and feather keeps the model. When the region was painted or set differently since, as a +mask painted wider and then laid as the whole part, the session keeps it as it now is, and the step +that records holds the region as it was, which undo puts back without a rebuild. A real rebuild +carries each distinct snapshot to the new grid once, writing each new node where the preview's own +skinning wrote its scan vertex, and rebinds samples, dropping those bound exactly as another. A line keeps its longest unbroken run of painted samples and its drawn path between them; an area keeps its largest connected piece of painted faces and the samples on it. Either is centred again on what is left, its target moved by as much as its centre; a line left with fewer than two samples, or an area @@ -459,10 +473,10 @@ dropped with a notice, and so is an unmoved one left on the new region's edge. A density change is one session undo step, and so is laying the grid on a changed region. The steps before it stay on the grid they were recorded on: their snapshots name a stand-in for it, their points let go of their reach and of binding arrays the solver caches against the old grid, -and the step the change records keeps the region as painted, the density and feather that grid was -laid from, with a hash of the model built. Undoing it rebuilds that grid (the build is -deterministic, one build's time), checks the hash, puts every step recorded on it back on the -rebuilt grid and restores the region, the handles and the surface exactly; undoing further restores +and the step the change records keeps the region as painted and the feather switch and width, the +density and feather that grid was laid from, with a hash of the model built. Undoing it rebuilds +that grid (the build is deterministic, one build's time), checks the hash, puts every step recorded +on it back on the rebuilt grid and restores the region, the handles and the surface exactly; undoing further restores each earlier step exactly, and undoing an earlier layout step rebuilds the grid it names in turn. Steps recorded on still earlier grids keep their own stand-ins and grid steps untouched. A rebuild that hashed differently would settle those steps again from rest and say so. Only the current diff --git a/src/components/WarpControls.tsx b/src/components/WarpControls.tsx index 60dc5bd..76d228d 100644 --- a/src/components/WarpControls.tsx +++ b/src/components/WarpControls.tsx @@ -296,7 +296,7 @@ function cancel() { /** Feathered edge for a painted region: a switch, and a width once it is on. */ function FeatherEdge({ part }: { part: Part | undefined }) { - const feather = useEditor((s) => s.warpFeather); + const feather = useEditor((s) => s.warp?.featherEdge ?? s.warpFeather); const brushRadius = useEditor(warpBrushRadius); const width = feather.width ?? brushRadius; const range = fittedSizeRange(part ? partSize(part) : 0); @@ -348,7 +348,7 @@ export function WarpControls() { const part = useEditor((s) => s.warp ? s.scene.parts.find((p) => p.id === s.warp!.partId) : undefined, ); - const feathered = useEditor((s) => s.warpFeather.enabled); + const feathered = useEditor((s) => (s.warp?.featherEdge ?? s.warpFeather).enabled); const featherNote = featherWarning(warp?.model?.feather); const featherWidth = warp?.model?.feather?.width; if (!warp) diff --git a/src/core/store.ts b/src/core/store.ts index a3dbb64..b8f3e04 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -251,6 +251,8 @@ export interface WarpSession { density: number; /** Feather width in mm the grid was laid with, 0 or absent for none. Density changes keep it. */ feather?: number; + /** The feather switch and width Edit region shows and the next lay takes. */ + featherEdge: WarpFeatherOption; /** Whether the user chose the density. Otherwise it follows the region. */ densityChosen: boolean; /** What the model was built from, so laying the same region again keeps it. */ @@ -294,17 +296,25 @@ export interface WarpSession { */ type WarpEdit = Pick< WarpSession, - 'points' | 'gapTargets' | 'gapHeld' | 'surface' | 'pointRadius' | 'pointFalloff' + | 'points' + | 'selectedPoints' + | 'gapTargets' + | 'gapHeld' + | 'surface' + | 'pointRadius' + | 'pointFalloff' > & { /** On the step a new grid records: the grid it undoes to, rebuilt when it is undone. */ grid?: WarpGridStep; + /** On the step laying the same grid records: the region as painted before, put back on undo. */ + painted?: WarpLaid['painted']; }; type WarpLaid = { faces: number[] | null; density: number; feather: number; /** The region as painted when the grid was laid, which undoing a later grid paints again. */ - painted: Pick; + painted: Pick; }; /** * The grid a density change or a new region left. Its steps' snapshots name `token` instead of the @@ -596,7 +606,12 @@ const toolChange = (state: EditorState, tool: Tool): Partial => { }; }; -const newWarpSession = (part: Part, epoch: number, faces: number[] = []): WarpSession => ({ +const newWarpSession = ( + part: Part, + epoch: number, + featherEdge: WarpFeatherOption, + faces: number[] = [], +): WarpSession => ({ id: uid(), partId: part.id, source: part.geometry, @@ -607,6 +622,7 @@ const newWarpSession = (part: Part, epoch: number, faces: number[] = []): WarpSe startFaces: faces, density: defaultWarpDensity, feather: 0, + featherEdge, densityChosen: false, laid: null, model: null, @@ -866,6 +882,7 @@ export const isWarpDragging = () => const warpEdit = (warp: WarpSession): WarpEdit => ({ points: warp.points, + selectedPoints: warp.selectedPoints, gapTargets: warp.gapTargets, gapHeld: warp.gapHeld ?? 0, surface: warp.model && warp.state ? settledOf(warp) : warp.surface, @@ -1372,11 +1389,13 @@ function restWarpPreview({ model, output, preview, source }: WarpSession) { */ function restoreWarp(scene: SceneDocument, warp: WarpSession, step: WarpEdit): WarpSession { const kept = new Set(step.points.map((point) => point.id)); + const { painted, ...edit } = step; const next: WarpSession = { ...warp, - ...step, + ...edit, + ...(painted && warp.laid ? { ...painted, laid: { ...warp.laid, painted } } : {}), surface: warp.surface, - selectedPoints: warp.selectedPoints.filter((id) => kept.has(id)), + selectedPoints: step.selectedPoints.filter((id) => kept.has(id)), }; const { model } = warp; const { surface } = step; @@ -2325,7 +2344,7 @@ export const useEditor = create((set, get) => ({ disposeWarpPreview(state.warp?.preview ?? null); set((state) => ({ ...toolChange(state, 'warp'), - warp: newWarpSession(part, state.sceneEpoch), + warp: newWarpSession(part, state.sceneEpoch, state.warpFeather), })); return true; }, @@ -2422,12 +2441,17 @@ export const useEditor = create((set, get) => ({ }, setWarpFeather: (patch) => set((state) => { - const enabled = patch.enabled ?? state.warpFeather.enabled; + const current = state.warp?.featherEdge ?? state.warpFeather; + const enabled = patch.enabled ?? current.enabled; const width = patch.width !== undefined && Number.isFinite(patch.width) ? Math.max(0, Math.min(100, patch.width)) - : (state.warpFeather.width ?? (enabled ? warpBrushRadius(state) : null)); - return { warpFeather: { enabled, width } }; + : (current.width ?? (enabled ? warpBrushRadius(state) : null)); + const warpFeather = { enabled, width }; + return { + warpFeather, + ...(state.warp ? { warp: { ...state.warp, featherEdge: warpFeather } } : {}), + }; }), cancelWarp: (notice) => { const { warp } = get(); @@ -2691,7 +2715,7 @@ export const useEditor = create((set, get) => ({ if (falloff !== undefined && Number.isFinite(falloff)) settings.pointFalloff = Math.min(1, Math.max(0, falloff)); const selected = new Set(warp.selectedPoints); - if (!model || warp.stage !== 'warp' || !warp.points.some((point) => selected.has(point.id))) { + if (!model || warp.stage !== 'warp') { set({ warp: { ...warp, ...settings } }); return; } @@ -2716,9 +2740,11 @@ export const useEditor = create((set, get) => ({ ? { ...next, baseline: surface } : next; }); - // Settings that leave every point as it was settle nothing. - if (!continuing && points.every((point, i) => point === warp.points[i])) { + // Settings that leave every point as it was settle nothing. With none selected they are what + // new points take, a step of their own. + if ((!continuing || !start.size) && points.every((point, i) => point === warp.points[i])) { const next = { ...warp, ...settings }; + if (!start.size) warpDrag = gesture === 'drag' ? { model, before, settings: start } : null; set({ warp: gesture === 'end' && !sameEdit(before, warpEdit(next)) @@ -2816,7 +2842,11 @@ export const useEditor = create((set, get) => ({ const points = warp.points.filter((point) => !released.has(point.id)); // Samples the user holds still keep their place: the seam stays open around them. const yielded = yieldingGapTargets(warp, points, gapTargets); - if (same(yielded.gapTargets, warp.gapTargets) && points.length === warp.points.length) return; + if (same(yielded.gapTargets, warp.gapTargets) && points.length === warp.points.length) { + // Nothing moves, but the panel still says why the seam stays open. + if (yielded.held !== (warp.gapHeld ?? 0)) set({ warp: { ...warp, gapHeld: yielded.held } }); + return; + } const kept = new Set(points.map((point) => point.id)); set({ warp: solveWarpSession( @@ -2880,6 +2910,7 @@ export const useEditor = create((set, get) => ({ seed, density, densityChosen, + featherEdge, snap, overlap, gizmo, @@ -2903,7 +2934,7 @@ export const useEditor = create((set, get) => ({ parts: state.scene.parts.map((p) => (p.id === part.id ? warped : p)), }), warp: { - ...newWarpSession(warped, state.sceneEpoch, faces), + ...newWarpSession(warped, state.sceneEpoch, featherEdge, faces), region, seed, density, @@ -3939,6 +3970,12 @@ useEditor.subscribe((state) => { state.settleWarp(true); }); +const samePainted = (a: WarpLaid['painted'], b: WarpLaid['painted']) => + a.region === b.region && + same(a.faces, b.faces) && + same(a.seed ?? null, b.seed ?? null) && + same(a.featherEdge, b.featherEdge); + const sameLaid = (a: WarpLaid, b: WarpLaid) => a.density === b.density && a.feather === b.feather && @@ -4055,8 +4092,8 @@ async function layWarp(from: WarpSettled, kind: 'region' | 'density' | WarpGridS ? 0 : kind === 'density' ? (warp.feather ?? 0) - : state.warpFeather.enabled - ? (state.warpFeather.width ?? warpBrushRadius(state)) + : warp.featherEdge.enabled + ? (warp.featherEdge.width ?? warpBrushRadius(state)) : 0; const density = restore ? restore.laid.density @@ -4069,15 +4106,35 @@ async function layWarp(from: WarpSettled, kind: 'region' | 'density' | WarpGridS faces, density, feather, - painted: { region: warp.region, faces: warp.faces, seed: warp.seed }, + painted: { + region: warp.region, + faces: warp.faces, + seed: warp.seed, + // A density change keeps the feather the grid was laid with. + featherEdge: (kind === 'density' && warp.laid?.painted.featherEdge) || warp.featherEdge, + }, }; - // The same region at the same density keeps its grid, so nothing moves. + // The same region at the same density keeps its grid, so nothing moves. A region painted or set + // differently since is a step of its own, which undo paints again without a rebuild. if (!restore && warp.model && warp.laid && sameLaid(warp.laid, laid)) { if (warp.settling) scheduleWarpSettle(); + const repainted = !samePainted(warp.laid.painted, laid.painted); useEditor.setState({ painting: false, paintHistory: [], - warp: { ...warp, stage: 'warp', density, feather, seam: warpSeam(state.scene, warp) }, + warp: { + ...warp, + stage: 'warp', + density, + feather, + seam: warpSeam(state.scene, warp), + ...(repainted + ? { + laid: { ...warp.laid, painted: laid.painted }, + undo: withUndo(warp, { ...warpEdit(warp), painted: warp.laid.painted }), + } + : {}), + }, }); return; } diff --git a/src/core/warp-handles.ts b/src/core/warp-handles.ts index 7bec25e..07abcd5 100644 --- a/src/core/warp-handles.ts +++ b/src/core/warp-handles.ts @@ -359,7 +359,8 @@ export function warpEligibleNodes(model: WarpModel) { } /** What a footprint is made from. Without a kind, a handle is a point. */ -type WarpFootprintOf = Pick & Partial>; +type WarpFootprintOf = Pick & + Partial>; /** * A line or an area moves as one the free nodes within this many node spacings of it. A sample's @@ -368,6 +369,15 @@ type WarpFootprintOf = Pick & Partial, a: Vec3, b: Vec3) { const ux = b[0] - a[0], @@ -384,13 +394,32 @@ function segmentDistance(p: ArrayLike, a: Vec3, b: Vec3) { return Math.hypot(p[0] - a[0] - t * ux, p[1] - a[1] - t * uy, p[2] - a[2] - t * uz); } +/** Whether a line is short and curved, at this node spacing. */ +function shortCurvedLine(samples: readonly WarpSample[], spacing: number) { + const a = samples[0].restWorld, + b = samples[samples.length - 1].restWorld; + let length = 0, + off = 0; + for (let s = 1; s < samples.length; s++) { + const p = samples[s].restWorld, + q = samples[s - 1].restWorld; + length += Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]); + off = Math.max(off, segmentDistance(p, a, b)); + } + const chord = Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]); + return length <= warpShortLineSpacings * spacing && off > warpShortLineBend * chord; +} + /** * Where a handle's reach is measured from, by kind. A point is its samples alone. A line or an area * moves as one the free nodes on it: within `warpFootprintSpacings` of the line through its * samples in order, or of an area's samples, found along the grid from the nodes the samples are - * bound to. A sample with none of its own nodes among them adds its most heavily bound one. An area - * also moves the free nodes on its faces still in the region, and straight-line distance is also - * measured from its outline. Paths start at every free node the samples are bound to. + * bound to. A sample with none of its own nodes among them adds its most heavily bound one. A short + * curved line whose guides fade across its samples' nodes moves every free node they are bound to: + * guides that hold one of them only partly while the samples pull it whole raise the surface + * between them. An + * area also moves the free nodes on its faces still in the region, and straight-line distance is + * also measured from its outline. Paths start at every free node the samples are bound to. */ export function handleFootprint(model: WarpModel, handle: WarpFootprintOf): WarpFootprint { const eligible = warpEligibleNodes(model); @@ -438,6 +467,15 @@ export function handleFootprint(model: WarpModel, handle: WarpFootprintOf): Warp }); if (heaviest >= 0) nodes.add(binding.node[heaviest]); } + if (handle.kind === 'line' && handle.radius) { + const spacing = spacingAt(model, new Set([...seeds, ...nodes])); + if ( + reachActivation(handle.radius, spacing) > 0 && + handle.radius < warpShortLineRadius * spacing && + shortCurvedLine(handle.samples, spacing) + ) + for (const n of seeds) nodes.add(n); + } } if (handle.kind === 'area' && handle.faces) { const { region, grid, restWorld } = model; diff --git a/tests/e2e/warp-grid.spec.ts b/tests/e2e/warp-grid.spec.ts index b2f199d..5f7a7b6 100644 --- a/tests/e2e/warp-grid.spec.ts +++ b/tests/e2e/warp-grid.spec.ts @@ -359,6 +359,70 @@ function gapFromSurface(page: Page) { }); } +/** + * Pixels of the view that change when the segments of edges drawn along mesh edges, after their + * walks failed, are moved out of sight in both of the grid's passes, and how many segments those + * are. The view is then drawn as it was. + */ +function reroutedPixels(page: Page) { + return page.evaluate(async () => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const root = (await import(urls.find((url) => url.includes('/@react-three_fiber.js'))!))._roots + .get(document.querySelector('canvas')) + .store.getState(); + const { gl, camera, scene } = root; + const drawing = scene.getObjectByName('warp-grid').userData.drawing; + const { path } = drawing; + const rerouted = (e: number) => + path.start[e + 1] > path.start[e] && + path.from + .subarray(path.start[e], path.start[e + 1]) + .every((from: number, i: number) => from === path.to[path.start[e] + i]); + const base = scene + .getObjectByName('warp-grid:core') + .geometry.getAttribute('instanceStart').data; + const canvas = gl.domElement as HTMLCanvasElement, + width = canvas.width, + height = canvas.height; + const context = gl.getContext() as WebGL2RenderingContext; + const read = () => { + gl.setRenderTarget(null); + gl.render(scene, camera); + const pixels = new Uint8Array(width * height * 4); + context.readPixels(0, 0, width, height, context.RGBA, context.UNSIGNED_BYTE, pixels); + return pixels; + }; + const differ = (a: Uint8Array, b: Uint8Array) => { + let count = 0; + for (let i = 0; i < a.length; i += 4) + if ( + Math.max( + Math.abs(a[i] - b[i]), + Math.abs(a[i + 1] - b[i + 1]), + Math.abs(a[i + 2] - b[i + 2]), + ) > 12 + ) + count++; + return count; + }; + const shown = read(); + const saved = base.array.slice(); + let segments = 0; + for (let s = 0; s < drawing.segments; s++) + if (rerouted(drawing.edgeOf[s])) { + segments++; + base.array.fill(1e7, s * 6, s * 6 + 6); + } + base.needsUpdate = true; + const without = read(); + base.array.set(saved); + base.needsUpdate = true; + const again = read(); + root.invalidate(); + return { segments, changed: differ(shown, without), restored: differ(shown, again) }; + }); +} + /** * On a plate laid flat, holds points at its corners and pulls one near its middle 2 mm up, and * returns how many points it holds and how far the surface under the pulled one rose. @@ -609,6 +673,12 @@ test('on a scan-like part, failed walks are drawn along the surface, never acros expect(gap.reroutedSamples).toBeGreaterThan(50); expect(cover.touched).toBeGreaterThan(0.05); expect(gap.worst).toBeLessThan(0.05); + // The rerouted segments themselves show: the view changes without them. + const alone = await reroutedPixels(page); + note(`density ${level}, rerouted`, alone); + expect(alone.segments).toBeGreaterThan(0); + expect(alone.restored).toBe(0); + expect(alone.changed).toBeGreaterThan(50); } }); diff --git a/tests/e2e/warp-strokes.spec.ts b/tests/e2e/warp-strokes.spec.ts index bdb1abc..4da8885 100644 --- a/tests/e2e/warp-strokes.spec.ts +++ b/tests/e2e/warp-strokes.spec.ts @@ -351,6 +351,144 @@ test('an area stroke leaves the region and its paint history alone', async ({ pa expect((await state(page)).handles).toHaveLength(before.handles.length); }); +test('after undoing an added area, the radius field still edits the line selected before', async ({ + page, +}) => { + await warpFront(page); + await page.getByRole('radio', { name: 'Line', exact: true }).click(); + await drag(page, [ + [-5, 9, 10], + [5, 11, 10], + ]); + const drawn = await state(page); + const line = drawn.handles.at(-1)!; + expect(drawn.selected).toEqual([line.id]); + const field = page.getByRole('spinbutton', { name: 'Point radius', exact: true }); + const radiusOf = (id: string) => + inStore( + page, + 'return store.useEditor.getState().warp.points.find((p) => p.id === args).radius;', + id, + ); + await field.fill('3.3'); + await field.press('Enter'); + expect(await radiusOf(line.id)).toBe(3.3); + + await page.getByRole('radio', { name: 'Area', exact: true }).click(); + await drag(page, [ + [-3, 4, 10], + [3, 5, 10], + ]); + const painted = await state(page); + expect(painted.handles.at(-1)!.kind).toBe('area'); + expect(painted.selected).not.toContain(line.id); + + await page.keyboard.press('ControlOrMeta+z'); + const undone = await state(page); + expect(undone.handles.map(({ id }: { id: string }) => id)).toEqual([line.id]); + expect(undone.selected).toEqual([line.id]); + await expect(page.locator('.warp-point-settings')).not.toContainText( + 'New points use this radius and falloff.', + ); + await field.fill('6.6'); + await field.press('Enter'); + expect(await radiusOf(line.id)).toBe(6.6); + expect((await state(page)).undo).toBe(undone.undo + 1); + + // With nothing selected the field sets what new handles take, and undo takes that back first. + const empty = await screen(page, [16, 10, 10]); + await page.mouse.click(empty.x, empty.y); + expect((await state(page)).selected).toEqual([]); + await expect(page.locator('.warp-point-settings')).toContainText( + 'New points use this radius and falloff.', + ); + await field.fill('2'); + await field.press('Enter'); + const defaults = await state(page); + expect(defaults.undo).toBe(undone.undo + 2); + await page.keyboard.press('ControlOrMeta+z'); + expect(await inStore(page, 'return store.useEditor.getState().warp.pointRadius;')).toBe( + 6.6, + ); + expect(await radiusOf(line.id)).toBe(6.6); +}); + +test('undo back to a feathered layout shows its feather, and laying it again changes nothing', async ({ + page, +}) => { + await page.goto('/'); + await expect(page.locator('canvas')).toBeVisible(); + await page.getByLabel('Open Kitbasher scene').setInputFiles({ + name: 'strokes.kitbash', + mimeType: 'application/json', + buffer: Buffer.from(JSON.stringify(fixture)), + }); + await page.getByRole('button', { name: 'Open scene', exact: true }).click(); + await page.locator('.part-select[title="Scanned block"]').click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.keyboard.press('w'); + const brush = page.getByRole('spinbutton', { name: 'Brush radius', exact: true }); + await brush.fill('6'); + await brush.press('Enter'); + const centre = await screen(page, [0, 10, 10]); + await page.mouse.click(centre.x, centre.y); + const feather = page.getByRole('switch', { name: 'Feather the painted edge', exact: true }); + const width = page.getByRole('spinbutton', { name: 'Feather width', exact: true }); + await feather.click(); + await width.fill('1.75'); + await width.press('Enter'); + const lay = page.getByRole('button', { name: 'Lay grid', exact: true }); + const edit = page.getByRole('button', { name: 'Edit region', exact: true }); + const laid = () => expect.poll(async () => (await state(page)).stage).toBe('warp'); + await lay.click(); + await laid(); + const laidWidth = () => + inStore( + page, + 'return store.useEditor.getState().warp.model.feather?.width ?? null;', + ); + expect(await laidWidth()).toBe(1.75); + await page.getByRole('radio', { name: 'Point', exact: true }).click(); + const spot = await screen(page, [2, 11, 10]); + await page.mouse.click(spot.x, spot.y); + for (let step = 0; step < 3; step++) + await page.getByRole('button', { name: 'Move Z positive', exact: true }).click(); + + // Feather off, laid again: a layout of its own. + await edit.click(); + await feather.click(); + await expect(feather).toHaveAttribute('aria-checked', 'false'); + await lay.click(); + await laid(); + expect(await laidWidth()).toBeNull(); + + await page.keyboard.press('ControlOrMeta+z'); + await laid(); + await expect.poll(laidWidth).toBe(1.75); + await inStore(page, 'store.finishWarpSettling();'); + const written = () => + inStore<{ marked: boolean; undo: number; surface: number[] }>( + page, + `const warp = store.useEditor.getState().warp; + const marked = warp.model.marked === true; + warp.model.marked = true; + return { marked, undo: warp.undo.length, surface: Array.from(warp.preview.getAttribute('position').array) };`, + ); + const before = await written(); + await edit.click(); + await expect(feather).toHaveAttribute('aria-checked', 'true'); + await expect(width).toHaveValue('1.75'); + await lay.click(); + await laid(); + await inStore(page, 'store.finishWarpSettling();'); + const after = await written(); + // The same model, no new step and not a vertex moved. + expect(after.marked).toBe(true); + expect(after.undo).toBe(before.undo); + expect(after.surface).toEqual(before.surface); +}); + test('the first drag of a new line with the default radius lifts a smooth ridge', async ({ page, }) => { diff --git a/tests/unit/free-transform.test.ts b/tests/unit/free-transform.test.ts index 4778c1a..c09def1 100644 --- a/tests/unit/free-transform.test.ts +++ b/tests/unit/free-transform.test.ts @@ -255,7 +255,7 @@ describe('free transform on warp control points', () => { return warp().points.at(-1)!.id; }; - /** Lays a grid over a whole plate and adds two selected points on it. */ + /** Lays a grid over a whole plate and adds two selected points on it: three session steps. */ async function warpPlate() { const plate = part('plate', { geometry: new PlaneGeometry(40, 40, 16, 16) }); state().setScene({ name: 'Warp', parts: [plate], joints: [] }); @@ -295,7 +295,7 @@ describe('free transform on warp control points', () => { it('free move on points confirms one session undo step and cancel restores', async () => { const [a, b] = await warpPlate(); const { scene, past, revision } = state(); - expect(warp().undo).toHaveLength(2); + expect(warp().undo).toHaveLength(3); const lift = freeLift(); expect(state().tool).toBe('warp'); @@ -303,12 +303,12 @@ describe('free transform on warp control points', () => { lift(10); expect(distance(targets()[0]!, [-4, 0, 2])).toBeLessThan(1e-6); expect(distance(targets()[1]!, [4, 0, 2])).toBeLessThan(1e-6); - expect(warp().undo).toHaveLength(2); + expect(warp().undo).toHaveLength(3); state().finishFreeTransform(true); expect(state().freeTransform).toBeNull(); expect(state().tool).toBe('warp'); // The whole gesture is one session step, holding the points from before it. - expect(warp().undo).toHaveLength(3); + expect(warp().undo).toHaveLength(4); expect( warp() .undo.at(-1)! @@ -329,7 +329,7 @@ describe('free transform on warp control points', () => { state().finishFreeTransform(false); expect(state().freeTransform).toBeNull(); expect(warp().points).toEqual(settled); - expect(warp().undo).toHaveLength(3); + expect(warp().undo).toHaveLength(4); const output = warp().output!.positions; expect(Math.max(...surface.map((value, i) => Math.abs(value - output[i])))).toBeLessThan(0.01); expect(state().scene).toBe(scene); @@ -339,7 +339,7 @@ describe('free transform on warp control points', () => { const c = add(0, 6); const added = warp().points; state().moveWarpPoints([{ id: a, target: [-4, 0, 1] }], 'end'); - expect(warp().undo).toHaveLength(5); + expect(warp().undo).toHaveLength(6); expect(warp().undo.at(-1)!.points).toEqual(added); state().undoWarpEdit(); expect(targets()).toEqual(added.map((point) => point.target)); @@ -354,12 +354,12 @@ describe('free transform on warp control points', () => { lift(-20); state().finishFreeTransform(true); expect(warp().points).toEqual(before); - expect(warp().undo).toHaveLength(2); + expect(warp().undo).toHaveLength(3); // Confirming without any movement adds none either. freeLift(); state().finishFreeTransform(true); expect(warp().points).toEqual(before); - expect(warp().undo).toHaveLength(2); + expect(warp().undo).toHaveLength(3); }); it('refuses a free move with no point selected and keeps the session', async () => { @@ -381,7 +381,7 @@ describe('free transform on warp control points', () => { expect(state().freeTransform).toBeNull(); expect(state().warp).not.toBeNull(); expect(warp().points).toEqual(before); - expect(warp().undo).toHaveLength(2); + expect(warp().undo).toHaveLength(3); add(0, 6); const added = warp().points; state().moveWarpPoints([{ id: a, target: [-4, 0, 1] }], 'end'); diff --git a/tests/unit/transform-selection.test.ts b/tests/unit/transform-selection.test.ts index 528d2a1..82f270d 100644 --- a/tests/unit/transform-selection.test.ts +++ b/tests/unit/transform-selection.test.ts @@ -221,6 +221,7 @@ const warping = (patch: Partial = {}, tool: 'warp' | 'select' = 'wa faces: [], startFaces: [], density: 3, + featherEdge: { enabled: false, width: null }, densityChosen: false, laid: null, model: null, diff --git a/tests/unit/warp-feather-session.test.ts b/tests/unit/warp-feather-session.test.ts index f3e504b..a620df2 100644 --- a/tests/unit/warp-feather-session.test.ts +++ b/tests/unit/warp-feather-session.test.ts @@ -211,6 +211,46 @@ describe('a session’s own feather', () => { }); }); +describe('the feather switch through undo', () => { + it('comes back with the layout undo restores, so laying the grid again changes nothing', async () => { + editor().setWarpFeather({ enabled: true, width: 1.75 }); + const part = plate(); + await layOn(part, disc(part.geometry, 8)); + editor().addWarpPoint(hit(0.3, 0.2), faceAt(part.geometry, 0.3, 0.2)); + editor().moveWarpPoints([{ id: session().points[0].id, target: [0.3, 0.2, 1] }], 'end'); + finishWarpSettling(); + const steps = session().undo.length; + // Turn the feather off and lay the grid again: a layout of its own. + editor().setWarpRegion('painted'); + editor().setWarpFeather({ enabled: false }); + expect(session().featherEdge.enabled).toBe(false); + await editor().layWarpGrid(); + expect(session().model!.feather).toBeNull(); + + await editor().undoWarpEdit(); + expect(session().model!.feather).toMatchObject({ width: 1.75 }); + expect(session().featherEdge).toEqual({ enabled: true, width: 1.75 }); + expect(session().undo).toHaveLength(steps); + finishWarpSettling(); + const { model, undo } = session(); + const surface = Array.from(session().output!.positions); + // Edit region, then Lay grid with nothing changed: no rebuild, no step, no movement. + editor().setWarpRegion('painted'); + await editor().layWarpGrid(); + finishWarpSettling(); + expect(session().model).toBe(model); + expect(session().undo).toBe(undo); + expect(Array.from(session().output!.positions)).toEqual(surface); + // The page option still starts a new session as the user last set it. + expect(editor().warpFeather).toEqual({ enabled: false, width: 1.75 }); + editor().cancelWarp(); + editor().setTool('select'); + useEditor.setState({ selected: [part.id] }); + editor().setTool('warp'); + expect(session().featherEdge).toEqual({ enabled: false, width: 1.75 }); + }); +}); + describe('a feathered region painted wider', () => { it('carries the band the new paint covers at the surface the user saw', async () => { editor().setWarpFeather({ enabled: true, width: 7 }); diff --git a/tests/unit/warp-session.test.ts b/tests/unit/warp-session.test.ts index e5cc26e..ec834f1 100644 --- a/tests/unit/warp-session.test.ts +++ b/tests/unit/warp-session.test.ts @@ -485,6 +485,7 @@ describe('warp session', () => { undo: [ { points: [inside, outside], + selectedPoints: ['inside', 'outside'], gapTargets, surface: inside.baseline, pointRadius: null, @@ -777,11 +778,11 @@ describe('warp points, close gap and apply', () => { expect(distance(deformed(session().points[0]), [0, 0, 3])).toBeLessThan(0.01); // One undo step for the whole gesture, holding the points from before it. - expect(session().undo).toHaveLength(2); + expect(session().undo).toHaveLength(3); expect(session().undo.at(-1)!.points[0].target).toBeNull(); // A release that moved nothing adds none. move(p.id, [0, 0, 3]); - expect(session().undo).toHaveLength(2); + expect(session().undo).toHaveLength(3); expect(session().folds.length).toBe(0); expect(session().seam).toBeNull(); @@ -1083,7 +1084,7 @@ describe('warp points, close gap and apply', () => { const lifted = Array.from(session().output!.positions); const q = addAt(a, -4, 0); move(q.id, [-4, 0, -1]); - expect(session().undo).toHaveLength(4); + expect(session().undo).toHaveLength(5); editor().selectWarpPoints([p.id, 'missing']); expect(session().selectedPoints).toEqual([p.id]); @@ -1114,8 +1115,12 @@ describe('warp points, close gap and apply', () => { expect(close(rest, session().output!.positions)).toBeLessThan(0.01); editor().undoWarpEdit(); expect(session().points).toEqual([]); - expect(session().undo).toEqual([]); + expect(session().undo).toHaveLength(1); expect(close(rest, session().output!.positions)).toBeLessThan(1e-5); + // The radius new points take was a step of its own. + editor().undoWarpEdit(); + expect(session().pointRadius).toBeNull(); + expect(session().undo).toEqual([]); editor().undoWarpEdit(); expect(session().points).toEqual([]); }); @@ -2091,6 +2096,35 @@ describe('warp handles', () => { } }); + it('close gap says why when a point the user placed holds back every target', async () => { + const a = plate('a', 0, 64); + const small = new PlaneGeometry(1.5, 1.5, 3, 3); + small.setAttribute( + 'color', + new BufferAttribute(new Float32Array(small.getAttribute('position').count * 3).fill(0.5), 3), + ); + // A small part facing the plate 1 mm in front of a point the user placed. + const b: Part = { + ...plate('b'), + geometry: small, + position: [3, 2, 1], + quaternion: [0, 1, 0, 0], + }; + setup([a, b], ['a']); + await warpDisc(a, 0, 0, 14); + editor().setWarpPointSettings({ radius: 0 }, 'end'); + addAt(a, 3, 2); + finishWarpSettling(); + const { undo, state } = session(); + const positions = Array.from(state!.positions); + editor().closeWarpGap(); + expect(session().gapTargets).toEqual([]); + expect(session().gapHeld).toBeGreaterThan(0); + expect(session().seam!.largestGap).toBeGreaterThan(0); + expect(session().undo).toBe(undo); + expect(Array.from(session().state!.positions)).toEqual(positions); + }); + it('names Close gap or a moved handle as what pulls a held point, whichever is nearer', async () => { const a = plate('a', 0, 32); setup([a], ['a']); @@ -2196,7 +2230,9 @@ describe('warp handles', () => { expect(handleGuides(first)).toBe(true); editor().selectWarpPoints([]); editor().setWarpPointSettings({ radius: 1.5, falloff: 0.4 }, 'end'); - expect(session().undo).toHaveLength(1); + // With nothing selected it changes only what new points take, as a step of its own. + expect(session().undo).toHaveLength(2); + expect(session().undo.at(-1)).toMatchObject({ pointRadius: null, pointFalloff: 1 }); expect(addAt(a, 4, 0)).toMatchObject({ radius: 1.5, falloff: 0.4 }); // A radius the user chose is used as given, and 0 stays a bare point. editor().selectWarpPoints([]); @@ -2213,6 +2249,50 @@ describe('warp handles', () => { expect(addAt(a, 0, 0).radius).toBeLessThanOrEqual(Number((extent / 4).toPrecision(2))); }); + it('undo selects the handles it brings back, and a radius set with none selected is a step', async () => { + const a = plate('a', 0, 64); + setup([a], ['a']); + await warpDisc(a, 0, 0, 14); + const spots = Array.from({ length: 60 }, (_, i) => { + const x = -6 + (12 * i) / 59; + return { face: faceAt(a.geometry, x, 1), barycentric: barycentricAt(a, x, 1) }; + }); + expect(editor().addWarpStroke({ kind: 'line', points: spots })).toBe(true); + const line = session().points.at(-1)!; + editor().selectWarpPoints([line.id]); + editor().setWarpPointSettings({ radius: 3.3 }, 'end'); + const first = { face: faceAt(a.geometry, -5, -5), barycentric: barycentricAt(a, -5, -5) }; + const faces = Array.from({ length: triangleCount(a.geometry) }, (_, f) => f).filter( + (f) => + readFace(a.geometry, f) + .getMidpoint(new Vector3()) + .distanceTo(new Vector3(-5, -5, 0)) < 1.2, + ); + expect(editor().addWarpStroke({ kind: 'area', faces, first })).toBe(true); + expect(session().selectedPoints).not.toContain(line.id); + + await editor().undoWarpEdit(); + expect(session().points.map(({ id }) => id)).toEqual([line.id]); + expect(session().selectedPoints).toEqual([line.id]); + const depth = session().undo.length; + editor().setWarpPointSettings({ radius: 6.6 }, 'end'); + expect(session().points[0].radius).toBe(6.6); + expect(session().undo).toHaveLength(depth + 1); + + // With nothing selected, a radius or falloff is what new handles take, and one step per gesture. + editor().selectWarpPoints([]); + for (const radius of [3, 4]) editor().setWarpPointSettings({ radius }, 'drag'); + editor().setWarpPointSettings({ radius: 5, falloff: 0.5 }, 'end'); + expect(session()).toMatchObject({ pointRadius: 5, pointFalloff: 0.5 }); + expect(session().undo).toHaveLength(depth + 2); + await editor().undoWarpEdit(); + expect(session()).toMatchObject({ pointRadius: 6.6, pointFalloff: 1 }); + expect(session().points[0].radius).toBe(6.6); + await editor().undoWarpEdit(); + expect(session().points[0].radius).toBe(3.3); + expect(session().selectedPoints).toEqual([line.id]); + }); + it('a whole part starts on a finer grid than a painted region, unless the user chose one', async () => { const a = plate('a'); setup([a], ['a']); @@ -2494,6 +2574,53 @@ describe('warp handles', () => { useEditor.setState({ warpFeather: { enabled: false, width: null } }); }, 60_000); + it('laying the same grid on a repainted region keeps what was painted, and undo puts it back', async () => { + const a = plate('a', 0, 64); + setup([a], ['a']); + editor().setTool('warp'); + editor().setWarpOptions({ autoPoints: false }); + editor().setWarpBrushRadius(6); + editor().paintWarpRegion(hit('a', 0, 0), faceAt(a.geometry, 0, 0), false, true); + editor().endPaintStroke(); + const painted = session().faces; + editor().setWarpRegion('whole'); + await editor().layWarpGrid(); + const model = session().model!; + const steps = session().undo.length; + // Paint more, then lay the whole part again: the same grid. + editor().setWarpRegion('painted'); + editor().paintWarpRegion(hit('a', 8, 0), faceAt(a.geometry, 8, 0), false, true); + editor().endPaintStroke(); + const repainted = session().faces; + expect(repainted.length).toBeGreaterThan(painted.length); + editor().setWarpRegion('whole'); + const tasks = warpTasks().length; + await editor().layWarpGrid(); + expect(session().model).toBe(model); + expect(warpTasks()).toHaveLength(tasks); + expect(session().undo).toHaveLength(steps + 1); + expect(session().laid!.painted.faces).toBe(repainted); + + await editor().setWarpDensity(2); + expect(session().model).not.toBe(model); + await editor().undoWarpEdit(); + expect(session().model!.grid.nodes).toEqual(model.grid.nodes); + expect(session()).toMatchObject({ region: 'whole', faces: repainted }); + // Undo once more paints the region as it was, on the same grid. + const rebuilt = session().model; + const surface = positionsOf(session().preview!); + await editor().undoWarpEdit(); + expect(session().model).toBe(rebuilt); + expect(session()).toMatchObject({ region: 'whole', faces: painted }); + expect(session().laid!.painted.faces).toBe(painted); + expect(session().undo).toHaveLength(steps); + expect(positionsOf(session().preview!)).toEqual(surface); + // Laying again with nothing changed adds no step. + editor().setWarpRegion('whole'); + await editor().layWarpGrid(); + expect(session().undo).toHaveLength(steps); + }); + it('a density change that would drop a handle is not made, and says why', async () => { for (const feather of [false, true]) for (const [x, y] of [ diff --git a/tests/unit/warp-strokes.test.ts b/tests/unit/warp-strokes.test.ts index 38d0001..385c8a8 100644 --- a/tests/unit/warp-strokes.test.ts +++ b/tests/unit/warp-strokes.test.ts @@ -27,6 +27,7 @@ import { strokeSample, type WarpStrokePoint, } from '../../src/core/warp-strokes'; +import { warpShortLineRadius } from '../../src/core/warp-handles'; import type { Part, SceneDocument, Vec3 } from '../../src/core/types'; function partOf(geometry: BufferGeometry): Part { @@ -296,6 +297,59 @@ describe('line handles', () => { for (const rise of rises) expect(Math.abs(rise - lift)).toBeLessThan(0.05 * lift); }, 30_000); + it('lift a short line over tight relief on a small painted patch level at default settings', async () => { + // A 1.2 mm tube about as coarse as a scanned miniature's mesh, one dab of paint on it at the + // default density, and a line a little over two node spacings around it, rising along it. + const R = 0.6; + const part = partOf(new CylinderGeometry(R, R, 12, 12, 70, true).toNonIndexed()); + editor().setScene({ name: 'Warp', parts: [part], joints: [] }); + useEditor.setState({ selected: [part.id] }); + editor().setTool('warp'); + editor().setWarpBrushRadius(1.1); + editor().paintWarpRegion( + { partId: part.id, point: [0, 0, R], normal: [0, 0, 1] }, + surfaceAt(part, [0, 0, R]).face, + false, + true, + ); + editor().endPaintStroke(); + await editor().layWarpGrid(); + const a = (35 * Math.PI) / 180; + const points = Array.from({ length: 81 }, (_, i) => { + const t = -a + (2 * a * i) / 80; + return surfaceAt(part, [R * Math.sin(t), 0.4 * t, R * Math.cos(t)]); + }); + expect(editor().addWarpStroke({ kind: 'line', points })).toBe(true); + const line = latest(); + const spacing = line.reach!.spacing; + expect(2 * a * R).toBeLessThan(3 * spacing); + expect(line.radius).toBeLessThan(warpShortLineRadius * spacing); + const lift = 0.5; + editor().moveWarpPoints( + [{ id: line.id, target: [line.pin[0], line.pin[1], line.pin[2] + lift] }], + 'end', + ); + finishWarpSettling(); + const model = session().model!; + const rises = points.map( + (p) => + facePoint(model, session().output!.positions, p)[2] - + facePoint(model, model.positions, p)[2], + ); + figures['short line over a small painted tube'] = { + nodes: model.grid.nodes.length, + samples: line.samples.length, + spacing, + radius: line.radius, + lowest: Math.min(...rises), + highest: Math.max(...rises), + peak: worstPeak(rises, 4), + }; + // Moving only the nodes nearest the line left spots between its samples 0.08 of the lift off. + for (const rise of rises) expect(Math.abs(rise - lift)).toBeLessThan(0.05 * lift); + expect(worstPeak(rises, 4)).toBeLessThan(0.02 * lift); + }); + it('take a sample about every half spacing and merge those bound alike, keeping both ends', async () => { const surface = { ...surfaces.plate, make: () => partOf(new PlaneGeometry(40, 40, 8, 8)) }; const part = await lay(surface); From f642c65fa325e4202c536004b92d1d791ad49550 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Wed, 18 Nov 2026 20:07:52 -0800 Subject: [PATCH 22/25] Bind warp line footprints to the drawn path and show mixed handle settings --- .../specs/2026-11-17-warp-handles-design.md | 47 ++- src/components/WarpControls.tsx | 29 +- src/components/ui.tsx | 26 +- src/core/warp-handles.ts | 76 ++-- src/styles.css | 10 + tests/e2e/warp.spec.ts | 129 +++++++ tests/unit/warp-handles.test.ts | 21 ++ tests/unit/warp-strokes.test.ts | 326 +++++++++++++++++- 8 files changed, 589 insertions(+), 75 deletions(-) diff --git a/docs/superpowers/specs/2026-11-17-warp-handles-design.md b/docs/superpowers/specs/2026-11-17-warp-handles-design.md index d9178f3..bae6121 100644 --- a/docs/superpowers/specs/2026-11-17-warp-handles-design.md +++ b/docs/superpowers/specs/2026-11-17-warp-handles-design.md @@ -220,7 +220,11 @@ samples at most 0.0027 mm, where the seam had moved them 0.78 and 0.72 mm. Every handle has a **radius** in mm and a **falloff** from 0 to 100 %, edited in the Control points section for the selected handles. New handles take the last values set; with nothing -selected, setting one is a session undo step of its own. Until the user +selected, setting one is a session undo step of its own. Where the selected handles differ in +radius, or in falloff, that field shows no value with a Mixed placeholder and its slider no thumb; +a value typed or slid there sets every selected handle, as one undo step, even one equal to a +value some already have. The line under the fields says what a new point will take: the same +settings as the selection when it does, or else its radius and falloff. Until the user sets a radius, a new point takes the larger of 6 % of the part's size and 4.5 node spacings where it is clicked, no more than a quarter of the region's extent. Radius 0 is a bare point; automatic points are radius 0. Effectively whole regions are laid at the 2,000-node level and @@ -419,26 +423,35 @@ the shoulder 1,501 faces and 13. **Footprint.** A line or an area moves as one the free nodes within 0.75 node spacings (each node's own) of the line through its samples in order, or of an area's samples, found by walking the grid from the nodes the samples are bound to; a sample with none of its nodes among them adds -its most heavily bound one; an area also moves the free nodes on its faces. Every bound free node -seeds the reach's paths, and straight-line distance is measured from the samples and an area's -outline. Taking every node a sample is bound to, as first written, made the ridge's width depend on -which triangles the samples fell in: a binding reaches one to one and a half spacings, unevenly to -either side, and two samplings of one stroke differed by a quarter of the lift. A short curved line -is the exception: one no longer than five node spacings that stands off its chord by more than -3.5 % of it, with a radius between one and four spacings, moves every free node its samples are -bound to. There the guides fade across those nodes while the samples pull them whole, and the -surface between the samples rose: on a small patch painted on the 35 mm Tomb Crawler at the default -density, a 1 mm line lifted 0.5 mm stood between 0.36 and 0.66 mm, and moving those nodes as one -keeps it between 0.45 and 0.51 mm, and at 41 spots along it between 0.48 and 0.51 mm. A whole part's default radius is wider, and longer or straighter -lines keep the narrower footprint. Section 4 applies with distance measured from the footprint: -radius 0 gives a continuous ridge or a rigid patch, and a radius above 0 adds the smooth skirt. +its most heavily bound one; an area also moves the free nodes on its faces. A line also moves +every free node its drawn path is bound to: every hit the stroke kept, not only its samples, +whatever its length, bend or radius. Every bound free node seeds the reach's paths, and +straight-line distance is measured from the samples and an area's outline. Taking every node the +samples alone are bound to, as first written, made the ridge's width depend on which triangles +the samples fell in: a binding reaches one to one and a half spacings, unevenly to either side, +and two samplings of one stroke differed by a quarter of the lift. Taking only the nodes near the +samples left nodes a hit is bound to that the guides held only partly while the line pulled the +hit, and the surface between the samples rose or sank: on 16 dabs of paint each on the 35 mm Tomb +Crawler and the torso scaled to 32 mm, at default settings and pulled 0.5 mm along a view up to +25° off the surface, 383 of 509 short lines and 127 of 257 longer ones stood within 0.45 to +0.55 mm with no peak over 0.025 mm, and drawn between two faces on the Tomb Crawler the middle of +a 0.6 mm line reached only 0.265 mm. A rule that took the samples' nodes only for short curved +lines (five spacings at most, bowed off the chord by more than 3.5 %, radius one to four +spacings) fixed the case it was written for and made the lift jump where a line crossed one of +those limits. With the path's nodes, 509 of 509 short lines and 256 of 257 longer ones meet that +tolerance; the other, ending one node spacing from the fixed edge, stands between 0.484 and +0.519 mm with a 0.030 mm peak beside the edge. Whole parts at default settings keep lines within +0.491 and 0.506 mm. Pointer speed does not change a line: its hits are taken every 2 screen +pixels along the pointer's path, so a straight stroke drawn slowly or quickly binds the same +nodes. Section 4 applies with distance measured from the footprint: radius 0 gives a continuous +ridge or a rigid patch, and a radius above 0 adds the smooth skirt. Acceptance: along a line handle moved by `h`, the written surface between samples stays within `0.1 h` of `h`, and no local maximum stands more than `0.05 h` above its neighbours; several interior points of an area do the same, including an area smaller than a cell and a 60-node grid; the same -stroke drawn slowly and quickly gives results within `0.02 h`. Measured: a line within 0.017 h -(radius 0: 0.005 h) with no peak above 0.011 h at default density, within 0.012 h on a 60-node -ball; areas within 0.01 h; slow and quick within 0.002 h. On the 32 mm torso scan, lifted 1.92 mm, +stroke drawn slowly and quickly gives results within `0.02 h`. Measured: a line within 0.007 h +(radius 0: 0.005 h) with no peak above 0.006 h at default density, within 0.011 h on a 60-node +ball; areas within 0.01 h; slow and quick within 0.003 h. On the 32 mm torso scan, lifted 1.92 mm, a line across the chest stays between 1.912 and 1.921 mm (default radius: 1.901 and 1.927), where points placed along the same path range from 0.71 to 2.03 mm. diff --git a/src/components/WarpControls.tsx b/src/components/WarpControls.tsx index 76d228d..73fd0fb 100644 --- a/src/components/WarpControls.tsx +++ b/src/components/WarpControls.tsx @@ -103,9 +103,21 @@ function PointSettingsControls({ warp, part }: { warp: WarpSession; part: Part | const shown = selected[0]; const radius = shown ? shown.radius : warpPointRadius(warp, part); const falloff = shown ? shown.falloff : warp.pointFalloff; + // Selected points that differ show neither value. + const mixedRadius = selected.some((point) => point.radius !== radius); + const mixedFalloff = selected.some((point) => point.falloff !== falloff); const { max } = fittedSizeRange(part ? partSize(part) : 40); const coarse = selected.some((point) => point.radius > 0 && !handleGuides(point)); - const fade = shown && handleGuides(shown) ? fadeWidth(shown) : null; + const fade = + shown && !mixedRadius && !mixedFalloff && handleGuides(shown) ? fadeWidth(shown) : null; + const percent = (value: number) => `${Math.round(value * 100)}%`; + // What a new point gets. + const newPoints = + !mixedRadius && !mixedFalloff && warp.pointRadius === radius && warp.pointFalloff === falloff + ? 'New points use the same settings.' + : warp.pointRadius === null + ? `New points use ${percent(warp.pointFalloff)} falloff, and reach a few grid spacings where you click until you set a radius.` + : `New points use a ${Number(warp.pointRadius.toPrecision(3))} mm radius and ${percent(warp.pointFalloff)} falloff.`; const shortfall = warpShortfall(warp); const drift = warpPinDrift(warp); const commit = (patch: PointSettings) => useEditor.getState().setWarpPointSettings(patch, 'end'); @@ -144,6 +156,7 @@ function PointSettingsControls({ warp, part }: { warp: WarpSession; part: Part | min={0.1} max={max} zero + mixed={mixedRadius} onChange={(value) => gesture.change('radius', { radius: value })} /> commit({ radius: value })} /> mm @@ -160,11 +174,13 @@ function PointSettingsControls({ warp, part }: { warp: WarpSession; part: Part | Falloff gesture.change('falloff', { falloff: Number(event.target.value) / 100 }) } @@ -174,15 +190,18 @@ function PointSettingsControls({ warp, part }: { warp: WarpSession; part: Part | value={Math.round(falloff * 100)} min={0} max={100} + mixed={mixedFalloff} onCommit={(value) => commit({ falloff: value / 100 })} /> %

{selected.length - ? radius > 0 - ? `Moves the surface within ${Number(radius.toPrecision(3))} mm of the selected ${selected.length === 1 ? 'point' : 'points'}${fade !== null ? `, fading over the outer ${Number(fade.toPrecision(2))} mm` : ''}. New points use the same settings.` - : `The selected ${selected.length === 1 ? 'point moves' : 'points move'} the surface at the point only.` + ? mixedRadius + ? `The selected points move the surface within their own radii. ${newPoints}` + : radius > 0 + ? `Moves the surface within ${Number(radius.toPrecision(3))} mm of the selected ${selected.length === 1 ? 'point' : 'points'}${fade !== null ? `, fading over the outer ${Number(fade.toPrecision(2))} mm` : ''}. ${newPoints}` + : `The selected ${selected.length === 1 ? 'point moves' : 'points move'} the surface at the point only.` : warp.pointRadius === null ? 'New points use this falloff, and reach a few grid spacings where you click until you set a radius.' : 'New points use this radius and falloff.'} diff --git a/src/components/ui.tsx b/src/components/ui.tsx index c962e3a..9b047f7 100644 --- a/src/components/ui.tsx +++ b/src/components/ui.tsx @@ -230,6 +230,7 @@ export function NumericInput({ step = 1, min, max, + mixed = false, }: { id?: string; value: number; @@ -239,16 +240,20 @@ export function NumericInput({ step?: number; min?: number; max?: number; + /** Shows no value, with a Mixed placeholder, and commits any valid value typed. */ + mixed?: boolean; }) { - const [draft, setDraft] = useState(String(Number(value.toFixed(3)))); + const shown = mixed ? '' : String(Number(value.toFixed(3))); + const [draft, setDraft] = useState(shown); const cancelled = useRef(false); - useEffect(() => setDraft(String(Number(value.toFixed(3)))), [value]); + useEffect(() => setDraft(shown), [value, mixed]); return ( { if (cancelled.current) { cancelled.current = false; - setDraft(String(Number(value.toFixed(3)))); + setDraft(shown); return; } const next = Number(draft); @@ -267,16 +272,16 @@ export function NumericInput({ (min === undefined || next >= min) && (max === undefined || next <= max) ) { - if (next !== Number(value.toFixed(3))) onCommit(next); + if (mixed || next !== Number(value.toFixed(3))) onCommit(next); } // A rejected constraint edit leaves the committed value unchanged. - setDraft(String(Number(value.toFixed(3)))); + setDraft(shown); }} onKeyDown={(e) => { if (e.key === 'Enter') e.currentTarget.blur(); if (e.key === 'Escape') { cancelled.current = true; - setDraft(String(Number(value.toFixed(3)))); + setDraft(shown); e.currentTarget.blur(); } }} @@ -469,6 +474,7 @@ export function LogRangeInput({ zero = false, className, disabled, + mixed = false, onChange, }: { label: string; @@ -478,18 +484,20 @@ export function LogRangeInput({ zero?: boolean; className?: string; disabled?: boolean; + /** Shows no value: the thumb hidden at the start. */ + mixed?: boolean; onChange: (value: number) => void; }) { return ( onChange(logSliderValue(Number(event.target.value), min, max, zero))} /> diff --git a/src/core/warp-handles.ts b/src/core/warp-handles.ts index 07abcd5..3fbc6b9 100644 --- a/src/core/warp-handles.ts +++ b/src/core/warp-handles.ts @@ -360,24 +360,16 @@ export function warpEligibleNodes(model: WarpModel) { /** What a footprint is made from. Without a kind, a handle is a point. */ type WarpFootprintOf = Pick & - Partial>; + Partial>; /** * A line or an area moves as one the free nodes within this many node spacings of it. A sample's - * binding reaches farther, unevenly to either side, so taking every node bound would make the - * ridge's width depend on which triangles the samples fell in, and so on pointer speed. + * binding reaches farther, unevenly to either side, so taking every node the samples are bound to + * would make the ridge's width depend on which triangles they fell in, and so on pointer speed. A + * line also takes every node its whole drawn path is bound to. */ export const warpFootprintSpacings = 0.75; -/** - * A line no longer than this many node spacings that bends off its chord by more than - * `warpShortLineBend` of it is short and curved. With a radius under `warpShortLineRadius` - * spacings, its guides fade across the nodes its samples are bound to. - */ -export const warpShortLineSpacings = 5; -export const warpShortLineBend = 0.035; -export const warpShortLineRadius = 4; - /** Distance from a point to the segment from `a` to `b`. */ function segmentDistance(p: ArrayLike, a: Vec3, b: Vec3) { const ux = b[0] - a[0], @@ -394,32 +386,43 @@ function segmentDistance(p: ArrayLike, a: Vec3, b: Vec3) { return Math.hypot(p[0] - a[0] - t * ux, p[1] - a[1] - t * uy, p[2] - a[2] - t * uz); } -/** Whether a line is short and curved, at this node spacing. */ -function shortCurvedLine(samples: readonly WarpSample[], spacing: number) { - const a = samples[0].restWorld, - b = samples[samples.length - 1].restWorld; - let length = 0, - off = 0; - for (let s = 1; s < samples.length; s++) { - const p = samples[s].restWorld, - q = samples[s - 1].restWorld; - length += Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]); - off = Math.max(off, segmentDistance(p, a, b)); +type WarpPath = NonNullable; +const boundToPath = new WeakMap>(); + +/** The grid nodes a line's drawn path is bound to, in node order. */ +function pathNodes(model: WarpModel, path: WarpPath) { + let paths = boundToPath.get(model); + if (!paths) boundToPath.set(model, (paths = new WeakMap())); + let nodes = paths.get(path); + if (!nodes) { + const bound = new Set(); + for (const { face, barycentric } of path) { + const triangle = regionTriangleOf(model.region, face); + if (triangle < 0) continue; + const { node } = bindTrianglePoint( + model.region, + model.binding, + model.restWorld, + triangle, + barycentric, + ); + for (const n of node) bound.add(n); + } + nodes = [...bound].sort((a, b) => a - b); + paths.set(path, nodes); } - const chord = Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]); - return length <= warpShortLineSpacings * spacing && off > warpShortLineBend * chord; + return nodes; } /** * Where a handle's reach is measured from, by kind. A point is its samples alone. A line or an area * moves as one the free nodes on it: within `warpFootprintSpacings` of the line through its * samples in order, or of an area's samples, found along the grid from the nodes the samples are - * bound to. A sample with none of its own nodes among them adds its most heavily bound one. A short - * curved line whose guides fade across its samples' nodes moves every free node they are bound to: - * guides that hold one of them only partly while the samples pull it whole raise the surface - * between them. An - * area also moves the free nodes on its faces still in the region, and straight-line distance is - * also measured from its outline. Paths start at every free node the samples are bound to. + * bound to. A sample with none of its own nodes among them adds its most heavily bound one. A line + * also moves every free node its drawn path is bound to: guides that hold one of them only partly + * while the line pulls the hits on it raise or sink the surface between the samples. An area also + * moves the free nodes on its faces still in the region, and straight-line distance is also + * measured from its outline. Paths start at every free node the samples are bound to. */ export function handleFootprint(model: WarpModel, handle: WarpFootprintOf): WarpFootprint { const eligible = warpEligibleNodes(model); @@ -467,15 +470,8 @@ export function handleFootprint(model: WarpModel, handle: WarpFootprintOf): Warp }); if (heaviest >= 0) nodes.add(binding.node[heaviest]); } - if (handle.kind === 'line' && handle.radius) { - const spacing = spacingAt(model, new Set([...seeds, ...nodes])); - if ( - reachActivation(handle.radius, spacing) > 0 && - handle.radius < warpShortLineRadius * spacing && - shortCurvedLine(handle.samples, spacing) - ) - for (const n of seeds) nodes.add(n); - } + if (handle.kind === 'line' && handle.path) + for (const n of pathNodes(model, handle.path)) if (eligible[n]) nodes.add(n); } if (handle.kind === 'area' && handle.faces) { const { region, grid, restWorld } = model; diff --git a/src/styles.css b/src/styles.css index ee0a9d5..7e1aba1 100644 --- a/src/styles.css +++ b/src/styles.css @@ -6544,6 +6544,16 @@ optgroup { width: 100%; accent-color: var(--accent); } +/* Selected points that differ: no thumb and no fill until the slider is used. */ +.warp-point-setting > input[type='range'].mixed { + accent-color: var(--muted); +} +.warp-point-setting > input[type='range'].mixed::-webkit-slider-thumb { + opacity: 0; +} +.warp-point-setting > input[type='range'].mixed::-moz-range-thumb { + opacity: 0; +} .warp-point-setting > input[type='number'], .warp-distribute-row > select, .warp-auto-points > select { diff --git a/tests/e2e/warp.spec.ts b/tests/e2e/warp.spec.ts index cb5f419..65542d2 100644 --- a/tests/e2e/warp.spec.ts +++ b/tests/e2e/warp.spec.ts @@ -627,3 +627,132 @@ test('each radius or falloff gesture is one undo step and ends exactly once', as await page.mouse.up(); expect((await sliderState(page)).undo).toBe(cancelled.undo); }); + +/** Every point's radius and falloff, which are selected, what new points take, and undo depth. */ +async function pointSettings(page: Page): Promise<{ + points: { radius: number; falloff: number; selected: boolean }[]; + pointRadius: number | null; + pointFalloff: number; + undo: number; +}> { + return page.evaluate(async () => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { useEditor } = await import( + urls.find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))! + ); + const warp = useEditor.getState().warp; + return { + points: warp.points.map((point: any) => ({ + radius: point.radius as number, + falloff: point.falloff as number, + selected: warp.selectedPoints.includes(point.id) as boolean, + })), + pointRadius: warp.pointRadius as number | null, + pointFalloff: warp.pointFalloff as number, + undo: warp.undo.length as number, + }; + }); +} + +test('selected points with different radii or falloffs show each field as mixed', async ({ + page, +}) => { + await open(page); + await page.keyboard.press('w'); + await page.getByRole('radio', { name: 'Whole part', exact: true }).click(); + await page.getByRole('checkbox', { name: 'Place points automatically' }).uncheck(); + await page.getByRole('button', { name: 'Lay grid', exact: true }).click(); + await expect(page.getByRole('button', { name: 'Close gap', exact: true })).toBeEnabled(); + const radius = page.getByRole('spinbutton', { name: 'Point radius', exact: true }); + const falloff = page.getByRole('spinbutton', { name: 'Point falloff', exact: true }); + const radiusSlider = page.getByRole('slider', { name: 'Point radius slider', exact: true }); + const falloffSlider = page.getByRole('slider', { name: 'Point falloff slider', exact: true }); + const help = page.locator('.warp-point-settings > .anchor-help'); + const set = async (field: typeof radius, value: string) => { + await field.fill(value); + await field.press('Tab'); + }; + /** Adds a point at a spot on the front with these settings, which then selects it alone. */ + const place = async (at: number[], r: string, f: string) => { + const spot = await screen(page, at); + await page.mouse.click(spot.x, spot.y); + await set(radius, r); + await set(falloff, f); + return spot; + }; + const a = await place([-5, 5, 10], '2.6', '70'); + await place([5, 15, 10], '3.8', '35'); + // One selected: its own values, as before. + await expect(radius).toHaveValue('3.8'); + await expect(falloff).toHaveValue('35'); + await expect(help).toContainText('New points use the same settings.'); + const single = await pointSettings(page); + // Typing the value it already has changes nothing. + await set(radius, '3.8'); + expect((await pointSettings(page)).undo).toBe(single.undo); + + // Both selected: both fields mixed, and the text says what a new point gets. + await page.keyboard.down('Shift'); + await page.mouse.click(a.x, a.y); + await page.keyboard.up('Shift'); + expect((await pointSettings(page)).points.map(({ selected }) => selected)).toEqual([true, true]); + for (const field of [radius, falloff]) { + await expect(field).toHaveValue(''); + await expect(field).toHaveAttribute('placeholder', 'Mixed'); + } + for (const slider of [radiusSlider, falloffSlider]) { + await expect(slider).toHaveAttribute('aria-valuetext', 'Mixed'); + await expect(slider).toHaveClass(/mixed/); + } + await expect(help).toHaveText( + 'The selected points move the surface within their own radii. New points use a 3.8 mm radius and 35% falloff.', + ); + await expect(help).not.toContainText('the same settings'); + // A new point gets just that. The gizmo sits between the two selected. + const spot = await screen(page, [-5, 15, 10]); + await page.mouse.click(spot.x, spot.y); + const added = await pointSettings(page); + expect(added.points).toHaveLength(3); + expect(added.points.at(-1)).toEqual({ radius: 3.8, falloff: 0.35, selected: true }); + // Undo takes it away and selects the two again. + await page.keyboard.press('ControlOrMeta+z'); + expect((await pointSettings(page)).points).toHaveLength(2); + + // Typing one of the values into the mixed field sets both, as one undo step. + const mixed = await pointSettings(page); + expect(mixed.points.map(({ selected }) => selected)).toEqual([true, true]); + await set(radius, '2.6'); + const same = await pointSettings(page); + expect(same.points.map(({ radius }) => radius)).toEqual([2.6, 2.6]); + expect(same.undo).toBe(mixed.undo + 1); + // Each field is mixed on its own: the radii now agree and the falloffs do not. + await expect(radius).toHaveValue('2.6'); + await expect(radiusSlider).not.toHaveClass(/mixed/); + await expect(falloff).toHaveValue(''); + await expect(falloffSlider).toHaveAttribute('aria-valuetext', 'Mixed'); + await set(falloff, '35'); + const level = await pointSettings(page); + expect(level.points.map(({ falloff }) => falloff)).toEqual([0.35, 0.35]); + expect(level.undo).toBe(same.undo + 1); + await expect(falloff).toHaveValue('35'); + // Undo gives back each step, and the fields show them mixed again. + await page.keyboard.press('ControlOrMeta+z'); + await expect(falloff).toHaveValue(''); + await page.keyboard.press('ControlOrMeta+z'); + expect((await pointSettings(page)).points.map(({ radius }) => radius)).toEqual([2.6, 3.8]); + await expect(radius).toHaveValue(''); + + // A slider used from mixed sets both. + const box = (await radiusSlider.boundingBox())!; + await page.mouse.click(box.x + 0.5 * box.width, box.y + box.height / 2); + const slid = await pointSettings(page); + expect(slid.points[0].radius).toBe(slid.points[1].radius); + expect(slid.undo).toBe(mixed.undo + 1); + + // Nothing selected: what new points take, as before. + const empty = await screen(page, [0, 27, 0]); + await page.mouse.click(empty.x, empty.y); + expect((await pointSettings(page)).points.some(({ selected }) => selected)).toBe(false); + await expect(radius).not.toHaveValue(''); + await expect(help).toHaveText('New points use this radius and falloff.'); +}); diff --git a/tests/unit/warp-handles.test.ts b/tests/unit/warp-handles.test.ts index 8b0ad01..ffd65b2 100644 --- a/tests/unit/warp-handles.test.ts +++ b/tests/unit/warp-handles.test.ts @@ -853,6 +853,27 @@ describe('footprints', () => { expect(wider.reach).not.toBe(line.reach); expect(wider.reach!.own).toBe(along.length); + // Drawn, a line also moves every free node its path is bound to, at any radius. + const [a, b] = samples.map(({ restWorld }) => restWorld); + const path = Array.from({ length: 41 }, (_, i) => { + const at = [0, 1, 2].map((k) => a[k] + ((b[k] - a[k]) * i) / 40) as Vec3; + const face = faceContaining(geometry, at); + const triangle = readFace(geometry, face); + const point = triangle.closestPointToPoint(new Vector3(...at), new Vector3()); + return { face, barycentric: triangle.getBarycoord(point, new Vector3())!.toArray() as Vec3 }; + }); + const onPath = path.flatMap(({ face, barycentric }) => + bindPoint(model.region, model.binding, model.restWorld, face, barycentric).node.filter( + (n) => !model.grid.fixed[n], + ), + ); + expect(onPath.filter((n) => !along.includes(n)).length).toBeGreaterThan(0); + const drawn = [...new Set([...along, ...onPath])].sort((x, y) => x - y); + for (const radius of [0, 0.5, 2, 20]) { + const reach = reachHandle(model, { ...line, path, radius }).reach!; + expect(Array.from(reach.node.subarray(0, reach.own))).toEqual(drawn); + } + // An area also holds the nodes on its faces. const faces = disc(geometry, 9); const area = reachHandle(model, { ...point, kind: 'area', samples, faces }); diff --git a/tests/unit/warp-strokes.test.ts b/tests/unit/warp-strokes.test.ts index 385c8a8..18d897a 100644 --- a/tests/unit/warp-strokes.test.ts +++ b/tests/unit/warp-strokes.test.ts @@ -2,13 +2,13 @@ import { writeFileSync } from 'node:fs'; import { afterEach, describe, expect, it } from 'vitest'; import { BufferAttribute, + BufferGeometry, CylinderGeometry, PlaneGeometry, SphereGeometry, Triangle, Vector3, } from 'three'; -import type { BufferGeometry } from 'three'; import { triangleCount } from '../../src/core/geometry'; import { finishWarpSettling, @@ -18,8 +18,11 @@ import { type WarpPoint, } from '../../src/core/store'; import { readFace } from '../../src/core/surfaces'; +import { bindTrianglePoint } from '../../src/core/warp-bind'; +import { warpEligibleNodes } from '../../src/core/warp-handles'; import { defaultWarpDensity } from '../../src/core/warp-grid'; -import { isPaintedFace } from '../../src/core/warp-model'; +import { isPaintedFace, type WarpModel } from '../../src/core/warp-model'; +import { regionTriangleOf } from '../../src/core/warp-region'; import { areaBrushFaces, facePoint, @@ -27,7 +30,6 @@ import { strokeSample, type WarpStrokePoint, } from '../../src/core/warp-strokes'; -import { warpShortLineRadius } from '../../src/core/warp-handles'; import type { Part, SceneDocument, Vec3 } from '../../src/core/types'; function partOf(geometry: BufferGeometry): Part { @@ -167,6 +169,22 @@ function profile(part: Part, surface: Surface, handle: WarpPoint) { ); } +const distance = (a: ArrayLike, b: ArrayLike) => + Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]); + +/** Distance from a point to the segment from `a` to `b`. */ +function segmentDistance(p: Vec3, a: Vec3, b: Vec3) { + const u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + const t = Math.max( + 0, + Math.min( + 1, + (u[0] * (p[0] - a[0]) + u[1] * (p[1] - a[1]) + u[2] * (p[2] - a[2])) / distance(a, b) ** 2, + ), + ); + return distance(p, [a[0] + t * u[0], a[1] + t * u[1], a[2] + t * u[2]]); +} + /** The most any local maximum stands above the lowest point within `window` probes each side. */ function worstPeak(zs: number[], window: number) { let worst = 0; @@ -323,7 +341,6 @@ describe('line handles', () => { const line = latest(); const spacing = line.reach!.spacing; expect(2 * a * R).toBeLessThan(3 * spacing); - expect(line.radius).toBeLessThan(warpShortLineRadius * spacing); const lift = 0.5; editor().moveWarpPoints( [{ id: line.id, target: [line.pin[0], line.pin[1], line.pin[2] + lift] }], @@ -350,6 +367,289 @@ describe('line handles', () => { expect(worstPeak(rises, 4)).toBeLessThan(0.02 * lift); }); + /** + * A 10 mm patch of creased relief, a heightfield about as finely and as unevenly triangulated as + * a scanned miniature, and the face under any spot seen from above. + */ + function creasedRelief() { + const size = 10, + cell = 0.05, + n = size / cell; + const height = (x: number, y: number) => + 0.25 * + (Math.abs(Math.sin(4.1 * x + 0.8 * Math.sin(1.9 * y))) + + 0.6 * Math.abs(Math.sin(3.3 * y - 1.7 * x + 0.5))); + let seed = 99; + const noise = () => { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + return seed / 0x7fffffff - 0.5; + }; + // Jittered, in denser and sparser bands, with the cells split either way at random. + const xy: number[][] = []; + for (let j = 0; j <= n; j++) + for (let i = 0; i <= n; i++) { + let u = -size / 2 + i * cell, + v = -size / 2 + j * cell; + if (i > 0 && i < n) u += 0.4 * cell * noise(); + if (j > 0 && j < n) v += 0.4 * cell * noise(); + u += 0.15 * Math.sin((u * Math.PI) / 1.5) * (size / 2 - Math.abs(u)); + v += 0.15 * Math.sin((v * Math.PI) / 1.1) * (size / 2 - Math.abs(v)); + xy.push([u, v]); + } + const at = (i: number, j: number) => { + const [x, y] = xy[j * (n + 1) + i]; + return [x, y, height(x, y)]; + }; + const positions: number[] = []; + for (let j = 0; j < n; j++) + for (let i = 0; i < n; i++) { + const [a, b, c, d] = [at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)]; + if (noise() > 0) positions.push(...a, ...b, ...c, ...a, ...c, ...d); + else positions.push(...a, ...b, ...d, ...b, ...c, ...d); + } + const geometry = new BufferGeometry(); + geometry.setAttribute('position', new BufferAttribute(new Float32Array(positions), 3)); + const key = (x: number, y: number) => + Math.floor((x + size) / cell) * 100000 + Math.floor((y + size) / cell); + const buckets = new Map(); + for (let f = 0; f < positions.length / 9; f++) { + const xs = [0, 3, 6].map((k) => positions[f * 9 + k]), + ys = [1, 4, 7].map((k) => positions[f * 9 + k]); + for (let x = Math.min(...xs); x < Math.max(...xs) + cell; x += cell) + for (let y = Math.min(...ys); y < Math.max(...ys) + cell; y += cell) { + const k = key(Math.min(x, Math.max(...xs)), Math.min(y, Math.max(...ys))); + const list = buckets.get(k) ?? []; + if (!list.includes(f)) list.push(f); + buckets.set(k, list); + } + } + const below = (x: number, y: number): WarpStrokePoint => { + let best: WarpStrokePoint | null = null, + inside = -Infinity; + for (const f of buckets.get(key(x, y)) ?? []) { + const [ax, ay, , bx, by, , cx, cy] = positions.slice(f * 9, f * 9 + 9); + const det = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy); + const l1 = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / det; + const l2 = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / det; + const weights = [l1, l2, 1 - l1 - l2]; + if (Math.min(...weights) <= inside) continue; + inside = Math.min(...weights); + const clamped = weights.map((w) => Math.max(0, w)); + const sum = clamped[0] + clamped[1] + clamped[2]; + best = { face: f, barycentric: clamped.map((w) => w / sum) as Vec3 }; + } + return best!; + }; + return { part: partOf(geometry), height, below }; + } + + /** Whether a spot is painted and every node it is bound to is free. */ + const freeAt = (model: WarpModel, { face, barycentric }: WarpStrokePoint) => + isPaintedFace(model, face) && + bindTrianglePoint( + model.region, + model.binding, + model.restWorld, + regionTriangleOf(model.region, face), + barycentric, + ).node.every((n) => !model.grid.fixed[n]); + + it('lift short lines of every length, direction and bend level on painted patches of creased relief', async () => { + // Six dabs of paint at the default density, ten strokes of up to 1 mm on each, curved either + // way, each pulled 0.5 mm along a view up to 17 degrees off vertical and measured at its hits. + const { part, height, below } = creasedRelief(); + let seed = 5; + const random = () => { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + return seed / 0x7fffffff; + }; + const lift = 0.5; + const failures: string[] = []; + let lines = 0, + lowest = Infinity, + highest = -Infinity, + largest = 0; + for (let dab = 0; dab < 6; dab++) { + const x0 = (random() - 0.5) * 3, + y0 = (random() - 0.5) * 3; + editor().setScene({ name: 'Warp', parts: [part], joints: [] }); + useEditor.setState({ selected: [part.id] }); + editor().setTool('warp'); + editor().setWarpBrushRadius(1.5); + editor().paintWarpRegion( + { partId: part.id, point: [x0, y0, height(x0, y0)], normal: [0, 0, 1] }, + below(x0, y0).face, + false, + true, + ); + editor().endPaintStroke(); + await editor().layWarpGrid(); + const model = session().model!; + for (let k = 0, made = 0; k < 40 && made < 10; k++) { + const direction = random() * Math.PI * 2, + length = 0.1 + random() * 0.9, + bend = (random() - 0.5) * 1.2; + const cx = x0 + (random() - 0.5) * 0.8, + cy = y0 + (random() - 0.5) * 0.8; + const points = Array.from({ length: 61 }, (_, i) => { + const s = i / 60 - 0.5, + q = bend * length * (s * s - 0.25); + return below( + cx + length * s * Math.cos(direction) - q * Math.sin(direction), + cy + length * s * Math.sin(direction) + q * Math.cos(direction), + ); + }); + // A line partly held by fixed nodes stops short by design. + if (!points.every((point) => freeAt(model, point))) continue; + expect(editor().addWarpStroke({ kind: 'line', points })).toBe(true); + made++; + lines++; + const line = latest(); + const tilt = random() * 0.3, + turn = random() * Math.PI * 2; + const up = [ + Math.sin(tilt) * Math.cos(turn), + Math.sin(tilt) * Math.sin(turn), + Math.cos(tilt), + ]; + editor().moveWarpPoints( + [{ id: line.id, target: line.pin.map((p, a) => p + lift * up[a]) as Vec3 }], + 'end', + ); + finishWarpSettling(); + const rest = points.map((p) => facePoint(model, model.positions, p)); + const rises = points.map((p, i) => { + const moved = facePoint(model, session().output!.positions, p); + return [0, 1, 2].reduce((sum, a) => sum + (moved[a] - rest[i][a]) * up[a], 0); + }); + let along = 0; + for (let i = 1; i < rest.length; i++) along += distance(rest[i], rest[i - 1]); + const peak = worstPeak(rises, Math.max(1, Math.round((line.reach!.spacing / along) * 60))); + const low = Math.min(...rises), + high = Math.max(...rises); + [lowest, highest, largest] = [ + Math.min(lowest, low), + Math.max(highest, high), + Math.max(largest, peak), + ]; + if (low < 0.9 * lift || high > 1.1 * lift || peak > 0.05 * lift) + failures.push( + `dab ${dab}, line ${made}: ${(along / line.reach!.spacing).toFixed(1)} spacings, ` + + `${low.toFixed(3)} to ${high.toFixed(3)} mm, peak ${peak.toFixed(3)} mm`, + ); + editor().undoWarpEdit(); + editor().undoWarpEdit(); + } + editor().cancelWarp(); + } + figures['short lines on creased relief'] = { lines, lowest, highest, peak: largest }; + expect(lines).toBe(60); + // Moving only the nodes nearest the samples left 5 of these between 0.41 and 0.54 mm, with + // peaks up to 0.09 mm. + expect(failures).toEqual([]); + }, 30_000); + + it('lift a line by as much on either side of where its footprint used to change', async () => { + // A line along a 1.2 mm tube on a dab of paint at the default density, bowed around it. Its + // footprint used to take more nodes at radii between 1 and 4 node spacings, for lines no + // longer than 5 spacings, bowed off their chord by more than 3.5 % of it. + const R = 0.6; + const part = partOf(new CylinderGeometry(R, R, 12, 12, 70, true).toNonIndexed()); + editor().setScene({ name: 'Warp', parts: [part], joints: [] }); + useEditor.setState({ selected: [part.id] }); + editor().setTool('warp'); + editor().setWarpBrushRadius(1.6); + editor().paintWarpRegion( + { partId: part.id, point: [0, 0, R], normal: [0, 0, 1] }, + surfaceAt(part, [0, 0, R]).face, + false, + true, + ); + editor().endPaintStroke(); + await editor().layWarpGrid(); + const spot = surfaceAt(part, [0, 0, R]); + /** Lifts a line `length` long through the spot, bowed by `bow`, and reads the spot's rise. */ + const lifted = (length: number, bow: number, radius: (spacing: number) => number) => { + const steps = session().undo.length; + const points = Array.from({ length: 81 }, (_, i) => { + const s = i / 80 - 0.5, + around = (bow * length * s * s) / R; + return surfaceAt(part, [R * Math.sin(around), length * s, R * Math.cos(around)]); + }); + expect(editor().addWarpStroke({ kind: 'line', points })).toBe(true); + const line = latest(); + const spacing = line.reach!.spacing; + const at = line.samples.map(({ restWorld }) => restWorld); + let along = 0, + off = 0; + for (let k = 1; k < at.length; k++) { + along += distance(at[k], at[k - 1]); + off = Math.max(off, segmentDistance(at[k], at[0], at.at(-1)!)); + } + editor().moveWarpPoints( + [{ id: line.id, target: [line.pin[0], line.pin[1], line.pin[2] + 0.5] }], + 'end', + ); + editor().setWarpPointSettings({ radius: radius(spacing) }, 'end'); + finishWarpSettling(); + const model = session().model!; + const rise = + facePoint(model, session().output!.positions, spot)[2] - + facePoint(model, model.positions, spot)[2]; + while (session().undo.length > steps) editor().undoWarpEdit(); + return { + rise, + spacings: along / spacing, + bend: off / distance(at[0], at.at(-1)!), + radius: radius(spacing) / spacing, + }; + }; + /** Two values of `x` about `gap` apart either side of where `f` passes 0. */ + const straddle = (f: (x: number) => number, low: number, high: number, gap: number) => { + while (high - low > gap) { + const middle = (low + high) / 2; + if (f(middle) <= 0) low = middle; + else high = middle; + } + return [low, high]; + }; + const twice = (s: number) => 2 * s; + const pairs = { + 'radius of 1 spacing': [ + lifted(0.6, 0.6, (s) => s - 0.0005), + lifted(0.6, 0.6, (s) => s + 0.0005), + ], + 'radius of 4 spacings': [ + lifted(0.6, 0.6, (s) => 4 * s - 0.0005), + lifted(0.6, 0.6, (s) => 4 * s + 0.0005), + ], + 'length of 5 spacings': straddle( + (length) => lifted(length, 0.6, twice).spacings - 5, + 0.3, + 2.5, + 1e-4, + ).map((length) => lifted(length, 0.6, twice)), + 'bend of 3.5 %': straddle((bow) => lifted(0.8, bow, twice).bend - 0.035, 0, 1.5, 1e-5).map( + (bow) => lifted(0.8, bow, twice), + ), + }; + expect(pairs['radius of 1 spacing'].map(({ radius }) => radius > 1)).toEqual([false, true]); + expect(pairs['radius of 4 spacings'].map(({ radius }) => radius > 4)).toEqual([false, true]); + expect(pairs['length of 5 spacings'].map(({ spacings }) => spacings > 5)).toEqual([ + false, + true, + ]); + expect(pairs['bend of 3.5 %'].map(({ bend }) => bend > 0.035)).toEqual([false, true]); + figures['rise either side of the old footprint thresholds'] = Object.fromEntries( + Object.entries(pairs).map(([name, [a, b]]) => [name, [a.rise, b.rise]]), + ); + // These changed the rise by 0.0008, 0.0073, 0.0098 and 0.0028 mm. + for (const [a, b] of Object.values(pairs)) { + expect(a.rise).toBeGreaterThan(0.45); + expect(Math.abs(b.rise - a.rise)).toBeLessThan(0.0001); + } + }); + it('take a sample about every half spacing and merge those bound alike, keeping both ends', async () => { const surface = { ...surfaces.plate, make: () => partOf(new PlaneGeometry(40, 40, 8, 8)) }; const part = await lay(surface); @@ -533,6 +833,22 @@ describe('handles made by strokes through a session', () => { } const offset = (handle: WarpPoint) => handle.target ? handle.target.map((value, a) => value - handle.pin[a]) : null; + /** Whether a line moves as one every free node its drawn path is bound to on the current grid. */ + const movesItsPath = (line: WarpPoint) => { + const model = session().model!; + const eligible = warpEligibleNodes(model); + const own = new Set(line.reach!.node.subarray(0, line.reach!.own)); + const bound = line.path!.flatMap(({ face, barycentric }) => + bindTrianglePoint( + model.region, + model.binding, + model.restWorld, + regionTriangleOf(model.region, face), + barycentric, + ).node.filter((n) => eligible[n]), + ); + return bound.length > 0 && bound.every((n) => own.has(n)); + }; for (const moved of [false, true]) it(`keep the run of a ${moved ? 'moved' : 'still'} line left on a smaller region, centred on it`, async () => { @@ -551,6 +867,7 @@ describe('handles made by strokes through a session', () => { expect(line.path!.length).toBeGreaterThan(10); for (const spot of line.path!) expect(isPaintedFace(model, spot.face)).toBe(true); for (const sample of line.samples) expect(isPaintedFace(model, sample.face)).toBe(true); + expect(movesItsPath(line)).toBe(true); const xs = line.samples.map(({ restWorld }) => restWorld[0]); expect(Math.max(...xs)).toBeLessThan(2.5); expect(Math.max(...xs)).toBeGreaterThan(1); @@ -648,6 +965,7 @@ describe('handles made by strokes through a session', () => { expect(handle.samples.length).toBeGreaterThan(1); expect(handle.reach!.grid).toBe(session().model!.grid); expect(handle.reach!.own).toBeGreaterThan(2); + if (kind === 'line') expect(movesItsPath(handle)).toBe(true); }; /** The handle's spots stand at its lift. */ const holds = (h: number) => { From 9196506cac771471bdc23e3bd250d1f2fd3ca765 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Wed, 18 Nov 2026 21:24:58 -0800 Subject: [PATCH 23/25] Narrow zero-radius warp lines and let mixed sliders reach zero --- .../specs/2026-11-17-warp-handles-design.md | 83 ++++++--- src/components/WarpControls.tsx | 32 +++- src/core/warp-handles.ts | 142 ++++++++++++---- tests/e2e/warp-strokes.spec.ts | 51 ++++++ tests/e2e/warp.spec.ts | 63 +++++++ tests/unit/warp-handles.test.ts | 25 ++- tests/unit/warp-strokes.test.ts | 159 ++++++++++++++---- 7 files changed, 461 insertions(+), 94 deletions(-) diff --git a/docs/superpowers/specs/2026-11-17-warp-handles-design.md b/docs/superpowers/specs/2026-11-17-warp-handles-design.md index bae6121..81ca814 100644 --- a/docs/superpowers/specs/2026-11-17-warp-handles-design.md +++ b/docs/superpowers/specs/2026-11-17-warp-handles-design.md @@ -223,8 +223,12 @@ points section for the selected handles. New handles take the last values set; w selected, setting one is a session undo step of its own. Where the selected handles differ in radius, or in falloff, that field shows no value with a Mixed placeholder and its slider no thumb; a value typed or slid there sets every selected handle, as one undo step, even one equal to a -value some already have. The line under the fields says what a new point will take: the same -settings as the selection when it does, or else its radius and falloff. Until the user +value some already have. The slider's least value counts too: a press at its left end, Home, +Left, Down or Page Down sets 0 on every selected handle, as one undo step, though the hidden +value the slider holds while mixed is already its least. The line under the fields says what +the selection does, and what a new point will take: the same settings as the selection when it +does, or else its radius and falloff. At radius 0 it says the selected point, line or area (or +handles, of mixed kinds) moves the surface it lies on, with nothing added around it. Until the user sets a radius, a new point takes the larger of 6 % of the part's size and 4.5 node spacings where it is clicked, no more than a quarter of the region's extent. Radius 0 is a bare point; automatic points are radius 0. Effectively whole regions are laid at the 2,000-node level and @@ -423,35 +427,60 @@ the shoulder 1,501 faces and 13. **Footprint.** A line or an area moves as one the free nodes within 0.75 node spacings (each node's own) of the line through its samples in order, or of an area's samples, found by walking the grid from the nodes the samples are bound to; a sample with none of its nodes among them adds -its most heavily bound one; an area also moves the free nodes on its faces. A line also moves -every free node its drawn path is bound to: every hit the stroke kept, not only its samples, -whatever its length, bend or radius. Every bound free node seeds the reach's paths, and -straight-line distance is measured from the samples and an area's outline. Taking every node the -samples alone are bound to, as first written, made the ridge's width depend on which triangles -the samples fell in: a binding reaches one to one and a half spacings, unevenly to either side, -and two samplings of one stroke differed by a quarter of the lift. Taking only the nodes near the -samples left nodes a hit is bound to that the guides held only partly while the line pulled the -hit, and the surface between the samples rose or sank: on 16 dabs of paint each on the 35 mm Tomb -Crawler and the torso scaled to 32 mm, at default settings and pulled 0.5 mm along a view up to -25° off the surface, 383 of 509 short lines and 127 of 257 longer ones stood within 0.45 to -0.55 mm with no peak over 0.025 mm, and drawn between two faces on the Tomb Crawler the middle of -a 0.6 mm line reached only 0.265 mm. A rule that took the samples' nodes only for short curved -lines (five spacings at most, bowed off the chord by more than 3.5 %, radius one to four -spacings) fixed the case it was written for and made the lift jump where a line crossed one of -those limits. With the path's nodes, 509 of 509 short lines and 256 of 257 longer ones meet that -tolerance; the other, ending one node spacing from the fixed edge, stands between 0.484 and -0.519 mm with a 0.030 mm peak beside the edge. Whole parts at default settings keep lines within -0.491 and 0.506 mm. Pointer speed does not change a line: its hits are taken every 2 screen -pixels along the pointer's path, so a straight stroke drawn slowly or quickly binds the same -nodes. Section 4 applies with distance measured from the footprint: radius 0 gives a continuous -ridge or a rigid patch, and a radius above 0 adds the smooth skirt. +its most heavily bound one; an area also moves the free nodes on its faces. Every bound free node +seeds the reach's paths, and straight-line distance is measured from the samples, the footprint's +nodes and an area's outline. Taking every node the samples alone are bound to, as first written, +made the ridge's width depend on which triangles the samples fell in: a binding reaches one to +one and a half spacings, unevenly to either side (on the scans, up to nearly three), and two +samplings of one stroke differed by a quarter of the lift. + +**Path nodes.** A line also guides the other free nodes its drawn path is bound to: every hit the +stroke kept, not only its samples. A node left behind while the line pulls the hits on it raises +or sinks the surface between the samples, but lifting every such node with the line widens the +ridge. So each takes a share of the guides graded by how far the path would lag there. A hit +bound to the node by `w`, with weight `B` on free nodes outside the footprint, gives it +`min(1, 6 (w B)^1.5)`, and the node takes the most any hit gives it. As a radius's guides apply +(the activation of section 4), the share rises to a smoothstep of the node's largest `w` over +0.05, and the radius's hold on the node at its baseline lets go by as much: a firm partial lift of +a node the path is bound to, as the radius's profile gives it beside the line, raises or sinks +the surface between the samples. The node's drive weight is the larger of its share and the +radius's `w`. Distance for the radius is still measured from the footprint, so the skirt begins +at the line. Every part of the rule is continuous in the line's length, bend and radius. + +Measured on 16 dabs of paint each, at the fitted brush, and 8 patches at a 3 mm brush, on the +35 mm Tomb Crawler and the torso scaled to 32 mm, with short strokes of 0.1 to 1.2 mm and longer +ones of 1.2 to 4 mm, straight or bowed, pulled 0.5 mm along a view up to 25° off the surface, and +counting a line as level when it stands within 0.45 to 0.55 mm with no peak over 0.025 mm (51 +lines the fixed edge stops short are left out): + +| Rule | Level at radius 0 | Level at default radius | Band at radius 0, Tomb Crawler line | +| ---------------------------- | ----------------- | ----------------------- | ----------------------------------- | +| Before path nodes | 351 of 372 | 300 of 373 | 0.52 mm | +| Every path node moved as one | 370 of 372 | 369 of 373 | 1.28 mm | +| Graded shares | 364 of 372 | 368 of 373 | 0.63 mm | + +The band is the width rising at least 0.45 mm across the middle of a 1.3 mm line drawn between +faces 458196 and 457924 on the Tomb Crawler. Moving every path node as one widened that band by +more than 0.1 mm on 81 of the 372 lines at radius 0, and the surface 0.7 mm beside the line by +more than 0.05 mm on 14; with graded shares, 6 and none. The share trades level against width: +a larger share levels more lines at radius 0 and widens more; a smaller one the reverse (at the +reviewer's line, 0.58 mm wide with 362 level, 0.70 mm with 366, 0.87 mm with 369). On 72 lines +across the whole of both scans, with automatic points, every line stands within 0.486 and +0.516 mm. Pointer speed does not change a line: its hits are taken every 2 screen pixels along +the pointer's path, so a straight stroke drawn slowly or quickly binds the same nodes. Section 4 +applies with distance measured from the footprint: radius 0 gives a continuous ridge or a rigid +patch, and a radius above 0 adds the smooth skirt. Acceptance: along a line handle moved by `h`, the written surface between samples stays within `0.1 h` of `h`, and no local maximum stands more than `0.05 h` above its neighbours; several interior points of an area do the same, including an area smaller than a cell and a 60-node grid; the same -stroke drawn slowly and quickly gives results within `0.02 h`. Measured: a line within 0.007 h -(radius 0: 0.005 h) with no peak above 0.006 h at default density, within 0.011 h on a 60-node -ball; areas within 0.01 h; slow and quick within 0.003 h. On the 32 mm torso scan, lifted 1.92 mm, +stroke drawn slowly and quickly gives results within `0.02 h`. At radius 0, a line raises a band +across it about as narrow as its footprint does alone. Measured: a line within 0.027 h (radius 0: +0.006 h) with no peak above 0.006 h at default density, within 0.013 h with no peak above 0.016 h +on a 60-node ball; areas within 0.01 h; slow and quick within 0.002 h. On wider dabs of creased +relief, the band rising at least 0.9 h across 60 lines at radius 0 is 2.69 node spacings wide on +average and 3.71 at most (the footprint alone: 2.66 and 3.71; every path node moved as one: 3.00 +and 4.36). On the 32 mm torso scan, lifted 1.92 mm, a line across the chest stays between 1.912 and 1.921 mm (default radius: 1.901 and 1.927), where points placed along the same path range from 0.71 to 2.03 mm. diff --git a/src/components/WarpControls.tsx b/src/components/WarpControls.tsx index 73fd0fb..9df9167 100644 --- a/src/components/WarpControls.tsx +++ b/src/components/WarpControls.tsx @@ -3,6 +3,7 @@ import { useMemo, useRef, type FocusEvent, + type KeyboardEvent, type PointerEvent as ReactPointerEvent, } from 'react'; import { LoaderCircle, TriangleAlert } from 'lucide-react'; @@ -20,6 +21,7 @@ import { warpShortfallCause, warpShortfallShown, warpWholePart, + type WarpPoint, type WarpSession, } from '../core/store'; import type { Part } from '../core/types'; @@ -62,9 +64,9 @@ function usePointSettingsGesture() { window.removeEventListener('blur', blur); if (owner.patch) useEditor.getState().setWarpPointSettings(owner.patch, 'end'); }; - const begin = (slider: Slider, pointer: number | null) => { + const begin = (slider: Slider, pointer: number | null, patch: PointSettings | null = null) => { end(); - current.current = { slider, pointer, patch: null, frame: 0 }; + current.current = { slider, pointer, patch, frame: 0 }; window.addEventListener('pointerup', release); window.addEventListener('pointercancel', release); window.addEventListener('blur', blur); @@ -86,6 +88,9 @@ function usePointSettingsGesture() { return gesture; } +/** Keys that take a slider to or toward its least value. */ +const lowering = new Set(['Home', 'PageDown', 'ArrowLeft', 'ArrowDown']); + const isSlider = (target: EventTarget) => target instanceof HTMLInputElement && target.type === 'range'; @@ -96,6 +101,15 @@ const shortfallCauses = { spot: 'A point on the same spot holds it back.', } as const; +/** What selected handles with radius 0 move. */ +function zeroRadius(selected: readonly WarpPoint[]) { + const kinds = new Set(selected.map(({ kind }) => kind)); + const kind = kinds.size === 1 ? selected[0].kind : 'handle'; + return selected.length === 1 + ? `The selected ${kind} moves the surface it lies on, with nothing added around it.` + : `The selected ${kind}s move the surface they lie on, with nothing added around them.`; +} + /** Radius, falloff and Distribute points, for the selected points or for new ones. */ function PointSettingsControls({ warp, part }: { warp: WarpSession; part: Part | undefined }) { const gesture = usePointSettingsGesture(); @@ -121,10 +135,20 @@ function PointSettingsControls({ warp, part }: { warp: WarpSession; part: Part | const shortfall = warpShortfall(warp); const drift = warpPinDrift(warp); const commit = (patch: PointSettings) => useEditor.getState().setWarpPointSettings(patch, 'end'); + // A mixed slider's hidden value is already its least, so choosing that fires no change. + const least = (slider: Slider): PointSettings | null => + (slider === 'radius' ? mixedRadius : mixedFalloff) ? { [slider]: 0 } : null; const owned = (slider: Slider) => ({ 'data-slider': slider, onPointerDown: (event: ReactPointerEvent) => { - if (isSlider(event.target)) gesture.begin(slider, event.pointerId); + if (isSlider(event.target)) gesture.begin(slider, event.pointerId, least(slider)); + }, + onKeyDown: (event: KeyboardEvent) => { + const patch = least(slider); + if (patch && isSlider(event.target) && lowering.has(event.key)) { + gesture.change(slider, patch); + gesture.end(slider); + } }, onBlur: (event: FocusEvent) => { if (isSlider(event.target)) gesture.end(slider); @@ -201,7 +225,7 @@ function PointSettingsControls({ warp, part }: { warp: WarpSession; part: Part | ? `The selected points move the surface within their own radii. ${newPoints}` : radius > 0 ? `Moves the surface within ${Number(radius.toPrecision(3))} mm of the selected ${selected.length === 1 ? 'point' : 'points'}${fade !== null ? `, fading over the outer ${Number(fade.toPrecision(2))} mm` : ''}. ${newPoints}` - : `The selected ${selected.length === 1 ? 'point moves' : 'points move'} the surface at the point only.` + : `${zeroRadius(selected)} ${newPoints}` : warp.pointRadius === null ? 'New points use this falloff, and reach a few grid spacings where you click until you set a radius.' : 'New points use this radius and falloff.'} diff --git a/src/core/warp-handles.ts b/src/core/warp-handles.ts index 3fbc6b9..ad5a4b4 100644 --- a/src/core/warp-handles.ts +++ b/src/core/warp-handles.ts @@ -49,6 +49,12 @@ export interface WarpFootprint { sources: readonly Vec3[]; /** Free nodes paths along the grid start from, at their straight-line distance. */ seeds: readonly number[]; + /** The other free nodes a line's drawn path is bound to, in node order. */ + path: readonly number[]; + /** The most weight any spot of the path gives each of them. */ + pathWeight: readonly number[]; + /** The share of the guides each takes at radius 0. */ + pathShare: readonly number[]; } /** The free nodes a handle's radius and holding band cover on one grid. */ @@ -67,6 +73,10 @@ export interface WarpReach { own: number; /** Intrinsic rest distance from the footprint, mm. */ distance: Float64Array; + /** The least share of the guides each node takes, from the line's path. */ + least: Float64Array; + /** How much of the radius's hold on each node the line's path lets go. */ + release: Float64Array; } export interface WarpHandle { @@ -366,7 +376,7 @@ type WarpFootprintOf = Pick & * A line or an area moves as one the free nodes within this many node spacings of it. A sample's * binding reaches farther, unevenly to either side, so taking every node the samples are bound to * would make the ridge's width depend on which triangles they fell in, and so on pointer speed. A - * line also takes every node its whole drawn path is bound to. + * line's drawn path also guides the other nodes it is bound to, by `warpPathShare`. */ export const warpFootprintSpacings = 0.75; @@ -387,40 +397,55 @@ function segmentDistance(p: ArrayLike, a: Vec3, b: Vec3) { } type WarpPath = NonNullable; -const boundToPath = new WeakMap>(); +type WarpPathBinding = { node: number[]; weight: number[] }[]; +const boundToPath = new WeakMap>(); -/** The grid nodes a line's drawn path is bound to, in node order. */ -function pathNodes(model: WarpModel, path: WarpPath) { +/** How each spot of a line's drawn path is bound to the grid. */ +function pathBinding(model: WarpModel, path: WarpPath) { let paths = boundToPath.get(model); if (!paths) boundToPath.set(model, (paths = new WeakMap())); - let nodes = paths.get(path); - if (!nodes) { - const bound = new Set(); + let bound = paths.get(path); + if (!bound) { + bound = []; for (const { face, barycentric } of path) { const triangle = regionTriangleOf(model.region, face); if (triangle < 0) continue; - const { node } = bindTrianglePoint( + const { node, weight } = bindTrianglePoint( model.region, model.binding, model.restWorld, triangle, barycentric, ); - for (const n of node) bound.add(n); + bound.push({ node, weight }); } - nodes = [...bound].sort((a, b) => a - b); - paths.set(path, nodes); + paths.set(path, bound); } - return nodes; + return bound; } +/** + * At radius 0, a node a spot of a line's path is bound to by `w`, where the spot has weight `B` + * on free nodes outside the footprint, takes `warpPathShare (w B)^warpPathPower` of the guides, + * at most all: as much as holds the path level without lifting the surface beside the line. + */ +export const warpPathShare = 6; +export const warpPathPower = 1.5; +/** + * As a radius's guides apply, a path node's share rises to a smoothstep of its weight over + * `warpPathBound`, and the radius's hold on it at its baseline lets go by as much: a firm partial + * lift of a node the line pulls a spot on raises or sinks the surface between the samples. + */ +export const warpPathBound = 0.05; + /** * Where a handle's reach is measured from, by kind. A point is its samples alone. A line or an area * moves as one the free nodes on it: within `warpFootprintSpacings` of the line through its * samples in order, or of an area's samples, found along the grid from the nodes the samples are * bound to. A sample with none of its own nodes among them adds its most heavily bound one. A line - * also moves every free node its drawn path is bound to: guides that hold one of them only partly - * while the line pulls the hits on it raise or sink the surface between the samples. An area also + * also guides the other free nodes its drawn path is bound to, each by a share that grows with how + * far the path's spots on it would lag (`warpPathShare`): a node left behind while the line pulls + * the spots on it raises or sinks the surface between the samples. An area also * moves the free nodes on its faces still in the region, and straight-line distance is also * measured from its outline. Paths start at every free node the samples are bound to. */ @@ -470,8 +495,33 @@ export function handleFootprint(model: WarpModel, handle: WarpFootprintOf): Warp }); if (heaviest >= 0) nodes.add(binding.node[heaviest]); } - if (handle.kind === 'line' && handle.path) - for (const n of pathNodes(model, handle.path)) if (eligible[n]) nodes.add(n); + } + const path: number[] = [], + pathWeight: number[] = [], + pathShare: number[] = []; + if (handle.kind === 'line' && handle.path) { + const most = new Map(), + share = new Map(); + for (const { node, weight } of pathBinding(model, handle.path)) { + let outside = 0; + node.forEach((n, k) => { + if (eligible[n] && !nodes.has(n)) outside += weight[k]; + }); + node.forEach((n, k) => { + if (!eligible[n] || nodes.has(n)) return; + most.set(n, Math.max(most.get(n) ?? 0, weight[k])); + const lag = weight[k] * outside; + share.set( + n, + Math.max(share.get(n) ?? 0, Math.min(1, warpPathShare * lag ** warpPathPower)), + ); + }); + } + for (const n of [...most.keys()].sort((a, b) => a - b)) { + path.push(n); + pathWeight.push(most.get(n)!); + pathShare.push(share.get(n)!); + } } if (handle.kind === 'area' && handle.faces) { const { region, grid, restWorld } = model; @@ -499,7 +549,7 @@ export function handleFootprint(model: WarpModel, handle: WarpFootprintOf): Warp } const sorted = (set: Set) => [...set].sort((a, b) => a - b); for (const n of nodes) seeds.add(n); - return { nodes: sorted(nodes), sources, seeds: sorted(seeds) }; + return { nodes: sorted(nodes), sources, seeds: sorted(seeds), path, pathWeight, pathShare }; } const sameNumbers = (a: readonly number[], b: readonly number[]) => @@ -509,6 +559,9 @@ const sameNumbers = (a: readonly number[], b: readonly number[]) => const sameFootprint = (a: WarpFootprint, b: WarpFootprint) => sameNumbers(a.nodes, b.nodes) && sameNumbers(a.seeds, b.seeds) && + sameNumbers(a.path, b.path) && + sameNumbers(a.pathWeight, b.pathWeight) && + sameNumbers(a.pathShare, b.pathShare) && a.sources.length === b.sources.length && a.sources.every((p, i) => samePosition(p, b.sources[i])); @@ -701,20 +754,44 @@ export function footprintReach( const spacing = spacingAt(model, seeds.keys()); const activation = reachActivation(radius, spacing); const node = own.slice(), - distance = own.map(() => 0); + distance = own.map(() => 0), + least = own.map(() => 1), + release = own.map(() => 0); + const ownSet = new Set(own); + // The line's path nodes: their least share and how much of the radius's hold they let go. + const share = new Map(), + letGo = new Map(); + footprint.path.forEach((n, k) => { + if (!eligible[n] || ownSet.has(n)) return; + const weight = footprint.pathWeight[k], + at0 = footprint.pathShare[k]; + const bound = smoothstep(weight / warpPathBound); + share.set(n, at0 + activation * (bound - at0)); + letGo.set(n, bound); + }); + const path = new Float64Array(grid.nodes.length).fill(Infinity); if (activation > 0) { const band = bandWidth(0, spacing) + warpTailSpacings * spacing; - const path = new Float64Array(grid.nodes.length).fill(Infinity); const settled = relax(model, seeds, path, eligible, (radius + band) * warpPathStretch); - const ownSet = new Set(own); for (const n of settled.sort((a, b) => a - b)) { if (ownSet.has(n)) continue; const d = Math.max(straight(n), path[n] / warpPathStretch); - if (d >= radius + band) continue; + if (d >= radius + band && !share.has(n)) continue; node.push(n); distance.push(d); + least.push(share.get(n) ?? 0); + release.push(letGo.get(n) ?? 0); + share.delete(n); } } + // Path nodes beyond the radius's reach. + for (const [n, s] of [...share].sort((a, b) => a[0] - b[0])) + if (s > 0) { + node.push(n); + distance.push(Infinity); + least.push(s); + release.push(letGo.get(n)!); + } return { grid, radius, @@ -724,6 +801,8 @@ export function footprintReach( node: Uint32Array.from(node), own: own.length, distance: Float64Array.from(distance), + least: Float64Array.from(least), + release: Float64Array.from(release), }; } @@ -763,9 +842,10 @@ function motionOf(handle: WarpHandle) { * has a profile: unmoved, its weight `w`, holding the surface softly over its radius; moved, 1 * out to its radius and fading to 0 across the band past it. It drives the node toward its * baseline plus its whole offset at stiffness `w`, and holds it at its baseline for the rest of - * the profile, so alone it targets `baseline + w × offset`. A holding term gives way by the - * largest driving weight any other moved handle has there, and so does all of an unmoved - * handle's profile. + * the profile, so alone it targets `baseline + w × offset`. A line's path raises `w` to its + * least share at the nodes the path is bound to and lets go of their hold by its release. A holding + * term gives way by the largest driving weight any other moved handle has there, and so does all of + * an unmoved handle's profile. * Stiffnesses add and the target is their stiffness-weighted mean, so nothing depends on the * order of the handles. The `exact` nodes, such as gap targets, get no guide. Undefined when no * handle guides a node. @@ -811,8 +891,9 @@ export function warpGuides( : d <= radius + band ? 1 - (1 - warpTailShare) * smoothstep((d - radius) / band) : warpTailShare * (1 - smoothstep((d - radius - band) / tail)); - weight[i] = reach.activation * w; - profile[i] = reach.activation * ((1 - motion) * w + motion * held); + const least = reach.least[i]; + weight[i] = Math.max(least, reach.activation * w); + profile[i] = Math.max(least, reach.activation * ((1 - motion) * w + motion * held)); } const share = carry?.get(handle) ?? 1; const offset = handleOffset(handle).map((value) => share * value) as Vec3; @@ -845,7 +926,7 @@ export function warpGuides( const full = warpGuideStiffness * warpNodeStiffness(grid, model.restNodes, n); const others = leader[n] === h ? second[n] : first[n]; const drive = full * weight[i] * (1 - (1 - motion) * others); - const hold = full * (profile[i] - weight[i]) * (1 - others); + const hold = full * (profile[i] - weight[i]) * (1 - others) * (1 - reach.release[i]); const s = drive + hold; if (!(s > 0)) continue; if (stiffness[n] === 0) touched.push(n); @@ -1001,8 +1082,11 @@ export function reachWeights(handle: WarpHandle) { weight[i] = i < reach.own ? 1 - : reach.activation * - handleWeight(reach.distance[i], handle.radius, handle.falloff, reach.spacing); + : Math.max( + reach.least[i], + reach.activation * + handleWeight(reach.distance[i], handle.radius, handle.falloff, reach.spacing), + ); return weight; } diff --git a/tests/e2e/warp-strokes.spec.ts b/tests/e2e/warp-strokes.spec.ts index 4da8885..bd75922 100644 --- a/tests/e2e/warp-strokes.spec.ts +++ b/tests/e2e/warp-strokes.spec.ts @@ -538,6 +538,57 @@ test('the first drag of a new line with the default radius lifts a smooth ridge' expect(found[i] - Math.min(found[i - 1], found[i + 1])).toBeLessThan(0.05 * lift); }); +test('at radius 0 the help says a point, a line or an area moves only the surface it lies on', async ({ + page, +}) => { + await warpFront(page); + const help = page.locator('.warp-point-settings > .anchor-help'); + const radius = page.getByRole('spinbutton', { name: 'Point radius', exact: true }); + const falloff = page.getByRole('spinbutton', { name: 'Point falloff', exact: true }); + const set = async (field: typeof radius, value: string) => { + await field.fill(value); + await field.press('Enter'); + }; + const plain = 'moves the surface it lies on, with nothing added around it.'; + // New handles take radius 0, so each is made with it. + await set(radius, '0'); + const spot = await screen(page, [-6, 4, 10]); + await page.mouse.click(spot.x, spot.y); + await expect(help).toHaveText(`The selected point ${plain} New points use the same settings.`); + await page.getByRole('radio', { name: 'Line', exact: true }).click(); + await drag(page, [ + [-5, 9, 10], + [5, 11, 10], + ]); + await expect(help).toHaveText(`The selected line ${plain} New points use the same settings.`); + await page.getByRole('radio', { name: 'Area', exact: true }).click(); + await drag(page, [ + [-3, 15, 10], + [3, 16, 10], + ]); + await expect(help).toHaveText(`The selected area ${plain} New points use the same settings.`); + const made = await state(page); + expect(made.handles.map(({ kind }: { kind: string }) => kind)).toEqual(['point', 'line', 'area']); + + // With new points set apart, the text says what they take. + const empty = await screen(page, [16, 10, 10]); + await page.mouse.click(empty.x, empty.y); + expect((await state(page)).selected).toEqual([]); + await set(radius, '3.3'); + await set(falloff, '45'); + const select = (ids: string[]) => + inStore(page, 'store.useEditor.getState().selectWarpPoints(args);', ids); + const [point, line, area] = made.handles.map(({ id }: { id: string }) => id); + await select([line]); + await expect(help).toHaveText( + `The selected line ${plain} New points use a 3.3 mm radius and 45% falloff.`, + ); + await select([point, area]); + await expect(help).toHaveText( + 'The selected handles move the surface they lie on, with nothing added around them. New points use a 3.3 mm radius and 45% falloff.', + ); +}); + test('a press on a part in front makes no handle on the part behind', async ({ page }) => { // An opaque cover 4 mm in front of the left of the block's painted face. const cover = part('cover', 'Cover', new BoxGeometry(8, 20, 1), [-6, 10, 14], '#3a4a5a'); diff --git a/tests/e2e/warp.spec.ts b/tests/e2e/warp.spec.ts index 65542d2..ef94931 100644 --- a/tests/e2e/warp.spec.ts +++ b/tests/e2e/warp.spec.ts @@ -756,3 +756,66 @@ test('selected points with different radii or falloffs show each field as mixed' await expect(radius).not.toHaveValue(''); await expect(help).toHaveText('New points use this radius and falloff.'); }); + +test('choosing the least value on a mixed slider sets it on every selected point', async ({ + page, +}) => { + await open(page); + await page.keyboard.press('w'); + await page.getByRole('radio', { name: 'Whole part', exact: true }).click(); + await page.getByRole('checkbox', { name: 'Place points automatically' }).uncheck(); + await page.getByRole('button', { name: 'Lay grid', exact: true }).click(); + await expect(page.getByRole('button', { name: 'Close gap', exact: true })).toBeEnabled(); + const radius = page.getByRole('spinbutton', { name: 'Point radius', exact: true }); + const falloff = page.getByRole('spinbutton', { name: 'Point falloff', exact: true }); + const set = async (field: typeof radius, value: string) => { + await field.fill(value); + await field.press('Tab'); + }; + const place = async (at: number[], r: string, f: string) => { + const spot = await screen(page, at); + await page.mouse.click(spot.x, spot.y); + await set(radius, r); + await set(falloff, f); + return spot; + }; + const a = await place([-5, 5, 10], '2.6', '70'); + await place([5, 15, 10], '3.8', '35'); + await page.keyboard.down('Shift'); + await page.mouse.click(a.x, a.y); + await page.keyboard.up('Shift'); + const mixed = await pointSettings(page); + expect(mixed.points.map(({ selected }) => selected)).toEqual([true, true]); + const blur = () => page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur()); + + for (const [name, setting, field] of [ + ['Point radius slider', 'radius', radius], + ['Point falloff slider', 'falloff', falloff], + ] as const) { + const slider = page.getByRole('slider', { name, exact: true }); + const gestures = { + Home: () => slider.press('Home'), + Left: () => slider.press('ArrowLeft'), + 'a click at the left end': async () => { + const box = (await slider.boundingBox())!; + await page.mouse.click(box.x + 1, box.y + box.height / 2); + }, + }; + for (const [gesture, act] of Object.entries(gestures)) { + await expect(slider, gesture).toHaveAttribute('aria-valuetext', 'Mixed'); + await act(); + const least = await pointSettings(page); + expect( + least.points.map((point) => point[setting]), + `${setting} after ${gesture}`, + ).toEqual([0, 0]); + expect(least.undo, `${setting} after ${gesture}`).toBe(mixed.undo + 1); + await expect(slider).not.toHaveClass(/mixed/); + await expect(field).toHaveValue('0'); + // Undo gives the two values back. + await blur(); + await page.keyboard.press('ControlOrMeta+z'); + expect((await pointSettings(page)).points).toEqual(mixed.points); + } + } +}); diff --git a/tests/unit/warp-handles.test.ts b/tests/unit/warp-handles.test.ts index ffd65b2..879f7bc 100644 --- a/tests/unit/warp-handles.test.ts +++ b/tests/unit/warp-handles.test.ts @@ -33,6 +33,7 @@ import { bandWidth, warpFootprintSpacings, warpGuides, + warpPathBound, warpPathStretch, warpPriorityStrength, warpTailSpacings, @@ -853,7 +854,7 @@ describe('footprints', () => { expect(wider.reach).not.toBe(line.reach); expect(wider.reach!.own).toBe(along.length); - // Drawn, a line also moves every free node its path is bound to, at any radius. + // Drawn, a line also guides the other free nodes its path is bound to, by graded shares. const [a, b] = samples.map(({ restWorld }) => restWorld); const path = Array.from({ length: 41 }, (_, i) => { const at = [0, 1, 2].map((k) => a[k] + ((b[k] - a[k]) * i) / 40) as Vec3; @@ -867,11 +868,27 @@ describe('footprints', () => { (n) => !model.grid.fixed[n], ), ); - expect(onPath.filter((n) => !along.includes(n)).length).toBeGreaterThan(0); - const drawn = [...new Set([...along, ...onPath])].sort((x, y) => x - y); + const others = [...new Set(onPath)].filter((n) => !along.includes(n)).sort((x, y) => x - y); + expect(others.length).toBeGreaterThan(0); + const footprint = handleFootprint(model, { ...line, path }); + expect(footprint.nodes).toEqual(along); + expect(footprint.path).toEqual(others); + for (const share of footprint.pathShare) { + expect(share).toBeGreaterThan(0); + expect(share).toBeLessThanOrEqual(1); + } + expect(Math.min(...footprint.pathShare)).toBeLessThan(Math.max(...footprint.pathShare)); + // As the radius applies, each share rises toward a smoothstep of the node's weight. + const smooth = (t: number) => (t <= 0 ? 0 : t >= 1 ? 1 : t * t * (3 - 2 * t)); for (const radius of [0, 0.5, 2, 20]) { const reach = reachHandle(model, { ...line, path, radius }).reach!; - expect(Array.from(reach.node.subarray(0, reach.own))).toEqual(drawn); + expect(Array.from(reach.node.subarray(0, reach.own))).toEqual(along); + const least = new Map([...reach.node].map((n, i) => [n, reach.least[i]])); + others.forEach((n, k) => { + const at0 = footprint.pathShare[k], + bound = smooth(footprint.pathWeight[k] / warpPathBound); + expect(least.get(n)).toBeCloseTo(at0 + reach.activation * (bound - at0), 12); + }); } // An area also holds the nodes on its faces. diff --git a/tests/unit/warp-strokes.test.ts b/tests/unit/warp-strokes.test.ts index 18d897a..017d140 100644 --- a/tests/unit/warp-strokes.test.ts +++ b/tests/unit/warp-strokes.test.ts @@ -456,7 +456,8 @@ describe('line handles', () => { it('lift short lines of every length, direction and bend level on painted patches of creased relief', async () => { // Six dabs of paint at the default density, ten strokes of up to 1 mm on each, curved either - // way, each pulled 0.5 mm along a view up to 17 degrees off vertical and measured at its hits. + // way, each pulled 0.5 mm along a view up to 17 degrees off vertical and measured at its hits, + // at the default radius and then at radius 0. const { part, height, below } = creasedRelief(); let seed = 5; const random = () => { @@ -465,10 +466,8 @@ describe('line handles', () => { }; const lift = 0.5; const failures: string[] = []; - let lines = 0, - lowest = Infinity, - highest = -Infinity, - largest = 0; + let lines = 0; + const extremes = { default: [Infinity, -Infinity, 0], 'radius 0': [Infinity, -Infinity, 0] }; for (let dab = 0; dab < 6; dab++) { const x0 = (random() - 0.5) * 3, y0 = (random() - 0.5) * 3; @@ -501,10 +500,11 @@ describe('line handles', () => { }); // A line partly held by fixed nodes stops short by design. if (!points.every((point) => freeAt(model, point))) continue; + const steps = session().undo.length; expect(editor().addWarpStroke({ kind: 'line', points })).toBe(true); made++; lines++; - const line = latest(); + let line = latest(); const tilt = random() * 0.3, turn = random() * Math.PI * 2; const up = [ @@ -518,37 +518,134 @@ describe('line handles', () => { ); finishWarpSettling(); const rest = points.map((p) => facePoint(model, model.positions, p)); - const rises = points.map((p, i) => { - const moved = facePoint(model, session().output!.positions, p); - return [0, 1, 2].reduce((sum, a) => sum + (moved[a] - rest[i][a]) * up[a], 0); - }); let along = 0; for (let i = 1; i < rest.length; i++) along += distance(rest[i], rest[i - 1]); - const peak = worstPeak(rises, Math.max(1, Math.round((line.reach!.spacing / along) * 60))); - const low = Math.min(...rises), - high = Math.max(...rises); - [lowest, highest, largest] = [ - Math.min(lowest, low), - Math.max(highest, high), - Math.max(largest, peak), - ]; - if (low < 0.9 * lift || high > 1.1 * lift || peak > 0.05 * lift) - failures.push( - `dab ${dab}, line ${made}: ${(along / line.reach!.spacing).toFixed(1)} spacings, ` + - `${low.toFixed(3)} to ${high.toFixed(3)} mm, peak ${peak.toFixed(3)} mm`, + for (const radius of ['default', 'radius 0'] as const) { + if (radius === 'radius 0') { + editor().setWarpPointSettings({ radius: 0 }, 'end'); + finishWarpSettling(); + line = latest(); + expect(line.radius).toBe(0); + } + const rises = points.map((p, i) => { + const moved = facePoint(model, session().output!.positions, p); + return [0, 1, 2].reduce((sum, a) => sum + (moved[a] - rest[i][a]) * up[a], 0); + }); + const peak = worstPeak( + rises, + Math.max(1, Math.round((line.reach!.spacing / along) * 60)), ); - editor().undoWarpEdit(); - editor().undoWarpEdit(); + const low = Math.min(...rises), + high = Math.max(...rises); + const extreme = extremes[radius]; + [extreme[0], extreme[1], extreme[2]] = [ + Math.min(extreme[0], low), + Math.max(extreme[1], high), + Math.max(extreme[2], peak), + ]; + if (low < 0.9 * lift || high > 1.1 * lift || peak > 0.05 * lift) + failures.push( + `dab ${dab}, line ${made}, ${radius}: ${(along / line.reach!.spacing).toFixed(1)} ` + + `spacings, ${low.toFixed(3)} to ${high.toFixed(3)} mm, peak ${peak.toFixed(3)} mm`, + ); + } + while (session().undo.length > steps) editor().undoWarpEdit(); } editor().cancelWarp(); } - figures['short lines on creased relief'] = { lines, lowest, highest, peak: largest }; + for (const [radius, [lowest, highest, peak]] of Object.entries(extremes)) + figures[`short lines on creased relief${radius === 'default' ? '' : `, ${radius}`}`] = { + lines, + lowest, + highest, + peak, + }; expect(lines).toBe(60); // Moving only the nodes nearest the samples left 5 of these between 0.41 and 0.54 mm, with // peaks up to 0.09 mm. expect(failures).toEqual([]); }, 30_000); + it('raise a ridge at radius 0 about as narrow as the footprint on painted patches of creased relief', async () => { + // Six wider dabs of paint at the default density, ten straight strokes of 0.3 to 1.5 mm on + // each at radius 0, each pulled 0.5 mm straight up. Across its middle, the band of surface + // that rises at least 0.9 of that is measured in the line's node spacings. + const { part, height, below } = creasedRelief(); + let seed = 5; + const random = () => { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + return seed / 0x7fffffff; + }; + const lift = 0.5; + const bands: number[] = []; + let worst = 0; + for (let dab = 0; dab < 6; dab++) { + const x0 = (random() - 0.5) * 3, + y0 = (random() - 0.5) * 3; + editor().setScene({ name: 'Warp', parts: [part], joints: [] }); + useEditor.setState({ selected: [part.id] }); + editor().setTool('warp'); + editor().setWarpBrushRadius(3); + editor().paintWarpRegion( + { partId: part.id, point: [x0, y0, height(x0, y0)], normal: [0, 0, 1] }, + below(x0, y0).face, + false, + true, + ); + editor().endPaintStroke(); + await editor().layWarpGrid(); + const model = session().model!; + editor().setWarpPointSettings({ radius: 0 }, 'end'); + for (let k = 0, made = 0; k < 40 && made < 10; k++) { + const direction = random() * Math.PI * 2, + length = 0.3 + random() * 1.2; + const cx = x0 + (random() - 0.5) * 0.8, + cy = y0 + (random() - 0.5) * 0.8; + const [c, s] = [Math.cos(direction), Math.sin(direction)]; + const points = Array.from({ length: 61 }, (_, i) => + below(cx + length * (i / 60 - 0.5) * c, cy + length * (i / 60 - 0.5) * s), + ); + if (!points.every((point) => freeAt(model, point))) continue; + const steps = session().undo.length; + expect(editor().addWarpStroke({ kind: 'line', points })).toBe(true); + made++; + const line = latest(); + expect(line.radius).toBe(0); + editor().moveWarpPoints( + [{ id: line.id, target: [line.pin[0], line.pin[1], line.pin[2] + lift] }], + 'end', + ); + finishWarpSettling(); + const rise = (spot: WarpStrokePoint) => + facePoint(model, session().output!.positions, spot)[2] - + facePoint(model, model.positions, spot)[2]; + for (const point of points) worst = Math.max(worst, Math.abs(rise(point) - lift)); + /** How far across the middle, to one side, the surface still rises 0.9 of the lift. */ + const edge = (side: number) => { + for (let o = 0.005; o < 1.5; o += 0.005) + if (rise(below(cx - side * o * s, cy + side * o * c)) < 0.9 * lift) return o; + return 1.5; + }; + bands.push((edge(1) + edge(-1)) / line.reach!.spacing); + while (session().undo.length > steps) editor().undoWarpEdit(); + } + editor().cancelWarp(); + } + const mean = bands.reduce((sum, band) => sum + band, 0) / bands.length; + figures['ridge width at radius 0 on creased relief'] = { + lines: bands.length, + mean, + widest: Math.max(...bands), + worst: worst / lift, + }; + expect(bands.length).toBe(60); + expect(worst).toBeLessThan(0.1 * lift); + // The narrow footprint alone made these 2.67 and 3.71 spacings; moving every node the path + // is bound to with the line made them 3.00 and 4.36. + expect(mean).toBeLessThan(2.8); + expect(Math.max(...bands)).toBeLessThan(4); + }, 30_000); + it('lift a line by as much on either side of where its footprint used to change', async () => { // A line along a 1.2 mm tube on a dab of paint at the default density, bowed around it. Its // footprint used to take more nodes at radii between 1 and 4 node spacings, for lines no @@ -834,10 +931,12 @@ describe('handles made by strokes through a session', () => { const offset = (handle: WarpPoint) => handle.target ? handle.target.map((value, a) => value - handle.pin[a]) : null; /** Whether a line moves as one every free node its drawn path is bound to on the current grid. */ - const movesItsPath = (line: WarpPoint) => { + /** Whether the line moves or guides every free node its drawn path is bound to. */ + const guidesItsPath = (line: WarpPoint) => { const model = session().model!; const eligible = warpEligibleNodes(model); - const own = new Set(line.reach!.node.subarray(0, line.reach!.own)); + const { node, least } = line.reach!; + const guided = new Set([...node].filter((_, i) => least[i] > 0)); const bound = line.path!.flatMap(({ face, barycentric }) => bindTrianglePoint( model.region, @@ -847,7 +946,7 @@ describe('handles made by strokes through a session', () => { barycentric, ).node.filter((n) => eligible[n]), ); - return bound.length > 0 && bound.every((n) => own.has(n)); + return bound.length > 0 && bound.every((n) => guided.has(n)); }; for (const moved of [false, true]) @@ -867,7 +966,7 @@ describe('handles made by strokes through a session', () => { expect(line.path!.length).toBeGreaterThan(10); for (const spot of line.path!) expect(isPaintedFace(model, spot.face)).toBe(true); for (const sample of line.samples) expect(isPaintedFace(model, sample.face)).toBe(true); - expect(movesItsPath(line)).toBe(true); + expect(guidesItsPath(line)).toBe(true); const xs = line.samples.map(({ restWorld }) => restWorld[0]); expect(Math.max(...xs)).toBeLessThan(2.5); expect(Math.max(...xs)).toBeGreaterThan(1); @@ -965,7 +1064,7 @@ describe('handles made by strokes through a session', () => { expect(handle.samples.length).toBeGreaterThan(1); expect(handle.reach!.grid).toBe(session().model!.grid); expect(handle.reach!.own).toBeGreaterThan(2); - if (kind === 'line') expect(movesItsPath(handle)).toBe(true); + if (kind === 'line') expect(guidesItsPath(handle)).toBe(true); }; /** The handle's spots stand at its lift. */ const holds = (h: number) => { From 5997b6ce771f01bbd5261d3573e1c1779a853fbb Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Wed, 18 Nov 2026 21:35:31 -0800 Subject: [PATCH 24/25] Set a mixed warp slider to zero only on a primary click --- src/components/WarpControls.tsx | 3 ++- tests/e2e/warp.spec.ts | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/components/WarpControls.tsx b/src/components/WarpControls.tsx index 9df9167..c210bbc 100644 --- a/src/components/WarpControls.tsx +++ b/src/components/WarpControls.tsx @@ -141,7 +141,8 @@ function PointSettingsControls({ warp, part }: { warp: WarpSession; part: Part | const owned = (slider: Slider) => ({ 'data-slider': slider, onPointerDown: (event: ReactPointerEvent) => { - if (isSlider(event.target)) gesture.begin(slider, event.pointerId, least(slider)); + if (event.button === 0 && isSlider(event.target)) + gesture.begin(slider, event.pointerId, least(slider)); }, onKeyDown: (event: KeyboardEvent) => { const patch = least(slider); diff --git a/tests/e2e/warp.spec.ts b/tests/e2e/warp.spec.ts index ef94931..7b355b7 100644 --- a/tests/e2e/warp.spec.ts +++ b/tests/e2e/warp.spec.ts @@ -801,6 +801,13 @@ test('choosing the least value on a mixed slider sets it on every selected point await page.mouse.click(box.x + 1, box.y + box.height / 2); }, }; + // Only the primary button chooses a value. + for (const button of ['right', 'middle'] as const) { + const box = (await slider.boundingBox())!; + await page.mouse.click(box.x + 1, box.y + box.height / 2, { button }); + await page.keyboard.press('Escape'); + expect(await pointSettings(page), `${setting} after a ${button} click`).toEqual(mixed); + } for (const [gesture, act] of Object.entries(gestures)) { await expect(slider, gesture).toHaveAttribute('aria-valuetext', 'Mixed'); await act(); From 70de03f96a200162cb880c0d9fa9d1bdadfbc350 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Wed, 18 Nov 2026 21:38:05 -0800 Subject: [PATCH 25/25] Add the release note for warp handles, lines and the grid --- src/docs/changelog.ts | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/docs/changelog.ts b/src/docs/changelog.ts index b859b2d..a04e53b 100644 --- a/src/docs/changelog.ts +++ b/src/docs/changelog.ts @@ -19,6 +19,40 @@ export interface Release { // Newest first. Each title must be unique: it names the release's link. export const releases: Release[] = [ + { + date: '2026-11-18', + title: 'Warp handles, lines and a clearer grid', + changes: [ + { + kind: 'improved', + text: 'The warp grid is drawn in dark lines that follow the surface and stay readable on any part color. Lines lighten as the grid gets denser, so the model stays visible underneath.', + }, + { + kind: 'improved', + text: 'Warp has its own brush, with a size slider fitted to the part you are warping.', + }, + { + kind: 'new', + text: 'A whole-part warp can place control points automatically, so moving one bends the part and no longer carries it away. Distribute points spreads more points over any region.', + }, + { + kind: 'new', + text: 'Each control point has a radius and a falloff, so one point can move a wide, smooth area.', + }, + { + kind: 'new', + text: 'Feather edge softens the edge of a painted region by letting the surface just beyond it bend too.', + }, + { + kind: 'new', + text: 'Draw a line or paint an area on the surface and move it as one handle, without a peak at each point.', + }, + { + kind: 'improved', + text: 'Warped surfaces fold far less on dense scans, a density or region change is one undo step, and Apply waits for the surface to settle.', + }, + ], + }, { date: '2026-11-17', title: 'Commit versions',