diff --git a/README.md b/README.md index 53a9cee..b9454b8 100644 --- a/README.md +++ b/README.md @@ -490,6 +490,23 @@ shared the mesh keep the original. Warp works on parts of up to 10 million triangles. On a large region the grid lines follow your drag, and the surface updates when you release. +## Sculpt a part + +Select a visible, unlocked part and choose **Sculpt**. Draw builds or removes material, Clay +Buildup layers broad strokes, and Inflate/Deflate changes the volume of rounded details. Grab +moves a patch, Crease sharpens a groove or ridge, and Smooth and Flatten clean up the surface. +The brush adds mesh detail locally as needed. Adjust **Detail** to change the density. + +- Hold **Alt** to invert an applicable brush and **Shift** for temporary smoothing. +- Use **Mask** to protect areas. Hold **Alt** to erase protection or **Shift** to soften it. + Masks stay with the active Sculpt session. Saved scenes contain the sculpted mesh. +- Open **Advanced** for falloff, stroke spacing, stabilization, pen pressure, and brush-specific + controls. When a Wacom tablet reports pen data through the browser, Sculpt can use pressure, + tilt, twist, the eraser, and the barrel button. Available signals depend on the tablet, driver, + and browser. +- Each completed stroke is one undo step, including any triangles it added. Press **Escape** + during a stroke to discard it. + ## Part colors and lighting Editor colors and lighting change only how the scene looks here. Both are undoable, are saved diff --git a/docs/superpowers/plans/2026-11-23-browser-sculpting.md b/docs/superpowers/plans/2026-11-23-browser-sculpting.md new file mode 100644 index 0000000..d29ff56 --- /dev/null +++ b/docs/superpowers/plans/2026-11-23-browser-sculpting.md @@ -0,0 +1,48 @@ +# Browser sculpting implementation plan + +Implement the [Sculpt v1 design](../specs/2026-11-23-browser-sculpting-design.md) +in the existing Three.js workbench. Keep working geometry separate from committed parts. + +- [x] Build and unit-test the editable mesh and brush kernel in `src/core/sculpt-mesh.ts`. + Verify local conforming subdivision of a coarse triangle, connected footprints, masks, + seam interpolation, bounded growth, and brush-specific displacement. +- [x] Add the Sculpt tool, settings and history in `src/core/store.ts`, + `src/components/SculptControls.tsx` and the existing workbench tool entry points. + Verify target identity, visibility and lock eligibility before accepting geometry. +- [x] Connect native pointer input and the editable preview in `src/components/SculptPointer.tsx` + and `src/components/Viewport.tsx`. Verify pressure and orientation, capture and cancellation, + occlusion, mask preview, symmetry and a single checkpoint per accepted stroke. +- [x] Exercise the workflow through the viewport, including undo/redo, automatic detail, + masking and save/reopen. Run the unit suite and production build. +- [x] Measure coarse and dense draft timing and committed mesh size. The sculpt history budget + is 256 MiB for geometry and 64 MiB for mask snapshots. +- [ ] Record physical Wacom results by OS, browser, tablet and driver before claiming compatibility. + +## Viewport measurements + +Chrome 158 on Apple M3 with ANGLE Metal. Times cover pointer receipt through Three.js draw +submission for a fitted 3 mm Draw brush. The probe sends each sample after the previous changed +draw. Queued input, GPU completion, and display presentation need separate measurement. + +| Fixture | First draw | Warm p95 | Warm worst | +| --------------------------- | ---------: | -------: | ---------: | +| 2 triangles | 25.2 ms | 17.5 ms | 17.6 ms | +| 999,698 indexed triangles | 88.0 ms | 25.7 ms | 26.1 ms | +| 999,698 unindexed triangles | 387.9 ms | 29.2 ms | 29.8 ms | + +The dense indexed CPU fixture used about 28 MB per committed mesh. Topology changes on dense +meshes may briefly delay the next stroke while picking is rebuilt. The viewport measurements +exceeded the 60 Hz frame budget on the tested fixtures. + +Run `KITBASHER_SCULPT_VIEWPORT_BENCH=1 npm run test:e2e -- tests/e2e/sculpt-benchmark.spec.ts` to +repeat the viewport measurements. + +## Wide dab measurements + +A 500,000-triangle sheet with a full-footprint 80 mm brush took 213 ms of CPU work for Mask +and 393 ms for Draw. The viewport spreads that work across frames. In the CPU probe, slices +targeted 6 ms and measured 6.4 ms at p95, with a 9.4 ms worst slice. The Draw commit took +19 ms. Preparing the first draft took 166 ms. These times exclude browser rendering. + +Run `KITBASHER_SCULPT_BENCH=1 npx vitest run tests/unit/sculpt-benchmark.test.ts` to repeat +the wide dab measurements. diff --git a/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md b/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md new file mode 100644 index 0000000..0fc9433 --- /dev/null +++ b/docs/superpowers/specs/2026-11-23-browser-sculpting-design.md @@ -0,0 +1,148 @@ +# Browser sculpting v1 + +Status: approved for implementation. + +## Intent + +Add freehand sculpting to Kitbasher's browser workbench, with ZBrush and Blender as workflow +references. The user chose automatic detail under the brush for the first release and asked +for full Wacom tablet support, masking, and advanced brush parameters. The brush set, controls, +and implementation below are proposed. + +## Approaches + +- **Local edge subdivision (recommended).** Split long edges as the brush passes over a coarse + area. Each split preserves the original triangle surfaces until the brush moves them. This + needs a growth limit and a picking index that can keep up with changing topology. +- **Local subdivision and edge collapse.** Also remove short edges to control density. This + adds geometric simplification, attribute transfer, and checks around boundaries and creases. +- **Voxel remeshing.** Kitbasher's current worker reconstructs a closed mesh and drops vertex + colors. Running it on a brush patch would require stitching the patch back into the source, + and can change thin features and open surfaces. + +## Workbench behavior + +Select one visible, unlocked part and choose **Sculpt** in the workbench toolbar. Keep the part +in its assembly so nearby parts remain visible. The panel shows the brush, radius, strength, +detail, and local X symmetry. Show a surface-aligned cursor at the hit under the tip and preview +the mirrored hit when symmetry is enabled. Start each direct dab on the nearest visible surface +under the tip, and act only when it belongs to the selected part. Resolve the mirror against a +nearby surface on that same part, including the far side when symmetry explicitly calls for it. +If the mirrored and direct footprints overlap, apply at most one dab's effect per vertex. + +The brush set includes Draw, Grab, Smooth, Flatten, Crease, Clay Buildup, Inflate/Deflate, and Mask. Draw raises the surface or +digs into it when inverted. Grab moves a patch with the pen. Smooth and Flatten use the local +surface and follow the existing Refine behavior where it suits freehand strokes. Crease pulls the +surface toward the stroke path while cutting a groove. Invert the depth to form a sharp ridge. +Clay Buildup adds broad layers against the local surface plane. Inflate/Deflate moves vertices along their individual surface normals. +Holding Shift temporarily switches to Smooth on the sculpting brushes. In Mask mode it temporarily +softens the mask. + +Strokes preview in the viewport and commit on release. One undo or redo covers deformation and +all topology changes from that stroke. Escape, pointer cancellation, lost capture, blur, or an +external change to the target discards the active stroke. Leaving Sculpt keeps completed strokes. +Commit against the target part's identity, source mesh, and pose. Follow Refine's behavior of +keeping existing pins, anchors, pivot, joints, and constraint frames during a geometry edit. +Committed geometry saves, exports, and shares through the existing part geometry paths. Start +with imported meshes. Later releases can address starter meshes, alphas, sculpt layers, and XR. + +## Advanced brush parameters + +Keep everyday controls visible and group advanced parameters in a collapsible section. Offer a +reset to the defaults for the active brush. Preserve each brush's settings when switching brushes. + +| Group | Proposed controls | +| -------------- | -------------------------------------------------------------------------------- | +| Falloff | Soft, linear, and hard profiles control how strength falls toward the edge. | +| Stroke | Dab spacing as a fraction of brush size and optional stroke stabilization. | +| Pressure | Separate strength and radius toggles and a pressure response curve. | +| Draw footprint | Round or elliptical, with roundness, rotation, and optional tilt or twist input. | +| Crease | Pinch controls how tightly the brush draws the surface toward the stroke path. | +| Detail limits | Minimum edge size bounds local refinement at the selected detail level. | + +Show controls only where the active brush uses them. Update the cursor when radius, footprint, +or symmetry changes. Apply parameter changes to subsequent strokes so the current stroke uses a +consistent configuration. + +## Masking + +- Paint protection with Mask. Use the inverse gesture to erase, Shift to soften the mask, and + offer Invert and Clear for the whole part. Show protection as an overlay with a visibility toggle. +- Mask weights range from zero to one. Partial protection scales down brush displacement and full + protection keeps a point fixed. Use the same connected-surface and symmetry rules as sculpt dabs. + Pressure-sensitive mask strength follows the pen settings. +- Use automatic subdivision for fine mask strokes on coarse faces. Preserve the surface during + those splits and interpolate existing mask weights onto the new vertices, including at seams. + Commit any new triangles alongside the mask stroke, and skip geometry commits when the mesh + stays identical. Fully masked sculpt dabs leave the mesh untouched. +- Keep masks as temporary state for the selected part while Sculpt is open. Within Sculpt, + undo and redo cover mask edits and geometry strokes in order. Roll back both on cancellation + or a refused stroke. Leaving Sculpt clears the overlay and temporary weights. Saved and exported + parts include committed mesh detail. + +## Automatic detail + +- Use the visible hit triangle to seed a connected surface patch. Test triangle overlap with the + brush footprint so a small dab inside a single coarse triangle can still create useful detail. + Stop at disconnected shells and avoid catching the opposite face of a thin wall. +- Refine long edges in the patch to a target derived from radius and detail, with a minimum edge + length in scene units. Split all incident faces of each chosen edge for conformity, including + neighbors just outside the brush. Retain their surface shape, open boundaries, winding, and + seams. Interpolate normals and supported attributes along each render edge. Use a shared + geometric midpoint with separate render vertices where attributes differ. +- Bound per-frame subdivision work and total growth. At the growth limit, show a brief status and + keep brushing at the available density. Roll back subdivision when the stroke changes neither + surface shape nor mask weights. Treat invalid triangles and ambiguous edges as patch boundaries + so usable areas of a damaged scan remain sculptable. +- Keep mutable stroke data separate from saved geometry. Update picking against current triangles + and refresh changed positions and normals locally. Batch splits so a pen sample never triggers + a whole-part topology or GPU rebuild in the input handler. Refine's seam handling and vertex + updates are precedents. Its fast preview currently requires unchanged topology. + +## Wacom behavior + +- Use browser Pointer Events for pen tip, hover, pressure, buttons, and orientation. Consume + coalesced samples where available and resample by brush-relative spacing. Use individual events + as the fallback. Mouse input has steady strength. Touch stays available for navigation outside + the active stroke and secondary contact cannot paint or move the camera during pen contact. +- Enable pressure-sensitive strength by default. Offer pressure-sensitive radius and a pressure + curve. Give a pen barrel button viewport navigation and map the physical eraser to inverted Draw + when the browser exposes those buttons. Use reported tilt to orient an optional angled Draw + footprint and use twist to rotate it when available. Round brush settings work with default or + unavailable orientation data. Keep keyboard and mouse equivalents for brush actions. +- Verify on a physical Wacom Intuos and Cintiq. Start with Windows and macOS in Chromium, then + record the browser, OS, tablet, pen, driver, and features actually delivered for every supported + combination. The proposed launch matrix covers the capabilities exposed by those combinations. + Automated synthetic pen tests establish application behavior. Physical testing establishes tablet + support. [Wacom browser API](https://developer-docs.wacom.com/docs/icbt/web/web-api-overview/) + +## Verification + +- Unit tests cover coarse-triangle dabs, shared splits, open edges, indexed and unindexed inputs, + hard normals and vertex colors, thin and disconnected shells, isolated non-manifold regions, + transformed parts, growth limits, and exact stroke undo and redo. Existing positions beyond the + brush footprint must stay bit-identical. +- Browser tests cover tool entry, live preview, picking after a split, pressure ramps, modifiers, + navigation, cancellation, undo, save/reopen, and shared-scene commit and rejection. A discarded + stroke must leave the committed geometry and history untouched. +- Verify mask painting, erasing, softening, inverting, clearing, and undo across subdivision. Test + that fully protected points keep their positions, partial protection scales the displacement, + and new vertices inherit interpolated weights. Verify that advanced settings affect subsequent + strokes, persist across brush switches, and reset to the active brush's defaults. +- Verify that Crease forms a groove or an inverted ridge on coarse and dense meshes, respects + masking, and undoes its deformation and added topology together. +- Profile input-to-preview latency and retained history memory on a coarse mesh and an approximately + one-million-triangle scan. Use a recorded reference browser and machine. Aim for updates by + the next frame on a 60 Hz display during sustained strokes. Record p95 and worst-case latency, + and set supported mesh sizes and byte limits from the measured budgets before launch. Cap + retained sculpt history by bytes to avoid retaining an unbounded series of dense meshes. +- Run `npm test`, `npm run test:e2e -- tests/e2e/sculpt.spec.ts`, and `npm run build`. Run a physical + tablet pass for hover, slow pressure ramps, fast strokes, barrel navigation, eraser, tilt, twist, + incidental touch, and cancellation where the hardware provides those inputs. + +## Build order + +Mesh subdivision and transactional stroke editing first, followed by viewport picking and input, +then masking, advanced brush parameters, and tablet controls. Measure the coarse and dense +fixtures as soon as the first Draw stroke works end to end. Keep the file format and dependencies +unchanged unless the implementation demonstrates a need to revisit them. diff --git a/mcp/document.ts b/mcp/document.ts index e94353e..eea99dd 100644 --- a/mcp/document.ts +++ b/mcp/document.ts @@ -1,5 +1,6 @@ import type { BufferGeometry } from 'three'; import { useEditor } from '../src/core/store'; +import { matchesSculptTarget, type SculptTarget } from '../src/core/sculpt-session'; import { applyPatch, composePatches, @@ -26,6 +27,8 @@ export interface Edit { checkpoint: boolean; /** Starts the scene over, as opening a file does. */ replace?: boolean; + replacementId?: string; + sculpt?: SculptTarget; } interface Logged { @@ -53,6 +56,8 @@ export class SharedDocument { version = 0; /** Counts scene replacements. Edits made before one no longer apply. */ epoch = 0; + /** Identifies the browser edit that started this epoch, if any. */ + replacementId?: string; private readonly versions = new Map(); private readonly log = new Map(); private readonly histories = new Map(); @@ -74,10 +79,11 @@ export class SharedDocument { } /** Starts over from a scene that nobody can undo, such as a file just opened. */ - replace(scene: SceneDocument, author = agent, saved = true) { + replace(scene: SceneDocument, author = agent, saved = true, replacementId?: string) { useEditor.getState().setScene(scene); if (!saved) useEditor.setState({ savedRevision: -1 }); this.epoch++; + this.replacementId = replacementId; this.versions.clear(); this.log.clear(); this.histories.clear(); @@ -94,16 +100,37 @@ export class SharedDocument { } apply(author: string, edit: Edit) { + if (edit.replace && edit.replacementId && this.replacementId === edit.replacementId) + return this.version; + if ((!edit.replace || edit.replacementId) && edit.epoch !== this.epoch) + throw new EditConflict('The scene was replaced while this change was being made.'); if (edit.replace) { - this.replace(edit.scene, author, false); + this.replace(edit.scene, author, false, edit.replacementId); return this.version; } - if (edit.epoch !== this.epoch) - throw new EditConflict('The scene was replaced while this change was being made.'); const base = this.versions.get(edit.base); if (!base) throw new EditConflict('This change was made on a version of the scene that is too old.'); const current = this.scene; + if (edit.sculpt) { + const target = edit.sculpt; + const part = current.parts.find((part) => part.id === target.partId); + const carved = edit.scene.parts.find((part) => part.id === target.partId); + if (part && carved && carved.geometry === part.geometry) return this.version; + if (!part || !carved || !matchesSculptTarget(part, target)) + throw new EditConflict( + 'The sculpt target changed before the stroke reached the shared scene.', + ); + const next = { + ...current, + parts: current.parts.map((candidate) => + candidate === part ? { ...part, geometry: carved.geometry } : candidate, + ), + }; + useEditor.setState((state) => ({ scene: next, revision: state.revision + 1 })); + this.commit(author, current); + return this.version; + } let next = mergeScenes(base, edit.scene, current, 'ours'); if (base !== current) try { @@ -231,7 +258,11 @@ export class SharedDocument { this.log.set(this.version, { author, summary: summarizePatch(patch), replaced }); this.versions.delete(this.version - keepVersions); this.log.delete(this.version - keepVersions); - for (const part of this.scene.parts) this.meshes.set(part.geometry.uuid, part.geometry); + for (const part of this.scene.parts) { + const { geometry } = part; + this.meshes.set(geometry.uuid, geometry); + this.uploads.delete(geometry.uuid); + } if (changesGeometry(patch)) this.trimMemory(); if (this.version % 50 === 0) this.prune(); for (const listener of this.listeners) listener(); diff --git a/mcp/live.ts b/mcp/live.ts index 2c09f78..c83a25c 100644 --- a/mcp/live.ts +++ b/mcp/live.ts @@ -302,7 +302,7 @@ export class LiveView { } private message() { - const { scene, version, epoch } = this.document; + const { scene, version, epoch, replacementId } = this.document; const geometries: Record = {}; for (const { geometry } of scene.parts) { let layout = this.layouts.get(geometry); @@ -315,6 +315,7 @@ export class LiveView { return `event: scene\ndata: ${JSON.stringify({ version, epoch, + replacementId, scene: sharedScene(scene), geometries, history: this.document.historyCounts(), @@ -426,6 +427,11 @@ export class LiveView { scene, checkpoint: body.checkpoint !== false, replace: body.replace === true, + replacementId: + typeof body.replacementId === 'string' && /^[\w-]{1,64}$/.test(body.replacementId) + ? body.replacementId + : undefined, + sculpt: body.sculpt, }); this.reply(response, 200, { version }); } catch (error) { diff --git a/src/App.tsx b/src/App.tsx index f8ce70b..2943b67 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -15,6 +15,7 @@ import { BoxSelect, Crosshair, Paintbrush, + Brush, Pin, FilePlus2, FolderOpen, @@ -503,6 +504,16 @@ function Toolbar({ Refine {keys.refine ? {keys.refine} : null} + + ))} + + patch('radius', value)} + /> + patch('strength', value)} + /> + patch('detail', value)} + /> + +

+ {brush === 'mask' + ? 'Drag to paint protection. Hold Alt to erase or Shift to soften.' + : 'Drag on the part to sculpt. Hold Shift to smooth.'} + {['draw', 'crease', 'clay', 'inflate'].includes(brush) ? ' Hold Alt to invert.' : ''} +

