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.

Brush cursor follows the mesh surface (#25)

islandmed9bdde8d25352
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 067543ea..28651747 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,14 @@ All notable changes to SculptForge are listed here. The format follows
## [Unreleased]
+### Added
+- The brush cursor follows the surface (#25), as in SculptGL: over the model the Draw Size and Focal Shift rings
+ lie on the surface under the pointer, turned to its (smoothed) direction and pressed onto its shape, at the
+ brush's real size there, with a short normal line; with symmetry on, a fainter mirrored ring shows too. Every
+ brush (sculpt, paint, mask, dynamic topology). A few dozen BVH ray casts per drawn frame, no pass over the mesh
+ (0.09 ms on 5M triangles), and the idle view still draws nothing. **Preferences > Input > Cursor follows
+ surface** (on by default) brings back the flat screen rings.
+
## [0.9.7] - 2026-10-31
Speed first: big brushes on dense meshes take a third less time per frame, trail the pen by half as far and no
diff --git a/CMakeLists.txt b/CMakeLists.txt
index ff6dc1f0..0b428d55 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -28,6 +28,7 @@ include(cmake/Dependencies.cmake)
add_library(sculptforge_core STATIC
src/core/Mesh.cpp
src/core/BVH.cpp
+ src/core/SurfaceCursor.cpp
src/core/IndexBits.cpp
src/core/ThreadPool.cpp
src/core/UploadOrder.cpp
diff --git a/docs/guide/interface.md b/docs/guide/interface.md
index 6baf6fa7..ccf6b12f 100644
--- a/docs/guide/interface.md
+++ b/docs/guide/interface.md
@@ -439,7 +439,8 @@ the numpad views and Blender's sculpt-mode keys (see [Blender keys](shortcuts.md
style, **Emulate Numpad** makes the number row work as the numpad, and **Import Blender keymap...** takes the keys
from a keymap you exported in Blender. **Right click opens the QuickMenu** (on by default, in every style) opens
the [QuickMenu](sculpting.md#the-quickmenu) with a right click on the canvas; a right drag navigates either
-way. **Rotation** chooses free rotation (ZBrush) or a turntable. See
+way. **Cursor follows surface** (on by default) lays the brush rings on the model under the pointer (see
+[Draw Size and Focal Shift](sculpting.md#draw-size-z-intensity-rgb-intensity-and-focal-shift)); off, they are flat circles on the screen. **Rotation** chooses free rotation (ZBrush) or a turntable. See
[Coming from ZBrush](coming-from-zbrush.md).
### The background
diff --git a/docs/guide/sculpting.md b/docs/guide/sculpting.md
index aff55753..44e955a3 100644
--- a/docs/guide/sculpting.md
+++ b/docs/guide/sculpting.md
@@ -138,6 +138,11 @@ The brush cursor shows two rings, as in ZBrush: the outer one is the Draw Size,
(where the brush works at half strength). Masking, painting, Move and SnakeHook follow Focal Shift too; custom
brushes made in Brush Lab keep their own tip shape.
+Over the model, the rings lie on the surface, as in SculptGL: they turn with the surface under the pointer, bend
+over its bumps and curves, and show the brush's real size there, with a short line pointing out of the surface.
+With symmetry on, a fainter ring shows where the mirrored brush lands. Off the model the rings are flat circles.
+**Preferences > Input > Cursor follows surface** (on by default) switches back to flat rings everywhere.
+
The <kbd>S</kbd>, <kbd>U</kbd>, <kbd>I</kbd> and <kbd>O</kbd> pop-ups take the mouse or the keyboard: drag the
slider and release to close it, or type a number and press <kbd>Enter</kbd> (a minus first for a negative Focal
Shift). <kbd>Esc</kbd> closes the pop-up without typing anything new.
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 20b9c572..87d673d2 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -2592,6 +2592,64 @@ void App::drawPalette_Splats() {
drawSculptableSection(); // Make sculptable (PanelSculptable.cpp)
}
+bool App::drawSurfaceCursor(ImDrawList* dl, float radiusPx, ImU32 col) {
+ // Only what brushes work on: the active, visible SubTool with an up-to-date BVH (a stale one, after a
+ // whole-mesh change, is rebuilt at the next press; until then the flat ring shows), not an LOD preview.
+ if (previewLod_ >= 0 || doc_.bvhDirty) return false;
+ RayHit hit;
+ if (!pick(mouseX_, mouseY_, hit)) return false; // one ray, as a press would cast
+ // The world radius a dab here gets (App::firstDab / the brushes: Draw Size times world size of a pixel).
+ const float radius = radiusPx * camera_.worldPerPixel(hit.position, canvasHeight());
+ if (!(radius > 0.0f) || !std::isfinite(radius)) return false;
+ // A steady normal (8 rays), the ring pressed onto the surface (48) and the Focal Shift ring (32): a few dozen
+ // BVH ray casts, only on frames that are drawn anyway, never a pass over the mesh.
+ const glm::vec3 n = surfaceCursorNormal(doc_.mesh, doc_.bvh, hit, radius);
+ surfaceCursorRing(doc_.mesh, doc_.bvh, hit.position, n, radius, 48, cursorRing_);
+ const float focal = focalRingFraction(focalShift_);
+ surfaceCursorRing(doc_.mesh, doc_.bvh, hit.position, n, radius * focal, 32, cursorInner_);
+
+ const glm::vec3 eye = camera_.position(), forward = camera_.forward();
+ const bool ortho = camera_.ortho;
+ auto facing = [&](const glm::vec3& p, const glm::vec3& pn) {
+ return glm::dot(pn, ortho ? -forward : eye - p) > 0.0f;
+ };
+ const ImU32 inner = IM_COL32(255, 255, 255, 90);
+ // Closed polyline through the points facing the camera; a point on the far side of a curve breaks the line.
+ auto drawRing = [&](const std::vector<SurfaceRingPoint>& ring, const glm::vec3& m, ImU32 colour, float width) {
+ const size_t count = std::min<size_t>(ring.size(), 64);
+ ImVec2 sp[64];
+ bool ok[64];
+ for (size_t i = 0; i < count; ++i)
+ ok[i] = facing(ring[i].position * m, ring[i].normal * m) && gizmoProject(ring[i].position * m, sp[i]);
+ for (size_t i = 0; i < count; ++i) {
+ const size_t j = (i + 1) % count;
+ if (ok[i] && ok[j]) dl->AddLine(sp[i], sp[j], colour, width);
+ }
+ };
+ auto fade = [](ImU32 colour, float k) {
+ const ImU32 a = ImU32(float((colour >> IM_COL32_A_SHIFT) & 0xFF) * k);
+ return (colour & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
+ };
+ // The mirrored rings first (fainter), as the brush mirrors its dabs (Sculptor::mirrors; the first is this one).
+ const std::vector<glm::vec3> mirrors = Sculptor::mirrors(symmetry_);
+ for (size_t k = mirrors.size(); k-- > 0;) {
+ const glm::vec3& m = mirrors[k];
+ const bool self = k == 0;
+ // A mirror that lands on the cursor's own ring (hovering on the plane) adds nothing.
+ if (!self && glm::length(hit.position * m - hit.position) < radius * 0.05f) continue;
+ if (!self && !facing(hit.position * m, n * m)) continue;
+ drawRing(cursorRing_, m, self ? col : fade(col, 0.45f), self ? 2.0f : 1.25f);
+ drawRing(cursorInner_, m, self ? inner : fade(inner, 0.6f), 1.0f);
+ }
+ // The surface's direction: a short line out of the centre (with a dot where the brush touches).
+ ImVec2 c0, c1;
+ if (gizmoProject(hit.position, c0) && gizmoProject(hit.position + n * (radius * 0.4f), c1)) {
+ dl->AddLine(c0, c1, fade(col, 0.85f), 1.5f);
+ dl->AddCircleFilled(c0, 2.0f * uiScale_, col);
+ }
+ return true;
+}
+
void App::drawBrushCursor() {
ImDrawList* dl = ImGui::GetForegroundDrawList();
const CanvasRect canvas = canvasRect();
@@ -2622,9 +2680,12 @@ void App::drawBrushCursor() {
const glm::vec3 pc = linearToSrgb(inverted ? glm::vec3(1.0f) : doc_.paintColor);
col = ImGui::GetColorU32(ImVec4(pc.x, pc.y, pc.z, 0.9f));
}
- dl->AddCircle(c, r, col, 64, 1.5f);
- // The inner ring is Focal Shift, as in ZBrush: where the falloff drops to half.
- dl->AddCircle(c, r * focalRingFraction(focalShift_), IM_COL32(255, 255, 255, 90), 48, 1.0f);
+ surfaceCursorShown_ = uiPrefs_.cursorFollowsSurface && drawSurfaceCursor(dl, r, col);
+ if (!surfaceCursorShown_) {
+ dl->AddCircle(c, r, col, 64, 1.5f);
+ // The inner ring is Focal Shift, as in ZBrush: where the falloff drops to half.
+ dl->AddCircle(c, r * focalRingFraction(focalShift_), IM_COL32(255, 255, 255, 90), 48, 1.0f);
+ }
if (strokeType_ == StrokeType::LazyMouse && drag_ == Drag::Stroke) {
// The string from the cursor to the lagging brush point.
const ImVec2 lp(lazyMouse_.point.x, lazyMouse_.point.y);
diff --git a/src/app/App.h b/src/app/App.h
index fffafe32..b1e0a866 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -25,6 +25,7 @@
#include "core/QRemesh.h"
#include "core/Stroke.h"
#include "core/StrokePath.h"
+#include "core/SurfaceCursor.h"
#include "core/SpaceMouse.h"
#include "core/Tablet.h"
#include "core/UpdateCheck.h"
@@ -172,6 +173,11 @@ private:
void pollBrushRequest();
const BrushRecipe* activeRecipe() const;
void drawBrushCursor();
+ // The brush ring lying on the surface under the pointer (#25, Preferences > Input > Cursor follows surface);
+ // false when the pointer is off the model (the flat screen ring is drawn instead).
+ bool drawSurfaceCursor(ImDrawList* dl, float radiusPx, ImU32 col);
+ std::vector<SurfaceRingPoint> cursorRing_, cursorInner_; // scratch, kept to avoid allocating per frame
+ bool surfaceCursorShown_ = false; // the last cursor drawn lay on the surface (UI tests: surface_cursor)
void updateTitle();
int runRecording(); // also runs UI tests (options_.uiTest)
diff --git a/src/app/Config.cpp b/src/app/Config.cpp
index ac6e7afe..406f9f5a 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -50,6 +50,7 @@ Json toJson(const UiPrefs& p) {
j.set("inputStyle", std::string(p.inputStyle == 2 ? "blender" : p.inputStyle == 1 ? "sculptforge" : "zbrush"));
j.set("emulateNumpad", p.emulateNumpad);
j.set("rightClickQuickMenu", p.rightClickQuickMenu);
+ j.set("cursorFollowsSurface", p.cursorFollowsSurface);
j.set("alphabeticalPalettes", p.alphabeticalPalettes);
j.set("tablet", toJson(p.tablet));
j.set("spaceMouse", toJson(p.spaceMouse));
@@ -84,6 +85,7 @@ void fromJson(const Json& j, UiPrefs& p) {
}
p.emulateNumpad = j["emulateNumpad"].asBool(p.emulateNumpad);
p.rightClickQuickMenu = j["rightClickQuickMenu"].asBool(p.rightClickQuickMenu);
+ p.cursorFollowsSurface = j["cursorFollowsSurface"].asBool(p.cursorFollowsSurface);
p.alphabeticalPalettes = j["alphabeticalPalettes"].asBool(p.alphabeticalPalettes);
fromJson(j["tablet"], p.tablet);
fromJson(j["spaceMouse"], p.spaceMouse);
diff --git a/src/app/Config.h b/src/app/Config.h
index 2f6dc245..ad2f7ef8 100644
--- a/src/app/Config.h
+++ b/src/app/Config.h
@@ -34,6 +34,7 @@ struct UiPrefs {
// 2 Blender (middle-drag orbit, numpad views, Blender's sculpt keys; Input.cpp)
bool emulateNumpad = false; // Blender style: the 1-9 and 0 keys above the letters act as the numpad (laptops)
bool rightClickQuickMenu = true; // a right click on the canvas (no drag) opens the QuickMenu, as in ZBrush (#22)
+ bool cursorFollowsSurface = true; // the brush ring lies on the surface under the pointer, as in SculptGL (#25)
TabletSettings tablet; // Preferences > Tablet: pressure curve, eraser, pen buttons
SpaceMouseSettings spaceMouse; // Preferences > Input > SpaceMouse
// Preferences > Performance (PanelPerformance.cpp).
diff --git a/src/app/Input.cpp b/src/app/Input.cpp
index 4237d243..2c27b8d0 100644
--- a/src/app/Input.cpp
+++ b/src/app/Input.cpp
@@ -136,6 +136,13 @@ void App::registerInputActions() {
"does too). A right drag still turns, pans or zooms the view. A pen button set to Right click works the same.",
[this] { uiPrefs_.rightClickQuickMenu = !uiPrefs_.rightClickQuickMenu; },
[this] { return uiPrefs_.rightClickQuickMenu; });
+ add("input.surface_cursor", "Cursor follows surface", nullptr, "Preferences > Input", "",
+ "The brush ring lies on the model under the pointer, turned to the surface and pressed onto its bumps, at "
+ "the brush's real size there (as in SculptGL), with a short line along the surface's direction. With "
+ "symmetry on, the mirrored ring shows too. Off the model, and with this off, the ring is a flat circle on "
+ "the screen.",
+ [this] { uiPrefs_.cursorFollowsSurface = !uiPrefs_.cursorFollowsSurface; },
+ [this] { return uiPrefs_.cursorFollowsSurface; });
add("input.import_blender", "Import Blender keymap...", ICON_LC_FILE_INPUT, "Preferences > Input", "",
"Use the keys from a keymap you exported in Blender (Preferences > Keymap > Export, a .py file). Switches "
"to the Blender style, then takes the navigation and sculpt keys SculptForge has an equivalent for. The "
@@ -397,6 +404,10 @@ void App::drawInputSection() {
if (ui::Checkbox("Right click opens the QuickMenu##input.right_click_menu", &rightClickMenu))
uiPrefs_.rightClickQuickMenu = rightClickMenu;
ui::HelpAction(*this, "input.right_click_menu");
+ bool surfaceCursor = uiPrefs_.cursorFollowsSurface;
+ if (ui::Checkbox("Cursor follows surface##input.surface_cursor", &surfaceCursor))
+ uiPrefs_.cursorFollowsSurface = surfaceCursor;
+ ui::HelpAction(*this, "input.surface_cursor");
ui::ActionButton(*this, "input.import_blender", ImVec2(-FLT_MIN, 0), ui::Look::IconLabel);
ImGui::TextDisabled("Rotation");
ImGui::SameLine();
diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cpp
index 41adc74d..b1595968 100644
--- a/src/app/UiTest.cpp
+++ b/src/app/UiTest.cpp
@@ -7,6 +7,9 @@
// "Brush Lab/Save settings" for the one in that window).
//
// click LABEL / double_click LABEL / right_click LABEL / hover LABEL
+// hover_model U V [S] glide the mouse (no button) to a point on the model (fractions of its on-screen bounds,
+// snapped onto the sculpt like stroke), e.g. to show the brush cursor
+// hover_window X Y [S] the same to window fractions (anywhere, e.g. the background)
// type LABEL TEXT click a text field and type into it
// key COMBO e.g. enter, escape, ctrl+z, ctrl+shift+z, 3, comma, backtick, tab, f3, space, minus,
// home, numpad1, ctrl+numpad7, numpad., numpadplus
@@ -70,6 +73,8 @@
// moved_out (summed movement along the snapshot's normals: > 0 out, < 0 in),
// pen_pressure (raw), brush_pressure (after the curve; 1 for the mouse),
// stroking (1 while a stroke is open), cursor_x / cursor_y (the brush cursor, pixels),
+// surface_cursor (1 when the brush ring last drawn lay on the surface, #25),
+// cursor_follows_surface (Preferences > Input, 1 on),
// camera_yaw / camera_pitch / camera_roll (degrees),
// camera_up (the view's up vector . world Y), camera_aligned (1 when looking along a world
// axis), camera_distance, camera_pan (target offset);
@@ -565,6 +570,8 @@ double Demo::query(const std::string& name, bool& known) const {
if (name == "stroking") return app_.drag_ == App::Drag::Stroke ? 1.0 : 0.0;
if (name == "cursor_x") return app_.mouseX_;
if (name == "cursor_y") return app_.mouseY_;
+ if (name == "surface_cursor") return app_.surfaceCursorShown_ ? 1.0 : 0.0;
+ if (name == "cursor_follows_surface") return app_.uiPrefs_.cursorFollowsSurface ? 1.0 : 0.0;
if (name == "camera_yaw") return glm::degrees(app_.camera_.yaw);
if (name == "camera_pitch") return glm::degrees(app_.camera_.pitch);
if (name == "camera_roll") return glm::degrees(app_.camera_.roll);
@@ -740,6 +747,24 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& e
return t > 3.0f;
});
wait(0.6f); // tooltips appear after a short delay
+ } else if (verb == "hover_model" || verb == "hover_window") {
+ if (!need(2)) return false;
+ const float u = num(1, 0.5f), v = num(2, 0.5f), seconds = num(3, 0.3f);
+ const bool window = verb == "hover_window";
+ auto from = std::make_shared<ImVec2>();
+ auto to = std::make_shared<ImVec2>();
+ steps_.push_back([this, from, to, u, v, seconds, window](float t) {
+ if (t == 0.0f) {
+ *from = mouse_;
+ int ww = 0, wh = 0;
+ SDL_GetWindowSize(app_.window_, &ww, &wh);
+ *to = window ? ImVec2(u * float(ww), v * float(wh)) : onModel(u, v);
+ }
+ const float k = std::min(t / seconds, 1.0f);
+ mouseMotion(from->x + (to->x - from->x) * k, from->y + (to->y - from->y) * k);
+ return t >= seconds;
+ });
+ wait(0.05f);
} else if (verb == "type") {
if (!need(2)) return false;
testClick(line, w[1], SDL_BUTTON_LEFT, false);
diff --git a/src/core/SurfaceCursor.cpp b/src/core/SurfaceCursor.cpp
new file mode 100644
index 00000000..8269f247
--- /dev/null
+++ b/src/core/SurfaceCursor.cpp
@@ -0,0 +1,94 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/SurfaceCursor.h"
+
+#include <cmath>
+
+namespace sf {
+
+namespace {
+
+// Two unit vectors spanning the plane with normal `n`.
+void tangentBasis(const glm::vec3& n, glm::vec3& u, glm::vec3& v) {
+ const glm::vec3 a = std::abs(n.x) < 0.9f ? glm::vec3(1, 0, 0) : glm::vec3(0, 1, 0);
+ u = glm::normalize(glm::cross(n, a));
+ v = glm::cross(n, u);
+}
+
+glm::vec3 safeNormalize(const glm::vec3& v, const glm::vec3& fallback) {
+ const float len = glm::length(v);
+ return len > 1e-12f && std::isfinite(len) ? v / len : fallback;
+}
+
+// Presses `p` onto the surface along -n, looking from `reach` above the plane down to `reach` below it.
+bool pressOnto(const Mesh& mesh, const BVH& bvh, const glm::vec3& p, const glm::vec3& n, float reach, RayHit& hit) {
+ if (!bvh.raycast(mesh, p + n * reach, -n, hit)) return false;
+ return hit.t <= 2.0f * reach;
+}
+
+} // namespace
+
+glm::vec3 interpolatedNormal(const Mesh& mesh, const RayHit& hit) {
+ if (hit.triangle >= mesh.triangles.size()) return hit.normal;
+ const glm::uvec3 t = mesh.triangles[hit.triangle];
+ if (mesh.normals.size() != mesh.positions.size() || t.x >= mesh.normals.size() || t.y >= mesh.normals.size() ||
+ t.z >= mesh.normals.size())
+ return hit.normal;
+ // Barycentric coordinates of the hit point.
+ const glm::vec3 a = mesh.positions[t.x], b = mesh.positions[t.y], c = mesh.positions[t.z];
+ const glm::vec3 e0 = b - a, e1 = c - a, ep = hit.position - a;
+ const float d00 = glm::dot(e0, e0), d01 = glm::dot(e0, e1), d11 = glm::dot(e1, e1);
+ const float d20 = glm::dot(ep, e0), d21 = glm::dot(ep, e1);
+ const float den = d00 * d11 - d01 * d01;
+ if (!(std::abs(den) > 1e-30f)) return hit.normal;
+ const float v = (d11 * d20 - d01 * d21) / den;
+ const float w = (d00 * d21 - d01 * d20) / den;
+ const float u = 1.0f - v - w;
+ glm::vec3 n = mesh.normals[t.x] * u + mesh.normals[t.y] * v + mesh.normals[t.z] * w;
+ n = safeNormalize(n, hit.normal);
+ // Vertex normals wound the other way from the triangle (a flipped import): keep the side the ray came from.
+ return glm::dot(n, hit.normal) < -0.2f ? hit.normal : n;
+}
+
+glm::vec3 surfaceCursorNormal(const Mesh& mesh, const BVH& bvh, const RayHit& hit, float radius, int samples) {
+ const glm::vec3 n0 = interpolatedNormal(mesh, hit);
+ if (!(radius > 0.0f) || samples <= 0) return n0;
+ glm::vec3 u, v;
+ tangentBasis(n0, u, v);
+ const float r = radius * 0.5f;
+ glm::vec3 sum = n0 * 2.0f; // the centre counts double: the cursor sits there
+ for (int i = 0; i < samples; ++i) {
+ const float a = 6.28318531f * float(i) / float(samples);
+ const glm::vec3 p = hit.position + (u * std::cos(a) + v * std::sin(a)) * r;
+ RayHit h;
+ if (!pressOnto(mesh, bvh, p, n0, r, h)) continue;
+ const glm::vec3 n = interpolatedNormal(mesh, h);
+ if (glm::dot(n, n0) > 0.0f) sum += n;
+ }
+ return safeNormalize(sum, n0);
+}
+
+void surfaceCursorRing(const Mesh& mesh, const BVH& bvh, const glm::vec3& center, const glm::vec3& normal, float radius,
+ int count, std::vector<SurfaceRingPoint>& out) {
+ out.clear();
+ if (count <= 0 || !(radius > 0.0f)) return;
+ const glm::vec3 n = safeNormalize(normal, glm::vec3(0, 0, 1));
+ glm::vec3 u, v;
+ tangentBasis(n, u, v);
+ out.reserve(size_t(count));
+ for (int i = 0; i < count; ++i) {
+ const float a = 6.28318531f * float(i) / float(count);
+ SurfaceRingPoint p;
+ p.position = center + (u * std::cos(a) + v * std::sin(a)) * radius;
+ p.normal = n;
+ RayHit h;
+ if (pressOnto(mesh, bvh, p.position, n, radius, h)) {
+ p.position = h.position;
+ p.normal = interpolatedNormal(mesh, h);
+ p.onSurface = true;
+ }
+ out.push_back(p);
+ }
+}
+
+} // namespace sf
diff --git a/src/core/SurfaceCursor.h b/src/core/SurfaceCursor.h
new file mode 100644
index 00000000..7c37637a
--- /dev/null
+++ b/src/core/SurfaceCursor.h
@@ -0,0 +1,43 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// The brush cursor lying on the surface (#25), as in SculptGL: a circle of the brush's world radius around the
+// point under the pointer, in the plane of the surface there, each point pressed onto the mesh so the ring follows
+// bumps and curves instead of floating flat in screen space.
+//
+// Cost: a few dozen BVH ray casts (each O(log n)) per cursor update, nothing that walks the whole mesh, so it stays
+// cheap at tens of millions of triangles. The app only calls it on frames it draws anyway (pointer moved, stroke,
+// view change), so the idle view stays at 0 fps.
+#pragma once
+
+#include "core/BVH.h"
+#include "core/Mesh.h"
+
+#include <glm/glm.hpp>
+
+#include <vector>
+
+namespace sf {
+
+struct SurfaceRingPoint {
+ glm::vec3 position{0.0f};
+ glm::vec3 normal{0.0f}; // the surface's there (the ring's own where nothing was hit)
+ bool onSurface = false; // pressed onto the mesh; false: left in the ring's plane (over a hole or an edge)
+};
+
+// The shading normal at a ray hit: the vertex normals blended across the hit triangle (smoother than the
+// triangle's own normal on a coarse mesh); the triangle's normal if the mesh has no usable vertex normals.
+glm::vec3 interpolatedNormal(const Mesh& mesh, const RayHit& hit);
+
+// A steady normal for the cursor at `hit`: the shading normal there averaged with the normals at `samples` points
+// of a ring of half the brush radius pressed onto the surface (an area normal, so the ring doesn't wobble from
+// triangle to triangle as the pointer moves over fine detail). Points facing away from the centre's normal (the
+// far side of a thin part) are left out.
+glm::vec3 surfaceCursorNormal(const Mesh& mesh, const BVH& bvh, const RayHit& hit, float radius, int samples = 8);
+
+// `count` points of the circle of `radius` about `center` in the plane through it with `normal`, each pressed
+// onto the mesh along -normal (from up to `radius` above the plane to `radius` below it). Clears `out` first.
+void surfaceCursorRing(const Mesh& mesh, const BVH& bvh, const glm::vec3& center, const glm::vec3& normal, float radius,
+ int count, std::vector<SurfaceRingPoint>& out);
+
+} // namespace sf
diff --git a/tests/test_surface_cursor.cpp b/tests/test_surface_cursor.cpp
new file mode 100644
index 00000000..321bfbd9
--- /dev/null
+++ b/tests/test_surface_cursor.cpp
@@ -0,0 +1,79 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// The brush cursor on the surface (core/SurfaceCursor.h, #25).
+#include "TestHarness.h"
+
+#include "core/BVH.h"
+#include "core/Primitives.h"
+#include "core/SurfaceCursor.h"
+
+#include <chrono>
+#include <cmath>
+#include <cstdio>
+#include <vector>
+
+using namespace sf;
+
+TEST(surface_cursor_ring_lies_on_sphere) {
+ Mesh m = makeIcosphere(5, 1.0f);
+ BVH bvh;
+ bvh.build(m);
+ RayHit hit;
+ CHECK(bvh.raycast(m, glm::vec3(0.2f, 0.3f, 5.0f), glm::vec3(0.0f, 0.0f, -1.0f), hit));
+ // The steady normal is the sphere's (radial) there, not just the hit triangle's.
+ const glm::vec3 n = surfaceCursorNormal(m, bvh, hit, 0.3f);
+ CHECK(glm::dot(n, glm::normalize(hit.position)) > 0.999f);
+ std::vector<SurfaceRingPoint> ring;
+ surfaceCursorRing(m, bvh, hit.position, n, 0.3f, 48, ring);
+ CHECK(ring.size() == 48);
+ for (const SurfaceRingPoint& p : ring) {
+ CHECK(p.onSurface);
+ // On the (faceted) sphere, not in the flat plane touching it.
+ CHECK(std::abs(glm::length(p.position) - 1.0f) < 0.01f);
+ // About the brush radius from the centre (pressed down onto the curve, a little further).
+ const float d = glm::length(p.position - hit.position);
+ CHECK(d > 0.299f && d < 0.31f);
+ CHECK(glm::dot(p.normal, glm::normalize(p.position)) > 0.99f);
+ }
+}
+
+TEST(surface_cursor_ring_flat_off_edge) {
+ // Near the edge of a plane: points past the edge stay in the ring's plane, marked off the surface.
+ Mesh m = makePlane(16, 2.0f);
+ BVH bvh;
+ bvh.build(m);
+ const AABB b = m.bounds();
+ glm::vec3 up(0.0f);
+ const glm::vec3 ext = b.max - b.min;
+ up[ext.x < ext.y && ext.x < ext.z ? 0 : ext.y < ext.z ? 1 : 2] = 1.0f; // the plane's flat axis
+ const glm::vec3 c = (b.min + b.max) * 0.5f + ext * 0.45f * (glm::vec3(1.0f) - up);
+ RayHit hit;
+ CHECK(bvh.raycast(m, c + up * 3.0f, -up, hit));
+ std::vector<SurfaceRingPoint> ring;
+ surfaceCursorRing(m, bvh, hit.position, interpolatedNormal(m, hit), 0.5f, 32, ring);
+ int on = 0, off = 0;
+ for (const SurfaceRingPoint& p : ring) (p.onSurface ? on : off)++;
+ CHECK(on > 0 && off > 0);
+}
+
+TEST(surface_cursor_cost_is_rays_not_mesh_passes) {
+ // A cursor update is ~90 ray casts: on a 5M-triangle sphere it stays well under a millisecond (it walks the
+ // BVH, never the mesh). Generous bound so slow CI machines and debug builds pass.
+ Mesh m = makeIcosphere(9, 1.0f);
+ BVH bvh;
+ bvh.build(m);
+ std::vector<SurfaceRingPoint> ring, inner;
+ const int n = 200;
+ const auto t0 = std::chrono::steady_clock::now();
+ for (int i = 0; i < n; ++i) {
+ RayHit hit;
+ CHECK(bvh.raycast(m, glm::vec3(-0.5f + float(i) / float(n), 0.2f, 5.0f), glm::vec3(0, 0, -1), hit));
+ const glm::vec3 nn = surfaceCursorNormal(m, bvh, hit, 0.3f);
+ surfaceCursorRing(m, bvh, hit.position, nn, 0.3f, 48, ring);
+ surfaceCursorRing(m, bvh, hit.position, nn, 0.15f, 32, inner);
+ }
+ const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count() / n;
+ std::printf(" surface cursor on %zu triangles: %.3f ms per update\n", m.triangles.size(), ms);
+ CHECK(ms < 5.0);
+}
diff --git a/tests/ui/surface_cursor.sfui b/tests/ui/surface_cursor.sfui
new file mode 100644
index 00000000..871a1b8f
--- /dev/null
+++ b/tests/ui/surface_cursor.sfui
@@ -0,0 +1,51 @@
+# The brush cursor follows the surface (#25): over the model the ring lies on it, turned to the surface and
+# pressed onto its shape, at the brush's real size there; off the model it is the flat screen ring. A preference
+# in Preferences > Input (on by default), kept by Store Config.
+run new_head
+camera 35 10
+key f
+expect_value cursor_follows_surface == 1
+
+# On the cheek, seen at an angle: the ring lies on the surface.
+hover_model 0.62 0.55
+expect_value surface_cursor == 1
+shot on-surface
+
+# From the front with X symmetry (on by default): the mirrored ring shows, fainter, on the other cheek.
+camera 0 0
+key f
+hover_model 0.3 0.55
+expect_value surface_cursor == 1
+shot symmetry
+camera 35 10
+key f
+
+# A bigger brush: the ring wraps around the curve.
+key ]
+key ]
+key ]
+key ]
+key ]
+key ]
+key ]
+key ]
+key ]
+hover_model 0.6 0.4
+expect_value surface_cursor == 1
+shot on-surface-big
+
+# Off the model: the flat screen ring.
+hover_window 0.68 0.5
+expect_value surface_cursor == 0
+shot off-surface
+
+# Preferences > Input turns it off.
+click "Preferences##palette.preferences"
+click "Input##preferences.input"
+expect "Cursor follows surface##input.surface_cursor"
+click "Cursor follows surface##input.surface_cursor"
+expect_value cursor_follows_surface == 0
+key escape
+hover_model 0.6 0.4
+expect_value surface_cursor == 0
+shot flat-ring