diff --git a/README.md b/README.md index b9454b8..3abea67 100644 --- a/README.md +++ b/README.md @@ -955,7 +955,7 @@ remeasured. These limits were not measured in Firefox or Safari. translation; a single mate still allows planar sliding and twist. - Lighting is for viewing in the editor. A scene has at most 8 lights. Only directional lights that do not follow the camera cast shadows; point lights do not. -- Undo history retains the most recent 40 changes in the current session. +- Undo history retains up to 120 changes in the current session. ## Source diff --git a/docs/mcp.md b/docs/mcp.md index 302f1da..c924869 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -87,7 +87,7 @@ The server gives connecting agents these conventions, along with a suggested way | `get_scene` | List parts with exact bounds, joints, constraints, and residuals | | `new_scene`, `open_scene`, `save_scene` | Start, open, and save `.kitbash` scenes | | `export_scene` | Write GLB, STL, 3MF, or a Blender package, chosen by file extension | -| `undo`, `redo` | Step through the most recent 40 changes | +| `undo`, `redo` | Step through up to 120 recent changes | | `open_live_view` | Open the scene in the app, where you and the agent edit it together | ## Behavior diff --git a/mcp/document.ts b/mcp/document.ts index eea99dd..b79e341 100644 --- a/mcp/document.ts +++ b/mcp/document.ts @@ -10,8 +10,36 @@ import { summarizePatch, } from '../src/core/sync'; import type { ScenePatch } from '../src/core/sync'; -import { arraysOf, historyBudgetBytes } from '../src/core/history-budget'; +import { buffersOf, historyBudgetBytes, historyLimit } from '../src/core/history-budget'; import type { SceneDocument } from '../src/core/types'; +import { + archiveGeometry, + archiveScene, + rememberSculptGeometry, + restoreGeometry, + restoreScene, + type HistoryScene, + type HistoryGeometry, +} from '../src/core/sculpt-history'; + +function mapPatchGeometry( + patch: ScenePatch, + map: (g: HistoryGeometry) => HistoryGeometry, +): ScenePatch { + return patch.map((change) => { + if (change.kind !== 'parts') return change; + const mapped = (entity: typeof change.before) => { + if (!entity) return entity; + const geometry = map(entity.geometry as HistoryGeometry); + return geometry === entity.geometry ? entity : { ...entity, geometry }; + }; + const before = mapped(change.before); + const after = mapped(change.after); + return before === change.before && after === change.after + ? change + : { ...change, before, after }; + }); +} export const agent = 'agent'; @@ -39,7 +67,6 @@ interface Logged { // Enough for a tab that falls behind during a large upload. const keepVersions = 200; -const keepSteps = 40; const keepUploadsMs = 10 * 60 * 1000; const changesGeometry = (patch: ScenePatch) => @@ -58,10 +85,10 @@ export class SharedDocument { epoch = 0; /** Identifies the browser edit that started this epoch, if any. */ replacementId?: string; - private readonly versions = new Map(); + private readonly versions = new Map(); private readonly log = new Map(); private readonly histories = new Map(); - private readonly meshes = new Map(); + private readonly meshes = new Map(); private readonly uploads = new Map(); private readonly listeners = new Set<() => void>(); @@ -108,8 +135,8 @@ export class SharedDocument { this.replace(edit.scene, author, false, edit.replacementId); return this.version; } - const base = this.versions.get(edit.base); - if (!base) + const version = this.versions.get(edit.base); + if (!version) throw new EditConflict('This change was made on a version of the scene that is too old.'); const current = this.scene; if (edit.sculpt) { @@ -121,6 +148,7 @@ export class SharedDocument { throw new EditConflict( 'The sculpt target changed before the stroke reached the shared scene.', ); + rememberSculptGeometry(part.geometry, carved.geometry); const next = { ...current, parts: current.parts.map((candidate) => @@ -131,6 +159,7 @@ export class SharedDocument { this.commit(author, current); return this.version; } + const base = edit.base === this.version ? current : restoreScene(version); let next = mergeScenes(base, edit.scene, current, 'ours'); if (base !== current) try { @@ -218,7 +247,8 @@ export class SharedDocument { } mesh(key: string) { - return this.meshes.get(key); + const geometry = this.meshes.get(key); + return geometry && restoreGeometry(geometry); } private step(author: string, direction: 'undo' | 'redo') { @@ -227,7 +257,11 @@ export class SharedDocument { const patch = stack?.at(-1); if (!history || !stack || !patch) return null; const current = this.scene; - const { scene, changed } = applyPatch(current, patch, direction); + const { scene, changed } = applyPatch( + current, + mapPatchGeometry(patch, restoreGeometry), + direction, + ); const next = changed ? reconcile(scene) : current; stack.pop(); (direction === 'undo' ? history.redo : history.undo).push(patch); @@ -242,25 +276,26 @@ export class SharedDocument { private record(author: string, patch: ScenePatch, amend: boolean) { let history = this.histories.get(author); if (!history) this.histories.set(author, (history = { undo: [], redo: [] })); + patch = mapPatchGeometry(patch, archiveGeometry); const last = history.undo.at(-1); if (amend && last && !history.redo.length) history.undo[history.undo.length - 1] = composePatches(last, patch); else { history.undo.push(patch); - if (history.undo.length > keepSteps) history.undo.shift(); + if (history.undo.length > historyLimit) history.undo.shift(); } history.redo = []; } private publish(author: string, patch: ScenePatch, replaced = false) { this.version++; - this.versions.set(this.version, this.scene); + this.versions.set(this.version, archiveScene(this.scene)); 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) { const { geometry } = part; - this.meshes.set(geometry.uuid, geometry); + this.meshes.set(geometry.uuid, archiveGeometry(geometry)); this.uploads.delete(geometry.uuid); } if (changesGeometry(patch)) this.trimMemory(); @@ -269,51 +304,62 @@ export class SharedDocument { } /** - * Drops old undo steps, far redo steps, then old scene versions until history fits the mesh - * budget. Change summaries, each author’s newest undo step, and the current version stay. + * Reserve the mesh budget for undo and redo before retaining older scene versions. + * Change summaries, each author’s newest undo step, and the current version stay. */ private trimMemory() { - const kept = arraysOf(this.scene.parts.map((part) => part.geometry)); - const counts = new Map, number>(); + const kept = buffersOf(this.scene.parts.map((part) => part.geometry)); + const counts = new Map(); + const references = new Map(); let total = 0; - const hold = (geometries: BufferGeometry[], by: 1 | -1) => { - for (const array of arraysOf(geometries)) { - if (kept.has(array)) continue; - const bytes = (array as unknown as { byteLength: number }).byteLength; - const count = (counts.get(array) ?? 0) + by; - counts.set(array, count); - if (by === 1 && count === 1) total += bytes; - if (by === -1 && count === 0) total -= bytes; + const hold = (geometries: HistoryGeometry[], by: 1 | -1) => { + for (const geometry of geometries) { + const previous = references.get(geometry) ?? 0; + references.set(geometry, previous + by); + if (previous !== 0 && previous + by !== 0) continue; + for (const buffer of buffersOf([geometry])) { + if (kept.has(buffer)) continue; + const count = (counts.get(buffer) ?? 0) + by; + counts.set(buffer, count); + if (by === 1 && count === 1) total += buffer.byteLength; + if (by === -1 && count === 0) total -= buffer.byteLength; + } } }; - const ofScene = (scene: SceneDocument) => scene.parts.map((part) => part.geometry); + const ofScene = (scene: HistoryScene) => scene.parts.map((part) => part.geometry); const ofPatch = (patch: ScenePatch) => patch.flatMap((change) => change.kind === 'parts' ? [change.before, change.after].flatMap((entity) => - entity ? [entity.geometry as BufferGeometry] : [], + entity ? [entity.geometry as HistoryGeometry] : [], ) : [], ); - for (const scene of this.versions.values()) hold(ofScene(scene), 1); + hold(ofScene(this.versions.get(this.version)!), 1); const histories = [...this.histories.values()]; for (const history of histories) for (const patch of [...history.undo, ...history.redo]) hold(ofPatch(patch), 1); - if (total <= this.budget) return; + let trimmed = total > this.budget; const drop = () => { const undo = histories.find((history) => history.undo.length > 1); if (undo) return (hold(ofPatch(undo.undo.shift()!), -1), true); const redo = histories.find((history) => history.redo.length); if (redo) return (hold(ofPatch(redo.redo.shift()!), -1), true); - const old = [...this.versions.keys()].find((version) => version !== this.version); - if (old === undefined) return false; - hold(ofScene(this.versions.get(old)!), -1); - this.versions.delete(old); - return true; + return false; }; while (total > this.budget && drop()); - this.prune(); + // Version snapshots often own exactly the same buffers as undo. Spend any + // remaining budget on the newest versions needed by late-arriving edits. + for (const [version, scene] of [...this.versions].reverse()) { + if (version === this.version) continue; + if (total <= this.budget) hold(ofScene(scene), 1); + if (total > this.budget) { + this.versions.delete(version); + trimmed = true; + } + } + if (trimmed) this.prune(); } /** Keeps every mesh that a version or an undo step can still bring back. */ diff --git a/mcp/tools.ts b/mcp/tools.ts index dd75944..5d65e27 100644 --- a/mcp/tools.ts +++ b/mcp/tools.ts @@ -500,12 +500,8 @@ export function createServer(session = new Session(), live = new LiveView()) { ({ joints, plane_constraints }) => session.removeRelationships(joints, plane_constraints), ); - tool( - 'undo', - 'Undoes the last scene change. The most recent 40 changes are kept.', - edits, - {}, - () => session.undo(), + tool('undo', 'Undoes the last scene change. Up to 120 recent changes are kept.', edits, {}, () => + session.undo(), ); tool('redo', 'Redoes the last undone change.', edits, {}, () => session.redo()); diff --git a/src/core/history-budget.ts b/src/core/history-budget.ts index bb67415..25f4112 100644 --- a/src/core/history-budget.ts +++ b/src/core/history-budget.ts @@ -1,43 +1,41 @@ -import type { BufferGeometry, InterleavedBufferAttribute } from 'three'; -import type { SceneDocument } from './types'; +import type { BufferAttribute } from 'three'; +import { SculptGeometrySnapshot, type HistoryGeometry, type HistoryScene } from './sculpt-history'; + +export const historyLimit = 120; export const historyBudgetBytes = 1024 ** 3; -function arrays(geometry: BufferGeometry) { - const found: ArrayLike[] = []; - for (const attribute of Object.values(geometry.attributes)) - found.push( - (attribute as InterleavedBufferAttribute).isInterleavedBufferAttribute - ? (attribute as InterleavedBufferAttribute).data.array - : (attribute as { array: ArrayLike }).array, - ); +function arrays(geometry: HistoryGeometry) { + if (geometry instanceof SculptGeometrySnapshot) return geometry.arrays; + const found: BufferAttribute['array'][] = []; + for (const attribute of Object.values(geometry.attributes)) found.push(attribute.array); if (geometry.index) found.push(geometry.index.array); return found; } /** Bytes of attribute and index arrays, each array counted once, skipping arrays in `exclude`. */ export function geometryBytes( - geometries: Iterable, - exclude: Set> = new Set(), + geometries: Iterable, + exclude: Set = new Set(), ) { - const seen = new Set>(exclude); + const seen = new Set(exclude); let bytes = 0; for (const geometry of geometries) for (const array of arrays(geometry)) { if (seen.has(array)) continue; seen.add(array); - bytes += (array as { byteLength?: number }).byteLength ?? 0; + bytes += array.byteLength; } return bytes; } -export function arraysOf(geometries: Iterable) { - const set = new Set>(); - for (const geometry of geometries) for (const array of arrays(geometry)) set.add(array); +export function buffersOf(geometries: Iterable) { + const set = new Set(); + for (const geometry of geometries) for (const array of arrays(geometry)) set.add(array.buffer); return set; } -const sceneGeometries = (scenes: SceneDocument[]) => +const sceneGeometries = (scenes: HistoryScene[]) => scenes.flatMap((scene) => scene.parts.map((part) => part.geometry)); /** @@ -45,21 +43,32 @@ const sceneGeometries = (scenes: SceneDocument[]) => * history reaches fit the budget. The newest `past` entry always stays. */ export function trimHistory( - past: SceneDocument[], - future: SceneDocument[], - keep: SceneDocument[], + past: HistoryScene[], + future: HistoryScene[], + keep: HistoryScene[], budget = historyBudgetBytes, ) { - const kept = arraysOf(sceneGeometries(keep)); - const bytes = (p: SceneDocument[], f: SceneDocument[]) => - geometryBytes(sceneGeometries([...p, ...f]), kept); - let start = 0; - let end = future.length; - while (bytes(past.slice(start), future.slice(0, end)) > budget) { - if (past.length - start > 1) start++; - else if (end > 0) end--; - else break; - } + const kept = buffersOf(sceneGeometries(keep)); + // Visit in retention order, so even a large eviction only walks each checkpoint once. + let bytes = 0; + const seen = new Set(); + const count = (scene: HistoryScene) => { + for (const part of scene.parts) { + if (seen.has(part.geometry)) continue; + seen.add(part.geometry); + for (const array of arrays(part.geometry)) { + if (kept.has(array.buffer)) continue; + kept.add(array.buffer); + bytes += array.buffer.byteLength; + } + } + return bytes <= budget; + }; + let start = past.length; + if (start) count(past[--start]); + let end = 0; + while (end < future.length && count(future[end])) end++; + if (end === future.length) while (start > 0 && count(past[start - 1])) start--; const trimmed = start > 0 || end < future.length; return trimmed ? { past: past.slice(start), future: future.slice(0, end), trimmed } diff --git a/src/core/sculpt-history.ts b/src/core/sculpt-history.ts new file mode 100644 index 0000000..f2f2a60 --- /dev/null +++ b/src/core/sculpt-history.ts @@ -0,0 +1,212 @@ +import { BufferAttribute, BufferGeometry } from 'three'; +import type { Part, SceneDocument } from './types'; + +type NumericArray = BufferAttribute['array']; +type Slice = { offset: number; bytes: Uint8Array }; + +/** A standalone snapshot. Each patch refers directly to a full array, so evicting an + * older stroke never breaks restoration or leaves a chain of retired strokes alive. */ +export class PackedArray { + private live: WeakRef; + constructor( + readonly base: T, + readonly length: number, + readonly slices: Slice[], + value: T, + ) { + this.live = new WeakRef(value); + } + + restore(): T { + const live = this.live.deref(); + if (live) return live; + if (!this.slices.length && this.length === this.base.length) return this.base; + const Type = this.base.constructor as new (length: number) => T; + const value = new Type(this.length); + value.set(this.base.subarray(0, this.length)); + const bytes = new Uint8Array(value.buffer); + for (const slice of this.slices) bytes.set(slice.bytes, slice.offset); + this.live = new WeakRef(value); + return value; + } +} + +function words(array: NumericArray) { + return new Uint32Array(array.buffer, array.byteOffset, Math.floor(array.byteLength / 4)); +} + +/** Compare aligned words, preserving signed zeros, NaN payloads and integer attributes. */ +export function packArray( + value: T, + previous?: T, + snapshot?: PackedArray, +): PackedArray { + if (snapshot && value === previous) return snapshot; + const full = () => new PackedArray(value, value.length, [], value); + if ( + !previous || + previous === value || + previous.constructor !== value.constructor || + previous.byteOffset % 4 || + value.byteOffset % 4 || + value.byteLength < 1024 + ) + return full(); + + const base = snapshot?.base ?? previous; + if (base.byteLength > value.byteLength * 2) return full(); + const before = words(previous); + const after = words(value); + const data = new Uint8Array(value.buffer, value.byteOffset, value.byteLength); + const slices: Slice[] = []; + const changed: number[] = []; + let priorIndex = 0; + let changedBytes = 0; + for (let offset = 0; offset < data.length; offset += 2048) { + const end = Math.min(offset + 2048, data.length); + const prior = snapshot?.slices[priorIndex]; + const inherited = prior?.offset === offset ? prior : undefined; + if (inherited) priorIndex++; + let different = end > previous.byteLength || end % 4 !== 0; + if (!different) { + for (let i = offset / 4; i < end / 4; i++) { + if (before[i] === after[i]) continue; + different = true; + break; + } + } + if (different) { + changedBytes += end - offset; + if (changedBytes > data.length / 3) return full(); + // Defer copying until we know a dense edit will not need a full checkpoint. + changed.push(slices.length); + slices.push({ offset, bytes: data.subarray(offset, end) }); + } else if (inherited) { + slices.push( + inherited.bytes.length <= end - offset + ? inherited + : { offset, bytes: inherited.bytes.slice(0, end - offset) }, + ); + } + } + for (const index of changed) slices[index].bytes = slices[index].bytes.slice(); + return new PackedArray(base, value.length, slices, value); +} + +const archived = new WeakMap(); +export const sculptFaceLimits = new WeakMap(); + +/** Mesh identity and render metadata survive eviction of the live mesh and its picking tree. */ +export class SculptGeometrySnapshot { + readonly uuid: string; + readonly arrays: NumericArray[] = []; + private live: WeakRef; + private readonly attributes = new Map< + string | null, + Pick & { + data: PackedArray; + } + >(); + private readonly template = new BufferGeometry(); + private readonly faceLimit?: number; + + constructor(source: BufferGeometry, geometry: BufferGeometry, faceLimit?: number) { + this.uuid = geometry.uuid; + this.faceLimit = faceLimit; + this.live = new WeakRef(geometry); + this.template.name = geometry.name; + this.template.userData = geometry.userData; + this.template.groups = geometry.groups; + this.template.drawRange = { ...geometry.drawRange }; + this.template.boundingBox = geometry.boundingBox; + this.template.boundingSphere = geometry.boundingSphere; + const prior = archived.get(source); + const save = (name: string | null, attribute: BufferAttribute, previous?: NumericArray) => { + const data = packArray(attribute.array, previous, prior?.attributes.get(name)?.data); + this.attributes.set(name, { + data, + itemSize: attribute.itemSize, + normalized: attribute.normalized, + name: attribute.name, + usage: attribute.usage, + gpuType: attribute.gpuType, + }); + this.arrays.push(data.base); + for (const slice of data.slices) this.arrays.push(slice.bytes); + }; + for (const [name, attribute] of Object.entries(geometry.attributes)) + save(name, attribute as BufferAttribute, source.getAttribute(name)?.array); + if (geometry.index) save(null, geometry.index, source.index?.array); + } + + restore() { + const live = this.live.deref(); + if (live) return live; + const geometry = this.template.clone(); + geometry.uuid = this.uuid; + for (const [name, { data, itemSize, normalized, name: label, usage, gpuType }] of this + .attributes) { + const attribute = new BufferAttribute(data.restore(), itemSize, normalized); + attribute.name = label; + attribute.setUsage(usage); + attribute.gpuType = gpuType; + if (name !== null) geometry.setAttribute(name, attribute); + else geometry.setIndex(attribute); + } + if (this.faceLimit !== undefined) sculptFaceLimits.set(geometry, this.faceLimit); + archived.set(geometry, this); + this.live = new WeakRef(geometry); + return geometry; + } +} + +export function rememberSculptGeometry(source: BufferGeometry, geometry: BufferGeometry) { + if ( + archived.has(geometry) || + geometry.constructor !== BufferGeometry || + geometry.indirect || + Object.keys(geometry.morphAttributes).length || + !Object.values(geometry.attributes).some((attribute) => attribute.array.byteLength >= 1024) || + [...Object.values(geometry.attributes), geometry.index].some( + (a) => a && a.constructor !== BufferAttribute, + ) + ) + return; + archived.set( + geometry, + new SculptGeometrySnapshot(source, geometry, sculptFaceLimits.get(geometry)), + ); +} + +export type HistoryGeometry = BufferGeometry | SculptGeometrySnapshot; +export const archiveGeometry = (geometry: HistoryGeometry) => + geometry instanceof SculptGeometrySnapshot ? geometry : (archived.get(geometry) ?? geometry); +export const restoreGeometry = (geometry: HistoryGeometry) => + geometry instanceof SculptGeometrySnapshot ? geometry.restore() : geometry; + +type HistoryPart = Omit & { geometry: HistoryGeometry }; +export type HistoryScene = Omit & { parts: HistoryPart[] }; + +export function archiveScene(scene: SceneDocument): HistoryScene { + if (!scene.parts.some((p) => archived.has(p.geometry))) return scene; + return { + ...scene, + parts: scene.parts.map((part) => { + const geometry = archived.get(part.geometry); + return geometry ? { ...part, geometry } : part; + }), + }; +} + +export function restoreScene(scene: HistoryScene): SceneDocument { + if (!scene.parts.some((p) => p.geometry instanceof SculptGeometrySnapshot)) + return scene as SceneDocument; + return { + ...scene, + parts: scene.parts.map((part) => + part.geometry instanceof SculptGeometrySnapshot + ? { ...part, geometry: part.geometry.restore() } + : (part as Part), + ), + }; +} diff --git a/src/core/sculpt-mesh.ts b/src/core/sculpt-mesh.ts index 9781d3d..575188a 100644 --- a/src/core/sculpt-mesh.ts +++ b/src/core/sculpt-mesh.ts @@ -16,6 +16,7 @@ import { type Raycaster, } from 'three'; import { MeshBVH } from 'three-mesh-bvh'; +import { sculptFaceLimits } from './sculpt-history'; import type { SculptBrush } from './types'; export type { SculptBrush } from './types'; @@ -92,7 +93,7 @@ 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. */ @@ -384,15 +385,18 @@ export class SculptMesh { 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) ?? + sculptFaceLimits.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; + if (source.index?.itemSize === 1 && !source.index.normalized) + indices.set(source.index.array.subarray(0, indices.length)); + else + 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); @@ -1397,15 +1401,38 @@ export class SculptMesh { for (const [name, attribute] of Object.entries(this.geometry.attributes)) { if (name === maskName) continue; const { array, itemSize, normalized } = attribute; + const original = this.source.getAttribute(name); + if ( + name !== 'position' && + name !== 'normal' && + this.vertexCount === this.initialVertices && + original instanceof BufferAttribute && + original.count === this.vertexCount + ) { + geometry.setAttribute(name, new BufferAttribute(original.array, itemSize, normalized)); + continue; + } 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; + if ( + this.source.index?.itemSize === 1 && + !this.source.index.normalized && + this.source.index.count === this.faceCount * 3 && + this.source.index.array instanceof (this.vertexCount <= 65_536 ? Uint16Array : Uint32Array) && + this.vertexCount === this.initialVertices && + this.faceCount === this.initialFaces + ) { + geometry.setIndex(new BufferAttribute(this.source.index.array, 1)); + } else if (this.source.index || this.faceCount !== this.initialFaces) { + const index = this.geometry.index!.array.subarray(0, this.faceCount * 3) as Uint32Array; geometry.setIndex( - new BufferAttribute(this.vertexCount <= 65_536 ? Uint16Array.from(index) : index, 1), + new BufferAttribute( + this.vertexCount <= 65_536 ? Uint16Array.from(index) : index.slice(), + 1, + ), ); } geometry.groups = this.geometry.groups.map((group) => ({ ...group })); @@ -1415,7 +1442,7 @@ export class SculptMesh { geometry.boundingSphere = new Sphere(bounds.center.clone(), bounds.radius); } this.refitPicking(geometry); - inheritedFaceLimits.set(geometry, this.faceLimit); + sculptFaceLimits.set(geometry, this.faceLimit); if (this.faceStart.length) rememberIncidence(geometry, { weldOf: diff --git a/src/core/sculpt-session.ts b/src/core/sculpt-session.ts index 388610a..a76415f 100644 --- a/src/core/sculpt-session.ts +++ b/src/core/sculpt-session.ts @@ -1,4 +1,6 @@ import type { BufferGeometry } from 'three'; +import { PackedArray, packArray } from './sculpt-history'; +import { historyLimit } from './history-budget'; import { same } from './sync'; import type { Part, Quat, SculptBrush, SculptureSettings, Vec3 } from './types'; @@ -34,9 +36,43 @@ export interface SculptStrokeCommit { mask: Float32Array | null; } +type MaskSnapshot = PackedArray | null; +const maskSnapshots = new WeakMap>(); + +export function archiveMask( + mask: Float32Array | null, + previous?: Float32Array | null, +): MaskSnapshot { + if (!mask) return null; + const known = maskSnapshots.get(mask); + if (known) return known; + let packed = packArray( + mask, + previous ?? undefined, + previous ? maskSnapshots.get(previous) : undefined, + ); + if ( + packed.slices.length && + packed.slices.reduce( + (bytes, slice) => bytes + slice.bytes.byteLength, + packed.base.buffer.byteLength, + ) > maskHistoryBytes + ) + packed = packArray(mask); + maskSnapshots.set(mask, packed); + return packed; +} + +export function restoreMask(snapshot: MaskSnapshot) { + if (!snapshot) return null; + const mask = snapshot.restore(); + maskSnapshots.set(mask, snapshot); + return mask; +} + interface SculptSnapshot { geometry: string; - mask: Float32Array | null; + mask: MaskSnapshot; } export interface SculptStep { @@ -87,18 +123,38 @@ 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]); +export function appendSculptStep( + past: SculptStep[], + step: SculptStep, + current: Float32Array | null, +) { + const kept = [...past, step].slice(-historyLimit); + const seen = new Set(); + const masks = new Set(); + if (current) seen.add(current.buffer); let bytes = 0; + const count = (buffer: ArrayBufferLike) => { + if (seen.has(buffer)) return; + seen.add(buffer); + bytes += buffer.byteLength; + }; 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 (!mask || masks.has(mask)) continue; + masks.add(mask); + count(mask.base.buffer); + for (const slice of mask.slices) count(slice.bytes.buffer); + } + if (bytes <= maskHistoryBytes) continue; + if (i < kept.length - 1) return kept.slice(i + 1); + // The latest mask already lives in the session. Keeping it directly frees + // its patches when the preceding mask needs the entire undo budget. + if (current) { + const full = packArray(current); + maskSnapshots.set(current, full); + return [{ ...step, after: { ...step.after, mask: full } }]; } - if (bytes > maskHistoryBytes) return kept.slice(i + 1); + return [step]; } return kept; } @@ -112,7 +168,7 @@ export function stepSculptSession( return { ...session, revision: session.revision + 1, - mask: (undo ? step.before : step.after).mask, + mask: restoreMask((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 b550bd3..8ebaa71 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -99,9 +99,18 @@ import type { RegionInput, RegionSolve } from './refine-region'; import type { NavigationMode } from './navigation'; import { createSample } from './sample'; import { useXR } from './xr-session'; -import { geometryBytes, historyBudgetBytes, trimHistory } from './history-budget'; +import { + archiveScene, + restoreScene, + rememberSculptGeometry, + SculptGeometrySnapshot, + type HistoryScene, +} from './sculpt-history'; +import { geometryBytes, historyBudgetBytes, historyLimit, trimHistory } from './history-budget'; import { appendSculptStep, + archiveMask, + restoreMask, maskHistoryBytes, sculptDefaults, sculptHistoryBytes, @@ -244,7 +253,7 @@ const initialScene: SceneDocument = liveSession constraints: [], } : createSample(); -const historyLimit = 40; + // Leaves a dragged frame time to draw. The part catches up over the next frames. const gestureBudget = 12; @@ -501,8 +510,8 @@ interface EditorState { lightingPanel: boolean; /** The light being edited in the lighting panel and moved in the viewport. */ activeLight: string | null; - past: SceneDocument[]; - future: SceneDocument[]; + past: HistoryScene[]; + future: HistoryScene[]; revision: number; savedRevision: number; driveFile: DriveFileBinding | null; @@ -1888,7 +1897,9 @@ function appliedWarpGeometry(source: BufferGeometry, output: WarpOutput) { const changed = (state: EditorState, scene: SceneDocument, checkpoint = true) => { const base = committedScene(state); - let past = checkpoint ? [...state.past.slice(-(historyLimit - 1)), base] : state.past; + let past = checkpoint + ? [...state.past.slice(-(historyLimit - 1)), archiveScene(base)] + : state.past; let notice = {}; if (checkpoint && (newGeometry(base, scene) || newGeometry(scene, base))) { const kept = trimHistory( @@ -1987,14 +1998,15 @@ function historyScene(state: EditorState, direction: HistoryDirection) { function restoreHistoryScene( state: EditorState, direction: HistoryDirection, - scene: SceneDocument, + entry: HistoryScene, sculpt: SculptSession | null = null, ): Partial { const undo = direction === 'undo'; + const scene = restoreScene(entry); return { scene, - past: undo ? state.past.slice(0, -1) : [...state.past, state.scene], - future: undo ? [state.scene, ...state.future] : state.future.slice(1), + past: undo ? state.past.slice(0, -1) : [...state.past, archiveScene(state.scene)], + future: undo ? [archiveScene(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), @@ -3507,9 +3519,10 @@ export const useEditor = create((set, get) => ({ ); return false; } + if (geometry !== part.geometry) rememberSculptGeometry(part.geometry, geometry); const step = { - before: { geometry: part.geometry.uuid, mask: sculpt.mask }, - after: { geometry: geometry.uuid, mask }, + before: { geometry: part.geometry.uuid, mask: archiveMask(sculpt.mask) }, + after: { geometry: geometry.uuid, mask: archiveMask(mask, sculpt.mask) }, }; set({ ...(geometry === part.geometry @@ -3526,7 +3539,7 @@ export const useEditor = create((set, get) => ({ ...sculpt, revision: nextSculptRevision(), mask, - past: appendSculptStep(sculpt.past, step), + past: appendSculptStep(sculpt.past, step, mask), future: [], }, }); @@ -5120,7 +5133,8 @@ function reachableGeometries(state: EditorState) { ...state.future.map((scene) => scene.parts), state.clipboard?.parts ?? [], ]) - for (const part of parts) geometries.add(part.geometry); + for (const part of parts) + if (!(part.geometry instanceof SculptGeometrySnapshot)) geometries.add(part.geometry); return geometries; } @@ -7023,7 +7037,7 @@ export function restoreSculptAfterRefusal(scene: SceneDocument, sculpt: SculptSe useEditor.setState({ sculpt: { ...sculpt, - mask: sculpt.past[start].before.mask, + mask: restoreMask(sculpt.past[start].before.mask), past: sculpt.past.slice(0, start), future: [], pending: null, diff --git a/src/docs/workspace-guides.ts b/src/docs/workspace-guides.ts index ebb7c69..13d8a26 100644 --- a/src/docs/workspace-guides.ts +++ b/src/docs/workspace-guides.ts @@ -81,7 +81,7 @@ export const workspaceGuides: DocArticle[] = [ id: 'undo-and-recovery', title: 'Undo is for the current editing session', paragraphs: [ - 'Undo and redo retain the most recent 40 changes. A complete gizmo drag, fit, or mesh-processing apply is one undo step; the scene file is a snapshot rather than a record of every earlier step. Save before an experiment if you may need to return after closing the editor.', + 'Undo and redo retain up to 120 changes. A complete gizmo drag, fit, or mesh-processing apply is one undo step; the scene file is a snapshot rather than a record of every earlier step. Save before an experiment if you may need to return after closing the editor.', 'If the editor encounters an unexpected error, its recovery screen offers to reload the local save. If the same recovered scene repeatedly fails, it also offers to discard that recovery data. Preserve an independent scene file before discarding when possible.', ], }, diff --git a/tests/unit/history-budget.test.ts b/tests/unit/history-budget.test.ts index b20aa41..59180fd 100644 --- a/tests/unit/history-budget.test.ts +++ b/tests/unit/history-budget.test.ts @@ -80,9 +80,9 @@ describe('history budget', () => { it('leaves history untouched for transform-only checkpoints', () => { const scene = sceneOf(new BoxGeometry(1, 1, 1)); useEditor.getState().setScene(scene); - for (let i = 0; i < 41; i++) useEditor.getState().transform('p0', { position: [i + 1, 0, 0] }); + for (let i = 0; i < 121; i++) useEditor.getState().transform('p0', { position: [i + 1, 0, 0] }); const state = useEditor.getState(); - expect(state.past.length).toBe(40); + expect(state.past.length).toBe(120); expect(state.historyTrimNotified).toBe(false); expect(state.toast).toBeNull(); }); @@ -165,8 +165,7 @@ describe('history budget', () => { meshes: Map; versions: Map; }; - expect(doc.counts('agent').undo).toBeLessThan(6); - expect(doc.counts('agent').undo).toBeGreaterThanOrEqual(1); + expect(doc.counts('agent').undo).toBe(2); expect(doc.version).toBe(7); expect(internal.versions.has(7)).toBe(true); const reachable = new Set(); diff --git a/tests/unit/regressions.test.ts b/tests/unit/regressions.test.ts index cf166a2..6002fc9 100644 --- a/tests/unit/regressions.test.ts +++ b/tests/unit/regressions.test.ts @@ -465,7 +465,7 @@ describe('geometry lifetime', () => { open([dropped]); useEditor.getState().select('dropped'); useEditor.getState().deleteSelected(); - for (let i = 0; i < 39; i++) useEditor.getState().renameScene(`Name ${i}`); + for (let i = 0; i < 119; i++) useEditor.getState().renameScene(`Name ${i}`); expect(disposed).not.toHaveBeenCalled(); useEditor.getState().renameScene('One more'); expect(disposed).toHaveBeenCalledTimes(1); diff --git a/tests/unit/sculpt-benchmark.test.ts b/tests/unit/sculpt-benchmark.test.ts index 81c4b5b..d0b6aaa 100644 --- a/tests/unit/sculpt-benchmark.test.ts +++ b/tests/unit/sculpt-benchmark.test.ts @@ -12,6 +12,8 @@ import { Vector3, } from 'three'; import { MeshBVH } from 'three-mesh-bvh'; +import { geometryBytes } from '../../src/core/history-budget'; +import { useEditor } from '../../src/core/store'; import { SculptMesh } from '../../src/core/sculpt-mesh'; const enabled = process.env.KITBASHER_SCULPT_BENCH; @@ -144,3 +146,80 @@ it.skipIf(!enabled)('profiles cooperative wide dabs on a dense mesh', () => { JSON.stringify(measurements, null, 2), ); }); + +it.skipIf(!enabled)('profiles 120 consecutive committed sculpt strokes', () => { + const editor = useEditor.getState; + const original = editor(); + const geometry = new PlaneGeometry(100, 100, 180, 180); + const durations: number[] = []; + try { + editor().setScene({ + name: 'Benchmark', + joints: [], + parts: [ + { + id: 'p', + name: 'Plane', + geometry, + position: [0, 0, 0], + quaternion: [0, 0, 0, 1], + scale: [1, 1, 1], + color: '#ffffff', + visible: true, + locked: false, + source: 'benchmark', + }, + ], + }); + editor().select('p'); + expect(editor().startSculpt()).toBe(true); + for (let i = 0; i < 120; i++) { + const part = editor().scene.parts[0]; + const commit = timed(() => { + const draft = new SculptMesh(part.geometry, new Matrix4()); + const changed = draft.dab({ + point: new Vector3(), + normal: new Vector3(0, 0, 1), + face: 32580, + radius: 1.5, + strength: 0.005, + detail: 0, + minEdge: 10, + brush: 'draw', + falloff: 'soft', + }); + return ( + changed && + editor().commitSculpt({ + ...part, + partId: part.id, + source: part.geometry, + epoch: editor().sceneEpoch, + geometry: draft.finish(), + mask: null, + }) + ); + }); + expect(commit.result).toBe(true); + if (i >= 10) durations.push(commit.ms); + } + durations.sort((a, b) => a - b); + const history = editor().past.map((scene) => scene.parts[0].geometry); + writeFileSync( + join(tmpdir(), 'kitbasher-sculpt-history.json'), + JSON.stringify( + { + triangles: geometry.index!.count / 3, + historySteps: history.length, + historyArrayBytes: geometryBytes(history), + medianStrokeMs: durations[Math.floor(durations.length / 2)], + p95StrokeMs: durations[Math.ceil(durations.length * 0.95) - 1], + }, + null, + 2, + ), + ); + } finally { + useEditor.setState(original); + } +}); diff --git a/tests/unit/sculpt-history.test.ts b/tests/unit/sculpt-history.test.ts new file mode 100644 index 0000000..a559787 --- /dev/null +++ b/tests/unit/sculpt-history.test.ts @@ -0,0 +1,155 @@ +import { BufferAttribute, BufferGeometry } from 'three'; +import { afterEach, expect, it, vi } from 'vitest'; +import { SharedDocument } from '../../mcp/document'; +import { geometryBytes, trimHistory } from '../../src/core/history-budget'; +import { packArray } from '../../src/core/sculpt-history'; +import { useEditor } from '../../src/core/store'; +import type { Part, SceneDocument } from '../../src/core/types'; + +const store = useEditor.getState; +const initial = store(); + +function surface(): SceneDocument { + const geometry = new BufferGeometry(); + geometry.setAttribute('position', new BufferAttribute(new Float32Array(24_576), 3)); + const part: Part = { + id: 'part', + name: 'part', + geometry, + position: [0, 0, 0], + quaternion: [0, 0, 0, 1], + scale: [1, 1, 1], + color: '#ffffff', + visible: true, + locked: false, + source: 'test', + }; + return { name: 'Test', joints: [], parts: [part] }; +} + +function edit(part: Part, stroke: number) { + const geometry = part.geometry.clone(); + geometry.attributes.position.setX(stroke * 47, stroke); + return geometry; +} + +afterEach(() => { + vi.restoreAllMocks(); + useEditor.setState(initial); +}); + +it('restores all 120 sculpt strokes and masks with less storage than 40 full meshes', () => { + const scene = surface(); + store().setScene(scene); + store().select('part'); + expect(store().startSculpt()).toBe(true); + const ids = [scene.parts[0].geometry.uuid]; + for (let i = 1; i <= 120; i++) { + const part = store().scene.parts[0]; + const geometry = edit(part, i); + const mask = store().sculpt!.mask?.slice() ?? new Float32Array(8192); + mask[i] = 0.5; + expect( + store().commitSculpt({ + ...part, + partId: part.id, + source: part.geometry, + geometry, + mask, + epoch: store().sceneEpoch, + }), + ).toBe(true); + ids.push(geometry.uuid); + } + const history = store().past.map((s) => s.parts[0].geometry); + expect(history).toHaveLength(120); + expect(geometryBytes(history)).toBeLessThan(40 * geometryBytes([scene.parts[0].geometry])); + expect(store().sculpt!.past).toHaveLength(120); + // Force the cold restoration path even on runners that have not collected a retired mesh. + vi.spyOn(WeakRef.prototype, 'deref').mockReturnValue(undefined); + function check(i: number) { + const geometry = store().scene.parts[0].geometry; + expect(geometry.uuid).toBe(ids[i]); + expect(geometry.attributes.position.getX(i * 47)).toBe(i); + expect(geometry.attributes.position.getX((i + 1) * 47)).toBe(0); + const mask = store().sculpt!.mask; + if (i === 0) expect(mask).toBeNull(); + else { + expect(mask![i]).toBe(0.5); + expect(mask![i + 1]).toBe(0); + } + } + for (let i = 119; i >= 0; i--) { + store().undo(); + check(i); + } + for (let i = 1; i <= 120; i++) { + store().redo(); + check(i); + } + store().setTool('select'); + for (let i = 0; i < 120; i++) store().undo(); + expect(store().scene).toBe(scene); +}); + +it('preserves a shared author’s 120 strokes within the previous 40-mesh budget', () => { + const scene = surface(); + const doc = new SharedDocument(40 * geometryBytes([scene.parts[0].geometry])); + doc.replace(scene); + const ids = [scene.parts[0].geometry.uuid]; + for (let i = 1; i <= 120; i++) { + const part = doc.scene.parts[0]; + const geometry = edit(part, i); + doc.addMesh(geometry.uuid, geometry); + doc.apply('artist', { + base: doc.version, + epoch: doc.epoch, + checkpoint: true, + scene: { ...doc.scene, parts: [{ ...part, geometry }] }, + sculpt: { ...part, partId: part.id, source: part.geometry.uuid }, + }); + ids.push(geometry.uuid); + } + expect(doc.counts('artist').undo).toBe(120); + for (let i = 119; i >= 0; i--) { + expect(doc.undo('artist')?.changed).toBe(true); + expect(doc.scene.parts[0].geometry.uuid).toBe(ids[i]); + } + for (let i = 1; i <= 120; i++) { + expect(doc.redo('artist')?.changed).toBe(true); + expect(doc.mesh(ids[i])).toBe(doc.scene.parts[0].geometry); + } +}); + +it('restores changed topology and raw attribute bits after buffers are collected', () => { + const initial = new Uint16Array(4097); + const longer = new Uint16Array(4111); + longer.set(initial); + longer[17] = 9; + longer[4110] = 73; + const first = packArray(longer, initial); + const shorter = longer.slice(0, 4100); + shorter[3000] = 21; + const second = packArray(shorter, longer, first); + const bits = new Uint32Array(8192); + bits[811] = 0x7fc00005; + bits[1001] = 0x80000000; + const floats = packArray(new Float32Array(bits.buffer), new Float32Array(bits.length)); + vi.spyOn(WeakRef.prototype, 'deref').mockReturnValue(undefined); + expect(first.restore()).toEqual(longer); + expect(second.restore()).toEqual(shorter); + expect(new Uint32Array(floats.restore().buffer)).toEqual(bits); +}); + +it('charges shared backing buffers once, including views with different offsets', () => { + const geometry = new BufferGeometry(); + const buffer = new ArrayBuffer(4096); + geometry.setAttribute('position', new BufferAttribute(new Float32Array(buffer, 0, 9), 3)); + geometry.setIndex(new BufferAttribute(new Uint16Array(buffer, 64, 3), 1)); + const scene = surface(); + const views = { ...scene, parts: [{ ...scene.parts[0], geometry }] }; + const keep = [{ ...scene, parts: [] }]; + const fullCost = geometryBytes([scene.parts[0].geometry]) + buffer.byteLength; + expect(trimHistory([views, scene], [], keep, fullCost).trimmed).toBe(false); + expect(trimHistory([views, scene], [], keep, fullCost - 1).past).toEqual([scene]); +}); diff --git a/tests/unit/warp-session.test.ts b/tests/unit/warp-session.test.ts index e4fdb5f..78f045b 100644 --- a/tests/unit/warp-session.test.ts +++ b/tests/unit/warp-session.test.ts @@ -1257,7 +1257,7 @@ describe('warp points, close gap and apply', () => { move(addAt(partOf('a'), 0, 0).id, [0, 0, 2]); editor().applyWarp(); const second = partOf('a').geometry; - for (let i = 0; i < 40; i++) editor().patchParts(['a'], { name: `Plate ${i}` }); + for (let i = 0; i < 120; i++) editor().patchParts(['a'], { name: `Plate ${i}` }); expect(source).toEqual([{ index: null, names: ['normal', 'position', 'uv'] }]); expect(second.index).toBe(index); expect(second.getAttribute('color')).toBe(color);