+
+ +
+ + +
+
+
+ + Advanced brush settings + +
+ + patch('minEdge', value)} + /> + patch('spacing', value)} + /> + patch('stabilization', value)} + /> + + + {(settings.pressureStrength || settings.pressureRadius) && ( + patch('pressureCurve', value)} + /> + )} + {brush === 'draw' && ( + <> + + {settings.aspect < 1 && ( + <> + patch('aspect', value)} + /> + patch('rotation', value)} + /> + + + + )} + + )} + {brush === 'crease' && ( + patch('pinch', value)} + /> + )} + +
+
+ + ); +} diff --git a/src/components/SculptPointer.tsx b/src/components/SculptPointer.tsx new file mode 100644 index 0000000..acf2a9b --- /dev/null +++ b/src/components/SculptPointer.tsx @@ -0,0 +1,818 @@ +import { useEffect } from 'react'; +import { useThree } from '@react-three/fiber'; +import { + BufferAttribute, + BufferGeometry, + DoubleSide, + Matrix3, + Matrix4, + Mesh, + MeshBasicMaterial, + Raycaster, + RingGeometry, + ShaderMaterial, + Vector2, + Vector3, + type Intersection, +} from 'three'; +import { acceleratedRaycast } from 'three-mesh-bvh'; +import { clearSculptIncidence, SculptMesh, type SculptDab } from '../core/sculpt-mesh'; +import { triangleCount } from '../core/geometry'; +import { workerIndexTriangles } from '../core/spatial-index'; +import { + afterReleasedSculpt, + cancelQueuedSculptActions, + flushSculptActions, + setSculptCompletionGate, + useEditor, +} from '../core/store'; +import type { Part, SculptureSettings } from '../core/types'; +import { partMeshes } from '../xr/part-meshes'; +import { SculptPath, type SculptSample as Sample } from '../core/sculpt-path'; +import { boundsEntry } from './RefinePointer'; + +type Hit = Pick; + +const visible = (mesh: Mesh) => { + for (let object = mesh.parent; object; object = object.parent) if (!object.visible) return false; + return mesh.visible; +}; + +function pressure(sample: Sample, settings: SculptureSettings) { + return sample.pointerType === 'pen' ? sample.pressure ** settings.pressureCurve : 1; +} + +function footprint(s: SculptureSettings, sample: Sample) { + const pen = sample.pointerType === 'pen'; + const tilt = s.tilt && pen && (sample.tiltX || sample.tiltY); + const angle = + (s.rotation + (s.twist && pen ? sample.twist : 0)) * (Math.PI / 180) + + (tilt ? Math.atan2(-sample.tiltY, sample.tiltX) : 0); + return angle; +} + +function hitFrom(intersection: Intersection, mesh: Mesh): Hit | null { + if (!intersection.face || intersection.faceIndex == null) return null; + return { + point: intersection.point, + normal: intersection.face.normal + .clone() + .applyNormalMatrix(new Matrix3().getNormalMatrix(mesh.matrixWorld)), + face: intersection.faceIndex, + }; +} + +interface Stroke { + id: number; + target: Part; + mask: Float32Array | null; + epoch: number; + revision: number; + own: Mesh; + draft: SculptMesh; + settings: SculptureSettings; + controls: { enabled: boolean } | null; + controlsEnabled: boolean; + brush: SculptDab['brush']; + eraser: boolean; + latest: Sample; + path: SculptPath; + released: boolean; + work: Generator | null; + changed: boolean; + first: Hit; + grabPoint: Vector3; + grabMirror: Hit | null; + applied: Sample | null; +} + +const sculptPreviews = new WeakMap(); + +export function restoreSculptPreview(mesh: Mesh) { + const preview = sculptPreviews.get(mesh); + if (preview) mesh.geometry = preview; +} + +export function SculptPointer() { + const get = useThree((s) => s.get); + const invalidate = useThree((s) => s.invalidate); + useEffect(() => { + const { events, gl, scene } = get(); + const canvas = events.connected instanceof HTMLElement ? events.connected : gl.domElement; + const ray = new Raycaster(); + ray.firstHitOnly = true; + const ndc = new Vector2(); + const direction = new Vector3(); + const right = new Vector3(); + const cursorShape = new RingGeometry(0.975, 1, 56); + const cursorPaint = new MeshBasicMaterial({ + color: '#ffd195', + side: DoubleSide, + polygonOffset: true, + polygonOffsetFactor: -2, + polygonOffsetUnits: -2, + depthWrite: false, + }); + const cursors = [new Mesh(cursorShape, cursorPaint), new Mesh(cursorShape, cursorPaint)]; + const maskPaint = new ShaderMaterial({ + transparent: true, + depthWrite: false, + polygonOffset: true, + polygonOffsetFactor: -1, + polygonOffsetUnits: -1, + vertexShader: ` + attribute float sculptMask; + varying float protection; + void main() { + protection = sculptMask; + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); + } + `, + fragmentShader: ` + varying float protection; + void main() { gl_FragColor = vec4(0.02, 0.05, 0.09, protection * 0.75); } + `, + }); + const overlay = new Mesh(undefined, maskPaint); + const emptyOverlay = overlay.geometry; + overlay.matrixAutoUpdate = false; + overlay.frustumCulled = false; + overlay.renderOrder = 1; + overlay.visible = false; + const mirrorMaterial = new MeshBasicMaterial({ side: DoubleSide }); + const mirrorMesh = new Mesh(undefined, mirrorMaterial); + const emptyMirror = mirrorMesh.geometry; + mirrorMesh.matrixAutoUpdate = false; + let idleOverlay: BufferGeometry | null = null; + let idleSource: BufferGeometry | null = null; + let idleWeights: Float32Array | null = null; + let stroke: Stroke | null = null; + let disposed = false; + let queuedPointer: { + down: PointerEvent; + partId: string; + epoch: number; + moves: PointerEvent[]; + up?: PointerEvent; + cancelled: boolean; + } | null = null; + let warm: { + source: BufferGeometry; + mask: Float32Array | null; + matrix: Matrix4; + draft: SculptMesh; + } | null = null; + let warmTimer = 0; + const discardWarm = () => { + warm?.draft.geometry.dispose(); + warm = null; + }; + const preparationTarget = () => { + const state = useEditor.getState(); + const sculpt = state.sculpt; + if (!sculpt || state.view.explode || stroke) return null; + const own = partMeshes.get(sculpt.partId); + const part = state.scene.parts.find((p) => p.id === sculpt.partId); + if (!own || !part || part.locked || !visible(own)) return null; + own.updateWorldMatrix(true, false); + return { source: part.geometry, mask: sculpt.mask, matrix: own.matrixWorld }; + }; + const prepare = () => { + if (warmTimer || stroke) return; + warmTimer = window.setTimeout(() => { + warmTimer = 0; + const target = preparationTarget(); + if (!target) return discardWarm(); + const { source, mask, matrix } = target; + if (warm?.source === source && warm.mask === mask && warm.matrix.equals(matrix)) return; + discardWarm(); + const draft = new SculptMesh(source, matrix, mask ?? undefined); + draft.prepare(); + warm = { source, mask, matrix: matrix.clone(), draft }; + }, 60); + }; + let frame = 0; + let hover: Sample | null = null; + let suppressClick = false; + let clickTimer = 0; + const hideCursor = () => cursors.forEach((cursor) => (cursor.visible = false)); + hideCursor(); + scene.add(...cursors, overlay); + + const setRay = (sample: Sample) => { + const rect = canvas.getBoundingClientRect(); + ndc.set( + ((sample.clientX - rect.left) / rect.width) * 2 - 1, + 1 - ((sample.clientY - rect.top) / rect.height) * 2, + ); + ray.setFromCamera(ndc, get().camera); + }; + const intersect = (mesh: Mesh): Intersection[] => { + if (stroke?.own !== mesh) return ray.intersectObject(mesh, false); + const hits: Intersection[] = []; + stroke.draft.raycast(ray, mesh, hits); + return hits; + }; + const pick = ( + sample: Sample, + own: Mesh, + exactOcclusion = false, + source?: BufferGeometry, + ): Hit | null => { + setRay(sample); + let hit: Intersection | undefined; + if (source) { + // The view can still hold the previous render's mesh immediately after a commit. + const displayed = own.geometry; + const hits: Intersection[] = []; + own.geometry = source; + try { + acceleratedRaycast.call(own, ray, hits); + hit = hits.reduce( + (nearest, current) => + !nearest || current.distance < nearest.distance ? current : nearest, + undefined, + ); + } finally { + own.geometry = displayed; + } + } else hit = intersect(own)[0]; + if (!hit || !visible(own)) return null; + for (const mesh of partMeshes.values()) { + if (mesh === own || !visible(mesh)) continue; + const geometry = mesh.geometry; + if (geometry.boundsTree || triangleCount(geometry) <= workerIndexTriangles) { + const other = intersect(mesh)[0]; + if (other && other.distance <= hit.distance) return null; + continue; + } + const entry = boundsEntry(ray.ray, mesh); + if (entry === null || entry > hit.distance) continue; + // Exact fallback is reserved for stroke samples near a mesh whose index is unavailable. + if (!exactOcclusion) return null; + const hits: Intersection[] = []; + ray.far = hit.distance; + try { + Mesh.prototype.raycast.call(mesh, ray, hits); + } finally { + ray.far = Infinity; + } + if (hits.length) return null; + } + return hitFrom(hit, own); + }; + const mirror = (hit: Hit, own: Mesh, radius: number): Hit | null => { + const inverse = new Matrix4().copy(own.matrixWorld).invert(); + const local = hit.point.clone().applyMatrix4(inverse); + if (Math.abs(local.x) < 1e-7) return null; + local.x = -local.x; + const point = local.applyMatrix4(own.matrixWorld); + const direction = hit.normal + .clone() + .applyNormalMatrix(new Matrix3().getNormalMatrix(inverse)); + direction.x = -direction.x; + direction.applyNormalMatrix(new Matrix3().getNormalMatrix(own.matrixWorld)); + const range = radius * 0.2; + mirrorMesh.geometry = own.geometry; + if (!stroke) { + const part = useEditor.getState().scene.parts.find((p) => partMeshes.get(p.id) === own); + if (part) mirrorMesh.geometry = part.geometry; + } + mirrorMesh.matrixWorld.copy(own.matrixWorld); + ray.set(point.clone().addScaledVector(direction, range), direction.clone().negate()); + ray.far = range * 2; + const hits: Intersection[] = []; + ray.firstHitOnly = false; + if (stroke) stroke.draft.raycast(ray, mirrorMesh, hits); + else if ( + mirrorMesh.geometry.boundsTree || + (mirrorMesh.geometry.index?.count ?? mirrorMesh.geometry.getAttribute('position').count) < + 150_000 + ) + acceleratedRaycast.call(mirrorMesh, ray, hits); + ray.firstHitOnly = true; + ray.far = Infinity; + const closest = hits.reduce( + (best, entry) => + !best || entry.point.distanceToSquared(point) < best.point.distanceToSquared(point) + ? entry + : best, + undefined, + ); + return closest ? hitFrom(closest, own) : null; + }; + const tangentAt = (hit: Hit, angle: number) => { + get().camera.matrixWorld.extractBasis(right, new Vector3(), new Vector3()); + const tangent = right.clone().addScaledVector(hit.normal, -right.dot(hit.normal)); + if (tangent.lengthSq() < 1e-8) + tangent.crossVectors( + hit.normal, + Math.abs(hit.normal.y) < 0.9 ? new Vector3(0, 1, 0) : new Vector3(1, 0, 0), + ); + return tangent.normalize().applyAxisAngle(hit.normal, angle); + }; + const reflect = (vector: Vector3, own: Mesh) => { + const local = vector + .clone() + .applyMatrix3(new Matrix3().setFromMatrix4(own.matrixWorld.clone().invert())); + local.x = -local.x; + return local.applyMatrix3(new Matrix3().setFromMatrix4(own.matrixWorld)); + }; + const reflectedTangent = (tangent: Vector3, hit: Hit, own: Mesh) => { + const reflected = reflect(tangent, own); + reflected.addScaledVector(hit.normal, -reflected.dot(hit.normal)); + return reflected.lengthSq() > 1e-8 ? reflected.normalize() : tangentAt(hit, 0); + }; + const show = ( + i: number, + hit: Hit | null, + radius: number, + aspect: number, + tangent?: Vector3, + ) => { + const cursor = cursors[i]; + cursor.visible = !!hit && !!tangent && radius > 0; + if (!hit || !tangent) return; + cursor.position.copy(hit.point).addScaledVector(hit.normal, radius * 0.006); + cursor.quaternion.setFromRotationMatrix( + new Matrix4().makeBasis( + tangent, + new Vector3().crossVectors(hit.normal, tangent), + hit.normal, + ), + ); + cursor.scale.set(radius, radius * aspect, radius); + }; + const displayMask = () => { + const state = useEditor.getState(); + const sculpt = state.sculpt; + const own = sculpt && partMeshes.get(sculpt.partId); + overlay.visible = false; + if ( + !sculpt || + !own || + !sculpt.settings.maskVisible || + (!sculpt.mask && stroke?.brush !== 'mask') || + !visible(own) + ) + return; + const source = state.scene.parts.find((part) => part.id === sculpt.partId)?.geometry; + if (!source) return; + if (stroke?.draft.geometry.hasAttribute('sculptMask')) + overlay.geometry = stroke.draft.geometry; + else if (sculpt.mask) { + if (idleSource !== source || idleWeights !== sculpt.mask || !idleOverlay) { + idleOverlay?.dispose(); + idleSource = source; + idleWeights = sculpt.mask; + idleOverlay = new BufferGeometry(); + idleOverlay.setAttribute('position', source.getAttribute('position')); + idleOverlay.setIndex(source.index); + idleOverlay.setAttribute('sculptMask', new BufferAttribute(sculpt.mask, 1)); + } + overlay.geometry = idleOverlay; + } else return; + overlay.matrix.copy(own.matrixWorld); + overlay.matrixWorldNeedsUpdate = true; + overlay.visible = true; + }; + const refresh = () => { + if (stroke?.work) return; + const state = useEditor.getState(); + const sculpt = state.sculpt; + const own = sculpt && partMeshes.get(sculpt.partId); + if ( + !hover || + !sculpt || + !own || + state.navigationMode || + state.temporaryOrbit || + state.view.explode + ) { + hideCursor(); + } else { + const settings = stroke?.settings ?? sculpt.settings; + const radius = + settings.radius * + (settings.pressureRadius && stroke ? Math.max(0.08, pressure(hover, settings)) : 1); + const hit = pick(hover, own); + const aspect = settings.brush === 'draw' ? settings.aspect : 1; + const angle = footprint(settings, hover); + const tangent = hit ? tangentAt(hit, angle) : undefined; + const twin = hit && settings.symmetry ? mirror(hit, own, radius) : null; + show(0, hit, radius, aspect, tangent); + show( + 1, + twin, + radius, + aspect, + twin && tangent ? reflectedTangent(tangent, twin, own) : undefined, + ); + } + displayMask(); + invalidate(); + }; + const detach = (accept: boolean) => { + const active = stroke; + if (!active) return; + stroke = null; + if (active.controls) active.controls.enabled = active.controlsEnabled; + if (!active.released && canvas.hasPointerCapture(active.id)) + canvas.releasePointerCapture(active.id); + sculptPreviews.delete(active.own); + if (active.own.geometry === active.draft.geometry) { + const part = useEditor.getState().scene.parts.find(({ id }) => id === active.target.id); + active.own.geometry = part?.geometry ?? active.target.geometry; + } + overlay.visible = false; + if (overlay.geometry === active.draft.geometry) overlay.geometry = emptyOverlay; + let refused = !accept && active.released; + if (accept && active.changed) { + const geometry = active.draft.finish(); + const grew = + geometry && + geometry.getAttribute('position').count !== + active.target.geometry.getAttribute('position').count; + const mask = + active.brush === 'mask' || (grew && active.mask) ? active.draft.getMask() : active.mask; + const { id: partId, geometry: source, position, quaternion, scale } = active.target; + if ( + !useEditor.getState().commitSculpt({ + partId, + source, + epoch: active.epoch, + revision: active.revision, + position, + quaternion, + scale, + geometry, + mask: mask?.some((value) => value > 0) ? mask : null, + }) + ) { + geometry?.dispose(); + refused = true; + } + } + if (accept && active.draft.detailLimited) + useEditor + .getState() + .notify( + 'Sculpt detail reached its limit. You can keep brushing at this density.', + 'info', + ); + active.work?.return(false); + active.draft.geometry.dispose(); + if (refused) { + cancelQueuedSculptActions('history'); + // A shared update can interrupt this stroke from inside the store's subscribers. + queueMicrotask(flushSculptActions); + } else flushSculptActions(); + prepare(); + refresh(); + }; + const apply = (active: Stroke, sample: Sample) => { + const s = active.settings; + const brush = + sample.shiftKey && !active.eraser && active.brush !== 'mask' ? 'smooth' : active.brush; + const hit = brush === 'grab' ? active.first : pick(sample, active.own, true); + if (!hit) return; + const p = pressure(sample, s); + const strength = s.strength * (s.pressureStrength ? p : 1); + if (!(strength > 0)) return; + const radius = s.radius * (s.pressureRadius ? Math.max(0.08, p) : 1); + let angle = footprint(s, sample); + if (brush === 'crease' && active.applied) { + const dx = sample.clientX - active.applied.clientX; + const dy = active.applied.clientY - sample.clientY; + if (dx || dy) angle = Math.atan2(dy, dx); + } + active.applied = sample; + const tangent = tangentAt(hit, angle); + const twin = + brush === 'grab' ? active.grabMirror : s.symmetry ? mirror(hit, active.own, radius) : null; + let grab: Vector3 | undefined; + let mirroredGrab: Vector3 | undefined; + if (active.brush === 'grab') { + setRay(sample); + get().camera.getWorldDirection(direction); + const projection = active.first.point.clone().sub(ray.ray.origin).dot(direction); + const point = ray.ray.at(projection / ray.ray.direction.dot(direction), new Vector3()); + grab = point.clone().sub(active.grabPoint); + active.grabPoint.copy(point); + if (twin) mirroredGrab = reflect(grab, active.own); + } + active.work = active.draft.dabWork({ + ...hit, + radius, + strength, + detail: s.detail, + minEdge: s.minEdge, + brush, + falloff: s.falloff, + inverted: active.eraser || sample.altKey, + pinch: s.pinch, + softenMask: brush === 'mask' && sample.shiftKey, + grab, + tangent, + aspect: brush === 'draw' ? s.aspect : 1, + mirror: twin + ? { ...twin, tangent: reflectedTangent(tangent, twin, active.own), grab: mirroredGrab } + : undefined, + }); + }; + const drain = (active: Stroke, until: number) => { + do { + if (active.work) { + const result = active.work.next(); + if (result.done) { + active.changed ||= result.value; + active.work = null; + } + } else { + const sample = active.path.next(); + if (!sample) break; + apply(active, sample); + } + } while ((active.work || active.path.pending) && performance.now() < until); + if (active.released && !active.work && !active.path.pending) detach(true); + }; + const schedule = () => { + if (frame) return; + frame = requestAnimationFrame(() => { + frame = 0; + if (stroke) drain(stroke, performance.now() + 6); + if (stroke && (stroke.work || stroke.path.pending)) schedule(); + refresh(); + }); + }; + const capture = (event: PointerEvent) => { + try { + canvas.setPointerCapture(event.pointerId); + } catch { + /* The pointer may have ended before the queued press is replayed. */ + } + }; + const down = (event: PointerEvent, ended = false, replayed = false) => { + const state = useEditor.getState(); + const sculpt = state.sculpt; + if (stroke && !stroke.released) { + event.stopImmediatePropagation(); + return; + } + if ( + !sculpt || + sculpt.pending || + !event.isPrimary || + (event.button !== 0 && !(event.pointerType === 'pen' && event.button === 5)) || + event.pointerType === 'touch' || + state.navigationMode || + state.temporaryOrbit || + state.pivotPicking || + state.view.explode || + state.freeTransform || + event.ctrlKey || + event.metaKey + ) + return; + if (queuedPointer && !replayed) return; + const gesture = { + down: event, + partId: sculpt.partId, + epoch: state.sceneEpoch, + moves: [], + cancelled: false, + }; + if (afterReleasedSculpt(() => replay(gesture))) { + event.preventDefault(); + event.stopImmediatePropagation(); + queuedPointer = gesture; + capture(event); + return; + } + const target = state.scene.parts.find((part) => part.id === sculpt.partId); + const own = target && partMeshes.get(target.id); + if (!target || !own || target.locked || !visible(own)) return; + const hit = pick(event, own, true, target.geometry); + if (!hit) return; + event.preventDefault(); + event.stopImmediatePropagation(); + if (!ended) capture(event); + const controls = get().controls as { enabled: boolean } | null; + const settings = sculpt.settings; + const camera = get().camera; + const projected = hit.point.clone().project(camera); + const radial = tangentAt(hit, 0) + .multiplyScalar(settings.radius) + .add(hit.point) + .project(camera); + const rect = canvas.getBoundingClientRect(); + const radiusPixels = + Math.hypot((radial.x - projected.x) * rect.width, (radial.y - projected.y) * rect.height) / + 2; + const cached = + warm?.source === target.geometry && + warm.mask === sculpt.mask && + warm.matrix.equals(own.matrixWorld) + ? warm.draft + : null; + if (cached) warm = null; + else discardWarm(); + const draft = + cached ?? new SculptMesh(target.geometry, own.matrixWorld, sculpt.mask ?? undefined); + const eraser = event.button === 5; + const brush = settings.brush === 'mask' ? 'mask' : eraser ? 'draw' : settings.brush; + stroke = { + id: event.pointerId, + target, + mask: sculpt.mask, + epoch: state.sceneEpoch, + revision: sculpt.revision, + own, + draft, + controls, + controlsEnabled: controls?.enabled ?? false, + settings, + brush, + eraser, + first: hit, + grabPoint: hit.point.clone(), + grabMirror: + brush === 'grab' && settings.symmetry ? mirror(hit, own, settings.radius) : null, + applied: null, + latest: event, + path: new SculptPath( + event, + (a, b) => { + const scale = settings.pressureRadius + ? Math.max(0.08, Math.min(pressure(a, settings), pressure(b, settings))) + : 1; + const footprint = settings.brush === 'draw' ? settings.aspect : 1; + return Math.max(0.025, radiusPixels * footprint * settings.spacing * scale); + }, + settings.stabilization, + ), + changed: false, + released: false, + work: null, + }; + if (controls) controls.enabled = false; + sculptPreviews.set(own, draft.geometry); + own.geometry = draft.geometry; + hover = event; + schedule(); + }; + const move = (event: PointerEvent, replayed = false) => { + if (!replayed && queuedPointer?.down.pointerId === event.pointerId) { + queuedPointer.moves.push(event); + event.stopImmediatePropagation(); + return; + } + if (stroke) { + if (event.pointerId !== stroke.id) return; + event.stopImmediatePropagation(); + if (stroke.released) return; + const events = event.getCoalescedEvents?.() ?? []; + stroke.latest = events.at(-1) ?? event; + for (const sample of events.length ? events : [event]) stroke.path.push(sample); + } else if (!canvas.contains(event.target as Node) || event.pointerType === 'touch') return; + hover = event; + schedule(); + }; + const release = (event: PointerEvent, replayed = false) => { + if (!replayed && queuedPointer?.down.pointerId === event.pointerId) { + queuedPointer.up = event; + queuedPointer = null; + event.stopImmediatePropagation(); + return; + } + if (!stroke || stroke.released || event.pointerId !== stroke.id) return; + event.stopImmediatePropagation(); + const { pressure, pointerType, tiltX, tiltY, twist } = stroke.latest; + stroke.path.push( + { + clientX: event.clientX, + clientY: event.clientY, + pressure, + pointerType, + tiltX, + tiltY, + twist, + shiftKey: event.shiftKey, + altKey: event.altKey, + }, + true, + ); + suppressClick = true; + window.clearTimeout(clickTimer); + clickTimer = window.setTimeout(() => (suppressClick = false), 300); + const active = stroke; + active.released = true; + drain(active, performance.now() + 6); + if (stroke) schedule(); + }; + const replay = (gesture: NonNullable) => { + if (queuedPointer === gesture) queuedPointer = null; + const state = useEditor.getState(); + if ( + disposed || + gesture.cancelled || + state.sceneEpoch !== gesture.epoch || + state.sculpt?.partId !== gesture.partId + ) + return; + down(gesture.down, !!gesture.up, true); + for (const event of gesture.moves) move(event, true); + if (gesture.up) release(gesture.up, true); + }; + const cancel = (event: PointerEvent) => { + if (queuedPointer?.down.pointerId === event.pointerId) { + queuedPointer.cancelled = true; + queuedPointer = null; + } + if (stroke?.id === event.pointerId && !stroke.released) detach(false); + }; + const escape = (event: KeyboardEvent) => { + if (event.key !== 'Escape' || (!stroke && !queuedPointer)) return; + event.preventDefault(); + event.stopImmediatePropagation(); + if (queuedPointer) cancel(queuedPointer.down); + if (stroke && !stroke.released) detach(false); + }; + const blur = () => { + hover = null; + if (queuedPointer) { + queuedPointer.cancelled = true; + queuedPointer = null; + } + if (!stroke?.released) detach(false); + refresh(); + }; + const leave = () => { + if (!stroke) { + hover = null; + schedule(); + } + }; + const click = (event: MouseEvent) => { + if (!suppressClick) return; + suppressClick = false; + event.stopImmediatePropagation(); + }; + const unsubscribe = useEditor.subscribe((state) => { + if ( + stroke && + (state.sculpt?.partId !== stroke.target.id || + state.sculpt.revision !== stroke.revision || + state.sceneEpoch !== stroke.epoch || + state.navigationMode || + state.temporaryOrbit || + state.view.explode || + state.scene.parts.find((part) => part.id === stroke?.target.id) !== stroke.target) + ) + detach(false); + prepare(); + schedule(); + }); + prepare(); + setSculptCompletionGate(() => !!stroke?.released); + canvas.addEventListener('pointerdown', down, true); + canvas.addEventListener('lostpointercapture', cancel); + canvas.addEventListener('pointerleave', leave); + canvas.addEventListener('click', click, true); + window.addEventListener('pointermove', move, true); + window.addEventListener('pointerup', release, true); + window.addEventListener('pointercancel', cancel, true); + window.addEventListener('keydown', escape, true); + window.addEventListener('blur', blur); + return () => { + disposed = true; + unsubscribe(); + setSculptCompletionGate(null); + canvas.removeEventListener('pointerdown', down, true); + canvas.removeEventListener('lostpointercapture', cancel); + canvas.removeEventListener('pointerleave', leave); + canvas.removeEventListener('click', click, true); + window.removeEventListener('pointermove', move, true); + window.removeEventListener('pointerup', release, true); + window.removeEventListener('pointercancel', cancel, true); + window.removeEventListener('keydown', escape, true); + window.removeEventListener('blur', blur); + cancelAnimationFrame(frame); + window.clearTimeout(clickTimer); + hover = null; + detach(false); + window.clearTimeout(warmTimer); + discardWarm(); + clearSculptIncidence(); + scene.remove(...cursors, overlay); + cursorShape.dispose(); + cursorPaint.dispose(); + idleOverlay?.dispose(); + emptyOverlay.dispose(); + emptyMirror.dispose(); + maskPaint.dispose(); + mirrorMaterial.dispose(); + }; + }, [get, invalidate]); + return null; +} diff --git a/src/components/Viewport.tsx b/src/components/Viewport.tsx index 81d67a2..7a5658f 100644 --- a/src/components/Viewport.tsx +++ b/src/components/Viewport.tsx @@ -71,6 +71,7 @@ import { FreeTransformController, FreeTransformPrompt } from './FreeTransform'; import { CombinedTransform } from './CombinedTransform'; import { ManagedTransformControls } from './ManagedTransformControls'; import { WarpOverlay, shownWarpPreview } from './WarpOverlay'; +import { restoreSculptPreview, SculptPointer } from './SculptPointer'; import { beginWarpStroke, endingWarpStroke, WarpStrokeController } from './WarpStroke'; import { beginRefinePaint, @@ -137,7 +138,7 @@ const noRaycast = () => {}; const RefineOverlay = lazy(() => import('./RefineOverlay').then(({ RefineOverlay }) => ({ default: RefineOverlay })), ); -const toolsPicking = ['align', 'joint', 'measure', 'anchors', 'pins', 'warp', 'refine']; +const toolsPicking = ['align', 'joint', 'measure', 'anchors', 'pins', 'warp', 'refine', 'sculpt']; // 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; @@ -210,6 +211,10 @@ const PartMesh = memo(function PartMesh({ (proxy?.source === part.geometry && shouldDrawProxy(detail, moving, headset, precision) ? proxy.geometry : part.geometry); + useLayoutEffect(() => { + const mesh = partMeshes.get(part.id); + if (mesh) restoreSculptPreview(mesh); + }); const [brushHit, setBrushHit] = useState(null); const register = useCallback( (mesh: Mesh | null) => { @@ -250,7 +255,7 @@ const PartMesh = memo(function PartMesh({ event.stopPropagation(); if (gizmoPressed) return; const state = useEditor.getState(); - if (state.navigationMode || state.temporaryOrbit) return; + if (state.navigationMode || state.temporaryOrbit || state.tool === 'sculpt') return; if (state.pivotPicking) { state.setPartPivot(toSurface(event)); return; @@ -343,6 +348,7 @@ const PartMesh = memo(function PartMesh({ receiveShadow={!ghost} onContextMenu={(event) => { event.nativeEvent.preventDefault(); + if (useEditor.getState().tool === 'sculpt') return; event.stopPropagation(); useEditor.getState().openContextMenu({ x: event.nativeEvent.clientX, @@ -449,6 +455,7 @@ const PartMesh = memo(function PartMesh({ !nearby && !warpPreview && !refinePreview && + tool !== 'sculpt' && triangleCount(part.geometry) < proxyThreshold ? ( ) : null} @@ -1233,6 +1240,7 @@ function Scene({ ) : null} + {tool === 'sculpt' ? : null} @@ -1356,7 +1364,8 @@ export function Viewport() { state.pivotPicking || tool === 'align' || tool === 'joint' || - tool === 'measure' + tool === 'measure' || + tool === 'sculpt' ) return; // While warping or refining, an empty click clears that tool's selection and keeps diff --git a/src/core/commands.ts b/src/core/commands.ts index 00cb135..14a7ad4 100644 --- a/src/core/commands.ts +++ b/src/core/commands.ts @@ -4,7 +4,15 @@ import { nextIsolation } from './isolation'; import { matchKeyAction } from './keybindings'; import type { KeyActionId, KeyInput } from './keybindings'; import { primaryShortcutText, usePreferences } from './preferences'; -import { canRedo, canUndo, refineEdited, useEditor, warpEdited, type WarpGizmo } from './store'; +import { + canRedo, + canUndo, + afterReleasedSculpt, + refineEdited, + useEditor, + warpEdited, + type WarpGizmo, +} from './store'; import { activeTransformTool, stepTransform, @@ -13,7 +21,22 @@ import { } from './transform-selection'; import type { SurfacePoint } from './types'; +function waitForReleasedSculpt(run: () => Promise) { + let resolveSave!: () => void; + let rejectSave!: (error: unknown) => void; + const saved = new Promise((resolve, reject) => { + resolveSave = resolve; + rejectSave = reject; + }); + if ( + afterReleasedSculpt(() => void run().then(resolveSave, rejectSave), { onCancel: resolveSave }) + ) + return saved; +} + export async function saveCurrentScene() { + const pending = waitForReleasedSculpt(saveCurrentScene); + if (pending) return pending; if (useEditor.getState().driveFile) { if (!(await driveAutosave.flush())) useDrive.setState({ dialogOpen: true }); return; @@ -22,6 +45,8 @@ export async function saveCurrentScene() { } export async function downloadCurrentScene() { + const pending = waitForReleasedSculpt(downloadCurrentScene); + if (pending) return pending; const state = useEditor.getState(); if (state.busy) return; const { revision } = state; @@ -293,7 +318,10 @@ export function editorCommands(context: CommandContext = {}) { ), export: command( 'Export assembly…', - () => state.setModal('export'), + () => { + const open = () => useEditor.getState().setModal('export'); + if (!afterReleasedSculpt(open)) open(); + }, !!state.scene.parts.length, 'export', ), @@ -319,6 +347,12 @@ export function editorCommands(context: CommandContext = {}) { export type CommandId = keyof ReturnType; export function executeEditorCommand(id: CommandId, context: CommandContext = {}) { + if ( + afterReleasedSculpt(() => executeEditorCommand(id, context), { + history: id === 'undo' || id === 'redo', + }) + ) + return; const command = editorCommands(context)[id]; useEditor.getState().closeContextMenu(); if (command.enabled) command.run(); diff --git a/src/core/live.ts b/src/core/live.ts index cf54362..706b2c1 100644 --- a/src/core/live.ts +++ b/src/core/live.ts @@ -1,14 +1,70 @@ import type { BufferGeometry } from 'three'; import { uid } from './geometry'; +import { geometryBytes } from './history-budget'; import { appendGeometry, parseSceneDocument, readGeometry, validateLayout } from './scene-file'; -import { committedScene, liveHost, useEditor, useSharedHistory } from './store'; +import { + cancelQueuedSculptActions, + committedScene, + liveHost, + restoreSculptAfterRefusal, + stopSharedSculptHistory, + useEditor, + useSharedHistory, + useSharedSculptQueueGuard, +} from './store'; import { useXR } from './xr-session'; +import { matchesSculptTarget, sculptHistoryBytes, type SculptTarget } from './sculpt-session'; import { keepUnchanged, mergeScenes, sharedScene } from './sync'; import type { GeometryLayout, SceneDocument } from './types'; +interface OrdinaryEdit { + before: SceneDocument; + scene: SceneDocument; + checkpoint: boolean; + replacementId?: string; + /** The shared epoch the user opened this scene from. */ + replacementEpoch?: number; +} + +interface SculptEdit { + sculpt: SculptTarget; + geometry: BufferGeometry; +} + +type QueuedEdit = OrdinaryEdit | SculptEdit; + +interface ActiveEdit { + edit: QueuedEdit; + epoch: number; + sceneEpoch: number; +} + +const replacementIdOf = (edit: QueuedEdit | null | undefined) => + edit && !('sculpt' in edit) ? edit.replacementId : undefined; + +interface HistoryRequest { + direction: 'undo' | 'redo'; + sculpt: number | null; +} + +function applyQueuedEdit(scene: SceneDocument, edit: QueuedEdit): SceneDocument { + if (!('sculpt' in edit)) + return edit.replacementId ? edit.scene : mergeScenes(edit.before, edit.scene, scene); + const { sculpt, geometry } = edit; + return { + ...scene, + parts: scene.parts.map((part) => + part.id === sculpt.partId && part.geometry.uuid === sculpt.source + ? { ...part, geometry } + : part, + ), + }; +} + interface Message { version: number; epoch: number; + replacementId?: string; scene: unknown; geometries: Record; history: Record; @@ -46,6 +102,9 @@ const post = (path: string, body: unknown) => const errorOf = async (response: Response) => ((await response.json().catch(() => ({}))) as { error?: string }).error; +const firstStreamRetry = 300; +const maxStreamRetry = 5000; + /** * Edits the scene an MCP server holds, alongside the agent and any other tabs. Changes made here * show at once and are sent in the background; the server combines them with everyone else's. @@ -53,56 +112,139 @@ const errorOf = async (response: Response) => */ export function joinLiveSession() { const client = tabId(); - const source = new EventSource('live/events'); + let source: EventSource | null = null; + let streamRetry: number | undefined; + let streamRetryDelay = firstStreamRetry; const meshes = new Map(); /** Mesh keys the server already holds. */ const known = new Set(); - const requests: ('undo' | 'redo')[] = []; + const edits: QueuedEdit[] = []; + const requests: HistoryRequest[] = []; /** The last scene the server sent. Unsent changes here are relative to it. */ - let confirmed: { version: number; epoch: number; scene: SceneDocument } | null = null; + let confirmed: { + version: number; + epoch: number; + replacementId?: string; + scene: SceneDocument; + } | null = null; let latest: Message | null = null; + let streamGeneration = 0; + let snapshotLoad: AbortController | null = null; let receiving = false; let pumping = false; - let sending = false; let applyingRemote = false; let connected = false; let closed = false; let viewMoved = false; - let dirty = false; - let checkpoint = false; - let replace = false; + let dirtyEdit: OrdinaryEdit | null = null; + let activeEdit: ActiveEdit | null = null; + let activeSculptObserved = false; + let acceptedSculpt: { edit: SculptEdit; version: number; epoch: number } | null = null; + let acceptedReplacement: { edit: OrdinaryEdit; version: number } | null = null; + let submittedReplacement: { id: string; epoch: number } | null = null; /** The version that holds this tab's last request. Nothing more is sent until it arrives. */ let awaited = 0; + let awaitedHistory: { version: number; sculpt: number | null } | null = null; const notify = (message: string, kind: 'error' | 'info' = 'error') => useEditor.getState().notify(message, kind); - const show = (scene: SceneDocument) => { + const show = (scene: SceneDocument, replace = false) => { + const state = useEditor.getState(); + const local = committedScene(state); + const next = keepUnchanged(local, scene); + if (!replace && next === local) return; applyingRemote = true; try { - useEditor.getState().receiveScene(keepUnchanged(useEditor.getState().scene, scene)); + state.receiveScene(replace && next === state.scene ? { ...next } : next); } finally { applyingRemote = false; } }; + const unsentEdits = () => (dirtyEdit ? [...edits, dirtyEdit] : edits); + + const invalidateSnapshot = () => { + streamGeneration++; + latest = null; + snapshotLoad?.abort(); + }; + + useSharedSculptQueueGuard((geometry) => { + if (!connected) return false; + const queued = [activeEdit?.edit, acceptedSculpt?.edit, ...edits].flatMap((edit) => + edit && 'sculpt' in edit ? [edit.geometry] : [], + ); + return queued.length < 40 && geometryBytes([...queued, geometry]) <= sculptHistoryBytes; + }); + const unsubscribe = useEditor.subscribe((state, previous) => { - if (applyingRemote || committedScene(state) === committedScene(previous) || !confirmed) return; - dirty = true; - if (state.sceneEpoch !== previous.sceneEpoch) replace = true; - // An action that adds an undo step here starts a new one on the server; a drag extends it. - if (replace || state.past !== previous.past) checkpoint = true; + const before = committedScene(previous); + const scene = committedScene(state); + if (applyingRemote || scene === before || !confirmed) return; + const sculpt = state.sculpt; + const step = sculpt?.past.at(-1); + const target = sculpt && before.parts.find((part) => part.id === sculpt.partId); + const changed = sculpt && scene.parts.find((part) => part.id === sculpt.partId); + if ( + sculpt && + sculpt.revision !== previous.sculpt?.revision && + step && + target && + changed && + target.geometry !== changed.geometry && + step.before.geometry === target.geometry.uuid && + step.after.geometry === changed.geometry.uuid + ) { + // Keep each geometry stroke as a separate shared undo step, even during an upload. + if (dirtyEdit) edits.push(dirtyEdit); + dirtyEdit = null; + edits.push({ + geometry: changed.geometry, + sculpt: { + partId: target.id, + source: target.geometry.uuid, + position: target.position, + quaternion: target.quaternion, + scale: target.scale, + }, + }); + } else { + const replace = state.sceneEpoch !== previous.sceneEpoch; + if (replace) { + edits.length = 0; + requests.length = 0; + dirtyEdit = null; + acceptedSculpt = null; + acceptedReplacement = null; + } + // Accumulate only ordinary edits, each relative to what this action actually changed. + // In particular, an optimistic sculpt mesh in both scenes must not enter this batch. + dirtyEdit = { + before: dirtyEdit?.before ?? before, + scene: + dirtyEdit && dirtyEdit.scene !== before + ? mergeScenes(before, scene, dirtyEdit.scene) + : scene, + checkpoint: replace || !!dirtyEdit?.checkpoint || state.past !== previous.past, + replacementId: replace ? uid() : dirtyEdit?.replacementId, + replacementEpoch: replace ? confirmed.epoch : dirtyEdit?.replacementEpoch, + }; + } void pump(); }); - const load = async (message: Message) => { + const load = async (message: Message, signal: AbortSignal) => { for (const [key, layout] of Object.entries(message.geometries)) { if (meshes.has(key)) continue; - const response = await fetch(`live/geometry/${encodeURIComponent(key)}`); - // The scene has already moved on from this mesh, and a newer message is on its way. - if (response.status === 404) return false; + const response = await fetch(`live/geometry/${encodeURIComponent(key)}`, { signal }).catch( + () => null, + ); + // The mesh may be temporarily unavailable or gone from the latest scene. + if (!response || response.status === 404 || response.status >= 500) return false; if (!response.ok) throw new Error(`${host} did not send a mesh.`); - const body = await response.blob(); + const body = await response.blob().catch(() => null); + if (!body) return false; validateLayout(layout, 0, body.size); const geometry = await readGeometry(body, layout); geometry.uuid = key; @@ -118,21 +260,102 @@ export function joinLiveSession() { return geometry; }); for (const key of Object.keys(message.geometries)) known.add(key); - const local = committedScene(useEditor.getState()); + const state = useEditor.getState(); + const local = committedScene(state); const first = !confirmed; const replaced = !!confirmed && message.epoch !== confirmed.epoch; + const active = + activeEdit && + activeEdit.sceneEpoch === state.sceneEpoch && + activeEdit.epoch === confirmed?.epoch + ? activeEdit.edit + : null; + const acknowledgesReplacement = (edit: QueuedEdit | null | undefined) => + !!message.replacementId && replacementIdOf(edit) === message.replacementId; + const acknowledgedRetry = edits.findIndex(acknowledgesReplacement); + if (acknowledgedRetry >= 0) edits.splice(acknowledgedRetry, 1); + const ownReplacement = + acknowledgesReplacement(active) || + acknowledgesReplacement(acceptedReplacement?.edit) || + acknowledgedRetry >= 0; + if (acceptedReplacement && message.version >= acceptedReplacement.version) + acceptedReplacement = null; + const unsent = unsentEdits(); + if (submittedReplacement && message.epoch !== submittedReplacement.epoch) { + // A second Open in this tab can be queued while its previous Open is still being confirmed. + if (message.replacementId === submittedReplacement.id) { + for (const edit of unsent) + if ( + !('sculpt' in edit) && + edit.replacementId && + edit.replacementEpoch === submittedReplacement.epoch + ) + edit.replacementEpoch = message.epoch; + } + submittedReplacement = null; + } + if (!replaced && active && 'sculpt' in active) { + const { sculpt, geometry } = active; + if ( + scene.parts.some( + (part) => part.id === sculpt.partId && part.geometry.uuid === geometry.uuid, + ) + ) + activeSculptObserved = true; + } + if ( + acceptedSculpt && + (message.epoch !== acceptedSculpt.epoch || message.version >= acceptedSculpt.version) + ) + acceptedSculpt = null; + const replacing = + !!acceptedReplacement || + unsent.some( + (edit) => + !('sculpt' in edit) && edit.replacementId && edit.replacementEpoch === message.epoch, + ); + const changedScene = !replacing && (first || (replaced && !ownReplacement)); let next = scene; - // This tab is about to replace the scene, so it keeps its own. - if (replace) next = local; - // Changes made on a scene that has since been replaced no longer apply. - else if (first || replaced) dirty = false; - else if (dirty || sending) next = mergeScenes(confirmed!.scene, local, scene, 'ours'); - confirmed = { version: message.version, epoch: message.epoch, scene }; + // Changes built on a replaced scene no longer apply, unless we will replace it ourselves. + if (changedScene) { + dirtyEdit = null; + edits.length = 0; + if (replaced) { + // Pending history and editor actions belong to the previous scene. + requests.length = 0; + cancelQueuedSculptActions(); + if (useEditor.getState().sculpt) useEditor.setState({ tool: 'select', sculpt: null }); + } + } else { + const optimistic = + acceptedSculpt?.edit ?? + acceptedReplacement?.edit ?? + (replaced || activeSculptObserved ? null : active); + const pending = optimistic ? [optimistic, ...unsent] : unsent; + next = pending.reduce(applyQueuedEdit, scene); + } + confirmed = { + version: message.version, + epoch: message.epoch, + replacementId: message.replacementId, + scene, + }; const [undo, redo] = message.history[client] ?? [0, 0]; + window.clearTimeout(streamRetry); + streamRetry = undefined; + if (ownReplacement || changedScene || !unsent.length) streamRetryDelay = firstStreamRetry; + if (!connected) { + connected = true; + useSharedHistory(history); + } useEditor.setState({ liveStatus: 'connected', sharedHistory: { undo, redo } }); const before = new Set(local.parts.map((part) => part.id)); - show(next); - if (!replace && (first || replaced)) useEditor.getState().settleWarp(true); + show(next, changedScene && replaced); + if (awaitedHistory && message.version >= awaitedHistory.version) { + stopSharedSculptHistory(true, awaitedHistory.sculpt); + awaitedHistory = null; + } + if (changedScene) useEditor.getState().settleWarp(true); const shown = useEditor.getState().scene; if (first) useEditor.getState().markSaved(useEditor.getState().revision); // Keep a growing model in view, until the person watching takes over the camera. @@ -152,10 +375,21 @@ export function joinLiveSession() { while (latest && !closed) { const message = latest; latest = null; - if ((await load(message)) && !closed) apply(message); + const generation = streamGeneration; + const controller = new AbortController(); + snapshotLoad = controller; + try { + const loaded = await load(message, controller.signal); + if (closed || generation !== streamGeneration) continue; + if (loaded) apply(message); + else if (!latest) refreshStream(); + } catch (error) { + if (!closed && generation === streamGeneration) + notify(`The shared scene stopped updating. ${(error as Error).message}`); + } finally { + snapshotLoad = null; + } } - } catch (error) { - notify(`The shared scene stopped updating. ${(error as Error).message}`); } finally { receiving = false; } @@ -170,16 +404,27 @@ export function joinLiveSession() { headers: { 'X-Kitbasher-Layout': JSON.stringify(layout) }, body: new Blob(body), }); - if (!response.ok) - throw new Refusal((await errorOf(response)) ?? `${host} could not take a mesh.`); + if (!response.ok) { + const reason = (await errorOf(response)) ?? `${host} could not take a mesh.`; + if (response.status >= 500) throw new Error(reason); + throw new Refusal(reason); + } }; /** The server's scene stands. Later changes here were built on the refused one, so they go too. */ - const refused = (reason?: string) => { - dirty = false; - replace = false; - checkpoint = true; - if (confirmed) show(confirmed.scene); + const refused = (reason?: string, replacement = false) => { + const { sculpt } = useEditor.getState(); + // Queued history requests refer to the discarded optimistic scene. + requests.length = 0; + cancelQueuedSculptActions(replacement ? 'all' : 'history'); + stopSharedSculptHistory(true); + edits.length = 0; + dirtyEdit = null; + if (confirmed) { + if (replacement && sculpt) useEditor.setState({ tool: 'select', sculpt: null }); + show(confirmed.scene, replacement); + if (!replacement) restoreSculptAfterRefusal(confirmed.scene, sculpt); + } notify( `Your last change was undone because it could not be combined with ${other}'s.${reason ? ` ${reason}` : ''}`, ); @@ -187,60 +432,127 @@ export function joinLiveSession() { }; const lost = () => { - if (closed) return; + if (closed || useEditor.getState().liveStatus === 'disconnected') return; connected = false; + awaitedHistory = null; useSharedHistory(null); + stopSharedSculptHistory(); // While the agent is away, undo here covers only changes made in the meantime. useEditor.setState({ liveStatus: 'disconnected', sharedHistory: null, past: [], future: [] }); }; - const sendEdit = async () => { - const scene = committedScene(useEditor.getState()); + const refreshStream = () => { + // The old stream may still have a snapshot from before the request was applied. + source?.close(); + source = null; + invalidateSnapshot(); + lost(); + window.clearTimeout(streamRetry); + streamRetry = window.setTimeout(() => { + streamRetry = undefined; + openStream(); + }, streamRetryDelay); + streamRetryDelay = Math.min(streamRetryDelay * 2, maxStreamRetry); + }; + + const sendEdit = async (edit: QueuedEdit) => { // Keep the submitted draft separate from any warp applied while this edit is in flight. const base = confirmed!; - const flags = { checkpoint, replace }; - dirty = checkpoint = replace = false; - sending = true; - useEditor.getState().submitWarp(); + const sculpt = 'sculpt' in edit ? edit.sculpt : undefined; + const checkpoint = 'sculpt' in edit || edit.checkpoint; + const replacement = !('sculpt' in edit) && edit.replacementId ? edit : null; + const replacementId = replacement?.replacementId; + const epoch = replacement?.replacementEpoch ?? base.epoch; + const sceneEpoch = useEditor.getState().sceneEpoch; + const replacementObserved = () => !!replacementId && confirmed?.replacementId === replacementId; + const stillApplies = () => + !closed && + useEditor.getState().sceneEpoch === sceneEpoch && + (confirmed?.epoch === base.epoch || replacementObserved()); + let uploadingMesh = false; + const observed = () => activeSculptObserved || replacementObserved(); + const rejectEdit = (reason?: string) => { + if (observed()) return; + if (submittedReplacement?.id === replacementId && replacementId) submittedReplacement = null; + if (stillApplies()) refused(reason, !!replacement); + }; + const recoverEdit = () => { + if (closed || observed() || confirmed?.epoch !== epoch) return; + if (stillApplies()) { + edits.unshift(edit); + if (!sculpt) useEditor.getState().retryWarp(); + } else if (!replacementId || submittedReplacement?.id !== replacementId) return; + if (replacement || sculpt || uploadingMesh) refreshStream(); + else lost(); + }; + activeEdit = { edit, epoch: base.epoch, sceneEpoch }; + activeSculptObserved = false; + if (!sculpt) useEditor.getState().submitWarp(); try { + if (replacementObserved() || epoch !== base.epoch) return; + if ('sculpt' in edit) { + const target = base.scene.parts.find((part) => part.id === edit.sculpt.partId); + // A request can succeed even when the connection drops before its response arrives. + if (target?.geometry.uuid === edit.geometry.uuid) { + streamRetryDelay = firstStreamRetry; + return; + } + if (!matchesSculptTarget(target, edit.sculpt)) + throw new Refusal( + 'The sculpt target changed before the stroke reached the shared scene.', + ); + } + const scene = applyQueuedEdit(base.scene, edit); for (const { geometry } of scene.parts) { const key = geometry.uuid; if (known.has(key)) continue; + uploadingMesh = true; await upload(key, geometry); + uploadingMesh = false; known.add(key); meshes.set(key, geometry); } + if (!stillApplies()) return; + if (replacementId) submittedReplacement = { id: replacementId, epoch }; const response = await post('live/edit', { client, base: base.version, - epoch: base.epoch, - ...flags, + epoch, + checkpoint, + replace: !!replacementId, + replacementId, + sculpt, scene: sharedScene(scene), }); if (response.ok) { awaited = ((await response.json()) as { version: number }).version; - useEditor.getState().settleWarp(true, true); - } else refused(await errorOf(response)); + streamRetryDelay = firstStreamRetry; + if (!stillApplies()) return; + if (!('sculpt' in edit)) { + if (replacementId && !replacementObserved() && confirmed && confirmed.version < awaited) + acceptedReplacement = { edit, version: awaited }; + useEditor.getState().settleWarp(true, true); + } else if (confirmed && confirmed.version >= awaited) { + // The stream can skip the accepted mesh or show it before the HTTP response arrives. + show(unsentEdits().reduce(applyQueuedEdit, confirmed.scene)); + } else if (!activeSculptObserved && confirmed?.epoch === base.epoch) { + acceptedSculpt = { edit, version: awaited, epoch: base.epoch }; + } + } else if ((replacement || sculpt) && response.status >= 500) recoverEdit(); + else rejectEdit(await errorOf(response)); } catch (error) { - if (error instanceof Refusal) refused(error.message); - else { - // Kept for when the agent can be reached again. - dirty = true; - checkpoint ||= flags.checkpoint; - replace ||= flags.replace; - useEditor.getState().retryWarp(); - lost(); - } + if (error instanceof Refusal) rejectEdit(error.message); + else recoverEdit(); } finally { - sending = false; + activeEdit = null; } }; - const sendHistory = async (direction: 'undo' | 'redo') => { - sending = true; + const sendHistory = async ({ direction, sculpt }: HistoryRequest) => { try { const response = await post(`live/${direction}`, { client }); if (!response.ok) { + stopSharedSculptHistory(false, sculpt); notify((await errorOf(response)) ?? `This could not be ${direction}ne.`); return; } @@ -250,6 +562,9 @@ export function joinLiveSession() { empty?: boolean; }; awaited = result.version; + if (sculpt && result.changed && awaited > confirmed!.version) + awaitedHistory = { version: awaited, sculpt }; + else stopSharedSculptHistory(result.changed, sculpt); if (!result.changed && !result.empty) notify( `Nothing to ${direction}: ${other} has since changed everything that step touched.`, @@ -257,8 +572,6 @@ export function joinLiveSession() { ); } catch { lost(); - } finally { - sending = false; } }; @@ -267,8 +580,11 @@ export function joinLiveSession() { pumping = true; try { while (!closed && connected && confirmed && awaited <= confirmed.version) { - if (dirty) await sendEdit(); - else if (requests.length) await sendHistory(requests.shift()!); + const edit = edits.shift() ?? dirtyEdit; + if (edit) { + if (edit === dirtyEdit) dirtyEdit = null; + await sendEdit(edit); + } else if (requests.length) await sendHistory(requests.shift()!); else break; } } finally { @@ -278,11 +594,17 @@ export function joinLiveSession() { const history = { undo: () => { - requests.push('undo'); + requests.push({ + direction: 'undo', + sculpt: useEditor.getState().sculpt?.pending?.id ?? null, + }); void pump(); }, redo: () => { - requests.push('redo'); + requests.push({ + direction: 'redo', + sculpt: useEditor.getState().sculpt?.pending?.id ?? null, + }); void pump(); }, }; @@ -293,27 +615,42 @@ export function joinLiveSession() { window.addEventListener('pointerdown', markViewMoved, { capture: true, once: true }); window.addEventListener('wheel', markViewMoved, { capture: true, once: true, passive: true }); - source.addEventListener('scene', (event) => { - latest = JSON.parse((event as MessageEvent).data); - if (!connected) { - connected = true; - useSharedHistory(history); - } - void receive(); - }); - // Sent only to tabs on the computer that holds the scene: how another device joins it. - source.addEventListener('share', (event) => - useXR.setState({ sharing: JSON.parse((event as MessageEvent).data) }), - ); - // EventSource keeps retrying, so a server that is only briefly unreachable reconnects by itself. - source.onerror = lost; + function openStream() { + const stream = new EventSource('live/events'); + source = stream; + stream.addEventListener('scene', (event) => { + if (closed || source !== stream) return; + latest = JSON.parse((event as MessageEvent).data); + void receive(); + }); + // Sent only to tabs on the computer that holds the scene: how another device joins it. + stream.addEventListener('share', (event) => { + if (!closed && source === stream) + useXR.setState({ sharing: JSON.parse((event as MessageEvent).data) }); + }); + // A native retry leaves the stream CONNECTING. A terminal error needs a new EventSource. + stream.onerror = () => { + if (closed || source !== stream) return; + if (stream.readyState === EventSource.CLOSED) { + refreshStream(); + return; + } + invalidateSnapshot(); + lost(); + }; + } + openStream(); useEditor.setState({ liveStatus: 'connecting' }); return () => { closed = true; - source.close(); + window.clearTimeout(streamRetry); + source?.close(); + invalidateSnapshot(); unsubscribe(); + useSharedSculptQueueGuard(null); useSharedHistory(null); + stopSharedSculptHistory(); useEditor.setState({ liveStatus: null }); window.removeEventListener('pointerdown', markViewMoved, { capture: true }); window.removeEventListener('wheel', markViewMoved, { capture: true }); diff --git a/src/core/sculpt-mesh.ts b/src/core/sculpt-mesh.ts new file mode 100644 index 0000000..9781d3d --- /dev/null +++ b/src/core/sculpt-mesh.ts @@ -0,0 +1,1439 @@ +import { + BackSide, + Box3, + BufferAttribute, + BufferGeometry, + DynamicDrawUsage, + FrontSide, + MathUtils, + Matrix4, + Mesh, + Quaternion, + Sphere, + Triangle, + Vector3, + type Intersection, + type Raycaster, +} from 'three'; +import { MeshBVH } from 'three-mesh-bvh'; +import type { SculptBrush } from './types'; + +export type { SculptBrush } from './types'; + +interface SculptHit { + point: Vector3; + normal: Vector3; + face: number; + tangent?: Vector3; + grab?: Vector3; +} + +export interface SculptDab extends SculptHit { + radius: number; + strength: number; + detail: number; + minEdge: number; + brush: SculptBrush; + falloff: 'soft' | 'linear' | 'hard'; + inverted?: boolean; + pinch?: number; + softenMask?: boolean; + aspect?: number; + mirror?: SculptHit; +} + +type Face = [number, number, number]; +type Attribute = ReturnType; +type AttributeArray = BufferAttribute['array']; +interface Split { + vertexCount: number; + weld: number; + faces: { id: number; previous: Face; child: number }[]; +} +interface SculptSample { + footprint: Footprint; + weight: number; + mirrored: boolean; +} +interface Incidence { + weldOf: Uint32Array; + representative: Uint32Array; + faceStart: Uint32Array; + incidentFaces: Uint32Array; + adjacent: Int32Array; + edits: ReadonlyMap>; +} + +let latestIncidence: + | { + source: WeakRef; + position: Attribute; + index: BufferAttribute | null; + incidence: Incidence; + } + | undefined; + +export function clearSculptIncidence() { + latestIncidence = undefined; +} + +function rememberIncidence(source: BufferGeometry, incidence: Incidence) { + latestIncidence = { + source: new WeakRef(source), + position: source.getAttribute('position'), + index: source.index, + incidence, + }; +} + +// Let the caller enforce a frame budget between batches on large footprints. +const batchMask = 511; + +const maxSplitsPerDab = 192; +/** Source meshes larger than this remain brushable at their available density. */ +const maxRefinedFaceCount = 1_200_000; +const inheritedFaceLimits = new WeakMap(); +const maskName = 'sculptMask'; + +/** Exact coincident vertices share connectivity without welding a nearby thin shell. */ +function weldVertices(position: Attribute) { + const capacity = 2 ** Math.ceil(Math.log2(Math.max(16, position.count * 1.5))); + const table = new Uint32Array(capacity); + const weldOf = new Uint32Array(position.count); + const representative = new Uint32Array(position.count); + const coordinate = new Float64Array(1); + const bits = new Uint32Array(coordinate.buffer); + function hash(value: number) { + coordinate[0] = value || 0; + const mixed = Math.imul(bits[0] ^ bits[1], 0x85ebca6b); + return mixed ^ (mixed >>> 16); + } + let count = 0; + for (let vertex = 0; vertex < position.count; vertex++) { + const x = position.getX(vertex); + const y = position.getY(vertex); + const z = position.getZ(vertex); + let slot = (hash(x) ^ Math.imul(hash(y), 31) ^ Math.imul(hash(z), 961)) & (capacity - 1); + while (table[slot]) { + const candidate = representative[table[slot] - 1]; + if ( + position.getX(candidate) === x && + position.getY(candidate) === y && + position.getZ(candidate) === z + ) + break; + slot = (slot + 1) & (capacity - 1); + } + if (!table[slot]) { + representative[count] = vertex; + table[slot] = ++count; + } + weldOf[vertex] = table[slot] - 1; + } + return { weldOf, representative: representative.slice(0, count) }; +} + +/** CSR incidence stays compact for indexed scans and for duplicated render vertices at seams. */ +function buildFaceIncidence(weldOf: Uint32Array, weldCount: number, corners: ArrayLike) { + const faceStart = new Uint32Array(weldCount + 1); + for (let corner = 0; corner < corners.length; corner++) faceStart[weldOf[corners[corner]] + 1]++; + for (let weld = 0; weld < weldCount; weld++) faceStart[weld + 1] += faceStart[weld]; + const next = faceStart.slice(0, -1); + const incidentFaces = new Uint32Array(corners.length); + for (let corner = 0; corner < corners.length; corner++) + incidentFaces[next[weldOf[corners[corner]]]++] = Math.floor(corner / 3); + return { faceStart, incidentFaces }; +} + +/** Link corners through edges, then give each disconnected fan its own render vertex. */ +function weldSeams(position: Attribute, corners: Uint32Array) { + const { weldOf: coordinateOf, representative } = weldVertices(position); + const { faceStart, incidentFaces } = buildFaceIncidence( + coordinateOf, + representative.length, + corners, + ); + const parent = Uint32Array.from(corners, (_vertex, corner) => corner); + function root(corner: number) { + while (parent[corner] !== corner) { + parent[corner] = parent[parent[corner]]; + corner = parent[corner]; + } + return corner; + } + const adjacent = new Int32Array(corners.length).fill(-1); + const valid = new Uint8Array(corners.length / 3); + const point = new Vector3(), + left = new Vector3(), + right = new Vector3(); + function validTriangle(face: number) { + if (valid[face]) return valid[face] === 1; + const corner = face * 3; + point.fromBufferAttribute(position, corners[corner]); + left.fromBufferAttribute(position, corners[corner + 1]).sub(point); + right.fromBufferAttribute(position, corners[corner + 2]).sub(point); + const area = left.cross(right).lengthSq(); + valid[face] = Number.isFinite(area) && area > 0 ? 1 : 2; + return valid[face] === 1; + } + + for (let corner = 0; corner < corners.length; corner++) { + const face = Math.floor(corner / 3); + const end = face * 3 + ((corner + 1) % 3); + const u = corners[corner]; + const v = corners[end]; + if (u === v) { + parent[root(end)] = root(corner); + continue; + } + const a = coordinateOf[u], + b = coordinateOf[v]; + // Looking up the smaller fan avoids walking a high-valence center for every spoke. + const smaller = faceStart[a + 1] - faceStart[a] <= faceStart[b + 1] - faceStart[b] ? a : b; + let reverse = -1; + let matchCount = 0; + let previous = -1; + for (let i = faceStart[smaller]; i < faceStart[smaller + 1]; i++) { + const neighbor = incidentFaces[i]; + if (neighbor === face || neighbor === previous) continue; + previous = neighbor; + const start = neighbor * 3; + let shared = false; + for (let edge = 0; edge < 3; edge++) { + const p = start + edge; + const q = start + ((edge + 1) % 3); + if (coordinateOf[corners[p]] === b && coordinateOf[corners[q]] === a) { + shared = true; + reverse = p; + if (neighbor > face && corners[q] === u && corners[p] === v) { + parent[root(q)] = root(corner); + parent[root(p)] = root(end); + } + } else if (coordinateOf[corners[p]] === a && coordinateOf[corners[q]] === b) { + shared = true; + if (neighbor > face && corners[p] === u && corners[q] === v) { + parent[root(p)] = root(corner); + parent[root(q)] = root(end); + } + } + } + if (shared) matchCount++; + } + const match = Math.floor(reverse / 3); + if (matchCount === 1 && a !== b && reverse !== -1) adjacent[corner] = reverse; + else if (matchCount > 1) adjacent[corner] = -2; + if ( + a !== b && + matchCount === 1 && + match > face && + (corners[reverse] !== v || corners[match * 3 + ((reverse + 1) % 3)] !== u) && + validTriangle(face) && + validTriangle(match) + ) { + parent[root(match * 3 + ((reverse + 1) % 3))] = root(corner); + parent[root(reverse)] = root(end); + } + } + + const weldOf = new Uint32Array(position.count); + const weldByRoot = new Uint32Array(corners.length); + const used = new Uint8Array(position.count); + const fanRepresentative: number[] = []; + const copies: number[] = []; + const copyByFan = new Map>(); + for (let corner = 0; corner < corners.length; corner++) { + const original = corners[corner]; + const fan = root(corner); + if (!weldByRoot[fan]) { + weldByRoot[fan] = fanRepresentative.length + 1; + fanRepresentative.push(original); + } + const weld = weldByRoot[fan] - 1; + if (!used[original]) { + used[original] = 1; + weldOf[original] = weld; + } else if (weldOf[original] !== weld) { + let byVertex = copyByFan.get(weld); + if (!byVertex) copyByFan.set(weld, (byVertex = new Map())); + let duplicate = byVertex.get(original); + if (duplicate === undefined) { + duplicate = position.count + copies.length; + copies.push(original); + byVertex.set(original, duplicate); + if (fanRepresentative[weld] === original) fanRepresentative[weld] = duplicate; + } + corners[corner] = duplicate; + } + } + for (let vertex = 0; vertex < weldOf.length; vertex++) { + if (used[vertex]) continue; + weldOf[vertex] = fanRepresentative.length; + fanRepresentative.push(vertex); + } + const vertices = copies.length ? resize(weldOf, position.count + copies.length) : weldOf; + for (const [weld, byVertex] of copyByFan) + for (const duplicate of byVertex.values()) vertices[duplicate] = weld; + return { + weldOf: vertices, + representative: Uint32Array.from(fanRepresentative), + adjacent, + copies, + }; +} + +function resize(array: T, length: number): T { + const ArrayType = array.constructor as new (length: number) => T; + const result = new ArrayType(length); + result.set(array.subarray(0, length)); + return result; +} + +function renderAttribute(source: Attribute) { + const attribute = source.clone(); + return attribute.setUsage(DynamicDrawUsage); +} + +class Footprint { + readonly normal: Vector3; + readonly tangent: Vector3; + readonly cross: Vector3; + private readonly aspect: number; + private readonly triangle = new Triangle(); + private readonly offset = new Vector3(); + + constructor( + readonly hit: SculptHit, + readonly radius: number, + aspect: number, + ) { + this.aspect = MathUtils.clamp(aspect, 0.1, 1); + this.normal = hit.normal.clone().normalize(); + this.tangent = hit.tangent?.clone() ?? new Vector3(); + this.tangent.addScaledVector(this.normal, -this.tangent.dot(this.normal)); + if (this.tangent.lengthSq() < 1e-8) { + const axis = Math.abs(this.normal.x) < 0.9 ? new Vector3(1, 0, 0) : new Vector3(0, 1, 0); + this.tangent.crossVectors(axis, this.normal); + } + this.tangent.normalize(); + this.cross = new Vector3().crossVectors(this.normal, this.tangent); + } + + private project(point: Vector3, target: Vector3) { + const offset = this.offset.subVectors(point, this.hit.point); + return target.set( + offset.dot(this.tangent), + offset.dot(this.cross) / this.aspect, + offset.dot(this.normal), + ); + } + + overlaps(a: Vector3, b: Vector3, c: Vector3) { + const triangle = this.triangle; + const squared = this.radius ** 2; + if ( + this.project(a, triangle.a).lengthSq() < squared || + this.project(b, triangle.b).lengthSq() < squared || + this.project(c, triangle.c).lengthSq() < squared + ) + return true; + return triangle.closestPointToPoint(origin, this.offset).lengthSq() < squared; + } + + distance(point: Vector3) { + return this.project(point, this.offset).length() / this.radius; + } +} + +const origin = new Vector3(); + +export class SculptMesh { + readonly geometry = new BufferGeometry(); + detailLimited = false; + + private readonly world: Matrix4; + private readonly inverse: Matrix4; + private readonly orientation: number; + private readonly source: BufferGeometry; + private readonly initialVertices: number; + private readonly initialFaces: number; + private readonly faceLimit: number; + private vertexCount: number; + private faceCount: number; + private weldCount = 0; + private weldOf = new Uint32Array(0); + private representative = new Uint32Array(0); + private faceStart = new Uint32Array(0); + private incidentFaces = new Uint32Array(0); + private adjacent = new Int32Array(0); + private baseEdits: ReadonlyMap> = new Map(); + private incidentEdits = new Map>(); + private readonly editedFaces = new Set(); + private readonly editedFaceBuckets = new Map(); + private readonly editedPoint = new Vector3(); + private grabSamples: Map | undefined; + private changed = false; + private readonly facePoints = [new Vector3(), new Vector3(), new Vector3()]; + private readonly faceEdges = [new Vector3(), new Vector3()]; + + constructor(source: BufferGeometry, matrixWorld: Matrix4, mask?: Float32Array) { + this.source = source; + this.world = matrixWorld.clone(); + this.inverse = matrixWorld.clone().invert(); + this.orientation = Math.sign(matrixWorld.determinant()); + this.initialVertices = this.vertexCount = source.getAttribute('position').count; + this.initialFaces = this.faceCount = Math.floor((source.index?.count ?? this.vertexCount) / 3); + const localBudget = Math.min(65_536, Math.max(4096, Math.ceil(this.initialFaces * 0.2))); + this.faceLimit = + inheritedFaceLimits.get(source) ?? + Math.min(maxRefinedFaceCount, this.initialFaces + localBudget); + this.geometry.name = source.name; + this.geometry.userData = { ...source.userData }; + for (const [name, attribute] of Object.entries(source.attributes)) + this.geometry.setAttribute(name, renderAttribute(attribute)); + const indices = new Uint32Array(this.faceCount * 3); + for (let corner = 0; corner < indices.length; corner++) + indices[corner] = source.index?.getX(corner) ?? corner; + this.geometry.setIndex(new BufferAttribute(indices, 1).setUsage(DynamicDrawUsage)); + this.geometry.groups = source.groups.map((group) => ({ ...group })); + this.geometry.setDrawRange(0, indices.length); + const weights = new Float32Array(this.vertexCount); + if (mask) weights.set(mask.subarray(0, this.vertexCount)); + this.geometry.setAttribute( + maskName, + new BufferAttribute(weights, 1).setUsage(DynamicDrawUsage), + ); + this.geometry.boundingBox = source.boundingBox?.clone() ?? null; + this.geometry.boundingSphere = source.boundingSphere?.clone() ?? null; + if (!this.geometry.boundingBox) this.geometry.computeBoundingBox(); + if (!this.geometry.boundingSphere) this.geometry.computeBoundingSphere(); + } + + getMask() { + return (this.geometry.getAttribute(maskName).array as Float32Array).slice( + 0, + this.changed ? this.vertexCount : this.initialVertices, + ); + } + + /** Build or reuse incidence before pen-down when the controller has an idle opportunity. */ + prepare() { + if (this.faceStart.length) return; + const cached = latestIncidence; + if ( + cached?.source.deref() === this.source && + cached.position === this.source.getAttribute('position') && + cached.index === this.source.index + ) { + const { weldOf, representative, faceStart, incidentFaces, adjacent, edits } = + cached.incidence; + this.weldOf = weldOf; + this.representative = representative; + this.weldCount = representative.length; + this.faceStart = faceStart; + this.incidentFaces = incidentFaces; + this.adjacent = adjacent; + this.baseEdits = edits; + return; + } + this.buildIncidence(); + if (this.vertexCount !== this.initialVertices) return; + rememberIncidence(this.source, { + weldOf: this.weldOf, + representative: this.representative, + faceStart: this.faceStart, + incidentFaces: this.incidentFaces, + adjacent: this.adjacent, + edits: this.baseEdits, + }); + } + + private trackEditedFace(face: number) { + const key = Math.floor(face / 128); + let bucket = this.editedFaceBuckets.get(key); + if (!bucket) this.editedFaceBuckets.set(key, (bucket = { bounds: new Box3(), faces: [] })); + if (!this.editedFaces.has(face)) { + this.editedFaces.add(face); + bucket.faces.push(face); + } + const position = this.attribute('position'); + const index = this.geometry.index!.array; + for (let corner = face * 3; corner < face * 3 + 3; corner++) + bucket.bounds.expandByPoint(this.editedPoint.fromBufferAttribute(position, index[corner])); + } + + /** Unedited faces remain in the source index. Test edited faces at their live positions. */ + raycast(raycaster: Raycaster, mesh: Mesh, hits: Intersection[]) { + const tree = this.source.boundsTree; + if (!(tree instanceof MeshBVH) || Array.isArray(mesh.material)) { + const found: Intersection[] = []; + Mesh.prototype.raycast.call(mesh, raycaster, found); + found.sort((a, b) => a.distance - b.distance); + hits.push(...(raycaster.firstHitOnly ? found.slice(0, 1) : found)); + return; + } + const world = mesh.matrixWorld; + const ray = raycaster.ray.clone().applyMatrix4(this.inverse); + if (this.geometry.boundingBox && !ray.intersectsBox(this.geometry.boundingBox)) return; + const worldStep = ray.at(1, new Vector3()).applyMatrix4(world).distanceTo(raycaster.ray.origin); + const near = raycaster.near / worldStep; + const far = raycaster.far / worldStep; + const side = mesh.material.side; + let sourceHits: Intersection[] = []; + if (raycaster.firstHitOnly) { + const first = tree.raycastFirst(ray, side, near, far); + if (first) + sourceHits = this.editedFaces.has(first.faceIndex!) + ? tree.raycast(ray, side, near, far) + : [first]; + } else sourceHits = tree.raycast(ray, side, near, far); + const found: Intersection[] = []; + for (const hit of sourceHits) { + if (this.editedFaces.has(hit.faceIndex!)) continue; + hit.point.applyMatrix4(world); + hit.distance = hit.point.distanceTo(raycaster.ray.origin); + hit.object = mesh; + found.push(hit); + } + + const position = this.attribute('position'); + const a = new Vector3(), + b = new Vector3(), + c = new Vector3(), + point = new Vector3(); + for (const bucket of this.editedFaceBuckets.values()) { + if (!ray.intersectsBox(bucket.bounds)) continue; + for (const faceIndex of bucket.faces) { + const [ia, ib, ic] = this.face(faceIndex); + a.fromBufferAttribute(position, ia); + b.fromBufferAttribute(position, ib); + c.fromBufferAttribute(position, ic); + const contact = + side === BackSide + ? ray.intersectTriangle(c, b, a, true, point) + : ray.intersectTriangle(a, b, c, side === FrontSide, point); + if (!contact) continue; + point.applyMatrix4(world); + const distance = point.distanceTo(raycaster.ray.origin); + if (distance < raycaster.near || distance > raycaster.far) continue; + found.push({ + distance, + point: point.clone(), + object: mesh, + faceIndex, + face: { + a: ia, + b: ib, + c: ic, + normal: Triangle.getNormal(a, b, c, new Vector3()), + materialIndex: 0, + }, + }); + } + } + found.sort((a, b) => a.distance - b.distance); + hits.push(...(raycaster.firstHitOnly ? found.slice(0, 1) : found)); + } + + invertMask() { + return this.replaceMask((value) => 1 - value); + } + + clearMask() { + return this.replaceMask(() => 0); + } + + private replaceMask(replace: (value: number) => number) { + const attribute = this.attribute(maskName); + let changed = false; + for (let vertex = 0; vertex < this.vertexCount; vertex++) { + const value = attribute.getX(vertex); + const next = Math.fround(replace(value)); + if (value === next) continue; + attribute.setX(vertex, next); + changed = true; + } + if (changed) { + attribute.addUpdateRange(0, this.vertexCount); + attribute.needsUpdate = true; + } + return changed; + } + + private attribute(name: string) { + return this.geometry.getAttribute(name) as BufferAttribute; + } + + private face(id: number): Face { + const index = this.geometry.index!.array; + const start = id * 3; + return [index[start], index[start + 1], index[start + 2]]; + } + + private buildIncidence() { + const faces = (this.geometry.index!.array as Uint32Array).subarray(0, this.faceCount * 3); + const { weldOf, representative, adjacent, copies } = weldSeams( + this.attribute('position'), + faces, + ); + if (copies.length) { + this.ensureCapacity(this.vertexCount + copies.length, this.faceCount); + for (const attribute of Object.values(this.geometry.attributes) as BufferAttribute[]) { + const { array, itemSize } = attribute; + for (let copy = 0; copy < copies.length; copy++) { + const source = copies[copy] * itemSize; + array.copyWithin((this.vertexCount + copy) * itemSize, source, source + itemSize); + } + attribute.needsUpdate = true; + } + this.vertexCount += copies.length; + this.syncCounts(); + this.geometry.index!.needsUpdate = true; + } + const capacity = this.attribute('position').array.length / 3; + this.weldOf = capacity === weldOf.length ? weldOf : resize(weldOf, capacity); + this.representative = + capacity === weldOf.length ? representative : resize(representative, capacity); + this.adjacent = adjacent; + this.weldCount = representative.length; + const { faceStart, incidentFaces } = buildFaceIncidence( + weldOf, + this.weldCount, + this.geometry.index!.array.subarray(0, this.faceCount * 3), + ); + this.faceStart = faceStart; + this.incidentFaces = incidentFaces; + } + + private incidence(weld: number): Iterable { + const edited = this.incidentEdits.get(weld) ?? this.baseEdits.get(weld); + if (edited) return edited; + if (weld + 1 >= this.faceStart.length) return []; + return this.incidentFaces.subarray(this.faceStart[weld], this.faceStart[weld + 1]); + } + + private editIncidence(id: number, vertices: Face, add: boolean) { + for (const vertex of vertices) { + const weld = this.weldOf[vertex]; + let faces = this.incidentEdits.get(weld); + if (!faces) this.incidentEdits.set(weld, (faces = new Set(this.incidence(weld)))); + if (add) faces.add(id); + else faces.delete(id); + } + } + + private worldAt(vertex: number, target = new Vector3()) { + return target.fromBufferAttribute(this.attribute('position'), vertex).applyMatrix4(this.world); + } + + private maskAt(weld: number) { + const attribute = this.attribute(maskName); + if (this.vertexCount === this.weldCount) return attribute.getX(this.representative[weld]); + let protection = 0; + for (const face of this.incidence(weld)) { + for (const vertex of this.face(face)) + if (this.weldOf[vertex] === weld) protection = Math.max(protection, attribute.getX(vertex)); + } + return protection; + } + + private neighbors(a: number, b: number) { + const faces: number[] = []; + const index = this.geometry.index!.array; + const weldOf = this.weldOf; + let previous = -1; + for (const id of this.incidence(a)) { + if (previous === id) continue; + previous = id; + const corner = id * 3; + if ( + weldOf[index[corner]] === b || + weldOf[index[corner + 1]] === b || + weldOf[index[corner + 2]] === b + ) + faces.push(id); + if (faces.length > 2) break; + } + return faces; + } + + private edgeSlot(vertices: Face, a: number, b: number) { + return vertices.findIndex((vertex, i) => { + const u = this.weldOf[vertex]; + const v = this.weldOf[vertices[(i + 1) % 3]]; + return (u === a && v === b) || (u === b && v === a); + }); + } + + private validFace(vertices: Face) { + const a = this.worldAt(vertices[0]); + const ab = this.worldAt(vertices[1]).sub(a); + const ac = this.worldAt(vertices[2]).sub(a); + const area = ab.cross(ac).lengthSq(); + return Number.isFinite(area) && area > 0; + } + + /** An edge with a third incident face, reversed adjacency, or a degenerate face is a boundary. */ + private splittableFaces(a: number, b: number) { + const faces = this.neighbors(a, b); + if (!faces.length || faces.length > 2) return []; + const first = this.face(faces[0]); + const start = this.edgeSlot(first, a, b); + if (start === -1 || !this.validFace(first)) return []; + if (faces.length === 2) { + const second = this.face(faces[1]); + const end = this.edgeSlot(second, a, b); + if ( + end === -1 || + this.weldOf[first[start]] === this.weldOf[second[end]] || + !this.validFace(second) + ) + return []; + } + return faces; + } + + private overlaps(id: number, footprint: Footprint) { + const index = this.geometry.index!.array; + const start = id * 3; + const a = this.worldAt(index[start], this.facePoints[0]); + const b = this.worldAt(index[start + 1], this.facePoints[1]); + const c = this.worldAt(index[start + 2], this.facePoints[2]); + const normal = this.faceEdges[0].subVectors(b, a).cross(this.faceEdges[1].subVectors(c, a)); + const facing = normal.dot(footprint.normal) * this.orientation; + return Number.isFinite(facing) && facing > 0 && footprint.overlaps(a, b, c); + } + + private *patch(footprint: Footprint): Generator, void> { + const faces = new Set(); + const seed = footprint.hit.face; + if (seed < 0 || seed >= this.faceCount || !Number.isInteger(seed)) return faces; + const visited = new Uint8Array(this.faceCount); + visited[seed] = 1; + const queue = [seed]; + const index = this.geometry.index!.array; + const weldOf = this.weldOf; + const enqueue = (neighbor: number) => { + if (visited[neighbor]) return; + visited[neighbor] = 1; + queue.push(neighbor); + }; + for (let i = 0; i < queue.length; i++) { + if (i && (i & batchMask) === 0) yield; + const face = queue[i]; + if (!this.overlaps(face, footprint)) continue; + faces.add(face); + const start = face * 3; + for (let edge = 0; edge < 3; edge++) { + const a = weldOf[index[start + edge]]; + const b = weldOf[index[start + ((edge + 1) % 3)]]; + const reverse = this.adjacent[start + edge]; + if ( + reverse === undefined || + reverse === -2 || + this.incidentEdits.has(a) || + this.baseEdits.has(a) + ) { + const incidents = this.splittableFaces(a, b); + if (incidents.length === 2) enqueue(incidents[0] === face ? incidents[1] : incidents[0]); + } else if (reverse >= 0) { + const neighbor = Math.floor(reverse / 3); + const end = neighbor * 3 + ((reverse + 1) % 3); + if (weldOf[index[reverse]] === b && weldOf[index[end]] === a) enqueue(neighbor); + } + } + } + return faces; + } + + private setFace(id: number, vertices: Face) { + const index = this.geometry.index!; + index.array.set(vertices, id * 3); + index.addUpdateRange(id * 3, 3); + } + + private ensureCapacity(vertices: number, faces: number) { + const position = this.attribute('position'); + const index = this.geometry.index!; + if (vertices <= position.array.length / 3 && faces <= index.array.length / 3) return; + // Three's GPU buffers cannot be resized. Release them only when the reserved capacity grows. + this.geometry.dispose(); + const vertexCapacity = Math.max( + vertices, + Math.ceil((position.array.length / 3) * 1.25), + this.initialVertices + 512, + ); + const faceCapacity = Math.max( + faces, + Math.ceil((index.array.length / 3) * 1.25), + this.initialFaces + 512, + ); + for (const [name, attribute] of Object.entries(this.geometry.attributes)) { + const old = attribute as BufferAttribute; + const next = new BufferAttribute( + resize(old.array, vertexCapacity * old.itemSize), + old.itemSize, + old.normalized, + ); + next.name = old.name; + this.geometry.setAttribute(name, next.setUsage(DynamicDrawUsage)); + } + this.geometry.setIndex( + new BufferAttribute(resize(index.array, faceCapacity * 3), 1).setUsage(DynamicDrawUsage), + ); + this.weldOf = resize(this.weldOf, vertexCapacity); + this.representative = resize(this.representative, vertexCapacity); + } + + private syncCounts() { + for (const attribute of Object.values(this.geometry.attributes)) + Object.assign(attribute, { count: this.vertexCount }); + const index = this.geometry.index!; + Object.assign(index, { count: this.faceCount * 3 }); + this.geometry.setDrawRange(0, this.faceCount * 3); + } + + private splitEdge(a: number, b: number, faces: number[]) { + const edit: Split = { vertexCount: this.vertexCount, weld: this.weldCount, faces: [] }; + this.ensureCapacity(this.vertexCount + faces.length, this.faceCount + faces.length); + const weld = this.weldCount++; + const edges: { a: number; b: number; vertex: number }[] = []; + const protection = (this.maskAt(a) + this.maskAt(b)) * 0.5; + for (const id of faces) { + const previous = this.face(id); + const start = this.edgeSlot(previous, a, b); + const u = previous[start]; + const v = previous[(start + 1) % 3]; + const w = previous[(start + 2) % 3]; + const repeated = edges.find((edge) => edge.a === v && edge.b === u); + const midpoint = repeated?.vertex ?? this.vertexCount++; + if (!repeated) { + for (const attr of Object.values(this.geometry.attributes) as BufferAttribute[]) { + for (let axis = 0; axis < attr.itemSize; axis++) + attr.setComponent( + midpoint, + axis, + (attr.getComponent(u, axis) + attr.getComponent(v, axis)) * 0.5, + ); + attr.addUpdateRange(midpoint * attr.itemSize, attr.itemSize); + } + const normals = this.geometry.getAttribute('normal'); + if (normals) { + const normal = new Vector3().fromBufferAttribute(normals, midpoint).normalize(); + normals.setXYZ(midpoint, normal.x, normal.y, normal.z); + } + this.attribute(maskName).setX(midpoint, protection); + this.weldOf[midpoint] = weld; + this.representative[weld] = midpoint; + edges.push({ a: u, b: v, vertex: midpoint }); + } + const left: Face = [u, midpoint, w]; + const right: Face = [midpoint, v, w]; + this.editIncidence(id, previous, false); + const child = this.faceCount++; + this.setFace(id, left); + this.setFace(child, right); + this.editIncidence(id, left, true); + this.editIncidence(child, right, true); + this.appendGroups(id, child); + edit.faces.push({ id, previous, child }); + } + return edit; + } + + private appendGroups(id: number, child: number) { + const groups = this.geometry.groups; + const matching = groups.filter(({ start, count }) => id * 3 >= start && id * 3 < start + count); + for (const group of matching) this.geometry.addGroup(child * 3, 3, group.materialIndex); + } + + private rollback(splits: Split[], groupCount: number) { + for (let i = splits.length - 1; i >= 0; i--) { + const { vertexCount, weld, faces } = splits[i]; + for (const { id, previous, child } of faces) { + this.editIncidence(id, this.face(id), false); + this.editIncidence(child, this.face(child), false); + this.setFace(id, previous); + this.editIncidence(id, previous, true); + } + this.incidentEdits.delete(weld); + this.vertexCount = vertexCount; + this.weldCount = weld; + this.faceCount -= faces.length; + } + this.geometry.groups.length = groupCount; + this.syncCounts(); + } + + private *refine( + settings: SculptDab, + brushes: { footprint: Footprint; faces: Set }[], + ): Generator { + const splits: Split[] = []; + const target = Math.max( + settings.minEdge * 2, + settings.radius * MathUtils.lerp(0.95, 0.22, settings.detail), + ); + const minEdgeSquared = (settings.minEdge ?? 0) ** 2; + const queue = + brushes.length === 1 + ? [...brushes[0].faces] + : [...new Set(brushes.flatMap(({ faces }) => [...faces]))]; + const edited = new Set(); + const points = [new Vector3(), new Vector3(), new Vector3()]; + const targetSquared = target ** 2; + for (let i = 0; i < queue.length; i++) { + if (i && (i & batchMask) === 0) yield; + const id = queue[i]; + if ( + edited.has(id) && + !brushes.some(({ faces, footprint }) => faces.has(id) && this.overlaps(id, footprint)) + ) + continue; + const vertices = this.face(id); + for (let corner = 0; corner < 3; corner++) this.worldAt(vertices[corner], points[corner]); + if ( + points[0].distanceToSquared(points[1]) <= targetSquared && + points[1].distanceToSquared(points[2]) <= targetSquared && + points[2].distanceToSquared(points[0]) <= targetSquared + ) + continue; + if ( + settings.brush !== 'mask' && + vertices.every((vertex) => this.maskAt(this.weldOf[vertex]) === 1) + ) + continue; + let longest = targetSquared; + let choice: { a: number; b: number; faces: number[] } | undefined; + for (let edge = 0; edge < 3; edge++) { + const next = (edge + 1) % 3; + const length = points[edge].distanceToSquared(points[next]); + if (length <= longest) continue; + const a = this.weldOf[vertices[edge]]; + const b = this.weldOf[vertices[next]]; + const faces = this.splittableFaces(a, b); + if (!faces.length) continue; + const middle = points[edge].clone().lerp(points[next], 0.5); + if ( + faces.some((incident) => + this.face(incident).some((vertex) => { + const weld = this.weldOf[vertex]; + return ( + weld !== a && + weld !== b && + this.worldAt(vertex).distanceToSquared(middle) < minEdgeSquared + ); + }), + ) + ) + continue; + longest = length; + choice = { a, b, faces }; + } + if (!choice) continue; + if (this.faceCount + choice.faces.length > this.faceLimit) { + this.detailLimited = true; + break; + } + if (splits.length >= maxSplitsPerDab) break; + const split = this.splitEdge(choice.a, choice.b, choice.faces); + splits.push(split); + for (const { id: parent, child } of split.faces) { + for (const { faces } of brushes) if (faces.has(parent)) faces.add(child); + edited.add(parent); + edited.add(child); + queue.push(parent, child); + } + } + for (const { faces, footprint } of brushes) + for (const id of edited) if (faces.has(id) && !this.overlaps(id, footprint)) faces.delete(id); + return splits; + } + + private weight(footprint: Footprint, point: Vector3, settings: SculptDab) { + const distance = footprint.distance(point); + if (!(distance < 1)) return 0; + const weight = 1 - distance; + switch (settings.falloff) { + case 'linear': + return weight; + case 'hard': + return 1; + case 'soft': + return weight * weight * (3 - 2 * weight); + } + } + + private neighborsOf(weld: number, footprint: Footprint) { + const neighbors = new Set(); + for (const id of this.incidence(weld)) { + const face = this.face(id); + const a = this.worldAt(face[0]); + const b = this.worldAt(face[1]).sub(a); + const c = this.worldAt(face[2]).sub(a); + if (!(b.cross(c).dot(footprint.normal) * this.orientation > 0)) continue; + for (const vertex of face) { + const neighbor = this.weldOf[vertex]; + if (neighbor !== weld && this.splittableFaces(weld, neighbor).length) + neighbors.add(neighbor); + } + } + return neighbors; + } + + private surfaceNormal(weld: number) { + const normal = new Vector3(); + const seen = new Set(); + for (const id of this.incidence(weld)) { + if (seen.has(id)) continue; + seen.add(id); + const face = this.face(id); + const a = this.worldAt(face[0]); + const b = this.worldAt(face[1]).sub(a); + const c = this.worldAt(face[2]).sub(a); + normal.add(b.cross(c)); + } + return normal.multiplyScalar(this.orientation).normalize(); + } + + private displacement( + weld: number, + point: Vector3, + footprint: Footprint, + settings: SculptDab, + strength: number, + mirrored: boolean, + ) { + const { hit, normal } = footprint; + const sign = settings.inverted ? -1 : 1; + const height = new Vector3().subVectors(point, hit.point).dot(normal); + const depth = settings.radius * strength; + switch (settings.brush) { + case 'draw': + return normal.clone().multiplyScalar(sign * depth * 0.2); + case 'inflate': + return this.surfaceNormal(weld).multiplyScalar(sign * depth * 0.2); + case 'grab': + return ( + (mirrored ? settings.mirror?.grab : settings.grab)?.clone().multiplyScalar(strength) ?? + new Vector3() + ); + case 'flatten': + return normal.clone().multiplyScalar(-height * strength); + case 'clay': { + const layer = Math.max(0, settings.radius * 0.16 - sign * height); + return normal + .clone() + .multiplyScalar(sign * Math.min(layer, settings.radius * 0.22) * strength); + } + case 'crease': { + const toward = new Vector3().subVectors(hit.point, point); + toward.addScaledVector(normal, -toward.dot(normal)); + if (hit.tangent) toward.addScaledVector(footprint.tangent, -toward.dot(footprint.tangent)); + return toward + .multiplyScalar(MathUtils.clamp(settings.pinch ?? 0.5, 0, 1) * strength * 0.4) + .addScaledVector(normal, -sign * depth * 0.22); + } + case 'smooth': { + const neighbors = this.neighborsOf(weld, footprint); + if (neighbors.size < 2) return new Vector3(); + const center = new Vector3(); + for (const neighbor of neighbors) center.add(this.worldAt(this.representative[neighbor])); + center.divideScalar(neighbors.size).sub(point); + const surface = this.surfaceNormal(weld); + return surface.multiplyScalar(center.dot(surface) * strength * 0.65); + } + case 'mask': + return new Vector3(); + } + } + + private renderVertices(weld: number) { + if (this.vertexCount === this.weldCount) return [this.representative[weld]]; + const vertices = new Set(); + for (const id of this.incidence(weld)) + for (const vertex of this.face(id)) if (this.weldOf[vertex] === weld) vertices.add(vertex); + return vertices; + } + + private localFaceCross(id: number, cross = new Vector3()) { + const index = this.geometry.index!.array; + const start = id * 3; + const position = this.attribute('position'); + const a = this.facePoints[0].fromBufferAttribute(position, index[start]); + cross + .fromBufferAttribute(position, index[start + 1]) + .sub(a) + .cross(this.facePoints[1].fromBufferAttribute(position, index[start + 2]).sub(a)); + return Number.isFinite(cross.lengthSq()) ? cross : cross.set(0, 0, 0); + } + + private *applyMoves(moves: Map): Generator { + const position = this.attribute('position'); + const bounds = this.geometry.boundingBox; + const sphere = this.geometry.boundingSphere; + let first = this.vertexCount; + let last = -1; + const batch = moves.size > 4096; + let count = 0; + for (const [weld, local] of moves) { + if (count && (count & batchMask) === 0) yield; + count++; + for (const vertex of this.renderVertices(weld)) { + position.setXYZ(vertex, local.x, local.y, local.z); + if (batch) { + first = Math.min(first, vertex); + last = Math.max(last, vertex); + } else position.addUpdateRange(vertex * 3, 3); + } + bounds?.expandByPoint(local); + if (sphere) sphere.radius = Math.max(sphere.radius, local.distanceTo(sphere.center)); + } + if (batch) position.addUpdateRange(first * 3, (last - first + 1) * 3); + position.needsUpdate = true; + } + + /** Accumulate area-weighted render normals in flat buffers for widely affected surfaces. */ + private *deformDense( + moves: Map, + changedFaces: Set, + output: BufferAttribute, + ): Generator { + const index = this.geometry.index!.array; + const affected = new Uint8Array(this.vertexCount); + let first = this.vertexCount; + let last = -1; + let count = 0; + for (const face of changedFaces) { + if (count && (count & batchMask) === 0) yield; + count++; + for (let corner = face * 3; corner < face * 3 + 3; corner++) { + const vertex = index[corner]; + affected[vertex] = 1; + first = Math.min(first, vertex); + last = Math.max(last, vertex); + } + } + const size = (last - first + 1) * 3; + const faceCross = new Vector3(); + const accumulate = function* (this: SculptMesh): Generator { + const sums = new Float64Array(size); + for (let face = 0; face < this.faceCount; face++) { + if (face && (face & batchMask) === 0) yield; + const corner = face * 3; + const a = index[corner]; + const b = index[corner + 1]; + const c = index[corner + 2]; + if (!(affected[a] || affected[b] || affected[c])) continue; + this.localFaceCross(face, faceCross); + // Repeated corners form a zero-area face and contribute nothing. + for (let offset = 0; offset < 3; offset++) { + const vertex = index[corner + offset]; + if (!affected[vertex]) continue; + const component = (vertex - first) * 3; + sums[component] += faceCross.x; + sums[component + 1] += faceCross.y; + sums[component + 2] += faceCross.z; + } + } + return sums; + }; + const before = yield* accumulate.call(this); + yield* this.applyMoves(moves); + const after = yield* accumulate.call(this); + const previous = new Vector3(); + const current = new Vector3(); + const normal = new Vector3(); + const rotate = new Quaternion(); + for (let vertex = first; vertex <= last; vertex++) { + if (vertex !== first && (vertex & batchMask) === 0) yield; + if (!affected[vertex]) continue; + const component = (vertex - first) * 3; + previous.fromArray(before, component); + current.fromArray(after, component); + if (!previous.lengthSq() || !current.lengthSq()) continue; + rotate.setFromUnitVectors(previous.normalize(), current.normalize()); + normal.fromBufferAttribute(output, vertex).applyQuaternion(rotate).normalize(); + output.setXYZ(vertex, normal.x, normal.y, normal.z); + } + output.addUpdateRange(first * 3, size); + output.needsUpdate = true; + } + + private *deform(moves: Map): Generator { + const outputNormals = this.geometry.getAttribute('normal') as BufferAttribute | undefined; + const changedFaces = new Set(); + let count = 0; + for (const weld of moves.keys()) { + if (count && (count & batchMask) === 0) yield; + count++; + for (const face of this.incidence(weld)) changedFaces.add(face); + } + if (outputNormals && changedFaces.size > Math.max(4096, this.faceCount / 8)) { + yield* this.deformDense(moves, changedFaces, outputNormals); + yield* this.trackEditedFaces(changedFaces); + return; + } + const normals = new Map(); + const renderFaces = new Map>(); + const faceBefore = new Map(); + if (outputNormals) { + for (const face of changedFaces) { + if ((count++ & batchMask) === 0) yield; + for (const vertex of this.face(face)) { + if (renderFaces.has(vertex)) continue; + const fan = new Set(); + for (const incident of this.incidence(this.weldOf[vertex])) { + if (!this.face(incident).includes(vertex)) continue; + fan.add(incident); + if (!faceBefore.has(incident)) faceBefore.set(incident, this.localFaceCross(incident)); + } + renderFaces.set(vertex, fan); + const normal = new Vector3(); + for (const incident of fan) normal.add(faceBefore.get(incident)!); + normals.set(vertex, normal.normalize()); + } + } + } + yield* this.applyMoves(moves); + if (outputNormals) { + const after = new Map(); + const rotate = new Quaternion(); + const normal = new Vector3(); + for (const [vertex, fan] of renderFaces) { + if ((count++ & batchMask) === 0) yield; + const current = new Vector3(); + for (const face of fan) { + if (!after.has(face)) after.set(face, this.localFaceCross(face)); + current.add(after.get(face)!); + } + const previous = normals.get(vertex)!; + if (!previous.lengthSq() || !current.lengthSq()) continue; + rotate.setFromUnitVectors(previous, current.normalize()); + normal.fromBufferAttribute(outputNormals, vertex).applyQuaternion(rotate).normalize(); + outputNormals.setXYZ(vertex, normal.x, normal.y, normal.z); + outputNormals.addUpdateRange(vertex * 3, 3); + } + outputNormals.needsUpdate = true; + } + yield* this.trackEditedFaces(changedFaces); + } + + private *trackEditedFaces(faces: Set) { + let count = 0; + for (const face of faces) { + if (count && (count & batchMask) === 0) yield; + count++; + this.trackEditedFace(face); + } + } + + dab(settings: SculptDab): boolean { + const work = this.dabWork(settings); + let result = work.next(); + while (!result.done) result = work.next(); + return result.value; + } + + /** A cancellable draft operation. The source geometry remains immutable between batches. */ + *dabWork(settings: SculptDab): Generator { + if (!(settings.radius > 0 && settings.strength > 0) || !this.orientation) return false; + if (settings.brush !== 'grab') this.grabSamples = undefined; + else if (!settings.grab?.lengthSq() && !settings.mirror?.grab?.lengthSq()) return false; + this.prepare(); + const groupCount = this.geometry.groups.length; + let samples = this.grabSamples; + let splits: Split[] = []; + let count = 0; + if (!samples) { + const hits: SculptHit[] = [settings]; + if (settings.mirror) hits.push(settings.mirror); + const brushes = []; + for (const hit of hits) { + const footprint = new Footprint(hit, settings.radius, settings.aspect ?? 1); + const faces = yield* this.patch(footprint); + brushes.push({ footprint, faces, mirrored: hit === settings.mirror }); + } + splits = yield* this.refine(settings, brushes); + samples = new Map(); + const visited = new Uint8Array(this.weldCount); + const index = this.geometry.index!.array; + const point = new Vector3(); + for (const { footprint, faces, mirrored } of brushes) { + const pass = mirrored ? 2 : 1; + for (const face of faces) { + if (count && (count & batchMask) === 0) yield; + count++; + for (let i = face * 3; i < face * 3 + 3; i++) { + const vertex = index[i]; + const weld = this.weldOf[vertex]; + if (visited[weld] === pass) continue; + visited[weld] = pass; + const weight = this.weight(footprint, this.worldAt(vertex, point), settings); + if (weight > (samples.get(weld)?.weight ?? 0)) + samples.set(weld, { footprint, weight, mirrored }); + } + } + } + } + const moves = new Map(); + const masks = new Map(); + for (const [weld, { footprint, weight, mirrored }] of samples) { + if (count && (count & batchMask) === 0) yield; + count++; + const protection = this.maskAt(weld); + const strength = Math.min(1, settings.strength) * weight; + if (settings.brush === 'mask') { + let next = protection + (settings.inverted ? -strength : strength); + if (settings.softenMask) { + const neighbors = this.neighborsOf(weld, footprint); + if (!neighbors.size) continue; + let mean = 0; + for (const neighbor of neighbors) mean += this.maskAt(neighbor); + next = MathUtils.lerp(protection, mean / neighbors.size, strength); + } + next = Math.fround(MathUtils.clamp(next, 0, 1)); + if (next !== protection) masks.set(weld, next); + } else if (protection < 1) { + const vertex = this.representative[weld]; + const point = this.worldAt(vertex); + const displacement = this.displacement( + weld, + point, + footprint, + settings, + strength * (1 - protection), + mirrored, + ); + if (!(displacement.lengthSq() > 1e-24)) continue; + const local = point.add(displacement).applyMatrix4(this.inverse); + const before = new Vector3().fromBufferAttribute(this.attribute('position'), vertex); + if (![local.x, local.y, local.z].every(Number.isFinite)) continue; + if (this.attribute('position').array instanceof Float32Array) + local.set(Math.fround(local.x), Math.fround(local.y), Math.fround(local.z)); + if (!local.equals(before)) moves.set(weld, local); + } + } + if (!moves.size && !masks.size) { + if (splits.length) this.rollback(splits, groupCount); + return false; + } + if (settings.brush === 'grab') this.grabSamples = samples; + if (splits.length) { + this.syncCounts(); + for (const attribute of Object.values(this.geometry.attributes) as BufferAttribute[]) + attribute.needsUpdate = true; + this.geometry.index!.needsUpdate = true; + for (const split of splits) + for (const { id, child } of split.faces) { + this.trackEditedFace(id); + this.trackEditedFace(child); + } + } + if (moves.size) yield* this.deform(moves); + if (masks.size) { + const mask = this.attribute(maskName); + const batch = masks.size > 4096; + let first = this.vertexCount; + let last = -1; + for (const [weld, value] of masks) { + if (count && (count & batchMask) === 0) yield; + count++; + for (const vertex of this.renderVertices(weld)) { + mask.setX(vertex, value); + if (batch) { + first = Math.min(first, vertex); + last = Math.max(last, vertex); + } else mask.addUpdateRange(vertex, 1); + } + } + if (batch) mask.addUpdateRange(first, last - first + 1); + mask.needsUpdate = true; + } + this.changed ||= moves.size > 0 || this.vertexCount !== this.initialVertices; + return true; + } + + private refitPicking(geometry: BufferGeometry) { + const sourceTree = this.source.boundsTree; + if ( + !(sourceTree instanceof MeshBVH) || + this.faceCount !== this.initialFaces || + !this.editedFaces.size + ) + return; + const data = MeshBVH.serialize(sourceTree, { cloneBuffers: false }); + const roots = data.roots.map((root) => root.slice(0)); + const tree = MeshBVH.deserialize({ ...data, roots }, geometry, { setIndex: false }); + if (this.editedFaces.size * 4 > this.faceCount) tree.refit(); + else { + const dirtyBounds = new Box3(); + const sourcePosition = this.source.getAttribute('position'); + const point = new Vector3(); + for (const face of this.editedFaces) { + for (let offset = 0; offset < 3; offset++) { + const corner = face * 3 + offset; + const vertex = this.source.index?.getX(corner) ?? corner; + dirtyBounds.expandByPoint(point.fromBufferAttribute(sourcePosition, vertex)); + } + } + const nodes = new Set(); + sourceTree.shapecast({ + intersectsBounds: (bounds, _leaf, _score, _depth, node) => { + if (!bounds.intersectsBox(dirtyBounds)) return false; + nodes.add(node); + return true; + }, + }); + tree.refit(nodes); + } + geometry.boundsTree = tree; + } + + finish() { + if (!this.changed) return null; + const geometry = new BufferGeometry(); + geometry.name = this.geometry.name; + geometry.userData = { ...this.geometry.userData }; + for (const [name, attribute] of Object.entries(this.geometry.attributes)) { + if (name === maskName) continue; + const { array, itemSize, normalized } = attribute; + geometry.setAttribute( + name, + new BufferAttribute(array.slice(0, this.vertexCount * itemSize), itemSize, normalized), + ); + } + if (this.source.index || this.faceCount !== this.initialFaces) { + const index = this.geometry.index!.array.slice(0, this.faceCount * 3) as Uint32Array; + geometry.setIndex( + new BufferAttribute(this.vertexCount <= 65_536 ? Uint16Array.from(index) : index, 1), + ); + } + geometry.groups = this.geometry.groups.map((group) => ({ ...group })); + geometry.computeBoundingBox(); + if (geometry.boundingBox && this.geometry.boundingSphere) { + const bounds = this.geometry.boundingSphere; + geometry.boundingSphere = new Sphere(bounds.center.clone(), bounds.radius); + } + this.refitPicking(geometry); + inheritedFaceLimits.set(geometry, this.faceLimit); + if (this.faceStart.length) + rememberIncidence(geometry, { + weldOf: + this.weldOf.length === this.vertexCount + ? this.weldOf + : this.weldOf.slice(0, this.vertexCount), + representative: + this.representative.length === this.weldCount + ? this.representative + : this.representative.slice(0, this.weldCount), + faceStart: this.faceStart, + incidentFaces: this.incidentFaces, + adjacent: this.adjacent, + edits: new Map([ + ...this.baseEdits, + ...Array.from(this.incidentEdits, ([vertex, faces]) => [vertex, new Set(faces)] as const), + ]), + }); + return geometry; + } +} diff --git a/src/core/sculpt-path.ts b/src/core/sculpt-path.ts new file mode 100644 index 0000000..1aa4e7a --- /dev/null +++ b/src/core/sculpt-path.ts @@ -0,0 +1,100 @@ +/** A pointer sample and the pen properties that affect a sculpt dab. */ +export type SculptSample = Pick< + PointerEvent, + | 'clientX' + | 'clientY' + | 'pressure' + | 'pointerType' + | 'tiltX' + | 'tiltY' + | 'twist' + | 'shiftKey' + | 'altKey' +>; + +function interpolate(a: SculptSample, b: SculptSample, t: number): SculptSample { + const lerp = (start: number, end: number) => start + (end - start) * t; + return { + pointerType: b.pointerType, + shiftKey: b.shiftKey, + altKey: b.altKey, + clientX: lerp(a.clientX, b.clientX), + clientY: lerp(a.clientY, b.clientY), + pressure: lerp(a.pressure, b.pressure), + tiltX: lerp(a.tiltX, b.tiltX), + tiltY: lerp(a.tiltY, b.tiltY), + twist: (a.twist + (((b.twist - a.twist + 540) % 360) - 180) * t + 360) % 360, + }; +} + +const distance = (a: SculptSample, b: SculptSample) => + Math.hypot(b.clientX - a.clientX, b.clientY - a.clientY); + +/** Keep input segments intact and produce only as many dabs as the caller has time to apply. */ +export class SculptPath { + private queue: { sample: SculptSample; final: boolean }[] = []; + private head = 0; + private cursor: SculptSample; + private filtered: SculptSample; + private lastDab: SculptSample; + private first = true; + private travelled = 0; + + constructor( + start: SculptSample, + private readonly spacing: (a: SculptSample, b: SculptSample) => number, + private readonly stabilization: number, + ) { + this.cursor = this.filtered = this.lastDab = start; + } + + get pending() { + return this.first || this.head < this.queue.length; + } + + push(incoming: SculptSample, final = false) { + this.filtered = final + ? incoming + : interpolate(this.filtered, incoming, 1 - this.stabilization * 0.85); + this.queue.push({ sample: this.filtered, final }); + } + + private consume() { + if (++this.head === this.queue.length) { + this.queue.length = 0; + this.head = 0; + } else if (this.head >= 256) { + this.queue = this.queue.slice(this.head); + this.head = 0; + } + } + + next(): SculptSample | undefined { + if (this.first) { + this.first = false; + return this.cursor; + } + while (this.head < this.queue.length) { + const { sample, final } = this.queue[this.head]; + const length = distance(this.cursor, sample); + const remaining = Math.max(0.001, this.spacing(this.cursor, sample) - this.travelled); + if (length >= remaining) { + this.cursor = interpolate(this.cursor, sample, remaining / length); + this.travelled = 0; + this.lastDab = this.cursor; + return this.cursor; + } + this.travelled += length; + this.cursor = sample; + this.consume(); + if ( + (final && this.travelled > 0.001) || + (this.travelled < 0.1 && Math.abs(sample.pressure - this.lastDab.pressure) > 0.015) + ) { + this.travelled = 0; + this.lastDab = sample; + return sample; + } + } + } +} diff --git a/src/core/sculpt-session.ts b/src/core/sculpt-session.ts new file mode 100644 index 0000000..388610a --- /dev/null +++ b/src/core/sculpt-session.ts @@ -0,0 +1,120 @@ +import type { BufferGeometry } from 'three'; +import { same } from './sync'; +import type { Part, Quat, SculptBrush, SculptureSettings, Vec3 } from './types'; + +export interface SculptTarget { + partId: string; + source: string; + position: Vec3; + quaternion: Quat; + scale: Vec3; +} + +export function matchesSculptTarget(part: Part | undefined, target: SculptTarget) { + return ( + part?.visible && + !part.locked && + part.id === target.partId && + part.geometry.uuid === target.source && + same(part.position, target.position) && + same(part.quaternion, target.quaternion) && + same(part.scale, target.scale) + ); +} + +export interface SculptStrokeCommit { + partId: string; + source: BufferGeometry; + epoch: number; + revision?: number; + position: Vec3; + quaternion: Quat; + scale: Vec3; + geometry: BufferGeometry | null; + mask: Float32Array | null; +} + +interface SculptSnapshot { + geometry: string; + mask: Float32Array | null; +} + +export interface SculptStep { + before: SculptSnapshot; + after: SculptSnapshot; +} + +export interface SculptSession { + partId: string; + settings: SculptureSettings; + byBrush: Partial>; + defaultRadius: number; + mask: Float32Array | null; + revision: number; + past: SculptStep[]; + future: SculptStep[]; + pending: { id: number; direction: 'undo' | 'redo'; step: SculptStep } | null; +} + +export function sculptDefaults( + brush: SculptBrush, + radius: number, + maskVisible = true, +): SculptureSettings { + return { + brush, + radius, + strength: 0.35, + detail: 0.5, + minEdge: 0.05, + falloff: 'soft', + symmetry: false, + spacing: 0.2, + stabilization: 0, + pressureStrength: true, + pressureRadius: false, + pressureCurve: 1, + aspect: 1, + rotation: 0, + tilt: false, + twist: false, + pinch: 0.5, + maskVisible, + }; +} + +export const maskHistoryBytes = 64 * 1024 * 1024; +export const sculptHistoryBytes = 256 * 1024 * 1024; + +/** Count unique allocations because consecutive strokes can share unchanged weights. */ +export function appendSculptStep(past: SculptStep[], step: SculptStep) { + const kept = [...past, step].slice(-40); + const seen = new Set([step.after.mask?.buffer]); + let bytes = 0; + for (let i = kept.length - 1; i >= 0; i--) { + for (const { mask } of [kept[i].before, kept[i].after]) { + if (mask && !seen.has(mask.buffer)) { + seen.add(mask.buffer); + bytes += mask.buffer.byteLength; + } + } + if (bytes > maskHistoryBytes) return kept.slice(i + 1); + } + return kept; +} + +export function stepSculptSession( + session: SculptSession, + direction: 'undo' | 'redo', + step: SculptStep, +): SculptSession { + const undo = direction === 'undo'; + return { + ...session, + revision: session.revision + 1, + mask: (undo ? step.before : step.after).mask, + pending: null, + past: undo ? session.past.slice(0, -1) : [...session.past, step], + future: undo ? [step, ...session.future] : session.future.slice(1), + }; +} diff --git a/src/core/store.ts b/src/core/store.ts index 423c3d6..b550bd3 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -99,7 +99,16 @@ import type { RegionInput, RegionSolve } from './refine-region'; import type { NavigationMode } from './navigation'; import { createSample } from './sample'; import { useXR } from './xr-session'; -import { trimHistory } from './history-budget'; +import { geometryBytes, historyBudgetBytes, trimHistory } from './history-budget'; +import { + appendSculptStep, + maskHistoryBytes, + sculptDefaults, + sculptHistoryBytes, + stepSculptSession, + type SculptSession, + type SculptStrokeCommit, +} from './sculpt-session'; import { captureComponents, instantiateComponents } from './clipboard'; import type { ComponentClipboard } from './clipboard'; import { referencePlanes, resolvePart } from './references'; @@ -185,6 +194,8 @@ import type { SurfacePair, SurfaceSide, Tool, + SculptBrush, + SculptureSettings, ViewSettings, Vec3, } from './types'; @@ -238,6 +249,7 @@ const historyLimit = 40; const gestureBudget = 12; interface FreeTransform { + id: string; mode: FreeTransformMode; axis: TransformAxis; baseline: SceneDocument; @@ -482,6 +494,7 @@ interface EditorState { warpPending: WarpRecovery | null; warpInFlight: WarpRecovery | null; refine: RefineSession | null; + sculpt: SculptSession | null; view: ViewSettings; /** Lighting for scenes that have none of their own. Kept in this browser. */ defaultLighting: SceneLighting; @@ -609,6 +622,13 @@ interface EditorState { retryWarp: () => void; settleWarp: (accepted: boolean, submittedOnly?: boolean) => void; /** Starts a session on the one selected part, or says why it cannot. */ + startSculpt: () => boolean; + setSculptBrush: (brush: SculptBrush) => void; + setSculptSettings: (patch: Partial>) => void; + resetSculptBrush: () => void; + cancelSculptStroke: () => void; + commitSculpt: (stroke: SculptStrokeCommit) => boolean; + changeSculptMask: (operation: 'invert' | 'clear') => void; startRefine: () => boolean; /** Ends the session without changing the part. It leaves the tool as it is. */ cancelRefine: (notice?: string) => void; @@ -763,6 +783,7 @@ const toolChange = (state: EditorState, tool: Tool): Partial => { const pair = mode === 'surface' ? emptySurfacePair() : null; return { tool, + sculpt: tool === 'sculpt' ? state.sculpt : null, pinPicking: tool === 'pins' && !state.scene.parts.find((p) => p.id === state.selected[0])?.pins?.length ? 'hard' @@ -1874,6 +1895,7 @@ const changed = (state: EditorState, scene: SceneDocument, checkpoint = true) => past, [], [scene, ...(state.clipboard ? [{ name: '', parts: state.clipboard.parts, joints: [] }] : [])], + historyBudgetBytes, ); if (kept.trimmed) { past = kept.past; @@ -1953,6 +1975,88 @@ const restoredIsolated = (state: EditorState, scene: SceneDocument) => scene.parts.filter((part) => !state.scene.parts.some((p) => p.id === part.id)), ); +let sculptRevision = 0; +const nextSculptRevision = () => ++sculptRevision; + +type HistoryDirection = 'undo' | 'redo'; + +function historyScene(state: EditorState, direction: HistoryDirection) { + return direction === 'undo' ? state.past.at(-1) : state.future[0]; +} + +function restoreHistoryScene( + state: EditorState, + direction: HistoryDirection, + scene: SceneDocument, + sculpt: SculptSession | null = null, +): Partial { + const undo = direction === 'undo'; + return { + scene, + past: undo ? state.past.slice(0, -1) : [...state.past, state.scene], + future: undo ? [state.scene, ...state.future] : state.future.slice(1), + revision: state.revision + 1, + selected: state.selected.filter((id) => scene.parts.some((part) => part.id === id)), + ...restoredIsolated(state, scene), + operation: blankOperation(), + // Keep placement tools ready for another adjustment after undo. + tool: + sculpt || ['translate', 'rotate', 'scale', 'transform'].includes(state.tool) + ? state.tool + : 'select', + sculpt, + navigationMode: null, + pivotPicking: false, + painting: false, + paintHistory: [], + measurement: [], + }; +} + +function sculptHistoryStep(state: EditorState, direction: HistoryDirection) { + const { sculpt } = state; + if (!sculpt || sculpt.pending) return; + const undo = direction === 'undo'; + const step = undo ? sculpt.past.at(-1) : sculpt.future[0]; + if (!step || step.before.geometry === step.after.geometry || state.sharedHistory) return step; + const destination = (undo ? step.before : step.after).geometry; + const scene = historyScene(state, direction); + if (scene?.parts.some((part) => part.id === sculpt.partId && part.geometry.uuid === destination)) + return step; +} + +function moveHistory(direction: HistoryDirection) { + const state = useEditor.getState(); + const { sculpt } = state; + const step = sculptHistoryStep(state, direction); + if (sculpt?.pending) return; + if (sculpt && step) { + const next = stepSculptSession(sculpt, direction, step); + next.revision = nextSculptRevision(); + if (step.before.geometry === step.after.geometry) useEditor.setState({ sculpt: next }); + else if (sharedHandlers) { + useEditor.setState({ + sculpt: { + ...sculpt, + pending: { id: next.revision, direction, step }, + revision: next.revision, + }, + }); + sharedHandlers[direction](); + } else { + useEditor.setState( + restoreHistoryScene(state, direction, historyScene(state, direction)!, next), + ); + } + return; + } + const scene = historyScene(state, direction); + if (sharedHandlers) { + if (sculpt) state.setTool('select'); + sharedHandlers[direction](); + } else if (scene) useEditor.setState(restoreHistoryScene(state, direction, scene)); +} + export const useEditor = create((set, get) => ({ scene: initialScene, selected: liveSession ? [] : ['torso'], @@ -1985,6 +2089,7 @@ export const useEditor = create((set, get) => ({ warpPending: null, warpInFlight: null, refine: null, + sculpt: null, view: { inspection: { enabled: false, @@ -2029,7 +2134,8 @@ export const useEditor = create((set, get) => ({ indexingMeshes: 0, focusRequest: { id: 0, all: true }, measurement: [], - select: (id, additive = false) => + select: (id, additive = false) => { + if (afterReleasedSculpt(() => get().select(id, additive))) return; set((state) => ({ selected: id ? additive @@ -2038,7 +2144,8 @@ export const useEditor = create((set, get) => ({ : [...state.selected, id] : [id] : [], - })), + })); + }, selectAll: () => set((state) => ({ selected: state.scene.parts.map((part) => part.id) })), isolate: (ids) => set({ isolated: ids?.length ? ids : null }), toggleIsolation: () => { @@ -2142,6 +2249,7 @@ export const useEditor = create((set, get) => ({ })), closeContextMenu: () => set({ contextMenu: null }), setTool: (tool) => { + if (afterReleasedSculpt(() => get().setTool(tool))) return; const state = get(); if (tool === 'warp' && state.tool === 'warp' && state.warp) set({ navigationMode: null, pivotPicking: false }); @@ -2149,6 +2257,7 @@ export const useEditor = create((set, get) => ({ else if (tool === 'refine' && state.tool === 'refine' && state.refine) set({ navigationMode: null, pivotPicking: false }); else if (tool === 'refine') state.startRefine(); + else if (tool === 'sculpt' && !state.sculpt) state.startSculpt(); else set((state) => toolChange(state, tool)); }, addFitAnchor: (point) => { @@ -2334,12 +2443,14 @@ export const useEditor = create((set, get) => ({ })), }); }, - setNavigationMode: (navigationMode) => + setNavigationMode: (navigationMode) => { + if (afterReleasedSculpt(() => get().setNavigationMode(navigationMode))) return; set(() => ({ navigationMode, pivotPicking: false, painting: false, - })), + })); + }, centerOrbit: () => { const state = get(); if (!state.scene.parts.some((part) => part.visible && state.selected.includes(part.id))) { @@ -3284,6 +3395,171 @@ export const useEditor = create((set, get) => ({ 'info', ); }, + startSculpt: () => { + const state = get(); + if (useXR.getState().session) return false; + const part = + state.selected.length === 1 + ? state.scene.parts.find((candidate) => candidate.id === state.selected[0]) + : undefined; + if (!part?.visible || part.locked) { + state.notify('Select one visible, unlocked part to sculpt.', 'info'); + return false; + } + if ( + geometryBytes([part.geometry]) > sculptHistoryBytes || + part.geometry.getAttribute('position').count * Float32Array.BYTES_PER_ELEMENT > + maskHistoryBytes + ) { + state.notify(`${part.name} is too large to sculpt with undo history.`, 'info'); + return false; + } + const defaultRadius = fittedWarpBrushRadius(part); + set({ + ...toolChange(state, 'sculpt'), + sculpt: { + partId: part.id, + settings: sculptDefaults('draw', defaultRadius), + byBrush: {}, + defaultRadius, + mask: null, + revision: nextSculptRevision(), + past: [], + future: [], + pending: null, + }, + }); + return true; + }, + setSculptBrush: (brush) => + set(({ sculpt }) => { + if (!sculpt || brush === sculpt.settings.brush) return {}; + const { maskVisible } = sculpt.settings; + const settings = sculpt.byBrush[brush] ?? sculptDefaults(brush, sculpt.defaultRadius); + return { + sculpt: { + ...sculpt, + settings: { ...settings, maskVisible }, + byBrush: { ...sculpt.byBrush, [sculpt.settings.brush]: sculpt.settings }, + }, + }; + }), + setSculptSettings: (patch) => + set(({ sculpt }) => + sculpt ? { sculpt: { ...sculpt, settings: { ...sculpt.settings, ...patch } } } : {}, + ), + resetSculptBrush: () => + set(({ sculpt }) => + sculpt + ? { + sculpt: { + ...sculpt, + settings: sculptDefaults( + sculpt.settings.brush, + sculpt.defaultRadius, + sculpt.settings.maskVisible, + ), + }, + } + : {}, + ), + cancelSculptStroke: () => + set(({ sculpt }) => (sculpt ? { sculpt: { ...sculpt, revision: nextSculptRevision() } } : {})), + commitSculpt: (stroke) => { + const state = get(); + const { sculpt } = state; + const part = state.scene.parts.find((candidate) => candidate.id === stroke.partId); + if ( + state.tool !== 'sculpt' || + !sculpt || + sculpt.pending || + sculpt.partId !== stroke.partId || + (stroke.revision !== undefined && stroke.revision !== sculpt.revision) || + !part?.visible || + part.locked || + state.selected.length !== 1 || + state.selected[0] !== part.id || + part.geometry !== stroke.source || + state.sceneEpoch !== stroke.epoch || + !same(part.position, stroke.position) || + !same(part.quaternion, stroke.quaternion) || + !same(part.scale, stroke.scale) + ) + return false; + const geometry = stroke.geometry ?? part.geometry; + if (stroke.mask && stroke.mask.length !== geometry.getAttribute('position').count) return false; + const mask = stroke.mask; + if (geometry === part.geometry && mask === sculpt.mask) return false; + if ( + geometry !== part.geometry && + (geometryBytes([geometry]) > sculptHistoryBytes || + geometry.getAttribute('position').count * Float32Array.BYTES_PER_ELEMENT > maskHistoryBytes) + ) { + state.notify('This stroke exceeded the mesh size limit for Sculpt.', 'info'); + return false; + } + if (geometry !== part.geometry && sharedSculptQueueGuard && !sharedSculptQueueGuard(geometry)) { + state.notify( + state.liveStatus === 'disconnected' + ? 'Reconnect to the shared scene to commit sculpt strokes.' + : 'Wait for pending sculpt strokes to reach the shared scene.', + 'info', + ); + return false; + } + const step = { + before: { geometry: part.geometry.uuid, mask: sculpt.mask }, + after: { geometry: geometry.uuid, mask }, + }; + set({ + ...(geometry === part.geometry + ? state.future.length + ? { future: [] } + : {} + : changed(state, { + ...state.scene, + parts: state.scene.parts.map((candidate) => + candidate.id === part.id ? { ...part, geometry } : candidate, + ), + })), + sculpt: { + ...sculpt, + revision: nextSculptRevision(), + mask, + past: appendSculptStep(sculpt.past, step), + future: [], + }, + }); + return true; + }, + changeSculptMask: (operation) => { + if (afterReleasedSculpt(() => get().changeSculptMask(operation))) return; + const state = get(); + const { sculpt } = state; + const part = sculpt && state.scene.parts.find((candidate) => candidate.id === sculpt.partId); + if (!sculpt || !part || (operation === 'clear' && !sculpt.mask)) return; + const mask = + operation === 'invert' + ? new Float32Array(part.geometry.getAttribute('position').count) + : null; + if (mask) { + const previous = sculpt.mask; + if (previous) { + for (let i = 0; i < mask.length; i++) mask[i] = 1 - previous[i]; + } else mask.fill(1); + } + state.commitSculpt({ + partId: part.id, + source: part.geometry, + epoch: state.sceneEpoch, + revision: sculpt.revision, + position: part.position, + quaternion: part.quaternion, + scale: part.scale, + geometry: null, + mask, + }); + }, startRefine: () => { const state = get(); if (useXR.getState().session) return false; @@ -4276,6 +4552,7 @@ export const useEditor = create((set, get) => ({ }), ), beginFreeTransform: (mode) => { + if (afterReleasedSculpt(() => get().beginFreeTransform(mode))) return false; const state = get(); if (state.busy || state.modal || state.freeTransform) return false; const selection = transformSelection( @@ -4293,7 +4570,7 @@ export const useEditor = create((set, get) => ({ : undefined; if (!warp) state.setTool(mode); set({ - freeTransform: { mode, axis: null, baseline: get().scene, patches: [], warp }, + freeTransform: { id: uid(), mode, axis: null, baseline: get().scene, patches: [], warp }, contextMenu: null, temporaryOrbit: false, }); @@ -4338,7 +4615,7 @@ export const useEditor = create((set, get) => ({ true, ); set((state) => { - if (state.freeTransform?.baseline !== session.baseline) return {}; + if (state.freeTransform?.id !== session.id) return {}; const differs = state.scene.parts.some((part, i) => { const before = session.baseline.parts[i]; return ( @@ -4480,7 +4757,8 @@ export const useEditor = create((set, get) => ({ ? { scene: { ...state.scene, parts } } : changed(state, { ...state.scene, parts }, checkpoint); }), - patchParts: (ids, patch, checkpoint = true) => + patchParts: (ids, patch, checkpoint = true) => { + if (afterReleasedSculpt(() => get().patchParts(ids, patch, checkpoint))) return; set((state) => { const keys = Object.keys(patch) as (keyof Part)[]; const differs = (part: Part) => @@ -4494,8 +4772,10 @@ export const useEditor = create((set, get) => ({ }, checkpoint, ); - }), + }); + }, setDisplayColor: (ids, color, checkpoint = true) => { + if (afterReleasedSculpt(() => get().setDisplayColor(ids, color, checkpoint))) return; set((state) => { const targets = new Set(ids); if ( @@ -4645,6 +4925,7 @@ export const useEditor = create((set, get) => ({ revision: state.revision + 1, savedRevision: recovered ? state.revision : state.revision + 1, tool: 'select', + sculpt: null, activeAnchor: null, activeLight: null, anchorPicking: false, @@ -4686,60 +4967,14 @@ export const useEditor = create((set, get) => ({ const next = name.trim() || 'Untitled assembly'; return next === state.scene.name ? {} : changed(state, { ...state.scene, name: next }); }), - undo: () => - sharedHandlers - ? sharedHandlers.undo() - : set((state) => - state.past.length - ? { - scene: state.past.at(-1)!, - past: state.past.slice(0, -1), - future: [state.scene, ...state.future], - revision: state.revision + 1, - selected: state.selected.filter((id) => - state.past.at(-1)!.parts.some((p) => p.id === id), - ), - ...restoredIsolated(state, state.past.at(-1)!), - operation: blankOperation(), - // Keep placement tools ready for another adjustment after undo. - tool: ['translate', 'rotate', 'scale', 'transform'].includes(state.tool) - ? state.tool - : 'select', - navigationMode: null, - pivotPicking: false, - painting: false, - paintHistory: [], - measurement: [], - } - : {}, - ), - redo: () => - sharedHandlers - ? sharedHandlers.redo() - : set((state) => - state.future.length - ? { - scene: state.future[0], - past: [...state.past, state.scene], - future: state.future.slice(1), - revision: state.revision + 1, - selected: state.selected.filter((id) => - state.future[0].parts.some((p) => p.id === id), - ), - ...restoredIsolated(state, state.future[0]), - operation: blankOperation(), - tool: ['translate', 'rotate', 'scale', 'transform'].includes(state.tool) - ? state.tool - : 'select', - navigationMode: null, - pivotPicking: false, - painting: false, - paintHistory: [], - measurement: [], - } - : {}, - ), + undo: () => { + if (!afterReleasedSculpt(() => get().undo(), { history: true })) moveHistory('undo'); + }, + redo: () => { + if (!afterReleasedSculpt(() => get().redo(), { history: true })) moveHistory('redo'); + }, setView: (patch) => { + if (patch.explode !== undefined && afterReleasedSculpt(() => get().setView(patch))) return; if (patch.orbitSelection !== undefined) saveOrbitPreference(patch.orbitSelection); if (patch.partColors !== undefined) savePartColorMode(patch.partColors); if (patch.clip) { @@ -4772,6 +5007,62 @@ useEditor.subscribe((state, previous) => { recordNotification(state.toast.message, state.toast.kind); }); +// Editor commands can outlive the viewport tool that queued them. +let sculptIsFinishing: (() => boolean) | null = null; +type SculptActionOptions = { history?: boolean; onCancel?: () => void }; +const afterSculptActions: (SculptActionOptions & { run: () => void })[] = []; +let runningSculptAction = false; + +// A Free Transform preview owns its baseline until the user confirms or cancels it. +const blocksSculptActions = (state: EditorState) => !!(state.busy || state.freeTransform); + +export function setSculptCompletionGate(gate: typeof sculptIsFinishing) { + sculptIsFinishing = gate; + if (!gate && afterSculptActions.length) queueMicrotask(flushSculptActions); +} + +export function afterReleasedSculpt(run: () => void, options: SculptActionOptions = {}): boolean { + if (!sculptIsFinishing?.() && (runningSculptAction || !afterSculptActions.length)) return false; + afterSculptActions.push({ run, ...options }); + return true; +} + +export function cancelQueuedSculptActions(scope: 'all' | 'history' = 'all') { + for (const action of afterSculptActions.splice(0)) { + if (scope === 'history' && !action.history) afterSculptActions.push(action); + else action.onCancel?.(); + } +} + +export function flushSculptActions() { + if (runningSculptAction) return; + runningSculptAction = true; + try { + while ( + afterSculptActions.length && + !sculptIsFinishing?.() && + !blocksSculptActions(useEditor.getState()) + ) { + afterSculptActions.shift()!.run(); + } + } finally { + runningSculptAction = false; + } +} + +useEditor.subscribe((state, previous) => { + if (!afterSculptActions.length) return; + if (state.sceneEpoch !== previous.sceneEpoch) cancelQueuedSculptActions(); + else if (blocksSculptActions(previous) && !blocksSculptActions(state)) + queueMicrotask(flushSculptActions); +}); + +let sharedSculptQueueGuard: ((geometry: BufferGeometry) => boolean) | null = null; + +export function useSharedSculptQueueGuard(guard: typeof sharedSculptQueueGuard) { + sharedSculptQueueGuard = guard; +} + let sharedHandlers: { undo: () => void; redo: () => void } | null = null; /** In a shared scene, undo and redo step through this tab's own changes on the server. */ @@ -4808,9 +5099,14 @@ export function warpBrushRadius(state: Pick - state.sharedHistory ? state.sharedHistory.undo > 0 : state.past.length > 0; + !state.sculpt?.pending && + (!!sculptHistoryStep(state, 'undo') || + (state.sharedHistory ? state.sharedHistory.undo > 0 : state.past.length > 0)); export const canRedo = (state: EditorState) => - state.sharedHistory ? state.sharedHistory.redo > 0 : state.future.length > 0; + !state.sculpt?.pending && + (!!sculptHistoryStep(state, 'redo') || + (!state.sculpt?.past.length && + (state.sharedHistory ? state.sharedHistory.redo > 0 : state.future.length > 0))); /** Preview poses never reach recovery, Drive, or other shared-session participants. */ export const committedScene = (state: EditorState) => state.freeTransform?.baseline ?? state.scene; @@ -6716,6 +7012,87 @@ function closesAs(segments: EdgeSegment[]) { : first.kind === 'spline' && samePoint(first.points[0], end); } +// A refused shared edit restores the mask that belonged to the server's geometry. +export function restoreSculptAfterRefusal(scene: SceneDocument, sculpt: SculptSession | null) { + if (!sculpt || useEditor.getState().sculpt?.partId !== sculpt.partId) return; + const geometry = scene.parts.find((part) => part.id === sculpt.partId)?.geometry.uuid; + const start = sculpt.past.findIndex( + (step) => step.before.geometry === geometry && step.after.geometry !== geometry, + ); + if (start < 0) return; + useEditor.setState({ + sculpt: { + ...sculpt, + mask: sculpt.past[start].before.mask, + past: sculpt.past.slice(0, start), + future: [], + pending: null, + revision: nextSculptRevision(), + }, + }); +} + +export function stopSharedSculptHistory(applied = false, pendingId?: number | null) { + const { sculpt } = useEditor.getState(); + if (!sculpt?.pending || (pendingId !== undefined && pendingId !== sculpt.pending.id)) return; + useEditor.setState({ + sculpt: { + ...sculpt, + ...(!applied ? { past: [], future: [] } : {}), + pending: null, + revision: nextSculptRevision(), + }, + }); +} + +useEditor.subscribe((state, previous) => { + const { sculpt } = state; + if (!sculpt) return; + if ( + state.tool !== 'sculpt' || + state.sceneEpoch !== previous.sceneEpoch || + state.selected.length !== 1 || + state.selected[0] !== sculpt.partId + ) { + useEditor.setState({ sculpt: null, ...(state.tool === 'sculpt' ? { tool: 'select' } : {}) }); + return; + } + if (state.scene === previous.scene) return; + const part = state.scene.parts.find((candidate) => candidate.id === sculpt.partId); + if (!part?.visible || part.locked) { + useEditor.setState({ sculpt: null, tool: 'select' }); + return; + } + const before = previous.scene.parts.find((candidate) => candidate.id === sculpt.partId); + if (!before) return; + const moved = + !same(part.position, before.position) || + !same(part.quaternion, before.quaternion) || + !same(part.scale, before.scale); + if (sculpt.pending) { + const { direction, step } = sculpt.pending; + if (part.geometry.uuid === (direction === 'undo' ? step.before : step.after).geometry) { + useEditor.setState({ + sculpt: { ...stepSculptSession(sculpt, direction, step), revision: nextSculptRevision() }, + }); + return; + } + } + const replaced = part.geometry.uuid !== before.geometry.uuid; + if (replaced && sculpt.revision === previous.sculpt?.revision) { + useEditor.setState({ + sculpt: { + ...sculpt, + mask: null, + past: [], + future: [], + pending: null, + revision: nextSculptRevision(), + }, + }); + } else if (moved) state.cancelSculptStroke(); +}); + // A refinement is built from one geometry of one scene at one pose. Undo, another editor, // opening a file or leaving the tool by any route ends the session. useEditor.subscribe((state, previous) => { diff --git a/src/core/types.ts b/src/core/types.ts index 75961ae..995a635 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -16,7 +16,33 @@ export type Tool = | 'pins' | 'anchors' | 'warp' - | 'refine'; + | 'refine' + | 'sculpt'; + +export type SculptBrush = + 'draw' | 'grab' | 'smooth' | 'flatten' | 'crease' | 'clay' | 'inflate' | 'mask'; + +export interface SculptureSettings { + brush: SculptBrush; + radius: number; + strength: number; + detail: number; + minEdge: number; + falloff: 'soft' | 'linear' | 'hard'; + symmetry: boolean; + spacing: number; + stabilization: number; + pressureStrength: boolean; + pressureRadius: boolean; + pressureCurve: number; + aspect: number; + rotation: number; + tilt: boolean; + twist: boolean; + pinch: number; + maskVisible: boolean; +} + export type AlignmentMode = 'point' | 'point-plane' | 'plane' | 'multi' | 'surface'; export type AlignmentView = 'scene' | 'pair' | 'active' | 'ghost'; diff --git a/src/hooks/useWorkbench.ts b/src/hooks/useWorkbench.ts index 9173317..9d71a23 100644 --- a/src/hooks/useWorkbench.ts +++ b/src/hooks/useWorkbench.ts @@ -1,6 +1,7 @@ import { useEffect, useRef } from 'react'; import { joinLiveSession } from '../core/live'; import { + afterReleasedSculpt, committedScene, chosenRefinePoint, brushingRefine, @@ -188,7 +189,11 @@ export function useKeyboard(openScene: () => void, searchParts: () => void) { event.preventDefault(); state.endPaintStroke(); orbitKey = event.code || keyName(event.key); - useEditor.setState({ temporaryOrbit: true }); + const held = orbitKey; + const orbit = () => { + if (orbitKey === held) useEditor.setState({ temporaryOrbit: true }); + }; + if (!afterReleasedSculpt(orbit)) orbit(); return; } const key = event.key.toLowerCase(); @@ -294,6 +299,10 @@ export function useKeyboard(openScene: () => void, searchParts: () => void) { state.setNavigationMode(null); return; } + if (state.tool === 'sculpt') { + if (!afterReleasedSculpt(() => {})) state.cancelSculptStroke(); + return; + } // Otherwise Escape leaves the tool, as it does for Warp. if (state.tool === 'refine' && refineKey(state, 'cancel')) return; const wasSelecting = state.tool === 'select'; @@ -339,11 +348,7 @@ export function useKeyboard(openScene: () => void, searchParts: () => void) { }; const up = (event: KeyboardEvent) => { if (event.key === 'Shift') useEditor.setState({ precision: false }); - if ( - useEditor.getState().temporaryOrbit && - orbitKey !== null && - (event.code || keyName(event.key)) === orbitKey - ) { + if (orbitKey !== null && (event.code || keyName(event.key)) === orbitKey) { event.preventDefault(); orbitKey = null; useEditor.setState({ temporaryOrbit: false }); diff --git a/src/styles.css b/src/styles.css index 37e423f..88d05b0 100644 --- a/src/styles.css +++ b/src/styles.css @@ -6696,7 +6696,8 @@ optgroup { gap: 3px; } .refine-ends select, -.refine-controls .brush-radius > select { +.refine-controls .brush-radius > select, +.sculpt-controls .brush-radius > select { min-width: 0; padding: 6px; border: 1px solid var(--border); @@ -6723,7 +6724,64 @@ optgroup { .refine-counts { margin: 12px 16px 0; } -/* Narrower toolbars show Pin, Anchors, Joint, Warp and Refine as icons, so the strip still fits +.sculpt-controls { + display: grid; + gap: 10px; + padding: 14px 16px; +} +.sculpt-brushes { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 5px; +} +.sculpt-brushes .button { + justify-content: center; + padding-inline: 6px; + white-space: normal; +} +.sculpt-brushes .button.active { + border-color: var(--accent); + color: var(--accent); +} +.sculpt-controls .field-help { + margin: 0; +} +.sculpt-check { + display: flex; + align-items: center; + gap: 8px; + min-height: 24px; + font-size: 11px; + color: var(--muted); +} +.sculpt-check input { + margin: 0; + accent-color: var(--accent); +} +.sculpt-mask-controls { + display: grid; + gap: 6px; + border-top: 1px solid var(--border); + padding-top: 8px; +} +.sculpt-mask-actions { + display: flex; + flex-wrap: wrap; + gap: 6px; +} +.sculpt-advanced { + margin-inline: -16px; +} +.sculpt-advanced:not([open]) > summary > svg { + transform: rotate(-90deg); +} +.sculpt-advanced-fields { + display: grid; + gap: 8px; + padding-inline: 16px; +} + +/* Narrower toolbars show secondary tools as icons, so the strip still fits on one row. Their names stay in the tooltip and for assistive technology. */ @media (max-width: 1500px) { .toolbar-left .compact-tool { @@ -6740,13 +6798,15 @@ optgroup { } @media (max-width: 1700px) { .toolbar-left .warp-tool, - .toolbar-left .refine-tool { + .toolbar-left .refine-tool, + .toolbar-left .sculpt-tool { position: relative; } .toolbar-left .warp-tool > span, .toolbar-left .warp-tool > kbd, .toolbar-left .refine-tool > span, - .toolbar-left .refine-tool > kbd { + .toolbar-left .refine-tool > kbd, + .toolbar-left .sculpt-tool > span { position: absolute; width: 1px; height: 1px; diff --git a/src/xr/runtime.ts b/src/xr/runtime.ts index 1645bcb..8579055 100644 --- a/src/xr/runtime.ts +++ b/src/xr/runtime.ts @@ -229,7 +229,7 @@ export class XRRuntime { ) { // Warp and Refine are desktop only. const editor = useEditor.getState(); - if (editor.tool === 'warp' || editor.tool === 'refine') { + if (editor.tool === 'warp' || editor.tool === 'refine' || editor.tool === 'sculpt') { editor.setTool('select'); this.tool = 'select'; } diff --git a/tests/e2e/helpers/sculpt.ts b/tests/e2e/helpers/sculpt.ts new file mode 100644 index 0000000..265e99b --- /dev/null +++ b/tests/e2e/helpers/sculpt.ts @@ -0,0 +1,46 @@ +import type { Page } from '@playwright/test'; + +type Shortcut = Pick; + +/** Dispatch shortcuts in the same task as a pen lift, with stroke work left for the next frame. */ +export async function queueAfterPenRelease( + page: Page, + point: { x: number; y: number }, + shortcuts: Shortcut[], + options: { end?: { x: number; y: number }; releaseClockOn?: string } = {}, +) { + await page.evaluate( + ({ point, shortcuts, options }) => { + const now = performance.now.bind(performance); + let elapsed = now(); + performance.now = () => (elapsed += 8); + try { + const canvas = document.querySelector('canvas')!; + const pen = { + clientX: point.x, + clientY: point.y, + pointerType: 'pen', + pointerId: 40, + isPrimary: true, + pressure: 0.8, + bubbles: true, + }; + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); + const end = options.end ? { ...pen, clientX: options.end.x, clientY: options.end.y } : pen; + if (options.end) + canvas.dispatchEvent(new PointerEvent('pointermove', { ...end, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', end)); + for (const shortcut of shortcuts) + window.dispatchEvent(new KeyboardEvent('keydown', shortcut)); + } finally { + const restore = () => { + performance.now = now; + }; + if (options.releaseClockOn) + window.addEventListener(options.releaseClockOn, restore, { once: true }); + else restore(); + } + }, + { point, shortcuts, options }, + ); +} diff --git a/tests/e2e/mcp.spec.ts b/tests/e2e/mcp.spec.ts index 14d23ce..7fd0473 100644 --- a/tests/e2e/mcp.spec.ts +++ b/tests/e2e/mcp.spec.ts @@ -6,9 +6,12 @@ import { join } from 'node:path'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; import { expect, test } from '@playwright/test'; -import type { Page } from '@playwright/test'; +import type { Page, Request } from '@playwright/test'; import { BoxGeometry, Mesh } from 'three'; import { STLExporter } from 'three/addons/exporters/STLExporter.js'; +import { serializeGeometry } from '../../src/core/geometry'; +import { queueAfterPenRelease } from './helpers/sculpt'; +import { readSavedScene } from './saved-scene'; // These drive the bundle a client would really start, over real stdio, with the real app. let folder: string; @@ -423,3 +426,981 @@ test('tabs and the agent edit one scene, each with its own view', async ({ brows expect(errors).toEqual([]); await context.close(); }); + +test('refusing an ordinary shared edit discards its queued undo', async ({ page }) => { + await call('add_parts', { parts: model }); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + await expect(page.getByText('Shared with agent')).toBeVisible(); + const undo = page.getByRole('button', { name: /^Undo \((⌘|Ctrl)\+Z\)$/ }); + const rename = async (name: string) => { + await page.getByTitle('Rename assembly').click(); + const field = page.getByRole('textbox', { name: 'Assembly name' }); + await field.fill(name); + await field.press('Enter'); + }; + await rename('Accepted assembly name'); + await expect(undo).toBeEnabled(); + + let reject = () => {}; + const held = new Promise((resolve) => { + reject = resolve; + }); + const edit = /\/live\/edit$/; + await page.route(edit, async (route) => { + await held; + await route.fulfill({ status: 409, json: { error: 'Edit refused for this test.' } }); + }); + const submitted = page.waitForRequest(edit); + await rename('Refused assembly name'); + await submitted; + const undoRequests: string[] = []; + page.on('request', (request) => { + if (/\/live\/undo$/.test(request.url())) undoRequests.push(request.url()); + }); + await undo.click(); + reject(); + await expect(page.getByText(/edit refused for this test/i)).toBeVisible(); + await expect(page.getByTitle('Rename assembly')).toHaveText('Accepted assembly name'); + + await page.unroute(edit); + const nextEdit = page.waitForResponse(edit); + await rename('New assembly name'); + expect((await nextEdit).ok()).toBe(true); + expect(undoRequests).toEqual([]); +}); + +for (const replaceScene of [false, true]) { + test( + replaceScene + ? 'discards commands from a queued preview when the shared scene is replaced' + : 'discards the queued Undo when a shared stroke refusal closes a preview', + async ({ page }) => { + await call('add_parts', { + parts: [{ id: 'block', name: 'Sculpt block', shapes: [{ type: 'box', size: [10, 8, 6] }] }], + }); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + const title = page.getByTitle('Rename assembly'); + const originalName = 'Untitled assembly'; + await expect(title).toHaveText(originalName); + const acceptedName = 'Accepted assembly name'; + const rename = async (name: string) => { + await title.click(); + const field = page.getByRole('textbox', { name: 'Assembly name' }); + await field.fill(name); + await field.press('Enter'); + }; + await rename(acceptedName); + await expect(page.getByRole('button', { name: /^Undo \((⌘|Ctrl)\+Z\)$/ })).toBeEnabled(); + await page.locator(part('Sculpt block')).click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.getByRole('button', { name: 'Sculpt', exact: true }).click(); + const canvas = (await page.locator('canvas').boundingBox())!; + const point = { x: canvas.x + canvas.width / 2 + 8, y: canvas.y + canvas.height / 2 - 7 }; + + let rejectStroke = () => {}; + const held = new Promise((resolve) => { + rejectStroke = resolve; + }); + const edit = /\/live\/edit$/; + await page.route(edit, async (route) => { + if (!route.request().postDataJSON().sculpt) return route.continue(); + await held; + await route.fulfill({ status: 409, json: { error: 'Stroke refused for this test.' } }); + }); + let undoRequests = 0; + page.on('request', (request) => { + if (request.url().endsWith('/live/undo')) undoRequests++; + }); + const submitted = page.waitForRequest(edit); + await queueAfterPenRelease(page, point, [ + { key: 'G', code: 'KeyG', shiftKey: true }, + { key: 'z', code: 'KeyZ', ctrlKey: true }, + { key: 'F1', code: 'F1' }, + ]); + expect((await submitted).postDataJSON().sculpt).toBeTruthy(); + const prompt = page.locator('.free-transform-prompt'); + const help = page.getByRole('dialog', { name: 'A workbench that gets out of your way.' }); + await expect(prompt).toBeVisible(); + if (replaceScene) { + await call('new_scene', { name: 'Replacement', discard_unsaved: true }); + await expect(title).toHaveText('Replacement'); + await expect(prompt).toHaveCount(0); + const renamed = page.waitForResponse( + (response) => + edit.test(response.url()) && + response.request().postDataJSON().scene.name === 'Newer rename', + { timeout: 8000 }, + ); + await rename('Newer rename'); + await expect(title).toHaveText('Newer rename'); + rejectStroke(); + expect((await renamed).ok()).toBe(true); + expect((await call('get_scene')).name).toBe('Newer rename'); + await expect(help).toHaveCount(0); + expect(undoRequests).toBe(0); + } else { + rejectStroke(); + await expect(page.getByText(/stroke refused for this test/i)).toBeVisible(); + await expect(prompt).toHaveCount(0); + // A later non-history command still runs after the refused stroke rolls back. + await expect(help).toBeVisible(); + await expect(title).toHaveText(acceptedName); + expect(undoRequests).toBe(0); + await help.getByRole('button', { name: 'Close dialog', exact: true }).click(); + await page.keyboard.press('ControlOrMeta+z'); + await expect(title).toHaveText(originalName); + expect(undoRequests).toBe(1); + } + }, + ); +} + +test('publishes Delete queued behind a stroke interrupted by a shared pose update', async ({ + page, +}) => { + await call('add_parts', { + parts: [{ id: 'block', name: 'Sculpt block', shapes: [{ type: 'box', size: [10, 8, 6] }] }], + }); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + await page.locator(part('Sculpt block')).click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.getByRole('button', { name: 'Sculpt', exact: true }).click(); + const radius = page.getByRole('spinbutton', { name: 'Radius', exact: true }); + await radius.fill('0.12'); + await radius.press('Enter'); + const box = (await page.locator('canvas').boundingBox())!; + const start = { x: box.x + box.width / 2 - 55, y: box.y + box.height / 2 - 7 }; + const edit = page.waitForResponse( + (response) => + response.url().endsWith('/live/edit') && !response.request().postDataJSON().sculpt, + { timeout: 5000 }, + ); + await queueAfterPenRelease(page, start, [{ key: 'Delete', code: 'Delete' }], { + end: { x: start.x + 140, y: start.y }, + releaseClockOn: 'resume-sculpt-clock', + }); + try { + await call('update_parts', { updates: [{ id: 'block', translate: [2, 0, 0] }] }); + await expect(page.locator(part('Sculpt block'))).toHaveCount(0); + expect((await edit).ok()).toBe(true); + expect((await call('get_scene')).parts).toHaveLength(0); + } finally { + await page.evaluate(() => window.dispatchEvent(new Event('resume-sculpt-clock'))); + } +}); + +const isMeshUpload = (request: Request) => + request.method() === 'POST' && /\/live\/geometry\/[^/]+$/.test(request.url()); + +async function failFirstMeshUpload(page: Page, held: Promise) { + const keys: string[] = []; + await page.route(/\/live\/geometry\//, async (route) => { + if (!isMeshUpload(route.request())) return route.continue(); + keys.push(route.request().url()); + if (keys.length !== 1) return route.continue(); + await held; + await route.fulfill({ status: 502, json: { error: 'The mesh upload response was lost.' } }); + }); + return keys; +} + +async function captureStaleSharedStream(page: Page) { + await page.addInitScript(() => { + const fetch = window.fetch.bind(window); + window.fetch = async (...args) => { + const response = await fetch(...args); + if (response.status === 502 && response.url.endsWith('/live/edit')) + window.setTimeout(() => window.dispatchEvent(new Event('replay-stale-scene')), 20); + return response; + }; + const NativeEventSource = window.EventSource; + let first = true; + window.EventSource = class extends NativeEventSource { + constructor(url: string | URL, init?: EventSourceInit) { + super(url, init); + if (!first) return; + first = false; + let initial: string | null = null; + this.addEventListener('scene', (event) => { + initial ??= event.data; + if (event.data !== initial) event.stopImmediatePropagation(); + }); + window.addEventListener( + 'replay-stale-scene', + () => { + document.documentElement.dataset.replayedStaleScene = '1'; + this.dispatchEvent(new MessageEvent('scene', { data: initial })); + }, + { once: true }, + ); + } + }; + }); +} + +test('recovers a shared scene after a mesh download fails during initial sync', async ({ + page, +}) => { + await call('add_parts', { + parts: [{ id: 'block', name: 'Shared block', shapes: [{ type: 'box', size: [8, 6, 4] }] }], + }); + const { url } = await call('open_live_view', { open_browser: false }); + const attempts: string[] = []; + let streams = 0; + await page.route(/\/live\/events$/, async (route) => { + if (++streams !== 2) return route.continue(); + await route.fulfill({ status: 502, body: 'Stream temporarily unavailable.' }); + }); + await page.route(/\/live\/geometry\//, async (route) => { + if (route.request().method() !== 'GET') return route.continue(); + attempts.push(route.request().url()); + if (attempts.length !== 1) return route.continue(); + await route.fulfill({ status: 502, body: 'Mesh temporarily unavailable.' }); + }); + await page.goto(url); + await expect(page.locator(part('Shared block'))).toBeVisible(); + await expect(page.getByText('Shared with agent')).toBeVisible(); + expect(attempts).toEqual([attempts[0], attempts[0]]); + expect(streams).toBe(3); +}); + +test('reconnects when the first shared event stream request returns 502', async ({ page }) => { + await call('add_parts', { parts: [model[0]] }); + const { url } = await call('open_live_view', { open_browser: false }); + let streams = 0; + await page.route(/\/live\/events$/, async (route) => { + if (++streams !== 1) return route.continue(); + await route.fulfill({ status: 502, body: 'Stream temporarily unavailable.' }); + }); + + await page.goto(url); + await expect(page.locator(part('Agent base'))).toBeVisible(); + await expect(page.getByText('Shared with agent')).toBeVisible(); + expect(streams).toBe(2); +}); + +async function initialSceneEvent(url: string) { + const stream = new AbortController(); + try { + const response = await fetch(new URL('live/events', url), { + signal: AbortSignal.any([stream.signal, AbortSignal.timeout(5000)]), + }); + if (!response.ok || !response.body) throw new Error('Could not read the first scene event.'); + const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); + let body = ''; + for (;;) { + const chunk = await reader.read(); + if (chunk.done) throw new Error('The stream ended before its first scene event.'); + body += chunk.value; + const end = body.indexOf('\n\n'); + if (end >= 0) return body.slice(0, end + 2); + } + } finally { + stream.abort(); + } +} + +for (const idle of [false, true]) { + test(`recovers a terminal native reconnect ${idle ? 'while idle' : 'while loading the first mesh'}`, async ({ + page, + }) => { + await call('new_scene', { name: 'Initial shared scene' }); + if (!idle) await call('add_parts', { parts: [model[0]] }); + const { url } = await call('open_live_view', { open_browser: false }); + const initial = await initialSceneEvent(url); + let streams = 0; + let firstMeshAborted = false; + const meshReads: string[] = []; + await page.route(/\/live\/events$/, async (route) => { + if (++streams === 1) + return route.fulfill({ contentType: 'text/event-stream', body: `retry: 100\n${initial}` }); + if (streams === 2) + return route.fulfill({ status: 502, body: 'Stream temporarily unavailable.' }); + return route.continue(); + }); + if (!idle) { + await page.route(/\/live\/geometry\//, async (route) => { + const request = route.request(); + if (request.method() !== 'GET') return route.continue(); + meshReads.push(request.url()); + if (meshReads.length !== 1) return route.continue(); + // The first response stays pending until the disconnect aborts the browser's fetch. + const failed = await page + .waitForEvent('requestfailed', { + predicate: (failed) => failed === request, + timeout: 3000, + }) + .catch(() => null); + firstMeshAborted = !!failed; + await route.abort().catch(() => {}); + }); + } + + await page.goto(url); + if (idle) { + await expect(page.getByText('Initial shared scene').first()).toBeVisible(); + await call('add_parts', { parts: [model[0]] }); + } + await expect(page.locator(part('Agent base'))).toBeVisible(); + await expect(page.getByText('Shared with agent')).toBeVisible(); + expect(streams).toBe(3); + if (!idle) { + expect(firstMeshAborted).toBe(true); + expect(meshReads).toEqual([meshReads[0], meshReads[0]]); + } + }); +} + +for (const replyOrder of [ + 'HTTP first', + 'stream first', + 'stream then HTTP error', + 'HTTP error then refreshed stream', + 'HTTP rejection', + 'mesh upload 502', + 'mesh upload 502 followed by stream 502', +] as const) { + test(`keeps sculpt and Save scoped to the right scene with ${replyOrder}`, async ({ page }) => { + const holdResponse = replyOrder.startsWith('stream'); + const httpError = replyOrder.includes('HTTP error'); + const rejected = replyOrder === 'HTTP rejection'; + const uploadError = replyOrder.startsWith('mesh upload'); + const streamError = replyOrder === 'mesh upload 502 followed by stream 502'; + let streams = 0; + if (streamError) + await page.route(/\/live\/events$/, async (route) => { + if (++streams !== 2) return route.continue(); + await route.fulfill({ status: 502, body: 'Stream temporarily unavailable.' }); + }); + await page.addInitScript(() => { + const NativeEventSource = window.EventSource; + let connections = 0; + window.EventSource = class extends NativeEventSource { + constructor(url: string | URL, init?: EventSourceInit) { + super(url, init); + const initialStream = ++connections === 1; + this.addEventListener('scene', (event) => { + const { version } = JSON.parse(event.data); + const { dataset } = document.documentElement; + dataset.sharedVersion = String(version); + if (initialStream && dataset.holdShared === '1') { + event.stopImmediatePropagation(); + window.addEventListener( + 'release-shared-scene', + () => this.dispatchEvent(new MessageEvent('scene', { data: event.data })), + { once: true }, + ); + } + }); + } + }; + }); + await call('add_parts', { + parts: [{ id: 'old', name: 'Old block', shapes: [{ type: 'box', size: [10, 8, 6] }] }], + }); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + await expect(page.locator(part('Old block'))).toBeVisible(); + const geometry = new BoxGeometry(10, 8, 6); + const openedScene = { + format: 'kitbasher', + version: 1, + units: 'mm', + name: 'Opened scene', + joints: [], + parts: [ + { + id: 'new', + name: 'New block', + geometry: serializeGeometry(geometry), + position: [0, 0, 0], + quaternion: [0, 0, 0, 1], + scale: [1, 1, 1], + color: '#cccccc', + visible: true, + locked: false, + source: 'block', + }, + ], + }; + let submit = () => {}; + let reply = () => {}; + const submitted = new Promise((resolve) => { + submit = resolve; + }); + const answered = new Promise((resolve) => { + reply = resolve; + }); + const edit = /\/live\/edit$/; + const uploads = uploadError ? await failFirstMeshUpload(page, submitted) : []; + let replacementVersion = 0; + await page.route(edit, async (route) => { + if (!route.request().postDataJSON().replace) return route.continue(); + await submitted; + if (rejected) + return route.fulfill({ + status: 409, + json: { error: 'Replacement refused for this test.' }, + }); + const response = await route.fetch(); + replacementVersion = (await response.json()).version; + if (holdResponse) await answered; + if (httpError) + await route.fulfill({ status: 502, json: { error: 'Replacement response was lost.' } }); + else await route.fulfill({ response }); + }); + await page.getByLabel('Open Kitbasher scene').setInputFiles({ + name: 'opened.kitbash', + mimeType: 'application/json', + buffer: Buffer.from(JSON.stringify(openedScene)), + }); + const opening = page.waitForRequest( + uploadError + ? isMeshUpload + : (request) => edit.test(request.url()) && request.postDataJSON().replace, + ); + await page.getByRole('button', { name: 'Open scene', exact: true }).click(); + const original = await opening; + await page.locator(part('New block')).click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.getByRole('button', { name: 'Sculpt', exact: true }).click(); + const box = (await page.locator('canvas').boundingBox())!; + await queueAfterPenRelease( + page, + { x: box.x + box.width / 2 + 8, y: box.y + box.height / 2 - 7 }, + [ + { key: 'G', code: 'KeyG', shiftKey: true }, + { key: 's', code: 'KeyS', ctrlKey: true }, + ], + ); + const prompt = page.locator('.free-transform-prompt'); + await expect(prompt).toBeVisible(); + const response = page.waitForResponse((result) => result.request() === original); + if (rejected) { + const download = page.waitForEvent('download', { timeout: 1500 }).catch(() => null); + submit(); + expect((await response).status()).toBe(409); + await expect(page.locator(part('Old block'))).toBeVisible(); + await expect(prompt).toHaveCount(0); + expect(await download).toBeNull(); + geometry.dispose(); + return; + } + const acceptedStroke = page + .waitForResponse( + (result) => edit.test(result.url()) && !!result.request().postDataJSON().sculpt, + { timeout: 8000 }, + ) + .catch(() => null); + if (!holdResponse && !uploadError) + await page.evaluate(() => { + document.documentElement.dataset.holdShared = '1'; + }); + submit(); + if (!holdResponse) expect((await response).status()).toBe(httpError || uploadError ? 502 : 200); + await expect.poll(() => replacementVersion).toBeGreaterThan(0); + await expect + .poll(async () => Number(await page.locator('html').getAttribute('data-shared-version'))) + .toBeGreaterThanOrEqual(replacementVersion); + if (holdResponse) { + reply(); + expect((await response).status()).toBe(httpError ? 502 : 200); + } else if (!httpError && !uploadError) { + await page.evaluate(() => { + delete document.documentElement.dataset.holdShared; + window.dispatchEvent(new Event('release-shared-scene')); + }); + } + expect((await acceptedStroke)?.ok()).toBe(true); + if (uploadError) expect(uploads.slice(0, 2)).toEqual([uploads[0], uploads[0]]); + if (streamError) expect(streams).toBe(3); + await expect(prompt).toBeVisible(); + const download = page.waitForEvent('download'); + await page.keyboard.press('Escape'); + const saved = await download; + const { scene } = await readSavedScene((await saved.path())!); + expect(scene.name).toBe('Opened scene'); + const sculpted = scene.parts[0].geometry; + expect(sculpted.index?.count ?? sculpted.getAttribute('position').count).toBeGreaterThan(36); + geometry.dispose(); + }); +} + +async function openBlankSceneInTab(page: Page, name: string) { + await page.getByLabel('Open Kitbasher scene').setInputFiles({ + name: 'opened.kitbash', + mimeType: 'application/json', + buffer: Buffer.from( + JSON.stringify({ format: 'kitbasher', version: 1, units: 'mm', name, parts: [], joints: [] }), + ), + }); + await page.getByRole('button', { name: 'Open scene', exact: true }).click(); +} + +for (const loseReply of [false, true]) { + test( + loseReply + ? 'preserves the newer shared scene after a replacement loses both acknowledgments' + : 'rejects an in-flight Open after another editor replaces the shared scene', + async ({ page }) => { + const openedName = 'Opened by this tab'; + if (loseReply) + await page.addInitScript((name) => { + const NativeEventSource = window.EventSource; + window.EventSource = class extends NativeEventSource { + constructor(url: string | URL, init?: EventSourceInit) { + super(url, init); + this.addEventListener('scene', (event) => { + if (JSON.parse(event.data).scene.name === name) event.stopImmediatePropagation(); + }); + } + }; + }, openedName); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + const title = page.getByTitle('Rename assembly'); + await expect(title).toHaveText('Untitled assembly'); + + let resume = () => {}; + const held = new Promise((resolve) => { + resume = resolve; + }); + const edit = /\/live\/edit$/; + let replacements = 0; + await page.route(edit, async (route) => { + if (!route.request().postDataJSON().replace || ++replacements !== 1) + return route.continue(); + if (loseReply) { + const response = await route.fetch(); + expect(response.ok()).toBe(true); + await route.abort('connectionreset'); + } else { + await held; + await route.continue(); + } + }); + const submitted = page.waitForRequest(edit); + await openBlankSceneInTab(page, openedName); + const request = await submitted; + if (loseReply) { + await expect(page.getByText(/Agent disconnected/)).toBeVisible(); + expect((await call('get_scene')).name).toBe(openedName); + } + const newer = 'Newer shared scene'; + await call('new_scene', { name: newer, discard_unsaved: true }); + await expect(title).toHaveText(newer); + if (!loseReply) { + const response = page.waitForResponse((result) => result.request() === request); + resume(); + expect((await response).status()).toBe(409); + } + await title.click(); + const field = page.getByRole('textbox', { name: 'Assembly name' }); + await field.fill('Edit on the newer scene'); + const renamed = page.waitForResponse( + (result) => edit.test(result.url()) && !result.request().postDataJSON().replace, + ); + await field.press('Enter'); + expect((await renamed).ok()).toBe(true); + expect((await call('get_scene')).name).toBe('Edit on the newer scene'); + expect(replacements).toBe(1); + }, + ); +} + +for (const firstEdit of ['remote', 'same tab', 'same tab with stale stream'] as const) { + const fromSameTab = firstEdit !== 'remote'; + test( + fromSameTab + ? `advances a queued second Open when this tab’s first Open is acknowledged (${firstEdit})` + : 'discards an unsent Open when another editor replaces its starting scene', + async ({ page }) => { + const staleStream = firstEdit === 'same tab with stale stream'; + if (staleStream) await captureStaleSharedStream(page); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + const title = page.getByTitle('Rename assembly'); + await expect(title).toHaveText('Untitled assembly'); + const rename = async (name: string) => { + await title.click(); + const field = page.getByRole('textbox', { name: 'Assembly name' }); + await field.fill(name); + await field.press('Enter'); + }; + let resume = () => {}; + const held = new Promise((resolve) => { + resume = resolve; + }); + const edit = /\/live\/edit$/; + const requests: { replace: boolean; epoch: number }[] = []; + await page.route(edit, async (route) => { + requests.push(route.request().postDataJSON()); + if (requests.length === 1) { + await held; + if (staleStream) { + expect((await route.fetch()).ok()).toBe(true); + return route.fulfill({ status: 502, json: { error: 'Open response was lost.' } }); + } + } + await route.continue(); + }); + const first = page.waitForRequest(edit); + if (fromSameTab) await openBlankSceneInTab(page, 'First Open'); + else await rename('Pending rename'); + await first; + await openBlankSceneInTab(page, 'Queued Open'); + await expect(title).toHaveText('Queued Open'); + if (fromSameTab) { + resume(); + await expect.poll(async () => (await call('get_scene')).name).toBe('Queued Open'); + if (staleStream) + await expect(page.locator('html')).toHaveAttribute('data-replayed-stale-scene', '1'); + expect(requests.map(({ epoch }) => epoch)).toEqual([ + requests[0].epoch, + requests[0].epoch + 1, + ]); + } else { + await call('new_scene', { name: 'Remote Open', discard_unsaved: true }); + await expect(title).toHaveText('Remote Open'); + resume(); + const renamed = page.waitForResponse( + (result) => + edit.test(result.url()) && result.request().postDataJSON().scene.name === 'Newer edit', + ); + await rename('Newer edit'); + expect((await renamed).ok()).toBe(true); + expect((await call('get_scene')).name).toBe('Newer edit'); + expect(requests.some(({ replace }) => replace)).toBe(false); + } + }, + ); +} + +for (const failure of [ + 'late 502', + 'connection reset', + 'upload 502', + '502 with stale stream', +] as const) { + test(`publishes the next shared stroke after ${failure}`, async ({ page }) => { + const staleStream = failure === '502 with stale stream'; + const uploadError = failure === 'upload 502'; + if (staleStream) await captureStaleSharedStream(page); + else + await page.addInitScript(() => { + const NativeEventSource = window.EventSource; + window.EventSource = class extends NativeEventSource { + constructor(url: string | URL, init?: EventSourceInit) { + super(url, init); + this.addEventListener('scene', (event) => { + document.documentElement.dataset.sharedVersion = String( + JSON.parse(event.data).version, + ); + }); + } + }; + }); + await call('add_parts', { + parts: [{ id: 'block', name: 'Sculpt block', shapes: [{ type: 'box', size: [10, 8, 6] }] }], + }); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + await page.locator(part('Sculpt block')).click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.getByRole('button', { name: 'Sculpt', exact: true }).click(); + const box = (await page.locator('canvas').boundingBox())!; + const point = { x: box.x + box.width / 2 + 8, y: box.y + box.height / 2 - 7 }; + let settle = () => {}; + const held = new Promise((resolve) => { + settle = resolve; + }); + const edit = /\/live\/edit$/; + const uploads = uploadError ? await failFirstMeshUpload(page, held) : []; + const firstUpload = uploadError ? page.waitForRequest(isMeshUpload) : null; + let firstVersion = 0; + let strokes = 0; + await page.route(edit, async (route) => { + if (!route.request().postDataJSON().sculpt || ++strokes !== 1 || uploadError) + return route.continue(); + const response = await route.fetch(); + expect(response.ok()).toBe(true); + firstVersion = (await response.json()).version; + await held; + if (failure === 'connection reset') await route.abort('connectionreset'); + else await route.fulfill({ status: 502, json: { error: 'Stroke response was lost.' } }); + }); + await page.mouse.click(point.x, point.y); + if (firstUpload) await firstUpload; + else { + await expect.poll(() => firstVersion).toBeGreaterThan(0); + if (!staleStream) + await expect(page.locator('html')).toHaveAttribute( + 'data-shared-version', + String(firstVersion), + ); + } + await page.mouse.click(point.x + 18, point.y); + const next = page.waitForResponse( + (result) => + edit.test(result.url()) && + result.ok() && + !!result.request().postDataJSON().sculpt && + strokes >= 2, + { timeout: 8000 }, + ); + settle(); + expect((await next).ok()).toBe(true); + if (staleStream) + await expect(page.locator('html')).toHaveAttribute('data-replayed-stale-scene', '1'); + expect(strokes).toBe(2); + if (uploadError) expect(uploads.slice(0, 2)).toEqual([uploads[0], uploads[0]]); + await expect(page.getByText('Shared with agent')).toBeVisible(); + }); +} + +test('shared sculpt strokes keep their checkpoints and refuse a stale target pose', async ({ + page, +}) => { + await call('add_parts', { + parts: [{ id: 'block', name: 'Sculpt block', shapes: [{ type: 'box', size: [10, 8, 6] }] }], + }); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + await page.locator(part('Sculpt block')).click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.getByRole('button', { name: 'Sculpt', exact: true }).click(); + const radius = page.getByRole('spinbutton', { name: 'Radius', exact: true }); + await radius.fill('1.5'); + await radius.press('Enter'); + + const canvas = await page.locator('canvas').boundingBox(); + expect(canvas).not.toBeNull(); + const x = canvas!.x + canvas!.width / 2; + const y = canvas!.y + canvas!.height / 2; + const editUrl = /\/live\/edit$/; + const ofSculpt = (request: { postDataJSON: () => { sculpt?: unknown } }) => + !!request.postDataJSON().sculpt; + + let unpause = () => {}; + let blocked = new Promise((resolve) => { + unpause = resolve; + }); + let intercept = true; + await page.route(editUrl, async (route) => { + if (intercept && ofSculpt(route.request())) { + intercept = false; + await blocked; + } + await route.continue(); + }); + + const first = page.waitForRequest((request) => editUrl.test(request.url()) && ofSculpt(request)); + await page.mouse.click(x + 8, y - 7); + const firstRequest = await first; + await page.mouse.click(x + 16, y - 7); + const second = page.waitForResponse( + (response) => + editUrl.test(response.url()) && + response.request() !== firstRequest && + ofSculpt(response.request()), + ); + unpause(); + const secondResponse = await second; + expect(secondResponse.status()).toBe(200); + expect(secondResponse.request().postDataJSON().sculpt.source).not.toEqual( + firstRequest.postDataJSON().sculpt.source, + ); + expect(secondResponse.request().postDataJSON().checkpoint).toBe(true); + + // The stroke can change geometry through zero-valued weights, which it then discards. + const invertMask = page.getByRole('button', { name: 'Invert mask', exact: true }); + const clearMask = page.getByRole('button', { name: 'Clear mask', exact: true }); + await invertMask.click(); + await invertMask.click(); + await expect(clearMask).toBeEnabled(); + + blocked = new Promise((resolve) => { + unpause = resolve; + }); + intercept = true; + const third = page.waitForRequest((request) => editUrl.test(request.url()) && ofSculpt(request)); + await page.mouse.click(x + 24, y - 7); + const thirdRequest = await third; + await expect(clearMask).toBeDisabled(); + const extraUndo: string[] = []; + page.on('request', (request) => { + if (/\/live\/undo$/.test(request.url())) extraUndo.push(request.url()); + }); + await page.keyboard.press('ControlOrMeta+z'); + await call('update_parts', { updates: [{ id: 'block', translate: [2, 0, 0] }] }); + const refused = page.waitForResponse((response) => response.request() === thirdRequest); + unpause(); + expect((await refused).status()).toBe(409); + await expect( + page.getByText(/sculpt target changed before the stroke reached the shared scene/i), + ).toBeVisible(); + await expect(clearMask).toBeEnabled(); + expect((await call('get_scene')).parts[0].position).toEqual([2, 0, 0]); + expect(extraUndo).toEqual([]); +}); + +test('an ordinary edit between queued strokes preserves a newer remote mesh', async ({ page }) => { + await call('add_parts', { + parts: [{ id: 'block', name: 'Sculpt block', shapes: [{ type: 'box', size: [10, 8, 6] }] }], + }); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + await page.locator(part('Sculpt block')).click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.getByRole('button', { name: 'Sculpt', exact: true }).click(); + const radius = page.getByRole('spinbutton', { name: 'Radius', exact: true }); + await radius.fill('1.5'); + await radius.press('Enter'); + + const canvas = (await page.locator('canvas').boundingBox())!; + const x = canvas.x + canvas.width / 2; + const y = canvas.y + canvas.height / 2; + const editUrl = /\/live\/edit$/; + let unblock = () => {}; + const blocked = new Promise((resolve) => { + unblock = resolve; + }); + let applyRemote = () => {}; + const remoteReady = new Promise((resolve) => { + applyRemote = resolve; + }); + let held = false; + let completed = false; + let remoteGeometry = ''; + await page.route(editUrl, async (route) => { + const body = route.request().postDataJSON(); + if (held || !body.sculpt) return await route.continue(); + held = true; + await remoteReady; + const accepted = await route.fetch(); + if (accepted.ok()) { + const { version } = await accepted.json(); + remoteGeometry = body.sculpt.source; + // Replace the stroke's mesh using a separate author's edit before this tab can send again. + const remote = await page.request.post(route.request().url(), { + data: { + client: 'remote-editor', + base: version, + epoch: body.epoch, + checkpoint: true, + scene: { + ...body.scene, + parts: body.scene.parts.map((part: { id: string }) => ({ + ...part, + ...(part.id === body.sculpt.partId + ? { geometry: remoteGeometry, name: 'Remotely edited block' } + : {}), + })), + }, + }, + }); + completed = remote.ok(); + } + await blocked; + await route.fulfill({ response: accepted }); + }); + + await page.mouse.click(x + 8, y - 7); + await expect.poll(() => held).toBe(true); + await page.getByTitle('Rename assembly').click(); + await page.getByRole('textbox', { name: 'Assembly name' }).fill('Renamed while sculpting'); + await page.getByRole('textbox', { name: 'Assembly name' }).press('Enter'); + await page.mouse.click(x + 16, y - 7); + applyRemote(); + await expect.poll(() => completed).toBe(true); + await expect(page.locator(part('Remotely edited block'))).toBeVisible(); + const ordinary = page.waitForRequest( + (request) => editUrl.test(request.url()) && !request.postDataJSON().sculpt, + ); + unblock(); + const request = await ordinary; + expect((await request.response())?.status()).toBe(200); + await expect( + page.getByText(/sculpt target changed before the stroke reached the shared scene/i), + ).toBeVisible(); + expect((await call('get_scene')).name).toBe('Renamed while sculpting'); + expect(request.postDataJSON().scene.parts[0].geometry).toBe(remoteGeometry); +}); + +test('a remote mesh survives the delayed response for a single sculpt stroke', async ({ page }) => { + await call('add_parts', { + parts: [{ id: 'block', name: 'Sculpt block', shapes: [{ type: 'box', size: [10, 8, 6] }] }], + }); + const { url } = await call('open_live_view', { open_browser: false }); + await page.goto(url); + await page.locator(part('Sculpt block')).click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page.getByRole('button', { name: 'Sculpt', exact: true }).click(); + const radius = page.getByRole('spinbutton', { name: 'Radius', exact: true }); + await radius.fill('1.5'); + await radius.press('Enter'); + + const canvas = page.locator('canvas'); + const box = (await canvas.boundingBox())!; + const triangles = page.locator('.scene-summary').getByText(/triangles$/); + const baseline = await triangles.innerText(); + const editUrl = /\/live\/edit$/; + let finish = () => {}; + const held = new Promise((resolve) => { + finish = resolve; + }); + let acceptedVersion = 0; + await page.route(editUrl, async (route) => { + const accepted = await route.fetch(); + if (accepted.ok() && route.request().postDataJSON().sculpt) { + const { version } = await accepted.json(); + acceptedVersion = version; + await held; + } + await route.fulfill({ response: accepted }); + }); + + const sent = page.waitForRequest( + (request) => editUrl.test(request.url()) && !!request.postDataJSON().sculpt, + ); + await page.mouse.click(box.x + box.width / 2 + 8, box.y + box.height / 2 - 7); + await page.mouse.move(box.x - 2, box.y + 2); + const request = await sent; + await expect.poll(() => acceptedVersion).toBeGreaterThan(0); + await expect(triangles).not.toHaveText(baseline); + + const original = request.postDataJSON(); + const remote = await page.request.post(request.url(), { + data: { + client: 'remote-editor', + base: acceptedVersion, + epoch: original.epoch, + checkpoint: true, + scene: { + ...original.scene, + parts: original.scene.parts.map((part: { id: string }) => ({ + ...part, + ...(part.id === original.sculpt.partId + ? { geometry: original.sculpt.source, name: 'Restored block' } + : {}), + })), + }, + }, + }); + expect(remote.ok()).toBe(true); + await expect(page.locator(part('Restored block'))).toBeVisible(); + const completed = page.waitForResponse((response) => response.request() === request); + finish(); + expect((await completed).ok()).toBe(true); + await expect(triangles).toHaveText(baseline); +}); diff --git a/tests/e2e/sculpt-benchmark.spec.ts b/tests/e2e/sculpt-benchmark.spec.ts new file mode 100644 index 0000000..02f331e --- /dev/null +++ b/tests/e2e/sculpt-benchmark.spec.ts @@ -0,0 +1,154 @@ +import { test, expect, type Page } from '@playwright/test'; +import { arch, cpus, release, type } from 'node:os'; +import type { BufferAttribute, Camera, Mesh } from 'three'; +import { inStore, openScene, screen } from './helpers/refine'; + +// Opt in with KITBASHER_SCULPT_VIEWPORT_BENCH=1. Each native move waits for its first +// changed draw before sending the next one, so these results exclude input queueing. +test.skip(!process.env.KITBASHER_SCULPT_VIEWPORT_BENCH, 'Opt-in viewport benchmark'); + +interface ProbeWindow extends Window { + sculptDrawTimes: number[]; +} + +async function setup(page: Page, segments: number, indexed: boolean) { + await openScene(page); + await expect(page.locator('.part-select[title="Scanned block"]')).toBeVisible(); + await page.evaluate( + async ({ segments, indexed }) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const three = await import(urls.find((url) => /\/deps\/three\.js/.test(url))!); + const { useEditor } = await import( + urls.find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))! + ); + const grid = new three.PlaneGeometry(100, 100, segments, segments); + const geometry = indexed ? grid : grid.toNonIndexed(); + const state = useEditor.getState(); + const part = { + ...state.scene.parts[0], + geometry, + name: 'Benchmark sheet', + position: [0, 55, 0], + }; + state.setScene({ ...state.scene, parts: [part] }); + }, + { segments, indexed }, + ); + await page.locator('.part-select[title="Benchmark sheet"]').click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + if (segments > 1) + await expect + .poll(() => inStore(page, (state) => !!state.scene.parts[0].geometry.boundsTree), { + timeout: 60_000, + }) + .toBe(true); + // Register capture before Sculpt's window listener consumes active stroke events. + const gpu = await installProbe(page); + await page + .getByRole('toolbar', { name: 'Assembly tools' }) + .getByRole('button', { name: 'Sculpt', exact: true }) + .click(); + return { gpu, settings: await inStore(page, (state) => state.sculpt!.settings) }; +} + +async function installProbe(page: Page) { + return page.evaluate(async () => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { partMeshes } = await import( + urls.find((url) => /\/src\/xr\/part-meshes\.ts(?:\?.*)?$/.test(url))! + ); + const { _roots } = await import(urls.find((url) => url.includes('/@react-three_fiber.js'))!); + const root = _roots.get(document.querySelector('canvas')).store.getState(); + const mesh: Mesh = partMeshes.get('block'); + const source = mesh.geometry; + const samples = ((window as unknown as ProbeWindow).sculptDrawTimes = [] as number[]); + let start = -1; + let lastVersion = 0; + let lastPosition = source.getAttribute('position'); + function onPointer(event: PointerEvent) { + if (event.buttons === 1) start = performance.now(); + } + window.addEventListener('pointerdown', onPointer, true); + window.addEventListener('pointermove', onPointer, true); + const previous = mesh.onAfterRender; + mesh.onAfterRender = function (...args) { + previous.apply(this, args); + const camera: Camera = args[2]; + const version = (this.geometry.getAttribute('position') as BufferAttribute).version; + if ( + start >= 0 && + camera === root.camera && + this.geometry !== source && + version > 0 && + (this.geometry.getAttribute('position') !== lastPosition || version > lastVersion) + ) { + samples.push(performance.now() - start); + lastPosition = this.geometry.getAttribute('position'); + lastVersion = version; + start = -1; + } + }; + const context = root.gl.getContext(); + const extension = context.getExtension('WEBGL_debug_renderer_info'); + return extension + ? (context.getParameter(extension.UNMASKED_RENDERER_WEBGL) as string) + : 'unavailable'; + }); +} + +for (const [name, segments, indexed] of [ + ['coarse', 1, true], + ['dense indexed', 707, true], + ['dense unindexed', 707, false], +] as const) { + test(`times pointer receipt to changed viewport draw on a ${name} sheet`, async ({ + page, + browser, + }, info) => { + test.setTimeout(180_000); + const { gpu, settings } = await setup(page, segments, indexed); + const warmSamples = 24; + const step = settings.radius * settings.spacing * 1.35; + const start = await screen(page, [(-step * warmSamples) / 2, 56, 0]); + const end = await screen(page, [(step * warmSamples) / 2, 56, 0]); + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + for (let sample = 0; sample <= warmSamples; sample++) { + if (sample) + await page.mouse.move(start.x + ((end.x - start.x) * sample) / warmSamples, start.y); + await page.waitForFunction( + (count) => (window as unknown as ProbeWindow).sculptDrawTimes.length >= count, + sample + 1, + { timeout: 30_000 }, + ); + } + const [firstMs, ...warmMs] = await page.evaluate( + () => (window as unknown as ProbeWindow).sculptDrawTimes, + ); + await page.mouse.up(); + await expect + .poll(() => inStore(page, (state) => state.sculpt?.past.length), { timeout: 60_000 }) + .toBe(1); + const sorted = [...warmMs].sort((a, b) => a - b); + const report = { + name, + triangles: segments * segments * 2, + indexed, + brushRadius: settings.radius, + browser: browser.version(), + os: [type(), release(), arch()].join(' '), + cpu: cpus()[0].model, + gpu, + firstMs, + warmP95Ms: sorted[Math.ceil(sorted.length * 0.95) - 1], + warmWorstMs: sorted.at(-1), + warmMs, + }; + console.log(JSON.stringify(report)); + await info.attach('sculpt-viewport.json', { + body: JSON.stringify(report, null, 2), + contentType: 'application/json', + }); + }); +} diff --git a/tests/e2e/sculpt.spec.ts b/tests/e2e/sculpt.spec.ts new file mode 100644 index 0000000..3744d77 --- /dev/null +++ b/tests/e2e/sculpt.spec.ts @@ -0,0 +1,757 @@ +import { expect, test, type Page } from '@playwright/test'; +import { BoxGeometry, PlaneGeometry } from 'three'; +import { serializeGeometry } from '../../src/core/geometry'; +import { fixture, inEditor, inStore, openScene, screen } from './helpers/refine'; +import { queueAfterPenRelease } from './helpers/sculpt'; +import { failOnBrowserErrors } from './helpers/warp-grid'; +import { readSavedScene } from './saved-scene'; + +failOnBrowserErrors(); + +const block = { + ...fixture, + parts: [ + { + ...fixture.parts[0], + name: 'Coarse block', + source: 'block.stl', + geometry: serializeGeometry(new BoxGeometry(8, 6, 4)), + }, + ], +}; + +async function openSculpt(page: Page, scene = block) { + await openScene(page, scene); + await page.locator('.part-select[title="Coarse block"]').click(); + await page.keyboard.press('1'); + await page.keyboard.press('Home'); + await page + .getByRole('toolbar', { name: 'Assembly tools' }) + .getByRole('button', { name: /^Sculpt\b/ }) + .click(); +} + +const mesh = (page: Page) => + inStore(page, (state) => { + const geometry = state.scene.parts[0].geometry; + const positions = geometry.getAttribute('position'); + let peak = -Infinity; + for (let i = 0; i < positions.count; i++) peak = Math.max(peak, positions.getZ(i)); + return { + positions: Array.from(positions.array), + indices: geometry.index ? Array.from(geometry.index.array) : null, + triangles: (geometry.index?.count ?? positions.count) / 3, + peak, + }; + }); + +async function penTap(page: Page, pressure: number) { + const point = await screen(page, [1, 0, 2]); + const session = await page.context().newCDPSession(page); + try { + const sample = { ...point, pointerType: 'pen' as const, button: 'left' as const }; + await session.send('Input.dispatchMouseEvent', { + ...sample, + type: 'mousePressed', + buttons: 1, + force: pressure, + }); + await page.evaluate( + () => new Promise((resolve) => requestAnimationFrame(() => resolve())), + ); + await session.send('Input.dispatchMouseEvent', { + ...sample, + type: 'mouseReleased', + buttons: 0, + }); + } finally { + await session.detach(); + } +} + +test('only sculpts the selected part when its surface is visible under the tip', async ({ + page, +}) => { + await openSculpt(page, { + ...block, + parts: [block.parts[0], { ...block.parts[0], id: 'cover', name: 'Cover', position: [0, 0, 6] }], + }); + const before = await mesh(page); + await penTap(page, 0.9); + await page.evaluate( + () => + new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ), + ); + expect(await mesh(page)).toEqual(before); + await page.getByRole('button', { name: 'Hide Cover' }).click(); + await penTap(page, 0.9); + await expect.poll(async () => (await mesh(page)).peak).toBeGreaterThan(before.peak); +}); + +test('commits a released stroke before a tool change in the same frame', async ({ page }) => { + await openSculpt(page); + const before = await mesh(page); + const point = await screen(page, [1, 0, 2]); + await page.evaluate(async (spot) => { + const storeUrl = performance + .getEntriesByType('resource') + .map((entry) => entry.name) + .find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))!; + const { useEditor } = await import(storeUrl); + const canvas = document.querySelector('canvas')!; + const event = { + clientX: spot.x, + clientY: spot.y, + pointerId: 42, + pointerType: 'pen', + isPrimary: true, + bubbles: true, + }; + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...event, buttons: 1, pressure: 0.8 })); + canvas.dispatchEvent(new PointerEvent('pointerup', event)); + useEditor.getState().setTool('select'); + }, point); + expect((await mesh(page)).peak).toBeGreaterThan(before.peak); +}); + +test('queues another press and mask changes while a released stroke finishes', async ({ page }) => { + await openSculpt(page); + const first = await screen(page, [-1, 0, 2]); + const second = await screen(page, [1, 0, 2]); + await page.evaluate( + ({ first, second }) => { + const canvas = document.querySelector('canvas')!; + const now = performance.now.bind(performance); + let elapsed = now(); + // Force the released-stroke path regardless of the test machine's speed. + performance.now = () => (elapsed += 8); + try { + for (const point of [first, second]) { + const pen = { + pointerId: 24, + isPrimary: true, + pointerType: 'pen', + pressure: 0.8, + bubbles: true, + clientX: point.x, + clientY: point.y, + }; + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', pen)); + } + window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); + const invert = Array.from(document.querySelectorAll('button')).find( + (button) => button.textContent?.trim() === 'Invert mask', + ); + if (!invert) throw new Error('Missing Invert mask button'); + invert.click(); + } finally { + performance.now = now; + } + }, + { first, second }, + ); + await expect + .poll(() => + inStore(page, (state) => { + const past = state.sculpt?.past ?? []; + return { + strokes: past.filter((step) => step.before.geometry !== step.after.geometry).length, + mask: state.sculpt?.mask?.every((weight) => weight === 1), + }; + }), + ) + .toEqual({ strokes: 2, mask: true }); +}); + +test('cancels a held queued press and preserves the released stroke through part edits', async ({ + page, +}) => { + await openSculpt(page); + const point = await screen(page, [1, 0, 2]); + await page.evaluate(async (point) => { + const storeUrl = performance + .getEntriesByType('resource') + .map((entry) => entry.name) + .find((url) => /\/src\/core\/store\.ts(?:\?.*)?$/.test(url))!; + const { useEditor } = await import(storeUrl); + const canvas = document.querySelector('canvas')!; + const now = performance.now.bind(performance); + let elapsed = now(); + performance.now = () => (elapsed += 8); + const pen = { + clientX: point.x, + clientY: point.y, + pointerId: 24, + isPrimary: true, + pointerType: 'pen', + pressure: 0.8, + bubbles: true, + }; + const press = () => + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); + const release = () => canvas.dispatchEvent(new PointerEvent('pointerup', pen)); + try { + press(); + release(); + press(); + document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); + release(); + for (const event of ['keydown', 'keyup']) { + document.body.dispatchEvent( + new KeyboardEvent(event, { key: ' ', code: 'Space', bubbles: true }), + ); + } + useEditor.getState().patchParts(['block'], { name: 'Renamed after release' }); + useEditor.getState().setView({ explode: 50 }); + } finally { + performance.now = now; + } + }, point); + await expect + .poll(() => + inStore(page, (state) => [ + state.sculpt?.past.length, + state.temporaryOrbit, + state.scene.parts[0].name, + state.view.explode, + ]), + ) + .toEqual([1, false, 'Renamed after release', 50]); +}); + +test('restores the committed mesh when a replayed preview is cancelled', async ({ page }) => { + await openSculpt(page); + const point = await screen(page, [1, 0, 2]); + await page.evaluate((point) => { + const canvas = document.querySelector('canvas')!; + const now = performance.now.bind(performance); + let elapsed = now(); + performance.now = () => (elapsed += 8); + const pen = { + clientX: point.x, + clientY: point.y, + isPrimary: true, + pointerType: 'pen', + pressure: 0.8, + bubbles: true, + }; + try { + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, pointerId: 40, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', { ...pen, pointerId: 40 })); + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, pointerId: 41, buttons: 1 })); + } finally { + performance.now = now; + } + }, point); + const previewState = () => + page.evaluate(async () => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { partMeshes } = await import( + urls.find((url) => /\/src\/xr\/part-meshes\.ts/.test(url))! + ); + const { useEditor } = await import(urls.find((url) => /\/src\/core\/store\.ts/.test(url))!); + const state = useEditor.getState(); + return { + strokes: state.sculpt?.past.length, + committed: partMeshes.get('block').geometry === state.scene.parts[0].geometry, + }; + }); + await expect.poll(previewState).toEqual({ strokes: 1, committed: false }); + await page.keyboard.press('Escape'); + await expect.poll(previewState).toEqual({ strokes: 1, committed: true }); +}); + +test('runs a queued undo after saving a released stroke', async ({ page }) => { + await openSculpt(page); + const before = await mesh(page); + const point = await screen(page, [1, 0, 2]); + const downloading = page.waitForEvent('download'); + await page.evaluate((point) => { + const canvas = document.querySelector('canvas')!; + const now = performance.now.bind(performance); + let elapsed = now(); + performance.now = () => (elapsed += 8); + try { + const pen = { + clientX: point.x, + clientY: point.y, + pointerId: 29, + isPrimary: true, + pointerType: 'pen', + pressure: 0.8, + bubbles: true, + }; + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', pen)); + document.querySelector('button[aria-label="Save scene"]')!.click(); + document.body.dispatchEvent( + new KeyboardEvent('keydown', { + key: 'z', + code: 'KeyZ', + ctrlKey: !navigator.platform.includes('Mac'), + metaKey: navigator.platform.includes('Mac'), + bubbles: true, + cancelable: true, + }), + ); + } finally { + performance.now = now; + } + }, point); + await downloading; + await expect.poll(() => inStore(page, (state) => state.sculpt?.future.length)).toBe(1); + expect(await mesh(page)).toEqual(before); +}); + +test('keeps Undo ahead of a mask edit queued behind Save', async ({ page }) => { + await openSculpt(page); + const before = await mesh(page); + const point = await screen(page, [1, 0, 2]); + const downloading = page.waitForEvent('download'); + await page.evaluate((point) => { + const canvas = document.querySelector('canvas')!; + const now = performance.now.bind(performance); + let elapsed = now(); + performance.now = () => (elapsed += 8); + try { + const pen = { + clientX: point.x, + clientY: point.y, + pointerId: 29, + isPrimary: true, + pointerType: 'pen', + pressure: 0.8, + bubbles: true, + }; + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', pen)); + document.querySelector('button[aria-label="Save scene"]')!.click(); + document.body.dispatchEvent( + new KeyboardEvent('keydown', { + key: 'z', + code: 'KeyZ', + ctrlKey: !navigator.platform.includes('Mac'), + metaKey: navigator.platform.includes('Mac'), + bubbles: true, + cancelable: true, + }), + ); + const invert = Array.from(document.querySelectorAll('button')).find( + (button) => button.textContent?.trim() === 'Invert mask', + ); + if (!invert) throw new Error('Missing Invert mask button'); + invert.click(); + } finally { + performance.now = now; + } + }, point); + await downloading; + await expect + .poll(() => inStore(page, (state) => state.sculpt?.mask?.every((weight) => weight === 1))) + .toBe(true); + expect(await mesh(page)).toEqual(before); +}); + +test('preserves Undo behind Save after leaving Sculpt', async ({ page }) => { + await openSculpt(page); + const before = await mesh(page); + const point = await screen(page, [1, 0, 2]); + const downloading = page.waitForEvent('download'); + await page.evaluate(async (point) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { useEditor } = await import(urls.find((url) => /\/src\/core\/store\.ts/.test(url))!); + const canvas = document.querySelector('canvas')!; + const now = performance.now.bind(performance); + let elapsed = now(); + performance.now = () => (elapsed += 8); + try { + const pen = { + clientX: point.x, + clientY: point.y, + pointerId: 29, + isPrimary: true, + pointerType: 'pen', + pressure: 0.8, + bubbles: true, + }; + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', pen)); + useEditor.getState().setTool('select'); + document.querySelector('button[aria-label="Save scene"]')!.click(); + document.body.dispatchEvent( + new KeyboardEvent('keydown', { + key: 'z', + code: 'KeyZ', + ctrlKey: !navigator.platform.includes('Mac'), + metaKey: navigator.platform.includes('Mac'), + bubbles: true, + cancelable: true, + }), + ); + } finally { + performance.now = now; + } + }, point); + await downloading; + await expect.poll(() => inStore(page, (state) => state.tool)).toBe('select'); + await expect.poll(() => inStore(page, (state) => state.future.length)).toBe(1); + await expect.poll(() => mesh(page)).toEqual(before); +}); + +test('cancels a held press queued behind a busy save after the released stroke detaches', async ({ + page, +}) => { + await openSculpt(page); + const point = await screen(page, [1, 0, 2]); + await page.evaluate(async (point) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { useEditor, afterReleasedSculpt } = await import( + urls.find((url) => /\/src\/core\/store\.ts/.test(url))! + ); + const canvas = document.querySelector('canvas')!; + const now = performance.now.bind(performance); + let elapsed = now(); + const pen = { + clientX: point.x, + clientY: point.y, + pointerType: 'pen', + isPrimary: true, + pressure: 0.8, + bubbles: true, + }; + performance.now = () => (elapsed += 8); + try { + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, pointerId: 40, buttons: 1 })); + canvas.dispatchEvent(new PointerEvent('pointerup', { ...pen, pointerId: 40 })); + afterReleasedSculpt(() => useEditor.getState().setBusy('Preparing scene file…')); + canvas.dispatchEvent(new PointerEvent('pointerdown', { ...pen, pointerId: 41, buttons: 1 })); + } finally { + performance.now = now; + } + }, point); + await expect + .poll(() => inStore(page, (state) => [state.busy, state.sculpt?.past.length])) + .toEqual(['Preparing scene file…', 1]); + await page.keyboard.press('Escape'); + await page.evaluate(async (point) => { + const urls = performance.getEntriesByType('resource').map((entry) => entry.name); + const { useEditor, afterReleasedSculpt } = await import( + urls.find((url) => /\/src\/core\/store\.ts/.test(url))! + ); + document.querySelector('canvas')!.dispatchEvent( + new PointerEvent('pointerup', { + clientX: point.x, + clientY: point.y, + pointerType: 'pen', + pointerId: 41, + isPrimary: true, + bubbles: true, + }), + ); + afterReleasedSculpt(() => + useEditor.getState().patchParts(['block'], { name: 'Queue settled' }), + ); + useEditor.getState().setBusy(null); + }, point); + await expect + .poll(() => inStore(page, (state) => [state.scene.parts[0].name, state.sculpt?.past.length])) + .toEqual(['Queue settled', 1]); +}); + +for (const queueUndo of [false, true]) { + test( + queueUndo + ? 'runs Undo after Free Transform closes when both follow a released stroke' + : 'takes the free-transform baseline after a released stroke commits', + async ({ page }) => { + await openSculpt(page); + const before = await mesh(page); + const point = await screen(page, [1, 0, 2]); + await queueAfterPenRelease(page, point, [ + { key: 'G', code: 'KeyG', shiftKey: true }, + ...(queueUndo ? [{ key: 'z', code: 'KeyZ', ctrlKey: true }] : []), + ]); + await expect(page.locator('.free-transform-prompt')).toBeVisible(); + const sculpted = await mesh(page); + expect(sculpted.triangles).toBeGreaterThan(before.triangles); + await page.keyboard.press('Escape'); + await expect.poll(() => inStore(page, (state) => Boolean(state.freeTransform))).toBe(false); + if (queueUndo) { + await expect.poll(() => mesh(page)).toEqual(before); + expect(await inStore(page, (state) => [state.past.length, state.future.length])).toEqual([ + 0, 1, + ]); + await page.keyboard.press('ControlOrMeta+Shift+Z'); + await expect.poll(() => mesh(page)).toEqual(sculpted); + } else { + expect(await mesh(page)).toEqual(sculpted); + } + }, + ); +} + +test('starts a fresh rotation preview after cancelling a queued move on the same mesh', async ({ + page, +}) => { + await openSculpt(page); + const point = await screen(page, [1, 0, 2]); + const pose = () => + inStore(page, (state) => { + const { position, quaternion } = state.scene.parts[0]; + return { position, quaternion }; + }); + const before = await pose(); + const prompt = page.locator('.free-transform-prompt'); + await page.mouse.move(point.x, point.y); + await queueAfterPenRelease(page, point, [ + { key: 'G', code: 'KeyG', shiftKey: true }, + { key: 'R', code: 'KeyR', shiftKey: true }, + ]); + await expect(prompt).toContainText('Free move'); + await page.mouse.move(point.x + 40, point.y + 15); + await expect.poll(pose).not.toEqual(before); + await page.keyboard.press('Escape'); + await expect(prompt).toContainText('Free rotation'); + expect(await pose()).toEqual(before); + await page.mouse.move(point.x + 65, point.y + 30); + await expect.poll(async () => (await pose()).quaternion).not.toEqual(before.quaternion); + await page.keyboard.press('Escape'); + await expect(prompt).toHaveCount(0); + expect(await pose()).toEqual(before); +}); + +test('discards queued commands when a new scene replaces a free-transform preview', async ({ + page, +}) => { + await openSculpt(page); + const point = await screen(page, [1, 0, 2]); + await queueAfterPenRelease(page, point, [ + { key: 'G', code: 'KeyG', shiftKey: true }, + { key: 'E', code: 'KeyE', shiftKey: true, ctrlKey: true }, + ]); + const prompt = page.locator('.free-transform-prompt'); + await expect(prompt).toBeVisible(); + await inEditor(page, ({ useEditor }) => { + const state = useEditor.getState(); + state.setScene({ ...state.scene, name: 'Replacement' }); + }); + await expect(prompt).toHaveCount(0); + expect(await inStore(page, (state) => [state.scene.name, state.modal])).toEqual([ + 'Replacement', + null, + ]); +}); + +test('discards queued Undo if a scene update interrupts the released stroke before commit', async ({ + page, +}) => { + await openSculpt(page); + const point = await screen(page, [1, 0, 2]); + await inEditor(page, ({ useEditor }) => { + useEditor.getState().renameScene('Earlier edit'); + const interrupt = (event: KeyboardEvent) => { + if (event.code !== 'Pause') return; + window.removeEventListener('keydown', interrupt); + const state = useEditor.getState(); + state.receiveScene({ + ...state.scene, + parts: [{ ...state.scene.parts[0], position: [2, 0, 0] }], + }); + }; + window.addEventListener('keydown', interrupt); + }); + await queueAfterPenRelease(page, point, [ + { key: 'z', code: 'KeyZ', ctrlKey: true }, + { key: 'Pause', code: 'Pause' }, + ]); + expect( + await inStore(page, (state) => [ + state.scene.name, + state.scene.parts[0].position, + state.past.length, + state.future.length, + ]), + ).toEqual(['Earlier edit', [2, 0, 0], 1, 0]); +}); + +test('fills the path of a fast small-brush pen sweep in one undo step', async ({ page }) => { + await openSculpt(page, { + ...block, + parts: [ + { + ...block.parts[0], + geometry: serializeGeometry(new PlaneGeometry(8, 6, 160, 120).translate(0, 0, 2)), + }, + ], + }); + const radius = page.getByRole('spinbutton', { name: 'Radius', exact: true }); + await radius.fill('0.12'); + await radius.press('Enter'); + const start = await screen(page, [-2, 0, 2]); + const end = await screen(page, [2, 0, 2]); + await page.evaluate( + ({ start, end }) => { + const canvas = document.querySelector('canvas')!; + const pen = { + pointerId: 17, + isPrimary: true, + pointerType: 'pen', + pressure: 0.8, + bubbles: true, + }; + canvas.dispatchEvent( + new PointerEvent('pointerdown', { ...pen, clientX: start.x, clientY: start.y, buttons: 1 }), + ); + canvas.dispatchEvent( + new PointerEvent('pointermove', { ...pen, clientX: end.x, clientY: end.y, buttons: 1 }), + ); + canvas.dispatchEvent( + new PointerEvent('pointerup', { ...pen, clientX: end.x, clientY: end.y }), + ); + }, + { start, end }, + ); + await expect + .poll(() => + inStore(page, (state) => { + const positions = state.scene.parts[0].geometry.getAttribute('position'); + const covered = new Set(); + for (let i = 0; i < positions.count; i++) { + const x = positions.getX(i); + if (x >= -2 && x < 2 && positions.getZ(i) > 2 + 1e-5) + covered.add(Math.floor((x + 2) * 10)); + } + return [covered.size, state.sculpt?.past.length]; + }), + ) + .toEqual([40, 1]); +}); + +test('draws into a coarse face with pen pressure and undoes topology with displacement', async ({ + page, +}) => { + await openSculpt(page); + const before = await mesh(page); + await penTap(page, 0.25); + await expect.poll(async () => (await mesh(page)).peak).toBeGreaterThan(before.peak); + const light = await mesh(page); + expect(light.triangles).toBeGreaterThan(before.triangles); + await page.keyboard.press('ControlOrMeta+z'); + await expect.poll(() => mesh(page)).toEqual(before); + await penTap(page, 0.9); + await expect.poll(async () => (await mesh(page)).peak).toBeGreaterThan(light.peak); + const heavy = await mesh(page); + await page.keyboard.press('ControlOrMeta+z'); + await expect.poll(() => mesh(page)).toEqual(before); + await page.keyboard.press('ControlOrMeta+Shift+z'); + await expect.poll(() => mesh(page)).toEqual(heavy); +}); + +test('cancels an active stroke and reopens the completed stroke from disk', async ({ page }) => { + await openSculpt(page); + const before = await mesh(page); + const point = await screen(page, [1, 0, 2]); + await page.mouse.move(point.x, point.y); + await page.mouse.down(); + await page.mouse.move(point.x + 12, point.y, { steps: 3 }); + await expect + .poll(() => + page.evaluate(async () => { + const url = performance + .getEntriesByType('resource') + .map((entry) => entry.name) + .find((url) => /\/src\/xr\/part-meshes\.ts(?:\?.*)?$/.test(url))!; + const { partMeshes } = await import(url); + const geometry = partMeshes.get('block').geometry; + return Math.min( + geometry.drawRange.count, + geometry.index?.count ?? geometry.getAttribute('position').count, + ); + }), + ) + .toBeGreaterThan(before.triangles * 3); + expect(await mesh(page)).toEqual(before); + await page.keyboard.press('Escape'); + await page.mouse.up(); + expect(await mesh(page)).toEqual(before); + expect(await inStore(page, (state) => state.sculpt?.past.length)).toBe(0); + await penTap(page, 0.8); + await expect.poll(async () => (await mesh(page)).triangles).toBeGreaterThan(before.triangles); + const completed = await mesh(page); + const downloading = page.waitForEvent('download'); + await page.getByRole('button', { name: 'Save scene', exact: true }).click(); + const file = await readSavedScene((await (await downloading).path())!); + const oldGeometry = await inStore(page, (state) => state.scene.parts[0].geometry.uuid); + await page.getByLabel('Open Kitbasher scene').setInputFiles({ + name: 'sculpt.kitbash', + mimeType: 'application/octet-stream', + buffer: file.bytes, + }); + await page.getByRole('button', { name: 'Open scene', exact: true }).click(); + await expect + .poll(() => inStore(page, (state) => state.scene.parts[0].geometry.uuid)) + .not.toBe(oldGeometry); + await expect.poll(() => mesh(page)).toEqual(completed); +}); + +test('a fully inverted mask protects the coarse surface until cleared', async ({ page }) => { + await openSculpt(page); + const before = await mesh(page); + await page.getByRole('button', { name: 'Mask', exact: true }).click(); + await page.getByRole('button', { name: /invert mask/i }).click(); + await page.getByRole('button', { name: 'Draw', exact: true }).click(); + await penTap(page, 0.9); + expect(await mesh(page)).toEqual(before); + await page.getByRole('button', { name: 'Mask', exact: true }).click(); + await page.getByRole('button', { name: /clear mask/i }).click(); + await page.getByRole('button', { name: 'Draw', exact: true }).click(); + await penTap(page, 0.9); + await expect.poll(async () => (await mesh(page)).peak).toBeGreaterThan(before.peak); +}); + +test('mask paint subdivides without displacement and restores weights with undo and redo', async ({ + page, +}) => { + await openSculpt(page); + const before = await mesh(page); + const weights = () => inStore(page, (state) => Array.from(state.sculpt?.mask ?? [])); + await page.getByRole('button', { name: 'Mask', exact: true }).click(); + await penTap(page, 0.8); + await expect.poll(async () => (await weights()).some((weight) => weight > 0)).toBe(true); + const painted = await mesh(page); + expect(painted.triangles).toBeGreaterThan(before.triangles); + expect(painted.peak).toEqual(before.peak); + const protection = await weights(); + await page.keyboard.press('ControlOrMeta+z'); + await expect.poll(() => mesh(page)).toEqual(before); + expect(await weights()).toEqual([]); + await page.keyboard.press('ControlOrMeta+Shift+z'); + await expect.poll(() => mesh(page)).toEqual(painted); + expect(await weights()).toEqual(protection); +}); + +test('applies Clay Buildup and Inflate and keeps their falloff settings independent', async ({ + page, +}) => { + await openSculpt(page); + const before = await mesh(page); + const falloff = page.getByRole('combobox', { name: 'Falloff' }); + await page.getByText('Advanced brush settings', { exact: true }).click(); + await page.getByRole('button', { name: 'Clay Buildup', exact: true }).click(); + await falloff.selectOption('hard'); + await penTap(page, 0.9); + await expect.poll(async () => (await mesh(page)).peak).toBeGreaterThan(before.peak); + await page.keyboard.press('ControlOrMeta+z'); + await expect.poll(() => mesh(page)).toEqual(before); + await page.getByRole('button', { name: 'Inflate/Deflate', exact: true }).click(); + await expect(falloff).toHaveValue('soft'); + await penTap(page, 0.9); + await expect.poll(async () => (await mesh(page)).peak).toBeGreaterThan(before.peak); + await page.getByRole('button', { name: 'Clay Buildup', exact: true }).click(); + await expect(falloff).toHaveValue('hard'); + await page.getByRole('button', { name: 'Reset brush settings' }).click(); + await expect(falloff).toHaveValue('soft'); +}); diff --git a/tests/unit/history-budget.test.ts b/tests/unit/history-budget.test.ts index 4d71a44..b20aa41 100644 --- a/tests/unit/history-budget.test.ts +++ b/tests/unit/history-budget.test.ts @@ -30,6 +30,10 @@ const sceneOf = (...geometries: BufferGeometry[]): SceneDocument => ({ }); const tiny = vi.hoisted(() => ({ on: false })); +vi.mock('../../src/core/sculpt-session', async (original) => ({ + ...(await original()), + sculptHistoryBytes: 1024, +})); vi.mock('../../src/core/history-budget', async (original) => { const actual = await original(); return { @@ -100,6 +104,37 @@ describe('history budget', () => { expect(useEditor.getState().historyTrimNotified).toBe(false); }); + it('preserves unrelated undo steps when they exceed the Sculpt mesh limit', () => { + const previous = mesh(300); + const sculptable = new BoxGeometry(); + const scene = sceneOf(previous, sculptable); + const store = useEditor.getState; + store().setScene(scene); + store().patchParts(['p0'], { geometry: mesh(3) }); + const beforeStroke = store().scene; + store().select('p1'); + expect(store().startSculpt()).toBe(true); + expect( + store().commitSculpt({ + partId: 'p1', + source: sculptable, + epoch: store().sceneEpoch, + position: [0, 0, 0], + quaternion: [0, 0, 0, 1], + scale: [1, 1, 1], + geometry: sculptable.clone(), + mask: null, + }), + ).toBe(true); + + expect(store().past).toEqual([scene, beforeStroke]); + expect(store().historyTrimNotified).toBe(false); + store().setTool('select'); + store().undo(); + store().undo(); + expect(store().scene.parts[0].geometry).toBe(previous); + }); + it('keeps undo steps when Cut retains the removed meshes in the new clipboard', () => { tiny.on = true; useEditor.getState().setScene(sceneOf(mesh(30), mesh(30))); @@ -111,7 +146,7 @@ describe('history budget', () => { expect(useEditor.getState().past).toHaveLength(3); }); - it('trims the shared document history over budget and frees dropped meshes', () => { + it('trims the shared document history and frees adopted uploads when dropped', () => { const doc = new SharedDocument(1024 * 1024); doc.replace(sceneOf(mesh(100_000))); const uuids: string[] = []; @@ -119,6 +154,7 @@ describe('history budget', () => { const before = doc.scene; const geometry = mesh(100_000 + i); uuids.push(geometry.uuid); + doc.addMesh(geometry.uuid, geometry); useEditor.setState((state) => ({ scene: { ...before, parts: [part('p0', geometry)] }, revision: state.revision + 1, diff --git a/tests/unit/sculpt-benchmark.test.ts b/tests/unit/sculpt-benchmark.test.ts new file mode 100644 index 0000000..81c4b5b --- /dev/null +++ b/tests/unit/sculpt-benchmark.test.ts @@ -0,0 +1,146 @@ +import { it, expect } from 'vitest'; +import { writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { + DoubleSide, + Matrix4, + Mesh, + MeshBasicMaterial, + PlaneGeometry, + Raycaster, + Vector3, +} from 'three'; +import { MeshBVH } from 'three-mesh-bvh'; +import { SculptMesh } from '../../src/core/sculpt-mesh'; + +const enabled = process.env.KITBASHER_SCULPT_BENCH; +const timed = (work: () => T) => { + const start = performance.now(); + const result = work(); + return { result, ms: performance.now() - start }; +}; + +it.skipIf(!enabled)('profiles coarse and dense sculpt strokes', () => { + const metrics = []; + for (const segments of [1, 707]) { + const source = new PlaneGeometry(100, 100, segments, segments); + source.boundsTree = new MeshBVH(source, { indirect: true }); + const initial = timed(() => new SculptMesh(source, new Matrix4())); + const { result: draft } = initial; + const prepare = timed(() => draft.prepare()); + const mesh = new Mesh(draft.geometry, new MeshBasicMaterial({ side: DoubleSide })); + const raycast = new Raycaster(); + raycast.firstHitOnly = true; + const durations: number[] = []; + for (let dab = 0; dab < 30; dab++) { + const result = timed(() => { + raycast.ray.origin.set(-5 + dab / 3, 0, 30); + raycast.ray.direction.set(0, 0, -1); + const hits: import('three').Intersection[] = []; + draft.raycast(raycast, mesh, hits); + const hit = hits[0]; + if (!hit?.face || hit.faceIndex == null) return false; + return draft.dab({ + brush: 'draw', + point: hit.point, + normal: hit.face.normal, + face: hit.faceIndex, + radius: 3, + strength: 0.2, + detail: 0.5, + minEdge: 0.05, + falloff: 'soft', + }); + }); + expect(result.result).toBe(true); + durations.push(result.ms); + } + const finish = timed(() => draft.finish()); + const geometry = finish.result!; + const bytes = + geometry.index!.array.byteLength + + Object.values(geometry.attributes).reduce( + (sum, attribute) => sum + attribute.array.byteLength, + 0, + ); + const warm = durations.slice(1).sort((a, b) => a - b); + metrics.push({ + triangles: source.index!.count / 3, + setupMs: initial.ms, + prepareMs: prepare.ms, + firstDabMs: durations[0], + warmP95Ms: warm[Math.floor(warm.length * 0.95)], + warmWorstMs: warm.at(-1), + finishMs: finish.ms, + committedMeshBytes: bytes, + }); + geometry.dispose(); + draft.geometry.dispose(); + mesh.material.dispose(); + source.dispose(); + } + writeFileSync( + join(tmpdir(), 'kitbasher-sculpt-benchmark.json'), + JSON.stringify(metrics, null, 2), + ); +}); + +it.skipIf(!enabled)('profiles cooperative wide dabs on a dense mesh', () => { + const segments = 500; + const source = new PlaneGeometry(100, 100, segments, segments); + source.boundsTree = new MeshBVH(source, { indirect: true }); + const measurements = []; + for (const brush of ['mask', 'draw'] as const) { + const draft = new SculptMesh(source, new Matrix4()); + const preparation = timed(() => draft.prepare()); + const job = draft.dabWork({ + brush, + point: new Vector3(), + normal: new Vector3(0, 0, 1), + face: 2 * ((segments / 2) * segments + segments / 2), + radius: 80, + strength: 1, + detail: 0, + minEdge: 0.04, + falloff: 'hard', + }); + let changed = false; + let done = false; + const slices: number[] = []; + while (!done) { + const { ms } = timed(() => { + const deadline = performance.now() + 6; + do { + const result = job.next(); + if (result.done) { + done = true; + changed = result.value; + } + } while (!done && performance.now() < deadline); + }); + slices.push(ms); + } + expect(changed).toBe(true); + expect(slices.length).toBeGreaterThan(1); + const committed = timed(() => draft.finish()); + const sorted = [...slices].sort((a, b) => a - b); + measurements.push({ + brush, + triangles: source.index!.count / 3, + prepareMs: preparation.ms, + totalDabMs: slices.reduce((sum, value) => sum + value, 0), + slices: slices.length, + sliceP95Ms: sorted[Math.ceil(sorted.length * 0.95) - 1], + sliceWorstMs: sorted.at(-1), + commitMs: committed.ms, + }); + committed.result?.dispose(); + draft.geometry.dispose(); + } + source.dispose(); + writeFileSync( + join(tmpdir(), 'kitbasher-sculpt-wide.json'), + JSON.stringify(measurements, null, 2), + ); +}); diff --git a/tests/unit/sculpt-mesh.test.ts b/tests/unit/sculpt-mesh.test.ts new file mode 100644 index 0000000..c20659c --- /dev/null +++ b/tests/unit/sculpt-mesh.test.ts @@ -0,0 +1,352 @@ +import { + BufferAttribute, + BufferGeometry, + Matrix4, + Mesh, + MeshBasicMaterial, + PlaneGeometry, + Raycaster, + Vector3, + type Intersection, +} from 'three'; +import { MeshBVH } from 'three-mesh-bvh'; +import { describe, expect, it } from 'vitest'; +import { SculptMesh, type SculptDab } from '../../src/core/sculpt-mesh'; + +const identity = new Matrix4(); +const dab = (point: Vector3, settings: Partial = {}): SculptDab => ({ + point, + normal: new Vector3(0, 0, 1), + face: 0, + radius: 0.8, + strength: 1, + detail: 0.6, + minEdge: 0.04, + brush: 'draw', + falloff: 'soft', + ...settings, +}); + +function mesh(positions: number[], corners?: number[]) { + const geometry = new BufferGeometry(); + geometry.setAttribute('position', new BufferAttribute(Float32Array.from(positions), 3)); + if (corners) geometry.setIndex(corners); + geometry.computeVertexNormals(); + return geometry; +} + +describe('sculpt mesh', () => { + it('protects the full footprint of a large mask on a dense surface', () => { + const segments = 200; + const source = new PlaneGeometry(100, 100, segments, segments); + const draft = new SculptMesh(source, identity); + expect( + draft.dab( + dab(new Vector3(), { + face: 2 * ((segments / 2) * segments + segments / 2), + radius: 30, + brush: 'mask', + falloff: 'hard', + detail: 0, + }), + ), + ).toBe(true); + const positions = source.getAttribute('position'); + const weights = draft.getMask(); + for (let i = 0; i < positions.count; i++) + expect(weights[i]).toBe(Math.hypot(positions.getX(i), positions.getY(i)) < 30 ? 1 : 0); + }); + it('updates area-weighted normals across a dense draw footprint', () => { + const source = new PlaneGeometry(20, 20, 80, 80); + const draft = new SculptMesh(source, identity); + expect(draft.dab(dab(new Vector3(), { face: 6480, radius: 8, minEdge: 100 }))).toBe(true); + const output = draft.finish()!; + const actual = output.getAttribute('normal'); + const reference = output.clone(); + reference.computeVertexNormals(); + const expected = reference.getAttribute('normal'); + const difference = new Vector3(); + const normal = new Vector3(); + let maxError = 0; + for (let vertex = 0; vertex < actual.count; vertex++) { + difference + .fromBufferAttribute(actual, vertex) + .sub(normal.fromBufferAttribute(expected, vertex)); + maxError = Math.max(maxError, difference.length()); + } + expect(maxError).toBeLessThan(1e-6); + }); + + it('adds detail under a small dab in a coarse face, keeping original positions and winding', () => { + const source = mesh([-4, -3, 0, 4, -3, 0, 0, 4, 0], [0, 1, 2]); + const draft = new SculptMesh(source, identity); + expect(draft.dab(dab(new Vector3(0.3, 0.4, 0)))).toBe(true); + const output = draft.finish()!; + const positions = output.getAttribute('position'); + expect(positions.count).toBeGreaterThan(3); + expect(Array.from(positions.array.slice(0, 9))).toEqual( + Array.from(source.getAttribute('position').array), + ); + expect( + Array.from({ length: positions.count }, (_, vertex) => positions.getZ(vertex)).some( + (z) => z > 0, + ), + ).toBe(true); + const meshObject = new Mesh(draft.geometry, new MeshBasicMaterial()); + const caster = new Raycaster(new Vector3(0.3, 0.4, 3), new Vector3(0, 0, -1)); + expect(caster.intersectObject(meshObject)[0]?.point.z).toBeGreaterThan(0); + expect(source.index?.count).toBe(3); + }); + + it('splits both sides of an unindexed color and normal seam at matching positions', () => { + const source = mesh([-4, 0, 0, 4, 0, 0, 0, 4, 0, 4, 0, 0, -4, 0, 0, 0, -4, 2]); + source.setAttribute( + 'color', + new BufferAttribute( + Float32Array.from([1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1]), + 3, + ), + ); + const draft = new SculptMesh(source, identity); + expect(draft.dab(dab(new Vector3(0, 0, 0), { brush: 'mask' }))).toBe(true); + const output = draft.finish()!; + const pos = output.getAttribute('position'); + const color = output.getAttribute('color'); + const normal = output.getAttribute('normal'); + const midpoint = [...Array(pos.count).keys()].filter( + (v) => pos.getX(v) === 0 && pos.getY(v) === 0, + ); + expect(midpoint).toHaveLength(2); + expect(color.getX(midpoint[0])).not.toBe(color.getX(midpoint[1])); + expect(normal.getY(midpoint[0])).not.toBe(normal.getY(midpoint[1])); + expect(draft.getMask()[midpoint[0]]).toBe(draft.getMask()[midpoint[1]]); + expect(output.getAttribute('sculptMask')).toBeUndefined(); + }); + + it('keeps protection and pending topology unchanged when a sculpt dab has no effect', () => { + const source = mesh([-4, -3, 0, 4, -3, 0, 0, 4, 0]); + const draft = new SculptMesh(source, identity, new Float32Array([1, 1, 1])); + expect(draft.dab(dab(new Vector3(0, 0, 0)))).toBe(false); + expect(draft.finish()).toBeNull(); + expect(draft.getMask()).toEqual(new Float32Array([1, 1, 1])); + expect(draft.geometry.drawRange.count).toBe(3); + }); + + it('protects points proportionally and applies overlapping symmetry once in world units', () => { + const source = mesh([0, 0, 0, 1, 0, 0, 0, 1, 0], [0, 1, 2]); + const transform = new Matrix4().makeScale(2, 3, 5).setPosition(4, 8, 1); + const point = new Vector3(4, 8, 1); + const settings = { minEdge: 100, mirror: { point, normal: new Vector3(0, 0, 1), face: 0 } }; + const direct = new SculptMesh(source, transform); + const masked = new SculptMesh(source, transform, new Float32Array([0.5, 0, 0])); + direct.dab(dab(point, { minEdge: 100 })); + masked.dab(dab(point, settings)); + expect(masked.finish()!.getAttribute('position').getZ(0)).toBeCloseTo( + direct.finish()!.getAttribute('position').getZ(0) / 2, + ); + }); + + it('ignores a nearby disconnected shell', () => { + const source = mesh([ + -2, -2, 0, 2, -2, 0, 0, 2, 0, -2, -2, -0.000001, 2, -2, -0.000001, 0, 2, -0.000001, + ]); + const draft = new SculptMesh(source, identity); + expect(draft.dab(dab(new Vector3(0, 0, 0)))).toBe(true); + const output = draft.finish()!; + const corners = output.getIndex()!; + expect([corners.getX(3), corners.getX(4), corners.getX(5)]).toEqual([3, 4, 5]); + }); + + it.each([false, true])( + 'keeps separate shells independent at a coincident corner (indexed: %s)', + (indexed) => { + const source = mesh( + [0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, -2, 0, 0, 0, -2, 0], + indexed ? [0, 1, 2, 3, 4, 5] : undefined, + ); + const draft = new SculptMesh(source, identity); + expect(draft.dab(dab(new Vector3(), { minEdge: 100 }))).toBe(true); + const positions = draft.finish()!.getAttribute('position'); + expect(positions.getZ(0)).toBeGreaterThan(0); + expect(positions.getZ(3)).toBe(0); + }, + ); + + it.each(['draw', 'mask'] as const)( + 'isolates a shared indexed corner during a %s dab', + (brush) => { + const source = mesh([0, 0, 0, 2, 0, 0, 0, 2, 0, -2, 0, 0, 0, -2, 0], [0, 1, 2, 0, 3, 4]); + source.addGroup(0, 3, 0); + source.addGroup(3, 3, 1); + source.setAttribute( + 'color', + new BufferAttribute(Uint8Array.from([127, 0, 0, 0, 0]), 1, true), + ); + const draft = new SculptMesh(source, identity, Float32Array.from([0.25, 0, 0, 0, 0])); + expect(draft.dab(dab(new Vector3(), { brush, minEdge: 100 }))).toBe(true); + const output = draft.finish()!; + const first = output.index!.getX(0); + const second = output.index!.getX(3); + expect(first).not.toBe(second); + expect(output.groups).toEqual(source.groups); + expect(output.getAttribute('color').array[second]).toBe(127); + expect(output.getAttribute('position').getZ(second)).toBe(0); + expect(draft.getMask()[second]).toBe(0.25); + if (brush === 'draw') expect(output.getAttribute('position').getZ(first)).toBeGreaterThan(0); + else expect(draft.getMask()[first]).toBe(1); + expect(Array.from(source.index!.array)).toEqual([0, 1, 2, 0, 3, 4]); + }, + ); + + it('reuses source ray acceleration and picks live triangle positions after splits', () => { + const source = mesh([-4, -3, 0, 4, -3, 0, 0, 4, 0], [0, 1, 2]); + source.boundsTree = new MeshBVH(source, { indirect: true, targetLeafSize: 1 }); + const draft = new SculptMesh(source, identity); + const point = new Vector3(0.3, 0.4, 0); + draft.dab(dab(point)); + const object = new Mesh(draft.geometry, new MeshBasicMaterial()); + const caster = new Raycaster(point.clone().setZ(3), new Vector3(0, 0, -1)); + caster.firstHitOnly = true; + const hits: Intersection[] = []; + draft.raycast(caster, object, hits); + expect(hits).toHaveLength(1); + expect(hits[0].point.z).toBeGreaterThan(0); + expect(hits[0].faceIndex).toBeLessThan(object.geometry.drawRange.count / 3); + expect(hits[0].point.z).toBeCloseTo(caster.intersectObject(object)[0].point.z); + }); + + it('refits an immutable committed picking tree after deformation without subdivision', () => { + const source = mesh([0, 0, 0, 1, 0, 0, 0, 1, 0, 5, 5, 0, 6, 5, 0, 5, 6, 0], [0, 1, 2, 3, 4, 5]); + source.boundsTree = new MeshBVH(source, { indirect: true, targetLeafSize: 1 }); + const point = new Vector3(0, 0, 0); + const draft = new SculptMesh(source, identity); + expect(draft.dab(dab(point, { minEdge: 100 }))).toBe(true); + const output = draft.finish()!; + const ray = new Raycaster(new Vector3(0.05, 0.05, 1), new Vector3(0, 0, -1)).ray; + expect((output.boundsTree as MeshBVH).raycastFirst(ray)?.point.z).toBeGreaterThan(0); + expect((source.boundsTree as MeshBVH).raycastFirst(ray)?.point.z).toBe(0); + expect(output.index?.count).toBe(6); + }); + + it('keeps the original grab weights across a long drag and after refinement', () => { + const source = mesh([-4, -3, 0, 4, -3, 0, 0, 4, 0], [0, 1, 2]); + const draft = new SculptMesh(source, identity); + const point = new Vector3(0.3, 0.4, 0); + const grab = dab(point, { brush: 'grab', grab: new Vector3(1.5, 0, 0) }); + expect(draft.dab(grab)).toBe(true); + const first = draft.finish()!.getAttribute('position'); + expect(draft.dab(grab)).toBe(true); + const second = draft.finish()!.getAttribute('position'); + expect(second.count).toBe(first.count); + expect(second.array).not.toEqual(first.array); + }); + + it('softens, erases, inverts, and clears mask values without committing dense geometry', () => { + const source = mesh([0, 0, 0, 1, 0, 0, 0, 1, 0], [0, 1, 2]); + const draft = new SculptMesh(source, identity, new Float32Array([1, 0, 0])); + const settings = dab(new Vector3(), { brush: 'mask', minEdge: 100, strength: 0.25 }); + expect(draft.dab({ ...settings, softenMask: true })).toBe(true); + expect(draft.getMask()).toEqual(new Float32Array([0.75, 0, 0])); + expect(draft.dab({ ...settings, inverted: true })).toBe(true); + expect(draft.getMask()).toEqual(new Float32Array([0.5, 0, 0])); + expect(draft.invertMask()).toBe(true); + expect(draft.getMask()).toEqual(new Float32Array([0.5, 1, 1])); + expect(draft.clearMask()).toBe(true); + expect(draft.getMask()).toEqual(new Float32Array(3)); + expect(draft.finish()).toBeNull(); + }); + + it('can refine and sculpt a previously subdivided mask commit', () => { + const source = mesh([-4, -3, 0, 4, -3, 0, 0, 4, 0], [0, 1, 2]); + const paint = new SculptMesh(source, identity); + expect(paint.dab(dab(new Vector3(0.3, 0.4, 0), { brush: 'mask', strength: 0.4 }))).toBe(true); + const painted = paint.finish()!; + const next = new SculptMesh(painted, identity, paint.getMask()); + const point = new Vector3(0.3, 0.4, 0); + const object = new Mesh(next.geometry, new MeshBasicMaterial()); + const caster = new Raycaster(point.clone().setZ(3), new Vector3(0, 0, -1)); + const hit = caster.intersectObject(object)[0]; + expect(next.dab(dab(point, { face: hit.faceIndex!, detail: 1 }))).toBe(true); + expect(next.finish()!.index!.count).toBeGreaterThanOrEqual(painted.index!.count); + expect(paint.getMask()).toHaveLength(painted.getAttribute('position').count); + }); + + it('cuts a pinched groove and uses inverted depth for a pinched ridge', () => { + const source = mesh([0, 0, 0, 0.5, 0, 0, 0, 0.5, 0], [0, 1, 2]); + const settings = dab(new Vector3(), { + brush: 'crease', + pinch: 1, + tangent: new Vector3(0, 1, 0), + minEdge: 100, + }); + const groove = new SculptMesh(source, identity); + const ridge = new SculptMesh(source, identity); + expect(groove.dab(settings)).toBe(true); + expect(ridge.dab({ ...settings, inverted: true })).toBe(true); + const cut = groove.finish()!.getAttribute('position'); + const raised = ridge.finish()!.getAttribute('position'); + expect(cut.getX(1)).toBeLessThan(0.5); + expect(raised.getX(1)).toBe(cut.getX(1)); + expect(cut.getZ(0)).toBeLessThan(0); + expect(raised.getZ(0)).toBe(-cut.getZ(0)); + }); + + it('builds clay toward a surface plane and inflates using an individual vertex normal', () => { + const source = mesh([0, 0, 0, 0.5, 0, 0, 0, 0.5, 0, -0.5, 0, 0.5], [0, 1, 2, 0, 2, 3]); + const clay = new SculptMesh(source, identity); + const inflate = new SculptMesh(source, identity); + const settings = dab(new Vector3(), { minEdge: 100 }); + expect(clay.dab({ ...settings, brush: 'clay' })).toBe(true); + expect(inflate.dab({ ...settings, brush: 'inflate' })).toBe(true); + const buildup = clay.finish()!.getAttribute('position'); + const inflated = inflate.finish()!.getAttribute('position'); + expect(buildup.getZ(0)).toBeGreaterThan(0); + expect(buildup.getX(0)).toBe(0); + expect(inflated.getX(0)).toBeGreaterThan(0); + expect(inflated.getZ(0)).toBeGreaterThan(0); + }); + + it('limits refinement work per dab', () => { + const source = mesh([-20, -20, 0, 20, -20, 0, 0, 20, 0], [0, 1, 2]); + const draft = new SculptMesh(source, identity); + const changed = draft.dab( + dab(new Vector3(), { + brush: 'mask', + radius: 5, + detail: 1, + minEdge: 0.01, + }), + ); + expect(changed).toBe(true); + expect(draft.geometry.index!.count / 3).toBeLessThanOrEqual(1 + 2 * 192); + }); + + it('keeps the original growth budget across committed strokes', () => { + const positions: number[] = []; + const faces: number[] = []; + for (let i = 0; i < 60; i++) { + const x = i * 100; + positions.push(x - 20, -20, 0, x + 20, -20, 0, x, 20, 0); + faces.push(i * 3, i * 3 + 1, i * 3 + 2); + } + let source = mesh(positions, faces); + let limited = false; + for (let i = 0; i < 60 && !limited; i++) { + const draft = new SculptMesh(source, identity); + draft.dab( + dab(new Vector3(i * 100, 0, 0), { + brush: 'mask', + face: i, + radius: 5, + detail: 1, + minEdge: 0.01, + }), + ); + const committed = draft.finish(); + if (committed) source = committed; + limited = draft.detailLimited; + } + expect(limited).toBe(true); + expect(source.index!.count / 3).toBeLessThanOrEqual(60 + 4096); + }); +}); diff --git a/tests/unit/sculpt-path.test.ts b/tests/unit/sculpt-path.test.ts new file mode 100644 index 0000000..78c8341 --- /dev/null +++ b/tests/unit/sculpt-path.test.ts @@ -0,0 +1,43 @@ +import { expect, it } from 'vitest'; +import { SculptPath, type SculptSample } from '../../src/core/sculpt-path'; + +const pen = (clientX: number, clientY = 0, pressure = 1): SculptSample => ({ + clientX, + clientY, + pressure, + pointerType: 'pen', + tiltX: 0, + tiltY: 0, + twist: 0, + shiftKey: false, + altKey: false, +}); + +it('lazily covers a fast sweep at the configured spacing and keeps its endpoint', () => { + const path = new SculptPath(pen(0, 0, 0.1), () => 2, 0); + path.push(pen(475, 0, 1), true); + expect(path.next()).toEqual(pen(0, 0, 0.1)); + let previous = 0; + let count = 0; + for (let sample = path.next(); sample; sample = path.next()) { + expect(sample.clientX - previous).toBeLessThanOrEqual(2.00001); + previous = sample.clientX; + count++; + } + expect(count).toBe(238); + expect(previous).toBe(475); + expect(path.pending).toBe(false); +}); + +it('carries spacing around the actual input path and accepts another move after draining', () => { + const path = new SculptPath(pen(0), () => 4, 0); + path.push(pen(3)); + path.push(pen(3, 3)); + expect(path.next()).toEqual(pen(0)); + expect(path.next()).toEqual(pen(3, 1)); + expect(path.next()).toBeUndefined(); + path.push(pen(6, 3), true); + expect(path.next()).toEqual(pen(5, 3)); + expect(path.next()).toEqual(pen(6, 3)); + expect(path.next()).toBeUndefined(); +}); diff --git a/tests/unit/sculpt-session.test.ts b/tests/unit/sculpt-session.test.ts new file mode 100644 index 0000000..b679390 --- /dev/null +++ b/tests/unit/sculpt-session.test.ts @@ -0,0 +1,221 @@ +import { BoxGeometry } from 'three'; +import { afterEach, describe, expect, it } from 'vitest'; +import { EditConflict, SharedDocument } from '../../mcp/document'; +import type { SculptStrokeCommit } from '../../src/core/sculpt-session'; +import { + restoreSculptAfterRefusal, + stopSharedSculptHistory, + useEditor, + useSharedHistory, + useSharedSculptQueueGuard, +} from '../../src/core/store'; +import type { Part, SceneDocument } from '../../src/core/types'; + +function fixture() { + const part: Part = { + id: 'sculpt-target', + name: 'Sculpt target', + geometry: new BoxGeometry(), + position: [0, 0, 0], + quaternion: [0, 0, 0, 1], + scale: [1, 1, 1], + color: '#ffffff', + visible: true, + locked: false, + source: 'test.stl', + }; + const scene: SceneDocument = { name: 'Sculpt', parts: [part], joints: [] }; + return { part, scene }; +} + +function openSculpt() { + const { part, scene } = fixture(); + useEditor.getState().setScene(scene); + useEditor.getState().select(part.id); + expect(useEditor.getState().startSculpt()).toBe(true); + return { part, scene }; +} + +function stroke(patch: Partial): SculptStrokeCommit { + const state = useEditor.getState(); + const part = state.scene.parts[0]; + return { + ...part, + partId: part.id, + source: part.geometry, + epoch: state.sceneEpoch, + revision: state.sculpt!.revision, + geometry: null, + mask: state.sculpt!.mask, + ...patch, + }; +} + +afterEach(() => { + useSharedHistory(null); + useSharedSculptQueueGuard(null); + useEditor.setState({ sharedHistory: null }); + useEditor.getState().setScene({ name: 'Empty', parts: [], joints: [] }); +}); + +describe('sculpt session', () => { + it('steps through temporary masks and geometry together while preserving committed history', () => { + const { part, scene } = openSculpt(); + const store = useEditor.getState; + store().changeSculptMask('invert'); + const firstMask = store().sculpt!.mask; + const geometry = part.geometry.clone(); + const newMask = new Float32Array(geometry.getAttribute('position').count).fill(0.25); + expect(store().commitSculpt(stroke({ geometry, mask: newMask }))).toBe(true); + store().changeSculptMask('clear'); + expect(store().revision - store().savedRevision).toBe(1); + expect(store().past).toEqual([scene]); + store().undo(); + expect(store().sculpt!.mask).toBe(newMask); + expect(store().scene.parts[0].geometry).toBe(geometry); + store().undo(); + expect(store().sculpt!.mask).toBe(firstMask); + expect(store().scene.parts[0].geometry).toBe(part.geometry); + store().undo(); + expect(store().sculpt!.mask).toBeNull(); + store().redo(); + store().redo(); + expect(store().sculpt!.mask).toBe(newMask); + expect(store().scene.parts[0].geometry).toBe(geometry); + store().redo(); + expect(store().sculpt!.mask).toBeNull(); + store().setTool('select'); + expect(store().sculpt).toBeNull(); + store().undo(); + expect(store().scene.parts[0].geometry).toBe(part.geometry); + }); + + it('remembers settings per brush and rejects a cancelled or moved stroke', () => { + const { part } = openSculpt(); + const store = useEditor.getState; + store().setSculptSettings({ radius: 7 }); + store().setSculptBrush('crease'); + store().setSculptSettings({ pinch: 0.9 }); + store().setSculptBrush('draw'); + expect(store().sculpt!.settings.radius).toBe(7); + store().resetSculptBrush(); + expect(store().sculpt!.settings.radius).toBe(store().sculpt!.defaultRadius); + store().setSculptBrush('crease'); + expect(store().sculpt!.settings.pinch).toBe(0.9); + const stale = stroke({ geometry: part.geometry.clone() }); + store().cancelSculptStroke(); + expect(store().commitSculpt(stale)).toBe(false); + const moved = stroke({ geometry: part.geometry.clone() }); + store().receiveScene({ ...store().scene, parts: [{ ...part, position: [1, 0, 0] }] }); + expect(store().commitSculpt(moved)).toBe(false); + expect(store().past).toHaveLength(0); + }); + + it('leaves the mesh and weights unchanged when the shared stroke queue is full', () => { + const { part, scene } = openSculpt(); + const store = useEditor.getState; + useSharedSculptQueueGuard(() => false); + store().changeSculptMask('invert'); + const session = store().sculpt; + expect(store().commitSculpt(stroke({ geometry: part.geometry.clone(), mask: null }))).toBe( + false, + ); + expect(store().scene).toBe(scene); + expect(store().sculpt).toBe(session); + expect(store().toast?.message).toMatch(/pending sculpt strokes/); + }); + + it('restores the appropriate weights on shared undo, redo, and refusal', () => { + const { part, scene } = openSculpt(); + const store = useEditor.getState; + const geometry = part.geometry.clone(); + const next = { ...scene, parts: [{ ...part, geometry }] }; + store().changeSculptMask('invert'); + const initialMask = store().sculpt!.mask; + expect(store().commitSculpt(stroke({ geometry, mask: null }))).toBe(true); + + useEditor.setState({ sharedHistory: { undo: 2, redo: 0 } }); + let ordinaryUndo = false; + useSharedHistory({ + undo: () => { + if (ordinaryUndo) store().receiveScene(scene); + else { + const pending = store().sculpt!.pending!.id; + store().receiveScene({ ...next, name: 'Ordinary change reverted' }); + stopSharedSculptHistory(true, pending); + ordinaryUndo = true; + } + }, + redo: () => store().receiveScene(next), + }); + store().undo(); + expect(store().sculpt!.pending).toBeNull(); + expect(store().sculpt!.past).toHaveLength(2); + expect(store().scene.parts[0].geometry).toBe(geometry); + store().undo(); + expect(store().sculpt!.mask).toBe(initialMask); + expect(store().scene.parts[0].geometry).toBe(part.geometry); + store().redo(); + expect(store().sculpt!.mask).toBeNull(); + expect(store().scene.parts[0].geometry).toBe(geometry); + + const refused = store().sculpt; + store().receiveScene(scene); + restoreSculptAfterRefusal(scene, refused); + expect(store().sculpt!.mask).toBe(initialMask); + expect(store().sculpt!.past).toHaveLength(1); + expect(store().sculpt!.future).toHaveLength(0); + }); +}); + +describe('shared sculpt transactions', () => { + it('rejects stale geometry and pose while preserving other authors’ changes', () => { + const { part, scene } = fixture(); + const document = new SharedDocument(); + document.replace(scene); + const first = document.version; + const geometry = part.geometry.clone(); + const target = { + partId: part.id, + source: part.geometry.uuid, + position: part.position, + quaternion: part.quaternion, + scale: part.scale, + }; + const edit = { + scene: { ...scene, parts: [{ ...part, geometry }] }, + base: first, + epoch: document.epoch, + checkpoint: true, + sculpt: target, + }; + document.apply('another-tab', { + ...edit, + sculpt: undefined, + scene: { ...scene, name: 'Renamed' }, + }); + document.apply('sculpt-tab', edit); + expect(document.scene.name).toBe('Renamed'); + expect(document.scene.parts[0].geometry).toBe(geometry); + const installed = document.version; + expect(document.apply('sculpt-tab', edit)).toBe(installed); + expect(document.counts('sculpt-tab').undo).toBe(1); + expect(() => + document.apply('sculpt-tab', { + ...edit, + scene: { ...scene, parts: [{ ...part, geometry: geometry.clone() }] }, + }), + ).toThrow(EditConflict); + document.undo('sculpt-tab'); + const base = document.version; + document.apply('another-tab', { + ...edit, + base, + sculpt: undefined, + scene: { ...document.scene, parts: [{ ...part, position: [1, 0, 0] }] }, + }); + expect(() => document.apply('sculpt-tab', { ...edit, base })).toThrow(EditConflict); + expect(document.scene.parts[0].position).toEqual([1, 0, 0]); + expect(document.scene.parts[0].geometry).toBe(part.geometry); + }); +});