From 1e48cd02faa369e462d2cccad141efeaa1940e10 Mon Sep 17 00:00:00 2001 From: Michael Pearce Date: Tue, 24 Nov 2026 18:20:35 -0800 Subject: [PATCH] (feat) Share brush sizing across tools --- src/App.tsx | 14 +- src/components/BrushSettings.tsx | 190 +++++++++++++++++ src/components/CameraNavigation.tsx | 12 +- src/components/EditorContextMenu.tsx | 11 +- src/components/RefineControls.tsx | 263 +----------------------- src/components/SculptControls.tsx | 11 +- src/components/SurfaceBrushControls.tsx | 150 -------------- src/components/SurfacePaintControls.tsx | 4 +- src/components/SurfacePainter.tsx | 11 +- src/components/WarpControls.tsx | 43 +--- src/core/brush.ts | 44 ++++ src/core/editor-brush.ts | 54 +++++ src/core/keybindings.ts | 4 +- src/hooks/useSliderEdit.ts | 200 ++++++++++++++++++ src/hooks/useWorkbench.ts | 30 +-- src/xr/editor-tools.ts | 3 +- tests/e2e/brush-settings.spec.ts | 35 ++++ 17 files changed, 561 insertions(+), 518 deletions(-) create mode 100644 src/components/BrushSettings.tsx delete mode 100644 src/components/SurfaceBrushControls.tsx create mode 100644 src/core/brush.ts create mode 100644 src/core/editor-brush.ts create mode 100644 src/hooks/useSliderEdit.ts create mode 100644 tests/e2e/brush-settings.spec.ts diff --git a/src/App.tsx b/src/App.tsx index 2943b67..04280e6 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -50,6 +50,7 @@ import { Undo2, X, } from 'lucide-react'; +import { activeBrush } from './core/editor-brush'; import { liveHost, liveSession, @@ -925,11 +926,7 @@ export default function App() { return; } const state = useEditor.getState(); - if ( - event.target instanceof HTMLCanvasElement && - state.tool === 'align' && - state.operation.mode === 'surface' - ) { + if (event.target instanceof HTMLCanvasElement && activeBrush(state)) { event.preventDefault(); event.stopPropagation(); state.openContextMenu({ x: event.clientX, y: event.clientY, kind: 'brush' }); @@ -951,12 +948,7 @@ export default function App() { state.openContextMenu({ x: event.clientX, y: event.clientY, - kind: - target.closest('.viewport') && - state.tool === 'align' && - state.operation.mode === 'surface' - ? 'brush' - : undefined, + kind: target.closest('.viewport') && activeBrush(state) ? 'brush' : undefined, ...(partId ? { partId } : {}), }); }} diff --git a/src/components/BrushSettings.tsx b/src/components/BrushSettings.tsx new file mode 100644 index 0000000..853bb81 --- /dev/null +++ b/src/components/BrushSettings.tsx @@ -0,0 +1,190 @@ +import { useShallow } from 'zustand/react/shallow'; +import type { ReactNode } from 'react'; +import { Eraser, Paintbrush, Undo2 } from 'lucide-react'; +import { useEditor, paintingRefine, paintingWarpRegion } from '../core/store'; +import { activeBrush, contactBrush, refineBrush, type EditorBrush } from '../core/editor-brush'; +import { useSliderEdit } from '../hooks/useSliderEdit'; +import { LogRangeInput, NumericInput } from './ui'; + +function PaintSettings({ full, children }: { full: boolean; children: ReactNode }) { + const erase = useEditor((state) => state.brushErase), + history = useEditor((state) => state.paintHistory), + plane = useEditor((state) => state.brushPlane); + return ( + <> +
+ + + {full ? ( + + ) : null} +
+ {children} + {full ? ( +
+
+ Stay on seed plane + +
+ {plane.enabled ? ( + <> + + +

+ Measured from this patch’s first hit. Clear a patch to choose a new seed plane. +

+ + ) : null} +
+ ) : null} + + ); +} + +function RadiusFields({ + brush, + label, + draft, + onSlide, +}: { + brush: EditorBrush; + label: string; + draft?: number | null; + onSlide?: (radius: number) => void; +}) { + const radius = useEditor(brush.radius); + const range = useEditor(useShallow(brush.slider)); + const set = (radius: number) => brush.setRadius(useEditor.getState(), radius); + const shown = draft ?? radius; + const slide = onSlide ?? set; + return ( + <> + + {range.scale === 'linear' ? ( + slide(Number(event.target.value))} + /> + ) : ( + + )} + + ); +} + +function RefineRadius({ partId }: { partId: string }) { + const slider = useSliderEdit({ + owned: () => useEditor.getState().refine?.partId === partId, + onSet: (value) => refineBrush.setRadius(useEditor.getState(), value), + }); + return ( +
+ +
+ ); +} + +/** The inspector and the viewport popup edit the same active brush. */ +export function BrushSettings({ label = 'Brush radius' }: { label?: string }) { + const brush = useEditor(activeBrush); + const painting = useEditor((state) => paintingWarpRegion(state) || paintingRefine(state)); + const refinePart = useEditor((state) => state.refine?.partId); + if (!brush) return null; + const fields = + brush === refineBrush && refinePart ? ( + + ) : ( + + ); + return painting || brush === contactBrush ? ( + {fields} + ) : ( + fields + ); +} diff --git a/src/components/CameraNavigation.tsx b/src/components/CameraNavigation.tsx index 2cbf36b..922d328 100644 --- a/src/components/CameraNavigation.tsx +++ b/src/components/CameraNavigation.tsx @@ -4,6 +4,7 @@ import { OrbitControls } from '@react-three/drei'; import type { OrbitControls as OrbitControlsImpl } from 'three-stdlib'; import { MOUSE, Quaternion, TOUCH, Vector3 } from 'three'; import { ArrowDown, ArrowLeft, ArrowRight, ArrowUp, Crosshair, Hand, Orbit, X } from 'lucide-react'; +import { activeBrush } from '../core/editor-brush'; import { sceneBounds } from '../core/geometry'; import { hasAlignmentView, partDisplay } from '../core/alignment-visibility'; import { @@ -15,7 +16,7 @@ import { viewDirections, } from '../core/navigation'; import type { CameraDirection, CameraStep } from '../core/navigation'; -import { brushingRefine, paintingRefine, paintingWarpRegion, useEditor } from '../core/store'; +import { useEditor } from '../core/store'; import { usePreferences, useShortcut, withShortcut } from '../core/preferences'; import { clampPendingZoom, wheelZoom, zoomGlideStep } from '../core/zoom'; import { IconButton } from './ui'; @@ -30,14 +31,7 @@ const drawnSelection = (state: Editor) => const initialOrbitTarget: [number, number, number] = [0, 54, 0]; /** Whether a left drag paints with a surface brush rather than moving the camera. */ const brushOwnsLeftDrag = (state: Editor) => - ((state.tool === 'align' && state.operation.mode === 'surface') || - state.tool === 'sculpt' || - paintingWarpRegion(state) || - paintingRefine(state) || - brushingRefine(state)) && - !state.navigationMode && - !state.temporaryOrbit && - !state.pivotPicking; + !!activeBrush(state) && !state.navigationMode && !state.temporaryOrbit && !state.pivotPicking; export function CameraRig() { const freeTransform = useEditor((state) => !!state.freeTransform); diff --git a/src/components/EditorContextMenu.tsx b/src/components/EditorContextMenu.tsx index 8f2fdc3..64cd67e 100644 --- a/src/components/EditorContextMenu.tsx +++ b/src/components/EditorContextMenu.tsx @@ -27,11 +27,12 @@ import { Trash2, UnlockKeyhole, } from 'lucide-react'; +import { contactBrush, activeBrush } from '../core/editor-brush'; import { editorCommands, executeEditorCommand } from '../core/commands'; import type { CommandContext, CommandId } from '../core/commands'; import { useEditor } from '../core/store'; import type { EditorContextMenu as MenuLocation } from '../core/store'; -import { SurfaceBrushControls } from './SurfaceBrushControls'; +import { BrushSettings } from './BrushSettings'; const icons = { copy: Copy, @@ -77,6 +78,8 @@ function OpenContextMenu({ }) { const state = useEditor(); const brush = location.kind === 'brush'; + const brushTitle = + activeBrush(state) === contactBrush ? 'Paint brush settings' : 'Brush settings'; const menu = useRef(null); const previousFocus = useRef(document.activeElement as HTMLElement | null); const typeahead = useRef({ query: '', time: 0 }); @@ -181,7 +184,7 @@ function OpenContextMenu({ ref={menu} className={`editor-context-menu ${brush ? 'brush-context-menu' : ''}`} role={brush ? 'dialog' : 'menu'} - aria-label={brush ? 'Paint brush settings' : 'Component actions'} + aria-label={brush ? brushTitle : 'Component actions'} tabIndex={-1} style={position} onContextMenu={(event) => event.preventDefault()} @@ -258,10 +261,10 @@ function OpenContextMenu({ {brush ? ( <>
- Paint brush settings + {brushTitle} Right-click to adjust · Right-drag to pan
- + diff --git a/src/components/RefineControls.tsx b/src/components/RefineControls.tsx index 2324e18..c014c3b 100644 --- a/src/components/RefineControls.tsx +++ b/src/components/RefineControls.tsx @@ -1,21 +1,10 @@ -import { - useEffect, - useId, - useMemo, - useRef, - useState, - type KeyboardEvent, - type PointerEvent, - type ReactNode, -} from 'react'; +import { useId, useMemo, useState, type ReactNode } from 'react'; import { useShallow } from 'zustand/react/shallow'; import { LoaderCircle, TriangleAlert } from 'lucide-react'; import { isTaskActive, useActivity } from '../core/activity'; -import { fittedSizeRange, partSize } from '../core/geometry'; import type { EdgeInput, EdgeSolve } from '../core/refine-edge'; import type { RegionInput, RegionSolve, RegionShape, Treatment } from '../core/refine-region'; import { - refineBrushRadius, refineDraftLimit, refineEdited, refinePointRemovable, @@ -42,14 +31,12 @@ import { targetKey, withEnd, } from './refine-panel'; -import { SurfaceBrushControls } from './SurfaceBrushControls'; +import { BrushSettings } from './BrushSettings'; +import { useSliderEdit } from '../hooks/useSliderEdit'; import { LogRangeInput, NumericInput, RadioGroup, Section } from './ui'; const editor = () => useEditor.getState(); -const isSlider = (target: EventTarget | null) => - target instanceof HTMLInputElement && target.type === 'range'; - /** What the panel shows of the session: everything but the painted triangles. */ const panelView = (refine: RefineSession | null) => refine && { @@ -81,202 +68,6 @@ function currentTarget() { /** Whether a setting rendered for `target` may still write: the panel still edits that target. */ const ownedBy = (target: string) => () => currentTarget() === target; -/** Keys that change a range input's value. */ -const editingKeys = new Set([ - 'ArrowLeft', - 'ArrowRight', - 'ArrowUp', - 'ArrowDown', - 'PageUp', - 'PageDown', - 'Home', - 'End', -]); - -/** - * One slider's edit. Unless `live`, a value is shown while dragged and set once, when let go or - * changed by key; a blur during a drag waits for the release. A live edit sets each value and - * remembers, through `begin`, how to put back what it started from. Escape cancels the edit (a - * live one with one write back) and the rest of that drag is ignored; so is a value whose target - * is no longer the panel's, and a live drag whose control goes away is put back. A press on a - * mixed slider starts at `least`, the value it shows. - */ -function useSliderEdit({ - owned, - onSet, - live = false, - begin, - mixed = false, - least = 0, -}: { - owned: () => boolean; - onSet: (value: number) => void; - live?: boolean; - begin?: () => () => void; - mixed?: boolean; - least?: number; -}) { - const [draft, setDraft] = useState(null); - const edit = useRef({ - pending: null as number | null, - restore: null as (() => void) | null, - dragging: false, - cancelled: false, - /** Whether the drag's pointer is known to be pressed still. */ - held: false, - /** Removes the drag's window listeners. */ - detach: null as (() => void) | null, - }); - const latest = useRef({ owned, onSet, live, begin }); - latest.current = { owned, onSet, live, begin }; - const row = useRef(null); - const finish = useRef(() => {}); - // Ends a drag's hold on the control, whether it finished or was cancelled. - const release = () => { - const current = edit.current; - current.detach?.(); - current.detach = null; - current.dragging = false; - current.cancelled = false; - current.held = false; - }; - // Drops the edit, putting a live one back; a drag stays cancelled until its pointer is let go. - const cancel = useRef(() => {}); - cancel.current = () => { - const current = edit.current; - const { restore } = current; - current.pending = null; - current.restore = null; - current.cancelled = true; - setDraft(null); - restore?.(); - }; - finish.current = () => { - const current = edit.current; - const next = current.pending; - current.pending = null; - current.restore = null; - release(); - setDraft(null); - if (next !== null && latest.current.owned()) latest.current.onSet(next); - }; - /** - * Follows a drag through the window: its release finishes it. A cancelled drag ends when the - * pointer shows no button pressed, on pointercancel, or when the window regains focus, so a - * release the window never saw does not leave the control locked. - */ - const follow = () => { - const current = edit.current; - current.detach?.(); - const up = (event: globalThis.PointerEvent) => { - current.held = false; - if (!current.dragging) return; - if (current.cancelled) release(); - else if (event.type === 'pointerup') finish.current(); - }; - const moved = (event: globalThis.PointerEvent) => { - if (event.buttons === 0) up(event); - }; - const aborted = () => { - if (!current.cancelled) cancel.current(); - release(); - }; - const focused = (event: Event) => { - if (event.target === window && current.cancelled) release(); - }; - window.addEventListener('pointerup', up); - window.addEventListener('pointermove', moved); - window.addEventListener('pointercancel', aborted); - window.addEventListener('focus', focused); - current.detach = () => { - window.removeEventListener('pointerup', up); - window.removeEventListener('pointermove', moved); - window.removeEventListener('pointercancel', aborted); - window.removeEventListener('focus', focused); - }; - }; - useEffect(() => { - const element = row.current!; - const current = edit.current; - // A range input fires a native change when it is let go, by pointer or by key, and when it - // blurs; a drag ends at the pointer's release instead. - const changed = (event: Event) => { - if (isSlider(event.target) && !current.dragging) finish.current(); - }; - const blurred = (event: Event) => { - if (isSlider(event.target) && !current.dragging) finish.current(); - }; - // The window losing focus mid-drag cancels it: the release may never reach the page. - const deactivated = (event: Event) => { - if (event.type === 'blur' && event.target !== window) return; - if (event.type === 'visibilitychange' && document.visibilityState !== 'hidden') return; - if (current.dragging && !current.cancelled) cancel.current(); - }; - element.addEventListener('change', changed); - element.addEventListener('focusout', blurred); - window.addEventListener('blur', deactivated); - document.addEventListener('visibilitychange', deactivated); - return () => { - element.removeEventListener('change', changed); - element.removeEventListener('focusout', blurred); - window.removeEventListener('blur', deactivated); - document.removeEventListener('visibilitychange', deactivated); - // A control that goes away, or whose target changed, drops its draft and its drag; a live - // drag it abandons is put back as it was before the drag began. - const { restore } = current; - current.pending = null; - current.restore = null; - restore?.(); - current.detach?.(); - current.detach = null; - current.dragging = false; - }; - }, []); - const change = (next: number) => { - const current = edit.current; - const { owned, onSet, live, begin } = latest.current; - if (current.cancelled || !owned()) return; - if (!live) { - current.pending = next; - setDraft(next); - return; - } - current.restore ??= begin?.() ?? null; - onSet(next); - }; - return { - draft, - hidden: mixed && draft === null, - change, - row: (element: HTMLElement | null) => { - row.current = element; - }, - onPointerDown: (event: PointerEvent) => { - if (!isSlider(event.target) || event.button !== 0) return; - const current = edit.current; - release(); - current.dragging = true; - current.held = true; - follow(); - if (mixed && draft === null) change(least); - }, - onKeyDown: (event: KeyboardEvent) => { - if (!isSlider(event.target)) return; - const current = edit.current; - if (event.key !== 'Escape') { - // A key that edits the slider ends a cancelled drag: the user has moved on from it. Any - // other key does so only once its pointer is no longer known to be pressed. - if (!current.dragging) current.cancelled = false; - else if (current.cancelled && (editingKeys.has(event.key) || !current.held)) release(); - return; - } - if (current.pending === null && !current.restore) return; - event.preventDefault(); - cancel.current(); - }, - }; -} - /** * A slider with a number field. A percent setting holds 0 to 1 and shows 0 to 100; a setting with * `range` is in mm on a logarithmic slider. Unless `live`, a drag sets its value once on release; @@ -716,56 +507,12 @@ const shapes: { id: RegionShape; label: string }[] = [ { id: 'sweep', label: 'Sweep' }, ]; -/** The brush radius on the session's part, set once a drag is let go. */ -function BrushRadius() { - const radius = useEditor(refineBrushRadius); - const size = useEditor((s) => { - const part = s.refine && s.scene.parts.find((p) => p.id === s.refine!.partId); - return part ? partSize(part) : 0; - }); - const range = fittedSizeRange(size); - const set = (value: number) => editor().setRefineBrushRadius(value); - const slider = useSliderEdit({ owned: always, onSet: set }); - const shown = slider.draft ?? radius; - return ( -
- - -
- ); -} - -const always = () => true; - /** Paint and Erase, the brush radius, and how much is painted. Session undo takes paint back. */ function PaintControls() { const painted = useEditor((s) => s.refine?.triangles.length ?? 0); return ( <> - } /> +

{painted ? `${painted.toLocaleString()} ${painted === 1 ? 'triangle' : 'triangles'} painted.` @@ -956,7 +703,7 @@ function BrushControls({ view, targets, owned }: ModeProps) { ]} onChange={(kind) => editor().setRefineBrush({ kind })} /> - + ))} - patch('radius', value)} - /> + ; - -/** - * With `fitted`, the radius is the caller's and the slider is logarithmic over its range. A caller - * whose painting has its own undo and ignores the seed plane turns those off, and `radius` replaces - * the radius field and slider. - */ -export function SurfaceBrushControls({ - fitted, - paintUndo = true, - seedPlane = true, - radius: radiusControl, -}: { - fitted?: { - radius: (state: EditorState) => number; - range: { min: number; max: number }; - set: (radius: number) => void; - }; - paintUndo?: boolean; - seedPlane?: boolean; - radius?: ReactNode; -} = {}) { - 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); - return ( - <> -

- - - {paintUndo ? ( - - ) : null} -
- {radiusControl ?? ( - <> - - {fitted ? ( - - ) : ( - setRadius(Number(event.target.value))} - /> - )} - - )} - {seedPlane ? ( -
-
- Stay on seed plane - -
- {plane.enabled ? ( - <> - - -

- Measured from this patch’s first hit. Clear a patch to choose a new seed plane. -

- - ) : null} -
- ) : null} - - ); -} diff --git a/src/components/SurfacePaintControls.tsx b/src/components/SurfacePaintControls.tsx index 9196420..361ee61 100644 --- a/src/components/SurfacePaintControls.tsx +++ b/src/components/SurfacePaintControls.tsx @@ -2,7 +2,7 @@ import type { CSSProperties } from 'react'; import { ArrowRight, Check, Plus, X } from 'lucide-react'; import { useEditor } from '../core/store'; import { contactColors, completedSurfacePairs } from '../core/surfaces'; -import { SurfaceBrushControls } from './SurfaceBrushControls'; +import { BrushSettings } from './BrushSettings'; import { planeKindLabels } from '../core/plane-constraints'; import type { SurfaceMethod } from '../core/types'; import { alignmentPartIds } from '../core/alignment-visibility'; @@ -60,7 +60,7 @@ export function SurfacePaintControls({ : 'Paint one or more pairs of planar areas to orient the parts using fitted planes.'}{' '} Each patch grows as one connected surface; start a new pair for a separate area.

- +
{op.surfacePairs.map((pair, i) => (
- paintingRefine(s) || brushingRefine(s) - ? refineBrushRadius(s) - : paintingWarpRegion(s) || paintingWarpArea(s) - ? warpBrushRadius(s) - : s.brushRadius, - ), + const radius = useEditor((s) => activeBrush(s)?.radius(s) ?? 0), 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 c210bbc..f52328c 100644 --- a/src/components/WarpControls.tsx +++ b/src/components/WarpControls.tsx @@ -28,7 +28,7 @@ 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 { BrushSettings } from './BrushSettings'; import { TransformAdjustments } from './TransformAdjustments'; import { LogRangeInput, NumericInput, RadioGroup, Section } from './ui'; @@ -284,11 +284,8 @@ const addHelp = { } as const; /** What a press on the surface makes, and for an area, Warp's brush size. */ -function AddControls({ part }: { part: Part | undefined }) { +function AddControls() { 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} + {mode === 'area' ? : null}
); } @@ -412,13 +386,6 @@ 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 (
@@ -442,7 +409,7 @@ export function WarpControls() { /> {painted ? ( <> - +

{warp.faces.length ? `${warp.faces.length.toLocaleString()} triangles painted.` @@ -560,7 +527,7 @@ 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.` diff --git a/src/core/brush.ts b/src/core/brush.ts new file mode 100644 index 0000000..eb67f15 --- /dev/null +++ b/src/core/brush.ts @@ -0,0 +1,44 @@ +interface RadiusRange { + min: number; + max: number; +} + +interface RadiusSlider extends RadiusRange { + scale: 'linear' | 'log'; +} + +interface BrushOptions { + radius: (state: State) => number; + write: (state: State, radius: number) => void; + limits?: RadiusRange; + step: number; + slider: (state: State) => RadiusSlider; +} + +/** Shared brush sizing with tool-supplied storage and slider range. */ +export class Brush { + readonly limits: RadiusRange; + readonly radius: BrushOptions['radius']; + readonly slider: BrushOptions['slider']; + readonly step: number; + private readonly write: BrushOptions['write']; + + constructor(options: BrushOptions) { + this.limits = options.limits ?? { min: 0.05, max: 100 }; + this.radius = options.radius; + this.slider = options.slider; + this.step = options.step; + this.write = options.write; + } + + setRadius(state: State, radius: number) { + if (Number.isFinite(radius)) + this.write(state, Math.max(this.limits.min, Math.min(this.limits.max, radius))); + } + + resize(state: State, factor: number) { + const radius = this.radius(state) * factor; + // Keep small brushes adjustable below the usual hundredth of a millimeter. + this.setRadius(state, Number(radius.toFixed(radius < 0.05 ? 3 : 2))); + } +} diff --git a/src/core/editor-brush.ts b/src/core/editor-brush.ts new file mode 100644 index 0000000..0ec5eb8 --- /dev/null +++ b/src/core/editor-brush.ts @@ -0,0 +1,54 @@ +import { fittedSizeRange, partSize } from './geometry'; +import { Brush } from './brush'; +import { + brushingRefine, + paintingRefine, + paintingWarpArea, + paintingWarpRegion, + refineBrushRadius, + useEditor, + warpBrushRadius, +} from './store'; + +type State = ReturnType; +export type EditorBrush = Brush; + +function partSlider(state: State, id: string | undefined) { + const part = state.scene.parts.find((part) => part.id === id); + return { scale: 'log' as const, ...fittedSizeRange(part ? partSize(part) : 0) }; +} + +export const contactBrush = new Brush({ + radius: (state) => state.brushRadius, + write: (state, radius) => state.setBrush({ radius }), + step: 0.5, + slider: () => ({ scale: 'linear', min: 0.1, max: 20 }), +}); +const warpBrush = new Brush({ + radius: warpBrushRadius, + write: (state, radius) => state.setWarpBrushRadius(radius), + step: 0.1, + slider: (state) => partSlider(state, state.warp?.partId), +}); +export const refineBrush = new Brush({ + radius: refineBrushRadius, + write: (state, radius) => state.setRefineBrushRadius(radius), + step: 0.1, + slider: (state) => partSlider(state, state.refine?.partId), +}); +const sculptLimits = { min: 0.01, max: 1000 }; +const sculptBrush = new Brush({ + radius: (state) => state.sculpt?.settings.radius ?? 0, + write: (state, radius) => state.setSculptSettings({ radius }), + step: 0.1, + limits: sculptLimits, + slider: () => ({ scale: 'log', ...sculptLimits }), +}); + +export function activeBrush(state: State): EditorBrush | null { + if (state.tool === 'align' && state.operation.mode === 'surface') return contactBrush; + if (paintingWarpRegion(state) || paintingWarpArea(state)) return warpBrush; + if (paintingRefine(state) || brushingRefine(state)) return refineBrush; + if (state.tool === 'sculpt' && state.sculpt) return sculptBrush; + return null; +} diff --git a/src/core/keybindings.ts b/src/core/keybindings.ts index b9fe118..e1a3de7 100644 --- a/src/core/keybindings.ts +++ b/src/core/keybindings.ts @@ -28,8 +28,8 @@ export const keyActions = { refine: { group: 'Tools', label: 'Refine', keys: ['E'] }, joint: { group: 'Tools', label: 'Create joint', keys: ['J'] }, measure: { group: 'Tools', label: 'Measure distance', keys: ['D'] }, - brushSmaller: { group: 'Tools', label: 'Shrink paint brush', keys: ['['], repeat: true }, - brushLarger: { group: 'Tools', label: 'Grow paint brush', keys: [']'], repeat: true }, + brushSmaller: { group: 'Tools', label: 'Shrink brush', keys: ['['], repeat: true }, + brushLarger: { group: 'Tools', label: 'Grow brush', keys: [']'], repeat: true }, apply: { group: 'Tools', label: 'Apply alignment or joint', keys: ['Enter'] }, cancel: { group: 'Tools', label: 'Cancel tool / clear selection', keys: ['Escape'] }, orbitTool: { group: 'Camera', label: 'Orbit tool', keys: ['O'] }, diff --git a/src/hooks/useSliderEdit.ts b/src/hooks/useSliderEdit.ts new file mode 100644 index 0000000..f808c6a --- /dev/null +++ b/src/hooks/useSliderEdit.ts @@ -0,0 +1,200 @@ +import { useEffect, useRef, useState, type PointerEvent, type KeyboardEvent } from 'react'; + +const isSlider = (target: EventTarget | null) => + target instanceof HTMLInputElement && target.type === 'range'; + +/** Keys that change a range input's value. */ +const editingKeys = new Set([ + 'ArrowLeft', + 'ArrowRight', + 'ArrowUp', + 'ArrowDown', + 'PageUp', + 'PageDown', + 'Home', + 'End', +]); + +/** + * One slider's edit. Unless `live`, a value is shown while dragged and set once, when let go or + * changed by key; a blur during a drag waits for the release. A live edit sets each value and + * remembers, through `begin`, how to put back what it started from. Escape cancels the edit (a + * live one with one write back) and the rest of that drag is ignored; so is a value whose target + * is no longer the panel's, and a live drag whose control goes away is put back. A press on a + * mixed slider starts at `least`, the value it shows. + */ +export function useSliderEdit({ + owned, + onSet, + live = false, + begin, + mixed = false, + least = 0, +}: { + owned: () => boolean; + onSet: (value: number) => void; + live?: boolean; + begin?: () => () => void; + mixed?: boolean; + least?: number; +}) { + const [draft, setDraft] = useState(null); + const edit = useRef({ + pending: null as number | null, + restore: null as (() => void) | null, + dragging: false, + cancelled: false, + /** Whether the drag's pointer is known to be pressed still. */ + held: false, + /** Removes the drag's window listeners. */ + detach: null as (() => void) | null, + }); + const latest = useRef({ owned, onSet, live, begin }); + latest.current = { owned, onSet, live, begin }; + const row = useRef(null); + const finish = useRef(() => {}); + // Ends a drag's hold on the control, whether it finished or was cancelled. + const release = () => { + const current = edit.current; + current.detach?.(); + current.detach = null; + current.dragging = false; + current.cancelled = false; + current.held = false; + }; + // Drops the edit, putting a live one back; a drag stays cancelled until its pointer is let go. + const cancel = useRef(() => {}); + cancel.current = () => { + const current = edit.current; + const { restore } = current; + current.pending = null; + current.restore = null; + current.cancelled = true; + setDraft(null); + restore?.(); + }; + finish.current = () => { + const current = edit.current; + const next = current.pending; + current.pending = null; + current.restore = null; + release(); + setDraft(null); + if (next !== null && latest.current.owned()) latest.current.onSet(next); + }; + /** + * Follows a drag through the window: its release finishes it. A cancelled drag ends when the + * pointer shows no button pressed, on pointercancel, or when the window regains focus, so a + * release the window never saw does not leave the control locked. + */ + const follow = () => { + const current = edit.current; + current.detach?.(); + const up = (event: globalThis.PointerEvent) => { + current.held = false; + if (!current.dragging) return; + if (current.cancelled) release(); + else if (event.type === 'pointerup') finish.current(); + }; + const moved = (event: globalThis.PointerEvent) => { + if (event.buttons === 0) up(event); + }; + const aborted = () => { + if (!current.cancelled) cancel.current(); + release(); + }; + const focused = (event: Event) => { + if (event.target === window && current.cancelled) release(); + }; + window.addEventListener('pointerup', up); + window.addEventListener('pointermove', moved); + window.addEventListener('pointercancel', aborted); + window.addEventListener('focus', focused); + current.detach = () => { + window.removeEventListener('pointerup', up); + window.removeEventListener('pointermove', moved); + window.removeEventListener('pointercancel', aborted); + window.removeEventListener('focus', focused); + }; + }; + useEffect(() => { + const element = row.current!; + const current = edit.current; + // A range input fires a native change when it is let go, by pointer or by key, and when it + // blurs; a drag ends at the pointer's release instead. + const changed = (event: Event) => { + if (isSlider(event.target) && !current.dragging) finish.current(); + }; + const blurred = (event: Event) => { + if (isSlider(event.target) && !current.dragging) finish.current(); + }; + // The window losing focus mid-drag cancels it: the release may never reach the page. + const deactivated = (event: Event) => { + if (event.type === 'blur' && event.target !== window) return; + if (event.type === 'visibilitychange' && document.visibilityState !== 'hidden') return; + if (current.dragging && !current.cancelled) cancel.current(); + }; + element.addEventListener('change', changed); + element.addEventListener('focusout', blurred); + window.addEventListener('blur', deactivated); + document.addEventListener('visibilitychange', deactivated); + return () => { + element.removeEventListener('change', changed); + element.removeEventListener('focusout', blurred); + window.removeEventListener('blur', deactivated); + document.removeEventListener('visibilitychange', deactivated); + // A control that goes away, or whose target changed, drops its draft and its drag; a live + // drag it abandons is put back as it was before the drag began. + const { restore } = current; + current.pending = null; + current.restore = null; + restore?.(); + current.detach?.(); + current.detach = null; + current.dragging = false; + }; + }, []); + const change = (next: number) => { + const current = edit.current; + const { owned, onSet, live, begin } = latest.current; + if (current.cancelled || !owned()) return; + if (!live) { + current.pending = next; + setDraft(next); + return; + } + current.restore ??= begin?.() ?? null; + onSet(next); + }; + return { + draft, + hidden: mixed && draft === null, + change, + row: (element: HTMLElement | null) => { + row.current = element; + }, + onPointerDown: (event: PointerEvent) => { + if (!isSlider(event.target) || event.button !== 0) return; + const current = edit.current; + release(); + current.dragging = true; + current.held = true; + follow(); + if (mixed && draft === null) change(least); + }, + onKeyDown: (event: KeyboardEvent) => { + if (!isSlider(event.target)) return; + const current = edit.current; + if (event.key !== 'Escape') { + // A key that edits the slider ends a cancelled drag: the user has moved on from it. Any + // other key does so only once its pointer is no longer known to be pressed. + if (!current.dragging) current.cancelled = false; + else if (current.cancelled && (editingKeys.has(event.key) || !current.held)) release(); + return; + } + if (current.pending === null && !current.restore) return; + event.preventDefault(); + cancel.current(); + }, + }; +} diff --git a/src/hooks/useWorkbench.ts b/src/hooks/useWorkbench.ts index 9d71a23..f60df51 100644 --- a/src/hooks/useWorkbench.ts +++ b/src/hooks/useWorkbench.ts @@ -1,18 +1,13 @@ import { useEffect, useRef } from 'react'; +import { activeBrush } from '../core/editor-brush'; import { joinLiveSession } from '../core/live'; import { afterReleasedSculpt, committedScene, chosenRefinePoint, - brushingRefine, drawingRefineGuide, liveSession, - paintingRefine, - paintingWarpArea, - paintingWarpRegion, - refineBrushRadius, useEditor, - warpBrushRadius, refineHoldsWork, } from '../core/store'; import { readRecovery, saveRecovery } from '../core/recovery'; @@ -199,15 +194,12 @@ export function useKeyboard(openScene: () => void, searchParts: () => void) { const key = event.key.toLowerCase(); if (key === 'contextmenu' || (key === 'f10' && event.shiftKey)) { event.preventDefault(); - state.openContextMenu( - keyboardContextMenu(target, state.tool === 'align' && state.operation.mode === 'surface'), - ); + state.openContextMenu(keyboardContextMenu(target, !!activeBrush(state))); return; } if (!action || inMenu) return; // Auto-repeat would flicker toggles such as P, O, H, and 5. Only brush sizing repeats. if (event.repeat && !actionRepeats(action)) return; - const paintingSurface = state.tool === 'align' && state.operation.mode === 'surface'; const transformTools = { move: 'translate', rotate: 'rotate', @@ -241,22 +233,10 @@ export function useKeyboard(openScene: () => void, searchParts: () => void) { return; case 'brushSmaller': case 'brushLarger': { - const warping = paintingWarpRegion(state) || paintingWarpArea(state); - const refining = paintingRefine(state) || brushingRefine(state); - if (!paintingSurface && !warping && !refining) return; + const brush = activeBrush(state); + if (!brush) return; event.preventDefault(); - const radius = Number( - ( - (warping - ? warpBrushRadius(state) - : refining - ? refineBrushRadius(state) - : state.brushRadius) * (action === 'brushSmaller' ? 0.8 : 1.25) - ).toFixed(2), - ); - if (warping) state.setWarpBrushRadius(radius); - else if (refining) state.setRefineBrushRadius(radius); - else state.setBrush({ radius }); + brush.resize(state, action === 'brushSmaller' ? 0.8 : 1.25); return; } case 'orbitTool': diff --git a/src/xr/editor-tools.ts b/src/xr/editor-tools.ts index 3095e6d..39d1a85 100644 --- a/src/xr/editor-tools.ts +++ b/src/xr/editor-tools.ts @@ -1,4 +1,5 @@ import { Quaternion, Vector3 } from 'three'; +import { contactBrush } from '../core/editor-brush'; import { isJointConnected } from '../core/constraints'; import { poseAtPivot, quat, worldPoint } from '../core/geometry'; import { hiddenByIsolation } from '../core/isolation'; @@ -491,7 +492,7 @@ export function xrAdjust( if (mode === 'context' && state.tool === 'align') { if (state.operation.mode === 'surface') { if (axis === 'y') { - state.setBrush({ radius: state.brushRadius * Math.exp(step) }); + contactBrush.setRadius(state, contactBrush.radius(state) * Math.exp(step)); return useEditor.getState().brushRadius !== state.brushRadius; } if (state.operation.surfaceMethod === 'angle') { diff --git a/tests/e2e/brush-settings.spec.ts b/tests/e2e/brush-settings.spec.ts new file mode 100644 index 0000000..98c6f7a --- /dev/null +++ b/tests/e2e/brush-settings.spec.ts @@ -0,0 +1,35 @@ +import { expect, test } from '@playwright/test'; + +for (const tool of ['Sculpt', 'Warp', 'Refine']) { + test(`right-click and shortcuts resize the active ${tool} brush`, async ({ page }) => { + await page.goto('/'); + const canvas = page.locator('canvas'); + await expect(canvas).toBeVisible(); + await page + .getByRole('toolbar', { name: 'Assembly tools' }) + .getByRole('button', { name: new RegExp('^' + tool + '\\b') }) + .click(); + if (tool === 'Refine') await page.getByRole('radio', { name: 'Brush', exact: true }).click(); + const inspectorRadius = page.getByRole('spinbutton', { + name: tool === 'Sculpt' ? 'Radius' : 'Brush radius', + exact: true, + }); + await expect(inspectorRadius).toBeVisible(); + await canvas.click({ button: 'right' }); + const popup = page.getByRole('dialog', { name: 'Brush settings' }); + const radius = popup.getByRole('spinbutton', { name: 'Brush radius' }); + await expect(radius).toBeFocused(); + await radius.fill('2'); + await popup.getByRole('button', { name: 'Done' }).click(); + await expect(inspectorRadius).toHaveValue('2'); + await page.keyboard.press(']'); + await expect(inspectorRadius).toHaveValue('2.5'); + await page.keyboard.press('['); + await expect(inspectorRadius).toHaveValue('2'); + await page.keyboard.press('Shift+F10'); + await expect(radius).toBeFocused(); + await expect(radius).toHaveValue('2'); + if (tool === 'Warp') await expect(popup.getByRole('button', { name: 'Erase' })).toBeVisible(); + else await expect(popup.getByRole('button', { name: 'Erase' })).toHaveCount(0); + }); +}