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.

Fix a use-after-free in the Fill layer panel; make ui_stroke_path independent of frame rate

islandmed96f6981f42cc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 88619e7a..a42e3abe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -88,6 +88,8 @@ All notable changes to SculptForge are listed here. The format follows
### Fixed
- Maya input style (#32): <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Shift</kbd>+drag erases the mask instead of starting
the <kbd>Ctrl</kbd>+<kbd>Shift</kbd> visibility selection.
+- Paint Layers: picking a Material Recipe, or changing a Fill layer, from the panel could crash: the panel kept
+ reading the texture the command had just replaced. Its commands now run once the panel is drawn.
## [0.10.5] - 2026-11-01
### Added
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 37716167..b514a2de 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -724,6 +724,7 @@ int App::run() {
double releaseMs = 0.0, releaseAt = 0.0;
uint64_t frames = 0, samples = 0, lagSamples = 0;
float cx = 0.0f, cy = 0.0f, r = 0.0f;
+ double angle = 0.0; // the pointer's angle round the circle (0 at the press, 4 pi at the end)
std::vector<glm::vec2> dabs;
MeasureView view{}; // the view before the stroke (it starts once this has held still for a second)
double viewSince = 0.0;
@@ -827,8 +828,15 @@ int App::run() {
return 1;
}
} else if (sm.moving) {
- const double u = std::min(1.0, (seconds() - sm.start) / double(options_.measureStroke));
- const double a = u * 4.0 * 3.14159265358979;
+ // The pointer follows the clock, but moves at most kMaxPointerStep per pass: the stroke follows the chords
+ // between samples, and on a slow frame rate (software GL on a busy machine: 100 ms frames and more) the
+ // chords would cut well inside the circle, or one long frame would skip the whole stroke. Above 30 fps
+ // the clock alone sets it; below, the stroke takes longer and is checked just as strictly.
+ constexpr double kMaxPointerStep = 0.25; // radians (a chord's middle 0.8% of the radius inside the circle)
+ const double clock = std::min(1.0, (seconds() - sm.start) / double(options_.measureStroke)) * 4.0 * 3.14159265358979;
+ const double a = std::min(clock, sm.angle + kMaxPointerStep);
+ const double u = a / (4.0 * 3.14159265358979);
+ sm.angle = a;
// SF_MEASURE_RESIZE=1: the brush size changes every frame mid-stroke, as [ and ] would (the solver thread
// must see each batch's own size: ui_stroke_resize, with verify).
static const bool resize = std::getenv("SF_MEASURE_RESIZE") != nullptr;
@@ -868,7 +876,7 @@ int App::run() {
" brush behind the pointer: surface mean %.0f px, worst %.0f px; preview mean %.0f px, worst %.0f px\n"
" release %.0f ms (last dab on screen after %.0f ms)\n",
interactiveStrokes_ ? "queued" : "immediate", predictiveStrokes() ? ", predictive" : "", sm.dabs.size(),
- (unsigned long long)sm.samples, double(options_.measureStroke), double(sm.r), double(radiusPx_),
+ (unsigned long long)sm.samples, sm.releaseAt - sm.start, double(sm.r), double(radiusPx_),
double(pct(0.5)), double(pct(0.95)), double(off.empty() ? 0.0f : off.back()), sm.pressMs,
sm.firstSurfaceMs, (unsigned long long)sm.frames, frameMean, sm.maxFrame * 1000.0, lagMean, sm.maxLag,
previewMean, sm.maxPreviewLag, releaseMs, releaseDoneMs);
@@ -890,7 +898,11 @@ int App::run() {
const float spacing = std::max(1.0f, radiusPx_ * 0.15f);
const double expected = 4.0 * 3.14159265358979 * double(sm.r) / double(spacing);
if (std::getenv("SF_MEASURE_RESIZE")) return 0; // (the spacing changed with the size: verify checked it)
- return double(sm.dabs.size()) >= 0.9 * expected && !off.empty() && off.back() < spacing ? 0 : 1;
+ const bool enough = double(sm.dabs.size()) >= 0.9 * expected, onCircle = !off.empty() && off.back() < spacing;
+ if (!enough || !onCircle)
+ std::printf("Stroke check failed: %zu dabs (want %.0f or more), worst %.1f px off the circle (want under %.1f)\n",
+ sm.dabs.size(), 0.9 * expected, double(off.empty() ? 0.0f : off.back()), double(spacing));
+ return enough && onCircle ? 0 : 1;
}
}
// The stroke's queued dabs: handed to the solver thread (predictive strokes, AsyncStroke.cpp), or placed here
@@ -1033,8 +1045,7 @@ int App::run() {
sm.lastFrame = now;
++sm.frames;
if (!sm.dabs.empty()) { // how far round the circle the brush is behind the pointer, on screen now
- const double u = std::min(1.0, (now - sm.start) / double(options_.measureStroke));
- const double pointer = std::fmod(u * 4.0 * 3.14159265358979, 2.0 * 3.14159265358979);
+ const double pointer = std::fmod(sm.angle, 2.0 * 3.14159265358979); // where the pointer was sent
const glm::vec2 d = sm.dabs.back();
double behind = pointer - std::atan2(double(d.y - sm.cy), double(d.x - sm.cx));
behind = std::remainder(behind, 2.0 * 3.14159265358979);
diff --git a/src/app/PanelFill.cpp b/src/app/PanelFill.cpp
index 475c5fb5..e2c62119 100644
--- a/src/app/PanelFill.cpp
+++ b/src/app/PanelFill.cpp
@@ -152,12 +152,23 @@ void App::drawFillLayerControls() {
const Mesh& mesh = doc_.mesh;
if (!hasTexture(mesh)) return;
const PaintTexture& t = *mesh.texture;
+ // Commands that edit the texture replace it (the old one goes into the undo step and may be freed), so `t`, the
+ // Fill layer and its effects below are only valid until one runs: they wait until the panel is drawn.
+ std::vector<std::pair<std::string, Args>> pending;
+ struct RunPending {
+ App& app;
+ std::vector<std::pair<std::string, Args>>& list;
+ ~RunPending() {
+ for (auto& [name, args] : list) app.runCommand(name, args);
+ }
+ } runPending{*this, pending};
+ auto run = [&pending](const char* name, Args args) { pending.emplace_back(name, std::move(args)); };
const ImGuiStyle& style = ImGui::GetStyle();
ImGui::Spacing();
ImGui::TextDisabled("%s", tr("Fill Layers"));
const float half = (ImGui::GetContentRegionAvail().x - style.ItemSpacing.x) * 0.5f;
if (ImGui::Button(ICON_LC_PLUS " Fill Layer##fill", ImVec2(half, 0)))
- runCommand("fill_layer", {{"name", std::string("Fill")}, {"color", colorToHex(doc_.paintColor)}});
+ run("fill_layer", {{"name", std::string("Fill")}, {"color", colorToHex(doc_.paintColor)}});
ui::HelpText("New Fill Layer", nullptr,
"Add a Fill layer: a material over the whole Part through a mask you build from effects (Edge Wear, "
"Dirt, Gradient, Thickness, Light Direction, Noise, a painted mask, Levels, Blur, Invert). Change it any "
@@ -167,12 +178,12 @@ void App::drawFillLayerControls() {
ImGui::SetNextItemWidth(-1);
if (ImGui::BeginCombo("##recipe", tr("Material Recipe"))) {
for (const MaterialRecipe& r : builtinMaterialRecipes()) {
- if (ImGui::Selectable((r.name + "##recipe").c_str())) runCommand("material_recipe", {{"name", r.id}});
+ if (ImGui::Selectable((r.name + "##recipe").c_str())) run("material_recipe", {{"name", r.id}});
if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", r.description.c_str());
}
for (const PackContentItem& it : packMaterials()) // from installed packs, tagged with the pack's name
if (ImGui::Selectable((it.label() + "##recipe" + it.file).c_str()))
- runCommand("material_recipe", {{"path", it.file}});
+ run("material_recipe", {{"path", it.file}});
ImGui::EndCombo();
}
ui::HelpText("Material Recipe", nullptr,
@@ -198,7 +209,7 @@ void App::drawFillLayerControls() {
kFillPath);
ImGui::SameLine();
bool live = !maps || maps->live;
- if (ui::Checkbox("Live##meshmaps", &live) && maps) runCommand("mesh_maps", {{"action", std::string("live")}, {"live", live}});
+ if (ui::Checkbox("Live##meshmaps", &live) && maps) run("mesh_maps", {{"action", std::string("live")}, {"live", live}});
ImGui::SameLine();
if (ImGui::SmallButton(tr("Bake##meshmaps"))) meshMapsWanted_ = true;
}
@@ -220,7 +231,7 @@ void App::drawFillLayerControls() {
if (ImGui::ColorEdit3("##fillcolor", &col.x, ImGuiColorEditFlags_NoInputs)) fillColorEdit_ = srgbToLinear(col), fillColorEditing_ = true;
if (ImGui::IsItemDeactivatedAfterEdit() && fillColorEditing_) {
fillColorEditing_ = false;
- runCommand("fill_layer", withLayer({{"action", std::string("set")}, {"color", colorToHex(fillColorEdit_)}}));
+ run("fill_layer", withLayer({{"action", std::string("set")}, {"color", colorToHex(fillColorEdit_)}}));
}
ui::HelpText("Fill colour", nullptr, "The base colour the Fill layer lays down.", kFillPath);
for (Channel c : {Channel::BaseColor, Channel::Roughness, Channel::Metallic, Channel::Height}) {
@@ -232,7 +243,7 @@ void App::drawFillLayerControls() {
const bool has = k == int(c) ? on : (f.material.channels & (1u << k)) != 0;
if (has) list += std::string(list.empty() ? "" : ",") + channelFormat(k).id;
}
- if (!list.empty()) runCommand("fill_layer", withLayer({{"action", std::string("set")}, {"channels", list}}));
+ if (!list.empty()) run("fill_layer", withLayer({{"action", std::string("set")}, {"channels", list}}));
}
}
auto materialSlider = [&](const char* id, const char* key, float value, const char* fmt, Channel c) {
@@ -240,7 +251,7 @@ void App::drawFillLayerControls() {
ImGui::SetNextItemWidth(-1);
float v = value;
ImGui::SliderFloat(id, &v, 0.0f, 1.0f, fmt);
- if (ImGui::IsItemDeactivatedAfterEdit()) runCommand("fill_layer", withLayer({{"action", std::string("set")}, {key, double(v)}}));
+ if (ImGui::IsItemDeactivatedAfterEdit()) run("fill_layer", withLayer({{"action", std::string("set")}, {key, double(v)}}));
};
materialSlider("##fillrough", "roughness", f.material.roughness, "Roughness %.2f", Channel::Roughness);
materialSlider("##fillmetal", "metallic", f.material.metallic, "Metallic %.2f", Channel::Metallic);
@@ -260,7 +271,7 @@ void App::drawFillLayerControls() {
return withLayer(std::move(a));
};
bool enabled = e.enabled;
- if (ui::Checkbox("##on", &enabled)) runCommand("fill_layer", effectArgs({{"enabled", enabled}}));
+ if (ui::Checkbox("##on", &enabled)) run("fill_layer", effectArgs({{"enabled", enabled}}));
ImGui::SameLine();
ImGui::TextUnformatted(title.c_str());
if (k > 0) {
@@ -269,7 +280,7 @@ void App::drawFillLayerControls() {
if (ImGui::BeginCombo("##blend", maskBlendId(e.blend))) {
for (int b = 0; b < kMaskBlendCount; ++b)
if (ImGui::Selectable(maskBlendId(MaskBlend(b)), int(e.blend) == b))
- runCommand("fill_layer", effectArgs({{"blend", std::string(maskBlendId(MaskBlend(b)))}}));
+ run("fill_layer", effectArgs({{"blend", std::string(maskBlendId(MaskBlend(b)))}}));
ImGui::EndCombo();
}
}
@@ -279,7 +290,7 @@ void App::drawFillLayerControls() {
ImGui::SetNextItemWidth(-1);
float v = value;
ImGui::SliderFloat(id, &v, lo, hi, fmt);
- if (ImGui::IsItemDeactivatedAfterEdit()) runCommand("fill_layer", effectArgs({{key, double(v)}}));
+ if (ImGui::IsItemDeactivatedAfterEdit()) run("fill_layer", effectArgs({{key, double(v)}}));
};
switch (e.kind) {
case MaskEffectKind::Generator:
@@ -304,16 +315,16 @@ void App::drawFillLayerControls() {
}
ImGui::PopID();
}
- if (remove >= 0) runCommand("fill_layer", withLayer({{"action", std::string("remove_effect")}, {"effect", double(remove)}}));
+ if (remove >= 0) run("fill_layer", withLayer({{"action", std::string("remove_effect")}, {"effect", double(remove)}}));
ImGui::SetNextItemWidth(-1);
if (ImGui::BeginCombo("##addeffect", tr("Add mask effect"))) {
for (int g = 0; g < kGeneratorKindCount; ++g)
if (ImGui::Selectable((std::string(generatorLabel(GeneratorKind(g))) + "##gen").c_str()))
- runCommand("fill_layer", withLayer({{"action", std::string("effect")}, {"generator", std::string(generatorId(GeneratorKind(g)))}}));
+ run("fill_layer", withLayer({{"action", std::string("effect")}, {"generator", std::string(generatorId(GeneratorKind(g)))}}));
for (MaskEffectKind k : {MaskEffectKind::Noise, MaskEffectKind::Paint, MaskEffectKind::Levels, MaskEffectKind::Blur,
MaskEffectKind::Invert, MaskEffectKind::Fill})
if (ImGui::Selectable((std::string(maskEffectLabel(k)) + "##kind").c_str()))
- runCommand("fill_layer", withLayer({{"action", std::string("effect")}, {"kind", std::string(maskEffectId(k))}}));
+ run("fill_layer", withLayer({{"action", std::string("effect")}, {"kind", std::string(maskEffectId(k))}}));
ImGui::EndCombo();
}
ui::HelpText("Add mask effect", nullptr,
diff --git a/tests/test_fill_layers.cpp b/tests/test_fill_layers.cpp
index 20a57df3..8e393a13 100644
--- a/tests/test_fill_layers.cpp
+++ b/tests/test_fill_layers.cpp
@@ -17,7 +17,9 @@
#include "core/TextureChannels.h"
#include "core/Undo.h"
+#include <atomic>
#include <cmath>
+#include <thread>
using namespace sf;
@@ -298,3 +300,87 @@ TEST(material_recipes_are_data_and_wear_the_model) {
std::string err;
CHECK(!parseMaterialRecipe("{\"format\":\"other\"}", bad, err));
}
+
+// The app's live re-bake (App::updateMeshMaps): the update runs on a worker thread while the main thread keeps
+// using the maps it updates (Fill layers evaluate from them, the texture is replaced by the next command, the Part
+// is sculpted again). Many rounds in a row, each landing as the app lands it, end equal to a full bake of the
+// final shape. (Under ThreadSanitizer or AddressSanitizer this catches shared writes and stale reads.)
+TEST(mesh_maps_live_rebake_on_a_worker_while_fill_layers_evaluate) {
+ Mesh m = trenchPart();
+ const MeshMapSettings st = quickMaps();
+ auto maps = std::make_shared<MeshMapSet>();
+ std::string err;
+ CHECK(bakeMeshMaps(m, 1024, 1024, kAllMeshMaps, st, *maps, err));
+ m.texture->meshMaps = maps;
+ FillLayer wear;
+ wear.material.channels = channelBit(Channel::BaseColor) | channelBit(Channel::Roughness);
+ MaskEffect e;
+ e.generator = GeneratorKind::EdgeWear;
+ e.level = 0.6f;
+ wear.effects.push_back(e);
+ MaskEffect blur;
+ blur.kind = MaskEffectKind::Blur;
+ blur.radius = 4.0f;
+ wear.effects.push_back(blur);
+ addFillLayer(m, *m.texture, "Edges", wear);
+ int landed = 0;
+ for (int round = 0; round < 6; ++round) {
+ // Sculpt a dent somewhere new.
+ const glm::vec2 c(-0.6f + 0.24f * float(round), 0.5f - 0.2f * float(round));
+ for (glm::vec3& p : m.positions) {
+ const float d = glm::distance(glm::vec2(p.x, p.z), c);
+ if (d < 0.12f) p.y -= 0.05f * (0.5f + 0.5f * std::cos(d / 0.12f * 3.14159265f));
+ }
+ m.recomputeAllNormals();
+ std::vector<uint32_t> moved;
+ const AABB region = changedRegion(*m.texture->meshMaps, m, &moved);
+ CHECK(region.valid());
+ auto up = std::make_shared<MeshMapUpdate>();
+ if (!prepareMeshMapUpdate(m, m.texture->meshMaps, region, std::move(moved), *up)) continue;
+ std::atomic<bool> done{false};
+ std::thread worker([up, &done] {
+ runMeshMapUpdate(*up);
+ done = true;
+ });
+ // Meanwhile: the Fill layers evaluate from the maps being updated, and a command replaces the texture
+ // (its undo step keeps the old one, which then goes).
+ int evaluations = 0;
+ do {
+ std::shared_ptr<PaintTexture> old = m.texture;
+ PaintTexture& t = mutableTexture(m);
+ evaluateFillLayers(m, t, nullptr);
+ old.reset();
+ ++evaluations;
+ } while (!done && evaluations < 50);
+ worker.join();
+ CHECK(up->ok);
+ if (m.texture->meshMaps != up->base) continue; // (as the app: only onto the set it was made from)
+ std::shared_ptr<MeshMapSet> set = applyMeshMapUpdate(*up);
+ CHECK(set != nullptr);
+ mutableTexture(m).meshMaps = std::move(set);
+ evaluateFillLayers(m, *m.texture, &up->tiles);
+ ++landed;
+ }
+ CHECK(landed >= 5);
+ CHECK(!changedRegion(*m.texture->meshMaps, m).valid());
+ MeshMapSet full;
+ CHECK(bakeMeshMaps(m, 1024, 1024, kAllMeshMaps, st, full, err));
+ size_t differ = 0;
+ const MeshMapSet& live = *m.texture->meshMaps;
+ for (int k = 0; k < kMeshMapCount; ++k) {
+ if (MeshMapKind(k) == MeshMapKind::Position) continue; // (keeps the first bake's box)
+ for (int y = 0; y < 1024; y += 3)
+ for (int x = 0; x < 1024; x += 3) {
+ float a[4] = {}, b[4] = {};
+ live.images[size_t(k)].values(x, y, a);
+ full.images[size_t(k)].values(x, y, b);
+ for (int i = 0; i < 3; ++i)
+ if (std::abs(a[i] - b[i]) > 1.0f / 255.0f) {
+ ++differ;
+ break;
+ }
+ }
+ }
+ std::printf(" %d of 6 updates landed; %zu sampled texels differ from a full bake\n", landed, differ);
+ CHECK(differ == 0);
+}