Skip to content

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.

Project files, unsaved-changes safety, recent files and autosave

islandmed9b780cd2c8d4
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4e439795..1beaece4 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -41,6 +41,7 @@ add_library(sculptforge_core STATIC
src/core/Splats.cpp
src/core/Voxel.cpp
src/core/EnginePresets.cpp
+ src/core/Project.cpp
src/io/ObjIO.cpp
src/io/FbxIO.cpp
third_party/ufbx/ufbx.c
@@ -58,6 +59,7 @@ else()
endif()
target_link_libraries(sculptforge_core PUBLIC glm::glm)
target_compile_definitions(sculptforge_core PUBLIC GLM_FORCE_XYZW_ONLY)
+target_compile_definitions(sculptforge_core PRIVATE SCULPTFORGE_VERSION="${PROJECT_VERSION}") # written into projects
if(MSVC)
target_compile_options(sculptforge_core PRIVATE /W4 /utf-8 /permissive-)
target_compile_definitions(sculptforge_core PUBLIC NOMINMAX _USE_MATH_DEFINES)
@@ -103,6 +105,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/main.cpp
src/app/App.cpp
src/app/Demo.cpp
+ src/app/PanelProject.cpp
src/render/GL.cpp
src/render/Camera.cpp
src/render/Renderer.cpp
diff --git a/docs/project-format.md b/docs/project-format.md
new file mode 100644
index 00000000..f47a26c9
--- /dev/null
+++ b/docs/project-format.md
@@ -0,0 +1,42 @@
+# SculptForge project files (.sfproj)
+
+A `.sfproj` is an uncompressed ("stored") ZIP (src/io/Zip.cpp) written by `saveProject` /
+read by `loadProject` (src/core/Project.cpp). Commands: `save_project path=...`,
+`open_project path=...`; `open` also recognises `.sfproj`.
+
+## Layout
+- `manifest.json`: always first. `format` = `"SculptForge project"`, `version` (integer, currently 1),
+ `app_version`, then `mesh`, `layers`, `active_layer`, `brushes` (recipe JSON), `active_brush`
+ (name), optional `splats`, and app-owned keys (`camera`, `render`, `brush`, `symmetry`).
+- Blobs are little-endian arrays. The manifest describes each one as
+ `{"file", "type": "f32"|"u32"|"u8", "components", "count"}`; readers check all four.
+
+| Manifest key | File | Layout |
+|--------------|------|--------|
+| `mesh.positions` | mesh/positions.bin | f32 x3 per vertex (current blend) |
+| `mesh.triangles` | mesh/triangles.bin | u32 x3 per triangle |
+| `mesh.base` | mesh/base.bin | f32 x3 per vertex (only with layers) |
+| `mesh.mask` / `colors` | mesh/mask.bin, colors.bin | f32 x1 / x3 per vertex (linear RGB) |
+| `mesh.polygroups` / `hidden` | mesh/polygroups.bin, hidden.bin | u32 / u8 per triangle |
+| `mesh.uvs` | mesh/uvs.bin | f32 x2 per triangle corner |
+| `layers[i].delta` | layers/<i>.bin | f32 x3 per vertex, plus `name`, `weight` |
+| `splats.*` | splats/*.bin | positions x3, rotations x4 (x,y,z,w), scales x3, opacities x1, sh x3 per coefficient; plus `count`, `sh_degree`, `name`, `transform` (16 floats, column-major) |
+
+Optional attributes are simply absent when the mesh doesn't have them.
+
+## Compatibility rules
+- Unknown keys and files are ignored. Unknown **top-level** keys are kept in
+ `Document::projectSettings` and written back, so older builds don't drop newer settings.
+- A file whose `version` is greater than `kProjectVersion` is refused with a message naming the app
+ version that wrote it. Bump `kProjectVersion` only for changes old readers would misread;
+ adding a new optional blob does not need a bump.
+- New mesh attributes: add a blob in `saveProject` and read it in `loadProject` (size-checked).
+
+## App behaviour (src/app/PanelProject.cpp)
+- `Document::dirty()` = any undo push/undo/redo, splat edit or `modified` since `markClean()`
+ (save, open, new). The window title shows `*` while dirty.
+- New / Open / Open Recent / drop / Quit / window close ask Save / Don't Save / Cancel when dirty
+ (never in `--render`, `--record` or demos).
+- The pref dir (`SDL_GetPrefPath`) holds `project.json` (10 recent files, autosave interval),
+ `autosave.sfproj` (every N minutes while dirty, default 5, removed once the work is saved) and
+ `clean_exit` (touched on normal exit). An autosave newer than `clean_exit` is offered for restore.
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 2125f4ba..c15133f5 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -11,6 +11,7 @@
#include "link/UnrealLink.h"
#include "core/Decimate.h"
#include "core/ImageTo3D.h"
+#include "core/Project.h"
#include "core/Script.h"
#include "render/GL.h"
@@ -42,7 +43,7 @@ namespace {
const SDL_DialogFileFilter kObjFilters[] = {{"Wavefront OBJ", "obj"}, {"All files", "*"}};
const SDL_DialogFileFilter kGlbFilters[] = {{"glTF binary", "glb"}, {"All files", "*"}};
const SDL_DialogFileFilter kBrushFilters[] = {{"SculptForge brush", "sfbrush"}, {"All files", "*"}};
-const SDL_DialogFileFilter kModelFilters[] = {{"Models and splats", "obj;fbx;glb;gltf;ply;splat;usda;usd;usdz"}, {"All files", "*"}};
+const SDL_DialogFileFilter kModelFilters[] = {{"Projects, models and splats", "sfproj;obj;fbx;glb;gltf;ply;splat;usda;usd;usdz"}, {"All files", "*"}};
const SDL_DialogFileFilter kFbxFilters[] = {{"FBX", "fbx"}, {"All files", "*"}};
const SDL_DialogFileFilter kUsdFilters[] = {{"USDZ package", "usdz"}, {"USD text", "usda"}};
const SDL_DialogFileFilter kSplatFilters[] = {{"Gaussian splats (PLY)", "ply"}, {"glTF splats", "glb"}, {"OpenUSD", "usda;usdz"}};
@@ -195,6 +196,7 @@ bool App::init(const AppOptions& options) {
ImGui_ImplOpenGL3_Init("#version 330 core");
for (int i = 0; i < int(FileAction::Count); ++i) dialogRequests_[i] = {this, FileAction(i)};
+ initProject(); // before opening anything, so it lands in the recent files
runCommand("new_sphere");
if (!options.openPath.empty()) openPath(options.openPath);
if (!options.script.empty()) {
@@ -389,7 +391,9 @@ int App::run() {
renderer_.draw(camera_, fbW, fbH, renderSettings_);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
SDL_GL_SwapWindow(window_);
+ tickProject(dt);
}
+ finishProject();
return 0;
}
@@ -403,10 +407,10 @@ void App::handleEvent(const SDL_Event& e) {
switch (e.type) {
case SDL_EVENT_QUIT:
- running_ = false;
+ requestQuit();
break;
case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
- if (e.window.windowID == SDL_GetWindowID(window_)) running_ = false;
+ if (e.window.windowID == SDL_GetWindowID(window_)) requestQuit();
break;
case SDL_EVENT_PEN_PROXIMITY_IN:
penSeen_ = true;
@@ -433,7 +437,7 @@ void App::handleEvent(const SDL_Event& e) {
onKey(e.key.key, e.key.mod);
break;
case SDL_EVENT_DROP_FILE:
- if (e.drop.data) openPath(e.drop.data);
+ if (e.drop.data) openPathConfirmed(e.drop.data);
break;
default:
break;
@@ -501,12 +505,9 @@ void App::onKey(SDL_Keycode key, SDL_Keymod mod) {
case SDLK_Z: runCommand(shift ? "redo" : "undo"); break;
case SDLK_Y: runCommand("redo"); break;
case SDLK_D: runCommand("subdivide"); break;
- case SDLK_O: openFileDialog(); break;
- case SDLK_S:
- if (shift || doc_.path.empty()) saveFileDialog(FileAction::SaveObj);
- else runCommand("save_obj");
- break;
- case SDLK_N: runCommand("new_sphere"); break;
+ case SDLK_O: confirmDiscard([this] { openFileDialog(); }); break;
+ case SDLK_S: saveProjectAs(shift); break;
+ case SDLK_N: confirmDiscard([this] { runCommand("new_sphere"); }); break;
case SDLK_E: saveFileDialog(FileAction::ExportGlb); break;
case SDLK_U: sendToUnreal(); break;
default: break;
@@ -648,10 +649,11 @@ void App::endStroke() {
void App::runCommand(const std::string& name, const Args& args) {
if (doc_.sculptor.strokeActive()) endStroke();
+ if (name == "save_project") storeProjectSettings();
CommandResult r = commands_.execute(doc_, name, args);
status_ = r.message;
if (r.ok && name != "export_glb" && name != "export_lods" && name != "export_usd" && name != "export_fbx" &&
- name != "export_unreal" && name.rfind("unreal_", 0) != 0 && name != "save_obj" &&
+ name != "export_unreal" && name.rfind("unreal_", 0) != 0 && name != "save_obj" && name != "save_project" &&
name != "mesh_info" && name.rfind("brush_", 0) != 0 && name.rfind("splat_", 0) != 0 && name != "mesh_to_splats") {
clearLods();
playingLayer_ = -1;
@@ -663,6 +665,7 @@ void App::runCommand(const std::string& name, const Args& args) {
name == "image_relief" || name == "image_inflate" || name == "splat_to_mesh" ||
(name == "splat_transform" && args.contains("fit"))))
camera_.frame(sceneBounds());
+ afterCommand(name, args, r);
updateTitle();
}
@@ -678,12 +681,13 @@ void SDLCALL onFileChosen(void* userdata, const char* const* files, int) {
void App::queueFile(FileAction action, std::string path) {
if (action != FileAction::OpenObj && action != FileAction::LoadBrush && action != FileAction::OpenImage &&
- std::filesystem::path(std::u8string(path.begin(), path.end())).extension().empty())
+ !path.empty() && std::filesystem::path(std::u8string(path.begin(), path.end())).extension().empty())
path += action == FileAction::SaveObj ? ".obj"
: action == FileAction::SaveBrush ? ".sfbrush"
: action == FileAction::ExportUsd ? ".usdz"
: action == FileAction::SaveSplats ? ".ply"
: action == FileAction::ExportUnreal ? ".fbx"
+ : action == FileAction::SaveProject ? ".sfproj"
: ".glb";
std::lock_guard lock(pendingMutex_);
pendingFiles_.push_back({action, std::move(path)});
@@ -756,6 +760,7 @@ void App::processPendingFiles() {
{"ratio", double(lodRatio_)}});
break;
}
+ case FileAction::SaveProject: saveProjectTo(f.path); break;
case FileAction::Count: break;
}
}
@@ -804,7 +809,9 @@ void App::updateTitle() {
std::string name = doc_.path.empty()
? std::string("Untitled")
: std::filesystem::path(std::u8string(doc_.path.begin(), doc_.path.end())).filename().string();
- std::string title = (doc_.modified ? "* " : "") + name + " - SculptForge";
+ std::string title = (doc_.dirty() ? "* " : "") + name + " - SculptForge";
+ if (title == windowTitle_) return; // called every frame
+ windowTitle_ = title;
SDL_SetWindowTitle(window_, title.c_str());
}
@@ -813,6 +820,7 @@ void App::updateTitle() {
// ---------------------------------------------------------------------------
void App::drawUi() {
+ drawProjectPopups();
if (hideUi_) return; // demos: clean beauty shots
drawMenuBar();
drawToolPanel();
@@ -885,16 +893,16 @@ void App::drawUi() {
void App::drawMenuBar() {
if (!ImGui::BeginMainMenuBar()) return;
if (ImGui::BeginMenu("File")) {
- if (ImGui::MenuItem("New Sphere", "Ctrl+N")) runCommand("new_sphere");
- if (ImGui::MenuItem("New Plane")) runCommand("new_plane");
+ if (ImGui::MenuItem("New Sphere", "Ctrl+N")) confirmDiscard([this] { runCommand("new_sphere"); });
+ if (ImGui::MenuItem("New Plane")) confirmDiscard([this] { runCommand("new_plane"); });
ImGui::Separator();
- if (ImGui::MenuItem("Open Model...", "Ctrl+O")) openFileDialog();
+ if (ImGui::MenuItem("Open...", "Ctrl+O")) confirmDiscard([this] { openFileDialog(); });
if (ImGui::MenuItem("Generate 3D..."))
SDL_ShowOpenFileDialog(onFileChosen, &dialogRequests_[int(FileAction::OpenImage)], window_, kImageFilters, 2,
nullptr, false);
- if (ImGui::MenuItem("Save", "Ctrl+S", false, !doc_.path.empty())) runCommand("save_obj");
- if (ImGui::MenuItem("Save As...", "Ctrl+Shift+S")) saveFileDialog(FileAction::SaveObj);
+ drawFileMenuProjectItems(); // Open Recent, Save, Save As, autosave
ImGui::Separator();
+ if (ImGui::MenuItem("Export OBJ...")) saveFileDialog(FileAction::SaveObj);
if (ImGui::MenuItem("Export GLB (blend shapes)...", "Ctrl+E")) saveFileDialog(FileAction::ExportGlb);
if (ImGui::MenuItem("Export LOD Chain...")) saveFileDialog(FileAction::ExportLods);
if (ImGui::MenuItem("Export USD / USDZ...")) saveFileDialog(FileAction::ExportUsd);
@@ -902,7 +910,7 @@ void App::drawMenuBar() {
if (ImGui::MenuItem("Send to Unreal", "Ctrl+U", false, !pendingUnreal_.valid())) sendToUnreal();
if (ImGui::MenuItem("Save Splats...", nullptr, false, !doc_.splats.empty())) saveFileDialog(FileAction::SaveSplats);
ImGui::Separator();
- if (ImGui::MenuItem("Quit")) running_ = false;
+ if (ImGui::MenuItem("Quit")) requestQuit();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Edit")) {
diff --git a/src/app/App.h b/src/app/App.h
index e6de675a..a400111f 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -13,6 +13,7 @@
#include <SDL3/SDL.h>
#include <imgui.h>
+#include <functional>
#include <future>
#include <memory>
#include <mutex>
@@ -49,7 +50,7 @@ public:
int run(); // returns the process exit code
void shutdown();
- enum class FileAction { OpenObj, SaveObj, ExportGlb, ExportLods, SaveBrush, LoadBrush, OpenImage, ExportUsd, SaveSplats, ExportUnreal, Count };
+ enum class FileAction { OpenObj, SaveObj, ExportGlb, ExportLods, SaveBrush, LoadBrush, OpenImage, ExportUsd, SaveSplats, ExportUnreal, SaveProject, Count };
struct DialogRequest {
App* app;
FileAction action;
@@ -229,6 +230,36 @@ private:
const Mesh* lastDisplayed_ = nullptr;
std::mutex pendingMutex_;
std::vector<PendingFile> pendingFiles_;
+
+ // Projects, unsaved-changes safety, recent files and autosave (PanelProject.cpp).
+ bool interactive() const; // false for --render, --record and demos: never prompt
+ void initProject(); // end of init(): recent files, autosave restore offer
+ void finishProject(); // clean exit: marks the session closed normally
+ void tickProject(float dt);
+ void saveProjectAs(bool forceDialog); // Ctrl+S (dialog only when needed) / Ctrl+Shift+S
+ void saveProjectTo(const std::string& path);
+ void storeProjectSettings(); // camera, render, brush and symmetry -> doc_.projectSettings
+ void applyProjectSettings(); // and back, after opening a project
+ void afterCommand(const std::string& name, const Args& args, const CommandResult& r);
+ // Runs `action` now, or after the Save / Don't Save / Cancel prompt if there are unsaved changes.
+ void confirmDiscard(std::function<void()> action);
+ void requestQuit();
+ void openPathConfirmed(const std::string& path); // prompts first if the file replaces the scene
+ void drawProjectPopups();
+ void drawFileMenuProjectItems();
+ void rememberRecent(const std::string& path);
+ void saveProjectPrefs();
+ std::string prefDir_;
+ std::vector<std::string> recentFiles_;
+ std::function<void()> discardAction_;
+ bool openUnsavedPopup_ = false;
+ bool continueAfterSave_ = false; // run discardAction_ once the Save As dialog saved
+ bool offerRestore_ = false;
+ int autosaveMinutes_ = 5; // 0 = off
+ float autosaveTimer_ = 0.0f;
+ uint64_t autosaveRevision_ = ~uint64_t(0);
+ bool autosaveWritten_ = false;
+ std::string windowTitle_;
};
} // namespace sf
diff --git a/src/app/PanelProject.cpp b/src/app/PanelProject.cpp
new file mode 100644
index 00000000..763c50ae
--- /dev/null
+++ b/src/app/PanelProject.cpp
@@ -0,0 +1,382 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Project files in the app: Save / Save As (.sfproj), the unsaved-changes
+// prompt (Save / Don't Save / Cancel) before new, open and quit, File > Open
+// Recent and autosave with crash recovery. Prompts only appear in interactive
+// sessions; --render, --record and demos run straight through.
+#include "app/App.h"
+
+#include "core/Project.h"
+
+#include <imgui.h>
+
+#include <algorithm>
+#include <cctype>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+#include <system_error>
+
+namespace sf {
+
+namespace {
+
+const SDL_DialogFileFilter kProjectFilters[] = {{"SculptForge project", "sfproj"}, {"All files", "*"}};
+constexpr const char* kUnsavedPopup = "Unsaved Changes";
+constexpr const char* kRestorePopup = "Restore Autosave?";
+
+std::filesystem::path fsPath(const std::string& p) { return std::filesystem::path(std::u8string(p.begin(), p.end())); }
+std::string utf8(const std::filesystem::path& p) {
+ auto s = p.u8string();
+ return std::string(s.begin(), s.end());
+}
+std::string autosavePath(const std::string& prefDir) { return prefDir + "autosave.sfproj"; }
+bool fileExists(const std::string& p) {
+ std::error_code ec;
+ return std::filesystem::is_regular_file(fsPath(p), ec);
+}
+
+Json vec3Json(const glm::vec3& v) {
+ Json a = Json::array();
+ for (int i = 0; i < 3; ++i) a.push(double(v[i]));
+ return a;
+}
+void readVec3(const Json& a, glm::vec3& v) {
+ if (a.size() != 3) return;
+ for (int i = 0; i < 3; ++i) v[i] = float(a[size_t(i)].asNumber(v[i]));
+}
+void readFloat(const Json& j, const char* key, float& v) { v = float(j[key].asNumber(v)); }
+void readBool(const Json& j, const char* key, bool& v) { v = j[key].asBool(v); }
+
+// Save As dialog: a cancelled dialog is reported as an empty path so a pending
+// "save, then quit/open/new" is dropped instead of firing on a later save.
+void SDLCALL onProjectChosen(void* userdata, const char* const* files, int) {
+ auto* req = static_cast<App::DialogRequest*>(userdata);
+ req->app->queueFile(req->action, files && files[0] ? std::string(files[0]) : std::string());
+}
+
+} // namespace
+
+bool App::interactive() const { return options_.renderPath.empty() && options_.recordPath.empty() && !demo_; }
+
+void App::initProject() {
+ if (!interactive()) return;
+ if (char* pref = SDL_GetPrefPath("SculptForge", "SculptForge")) {
+ prefDir_ = pref;
+ SDL_free(pref);
+ }
+ if (prefDir_.empty()) return;
+ std::ifstream f(fsPath(prefDir_ + "project.json"), std::ios::binary);
+ Json prefs;
+ std::string err;
+ if (f && Json::parse(std::string(std::istreambuf_iterator<char>(f), {}), prefs, err)) {
+ for (const auto& p : prefs["recent_files"].items())
+ if (p.isString()) recentFiles_.push_back(p.asString());
+ autosaveMinutes_ = std::clamp(int(prefs["autosave_minutes"].asNumber(autosaveMinutes_)), 0, 120);
+ }
+ recentFiles_ = pruneRecentFiles(std::move(recentFiles_), fileExists);
+
+ // An autosave newer than the last clean exit means the previous session ended unexpectedly.
+ std::error_code ec;
+ const auto autosave = fsPath(autosavePath(prefDir_)), marker = fsPath(prefDir_ + "clean_exit");
+ if (std::filesystem::is_regular_file(autosave, ec)) {
+ const auto saved = std::filesystem::last_write_time(autosave, ec);
+ std::error_code ec2;
+ const auto exited = std::filesystem::last_write_time(marker, ec2);
+ offerRestore_ = !ec && (ec2 || saved > exited);
+ }
+}
+
+void App::finishProject() {
+ if (!interactive() || prefDir_.empty()) return;
+ saveProjectPrefs();
+ std::ofstream(fsPath(prefDir_ + "clean_exit"), std::ios::binary | std::ios::trunc) << "SculptForge exited normally\n";
+}
+
+void App::saveProjectPrefs() {
+ if (prefDir_.empty()) return;
+ Json prefs = Json::object(), recent = Json::array();
+ for (const auto& p : recentFiles_) recent.push(p);
+ prefs.set("recent_files", std::move(recent));
+ prefs.set("autosave_minutes", autosaveMinutes_);
+ std::ofstream(fsPath(prefDir_ + "project.json"), std::ios::binary | std::ios::trunc) << prefs.dump(true);
+}
+
+void App::rememberRecent(const std::string& path) {
+ if (path.empty() || prefDir_.empty()) return;
+ std::error_code ec;
+ std::string full = utf8(std::filesystem::absolute(fsPath(path), ec).lexically_normal());
+ if (ec) full = path;
+ if (full == utf8(fsPath(autosavePath(prefDir_)).lexically_normal())) return;
+ recentFiles_ = addRecentFile(std::move(recentFiles_), full);
+ saveProjectPrefs();
+}
+
+void App::tickProject(float dt) {
+ updateTitle();
+ if (!interactive() || prefDir_.empty()) return;
+ if (!doc_.dirty()) {
+ autosaveTimer_ = 0.0f;
+ if (autosaveWritten_) { // nothing left to recover
+ std::error_code ec;
+ std::filesystem::remove(fsPath(autosavePath(prefDir_)), ec);
+ autosaveWritten_ = false;
+ autosaveRevision_ = ~uint64_t(0);
+ }
+ return;
+ }
+ autosaveTimer_ += dt;
+ const uint64_t revision = doc_.undo.revision() * 1000003u + doc_.splatsVersion;
+ if (autosaveMinutes_ <= 0 || autosaveTimer_ < float(autosaveMinutes_) * 60.0f || doc_.sculptor.strokeActive() ||
+ revision == autosaveRevision_)
+ return;
+ autosaveTimer_ = 0.0f;
+ storeProjectSettings();
+ std::string err;
+ if (saveProject(autosavePath(prefDir_), doc_, err)) {
+ autosaveRevision_ = revision;
+ autosaveWritten_ = true;
+ SDL_Log("Autosaved to %s", autosavePath(prefDir_).c_str());
+ } else {
+ status_ = "Autosave failed: " + err;
+ }
+}
+
+void App::saveProjectAs(bool forceDialog) {
+ if (!forceDialog && isProjectPath(doc_.path)) {
+ saveProjectTo(doc_.path);
+ return;
+ }
+ std::string suggestion;
+ if (!doc_.path.empty()) suggestion = utf8(fsPath(doc_.path).replace_extension(kProjectExtension));
+ SDL_ShowSaveFileDialog(onProjectChosen, &dialogRequests_[int(FileAction::SaveProject)], window_, kProjectFilters, 2,
+ suggestion.empty() ? nullptr : suggestion.c_str());
+}
+
+void App::saveProjectTo(const std::string& path) {
+ if (path.empty()) { // dialog cancelled
+ continueAfterSave_ = false;
+ discardAction_ = nullptr;
+ return;
+ }
+ runCommand("save_project", {{"path", path}});
+ if (continueAfterSave_) {
+ continueAfterSave_ = false;
+ auto action = std::move(discardAction_);
+ discardAction_ = nullptr;
+ if (!doc_.dirty() && action) action(); // only once the work is really saved
+ }
+}
+
+void App::storeProjectSettings() {
+ Json& s = doc_.projectSettings;
+ if (!s.isObject()) s = Json::object();
+ Json cam = Json::object();
+ cam.set("target", vec3Json(camera_.target));
+ cam.set("distance", double(camera_.distance));
+ cam.set("yaw", double(camera_.yaw));
+ cam.set("pitch", double(camera_.pitch));
+ cam.set("fov_y", double(camera_.fovY));
+ s.set("camera", std::move(cam));
+
+ Json render = Json::object();
+ render.set("wireframe", renderSettings_.wireframe);
+ render.set("base_color", vec3Json(renderSettings_.baseColor));
+ render.set("show_polypaint", renderSettings_.showPolypaint);
+ render.set("show_mask", renderSettings_.showMask);
+ render.set("show_polygroups", renderSettings_.showPolygroups);
+ render.set("show_mesh", renderSettings_.showMesh);
+ render.set("show_splats", renderSettings_.showSplats);
+ render.set("splat_opacity", double(renderSettings_.splatOpacity));
+ s.set("render", std::move(render));
+
+ Json brush = Json::object();
+ brush.set("type", brushName(brush_));
+ brush.set("radius_px", double(radiusPx_));
+ brush.set("strength", double(strength_));
+ brush.set("invert", invertToggle_);
+ brush.set("front_faces_only", frontFacesOnly_);
+ brush.set("pressure_strength", pressureStrength_);
+ brush.set("pressure_size", pressureSize_);
+ s.set("brush", std::move(brush));
+
+ Json sym = Json::object();
+ sym.set("x", symmetry_.x);
+ sym.set("y", symmetry_.y);
+ sym.set("z", symmetry_.z);
+ s.set("symmetry", std::move(sym));
+}
+
+// Lenient: anything missing keeps its current value.
+void App::applyProjectSettings() {
+ const Json& s = doc_.projectSettings;
+ if (const Json& cam = s["camera"]; cam.isObject()) {
+ readVec3(cam["target"], camera_.target);
+ readFloat(cam, "distance", camera_.distance);
+ readFloat(cam, "yaw", camera_.yaw);
+ readFloat(cam, "pitch", camera_.pitch);
+ readFloat(cam, "fov_y", camera_.fovY);
+ camera_.distance = std::max(camera_.distance, 1e-4f);
+ camera_.fovY = std::clamp(camera_.fovY, 0.05f, 3.0f);
+ }
+ if (const Json& r = s["render"]; r.isObject()) {
+ readBool(r, "wireframe", renderSettings_.wireframe);
+ readVec3(r["base_color"], renderSettings_.baseColor);
+ readBool(r, "show_polypaint", renderSettings_.showPolypaint);
+ readBool(r, "show_mask", renderSettings_.showMask);
+ readBool(r, "show_polygroups", renderSettings_.showPolygroups);
+ readBool(r, "show_mesh", renderSettings_.showMesh);
+ readBool(r, "show_splats", renderSettings_.showSplats);
+ readFloat(r, "splat_opacity", renderSettings_.splatOpacity);
+ }
+ if (const Json& b = s["brush"]; b.isObject()) {
+ for (int i = 0; i < int(BrushType::Count); ++i)
+ if (b["type"].asString() == brushName(BrushType(i))) brush_ = BrushType(i);
+ readFloat(b, "radius_px", radiusPx_);
+ readFloat(b, "strength", strength_);
+ radiusPx_ = std::clamp(radiusPx_, 2.0f, 800.0f);
+ strength_ = std::clamp(strength_, 0.0f, 1.0f);
+ readBool(b, "invert", invertToggle_);
+ readBool(b, "front_faces_only", frontFacesOnly_);
+ readBool(b, "pressure_strength", pressureStrength_);
+ readBool(b, "pressure_size", pressureSize_);
+ }
+ if (const Json& sym = s["symmetry"]; sym.isObject()) {
+ readBool(sym, "x", symmetry_.x);
+ readBool(sym, "y", symmetry_.y);
+ readBool(sym, "z", symmetry_.z);
+ }
+}
+
+void App::afterCommand(const std::string& name, const Args& args, const CommandResult& r) {
+ if (!r.ok) return;
+ const std::string path = argString(args, "path", doc_.path);
+ const bool project = name == "open_project" || (name == "open" && isProjectPath(path));
+ if (project) {
+ if (!doc_.projectSettings["camera"].isObject()) camera_.frame(sceneBounds()); // e.g. saved by the CLI
+ applyProjectSettings(); // after runCommand framed the camera, so the saved view wins
+ }
+ if (project || name == "open" || name == "open_obj" || name == "save_project" || name == "save_obj")
+ rememberRecent(path);
+}
+
+void App::confirmDiscard(std::function<void()> action) {
+ if (!interactive() || !doc_.dirty()) {
+ action();
+ return;
+ }
+ discardAction_ = std::move(action);
+ continueAfterSave_ = false;
+ openUnsavedPopup_ = true;
+}
+
+void App::requestQuit() {
+ confirmDiscard([this] { running_ = false; });
+}
+
+void App::openPathConfirmed(const std::string& path) {
+ // Images go to the Image to 3D panel and brushes into the library: no scene change.
+ std::string ext = fsPath(path).extension().string();
+ for (auto& c : ext) c = char(std::tolower(static_cast<unsigned char>(c)));
+ if (Image::isImagePath(path) || ext == ".sfbrush") openPath(path);
+ else confirmDiscard([this, path] { openPath(path); });
+}
+
+void App::drawFileMenuProjectItems() {
+ if (ImGui::BeginMenu("Open Recent", !recentFiles_.empty())) {
+ const size_t before = recentFiles_.size();
+ recentFiles_ = pruneRecentFiles(std::move(recentFiles_), fileExists);
+ if (recentFiles_.size() != before) saveProjectPrefs();
+ std::string chosen;
+ for (size_t i = 0; i < recentFiles_.size(); ++i) {
+ const std::string label = utf8(fsPath(recentFiles_[i]).filename()) + "##recent" + std::to_string(i);
+ if (ImGui::MenuItem(label.c_str())) chosen = recentFiles_[i];
+ if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", recentFiles_[i].c_str());
+ }
+ ImGui::Separator();
+ if (ImGui::MenuItem("Clear Recent")) {
+ recentFiles_.clear();
+ saveProjectPrefs();
+ }
+ ImGui::EndMenu();
+ if (!chosen.empty()) openPathConfirmed(chosen);
+ }
+ if (ImGui::MenuItem("Save", "Ctrl+S")) saveProjectAs(false);
+ if (ImGui::MenuItem("Save As...", "Ctrl+Shift+S")) saveProjectAs(true);
+ ImGui::SetNextItemWidth(120.0f * uiScale_);
+ ImGui::SliderInt("Autosave (min)", &autosaveMinutes_, 0, 60, autosaveMinutes_ ? "%d" : "off");
+ if (ImGui::IsItemDeactivatedAfterEdit()) saveProjectPrefs();
+}
+
+void App::drawProjectPopups() {
+ const ImVec2 center = ImGui::GetMainViewport()->GetCenter();
+ if (openUnsavedPopup_) {
+ ImGui::OpenPopup(kUnsavedPopup);
+ openUnsavedPopup_ = false;
+ }
+ ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
+ if (ImGui::BeginPopupModal(kUnsavedPopup, nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
+ const std::string name = doc_.path.empty() ? std::string("Untitled") : utf8(fsPath(doc_.path).filename());
+ ImGui::Text("Save changes to %s before continuing?", name.c_str());
+ ImGui::TextDisabled("Your changes will be lost if you don't save them.");
+ ImGui::Spacing();
+ const float w = 110.0f * uiScale_;
+ if (ImGui::Button("Save", ImVec2(w, 0)) || ImGui::IsKeyPressed(ImGuiKey_Enter)) {
+ ImGui::CloseCurrentPopup();
+ if (isProjectPath(doc_.path)) {
+ saveProjectTo(doc_.path);
+ auto action = std::move(discardAction_);
+ discardAction_ = nullptr;
+ if (!doc_.dirty() && action) action();
+ } else {
+ continueAfterSave_ = true;
+ saveProjectAs(true);
+ }
+ }
+ ImGui::SameLine();
+ if (ImGui::Button("Don't Save", ImVec2(w, 0))) {
+ ImGui::CloseCurrentPopup();
+ auto action = std::move(discardAction_);
+ discardAction_ = nullptr;
+ if (action) action();
+ }
+ ImGui::SameLine();
+ if (ImGui::Button("Cancel", ImVec2(w, 0)) || ImGui::IsKeyPressed(ImGuiKey_Escape)) {
+ ImGui::CloseCurrentPopup();
+ discardAction_ = nullptr;
+ }
+ ImGui::EndPopup();
+ }
+
+ if (offerRestore_) {
+ ImGui::OpenPopup(kRestorePopup);
+ offerRestore_ = false;
+ }
+ ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
+ if (ImGui::BeginPopupModal(kRestorePopup, nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
+ ImGui::TextUnformatted("SculptForge did not close normally last time.");
+ ImGui::TextUnformatted("Restore the autosaved work?");
+ ImGui::Spacing();
+ const float w = 110.0f * uiScale_;
+ const std::string autosave = autosavePath(prefDir_);
+ if (ImGui::Button("Restore", ImVec2(w, 0))) {
+ ImGui::CloseCurrentPopup();
+ runCommand("open_project", {{"path", autosave}});
+ if (doc_.path == autosave) {
+ doc_.path.clear(); // Save asks where to put it
+ doc_.modified = true; // still unsaved work
+ autosaveWritten_ = true;
+ }
+ }
+ ImGui::SameLine();
+ if (ImGui::Button("Discard", ImVec2(w, 0))) {
+ ImGui::CloseCurrentPopup();
+ std::error_code ec;
+ std::filesystem::remove(fsPath(autosave), ec);
+ }
+ ImGui::EndPopup();
+ }
+}
+
+} // namespace sf
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index 22da76d6..91692a58 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -6,6 +6,7 @@
#include "core/EnginePresets.h"
#include "core/ImageTo3D.h"
#include "core/Primitives.h"
+#include "core/Project.h"
#include "core/Splats.h"
#include "core/Voxel.h"
#include "io/FbxIO.h"
@@ -108,10 +109,12 @@ CommandRegistry::CommandRegistry() {
add({"open",
"Open a file: models (.obj, .fbx, .glb, .gltf, .ply, .usda, .usdz) replace the scene; Gaussian splats "
"(.ply/.splat captures, KHR_gaussian_splatting .glb, USD ParticleField) load as a reference next to the sculpt. "
- "glTF morph targets and FBX/USD blend shapes become sculpt layers.",
+ "glTF morph targets and FBX/USD blend shapes become sculpt layers. SculptForge projects (.sfproj) "
+ "restore the whole scene.",
{{"path", T::String, "File path (UTF-8).", true}},
[](Document& doc, const Args& a) -> CommandResult {
std::string path = argString(a, "path");
+ if (isProjectPath(path)) return openProjectCommand(doc, path);
const std::string ext = lowerExtension(path);
Mesh m;
SplatCloud splats;
@@ -127,7 +130,8 @@ CommandRegistry::CommandRegistry() {
} else ok = loadObj(path, m, err);
if (!ok) return {false, err};
std::string msg = "Opened " + path;
- if (m.triangleCount()) {
+ const bool hasMesh = m.triangleCount() > 0;
+ if (hasMesh) {
doc.setMesh(std::move(m));
doc.path = ext == ".obj" ? path : std::string(); // other formats are exported explicitly
msg += " (" + std::to_string(doc.mesh.triangleCount()) + " triangles" +
@@ -138,6 +142,7 @@ CommandRegistry::CommandRegistry() {
doc.splatsChanged();
msg += " (" + std::to_string(doc.splats.size()) + " Gaussian splats, SH degree " +
std::to_string(doc.splats.shDegree) + ")";
+ if (hasMesh) doc.markClean(); // a model with its own splats is one freshly opened scene
}
return {true, msg};
}});
@@ -234,7 +239,7 @@ CommandRegistry::CommandRegistry() {
std::string err;
if (!saveObj(path, doc.mesh, err)) return {false, err};
doc.path = path;
- doc.modified = false;
+ doc.markClean();
return {true, "Saved " + path};
}});
@@ -596,6 +601,8 @@ CommandRegistry::CommandRegistry() {
<< b.max.y << ", " << b.max.z << ")";
return {true, s.str()};
}});
+
+ registerProjectCommands(*this);
}
void CommandRegistry::add(Command cmd) { commands_.push_back(std::move(cmd)); }
diff --git a/src/core/Document.cpp b/src/core/Document.cpp
index 02feb890..82261f59 100644
--- a/src/core/Document.cpp
+++ b/src/core/Document.cpp
@@ -12,7 +12,7 @@ void Document::setMesh(Mesh m) {
mesh.topologyDirty = true;
bvh.build(mesh);
undo.clear();
- modified = false;
+ markClean();
activeLayer = -1;
bvhDirty = false;
}
diff --git a/src/core/Document.h b/src/core/Document.h
index 1920f1a7..3e178daa 100644
--- a/src/core/Document.h
+++ b/src/core/Document.h
@@ -4,6 +4,7 @@
#include "core/BVH.h"
#include "core/BrushRecipe.h"
+#include "core/Json.h"
#include "core/Mesh.h"
#include "core/Sculpt.h"
#include "core/Splats.h"
@@ -22,7 +23,7 @@ struct Document {
UndoStack undo;
Sculptor sculptor;
std::string path; // empty until saved/loaded
- bool modified = false;
+ bool modified = false; // set by edits the undo stack doesn't see (e.g. layer weights)
int activeLayer = -1; // sculpt layer strokes write into (-1 = base)
// Recipe brush library (built-ins, loaded .sfbrush files, AI-made brushes).
std::vector<BrushRecipe> brushes = builtinBrushRecipes();
@@ -43,10 +44,29 @@ struct Document {
// Asset name derived from the document path (for exports).
std::string assetName() const;
+ // App-owned state saved in projects (camera, render, brush, symmetry, ...):
+ // the app fills it before saving and applies it after opening; the core
+ // keeps it as loaded so CLI and scripts round-trip it unchanged.
+ Json projectSettings = Json::object();
+
+ // Unsaved changes: any undoable edit, splat edit or `modified` since the
+ // last markClean() (save, open, new scene).
+ bool dirty() const {
+ return modified || undo.revision() != cleanRevision_ || splatsVersion != cleanSplatsVersion_;
+ }
+ void markClean() {
+ modified = false;
+ cleanRevision_ = undo.revision();
+ cleanSplatsVersion_ = splatsVersion;
+ }
+
// Replaces the mesh and clears the edit history.
void setMesh(Mesh m);
// Replaces the mesh as an undoable topology change.
void replaceMeshUndoable(Mesh m, std::string label);
+
+private:
+ uint64_t cleanRevision_ = 0, cleanSplatsVersion_ = 0;
};
} // namespace sf
diff --git a/src/core/Project.cpp b/src/core/Project.cpp
new file mode 100644
index 00000000..4b2dd3b5
--- /dev/null
+++ b/src/core/Project.cpp
@@ -0,0 +1,409 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Project.h"
+
+#include "io/Zip.h"
+
+#include <algorithm>
+#include <bit>
+#include <cctype>
+#include <cstring>
+#include <filesystem>
+#include <map>
+#include <system_error>
+
+#ifndef SCULPTFORGE_VERSION
+#define SCULPTFORGE_VERSION "unknown"
+#endif
+
+namespace sf {
+
+namespace {
+
+constexpr const char* kFormatName = "SculptForge project";
+constexpr const char* kManifestName = "manifest.json";
+// Top-level manifest keys owned by the core; every other key belongs to
+// Document::projectSettings (camera, render, brush, symmetry, ...).
+const char* const kCoreKeys[] = {"format", "version", "app_version", "mesh", "layers", "active_layer",
+ "brushes", "active_brush", "splats"};
+
+std::filesystem::path fsPath(const std::string& p) { return std::filesystem::path(std::u8string(p.begin(), p.end())); }
+
+bool isCoreKey(const std::string& key) {
+ return std::any_of(std::begin(kCoreKeys), std::end(kCoreKeys), [&](const char* k) { return key == k; });
+}
+
+// --- Blobs: little-endian arrays of f32 / u32 / u8 with N components per element ---
+
+enum class Scalar { F32, U32, U8 };
+
+const char* scalarName(Scalar s) { return s == Scalar::F32 ? "f32" : s == Scalar::U32 ? "u32" : "u8"; }
+size_t scalarSize(Scalar s) { return s == Scalar::U8 ? 1 : 4; }
+
+void put32(std::vector<uint8_t>& out, uint32_t v) {
+ for (int i = 0; i < 4; ++i) out.push_back(uint8_t(v >> (8 * i)));
+}
+uint32_t get32(const uint8_t* p) { return uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24; }
+
+class Writer {
+public:
+ // Adds a blob and returns its manifest descriptor.
+ Json add(const std::string& file, Scalar type, int components, size_t count, std::vector<uint8_t> data) {
+ Json d = Json::object();
+ d.set("file", file);
+ d.set("type", scalarName(type));
+ d.set("components", components);
+ d.set("count", double(count));
+ entries.push_back({file, std::move(data)});
+ return d;
+ }
+ Json floats(const std::string& file, const float* v, size_t count, int components) {
+ std::vector<uint8_t> data;
+ data.reserve(count * size_t(components) * 4);
+ for (size_t i = 0; i < count * size_t(components); ++i) put32(data, std::bit_cast<uint32_t>(v[i]));
+ return add(file, Scalar::F32, components, count, std::move(data));
+ }
+ Json vec3s(const std::string& file, const std::vector<glm::vec3>& v) {
+ return floats(file, v.empty() ? nullptr : &v[0].x, v.size(), 3);
+ }
+ Json uints(const std::string& file, const uint32_t* v, size_t count, int components) {
+ std::vector<uint8_t> data;
+ data.reserve(count * size_t(components) * 4);
+ for (size_t i = 0; i < count * size_t(components); ++i) put32(data, v[i]);
+ return add(file, Scalar::U32, components, count, std::move(data));
+ }
+ Json bytes(const std::string& file, const std::vector<uint8_t>& v) { return add(file, Scalar::U8, 1, v.size(), v); }
+
+ std::vector<ZipEntry> entries;
+};
+
+class Reader {
+public:
+ std::map<std::string, const std::vector<uint8_t>*> files;
+ std::string error;
+
+ // Validates `desc` against the expected layout and returns its bytes (nullptr + error on mismatch).
+ const uint8_t* blob(const Json& desc, const char* what, Scalar type, int components, size_t count) {
+ if (!desc.isObject()) return fail(what, "is missing");
+ if (desc["type"].asString() != scalarName(type) || int(desc["components"].asNumber()) != components)
+ return fail(what, "has an unexpected layout");
+ if (desc["count"].asNumber(-1) != double(count)) return fail(what, "has the wrong size");
+ auto it = files.find(desc["file"].asString());
+ if (it == files.end()) return fail(what, "data is missing from the archive");
+ if (it->second->size() != count * size_t(components) * scalarSize(type)) return fail(what, "data is truncated");
+ static const uint8_t kEmpty = 0;
+ return it->second->empty() ? &kEmpty : it->second->data();
+ }
+ bool floats(const Json& desc, const char* what, size_t count, int components, float* out) {
+ const uint8_t* p = blob(desc, what, Scalar::F32, components, count);
+ if (!p) return false;
+ for (size_t i = 0; i < count * size_t(components); ++i) out[i] = std::bit_cast<float>(get32(p + 4 * i));
+ return true;
+ }
+ bool vec3s(const Json& desc, const char* what, size_t count, std::vector<glm::vec3>& out) {
+ out.resize(count);
+ return floats(desc, what, count, 3, count ? &out[0].x : nullptr);
+ }
+ bool uints(const Json& desc, const char* what, size_t count, int components, uint32_t* out) {
+ const uint8_t* p = blob(desc, what, Scalar::U32, components, count);
+ if (!p) return false;
+ for (size_t i = 0; i < count * size_t(components); ++i) out[i] = get32(p + 4 * i);
+ return true;
+ }
+
+private:
+ const uint8_t* fail(const char* what, const char* problem) {
+ if (error.empty()) error = std::string("Project ") + what + " " + problem;
+ return nullptr;
+ }
+};
+
+Json matrixJson(const glm::mat4& m) {
+ Json a = Json::array();
+ for (int c = 0; c < 4; ++c)
+ for (int r = 0; r < 4; ++r) a.push(double(m[c][r]));
+ return a;
+}
+
+glm::mat4 matrixFromJson(const Json& a) {
+ glm::mat4 m(1.0f);
+ if (a.size() != 16) return m;
+ for (int c = 0; c < 4; ++c)
+ for (int r = 0; r < 4; ++r) m[c][r] = float(a[size_t(c * 4 + r)].asNumber(c == r ? 1.0 : 0.0));
+ return m;
+}
+
+size_t countOf(const Json& j) {
+ const double n = j.asNumber(-1);
+ return n >= 0 && n < 4.0e9 ? size_t(n) : size_t(-1);
+}
+
+} // namespace
+
+bool isProjectPath(const std::string& path) {
+ std::string ext = fsPath(path).extension().string();
+ std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+ return ext == kProjectExtension;
+}
+
+bool saveProject(const std::string& path, const Document& doc, std::string& error) {
+ const Mesh& m = doc.mesh;
+ Writer w;
+ Json manifest = Json::object();
+ manifest.set("format", kFormatName);
+ manifest.set("version", kProjectVersion);
+ manifest.set("app_version", SCULPTFORGE_VERSION);
+
+ Json mesh = Json::object();
+ mesh.set("vertex_count", double(m.vertexCount()));
+ mesh.set("triangle_count", double(m.triangleCount()));
+ mesh.set("positions", w.vec3s("mesh/positions.bin", m.positions));
+ mesh.set("triangles", w.uints("mesh/triangles.bin", m.triangles.empty() ? nullptr : &m.triangles[0].x,
+ m.triangleCount(), 3));
+ if (!m.layers.empty()) mesh.set("base", w.vec3s("mesh/base.bin", m.base));
+ if (m.hasMask()) mesh.set("mask", w.floats("mesh/mask.bin", m.mask.data(), m.mask.size(), 1));
+ if (m.hasColors()) mesh.set("colors", w.vec3s("mesh/colors.bin", m.colors));
+ if (m.hasPolygroups()) mesh.set("polygroups", w.uints("mesh/polygroups.bin", m.polygroups.data(), m.polygroups.size(), 1));
+ if (m.hasHidden()) mesh.set("hidden", w.bytes("mesh/hidden.bin", m.hidden));
+ if (m.hasUvs()) mesh.set("uvs", w.floats("mesh/uvs.bin", &m.uvs[0].x, m.uvs.size(), 2));
+ manifest.set("mesh", std::move(mesh));
+
+ Json layers = Json::array();
+ for (size_t i = 0; i < m.layers.size(); ++i) {
+ Json l = Json::object();
+ l.set("name", m.layers[i].name);
+ l.set("weight", double(m.layers[i].weight));
+ l.set("delta", w.vec3s("layers/" + std::to_string(i) + ".bin", m.layers[i].delta));
+ layers.push(std::move(l));
+ }
+ manifest.set("layers", std::move(layers));
+ manifest.set("active_layer", doc.activeLayer);
+
+ Json brushes = Json::array();
+ for (const auto& b : doc.brushes) brushes.push(b.toJson());
+ manifest.set("brushes", std::move(brushes));
+ if (doc.activeBrush >= 0 && doc.activeBrush < int(doc.brushes.size()))
+ manifest.set("active_brush", doc.brushes[size_t(doc.activeBrush)].name);
+
+ if (!doc.splats.empty()) {
+ const SplatCloud& s = doc.splats;
+ if (std::string v = s.validate(); !v.empty()) {
+ error = "Cannot save splats: " + v;
+ return false;
+ }
+ Json splats = Json::object();
+ splats.set("count", double(s.size()));
+ splats.set("sh_degree", s.shDegree);
+ splats.set("name", s.name);
+ splats.set("transform", matrixJson(s.transform));
+ splats.set("positions", w.vec3s("splats/positions.bin", s.positions));
+ std::vector<float> rot;
+ rot.reserve(s.size() * 4);
+ for (const auto& q : s.rotations) rot.insert(rot.end(), {q.x, q.y, q.z, q.w});
+ splats.set("rotations", w.floats("splats/rotations.bin", rot.data(), s.size(), 4));
+ splats.set("scales", w.vec3s("splats/scales.bin", s.scales));
+ splats.set("opacities", w.floats("splats/opacities.bin", s.opacities.data(), s.size(), 1));
+ splats.set("sh", w.vec3s("splats/sh.bin", s.sh));
+ manifest.set("splats", std::move(splats));
+ }
+
+ if (doc.projectSettings.isObject())
+ for (const auto& [key, value] : doc.projectSettings.members())
+ if (!isCoreKey(key)) manifest.set(key, value);
+
+ const std::string text = manifest.dump(true);
+ w.entries.insert(w.entries.begin(), ZipEntry{kManifestName, std::vector<uint8_t>(text.begin(), text.end())});
+
+ // Write next to the target and rename, so a failed save never destroys the previous file.
+ const std::string tmp = path + ".tmp";
+ if (!writeStoredZip(tmp, w.entries, 64, error)) return false;
+ std::error_code ec;
+ std::filesystem::rename(fsPath(tmp), fsPath(path), ec);
+ if (ec) {
+ std::filesystem::remove(fsPath(tmp), ec);
+ error = "Cannot write " + path;
+ return false;
+ }
+ return true;
+}
+
+bool loadProject(const std::string& path, Document& doc, std::string& error) {
+ std::vector<ZipEntry> entries;
+ if (!readStoredZip(path, entries, error)) return false;
+ Reader r;
+ for (const auto& e : entries) r.files[e.name] = &e.data;
+ auto mf = r.files.find(kManifestName);
+ if (mf == r.files.end()) {
+ error = path + " is not a SculptForge project (no manifest)";
+ return false;
+ }
+ Json manifest;
+ if (!Json::parse(std::string(mf->second->begin(), mf->second->end()), manifest, error) || !manifest.isObject() ||
+ manifest["format"].asString() != kFormatName) {
+ error = path + " is not a SculptForge project" + (error.empty() ? "" : " (" + error + ")");
+ return false;
+ }
+ const double version = manifest["version"].asNumber(0);
+ if (version > kProjectVersion) {
+ error = path + " was saved by a newer SculptForge (" + manifest["app_version"].asString() +
+ ", project format " + std::to_string(int(version)) + "); this version reads format " +
+ std::to_string(kProjectVersion) + ". Please update SculptForge to open it.";
+ return false;
+ }
+ if (version < 1) {
+ error = path + " has an invalid project version";
+ return false;
+ }
+
+ // Mesh
+ const Json& mj = manifest["mesh"];
+ const size_t nv = countOf(mj["vertex_count"]), nt = countOf(mj["triangle_count"]);
+ if (nv == size_t(-1) || nt == size_t(-1)) {
+ error = "Project mesh has no valid vertex/triangle count";
+ return false;
+ }
+ Mesh m;
+ m.triangles.resize(nt);
+ if (!r.vec3s(mj["positions"], "positions", nv, m.positions) ||
+ !r.uints(mj["triangles"], "triangles", nt, 3, nt ? &m.triangles[0].x : nullptr)) {
+ error = r.error;
+ return false;
+ }
+ for (const auto& t : m.triangles)
+ if (t.x >= nv || t.y >= nv || t.z >= nv) {
+ error = "Project triangles reference missing vertices";
+ return false;
+ }
+ if (mj.has("mask")) {
+ m.mask.resize(nv);
+ r.floats(mj["mask"], "mask", nv, 1, m.mask.data());
+ }
+ if (mj.has("colors")) r.vec3s(mj["colors"], "colors", nv, m.colors);
+ if (mj.has("polygroups")) {
+ m.polygroups.resize(nt);
+ r.uints(mj["polygroups"], "polygroups", nt, 1, m.polygroups.data());
+ }
+ if (mj.has("hidden")) {
+ if (const uint8_t* p = r.blob(mj["hidden"], "hidden flags", Scalar::U8, 1, nt)) m.hidden.assign(p, p + nt);
+ }
+ if (mj.has("uvs")) {
+ m.uvs.resize(nt * 3);
+ r.floats(mj["uvs"], "uvs", nt * 3, 2, nt ? &m.uvs[0].x : nullptr);
+ }
+ const Json& lj = manifest["layers"];
+ if (lj.size()) {
+ r.vec3s(mj["base"], "base positions", nv, m.base);
+ for (size_t i = 0; i < lj.size(); ++i) {
+ SculptLayer layer;
+ layer.name = lj[i]["name"].asString();
+ layer.weight = float(lj[i]["weight"].asNumber(1.0));
+ r.vec3s(lj[i]["delta"], "layer offsets", nv, layer.delta);
+ m.layers.push_back(std::move(layer));
+ }
+ }
+ if (!r.error.empty()) {
+ error = r.error;
+ return false;
+ }
+ m.rebuildTopology();
+ if (!m.layers.empty()) m.evaluateAll();
+ m.recomputeAllNormals();
+
+ // Splats
+ SplatCloud splats;
+ if (const Json& sj = manifest["splats"]; sj.isObject()) {
+ const size_t n = countOf(sj["count"]);
+ const int degree = int(sj["sh_degree"].asNumber(0));
+ if (n == size_t(-1) || degree < 0 || degree > 3) {
+ error = "Project splats have an invalid size";
+ return false;
+ }
+ splats.resize(n, degree);
+ splats.name = sj["name"].isString() ? sj["name"].asString() : splats.name;
+ splats.transform = matrixFromJson(sj["transform"]);
+ std::vector<float> rot(n * 4);
+ r.vec3s(sj["positions"], "splat positions", n, splats.positions);
+ r.floats(sj["rotations"], "splat rotations", n, 4, rot.data());
+ r.vec3s(sj["scales"], "splat scales", n, splats.scales);
+ r.floats(sj["opacities"], "splat opacities", n, 1, splats.opacities.data());
+ r.vec3s(sj["sh"], "splat colours", n * size_t(splats.shCount()), splats.sh);
+ if (!r.error.empty()) {
+ error = r.error;
+ return false;
+ }
+ for (size_t i = 0; i < n; ++i) splats.rotations[i] = glm::quat(rot[i * 4 + 3], rot[i * 4], rot[i * 4 + 1], rot[i * 4 + 2]);
+ }
+
+ // Everything parsed: replace the scene.
+ doc.setMesh(std::move(m));
+ doc.splats = std::move(splats);
+ doc.splatsChanged();
+ const int active = int(manifest["active_layer"].asNumber(-1));
+ doc.activeLayer = active >= 0 && active < int(doc.mesh.layers.size()) ? active : -1;
+ for (const auto& b : manifest["brushes"].items())
+ if (b.isObject()) doc.addBrush(BrushRecipe::fromJson(b));
+ doc.activeBrush = -1;
+ const std::string& activeBrush = manifest["active_brush"].asString();
+ for (size_t i = 0; i < doc.brushes.size() && !activeBrush.empty(); ++i)
+ if (doc.brushes[i].name == activeBrush) doc.activeBrush = int(i);
+ doc.projectSettings = Json::object();
+ for (const auto& [key, value] : manifest.members())
+ if (!isCoreKey(key)) doc.projectSettings.set(key, value);
+ doc.path = path;
+ doc.markClean();
+ return true;
+}
+
+CommandResult openProjectCommand(Document& doc, const std::string& path) {
+ std::string err;
+ if (!loadProject(path, doc, err)) return {false, err};
+ std::string msg = "Opened project " + path + " (" + std::to_string(doc.mesh.triangleCount()) + " triangles";
+ if (!doc.mesh.layers.empty()) msg += ", " + std::to_string(doc.mesh.layers.size()) + " layers";
+ if (!doc.splats.empty()) msg += ", " + std::to_string(doc.splats.size()) + " splats";
+ return {true, msg + ")"};
+}
+
+void registerProjectCommands(CommandRegistry& registry) {
+ using T = ParamSpec::Type;
+ registry.add({"save_project",
+ "Save everything (mesh, mask, polypaint, polygroups, visibility, UVs, sculpt layers, splats, brushes "
+ "and view settings) as a SculptForge project (.sfproj).",
+ {{"path", T::String, "Output .sfproj path (UTF-8). Defaults to the current project path.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ std::string path = argString(a, "path", isProjectPath(doc.path) ? doc.path : std::string());
+ if (path.empty()) return {false, "No path given"};
+ if (fsPath(path).extension().empty()) path += kProjectExtension;
+ std::string err;
+ if (!saveProject(path, doc, err)) return {false, err};
+ doc.path = path;
+ doc.markClean();
+ return {true, "Saved project " + path};
+ }});
+ registry.add({"open_project", "Open a SculptForge project (.sfproj), replacing the current scene.",
+ {{"path", T::String, ".sfproj path (UTF-8).", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ return openProjectCommand(doc, argString(a, "path"));
+ }});
+}
+
+// ---------------------------------------------------------------------------
+// Recent files
+// ---------------------------------------------------------------------------
+
+std::vector<std::string> addRecentFile(std::vector<std::string> list, const std::string& path, size_t limit) {
+ if (path.empty()) return list;
+ list.erase(std::remove(list.begin(), list.end(), path), list.end());
+ list.insert(list.begin(), path);
+ if (list.size() > limit) list.resize(limit);
+ return list;
+}
+
+std::vector<std::string> pruneRecentFiles(std::vector<std::string> list,
+ const std::function<bool(const std::string&)>& exists) {
+ std::vector<std::string> out;
+ for (auto& p : list)
+ if (!p.empty() && std::find(out.begin(), out.end(), p) == out.end() && exists(p)) out.push_back(std::move(p));
+ return out;
+}
+
+} // namespace sf
diff --git a/src/core/Project.h b/src/core/Project.h
new file mode 100644
index 00000000..d47cee6c
--- /dev/null
+++ b/src/core/Project.h
@@ -0,0 +1,50 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Native project files (.sfproj): an uncompressed ZIP holding a JSON manifest
+// ("manifest.json") and little-endian binary blobs for the mesh, its optional
+// attributes, sculpt layers and any loaded Gaussian splats.
+//
+// The manifest names every blob with its element type and count, so readers
+// ignore anything they don't know (forward compatible) and refuse files whose
+// `version` is newer than kProjectVersion with a clear message.
+#pragma once
+
+#include "core/Commands.h"
+#include "core/Document.h"
+
+#include <functional>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+constexpr int kProjectVersion = 1;
+constexpr const char* kProjectExtension = ".sfproj";
+
+// True for paths ending in .sfproj (any case).
+bool isProjectPath(const std::string& path);
+
+// Writes `doc` (mesh, attributes, layers, splats, brush library, active layer
+// and doc.projectSettings) to `path`. Does not change the document.
+bool saveProject(const std::string& path, const Document& doc, std::string& error);
+// Replaces the scene with the project at `path`. On failure `doc` is untouched.
+// Sets doc.path, clears the edit history and marks the document clean.
+bool loadProject(const std::string& path, Document& doc, std::string& error);
+// loadProject wrapped as a command result (open_project, and `open` for .sfproj paths).
+CommandResult openProjectCommand(Document& doc, const std::string& path);
+
+// save_project / open_project (called by the CommandRegistry constructor).
+void registerProjectCommands(CommandRegistry& registry);
+
+// --- Recent files (pure list logic; the app persists the list) ---
+
+constexpr size_t kMaxRecentFiles = 10;
+// Moves `path` to the front (adding it if new), keeping at most `limit` entries.
+std::vector<std::string> addRecentFile(std::vector<std::string> list, const std::string& path,
+ size_t limit = kMaxRecentFiles);
+// Drops entries for which `exists` is false, and empty or duplicate entries.
+std::vector<std::string> pruneRecentFiles(std::vector<std::string> list,
+ const std::function<bool(const std::string&)>& exists);
+
+} // namespace sf
diff --git a/src/core/Undo.cpp b/src/core/Undo.cpp
index 263ecbe1..c54fb07a 100644
--- a/src/core/Undo.cpp
+++ b/src/core/Undo.cpp
@@ -68,6 +68,7 @@ void UndoStack::push(UndoRecord record) {
if (record.empty()) return;
undo_.push_back(std::move(record));
redo_.clear();
+ ++revision_;
enforceBudget();
}
@@ -110,6 +111,7 @@ bool UndoStack::undo(Mesh& mesh, BVH& bvh) {
undo_.pop_back();
apply(r, mesh, bvh);
redo_.push_back(std::move(r));
+ ++revision_;
return true;
}
@@ -119,6 +121,7 @@ bool UndoStack::redo(Mesh& mesh, BVH& bvh) {
redo_.pop_back();
apply(r, mesh, bvh);
undo_.push_back(std::move(r));
+ ++revision_;
return true;
}
diff --git a/src/core/Undo.h b/src/core/Undo.h
index e8d0dbf0..3f67aeb9 100644
--- a/src/core/Undo.h
+++ b/src/core/Undo.h
@@ -74,6 +74,8 @@ public:
bool undo(Mesh& mesh, BVH& bvh);
bool redo(Mesh& mesh, BVH& bvh);
void clear();
+ // Bumped by every push, undo and redo (unsaved-changes tracking).
+ uint64_t revision() const { return revision_; }
size_t byteBudget = size_t(1) << 30; // 1 GiB
@@ -82,6 +84,7 @@ private:
void enforceBudget();
std::deque<UndoRecord> undo_, redo_;
+ uint64_t revision_ = 0;
};
} // namespace sf
diff --git a/tests/test_project.cpp b/tests/test_project.cpp
new file mode 100644
index 00000000..609cc268
--- /dev/null
+++ b/tests/test_project.cpp
@@ -0,0 +1,277 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Project files (.sfproj): lossless round trip of the mesh, every optional
+// attribute, layers and splats; version handling; dirty tracking; recent files.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/Primitives.h"
+#include "core/Project.h"
+#include "io/Zip.h"
+
+#include <filesystem>
+
+using namespace sf;
+
+namespace {
+
+Document makeRichDoc() {
+ Mesh m = makeIcosphere(2);
+ m.ensureMask();
+ m.ensureColors();
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {
+ m.mask[v] = float(v % 7) / 6.0f;
+ m.colors[v] = glm::vec3(float(v % 3) * 0.5f, 0.25f, 1.0f / float(v + 1));
+ }
+ m.ensurePolygroups();
+ m.ensureHidden();
+ for (uint32_t t = 0; t < m.triangleCount(); ++t) {
+ m.polygroups[t] = t % 5 + 100000u;
+ m.hidden[t] = t % 11 == 0 ? 1 : 0;
+ }
+ m.uvs.resize(m.triangleCount() * 3);
+ for (size_t i = 0; i < m.uvs.size(); ++i) m.uvs[i] = glm::vec2(float(i) * 0.001f, -float(i) * 0.5f);
+ m.addLayer("Smile");
+ m.addLayer("Blink L");
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {
+ m.layers[0].delta[v] = glm::vec3(0.01f * float(v % 4), 0, 0);
+ m.layers[1].delta[v] = glm::vec3(0, -0.002f * float(v % 9), 0.1f);
+ }
+ m.setLayerWeight(0, 0.75f);
+ m.setLayerWeight(1, -0.3f);
+
+ Document doc = makeDoc(std::move(m));
+ doc.activeLayer = 1;
+ doc.splats.resize(37, 1);
+ for (size_t i = 0; i < doc.splats.size(); ++i) {
+ doc.splats.positions[i] = glm::vec3(float(i), -float(i) * 0.5f, 2.0f);
+ doc.splats.rotations[i] = glm::normalize(glm::quat(1.0f, 0.1f * float(i), 0.2f, -0.3f));
+ doc.splats.scales[i] = glm::vec3(0.01f, 0.02f, 0.03f * float(i + 1));
+ doc.splats.opacities[i] = float(i) / 37.0f;
+ }
+ for (size_t i = 0; i < doc.splats.sh.size(); ++i) doc.splats.sh[i] = glm::vec3(float(i) * 0.01f, 0.5f, -0.25f);
+ doc.splats.transform = glm::mat4(2.0f);
+ doc.splats.transform[3] = glm::vec4(1, 2, 3, 1);
+ doc.splats.name = "Capture";
+ BrushRecipe recipe;
+ recipe.name = "Test Scales";
+ recipe.description = "for the project test";
+ doc.activeBrush = doc.addBrush(recipe);
+ Json cam = Json::object();
+ cam.set("distance", 7.5);
+ doc.projectSettings.set("camera", std::move(cam));
+ doc.projectSettings.set("future_feature", "kept");
+ return doc;
+}
+
+std::string readManifest(const std::string& path) {
+ std::vector<ZipEntry> entries;
+ std::string err;
+ if (!readStoredZip(path, entries, err)) return {};
+ for (const auto& e : entries)
+ if (e.name == "manifest.json") return std::string(e.data.begin(), e.data.end());
+ return {};
+}
+
+// Rewrites the manifest of an existing project with `edit` applied.
+bool editManifest(const std::string& path, const std::function<void(Json&)>& edit) {
+ std::vector<ZipEntry> entries;
+ std::string err;
+ if (!readStoredZip(path, entries, err)) return false;
+ for (auto& e : entries) {
+ if (e.name != "manifest.json") continue;
+ Json j;
+ if (!Json::parse(std::string(e.data.begin(), e.data.end()), j, err)) return false;
+ edit(j);
+ const std::string text = j.dump();
+ e.data.assign(text.begin(), text.end());
+ }
+ return writeStoredZip(path, entries, 1, err);
+}
+
+} // namespace
+
+TEST(project_round_trip_every_attribute) {
+ Document doc = makeRichDoc();
+ const std::string path = tempPath("sf_project_roundtrip.sfproj");
+ std::string err;
+ CHECK(saveProject(path, doc, err));
+
+ Document back;
+ back.splats.resize(3, 0); // replaced by the project's splats
+ CHECK(loadProject(path, back, err));
+ const Mesh& a = doc.mesh;
+ const Mesh& b = back.mesh;
+ CHECK(b.positions == a.positions);
+ CHECK(b.triangles == a.triangles);
+ CHECK(b.base == a.base);
+ CHECK(b.mask == a.mask);
+ CHECK(b.colors == a.colors);
+ CHECK(b.polygroups == a.polygroups);
+ CHECK(b.hidden == a.hidden);
+ CHECK(b.uvs == a.uvs);
+ CHECK(b.layers.size() == 2);
+ for (size_t i = 0; i < b.layers.size() && i < a.layers.size(); ++i) {
+ CHECK(b.layers[i].name == a.layers[i].name);
+ CHECK(b.layers[i].weight == a.layers[i].weight);
+ CHECK(b.layers[i].delta == a.layers[i].delta);
+ }
+ CHECK(b.normals.size() == b.vertexCount());
+ CHECK(back.activeLayer == 1);
+
+ const SplatCloud& sa = doc.splats;
+ const SplatCloud& sb = back.splats;
+ CHECK(sb.size() == sa.size() && sb.shDegree == sa.shDegree);
+ CHECK(sb.positions == sa.positions && sb.scales == sa.scales && sb.opacities == sa.opacities && sb.sh == sa.sh);
+ bool rotOk = sb.rotations.size() == sa.rotations.size();
+ for (size_t i = 0; rotOk && i < sa.rotations.size(); ++i)
+ rotOk = sb.rotations[i].x == sa.rotations[i].x && sb.rotations[i].y == sa.rotations[i].y &&
+ sb.rotations[i].z == sa.rotations[i].z && sb.rotations[i].w == sa.rotations[i].w;
+ CHECK(rotOk);
+ CHECK(sb.transform == sa.transform);
+ CHECK(sb.name == "Capture");
+
+ CHECK(back.activeBrush >= 0 && back.brushes[size_t(back.activeBrush)].name == "Test Scales");
+ CHECK(back.projectSettings["camera"]["distance"].asNumber() == 7.5);
+ CHECK(back.projectSettings["future_feature"].asString() == "kept");
+ CHECK(back.path == path);
+ CHECK(!back.dirty());
+ CHECK(!back.undo.canUndo());
+ std::filesystem::remove(path);
+}
+
+TEST(project_plain_mesh_keeps_attributes_empty) {
+ Document doc = makeDoc(makeIcosphere(1));
+ const std::string path = tempPath("sf_project_plain.sfproj");
+ std::string err;
+ CHECK(saveProject(path, doc, err));
+ Document back;
+ CHECK(loadProject(path, back, err));
+ CHECK(back.mesh.positions == doc.mesh.positions);
+ CHECK(!back.mesh.hasMask() && !back.mesh.hasColors() && !back.mesh.hasPolygroups() && !back.mesh.hasHidden() &&
+ !back.mesh.hasUvs());
+ CHECK(back.mesh.layers.empty() && back.mesh.base.empty() && back.splats.empty());
+ std::filesystem::remove(path);
+}
+
+TEST(project_commands_and_open) {
+ CommandRegistry reg;
+ Document doc = makeRichDoc();
+ const std::string path = tempPath("sf_project_cmd.sfproj");
+ std::filesystem::remove(path);
+ CHECK(!reg.execute(doc, "save_project").ok); // no project path yet
+ const std::string noExt = path.substr(0, path.size() - std::string(kProjectExtension).size());
+ CHECK(reg.execute(doc, "save_project", {{"path", noExt}}).ok);
+ CHECK(doc.path == path && std::filesystem::exists(path) && !doc.dirty());
+ CHECK(reg.execute(doc, "save_project").ok); // defaults to the project path
+
+ Document other = makeDoc(makeIcosphere(1));
+ CommandResult r = reg.execute(other, "open", {{"path", path}});
+ CHECK(r.ok);
+ CHECK(other.mesh.triangleCount() == doc.mesh.triangleCount() && other.mesh.layers.size() == 2);
+ Document third;
+ CHECK(reg.execute(third, "open_project", {{"path", path}}).ok);
+ CHECK(third.mesh.colors == doc.mesh.colors);
+ CHECK(!reg.execute(third, "open_project", {{"path", tempPath("sf_project_missing.sfproj")}}).ok);
+ CHECK(isProjectPath("a/b/Scene.SFPROJ") && !isProjectPath("scene.obj"));
+ std::filesystem::remove(path);
+}
+
+TEST(project_version_handling) {
+ Document doc = makeDoc(makeIcosphere(1));
+ const std::string path = tempPath("sf_project_version.sfproj");
+ std::string err;
+ CHECK(saveProject(path, doc, err));
+ const std::string manifest = readManifest(path);
+ CHECK(manifest.find("\"version\": 1") != std::string::npos || manifest.find("\"version\":1") != std::string::npos);
+ CHECK(manifest.find("app_version") != std::string::npos);
+
+ // Unknown fields (top level and inside the mesh) are ignored.
+ CHECK(editManifest(path, [](Json& j) {
+ j.set("shiny_new_thing", Json::object());
+ Json mesh = j["mesh"];
+ mesh.set("creases", "future blob");
+ j.set("mesh", std::move(mesh));
+ }));
+ Document back;
+ CHECK(loadProject(path, back, err));
+ CHECK(back.mesh.positions == doc.mesh.positions);
+
+ // A newer format is refused with a clear message and leaves the document alone.
+ CHECK(editManifest(path, [](Json& j) {
+ j.set("version", kProjectVersion + 1);
+ j.set("app_version", "9.9.9");
+ }));
+ Document keep = makeDoc(makePlane(4));
+ const size_t tris = keep.mesh.triangleCount();
+ err.clear();
+ CHECK(!loadProject(path, keep, err));
+ CHECK(err.find("newer") != std::string::npos && err.find("9.9.9") != std::string::npos);
+ CHECK(keep.mesh.triangleCount() == tris);
+
+ // Not a project / corrupt blob.
+ CHECK(editManifest(path, [](Json& j) { j.set("format", "something else"); }));
+ CHECK(!loadProject(path, keep, err));
+ CHECK(saveProject(path, doc, err));
+ CHECK(editManifest(path, [](Json& j) {
+ Json mesh = j["mesh"];
+ mesh.set("vertex_count", double(j["mesh"]["vertex_count"].asNumber() + 1));
+ j.set("mesh", std::move(mesh));
+ }));
+ err.clear();
+ CHECK(!loadProject(path, keep, err) && !err.empty());
+ CHECK(keep.mesh.triangleCount() == tris);
+ std::filesystem::remove(path);
+}
+
+TEST(project_dirty_tracking) {
+ CommandRegistry reg;
+ Document doc;
+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 2.0}}).ok);
+ CHECK(!doc.dirty());
+ CHECK(reg.execute(doc, "subdivide").ok);
+ CHECK(doc.dirty());
+ const std::string path = tempPath("sf_project_dirty.sfproj");
+ CHECK(reg.execute(doc, "save_project", {{"path", path}}).ok);
+ CHECK(!doc.dirty());
+ CHECK(reg.execute(doc, "undo").ok);
+ CHECK(doc.dirty());
+ CHECK(reg.execute(doc, "redo").ok);
+ CHECK(doc.dirty()); // redo is a change too (conservative)
+ doc.markClean();
+ doc.mesh.ensureMask();
+ doc.undo.push(UndoRecord::captureMask(doc.mesh, "Mask All")); // e.g. a command another feature adds
+ CHECK(doc.dirty());
+ doc.markClean();
+ CHECK(reg.execute(doc, "layer_add", {{"name", std::string("L")}}).ok);
+ CHECK(doc.dirty());
+ doc.markClean();
+ CHECK(reg.execute(doc, "layer_set_weight", {{"index", 0.0}, {"weight", 0.5}}).ok);
+ CHECK(doc.dirty());
+ doc.markClean();
+ CHECK(reg.execute(doc, "mesh_to_splats", {{"count", 1000.0}}).ok);
+ CHECK(doc.dirty());
+ CHECK(reg.execute(doc, "open", {{"path", path}}).ok);
+ CHECK(!doc.dirty());
+ std::filesystem::remove(path);
+}
+
+TEST(project_recent_files_logic) {
+ std::vector<std::string> list;
+ list = addRecentFile(list, "/a.sfproj");
+ list = addRecentFile(list, "/b.obj");
+ list = addRecentFile(list, "/a.sfproj"); // moves to the front, no duplicate
+ CHECK((list == std::vector<std::string>{"/a.sfproj", "/b.obj"}));
+ list = addRecentFile(list, "");
+ CHECK(list.size() == 2);
+ for (int i = 0; i < 15; ++i) list = addRecentFile(list, "/f" + std::to_string(i));
+ CHECK(list.size() == kMaxRecentFiles);
+ CHECK(list.front() == "/f14" && list.back() == "/f5");
+ CHECK(addRecentFile({"x", "y", "z"}, "w", 2) == (std::vector<std::string>{"w", "x"}));
+
+ auto pruned = pruneRecentFiles({"/keep1", "/gone", "", "/keep1", "/keep2"},
+ [](const std::string& p) { return p != "/gone"; });
+ CHECK((pruned == std::vector<std::string>{"/keep1", "/keep2"}));
+ CHECK(pruneRecentFiles({"/x"}, [](const std::string&) { return false; }).empty());
+}