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
Preferences > Performance: antialiasing, Fast Navigation, multithreading, stroke cost and memory
islandmede0a73c62c999
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 0cc93f49..2c46eb94 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -181,6 +181,7 @@ if(SCULPTFORGE_BUILD_APP)src/app/Gizmo.cppsrc/app/PanelBake.cppsrc/app/PanelRetopo.cpp+ src/app/PanelPerformance.cppsrc/app/PanelGoz.cppsrc/app/PanelProject.cppsrc/app/PanelSubTools.cppdiff --git a/src/app/App.cpp b/src/app/App.cppindex 21ce16b4..e4831e19 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -26,6 +26,7 @@#include <imgui_impl_sdl3.h>#include <algorithm>+#include <chrono>#include <cfloat>#include <cmath>#include <filesystem>@@ -88,20 +89,16 @@ bool App::init(const AppOptions& options) {SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);- SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);- SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);+ // No multisampling in the window: the 3D view antialiases in its own target (Renderer::drawView), so it can+ // draw with fewer samples while a huge scene moves (Preferences > Performance).+ SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);+ SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);const SDL_WindowFlags flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY |(headless ? SDL_WINDOW_HIDDEN : 0) |(options.fullscreen && !headless ? SDL_WINDOW_FULLSCREEN : 0);const int winW = recording ? options.width : 1600, winH = recording ? options.height : 960;window_ = SDL_CreateWindow("SculptForge", winW, winH, flags);- if (!window_) {- // Retry without multisampling for drivers that refuse it.- SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);- SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);- window_ = SDL_CreateWindow("SculptForge", winW, winH, flags);- }if (!window_) {SDL_Log("SDL_CreateWindow failed: %s", SDL_GetError());return false;@@ -359,6 +356,7 @@ int App::runUiTest(int w, int h, int fps) {ImGui::Render();syncScene();+ viewSamples(); // keeps Fast Navigation's view of the camera current (UI tests read view_samples)++frames;const std::string shot = demo_->takeShotRequest();if (shot.empty()) continue;@@ -578,8 +576,10 @@ int App::run() {drawUi();ImGui::Render();+ const auto syncStart = std::chrono::steady_clock::now();syncScene();- renderer_.draw(camera_, fbW, fbH, renderSettings_, canvasViewport(fbW, fbH));+ notePerformanceFrame(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - syncStart).count());+ perf_.samplesUsed = renderer_.drawView(camera_, fbW, fbH, renderSettings_, canvasViewport(fbW, fbH), viewSamples());ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());SDL_GL_SwapWindow(window_);tickProject(dt);@@ -939,6 +939,15 @@ void App::dabAt(float x, float y, float pressure) {void App::endStroke() {strokeMask_ = false;firstDabPending_ = false;+ // Preferences > Performance shows what the stroke cost.+ if (doc_.sculptor.timings.dabs > 0) {+ perf_.lastStroke = doc_.sculptor.timings;+ perf_.lastStrokeSyncMs = perf_.strokeSyncMs;+ perf_.lastStrokeFrames = perf_.strokeFrames;+ }+ doc_.sculptor.timings = {};+ perf_.strokeSyncMs = 0.0;+ perf_.strokeFrames = 0;UndoRecord r = doc_.sculptor.endStroke();finishPaintStroke(r);if (!r.empty()) {diff --git a/src/app/App.h b/src/app/App.hindex 1893de85..9e92a167 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -425,6 +425,25 @@ private:// Cached UV wireframe of the active SubTool for the UV view: segments in 0..1 UV space.std::vector<glm::vec2> uvLines_;uint64_t uvLinesKey_ = 0;+ // Preferences > Performance (PanelPerformance.cpp): antialiasing and fast navigation, multithreading, what the+ // last stroke cost per dab, and memory. viewSamples() picks this frame's 3D view samples.+ void registerPerformanceUiActions();+ void drawPerformanceSection();+ int viewSamples();+ void applyPerformancePrefs();+ void notePerformanceFrame(double syncMs); // after syncScene: upload time, GPU memory warnings+ struct PerfState {+ glm::mat4 lastView{0.0f};+ double lastCameraMove = -1.0; // seconds (SDL ticks)+ bool fastNow = false; // this frame draws without antialiasing (fast navigation)+ int samplesUsed = 0; // what the renderer managed last frame (fewer when out of memory)+ double strokeSyncMs = 0.0; // upload time summed over the open stroke's frames+ int strokeFrames = 0;+ SculptTimings lastStroke; // the last finished stroke+ double lastStrokeSyncMs = 0.0;+ int lastStrokeFrames = 0;+ bool gpuOutOfMemory = false;+ } perf_;// Geometry > QRemesh (quad retopology on a worker thread) and SubTool > Project (ProjectAll); PanelRetopo.cpp.void registerRetopoUiActions();void drawQRemeshContents();diff --git a/src/app/Bench.cpp b/src/app/Bench.cppindex b1e88a16..3b6c051f 100644--- a/src/app/Bench.cpp+++ b/src/app/Bench.cpp@@ -9,11 +9,15 @@#include "render/GL.h"#include "render/Renderer.h"+#include "core/Image.h"+#include <SDL3/SDL.h>#include <chrono>#include <cmath>+#include <algorithm>#include <cstdio>+#include <cstdlib>namespace sf {@@ -33,8 +37,8 @@ int runAppBenchmark(BenchCommandLine cl) {SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);- SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);- SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);+ SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); // as in the app: the view antialiases in its own target+ SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);SDL_Window* window = SDL_CreateWindow("SculptForge benchmark", 1600, 960, SDL_WINDOW_OPENGL | SDL_WINDOW_HIGH_PIXEL_DENSITY);if (!window) {std::fprintf(stderr, "SDL_CreateWindow failed: %s\n", SDL_GetError());@@ -69,7 +73,7 @@ int runAppBenchmark(BenchCommandLine cl) {gl::Finish();return msSince(t);};- gpu.orbitFrameMs = [&](Mesh& m) {+ gpu.orbitFrameMs = [&](Mesh& m, int samples) {int w = 0, h = 0;SDL_GetWindowSizeInPixels(window, &w, &h);Camera camera;@@ -86,11 +90,29 @@ int runAppBenchmark(BenchCommandLine cl) {}SDL_PumpEvents();camera.yaw = float(i) * 6.2831853f / float(frames);- renderer.draw(camera, w, h, settings);+ renderer.drawView(camera, w, h, settings, {}, samples);SDL_GL_SwapWindow(window);}gl::Finish();- return msSince(t) / frames;+ const double ms = msSince(t) / frames;+ // SF_BENCH_SHOT=prefix: one frame as the window shows it, read back, to check the view draws right.+ if (const char* shot = std::getenv("SF_BENCH_SHOT")) {+ renderer.drawView(camera, w, h, settings, {}, samples);+ Image img;+ img.width = w;+ img.height = h;+ img.rgba.resize(size_t(w) * size_t(h) * 4);+ gl::PixelStorei(GL_PACK_ALIGNMENT, 1);+ gl::ReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, img.rgba.data());+ std::vector<uint8_t> flipped(img.rgba.size());+ for (int y = 0; y < h; ++y)+ std::copy_n(img.rgba.data() + size_t(h - 1 - y) * size_t(w) * 4, size_t(w) * 4, flipped.data() + size_t(y) * size_t(w) * 4);+ img.rgba = std::move(flipped);+ for (size_t i = 3; i < img.rgba.size(); i += 4) img.rgba[i] = 255;+ std::string err;+ img.savePng(std::string(shot) + "-" + std::to_string(m.triangleCount()) + "-" + std::to_string(samples) + "x.png", err);+ }+ return ms;};code = runBenchCommandLine(cl, "## With the GPU (sculptforge --bench)\n\n", &gpu);renderer.shutdown();diff --git a/src/app/Config.cpp b/src/app/Config.cppindex 3774b1ef..2b069441 100644--- a/src/app/Config.cpp+++ b/src/app/Config.cpp@@ -47,6 +47,9 @@ Json toJson(const UiPrefs& p) {j.set("turntable", p.turntable);j.set("alphabeticalPalettes", p.alphabeticalPalettes);j.set("tablet", toJson(p.tablet));+ j.set("antialiasing", double(p.antialiasing));+ j.set("fastNavigation", p.fastNavigation);+ j.set("multithreading", p.multithreading);return j;}@@ -65,6 +68,10 @@ void fromJson(const Json& j, UiPrefs& p) {p.turntable = j["turntable"].asBool(p.turntable);p.alphabeticalPalettes = j["alphabeticalPalettes"].asBool(p.alphabeticalPalettes);fromJson(j["tablet"], p.tablet);+ const int aa = int(j["antialiasing"].asNumber(p.antialiasing));+ p.antialiasing = aa >= 8 ? 8 : aa >= 4 ? 4 : aa >= 2 ? 2 : 1;+ p.fastNavigation = j["fastNavigation"].asBool(p.fastNavigation);+ p.multithreading = j["multithreading"].asBool(p.multithreading);}namespace {@@ -333,6 +340,7 @@ void App::initActions() {registerGizmoActions(); // Q W E R: Draw, and the Gizmo 3D's Move, Scale, Rotate (Gizmo.cpp)registerBakeUiActions(); // Tool > Bake (PanelBake.cpp)registerRetopoUiActions(); // Geometry > QRemesh, SubTool > ProjectAll (PanelRetopo.cpp)+ registerPerformanceUiActions(); // Preferences > Performance (PanelPerformance.cpp)// Every command, so the command palette finds anything scriptable.actions_.registerCommands(@@ -399,6 +407,7 @@ bool App::readUiConfig(const std::string& path, std::string& err) {layout_.customize = customize;actions_.overridesFromJson(j["shortcuts"]);fromJson(j["prefs"], uiPrefs_);+ applyPerformancePrefs();return true;}diff --git a/src/app/Config.h b/src/app/Config.hindex e0c71fa6..cfe9b415 100644--- a/src/app/Config.h+++ b/src/app/Config.h@@ -30,6 +30,10 @@ struct UiPrefs {int cameraNotch = 0; // keep the UI out of a laptop's camera notch: 0 automatic, 1 always, 2 neverbool turntable = false; // rotation: false = free, about the screen axes (ZBrush); true = turntable (Y up)TabletSettings tablet; // Preferences > Tablet: pressure curve, eraser, pen buttons+ // Preferences > Performance (PanelPerformance.cpp).+ int antialiasing = 4; // samples per pixel in the 3D view: 1 (off), 2, 4 or 8+ bool fastNavigation = true; // big scenes draw without antialiasing while the view moves+ bool multithreading = true; // brushes, normals and BVH updates on every core (off: one thread)};Json toJson(const UiPrefs& prefs);diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex 9464d1ec..45192bc5 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -283,6 +283,7 @@ void App::drawPalette_Preferences() {if (subpalette("preferences.hotkeys", "Hotkeys")) config::drawHotkeysSection(*this);if (subpalette("preferences.lightbox", "LightBox")) config::drawLightBoxSection(*this);if (subpalette("preferences.tablet", "Tablet")) drawTabletSection();+ if (subpalette("preferences.performance", "Performance")) drawPerformanceSection();if (subpalette("preferences.autosave", "Autosave")) {ImGui::SetNextItemWidth(-1);ImGui::SliderInt("##autosave", &autosaveMinutes_, 0, 60, autosaveMinutes_ ? "Every %d min" : "Autosave off");diff --git a/src/app/PanelPerformance.cpp b/src/app/PanelPerformance.cppnew file mode 100644index 00000000..d02d1c4d--- /dev/null+++ b/src/app/PanelPerformance.cpp@@ -0,0 +1,179 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Preferences > Performance (ZBrush: Preferences > Performance and Mem): how the 3D view draws (Antialiasing,+// Fast Navigation), Multithreading, what the last stroke cost per dab, and the memory the scene holds. The+// numbers come from the same instruments as the benchmark (core/Benchmark.h, docs/performance.md).+#include "app/App.h"+#include "app/Ui.h"++#include "core/Benchmark.h"+#include "core/ThreadPool.h"++#include <chrono>+#include <cstdio>++namespace sf {++namespace {++constexpr const char* kPath = "Preferences > Performance";+// Scenes this big draw without antialiasing while the view moves (with Fast Navigation on).+constexpr size_t kFastNavigationTriangles = 10'000'000;++std::string megabytes(size_t bytes) {+ char buf[32];+ if (bytes >= size_t(1) << 30) std::snprintf(buf, sizeof buf, "%.2f GB", double(bytes) / double(size_t(1) << 30));+ else std::snprintf(buf, sizeof buf, "%.0f MB", double(bytes) / double(size_t(1) << 20));+ return buf;+}++void dimText(const std::string& text) {+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));+ ImGui::TextWrapped("%s", text.c_str());+ ImGui::PopStyleColor();+}++} // namespace++void App::registerPerformanceUiActions() {+ auto add = [this](std::string id, std::string label, std::function<void()> run, std::function<bool()> checked,+ std::string description) {+ Action a;+ a.id = std::move(id);+ a.label = std::move(label);+ a.palette = kPath;+ a.run = std::move(run);+ a.checked = std::move(checked);+ a.description = std::move(description);+ actions_.add(std::move(a));+ };+ for (int samples : {1, 2, 4, 8}) {+ const std::string name = samples == 1 ? "Off" : std::to_string(samples) + "x";+ add("perf.aa_" + std::to_string(samples), "AA " + name,+ [this, samples, name] {+ uiPrefs_.antialiasing = samples;+ status_ = "Antialiasing " + name + (samples > 1 && uiPrefs_.fastNavigation ? " (off while big scenes move)" : "");+ },+ [this, samples] { return uiPrefs_.antialiasing == samples; },+ samples == 1 ? "Draw the 3D view without antialiasing: fastest, with jagged edges."+ : "Smooth the 3D view's edges with " + std::to_string(samples) ++ " samples per pixel (multisampling). More samples look smoother and cost more on huge "+ "meshes. If the GPU can't make room for them, the view uses fewer.");+ }+ add("perf.fast_navigation", "Fast Navigation",+ [this] {+ uiPrefs_.fastNavigation = !uiPrefs_.fastNavigation;+ status_ = uiPrefs_.fastNavigation ? "Fast Navigation on" : "Fast Navigation off";+ },+ [this] { return uiPrefs_.fastNavigation; },+ "While you rotate, pan or zoom a scene of 10 million triangles or more, draw it without antialiasing, so the "+ "view keeps up; it is smooth again as soon as the view stops.");+ add("perf.multithreading", "Multithreading",+ [this] {+ uiPrefs_.multithreading = ThreadPool::shared().serial();+ applyPerformancePrefs();+ status_ = uiPrefs_.multithreading ? "Multithreading on (" + std::to_string(ThreadPool::shared().threads()) + " threads)"+ : "Multithreading off (one thread)";+ },+ [] { return !ThreadPool::shared().serial(); },+ "Run brushes, normal and BVH updates and project saving on every core. Turn it off only to compare speeds "+ "or rule it out when troubleshooting: the results are the same either way.");+}++void App::applyPerformancePrefs() { ThreadPool::shared().setSerial(!uiPrefs_.multithreading); }++int App::viewSamples() {+ const int aa = uiPrefs_.antialiasing;+ // The view moved this frame or a moment ago (orbit, pan, zoom, snapping, framing), or is being dragged.+ const glm::mat4 view = camera_.view();+ const double now = double(SDL_GetTicks()) / 1000.0;+ if (view != perf_.lastView) {+ perf_.lastView = view;+ perf_.lastCameraMove = now;+ }+ const bool moving = drag_ == Drag::Orbit || drag_ == Drag::Pan || drag_ == Drag::Zoom || now - perf_.lastCameraMove < 0.25;+ size_t triangles = 0;+ for (int i = 0; i < doc_.subtoolCount(); ++i)+ if (doc_.subtools[size_t(i)].visible) triangles += doc_.subtoolMesh(i).triangleCount();+ perf_.fastNow = aa > 1 && uiPrefs_.fastNavigation && moving && triangles >= kFastNavigationTriangles;+ return perf_.fastNow ? 1 : aa;+}++void App::notePerformanceFrame(double syncMs) {+ if (doc_.sculptor.strokeActive()) {+ perf_.strokeSyncMs += syncMs;+ ++perf_.strokeFrames;+ }+ // A SubTool too big for the GPU's memory isn't drawn: say so once.+ bool oom = false;+ for (const SubTool& s : doc_.subtools) oom = oom || (s.visible && renderer_.outOfMemory(s.id));+ if (oom && !perf_.gpuOutOfMemory)+ status_ = "Not enough GPU memory to show every SubTool: hide some, or step down a subdivision level "+ "(Preferences > Performance)";+ perf_.gpuOutOfMemory = oom;+}++void App::drawPerformanceSection() {+ // --- The 3D view ---+ ImGui::TextUnformatted("Antialiasing");+ ui::HelpText("Antialiasing", nullptr,+ "Samples per pixel in the 3D view: more smooths edges, fewer is faster on huge meshes.", kPath);+ ui::Segmented(*this, {"perf.aa_1", "perf.aa_2", "perf.aa_4", "perf.aa_8"});+ bool fast = uiPrefs_.fastNavigation;+ if (ImGui::Checkbox("Fast Navigation", &fast)) actions_.find("perf.fast_navigation")->run();+ ui::HelpAction(*this, "perf.fast_navigation");+ if (perf_.samplesUsed > 0 && perf_.samplesUsed < uiPrefs_.antialiasing && !perf_.fastNow)+ dimText("The GPU had no room for " + std::to_string(uiPrefs_.antialiasing) + "x: using " ++ (perf_.samplesUsed == 1 ? std::string("none") : std::to_string(perf_.samplesUsed) + "x") + ".");++ // --- Threads ---+ bool threads = !ThreadPool::shared().serial();+ if (ImGui::Checkbox(("Multithreading (" + std::to_string(ThreadPool::shared().threads()) + " threads)##perf.mt").c_str(), &threads))+ actions_.find("perf.multithreading")->run();+ ui::HelpAction(*this, "perf.multithreading");++ // --- The last stroke ---+ ImGui::Spacing();+ ImGui::TextUnformatted("Last stroke");+ ui::HelpText("Last stroke", nullptr,+ "What the last brush stroke cost, per dab (one step of the brush, all symmetry sides): finding and "+ "moving the vertices, updating their normals and the BVH (the picking structure), and sending the "+ "change to the GPU (per frame). Under 16 ms keeps up with a 60 Hz display.",+ kPath);+ const SculptTimings& t = perf_.lastStroke;+ if (t.dabs == 0) {+ dimText("Sculpt a stroke to see what it costs.");+ } else {+ const double d = double(t.dabs);+ const double upload = perf_.lastStrokeFrames ? perf_.lastStrokeSyncMs / perf_.lastStrokeFrames : 0.0;+ char buf[256];+ std::snprintf(buf, sizeof buf, "%llu dabs, %.0fk vertices each\nBrush %.2f ms Normals %.2f ms BVH %.2f ms\nGPU upload %.2f ms per frame",+ static_cast<unsigned long long>(t.dabs), double(t.vertices) / d / 1000.0, t.kernelMs / d,+ t.normalsMs / d, t.bvhMs / d, upload);+ ImGui::TextUnformatted(buf);+ ImGui::LogText("%s", buf);+ }++ // --- Memory ---+ ImGui::Spacing();+ ImGui::TextUnformatted("Memory");+ ui::HelpText("Memory", nullptr,+ "What the scene holds: the meshes with their topology, the BVHs, the subdivision levels kept for "+ "stepping between them, the undo history (Edit keeps up to 1 GB, dropping the oldest steps) and the "+ "GPU buffers of the visible SubTools.",+ kPath);+ const MemoryUse m = documentMemory(doc_);+ const std::string mem = "Meshes " + megabytes(m.mesh) + " BVH " + megabytes(m.bvh) + "\nSubdivision levels " ++ megabytes(m.levels) + "\nUndo " + megabytes(m.undo) + " of " + megabytes(doc_.undo.byteBudget) ++ "\nGPU buffers about " + megabytes(m.gpu);+ ImGui::TextUnformatted(mem.c_str());+ ImGui::LogText("%s", mem.c_str());+ if (perf_.gpuOutOfMemory) {+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(ui::color::danger));+ ImGui::TextWrapped("Not enough GPU memory to show every SubTool: hide some or step down a subdivision level.");+ ImGui::PopStyleColor();+ }+}++} // namespace sfdiff --git a/src/app/UiTest.cpp b/src/app/UiTest.cppindex 068fed08..e135b726 100644--- a/src/app/UiTest.cpp+++ b/src/app/UiTest.cpp@@ -64,6 +64,9 @@// auto_uv_running, qremesh_running (QRemesh working in the background),// quads (quad pairs in the active SubTool), quad_percent (quads among its polygons)// sdiv (the current subdivision level, 1 = base; 0 without levels), sdiv_levels (0 = none)+// antialiasing (Preferences > Performance: 1, 2, 4, 8), view_samples (what the interactive+// view draws with now: 1 while Fast Navigation moves a big scene), multithreading (1 on),+// last_stroke_dabs (dabs of the last finished stroke)// gizmo_mode (0 Draw, 1 Move, 2 Scale, 3 Rotate), gizmo_hover (handle under the cursor,// 0 = none, in gizmo_drag's order from 1), gizmo_falloff, pivot_x / pivot_y / pivot_z,// center_x / center_y / center_z and size_x / size_y / size_z (active mesh bounds)@@ -101,6 +104,7 @@#include "core/BrushLibrary.h"#include "core/Multires.h"#include "core/Script.h"+#include "core/ThreadPool.h"#include <imgui_internal.h>@@ -234,6 +238,10 @@ double Demo::query(const std::string& name, bool& known) const {if (name == "uvs") return m.hasUvs() ? 1.0 : 0.0;if (name == "sdiv") return subdivLevelCount(m) ? double(subdivCurrentLevel(m) + 1) : 0.0;if (name == "sdiv_levels") return double(subdivLevelCount(m));+ if (name == "antialiasing") return double(app_.uiPrefs_.antialiasing);+ if (name == "view_samples") return double(app_.viewSamples());+ if (name == "multithreading") return ThreadPool::shared().serial() ? 0.0 : 1.0;+ if (name == "last_stroke_dabs") return double(app_.perf_.lastStroke.dabs);if (name == "texture_size") return hasTexture(m) ? double(m.texture->width) : 0.0;if (name == "paint_texture") return paintsTexture(m) ? 1.0 : 0.0;if (name == "texture_layers") return hasTexture(m) ? double(m.texture->layers.size()) : 0.0;diff --git a/src/core/Benchmark.cpp b/src/core/Benchmark.cppindex ff330674..b5d7892f 100644--- a/src/core/Benchmark.cpp+++ b/src/core/Benchmark.cpp@@ -3,6 +3,7 @@#include "core/Benchmark.h"#include "core/BrushRecipe.h"+#include "core/Commands.h"#include "core/Document.h"#include "core/Multires.h"#include "core/Polypaint.h"@@ -26,6 +27,18 @@namespace sf {+namespace {++std::string fmt(const char* f, double v) {+ char buf[64];+ std::snprintf(buf, sizeof buf, f, v);+ return buf;+}++std::string millions(double n) { return n >= 1e6 ? fmt("%.1fM", n / 1e6) : fmt("%.0fk", n / 1e3); }++} // namespace+size_t residentBytes() {#if defined(__linux__)std::ifstream f("/proc/self/statm");@@ -35,6 +48,51 @@ size_t residentBytes() {return 0;}+MemoryUse documentMemory(const Document& doc) {+ MemoryUse u;+ for (int i = 0; i < doc.subtoolCount(); ++i) {+ const bool active = i == doc.activeSubtool;+ const SubTool& st = doc.subtools[size_t(i)];+ const Mesh& m = doc.subtoolMesh(i);+ u.mesh += m.memoryBytes();+ u.bvh += (active ? doc.bvh : st.bvh).memoryBytes();+ u.levels += subdivBytes(m);+ u.undo += (active ? doc.undo : st.undo).undoBytes();+ u.triangles += m.triangleCount();+ u.vertices += m.vertexCount();+ if (st.visible) // positions, normals, curvature (+ colours, mask) per vertex; indices per triangle+ u.gpu += m.vertexCount() * (28 + (m.hasColors() ? 12 : 0) + (m.hasMask() ? 4 : 0)) + m.triangleCount() * 12;+ }+ return u;+}++void registerPerformanceCommands(CommandRegistry& registry) {+ registry.add({"perf_info",+ "Performance information: the threads brushes use, and the memory the scene holds (meshes, BVHs, "+ "subdivision levels, undo history, GPU buffers), per SubTool and in total.",+ {},+ [](Document& doc, const Args&) -> CommandResult {+ auto mb = [](size_t b) { return fmt("%.1f MB", double(b) / 1e6); };+ const MemoryUse u = documentMemory(doc);+ std::string msg = "Threads " + std::to_string(ThreadPool::shared().threads()) ++ (ThreadPool::shared().serial() ? " (multithreading off)" : "") + "; " ++ millions(double(u.triangles)) + " triangles; memory " + mb(u.total()) + " (meshes " ++ mb(u.mesh) + ", BVH " + mb(u.bvh) + ", subdivision levels " + mb(u.levels) ++ ", undo " + mb(u.undo) + "), GPU buffers about " + mb(u.gpu);+ return {true, msg};+ }});+ registry.add({"set_multithreading",+ "Run brushes, normal and BVH updates, project saving and other per-dab work on every core (on, the "+ "default) or on one thread (off: slower, for comparing or troubleshooting). Results are the same.",+ {{"enabled", ParamSpec::Type::Bool, "true = every core, false = one thread.", true}},+ [](Document&, const Args& a) -> CommandResult {+ const bool on = argBool(a, "enabled", true);+ ThreadPool::shared().setSerial(!on);+ return {true, on ? "Multithreading on (" + std::to_string(ThreadPool::shared().threads()) + " threads)"+ : std::string("Multithreading off (one thread)")};+ }});+}+Mesh makeBenchSphere(size_t triangles) {// A cube of r x r quads per side has 12 r^2 triangles; each Divide multiplies that by 4.int levels = 1, res = 1;@@ -150,14 +208,6 @@ StrokeStats runStroke(Document& doc, const BenchBrush& b, int dabs, const BenchGreturn st;}-std::string fmt(const char* f, double v) {- char buf[64];- std::snprintf(buf, sizeof buf, f, v);- return buf;-}--std::string millions(double n) { return n >= 1e6 ? fmt("%.1fM", n / 1e6) : fmt("%.0fk", n / 1e3); }-} // namespacebool parseBenchArg(int argc, char** argv, int& i, BenchCommandLine& cl) {@@ -327,8 +377,11 @@ std::string runBenchmark(const BenchOptions& o, const BenchGpu* gpu) {}if (gpu && gpu->orbitFrameMs) {log(" orbit");- const double f = gpu->orbitFrameMs(m);- md << "| Orbit: frame time | " << fmt("%.1f", f) << " (" << fmt("%.0f", 1000.0 / std::max(f, 1e-3)) << " fps) |\n";+ for (int samples : {4, 1}) {+ const double f = gpu->orbitFrameMs(m, samples);+ md << "| Orbit: frame time, " << (samples == 1 ? "Fast Navigation (no antialiasing)" : "4x antialiasing") << " | "+ << fmt("%.1f", f) << " (" << fmt("%.0f", 1000.0 / std::max(f, 1e-3)) << " fps) |\n";+ }}md << "\n";if (o.partial) o.partial(md.str());diff --git a/src/core/Benchmark.h b/src/core/Benchmark.hindex 0cefc3d0..c607ad2c 100644--- a/src/core/Benchmark.h+++ b/src/core/Benchmark.h@@ -19,11 +19,14 @@namespace sf {+struct Document;+struct BenchGpu {// Uploads what the mesh marked dirty and waits for the GPU; returns milliseconds. First call: everything.std::function<double(Mesh&)> upload;- // Average milliseconds per frame over a turn around the mesh (already uploaded).- std::function<double(Mesh&)> orbitFrameMs;+ // Average milliseconds per frame over a turn around the mesh (already uploaded), drawn with `samples`+ // antialiasing samples as the app's view draws (1 = Fast Navigation while the view moves).+ std::function<double(Mesh&, int samples)> orbitFrameMs;std::string description; // GPU / driver, for the report};@@ -59,4 +62,20 @@ Mesh makeBenchSphere(size_t triangles);// Resident memory of this process in bytes (0 where unknown).size_t residentBytes();+// What the scene holds in memory, summed over SubTools (Preferences > Performance, perf_info).+struct MemoryUse {+ size_t mesh = 0; // meshes with topology (Mesh::memoryBytes)+ size_t bvh = 0; // acceleration structures+ size_t levels = 0; // subdivision level stacks (subdivBytes)+ size_t undo = 0; // undo history (UndoStack::undoBytes)+ size_t gpu = 0; // vertex and index buffers the renderer keeps for the visible SubTools (an estimate)+ size_t triangles = 0, vertices = 0;+ size_t total() const { return mesh + bvh + levels + undo; }+};+MemoryUse documentMemory(const Document& doc);++class CommandRegistry;+// perf_info (threads, memory) and set_multithreading.+void registerPerformanceCommands(CommandRegistry& registry);+} // namespace sfdiff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex 03edd06c..9f9e8f61 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -3,6 +3,7 @@#include "core/Commands.h"#include "core/Bake.h"+#include "core/Benchmark.h"#include "core/BrushAlpha.h"#include "core/BrushLibrary.h"#include "core/Decimate.h"@@ -761,6 +762,7 @@ CommandRegistry::CommandRegistry() {registerSubToolCommands(*this);registerSubdivCommands(*this); // subdiv_* (core/MultiresCommands.cpp)registerTransformCommands(*this); // transform (core/MeshTransform.h)+ registerPerformanceCommands(*this); // perf_info, set_multithreading (core/Benchmark.cpp)registerPaintCommands(*this); // core/Polypaint.cppregisterGozCommands(*this); // goz_import/export/send/receive, export_stl (io/GozCommands.cpp)registerBakeCommands(*this); // bake (core/Bake.cpp)diff --git a/src/render/GL.h b/src/render/GL.hindex cc39f480..71e23b27 100644--- a/src/render/GL.h+++ b/src/render/GL.h@@ -69,6 +69,9 @@ constexpr GLenum GL_DEPTH_COMPONENT24 = 0x81A6;constexpr GLenum GL_CLAMP_TO_EDGE = 0x812F;constexpr GLenum GL_READ_FRAMEBUFFER = 0x8CA8;constexpr GLenum GL_DRAW_FRAMEBUFFER = 0x8CA9;+constexpr GLenum GL_MAX_SAMPLES = 0x8D57;+constexpr GLenum GL_NO_ERROR = 0;+constexpr GLenum GL_OUT_OF_MEMORY = 0x0505;constexpr GLenum GL_FRAMEBUFFER_COMPLETE = 0x8CD5;constexpr GLenum GL_COLOR_ATTACHMENT0 = 0x8CE0;constexpr GLenum GL_DEPTH_ATTACHMENT = 0x8D00;@@ -107,6 +110,7 @@ constexpr GLbitfield GL_COLOR_BUFFER_BIT = 0x4000;X(void, PolygonOffset, GLfloat, GLfloat) \X(const GLubyte*, GetString, GLenum) \X(void, Finish, void) \+ X(GLenum, GetError, void) \X(void, GenBuffers, GLsizei, GLuint*) \X(void, DeleteBuffers, GLsizei, const GLuint*) \X(void, BindBuffer, GLenum, GLuint) \diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cppindex 3531343b..63a7bf86 100644--- a/src/render/Renderer.cpp+++ b/src/render/Renderer.cpp@@ -508,6 +508,11 @@ void Renderer::shutdown() {gl::DeleteBuffers(1, &splatOrder_);gl::DeleteTextures(1, &splatTexture_);gl::DeleteVertexArrays(1, &splatVao_);+ if (viewFbo_) {+ gl::DeleteFramebuffers(1, &viewFbo_);+ gl::DeleteRenderbuffers(2, viewRb_);+ viewFbo_ = 0;+ }}void Renderer::syncSplats(const SplatCloud& c, uint64_t version) {@@ -745,6 +750,12 @@ void Renderer::uploadFaces(MeshSlot& s, const Mesh& mesh, bool wantUvs) {if (wireLines_.capacity() > (size_t(1) << 16)) std::vector<uint32_t>().swap(wireLines_);}+bool Renderer::outOfMemory(uint32_t id) const {+ for (const MeshSlot& s : slots_)+ if (s.id == id) return s.outOfMemory;+ return false;+}+void Renderer::syncScene(const std::vector<SceneMesh>& scene) {// Free the slots of SubTools that are gone (deleted, merged, a new scene).for (size_t i = 0; i < slots_.size();) {@@ -794,6 +805,25 @@ void Renderer::sync(MeshSlot& s, Mesh& mesh, const NormalMapView* normalMap) {if (full) {uploadFaces(s, mesh, wantUvs);s.vertexCapacity = nv;+ // A mesh too big for the GPU's memory isn't drawn (rather than taking the driver down); the next full+ // upload (e.g. after Lower Res or a decimation) tries again.+ s.outOfMemory = false;+ for (int i = 0; i < 16; ++i) {+ const GLenum e = gl::GetError();+ if (e == GL_NO_ERROR) break;+ s.outOfMemory = s.outOfMemory || e == GL_OUT_OF_MEMORY;+ }+ if (s.outOfMemory) {+ for (GLuint b : {s.posBuffer, s.nrmBuffer, s.curvBuffer}) {+ gl::BindBuffer(GL_ARRAY_BUFFER, b);+ gl::BufferData(GL_ARRAY_BUFFER, 0, nullptr, GL_DYNAMIC_DRAW);+ }+ gl::BindVertexArray(s.vao);+ gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, 0, nullptr, GL_STATIC_DRAW);+ gl::BindVertexArray(0);+ s.indexCount = 0;+ s.lineCount = 0;+ }}if (!full && (mesh.facesDirty || wantUvs != s.hasUvs)) uploadFaces(s, mesh, wantUvs);syncTexture(s, mesh);@@ -964,6 +994,62 @@ bool Renderer::renderToImage(const Camera& camera, int width, int height, constreturn ok;}+bool Renderer::viewTarget(int width, int height, int samples) {+ if (viewFbo_ && width == viewW_ && height == viewH_ && samples == viewSamples_) return true;+ if (width == viewW_ && height == viewH_ && samples == viewFailed_) return false; // don't retry every frame+ if (viewFbo_) {+ gl::DeleteFramebuffers(1, &viewFbo_);+ gl::DeleteRenderbuffers(2, viewRb_);+ viewFbo_ = 0;+ }+ for (int i = 0; i < 16 && gl::GetError() != GL_NO_ERROR; ++i) {+ }+ gl::GenFramebuffers(1, &viewFbo_);+ gl::GenRenderbuffers(2, viewRb_);+ gl::BindRenderbuffer(GL_RENDERBUFFER, viewRb_[0]);+ gl::RenderbufferStorageMultisample(GL_RENDERBUFFER, samples, GL_RGBA8, width, height);+ gl::BindRenderbuffer(GL_RENDERBUFFER, viewRb_[1]);+ gl::RenderbufferStorageMultisample(GL_RENDERBUFFER, samples, GL_DEPTH_COMPONENT24, width, height);+ gl::BindFramebuffer(GL_FRAMEBUFFER, viewFbo_);+ gl::FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, viewRb_[0]);+ gl::FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, viewRb_[1]);+ const bool ok = gl::CheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE && gl::GetError() == GL_NO_ERROR;+ gl::BindFramebuffer(GL_FRAMEBUFFER, 0);+ viewW_ = width;+ viewH_ = height;+ if (!ok) {+ gl::DeleteFramebuffers(1, &viewFbo_);+ gl::DeleteRenderbuffers(2, viewRb_);+ viewFbo_ = 0;+ viewSamples_ = 0;+ viewFailed_ = samples;+ return false;+ }+ viewSamples_ = samples;+ viewFailed_ = 0;+ return true;+}++int Renderer::drawView(const Camera& camera, int width, int height, const RenderSettings& settings, const Viewport& viewport,+ int samples) {+ GLint maxSamples = 1;+ gl::GetIntegerv(GL_MAX_SAMPLES, &maxSamples);+ samples = std::clamp(samples, 1, std::max(1, int(maxSamples)));+ while (samples > 1 && !viewTarget(width, height, samples)) samples /= 2;+ if (samples <= 1) {+ gl::BindFramebuffer(GL_FRAMEBUFFER, 0);+ draw(camera, width, height, settings, viewport);+ return 1;+ }+ gl::BindFramebuffer(GL_FRAMEBUFFER, viewFbo_);+ draw(camera, width, height, settings, viewport);+ gl::BindFramebuffer(GL_READ_FRAMEBUFFER, viewFbo_);+ gl::BindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);+ gl::BlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);+ gl::BindFramebuffer(GL_FRAMEBUFFER, 0);+ return samples;+}+bool Renderer::beginCapture(int width, int height, std::string& error) {if (width != captureW_ || height != captureH_) {if (captureFbo_[0]) {diff --git a/src/render/Renderer.h b/src/render/Renderer.hindex 06e7841f..f0fe8782 100644--- a/src/render/Renderer.h+++ b/src/render/Renderer.h@@ -72,10 +72,17 @@ public:// mesh marked dirty and clears its dirty state (a new slot uploads// everything), and frees the slots of ids no longer listed.void syncScene(const std::vector<SceneMesh>& scene);+ // True when SubTool `id` didn't fit in GPU memory at its last full upload (it isn't drawn until it does).+ bool outOfMemory(uint32_t id) const;// Re-uploads the splats when `version` differs from the last upload.void syncSplats(const SplatCloud& splats, uint64_t version);using Viewport = RenderViewport;void draw(const Camera& camera, int fbWidth, int fbHeight, const RenderSettings& settings, const Viewport& viewport = {});+ // draw() for the app's window (whose framebuffer has no multisampling): through an offscreen target with+ // `samples` samples, resolved to the screen, or straight to the screen for 1. When the GPU can't make the+ // target (e.g. out of memory) it uses fewer samples. Returns the samples used.+ int drawView(const Camera& camera, int fbWidth, int fbHeight, const RenderSettings& settings, const Viewport& viewport,+ int samples);// Offscreen render (4x MSAA) into top-down RGBA8 pixels.bool renderToImage(const Camera& camera, int width, int height, const RenderSettings& settings,std::vector<uint8_t>& rgba, std::string& error);@@ -108,6 +115,10 @@ private:std::vector<uint32_t> splatSorted_;glm::mat4 lastSortView_{0.0f};GLuint captureFbo_[2] = {}, captureRb_[3] = {};+ // drawView's multisampled target; viewFailed_ = the sample count that couldn't be made at this size.+ bool viewTarget(int width, int height, int samples);+ GLuint viewFbo_ = 0, viewRb_[2] = {};+ int viewW_ = 0, viewH_ = 0, viewSamples_ = 0, viewFailed_ = 0;int captureW_ = 0, captureH_ = 0;GLuint emptyVao_ = 0;bool thumbnailPass_ = false; // draw(): transparent background, no gradient (renderMeshThumbnail)@@ -128,6 +139,7 @@ private:bool hasTangents = false, tangentsStale = true, normalFlipGreen = false;bool hasColors = false, hasMask = false, hasGroups = false, hasUvs = false;bool fresh = true; // nothing uploaded yet+ bool outOfMemory = false; // the last full upload ran out of GPU memory: not drawnUploadOrder order; // the vertices' order in the GPU buffersGLsizei indexCount = 0;GLsizei lineCount = 0; // wireframe edge indices after the triangles (meshes with quads; 0 = draw triangles)