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.

ZBrush-style UI, workstream B: LightBox, thumbnails and pickers

islandmeddf90584db365
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 3a9eae53..8b8559c2 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -128,7 +128,10 @@ if(SCULPTFORGE_BUILD_APP)
src/app/Actions.cpp
src/app/Ui.cpp
src/app/UiLayout.cpp
- src/app/LightBoxStubs.cpp
+ src/app/LightBox.cpp
+ src/app/Thumbnails.cpp
+ src/app/Pickers.cpp
+ src/app/AssetLibrary.cpp
src/app/PanelMasking.cpp
src/app/PanelPolygroups.cpp
src/app/PanelBrushes.cpp
@@ -305,7 +308,7 @@ endif()
if(SCULPTFORGE_BUILD_TESTS)
# tests/test_main.cpp plus every tests/test_*.cpp (add a file to add tests; see tests/TestHarness.h).
file(GLOB SCULPTFORGE_TEST_SOURCES CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_*.cpp)
- add_executable(sculptforge_tests ${SCULPTFORGE_TEST_SOURCES} src/cli/McpServer.cpp)
+ add_executable(sculptforge_tests ${SCULPTFORGE_TEST_SOURCES} src/cli/McpServer.cpp src/app/AssetLibrary.cpp)
target_include_directories(sculptforge_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/tests)
target_link_libraries(sculptforge_tests PRIVATE sculptforge_core sculptforge_ai)
if(MSVC)
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 7617ab4c..42326419 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -218,6 +218,7 @@ bool App::init(const AppOptions& options) {
for (int i = 0; i < int(FileAction::Count); ++i) dialogRequests_[i] = {this, FileAction(i)};
initBrushLibrary(); // before a project can bring its own brushes
initProject(); // before opening anything, so it lands in the recent files
+ initLightBox();
runCommand("new_sphere");
if (!options.openPath.empty()) openPath(options.openPath);
if (!options.script.empty()) {
@@ -253,6 +254,7 @@ void App::shutdown() {
flushBrushEdits();
if (refTexture_) gl::DeleteTextures(1, &refTexture_);
gallery_.reset(); // its preview textures need the GL context
+ thumbs_.clear();
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplSDL3_Shutdown();
ImGui::DestroyContext();
@@ -606,6 +608,7 @@ void App::onMouseUp() {
}
void App::onKey(SDL_Keycode key, SDL_Keymod mod) {
+ if (lightBoxKey(key, mod)) return;
const bool ctrl = ctrlDown(mod);
const bool shift = (mod & SDL_KMOD_SHIFT) != 0;
if (ctrl) {
@@ -1044,6 +1047,7 @@ void App::updateTitle() {
void App::drawUi() {
drawProjectPopups();
if (hideUi_) return; // demos: clean beauty shots
+ drawLightBoxUi();
drawMenuBar();
drawToolPanel();
if (showSubToolsPanel_) drawSubToolsPanel();
diff --git a/src/app/App.h b/src/app/App.h
index 3191704c..5b20a995 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -4,6 +4,7 @@
#include "ai/BrushAssistant.h"
#include "app/Actions.h"
+#include "app/AssetLibrary.h"
#include "app/LightBox.h"
#include "app/Pickers.h"
#include "app/Thumbnails.h"
@@ -446,6 +447,18 @@ private:
// ---- LightBox (B): LightBox, thumbnails, pickers ----
LightBox lightbox_;
ThumbnailCache thumbs_;
+ friend struct PickerUi;
+ friend void drawAlphaGrid(App&, GridMode);
+ friend void drawMaterialGrid(App&, GridMode);
+ friend void drawStrokeGrid(App&, GridMode);
+ void initLightBox(); // end of init(): library folders, thumbnail cache, actions, project thumbnails
+ void drawLightBoxUi(); // every frame from drawUi: thumbnails, the LightBox, pickers, size / strength pop-ups
+ // The LightBox / picker shortcuts (, B M S I) until the action registry dispatches keys.
+ bool lightBoxKey(SDL_Keycode key, SDL_Keymod mod);
+ CanvasRect lightBoxCanvas() const; // the canvas until the shell provides canvasRect()
+ void quickSave(); // file.quicksave: a timestamped project in <library>/QuickSave
+ LibraryRoots library_;
+ FolderScanner libraryScanner_;
// ---- end LightBox (B) ----
// ---- Help/Console/Config (C): actions, help, command palette, console, config ----
diff --git a/src/app/AssetLibrary.cpp b/src/app/AssetLibrary.cpp
new file mode 100644
index 00000000..19ae7aa7
--- /dev/null
+++ b/src/app/AssetLibrary.cpp
@@ -0,0 +1,400 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "app/AssetLibrary.h"
+
+#include <algorithm>
+#include <cctype>
+#include <chrono>
+#include <cstdio>
+#include <ctime>
+#include <filesystem>
+#include <system_error>
+
+namespace sf {
+
+namespace fs = std::filesystem;
+
+namespace {
+
+fs::path fsPath(const std::string& p) { return fs::path(std::u8string(p.begin(), p.end())); }
+std::string utf8(const fs::path& p) {
+ const std::u8string s = p.u8string();
+ return std::string(s.begin(), s.end());
+}
+
+std::string lowerExt(const std::string& path) {
+ std::string ext = utf8(fsPath(path).extension());
+ std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+ return ext;
+}
+
+bool anyOf(const std::string& ext, std::initializer_list<const char*> list) {
+ return std::any_of(list.begin(), list.end(), [&](const char* e) { return ext == e; });
+}
+
+int64_t toEpoch(fs::file_time_type t) {
+ // file_clock -> system_clock without C++20 clock_cast (not on every standard library yet).
+ const auto sys = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
+ t - fs::file_time_type::clock::now() + std::chrono::system_clock::now());
+ return std::chrono::duration_cast<std::chrono::seconds>(sys.time_since_epoch()).count();
+}
+
+bool lessNoCase(const std::string& a, const std::string& b) {
+ return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), [](unsigned char x, unsigned char y) {
+ return std::tolower(x) < std::tolower(y);
+ });
+}
+
+} // namespace
+
+const char* primitiveName(Primitive p) {
+ switch (p) {
+ case Primitive::Sphere:
+ return "Sphere";
+ case Primitive::Cube:
+ return "Cube";
+ case Primitive::Plane:
+ return "Plane";
+ default:
+ return "";
+ }
+}
+
+const char* libraryTabName(LibraryTab tab) {
+ static const char* const names[] = {"Project", "Tool", "Brush", "Alpha", "Material",
+ "Image", "Splats", "QuickSave", "Recent"};
+ return tab < LibraryTab::Count ? names[int(tab)] : "";
+}
+
+const char* libraryTabId(LibraryTab tab) {
+ static const char* const ids[] = {"project", "tool", "brush", "alpha", "material",
+ "image", "splats", "quicksave", "recent"};
+ return tab < LibraryTab::Count ? ids[int(tab)] : "project";
+}
+
+LibraryTab libraryTabFromId(std::string_view id) {
+ for (int i = 0; i < int(LibraryTab::Count); ++i)
+ if (id == libraryTabId(LibraryTab(i))) return LibraryTab(i);
+ return LibraryTab::Project;
+}
+
+const char* libraryTabFolder(LibraryTab tab) {
+ switch (tab) {
+ case LibraryTab::Project:
+ return "Projects";
+ case LibraryTab::Tool:
+ return "Tools";
+ case LibraryTab::Brush:
+ return "Brushes";
+ case LibraryTab::Alpha:
+ return "Alphas";
+ case LibraryTab::Image:
+ return "Images";
+ case LibraryTab::Splats:
+ return "Splats";
+ case LibraryTab::QuickSave:
+ return "QuickSave";
+ default:
+ return "";
+ }
+}
+
+bool isMeshFile(const std::string& path) {
+ return anyOf(lowerExt(path), {".obj", ".glb", ".gltf", ".fbx", ".stl", ".ply", ".usda", ".usdz", ".usd", ".goz"});
+}
+bool isSplatFile(const std::string& path) { return anyOf(lowerExt(path), {".ply", ".splat"}); }
+bool isImageFile(const std::string& path) {
+ return anyOf(lowerExt(path), {".png", ".jpg", ".jpeg", ".bmp", ".tga", ".psd", ".gif", ".webp"});
+}
+bool isBrushFile(const std::string& path) { return lowerExt(path) == ".sfbrush"; }
+bool isProjectFile(const std::string& path) { return lowerExt(path) == ".sfproj"; }
+
+AssetKind fileKindForTab(LibraryTab tab, const std::string& path) {
+ switch (tab) {
+ case LibraryTab::Project:
+ return isProjectFile(path) ? AssetKind::Project : AssetKind::Folder;
+ case LibraryTab::Tool:
+ return isMeshFile(path) ? AssetKind::Mesh : AssetKind::Folder;
+ case LibraryTab::Brush:
+ return isBrushFile(path) ? AssetKind::BrushFile : AssetKind::Folder;
+ case LibraryTab::Alpha:
+ return isImageFile(path) ? AssetKind::AlphaFile : AssetKind::Folder;
+ case LibraryTab::Image:
+ return isImageFile(path) ? AssetKind::Image : AssetKind::Folder;
+ case LibraryTab::Splats:
+ return isSplatFile(path) ? AssetKind::Splat : AssetKind::Folder;
+ case LibraryTab::QuickSave:
+ return isProjectFile(path) ? AssetKind::Project : AssetKind::Folder;
+ case LibraryTab::Recent:
+ if (isProjectFile(path)) return AssetKind::Project;
+ if (isMeshFile(path)) return AssetKind::Mesh;
+ if (isSplatFile(path)) return AssetKind::Splat;
+ if (isImageFile(path)) return AssetKind::Image;
+ if (isBrushFile(path)) return AssetKind::BrushFile;
+ return AssetKind::Folder;
+ default:
+ return AssetKind::Folder;
+ }
+}
+
+std::string findBuiltinAssets(const std::string& exeDir) {
+ if (exeDir.empty()) return {};
+ std::error_code ec;
+ fs::path dir = fsPath(exeDir);
+ for (int up = 0; up < 4; ++up) {
+ for (const char* sub : {"assets", "share/sculptforge/assets", "Resources/assets"}) {
+ const fs::path p = dir / sub;
+ if (fs::is_directory(p / "demo", ec)) return utf8(p.lexically_normal());
+ }
+ if (!dir.has_parent_path() || dir.parent_path() == dir) break;
+ dir = dir.parent_path();
+ }
+ return {};
+}
+
+std::string defaultUserLibrary(const std::string& documentsDir, const std::string& prefDir) {
+ if (!documentsDir.empty()) return utf8(fsPath(documentsDir) / "SculptForge");
+ if (!prefDir.empty()) return utf8(fsPath(prefDir) / "library");
+ return {};
+}
+
+bool ensureUserLibrary(const std::string& root, std::string& error) {
+ if (root.empty()) {
+ error = "No library folder";
+ return false;
+ }
+ std::error_code ec;
+ for (int i = 0; i < int(LibraryTab::Count); ++i) {
+ const char* sub = libraryTabFolder(LibraryTab(i));
+ if (!*sub) continue;
+ fs::create_directories(fsPath(root) / sub, ec);
+ if (ec) {
+ error = "Cannot create " + utf8(fsPath(root) / sub) + ": " + ec.message();
+ return false;
+ }
+ }
+ return true;
+}
+
+int64_t modifiedTime(const std::string& path) {
+ std::error_code ec;
+ const auto t = fs::last_write_time(fsPath(path), ec);
+ return ec ? 0 : toEpoch(t);
+}
+
+std::vector<AssetEntry> listFolder(const std::string& dir, const std::function<AssetKind(const std::string&)>& accept,
+ bool newestFirst) {
+ std::vector<AssetEntry> folders, files;
+ std::error_code ec;
+ for (fs::directory_iterator it(fsPath(dir), fs::directory_options::skip_permission_denied, ec), end;
+ !ec && it != end; it.increment(ec)) {
+ const fs::path& p = it->path();
+ const std::string name = utf8(p.filename());
+ if (name.empty() || name[0] == '.') continue;
+ std::error_code e2;
+ AssetEntry a;
+ a.path = utf8(p);
+ if (it->is_directory(e2)) {
+ a.kind = AssetKind::Folder;
+ a.name = name;
+ folders.push_back(std::move(a));
+ continue;
+ }
+ if (!it->is_regular_file(e2)) continue;
+ a.kind = accept ? accept(a.path) : AssetKind::Folder;
+ if (a.kind == AssetKind::Folder) continue;
+ a.name = utf8(p.stem());
+ a.size = uint64_t(it->file_size(e2));
+ a.mtime = toEpoch(it->last_write_time(e2));
+ files.push_back(std::move(a));
+ }
+ auto byName = [](const AssetEntry& a, const AssetEntry& b) { return lessNoCase(a.name, b.name); };
+ std::sort(folders.begin(), folders.end(), byName);
+ if (newestFirst)
+ std::sort(files.begin(), files.end(),
+ [](const AssetEntry& a, const AssetEntry& b) { return a.mtime > b.mtime; });
+ else
+ std::sort(files.begin(), files.end(), byName);
+ folders.insert(folders.end(), std::make_move_iterator(files.begin()), std::make_move_iterator(files.end()));
+ return folders;
+}
+
+// ---------------------------------------------------------------------------
+// FolderScanner
+// ---------------------------------------------------------------------------
+
+FolderScanner::~FolderScanner() {
+ for (auto& [key, l] : listings_)
+ if (l.pending.valid()) l.pending.wait();
+}
+
+const std::vector<AssetEntry>* FolderScanner::get(const std::string& dir, const std::string& filterKey, Accept accept,
+ bool newestFirst) {
+ Listing& l = listings_[dir + "|" + filterKey];
+ if (!l.ready && !l.pending.valid()) {
+ l.dir = dir;
+ l.accept = std::move(accept);
+ l.newestFirst = newestFirst;
+ l.stamp = modifiedTime(dir);
+ l.checkedAt = now_;
+ l.pending = std::async(std::launch::async,
+ [dir, a = l.accept, newestFirst] { return listFolder(dir, a, newestFirst); });
+ }
+ return l.ready ? &l.entries : nullptr;
+}
+
+void FolderScanner::poll(double now, double recheckSeconds) {
+ now_ = now;
+ for (auto& [key, l] : listings_) {
+ if (l.pending.valid()) {
+ if (l.pending.wait_for(std::chrono::seconds(0)) != std::future_status::ready) continue;
+ l.entries = l.pending.get();
+ l.ready = true;
+ continue;
+ }
+ if (!l.ready || now - l.checkedAt < recheckSeconds) continue;
+ l.checkedAt = now;
+ // A folder's time stamp changes when files are added, removed or renamed in it; files
+ // rewritten in place are caught by their own time stamps in the thumbnail keys.
+ const int64_t stamp = modifiedTime(l.dir);
+ if (stamp == l.stamp) continue;
+ l.stamp = stamp;
+ l.pending = std::async(std::launch::async,
+ [dir = l.dir, a = l.accept, nf = l.newestFirst] { return listFolder(dir, a, nf); });
+ }
+}
+
+void FolderScanner::invalidate() {
+ for (auto& [key, l] : listings_) {
+ if (l.pending.valid()) continue; // its result lands soon anyway
+ l.stamp = -1;
+ l.checkedAt = -1e9;
+ }
+}
+
+bool FolderScanner::busy() const {
+ return std::any_of(listings_.begin(), listings_.end(), [](const auto& kv) { return kv.second.pending.valid(); });
+}
+
+// ---------------------------------------------------------------------------
+// Thumbnail keys
+// ---------------------------------------------------------------------------
+
+uint64_t fnv1a64(std::string_view data, uint64_t seed) {
+ uint64_t h = seed;
+ for (unsigned char c : data) {
+ h ^= c;
+ h *= 0x100000001b3ull;
+ }
+ return h;
+}
+
+std::string hex64(uint64_t v) {
+ char buf[17];
+ std::snprintf(buf, sizeof buf, "%016llx", static_cast<unsigned long long>(v));
+ return buf;
+}
+
+std::string fileThumbnailKey(const std::string& kind, const std::string& absPath, uint64_t size, int64_t mtime,
+ int pixels, int version) {
+ const std::string text = kind + "|" + absPath + "|" + std::to_string(size) + "|" + std::to_string(mtime) + "|" +
+ std::to_string(pixels) + "|" + std::to_string(version);
+ return hex64(fnv1a64(text));
+}
+
+std::string thumbnailCachePath(const std::string& cacheDir, const std::string& key) {
+ return utf8(fsPath(cacheDir) / (key + ".png"));
+}
+
+// ---------------------------------------------------------------------------
+// Brush pop-up letters
+// ---------------------------------------------------------------------------
+
+std::string typedName(const std::string& name) {
+ std::string out;
+ for (unsigned char c : name)
+ if (std::isalnum(c)) out += char(std::tolower(c));
+ return out;
+}
+
+std::vector<size_t> filterByTyped(const std::vector<std::string>& names, const std::string& typed, bool* substring) {
+ std::vector<size_t> out;
+ if (substring) *substring = false;
+ for (size_t i = 0; i < names.size(); ++i)
+ if (typed.empty() || typedName(names[i]).rfind(typed, 0) == 0) out.push_back(i);
+ if (!out.empty() || typed.empty()) return out;
+ if (substring) *substring = true;
+ for (size_t i = 0; i < names.size(); ++i)
+ if (typedName(names[i]).find(typed) != std::string::npos) out.push_back(i);
+ return out;
+}
+
+std::vector<std::pair<char, size_t>> letterBadges(const std::vector<std::string>& names,
+ const std::vector<size_t>& kept, const std::string& typed) {
+ std::vector<std::pair<char, size_t>> badges;
+ if (typed.empty()) return badges;
+ auto taken = [&](char c) {
+ return std::any_of(badges.begin(), badges.end(), [c](const auto& b) { return b.first == c; });
+ };
+ for (size_t i : kept) {
+ const std::string n = typedName(names[i]);
+ if (n.rfind(typed, 0) != 0) continue;
+ for (size_t k = typed.size(); k < n.size(); ++k)
+ if (std::isalpha(static_cast<unsigned char>(n[k])) && !taken(n[k])) {
+ badges.emplace_back(n[k], i);
+ break;
+ }
+ }
+ return badges;
+}
+
+// ---------------------------------------------------------------------------
+// QuickSave
+// ---------------------------------------------------------------------------
+
+std::string quickSaveName(int64_t epochSeconds, int serial) {
+ const std::time_t t = std::time_t(epochSeconds);
+ std::tm tm{};
+#if defined(_WIN32)
+ localtime_s(&tm, &t);
+#else
+ localtime_r(&t, &tm);
+#endif
+ char buf[64];
+ std::strftime(buf, sizeof buf, "QuickSave %Y-%m-%d %H-%M-%S", &tm);
+ std::string name = buf;
+ if (serial > 0) name += " (" + std::to_string(serial) + ")";
+ return name + ".sfproj";
+}
+
+std::string nextQuickSavePath(const std::string& folder, int64_t epochSeconds) {
+ std::error_code ec;
+ for (int serial = 0;; ++serial) {
+ const fs::path p = fsPath(folder) / fsPath(quickSaveName(epochSeconds, serial));
+ if (!fs::exists(p, ec)) return utf8(p);
+ }
+}
+
+size_t pruneQuickSaves(const std::string& folder, size_t keep) {
+ std::vector<AssetEntry> saves = listFolder(
+ folder,
+ [](const std::string& p) {
+ const std::string name = utf8(fsPath(p).filename());
+ return isProjectFile(p) && name.rfind("QuickSave ", 0) == 0 ? AssetKind::Project : AssetKind::Folder;
+ },
+ true);
+ saves.erase(
+ std::remove_if(saves.begin(), saves.end(), [](const AssetEntry& a) { return a.kind != AssetKind::Project; }),
+ saves.end());
+ // Same second: the name breaks the tie (later names sort after earlier ones).
+ std::stable_sort(saves.begin(), saves.end(), [](const AssetEntry& a, const AssetEntry& b) {
+ return a.mtime != b.mtime ? a.mtime > b.mtime : a.name > b.name;
+ });
+ size_t removed = 0;
+ std::error_code ec;
+ for (size_t i = keep; i < saves.size(); ++i)
+ if (fs::remove(fsPath(saves[i].path), ec)) ++removed;
+ return removed;
+}
+
+} // namespace sf
diff --git a/src/app/AssetLibrary.h b/src/app/AssetLibrary.h
new file mode 100644
index 00000000..1c394a6b
--- /dev/null
+++ b/src/app/AssetLibrary.h
@@ -0,0 +1,147 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// The asset library behind the LightBox: the built-in and user folders, what
+// each LightBox tab lists, folder scanning on a worker thread, QuickSave files
+// and the thumbnail cache keys. No GL or ImGui here, so the unit tests link it.
+#pragma once
+
+#include <cstdint>
+#include <functional>
+#include <future>
+#include <map>
+#include <memory>
+#include <string>
+#include <string_view>
+#include <vector>
+
+namespace sf {
+
+enum class AssetKind {
+ Folder, // a directory (double-click enters it)
+ Up, // the ".." tile at the start of a sub-folder
+ Project, // .sfproj
+ Mesh, // .obj .glb .gltf .fbx .stl .ply .usda .usdz .GoZ
+ Primitive, // built-in Sphere / Cube / Plane (index = Primitive)
+ BrushType, // built-in brush (index = BrushType, kPaintBrush = the Paint brush)
+ Recipe, // custom brush in the document (index into doc.brushes)
+ BrushFile, // .sfbrush not loaded yet
+ Alpha, // built-in alpha (name)
+ AlphaFile, // image used as an alpha
+ Material, // matcap (index; -1 = Studio)
+ Image, // reference image
+ Splat, // Gaussian splat capture (.ply .splat, splat .glb)
+};
+
+enum class Primitive { Sphere, Cube, Plane, Count };
+const char* primitiveName(Primitive p);
+constexpr int kPaintBrush = 1000; // AssetKind::BrushType index of the Paint brush
+
+struct AssetEntry {
+ AssetKind kind = AssetKind::Folder;
+ std::string name; // shown under the tile
+ std::string path; // absolute UTF-8 path (files and folders); empty for built-in items
+ int index = -1;
+ uint64_t size = 0; // bytes (files)
+ int64_t mtime = 0; // seconds since the epoch (files)
+};
+
+// The LightBox tabs, in the order they are shown.
+enum class LibraryTab { Project, Tool, Brush, Alpha, Material, Image, Splats, QuickSave, Recent, Count };
+const char* libraryTabName(LibraryTab tab); // "Project"
+const char* libraryTabId(LibraryTab tab); // "project" (UiLayout::lightboxTab)
+LibraryTab libraryTabFromId(std::string_view id); // unknown -> Project
+// User-library sub-folder a tab browses ("Projects", "Tools", ...); "" for tabs without one.
+const char* libraryTabFolder(LibraryTab tab);
+
+// File types (case-insensitive extension checks).
+bool isMeshFile(const std::string& path);
+bool isSplatFile(const std::string& path); // .ply/.splat: the Splats tab (.ply also opens as a mesh)
+bool isImageFile(const std::string& path);
+bool isBrushFile(const std::string& path);
+bool isProjectFile(const std::string& path);
+// Kind of a file for a tab (Recent and QuickSave mix kinds); Folder for files the tab doesn't show.
+AssetKind fileKindForTab(LibraryTab tab, const std::string& path);
+
+struct LibraryRoots {
+ std::string builtin; // bundled assets (contains demo/); may be empty
+ std::string user; // Documents/SculptForge (created on first use)
+};
+// The bundled assets folder: "assets" next to the executable or up to three levels above it.
+std::string findBuiltinAssets(const std::string& exeDir);
+// SDL's Documents folder + "SculptForge"; falls back to `prefDir` + "library".
+std::string defaultUserLibrary(const std::string& documentsDir, const std::string& prefDir);
+// Creates the root and Projects/ Tools/ Brushes/ Alphas/ Images/ Splats/ QuickSave/. False on failure.
+bool ensureUserLibrary(const std::string& root, std::string& error);
+
+// Directory listing: sub-folders (sorted by name), then the files `accept` keeps, sorted by name or
+// newest first. Hidden files (".x") are skipped. Never throws.
+std::vector<AssetEntry> listFolder(const std::string& dir, const std::function<AssetKind(const std::string&)>& accept,
+ bool newestFirst = false);
+// Seconds since the epoch of the last change of `path` (0 if missing).
+int64_t modifiedTime(const std::string& path);
+
+// Lists folders on a worker thread. get() never blocks: it returns the last finished listing (or
+// nullptr before the first one) and starts a scan when there is none or the folder changed. Call
+// poll() once per frame; it collects finished scans and re-checks each folder's time stamp every
+// `recheckSeconds` (a cheap stat, as ZBrush's LightBox refreshes while open).
+class FolderScanner {
+public:
+ using Accept = std::function<AssetKind(const std::string&)>;
+ ~FolderScanner();
+ const std::vector<AssetEntry>* get(const std::string& dir, const std::string& filterKey, Accept accept,
+ bool newestFirst = false);
+ void poll(double now, double recheckSeconds = 5.0);
+ void invalidate(); // re-scan everything on the next get()
+ bool busy() const;
+
+private:
+ struct Listing {
+ std::vector<AssetEntry> entries;
+ bool ready = false;
+ int64_t stamp = 0; // folder mtime the listing was made at
+ double checkedAt = 0; // last stat
+ Accept accept;
+ bool newestFirst = false;
+ std::string dir;
+ std::future<std::vector<AssetEntry>> pending;
+ };
+ std::map<std::string, Listing> listings_; // by dir + "|" + filterKey
+ double now_ = 0;
+};
+
+// --- Thumbnail cache keys (spec: fnv1a64(kind|absPath|size|mtime|version)) ---
+
+constexpr int kThumbnailVersion = 1; // bump when thumbnails are rendered differently
+uint64_t fnv1a64(std::string_view data, uint64_t seed = 0xcbf29ce484222325ull);
+std::string hex64(uint64_t v); // 16 lower-case hex digits
+// Key of a file's thumbnail: changes when the file is rewritten (size or time) or the renderer changes.
+std::string fileThumbnailKey(const std::string& kind, const std::string& absPath, uint64_t size, int64_t mtime,
+ int pixels, int version = kThumbnailVersion);
+// <cacheDir>/<key>.png
+std::string thumbnailCachePath(const std::string& cacheDir, const std::string& key);
+
+// --- Brush pop-up letters (ZBrush: B, then S, then T picks Standard) ---
+
+// Lower-case letters and digits only ("Clay Buildup" -> "claybuildup"): what a name is typed as.
+std::string typedName(const std::string& name);
+// Indices of `names` the typed letters keep: names starting with `typed`, or (when none does) names
+// containing it (`substring` says which). Empty `typed` keeps all.
+std::vector<size_t> filterByTyped(const std::vector<std::string>& names, const std::string& typed,
+ bool* substring = nullptr);
+// The key badge of each kept name: the first letter after `typed` in the name that no earlier name
+// took. Returns (letter, index into names) pairs; substring matches get none.
+std::vector<std::pair<char, size_t>> letterBadges(const std::vector<std::string>& names,
+ const std::vector<size_t>& kept, const std::string& typed);
+
+// --- QuickSave (title strip, file.quicksave): timestamped projects in <user library>/QuickSave ---
+
+constexpr size_t kQuickSaveKeep = 10;
+// "QuickSave 2026-10-21 23-15-04.sfproj" for a local time; `serial` > 0 appends " (n)".
+std::string quickSaveName(int64_t epochSeconds, int serial = 0);
+// A path in `folder` that doesn't exist yet.
+std::string nextQuickSavePath(const std::string& folder, int64_t epochSeconds);
+// Deletes the oldest QuickSave projects beyond `keep`; returns how many were removed.
+size_t pruneQuickSaves(const std::string& folder, size_t keep = kQuickSaveKeep);
+
+} // namespace sf
diff --git a/src/app/LightBox.cpp b/src/app/LightBox.cpp
new file mode 100644
index 00000000..50dd360a
--- /dev/null
+++ b/src/app/LightBox.cpp
@@ -0,0 +1,1061 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "app/LightBox.h"
+
+#include "app/App.h"
+#include "app/Pickers.h"
+#include "app/Ui.h"
+#include "core/Matcap.h"
+#include "core/Primitives.h"
+#include "core/Project.h"
+#include "render/GL.h"
+
+#include <IconsLucide.h>
+
+#include <imgui_internal.h>
+
+#include <algorithm>
+#include <cctype>
+#include <chrono>
+#include <cmath>
+#include <ctime>
+#include <filesystem>
+
+namespace sf {
+
+namespace {
+
+namespace fs = std::filesystem;
+
+constexpr float kTile = 96.0f; // thumbnail size (logical px)
+constexpr float kLabel = 22.0f; // label under it
+constexpr float kGap = 8.0f; // between tiles
+constexpr float kHeader = 28.0f; // tab row
+constexpr ImU32 kAccent = IM_COL32(240, 136, 46, 255);
+constexpr ImU32 kStripBg = IM_COL32(20, 20, 22, 250); // #141416 at 98%
+constexpr ImU32 kHeaderLine = IM_COL32(46, 46, 50, 255);
+
+fs::path fsPath(const std::string& p) { return fs::path(std::u8string(p.begin(), p.end())); }
+std::string utf8(const fs::path& p) {
+ const std::u8string s = p.u8string();
+ return std::string(s.begin(), s.end());
+}
+std::string lower(std::string s) {
+ for (auto& c : s)
+ c = char(std::tolower(static_cast<unsigned char>(c)));
+ return s;
+}
+bool isUnder(const std::string& path, const std::string& root) {
+ if (root.empty() || path.size() < root.size() || path.compare(0, root.size(), root) != 0) return false;
+ return path.size() == root.size() || path[root.size()] == '/' || path[root.size()] == '\\';
+}
+
+const char* glyphFor(AssetKind k) {
+ switch (k) {
+ case AssetKind::Folder:
+ return ICON_LC_FOLDER;
+ case AssetKind::Up:
+ return ICON_LC_FOLDER_UP;
+ case AssetKind::Project:
+ case AssetKind::Mesh:
+ case AssetKind::Primitive:
+ return ICON_LC_BOX;
+ case AssetKind::BrushType:
+ case AssetKind::Recipe:
+ case AssetKind::BrushFile:
+ return ICON_LC_BRUSH;
+ case AssetKind::Alpha:
+ case AssetKind::AlphaFile:
+ return ICON_LC_CIRCLE_DASHED;
+ case AssetKind::Material:
+ return ICON_LC_SUN;
+ case AssetKind::Image:
+ return ICON_LC_IMAGE;
+ case AssetKind::Splat:
+ return ICON_LC_SPARKLES;
+ }
+ return ICON_LC_BOX;
+}
+
+std::string sizeText(uint64_t bytes) {
+ char buf[32];
+ if (bytes >= 1024ull * 1024ull)
+ std::snprintf(buf, sizeof buf, "%.1f MB", double(bytes) / (1024.0 * 1024.0));
+ else
+ std::snprintf(buf, sizeof buf, "%.0f KB", std::max(1.0, double(bytes) / 1024.0));
+ return buf;
+}
+std::string dateText(int64_t t) {
+ const std::time_t tt = std::time_t(t);
+ std::tm tm{};
+#if defined(_WIN32)
+ localtime_s(&tm, &tt);
+#else
+ localtime_r(&tt, &tm);
+#endif
+ char buf[32];
+ std::strftime(buf, sizeof buf, "%Y-%m-%d %H:%M", &tm);
+ return buf;
+}
+
+const BrushAlpha& builtinAlpha(int i) {
+ static const BrushAlpha alphas[] = {BrushAlpha::round(), BrushAlpha::square(), BrushAlpha::noise()};
+ return alphas[std::clamp(i, 0, 2)];
+}
+const char* const kAlphaNames[] = {"Round", "Square", "Noise"};
+
+void SDLCALL onFolderChosen(void* userdata, const char* const* files, int) {
+ if (files && files[0]) static_cast<LightBox*>(userdata)->folderChosen(files[0]);
+}
+
+} // namespace
+
+float LightBox::height(int rows, float scale) {
+ return (kHeader + float(std::clamp(rows, 1, 4)) * (kTile + kLabel + 4.0f) + 12.0f) * scale;
+}
+
+void LightBox::show(LibraryTab tab) {
+ open_ = true;
+ if (place_.tab != tab || !place_.folder.empty()) {
+ back_.push_back(place_);
+ forward_.clear();
+ place_ = {tab, ""};
+ scrollTo_ = 0.0f;
+ }
+}
+
+void LightBox::folderChosen(const std::string& path) {
+ std::lock_guard lock(folderMutex_);
+ chosenFolder_ = path;
+}
+
+void LightBox::navigate(App&, Place to) {
+ if (to == place_) return;
+ back_.push_back(place_);
+ if (back_.size() > 64) back_.erase(back_.begin());
+ forward_.clear();
+ place_ = std::move(to);
+ filter_[0] = 0;
+ selected_.clear();
+ scrollTo_ = 0.0f;
+}
+
+// ---------------------------------------------------------------------------
+// What a tab shows
+// ---------------------------------------------------------------------------
+
+void LightBox::rootEntries(App& app, std::vector<AssetEntry>& out) {
+ const LibraryTab tab = place_.tab;
+ const LibraryRoots& roots = app.library_;
+ auto folderTile = [&](const std::string& name, const std::string& path) {
+ AssetEntry e;
+ e.kind = AssetKind::Folder;
+ e.name = name;
+ e.path = path;
+ out.push_back(std::move(e));
+ };
+ auto scan = [&](const std::string& dir, bool newestFirst) -> std::vector<AssetEntry> {
+ if (dir.empty()) return {};
+ const auto* list = app.libraryScanner_.get(
+ dir, libraryTabId(tab), [tab](const std::string& p) { return fileKindForTab(tab, p); }, newestFirst);
+ std::vector<AssetEntry> files;
+ if (list)
+ for (const auto& e : *list)
+ if (e.kind != AssetKind::Folder) files.push_back(e);
+ return files;
+ };
+ const std::string userDir =
+ roots.user.empty() || !*libraryTabFolder(tab) ? std::string() : roots.user + "/" + libraryTabFolder(tab);
+ const std::string builtinDir = roots.builtin.empty() ? std::string() : roots.builtin + "/demo";
+ // The Built-in and User folders (ZBrush: Maxon and User), and folders the artist added.
+ const bool folders = tab == LibraryTab::Project || tab == LibraryTab::Tool || tab == LibraryTab::Alpha ||
+ tab == LibraryTab::Image || tab == LibraryTab::Splats || tab == LibraryTab::Brush;
+ if (folders) {
+ const bool builtinHasFiles = !builtinDir.empty() && (tab == LibraryTab::Tool || tab == LibraryTab::Image);
+ if (builtinHasFiles) folderTile("Built-in", builtinDir);
+ if (!userDir.empty()) folderTile("User", userDir);
+ for (const std::string& r : extraRoots_)
+ folderTile(utf8(fsPath(r).filename()), r);
+ }
+ switch (tab) {
+ case LibraryTab::Project: {
+ std::vector<AssetEntry> files = scan(userDir, true);
+ for (const std::string& p : app.recentFiles_)
+ if (isProjectFile(p) &&
+ std::none_of(files.begin(), files.end(), [&](const AssetEntry& e) { return e.path == p; })) {
+ AssetEntry e;
+ e.kind = AssetKind::Project;
+ e.name = utf8(fsPath(p).stem());
+ e.path = p;
+ files.push_back(std::move(e));
+ }
+ out.insert(out.end(), files.begin(), files.end());
+ break;
+ }
+ case LibraryTab::Tool: {
+ for (int i = 0; i < int(Primitive::Count); ++i) {
+ AssetEntry e;
+ e.kind = AssetKind::Primitive;
+ e.index = i;
+ e.name = primitiveName(Primitive(i));
+ out.push_back(std::move(e));
+ }
+ const auto files = scan(userDir, false);
+ out.insert(out.end(), files.begin(), files.end());
+ break;
+ }
+ case LibraryTab::Brush:
+ for (const BrushItem& b : PickerUi::brushItems(app, true)) {
+ AssetEntry e;
+ e.name = b.name;
+ e.path = b.path;
+ switch (b.kind) {
+ case BrushItem::Kind::Type:
+ e.kind = AssetKind::BrushType, e.index = b.index;
+ break;
+ case BrushItem::Kind::Paint:
+ e.kind = AssetKind::BrushType, e.index = kPaintBrush;
+ break;
+ case BrushItem::Kind::Recipe:
+ e.kind = AssetKind::Recipe, e.index = b.index;
+ break;
+ case BrushItem::Kind::File:
+ e.kind = AssetKind::BrushFile;
+ break;
+ }
+ out.push_back(std::move(e));
+ }
+ break;
+ case LibraryTab::Alpha: {
+ for (int i = 0; i < 3; ++i) {
+ AssetEntry e;
+ e.kind = AssetKind::Alpha;
+ e.index = i;
+ e.name = kAlphaNames[i];
+ out.push_back(std::move(e));
+ }
+ const auto files = scan(userDir, false);
+ out.insert(out.end(), files.begin(), files.end());
+ break;
+ }
+ case LibraryTab::Material:
+ for (int i = -1; i < matcapCount(); ++i) {
+ AssetEntry e;
+ e.kind = AssetKind::Material;
+ e.index = i;
+ e.name = i < 0 ? "Studio" : matcapName(i);
+ out.push_back(std::move(e));
+ }
+ break;
+ case LibraryTab::Image:
+ case LibraryTab::Splats: {
+ const auto files = scan(userDir, false);
+ out.insert(out.end(), files.begin(), files.end());
+ break;
+ }
+ case LibraryTab::QuickSave: {
+ // Autosave first (it is the newest by nature), then QuickSaves newest first.
+ if (!app.prefDir_.empty()) {
+ const std::string autosave = app.prefDir_ + "autosave.sfproj";
+ std::error_code ec;
+ if (fs::is_regular_file(fsPath(autosave), ec)) {
+ AssetEntry e;
+ e.kind = AssetKind::Project;
+ e.name = "Autosave";
+ e.path = autosave;
+ e.mtime = modifiedTime(autosave);
+ out.push_back(std::move(e));
+ }
+ }
+ // "QuickSave 2026-10-21 23-15-04" reads better as its time: "Oct 21 23:15:04".
+ for (AssetEntry e : scan(userDir, true)) {
+ if (e.name.rfind("QuickSave ", 0) == 0 && e.mtime) {
+ const std::time_t t = std::time_t(e.mtime);
+ std::tm tm{};
+#if defined(_WIN32)
+ localtime_s(&tm, &t);
+#else
+ localtime_r(&t, &tm);
+#endif
+ char buf[32];
+ std::strftime(buf, sizeof buf, "%b %d %H:%M:%S", &tm);
+ e.name = buf;
+ }
+ out.push_back(std::move(e));
+ }
+ break;
+ }
+ case LibraryTab::Recent:
+ for (const std::string& p : app.recentFiles_) {
+ AssetEntry e;
+ e.kind = fileKindForTab(LibraryTab::Recent, p);
+ if (e.kind == AssetKind::Folder) continue;
+ e.name = utf8(fsPath(p).filename());
+ e.path = p;
+ out.push_back(std::move(e));
+ }
+ break;
+ default:
+ break;
+ }
+}
+
+std::vector<AssetEntry> LightBox::entries(App& app) {
+ std::vector<AssetEntry> out;
+ if (place_.folder.empty()) {
+ rootEntries(app, out);
+ } else {
+ AssetEntry up;
+ up.kind = AssetKind::Up;
+ up.name = "..";
+ out.push_back(up);
+ const LibraryTab tab = place_.tab;
+ if (const auto* list = app.libraryScanner_.get(
+ place_.folder, libraryTabId(tab), [tab](const std::string& p) { return fileKindForTab(tab, p); },
+ tab == LibraryTab::QuickSave || tab == LibraryTab::Project))
+ out.insert(out.end(), list->begin(), list->end());
+ }
+ if (filter_[0]) {
+ const std::string f = lower(filter_);
+ out.erase(std::remove_if(out.begin(), out.end(),
+ [&](const AssetEntry& e) {
+ return e.kind != AssetKind::Up && lower(e.name).find(f) == std::string::npos;
+ }),
+ out.end());
+ }
+ return out;
+}
+
+namespace {
+bool isActiveBrushType(const App& app, int index) {
+ BrushItem b;
+ b.kind = index == kPaintBrush ? BrushItem::Kind::Paint : BrushItem::Kind::Type;
+ b.index = index;
+ return PickerUi::isActive(app, b);
+}
+} // namespace
+
+ImTextureID LightBox::thumbnail(App& app, const AssetEntry& e) {
+ ThumbnailCache& t = app.thumbs_;
+ switch (e.kind) {
+ case AssetKind::Project:
+ case AssetKind::Mesh:
+ case AssetKind::Image:
+ case AssetKind::AlphaFile:
+ return t.file(e.path);
+ case AssetKind::Primitive:
+ return t.primitive(e.index);
+ case AssetKind::BrushType:
+ return t.brush(e.index);
+ case AssetKind::Recipe:
+ return e.index >= 0 && e.index < int(app.doc_.brushes.size()) ? t.recipe(app.doc_.brushes[size_t(e.index)])
+ : ImTextureID(0);
+ case AssetKind::Alpha:
+ return t.alpha(builtinAlpha(e.index));
+ case AssetKind::Material:
+ return t.material(e.index);
+ default:
+ return ImTextureID(0);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Actions
+// ---------------------------------------------------------------------------
+
+void LightBox::activate(App& app, const AssetEntry& e, bool append) {
+ switch (e.kind) {
+ case AssetKind::Up: {
+ const std::string parent = utf8(fsPath(place_.folder).parent_path());
+ // Leaving the folder a tab started in goes back to the tab's root.
+ const LibraryRoots& r = app.library_;
+ const std::string tabUser = r.user.empty() ? std::string() : r.user + "/" + libraryTabFolder(place_.tab);
+ const bool atTop = place_.folder == tabUser || place_.folder == r.builtin + "/demo" ||
+ std::find(extraRoots_.begin(), extraRoots_.end(), place_.folder) != extraRoots_.end();
+ navigate(app, {place_.tab, atTop ? std::string() : parent});
+ return;
+ }
+ case AssetKind::Folder:
+ navigate(app, {place_.tab, e.path});
+ return;
+ case AssetKind::Primitive: {
+ if (append) {
+ app.runCommand("subtool_append", {{"type", lower(primitiveName(Primitive(e.index)))}});
+ return;
+ }
+ const Primitive p = Primitive(e.index);
+ app.confirmDiscard([&app, p] {
+ if (p == Primitive::Sphere)
+ app.runCommand("new_sphere");
+ else if (p == Primitive::Plane)
+ app.runCommand("new_plane");
+ else {
+ app.runCommand("new_cube");
+ if (app.lastCommandOk_) app.camera_.frame(app.sceneBounds());
+ }
+ });
+ return;
+ }
+ case AssetKind::Project:
+ case AssetKind::Mesh:
+ if (append)
+ app.runCommand("subtool_append", {{"path", e.path}});
+ else
+ app.openPathConfirmed(e.path);
+ return;
+ case AssetKind::BrushType: {
+ BrushItem b;
+ b.kind = e.index == kPaintBrush ? BrushItem::Kind::Paint : BrushItem::Kind::Type;
+ b.index = e.index;
+ b.name = e.name;
+ PickerUi::select(app, b);
+ return;
+ }
+ case AssetKind::Recipe: {
+ BrushItem b;
+ b.kind = BrushItem::Kind::Recipe;
+ b.index = e.index;
+ b.name = e.name;
+ PickerUi::select(app, b);
+ return;
+ }
+ case AssetKind::BrushFile:
+ app.runCommand("brush_load", {{"path", e.path}});
+ return;
+ case AssetKind::Alpha:
+ app.runCommand("brush_set_alpha", {{"name", lower(kAlphaNames[std::clamp(e.index, 0, 2)])}});
+ return;
+ case AssetKind::AlphaFile:
+ app.runCommand("brush_set_alpha", {{"path", e.path}, {"invert", app.alphaInvert_}});
+ return;
+ case AssetKind::Material:
+ app.runCommand("set_material", {{"name", std::string(e.index < 0 ? "studio" : matcapName(e.index))}});
+ return;
+ case AssetKind::Image:
+ imageMenu_ = e.path;
+ return; // what to do with it: a small menu
+ case AssetKind::Splat:
+ app.runCommand("open", {{"path", e.path}});
+ return;
+ }
+}
+
+void LightBox::contextMenu(App& app, const AssetEntry& e) {
+ ImGui::TextDisabled("%s", e.name.c_str());
+ ImGui::Separator();
+ const bool mesh = e.kind == AssetKind::Mesh || e.kind == AssetKind::Project || e.kind == AssetKind::Primitive;
+ if (ImGui::MenuItem(e.kind == AssetKind::Folder || e.kind == AssetKind::Up ? "Open folder" : "Open"))
+ activate(app, e, false);
+ if (mesh && ImGui::MenuItem("Append as SubTool", "Shift+double-click")) activate(app, e, true);
+ if (e.kind == AssetKind::Image) {
+ if (ImGui::MenuItem("Generate 3D...")) app.openPath(e.path);
+ if (ImGui::MenuItem("Relief from image"))
+ app.confirmDiscard([&app, p = e.path] { app.runCommand("image_relief", {{"path", p}}); });
+ if (ImGui::MenuItem("Inflate image"))
+ app.confirmDiscard([&app, p = e.path] { app.runCommand("image_inflate", {{"path", p}}); });
+ if (ImGui::MenuItem("Project onto model")) app.runCommand("image_project", {{"path", e.path}});
+ if (ImGui::MenuItem("Use as alpha"))
+ app.runCommand("brush_set_alpha", {{"path", e.path}, {"invert", app.alphaInvert_}});
+ }
+ if (!e.path.empty() && e.kind != AssetKind::Up) {
+ ImGui::Separator();
+ if (ImGui::MenuItem("Show in file manager")) {
+ const std::string dir = e.kind == AssetKind::Folder ? e.path : utf8(fsPath(e.path).parent_path());
+ if (!SDL_OpenURL(("file://" + dir).c_str())) app.status_ = "Couldn't open " + dir + ": " + SDL_GetError();
+ }
+ if (e.kind != AssetKind::Folder && ImGui::MenuItem("Refresh thumbnail")) app.thumbs_.refresh(e.path);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Drawing
+// ---------------------------------------------------------------------------
+
+std::string LightBox::folderLabel(const App& app, const std::string& folder) const {
+ const LibraryRoots& r = app.library_;
+ if (!r.builtin.empty() && isUnder(folder, r.builtin)) return "Built-in";
+ if (!r.user.empty() && isUnder(folder, r.user)) return "User";
+ return utf8(fsPath(folder).filename());
+}
+
+void LightBox::drawBreadcrumb(App& app) {
+ // Tab > Built-in/User > sub > sub: each crumb goes back there.
+ std::vector<std::pair<std::string, Place>> crumbs;
+ crumbs.push_back({libraryTabName(place_.tab), {place_.tab, ""}});
+ if (!place_.folder.empty()) {
+ const LibraryRoots& r = app.library_;
+ std::string top;
+ const std::string tabUser = r.user.empty() ? std::string() : r.user + "/" + libraryTabFolder(place_.tab);
+ if (!tabUser.empty() && isUnder(place_.folder, tabUser))
+ top = tabUser;
+ else if (!r.builtin.empty() && isUnder(place_.folder, r.builtin + "/demo"))
+ top = r.builtin + "/demo";
+ else
+ for (const auto& x : extraRoots_)
+ if (isUnder(place_.folder, x)) top = x;
+ if (top.empty()) top = place_.folder;
+ crumbs.push_back({folderLabel(app, top), {place_.tab, top}});
+ const fs::path rel = fsPath(place_.folder).lexically_relative(fsPath(top));
+ fs::path acc = fsPath(top);
+ for (const auto& part : rel) {
+ if (part == ".") continue;
+ acc /= part;
+ crumbs.push_back({utf8(part), {place_.tab, utf8(acc)}});
+ }
+ }
+ for (size_t i = 0; i < crumbs.size(); ++i) {
+ if (i) {
+ ImGui::SameLine(0, 2);
+ ImGui::TextDisabled(ICON_LC_CHEVRON_RIGHT);
+ ImGui::SameLine(0, 2);
+ }
+ const bool last = i + 1 == crumbs.size();
+ ImGui::PushID(int(i));
+ ImGui::PushStyleColor(ImGuiCol_Button, IM_COL32(0, 0, 0, 0));
+ ImGui::PushStyleColor(ImGuiCol_Text, last ? ImGui::GetStyleColorVec4(ImGuiCol_Text)
+ : ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
+ if (ImGui::SmallButton(crumbs[i].first.c_str()) && !last) navigate(app, crumbs[i].second);
+ ImGui::PopStyleColor(2);
+ ImGui::PopID();
+ }
+}
+
+void LightBox::drawHeader(App& app, float width) {
+ const float scale = app.uiScale_;
+ ImGuiStyle& style = ImGui::GetStyle();
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ const ImVec2 origin = ImGui::GetCursorScreenPos();
+
+ // Title (an item, so tests and help find "LightBox").
+ {
+ const char* title = ICON_LC_IMAGES " LightBox";
+ const ImVec2 ts = ImGui::CalcTextSize(title);
+ const ImVec2 p = ImGui::GetCursorScreenPos();
+ ImGui::InvisibleButton("LightBox", ImVec2(ts.x, ImGui::GetFrameHeight()));
+ dl->AddText(ImVec2(p.x, p.y + (ImGui::GetFrameHeight() - ts.y) * 0.5f), ImGui::GetColorU32(ImGuiCol_Text),
+ title);
+ ui::HelpText("LightBox", ",",
+ "Browse projects, models, brushes, alphas, materials, images and splats. Double-click to load; "
+ "Shift+double-click a model to append it as a SubTool; drag sideways to scrub.",
+ "LightBox");
+ }
+ ImGui::SameLine(0, 14 * scale);
+
+ // Tabs: text buttons, the active one underlined in accent.
+ for (int i = 0; i < int(LibraryTab::Count); ++i) {
+ const auto tab = LibraryTab(i);
+ const bool on = place_.tab == tab;
+ ImGui::PushStyleColor(ImGuiCol_Button, IM_COL32(0, 0, 0, 0));
+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, IM_COL32(255, 255, 255, 18));
+ ImGui::PushStyleColor(ImGuiCol_ButtonActive, IM_COL32(255, 255, 255, 30));
+ ImGui::PushStyleColor(ImGuiCol_Text,
+ on ? IM_COL32(255, 255, 255, 255) : ImGui::GetColorU32(ImGuiCol_TextDisabled));
+ if (ImGui::Button(libraryTabName(tab)) && !on) navigate(app, {tab, ""});
+ ImGui::PopStyleColor(4);
+ if (on) {
+ const ImVec2 a = ImGui::GetItemRectMin(), b = ImGui::GetItemRectMax();
+ dl->AddRectFilled(ImVec2(a.x + 4, b.y - 2), ImVec2(b.x - 4, b.y), kAccent, 1.0f);
+ }
+ static const char* const tips[] = {
+ "Your projects (.sfproj) and recently opened projects.",
+ "Models to start from or append as SubTools: primitives and model files.",
+ "Every brush: built-in, custom and .sfbrush files in your library.",
+ "Brush alphas: built-in stamps and images in your Alphas folder.",
+ "Viewport materials: Studio and the MatCaps.",
+ "Reference images: generate 3D, relief, inflate, project onto the model or use as an alpha.",
+ "Gaussian splat captures (.ply, .splat) to sculpt against.",
+ "QuickSaves and the autosave, newest first.",
+ "Recently opened files of every kind.",
+ };
+ ui::HelpText(libraryTabName(tab), nullptr, tips[i], "LightBox");
+ ImGui::SameLine(0, 0);
+ }
+ ImGui::SameLine(0, 10 * scale);
+
+ // History.
+ ImGui::PushStyleColor(ImGuiCol_Button, IM_COL32(0, 0, 0, 0));
+ ImGui::BeginDisabled(back_.empty());
+ if (ImGui::Button(ICON_LC_CHEVRON_LEFT "###Back")) {
+ forward_.push_back(place_);
+ place_ = back_.back();
+ back_.pop_back();
+ scrollTo_ = 0.0f;
+ }
+ ImGui::EndDisabled();
+ ui::HelpText("Back", nullptr, "The previous tab or folder.", "LightBox");
+ ImGui::SameLine(0, 2);
+ ImGui::BeginDisabled(forward_.empty());
+ if (ImGui::Button(ICON_LC_CHEVRON_RIGHT "###Forward")) {
+ back_.push_back(place_);
+ place_ = forward_.back();
+ forward_.pop_back();
+ scrollTo_ = 0.0f;
+ }
+ ImGui::EndDisabled();
+ ui::HelpText("Forward", nullptr, "Forward again after going back.", "LightBox");
+ ImGui::PopStyleColor();
+ if (!place_.folder.empty()) {
+ ImGui::SameLine(0, 8 * scale);
+ drawBreadcrumb(app);
+ }
+
+ // Right side: [Save now] on the QuickSave tab, filter, rows, open folder, close. Narrow canvases
+ // get icon-only buttons and a shorter filter first.
+ const bool quickTab = place_.tab == LibraryTab::QuickSave;
+ const float rowsW = 4 * (ImGui::GetFrameHeight() + 2.0f);
+ const float closeW = ImGui::GetFrameHeight();
+ const float right = origin.x + width;
+ ImGui::SameLine();
+ const float leftEnd = ImGui::GetCursorScreenPos().x;
+ auto buttonW = [&](const char* text) {
+ return ImGui::CalcTextSize(text, nullptr, true).x + style.FramePadding.x * 2;
+ };
+ float filterW = 160.0f * scale;
+ bool compact = false;
+ auto groupW = [&] {
+ const float saveW =
+ quickTab ? buttonW(compact ? ICON_LC_SAVE : ICON_LC_SAVE " Save now") + 8.0f * scale : 0.0f;
+ const float folderW = buttonW(compact ? ICON_LC_FOLDER_PLUS : ICON_LC_FOLDER_PLUS " Open folder...");
+ return saveW + filterW + rowsW + folderW + closeW + 3 * 8.0f * scale;
+ };
+ if (right - leftEnd - 8.0f < groupW()) compact = true;
+ if (right - leftEnd - 8.0f < groupW())
+ filterW = std::max(70.0f * scale, filterW - (groupW() - (right - leftEnd - 8.0f)));
+ ImGui::SetCursorScreenPos(ImVec2(std::max(leftEnd + 8.0f, right - groupW()), origin.y));
+ if (quickTab) {
+ if (ImGui::Button(compact ? ICON_LC_SAVE "###QuickSave now" : ICON_LC_SAVE " Save now###QuickSave now"))
+ app.quickSave();
+ ui::HelpAction(app, "file.quicksave");
+ ImGui::SameLine(0, 8 * scale);
+ }
+ ImGui::SetNextItemWidth(filterW);
+ ImGui::InputTextWithHint("##lbfilter", ICON_LC_SEARCH " Filter", filter_, sizeof filter_);
+ ui::HelpText("Filter", nullptr, "Show only the items whose names contain this text.", "LightBox");
+ ImGui::SameLine(0, 8 * scale);
+ for (int r = 1; r <= 4; ++r) {
+ const bool on = app.layout_.lightboxRows == r;
+ char label[16];
+ std::snprintf(label, sizeof label, "%d##lbrows", r);
+ if (on) ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(kAccent));
+ if (ImGui::Button(label, ImVec2(ImGui::GetFrameHeight(), 0))) app.layout_.lightboxRows = r;
+ if (on) ImGui::PopStyleColor();
+ ui::HelpText("Rows", nullptr, "How many rows of thumbnails the LightBox shows (1-4).", "LightBox");
+ ImGui::SameLine(0, 2);
+ }
+ ImGui::SameLine(0, 8 * scale);
+ if (ImGui::Button(compact ? ICON_LC_FOLDER_PLUS "###Open folder"
+ : ICON_LC_FOLDER_PLUS " Open folder...###Open folder"))
+ SDL_ShowOpenFolderDialog(onFolderChosen, this, app.window_, nullptr, false);
+ ui::HelpText("Open folder", nullptr, "Add a folder of your own to the LightBox (shown at the root of every tab).",
+ "LightBox");
+ ImGui::SameLine(0, 8 * scale);
+ if (ImGui::Button(ICON_LC_X "##lbclose", ImVec2(closeW, 0))) open_ = false;
+ ui::HelpText("Close LightBox", ",", "Hide the LightBox (comma toggles it).", "LightBox");
+
+ const float y = origin.y + kHeader * scale - 2.0f;
+ dl->AddLine(ImVec2(origin.x - 8, y), ImVec2(right + 8, y), kHeaderLine, 1.0f);
+ ImGui::SetCursorScreenPos(ImVec2(origin.x, origin.y + kHeader * scale + 2.0f));
+}
+
+void LightBox::draw(App& app, const CanvasRect& canvas) {
+ {
+ std::lock_guard lock(folderMutex_);
+ if (!chosenFolder_.empty()) {
+ if (std::find(extraRoots_.begin(), extraRoots_.end(), chosenFolder_) == extraRoots_.end())
+ extraRoots_.push_back(chosenFolder_);
+ app.status_ = "Added " + chosenFolder_ + " to the LightBox";
+ Place to{place_.tab, chosenFolder_};
+ chosenFolder_.clear();
+ open_ = true;
+ navigate(app, to);
+ }
+ }
+ // The layout holds what Store Config saves (open, rows, tab, placement).
+ UiLayout& layout = app.layout_;
+ if (!syncedLayout_) {
+ syncedLayout_ = true;
+ place_.tab = libraryTabFromId(layout.lightboxTab);
+ open_ = open_ || layout.lightboxOpen;
+ }
+ layout.lightboxOpen = open_;
+ layout.lightboxTab = libraryTabId(place_.tab);
+ layout.lightboxRows = std::clamp(layout.lightboxRows, 1, 4);
+ app.libraryScanner_.poll(ImGui::GetTime());
+ if (!open_) {
+ pressing_ = tileDrag_ = false;
+ return;
+ }
+
+ const float scale = app.uiScale_;
+ const int rows = layout.lightboxRows;
+ const float h = std::min(height(rows, scale), canvas.h);
+ const float y = layout.lightboxBottom ? canvas.y + canvas.h - h : canvas.y;
+ ImGui::SetNextWindowPos(ImVec2(canvas.x, y));
+ ImGui::SetNextWindowSize(ImVec2(canvas.w, h));
+ ImGui::PushStyleColor(ImGuiCol_WindowBg, kStripBg);
+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8 * scale, 0));
+ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
+ ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
+ const bool visible =
+ ImGui::Begin("LightBox", nullptr,
+ ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
+ ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoScrollWithMouse);
+ ImGui::PopStyleVar(3);
+ ImGui::PopStyleColor();
+ if (!visible) {
+ ImGui::End();
+ return;
+ }
+ ImDrawList* wdl = ImGui::GetWindowDrawList();
+ const ImVec2 wp = ImGui::GetWindowPos(), ws = ImGui::GetWindowSize();
+ // 1 px edge toward the canvas.
+ const float edge = layout.lightboxBottom ? wp.y : wp.y + ws.y - 1.0f;
+ wdl->AddLine(ImVec2(wp.x, edge), ImVec2(wp.x + ws.x, edge), IM_COL32(14, 14, 16, 255));
+
+ ImGui::SetCursorPosY(std::round((kHeader * scale - ImGui::GetFrameHeight()) * 0.5f));
+ drawHeader(app, ws.x - 16.0f * scale);
+
+ const std::vector<AssetEntry> items = entries(app);
+ const float tile = kTile * scale, rowH = (kTile + kLabel + 4.0f) * scale, gap = kGap * scale;
+ const int columns = int((items.size() + size_t(rows) - 1) / size_t(rows));
+ const float contentW = float(columns) * (tile + gap);
+
+ ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarSize, 6.0f * scale);
+ ImGui::SetNextWindowContentSize(ImVec2(contentW, float(rows) * rowH));
+ ImGui::BeginChild("##lbstrip", ImVec2(0, float(rows) * rowH + 8.0f * scale), ImGuiChildFlags_None,
+ ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NoScrollWithMouse |
+ ImGuiWindowFlags_NoBackground);
+ ImGui::PopStyleVar();
+ if (scrollTo_ >= 0.0f) {
+ ImGui::SetScrollX(scrollTo_);
+ scrollTo_ = -1.0f;
+ }
+ const ImGuiIO& io = ImGui::GetIO();
+ const bool stripHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem);
+ // The wheel scrolls sideways, a tile column per notch.
+ if (stripHovered && (io.MouseWheel != 0.0f || io.MouseWheelH != 0.0f))
+ ImGui::SetScrollX(ImGui::GetScrollX() - (io.MouseWheel + io.MouseWheelH) * (tile + gap));
+ // Left-drag scrubs the strip (after 4 px, so a click stays a click).
+ if (stripHovered && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) {
+ pressing_ = true;
+ scrubbed_ = tileDrag_ = false;
+ pressX_ = io.MousePos.x;
+ pressY_ = io.MousePos.y;
+ pressScroll_ = ImGui::GetScrollX();
+ pressTile_ = -1;
+ }
+ if (pressing_ && ImGui::IsMouseDown(ImGuiMouseButton_Left) && !tileDrag_) {
+ if (std::abs(io.MousePos.x - pressX_) > 4.0f) scrubbed_ = true;
+ if (scrubbed_) ImGui::SetScrollX(pressScroll_ - (io.MousePos.x - pressX_));
+ // Pulled out of the LightBox onto the canvas: drop it there to load it.
+ const float outside = layout.lightboxBottom ? wp.y - io.MousePos.y : io.MousePos.y - (wp.y + ws.y);
+ if (pressTile_ >= 0 && outside > 12.0f) {
+ tileDrag_ = true;
+ dragEntry_ = items[size_t(pressTile_)];
+ ImGui::SetScrollX(pressScroll_);
+ }
+ }
+
+ const float scrollX = ImGui::GetScrollX();
+ const float viewW = ImGui::GetWindowWidth();
+ const ImVec2 base = ImGui::GetCursorScreenPos();
+ for (size_t i = 0; i < items.size(); ++i) {
+ const AssetEntry& e = items[i];
+ const int col = int(i) / rows, row = int(i) % rows;
+ const float x = float(col) * (tile + gap);
+ if (x + tile < scrollX - tile || x > scrollX + viewW + tile) continue; // off screen: no thumbnail work
+ ImGui::SetCursorScreenPos(ImVec2(base.x + x, base.y + float(row) * rowH + 4.0f * scale));
+ const ImTextureID tex = thumbnail(app, e);
+ const std::string key = e.path.empty() ? e.name : e.path;
+ const bool selected = key == selected_ ||
+ (e.kind == AssetKind::Material && app.renderSettings_.matcap == e.index) ||
+ (e.kind == AssetKind::BrushType && isActiveBrushType(app, e.index)) ||
+ (e.kind == AssetKind::Recipe && !app.paintMode_ && app.doc_.activeBrush == e.index);
+ const std::string id = e.name + "##lb" + std::to_string(i);
+ const bool clicked = AssetTile(id.c_str(), tex, glyphFor(e.kind), e.name, tile, selected);
+ if (ImGui::IsItemActivated()) pressTile_ = int(i);
+ if (clicked && !scrubbed_) selected_ = key;
+ const bool doubleClicked = ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left);
+ if (doubleClicked && !scrubbed_) {
+ selected_ = key;
+ activate(app, e, (SDL_GetModState() & SDL_KMOD_SHIFT) != 0);
+ }
+ // Plain hover: the full name and path. Ctrl: the details.
+ if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal) && !io.KeyCtrl && !pressing_ &&
+ !ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId)) {
+ ImGui::BeginTooltip();
+ ImGui::TextUnformatted(e.name.c_str());
+ if (!e.path.empty()) ImGui::TextDisabled("%s", e.path.c_str());
+ ImGui::EndTooltip();
+ }
+ std::string details =
+ e.kind == AssetKind::Folder || e.kind == AssetKind::Up ? "Double-click to open the folder."
+ : e.kind == AssetKind::Mesh || e.kind == AssetKind::Primitive || e.kind == AssetKind::Project
+ ? "Double-click to open (replaces the scene); Shift+double-click appends it as a SubTool."
+ : e.kind == AssetKind::Image ? "Double-click for what to do with the image."
+ : "Double-click to use it.";
+ if (e.size) details += "\n" + sizeText(e.size) + ", modified " + dateText(e.mtime);
+ ui::HelpText(e.name.c_str(), nullptr, details.c_str(), e.path.empty() ? "LightBox" : e.path.c_str());
+ if (ImGui::BeginPopupContextItem()) {
+ contextMenu(app, e);
+ ImGui::EndPopup();
+ }
+ }
+ // Only folders (or nothing): say how things get here.
+ const bool onlyFolders = std::all_of(items.begin(), items.end(), [](const AssetEntry& e) {
+ return e.kind == AssetKind::Folder || e.kind == AssetKind::Up;
+ });
+ if (onlyFolders) {
+ const char* hint = filter_[0] ? nullptr
+ : place_.tab == LibraryTab::Project
+ ? "Nothing here yet. Projects you save (Ctrl+S) into the User folder show up here."
+ : place_.tab == LibraryTab::QuickSave
+ ? "Nothing here yet. QuickSave keeps timestamped copies of your scene here."
+ : place_.tab == LibraryTab::Recent ? "Nothing here yet. Files you open show up here."
+ : place_.tab == LibraryTab::Image
+ ? "Nothing here yet. Put reference images in the User folder."
+ : place_.tab == LibraryTab::Splats
+ ? "Nothing here yet. Put Gaussian splat captures (.ply, .splat) in the User folder."
+ : "Nothing here yet.";
+ const float x =
+ base.x +
+ (items.empty() ? 8.0f : float((items.size() + size_t(rows) - 1) / size_t(rows)) * (tile + gap) + 12.0f);
+ ImGui::SetCursorScreenPos(ImVec2(x, base.y + 4.0f * scale + tile * 0.5f - ImGui::GetTextLineHeight() * 0.5f));
+ if (hint)
+ ImGui::TextDisabled("%s", hint);
+ else
+ ImGui::TextDisabled("Nothing here matches \"%s\".", filter_);
+ }
+ AssetTileHoverGlow();
+ ImGui::EndChild();
+
+ // Image tiles: what to do with the picture.
+ if (!imageMenu_.empty()) {
+ ImGui::OpenPopup("##lbimage");
+ if (ImGui::BeginPopup("##lbimage")) {
+ AssetEntry e;
+ e.kind = AssetKind::Image;
+ e.path = imageMenu_;
+ e.name = utf8(fsPath(imageMenu_).filename());
+ ImGui::TextDisabled("%s", e.name.c_str());
+ ImGui::Separator();
+ bool done = false;
+ if (ImGui::MenuItem(ICON_LC_SPARKLES " Generate 3D...")) app.openPath(e.path), done = true;
+ if (ImGui::MenuItem("Relief from image")) {
+ app.confirmDiscard([&app, p = e.path] { app.runCommand("image_relief", {{"path", p}}); });
+ done = true;
+ }
+ if (ImGui::MenuItem("Inflate image")) {
+ app.confirmDiscard([&app, p = e.path] { app.runCommand("image_inflate", {{"path", p}}); });
+ done = true;
+ }
+ if (ImGui::MenuItem("Project onto model")) app.runCommand("image_project", {{"path", e.path}}), done = true;
+ if (ImGui::MenuItem("Use as alpha"))
+ app.runCommand("brush_set_alpha", {{"path", e.path}, {"invert", app.alphaInvert_}}), done = true;
+ if (done) imageMenu_.clear();
+ ImGui::EndPopup();
+ } else {
+ imageMenu_.clear();
+ }
+ }
+ ImGui::End();
+
+ // A tile dragged out of the strip follows the cursor; releasing it over the canvas loads it.
+ if (tileDrag_) {
+ const ImTextureID tex = thumbnail(app, dragEntry_);
+ const float s = 64.0f * scale;
+ ImDrawList* fg = ImGui::GetForegroundDrawList();
+ const ImVec2 a(io.MousePos.x - s * 0.5f, io.MousePos.y - s * 0.5f), b(a.x + s, a.y + s);
+ fg->AddRectFilled(a, b, IM_COL32(42, 42, 46, 220), 4.0f);
+ if (tex) fg->AddImageRounded(tex, a, b, ImVec2(0, 0), ImVec2(1, 1), IM_COL32(255, 255, 255, 220), 4.0f);
+ fg->AddRect(a, b, kAccent, 4.0f, 0, 1.5f);
+ }
+ if (pressing_ && !ImGui::IsMouseDown(ImGuiMouseButton_Left)) {
+ if (tileDrag_ && canvas.contains(io.MousePos.x, io.MousePos.y) && !ImGui::GetCurrentContext()->HoveredWindow)
+ activate(app, dragEntry_, (SDL_GetModState() & SDL_KMOD_SHIFT) != 0);
+ pressing_ = tileDrag_ = false;
+ }
+}
+
+void LightBox::drawPreferences(App& app) {
+ UiLayout& layout = app.layout_;
+ ImGui::Checkbox("Show at startup##lightbox", &showAtStartup);
+ ui::HelpText("Show at startup", nullptr,
+ "Open the LightBox on the Project tab when SculptForge starts (as ZBrush does).",
+ "Preferences > LightBox");
+ ImGui::SetNextItemWidth(-1);
+ ImGui::SliderInt("##lbrowspref", &layout.lightboxRows, 1, 4, "Rows %d");
+ ui::HelpText("Rows", nullptr, "Rows of thumbnails in the LightBox strip.", "Preferences > LightBox");
+ int placement = layout.lightboxBottom ? 1 : 0;
+ ImGui::TextUnformatted("Placement");
+ ImGui::SameLine();
+ if (ImGui::RadioButton("Top##lbplace", placement == 0)) layout.lightboxBottom = false;
+ ImGui::SameLine();
+ if (ImGui::RadioButton("Bottom##lbplace", placement == 1)) layout.lightboxBottom = true;
+ ui::HelpText("Placement", nullptr, "Show the LightBox along the top or the bottom of the canvas.",
+ "Preferences > LightBox");
+ ImGui::TextDisabled("Library folder");
+ ImGui::TextWrapped("%s", app.library_.user.empty() ? "(none)" : app.library_.user.c_str());
+ if (!app.library_.user.empty() && ImGui::Button(ICON_LC_FOLDER_OPEN " Show library folder"))
+ SDL_OpenURL(("file://" + app.library_.user).c_str());
+}
+
+// ---------------------------------------------------------------------------
+// App glue: library folders, actions, QuickSave, project thumbnails
+// ---------------------------------------------------------------------------
+
+void App::initLightBox() {
+ if (const char* base = SDL_GetBasePath()) library_.builtin = findBuiltinAssets(base);
+ const bool recording = !options_.recordPath.empty() || !options_.renderPath.empty();
+ if (!options_.uiTest.empty()) {
+ // UI tests get an empty library of their own (like their brush library), never the artist's.
+ const fs::path base =
+ options_.uiOutDir.empty() ? fs::temp_directory_path() / "sculptforge-ui-test" : fsPath(options_.uiOutDir);
+ library_.user = utf8(base / "library");
+ std::error_code ec;
+ fs::remove_all(fsPath(library_.user), ec);
+ } else if (!recording) {
+ const char* docs = SDL_GetUserFolder(SDL_FOLDER_DOCUMENTS);
+ library_.user = defaultUserLibrary(docs ? docs : "", prefDir_);
+ }
+ if (!library_.user.empty()) {
+ std::string err;
+ if (!ensureUserLibrary(library_.user, err)) {
+ SDL_Log("LightBox library: %s", err.c_str());
+ library_.user.clear();
+ }
+ }
+ // Thumbnails are cached on disk for the artist; tests and recordings render fresh ones.
+ if (interactive() && options_.uiTest.empty() && !prefDir_.empty()) thumbs_.setCacheDir(prefDir_ + "thumbs");
+ if (const char* dir = SDL_getenv("SCULPTFORGE_THUMBNAIL_CACHE")) thumbs_.setCacheDir(dir); // to look at them
+
+ // Cube is a LightBox primitive like Sphere and Plane (new_sphere / new_plane live in the core).
+ commands_.add({"new_cube",
+ "Replace the scene with a new cube ready for sculpting (one polygroup per side).",
+ {{"resolution", ParamSpec::Type::Number, "Cells along each edge (1-256). Default 48.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const int res = std::clamp(int(argNumber(a, "resolution", 48)), 1, 256);
+ doc.setMesh(makeCube(res), "Cube");
+ doc.path.clear();
+ return {true, "Created cube with " + std::to_string(doc.mesh.triangleCount()) + " triangles"};
+ }});
+
+ // Projects carry a 256 px picture of the current view, so the LightBox shows them without loading.
+ setProjectThumbnailProvider([this](const Document&, Image& out) {
+ if (!glContext_ || SDL_GL_GetCurrentContext() != glContext_) return false; // not the UI thread
+ constexpr GLenum kFramebufferBinding = 0x8CA6, kViewport = 0x0BA2;
+ GLint fbo = 0, viewport[4] = {};
+ gl::GetIntegerv(kFramebufferBinding, &fbo);
+ gl::GetIntegerv(kViewport, viewport);
+ Camera cam = camera_;
+ cam.aspect = 1.0f;
+ std::string err;
+ out.width = out.height = kProjectThumbnailSize;
+ const bool ok = renderer_.renderToImage(cam, out.width, out.height, renderSettings_, out.rgba, err);
+ gl::BindFramebuffer(GL_FRAMEBUFFER, GLuint(fbo));
+ gl::Viewport(viewport[0], viewport[1], viewport[2], viewport[3]);
+ return ok;
+ });
+
+ auto add = [this](const char* id, const char* label, const char* icon, const char* palette, const char* shortcut,
+ const char* description, std::function<void()> run, std::function<bool()> checked = nullptr) {
+ Action a;
+ a.id = id;
+ a.label = label;
+ a.icon = icon;
+ a.palette = palette;
+ a.shortcut = shortcut;
+ a.description = description;
+ a.run = std::move(run);
+ a.checked = std::move(checked);
+ actions_.add(std::move(a));
+ };
+ add(
+ "ui.lightbox", "LightBox", ICON_LC_IMAGES, "LightBox", ",",
+ "Show or hide the LightBox: thumbnails of your projects, models, brushes, alphas, materials, images, splats "
+ "and "
+ "QuickSaves along the top of the canvas. Double-click to load.",
+ [this] { lightbox_.toggle(); }, [this] { return lightbox_.open(); });
+ add("ui.picker.brush", "Brush picker", ICON_LC_BRUSH, "Brush", "B",
+ "Pop up every brush under the cursor. Type the first letter of a brush, then the orange letter on its tile "
+ "(B S T = Standard).",
+ [] { openPicker(Picker::Brush, ImVec2(-1, -1)); });
+ add("ui.picker.stroke", "Stroke picker", ICON_LC_SPLINE, "Stroke", "",
+ "Pop up the stroke types: Dots, DragRect, Spray and LazyMouse.",
+ [] { openPicker(Picker::Stroke, ImVec2(-1, -1)); });
+ add("ui.picker.alpha", "Alpha picker", ICON_LC_CIRCLE_DASHED, "Alpha", "",
+ "Pop up the brush alphas: built-in stamps and images from your library.",
+ [] { openPicker(Picker::Alpha, ImVec2(-1, -1)); });
+ add("ui.picker.material", "Material picker", ICON_LC_SUN, "Material", "M",
+ "Pop up the materials under the cursor. Hover one to preview it on the model; click to keep it.",
+ [] { openPicker(Picker::Material, ImVec2(-1, -1)); });
+ add("ui.size_popup", "Draw Size at cursor", ICON_LC_CIRCLE, "Draw", "S",
+ "A Draw Size slider under the cursor: drag it, or type a number and press Enter.",
+ [this] { PickerUi::sizePopup(*this, false); });
+ add("ui.strength_popup", "Strength at cursor", ICON_LC_CIRCLE_DOT, "Draw", "I",
+ "A Strength slider under the cursor: drag it, or type a number and press Enter.",
+ [this] { PickerUi::sizePopup(*this, true); });
+ add("file.quicksave", "QuickSave", ICON_LC_SAVE, "File", "",
+ "Save a timestamped copy of the whole scene to the QuickSave folder of your library (the last 10 are kept). "
+ "Your project file is not changed. Find them in the LightBox QuickSave tab.",
+ [this] { quickSave(); });
+
+ // ZBrush opens the LightBox at startup on the Project tab (never in tests, renders or recordings).
+ if (lightbox_.showAtStartup && interactive() && options_.uiTest.empty() && options_.openPath.empty())
+ lightbox_.show(LibraryTab::Project);
+}
+
+CanvasRect App::lightBoxCanvas() const {
+ // Below the menu bar, the whole window wide (the shell replaces this with its canvasRect()).
+ const ImGuiViewport* vp = ImGui::GetMainViewport();
+ const float top = hideUi_ ? 0.0f : ImGui::GetFrameHeight();
+ return {vp->Pos.x, vp->Pos.y + top, vp->Size.x, vp->Size.y - top};
+}
+
+void App::drawLightBoxUi() {
+ thumbs_.pump(renderer_);
+ lightbox_.draw(*this, lightBoxCanvas());
+ drawPickers(*this);
+}
+
+bool App::lightBoxKey(SDL_Keycode key, SDL_Keymod mod) {
+ if (mod & (SDL_KMOD_CTRL | SDL_KMOD_ALT | SDL_KMOD_GUI | SDL_KMOD_SHIFT)) return false;
+ const char* id = key == SDLK_COMMA ? "ui.lightbox"
+ : key == SDLK_B ? "ui.picker.brush"
+ : key == SDLK_M ? "ui.picker.material"
+ : key == SDLK_S ? "ui.size_popup"
+ : key == SDLK_I ? "ui.strength_popup"
+ : nullptr;
+ const Action* a = id ? actions_.find(id) : nullptr;
+ if (!a || !a->run) return false;
+ actions_.touch(a->id);
+ a->run();
+ return true;
+}
+
+void App::quickSave() {
+ if (library_.user.empty()) {
+ status_ = "QuickSave needs a library folder (Preferences > LightBox)";
+ return;
+ }
+ const std::string folder = library_.user + "/QuickSave";
+ std::error_code ec;
+ fs::create_directories(fsPath(folder), ec);
+ const auto now = std::chrono::system_clock::now();
+ const std::string path =
+ nextQuickSavePath(folder, std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count());
+ storeProjectSettings();
+ std::string err;
+ // A copy: the document keeps its own path and unsaved state, as with ZBrush's QuickSave.
+ if (!saveProject(path, doc_, err)) {
+ status_ = "QuickSave failed: " + err;
+ lastCommandOk_ = false;
+ return;
+ }
+ pruneQuickSaves(folder);
+ libraryScanner_.invalidate();
+ status_ = "QuickSaved " + utf8(fsPath(path).filename());
+ lastCommandOk_ = true;
+}
+
+} // namespace sf
diff --git a/src/app/LightBox.h b/src/app/LightBox.h
index 6526a88b..c383af72 100644
--- a/src/app/LightBox.h
+++ b/src/app/LightBox.h
@@ -3,10 +3,22 @@
//
// LightBox (comma key): a thumbnail strip over the canvas for projects, models,
// brushes, alphas, materials, images, splats, QuickSaves and recent files.
+//
+// As in ZBrush: category tabs along the top, back / forward through the tabs
+// and folders visited, a "Built-in" and a "User" folder at each tab's root,
+// double-click to enter a folder or load an item, drag to scrub the strip
+// sideways, 1-4 rows of thumbnails, top or bottom of the canvas.
#pragma once
+#include "app/AssetLibrary.h"
#include "app/UiLayout.h"
+#include <imgui.h>
+
+#include <mutex>
+#include <string>
+#include <vector>
+
namespace sf {
class App;
@@ -17,9 +29,52 @@ public:
bool open() const { return open_; }
void setOpen(bool open) { open_ = open; }
void toggle() { open_ = !open_; }
+ // Shows `tab` (its root) and opens the LightBox.
+ void show(LibraryTab tab);
+ // Preferences > LightBox (the shell's Preferences palette calls this).
+ void drawPreferences(App& app);
+ // Height the strip takes over the canvas at `rows` rows (logical px x scale).
+ static float height(int rows, float scale);
+
+ // Thread-safe: the folder dialog's callback ("Open folder..." adds a library root).
+ void folderChosen(const std::string& path);
+
+ bool showAtStartup = true; // Preferences > LightBox: opens on the Project tab (interactive sessions only)
private:
+ struct Place {
+ LibraryTab tab = LibraryTab::Project;
+ std::string folder; // "" = the tab's root, else an absolute folder
+ bool operator==(const Place& o) const { return tab == o.tab && folder == o.folder; }
+ };
+ void navigate(App& app, Place to);
+ std::vector<AssetEntry> entries(App& app);
+ void rootEntries(App& app, std::vector<AssetEntry>& out);
+ void activate(App& app, const AssetEntry& e, bool append);
+ void contextMenu(App& app, const AssetEntry& e);
+ ImTextureID thumbnail(App& app, const AssetEntry& e);
+ void drawHeader(App& app, float width);
+ void drawBreadcrumb(App& app);
+ std::string folderLabel(const App& app, const std::string& folder) const;
+
bool open_ = false;
+ Place place_;
+ std::vector<Place> back_, forward_;
+ char filter_[64] = "";
+ std::string selected_; // path or name of the selected tile
+ bool syncedLayout_ = false;
+ // Scrubbing (left-drag sideways) and dragging a tile out onto the canvas.
+ bool pressing_ = false, scrubbed_ = false;
+ float pressX_ = 0.0f, pressY_ = 0.0f, pressScroll_ = 0.0f;
+ int pressTile_ = -1;
+ bool tileDrag_ = false;
+ AssetEntry dragEntry_;
+ float scrollTo_ = -1.0f; // reset scroll after navigating
+ std::string imageMenu_; // image tile double-clicked: its action menu
+ // Folders added with "Open folder..." (shown at every tab's root).
+ std::vector<std::string> extraRoots_;
+ std::mutex folderMutex_;
+ std::string chosenFolder_; // from the folder dialog thread
};
} // namespace sf
diff --git a/src/app/LightBoxStubs.cpp b/src/app/LightBoxStubs.cpp
deleted file mode 100644
index 800fd1d9..00000000
--- a/src/app/LightBoxStubs.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-// SculptForge - open source digital sculpting
-// SPDX-License-Identifier: GPL-3.0-or-later
-//
-// Phase 0 stubs for the LightBox / thumbnails / pickers workstream, which replaces this file with
-// LightBox.cpp, Thumbnails.cpp and Pickers.cpp.
-#include "app/LightBox.h"
-#include "app/Pickers.h"
-#include "app/Thumbnails.h"
-
-namespace sf {
-
-void LightBox::draw(App&, const CanvasRect&) {}
-
-ImTextureID ThumbnailCache::brush(int) { return ImTextureID(0); }
-ImTextureID ThumbnailCache::recipe(const BrushRecipe&) { return ImTextureID(0); }
-ImTextureID ThumbnailCache::alpha(const BrushAlpha&) { return ImTextureID(0); }
-ImTextureID ThumbnailCache::material(int) { return ImTextureID(0); }
-ImTextureID ThumbnailCache::file(const std::string&) { return ImTextureID(0); }
-void ThumbnailCache::pump(Renderer&) {}
-
-void openPicker(Picker, ImVec2) {}
-void drawPickers(App&) {}
-void drawBrushGrid(App&, GridMode) {}
-
-} // namespace sf
diff --git a/src/app/Pickers.cpp b/src/app/Pickers.cpp
new file mode 100644
index 00000000..00211b4d
--- /dev/null
+++ b/src/app/Pickers.cpp
@@ -0,0 +1,991 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Pop-up pickers (ZBrush's brush, stroke, alpha and material pop-ups), the
+// Draw Size / Strength sliders at the cursor, and the thumbnail tile.
+#include "app/Pickers.h"
+
+#include "app/App.h"
+#include "app/AssetLibrary.h"
+#include "app/Ui.h"
+#include "core/BrushLibrary.h"
+#include "core/Matcap.h"
+
+#include <IconsLucide.h>
+
+#include <imgui_internal.h>
+
+#include <algorithm>
+#include <array>
+#include <cctype>
+#include <cmath>
+#include <cstring>
+
+namespace sf {
+
+namespace {
+
+// Theme tokens (docs/ui-design.md section 10).
+constexpr ImU32 kAccent = IM_COL32(240, 136, 46, 255);
+constexpr ImU32 kTileBg = IM_COL32(42, 42, 46, 255);
+constexpr ImU32 kTileHover = IM_COL32(54, 54, 59, 255);
+constexpr ImU32 kTileBorder = IM_COL32(18, 18, 20, 255);
+constexpr ImU32 kGlyph = IM_COL32(140, 140, 144, 255);
+constexpr ImU32 kText = IM_COL32(216, 216, 216, 255);
+constexpr ImU32 kTextDim = IM_COL32(140, 140, 144, 255);
+constexpr ImU32 kPanelBg = IM_COL32(37, 37, 40, 252); // #252528, pop-ups
+
+const SDL_DialogFileFilter kAlphaFilters[] = {{"Images", "png;jpg;jpeg;bmp;tga;psd;gif"}, {"All files", "*"}};
+
+std::string lower(std::string s) {
+ for (auto& c : s)
+ c = char(std::tolower(static_cast<unsigned char>(c)));
+ return s;
+}
+// Shortens `text` with "..." to fit `width`.
+std::string elide(const std::string& text, float width) {
+ if (ImGui::CalcTextSize(text.c_str()).x <= width) return text;
+ std::string s = text;
+ while (!s.empty() && ImGui::CalcTextSize((s + "...").c_str()).x > width) {
+ s.pop_back();
+ while (!s.empty() && (static_cast<unsigned char>(s.back()) & 0xC0) == 0x80)
+ s.pop_back(); // whole UTF-8 chars
+ }
+ return s + "...";
+}
+
+struct Glow {
+ int frame = -1;
+ ImRect rect;
+ ImTextureID tex = ImTextureID(0);
+ std::string glyph;
+};
+Glow& glow() {
+ static Glow g;
+ return g;
+}
+
+// --- Picker state ---
+
+struct State {
+ bool open = false;
+ Picker picker = Picker::Brush;
+ ImVec2 anchor{0, 0};
+ bool underMouse = false;
+ int openedFrame = -1, closedFrame = -1;
+ int keysFrom = 0; // frame from which typed keys count (not the key that opened it)
+ bool addToShelf = false;
+ std::string typed; // brush picker: letters typed so far
+ // Material hover preview: the material to go back to.
+ bool previewing = false;
+ int savedMatcap = -1;
+ // Draw Size / Strength at the cursor.
+ int slider = -1; // 0 = size, 1 = strength
+ ImVec2 sliderAt{0, 0};
+ int sliderFrame = -1;
+ std::string sliderTyped;
+ bool sliderWasActive = false;
+ // Recently used brushes (ids, newest first).
+ std::vector<std::string> recent;
+ std::string lastActive;
+};
+State& st() {
+ static State s;
+ return s;
+}
+
+void closePicker() {
+ State& s = st();
+ if (!s.open) return;
+ s.open = false;
+ s.closedFrame = ImGui::GetFrameCount();
+ s.typed.clear();
+}
+
+// Lays tiles out left to right, `columns` per row.
+void tileGrid(int& column, int columns) {
+ if (column > 0 && column < columns) ImGui::SameLine(0.0f, 6.0f);
+ if (column >= columns) column = 0;
+ ++column;
+}
+
+int columnsFor(float tile, GridMode mode) {
+ if (mode == GridMode::Popup) return 6;
+ return std::max(1, int((ImGui::GetContentRegionAvail().x + 6.0f) / (tile + 6.0f)));
+}
+
+void sectionHeader(const char* text) {
+ ImGui::Dummy(ImVec2(0, 2));
+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
+ ImGui::SeparatorText(text);
+ ImGui::PopStyleColor();
+}
+
+// Hover "Quick Info": a large thumbnail and the description, as ZBrush shows for palette items.
+void quickInfo(ImTextureID tex, const char* glyph, const std::string& title, const std::string& text,
+ const std::string& footer = {}) {
+ if (!ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_NoSharedDelay) ||
+ ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId) || ImGui::GetIO().KeyCtrl)
+ return;
+ ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(340, FLT_MAX));
+ ImGui::BeginTooltip();
+ const float big = 192.0f * 0.75f;
+ if (tex)
+ ImGui::Image(tex, ImVec2(big, big));
+ else if (glyph) {
+ ImGui::Dummy(ImVec2(big, big));
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ dl->AddRectFilled(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), kTileBg, 4.0f);
+ const float fs = ImGui::GetFontSize() * 3.0f;
+ const ImVec2 sz = ImGui::GetFont()->CalcTextSizeA(fs, FLT_MAX, 0, glyph);
+ const ImVec2 c = ImRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax()).GetCenter();
+ dl->AddText(ImGui::GetFont(), fs, ImVec2(c.x - sz.x * 0.5f, c.y - sz.y * 0.5f), kGlyph, glyph);
+ }
+ ImGui::TextUnformatted(title.c_str());
+ if (!text.empty()) {
+ ImGui::PushTextWrapPos(330.0f);
+ ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.78f, 0.78f, 0.78f, 1.0f));
+ ImGui::TextUnformatted(text.c_str());
+ ImGui::PopStyleColor();
+ ImGui::PopTextWrapPos();
+ }
+ if (!footer.empty()) ImGui::TextDisabled("%s", footer.c_str());
+ ImGui::EndTooltip();
+}
+
+// Opens the picker's window at its anchor (or the mouse); returns false when it isn't showing.
+bool beginPickerWindow(const char* title, float width) {
+ State& s = st();
+ const ImGuiViewport* vp = ImGui::GetMainViewport();
+ ImVec2 pos = s.anchor;
+ if (s.underMouse) pos = ImVec2(s.anchor.x - 24.0f, s.anchor.y - 24.0f);
+ ImGui::SetNextWindowPos(pos, ImGuiCond_Appearing);
+ ImGui::SetNextWindowSizeConstraints(ImVec2(width, 0), ImVec2(width, vp->Size.y - 60.0f));
+ if (s.openedFrame == ImGui::GetFrameCount()) ImGui::SetNextWindowFocus();
+ ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 6.0f);
+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(10, 8));
+ ImGui::PushStyleColor(ImGuiCol_WindowBg, kPanelBg);
+ ImGui::PushStyleColor(ImGuiCol_Border, IM_COL32(64, 64, 70, 255));
+ const bool visible = ImGui::Begin(title, nullptr,
+ ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize |
+ ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
+ ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse);
+ ImGui::PopStyleColor(2);
+ ImGui::PopStyleVar(2);
+ // Keep it inside the window (it may have opened near an edge).
+ ImGuiWindow* w = ImGui::GetCurrentWindow();
+ ImVec2 p = w->Pos;
+ p.x = std::clamp(p.x, vp->Pos.x + 4.0f, std::max(vp->Pos.x + 4.0f, vp->Pos.x + vp->Size.x - w->Size.x - 4.0f));
+ p.y = std::clamp(p.y, vp->Pos.y + 4.0f, std::max(vp->Pos.y + 4.0f, vp->Pos.y + vp->Size.y - w->Size.y - 4.0f));
+ if (p.x != w->Pos.x || p.y != w->Pos.y) ImGui::SetWindowPos(p);
+ // A click outside closes it (context menus of its tiles are part of it).
+ const bool clicked = ImGui::IsMouseClicked(ImGuiMouseButton_Left) || ImGui::IsMouseClicked(ImGuiMouseButton_Right);
+ if (clicked && s.openedFrame != ImGui::GetFrameCount() &&
+ !ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows | ImGuiHoveredFlags_AllowWhenBlockedByPopup) &&
+ !ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId))
+ closePicker();
+ return visible;
+}
+
+void pickerTitle(const char* icon, const char* title, const char* hint) {
+ ImGui::TextUnformatted(icon);
+ ImGui::SameLine();
+ ImGui::TextUnformatted(title);
+ if (hint) {
+ ImGui::SameLine();
+ const float w = ImGui::CalcTextSize(hint).x;
+ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + std::max(0.0f, ImGui::GetContentRegionAvail().x - w));
+ ImGui::TextDisabled("%s", hint);
+ }
+}
+
+const BrushAlpha& builtinAlpha(int i) {
+ static const std::array<BrushAlpha, 3> alphas = {BrushAlpha::round(), BrushAlpha::square(), BrushAlpha::noise()};
+ return alphas[size_t(std::clamp(i, 0, 2))];
+}
+
+} // namespace
+
+// ---------------------------------------------------------------------------
+// Tiles
+// ---------------------------------------------------------------------------
+
+bool AssetTile(const char* id, ImTextureID texture, const char* glyph, const std::string& label, float thumbSize,
+ bool selected, const char* badge, bool dim) {
+ const float labelH = ImGui::GetFontSize() + 4.0f;
+ const ImVec2 size(thumbSize, thumbSize + labelH);
+ const ImVec2 p = ImGui::GetCursorScreenPos();
+ const bool clicked = ImGui::InvisibleButton(id, size);
+ const bool hovered = ImGui::IsItemHovered();
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ const ImVec2 t0 = p, t1(p.x + thumbSize, p.y + thumbSize);
+ dl->AddRectFilled(t0, t1, hovered ? kTileHover : kTileBg, 4.0f);
+ if (texture) {
+ const float pad = 2.0f;
+ dl->AddImageRounded(texture, ImVec2(t0.x + pad, t0.y + pad), ImVec2(t1.x - pad, t1.y - pad), ImVec2(0, 0),
+ ImVec2(1, 1), dim ? IM_COL32(255, 255, 255, 110) : IM_COL32_WHITE, 3.0f);
+ } else if (glyph) {
+ const float fs = std::round(thumbSize * 0.36f);
+ const ImVec2 gs = ImGui::GetFont()->CalcTextSizeA(fs, FLT_MAX, 0, glyph);
+ dl->AddText(ImGui::GetFont(), fs,
+ ImVec2(std::round((t0.x + t1.x - gs.x) * 0.5f), std::round((t0.y + t1.y - gs.y) * 0.5f)), kGlyph,
+ glyph);
+ }
+ dl->AddRect(t0, t1,
+ selected ? kAccent
+ : hovered ? IM_COL32(90, 90, 96, 255)
+ : kTileBorder,
+ 4.0f, 0, selected ? 2.0f : 1.0f);
+ if (badge && *badge) {
+ // The orange key of the brush pop-up: press it to pick this tile.
+ const float fs = ImGui::GetFontSize();
+ const ImVec2 bs = ImGui::CalcTextSize(badge);
+ const ImVec2 b1(t1.x - 3.0f, t0.y + 3.0f + fs + 2.0f), b0(b1.x - std::max(bs.x + 8.0f, fs + 2.0f), t0.y + 3.0f);
+ dl->AddRectFilled(b0, b1, kAccent, 3.0f);
+ dl->AddText(ImVec2(std::round((b0.x + b1.x - bs.x) * 0.5f), b0.y + 1.0f), IM_COL32(20, 20, 22, 255), badge);
+ ImGui::LogText(" [%s]", badge);
+ }
+ const std::string shown = elide(label, thumbSize);
+ const ImVec2 ls = ImGui::CalcTextSize(shown.c_str());
+ dl->AddText(ImVec2(std::round(p.x + (thumbSize - ls.x) * 0.5f), t1.y + 2.0f),
+ selected ? IM_COL32(255, 255, 255, 255)
+ : dim ? kTextDim
+ : kText,
+ shown.c_str());
+ ImGui::LogText(" %s", label.c_str()); // drawn directly: tell the log (UI tests read it) too
+ if (hovered) {
+ Glow& g = glow();
+ g.frame = ImGui::GetFrameCount();
+ g.rect = ImRect(t0, t1);
+ g.tex = texture;
+ g.glyph = glyph ? glyph : "";
+ }
+ return clicked;
+}
+
+void AssetTileHoverGlow() {
+ Glow& g = glow();
+ if (g.frame != ImGui::GetFrameCount() || !g.tex || ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId)) return;
+ if (ImGui::IsMouseDragging(ImGuiMouseButton_Left)) return;
+ // ZBrush's thumbnail glow: the hovered thumbnail pops out at 1.5x.
+ const float s = g.rect.GetWidth() * 1.5f;
+ const ImVec2 c = g.rect.GetCenter();
+ const ImGuiViewport* vp = ImGui::GetMainViewport();
+ ImVec2 a(c.x - s * 0.5f, c.y - s * 0.5f);
+ a.x = std::clamp(a.x, vp->Pos.x + 2.0f, vp->Pos.x + vp->Size.x - s - 2.0f);
+ a.y = std::clamp(a.y, vp->Pos.y + 2.0f, vp->Pos.y + vp->Size.y - s - 2.0f);
+ const ImVec2 b(a.x + s, a.y + s);
+ // In the window's own draw list, unclipped: over the neighbouring tiles but under tooltips.
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ dl->PushClipRect(vp->Pos, ImVec2(vp->Pos.x + vp->Size.x, vp->Pos.y + vp->Size.y), false);
+ struct PopClip {
+ ImDrawList* dl;
+ ~PopClip() { dl->PopClipRect(); }
+ } pop{dl};
+ dl->AddRectFilled(ImVec2(a.x + 3, a.y + 5), ImVec2(b.x + 3, b.y + 5), IM_COL32(0, 0, 0, 90), 8.0f);
+ dl->AddRectFilled(a, b, IM_COL32(48, 48, 53, 255), 6.0f);
+ dl->AddImageRounded(g.tex, ImVec2(a.x + 3, a.y + 3), ImVec2(b.x - 3, b.y - 3), ImVec2(0, 0), ImVec2(1, 1),
+ IM_COL32_WHITE, 5.0f);
+ dl->AddRect(a, b, IM_COL32(240, 136, 46, 160), 6.0f, 0, 1.5f);
+}
+
+// ---------------------------------------------------------------------------
+// Brushes
+// ---------------------------------------------------------------------------
+
+std::string BrushItem::id() const {
+ switch (kind) {
+ case Kind::Type:
+ return std::string("type:") + brushName(BrushType(index));
+ case Kind::Paint:
+ return "paint";
+ case Kind::Recipe:
+ return "recipe:" + name;
+ case Kind::File:
+ return "file:" + path;
+ }
+ return {};
+}
+
+std::string brushActionId(const BrushItem& item) {
+ switch (item.kind) {
+ case BrushItem::Kind::Type:
+ return "brush." + lower(brushName(BrushType(item.index)));
+ case BrushItem::Kind::Paint:
+ return "brush.paint";
+ case BrushItem::Kind::Recipe:
+ return "brush.recipe." + item.name;
+ case BrushItem::Kind::File:
+ return "brush.file." + item.path;
+ }
+ return {};
+}
+
+const char* brushTypeDescription(int type) {
+ if (type == kPaintBrush) return "Polypaint: paints the current colour onto the surface without sculpting (P).";
+ switch (BrushType(type)) {
+ case BrushType::Standard:
+ return "Pushes the surface out along its normal, building soft, rounded form. Alt carves.";
+ case BrushType::Clay:
+ return "Builds up flat-bottomed layers of clay that fill dents first, for blocking in form.";
+ case BrushType::Smooth:
+ return "Relaxes the surface and evens out bumps. Hold Shift with any brush to smooth.";
+ case BrushType::Move:
+ return "Grabs the area under the brush and drags it with the cursor, for big shape changes.";
+ case BrushType::Inflate:
+ return "Swells the surface outwards in every direction, like blowing up a balloon.";
+ case BrushType::Crease:
+ return "Cuts a sharp groove (or ridge with Alt), pinching the sides together.";
+ case BrushType::Flatten:
+ return "Presses the surface onto a plane, levelling hills and valleys.";
+ case BrushType::Pinch:
+ return "Pulls the surface toward the stroke, sharpening edges and creases.";
+ case BrushType::DamStandard:
+ return "A sharp V-shaped crease with the sides pinched in, for wrinkles and folds.";
+ case BrushType::ClayBuildup:
+ return "Square, flat-topped clay strokes that stack up quickly, for bold blocking.";
+ case BrushType::SnakeHook:
+ return "Pulls the surface out along the stroke into horns, tentacles and spikes.";
+ case BrushType::Trim:
+ return "Trim Dynamic: cuts away everything above a plane, for hard planar surfaces.";
+ case BrushType::Layer:
+ return "Raises the surface to one fixed height per stroke; overlapping passes never stack.";
+ case BrushType::Nudge:
+ return "Slides the surface sideways along the stroke without changing its height.";
+ default:
+ return "";
+ }
+}
+
+std::vector<BrushItem> PickerUi::brushItems(App& app, bool libraryFiles) {
+ std::vector<BrushItem> items;
+ for (int i = 0; i < int(BrushType::Count); ++i) {
+ BrushItem b;
+ b.kind = BrushItem::Kind::Type;
+ b.index = i;
+ b.name = brushName(BrushType(i));
+ b.description = brushTypeDescription(i);
+ items.push_back(std::move(b));
+ }
+ BrushItem paint;
+ paint.kind = BrushItem::Kind::Paint;
+ paint.name = "Paint";
+ paint.description = brushTypeDescription(kPaintBrush);
+ items.push_back(std::move(paint));
+ for (int i = 0; i < int(app.doc_.brushes.size()); ++i) {
+ const BrushRecipe& r = app.doc_.brushes[size_t(i)];
+ BrushItem b;
+ b.kind = BrushItem::Kind::Recipe;
+ b.index = i;
+ b.name = r.name;
+ b.path = r.origin.path;
+ b.description = r.description;
+ switch (r.origin.source) {
+ case BrushSource::Studio:
+ b.tag = "studio";
+ break;
+ case BrushSource::Gallery:
+ b.tag = "gallery";
+ break;
+ case BrushSource::Project:
+ b.tag = "project";
+ break;
+ case BrushSource::Session:
+ b.tag = "unsaved";
+ break;
+ default:
+ break;
+ }
+ items.push_back(std::move(b));
+ }
+ if (libraryFiles && !app.library_.user.empty()) {
+ // .sfbrush files in the LightBox library that aren't loaded yet.
+ const std::string dir = app.library_.user + "/Brushes";
+ if (const auto* files = app.libraryScanner_.get(dir, "brush", [](const std::string& p) {
+ return isBrushFile(p) ? AssetKind::BrushFile : AssetKind::Folder;
+ }))
+ for (const AssetEntry& e : *files) {
+ if (e.kind != AssetKind::BrushFile) continue;
+ const bool loaded =
+ std::any_of(app.doc_.brushes.begin(), app.doc_.brushes.end(), [&](const BrushRecipe& r) {
+ return r.origin.path == e.path || typedName(r.name) == typedName(e.name);
+ });
+ if (loaded) continue;
+ BrushItem b;
+ b.kind = BrushItem::Kind::File;
+ b.name = e.name;
+ b.path = e.path;
+ b.description = "Brush file in your library: " + e.path;
+ items.push_back(std::move(b));
+ }
+ }
+ return items;
+}
+
+bool PickerUi::isActive(const App& app, const BrushItem& item) {
+ switch (item.kind) {
+ case BrushItem::Kind::Type:
+ return !app.paintMode_ && app.doc_.activeBrush < 0 && int(app.brush_) == item.index;
+ case BrushItem::Kind::Paint:
+ return app.paintMode_;
+ case BrushItem::Kind::Recipe:
+ return !app.paintMode_ && app.doc_.activeBrush == item.index;
+ case BrushItem::Kind::File:
+ return false;
+ }
+ return false;
+}
+
+void PickerUi::select(App& app, const BrushItem& item) {
+ switch (item.kind) {
+ case BrushItem::Kind::Type:
+ app.brush_ = BrushType(item.index);
+ app.doc_.activeBrush = -1;
+ app.paintMode_ = false;
+ app.status_ = std::string("Brush: ") + item.name;
+ break;
+ case BrushItem::Kind::Paint:
+ app.paintMode_ = true;
+ app.status_ = "Brush: Paint";
+ break;
+ case BrushItem::Kind::Recipe:
+ if (item.index < 0 || item.index >= int(app.doc_.brushes.size())) return;
+ app.doc_.activeBrush = item.index;
+ app.paintMode_ = false;
+ app.status_ = "Brush: " + item.name;
+ break;
+ case BrushItem::Kind::File:
+ app.runCommand("brush_load", {{"path", item.path}});
+ if (app.lastCommandOk_) app.paintMode_ = false;
+ break;
+ }
+}
+
+ImTextureID PickerUi::thumbnail(App& app, const BrushItem& item) {
+ switch (item.kind) {
+ case BrushItem::Kind::Type:
+ return app.thumbs_.brush(item.index);
+ case BrushItem::Kind::Paint:
+ return app.thumbs_.brush(kPaintBrush);
+ case BrushItem::Kind::Recipe:
+ return item.index >= 0 && item.index < int(app.doc_.brushes.size())
+ ? app.thumbs_.recipe(app.doc_.brushes[size_t(item.index)])
+ : ImTextureID(0);
+ case BrushItem::Kind::File:
+ return ImTextureID(0);
+ }
+ return ImTextureID(0);
+}
+
+void drawBrushGrid(App& app, GridMode mode) {
+ State& s = st();
+ const bool popup = mode == GridMode::Popup;
+ const float tile = 64.0f * app.uiScale_;
+ const std::vector<BrushItem> items = PickerUi::brushItems(app, true);
+
+ static char paletteFilter[64] = "";
+ if (!popup) {
+ ImGui::SetNextItemWidth(-1);
+ ImGui::InputTextWithHint("##brushfilter", ICON_LC_SEARCH " Filter brushes", paletteFilter,
+ sizeof paletteFilter);
+ }
+ const std::string typed = popup ? s.typed : typedName(paletteFilter);
+ std::vector<std::string> names;
+ for (const auto& it : items)
+ names.push_back(it.name);
+ bool substring = false;
+ const std::vector<size_t> shown = filterByTyped(names, typed, &substring);
+ const auto badges = popup ? letterBadges(names, shown, typed) : std::vector<std::pair<char, size_t>>{};
+
+ // Letter keys (pop-up only; the palette has a filter field instead).
+ if (popup && ImGui::GetFrameCount() >= s.keysFrom) {
+ for (int k = 0; k < 26; ++k) {
+ if (!ImGui::IsKeyPressed(ImGuiKey(ImGuiKey_A + k), false)) continue;
+ const char c = char('a' + k);
+ if (auto b = std::find_if(badges.begin(), badges.end(), [c](const auto& x) { return x.first == c; });
+ b != badges.end()) {
+ const BrushItem pick = items[b->second];
+ closePicker();
+ PickerUi::select(app, pick);
+ return;
+ }
+ s.typed += c;
+ }
+ if (ImGui::IsKeyPressed(ImGuiKey_Backspace) && !s.typed.empty()) s.typed.pop_back();
+ if ((ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter)) && !shown.empty() &&
+ !typed.empty()) {
+ const BrushItem pick = items[shown.front()];
+ closePicker();
+ PickerUi::select(app, pick);
+ return;
+ }
+ }
+
+ if (popup) {
+ // What was typed, or how to type.
+ if (typed.empty()) {
+ ImGui::TextDisabled("Type a letter to narrow the brushes, then press its orange key");
+ } else {
+ std::string shownTyped = typed;
+ for (auto& c : shownTyped)
+ c = char(std::toupper(static_cast<unsigned char>(c)));
+ ImGui::TextColored(ImVec4(0.94f, 0.53f, 0.18f, 1.0f), "%s", shownTyped.c_str());
+ ImGui::SameLine();
+ ImGui::TextDisabled(substring ? "(contains) Backspace: undo a letter Enter: first match"
+ : "Backspace: undo a letter Enter: first match");
+ }
+ }
+
+ // Letter index: A-Z chips with how many brushes start with each letter.
+ {
+ std::array<int, 26> counts{};
+ for (const auto& it : items) {
+ const std::string n = typedName(it.name);
+ if (!n.empty() && n[0] >= 'a' && n[0] <= 'z') ++counts[size_t(n[0] - 'a')];
+ }
+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4, 1));
+ ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(3, 3));
+ const float avail = ImGui::GetContentRegionAvail().x;
+ float x = 0.0f;
+ for (int k = 0; k < 26; ++k) {
+ if (!counts[size_t(k)]) continue;
+ char text[24];
+ std::snprintf(text, sizeof text, "%c %d##chip", char('A' + k), counts[size_t(k)]);
+ const float w = ImGui::CalcTextSize(text, std::strstr(text, "##")).x + 8.0f;
+ if (x > 0.0f && x + w <= avail)
+ ImGui::SameLine();
+ else
+ x = 0.0f;
+ x += w + 3.0f;
+ const bool on = !typed.empty() && typed[0] == char('a' + k);
+ if (on) ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(kAccent));
+ if (ImGui::SmallButton(text)) {
+ if (popup)
+ s.typed = std::string(1, char('a' + k));
+ else
+ std::snprintf(paletteFilter, sizeof paletteFilter, "%c", char('a' + k));
+ }
+ if (on) ImGui::PopStyleColor();
+ ui::HelpText("Letter index", nullptr,
+ "Brushes whose names start with this letter. Click to show only them.", "Brush");
+ }
+ ImGui::PopStyleVar(2);
+ }
+
+ const int columns = columnsFor(tile, mode);
+ auto drawItem = [&](size_t i, int& column, const char* section) {
+ const BrushItem& b = items[i];
+ tileGrid(column, columns);
+ char badge[2] = {0, 0};
+ for (const auto& [c, idx] : badges)
+ if (idx == i) badge[0] = char(std::toupper(static_cast<unsigned char>(c)));
+ const std::string id = b.name + "##" + section + std::to_string(i);
+ const ImTextureID tex = PickerUi::thumbnail(app, b);
+ const char* glyph = b.kind == BrushItem::Kind::Paint ? ICON_LC_PAINTBRUSH : ICON_LC_BRUSH;
+ const bool picked = AssetTile(id.c_str(), tex, glyph, b.name, tile, PickerUi::isActive(app, b),
+ badge[0] ? badge : nullptr, b.kind == BrushItem::Kind::File);
+ std::string footer = b.kind == BrushItem::Kind::Recipe
+ ? (b.tag.empty() ? "Custom brush" : "Custom brush (" + b.tag + ")")
+ : b.kind == BrushItem::Kind::File ? "Library file - pick to load it"
+ : "Built-in brush";
+ quickInfo(tex, glyph, b.name, b.description, footer);
+ ui::HelpText(b.name.c_str(), nullptr, b.description.c_str(), "Brush");
+ if (ImGui::BeginPopupContextItem()) {
+ ImGui::TextDisabled("%s", b.name.c_str());
+ ImGui::Separator();
+ const std::string action = brushActionId(b);
+ auto& shelf = app.layout_.bottomShelf;
+ const bool onShelf = std::find(shelf.begin(), shelf.end(), action) != shelf.end();
+ if (ImGui::MenuItem("Add to bottom shelf", nullptr, false, !onShelf && b.kind != BrushItem::Kind::File)) {
+ shelf.push_back(action);
+ app.status_ = "Added " + b.name + " to the bottom shelf";
+ }
+ if (b.kind == BrushItem::Kind::Recipe) {
+ if (ImGui::MenuItem("Save as .sfbrush...")) {
+ app.doc_.activeBrush = b.index;
+ app.paintMode_ = false;
+ app.saveFileDialog(App::FileAction::SaveBrush);
+ }
+ const BrushRecipe& r = app.doc_.brushes[size_t(b.index)];
+ if (ImGui::MenuItem("Delete...", nullptr, false, isUserLibraryBrush(r))) {
+ app.brushPopup_ = App::BrushPopup::Delete;
+ app.brushPopupName_ = r.name;
+ }
+ if (ImGui::MenuItem("Reveal in folder", nullptr, false, !r.origin.path.empty()))
+ app.revealBrushFile(b.index);
+ }
+ ImGui::EndPopup();
+ }
+ if (picked) {
+ if (popup && s.addToShelf) {
+ auto& shelf = app.layout_.bottomShelf;
+ const std::string action = brushActionId(b);
+ if (std::find(shelf.begin(), shelf.end(), action) == shelf.end()) shelf.push_back(action);
+ app.status_ = "Added " + b.name + " to the bottom shelf";
+ } else {
+ PickerUi::select(app, b);
+ }
+ if (popup) closePicker();
+ }
+ };
+
+ // Recent brushes first (the pop-up, before typing).
+ if (popup && typed.empty() && !s.recent.empty()) {
+ sectionHeader("Recent");
+ int column = 0;
+ for (const std::string& rid : s.recent)
+ for (size_t i = 0; i < items.size(); ++i)
+ if (items[i].id() == rid) {
+ drawItem(i, column, "recent");
+ break;
+ }
+ }
+ struct Section {
+ const char* title;
+ bool (*match)(const BrushItem&);
+ };
+ const Section sections[] = {
+ {"Built-in",
+ [](const BrushItem& b) { return b.kind == BrushItem::Kind::Type || b.kind == BrushItem::Kind::Paint; }},
+ {"Custom", [](const BrushItem& b) { return b.kind == BrushItem::Kind::Recipe; }},
+ {"Library", [](const BrushItem& b) { return b.kind == BrushItem::Kind::File; }},
+ };
+ if (popup) {
+ // The grid scrolls inside the pop-up when there are many custom brushes.
+ const float rowH = tile + ImGui::GetFontSize() + 4.0f + ImGui::GetStyle().ItemSpacing.y;
+ ImGui::SetNextWindowSizeConstraints(
+ ImVec2(0, 0), ImVec2(FLT_MAX, std::min(rowH * 6.5f, ImGui::GetMainViewport()->Size.y * 0.6f)));
+ ImGui::BeginChild("##brushgrid", ImVec2(columns * (tile + 6.0f), 0), ImGuiChildFlags_AutoResizeY,
+ ImGuiWindowFlags_NoBackground);
+ }
+ for (const Section& sec : sections) {
+ std::vector<size_t> in;
+ for (size_t i : shown)
+ if (sec.match(items[i])) in.push_back(i);
+ if (in.empty()) continue;
+ sectionHeader(sec.title);
+ int column = 0;
+ for (size_t i : in)
+ drawItem(i, column, sec.title);
+ }
+ if (shown.empty()) ImGui::TextDisabled("No brush matches \"%s\"", typed.c_str());
+ if (popup) ImGui::EndChild();
+ AssetTileHoverGlow();
+}
+
+// ---------------------------------------------------------------------------
+// Stroke, alpha and material grids
+// ---------------------------------------------------------------------------
+
+void drawStrokeGrid(App& app, GridMode mode) {
+ const float tile = 64.0f * app.uiScale_;
+ static const char* const glyphs[] = {ICON_LC_ELLIPSIS, ICON_LC_SQUARE_DASHED_MOUSE_POINTER, ICON_LC_SPRAY_CAN,
+ ICON_LC_SPLINE_POINTER};
+ static const char* const help[] = {
+ "Even dabs along the path: the classic brush stroke.",
+ "Click and drag one stamp: the drag length sets its size and its direction the rotation (great with alphas).",
+ "Scattered dabs of random size and strength, for organic texture.",
+ "The brush trails the cursor on a string, for smooth, steady lines.",
+ };
+ int column = 0;
+ const int columns = mode == GridMode::Popup ? 4 : columnsFor(tile, mode);
+ for (int i = 0; i < int(StrokeType::Count); ++i) {
+ tileGrid(column, columns);
+ const std::string id = std::string(strokeTypeName(StrokeType(i))) + "##stroke";
+ if (AssetTile(id.c_str(), ImTextureID(0), glyphs[i], strokeTypeName(StrokeType(i)), tile,
+ app.strokeType_ == StrokeType(i))) {
+ app.strokeType_ = StrokeType(i);
+ app.status_ = std::string("Stroke: ") + strokeTypeName(StrokeType(i));
+ }
+ quickInfo(ImTextureID(0), glyphs[i], strokeTypeName(StrokeType(i)), help[i]);
+ ui::HelpText(strokeTypeName(StrokeType(i)), nullptr, help[i], "Stroke");
+ }
+ if (app.strokeType_ == StrokeType::Spray) {
+ ImGui::SetNextItemWidth(-1);
+ ImGui::SliderFloat("##scatter", &app.sprayScatter_, 0.0f, 2.0f, "Scatter %.2f");
+ ui::HelpText("Scatter", nullptr, "How far spray dabs land from the cursor, as a fraction of the brush size.",
+ "Stroke");
+ } else if (app.strokeType_ == StrokeType::LazyMouse) {
+ ImGui::SetNextItemWidth(-1);
+ ImGui::SliderFloat("##lazy", &app.lazyMouse_.radius, 1.0f, 300.0f, "Lazy radius %.0f px");
+ ui::HelpText("Lazy radius", nullptr, "Length of the string the brush trails on: longer = steadier lines.",
+ "Stroke");
+ }
+}
+
+void drawAlphaGrid(App& app, GridMode mode) {
+ const float tile = 64.0f * app.uiScale_;
+ const int columns = columnsFor(tile, mode);
+ const BrushAlpha& current = app.doc_.brushAlpha;
+ static const char* const names[] = {"Round", "Square", "Noise"};
+ static const char* const help[] = {"The plain round falloff (no alpha).", "A square stamp with soft edges.",
+ "A noisy stamp for rough, organic texture."};
+ sectionHeader("Built-in");
+ int column = 0;
+ for (int i = 0; i < 3; ++i) {
+ tileGrid(column, columns);
+ const bool on = lower(current.name) == lower(names[i]) || (i == 0 && current.empty());
+ const ImTextureID tex = app.thumbs_.alpha(builtinAlpha(i));
+ if (AssetTile((std::string(names[i]) + "##alpha").c_str(), tex, ICON_LC_CIRCLE_DASHED, names[i], tile, on))
+ app.runCommand("brush_set_alpha", {{"name", lower(names[i])}});
+ quickInfo(tex, ICON_LC_CIRCLE_DASHED, names[i], help[i]);
+ ui::HelpText(names[i], nullptr, help[i], "Alpha");
+ }
+ // The loaded image alpha, then images in the library's Alphas folder.
+ const bool custom = !current.empty() && lower(current.name) != "square" && lower(current.name) != "noise";
+ std::vector<AssetEntry> files;
+ if (!app.library_.user.empty()) {
+ const std::string dir = app.library_.user + "/Alphas";
+ if (const auto* list = app.libraryScanner_.get(dir, "alpha", [](const std::string& p) {
+ return isImageFile(p) ? AssetKind::AlphaFile : AssetKind::Folder;
+ }))
+ for (const auto& e : *list)
+ if (e.kind == AssetKind::AlphaFile) files.push_back(e);
+ }
+ if (custom || !files.empty()) {
+ sectionHeader("Images");
+ column = 0;
+ if (custom) {
+ tileGrid(column, columns);
+ const ImTextureID tex = app.thumbs_.alpha(current);
+ AssetTile((current.name + "##alphacur").c_str(), tex, ICON_LC_CIRCLE_DASHED, current.name, tile, true);
+ quickInfo(tex, ICON_LC_CIRCLE_DASHED, current.name, "The loaded image alpha (white = full effect).");
+ }
+ for (const auto& e : files) {
+ if (custom && lower(e.name) == lower(current.name)) continue;
+ tileGrid(column, columns);
+ const ImTextureID tex = app.thumbs_.file(e.path);
+ if (AssetTile((e.name + "##alphafile").c_str(), tex, ICON_LC_IMAGE, e.name, tile, false))
+ app.runCommand("brush_set_alpha", {{"path", e.path}, {"invert", app.alphaInvert_}});
+ quickInfo(tex, ICON_LC_IMAGE, e.name, "Image in your library's Alphas folder.", e.path);
+ }
+ }
+ ImGui::Dummy(ImVec2(0, 2));
+ if (ImGui::Button(ICON_LC_FOLDER_OPEN " Load image...", ImVec2(mode == GridMode::Popup ? 0.0f : -1.0f, 0)))
+ SDL_ShowOpenFileDialog(App::onAlphaChosen, &app, app.window_, kAlphaFilters, 2, nullptr, false);
+ ui::HelpText("Load image", nullptr, "Use any grayscale image as the alpha: white = full effect, black = none.",
+ "Alpha");
+ if (mode == GridMode::Popup) ImGui::SameLine();
+ ImGui::Checkbox("Invert loaded image", &app.alphaInvert_);
+ ui::HelpText("Invert loaded image", nullptr, "Load image alphas as their negative (black = full effect).", "Alpha");
+ AssetTileHoverGlow();
+}
+
+void drawMaterialGrid(App& app, GridMode mode) {
+ State& s = st();
+ const bool popup = mode == GridMode::Popup;
+ const float tile = 64.0f * app.uiScale_;
+ const int columns = columnsFor(tile, mode);
+ int column = 0;
+ int hovered = -2;
+ const int active = s.previewing ? s.savedMatcap : app.renderSettings_.matcap;
+ for (int i = -1; i < matcapCount(); ++i) {
+ tileGrid(column, columns);
+ const char* name = i < 0 ? "Studio" : matcapName(i);
+ const ImTextureID tex = app.thumbs_.material(i);
+ if (AssetTile((std::string(name) + "##mat").c_str(), tex, ICON_LC_SUN, name, tile, active == i)) {
+ s.previewing = false;
+ app.renderSettings_.matcap = s.savedMatcap = i; // runCommand below echoes it for scripts
+ app.runCommand("set_material", {{"name", std::string(i < 0 ? "studio" : name)}});
+ if (popup) closePicker();
+ }
+ if (ImGui::IsItemHovered()) hovered = i;
+ ui::HelpText(name, nullptr,
+ i < 0 ? "Clay lighting with cavity shading (the default)."
+ : "MatCap material: the whole lit look in one image.",
+ "Material");
+ }
+ // ZBrush's "Preview Material On Mesh": hovering a material shows it on the model until the pointer leaves.
+ if (popup && st().open) {
+ if (hovered >= -1) {
+ if (!s.previewing) {
+ s.previewing = true;
+ s.savedMatcap = app.renderSettings_.matcap;
+ }
+ app.renderSettings_.matcap = hovered;
+ } else if (s.previewing) {
+ app.renderSettings_.matcap = s.savedMatcap;
+ s.previewing = false;
+ }
+ }
+ AssetTileHoverGlow();
+}
+
+// ---------------------------------------------------------------------------
+// The pop-ups
+// ---------------------------------------------------------------------------
+
+void openPicker(Picker picker, ImVec2 anchor) {
+ State& s = st();
+ // A click on the tile that opened it closes it (the click outside closed it this very frame).
+ if ((s.open && s.picker == picker && s.openedFrame != ImGui::GetFrameCount()) ||
+ (!s.open && s.picker == picker && s.closedFrame == ImGui::GetFrameCount())) {
+ closePicker();
+ return;
+ }
+ s.open = true;
+ s.picker = picker;
+ s.underMouse = anchor.x < 0.0f;
+ s.anchor = s.underMouse ? ImGui::GetIO().MousePos : anchor;
+ s.openedFrame = ImGui::GetFrameCount();
+ // Opened by a key between frames: that key is still "pressed" in the next frame, so skip it.
+ s.keysFrom = ImGui::GetFrameCount() + 2;
+ s.typed.clear();
+ s.addToShelf = false;
+}
+
+void openBrushPickerForShelf(ImVec2 anchor) {
+ openPicker(Picker::Brush, anchor);
+ st().addToShelf = st().open;
+}
+
+bool pickerOpen() { return st().open || st().slider >= 0; }
+
+void PickerUi::sizePopup(App&, bool strength) {
+ State& s = st();
+ s.slider = strength ? 1 : 0;
+ s.sliderAt = ImGui::GetIO().MousePos;
+ s.sliderFrame = ImGui::GetFrameCount();
+ s.sliderTyped.clear();
+ s.sliderWasActive = false;
+}
+
+void drawPickers(App& app) {
+ State& s = st();
+ // Remember what was picked recently, from anywhere (picker, shelf, keys, scripts).
+ {
+ BrushItem active;
+ if (app.paintMode_)
+ active.kind = BrushItem::Kind::Paint;
+ else if (app.doc_.activeBrush >= 0 && app.doc_.activeBrush < int(app.doc_.brushes.size())) {
+ active.kind = BrushItem::Kind::Recipe;
+ active.name = app.doc_.brushes[size_t(app.doc_.activeBrush)].name;
+ } else {
+ active.kind = BrushItem::Kind::Type;
+ active.index = int(app.brush_);
+ }
+ const std::string id = active.id();
+ if (id != s.lastActive) {
+ if (!s.lastActive.empty()) {
+ s.recent.erase(std::remove(s.recent.begin(), s.recent.end(), id), s.recent.end());
+ s.recent.insert(s.recent.begin(), id);
+ if (s.recent.size() > 8) s.recent.resize(8);
+ }
+ s.lastActive = id;
+ }
+ }
+
+ if (s.open) {
+ // Pickers own the keyboard while open (letters choose brushes; Esc closes).
+ ImGui::SetNextFrameWantCaptureKeyboard(true);
+ if (ImGui::IsKeyPressed(ImGuiKey_Escape) && s.openedFrame != ImGui::GetFrameCount()) closePicker();
+ }
+ if (s.open) {
+ const float scale = app.uiScale_;
+ const float gridW = 6 * (64.0f * scale + 6.0f) + 20.0f + ImGui::GetStyle().ScrollbarSize;
+ switch (s.picker) {
+ case Picker::Brush:
+ if (beginPickerWindow("Brushes##picker", gridW)) {
+ pickerTitle(ICON_LC_BRUSH, s.addToShelf ? "Add a brush to the shelf" : "Brushes", "B");
+ drawBrushGrid(app, GridMode::Popup);
+ }
+ ImGui::End();
+ break;
+ case Picker::Stroke:
+ if (beginPickerWindow("Strokes##picker", 4 * (64.0f * scale + 6.0f) + 20.0f)) {
+ pickerTitle(ICON_LC_SPLINE, "Stroke", nullptr);
+ ImGui::Spacing();
+ drawStrokeGrid(app, GridMode::Popup);
+ }
+ ImGui::End();
+ break;
+ case Picker::Alpha:
+ if (beginPickerWindow("Alphas##picker", gridW)) {
+ pickerTitle(ICON_LC_CIRCLE_DASHED, "Alpha", nullptr);
+ drawAlphaGrid(app, GridMode::Popup);
+ }
+ ImGui::End();
+ break;
+ case Picker::Material:
+ if (beginPickerWindow("Materials##picker", gridW)) {
+ pickerTitle(ICON_LC_SUN, "Material", "M");
+ ImGui::Spacing();
+ drawMaterialGrid(app, GridMode::Popup);
+ }
+ ImGui::End();
+ break;
+ }
+ }
+ if (!s.open && s.previewing) { // closed without picking: put the material back
+ app.renderSettings_.matcap = s.savedMatcap;
+ s.previewing = false;
+ }
+
+ // Draw Size (S) / Strength (I) at the cursor.
+ if (s.slider >= 0) {
+ ImGui::SetNextFrameWantCaptureKeyboard(true);
+ const bool size = s.slider == 0;
+ const float w = 200.0f * app.uiScale_;
+ ImGui::SetNextWindowPos(ImVec2(s.sliderAt.x - w * 0.5f, s.sliderAt.y + 14.0f), ImGuiCond_Appearing);
+ if (s.sliderFrame == ImGui::GetFrameCount()) ImGui::SetNextWindowFocus();
+ ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 6.0f);
+ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8, 8));
+ ImGui::PushStyleColor(ImGuiCol_WindowBg, kPanelBg);
+ bool close = false;
+ if (ImGui::Begin(size ? "Draw Size##cursor" : "Strength##cursor", nullptr,
+ ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
+ ImGuiWindowFlags_AlwaysAutoResize)) {
+ const bool first = ImGui::GetFrameCount() < s.sliderFrame + 2; // the S / I key itself
+ // Typing a number sets it (Enter applies, Esc cancels); dragging the slider works too.
+ if (!first) {
+ for (int k = 0; k <= 9; ++k)
+ if (ImGui::IsKeyPressed(ImGuiKey(ImGuiKey_0 + k), false) ||
+ ImGui::IsKeyPressed(ImGuiKey(ImGuiKey_Keypad0 + k), false))
+ s.sliderTyped += char('0' + k);
+ if (ImGui::IsKeyPressed(ImGuiKey_Period, false) || ImGui::IsKeyPressed(ImGuiKey_KeypadDecimal, false))
+ s.sliderTyped += '.';
+ if (ImGui::IsKeyPressed(ImGuiKey_Backspace) && !s.sliderTyped.empty()) s.sliderTyped.pop_back();
+ if (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter)) {
+ if (!s.sliderTyped.empty()) {
+ const float v = std::strtof(s.sliderTyped.c_str(), nullptr);
+ if (size)
+ app.radiusPx_ = std::clamp(v, 2.0f, 800.0f);
+ else
+ app.strength_ = std::clamp(v > 1.0f ? v / 100.0f : v, 0.01f, 1.0f);
+ }
+ close = true;
+ }
+ if (ImGui::IsKeyPressed(ImGuiKey_Escape)) close = true;
+ }
+ ImGui::SetNextItemWidth(w);
+ char fmt[64];
+ if (!s.sliderTyped.empty())
+ std::snprintf(fmt, sizeof fmt, "%s %s_", size ? "Draw Size" : "Strength", s.sliderTyped.c_str());
+ else
+ std::snprintf(fmt, sizeof fmt, "%s", size ? "Draw Size %.0f" : "Strength %.2f");
+ if (size)
+ ImGui::SliderFloat("##cursorvalue", &app.radiusPx_, 2.0f, 800.0f, fmt, ImGuiSliderFlags_Logarithmic);
+ else
+ ImGui::SliderFloat("##cursorvalue", &app.strength_, 0.01f, 1.0f, fmt);
+ ImGui::LogText(size ? "Draw Size %.0f" : "Strength %.2f", size ? app.radiusPx_ : app.strength_);
+ ui::HelpText(
+ size ? "Draw Size" : "Strength", size ? "S" : "I",
+ size ? "Brush radius in screen pixels. Drag, or type a number and press Enter. [ and ] also change it."
+ : "How strongly the brush works (0.01-1). Drag, or type a number and press Enter.",
+ "Draw");
+ if (ImGui::IsItemActive())
+ s.sliderWasActive = true;
+ else if (s.sliderWasActive)
+ close = true; // closes on release, as in ZBrush
+ const bool clicked =
+ ImGui::IsMouseClicked(ImGuiMouseButton_Left) || ImGui::IsMouseClicked(ImGuiMouseButton_Right);
+ if (clicked && !first && !ImGui::IsWindowHovered()) close = true;
+ }
+ ImGui::End();
+ ImGui::PopStyleColor();
+ ImGui::PopStyleVar(2);
+ if (close) s.slider = -1;
+ }
+}
+
+} // namespace sf
diff --git a/src/app/Pickers.h b/src/app/Pickers.h
index 9c8f63d3..3f8a3f32 100644
--- a/src/app/Pickers.h
+++ b/src/app/Pickers.h
@@ -2,11 +2,15 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// ZBrush-style pop-up pickers: brush grid (B; type letters to choose), stroke,
-// alpha and material (M) grids.
+// alpha and material (M) grids, and the Draw Size / Strength sliders at the
+// cursor (S / I). Also the thumbnail tile every grid and the LightBox draw.
#pragma once
#include <imgui.h>
+#include <string>
+#include <vector>
+
namespace sf {
class App;
@@ -14,9 +18,50 @@ class App;
enum class Picker { Brush, Stroke, Alpha, Material };
enum class GridMode { Popup, Palette };
+// Opens a picker with its top-left at `anchor` (beside a shelf tile). A negative anchor.x opens it
+// under the mouse, as the keyboard shortcuts do.
void openPicker(Picker picker, ImVec2 anchor);
+// The brush picker in "add to bottom shelf" mode (the shelf's [+] tile): picking adds instead of selecting.
+void openBrushPickerForShelf(ImVec2 anchor);
+bool pickerOpen(); // any picker or size/strength pop-up is showing
void drawPickers(App& app);
// The brush grid, reused by the Brush palette.
void drawBrushGrid(App& app, GridMode mode);
+// The alpha and material grids, reused by the Alpha and Material palettes.
+void drawAlphaGrid(App& app, GridMode mode);
+void drawMaterialGrid(App& app, GridMode mode);
+void drawStrokeGrid(App& app, GridMode mode);
+
+// One brush of the picker, the LightBox Brush tab and the shelves.
+struct BrushItem {
+ enum class Kind { Type, Paint, Recipe, File } kind = Kind::Type;
+ int index = -1; // BrushType (Type) or doc.brushes index (Recipe)
+ std::string name; // shown under the tile
+ std::string path; // .sfbrush (File)
+ std::string description;
+ std::string tag; // "gallery", "studio", "unsaved"... (Recipe)
+ std::string id() const; // stable across frames: "type:Clay", "recipe:Dragon Scales", "file:<path>"
+};
+
+// Shared by the pickers, the LightBox and (through ui ids) the shelves; they read App internals.
+struct PickerUi {
+ static std::vector<BrushItem> brushItems(App& app, bool libraryFiles);
+ static bool isActive(const App& app, const BrushItem& item);
+ static void select(App& app, const BrushItem& item);
+ static ImTextureID thumbnail(App& app, const BrushItem& item);
+ static void sizePopup(App& app, bool strength); // opens the S / I slider under the mouse
+};
+
+// Action id of a brush for the shelves ("brush.clay", "brush.paint", "brush.recipe.<name>").
+std::string brushActionId(const BrushItem& item);
+const char* brushTypeDescription(int brushType); // BrushType, or kPaintBrush
+
+// A thumbnail tile: the image (or `glyph` on a dark square while it loads), the label under it,
+// accent outline when selected. `id` must be unique in the window. Returns true on click; check
+// ImGui::IsItemHovered() / IsMouseDoubleClicked() after it for more.
+bool AssetTile(const char* id, ImTextureID texture, const char* glyph, const std::string& label, float thumbSize,
+ bool selected, const char* badge = nullptr, bool dim = false);
+// Draws the 1.5x hover "glow" of the tile under the mouse (call once the grid is drawn).
+void AssetTileHoverGlow();
} // namespace sf
diff --git a/src/app/Thumbnails.cpp b/src/app/Thumbnails.cpp
new file mode 100644
index 00000000..a4c2dddc
--- /dev/null
+++ b/src/app/Thumbnails.cpp
@@ -0,0 +1,514 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "app/Thumbnails.h"
+
+#include "app/AssetLibrary.h"
+#include "core/Commands.h"
+#include "core/Document.h"
+#include "core/PathStroke.h"
+#include "core/Primitives.h"
+#include "core/Project.h"
+#include "core/Sculpt.h"
+#include "render/Camera.h"
+#include "render/GL.h"
+#include "render/Renderer.h"
+
+#include <SDL3/SDL.h>
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <filesystem>
+#include <system_error>
+
+namespace sf {
+
+namespace {
+
+constexpr size_t kMaxJobs = 3; // worker threads at a time
+constexpr int kRendersPerFrame = 2; // GL renders per frame
+constexpr double kStatSeconds = 2.0; // how long a file's size / time stamp is trusted
+
+std::filesystem::path fsPath(const std::string& p) { return std::filesystem::path(std::u8string(p.begin(), p.end())); }
+
+template <class T> bool ready(const std::future<T>& f) {
+ return f.valid() && f.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
+}
+
+ImTextureID texId(unsigned tex) { return ImTextureID(uintptr_t(tex)); }
+
+// One mesh of every visible SubTool of `doc` (positions, triangles and polypaint), for the preview.
+std::unique_ptr<Mesh> sceneMesh(Document& doc) {
+ auto out = std::make_unique<Mesh>();
+ bool colors = false;
+ for (int i = 0; i < doc.subtoolCount(); ++i)
+ colors |= doc.subtools[size_t(i)].visible &&
+ doc.subtoolMesh(i).colors.size() == doc.subtoolMesh(i).positions.size() &&
+ !doc.subtoolMesh(i).colors.empty();
+ for (int i = 0; i < doc.subtoolCount(); ++i) {
+ if (!doc.subtools[size_t(i)].visible) continue;
+ const Mesh& m = doc.subtoolMesh(i);
+ const uint32_t base = uint32_t(out->positions.size());
+ out->positions.insert(out->positions.end(), m.positions.begin(), m.positions.end());
+ if (colors) {
+ if (m.colors.size() == m.positions.size())
+ out->colors.insert(out->colors.end(), m.colors.begin(), m.colors.end());
+ else
+ out->colors.insert(out->colors.end(), m.positions.size(), glm::vec3(1.0f));
+ }
+ const bool hidden = m.hidden.size() == m.triangles.size();
+ for (size_t t = 0; t < m.triangles.size(); ++t)
+ if (!hidden || !m.hidden[t]) out->triangles.push_back(m.triangles[t] + glm::uvec3(base));
+ }
+ if (out->triangles.empty()) return nullptr;
+ out->rebuildTopology();
+ out->recomputeAllNormals();
+ return out;
+}
+
+// Paths for brush previews: an S across a plane at y = 0 (seen from above), or across the front of a sphere.
+std::vector<glm::vec3> planeCurve() {
+ std::vector<glm::vec3> pts;
+ for (int i = 0; i <= 8; ++i) {
+ const float u = float(i) / 8.0f;
+ pts.emplace_back(-0.66f + 1.32f * u, 1.0f, 0.28f * std::sin(u * 6.2831853f));
+ }
+ return pts;
+}
+std::vector<glm::vec3> line(glm::vec3 a, glm::vec3 b) { return {a, b}; }
+
+void stroke(Document& d, const BrushRecipe* recipe, BrushType type, std::vector<glm::vec3> pts, glm::vec3 view,
+ float radius, float strength, bool curve = true) {
+ PathStroke st;
+ st.points = std::move(pts);
+ st.view = view;
+ st.radius = radius;
+ st.strength = strength;
+ st.curve = curve;
+ std::string err;
+ strokePath(d, recipe, type, st, err);
+}
+
+// Sculpts the preview of a brush (a recipe when given, else `type`) with the same code real strokes use.
+std::unique_ptr<Mesh> sculptBrushPreview(const BrushRecipe* recipe, int type, float& pitch, float& zoom,
+ float& distance) {
+ Document d;
+ const glm::vec3 down(0.0f, -1.0f, 0.0f), front(0.0f, 0.0f, -1.0f);
+ // A close-up of the stroke from above at an angle; the plane's edges stay outside the tile.
+ pitch = -46.0f;
+ distance = 2.15f;
+ if (type == kPaintBrush) {
+ // Polypaint: a coloured S on a clay sphere.
+ Mesh m = makeIcosphere(5, 0.9f);
+ m.ensureColors(glm::vec3(0.62f, 0.60f, 0.58f));
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {
+ const glm::vec3 p = m.positions[v];
+ const float curve = 0.32f * std::sin(p.x * 3.4f);
+ const float d2 = std::abs(p.y - curve);
+ if (p.z > 0.0f && d2 < 0.16f) {
+ const float t = std::clamp((0.16f - d2) / 0.05f, 0.0f, 1.0f);
+ m.colors[v] = glm::mix(m.colors[v], glm::vec3(0.85f, 0.18f, 0.06f), t);
+ }
+ }
+ pitch = -12.0f;
+ distance = 0.0f;
+ return std::make_unique<Mesh>(std::move(m));
+ }
+ const auto bt = BrushType(type);
+ const bool sphere = !recipe && (bt == BrushType::Move || bt == BrushType::SnakeHook || bt == BrushType::Inflate);
+ if (sphere) {
+ d.setMesh(makeIcosphere(5, 0.9f));
+ pitch = -12.0f;
+ distance = 0.0f;
+ if (bt == BrushType::Move)
+ stroke(d, nullptr, bt, line({-0.1f, 0.0f, 2.0f}, {0.5f, 0.32f, 2.0f}), front, 0.6f, 1.0f, false);
+ else if (bt == BrushType::SnakeHook) {
+ // SnakeHook pulls out along the stroke; the path heads out of the surface to the side.
+ stroke(d, nullptr, bt, line({0.15f, 0.15f, 2.0f}, {0.9f, 0.55f, 2.0f}), front, 0.28f, 1.0f, false);
+ } else {
+ std::vector<glm::vec3> pts;
+ for (glm::vec3 p : planeCurve())
+ pts.emplace_back(p.x * 0.8f, p.z * 1.4f, 2.0f);
+ stroke(d, nullptr, bt, pts, front, 0.2f, 0.8f);
+ }
+ return sceneMesh(d);
+ }
+ d.setMesh(makePlane(220, 3.0f));
+ const float r = 0.19f;
+ if (recipe) {
+ stroke(d, recipe, BrushType::Standard, planeCurve(), down, r, 0.9f);
+ return sceneMesh(d);
+ }
+ switch (bt) {
+ case BrushType::Smooth:
+ case BrushType::Flatten:
+ case BrushType::Trim:
+ case BrushType::Nudge: {
+ // These change existing form: raise a ridge first, then cross it with the brush.
+ const auto ridge = line({-0.9f, 1.0f, 0.0f}, {0.9f, 1.0f, 0.0f});
+ stroke(d, nullptr, BrushType::Standard, ridge, down, 0.26f, 1.0f, false);
+ stroke(d, nullptr, BrushType::Clay, ridge, down, 0.26f, 1.0f, false);
+ const auto across = bt == BrushType::Nudge ? line({-0.15f, 1.0f, -0.35f}, {0.15f, 1.0f, 0.35f})
+ : line({0.0f, 1.0f, -0.8f}, {0.0f, 1.0f, 0.8f});
+ const float strength = bt == BrushType::Nudge ? 0.05f : bt == BrushType::Trim ? 0.5f : 1.0f;
+ const int passes = bt == BrushType::Smooth ? 3 : 1;
+ for (int pass = 0; pass < passes; ++pass)
+ stroke(d, nullptr, bt, across, down, bt == BrushType::Nudge ? 0.26f : 0.22f, strength, false);
+ break;
+ }
+ case BrushType::Pinch:
+ stroke(d, nullptr, BrushType::Standard, planeCurve(), down, r * 1.2f, 0.9f);
+ stroke(d, nullptr, bt, planeCurve(), down, r * 1.2f, 1.0f);
+ break;
+ case BrushType::ClayBuildup:
+ stroke(d, nullptr, bt, planeCurve(), down, r, 0.12f);
+ break;
+ case BrushType::Layer:
+ stroke(d, nullptr, bt, planeCurve(), down, 0.34f, 1.0f); // its height scales with the radius
+ break;
+ default:
+ stroke(d, nullptr, bt, planeCurve(), down, r, 1.0f);
+ break;
+ }
+ return sceneMesh(d);
+}
+
+} // namespace
+
+ThumbnailCache::ThumbnailCache() = default;
+
+ThumbnailCache::~ThumbnailCache() {
+ // Textures die with the GL context (App::shutdown calls clear() while it is current).
+ for (auto& j : jobs_)
+ if (j.result.valid()) j.result.wait();
+ for (auto& w : writes_)
+ if (w.valid()) w.wait();
+}
+
+void ThumbnailCache::clear() {
+ for (auto& [key, e] : entries_)
+ if (e.tex) gl::DeleteTextures(1, &e.tex);
+ entries_.clear();
+ queue_.clear();
+ renders_.clear();
+}
+
+void ThumbnailCache::setCacheDir(std::string dir) {
+ cacheDir_ = std::move(dir);
+ if (cacheDir_.empty()) return;
+ std::error_code ec;
+ std::filesystem::create_directories(fsPath(cacheDir_), ec);
+ if (ec) {
+ cacheDir_.clear();
+ return;
+ }
+ // Keep the disk cache bounded: the least recently written thumbnails go first.
+ writes_.push_back(std::async(std::launch::async, [dir = cacheDir_] {
+ constexpr size_t kKeep = 2000;
+ std::vector<std::pair<std::filesystem::file_time_type, std::filesystem::path>> files;
+ std::error_code e;
+ for (std::filesystem::directory_iterator it(fsPath(dir), e), end; !e && it != end; it.increment(e))
+ if (it->path().extension() == ".png") files.emplace_back(it->last_write_time(e), it->path());
+ if (files.size() <= kKeep) return;
+ std::sort(files.begin(), files.end(), [](const auto& a, const auto& b) { return a.first > b.first; });
+ for (size_t i = kKeep; i < files.size(); ++i)
+ std::filesystem::remove(files[i].second, e);
+ }));
+}
+
+bool ThumbnailCache::busy() const { return !queue_.empty() || !jobs_.empty() || !renders_.empty(); }
+
+ImTextureID ThumbnailCache::request(const std::string& key, Producer produce, bool diskCache) {
+ auto it = entries_.find(key);
+ if (it != entries_.end()) {
+ it->second.used = frame_;
+ return it->second.state == State::Ready ? texId(it->second.tex) : ImTextureID(0);
+ }
+ Entry& e = entries_[key];
+ e.used = frame_;
+ if (diskCache && !cacheDir_.empty()) {
+ // Try the disk cache first; fall back to making it.
+ const std::string cached = thumbnailCachePath(cacheDir_, key);
+ produce = [cached, make = std::move(produce)]() {
+ Result r;
+ std::string err;
+ std::error_code ec;
+ if (std::filesystem::is_regular_file(fsPath(cached), ec) && Image::load(cached, r.image, err)) {
+ r.store = false;
+ return r;
+ }
+ return make();
+ };
+ } else if (!diskCache) {
+ produce = [make = std::move(produce)]() {
+ Result r = make();
+ r.store = false;
+ return r;
+ };
+ }
+ queue_.emplace_front(key, std::move(produce));
+ return ImTextureID(0);
+}
+
+ImTextureID ThumbnailCache::brush(int brushType) {
+ const std::string key = "brush|" + std::to_string(brushType) + "|" + std::to_string(kThumbnailVersion);
+ return request(
+ hex64(fnv1a64(key)),
+ [brushType] {
+ Result r;
+ r.mesh = sculptBrushPreview(nullptr, brushType, r.pitch, r.zoom, r.distance);
+ r.label = "brush-" + std::to_string(brushType);
+ r.yaw = 0.0f;
+ r.polypaint = brushType == kPaintBrush;
+ return r;
+ },
+ true);
+}
+
+ImTextureID ThumbnailCache::recipe(const BrushRecipe& recipe) {
+ const std::string key = "recipe|" + recipe.toJson().dump() + "|" + std::to_string(kThumbnailVersion);
+ return request(
+ hex64(fnv1a64(key)),
+ [recipe] {
+ Result r;
+ r.mesh = sculptBrushPreview(&recipe, 0, r.pitch, r.zoom, r.distance);
+ r.label = "recipe-" + recipe.name;
+ r.yaw = 0.0f;
+ return r;
+ },
+ true);
+}
+
+ImTextureID ThumbnailCache::alpha(const BrushAlpha& alpha) {
+ // Name, size and a sparse sample of the values: cheap enough to compute every frame.
+ uint64_t h = fnv1a64(alpha.name + "|" + std::to_string(alpha.width) + "x" + std::to_string(alpha.height));
+ const size_t n = alpha.values.size();
+ for (size_t i = 0; i < 64 && n; ++i) {
+ const float v = alpha.values[i * n / 64];
+ h = fnv1a64(std::string_view(reinterpret_cast<const char*>(&v), sizeof v), h);
+ }
+ return request(
+ "alpha|" + hex64(h),
+ [alpha] {
+ // The stamp as ZBrush shows alphas: white = full effect on black.
+ Result r;
+ constexpr int S = 128;
+ r.image.width = r.image.height = S;
+ r.image.rgba.resize(size_t(S) * S * 4);
+ const BrushAlpha shown = alpha.empty() ? BrushAlpha::round() : alpha;
+ for (int y = 0; y < S; ++y)
+ for (int x = 0; x < S; ++x) {
+ const float u = (float(x) + 0.5f) / S * 2.0f - 1.0f, v = 1.0f - (float(y) + 0.5f) / S * 2.0f;
+ float g = shown.empty() ? brushFalloff(std::sqrt(u * u + v * v), 1.0f) : shown.sample(u, v);
+ const auto c = uint8_t(std::clamp(g, 0.0f, 1.0f) * 255.0f + 0.5f);
+ uint8_t* p = &r.image.rgba[(size_t(y) * S + size_t(x)) * 4];
+ p[0] = p[1] = p[2] = c;
+ p[3] = 255;
+ }
+ return r;
+ },
+ false);
+}
+
+ImTextureID ThumbnailCache::material(int matcap) {
+ const std::string key = "material|" + std::to_string(matcap) + "|" + std::to_string(kThumbnailVersion);
+ return request(
+ hex64(fnv1a64(key)),
+ [matcap] {
+ Result r;
+ r.mesh = std::make_unique<Mesh>(makeIcosphere(5, 1.0f));
+ r.matcap = matcap;
+ r.yaw = 0.0f;
+ r.pitch = 0.0f;
+ return r;
+ },
+ true);
+}
+
+ImTextureID ThumbnailCache::primitive(int primitive) {
+ const std::string key = "primitive|" + std::to_string(primitive) + "|" + std::to_string(kThumbnailVersion);
+ return request(
+ hex64(fnv1a64(key)),
+ [primitive] {
+ Result r;
+ switch (Primitive(primitive)) {
+ case Primitive::Cube:
+ r.mesh = std::make_unique<Mesh>(makeCube(24, 1.4f));
+ break;
+ case Primitive::Plane:
+ r.mesh = std::make_unique<Mesh>(makePlane(32, 2.0f));
+ r.pitch = -35.0f;
+ break;
+ default:
+ r.mesh = std::make_unique<Mesh>(makeIcosphere(5, 1.0f));
+ break;
+ }
+ return r;
+ },
+ true);
+}
+
+ImTextureID ThumbnailCache::file(const std::string& path) {
+ Stat& s = stats_[path];
+ const double now = ImGui::GetTime();
+ if (now - s.at > kStatSeconds) {
+ std::error_code ec;
+ s.at = now;
+ s.exists = std::filesystem::is_regular_file(fsPath(path), ec);
+ s.size = s.exists ? uint64_t(std::filesystem::file_size(fsPath(path), ec)) : 0;
+ s.mtime = modifiedTime(path);
+ }
+ if (!s.exists) return ImTextureID(0);
+ const bool image = isImageFile(path), project = isProjectFile(path);
+ const std::string kind = project ? "project" : image ? "image" : "mesh";
+ const std::string key = fileThumbnailKey(kind, path, s.size, s.mtime, kPixels);
+ return request(
+ key,
+ [path, image, project] {
+ Result r;
+ std::string err;
+ if (image) {
+ Image full;
+ if (Image::load(path, full, err)) r.image = full.downscaled(kPixels);
+ return r;
+ }
+ if (project && loadProjectThumbnail(path, r.image, err)) return r;
+ // Meshes (and projects saved without a thumbnail): load on this worker, render on the main thread.
+ Document scratch;
+ if (CommandRegistry().execute(scratch, "open", {{"path", path}}).ok) r.mesh = sceneMesh(scratch);
+ r.polypaint = true;
+ return r;
+ },
+ true);
+}
+
+void ThumbnailCache::refresh(const std::string& path) {
+ auto s = stats_.find(path);
+ if (s == stats_.end()) return;
+ const std::string kind = isProjectFile(path) ? "project" : isImageFile(path) ? "image" : "mesh";
+ const std::string key = fileThumbnailKey(kind, path, s->second.size, s->second.mtime, kPixels);
+ if (!cacheDir_.empty()) {
+ std::error_code ec;
+ std::filesystem::remove(fsPath(thumbnailCachePath(cacheDir_, key)), ec);
+ }
+ if (auto e = entries_.find(key); e != entries_.end() && e->second.state != State::Running) {
+ if (e->second.tex) gl::DeleteTextures(1, &e->second.tex);
+ entries_.erase(e);
+ }
+ stats_.erase(s);
+}
+
+void ThumbnailCache::upload(const std::string& key, const Image& image) {
+ auto it = entries_.find(key);
+ if (it == entries_.end()) return; // evicted meanwhile
+ Entry& e = it->second;
+ if (image.empty()) {
+ e.state = State::Failed;
+ return;
+ }
+ if (!e.tex) gl::GenTextures(1, &e.tex);
+ gl::BindTexture(GL_TEXTURE_2D, e.tex);
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ gl::PixelStorei(GL_UNPACK_ALIGNMENT, 1);
+ gl::TexImage2D(GL_TEXTURE_2D, 0, GLint(GL_RGBA8), image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
+ image.rgba.data());
+ gl::BindTexture(GL_TEXTURE_2D, 0);
+ e.state = State::Ready;
+}
+
+void ThumbnailCache::evict() {
+ size_t live = 0;
+ for (const auto& [k, e] : entries_)
+ live += e.tex != 0;
+ if (live <= kMaxTextures) return;
+ std::vector<std::pair<uint64_t, std::string>> byAge;
+ for (const auto& [k, e] : entries_)
+ if (e.tex && e.used + 2 < frame_) byAge.emplace_back(e.used, k);
+ std::sort(byAge.begin(), byAge.end());
+ for (size_t i = 0; i < byAge.size() && live > kMaxTextures; ++i, --live) {
+ auto it = entries_.find(byAge[i].second);
+ gl::DeleteTextures(1, &it->second.tex);
+ entries_.erase(it); // made again (from the disk cache) when shown again
+ }
+}
+
+void ThumbnailCache::pump(Renderer& renderer) {
+ ++frame_;
+ // Requests not seen for a while (scrolled away, picker closed) leave the queue.
+ for (auto it = queue_.begin(); it != queue_.end();) {
+ auto e = entries_.find(it->first);
+ if (e == entries_.end() || e->second.used + 30 < frame_) {
+ if (e != entries_.end()) entries_.erase(e);
+ it = queue_.erase(it);
+ } else {
+ ++it;
+ }
+ }
+ while (jobs_.size() < kMaxJobs && !queue_.empty()) {
+ auto [key, produce] = std::move(queue_.front());
+ queue_.pop_front();
+ entries_[key].state = State::Running;
+ jobs_.push_back({key, std::async(std::launch::async, std::move(produce))});
+ }
+ for (auto it = jobs_.begin(); it != jobs_.end();) {
+ if (!ready(it->result)) {
+ ++it;
+ continue;
+ }
+ Result r = it->result.get();
+ if (r.mesh) {
+ if (auto e = entries_.find(it->key); e != entries_.end()) e->second.state = State::Rendering;
+ renders_.emplace_back(it->key, std::move(r));
+ } else {
+ upload(it->key, r.image);
+ if (r.store && !r.image.empty() && !cacheDir_.empty())
+ writes_.push_back(
+ std::async(std::launch::async, [path = thumbnailCachePath(cacheDir_, it->key), img = r.image] {
+ std::string err;
+ img.savePng(path, err);
+ }));
+ }
+ it = jobs_.erase(it);
+ }
+ for (int n = 0; n < kRendersPerFrame && !renders_.empty(); ++n) {
+ auto [key, r] = std::move(renders_.front());
+ renders_.pop_front();
+ Camera cam;
+ cam.aspect = 1.0f;
+ cam.yaw = glm::radians(r.yaw);
+ cam.pitch = glm::radians(r.pitch);
+ cam.frame(r.mesh->bounds());
+ cam.distance *= r.zoom;
+ if (r.distance > 0.0f) {
+ cam.target = glm::vec3(0.0f);
+ cam.distance = r.distance;
+ }
+ RenderSettings settings;
+ settings.matcap = r.matcap;
+ settings.showPolypaint = r.polypaint;
+ settings.showMask = settings.showPolygroups = false;
+ settings.dimInactive = false;
+ Image img;
+ img.width = img.height = kPixels;
+ std::string err;
+ if (!renderer.renderMeshThumbnail(*r.mesh, cam, kPixels, settings, img.rgba, err)) img = Image();
+ upload(key, img);
+ if (!r.label.empty() && !img.empty() && SDL_getenv("SCULPTFORGE_THUMBNAIL_CACHE") && !cacheDir_.empty()) {
+ std::string e;
+ img.savePng(cacheDir_ + "/" + r.label + ".png", e);
+ }
+ if (r.store && !img.empty() && !cacheDir_.empty())
+ writes_.push_back(std::async(std::launch::async, [path = thumbnailCachePath(cacheDir_, key), img] {
+ std::string e;
+ img.savePng(path, e);
+ }));
+ }
+ writes_.erase(std::remove_if(writes_.begin(), writes_.end(), [](const std::future<void>& f) { return ready(f); }),
+ writes_.end());
+ evict();
+}
+
+} // namespace sf
diff --git a/src/app/Thumbnails.h b/src/app/Thumbnails.h
index c5cb06b6..aed2c35c 100644
--- a/src/app/Thumbnails.h
+++ b/src/app/Thumbnails.h
@@ -4,14 +4,28 @@
// Thumbnails for brushes, alphas, materials and files, rendered offscreen and
// cached in memory and on disk. Calls never block: they return 0 until the
// image is ready, and pump() does a little work each frame.
+//
+// Workers sculpt the brush previews (one S-stroke with the real brush code on a
+// fresh plane or sphere), load meshes and decode images; the main thread then
+// renders at most two meshes per frame. Finished thumbnails are written to
+// <cache dir>/<fnv1a64 key>.png, and at most 256 textures stay in GPU memory.
#pragma once
#include "core/BrushAlpha.h"
#include "core/BrushRecipe.h"
+#include "core/Image.h"
+#include "core/Mesh.h"
#include <imgui.h>
+#include <cstdint>
+#include <deque>
+#include <functional>
+#include <future>
+#include <memory>
#include <string>
+#include <unordered_map>
+#include <vector>
namespace sf {
@@ -19,12 +33,70 @@ class Renderer;
class ThumbnailCache {
public:
- ImTextureID brush(int brushType);
+ static constexpr int kPixels = 192; // rendered size (shown at 96, crisp on HiDPI)
+ static constexpr size_t kMaxTextures = 256;
+
+ ThumbnailCache();
+ ~ThumbnailCache();
+ ThumbnailCache(const ThumbnailCache&) = delete;
+ ThumbnailCache& operator=(const ThumbnailCache&) = delete;
+
+ ImTextureID brush(int brushType); // BrushType, or kPaintBrush (AssetLibrary.h)
ImTextureID recipe(const BrushRecipe& recipe);
ImTextureID alpha(const BrushAlpha& alpha);
- ImTextureID material(int matcap);
+ ImTextureID material(int matcap); // -1 = Studio
+ ImTextureID primitive(int primitive); // Primitive (AssetLibrary.h)
+ // Projects (their embedded thumbnail.png, else rendered once), meshes and images.
ImTextureID file(const std::string& path);
+ // Every frame on the main thread with the GL context current.
void pump(Renderer& renderer);
+
+ void setCacheDir(std::string dir); // "" = memory only (UI tests, renders)
+ void refresh(const std::string& path); // forget a file's thumbnail (memory and disk) and make it again
+ bool busy() const; // work queued or running (UI tests: wait_idle)
+ void clear(); // frees every texture (needs the GL context)
+
+private:
+ struct Result {
+ Image image; // ready to upload (cache hit, image file, alpha, project thumbnail)
+ std::unique_ptr<Mesh> mesh; // needs a render
+ int matcap = -1;
+ float yaw = 30.0f, pitch = -15.0f; // degrees
+ float zoom = 0.92f; // camera distance relative to framing the whole mesh
+ float distance = 0.0f; // > 0: this camera distance from the origin instead
+ std::string label; // for SCULPTFORGE_THUMBNAIL_CACHE debugging
+ bool polypaint = false;
+ bool store = true; // write to the disk cache
+ };
+ using Producer = std::function<Result()>;
+ enum class State { Queued, Running, Rendering, Ready, Failed };
+ struct Entry {
+ State state = State::Queued;
+ unsigned tex = 0;
+ uint64_t used = 0;
+ };
+ ImTextureID request(const std::string& key, Producer produce, bool diskCache);
+ void upload(const std::string& key, const Image& image);
+ void evict();
+
+ std::unordered_map<std::string, Entry> entries_;
+ std::deque<std::pair<std::string, Producer>> queue_; // newest first: what is on screen now
+ struct Job {
+ std::string key;
+ std::future<Result> result;
+ };
+ std::vector<Job> jobs_;
+ std::deque<std::pair<std::string, Result>> renders_;
+ std::vector<std::future<void>> writes_;
+ std::string cacheDir_;
+ uint64_t frame_ = 0;
+ struct Stat {
+ uint64_t size = 0;
+ int64_t mtime = 0;
+ double at = -1e9;
+ bool exists = false;
+ };
+ std::unordered_map<std::string, Stat> stats_; // file stats, refreshed every 2 s
};
} // namespace sf
diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cpp
index 8c2e8ecb..16053e04 100644
--- a/src/app/UiTest.cpp
+++ b/src/app/UiTest.cpp
@@ -12,11 +12,12 @@
// hold MODS ctrl / shift / alt / ctrl+shift ... or none (for strokes and drags)
// stroke U0 V0 U1 V1 [S] brush stroke across the model (fractions of its on-screen bounds)
// drag X0 Y0 X1 Y1 [S] left-drag in window fractions (rectangle hide, sliders...)
+// drag_item LABEL DX DY [S] left-drag from the item by DX DY pixels (scrubbing, dragging a tile out)
// orbit DX DY right-drag on the background, in pixels
// run COMMANDS sculptforge-cli commands, e.g. run new_sphere subdivisions=4
// drop FILE as if FILE were dropped onto the window (relative to the script's folder)
// env NAME VALUE set an environment variable; $SCRIPT_DIR is the script's folder
-// wait SECONDS / wait_idle [TIMEOUT] (AI requests and background jobs) / wait_for LABEL [TIMEOUT]
+// wait SECONDS / wait_idle [TIMEOUT] (AI requests, thumbnails and other background jobs) / wait_for LABEL [TIMEOUT]
// expect LABEL / expect_not LABEL
// expect_text TEXT / expect_no_text TEXT any text drawn this frame contains TEXT
// expect_status TEXT the status bar message contains TEXT
@@ -426,6 +427,31 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& e
return false;
});
wait(0.1f);
+ } else if (verb == "drag_item") {
+ if (!need(3)) return false;
+ const std::string label = w[1];
+ const float dx = num(2, 0), dy = num(3, 0), seconds = num(4, 0.4f);
+ auto from = std::make_shared<ImVec2>();
+ steps_.push_back([this, line, label, from](float t) {
+ if (findItem(label, *from)) {
+ mouseMotion(from->x, from->y);
+ return true;
+ }
+ if (t > 3.0f) fail(line, notFound(label));
+ return t > 3.0f;
+ });
+ steps_.push_back([this, from, dx, dy, seconds](float t) {
+ if (t == 0.0f) return false; // a frame of hover first
+ if (!buttonDown_ && t < seconds) mouseButton(true, SDL_BUTTON_LEFT);
+ const float u = std::min(t / seconds, 1.0f);
+ mouseMotion(from->x + dx * u, from->y + dy * u);
+ if (t >= seconds) {
+ mouseButton(false, SDL_BUTTON_LEFT);
+ return true;
+ }
+ return false;
+ });
+ wait(0.1f);
} else if (verb == "orbit") {
if (!need(2)) return false;
orbit(num(1, 0), num(2, 0), 0.4f);
@@ -467,7 +493,8 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& e
const float timeout = num(1, 120.0f);
steps_.push_back([this, line, timeout](float t) {
const bool idle = !busy(app_.pendingBrush_) && !busy(app_.pendingGenerator_) && !busy(app_.pendingModels_) &&
- !busy(app_.pendingUnreal_) && !busy(app_.pendingComfyCheck_) && !app_.galleryBusy();
+ !busy(app_.pendingUnreal_) && !busy(app_.pendingComfyCheck_) && !app_.galleryBusy() &&
+ !app_.thumbs_.busy() && !app_.libraryScanner_.busy();
if (idle) return true;
SDL_Delay(10); // real work runs in real time
if (t > timeout) fail(line, "still busy after " + number(timeout) + " s");
diff --git a/src/core/Project.cpp b/src/core/Project.cpp
index 3f677a04..9213d979 100644
--- a/src/core/Project.cpp
+++ b/src/core/Project.cpp
@@ -9,6 +9,7 @@
#include <cctype>
#include <cstring>
#include <filesystem>
+#include <fstream>
#include <map>
#include <system_error>
@@ -22,6 +23,12 @@ namespace {
constexpr const char* kFormatName = "SculptForge project";
constexpr const char* kManifestName = "manifest.json";
+constexpr const char* kThumbnailName = "thumbnail.png";
+
+ProjectThumbnailProvider& thumbnailProvider() {
+ static ProjectThumbnailProvider provider;
+ return provider;
+}
// Top-level manifest keys owned by the core (mesh, layers and active_layer are
// version 1); every other key belongs to
// Document::projectSettings (camera, render, brush, symmetry, ...).
@@ -297,6 +304,13 @@ bool saveProject(const std::string& path, const Document& doc, std::string& erro
const std::string text = manifest.dump(true);
w.entries.insert(w.entries.begin(), ZipEntry{kManifestName, std::vector<uint8_t>(text.begin(), text.end())});
+ // The preview goes second, so loadProjectThumbnail finds it after reading two local headers.
+ if (const ProjectThumbnailProvider& provider = thumbnailProvider()) {
+ Image thumb;
+ std::vector<uint8_t> png;
+ if (provider(doc, thumb) && !thumb.empty() && thumb.encodePng(png))
+ w.entries.insert(w.entries.begin() + 1, ZipEntry{kThumbnailName, std::move(png)});
+ }
// Write next to the target and rename, so a failed save never destroys the previous file.
const std::string tmp = path + ".tmp";
@@ -434,6 +448,36 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {
return true;
}
+void setProjectThumbnailProvider(ProjectThumbnailProvider provider) { thumbnailProvider() = std::move(provider); }
+
+bool loadProjectThumbnail(const std::string& path, Image& out, std::string& error) {
+ std::ifstream f(fsPath(path), std::ios::binary);
+ if (!f) {
+ error = "Cannot open " + path;
+ return false;
+ }
+ // Walk the local file headers from the start: the thumbnail is the second entry when present,
+ // so this reads a few hundred bytes plus the PNG instead of the whole project.
+ for (int entry = 0; entry < 4; ++entry) {
+ uint8_t h[30];
+ if (!f.read(reinterpret_cast<char*>(h), sizeof h) || get32(h) != 0x04034B50) break;
+ const uint32_t method = uint32_t(h[8]) | uint32_t(h[9]) << 8;
+ const uint32_t size = get32(h + 18);
+ const size_t nameLen = size_t(h[26]) | size_t(h[27]) << 8, extraLen = size_t(h[28]) | size_t(h[29]) << 8;
+ std::string name(nameLen, '\0');
+ if (!f.read(name.data(), std::streamsize(nameLen))) break;
+ f.seekg(std::streamoff(extraLen), std::ios::cur);
+ if (name == kThumbnailName && method == 0) {
+ std::vector<uint8_t> png(size);
+ if (!f.read(reinterpret_cast<char*>(png.data()), std::streamsize(size))) break;
+ return Image::decode(png.data(), png.size(), out, error);
+ }
+ f.seekg(std::streamoff(size), std::ios::cur);
+ }
+ error = path + " has no thumbnail";
+ return false;
+}
+
CommandResult openProjectCommand(Document& doc, const std::string& path) {
std::string err;
if (!loadProject(path, doc, err)) return {false, err};
diff --git a/src/core/Project.h b/src/core/Project.h
index ed506cc6..2e13a26a 100644
--- a/src/core/Project.h
+++ b/src/core/Project.h
@@ -12,6 +12,7 @@
#include "core/Commands.h"
#include "core/Document.h"
+#include "core/Image.h"
#include <functional>
#include <string>
@@ -34,6 +35,18 @@ bool saveProject(const std::string& path, const Document& doc, std::string& erro
// Restores the active SubTool, sets doc.path, gives every SubTool an empty
// edit history and marks the document clean.
bool loadProject(const std::string& path, Document& doc, std::string& error);
+// --- Thumbnails: a small PNG preview ("thumbnail.png") stored right after the manifest, so the
+// LightBox can show a project without loading it. Optional: older projects have none.
+
+constexpr int kProjectThumbnailSize = 256;
+// Called by saveProject on the saving thread to render the preview (the app renders the current
+// view; the CLI sets none). Returning false or an empty image saves no thumbnail.
+using ProjectThumbnailProvider = std::function<bool(const Document& doc, Image& out)>;
+void setProjectThumbnailProvider(ProjectThumbnailProvider provider);
+// Reads only the thumbnail of the project at `path` (seeks past the other entries). False if the
+// file is not a project or has no thumbnail; `error` says which.
+bool loadProjectThumbnail(const std::string& path, Image& out, std::string& error);
+
// loadProject wrapped as a command result (open_project, and `open` for .sfproj paths).
CommandResult openProjectCommand(Document& doc, const std::string& path);
diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cpp
index cbca892b..d4922e28 100644
--- a/src/render/Renderer.cpp
+++ b/src/render/Renderer.cpp
@@ -684,7 +684,8 @@ void Renderer::endCapture(std::vector<uint8_t>& rgba) {
void Renderer::draw(const Camera& camera, int fbWidth, int fbHeight, const RenderSettings& settings) {
gl::Viewport(0, 0, fbWidth, fbHeight);
- gl::ClearColor(0.1f, 0.1f, 0.11f, 1.0f);
+ if (thumbnailPass_) gl::ClearColor(0.0f, 0.0f, 0.0f, 0.0f);
+ else gl::ClearColor(0.1f, 0.1f, 0.11f, 1.0f);
gl::Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
gl::Enable(GL_MULTISAMPLE);
@@ -692,7 +693,7 @@ void Renderer::draw(const Camera& camera, int fbWidth, int fbHeight, const Rende
gl::Disable(GL_DEPTH_TEST);
gl::UseProgram(bgProgram_);
gl::BindVertexArray(emptyVao_);
- gl::DrawArrays(GL_TRIANGLES, 0, 3);
+ if (!thumbnailPass_) gl::DrawArrays(GL_TRIANGLES, 0, 3);
glm::mat4 view = camera.view(), proj = camera.projection();
gl::Enable(GL_DEPTH_TEST);
@@ -773,4 +774,38 @@ void Renderer::drawSlot(const MeshSlot& s, bool active, const RenderSettings& se
gl::DrawElements(GL_TRIANGLES, s.indexCount, GL_UNSIGNED_INT, nullptr);
}
+// ---------------------------------------------------------------------------
+// Thumbnails (LightBox / pickers)
+// ---------------------------------------------------------------------------
+
+bool Renderer::renderMeshThumbnail(Mesh& mesh, const Camera& camera, int size, const RenderSettings& settings,
+ std::vector<uint8_t>& rgba, std::string& error) {
+ constexpr GLenum kFramebufferBinding = 0x8CA6, kViewport = 0x0BA2;
+ GLint fbo = 0, viewport[4] = {};
+ gl::GetIntegerv(kFramebufferBinding, &fbo);
+ gl::GetIntegerv(kViewport, viewport);
+
+ // A scratch slot outside the SubTool id range; the scene's draw list is put back afterwards.
+ constexpr uint32_t kThumbnailSlot = 0xFFFFFFF0u;
+ mesh.topologyDirty = true;
+ sync(slot(kThumbnailSlot), mesh);
+ std::vector<DrawItem> scene;
+ scene.swap(drawList_);
+ drawList_.push_back({kThumbnailSlot, true});
+ thumbnailPass_ = true;
+ const bool ok = renderToImage(camera, size, size, settings, rgba, error);
+ thumbnailPass_ = false;
+ drawList_.swap(scene);
+ for (size_t i = 0; i < slots_.size(); ++i)
+ if (slots_[i].id == kThumbnailSlot) {
+ freeSlot(slots_[i]);
+ slots_.erase(slots_.begin() + std::ptrdiff_t(i));
+ break;
+ }
+
+ gl::BindFramebuffer(GL_FRAMEBUFFER, GLuint(fbo));
+ gl::Viewport(viewport[0], viewport[1], viewport[2], viewport[3]);
+ return ok;
+}
+
} // namespace sf
diff --git a/src/render/Renderer.h b/src/render/Renderer.h
index a82d21d3..8d2b5f6d 100644
--- a/src/render/Renderer.h
+++ b/src/render/Renderer.h
@@ -66,6 +66,12 @@ public:
// Texture of built-in matcap `index` (sRGB RGBA8, rows bottom-up) for UI previews; 0 if none.
GLuint matcapTexture(int index) const;
+ // --- Thumbnails (LightBox / pickers) ---
+ // Renders `mesh` alone (not the synced scene, which is left as it was) into a `size` x `size`
+ // top-down RGBA8 image with a transparent background. Keeps the caller's framebuffer and viewport.
+ bool renderMeshThumbnail(Mesh& mesh, const Camera& camera, int size, const RenderSettings& settings,
+ std::vector<uint8_t>& rgba, std::string& error);
+
private:
void drawSplats(const glm::mat4& view, const glm::mat4& proj, int fbWidth, int fbHeight, float opacity);
@@ -80,6 +86,7 @@ private:
GLuint captureFbo_[2] = {}, captureRb_[3] = {};
int captureW_ = 0, captureH_ = 0;
GLuint emptyVao_ = 0;
+ bool thumbnailPass_ = false; // draw(): transparent background, no gradient (renderMeshThumbnail)
// The GPU copy of one mesh (one SubTool).
struct MeshSlot {
uint32_t id = 0;
diff --git a/tests/test_lightbox.cpp b/tests/test_lightbox.cpp
new file mode 100644
index 00000000..8269fc83
--- /dev/null
+++ b/tests/test_lightbox.cpp
@@ -0,0 +1,229 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// LightBox library logic: thumbnail cache keys, project thumbnails in .sfproj,
+// folder listing, QuickSave files and the brush pop-up's letter keys.
+#include "TestHarness.h"
+
+#include "app/AssetLibrary.h"
+#include "core/Primitives.h"
+#include "core/Project.h"
+
+#include <chrono>
+#include <filesystem>
+#include <fstream>
+
+using namespace sf;
+
+namespace {
+
+namespace fs = std::filesystem;
+
+void touch(const fs::path& p, const std::string& text = "x") { std::ofstream(p, std::ios::binary) << text; }
+
+Image gradient(int w, int h) {
+ Image img;
+ img.width = w;
+ img.height = h;
+ img.rgba.resize(size_t(w) * size_t(h) * 4);
+ for (int y = 0; y < h; ++y)
+ for (int x = 0; x < w; ++x) {
+ uint8_t* p = &img.rgba[(size_t(y) * size_t(w) + size_t(x)) * 4];
+ p[0] = uint8_t(x * 255 / std::max(w - 1, 1));
+ p[1] = uint8_t(y * 255 / std::max(h - 1, 1));
+ p[2] = 77;
+ p[3] = 255;
+ }
+ return img;
+}
+
+} // namespace
+
+TEST(thumbnail_cache_keys) {
+ // FNV-1a 64 reference values.
+ CHECK(fnv1a64("") == 0xcbf29ce484222325ull);
+ CHECK(fnv1a64("a") == 0xaf63dc4c8601ec8cull);
+ CHECK(hex64(0xaf63dc4c8601ec8cull) == "af63dc4c8601ec8c");
+
+ const std::string k = fileThumbnailKey("mesh", "/lib/Tools/head.obj", 1234, 1700000000, 192);
+ CHECK(k.size() == 16);
+ CHECK(k == fileThumbnailKey("mesh", "/lib/Tools/head.obj", 1234, 1700000000, 192)); // stable
+ // Anything that changes the picture changes the key.
+ CHECK(k != fileThumbnailKey("mesh", "/lib/Tools/head.obj", 1235, 1700000000, 192)); // rewritten (size)
+ CHECK(k != fileThumbnailKey("mesh", "/lib/Tools/head.obj", 1234, 1700000001, 192)); // rewritten (time)
+ CHECK(k != fileThumbnailKey("mesh", "/lib/Tools/head2.obj", 1234, 1700000000, 192)); // another file
+ CHECK(k != fileThumbnailKey("project", "/lib/Tools/head.obj", 1234, 1700000000, 192)); // another kind
+ CHECK(k != fileThumbnailKey("mesh", "/lib/Tools/head.obj", 1234, 1700000000, 96)); // another size
+ CHECK(k != fileThumbnailKey("mesh", "/lib/Tools/head.obj", 1234, 1700000000, 192, kThumbnailVersion + 1));
+ const std::string path = thumbnailCachePath("/prefs/thumbs", k);
+ CHECK(fs::path(path).filename().string() == k + ".png");
+}
+
+TEST(project_thumbnail_round_trip) {
+ const fs::path dir = fs::path(tempPath("sf_lightbox_thumb"));
+ fs::remove_all(dir);
+ fs::create_directories(dir);
+ Document doc = makeDoc(makeIcosphere(2));
+ const Image picture = gradient(32, 24);
+
+ // With a provider, saving embeds the picture and loadProjectThumbnail reads it back exactly.
+ int calls = 0;
+ setProjectThumbnailProvider([&](const Document& d, Image& out) {
+ ++calls;
+ CHECK(d.mesh.triangleCount() == doc.mesh.triangleCount());
+ out = picture;
+ return true;
+ });
+ const std::string with = (dir / "with.sfproj").string();
+ std::string err;
+ CHECK(saveProject(with, doc, err));
+ CHECK(calls == 1);
+ Image back;
+ CHECK(loadProjectThumbnail(with, back, err));
+ CHECK(back.width == 32 && back.height == 24);
+ CHECK(back.rgba == picture.rgba);
+ // The project itself still loads (the extra entry is ignored).
+ Document loaded;
+ CHECK(loadProject(with, loaded, err));
+ CHECK(loaded.mesh.triangleCount() == doc.mesh.triangleCount());
+
+ // A provider that declines (e.g. not on the UI thread), or none at all (the CLI): no thumbnail.
+ setProjectThumbnailProvider([](const Document&, Image&) { return false; });
+ const std::string declined = (dir / "declined.sfproj").string();
+ CHECK(saveProject(declined, doc, err));
+ CHECK(!loadProjectThumbnail(declined, back, err));
+ setProjectThumbnailProvider(nullptr);
+ const std::string without = (dir / "without.sfproj").string();
+ CHECK(saveProject(without, doc, err));
+ CHECK(!loadProjectThumbnail(without, back, err));
+ CHECK(err.find("no thumbnail") != std::string::npos);
+ CHECK(loadProject(without, loaded, err));
+
+ // Not a project at all.
+ touch(dir / "junk.sfproj", "definitely not a zip");
+ CHECK(!loadProjectThumbnail((dir / "junk.sfproj").string(), back, err));
+ CHECK(!loadProjectThumbnail((dir / "missing.sfproj").string(), back, err));
+ fs::remove_all(dir);
+}
+
+TEST(library_folders_and_listing) {
+ const fs::path root = fs::path(tempPath("sf_lightbox_lib"));
+ fs::remove_all(root);
+ std::string err;
+ CHECK(ensureUserLibrary(root.string(), err));
+ for (const char* sub : {"Projects", "Tools", "Brushes", "Alphas", "Images", "Splats", "QuickSave"})
+ CHECK(fs::is_directory(root / sub));
+ CHECK(defaultUserLibrary("/home/a/Documents", "/prefs/") ==
+ (fs::path("/home/a/Documents") / "SculptForge").string());
+ CHECK(!defaultUserLibrary("", "/prefs/").empty());
+
+ // Folders first (by name, any case), then the files the tab takes; hidden files skipped.
+ const fs::path tools = root / "Tools";
+ fs::create_directories(tools / "creatures");
+ fs::create_directories(tools / "Armor");
+ touch(tools / "zebra.obj");
+ touch(tools / "Apple.glb");
+ touch(tools / "notes.txt");
+ touch(tools / ".hidden.obj");
+ const auto list =
+ listFolder(tools.string(), [](const std::string& p) { return fileKindForTab(LibraryTab::Tool, p); });
+ CHECK(list.size() == 4);
+ if (list.size() == 4) {
+ CHECK(list[0].kind == AssetKind::Folder && list[0].name == "Armor");
+ CHECK(list[1].kind == AssetKind::Folder && list[1].name == "creatures");
+ CHECK(list[2].kind == AssetKind::Mesh && list[2].name == "Apple");
+ CHECK(list[3].kind == AssetKind::Mesh && list[3].name == "zebra");
+ CHECK(list[3].size == 1);
+ }
+ CHECK(listFolder((root / "nope").string(), nullptr).empty());
+
+ // Tabs and file kinds.
+ for (int i = 0; i < int(LibraryTab::Count); ++i)
+ CHECK(libraryTabFromId(libraryTabId(LibraryTab(i))) == LibraryTab(i));
+ CHECK(libraryTabFromId("bogus") == LibraryTab::Project);
+ CHECK(fileKindForTab(LibraryTab::Recent, "/a/b.SFPROJ") == AssetKind::Project);
+ CHECK(fileKindForTab(LibraryTab::Splats, "/a/capture.ply") == AssetKind::Splat);
+ CHECK(fileKindForTab(LibraryTab::Tool, "/a/capture.ply") == AssetKind::Mesh);
+ CHECK(fileKindForTab(LibraryTab::Image, "/a/sketch.PNG") == AssetKind::Image);
+ CHECK(fileKindForTab(LibraryTab::Image, "/a/head.obj") == AssetKind::Folder);
+ CHECK(findBuiltinAssets("").empty());
+ fs::remove_all(root);
+}
+
+TEST(quicksave_files) {
+ const fs::path dir = fs::path(tempPath("sf_lightbox_quick"));
+ fs::remove_all(dir);
+ fs::create_directories(dir);
+ const std::string name = quickSaveName(1700000000);
+ CHECK(name.rfind("QuickSave ", 0) == 0);
+ CHECK(name.size() > 10 && name.substr(name.size() - 7) == ".sfproj");
+ CHECK(quickSaveName(1700000000, 2).find(" (2).sfproj") != std::string::npos);
+
+ // Two in the same second get different names.
+ const std::string a = nextQuickSavePath(dir.string(), 1700000000);
+ touch(fs::path(a));
+ const std::string b = nextQuickSavePath(dir.string(), 1700000000);
+ CHECK(a != b);
+ fs::remove(fs::path(a));
+
+ // Only the newest ten QuickSaves stay; other projects in the folder are never touched.
+ const auto now = fs::file_time_type::clock::now();
+ std::vector<fs::path> files;
+ for (int i = 0; i < 12; ++i) {
+ const fs::path p = dir / quickSaveName(1700000000 + i * 60);
+ touch(p);
+ fs::last_write_time(p, now - std::chrono::minutes(12 - i)); // i = 11 is the newest
+ files.push_back(p);
+ }
+ touch(dir / "my project.sfproj");
+ fs::last_write_time(dir / "my project.sfproj", now - std::chrono::hours(5));
+ CHECK(pruneQuickSaves(dir.string()) == 2);
+ CHECK(!fs::exists(files[0]) && !fs::exists(files[1]));
+ for (int i = 2; i < 12; ++i)
+ CHECK(fs::exists(files[size_t(i)]));
+ CHECK(fs::exists(dir / "my project.sfproj"));
+ CHECK(pruneQuickSaves(dir.string()) == 0);
+ fs::remove_all(dir);
+}
+
+TEST(brush_popup_letter_keys) {
+ // The built-in brushes in the pop-up's order, plus a custom one.
+ const std::vector<std::string> names = {"Standard", "Clay", "Smooth", "Move", "Inflate", "Crease",
+ "Flatten", "Pinch", "DamStandard", "ClayBuildup", "SnakeHook", "Trim",
+ "Layer", "Nudge", "Paint", "Clay Buildup"};
+ auto keyOf = [&](const std::vector<std::pair<char, size_t>>& badges, const std::string& brush) {
+ for (const auto& [c, i] : badges)
+ if (names[i] == brush) return c;
+ return '\0';
+ };
+ // B, then S: Standard is T, Smooth M, SnakeHook N (ZBrush's B S T = Standard).
+ bool substring = true;
+ auto kept = filterByTyped(names, "s", &substring);
+ CHECK(!substring);
+ CHECK(kept.size() == 3);
+ auto badges = letterBadges(names, kept, "s");
+ CHECK(keyOf(badges, "Standard") == 't');
+ CHECK(keyOf(badges, "Smooth") == 'm');
+ CHECK(keyOf(badges, "SnakeHook") == 'n');
+ // C: Clay L, Crease R, ClayBuildup A, and the custom "Clay Buildup" the next free letter (Y).
+ kept = filterByTyped(names, "c");
+ badges = letterBadges(names, kept, "c");
+ CHECK(kept.size() == 4);
+ CHECK(keyOf(badges, "Clay") == 'l');
+ CHECK(keyOf(badges, "Crease") == 'r');
+ CHECK(keyOf(badges, "ClayBuildup") == 'a');
+ CHECK(keyOf(badges, "Clay Buildup") == 'y');
+ // Every key is unique.
+ for (size_t i = 0; i < badges.size(); ++i)
+ for (size_t j = i + 1; j < badges.size(); ++j)
+ CHECK(badges[i].first != badges[j].first);
+ // Nothing starts with "hook": fall back to names containing it, without keys.
+ kept = filterByTyped(names, "hook", &substring);
+ CHECK(substring);
+ CHECK(kept.size() == 1 && names[kept[0]] == "SnakeHook");
+ CHECK(letterBadges(names, kept, "hook").empty());
+ // Nothing typed: everything, no keys.
+ CHECK(filterByTyped(names, "").size() == names.size());
+ CHECK(letterBadges(names, filterByTyped(names, ""), "").empty());
+ CHECK(typedName("Clay Buildup!") == "claybuildup");
+}
diff --git a/tests/ui/lightbox.sfui b/tests/ui/lightbox.sfui
new file mode 100644
index 00000000..b57411a0
--- /dev/null
+++ b/tests/ui/lightbox.sfui
@@ -0,0 +1,142 @@
+# LightBox (comma key): tabs, history, loading models, appending SubTools, materials,
+# brushes, QuickSave; then the ZBrush-style pickers: the brush pop-up (B, type letters,
+# press the orange key), the material pop-up (M) and Draw Size / Strength at the cursor (S / I).
+run new_plane resolution=8
+expect_value triangles == 128
+expect_not "LightBox"
+
+key ,
+expect "LightBox"
+click "LightBox/Tool"
+expect "LightBox/Sphere"
+expect "LightBox/Cube"
+expect "LightBox/Built-in"
+wait_idle 60
+shot lightbox-tool
+
+# Double-click a model to open it (replaces the scene), Shift+double-click to append it as a SubTool.
+double_click "LightBox/Sphere"
+expect_value triangles > 128
+expect_value subtools == 1
+hold shift
+double_click "LightBox/Cube"
+hold none
+expect_value subtools == 2
+expect_status Appended SubTool
+
+# A tile dragged out of the strip onto the canvas loads like a double-click (the Cube tile).
+drag_item "LightBox/Cube" 500 300
+expect_status Created cube
+expect_value subtools == 1
+
+# Folders: Built-in holds the bundled demo files; ".." and Back return to the tab's root.
+double_click "LightBox/Built-in"
+wait_idle 30
+expect "LightBox/lion-head"
+expect_not "LightBox/Sphere"
+double_click "LightBox/.."
+expect "LightBox/Sphere"
+double_click "LightBox/User"
+wait_idle 30
+expect "LightBox/.."
+click "LightBox/###Back"
+expect "LightBox/Sphere"
+
+# Materials and brushes load with a double-click too.
+click "LightBox/Material"
+expect "LightBox/Chrome"
+double_click "LightBox/Chrome"
+expect_status Material: Chrome
+click "LightBox/Brush"
+expect "LightBox/DamStandard"
+double_click "LightBox/DamStandard"
+expect_status Brush: DamStandard
+wait_idle 60
+shot lightbox-brush
+
+# Drag sideways to scrub the strip: brushes far to the right come into view.
+expect_not "LightBox/Skin Pores"
+drag_item "LightBox/Inflate" -700 0
+drag_item "LightBox/Nudge" -700 0
+expect "LightBox/Skin Pores"
+expect_status Brush: DamStandard
+
+# More rows, then back through the history to the Material tab.
+click "LightBox/3"
+wait_idle 60
+shot lightbox-3-rows
+click "LightBox/1"
+click "LightBox/###Back"
+expect "LightBox/Chrome"
+
+# QuickSave: a timestamped copy in the library's QuickSave folder, listed newest first.
+click "LightBox/QuickSave"
+expect_text QuickSave keeps timestamped copies
+click "LightBox/###QuickSave now"
+expect_status QuickSaved
+wait 6
+wait_idle 30
+expect_no_text QuickSave keeps timestamped copies
+shot lightbox-quicksave
+
+key ,
+expect_not "LightBox"
+
+# Brush pop-up: B, then a letter narrows the grid and puts an orange key on each brush.
+key b
+expect "Brushes/Standard"
+expect "Brushes/Clay"
+wait_idle 60
+shot picker-brush
+key c
+expect_text [R]
+expect_not "Brushes/Standard"
+shot picker-brush-c
+key r
+expect_not "Brushes/Clay"
+expect_status Brush: Crease
+key b
+key s
+key t
+expect_status Brush: Standard
+# Backspace undoes a letter, Esc closes without picking.
+key b
+key s
+key n
+expect_status Brush: SnakeHook
+key b
+key z
+expect_text No brush matches
+key backspace
+expect "Brushes/Standard"
+# Brushes used lately come first.
+expect_text Recent
+wait_idle 30
+shot picker-brush-recent
+key escape
+expect_not "Brushes/Standard"
+
+# Material pop-up: hovering previews on the model, a click keeps it.
+key m
+expect "Materials/Red Wax"
+hover "Materials/Red Wax"
+shot picker-material-hover
+click "Materials/Bronze"
+expect_status Material: Bronze
+expect_not "Materials/Red Wax"
+
+# Draw Size / Strength at the cursor: type a number and press Enter.
+key s
+expect_text Draw Size 60
+key 1
+key 2
+key 0
+key enter
+key s
+expect_text Draw Size 120
+key escape
+key i
+expect_text Strength 0.50
+shot strength-popup
+key escape
+expect_no_text Strength 0.50