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.

Line Gradient (#99): Color > Line Gradient drags a screen-space colour ramp (to a second colour or to clear) into vertex paint or the texture; adjustable end handles, one undo step, respects the mask; paint_gradient command

islandmedad3e1378d941
diff --git a/CMakeLists.txt b/CMakeLists.txt
index ffe7a2e6..92fcd279 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -411,6 +411,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/PanelBrushLibrary.cpp
src/app/PanelBrushGallery.cpp
src/app/PanelVertexPaint.cpp
+ src/app/LineGradient.cpp
src/app/PanelPacks.cpp
src/app/MemoryConfirm.cpp
src/app/PanelPaintLayers.cpp
diff --git a/assets/fonts/NotoSansTC-UI.otf b/assets/fonts/NotoSansTC-UI.otf
index 6e85706e..6b27f320 100644
Binary files a/assets/fonts/NotoSansTC-UI.otf and b/assets/fonts/NotoSansTC-UI.otf differ
diff --git a/changes/feat-line-gradient.md b/changes/feat-line-gradient.md
new file mode 100644
index 00000000..e626990f
--- /dev/null
+++ b/changes/feat-line-gradient.md
@@ -0,0 +1,10 @@
+---
+whats_new: **Line Gradient**: **Color > Line Gradient**, then drag across the model: the paint colour runs into a second colour (or fades out) along the line; drag its ends to adjust it. Thanks @Devon0209 (#99).
+added: **Line Gradient** (Color, #99, requested by @Devon0209): a screen-space colour ramp for vertex paint and textures,
+ its ends adjustable before you keep it (Enter; Esc takes it back); respects the mask, one undo step. Script: `paint_gradient`.
+testers:
+ - Color > Line Gradient, drag across a sphere: the paint colour runs into the End colour (black); drag an end handle:
+ the ramp follows. Ctrl+Z once removes it.
+ - Mask the top (Ctrl+drag), tick Clear, drag again: the masked part keeps its paint, the rest fades out along the line.
+ - In a texture (Tool > Texture Map > New Texture): the ramp is smooth across the texture.
+---
diff --git a/docs/guide/interface.md b/docs/guide/interface.md
index a0172ac9..33dc8c29 100644
--- a/docs/guide/interface.md
+++ b/docs/guide/interface.md
@@ -161,7 +161,7 @@ turn on **Edit > Preferences > Interface > Palettes strictly A-Z (strict order)*
| **Edit** | Edit | Undo and Redo (with the name of the step), Paste brush |
| **Alpha** | Sculpt > Alpha | The brush alphas: Round, Square, Noise and twelve patterns (Pores, Cracks, Scales...), images from your library, Load image, Invert loaded image |
| **Brush** | Sculpt > Brush | AI Brush (Brush Lab), Community brushes, Paste brush, your custom brushes, Front faces only, Invert (Alt), the recipe editor for a custom brush, and every brush as a thumbnail grid with a filter |
-| **Color** | Paint | The Paint brush, RGB while sculpting, the paint colour and swatches, Fill, Fill masked, Cavity, Clear, Show vertex paint |
+| **Color** | Paint | The Paint brush, RGB while sculpting, the paint colour and swatches, Fill, Fill masked, Cavity, Clear, Line Gradient, Show vertex paint |
| **Draw** | Sculpt > Draw & Tablet | Size, Intensity, Colour intensity, Falloff, Sculpt/Paint, Add/Sub, Rgb, Front, and the tablet options (Pressure > strength, Pressure > size) with a pen readout |
| **Generate** | Mesh > Generate 3D (Mesh > From Image while Edit > Preferences > AI is off) | Generate 3D (image or text to 3D), Relief, Inflate and Stamp from an image, and the AI brush provider settings; with AI off only Relief, Inflate and Stamp |
| **Material** | Render > Materials | The Lit Sphere materials (Soft Clay, the default, first), your own (**Load Lit Sphere...**) and Studio, Base colour, Smooth / Flat shading for the scene and the active Part |
diff --git a/docs/guide/vertex-paint.md b/docs/guide/vertex-paint.md
index 6184d04a..5ef3871b 100644
--- a/docs/guide/vertex-paint.md
+++ b/docs/guide/vertex-paint.md
@@ -67,6 +67,19 @@ off in the viewport without deleting them.
> **Tip:** To paint a base colour and then dirt in the creases: **Fill** with the base colour, then **Cavity**. For
> a different cavity colour or strength, use the command (below).
+## Line Gradient
+
+**Line Gradient** (under **Clear**) paints a straight colour ramp across the model as you see it: turn it on, then drag
+a line over the view. The paint colour at the start of the line runs into the **End** colour at its end; past the ends
+the two colours carry on. Tick **Clear** to fade the paint colour out instead, so the paint underneath shows through
+towards the end. The swap button swaps the two colours.
+
+The line stays on screen with a handle at each end until you keep it: drag a handle, or change a colour, and the
+gradient is painted again in place of the last one. <kbd>Enter</kbd> keeps it (so does turning the view or any other
+edit), <kbd>Esc</kbd> takes it back. Each gradient is one undo step. It respects the mask like **Fill**, never paints
+hidden faces, and goes into the texture when the Part paints into one. With it on, <kbd>Ctrl</kbd> still masks and
+<kbd>Shift</kbd> still smooths; turn it off with its button or <kbd>Esc</kbd>.
+
## Paint layers
Paint layers stack vertex paint the way Photoshop stacks image layers. Each layer has its own name, visibility,
@@ -250,6 +263,7 @@ classic key changes meaning; assign one under **Edit > Preferences > Hotkeys** i
|---|---|
| `set_color color=#c08060` | Set the paint colour: `rrggbb`, `#rrggbb` (quote it in scripts), `r,g,b` or a name such as `white`, `skin`, `bone` |
| `paint_fill area=unmasked` | Fill; `area` is `unmasked` (default), `masked` or `all`; `strength` 0-1 |
+| `paint_gradient x0=-1 y0=0 x1=1 y1=0 to=clear` | Line Gradient from the paint colour (or `color`) at the start to `to` (a colour, or `clear`) at the end; the line in -1..1 view coordinates (`view_proj`, default the front view); `area` as `paint_fill` |
| `paint_from_cavity color=#202020 strength=0.7 smoothing=2` | Cavity paint (defaults: dark brown, 0.7, 2 blur passes) |
| `paint_clear` | Remove all vertex paint, paint layers included |
| `paint_layer_add name=Dirt blend=multiply opacity=0.8` | Add a paint layer above the active one and paint on it |
diff --git a/src/app/App.cpp b/src/app/App.cpp
index d5e9a485..94e45a0e 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -1724,6 +1724,7 @@ void App::onMouseDown(float x, float y, Uint8 button) {
if (button == SDL_BUTTON_LEFT) {
if (axisGizmoMouseDown(x, y)) return; // the axis gizmo's ends snap to a side view (#43)
if (forgesphereMouseDown(x, y, mod)) return; // a Forge Sphere Part takes clicks on it (PanelForge Spheres.cpp)
+ if (gradientMouseDown(x, y, nav)) return; // Line Gradient: a new line or an end handle (LineGradient.cpp)
if (facegroupMouseDown(x, y, mod)) return;
if (maskSelectMouseDown(x, y, mod)) return;
if (gizmoMouseDown(x, y, mod)) return; // Transform gizmo handles, pivot clicks (Gizmo.cpp)
@@ -1902,6 +1903,7 @@ void App::onMouseMove(float x, float y, float dx, float dy, bool fromPen) {
case Drag::UvTool: uvToolDragTo(x, y); break;
case Drag::Sculptable: sculptableMouseMove(x, y); break;
case Drag::Capture: captureMouseMove(x, y); break;
+ case Drag::Gradient: gradientMouseMove(x, y); break;
case Drag::ForgeSphere: forgesphereDragTo(x, y); break;
case Drag::AirStroke: airStrokeTo(x, y); break;
case Drag::QuickRemesh: break; // (remeshes when let go)
@@ -2040,6 +2042,7 @@ void App::onMouseUp() {
if (drag_ == Drag::UvTool) uvToolRelease();
if (drag_ == Drag::Sculptable) sculptableMouseUp();
if (drag_ == Drag::Capture) captureMouseUp();
+ if (drag_ == Drag::Gradient) gradientMouseUp();
if (drag_ == Drag::ForgeSphere) forgesphereRelease();
if (drag_ == Drag::AirStroke) airStrokeRelease();
gizmoRelease();
@@ -2050,6 +2053,7 @@ void App::onMouseUp() {
void App::onKey(SDL_Keycode key, SDL_Keymod mod) {
if (cutPolylineKey(key)) return; // Enter ends a Cut Polyline, Esc drops it (PanelCut.cpp)
+ if (gradientKey(key)) return; // Enter keeps a Line Gradient, Esc takes it back (LineGradient.cpp)
if (key == SDLK_ESCAPE && radial_.menu >= 0) {
closeRadialMenu();
return;
@@ -2909,6 +2913,7 @@ void App::drawUi() {
drawSplatTrainOverlay(); // splat training progress (PanelSplatTrain.cpp)
drawSculptableOverlay(); // Make sculptable: crop box, face landmarks (PanelSculptable.cpp)
drawCaptureOverlay(); // Capture from view: the square, the result window (PanelKelvinlet.cpp)
+ drawGradientOverlay(); // Line Gradient: the line and its end handles (LineGradient.cpp)
if (uiPrefs_.showAxes) drawAxisGizmo(); // X / Y / Z in the canvas corner (#31)
if (uiPrefs_.showViewFigure) drawViewFigure();
drawAirStrokeIndicator(); // Start strokes off the model is on (#62, Input.cpp)
@@ -2929,6 +2934,7 @@ void App::drawUi() {
if (!sliderRing) sizeRingPreview_ = false;
if (((!ImGui::GetIO().WantCaptureMouse && canvasRect().contains(mouse.x, mouse.y)) || drag_ == Drag::Stroke || sliderRing) &&
!hideBrushCursor_ && radial_.menu < 0 && !strokePopup_.open && drag_ != Drag::Select && drag_ != Drag::Guide && // (no ring under a pie or the stroke popup)
+ (!gradient_.armed || ctrlDown(inputMods()) || (inputMods() & SDL_KMOD_SHIFT)) && // (nor while a Line Gradient takes the drags)
aiLinkStateValue() != 2 && aiLinkStateValue() != 4 && // (nor over a live-mode question: it is drawn above windows)
(!ringOff || drag_ == Drag::Stroke || ctrlDown(inputMods())))
drawBrushCursor();
diff --git a/src/app/App.h b/src/app/App.h
index 0dcea562..8dc68dcb 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -164,7 +164,7 @@ public:
private:
enum class Drag { None, Stroke, Orbit, Pan, Zoom, Roll, MaskCanvas, PartClick, Select, Gizmo, Guide, Sculptable, ForgeSphere, Insert, Capture,
- AirStroke, UvTool, SizeScrub, QuickRemesh }; // AirStroke: a stroke begun off the model, waiting to reach it (#62)
+ AirStroke, UvTool, SizeScrub, QuickRemesh, Gradient }; // AirStroke: a stroke begun off the model, waiting to reach it (#62)
void handleEvent(const SDL_Event& e); // the pen's mouse events first (penMouseEvents), then dispatchEvent
void dispatchEvent(const SDL_Event& e);
@@ -911,6 +911,34 @@ private:
std::string error;
char name[64] = "Captured";
} capture_;
+ // Line Gradient (#99, LineGradient.cpp): Color > Line Gradient arms it; a drag on the view paints a colour ramp
+ // (paint_gradient) whose two ends stay draggable, each change painting it again in place of the same undo step.
+ // Enter, a camera move or any other edit keeps it; Esc takes it back.
+ void registerLineGradientActions();
+ bool gradientMouseDown(float x, float y, SDL_Keymod mod); // true when it takes the click
+ void gradientMouseMove(float x, float y);
+ void gradientMouseUp();
+ bool gradientKey(SDL_Keycode key); // Enter / Esc
+ void applyGradient();
+ void endGradientEdit();
+ void drawGradientOverlay();
+ void drawLineGradientControls(); // Color palette
+ bool gradientUiValue(const std::string& name, double& out) const; // UI test values
+ struct GradientUi {
+ bool armed = false;
+ bool placed = false; // painted, and its ends can still move
+ int handle = -1; // being dragged: 0 the start, 1 the end, 2 a new line
+ glm::vec2 a{0.0f}, b{0.0f}; // window pixels
+ glm::vec2 grabOffset{0.0f}; // from the pointer to the handle it grabbed
+ glm::vec3 to{0.0f}; // the End colour (linear)
+ bool toClear = false;
+ uint64_t revision = 0; // the undo history right after it was painted
+ glm::mat4 view{1.0f}; // the camera and canvas it was painted in
+ glm::vec4 canvas{0.0f};
+ glm::vec2 appliedA{0.0f}, appliedB{0.0f};
+ glm::vec3 appliedFrom{0.0f}, appliedTo{0.0f};
+ bool appliedClear = false;
+ } gradient_;
glm::vec3 kelvinCenter_{0.0f};
float kelvinRadius_ = 0.0f, kelvinLastX_ = 0.0f;
glm::vec3 kelvinTarget_{0.0f}; // KelvinGrab: where the cursor wants the grabbed point
diff --git a/src/app/Config.cpp b/src/app/Config.cpp
index edac560a..64bea9fa 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -760,6 +760,7 @@ void App::initActions() {
// the same id and own P (Paint), the symmetry toggles and Tab.
registerShellActions();
registerTextureUiActions(); // Tool > Texture Map, the Vertex / Texture paint target (PanelTexture.cpp)
+ registerLineGradientActions(); // Color > Line Gradient (LineGradient.cpp)
registerPbrUiActions(); // material channels, solo view, map export (PanelPbr.cpp)
registerGizmoActions(); // Q W E R: Draw, and the Transform gizmo's Move, Scale, Rotate (Gizmo.cpp)
registerBakeUiActions(); // Tool > Bake (PanelBake.cpp)
diff --git a/src/app/I18nSimplifiedChinese.cpp b/src/app/I18nSimplifiedChinese.cpp
index fdc0fcc1..edbe8a54 100644
--- a/src/app/I18nSimplifiedChinese.cpp
+++ b/src/app/I18nSimplifiedChinese.cpp
@@ -701,6 +701,20 @@ constexpr Entry kSimplifiedChinese[] = {
{"Fill", "填满"},
{"Fill layer", "填满图层"},
{"Fill masked", "填满遮罩区域"},
+ {"Line Gradient", "线性渐变"},
+ {"End", "终点"},
+ {"Swap", "交换"},
+ {"Drag a line across the model.", "在模型上拖动一条线。"},
+ {"Drag its ends to adjust. Enter keeps it, Esc takes it back.", "拖动两端即可调整。Enter 保留,Esc 撤回。"},
+ {"Swap the paint colour and the End colour.", "交换绘制颜色与终点颜色。"},
+ {"The colour at the end of the line. The start is the paint colour above.",
+ "线条终点的颜色。起点是上方的绘制颜色。"},
+ {"Fade the paint colour out instead: the paint underneath shows through towards the end of the line.",
+ "改为让绘制颜色淡出:越接近线条终点,下面原有的颜色越明显。"},
+ {"Drag a line across the model: the paint colour at its start runs into the End colour (or fades to "
+ "clear) at its end, in screen space, into vertex paint or the texture. Drag either end to adjust it; "
+ "Enter keeps it, Esc takes it back. Respects the mask; one undo step.",
+ "在模型上拖动一条线:起点的绘制颜色会在终点渐变为终点颜色(或淡出),按屏幕空间计算,画入顶点绘制或贴图。拖动任一端即可调整;Enter 保留,Esc 撤回。遵守遮罩;一个撤销步骤。"},
{"Fill the unmasked area (the whole mesh if nothing is masked)", "填满未遮罩区域(若没有任何遮罩,则填满整个网格)"},
{"Cavity", "凹陷"},
{"Darken creases and cavities (respects the mask)", "加深皱褶与凹陷(遵循遮罩)"},
diff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cpp
index cbca1f9f..ea3f08d2 100644
--- a/src/app/I18nSpanish.cpp
+++ b/src/app/I18nSpanish.cpp
@@ -843,6 +843,24 @@ constexpr Entry kSpanish[] = {
{"Fill", "Rellenar"},
{"Fill layer", "Rellenar capa"},
{"Fill masked", "Rellenar enmascarado"},
+ {"Line Gradient", "Degradado lineal"},
+ {"End", "Final"},
+ {"Swap", "Intercambiar"},
+ {"Drag a line across the model.", "Arrastra una línea sobre el modelo."},
+ {"Drag its ends to adjust. Enter keeps it, Esc takes it back.", "Arrastra sus extremos para ajustarlo. Intro lo conserva, Esc lo deshace."},
+ {"Swap the paint colour and the End colour.", "Intercambia el color de pintura y el color final."},
+ {"The colour at the end of the line. The start is the paint colour above.",
+ "El color al final de la línea. El inicio es el color de pintura de arriba."},
+ {"Fade the paint colour out instead: the paint underneath shows through towards the end of the line.",
+ "En su lugar, desvanece el color de pintura: la pintura de debajo se ve cada vez más hacia el final de "
+ "la línea."},
+ {"Drag a line across the model: the paint colour at its start runs into the End colour (or fades to "
+ "clear) at its end, in screen space, into vertex paint or the texture. Drag either end to adjust it; "
+ "Enter keeps it, Esc takes it back. Respects the mask; one undo step.",
+ "Arrastra una línea sobre el modelo: el color de pintura de su inicio pasa al color final (o se "
+ "desvanece) en su extremo, en el espacio de la pantalla, en la pintura de vértices o en la textura. "
+ "Arrastra cualquiera de los extremos para ajustarlo; Intro lo conserva, Esc lo deshace. Respeta la "
+ "máscara; un solo paso de deshacer."},
{"Fill the unmasked area (the whole mesh if nothing is masked)",
"Rellena la zona sin máscara (toda la malla si no hay nada enmascarado)"},
{"Cavity", "Cavidad"},
diff --git a/src/app/I18nTraditionalChinese.cpp b/src/app/I18nTraditionalChinese.cpp
index cf787c0e..6ce08ea3 100644
--- a/src/app/I18nTraditionalChinese.cpp
+++ b/src/app/I18nTraditionalChinese.cpp
@@ -701,6 +701,20 @@ constexpr Entry kTraditionalChinese[] = {
{"Fill", "填滿"},
{"Fill layer", "填滿圖層"},
{"Fill masked", "填滿遮罩區域"},
+ {"Line Gradient", "線性漸層"},
+ {"End", "終點"},
+ {"Swap", "交換"},
+ {"Drag a line across the model.", "在模型上拖曳一條線。"},
+ {"Drag its ends to adjust. Enter keeps it, Esc takes it back.", "拖曳兩端即可調整。Enter 保留,Esc 撤回。"},
+ {"Swap the paint colour and the End colour.", "交換繪製顏色與終點顏色。"},
+ {"The colour at the end of the line. The start is the paint colour above.",
+ "線條終點的顏色。起點是上方的繪製顏色。"},
+ {"Fade the paint colour out instead: the paint underneath shows through towards the end of the line.",
+ "改為讓繪製顏色淡出:越接近線條終點,底下原有的顏色越明顯。"},
+ {"Drag a line across the model: the paint colour at its start runs into the End colour (or fades to "
+ "clear) at its end, in screen space, into vertex paint or the texture. Drag either end to adjust it; "
+ "Enter keeps it, Esc takes it back. Respects the mask; one undo step.",
+ "在模型上拖曳一條線:起點的繪製顏色會在終點漸變為終點顏色(或淡出),依螢幕空間計算,畫入頂點繪製或貼圖。拖曳任一端即可調整;Enter 保留,Esc 撤回。遵守遮罩;一個復原步驟。"},
{"Fill the unmasked area (the whole mesh if nothing is masked)", "填滿未遮罩區域(若沒有任何遮罩,則填滿整個網格)"},
{"Cavity", "凹陷"},
{"Darken creases and cavities (respects the mask)", "加深皺褶與凹陷(遵循遮罩)"},
diff --git a/src/app/LineGradient.cpp b/src/app/LineGradient.cpp
new file mode 100644
index 00000000..35113560
--- /dev/null
+++ b/src/app/LineGradient.cpp
@@ -0,0 +1,263 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Line Gradient (#99): Color > Line Gradient, then a drag across the view paints a straight colour ramp from the
+// paint colour to the End colour (or to clear) with paint_gradient (core/VertexPaint.h), into vertex paint or the
+// texture. Its two ends stay on screen as handles: dragging one, or changing a colour, paints it again in place of
+// the same undo step. Enter (or a camera move, or any other edit) keeps it; Esc takes it back.
+#include "app/App.h"
+#include "app/I18n.h"
+#include "app/Ui.h"
+
+#include "core/VertexPaint.h"
+
+#include <IconsLucide.h>
+
+#include <glm/gtc/type_ptr.hpp>
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+
+namespace sf {
+
+namespace {
+
+constexpr float kHandleRadius = 7.0f; // logical px; a little more is grabbable
+constexpr float kMinLinePx = 6.0f; // shorter drags are clicks
+
+std::string matrixText(const glm::mat4& m) {
+ std::string s;
+ char buf[32];
+ for (int i = 0; i < 16; ++i) {
+ std::snprintf(buf, sizeof buf, "%s%.9g", i ? " " : "", double(m[i / 4][i % 4]));
+ s += buf;
+ }
+ return s;
+}
+
+ImU32 displayColor(const glm::vec3& linear, int alpha = 255) {
+ const glm::vec3 c = glm::clamp(linearToSrgb(linear), 0.0f, 1.0f);
+ return IM_COL32(int(c.x * 255.0f + 0.5f), int(c.y * 255.0f + 0.5f), int(c.z * 255.0f + 0.5f), alpha);
+}
+
+} // namespace
+
+void App::registerLineGradientActions() {
+ Action a;
+ a.id = "paint.line_gradient";
+ a.label = "Line Gradient";
+ a.icon = ICON_LC_BLEND;
+ a.palette = "Color";
+ a.description = "Drag a line across the model: the paint colour at its start runs into the End colour (or fades to "
+ "clear) at its end, in screen space, into vertex paint or the texture. Drag either end to adjust it; "
+ "Enter keeps it, Esc takes it back. Respects the mask; one undo step.";
+ a.command = "paint_gradient";
+ a.run = [this] {
+ if (gradient_.armed) {
+ gradient_.armed = false;
+ endGradientEdit();
+ status_ = "Line Gradient off";
+ } else {
+ gradient_.armed = true;
+ status_ = "Line Gradient: drag across the model (Esc: off)";
+ }
+ };
+ a.checked = [this] { return gradient_.armed; };
+ a.enabled = [this] { return doc_.mesh.vertexCount() > 0; };
+ actions_.add(std::move(a));
+}
+
+bool App::gradientMouseDown(float x, float y, SDL_Keymod mod) {
+ // Ctrl, Shift and Alt keep their gestures (masking, smoothing, navigation) while it is on.
+ if (!gradient_.armed || (mod & (SDL_KMOD_CTRL | SDL_KMOD_SHIFT | SDL_KMOD_ALT | SDL_KMOD_GUI))) return false;
+ const glm::vec2 p(x, y);
+ const float grab = (kHandleRadius + 5.0f) * uiScale_;
+ gradient_.handle = 2;
+ if (gradient_.placed) { // an end under the pointer moves; anywhere else starts a new gradient (the last one stays)
+ const float da = glm::distance(p, gradient_.a), db = glm::distance(p, gradient_.b);
+ if (std::min(da, db) <= grab) gradient_.handle = da <= db ? 0 : 1;
+ else endGradientEdit();
+ }
+ if (gradient_.handle == 2) gradient_.a = gradient_.b = p;
+ gradient_.grabOffset = gradient_.handle == 0 ? gradient_.a - p : gradient_.handle == 1 ? gradient_.b - p : glm::vec2(0.0f);
+ drag_ = Drag::Gradient;
+ return true;
+}
+
+void App::gradientMouseMove(float x, float y) {
+ const glm::vec2 p = glm::vec2(x, y) + gradient_.grabOffset;
+ if (gradient_.handle == 0) gradient_.a = p;
+ else gradient_.b = p; // the end of a new line, or the end handle
+}
+
+void App::gradientMouseUp() {
+ const int handle = gradient_.handle;
+ gradient_.handle = -1;
+ if (glm::distance(gradient_.a, gradient_.b) < kMinLinePx * uiScale_) {
+ if (handle == 2) status_ = "Line Gradient: drag a line across the model";
+ else applyGradient(); // an end dropped onto the other: put the last good one back
+ return;
+ }
+ applyGradient();
+}
+
+void App::applyGradient() {
+ const CanvasRect c = canvasRect();
+ if (c.w <= 0.0f || c.h <= 0.0f) return;
+ if (glm::distance(gradient_.a, gradient_.b) < kMinLinePx * uiScale_) {
+ if (gradient_.placed) { // restore the ends it was painted with
+ gradient_.a = gradient_.appliedA;
+ gradient_.b = gradient_.appliedB;
+ }
+ return;
+ }
+ // A gradient still being adjusted replaces its own undo step (nothing else has been done since).
+ if (gradient_.placed && doc_.undo.revision() == gradient_.revision) runCommand("undo");
+ gradient_.placed = false;
+ auto ndc = [&](glm::vec2 p) { return glm::vec2((p.x - c.x) / c.w * 2.0f - 1.0f, 1.0f - (p.y - c.y) / c.h * 2.0f); };
+ const glm::vec2 a = ndc(gradient_.a), b = ndc(gradient_.b);
+ const uint64_t before = doc_.undo.revision();
+ runCommand("paint_gradient", {{"x0", double(a.x)}, {"y0", double(a.y)}, {"x1", double(b.x)}, {"y1", double(b.y)},
+ {"color", colorToHex(doc_.paintColor)},
+ {"to", gradient_.toClear ? std::string("clear") : colorToHex(gradient_.to)},
+ {"aspect", double(c.w / c.h)},
+ {"view_proj", matrixText(camera_.projection() * camera_.view())}});
+ if (!lastCommandOk_ || doc_.undo.revision() == before) return;
+ gradient_.placed = true;
+ gradient_.revision = doc_.undo.revision();
+ gradient_.view = camera_.view();
+ gradient_.canvas = glm::vec4(c.x, c.y, c.w, c.h);
+ gradient_.appliedA = gradient_.a;
+ gradient_.appliedB = gradient_.b;
+ gradient_.appliedFrom = doc_.paintColor;
+ gradient_.appliedTo = gradient_.to;
+ gradient_.appliedClear = gradient_.toClear;
+ status_ = "Line Gradient: drag its ends to adjust; Enter keeps it, Esc takes it back";
+}
+
+void App::endGradientEdit() {
+ gradient_.placed = false;
+ gradient_.handle = -1;
+}
+
+bool App::gradientKey(SDL_Keycode key) {
+ if (!gradient_.armed) return false;
+ if (key == SDLK_RETURN || key == SDLK_KP_ENTER) {
+ if (!gradient_.placed) return false;
+ endGradientEdit();
+ status_ = "Line Gradient kept";
+ return true;
+ }
+ if (key != SDLK_ESCAPE) return false;
+ if (gradient_.placed) {
+ if (doc_.undo.revision() == gradient_.revision) runCommand("undo");
+ endGradientEdit();
+ status_ = "Line Gradient taken back";
+ } else {
+ gradient_.armed = false;
+ status_ = "Line Gradient off";
+ }
+ return true;
+}
+
+void App::drawGradientOverlay() {
+ if (!gradient_.armed) return;
+ const CanvasRect c = canvasRect();
+ if (gradient_.placed && gradient_.handle < 0) {
+ // The view or the history moved on: the gradient stays as painted and its handles go.
+ if (doc_.undo.revision() != gradient_.revision || camera_.view() != gradient_.view ||
+ gradient_.canvas != glm::vec4(c.x, c.y, c.w, c.h))
+ endGradientEdit();
+ // A colour changed (the picker, a swatch, End, Clear) once the mouse is up: paint it again.
+ else if (!ImGui::IsMouseDown(ImGuiMouseButton_Left) &&
+ (doc_.paintColor != gradient_.appliedFrom || gradient_.toClear != gradient_.appliedClear ||
+ (!gradient_.toClear && gradient_.to != gradient_.appliedTo)))
+ applyGradient();
+ }
+ const bool dragging = drag_ == Drag::Gradient;
+ if (!gradient_.placed && !dragging) return;
+ if (dragging && gradient_.handle == 2 && glm::distance(gradient_.a, gradient_.b) < 1.0f) return;
+ ImDrawList* dl = ImGui::GetForegroundDrawList();
+ dl->PushClipRect(ImVec2(c.x, c.y), ImVec2(c.x + c.w, c.y + c.h), true);
+ const float s = uiScale_;
+ const ImVec2 a(gradient_.a.x, gradient_.a.y), b(gradient_.b.x, gradient_.b.y);
+ const glm::vec2 d = gradient_.b - gradient_.a;
+ const float len = std::max(glm::length(d), 1e-3f);
+ const glm::vec2 n = glm::vec2(-d.y, d.x) / len; // across the line
+ // The ramp along the line, over a dark edge so it reads on any model and background.
+ LineGradient g;
+ g.from = doc_.paintColor;
+ g.to = gradient_.to;
+ g.toClear = gradient_.toClear;
+ dl->AddLine(a, b, IM_COL32(0, 0, 0, 150), 6.0f * s);
+ constexpr int kSegments = 24;
+ for (int i = 0; i < kSegments; ++i) {
+ const float t0 = float(i) / kSegments, t1 = float(i + 1) / kSegments;
+ const glm::vec4 col = g.at(0.5f * (t0 + t1));
+ const glm::vec2 p0 = gradient_.a + d * t0, p1 = gradient_.a + d * t1;
+ dl->AddLine(ImVec2(p0.x, p0.y), ImVec2(p1.x, p1.y), displayColor(glm::vec3(col), int(60 + 195 * col.w)), 3.0f * s);
+ }
+ // Ticks across both ends: the bands run parallel to them.
+ const float tick = 14.0f * s;
+ for (const glm::vec2& e : {gradient_.a, gradient_.b}) {
+ dl->AddLine(ImVec2(e.x - n.x * tick, e.y - n.y * tick), ImVec2(e.x + n.x * tick, e.y + n.y * tick), IM_COL32(0, 0, 0, 150), 3.5f * s);
+ dl->AddLine(ImVec2(e.x - n.x * tick, e.y - n.y * tick), ImVec2(e.x + n.x * tick, e.y + n.y * tick), IM_COL32(255, 255, 255, 200), 1.5f * s);
+ }
+ // The handles: filled with their colour (the end hollow when it fades to clear), the one under the pointer lit.
+ const glm::vec2 mouse(mouseX_, mouseY_);
+ const float r = kHandleRadius * s, grab = (kHandleRadius + 5.0f) * s;
+ for (int h = 0; h < 2; ++h) {
+ const ImVec2 p = h == 0 ? a : b;
+ const bool hot = gradient_.handle == h ||
+ (gradient_.handle < 0 && gradient_.placed && glm::distance(mouse, glm::vec2(p.x, p.y)) <= grab);
+ dl->AddCircleFilled(p, r + 2.0f * s, IM_COL32(0, 0, 0, 160), 24);
+ if (h == 1 && gradient_.toClear) {
+ dl->AddCircleFilled(p, r, IM_COL32(40, 40, 44, 200), 24);
+ dl->AddLine(ImVec2(p.x - r * 0.6f, p.y + r * 0.6f), ImVec2(p.x + r * 0.6f, p.y - r * 0.6f), IM_COL32(230, 90, 80, 255), 1.5f * s);
+ } else {
+ dl->AddCircleFilled(p, r, displayColor(h == 0 ? doc_.paintColor : gradient_.to), 24);
+ }
+ dl->AddCircle(p, r, hot ? ui::color::accent : IM_COL32(255, 255, 255, 230), 24, (hot ? 2.5f : 1.5f) * s);
+ }
+ dl->PopClipRect();
+}
+
+// Color palette: the Line Gradient button and, while it is on, its End colour.
+void App::drawLineGradientControls() {
+ ui::ActionButton(*this, "paint.line_gradient", ImVec2(-1, 0), ui::Look::IconLabel);
+ if (!gradient_.armed) return;
+ ImGui::AlignTextToFramePadding();
+ ImGui::TextDisabled("%s", tr("End"));
+ ImGui::SameLine();
+ ImGui::BeginDisabled(gradient_.toClear);
+ glm::vec3 srgb = linearToSrgb(gradient_.to);
+ if (ImGui::ColorEdit3("##gradient_end", glm::value_ptr(srgb), ImGuiColorEditFlags_NoInputs))
+ gradient_.to = srgbToLinear(srgb);
+ ImGui::EndDisabled();
+ ui::HelpText("End", nullptr, "The colour at the end of the line. The start is the paint colour above.", "Color > Line Gradient");
+ ImGui::SameLine();
+ ui::Checkbox(tr("Clear##gradient"), &gradient_.toClear);
+ ui::HelpText("Clear", nullptr,
+ "Fade the paint colour out instead: the paint underneath shows through towards the end of the line.",
+ "Color > Line Gradient");
+ ImGui::SameLine();
+ ImGui::BeginDisabled(gradient_.toClear);
+ if (ui::GlyphButton("##gradient_swap", ICON_LC_ARROW_LEFT_RIGHT, ImVec2(ImGui::GetFrameHeight(), ImGui::GetFrameHeight())))
+ std::swap(doc_.paintColor, gradient_.to);
+ ImGui::EndDisabled();
+ ui::HelpText("Swap", nullptr, "Swap the paint colour and the End colour.", "Color > Line Gradient");
+ ImGui::PushTextWrapPos(0.0f);
+ ImGui::TextDisabled("%s", gradient_.placed ? tr("Drag its ends to adjust. Enter keeps it, Esc takes it back.")
+ : tr("Drag a line across the model."));
+ ImGui::PopTextWrapPos();
+}
+
+bool App::gradientUiValue(const std::string& name, double& out) const {
+ if (name == "gradient_armed") out = gradient_.armed ? 1.0 : 0.0;
+ else if (name == "gradient_placed") out = gradient_.placed ? 1.0 : 0.0;
+ else return false;
+ return true;
+}
+
+} // namespace sf
diff --git a/src/app/PanelVertexPaint.cpp b/src/app/PanelVertexPaint.cpp
index 388e7fba..e4c4bc25 100644
--- a/src/app/PanelVertexPaint.cpp
+++ b/src/app/PanelVertexPaint.cpp
@@ -555,6 +555,7 @@ void App::drawPalette_Color() {
if (ImGui::Button(tr("Clear"), ImVec2(half, 0))) runCommand("paint_clear");
ImGui::EndDisabled();
ui::HelpText("Clear", nullptr, "Remove all vertex paint from the Part, paint layers included (undoable).", "Color");
+ drawLineGradientControls(); // LineGradient.cpp
ImGui::Checkbox(tr("Show vertex paint"), &renderSettings_.showVertexPaint);
ImGui::Checkbox(tr("Colour tints the material"), &renderSettings_.colorTintsMaterial);
ui::HelpText("Colour tints the material", nullptr,
diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cpp
index 0e26cc52..05affe22 100644
--- a/src/app/UiTest.cpp
+++ b/src/app/UiTest.cpp
@@ -706,6 +706,7 @@ double Demo::query(const std::string& name, bool& known) const {
if (name == "stroke_type") return double(int(app_.strokeType_)); // 0 Dots, 1 DragRect, 2 DragDot, 3 Spray, 4 LazyMouse
if (name == "stroke_continuous") return app_.strokeContinuous_ ? 1.0 : 0.0; // Continuous (#31)
if (name == "vdms") return double(app_.doc_.vdms.size());
+ if (double gv = 0.0; app_.gradientUiValue(name, gv)) return gv; // gradient_armed, gradient_placed (LineGradient.cpp)
if (double kv = 0.0; app_.kelvinUiValue(name, kv)) return kv; // capture_*, kelvin_* (PanelKelvinlet.cpp)
// Facial shapes (PanelFace.cpp): landmarks placed, placing them, a take playing, and face_<shape>: that layer's weight.
if (name == "face_landmarks") return double(app_.faceLandmarks_.count());
diff --git a/src/core/Texture.cpp b/src/core/Texture.cpp
index 505c4619..a6321c06 100644
--- a/src/core/Texture.cpp
+++ b/src/core/Texture.cpp
@@ -1754,6 +1754,31 @@ size_t textureFill(Mesh& m, const glm::vec3& color, const std::vector<float>& vw
return changed;
}
+size_t textureFillBy(Mesh& m, const std::vector<float>& tv, const std::vector<float>& vw,
+ const std::function<glm::vec4(float)>& shade) {
+ if (!hasTexture(m) || vw.size() != m.vertexCount() || tv.size() != m.vertexCount()) return 0;
+ PaintTexture& tex = mutableTexture(m);
+ const int layer = tex.layers.empty() ? -1 : tex.activeLayer;
+ if (!textureLayerEditable(tex, layer)) return 0;
+ std::vector<uint8_t>& target = tex.target(layer);
+ const bool onLayer = layer >= 0;
+ size_t changed = 0;
+ bakeTexels(m, tex, [&](uint32_t t, float b0, float b1, float b2, int x, int y) {
+ const glm::uvec3& v = m.triangles[t];
+ const float wgt = std::clamp(vw[v.x] * b0 + vw[v.y] * b1 + vw[v.z] * b2, 0.0f, 1.0f);
+ if (wgt <= 0.0f) return;
+ const glm::vec4 c = shade(tv[v.x] * b0 + tv[v.y] * b1 + tv[v.z] * b2);
+ if (c.w * wgt <= 0.0f) return;
+ uint8_t* px = &target[(size_t(y) * size_t(tex.width) + size_t(x)) * 4];
+ uint8_t orig[4];
+ std::memcpy(orig, px, 4);
+ paintTexel(px, orig, onLayer, glm::vec3(c), c.w * wgt, false);
+ ++changed;
+ });
+ compositeTextureAll(tex);
+ return changed;
+}
+
void vertexpaintToTexture(Mesh& m) {
if (!hasTexture(m)) return;
PaintTexture& tex = mutableTexture(m);
diff --git a/src/core/Texture.h b/src/core/Texture.h
index db2102c1..698fff90 100644
--- a/src/core/Texture.h
+++ b/src/core/Texture.h
@@ -290,6 +290,10 @@ void bakeTexels(const Mesh& mesh, PaintTexture& tex, const BakeFn& fn, bool skip
// Blends `color` into the target layer of every texel with the weight interpolated from `vertexWeight`
// (per vertex 0..1). Returns the number of texels changed.
size_t textureFill(Mesh& mesh, const glm::vec3& color, const std::vector<float>& vertexWeight);
+// Like textureFill with a colour per texel: `shade(t)` (rgb, and a weight in a) of the vertex value `t`
+// interpolated over the texel, times the interpolated `vertexWeight` (Line Gradient).
+size_t textureFillBy(Mesh& mesh, const std::vector<float>& t, const std::vector<float>& vertexWeight,
+ const std::function<glm::vec4(float)>& shade);
// Bakes the vertex paint (Mesh::colors, composited) into the active texture layer (opaque).
void vertexpaintToTexture(Mesh& mesh);
// Sets the vertex paint (active paint layer) of every vertex to the texture's colour at its UVs (seams average).
diff --git a/src/core/VertexPaint.cpp b/src/core/VertexPaint.cpp
index 0b258660..5fcb320e 100644
--- a/src/core/VertexPaint.cpp
+++ b/src/core/VertexPaint.cpp
@@ -9,6 +9,7 @@
#include "core/Commands.h"
#include "core/Parts.h"
+#include "core/ScreenSelect.h"
#include "core/Texture.h"
#include "core/Undo.h"
#include "io/PlyIO.h"
@@ -17,6 +18,7 @@
#include <cctype>
#include <cmath>
#include <cstdio>
+#include <limits>
#include <memory>
#include <sstream>
@@ -160,6 +162,42 @@ size_t paintFill(Mesh& mesh, const glm::vec3& color, PaintArea area, float amoun
return changed;
}
+std::vector<float> gradientPositions(const Mesh& mesh, const glm::mat4& viewProj, glm::vec2 a, glm::vec2 b, float aspect) {
+ // On screen (x scaled by the aspect), so the bands cross the line at right angles as the user sees them.
+ const glm::vec2 s(std::max(aspect, 1e-4f), 1.0f);
+ const glm::vec2 d = (b - a) * s;
+ const float len2 = std::max(glm::dot(d, d), 1e-12f);
+ std::vector<float> t(mesh.vertexCount(), std::numeric_limits<float>::quiet_NaN());
+ for (uint32_t v = 0; v < mesh.vertexCount(); ++v) {
+ glm::vec2 p;
+ if (projectToNdc(viewProj, mesh.positions[v], p)) t[v] = glm::dot((p - a) * s, d) / len2;
+ }
+ return t;
+}
+
+glm::vec4 LineGradient::at(float t) const {
+ t = std::clamp(t, 0.0f, 1.0f);
+ if (toClear) return glm::vec4(from, 1.0f - t);
+ return glm::vec4(srgbToLinear(glm::mix(linearToSrgb(from), linearToSrgb(to), t)), 1.0f);
+}
+
+size_t paintGradient(Mesh& mesh, const std::vector<float>& t, const LineGradient& g, PaintArea area) {
+ if (mesh.vertexCount() == 0 || t.size() != mesh.vertexCount()) return 0;
+ if (!paintLayerEditable(mesh, mesh.paintLayers.empty() ? -1 : mesh.activePaintLayer)) return 0;
+ mesh.ensureColors();
+ size_t changed = 0;
+ for (uint32_t v = 0; v < mesh.vertexCount(); ++v) {
+ if (std::isnan(t[v]) || (mesh.hasHidden() && mesh.vertexHidden(v))) continue;
+ const glm::vec4 c = g.at(t[v]);
+ const float w = areaWeight(mesh, v, area) * c.w;
+ if (w <= 0.0f) continue;
+ paintVertex(mesh, v, glm::vec3(c), w);
+ ++changed;
+ }
+ mesh.markAllDirty();
+ return changed;
+}
+
std::vector<float> cavityMap(const Mesh& mesh, int smoothing) {
const size_t nv = mesh.vertexCount();
std::vector<float> curv(nv, 0.0f);
@@ -341,6 +379,65 @@ void registerPaintCommands(CommandRegistry& registry) {
return {true, "Filled " + std::to_string(n) + " vertices with " + colorToHex(c)};
}});
+ registry.add({"paint_gradient",
+ "Line Gradient (#99): paint a straight colour ramp across the model as seen in a view, from one colour "
+ "at the start of a screen line to another (or to nothing) at its end; before the start and after the "
+ "end the end colours carry on. Into the active paint layer (of the texture when the Part paints into "
+ "one), one undo step. The mask is respected like paint_fill; hidden faces are never painted.",
+ {{"x0", T::Number, "Line start x (-1..1, normalised in the view). Default -1.", false},
+ {"y0", T::Number, "Line start y (-1..1, y up). Default 0.", false},
+ {"x1", T::Number, "Line end x. Default 1.", false},
+ {"y1", T::Number, "Line end y. Default 0.", false},
+ {"color", T::String, std::string(kColorHelp) + " The start colour. Default: the current paint colour.", false},
+ {"to", T::String, "The end colour (any color form), or clear: the start colour fades out. Default clear.", false},
+ {"area", T::String, "unmasked (default), masked or all, as paint_fill.", false},
+ {"aspect", T::Number, "The view's width / height, so the bands cross the line squarely on screen. Default 1.", false},
+ {"view_proj", T::String, "Optional 16 numbers: column-major view-projection matrix (default: the front view).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Mesh& m = doc.mesh;
+ if (m.vertexCount() == 0) return {false, "There is no mesh to paint"};
+ LineGradient g;
+ g.from = doc.paintColor;
+ std::string err;
+ if (!colorArg(a, g.from, err) && !err.empty()) return {false, err};
+ const std::string to = argString(a, "to", "clear");
+ g.toClear = to == "clear" || to == "transparent" || to == "none";
+ if (!g.toClear && !parseColor(to, g.to)) return {false, "Unknown colour '" + to + "' (or clear)"};
+ const std::string areaName = argString(a, "area", "unmasked");
+ PaintArea area;
+ if (areaName == "unmasked") area = PaintArea::Unmasked;
+ else if (areaName == "masked") area = PaintArea::Masked;
+ else if (areaName == "all") area = PaintArea::All;
+ else return {false, "area must be unmasked, masked or all"};
+ if (area == PaintArea::Masked && !m.hasMask()) return {false, "Nothing is masked"};
+ glm::mat4 vp;
+ if (!viewProjArg(m, a, vp, err)) return {false, err};
+ const glm::vec2 p0(float(argNumber(a, "x0", -1.0)), float(argNumber(a, "y0", 0.0)));
+ const glm::vec2 p1(float(argNumber(a, "x1", 1.0)), float(argNumber(a, "y1", 0.0)));
+ if (glm::distance(p0, p1) < 1e-4f) return {false, "The line needs two different ends"};
+ if (std::string why = paintBlocked(m); !why.empty()) return {false, why};
+ const std::vector<float> t = gradientPositions(m, vp, p0, p1, float(argNumber(a, "aspect", 1.0)));
+ const std::string ends = colorToHex(g.from) + " to " + (g.toClear ? std::string("clear") : colorToHex(g.to));
+ if (paintsTexture(m)) {
+ std::vector<float> w(m.vertexCount()), tv(t);
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {
+ w[v] = std::isnan(t[v]) ? 0.0f : area == PaintArea::Unmasked ? 1.0f - m.maskAt(v)
+ : area == PaintArea::Masked ? m.maskAt(v)
+ : 1.0f;
+ if (std::isnan(tv[v])) tv[v] = 0.0f;
+ }
+ UndoRecord r = captureTexture(m, "Line Gradient");
+ const size_t n = textureFillBy(m, tv, w, [&g](float x) { return g.at(x); });
+ finishTextureUndo(r, m);
+ doc.undo.push(std::move(r));
+ return {true, "Line Gradient " + ends + " on " + std::to_string(n) + " texels"};
+ }
+ doc.undo.push(colorUndo(m, "Line Gradient"));
+ const size_t n = paintGradient(m, t, g, area);
+ doc.modified = true;
+ return {true, "Line Gradient " + ends + " on " + std::to_string(n) + " vertices"};
+ }});
+
registry.add({"paint_clear", "Remove all vertex paint from the mesh, paint layers included (undoable).", {},
[](Document& doc, const Args&) -> CommandResult {
if (paintsTexture(doc.mesh)) {
diff --git a/src/core/VertexPaint.h b/src/core/VertexPaint.h
index 0a06bc80..056c433d 100644
--- a/src/core/VertexPaint.h
+++ b/src/core/VertexPaint.h
@@ -50,6 +50,21 @@ enum class PaintArea { All, Unmasked, Masked };
// ignores it. Hidden faces are never painted. Not undoable by itself.
size_t paintFill(Mesh& mesh, const glm::vec3& color, PaintArea area = PaintArea::Unmasked, float amount = 1.0f);
+// Line Gradient (#99): a straight colour ramp dragged across the screen. Where each vertex lies along the line from
+// `a` to `b` (normalised device coordinates under `viewProj`): 0 at a, 1 at b, beyond the ends below 0 or above 1.
+// `aspect` (view width / height) keeps the bands square to the line as seen on screen. NaN behind the camera.
+std::vector<float> gradientPositions(const Mesh& mesh, const glm::mat4& viewProj, glm::vec2 a, glm::vec2 b, float aspect);
+// The ramp: `from` at the start to `to` at the end (blended as display colours), or with `toClear` `from` fading out.
+struct LineGradient {
+ glm::vec3 from{1.0f}, to{1.0f}; // linear
+ bool toClear = false;
+ // The colour (rgb) and how much of it goes on (a) at position t, clamped to the ends.
+ glm::vec4 at(float t) const;
+};
+// Paints the gradient over the vertices at their positions `t` (gradientPositions), in `area` as paintFill (hidden
+// faces never). Not undoable by itself.
+size_t paintGradient(Mesh& mesh, const std::vector<float>& t, const LineGradient& g, PaintArea area = PaintArea::Unmasked);
+
// Per-vertex cavity amount 0..1 (1 = deep crease), from the same signed
// curvature the viewport's cavity shading uses, blurred `smoothing` times.
std::vector<float> cavityMap(const Mesh& mesh, int smoothing = 2);
diff --git a/tests/test_texture.cpp b/tests/test_texture.cpp
index 795f1189..f1adfc29 100644
--- a/tests/test_texture.cpp
+++ b/tests/test_texture.cpp
@@ -454,6 +454,23 @@ TEST(texture_commands) {
CHECK(doc.mesh.hasColors());
CHECK(glm::all(glm::lessThan(glm::abs(doc.mesh.colors[0] - glm::vec3(1, 0, 0)), glm::vec3(0.02f))));
+ // Line Gradient (#99) paints texels: red at the left of the front view, blue at the right, one undo step.
+ CHECK(reg.execute(doc, "paint_gradient", {{"color", std::string("#ff0000")}, {"to", std::string("#0000ff")}}).ok);
+ {
+ const Mesh& m = doc.mesh;
+ float minX = 1e9f, maxX = -1e9f;
+ glm::vec3 atMin(0.0f), atMax(0.0f);
+ for (size_t t = 0; t < m.triangleCount(); ++t)
+ for (int k = 0; k < 3; ++k) {
+ const glm::vec3& p = m.positions[m.triangles[t][k]];
+ const glm::vec3 c = sampleTexture(*m.texture, m.uvs[t * 3 + size_t(k)]);
+ if (p.x < minX) minX = p.x, atMin = c;
+ if (p.x > maxX) maxX = p.x, atMax = c;
+ }
+ CHECK(atMin.x > 0.9f && atMin.z < 0.1f && atMax.z > 0.9f && atMax.x < 0.1f);
+ }
+ CHECK(doc.undo.undoLabel() == "Line Gradient");
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));
// Vertex paint > Texture bakes vertex colours (green) back.
CHECK(reg.execute(doc, "paint_target", {{"target", std::string("vertex")}}).ok);
CHECK(!paintsTexture(doc.mesh));
diff --git a/tests/test_vertexpaint.cpp b/tests/test_vertexpaint.cpp
index 336e19fd..715b4b7c 100644
--- a/tests/test_vertexpaint.cpp
+++ b/tests/test_vertexpaint.cpp
@@ -182,6 +182,44 @@ TEST(vertexpaint_fill_and_clear_commands) {
CHECK(reg.execute(doc, "set_color", {{"r", 255.0}, {"g", 0.0}, {"b", 0.0}}).ok && near(doc.paintColor, kRed));
}
+// Line Gradient (#99): left to right across the front view, the mask respected, one undo step per gradient.
+TEST(vertexpaint_line_gradient) {
+ CommandRegistry reg;
+ Document doc = makeDoc(makeIcosphere(3));
+ Mesh& m = doc.mesh;
+ const uint32_t left = nearestVertex(m, {-1, 0, 0}), right = nearestVertex(m, {1, 0, 0}), mid = nearestVertex(m, {0, 0, 1});
+ CHECK(!reg.execute(doc, "paint_gradient", {{"x0", 0.2}, {"y0", 0.1}, {"x1", 0.2}, {"y1", 0.1}}).ok); // no line
+ CHECK(!reg.execute(doc, "paint_gradient", {{"to", std::string("not a colour")}}).ok);
+ CHECK(!m.hasColors());
+
+ CHECK(reg.execute(doc, "paint_gradient", {{"color", std::string("#ff0000")}, {"to", std::string("#0000ff")}}).ok);
+ CHECK(near(m.colors[left], kRed) && near(m.colors[right], glm::vec3(0, 0, 1)));
+ const glm::vec3 half = srgbToLinear(glm::vec3(0.5f, 0.0f, 0.5f)); // blended as display colours
+ CHECK(near(m.colors[mid], half, 0.05f));
+ CHECK(near(m.colors[nearestVertex(m, {0, 0, -1})], m.colors[mid], 0.05f)); // a ramp through the whole Part
+ CHECK(reg.execute(doc, "undo").ok && !m.hasColors());
+ CHECK(reg.execute(doc, "redo").ok && near(m.colors[left], kRed));
+
+ // To clear: the start colour fades out over what is there; masked vertices keep their paint.
+ m.ensureMask();
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) m.mask[v] = m.positions[v].y > 0.5f ? 1.0f : 0.0f;
+ const uint32_t top = nearestVertex(m, {0, 1, 0});
+ const glm::vec3 topBefore = m.colors[top];
+ CHECK(reg.execute(doc, "paint_gradient", {{"color", std::string("#00ff00")}, {"x0", 0.0}, {"y0", -1.0}, {"x1", 0.0}, {"y1", 1.0}}).ok);
+ CHECK(near(m.colors[nearestVertex(m, {0, -1, 0})], glm::vec3(0, 1, 0)));
+ CHECK(near(m.colors[top], topBefore));
+ CHECK(m.colors[mid].y > 0.1f && m.colors[mid].y < 0.9f && m.colors[mid].x > 0.05f); // half green over the old ramp
+ CHECK(reg.execute(doc, "undo").ok && near(m.colors[mid], half, 0.05f));
+
+ // Masked only, and hidden faces are never painted.
+ CHECK(reg.execute(doc, "paint_gradient", {{"color", std::string("white")}, {"to", std::string("white")}, {"area", std::string("masked")}}).ok);
+ CHECK(near(m.colors[top], glm::vec3(1.0f)) && near(m.colors[left], kRed));
+ m.ensureHidden();
+ for (uint32_t t : m.vertexTriangles(left)) m.hidden[t] = 1;
+ CHECK(reg.execute(doc, "paint_gradient", {{"color", std::string("black")}, {"to", std::string("black")}, {"area", std::string("all")}}).ok);
+ CHECK(near(m.colors[left], kRed) && near(m.colors[right], glm::vec3(0.0f)) && near(m.colors[top], glm::vec3(0.0f)));
+}
+
TEST(vertexpaint_fill_skips_hidden) {
Mesh m = makeIcosphere(2);
m.ensureHidden();
@@ -271,7 +309,7 @@ TEST(vertexpaint_export_ply_and_usd) {
TEST(vertexpaint_commands_in_schema) {
CommandRegistry reg;
const std::string schema = reg.toolSchemaJson();
- for (const char* name : {"set_color", "paint_fill", "paint_clear", "paint_from_cavity", "export_ply"}) {
+ for (const char* name : {"set_color", "paint_fill", "paint_gradient", "paint_clear", "paint_from_cavity", "export_ply"}) {
CHECK(reg.find(name) != nullptr);
CHECK(schema.find(std::string("\"") + name + "\"") != std::string::npos);
}
diff --git a/tests/ui/line_gradient.sfui b/tests/ui/line_gradient.sfui
new file mode 100644
index 00000000..5b626a65
--- /dev/null
+++ b/tests/ui/line_gradient.sfui
@@ -0,0 +1,97 @@
+# Line Gradient (#99): Color > Line Gradient, then a drag across the view paints a colour ramp from the paint colour
+# to the End colour (or to clear). Its ends stay draggable, every change replacing the same undo step; Enter keeps
+# it, Esc takes it back. The mask is respected.
+run ui_look look=classic layout=classic # the classic palette bar: Color drops down from it
+run new_sphere subdivisions=5
+run set_color color=f0a020
+shot before
+click "Color##palette.color"
+click "Line Gradient##paint.line_gradient"
+expect_value gradient_armed == 1
+expect "Clear##gradient"
+shot palette
+
+# Ctrl-hover help explains it.
+hold ctrl
+hover "Line Gradient##paint.line_gradient"
+expect_help "Drag a line"
+hold none
+
+# Closing the drop-down (the tool stays on), then a drag across the sphere: orange at the start,
+# black (the End colour) at the end.
+click "Color##palette.color"
+expect_not "Clear##gradient"
+expect_value gradient_armed == 1
+drag_path 0.05 0.15 0.95 0.85 keep
+wait 0.1
+shot dragging
+release
+wait 0.2
+expect_value gradient_placed == 1
+expect_value colored == 1
+expect_value can_undo == 1
+remember paint_mean_r first
+shot sphere
+
+# Its end handle moves: the same gradient, painted again (still one undo step).
+drag_path 0.95 0.85 0.6 0.55
+wait 0.2
+expect_value gradient_placed == 1
+expect_value paint_mean_r < $first
+remember paint_mean_r moved
+hover_window 0.5 0.95
+shot handle-moved
+key enter
+expect_value gradient_placed == 0
+key ctrl+z
+expect_value colored == 0
+key ctrl+shift+z
+expect_value paint_mean_r == $moved
+
+# Esc takes the gradient being adjusted back.
+drag_path 0.5 0.05 0.5 0.95
+wait 0.2
+expect_value gradient_placed == 1
+expect_value paint_mean_r != $moved
+key escape
+expect_value gradient_placed == 0
+expect_value paint_mean_r == $moved
+
+# The mask: a blue fade to clear across the sphere leaves the masked top as it was.
+run mask_rect y0=0.3
+run set_color color=2a6be0
+click "Color##palette.color"
+click "Clear##gradient"
+click "Color##palette.color"
+drag_path 0.0 0.5 1.0 0.5
+wait 0.2
+expect_value gradient_placed == 1
+expect_value paint_mean_b > 20
+shot masked
+key enter
+run mask_clear
+hover_window 0.5 0.95
+shot masked-result
+
+# At 200 % the handles and the palette scale with the UI.
+display_scale 200
+wait 0.3
+run mask_rect y0=0.3
+drag_path 0.15 0.9 0.85 0.3 keep
+wait 0.1
+shot dragging-hidpi
+release
+wait 0.2
+expect_value gradient_placed == 1
+hover_window 0.3 0.75
+shot hidpi
+key escape
+expect_value gradient_placed == 0
+expect_value gradient_armed == 1
+click "Color##palette.color"
+hover "Clear##gradient"
+wait 0.2
+shot palette-hidpi
+click "Line Gradient##paint.line_gradient"
+expect_value gradient_armed == 0
+expect_not "Clear##gradient"