Skip to content

Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.

Smooth averages the polygon ring on quad meshes (no shear into zigzags after Quad Remesh, #69); Keep Masked joins voxel remeshes that meet themselves and tidies awkward mask edges, with messages that say what to change (#67)

islandmed32cc55fdced7
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index c1910671..02ae0080 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -242,14 +242,16 @@ CommandRegistry::CommandRegistry() {
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};
+ std::string keepNote;
if (keeping) {
Mesh stitched;
- if (!stitchKeptTriangles(doc.mesh, keep, m, stitched, err)) return {false, "Remesh (Keep masked): " + err};
+ if (!stitchKeptTriangles(doc.mesh, keep, m, stitched, err, &keepNote)) 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};
+ return {true, "Remeshed to " + std::to_string(doc.mesh.triangleCount()) + " triangles" + texture +
+ (keepNote.empty() ? "" : "; Keep masked: " + keepNote)};
}});
add({"image_relief",
diff --git a/src/core/Deform.cpp b/src/core/Deform.cpp
index 3d4b43ef..cc5fbfa9 100644
--- a/src/core/Deform.cpp
+++ b/src/core/Deform.cpp
@@ -60,7 +60,7 @@ void normalsOf(const Mesh& m, const std::vector<vec3>& P, std::vector<vec3>& N)
}
vec3 laplacian(const Mesh& m, const std::vector<vec3>& P, uint32_t v) {
- const IndexRing ring = m.neighbors(v);
+ const IndexRing ring = m.polygonNeighbors(v);
vec3 avg(0.0f);
for (uint32_t n : ring) avg += P[n];
return avg / float(ring.size()) - P[v];
diff --git a/src/core/KeepMasked.cpp b/src/core/KeepMasked.cpp
index abef238b..b6e4af84 100644
--- a/src/core/KeepMasked.cpp
+++ b/src/core/KeepMasked.cpp
@@ -7,6 +7,7 @@
#include "core/SubTools.h"
#include <algorithm>
+#include <string>
#include <limits>
#include <map>
#include <unordered_map>
@@ -36,22 +37,40 @@ 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) {
+// its left). An edge is open where more triangles run along it one way than the other, so an edge where the
+// surface meets itself (four triangles, as voxel remeshing leaves where two parts of a model touch) is not
+// open (#67: the stitch used to refuse every such surface). False when the open edges aren't a set of simple
+// loops: an edge open twice over, or a vertex where two loops meet (each such vertex is added to `pinches`).
+bool boundaryLoops(const std::vector<glm::uvec3>& tris, std::vector<std::vector<uint32_t>>& loops,
+ std::vector<uint32_t>* pinches = nullptr) {
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;
+ if (t[e] != t[(e + 1) % 3]) ++used[directedKey(t[e], t[(e + 1) % 3])];
std::unordered_map<uint32_t, uint32_t> next;
- std::unordered_set<uint32_t> hasIn;
+ std::unordered_map<uint32_t, int> outs, ins;
+ bool ok = true;
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;
+ const auto back = used.find(directedKey(b, a));
+ const int open = n - (back == used.end() ? 0 : back->second);
+ if (open <= 0) continue;
+ if (open > 1) {
+ ok = false;
+ if (pinches) pinches->push_back(a);
+ }
+ next.emplace(a, b);
+ ++outs[a];
+ ++ins[b];
}
+ for (const auto& [v, n] : outs)
+ if (n > 1 || ins[v] > 1) {
+ ok = false;
+ if (pinches) pinches->push_back(v);
+ }
+ if (!ok) return false;
std::unordered_set<uint32_t> seen;
std::vector<uint32_t> starts;
for (const auto& [a, b] : next) starts.push_back(a);
@@ -128,24 +147,31 @@ Mesh keptPiece(const Mesh& source, const std::vector<uint8_t>& keep, std::vector
return k;
}
-} // namespace
+// Why one stitch failed, for stitchKeptTriangles to adjust the kept area and try again.
+struct StitchFailure {
+ enum Kind { None, KeptPinch, OpenEdge, Cut, Unmatched, Join } kind = None;
+ std::vector<uint32_t> pinches; // KeptPinch: source vertices where the masked area's edge touches itself
+ std::vector<uint32_t> tooSmall; // Unmatched: a source vertex of each kept piece no cut was made around
+};
-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;
- }
+// One stitch. `cutRings`: cut that many more rings of the new surface away round the masked area (a wider strip
+// for the bridge, past spots where the new surface folds or meets itself next to the mask's edge).
+bool stitchOnce(const Mesh& source, const std::vector<uint8_t>& keep, const Mesh& remeshed, Mesh& out,
+ std::string& error, StitchFailure& why, int cutRings) {
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::vector<uint32_t> pinches;
+ if (!boundaryLoops(kept.triangles, keptLoops, &pinches)) {
+ error = "The masked area's edge touches itself; smooth or grow the mask a little";
+ why.kind = StitchFailure::KeptPinch;
+ for (uint32_t v : pinches) why.pinches.push_back(keptSource[v]);
+ return false;
+ }
}
{
std::unordered_set<uint64_t> sourceEdges;
@@ -160,7 +186,8 @@ bool stitchKeptTriangles(const Mesh& source, const std::vector<uint8_t>& keep, c
}
if (open == loop.size()) continue;
if (open > 0) {
- error = "The masked area reaches an open edge of the mesh";
+ error = "The masked area reaches an open edge of the mesh; unmask the strip along the open edge";
+ why.kind = StitchFailure::OpenEdge;
return false;
}
inner.push_back(std::move(loop));
@@ -188,19 +215,27 @@ bool stitchKeptTriangles(const Mesh& source, const std::vector<uint8_t>& keep, c
}
};
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 (int ring = 0; ring < cutRings; ++ring) {
+ std::vector<uint8_t> cutCorner(remeshed.vertexCount(), 0);
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;
+ if (!stay[t])
+ for (int c = 0; c < 3; ++c) cutCorner[remeshed.triangles[t][c]] = 1;
+ for (size_t t = 0; t < rt; ++t) {
+ const glm::uvec3& tri = remeshed.triangles[t];
+ if (cutCorner[tri.x] || cutCorner[tri.y] || cutCorner[tri.z]) stay[t] = 0;
+ }
+ dropHalfQuads();
+ }
+ // Where the cut leaves two open loops meeting at a vertex (or runs along a spot where the new surface meets
+ // itself), cut the triangles around it too.
+ for (int pass = 0; pass < 32; ++pass) {
+ std::vector<glm::uvec3> stayed;
+ for (size_t t = 0; t < rt; ++t)
+ if (stay[t]) stayed.push_back(remeshed.triangles[t]);
+ std::vector<std::vector<uint32_t>> loops;
+ std::vector<uint32_t> pinches;
+ if (boundaryLoops(stayed, loops, &pinches) || pinches.empty()) break;
+ const std::unordered_set<uint32_t> pinch(pinches.begin(), pinches.end());
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;
@@ -219,7 +254,8 @@ bool stitchKeptTriangles(const Mesh& source, const std::vector<uint8_t>& keep, c
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";
+ error = "Couldn't cut the remeshed surface cleanly around the mask";
+ why.kind = StitchFailure::Cut;
return false;
}
std::vector<glm::vec3> keptPoints, restPoints;
@@ -234,10 +270,15 @@ bool stitchKeptTriangles(const Mesh& source, const std::vector<uint8_t>& keep, c
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);
+ std::vector<uint8_t> voted(keptLoops.size(), 0); // a cut's loop runs near it at all
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++])];
+ for (size_t i = 0; i < restLoops[r].size(); ++i) {
+ const int id = int(nearestLoop[at++]);
+ ++votes[id];
+ if (id >= 0 && size_t(id) < voted.size()) voted[size_t(id)] = 1;
+ }
size_t best = 0;
for (const auto& [id, n] : votes)
if (id >= 0 && n > best) {
@@ -255,12 +296,19 @@ bool stitchKeptTriangles(const Mesh& source, const std::vector<uint8_t>& keep, c
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";
+ // No cut's loop of its own: a masked spot smaller than the new surface's polygons (no new vertex lies
+ // nearest to it, so nothing was cut around it), or two masked areas so close that one cut opened
+ // round both.
+ error = "Part of the mask is too thin for this resolution";
+ why.kind = StitchFailure::Unmatched;
+ for (size_t l = 0; l < keptLoops.size(); ++l)
+ if (match[l] < 0 && !voted[l]) why.tooSmall.push_back(keptSource[keptLoops[l][0]]);
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";
+ error = "Couldn't match the remeshed surface to the mask's edge";
+ why.kind = StitchFailure::Unmatched;
return false;
}
// Leftover loops: drop the small pieces of the new surface they belong to, then look again.
@@ -280,7 +328,8 @@ bool stitchKeptTriangles(const Mesh& source, const std::vector<uint8_t>& keep, c
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";
+ error = "Couldn't match the remeshed surface to the mask's edge";
+ why.kind = StitchFailure::Unmatched;
return false;
}
// Map the stray pieces back to the remeshed triangles (extractTriangles keeps the order).
@@ -337,13 +386,153 @@ bool stitchKeptTriangles(const Mesh& source, const std::vector<uint8_t>& keep, c
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";
+ // The join must not add defects: the result may only meet itself where the new surface or the kept piece
+ // already did (voxel remeshing leaves such spots where parts of a model touch), and stays closed when the
+ // source was.
+ const TopologyReport after = topologyReport(merged), restReport = topologyReport(rest), keptReport = topologyReport(kept);
+ if (after.nonManifoldEdges > restReport.nonManifoldEdges + keptReport.nonManifoldEdges ||
+ after.nonManifoldVertices > restReport.nonManifoldVertices + keptReport.nonManifoldVertices ||
+ (topologyReport(source).boundaryEdges == 0 && after.boundaryEdges != 0)) {
+ error = "Couldn't join the masked area to the remeshed surface cleanly";
+ why.kind = StitchFailure::Join;
return false;
}
out = std::move(merged);
return true;
}
+// Every triangle of `keep` connected (through shared corners) to one with a corner in `seeds`, unkept.
+void dropPieces(const Mesh& source, std::vector<uint8_t>& keep, const std::vector<uint32_t>& seeds) {
+ std::vector<uint32_t> parent(source.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 (size_t t = 0; t < keep.size(); ++t)
+ if (keep[t]) {
+ const glm::uvec3& tri = source.triangles[t];
+ parent[find(tri.y)] = find(tri.x);
+ parent[find(tri.z)] = find(tri.x);
+ }
+ std::unordered_set<uint32_t> drop;
+ for (uint32_t v : seeds) drop.insert(find(v));
+ for (size_t t = 0; t < keep.size(); ++t)
+ if (keep[t] && drop.count(find(source.triangles[t].x))) keep[t] = 0;
+}
+
+// Morphological closing of the kept area by `rings` rings of vertices (grown, then shrunk back): gaps and notches
+// up to about 2 x rings edges across are filled with the source's own triangles, the rest of the edge stays.
+void closeKept(const Mesh& source, std::vector<uint8_t>& keep, int rings) {
+ const size_t nv = source.vertexCount();
+ std::vector<uint8_t> in(nv, 0), next(nv, 0);
+ for (size_t t = 0; t < keep.size(); ++t)
+ if (keep[t])
+ for (int c = 0; c < 3; ++c) in[source.triangles[t][c]] = 1;
+ for (int pass = 0; pass < 2 * rings; ++pass) {
+ const bool grow = pass < rings;
+ for (uint32_t v = 0; v < nv; ++v) {
+ uint8_t x = in[v];
+ for (uint32_t n : source.neighbors(v)) x = grow ? uint8_t(x | in[n]) : uint8_t(x & in[n]);
+ next[v] = x;
+ }
+ in.swap(next);
+ }
+ for (size_t t = 0; t < keep.size(); ++t) {
+ const glm::uvec3& tri = source.triangles[t];
+ if (in[tri.x] && in[tri.y] && in[tri.z]) keep[t] = 1;
+ }
+}
+
+} // namespace
+
+bool stitchKeptTriangles(const Mesh& source, const std::vector<uint8_t>& keepIn, const Mesh& remeshed, Mesh& out,
+ std::string& error, std::string* note) {
+ const size_t nt = source.triangleCount();
+ if (keepIn.size() != nt || std::find(keepIn.begin(), keepIn.end(), 1) == keepIn.end()) {
+ error = "Nothing is masked";
+ return false;
+ }
+ // A mask edge the stitch can't follow is tidied and tried again (#67): where the edge touches itself, the
+ // triangles at that corner are remeshed; masked spots smaller than the new polygons are remeshed with the
+ // rest; a join that folds gets a wider cut (1, then 2 more rings of the new surface); narrow gaps and notches
+ // between masked areas are kept too (a closing of 1, 2, then 4 rings).
+ std::vector<uint8_t> keep = keepIn;
+ StitchFailure first;
+ size_t pinchFixes = 0;
+ int rings = 0, cutRings = 0;
+ for (int attempt = 0; attempt < 24; ++attempt) {
+ StitchFailure why;
+ std::string err;
+ if (stitchOnce(source, keep, remeshed, out, err, why, cutRings)) {
+ if (note) {
+ size_t added = 0, removed = 0;
+ for (size_t t = 0; t < nt; ++t) {
+ added += keep[t] && !keepIn[t];
+ removed += !keep[t] && keepIn[t];
+ }
+ note->clear();
+ if (added || removed) {
+ *note = "the mask's edge was tidied to fit the new surface (";
+ if (added) *note += std::to_string(added) + " triangles in narrow gaps kept";
+ if (added && removed) *note += ", ";
+ if (removed) *note += std::to_string(removed) + " triangles at tight corners or small spots remeshed";
+ *note += ")";
+ }
+ }
+ return true;
+ }
+ if (first.kind == StitchFailure::None) {
+ first = why;
+ error = err;
+ }
+ bool changed = false;
+ if (why.kind == StitchFailure::KeptPinch && !why.pinches.empty() && pinchFixes < 8) {
+ const std::unordered_set<uint32_t> pinch(why.pinches.begin(), why.pinches.end());
+ for (size_t t = 0; t < nt; ++t) {
+ const glm::uvec3& tri = source.triangles[t];
+ if (keep[t] && (pinch.count(tri.x) || pinch.count(tri.y) || pinch.count(tri.z))) {
+ keep[t] = 0;
+ changed = true;
+ }
+ }
+ ++pinchFixes;
+ } else if (why.kind == StitchFailure::Unmatched && !why.tooSmall.empty()) {
+ dropPieces(source, keep, why.tooSmall);
+ changed = true;
+ } else if ((why.kind == StitchFailure::Join || why.kind == StitchFailure::Cut) && cutRings < 2) {
+ ++cutRings;
+ changed = true;
+ } else if (why.kind != StitchFailure::OpenEdge && rings < 4) {
+ rings = rings ? rings * 2 : 1;
+ const std::vector<uint8_t> before = keep;
+ closeKept(source, keep, rings);
+ changed = keep != before;
+ }
+ if (!changed) break;
+ if (std::find(keep.begin(), keep.end(), 1) == keep.end()) break;
+ if (std::find(keep.begin(), keep.end(), 0) == keep.end()) break;
+ }
+ // Still no clean join: say what to change.
+ switch (first.kind) {
+ case StitchFailure::KeptPinch:
+ error = "The masked area's edge touches itself (" + std::to_string(first.pinches.size()) +
+ (first.pinches.size() == 1 ? " place" : " places") +
+ "); blur the mask (Tool > Masking > Blur) or grow it by 2 passes, then try again";
+ break;
+ case StitchFailure::OpenEdge:
+ break; // (its own message says what to do)
+ case StitchFailure::Unmatched:
+ error = "Two masked areas are too close together, one is too small for this resolution, or the mask runs inside "
+ "another part of the model; grow the mask by 2-3 passes (Tool > Masking > Grow) to join them, unmask the "
+ "small spots, or unmask where the parts overlap";
+ break;
+ default:
+ error = "Couldn't join the masked area to the remeshed surface; blur the mask (Tool > Masking > Blur) so its "
+ "edge is smoother, or grow it by 2 passes, then try again";
+ break;
+ }
+ return false;
+}
+
} // namespace sf
diff --git a/src/core/KeepMasked.h b/src/core/KeepMasked.h
index a76c52d6..a4d7a692 100644
--- a/src/core/KeepMasked.h
+++ b/src/core/KeepMasked.h
@@ -27,10 +27,13 @@ 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.
+// strip of triangles. Sculpt layers, levels and paint layers are dropped (the remeshers bake them). Spots where
+// the new surface meets itself (voxel remeshing leaves them where parts of a model touch) are fine. A mask edge
+// the stitch can't follow is tidied and tried again (#67): triangles where the edge touches itself and masked
+// spots smaller than the new polygons are remeshed, narrow gaps between masked areas are kept; `note` (when
+// given) then says so, else it is cleared. Fails, saying what to change, when even that can't be joined up;
+// `out` is then untouched.
bool stitchKeptTriangles(const Mesh& source, const std::vector<uint8_t>& keep, const Mesh& remeshed, Mesh& out,
- std::string& error);
+ std::string& error, std::string* note = nullptr);
} // namespace sf
diff --git a/src/core/Mesh.cpp b/src/core/Mesh.cpp
index 726f25b0..7dce3135 100644
--- a/src/core/Mesh.cpp
+++ b/src/core/Mesh.cpp
@@ -454,6 +454,33 @@ IndexRing Mesh::implicitTriangles(uint32_t v) const {
return r;
}
+IndexRing Mesh::quadNeighbors(uint32_t v) const {
+ const IndexRing ring = neighbors(v);
+ if (ring.size() > IndexRing::kCapacity) return ring; // (a fan this wide is no quad mesh)
+ // The far ends of the diagonals at v (at most one per triangle around it).
+ uint32_t skip[IndexRing::kCapacity];
+ uint32_t ns = 0;
+ for (uint32_t t : vertexTriangles(v)) {
+ const uint32_t u = quadPartnerAt(t);
+ if (u == kNoQuad) continue;
+ const int e = quadDiagonal(t, u);
+ if (e < 0) continue;
+ const glm::uvec3& tri = triangles[t];
+ const uint32_t a = tri[e], b = tri[(e + 1) % 3];
+ if (a == v || b == v) skip[ns++ % IndexRing::kCapacity] = a == v ? b : a;
+ }
+ if (ns == 0) return ring;
+ IndexRing r;
+ uint32_t n = 0;
+ for (uint32_t w : ring) {
+ bool diagonal = false;
+ for (uint32_t i = 0; i < std::min<uint32_t>(ns, IndexRing::kCapacity) && !diagonal; ++i) diagonal = skip[i] == w;
+ if (!diagonal) r.buf_[n++] = w;
+ }
+ r.size_ = n;
+ return n ? r : ring;
+}
+
IndexRing Mesh::implicitNeighbors(uint32_t v) const {
// The ring follows from the same layout: Catmull-Clark joins a corner to the edge points of its edges and the
// face points of its polygons, an edge point to the edge's ends and face points, and a face point to the
diff --git a/src/core/Mesh.h b/src/core/Mesh.h
index b5a81100..af21c444 100644
--- a/src/core/Mesh.h
+++ b/src/core/Mesh.h
@@ -248,6 +248,14 @@ public:
if (implicit_) return implicitTriangles(v);
return {vtList_.data() + vtOffsets_[v], vtList_.data() + (vtEnds_.empty() ? vtOffsets_[v + 1] : vtEnds_[v])};
}
+ // The vertices sharing a polygon edge with `v`: neighbors() less the far ends of the quad diagonals at `v`
+ // (each quad is stored as two triangles; its diagonal is no edge of the polygon). Smoothing averages this ring:
+ // with the diagonals, a vertex on one end of a quad's diagonal and not the other is pulled along it, which
+ // shears a quad mesh into zigzags (#69). Without quads, neighbors() itself.
+ IndexRing polygonNeighbors(uint32_t v) const {
+ if (quadPartners.empty()) return neighbors(v);
+ return quadNeighbors(v);
+ }
// True when the adjacency follows from the subdivision level this mesh is (see rebuildTopology).
bool implicitAdjacency() const { return bool(implicit_); }
@@ -311,6 +319,7 @@ private:
void finishNormals(float* curvature, bool computeNormals = true); // ... then each member's normal (and curvatureAt)
IndexRing implicitTriangles(uint32_t v) const;
IndexRing implicitNeighbors(uint32_t v) const;
+ IndexRing quadNeighbors(uint32_t v) const;
// Vertex adjacency (CSR), or, on a mesh that is a level made by Divide (whose triangles are the ones its
// subdivision topology generates), that topology and two small indexes into it: the triangles and rings
diff --git a/src/core/RetopoCommands.cpp b/src/core/RetopoCommands.cpp
index e605cb3b..99400eed 100644
--- a/src/core/RetopoCommands.cpp
+++ b/src/core/RetopoCommands.cpp
@@ -147,16 +147,17 @@ void registerRetopoCommands(CommandRegistry& reg) {
if (argBool(a, "guides", true)) o.guides = doc.qremeshGuides;
o.guideStrength = float(std::clamp(argNumber(a, "curves_strength", 50.0), 0.0, 100.0) / 100.0);
Mesh out;
- std::string err;
+ std::string err, keepNote;
QRemeshStats st;
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, "Quad Remesh (Keep masked): " + err};
+ if (!stitchKeptTriangles(doc.mesh, keep, out, stitched, err, &keepNote)) return {false, "Quad Remesh (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};
+ return {true, applyQRemesh(doc, std::move(out), argBool(a, "keep_original", false), st) + texture +
+ (keepNote.empty() ? "" : "; Keep masked: " + keepNote)};
}});
reg.add({"project_all",
diff --git a/src/core/Sculpt.cpp b/src/core/Sculpt.cpp
index 7354f0ad..13704ad6 100644
--- a/src/core/Sculpt.cpp
+++ b/src/core/Sculpt.cpp
@@ -776,7 +776,7 @@ void Sculptor::dabSingle(Mesh& mesh, BVH& bvh, BrushType type, const DabParams&
d = nrm[v] * (sign * s * r * 0.05f * f);
break;
case BrushType::Smooth: {
- auto ring = mesh.neighbors(v);
+ auto ring = mesh.polygonNeighbors(v);
if (ring.empty()) break;
glm::vec3 avg(0.0f);
if (keepVolume) {
@@ -912,7 +912,7 @@ void Sculptor::taubinShrink(const Mesh& mesh) {
poolFor(verts_.size(), [&](size_t begin, size_t end) {
for (size_t i = begin; i < end; ++i) {
const uint32_t v = verts_[i];
- auto ring = mesh.neighbors(v);
+ auto ring = mesh.polygonNeighbors(v);
shrunk_[i] = pos[v];
if (ring.empty()) continue;
glm::vec3 avg(0.0f);
@@ -1127,7 +1127,7 @@ void Sculptor::dabRecipeSingle(Mesh& mesh, BVH& bvh, const BrushRecipe& r, const
if (r.smooth > 0.0f) {
poolFor(verts_.size(), [&](size_t begin, size_t end) {
for (size_t i = begin; i < end; ++i) {
- auto ring = mesh.neighbors(verts_[i]);
+ auto ring = mesh.polygonNeighbors(verts_[i]);
if (ring.empty()) {
scratch_[i] = glm::vec3(0.0f);
continue;
diff --git a/tests/test_inbox_0106.cpp b/tests/test_inbox_0106.cpp
new file mode 100644
index 00000000..4426beef
--- /dev/null
+++ b/tests/test_inbox_0106.cpp
@@ -0,0 +1,212 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// 0.10.6 inbox: the Smooth brush on a Quad Remesh result (#69) and Keep Masked remeshing (#67).
+//
+// #69: smoothing averaged every vertex joined by a triangle edge, quad diagonals included. A vertex at one end of a
+// quad's diagonal (and not the other) was pulled along it, so smoothing sheared a quad mesh into zigzags. Smooth now
+// averages the polygon ring (Mesh::polygonNeighbors).
+// #67: voxel remeshing leaves spots where the surface meets itself (where parts of a model touch: a lion's mane),
+// and the stitch refused any such surface ("Couldn't cut the remeshed surface cleanly"), at every resolution.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/Document.h"
+#include "core/KeepMasked.h"
+#include "core/Primitives.h"
+#include "core/QRemesh.h"
+#include "core/Voxel.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <functional>
+#include <map>
+#include <string>
+#include <tuple>
+
+using namespace sf;
+
+namespace {
+
+std::string repoPath(const char* rel) {
+ std::string root = __FILE__;
+ return root.substr(0, root.rfind("tests")) + rel;
+}
+
+size_t coincidentVertices(const Mesh& m) {
+ std::map<std::tuple<float, float, float>, int> seen;
+ size_t dup = 0;
+ for (const auto& p : m.positions) dup += seen[{p.x, p.y, p.z}]++ > 0;
+ return dup;
+}
+
+// Smooth strokes across the front, mirrored in X, as a user evens out a remeshed form.
+void smoothAcross(CommandRegistry& reg, Document& doc, float radius) {
+ const AABB b = doc.mesh.bounds();
+ const glm::vec3 c = (b.min + b.max) * 0.5f, e = b.max - b.min;
+ for (int i = 0; i < 30; ++i) {
+ const float y = c.y + e.y * (-0.4f + 0.8f * float(i % 10) / 9.0f);
+ char pts[160];
+ std::snprintf(pts, sizeof pts, "%.4f,%.4f,%.4f %.4f,%.4f,%.4f", c.x - 0.45f * e.x, y, b.max.z + e.z, c.x + 0.45f * e.x,
+ y + 0.02f * e.y * float(i / 10), b.max.z + e.z);
+ CHECK(reg.execute(doc, "stroke", {{"points", std::string(pts)}, {"brush", std::string("Smooth")}, {"radius", double(radius)},
+ {"strength", 1.0}, {"symmetry", std::string("x")}})
+ .ok);
+ }
+}
+
+// Quad Remesh, then smoothing: the quads keep their shape (no shear), and the surface stays closed and welded.
+// `slack`: how much the mean corner angle deviation may grow (curved, uneven remeshes change a little as they smooth).
+void checkSmoothKeepsQuads(Document& doc, double target, float radius, const char* name, float slack, float maxSlackDeg) {
+ CommandRegistry reg;
+ CHECK(reg.execute(doc, "qremesh", {{"target", target}, {"symmetry", std::string("x")}, {"quality", false}}).ok);
+ const QuadQuality before = quadQuality(doc.mesh);
+ CHECK(topologyReport(doc.mesh).boundaryEdges == 0);
+ CHECK(coincidentVertices(doc.mesh) == 0); // (the remesh is welded: not the cause)
+ smoothAcross(reg, doc, radius);
+ const QuadQuality after = quadQuality(doc.mesh);
+ const TopologyReport r = topologyReport(doc.mesh);
+ std::printf(" %s: corner angle deviation %.2f -> %.2f deg (99th percentile %.2f -> %.2f)\n", name, before.angleDeviation,
+ after.angleDeviation, before.angleDeviationMax, after.angleDeviationMax);
+ // Before the fix: sphere 3.9 -> 8.8 deg (99th percentile 15 -> 41), lion 8.7 -> 19.5 deg (37 -> 55).
+ CHECK(after.angleDeviation <= before.angleDeviation * slack);
+ CHECK(after.angleDeviationMax <= before.angleDeviationMax + maxSlackDeg);
+ CHECK(r.boundaryEdges == 0 && r.manifold());
+}
+
+} // namespace
+
+TEST(inbox0106_polygon_neighbors_skip_quad_diagonals) {
+ // A 3 x 3 grid of quads, each split along a diagonal running the same way: the middle vertex's triangle ring
+ // has 6 vertices (4 edges + 2 diagonals), its polygon ring the 4 edge neighbours.
+ Mesh m;
+ for (int y = 0; y < 4; ++y)
+ for (int x = 0; x < 4; ++x) m.positions.emplace_back(float(x), float(y), 0.0f);
+ auto id = [](int x, int y) { return uint32_t(y * 4 + x); };
+ for (int y = 0; y < 3; ++y)
+ for (int x = 0; x < 3; ++x) {
+ const uint32_t t = uint32_t(m.triangles.size());
+ m.triangles.emplace_back(id(x, y), id(x + 1, y), id(x + 1, y + 1));
+ m.triangles.emplace_back(id(x, y), id(x + 1, y + 1), id(x, y + 1));
+ m.pairQuad(t, t + 1);
+ }
+ m.rebuildTopology();
+ const uint32_t v = id(1, 1);
+ CHECK(m.neighbors(v).size() == 6);
+ const IndexRing ring = m.polygonNeighbors(v);
+ CHECK(ring.size() == 4);
+ for (uint32_t w : ring) CHECK(w == id(0, 1) || w == id(2, 1) || w == id(1, 0) || w == id(1, 2));
+ // Without quads, the triangle ring.
+ m.clearQuads();
+ CHECK(m.polygonNeighbors(v).size() == 6);
+}
+
+TEST(inbox0106_smooth_keeps_quad_remesh_regular_sphere) {
+ Document doc;
+ CommandRegistry reg;
+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 5.0}}).ok);
+ checkSmoothKeepsQuads(doc, 3000.0, 0.25f, "sphere", 1.05f, 1.0f);
+}
+
+TEST(inbox0106_smooth_keeps_quad_remesh_regular_lion) {
+ Document doc;
+ CommandRegistry reg;
+ CHECK(reg.execute(doc, "open", {{"path", repoPath("assets/demo/lion-head.glb")}, {"subdivisions", 0.0}}).ok);
+ const float size = glm::length(doc.mesh.bounds().extent());
+ checkSmoothKeepsQuads(doc, 3000.0, 0.08f * size, "lion", 1.25f, 6.0f);
+}
+
+namespace {
+
+// The lion head masked by `masked` (in its box, -0.5..0.5), voxel remeshed with Keep masked.
+CommandResult lionKeepMasked(const std::function<bool(const glm::vec3&)>& masked, double resolution, Document& doc) {
+ CommandRegistry reg;
+ CHECK(reg.execute(doc, "open", {{"path", repoPath("assets/demo/lion-head.glb")}, {"subdivisions", 0.0}}).ok);
+ const AABB b = doc.mesh.bounds();
+ const glm::vec3 c = (b.min + b.max) * 0.5f, e = b.max - b.min;
+ auto& mask = doc.mesh.ensureMask();
+ for (size_t v = 0; v < mask.size(); ++v) mask[v] = masked((doc.mesh.positions[v] - c) / e) ? 1.0f : 0.0f;
+ return reg.execute(doc, "remesh", {{"resolution", resolution}, {"keep_masked", true}, {"keep_texture", false}});
+}
+
+} // namespace
+
+TEST(inbox0106_keep_masked_voxel_on_a_real_model) {
+ // Before the fix every one of these failed with "Couldn't cut the remeshed surface cleanly" (the plain voxel
+ // remesh of the lion meets itself on 150-200 edges in the mane at any resolution).
+ const std::function<bool(const glm::vec3&)> masks[] = {
+ [](const glm::vec3& q) { return q.y > 0.1f; }, // the top
+ [](const glm::vec3& q) { return q.z > 0.2f; }, // the face
+ [](const glm::vec3& q) { return glm::length(glm::vec2(q.x, q.y)) < 0.2f; }, // a disc right through
+ [](const glm::vec3& q) { return q.z > 0.0f && std::abs(q.x) < 0.15f; }, // a stripe down the front
+ };
+ for (const auto& masked : masks)
+ for (double res : {128.0, 300.0}) {
+ Document doc;
+ const CommandResult r = lionKeepMasked(masked, res, doc);
+ if (!r.ok) std::printf(" res %.0f: %s\n", res, r.message.c_str());
+ CHECK(r.ok);
+ if (!r.ok) continue;
+ const TopologyReport t = topologyReport(doc.mesh);
+ CHECK(t.boundaryEdges == 0);
+ // Every kept triangle is still there with its mask.
+ size_t kept = 0;
+ for (uint8_t k : keepMaskedTriangles(doc.mesh)) kept += k;
+ CHECK(kept > 1000);
+ }
+}
+
+TEST(inbox0106_keep_masked_tidies_awkward_masks) {
+ // A mask whose edge touches itself (stripes meeting at corners) and two masked spots so close that one cut
+ // opened round both: tidied (the corner triangles remeshed, the gap kept) and joined, saying so.
+ struct Case {
+ const char* name;
+ std::function<bool(const glm::vec3&)> masked;
+ } cases[] = {
+ {"stripes", [](const glm::vec3& p) { return std::sin(p.x * 25.0f) > 0.0f && p.z > 0.0f; }},
+ {"close spots", [](const glm::vec3& p) {
+ return glm::distance(p, glm::vec3(0.0f, 0.2f, 1.0f)) < 0.18f || glm::distance(p, glm::vec3(0.0f, -0.2f, 1.0f)) < 0.18f;
+ }},
+ };
+ for (const Case& c : cases) {
+ Document doc;
+ CommandRegistry reg;
+ CHECK(reg.execute(doc, "new_sphere", {{"subdivisions", 4.0}}).ok);
+ auto& mask = doc.mesh.ensureMask();
+ for (size_t v = 0; v < mask.size(); ++v) mask[v] = c.masked(doc.mesh.positions[v]) ? 1.0f : 0.0f;
+ const std::vector<uint8_t> keep = keepMaskedTriangles(doc.mesh);
+ const Mesh remeshed = voxelRemesh(doc.mesh, 128);
+ Mesh out;
+ std::string err, note;
+ const bool ok = stitchKeptTriangles(doc.mesh, keep, remeshed, out, err, &note);
+ std::printf(" %s: %s\n", c.name, ok ? note.c_str() : err.c_str());
+ CHECK(ok);
+ CHECK(!note.empty());
+ const TopologyReport t = topologyReport(out);
+ CHECK(t.boundaryEdges == 0 && t.manifold());
+ // Through the command, the note is in the message.
+ CommandResult r = reg.execute(doc, "remesh", {{"resolution", 128.0}, {"keep_masked", true}, {"keep_texture", false}});
+ CHECK(r.ok && r.message.find("Keep masked:") != std::string::npos);
+ }
+}
+
+TEST(inbox0106_keep_masked_says_what_to_change) {
+ // A mask that runs into the inside of another part (two overlapping spheres as one Part, masked across both):
+ // there's nothing to join it to, and the message says what to change.
+ Mesh a = makeIcosphere(5), m = a;
+ const uint32_t base = uint32_t(m.positions.size());
+ for (const auto& p : a.positions) m.positions.push_back(p * 0.8f + glm::vec3(1.2f, 0.0f, 0.0f));
+ for (const auto& t : a.triangles) m.triangles.push_back(t + glm::uvec3(base));
+ m.quadPartners.clear();
+ m.rebuildTopology();
+ m.recomputeAllNormals();
+ auto& mask = m.ensureMask();
+ for (size_t v = 0; v < mask.size(); ++v) mask[v] = m.positions[v].y > 0.3f ? 1.0f : 0.0f;
+ Mesh out;
+ std::string err;
+ CHECK(!stitchKeptTriangles(m, keepMaskedTriangles(m), voxelRemesh(m, 128), out, err));
+ std::printf(" %s\n", err.c_str());
+ CHECK(err.find("Tool > Masking > Grow") != std::string::npos);
+ CHECK(out.triangleCount() == 0); // untouched
+}