Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Divide no longer crashes around high-valence vertices (#16); a log file with crash notes
islandmedfa221d070daf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fb357786..57e6bfbc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,27 @@ All notable changes to SculptForge are listed here. The format follows## [Unreleased]+### Fixed+- Divide crashed on models with a vertex shared by 22 or more triangles (#16), such as a cylinder sent from Blender+ with Triangle Fan caps of 22 sides or more (21 worked) or Blender's UV sphere. The first subdivision level+ works out each vertex's neighbours from the base mesh; around a high-valence base vertex the list was gathered+ with every polygon twice before removing the repeats, which overran its 64 slots (3 x valence) and corrupted+ the stack when the viewport shaded the new level. The repeats are now removed before the list is joined, so+ it never holds more than 2 x valence (implicit adjacency is only used up to valence 32; above that the stored+ adjacency has no limit). Unit tests divide fan cylinders of 3 to 300 sides and UV spheres up to 200 segments,+ through OBJ and through the Blender Bridge, and compare every level's adjacency with a plain rebuild; a UI test+ receives the issue's meshes from the bridge and divides them in the app.++### Added+- A log file, `sculptforge.log` in the user data folder (`%APPDATA%\SculptForge\SculptForge` on Windows,+ `~/Library/Application Support/SculptForge/SculptForge` on macOS, `~/.local/share/SculptForge/SculptForge` on+ Linux), so a crash is never silent: it holds the version, system and GPU, everything SDL_Log reports (the+ Windows build has no console), each command run (written before it runs), and on a crash a note with the+ cause, the last command and, on Linux and macOS, a stack trace. Each start keeps the previous session's log as+ `sculptforge-previous.log` and notes when that session didn't close normally; the restore dialog after a+ crash points to it. **Help > Open log folder** opens the folder; `--log-dir` writes the log elsewhere, and+ `--crash-test segv|abort|throw` crashes on purpose to test the note (ctest `crash_log`).+## [0.9.5] - 2026-10-31The day after launch, people filed ten issues. 0.9.5 answers all of them: ZSpheres for blocking out a base mesh,diff --git a/CMakeLists.txt b/CMakeLists.txtindex 045ea1b2..f6b2d39e 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -204,6 +204,7 @@ if(SCULPTFORGE_BUILD_APP)${CMAKE_CURRENT_BINARY_DIR}/EmbeddedGuide.cppsrc/app/main.cppsrc/app/Bench.cpp+ src/app/CrashLog.cppsrc/app/App.cppsrc/app/Demo.cppsrc/app/UiTest.cpp@@ -535,6 +536,9 @@ if(SCULPTFORGE_BUILD_TESTS)add_test(NAME ui_user_guide_1080 COMMAND sculptforge --ui-test ${CMAKE_CURRENT_SOURCE_DIR}/tests/ui/user_guide.sfui--size 1920x1080 --ui-out ${CMAKE_CURRENT_BINARY_DIR}/ui-shots/user_guide_1080)set_tests_properties(ui_user_guide_1080 PROPERTIES LABELS ui TIMEOUT 300)+ # A crash leaves a note in the log file (#16). Needs no window.+ add_test(NAME crash_log COMMAND ${CMAKE_COMMAND} -DAPP=$<TARGET_FILE:sculptforge>+ -DDIR=${CMAKE_CURRENT_BINARY_DIR}/crash-log-test -P ${CMAKE_CURRENT_SOURCE_DIR}/tests/crash_log.cmake)# Idle, the app draws nothing (#14): --measure-idle fails when it keeps drawing frames.add_test(NAME ui_idle_redraw COMMAND sculptforge --measure-idle 4)set_tests_properties(ui_idle_redraw PROPERTIES LABELS ui TIMEOUT 60 ENVIRONMENT "SF_NO_UPDATE_CHECK=1")diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.mdindex e4a291d5..8ad3f3c2 100644--- a/docs/guide/troubleshooting.md+++ b/docs/guide/troubleshooting.md@@ -22,7 +22,8 @@ found at start-up (for example `OpenGL 4.6 (Core Profile) Mesa 26.1.8 on ...`),- Linux: run `sculptforge` in a terminal.- macOS: run `/Applications/SculptForge.app/Contents/MacOS/SculptForge` in Terminal.-- Windows: the release build has no console window; if it closes straight away, update the driver first.+- Windows: the release build has no console window; if it closes straight away, update the driver first, then+ read the [log file](#the-log-file), which holds the same messages.## First launch warnings on macOS and Windows@@ -179,6 +180,7 @@ SculptForge keeps its settings in one folder per user:| `project.json` | Recent files and the autosave interval || `autosave.sfproj` | The autosaved copy of unsaved work (removed once you save) || `clean_exit` | Marks a normal exit; without it, the autosave is offered for restore |+| `sculptforge.log`, `sculptforge-previous.log` | What this session and the last one did, and what crashed (see [The log file](#the-log-file)) || `console_history.txt` | The console's command history || `recent_actions.txt` | Recently used entries of the command palette || `brushes/` | Your brush library, one `.sfbrush` file per brush |@@ -191,12 +193,30 @@ separate: `Documents/SculptForge` by default, changeable in **Preferences > Ligh> **Tip:** To move settings to another computer, copy `ui.json`, `ai.json` and the `brushes` folder. For a> shared layout, use **Preferences > Config > Save UI...** and **Load UI...** instead.+## The log file++SculptForge writes what it does to `sculptforge.log` in its [settings folder](#where-settings-live). Choose+**Help > Open log folder** to open it:++| System | Log file |+|---|---|+| Windows | `%APPDATA%\SculptForge\SculptForge\sculptforge.log` |+| macOS | `~/Library/Application Support/SculptForge/SculptForge/sculptforge.log` |+| Linux | `~/.local/share/SculptForge/SculptForge/sculptforge.log` |++It holds the version, your system and GPU (the `OpenGL ... on ...` line), warnings and errors, and each command+you ran. If SculptForge crashes, it ends with lines starting `CRASH:` that say what crashed and what was done+last. Every start keeps the previous session's log as `sculptforge-previous.log` beside it, so after a crash+**attach `sculptforge-previous.log` to your report** (the new `sculptforge.log` is the session after it). It holds+no models and no keys, only command names and messages, which may include file names.+## Recovering work after a crashSculptForge autosaves unsaved work every 5 minutes by default (**Preferences > Autosave**, 0 turns it off).After a crash, the next start asks "SculptForge did not close normally last time. Restore the autosavedwork?". **Restore** opens it as unsaved work (save it under a name); **Discard** deletes it. See-[Projects, autosave and QuickSave](projects.md).+[Projects, autosave and QuickSave](projects.md). The dialog also points to the crashed session's+[log file](#the-log-file).## Frequently asked questions@@ -238,7 +258,9 @@ good report includes:3. **Steps to reproduce**: what you did, what you expected and what happened instead.4. **The commands you ran**: open the console (the backtick key, left of <kbd>1</kbd>), click **Copy sessionas script** and paste it into the report. It often reproduces the problem exactly.-5. **A file** if the problem is with a particular model (a small `.sfproj` or the original file), and a+5. **After a crash, the log**: `sculptforge-previous.log` from **Help > Open log folder** (see+ [The log file](#the-log-file)).+6. **A file** if the problem is with a particular model (a small `.sfproj` or the original file), and ascreenshot for display problems.For a security problem, don't open a public issue; follow `SECURITY.md` in the repository instead.diff --git a/docs/guide/whats-new.md b/docs/guide/whats-new.mdindex e462ccdb..11ad9dc1 100644--- a/docs/guide/whats-new.md+++ b/docs/guide/whats-new.md@@ -5,6 +5,16 @@ chapter opens by itself the first time you start a new version; you can always f**Help > What's New**. Every detail is in the[changelog](https://github.com/islandmed/SculptForge/blob/main/CHANGELOG.md).+## Next version++### Fixes++- Divide (<kbd>Ctrl</kbd>+<kbd>D</kbd>) no longer crashes on models with a point where many polygons meet, such+ as a Blender cylinder with Triangle Fan caps of 22 or more sides or a UV sphere's poles.+- SculptForge now keeps a log file, `sculptforge.log`, in its settings folder (**Help > Open log folder**). After+ a crash it says what crashed and what you did last; attach it when you report a problem. See+ [The log file](troubleshooting.md#the-log-file).+## Version 0.9.5### ZSpheresdiff --git a/src/app/App.cpp b/src/app/App.cppindex 5a1a4a8c..9d9e31c2 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -1,6 +1,7 @@// SculptForge - open source digital sculpting// SPDX-License-Identifier: GPL-3.0-or-later#include "app/App.h"+#include "app/CrashLog.h"#include "ai/AiCommands.h"#include "app/Demo.h"@@ -1242,6 +1243,7 @@ void App::runCommand(const std::string& name, const Args& args) {if (doc_.sculptor.strokeActive()) endStroke();if (name == "save_project") storeProjectSettings();flushBrushEdits(); // commands may replace brushes: save edits first, then watch what's there afterwards+ crashlog::action(name); // (failures reach the log through SDL_Log below)CommandResult r = commands_.execute(doc_, name, args);status_ = r.message;lastCommandOk_ = r.ok;diff --git a/src/app/Config.cpp b/src/app/Config.cppindex 30fe32b8..8e3ac8e3 100644--- a/src/app/Config.cpp+++ b/src/app/Config.cpp@@ -8,6 +8,7 @@#include "app/Config.h"#include "app/App.h"+#include "app/CrashLog.h"#include "app/Ui.h"#include "core/Multires.h"#include "core/Script.h"@@ -346,6 +347,16 @@ void App::initActions() {ICON_LC_BOOK_OPEN, nullptr, nullptr, nullptr, "Open the SculptForge website and user guide in your browser.");add("help.report", "Report a problem", "Help", nullptr, [] { SDL_OpenURL("https://github.com/islandmed/SculptForge/issues"); },ICON_LC_CIRCLE_ALERT, nullptr, nullptr, nullptr, "Open the issue tracker in your browser.");+ add("help.log", "Open log folder", "Help", nullptr,+ [this] {+ const std::string url = crashlog::folderUrl();+ if (url.empty()) status_ = "There is no log file (the user data folder couldn't be written).";+ else if (!SDL_OpenURL(url.c_str()))+ status_ = "The log is " + crashlog::path() + " (couldn't open its folder: " + SDL_GetError() + ")";+ },+ ICON_LC_FILE_TEXT, nullptr, nullptr, nullptr,+ "Open the folder with sculptforge.log: what SculptForge did and, after a crash, what crashed. "+ "sculptforge-previous.log beside it is the last session's. Attach both to a problem report.");add("help.feedback", "Fixes & suggestions", "Help", nullptr,[] { SDL_OpenURL("https://github.com/islandmed/SculptForge/issues/new/choose"); }, ICON_LC_MESSAGE_SQUARE_PLUS,nullptr, nullptr, nullptr,diff --git a/src/app/CrashLog.cpp b/src/app/CrashLog.cppnew file mode 100644index 00000000..29b327b4--- /dev/null+++ b/src/app/CrashLog.cpp@@ -0,0 +1,335 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "app/CrashLog.h"++#include <SDL3/SDL.h>++#include <atomic>+#include <cctype>+#include <cerrno>+#include <csignal>+#include <cstdio>+#include <cstring>+#include <ctime>+#include <exception>+#include <filesystem>+#include <fstream>+#include <mutex>+#include <vector>+#include <algorithm>++#if defined(_WIN32)+#define WIN32_LEAN_AND_MEAN+#define NOMINMAX+#include <windows.h>+#include <io.h>+#else+#include <fcntl.h>+#include <signal.h>+#include <unistd.h>+#if __has_include(<execinfo.h>)+#include <execinfo.h>+#define SF_HAVE_BACKTRACE 1+#endif+#endif++namespace sf::crashlog {++namespace {++constexpr const char* kClosed = "SculptForge closed normally.";+constexpr size_t kMaxBytes = 8u << 20; // a runaway log stops growing here (crash notes are still written)++std::mutex g_mutex;+FILE* g_file = nullptr;+int g_fd = -1; // the same file, for the crash handlers (which can't take locks or allocate)+std::string g_path, g_previous;+bool g_previousCrashed = false;+size_t g_bytes = 0;+SDL_LogOutputFunction g_sdlDefault = nullptr;+void* g_sdlDefaultData = nullptr;+// The last command, as a C string the crash handlers can read without allocating.+char g_last[256] = "(none yet)";+std::atomic<bool> g_crashing{false};++std::filesystem::path fsPath(const std::string& utf8) {+ return std::filesystem::path(std::u8string(reinterpret_cast<const char8_t*>(utf8.data()), utf8.size()));+}++std::string timeStamp() {+ const std::time_t t = std::time(nullptr);+ std::tm tm{};+#if defined(_WIN32)+ localtime_s(&tm, &t);+#else+ localtime_r(&t, &tm);+#endif+ char buf[32];+ std::strftime(buf, sizeof buf, "%Y-%m-%d %H:%M:%S", &tm);+ return buf;+}++void writeLocked(const std::string& line) {+ if (!g_file || (g_bytes > kMaxBytes && line.rfind("CRASH", 0) != 0)) return;+ const std::string text = timeStamp() + " " + line + "\n";+ std::fwrite(text.data(), 1, text.size(), g_file);+ std::fflush(g_file);+ g_bytes += text.size();+}++// --- Crash handlers: async-signal-safe writes of fixed text to g_fd ---++void rawWrite(const char* s) {+ if (g_fd < 0 || !s) return;+#if defined(_WIN32)+ _write(g_fd, s, unsigned(std::strlen(s)));+#else+ size_t n = std::strlen(s);+ while (n > 0) {+ const ssize_t w = ::write(g_fd, s, n);+ if (w <= 0) break;+ s += w;+ n -= size_t(w);+ }+#endif+}++[[maybe_unused]] void rawWriteNumber(unsigned long long v, int base) {+ char buf[24];+ int i = sizeof buf - 1;+ buf[i] = 0;+ do {+ buf[--i] = "0123456789abcdef"[v % unsigned(base)];+ v /= unsigned(base);+ } while (v && i > 0);+ if (base == 16) rawWrite("0x");+ rawWrite(buf + i);+}++void crashHeader(const char* what, const char* detail = nullptr) {+ rawWrite("\nCRASH: SculptForge " SCULPTFORGE_VERSION " crashed: ");+ rawWrite(what);+ rawWrite(detail);+ rawWrite("\nCRASH: last thing done: ");+ rawWrite(g_last);+ rawWrite("\n");+}++#if !defined(_WIN32)+void onSignal(int sig) {+ if (!g_crashing.exchange(true)) {+ const char* name = sig == SIGSEGV ? "segmentation fault (SIGSEGV)"+ : sig == SIGABRT ? "aborted (SIGABRT)"+ : sig == SIGFPE ? "arithmetic error (SIGFPE)"+ : sig == SIGILL ? "illegal instruction (SIGILL)"+ : sig == SIGBUS ? "bus error (SIGBUS)"+ : "signal";+ crashHeader(name);+#if defined(SF_HAVE_BACKTRACE)+ void* frames[64];+ const int n = backtrace(frames, 64);+ rawWrite("CRASH: stack:\n");+ if (g_fd >= 0) backtrace_symbols_fd(frames, n, g_fd);+#endif+ }+ std::signal(sig, SIG_DFL); // the system's own handling (core dump, crash reporter) follows+ std::raise(sig);+}+#else+LONG WINAPI onException(EXCEPTION_POINTERS* info) {+ if (!g_crashing.exchange(true)) {+ crashHeader("unhandled exception");+ const EXCEPTION_RECORD* r = info ? info->ExceptionRecord : nullptr;+ if (r) {+ rawWrite("CRASH: code ");+ rawWriteNumber(r->ExceptionCode, 16);+ rawWrite(" at ");+ rawWriteNumber(reinterpret_cast<uintptr_t>(r->ExceptionAddress), 16);+ HMODULE module = nullptr;+ if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,+ reinterpret_cast<LPCWSTR>(r->ExceptionAddress), &module) && module) {+ char name[MAX_PATH] = {};+ GetModuleFileNameA(module, name, MAX_PATH);+ const char* base = std::strrchr(name, '\\');+ rawWrite(" (");+ rawWrite(base ? base + 1 : name);+ rawWrite(" + ");+ rawWriteNumber(reinterpret_cast<uintptr_t>(r->ExceptionAddress) - reinterpret_cast<uintptr_t>(module), 16);+ rawWrite(")");+ }+ rawWrite("\n");+ }+ }+ return EXCEPTION_CONTINUE_SEARCH; // Windows' own crash handling follows+}++void onAbortSignal(int) {+ if (!g_crashing.exchange(true)) crashHeader("aborted (abort() or a failed check)");+ std::signal(SIGABRT, SIG_DFL);+ std::raise(SIGABRT);+}+#endif++void onTerminate() {+ if (!g_crashing.exchange(true)) {+ const char* what = "uncaught exception";+ try {+ if (std::exception_ptr e = std::current_exception()) std::rethrow_exception(e);+ } catch (const std::exception& e) {+ crashHeader("uncaught exception: ", e.what());+ what = nullptr;+ } catch (...) {+ }+ if (what) crashHeader(what);+ }+ std::abort();+}++void SDLCALL onSdlLog(void*, int category, SDL_LogPriority priority, const char* message) {+ if (g_sdlDefault) g_sdlDefault(g_sdlDefaultData, category, priority, message);+ static const char* const names[] = {"", "trace", "verbose", "debug", "info", "warning", "error", "critical"};+ const int p = int(priority);+ std::lock_guard lock(g_mutex);+ writeLocked(p >= 5 && p <= 7 ? std::string(names[p]) + ": " + (message ? message : "") : (message ? message : ""));+}++} // namespace++void start(const std::string& folder) {+ std::lock_guard lock(g_mutex);+ if (g_file) return;+ std::string dir = folder;+ if (dir.empty()) {+ if (char* pref = SDL_GetPrefPath("SculptForge", "SculptForge")) {+ dir = pref;+ SDL_free(pref);+ }+ }+ if (dir.empty()) return;+ if (dir.back() != '/' && dir.back() != '\\') dir += '/';+ g_path = dir + "sculptforge.log";+ g_previous = dir + "sculptforge-previous.log";++ std::error_code ec;+ std::filesystem::create_directories(fsPath(dir), ec);+ // The last session's log: kept beside, and a crash if it didn't end with the closing line.+ if (std::filesystem::exists(fsPath(g_path), ec)) {+ std::ifstream in(fsPath(g_path), std::ios::binary);+ std::string text((std::istreambuf_iterator<char>(in)), {});+ in.close();+ g_previousCrashed = text.find(kClosed) == std::string::npos;+ std::filesystem::remove(fsPath(g_previous), ec);+ std::filesystem::rename(fsPath(g_path), fsPath(g_previous), ec);+ }+#if defined(_WIN32)+ g_file = _wfopen(fsPath(g_path).c_str(), L"wb");+ if (g_file) g_fd = _fileno(g_file);+#else+ g_file = std::fopen(g_path.c_str(), "wb");+ if (g_file) g_fd = fileno(g_file);+#endif+ if (!g_file) {+ g_path.clear();+ return;+ }+ writeLocked(std::string("SculptForge ") + SCULPTFORGE_VERSION + " on " + SDL_GetPlatform() + ", " ++ std::to_string(SDL_GetNumLogicalCPUCores()) + " CPU threads, " + std::to_string(SDL_GetSystemRAM()) ++ " MB RAM, SDL " + std::to_string(SDL_MAJOR_VERSION) + "." + std::to_string(SDL_MINOR_VERSION) + "." ++ std::to_string(SDL_MICRO_VERSION) + " (linked " + std::to_string(SDL_VERSIONNUM_MAJOR(SDL_GetVersion())) ++ "." + std::to_string(SDL_VERSIONNUM_MINOR(SDL_GetVersion())) + "." ++ std::to_string(SDL_VERSIONNUM_MICRO(SDL_GetVersion())) + ")");+ if (g_previousCrashed)+ writeLocked("The last session did not close normally: its log, with the last command it ran, is " + g_previous);++ SDL_GetLogOutputFunction(&g_sdlDefault, &g_sdlDefaultData);+ SDL_SetLogOutputFunction(onSdlLog, nullptr);+ std::set_terminate(onTerminate);+#if defined(_WIN32)+ SetUnhandledExceptionFilter(onException);+ ULONG guarantee = 64 * 1024; // room for the note after a stack overflow+ SetThreadStackGuarantee(&guarantee);+ std::signal(SIGABRT, onAbortSignal);+#if defined(_MSC_VER)+ _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // our note instead of a dialog box+#endif+#else+ // On a stack of their own, so a stack overflow can still write its note.+ static std::vector<char> altStack(std::max<size_t>(64 * 1024, size_t(SIGSTKSZ)));+ stack_t ss{};+ ss.ss_sp = altStack.data();+ ss.ss_size = altStack.size();+ sigaltstack(&ss, nullptr);+ struct sigaction sa{};+ sa.sa_handler = onSignal;+ sa.sa_flags = SA_ONSTACK;+ sigemptyset(&sa.sa_mask);+ for (int sig : {SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS}) sigaction(sig, &sa, nullptr);+#if defined(SF_HAVE_BACKTRACE)+ void* warm[1];+ backtrace(warm, 1); // loads the unwinder now: the first call allocates, which a crash handler must not+#endif+#endif+}++void note(const std::string& line) {+ std::lock_guard lock(g_mutex);+ writeLocked(line);+}++void action(const std::string& what) {+ std::lock_guard lock(g_mutex);+ // Commands that run on every slider step would bury the rest: a repeat of the last one isn't written again.+ static std::string last;+ std::snprintf(g_last, sizeof g_last, "%s", what.c_str());+ if (what == last) return;+ last = what;+ writeLocked(what);+}++void quietSystemCrashDialog() {+#if defined(_WIN32)+ SetErrorMode(SetErrorMode(0) | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);+#endif+}++void stop() {+ std::lock_guard lock(g_mutex);+ if (!g_file) return;+ writeLocked(kClosed);+ SDL_SetLogOutputFunction(g_sdlDefault, g_sdlDefaultData);+ std::fclose(g_file);+ g_file = nullptr;+ g_fd = -1;+}++std::string path() {+ std::lock_guard lock(g_mutex);+ return g_path;+}++std::string folderUrl() {+ std::string p = path();+ if (p.empty()) return {};+ for (char& c : p)+ if (c == '\\') c = '/';+ p.erase(p.find_last_of('/') + 1);+ std::string url = p.rfind('/', 0) == 0 ? "file://" : "file:///";+ const char* hex = "0123456789ABCDEF";+ for (unsigned char c : p) {+ if (std::isalnum(c) || std::strchr("/:-_.~", c)) url += char(c);+ else url += {'%', hex[c >> 4], hex[c & 15]};+ }+ return url;+}++std::string previousPath() {+ std::lock_guard lock(g_mutex);+ return g_previous;+}++bool previousCrashed() {+ std::lock_guard lock(g_mutex);+ return g_previousCrashed;+}++} // namespace sf::crashlogdiff --git a/src/app/CrashLog.h b/src/app/CrashLog.hnew file mode 100644index 00000000..4059a40b--- /dev/null+++ b/src/app/CrashLog.h@@ -0,0 +1,33 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// The log file: sculptforge.log in the user data folder (SDL_GetPrefPath: %APPDATA%\SculptForge\SculptForge on+// Windows, ~/Library/Application Support/SculptForge/SculptForge on macOS, ~/.local/share/SculptForge/SculptForge+// on Linux). It holds what SDL_Log says (the Windows app has no console to say it on), the commands run, and, when+// SculptForge crashes, what crashed and after which command. Each start keeps the last session's log as+// sculptforge-previous.log and notes there if that session ended without closing (a crash no handler can catch,+// such as a stack overrun on Windows, still leaves its last command there). Lines are flushed as written.+#pragma once++#include <string>++namespace sf::crashlog {++// Opens the log in `folder` (empty: the user data folder) and installs the crash handlers. Safe to call once.+void start(const std::string& folder = {});+// A line in the log (with the time).+void note(const std::string& line);+// Something about to be done (a command): logged before it runs, so even a crash no handler sees leaves it as the+// log's last line, and named by a crash note. A repeat of the last one isn't written again.+void action(const std::string& what);+// For --crash-test: no system crash dialog after the note (Windows Error Reporting would wait for a click).+void quietSystemCrashDialog();+// The session ended normally (the next start doesn't call it a crash).+void stop();+std::string path(); // the log file ("" before start or when it couldn't be opened)+std::string previousPath(); // the last session's log+std::string folderUrl(); // file:// URL of the log's folder, for SDL_OpenURL ("" without a log)+// True when the last session ended without stop() (its log said so; see sculptforge-previous.log).+bool previousCrashed();++} // namespace sf::crashlogdiff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex 7ecfd41b..9fa11706 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -385,6 +385,7 @@ void App::drawPalette_Help() {menuAction(*this, "ui.command_palette");menuAction(*this, "help.website");menuAction(*this, "help.report");+ menuAction(*this, "help.log");menuAction(*this, "help.feedback");ImGui::Separator();menuAction(*this, "help.about");diff --git a/src/app/PanelProject.cpp b/src/app/PanelProject.cppindex 129a6ea8..a22040a3 100644--- a/src/app/PanelProject.cpp+++ b/src/app/PanelProject.cpp@@ -6,6 +6,7 @@// Recent and autosave with crash recovery. Prompts only appear in interactive// sessions; --render, --record and demos run straight through.#include "app/App.h"+#include "app/CrashLog.h"#include "core/SplatCapture.h"#include "app/Ui.h"@@ -489,6 +490,11 @@ void App::drawProjectPopups() {if (ImGui::BeginPopupModal(kRestorePopup, nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {ImGui::TextUnformatted("SculptForge did not close normally last time.");ImGui::TextUnformatted("Restore the autosaved work?");+ if (crashlog::previousCrashed()) {+ ImGui::Spacing();+ ImGui::TextDisabled("What happened is in sculptforge-previous.log (Help > Open log folder);");+ ImGui::TextDisabled("please attach it if you report the problem.");+ }ImGui::Spacing();const float w = 110.0f * uiScale_;const std::string autosave = autosavePath(prefDir_);diff --git a/src/app/main.cpp b/src/app/main.cppindex 6b83ed79..1ff48ec6 100644--- a/src/app/main.cpp+++ b/src/app/main.cpp@@ -2,6 +2,7 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "app/App.h"#include "app/Bench.h"+#include "app/CrashLog.h"#include <SDL3/SDL_main.h>@@ -10,6 +11,7 @@#include <cstdio>#include <cstdlib>#include <filesystem>+#include <stdexcept>#include <string>namespace {@@ -46,7 +48,9 @@ void usage() {" --bench-no-project Skip the project save / open (it needs twice the memory)\n"" --bench-view Benchmark only what the viewport costs (uploads, orbit)\n"" --bench-dyntopo Benchmark dynamic topology strokes (e.g. --bench-sizes 0.25,1,4)\n"- " --bench-out FILE Write the benchmark report (Markdown) to FILE");+ " --bench-out FILE Write the benchmark report (Markdown) to FILE\n"+ " --log-dir DIR Write sculptforge.log to DIR instead of the user data folder\n"+ " --crash-test KIND Crash on purpose (segv, abort or throw) to test the crash note in the log");}// UI tests must never read or change the user's real settings, recent files or@@ -77,8 +81,20 @@ void isolateSettings() {} // namespace+// --crash-test: crash the way real bugs do, after the log has started.+[[noreturn]] static void crashOnPurpose(const std::string& kind) {+ sf::crashlog::quietSystemCrashDialog();+ sf::crashlog::action("crash_test " + kind);+ if (kind == "abort") std::abort();+ if (kind == "throw") throw std::runtime_error("crash test");+ volatile int* nowhere = nullptr;+ *nowhere = 1;+ std::abort();+}+int main(int argc, char** argv) {sf::AppOptions options;+ std::string logDir, crashTest;bool sizeGiven = false;sf::BenchCommandLine bench;for (int i = 1; i < argc; ++i) {@@ -104,6 +120,8 @@ int main(int argc, char** argv) {else if (a == "--fullscreen") options.fullscreen = true;else if (a == "--blender") options.blender = true;else if (a == "--ui-out") options.uiOutDir = next();+ else if (a == "--log-dir") logDir = next();+ else if (a == "--crash-test") crashTest = next();else if (a == "--measure-idle") options.measureIdle = std::max(0.5f, float(std::atof(next().c_str())));else if (a == "-h" || a == "--help") {usage();@@ -125,12 +143,16 @@ int main(int argc, char** argv) {options.width *= options.supersample;options.height *= options.supersample;}+ sf::crashlog::start(logDir); // after isolateSettings: a UI test logs into its own folder+ if (!crashTest.empty()) crashOnPurpose(crashTest);sf::App app;if (!app.init(options)) {app.shutdown();+ sf::crashlog::stop();return 1;}int code = app.run();app.shutdown();+ sf::crashlog::stop();return code;}diff --git a/src/core/Mesh.cpp b/src/core/Mesh.cppindex 0a3e3331..5db2d9be 100644--- a/src/core/Mesh.cpp+++ b/src/core/Mesh.cpp@@ -470,7 +470,10 @@ IndexRing Mesh::implicitNeighbors(uint32_t v) const {if (tp.catmullClark && ia.sides) { // one corner per polygon around v, ascendingfor (uint32_t k = ia.cornerOffsets[v]; k < ia.cornerOffsets[v + 1]; ++k) out[n++] = nf + ia.corners[k] / 4;} else if (tp.catmullClark) {- uint32_t* faces = out + n;+ // Each polygon is listed by both its edges at v: gathered apart (up to 2 x valence) and made unique+ // before joining the ring, which then holds valence + polygons <= 2 x valence (#16: gathered after+ // the edge points, a fan centre of 22 triangles needed 66 slots and overran the ring).+ uint32_t faces[IndexRing::kCapacity];uint32_t m = 0;for (uint32_t k = k0; k < k1; ++k) {const glm::uvec2 f = tp.edgeFaces[tp.vertEdges[k]];@@ -478,7 +481,9 @@ IndexRing Mesh::implicitNeighbors(uint32_t v) const {if (f.y != kNone) faces[m++] = nf + f.y;}sortSmall(faces, m);- n += uniqueSmall(faces, m);+ m = uniqueSmall(faces, m);+ std::copy(faces, faces + m, out + n);+ n += m;}} else if (v < nf) {const uint32_t e = v - nv;diff --git a/tests/crash_log.cmake b/tests/crash_log.cmakenew file mode 100644index 00000000..e6613467--- /dev/null+++ b/tests/crash_log.cmake@@ -0,0 +1,27 @@+# A crash leaves a note in sculptforge.log (#16: a crash on Windows left nothing to report). Runs the app with+# --crash-test KIND for each kind of crash, then once normally: each crash's log names the crash and the last+# thing done, and the next start keeps it as sculptforge-previous.log and says the last session didn't close.+# cmake -DAPP=<sculptforge> -DDIR=<scratch folder> -P crash_log.cmake+file(REMOVE_RECURSE "${DIR}")+file(MAKE_DIRECTORY "${DIR}")+foreach(kind segv abort throw)+ execute_process(COMMAND "${APP}" --log-dir "${DIR}" --crash-test ${kind} RESULT_VARIABLE rc OUTPUT_QUIET ERROR_QUIET)+ if(rc EQUAL 0)+ message(FATAL_ERROR "--crash-test ${kind} exited normally")+ endif()+ file(READ "${DIR}/sculptforge.log" log)+ if(NOT log MATCHES "CRASH: SculptForge [^\n]* crashed" OR NOT log MATCHES "CRASH: last thing done: crash_test ${kind}")+ message(FATAL_ERROR "no crash note for ${kind}:\n${log}")+ endif()+ if(kind STREQUAL "throw" AND NOT log MATCHES "uncaught exception: crash test")+ message(FATAL_ERROR "the exception's text is missing:\n${log}")+ endif()+endforeach()+# The next start (another crash test: it needs no window) keeps the crashed session's log and says so.+execute_process(COMMAND "${APP}" --log-dir "${DIR}" --crash-test abort OUTPUT_QUIET ERROR_QUIET)+file(READ "${DIR}/sculptforge.log" log)+file(READ "${DIR}/sculptforge-previous.log" previous)+if(NOT log MATCHES "The last session did not close normally" OR NOT previous MATCHES "crash_test throw")+ message(FATAL_ERROR "the last session's log wasn't kept:\n${log}\n---\n${previous}")+endif()+message(STATUS "crash notes written")diff --git a/tests/test_divide_valence.cpp b/tests/test_divide_valence.cppnew file mode 100644index 00000000..dc1e442b--- /dev/null+++ b/tests/test_divide_valence.cpp@@ -0,0 +1,196 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Divide on meshes with high-valence vertices (#16): Blender's cylinder with Triangle Fan caps (the fan centre has+// one edge per side) and its UV sphere (poles with one edge per segment) crashed Divide from 22 sides up. Built+// here as Blender builds them, through OBJ and through the Blender Bridge (.GoZ + manifest), then divided three+// times; the levels' adjacency must match a plain rebuild and stepping down and up must keep the shape.+#include "TestHarness.h"++#include "core/Commands.h"+#include "core/Multires.h"+#include "core/Primitives.h"+#include "io/BlenderBridge.h"+#include "io/GozIO.h"+#include "io/ObjIO.h"++#include <algorithm>+#include <cmath>+#include <filesystem>+#include <fstream>+#include <sstream>++using namespace sf;+namespace fs = std::filesystem;++namespace {++const CommandRegistry& registry() {+ static CommandRegistry r;+ return r;+}++// Blender's "Add Cylinder": `n` vertices per ring, quad sides, caps as triangle fans around a centre vertex+// (fan = true) or one n-gon each. UVs as Blender lays them out: the sides a strip with a seam, each cap a disc.+std::string cylinderObj(int n, bool fan) {+ std::ostringstream s;+ const double pi = 3.14159265358979323846;+ for (int ring = 0; ring < 2; ++ring)+ for (int i = 0; i < n; ++i)+ s << "v " << std::cos(2 * pi * i / n) << ' ' << (ring ? 1 : -1) << ' ' << std::sin(2 * pi * i / n) << '\n';+ for (int ring = 0; ring < 2; ++ring)+ for (int i = 0; i <= n; ++i) s << "vt " << double(i) / n << ' ' << (ring ? 0.5 : 0.0) << '\n';+ for (int cap = 0; cap < 2; ++cap)+ for (int i = 0; i < n; ++i)+ s << "vt " << 0.25 + cap * 0.5 + 0.2 * std::cos(2 * pi * i / n) << ' ' << 0.75 + 0.2 * std::sin(2 * pi * i / n) << '\n';+ const int capUv = 2 * (n + 1) + 1; // 1-based: bottom cap's first, then the top's+ for (int i = 0; i < n; ++i) {+ const int a = 1 + i, b = 1 + (i + 1) % n, ta = 1 + i, tb = 2 + i;+ s << "f " << a << '/' << ta << ' ' << b << '/' << tb << ' ' << b + n << '/' << tb + n + 1 << ' ' << a + n << '/'+ << ta + n + 1 << '\n';+ }+ auto cv = [&](int cap, int i) { return capUv + cap * n + (i % n); };+ if (fan) {+ s << "v 0 -1 0\nv 0 1 0\nvt 0.25 0.75\nvt 0.75 0.75\n";+ const int bottom = 2 * n + 1, top = 2 * n + 2, cb = capUv + 2 * n, ct = cb + 1;+ for (int i = 0; i < n; ++i) {+ const int a = 1 + i, b = 1 + (i + 1) % n;+ s << "f " << bottom << '/' << cb << ' ' << b << '/' << cv(0, i + 1) << ' ' << a << '/' << cv(0, i) << '\n';+ s << "f " << top << '/' << ct << ' ' << a + n << '/' << cv(1, i) << ' ' << b + n << '/' << cv(1, i + 1) << '\n';+ }+ } else {+ s << 'f';+ for (int i = n - 1; i >= 0; --i) s << ' ' << 1 + i << '/' << cv(0, i);+ s << "\nf";+ for (int i = 0; i < n; ++i) s << ' ' << 1 + i + n << '/' << cv(1, i);+ s << '\n';+ }+ return s.str();+}++// Blender's "Add UV Sphere": `segments` around, `rings` from pole to pole; triangle fans at the poles. UVs as+// Blender's: a grid with a seam, each pole triangle with its own pole UV.+std::string uvSphereObj(int segments, int rings) {+ std::ostringstream s;+ const double pi = 3.14159265358979323846;+ s << "v 0 1 0\n"; // 1: north pole+ for (int r = 1; r < rings; ++r)+ for (int i = 0; i < segments; ++i) {+ const double th = pi * r / rings, ph = 2 * pi * i / segments;+ s << "v " << std::sin(th) * std::cos(ph) << ' ' << std::cos(th) << ' ' << std::sin(th) * std::sin(ph) << '\n';+ }+ s << "v 0 -1 0\n";+ for (int r = 0; r <= rings; ++r)+ for (int i = 0; i <= segments; ++i)+ s << "vt " << (i + (r == 0 || r == rings ? 0.5 : 0.0)) / segments << ' ' << 1.0 - double(r) / rings << '\n';+ const int south = 2 + (rings - 1) * segments;+ auto at = [&](int r, int i) {+ if (r == 0) return 1;+ if (r == rings) return south;+ return 2 + (r - 1) * segments + (i % segments);+ };+ auto uv = [&](int r, int i) { return 1 + r * (segments + 1) + i; };+ auto corner = [&](int r, int i) { return std::to_string(at(r, i)) + '/' + std::to_string(uv(r, i)) + ' '; };+ for (int i = 0; i < segments; ++i)+ for (int r = 0; r < rings; ++r) {+ if (r == 0) s << "f " << corner(0, i) << corner(1, i) << corner(1, i + 1) << '\n';+ else if (r + 1 == rings) s << "f " << corner(r, i) << corner(r + 1, i) << corner(r, i + 1) << '\n';+ else s << "f " << corner(r, i) << corner(r + 1, i) << corner(r + 1, i + 1) << corner(r, i + 1) << '\n';+ }+ return s.str();+}++bool loadObjText(const std::string& text, Mesh& out) {+ const std::string path = tempPath("sf_divide_valence.obj");+ std::ofstream(path, std::ios::binary) << text;+ std::string err;+ const bool ok = loadObj(path, out, err);+ if (!ok) std::printf(" (loadObj: %s)\n", err.c_str());+ return ok;+}++// The level's adjacency (implicit or stored) matches a plain rebuild of the same triangles.+bool adjacencyMatchesRebuild(const Mesh& m) {+ Mesh plain;+ plain.positions = m.positions;+ plain.triangles = m.triangles;+ plain.rebuildTopology();+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {+ const IndexRing a = m.neighbors(v), b = plain.neighbors(v);+ const IndexRing ta = m.vertexTriangles(v), tb = plain.vertexTriangles(v);+ if (!std::equal(a.begin(), a.end(), b.begin(), b.end())) return false;+ if (!std::equal(ta.begin(), ta.end(), tb.begin(), tb.end())) return false;+ }+ return true;+}++// Divides three times (the third only if under the triangle budget), checking each level, then steps down to the+// base and back up.+bool divideThrice(Document& d, const char* what) {+ const std::vector<glm::vec3> base = d.mesh.positions;+ bool ok = true;+ for (int level = 1; level <= 3; ++level) {+ const size_t before = d.mesh.triangleCount();+ const CommandResult r = registry().execute(d, "subdiv_divide");+ if (!r.ok) {+ std::printf(" (%s, divide %d: %s)\n", what, level, r.message.c_str());+ return false;+ }+ ok = ok && d.mesh.triangleCount() >= 2 * before && subdivCurrentLevel(d.mesh) == level;+ ok = ok && adjacencyMatchesRebuild(d.mesh);+ for (const glm::vec3& p : d.mesh.positions) ok = ok && std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.z);+ }+ std::string err;+ ok = ok && subdivSetLevel(d.mesh, 0, err) && d.mesh.positions == base;+ ok = ok && subdivSetLevel(d.mesh, 3, err) && adjacencyMatchesRebuild(d.mesh);+ if (!ok) std::printf(" (%s: wrong result)\n", what);+ return ok;+}++} // namespace++TEST(divide_cylinder_triangle_fan_caps) {+ // 21 sides divided in 0.9.4, 22 crashed; any number must work (and the n-gon caps Blender also offers).+ for (int n : {3, 20, 21, 22, 23, 31, 32, 33, 40, 63, 64, 65, 128, 300}) {+ for (bool fan : {true, false}) {+ Mesh m;+ CHECK(loadObjText(cylinderObj(n, fan), m));+ Document d = makeDoc(std::move(m));+ const std::string what = "cylinder " + std::to_string(n) + (fan ? " fan" : " ngon");+ CHECK(divideThrice(d, what.c_str()));+ }+ }+}++TEST(divide_uv_sphere) {+ for (auto [segments, rings] : {std::pair{32, 16}, std::pair{64, 32}, std::pair{24, 12}, std::pair{200, 8}}) {+ Mesh m;+ CHECK(loadObjText(uvSphereObj(segments, rings), m));+ Document d = makeDoc(std::move(m));+ CHECK(divideThrice(d, ("uv sphere " + std::to_string(segments)).c_str()));+ }+}++TEST(divide_after_blender_bridge) {+ // The issue's path: Blender sends the mesh through the bridge (a .GoZ and a manifest), then Ctrl+D.+ const fs::path root = fs::temp_directory_path() / "sf_divide_bridge";+ fs::remove_all(root);+ const fs::path inbox = root / "to_sculptforge";+ fs::create_directories(inbox);+ std::string err;+ Mesh cylinder, sphere;+ CHECK(loadObjText(cylinderObj(22, true), cylinder));+ CHECK(saveGoz((inbox / "r1_000.GoZ").string(), cylinder, "Cylinder", err));+ CHECK(loadObjText(uvSphereObj(32, 16), sphere));+ CHECK(saveGoz((inbox / "r1_001.GoZ").string(), sphere, "Sphere", err));+ std::ofstream(inbox / "manifest.json") << R"({"format": "sculptforge-bridge", "version": 1, "revision": 1,+ "sender": "blender", "objects": [{"name": "Cylinder", "file": "r1_000.GoZ"},+ {"name": "Sphere", "file": "r1_001.GoZ"}]})";+ Document d = makeDoc(makeCube(2));+ CHECK(registry().execute(d, "blender_receive", {{"folder", root.string()}}).ok);+ CHECK(d.subtoolCount() == 2);+ CHECK(divideThrice(d, "bridge cylinder 22"));+ d.selectSubtool(1);+ CHECK(divideThrice(d, "bridge uv sphere"));+ fs::remove_all(root);+}diff --git a/tests/ui/data/blender/divide/manifest.json b/tests/ui/data/blender/divide/manifest.jsonnew file mode 100644index 00000000..e3be3618--- /dev/null+++ b/tests/ui/data/blender/divide/manifest.json@@ -0,0 +1,11 @@+{+ "format": "sculptforge-bridge",+ "version": 1,+ "revision": 1,+ "sender": "blender",+ "sender_version": "4.2.0",+ "objects": [+ {"name": "Cylinder", "file": "r1_000.GoZ"},+ {"name": "Sphere", "file": "r1_001.GoZ"}+ ]+}diff --git a/tests/ui/data/blender/divide/r1_000.GoZ b/tests/ui/data/blender/divide/r1_000.GoZnew file mode 100644index 00000000..0db902a2Binary files /dev/null and b/tests/ui/data/blender/divide/r1_000.GoZ differdiff --git a/tests/ui/data/blender/divide/r1_001.GoZ b/tests/ui/data/blender/divide/r1_001.GoZnew file mode 100644index 00000000..2b3b0140Binary files /dev/null and b/tests/ui/data/blender/divide/r1_001.GoZ differdiff --git a/tests/ui/divide_blender_fans.sfui b/tests/ui/divide_blender_fans.sfuinew file mode 100644index 00000000..9b8208c6--- /dev/null+++ b/tests/ui/divide_blender_fans.sfui@@ -0,0 +1,46 @@+# Divide on meshes sent from Blender with high-valence vertices (#16): a cylinder with 22-sided Triangle Fan caps+# (21 worked) and the default UV sphere (32 x 16, its poles are fans of 32 triangles) crashed SculptForge 0.9.4 on+# Ctrl+D: the first level's ring around a fan centre overran a fixed buffer while the viewport shaded it. Sent+# through the bridge as the add-on does (tests/ui/data/blender/divide, with Blender's UVs), divided and drawn.+run new_sphere subdivisions=2+env SCULPTFORGE_BLENDER_EXCHANGE sf_ui_blender_divide+copy data/blender/divide sf_ui_blender_divide/to_sculptforge+wait 0.2+expect_status "Received 2 objects from Blender"+expect_value subtools == 2+expect_value active_subtool == 0+remember triangles t0++# The cylinder: three levels, each drawn (the crash was in the viewport's shading after Divide).+key ctrl+d+wait 0.2+expect_value sdiv == 2+key ctrl+d+wait 0.2+key ctrl+d+wait 0.2+expect_value sdiv == 4+expect_value triangles > $t0*60+key f+shot cylinder+# Down to the base and back up.+key shift+d+key shift+d+key shift+d+expect_value sdiv == 1+expect_value triangles == $t0+key d+key d+key d+expect_value sdiv == 4++# The UV sphere.+run subtool_select index=1+expect_value active_subtool == 1+key ctrl+d+wait 0.2+key ctrl+d+wait 0.2+expect_value sdiv == 3+key f+shot spherediff --git a/tests/ui/whats_new.sfui b/tests/ui/whats_new.sfuiindex f11b447f..ae7e8969 100644--- a/tests/ui/whats_new.sfui+++ b/tests/ui/whats_new.sfui@@ -4,10 +4,10 @@ click "Help##palette.help"click "What's New##help.whats_new"expect_value guide_open == 1expect_guide whats-new.md+expect_text "Next version"+expect_text "Open log folder"expect_text "Version 0.9.5"expect_text "ZSpheres"-expect_text "Blender keys"-expect_text "Flat shading"expect_text "Version 0.9.4"expect_text "Version 0.9.3"expect_text "Version 0.9.2"