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.

QRemesh (field-aligned quad retopology) and ProjectAll in the core, with qremesh / project_all commands and tests

islandmedaac1699a4264
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4c70174e..a72952a3 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -56,6 +56,10 @@ add_library(sculptforge_core STATIC
src/core/Texture.cpp
src/core/TextureCommands.cpp
src/core/AutoUv.cpp
+ src/core/SurfaceQuery.cpp
+ src/core/QRemesh.cpp
+ src/core/Projection.cpp
+ src/core/RetopoCommands.cpp
third_party/xatlas/xatlas.cpp
src/core/Matcap.cpp
src/core/Project.cpp
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index 06c299ca..c39f6889 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -14,6 +14,7 @@
#include "core/Polypaint.h"
#include "core/Primitives.h"
#include "core/Project.h"
+#include "core/QRemesh.h"
#include "core/Splats.h"
#include "core/Voxel.h"
#include "io/FbxIO.h"
@@ -549,6 +550,7 @@ CommandRegistry::CommandRegistry() {
}});
registerBrushLibraryCommands(*this); // brush_install, brush_code, brush_delete, ... (BrushLibrary.cpp)
registerBrushCommands(*this); // brush_set_alpha (BrushAlpha.cpp)
+ registerRetopoCommands(*this); // qremesh, project_all (RetopoCommands.cpp)
add({"stroke",
"Apply a brush along a path on the active SubTool, like dragging the cursor in the viewport (one undo "
diff --git a/src/core/Parallel.h b/src/core/Parallel.h
new file mode 100644
index 00000000..f846aefb
--- /dev/null
+++ b/src/core/Parallel.h
@@ -0,0 +1,41 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// parallelFor: splits [0, n) into chunks run on up to 16 threads (the calling one included). For coarse jobs
+// (QRemesh's field smoothing, ProjectAll); small ranges run inline.
+#pragma once
+
+#include <algorithm>
+#include <cstddef>
+#include <thread>
+#include <vector>
+
+namespace sf {
+
+inline int parallelThreads() { return int(std::clamp(std::thread::hardware_concurrency(), 1u, 16u)); }
+
+// Calls fn(begin, end) on disjoint chunks covering [0, n); runs inline when n < minParallel.
+template <class F>
+void parallelFor(size_t n, F&& fn, size_t minParallel = 20000) {
+ if (n == 0) return;
+ const size_t threads = n < minParallel ? 1 : std::min<size_t>(size_t(parallelThreads()), (n + 255) / 256);
+ if (threads <= 1) {
+ fn(size_t(0), n);
+ return;
+ }
+ // More chunks than threads so uneven work balances; threads take chunks in turn.
+ const size_t chunks = threads * 4, step = (n + chunks - 1) / chunks;
+ std::vector<std::thread> pool;
+ pool.reserve(threads - 1);
+ auto work = [&](size_t t) {
+ for (size_t c = t; c < chunks; c += threads) {
+ const size_t b = c * step, e = std::min(n, b + step);
+ if (b < e) fn(b, e);
+ }
+ };
+ for (size_t t = 1; t < threads; ++t) pool.emplace_back(work, t);
+ work(0);
+ for (auto& th : pool) th.join();
+}
+
+} // namespace sf
diff --git a/src/core/Projection.cpp b/src/core/Projection.cpp
new file mode 100644
index 00000000..ed5bb7e2
--- /dev/null
+++ b/src/core/Projection.cpp
@@ -0,0 +1,213 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Projection.h"
+
+#include "core/PaintLayer.h"
+#include "core/Parallel.h"
+#include "core/SurfaceQuery.h"
+
+#include <algorithm>
+#include <atomic>
+#include <chrono>
+#include <cmath>
+
+namespace sf {
+
+bool computeProjection(const Mesh& target, const std::vector<const Mesh*>& sources, const ProjectOptions& opt,
+ std::vector<glm::vec3>& positions, std::vector<glm::vec3>* colors, ProjectStats& stats,
+ std::string& error, const ProjectProgress& progress) {
+ const auto start = std::chrono::steady_clock::now();
+ stats = {};
+ const size_t nv = target.vertexCount();
+ if (nv == 0) {
+ error = "ProjectAll: the active SubTool is empty";
+ return false;
+ }
+ // One triangle soup of every visible source triangle, with its colours.
+ std::vector<glm::vec3> P, C;
+ std::vector<glm::uvec3> T;
+ bool anyColor = false;
+ for (const Mesh* s : sources) anyColor |= s->hasColors();
+ for (const Mesh* s : sources) {
+ const uint32_t first = uint32_t(P.size());
+ P.insert(P.end(), s->positions.begin(), s->positions.end());
+ if (anyColor) {
+ if (s->hasColors()) C.insert(C.end(), s->colors.begin(), s->colors.end());
+ else C.insert(C.end(), s->vertexCount(), glm::vec3(1.0f));
+ }
+ for (uint32_t t = 0; t < s->triangleCount(); ++t)
+ if (!s->triangleHidden(t)) T.push_back(s->triangles[t] + glm::uvec3(first));
+ }
+ if (T.empty()) {
+ error = "ProjectAll needs another visible SubTool to project from";
+ return false;
+ }
+ TriangleBVH bvh;
+ bvh.build(std::move(P), std::move(T));
+ if (progress && !progress(0.3f)) {
+ error = "ProjectAll cancelled";
+ return false;
+ }
+
+ const float reach = std::max(opt.distance, 1e-6f) * glm::length(target.bounds().extent());
+ const bool doColors = colors && opt.polypaint && anyColor;
+ positions = target.positions;
+ if (doColors) *colors = target.hasColors() ? target.colors : std::vector<glm::vec3>(nv, glm::vec3(1.0f));
+ std::vector<float> moved(nv, 0.0f); // weight each vertex was projected with (0 = untouched)
+ std::atomic<size_t> projected{0}, missed{0}, masked{0}, done{0};
+ std::atomic<bool> cancel{false};
+ const auto& tp = bvh.triangles();
+ const bool hasNormals = target.normals.size() == nv;
+ parallelFor(nv, [&](size_t b, size_t e) {
+ size_t p = 0, m = 0, k = 0;
+ for (size_t v = b; v < e; ++v) {
+ if (cancel.load(std::memory_order_relaxed)) break;
+ const float w = 1.0f - target.maskAt(uint32_t(v));
+ if (w <= 0.0f || (target.hasHidden() && target.vertexHidden(uint32_t(v)))) {
+ ++k;
+ continue;
+ }
+ const glm::vec3 o = target.positions[v];
+ const glm::vec3 n = hasNormals ? target.normals[v] : glm::vec3(0.0f);
+ SurfaceHit out, in, hit;
+ const bool hasN = glm::dot(n, n) > 0.25f;
+ const bool hitOut = hasN && bvh.raycast(o, n, reach, out);
+ const bool hitIn = hasN && bvh.raycast(o, -n, reach, in);
+ bool found = true;
+ glm::vec3 to;
+ if (hitOut && hitIn && opt.mean) {
+ to = 0.5f * (out.position + in.position);
+ hit = out.distance <= in.distance ? out : in;
+ } else if (hitOut || hitIn) {
+ hit = hitOut && (!hitIn || out.distance <= in.distance) ? out : in;
+ to = hit.position;
+ } else if (bvh.closestPoint(o, reach, hit)) { // no surface straight along the normal: nearest point
+ to = hit.position;
+ } else {
+ found = false;
+ }
+ if (!found) {
+ ++m;
+ continue;
+ }
+ ++p;
+ moved[v] = w;
+ if (opt.geometry) positions[v] = glm::mix(o, to, w);
+ if (doColors) {
+ const glm::uvec3 t = tp[hit.prim];
+ const glm::vec3 c = hit.bary.x * C[t.x] + hit.bary.y * C[t.y] + hit.bary.z * C[t.z];
+ (*colors)[v] = glm::mix((*colors)[v], c, w);
+ }
+ }
+ projected += p, missed += m, masked += k;
+ const size_t d = done += e - b;
+ if (progress && !progress(0.3f + 0.6f * float(d) / float(nv))) cancel = true;
+ });
+ if (cancel) {
+ error = "ProjectAll cancelled";
+ return false;
+ }
+ // PA Blur: smooth the offsets of the projected vertices.
+ if (opt.geometry && opt.blur > 0) {
+ std::vector<glm::vec3> d(nv), next(nv);
+ for (size_t v = 0; v < nv; ++v) d[v] = positions[v] - target.positions[v];
+ for (int it = 0; it < opt.blur; ++it) {
+ parallelFor(nv, [&](size_t b, size_t e) {
+ for (size_t v = b; v < e; ++v) {
+ const auto ring = target.neighbors(uint32_t(v));
+ if (moved[v] <= 0.0f || ring.empty()) {
+ next[v] = d[v];
+ continue;
+ }
+ glm::vec3 s(0.0f);
+ for (uint32_t u : ring) s += d[u];
+ next[v] = glm::mix(d[v], s / float(ring.size()), 0.5f * moved[v]);
+ }
+ });
+ d.swap(next);
+ }
+ for (size_t v = 0; v < nv; ++v)
+ if (moved[v] > 0.0f) positions[v] = target.positions[v] + d[v];
+ }
+ stats.projected = projected;
+ stats.missed = missed;
+ stats.masked = masked;
+ stats.colors = doColors;
+ stats.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();
+ return true;
+}
+
+bool projectAll(Document& doc, const ProjectOptions& opt, std::string& message, int source, ProjectStats* statsOut) {
+ std::vector<const Mesh*> sources;
+ for (int i = 0; i < doc.subtoolCount(); ++i) {
+ if (i == doc.activeSubtool) continue;
+ if (source >= 0 ? i != source : !doc.subtools[size_t(i)].visible) continue;
+ if (doc.subtoolMesh(i).triangleCount() > 0) sources.push_back(&doc.subtoolMesh(i));
+ }
+ if (sources.empty()) {
+ message = source >= 0 ? "ProjectAll: that SubTool can't be projected from"
+ : "ProjectAll needs another visible SubTool to project from (the source)";
+ return false;
+ }
+ if (!opt.geometry && !opt.polypaint) {
+ message = "ProjectAll: nothing to project (turn on Geometry or Polypaint)";
+ return false;
+ }
+ Mesh& m = doc.mesh;
+ const int layer = m.layers.empty() ? -1 : doc.activeLayer;
+ const float weight = m.layerTargetWeight(layer);
+ if (opt.geometry && !m.layers.empty() && std::abs(weight) < 1e-4f) {
+ message = "ProjectAll: the active sculpt layer's weight is 0";
+ return false;
+ }
+ if (opt.polypaint && !m.paintLayers.empty() && !paintLayerEditable(m, m.activePaintLayer)) {
+ message = "ProjectAll: the active paint layer is locked or hidden";
+ return false;
+ }
+ std::vector<glm::vec3> positions, colors;
+ ProjectStats st;
+ if (!computeProjection(m, sources, opt, positions, opt.polypaint ? &colors : nullptr, st, message)) return false;
+
+ // One undo step: the shape (active sculpt layer) and the colours (active paint layer), or a snapshot when
+ // the SubTool had no polypaint yet, so undo takes the attribute away again.
+ UndoRecord r;
+ if (st.colors && !m.hasColors()) {
+ r.mesh = std::make_unique<Mesh>(m);
+ } else if (st.colors) {
+ r = UndoRecord::captureColors(m, "");
+ }
+ r.label = "ProjectAll";
+ const size_t nv = m.vertexCount();
+ if (opt.geometry) {
+ std::vector<glm::vec3>& tgt = m.layerTarget(layer);
+ std::vector<uint32_t> changed;
+ for (uint32_t v = 0; v < nv; ++v)
+ if (positions[v] != m.positions[v]) changed.push_back(v);
+ if (!r.mesh) {
+ r.layer = layer;
+ for (uint32_t v : changed) r.positions.add(v, tgt[v]);
+ }
+ for (uint32_t v : changed) tgt[v] += (positions[v] - m.positions[v]) / weight;
+ if (!m.layers.empty()) m.evaluate(changed);
+ m.recomputeAllNormals();
+ }
+ if (st.colors) {
+ m.ensureColors();
+ for (uint32_t v = 0; v < nv; ++v)
+ if (colors[v] != m.colors[v]) paintVertex(m, v, colors[v], 1.0f);
+ }
+ m.markAllDirty();
+ doc.bvh.build(m);
+ if (!r.empty()) doc.undo.push(std::move(r));
+ doc.modified = true;
+
+ char buf[256];
+ std::snprintf(buf, sizeof buf, "ProjectAll: %zu vertices projected%s from %zu SubTool%s in %.2f s%s", st.projected,
+ st.colors ? " (shape and polypaint)" : "", sources.size(), sources.size() == 1 ? "" : "s", st.seconds,
+ st.missed ? (", " + std::to_string(st.missed) + " found nothing within Dist").c_str() : "");
+ message = buf;
+ if (statsOut) *statsOut = st;
+ return true;
+}
+
+} // namespace sf
diff --git a/src/core/Projection.h b/src/core/Projection.h
new file mode 100644
index 00000000..326ccddf
--- /dev/null
+++ b/src/core/Projection.h
@@ -0,0 +1,50 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// ProjectAll (SubTool palette, as in ZBrush): moves the active SubTool's vertices onto the surface of other
+// SubTools and takes their polypaint, so detail survives a retopology: QRemesh a copy, divide it a few
+// times, then project from the original. Each vertex shoots a ray both ways along its normal and takes the
+// nearest hit within Dist (or the mean of both sides with Mean); the mask holds vertices back (partly
+// masked ones move part way). Rays run on all threads against a read-only BVH (core/SurfaceQuery.h).
+#pragma once
+
+#include "core/Document.h"
+
+#include <functional>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+struct ProjectOptions {
+ float distance = 0.02f; // Dist: how far to search, as a fraction of the target's bounding-box diagonal
+ bool mean = false; // Mean: with hits on both sides, settle halfway between them
+ bool geometry = true; // project the shape
+ bool polypaint = true; // project the polypaint (when a source has any)
+ int blur = 0; // PA Blur: smoothing passes over the projected offsets
+};
+
+struct ProjectStats {
+ size_t projected = 0; // vertices that found the source
+ size_t missed = 0; // nothing within Dist
+ size_t masked = 0; // fully masked or hidden: left alone
+ bool colors = false; // polypaint was projected
+ double seconds = 0.0;
+};
+
+// Fraction 0..1; return false to cancel.
+using ProjectProgress = std::function<bool(float fraction)>;
+
+// New positions (and colours, when `colors` is not null and a source has polypaint) for every vertex of
+// `target`, from the surfaces of `sources`. Vertices are moved by (1 - mask); hidden ones stay.
+bool computeProjection(const Mesh& target, const std::vector<const Mesh*>& sources, const ProjectOptions& options,
+ std::vector<glm::vec3>& positions, std::vector<glm::vec3>* colors, ProjectStats& stats,
+ std::string& error, const ProjectProgress& progress = {});
+
+// ProjectAll on the document: from every visible SubTool except the active one (or only SubTool `source`
+// when >= 0) onto the active one, as one undo step. Shape offsets go into the active sculpt layer, colours
+// into the active paint layer.
+bool projectAll(Document& doc, const ProjectOptions& options, std::string& message, int source = -1,
+ ProjectStats* stats = nullptr);
+
+} // namespace sf
diff --git a/src/core/QRemesh.cpp b/src/core/QRemesh.cpp
new file mode 100644
index 00000000..cc2438a2
--- /dev/null
+++ b/src/core/QRemesh.cpp
@@ -0,0 +1,1470 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// QRemesh: field-aligned quad remeshing (see QRemesh.h for the outline). The field formulas (extrinsic 4-RoSy
+// orientation and position compatibility, the middle point of two tangent planes) follow Instant Meshes
+// (Jakob et al. 2015); hierarchy, extraction, quad splitting and relaxation are our own.
+#include "core/QRemesh.h"
+
+#include "core/Parallel.h"
+#include "core/SurfaceQuery.h"
+
+#include <algorithm>
+#include <chrono>
+#include <map>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <numeric>
+#include <unordered_map>
+
+namespace sf {
+
+namespace {
+
+using glm::ivec2;
+using glm::vec3;
+
+constexpr uint32_t kNone = ~0u;
+
+
+uint64_t edgeKey(uint32_t a, uint32_t b) { return a < b ? (uint64_t(a) << 32) | b : (uint64_t(b) << 32) | a; }
+
+vec3 safeNormalize(const vec3& v, const vec3& fallback = vec3(0, 0, 1)) {
+ const float l = glm::length(v);
+ return l > 1e-20f ? v / l : fallback;
+}
+
+// Any unit vector perpendicular to n.
+vec3 anyTangent(const vec3& n) {
+ const vec3 a = std::abs(n.x) < 0.6f ? vec3(1, 0, 0) : vec3(0, 1, 0);
+ return safeNormalize(glm::cross(n, a));
+}
+
+struct Rng {
+ uint64_t s;
+ explicit Rng(uint64_t seed) : s(seed * 0x9E3779B97F4A7C15ull + 0x632BE59BD9B4E019ull) {}
+ float next() { // 0..1
+ s ^= s << 13;
+ s ^= s >> 7;
+ s ^= s << 17;
+ return float((s >> 40) & 0xFFFFFF) / float(0x1000000);
+ }
+};
+
+// --- Instant Meshes field formulas (4-RoSy, 4-PoSy, extrinsic) -------------------------------------------
+
+// The pair of representatives of q0's and q1's crosses (each a direction and its 90 degree rotations) that
+// are closest to each other.
+inline std::pair<vec3, vec3> compatOrientation(const vec3& q0, const vec3& n0, const vec3& q1, const vec3& n1) {
+ const vec3 A[2] = {q0, glm::cross(n0, q0)};
+ const vec3 B[2] = {q1, glm::cross(n1, q1)};
+ float best = -1.0f;
+ int ba = 0, bb = 0;
+ for (int a = 0; a < 2; ++a)
+ for (int b = 0; b < 2; ++b) {
+ const float s = std::abs(glm::dot(A[a], B[b]));
+ if (s > best) best = s, ba = a, bb = b;
+ }
+ const float dp = glm::dot(A[ba], B[bb]);
+ return {A[ba], B[bb] * (dp < 0.0f ? -1.0f : 1.0f)};
+}
+
+// q1's cross member that best matches q0 (q1 rotated into q0's frame).
+inline vec3 alignTo(const vec3& q0, const vec3& n0, const vec3& q1, const vec3& n1) {
+ const vec3 t1 = glm::cross(n1, q1);
+ const vec3 cands[4] = {q1, t1, -q1, -t1};
+ int best = 0;
+ float bd = -2.0f;
+ for (int k = 0; k < 4; ++k)
+ if (const float d = glm::dot(q0, cands[k]); d > bd) bd = d, best = k;
+ return cands[best];
+}
+
+// The point minimising the distance to p0 and p1 while lying on both tangent planes (Instant Meshes).
+inline vec3 middlePoint(const vec3& p0, const vec3& n0, const vec3& p1, const vec3& n1) {
+ const float n0p0 = glm::dot(n0, p0), n0p1 = glm::dot(n0, p1), n1p0 = glm::dot(n1, p0), n1p1 = glm::dot(n1, p1);
+ const float n0n1 = glm::dot(n0, n1), denom = 1.0f / (1.0f - n0n1 * n0n1 + 1e-4f);
+ const float l0 = 2.0f * (n0p1 - n0p0 - n0n1 * (n1p0 - n1p1)) * denom;
+ const float l1 = 2.0f * (n1p0 - n1p1 - n0n1 * (n0p1 - n0p0)) * denom;
+ return 0.5f * (p0 + p1) - 0.25f * (n0 * l0 + n1 * l1);
+}
+
+inline ivec2 floorIndex(const vec3& o, const vec3& q, const vec3& t, float inv, const vec3& p) {
+ const vec3 d = p - o;
+ return {int(std::floor(glm::dot(q, d) * inv)), int(std::floor(glm::dot(t, d) * inv))};
+}
+
+inline vec3 latticePoint(const vec3& o, const vec3& q, const vec3& t, float s, ivec2 i) {
+ return o + q * (float(i.x) * s) + t * (float(i.y) * s);
+}
+
+// The lattice corners of vertex 0 and vertex 1 (q1 already aligned with q0) nearest each other around the
+// middle of the two vertices, as lattice indices relative to o0 / o1, and their squared distance.
+inline float compatIndex(const vec3& v0, const vec3& n0, const vec3& q0, const vec3& o0, float s0, const vec3& v1,
+ const vec3& n1, const vec3& q1, const vec3& o1, float s1, ivec2& i0, ivec2& i1) {
+ const vec3 t0 = glm::cross(n0, q0), t1 = glm::cross(n1, q1);
+ const vec3 mid = middlePoint(v0, n0, v1, n1);
+ const ivec2 b0 = floorIndex(o0, q0, t0, 1.0f / s0, mid), b1 = floorIndex(o1, q1, t1, 1.0f / s1, mid);
+ float best = std::numeric_limits<float>::max();
+ for (int a = 0; a < 4; ++a) {
+ const ivec2 c0 = b0 + ivec2(a & 1, a >> 1);
+ const vec3 p0 = latticePoint(o0, q0, t0, s0, c0);
+ for (int b = 0; b < 4; ++b) {
+ const ivec2 c1 = b1 + ivec2(b & 1, b >> 1);
+ const vec3 d = p0 - latticePoint(o1, q1, t1, s1, c1);
+ const float cost = glm::dot(d, d);
+ if (cost < best) best = cost, i0 = c0, i1 = c1;
+ }
+ }
+ return best;
+}
+
+inline vec3 positionRound(const vec3& o, const vec3& q, const vec3& n, const vec3& p, float s) {
+ const vec3 t = glm::cross(n, q), d = p - o;
+ const float inv = 1.0f / s;
+ return o + q * (std::round(glm::dot(q, d) * inv) * s) + t * (std::round(glm::dot(t, d) * inv) * s);
+}
+
+// --- Working surface ------------------------------------------------------------------------------------
+
+struct WorkMesh {
+ std::vector<vec3> P;
+ std::vector<glm::uvec3> T;
+ std::vector<uint32_t> group; // per triangle
+ std::vector<vec3> color; // per vertex (only with usePolypaint)
+ std::vector<uint8_t> cutEdge; // filled later: per boundary segment, 1 = made by the symmetry cut
+};
+
+// Keeps the side of the plane (axis coordinate >= 0), splitting the triangles that cross it.
+WorkMesh cutAtPlane(const WorkMesh& in, int axis, float eps) {
+ WorkMesh out;
+ std::vector<vec3> P = in.P;
+ for (vec3& p : P)
+ if (std::abs(p[axis]) <= eps) p[axis] = 0.0f;
+ std::vector<uint32_t> remap(P.size(), kNone);
+ auto keep = [&](uint32_t v) {
+ if (remap[v] == kNone) {
+ remap[v] = uint32_t(out.P.size());
+ out.P.push_back(P[v]);
+ if (!in.color.empty()) out.color.push_back(in.color[v]);
+ }
+ return remap[v];
+ };
+ std::unordered_map<uint64_t, uint32_t> cuts;
+ auto cutPoint = [&](uint32_t a, uint32_t b) {
+ auto [it, inserted] = cuts.try_emplace(edgeKey(a, b), 0);
+ if (inserted) {
+ const float t = P[a][axis] / (P[a][axis] - P[b][axis]);
+ vec3 p = glm::mix(P[a], P[b], t);
+ p[axis] = 0.0f;
+ it->second = uint32_t(out.P.size());
+ out.P.push_back(p);
+ if (!in.color.empty()) out.color.push_back(glm::mix(in.color[a], in.color[b], t));
+ }
+ return it->second;
+ };
+ for (size_t t = 0; t < in.T.size(); ++t) {
+ const glm::uvec3 tri = in.T[t];
+ int side[3];
+ bool anyPos = false, anyNeg = false;
+ for (int k = 0; k < 3; ++k) {
+ const float x = P[tri[k]][axis];
+ side[k] = x > 0.0f ? 1 : x < 0.0f ? -1 : 0;
+ anyPos |= side[k] > 0;
+ anyNeg |= side[k] < 0;
+ }
+ if (!anyPos) continue;
+ uint32_t poly[4];
+ int n = 0;
+ if (!anyNeg) {
+ for (int k = 0; k < 3; ++k) poly[n++] = keep(tri[k]);
+ } else {
+ for (int k = 0; k < 3; ++k) {
+ const uint32_t a = tri[k], b = tri[(k + 1) % 3];
+ if (side[k] >= 0) poly[n++] = keep(a);
+ if ((side[k] > 0 && side[(k + 1) % 3] < 0) || (side[k] < 0 && side[(k + 1) % 3] > 0)) poly[n++] = cutPoint(a, b);
+ }
+ }
+ for (int k = 1; k + 1 < n; ++k) {
+ out.T.push_back({poly[0], poly[k], poly[k + 1]});
+ out.group.push_back(in.group[t]);
+ }
+ }
+ return out;
+}
+
+// Splits edges longer than `maxEdge` at their midpoints (each triangle into 2, 3 or 4, conforming), pass after
+// pass, so coarse parts of the input (a low-poly base under a dense sculpt) are dense enough for the fields.
+// Stops early when the triangle count would pass `maxTriangles`.
+WorkMesh refineLongEdges(WorkMesh m, float maxEdge, size_t maxTriangles) {
+ const float max2 = maxEdge * maxEdge;
+ for (int pass = 0; pass < 12; ++pass) {
+ std::unordered_map<uint64_t, uint32_t> mids;
+ auto longEdge = [&](uint32_t a, uint32_t b) { return glm::dot(m.P[a] - m.P[b], m.P[a] - m.P[b]) > max2; };
+ size_t extra = 0;
+ for (const glm::uvec3& t : m.T)
+ for (int k = 0; k < 3; ++k)
+ if (longEdge(t[k], t[(k + 1) % 3])) ++extra;
+ if (extra == 0 || m.T.size() + extra > maxTriangles) break;
+ auto mid = [&](uint32_t a, uint32_t b) {
+ auto [it, inserted] = mids.try_emplace(edgeKey(a, b), uint32_t(m.P.size()));
+ if (inserted) {
+ m.P.push_back(0.5f * (m.P[a] + m.P[b]));
+ if (!m.color.empty()) m.color.push_back(0.5f * (m.color[a] + m.color[b]));
+ }
+ return it->second;
+ };
+ std::vector<glm::uvec3> T;
+ std::vector<uint32_t> G;
+ T.reserve(m.T.size() + extra);
+ G.reserve(m.T.size() + extra);
+ for (size_t i = 0; i < m.T.size(); ++i) {
+ const glm::uvec3 t = m.T[i];
+ const uint32_t g = m.group[i];
+ uint32_t mk[3];
+ int marked = 0, first = -1;
+ for (int k = 0; k < 3; ++k) {
+ mk[k] = longEdge(t[k], t[(k + 1) % 3]) ? mid(t[k], t[(k + 1) % 3]) : kNone;
+ if (mk[k] != kNone) {
+ ++marked;
+ if (first < 0) first = k;
+ }
+ }
+ auto emit = [&](uint32_t a, uint32_t b, uint32_t c) {
+ T.push_back({a, b, c});
+ G.push_back(g);
+ };
+ if (marked == 0) {
+ emit(t.x, t.y, t.z);
+ } else if (marked == 3) {
+ emit(t.x, mk[0], mk[2]);
+ emit(mk[0], t.y, mk[1]);
+ emit(mk[2], mk[1], t.z);
+ emit(mk[0], mk[1], mk[2]);
+ } else if (marked == 1) {
+ const int k = first;
+ const uint32_t a = t[k], b = t[(k + 1) % 3], c = t[(k + 2) % 3], ab = mk[k];
+ emit(a, ab, c);
+ emit(ab, b, c);
+ } else { // two edges: the unmarked one is (c, a) after rotating so edges k and k+1 are marked
+ int k = 0;
+ while (!(mk[k] != kNone && mk[(k + 1) % 3] != kNone)) ++k;
+ const uint32_t a = t[k], b = t[(k + 1) % 3], c = t[(k + 2) % 3], ab = mk[k], bc = mk[(k + 1) % 3];
+ emit(ab, b, bc);
+ emit(a, ab, bc);
+ emit(a, bc, c);
+ }
+ }
+ m.T.swap(T);
+ m.group.swap(G);
+ }
+ return m;
+}
+
+// --- Hierarchy ------------------------------------------------------------------------------------------
+
+enum : uint8_t { kFree = 0, kLine = 1, kPoint = 2 };
+
+struct Level {
+ std::vector<vec3> V, N;
+ std::vector<float> A;
+ std::vector<uint32_t> off, adj; // CSR adjacency
+ std::vector<float> w;
+ std::vector<uint32_t> up; // index of the merged vertex in the next (coarser) level
+ // Constraints: kLine = the lattice has a line through cpos along cdir; kPoint = a lattice corner at cpos.
+ std::vector<uint8_t> ctype;
+ std::vector<vec3> cdir, cpos;
+ std::vector<uint8_t> boundary; // on an open edge of the mesh
+ std::vector<vec3> color; // polypaint (usePolypaint only)
+ // Fields.
+ std::vector<vec3> Q, O;
+ std::vector<float> S;
+ std::vector<std::vector<uint32_t>> phases; // independent sets for parallel Gauss-Seidel
+ float meanEdge = 0.0f;
+
+ size_t size() const { return V.size(); }
+};
+
+void computePhases(Level& l) {
+ l.phases.clear();
+ const size_t n = l.size();
+ if (n < 4000) { // sequential sweeps: one phase in index order
+ l.phases.emplace_back(n);
+ std::iota(l.phases[0].begin(), l.phases[0].end(), 0u);
+ return;
+ }
+ std::vector<uint8_t> color(n, 255);
+ std::vector<uint8_t> used;
+ for (uint32_t i = 0; i < n; ++i) {
+ used.assign(64, 0);
+ for (uint32_t k = l.off[i]; k < l.off[i + 1]; ++k)
+ if (color[l.adj[k]] < 64) used[color[l.adj[k]]] = 1;
+ uint8_t c = 0;
+ while (c < 63 && used[c]) ++c;
+ color[i] = c;
+ if (c >= l.phases.size()) l.phases.resize(c + 1);
+ l.phases[c].push_back(i);
+ }
+}
+
+void computeMeanEdge(Level& l) {
+ double sum = 0.0;
+ size_t cnt = 0;
+ for (uint32_t i = 0; i < l.size(); ++i)
+ for (uint32_t k = l.off[i]; k < l.off[i + 1]; ++k) {
+ sum += glm::length(l.V[i] - l.V[l.adj[k]]);
+ ++cnt;
+ }
+ l.meanEdge = cnt ? float(sum / double(cnt)) : 0.0f;
+}
+
+// Level 0 from the working mesh: vertex graph, area-weighted normals, constraints on open edges and (with
+// keepGroups) polygroup borders.
+Level buildFinest(const WorkMesh& m, bool keepGroups, float sharpCos, std::vector<std::pair<vec3, vec3>>& boundarySegs,
+ std::vector<uint8_t>& boundarySegIsCut, std::vector<std::pair<vec3, vec3>>& borderSegs, int symAxis) {
+ Level l;
+ const size_t nv = m.P.size();
+ l.V = m.P;
+ l.N.assign(nv, vec3(0.0f));
+ l.A.assign(nv, 0.0f);
+ for (const glm::uvec3& t : m.T) {
+ const vec3 n = glm::cross(m.P[t.y] - m.P[t.x], m.P[t.z] - m.P[t.x]);
+ const float a = 0.5f * glm::length(n);
+ for (int k = 0; k < 3; ++k) {
+ l.N[t[k]] += n;
+ l.A[t[k]] += a / 3.0f;
+ }
+ }
+ for (auto& n : l.N) n = safeNormalize(n);
+
+ // Edges with the triangles on each side.
+ struct EdgeInfo {
+ uint32_t a, b;
+ uint32_t t0, t1;
+ int count;
+ };
+ std::unordered_map<uint64_t, uint32_t> edgeIndex;
+ edgeIndex.reserve(m.T.size() * 2);
+ std::vector<EdgeInfo> edges;
+ edges.reserve(m.T.size() * 3 / 2 + 16);
+ for (uint32_t t = 0; t < m.T.size(); ++t)
+ for (int k = 0; k < 3; ++k) {
+ const uint32_t a = m.T[t][k], b = m.T[t][(k + 1) % 3];
+ if (a == b) continue;
+ auto [it, inserted] = edgeIndex.try_emplace(edgeKey(a, b), uint32_t(edges.size()));
+ if (inserted)
+ edges.push_back({std::min(a, b), std::max(a, b), t, kNone, 1});
+ else {
+ EdgeInfo& e = edges[it->second];
+ if (e.count == 1) e.t1 = t;
+ ++e.count;
+ }
+ }
+ // CSR adjacency.
+ l.off.assign(nv + 1, 0);
+ for (const EdgeInfo& e : edges) ++l.off[e.a + 1], ++l.off[e.b + 1];
+ for (size_t i = 0; i < nv; ++i) l.off[i + 1] += l.off[i];
+ l.adj.resize(l.off[nv]);
+ l.w.assign(l.off[nv], 1.0f);
+ {
+ std::vector<uint32_t> fill(l.off.begin(), l.off.end() - 1);
+ for (const EdgeInfo& e : edges) {
+ l.adj[fill[e.a]++] = e.b;
+ l.adj[fill[e.b]++] = e.a;
+ }
+ }
+
+ // Feature edges: open edges and polygroup borders.
+ l.ctype.assign(nv, kFree);
+ l.cdir.assign(nv, vec3(0.0f));
+ l.cpos = l.V;
+ l.boundary.assign(nv, 0);
+ std::vector<std::vector<uint32_t>> featureNb(nv);
+ for (const EdgeInfo& e : edges) {
+ const bool open = e.count == 1;
+ bool border = keepGroups && e.count == 2 && m.group[e.t0] != m.group[e.t1];
+ if (!border && sharpCos < 1.0f && e.count == 2) { // a hard edge (Detect Edges)
+ const glm::uvec3 a = m.T[e.t0], b = m.T[e.t1];
+ const vec3 na = safeNormalize(glm::cross(m.P[a.y] - m.P[a.x], m.P[a.z] - m.P[a.x]));
+ const vec3 nb = safeNormalize(glm::cross(m.P[b.y] - m.P[b.x], m.P[b.z] - m.P[b.x]));
+ border = glm::dot(na, nb) < sharpCos;
+ }
+ if (!open && !border) continue;
+ featureNb[e.a].push_back(e.b);
+ featureNb[e.b].push_back(e.a);
+ if (open) {
+ l.boundary[e.a] = l.boundary[e.b] = 1;
+ boundarySegs.push_back({m.P[e.a], m.P[e.b]});
+ boundarySegIsCut.push_back(symAxis >= 0 && m.P[e.a][symAxis] == 0.0f && m.P[e.b][symAxis] == 0.0f);
+ } else {
+ borderSegs.push_back({m.P[e.a], m.P[e.b]});
+ }
+ }
+ // Tangent of the feature curve at each vertex, smoothed along the curve (borders on triangle meshes zigzag).
+ std::vector<vec3> dir(nv, vec3(0.0f));
+ for (uint32_t v = 0; v < nv; ++v) {
+ const auto& f = featureNb[v];
+ if (f.size() == 2) dir[v] = safeNormalize(m.P[f[0]] - m.P[f[1]], vec3(0.0f));
+ }
+ for (int it = 0; it < 4; ++it) {
+ std::vector<vec3> next = dir;
+ for (uint32_t v = 0; v < nv; ++v) {
+ if (featureNb[v].size() != 2) continue;
+ vec3 sum = dir[v];
+ for (uint32_t u : featureNb[v])
+ if (featureNb[u].size() == 2) sum += glm::dot(dir[u], sum) < 0.0f ? -dir[u] : dir[u];
+ next[v] = safeNormalize(sum, dir[v]);
+ }
+ dir.swap(next);
+ }
+ for (uint32_t v = 0; v < nv; ++v) {
+ const size_t k = featureNb[v].size();
+ if (k == 0) continue;
+ if (k == 2) {
+ const vec3 d = dir[v] - l.N[v] * glm::dot(l.N[v], dir[v]);
+ if (glm::length(d) > 1e-6f) {
+ l.ctype[v] = kLine;
+ l.cdir[v] = glm::normalize(d);
+ continue;
+ }
+ }
+ l.ctype[v] = kPoint; // junction of several borders, or the end of one
+ }
+ if (!m.color.empty()) l.color = m.color;
+ computeMeanEdge(l);
+ return l;
+}
+
+// The next coarser level: greedy matching of neighbours with similar normals (Instant Meshes' ordering).
+bool downsample(Level& f, Level& c) {
+ const size_t n = f.size();
+ struct Entry {
+ uint32_t i, j;
+ float order;
+ };
+ std::vector<Entry> entries;
+ entries.reserve(f.adj.size() / 2);
+ for (uint32_t i = 0; i < n; ++i)
+ for (uint32_t k = f.off[i]; k < f.off[i + 1]; ++k) {
+ const uint32_t j = f.adj[k];
+ if (j <= i) continue;
+ const float ratio = f.A[i] > f.A[j] ? f.A[i] / std::max(f.A[j], 1e-30f) : f.A[j] / std::max(f.A[i], 1e-30f);
+ entries.push_back({i, j, glm::dot(f.N[i], f.N[j]) * ratio});
+ }
+ std::sort(entries.begin(), entries.end(), [](const Entry& a, const Entry& b) { return a.order > b.order; });
+
+ std::vector<uint32_t>& up = f.up;
+ up.assign(n, kNone);
+ const bool colors = !f.color.empty();
+ auto addVertex = [&](uint32_t i) {
+ up[i] = uint32_t(c.V.size());
+ c.V.push_back(f.V[i]);
+ c.N.push_back(f.N[i]);
+ c.A.push_back(f.A[i]);
+ c.ctype.push_back(f.ctype[i]);
+ c.cdir.push_back(f.cdir[i]);
+ c.cpos.push_back(f.cpos[i]);
+ c.boundary.push_back(f.boundary[i]);
+ if (colors) c.color.push_back(f.color[i]);
+ };
+ for (const Entry& e : entries) {
+ if (up[e.i] != kNone || up[e.j] != kNone) continue;
+ addVertex(e.i);
+ up[e.j] = up[e.i];
+ const uint32_t v = up[e.i];
+ const float ai = f.A[e.i], aj = f.A[e.j], a = std::max(ai + aj, 1e-30f);
+ c.V[v] = (f.V[e.i] * ai + f.V[e.j] * aj) / a;
+ c.N[v] = safeNormalize(f.N[e.i] * ai + f.N[e.j] * aj, f.N[e.i]);
+ c.A[v] = ai + aj;
+ if (colors) c.color[v] = (f.color[e.i] * ai + f.color[e.j] * aj) / a;
+ // Constraints: a point beats a line; otherwise keep the first child's.
+ if (f.ctype[e.j] > f.ctype[e.i]) {
+ c.ctype[v] = f.ctype[e.j];
+ c.cdir[v] = f.cdir[e.j];
+ c.cpos[v] = f.cpos[e.j];
+ }
+ c.boundary[v] |= f.boundary[e.j];
+ }
+ for (uint32_t i = 0; i < n; ++i)
+ if (up[i] == kNone) addVertex(i);
+ const size_t nc = c.V.size();
+ if (nc >= n) return false;
+
+ // Coarse adjacency: neighbours' parents, weights summed.
+ std::vector<std::vector<std::pair<uint32_t, float>>> lists(nc);
+ for (uint32_t i = 0; i < n; ++i)
+ for (uint32_t k = f.off[i]; k < f.off[i + 1]; ++k) {
+ const uint32_t a = up[i], b = up[f.adj[k]];
+ if (a != b) lists[a].push_back({b, f.w[k]});
+ }
+ c.off.assign(nc + 1, 0);
+ c.adj.clear();
+ c.w.clear();
+ for (uint32_t v = 0; v < nc; ++v) {
+ auto& l = lists[v];
+ std::sort(l.begin(), l.end(), [](auto& x, auto& y) { return x.first < y.first; });
+ for (size_t k = 0; k < l.size(); ++k) {
+ if (!c.adj.empty() && c.off[v] < c.adj.size() && c.adj.back() == l[k].first) {
+ c.w.back() += l[k].second;
+ continue;
+ }
+ c.adj.push_back(l[k].first);
+ c.w.push_back(l[k].second);
+ }
+ c.off[v + 1] = uint32_t(c.adj.size());
+ std::vector<std::pair<uint32_t, float>>().swap(l);
+ }
+ computeMeanEdge(c);
+ return true;
+}
+
+// --- Field solvers --------------------------------------------------------------------------------------
+
+void applyOrientationConstraint(const Level& l, uint32_t i, vec3& q) {
+ if (l.ctype[i] != kLine) return;
+ q = alignTo(q, l.N[i], l.cdir[i], l.N[i]);
+}
+
+void smoothOrientations(Level& l, int iterations) {
+ const auto& phases = l.phases;
+ for (int it = 0; it < iterations; ++it)
+ for (const auto& phase : phases)
+ parallelFor(phase.size(), [&](size_t b, size_t e) {
+ for (size_t k = b; k < e; ++k) {
+ const uint32_t i = phase[k];
+ const vec3 n = l.N[i];
+ vec3 sum = l.Q[i];
+ float wsum = 0.0f;
+ for (uint32_t a = l.off[i]; a < l.off[i + 1]; ++a) {
+ const uint32_t j = l.adj[a];
+ const float w = l.w[a];
+ const auto [x, y] = compatOrientation(sum, n, l.Q[j], l.N[j]);
+ sum = x * wsum + y * w;
+ sum -= n * glm::dot(n, sum);
+ wsum += w;
+ const float len = glm::length(sum);
+ if (len > 1e-20f) sum /= len;
+ }
+ if (glm::length(sum) < 0.5f) sum = l.Q[i];
+ applyOrientationConstraint(l, i, sum);
+ l.Q[i] = sum;
+ }
+ }, phases.size() > 1 ? 1000 : ~size_t(0)); // one phase = plain sequential sweep
+}
+
+void applyPositionConstraint(const Level& l, uint32_t i, const vec3& q, vec3& o) {
+ if (l.ctype[i] == kPoint) {
+ o = l.cpos[i] - l.N[i] * glm::dot(l.N[i], l.cpos[i] - l.V[i]);
+ } else if (l.ctype[i] == kLine) {
+ const vec3 perp = glm::cross(l.N[i], l.cdir[i]); // across the line, in the tangent plane
+ o -= perp * glm::dot(o - l.cpos[i], perp);
+ }
+}
+
+void smoothPositions(Level& l, int iterations) {
+ const auto& phases = l.phases;
+ for (int it = 0; it < iterations; ++it)
+ for (const auto& phase : phases)
+ parallelFor(phase.size(), [&](size_t b, size_t e) {
+ for (size_t k = b; k < e; ++k) {
+ const uint32_t i = phase[k];
+ const vec3 n = l.N[i], v = l.V[i], q = l.Q[i];
+ const float s = l.S[i];
+ vec3 sum = l.O[i];
+ float wsum = 0.0f;
+ for (uint32_t a = l.off[i]; a < l.off[i + 1]; ++a) {
+ const uint32_t j = l.adj[a];
+ const float w = l.w[a];
+ const vec3 qj = alignTo(q, n, l.Q[j], l.N[j]);
+ ivec2 i0, i1;
+ compatIndex(v, n, q, sum, s, l.V[j], l.N[j], qj, l.O[j], l.S[j], i0, i1);
+ const vec3 p0 = latticePoint(sum, q, glm::cross(n, q), s, i0);
+ const vec3 p1 = latticePoint(l.O[j], qj, glm::cross(l.N[j], qj), l.S[j], i1);
+ sum = (p0 * wsum + p1 * w) / (wsum + w);
+ wsum += w;
+ sum -= n * glm::dot(n, sum - v);
+ }
+ applyPositionConstraint(l, i, q, sum);
+ l.O[i] = positionRound(sum, q, n, v, s);
+ }
+ }, phases.size() > 1 ? 1000 : ~size_t(0)); // one phase = plain sequential sweep
+}
+
+// --- Extraction -----------------------------------------------------------------------------------------
+
+struct UnionFind {
+ std::vector<uint32_t> parent;
+ explicit UnionFind(size_t n) : parent(n) { std::iota(parent.begin(), parent.end(), 0u); }
+ uint32_t find(uint32_t x) {
+ while (parent[x] != x) x = parent[x] = parent[parent[x]];
+ return x;
+ }
+};
+
+struct PolyMesh {
+ std::vector<vec3> P, N;
+ std::vector<std::vector<uint32_t>> faces;
+ size_t cornerCount() const {
+ size_t c = 0;
+ for (const auto& f : faces) c += f.size();
+ return c;
+ }
+};
+
+// Turns the fields on level `l` into a polygon mesh (faces wound counter-clockwise about the normals).
+// Faces that are mostly mesh boundary (the outside of an open surface, the symmetry cut) are left out.
+PolyMesh extractPolygons(const Level& l) {
+ const size_t n = l.size();
+ struct Link {
+ uint32_t i, j;
+ float cost;
+ };
+ std::vector<Link> collapse, links;
+ for (uint32_t i = 0; i < n; ++i)
+ for (uint32_t a = l.off[i]; a < l.off[i + 1]; ++a) {
+ const uint32_t j = l.adj[a];
+ if (j <= i) continue;
+ const vec3 qj = alignTo(l.Q[i], l.N[i], l.Q[j], l.N[j]);
+ ivec2 i0, i1;
+ const float err = compatIndex(l.V[i], l.N[i], l.Q[i], l.O[i], l.S[i], l.V[j], l.N[j], qj, l.O[j], l.S[j], i0, i1);
+ const float s = 0.5f * (l.S[i] + l.S[j]);
+ if (err > 0.25f * s * s) continue; // the two lattices disagree here (near a singularity)
+ const ivec2 d = i0 - i1;
+ const int l1 = std::abs(d.x) + std::abs(d.y);
+ if (l1 == 0) collapse.push_back({i, j, glm::length(l.O[i] - l.O[j])});
+ else if (l1 == 1) links.push_back({i, j, 0.0f});
+ }
+ std::sort(collapse.begin(), collapse.end(), [](const Link& a, const Link& b) { return a.cost < b.cost; });
+
+ // Merge vertices that sit on the same lattice corner, unless that drags a cluster too far.
+ UnionFind uf(n);
+ std::vector<vec3> sum(l.O);
+ std::vector<float> cnt(n, 1.0f);
+ for (const Link& c : collapse) {
+ uint32_t a = uf.find(c.i), b = uf.find(c.j);
+ if (a == b) continue;
+ const float s = 0.5f * (l.S[c.i] + l.S[c.j]);
+ if (glm::length(sum[a] / cnt[a] - sum[b] / cnt[b]) > 0.45f * s) continue;
+ if (cnt[a] < cnt[b]) std::swap(a, b);
+ uf.parent[b] = a;
+ sum[a] += sum[b];
+ cnt[a] += cnt[b];
+ }
+ std::vector<uint32_t> cluster(n, kNone);
+ PolyMesh pm;
+ std::vector<vec3> qOf;
+ std::vector<float> area, scale;
+ std::vector<uint8_t> boundary;
+ for (uint32_t i = 0; i < n; ++i) {
+ const uint32_t r = uf.find(i);
+ if (cluster[r] == kNone) {
+ cluster[r] = uint32_t(pm.P.size());
+ pm.P.push_back(sum[r] / cnt[r]);
+ pm.N.push_back(vec3(0.0f));
+ qOf.push_back(l.Q[i]);
+ area.push_back(0.0f);
+ scale.push_back(0.0f);
+ boundary.push_back(0);
+ }
+ const uint32_t c = cluster[r];
+ cluster[i] = c;
+ pm.N[c] += l.N[i] * l.A[i];
+ area[c] += l.A[i];
+ scale[c] = std::max(scale[c], l.S[i]);
+ boundary[c] |= l.boundary[i];
+ }
+ const size_t nc = pm.P.size();
+ for (uint32_t c = 0; c < nc; ++c) pm.N[c] = safeNormalize(pm.N[c]);
+
+ // Graph edges between clusters one lattice step apart; tiny clusters (stray vertices at singularities) go.
+ std::vector<std::vector<uint32_t>> adj(nc);
+ std::vector<uint8_t> alive(nc, 1);
+ for (uint32_t c = 0; c < nc; ++c)
+ if (area[c] < 0.04f * scale[c] * scale[c]) alive[c] = 0;
+ for (const Link& e : links) {
+ const uint32_t a = cluster[e.i], b = cluster[e.j];
+ if (a == b || !alive[a] || !alive[b]) continue;
+ adj[a].push_back(b);
+ adj[b].push_back(a);
+ }
+ for (auto& a : adj) {
+ std::sort(a.begin(), a.end());
+ a.erase(std::unique(a.begin(), a.end()), a.end());
+ }
+ auto removeEdge = [&](uint32_t a, uint32_t b) {
+ adj[a].erase(std::remove(adj[a].begin(), adj[a].end(), b), adj[a].end());
+ adj[b].erase(std::remove(adj[b].begin(), adj[b].end(), a), adj[b].end());
+ };
+ auto hasEdge = [&](uint32_t a, uint32_t b) { return std::binary_search(adj[a].begin(), adj[a].end(), b); };
+ auto len2 = [&](uint32_t a, uint32_t b) { return glm::dot(pm.P[a] - pm.P[b], pm.P[a] - pm.P[b]); };
+
+ // A quad lattice has no 3-cycles: drop the longest edge of each (a diagonal from a lattice mismatch).
+ for (int round = 0; round < 8; ++round) {
+ std::vector<std::pair<uint32_t, uint32_t>> drop;
+ for (uint32_t u = 0; u < nc; ++u)
+ for (uint32_t v : adj[u]) {
+ if (v <= u) continue;
+ for (uint32_t w : adj[u]) {
+ if (w <= v || !hasEdge(v, w)) continue;
+ std::pair<uint32_t, uint32_t> e{u, v};
+ float best = len2(u, v);
+ if (const float d = len2(v, w); d > best) best = d, e = {v, w};
+ if (const float d = len2(u, w); d > best) best = d, e = {u, w};
+ drop.push_back(e);
+ }
+ }
+ if (drop.empty()) break;
+ for (auto [a, b] : drop)
+ if (hasEdge(a, b)) removeEdge(a, b);
+ }
+
+ std::vector<std::vector<uint32_t>> faces;
+ for (int round = 0; round < 16; ++round) {
+ // Dangling vertices (fewer than two edges) can't bound a face.
+ std::vector<uint32_t> stack;
+ for (uint32_t u = 0; u < nc; ++u)
+ if (adj[u].size() == 1) stack.push_back(u);
+ while (!stack.empty()) {
+ const uint32_t u = stack.back();
+ stack.pop_back();
+ if (adj[u].size() != 1) continue;
+ const uint32_t v = adj[u][0];
+ removeEdge(u, v);
+ if (adj[v].size() == 1) stack.push_back(v);
+ }
+ // Rotation system: neighbours counter-clockwise about the vertex normal.
+ std::vector<std::vector<uint32_t>> ring(nc);
+ std::vector<uint32_t> heOff(nc + 1, 0);
+ for (uint32_t u = 0; u < nc; ++u) {
+ const vec3 nn = pm.N[u];
+ vec3 q = qOf[u] - nn * glm::dot(nn, qOf[u]);
+ q = glm::length(q) > 1e-6f ? glm::normalize(q) : anyTangent(nn);
+ const vec3 t = glm::cross(nn, q);
+ std::vector<std::pair<float, uint32_t>> ang;
+ for (uint32_t v : adj[u]) {
+ const vec3 d = pm.P[v] - pm.P[u];
+ ang.push_back({std::atan2(glm::dot(d, t), glm::dot(d, q)), v});
+ }
+ std::sort(ang.begin(), ang.end());
+ for (auto& [a, v] : ang) ring[u].push_back(v);
+ heOff[u + 1] = heOff[u] + uint32_t(ring[u].size());
+ }
+ auto slot = [&](uint32_t u, uint32_t v) { // index of v in u's ring
+ const auto& r = ring[u];
+ return uint32_t(std::find(r.begin(), r.end(), v) - r.begin());
+ };
+ std::vector<uint8_t> used(heOff[nc], 0);
+ faces.clear();
+ std::vector<std::pair<uint32_t, uint32_t>> bad;
+ for (uint32_t u0 = 0; u0 < nc; ++u0)
+ for (uint32_t k0 = 0; k0 < ring[u0].size(); ++k0) {
+ if (used[heOff[u0] + k0]) continue;
+ std::vector<uint32_t> face;
+ uint32_t u = u0, k = k0;
+ while (!used[heOff[u] + k]) {
+ used[heOff[u] + k] = 1;
+ face.push_back(u);
+ const uint32_t v = ring[u][k];
+ const uint32_t back = slot(v, u);
+ const uint32_t deg = uint32_t(ring[v].size());
+ k = (back + deg - 1) % deg; // next face edge: the neighbour before u, clockwise turn
+ u = v;
+ }
+ // An edge walked both ways in one face is a bridge, not a face side: drop it and retrace.
+ std::unordered_map<uint64_t, int> seen;
+ for (size_t a = 0; a < face.size(); ++a) {
+ const uint64_t key = edgeKey(face[a], face[(a + 1) % face.size()]);
+ if (++seen[key] == 2) bad.push_back({face[a], face[(a + 1) % face.size()]});
+ }
+ faces.push_back(std::move(face));
+ }
+ if (bad.empty() || round == 15) break;
+ for (auto [a, b] : bad)
+ if (std::find(adj[a].begin(), adj[a].end(), b) != adj[a].end()) removeEdge(a, b);
+ }
+
+ // Keep the faces; leave the outside of open surfaces open.
+ std::vector<uint32_t> remap(nc, kNone);
+ PolyMesh out;
+ for (auto& f : faces) {
+ if (f.size() < 3) continue;
+ if (f.size() >= 5) {
+ size_t onBoundary = 0;
+ for (uint32_t v : f) onBoundary += boundary[v];
+ if (onBoundary * 10 >= f.size() * 6) continue;
+ }
+ // Drop a face whose edge appears twice (left after the retrace limit).
+ bool twice = false;
+ {
+ std::unordered_map<uint64_t, int> seen;
+ for (size_t a = 0; a < f.size(); ++a)
+ if (++seen[edgeKey(f[a], f[(a + 1) % f.size()])] == 2) twice = true;
+ }
+ if (twice) continue;
+ for (uint32_t& v : f) {
+ if (remap[v] == kNone) {
+ remap[v] = uint32_t(out.P.size());
+ out.P.push_back(pm.P[v]);
+ out.N.push_back(pm.N[v]);
+ }
+ v = remap[v];
+ }
+ out.faces.push_back(std::move(f));
+ }
+ return out;
+}
+
+// Faces with six or more sides are cut along inside diagonals into quads (and at most one pentagon), so the
+// quad split doesn't leave a star of six or more quads around one centre.
+void splitLargeFaces(PolyMesh& pm) {
+ std::vector<std::vector<uint32_t>> out, todo = std::move(pm.faces);
+ std::unordered_map<uint64_t, int> edges; // existing edges: a diagonal must not duplicate one
+ for (const auto& f : todo)
+ for (size_t k = 0; k < f.size(); ++k) edges[edgeKey(f[k], f[(k + 1) % f.size()])] = 1;
+ while (!todo.empty()) {
+ std::vector<uint32_t> f = std::move(todo.back());
+ todo.pop_back();
+ const size_t n = f.size();
+ if (n <= 5) {
+ out.push_back(std::move(f));
+ continue;
+ }
+ // The face flattened onto its own plane.
+ vec3 nrm(0.0f), c(0.0f);
+ for (size_t k = 0; k < n; ++k) {
+ nrm += glm::cross(pm.P[f[k]], pm.P[f[(k + 1) % n]]);
+ c += pm.P[f[k]];
+ }
+ c /= float(n);
+ nrm = safeNormalize(nrm, pm.N[f[0]]);
+ const vec3 ax = anyTangent(nrm), ay = glm::cross(nrm, ax);
+ std::vector<glm::vec2> q(n);
+ float perimeter = 0.0f;
+ for (size_t k = 0; k < n; ++k) {
+ q[k] = {glm::dot(pm.P[f[k]] - c, ax), glm::dot(pm.P[f[k]] - c, ay)};
+ perimeter += glm::length(pm.P[f[k]] - pm.P[f[(k + 1) % n]]);
+ }
+ auto cross2 = [](glm::vec2 a, glm::vec2 b) { return a.x * b.y - a.y * b.x; };
+ auto segmentsCross = [&](glm::vec2 a, glm::vec2 b, glm::vec2 p, glm::vec2 r) {
+ const float d1 = cross2(b - a, p - a), d2 = cross2(b - a, r - a);
+ const float d3 = cross2(r - p, a - p), d4 = cross2(r - p, b - p);
+ return ((d1 > 0) != (d2 > 0)) && ((d3 > 0) != (d4 > 0));
+ };
+ auto inside = [&](glm::vec2 p) {
+ bool in = false;
+ for (size_t k = 0, l = n - 1; k < n; l = k++)
+ if ((q[k].y > p.y) != (q[l].y > p.y) && p.x < (q[l].x - q[k].x) * (p.y - q[k].y) / (q[l].y - q[k].y) + q[k].x)
+ in = !in;
+ return in;
+ };
+ float best = std::numeric_limits<float>::max();
+ size_t bi = 0, bj = 0;
+ for (size_t i = 0; i < n; ++i)
+ for (size_t j = i + 3; j < n; ++j) {
+ const size_t a = j - i + 1, b = n - (j - i) + 1;
+ if (b < 4 || f[i] == f[j] || edges.count(edgeKey(f[i], f[j]))) continue;
+ bool ok = inside(0.5f * (q[i] + q[j]));
+ for (size_t k = 0; k < n && ok; ++k) {
+ const size_t l = (k + 1) % n;
+ if (k == i || l == i || k == j || l == j) continue;
+ if (segmentsCross(q[i], q[j], q[k], q[l])) ok = false;
+ }
+ if (!ok) continue;
+ // Short diagonals and even (quad-friendly) halves first.
+ float score = glm::length(pm.P[f[i]] - pm.P[f[j]]) / perimeter;
+ if (a % 2) score += 0.25f;
+ if (b % 2) score += 0.25f;
+ score += 0.02f * float(std::max(a, b) - std::min(a, b));
+ if (score < best) best = score, bi = i, bj = j;
+ }
+ if (best == std::numeric_limits<float>::max()) {
+ out.push_back(std::move(f));
+ continue;
+ }
+ edges[edgeKey(f[bi], f[bj])] = 1;
+ std::vector<uint32_t> fa(f.begin() + long(bi), f.begin() + long(bj) + 1), fb(f.begin() + long(bj), f.end());
+ fb.insert(fb.end(), f.begin(), f.begin() + long(bi) + 1);
+ todo.push_back(std::move(fa));
+ todo.push_back(std::move(fb));
+ }
+ pm.faces = std::move(out);
+}
+
+// --- Quads, relaxation, attributes ----------------------------------------------------------------------
+
+struct QuadMesh {
+ std::vector<vec3> P;
+ std::vector<glm::uvec4> quads; // counter-clockwise
+};
+
+// Every n-sided face becomes n quads (corner, edge midpoint, centre, edge midpoint).
+QuadMesh splitIntoQuads(const PolyMesh& pm) {
+ QuadMesh q;
+ q.P = pm.P;
+ std::unordered_map<uint64_t, uint32_t> mids;
+ auto mid = [&](uint32_t a, uint32_t b) {
+ auto [it, inserted] = mids.try_emplace(edgeKey(a, b), uint32_t(q.P.size()));
+ if (inserted) q.P.push_back(0.5f * (pm.P[a] + pm.P[b]));
+ return it->second;
+ };
+ for (const auto& f : pm.faces) {
+ const size_t n = f.size();
+ vec3 c(0.0f);
+ for (uint32_t v : f) c += pm.P[v];
+ const uint32_t center = uint32_t(q.P.size());
+ q.P.push_back(c / float(n));
+ for (size_t k = 0; k < n; ++k) {
+ const uint32_t prev = f[(k + n - 1) % n], cur = f[k], next = f[(k + 1) % n];
+ q.quads.push_back({cur, mid(cur, next), center, mid(prev, cur)});
+ }
+ }
+ return q;
+}
+
+// A vertex inside the surface with only two quads (a "doublet", left where a two-sided face met a corner)
+// adds nothing: the two quads become one. Unused vertices are dropped afterwards.
+void removeDoublets(QuadMesh& q) {
+ for (int pass = 0; pass < 6; ++pass) {
+ const size_t nv = q.P.size();
+ std::vector<std::vector<uint32_t>> vq(nv);
+ for (uint32_t f = 0; f < q.quads.size(); ++f)
+ for (int k = 0; k < 4; ++k) vq[q.quads[f][k]].push_back(f);
+ std::vector<uint8_t> dead(q.quads.size(), 0), touched(nv, 0);
+ auto rotated = [&](uint32_t f, uint32_t v) {
+ glm::uvec4 r = q.quads[f];
+ for (int k = 0; k < 4 && r.x != v; ++k) r = {r.y, r.z, r.w, r.x};
+ return r;
+ };
+ bool any = false;
+ for (uint32_t v = 0; v < nv; ++v) {
+ if (vq[v].size() != 2 || touched[v]) continue;
+ const uint32_t fa = vq[v][0], fb = vq[v][1];
+ const glm::uvec4 A = rotated(fa, v), B = rotated(fb, v); // (v, a, x, c) and (v, c, y, a)
+ if (A.x != v || B.x != v || B.y != A.w || B.w != A.y || A.z == B.z) continue;
+ bool busy = false;
+ for (int k = 0; k < 4; ++k) busy |= touched[A[k]] || touched[B[k]];
+ if (busy) continue;
+ q.quads[fa] = {A.y, A.z, A.w, B.z};
+ dead[fb] = 1;
+ for (int k = 0; k < 4; ++k) touched[A[k]] = touched[B[k]] = 1;
+ any = true;
+ }
+ if (!any) break;
+ size_t w = 0;
+ for (size_t f = 0; f < q.quads.size(); ++f)
+ if (!dead[f]) q.quads[w++] = q.quads[f];
+ q.quads.resize(w);
+ }
+ std::vector<uint32_t> remap(q.P.size(), kNone);
+ std::vector<vec3> P;
+ for (auto& f : q.quads)
+ for (int k = 0; k < 4; ++k) {
+ if (remap[f[k]] == kNone) {
+ remap[f[k]] = uint32_t(P.size());
+ P.push_back(q.P[f[k]]);
+ }
+ f[k] = remap[f[k]];
+ }
+ q.P.swap(P);
+}
+
+struct Snapper {
+ const TriangleBVH* surface = nullptr;
+ const SegmentBVH* boundary = nullptr; // open edges of the source (incl. the symmetry cut)
+ const SegmentBVH* borders = nullptr; // polygroup borders (Keep Groups)
+ float reach = 1.0f;
+};
+
+// Tangential relaxation on the source surface; vertices on open edges stay on the source's open edges, those
+// on polygroup borders on the borders.
+void relax(QuadMesh& q, const Snapper& snap, int iterations, float edge, const QRemeshProgress& progress, float p0,
+ float p1, bool& cancelled) {
+ const size_t nv = q.P.size();
+ // Neighbours and open edges from the quads.
+ std::unordered_map<uint64_t, int> edgeUse;
+ for (const auto& f : q.quads)
+ for (int k = 0; k < 4; ++k) ++edgeUse[edgeKey(f[k], f[(k + 1) % 4])];
+ std::vector<std::vector<uint32_t>> nb(nv);
+ std::vector<uint8_t> open(nv, 0);
+ for (auto [key, uses] : edgeUse) {
+ const uint32_t a = uint32_t(key >> 32), b = uint32_t(key & 0xffffffffu);
+ nb[a].push_back(b);
+ nb[b].push_back(a);
+ if (uses == 1) open[a] = open[b] = 2; // 2 = open-edge vertex, 1 = polygroup border vertex
+ }
+ std::vector<std::vector<uint32_t>> openNb(nv);
+ for (auto [key, uses] : edgeUse) {
+ if (uses != 1) continue;
+ const uint32_t a = uint32_t(key >> 32), b = uint32_t(key & 0xffffffffu);
+ openNb[a].push_back(b);
+ openNb[b].push_back(a);
+ }
+ auto project = [&](uint32_t v, const vec3& p, vec3& normal) {
+ SurfaceHit hit;
+ if (open[v] == 2 && snap.boundary && snap.boundary->closestPoint(p, snap.reach, hit)) {
+ normal = vec3(0.0f);
+ return hit.position;
+ }
+ if (open[v] == 1 && snap.borders && snap.borders->closestPoint(p, snap.reach, hit)) {
+ normal = vec3(0.0f);
+ return hit.position;
+ }
+ if (snap.surface->closestPoint(p, snap.reach, hit)) {
+ normal = snap.surface->faceNormal(hit.prim);
+ return hit.position;
+ }
+ normal = vec3(0.0f);
+ return p;
+ };
+ std::vector<vec3> normal(nv, vec3(0.0f));
+ parallelFor(nv, [&](size_t b, size_t e) {
+ for (size_t v = b; v < e; ++v) q.P[v] = project(uint32_t(v), q.P[v], normal[v]);
+ });
+ // Polygroup-border vertices: within a fifth of an edge of a border.
+ if (snap.borders && !snap.borders->empty())
+ for (uint32_t v = 0; v < nv; ++v) {
+ SurfaceHit hit;
+ if (open[v] == 0 && snap.borders->closestPoint(q.P[v], 0.2f * edge, hit)) open[v] = 1;
+ }
+ std::vector<std::vector<uint32_t>> borderNb(nv);
+ for (uint32_t v = 0; v < nv; ++v)
+ if (open[v] == 1)
+ for (uint32_t u : nb[v])
+ if (open[u] == 1) borderNb[v].push_back(u);
+
+ std::vector<vec3> next(nv);
+ for (int it = 0; it < iterations; ++it) {
+ parallelFor(nv, [&](size_t b, size_t e) {
+ for (size_t v = b; v < e; ++v) {
+ const auto& ring = open[v] == 2 ? openNb[v] : open[v] == 1 && borderNb[v].size() == 2 ? borderNb[v] : nb[v];
+ if (ring.empty() || (open[v] == 1 && borderNb[v].size() != 2)) {
+ next[v] = q.P[v];
+ continue;
+ }
+ vec3 avg(0.0f);
+ for (uint32_t u : ring) avg += q.P[u];
+ avg /= float(ring.size());
+ vec3 d = avg - q.P[v];
+ if (open[v] == 0) d -= normal[v] * glm::dot(normal[v], d);
+ next[v] = q.P[v] + 0.6f * d;
+ }
+ });
+ parallelFor(nv, [&](size_t b, size_t e) {
+ for (size_t v = b; v < e; ++v) q.P[v] = project(uint32_t(v), next[v], normal[v]);
+ });
+ if (progress && !progress(p0 + (p1 - p0) * float(it + 1) / float(std::max(iterations, 1)))) {
+ cancelled = true;
+ return;
+ }
+ }
+}
+
+} // namespace
+
+bool qremesh(const Mesh& source, const QRemeshOptions& opt, Mesh& out, std::string& error,
+ const QRemeshProgress& progress, QRemeshStats* stats) {
+ const auto start = std::chrono::steady_clock::now();
+ static const bool timing = std::getenv("SF_QREMESH_TIMING") != nullptr; // stage times on stderr
+ auto report = [&](float f) {
+ if (timing)
+ std::fprintf(stderr, "qremesh %.2f: %.3f s\n", f,
+ std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count());
+ if (progress && !progress(std::clamp(f, 0.0f, 1.0f))) {
+ error = "QRemesh cancelled";
+ return false;
+ }
+ return true;
+ };
+ if (source.triangleCount() == 0) {
+ error = "QRemesh: the SubTool is empty";
+ return false;
+ }
+ const int target = std::clamp(opt.targetQuads, 16, 2'000'000);
+ const int axis = opt.symmetryAxis >= 0 && opt.symmetryAxis <= 2 ? opt.symmetryAxis : -1;
+
+ // Working surface (one half with symmetry).
+ WorkMesh work;
+ work.P = source.positions;
+ work.T = source.triangles;
+ work.group.resize(work.T.size());
+ for (uint32_t t = 0; t < work.T.size(); ++t) work.group[t] = source.polygroupAt(t);
+ if (opt.usePolypaint && source.hasColors()) work.color = source.colors;
+ const AABB box = source.bounds();
+ const float diag = glm::length(box.extent());
+ if (!(diag > 0.0f)) {
+ error = "QRemesh: the SubTool has no size";
+ return false;
+ }
+ if (axis >= 0) {
+ work = cutAtPlane(work, axis, 1e-6f * diag);
+ if (work.T.empty()) {
+ error = "QRemesh: nothing on the positive side of the symmetry plane";
+ return false;
+ }
+ }
+ double area = 0.0;
+ for (const glm::uvec3& t : work.T) area += 0.5 * glm::length(glm::cross(work.P[t.y] - work.P[t.x], work.P[t.z] - work.P[t.x]));
+ // Coarse lattice spacing: the extracted faces (about target / 4 of them, each split into ~4 quads).
+ const double faces = std::max(4.0, double(target) / 4.0 / (axis >= 0 ? 2.0 : 1.0));
+ float spacing = float(std::sqrt(area / faces));
+ const bool adaptive = opt.adaptive > 0.01f || !work.color.empty();
+ const float wantEdge = spacing / (adaptive ? 6.0f : 4.0f);
+
+ // Surface the quads snap to (before any subdivision for density: same surface).
+ TriangleBVH surface;
+ surface.build(work.P, work.T);
+ if (!report(0.05f)) return false;
+
+ std::vector<std::pair<vec3, vec3>> boundarySegs, borderSegs;
+ std::vector<uint8_t> boundaryIsCut;
+ work = refineLongEdges(std::move(work), 1.5f * wantEdge, std::max<size_t>(4'000'000, work.T.size()));
+ std::vector<Level> levels;
+ const float sharpCos = opt.detectEdges ? std::cos(glm::radians(50.0f)) : 2.0f;
+ levels.push_back(buildFinest(work, opt.keepGroups, sharpCos, boundarySegs, boundaryIsCut, borderSegs, axis));
+ if (!report(0.10f)) return false;
+ // Hierarchy down to a few vertices; fields are solved from the top to the finest level dense enough.
+ while (levels.back().size() > 64 && levels.size() < 40) {
+ Level c;
+ if (!downsample(levels.back(), c)) break;
+ if (c.size() > levels.back().size() * 95 / 100) {
+ levels.push_back(std::move(c));
+ break;
+ }
+ levels.push_back(std::move(c));
+ }
+ size_t base = 0;
+ while (base + 1 < levels.size() && levels[base + 1].meanEdge <= wantEdge) ++base;
+ if (!report(0.20f)) return false;
+ for (size_t i = base; i < levels.size(); ++i) computePhases(levels[i]);
+
+ // Orientation field, coarse to fine.
+ Rng rng(opt.seed);
+ {
+ Level& top = levels.back();
+ top.Q.resize(top.size());
+ for (uint32_t i = 0; i < top.size(); ++i) {
+ const vec3 t0 = anyTangent(top.N[i]), t1 = glm::cross(top.N[i], t0);
+ const float a = rng.next() * 6.2831853f;
+ top.Q[i] = t0 * std::cos(a) + t1 * std::sin(a);
+ applyOrientationConstraint(top, i, top.Q[i]);
+ }
+ }
+ for (size_t li = levels.size(); li-- > base;) {
+ Level& l = levels[li];
+ if (li + 1 < levels.size()) {
+ const Level& c = levels[li + 1];
+ l.Q.resize(l.size());
+ for (uint32_t i = 0; i < l.size(); ++i) {
+ const vec3 q = c.Q[l.up[i]];
+ const vec3 p = q - l.N[i] * glm::dot(l.N[i], q);
+ l.Q[i] = glm::length(p) > 1e-6f ? glm::normalize(p) : anyTangent(l.N[i]);
+ applyOrientationConstraint(l, i, l.Q[i]);
+ }
+ }
+ smoothOrientations(l, li == base ? 12 : 10);
+ if (!report(0.20f + 0.20f * float(levels.size() - li) / float(levels.size() - base))) return false;
+ }
+
+ // Scale field on the base level: curvature (Adaptive Size) and polypaint density, then normalised to the
+ // wanted number of faces and passed up the hierarchy.
+ Level& L = levels[base];
+ std::vector<float> rel(L.size(), 1.0f); // relative edge length
+ if (opt.adaptive > 0.01f) {
+ // Curvature: normal change per length (-1 = unknown, filled in from the neighbours).
+ std::vector<float> k(L.size(), -1.0f);
+ for (uint32_t i = 0; i < L.size(); ++i) {
+ if (L.ctype[i] != kFree) continue; // a feature's normal is the average of two sides
+ float s = 0.0f;
+ int c = 0;
+ for (uint32_t a = L.off[i]; a < L.off[i + 1]; ++a) {
+ const uint32_t j = L.adj[a];
+ const float d = glm::length(L.V[i] - L.V[j]);
+ // Normals jumping across a hard edge or a group border are features with their own loops, not
+ // curvature to pack quads into.
+ if (L.ctype[j] != kFree || glm::dot(L.N[i], L.N[j]) < sharpCos) continue;
+ if (d > 0.0f) s += glm::length(L.N[i] - L.N[j]) / d, ++c;
+ }
+ if (c) k[i] = s / float(c);
+ }
+ for (int it = 0; it < 6; ++it) {
+ std::vector<float> nk = k;
+ for (uint32_t i = 0; i < L.size(); ++i) {
+ float s = std::max(k[i], 0.0f);
+ int c = k[i] >= 0.0f;
+ for (uint32_t a = L.off[i]; a < L.off[i + 1]; ++a)
+ if (k[L.adj[a]] >= 0.0f) s += k[L.adj[a]], ++c;
+ nk[i] = c ? s / float(c) : -1.0f;
+ }
+ k.swap(nk);
+ }
+ // Relative to the median, but never finer than a bend of ~11 degrees per quad: flat models stay even.
+ std::vector<float> sorted;
+ for (float x : k)
+ if (x >= 0.0f) sorted.push_back(x);
+ float ref = 0.2f / spacing;
+ if (!sorted.empty()) {
+ std::nth_element(sorted.begin(), sorted.begin() + long(sorted.size() / 2), sorted.end());
+ ref = std::max(ref, sorted[sorted.size() / 2]);
+ }
+ for (uint32_t i = 0; i < L.size(); ++i)
+ rel[i] = k[i] < 0.0f ? 1.0f : std::clamp(std::pow(std::max(k[i], 1e-9f) / ref, -0.6f * opt.adaptive), 0.45f, 2.2f);
+ }
+ if (!L.color.empty())
+ for (uint32_t i = 0; i < L.size(); ++i) {
+ const vec3 c = L.color[i];
+ const float red = std::clamp(c.x - std::max(c.y, c.z), 0.0f, 1.0f);
+ const float blue = std::clamp(c.z - std::max(c.x, c.y), 0.0f, 1.0f);
+ rel[i] *= std::pow(2.0f, blue - red); // pure red: half the edge (4x the quads), pure blue: double
+ }
+ if (adaptive) // smooth the log of the size so it changes gradually
+ for (int it = 0; it < 8; ++it) {
+ std::vector<float> lr(L.size());
+ for (uint32_t i = 0; i < L.size(); ++i) {
+ float s = std::log(rel[i]);
+ int c = 1;
+ for (uint32_t a = L.off[i]; a < L.off[i + 1]; ++a) s += std::log(rel[L.adj[a]]), ++c;
+ lr[i] = std::exp(s / float(c));
+ }
+ rel.swap(lr);
+ }
+ auto setScale = [&](float sp) {
+ double want = 0.0;
+ for (uint32_t i = 0; i < L.size(); ++i) want += double(L.A[i]) / double(rel[i] * rel[i]);
+ const float c = float(std::sqrt(want / faces)) * (sp / spacing);
+ L.S.resize(L.size());
+ for (uint32_t i = 0; i < L.size(); ++i) L.S[i] = c * rel[i];
+ for (size_t li = base + 1; li < levels.size(); ++li) {
+ const Level& f = levels[li - 1];
+ Level& cl = levels[li];
+ std::vector<double> s(cl.size(), 0.0), a(cl.size(), 0.0);
+ for (uint32_t i = 0; i < f.size(); ++i) s[f.up[i]] += double(f.S[i]) * f.A[i], a[f.up[i]] += f.A[i];
+ cl.S.resize(cl.size());
+ for (uint32_t i = 0; i < cl.size(); ++i) cl.S[i] = a[i] > 0.0 ? float(s[i] / a[i]) : c;
+ }
+ };
+
+ // Position field and extraction; the lattice size is corrected until the quad count is near the target.
+ PolyMesh poly;
+ QuadMesh qm;
+ QRemeshStats st;
+ float sp = spacing;
+ const double wantQuads = double(target) / (axis >= 0 ? 2.0 : 1.0);
+ for (int attempt = 0; attempt < 4; ++attempt) {
+ setScale(sp);
+ Level& top = levels.back();
+ top.O = top.V;
+ for (uint32_t i = 0; i < top.size(); ++i) applyPositionConstraint(top, i, top.Q[i], top.O[i]);
+ for (size_t li = levels.size(); li-- > base;) {
+ Level& l = levels[li];
+ if (li + 1 < levels.size()) {
+ const Level& c = levels[li + 1];
+ l.O.resize(l.size());
+ for (uint32_t i = 0; i < l.size(); ++i) {
+ const vec3 o = c.O[l.up[i]];
+ l.O[i] = o - l.N[i] * glm::dot(l.N[i], o - l.V[i]);
+ }
+ }
+ smoothPositions(l, li == base ? 10 : 10);
+ }
+ if (!report(0.45f + 0.1f * float(attempt))) return false;
+ poly = extractPolygons(L);
+ if (timing) {
+ std::map<size_t, size_t> sizes;
+ for (const auto& f : poly.faces) ++sizes[f.size()];
+ std::fprintf(stderr, "faces:");
+ for (auto [k, c] : sizes) std::fprintf(stderr, " %zu:%zu", k, c);
+ std::fprintf(stderr, "\n");
+ }
+ splitLargeFaces(poly);
+ qm = splitIntoQuads(poly);
+ removeDoublets(qm);
+ st.attempts = attempt + 1;
+ const double quads = double(qm.quads.size());
+ if (quads <= 0.0) break;
+ const double ratio = quads / wantQuads;
+ if (std::abs(ratio - 1.0) < 0.05 || attempt == 3) break;
+ sp *= float(std::sqrt(ratio));
+ }
+ if (qm.quads.empty()) {
+ error = "QRemesh could not build quads on this surface (try a higher Target or turn Keep Groups off)";
+ return false;
+ }
+ if (!report(0.85f)) return false;
+
+ // Snap to the sculpt and relax.
+ SegmentBVH boundaryBvh, borderBvh;
+ {
+ std::vector<vec3> a, b;
+ for (auto& s : boundarySegs) a.push_back(s.first), b.push_back(s.second);
+ boundaryBvh.build(std::move(a), std::move(b));
+ a.clear(), b.clear();
+ for (auto& s : borderSegs) a.push_back(s.first), b.push_back(s.second);
+ borderBvh.build(std::move(a), std::move(b));
+ }
+ Snapper snap{&surface, boundaryBvh.empty() ? nullptr : &boundaryBvh, borderBvh.empty() ? nullptr : &borderBvh,
+ spacing * 4.0f + 1e-3f * diag};
+ bool cancelled = false;
+ relax(qm, snap, std::max(opt.smoothIterations, 0), sp * 0.5f, progress, 0.85f, 0.95f, cancelled);
+ if (cancelled) {
+ error = "QRemesh cancelled";
+ return false;
+ }
+
+ // Symmetry: mirror the half, welding the vertices on the plane.
+ if (axis >= 0) {
+ std::unordered_map<uint64_t, int> edgeUse;
+ for (const auto& f : qm.quads)
+ for (int k = 0; k < 4; ++k) ++edgeUse[edgeKey(f[k], f[(k + 1) % 4])];
+ std::vector<uint8_t> seam(qm.P.size(), 0);
+ for (auto [key, uses] : edgeUse)
+ if (uses == 1) {
+ const uint32_t a = uint32_t(key >> 32), b = uint32_t(key & 0xffffffffu);
+ if (std::abs(qm.P[a][axis]) < 0.3f * sp && std::abs(qm.P[b][axis]) < 0.3f * sp) seam[a] = seam[b] = 1;
+ }
+ const size_t nv = qm.P.size(), nq = qm.quads.size();
+ std::vector<uint32_t> mirror(nv);
+ for (uint32_t v = 0; v < nv; ++v) {
+ if (seam[v]) {
+ qm.P[v][axis] = 0.0f;
+ mirror[v] = v;
+ } else {
+ mirror[v] = uint32_t(qm.P.size());
+ vec3 p = qm.P[v];
+ p[axis] = -p[axis];
+ qm.P.push_back(p);
+ }
+ }
+ for (size_t f = 0; f < nq; ++f) {
+ const glm::uvec4 q = qm.quads[f];
+ qm.quads.push_back({mirror[q.w], mirror[q.z], mirror[q.y], mirror[q.x]});
+ }
+ }
+
+ // Output mesh: each quad as two triangles split along corner 0 - 2.
+ Mesh m;
+ m.positions = qm.P;
+ m.triangles.reserve(qm.quads.size() * 2);
+ for (const auto& q : qm.quads) {
+ const uint32_t t = uint32_t(m.triangles.size());
+ m.triangles.push_back({q.x, q.y, q.z});
+ m.triangles.push_back({q.x, q.z, q.w});
+ m.pairQuad(t, t + 1);
+ }
+ if (!report(0.96f)) return false;
+
+ // Attributes from the closest point of the original sculpt.
+ const bool needAttr = source.hasMask() || source.hasColors() || opt.keepGroups;
+ if (needAttr) {
+ TriangleBVH full;
+ full.build(source.positions, source.triangles);
+ const float reach = diag;
+ if (source.hasMask() || source.hasColors()) {
+ if (source.hasMask()) m.ensureMask();
+ if (source.hasColors()) m.ensureColors();
+ parallelFor(m.positions.size(), [&](size_t b, size_t e) {
+ for (size_t v = b; v < e; ++v) {
+ SurfaceHit hit;
+ if (!full.closestPoint(m.positions[v], reach, hit)) continue;
+ const glm::uvec3 t = source.triangles[hit.prim];
+ if (source.hasMask())
+ m.mask[v] = hit.bary.x * source.mask[t.x] + hit.bary.y * source.mask[t.y] + hit.bary.z * source.mask[t.z];
+ if (source.hasColors())
+ m.colors[v] = hit.bary.x * source.colors[t.x] + hit.bary.y * source.colors[t.y] +
+ hit.bary.z * source.colors[t.z];
+ }
+ });
+ }
+ if (opt.keepGroups && source.hasPolygroups()) {
+ m.ensurePolygroups();
+ const size_t nq = m.triangles.size() / 2;
+ parallelFor(nq, [&](size_t b, size_t e) {
+ for (size_t q = b; q < e; ++q) {
+ const glm::uvec3 t0 = m.triangles[2 * q], t1 = m.triangles[2 * q + 1];
+ const vec3 c = 0.25f * (m.positions[t0.x] + m.positions[t0.y] + m.positions[t0.z] + m.positions[t1.z]);
+ SurfaceHit hit;
+ const uint32_t g = full.closestPoint(c, reach, hit) ? source.polygroupAt(hit.prim) : 0u;
+ m.polygroups[2 * q] = m.polygroups[2 * q + 1] = g;
+ }
+ });
+ }
+ }
+ m.rebuildTopology();
+ m.recomputeAllNormals();
+
+ const TopologyReport topo = topologyReport(m);
+ st.quads = topo.quads;
+ st.triangles = topo.triangles;
+ st.boundaryEdges = topo.boundaryEdges;
+ st.nonManifoldEdges = topo.nonManifoldEdges;
+ {
+ double len = 0.0;
+ size_t cnt = 0;
+ for (const auto& q : qm.quads)
+ for (int k = 0; k < 4; ++k) len += glm::length(qm.P[q[k]] - qm.P[q[(k + 1) % 4]]), ++cnt;
+ st.edgeLength = cnt ? float(len / double(cnt)) : 0.0f;
+ }
+ st.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();
+ if (stats) *stats = st;
+ out = std::move(m);
+ return report(1.0f);
+}
+
+TopologyReport topologyReport(const Mesh& mesh) {
+ TopologyReport r;
+ // Faces as exported: quads once, triangles.
+ std::vector<std::vector<uint32_t>> faces;
+ for (uint32_t t = 0; t < mesh.triangleCount(); ++t) {
+ glm::uvec4 f;
+ const int n = mesh.exportFace(t, f);
+ if (n == 0) continue;
+ faces.push_back(n == 4 ? std::vector<uint32_t>{f.x, f.y, f.z, f.w} : std::vector<uint32_t>{f.x, f.y, f.z});
+ ++(n == 4 ? r.quads : r.triangles);
+ }
+ r.faces = faces.size();
+ // Directed edge counts.
+ std::unordered_map<uint64_t, std::pair<int, int>> edges; // key (min,max) -> (uses a->b with a<b, uses b->a)
+ for (const auto& f : faces)
+ for (size_t k = 0; k < f.size(); ++k) {
+ const uint32_t a = f[k], b = f[(k + 1) % f.size()];
+ auto& e = edges[edgeKey(a, b)];
+ ++(a < b ? e.first : e.second);
+ }
+ std::vector<std::vector<std::pair<uint32_t, uint32_t>>> fan(mesh.vertexCount()); // per vertex: (prev, next) corners
+ for (const auto& f : faces)
+ for (size_t k = 0; k < f.size(); ++k)
+ fan[f[k]].push_back({f[(k + f.size() - 1) % f.size()], f[(k + 1) % f.size()]});
+ for (auto& [key, e] : edges) {
+ const int total = e.first + e.second;
+ if (total == 1) ++r.boundaryEdges;
+ else if (total > 2 || e.first != 1 || e.second != 1) ++r.nonManifoldEdges;
+ }
+ // A manifold vertex's corners chain into one fan (a cycle inside, a path on a boundary).
+ for (uint32_t v = 0; v < fan.size(); ++v) {
+ const auto& c = fan[v];
+ if (c.size() < 2) continue;
+ std::unordered_map<uint32_t, size_t> byNext; // corner whose "next" is u
+ for (size_t i = 0; i < c.size(); ++i) byNext[c[i].second] = i;
+ std::vector<uint8_t> seen(c.size(), 0);
+ size_t start = 0;
+ // Start from a corner whose prev neighbour isn't any corner's next (a boundary end), if any.
+ for (size_t i = 0; i < c.size(); ++i) {
+ bool hasPrev = false;
+ for (size_t j = 0; j < c.size(); ++j) hasPrev |= c[j].first == c[i].second;
+ if (!hasPrev) start = i;
+ }
+ size_t walked = 0, cur = start;
+ while (!seen[cur]) {
+ seen[cur] = 1;
+ ++walked;
+ // The corner across the edge (v, c[cur].first): it has that vertex as its "next".
+ auto it = byNext.find(c[cur].first);
+ if (it == byNext.end()) break;
+ cur = it->second;
+ }
+ if (walked != c.size()) ++r.nonManifoldVertices;
+ }
+ return r;
+}
+
+} // namespace sf
diff --git a/src/core/QRemesh.h b/src/core/QRemesh.h
new file mode 100644
index 00000000..c5057e70
--- /dev/null
+++ b/src/core/QRemesh.h
@@ -0,0 +1,81 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// QRemesh (Geometry > QRemesh, like ZBrush's ZRemesher): automatic quad retopology. A field-aligned method
+// after Instant Field-Aligned Meshes (Jakob, Tarini, Panozzo, Sorkine-Hornung, SIGGRAPH Asia 2015; the
+// reference code is BSD-3, this is a fresh implementation of the parts we need):
+//
+// 1. A multi-resolution hierarchy of the surface's vertex graph (greedy edge matching, ~halving per level).
+// 2. A smooth 4-RoSy orientation field (where the quad edges point), solved coarse to fine.
+// 3. A position field: per vertex the nearest corner of a local quad lattice with the wanted edge length,
+// made consistent across neighbours (also coarse to fine). Adaptive Size scales the lattice with the
+// curvature; polypaint can ask for more (red) or fewer (blue) polygons.
+// 4. Extraction: vertices whose lattice corners coincide merge, lattice-neighbours become edges, the graph's
+// faces are traced in each vertex's tangent plane, and every face (quad, or the odd triangle / pentagon
+// around a field singularity) is split into quads, so the result is all quads and closed (2-manifold)
+// where the sculpt is.
+// 5. The quads are relaxed and snapped back onto the sculpt; the target count is met by adjusting the
+// lattice size and extracting again.
+//
+// Keep Groups constrains the fields to the polygroup borders, so edge loops run along them (and the result
+// keeps the groups). Symmetry remeshes one half (cut at the plane) and mirrors it, welded on the seam.
+#pragma once
+
+#include "core/Mesh.h"
+
+#include <functional>
+#include <string>
+
+namespace sf {
+
+class CommandRegistry;
+struct Document;
+
+struct QRemeshOptions {
+ int targetQuads = 5000; // ZBrush's Target Polygons Count (here in polygons, not thousands)
+ float adaptive = 0.5f; // Adaptive Size: 0 = even quads, 1 = sizes follow the curvature strongly
+ bool keepGroups = false; // edge loops along polygroup borders; the result keeps the groups
+ bool detectEdges = true; // hard edges (faces meeting at more than 50 degrees) get an edge loop
+ bool usePolypaint = false; // red polypaint: up to 4x the density, blue: down to 1/4
+ int symmetryAxis = -1; // -1 none, 0 X, 1 Y, 2 Z (mirror across the plane through the origin)
+ int smoothIterations = 6;
+ uint32_t seed = 1; // the field's random start (the result is deterministic for a seed)
+};
+
+struct QRemeshStats {
+ size_t quads = 0, triangles = 0; // faces of the result (triangles only for degenerate leftovers)
+ size_t boundaryEdges = 0, nonManifoldEdges = 0;
+ int attempts = 0; // extractions run to approach the target count
+ float edgeLength = 0; // mean quad edge length
+ double seconds = 0;
+};
+
+// Fraction 0..1 of the whole job; return false to cancel. Called from the thread running qremesh.
+using QRemeshProgress = std::function<bool(float fraction)>;
+
+// Retopologises `source` (its evaluated positions: sculpt layers are baked; hidden parts are remeshed too)
+// into `out`: all quads (as triangle pairs, Mesh::quadPartners), mask and polypaint interpolated from the
+// sculpt, polygroups with Keep Groups. False with `error` set on failure or cancel.
+bool qremesh(const Mesh& source, const QRemeshOptions& options, Mesh& out, std::string& error,
+ const QRemeshProgress& progress = {}, QRemeshStats* stats = nullptr);
+
+// Edge-manifold check used by the tests and the status line: faces as exported (quads counted once).
+struct TopologyReport {
+ size_t faces = 0, quads = 0, triangles = 0;
+ size_t boundaryEdges = 0; // edges with one face
+ size_t nonManifoldEdges = 0; // edges with more than two faces, or two faces wound the same way
+ size_t nonManifoldVertices = 0; // vertices whose faces form more than one fan
+ bool manifold() const { return nonManifoldEdges == 0 && nonManifoldVertices == 0; }
+ float quadFraction() const { return faces ? float(quads) / float(faces) : 0.0f; }
+};
+TopologyReport topologyReport(const Mesh& mesh);
+
+// Puts a qremesh result into the active SubTool as one undo step. keepOriginal: first a hidden copy of the
+// SubTool as it was goes right below it ("<name> Original"), ready to ProjectAll the detail back from.
+// Returns the status message.
+std::string applyQRemesh(Document& doc, Mesh result, bool keepOriginal, const QRemeshStats& stats);
+
+// qremesh (core/RetopoCommands.cpp) and project_all (core/Projection.h).
+void registerRetopoCommands(CommandRegistry& registry);
+
+} // namespace sf
diff --git a/src/core/RetopoCommands.cpp b/src/core/RetopoCommands.cpp
new file mode 100644
index 00000000..6dc49e2d
--- /dev/null
+++ b/src/core/RetopoCommands.cpp
@@ -0,0 +1,111 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// 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/Projection.h"
+#include "core/QRemesh.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+
+namespace sf {
+
+namespace {
+
+using T = ParamSpec::Type;
+
+int symmetryAxisArg(const std::string& s) {
+ if (s == "x" || s == "X") return 0;
+ if (s == "y" || s == "Y") return 1;
+ if (s == "z" || s == "Z") return 2;
+ return -1;
+}
+
+} // namespace
+
+std::string applyQRemesh(Document& doc, Mesh result, bool keepOriginal, const QRemeshStats& st) {
+ const size_t before = doc.mesh.triangleCount();
+ if (keepOriginal) {
+ const SubTool& active = doc.activeSubtoolInfo();
+ const int at = doc.activeSubtool + 1;
+ doc.addSubtool(doc.mesh, active.name + " Original", false, at);
+ doc.subtools[size_t(at)].visible = false;
+ }
+ doc.replaceMeshUndoable(std::move(result), "QRemesh");
+ const size_t faces = st.quads + st.triangles;
+ char buf[256];
+ std::snprintf(buf, sizeof buf, "QRemesh: %zu quads%s from %zu triangles (%.0f%% quads%s) in %.1f s%s", st.quads,
+ st.triangles ? (" + " + std::to_string(st.triangles) + " triangles").c_str() : "", before,
+ faces ? 100.0 * double(st.quads) / double(faces) : 0.0,
+ st.nonManifoldEdges ? (", " + std::to_string(st.nonManifoldEdges) + " non-manifold edges").c_str() : "",
+ st.seconds, keepOriginal ? "; the original is kept as a hidden SubTool" : "");
+ return buf;
+}
+
+void registerRetopoCommands(CommandRegistry& reg) {
+ reg.add({"qremesh",
+ "QRemesh (like ZBrush's ZRemesher): automatic quad retopology of the active SubTool. Builds clean, "
+ "all-quad topology with edge loops that follow the form, close to the target polygon count. Sculpt "
+ "layers are baked; mask and polypaint carry over. Undoable. Use project_all afterwards (from a kept "
+ "original) to bring fine detail back onto a divided copy.",
+ {{"target", T::Number, "Target polygon (quad) count, 16-2000000. Default 5000.", false},
+ {"adaptive", T::Number, "Adaptive Size 0-1: 0 = even quads, 1 = small quads in curved areas, big "
+ "ones on flat areas. Default 0.5.", false},
+ {"keep_groups", T::Bool, "Keep Groups: edge loops follow the polygroup borders and the groups are kept.", false},
+ {"use_polypaint", T::Bool, "Use the polypaint as a density guide: red areas get up to 4x the quads, blue "
+ "areas down to a quarter.", false},
+ {"symmetry", T::String, "Mirror the topology across x, y or z (the plane through the origin). Default: none.", false},
+ {"keep_original", T::Bool, "Keep the original as a hidden SubTool below (for project_all). Default false.", false},
+ {"smooth", T::Number, "Relaxation passes on the surface (0-30). Default 6.", false},
+ {"seed", T::Number, "Random start of the direction field (results are repeatable per seed).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ if (doc.mesh.triangleCount() == 0) return {false, "QRemesh: the SubTool is empty"};
+ QRemeshOptions o;
+ o.targetQuads = int(std::clamp(argNumber(a, "target", 5000), 16.0, 2'000'000.0));
+ o.adaptive = float(std::clamp(argNumber(a, "adaptive", 0.5), 0.0, 1.0));
+ o.keepGroups = argBool(a, "keep_groups", false);
+ o.usePolypaint = argBool(a, "use_polypaint", false);
+ o.symmetryAxis = symmetryAxisArg(argString(a, "symmetry"));
+ o.smoothIterations = int(std::clamp(argNumber(a, "smooth", 6), 0.0, 30.0));
+ o.seed = uint32_t(std::max(0.0, argNumber(a, "seed", 1)));
+ Mesh out;
+ std::string err;
+ QRemeshStats st;
+ if (!qremesh(doc.mesh, o, out, err, {}, &st)) return {false, err};
+ return {true, applyQRemesh(doc, std::move(out), argBool(a, "keep_original", false), st)};
+ }});
+
+ reg.add({"project_all",
+ "ProjectAll (SubTool palette): move the active SubTool's vertices onto the surface of the other visible "
+ "SubTools and take their polypaint, e.g. after QRemesh and a few subdivisions, to get the sculpted detail "
+ "back. Respects the mask (masked vertices stay). One undo step.",
+ {{"distance", T::Number, "Dist: how far each vertex searches along its normal, as a fraction of the "
+ "SubTool's bounding-box diagonal (0.001-1). Default 0.02.", false},
+ {"mean", T::Bool, "Mean: with surface on both sides, settle halfway between them. Default false.", false},
+ {"blur", T::Number, "PA Blur: smoothing passes over the projected offsets (0-20). Default 0.", false},
+ {"geometry", T::Bool, "Project the shape. Default true.", false},
+ {"polypaint", T::Bool, "Project the polypaint (when a source has any). Default true.", false},
+ {"source", T::String, "Project only from the SubTool with this name (default: all visible ones).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ ProjectOptions o;
+ o.distance = float(std::clamp(argNumber(a, "distance", 0.02), 0.001, 1.0));
+ o.mean = argBool(a, "mean", false);
+ o.blur = int(std::clamp(argNumber(a, "blur", 0), 0.0, 20.0));
+ o.geometry = argBool(a, "geometry", true);
+ o.polypaint = argBool(a, "polypaint", true);
+ int source = -1;
+ if (a.contains("source")) {
+ source = doc.findSubtool(argString(a, "source"));
+ if (source < 0) return {false, "No SubTool called '" + argString(a, "source") + "'"};
+ if (source == doc.activeSubtool) return {false, "ProjectAll can't project a SubTool onto itself"};
+ }
+ std::string msg;
+ const bool ok = projectAll(doc, o, msg, source);
+ return {ok, msg};
+ }});
+}
+
+} // namespace sf
diff --git a/src/core/SurfaceQuery.cpp b/src/core/SurfaceQuery.cpp
new file mode 100644
index 00000000..6ce4effc
--- /dev/null
+++ b/src/core/SurfaceQuery.cpp
@@ -0,0 +1,355 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/SurfaceQuery.h"
+
+#include "core/Parallel.h"
+
+#include <algorithm>
+#include <atomic>
+#include <cmath>
+#include <cstring>
+#include <limits>
+
+namespace sf {
+
+namespace {
+
+constexpr uint32_t kLeafSize = 4;
+
+float boxDistance2(const AABB& b, const glm::vec3& p) {
+ const glm::vec3 d = glm::max(glm::max(b.min - p, p - b.max), glm::vec3(0.0f));
+ return glm::dot(d, d);
+}
+
+// Ray / box slab test: entry distance, or a negative value for a miss.
+float rayBox(const AABB& b, const glm::vec3& o, const glm::vec3& inv, float maxT) {
+ const glm::vec3 t0 = (b.min - o) * inv, t1 = (b.max - o) * inv;
+ const glm::vec3 lo = glm::min(t0, t1), hi = glm::max(t0, t1);
+ const float enter = std::max(std::max(lo.x, lo.y), std::max(lo.z, 0.0f));
+ const float exit = std::min(std::min(hi.x, hi.y), std::min(hi.z, maxT));
+ return enter <= exit ? enter : -1.0f;
+}
+
+glm::vec3 closestPointOnSegment(const glm::vec3& p, const glm::vec3& a, const glm::vec3& b, float& u) {
+ const glm::vec3 ab = b - a;
+ const float len2 = glm::dot(ab, ab);
+ u = len2 > 0.0f ? std::clamp(glm::dot(p - a, ab) / len2, 0.0f, 1.0f) : 0.0f;
+ return a + ab * u;
+}
+
+} // namespace
+
+void FlatBVH::build(const std::vector<AABB>& boxes) {
+ nodes_.clear();
+ order_.resize(boxes.size());
+ for (uint32_t i = 0; i < order_.size(); ++i) order_[i] = i;
+ if (boxes.empty()) return;
+ std::vector<glm::vec3> centers(boxes.size());
+ for (size_t i = 0; i < boxes.size(); ++i) centers[i] = boxes[i].center();
+
+ nodes_.reserve(2 * boxes.size() / kLeafSize + 2);
+ nodes_.push_back({});
+ struct Task {
+ uint32_t node, begin, end;
+ };
+ std::vector<Task> stack{{0, 0, uint32_t(boxes.size())}};
+ while (!stack.empty()) {
+ const Task t = stack.back();
+ stack.pop_back();
+ AABB box, cbox;
+ for (uint32_t i = t.begin; i < t.end; ++i) {
+ box.expand(boxes[order_[i]]);
+ cbox.expand(centers[order_[i]]);
+ }
+ nodes_[t.node].box = box;
+ const uint32_t count = t.end - t.begin;
+ const glm::vec3 ext = cbox.extent();
+ if (count <= kLeafSize || std::max({ext.x, ext.y, ext.z}) <= 0.0f) {
+ nodes_[t.node].first = t.begin;
+ nodes_[t.node].count = count;
+ continue;
+ }
+ const int axis = ext.x >= ext.y && ext.x >= ext.z ? 0 : ext.y >= ext.z ? 1 : 2;
+ const uint32_t mid = t.begin + count / 2;
+ std::nth_element(order_.begin() + t.begin, order_.begin() + mid, order_.begin() + t.end,
+ [&](uint32_t a, uint32_t b) { return centers[a][axis] < centers[b][axis]; });
+ const uint32_t left = uint32_t(nodes_.size());
+ nodes_.push_back({});
+ nodes_.push_back({});
+ nodes_[t.node].first = left;
+ nodes_[t.node].count = 0;
+ stack.push_back({left, t.begin, mid});
+ stack.push_back({left + 1, mid, t.end});
+ }
+}
+
+glm::vec3 closestPointOnTriangle(const glm::vec3& p, const glm::vec3& a, const glm::vec3& b, const glm::vec3& c,
+ glm::vec3& bary) {
+ // Ericson, Real-Time Collision Detection 5.1.5.
+ const glm::vec3 ab = b - a, ac = c - a, ap = p - a;
+ const float d1 = glm::dot(ab, ap), d2 = glm::dot(ac, ap);
+ if (d1 <= 0.0f && d2 <= 0.0f) {
+ bary = {1, 0, 0};
+ return a;
+ }
+ const glm::vec3 bp = p - b;
+ const float d3 = glm::dot(ab, bp), d4 = glm::dot(ac, bp);
+ if (d3 >= 0.0f && d4 <= d3) {
+ bary = {0, 1, 0};
+ return b;
+ }
+ const float vc = d1 * d4 - d3 * d2;
+ if (vc <= 0.0f && d1 >= 0.0f && d3 <= 0.0f && d1 - d3 > 0.0f) {
+ const float v = d1 / (d1 - d3);
+ bary = {1 - v, v, 0};
+ return a + ab * v;
+ }
+ const glm::vec3 cp = p - c;
+ const float d5 = glm::dot(ab, cp), d6 = glm::dot(ac, cp);
+ if (d6 >= 0.0f && d5 <= d6) {
+ bary = {0, 0, 1};
+ return c;
+ }
+ const float vb = d5 * d2 - d1 * d6;
+ if (vb <= 0.0f && d2 >= 0.0f && d6 <= 0.0f && d2 - d6 > 0.0f) {
+ const float w = d2 / (d2 - d6);
+ bary = {1 - w, 0, w};
+ return a + ac * w;
+ }
+ const float va = d3 * d6 - d5 * d4;
+ if (va <= 0.0f && d4 - d3 >= 0.0f && d5 - d6 >= 0.0f && (d4 - d3) + (d5 - d6) > 0.0f) {
+ const float w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
+ bary = {0, 1 - w, w};
+ return b + (c - b) * w;
+ }
+ const float sum = va + vb + vc;
+ if (!(std::abs(sum) > 0.0f)) { // degenerate triangle: nearest of its edges
+ float u = 0.0f;
+ glm::vec3 best = closestPointOnSegment(p, a, b, u);
+ bary = {1 - u, u, 0};
+ float bestD = glm::dot(best - p, best - p);
+ const glm::vec3 q1 = closestPointOnSegment(p, b, c, u);
+ if (const float d = glm::dot(q1 - p, q1 - p); d < bestD) {
+ best = q1, bestD = d, bary = {0, 1 - u, u};
+ }
+ const glm::vec3 q2 = closestPointOnSegment(p, a, c, u);
+ if (glm::dot(q2 - p, q2 - p) < bestD) best = q2, bary = {1 - u, 0, u};
+ return best;
+ }
+ const float denom = 1.0f / sum;
+ const float v = vb * denom, w = vc * denom;
+ bary = {1 - v - w, v, w};
+ return a + ab * v + ac * w;
+}
+
+void TriangleBVH::build(std::vector<glm::vec3> positions, std::vector<glm::uvec3> triangles) {
+ positions_ = std::move(positions);
+ triangles_ = std::move(triangles);
+ std::vector<AABB> boxes(triangles_.size());
+ parallelFor(triangles_.size(), [&](size_t b, size_t e) {
+ for (size_t t = b; t < e; ++t) {
+ AABB box;
+ for (int k = 0; k < 3; ++k) box.expand(positions_[triangles_[t][k]]);
+ boxes[t] = box;
+ }
+ });
+ bvh_.build(boxes);
+}
+
+glm::vec3 TriangleBVH::faceNormal(uint32_t t) const {
+ const glm::uvec3 tri = triangles_[t];
+ const glm::vec3 n = glm::cross(positions_[tri.y] - positions_[tri.x], positions_[tri.z] - positions_[tri.x]);
+ const float len = glm::length(n);
+ return len > 0.0f ? n / len : glm::vec3(0.0f);
+}
+
+bool TriangleBVH::closestPoint(const glm::vec3& p, float maxDistance, SurfaceHit& hit) const {
+ if (bvh_.empty()) return false;
+ const auto& nodes = bvh_.nodes();
+ const auto& order = bvh_.order();
+ float best2 = maxDistance * maxDistance;
+ bool found = false;
+ uint32_t stack[64];
+ int sp = 0;
+ stack[sp++] = 0;
+ while (sp > 0) {
+ const FlatBVH::Node& n = nodes[stack[--sp]];
+ if (boxDistance2(n.box, p) > best2) continue;
+ if (n.count > 0) {
+ for (uint32_t i = n.first; i < n.first + n.count; ++i) {
+ const uint32_t t = order[i];
+ const glm::uvec3 tri = triangles_[t];
+ glm::vec3 bary;
+ const glm::vec3 q = closestPointOnTriangle(p, positions_[tri.x], positions_[tri.y], positions_[tri.z], bary);
+ const float d2 = glm::dot(q - p, q - p);
+ if (d2 <= best2) {
+ best2 = d2;
+ found = true;
+ hit.prim = t;
+ hit.position = q;
+ hit.bary = bary;
+ }
+ }
+ continue;
+ }
+ // Nearer child last, so it is popped first.
+ const float dl = boxDistance2(nodes[n.first].box, p), dr = boxDistance2(nodes[n.first + 1].box, p);
+ if (sp + 2 > 64) continue; // cannot happen with a median split of < 2^60 primitives
+ if (dl < dr) {
+ stack[sp++] = n.first + 1;
+ stack[sp++] = n.first;
+ } else {
+ stack[sp++] = n.first;
+ stack[sp++] = n.first + 1;
+ }
+ }
+ if (found) hit.distance = std::sqrt(best2);
+ return found;
+}
+
+bool TriangleBVH::raycast(const glm::vec3& origin, const glm::vec3& dir, float maxT, SurfaceHit& hit) const {
+ if (bvh_.empty()) return false;
+ const auto& nodes = bvh_.nodes();
+ const auto& order = bvh_.order();
+ const glm::vec3 inv(1.0f / dir.x, 1.0f / dir.y, 1.0f / dir.z);
+ float bestT = maxT;
+ bool found = false;
+ uint32_t stack[64];
+ int sp = 0;
+ stack[sp++] = 0;
+ while (sp > 0) {
+ const FlatBVH::Node& n = nodes[stack[--sp]];
+ if (rayBox(n.box, origin, inv, bestT) < 0.0f) continue;
+ if (n.count > 0) {
+ for (uint32_t i = n.first; i < n.first + n.count; ++i) {
+ const uint32_t t = order[i];
+ const glm::uvec3 tri = triangles_[t];
+ const glm::vec3 a = positions_[tri.x], e1 = positions_[tri.y] - a, e2 = positions_[tri.z] - a;
+ const glm::vec3 pv = glm::cross(dir, e2);
+ const float det = glm::dot(e1, pv);
+ if (std::abs(det) < 1e-20f) continue;
+ const float invDet = 1.0f / det;
+ const glm::vec3 tv = origin - a;
+ const float u = glm::dot(tv, pv) * invDet;
+ if (u < 0.0f || u > 1.0f) continue;
+ const glm::vec3 qv = glm::cross(tv, e1);
+ const float v = glm::dot(dir, qv) * invDet;
+ if (v < 0.0f || u + v > 1.0f) continue;
+ const float tt = glm::dot(e2, qv) * invDet;
+ if (tt < 0.0f || tt > bestT) continue;
+ bestT = tt;
+ found = true;
+ hit.prim = t;
+ hit.bary = {1 - u - v, u, v};
+ hit.position = origin + dir * tt;
+ }
+ continue;
+ }
+ const float tl = rayBox(nodes[n.first].box, origin, inv, bestT);
+ const float tr = rayBox(nodes[n.first + 1].box, origin, inv, bestT);
+ if (sp + 2 > 64) continue;
+ if (tl >= 0.0f && tr >= 0.0f) {
+ if (tl < tr) {
+ stack[sp++] = n.first + 1;
+ stack[sp++] = n.first;
+ } else {
+ stack[sp++] = n.first;
+ stack[sp++] = n.first + 1;
+ }
+ } else if (tl >= 0.0f) {
+ stack[sp++] = n.first;
+ } else if (tr >= 0.0f) {
+ stack[sp++] = n.first + 1;
+ }
+ }
+ if (found) hit.distance = bestT;
+ return found;
+}
+
+void SegmentBVH::build(std::vector<glm::vec3> a, std::vector<glm::vec3> b) {
+ a_ = std::move(a);
+ b_ = std::move(b);
+ std::vector<AABB> boxes(a_.size());
+ for (size_t i = 0; i < a_.size(); ++i) {
+ boxes[i].expand(a_[i]);
+ boxes[i].expand(b_[i]);
+ }
+ bvh_.build(boxes);
+}
+
+bool SegmentBVH::closestPoint(const glm::vec3& p, float maxDistance, SurfaceHit& hit) const {
+ if (bvh_.empty()) return false;
+ const auto& nodes = bvh_.nodes();
+ const auto& order = bvh_.order();
+ float best2 = maxDistance * maxDistance;
+ bool found = false;
+ uint32_t stack[64];
+ int sp = 0;
+ stack[sp++] = 0;
+ while (sp > 0) {
+ const FlatBVH::Node& n = nodes[stack[--sp]];
+ if (boxDistance2(n.box, p) > best2) continue;
+ if (n.count > 0) {
+ for (uint32_t i = n.first; i < n.first + n.count; ++i) {
+ const uint32_t s = order[i];
+ float u = 0.0f;
+ const glm::vec3 q = closestPointOnSegment(p, a_[s], b_[s], u);
+ const float d2 = glm::dot(q - p, q - p);
+ if (d2 <= best2) {
+ best2 = d2;
+ found = true;
+ hit.prim = s;
+ hit.position = q;
+ hit.bary = {1 - u, u, 0};
+ }
+ }
+ continue;
+ }
+ if (sp + 2 > 64) continue;
+ stack[sp++] = n.first;
+ stack[sp++] = n.first + 1;
+ }
+ if (found) hit.distance = std::sqrt(best2);
+ return found;
+}
+
+SurfaceDeviation measureDeviation(const Mesh& mesh, const Mesh& reference, bool symmetric) {
+ SurfaceDeviation out;
+ double sum = 0.0, sum2 = 0.0;
+ size_t count = 0;
+ std::atomic<uint32_t> maxBits{0}; // non-negative floats order like their bits
+ auto oneWay = [&](const Mesh& from, const Mesh& to) {
+ TriangleBVH bvh;
+ bvh.build(to);
+ const size_t n = from.vertexCount();
+ std::vector<float> d(n, 0.0f);
+ parallelFor(n, [&](size_t b, size_t e) {
+ float localMax = 0.0f;
+ for (size_t v = b; v < e; ++v) {
+ SurfaceHit hit;
+ d[v] = bvh.closestPoint(from.positions[v], std::numeric_limits<float>::max(), hit) ? hit.distance : 0.0f;
+ localMax = std::max(localMax, d[v]);
+ }
+ uint32_t bits;
+ std::memcpy(&bits, &localMax, 4);
+ uint32_t cur = maxBits.load();
+ while (bits > cur && !maxBits.compare_exchange_weak(cur, bits)) {
+ }
+ });
+ for (float x : d) {
+ sum += x;
+ sum2 += double(x) * x;
+ }
+ count += n;
+ };
+ if (mesh.vertexCount() == 0 || reference.triangleCount() == 0) return out;
+ oneWay(mesh, reference);
+ if (symmetric && reference.vertexCount() > 0 && mesh.triangleCount() > 0) oneWay(reference, mesh);
+ const uint32_t bits = maxBits.load();
+ std::memcpy(&out.max, &bits, 4);
+ out.mean = count ? float(sum / double(count)) : 0.0f;
+ out.rms = count ? float(std::sqrt(sum2 / double(count))) : 0.0f;
+ return out;
+}
+
+} // namespace sf
diff --git a/src/core/SurfaceQuery.h b/src/core/SurfaceQuery.h
new file mode 100644
index 00000000..70497468
--- /dev/null
+++ b/src/core/SurfaceQuery.h
@@ -0,0 +1,91 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Read-only spatial queries on a fixed surface, safe to call from many threads at once (core/BVH.h is the
+// sculpting BVH: refittable, but its queries share scratch buffers). Used by QRemesh (snapping the new
+// quads onto the sculpt) and ProjectAll (shooting rays at the source SubTools), plus the deviation
+// (Hausdorff) measure the tests and the status line report.
+#pragma once
+
+#include "core/Mesh.h"
+
+#include <cstdint>
+#include <vector>
+
+namespace sf {
+
+struct SurfaceHit {
+ uint32_t prim = 0; // triangle (or segment) index
+ glm::vec3 position{0.0f};
+ glm::vec3 bary{0.0f}; // barycentric weights of the triangle's corners (segments: x = 1 - u, y = u)
+ float distance = 0.0f; // from the query point, or the ray parameter
+};
+
+// Bounding volume hierarchy over primitives given by their boxes (median split, 4 per leaf).
+class FlatBVH {
+public:
+ struct Node {
+ AABB box;
+ uint32_t first = 0; // leaf: first index into order(); inner: left child (right = first + 1)
+ uint32_t count = 0; // > 0 for leaves
+ };
+ void build(const std::vector<AABB>& boxes);
+ const std::vector<Node>& nodes() const { return nodes_; }
+ const std::vector<uint32_t>& order() const { return order_; }
+ bool empty() const { return nodes_.empty(); }
+
+private:
+ std::vector<Node> nodes_;
+ std::vector<uint32_t> order_;
+};
+
+class TriangleBVH {
+public:
+ // Takes the triangles to query (hidden ones should be left out by the caller).
+ void build(std::vector<glm::vec3> positions, std::vector<glm::uvec3> triangles);
+ void build(const Mesh& mesh) { build(mesh.positions, mesh.triangles); }
+ bool empty() const { return bvh_.empty(); }
+
+ // Closest surface point within `maxDistance` of `p`.
+ bool closestPoint(const glm::vec3& p, float maxDistance, SurfaceHit& hit) const;
+ // Nearest hit along the ray (either side of a triangle) with 0 <= t <= maxT; `dir` need not be unit
+ // length (t is in its units).
+ bool raycast(const glm::vec3& origin, const glm::vec3& dir, float maxT, SurfaceHit& hit) const;
+
+ const std::vector<glm::vec3>& positions() const { return positions_; }
+ const std::vector<glm::uvec3>& triangles() const { return triangles_; }
+ glm::vec3 faceNormal(uint32_t t) const;
+
+private:
+ std::vector<glm::vec3> positions_;
+ std::vector<glm::uvec3> triangles_;
+ FlatBVH bvh_;
+};
+
+// Closest points on a set of line segments (mesh boundaries, polygroup borders).
+class SegmentBVH {
+public:
+ void build(std::vector<glm::vec3> a, std::vector<glm::vec3> b);
+ bool empty() const { return bvh_.empty(); }
+ bool closestPoint(const glm::vec3& p, float maxDistance, SurfaceHit& hit) const;
+ size_t size() const { return a_.size(); }
+
+private:
+ std::vector<glm::vec3> a_, b_;
+ FlatBVH bvh_;
+};
+
+// Closest point to `p` on triangle abc, with its barycentric weights.
+glm::vec3 closestPointOnTriangle(const glm::vec3& p, const glm::vec3& a, const glm::vec3& b, const glm::vec3& c,
+ glm::vec3& bary);
+
+// How far the surface of `mesh` strays from `reference`: distances from every vertex of `mesh` (and, for the
+// symmetric measure, every vertex of `reference` back to `mesh`) to the other surface.
+struct SurfaceDeviation {
+ float max = 0.0f; // Hausdorff distance (symmetric when measured both ways)
+ float mean = 0.0f;
+ float rms = 0.0f;
+};
+SurfaceDeviation measureDeviation(const Mesh& mesh, const Mesh& reference, bool symmetric = true);
+
+} // namespace sf
diff --git a/tests/test_retopo.cpp b/tests/test_retopo.cpp
new file mode 100644
index 00000000..2acbec43
--- /dev/null
+++ b/tests/test_retopo.cpp
@@ -0,0 +1,375 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// QRemesh (quad retopology) and ProjectAll (detail projection): the result is a closed 2-manifold made of
+// quads, near the target count and the sculpt's surface (Hausdorff distance); Keep Groups, symmetry, open
+// surfaces, polypaint density, mask / colour transfer, cancel; projecting detail back onto a divided retopo
+// brings the error down and respects the mask; both commands are one undo step.
+// SF_RETOPO_BENCH=1 also times both on a 1M+ triangle sculpt.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/Primitives.h"
+#include "core/Projection.h"
+#include "core/QRemesh.h"
+#include "core/SurfaceQuery.h"
+
+#include <chrono>
+#include <cmath>
+#include <cstdlib>
+#include <set>
+
+using namespace sf;
+
+namespace {
+
+float diagonal(const Mesh& m) { return glm::length(m.bounds().extent()); }
+
+// A sphere with a few brush strokes on the front: ridges, a crease and a dent.
+Document sculptedSphere(int subdivisions = 6) {
+ CommandRegistry reg;
+ Document doc;
+ reg.execute(doc, "new_sphere", {{"subdivisions", double(subdivisions)}});
+ auto stroke = [&](const char* points, const char* brush, double radius, bool invert = false) {
+ const CommandResult r = reg.execute(doc, "stroke", {{"points", std::string(points)}, {"brush", std::string(brush)},
+ {"radius", radius}, {"strength", 1.0}, {"invert", invert}});
+ CHECK(r.ok);
+ };
+ stroke("-0.6,0.3,2 0,0.5,2 0.6,0.3,2", "Standard", 0.18);
+ stroke("-0.5,-0.3,2 0.5,-0.4,2", "Crease", 0.12);
+ stroke("0.1,0,2 0.2,0.1,2", "Clay", 0.25, true);
+ doc.undo.clear();
+ return doc;
+}
+
+void checkQuadMesh(const Mesh& m, bool closed, const char* what) {
+ const TopologyReport t = topologyReport(m);
+ std::printf(" %s: %zu faces, %.1f%% quads, %zu boundary / %zu non-manifold edges, %zu non-manifold vertices\n", what,
+ t.faces, 100.0f * t.quadFraction(), t.boundaryEdges, t.nonManifoldEdges, t.nonManifoldVertices);
+ CHECK(t.manifold());
+ CHECK(t.quadFraction() >= 0.95f); // brief: mostly quads (the method gives all quads)
+ if (closed) CHECK(t.boundaryEdges == 0);
+ CHECK(m.quadCount() * 2 == m.triangleCount() || t.triangles > 0);
+}
+
+} // namespace
+
+TEST(qremesh_sphere_is_closed_quads_near_target) {
+ CommandRegistry reg;
+ Document doc;
+ reg.execute(doc, "new_sphere", {{"subdivisions", 5.0}});
+ const Mesh source = doc.mesh;
+ QRemeshOptions o;
+ o.targetQuads = 2000;
+ Mesh out;
+ std::string err;
+ QRemeshStats st;
+ CHECK(qremesh(source, o, out, err, {}, &st));
+ checkQuadMesh(out, true, "sphere");
+ CHECK(st.quads >= 1700 && st.quads <= 2300);
+ const SurfaceDeviation d = measureDeviation(out, source);
+ std::printf(" sphere: %zu quads (target 2000), Hausdorff %.3f%% of the size, %.2f s\n", st.quads,
+ 100.0f * d.max / diagonal(source), st.seconds);
+ CHECK(d.max < 0.01f * diagonal(source));
+ // Same seed, same result.
+ Mesh again;
+ CHECK(qremesh(source, o, again, err));
+ CHECK(again.positions == out.positions && again.triangles == out.triangles);
+}
+
+TEST(qremesh_sculpt_target_counts) {
+ Document doc = sculptedSphere(5);
+ for (int target : {500, 3000, 8000}) {
+ QRemeshOptions o;
+ o.targetQuads = target;
+ Mesh out;
+ std::string err;
+ QRemeshStats st;
+ CHECK(qremesh(doc.mesh, o, out, err, {}, &st));
+ checkQuadMesh(out, true, "sculpt");
+ const double ratio = double(st.quads) / double(target);
+ std::printf(" target %d -> %zu quads (%.0f%%)\n", target, st.quads, ratio * 100.0);
+ CHECK(ratio > 0.8 && ratio < 1.2);
+ }
+}
+
+TEST(qremesh_keep_groups_follows_borders) {
+ CommandRegistry reg;
+ Document doc;
+ doc.setMesh(makeCube(24));
+ CHECK(reg.execute(doc, "polygroup_auto_by_normals", {{"angle", 40.0}}).ok);
+ QRemeshOptions o;
+ o.targetQuads = 1500;
+ o.keepGroups = true;
+ o.detectEdges = false; // the borders alone must hold the edges
+ Mesh out;
+ std::string err;
+ CHECK(qremesh(doc.mesh, o, out, err));
+ checkQuadMesh(out, true, "cube, Keep Groups");
+ // Six groups, each quad entirely in one (halves agree), and the cube's sharp edges kept.
+ CHECK(out.hasPolygroups());
+ std::set<uint32_t> groups(out.polygroups.begin(), out.polygroups.end());
+ CHECK(groups.size() == 6);
+ for (size_t t = 0; t + 1 < out.triangleCount(); t += 2) CHECK(out.polygroups[t] == out.polygroups[t + 1]);
+ const SurfaceDeviation d = measureDeviation(out, doc.mesh);
+ std::printf(" cube with Keep Groups: Hausdorff %.3f%% of the size\n", 100.0f * d.max / diagonal(doc.mesh));
+ CHECK(d.max < 0.005f * diagonal(doc.mesh));
+ // Without groups or edge detection the corners round off.
+ o.keepGroups = false;
+ Mesh soft;
+ CHECK(qremesh(doc.mesh, o, soft, err));
+ CHECK(measureDeviation(soft, doc.mesh).max > d.max * 2.0f);
+ // Detect Edges alone also keeps them.
+ o.detectEdges = true;
+ Mesh hard;
+ CHECK(qremesh(doc.mesh, o, hard, err));
+ CHECK(measureDeviation(hard, doc.mesh).max < 0.005f * diagonal(doc.mesh));
+}
+
+TEST(qremesh_symmetry_mirrors_the_topology) {
+ CommandRegistry reg;
+ Document doc;
+ reg.execute(doc, "new_sphere", {{"subdivisions", 5.0}});
+ QRemeshOptions o;
+ o.targetQuads = 1600;
+ o.symmetryAxis = 0;
+ Mesh out;
+ std::string err;
+ CHECK(qremesh(doc.mesh, o, out, err));
+ checkQuadMesh(out, true, "sphere, X symmetry");
+ // Every vertex has a mirror twin (exactly: the halves are copies).
+ TriangleBVH bvh; // nearest vertex via degenerate triangles
+ std::vector<glm::uvec3> points(out.vertexCount());
+ for (uint32_t v = 0; v < out.vertexCount(); ++v) points[v] = {v, v, v};
+ bvh.build(out.positions, points);
+ size_t unmatched = 0;
+ for (const glm::vec3& p : out.positions) {
+ SurfaceHit hit;
+ if (!bvh.closestPoint({-p.x, p.y, p.z}, 1.0f, hit) || hit.distance > 1e-5f) ++unmatched;
+ }
+ CHECK(unmatched == 0);
+}
+
+TEST(qremesh_open_surface_keeps_its_outline) {
+ CommandRegistry reg;
+ Document doc;
+ reg.execute(doc, "new_plane", {});
+ CHECK(doc.mesh.triangleCount() > 0);
+ QRemeshOptions o;
+ o.targetQuads = 400;
+ Mesh out;
+ std::string err;
+ CHECK(qremesh(doc.mesh, o, out, err));
+ checkQuadMesh(out, false, "plane");
+ const TopologyReport t = topologyReport(out);
+ CHECK(t.boundaryEdges > 40);
+ const AABB a = doc.mesh.bounds(), b = out.bounds();
+ CHECK(glm::length(a.min - b.min) < 0.01f * diagonal(doc.mesh));
+ CHECK(glm::length(a.max - b.max) < 0.01f * diagonal(doc.mesh));
+}
+
+TEST(qremesh_transfers_mask_and_polypaint) {
+ CommandRegistry reg;
+ Document doc;
+ reg.execute(doc, "new_sphere", {{"subdivisions", 5.0}});
+ Mesh& m = doc.mesh;
+ m.ensureMask();
+ m.ensureColors();
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {
+ m.mask[v] = m.positions[v].y > 0.0f ? 1.0f : 0.0f;
+ m.colors[v] = m.positions[v].x > 0.0f ? glm::vec3(1, 0, 0) : glm::vec3(0, 0, 1);
+ }
+ QRemeshOptions o;
+ o.targetQuads = 1500;
+ Mesh out;
+ std::string err;
+ CHECK(qremesh(m, o, out, err));
+ CHECK(out.hasMask() && out.hasColors());
+ size_t wrong = 0;
+ for (uint32_t v = 0; v < out.vertexCount(); ++v) {
+ const glm::vec3 p = out.positions[v];
+ if (std::abs(p.y) > 0.1f && (out.mask[v] > 0.5f) != (p.y > 0.0f)) ++wrong;
+ if (std::abs(p.x) > 0.1f && (out.colors[v].x > 0.5f) != (p.x > 0.0f)) ++wrong;
+ }
+ CHECK(wrong == 0);
+}
+
+TEST(qremesh_polypaint_density) {
+ CommandRegistry reg;
+ Document doc;
+ reg.execute(doc, "new_sphere", {{"subdivisions", 5.0}});
+ Mesh& m = doc.mesh;
+ m.ensureColors();
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) m.colors[v] = m.positions[v].y > 0.0f ? glm::vec3(1, 0, 0) : glm::vec3(1);
+ QRemeshOptions o;
+ o.targetQuads = 2000;
+ o.adaptive = 0.0f;
+ o.usePolypaint = true;
+ Mesh out;
+ std::string err;
+ CHECK(qremesh(m, o, out, err));
+ checkQuadMesh(out, true, "sphere, polypaint density");
+ size_t top = 0, bottom = 0;
+ for (size_t t = 0; t < out.triangleCount(); t += 2) {
+ const glm::uvec3 tri = out.triangles[t];
+ const float y = out.positions[tri.x].y + out.positions[tri.y].y + out.positions[tri.z].y;
+ ++(y > 0.0f ? top : bottom);
+ }
+ std::printf(" red top half: %zu quads, white bottom half: %zu\n", top, bottom);
+ CHECK(top > bottom * 2);
+}
+
+TEST(qremesh_adaptive_size_varies_quads) {
+ Document doc = sculptedSphere(5);
+ auto spread = [&](float adaptive) {
+ QRemeshOptions o;
+ o.targetQuads = 3000;
+ o.adaptive = adaptive;
+ Mesh out;
+ std::string err;
+ CHECK(qremesh(doc.mesh, o, out, err));
+ double s = 0.0, s2 = 0.0;
+ size_t n = 0;
+ for (const glm::uvec3& t : out.triangles) {
+ const double l = glm::length(out.positions[t.x] - out.positions[t.y]);
+ s += l, s2 += l * l, ++n;
+ }
+ const double mean = s / double(n);
+ return std::sqrt(std::max(0.0, s2 / double(n) - mean * mean)) / mean; // coefficient of variation
+ };
+ const double even = spread(0.0f), adaptive = spread(1.0f);
+ std::printf(" edge length variation: %.2f even, %.2f adaptive\n", even, adaptive);
+ CHECK(adaptive > even * 1.2);
+}
+
+TEST(qremesh_cancel_and_errors) {
+ CommandRegistry reg;
+ Document doc;
+ reg.execute(doc, "new_sphere", {{"subdivisions", 4.0}});
+ Mesh out;
+ std::string err;
+ int calls = 0;
+ CHECK(!qremesh(doc.mesh, {}, out, err, [&](float) { return ++calls < 3; }));
+ CHECK(err.find("cancelled") != std::string::npos);
+ CHECK(!qremesh(Mesh{}, {}, out, err));
+}
+
+TEST(qremesh_command_keeps_original_and_undoes) {
+ CommandRegistry reg;
+ Document doc = sculptedSphere(5);
+ const size_t before = doc.mesh.triangleCount();
+ const CommandResult r = reg.execute(doc, "qremesh", {{"target", 1200.0}, {"keep_original", true}, {"adaptive", 0.3}});
+ CHECK(r.ok);
+ CHECK(r.message.find("quads") != std::string::npos);
+ CHECK(doc.subtoolCount() == 2);
+ CHECK(doc.activeSubtool == 0);
+ CHECK(!doc.subtools[1].visible);
+ CHECK(doc.subtools[1].name == doc.subtools[0].name + " Original");
+ CHECK(doc.subtoolMesh(1).triangleCount() == before);
+ CHECK(doc.mesh.quadCount() * 2 == doc.mesh.triangleCount());
+ CHECK(doc.undo.canUndo());
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));
+ CHECK(doc.mesh.triangleCount() == before);
+ CHECK(reg.execute(doc, "qremesh", {{"target", 800.0}, {"symmetry", std::string("x")}, {"keep_groups", true}}).ok);
+ CHECK(!reg.execute(doc, "project_all", {{"source", std::string("Nope")}}).ok);
+}
+
+TEST(project_all_brings_detail_back) {
+ CommandRegistry reg;
+ Document doc = sculptedSphere(6);
+ doc.subtools[0].name = "Sculpt";
+ // Paint the source so polypaint comes across too.
+ doc.mesh.ensureColors();
+ for (uint32_t v = 0; v < doc.mesh.vertexCount(); ++v)
+ doc.mesh.colors[v] = doc.mesh.positions[v].y > 0.0f ? glm::vec3(0.8f, 0.1f, 0.1f) : glm::vec3(0.1f, 0.2f, 0.8f);
+ const Mesh source = doc.mesh;
+ // Retopo a copy, divide it twice, then project from the original.
+ doc.addSubtool(doc.mesh, "Retopo");
+ CHECK(reg.execute(doc, "qremesh", {{"target", 2000.0}}).ok);
+ CHECK(reg.execute(doc, "subdivide", {{"levels", 2.0}}).ok);
+ const Mesh divided = doc.mesh;
+ // Both ways: the divided retopo's vertices to the sculpt, and the sculpt's (its detail) to the retopo.
+ const SurfaceDeviation before = measureDeviation(divided, source);
+ const CommandResult r = reg.execute(doc, "project_all", {{"distance", 0.05}});
+ CHECK(r.ok);
+ std::printf(" %s\n", r.message.c_str());
+ const SurfaceDeviation after = measureDeviation(doc.mesh, source);
+ std::printf(" divided retopo vs sculpt: mean %.5f max %.5f before ProjectAll, mean %.5f max %.5f after\n",
+ before.mean, before.max, after.mean, after.max);
+ CHECK(after.mean < before.mean * 0.25f);
+ CHECK(after.max < before.max * 0.5f);
+ // Colours came across.
+ CHECK(doc.mesh.hasColors());
+ size_t wrong = 0;
+ for (uint32_t v = 0; v < doc.mesh.vertexCount(); ++v) {
+ const float y = doc.mesh.positions[v].y;
+ if (std::abs(y) > 0.05f && (doc.mesh.colors[v].x > 0.5f) != (y > 0.0f)) ++wrong;
+ }
+ CHECK(wrong == 0);
+ // One undo step back to the divided retopo.
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));
+ CHECK(doc.mesh.positions == divided.positions);
+ CHECK(doc.mesh.colors == divided.colors);
+}
+
+TEST(project_all_respects_mask_and_options) {
+ CommandRegistry reg;
+ Document doc = sculptedSphere(5);
+ doc.addSubtool(doc.mesh, "Retopo");
+ CHECK(reg.execute(doc, "qremesh", {{"target", 1500.0}}).ok);
+ CHECK(reg.execute(doc, "subdivide", {}).ok);
+ const Mesh divided = doc.mesh;
+ // Mask the top half: it must not move.
+ doc.mesh.ensureMask();
+ for (uint32_t v = 0; v < doc.mesh.vertexCount(); ++v) doc.mesh.mask[v] = doc.mesh.positions[v].y > 0.0f ? 1.0f : 0.0f;
+ CHECK(reg.execute(doc, "project_all", {{"polypaint", false}}).ok);
+ size_t movedMasked = 0, movedFree = 0;
+ for (uint32_t v = 0; v < doc.mesh.vertexCount(); ++v) {
+ const bool moved = doc.mesh.positions[v] != divided.positions[v];
+ if (doc.mesh.mask[v] > 0.5f) movedMasked += moved;
+ else movedFree += moved;
+ }
+ CHECK(movedMasked == 0);
+ CHECK(movedFree > doc.mesh.vertexCount() / 4);
+ // A tiny Dist finds nothing for vertices far from the sculpt; geometry off moves nothing.
+ doc.mesh.clearMask();
+ std::vector<glm::vec3> positions;
+ ProjectStats st;
+ std::string err;
+ ProjectOptions o;
+ o.geometry = false;
+ std::vector<const Mesh*> sources{&doc.subtoolMesh(0)};
+ CHECK(computeProjection(divided, sources, o, positions, nullptr, st, err));
+ CHECK(positions == divided.positions);
+ // Nothing visible to project from.
+ doc.subtools[0].visible = false;
+ CHECK(!reg.execute(doc, "project_all", {}).ok);
+}
+
+TEST(retopo_bench_1m_triangles) {
+ if (!std::getenv("SF_RETOPO_BENCH")) return;
+ CommandRegistry reg;
+ Document doc = sculptedSphere(6);
+ CHECK(reg.execute(doc, "subdivide", {{"levels", 2.0}}).ok); // 1.3M triangles
+ std::printf(" bench: sculpt with %zu triangles\n", doc.mesh.triangleCount());
+ for (int target : {5000, 20000, 100000}) {
+ QRemeshOptions o;
+ o.targetQuads = target;
+ Mesh out;
+ std::string err;
+ QRemeshStats st;
+ CHECK(qremesh(doc.mesh, o, out, err, {}, &st));
+ const TopologyReport t = topologyReport(out);
+ std::printf(" bench: QRemesh target %d -> %zu quads (%.1f%% quads, manifold %d) in %.2f s\n", target, st.quads,
+ 100.0f * t.quadFraction(), int(t.manifold()), st.seconds);
+ }
+ // ProjectAll onto a 1.3M-triangle target from the 1.3M-triangle sculpt.
+ doc.addSubtool(doc.mesh, "Retopo");
+ CHECK(reg.execute(doc, "qremesh", {{"target", 5000.0}}).ok);
+ CHECK(reg.execute(doc, "subdivide", {{"levels", 4.0}}).ok);
+ const auto t0 = std::chrono::steady_clock::now();
+ const CommandResult r = reg.execute(doc, "project_all", {});
+ const double s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+ std::printf(" bench: ProjectAll onto %zu triangles: %.2f s (with undo and BVH) - %s\n", doc.mesh.triangleCount(), s,
+ r.message.c_str());
+}