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
Strokes on dense meshes keep their curve (#19): dabs queued and placed within 10 ms a frame
islandmed8e0be79d5d92
diff --git a/src/app/App.cpp b/src/app/App.cppindex 5a1a4a8c..a2f5dfbe 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -577,6 +577,7 @@ Uint32 g_wakeEvent = 0; // registered in App::run(); 0 beforeconstexpr int kIdleTickMs = 250; // asleep: wake this often to run the pollers (the Blender bridge, autosave)constexpr int kCaretTickMs = 530; // a text field has the keyboard: redraw for the caret's blinkconstexpr double kAfterChangeSeconds = 0.25; // a poller changed something: draw for this long+constexpr double kStrokeBudgetSeconds = 0.010; // a frame's share of placing a stroke's dabs; the rest waits for the next} // namespace@@ -618,6 +619,7 @@ int App::run() {if (!options_.renderPath.empty()) return renderHeadless();if (!options_.recordPath.empty() || !options_.uiTest.empty()) return runRecording();if (g_wakeEvent == 0) g_wakeEvent = SDL_RegisterEvents(1);+ interactiveStrokes_ = true; // dabs are queued and placed within a time budget each frame (strokeTo)// SF_CONTINUOUS_REDRAW=1 draws every frame as before 0.9.5 (for comparison, or a driver that misbehaves).const char* continuousEnv = std::getenv("SF_CONTINUOUS_REDRAW");const bool continuous = continuousEnv && *continuousEnv && *continuousEnv != '0';@@ -684,6 +686,7 @@ int App::run() {++wakeUps;}while (SDL_PollEvent(&e)) onEvent(e);+ drainStrokeDabs(kStrokeBudgetSeconds); // the stroke's queued dabs, for a limited time: then look at the pointer againUint64 now = SDL_GetTicksNS();float dt = float(double(now - lastTicks) * 1e-9);lastTicks = now;@@ -1046,7 +1049,8 @@ void App::beginStroke(float x, float y, const RayHit& hit) {status_ = "Dynamic is on, but this SubTool has subdivision levels: sculpting without remeshing";lastX_ = x;lastY_ = y;- residual_ = 0.0f;+ strokePath_.reset(x, y);+ dabQueue_.clear();if (strokeBrush_ == BrushType::Move && !recipe && strokeSculpt_) {const float pressure = pressureSize_ ? std::max(strokePressure(), 0.05f) : 1.0f;@@ -1125,6 +1129,7 @@ void App::strokeTo(float x, float y) {if (!penTracker_.readyForFirstDab() && penTracker_.everSampled()) {lastX_ = x;lastY_ = y;+ strokePath_.reset(x, y);return;}firstDabPending_ = false;@@ -1134,21 +1139,50 @@ void App::strokeTo(float x, float y) {// Place dabs at even screen-space spacing along the cursor path. Every input sample counts (pens// send 100-200+ a second, several per frame); the pressure is interpolated between samples.+ // The dabs are queued, not placed here: on a huge mesh one dab can cost more than a frame, and placing every+ // dab of a long gap before the next look at the pointer made the gaps longer still, until the stroke was one+ // straight line. The interactive loop works through the queue for a limited time per frame (drainStrokeDabs),+ // and a gap between samples that is long is drawn as a curve (core/StrokePath.h).const float spacing = std::max(1.0f, radiusPx_ * (recipe ? recipe->spacing : 0.15f));- glm::vec2 from(lastX_, lastY_), to(x, y);- float len = glm::length(to - from);const float p0 = lastStrokePressure_, p1 = strokePressure();- float travelled = spacing - residual_;- while (travelled <= len) {- const float u = travelled / len;- glm::vec2 p = from + (to - from) * u;- dabAt(p.x, p.y, p0 + (p1 - p0) * u);- travelled += spacing;- }- residual_ = len - (travelled - spacing);+ strokeScratch_.clear();+ strokePath_.addSample(x, y, p0, p1, spacing, interactiveStrokes_, strokeScratch_);+ for (const PathDab& d : strokeScratch_) dabQueue_.push(d);lastX_ = x;lastY_ = y;lastStrokePressure_ = p1;+ if (interactiveStrokes_) {+ // Too far behind the pointer: place every second waiting dab only (a wider spacing under load). Set+ // SF_STROKE_BACKLOG=0 to never drop dabs, or a number to change the limit (default 24).+ static const size_t limit = [] {+ const char* env = std::getenv("SF_STROKE_BACKLOG");+ return env && *env ? size_t(std::max(0L, std::strtol(env, nullptr, 10))) : size_t(24);+ }();+ dabQueue_.thin(limit);+ } else {+ drainStrokeDabs(0.0); // scripts, UI tests and recordings place every dab at once, as before+ }+}++void App::drainStrokeDabs(double budgetSeconds) {+ if (dabQueue_.empty()) return;+ static const bool log = std::getenv("SF_STROKE_LOG") != nullptr; // per frame: dabs waiting, placed, ms+ const auto start = std::chrono::steady_clock::now();+ const size_t waiting = dabQueue_.size();+ size_t placed = 0;+ while (!dabQueue_.empty()) {+ const PathDab d = dabQueue_.pop();+ dabAt(d.x, d.y, d.pressure);+ ++placed;+ if (budgetSeconds > 0.0 &&+ std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count() >= budgetSeconds)+ break; // at least one dab per call, so a stroke always moves on+ }+ if (log)+ SDL_Log("stroke: %llu waiting, %llu placed in %.1f ms, %llu left", (unsigned long long)waiting,+ (unsigned long long)placed,+ std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count(),+ (unsigned long long)dabQueue_.size());}void App::dabAt(float x, float y, float pressure) {@@ -1211,6 +1245,7 @@ void App::dabAt(float x, float y, float pressure) {}void App::endStroke() {+ drainStrokeDabs(0.0); // the dabs still waiting belong to this strokestrokeMask_ = false;maskClickPending_ = false; // (a command can end a Ctrl+click before its release)firstDabPending_ = false;diff --git a/src/app/App.h b/src/app/App.hindex a6229e05..cc2eae3d 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -24,6 +24,7 @@#include "core/AutoUv.h"#include "core/QRemesh.h"#include "core/Stroke.h"+#include "core/StrokePath.h"#include "core/SpaceMouse.h"#include "core/Tablet.h"#include "core/UpdateCheck.h"@@ -207,7 +208,14 @@ private:bool panFromAlt_ = false; // a pan started with Alt: releasing Alt mid-drag zooms (ZBrush)bool forceTurntable_ = false; // demos orbit like a turntable whatever the preferencefloat mouseX_ = 0.0f, mouseY_ = 0.0f;- float lastX_ = 0.0f, lastY_ = 0.0f, residual_ = 0.0f;+ float lastX_ = 0.0f, lastY_ = 0.0f;+ // Dabs are placed along the pointer's path (strokePath_), queued, and worked through for a limited time per+ // frame in the interactive loop, so a stroke on a huge mesh keeps its curve (core/StrokePath.h).+ StrokePath strokePath_;+ DabQueue dabQueue_;+ std::vector<PathDab> strokeScratch_;+ bool interactiveStrokes_ = false; // App::run(): budgeted dabs and curved long gaps; other loops dab at once+ void drainStrokeDabs(double budgetSeconds); // places queued dabs; budget <= 0: all of thembool lastInputPen_ = false; // the last mouse event came from a pen (SDL_PEN_MOUSEID)bool penSeen_ = false;BrushType strokeBrush_ = BrushType::Standard;diff --git a/src/app/PanelMasking.cpp b/src/app/PanelMasking.cppindex f8f1b98f..211b70d9 100644--- a/src/app/PanelMasking.cpp+++ b/src/app/PanelMasking.cpp@@ -44,7 +44,8 @@ void App::beginMaskStroke(float x, float y) {drag_ = Drag::Stroke;lastX_ = x;lastY_ = y;- residual_ = 0.0f;+ strokePath_.reset(x, y);+ dabQueue_.clear();lazyMouse_.reset(glm::vec2(x, y));// ZBrush: a Ctrl+click on the model blurs the mask (Ctrl+Alt+click sharpens it); only a drag paints. The// pen's eraser end set to Erase mask paints straight away.diff --git a/src/core/StrokePath.h b/src/core/StrokePath.hnew file mode 100644index 00000000..ed969ad3--- /dev/null+++ b/src/core/StrokePath.h@@ -0,0 +1,177 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// How input samples become dabs, for strokes that cannot keep up with the cursor (tens of millions of triangles).+//+// A dab on a huge mesh can cost more than a frame. The app only reads the pointer between dabs, and Windows (like+// the other window systems) hands over just the latest position when the program was busy. Placing every dab of a+// long segment before the next read made the segments longer still: the stroke collapsed into one straight line+// from where it began to where the pointer is now.+//+// So the work is split in two:+// StrokePath turns each input sample into the dabs between the previous sample and this one, at an even+// spacing. With `smooth`, a long gap between samples is drawn as a curve through the last three+// samples (a Hermite segment), not a chord, so a fast arc stays an arc.+// DabQueue holds those dabs; the main loop works through it for a limited time per frame and reads input and+// draws in between. If the queue grows past a limit, every second waiting dab is dropped (a wider+// spacing under load) so the brush stays near the pointer instead of minutes behind it.+//+// Plain floats, no UI or maths library, so it is tested without a window (tests/test_stroke_path.cpp).+#pragma once++#include <algorithm>+#include <cmath>+#include <cstddef>+#include <deque>+#include <vector>++namespace sf {++struct PathDab {+ float x = 0.0f, y = 0.0f; // screen pixels+ float pressure = 1.0f;+};++class StrokePath {+public:+ // Starts a path at (x, y). Also used when a stroke restarts its position (a pen that has not pressed yet).+ void reset(float x, float y) {+ x_ = x;+ y_ = y;+ px_ = x;+ py_ = y;+ havePrev_ = false;+ residual_ = 0.0f;+ }++ // Appends the dabs between the previous point and (x, y), `spacing` pixels apart (the leftover distance+ // carries over to the next call). Pressure runs from p0 at the previous point to p1 at (x, y).+ // smooth: a gap longer than two spacings is curved through the last three points. Otherwise it is straight.+ void addSample(float x, float y, float p0, float p1, float spacing, bool smooth, std::vector<PathDab>& out) {+ spacing = std::max(spacing, 1.0f);+ const float dx = x - x_, dy = y - y_;+ const float chord = std::sqrt(dx * dx + dy * dy);+ if (chord <= 1e-6f) return;++ int n = 1;+ float m1x = dx, m1y = dy; // Hermite tangents at the start and at the end of the segment+ float m2x = dx, m2y = dy;+ if (smooth && chord > 2.0f * spacing) {+ if (havePrev_) {+ // The path is taken to keep turning at the rate it just did (the next gap is the current one turned by+ // the last turn), and the tangents are the Catmull-Rom ones: half of the two gaps beside the point.+ // Nothing here waits for a later sample, so the dab never lags the pointer.+ const float cx = x_ - px_, cy = y_ - py_; // the previous gap+ const float clen = std::sqrt(cx * cx + cy * cy);+ if (clen > 1e-6f) {+ const float cs = (cx * dx + cy * dy) / (clen * chord);+ const float sn = (cx * dy - cy * dx) / (clen * chord);+ const float nx = dx * cs - dy * sn, ny = dx * sn + dy * cs; // the predicted next gap+ float t1x = 0.5f * (cx * chord / clen + dx), t1y = 0.5f * (cy * chord / clen + dy);+ float t2x = 0.5f * (dx + nx), t2y = 0.5f * (dy + ny);+ // a hairpin turn (a tangent points backwards) stays a corner: straight+ if (t1x * dx + t1y * dy > 0.0f && t2x * dx + t2y * dy > 0.0f) {+ limit(t1x, t1y, chord);+ limit(t2x, t2y, chord);+ m1x = t1x;+ m1y = t1y;+ m2x = t2x;+ m2y = t2y;+ }+ }+ }+ n = std::clamp(int(std::ceil(chord / (2.0f * spacing))), 1, kMaxSubdivisions);+ }++ // Walk the path (n straight pieces) placing dabs at even spacing.+ float ax = x_, ay = y_, at = 0.0f;+ float travelled = spacing - residual_;+ for (int i = 1; i <= n; ++i) {+ const float t = float(i) / float(n);+ float bx = x, by = y;+ if (i < n) { // a point on the Hermite curve; the last piece ends exactly on the sample+ const float t2 = t * t, t3 = t2 * t;+ const float h00 = 2 * t3 - 3 * t2 + 1, h10 = t3 - 2 * t2 + t, h01 = -2 * t3 + 3 * t2, h11 = t3 - t2;+ bx = h00 * x_ + h10 * m1x + h01 * x + h11 * m2x;+ by = h00 * y_ + h10 * m1y + h01 * y + h11 * m2y;+ }+ const float sx = bx - ax, sy = by - ay;+ const float len = std::sqrt(sx * sx + sy * sy);+ if (len > 1e-6f) {+ while (travelled <= len) {+ const float u = travelled / len;+ PathDab d;+ d.x = ax + sx * u;+ d.y = ay + sy * u;+ const float tt = at + (t - at) * u;+ d.pressure = p0 + (p1 - p0) * tt;+ out.push_back(d);+ travelled += spacing;+ }+ travelled -= len; // distance still to go to the next dab, from the end of this piece+ }+ ax = bx;+ ay = by;+ at = t;+ }+ residual_ = spacing - travelled; // distance since the last dab+ if (residual_ < 0.0f) residual_ = 0.0f;+ px_ = x_;+ py_ = y_;+ havePrev_ = true;+ x_ = x;+ y_ = y;+ }++ float lastX() const { return x_; }+ float lastY() const { return y_; }++private:+ static constexpr int kMaxSubdivisions = 64;+ static void limit(float& tx, float& ty, float maxLen) {+ const float len = std::sqrt(tx * tx + ty * ty);+ if (len > maxLen) {+ tx *= maxLen / len;+ ty *= maxLen / len;+ }+ }+ float x_ = 0.0f, y_ = 0.0f; // the previous sample+ float px_ = 0.0f, py_ = 0.0f; // the one before it+ bool havePrev_ = false;+ float residual_ = 0.0f;+};++// Dabs waiting to be placed.+class DabQueue {+public:+ void push(const PathDab& d) { q_.push_back(d); }+ bool empty() const { return q_.empty(); }+ size_t size() const { return q_.size(); }+ void clear() { q_.clear(); }+ PathDab pop() {+ PathDab d = q_.front();+ q_.pop_front();+ return d;+ }++ // Keeps the queue at `limit` dabs or fewer by dropping every second waiting dab (the newest always stays).+ // limit 0: never drop. Returns how many were dropped.+ size_t thin(size_t limit) {+ if (limit == 0) return 0;+ size_t dropped = 0;+ while (q_.size() > limit) {+ std::deque<PathDab> kept;+ for (size_t i = 0; i < q_.size(); ++i)+ if (i % 2 == 1 || i + 1 == q_.size()) kept.push_back(q_[i]);+ dropped += q_.size() - kept.size();+ if (kept.size() >= q_.size()) break; // (a queue of one)+ q_.swap(kept);+ }+ return dropped;+ }++private:+ std::deque<PathDab> q_;+};++} // namespace sfdiff --git a/tests/test_stroke_path.cpp b/tests/test_stroke_path.cppnew file mode 100644index 00000000..a31a1550--- /dev/null+++ b/tests/test_stroke_path.cpp@@ -0,0 +1,182 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// StrokePath / DabQueue (core/StrokePath.h): the stroke that keeps its path when a dab costs more than a frame.+#include "TestHarness.h"++#include "core/StrokePath.h"++#include <algorithm>+#include <cmath>+#include <cstdint>+#include <vector>++using namespace sf;++namespace {++bool near(float a, float b, float eps = 1e-3f) { return std::abs(a - b) < eps; }++// The loop App::strokeTo used before StrokePath: straight dabs at even spacing, pressure interpolated.+struct Reference {+ float lx = 0, ly = 0, residual = 0;+ void addSample(float x, float y, float p0, float p1, float spacing, std::vector<PathDab>& out) {+ const float dx = x - lx, dy = y - ly;+ const float len = std::sqrt(dx * dx + dy * dy);+ float travelled = spacing - residual;+ while (travelled <= len) {+ const float u = travelled / len;+ out.push_back({lx + dx * u, ly + dy * u, p0 + (p1 - p0) * u});+ travelled += spacing;+ }+ residual = len - (travelled - spacing);+ lx = x;+ ly = y;+ }+};++float lcg(uint32_t& s) {+ s = s * 1664525u + 1013904223u;+ return float(s >> 8) / float(1 << 24);+}++} // namespace++TEST(stroke_path_straight_matches_the_old_loop) {+ uint32_t seed = 7;+ StrokePath path;+ Reference ref;+ path.reset(10.0f, 20.0f);+ ref.lx = 10.0f;+ ref.ly = 20.0f;+ float x = 10.0f, y = 20.0f, p = 0.5f;+ std::vector<PathDab> a, b;+ for (int i = 0; i < 200; ++i) {+ x += (lcg(seed) - 0.5f) * 60.0f;+ y += (lcg(seed) - 0.5f) * 60.0f;+ const float p1 = lcg(seed);+ const float spacing = 3.0f + lcg(seed) * 12.0f;+ path.addSample(x, y, p, p1, spacing, false, a);+ ref.addSample(x, y, p, p1, spacing, b);+ p = p1;+ }+ CHECK(a.size() == b.size());+ CHECK(a.size() > 50);+ const size_t n = std::min(a.size(), b.size());+ int bad = 0;+ for (size_t i = 0; i < n; ++i)+ if (!near(a[i].x, b[i].x, 0.01f) || !near(a[i].y, b[i].y, 0.01f) || !near(a[i].pressure, b[i].pressure, 1e-4f)) ++bad;+ CHECK(bad == 0);+}++TEST(stroke_path_dabs_are_evenly_spaced) {+ StrokePath path;+ path.reset(0.0f, 0.0f);+ std::vector<PathDab> out;+ path.addSample(500.0f, 0.0f, 1.0f, 1.0f, 12.5f, false, out);+ path.addSample(500.0f, 300.0f, 1.0f, 1.0f, 12.5f, false, out); // a corner: spacing carries over it+ CHECK(out.size() > 60);+ int bad = 0;+ for (size_t i = 1; i < out.size(); ++i) {+ const float d = std::hypot(out[i].x - out[i - 1].x, out[i].y - out[i - 1].y);+ // across the corner the straight distance is shorter than the spacing, never longer+ if (d > 12.5f + 1e-3f || d < 12.5f * 0.7f) ++bad;+ }+ CHECK(bad == 0);+}++TEST(stroke_path_curve_stays_a_curve_when_samples_are_far_apart) {+ // A circle of radius 300 px sampled every 40 degrees: a chord is 205 px long, 18 px off the circle in the middle.+ const float r = 300.0f, step = 40.0f * 3.14159265f / 180.0f;+ auto deviation = [&](bool smooth) {+ StrokePath path;+ path.reset(r, 0.0f);+ std::vector<PathDab> out;+ size_t from = 0;+ for (int k = 1; k <= 8; ++k) {+ path.addSample(r * std::cos(k * step), r * std::sin(k * step), 1.0f, 1.0f, 15.0f, smooth, out);+ if (k == 2) from = out.size(); // the first piece has no earlier point to curve through+ }+ float worst = 0.0f;+ for (size_t i = from; i < out.size(); ++i) worst = std::max(worst, std::abs(std::hypot(out[i].x, out[i].y) - r));+ return worst;+ };+ const float straight = deviation(false), curved = deviation(true);+ CHECK(straight > 15.0f);+ CHECK(curved < 6.0f);+ CHECK(curved < straight * 0.4f);+}++TEST(stroke_path_curve_ends_on_the_sample_and_keeps_the_spacing) {+ StrokePath path;+ path.reset(0.0f, 0.0f);+ std::vector<PathDab> out;+ path.addSample(100.0f, 0.0f, 0.0f, 0.5f, 10.0f, true, out);+ path.addSample(180.0f, 90.0f, 0.5f, 1.0f, 10.0f, true, out);+ path.addSample(200.0f, 250.0f, 1.0f, 0.2f, 10.0f, true, out);+ CHECK(!out.empty());+ // the last dab is within one spacing of the last sample+ CHECK(std::hypot(out.back().x - 200.0f, out.back().y - 250.0f) <= 10.0f + 1e-3f);+ // pressure stays within what the samples carried+ for (const PathDab& d : out) CHECK(d.pressure >= -1e-4f && d.pressure <= 1.0f + 1e-4f);+}++TEST(stroke_path_hairpin_turn_does_not_loop) {+ StrokePath path;+ path.reset(0.0f, 0.0f);+ std::vector<PathDab> out;+ path.addSample(200.0f, 0.0f, 1.0f, 1.0f, 8.0f, true, out);+ path.addSample(0.0f, 10.0f, 1.0f, 1.0f, 8.0f, true, out); // straight back+ for (const PathDab& d : out) {+ CHECK(std::isfinite(d.x) && std::isfinite(d.y));+ CHECK(d.x > -1.0f && d.x < 201.0f);+ CHECK(d.y > -1.0f && d.y < 11.0f);+ }+}++TEST(stroke_path_dense_samples_barely_change) {+ // At ordinary speeds (gaps under two spacings) smoothing does nothing at all.+ uint32_t seed = 3;+ StrokePath s, t;+ s.reset(0, 0);+ t.reset(0, 0);+ std::vector<PathDab> a, b;+ float x = 0, y = 0;+ for (int i = 0; i < 300; ++i) {+ x += 3.0f + lcg(seed) * 4.0f;+ y += (lcg(seed) - 0.5f) * 6.0f;+ s.addSample(x, y, 1.0f, 1.0f, 10.0f, true, a);+ t.addSample(x, y, 1.0f, 1.0f, 10.0f, false, b);+ }+ CHECK(a.size() == b.size());+ for (size_t i = 0; i < std::min(a.size(), b.size()); ++i) CHECK(near(a[i].x, b[i].x) && near(a[i].y, b[i].y));+}++TEST(dab_queue_keeps_order_and_thins_from_the_old_end) {+ DabQueue q;+ for (int i = 0; i < 100; ++i) q.push({float(i), 0.0f, 1.0f});+ CHECK(q.thin(0) == 0 && q.size() == 100); // 0: never+ const size_t dropped = q.thin(24);+ CHECK(q.size() <= 24 && q.size() > 0);+ CHECK(dropped == 100 - q.size());+ float last = -1.0f, newest = 0.0f;+ bool ordered = true;+ while (!q.empty()) {+ const PathDab d = q.pop();+ if (d.x <= last) ordered = false;+ last = d.x;+ newest = d.x;+ }+ CHECK(ordered);+ CHECK(near(newest, 99.0f)); // the newest dab always stays+}++TEST(dab_queue_under_the_limit_is_untouched) {+ DabQueue q;+ for (int i = 0; i < 10; ++i) q.push({float(i), 0.0f, 1.0f});+ CHECK(q.thin(24) == 0);+ CHECK(q.size() == 10);+ DabQueue one;+ one.push({1.0f, 1.0f, 1.0f});+ CHECK(one.thin(1) == 0 && one.size() == 1);+}