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.

Tablet support: eraser, pen buttons, global pressure curve, Preferences > Tablet

islandmed4bdda1db8144
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9a1cd569..6c517457 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,20 @@ All notable changes to SculptForge are listed here. The format follows
shortcuts (Ctrl+Alt+click a button, then press a key). Tab hides the shelves.
- Lucide icons (ISC/MIT). Brush Lab now opens from the "AI Brush" button instead of covering the model at start.
+### Graphics tablets
+- Preferences > Tablet: the pen in use, a live pressure meter, a draw-test area that shows the pressure along
+ your stroke, a global pressure curve (Soft / Linear / Firm, curve, min / max, threshold, full-pressure point)
+ applied before each brush's own curve, Pressure > Strength / Size, and the pen's tilt when reported.
+- The eraser end inverts the brush (Ctrl + eraser erases mask); it can be set to Smooth, Erase mask or Nothing.
+- Pen side buttons are mapped by SculptForge instead of SDL's version-dependent clicks: lower = right-click
+ (drag to rotate, context menus), upper = Alt (invert), third = pan; each can be Invert, Smooth, Rotate view,
+ Pan view, Right-click or Nothing.
+- No pressure spike at the start of a stroke (the first dab waits for the touch's own pressure sample), every
+ pen sample is used with the pressure interpolated between samples, the mouse always presses fully, and a pen
+ that leaves the tablet's range mid-stroke ends the stroke cleanly.
+- UI tests drive a simulated pen (`pen_stroke`, `pen_button`, `pen_hover`, ...), see tests/ui/tablet.sfui.
+ Guide: docs/tablet.md.
+
### ComfyUI
- Generate 3D can run on your own ComfyUI (local or a studio GPU server): any API-format workflow, with
ready-made Hunyuan3D 2.1 image-to-3D and FLUX + Hunyuan3D text-to-3D workflows, a connection test, queue
diff --git a/CMakeLists.txt b/CMakeLists.txt
index b9a25fd2..8c696354 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -53,6 +53,7 @@ add_library(sculptforge_core STATIC
src/core/Polypaint.cpp
src/core/Matcap.cpp
src/core/Project.cpp
+ src/core/Tablet.cpp
src/io/ObjIO.cpp
src/io/FbxIO.cpp
third_party/ufbx/ufbx.c
@@ -148,6 +149,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/PanelGoz.cpp
src/app/PanelProject.cpp
src/app/PanelSubTools.cpp
+ src/app/Tablet.cpp
src/render/GL.cpp
src/render/Camera.cpp
src/render/Renderer.cpp
diff --git a/README.md b/README.md
index 07d2cfef..d5736af9 100644
--- a/README.md
+++ b/README.md
@@ -247,6 +247,9 @@ argument `--mcp`. The agent gets every command as a tool and works on one live s
| Select a SubTool | Alt + click it |
| Show all | Ctrl+Shift + click on the background |
| Hide outside / inside a rectangle | Ctrl+Shift + drag / Ctrl+Shift+Alt + drag |
+| Pen pressure | Strength (and optionally size); curve and test area in **Preferences > Tablet** |
+| Pen eraser end | Inverts the brush (Ctrl + eraser erases mask); or Smooth / Erase mask |
+| Pen side buttons | Lower: right-click (drag to rotate), upper: Alt (invert), third: pan; remappable |
| Brush size | `[` / `]` |
| Select brush | `1`–`9`, `0` |
| Paint brush / pick colour | `P` / `C` |
@@ -258,6 +261,9 @@ argument `--mcp`. The agent gets every command as a tool and works on one live s
| Export GLB | Ctrl+E |
| Send to Unreal | Ctrl+U |
+Graphics tablets (Wacom, XP-Pen, Huion ...) work through the system's tablet driver on Windows (Windows Ink),
+macOS and Linux (Wayland / X11). Setup and mappings: [docs/tablet.md](docs/tablet.md).
+
## Project layout
```
diff --git a/docs/tablet.md b/docs/tablet.md
new file mode 100644
index 00000000..cad82dc7
--- /dev/null
+++ b/docs/tablet.md
@@ -0,0 +1,81 @@
+# Graphics tablets
+
+SculptForge reads pens through SDL3, which uses each system's own tablet support: **Windows Ink** on Windows,
+the native tablet events on **macOS**, and **Wayland** (tablet-v2) or **X11** (XInput2) on Linux. Any pen the
+system sees with pressure works: Wacom Intuos, Cintiq and One, XP-Pen, Huion, Gaomon, Surface Pen and others.
+Nothing needs to be turned on in SculptForge: pressure is used as soon as the pen touches the canvas.
+
+Open **Preferences > Tablet** to check the pen and tune it:
+
+- **Pen**: whether a pen has been seen, whether it is in range or touching (and with which end), the display
+ server, and on Linux the device's name. SDL 3.4 and later also says whether it's a pen display or a tablet.
+- **Pressure meter**: the pressure the tablet reports, and what brushes get after the curve below.
+- **Draw-test area**: draw in it with the pen; the stroke is as thick as the brush pressure and the line along
+ the bottom plots the pressure along the stroke. Good for checking a light touch and a full press.
+- **Pressure curve** (all brushes): Soft / Linear / Firm presets, or set it yourself: **Curve** (below 1 soft,
+ above 1 firm), **Min** / **Max** (brush pressure at the lightest touch and at full press), **Threshold**
+ (pen pressure below it counts as the lightest touch) and **Full at** (pen pressure that already counts as a
+ full press, for a light hand). It applies before each brush's own pressure curve (Brush Lab recipes).
+- **Pressure > Strength / Size**: the same toggles as on the top shelf. Strength is on by default.
+- **Tilt**: shown when the pen reports it (brushes don't use it yet).
+- **Eraser** and the **side buttons**, below.
+
+Settings are kept with the UI configuration: **Store Config (Ctrl+Shift+I)** saves them (as in ZBrush, nothing
+is saved automatically).
+
+## Eraser and side buttons
+
+| Pen | Default | Choices |
+|---|---|---|
+| Eraser end | **Invert (Alt)**: brushes subtract; Ctrl + eraser erases mask | Invert, Smooth (Shift), Erase mask, Nothing |
+| Lower side button (nearer the tip) | **Right-click**: drag to rotate the view (Shift: pan), context menus in the UI | Right-click, Invert (Alt), Smooth (Shift), Rotate view, Pan view, Nothing |
+| Upper side button | **Invert (Alt)** while held | same |
+| Third button (e.g. Wacom Pro Pen 3D) | **Pan view** | same |
+
+The defaults follow the usual ZBrush setup: Alt on the pen to carve without reaching for the keyboard, and
+right-click to turn the model. Invert and Smooth act exactly like holding Alt or Shift, so Alt + click on
+another SubTool selects it and Alt + drag on the background pans. Rotate view and Pan view: hold the button
+and move the pen above the tablet (or drag with the tip down).
+
+SDL also turns pen buttons into mouse clicks, but which mouse button depends on the SDL version, so
+SculptForge ignores those and uses the mapping above. If the tablet driver itself turns a side button into a
+keystroke or a mouse click (Wacom Tablet Properties, the XP-Pen or Huion driver), SculptForge receives that
+key or click instead of a pen button: a driver right-click still rotates the view, and a driver Alt still
+inverts.
+
+## Setup by system
+
+**Windows**: SculptForge uses Windows Ink. Wacom: Wacom Tablet Properties > Grip Pen > Mapping, keep **Use
+Windows Ink** checked (without it Windows sees only a mouse, without pressure). XP-Pen and Huion drivers have a
+"Windows Ink" option that must be on as well. Surface pens work as they are. If strokes start late or the
+cursor shows a ripple, turn off "Press and hold for right-click" and the pen feedback in Windows Settings >
+Bluetooth & devices > Pen & Windows Ink.
+
+**macOS**: install the tablet maker's driver and allow it under System Settings > Privacy & Security >
+Accessibility (and Input Monitoring) so it can send pressure. Sidecar with an Apple Pencil works too.
+
+**Linux**: the kernel (wacom, hid-uclogic for many XP-Pen / Huion / Gaomon models) and libinput do the work.
+On Wayland, GNOME (Settings > Wacom Tablet) and KDE Plasma (System Settings > Drawing Tablet) map the tablet to
+a screen and set the pen buttons; on X11 the xf86-input-wacom driver and `xsetwacom` do the same. To check
+that pressure arrives at all, run `libinput debug-events` and look for `TABLET_TOOL_AXIS` lines with a
+`pressure` value.
+
+## Troubleshooting
+
+- **No pressure** (the meter stays at 1.00 or never moves): the system doesn't pass pressure on. On Windows
+ turn Windows Ink on (above); on Linux check `libinput debug-events`. A pen that never reports pressure
+ still draws, at full strength.
+- **Strokes too strong or too weak**: pick Soft or Firm, or lower **Max** / raise **Min**. A heavy hand that
+ always ends at full pressure: lower **Full at**.
+- **The first dab is missing at the very start of a stroke**: SculptForge waits for the touch's first real
+ pressure value, so a stroke begins where the pen starts pressing, never with a leftover value from the last
+ stroke. This is a few milliseconds at most.
+- **Lifting the pen out of range mid-stroke**: the stroke ends there and is one undo step.
+
+## For developers
+
+The settings and the curve are in `src/core/Tablet.h` (unit tests: `tests/test_tablet.cpp`); the pen event
+handling and the preferences panel in `src/app/Tablet.cpp`. UI tests drive a simulated pen with real SDL pen
+events plus the mouse events SDL synthesizes from them: `pen_stroke`, `pen_drag_item`, `pen_button`,
+`pen_hover`, `pen_pressure` and `pen_out` (documented in `src/app/UiTest.cpp`); `tests/ui/tablet.sfui` covers
+pressure, the curve, Pressure > Size, the eraser, side buttons, leaving proximity and the panel.
diff --git a/docs/ui-design.md b/docs/ui-design.md
index 0d609433..78722df6 100644
--- a/docs/ui-design.md
+++ b/docs/ui-design.md
@@ -166,7 +166,7 @@ Every palette's body is one function `void drawPalette_<Id>()`, and the same fun
| **Generate** | Generate 3D (image/text -> 3D, ComfyUI) opens the existing Generate 3D window; Image Relief / Inflate / Project (`cmd:image_relief`, `image_inflate`, `image_project`); AI provider settings (`drawAiSettings`) |
| **Help** | Controls (shortcut sheet generated from the Action registry), Command palette (F3), Website & documentation, Report a problem, About SculptForge |
| **Material** | Studio + MatCap thumbnail grid (`cmd:set_material`); base colour (today's "Material" ColorEdit in Tools) |
-| **Preferences** | Sub-palettes: **Config** (Enable Customize, Store Config Ctrl+Shift+I, Restore Custom UI, Restore Standard UI, Save UI..., Load UI... Ctrl+L); **Interface** (UI scale, Popup Info, Plain tooltips delay, One sub-palette open, Left-handed layout); **LightBox** (library folder, Show at startup, Startup rows, Placement top/bottom); **Hotkeys** (list with reset; Store); **Autosave** |
+| **Preferences** | Sub-palettes: **Config** (Enable Customize, Store Config Ctrl+Shift+I, Restore Custom UI, Restore Standard UI, Save UI..., Load UI... Ctrl+L); **Interface** (UI scale, Popup Info, Plain tooltips delay, One sub-palette open, Left-handed layout); **LightBox** (library folder, Show at startup, Startup rows, Placement top/bottom); **Hotkeys** (list with reset; Store); **Tablet** (pen, pressure meter, test area, pressure curve, eraser and side-button mappings; see docs/tablet.md); **Autosave** |
| **Render** | Wireframe (W), Show Mesh, Show Polypaint, Show Mask, Show Polygroups, Show Splats, Frame Model (F) (today's View menu render toggles) |
| **Script** | Show console (`` ` ``), Run script file..., Copy session as script, Clear console |
| **Splats** | `drawSplatSection` body (info, clean, transform, to mesh, save, clear) |
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 74be3332..578a0299 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -500,6 +500,7 @@ int App::run() {
// ---------------------------------------------------------------------------
void App::handleEvent(const SDL_Event& e) {
+ if (dropPenMouseEvent(e)) return; // pen side buttons are mapped in Tablet.cpp, not left to SDL
ImGui_ImplSDL3_ProcessEvent(&e);
const ImGuiIO& io = ImGui::GetIO();
@@ -511,10 +512,14 @@ void App::handleEvent(const SDL_Event& e) {
if (e.window.windowID == SDL_GetWindowID(window_)) requestQuit();
break;
case SDL_EVENT_PEN_PROXIMITY_IN:
- penSeen_ = true;
- break;
+ case SDL_EVENT_PEN_PROXIMITY_OUT:
+ case SDL_EVENT_PEN_DOWN:
+ case SDL_EVENT_PEN_UP:
+ case SDL_EVENT_PEN_MOTION:
case SDL_EVENT_PEN_AXIS:
- if (e.paxis.axis == SDL_PEN_AXIS_PRESSURE) penPressure_ = e.paxis.value;
+ case SDL_EVENT_PEN_BUTTON_DOWN:
+ case SDL_EVENT_PEN_BUTTON_UP:
+ handlePenEvent(e);
break;
case SDL_EVENT_MOUSE_BUTTON_DOWN:
lastInputPen_ = e.button.which == SDL_PEN_MOUSEID;
@@ -553,14 +558,25 @@ bool App::pick(float x, float y, RayHit& hit) const {
BrushType App::activeBrush() const {
// ZBrush convention: holding Shift temporarily switches to Smooth.
- return (SDL_GetModState() & SDL_KMOD_SHIFT) ? BrushType::Smooth : brush_;
+ // The pen's eraser end can be set to smooth too (Preferences > Tablet).
+ const bool smooth = (inputMods() & SDL_KMOD_SHIFT) || (erasing() && eraserAction() == PenAction::Smooth);
+ return smooth ? BrushType::Smooth : brush_;
}
void App::onMouseDown(float x, float y, Uint8 button) {
mouseX_ = x;
mouseY_ = y;
- const SDL_Keymod mod = SDL_GetModState();
+ const SDL_Keymod mod = inputMods();
+ // A pen button is already driving the view: touching down with the tip keeps navigating.
+ if (penNavButton_ && (drag_ == Drag::Orbit || drag_ == Drag::Pan)) return;
+ dragFromPen_ = lastInputPen_;
doc_.syncBvh();
+ if (button == SDL_BUTTON_LEFT && erasing() && eraserAction() != PenAction::Invert && eraserAction() != PenAction::Smooth) {
+ // The eraser end set to Erase mask or Nothing (Preferences > Tablet).
+ RayHit hit;
+ if (eraserAction() == PenAction::EraseMask && previewLod_ < 0 && pick(x, y, hit)) beginMaskStroke(x, y);
+ return;
+ }
if (button == SDL_BUTTON_LEFT) {
if (polygroupMouseDown(x, y, mod)) return;
// Alt+click on another SubTool selects it (ZBrush); Alt+drag stays an inverted stroke or a pan.
@@ -599,6 +615,7 @@ void App::onMouseMove(float x, float y, float dx, float dy, bool fromPen) {
mouseX_ = x;
mouseY_ = y;
lastInputPen_ = fromPen;
+ if (!fromPen && dragFromPen_ && drag_ != Drag::None) return; // a pen drag ignores a stray mouse
switch (drag_) {
case Drag::Stroke: strokeTo(x, y); break;
case Drag::Orbit: camera_.orbit(dx, dy); break;
@@ -616,6 +633,8 @@ void App::onMouseUp() {
if (drag_ == Drag::MaskCanvas) maskCanvasRelease();
if (drag_ == Drag::SubToolClick) subtoolClickRelease();
drag_ = Drag::None;
+ dragFromPen_ = false;
+ penNavButton_ = 0;
}
void App::onKey(SDL_Keycode key, SDL_Keymod mod) {
@@ -630,7 +649,7 @@ void App::onKey(SDL_Keycode key, SDL_Keymod mod) {
void App::beginStroke(float x, float y, const RayHit& hit) {
strokeBrush_ = activeBrush();
- strokeInvert_ = invertToggle_ != ((SDL_GetModState() & SDL_KMOD_ALT) != 0);
+ strokeInvert_ = invertToggle_ != (((inputMods() & SDL_KMOD_ALT) != 0) || (erasing() && eraserAction() == PenAction::Invert));
// Shift still smooths geometry while the Paint brush is active (ZBrush behaviour).
strokePaint_ = strokeBrush_ != BrushType::Smooth && (paintMode_ || paintRgb_);
strokeSculpt_ = !(strokePaint_ && paintMode_);
@@ -652,7 +671,7 @@ void App::beginStroke(float x, float y, const RayHit& hit) {
residual_ = 0.0f;
if (strokeBrush_ == BrushType::Move && !recipe && strokeSculpt_) {
- float pressure = lastInputPen_ && pressureSize_ ? penPressure_ : 1.0f;
+ const float pressure = pressureSize_ ? std::max(strokePressure(), 0.05f) : 1.0f;
DabParams p;
p.center = hit.position;
p.viewDir = camera_.forward();
@@ -672,7 +691,7 @@ void App::beginStroke(float x, float y, const RayHit& hit) {
dragAnchorHit_ = hit.position;
return; // the stamp appears once the drag gives it a size
}
- dabAt(x, y);
+ firstDab(x, y);
}
void App::strokeTo(float x, float y) {
@@ -703,22 +722,39 @@ void App::strokeTo(float x, float y) {
y = lazy.y;
}
- // Place dabs at even screen-space spacing along the cursor path.
+ if (firstDabPending_) {
+ // The pen touched down without a real pressure yet: the stroke starts where it first presses
+ // (a pen that has never reported pressure draws from its first motion).
+ if (!penTracker_.readyForFirstDab() && penTracker_.everSampled()) {
+ lastX_ = x;
+ lastY_ = y;
+ return;
+ }
+ firstDabPending_ = false;
+ lastStrokePressure_ = strokePressure();
+ dabAt(lastX_, lastY_, lastStrokePressure_);
+ }
+
+ // 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.
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) {
- glm::vec2 p = from + (to - from) * (travelled / len);
- dabAt(p.x, p.y);
+ 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);
lastX_ = x;
lastY_ = y;
+ lastStrokePressure_ = p1;
}
-void App::dabAt(float x, float y) {
+void App::dabAt(float x, float y, float pressure) {
const BrushRecipe* recipe = strokeRecipe();
if (recipe && recipe->jitter > 0.0f) {
// Deterministic per-stroke scatter (xorshift).
@@ -743,7 +779,7 @@ void App::dabAt(float x, float y) {
}
RayHit hit;
if (!pick(x, y, hit)) return;
- const float pressure = lastInputPen_ ? std::clamp(penPressure_, 0.0f, 1.0f) : 1.0f;
+ if (pressure < 0.0f) pressure = strokePressure();
DabParams p;
p.center = hit.position;
@@ -775,6 +811,7 @@ void App::dabAt(float x, float y) {
void App::endStroke() {
strokeMask_ = false;
+ firstDabPending_ = false;
UndoRecord r = doc_.sculptor.endStroke();
finishPaintStroke(r);
if (!r.empty()) {
@@ -1933,10 +1970,12 @@ void App::drawBrushCursor() {
ImDrawList* dl;
~PopClip() { dl->PopClipRect(); }
} popClip{dl};
- const float r = radiusPx_ * (pressureSize_ && lastInputPen_ ? std::max(penPressure_, 0.05f) : 1.0f);
+ const float r = radiusPx_ * (pressureSize_ && lastInputPen_ ? std::max(strokePressure(), 0.05f) : 1.0f);
const ImVec2 c(mouseX_, mouseY_);
- const bool inverted = invertToggle_ != ((SDL_GetModState() & SDL_KMOD_ALT) != 0);
- const SDL_Keymod mod = SDL_GetModState();
+ const SDL_Keymod mod = inputMods();
+ const bool inverted = drag_ == Drag::Stroke ? strokeInvert_
+ : invertToggle_ != (((mod & SDL_KMOD_ALT) != 0) ||
+ (erasing() && eraserAction() == PenAction::Invert));
const bool masking = drag_ == Drag::Stroke ? strokeMask_ : ctrlDown(mod) && !(mod & SDL_KMOD_SHIFT);
ImU32 col = masking ? IM_COL32(230, 230, 230, 200)
: activeBrush() == BrushType::Smooth ? IM_COL32(120, 200, 255, 200)
diff --git a/src/app/App.h b/src/app/App.h
index f7be229e..42b03f8e 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -19,6 +19,7 @@
#include "core/Image.h"
#include "core/Document.h"
#include "core/Stroke.h"
+#include "core/Tablet.h"
#include "render/Camera.h"
#include "render/Renderer.h"
@@ -99,7 +100,7 @@ private:
BrushType activeBrush() const;
void beginStroke(float x, float y, const RayHit& hit);
void strokeTo(float x, float y);
- void dabAt(float x, float y);
+ void dabAt(float x, float y, float pressure = -1.0f); // pressure < 0: strokePressure()
void endStroke();
void runCommand(const std::string& name, const Args& args = {});
@@ -169,8 +170,7 @@ private:
Drag drag_ = Drag::None;
float mouseX_ = 0.0f, mouseY_ = 0.0f;
float lastX_ = 0.0f, lastY_ = 0.0f, residual_ = 0.0f;
- float penPressure_ = 1.0f;
- bool lastInputPen_ = false;
+ bool lastInputPen_ = false; // the last mouse event came from a pen (SDL_PEN_MOUSEID)
bool penSeen_ = false;
BrushType strokeBrush_ = BrushType::Standard;
bool strokeInvert_ = false;
@@ -593,6 +593,38 @@ private:
std::mutex uiFileMutex_;
std::vector<std::pair<int, std::string>> uiFiles_; // (kind, path) from file dialogs
// ---- end Help/Console/Config (C) ----
+
+ // ---- Tablet (Tablet.cpp, core/Tablet.h, docs/tablet.md) ----
+ // SDL turns pen tip contact into left mouse button events (SDL_PEN_MOUSEID); the pen's own events
+ // add pressure, tilt, the eraser end and the side buttons, which are mapped in Preferences > Tablet.
+ bool dropPenMouseEvent(const SDL_Event& e) const; // SDL's version-dependent clicks for pen buttons
+ void handlePenEvent(const SDL_Event& e);
+ void penButton(int button, bool down, float x, float y);
+ void penLeft(); // out of proximity: ends what the pen was doing
+ float strokePressure() const; // pressure after the global curve; 1 for the mouse
+ SDL_Keymod inputMods() const; // the keyboard's modifiers plus those a pen button holds (Alt, Shift)
+ bool erasing() const; // the pen's eraser end is drawing
+ PenAction eraserAction() const { return uiPrefs_.tablet.eraser; }
+ void firstDab(float x, float y); // the stroke's first dab, once the pen reports a real pressure
+ void drawTabletSection(); // Preferences > Tablet
+ void detectPenName();
+ PenPressureTracker penTracker_;
+ bool penInProximity_ = false, penTouching_ = false, penEraser_ = false;
+ uint32_t penButtons_ = 0; // bit N: pen button N is held
+ int penNavButton_ = 0; // the pen button driving a view drag (0: none)
+ bool dragFromPen_ = false;
+ bool firstDabPending_ = false;
+ float lastStrokePressure_ = 1.0f; // pressure at the previous stroke sample (dabs in between interpolate)
+ float penTiltX_ = 0.0f, penTiltY_ = 0.0f;
+ bool penTiltSeen_ = false;
+ SDL_PenID penId_ = 0;
+ std::string penName_; // best guess at the device's name (empty: unknown)
+ struct TabletTestSample {
+ ImVec2 at; // relative to the test area
+ float raw, pressure;
+ };
+ std::vector<TabletTestSample> tabletTest_; // Preferences > Tablet draw-test area
+ // ---- end Tablet ----
};
} // namespace sf
diff --git a/src/app/Config.cpp b/src/app/Config.cpp
index c3ac8ac9..00072f84 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -42,6 +42,7 @@ Json toJson(const UiPrefs& p) {
j.set("uiScale", double(p.uiScale));
j.set("lightboxAtStartup", p.lightboxAtStartup);
j.set("libraryFolder", p.libraryFolder);
+ j.set("tablet", toJson(p.tablet));
return j;
}
@@ -56,6 +57,7 @@ void fromJson(const Json& j, UiPrefs& p) {
p.uiScale = std::clamp(float(j["uiScale"].asNumber(p.uiScale)), 0.0f, 3.0f);
p.lightboxAtStartup = j["lightboxAtStartup"].asBool(p.lightboxAtStartup);
if (j["libraryFolder"].isString()) p.libraryFolder = j["libraryFolder"].asString();
+ fromJson(j["tablet"], p.tablet);
}
namespace {
@@ -113,7 +115,9 @@ constexpr Gesture kGestures[] = {
{"Select a SubTool", "Alt + click it"},
{"Help on any control", "Hold Ctrl and point at it (Ctrl+Alt: scripting parameters)"},
{"Assign a shortcut", "Ctrl+Alt + click any button, then press the key"},
- {"Tablet pressure", "Used automatically when a pen is detected"},
+ {"Tablet pressure", "Used automatically when a pen is detected (Preferences > Tablet: curve, test area)"},
+ {"Pen eraser end", "Inverts the brush (Ctrl + eraser erases mask); Preferences > Tablet"},
+ {"Pen side buttons", "Lower: right-click (drag to rotate), upper: Alt (invert); Preferences > Tablet"},
{"Open files", "Drop a model (.obj, .glb ...), brush (.sfbrush) or image onto the window"},
};
diff --git a/src/app/Config.h b/src/app/Config.h
index 26924acd..eeba4480 100644
--- a/src/app/Config.h
+++ b/src/app/Config.h
@@ -9,6 +9,7 @@
#pragma once
#include "core/Json.h"
+#include "core/Tablet.h"
#include <string>
@@ -25,6 +26,7 @@ struct UiPrefs {
float uiScale = 0.0f; // 0 = follow the display; otherwise applied at the next start
bool lightboxAtStartup = true;
std::string libraryFolder; // "" = Documents/SculptForge
+ TabletSettings tablet; // Preferences > Tablet: pressure curve, eraser, pen buttons
};
Json toJson(const UiPrefs& prefs);
diff --git a/src/app/Demo.cpp b/src/app/Demo.cpp
index 538d4c4c..2f2c9b2f 100644
--- a/src/app/Demo.cpp
+++ b/src/app/Demo.cpp
@@ -195,10 +195,11 @@ void Demo::update(float dt) {
// ---------------------------------------------------------------- input
-void Demo::mouseMotion(float x, float y) {
+void Demo::mouseMotion(float x, float y, SDL_MouseID which) {
SDL_Event e{};
e.type = SDL_EVENT_MOUSE_MOTION;
e.motion.windowID = SDL_GetWindowID(app_.window_);
+ e.motion.which = which;
e.motion.x = x;
e.motion.y = y;
e.motion.xrel = x - mouse_.x;
@@ -208,16 +209,17 @@ void Demo::mouseMotion(float x, float y) {
app_.handleEvent(e);
}
-void Demo::mouseButton(bool down, int button) {
+void Demo::mouseButton(bool down, int button, SDL_MouseID which) {
SDL_Event e{};
e.type = down ? SDL_EVENT_MOUSE_BUTTON_DOWN : SDL_EVENT_MOUSE_BUTTON_UP;
e.button.windowID = SDL_GetWindowID(app_.window_);
+ e.button.which = which;
e.button.button = Uint8(button);
e.button.down = down;
e.button.clicks = 1;
e.button.x = mouse_.x;
e.button.y = mouse_.y;
- buttonDown_ = down && button == SDL_BUTTON_LEFT;
+ if (button == SDL_BUTTON_LEFT) buttonDown_ = down;
app_.handleEvent(e);
}
diff --git a/src/app/Demo.h b/src/app/Demo.h
index 8e5a503f..cb13e0ce 100644
--- a/src/app/Demo.h
+++ b/src/app/Demo.h
@@ -21,6 +21,7 @@
#include <SDL3/SDL.h>
#include <functional>
+#include <map>
#include <string>
#include <utility>
#include <vector>
@@ -92,8 +93,15 @@ private:
void buildSplats();
// Input injection.
- void mouseMotion(float x, float y);
- void mouseButton(bool down, int button);
+ void mouseMotion(float x, float y, SDL_MouseID which = 0); // which = SDL_PEN_MOUSEID: synthesized from a pen
+ void mouseButton(bool down, int button, SDL_MouseID which = 0);
+ // Pen events as SDL3 sends them (UiTest.cpp): the pen's own event, then the mouse event SDL synthesizes.
+ void penProximity(bool in);
+ void penMove(float x, float y); // PEN_MOTION (+ mouse motion), touching or hovering
+ void penPressure(float pressure); // PEN_AXIS pressure
+ void penTouch(bool down, bool eraser); // PEN_DOWN / PEN_UP (+ left button)
+ void penButtonEvent(int button, bool down); // PEN_BUTTON_DOWN / UP (+ SDL 3.4's mouse button)
+ void penStroke(std::function<ImVec2(float u)> path, float p0, float p1, bool eraser, bool leave, float seconds);
// World -> screen in window coordinates.
ImVec2 project(const glm::vec3& p) const;
@@ -120,6 +128,13 @@ private:
std::string frameText_, shotRequest_, shotDir_, scriptName_, lineText_;
std::string scriptDir_; // the .sfui script's folder: relative `drop` paths, $SCRIPT_DIR in env steps
SDL_Keymod held_ = SDL_KMOD_NONE; // modifiers held by `hold` (Ctrl to mask, Ctrl+Shift to hide...)
+ // Simulated pen (pen_* steps).
+ static constexpr SDL_PenID kTestPen = 1;
+ bool penIn_ = false, penDown_ = false, penEraser_ = false;
+ SDL_PenInputFlags penState_ = 0;
+ // `snapshot` saves the active mesh; moved* values compare against it. `remember` keeps values for $NAME.
+ std::vector<glm::vec3> basePositions_, baseNormals_;
+ std::map<std::string, double> remembered_;
};
} // namespace sf
diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cpp
index 34ab6564..d1e84fb5 100644
--- a/src/app/Palettes.cpp
+++ b/src/app/Palettes.cpp
@@ -194,7 +194,7 @@ void App::drawPalette_Draw() {
ui::HelpAction(*this, "draw.pressure_strength");
ImGui::Checkbox("Pressure > size", &pressureSize_);
ui::HelpAction(*this, "draw.pressure_size");
- if (penSeen_) ImGui::Text("Pen pressure: %.2f", penPressure_);
+ if (penSeen_) ImGui::Text("Pen pressure: %.2f", uiPrefs_.tablet.curve.apply(penTracker_.raw()));
else ImGui::TextDisabled("No pen detected");
}
@@ -291,6 +291,7 @@ void App::drawPalette_Preferences() {
if (subpalette("preferences.interface", "Interface")) config::drawInterfaceSection(*this);
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.autosave", "Autosave")) {
ImGui::SetNextItemWidth(-1);
ImGui::SliderInt("##autosave", &autosaveMinutes_, 0, 60, autosaveMinutes_ ? "Every %d min" : "Autosave off");
diff --git a/src/app/PanelBrushes.cpp b/src/app/PanelBrushes.cpp
index d43ba205..f3ea0f93 100644
--- a/src/app/PanelBrushes.cpp
+++ b/src/app/PanelBrushes.cpp
@@ -88,7 +88,7 @@ void App::snakeHookTo(float x, float y) {
if (std::abs(denom) < 1e-6f) return;
const glm::vec3 target = origin + dir * (glm::dot(grabLast_ - origin, n) / denom);
- const float pressure = lastInputPen_ ? std::clamp(penPressure_, 0.0f, 1.0f) : 1.0f;
+ const float pressure = strokePressure();
DabParams p;
p.viewDir = n;
p.radius = radiusPx_ * (pressureSize_ ? std::max(pressure, 0.05f) : 1.0f) * camera_.worldPerPixel(grabLast_, h);
@@ -115,7 +115,7 @@ void App::dragRectTo(float x, float y) {
const float len = glm::length(drag);
if (len < 2.0f) return;
const glm::quat q = camera_.orientation();
- const float pressure = lastInputPen_ ? std::clamp(penPressure_, 0.0f, 1.0f) : 1.0f;
+ const float pressure = strokePressure();
DabParams p;
p.center = dragAnchorHit_;
diff --git a/src/app/PanelMasking.cpp b/src/app/PanelMasking.cpp
index 13a73272..541e27de 100644
--- a/src/app/PanelMasking.cpp
+++ b/src/app/PanelMasking.cpp
@@ -24,7 +24,9 @@ bool anyMasked(const Mesh& mesh) {
void App::beginMaskStroke(float x, float y) {
// Masks are not layered, so the stroke always targets the base (its weight is never 0).
- strokeInvert_ = (SDL_GetModState() & SDL_KMOD_ALT) != 0; // Ctrl+Alt erases
+ // Ctrl+Alt erases, and so does the pen's eraser end (set to Invert or Erase mask).
+ strokeInvert_ = (inputMods() & SDL_KMOD_ALT) != 0 ||
+ (erasing() && (eraserAction() == PenAction::Invert || eraserAction() == PenAction::EraseMask));
if (!doc_.sculptor.beginStroke(doc_.mesh, strokeInvert_ ? "Unmask" : "Mask", -1)) return;
strokeMask_ = true;
strokePaint_ = false; // mask strokes never paint or sculpt
@@ -37,7 +39,7 @@ void App::beginMaskStroke(float x, float y) {
lastY_ = y;
residual_ = 0.0f;
lazyMouse_.reset(glm::vec2(x, y));
- dabAt(x, y);
+ firstDab(x, y);
}
// ZBrush convention: Ctrl+drag on the background clears the mask. With
diff --git a/src/app/PanelPolygroups.cpp b/src/app/PanelPolygroups.cpp
index 4471c8c2..58f724a3 100644
--- a/src/app/PanelPolygroups.cpp
+++ b/src/app/PanelPolygroups.cpp
@@ -45,7 +45,7 @@ bool App::polygroupMouseDown(float x, float y, SDL_Keymod mod) {
void App::polygroupMouseUp() {
hideRectActive_ = false;
- const bool alt = (SDL_GetModState() & SDL_KMOD_ALT) != 0;
+ const bool alt = (inputMods() & SDL_KMOD_ALT) != 0;
const CanvasRect c = canvasRect();
if (c.w <= 0.0f || c.h <= 0.0f) return;
@@ -80,7 +80,7 @@ void App::drawPolygroupOverlay() {
if (!hideRectActive_) return;
if (std::abs(mouseX_ - hideRectX_) < kClickSlopPx && std::abs(mouseY_ - hideRectY_) < kClickSlopPx) return;
// Green keeps the inside, red hides it (Alt).
- const bool alt = (SDL_GetModState() & SDL_KMOD_ALT) != 0;
+ const bool alt = (inputMods() & SDL_KMOD_ALT) != 0;
const ImU32 line = alt ? IM_COL32(255, 110, 110, 230) : IM_COL32(120, 230, 140, 230);
const ImU32 fill = alt ? IM_COL32(255, 110, 110, 40) : IM_COL32(120, 230, 140, 30);
ImDrawList* dl = ImGui::GetForegroundDrawList();
diff --git a/src/app/Tablet.cpp b/src/app/Tablet.cpp
new file mode 100644
index 00000000..3a5892be
--- /dev/null
+++ b/src/app/Tablet.cpp
@@ -0,0 +1,408 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Graphics tablets: pen pressure through the global curve, the eraser end,
+// the pen's side buttons, and Preferences > Tablet (device, live pressure,
+// draw-test area, curve editor, mappings). SDL3 reports pens the same way on
+// Windows (Windows Ink), macOS, Wayland and X11 and also turns the tip into
+// left mouse button events (SDL_PEN_MOUSEID), which the canvas and the UI use
+// like a mouse. The settings live in UiPrefs::tablet (Store Config keeps them);
+// the math is in core/Tablet.h. User guide: docs/tablet.md.
+#include "app/App.h"
+#include "app/Ui.h"
+
+#include <IconsLucide.h>
+
+#include <algorithm>
+#include <cctype>
+#include <cfloat>
+#include <cmath>
+#include <cstdio>
+#include <fstream>
+
+namespace sf {
+
+namespace {
+
+ImVec4 col(ImU32 c) { return ImGui::ColorConvertU32ToFloat4(c); }
+
+constexpr const char* kButtonNames[kPenButtons] = {"Lower button", "Upper button", "Third button"};
+
+} // namespace
+
+// SDL also turns pen side buttons into mouse clicks, but which button depends on the SDL version
+// (3.2: middle / right and only while touching; 3.4: right / middle, also while hovering).
+// The mapping in Preferences > Tablet decides instead (see penButton).
+bool App::dropPenMouseEvent(const SDL_Event& e) const {
+ return (e.type == SDL_EVENT_MOUSE_BUTTON_DOWN || e.type == SDL_EVENT_MOUSE_BUTTON_UP) &&
+ e.button.which == SDL_PEN_MOUSEID && e.button.button != SDL_BUTTON_LEFT;
+}
+
+void App::handlePenEvent(const SDL_Event& e) {
+ switch (e.type) {
+ case SDL_EVENT_PEN_PROXIMITY_IN:
+ penSeen_ = penInProximity_ = true;
+ penId_ = e.pproximity.which;
+ if (penName_.empty()) detectPenName();
+ break;
+ case SDL_EVENT_PEN_PROXIMITY_OUT:
+ penLeft();
+ break;
+ case SDL_EVENT_PEN_DOWN:
+ penSeen_ = penInProximity_ = penTouching_ = true;
+ penId_ = e.ptouch.which;
+ penEraser_ = e.ptouch.eraser;
+ penTracker_.touchDown(); // SDL's left button down follows and starts the stroke
+ break;
+ case SDL_EVENT_PEN_UP:
+ // End the stroke here rather than waiting for SDL's mouse button up: the pen may leave
+ // proximity right after, and some drivers then never send it.
+ if (drag_ == Drag::Stroke && dragFromPen_) onMouseUp();
+ penTouching_ = penEraser_ = false;
+ penTracker_.touchUp();
+ break;
+ case SDL_EVENT_PEN_MOTION:
+ penSeen_ = penInProximity_ = true;
+ penId_ = e.pmotion.which;
+ break;
+ case SDL_EVENT_PEN_AXIS:
+ if (e.paxis.axis == SDL_PEN_AXIS_PRESSURE) {
+ penTracker_.sample(e.paxis.value);
+ if (drag_ == Drag::Stroke && firstDabPending_ && penTracker_.readyForFirstDab()) firstDab(lastX_, lastY_);
+ } else if (e.paxis.axis == SDL_PEN_AXIS_XTILT || e.paxis.axis == SDL_PEN_AXIS_YTILT) {
+ (e.paxis.axis == SDL_PEN_AXIS_XTILT ? penTiltX_ : penTiltY_) = e.paxis.value;
+ penTiltSeen_ = penTiltSeen_ || e.paxis.value != 0.0f;
+ }
+ break;
+ case SDL_EVENT_PEN_BUTTON_DOWN:
+ case SDL_EVENT_PEN_BUTTON_UP:
+ penButton(e.pbutton.button, e.pbutton.down, e.pbutton.x, e.pbutton.y);
+ break;
+ default:
+ break;
+ }
+}
+
+void App::penButton(int button, bool down, float x, float y) {
+ if (button < 1 || button > 31) return;
+ const uint32_t bit = 1u << button;
+ if (((penButtons_ & bit) != 0) == down) return;
+ penButtons_ = down ? penButtons_ | bit : penButtons_ & ~bit;
+ penSeen_ = true;
+ // Invert and Smooth need nothing here: inputMods() reports them as Alt / Shift while held.
+ const PenAction a = button <= kPenButtons ? uiPrefs_.tablet.buttons[size_t(button - 1)] : PenAction::None;
+ if (a != PenAction::RotateView && a != PenAction::PanView && a != PenAction::RightClick) return;
+ ImGuiIO& io = ImGui::GetIO();
+ if (a == PenAction::RightClick) { // context menus and right-click items in the UI
+ io.AddMouseSourceEvent(ImGuiMouseSource_Pen);
+ io.AddMouseButtonEvent(ImGuiMouseButton_Right, down);
+ }
+ if (down) {
+ if (drag_ != Drag::None || io.WantCaptureMouse || !canvasRect().contains(x, y)) return;
+ lastInputPen_ = true;
+ if (a == PenAction::RightClick) {
+ onMouseDown(x, y, SDL_BUTTON_RIGHT); // drag to rotate (Shift: pan), as with the mouse
+ } else {
+ mouseX_ = x;
+ mouseY_ = y;
+ drag_ = a == PenAction::RotateView ? Drag::Orbit : Drag::Pan;
+ dragFromPen_ = true;
+ }
+ if (drag_ != Drag::None) penNavButton_ = button;
+ } else if (penNavButton_ == button) {
+ if (drag_ == Drag::Orbit || drag_ == Drag::Pan || drag_ == Drag::Zoom) {
+ drag_ = Drag::None;
+ dragFromPen_ = false;
+ }
+ penNavButton_ = 0;
+ }
+}
+
+void App::penLeft() {
+ // A pen lifted out of range mid-stroke: finish the stroke (one undo step) instead of leaving it open.
+ if (drag_ != Drag::None && dragFromPen_) onMouseUp();
+ ImGuiIO& io = ImGui::GetIO();
+ if (penTouching_) io.AddMouseButtonEvent(ImGuiMouseButton_Left, false);
+ for (int b = 1; b <= kPenButtons; ++b)
+ if ((penButtons_ & (1u << b)) && uiPrefs_.tablet.buttons[size_t(b - 1)] == PenAction::RightClick)
+ io.AddMouseButtonEvent(ImGuiMouseButton_Right, false);
+ penInProximity_ = penTouching_ = penEraser_ = false;
+ penButtons_ = 0;
+ penNavButton_ = 0;
+ firstDabPending_ = false;
+ penTracker_.touchUp();
+ lastInputPen_ = false; // whatever moves the cursor next is a mouse until the pen says otherwise
+}
+
+float App::strokePressure() const {
+ if (!lastInputPen_) return 1.0f; // the mouse always presses fully
+ return uiPrefs_.tablet.curve.apply(penTracker_.raw());
+}
+
+SDL_Keymod App::inputMods() const {
+ SDL_Keymod mods = SDL_GetModState();
+ for (int b = 1; b <= kPenButtons; ++b) {
+ if (!(penButtons_ & (1u << b))) continue;
+ const PenAction a = uiPrefs_.tablet.buttons[size_t(b - 1)];
+ if (a == PenAction::Invert) mods |= SDL_KMOD_LALT;
+ else if (a == PenAction::Smooth) mods |= SDL_KMOD_LSHIFT;
+ }
+ return mods;
+}
+
+bool App::erasing() const { return lastInputPen_ && penEraser_; }
+
+void App::firstDab(float x, float y) {
+ if (lastInputPen_ && !penTracker_.readyForFirstDab()) {
+ firstDabPending_ = true; // strokeTo / the next pressure sample places it
+ return;
+ }
+ firstDabPending_ = false;
+ lastStrokePressure_ = strokePressure();
+ dabAt(x, y, lastStrokePressure_);
+}
+
+// SDL has no pen names, so on Linux read the kernel's input device list; elsewhere the pen stays unnamed.
+void App::detectPenName() {
+#if defined(__linux__)
+ std::ifstream f("/proc/bus/input/devices");
+ std::string line, fallback;
+ auto has = [](std::string s, const char* what) {
+ std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+ return s.find(what) != std::string::npos;
+ };
+ while (std::getline(f, line)) {
+ if (line.rfind("N: Name=\"", 0) != 0) continue;
+ std::string name = line.substr(9);
+ if (!name.empty() && name.back() == '"') name.pop_back();
+ if (has(name, "pen") || has(name, "stylus")) {
+ penName_ = name;
+ return;
+ }
+ if (fallback.empty() && (has(name, "wacom") || has(name, "huion") || has(name, "xp-pen") || has(name, "tablet") ||
+ has(name, "gaomon") || has(name, "ugee")))
+ fallback = name;
+ }
+ penName_ = fallback;
+#endif
+}
+
+// ---------------------------------------------------------------------------
+// Preferences > Tablet
+// ---------------------------------------------------------------------------
+
+void App::drawTabletSection() {
+ TabletSettings& t = uiPrefs_.tablet;
+ const float s = ImGui::GetFontSize() / 15.0f;
+ const float width = ImGui::GetContentRegionAvail().x;
+ const char* path = "Preferences > Tablet";
+
+ // --- Device ---
+ if (!penSeen_) {
+ ImGui::TextUnformatted(ICON_LC_PEN_LINE " No pen seen yet");
+ ImGui::PushStyleColor(ImGuiCol_Text, col(ui::color::textDim));
+ ImGui::PushTextWrapPos(0.0f);
+#if defined(_WIN32)
+ ImGui::TextUnformatted("Bring the pen close to the tablet. Wacom: turn on \"Use Windows Ink\" in Wacom Tablet "
+ "Properties > Mapping; Huion / XP-Pen: enable Windows Ink in the driver.");
+#else
+ ImGui::TextUnformatted("Bring the pen close to the tablet. Pressure works through the system's tablet driver.");
+#endif
+ ImGui::PopTextWrapPos();
+ ImGui::PopStyleColor();
+ } else {
+ ImGui::TextColored(col(ui::color::accent), ICON_LC_PEN_LINE);
+ ImGui::SameLine();
+ ImGui::TextUnformatted(penName_.empty() ? "Pen detected" : penName_.c_str());
+ ui::HelpText("Pen", nullptr, "The pen SculptForge last saw, and whether it is in range or touching.", path);
+ std::string info = penTouching_ ? (penEraser_ ? "eraser touching" : "touching") : penInProximity_ ? "in range" : "away";
+ const char* sep = " \xc2\xb7 "; // middle dot
+#if SDL_VERSION_ATLEAST(3, 4, 0)
+ const SDL_PenDeviceType type = SDL_GetPenDeviceType(penId_);
+ if (type == SDL_PEN_DEVICE_TYPE_DIRECT) info += std::string(sep) + "pen display";
+ else if (type == SDL_PEN_DEVICE_TYPE_INDIRECT) info += std::string(sep) + "tablet";
+#endif
+ if (const char* driver = SDL_GetCurrentVideoDriver()) info += sep + std::string(driver);
+ ImGui::TextColored(col(ui::color::textDim), "%s", info.c_str());
+ }
+
+ // --- Live pressure ---
+ const float raw = penTracker_.raw(), curved = t.curve.apply(raw);
+ char overlay[64];
+ std::snprintf(overlay, sizeof overlay, "Pressure %.2f " ICON_LC_ARROW_RIGHT " %.2f", raw, curved);
+ ImGui::PushStyleColor(ImGuiCol_PlotHistogram, col(ui::color::accent));
+ ImGui::ProgressBar(penSeen_ ? curved : 0.0f, ImVec2(-FLT_MIN, 0), penSeen_ ? overlay : "Pressure -");
+ ImGui::PopStyleColor();
+ ui::HelpText("Pressure meter", nullptr,
+ "The pen's pressure as the tablet reports it, and after the pressure curve below (what brushes get).", path);
+ if (penTiltSeen_) {
+ ImGui::Text("Tilt X %+.0f" "\xc2\xb0" " Y %+.0f" "\xc2\xb0", penTiltX_, penTiltY_);
+ ui::HelpText("Tilt", nullptr, "The pen's tilt, as the tablet reports it (brushes don't use it yet).", path);
+ } else if (penSeen_) {
+ ImGui::TextColored(col(ui::color::textDim), "Tilt: not reported by this pen");
+ }
+
+ // --- Draw-test area: the stroke's width follows the pressure, the line along the bottom plots it ---
+ const ImVec2 area(width, 86.0f * s);
+ const ImVec2 a0 = ImGui::GetCursorScreenPos();
+ ImGui::InvisibleButton("##tablet_test", area);
+ ui::HelpText("Pressure test", nullptr,
+ "Draw here with the pen: the stroke is as thick as the brush pressure, and the line at the bottom plots "
+ "it along the stroke.",
+ path);
+ if (ImGui::IsItemActivated()) tabletTest_.clear();
+ if (ImGui::IsItemActive()) {
+ const ImVec2 m = ImGui::GetIO().MousePos;
+ const ImVec2 rel(std::clamp(m.x - a0.x, 0.0f, area.x), std::clamp(m.y - a0.y, 0.0f, area.y));
+ const float p = strokePressure();
+ if (tabletTest_.empty() || std::abs(tabletTest_.back().at.x - rel.x) + std::abs(tabletTest_.back().at.y - rel.y) > 0.5f ||
+ std::abs(tabletTest_.back().pressure - p) > 0.01f)
+ if (tabletTest_.size() < 4000) tabletTest_.push_back({rel, lastInputPen_ ? raw : 1.0f, p});
+ }
+ ImDrawList* dl = ImGui::GetWindowDrawList();
+ const ImVec2 a1(a0.x + area.x, a0.y + area.y);
+ dl->AddRectFilled(a0, a1, IM_COL32(0x18, 0x18, 0x1a, 0xff), 3.0f * s);
+ dl->AddRect(a0, a1, ImGui::IsItemHovered() ? ui::color::accent : ui::color::border, 3.0f * s);
+ if (tabletTest_.empty()) {
+ const char* hint = "Draw here to test the pressure";
+ const ImVec2 ts = ImGui::CalcTextSize(hint);
+ dl->AddText(ImVec2(a0.x + (area.x - ts.x) * 0.5f, a0.y + (area.y - ts.y) * 0.5f), ui::color::textDim, hint);
+ } else {
+ dl->PushClipRect(a0, a1, true);
+ for (size_t i = 0; i < tabletTest_.size(); ++i) {
+ const TabletTestSample& q = tabletTest_[i];
+ const ImVec2 p(a0.x + q.at.x, a0.y + q.at.y);
+ const float r = 0.75f * s + q.pressure * 9.0f * s;
+ if (i > 0) {
+ const TabletTestSample& prev = tabletTest_[i - 1];
+ dl->AddLine(ImVec2(a0.x + prev.at.x, a0.y + prev.at.y), p, ui::color::accent, 2.0f * r);
+ }
+ dl->AddCircleFilled(p, r, ui::color::accent, 12);
+ }
+ // Pressure along the stroke (left to right = first to last sample).
+ const float plotH = 26.0f * s, n = float(std::max<size_t>(tabletTest_.size() - 1, 1));
+ for (size_t i = 1; i < tabletTest_.size(); ++i) {
+ auto at = [&](size_t k) {
+ return ImVec2(a0.x + 4.0f * s + (area.x - 8.0f * s) * float(k) / n, a1.y - 3.0f * s - plotH * tabletTest_[k].pressure);
+ };
+ dl->AddLine(at(i - 1), at(i), IM_COL32(255, 255, 255, 170), 1.5f * s);
+ }
+ dl->PopClipRect();
+ }
+
+ // --- Global pressure curve ---
+ ImGui::Spacing();
+ ImGui::TextColored(col(ui::color::textDim), "Pressure curve (all brushes)");
+ const float graphW = width, graphH = 96.0f * s;
+ const ImVec2 g0 = ImGui::GetCursorScreenPos(), g1(g0.x + graphW, g0.y + graphH);
+ ImGui::Dummy(ImVec2(graphW, graphH));
+ ui::HelpText("Pressure curve", nullptr,
+ "How pen pressure (left to right) becomes brush pressure (bottom to top), before each brush's own curve. "
+ "The dot is the pen right now.",
+ path);
+ dl->AddRectFilled(g0, g1, IM_COL32(0x18, 0x18, 0x1a, 0xff), 3.0f * s);
+ for (int i = 1; i < 4; ++i) {
+ const float fx = g0.x + graphW * float(i) / 4.0f, fy = g0.y + graphH * float(i) / 4.0f;
+ dl->AddLine(ImVec2(fx, g0.y), ImVec2(fx, g1.y), IM_COL32(255, 255, 255, 18));
+ dl->AddLine(ImVec2(g0.x, fy), ImVec2(g1.x, fy), IM_COL32(255, 255, 255, 18));
+ }
+ dl->AddLine(ImVec2(g0.x, g1.y), ImVec2(g1.x, g0.y), IM_COL32(255, 255, 255, 40)); // linear reference
+ ImVec2 pts[49];
+ for (int i = 0; i <= 48; ++i) {
+ const float x = float(i) / 48.0f;
+ pts[i] = ImVec2(g0.x + x * graphW, g1.y - t.curve.apply(x) * graphH);
+ }
+ dl->AddPolyline(pts, 49, ui::color::accent, 0, 2.0f * s);
+ if (penSeen_) dl->AddCircleFilled(ImVec2(g0.x + raw * graphW, g1.y - curved * graphH), 4.0f * s, IM_COL32(255, 255, 255, 230));
+ dl->AddRect(g0, g1, ui::color::border, 3.0f * s);
+
+ // Presets, then the numbers.
+ struct Preset {
+ const char* label;
+ PressureCurve curve;
+ const char* help;
+ };
+ const Preset presets[] = {{"Soft", PressureCurve::soft(), "A light touch already gives a strong stroke."},
+ {"Linear", PressureCurve::linear(), "Brush pressure equals pen pressure."},
+ {"Firm", PressureCurve::firm(), "Press harder for a strong stroke; fine control when light."}};
+ const float bw = (width - 2.0f * ImGui::GetStyle().ItemSpacing.x) / 3.0f;
+ for (int i = 0; i < 3; ++i) {
+ if (i) ImGui::SameLine();
+ const PressureCurve& c = presets[i].curve;
+ const bool on = std::abs(t.curve.gamma - c.gamma) < 1e-3f && t.curve.minOut == c.minOut && t.curve.maxOut == c.maxOut &&
+ t.curve.threshold == c.threshold && t.curve.fullAt == c.fullAt;
+ if (on) ImGui::PushStyleColor(ImGuiCol_Button, col(ui::color::accent));
+ if (ImGui::Button((std::string(presets[i].label) + "##tablet_curve").c_str(), ImVec2(bw, 0))) t.curve = c;
+ if (on) ImGui::PopStyleColor();
+ ui::HelpText((std::string(presets[i].label) + " pressure").c_str(), nullptr, presets[i].help, path);
+ }
+ ImGui::SetNextItemWidth(-FLT_MIN);
+ ui::SliderInside("##tablet_gamma", &t.curve.gamma, 0.25f, 4.0f, "Curve %.2f", ImGuiSliderFlags_Logarithmic);
+ ui::HelpText("Curve", nullptr, "Below 1: soft, a light touch gives a lot. Above 1: firm, press harder.", path);
+ const float half = (width - ImGui::GetStyle().ItemSpacing.x) * 0.5f;
+ ImGui::SetNextItemWidth(half);
+ ui::SliderInside("##tablet_min", &t.curve.minOut, 0.0f, 1.0f, "Min %.2f");
+ ui::HelpText("Minimum", nullptr, "Brush pressure at the lightest touch.", path);
+ ImGui::SameLine();
+ ImGui::SetNextItemWidth(half);
+ ui::SliderInside("##tablet_max", &t.curve.maxOut, 0.0f, 1.0f, "Max %.2f");
+ ui::HelpText("Maximum", nullptr, "Brush pressure when pressing fully.", path);
+ ImGui::SetNextItemWidth(half);
+ ui::SliderInside("##tablet_threshold", &t.curve.threshold, 0.0f, 0.5f, "Threshold %.2f");
+ ui::HelpText("Threshold", nullptr, "Pen pressure below this counts as the lightest touch (ignores a resting hand).",
+ path);
+ ImGui::SameLine();
+ ImGui::SetNextItemWidth(half);
+ ui::SliderInside("##tablet_full", &t.curve.fullAt, 0.3f, 1.0f, "Full at %.2f");
+ ui::HelpText("Full pressure at", nullptr, "Pen pressure that already counts as pressing fully (for a light hand).",
+ path);
+ t.curve.fullAt = std::max(t.curve.fullAt, t.curve.threshold + 0.05f);
+
+ // --- Pressure > Strength / Size: the same toggles as the top shelf ---
+ ImGui::Spacing();
+ const float tw = (width - ImGui::GetStyle().ItemSpacing.x) * 0.5f;
+ ui::ActionButton(*this, "draw.pressure_strength", ImVec2(tw, 0));
+ ImGui::SameLine();
+ ui::ActionButton(*this, "draw.pressure_size", ImVec2(tw, 0));
+
+ // --- Eraser and side buttons ---
+ ImGui::Spacing();
+ auto mapping = [&](const char* label, PenAction& value, std::initializer_list<PenAction> choices, const char* help) {
+ ImGui::AlignTextToFramePadding();
+ ImGui::TextUnformatted(label);
+ ImGui::SameLine(width * 0.42f);
+ ImGui::SetNextItemWidth(-FLT_MIN);
+ if (ImGui::BeginCombo((std::string("##") + label).c_str(), penActionLabel(value))) {
+ for (PenAction a : choices)
+ if (ImGui::Selectable((std::string(penActionLabel(a)) + "##" + label).c_str(), a == value)) value = a;
+ ImGui::EndCombo();
+ }
+ ui::HelpText(label, nullptr, help, path);
+ };
+ mapping("Eraser", t.eraser, {PenAction::Invert, PenAction::Smooth, PenAction::EraseMask, PenAction::None},
+ "What the pen's eraser end does. Invert: brushes subtract, like holding Alt (with Ctrl it erases mask). "
+ "Erase mask: removes mask wherever it draws.");
+ static const char* kButtonHelp[kPenButtons] = {
+ "The side button nearer the tip. Right-click: drag to rotate the view (Shift: pan) and open context menus.",
+ "The side button further from the tip. Invert (Alt): brushes subtract while it is held.",
+ "A third button, on pens that have one (e.g. Wacom Pro Pen 3D)."};
+ for (int b = 0; b < kPenButtons; ++b)
+ mapping(kButtonNames[b], t.buttons[size_t(b)],
+ {PenAction::RightClick, PenAction::Invert, PenAction::Smooth, PenAction::RotateView, PenAction::PanView,
+ PenAction::None},
+ kButtonHelp[b]);
+ if (ImGui::SmallButton(ICON_LC_ROTATE_CCW " Tablet defaults")) {
+ const PressureCurve keep = t.curve;
+ t = TabletSettings();
+ t.curve = keep;
+ }
+ ui::HelpText("Tablet defaults", nullptr, "Eraser: Invert; lower button: Right-click; upper button: Invert (Alt); third "
+ "button: Pan view. The curve stays.", path);
+ ImGui::PushStyleColor(ImGuiCol_Text, col(ui::color::textDim));
+ ImGui::PushTextWrapPos(0.0f);
+ ImGui::TextUnformatted("Store Config (Ctrl+Shift+I) keeps these settings.");
+ ImGui::PopTextWrapPos();
+ ImGui::PopStyleColor();
+}
+
+} // namespace sf
diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cpp
index a0d66101..c1f80325 100644
--- a/src/app/UiTest.cpp
+++ b/src/app/UiTest.cpp
@@ -35,8 +35,27 @@
// console_open, command_palette_open, customize, shelves_visible,
// right_tray_open, left_tray_open, lightbox_open, shelves (1 shown), left_tray / right_tray (palettes in
// the tray, -1 when closed); OP is == != < <= > >=
+// moved (vertices moved since `snapshot`), moved_max / moved_sum (distance),
+// 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), camera_yaw (degrees), camera_pan (target offset);
+// N may be $NAME or $NAME*K for a value kept by `remember`
// (mesh values are the active SubTool's)
+// snapshot remember the active mesh's vertices (for the moved* values)
+// remember VALUE NAME keep VALUE's current value as $NAME
// shot NAME save a screenshot NAME.png (to --ui-out)
+//
+// Simulated graphics tablet: real SDL3 pen events, each followed by the mouse event SDL synthesizes
+// from it (SDL_PEN_MOUSEID), in SDL's order. The touch comes before its first pressure sample, as
+// with Windows Ink, and every frame carries 4 pen samples (a 240 Hz pen at 60 fps).
+// pen_stroke U0 V0 U1 V1 P0 P1 [eraser] [leave] [S] pen stroke across the model with pressure P0 -> P1;
+// eraser: the eraser end; leave: the pen leaves proximity before lifting
+// pen_drag_item LABEL DX DY P0 P1 [S] pen stroke through the item's centre, DX DY pixels long
+// pen_button N down|up side button N (1 lower, 2 upper, 3 third) with SDL 3.4's synthesized click
+// pen_hover U V [S] move the hovering pen to a point on the model (drags the view while a
+// button mapped to rotate / pan / right-click is held)
+// pen_pressure P a pressure sample from the hovering pen (e.g. a stale value before a stroke)
+// pen_out the pen leaves proximity
#include "app/App.h"
#include "app/Demo.h"
#include "app/Ui.h"
@@ -217,6 +236,24 @@ double Demo::query(const std::string& name, bool& known) const {
for (uint8_t h : m.hidden) n += h != 0;
return double(n);
}
+ if (name == "moved" || name == "moved_max" || name == "moved_sum" || name == "moved_out") {
+ if (basePositions_.size() != m.vertexCount()) return -1.0; // no snapshot, or the topology changed
+ double count = 0.0, maxD = 0.0, sum = 0.0, out = 0.0;
+ for (size_t v = 0; v < basePositions_.size(); ++v) {
+ const glm::vec3 d = m.positions[v] - basePositions_[v];
+ const double len = glm::length(d);
+ count += len > 1e-6 ? 1.0 : 0.0;
+ maxD = std::max(maxD, len);
+ sum += len;
+ if (v < baseNormals_.size()) out += glm::dot(d, baseNormals_[v]);
+ }
+ return name == "moved" ? count : name == "moved_max" ? maxD : name == "moved_sum" ? sum : out;
+ }
+ if (name == "pen_pressure") return app_.penTracker_.raw();
+ if (name == "brush_pressure") return app_.strokePressure();
+ if (name == "stroking") return app_.drag_ == App::Drag::Stroke ? 1.0 : 0.0;
+ if (name == "camera_yaw") return glm::degrees(app_.camera_.yaw);
+ if (name == "camera_pan") return glm::length(app_.camera_.target);
if (name == "groups") {
std::set<uint32_t> ids(m.polygroups.begin(), m.polygroups.end());
return double(std::max<size_t>(ids.size(), m.triangleCount() ? 1 : 0));
@@ -600,13 +637,107 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& e
error = "unknown value '" + w[1] + "'";
return false;
}
- const std::string name = w[1], op = w[2];
- const double want = num(3, 0);
- run([this, line, name, op, want] {
+ const std::string name = w[1], op = w[2], wantText = w[3];
+ run([this, line, name, op, wantText] {
+ double want = std::strtod(wantText.c_str(), nullptr);
+ if (!wantText.empty() && wantText[0] == '$') { // $NAME or $NAME*K
+ const size_t star = wantText.find('*');
+ const std::string key = wantText.substr(1, star == std::string::npos ? std::string::npos : star - 1);
+ const auto it = remembered_.find(key);
+ if (it == remembered_.end()) {
+ fail(line, "nothing remembered as $" + key);
+ return;
+ }
+ want = it->second * (star == std::string::npos ? 1.0 : std::strtod(wantText.c_str() + star + 1, nullptr));
+ }
bool k = false;
const double v = query(name, k);
- if (!compare(v, op, want)) fail(line, name + " is " + number(v) + ", expected " + op + " " + number(want));
+ if (!compare(v, op, want)) fail(line, name + " is " + number(v) + ", expected " + op + " " + number(want) + " (" + wantText + ")");
+ });
+ } else if (verb == "snapshot") {
+ run([this] {
+ basePositions_ = app_.doc_.mesh.positions;
+ baseNormals_ = app_.doc_.mesh.normals;
+ });
+ } else if (verb == "remember") {
+ if (!need(2)) return false;
+ bool known = false;
+ query(w[1], known);
+ if (!known) {
+ error = "unknown value '" + w[1] + "'";
+ return false;
+ }
+ run([this, name = w[1], as = w[2]] {
+ bool k = false;
+ remembered_[as] = query(name, k);
+ SDL_Log("remember %s = %s", as.c_str(), number(remembered_[as]).c_str());
+ });
+ } else if (verb == "pen_stroke") {
+ if (!need(6)) return false;
+ const float u0 = num(1, 0), v0 = num(2, 0), u1 = num(3, 0), v1 = num(4, 0), p0 = num(5, 1), p1 = num(6, 1);
+ bool eraser = false, leave = false;
+ float seconds = 0.6f;
+ for (size_t i = 7; i < w.size(); ++i) {
+ if (w[i] == "eraser") eraser = true;
+ else if (w[i] == "leave") leave = true;
+ else seconds = num(i, seconds);
+ }
+ auto ends = std::make_shared<std::pair<ImVec2, ImVec2>>();
+ run([this, ends, u0, v0, u1, v1] { *ends = {onModel(u0, v0), onModel(u1, v1)}; });
+ penStroke([ends](float u) {
+ return ImVec2(ends->first.x + (ends->second.x - ends->first.x) * u, ends->first.y + (ends->second.y - ends->first.y) * u);
+ }, p0, p1, eraser, leave, seconds);
+ wait(0.1f);
+ } else if (verb == "pen_drag_item") {
+ if (!need(5)) return false;
+ const std::string label = w[1];
+ const float dx = num(2, 0), dy = num(3, 0), p0 = num(4, 1), p1 = num(5, 1), seconds = num(6, 0.6f);
+ auto centre = std::make_shared<ImVec2>();
+ steps_.push_back([this, line, label, centre](float t) {
+ if (findItem(label, *centre)) return true;
+ if (t > 3.0f) fail(line, notFound(label));
+ return t > 3.0f;
+ });
+ penStroke([centre, dx, dy](float u) { return ImVec2(centre->x + dx * (u - 0.5f), centre->y + dy * (u - 0.5f)); }, p0, p1,
+ false, false, seconds);
+ wait(0.1f);
+ } else if (verb == "pen_button") {
+ if (!need(2)) return false;
+ const int button = int(num(1, 1));
+ if (w[2] != "down" && w[2] != "up") {
+ error = "pen_button needs down or up";
+ return false;
+ }
+ run([this, button, down = w[2] == "down"] {
+ if (!penIn_) penProximity(true);
+ penButtonEvent(button, down);
});
+ wait(0.05f);
+ } else if (verb == "pen_hover") {
+ if (!need(2)) return false;
+ const float u = num(1, 0.5f), v = num(2, 0.5f), seconds = num(3, 0.4f);
+ auto from = std::make_shared<ImVec2>();
+ auto to = std::make_shared<ImVec2>();
+ steps_.push_back([this, from, to, u, v, seconds](float t) {
+ if (t == 0.0f) {
+ if (!penIn_) penProximity(true);
+ *from = mouse_;
+ *to = onModel(u, v);
+ }
+ const float k = std::min(t / seconds, 1.0f);
+ penMove(from->x + (to->x - from->x) * k, from->y + (to->y - from->y) * k);
+ return t >= seconds;
+ });
+ wait(0.05f);
+ } else if (verb == "pen_pressure") {
+ if (!need(1)) return false;
+ run([this, p = num(1, 0)] {
+ if (!penIn_) penProximity(true);
+ penPressure(p);
+ });
+ } else if (verb == "pen_out") {
+ run([this] { penProximity(false); });
+ wait(0.05f);
} else if (verb == "shot") {
if (!need(1)) return false;
const std::string name = w[1];
@@ -623,6 +754,123 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& e
return true;
}
+// ---------------------------------------------------------------- simulated pen
+
+void Demo::penProximity(bool in) {
+ SDL_Event e{};
+ e.type = in ? SDL_EVENT_PEN_PROXIMITY_IN : SDL_EVENT_PEN_PROXIMITY_OUT;
+ e.pproximity.windowID = SDL_GetWindowID(app_.window_);
+ e.pproximity.which = kTestPen;
+ penIn_ = in;
+ if (!in) penDown_ = penEraser_ = false;
+ penState_ = in ? SDL_PEN_INPUT_IN_PROXIMITY : 0; // leaving releases the tip and every button
+ app_.handleEvent(e);
+}
+
+void Demo::penMove(float x, float y) {
+ SDL_Event e{};
+ e.type = SDL_EVENT_PEN_MOTION;
+ e.pmotion.windowID = SDL_GetWindowID(app_.window_);
+ e.pmotion.which = kTestPen;
+ e.pmotion.pen_state = penState_;
+ e.pmotion.x = x;
+ e.pmotion.y = y;
+ app_.handleEvent(e);
+ mouseMotion(x, y, SDL_PEN_MOUSEID); // SDL moves the mouse with a touching or hovering pen
+}
+
+void Demo::penPressure(float pressure) {
+ SDL_Event e{};
+ e.type = SDL_EVENT_PEN_AXIS;
+ e.paxis.windowID = SDL_GetWindowID(app_.window_);
+ e.paxis.which = kTestPen;
+ e.paxis.pen_state = penState_;
+ e.paxis.x = mouse_.x;
+ e.paxis.y = mouse_.y;
+ e.paxis.axis = SDL_PEN_AXIS_PRESSURE;
+ e.paxis.value = pressure;
+ app_.handleEvent(e);
+}
+
+void Demo::penTouch(bool down, bool eraser) {
+ penDown_ = down;
+ penEraser_ = down && eraser;
+ penState_ = (penState_ & ~(SDL_PEN_INPUT_DOWN | SDL_PEN_INPUT_ERASER_TIP)) | (down ? SDL_PEN_INPUT_DOWN : 0) |
+ (penEraser_ ? SDL_PEN_INPUT_ERASER_TIP : 0);
+ SDL_Event e{};
+ e.type = down ? SDL_EVENT_PEN_DOWN : SDL_EVENT_PEN_UP;
+ e.ptouch.windowID = SDL_GetWindowID(app_.window_);
+ e.ptouch.which = kTestPen;
+ e.ptouch.pen_state = penState_;
+ e.ptouch.x = mouse_.x;
+ e.ptouch.y = mouse_.y;
+ e.ptouch.eraser = eraser;
+ e.ptouch.down = down;
+ app_.handleEvent(e);
+ if (down) mouseMotion(mouse_.x, mouse_.y, SDL_PEN_MOUSEID); // SDL_SendPenTouch: motion, then the left button
+ mouseButton(down, SDL_BUTTON_LEFT, SDL_PEN_MOUSEID);
+}
+
+void Demo::penButtonEvent(int button, bool down) {
+ const SDL_PenInputFlags bit = SDL_PenInputFlags(1u << button);
+ penState_ = down ? (penState_ | bit) : (penState_ & ~bit);
+ SDL_Event e{};
+ e.type = down ? SDL_EVENT_PEN_BUTTON_DOWN : SDL_EVENT_PEN_BUTTON_UP;
+ e.pbutton.windowID = SDL_GetWindowID(app_.window_);
+ e.pbutton.which = kTestPen;
+ e.pbutton.pen_state = penState_;
+ e.pbutton.x = mouse_.x;
+ e.pbutton.y = mouse_.y;
+ e.pbutton.button = Uint8(button);
+ e.pbutton.down = down;
+ app_.handleEvent(e);
+ // SDL 3.4 also clicks a mouse button for it (1: right, 2: middle ...); the app must ignore that.
+ static const int kMouse[] = {SDL_BUTTON_LEFT, SDL_BUTTON_RIGHT, SDL_BUTTON_MIDDLE, SDL_BUTTON_X1, SDL_BUTTON_X2};
+ if (button >= 1 && button < 5) mouseButton(down, kMouse[button], SDL_PEN_MOUSEID);
+}
+
+void Demo::penStroke(std::function<ImVec2(float u)> path, float p0, float p1, bool eraser, bool leave, float seconds) {
+ // Hover to the start, touch down, then 4 samples a frame along the path, then lift (or leave).
+ auto from = std::make_shared<ImVec2>();
+ steps_.push_back([this, path, from](float t) {
+ if (t == 0.0f) {
+ if (!penIn_) penProximity(true);
+ *from = mouse_;
+ }
+ const ImVec2 p = path(0.0f);
+ const float k = std::min(t / 0.25f, 1.0f), u = k * k * (3.0f - 2.0f * k);
+ penMove(from->x + (p.x - from->x) * u, from->y + (p.y - from->y) * u);
+ return t >= 0.25f;
+ });
+ auto last = std::make_shared<float>(-1.0f);
+ steps_.push_back([this, path, p0, p1, eraser, leave, seconds, last](float t) {
+ if (*last < 0.0f) {
+ penTouch(true, eraser);
+ penPressure(p0); // the first pressure sample comes after the touch
+ *last = 0.0f;
+ return false;
+ }
+ const float u = std::min(t / seconds, 1.0f);
+ constexpr int kSamples = 4;
+ for (int k = 1; k <= kSamples; ++k) {
+ const float uu = *last + (u - *last) * float(k) / float(kSamples);
+ penPressure(p0 + (p1 - p0) * uu);
+ const ImVec2 p = path(uu);
+ penMove(p.x, p.y);
+ }
+ *last = u;
+ if (u < 1.0f) return false;
+ if (leave) {
+ penProximity(false); // out of range without lifting first
+ } else {
+ penTouch(false, eraser);
+ penPressure(0.0f);
+ }
+ *last = -1.0f;
+ return true;
+ });
+}
+
void Demo::testKeyNow(SDL_Keycode key, SDL_Keymod mods) {
SDL_Event e{};
e.type = SDL_EVENT_KEY_DOWN;
diff --git a/src/core/Tablet.cpp b/src/core/Tablet.cpp
new file mode 100644
index 00000000..68fb6382
--- /dev/null
+++ b/src/core/Tablet.cpp
@@ -0,0 +1,106 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Tablet.h"
+
+#include <algorithm>
+#include <cmath>
+
+namespace sf {
+
+namespace {
+
+struct ActionName {
+ PenAction action;
+ const char* id;
+ const char* label;
+};
+constexpr ActionName kActions[] = {
+ {PenAction::None, "none", "Nothing"},
+ {PenAction::Invert, "invert", "Invert (Alt)"},
+ {PenAction::Smooth, "smooth", "Smooth (Shift)"},
+ {PenAction::RotateView, "rotate", "Rotate view"},
+ {PenAction::PanView, "pan", "Pan view"},
+ {PenAction::RightClick, "right_click", "Right-click"},
+ {PenAction::EraseMask, "erase_mask", "Erase mask"},
+};
+
+float clamp01(float v) { return std::isfinite(v) ? std::clamp(v, 0.0f, 1.0f) : 0.0f; }
+
+} // namespace
+
+float PressureCurve::apply(float pressure) const {
+ const float lo = clamp01(threshold);
+ const float hi = std::max(clamp01(fullAt), lo + 1e-3f);
+ const float t = std::clamp((clamp01(pressure) - lo) / (hi - lo), 0.0f, 1.0f);
+ const float g = std::isfinite(gamma) ? std::clamp(gamma, 0.25f, 4.0f) : 1.0f;
+ const float a = clamp01(minOut), b = clamp01(maxOut);
+ return a + (b - a) * std::pow(t, g);
+}
+
+bool PressureCurve::isLinear() const {
+ return std::abs(gamma - 1.0f) < 1e-3f && minOut <= 0.0f && maxOut >= 1.0f && threshold <= 0.0f && fullAt >= 1.0f;
+}
+
+const char* penActionId(PenAction a) {
+ for (const auto& n : kActions)
+ if (n.action == a) return n.id;
+ return "none";
+}
+
+const char* penActionLabel(PenAction a) {
+ for (const auto& n : kActions)
+ if (n.action == a) return n.label;
+ return "Nothing";
+}
+
+PenAction penActionFromId(const std::string& id, PenAction fallback) {
+ for (const auto& n : kActions)
+ if (id == n.id) return n.action;
+ return fallback;
+}
+
+Json toJson(const TabletSettings& t) {
+ Json curve = Json::object();
+ curve.set("gamma", double(t.curve.gamma));
+ curve.set("min", double(t.curve.minOut));
+ curve.set("max", double(t.curve.maxOut));
+ curve.set("threshold", double(t.curve.threshold));
+ curve.set("fullAt", double(t.curve.fullAt));
+ Json j = Json::object();
+ j.set("pressureCurve", curve);
+ j.set("eraser", std::string(penActionId(t.eraser)));
+ Json buttons = Json::array();
+ for (PenAction a : t.buttons) buttons.push(std::string(penActionId(a)));
+ j.set("buttons", buttons);
+ return j;
+}
+
+void fromJson(const Json& j, TabletSettings& t) {
+ if (!j.isObject()) return;
+ if (const Json& c = j["pressureCurve"]; c.isObject()) {
+ t.curve.gamma = std::clamp(float(c["gamma"].asNumber(t.curve.gamma)), 0.25f, 4.0f);
+ t.curve.minOut = clamp01(float(c["min"].asNumber(t.curve.minOut)));
+ t.curve.maxOut = clamp01(float(c["max"].asNumber(t.curve.maxOut)));
+ t.curve.threshold = std::clamp(float(c["threshold"].asNumber(t.curve.threshold)), 0.0f, 0.9f);
+ t.curve.fullAt = std::clamp(float(c["fullAt"].asNumber(t.curve.fullAt)), t.curve.threshold + 0.05f, 1.0f);
+ }
+ if (j["eraser"].isString()) {
+ const PenAction a = penActionFromId(j["eraser"].asString(), t.eraser);
+ // The eraser can't take a button-only action (a view drag while drawing makes no sense).
+ if (a == PenAction::None || a == PenAction::Invert || a == PenAction::Smooth || a == PenAction::EraseMask) t.eraser = a;
+ }
+ if (const Json& b = j["buttons"]; b.isArray())
+ for (size_t i = 0; i < t.buttons.size() && i < b.size(); ++i)
+ if (b[i].isString()) {
+ const PenAction a = penActionFromId(b[i].asString(), t.buttons[i]);
+ if (a != PenAction::EraseMask) t.buttons[i] = a;
+ }
+}
+
+void PenPressureTracker::sample(float pressure) {
+ raw_ = clamp01(pressure);
+ sinceDown_ = true;
+ everSampled_ = true;
+}
+
+} // namespace sf
diff --git a/src/core/Tablet.h b/src/core/Tablet.h
new file mode 100644
index 00000000..5d86b662
--- /dev/null
+++ b/src/core/Tablet.h
@@ -0,0 +1,87 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Graphics tablet settings (Preferences > Tablet), independent of SDL so they
+// can be unit tested: the global pressure curve applied to every pen sample
+// before a brush's own pressure curve, what the eraser end and the pen's side
+// buttons do, and the stroke-start pressure guard. The app's event handling
+// lives in src/app/Tablet.cpp; docs/tablet.md is the user guide.
+#pragma once
+
+#include "core/Json.h"
+
+#include <array>
+#include <string>
+
+namespace sf {
+
+// Raw pen pressure (0..1) -> brush pressure:
+// t = (p - threshold) / (fullAt - threshold), clamped to 0..1
+// out = minOut + (maxOut - minOut) * t^gamma
+// gamma < 1 is soft (a light touch already gives a lot), > 1 is firm.
+struct PressureCurve {
+ float gamma = 1.0f; // 0.25 .. 4
+ float minOut = 0.0f; // output at the lightest touch
+ float maxOut = 1.0f; // output at full pressure
+ float threshold = 0.0f; // input at or below this counts as the lightest touch
+ float fullAt = 1.0f; // input at or above this counts as full pressure
+
+ float apply(float pressure) const;
+ bool isLinear() const;
+
+ static PressureCurve soft() { return {0.55f}; }
+ static PressureCurve linear() { return {}; }
+ static PressureCurve firm() { return {1.8f}; }
+};
+
+// What the eraser end or a side button does.
+enum class PenAction {
+ None,
+ Invert, // like holding Alt: brushes subtract (ZBrush Zsub), Alt+drag on the background pans
+ Smooth, // like holding Shift: the Smooth brush
+ RotateView, // hold the button and move the pen to orbit
+ PanView, // hold the button and move the pen to pan
+ RightClick, // a right mouse button: drag to orbit on the canvas, context menus in the UI
+ EraseMask, // eraser only: the eraser removes mask (like Ctrl+Alt)
+};
+
+const char* penActionId(PenAction a); // "invert", "right_click" ... (stored in ui.json)
+const char* penActionLabel(PenAction a); // "Invert (Alt)", "Right-click" ... (Preferences > Tablet)
+PenAction penActionFromId(const std::string& id, PenAction fallback);
+
+constexpr int kPenButtons = 3; // SDL pen buttons 1 (lower barrel), 2 (upper barrel), 3 (third, e.g. Pro Pen 3D)
+
+struct TabletSettings {
+ PressureCurve curve;
+ PenAction eraser = PenAction::Invert;
+ // Lower button: right-click (drag to rotate, as with a Wacom's default mapping); upper: Alt (invert);
+ // third: pan.
+ std::array<PenAction, kPenButtons> buttons{PenAction::RightClick, PenAction::Invert, PenAction::PanView};
+};
+
+Json toJson(const TabletSettings& t);
+void fromJson(const Json& j, TabletSettings& t);
+
+// Guards the start of a pen stroke against pressure spikes: the pen touches down
+// before (or after) its first pressure sample, and the value left over from the
+// previous stroke (or the 1.0 assumed before any sample) may still be high. The
+// first dab waits until a fresh, non-zero sample arrives; the app draws anyway at
+// the first motion for pens that have never reported pressure.
+class PenPressureTracker {
+public:
+ static constexpr float kContact = 0.002f; // below this the tip is not really pressing
+
+ void touchDown() { sinceDown_ = false; }
+ void touchUp() { sinceDown_ = false; }
+ void sample(float pressure);
+ float raw() const { return raw_; }
+ bool everSampled() const { return everSampled_; } // false: maybe a pen without pressure
+ bool readyForFirstDab() const { return sinceDown_ && raw_ > kContact; }
+
+private:
+ float raw_ = 1.0f;
+ bool sinceDown_ = false;
+ bool everSampled_ = false;
+};
+
+} // namespace sf
diff --git a/tests/test_tablet.cpp b/tests/test_tablet.cpp
new file mode 100644
index 00000000..3b4330fe
--- /dev/null
+++ b/tests/test_tablet.cpp
@@ -0,0 +1,116 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Tablet settings: the global pressure curve, pen button / eraser mappings
+// and their JSON round trip, and the stroke-start pressure guard.
+#include "TestHarness.h"
+
+#include "core/Tablet.h"
+
+#include <cmath>
+
+using namespace sf;
+
+namespace {
+bool near(float a, float b, float eps = 1e-4f) { return std::abs(a - b) < eps; }
+} // namespace
+
+TEST(pressure_curve_linear_is_identity) {
+ const PressureCurve c;
+ CHECK(c.isLinear());
+ for (float p : {0.0f, 0.1f, 0.5f, 0.77f, 1.0f}) CHECK(near(c.apply(p), p));
+ CHECK(near(c.apply(-1.0f), 0.0f)); // clamped
+ CHECK(near(c.apply(2.0f), 1.0f));
+ CHECK(near(c.apply(NAN), 0.0f));
+}
+
+TEST(pressure_curve_soft_and_firm) {
+ const PressureCurve soft = PressureCurve::soft(), firm = PressureCurve::firm();
+ CHECK(!soft.isLinear());
+ CHECK(!firm.isLinear());
+ // Same ends, different middle: soft gives more for a light touch, firm needs a harder press.
+ for (const PressureCurve& c : {soft, firm}) {
+ CHECK(near(c.apply(0.0f), 0.0f));
+ CHECK(near(c.apply(1.0f), 1.0f));
+ }
+ CHECK(soft.apply(0.3f) > 0.3f);
+ CHECK(firm.apply(0.3f) < 0.3f);
+ CHECK(near(firm.apply(0.5f), std::pow(0.5f, firm.gamma)));
+ // Monotonic.
+ float last = -1.0f;
+ for (int i = 0; i <= 20; ++i) {
+ const float v = firm.apply(float(i) / 20.0f);
+ CHECK(v >= last);
+ last = v;
+ }
+}
+
+TEST(pressure_curve_min_max_threshold) {
+ PressureCurve c;
+ c.minOut = 0.2f;
+ c.maxOut = 0.8f;
+ CHECK(near(c.apply(0.0f), 0.2f));
+ CHECK(near(c.apply(1.0f), 0.8f));
+ CHECK(near(c.apply(0.5f), 0.5f));
+ c = PressureCurve();
+ c.threshold = 0.1f;
+ c.fullAt = 0.6f;
+ CHECK(near(c.apply(0.05f), 0.0f)); // below the threshold: the lightest touch
+ CHECK(near(c.apply(0.35f), 0.5f)); // halfway between threshold and full
+ CHECK(near(c.apply(0.7f), 1.0f)); // a heavy hand reaches full pressure sooner
+ c.fullAt = c.threshold; // degenerate range must not divide by zero
+ CHECK(std::isfinite(c.apply(0.1f)));
+ c = PressureCurve();
+ c.gamma = 100.0f; // out of range: clamped to 4
+ CHECK(near(c.apply(0.5f), std::pow(0.5f, 4.0f)));
+}
+
+TEST(tablet_settings_json_round_trip) {
+ TabletSettings t;
+ CHECK(t.eraser == PenAction::Invert);
+ CHECK(t.buttons[0] == PenAction::RightClick);
+ CHECK(t.buttons[1] == PenAction::Invert);
+ t.curve = PressureCurve::firm();
+ t.curve.minOut = 0.1f;
+ t.eraser = PenAction::EraseMask;
+ t.buttons = {PenAction::RotateView, PenAction::Smooth, PenAction::None};
+ TabletSettings back;
+ fromJson(toJson(t), back);
+ CHECK(near(back.curve.gamma, t.curve.gamma));
+ CHECK(near(back.curve.minOut, 0.1f));
+ CHECK(back.eraser == PenAction::EraseMask);
+ CHECK(back.buttons[0] == PenAction::RotateView);
+ CHECK(back.buttons[1] == PenAction::Smooth);
+ CHECK(back.buttons[2] == PenAction::None);
+
+ // Unknown or unsuitable values keep the defaults.
+ Json j;
+ std::string err;
+ CHECK(Json::parse(R"({"eraser":"pan","buttons":["erase_mask","bogus"],"pressureCurve":{"gamma":-3}})", j, err));
+ TabletSettings d;
+ fromJson(j, d);
+ CHECK(d.eraser == PenAction::Invert);
+ CHECK(d.buttons[0] == PenAction::RightClick);
+ CHECK(d.buttons[1] == PenAction::Invert);
+ CHECK(near(d.curve.gamma, 0.25f));
+ CHECK(std::string(penActionLabel(PenAction::RightClick)) == "Right-click");
+}
+
+TEST(pen_pressure_tracker_guards_stroke_start) {
+ PenPressureTracker t;
+ t.touchDown();
+ CHECK(!t.readyForFirstDab()); // the first touch after start: 1.0 is only assumed
+ CHECK(!t.everSampled()); // (the app draws at the first motion if no sample ever comes)
+ CHECK(near(t.raw(), 1.0f));
+ t.sample(0.9f); // end of the previous stroke
+ t.touchUp();
+ t.touchDown();
+ CHECK(!t.readyForFirstDab()); // 0.9 is stale: wait for this stroke's own sample
+ t.sample(0.0f);
+ CHECK(!t.readyForFirstDab()); // touching but not pressing yet
+ t.sample(0.15f);
+ CHECK(t.readyForFirstDab());
+ CHECK(near(t.raw(), 0.15f));
+ t.sample(5.0f);
+ CHECK(near(t.raw(), 1.0f));
+}
diff --git a/tests/ui/tablet.sfui b/tests/ui/tablet.sfui
new file mode 100644
index 00000000..574f08bb
--- /dev/null
+++ b/tests/ui/tablet.sfui
@@ -0,0 +1,118 @@
+# Graphics tablet with a simulated pen (real SDL3 pen events plus the mouse events SDL synthesizes from them):
+# pressure, the global pressure curve, Pressure > Size, the eraser end, side buttons, leaving proximity
+# mid-stroke, and Preferences > Tablet.
+run new_sphere subdivisions=5
+snapshot
+
+# No pressure spike at the stroke start: the touch comes before its first pressure sample, and the
+# value before it (1.0 assumed at start-up, or stale from the last stroke) must not reach the first
+# dab. A short stroke, so one wrong dab would show.
+pen_stroke 0.4 0.45 0.45 0.45 0.2 0.2
+remember moved_out short
+key ctrl+z
+pen_pressure 1
+pen_stroke 0.4 0.45 0.45 0.45 0.2 0.2
+expect_value moved_out <= $short*1.01
+expect_value moved_out >= $short*0.99
+key ctrl+z
+pen_stroke 0.4 0.45 0.45 0.45 1 1
+expect_value moved_out > $short*2
+key ctrl+z
+
+# Light and heavy pressure: the heavy stroke pushes the surface out much further.
+pen_stroke 0.3 0.45 0.7 0.55 0.2 0.2
+expect_value moved_out > 0
+remember moved_out light
+remember moved light_area
+expect_value can_undo == 1
+key ctrl+z
+expect_value moved == 0
+pen_stroke 0.3 0.45 0.7 0.55 0.9 0.9
+expect_value moved_out > $light*3
+remember moved_out heavy
+key ctrl+z
+
+
+# The mouse always presses fully, whatever the pen did last.
+stroke 0.3 0.45 0.7 0.55
+expect_value brush_pressure == 1
+expect_value moved_out > $heavy
+key ctrl+z
+
+# Pressure > Size (top shelf): a light touch also makes the brush smaller.
+click "Pressure > Size"
+pen_stroke 0.3 0.45 0.7 0.55 0.2 0.2
+expect_value moved < $light_area*0.6
+key ctrl+z
+click "Pressure > Size"
+
+# The eraser end inverts the brush: the surface goes in.
+pen_stroke 0.3 0.45 0.7 0.55 0.6 0.6 eraser
+expect_value moved_out < 0
+shot eraser
+key ctrl+z
+
+# Upper side button = Alt (default): inverts while held.
+pen_button 2 down
+pen_stroke 0.3 0.45 0.7 0.55 0.6 0.6
+pen_button 2 up
+expect_value moved_out < 0
+key ctrl+z
+pen_stroke 0.3 0.45 0.7 0.55 0.6 0.6
+expect_value moved_out > 0
+key ctrl+z
+
+# Lower side button = right-click (default): drag to rotate. SDL's own synthesized click is ignored.
+pen_hover 0.5 0.5
+remember camera_yaw yaw
+pen_button 1 down
+pen_hover 0.9 0.5
+pen_button 1 up
+expect_value camera_yaw != $yaw
+expect_value moved == 0
+
+# Out of range mid-stroke: the stroke still ends cleanly, as one undo step.
+pen_stroke 0.3 0.45 0.7 0.55 0.6 0.6 leave
+expect_value stroking == 0
+expect_value moved_out > 0
+key ctrl+z
+expect_value moved == 0
+expect_value can_undo == 0
+
+# Preferences > Tablet: device, live pressure meter, draw-test area, curve editor, mappings.
+click "Preferences##palette.preferences"
+click "Tablet##preferences.tablet"
+expect_text Pressure curve (all brushes)
+expect "##Lower button"
+pen_drag_item "##tablet_test" 220 0 0.05 1.0 0.8
+pen_pressure 0.62
+expect_value pen_pressure == 0.62
+expect_text Pressure 0.62
+wait 0.1
+shot preferences-tablet
+
+# A firm global curve: the same light stroke now does much less.
+click "Firm##tablet_curve"
+wait 0.1
+shot curve-firm
+key escape
+pen_stroke 0.3 0.45 0.7 0.55 0.2 0.2
+expect_value moved_out < $light*0.5
+expect_value moved_out > 0
+key ctrl+z
+
+# Eraser mapped to Erase mask: the eraser removes mask instead of sculpting.
+click "Preferences##palette.preferences"
+click "Linear##tablet_curve"
+click "##Eraser"
+click "Erase mask##Eraser"
+expect_text Erase mask
+key escape
+hold ctrl
+stroke 0.2 0.5 0.8 0.5
+hold none
+expect_value masked > 50
+remember masked mask_before
+pen_stroke 0.2 0.5 0.8 0.5 1 1 eraser
+expect_value masked < $mask_before*0.5
+expect_value moved == 0