Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Sculpt Timeline core: the undo history as a branching tree with fast seeking, re-tune and a .sfhist sidecar
islandmede87bfab96ce1
diff --git a/CMakeLists.txt b/CMakeLists.txtindex ff6dc1f0..b50f484c 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -36,6 +36,7 @@ add_library(sculptforge_core STATICsrc/core/Dyntopo.cppsrc/core/DyntopoCommands.cppsrc/core/Undo.cpp+ src/core/Timeline.cppsrc/core/Primitives.cppsrc/core/Document.cppsrc/core/Commands.cppdiff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex 5af26762..bda7341e 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -26,6 +26,7 @@#include "core/Sculptable.h"#include "core/Splats.h"#include "core/TextureTransfer.h"+#include "core/Timeline.h"#include "core/Voxel.h"#include "io/FbxIO.h"#include "io/GltfIO.h"@@ -774,6 +775,7 @@ CommandRegistry::CommandRegistry() {registerTransformCommands(*this); // transform (core/MeshTransform.h)registerExtractMirrorCommands(*this); // extract, mirror_and_weld, mirror (core/ExtractMirror.h)registerPerformanceCommands(*this); // perf_info, set_multithreading (core/Benchmark.cpp)+ registerTimelineCommands(*this); // timeline_info / seek / select / retune / save / load (core/Timeline.h)registerPaintCommands(*this); // core/Polypaint.cppregisterGozCommands(*this); // goz_import/export/send/receive, export_stl (io/GozCommands.cpp)registerBlenderCommands(*this); // blender_send/receive (io/BlenderCommands.cpp)diff --git a/src/core/Project.cpp b/src/core/Project.cppindex eb4418dd..630eaefa 100644--- a/src/core/Project.cpp+++ b/src/core/Project.cpp@@ -1,6 +1,7 @@// SculptForge - open source digital sculpting// SPDX-License-Identifier: GPL-3.0-or-later#include "core/Project.h"+#include "core/Timeline.h"#include "core/Multires.h"@@ -1048,6 +1049,7 @@ bool loadProjectThumbnail(const std::string& path, Image& out, std::string& erroCommandResult openProjectCommand(Document& doc, const std::string& path) {std::string err;if (!loadProject(path, doc, err)) return {false, err};+ const int histories = loadHistorySidecar(doc, path); // the Sculpt Timeline saved beside it, if it matchesstd::string msg = "Opened project " + path + " (";if (doc.subtoolCount() > 1) msg += std::to_string(doc.subtoolCount()) + " SubTools, ";size_t tris = 0, layers = 0;@@ -1058,6 +1060,7 @@ CommandResult openProjectCommand(Document& doc, const std::string& path) {msg += std::to_string(tris) + " triangles";if (layers) msg += ", " + std::to_string(layers) + " layers";if (!doc.splats.empty()) msg += ", " + std::to_string(doc.splats.size()) + " splats";+ if (histories > 0) msg += ", with its history";return {true, msg + ")"};}@@ -1079,6 +1082,9 @@ void registerProjectCommands(CommandRegistry& registry) {if (!saveProject(path, doc, err)) return {false, err};doc.path = path;doc.markClean();+ // The Sculpt Timeline's history beside it (<name>.sfhist), when the app asks for it.+ if (Timeline::saveWithProject && !saveHistorySidecar(doc, path, &err))+ return {true, "Saved project " + path + " (the history wasn't saved: " + err + ")"};return {true, "Saved project " + path};}});registry.add({"open_project", "Open a SculptForge project (.sfproj), replacing the current scene.",diff --git a/src/core/Timeline.cpp b/src/core/Timeline.cppnew file mode 100644index 00000000..e19fdb2c--- /dev/null+++ b/src/core/Timeline.cpp@@ -0,0 +1,1127 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/Timeline.h"++#include "core/Commands.h"+#include "core/Document.h"+#include "core/IndexBits.h"+#include "core/ThreadPool.h"++#include <algorithm>+#include <chrono>+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <filesystem>+#include <fstream>+#include <sstream>++namespace sf {++namespace {++using Clock = std::chrono::steady_clock;++double unixNow() {+ return std::chrono::duration<double>(std::chrono::system_clock::now().time_since_epoch()).count();+}++// Shared scratch set for a seek's moved vertices (one seek at a time: the main thread).+IndexBits& batchBits() {+ static IndexBits bits;+ return bits;+}++void gather(const std::vector<glm::vec3>& from, const std::vector<uint32_t>& idx, std::vector<glm::vec3>& out) {+ out.resize(idx.size());+ poolFor(idx.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) out[i] = from[idx[i]];+ }, 1 << 14);+}++void scatter(std::vector<glm::vec3>& to, const std::vector<uint32_t>& idx, const std::vector<glm::vec3>& values) {+ poolFor(idx.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) to[idx[i]] = values[i];+ }, 1 << 14);+}++size_t vecBytes(const std::vector<glm::vec3>& v) { return v.capacity() * sizeof(glm::vec3); }++} // namespace++// ---------------------------------------------------------------------------------------------------------------+// The tree++Timeline::Kind Timeline::classify(const UndoRecord& r) {+ if (r.subdiv || r.mesh || r.topology || r.subtool) return Kind::Topology;+ if (!r.positions.empty()) return Kind::Stroke;+ if (!r.mask.empty()) return Kind::Mask;+ if (!r.colors.empty() || r.paint || r.texture || r.textureTiles) return Kind::Paint;+ if (!r.hidden.empty() || !r.polygroups.empty()) return Kind::Visibility;+ return Kind::Other;+}++bool Timeline::fastShape(const UndoRecord& r) {+ return !r.positions.empty() && r.layer == -1 && r.layerOffsets.empty() && r.mask.empty() && r.colors.empty() &&+ r.paintAlpha.empty() && !r.paint && r.hidden.empty() && r.polygroups.empty() && !r.textureTiles &&+ !r.texture && !r.mesh && !r.subdiv && !r.topology && !r.subtool;+}++void Timeline::reset() {+ nodes_.clear();+ checkpoints_.clear();+ nodes_.emplace_back();+ nodes_[0].kind = Kind::Start;+ nodes_[0].label = "Start";+ nodes_[0].time = unixNow();+ path_.assign(1, 0);+ cursor_ = 0;+}++uint32_t Timeline::newNode(uint32_t parent, const UndoRecord* r) {+ const uint32_t id = uint32_t(nodes_.size());+ nodes_.emplace_back();+ Node& n = nodes_.back();+ n.parent = parent;+ n.time = unixNow();+ if (r) {+ n.label = r->label.empty() ? "Edit" : r->label;+ n.kind = classify(*r);+ n.touched = uint32_t(std::max({r->positions.indices.size(), r->mask.indices.size(), r->colors.indices.size(),+ r->hidden.indices.size(), r->polygroups.indices.size()}));+ }+ if (parent != kNone) {+ nodes_[parent].children.push_back(id);+ nodes_[parent].activeChild = id;+ }+ return id;+}++std::shared_ptr<Timeline> Timeline::attach(Document& doc) {+ auto t = std::make_shared<Timeline>();+ t->reset();+ t->stack_ = &doc.undo;+ UndoStack& s = doc.undo;+ for (UndoRecord& r : s.undo_) t->path_.push_back(t->newNode(t->path_.back(), &r));+ t->cursor_ = s.undo_.size();+ for (auto it = s.redo_.rbegin(); it != s.redo_.rend(); ++it) t->path_.push_back(t->newNode(t->path_.back(), &*it));+ // Back to the cursor's branch: newNode made each new node its parent's active child already.+ doc.undo.listener = t;+ t->sync(doc);+ return t;+}++Timeline* Timeline::of(UndoStack& stack) { return dynamic_cast<Timeline*>(stack.listener.get()); }++bool Timeline::onPath(uint32_t id) const {+ if (id >= nodes_.size() || !nodes_[id].alive) return false;+ const int d = depth(id);+ return d >= 0 && size_t(d) < path_.size() && path_[size_t(d)] == id;+}++int Timeline::depth(uint32_t id) const {+ if (id >= nodes_.size()) return -1;+ int d = 0;+ for (uint32_t p = nodes_[id].parent; p != kNone; p = nodes_[p].parent) ++d;+ return d;+}++size_t Timeline::aliveCount() const {+ size_t n = 0;+ for (const Node& x : nodes_) n += x.alive;+ return n;+}++std::vector<Timeline::Branch> Timeline::branches() const {+ std::vector<Branch> out;+ for (size_t i = 0; i < path_.size(); ++i) {+ const Node& p = nodes_[path_[i]];+ for (uint32_t c : p.children) {+ if (!nodes_[c].alive || (i + 1 < path_.size() && path_[i + 1] == c)) continue;+ Branch b{c, i, 1, c};+ while (nodes_[b.tip].activeChild != kNone && nodes_[nodes_[b.tip].activeChild].alive) {+ b.tip = nodes_[b.tip].activeChild;+ ++b.length;+ }+ out.push_back(b);+ }+ }+ return out;+}++UndoRecord* Timeline::recordOf(uint32_t id) {+ if (id >= nodes_.size() || !nodes_[id].alive || nodes_[id].parent == kNone) return nullptr;+ if (nodes_[id].stored) return nodes_[id].stored.get();+ if (!stack_) return nullptr;+ const int d = depth(id);+ if (d <= 0 || size_t(d) >= path_.size() || path_[size_t(d)] != id) return nullptr;+ const size_t i = size_t(d);+ if (i <= cursor_) return i - 1 < stack_->undo_.size() ? &stack_->undo_[i - 1] : nullptr;+ const size_t k = i - cursor_ - 1; // 0 = the next redo+ return k < stack_->redo_.size() ? &stack_->redo_[stack_->redo_.size() - 1 - k] : nullptr;+}++void Timeline::freeSubtree(uint32_t id) {+ std::vector<uint32_t> todo{id};+ while (!todo.empty()) {+ const uint32_t x = todo.back();+ todo.pop_back();+ Node& n = nodes_[x];+ for (uint32_t c : n.children) todo.push_back(c);+ n.alive = false;+ n.children.clear();+ n.activeChild = kNone;+ n.stored.reset();+ std::vector<glm::vec3>().swap(n.other);+ std::vector<glm::vec3>().swap(n.retuneDelta);+ n.fast = false;+ checkpoints_.erase(x);+ }+ const uint32_t p = nodes_[id].parent;+ if (p != kNone) {+ auto& ch = nodes_[p].children;+ ch.erase(std::remove(ch.begin(), ch.end(), id), ch.end());+ if (nodes_[p].activeChild == id) nodes_[p].activeChild = ch.empty() ? kNone : ch.back();+ }+}++// ---------------------------------------------------------------------------------------------------------------+// Following the undo stack++void Timeline::undoPushed(UndoRecord& pushed, std::deque<UndoRecord>& discardedRedo) {+ // The redo steps become an inactive branch: redo.back() is path_[cursor_ + 1].+ const size_t n = discardedRedo.size();+ for (size_t k = 0; k < n && cursor_ + 1 + k < path_.size(); ++k)+ nodes_[path_[cursor_ + 1 + k]].stored = std::make_unique<UndoRecord>(std::move(discardedRedo[n - 1 - k]));+ path_.resize(cursor_ + 1);+ path_.push_back(newNode(path_.back(), &pushed));+ ++cursor_;+ enforceBudgets();+}++void Timeline::captureFrom(Node& n, const UndoRecord& r, Mesh& mesh) {+ n.captured = true;+ const auto& idx = r.positions.indices;+ uint32_t maxIndex = 0;+ for (uint32_t v : idx) maxIndex = std::max(maxIndex, v);+ if (idx.empty() || maxIndex >= mesh.vertexCount()) return;+ glm::vec3 lo(1e30f), hi(-1e30f); // bounds of the stroke after it+ for (uint32_t v : idx) {+ lo = glm::min(lo, mesh.positions[v]);+ hi = glm::max(hi, mesh.positions[v]);+ }+ n.center = (lo + hi) * 0.5f;+ n.radius = glm::length(hi - lo) * 0.5f;+ if (fastShape(r) && mesh.layers.empty()) {+ gather(mesh.positions, idx, n.other);+ n.fast = true;+ }+}++void Timeline::capture(Mesh& mesh) {+ if (cursor_ == 0 || cursor_ >= path_.size() || !stack_ || cursor_ - 1 >= stack_->undo_.size()) return;+ captureFrom(nodes_[path_[cursor_]], stack_->undo_[cursor_ - 1], mesh);+}++void Timeline::undoApplying(UndoRecord& r, Mesh& mesh, bool isUndo) {+ // A step about to be undone: bring its "after" values in while the mesh still shows them.+ if (isUndo && cursor_ > 0 && !nodes_[path_[cursor_]].captured) captureFrom(nodes_[path_[cursor_]], r, mesh);+}++void Timeline::undoApplied(UndoRecord& r, Mesh& mesh, bool isUndo) {+ if (isUndo) {+ if (cursor_ == 0) return;+ Node& n = nodes_[path_[cursor_]];+ if (n.fast) {+ if (mesh.layers.empty() && fastShape(r)) gather(mesh.positions, r.positions.indices, n.other); // now "before"+ else n.fast = false, std::vector<glm::vec3>().swap(n.other);+ }+ --cursor_;+ } else {+ if (cursor_ + 1 >= path_.size()) return;+ ++cursor_;+ Node& n = nodes_[path_[cursor_]];+ if (!n.captured) {+ captureFrom(n, r, mesh);+ } else if (mesh.layers.empty() && fastShape(r)) {+ gather(mesh.positions, r.positions.indices, n.other); // "after"+ n.fast = true;+ } else {+ n.fast = false;+ std::vector<glm::vec3>().swap(n.other);+ }+ }+}++void Timeline::undoDroppedOldest() {+ if (path_.size() < 2) return;+ const uint32_t oldRoot = path_[0], newRoot = path_[1];+ for (uint32_t c : std::vector<uint32_t>(nodes_[oldRoot].children))+ if (c != newRoot) freeSubtree(c);+ Node& o = nodes_[oldRoot];+ o.alive = false;+ o.children.clear();+ checkpoints_.erase(oldRoot);+ Node& n = nodes_[newRoot];+ n.parent = kNone;+ n.stored.reset();+ n.fast = false;+ std::vector<glm::vec3>().swap(n.other);+ std::vector<glm::vec3>().swap(n.retuneDelta);+ path_.erase(path_.begin());+ if (cursor_ > 0) --cursor_;+}++void Timeline::undoCleared() { reset(); }++void Timeline::sync(Document& doc) {+ stack_ = &doc.undo;+ if (doc.undo.listener.get() != this) return;+ // The stack and the tree should always agree; if something replaced the stack's steps behind our back,+ // start over from what the stack holds.+ if (path_.size() != doc.undo.undo_.size() + doc.undo.redo_.size() + 1 || cursor_ != doc.undo.undo_.size()) {+ reset();+ for (UndoRecord& r : doc.undo.undo_) path_.push_back(newNode(path_.back(), &r));+ cursor_ = doc.undo.undo_.size();+ for (auto it = doc.undo.redo_.rbegin(); it != doc.undo.redo_.rend(); ++it)+ path_.push_back(newNode(path_.back(), &*it));+ }+ if (cursor_ > 0) {+ Node& n = nodes_[path_[cursor_]];+ if (!n.captured) capture(doc.mesh);+ }+ maybeCheckpoint(doc.mesh);+}++// ---------------------------------------------------------------------------------------------------------------+// Checkpoints and budgets++size_t Timeline::checkpointBytes() const {+ size_t b = 0;+ for (const auto& [id, c] : checkpoints_) b += vecBytes(c);+ return b;+}++size_t Timeline::extraBytes() const {+ size_t b = 0;+ for (const Node& n : nodes_) {+ if (!n.alive) continue;+ b += vecBytes(n.other) + vecBytes(n.retuneDelta);+ if (n.stored) b += n.stored->approxBytes();+ }+ return b;+}++void Timeline::maybeCheckpoint(const Mesh& mesh) {+ const uint32_t id = path_[cursor_];+ if (checkpoints_.count(id) || cursor_ % std::max<size_t>(checkpointEvery, 1) != 0 || !mesh.layers.empty() ||+ mesh.vertexCount() == 0)+ return;+ if (cursor_ > 0 && !nodes_[id].fast) return; // a checkpoint helps runs of fast steps+ const size_t bytes = mesh.vertexCount() * sizeof(glm::vec3);+ if (bytes > checkpointBudget) return;+ std::vector<glm::vec3> copy(mesh.vertexCount());+ poolFor(copy.size(), [&](size_t b, size_t e) { std::memcpy(©[b], &mesh.positions[b], (e - b) * sizeof(glm::vec3)); },+ 1 << 18);+ checkpoints_[id] = std::move(copy);+ enforceBudgets();+}++void Timeline::enforceBudgets() {+ // Checkpoints: thin them out by doubling the interval, then drop the deepest ones off the active branch.+ while (checkpointBytes() > checkpointBudget && !checkpoints_.empty()) {+ checkpointEvery = std::max<size_t>(checkpointEvery, 1) * 2;+ bool dropped = false;+ for (auto it = checkpoints_.begin(); it != checkpoints_.end();) {+ const int d = depth(it->first);+ if (d > 0 && size_t(d) % checkpointEvery != 0) {+ it = checkpoints_.erase(it);+ dropped = true;+ } else {+ ++it;+ }+ }+ if (!dropped && checkpointBytes() > checkpointBudget) {+ // Even the multiples don't fit: keep the shallowest.+ uint32_t deepest = checkpoints_.begin()->first;+ for (const auto& [id, c] : checkpoints_)+ if (depth(id) > depth(deepest)) deepest = id;+ checkpoints_.erase(deepest);+ }+ }+ // Inactive branches and `other` copies: the oldest branches go first, then the oldest steps' copies (those+ // steps are then walked by the undo stack instead).+ size_t extra = extraBytes();+ if (extra <= branchBudget) return;+ std::vector<Branch> bs = branches();+ std::sort(bs.begin(), bs.end(), [&](const Branch& a, const Branch& b) { return nodes_[a.first].time < nodes_[b.first].time; });+ for (const Branch& b : bs) {+ if (extra <= branchBudget) break;+ freeSubtree(b.first);+ extra = extraBytes();+ }+ for (size_t i = 1; i < path_.size() && extra > branchBudget; ++i) {+ Node& n = nodes_[path_[i]];+ if (!n.fast) continue;+ extra -= std::min(extra, vecBytes(n.other));+ n.fast = false;+ std::vector<glm::vec3>().swap(n.other);+ }+}++// ---------------------------------------------------------------------------------------------------------------+// Travel++void Timeline::flushBatch(Document& doc) {+ if (batch_.empty()) return;+ const auto t0 = Clock::now();+ struct Done {+ Clock::time_point t0;+ double& ms;+ ~Done() { ms += std::chrono::duration<double, std::milli>(Clock::now() - t0).count(); }+ } done{t0, flushMs_};+ Mesh& mesh = doc.mesh;+ IndexBits& bits = batchBits();+ if (bits.capacity() < mesh.vertexCount()) bits.resize(mesh.vertexCount());+ std::vector<uint32_t> verts;+ for (uint32_t v : batch_) bits.insertLocal(v);+ bits.take(verts);+ batch_.clear();+ // Normals: the parallel update unless nearly everything moved (Mesh::recomputeAllNormals sums serially).+ if (verts.size() * 10 > mesh.vertexCount() * 9) mesh.recomputeAllNormals();+ else mesh.updateNormals(verts);+ // Refits only grow boxes: after moving much of the mesh, tighten the whole tree (as UndoStack::apply does).+ if (verts.size() * 4 > mesh.vertexCount()) doc.bvh.refitAll(mesh);+ else doc.bvh.refit(mesh, verts);+}++namespace {+bool fastUsable(const Timeline::Node& n, const UndoRecord* r, const Mesh& mesh) {+ if (!n.fast || !r || !Timeline::fastShape(*r) || !mesh.layers.empty()) return false;+ if (n.other.size() != r->positions.indices.size()) return false;+ for (uint32_t v : r->positions.indices) // (cheap next to the copy below)+ if (v >= mesh.vertexCount()) return false;+ return true;+}+} // namespace++void Timeline::walkTo(Document& doc, size_t index) {+ UndoStack& s = doc.undo;+ Mesh& mesh = doc.mesh;+ while (cursor_ > index) {+ Node& n = nodes_[path_[cursor_]];+ UndoRecord* r = s.undo_.empty() ? nullptr : &s.undo_.back();+ if (fastUsable(n, r, mesh)) {+ scatter(mesh.positions, r->positions.indices, r->positions.values); // "before"+ std::swap(r->positions.values, n.other); // the record now holds "after"+ batch_.insert(batch_.end(), r->positions.indices.begin(), r->positions.indices.end());+ s.redo_.push_back(std::move(*r));+ s.undo_.pop_back();+ ++s.revision_;+ --cursor_;+ ++lastSeek_.batched;+ } else {+ flushBatch(doc);+ if (!s.undo(mesh, doc.bvh)) break;+ if (UndoRecord* u = s.lastRedo(); u && u->subtool) doc.applySubtoolStep(*u->subtool);+ ++lastSeek_.walked;+ }+ }+ while (cursor_ < index) {+ Node& n = nodes_[path_[cursor_ + 1]];+ UndoRecord* r = s.redo_.empty() ? nullptr : &s.redo_.back();+ if (fastUsable(n, r, mesh)) {+ scatter(mesh.positions, r->positions.indices, r->positions.values); // "after"+ std::swap(r->positions.values, n.other);+ batch_.insert(batch_.end(), r->positions.indices.begin(), r->positions.indices.end());+ s.undo_.push_back(std::move(*r));+ s.redo_.pop_back();+ ++s.revision_;+ ++cursor_;+ ++lastSeek_.batched;+ } else {+ flushBatch(doc);+ if (!s.redo(mesh, doc.bvh)) break;+ if (UndoRecord* u = s.lastUndo(); u && u->subtool) doc.applySubtoolStep(*u->subtool);+ ++lastSeek_.walked;+ }+ }+ flushBatch(doc);+}++bool Timeline::jumpWithCheckpoint(Document& doc, size_t index) {+ Mesh& mesh = doc.mesh;+ const size_t V = mesh.vertexCount();+ if (checkpoints_.empty() || index == cursor_ || !mesh.layers.empty()) return false;+ const size_t lo = std::min(index, cursor_), hi = std::max(index, cursor_);+ auto fastAt = [&](size_t i) { return fastUsable(nodes_[path_[i]], recordOf(path_[i]), mesh); };+ size_t walkCost = 0;+ for (size_t i = lo + 1; i <= hi; ++i) {+ if (!fastAt(i)) return false; // a slow step in between: walk+ walkCost += nodes_[path_[i]].other.size();+ }+ // The nearest usable checkpoint at or before the target.+ size_t from = std::string::npos, replayCost = 0;+ for (size_t p = index + 1; p-- > 0;) {+ if (p < index && !fastAt(p + 1)) break;+ if (p < index) replayCost += nodes_[path_[p + 1]].other.size();+ auto it = checkpoints_.find(path_[p]);+ if (it != checkpoints_.end() && it->second.size() == V) {+ from = p;+ break;+ }+ if (replayCost + V >= walkCost) return false;+ }+ if (from == std::string::npos || V + replayCost >= walkCost) return false;+ const std::vector<glm::vec3>& ck = checkpoints_[path_[from]];+ poolFor(V, [&](size_t b, size_t e) { std::memcpy(&mesh.positions[b], &ck[b], (e - b) * sizeof(glm::vec3)); }, 1 << 18);+ for (size_t j = from + 1; j <= index; ++j) {+ Node& n = nodes_[path_[j]];+ const UndoRecord* r = recordOf(path_[j]);+ scatter(mesh.positions, r->positions.indices, j <= cursor_ ? n.other : r->positions.values); // "after" values+ ++lastSeek_.replayed;+ }+ // The steps between move sides without touching the mesh: swap which vector the record holds.+ UndoStack& s = *stack_;+ while (cursor_ > index) {+ UndoRecord& r = s.undo_.back();+ std::swap(r.positions.values, nodes_[path_[cursor_]].other);+ s.redo_.push_back(std::move(r));+ s.undo_.pop_back();+ --cursor_;+ }+ while (cursor_ < index) {+ UndoRecord& r = s.redo_.back();+ std::swap(r.positions.values, nodes_[path_[cursor_ + 1]].other);+ s.undo_.push_back(std::move(r));+ s.redo_.pop_back();+ ++cursor_;+ }+ ++s.revision_;+ // Normals, the BVH and the GPU: only where the shape changed (the steps between the old and the new cursor).+ for (size_t j = lo + 1; j <= hi; ++j) {+ const UndoRecord* r = recordOf(path_[j]);+ batch_.insert(batch_.end(), r->positions.indices.begin(), r->positions.indices.end());+ }+ flushBatch(doc);+ lastSeek_.usedCheckpoint = true;+ return true;+}++bool Timeline::seek(Document& doc, size_t index, std::string* error) {+ if (doc.undo.listener.get() != this) {+ if (error) *error = "This timeline doesn't watch the document's history";+ return false;+ }+ sync(doc);+ if (index >= path_.size()) {+ if (error) *error = "No step " + std::to_string(index) + " on this branch (it has " + std::to_string(path_.size() - 1) + ")";+ return false;+ }+ const auto t0 = Clock::now();+ lastSeek_ = {};+ if (!jumpWithCheckpoint(doc, index)) walkTo(doc, index);+ lastSeek_.ms = std::chrono::duration<double, std::milli>(Clock::now() - t0).count();+ sync(doc);+ if (std::getenv("SF_TIMELINE_LOG"))+ std::fprintf(stderr, "timeline seek to %zu: %.1f ms (flush %.1f ms), then sync %.1f ms\n", index, lastSeek_.ms,+ flushMs_, std::chrono::duration<double, std::milli>(Clock::now() - t0).count() - lastSeek_.ms);+ flushMs_ = 0.0;+ if (cursor_ != index) {+ if (error) *error = "Stopped at step " + std::to_string(cursor_);+ return false;+ }+ return true;+}++bool Timeline::select(Document& doc, uint32_t id, std::string* error) {+ if (doc.undo.listener.get() != this) {+ if (error) *error = "This timeline doesn't watch the document's history";+ return false;+ }+ sync(doc);+ if (id >= nodes_.size() || !nodes_[id].alive) {+ if (error) *error = "No such step";+ return false;+ }+ if (onPath(id)) return seek(doc, size_t(depth(id)), error);+ std::vector<uint32_t> chain; // from the branch's first node to `id`+ uint32_t a = id;+ while (a != kNone && !onPath(a)) {+ chain.push_back(a);+ a = nodes_[a].parent;+ }+ if (a == kNone) {+ if (error) *error = "That step isn't connected to the history any more";+ return false;+ }+ std::reverse(chain.begin(), chain.end());+ const size_t ap = size_t(depth(a));+ if (!seek(doc, ap, error)) return false;+ UndoStack& s = doc.undo;+ // The current continuation becomes an inactive branch (all of it is redo steps now).+ const size_t n = path_.size() - 1 - ap;+ for (size_t k = 0; k < n && k < s.redo_.size(); ++k)+ nodes_[path_[ap + 1 + k]].stored = std::make_unique<UndoRecord>(std::move(s.redo_[s.redo_.size() - 1 - k]));+ s.redo_.clear();+ path_.resize(ap + 1);+ for (uint32_t c : chain) {+ nodes_[path_.back()].activeChild = c;+ path_.push_back(c);+ }+ for (uint32_t x = nodes_[id].activeChild; x != kNone && nodes_[x].alive; x = nodes_[x].activeChild) path_.push_back(x);+ for (size_t k = path_.size() - 1; k > ap; --k) {+ Node& node = nodes_[path_[k]];+ if (!node.stored) { // (shouldn't happen) cut the branch here+ path_.resize(k);+ s.redo_.clear();+ for (size_t j = path_.size() - 1; j > ap; --j) {+ s.redo_.push_back(std::move(*nodes_[path_[j]].stored));+ nodes_[path_[j]].stored.reset();+ }+ break;+ }+ s.redo_.push_back(std::move(*node.stored));+ node.stored.reset();+ }+ ++s.revision_;+ const int d = depth(id);+ if (d < 0 || size_t(d) >= path_.size()) {+ if (error) *error = "That branch couldn't be restored";+ return false;+ }+ return seek(doc, size_t(d), error);+}++bool Timeline::canRetune(uint32_t id, std::string* why) const {+ auto no = [&](const std::string& w) {+ if (why) *why = w;+ return false;+ };+ if (id >= nodes_.size() || !nodes_[id].alive || nodes_[id].parent == kNone) return no("Pick a stroke");+ const Node& n = nodes_[id];+ if (!onPath(id)) return no("Select the stroke's branch first");+ if (n.kind != Kind::Stroke) return no("Only sculpt strokes can be re-tuned");+ if (!n.fast) return no("This stroke can't be re-tuned (it was made on a sculpt layer, or its history was trimmed)");+ std::vector<uint32_t> todo(n.children.begin(), n.children.end());+ while (!todo.empty()) {+ const uint32_t x = todo.back();+ todo.pop_back();+ const UndoRecord* r = recordOf(x);+ if (!r) continue;+ if (r->mesh || r->topology || r->subdiv || r->subtool || !r->layerOffsets.empty() || (!r->positions.empty() && r->layer != -1))+ return no("A later step (\"" + nodes_[x].label + "\") changes the mesh as a whole; re-tuning would undo it");+ for (uint32_t c : nodes_[x].children) todo.push_back(c);+ }+ return true;+}++bool Timeline::retune(Document& doc, uint32_t id, float strength, std::string* error) {+ if (doc.undo.listener.get() != this) {+ if (error) *error = "This timeline doesn't watch the document's history";+ return false;+ }+ sync(doc);+ if (!canRetune(id, error)) return false;+ strength = std::clamp(strength, 0.0f, 4.0f);+ Node& n = nodes_[id];+ const float old = n.strength;+ if (std::abs(strength - old) < 1e-6f) return true;+ UndoRecord* r = recordOf(id);+ const size_t pos = size_t(depth(id));+ const bool applied = pos <= cursor_; // the mesh shows this stroke+ std::vector<glm::vec3>& before = applied ? r->positions.values : n.other;+ std::vector<glm::vec3>& after = applied ? n.other : r->positions.values;+ const auto& idx = r->positions.indices;+ if (n.retuneDelta.empty()) { // first re-tune: the stroke's own delta at strength 1 (old is 1 then)+ n.retuneDelta.resize(idx.size());+ for (size_t i = 0; i < idx.size(); ++i) n.retuneDelta[i] = after[i] - before[i];+ }+ std::vector<glm::vec3> d(idx.size());+ for (size_t i = 0; i < idx.size(); ++i) d[i] = (strength - old) * n.retuneDelta[i];+ for (size_t i = 0; i < idx.size(); ++i) after[i] += d[i];+ // Where later steps overlap the stroke, their stored positions move with it (both sides).+ std::vector<std::pair<uint32_t, uint32_t>> sorted(idx.size());+ for (size_t i = 0; i < idx.size(); ++i) sorted[i] = {idx[i], uint32_t(i)};+ std::sort(sorted.begin(), sorted.end());+ auto lookup = [&](uint32_t v) -> int64_t {+ auto it = std::lower_bound(sorted.begin(), sorted.end(), std::make_pair(v, uint32_t(0)));+ return it != sorted.end() && it->first == v ? int64_t(it->second) : -1;+ };+ std::vector<uint32_t> todo(n.children.begin(), n.children.end());+ while (!todo.empty()) {+ const uint32_t x = todo.back();+ todo.pop_back();+ for (uint32_t c : nodes_[x].children) todo.push_back(c);+ UndoRecord* rx = recordOf(x);+ if (!rx || rx->positions.empty()) continue;+ Node& nx = nodes_[x];+ const auto& ix = rx->positions.indices;+ const bool hasOther = nx.fast && nx.other.size() == ix.size();+ poolFor(ix.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) {+ const int64_t k = lookup(ix[i]);+ if (k < 0) continue;+ rx->positions.values[i] += d[size_t(k)];+ if (hasOther) nx.other[i] += d[size_t(k)];+ }+ }, 1 << 14);+ }+ // Checkpoints at or after the stroke.+ for (auto& [cid, ck] : checkpoints_) {+ bool below = false;+ for (uint32_t p = cid; p != kNone; p = nodes_[p].parent)+ if (p == id) {+ below = true;+ break;+ }+ if (!below) continue;+ for (size_t i = 0; i < idx.size(); ++i)+ if (idx[i] < ck.size()) ck[idx[i]] += d[i];+ }+ if (applied) {+ Mesh& mesh = doc.mesh;+ for (size_t i = 0; i < idx.size(); ++i) mesh.positions[idx[i]] += d[i];+ mesh.updateNormals(idx);+ doc.bvh.refit(mesh, idx);+ }+ n.strength = strength;+ ++doc.undo.revision_;+ return true;+}++// ---------------------------------------------------------------------------------------------------------------+// Saving++namespace {++constexpr char kMagic[8] = {'S', 'F', 'H', 'I', 'S', 'T', '1', '\0'};+constexpr char kSidecarMagic[8] = {'S', 'F', 'H', 'I', 'S', 'T', 'S', '\0'};+constexpr uint32_t kVersion = 1;++struct Writer {+ std::vector<uint8_t>& out;+ template <class T>+ void pod(const T& v) {+ const auto* p = reinterpret_cast<const uint8_t*>(&v);+ out.insert(out.end(), p, p + sizeof(T));+ }+ template <class T>+ void vec(const std::vector<T>& v) {+ pod(uint64_t(v.size()));+ const auto* p = reinterpret_cast<const uint8_t*>(v.data());+ out.insert(out.end(), p, p + v.size() * sizeof(T));+ }+ void str(const std::string& s) {+ pod(uint32_t(s.size()));+ out.insert(out.end(), s.begin(), s.end());+ }+};++struct Reader {+ const uint8_t* p;+ const uint8_t* end;+ bool ok = true;+ template <class T>+ T pod() {+ T v{};+ if (size_t(end - p) < sizeof(T)) {+ ok = false;+ return v;+ }+ std::memcpy(&v, p, sizeof(T));+ p += sizeof(T);+ return v;+ }+ template <class T>+ void vec(std::vector<T>& v) {+ const uint64_t n = pod<uint64_t>();+ if (!ok || n > uint64_t(end - p) / sizeof(T)) {+ ok = false;+ return;+ }+ v.resize(size_t(n));+ std::memcpy(v.data(), p, size_t(n) * sizeof(T));+ p += n * sizeof(T);+ }+ std::string str() {+ const uint32_t n = pod<uint32_t>();+ if (!ok || n > uint64_t(end - p)) {+ ok = false;+ return {};+ }+ std::string s(reinterpret_cast<const char*>(p), n);+ p += n;+ return s;+ }+};++bool savable(const UndoRecord& r) {+ return !r.mesh && !r.subdiv && !r.topology && !r.subtool && !r.texture && !r.textureTiles && !r.paint &&+ r.layerOffsets.empty() && r.layer == -1 && r.paintLayer == -1 && r.paintAlpha.empty();+}++template <class T>+void writeChannel(Writer& w, const UndoChannel<T>& c) {+ w.vec(c.indices);+ w.vec(c.values);+}+template <class T>+bool readChannel(Reader& rd, UndoChannel<T>& c) {+ rd.vec(c.indices);+ rd.vec(c.values);+ return rd.ok && c.indices.size() == c.values.size();+}++template <class T>+bool channelInRange(const UndoChannel<T>& c, size_t n) {+ for (uint32_t i : c.indices)+ if (i >= n) return false;+ return true;+}++} // namespace++// A fingerprint of the mesh a history belongs to.+static uint64_t meshFingerprint(const Mesh& mesh) {+ const size_t n = mesh.vertexCount();+ const size_t blocks = (n + (1 << 16) - 1) >> 16;+ std::vector<uint64_t> part(blocks, 0);+ poolFor(n, [&](size_t b, size_t e) {+ uint64_t h = 1469598103934665603ull;+ const auto* p = reinterpret_cast<const uint32_t*>(&mesh.positions[b]);+ for (size_t i = 0; i < (e - b) * 3; ++i) h = (h ^ p[i]) * 1099511628211ull;+ part[b >> 16] = h;+ }, 1 << 16);+ uint64_t h = 1469598103934665603ull ^ n ^ (uint64_t(mesh.triangleCount()) << 32);+ for (uint64_t x : part) h = (h ^ x) * 1099511628211ull;+ return h;+}++bool Timeline::save(std::vector<uint8_t>& out, const Mesh& mesh, std::string* error) const {+ // Which nodes can go in: the path from the newest unsavable step at or before the cursor, up to the first+ // unsavable one after it, and the branches off it that are savable all the way.+ auto ok = [&](uint32_t id) {+ const UndoRecord* r = recordOf(id);+ return r && savable(*r);+ };+ size_t first = 0;+ for (size_t i = 1; i <= cursor_; ++i)+ if (!ok(path_[i])) first = i;+ size_t last = cursor_;+ while (last + 1 < path_.size() && ok(path_[last + 1])) ++last;+ std::vector<uint32_t> order; // parents before children+ std::map<uint32_t, uint32_t> local;+ for (size_t i = first; i <= last; ++i) {+ local[path_[i]] = uint32_t(order.size());+ order.push_back(path_[i]);+ }+ for (size_t i = first; i <= last; ++i) { // inactive branches+ std::vector<uint32_t> todo;+ for (uint32_t c : nodes_[path_[i]].children)+ if (!local.count(c)) todo.push_back(c);+ while (!todo.empty()) {+ const uint32_t x = todo.back();+ todo.pop_back();+ if (!nodes_[x].alive || !ok(x)) continue;+ local[x] = uint32_t(order.size());+ order.push_back(x);+ for (uint32_t c : nodes_[x].children) todo.push_back(c);+ }+ }+ if (order.size() < 2) {+ if (error) *error = "Nothing in the history can be saved";+ return false;+ }+ out.clear();+ Writer w{out};+ out.insert(out.end(), kMagic, kMagic + 8);+ w.pod(kVersion);+ w.pod(uint64_t(mesh.vertexCount()));+ w.pod(uint64_t(mesh.triangleCount()));+ w.pod(meshFingerprint(mesh));+ w.pod(uint32_t(order.size()));+ w.pod(uint32_t(cursor_ - first)); // the cursor's local index (path nodes come first, in order)+ w.pod(uint32_t(last - first + 1)); // how many of the first nodes are the active branch+ for (size_t k = 0; k < order.size(); ++k) {+ const Node& n = nodes_[order[k]];+ const uint32_t parent = k == 0 ? kNone : local.at(n.parent);+ const uint32_t active = n.activeChild != kNone && local.count(n.activeChild) ? local.at(n.activeChild) : kNone;+ w.pod(parent);+ w.pod(active);+ w.pod(uint8_t(k == 0 ? Kind::Start : n.kind));+ w.pod(n.time);+ w.pod(n.strength);+ w.pod(n.touched);+ w.pod(n.center);+ w.pod(n.radius);+ w.str(k == 0 ? std::string("Start") : n.label);+ if (k == 0) continue;+ const UndoRecord& r = *recordOf(order[k]);+ writeChannel(w, r.positions);+ writeChannel(w, r.mask);+ writeChannel(w, r.colors);+ writeChannel(w, r.hidden);+ writeChannel(w, r.polygroups);+ w.pod(uint8_t(n.fast));+ if (n.fast) w.vec(n.other);+ w.vec(n.retuneDelta);+ }+ return true;+}++bool Timeline::load(Document& doc, const std::vector<uint8_t>& in, std::string* error) {+ auto fail = [&](const std::string& e) {+ if (error) *error = e;+ return false;+ };+ if (in.size() < 8 || std::memcmp(in.data(), kMagic, 8) != 0) return fail("Not a SculptForge history");+ Reader rd{in.data() + 8, in.data() + in.size()};+ if (rd.pod<uint32_t>() != kVersion) return fail("This history was saved by a newer SculptForge");+ const Mesh& mesh = doc.mesh;+ const uint64_t verts = rd.pod<uint64_t>(), tris = rd.pod<uint64_t>(), print = rd.pod<uint64_t>();+ if (!rd.ok || verts != mesh.vertexCount() || tris != mesh.triangleCount() || print != meshFingerprint(mesh))+ return fail("The history belongs to a different version of this mesh");+ const uint32_t count = rd.pod<uint32_t>(), cursor = rd.pod<uint32_t>(), pathLen = rd.pod<uint32_t>();+ if (!rd.ok || count < 2 || pathLen < 1 || pathLen > count || cursor >= pathLen) return fail("The history file is damaged");+ auto t = std::make_shared<Timeline>();+ t->nodes_.resize(count);+ std::vector<std::unique_ptr<UndoRecord>> records(count);+ for (uint32_t k = 0; k < count; ++k) {+ Node& n = t->nodes_[k];+ n.parent = rd.pod<uint32_t>();+ n.activeChild = rd.pod<uint32_t>();+ n.kind = Kind(rd.pod<uint8_t>());+ n.time = rd.pod<double>();+ n.strength = rd.pod<float>();+ n.touched = rd.pod<uint32_t>();+ n.center = rd.pod<glm::vec3>();+ n.radius = rd.pod<float>();+ n.label = rd.str();+ if (!rd.ok || (k == 0) != (n.parent == kNone) || (k > 0 && n.parent >= k) ||+ (n.activeChild != kNone && n.activeChild >= count))+ return fail("The history file is damaged");+ if (k > 0) t->nodes_[n.parent].children.push_back(k);+ if (k == 0) continue;+ auto r = std::make_unique<UndoRecord>();+ r->label = n.label;+ bool good = readChannel(rd, r->positions) && readChannel(rd, r->mask) && readChannel(rd, r->colors) &&+ readChannel(rd, r->hidden) && readChannel(rd, r->polygroups);+ n.fast = rd.pod<uint8_t>() != 0;+ if (n.fast) rd.vec(n.other);+ rd.vec(n.retuneDelta);+ good = good && rd.ok && channelInRange(r->positions, verts) && channelInRange(r->mask, verts) &&+ channelInRange(r->colors, verts) && channelInRange(r->hidden, tris) && channelInRange(r->polygroups, tris) &&+ (!n.fast || n.other.size() == r->positions.indices.size()) &&+ (n.retuneDelta.empty() || n.retuneDelta.size() == r->positions.indices.size());+ if (!good || r->empty()) return fail("The history file is damaged");+ records[k] = std::move(r);+ }+ // The active branch is nodes 0 .. pathLen - 1, each the parent of the next.+ for (uint32_t k = 1; k < pathLen; ++k)+ if (t->nodes_[k].parent != k - 1) return fail("The history file is damaged");+ UndoStack& s = doc.undo;+ s.listener.reset();+ s.undo_.clear();+ s.redo_.clear();+ t->path_.resize(pathLen);+ for (uint32_t k = 0; k < pathLen; ++k) t->path_[k] = k;+ t->cursor_ = cursor;+ for (uint32_t k = 1; k <= cursor; ++k) s.undo_.push_back(std::move(*records[k]));+ for (uint32_t k = pathLen - 1; k > cursor; --k) s.redo_.push_back(std::move(*records[k]));+ for (uint32_t k = pathLen; k < count; ++k) t->nodes_[k].stored = std::move(records[k]);+ t->stack_ = &s;+ s.listener = t;+ t->sync(doc);+ return true;+}++std::string historySidecarPath(const std::string& projectPath) {+ std::filesystem::path p(projectPath);+ p.replace_extension(".sfhist");+ return p.string();+}++bool saveHistorySidecar(Document& doc, const std::string& projectPath, std::string* error) {+ std::vector<uint8_t> file(kSidecarMagic, kSidecarMagic + 8);+ Writer w{file};+ uint32_t saved = 0;+ std::vector<uint8_t> blob;+ std::vector<uint8_t> body;+ Writer wb{body};+ for (int i = 0; i < doc.subtoolCount(); ++i) {+ UndoStack& stack = i == doc.activeSubtool ? doc.undo : doc.subtools[size_t(i)].undo;+ Timeline* t = Timeline::of(stack);+ if (!t) continue;+ t->bindStack(stack);+ if (!t->save(blob, doc.subtoolMesh(i))) continue;+ wb.pod(uint32_t(i));+ wb.str(doc.subtools[size_t(i)].name);+ wb.vec(blob);+ ++saved;+ }+ const std::string path = historySidecarPath(projectPath);+ std::error_code ec;+ if (saved == 0) {+ std::filesystem::remove(path, ec); // a history from before would no longer match+ return true;+ }+ w.pod(kVersion);+ w.pod(saved);+ file.insert(file.end(), body.begin(), body.end());+ const std::string tmp = path + ".tmp";+ {+ std::ofstream f(std::filesystem::path(tmp), std::ios::binary | std::ios::trunc);+ f.write(reinterpret_cast<const char*>(file.data()), std::streamsize(file.size()));+ if (!f) {+ if (error) *error = "Couldn't write " + tmp;+ return false;+ }+ }+ std::filesystem::rename(tmp, path, ec);+ if (ec) {+ if (error) *error = "Couldn't write " + path + ": " + ec.message();+ return false;+ }+ return true;+}++int loadHistorySidecar(Document& doc, const std::string& projectPath, std::string* error) {+ const std::string path = historySidecarPath(projectPath);+ std::ifstream f(std::filesystem::path(path), std::ios::binary);+ if (!f) return 0;+ std::vector<uint8_t> file((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());+ if (file.size() < 16 || std::memcmp(file.data(), kSidecarMagic, 8) != 0) {+ if (error) *error = path + " is not a SculptForge history";+ return 0;+ }+ Reader rd{file.data() + 8, file.data() + file.size()};+ if (rd.pod<uint32_t>() != kVersion) {+ if (error) *error = path + " was saved by a newer SculptForge";+ return 0;+ }+ const uint32_t count = rd.pod<uint32_t>();+ int loaded = 0;+ const int active = doc.activeSubtool;+ for (uint32_t k = 0; k < count && rd.ok; ++k) {+ const uint32_t index = rd.pod<uint32_t>();+ const std::string name = rd.str();+ std::vector<uint8_t> blob;+ rd.vec(blob);+ if (!rd.ok || int(index) >= doc.subtoolCount() || doc.subtools[index].name != name) continue;+ doc.selectSubtool(int(index));+ std::string e;+ if (Timeline::load(doc, blob, &e)) ++loaded;+ else if (error) *error = e;+ }+ doc.selectSubtool(active);+ return loaded;+}++// ---------------------------------------------------------------------------------------------------------------+// Commands++namespace {++Timeline& ensureTimeline(Document& doc) {+ if (Timeline* t = Timeline::of(doc.undo)) {+ t->sync(doc);+ return *t;+ }+ return *Timeline::attach(doc);+}++const char* kindName(Timeline::Kind k) {+ switch (k) {+ case Timeline::Kind::Start: return "start";+ case Timeline::Kind::Stroke: return "stroke";+ case Timeline::Kind::Mask: return "mask";+ case Timeline::Kind::Paint: return "paint";+ case Timeline::Kind::Visibility: return "visibility";+ case Timeline::Kind::Topology: return "topology";+ default: return "other";+ }+}++} // namespace++void registerTimelineCommands(CommandRegistry& registry) {+ registry.add({"timeline_info", "Describe the Sculpt Timeline: steps on the active branch, the cursor, branches and checkpoints.",+ {{"list", ParamSpec::Type::Bool, "List every step of the active branch", false}},+ [](Document& doc, const Args& args) -> CommandResult {+ Timeline& t = ensureTimeline(doc);+ std::ostringstream s;+ s << "Timeline: " << t.path().size() - 1 << " steps on the active branch, at step " << t.cursor()+ << ", " << t.branches().size() << " other branches, " << t.checkpointCount() << " checkpoints ("+ << t.checkpointBytes() / (1024 * 1024) << " MiB), history extras "+ << t.extraBytes() / (1024 * 1024) << " MiB";+ if (argBool(args, "list", false)) {+ for (size_t i = 0; i < t.path().size(); ++i) {+ const Timeline::Node& n = t.node(t.path()[i]);+ s << "\n" << (i == t.cursor() ? "> " : " ") << i << " #" << t.path()[i] << " " << kindName(n.kind)+ << " \"" << n.label << "\" " << n.touched << (n.fast ? " fast" : "")+ << (t.hasCheckpoint(t.path()[i]) ? " checkpoint" : "");+ if (n.strength != 1.0f) s << " strength " << n.strength;+ }+ for (const Timeline::Branch& b : t.branches())+ s << "\n branch from step " << b.from << ": #" << b.first << " .. #" << b.tip << " (" << b.length << " steps)";+ }+ return {true, s.str()};+ }});+ registry.add({"timeline_seek", "Show the model as it was after step `index` of the active branch (0 = the start).",+ {{"index", ParamSpec::Type::Number, "Step on the active branch", true}},+ [](Document& doc, const Args& args) -> CommandResult {+ Timeline& t = ensureTimeline(doc);+ const double v = argNumber(args, "index", -1.0);+ if (v < 0) return {false, "index must be 0 or more"};+ std::string e;+ if (!t.seek(doc, size_t(v), &e)) return {false, e};+ const auto& st = t.lastSeek();+ std::ostringstream s;+ s << "At step " << t.cursor() << " (" << st.ms << " ms; " << st.batched << " batched, " << st.walked+ << " walked, " << st.replayed << " replayed" << (st.usedCheckpoint ? ", from a checkpoint" : "") << ")";+ return {true, s.str()};+ }});+ registry.add({"timeline_select", "Make the branch through step `node` (an id from timeline_info list) active and show it.",+ {{"node", ParamSpec::Type::Number, "Step id (#)", true}},+ [](Document& doc, const Args& args) -> CommandResult {+ Timeline& t = ensureTimeline(doc);+ std::string e;+ if (!t.select(doc, uint32_t(argNumber(args, "node", -1.0)), &e)) return {false, e};+ return {true, "At step " + std::to_string(t.cursor()) + " of the selected branch"};+ }});+ registry.add({"timeline_retune", "Change how strongly a past stroke shows (1 = as sculpted, 0 = gone) without redoing the strokes after it.",+ {{"node", ParamSpec::Type::Number, "Step id (#) of the stroke", true},+ {"strength", ParamSpec::Type::Number, "0 .. 4", true}},+ [](Document& doc, const Args& args) -> CommandResult {+ Timeline& t = ensureTimeline(doc);+ std::string e;+ if (!t.retune(doc, uint32_t(argNumber(args, "node", -1.0)), float(argNumber(args, "strength", 1.0)), &e))+ return {false, e};+ doc.modified = true;+ return {true, "Stroke re-tuned"};+ }});+ registry.add({"timeline_save", "Save the history beside the project (<name>.sfhist).",+ {{"path", ParamSpec::Type::String, "Project path (default: the open project)", false}},+ [](Document& doc, const Args& args) -> CommandResult {+ ensureTimeline(doc);+ const std::string path = argString(args, "path", doc.path);+ if (path.empty()) return {false, "Save the project first (or give a path)"};+ std::string e;+ if (!saveHistorySidecar(doc, path, &e)) return {false, e};+ return {true, "History saved to " + historySidecarPath(path)};+ }});+ registry.add({"timeline_load", "Load the history saved beside the project (<name>.sfhist), if it matches the mesh.",+ {{"path", ParamSpec::Type::String, "Project path (default: the open project)", false}},+ [](Document& doc, const Args& args) -> CommandResult {+ const std::string path = argString(args, "path", doc.path);+ if (path.empty()) return {false, "No project path"};+ std::string e;+ const int n = loadHistorySidecar(doc, path, &e);+ if (n == 0) return {false, e.empty() ? "No history beside " + path : e};+ return {true, "History loaded for " + std::to_string(n) + " SubTool(s)"};+ }});+}++} // namespace sfdiff --git a/src/core/Timeline.h b/src/core/Timeline.hnew file mode 100644index 00000000..b87dc3d0--- /dev/null+++ b/src/core/Timeline.h@@ -0,0 +1,185 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Sculpt Timeline: the edit history as a tree you can travel in (docs/guide/timeline.md).+//+// Every undo step is a node; the root is the state before the first one. The undo stack (core/Undo.h) holds the+// steps of one path through the tree, the active branch: its undo steps lead from the root to the cursor (the+// state the mesh shows), its redo steps on to the branch's tip. Undoing and then editing doesn't throw the old+// continuation away as a plain undo stack does: those steps stay in the tree as an inactive branch, and selecting+// any of its nodes makes it the active branch again.+//+// Moving the cursor (seek) reuses the stack's own sparse per-step deltas. A sculpt stroke on the base mesh (a+// "fast" step: positions only, no sculpt layers) also keeps the values its record doesn't hold (`other`: after+// an undo the record holds the new positions and `other` the old ones, and the other way round), so the+// timeline can move it between undo and redo by swapping two vectors and writing the positions it needs, and+// updates normals, the BVH and the GPU once for a whole run of steps instead of after each one. Every+// `checkpointEvery` fast steps it keeps a full copy of the positions (a checkpoint, within `checkpointBudget`):+// a long jump writes the nearest checkpoint at or before the target and replays at most a few steps forward,+// instead of walking every step in between, so seeking costs about the same wherever the target is. Other steps+// (dynamic topology, remeshes, masks, paint, SubTool changes) are walked with the undo stack's own undo / redo.+//+// Re-tune: a past stroke's strength can be changed (its delta scaled) without redoing the strokes after it. The+// change is added to the current shape and to every later step's stored positions where they overlap the+// stroke. That is exact where later strokes don't overlap it; where they do, they keep the displacement they+// made then on top of the new shape: a later stroke isn't simulated again (a Smooth over the area won't re-smooth+// it, a later Inflate keeps its old direction). Steps after the stroke that store whole meshes or topology make+// re-tuning it impossible (it reports why).+//+// The history can be saved beside a project as <name>.sfhist (saveHistory / loadHistory): sculpt strokes, masks,+// polypaint, visibility and polygroup steps; the tree, labels, times and strengths. Steps that can't be saved+// (topology changes, textures, layers) cut the saved history at the newest such step before the cursor.+#pragma once++#include "core/Undo.h"++#include <glm/glm.hpp>++#include <cstdint>+#include <functional>+#include <limits>+#include <map>+#include <memory>+#include <string>+#include <vector>++namespace sf {++struct Document;++class Timeline : public UndoListener {+public:+ static constexpr uint32_t kNone = std::numeric_limits<uint32_t>::max();+ enum class Kind : uint8_t { Start, Stroke, Mask, Paint, Visibility, Topology, Other };++ struct Node {+ uint32_t parent = kNone;+ std::vector<uint32_t> children;+ uint32_t activeChild = kNone; // the child the branch continues with (the newest, or the last one visited)+ std::string label;+ double time = 0.0; // seconds since the Unix epoch when the step was made+ Kind kind = Kind::Other;+ uint32_t touched = 0; // vertices (or triangles) the step changed+ glm::vec3 center{0.0f}; // bounds of the changed vertices after the step (fast steps; for overlap and the timelapse)+ float radius = 0.0f;+ float strength = 1.0f; // re-tune: how strongly the stroke shows (1 = as sculpted)+ bool alive = true;+ bool fast = false; // `other` is valid (see the file comment)+ bool captured = false; // `other` / bounds were taken from the mesh after the step+ std::vector<glm::vec3> other;+ std::vector<glm::vec3> retuneDelta; // the stroke's delta at strength 1, kept from the first re-tune on+ std::unique_ptr<UndoRecord> stored; // a node on an inactive branch: its step, as a redo step+ };++ Timeline() = default;+ // Starts watching `doc.undo` (replacing any other listener): the tree is the stack's undo and redo steps.+ static std::shared_ptr<Timeline> attach(Document& doc);+ // The timeline watching `stack`, if any.+ static Timeline* of(UndoStack& stack);+ void bindStack(UndoStack& stack) { stack_ = &stack; } // after the stack moved (SubTools); Document calls do it++ // --- the tree+ const Node& node(uint32_t id) const { return nodes_[id]; }+ size_t nodeCount() const { return nodes_.size(); } // ids; some may be dead (!alive)+ uint32_t root() const { return path_.front(); }+ const std::vector<uint32_t>& path() const { return path_; } // the active branch, root first+ size_t cursor() const { return cursor_; } // index into path(): the state shown+ uint32_t cursorNode() const { return path_[cursor_]; }+ bool onPath(uint32_t id) const;+ int depth(uint32_t id) const; // steps from the root+ // Nodes not on the active branch, each with the path index of the node it branches from.+ struct Branch {+ uint32_t first; // its first node (a child of path()[from])+ size_t from;+ size_t length; // nodes along its own active children+ uint32_t tip;+ };+ std::vector<Branch> branches() const;+ size_t aliveCount() const;++ // --- travel (`doc.undo` must be the watched stack). Each returns false with `error` set when it can't.+ // Shows the state after path()[index].+ bool seek(Document& doc, size_t index, std::string* error = nullptr);+ // Makes the branch through `id` active and shows the state after it.+ bool select(Document& doc, uint32_t id, std::string* error = nullptr);+ // Sets how strongly stroke `id` (on the active branch) shows; see the file comment for the approximation.+ bool retune(Document& doc, uint32_t id, float strength, std::string* error = nullptr);+ bool canRetune(uint32_t id, std::string* why = nullptr) const;+ // Brings what the mesh shows into the tree (fast-step capture, checkpoints): call once a frame, and before+ // reading node data after edits.+ void sync(Document& doc);++ // --- settings and statistics+ // save_project also writes <name>.sfhist (the app's Preferences; off for the CLI and scripts).+ inline static bool saveWithProject = false;+ size_t checkpointEvery = 16; // a checkpoint every this many path steps (doubles when over budget)+ size_t checkpointBudget = size_t(1) << 30; // bytes of checkpoints+ size_t branchBudget = size_t(3) << 29; // 1.5 GiB of inactive branches and `other` copies+ size_t checkpointBytes() const;+ size_t extraBytes() const; // `other` copies and inactive branches+ size_t checkpointCount() const { return checkpoints_.size(); }+ bool hasCheckpoint(uint32_t id) const { return checkpoints_.count(id) != 0; }+ struct SeekStats {+ size_t walked = 0, batched = 0, replayed = 0; // steps undone / redone by the stack, swapped in batches, replayed from a checkpoint+ bool usedCheckpoint = false;+ double ms = 0.0;+ };+ const SeekStats& lastSeek() const { return lastSeek_; }++ // --- saving (see the file comment). Fails when nothing can be saved.+ bool save(std::vector<uint8_t>& out, const Mesh& mesh, std::string* error = nullptr) const;+ // Rebuilds the tree from save()'s bytes into `doc.undo` (whose mesh must be the one saved); false (and the+ // history left alone) when the bytes don't match the mesh.+ static bool load(Document& doc, const std::vector<uint8_t>& in, std::string* error = nullptr);++ // UndoListener+ void undoPushed(UndoRecord& pushed, std::deque<UndoRecord>& discardedRedo) override;+ void undoApplying(UndoRecord& r, Mesh& mesh, bool isUndo) override;+ void undoApplied(UndoRecord& r, Mesh& mesh, bool isUndo) override;+ void undoDroppedOldest() override;+ void undoCleared() override;++ // The step of node `id` (on the path: in the stack; else its stored record), or null for the root.+ UndoRecord* recordOf(uint32_t id);+ const UndoRecord* recordOf(uint32_t id) const { return const_cast<Timeline*>(this)->recordOf(id); }+ static Kind classify(const UndoRecord& r);+ static bool fastShape(const UndoRecord& r); // a step that can be fast (positions of the base only)++private:+ uint32_t newNode(uint32_t parent, const UndoRecord* r);+ void reset();+ void capture(Mesh& mesh); // the cursor node's `other` and bounds from the mesh (which shows it)+ void captureFrom(Node& n, const UndoRecord& r, Mesh& mesh); // the same, `r` being n's step in undo form+ void freeSubtree(uint32_t id);+ void maybeCheckpoint(const Mesh& mesh);+ void enforceBudgets();+ void walkTo(Document& doc, size_t index);+ bool jumpWithCheckpoint(Document& doc, size_t index);+ void flushBatch(Document& doc);++ std::vector<Node> nodes_;+ std::vector<uint32_t> path_{};+ size_t cursor_ = 0;+ UndoStack* stack_ = nullptr; // the watched stack (re-pointed by attach / every Document call)+ std::map<uint32_t, std::vector<glm::vec3>> checkpoints_; // node id -> positions after it+ size_t meshVertices_ = 0; // vertex count fast steps and checkpoints belong to+ std::vector<uint32_t> batch_; // vertices a batched run moved (flushBatch)+ std::vector<uint8_t> batchSeen_;+ SeekStats lastSeek_;+ double flushMs_ = 0.0;+};++// The sidecar file beside a project: "<dir>/<name>.sfhist" for "<dir>/<name>.sfp" (any extension).+std::string historySidecarPath(const std::string& projectPath);+// Writes every SubTool's history (those with a timeline) to the sidecar of `projectPath`; removes a stale one when+// there's nothing to save. Returns false with `error` on a write failure.+bool saveHistorySidecar(Document& doc, const std::string& projectPath, std::string* error = nullptr);+// Reads the sidecar of `projectPath`, if there is one, into the SubTools whose meshes it matches (attaching+// timelines). Returns how many SubTools got their history back.+int loadHistorySidecar(Document& doc, const std::string& projectPath, std::string* error = nullptr);++class CommandRegistry;+// timeline_info, timeline_seek, timeline_select, timeline_retune, timeline_save, timeline_load.+void registerTimelineCommands(CommandRegistry& registry);++} // namespace sfdiff --git a/src/core/Undo.cpp b/src/core/Undo.cppindex 84e46d5a..0ea2cc5a 100644--- a/src/core/Undo.cpp+++ b/src/core/Undo.cpp@@ -141,6 +141,7 @@ UndoRecord UndoRecord::capturePolygroups(const Mesh& mesh, std::string label, stvoid UndoStack::push(UndoRecord record) {if (record.empty()) return;undo_.push_back(std::move(record));+ if (listener) listener->undoPushed(undo_.back(), redo_);redo_.clear();++revision_;enforceBudget();@@ -215,8 +216,10 @@ bool UndoStack::undo(Mesh& mesh, BVH& bvh) {if (undo_.empty()) return false;UndoRecord r = std::move(undo_.back());undo_.pop_back();+ if (listener) listener->undoApplying(r, mesh, true);apply(r, mesh, bvh);redo_.push_back(std::move(r));+ if (listener) listener->undoApplied(redo_.back(), mesh, true);++revision_;return true;}@@ -225,8 +228,10 @@ bool UndoStack::redo(Mesh& mesh, BVH& bvh) {if (redo_.empty()) return false;UndoRecord r = std::move(redo_.back());redo_.pop_back();+ if (listener) listener->undoApplying(r, mesh, false);apply(r, mesh, bvh);undo_.push_back(std::move(r));+ if (listener) listener->undoApplied(undo_.back(), mesh, false);++revision_;return true;}@@ -234,6 +239,7 @@ bool UndoStack::redo(Mesh& mesh, BVH& bvh) {void UndoStack::clear() {undo_.clear();redo_.clear();+ if (listener) listener->undoCleared();}size_t UndoStack::undoBytes() const {@@ -248,6 +254,7 @@ void UndoStack::enforceBudget() {while (undo_.size() > 1 && total > byteBudget) {total -= undo_.front().approxBytes();undo_.pop_front();+ if (listener) listener->undoDroppedOldest();}}diff --git a/src/core/Undo.h b/src/core/Undo.hindex 2f3e4de0..fc4c893b 100644--- a/src/core/Undo.h+++ b/src/core/Undo.h@@ -149,7 +149,24 @@ struct UndoRecord {static UndoRecord capturePolygroups(const Mesh& mesh, std::string label, std::span<const uint32_t> tris = {});};+// Watches an UndoStack: the Sculpt Timeline (core/Timeline.h) keeps its history tree in step with it. Held by the+// stack (UndoStack::listener), so it moves with it (each SubTool's history has its own).+struct UndoListener {+ virtual ~UndoListener() = default;+ // A step was pushed (it is the stack's last undo step); `discardedRedo` holds the redo steps the push is about+ // to drop (redo_.back() is the next redo) and may be moved from.+ virtual void undoPushed(UndoRecord& pushed, std::deque<UndoRecord>& discardedRedo) = 0;+ // Around UndoStack::undo / redo applying `r` to `mesh`.+ virtual void undoApplying(UndoRecord& r, Mesh& mesh, bool isUndo) = 0;+ virtual void undoApplied(UndoRecord& r, Mesh& mesh, bool isUndo) = 0;+ virtual void undoDroppedOldest() = 0; // the byte budget dropped the oldest undo step+ virtual void undoCleared() = 0;+};++class Timeline;+class UndoStack {+ friend class Timeline; // moves steps between undo and redo without applying them (core/Timeline.h)public:UndoStack() = default;UndoStack(UndoStack&&) = default; // move-only (records own mesh snapshots)@@ -176,6 +193,7 @@ public:size_t undoBytes() const;size_t byteBudget = size_t(1) << 30; // 1 GiB+ std::shared_ptr<UndoListener> listener; // the Sculpt Timeline (core/Timeline.h), if one watches this historyprivate:static void apply(UndoRecord& r, Mesh& mesh, BVH& bvh);diff --git a/tests/test_timeline.cpp b/tests/test_timeline.cppnew file mode 100644index 00000000..9ca39a8c--- /dev/null+++ b/tests/test_timeline.cpp@@ -0,0 +1,346 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// The Sculpt Timeline (core/Timeline.h): seeking, branches, re-tune, the .sfhist sidecar. SF_BENCH_LIMITS=1 adds+// timing checks on a large mesh.+#include "TestHarness.h"++#include "core/Benchmark.h"+#include "core/Commands.h"+#include "core/Masking.h"+#include "core/Primitives.h"+#include "core/Project.h"+#include "core/Timeline.h"++#include <chrono>+#include <cmath>+#include <cstdlib>+#include <filesystem>+#include <random>++using namespace sf;++namespace {++// One Standard stroke of `dabs` dabs from `a` towards `b` on the unit sphere.+void stroke(Document& d, glm::vec3 a, glm::vec3 b, float radius = 0.3f, int dabs = 4, BrushType t = BrushType::Standard) {+ d.sculptor.beginStroke(d.mesh, brushName(t));+ for (int i = 0; i < dabs; ++i) {+ DabParams p;+ p.center = glm::normalize(glm::mix(a, b, dabs > 1 ? float(i) / float(dabs - 1) : 0.0f));+ p.viewDir = -p.center;+ p.radius = radius;+ p.strength = 0.6f;+ d.sculptor.dab(d.mesh, d.bvh, t, p, Symmetry{});+ }+ d.undo.push(d.sculptor.endStroke());+}++glm::vec3 randomDir(std::mt19937& rng) {+ std::normal_distribution<float> n;+ return glm::normalize(glm::vec3(n(rng), n(rng), n(rng)));+}++float maxDiff(const std::vector<glm::vec3>& a, const std::vector<glm::vec3>& b) {+ if (a.size() != b.size()) return 1e30f;+ float m = 0.0f;+ for (size_t i = 0; i < a.size(); ++i) m = std::max(m, glm::length(a[i] - b[i]));+ return m;+}++bool benchLimits() {+ const char* e = std::getenv("SF_BENCH_LIMITS");+ return e && std::string(e) == "1";+}++} // namespace++TEST(timeline_seek_matches_undo_history) {+ Document d = makeDoc(makeIcosphere(4));+ auto t = Timeline::attach(d);+ t->checkpointEvery = 3;+ std::mt19937 rng(7);+ std::vector<std::vector<glm::vec3>> states{d.mesh.positions};+ for (int i = 0; i < 14; ++i) {+ stroke(d, randomDir(rng), randomDir(rng));+ t->sync(d); // as the app does every frame+ states.push_back(d.mesh.positions);+ }+ CHECK(t->path().size() == 15);+ CHECK(t->cursor() == 14);+ CHECK(t->checkpointCount() >= 4); // steps 0, 3, 6, 9, 12+ // Jump around: every state must come back exactly, whichever way it is reached.+ for (size_t target : {0u, 14u, 7u, 1u, 13u, 6u, 6u, 0u, 9u, 2u, 14u}) {+ CHECK(t->seek(d, target));+ CHECK(t->cursor() == target);+ CHECK(maxDiff(d.mesh.positions, states[target]) == 0.0f);+ }+ // The undo stack still works as before after the timeline moved steps around.+ CHECK(t->seek(d, 14));+ for (int k = 13; k >= 10; --k) {+ CHECK(d.undo.undo(d.mesh, d.bvh));+ CHECK(maxDiff(d.mesh.positions, states[size_t(k)]) == 0.0f);+ }+ CHECK(d.undo.redo(d.mesh, d.bvh));+ CHECK(maxDiff(d.mesh.positions, states[11]) == 0.0f);+ CHECK(t->cursor() == 11);+ // A checkpoint jump is used for a long seek on a run of strokes.+ CHECK(t->seek(d, 0));+ CHECK(t->seek(d, 13));+ CHECK(maxDiff(d.mesh.positions, states[13]) == 0.0f);+ // The normals follow the positions (compared with a full recompute).+ std::vector<glm::vec3> normals = d.mesh.normals;+ d.mesh.recomputeAllNormals();+ CHECK(maxDiff(normals, d.mesh.normals) < 1e-5f);+}++TEST(timeline_walks_steps_that_are_not_strokes) {+ Document d = makeDoc(makeIcosphere(3));+ CommandRegistry reg;+ auto t = Timeline::attach(d);+ t->checkpointEvery = 2;+ std::vector<std::vector<glm::vec3>> states{d.mesh.positions};+ std::vector<size_t> masked{0};+ stroke(d, {0, 0, 1}, {0, 1, 0});+ t->sync(d);+ states.push_back(d.mesh.positions);+ CHECK(reg.execute(d, "mask_all").ok); // a mask step between strokes: walked by the undo stack+ t->sync(d);+ states.push_back(d.mesh.positions);+ CHECK(reg.execute(d, "mask_clear").ok);+ t->sync(d);+ states.push_back(d.mesh.positions);+ stroke(d, {1, 0, 0}, {0, 0, -1});+ t->sync(d);+ states.push_back(d.mesh.positions);+ CHECK(t->path().size() == 5);+ CHECK(t->node(t->path()[2]).kind == Timeline::Kind::Mask);+ CHECK(t->seek(d, 0));+ CHECK(maxDiff(d.mesh.positions, states[0]) == 0.0f);+ CHECK(t->seek(d, 2));+ CHECK(!d.mesh.mask.empty() && d.mesh.mask[0] > 0.5f); // mask_all is shown+ CHECK(t->seek(d, 4));+ CHECK(maxDiff(d.mesh.positions, states[4]) == 0.0f);+ CHECK(d.mesh.mask.empty() || d.mesh.mask[0] < 0.5f);+ CHECK(t->lastSeek().walked >= 1);+}++TEST(timeline_branches_keep_the_old_continuation) {+ Document d = makeDoc(makeIcosphere(4));+ auto t = Timeline::attach(d);+ stroke(d, {0, 0, 1}, {0, 0.5f, 1});+ stroke(d, {1, 0, 0}, {1, 0.5f, 0});+ stroke(d, {0, 1, 0}, {0.5f, 1, 0});+ t->sync(d);+ const std::vector<glm::vec3> oldTip = d.mesh.positions;+ const uint32_t oldTipId = t->cursorNode();+ CHECK(t->seek(d, 1)); // back to after the first stroke ...+ stroke(d, {0, -1, 0}, {0, -1, 0.5f}); // ... and sculpt something else: a branch+ t->sync(d);+ const std::vector<glm::vec3> newTip = d.mesh.positions;+ CHECK(t->path().size() == 3);+ CHECK(t->branches().size() == 1);+ CHECK(t->branches()[0].from == 1);+ CHECK(t->branches()[0].length == 2);+ CHECK(t->branches()[0].tip == oldTipId);+ CHECK(!d.undo.canRedo()); // the undo stack sees only the active branch+ // Select the old continuation: it comes back exactly, and the new one becomes the alternative.+ std::string e;+ CHECK(t->select(d, oldTipId, &e));+ CHECK(maxDiff(d.mesh.positions, oldTip) == 0.0f);+ CHECK(t->path().size() == 4);+ CHECK(t->branches().size() == 1);+ CHECK(t->branches()[0].length == 1);+ // ... and back again, through the command.+ CommandRegistry reg;+ const uint32_t newTipId = t->branches()[0].tip;+ CHECK(reg.execute(d, "timeline_select", {{"node", double(newTipId)}}).ok);+ CHECK(maxDiff(d.mesh.positions, newTip) == 0.0f);+ CHECK(reg.execute(d, "timeline_info", {{"list", true}}).ok);+ // Undo then a new edit with the plain undo stack also keeps the redo steps as a branch.+ CHECK(d.undo.undo(d.mesh, d.bvh));+ stroke(d, {0, 0, -1}, {0.3f, 0, -1});+ t->sync(d);+ CHECK(t->branches().size() == 2);+}++TEST(timeline_retune_scales_one_stroke) {+ Document d = makeDoc(makeIcosphere(5));+ auto t = Timeline::attach(d);+ const std::vector<glm::vec3> start = d.mesh.positions;+ stroke(d, {0, 0, 1}, {0, 0.3f, 1}, 0.25f); // A (front)+ t->sync(d);+ const uint32_t a = t->cursorNode();+ stroke(d, {0, 0, -1}, {0, 0.3f, -1}, 0.25f); // B (back): doesn't overlap A+ t->sync(d);+ // B alone, for comparison.+ Document only = makeDoc(makeIcosphere(5));+ stroke(only, {0, 0, -1}, {0, 0.3f, -1}, 0.25f);+ std::string why;+ CHECK(t->canRetune(a, &why));+ CHECK(t->retune(d, a, 0.0f)); // A gone: exactly B alone where they don't overlap+ CHECK(maxDiff(d.mesh.positions, only.mesh.positions) < 1e-5f);+ CHECK(t->retune(d, a, 2.0f)); // twice as strong+ const glm::vec3 front = d.mesh.positions[0];+ (void)front;+ float maxFront = 0.0f;+ for (const glm::vec3& p : d.mesh.positions)+ if (p.z > 0.5f) maxFront = std::max(maxFront, glm::length(p));+ CHECK(t->retune(d, a, 1.0f));+ float maxFront1 = 0.0f;+ for (const glm::vec3& p : d.mesh.positions)+ if (p.z > 0.5f) maxFront1 = std::max(maxFront1, glm::length(p));+ CHECK(maxFront - 1.0f > 1.8f * (maxFront1 - 1.0f));+ // Seeking still reproduces consistent states with the new strength: start, then back to the end.+ CHECK(t->seek(d, 0));+ CHECK(maxDiff(d.mesh.positions, start) < 1e-6f);+ CHECK(t->retune(d, a, 0.0f)); // re-tuning a stroke ahead of the cursor changes only the stored steps+ CHECK(maxDiff(d.mesh.positions, start) < 1e-6f);+ CHECK(t->seek(d, 2));+ CHECK(maxDiff(d.mesh.positions, only.mesh.positions) < 1e-5f);+ // An overlapping later stroke keeps its displacement on top (the documented approximation): re-tuning to the+ // same strength twice is the identity.+ stroke(d, {0, 0.1f, 1}, {0, 0.2f, 1}, 0.3f); // overlaps A+ t->sync(d);+ const std::vector<glm::vec3> before = d.mesh.positions;+ CHECK(t->retune(d, a, 1.5f));+ CHECK(maxDiff(d.mesh.positions, before) > 1e-4f);+ CHECK(t->retune(d, a, 0.0f));+ CHECK(maxDiff(d.mesh.positions, before) < 1e-5f);+ CHECK(!t->canRetune(t->path()[0], &why)); // the start isn't a stroke+}++TEST(timeline_history_sidecar_round_trip) {+ Document d = makeDoc(makeIcosphere(4));+ CommandRegistry reg;+ auto t = Timeline::attach(d);+ std::vector<std::vector<glm::vec3>> states{d.mesh.positions};+ for (int i = 0; i < 5; ++i) {+ stroke(d, glm::vec3(std::cos(float(i)), std::sin(float(i)), 0.3f), glm::vec3(std::cos(float(i) + 0.4f), std::sin(float(i) + 0.4f), 0.3f));+ t->sync(d);+ states.push_back(d.mesh.positions);+ }+ CHECK(t->seek(d, 2));+ stroke(d, {0, 0, 1}, {0, 0.2f, 1}); // a branch+ t->sync(d);+ const std::vector<glm::vec3> branchTip = d.mesh.positions;+ CHECK(t->retune(d, t->path()[1], 0.5f));+ const std::vector<glm::vec3> saved = d.mesh.positions;+ const std::string dir = tempPath("sf_timeline_test");+ std::filesystem::create_directories(dir);+ const std::string project = dir + "/history.sfp";+ std::string err;+ CHECK(saveProject(project, d, err));+ CHECK(saveHistorySidecar(d, project, &err));+ CHECK(std::filesystem::exists(dir + "/history.sfhist"));++ Document e;+ CHECK(loadProject(project, e, err));+ CHECK(maxDiff(e.mesh.positions, saved) == 0.0f);+ CHECK(loadHistorySidecar(e, project, &err) == 1);+ Timeline* u = Timeline::of(e.undo);+ CHECK(u != nullptr);+ if (!u) return;+ CHECK(u->path().size() == 4);+ CHECK(u->cursor() == 3);+ CHECK(u->branches().size() == 1);+ CHECK(u->node(u->path()[1]).strength == 0.5f);+ CHECK(maxDiff(e.mesh.positions, branchTip) > 0.0f); // (re-tuned since)+ CHECK(u->seek(e, 0));+ CHECK(maxDiff(e.mesh.positions, states[0]) < 1e-6f);+ CHECK(u->seek(e, 3));+ CHECK(maxDiff(e.mesh.positions, saved) < 1e-6f);+ CHECK(u->select(e, u->branches()[0].tip, &err));+ CHECK(e.undo.canUndo());+ // A sidecar for another mesh is refused, leaving the history alone.+ Document other = makeDoc(makeIcosphere(4));+ CHECK(loadHistorySidecar(other, project, &err) == 0);+ CHECK(!other.undo.canUndo());+ // Damaged files are refused.+ std::vector<uint8_t> blob;+ CHECK(u->save(blob, e.mesh));+ for (size_t cut : {size_t(9), blob.size() / 2, blob.size() - 1}) {+ std::vector<uint8_t> part(blob.begin(), blob.begin() + long(cut));+ Document f;+ CHECK(loadProject(project, f, err));+ // (loadProject read the saved state; the blob belongs to `e`'s state, which may differ: either way no crash)+ CHECK(!Timeline::load(f, part, &err));+ }+ std::filesystem::remove_all(dir);+}++TEST(timeline_follows_the_undo_budget_and_clear) {+ Document d = makeDoc(makeIcosphere(4));+ auto t = Timeline::attach(d);+ stroke(d, {0, 0, 1}, {0, 0.3f, 1});+ t->sync(d);+ d.undo.byteBudget = d.undo.undoBytes() + 1; // room for about one more step+ stroke(d, {1, 0, 0}, {1, 0.3f, 0});+ stroke(d, {0, 1, 0}, {0.3f, 1, 0});+ t->sync(d);+ CHECK(t->path().size() == d.undo.undoCount() + 1);+ CHECK(t->cursor() == d.undo.undoCount());+ CHECK(t->seek(d, 0));+ CHECK(t->seek(d, t->path().size() - 1));+ d.setMesh(makeIcosphere(3)); // a new scene clears the history+ CHECK(Timeline::of(d.undo) == t.get());+ CHECK(t->path().size() == 1);+ // SubTools: each history keeps its own timeline.+ stroke(d, {0, 0, 1}, {0, 0.3f, 1});+ t->sync(d);+ d.addSubtool(makeIcosphere(3), "Other");+ CHECK(Timeline::of(d.undo) == nullptr);+ auto t2 = Timeline::attach(d);+ stroke(d, {0, 0, 1}, {0, 0.3f, 1});+ stroke(d, {0, 1, 0}, {0, 1, 0.3f});+ d.selectSubtool(0);+ CHECK(Timeline::of(d.undo) == t.get());+ CHECK(t->path().size() == 2);+ d.selectSubtool(1);+ CHECK(Timeline::of(d.undo) == t2.get());+ CHECK(t2->path().size() == 3);+ CHECK(t2->seek(d, 0));+}++// Large meshes: seeking must stay interactive (SF_BENCH_LIMITS=1; the sizes follow SF_TIMELINE_MILLIONS, default 5).+TEST(timeline_seek_large_mesh_timing) {+ const bool limits = benchLimits();+ double millions = 0.3;+ if (limits) millions = std::getenv("SF_TIMELINE_MILLIONS") ? std::atof(std::getenv("SF_TIMELINE_MILLIONS")) : 5.0;+ Document d = makeDoc(makeBenchSphere(size_t(millions * 1e6)));+ auto t = Timeline::attach(d);+ const int strokes = limits ? 64 : 12;+ std::mt19937 rng(3);+ using C = std::chrono::steady_clock;+ for (int i = 0; i < strokes; ++i) {+ stroke(d, randomDir(rng), randomDir(rng), 0.35f, 6);+ t->sync(d);+ }+ const std::vector<glm::vec3> end = d.mesh.positions;+ double worstStep = 0.0, full = 0.0, back = 0.0;+ auto c0 = C::now();+ CHECK(t->seek(d, 0));+ full = std::chrono::duration<double, std::milli>(C::now() - c0).count();+ const size_t last = t->path().size() - 1; // (the undo budget may have dropped the oldest strokes)+ c0 = C::now();+ CHECK(t->seek(d, last));+ back = std::chrono::duration<double, std::milli>(C::now() - c0).count();+ CHECK(maxDiff(d.mesh.positions, end) == 0.0f);+ size_t touched = 0;+ for (size_t i = last; i > last - 8; --i) { // scrubbing one step at a time+ touched = std::max<size_t>(touched, t->node(t->path()[i]).touched);+ c0 = C::now();+ CHECK(t->seek(d, i - 1));+ worstStep = std::max(worstStep, std::chrono::duration<double, std::milli>(C::now() - c0).count());+ }+ std::printf(" timeline %.1fM tris, %d strokes: seek to start %.1f ms, to end %.1f ms (%s), one step worst %.1f ms (strokes of up to %zu vertices), "+ "checkpoints %zu (%zu MiB), extras %zu MiB\n",+ double(d.mesh.triangleCount()) / 1e6, strokes, full, back,+ t->lastSeek().usedCheckpoint ? "checkpoint" : "walked", worstStep, touched, t->checkpointCount(),+ t->checkpointBytes() >> 20, t->extraBytes() >> 20);+ if (limits) {+ CHECK(full < 400.0);+ CHECK(back < 400.0);+ CHECK(worstStep < 60.0);+ }+}