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
Keep Masked for Voxel Remesh, Decimate and QRemesh (#43): masked triangles stay bit-identical; the remeshers cut the new surface around them and bridge each edge loop watertight; unit and UI tests
islandmed36393a05d764
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1d6b2ac4..aa8098d8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,9 @@ All notable changes to SculptForge are listed here. The format follows**From file...** (`.obj`, `.ply`, `.glb`), dragged onto the surface like the shapes: centred, sized by the drag,its up axis along the normal, turned by the drag and mirrored by symmetry, one undo step(`insert_mesh subtool=<name>|file=<path>`).+- **Keep Masked** for Voxel Remesh, Decimate and QRemesh (#43, off by default): masked areas keep their+ triangles exactly; the rest is rebuilt and, for the remeshers, joined to them along the mask's edge with a+ strip of triangles so the model stays closed (`keep_masked=true` on `remesh`, `decimate`, `qremesh`).- SubTool thumbnails in the SubTool list (#43), drawn from each SubTool's existing GPU buffers (no upload, themotion proxy on dense meshes), one per frame at most and only once a change has settled, never during a stroke.diff --git a/CMakeLists.txt b/CMakeLists.txtindex 9958320e..1118fa28 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -103,6 +103,7 @@ add_library(sculptforge_core STATICthird_party/mikktspace/mikktspace.csrc/core/Vdm.cppsrc/core/Kelvinlet.cpp+ src/core/KeepMasked.cppsrc/core/ViewCapture.cppthird_party/tinyexr/tinyexr_impl.cppsrc/core/Matcap.cppdiff --git a/docs/guide/geometry.md b/docs/guide/geometry.mdindex 5cbfe73c..f817214a 100644--- a/docs/guide/geometry.md+++ b/docs/guide/geometry.md@@ -86,6 +86,11 @@ What happens to your data:progress bar and **Cancel**. Off: the texture is dropped. See [Texture painting](texture-painting.md#uvs-and-geometry).- Separate pieces that don't touch stay separate pieces; overlapping ones are merged.- The new surface is made of even quads (the original's quads are rebuilt, not kept).+- **Keep Masked** (off by default): masked areas keep their triangles exactly, detail included, and only the rest+ is remeshed. The new surface is joined to the masked area along the mask's edge by a narrow strip of triangles,+ so the model stays closed. A triangle counts as masked when all three of its corners are at least half masked.+ If the mask's edge is too ragged or too thin to join up at this resolution, the status line says so and nothing+ changes (smooth or grow the mask, or raise the resolution). Command: `remesh keep_masked=true`.To remesh several SubTools into one, first combine them with **Merge visible...** or **Merge down...** in[SubTools](subtools.md#merge-subtools).@@ -112,6 +117,9 @@ Decimation keeps open borders in place, and because it only removes vertices, evexact sculpt layer offsets, mask and polypaint. Polygroups, hidden flags and UVs survive on the remainingtriangles. The result is all triangles: quads are not kept.+With **Keep Masked** (under the button, off by default) masked vertices are never removed, so masked areas keep+their triangles exactly and only the rest is decimated (`decimate keep_masked=true`).+Use it to make a lighter version of a finished sculpt for export, 3D printing or a review, or to bring a densescan down to something you can work with.diff --git a/docs/guide/retopology.md b/docs/guide/retopology.mdindex 89e2f71b..ecaac1ec 100644--- a/docs/guide/retopology.md+++ b/docs/guide/retopology.md@@ -40,6 +40,7 @@ Both steps are single undo steps (<kbd>Ctrl</kbd>+<kbd>Z</kbd>).| **Use Polypaint** | Paint where you want density: red areas get up to four times the quads, blue areas down to a quarter, white areas are unchanged || **Symmetry** | Remesh one half and mirror it, welded on the seam, for exactly symmetric topology (on by default). It mirrors on the axis chosen in the **Transform** palette (X if none), across the model's own middle plane: the world's centre plane when the model is symmetric about it, otherwise the plane through the model's middle, so a model moved away from the centre works too. A model that isn't mirror-symmetric is remeshed whole instead, and the status line says "Symmetry off: the model isn't mirror-symmetric"; one that is nearly symmetric (a bump on one side) gets mirrored topology that follows each side's own surface || **Keep Original** | Keep the SubTool as it was, hidden, below the new one, ready for ProjectAll. Off: the SubTool is replaced, as in ZBrush (undo brings it back) |+| **Keep Masked** | Masked areas keep their triangles exactly, as a fixed piece: only the unmasked part is remeshed (the target counts its quads), and it's joined to the masked part along the mask's edge with a strip of triangles, so the model stays closed. If the mask's edge can't be joined up, the status line says so and nothing changes (off by default; `qremesh keep_masked=true`) || **Keep Texture** | Shown when the SubTool has a painted texture (on by default): Auto UV the result and project the texture onto it. Off: the texture is dropped || **QRemesh Guides** | Picks the guides brush: draw curves on the model for the edge loops to follow. See [QRemesh Guides](#qremesh-guides) || **Delete Last** / **Clear** | Delete the last guide curve drawn (with its mirror copies), or all of them |diff --git a/src/app/App.h b/src/app/App.hindex a38b8d9d..65d48a01 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -406,6 +406,11 @@ private:std::string comfyWorkflowError_;bool remeshGenerated_ = true;int voxelResolution_ = 200;+ bool voxelKeepMasked_ = false; // Voxel Remesh's Keep Masked (#43)+ static constexpr const char* kKeepMaskedHelp =+ "Masked areas keep their triangles exactly as they are (their detail too); only the rest is rebuilt, and "+ "it's joined to them along the mask's edge so the model stays closed. Mask what to keep first (Ctrl). "+ "If the mask's edge is too ragged to join up, the status line says so and nothing changes.";bool keepTexture_ = true; // Keep Texture: remeshes carry a painted texture over (core/TextureTransfer.h)int remeshResolution_ = 256;std::future<ai::GeneratorResult> pendingGenerator_;@@ -764,6 +769,7 @@ private:uint32_t subtool = 0;size_t triangles = 0;int resolution = 200;+ bool keepMasked = false;};std::unique_ptr<VoxelRemeshJob> voxelRemesh_;void pollQRemesh();@@ -786,6 +792,7 @@ private:int target = 5000;float adaptive = 0.5f;bool keepGroups = false, detectEdges = true, usePolypaint = false, symmetry = true, keepOriginal = false;+ bool keepMasked = false; // Keep Masked (#43): the masked area stays as it is (core/KeepMasked.h)float projectDist = 0.02f;int projectBlur = 0;bool projectMean = false, projectGeometry = true, projectPolypaint = true;@@ -1093,6 +1100,7 @@ private:float dropdownX_ = 0.0f;bool openDropdown_ = false;float decimateRatio_ = 0.5f;+ bool decimateKeepMasked_ = false; // Decimate's Keep Masked (#43)std::string flashPalette_; // a tray palette that was clicked in the bar: scrolled to and flasheddouble flashStart_ = 0.0;std::vector<std::string> collapsedPalettes_; // tray palettes showing only their headerdiff --git a/src/app/Palettes.cpp b/src/app/Palettes.cppindex 6c6d88ba..a9f645a3 100644--- a/src/app/Palettes.cpp+++ b/src/app/Palettes.cpp@@ -585,13 +585,22 @@ void App::drawPalette_Tool() {drawGeometrySection();actionRow(*this, {"geometry.subdivide"});const float half = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f;- if (ImGui::Button("Decimate", ImVec2(half, 0))) runCommand("decimate", {{"ratio", double(decimateRatio_)}});+ if (ImGui::Button("Decimate", ImVec2(half, 0))) {+ Args args{{"ratio", double(decimateRatio_)}};+ if (decimateKeepMasked_) args["keep_masked"] = true;+ runCommand("decimate", args);+ }ui::HelpText("Decimate", nullptr, "Reduce the triangle count while keeping the shape. Sculpt layers are kept.","Tool > Geometry");ImGui::SameLine();ImGui::SetNextItemWidth(-1);ui::SliderInside("##decimate", &decimateRatio_, 0.05f, 0.95f, "Keep %.2f");ui::HelpText("Keep", nullptr, "Fraction of the triangles Decimate keeps.", "Tool > Geometry");+ ImGui::Checkbox("Keep Masked##decimate", &decimateKeepMasked_);+ ui::HelpText("Keep Masked", nullptr,+ "Decimate leaves masked vertices where they are, so masked areas keep their triangles exactly; "+ "the rest is decimated around them.",+ "Tool > Geometry");Demo::pushScope("QRemesh");drawQRemeshContents(); // quad retopology (PanelRetopo.cpp)Demo::popScope();@@ -625,8 +634,13 @@ void App::drawPalette_Tool() {if (voxelRemesh_) {if (ImGui::Button("Cancel##voxelremesh", ImVec2(half, 0))) voxelRemesh_->cancel->store(true);ui::HelpText("Cancel", nullptr, "Stop the remesh; the SubTool stays as it is.", "Tool > Remesh");- } else if (hasTexture(doc_.mesh)) {- drawKeepTextureCheckbox("Keep Texture##remesh", "Tool > Remesh"); // only for a painted SubTool+ } else {+ ImGui::Checkbox("Keep Masked##remesh", &voxelKeepMasked_);+ ui::HelpText("Keep Masked", nullptr, kKeepMaskedHelp, "Tool > Remesh");+ if (hasTexture(doc_.mesh)) {+ ImGui::SameLine();+ drawKeepTextureCheckbox("Keep Texture##remesh", "Tool > Remesh"); // only for a painted SubTool+ }}}if (subpalette("tool.deformation", "Deformation")) {diff --git a/src/app/PanelRetopo.cpp b/src/app/PanelRetopo.cppindex 4eb53654..3a62dd90 100644--- a/src/app/PanelRetopo.cpp+++ b/src/app/PanelRetopo.cpp@@ -11,6 +11,7 @@#include "app/Palettes.h"#include "app/Ui.h"+#include "core/KeepMasked.h"#include "core/TextureTransfer.h"#include "core/Voxel.h"@@ -99,9 +100,29 @@ void App::registerRetopoUiActions() {"project_all");}+namespace {++// Keep Masked (#43): the triangles to keep, or empty when it's off or nothing is masked. `allMasked`: there's+// nothing left to remesh.+std::vector<uint8_t> keptForRemesh(const Mesh& mesh, bool keepMasked, bool& allMasked) {+ allMasked = false;+ std::vector<uint8_t> keep = keepMasked ? keepMaskedTriangles(mesh) : std::vector<uint8_t>();+ if (std::find(keep.begin(), keep.end(), 1) == keep.end()) return {};+ allMasked = std::find(keep.begin(), keep.end(), 0) == keep.end();+ return keep;+}++} // namespace+void App::startQRemesh() {if (qremesh_ || doc_.mesh.triangleCount() == 0) return;if (doc_.sculptor.strokeActive()) endStroke();+ bool allMasked = false;+ std::vector<uint8_t> keep = keptForRemesh(doc_.mesh, retopo_.keepMasked, allMasked);+ if (allMasked) {+ status_ = "QRemesh: everything is masked, so nothing would change (Keep Masked)";+ return;+ }QRemeshOptions o;o.method = retopo_.method == 1 ? QRemeshMethod::Legacy : QRemeshMethod::V2;o.targetQuads = std::clamp(retopo_.target, 16, 2'000'000);@@ -129,6 +150,7 @@ void App::startQRemesh() {if (o.usePolypaint) job->args["use_polypaint"] = true;if (o.symmetryAxis >= 0) job->args["symmetry"] = std::string(1, char('x' + o.symmetryAxis));if (job->keepOriginal) job->args["keep_original"] = true;+ if (!keep.empty()) job->args["keep_masked"] = true;if (!o.guides.empty() && std::abs(curvesStrength_ - 50.0f) > 0.01f) job->args["curves_strength"] = double(curvesStrength_);const bool keepTexture = keepTexture_;if (!keepTexture && hasTexture(doc_.mesh)) job->args["keep_texture"] = false;@@ -138,13 +160,20 @@ void App::startQRemesh() {job->done = promise.get_future();std::thread([promise = std::move(promise), source = std::make_shared<Mesh>(doc_.mesh), o, progress = job->progress,cancel = job->cancel, result = job->result, stats = job->stats, error = job->error,- note = job->textureNote, keepTexture]() mutable {+ note = job->textureNote, keepTexture, keep = std::move(keep)]() mutable {// With a texture to keep, QRemesh takes the first 80% of the bar and Auto UV + transfer the rest.const float share = hasTexture(*source) && keepTexture ? 0.8f : 1.0f;- bool ok = qremesh(*source, o, *result, *error, [&](float f) {+ // Keep Masked: the unmasked part is remeshed on its own, then the masked part is joined back to it.+ bool ok = qremesh(keep.empty() ? *source : unmaskedPart(*source, keep), o, *result, *error, [&](float f) {progress->store(f * share);return !cancel->load();}, stats.get());+ if (ok && !keep.empty()) {+ Mesh stitched;+ ok = stitchKeptTriangles(*source, keep, *result, stitched, *error);+ if (ok) *result = std::move(stitched);+ else *error = "QRemesh (Keep Masked): " + *error;+ }if (ok) *note = carryTextureNote(*source, *result, keepTexture, [&](float f) {progress->store(share + (1.0f - share) * f);return !cancel->load();@@ -163,6 +192,7 @@ void App::startQRemesh() {void App::startVoxelRemesh() {if (voxelRemesh_) return;Args args{{"resolution", double(voxelResolution_)}};+ if (voxelKeepMasked_) args["keep_masked"] = true;if (!hasTexture(doc_.mesh) || !keepTexture_) {if (hasTexture(doc_.mesh)) args["keep_texture"] = false; // Keep Texture offrunCommand("remesh", args);@@ -179,14 +209,27 @@ void App::startVoxelRemesh() {job->subtool = doc_.activeSubtoolInfo().id;job->triangles = doc_.mesh.triangleCount();job->resolution = std::clamp(voxelResolution_, 32, 512);+ bool allMasked = false;+ std::vector<uint8_t> keep = keptForRemesh(doc_.mesh, voxelKeepMasked_, allMasked);+ if (allMasked) {+ status_ = "Remesh: everything is masked, so nothing would change (Keep Masked)";+ return;+ }+ job->keepMasked = !keep.empty();std::promise<bool> promise;job->done = promise.get_future();std::thread([promise = std::move(promise), source = std::make_shared<Mesh>(doc_.mesh), res = job->resolution,progress = job->progress, cancel = job->cancel, result = job->result, error = job->error,- note = job->note]() mutable {+ note = job->note, keep = std::move(keep)]() mutable {progress->store(0.02f);*result = voxelRemesh(*source, res, error.get());bool ok = result->triangleCount() > 0;+ if (ok && !keep.empty()) { // Keep Masked: the masked part goes back in, joined to the new surface+ Mesh stitched;+ ok = stitchKeptTriangles(*source, keep, *result, stitched, *error);+ if (ok) *result = std::move(stitched);+ else *error = "Remesh (Keep Masked): " + *error;+ }progress->store(0.15f);if (ok) *note = carryTextureNote(*source, *result, true, [&](float f) {progress->store(0.15f + 0.85f * f);@@ -231,7 +274,9 @@ void App::pollVoxelRemesh() {playingLayer_ = -1;uvLinesKey_ = 0;updateTitle();- consoleEcho("remesh", {{"resolution", double(job->resolution)}}, r);+ Args echo{{"resolution", double(job->resolution)}};+ if (job->keepMasked) echo["keep_masked"] = true;+ consoleEcho("remesh", echo, r);}void App::pollQRemesh() {@@ -355,11 +400,12 @@ void App::drawQRemeshContents() {"Keep the SubTool as it was, hidden, right below the new one (\"<name> Original\"), ready to ""ProjectAll its detail back. Off: replace it, as ZBrush does (undo brings it back).",kQRemeshPath);- if (hasTexture(doc_.mesh)) { // only matters for a painted SubTool- ImGui::SameLine();- ImGui::SetCursorPosX(x0 + half + style.ItemSpacing.x); // the right column, inside the section indent+ ImGui::SameLine();+ ImGui::SetCursorPosX(x0 + half + style.ItemSpacing.x); // the right column, inside the section indent+ ImGui::Checkbox("Keep Masked##qremesh", &retopo_.keepMasked);+ ui::HelpText("Keep Masked", nullptr, kKeepMaskedHelp, kQRemeshPath);+ if (hasTexture(doc_.mesh)) // only matters for a painted SubTooldrawKeepTextureCheckbox("Keep Texture##qremesh", kQRemeshPath);- }drawQRemeshGuideControls();drawQRemeshReport();}diff --git a/src/core/Commands.cpp b/src/core/Commands.cppindex ec2f48f4..de3ea564 100644--- a/src/core/Commands.cpp+++ b/src/core/Commands.cpp@@ -8,6 +8,7 @@#include "core/BrushAlpha.h"#include "core/BrushLibrary.h"#include "core/Decimate.h"+#include "core/KeepMasked.h"#include "core/Dyntopo.h"#include "core/EnginePresets.h"#include "core/ExtractMirror.h"@@ -225,11 +226,22 @@ CommandRegistry::CommandRegistry() {"kept (new Auto UVs, colour projected from the old surface) unless keep_texture=false.",{{"resolution", T::Number, "Voxels across the longest side (32-512). Default 200; higher keeps more detail.", false},{"keep_texture", T::Bool, "Keep a painted texture: Auto UV the result and project the texture onto it. "- "Default true.", false}},+ "Default true.", false},+ {"keep_masked", T::Bool, "Keep masked: masked areas keep their triangles exactly; the rest is remeshed and "+ "joined to them watertight. Default false.", false}},[](Document& doc, const Args& a) -> CommandResult {std::string err;+ const std::vector<uint8_t> keep = argBool(a, "keep_masked", false) ? keepMaskedTriangles(doc.mesh) : std::vector<uint8_t>();+ const bool keeping = std::find(keep.begin(), keep.end(), 1) != keep.end();+ if (keeping && std::find(keep.begin(), keep.end(), 0) == keep.end())+ return {false, "Remesh: everything is masked, so nothing would change"};Mesh m = voxelRemesh(doc.mesh, std::clamp(int(argNumber(a, "resolution", 200)), 32, 512), &err);if (m.triangleCount() == 0) return {false, err};+ if (keeping) {+ Mesh stitched;+ if (!stitchKeptTriangles(doc.mesh, keep, m, stitched, err)) return {false, "Remesh (Keep masked): " + err};+ m = std::move(stitched);+ }const std::string texture = carryTextureNote(doc.mesh, m, argBool(a, "keep_texture", true));doc.replaceMeshUndoable(std::move(m), "Remesh");return {true, "Remeshed to " + std::to_string(doc.mesh.triangleCount()) + " triangles" + texture};@@ -389,13 +401,15 @@ CommandRegistry::CommandRegistry() {add({"decimate","Reduce triangle count while preserving shape (quadric edge collapse). Sculpt layers are kept.",{{"ratio", T::Number, "Fraction of triangles to keep (0.01-1). Default 0.5.", false},- {"triangles", T::Number, "Exact target triangle count (overrides ratio).", false}},+ {"triangles", T::Number, "Exact target triangle count (overrides ratio).", false},+ {"keep_masked", T::Bool, "Keep masked: masked vertices aren't moved or removed, so masked areas keep their "+ "triangles exactly. Default false.", false}},[](Document& doc, const Args& a) -> CommandResult {size_t target = a.contains("triangles")? size_t(std::max(4.0, argNumber(a, "triangles", 4))): size_t(double(doc.mesh.triangleCount()) *std::clamp(argNumber(a, "ratio", 0.5), 0.01, 1.0));- doc.replaceMeshUndoable(decimate(doc.mesh, target), "Decimate");+ doc.replaceMeshUndoable(decimate(doc.mesh, target, argBool(a, "keep_masked", false)), "Decimate");return {true, "Decimated to " + std::to_string(doc.mesh.triangleCount()) + " triangles"};}});diff --git a/src/core/Decimate.cpp b/src/core/Decimate.cppindex 88274b34..9dac6779 100644--- a/src/core/Decimate.cpp+++ b/src/core/Decimate.cpp@@ -52,7 +52,7 @@ uint64_t edgeKey(uint32_t a, uint32_t b) {} // namespace-Mesh decimate(const Mesh& src, size_t targetTriangles) {+Mesh decimate(const Mesh& src, size_t targetTriangles, bool keepMasked) {const size_t nv = src.vertexCount();const size_t nt = src.triangleCount();targetTriangles = std::max<size_t>(targetTriangles, 4);@@ -81,6 +81,12 @@ Mesh decimate(const Mesh& src, size_t targetTriangles) {}}+ // Keep masked (#43): masked vertices are never collapsed away, so they and the triangles between them stay+ // exactly as they were (a collapse keeps the other endpoint where it is).+ std::vector<char> locked(nv, 0);+ if (keepMasked && src.hasMask())+ for (size_t v = 0; v < nv; ++v) locked[v] = src.mask[v] >= kKeepMaskedThreshold;+// Area-weighted plane quadrics.std::vector<Quadric> Q(nv);std::vector<glm::dvec3> faceN(nt);@@ -149,7 +155,7 @@ Mesh decimate(const Mesh& src, size_t targetTriangles) {heap.pop();const uint32_t u = c.from, v = c.to;if (!vAlive[u] || !vAlive[v] || version[u] != c.fromVersion || version[v] != c.toVersion) continue;- if (uvSeam[u]) continue;+ if (uvSeam[u] || locked[u]) continue;shared.clear();for (uint32_t f : vFaces[u]) {diff --git a/src/core/Decimate.h b/src/core/Decimate.hindex 219283bd..7c0b5fac 100644--- a/src/core/Decimate.h+++ b/src/core/Decimate.h@@ -2,6 +2,7 @@// SPDX-License-Identifier: GPL-3.0-or-later#pragma once+#include "core/KeepMasked.h"#include "core/Mesh.h"#include <vector>@@ -14,8 +15,9 @@ namespace sf {// and sculpt layers / blend shapes, mask and colours carry over exactly;// surviving triangles keep their polygroup and hidden flag, and corner UVs// follow the kept vertex. A decimated result is all triangles (quad pairs are-// dropped).-Mesh decimate(const Mesh& src, size_t targetTriangles);+// dropped). keepMasked: masked vertices (mask >= kKeepMaskedThreshold) are never collapsed, so they and the+// triangles between them come through unchanged (#43).+Mesh decimate(const Mesh& src, size_t targetTriangles, bool keepMasked = false);// LOD chain: lods[0] is a copy of `src`, each following level has// `ratio` times the triangles of the previous one.diff --git a/src/core/KeepMasked.cpp b/src/core/KeepMasked.cppnew file mode 100644index 00000000..f16efdbf--- /dev/null+++ b/src/core/KeepMasked.cpp@@ -0,0 +1,349 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/KeepMasked.h"++#include "core/Polygroups.h"+#include "core/QRemesh.h"+#include "core/SubTools.h"++#include <algorithm>+#include <limits>+#include <map>+#include <unordered_map>+#include <unordered_set>++namespace sf {++std::vector<uint8_t> keepMaskedTriangles(const Mesh& mesh) {+ if (!mesh.hasMask() || mesh.mask.size() != mesh.vertexCount()) return {};+ std::vector<uint8_t> keep(mesh.triangleCount(), 0);+ for (size_t t = 0; t < keep.size(); ++t) {+ const glm::uvec3& tri = mesh.triangles[t];+ keep[t] = mesh.mask[tri.x] >= kKeepMaskedThreshold && mesh.mask[tri.y] >= kKeepMaskedThreshold &&+ mesh.mask[tri.z] >= kKeepMaskedThreshold;+ }+ return keep;+}++Mesh unmaskedPart(const Mesh& source, const std::vector<uint8_t>& keep) {+ std::vector<uint8_t> rest(source.triangleCount(), 1);+ for (size_t t = 0; t < rest.size() && t < keep.size(); ++t) rest[t] = !keep[t];+ return extractTriangles(source, rest);+}++namespace {++uint64_t directedKey(uint32_t a, uint32_t b) { return (uint64_t(a) << 32) | b; }++// The closed loops of open edges of `tris`, each in the direction its triangle runs along it (the triangle on+// its left). False when that isn't a set of simple loops: an edge used twice the same way, or a vertex where+// two loops meet.+bool boundaryLoops(const std::vector<glm::uvec3>& tris, std::vector<std::vector<uint32_t>>& loops) {+ loops.clear();+ std::unordered_map<uint64_t, int> used;+ used.reserve(tris.size() * 3);+ for (const glm::uvec3& t : tris)+ for (int e = 0; e < 3; ++e)+ if (++used[directedKey(t[e], t[(e + 1) % 3])] > 1) return false;+ std::unordered_map<uint32_t, uint32_t> next;+ std::unordered_set<uint32_t> hasIn;+ for (const auto& [key, n] : used) {+ const uint32_t a = uint32_t(key >> 32), b = uint32_t(key & 0xffffffffu);+ if (used.count(directedKey(b, a))) continue;+ if (!next.emplace(a, b).second || !hasIn.insert(b).second) return false;+ }+ std::unordered_set<uint32_t> seen;+ std::vector<uint32_t> starts;+ for (const auto& [a, b] : next) starts.push_back(a);+ std::sort(starts.begin(), starts.end()); // the same loops in the same order every run+ for (uint32_t start : starts) {+ if (seen.count(start)) continue;+ std::vector<uint32_t> loop;+ uint32_t v = start;+ do {+ if (!seen.insert(v).second) return false;+ loop.push_back(v);+ const auto it = next.find(v);+ if (it == next.end()) return false;+ v = it->second;+ } while (v != start);+ if (loop.size() < 3) return false;+ loops.push_back(std::move(loop));+ }+ return true;+}++// For each point in `query`, the value of the nearest point in `points` (transferVertexAttributes' search,+// with the value carried in the colour's red channel: whole numbers come through exactly).+std::vector<float> nearestValues(std::vector<glm::vec3> points, const std::vector<float>& values, std::vector<glm::vec3> query) {+ Mesh from, to;+ from.positions = std::move(points);+ from.colors.reserve(values.size());+ for (float v : values) from.colors.emplace_back(v, 0.0f, 0.0f);+ to.positions = std::move(query);+ transferVertexAttributes(from, to);+ std::vector<float> out(to.positions.size(), -1.0f);+ for (size_t i = 0; i < out.size() && i < to.colors.size(); ++i) out[i] = to.colors[i].x;+ return out;+}++// The kept triangles as their own plain mesh (no layers, levels, paint layers or texture), and which source+// vertex each of its vertices is.+Mesh keptPiece(const Mesh& source, const std::vector<uint8_t>& keep, std::vector<uint32_t>& sourceVertex) {+ const size_t nt = source.triangleCount();+ std::vector<uint32_t> remap(source.vertexCount(), ~0u), triRemap(nt, ~0u);+ sourceVertex.clear();+ Mesh k;+ for (uint32_t t = 0; t < nt; ++t) {+ if (!keep[t]) continue;+ glm::uvec3 tri = source.triangles[t];+ for (int c = 0; c < 3; ++c) {+ uint32_t& r = remap[tri[c]];+ if (r == ~0u) {+ r = uint32_t(sourceVertex.size());+ sourceVertex.push_back(tri[c]);+ }+ tri[c] = r;+ }+ triRemap[t] = uint32_t(k.triangles.size());+ k.triangles.push_back(tri);+ }+ for (uint32_t v : sourceVertex) k.positions.push_back(source.positions[v]);+ if (source.mask.size() == source.vertexCount())+ for (uint32_t v : sourceVertex) k.mask.push_back(source.mask[v]);+ if (source.colors.size() == source.vertexCount())+ for (uint32_t v : sourceVertex) k.colors.push_back(source.colors[v]);+ for (uint32_t t = 0; t < nt; ++t) {+ if (!keep[t]) continue;+ if (source.polygroups.size() == nt) k.polygroups.push_back(source.polygroups[t]);+ if (source.hidden.size() == nt) k.hidden.push_back(source.hidden[t]);+ if (source.uvs.size() == nt * 3)+ for (int c = 0; c < 3; ++c) k.uvs.push_back(source.uvs[size_t(t) * 3 + size_t(c)]);+ if (source.quadPartners.size() == nt) {+ const uint32_t u = source.quadPartners[t];+ k.quadPartners.push_back(u < nt && triRemap[u] != ~0u ? triRemap[u] : Mesh::kNoQuad);+ }+ }+ k.sanitizeAttributes();+ return k;+}++} // namespace++bool stitchKeptTriangles(const Mesh& source, const std::vector<uint8_t>& keep, const Mesh& remeshed, Mesh& out,+ std::string& error) {+ const size_t nt = source.triangleCount();+ if (keep.size() != nt || std::find(keep.begin(), keep.end(), 1) == keep.end()) {+ error = "Nothing is masked";+ return false;+ }+ std::vector<uint32_t> keptSource;+ const Mesh kept = keptPiece(source, keep, keptSource);++ // The masked area's edge loops (in the kept piece's numbering). A loop made only of the source's own open+ // edges is a hole the source already had: it stays open. One partly on them can't be joined up.+ std::vector<std::vector<uint32_t>> keptLoops;+ if (!boundaryLoops(kept.triangles, keptLoops)) {+ error = "The masked area's edge touches itself; smooth or grow the mask a little";+ return false;+ }+ {+ std::unordered_set<uint64_t> sourceEdges;+ for (const glm::uvec3& t : source.triangles)+ for (int e = 0; e < 3; ++e) sourceEdges.insert(directedKey(t[e], t[(e + 1) % 3]));+ std::vector<std::vector<uint32_t>> inner;+ for (auto& loop : keptLoops) {+ size_t open = 0;+ for (size_t i = 0; i < loop.size(); ++i) {+ const uint32_t a = keptSource[loop[i]], b = keptSource[loop[(i + 1) % loop.size()]];+ open += !sourceEdges.count(directedKey(b, a));+ }+ if (open == loop.size()) continue;+ if (open > 0) {+ error = "The masked area reaches an open edge of the mesh";+ return false;+ }+ inner.push_back(std::move(loop));+ }+ keptLoops = std::move(inner);+ }++ // Cut the new surface away over the masked area and next to it: every new triangle with a corner whose+ // nearest source vertex belongs to a kept triangle (so the cut lies just outside the kept piece), and the+ // other half of any quad cut in two.+ std::vector<float> inKept(source.vertexCount(), 0.0f);+ for (uint32_t v : keptSource) inKept[v] = 1.0f;+ const std::vector<float> near = nearestValues(source.positions, inKept, remeshed.positions);+ const size_t rt = remeshed.triangleCount();+ std::vector<uint8_t> stay(rt, 1);+ for (size_t t = 0; t < rt; ++t) {+ const glm::uvec3& tri = remeshed.triangles[t];+ if (near[tri.x] > 0.5f || near[tri.y] > 0.5f || near[tri.z] > 0.5f) stay[t] = 0;+ }+ auto dropHalfQuads = [&] {+ if (remeshed.quadPartners.size() != rt) return;+ for (size_t t = 0; t < rt; ++t) {+ const uint32_t u = remeshed.quadPartners[t];+ if (u < rt && !stay[u]) stay[t] = 0;+ }+ };+ dropHalfQuads();+ // Where the cut leaves two open loops meeting at a vertex, cut the triangles around it too.+ for (int pass = 0; pass < 8; ++pass) {+ std::unordered_map<uint64_t, int> used;+ for (size_t t = 0; t < rt; ++t)+ if (stay[t])+ for (int e = 0; e < 3; ++e) ++used[directedKey(remeshed.triangles[t][e], remeshed.triangles[t][(e + 1) % 3])];+ std::unordered_map<uint32_t, int> starts;+ for (const auto& [key, n] : used)+ if (!used.count(directedKey(uint32_t(key & 0xffffffffu), uint32_t(key >> 32)))) ++starts[uint32_t(key >> 32)];+ std::unordered_set<uint32_t> pinch;+ for (const auto& [v, n] : starts)+ if (n > 1) pinch.insert(v);+ if (pinch.empty()) break;+ for (size_t t = 0; t < rt; ++t) {+ const glm::uvec3& tri = remeshed.triangles[t];+ if (pinch.count(tri.x) || pinch.count(tri.y) || pinch.count(tri.z)) stay[t] = 0;+ }+ dropHalfQuads();+ }++ // Match each of the kept piece's loops with the cut's loop around it (the cut's loop whose points are+ // mostly nearest to it). A small leftover piece of the new surface with a loop nothing matches (a sliver+ // inside the masked area) is dropped; anything else that doesn't match up is reported.+ Mesh rest;+ std::vector<std::vector<uint32_t>> restLoops;+ std::vector<int> match(keptLoops.size(), -1);+ for (int attempt = 0; attempt < 2; ++attempt) {+ rest = extractTriangles(remeshed, stay);+ rest.layers.clear();+ rest.base.clear();+ if (!boundaryLoops(rest.triangles, restLoops)) {+ error = "Couldn't cut the remeshed surface cleanly around the mask; try a higher resolution";+ return false;+ }+ std::vector<glm::vec3> keptPoints, restPoints;+ std::vector<float> keptLoopId;+ for (size_t l = 0; l < keptLoops.size(); ++l)+ for (uint32_t v : keptLoops[l]) {+ keptPoints.push_back(kept.positions[v]);+ keptLoopId.push_back(float(l));+ }+ for (const auto& loop : restLoops)+ for (uint32_t v : loop) restPoints.push_back(rest.positions[v]);+ const std::vector<float> nearestLoop =+ keptPoints.empty() ? std::vector<float>(restPoints.size(), -1.0f) : nearestValues(keptPoints, keptLoopId, restPoints);+ std::vector<int> votedFor(restLoops.size(), -1);+ size_t at = 0;+ for (size_t r = 0; r < restLoops.size(); ++r) {+ std::map<int, size_t> votes;+ for (size_t i = 0; i < restLoops[r].size(); ++i) ++votes[int(nearestLoop[at++])];+ size_t best = 0;+ for (const auto& [id, n] : votes)+ if (id >= 0 && n > best) {+ best = n;+ votedFor[r] = id;+ }+ }+ std::fill(match.begin(), match.end(), -1);+ for (size_t r = 0; r < restLoops.size(); ++r) {+ const int k = votedFor[r];+ if (k >= 0 && (match[size_t(k)] < 0 || restLoops[r].size() > restLoops[size_t(match[size_t(k)])].size()))+ match[size_t(k)] = int(r);+ }+ std::vector<uint8_t> matched(restLoops.size(), 0);+ for (int r : match)+ if (r >= 0) matched[size_t(r)] = 1;+ if (std::find(match.begin(), match.end(), -1) != match.end()) {+ error = "Part of the mask is too thin for this resolution; grow the mask or raise the resolution";+ return false;+ }+ if (std::find(matched.begin(), matched.end(), 0) == matched.end()) break;+ if (attempt == 1) {+ error = "Couldn't match the remeshed surface to the mask's edge; smooth the mask or raise the resolution";+ return false;+ }+ // Leftover loops: drop the small pieces of the new surface they belong to, then look again.+ std::vector<uint32_t> parent(rest.vertexCount());+ for (uint32_t v = 0; v < parent.size(); ++v) parent[v] = v;+ auto find = [&](uint32_t v) {+ while (parent[v] != v) v = parent[v] = parent[parent[v]];+ return v;+ };+ for (const glm::uvec3& t : rest.triangles) {+ parent[find(t.y)] = find(t.x);+ parent[find(t.z)] = find(t.x);+ }+ std::unordered_map<uint32_t, size_t> pieceTris;+ for (const glm::uvec3& t : rest.triangles) ++pieceTris[find(t.x)];+ std::unordered_set<uint32_t> neededPieces, strayPieces;+ for (size_t r = 0; r < restLoops.size(); ++r) (matched[r] ? neededPieces : strayPieces).insert(find(restLoops[r][0]));+ for (uint32_t p : strayPieces)+ if (neededPieces.count(p) || pieceTris[p] * 10 > rest.triangleCount()) {+ error = "Couldn't match the remeshed surface to the mask's edge; smooth the mask or raise the resolution";+ return false;+ }+ // Map the stray pieces back to the remeshed triangles (extractTriangles keeps the order).+ size_t r = 0;+ for (size_t t = 0; t < rt; ++t)+ if (stay[t] && strayPieces.count(find(rest.triangles[r++].x))) stay[t] = 0;+ }++ Mesh merged = mergeMeshes({&kept, &rest});+ const uint32_t offset = uint32_t(kept.vertexCount());+ const size_t keptTris = kept.triangleCount();+ const uint32_t bridgeGroup = merged.polygroups.size() > keptTris ? merged.polygroups[keptTris] : 0u;+ std::vector<glm::uvec3> bridge;+ for (size_t l = 0; l < keptLoops.size(); ++l) {+ const auto& P = keptLoops[l];+ const auto& Q = restLoops[size_t(match[l])];+ // The cut's loop runs the other way round the gap: walk it backwards from its point nearest P's start.+ size_t j0 = 0;+ float bestD = std::numeric_limits<float>::max();+ for (size_t j = 0; j < Q.size(); ++j) {+ const float d = glm::distance(kept.positions[P[0]], rest.positions[Q[j]]);+ if (d < bestD) {+ bestD = d;+ j0 = j;+ }+ }+ const size_t n = P.size(), m = Q.size();+ auto p = [&](size_t i) { return P[i % n]; };+ auto s = [&](size_t k) { return Q[(j0 + m - (k % m)) % m] + offset; };+ auto pos = [&](uint32_t v) { return merged.positions[v]; };+ // Zip the two loops together, each step taking the shorter new diagonal. Every triangle runs along both+ // loops the opposite way to the surfaces they edge, so the result stays consistently wound.+ size_t i = 0, k = 0;+ while (i < n || k < m) {+ const bool advanceP =+ k >= m || (i < n && glm::distance(pos(p(i + 1)), pos(s(k))) <= glm::distance(pos(p(i)), pos(s(k + 1))));+ if (advanceP) {+ bridge.emplace_back(p(i + 1), p(i), s(k));+ ++i;+ } else {+ bridge.emplace_back(s(k), s(k + 1), p(i));+ ++k;+ }+ }+ }+ for (const glm::uvec3& t : bridge) {+ merged.triangles.push_back(t);+ if (!merged.polygroups.empty()) merged.polygroups.push_back(bridgeGroup);+ if (!merged.hidden.empty()) merged.hidden.push_back(0);+ if (!merged.uvs.empty()) merged.uvs.insert(merged.uvs.end(), 3, glm::vec2(0.0f));+ if (!merged.quadPartners.empty()) merged.quadPartners.push_back(Mesh::kNoQuad);+ }+ merged.sanitizeAttributes();+ merged.rebuildTopology();+ merged.recomputeAllNormals();++ const TopologyReport after = topologyReport(merged);+ if (!after.manifold() || (topologyReport(source).boundaryEdges == 0 && after.boundaryEdges != 0)) {+ error = "Couldn't join the masked area to the remeshed surface cleanly; smooth the mask or raise the resolution";+ return false;+ }+ out = std::move(merged);+ return true;+}++} // namespace sfdiff --git a/src/core/KeepMasked.h b/src/core/KeepMasked.hnew file mode 100644index 00000000..a76c52d6--- /dev/null+++ b/src/core/KeepMasked.h@@ -0,0 +1,36 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Keep masked (#43): Voxel Remesh, Decimate and QRemesh can leave the masked part of a mesh exactly as it was+// and rebuild only the rest. Decimate does it by never collapsing a masked vertex (core/Decimate.h); the+// remeshers rebuild the surface, then the masked triangles are put back in place of the new surface there and+// the two are joined by a strip of triangles along each edge of the masked area, so the result stays closed.+#pragma once++#include "core/Mesh.h"++#include <cstdint>+#include <string>+#include <vector>++namespace sf {++// A vertex counts as masked for Keep masked from this mask value on.+inline constexpr float kKeepMaskedThreshold = 0.5f;++// Per triangle: 1 when all three corners are masked (the triangles Keep masked keeps). Empty without a mask.+std::vector<uint8_t> keepMaskedTriangles(const Mesh& mesh);++// `source` without its kept triangles (keep[t] != 0): the open piece a remesher can rebuild on its own.+Mesh unmaskedPart(const Mesh& source, const std::vector<uint8_t>& keep);++// Puts the kept triangles of `source` (keep[t] != 0, positions, mask, paint, groups and UVs unchanged) into+// `remeshed` (a rebuild of the whole mesh or of its unmasked part): the remeshed surface over and next to+// them is cut away and each edge loop of the kept area is bridged to the cut's matching edge loop with a+// strip of triangles. Sculpt layers, levels and paint layers are dropped (the remeshers bake them). Fails,+// saying why, when the masked area's edges can't be matched up (for example a mask edge that touches+// itself, or detail finer than the remesh); `out` is then untouched.+bool stitchKeptTriangles(const Mesh& source, const std::vector<uint8_t>& keep, const Mesh& remeshed, Mesh& out,+ std::string& error);++} // namespace sfdiff --git a/src/core/RetopoCommands.cpp b/src/core/RetopoCommands.cppindex fdb49c8c..35281632 100644--- a/src/core/RetopoCommands.cpp+++ b/src/core/RetopoCommands.cpp@@ -4,6 +4,7 @@// qremesh and project_all: the scriptable side of Geometry > QRemesh and SubTool > Project (core/QRemesh.h,// core/Projection.h). The app runs QRemesh on a worker thread and applies the result with applyQRemesh.#include "core/Commands.h"+#include "core/KeepMasked.h"#include "core/Projection.h"#include "core/QRemesh.h"#include "core/TextureTransfer.h"@@ -115,9 +116,16 @@ void registerRetopoCommands(CommandRegistry& reg) {"runs along each. Default true.", false},{"curves_strength", T::Number, "Curves Strength 0-100: how far around each guide the edge flow follows ""it (0 = just the loop on the curve, 100 = about six quads to each side). "- "Default 50.", false}},+ "Default 50.", false},+ {"keep_masked", T::Bool, "Keep masked: masked areas keep their triangles exactly as a fixed piece; the "+ "rest is remeshed and joined to them watertight. Default false.", false}},[](Document& doc, const Args& a) -> CommandResult {if (doc.mesh.triangleCount() == 0) return {false, "QRemesh: the SubTool is empty"};+ const std::vector<uint8_t> keep =+ argBool(a, "keep_masked", false) ? keepMaskedTriangles(doc.mesh) : std::vector<uint8_t>();+ const bool keeping = std::find(keep.begin(), keep.end(), 1) != keep.end();+ if (keeping && std::find(keep.begin(), keep.end(), 0) == keep.end())+ return {false, "QRemesh: everything is masked, so nothing would change"};QRemeshOptions o;const std::string method = argString(a, "method");if (method == "legacy" || method == "Legacy") o.method = QRemeshMethod::Legacy;@@ -141,7 +149,12 @@ void registerRetopoCommands(CommandRegistry& reg) {Mesh out;std::string err;QRemeshStats st;- if (!qremesh(doc.mesh, o, out, err, {}, &st)) return {false, err};+ if (keeping) { // remesh the unmasked part on its own, then put the masked part back beside it+ if (!qremesh(unmaskedPart(doc.mesh, keep), o, out, err, {}, &st)) return {false, err};+ Mesh stitched;+ if (!stitchKeptTriangles(doc.mesh, keep, out, stitched, err)) return {false, "QRemesh (Keep masked): " + err};+ out = std::move(stitched);+ } else if (!qremesh(doc.mesh, o, out, err, {}, &st)) return {false, err};const std::string texture = carryTextureNote(doc.mesh, out, argBool(a, "keep_texture", true));return {true, applyQRemesh(doc, std::move(out), argBool(a, "keep_original", false), st) + texture};}});diff --git a/tests/test_keep_masked.cpp b/tests/test_keep_masked.cppnew file mode 100644index 00000000..98bbb6ba--- /dev/null+++ b/tests/test_keep_masked.cpp@@ -0,0 +1,154 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+// Keep masked (#43): Voxel Remesh, Decimate and QRemesh leave the masked area's triangles exactly as they were.+#include "TestHarness.h"++#include "core/Commands.h"+#include "core/Document.h"+#include "core/KeepMasked.h"+#include "core/QRemesh.h"++#include <cstdint>+#include <cstring>+#include <functional>+#include <set>+#include <tuple>++using namespace sf;++namespace {++using Bits = std::tuple<uint32_t, uint32_t, uint32_t>;+Bits bitsOf(const glm::vec3& p) {+ uint32_t x, y, z;+ std::memcpy(&x, &p.x, 4);+ std::memcpy(&y, &p.y, 4);+ std::memcpy(&z, &p.z, 4);+ return {x, y, z};+}++// A sphere masked where `masked` says, and the positions of the kept triangles' corners.+Document maskedSphere(const std::function<bool(const glm::vec3&)>& masked, std::set<Bits>& keptCorners) {+ Document doc;+ CommandRegistry reg;+ reg.execute(doc, "new_sphere", {{"subdivisions", 4.0}});+ auto& mask = doc.mesh.ensureMask();+ for (size_t v = 0; v < mask.size(); ++v) mask[v] = masked(doc.mesh.positions[v]) ? 1.0f : 0.0f;+ const std::vector<uint8_t> keep = keepMaskedTriangles(doc.mesh);+ for (size_t t = 0; t < keep.size(); ++t)+ if (keep[t])+ for (int c = 0; c < 3; ++c) keptCorners.insert(bitsOf(doc.mesh.positions[doc.mesh.triangles[t][c]]));+ return doc;+}++// Every kept corner is still there, bit for bit, and the mesh is closed and manifold.+bool keptAndClosed(const Mesh& m, const std::set<Bits>& keptCorners) {+ std::set<Bits> now;+ for (const auto& p : m.positions) now.insert(bitsOf(p));+ for (const Bits& b : keptCorners)+ if (!now.count(b)) return false;+ const TopologyReport r = topologyReport(m);+ return r.manifold() && r.boundaryEdges == 0;+}++} // namespace++TEST(keep_masked_triangles_need_every_corner) {+ Document doc;+ CommandRegistry reg;+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 2.0}}).ok);+ CHECK(keepMaskedTriangles(doc.mesh).empty()); // no mask+ auto& mask = doc.mesh.ensureMask();+ mask[doc.mesh.triangles[0].x] = 1.0f;+ mask[doc.mesh.triangles[0].y] = 1.0f;+ const auto partly = keepMaskedTriangles(doc.mesh);+ CHECK(partly.size() == doc.mesh.triangleCount() && partly[0] == 0);+ mask[doc.mesh.triangles[0].z] = 0.6f;+ CHECK(keepMaskedTriangles(doc.mesh)[0] == 1);+}++TEST(keep_masked_voxel_remesh_cap) {+ std::set<Bits> kept;+ Document doc = maskedSphere([](const glm::vec3& p) { return p.y > 0.4f; }, kept);+ CHECK(kept.size() > 50);+ CommandRegistry reg;+ CommandResult r = reg.execute(doc, "remesh", {{"resolution", 48.0}, {"keep_masked", true}});+ CHECK(r.ok);+ if (!r.ok) std::printf(" %s\n", r.message.c_str());+ CHECK(keptAndClosed(doc.mesh, kept));+ // The rest was rebuilt: no original vertex below the cap's edge survives.+ CHECK(reg.execute(doc, "undo", {}).ok);+ std::set<Bits> rest;+ for (const auto& p : doc.mesh.positions)+ if (p.y < 0.0f) rest.insert(bitsOf(p));+ CHECK(reg.execute(doc, "redo", {}).ok);+ size_t survived = 0;+ for (const auto& p : doc.mesh.positions) survived += rest.count(bitsOf(p));+ CHECK(survived == 0);+}++TEST(keep_masked_voxel_remesh_band) {+ // A band round the middle: two edge loops to join.+ std::set<Bits> kept;+ Document doc = maskedSphere([](const glm::vec3& p) { return std::abs(p.y) < 0.35f; }, kept);+ CommandRegistry reg;+ CommandResult r = reg.execute(doc, "remesh", {{"resolution", 48.0}, {"keep_masked", true}});+ CHECK(r.ok);+ if (!r.ok) std::printf(" %s\n", r.message.c_str());+ CHECK(keptAndClosed(doc.mesh, kept));+}++TEST(keep_masked_decimate) {+ std::set<Bits> kept;+ Document doc = maskedSphere([](const glm::vec3& p) { return p.x > 0.3f; }, kept);+ const size_t before = doc.mesh.triangleCount();+ size_t keptTris = 0;+ for (uint8_t k : keepMaskedTriangles(doc.mesh)) keptTris += k;+ CommandRegistry reg;+ CHECK(reg.execute(doc, "decimate", {{"ratio", 0.3}, {"keep_masked", true}}).ok);+ CHECK(doc.mesh.triangleCount() < before);+ CHECK(keptAndClosed(doc.mesh, kept));+ // Every kept triangle is still there.+ size_t keptAfter = 0;+ for (uint8_t k : keepMaskedTriangles(doc.mesh)) keptAfter += k;+ CHECK(keptAfter >= keptTris);+ // Without Keep masked the masked side is decimated too.+ CHECK(reg.execute(doc, "undo", {}).ok);+ CHECK(reg.execute(doc, "decimate", {{"ratio", 0.3}}).ok);+ std::set<Bits> now;+ for (const auto& p : doc.mesh.positions) now.insert(bitsOf(p));+ size_t missing = 0;+ for (const Bits& b : kept) missing += !now.count(b);+ CHECK(missing > 0);+}++TEST(keep_masked_qremesh) {+ std::set<Bits> kept;+ Document doc = maskedSphere([](const glm::vec3& p) { return p.z > 0.5f; }, kept);+ CommandRegistry reg;+ CommandResult r = reg.execute(doc, "qremesh", {{"target", 400.0}, {"keep_masked", true}, {"quality", false}});+ CHECK(r.ok);+ if (!r.ok) std::printf(" %s\n", r.message.c_str());+ CHECK(keptAndClosed(doc.mesh, kept));+ CHECK(topologyReport(doc.mesh).quads > 100); // the rest is quads+}++TEST(keep_masked_edge_cases) {+ CommandRegistry reg;+ // Nothing masked: an ordinary remesh.+ {+ std::set<Bits> kept;+ Document doc = maskedSphere([](const glm::vec3&) { return false; }, kept);+ CHECK(reg.execute(doc, "remesh", {{"resolution", 32.0}, {"keep_masked", true}}).ok);+ CHECK(topologyReport(doc.mesh).manifold());+ }+ // Everything masked: nothing to do, and the mesh is left as it was.+ {+ std::set<Bits> kept;+ Document doc = maskedSphere([](const glm::vec3&) { return true; }, kept);+ const size_t tris = doc.mesh.triangleCount();+ CHECK(!reg.execute(doc, "remesh", {{"resolution", 32.0}, {"keep_masked", true}}).ok);+ CHECK(!reg.execute(doc, "qremesh", {{"target", 200.0}, {"keep_masked", true}}).ok);+ CHECK(doc.mesh.triangleCount() == tris);+ }+}diff --git a/tests/ui/keep_masked.sfui b/tests/ui/keep_masked.sfuinew file mode 100644index 00000000..5a4023b7--- /dev/null+++ b/tests/ui/keep_masked.sfui@@ -0,0 +1,46 @@+# #43: Keep Masked for Voxel Remesh, Decimate and QRemesh: the masked top of a sphere keeps its triangles while+# the rest is rebuilt and joined to it.+run new_sphere subdivisions=5+run mask_rect x0=-1 y0=0.3 x1=1 y1=1+expect_value masked > 100+key f++# Voxel Remesh, Keep Masked on: one undo step; the masked vertices are all still masked.+click "Remesh##tool.remesh"+expect "Keep Masked##remesh"+hold ctrl+hover "Keep Masked##remesh"+expect_help "keep their triangles"+hold none+remember masked kept+remember triangles before+click "Keep Masked##remesh"+click "Voxel Remesh##geometry.remesh"+wait_idle 120+expect_status Remeshed to+expect_value triangles != $before+expect_value masked >= $kept+click "PolyF##view.polyf"+shot voxel_keep_masked+click "PolyF##view.polyf"+key ctrl+z+expect_value triangles == $before++# Decimate with Keep Masked.+click "Geometry##tool.geometry"+click "Keep Masked##decimate"+click "Decimate"+expect_status Decimated to+expect_value triangles < $before+expect_value masked >= $kept+key ctrl+z++# QRemesh with Keep Masked: the unmasked part becomes quads.+click "QRemesh/Keep Masked##qremesh"+click "QRemesh/QRemesh"+wait_idle 120+expect_status quads+expect_value quads > 100+expect_value masked >= $kept+click "PolyF##view.polyf"+shot qremesh_keep_masked