Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
0fdea96
(docs) Propose browser sculpting with automatic detail
nimerix Nov 24, 2026
e68611d
(docs) Include masking and advanced sculpt controls
nimerix Nov 24, 2026
7e2bf9c
(docs) Add the Crease sculpt brush to v1
nimerix Nov 24, 2026
d2602d0
(docs) Plan browser sculpting implementation and volume brushes
nimerix Nov 24, 2026
4463561
(feat) Wire sculpt strokes into the browser viewport
nimerix Nov 24, 2026
2c11a0e
(test) Exercise browser sculpting with pen and mask input
nimerix Nov 24, 2026
6265881
(feat) Add adaptive sculpt mesh editing
nimerix Nov 24, 2026
db39cf1
(feat) Add sculpt controls and transactional history
nimerix Nov 24, 2026
f1cf95c
(fix) Preserve sculpt growth bounds and separate touching shells
nimerix Nov 24, 2026
1d976b9
(test) Verify guarded shared sculpt checkpoints
nimerix Nov 24, 2026
b8475f7
(test) Measure sculpt input through viewport drawing
nimerix Nov 24, 2026
303fcdb
(fix) Preserve remote meshes across queued sculpt edits
nimerix Nov 24, 2026
b77bd6a
(fix) Preserve sculpt history across shared document undo
nimerix Nov 24, 2026
623055d
(fix) Commit released strokes and preserve pen controls
nimerix Nov 24, 2026
6a83cc3
(docs) Record sculpt verification and viewport timings
nimerix Nov 24, 2026
ea00c92
(fix) Keep shared meshes current after delayed sculpt responses
nimerix Nov 24, 2026
95cb63b
(fix) Skip retrying confirmed sculpt strokes
nimerix Nov 24, 2026
910d665
(fix) Preserve shared sculpt history and full brush coverage
nimerix Nov 24, 2026
2ea0b85
(fix) Restore sculpt masks and ignore stale stream loads
nimerix Nov 24, 2026
63e1ca8
(fix) Process reconnect snapshots after stale load failures
nimerix Nov 24, 2026
e65c855
(fix) Preserve global undo history when sculpting
nimerix Nov 24, 2026
bcf58ac
(fix) Discard queued undo when a shared edit is refused
nimerix Nov 24, 2026
252e10e
(fix) Keep fast sculpt strokes continuous
nimerix Nov 24, 2026
a751f61
(fix) Cancel pending Sculpt work on shared scene replacement
nimerix Nov 24, 2026
6d583ff
(fix) Isolate sculpt fans and speed up dense brush dabs
nimerix Nov 24, 2026
3dc65ec
(perf) Spread dense sculpt dabs across frames
nimerix Nov 24, 2026
4749411
(fix) Queue input while sculpt strokes finish
nimerix Nov 24, 2026
8b5e951
(fix) Preserve released sculpt work across editor actions
nimerix Nov 24, 2026
7492ee7
(fix) Restore committed mesh after sculpt cancellation
nimerix Nov 24, 2026
d86695b
(fix) Preserve the order of actions queued after sculpting
nimerix Nov 24, 2026
a443aaf
(fix) Keep queued sculpt actions across tool switches
nimerix Nov 24, 2026
531066c
(fix) Preserve queued sculpt cancellation and transform baselines
nimerix Nov 24, 2026
38bab61
(fix) Keep queued sculpt actions out of free transform previews
nimerix Nov 24, 2026
b504093
(fix) Invalidate stale sculpt commands and transform previews
nimerix Nov 24, 2026
15f4085
(fix) Keep shared sculpt edits bound to their scene
nimerix Nov 24, 2026
279bc38
(fix) Keep stale Open requests from replacing newer shared scenes
nimerix Nov 24, 2026
ff7f25e
(fix) Recover shared sculpt edits after ambiguous responses
nimerix Nov 24, 2026
29df023
(fix) Retry shared mesh uploads and ignore stale recovery snapshots
nimerix Nov 24, 2026
38b8d50
(fix) Resume shared edits after event stream reconnect failures
nimerix Nov 24, 2026
a483460
(fix) Reconnect shared scenes after terminal stream errors
nimerix Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
48 changes: 48 additions & 0 deletions docs/superpowers/plans/2026-11-23-browser-sculpting.md
Original file line number Diff line number Diff line change
@@ -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.
148 changes: 148 additions & 0 deletions docs/superpowers/specs/2026-11-23-browser-sculpting-design.md
Original file line number Diff line number Diff line change
@@ -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.
41 changes: 36 additions & 5 deletions mcp/document.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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 {
Expand Down Expand Up @@ -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<number, SceneDocument>();
private readonly log = new Map<number, Logged>();
private readonly histories = new Map<string, { undo: ScenePatch[]; redo: ScenePatch[] }>();
Expand All @@ -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();
Expand All @@ -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 {
Expand Down Expand Up @@ -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();
Expand Down
8 changes: 7 additions & 1 deletion mcp/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, GeometryLayout> = {};
for (const { geometry } of scene.parts) {
let layout = this.layouts.get(geometry);
Expand All @@ -315,6 +315,7 @@ export class LiveView {
return `event: scene\ndata: ${JSON.stringify({
version,
epoch,
replacementId,
scene: sharedScene(scene),
geometries,
history: this.document.historyCounts(),
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading