Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Polypaint and MatCap materials
islandmedf905369c7234
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 4e439795..459115fd 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -41,6 +41,8 @@ add_library(sculptforge_core STATICsrc/core/Splats.cppsrc/core/Voxel.cppsrc/core/EnginePresets.cpp+ src/core/Polypaint.cpp+ src/core/Matcap.cppsrc/io/ObjIO.cppsrc/io/FbxIO.cppthird_party/ufbx/ufbx.c@@ -103,6 +105,7 @@ if(SCULPTFORGE_BUILD_APP)src/app/main.cppsrc/app/App.cppsrc/app/Demo.cpp+ src/app/PanelPolypaint.cppsrc/render/GL.cppsrc/render/Camera.cppsrc/render/Renderer.cppdiff --git a/src/app/App.cpp b/src/app/App.cppindex 2125f4ba..8c177128 100644--- a/src/app/App.cpp+++ b/src/app/App.cpp@@ -162,6 +162,7 @@ bool App::init(const AppOptions& options) {io.IniFilename = nullptr;}ai::registerAiCommands(commands_, [this] { return aiSettings_; });+ registerPaintUiCommands();std::snprintf(falKey_, sizeof falKey_, "%s", aiSettings_.falKey.c_str());std::snprintf(falModel_, sizeof falModel_, "%s", aiSettings_.falModel.c_str());std::snprintf(meshyKey_, sizeof meshyKey_, "%s", aiSettings_.meshyKey.c_str());@@ -520,8 +521,16 @@ void App::onKey(SDL_Keycode key, SDL_Keymod mod) {case SDLK_W: renderSettings_.wireframe = !renderSettings_.wireframe; break;case SDLK_F: camera_.frame(sceneBounds()); break;case SDLK_F1: showHelp_ = !showHelp_; break;+ case SDLK_P:+ paintMode_ = !paintMode_;+ if (paintMode_) showPolypaintPanel_ = true; // colour picker at hand+ break;+ case SDLK_C: pickColorUnderCursor(); break;default:- if (key >= SDLK_1 && key < SDLK_1 + int(BrushType::Count)) brush_ = BrushType(key - SDLK_1);+ if (key >= SDLK_1 && key < SDLK_1 + int(BrushType::Count)) {+ brush_ = BrushType(key - SDLK_1);+ paintMode_ = false;+ }break;}}@@ -533,9 +542,14 @@ 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);- const BrushRecipe* recipe = strokeBrush_ == BrushType::Smooth ? nullptr : activeRecipe();+ // Shift still smooths geometry while the Paint brush is active (ZBrush behaviour).+ strokePaint_ = strokeBrush_ != BrushType::Smooth && (paintMode_ || paintRgb_);+ strokeSculpt_ = !(strokePaint_ && paintMode_);+ const BrushRecipe* recipe = strokeRecipe();haveLastDab_ = false;- if (!doc_.sculptor.beginStroke(doc_.mesh, recipe ? recipe->name : brushName(strokeBrush_), doc_.activeLayer)) {+ if (!doc_.sculptor.beginStroke(doc_.mesh,+ !strokeSculpt_ ? std::string("Paint") : recipe ? recipe->name : brushName(strokeBrush_),+ strokeSculpt_ ? doc_.activeLayer : -1)) {status_ = "Active layer weight is 0 - raise it to sculpt into the layer";drag_ = Drag::Orbit;return;@@ -543,11 +557,12 @@ void App::beginStroke(float x, float y, const RayHit& hit) {drag_ = Drag::Stroke;playingLayer_ = -1;clearLods();+ beginPaintStroke();lastX_ = x;lastY_ = y;residual_ = 0.0f;- if (strokeBrush_ == BrushType::Move && !recipe) {+ if (strokeBrush_ == BrushType::Move && !recipe && strokeSculpt_) {int w = 0, h = 0;SDL_GetWindowSize(window_, &w, &h);float pressure = lastInputPen_ && pressureSize_ ? penPressure_ : 1.0f;@@ -564,8 +579,8 @@ void App::beginStroke(float x, float y, const RayHit& hit) {}void App::strokeTo(float x, float y) {- const BrushRecipe* recipe = strokeBrush_ == BrushType::Smooth ? nullptr : activeRecipe();- if (strokeBrush_ == BrushType::Move && !recipe) {+ const BrushRecipe* recipe = strokeRecipe();+ if (strokeBrush_ == BrushType::Move && !recipe && strokeSculpt_) {int w = 0, h = 0;SDL_GetWindowSize(window_, &w, &h);glm::vec3 origin, dir;@@ -596,7 +611,7 @@ void App::strokeTo(float x, float y) {}void App::dabAt(float x, float y) {- const BrushRecipe* recipe = strokeBrush_ == BrushType::Smooth ? nullptr : activeRecipe();+ const BrushRecipe* recipe = strokeRecipe();if (recipe && recipe->jitter > 0.0f) {// Deterministic per-stroke scatter (xorshift).auto rnd = [this] {@@ -623,6 +638,8 @@ void App::dabAt(float x, float y) {p.pressure = pressureStrength_ ? pressure : 1.0f;p.invert = strokeInvert_;p.frontFacesOnly = frontFacesOnly_;+ if (strokePaint_) paintAt(p);+ if (!strokeSculpt_) return;if (recipe) {p.strokeDelta = haveLastDab_ ? hit.position - lastDabHit_ : glm::vec3(0.0f);lastDabHit_ = hit.position;@@ -635,6 +652,7 @@ void App::dabAt(float x, float y) {void App::endStroke() {UndoRecord r = doc_.sculptor.endStroke();+ finishPaintStroke(r);if (!r.empty()) {doc_.undo.push(std::move(r));doc_.modified = true;@@ -652,7 +670,8 @@ void App::runCommand(const std::string& name, const Args& args) {status_ = r.message;if (r.ok && name != "export_glb" && name != "export_lods" && name != "export_usd" && name != "export_fbx" &&name != "export_unreal" && name.rfind("unreal_", 0) != 0 && name != "save_obj" &&- name != "mesh_info" && name.rfind("brush_", 0) != 0 && name.rfind("splat_", 0) != 0 && name != "mesh_to_splats") {+ name != "mesh_info" && name.rfind("brush_", 0) != 0 && name.rfind("splat_", 0) != 0 && name != "mesh_to_splats" &&+ name != "set_color" && name != "set_material" && name != "export_ply") {clearLods();playingLayer_ = -1;}@@ -821,6 +840,7 @@ void App::drawUi() {drawSplatSection();if (showBrushLab_) drawBrushLab();if (showImageTo3D_) drawImageTo3D();+ if (showPolypaintPanel_) drawPolypaintPanel();if (previewLod_ >= 0) {const ImGuiViewport* vp = ImGui::GetMainViewport();std::string banner = "Previewing LOD" + std::to_string(previewLod_) + " - " +@@ -869,6 +889,8 @@ void App::drawUi() {"Zoom Mouse wheel / Ctrl + left drag background\n""Brush size [ and ]\n""Brushes 1-8\n"+ "Paint brush P (colour only; Alt paints white)\n"+ "Pick colour C over the model\n""Symmetry X X\n""Wireframe W\n""Frame model F\n"@@ -929,6 +951,7 @@ void App::drawMenuBar() {ImGui::MenuItem("Game Ready Panel", nullptr, &showGamePanel_);ImGui::MenuItem("Gaussian Splats", nullptr, &showSplatsPanel_);ImGui::MenuItem("Brush Lab", nullptr, &showBrushLab_);+ ImGui::MenuItem("Polypaint & Materials", nullptr, &showPolypaintPanel_);ImGui::MenuItem("Generate 3D", nullptr, &showImageTo3D_);ImGui::MenuItem("Show Splats", nullptr, &renderSettings_.showSplats, !doc_.splats.empty());if (ImGui::MenuItem("Frame Model", "F")) camera_.frame(sceneBounds());@@ -1583,12 +1606,13 @@ void App::drawToolPanel() {const float bw = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;for (int i = 0; i < int(BrushType::Count); ++i) {const auto type = BrushType(i);- const bool selected = brush_ == type && doc_.activeBrush < 0;+ const bool selected = brush_ == type && doc_.activeBrush < 0 && !paintMode_;if (selected) ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive));std::string label = std::to_string(i + 1) + " " + brushName(type);if (ImGui::Button(label.c_str(), ImVec2(bw, 0))) {brush_ = type;doc_.activeBrush = -1;+ paintMode_ = false;}if (selected) ImGui::PopStyleColor();if (i % 2 == 0) ImGui::SameLine();@@ -1597,7 +1621,10 @@ void App::drawToolPanel() {ImGui::SeparatorText("Custom brushes");if (ImGui::BeginListBox("##custom", ImVec2(-1, ImGui::GetTextLineHeightWithSpacing() * 5.5f))) {for (int i = 0; i < int(doc_.brushes.size()); ++i) {- if (ImGui::Selectable(doc_.brushes[i].name.c_str(), doc_.activeBrush == i)) doc_.activeBrush = i;+ if (ImGui::Selectable(doc_.brushes[i].name.c_str(), doc_.activeBrush == i)) {+ doc_.activeBrush = i;+ paintMode_ = false;+ }if (ImGui::IsItemHovered() && !doc_.brushes[i].description.empty())ImGui::SetTooltip("%s", doc_.brushes[i].description.c_str());}@@ -1607,6 +1634,8 @@ void App::drawToolPanel() {showBrushLab_ = !showBrushLab_;if (ImGui::Button(showImageTo3D_ ? "Hide Generate 3D" : "Generate 3D...", ImVec2(-1, 0)))showImageTo3D_ = !showImageTo3D_;+ if (ImGui::Button(showPolypaintPanel_ ? "Hide Polypaint" : "Polypaint & Materials...", ImVec2(-1, 0)))+ showPolypaintPanel_ = !showPolypaintPanel_;ImGui::PushItemWidth(-ImGui::CalcTextSize("Strength").x - ImGui::GetStyle().ItemInnerSpacing.x);ImGui::SliderFloat("Size", &radiusPx_, 2.0f, 800.0f, "%.0f px", ImGuiSliderFlags_Logarithmic);@@ -1704,9 +1733,13 @@ void App::drawBrushCursor() {const float r = radiusPx_ * (pressureSize_ && lastInputPen_ ? std::max(penPressure_, 0.05f) : 1.0f);const ImVec2 c(mouseX_, mouseY_);const bool inverted = invertToggle_ != ((SDL_GetModState() & SDL_KMOD_ALT) != 0);- const ImU32 col = activeBrush() == BrushType::Smooth ? IM_COL32(120, 200, 255, 200)- : inverted ? IM_COL32(255, 110, 110, 200)- : IM_COL32(255, 190, 120, 200);+ ImU32 col = activeBrush() == BrushType::Smooth ? IM_COL32(120, 200, 255, 200)+ : inverted ? IM_COL32(255, 110, 110, 200)+ : IM_COL32(255, 190, 120, 200);+ if (paintMode_ && activeBrush() != BrushType::Smooth) { // Paint brush: ring in the paint colour+ const glm::vec3 c = linearToSrgb(inverted ? glm::vec3(1.0f) : doc_.paintColor);+ col = ImGui::GetColorU32(ImVec4(c.x, c.y, c.z, 0.9f));+ }dl->AddCircle(c, r, col, 64, 1.5f);dl->AddCircle(c, r * (0.25f + 0.75f * (1.0f - strength_)), IM_COL32(255, 255, 255, 60), 48, 1.0f);}diff --git a/src/app/App.h b/src/app/App.hindex e6de675a..20713545 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -229,6 +229,21 @@ private:const Mesh* lastDisplayed_ = nullptr;std::mutex pendingMutex_;std::vector<PendingFile> pendingFiles_;++ // Polypaint and MatCap materials (PanelPolypaint.cpp)+ bool paintMode_ = false; // Paint brush: colour only, no sculpting (ZBrush Rgb on, Zadd off)+ bool paintRgb_ = false; // also paint the colour while sculpting (ZBrush Rgb + Zadd)+ bool strokePaint_ = false, strokeSculpt_ = true;+ bool showPolypaintPanel_ = false; // off by default (keeps the viewport and demo videos clear)+ void registerPaintUiCommands();+ void drawPolypaintPanel();+ void paintAt(const DabParams& p);+ void pickColorUnderCursor();+ // First paint stroke on a mesh without polypaint: undo restores this snapshot so the attribute goes away again.+ std::unique_ptr<Mesh> paintSnapshot_;+ void beginPaintStroke();+ void finishPaintStroke(UndoRecord& record);+ const BrushRecipe* strokeRecipe() const; // recipe the current stroke sculpts with (none for Smooth / paint only)};} // namespace sfdiff --git a/src/app/PanelPolypaint.cpp b/src/app/PanelPolypaint.cppnew file mode 100644index 00000000..5efef8e5--- /dev/null+++ b/src/app/PanelPolypaint.cpp@@ -0,0 +1,162 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Polypaint & Materials panel: the Paint brush (ZBrush Rgb / Zadd), colour+// picker and swatches, fills, and the viewport MatCap material picker.+#include "app/App.h"++#include "core/Matcap.h"+#include "core/Polypaint.h"++#include <glm/gtc/type_ptr.hpp>++#include <cfloat>+#include <iterator>++namespace sf {++void App::registerPaintUiCommands() {+ // A view setting, so it lives with the app (scripts: --script "set_material name=Chrome").+ std::string names = "studio";+ for (int i = 0; i < matcapCount(); ++i) names += std::string(", ") + matcapName(i);+ commands_.add({"set_material",+ "Viewport material: studio (default clay lighting) or a built-in MatCap. Polypaint multiplies "+ "the matcap; cavity shading stays on.",+ {{"name", ParamSpec::Type::String, "One of: " + names + ".", true}},+ [this, names](Document&, const Args& a) -> CommandResult {+ const std::string name = argString(a, "name");+ if (name == "studio" || name == "Studio") {+ renderSettings_.matcap = -1;+ return {true, "Material: Studio"};+ }+ const int index = findMatcap(name);+ if (index < 0) return {false, "Unknown material '" + name + "' (" + names + ")"};+ renderSettings_.matcap = index;+ return {true, std::string("Material: ") + matcapName(index)};+ }});+}++const BrushRecipe* App::strokeRecipe() const {+ return strokeBrush_ == BrushType::Smooth || !strokeSculpt_ ? nullptr : activeRecipe();+}++void App::paintAt(const DabParams& p) {+ paintDab(doc_.sculptor, doc_.mesh, doc_.bvh, p, doc_.paintColor, symmetry_);+}++void App::beginPaintStroke() {+ paintSnapshot_.reset();+ if (strokePaint_ && !doc_.mesh.hasColors()) paintSnapshot_ = std::make_unique<Mesh>(doc_.mesh);+}++void App::finishPaintStroke(UndoRecord& record) {+ if (!paintSnapshot_) return;+ UndoRecord snapshot;+ snapshot.label = std::move(record.label);+ snapshot.mesh = std::move(paintSnapshot_);+ record = std::move(snapshot);+}++void App::pickColorUnderCursor() {+ doc_.syncBvh();+ RayHit hit;+ if (!pick(mouseX_, mouseY_, hit)) return;+ if (!doc_.mesh.hasColors()) {+ status_ = "The mesh has no polypaint to pick from";+ return;+ }+ doc_.paintColor = sampleColor(doc_.mesh, hit.triangle, hit.position);+ status_ = "Paint colour " + colorToHex(doc_.paintColor);+}++void App::drawPolypaintPanel() {+ const float scale = uiScale_;+ const ImGuiViewport* vp = ImGui::GetMainViewport();+ ImGui::SetNextWindowPos(ImVec2(vp->Pos.x + 270 * scale, vp->Pos.y + 34 * scale), ImGuiCond_FirstUseEver);+ ImGui::SetNextWindowSizeConstraints(ImVec2(250 * scale, 0), ImVec2(250 * scale, FLT_MAX));+ if (!ImGui::Begin("Polypaint & Materials", &showPolypaintPanel_, ImGuiWindowFlags_AlwaysAutoResize)) {+ ImGui::End();+ return;+ }++ ImGui::SeparatorText("Paint");+ const bool painting = paintMode_;+ if (painting) ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive));+ if (ImGui::Button("Paint brush (P)", ImVec2(-1, 0))) paintMode_ = !paintMode_;+ if (painting) ImGui::PopStyleColor();+ if (ImGui::IsItemHovered())+ ImGui::SetTooltip("Paint colour without sculpting. Size, strength, pressure and symmetry come from Tools;\n"+ "Alt paints back to white, Shift smooths the surface, masked areas are protected.");+ ImGui::Checkbox("RGB while sculpting", &paintRgb_);+ if (ImGui::IsItemHovered()) ImGui::SetTooltip("Sculpt brushes also paint the colour (ZBrush Rgb with Zadd)");++ // The picker edits display (sRGB) values; the mesh stores linear colour.+ glm::vec3 srgb = linearToSrgb(doc_.paintColor);+ ImGui::SetNextItemWidth(-1);+ if (ImGui::ColorPicker3("##paintcolor", glm::value_ptr(srgb),+ ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_NoSidePreview |+ ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_DisplayHex))+ doc_.paintColor = srgbToLinear(srgb);+ static const glm::vec3 kSwatches[] = {{1.0f, 1.0f, 1.0f}, {0.1f, 0.1f, 0.1f}, {0.85f, 0.12f, 0.1f},+ {0.95f, 0.5f, 0.12f}, {0.95f, 0.85f, 0.2f}, {0.2f, 0.65f, 0.25f},+ {0.15f, 0.35f, 0.85f}, {0.5f, 0.25f, 0.7f}, {0.87f, 0.66f, 0.55f},+ {0.45f, 0.28f, 0.16f}};+ const float swatch = (ImGui::GetContentRegionAvail().x - 4 * ImGui::GetStyle().ItemSpacing.x) / 5.0f;+ for (int i = 0; i < int(std::size(kSwatches)); ++i) {+ const glm::vec3& c = kSwatches[i];+ ImGui::PushID(i);+ if (ImGui::ColorButton("##swatch", ImVec4(c.x, c.y, c.z, 1.0f), ImGuiColorEditFlags_NoTooltip,+ ImVec2(swatch, swatch * 0.6f)))+ doc_.paintColor = srgbToLinear(c);+ ImGui::PopID();+ if (i % 5 != 4) ImGui::SameLine();+ }+ ImGui::TextDisabled("C over the model picks its colour");++ const float half = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;+ const std::string hex = colorToHex(doc_.paintColor);+ if (ImGui::Button("Fill", ImVec2(half, 0))) runCommand("paint_fill", {{"color", hex}});+ if (ImGui::IsItemHovered()) ImGui::SetTooltip("Fill the unmasked area (the whole mesh if nothing is masked)");+ ImGui::SameLine();+ ImGui::BeginDisabled(!doc_.mesh.hasMask());+ if (ImGui::Button("Fill masked", ImVec2(half, 0)))+ runCommand("paint_fill", {{"color", hex}, {"area", std::string("masked")}});+ ImGui::EndDisabled();+ if (ImGui::Button("Cavity", ImVec2(half, 0))) runCommand("paint_from_cavity");+ if (ImGui::IsItemHovered()) ImGui::SetTooltip("Darken creases and cavities (respects the mask)");+ ImGui::SameLine();+ ImGui::BeginDisabled(!doc_.mesh.hasColors());+ if (ImGui::Button("Clear", ImVec2(half, 0))) runCommand("paint_clear");+ ImGui::EndDisabled();+ ImGui::Checkbox("Show polypaint", &renderSettings_.showPolypaint);++ ImGui::SeparatorText("Material");+ const float spacing = ImGui::GetStyle().ItemSpacing.x;+ const float tile = (ImGui::GetContentRegionAvail().x - 3 * spacing) / 4.0f;+ auto outline = [&](bool selected) {+ if (!selected) return;+ ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(),+ ImGui::GetColorU32(ImGuiCol_ButtonActive), 4.0f, 0, 2.0f * scale);+ };+ if (ImGui::Button("Studio", ImVec2(tile, tile))) renderSettings_.matcap = -1;+ if (ImGui::IsItemHovered()) ImGui::SetTooltip("Studio lights with the Tools material colour");+ outline(renderSettings_.matcap < 0);+ for (int i = 0; i < matcapCount(); ++i) {+ if ((i + 1) % 4 != 0) ImGui::SameLine();+ const GLuint tex = renderer_.matcapTexture(i);+ if (!tex) continue;+ ImGui::PushID(i);+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));+ // Textures are stored bottom-up: flip V for display.+ if (ImGui::ImageButton("##matcap", ImTextureID(uintptr_t(tex)), ImVec2(tile, tile), ImVec2(0, 1), ImVec2(1, 0)))+ renderSettings_.matcap = i;+ ImGui::PopStyleVar();+ ImGui::PopID();+ if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", matcapName(i));+ outline(renderSettings_.matcap == i);+ }+ ImGui::Text("%s", renderSettings_.matcap < 0 ? "Studio" : matcapName(renderSettings_.matcap));+ ImGui::End();+}++} // namespace sfdiff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex 22da76d6..a32e85e5 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -5,6 +5,7 @@#include "core/Decimate.h"#include "core/EnginePresets.h"#include "core/ImageTo3D.h"+#include "core/Polypaint.h"#include "core/Primitives.h"#include "core/Splats.h"#include "core/Voxel.h"@@ -596,6 +597,8 @@ CommandRegistry::CommandRegistry() {<< b.max.y << ", " << b.max.z << ")";return {true, s.str()};}});++ registerPaintCommands(*this); // core/Polypaint.cpp}void CommandRegistry::add(Command cmd) { commands_.push_back(std::move(cmd)); }diff --git a/src/core/Document.h b/src/core/Document.hindex 1920f1a7..70812e25 100644--- a/src/core/Document.h+++ b/src/core/Document.h@@ -27,6 +27,7 @@ struct Document {// Recipe brush library (built-ins, loaded .sfbrush files, AI-made brushes).std::vector<BrushRecipe> brushes = builtinBrushRecipes();int activeBrush = -1; // index into `brushes`, -1 = use a built-in brush type+ glm::vec3 paintColor{0.6f, 0.03f, 0.02f}; // current polypaint colour (linear RGB; see set_color)// Adds or replaces (by name) a recipe and returns its index.int addBrush(BrushRecipe recipe);// Gaussian splats shown alongside the mesh (a capture used as reference ordiff --git a/src/core/Matcap.cpp b/src/core/Matcap.cppnew file mode 100644index 00000000..209cd21f--- /dev/null+++ b/src/core/Matcap.cpp@@ -0,0 +1,125 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/Matcap.h"++#include "core/Mesh.h"++#include <algorithm>+#include <cctype>+#include <cmath>++namespace sf {++namespace {++// A small lighting model evaluated once per matcap pixel: wrapped diffuse with+// a subsurface tint at the terminator, Blinn specular, rim, and for metals a+// studio environment (sky, horizon, ground, softbox) seen by reflection.+struct MatcapStyle {+ const char* name;+ glm::vec3 albedo; // linear+ float wrap; // diffuse wrap (soft, waxy materials)+ glm::vec3 subsurface; // colour bleeding into the shadow side+ float specular, shininess;+ glm::vec3 rim;+ float metal; // 0 = dielectric, 1 = pure environment reflection+ float roughness; // blurs the environment for metals+};++const MatcapStyle kStyles[] = {+ {"Red Wax", {0.50f, 0.045f, 0.03f}, 0.55f, {0.55f, 0.06f, 0.03f}, 0.55f, 70.0f, {0.25f, 0.08f, 0.06f}, 0.0f, 0.0f},+ {"Clay", {0.46f, 0.38f, 0.33f}, 0.25f, {0.05f, 0.03f, 0.02f}, 0.06f, 10.0f, {0.10f, 0.10f, 0.11f}, 0.0f, 0.0f},+ {"Skin", {0.68f, 0.38f, 0.28f}, 0.6f, {0.6f, 0.16f, 0.08f}, 0.16f, 28.0f, {0.22f, 0.16f, 0.15f}, 0.0f, 0.0f},+ {"Chrome", {0.95f, 0.96f, 1.0f}, 0.0f, {0.0f, 0.0f, 0.0f}, 0.0f, 1.0f, {0.0f, 0.0f, 0.0f}, 1.0f, 0.05f},+ {"White", {0.78f, 0.78f, 0.76f}, 0.3f, {0.04f, 0.04f, 0.05f}, 0.3f, 45.0f, {0.12f, 0.13f, 0.15f}, 0.0f, 0.0f},+ {"Bronze", {0.80f, 0.50f, 0.25f}, 0.0f, {0.0f, 0.0f, 0.0f}, 0.0f, 1.0f, {0.0f, 0.0f, 0.0f}, 1.0f, 0.35f},+};+constexpr int kStyleCount = int(sizeof kStyles / sizeof kStyles[0]);++const glm::vec3 kKey = glm::normalize(glm::vec3(-0.45f, 0.6f, 0.65f));+const glm::vec3 kFill = glm::normalize(glm::vec3(0.75f, -0.15f, 0.45f));++// Studio environment radiance in direction `r` (y up, z towards the viewer).+glm::vec3 environment(const glm::vec3& r, float roughness) {+ const float soft = 0.04f + roughness * 0.5f;+ const float up = r.y;+ const glm::vec3 sky = glm::mix(glm::vec3(0.75f, 0.8f, 0.85f), glm::vec3(0.22f, 0.26f, 0.32f), std::sqrt(std::max(up, 0.0f)));+ const glm::vec3 ground = glm::mix(glm::vec3(0.12f, 0.11f, 0.1f), glm::vec3(0.03f, 0.03f, 0.03f), std::sqrt(std::max(-up, 0.0f)));+ const float t = std::clamp(up / soft * 0.5f + 0.5f, 0.0f, 1.0f); // horizon line+ glm::vec3 c = glm::mix(ground, sky, t * t * (3.0f - 2.0f * t));+ // Soft box behind the camera's upper left, and a dimmer strip on the right.+ const float box = std::pow(std::max(glm::dot(r, kKey), 0.0f), 30.0f / (1.0f + 20.0f * roughness));+ const float strip = std::pow(std::max(glm::dot(r, kFill), 0.0f), 60.0f / (1.0f + 20.0f * roughness));+ c += glm::vec3(3.0f) * box + glm::vec3(0.6f, 0.65f, 0.7f) * strip;+ return c;+}++glm::vec3 shade(const MatcapStyle& m, const glm::vec3& n) {+ const glm::vec3 v(0.0f, 0.0f, 1.0f);+ const float nv = std::max(n.z, 0.0f);+ if (m.metal > 0.0f) {+ const glm::vec3 r = 2.0f * n.z * n - v; // reflect(-v, n)+ // Schlick-style brightening towards grazing angles.+ const float fresnel = std::pow(1.0f - nv, 5.0f);+ const glm::vec3 f0 = m.albedo;+ return environment(r, m.roughness) * (f0 + (glm::vec3(1.0f) - f0) * fresnel);+ }+ const float ndl = glm::dot(n, kKey);+ const float diff = std::max((ndl + m.wrap) / (1.0f + m.wrap), 0.0f);+ const float terminator = std::max(0.0f, 1.0f - std::abs(ndl - 0.05f) * 2.5f); // band around the shadow edge+ const float fill = std::max(glm::dot(n, kFill), 0.0f) * 0.2f;+ const float hemi = 0.06f + 0.06f * (0.5f + 0.5f * n.y);+ const glm::vec3 h = glm::normalize(kKey + v);+ const float spec = m.specular * std::pow(std::max(glm::dot(n, h), 0.0f), m.shininess);+ const float rim = std::pow(1.0f - nv, 3.0f);+ glm::vec3 c = m.albedo * (diff * diff * 1.05f + fill + hemi);+ c += m.subsurface * terminator * 0.35f;+ c += glm::vec3(spec) + m.rim * rim;+ return c;+}++std::string squash(const std::string& s) {+ std::string out;+ for (unsigned char c : s)+ if (!std::isspace(c)) out += char(std::tolower(c));+ return out;+}++} // namespace++int matcapCount() { return kStyleCount; }++const char* matcapName(int index) { return index >= 0 && index < kStyleCount ? kStyles[index].name : ""; }++int findMatcap(const std::string& name) {+ const std::string key = squash(name);+ for (int i = 0; i < kStyleCount; ++i)+ if (squash(kStyles[i].name) == key) return i;+ return -1;+}++std::vector<uint8_t> generateMatcap(int index, int size) {+ if (index < 0 || index >= kStyleCount || size <= 0) return {};+ const MatcapStyle& m = kStyles[index];+ std::vector<uint8_t> rgba(size_t(size) * size_t(size) * 4);+ for (int j = 0; j < size; ++j)+ for (int i = 0; i < size; ++i) {+ float x = (float(i) + 0.5f) / float(size) * 2.0f - 1.0f;+ float y = (float(j) + 0.5f) / float(size) * 2.0f - 1.0f;+ float r2 = x * x + y * y;+ if (r2 > 0.998f) { // outside the disk: repeat the rim so filtering at the edge stays clean+ const float k = std::sqrt(0.998f / r2);+ x *= k;+ y *= k;+ r2 = 0.998f;+ }+ const glm::vec3 n(x, y, std::sqrt(1.0f - r2));+ const glm::vec3 c = glm::clamp(linearToSrgb(glm::max(shade(m, n), glm::vec3(0.0f))), 0.0f, 1.0f);+ uint8_t* px = rgba.data() + (size_t(j) * size_t(size) + size_t(i)) * 4;+ for (int k = 0; k < 3; ++k) px[k] = uint8_t(std::lround(c[k] * 255.0f));+ px[3] = 255;+ }+ return rgba;+}++} // namespace sfdiff --git a/src/core/Matcap.h b/src/core/Matcap.hnew file mode 100644index 00000000..653db4ff--- /dev/null+++ b/src/core/Matcap.h@@ -0,0 +1,26 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Built-in MatCap ("material capture") materials. Each is a lit-sphere image+// generated procedurally here (no third-party images): the viewport looks up+// the colour by the view-space normal, so a whole material costs one texture+// fetch. Polypaint multiplies the matcap; cavity shading is applied on top.+#pragma once++#include <cstdint>+#include <string>+#include <vector>++namespace sf {++int matcapCount();+const char* matcapName(int index);+// Case-insensitive; also accepts names without spaces ("redwax"). -1 if unknown.+int findMatcap(const std::string& name);++// `size` x `size` RGBA8 pixels, sRGB-encoded, rows bottom-up (OpenGL order):+// pixel (i, j) shows the sphere normal x = (i + 0.5) / size * 2 - 1,+// y = (j + 0.5) / size * 2 - 1. Pixels outside the disk repeat the rim.+std::vector<uint8_t> generateMatcap(int index, int size = 256);++} // namespace sfdiff --git a/src/core/Polypaint.cpp b/src/core/Polypaint.cppnew file mode 100644index 00000000..4d091160--- /dev/null+++ b/src/core/Polypaint.cpp@@ -0,0 +1,336 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/Polypaint.h"++#include "core/Commands.h"+#include "io/PlyIO.h"++#include <algorithm>+#include <cctype>+#include <cmath>+#include <cstdio>+#include <memory>+#include <sstream>++namespace sf {++namespace {++struct NamedColor {+ const char* name;+ glm::vec3 srgb;+};++const NamedColor kNamedColors[] = {+ {"white", {1.0f, 1.0f, 1.0f}}, {"black", {0.0f, 0.0f, 0.0f}}, {"gray", {0.5f, 0.5f, 0.5f}},+ {"grey", {0.5f, 0.5f, 0.5f}}, {"red", {0.85f, 0.12f, 0.1f}}, {"green", {0.2f, 0.65f, 0.25f}},+ {"blue", {0.15f, 0.35f, 0.85f}}, {"yellow", {0.95f, 0.85f, 0.2f}}, {"orange", {0.95f, 0.5f, 0.12f}},+ {"purple", {0.5f, 0.25f, 0.7f}}, {"pink", {0.95f, 0.6f, 0.7f}}, {"brown", {0.45f, 0.28f, 0.16f}},+ {"cyan", {0.2f, 0.8f, 0.85f}}, {"magenta", {0.85f, 0.2f, 0.75f}}, {"skin", {0.87f, 0.66f, 0.55f}},+ {"bone", {0.89f, 0.85f, 0.75f}}, {"gold", {0.83f, 0.66f, 0.25f}}, {"blood", {0.45f, 0.03f, 0.03f}},+};++int hexDigit(char c) {+ if (c >= '0' && c <= '9') return c - '0';+ c = char(std::tolower(static_cast<unsigned char>(c)));+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;+ return -1;+}++std::string trimLower(const std::string& s) {+ size_t b = 0, e = s.size();+ while (b < e && std::isspace(static_cast<unsigned char>(s[b]))) ++b;+ while (e > b && std::isspace(static_cast<unsigned char>(s[e - 1]))) --e;+ std::string out = s.substr(b, e - b);+ std::transform(out.begin(), out.end(), out.begin(), [](unsigned char c) { return char(std::tolower(c)); });+ return out;+}++bool parseHex(const std::string& s, glm::vec3& srgb) {+ if (s.size() != 3 && s.size() != 6) return false;+ for (char c : s)+ if (hexDigit(c) < 0) return false;+ for (int k = 0; k < 3; ++k) {+ const int v = s.size() == 3 ? hexDigit(s[size_t(k)]) * 17 : hexDigit(s[size_t(2 * k)]) * 16 + hexDigit(s[size_t(2 * k + 1)]);+ srgb[k] = float(v) / 255.0f;+ }+ return true;+}++// Vertex weight for a fill over `area`, before hidden faces are excluded.+float areaWeight(const Mesh& mesh, uint32_t v, PaintArea area) {+ switch (area) {+ case PaintArea::Unmasked: return 1.0f - mesh.maskAt(v);+ case PaintArea::Masked: return mesh.maskAt(v);+ default: return 1.0f;+ }+}++} // namespace++bool parseColor(const std::string& text, glm::vec3& linear) {+ const std::string s = trimLower(text);+ if (s.empty()) return false;+ for (const auto& n : kNamedColors)+ if (s == n.name) {+ linear = srgbToLinear(n.srgb);+ return true;+ }+ glm::vec3 srgb;+ if (parseHex(s[0] == '#' ? s.substr(1) : s, srgb)) {+ linear = srgbToLinear(srgb);+ return true;+ }+ // "r,g,b" or "r g b": 0..1, or 0..255 when any component exceeds 1.+ std::string list = s;+ std::replace(list.begin(), list.end(), ',', ' ');+ std::istringstream in(list);+ float c[3];+ if (!(in >> c[0] >> c[1] >> c[2])) return false;+ std::string rest;+ if (in >> rest) return false;+ const float scale = std::max({c[0], c[1], c[2]}) > 1.0f ? 1.0f / 255.0f : 1.0f;+ for (int k = 0; k < 3; ++k) {+ if (!std::isfinite(c[k]) || c[k] < 0.0f) return false;+ srgb[k] = std::min(c[k] * scale, 1.0f);+ }+ linear = srgbToLinear(srgb);+ return true;+}++std::string colorToHex(const glm::vec3& linear) {+ const glm::vec3 c = glm::clamp(linearToSrgb(linear), 0.0f, 1.0f);+ char buf[8];+ std::snprintf(buf, sizeof buf, "#%02x%02x%02x", int(std::lround(c.x * 255.0f)), int(std::lround(c.y * 255.0f)),+ int(std::lround(c.z * 255.0f)));+ return buf;+}++size_t paintDab(Sculptor& sculptor, Mesh& mesh, const BVH& bvh, const DabParams& p, const glm::vec3& color,+ Symmetry sym) {+ if (!sculptor.strokeActive() || mesh.vertexCount() == 0 || p.radius <= 0.0f) return 0;+ auto& colors = mesh.ensureColors();+ const glm::vec3 target = p.invert ? glm::vec3(1.0f) : color; // Alt paints back to white+ const float s = std::clamp(p.strength, 0.0f, 1.0f) * std::clamp(p.pressure, 0.0f, 1.0f);+ static thread_local std::vector<uint32_t> verts;+ size_t changed = 0;+ for (const glm::vec3& m : Sculptor::mirrors(sym)) {+ const glm::vec3 center = p.center * m, viewDir = p.viewDir * m;+ brushVertices(mesh, bvh, center, p.radius, verts);+ for (uint32_t v : verts) {+ if (p.frontFacesOnly && v < mesh.normals.size() && glm::dot(mesh.normals[v], viewDir) > 0.0f) continue;+ const float w = brushFalloff(glm::distance(mesh.positions[v], center), p.radius) * s * vertexInfluence(mesh, v);+ if (w <= 0.0f) continue;+ sculptor.recordColor(mesh, v);+ colors[v] = glm::mix(colors[v], target, std::min(w, 1.0f));+ mesh.markDirty(v);+ ++changed;+ }+ }+ return changed;+}++size_t paintFill(Mesh& mesh, const glm::vec3& color, PaintArea area, float amount) {+ if (mesh.vertexCount() == 0) return 0;+ auto& colors = mesh.ensureColors();+ amount = std::clamp(amount, 0.0f, 1.0f);+ size_t changed = 0;+ for (uint32_t v = 0; v < mesh.vertexCount(); ++v) {+ if (mesh.hasHidden() && mesh.vertexHidden(v)) continue;+ const float w = areaWeight(mesh, v, area) * amount;+ if (w <= 0.0f) continue;+ colors[v] = glm::mix(colors[v], color, 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);+ if (mesh.normals.size() != nv) return curv;+ // Signed curvature as in Renderer::updateCurvature: > 0 in creases.+ for (uint32_t v = 0; v < nv; ++v) {+ const auto ring = mesh.neighbors(v);+ if (ring.empty()) continue;+ glm::vec3 avg(0.0f);+ float edge = 0.0f;+ const glm::vec3 p = mesh.positions[v];+ for (uint32_t n : ring) {+ avg += mesh.positions[n];+ edge += glm::distance(mesh.positions[n], p);+ }+ avg /= float(ring.size());+ edge /= float(ring.size());+ curv[v] = edge > 0.0f ? glm::dot(mesh.normals[v], avg - p) / edge : 0.0f;+ }+ std::vector<float> tmp(nv);+ for (int it = 0; it < smoothing; ++it) {+ for (uint32_t v = 0; v < nv; ++v) {+ const auto ring = mesh.neighbors(v);+ float sum = curv[v];+ for (uint32_t n : ring) sum += curv[n];+ tmp[v] = sum / float(ring.size() + 1);+ }+ curv.swap(tmp);+ }+ for (float& c : curv) {+ const float t = std::clamp(c / 0.12f, 0.0f, 1.0f);+ c = t * t * (3.0f - 2.0f * t);+ }+ return curv;+}++size_t paintFromCavity(Mesh& mesh, const glm::vec3& color, float strength, int smoothing) {+ if (mesh.vertexCount() == 0) return 0;+ const std::vector<float> cavity = cavityMap(mesh, std::clamp(smoothing, 0, 50));+ auto& colors = mesh.ensureColors();+ strength = std::clamp(strength, 0.0f, 1.0f);+ size_t changed = 0;+ for (uint32_t v = 0; v < mesh.vertexCount(); ++v) {+ const float w = cavity[v] * strength * vertexInfluence(mesh, v);+ if (w <= 0.0f) continue;+ colors[v] = glm::mix(colors[v], color, w);+ ++changed;+ }+ mesh.markAllDirty();+ return changed;+}++glm::vec3 sampleColor(const Mesh& mesh, uint32_t triangle, const glm::vec3& point) {+ if (triangle >= mesh.triangleCount()) return glm::vec3(1.0f);+ const glm::uvec3 t = mesh.triangles[triangle];+ const glm::vec3 a = mesh.positions[t.x], b = mesh.positions[t.y], c = mesh.positions[t.z];+ // Barycentric coordinates of the point projected onto the triangle.+ const glm::vec3 v0 = b - a, v1 = c - a, v2 = point - a;+ const float d00 = glm::dot(v0, v0), d01 = glm::dot(v0, v1), d11 = glm::dot(v1, v1);+ const float d20 = glm::dot(v2, v0), d21 = glm::dot(v2, v1);+ const float denom = d00 * d11 - d01 * d01;+ if (std::abs(denom) < 1e-20f) return mesh.colorAt(t.x);+ float wb = std::clamp((d11 * d20 - d01 * d21) / denom, 0.0f, 1.0f);+ float wc = std::clamp((d00 * d21 - d01 * d20) / denom, 0.0f, 1.0f);+ if (wb + wc > 1.0f) {+ const float k = 1.0f / (wb + wc);+ wb *= k;+ wc *= k;+ }+ return mesh.colorAt(t.x) * (1.0f - wb - wc) + mesh.colorAt(t.y) * wb + mesh.colorAt(t.z) * wc;+}++namespace {++// A colour from "color" (any parseColor form) or numeric "r"/"g"/"b" (sRGB 0..1).+// Returns false with `error` empty when no colour was given.+bool colorArg(const Args& a, glm::vec3& linear, std::string& error) {+ if (a.contains("color")) {+ const std::string text = argString(a, "color");+ if (parseColor(text, linear)) return true;+ error = "Unrecognised colour '" + text + "' (use #rrggbb, r,g,b or a name such as red)";+ return false;+ }+ if (a.contains("r") || a.contains("g") || a.contains("b")) {+ glm::vec3 srgb(float(argNumber(a, "r", 0.0)), float(argNumber(a, "g", 0.0)), float(argNumber(a, "b", 0.0)));+ if (std::max({srgb.x, srgb.y, srgb.z}) > 1.0f) srgb /= 255.0f;+ linear = srgbToLinear(glm::clamp(srgb, 0.0f, 1.0f));+ return true;+ }+ return false;+}++// Undo step for a whole-mesh colour edit, pushed before the edit: the old+// colours, or a mesh snapshot when there is no polypaint yet, so undo removes+// the attribute again instead of leaving the mesh painted white.+UndoRecord colorUndo(const Mesh& mesh, std::string label) {+ if (mesh.hasColors()) return UndoRecord::captureColors(mesh, std::move(label));+ UndoRecord r;+ r.label = std::move(label);+ r.mesh = std::make_unique<Mesh>(mesh);+ return r;+}++const char* kColorHelp = "Colour: rrggbb or #rrggbb (quote it in scripts), r,g,b (0-1 or 0-255) or a name (white, black, red, skin, bone, ...).";++} // namespace++void registerPaintCommands(CommandRegistry& registry) {+ using T = ParamSpec::Type;++ registry.add({"set_color",+ "Set the current polypaint colour used by the Paint brush and paint_fill.",+ {{"color", T::String, kColorHelp, false},+ {"r", T::Number, "Red 0-1 (sRGB), instead of color.", false},+ {"g", T::Number, "Green 0-1 (sRGB).", false},+ {"b", T::Number, "Blue 0-1 (sRGB).", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ glm::vec3 c;+ std::string err;+ if (!colorArg(a, c, err)) return {false, err.empty() ? "Give a color (or r, g, b)" : err};+ doc.paintColor = c;+ return {true, "Paint colour " + colorToHex(c)};+ }});++ registry.add({"paint_fill",+ "Fill the mesh with a polypaint colour (undoable). By default the mask is respected: only "+ "unmasked areas are painted. Hidden faces are never painted.",+ {{"color", T::String, std::string(kColorHelp) + " Default: the current paint colour.", false},+ {"area", T::String, "unmasked (default), masked (only the masked area) or all (ignore the mask).", false},+ {"strength", T::Number, "Blend amount 0-1. Default 1.", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ if (doc.mesh.vertexCount() == 0) return {false, "There is no mesh to paint"};+ glm::vec3 c = doc.paintColor;+ std::string err;+ if (!colorArg(a, c, err) && !err.empty()) return {false, err};+ 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 && !doc.mesh.hasMask()) return {false, "Nothing is masked"};+ doc.undo.push(colorUndo(doc.mesh, "Fill Color"));+ const size_t n = paintFill(doc.mesh, c, area, float(argNumber(a, "strength", 1.0)));+ doc.modified = true;+ return {true, "Filled " + std::to_string(n) + " vertices with " + colorToHex(c)};+ }});++ registry.add({"paint_clear", "Remove all polypaint from the mesh (undoable).", {},+ [](Document& doc, const Args&) -> CommandResult {+ if (!doc.mesh.hasColors()) return {true, "The mesh has no polypaint"};+ // A snapshot, so redo removes the attribute again instead of leaving white paint.+ Mesh cleared = doc.mesh;+ cleared.clearColors();+ doc.replaceMeshUndoable(std::move(cleared), "Clear Polypaint");+ return {true, "Polypaint cleared"};+ }});++ registry.add({"paint_from_cavity",+ "Darken (or tint) the creases and cavities of the sculpt with polypaint, like ZBrush's cavity "+ "masking plus fill (undoable, respects the mask).",+ {{"color", T::String, std::string(kColorHelp) + " Default: a dark brown.", false},+ {"strength", T::Number, "0-1. Default 0.7.", false},+ {"smoothing", T::Number, "Blur passes over the cavity map (0-50). Default 2.", false}},+ [](Document& doc, const Args& a) -> CommandResult {+ if (doc.mesh.vertexCount() == 0) return {false, "There is no mesh to paint"};+ glm::vec3 c = srgbToLinear(glm::vec3(0.16f, 0.1f, 0.08f));+ std::string err;+ if (!colorArg(a, c, err) && !err.empty()) return {false, err};+ doc.undo.push(colorUndo(doc.mesh, "Paint Cavity"));+ const size_t n = paintFromCavity(doc.mesh, c, float(argNumber(a, "strength", 0.7)),+ int(argNumber(a, "smoothing", 2)));+ doc.modified = true;+ return {true, "Painted cavities on " + std::to_string(n) + " vertices"};+ }});++ registry.add({"export_ply",+ "Export the mesh as a binary PLY with vertex colours (polypaint), for scan tools, MeshLab, Blender.",+ {{"path", T::String, "Output .ply path (UTF-8).", true}},+ [](Document& doc, const Args& a) -> CommandResult {+ const std::string path = argString(a, "path");+ std::string err;+ if (!savePlyMesh(path, doc.mesh, err)) return {false, err};+ return {true, "Exported " + path + (doc.mesh.hasColors() ? " (with polypaint)" : "")};+ }});+}++} // namespace sfdiff --git a/src/core/Polypaint.h b/src/core/Polypaint.hnew file mode 100644index 00000000..0e4f44df--- /dev/null+++ b/src/core/Polypaint.h@@ -0,0 +1,53 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Polypaint: per-vertex colour painting (Mesh::colors, linear RGB). The Paint+// brush, whole-mesh fills, cavity darkening and the paint_* commands. Every+// operation respects the mask (and hidden faces) like the sculpt brushes do.+#pragma once++#include "core/BVH.h"+#include "core/Mesh.h"+#include "core/Sculpt.h"++#include <string>++namespace sf {++class CommandRegistry;++// Parses a colour given as "#rgb", "#rrggbb", "rrggbb", "r,g,b" (0..1 or+// 0..255) or a basic name ("red", "skin", ...). The text is a display (sRGB)+// colour; `linear` receives the linear value Mesh::colors stores.+bool parseColor(const std::string& text, glm::vec3& linear);+// "#rrggbb" (sRGB) for a linear colour.+std::string colorToHex(const glm::vec3& linear);++// One Paint brush dab inside a Sculptor stroke: blends `color` into the+// vertices under the brush with the smoothstep falloff, strength x pressure,+// symmetry and vertexInfluence() (mask / hidden). `p.invert` paints back to+// white. Records old colours for the stroke's undo step and marks vertices+// dirty. Returns the number of vertices changed.+size_t paintDab(Sculptor& sculptor, Mesh& mesh, const BVH& bvh, const DabParams& p, const glm::vec3& color,+ Symmetry sym);++enum class PaintArea { All, Unmasked, Masked };++// Blends `color` over the mesh with weight `amount` (0..1). Unmasked scales by+// 1 - mask (the whole mesh when nothing is masked), Masked by the mask, All+// 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);++// 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);+// Blends `color` into the creases by cavity x strength (respects the mask).+size_t paintFromCavity(Mesh& mesh, const glm::vec3& color, float strength, int smoothing = 2);++// Colour under a surface point: barycentric blend of the hit triangle's vertex colours.+glm::vec3 sampleColor(const Mesh& mesh, uint32_t triangle, const glm::vec3& point);++// set_color, paint_fill, paint_clear, paint_from_cavity, export_ply.+void registerPaintCommands(CommandRegistry& registry);++} // namespace sfdiff --git a/src/io/PlyIO.cpp b/src/io/PlyIO.cppindex 414a3f86..dcf44052 100644--- a/src/io/PlyIO.cpp+++ b/src/io/PlyIO.cpp@@ -448,4 +448,55 @@ bool saveDotSplat(const std::string& path, const SplatCloud& input, std::string&return true;}+bool savePlyMesh(const std::string& path, const Mesh& mesh, std::string& error) {+ if (mesh.triangleCount() == 0) {+ error = "There is no mesh to save";+ return false;+ }+ const bool colors = mesh.hasColors() && mesh.colors.size() == mesh.vertexCount();+ const bool normals = mesh.normals.size() == mesh.vertexCount();+ std::ostringstream h;+ h << "ply\nformat binary_little_endian 1.0\ncomment Generated by SculptForge\nelement vertex " << mesh.vertexCount()+ << "\nproperty float x\nproperty float y\nproperty float z\n";+ if (normals) h << "property float nx\nproperty float ny\nproperty float nz\n";+ if (colors) h << "property uchar red\nproperty uchar green\nproperty uchar blue\n";+ h << "element face " << mesh.triangleCount() << "\nproperty list uchar int vertex_indices\nend_header\n";++ std::vector<uint8_t> data;+ data.reserve(mesh.vertexCount() * 27 + mesh.triangleCount() * 13);+ auto put32 = [&](uint32_t u) {+ for (int k = 0; k < 4; ++k) data.push_back(uint8_t(u >> (8 * k))); // little-endian on any host+ };+ auto putFloat = [&](float v) { put32(std::bit_cast<uint32_t>(v)); };+ for (size_t v = 0; v < mesh.vertexCount(); ++v) {+ for (int c = 0; c < 3; ++c) putFloat(mesh.positions[v][c]);+ if (normals)+ for (int c = 0; c < 3; ++c) putFloat(mesh.normals[v][c]);+ if (colors) {+ const glm::vec3 c = glm::clamp(linearToSrgb(mesh.colors[v]), 0.0f, 1.0f);+ for (int k = 0; k < 3; ++k) data.push_back(uint8_t(std::lround(c[k] * 255.0f)));+ }+ }+ for (const auto& t : mesh.triangles) {+ data.push_back(3);+ put32(t.x);+ put32(t.y);+ put32(t.z);+ }++ std::ofstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);+ if (!f) {+ error = "Cannot write " + path;+ return false;+ }+ const std::string hs = h.str();+ f.write(hs.data(), std::streamsize(hs.size()));+ f.write(reinterpret_cast<const char*>(data.data()), std::streamsize(data.size()));+ if (!f) {+ error = "Write failed for " + path;+ return false;+ }+ return true;+}+} // namespace sfdiff --git a/src/io/PlyIO.h b/src/io/PlyIO.hindex 91e5e2e2..df511132 100644--- a/src/io/PlyIO.h+++ b/src/io/PlyIO.h@@ -30,4 +30,8 @@ bool saveSplatPly(const std::string& path, const SplatCloud& splats, std::stringbool loadDotSplat(const std::string& path, SplatCloud& splats, std::string& error);bool saveDotSplat(const std::string& path, const SplatCloud& splats, std::string& error);+// Writes a triangle mesh (binary little-endian: positions, normals and, when+// the mesh has polypaint, uchar red/green/blue in sRGB) that loadPly reads back.+bool savePlyMesh(const std::string& path, const Mesh& mesh, std::string& error);+} // namespace sfdiff --git a/src/io/UsdIO.cpp b/src/io/UsdIO.cppindex b80fbb4f..c24a417f 100644--- a/src/io/UsdIO.cpp+++ b/src/io/UsdIO.cpp@@ -144,6 +144,14 @@ void writeMesh(Writer& w, const Mesh& mesh, const std::string& root, const std::w.line(" interpolation = \"vertex\"");w.line(")");w.array("point3f[] points", base.positions, [&](const glm::vec3& p) { w.vec3(p); });+ if (mesh.hasColors() && mesh.colors.size() == mesh.vertexCount()) {+ // Polypaint (linear, as USD expects); the material reads it through a primvar reader.+ w.array("color3f[] primvars:displayColor", mesh.colors, [&](const glm::vec3& c) { w.vec3(c); });+ w.s.pop_back();+ w.s += " (\n";+ w.line(" interpolation = \"vertex\"");+ w.line(")");+ }w.line("uniform token subdivisionScheme = \"none\"");if (skinned) {w.array("uniform token[] skel:blendShapes", shapeNames, [&](const std::string& n) { w.s += quoted(n); });@@ -243,11 +251,20 @@ std::string buildUsda(const Mesh* mesh, const SplatCloud* splats, const std::strw.s += '\n';w.open("def Shader \"PreviewSurface\"");w.line("uniform token info:id = \"UsdPreviewSurface\"");- w.line("color3f inputs:diffuseColor = (0.8, 0.55, 0.45)");+ if (mesh->hasColors()) w.line("color3f inputs:diffuseColor.connect = <" + material + "/Polypaint.outputs:result>");+ else w.line("color3f inputs:diffuseColor = (0.8, 0.55, 0.45)");w.line("float inputs:metallic = 0");w.line("float inputs:roughness = 0.65");w.line("token outputs:surface");w.close();+ if (mesh->hasColors()) {+ w.s += '\n';+ w.open("def Shader \"Polypaint\"");+ w.line("uniform token info:id = \"UsdPrimvarReader_float3\"");+ w.line("string inputs:varname = \"displayColor\"");+ w.line("float3 outputs:result");+ w.close();+ }w.close();w.close();}diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cppindex 54cb15ea..6934f8a7 100644--- a/src/render/Renderer.cpp+++ b/src/render/Renderer.cpp@@ -2,6 +2,8 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "render/Renderer.h"+#include "core/Matcap.h"+#include <glm/gtc/type_ptr.hpp>#include <algorithm>@@ -49,6 +51,8 @@ uniform int uPaint; // 1: vertex colours replace the base colouruniform int uShowMask; // 1: darken masked areasuniform int uGroups; // 0: off, 1: per-triangle ids from uGroupIds, 2: everything is group 0uniform usamplerBuffer uGroupIds;+uniform int uMatcap; // 1: shade with the matcap texture instead of the studio lights+uniform sampler2D uMatcapTex; // sRGB-encoded lit sphere (core/Matcap.h)out vec4 fragColor;// Keep in sync with sf::polygroupColor.vec3 groupColor(uint id) {@@ -64,12 +68,26 @@ vec3 groupColor(uint id) {}void main() {vec3 albedo = uBaseColor;- if (uGroups == 1) albedo = groupColor(texelFetch(uGroupIds, gl_PrimitiveID).r);- else if (uGroups == 2) albedo = groupColor(0u);- else if (uPaint == 1) albedo = vColor;+ vec3 tint = vec3(1.0); // multiplies a matcap: polypaint or polygroup colours+ if (uGroups == 1) albedo = tint = groupColor(texelFetch(uGroupIds, gl_PrimitiveID).r);+ else if (uGroups == 2) albedo = tint = groupColor(0u);+ else if (uPaint == 1) albedo = tint = vColor;vec3 n = normalize(vNormal);if (!gl_FrontFacing) n = -n;vec3 v = normalize(-vPos);+ if (uMatcap == 1) {+ // View-aligned basis so the material stays put towards the edges of a perspective view.+ vec3 bx = normalize(vec3(v.z, 0.0, -v.x));+ vec3 by = cross(v, bx);+ vec2 uv = vec2(dot(bx, n), dot(by, n)) * 0.495 + 0.5;+ vec3 mc = pow(texture(uMatcapTex, uv).rgb, vec3(2.2));+ float mcrease = smoothstep(0.0, 0.16, vCurvature);+ float mridge = smoothstep(0.0, 0.2, -vCurvature);+ vec3 c = mc * tint * (1.0 - 0.55 * mcrease) * (1.0 + 0.2 * mridge);+ if (uShowMask == 1) c *= 1.0 - 0.75 * clamp(vMask, 0.0, 1.0);+ fragColor = vec4(pow(c, vec3(1.0 / 2.2)), 1.0);+ return;+ }vec3 key = normalize(vec3(0.45, 0.65, 0.6));vec3 fill = normalize(vec3(-0.7, -0.1, 0.4));float diff = max((dot(n, key) + 0.25) / 1.25, 0.0);@@ -174,6 +192,8 @@ void main() {})";+constexpr GLenum kTexture2 = 0x84C2; // GL_TEXTURE2 (matcap)+GLuint compile(GLenum type, const char* src, std::string& error) {GLuint s = gl::CreateShader(type);gl::ShaderSource(s, 1, &src, nullptr);@@ -281,9 +301,29 @@ bool Renderer::init(std::string& error) {gl::BindBuffer(GL_ARRAY_BUFFER, 0);gl::GenBuffers(1, &groupData_);gl::GenTextures(1, &groupTexture_);++ // Built-in matcaps, generated once (6 x 256 KB).+ matcapTextures_.assign(size_t(matcapCount()), 0);+ gl::GenTextures(GLsizei(matcapTextures_.size()), matcapTextures_.data());+ gl::PixelStorei(GL_UNPACK_ALIGNMENT, 1);+ for (int i = 0; i < matcapCount(); ++i) {+ constexpr int kSize = 256;+ const std::vector<uint8_t> pixels = generateMatcap(i, kSize);+ gl::BindTexture(GL_TEXTURE_2D, matcapTextures_[size_t(i)]);+ gl::TexImage2D(GL_TEXTURE_2D, 0, GLint(GL_RGBA8), kSize, kSize, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GLint(GL_LINEAR));+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GLint(GL_LINEAR));+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GLint(GL_CLAMP_TO_EDGE));+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GLint(GL_CLAMP_TO_EDGE));+ }+ gl::BindTexture(GL_TEXTURE_2D, 0);return true;}+GLuint Renderer::matcapTexture(int index) const {+ return index >= 0 && index < int(matcapTextures_.size()) ? matcapTextures_[size_t(index)] : 0;+}+void Renderer::shutdown() {gl::DeleteBuffers(1, &posBuffer_);gl::DeleteBuffers(1, &nrmBuffer_);@@ -292,6 +332,8 @@ void Renderer::shutdown() {gl::DeleteBuffers(1, &maskBuffer_);gl::DeleteBuffers(1, &groupData_);gl::DeleteTextures(1, &groupTexture_);+ if (!matcapTextures_.empty()) gl::DeleteTextures(GLsizei(matcapTextures_.size()), matcapTextures_.data());+ matcapTextures_.clear();gl::DeleteBuffers(1, &indexBuffer_);gl::DeleteVertexArrays(1, &vao_);gl::DeleteVertexArrays(1, &emptyVao_);@@ -632,6 +674,11 @@ void Renderer::draw(const Camera& camera, int fbWidth, int fbHeight, const Rendegl::Uniform1i(gl::GetUniformLocation(meshProgram_, "uShowMask"), settings.showMask && hasMask_ ? 1 : 0);gl::Uniform1i(gl::GetUniformLocation(meshProgram_, "uGroups"), settings.showPolygroups ? (hasGroups_ ? 1 : 2) : 0);gl::Uniform1i(gl::GetUniformLocation(meshProgram_, "uGroupIds"), 1);+ const GLuint matcap = matcapTexture(settings.matcap);+ gl::Uniform1i(gl::GetUniformLocation(meshProgram_, "uMatcap"), matcap ? 1 : 0);+ gl::Uniform1i(gl::GetUniformLocation(meshProgram_, "uMatcapTex"), 2);+ gl::ActiveTexture(kTexture2);+ gl::BindTexture(GL_TEXTURE_2D, matcap);// Constant values for the attribute arrays that are disabled.if (!hasColors_) gl::VertexAttrib3f(3, 1.0f, 1.0f, 1.0f);if (!hasMask_) gl::VertexAttrib1f(4, 0.0f);@@ -644,6 +691,8 @@ void Renderer::draw(const Camera& camera, int fbWidth, int fbHeight, const Rendegl::Disable(GL_POLYGON_OFFSET_FILL);gl::ActiveTexture(GL_TEXTURE1);gl::BindTexture(GL_TEXTURE_BUFFER, 0);+ gl::ActiveTexture(kTexture2);+ gl::BindTexture(GL_TEXTURE_2D, 0);gl::ActiveTexture(GL_TEXTURE0);if (settings.wireframe) {diff --git a/src/render/Renderer.h b/src/render/Renderer.hindex 95c7c650..a6a44f5d 100644--- a/src/render/Renderer.h+++ b/src/render/Renderer.h@@ -19,6 +19,7 @@ struct RenderSettings {bool showPolypaint = true; // vertex colours replace baseColor when the mesh has thembool showMask = true; // masked areas render darker (ZBrush style)bool showPolygroups = false; // colour each polygroup (see polygroupColor)+ int matcap = -1; // built-in MatCap material (core/Matcap.h); -1 = studio clay lightingbool showMesh = true;bool showSplats = true;float splatOpacity = 1.0f; // global fade for using a capture as reference@@ -49,6 +50,9 @@ public:bool beginCapture(int width, int height, std::string& error);void endCapture(std::vector<uint8_t>& rgba); // top-down RGBA rows+ // Texture of built-in matcap `index` (sRGB RGBA8, rows bottom-up) for UI previews; 0 if none.+ GLuint matcapTexture(int index) const;+private:void drawSplats(const glm::mat4& view, const glm::mat4& proj, int fbWidth, int fbHeight, float opacity);@@ -73,6 +77,7 @@ private:std::vector<glm::uvec3> visibleTris_;std::vector<uint32_t> visibleGroups_;GLsizei indexCount_ = 0;+ std::vector<GLuint> matcapTextures_; // one per built-in matcap (core/Matcap.h)size_t vertexCapacity_ = 0;};diff --git a/tests/test_polypaint.cpp b/tests/test_polypaint.cppnew file mode 100644index 00000000..1bb234c2--- /dev/null+++ b/tests/test_polypaint.cpp@@ -0,0 +1,308 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Polypaint (Paint brush, fills, cavity paint, colour commands, PLY/USD+// export) and the built-in MatCap materials.+#include "TestHarness.h"++#include "core/Commands.h"+#include "core/Matcap.h"+#include "core/Polypaint.h"+#include "core/Primitives.h"+#include "io/PlyIO.h"++#include <algorithm>+#include <cmath>+#include <filesystem>+#include <fstream>+#include <sstream>++using namespace sf;++namespace {++bool near(const glm::vec3& a, const glm::vec3& b, float eps = 1e-3f) { return glm::all(glm::lessThan(glm::abs(a - b), glm::vec3(eps))); }++uint32_t nearestVertex(const Mesh& m, const glm::vec3& p) {+ uint32_t best = 0;+ for (uint32_t v = 1; v < m.vertexCount(); ++v)+ if (glm::distance(m.positions[v], p) < glm::distance(m.positions[best], p)) best = v;+ return best;+}++DabParams paintParams(const glm::vec3& center, float radius) {+ DabParams p;+ p.center = center;+ p.viewDir = -glm::normalize(center);+ p.radius = radius;+ p.strength = 1.0f;+ return p;+}++const glm::vec3 kRed(1.0f, 0.0f, 0.0f);++} // namespace++TEST(polypaint_parse_color) {+ glm::vec3 c;+ CHECK(parseColor("#ff0000", c) && near(c, kRed));+ CHECK(parseColor(" #F00 ", c) && near(c, kRed));+ CHECK(parseColor("00ff00", c) && near(c, glm::vec3(0, 1, 0)));+ CHECK(parseColor("Red", c) && c.x > 0.5f && c.y < 0.05f);+ CHECK(parseColor("255,0,0", c) && near(c, kRed));+ CHECK(parseColor("0.5 0.5 0.5", c) && near(c, srgbToLinear(glm::vec3(0.5f))));+ CHECK(!parseColor("nope", c));+ CHECK(!parseColor("#12345", c));+ CHECK(!parseColor("1,2", c));+ CHECK(!parseColor("1,2,3,4", c));+ CHECK(!parseColor("", c));+ CHECK(colorToHex(srgbToLinear(glm::vec3(0.5f, 1.0f, 0.0f))) == "#80ff00");+ CHECK(parseColor(colorToHex(srgbToLinear(glm::vec3(0.2f, 0.4f, 0.6f))), c) &&+ near(linearToSrgb(c), glm::vec3(0.2f, 0.4f, 0.6f), 3e-3f));+}++TEST(polypaint_brush_falloff_symmetry_mask_undo) {+ Document doc = makeDoc(makeIcosphere(4));+ Mesh& m = doc.mesh;+ const std::vector<glm::vec3> before = m.positions;+ // Mask the upper half.+ m.ensureMask();+ for (uint32_t v = 0; v < m.vertexCount(); ++v) m.mask[v] = m.positions[v].y > 0.05f ? 1.0f : 0.0f;++ const uint32_t centre = nearestVertex(m, {1, 0, 0}), mirror = nearestVertex(m, {-1, 0, 0});+ const uint32_t masked = nearestVertex(m, {0.97f, 0.24f, 0}), far = nearestVertex(m, {0, 0, 1});+ CHECK(!m.hasColors());+ CHECK(doc.sculptor.beginStroke(m, "Paint"));+ const size_t n = paintDab(doc.sculptor, m, doc.bvh, paintParams(m.positions[centre], 0.5f), kRed, Symmetry{});+ doc.undo.push(doc.sculptor.endStroke());+ CHECK(n > 0 && m.hasColors() && m.colors.size() == m.vertexCount());+ CHECK(near(m.colors[centre], kRed, 0.02f));+ CHECK(near(m.colors[mirror], kRed, 0.05f)); // X symmetry is on by default+ CHECK(m.colors[masked] == glm::vec3(1.0f));+ CHECK(m.colors[far] == glm::vec3(1.0f));+ // Falloff: a vertex half-way out is painted less than the centre.+ const uint32_t mid = nearestVertex(m, glm::normalize(glm::vec3(1, -0.1f, 0.25f)));+ CHECK(m.colors[mid].y > m.colors[centre].y && m.colors[mid].y < 1.0f);+ CHECK(m.positions == before); // paint never sculpts++ CHECK(doc.undo.undo(m, doc.bvh));+ bool allWhite = true;+ for (const auto& c : m.colors) allWhite = allWhite && c == glm::vec3(1.0f);+ CHECK(allWhite);+ CHECK(doc.undo.redo(m, doc.bvh));+ CHECK(near(m.colors[centre], kRed, 0.02f));++ // Without an active stroke nothing happens.+ CHECK(paintDab(doc.sculptor, m, doc.bvh, paintParams(m.positions[far], 0.5f), kRed, Symmetry{}) == 0);+}++TEST(polypaint_invert_hidden_front_faces) {+ Document doc = makeDoc(makeIcosphere(3));+ Mesh& m = doc.mesh;+ m.ensureColors(kRed);+ const uint32_t v = nearestVertex(m, {0, 0, 1});+ // Hide the triangles around one vertex near the dab, off-centre.+ const uint32_t hiddenV = nearestVertex(m, glm::normalize(glm::vec3(0.15f, 0, 1)));+ m.ensureHidden();+ for (uint32_t t : m.vertexTriangles(hiddenV)) m.hidden[t] = 1;+ doc.sculptor.beginStroke(m, "Paint");+ DabParams p = paintParams(m.positions[v], 0.4f);+ p.invert = true; // Alt: back to white+ paintDab(doc.sculptor, m, doc.bvh, p, glm::vec3(0, 0, 1), Symmetry{false, false, false});+ // Front faces only: a dab "seen" from behind the sphere paints nothing.+ DabParams back = paintParams(m.positions[v], 0.4f);+ back.viewDir = glm::vec3(0, 0, 1);+ back.frontFacesOnly = true;+ const size_t backCount = paintDab(doc.sculptor, m, doc.bvh, back, glm::vec3(0, 1, 0), Symmetry{false, false, false});+ doc.undo.push(doc.sculptor.endStroke());+ CHECK(m.colors[v].y > 0.9f && m.colors[v].z > 0.9f); // painted towards white, not blue+ CHECK(m.colors[hiddenV] == kRed);+ CHECK(backCount == 0);+}++TEST(polypaint_with_sculpt_is_one_undo_step) {+ Document doc = makeDoc(makeIcosphere(3));+ Mesh& m = doc.mesh;+ const std::vector<glm::vec3> before = m.positions;+ const uint32_t v = nearestVertex(m, {0, 1, 0});+ DabParams p = paintParams(m.positions[v], 0.4f);+ doc.sculptor.beginStroke(m, "Standard");+ doc.sculptor.dab(m, doc.bvh, BrushType::Standard, p, Symmetry{});+ paintDab(doc.sculptor, m, doc.bvh, p, kRed, Symmetry{});+ UndoRecord r = doc.sculptor.endStroke();+ CHECK(!r.positions.empty() && !r.colors.empty());+ doc.undo.push(std::move(r));+ CHECK(m.positions != before && m.colors[v] != glm::vec3(1.0f));+ doc.undo.undo(m, doc.bvh);+ CHECK(m.positions == before && m.colors[v] == glm::vec3(1.0f));+}++TEST(polypaint_fill_and_clear_commands) {+ CommandRegistry reg;+ Document doc = makeDoc(makeIcosphere(3));+ Mesh& m = doc.mesh;+ CHECK(!reg.execute(doc, "paint_fill", {{"area", std::string("masked")}}).ok); // nothing masked+ CHECK(!reg.execute(doc, "paint_fill", {{"color", std::string("not a colour")}}).ok);+ CHECK(!reg.execute(doc, "paint_fill", {{"area", std::string("sideways")}}).ok);+ CHECK(!m.hasColors());++ // Default: the current colour over the unmasked area (= whole mesh without a mask).+ CHECK(reg.execute(doc, "set_color", {{"color", std::string("#0000ff")}}).ok);+ CHECK(near(doc.paintColor, glm::vec3(0, 0, 1)));+ CHECK(reg.execute(doc, "paint_fill").ok);+ CHECK(reg.execute(doc, "undo").ok && !m.hasColors()); // the first fill's undo removes polypaint again+ CHECK(reg.execute(doc, "redo").ok && m.hasColors());+ CHECK(std::all_of(m.colors.begin(), m.colors.end(), [](const glm::vec3& c) { return near(c, glm::vec3(0, 0, 1)); }));++ m.ensureMask();+ for (uint32_t v = 0; v < m.vertexCount(); ++v) m.mask[v] = m.positions[v].x > 0.0f ? 1.0f : 0.0f;+ const uint32_t right = nearestVertex(m, {1, 0, 0}), left = nearestVertex(m, {-1, 0, 0});+ CHECK(reg.execute(doc, "paint_fill", {{"color", std::string("red")}, {"area", std::string("masked")}}).ok);+ CHECK(m.colors[right].x > 0.5f && m.colors[right].z < 0.05f && near(m.colors[left], glm::vec3(0, 0, 1)));+ CHECK(reg.execute(doc, "paint_fill", {{"r", 1.0}, {"g", 1.0}, {"b", 1.0}, {"strength", 0.5}}).ok); // unmasked, half+ CHECK(near(m.colors[left], glm::vec3(0.5f, 0.5f, 1.0f)) && m.colors[right].z < 0.05f);+ CHECK(reg.execute(doc, "paint_fill", {{"color", std::string("#00ff00")}, {"area", std::string("all")}}).ok);+ CHECK(near(m.colors[right], glm::vec3(0, 1, 0)) && near(m.colors[left], glm::vec3(0, 1, 0)));++ // Each fill is one undo step.+ CHECK(reg.execute(doc, "undo").ok);+ CHECK(near(m.colors[left], glm::vec3(0.5f, 0.5f, 1.0f)));+ CHECK(reg.execute(doc, "paint_clear").ok);+ CHECK(!m.hasColors());+ CHECK(reg.execute(doc, "undo").ok);+ CHECK(m.hasColors() && near(m.colors[left], glm::vec3(0.5f, 0.5f, 1.0f)));+ CHECK(reg.execute(doc, "redo").ok && !m.hasColors());+ CHECK(reg.execute(doc, "paint_clear").ok); // no-op when there is nothing to clear++ CHECK(!reg.execute(doc, "set_color").ok);+ CHECK(!reg.execute(doc, "set_color", {{"color", std::string("#zzz")}}).ok);+ CHECK(reg.execute(doc, "set_color", {{"r", 255.0}, {"g", 0.0}, {"b", 0.0}}).ok && near(doc.paintColor, kRed));+}++TEST(polypaint_fill_skips_hidden) {+ Mesh m = makeIcosphere(2);+ m.ensureHidden();+ const uint32_t v = nearestVertex(m, {0, 1, 0});+ for (uint32_t t : m.vertexTriangles(v)) m.hidden[t] = 1;+ paintFill(m, kRed, PaintArea::All);+ CHECK(m.colors[v] == glm::vec3(1.0f) && m.colors[nearestVertex(m, {0, -1, 0})] == kRed);+}++TEST(polypaint_from_cavity) {+ Mesh m = makeIcosphere(4);+ // Push one vertex in to make a dent; the rest of the sphere is convex.+ const uint32_t dent = nearestVertex(m, {0, 0, 1}), far = nearestVertex(m, {0, 0, -1});+ m.positions[dent] *= 0.97f;+ m.recomputeAllNormals();+ const std::vector<float> cav = cavityMap(m, 0);+ CHECK(cav[dent] > 0.5f && cav[far] == 0.0f);+ CHECK(*std::min_element(cav.begin(), cav.end()) >= 0.0f && *std::max_element(cav.begin(), cav.end()) <= 1.0f);++ CommandRegistry reg;+ Document doc = makeDoc(m);+ CHECK(reg.execute(doc, "paint_from_cavity", {{"smoothing", 0.0}, {"strength", 1.0}}).ok);+ CHECK(doc.mesh.colors[dent].x < 0.5f && doc.mesh.colors[far] == glm::vec3(1.0f));+ CHECK(reg.execute(doc, "undo").ok);+ CHECK(!doc.mesh.hasColors()); // undo of the first colour edit removes polypaint+ // Masked vertices keep their colour.+ doc.mesh.ensureMask();+ doc.mesh.mask[dent] = 1.0f;+ CHECK(reg.execute(doc, "paint_from_cavity", {{"smoothing", 0.0}, {"color", std::string("#ff0000")}}).ok);+ CHECK(doc.mesh.colors[dent] == glm::vec3(1.0f));+}++TEST(polypaint_sample_color) {+ Mesh m = makeIcosphere(1);+ m.ensureColors(glm::vec3(0.0f));+ const glm::uvec3 t = m.triangles[0];+ m.colors[t.x] = glm::vec3(1, 0, 0);+ m.colors[t.y] = glm::vec3(0, 1, 0);+ m.colors[t.z] = glm::vec3(0, 0, 1);+ CHECK(near(sampleColor(m, 0, m.positions[t.y]), glm::vec3(0, 1, 0)));+ const glm::vec3 centre = (m.positions[t.x] + m.positions[t.y] + m.positions[t.z]) / 3.0f;+ CHECK(near(sampleColor(m, 0, centre), glm::vec3(1.0f / 3.0f)));+ CHECK(sampleColor(m, uint32_t(m.triangleCount()), centre) == glm::vec3(1.0f)); // out of range+}++TEST(polypaint_export_ply_and_usd) {+ CommandRegistry reg;+ Document doc = makeDoc(makeIcosphere(3));+ const std::string plain = tempPath("sf_polypaint_plain.ply"), painted = tempPath("sf_polypaint.ply");+ CHECK(reg.execute(doc, "export_ply", {{"path", plain}}).ok);+ for (uint32_t v = 0; v < doc.mesh.vertexCount(); ++v) {+ doc.mesh.ensureColors();+ doc.mesh.colors[v] = srgbToLinear(glm::clamp(doc.mesh.positions[v] * 0.5f + 0.5f, 0.0f, 1.0f));+ }+ CHECK(reg.execute(doc, "export_ply", {{"path", painted}}).ok);++ Mesh a, b;+ SplatCloud splats;+ PlyContent content;+ std::string err;+ CHECK(loadPly(plain, a, splats, content, err) && content == PlyContent::Mesh);+ CHECK(a.triangleCount() == doc.mesh.triangleCount() && !a.hasColors());+ CHECK(loadPly(painted, b, splats, content, err) && content == PlyContent::Mesh);+ CHECK(b.vertexCount() == doc.mesh.vertexCount() && b.hasColors());+ bool same = b.vertexCount() == doc.mesh.vertexCount();+ for (uint32_t v = 0; same && v < b.vertexCount(); ++v) {+ const uint32_t o = nearestVertex(doc.mesh, b.positions[v]);+ same = near(linearToSrgb(b.colors[v]), linearToSrgb(doc.mesh.colors[o]), 0.5f / 255.0f + 1e-4f);+ }+ CHECK(same);++ const std::string usd = tempPath("sf_polypaint.usda");+ CHECK(reg.execute(doc, "export_usd", {{"path", usd}}).ok);+ std::ifstream f(usd);+ std::stringstream text;+ text << f.rdbuf();+ CHECK(text.str().find("color3f[] primvars:displayColor") != std::string::npos);+ CHECK(text.str().find("UsdPrimvarReader_float3") != std::string::npos);+ CHECK(text.str().find("inputs:diffuseColor.connect") != std::string::npos);+ f.close();+ CHECK(!reg.execute(doc, "export_ply", {{"path", tempPath("no_such_dir_sf/x/y.ply")}}).ok);+ std::filesystem::remove(plain);+ std::filesystem::remove(painted);+ std::filesystem::remove(usd);+}++TEST(polypaint_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"}) {+ CHECK(reg.find(name) != nullptr);+ CHECK(schema.find(std::string("\"") + name + "\"") != std::string::npos);+ }+}++TEST(matcap_builtin_materials) {+ CHECK(matcapCount() >= 4 && matcapCount() <= 8);+ for (int i = 0; i < matcapCount(); ++i) {+ CHECK(std::string(matcapName(i)).size() > 0);+ CHECK(findMatcap(matcapName(i)) == i);+ for (int j = 0; j < i; ++j) CHECK(std::string(matcapName(i)) != matcapName(j));+ }+ CHECK(findMatcap("red wax") >= 0 && findMatcap("RedWax") == findMatcap("Red Wax"));+ CHECK(findMatcap("chrome") >= 0 && findMatcap("unobtainium") == -1);+ CHECK(generateMatcap(-1).empty() && generateMatcap(matcapCount()).empty() && generateMatcap(0, 0).empty());++ const int size = 64;+ auto pixel = [&](const std::vector<uint8_t>& img, int i, int j) {+ const uint8_t* p = img.data() + (size_t(j) * size + size_t(i)) * 4;+ return glm::ivec4(p[0], p[1], p[2], p[3]);+ };+ const std::vector<uint8_t> wax = generateMatcap(findMatcap("Red Wax"), size);+ CHECK(wax.size() == size_t(size) * size * 4);+ const glm::ivec4 c = pixel(wax, size / 2, size / 2);+ CHECK(c.x > c.y + 40 && c.x > c.z + 40 && c.w == 255); // red+ // Lit from the upper left: that side of the sphere is brighter than the lower right (rows are bottom-up).+ const glm::ivec4 lit = pixel(wax, size / 4, size * 3 / 4), dark = pixel(wax, size * 3 / 4, size / 4);+ CHECK(lit.x > dark.x);+ // Corners repeat the rim instead of being undefined.+ CHECK(pixel(wax, 0, 0).w == 255);+ const std::vector<uint8_t> chrome = generateMatcap(findMatcap("Chrome"), size);+ CHECK(chrome != wax);+ const glm::ivec4 cc = pixel(chrome, size / 2, size / 2);+ CHECK(std::abs(cc.x - cc.z) < 40); // neutral metal+ // Deterministic.+ CHECK(generateMatcap(findMatcap("Chrome"), size) == chrome);+}