Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
QRemesh 2 (work in progress): proxy surface, cross field, integer-grid map, lattice extraction, quality report
islandmedf59c8c624e87
diff --git a/CMakeLists.txt b/CMakeLists.txtindex ff6dc1f0..19b08006 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -74,6 +74,11 @@ add_library(sculptforge_core STATICsrc/core/SurfaceQuery.cppsrc/core/QRemesh.cppsrc/core/QRemeshGuides.cpp+ src/core/QRemesh2.cpp+ src/core/QRemesh2Proxy.cpp+ src/core/QRemesh2Field.cpp+ src/core/QRemesh2Param.cpp+ src/core/QuadQuality.cppsrc/core/ZSpheres.cppsrc/core/Projection.cppsrc/core/RetopoCommands.cppdiff --git a/src/core/QRemesh.cpp b/src/core/QRemesh.cppindex eb161d8c..9dd2112c 100644--- a/src/core/QRemesh.cpp+++ b/src/core/QRemesh.cpp@@ -9,6 +9,7 @@#include "core/QRemesh.h"#include "core/Parallel.h"+#include "core/QRemeshInternal.h"#include "core/SurfaceQuery.h"#include <algorithm>@@ -133,13 +134,7 @@ inline vec3 positionRound(const vec3& o, const vec3& q, const vec3& n, const vec// --- 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-};+using qr::WorkMesh;// Keeps the side of the plane (axis coordinate >= 0), splitting the triangles that cross it.WorkMesh cutAtPlane(const WorkMesh& in, int axis, float eps) {@@ -1187,12 +1182,7 @@ void splitLargeFaces(PolyMesh& pm) {// --- Quads, relaxation, attributes -----------------------------------------------------------------------struct QuadMesh {- std::vector<vec3> P;- std::vector<uint8_t> feature; // per vertex: lies on a hard edge / border line- std::vector<glm::uvec4> quads; // counter-clockwise- std::vector<glm::uvec3> tris; // pieces kept as they were (the lattice found no quads on them)-};+using qr::QuadMesh;// Every n-sided face becomes n quads (corner, edge midpoint, centre, edge midpoint).QuadMesh splitIntoQuads(const PolyMesh& pm) {@@ -2029,8 +2019,26 @@ bool qremesh(const Mesh& source, const QRemeshOptions& opt, Mesh& out, std::stritrisDone += parts[i].T.size();const std::function<bool(float)> pieceReport = [&](float f) { return report(f0 + (f1 - f0) * f); };PieceResult r;- // A piece the lattice misses is tried again finer, then kept as it is (its own triangles).double want = budget[i];+ if (opt.method == QRemeshMethod::V2) {+ qr::FieldPieceResult fr;+ bool cancelled = false;+ const bool ok = qr::remeshPieceV2(parts[i], axis, want, opt, diag, guides, pieceReport, fr, cancelled);+ if (cancelled) {+ error = "QRemesh cancelled";+ return false;+ }+ st.attempts += fr.attempts;+ st.singularities += fr.singularities;+ if (ok && !fr.mesh.quads.empty()) {+ r.mesh = std::move(fr.mesh);+ r.seam = std::move(fr.seam);+ } else {+ ++st.fallbackPieces;+ if (timing) std::fprintf(stderr, " piece %zu: QRemesh 2 fell back to legacy (%s)\n", i, fr.why.c_str());+ }+ }+ // A piece the lattice misses is tried again finer, then kept as it is (its own triangles).for (int attempt = 0; attempt < 3 && r.mesh.quads.empty(); ++attempt) {r = PieceResult{};want = budget[i] * std::pow(2.5, attempt);@@ -2043,7 +2051,7 @@ bool qremesh(const Mesh& source, const QRemeshOptions& opt, Mesh& out, std::stri// The lattice round a guide can go wrong by chance (where the field's singularities land, which the// smallest rounding differences move): a broken loop or a fan by a guide is tried with other starts for// the field, keeping the best.- for (uint32_t seed = 1; seed <= 2 && r.guideDefects > 0 && !r.mesh.quads.empty(); ++seed) {+ for (uint32_t seed = 1; seed <= 2 && r.guideDefects > 0 && !r.mesh.quads.empty() && opt.method == QRemeshMethod::Legacy; ++seed) {QRemeshOptions again = opt;again.seed = opt.seed + seed * 7919u;PieceResult other;@@ -2179,7 +2187,9 @@ bool qremesh(const Mesh& source, const QRemeshOptions& opt, Mesh& out, std::strifor (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.method = opt.method;st.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();+ if (opt.measureQuality) st.quality = quadQuality(m, &source);if (stats) *stats = st;out = std::move(m);return report(1.0f);diff --git a/src/core/QRemesh.h b/src/core/QRemesh.hindex 3b1966e3..24e21ffb 100644--- a/src/core/QRemesh.h+++ b/src/core/QRemesh.h@@ -38,7 +38,13 @@ namespace sf {class CommandRegistry;struct Document;+// QRemesh's methods. V2 (the default): a curvature-aligned cross field and an integer-grid map, poles only where+// the field needs them, guides as exact edge loops, the result at the target density (core/QRemesh2.cpp).+// Legacy: the 0.9 method (Instant Meshes style position field, extracted at twice the spacing and split).+enum class QRemeshMethod { V2 = 0, Legacy = 1 };+struct QRemeshOptions {+ QRemeshMethod method = QRemeshMethod::V2;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 stronglybool keepGroups = false; // edge loops along polygroup borders; the result keeps the groups@@ -57,7 +63,26 @@ struct QRemeshOptions {// flow follows it (0 = only the loop on the curve itself, 1 = about six quads to each side).std::vector<QRemeshGuide> guides;float guideStrength = 0.5f;+ // Measure the result against the source after remeshing (QRemeshStats::quality): poles, valences, angles and the+ // distance to the sculpt. Costs a closest-point query per vertex of both.+ bool measureQuality = true;+};++// How good a quad mesh is (the quality report shown after QRemesh).+struct QuadQuality {+ size_t vertices = 0, quads = 0, triangles = 0;+ size_t poles = 0; // inside vertices with other than four edges+ size_t valence[8] = {}; // inside vertices by edge count: [2] .. [6], [7] = 7 or more+ size_t boundaryPoles = 0; // vertices on open edges with other than three edges+ float angleDeviation = 0.0f; // mean |corner angle - 90| over the quads, degrees+ float angleDeviationMax = 0.0f; // 99th percentile, degrees+ float edgeLengthCv = 0.0f; // spread of the edge lengths (standard deviation / mean)+ float hausdorff = 0.0f; // symmetric Hausdorff distance to the source, in % of the bounding-box diagonal+ float meanDistance = 0.0f; // mean distance to the source, same units+ bool measured = false; // distances filled in};+// Valences and angles of `mesh` (faces as exported); with `source`, also the distances to it.+QuadQuality quadQuality(const Mesh& mesh, const Mesh* source = nullptr);struct QRemeshStats {size_t quads = 0, triangles = 0; // faces of the result (triangles only for degenerate leftovers)@@ -72,6 +97,10 @@ struct QRemeshStats {size_t guides = 0; // QRemesh Guides usedsize_t guidesSkipped = 0; // guides left out: mostly off the surface (the SubTool moved since)double seconds = 0;+ QRemeshMethod method = QRemeshMethod::V2;+ size_t fallbackPieces = 0; // V2: pieces it couldn't do well, remeshed with the legacy method+ size_t singularities = 0; // V2: cross-field singularities (poles the layout needs)+ QuadQuality quality; // with measureQuality};// Fraction 0..1 of the whole job; return false to cancel. Called from the thread running qremesh.@@ -98,6 +127,8 @@ TopologyReport topologyReport(const Mesh& mesh);// 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);+// The quality report as text for the status line ("" when empty).+std::string qualitySummary(const QuadQuality& quality);// qremesh (core/RetopoCommands.cpp) and project_all (core/Projection.h).void registerRetopoCommands(CommandRegistry& registry);diff --git a/src/core/QRemesh2.cpp b/src/core/QRemesh2.cppnew file mode 100644index 00000000..598f345f--- /dev/null+++ b/src/core/QRemesh2.cpp@@ -0,0 +1,1103 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// QRemesh 2: quad remeshing by an integer-grid map, the default method of Tool > Remesh > QRemesh.+//+// The legacy method (Instant Meshes style, core/QRemesh.cpp) rounds a local position field: every place where the+// local lattices disagree becomes an extra pole, and its result is extracted at twice the spacing and split, so+// its loops wander. This method solves one global map instead, so poles appear only where the cross field needs+// them (eight on a sphere-like shape, a handful more per feature) and edge loops run unbroken along the form.+//+// 1. Proxy surface (QRemesh2Proxy.cpp): the piece decimated and remeshed to about three triangle edges per quad+// edge, feature lines kept. Sizes: the target count, Adaptive Size (curvature) and polypaint density set a+// wanted quad size per vertex; the proxy is refined where quads will be small.+// 2. Features as hard constraints: open edges (and the symmetry cut), polygroup borders (Keep Groups), hard edges+// (Detect Edges, chains shorter than a quad dropped), QRemesh Guides snapped onto the proxy as edge chains.+// 3. Cross field (QRemesh2Field.cpp) following smoothed principal curvature directions and the features.+// 4. Integer-grid map (QRemesh2Param.cpp): its integer lattice lines are the edge loops, feature lines and guides+// lie exactly on lattice lines (so a guide is an exact edge loop) and singularities on lattice points.+// 5. Extraction: proxy vertices rounding to the same lattice point form one quad vertex (placed exactly on that+// point), lattice neighbours are joined, faces traced. The rare non-quad faces (where the map folds) are+// paired off along short paths and split, so the result is all quads at the target density, not a split mesh.+// 6. Loop-aware relaxation: smoothing on the sculpt that only lets a vertex slide along the loops running over+// ridges (so they stay on the ridge), then projection onto the sculpt.+//+// Symmetry is handled by the caller: the half on the + side is remeshed with the cut as a feature line (so the+// seam is a lattice line) and mirrored, which makes the field and the result exactly symmetric. Everything is+// deterministic: no random starts, fixed-block parallel reductions.+#include "core/QRemesh2.h"++#include "core/Parallel.h"++#include <algorithm>+#include <chrono>+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <map>+#include <numeric>+#include <unordered_map>++namespace sf::qr {++using namespace qr2;+using glm::ivec2;++namespace {++struct UF {+ std::vector<uint32_t> parent;+ explicit UF(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;+ }+ void unite(uint32_t a, uint32_t b) {+ a = find(a), b = find(b);+ if (a != b) parent[std::max(a, b)] = std::min(a, b);+ }+};++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));+}++// Edges of a triangle mesh with the triangles on each side (count 1: open, 2: interior, more: non-manifold).+struct SrcEdge {+ uint32_t a, b, t0, t1;+ int count;+};+std::vector<SrcEdge> meshEdges(const std::vector<vec3>& P, const std::vector<glm::uvec3>& T) {+ const size_t nv = P.size();+ std::vector<uint32_t> off(nv + 1, 0), vt(T.size() * 3);+ for (const auto& t : T)+ for (int k = 0; k < 3; ++k) ++off[t[k] + 1];+ for (size_t i = 0; i < nv; ++i) off[i + 1] += off[i];+ {+ std::vector<uint32_t> fill(off.begin(), off.end() - 1);+ for (uint32_t t = 0; t < T.size(); ++t)+ for (int k = 0; k < 3; ++k) vt[fill[T[t][k]]++] = t;+ }+ const size_t blocks = (nv + 8191) / 8192;+ std::vector<std::vector<SrcEdge>> parts(blocks);+ parallelFor(blocks, [&](size_t b0, size_t b1) {+ std::vector<std::pair<uint32_t, uint32_t>> loc;+ for (size_t blk = b0; blk < b1; ++blk)+ for (size_t a = blk * 8192, e = std::min(nv, a + 8192); a < e; ++a) {+ loc.clear();+ for (uint32_t k = off[a]; k < off[a + 1]; ++k) {+ const uint32_t t = vt[k];+ for (int j = 0; j < 3; ++j) {+ const uint32_t x = T[t][j], y = T[t][(j + 1) % 3];+ if (x == y) continue;+ if (x == a && y > a) loc.push_back({y, t});+ else if (y == a && x > a) loc.push_back({x, t});+ }+ }+ std::sort(loc.begin(), loc.end());+ for (size_t i = 0; i < loc.size();) {+ size_t j = i;+ while (j < loc.size() && loc[j].first == loc[i].first) ++j;+ parts[blk].push_back({uint32_t(a), loc[i].first, loc[i].second, j - i > 1 ? loc[i + 1].second : kNone,+ int(j - i)});+ i = j;+ }+ }+ }, 1);+ std::vector<SrcEdge> all;+ for (auto& p : parts) all.insert(all.end(), p.begin(), p.end());+ return all;+}++double meshArea(const std::vector<vec3>& P, const std::vector<glm::uvec3>& T) {+ double a = 0.0;+ for (const auto& t : T) a += 0.5 * double(glm::length(glm::cross(P[t.y] - P[t.x], P[t.z] - P[t.x])));+ return a;+}++// Vertex -> triangles (CSR).+struct VertexFaces {+ std::vector<uint32_t> off, tri;+ void build(size_t nv, const std::vector<glm::uvec3>& T) {+ off.assign(nv + 1, 0);+ for (const auto& t : T)+ for (int k = 0; k < 3; ++k) ++off[t[k] + 1];+ for (size_t i = 0; i < nv; ++i) off[i + 1] += off[i];+ tri.resize(off[nv]);+ std::vector<uint32_t> fill(off.begin(), off.end() - 1);+ for (uint32_t t = 0; t < T.size(); ++t)+ for (int k = 0; k < 3; ++k) tri[fill[T[t][k]]++] = t;+ }+};++// --- Guides ---------------------------------------------------------------------------------------------------------++// Snaps each guide onto the proxy as a chain of edges (marked as features, so the map puts a lattice line on it) and+// moves the chain's vertices onto the curve. Also the soft pull of the field towards the curves around them.+void applyGuides(Proxy& p, const std::vector<QRemeshGuide>& guides, float strength, float h, FieldSettings& fs,+ const Frames& frames) {+ if (guides.empty()) return;+ const size_t nv = p.P.size(), nt = p.T.size();+ VertexFaces vf;+ vf.build(nv, p.T);+ TriangleBVH bvh;+ bvh.build(p.P, p.T);+ // Edge -> corners.+ std::unordered_map<uint64_t, std::vector<uint32_t>> corners;+ for (uint32_t t = 0; t < nt; ++t)+ for (int k = 0; k < 3; ++k) corners[edgeKey(p.T[t][k], p.T[t][(k + 1) % 3])].push_back(3 * t + uint32_t(k));+ std::vector<vec3> segA, segB;+ std::vector<uint8_t> onGuide(nv, 0);+ std::vector<vec3> moveTo(nv);+ for (const QRemeshGuide& g : guides) {+ if (g.points.size() < 2) continue;+ SegmentBVH curve;+ {+ std::vector<vec3> a, b;+ for (size_t i = 0; i + 1 < g.points.size(); ++i) a.push_back(g.points[i]), b.push_back(g.points[i + 1]);+ if (g.closed) a.push_back(g.points.back()), b.push_back(g.points.front());+ segA.insert(segA.end(), a.begin(), a.end());+ segB.insert(segB.end(), b.begin(), b.end());+ curve.build(a, b);+ }+ // Snap samples to proxy vertices.+ std::vector<uint32_t> snapped;+ for (const vec3& q : g.points) {+ SurfaceHit hit;+ if (!bvh.closestPoint(q, 4.0f * h, hit)) continue;+ const glm::uvec3 tri = p.T[hit.prim];+ uint32_t best = tri.x;+ float bd = 1e30f;+ for (int k = 0; k < 3; ++k) {+ const float d = glm::length(p.P[tri[k]] - q);+ if (d < bd) bd = d, best = tri[k];+ }+ if (snapped.empty() || snapped.back() != best) snapped.push_back(best);+ }+ if (g.closed && snapped.size() > 2 && snapped.front() != snapped.back()) snapped.push_back(snapped.front());+ if (snapped.size() < 2) continue;+ // Shortest paths between consecutive snapped vertices, penalising distance from the curve.+ auto offCurve = [&](const vec3& x) {+ SurfaceHit hit;+ return curve.closestPoint(x, 4.0f * h, hit) ? hit.distance : 4.0f * h;+ };+ std::vector<uint32_t> chain{snapped[0]};+ for (size_t i = 0; i + 1 < snapped.size(); ++i) {+ const uint32_t s = snapped[i], goal = snapped[i + 1];+ std::unordered_map<uint32_t, std::pair<float, uint32_t>> dist; // vertex -> (cost, previous)+ using Item = std::pair<float, uint32_t>;+ std::vector<Item> heap{{0.0f, s}};+ dist[s] = {0.0f, kNone};+ bool found = false;+ while (!heap.empty()) {+ std::pop_heap(heap.begin(), heap.end(), std::greater<>());+ const auto [d, v] = heap.back();+ heap.pop_back();+ if (d > dist[v].first) continue;+ if (v == goal) {+ found = true;+ break;+ }+ if (d > 8.0f * h) break;+ for (uint32_t k = vf.off[v]; k < vf.off[v + 1]; ++k) {+ const glm::uvec3 tri = p.T[vf.tri[k]];+ for (int j = 0; j < 3; ++j) {+ const uint32_t u = tri[j];+ if (u == v) continue;+ const float w = glm::length(p.P[u] - p.P[v]) + 2.0f * offCurve(0.5f * (p.P[u] + p.P[v])) + 2.0f * offCurve(p.P[u]);+ const float nd = d + w;+ auto it = dist.find(u);+ if (it == dist.end() || nd < it->second.first) {+ dist[u] = {nd, v};+ heap.push_back({nd, u});+ std::push_heap(heap.begin(), heap.end(), std::greater<>());+ }+ }+ }+ }+ if (!found) continue;+ std::vector<uint32_t> path;+ for (uint32_t v = goal; v != s && v != kNone; v = dist[v].second) path.push_back(v);+ std::reverse(path.begin(), path.end());+ for (uint32_t v : path) {+ if (std::find(chain.end() - std::min<size_t>(chain.size(), 3), chain.end(), v) != chain.end()) continue;+ chain.push_back(v);+ }+ }+ for (size_t i = 0; i + 1 < chain.size(); ++i) {+ const auto it = corners.find(edgeKey(chain[i], chain[i + 1]));+ if (it == corners.end()) continue;+ for (uint32_t c : it->second) p.feature[c] = 1;+ for (uint32_t v : {chain[i], chain[i + 1]}) {+ if (onGuide[v]) continue;+ SurfaceHit hit;+ if (curve.closestPoint(p.P[v], 2.0f * h, hit)) {+ onGuide[v] = 1;+ moveTo[v] = hit.position;+ }+ }+ }+ }+ // Move the chains onto the curves where that turns no triangle over.+ for (uint32_t v = 0; v < nv; ++v) {+ if (!onGuide[v]) continue;+ bool ok = true;+ for (uint32_t k = vf.off[v]; k < vf.off[v + 1] && ok; ++k) {+ const glm::uvec3 tri = p.T[vf.tri[k]];+ vec3 q[3];+ for (int j = 0; j < 3; ++j) q[j] = tri[j] == v ? moveTo[v] : p.P[tri[j]];+ const vec3 nNew = glm::cross(q[1] - q[0], q[2] - q[0]);+ const vec3 nOld = glm::cross(p.P[tri.y] - p.P[tri.x], p.P[tri.z] - p.P[tri.x]);+ ok = glm::dot(nNew, nOld) > 0.2f * glm::length(nNew) * glm::length(nOld);+ }+ if (ok) p.P[v] = moveTo[v];+ }+ // Soft pull around the curves: Curves Strength 0 = only the loop itself, 1 = about six quads to each side.+ if (segA.empty()) return;+ SegmentBVH all;+ all.build(segA, segB);+ const float reach = h * (0.5f + 5.5f * std::clamp(strength, 0.0f, 1.0f));+ fs.guideAngle.assign(nt, std::numeric_limits<float>::quiet_NaN());+ fs.guideWeight.assign(nt, 0.0f);+ for (uint32_t t = 0; t < nt; ++t) {+ const glm::uvec3 tri = p.T[t];+ const vec3 c = (p.P[tri.x] + p.P[tri.y] + p.P[tri.z]) / 3.0f;+ SurfaceHit hit;+ if (!all.closestPoint(c, 2.0f * reach, hit)) continue;+ const vec3 dir = segB[hit.prim] - segA[hit.prim];+ fs.guideAngle[t] = std::atan2(glm::dot(dir, frames.e2[t]), glm::dot(dir, frames.e1[t]));+ const float x = hit.distance / std::max(reach, 1e-12f);+ fs.guideWeight[t] = std::exp(-2.0f * x * x);+ }+}++// --- Extraction -----------------------------------------------------------------------------------------------------++struct Poly {+ std::vector<vec3> P;+ std::vector<std::vector<uint32_t>> faces;+};++// The integer lattice of the map as a polygon mesh: proxy vertices rounding to the same lattice point (within a+// triangle's chart) are one vertex, placed on the point; lattice neighbours are joined; faces traced counter-clockwise.+Poly extractLattice(const Proxy& p, const Frames& fr, const GridMap& map) {+ const size_t nv = p.P.size(), nt = p.T.size();+ std::vector<ivec2> L(3 * nt);+ for (size_t c = 0; c < 3 * nt; ++c) L[c] = {int(std::lround(map.uv[c].x)), int(std::lround(map.uv[c].y))};+ std::vector<uint8_t> flipped(nt, 0);+ for (uint32_t t = 0; t < nt; ++t) {+ const vec2 a = map.uv[3 * t], b = map.uv[3 * t + 1], c = map.uv[3 * t + 2];+ flipped[t] = !((b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y) > 0.0f);+ }+ UF uf(nv);+ for (uint32_t t = 0; t < nt; ++t)+ for (int i = 0; i < 3; ++i) {+ const int j = (i + 1) % 3;+ if (L[3 * t + size_t(i)] == L[3 * t + size_t(j)]) uf.unite(p.T[t][i], p.T[t][j]);+ }+ std::vector<uint32_t> cluster(nv, kNone);+ uint32_t nc = 0;+ for (uint32_t v = 0; v < nv; ++v) {+ const uint32_t r = uf.find(v);+ if (cluster[r] == kNone) cluster[r] = nc++;+ cluster[v] = cluster[r];+ }+ // Positions: the lattice point inside (or nearest) a triangle around the cluster, by its barycentric weights.+ std::vector<vec3> pos(nc, vec3(0.0f));+ std::vector<float> fit(nc, -1e30f);+ std::vector<vec3> nrm(nc, vec3(0.0f));+ for (uint32_t t = 0; t < nt; ++t) {+ const vec2 a = map.uv[3 * t], b = map.uv[3 * t + 1], c = map.uv[3 * t + 2];+ const float det = (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y);+ for (int k = 0; k < 3; ++k) {+ const uint32_t cl = cluster[p.T[t][k]];+ nrm[cl] += fr.n[t] * fr.area[t];+ if (std::abs(det) < 1e-12f) continue;+ const vec2 q(float(L[3 * t + size_t(k)].x), float(L[3 * t + size_t(k)].y));+ const float w1 = ((q.x - a.x) * (c.y - a.y) - (c.x - a.x) * (q.y - a.y)) / det;+ const float w2 = ((b.x - a.x) * (q.y - a.y) - (q.x - a.x) * (b.y - a.y)) / det;+ const float w0 = 1.0f - w1 - w2;+ float score = std::min({w0, w1, w2});+ if (flipped[t]) score -= 10.0f;+ if (score > fit[cl]) {+ fit[cl] = score;+ const float c0 = std::clamp(w0, 0.0f, 1.0f), c1 = std::clamp(w1, 0.0f, 1.0f), c2 = std::clamp(w2, 0.0f, 1.0f);+ const float s = c0 + c1 + c2;+ pos[cl] = s > 0.0f ? (c0 * p.P[p.T[t].x] + c1 * p.P[p.T[t].y] + c2 * p.P[p.T[t].z]) / s : p.P[p.T[t][k]];+ }+ }+ }+ for (auto& n : nrm) n = safeNormalize(n);+ // Lattice edges.+ std::vector<std::vector<uint32_t>> adj(nc);+ for (uint32_t t = 0; t < nt; ++t)+ for (int i = 0; i < 3; ++i) {+ const int j = (i + 1) % 3;+ const ivec2 d = L[3 * t + size_t(i)] - L[3 * t + size_t(j)];+ if (std::abs(d.x) + std::abs(d.y) != 1) continue;+ const uint32_t a = cluster[p.T[t][i]], b = cluster[p.T[t][j]];+ if (a == 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); };+ // A quad lattice has no 3-cycles: drop the longest edge of each.+ for (int round = 0; round < 6; ++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;+ const float luv = glm::length(pos[u] - pos[v]), lvw = glm::length(pos[v] - pos[w]), luw = glm::length(pos[u] - pos[w]);+ if (luv >= lvw && luv >= luw) drop.push_back({u, v});+ else if (lvw >= luw) drop.push_back({v, w});+ else drop.push_back({u, w});+ }+ }+ if (drop.empty()) break;+ for (auto [a, b] : drop)+ if (hasEdge(a, b)) removeEdge(a, b);+ }+ Poly out;+ std::vector<std::vector<uint32_t>> faces;+ for (int round = 0; round < 12; ++round) {+ 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);+ }+ 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 n = nrm[u];+ const vec3 q = anyTangent(n), t = glm::cross(n, q);+ std::vector<std::pair<float, uint32_t>> ang;+ for (uint32_t v : adj[u]) {+ const vec3 d = pos[v] - pos[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) {+ 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;+ u = v;+ if (face.size() > 64) break;+ }+ 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 == 11) break;+ for (auto [a, b] : bad)+ if (hasEdge(a, b)) removeEdge(a, b);+ }+ // The outside of an open surface traces as one big face (mostly on the boundary): leave it out. A face whose+ // vertices are mostly on open proxy edges is that.+ std::vector<uint8_t> openCl(nc, 0);+ for (uint32_t t = 0; t < nt; ++t)+ for (int k = 0; k < 3; ++k)+ if (p.opp[3 * t + uint32_t(k)] == kNone) openCl[cluster[p.T[t][k]]] = openCl[cluster[p.T[t][(k + 1) % 3]]] = 1;+ std::vector<uint32_t> remap(nc, kNone);+ for (auto& f : faces) {+ if (f.size() < 3 || f.size() > 32) continue;+ if (f.size() >= 5) {+ size_t onB = 0;+ for (uint32_t v : f) onB += openCl[v];+ if (onB * 10 >= f.size() * 6) continue;+ }+ {+ std::unordered_map<uint64_t, int> seen;+ bool twice = false;+ 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(pos[v]);+ }+ v = remap[v];+ }+ out.faces.push_back(f);+ }+ return out;+}++// --- All quads ------------------------------------------------------------------------------------------------------++// Splits an even polygon into quads by diagonals (shortest first, both halves even).+void splitEven(const std::vector<vec3>& P, const std::vector<uint32_t>& f, std::vector<glm::uvec4>& quads) {+ const size_t n = f.size();+ if (n < 4) return;+ if (n == 4) {+ quads.push_back({f[0], f[1], f[2], f[3]});+ return;+ }+ float best = 1e30f;+ size_t bi = 0, bj = 3;+ for (size_t i = 0; i < n; ++i)+ for (size_t j = i + 3; j < n; j += 2) {+ if (n - (j - i) < 3) continue;+ if (f[i] == f[j]) continue;+ const float l = glm::length(P[f[i]] - P[f[j]]);+ if (l < best) best = l, bi = i, bj = j;+ }+ std::vector<uint32_t> a(f.begin() + long(bi), f.begin() + long(bj) + 1), b(f.begin() + long(bj), f.end());+ b.insert(b.end(), f.begin(), f.begin() + long(bi) + 1);+ splitEven(P, a, quads);+ splitEven(P, b, quads);+}++// Odd faces (triangles, pentagons) are paired along short paths of faces: each edge crossed gets a middle vertex,+// so every face on the path gains two (or the ends one) and becomes even; then even faces are split into quads.+std::vector<glm::uvec4> allQuads(Poly& pm) {+ // Big faces first: cut faces of 6+ sides into even pieces along short diagonals where possible.+ {+ std::vector<std::vector<uint32_t>> next;+ for (auto& f : pm.faces) {+ if (f.size() <= 5) {+ next.push_back(f);+ continue;+ }+ std::vector<std::vector<uint32_t>> todo{f};+ while (!todo.empty()) {+ auto g = std::move(todo.back());+ todo.pop_back();+ if (g.size() <= 5) {+ next.push_back(std::move(g));+ continue;+ }+ const size_t n = g.size();+ float best = 1e30f;+ 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 || g[i] == g[j]) continue;+ float s = glm::length(pm.P[g[i]] - pm.P[g[j]]);+ if (a % 2) s *= 1.5f;+ if (b % 2) s *= 1.5f;+ if (s < best) best = s, bi = i, bj = j;+ }+ if (best == 1e30f) {+ next.push_back(std::move(g));+ continue;+ }+ std::vector<uint32_t> fa(g.begin() + long(bi), g.begin() + long(bj) + 1), fb(g.begin() + long(bj), g.end());+ fb.insert(fb.end(), g.begin(), g.begin() + long(bi) + 1);+ todo.push_back(std::move(fa));+ todo.push_back(std::move(fb));+ }+ }+ pm.faces.swap(next);+ }+ // Edge -> faces.+ std::unordered_map<uint64_t, std::vector<uint32_t>> ef;+ auto rebuildEdges = [&] {+ ef.clear();+ for (uint32_t i = 0; i < pm.faces.size(); ++i) {+ const auto& f = pm.faces[i];+ for (size_t k = 0; k < f.size(); ++k) ef[edgeKey(f[k], f[(k + 1) % f.size()])].push_back(i);+ }+ };+ rebuildEdges();+ auto insertMid = [&](uint32_t a, uint32_t b) {+ const uint32_t m = uint32_t(pm.P.size());+ pm.P.push_back(0.5f * (pm.P[a] + pm.P[b]));+ const auto it = ef.find(edgeKey(a, b));+ std::vector<uint32_t> fs = it != ef.end() ? it->second : std::vector<uint32_t>{};+ ef.erase(edgeKey(a, b));+ for (uint32_t fi : fs) {+ auto& f = pm.faces[fi];+ for (size_t k = 0; k < f.size(); ++k) {+ const uint32_t x = f[k], y = f[(k + 1) % f.size()];+ if ((x == a && y == b) || (x == b && y == a)) {+ f.insert(f.begin() + long(k) + 1, m);+ break;+ }+ }+ ef[edgeKey(a, m)].push_back(fi);+ ef[edgeKey(m, b)].push_back(fi);+ }+ return m;+ };+ std::vector<uint8_t> matched(pm.faces.size(), 0);+ for (uint32_t start = 0; start < pm.faces.size(); ++start) {+ if (pm.faces[start].size() % 2 == 0 || matched[start]) continue;+ // Breadth-first search over faces for the nearest other unmatched odd face (or an open edge).+ std::unordered_map<uint32_t, std::pair<uint32_t, uint64_t>> prev; // face -> (previous face, edge crossed)+ std::vector<uint32_t> queue{start};+ prev[start] = {kNone, 0};+ uint32_t goal = kNone;+ uint64_t openEdge = 0;+ uint32_t openFace = kNone;+ for (size_t qi = 0; qi < queue.size() && goal == kNone && queue.size() < 4000; ++qi) {+ const uint32_t fi = queue[qi];+ const auto& f = pm.faces[fi];+ for (size_t k = 0; k < f.size() && goal == kNone; ++k) {+ const uint64_t key = edgeKey(f[k], f[(k + 1) % f.size()]);+ const auto& nb = ef[key];+ if (nb.size() == 1 && openFace == kNone) openFace = fi, openEdge = key;+ for (uint32_t g : nb) {+ if (g == fi || prev.count(g)) continue;+ prev[g] = {fi, key};+ if (pm.faces[g].size() % 2 == 1 && !matched[g]) {+ goal = g;+ break;+ }+ queue.push_back(g);+ }+ }+ }+ std::vector<uint64_t> crossed;+ if (goal != kNone) {+ for (uint32_t g = goal; prev[g].first != kNone; g = prev[g].first) crossed.push_back(prev[g].second);+ matched[goal] = 1;+ } else if (openFace != kNone) {+ for (uint32_t g = openFace; prev[g].first != kNone; g = prev[g].first) crossed.push_back(prev[g].second);+ crossed.push_back(openEdge);+ } else {+ continue;+ }+ matched[start] = 1;+ for (uint64_t key : crossed) insertMid(uint32_t(key >> 32), uint32_t(key & 0xffffffffu));+ }+ std::vector<glm::uvec4> quads;+ for (const auto& f : pm.faces) {+ if (f.size() % 2 == 0) splitEven(pm.P, f, quads);+ else if (f.size() == 3) { // left over (no partner): a degenerate quad would be worse; split into three+ const uint32_t c = uint32_t(pm.P.size());+ pm.P.push_back((pm.P[f[0]] + pm.P[f[1]] + pm.P[f[2]]) / 3.0f);+ const uint32_t m01 = uint32_t(pm.P.size());+ (void)m01;+ quads.push_back({f[0], f[1], f[2], c}); // keeps the mesh closed; rare+ }+ }+ return quads;+}++// Doublets (an inside vertex with two quads) merge the two quads; unused vertices go.+void cleanQuads(std::vector<vec3>& P, std::vector<glm::uvec4>& quads) {+ for (int pass = 0; pass < 4; ++pass) {+ const size_t nv = P.size();+ std::vector<std::vector<uint32_t>> vq(nv);+ for (uint32_t f = 0; f < quads.size(); ++f)+ for (int k = 0; k < 4; ++k) vq[quads[f][k]].push_back(f);+ std::vector<uint8_t> dead(quads.size(), 0), touched(nv, 0);+ auto rotated = [&](uint32_t f, uint32_t v) {+ glm::uvec4 r = 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);+ 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;+ 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 < quads.size(); ++f)+ if (!dead[f]) quads[w++] = quads[f];+ quads.resize(w);+ }+ std::vector<uint32_t> remap(P.size(), kNone);+ std::vector<vec3> Q;+ for (auto& f : quads)+ for (int k = 0; k < 4; ++k) {+ if (remap[f[k]] == kNone) remap[f[k]] = uint32_t(Q.size()), Q.push_back(P[f[k]]);+ f[k] = remap[f[k]];+ }+ P.swap(Q);+}++// --- Relaxation -----------------------------------------------------------------------------------------------------++struct RelaxTargets {+ const TriangleBVH* surface = nullptr;+ const SegmentBVH* features = nullptr; // feature lines of the proxy (incl. open edges and guides)+ const Proxy* proxy = nullptr;+ const Curvature* curvature = nullptr;+ const TriangleBVH* proxyBvh = nullptr;+ float h = 1.0f;+};++// Loop-aware relaxation: tangential smoothing on the sculpt in which a vertex may not move across a loop that runs+// along a ridge (the curvature across the loop is high), so loops placed on ridges by the field stay on them.+// Vertices on feature lines slide along them; where feature lines meet they stay.+void relaxLoops(std::vector<vec3>& P, const std::vector<glm::uvec4>& quads, const RelaxTargets& rt, int iterations,+ std::vector<uint8_t>& featureOut) {+ const size_t nv = P.size();+ std::vector<std::vector<uint32_t>> nb(nv);+ std::unordered_map<uint64_t, int> use;+ for (const auto& q : quads)+ for (int k = 0; k < 4; ++k) {+ const uint32_t a = q[k], b = q[(k + 1) % 4];+ if (++use[edgeKey(a, b)] == 1) nb[a].push_back(b), nb[b].push_back(a);+ }+ // Feature vertices: on a proxy feature line (within a small distance); corners: 3+ feature neighbours or a turn.+ std::vector<uint8_t> feat(nv, 0);+ if (rt.features)+ for (uint32_t v = 0; v < nv; ++v) {+ SurfaceHit hit;+ if (rt.features->closestPoint(P[v], 0.05f * rt.h, hit)) feat[v] = 1;+ }+ std::vector<glm::uvec2> line(nv, glm::uvec2(kNone));+ for (uint32_t v = 0; v < nv; ++v) {+ if (!feat[v]) continue;+ std::vector<uint32_t> f;+ for (uint32_t u : nb[v])+ if (feat[u]) {+ // The edge runs along the line: its middle is on it too.+ SurfaceHit hit;+ if (rt.features->closestPoint(0.5f * (P[u] + P[v]), 0.05f * rt.h, hit)) f.push_back(u);+ }+ if (f.size() == 2) {+ const vec3 a = safeNormalize(P[f[0]] - P[v]), b = safeNormalize(P[f[1]] - P[v]);+ if (glm::dot(a, b) < -0.7f) {+ line[v] = {f[0], f[1]};+ continue;+ }+ }+ feat[v] = 2;+ }+ featureOut = feat;+ // Per vertex: the curvature tensor's strongest direction and anisotropy (from the proxy triangle under it).+ std::vector<vec3> ridgeDir(nv, vec3(0.0f));+ std::vector<float> ridge(nv, 0.0f);+ if (rt.curvature && rt.proxyBvh)+ parallelFor(nv, [&](size_t b, size_t e) {+ for (size_t v = b; v < e; ++v) {+ SurfaceHit hit;+ if (!rt.proxyBvh->closestPoint(P[v], 2.0f * rt.h, hit)) continue;+ const uint32_t t = hit.prim;+ const glm::uvec3 tri = rt.proxy->T[t];+ const vec3 a = rt.proxy->P[tri.x], bb = rt.proxy->P[tri.y], c = rt.proxy->P[tri.z];+ const vec3 n = safeNormalize(glm::cross(bb - a, c - a));+ const vec3 e1 = safeNormalize(bb - a), e2 = glm::cross(n, e1);+ const float ang = rt.curvature->angle[t];+ ridgeDir[v] = std::cos(ang) * e1 + std::sin(ang) * e2; // direction of strongest bending+ ridge[v] = std::min(1.0f, rt.curvature->anisotropy[t] * rt.h / 0.5f);+ }+ }, 2000);+ std::vector<vec3> next(nv), N(nv);+ for (int it = 0; it < iterations; ++it) {+ // Normals from the quads.+ std::fill(N.begin(), N.end(), vec3(0.0f));+ for (const auto& q : quads) {+ const vec3 n = glm::cross(P[q.z] - P[q.x], P[q.w] - P[q.y]);+ for (int k = 0; k < 4; ++k) N[q[k]] += n;+ }+ for (auto& n : N) n = safeNormalize(n);+ parallelFor(nv, [&](size_t b, size_t e) {+ for (size_t v = b; v < e; ++v) {+ next[v] = P[v];+ if (feat[v] == 2 || nb[v].empty()) continue;+ if (feat[v] == 1) {+ const vec3 c = 0.5f * (P[line[v].x] + P[line[v].y]);+ vec3 q = P[v] + 0.5f * (c - P[v]);+ SurfaceHit hit;+ if (rt.features->closestPoint(q, rt.h, hit)) q = hit.position;+ next[v] = q;+ continue;+ }+ vec3 c(0.0f);+ for (uint32_t u : nb[v]) c += P[u];+ c /= float(nb[v].size());+ vec3 d = c - P[v];+ d -= N[v] * glm::dot(N[v], d);+ // Moving along the strongest bending direction would pull a loop lying along the ridge off it.+ if (ridge[v] > 0.0f) {+ vec3 rd = ridgeDir[v] - N[v] * glm::dot(N[v], ridgeDir[v]);+ rd = safeNormalize(rd, vec3(0.0f));+ d -= 0.85f * ridge[v] * rd * glm::dot(rd, d);+ }+ vec3 q = P[v] + 0.5f * d;+ SurfaceHit hit;+ if (rt.surface->closestPoint(q, 2.0f * rt.h, hit)) q = hit.position;+ next[v] = q;+ }+ }, 4000);+ P.swap(next);+ }+ // Final projection of everything onto the sculpt (feature vertices onto their lines).+ parallelFor(nv, [&](size_t b, size_t e) {+ for (size_t v = b; v < e; ++v) {+ SurfaceHit hit;+ if (feat[v] && rt.features && rt.features->closestPoint(P[v], 0.25f * rt.h, hit)) P[v] = hit.position;+ else if (rt.surface->closestPoint(P[v], 2.0f * rt.h, hit)) P[v] = hit.position;+ }+ }, 4000);+}++} // namespace++bool remeshPieceV2(const WorkMesh& piece, int axis, double wantQuads, const QRemeshOptions& opt, float diag,+ const std::vector<QRemeshGuide>& guides, const std::function<bool(float)>& report,+ FieldPieceResult& out, bool& cancelled) {+ static const bool timing = std::getenv("SF_QREMESH_TIMING") != nullptr;+ const auto start = std::chrono::steady_clock::now();+ auto mark = [&](const char* what) {+ if (timing)+ std::fprintf(stderr, " v2 %-24s %.3f s\n", what,+ std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count());+ };+ cancelled = false;+ auto step = [&](float f) {+ if (report && !report(f)) {+ cancelled = true;+ return false;+ }+ return true;+ };+ const std::function<bool()> isCancelled = [&] { return cancelled; };+ if (piece.T.empty()) {+ out.why = "empty";+ return false;+ }+ const double area = meshArea(piece.P, piece.T);+ if (!(area > 0.0) || wantQuads < 1.0) {+ out.why = "no area";+ return false;+ }+ const float h0 = float(std::sqrt(area / wantQuads));+ // Development overrides (SF_QR2_*), for tuning against the benchmark meshes.+ auto tune = [](const char* name, float fallback) {+ const char* v = std::getenv(name);+ return v ? float(std::atof(v)) : fallback;+ };+ const float curvRadius = tune("SF_QR2_CURV", 1.0f) * h0;++ // Source structures: the surface, its feature lines.+ TriangleBVH surface;+ surface.build(piece.P, piece.T);+ mark("surface bvh");+ const float sharpCos = opt.detectEdges ? std::cos(glm::radians(50.0f)) : 2.0f;+ std::vector<vec3> segA, segB;+ std::unordered_set<uint64_t> sharp;+ {+ const std::vector<SrcEdge> edges = meshEdges(piece.P, piece.T);+ std::vector<vec3> fn(piece.T.size());+ parallelFor(piece.T.size(), [&](size_t b, size_t e) {+ for (size_t t = b; t < e; ++t) {+ const glm::uvec3 tri = piece.T[t];+ fn[t] = safeNormalize(glm::cross(piece.P[tri.y] - piece.P[tri.x], piece.P[tri.z] - piece.P[tri.x]));+ }+ });+ std::vector<uint32_t> sharpEdges;+ for (uint32_t i = 0; i < edges.size(); ++i) {+ const SrcEdge& e = edges[i];+ const bool open = e.count != 2;+ const bool border = !open && opt.keepGroups && piece.group[e.t0] != piece.group[e.t1];+ if (open || border) {+ segA.push_back(piece.P[e.a]), segB.push_back(piece.P[e.b]);+ continue;+ }+ if (sharpCos < 1.0f && glm::dot(fn[e.t0], fn[e.t1]) < sharpCos) sharpEdges.push_back(i);+ }+ if (!sharpEdges.empty()) {+ // Hard-edge chains shorter than about a quad are sculpt detail, not features.+ std::unordered_map<uint32_t, uint32_t> id;+ std::vector<uint32_t> verts;+ for (uint32_t i : sharpEdges)+ for (uint32_t v : {edges[i].a, edges[i].b})+ if (id.emplace(v, uint32_t(verts.size())).second) verts.push_back(v);+ UF uf(verts.size());+ for (uint32_t i : sharpEdges) uf.unite(id[edges[i].a], id[edges[i].b]);+ std::vector<double> len(verts.size(), 0.0);+ for (uint32_t i : sharpEdges) len[uf.find(id[edges[i].a])] += double(glm::length(piece.P[edges[i].a] - piece.P[edges[i].b]));+ for (uint32_t i : sharpEdges) {+ if (len[uf.find(id[edges[i].a])] < 1.5 * double(h0)) continue;+ sharp.insert(edgeKey(edges[i].a, edges[i].b));+ segA.push_back(piece.P[edges[i].a]), segB.push_back(piece.P[edges[i].b]);+ }+ }+ }+ SegmentBVH features;+ if (!segA.empty()) features.build(segA, segB);+ mark("features");+ if (!step(0.08f)) return false;++ // 1. Proxy.+ ProxySource ps;+ ps.mesh = &piece;+ ps.surface = &surface;+ ps.features = features.empty() ? nullptr : &features;+ ps.sharp = std::move(sharp);+ ps.keepGroups = opt.keepGroups;+ ProxyBuilder pb(ps);+ // About three proxy edges per quad edge, at most ~400k proxy triangles.+ const float minEdge = float(std::sqrt(area / (0.433 * 400000.0)));+ const float L0 = std::max(h0 / 3.0f, minEdge);+ pb.decimate(L0);+ mark("decimate");+ if (!step(0.25f)) return false;+ pb.remesh(L0, {}, 2);+ mark("remesh");+ std::vector<uint32_t> vmap;+ Proxy proxy = pb.result(&vmap);+ Frames frames;+ frames.build(proxy);+ proxy.size.assign(proxy.P.size(), h0);+ Curvature curv = computeCurvature(proxy, frames, curvRadius);+ mark("curvature");+ if (!step(0.35f)) return false;++ // Sizes: Adaptive Size (curvature) and polypaint, relative; then normalised to the target.+ const bool adaptive = opt.adaptive > 0.01f || !piece.color.empty();+ std::vector<float> rel(proxy.P.size(), 1.0f);+ auto vertexAverage = [&](const std::vector<float>& perTri) {+ std::vector<float> s(proxy.P.size(), 0.0f), w(proxy.P.size(), 0.0f);+ for (uint32_t t = 0; t < proxy.T.size(); ++t)+ for (int k = 0; k < 3; ++k) s[proxy.T[t][k]] += perTri[t] * frames.area[t], w[proxy.T[t][k]] += frames.area[t];+ for (size_t v = 0; v < s.size(); ++v) s[v] = w[v] > 0.0f ? s[v] / w[v] : 0.0f;+ return s;+ };+ auto computeRel = [&]() {+ rel.assign(proxy.P.size(), 1.0f);+ if (opt.adaptive > 0.01f) {+ const std::vector<float> k = vertexAverage(curv.magnitude);+ std::vector<float> sorted(k);+ std::nth_element(sorted.begin(), sorted.begin() + long(sorted.size() / 2), sorted.end());+ const float ref = std::max(sorted[sorted.size() / 2], 0.2f / h0); // flat models stay even+ for (size_t v = 0; v < rel.size(); ++v)+ rel[v] = std::clamp(std::pow(std::max(k[v], 1e-9f) / ref, -0.6f * opt.adaptive), 0.45f, 2.2f);+ }+ if (!piece.color.empty()) {+ proxy.color.assign(proxy.P.size(), vec3(1.0f));+ for (size_t v = 0; v < proxy.P.size(); ++v) {+ SurfaceHit hit;+ if (!surface.closestPoint(proxy.P[v], 2.0f * h0, hit)) continue;+ const glm::uvec3 t = piece.T[hit.prim];+ const vec3 c = hit.bary.x * piece.color[t.x] + hit.bary.y * piece.color[t.y] + hit.bary.z * piece.color[t.z];+ proxy.color[v] = c;+ 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[v] *= std::pow(2.0f, blue - red);+ }+ }+ // Smooth the log size so it changes gradually.+ VertexFaces vf;+ vf.build(proxy.P.size(), proxy.T);+ for (int it = 0; it < 10; ++it) {+ std::vector<float> lr(rel.size());+ for (size_t v = 0; v < rel.size(); ++v) {+ double s = 0.0;+ int c = 0;+ for (uint32_t k = vf.off[v]; k < vf.off[v + 1]; ++k)+ for (int j = 0; j < 3; ++j) s += std::log(double(rel[proxy.T[vf.tri[k]][j]])), ++c;+ lr[v] = c ? float(std::exp(s / double(c))) : rel[v];+ }+ rel.swap(lr);+ }+ };+ if (adaptive) {+ computeRel();+ // Refine the proxy where quads will be small.+ std::vector<float> relB(pb.vertexCount(), 1.0f);+ for (size_t v = 0; v < vmap.size(); ++v) relB[vmap[v]] = std::max(rel[v], minEdge / L0);+ pb.remesh(L0, relB, 2);+ vmap.clear();+ proxy = pb.result(&vmap);+ frames.build(proxy);+ proxy.size.assign(proxy.P.size(), h0);+ curv = computeCurvature(proxy, frames, curvRadius);+ computeRel();+ mark("adaptive proxy");+ }+ out.proxyTriangles = proxy.T.size();+ auto setSizes = [&](double scale) {+ double sum = 0.0;+ std::vector<float> va(proxy.P.size(), 0.0f);+ for (uint32_t t = 0; t < proxy.T.size(); ++t)+ for (int k = 0; k < 3; ++k) va[proxy.T[t][k]] += frames.area[t] / 3.0f;+ for (size_t v = 0; v < va.size(); ++v) sum += double(va[v]) / double(rel[v] * rel[v]);+ const double c = std::sqrt(sum / wantQuads) * scale;+ for (size_t v = 0; v < proxy.size.size(); ++v) proxy.size[v] = float(c * double(rel[v]));+ };+ setSizes(1.0);+ if (!step(0.45f)) return false;++ // 2. Guides as feature chains.+ FieldSettings fs;+ fs.alignWeight = tune("SF_QR2_ALIGN", 1.0f);+ applyGuides(proxy, guides, opt.guideStrength, h0, fs, frames);+ if (!guides.empty()) {+ frames.build(proxy);+ mark("guides");+ }++ // 3. Cross field.+ // Solved on a copy of the proxy smoothed at the quad scale: the field's holonomy (where it must turn, hence the+ // singularities) then comes from the form, not from bumps smaller than a quad. Angles are relative to each+ // triangle's first edge, so they carry over to the real proxy unchanged.+ CrossField field;+ Proxy smooth = proxy;+ Frames sframes;+ {+ const float edgeLen = L0;+ const int rounds = std::clamp(int(tune("SF_QR2_SMOOTH", 1.5f) * (h0 / edgeLen) * (h0 / edgeLen)), 0, 200);+ VertexFaces vf;+ vf.build(smooth.P.size(), smooth.T);+ std::vector<uint8_t> pinned(smooth.P.size(), 0);+ for (uint32_t c = 0; c < smooth.feature.size(); ++c)+ if (smooth.feature[c]) pinned[smooth.T[c / 3][c % 3]] = pinned[smooth.T[c / 3][(c % 3 + 1) % 3]] = 1;+ std::vector<vec3> next(smooth.P.size());+ for (int r = 0; r < rounds; ++r) {+ parallelFor(smooth.P.size(), [&](size_t b, size_t e) {+ for (size_t v = b; v < e; ++v) {+ if (pinned[v]) {+ next[v] = smooth.P[v];+ continue;+ }+ vec3 s(0.0f);+ int n = 0;+ for (uint32_t k = vf.off[v]; k < vf.off[v + 1]; ++k)+ for (int j = 0; j < 3; ++j) s += smooth.P[smooth.T[vf.tri[k]][j]], ++n;+ next[v] = n ? 0.5f * smooth.P[v] + 0.5f * s / float(n) : smooth.P[v];+ }+ }, 4000);+ smooth.P.swap(next);+ }+ sframes.build(smooth);+ const Curvature scurv = computeCurvature(smooth, sframes, tune("SF_QR2_SCURV", 0.5f) * curvRadius);+ if (!solveCrossField(smooth, sframes, scurv, fs, field, isCancelled)) return false;+ }+ out.singularities = field.singularities;+ mark("cross field");+ if (timing) std::fprintf(stderr, " v2 proxy %zu triangles, %zu singularities\n", proxy.T.size(), field.singularities);+ if (std::getenv("SF_QR2_FIELD_ONLY")) {+ out.why = "field only";+ return false;+ }+ if (!step(0.55f)) return false;++ // 4 + 5. Map and extraction; the count is corrected once when it is far off.+ TriangleBVH proxyBvh;+ proxyBvh.build(proxy.P, proxy.T);+ std::vector<vec3> fa, fb;+ for (uint32_t t = 0; t < proxy.T.size(); ++t)+ for (int k = 0; k < 3; ++k)+ if (proxy.feature[3 * t + uint32_t(k)]) fa.push_back(proxy.P[proxy.T[t][k]]), fb.push_back(proxy.P[proxy.T[t][(k + 1) % 3]]);+ SegmentBVH proxyFeatures;+ if (!fa.empty()) proxyFeatures.build(fa, fb);++ std::vector<glm::uvec4> quads;+ std::vector<vec3> qp;+ const CrossField fieldStart = field;+ double scale = 1.0;+ for (int attempt = 0; attempt < 2; ++attempt) {+ field = fieldStart;+ GridMap map;+ smooth.size = proxy.size;+ if (!solveGridMap(smooth, sframes, field, map, isCancelled)) {+ if (cancelled) return false;+ out.why = "map";+ return false;+ }+ out.flippedTriangles = map.flipped;+ out.attempts = attempt + 1;+ mark("grid map");+ Poly poly = extractLattice(proxy, frames, map);+ if (timing) {+ std::map<size_t, size_t> sizes;+ for (const auto& f : poly.faces) ++sizes[f.size()];+ std::fprintf(stderr, " v2 extracted: flipped %zu, faces", map.flipped);+ for (auto [k, c] : sizes) std::fprintf(stderr, " %zu:%zu", k, c);+ std::fprintf(stderr, "\n");+ }+ quads = allQuads(poly);+ qp = std::move(poly.P);+ cleanQuads(qp, quads);+ mark("extract");+ const double ratio = double(quads.size()) / wantQuads;+ if (quads.empty() || attempt == 1 || std::abs(ratio - 1.0) < 0.08) break;+ scale *= std::sqrt(ratio);+ setSizes(scale);+ if (!step(0.7f)) return false;+ }+ if (quads.size() < 4) {+ out.why = "no quads";+ return false;+ }+ if (!step(0.85f)) return false;++ // 6. Loop-aware relaxation and projection.+ RelaxTargets rt;+ rt.surface = &surface;+ rt.features = proxyFeatures.empty() ? nullptr : &proxyFeatures;+ rt.proxy = &proxy;+ rt.curvature = &curv;+ rt.proxyBvh = &proxyBvh;+ rt.h = h0;+ std::vector<uint8_t> feat;+ relaxLoops(qp, quads, rt, std::max(opt.smoothIterations, 0), feat);+ mark("relax");++ out.mesh.P = std::move(qp);+ out.mesh.quads = std::move(quads);+ out.mesh.feature = feat;+ out.seam.assign(out.mesh.P.size(), 0);+ if (axis >= 0) {+ std::unordered_map<uint64_t, int> use;+ for (const auto& q : out.mesh.quads)+ for (int k = 0; k < 4; ++k) ++use[edgeKey(q[k], q[(k + 1) % 4])];+ for (auto [key, n] : use) {+ if (n != 1) continue;+ const uint32_t a = uint32_t(key >> 32), b = uint32_t(key & 0xffffffffu);+ if (std::abs(out.mesh.P[a][axis]) < 0.05f * h0 && std::abs(out.mesh.P[b][axis]) < 0.05f * h0)+ out.seam[a] = out.seam[b] = 1;+ }+ }+ (void)diag;+ return step(0.95f);+}++} // namespace sf::qrdiff --git a/src/core/QRemesh2.h b/src/core/QRemesh2.hnew file mode 100644index 00000000..573d2998--- /dev/null+++ b/src/core/QRemesh2.h@@ -0,0 +1,123 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// QRemesh 2 internals (core/QRemesh2.cpp has the outline): the proxy surface (QRemesh2Proxy.cpp), the cross field+// (QRemesh2Field.cpp) and the integer-grid map (QRemesh2Param.cpp). Not a public header.+#pragma once++#include "core/QRemeshInternal.h"+#include "core/SurfaceQuery.h"++#include <glm/glm.hpp>++#include <complex>+#include <cstdint>+#include <functional>+#include <memory>+#include <unordered_set>+#include <vector>++namespace sf::qr2 {++using glm::vec2;+using glm::vec3;+constexpr uint32_t kNone = ~0u;++inline uint64_t edgeKey(uint32_t a, uint32_t b) { return a < b ? (uint64_t(a) << 32) | b : (uint64_t(b) << 32) | a; }+inline 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;+}++// --- Proxy surface ----------------------------------------------------------------------------------------------++// The triangle mesh the field and the map are solved on: about three triangle edges per quad edge, even triangles,+// feature lines (open edges, polygroup borders, hard edges) kept as edge chains on their exact place.+struct Proxy {+ std::vector<vec3> P;+ std::vector<glm::uvec3> T;+ std::vector<uint32_t> group; // per triangle+ std::vector<uint32_t> opp; // per corner 3t+k (the edge T[k] -> T[k+1]): the twin corner, kNone when open+ std::vector<uint8_t> feature; // per corner: the edge is a feature line (open edges included)+ std::vector<float> size; // per vertex: wanted quad edge length+ std::vector<vec3> color; // per vertex polypaint (usePolypaint only)++ size_t triangles() const { return T.size(); }+ void buildOpposites(); // opp from T (edges with other than two consistently wound triangles stay open)+};++struct ProxySource {+ const qr::WorkMesh* mesh = nullptr;+ const TriangleBVH* surface = nullptr; // the source piece+ const SegmentBVH* features = nullptr; // the source's feature lines (to keep feature vertices on them)+ std::unordered_set<uint64_t> sharp; // hard-edge source edges (vertex pairs) that must stay+ bool keepGroups = false;+};++class ProxyBuilder {+public:+ explicit ProxyBuilder(const ProxySource& source);+ ~ProxyBuilder();+ // Edge collapses down to edges of about `edge` (the dense sculpt to the proxy's density).+ void decimate(float edge);+ // Isotropic remeshing passes (split, collapse, flip, smooth onto the source) towards `edge` times each+ // vertex's relative size (relSize: per current vertex, empty = 1).+ void remesh(float edge, const std::vector<float>& relSize, int iterations);+ // The current mesh, compacted. vertexMap (optional): proxy vertex -> builder vertex.+ Proxy result(std::vector<uint32_t>* vertexMap = nullptr) const;+ size_t vertexCount() const; // builder vertex slots (relSize's length)++private:+ struct Impl;+ std::unique_ptr<Impl> impl_;+};++// --- Curvature and cross field -------------------------------------------------------------------------------------++// Per triangle: an orthonormal frame (e1 along the first edge, e2 = n x e1) the field angles are measured in.+struct Frames {+ std::vector<vec3> e1, e2, n;+ std::vector<float> area;+ void build(const Proxy& p);+};++// Per triangle curvature tensor (Cohen-Steiner & Morvan, from dihedral angles), smoothed over `radius`: the+// direction of strongest bending (angle in the frame) and the anisotropy |k1 - k2| (1 / length).+struct Curvature {+ std::vector<float> angle, anisotropy, magnitude;+};+Curvature computeCurvature(const Proxy& p, const Frames& f, float radius);++struct FieldSettings {+ float alignWeight = 1.0f; // how strongly the field follows the curvature directions+ std::vector<float> guideAngle; // per triangle: a guide's direction to follow softly (NaN: none)+ std::vector<float> guideWeight;+};++struct CrossField {+ std::vector<float> theta; // per triangle, combed: the u direction's angle in the triangle's frame+ std::vector<int8_t> match; // per corner: quarter turns from this triangle's cross to the twin's (combed)+ std::vector<int8_t> vertexIndex; // per vertex: singularity index in quarter turns (0 regular, +1 = valence 3)+ size_t singularities = 0;+};++// Smooth 4-RoSy field: feature edges fixed, curvature directions followed with `alignWeight`. Solved as one sparse+// complex linear system (u = e^{4 i theta}), then normalised; deterministic.+bool solveCrossField(const Proxy& p, const Frames& f, const Curvature& c, const FieldSettings& s, CrossField& out,+ const std::function<bool()>& cancelled);+// Matching across each edge and the singularity index of each vertex for the current angles (no combing).+void computeMatching(const Proxy& p, const Frames& f, CrossField& field);++// --- Integer-grid map ------------------------------------------------------------------------------------------------++struct GridMap {+ std::vector<vec2> uv; // per corner 3t+k: the map at that corner, in the triangle's chart+ size_t flipped = 0; // triangles whose image is turned over+ size_t cutEdges = 0, integerVars = 0;+};++// Seamless map with the u / v gradients following the field at 1 / size, singularities and feature lines on the+// integer lattice (greedy rounding), so the lattice is a quad mesh. Combs `field` (match is 0 off the cut).+bool solveGridMap(const Proxy& p, const Frames& f, CrossField& field, GridMap& out, const std::function<bool()>& cancelled);++} // namespace sf::qr2diff --git a/src/core/QRemesh2Field.cpp b/src/core/QRemesh2Field.cppnew file mode 100644index 00000000..2eaf87a8--- /dev/null+++ b/src/core/QRemesh2Field.cpp@@ -0,0 +1,333 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// QRemesh 2: curvature and the cross field on the proxy surface.+//+// Curvature: the per-edge dihedral angle tensor of Cohen-Steiner & Morvan ("Restricted Delaunay triangulations and+// normal cycle", 2003), summed per triangle and smoothed over about one quad, so a dense sculpt's pores and+// scratches don't steer the edge flow but its brow, lips and limbs do.+//+// Cross field: a 4-RoSy field per triangle as u = e^{4 i theta} (Ray, Vallet, Li & Levy, "N-symmetry direction+// field design", 2008; Knoppel, Crane, Pinkall & Schroder, "Globally optimal direction fields", 2013): the+// connection Laplacian (smoothness) plus a pull towards the principal curvature directions weighted by how+// anisotropic the bending is, with feature edges (open edges, borders, hard edges, guides) as fixed directions.+// One sparse Hermitian system, solved by preconditioned conjugate gradients with deterministic reductions.+#include "core/QRemesh2.h"++#include "core/QRemesh2Solver.h"+#include "core/ThreadPool.h"++#include <cstdio>+#include <cstdlib>++#include <algorithm>+#include <cmath>+#include <numbers>++namespace sf::qr2 {++namespace {++constexpr double kPi = std::numbers::pi;+using cd = std::complex<double>;++float angleIn(const Frames& f, uint32_t t, const vec3& v) { return std::atan2(glm::dot(v, f.e2[t]), glm::dot(v, f.e1[t])); }++double wrapHalfPi(double a) { // to (-pi/4, pi/4]+ const double q = kPi / 2.0;+ return a - q * std::round(a / q);+}++// Deterministic block reductions.+template <class F>+double blockSum(size_t n, F&& term) {+ const size_t block = 8192, blocks = (n + block - 1) / block;+ std::vector<double> part(blocks, 0.0);+ poolFor(n, [&](size_t b, size_t e) {+ double s = 0.0;+ for (size_t i = b; i < e; ++i) s += term(i);+ part[b / block] = s;+ }, block);+ double s = 0.0;+ for (double p : part) s += p;+ return s;+}++} // namespace++void Frames::build(const Proxy& p) {+ const size_t nt = p.T.size();+ e1.resize(nt), e2.resize(nt), n.resize(nt), area.resize(nt);+ for (size_t t = 0; t < nt; ++t) {+ const glm::uvec3 tri = p.T[t];+ const vec3 a = p.P[tri.y] - p.P[tri.x], b = p.P[tri.z] - p.P[tri.x];+ const vec3 c = glm::cross(a, b);+ area[t] = 0.5f * glm::length(c);+ n[t] = safeNormalize(c);+ e1[t] = safeNormalize(a - n[t] * glm::dot(n[t], a), vec3(1, 0, 0));+ e2[t] = glm::cross(n[t], e1[t]);+ }+}++Curvature computeCurvature(const Proxy& p, const Frames& f, float radius) {+ const size_t nt = p.T.size();+ // Per triangle 3x3 symmetric tensor (xx, xy, xz, yy, yz, zz), area-weighted sums.+ std::vector<std::array<float, 6>> tensor(nt, std::array<float, 6>{});+ double edgeSum = 0.0;+ size_t edgeCount = 0;+ for (uint32_t t = 0; t < nt; ++t)+ for (int k = 0; k < 3; ++k) {+ const uint32_t c = 3 * t + uint32_t(k), o = p.opp[c];+ const vec3 e = p.P[p.T[t][(k + 1) % 3]] - p.P[p.T[t][k]];+ const float len = glm::length(e);+ edgeSum += len, ++edgeCount;+ if (o == kNone || o < c) continue;+ const uint32_t g = o / 3;+ const vec3 ed = e / std::max(len, 1e-30f);+ // Signed dihedral angle: positive where the surface bends away from its normal (convex).+ const float beta = std::atan2(glm::dot(glm::cross(f.n[t], f.n[g]), ed), glm::dot(f.n[t], f.n[g]));+ const float w = 0.5f * beta * len;+ const std::array<float, 6> m{w * ed.x * ed.x, w * ed.x * ed.y, w * ed.x * ed.z,+ w * ed.y * ed.y, w * ed.y * ed.z, w * ed.z * ed.z};+ for (int i = 0; i < 6; ++i) tensor[t][i] += m[i], tensor[g][i] += m[i];+ }+ const float meanEdge = edgeCount ? float(edgeSum / double(edgeCount)) : 1.0f;+ // Smoothing: area-weighted averages over edge neighbours; diffusion reaches about meanEdge * sqrt(rounds).+ const int rounds = std::clamp(int(std::lround(double(radius / meanEdge) * double(radius / meanEdge))), 1, 60);+ std::vector<float> area(f.area);+ std::vector<std::array<float, 6>> next(nt);+ // tensor holds sums (curvature x area); smooth the sums and the areas together.+ for (int r = 0; r < rounds; ++r) {+ std::vector<float> nextArea(nt);+ poolFor(nt, [&](size_t b, size_t e) {+ for (size_t t = b; t < e; ++t) {+ std::array<float, 6> s = tensor[t];+ float a = area[t];+ for (int k = 0; k < 3; ++k) {+ const uint32_t o = p.opp[3 * t + size_t(k)];+ if (o == kNone || p.feature[3 * t + size_t(k)]) continue; // don't blur across feature lines+ const uint32_t g = o / 3;+ for (int i = 0; i < 6; ++i) s[i] += tensor[g][i];+ a += area[g];+ }+ const float w = 1.0f / float(1 + 3);+ for (int i = 0; i < 6; ++i) next[t][i] = s[i] * w;+ nextArea[t] = a * w;+ }+ });+ tensor.swap(next);+ area.swap(nextArea);+ }+ Curvature c;+ c.angle.resize(nt), c.anisotropy.resize(nt), c.magnitude.resize(nt);+ for (size_t t = 0; t < nt; ++t) {+ const auto& m = tensor[t];+ const float inv = 1.0f / std::max(area[t], 1e-30f);+ auto apply = [&](const vec3& v) {+ return vec3(m[0] * v.x + m[1] * v.y + m[2] * v.z, m[1] * v.x + m[3] * v.y + m[4] * v.z,+ m[2] * v.x + m[4] * v.y + m[5] * v.z) * inv;+ };+ const vec3 a1 = apply(f.e1[t]), a2 = apply(f.e2[t]);+ const float xx = glm::dot(f.e1[t], a1), xy = glm::dot(f.e2[t], a1), yy = glm::dot(f.e2[t], a2);+ c.angle[t] = 0.5f * std::atan2(2.0f * xy, xx - yy);+ c.anisotropy[t] = std::sqrt((xx - yy) * (xx - yy) + 4.0f * xy * xy);+ c.magnitude[t] = 0.5f * std::abs(xx + yy) + 0.5f * c.anisotropy[t];+ }+ return c;+}++bool solveCrossField(const Proxy& p, const Frames& f, const Curvature& curv, const FieldSettings& s, CrossField& out,+ const std::function<bool()>& cancelled) {+ const size_t nt = p.T.size();+ // Fixed triangles: those with a feature edge, along the longest one.+ std::vector<uint8_t> fixed(nt, 0);+ std::vector<cd> z(nt, cd(0.0, 0.0)), target(nt, cd(0.0, 0.0));+ std::vector<double> weight(nt, 0.0);+ for (uint32_t t = 0; t < nt; ++t) {+ float best = -1.0f;+ for (int k = 0; k < 3; ++k) {+ if (!p.feature[3 * t + uint32_t(k)]) continue;+ const vec3 e = p.P[p.T[t][(k + 1) % 3]] - p.P[p.T[t][k]];+ const float l = glm::length(e);+ if (l > best) {+ best = l;+ const double a = angleIn(f, t, e);+ z[t] = std::polar(1.0, 4.0 * a);+ }+ }+ if (best > 0.0f) {+ fixed[t] = 1;+ continue;+ }+ // Curvature: anisotropy times the quad size is the bend across one quad (radians); full weight from ~17 degrees.+ const glm::uvec3 tri = p.T[t];+ const double h = (double(p.size[tri.x]) + double(p.size[tri.y]) + double(p.size[tri.z])) / 3.0;+ const double bend = std::min(1.0, double(curv.anisotropy[t]) * h / 0.3);+ weight[t] = double(s.alignWeight) * bend * bend;+ target[t] = std::polar(1.0, 4.0 * double(curv.angle[t]));+ if (t < s.guideAngle.size() && !std::isnan(s.guideAngle[t]) && s.guideWeight[t] > 0.0f) {+ // A soft guide replaces the curvature pull near the curve.+ const double gw = double(s.guideWeight[t]);+ target[t] = (1.0 - std::min(gw, 1.0)) * target[t] * weight[t] + gw * 10.0 * std::polar(1.0, 4.0 * double(s.guideAngle[t]));+ weight[t] = std::abs(target[t]);+ target[t] = weight[t] > 0.0 ? target[t] / weight[t] : cd(1.0, 0.0);+ }+ }+ // Transport factors per corner: from the twin triangle's frame into this one's.+ std::vector<cd> transport(3 * nt, cd(0.0, 0.0));+ for (uint32_t t = 0; t < nt; ++t)+ for (int k = 0; k < 3; ++k) {+ const uint32_t c = 3 * t + uint32_t(k), o = p.opp[c];+ if (o == kNone) continue;+ const uint32_t g = o / 3;+ const vec3 e = p.P[p.T[t][(k + 1) % 3]] - p.P[p.T[t][k]];+ const double at = angleIn(f, t, e), ag = angleIn(f, g, e);+ transport[c] = std::polar(1.0, 4.0 * (at - ag));+ }+ // System: for free t, (deg + w) z_t - sum r z_g = w target (+ fixed neighbours).+ std::vector<double> diag(nt, 1.0);+ std::vector<cd> rhs(nt, cd(0.0, 0.0));+ for (uint32_t t = 0; t < nt; ++t) {+ if (fixed[t]) continue;+ double d = weight[t];+ cd b = weight[t] * target[t];+ for (int k = 0; k < 3; ++k) {+ const uint32_t c = 3 * t + uint32_t(k), o = p.opp[c];+ if (o == kNone) continue;+ d += 1.0;+ if (fixed[o / 3]) b += transport[c] * z[o / 3];+ }+ diag[t] = std::max(d, 1e-12);+ rhs[t] = b;+ }+ // The system over the free triangles, preconditioned by multigrid.+ std::vector<uint32_t> fid(nt, kNone), freeTris;+ for (uint32_t t = 0; t < nt; ++t)+ if (!fixed[t]) fid[t] = uint32_t(freeTris.size()), freeTris.push_back(t);+ const size_t nfree = freeTris.size();+ std::vector<cd> x(nfree), b(nfree);+ if (nfree > 0) {+ SparseMatrix<cd> A;+ std::vector<std::pair<uint64_t, cd>> trips;+ trips.reserve(nfree * 4);+ for (uint32_t i = 0; i < nfree; ++i) {+ const uint32_t t = freeTris[i];+ trips.push_back({(uint64_t(i) << 32) | i, cd(diag[t], 0.0)});+ for (int k = 0; k < 3; ++k) {+ const uint32_t c = 3 * t + uint32_t(k), o = p.opp[c];+ if (o == kNone || fixed[o / 3]) continue;+ trips.push_back({(uint64_t(i) << 32) | fid[o / 3], -transport[c]});+ }+ b[i] = rhs[t];+ x[i] = weight[t] > 0.0 ? target[t] : cd(0.0, 0.0);+ }+ // A tiny shift keeps a closed surface's system definite.+ double meanDiag = 0.0;+ for (uint32_t i = 0; i < nfree; ++i) meanDiag += diag[freeTris[i]];+ meanDiag /= double(nfree);+ for (uint32_t i = 0; i < nfree; ++i) trips.push_back({(uint64_t(i) << 32) | i, cd(1e-4 * meanDiag, 0.0)});+ A.build(nfree, trips);+ Multigrid<cd> mg;+ mg.build(A);+ bool stop = false;+ // Inverse power iteration (the smoothest field, Knoppel et al. 2013) with the alignment and the fixed+ // triangles as a steady pull: x <- A^-1 (sigma x / |x| + b). Where nothing pulls, the field is the smoothest+ // one rather than noise.+ int its = 0;+ if (x.empty()) x.assign(nfree, cd(0.0, 0.0));+ {+ double bn = 0.0;+ for (const cd& v : b) bn += std::norm(v);+ bn = std::sqrt(bn / double(nfree));+ // Start: the pull, or a constant phase where there is none.+ for (uint32_t i = 0; i < nfree; ++i)+ if (std::abs(x[i]) == 0.0) x[i] = cd(1.0, 0.0);+ const double sigma = std::max(bn, 1e-3 * meanDiag) * 1.0;+ std::vector<cd> rhsk(nfree);+ for (int round = 0; round < 6; ++round) {+ double xn = 0.0;+ for (const cd& v : x) xn += std::norm(v);+ xn = std::sqrt(xn / double(nfree)) + 1e-300;+ for (uint32_t i = 0; i < nfree; ++i) rhsk[i] = sigma * x[i] / xn + b[i];+ std::vector<cd> nx(x);+ its += pcg<cd>([&](const std::vector<cd>& in, std::vector<cd>& o) { A.mul(in, o); }, &mg, A.diag, rhsk, nx,+ 1e-5, 200, cancelled, stop);+ if (stop) return false;+ x.swap(nx);+ }+ }+ if (std::getenv("SF_QREMESH_TIMING"))+ std::fprintf(stderr, " cross field: %zu free triangles, %zu levels, %d iterations\n", nfree, mg.levels(), its);+ }+ out.theta.resize(nt);+ for (size_t t = 0; t < nt; ++t) {+ const cd v = fixed[t] ? z[t] : x[fid[t]];+ out.theta[t] = std::abs(v) > 1e-30 ? float(std::arg(v) / 4.0) : 0.0f;+ }+ // A few rounds of local smoothing of the normalised field (the linear solve shrinks |u| near singularities and+ // under-smooths there).+ for (int round = 0; round < 4; ++round) {+ std::vector<float> nextTheta(out.theta);+ poolFor(nt, [&](size_t b, size_t e) {+ for (size_t t = b; t < e; ++t) {+ if (fixed[t]) continue;+ cd s = std::polar(1.0, 4.0 * double(out.theta[t])) * (1.0 + weight[t]);+ s += weight[t] * target[t];+ for (int k = 0; k < 3; ++k) {+ const size_t c = 3 * t + size_t(k);+ const uint32_t o = p.opp[c];+ if (o == kNone) continue;+ s += transport[c] * std::polar(1.0, 4.0 * double(out.theta[o / 3]));+ }+ if (std::abs(s) > 1e-30) nextTheta[t] = float(std::arg(s) / 4.0);+ }+ });+ out.theta.swap(nextTheta);+ }+ computeMatching(p, f, out);+ return true;+}++void computeMatching(const Proxy& p, const Frames& f, CrossField& field) {+ const size_t nt = p.T.size(), nv = p.P.size();+ field.match.assign(3 * nt, 0);+ std::vector<float> eps(3 * nt, 0.0f); // field rotation across the edge, beyond the matching+ for (uint32_t t = 0; t < nt; ++t)+ for (int k = 0; k < 3; ++k) {+ const uint32_t c = 3 * t + uint32_t(k), o = p.opp[c];+ if (o == kNone) continue;+ const uint32_t g = o / 3;+ const vec3 e = p.P[p.T[t][(k + 1) % 3]] - p.P[p.T[t][k]];+ const double moved = double(field.theta[t]) - angleIn(f, t, e) + angleIn(f, g, e);+ const double d = double(field.theta[g]) - moved;+ const long q = std::lround(d / (kPi / 2.0));+ field.match[c] = int8_t(((q % 4) + 4) % 4);+ eps[c] = float(d - double(q) * kPi / 2.0);+ }+ // Singularity index: (sum of eps going round + angle defect) / (pi/2), interior vertices only.+ field.vertexIndex.assign(nv, 0);+ std::vector<double> angleSum(nv, 0.0), epsSum(nv, 0.0);+ std::vector<uint8_t> open(nv, 0);+ for (uint32_t t = 0; t < nt; ++t)+ for (int k = 0; k < 3; ++k) {+ const uint32_t v = p.T[t][k];+ const vec3 a = p.P[p.T[t][(k + 1) % 3]] - p.P[v], b = p.P[p.T[t][(k + 2) % 3]] - p.P[v];+ angleSum[v] += std::atan2(double(glm::length(glm::cross(a, b))), double(glm::dot(a, b)));+ // Going round v counter-clockwise, triangle t hands over to the twin across the edge (T[k+2] -> v).+ const uint32_t c = 3 * t + uint32_t((k + 2) % 3);+ if (p.opp[c] == kNone) open[v] = 1;+ else epsSum[v] += double(eps[c]);+ if (p.opp[3 * t + uint32_t(k)] == kNone) open[v] = 1;+ }+ field.singularities = 0;+ for (uint32_t v = 0; v < nv; ++v) {+ if (open[v]) continue;+ const double defect = 2.0 * kPi - angleSum[v];+ const long q = std::lround((epsSum[v] + defect) / (kPi / 2.0));+ field.vertexIndex[v] = int8_t(std::clamp<long>(q, -4, 4));+ if (q != 0) ++field.singularities;+ }+ (void)wrapHalfPi;+}++} // namespace sf::qr2diff --git a/src/core/QRemesh2Param.cpp b/src/core/QRemesh2Param.cppnew file mode 100644index 00000000..d51dea8f--- /dev/null+++ b/src/core/QRemesh2Param.cpp@@ -0,0 +1,668 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// QRemesh 2: the integer-grid map. A seamless parametrization whose gradients follow the cross field at the wanted+// quad size, with transitions across the cut that are grid symmetries (quarter turns plus integer shifts),+// singularities on lattice points and feature lines on lattice lines, so the integer lattice drawn on the surface is+// a quad mesh with poles only at the field's singularities. After Mixed-Integer Quadrangulation (Bommes, Zimmer &+// Kobbelt, SIGGRAPH 2009) and integer-grid maps (Bommes, Campen, Ebke, Alliez & Kobbelt, SIGGRAPH 2013); the+// constraint elimination and greedy rounding are our own small solver (no CoMISo).+//+// 1. Comb the field along a spanning tree of the triangles; the edges off the tree, pruned to the branches that+// reach singularities, open edges or handles, are the cut.+// 2. Unknowns (u, v) per vertex wedge (corners not separated by the cut); linear constraints: across each cut edge+// the two sides differ by the quarter turn and an integer shift, feature edges keep one coordinate on an+// integer, singularities sit on integers. Eliminated one by one (integer unknowns stay integer combinations).+// 3. Least squares for the gradients, solved by conjugate gradients; integer unknowns rounded nearest-first in+// batches, each followed by a warm-started re-solve.+#include "core/QRemesh2.h"++#include "core/QRemesh2Solver.h"+#include "core/ThreadPool.h"++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <numbers>+#include <numeric>+#include <queue>++namespace sf::qr2 {++namespace {++constexpr double kPi = std::numbers::pi;++struct Term {+ uint32_t var;+ double a;+};++// Linear constraints sum a_i x_i + c = 0, eliminated as they come: each picks one unknown (the pivot) and expresses it+// by the others; expressions only ever mention unknowns still free.+class Eliminator {+public:+ // kind: 0 = real, 1..3 = integer (1 eliminated first: seam shifts, 2: feature lines, 3: singularity positions).+ uint32_t add(uint8_t kind) {+ kind_.push_back(kind);+ elim_.push_back(0);+ expr_.emplace_back();+ cst_.push_back(0.0);+ users_.emplace_back();+ return uint32_t(kind_.size() - 1);+ }+ size_t size() const { return kind_.size(); }+ bool eliminated(uint32_t v) const { return elim_[v] != 0; }+ uint8_t kind(uint32_t v) const { return kind_[v]; }+ const std::vector<Term>& expr(uint32_t v) const { return expr_[v]; }+ double constant(uint32_t v) const { return cst_[v]; }+ size_t lostIntegers() const { return lost_; }++ void constrain(const std::vector<Term>& row, double c) {+ // Substitute.+ std::vector<Term> r;+ double k = c;+ for (const Term& t : row) {+ if (std::abs(t.a) < 1e-14) continue;+ if (elim_[t.var]) {+ for (const Term& u : expr_[t.var]) r.push_back({u.var, t.a * u.a});+ k += t.a * cst_[t.var];+ } else {+ r.push_back(t);+ }+ }+ std::sort(r.begin(), r.end(), [](const Term& x, const Term& y) { return x.var < y.var; });+ std::vector<Term> m;+ for (const Term& t : r) {+ if (!m.empty() && m.back().var == t.var) m.back().a += t.a;+ else m.push_back(t);+ }+ m.erase(std::remove_if(m.begin(), m.end(), [](const Term& t) { return std::abs(t.a) < 1e-9; }), m.end());+ if (m.empty()) return; // redundant (or inconsistent, which the least squares then can't satisfy)+ // Pivot: a real unknown with the largest coefficient; else an integer one with coefficient +-1, lowest kind.+ int best = -1;+ for (size_t i = 0; i < m.size(); ++i)+ if (kind_[m[i].var] == 0 && (best < 0 || std::abs(m[i].a) > std::abs(m[size_t(best)].a) + 1e-12)) best = int(i);+ if (best < 0)+ for (size_t i = 0; i < m.size(); ++i)+ if (std::abs(std::abs(m[i].a) - 1.0) < 1e-9 &&+ (best < 0 || kind_[m[i].var] < kind_[m[size_t(best)].var]))+ best = int(i);+ if (best < 0) {+ ++lost_;+ for (size_t i = 0; i < m.size(); ++i)+ if (best < 0 || std::abs(m[i].a) > std::abs(m[size_t(best)].a)) best = int(i);+ }+ const uint32_t p = m[size_t(best)].var;+ const double ap = m[size_t(best)].a;+ std::vector<Term> e;+ for (const Term& t : m)+ if (t.var != p) e.push_back({t.var, -t.a / ap});+ const double ec = -k / ap;+ // Replace p in every expression using it.+ for (uint32_t q : users_[p]) {+ if (!elim_[q]) continue;+ auto& ex = expr_[q];+ double ap2 = 0.0;+ for (const Term& t : ex)+ if (t.var == p) ap2 += t.a;+ if (ap2 == 0.0) continue;+ std::vector<Term> merged;+ merged.reserve(ex.size() + e.size());+ for (const Term& t : ex)+ if (t.var != p) merged.push_back(t);+ for (const Term& t : e) merged.push_back({t.var, ap2 * t.a});+ std::sort(merged.begin(), merged.end(), [](const Term& x, const Term& y) { return x.var < y.var; });+ ex.clear();+ for (const Term& t : merged) {+ if (!ex.empty() && ex.back().var == t.var) ex.back().a += t.a;+ else ex.push_back(t);+ }+ ex.erase(std::remove_if(ex.begin(), ex.end(), [](const Term& t) { return std::abs(t.a) < 1e-12; }), ex.end());+ cst_[q] += ap2 * ec;+ for (const Term& t : e) addUser(t.var, q);+ }+ users_[p].clear();+ users_[p].shrink_to_fit();+ elim_[p] = 1;+ expr_[p] = e;+ cst_[p] = ec;+ for (const Term& t : e) addUser(t.var, p);+ }++private:+ void addUser(uint32_t var, uint32_t q) {+ auto& u = users_[var];+ if (!u.empty() && u.back() == q) return;+ u.push_back(q);+ if (u.size() >= 32 && (u.size() & (u.size() - 1)) == 0) { // at powers of two: drop duplicates and stale ones+ std::sort(u.begin(), u.end());+ u.erase(std::unique(u.begin(), u.end()), u.end());+ u.erase(std::remove_if(u.begin(), u.end(), [&](uint32_t x) {+ if (!elim_[x]) return true;+ for (const Term& t : expr_[x])+ if (t.var == var) return false;+ return true;+ }), u.end());+ }+ }++ std::vector<uint8_t> kind_, elim_;+ std::vector<std::vector<Term>> expr_;+ std::vector<double> cst_;+ std::vector<std::vector<uint32_t>> users_;+ size_t lost_ = 0;+};++template <class F>+double blockSum(size_t n, F&& term) {+ const size_t block = 8192, blocks = (n + block - 1) / block;+ std::vector<double> part(blocks, 0.0);+ poolFor(n, [&](size_t b, size_t e) {+ double s = 0.0;+ for (size_t i = b; i < e; ++i) s += term(i);+ part[b / block] = s;+ }, block);+ double s = 0.0;+ for (double p : part) s += p;+ return s;+}++struct Csr {+ std::vector<uint32_t> off, col;+ std::vector<double> val;+ std::vector<double> diag;+ size_t n = 0;+};++struct ReducedOp {+ std::function<void(const std::vector<double>&, std::vector<double>&)> apply;+ const std::vector<double>* diag;+ size_t n;+};++// Conjugate gradients on the unknowns not fixed (Jacobi preconditioner); fixed entries of x stay. Returns iterations.+int conjugateGradients(const ReducedOp& A, const std::vector<double>& b, const std::vector<uint8_t>& fixed,+ std::vector<double>& x, double tol, int maxIt, const std::function<bool()>& cancelled, bool& stop,+ const Multigrid<double>* mg = nullptr) {+ const size_t n = A.n;+ const std::vector<double>& D = *A.diag;+ std::vector<double> r(n), z(n), d(n), q(n);+ auto precond = [&] {+ if (mg) {+ mg->apply(r, z);+ for (size_t i = 0; i < n; ++i)+ if (fixed[i]) z[i] = 0.0;+ } else {+ for (size_t i = 0; i < n; ++i) z[i] = fixed[i] ? 0.0 : r[i] / D[i];+ }+ };+ A.apply(x, q);+ for (size_t i = 0; i < n; ++i) r[i] = fixed[i] ? 0.0 : b[i] - q[i];+ precond();+ d = z;+ double rz = blockSum(n, [&](size_t i) { return r[i] * z[i]; });+ const double bn = std::sqrt(blockSum(n, [&](size_t i) { return fixed[i] ? 0.0 : b[i] * b[i]; })) + 1e-30;+ int it = 0;+ for (; it < maxIt; ++it) {+ const double rn = std::sqrt(blockSum(n, [&](size_t i) { return r[i] * r[i]; }));+ if (rn < tol * bn) break;+ if ((it & 31) == 0 && cancelled && cancelled()) {+ stop = true;+ return it;+ }+ A.apply(d, q);+ const double dq = blockSum(n, [&](size_t i) { return fixed[i] ? 0.0 : d[i] * q[i]; });+ if (!(dq > 1e-300)) break;+ const double alpha = rz / dq;+ poolFor(n, [&](size_t b0, size_t e0) {+ for (size_t i = b0; i < e0; ++i) {+ if (fixed[i]) continue;+ x[i] += alpha * d[i];+ r[i] -= alpha * q[i];+ }+ });+ precond();+ const double rzNew = blockSum(n, [&](size_t i) { return r[i] * z[i]; });+ const double beta = rzNew / rz;+ rz = rzNew;+ poolFor(n, [&](size_t b0, size_t e0) {+ for (size_t i = b0; i < e0; ++i) d[i] = fixed[i] ? 0.0 : z[i] + beta * d[i];+ });+ }+ return it;+}+} // namespace++bool solveGridMap(const Proxy& p, const Frames& f, CrossField& field, GridMap& out, const std::function<bool()>& cancelled) {+ static const bool timing = std::getenv("SF_QREMESH_TIMING") != nullptr;+ const size_t nt = p.T.size(), nv = p.P.size();+ const size_t nc = 3 * nt;+ if (nt == 0) return false;++ // 1. Comb along a breadth-first spanning tree of the triangles.+ std::vector<uint8_t> tree(nc, 0), seen(nt, 0);+ {+ std::vector<uint32_t> queue;+ queue.reserve(nt);+ for (uint32_t root = 0; root < nt; ++root) {+ if (seen[root]) continue;+ seen[root] = 1;+ queue.clear();+ queue.push_back(root);+ for (size_t qi = 0; qi < queue.size(); ++qi) {+ const uint32_t t = queue[qi];+ for (int k = 0; k < 3; ++k) {+ const uint32_t c = 3 * t + uint32_t(k), o = p.opp[c];+ if (o == kNone || seen[o / 3]) continue;+ const uint32_t g = o / 3;+ seen[g] = 1;+ // Turn g's cross so it matches t's across this edge.+ field.theta[g] -= float(field.match[c]) * float(kPi / 2.0);+ // match from t to g is now 0; refresh g's other corners lazily below.+ tree[c] = tree[o] = 1;+ // Update matchings of g's edges for the turn (q - m on corners of g, + m on their twins).+ const int m = field.match[c];+ for (int j = 0; j < 3; ++j) {+ const uint32_t cg = 3 * g + uint32_t(j), og = p.opp[cg];+ field.match[cg] = int8_t((field.match[cg] + m) % 4);+ if (og != kNone) field.match[og] = int8_t((field.match[og] + 4 - m) % 4);+ }+ queue.push_back(g);+ }+ }+ }+ }+ // Sanity: tree edges have match 0.+ // 2. Cut graph: interior edges off the tree, pruned.+ std::vector<uint8_t> cut(nc, 0), open(nv, 0);+ for (uint32_t c = 0; c < nc; ++c) {+ if (p.opp[c] == kNone) {+ open[p.T[c / 3][c % 3]] = open[p.T[c / 3][(c % 3 + 1) % 3]] = 1;+ continue;+ }+ if (!tree[c]) cut[c] = 1;+ }+ {+ std::vector<std::vector<uint32_t>> vedges(nv); // per vertex: cut edges as their lower corner+ for (uint32_t c = 0; c < nc; ++c) {+ if (!cut[c] || p.opp[c] < c) continue;+ vedges[p.T[c / 3][c % 3]].push_back(c);+ vedges[p.T[c / 3][(c % 3 + 1) % 3]].push_back(c);+ }+ std::vector<int> deg(nv, 0);+ for (uint32_t v = 0; v < nv; ++v) deg[v] = int(vedges[v].size());+ std::vector<uint32_t> stack;+ for (uint32_t v = 0; v < nv; ++v)+ if (deg[v] == 1 && !open[v] && field.vertexIndex[v] == 0) stack.push_back(v);+ while (!stack.empty()) {+ const uint32_t v = stack.back();+ stack.pop_back();+ if (deg[v] != 1) continue;+ uint32_t e = kNone;+ for (uint32_t c : vedges[v])+ if (cut[c]) e = c;+ if (e == kNone) continue;+ cut[e] = cut[p.opp[e]] = 0;+ const uint32_t a = p.T[e / 3][e % 3], b = p.T[e / 3][(e % 3 + 1) % 3];+ --deg[a], --deg[b];+ const uint32_t other = a == v ? b : a;+ if (deg[other] == 1 && !open[other] && field.vertexIndex[other] == 0) stack.push_back(other);+ }+ }+ size_t cutEdges = 0;+ for (uint32_t c = 0; c < nc; ++c) cutEdges += cut[c] && p.opp[c] > c;++ // 3. Wedges: corners of a vertex joined across edges that are neither open nor cut.+ std::vector<uint32_t> parent(nc);+ std::iota(parent.begin(), parent.end(), 0u);+ auto find = [&](uint32_t x) {+ while (parent[x] != x) x = parent[x] = parent[parent[x]];+ return x;+ };+ auto cornerOf = [&](uint32_t t, uint32_t v) -> uint32_t {+ for (int k = 0; k < 3; ++k)+ if (p.T[t][k] == v) return 3 * t + uint32_t(k);+ return kNone;+ };+ for (uint32_t c = 0; c < nc; ++c) {+ const uint32_t o = p.opp[c];+ if (o == kNone || cut[c] || o < c) continue;+ const uint32_t t = c / 3, g = o / 3;+ const uint32_t a = p.T[t][c % 3], b = p.T[t][(c % 3 + 1) % 3];+ for (uint32_t v : {a, b}) {+ const uint32_t x = find(cornerOf(t, v)), y = find(cornerOf(g, v));+ if (x != y) parent[std::max(x, y)] = std::min(x, y);+ }+ }+ std::vector<uint32_t> copyOf(nc), copyId(nc, kNone);+ uint32_t copies = 0;+ for (uint32_t c = 0; c < nc; ++c) {+ const uint32_t r = find(c);+ if (copyId[r] == kNone) copyId[r] = copies++;+ copyOf[c] = copyId[r];+ }++ Eliminator el;+ for (uint32_t i = 0; i < 2 * copies; ++i) el.add(0);+ auto U = [&](uint32_t corner) { return 2 * copyOf[corner]; };++ // Axis of each triangle's field: X = (cos theta, sin theta) in its frame.+ auto axisOfEdge = [&](uint32_t t, const vec3& e) { // 0: the edge runs along u (so v is constant), 1: along v+ const double th = double(field.theta[t]);+ const double x = double(glm::dot(e, f.e1[t])), y = double(glm::dot(e, f.e2[t]));+ const double du = std::abs(x * std::cos(th) + y * std::sin(th)), dv = std::abs(-x * std::sin(th) + y * std::cos(th));+ return du >= dv ? 0 : 1;+ };++ // Singularities on lattice points.+ size_t ints = 0;+ {+ std::vector<uint8_t> done(nv, 0);+ for (uint32_t c = 0; c < nc; ++c) {+ const uint32_t v = p.T[c / 3][c % 3];+ if (field.vertexIndex[v] == 0 || open[v] || done[v]) continue;+ done[v] = 1;+ const uint32_t iu = el.add(3), iv = el.add(3);+ ints += 2;+ el.constrain({{U(c), 1.0}, {iu, -1.0}}, 0.0);+ el.constrain({{U(c) + 1, 1.0}, {iv, -1.0}}, 0.0);+ }+ }+ // Feature lines on lattice lines.+ for (uint32_t c = 0; c < nc; ++c) {+ if (!p.feature[c]) continue;+ const uint32_t t = c / 3, k = c % 3;+ const vec3 e = p.P[p.T[t][(k + 1) % 3]] - p.P[p.T[t][k]];+ const int along = axisOfEdge(t, e);+ const uint32_t coord = along == 0 ? 1 : 0; // the coordinate that stays constant+ const uint32_t s = el.add(2);+ ++ints;+ el.constrain({{U(c) + coord, 1.0}, {s, -1.0}}, 0.0);+ el.constrain({{U(3 * t + (k + 1) % 3) + coord, 1.0}, {s, -1.0}}, 0.0);+ }+ // Seams: across each cut edge, (u, v) on the far side = R^m (u, v) + integer shift.+ for (uint32_t c = 0; c < nc; ++c) {+ if (!cut[c] || p.opp[c] < c) continue;+ const uint32_t o = p.opp[c], t = c / 3, g = o / 3, k = c % 3;+ const int m = field.match[c];+ const uint32_t tu = el.add(1), tv = el.add(1);+ ints += 2;+ for (uint32_t v : {p.T[t][k], p.T[t][(k + 1) % 3]}) {+ const uint32_t a = U(cornerOf(t, v)), b = U(cornerOf(g, v));+ // R^m: m=1: (u, v) -> (v, -u).+ double r[2][2];+ switch (m) {+ case 0: r[0][0] = 1, r[0][1] = 0, r[1][0] = 0, r[1][1] = 1; break;+ case 1: r[0][0] = 0, r[0][1] = 1, r[1][0] = -1, r[1][1] = 0; break;+ case 2: r[0][0] = -1, r[0][1] = 0, r[1][0] = 0, r[1][1] = -1; break;+ default: r[0][0] = 0, r[0][1] = -1, r[1][0] = 1, r[1][1] = 0; break;+ }+ el.constrain({{b, 1.0}, {a, -r[0][0]}, {a + 1, -r[0][1]}, {tu, -1.0}}, 0.0);+ el.constrain({{b + 1, 1.0}, {a, -r[1][0]}, {a + 1, -r[1][1]}, {tv, -1.0}}, 0.0);+ }+ }+ if (timing)+ std::fprintf(stderr, " grid map: %zu triangles, %u wedges, %zu cut edges, %zu integer unknowns (%zu lost)\n", nt,+ copies, cutEdges, ints, el.lostIntegers());++ if (timing) {+ size_t maxLen = 0, total = 0;+ for (uint32_t v = 0; v < el.size(); ++v)+ if (el.eliminated(v)) maxLen = std::max(maxLen, el.expr(v).size()), total += el.expr(v).size();+ std::fprintf(stderr, " grid map: expressions max %zu terms, %zu in all\n", maxLen, total);+ for (uint32_t v = 0; v < el.size(); ++v)+ if (el.eliminated(v) && el.expr(v).size() == maxLen) {+ int kinds[4] = {};+ for (const Term& t : el.expr(v)) ++kinds[el.kind(t.var)];+ std::fprintf(stderr, " var %u kind %d: terms real %d seam %d feature %d sing %d, first coefs %g %g %g\n", v,+ el.kind(v), kinds[0], kinds[1], kinds[2], kinds[3], el.expr(v)[0].a, el.expr(v)[1].a,+ el.expr(v)[2].a);+ break;+ }+ }+ // 4. Free unknowns. The reduced system C^T K C y = C^T (b - K d) (x = C y + d) is applied without forming it:+ // the cut tree makes C fill in (a transition is the composition of everything below it), C^T K C would not fit.+ const size_t nvar = el.size(), ncopy = 2 * size_t(copies);+ std::vector<uint32_t> freeId(nvar, kNone);+ std::vector<uint32_t> freeVars;+ for (uint32_t v = 0; v < nvar; ++v)+ if (!el.eliminated(v)) {+ freeId[v] = uint32_t(freeVars.size());+ freeVars.push_back(v);+ }+ const size_t nf = freeVars.size();+ auto expand = [&](uint32_t v, std::vector<Term>& terms, double& c) {+ terms.clear();+ if (!el.eliminated(v)) {+ terms.push_back({freeId[v], 1.0});+ c = 0.0;+ return;+ }+ for (const Term& t : el.expr(v)) terms.push_back({freeId[t.var], t.a});+ c = el.constant(v);+ };+ // K and b on the wedge unknowns: per triangle, the hat-function gradients against the target gradients.+ Csr K;+ K.n = ncopy;+ std::vector<double> bFull(ncopy, 0.0);+ {+ struct Trip {+ uint32_t r, c;+ double v;+ };+ std::vector<Trip> trips;+ trips.reserve(nt * 18);+ for (uint32_t t = 0; t < nt; ++t) {+ const glm::uvec3 tri = p.T[t];+ const vec3 o = p.P[tri.x];+ vec2 q[3];+ for (int k = 0; k < 3; ++k) {+ const vec3 d = p.P[tri[k]] - o;+ q[k] = {glm::dot(d, f.e1[t]), glm::dot(d, f.e2[t])};+ }+ const double A2 = double(q[1].x - q[0].x) * double(q[2].y - q[0].y) - double(q[2].x - q[0].x) * double(q[1].y - q[0].y);+ if (!(A2 > 1e-30)) continue;+ const double A = 0.5 * A2;+ double gx[3], gy[3];+ for (int k = 0; k < 3; ++k) {+ const vec2 e = q[(k + 2) % 3] - q[(k + 1) % 3];+ gx[k] = -double(e.y) / A2;+ gy[k] = double(e.x) / A2;+ }+ const double h = (double(p.size[tri.x]) + double(p.size[tri.y]) + double(p.size[tri.z])) / 3.0;+ const double th = double(field.theta[t]);+ const double gu[2] = {std::cos(th) / h, std::sin(th) / h}, gv[2] = {-std::sin(th) / h, std::cos(th) / h};+ for (int coord = 0; coord < 2; ++coord) {+ const double* g = coord == 0 ? gu : gv;+ for (int i = 0; i < 3; ++i) {+ const uint32_t vi = U(3 * t + uint32_t(i)) + uint32_t(coord);+ bFull[vi] += A * (gx[i] * g[0] + gy[i] * g[1]);+ for (int j = 0; j < 3; ++j) {+ const uint32_t vj = U(3 * t + uint32_t(j)) + uint32_t(coord);+ trips.push_back({vi, vj, A * (gx[i] * gx[j] + gy[i] * gy[j])});+ }+ }+ }+ }+ std::sort(trips.begin(), trips.end(), [](const Trip& x, const Trip& y) { return x.r < y.r || (x.r == y.r && x.c < y.c); });+ K.off.assign(ncopy + 1, 0);+ for (size_t i = 0; i < trips.size();) {+ size_t j = i;+ double v = 0.0;+ while (j < trips.size() && trips[j].r == trips[i].r && trips[j].c == trips[i].c) v += trips[j++].v;+ K.col.push_back(trips[i].c);+ K.val.push_back(v);+ ++K.off[trips[i].r + 1];+ i = j;+ }+ for (size_t i = 0; i < ncopy; ++i) K.off[i + 1] += K.off[i];+ K.diag.assign(ncopy, 0.0);+ for (size_t i = 0; i < ncopy; ++i)+ for (uint32_t k = K.off[i]; k < K.off[i + 1]; ++k)+ if (K.col[k] == i) K.diag[i] = K.val[k];+ }+ // C as rows (per wedge unknown) and columns (per free unknown).+ std::vector<uint32_t> cOff(ncopy + 1, 0), cCol;+ std::vector<double> cVal, dConst(ncopy, 0.0);+ {+ std::vector<Term> terms;+ for (uint32_t v = 0; v < ncopy; ++v) {+ double c;+ expand(v, terms, c);+ dConst[v] = c;+ for (const Term& t : terms) cCol.push_back(t.var), cVal.push_back(t.a);+ cOff[v + 1] = uint32_t(cCol.size());+ }+ }+ std::vector<uint32_t> tOff(nf + 1, 0), tRow(cCol.size());+ std::vector<double> tVal(cCol.size());+ for (uint32_t c : cCol) ++tOff[c + 1];+ for (size_t i = 0; i < nf; ++i) tOff[i + 1] += tOff[i];+ {+ std::vector<uint32_t> fill(tOff.begin(), tOff.end() - 1);+ for (uint32_t v = 0; v < ncopy; ++v)+ for (uint32_t k = cOff[v]; k < cOff[v + 1]; ++k) {+ const uint32_t at = fill[cCol[k]]++;+ tRow[at] = v;+ tVal[at] = cVal[k];+ }+ }+ if (timing) std::fprintf(stderr, " grid map: C has %zu terms\n", cCol.size());+ auto mulK = [&](const std::vector<double>& x, std::vector<double>& z) {+ poolFor(ncopy, [&](size_t b0, size_t e0) {+ for (size_t i = b0; i < e0; ++i) {+ double s = 0.0;+ for (uint32_t k = K.off[i]; k < K.off[i + 1]; ++k) s += K.val[k] * x[K.col[k]];+ z[i] = s;+ }+ });+ };+ std::vector<double> rhs(nf, 0.0), diag(nf, 0.0);+ {+ std::vector<double> kd(ncopy);+ mulK(dConst, kd);+ for (size_t j = 0; j < nf; ++j) {+ double s = 0.0, dg = 0.0;+ for (uint32_t k = tOff[j]; k < tOff[j + 1]; ++k) {+ s += tVal[k] * (bFull[tRow[k]] - kd[tRow[k]]);+ dg += tVal[k] * tVal[k] * K.diag[tRow[k]];+ }+ rhs[j] = s;+ diag[j] = dg;+ }+ }+ double meanDiag = 0.0;+ for (double d : diag) meanDiag += d;+ meanDiag = nf ? meanDiag / double(nf) : 1.0;+ const double reg = 1e-7 * meanDiag;+ for (double& d : diag) d = d > 0.0 ? d + reg : 1.0;+ std::vector<double> xs(ncopy), zs(ncopy);+ const ReducedOp op{[&](const std::vector<double>& yv, std::vector<double>& outv) {+ poolFor(ncopy, [&](size_t b0, size_t e0) {+ for (size_t v = b0; v < e0; ++v) {+ double s = 0.0;+ for (uint32_t k = cOff[v]; k < cOff[v + 1]; ++k) s += cVal[k] * yv[cCol[k]];+ xs[v] = s;+ }+ });+ mulK(xs, zs);+ poolFor(nf, [&](size_t b0, size_t e0) {+ for (size_t j = b0; j < e0; ++j) {+ double s = reg * yv[j];+ for (uint32_t k = tOff[j]; k < tOff[j + 1]; ++k) s += tVal[k] * zs[tRow[k]];+ outv[j] = s;+ }+ });+ }, &diag, nf};+ // Multigrid preconditioner on a sparse stand-in for C^T K C: each wedge unknown mapped to its main free real+ // unknown only (the integer fill-in dropped), integer unknowns on their own diagonal.+ Multigrid<double> mg;+ {+ std::vector<int64_t> mainOf(ncopy, -1);+ std::vector<double> mainCoef(ncopy, 0.0);+ for (uint32_t v = 0; v < ncopy; ++v) {+ double best = 0.0;+ for (uint32_t k = cOff[v]; k < cOff[v + 1]; ++k)+ if (el.kind(freeVars[cCol[k]]) == 0 && std::abs(cVal[k]) > best) best = std::abs(cVal[k]), mainOf[v] = cCol[k], mainCoef[v] = cVal[k];+ }+ std::vector<std::pair<uint64_t, double>> trips;+ trips.reserve(K.val.size() + nf);+ for (uint32_t i = 0; i < ncopy; ++i) {+ if (mainOf[i] < 0) continue;+ for (uint32_t k = K.off[i]; k < K.off[i + 1]; ++k) {+ const uint32_t j = K.col[k];+ if (mainOf[j] < 0) continue;+ trips.push_back({(uint64_t(mainOf[i]) << 32) | uint64_t(mainOf[j]), mainCoef[i] * K.val[k] * mainCoef[j]});+ }+ }+ for (size_t j = 0; j < nf; ++j) trips.push_back({(uint64_t(j) << 32) | j, el.kind(freeVars[j]) != 0 ? diag[j] : reg});+ SparseMatrix<double> As;+ As.build(nf, trips);+ mg.build(As);+ }++ // 5. Solve, round the integers nearest-first, re-solve.+ std::vector<double> y(nf, 0.0);+ std::vector<uint8_t> fixed(nf, 0);+ bool stop = false;+ int iters = conjugateGradients(op, rhs, fixed, y, 1e-6, 2000, cancelled, stop, &mg);+ if (stop) return false;+ std::vector<uint32_t> intFree;+ for (size_t i = 0; i < nf; ++i)+ if (el.kind(freeVars[i]) != 0) intFree.push_back(uint32_t(i));+ size_t rounds = 0;+ {+ std::vector<uint32_t> left = intFree;+ while (!left.empty()) {+ std::vector<std::pair<double, uint32_t>> dist;+ for (uint32_t i : left) dist.push_back({std::abs(y[i] - std::round(y[i])), i});+ std::sort(dist.begin(), dist.end());+ static const double frac = std::getenv("SF_QR2_ROUND") ? std::atof(std::getenv("SF_QR2_ROUND")) : 0.2;+ size_t take = std::max<size_t>(1, size_t(double(left.size()) * frac + 0.999));+ while (take < dist.size() && dist[take].first < 0.08) ++take;+ if (left.size() <= 8) take = left.size();+ for (size_t k = 0; k < take; ++k) {+ const uint32_t i = dist[k].second;+ y[i] = std::round(y[i]);+ fixed[i] = 1;+ }+ std::vector<uint32_t> rest;+ for (size_t k = take; k < dist.size(); ++k) rest.push_back(dist[k].second);+ left.swap(rest);+ static const double midTol = std::getenv("SF_QR2_TOL") ? std::atof(std::getenv("SF_QR2_TOL")) : 1e-5;+ iters += conjugateGradients(op, rhs, fixed, y, left.empty() ? 1e-6 : midTol, left.empty() ? 2000 : 500, cancelled, stop, &mg);+ if (stop) return false;+ ++rounds;+ }+ }+ if (timing)+ std::fprintf(stderr, " grid map: %zu free unknowns (%zu integer), %zu rounding rounds, %d CG iterations\n", nf,+ intFree.size(), rounds, iters);+ // 6. The map at each corner.+ out.uv.assign(nc, vec2(0.0f));+ std::vector<Term> terms;+ for (uint32_t c = 0; c < nc; ++c) {+ double val[2];+ for (int coord = 0; coord < 2; ++coord) {+ double k;+ expand(U(c) + uint32_t(coord), terms, k);+ double s = k;+ for (const Term& t : terms) s += t.a * y[t.var];+ val[coord] = s;+ }+ out.uv[c] = vec2(float(val[0]), float(val[1]));+ }+ out.flipped = 0;+ for (uint32_t t = 0; t < nt; ++t) {+ const vec2 a = out.uv[3 * t], b = out.uv[3 * t + 1], c = out.uv[3 * t + 2];+ const float area = (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y);+ if (!(area > 0.0f)) ++out.flipped;+ }+ out.cutEdges = cutEdges;+ out.integerVars = intFree.size();+ return true;+}++} // namespace sf::qr2diff --git a/src/core/QRemesh2Proxy.cpp b/src/core/QRemesh2Proxy.cppnew file mode 100644index 00000000..26c1ec14--- /dev/null+++ b/src/core/QRemesh2Proxy.cpp@@ -0,0 +1,573 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// QRemesh 2's proxy surface: the sculpt brought to about three triangle edges per quad edge, with even triangles,+// so the cross field and the integer-grid map have a well-shaped mesh to live on whatever the sculpt's density.+//+// 1. Decimation: rounds of shortest-edge-first collapses (each round touches a vertex's neighbourhood once, so the+// density stays even), collapsed vertices settling at the middle of the edge and back onto the sculpt.+// 2. Isotropic remeshing (after Botsch & Kobbelt, "A remeshing approach to multiresolution modeling", 2004):+// split long edges, collapse short ones, flip edges towards valence 6, smooth tangentially and project onto+// the sculpt, towards a per-vertex target length (smaller where Adaptive Size or polypaint want small quads).+//+// Feature lines (open edges, polygroup borders with Keep Groups, hard edges with Detect Edges) are kept: their+// vertices only collapse along the line, slide along it when smoothed and project onto the source's line; where+// lines meet or turn sharply the vertex is pinned.+#include "core/QRemesh2.h"++#include "core/Parallel.h"++#include <algorithm>+#include <cmath>+#include <unordered_map>++namespace sf::qr2 {++void Proxy::buildOpposites() {+ const size_t nt = T.size();+ opp.assign(3 * nt, kNone);+ std::unordered_map<uint64_t, uint32_t> first; // edge -> first corner seen (kNone once a third shows up)+ std::unordered_map<uint64_t, int> count;+ first.reserve(3 * nt / 2 + 16);+ count.reserve(3 * nt / 2 + 16);+ for (uint32_t t = 0; t < nt; ++t)+ for (int k = 0; k < 3; ++k) {+ const uint64_t key = edgeKey(T[t][k], T[t][(k + 1) % 3]);+ if (++count[key] == 1) first[key] = 3 * t + uint32_t(k);+ }+ for (uint32_t t = 0; t < nt; ++t)+ for (int k = 0; k < 3; ++k) {+ const uint32_t a = T[t][k], b = T[t][(k + 1) % 3];+ const uint64_t key = edgeKey(a, b);+ if (count[key] != 2) continue;+ const uint32_t c = first[key];+ if (c == 3 * t + uint32_t(k)) continue;+ const uint32_t ot = c / 3, ok = c % 3;+ // Consistently wound neighbours run the edge the other way.+ if (T[ot][ok] != b || T[ot][(ok + 1) % 3] != a) continue;+ opp[3 * t + uint32_t(k)] = c;+ opp[c] = 3 * t + uint32_t(k);+ }+}++struct ProxyBuilder::Impl {+ const qr::WorkMesh& src;+ const TriangleBVH* surface;+ const SegmentBVH* features;+ std::unordered_set<uint64_t> sharp;+ bool groups;++ std::vector<vec3> P;+ std::vector<glm::uvec3> T;+ std::vector<uint32_t> G;+ std::vector<uint8_t> deadT, deadV;+ std::vector<std::vector<uint32_t>> VT;+ std::vector<float> Lt; // per vertex target length (remesh)+ float reach = 1.0f;++ explicit Impl(const ProxySource& s)+ : src(*s.mesh), surface(s.surface), features(s.features), sharp(s.sharp), groups(s.keepGroups) {+ P = src.P;+ T = src.T;+ G = src.group;+ if (G.size() != T.size()) G.assign(T.size(), 0);+ deadT.assign(T.size(), 0);+ deadV.assign(P.size(), 0);+ VT.resize(P.size());+ std::vector<uint32_t> deg(P.size(), 0);+ for (const auto& t : T)+ for (int k = 0; k < 3; ++k) ++deg[t[k]];+ for (size_t v = 0; v < P.size(); ++v) VT[v].reserve(deg[v]);+ for (uint32_t t = 0; t < T.size(); ++t) {+ const auto& tri = T[t];+ if (tri.x == tri.y || tri.y == tri.z || tri.x == tri.z) {+ deadT[t] = 1;+ continue;+ }+ for (int k = 0; k < 3; ++k) VT[tri[k]].push_back(t);+ }+ for (size_t v = 0; v < P.size(); ++v)+ if (VT[v].empty()) deadV[v] = 1;+ Lt.assign(P.size(), 1.0f);+ }++ static bool has(const glm::uvec3& t, uint32_t v) { return t.x == v || t.y == v || t.z == v; }++ int edgeTris(uint32_t a, uint32_t b, uint32_t* out, int max) const {+ int n = 0;+ for (uint32_t t : VT[a])+ if (has(T[t], b)) {+ if (n < max) out[n] = t;+ ++n;+ }+ return n;+ }++ // a -> b runs forwards in t.+ static bool forwards(const glm::uvec3& t, uint32_t a, uint32_t b) {+ return (t.x == a && t.y == b) || (t.y == a && t.z == b) || (t.z == a && t.x == b);+ }++ bool featureEdge(uint32_t a, uint32_t b) const {+ uint32_t t[4];+ const int n = edgeTris(a, b, t, 4);+ if (n != 2) return true;+ if (forwards(T[t[0]], a, b) == forwards(T[t[1]], a, b)) return true; // wound inconsistently+ if (groups && G[t[0]] != G[t[1]]) return true;+ return !sharp.empty() && sharp.count(edgeKey(a, b)) > 0;+ }++ void ring(uint32_t v, std::vector<uint32_t>& out) const {+ out.clear();+ for (uint32_t t : VT[v])+ for (int k = 0; k < 3; ++k)+ if (T[t][k] != v) out.push_back(T[t][k]);+ std::sort(out.begin(), out.end());+ out.erase(std::unique(out.begin(), out.end()), out.end());+ }++ // Feature edges at v: how many, and the first two other ends.+ int featureInfo(uint32_t v, uint32_t* ends, std::vector<uint32_t>& scratch) const {+ ring(v, scratch);+ int n = 0;+ for (uint32_t u : scratch)+ if (featureEdge(v, u)) {+ if (n < 2) ends[n] = u;+ ++n;+ }+ return n;+ }++ // 0 free, 1 on a feature line, 2 pinned (lines meet, end, or turn by more than 45 degrees).+ int kind(uint32_t v, uint32_t* ends, std::vector<uint32_t>& scratch) const {+ const int n = featureInfo(v, ends, scratch);+ if (n == 0) return 0;+ if (n != 2) return 2;+ const vec3 a = safeNormalize(P[ends[0]] - P[v]), b = safeNormalize(P[ends[1]] - P[v]);+ return glm::dot(a, b) > -0.7f ? 2 : 1;+ }++ vec3 triNormal(const glm::uvec3& t) const { return glm::cross(P[t.y] - P[t.x], P[t.z] - P[t.x]); }++ vec3 projectSurface(const vec3& p) const {+ SurfaceHit hit;+ return surface && surface->closestPoint(p, reach, hit) ? hit.position : p;+ }+ vec3 projectFeature(const vec3& p) const {+ SurfaceHit hit;+ if (features && features->closestPoint(p, reach, hit)) return hit.position;+ return projectSurface(p);+ }++ // Collapses b into a, a moving to `to`. maxLen: the longest edge the collapse may make.+ bool collapse(uint32_t b, uint32_t a, const vec3& to, float maxLen, std::vector<uint32_t>& ra,+ std::vector<uint32_t>& rb, std::vector<uint32_t>& scratch) {+ uint32_t ends[2];+ const int kb = kind(b, ends, scratch);+ if (kb == 2) return false;+ if (kb == 1 && !featureEdge(a, b)) return false;+ uint32_t et[4];+ const int ne = edgeTris(a, b, et, 4);+ if (ne < 1 || ne > 2) return false;+ ring(a, ra);+ ring(b, rb);+ if (ra.size() <= 3 && rb.size() <= 3) return false; // a tetrahedron+ size_t common = 0;+ for (uint32_t x : rb)+ if (std::binary_search(ra.begin(), ra.end(), x)) ++common;+ if (common != size_t(ne)) return false; // link condition: the collapse would pinch the surface+ const float max2 = maxLen * maxLen;+ auto check = [&](uint32_t v) {+ for (uint32_t t : VT[v]) {+ const glm::uvec3 tri = T[t];+ if (has(tri, a) && has(tri, b)) continue;+ vec3 q[3];+ for (int k = 0; k < 3; ++k) q[k] = (tri[k] == a || tri[k] == b) ? to : P[tri[k]];+ const vec3 nNew = glm::cross(q[1] - q[0], q[2] - q[0]), nOld = triNormal(tri);+ const float ln = glm::length(nNew), lo = glm::length(nOld);+ if (ln <= 1e-12f * (lo + 1e-30f) || ln <= 0.0f) return false;+ if (glm::dot(nNew, nOld) < 0.2f * ln * lo) return false;+ for (int k = 0; k < 3; ++k)+ if ((tri[k] == a || tri[k] == b) && maxLen > 0.0f) {+ for (int j = 1; j < 3; ++j) {+ const vec3 d = q[(k + j) % 3] - to;+ if (glm::dot(d, d) > max2) return false;+ }+ }+ // Degenerate (needle) triangles: smallest height against the longest edge.+ float longest = 0.0f;+ for (int k = 0; k < 3; ++k) longest = std::max(longest, glm::length(q[(k + 1) % 3] - q[k]));+ if (ln < 0.02f * longest * longest) return false;+ }+ return true;+ };+ if (!check(b)) return false;+ if (to != P[a] && !check(a)) return false;+ // Do it.+ for (uint32_t t : VT[b]) {+ glm::uvec3& tri = T[t];+ if (has(tri, a)) {+ deadT[t] = 1;+ for (int k = 0; k < 3; ++k)+ if (tri[k] != a && tri[k] != b) {+ auto& l = VT[tri[k]];+ l.erase(std::remove(l.begin(), l.end(), t), l.end());+ }+ continue;+ }+ for (int k = 0; k < 3; ++k)+ if (tri[k] == b) tri[k] = a;+ VT[a].push_back(t);+ }+ {+ auto& l = VT[a];+ l.erase(std::remove_if(l.begin(), l.end(), [&](uint32_t t) { return deadT[t] != 0; }), l.end());+ }+ VT[b].clear();+ VT[b].shrink_to_fit();+ deadV[b] = 1;+ P[a] = to;+ Lt[a] = std::min(Lt[a], Lt[b]);+ if (!sharp.empty())+ for (uint32_t x : rb)+ if (sharp.erase(edgeKey(b, x)) && x != a) sharp.insert(edgeKey(a, x));+ return true;+ }++ // Tries to collapse the edge (a, b) whichever way the feature rules allow; the survivor, or kNone.+ uint32_t collapseEdge(uint32_t a, uint32_t b, float maxLen, std::vector<uint32_t>& ra, std::vector<uint32_t>& rb,+ std::vector<uint32_t>& scratch) {+ uint32_t ends[2];+ const int ka = kind(a, ends, scratch), kbb = kind(b, ends, scratch);+ if (ka == 0 && kbb == 0) {+ const vec3 mid = 0.5f * (P[a] + P[b]);+ if (collapse(b, a, mid, maxLen, ra, rb, scratch)) return a;+ return kNone;+ }+ if (ka >= kbb) {+ if (collapse(b, a, P[a], maxLen, ra, rb, scratch)) return a;+ if (ka != 2 && collapse(a, b, P[b], maxLen, ra, rb, scratch)) return b;+ } else {+ if (collapse(a, b, P[b], maxLen, ra, rb, scratch)) return b;+ }+ return kNone;+ }++ struct Cand {+ float len2;+ uint32_t a, b;+ };+ // Edges (a < b) with length^2 in [lo2, hi2) scaled by the per-vertex target when `scaled`.+ std::vector<Cand> edges(float lo, float hi, bool scaled) const {+ const size_t nv = P.size();+ const size_t blocks = (nv + 4095) / 4096;+ std::vector<std::vector<Cand>> parts(blocks);+ parallelFor(blocks, [&](size_t b0, size_t b1) {+ std::vector<uint32_t> r;+ for (size_t blk = b0; blk < b1; ++blk) {+ auto& out = parts[blk];+ for (size_t v = blk * 4096, e = std::min(nv, v + 4096); v < e; ++v) {+ if (deadV[v]) continue;+ ring(uint32_t(v), r);+ for (uint32_t u : r) {+ if (u <= v) continue;+ const float l2 = glm::dot(P[u] - P[v], P[u] - P[v]);+ const float s = scaled ? 0.5f * (Lt[v] + Lt[u]) : 1.0f;+ if (l2 >= lo * lo * s * s && l2 < hi * hi * s * s) out.push_back({l2 / (s * s), uint32_t(v), u});+ }+ }+ }+ }, 1);+ size_t total = 0;+ for (auto& p : parts) total += p.size();+ std::vector<Cand> all;+ all.reserve(total);+ for (auto& p : parts) all.insert(all.end(), p.begin(), p.end());+ return all;+ }++ size_t alive() const {+ size_t n = 0;+ for (uint8_t d : deadV) n += !d;+ return n;+ }++ void projectMoved(std::vector<uint32_t>& moved) {+ std::sort(moved.begin(), moved.end());+ moved.erase(std::unique(moved.begin(), moved.end()), moved.end());+ parallelFor(moved.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i)+ if (!deadV[moved[i]]) P[moved[i]] = projectSurface(P[moved[i]]);+ }, 2000);+ moved.clear();+ }++ void decimate(float edge) {+ reach = 3.0f * edge;+ std::vector<uint32_t> ra, rb, scratch, moved;+ std::vector<uint8_t> touched(P.size(), 0);+ for (int pass = 0; pass < 60; ++pass) {+ std::vector<Cand> c = edges(0.0f, 0.8f * edge, false);+ if (c.empty()) break;+ std::sort(c.begin(), c.end(), [](const Cand& x, const Cand& y) {+ return x.len2 < y.len2 || (x.len2 == y.len2 && (x.a < y.a || (x.a == y.a && x.b < y.b)));+ });+ std::fill(touched.begin(), touched.end(), 0);+ size_t done = 0;+ for (const Cand& e : c) {+ if (deadV[e.a] || deadV[e.b] || touched[e.a] || touched[e.b]) continue;+ const uint32_t s = collapseEdge(e.a, e.b, 1.25f * edge, ra, rb, scratch);+ if (s == kNone) continue;+ ++done;+ moved.push_back(s);+ touched[s] = 1;+ ring(s, ra);+ for (uint32_t u : ra) touched[u] = 1;+ }+ projectMoved(moved);+ if (done == 0 || done < c.size() / 400) break;+ }+ }++ // Splits the edge (a, b) at its middle; the new vertex, or kNone.+ uint32_t split(uint32_t a, uint32_t b) {+ uint32_t et[4];+ const int ne = edgeTris(a, b, et, 4);+ if (ne < 1 || ne > 2) return kNone;+ const bool feature = featureEdge(a, b);+ const uint32_t m = uint32_t(P.size());+ const vec3 mid = 0.5f * (P[a] + P[b]);+ P.push_back(feature ? projectFeature(mid) : projectSurface(mid));+ deadV.push_back(0);+ VT.emplace_back();+ Lt.push_back(0.5f * (Lt[a] + Lt[b]));+ for (int i = 0; i < ne; ++i) {+ const uint32_t t = et[i];+ glm::uvec3 tri = T[t];+ // Rotate so the edge is (tri.x, tri.y).+ for (int r = 0; r < 3 && !((tri.x == a && tri.y == b) || (tri.x == b && tri.y == a)); ++r) tri = {tri.y, tri.z, tri.x};+ const uint32_t x = tri.x, y = tri.y, z = tri.z;+ T[t] = {x, m, z};+ const uint32_t n = uint32_t(T.size());+ T.push_back({m, y, z});+ G.push_back(G[t]);+ deadT.push_back(0);+ auto& ly = VT[y];+ std::replace(ly.begin(), ly.end(), t, n);+ VT[m].push_back(t);+ VT[m].push_back(n);+ VT[z].push_back(n);+ }+ if (!sharp.empty() && sharp.erase(edgeKey(a, b))) {+ sharp.insert(edgeKey(a, m));+ sharp.insert(edgeKey(m, b));+ }+ return m;+ }++ void splitLong() {+ std::vector<Cand> c = edges(4.0f / 3.0f, 1e30f, true);+ std::sort(c.begin(), c.end(), [](const Cand& x, const Cand& y) {+ return x.len2 > y.len2 || (x.len2 == y.len2 && (x.a < y.a || (x.a == y.a && x.b < y.b)));+ });+ for (const Cand& e : c) {+ uint32_t et[4];+ if (edgeTris(e.a, e.b, et, 4) == 0) continue; // gone (split already from the other side)+ split(e.a, e.b);+ }+ }++ void collapseShort() {+ std::vector<Cand> c = edges(0.0f, 0.8f, true);+ std::sort(c.begin(), c.end(), [](const Cand& x, const Cand& y) {+ return x.len2 < y.len2 || (x.len2 == y.len2 && (x.a < y.a || (x.a == y.a && x.b < y.b)));+ });+ std::vector<uint32_t> ra, rb, scratch, moved;+ for (const Cand& e : c) {+ if (deadV[e.a] || deadV[e.b]) continue;+ const float s = 0.5f * (Lt[e.a] + Lt[e.b]);+ const float l2 = glm::dot(P[e.a] - P[e.b], P[e.a] - P[e.b]);+ if (l2 >= 0.64f * s * s) continue;+ uint32_t et[4];+ if (edgeTris(e.a, e.b, et, 4) == 0) continue;+ const uint32_t sv = collapseEdge(e.a, e.b, 4.0f / 3.0f * s, ra, rb, scratch);+ if (sv != kNone) moved.push_back(sv);+ }+ projectMoved(moved);+ }++ void flipEdges() {+ const size_t nv = P.size();+ std::vector<int> val(nv, 0), target(nv, 6);+ {+ std::vector<uint32_t> r, scratch;+ uint32_t ends[2];+ for (uint32_t v = 0; v < nv; ++v) {+ if (deadV[v]) continue;+ ring(v, r);+ val[v] = int(r.size());+ const int k = kind(v, ends, scratch);+ if (k != 0) target[v] = 4;+ }+ }+ std::vector<Cand> c = edges(0.0f, 1e30f, false);+ for (const Cand& e : c) {+ const uint32_t a = e.a, b = e.b;+ uint32_t et[4];+ if (edgeTris(a, b, et, 4) != 2 || featureEdge(a, b)) continue;+ glm::uvec3 t1 = T[et[0]], t2 = T[et[1]];+ if (!forwards(t1, a, b)) std::swap(t1, t2), std::swap(et[0], et[1]);+ if (!forwards(t1, a, b) || !forwards(t2, b, a)) continue;+ uint32_t c1 = kNone, d1 = kNone;+ for (int k = 0; k < 3; ++k) {+ if (t1[k] != a && t1[k] != b) c1 = t1[k];+ if (t2[k] != a && t2[k] != b) d1 = t2[k];+ }+ if (c1 == kNone || d1 == kNone || c1 == d1) continue;+ if (val[a] <= 3 || val[b] <= 3) continue;+ auto dev = [&](uint32_t v, int dv) { return std::abs(val[v] + dv - target[v]); };+ const int before = dev(a, 0) + dev(b, 0) + dev(c1, 0) + dev(d1, 0);+ const int after = dev(a, -1) + dev(b, -1) + dev(c1, 1) + dev(d1, 1);+ if (after >= before) continue;+ // c-d must not be an edge already.+ uint32_t tmp[1];+ if (edgeTris(c1, d1, tmp, 1) > 0) continue;+ const vec3 n1 = triNormal(t1), n2 = triNormal(t2);+ const vec3 nOld = safeNormalize(n1) + safeNormalize(n2);+ if (glm::dot(safeNormalize(n1), safeNormalize(n2)) < 0.85f) continue; // not across a fold+ const glm::uvec3 u1{a, d1, c1}, u2{d1, b, c1};+ const vec3 m1 = triNormal(u1), m2 = triNormal(u2);+ if (glm::dot(m1, nOld) <= 0.0f || glm::dot(m2, nOld) <= 0.0f) continue;+ if (glm::dot(safeNormalize(m1), safeNormalize(m2)) < 0.85f) continue;+ T[et[0]] = u1;+ T[et[1]] = u2;+ // VT: a loses et[1], b loses et[0], c gains et[1], d gains et[0].+ auto& la = VT[a];+ la.erase(std::remove(la.begin(), la.end(), et[1]), la.end());+ auto& lb = VT[b];+ lb.erase(std::remove(lb.begin(), lb.end(), et[0]), lb.end());+ VT[c1].push_back(et[1]);+ VT[d1].push_back(et[0]);+ --val[a], --val[b], ++val[c1], ++val[d1];+ }+ }++ void smooth(int rounds) {+ const size_t nv = P.size();+ std::vector<vec3> N(nv, vec3(0.0f)), next(nv);+ std::vector<int8_t> kinds(nv, 0);+ std::vector<glm::uvec2> lineNb(nv, glm::uvec2(kNone));+ parallelFor(nv, [&](size_t b, size_t e) {+ std::vector<uint32_t> scratch;+ uint32_t ends[2];+ for (size_t v = b; v < e; ++v) {+ if (deadV[v]) continue;+ kinds[v] = int8_t(kind(uint32_t(v), ends, scratch));+ if (kinds[v] == 1) lineNb[v] = {ends[0], ends[1]};+ }+ }, 2000);+ for (int r = 0; r < rounds; ++r) {+ parallelFor(nv, [&](size_t b, size_t e) {+ for (size_t v = b; v < e; ++v) {+ vec3 n(0.0f);+ for (uint32_t t : VT[v]) n += triNormal(T[t]);+ N[v] = safeNormalize(n);+ }+ }, 2000);+ parallelFor(nv, [&](size_t b, size_t e) {+ std::vector<uint32_t> rg;+ for (size_t v = b; v < e; ++v) {+ next[v] = P[v];+ if (deadV[v] || kinds[v] == 2) continue;+ if (kinds[v] == 1) {+ const vec3 c = 0.5f * (P[lineNb[v].x] + P[lineNb[v].y]);+ next[v] = projectFeature(P[v] + 0.5f * (c - P[v]));+ continue;+ }+ ring(uint32_t(v), rg);+ if (rg.empty()) continue;+ // Weighted towards the target sizes: a neighbour wanting small edges pulls less.+ vec3 c(0.0f);+ float w = 0.0f;+ for (uint32_t u : rg) {+ const float wu = Lt[u];+ c += wu * P[u];+ w += wu;+ }+ c /= w;+ vec3 d = c - P[v];+ d -= N[v] * glm::dot(N[v], d);+ next[v] = projectSurface(P[v] + 0.5f * d);+ }+ }, 2000);+ // Keep a move only if no triangle around turns over.+ parallelFor(nv, [&](size_t b, size_t e) {+ for (size_t v = b; v < e; ++v) {+ if (deadV[v] || next[v] == P[v]) continue;+ bool ok = true;+ for (uint32_t t : VT[v]) {+ const glm::uvec3 tri = T[t];+ vec3 q[3];+ for (int k = 0; k < 3; ++k) q[k] = tri[k] == v ? next[v] : P[tri[k]];+ const vec3 nn = glm::cross(q[1] - q[0], q[2] - q[0]);+ if (glm::dot(nn, triNormal(tri)) <= 0.0f) {+ ok = false;+ break;+ }+ }+ if (!ok) next[v] = P[v];+ }+ }, 2000);+ P.swap(next);+ }+ }++ void remesh(float edge, const std::vector<float>& rel, int iterations) {+ reach = 3.0f * edge;+ for (size_t v = 0; v < P.size(); ++v) Lt[v] = edge * (v < rel.size() ? rel[v] : 1.0f);+ for (int it = 0; it < iterations; ++it) {+ splitLong();+ collapseShort();+ flipEdges();+ smooth(2);+ }+ }+};++ProxyBuilder::ProxyBuilder(const ProxySource& source) : impl_(std::make_unique<Impl>(source)) {}+ProxyBuilder::~ProxyBuilder() = default;+void ProxyBuilder::decimate(float edge) { impl_->decimate(edge); }+void ProxyBuilder::remesh(float edge, const std::vector<float>& relSize, int iterations) {+ impl_->remesh(edge, relSize, iterations);+}+size_t ProxyBuilder::vertexCount() const { return impl_->P.size(); }++Proxy ProxyBuilder::result(std::vector<uint32_t>* vertexMap) const {+ const Impl& m = *impl_;+ Proxy p;+ std::vector<uint32_t> remap(m.P.size(), kNone);+ for (uint32_t t = 0; t < m.T.size(); ++t) {+ if (m.deadT[t]) continue;+ glm::uvec3 tri = m.T[t];+ for (int k = 0; k < 3; ++k) {+ uint32_t& r = remap[tri[k]];+ if (r == kNone) {+ r = uint32_t(p.P.size());+ p.P.push_back(m.P[tri[k]]);+ if (vertexMap) vertexMap->push_back(tri[k]);+ }+ }+ p.T.push_back({remap[tri.x], remap[tri.y], remap[tri.z]});+ p.group.push_back(m.G[t]);+ p.feature.push_back(0), p.feature.push_back(0), p.feature.push_back(0);+ const size_t f = p.T.size() - 1;+ for (int k = 0; k < 3; ++k) p.feature[3 * f + size_t(k)] = m.featureEdge(tri[k], tri[(k + 1) % 3]) ? 1 : 0;+ }+ p.buildOpposites();+ for (size_t c = 0; c < p.opp.size(); ++c)+ if (p.opp[c] == kNone) p.feature[c] = 1;+ p.size.assign(p.P.size(), 1.0f);+ return p;+}++} // namespace sf::qr2diff --git a/src/core/QRemesh2Solver.h b/src/core/QRemesh2Solver.hnew file mode 100644index 00000000..28f9223b--- /dev/null+++ b/src/core/QRemesh2Solver.h@@ -0,0 +1,308 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// QRemesh 2's sparse solver: conjugate gradients preconditioned by an aggregation multigrid V-cycle, for the+// symmetric (real) or Hermitian (complex) positive definite systems of the cross field and the integer-grid map.+// Plain Jacobi-CG needs thousands of iterations on a 100k-triangle surface (smooth fields are the slowest modes);+// with the V-cycle a few dozen do. Aggregates are a vertex and its free neighbours; the prolongation carries the+// phase of the connection (so it also works for the cross field's connection Laplacian); coarse matrices are+// Galerkin products; the smoother is symmetric Gauss-Seidel. Everything is sequential or in fixed blocks, so the+// results don't depend on the thread count.+#pragma once++#include "core/ThreadPool.h"++#include <algorithm>+#include <cmath>+#include <complex>+#include <cstdint>+#include <functional>+#include <unordered_map>+#include <vector>++namespace sf::qr2 {++template <class S>+inline double absq(const S& v) {+ if constexpr (std::is_same_v<S, double>) return v * v;+ else return std::norm(v);+}+template <class S>+inline S conjOf(const S& v) {+ if constexpr (std::is_same_v<S, double>) return v;+ else return std::conj(v);+}+template <class S>+inline double realOf(const S& v) {+ if constexpr (std::is_same_v<S, double>) return v;+ else return v.real();+}++template <class S>+struct SparseMatrix {+ size_t n = 0;+ std::vector<uint32_t> off, col; // CSR, columns sorted, diagonal included+ std::vector<S> val;+ std::vector<double> diag; // real diagonal++ // From (row, col, value) triplets (duplicates summed).+ void build(size_t size, std::vector<std::pair<uint64_t, S>>& trips) {+ n = size;+ std::sort(trips.begin(), trips.end(), [](const auto& a, const auto& b) { return a.first < b.first; });+ off.assign(n + 1, 0);+ col.clear();+ val.clear();+ for (size_t i = 0; i < trips.size();) {+ size_t j = i;+ S v{};+ while (j < trips.size() && trips[j].first == trips[i].first) v += trips[j++].second;+ const uint32_t r = uint32_t(trips[i].first >> 32), c = uint32_t(trips[i].first & 0xffffffffu);+ col.push_back(c);+ val.push_back(v);+ ++off[r + 1];+ i = j;+ }+ for (size_t i = 0; i < n; ++i) off[i + 1] += off[i];+ diag.assign(n, 0.0);+ for (size_t i = 0; i < n; ++i)+ for (uint32_t k = off[i]; k < off[i + 1]; ++k)+ if (col[k] == i) diag[i] = realOf(val[k]);+ for (double& d : diag)+ if (!(d > 0.0)) d = 1.0;+ }+ void mul(const std::vector<S>& x, std::vector<S>& y) const {+ poolFor(n, [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) {+ S s{};+ for (uint32_t k = off[i]; k < off[i + 1]; ++k) s += val[k] * x[col[k]];+ y[i] = s;+ }+ });+ }+};++template <class S>+class Multigrid {+public:+ void build(const SparseMatrix<S>& A) {+ levels_.clear();+ levels_.push_back({A, {}, {}});+ while (levels_.back().A.n > 400 && levels_.size() < 30) {+ Level& f = levels_.back();+ Level c;+ if (!coarsen(f, c)) break;+ if (c.A.n * 10 > f.A.n * 9) break;+ levels_.push_back(std::move(c));+ }+ dense_.clear();+ if (levels_.back().A.n <= 2500) factorCoarsest();+ }+ // z = M^{-1} r (one V-cycle from zero).+ void apply(const std::vector<S>& r, std::vector<S>& z) const {+ if (levels_.empty()) {+ z = r;+ return;+ }+ vcycle(0, r, z);+ }+ size_t levels() const { return levels_.size(); }++private:+ struct Level {+ SparseMatrix<S> A;+ std::vector<uint32_t> agg; // fine unknown -> coarse unknown (this level -> next)+ std::vector<S> phase; // prolongation coefficient of each fine unknown+ };+ std::vector<Level> levels_;++ // Aggregates: an unaggregated unknown takes its unaggregated neighbours; leftovers join the neighbour they're+ // most strongly coupled to.+ bool coarsen(Level& f, Level& c) {+ const SparseMatrix<S>& A = f.A;+ const size_t n = A.n;+ f.agg.assign(n, ~0u);+ f.phase.assign(n, S(1.0));+ uint32_t nc = 0;+ auto strong = [&](size_t i, uint32_t k) {+ return absq(A.val[k]) >= 0.0625 * A.diag[i] * A.diag[A.col[k]] / 9.0;+ };+ for (size_t i = 0; i < n; ++i) {+ if (f.agg[i] != ~0u) continue;+ bool free = true;+ for (uint32_t k = A.off[i]; k < A.off[i + 1] && free; ++k)+ if (A.col[k] != i && strong(i, k) && f.agg[A.col[k]] != ~0u) free = false;+ if (!free) continue;+ f.agg[i] = nc;+ f.phase[i] = S(1.0);+ for (uint32_t k = A.off[i]; k < A.off[i + 1]; ++k) {+ const uint32_t j = A.col[k];+ if (j == i || !strong(i, k)) continue;+ f.agg[j] = nc;+ // Value at j for a value at i: -A_ji / |A_ji| (A_ji = conj(A_ij)).+ const S aji = conjOf(A.val[k]);+ const double m = std::sqrt(absq(aji));+ f.phase[j] = m > 0.0 ? -aji / m : S(1.0);+ }+ ++nc;+ }+ for (int pass = 0; pass < 4; ++pass)+ for (size_t i = 0; i < n; ++i) {+ if (f.agg[i] != ~0u) continue;+ double best = -1.0;+ uint32_t bk = ~0u;+ for (uint32_t k = A.off[i]; k < A.off[i + 1]; ++k) {+ const uint32_t j = A.col[k];+ if (j == i || f.agg[j] == ~0u) continue;+ if (absq(A.val[k]) > best) best = absq(A.val[k]), bk = k;+ }+ if (bk == ~0u) continue;+ const uint32_t j = A.col[bk];+ f.agg[i] = f.agg[j];+ const S aij = A.val[bk]; // couples i to j: value at i = -conj(A_ij)... phase via j+ const S aji = conjOf(aij);+ (void)aji;+ const double m = std::sqrt(absq(aij));+ f.phase[i] = m > 0.0 ? (-aij / m) * f.phase[j] : f.phase[j];+ }+ for (size_t i = 0; i < n; ++i)+ if (f.agg[i] == ~0u) f.agg[i] = nc++, f.phase[i] = S(1.0);+ if (nc == 0 || nc >= n) return false;+ // Galerkin: Ac[I][J] = sum conj(P_i) A_ij P_j.+ std::vector<std::pair<uint64_t, S>> trips;+ trips.reserve(A.val.size());+ for (size_t i = 0; i < n; ++i)+ for (uint32_t k = A.off[i]; k < A.off[i + 1]; ++k) {+ const uint32_t j = A.col[k];+ trips.push_back({(uint64_t(f.agg[i]) << 32) | f.agg[j], conjOf(f.phase[i]) * A.val[k] * f.phase[j]});+ }+ c.A.build(nc, trips);+ return true;+ }++ // Gauss-Seidel sweep on A x = b, forwards or backwards.+ static void sweep(const SparseMatrix<S>& A, const std::vector<S>& b, std::vector<S>& x, bool forwards) {+ const size_t n = A.n;+ for (size_t s = 0; s < n; ++s) {+ const size_t i = forwards ? s : n - 1 - s;+ S r = b[i];+ for (uint32_t k = A.off[i]; k < A.off[i + 1]; ++k)+ if (A.col[k] != i) r -= A.val[k] * x[A.col[k]];+ x[i] = r / A.diag[i];+ }+ }++ // Dense Cholesky (A = L L^H) of the coarsest level.+ void factorCoarsest() {+ const SparseMatrix<S>& A = levels_.back().A;+ const size_t n = A.n;+ dense_.assign(n * n, S{});+ for (size_t i = 0; i < n; ++i)+ for (uint32_t k = A.off[i]; k < A.off[i + 1]; ++k) dense_[i * n + A.col[k]] = A.val[k];+ for (size_t j = 0; j < n; ++j) {+ double d = realOf(dense_[j * n + j]);+ for (size_t k = 0; k < j; ++k) d -= absq(dense_[j * n + k]);+ d = std::sqrt(std::max(d, 1e-300));+ dense_[j * n + j] = S(d);+ for (size_t i = j + 1; i < n; ++i) {+ S s = dense_[i * n + j];+ for (size_t k = 0; k < j; ++k) s -= dense_[i * n + k] * conjOf(dense_[j * n + k]);+ dense_[i * n + j] = s / d;+ }+ }+ }+ void solveCoarsest(const std::vector<S>& b, std::vector<S>& x) const {+ const size_t n = b.size();+ x = b;+ for (size_t i = 0; i < n; ++i) {+ S s = x[i];+ for (size_t k = 0; k < i; ++k) s -= dense_[i * n + k] * x[k];+ x[i] = s / realOf(dense_[i * n + i]);+ }+ for (size_t i = n; i-- > 0;) {+ S s = x[i];+ for (size_t k = i + 1; k < n; ++k) s -= conjOf(dense_[k * n + i]) * x[k];+ x[i] = s / realOf(dense_[i * n + i]);+ }+ }++ // Symmetric V-cycle: forward sweep, coarse correction, backward sweep.+ void vcycle(size_t li, const std::vector<S>& b, std::vector<S>& x) const {+ const Level& L = levels_[li];+ const size_t n = L.A.n;+ x.assign(n, S{});+ if (li + 1 == levels_.size()) {+ if (!dense_.empty()) solveCoarsest(b, x);+ else+ for (int s = 0; s < 20; ++s) sweep(L.A, b, x, true), sweep(L.A, b, x, false);+ return;+ }+ sweep(L.A, b, x, true);+ std::vector<S> r(n);+ L.A.mul(x, r);+ for (size_t i = 0; i < n; ++i) r[i] = b[i] - r[i];+ const size_t nc = levels_[li + 1].A.n;+ std::vector<S> rc(nc, S{}), xc;+ for (size_t i = 0; i < n; ++i) rc[L.agg[i]] += conjOf(L.phase[i]) * r[i];+ vcycle(li + 1, rc, xc);+ for (size_t i = 0; i < n; ++i) x[i] += L.phase[i] * xc[L.agg[i]];+ sweep(L.A, b, x, false);+ }+ std::vector<S> dense_;+};++template <class S, class F>+double blockSumT(size_t n, F&& term) {+ const size_t block = 8192, blocks = (n + block - 1) / block;+ std::vector<double> part(blocks, 0.0);+ poolFor(n, [&](size_t b, size_t e) {+ double s = 0.0;+ for (size_t i = b; i < e; ++i) s += term(i);+ part[b / block] = s;+ }, block);+ double s = 0.0;+ for (double p : part) s += p;+ return s;+}++// Preconditioned CG on A x = b with A applied by `mul` and the multigrid of `A` (or Jacobi when mg is null).+// Returns the iterations; stop is set when `cancelled` said so.+template <class S>+int pcg(const std::function<void(const std::vector<S>&, std::vector<S>&)>& mul, const Multigrid<S>* mg,+ const std::vector<double>& diag, const std::vector<S>& b, std::vector<S>& x, double tol, int maxIt,+ const std::function<bool()>& cancelled, bool& stop) {+ const size_t n = b.size();+ std::vector<S> r(n), z(n), d(n), q(n);+ mul(x, q);+ for (size_t i = 0; i < n; ++i) r[i] = b[i] - q[i];+ auto precond = [&](const std::vector<S>& in, std::vector<S>& out) {+ if (mg) mg->apply(in, out);+ else+ for (size_t i = 0; i < n; ++i) out[i] = in[i] / diag[i];+ };+ precond(r, z);+ d = z;+ double rz = blockSumT<S>(n, [&](size_t i) { return realOf(conjOf(r[i]) * z[i]); });+ const double bn = std::sqrt(blockSumT<S>(n, [&](size_t i) { return absq(b[i]); })) + 1e-300;+ int it = 0;+ for (; it < maxIt; ++it) {+ const double rn = std::sqrt(blockSumT<S>(n, [&](size_t i) { return absq(r[i]); }));+ if (rn < tol * bn) break;+ if ((it & 7) == 0 && cancelled && cancelled()) {+ stop = true;+ return it;+ }+ mul(d, q);+ const double dq = blockSumT<S>(n, [&](size_t i) { return realOf(conjOf(d[i]) * q[i]); });+ if (!(dq > 1e-300)) break;+ const double alpha = rz / dq;+ for (size_t i = 0; i < n; ++i) x[i] += alpha * d[i], r[i] -= alpha * q[i];+ precond(r, z);+ const double rzNew = blockSumT<S>(n, [&](size_t i) { return realOf(conjOf(r[i]) * z[i]); });+ const double beta = rzNew / rz;+ rz = rzNew;+ for (size_t i = 0; i < n; ++i) d[i] = z[i] + beta * d[i];+ }+ return it;+}++} // namespace sf::qr2diff --git a/src/core/QRemeshInternal.h b/src/core/QRemeshInternal.hnew file mode 100644index 00000000..5e99af03--- /dev/null+++ b/src/core/QRemeshInternal.h@@ -0,0 +1,60 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// What QRemesh's two methods share (core/QRemesh.cpp runs the common steps: symmetry, guides, pieces, attributes;+// each method remeshes one piece). Not a public header.+//+// - Legacy (core/QRemesh.cpp): the Instant Meshes style position field, extracted at twice the spacing and+// split into quads.+// - QRemesh 2 (core/QRemesh2*.cpp): a feature-preserving proxy surface, a curvature-aligned cross field, an+// integer-grid map (seamless parametrization with singularities on lattice points) and extraction of its+// lattice at the target resolution. See QRemesh2.cpp for the outline.+#pragma once++#include "core/QRemesh.h"++#include <glm/glm.hpp>++#include <cstdint>+#include <functional>+#include <string>+#include <vector>++namespace sf::qr {++// A piece of the sculpt being remeshed (triangles), in the working frame (with symmetry: the half on the + side of+// the plane, which sits at 0).+struct WorkMesh {+ std::vector<glm::vec3> P;+ std::vector<glm::uvec3> T;+ std::vector<uint32_t> group; // per triangle+ std::vector<glm::vec3> color; // per vertex (only with usePolypaint)+ std::vector<uint8_t> cutEdge; // filled later: per boundary segment, 1 = made by the symmetry cut+};++// A remeshed piece: quads (counter-clockwise) and, for pieces kept as they were, triangles.+struct QuadMesh {+ std::vector<glm::vec3> P;+ std::vector<uint8_t> feature; // per vertex: lies on a hard edge / border line+ std::vector<glm::uvec4> quads;+ std::vector<glm::uvec3> tris;+};++// QRemesh 2 on one piece.+struct FieldPieceResult {+ QuadMesh mesh;+ std::vector<uint8_t> seam; // per vertex: on the symmetry plane (welded to its mirror image)+ int attempts = 0; // parametrizations solved (the count is corrected once when far off)+ size_t singularities = 0; // cross-field singularities (the poles the layout needs)+ size_t proxyTriangles = 0;+ size_t flippedTriangles = 0; // proxy triangles the map turned over (should be ~0)+ std::string why; // why the piece fell back to the legacy method+};++// False with `cancelled` set when the progress callback asked to stop, false with `why` when the method could not+// build a good result (the caller then uses the legacy method on that piece).+bool remeshPieceV2(const WorkMesh& piece, int axis, double wantQuads, const QRemeshOptions& opt, float diag,+ const std::vector<QRemeshGuide>& guides, const std::function<bool(float)>& report,+ FieldPieceResult& out, bool& cancelled);++} // namespace sf::qrdiff --git a/src/core/QuadQuality.cpp b/src/core/QuadQuality.cppnew file mode 100644index 00000000..782d483f--- /dev/null+++ b/src/core/QuadQuality.cpp@@ -0,0 +1,90 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// The quality report shown after QRemesh (core/QRemesh.h, quadQuality): poles and the valence histogram, how far+// quad corners are from right angles, how even the edges are, and the distance to the source sculpt.+#include "core/QRemesh.h"++#include "core/SurfaceQuery.h"++#include <algorithm>+#include <cmath>+#include <unordered_map>++namespace sf {++QuadQuality quadQuality(const Mesh& mesh, const Mesh* source) {+ QuadQuality q;+ q.vertices = mesh.vertexCount();+ 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 == 4) faces.push_back({f.x, f.y, f.z, f.w}), ++q.quads;+ else if (n == 3) faces.push_back({f.x, f.y, f.z}), ++q.triangles;+ }+ std::unordered_map<uint64_t, int> edges;+ edges.reserve(faces.size() * 3);+ 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()];+ ++edges[a < b ? (uint64_t(a) << 32) | b : (uint64_t(b) << 32) | a];+ }+ std::vector<int> valence(mesh.vertexCount(), 0);+ std::vector<uint8_t> open(mesh.vertexCount(), 0);+ double lsum = 0.0, lsum2 = 0.0;+ for (auto [key, uses] : edges) {+ const uint32_t a = uint32_t(key >> 32), b = uint32_t(key & 0xffffffffu);+ ++valence[a], ++valence[b];+ if (uses == 1) open[a] = open[b] = 1;+ const double l = double(glm::length(mesh.positions[a] - mesh.positions[b]));+ lsum += l, lsum2 += l * l;+ }+ if (!edges.empty()) {+ const double mean = lsum / double(edges.size());+ const double var = std::max(0.0, lsum2 / double(edges.size()) - mean * mean);+ q.edgeLengthCv = mean > 0.0 ? float(std::sqrt(var) / mean) : 0.0f;+ }+ for (uint32_t v = 0; v < mesh.vertexCount(); ++v) {+ if (valence[v] == 0) continue;+ if (open[v]) {+ if (valence[v] != 3) ++q.boundaryPoles;+ continue;+ }+ ++q.valence[std::clamp(valence[v], 0, 7)];+ if (valence[v] != 4) ++q.poles;+ }+ std::vector<float> dev;+ dev.reserve(q.quads * 4);+ for (const auto& f : faces) {+ if (f.size() != 4) continue;+ for (int k = 0; k < 4; ++k) {+ const glm::vec3 p = mesh.positions[f[size_t(k)]];+ const glm::vec3 a = mesh.positions[f[size_t((k + 1) % 4)]] - p, b = mesh.positions[f[size_t((k + 3) % 4)]] - p;+ const float la = glm::length(a), lb = glm::length(b);+ if (la <= 0.0f || lb <= 0.0f) continue;+ const float ang = glm::degrees(std::acos(std::clamp(glm::dot(a, b) / (la * lb), -1.0f, 1.0f)));+ dev.push_back(std::abs(ang - 90.0f));+ }+ }+ if (!dev.empty()) {+ double s = 0.0;+ for (float d : dev) s += d;+ q.angleDeviation = float(s / double(dev.size()));+ const size_t k = std::min(dev.size() - 1, dev.size() * 99 / 100);+ std::nth_element(dev.begin(), dev.begin() + long(k), dev.end());+ q.angleDeviationMax = dev[k];+ }+ if (source && source->triangleCount() > 0 && mesh.triangleCount() > 0) {+ const float diag = glm::length(source->bounds().extent());+ const SurfaceDeviation d = measureDeviation(mesh, *source, true);+ if (diag > 0.0f) {+ q.hausdorff = 100.0f * d.max / diag;+ q.meanDistance = 100.0f * d.mean / diag;+ }+ q.measured = true;+ }+ return q;+}++} // namespace sfdiff --git a/src/core/RetopoCommands.cpp b/src/core/RetopoCommands.cppindex 66ba982e..5737ba80 100644--- a/src/core/RetopoCommands.cpp+++ b/src/core/RetopoCommands.cpp@@ -27,6 +27,20 @@ int symmetryAxisArg(const std::string& s) {} // namespace+std::string qualitySummary(const QuadQuality& q) {+ if (q.quads == 0) return {};+ char s[256];+ std::snprintf(s, sizeof s, ". Quality: %zu poles (%zu x3, %zu x5, %zu other), corners %.1f deg off square", q.poles,+ q.valence[3], q.valence[5], q.poles - q.valence[3] - q.valence[5], double(q.angleDeviation));+ std::string out = s;+ if (q.measured) {+ std::snprintf(s, sizeof s, ", distance to the sculpt %.3f%% mean / %.2f%% max of its size", double(q.meanDistance),+ double(q.hausdorff));+ out += s;+ }+ return out;+}+std::string applyQRemesh(Document& doc, Mesh result, bool keepOriginal, const QRemeshStats& st) {const size_t before = doc.mesh.triangleCount();if (keepOriginal) {@@ -54,7 +68,11 @@ std::string applyQRemesh(Document& doc, Mesh result, bool keepOriginal, const QRif (st.guidesSkipped)sym += "; " + std::to_string(st.guidesSkipped) + (st.guidesSkipped == 1 ? " guide is" : " guides are") +" off the surface and were ignored (draw them again after moving the SubTool)";- char buf[512];+ if (st.method == QRemeshMethod::Legacy) sym += "; legacy method";+ else if (st.fallbackPieces)+ sym += "; " + std::to_string(st.fallbackPieces) + (st.fallbackPieces == 1 ? " piece" : " pieces") + " used the legacy method";+ sym += qualitySummary(st.quality);+ char buf[768];std::snprintf(buf, sizeof buf, "QRemesh: %zu quads%s from %zu triangles (%.0f%% quads%s) in %.1f s%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,@@ -70,6 +88,11 @@ void registerRetopoCommands(CommandRegistry& reg) {"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},+ {"method", T::String, "'v2' (default): QRemesh 2, a curvature-aligned integer-grid layout with poles only "+ "where the form needs them, guides as exact edge loops and a quality report. "+ "'legacy': the 0.9 method.", false},+ {"quality", T::Bool, "Measure the result (poles, valences, corner angles, distance to the sculpt) and "+ "report it. Default true.", 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},@@ -95,6 +118,11 @@ void registerRetopoCommands(CommandRegistry& reg) {[](Document& doc, const Args& a) -> CommandResult {if (doc.mesh.triangleCount() == 0) return {false, "QRemesh: the SubTool is empty"};QRemeshOptions o;+ const std::string method = argString(a, "method");+ if (method == "legacy" || method == "Legacy") o.method = QRemeshMethod::Legacy;+ else if (!method.empty() && method != "v2" && method != "V2")+ return {false, "QRemesh: method must be v2 or legacy"};+ o.measureQuality = argBool(a, "quality", true);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);